SimulationView.py 25 KB

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