LayerView.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. import sys
  4. from UM.PluginRegistry import PluginRegistry
  5. from UM.View.View import View
  6. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  7. from UM.Resources import Resources
  8. from UM.Event import Event, KeyEvent
  9. from UM.Signal import Signal
  10. from UM.Scene.Selection import Selection
  11. from UM.Math.Color import Color
  12. from UM.Mesh.MeshBuilder import MeshBuilder
  13. from UM.Job import Job
  14. from UM.Preferences import Preferences
  15. from UM.Logger import Logger
  16. from UM.View.GL.OpenGL import OpenGL
  17. from UM.Message import Message
  18. from UM.Application import Application
  19. from UM.View.GL.OpenGLContext import OpenGLContext
  20. from cura.ConvexHullNode import ConvexHullNode
  21. from cura.Settings.ExtruderManager import ExtruderManager
  22. from PyQt5.QtCore import Qt
  23. from PyQt5.QtWidgets import QApplication
  24. from . import LayerViewProxy
  25. from UM.i18n import i18nCatalog
  26. catalog = i18nCatalog("cura")
  27. from . import LayerPass
  28. import numpy
  29. import os.path
  30. ## View used to display g-code paths.
  31. class LayerView(View):
  32. # Must match LayerView.qml
  33. LAYER_VIEW_TYPE_MATERIAL_TYPE = 0
  34. LAYER_VIEW_TYPE_LINE_TYPE = 1
  35. def __init__(self):
  36. super().__init__()
  37. self._max_layers = 0
  38. self._current_layer_num = 0
  39. self._minimum_layer_num = 0
  40. self._current_layer_mesh = None
  41. self._current_layer_jumps = None
  42. self._top_layers_job = None
  43. self._activity = False
  44. self._old_max_layers = 0
  45. self._busy = False
  46. self._ghost_shader = None
  47. self._layer_pass = None
  48. self._composite_pass = None
  49. self._old_layer_bindings = None
  50. self._layerview_composite_shader = None
  51. self._old_composite_shader = None
  52. self._global_container_stack = None
  53. self._proxy = LayerViewProxy.LayerViewProxy()
  54. self._controller.getScene().getRoot().childrenChanged.connect(self._onSceneChanged)
  55. self._resetSettings()
  56. self._legend_items = None
  57. self._show_travel_moves = False
  58. Preferences.getInstance().addPreference("view/top_layer_count", 5)
  59. Preferences.getInstance().addPreference("view/only_show_top_layers", False)
  60. Preferences.getInstance().addPreference("view/force_layer_view_compatibility_mode", False)
  61. Preferences.getInstance().addPreference("layerview/layer_view_type", 0)
  62. Preferences.getInstance().addPreference("layerview/extruder_opacities", "")
  63. Preferences.getInstance().addPreference("layerview/show_travel_moves", False)
  64. Preferences.getInstance().addPreference("layerview/show_helpers", True)
  65. Preferences.getInstance().addPreference("layerview/show_skin", True)
  66. Preferences.getInstance().addPreference("layerview/show_infill", True)
  67. Preferences.getInstance().preferenceChanged.connect(self._onPreferencesChanged)
  68. self._updateWithPreferences()
  69. self._solid_layers = int(Preferences.getInstance().getValue("view/top_layer_count"))
  70. self._only_show_top_layers = bool(Preferences.getInstance().getValue("view/only_show_top_layers"))
  71. self._compatibility_mode = True # for safety
  72. self._wireprint_warning_message = Message(catalog.i18nc("@info:status", "Cura does not accurately display layers when Wire Printing is enabled"))
  73. def _resetSettings(self):
  74. self._layer_view_type = 0 # 0 is material color, 1 is color by linetype, 2 is speed
  75. self._extruder_count = 0
  76. self._extruder_opacity = [1.0, 1.0, 1.0, 1.0]
  77. self._show_travel_moves = 0
  78. self._show_helpers = 1
  79. self._show_skin = 1
  80. self._show_infill = 1
  81. def getActivity(self):
  82. return self._activity
  83. def getLayerPass(self):
  84. if not self._layer_pass:
  85. # Currently the RenderPass constructor requires a size > 0
  86. # This should be fixed in RenderPass's constructor.
  87. self._layer_pass = LayerPass.LayerPass(1, 1)
  88. self._compatibility_mode = OpenGLContext.isLegacyOpenGL() or bool(Preferences.getInstance().getValue("view/force_layer_view_compatibility_mode"))
  89. self._layer_pass.setLayerView(self)
  90. self.getRenderer().addRenderPass(self._layer_pass)
  91. return self._layer_pass
  92. def getCurrentLayer(self):
  93. return self._current_layer_num
  94. def getMinimumLayer(self):
  95. return self._minimum_layer_num
  96. def _onSceneChanged(self, node):
  97. self.calculateMaxLayers()
  98. def getMaxLayers(self):
  99. return self._max_layers
  100. busyChanged = Signal()
  101. def isBusy(self):
  102. return self._busy
  103. def setBusy(self, busy):
  104. if busy != self._busy:
  105. self._busy = busy
  106. self.busyChanged.emit()
  107. def resetLayerData(self):
  108. self._current_layer_mesh = None
  109. self._current_layer_jumps = None
  110. def beginRendering(self):
  111. scene = self.getController().getScene()
  112. renderer = self.getRenderer()
  113. if not self._ghost_shader:
  114. self._ghost_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "color.shader"))
  115. self._ghost_shader.setUniformValue("u_color", Color(*Application.getInstance().getTheme().getColor("layerview_ghost").getRgb()))
  116. for node in DepthFirstIterator(scene.getRoot()):
  117. # We do not want to render ConvexHullNode as it conflicts with the bottom layers.
  118. # However, it is somewhat relevant when the node is selected, so do render it then.
  119. if type(node) is ConvexHullNode and not Selection.isSelected(node.getWatchedNode()):
  120. continue
  121. if not node.render(renderer):
  122. if (node.getMeshData()) and node.isVisible():
  123. renderer.queueNode(node, transparent = True, shader = self._ghost_shader)
  124. def setLayer(self, value):
  125. if self._current_layer_num != value:
  126. self._current_layer_num = value
  127. if self._current_layer_num < 0:
  128. self._current_layer_num = 0
  129. if self._current_layer_num > self._max_layers:
  130. self._current_layer_num = self._max_layers
  131. if self._current_layer_num < self._minimum_layer_num:
  132. self._minimum_layer_num = self._current_layer_num
  133. self._startUpdateTopLayers()
  134. self.currentLayerNumChanged.emit()
  135. def setMinimumLayer(self, value):
  136. if self._minimum_layer_num != value:
  137. self._minimum_layer_num = value
  138. if self._minimum_layer_num < 0:
  139. self._minimum_layer_num = 0
  140. if self._minimum_layer_num > self._max_layers:
  141. self._minimum_layer_num = self._max_layers
  142. if self._minimum_layer_num > self._current_layer_num:
  143. self._current_layer_num = self._minimum_layer_num
  144. self._startUpdateTopLayers()
  145. self.currentLayerNumChanged.emit()
  146. ## Set the layer view type
  147. #
  148. # \param layer_view_type integer as in LayerView.qml and this class
  149. def setLayerViewType(self, layer_view_type):
  150. self._layer_view_type = layer_view_type
  151. self.currentLayerNumChanged.emit()
  152. ## Return the layer view type, integer as in LayerView.qml and this class
  153. def getLayerViewType(self):
  154. return self._layer_view_type
  155. ## Set the extruder opacity
  156. #
  157. # \param extruder_nr 0..3
  158. # \param opacity 0.0 .. 1.0
  159. def setExtruderOpacity(self, extruder_nr, opacity):
  160. if 0 <= extruder_nr <= 3:
  161. self._extruder_opacity[extruder_nr] = opacity
  162. self.currentLayerNumChanged.emit()
  163. def getExtruderOpacities(self):
  164. return self._extruder_opacity
  165. def setShowTravelMoves(self, show):
  166. self._show_travel_moves = show
  167. self.currentLayerNumChanged.emit()
  168. def getShowTravelMoves(self):
  169. return self._show_travel_moves
  170. def setShowHelpers(self, show):
  171. self._show_helpers = show
  172. self.currentLayerNumChanged.emit()
  173. def getShowHelpers(self):
  174. return self._show_helpers
  175. def setShowSkin(self, show):
  176. self._show_skin = show
  177. self.currentLayerNumChanged.emit()
  178. def getShowSkin(self):
  179. return self._show_skin
  180. def setShowInfill(self, show):
  181. self._show_infill = show
  182. self.currentLayerNumChanged.emit()
  183. def getShowInfill(self):
  184. return self._show_infill
  185. def getCompatibilityMode(self):
  186. return self._compatibility_mode
  187. def getExtruderCount(self):
  188. return self._extruder_count
  189. def calculateMaxLayers(self):
  190. scene = self.getController().getScene()
  191. self._activity = True
  192. self._old_max_layers = self._max_layers
  193. ## Recalculate num max layers
  194. new_max_layers = 0
  195. for node in DepthFirstIterator(scene.getRoot()):
  196. layer_data = node.callDecoration("getLayerData")
  197. if not layer_data:
  198. continue
  199. min_layer_number = sys.maxsize
  200. max_layer_number = -sys.maxsize
  201. for layer_id in layer_data.getLayers():
  202. if max_layer_number < layer_id:
  203. max_layer_number = layer_id
  204. if min_layer_number > layer_id:
  205. min_layer_number = layer_id
  206. layer_count = max_layer_number - min_layer_number
  207. if new_max_layers < layer_count:
  208. new_max_layers = layer_count
  209. if new_max_layers > 0 and new_max_layers != self._old_max_layers:
  210. self._max_layers = new_max_layers
  211. # The qt slider has a bit of weird behavior that if the maxvalue needs to be changed first
  212. # if it's the largest value. If we don't do this, we can have a slider block outside of the
  213. # slider.
  214. if new_max_layers > self._current_layer_num:
  215. self.maxLayersChanged.emit()
  216. self.setLayer(int(self._max_layers))
  217. else:
  218. self.setLayer(int(self._max_layers))
  219. self.maxLayersChanged.emit()
  220. self._startUpdateTopLayers()
  221. maxLayersChanged = Signal()
  222. currentLayerNumChanged = Signal()
  223. globalStackChanged = Signal()
  224. preferencesChanged = Signal()
  225. ## Hackish way to ensure the proxy is already created, which ensures that the layerview.qml is already created
  226. # as this caused some issues.
  227. def getProxy(self, engine, script_engine):
  228. return self._proxy
  229. def endRendering(self):
  230. pass
  231. def event(self, event):
  232. modifiers = QApplication.keyboardModifiers()
  233. ctrl_is_active = modifiers & Qt.ControlModifier
  234. shift_is_active = modifiers & Qt.ShiftModifier
  235. if event.type == Event.KeyPressEvent and ctrl_is_active:
  236. amount = 10 if shift_is_active else 1
  237. if event.key == KeyEvent.UpKey:
  238. self.setLayer(self._current_layer_num + amount)
  239. return True
  240. if event.key == KeyEvent.DownKey:
  241. self.setLayer(self._current_layer_num - amount)
  242. return True
  243. if event.type == Event.ViewActivateEvent:
  244. # Make sure the LayerPass is created
  245. self.getLayerPass()
  246. Application.getInstance().globalContainerStackChanged.connect(self._onGlobalStackChanged)
  247. self._onGlobalStackChanged()
  248. if not self._layerview_composite_shader:
  249. self._layerview_composite_shader = OpenGL.getInstance().createShaderProgram(os.path.join(PluginRegistry.getInstance().getPluginPath("LayerView"), "layerview_composite.shader"))
  250. theme = Application.getInstance().getTheme()
  251. self._layerview_composite_shader.setUniformValue("u_background_color", Color(*theme.getColor("viewport_background").getRgb()))
  252. self._layerview_composite_shader.setUniformValue("u_outline_color", Color(*theme.getColor("model_selection_outline").getRgb()))
  253. if not self._composite_pass:
  254. self._composite_pass = self.getRenderer().getRenderPass("composite")
  255. self._old_layer_bindings = self._composite_pass.getLayerBindings()[:] # make a copy so we can restore to it later
  256. self._composite_pass.getLayerBindings().append("layerview")
  257. self._old_composite_shader = self._composite_pass.getCompositeShader()
  258. self._composite_pass.setCompositeShader(self._layerview_composite_shader)
  259. elif event.type == Event.ViewDeactivateEvent:
  260. self._wireprint_warning_message.hide()
  261. Application.getInstance().globalContainerStackChanged.disconnect(self._onGlobalStackChanged)
  262. if self._global_container_stack:
  263. self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  264. self._composite_pass.setLayerBindings(self._old_layer_bindings)
  265. self._composite_pass.setCompositeShader(self._old_composite_shader)
  266. def getCurrentLayerMesh(self):
  267. return self._current_layer_mesh
  268. def getCurrentLayerJumps(self):
  269. return self._current_layer_jumps
  270. def _onGlobalStackChanged(self):
  271. if self._global_container_stack:
  272. self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  273. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  274. if self._global_container_stack:
  275. self._global_container_stack.propertyChanged.connect(self._onPropertyChanged)
  276. self._extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  277. self._onPropertyChanged("wireframe_enabled", "value")
  278. self.globalStackChanged.emit()
  279. else:
  280. self._wireprint_warning_message.hide()
  281. def _onPropertyChanged(self, key, property_name):
  282. if key == "wireframe_enabled" and property_name == "value":
  283. if self._global_container_stack.getProperty("wireframe_enabled", "value"):
  284. self._wireprint_warning_message.show()
  285. else:
  286. self._wireprint_warning_message.hide()
  287. def _startUpdateTopLayers(self):
  288. if not self._compatibility_mode:
  289. return
  290. if self._top_layers_job:
  291. self._top_layers_job.finished.disconnect(self._updateCurrentLayerMesh)
  292. self._top_layers_job.cancel()
  293. self.setBusy(True)
  294. self._top_layers_job = _CreateTopLayersJob(self._controller.getScene(), self._current_layer_num, self._solid_layers)
  295. self._top_layers_job.finished.connect(self._updateCurrentLayerMesh)
  296. self._top_layers_job.start()
  297. def _updateCurrentLayerMesh(self, job):
  298. self.setBusy(False)
  299. if not job.getResult():
  300. return
  301. self.resetLayerData() # Reset the layer data only when job is done. Doing it now prevents "blinking" data.
  302. self._current_layer_mesh = job.getResult().get("layers")
  303. if self._show_travel_moves:
  304. self._current_layer_jumps = job.getResult().get("jumps")
  305. self._controller.getScene().sceneChanged.emit(self._controller.getScene().getRoot())
  306. self._top_layers_job = None
  307. def _updateWithPreferences(self):
  308. self._solid_layers = int(Preferences.getInstance().getValue("view/top_layer_count"))
  309. self._only_show_top_layers = bool(Preferences.getInstance().getValue("view/only_show_top_layers"))
  310. self._compatibility_mode = OpenGLContext.isLegacyOpenGL() or bool(
  311. Preferences.getInstance().getValue("view/force_layer_view_compatibility_mode"))
  312. self.setLayerViewType(int(float(Preferences.getInstance().getValue("layerview/layer_view_type"))));
  313. for extruder_nr, extruder_opacity in enumerate(Preferences.getInstance().getValue("layerview/extruder_opacities").split("|")):
  314. try:
  315. opacity = float(extruder_opacity)
  316. except ValueError:
  317. opacity = 1.0
  318. self.setExtruderOpacity(extruder_nr, opacity)
  319. self.setShowTravelMoves(bool(Preferences.getInstance().getValue("layerview/show_travel_moves")))
  320. self.setShowHelpers(bool(Preferences.getInstance().getValue("layerview/show_helpers")))
  321. self.setShowSkin(bool(Preferences.getInstance().getValue("layerview/show_skin")))
  322. self.setShowInfill(bool(Preferences.getInstance().getValue("layerview/show_infill")))
  323. self._startUpdateTopLayers()
  324. self.preferencesChanged.emit()
  325. def _onPreferencesChanged(self, preference):
  326. if preference not in {
  327. "view/top_layer_count",
  328. "view/only_show_top_layers",
  329. "view/force_layer_view_compatibility_mode",
  330. "layerview/layer_view_type",
  331. "layerview/extruder_opacities",
  332. "layerview/show_travel_moves",
  333. "layerview/show_helpers",
  334. "layerview/show_skin",
  335. "layerview/show_infill",
  336. }:
  337. return
  338. self._updateWithPreferences()
  339. class _CreateTopLayersJob(Job):
  340. def __init__(self, scene, layer_number, solid_layers):
  341. super().__init__()
  342. self._scene = scene
  343. self._layer_number = layer_number
  344. self._solid_layers = solid_layers
  345. self._cancel = False
  346. def run(self):
  347. layer_data = None
  348. for node in DepthFirstIterator(self._scene.getRoot()):
  349. layer_data = node.callDecoration("getLayerData")
  350. if layer_data:
  351. break
  352. if self._cancel or not layer_data:
  353. return
  354. layer_mesh = MeshBuilder()
  355. for i in range(self._solid_layers):
  356. layer_number = self._layer_number - i
  357. if layer_number < 0:
  358. continue
  359. try:
  360. layer = layer_data.getLayer(layer_number).createMesh()
  361. except Exception:
  362. Logger.logException("w", "An exception occurred while creating layer mesh.")
  363. return
  364. if not layer or layer.getVertices() is None:
  365. continue
  366. layer_mesh.addIndices(layer_mesh.getVertexCount() + layer.getIndices())
  367. layer_mesh.addVertices(layer.getVertices())
  368. # Scale layer color by a brightness factor based on the current layer number
  369. # This will result in a range of 0.5 - 1.0 to multiply colors by.
  370. brightness = numpy.ones((1, 4), dtype=numpy.float32) * (2.0 - (i / self._solid_layers)) / 2.0
  371. brightness[0, 3] = 1.0
  372. layer_mesh.addColors(layer.getColors() * brightness)
  373. if self._cancel:
  374. return
  375. Job.yieldThread()
  376. if self._cancel:
  377. return
  378. Job.yieldThread()
  379. jump_mesh = layer_data.getLayer(self._layer_number).createJumps()
  380. if not jump_mesh or jump_mesh.getVertices() is None:
  381. jump_mesh = None
  382. self.setResult({"layers": layer_mesh.build(), "jumps": jump_mesh})
  383. def cancel(self):
  384. self._cancel = True
  385. super().cancel()