SimulationView.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import sys
  4. from PyQt6.QtCore import Qt
  5. from PyQt6.QtGui import QOpenGLContext
  6. from PyQt6.QtWidgets import QApplication
  7. from UM.Application import Application
  8. from UM.Event import Event, KeyEvent
  9. from UM.Job import Job
  10. from UM.Logger import Logger
  11. from UM.Math.Color import Color
  12. from UM.Math.Matrix import Matrix
  13. from UM.Mesh.MeshBuilder import MeshBuilder
  14. from UM.Message import Message
  15. from UM.Platform import Platform
  16. from UM.PluginRegistry import PluginRegistry
  17. from UM.Qt.QtApplication import QtApplication
  18. from UM.Resources import Resources
  19. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  20. from UM.Scene.Selection import Selection
  21. from UM.Signal import Signal
  22. from UM.View.CompositePass import CompositePass
  23. from UM.View.GL.OpenGL import OpenGL
  24. from UM.View.GL.OpenGLContext import OpenGLContext
  25. from UM.View.GL.ShaderProgram import ShaderProgram
  26. from UM.i18n import i18nCatalog
  27. from cura.CuraView import CuraView
  28. from cura.LayerPolygon import LayerPolygon # To distinguish line types.
  29. from cura.Scene.ConvexHullNode import ConvexHullNode
  30. from cura.CuraApplication import CuraApplication
  31. from .NozzleNode import NozzleNode
  32. from .SimulationPass import SimulationPass
  33. from .SimulationViewProxy import SimulationViewProxy
  34. import numpy
  35. import os.path
  36. from typing import Optional, TYPE_CHECKING, List, cast
  37. if TYPE_CHECKING:
  38. from UM.Scene.SceneNode import SceneNode
  39. from UM.Scene.Scene import Scene
  40. from UM.Settings.ContainerStack import ContainerStack
  41. catalog = i18nCatalog("cura")
  42. class SimulationView(CuraView):
  43. """The preview layer view. It is used to display g-code paths."""
  44. # Must match SimulationViewMenuComponent.qml
  45. LAYER_VIEW_TYPE_MATERIAL_TYPE = 0
  46. LAYER_VIEW_TYPE_LINE_TYPE = 1
  47. LAYER_VIEW_TYPE_FEEDRATE = 2
  48. LAYER_VIEW_TYPE_THICKNESS = 3
  49. _no_layers_warning_preference = "view/no_layers_warning"
  50. def __init__(self, parent = None) -> None:
  51. super().__init__(parent)
  52. self._max_layers = 0
  53. self._current_layer_num = 0
  54. self._minimum_layer_num = 0
  55. self._current_layer_mesh = None
  56. self._current_layer_jumps = None
  57. self._top_layers_job = None # type: Optional["_CreateTopLayersJob"]
  58. self._activity = False
  59. self._old_max_layers = 0
  60. self._max_paths = 0
  61. self._current_path_num = 0
  62. self._minimum_path_num = 0
  63. self.currentLayerNumChanged.connect(self._onCurrentLayerNumChanged)
  64. self._busy = False
  65. self._simulation_running = False
  66. self._ghost_shader = None # type: Optional["ShaderProgram"]
  67. self._layer_pass = None # type: Optional[SimulationPass]
  68. self._composite_pass = None # type: Optional[CompositePass]
  69. self._old_layer_bindings = None # type: Optional[List[str]]
  70. self._simulationview_composite_shader = None # type: Optional["ShaderProgram"]
  71. self._old_composite_shader = None # type: Optional["ShaderProgram"]
  72. self._max_feedrate = sys.float_info.min
  73. self._min_feedrate = sys.float_info.max
  74. self._max_thickness = sys.float_info.min
  75. self._min_thickness = sys.float_info.max
  76. self._max_line_width = sys.float_info.min
  77. self._min_line_width = sys.float_info.max
  78. self._min_flow_rate = sys.float_info.max
  79. self._max_flow_rate = sys.float_info.min
  80. self._global_container_stack = None # type: Optional[ContainerStack]
  81. self._proxy = None
  82. self._resetSettings()
  83. self._legend_items = None
  84. self._show_travel_moves = False
  85. self._nozzle_node = None # type: Optional[NozzleNode]
  86. Application.getInstance().getPreferences().addPreference("view/top_layer_count", 5)
  87. Application.getInstance().getPreferences().addPreference("view/only_show_top_layers", False)
  88. Application.getInstance().getPreferences().addPreference("view/force_layer_view_compatibility_mode", False)
  89. Application.getInstance().getPreferences().addPreference("layerview/layer_view_type", 1) # Default to "Line Type".
  90. Application.getInstance().getPreferences().addPreference("layerview/extruder_opacities", "")
  91. Application.getInstance().getPreferences().addPreference("layerview/show_travel_moves", False)
  92. Application.getInstance().getPreferences().addPreference("layerview/show_helpers", True)
  93. Application.getInstance().getPreferences().addPreference("layerview/show_skin", True)
  94. Application.getInstance().getPreferences().addPreference("layerview/show_infill", True)
  95. Application.getInstance().getPreferences().addPreference("layerview/show_starts", True)
  96. self.visibleStructuresChanged.connect(self.calculateColorSchemeLimits)
  97. self._updateWithPreferences()
  98. self._solid_layers = int(Application.getInstance().getPreferences().getValue("view/top_layer_count"))
  99. self._only_show_top_layers = bool(Application.getInstance().getPreferences().getValue("view/only_show_top_layers"))
  100. self._compatibility_mode = self._evaluateCompatibilityMode()
  101. self._wireprint_warning_message = Message(catalog.i18nc("@info:status",
  102. "Cura does not accurately display layers when Wire Printing is enabled."),
  103. title = catalog.i18nc("@info:title", "Simulation View"),
  104. message_type = Message.MessageType.WARNING)
  105. self._slice_first_warning_message = Message(catalog.i18nc("@info:status",
  106. "Nothing is shown because you need to slice first."),
  107. title = catalog.i18nc("@info:title", "No layers to show"),
  108. option_text = catalog.i18nc("@info:option_text",
  109. "Do not show this message again"),
  110. option_state = False,
  111. message_type = Message.MessageType.WARNING)
  112. self._slice_first_warning_message.optionToggled.connect(self._onDontAskMeAgain)
  113. CuraApplication.getInstance().getPreferences().addPreference(self._no_layers_warning_preference, True)
  114. QtApplication.getInstance().engineCreatedSignal.connect(self._onEngineCreated)
  115. def _onEngineCreated(self) -> None:
  116. plugin_path = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
  117. if plugin_path:
  118. self.addDisplayComponent("main", os.path.join(plugin_path, "SimulationViewMainComponent.qml"))
  119. self.addDisplayComponent("menu", os.path.join(plugin_path, "SimulationViewMenuComponent.qml"))
  120. else:
  121. Logger.log("e", "Unable to find the path for %s", self.getPluginId())
  122. def _evaluateCompatibilityMode(self) -> bool:
  123. return OpenGLContext.isLegacyOpenGL() or bool(Application.getInstance().getPreferences().getValue("view/force_layer_view_compatibility_mode"))
  124. def _resetSettings(self) -> None:
  125. self._layer_view_type = 0 # type: int # 0 is material color, 1 is color by linetype, 2 is speed, 3 is layer thickness
  126. self._extruder_count = 0
  127. self._extruder_opacity = [[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]
  128. self._show_travel_moves = False
  129. self._show_helpers = True
  130. self._show_skin = True
  131. self._show_infill = True
  132. self._show_starts = True
  133. self.resetLayerData()
  134. def getActivity(self) -> bool:
  135. return self._activity
  136. def setActivity(self, activity: bool) -> None:
  137. if self._activity == activity:
  138. return
  139. self._activity = activity
  140. self._updateSliceWarningVisibility()
  141. self.activityChanged.emit()
  142. def getSimulationPass(self) -> SimulationPass:
  143. if not self._layer_pass:
  144. # Currently the RenderPass constructor requires a size > 0
  145. # This should be fixed in RenderPass's constructor.
  146. self._layer_pass = SimulationPass(1, 1)
  147. self._compatibility_mode = self._evaluateCompatibilityMode()
  148. self._layer_pass.setSimulationView(self)
  149. return self._layer_pass
  150. def getCurrentLayer(self) -> int:
  151. return self._current_layer_num
  152. def getMinimumLayer(self) -> int:
  153. return self._minimum_layer_num
  154. def getMaxLayers(self) -> int:
  155. return self._max_layers
  156. def getCurrentPath(self) -> int:
  157. return self._current_path_num
  158. def getMinimumPath(self) -> int:
  159. return self._minimum_path_num
  160. def getMaxPaths(self) -> int:
  161. return self._max_paths
  162. def getNozzleNode(self) -> NozzleNode:
  163. if not self._nozzle_node:
  164. self._nozzle_node = NozzleNode()
  165. return self._nozzle_node
  166. def _onSceneChanged(self, node: "SceneNode") -> None:
  167. if node.getMeshData() is None:
  168. return
  169. self.setActivity(False)
  170. self.calculateColorSchemeLimits()
  171. self.calculateMaxLayers()
  172. self.calculateMaxPathsOnLayer(self._current_layer_num)
  173. def isBusy(self) -> bool:
  174. return self._busy
  175. def setBusy(self, busy: bool) -> None:
  176. if busy != self._busy:
  177. self._busy = busy
  178. self.busyChanged.emit()
  179. def isSimulationRunning(self) -> bool:
  180. return self._simulation_running
  181. def setSimulationRunning(self, running: bool) -> None:
  182. self._simulation_running = running
  183. def resetLayerData(self) -> None:
  184. self._current_layer_mesh = None
  185. self._current_layer_jumps = None
  186. def beginRendering(self) -> None:
  187. scene = self.getController().getScene()
  188. renderer = self.getRenderer()
  189. if renderer is None:
  190. return
  191. if not self._ghost_shader:
  192. self._ghost_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "color.shader"))
  193. theme = CuraApplication.getInstance().getTheme()
  194. if theme is not None:
  195. self._ghost_shader.setUniformValue("u_color", Color(*theme.getColor("layerview_ghost").getRgb()))
  196. for node in DepthFirstIterator(scene.getRoot()):
  197. # We do not want to render ConvexHullNode as it conflicts with the bottom layers.
  198. # However, it is somewhat relevant when the node is selected, so do render it then.
  199. if type(node) is ConvexHullNode and not Selection.isSelected(cast(ConvexHullNode, node).getWatchedNode()):
  200. continue
  201. if not node.render(renderer):
  202. if (node.getMeshData()) and node.isVisible():
  203. renderer.queueNode(node, transparent = True, shader = self._ghost_shader)
  204. def setLayer(self, value: int) -> None:
  205. """
  206. Set the upper end of the range of visible layers.
  207. If setting it below the lower end of the range, the lower end is lowered so that 1 layer stays visible.
  208. :param value: The new layer number to show, 0-indexed.
  209. """
  210. if self._current_layer_num != value:
  211. self._current_layer_num = min(max(value, 0), self._max_layers)
  212. self._minimum_layer_num = min(self._current_layer_num, self._minimum_layer_num)
  213. self._startUpdateTopLayers()
  214. self.currentLayerNumChanged.emit()
  215. def setMinimumLayer(self, value: int) -> None:
  216. """
  217. Set the lower end of the range of visible layers.
  218. If setting it above the upper end of the range, the upper end is increased so that 1 layer stays visible.
  219. :param value: The new lower end of the range of visible layers, 0-indexed.
  220. """
  221. if self._minimum_layer_num != value:
  222. self._minimum_layer_num = min(max(value, 0), self._max_layers)
  223. self._current_layer_num = max(self._current_layer_num, self._minimum_layer_num)
  224. self._startUpdateTopLayers()
  225. self.currentLayerNumChanged.emit()
  226. def setPath(self, value: int) -> None:
  227. """
  228. Set the upper end of the range of visible paths on the current layer.
  229. If setting it below the lower end of the range, the lower end is lowered so that 1 path stays visible.
  230. :param value: The new path index to show, 0-indexed.
  231. """
  232. if self._current_path_num != value:
  233. self._current_path_num = min(max(value, 0), self._max_paths)
  234. self._minimum_path_num = min(self._minimum_path_num, self._current_path_num)
  235. self._startUpdateTopLayers()
  236. self.currentPathNumChanged.emit()
  237. def setMinimumPath(self, value: int) -> None:
  238. """
  239. Set the lower end of the range of visible paths on the current layer.
  240. If setting it above the upper end of the range, the upper end is increased so that 1 path stays visible.
  241. :param value: The new lower end of the range of visible paths, 0-indexed.
  242. """
  243. if self._minimum_path_num != value:
  244. self._minimum_path_num = min(max(value, 0), self._max_paths)
  245. self._current_path_num = max(self._current_path_num, self._minimum_path_num)
  246. self._startUpdateTopLayers()
  247. self.currentPathNumChanged.emit()
  248. def setSimulationViewType(self, layer_view_type: int) -> None:
  249. """Set the layer view type
  250. :param layer_view_type: integer as in SimulationView.qml and this class
  251. """
  252. if layer_view_type != self._layer_view_type:
  253. self._layer_view_type = layer_view_type
  254. self.currentLayerNumChanged.emit()
  255. def getSimulationViewType(self) -> int:
  256. """Return the layer view type, integer as in SimulationView.qml and this class"""
  257. return self._layer_view_type
  258. def setExtruderOpacity(self, extruder_nr: int, opacity: float) -> None:
  259. """Set the extruder opacity
  260. :param extruder_nr: 0..15
  261. :param opacity: 0.0 .. 1.0
  262. """
  263. if 0 <= extruder_nr <= 15:
  264. self._extruder_opacity[extruder_nr // 4][extruder_nr % 4] = opacity
  265. self.currentLayerNumChanged.emit()
  266. def getExtruderOpacities(self) -> Matrix:
  267. # NOTE: Extruder opacities are stored in a matrix for (minor) performance reasons (w.r.t. OpenGL/shaders).
  268. # If more than 16 extruders are called for, this should be converted to a sampler1d.
  269. return Matrix(self._extruder_opacity)
  270. def setShowTravelMoves(self, show: bool) -> None:
  271. if show == self._show_travel_moves:
  272. return
  273. self._show_travel_moves = show
  274. self.currentLayerNumChanged.emit()
  275. self.visibleStructuresChanged.emit()
  276. def getShowTravelMoves(self) -> bool:
  277. return self._show_travel_moves
  278. def setShowHelpers(self, show: bool) -> None:
  279. if show == self._show_helpers:
  280. return
  281. self._show_helpers = show
  282. self.currentLayerNumChanged.emit()
  283. self.visibleStructuresChanged.emit()
  284. def getShowHelpers(self) -> bool:
  285. return self._show_helpers
  286. def setShowSkin(self, show: bool) -> None:
  287. if show == self._show_skin:
  288. return
  289. self._show_skin = show
  290. self.currentLayerNumChanged.emit()
  291. self.visibleStructuresChanged.emit()
  292. def getShowSkin(self) -> bool:
  293. return self._show_skin
  294. def setShowInfill(self, show: bool) -> None:
  295. if show == self._show_infill:
  296. return
  297. self._show_infill = show
  298. self.currentLayerNumChanged.emit()
  299. self.visibleStructuresChanged.emit()
  300. def getShowInfill(self) -> bool:
  301. return self._show_infill
  302. def setShowStarts(self, show: bool) -> None:
  303. if show == self._show_starts:
  304. return
  305. self._show_starts = show
  306. self.currentLayerNumChanged.emit()
  307. self.visibleStructuresChanged.emit()
  308. def getShowStarts(self) -> bool:
  309. return self._show_starts
  310. def getCompatibilityMode(self) -> bool:
  311. return self._compatibility_mode
  312. def getExtruderCount(self) -> int:
  313. return self._extruder_count
  314. def getMinFeedrate(self) -> float:
  315. if abs(self._min_feedrate - sys.float_info.max) < 10: # Some lenience due to floating point rounding.
  316. return 0.0 # If it's still max-float, there are no measurements. Use 0 then.
  317. return self._min_feedrate
  318. def getMaxFeedrate(self) -> float:
  319. return self._max_feedrate
  320. def getMinThickness(self) -> float:
  321. if abs(self._min_thickness - sys.float_info.max) < 10: # Some lenience due to floating point rounding.
  322. return 0.0 # If it's still max-float, there are no measurements. Use 0 then.
  323. return self._min_thickness
  324. def getMaxThickness(self) -> float:
  325. return self._max_thickness
  326. def getMaxLineWidth(self) -> float:
  327. return self._max_line_width
  328. def getMinLineWidth(self) -> float:
  329. if abs(self._min_line_width - sys.float_info.max) < 10: # Some lenience due to floating point rounding.
  330. return 0.0 # If it's still max-float, there are no measurements. Use 0 then.
  331. return self._min_line_width
  332. def getMaxFlowRate(self) -> float:
  333. return self._max_flow_rate
  334. def getMinFlowRate(self) -> float:
  335. if abs(self._min_flow_rate - sys.float_info.max) < 10: # Some lenience due to floating point rounding.
  336. return 0.0 # If it's still max-float, there are no measurements. Use 0 then.
  337. return self._min_flow_rate
  338. def calculateMaxLayers(self) -> None:
  339. """
  340. Calculates number of layers, triggers signals if the number of layers changed and makes sure the top layers are
  341. recalculated for legacy layer view.
  342. """
  343. scene = self.getController().getScene()
  344. self._old_max_layers = self._max_layers
  345. new_max_layers = -1
  346. for node in DepthFirstIterator(scene.getRoot()): # type: ignore
  347. layer_data = node.callDecoration("getLayerData")
  348. if not layer_data:
  349. continue
  350. self.setActivity(True)
  351. min_layer_number = sys.maxsize
  352. max_layer_number = -sys.maxsize
  353. for layer_id in layer_data.getLayers():
  354. # If a layer doesn't contain any polygons, skip it (for infill meshes taller than print objects
  355. if len(layer_data.getLayer(layer_id).polygons) < 1:
  356. continue
  357. if max_layer_number < layer_id:
  358. max_layer_number = layer_id
  359. if min_layer_number > layer_id:
  360. min_layer_number = layer_id
  361. layer_count = max_layer_number - min_layer_number
  362. if new_max_layers < layer_count:
  363. new_max_layers = layer_count
  364. if new_max_layers >= 0 and new_max_layers != self._old_max_layers:
  365. self._max_layers = new_max_layers
  366. # The qt slider has a bit of weird behavior that if the maxvalue needs to be changed first
  367. # if it's the largest value. If we don't do this, we can have a slider block outside of the
  368. # slider.
  369. if new_max_layers > self._current_layer_num:
  370. self.maxLayersChanged.emit()
  371. self.setLayer(int(self._max_layers))
  372. else:
  373. self.setLayer(int(self._max_layers))
  374. self.maxLayersChanged.emit()
  375. self._startUpdateTopLayers()
  376. def calculateColorSchemeLimits(self) -> None:
  377. """
  378. Calculates the limits of the colour schemes, depending on the layer view data that is visible to the user.
  379. """
  380. # Before we start, save the old values so that we can tell if any of the spectrums need to change.
  381. old_min_feedrate = self._min_feedrate
  382. old_max_feedrate = self._max_feedrate
  383. old_min_linewidth = self._min_line_width
  384. old_max_linewidth = self._max_line_width
  385. old_min_thickness = self._min_thickness
  386. old_max_thickness = self._max_thickness
  387. old_min_flow_rate = self._min_flow_rate
  388. old_max_flow_rate = self._max_flow_rate
  389. self._min_feedrate = sys.float_info.max
  390. self._max_feedrate = sys.float_info.min
  391. self._min_line_width = sys.float_info.max
  392. self._max_line_width = sys.float_info.min
  393. self._min_thickness = sys.float_info.max
  394. self._max_thickness = sys.float_info.min
  395. self._min_flow_rate = sys.float_info.max
  396. self._max_flow_rate = sys.float_info.min
  397. # The colour scheme is only influenced by the visible lines, so filter the lines by if they should be visible.
  398. visible_line_types = []
  399. if self.getShowSkin(): # Actually "shell".
  400. visible_line_types.append(LayerPolygon.SkinType)
  401. visible_line_types.append(LayerPolygon.Inset0Type)
  402. visible_line_types.append(LayerPolygon.InsetXType)
  403. if self.getShowInfill():
  404. visible_line_types.append(LayerPolygon.InfillType)
  405. if self.getShowHelpers():
  406. visible_line_types.append(LayerPolygon.PrimeTowerType)
  407. visible_line_types.append(LayerPolygon.SkirtType)
  408. visible_line_types.append(LayerPolygon.SupportType)
  409. visible_line_types.append(LayerPolygon.SupportInfillType)
  410. visible_line_types.append(LayerPolygon.SupportInterfaceType)
  411. visible_line_types_with_extrusion = visible_line_types.copy() # Copy before travel moves are added
  412. if self.getShowTravelMoves():
  413. visible_line_types.append(LayerPolygon.MoveCombingType)
  414. visible_line_types.append(LayerPolygon.MoveRetractionType)
  415. for node in DepthFirstIterator(self.getController().getScene().getRoot()):
  416. layer_data = node.callDecoration("getLayerData")
  417. if not layer_data:
  418. continue
  419. for layer_index in layer_data.getLayers():
  420. for polyline in layer_data.getLayer(layer_index).polygons:
  421. is_visible = numpy.isin(polyline.types, visible_line_types)
  422. visible_indices = numpy.where(is_visible)[0]
  423. visible_indicies_with_extrusion = numpy.where(numpy.isin(polyline.types, visible_line_types_with_extrusion))[0]
  424. if visible_indices.size == 0: # No items to take maximum or minimum of.
  425. continue
  426. visible_feedrates = numpy.take(polyline.lineFeedrates, visible_indices)
  427. visible_feedrates_with_extrusion = numpy.take(polyline.lineFeedrates, visible_indicies_with_extrusion)
  428. visible_linewidths = numpy.take(polyline.lineWidths, visible_indices)
  429. visible_linewidths_with_extrusion = numpy.take(polyline.lineWidths, visible_indicies_with_extrusion)
  430. visible_thicknesses = numpy.take(polyline.lineThicknesses, visible_indices)
  431. visible_thicknesses_with_extrusion = numpy.take(polyline.lineThicknesses, visible_indicies_with_extrusion)
  432. self._max_feedrate = max(float(visible_feedrates.max()), self._max_feedrate)
  433. if visible_feedrates_with_extrusion.size != 0:
  434. flow_rates = visible_feedrates_with_extrusion * visible_linewidths_with_extrusion * visible_thicknesses_with_extrusion
  435. self._min_flow_rate = min(float(flow_rates.min()), self._min_flow_rate)
  436. self._max_flow_rate = max(float(flow_rates.max()), self._max_flow_rate)
  437. self._min_feedrate = min(float(visible_feedrates.min()), self._min_feedrate)
  438. self._max_line_width = max(float(visible_linewidths.max()), self._max_line_width)
  439. self._min_line_width = min(float(visible_linewidths.min()), self._min_line_width)
  440. self._max_thickness = max(float(visible_thicknesses.max()), self._max_thickness)
  441. try:
  442. self._min_thickness = min(float(visible_thicknesses[numpy.nonzero(visible_thicknesses)].min()), self._min_thickness)
  443. except ValueError:
  444. # Sometimes, when importing a GCode the line thicknesses are zero and so the minimum (avoiding the zero) can't be calculated.
  445. Logger.log("w", "Min thickness can't be calculated because all the values are zero")
  446. if old_min_feedrate != self._min_feedrate or old_max_feedrate != self._max_feedrate \
  447. or old_min_linewidth != self._min_line_width or old_max_linewidth != self._max_line_width \
  448. or old_min_thickness != self._min_thickness or old_max_thickness != self._max_thickness \
  449. or old_min_flow_rate != self._min_flow_rate or old_max_flow_rate != self._max_flow_rate:
  450. self.colorSchemeLimitsChanged.emit()
  451. def calculateMaxPathsOnLayer(self, layer_num: int) -> None:
  452. # Update the currentPath
  453. scene = self.getController().getScene()
  454. for node in DepthFirstIterator(scene.getRoot()): # type: ignore
  455. layer_data = node.callDecoration("getLayerData")
  456. if not layer_data:
  457. continue
  458. layer = layer_data.getLayer(layer_num)
  459. if layer is None:
  460. return
  461. new_max_paths = layer.lineMeshElementCount()
  462. if new_max_paths >= 0 and new_max_paths != self._max_paths:
  463. self._max_paths = new_max_paths
  464. self.maxPathsChanged.emit()
  465. self.setPath(int(new_max_paths))
  466. maxLayersChanged = Signal()
  467. maxPathsChanged = Signal()
  468. currentLayerNumChanged = Signal()
  469. currentPathNumChanged = Signal()
  470. globalStackChanged = Signal()
  471. preferencesChanged = Signal()
  472. busyChanged = Signal()
  473. activityChanged = Signal()
  474. visibleStructuresChanged = Signal()
  475. colorSchemeLimitsChanged = Signal()
  476. def getProxy(self, engine, script_engine):
  477. """Hackish way to ensure the proxy is already created
  478. which ensures that the layerview.qml is already created as this caused some issues.
  479. """
  480. if self._proxy is None:
  481. self._proxy = SimulationViewProxy(self)
  482. return self._proxy
  483. def endRendering(self) -> None:
  484. pass
  485. def event(self, event) -> bool:
  486. modifiers = QApplication.keyboardModifiers()
  487. ctrl_is_active = modifiers & Qt.KeyboardModifier.ControlModifier
  488. shift_is_active = modifiers & Qt.KeyboardModifier.ShiftModifier
  489. if event.type == Event.KeyPressEvent and ctrl_is_active:
  490. amount = 10 if shift_is_active else 1
  491. if event.key == KeyEvent.UpKey:
  492. self.setLayer(self._current_layer_num + amount)
  493. return True
  494. if event.key == KeyEvent.DownKey:
  495. self.setLayer(self._current_layer_num - amount)
  496. return True
  497. if event.type == Event.ViewActivateEvent:
  498. # Start listening to changes.
  499. Application.getInstance().getPreferences().preferenceChanged.connect(self._onPreferencesChanged)
  500. self._controller.getScene().getRoot().childrenChanged.connect(self._onSceneChanged)
  501. self.calculateColorSchemeLimits()
  502. self.calculateMaxLayers()
  503. self.calculateMaxPathsOnLayer(self._current_layer_num)
  504. # FIX: on Max OS X, somehow QOpenGLContext.currentContext() can become None during View switching.
  505. # This can happen when you do the following steps:
  506. # 1. Start Cura
  507. # 2. Load a model
  508. # 3. Switch to Custom mode
  509. # 4. Select the model and click on the per-object tool icon
  510. # 5. Switch view to Layer view or X-Ray
  511. # 6. Cura will very likely crash
  512. # It seems to be a timing issue that the currentContext can somehow be empty, but I have no clue why.
  513. # This fix tries to reschedule the view changing event call on the Qt thread again if the current OpenGL
  514. # context is None.
  515. if Platform.isOSX():
  516. if QOpenGLContext.currentContext() is None:
  517. Logger.log("d", "current context of OpenGL is empty on Mac OS X, will try to create shaders later")
  518. CuraApplication.getInstance().callLater(lambda e=event: self.event(e))
  519. return False
  520. # Make sure the SimulationPass is created
  521. layer_pass = self.getSimulationPass()
  522. renderer = self.getRenderer()
  523. if renderer is None:
  524. return False
  525. renderer.addRenderPass(layer_pass)
  526. # Make sure the NozzleNode is add to the root
  527. nozzle = self.getNozzleNode()
  528. nozzle.setParent(self.getController().getScene().getRoot())
  529. nozzle.setVisible(False)
  530. Application.getInstance().globalContainerStackChanged.connect(self._onGlobalStackChanged)
  531. self._onGlobalStackChanged()
  532. if not self._simulationview_composite_shader:
  533. plugin_path = cast(str, PluginRegistry.getInstance().getPluginPath("SimulationView"))
  534. self._simulationview_composite_shader = OpenGL.getInstance().createShaderProgram(os.path.join(plugin_path, "simulationview_composite.shader"))
  535. theme = CuraApplication.getInstance().getTheme()
  536. if theme is not None:
  537. self._simulationview_composite_shader.setUniformValue("u_background_color", Color(*theme.getColor("viewport_background").getRgb()))
  538. self._simulationview_composite_shader.setUniformValue("u_outline_color", Color(*theme.getColor("model_selection_outline").getRgb()))
  539. if not self._composite_pass:
  540. self._composite_pass = cast(CompositePass, renderer.getRenderPass("composite"))
  541. self._old_layer_bindings = self._composite_pass.getLayerBindings()[:] # make a copy so we can restore to it later
  542. self._composite_pass.getLayerBindings().append("simulationview")
  543. self._old_composite_shader = self._composite_pass.getCompositeShader()
  544. self._composite_pass.setCompositeShader(self._simulationview_composite_shader)
  545. self._updateSliceWarningVisibility()
  546. elif event.type == Event.ViewDeactivateEvent:
  547. self._controller.getScene().getRoot().childrenChanged.disconnect(self._onSceneChanged)
  548. Application.getInstance().getPreferences().preferenceChanged.disconnect(self._onPreferencesChanged)
  549. self._wireprint_warning_message.hide()
  550. self._slice_first_warning_message.hide()
  551. Application.getInstance().globalContainerStackChanged.disconnect(self._onGlobalStackChanged)
  552. if self._global_container_stack:
  553. self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  554. if self._nozzle_node:
  555. self._nozzle_node.setParent(None)
  556. renderer = self.getRenderer()
  557. if renderer is None:
  558. return False
  559. if self._layer_pass is not None:
  560. renderer.removeRenderPass(self._layer_pass)
  561. if self._composite_pass:
  562. self._composite_pass.setLayerBindings(cast(List[str], self._old_layer_bindings))
  563. self._composite_pass.setCompositeShader(cast(ShaderProgram, self._old_composite_shader))
  564. return False
  565. def getCurrentLayerMesh(self):
  566. return self._current_layer_mesh
  567. def getCurrentLayerJumps(self):
  568. return self._current_layer_jumps
  569. def _onGlobalStackChanged(self) -> None:
  570. if self._global_container_stack:
  571. self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  572. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  573. if self._global_container_stack:
  574. self._global_container_stack.propertyChanged.connect(self._onPropertyChanged)
  575. self._extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  576. self._onPropertyChanged("wireframe_enabled", "value")
  577. self.globalStackChanged.emit()
  578. else:
  579. self._wireprint_warning_message.hide()
  580. def _onPropertyChanged(self, key: str, property_name: str) -> None:
  581. if key == "wireframe_enabled" and property_name == "value":
  582. if self._global_container_stack and self._global_container_stack.getProperty("wireframe_enabled", "value"):
  583. self._wireprint_warning_message.show()
  584. else:
  585. self._wireprint_warning_message.hide()
  586. def _onCurrentLayerNumChanged(self) -> None:
  587. self.calculateMaxPathsOnLayer(self._current_layer_num)
  588. scene = Application.getInstance().getController().getScene()
  589. scene.sceneChanged.emit(scene.getRoot())
  590. def _startUpdateTopLayers(self) -> None:
  591. if not self._compatibility_mode:
  592. return
  593. if self._top_layers_job:
  594. self._top_layers_job.finished.disconnect(self._updateCurrentLayerMesh)
  595. self._top_layers_job.cancel()
  596. self.setBusy(True)
  597. self._top_layers_job = _CreateTopLayersJob(self._controller.getScene(), self._current_layer_num, self._solid_layers)
  598. self._top_layers_job.finished.connect(self._updateCurrentLayerMesh) # type: ignore # mypy doesn't understand the whole private class thing that's going on here.
  599. self._top_layers_job.start() # type: ignore
  600. def _updateCurrentLayerMesh(self, job: "_CreateTopLayersJob") -> None:
  601. self.setBusy(False)
  602. if not job.getResult():
  603. return
  604. self.resetLayerData() # Reset the layer data only when job is done. Doing it now prevents "blinking" data.
  605. self._current_layer_mesh = job.getResult().get("layers")
  606. if self._show_travel_moves:
  607. self._current_layer_jumps = job.getResult().get("jumps")
  608. self._controller.getScene().sceneChanged.emit(self._controller.getScene().getRoot())
  609. self._top_layers_job = None
  610. def _updateWithPreferences(self) -> None:
  611. self._solid_layers = int(Application.getInstance().getPreferences().getValue("view/top_layer_count"))
  612. self._only_show_top_layers = bool(Application.getInstance().getPreferences().getValue("view/only_show_top_layers"))
  613. self._compatibility_mode = self._evaluateCompatibilityMode()
  614. self.setSimulationViewType(int(float(Application.getInstance().getPreferences().getValue("layerview/layer_view_type"))))
  615. for extruder_nr, extruder_opacity in enumerate(Application.getInstance().getPreferences().getValue("layerview/extruder_opacities").split("|")):
  616. try:
  617. opacity = float(extruder_opacity)
  618. except ValueError:
  619. opacity = 1.0
  620. self.setExtruderOpacity(extruder_nr, opacity)
  621. self.setShowTravelMoves(bool(Application.getInstance().getPreferences().getValue("layerview/show_travel_moves")))
  622. self.setShowHelpers(bool(Application.getInstance().getPreferences().getValue("layerview/show_helpers")))
  623. self.setShowSkin(bool(Application.getInstance().getPreferences().getValue("layerview/show_skin")))
  624. self.setShowInfill(bool(Application.getInstance().getPreferences().getValue("layerview/show_infill")))
  625. self.setShowStarts(bool(Application.getInstance().getPreferences().getValue("layerview/show_starts")))
  626. self._startUpdateTopLayers()
  627. self.preferencesChanged.emit()
  628. def _onPreferencesChanged(self, preference: str) -> None:
  629. if preference not in {
  630. "view/top_layer_count",
  631. "view/only_show_top_layers",
  632. "view/force_layer_view_compatibility_mode",
  633. "layerview/layer_view_type",
  634. "layerview/extruder_opacities",
  635. "layerview/show_travel_moves",
  636. "layerview/show_helpers",
  637. "layerview/show_skin",
  638. "layerview/show_infill",
  639. "layerview/show_starts",
  640. }:
  641. return
  642. self._updateWithPreferences()
  643. def _updateSliceWarningVisibility(self):
  644. if not self.getActivity()\
  645. and not CuraApplication.getInstance().getPreferences().getValue("general/auto_slice")\
  646. and CuraApplication.getInstance().getPreferences().getValue(self._no_layers_warning_preference):
  647. self._slice_first_warning_message.show()
  648. else:
  649. self._slice_first_warning_message.hide()
  650. def _onDontAskMeAgain(self, checked: bool) -> None:
  651. CuraApplication.getInstance().getPreferences().setValue(self._no_layers_warning_preference, not checked)
  652. class _CreateTopLayersJob(Job):
  653. def __init__(self, scene: "Scene", layer_number: int, solid_layers: int) -> None:
  654. super().__init__()
  655. self._scene = scene
  656. self._layer_number = layer_number
  657. self._solid_layers = solid_layers
  658. self._cancel = False
  659. def run(self) -> None:
  660. layer_data = None
  661. for node in DepthFirstIterator(self._scene.getRoot()): # type: ignore
  662. layer_data = node.callDecoration("getLayerData")
  663. if layer_data:
  664. break
  665. if self._cancel or not layer_data:
  666. return
  667. layer_mesh = MeshBuilder()
  668. for i in range(self._solid_layers):
  669. layer_number = self._layer_number - i
  670. if layer_number < 0:
  671. continue
  672. try:
  673. layer = layer_data.getLayer(layer_number).createMesh()
  674. except Exception:
  675. Logger.logException("w", "An exception occurred while creating layer mesh.")
  676. return
  677. if not layer or layer.getVertices() is None:
  678. continue
  679. layer_mesh.addIndices(layer_mesh.getVertexCount() + layer.getIndices())
  680. layer_mesh.addVertices(layer.getVertices())
  681. # Scale layer color by a brightness factor based on the current layer number
  682. # This will result in a range of 0.5 - 1.0 to multiply colors by.
  683. brightness = numpy.ones((1, 4), dtype=numpy.float32) * (2.0 - (i / self._solid_layers)) / 2.0
  684. brightness[0, 3] = 1.0
  685. layer_mesh.addColors(layer.getColors() * brightness)
  686. if self._cancel:
  687. return
  688. Job.yieldThread()
  689. if self._cancel:
  690. return
  691. Job.yieldThread()
  692. jump_mesh = layer_data.getLayer(self._layer_number).createJumps()
  693. if not jump_mesh or jump_mesh.getVertices() is None:
  694. jump_mesh = None
  695. self.setResult({"layers": layer_mesh.build(), "jumps": jump_mesh})
  696. def cancel(self) -> None:
  697. self._cancel = True
  698. super().cancel()