SimulationView.py 30 KB

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