SimulationView.py 31 KB

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