SimulationView.py 32 KB

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