SimulationView.py 37 KB

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