SimulationView.py 41 KB

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