BuildVolume.py 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import numpy
  4. import math
  5. from typing import List, Optional, TYPE_CHECKING, Any, Set, cast, Iterable, Dict
  6. from UM.Logger import Logger
  7. from UM.Mesh.MeshData import MeshData
  8. from UM.Mesh.MeshBuilder import MeshBuilder
  9. from UM.Application import Application #To modify the maximum zoom level.
  10. from UM.i18n import i18nCatalog
  11. from UM.Scene.Platform import Platform
  12. from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
  13. from UM.Scene.SceneNode import SceneNode
  14. from UM.Resources import Resources
  15. from UM.Math.Vector import Vector
  16. from UM.Math.Matrix import Matrix
  17. from UM.Math.Color import Color
  18. from UM.Math.AxisAlignedBox import AxisAlignedBox
  19. from UM.Math.Polygon import Polygon
  20. from UM.Message import Message
  21. from UM.Signal import Signal
  22. from UM.View.RenderBatch import RenderBatch
  23. from UM.View.GL.OpenGL import OpenGL
  24. from cura.Settings.GlobalStack import GlobalStack
  25. from cura.Scene.CuraSceneNode import CuraSceneNode
  26. from cura.Settings.ExtruderManager import ExtruderManager
  27. from PyQt6.QtCore import QTimer
  28. if TYPE_CHECKING:
  29. from cura.CuraApplication import CuraApplication
  30. from cura.Settings.ExtruderStack import ExtruderStack
  31. from UM.Settings.ContainerStack import ContainerStack
  32. catalog = i18nCatalog("cura")
  33. # Radius of disallowed area in mm around prime. I.e. how much distance to keep from prime position.
  34. PRIME_CLEARANCE = 6.5
  35. class BuildVolume(SceneNode):
  36. """Build volume is a special kind of node that is responsible for rendering the printable area & disallowed areas."""
  37. raftThicknessChanged = Signal()
  38. def __init__(self, application: "CuraApplication", parent: Optional[SceneNode] = None) -> None:
  39. super().__init__(parent)
  40. self._application = application
  41. self._machine_manager = self._application.getMachineManager()
  42. self._volume_outline_color = None # type: Optional[Color]
  43. self._x_axis_color = None # type: Optional[Color]
  44. self._y_axis_color = None # type: Optional[Color]
  45. self._z_axis_color = None # type: Optional[Color]
  46. self._disallowed_area_color = None # type: Optional[Color]
  47. self._error_area_color = None # type: Optional[Color]
  48. self._width = 0 # type: float
  49. self._height = 0 # type: float
  50. self._depth = 0 # type: float
  51. self._shape = "" # type: str
  52. self._scale_vector = Vector(1.0, 1.0, 1.0)
  53. self._shader = None
  54. self._origin_mesh = None # type: Optional[MeshData]
  55. self._origin_line_length = 20
  56. self._origin_line_width = 1
  57. self._enabled = False
  58. self._grid_mesh = None # type: Optional[MeshData]
  59. self._grid_shader = None
  60. self._disallowed_areas = [] # type: List[Polygon]
  61. self._disallowed_areas_no_brim = [] # type: List[Polygon]
  62. self._disallowed_area_mesh = None # type: Optional[MeshData]
  63. self._disallowed_area_size = 0.
  64. self._error_areas = [] # type: List[Polygon]
  65. self._error_mesh = None # type: Optional[MeshData]
  66. self.setCalculateBoundingBox(False)
  67. self._volume_aabb = None # type: Optional[AxisAlignedBox]
  68. self._raft_thickness = 0.0
  69. self._extra_z_clearance = 0.0
  70. self._adhesion_type = None # type: Any
  71. self._platform = Platform(self)
  72. self._edge_disallowed_size = None
  73. self._build_volume_message = Message(catalog.i18nc("@info:status",
  74. "The build volume height has been reduced due to the value of the"
  75. " \"Print Sequence\" setting to prevent the gantry from colliding"
  76. " with printed models."),
  77. title = catalog.i18nc("@info:title", "Build Volume"),
  78. message_type = Message.MessageType.WARNING)
  79. self._global_container_stack = None # type: Optional[GlobalStack]
  80. self._stack_change_timer = QTimer()
  81. self._stack_change_timer.setInterval(100)
  82. self._stack_change_timer.setSingleShot(True)
  83. self._stack_change_timer.timeout.connect(self._onStackChangeTimerFinished)
  84. self._application.globalContainerStackChanged.connect(self._onStackChanged)
  85. self._engine_ready = False
  86. self._application.engineCreatedSignal.connect(self._onEngineCreated)
  87. self._has_errors = False
  88. self._application.getController().getScene().sceneChanged.connect(self._onSceneChanged)
  89. # Objects loaded at the moment. We are connected to the property changed events of these objects.
  90. self._scene_objects = set() # type: Set[SceneNode]
  91. self._scene_change_timer = QTimer()
  92. self._scene_change_timer.setInterval(200)
  93. self._scene_change_timer.setSingleShot(True)
  94. self._scene_change_timer.timeout.connect(self._onSceneChangeTimerFinished)
  95. self._setting_change_timer = QTimer()
  96. self._setting_change_timer.setInterval(150)
  97. self._setting_change_timer.setSingleShot(True)
  98. self._setting_change_timer.timeout.connect(self._onSettingChangeTimerFinished)
  99. # Must be after setting _build_volume_message, apparently that is used in getMachineManager.
  100. # activeQualityChanged is always emitted after setActiveVariant, setActiveMaterial and setActiveQuality.
  101. # Therefore this works.
  102. self._machine_manager.activeQualityChanged.connect(self._onStackChanged)
  103. # Enable and disable extruder
  104. self._machine_manager.extruderChanged.connect(self.updateNodeBoundaryCheck)
  105. # List of settings which were updated
  106. self._changed_settings_since_last_rebuild = [] # type: List[str]
  107. def _onSceneChanged(self, source):
  108. if self._global_container_stack:
  109. # Ignore anything that is not something we can slice in the first place!
  110. if source.callDecoration("isSliceable"):
  111. self._scene_change_timer.start()
  112. def _onSceneChangeTimerFinished(self):
  113. root = self._application.getController().getScene().getRoot()
  114. new_scene_objects = set(node for node in BreadthFirstIterator(root) if node.callDecoration("isSliceable"))
  115. if new_scene_objects != self._scene_objects:
  116. for node in new_scene_objects - self._scene_objects: #Nodes that were added to the scene.
  117. self._updateNodeListeners(node)
  118. node.decoratorsChanged.connect(self._updateNodeListeners) # Make sure that decoration changes afterwards also receive the same treatment
  119. for node in self._scene_objects - new_scene_objects: #Nodes that were removed from the scene.
  120. per_mesh_stack = node.callDecoration("getStack")
  121. if per_mesh_stack:
  122. per_mesh_stack.propertyChanged.disconnect(self._onSettingPropertyChanged)
  123. active_extruder_changed = node.callDecoration("getActiveExtruderChangedSignal")
  124. if active_extruder_changed is not None:
  125. node.callDecoration("getActiveExtruderChangedSignal").disconnect(self._updateDisallowedAreasAndRebuild)
  126. node.decoratorsChanged.disconnect(self._updateNodeListeners)
  127. self.rebuild()
  128. self._scene_objects = new_scene_objects
  129. self._onSettingPropertyChanged("print_sequence", "value") # Create fake event, so right settings are triggered.
  130. def _updateNodeListeners(self, node: SceneNode):
  131. """Updates the listeners that listen for changes in per-mesh stacks.
  132. :param node: The node for which the decorators changed.
  133. """
  134. per_mesh_stack = node.callDecoration("getStack")
  135. if per_mesh_stack:
  136. per_mesh_stack.propertyChanged.connect(self._onSettingPropertyChanged)
  137. active_extruder_changed = node.callDecoration("getActiveExtruderChangedSignal")
  138. if active_extruder_changed is not None:
  139. active_extruder_changed.connect(self._updateDisallowedAreasAndRebuild)
  140. def setWidth(self, width: float) -> None:
  141. self._width = width
  142. def getWidth(self) -> float:
  143. return self._width
  144. def setHeight(self, height: float) -> None:
  145. self._height = height
  146. def getHeight(self) -> float:
  147. return self._height
  148. def setDepth(self, depth: float) -> None:
  149. self._depth = depth
  150. def getDepth(self) -> float:
  151. return self._depth
  152. def setShape(self, shape: str) -> None:
  153. if shape:
  154. self._shape = shape
  155. def getDiagonalSize(self) -> float:
  156. """Get the length of the 3D diagonal through the build volume.
  157. This gives a sense of the scale of the build volume in general.
  158. :return: length of the 3D diagonal through the build volume
  159. """
  160. return math.sqrt(self._width * self._width + self._height * self._height + self._depth * self._depth)
  161. def getDisallowedAreas(self) -> List[Polygon]:
  162. return self._disallowed_areas
  163. def getDisallowedAreasNoBrim(self) -> List[Polygon]:
  164. return self._disallowed_areas_no_brim
  165. def setDisallowedAreas(self, areas: List[Polygon]):
  166. self._disallowed_areas = areas
  167. def render(self, renderer):
  168. if not self.getMeshData() or not self.isVisible():
  169. return True
  170. if not self._shader:
  171. self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "default.shader"))
  172. self._grid_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "grid.shader"))
  173. theme = self._application.getTheme()
  174. self._grid_shader.setUniformValue("u_plateColor", Color(*theme.getColor("buildplate").getRgb()))
  175. self._grid_shader.setUniformValue("u_gridColor0", Color(*theme.getColor("buildplate_grid").getRgb()))
  176. self._grid_shader.setUniformValue("u_gridColor1", Color(*theme.getColor("buildplate_grid_minor").getRgb()))
  177. renderer.queueNode(self, mode = RenderBatch.RenderMode.Lines)
  178. renderer.queueNode(self, mesh = self._origin_mesh, backface_cull = True)
  179. renderer.queueNode(self, mesh = self._grid_mesh, shader = self._grid_shader, backface_cull = True)
  180. if self._disallowed_area_mesh:
  181. renderer.queueNode(self, mesh = self._disallowed_area_mesh, shader = self._shader, transparent = True, backface_cull = True, sort = -9)
  182. if self._error_mesh:
  183. renderer.queueNode(self, mesh=self._error_mesh, shader=self._shader, transparent=True,
  184. backface_cull=True, sort=-8)
  185. return True
  186. def updateNodeBoundaryCheck(self):
  187. """For every sliceable node, update node._outside_buildarea"""
  188. if not self._global_container_stack:
  189. return
  190. root = self._application.getController().getScene().getRoot()
  191. nodes = cast(List[SceneNode], list(cast(Iterable, BreadthFirstIterator(root))))
  192. group_nodes = [] # type: List[SceneNode]
  193. build_volume_bounding_box = self.getBoundingBox()
  194. if build_volume_bounding_box:
  195. # It's over 9000!
  196. # We set this to a very low number, as we do allow models to intersect the build plate.
  197. # This means the model gets cut off at the build plate.
  198. build_volume_bounding_box = build_volume_bounding_box.set(bottom=-9001)
  199. else:
  200. # No bounding box. This is triggered when running Cura from command line with a model for the first time
  201. # In that situation there is a model, but no machine (and therefore no build volume.
  202. return
  203. for node in nodes:
  204. # Need to check group nodes later
  205. if node.callDecoration("isGroup"):
  206. group_nodes.append(node) # Keep list of affected group_nodes
  207. if node.callDecoration("isSliceable") or node.callDecoration("isGroup"):
  208. if not isinstance(node, CuraSceneNode):
  209. continue
  210. if node.collidesWithBbox(build_volume_bounding_box):
  211. node.setOutsideBuildArea(True)
  212. continue
  213. if node.collidesWithAreas(self.getDisallowedAreas()):
  214. node.setOutsideBuildArea(True)
  215. continue
  216. # If the entire node is below the build plate, still mark it as outside.
  217. node_bounding_box = node.getBoundingBox()
  218. if node_bounding_box and node_bounding_box.top < 0 and not node.getParent().callDecoration("isGroup"):
  219. node.setOutsideBuildArea(True)
  220. continue
  221. # Mark the node as outside build volume if the set extruder is disabled
  222. extruder_position = node.callDecoration("getActiveExtruderPosition")
  223. try:
  224. if not self._global_container_stack.extruderList[int(extruder_position)].isEnabled and not node.callDecoration("isGroup"):
  225. node.setOutsideBuildArea(True)
  226. continue
  227. except IndexError: # Happens when the extruder list is too short. We're not done building the printer in memory yet.
  228. continue
  229. except TypeError: # Happens when extruder_position is None. This object has no extruder decoration.
  230. continue
  231. node.setOutsideBuildArea(False)
  232. # Group nodes should override the _outside_buildarea property of their children.
  233. for group_node in group_nodes:
  234. children = group_node.getAllChildren()
  235. # Check if one or more children are non-printable and if so, set the parent as non-printable:
  236. for child_node in children:
  237. if child_node.isOutsideBuildArea():
  238. group_node.setOutsideBuildArea(True)
  239. break
  240. # Apply results of the check to all children of the group:
  241. for child_node in children:
  242. child_node.setOutsideBuildArea(group_node.isOutsideBuildArea())
  243. def checkBoundsAndUpdate(self, node: CuraSceneNode, bounds: Optional[AxisAlignedBox] = None) -> None:
  244. """Update the outsideBuildArea of a single node, given bounds or current build volume
  245. :param node: single node
  246. :param bounds: bounds or current build volume
  247. """
  248. if not isinstance(node, CuraSceneNode) or self._global_container_stack is None:
  249. return
  250. if bounds is None:
  251. build_volume_bounding_box = self.getBoundingBox()
  252. if build_volume_bounding_box:
  253. # It's over 9000!
  254. build_volume_bounding_box = build_volume_bounding_box.set(bottom=-9001)
  255. else:
  256. # No bounding box. This is triggered when running Cura from command line with a model for the first time
  257. # In that situation there is a model, but no machine (and therefore no build volume.
  258. return
  259. else:
  260. build_volume_bounding_box = bounds
  261. if node.callDecoration("isSliceable") or node.callDecoration("isGroup"):
  262. if node.collidesWithBbox(build_volume_bounding_box):
  263. node.setOutsideBuildArea(True)
  264. return
  265. if node.collidesWithAreas(self.getDisallowedAreas()):
  266. node.setOutsideBuildArea(True)
  267. return
  268. # Mark the node as outside build volume if the set extruder is disabled
  269. extruder_position = node.callDecoration("getActiveExtruderPosition")
  270. try:
  271. if not self._global_container_stack.extruderList[int(extruder_position)].isEnabled:
  272. node.setOutsideBuildArea(True)
  273. return
  274. except IndexError:
  275. # If the extruder doesn't exist, also mark it as unprintable.
  276. node.setOutsideBuildArea(True)
  277. return
  278. node.setOutsideBuildArea(False)
  279. def _buildGridMesh(self, min_w: float, max_w: float, min_h: float, max_h: float, min_d: float, max_d:float, z_fight_distance: float) -> MeshData:
  280. mb = MeshBuilder()
  281. if self._shape != "elliptic":
  282. # Build plate grid mesh
  283. mb.addQuad(
  284. Vector(min_w, min_h - z_fight_distance, min_d),
  285. Vector(max_w, min_h - z_fight_distance, min_d),
  286. Vector(max_w, min_h - z_fight_distance, max_d),
  287. Vector(min_w, min_h - z_fight_distance, max_d)
  288. )
  289. for n in range(0, 6):
  290. v = mb.getVertex(n)
  291. mb.setVertexUVCoordinates(n, v[0], v[2])
  292. return mb.build()
  293. else:
  294. aspect = 1.0
  295. scale_matrix = Matrix()
  296. if self._width != 0:
  297. # Scale circular meshes by aspect ratio if width != height
  298. aspect = self._depth / self._width
  299. scale_matrix.compose(scale=Vector(1, 1, aspect))
  300. mb.addVertex(0, min_h - z_fight_distance, 0)
  301. mb.addArc(max_w, Vector.Unit_Y, center=Vector(0, min_h - z_fight_distance, 0))
  302. sections = mb.getVertexCount() - 1 # Center point is not an arc section
  303. indices = []
  304. for n in range(0, sections - 1):
  305. indices.append([0, n + 2, n + 1])
  306. mb.addIndices(numpy.asarray(indices, dtype=numpy.int32))
  307. mb.calculateNormals()
  308. for n in range(0, mb.getVertexCount()):
  309. v = mb.getVertex(n)
  310. mb.setVertexUVCoordinates(n, v[0], v[2] * aspect)
  311. return mb.build().getTransformed(scale_matrix)
  312. def _buildMesh(self, min_w: float, max_w: float, min_h: float, max_h: float, min_d: float, max_d:float, z_fight_distance: float) -> MeshData:
  313. if self._shape != "elliptic":
  314. # Outline 'cube' of the build volume
  315. mb = MeshBuilder()
  316. mb.addLine(Vector(min_w, min_h, min_d), Vector(max_w, min_h, min_d), color = self._volume_outline_color)
  317. mb.addLine(Vector(min_w, min_h, min_d), Vector(min_w, max_h, min_d), color = self._volume_outline_color)
  318. mb.addLine(Vector(min_w, max_h, min_d), Vector(max_w, max_h, min_d), color = self._volume_outline_color)
  319. mb.addLine(Vector(max_w, min_h, min_d), Vector(max_w, max_h, min_d), color = self._volume_outline_color)
  320. mb.addLine(Vector(min_w, min_h, max_d), Vector(max_w, min_h, max_d), color = self._volume_outline_color)
  321. mb.addLine(Vector(min_w, min_h, max_d), Vector(min_w, max_h, max_d), color = self._volume_outline_color)
  322. mb.addLine(Vector(min_w, max_h, max_d), Vector(max_w, max_h, max_d), color = self._volume_outline_color)
  323. mb.addLine(Vector(max_w, min_h, max_d), Vector(max_w, max_h, max_d), color = self._volume_outline_color)
  324. mb.addLine(Vector(min_w, min_h, min_d), Vector(min_w, min_h, max_d), color = self._volume_outline_color)
  325. mb.addLine(Vector(max_w, min_h, min_d), Vector(max_w, min_h, max_d), color = self._volume_outline_color)
  326. mb.addLine(Vector(min_w, max_h, min_d), Vector(min_w, max_h, max_d), color = self._volume_outline_color)
  327. mb.addLine(Vector(max_w, max_h, min_d), Vector(max_w, max_h, max_d), color = self._volume_outline_color)
  328. return mb.build()
  329. else:
  330. # Bottom and top 'ellipse' of the build volume
  331. scale_matrix = Matrix()
  332. if self._width != 0:
  333. # Scale circular meshes by aspect ratio if width != height
  334. aspect = self._depth / self._width
  335. scale_matrix.compose(scale = Vector(1, 1, aspect))
  336. mb = MeshBuilder()
  337. mb.addArc(max_w, Vector.Unit_Y, center = (0, min_h - z_fight_distance, 0), color = self._volume_outline_color)
  338. mb.addArc(max_w, Vector.Unit_Y, center = (0, max_h, 0), color = self._volume_outline_color)
  339. return mb.build().getTransformed(scale_matrix)
  340. def _buildOriginMesh(self, origin: Vector) -> MeshData:
  341. mb = MeshBuilder()
  342. mb.addCube(
  343. width=self._origin_line_length,
  344. height=self._origin_line_width,
  345. depth=self._origin_line_width,
  346. center=origin + Vector(self._origin_line_length / 2, 0, 0),
  347. color=self._x_axis_color
  348. )
  349. mb.addCube(
  350. width=self._origin_line_width,
  351. height=self._origin_line_length,
  352. depth=self._origin_line_width,
  353. center=origin + Vector(0, self._origin_line_length / 2, 0),
  354. color=self._y_axis_color
  355. )
  356. mb.addCube(
  357. width=self._origin_line_width,
  358. height=self._origin_line_width,
  359. depth=self._origin_line_length,
  360. center=origin - Vector(0, 0, self._origin_line_length / 2),
  361. color=self._z_axis_color
  362. )
  363. return mb.build()
  364. def _updateColors(self):
  365. theme = self._application.getTheme()
  366. if theme is None:
  367. return
  368. self._volume_outline_color = Color(*theme.getColor("volume_outline").getRgb())
  369. self._x_axis_color = Color(*theme.getColor("x_axis").getRgb())
  370. self._y_axis_color = Color(*theme.getColor("y_axis").getRgb())
  371. self._z_axis_color = Color(*theme.getColor("z_axis").getRgb())
  372. self._disallowed_area_color = Color(*theme.getColor("disallowed_area").getRgb())
  373. self._error_area_color = Color(*theme.getColor("error_area").getRgb())
  374. def _buildErrorMesh(self, min_w: float, max_w: float, min_h: float, max_h: float, min_d: float, max_d: float, disallowed_area_height: float) -> Optional[MeshData]:
  375. if not self._error_areas:
  376. return None
  377. mb = MeshBuilder()
  378. for error_area in self._error_areas:
  379. color = self._error_area_color
  380. points = error_area.getPoints()
  381. first = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height,
  382. self._clamp(points[0][1], min_d, max_d))
  383. previous_point = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height,
  384. self._clamp(points[0][1], min_d, max_d))
  385. for point in points:
  386. new_point = Vector(self._clamp(point[0], min_w, max_w), disallowed_area_height,
  387. self._clamp(point[1], min_d, max_d))
  388. mb.addFace(first, previous_point, new_point, color=color)
  389. previous_point = new_point
  390. return mb.build()
  391. def _buildDisallowedAreaMesh(self, min_w: float, max_w: float, min_h: float, max_h: float, min_d: float, max_d: float, disallowed_area_height: float) -> Optional[MeshData]:
  392. if not self._disallowed_areas:
  393. return None
  394. mb = MeshBuilder()
  395. color = self._disallowed_area_color
  396. for polygon in self._disallowed_areas:
  397. points = polygon.getPoints()
  398. if len(points) == 0:
  399. continue
  400. first = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height,
  401. self._clamp(points[0][1], min_d, max_d))
  402. previous_point = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height,
  403. self._clamp(points[0][1], min_d, max_d))
  404. for point in points:
  405. new_point = Vector(self._clamp(point[0], min_w, max_w), disallowed_area_height,
  406. self._clamp(point[1], min_d, max_d))
  407. mb.addFace(first, previous_point, new_point, color=color)
  408. previous_point = new_point
  409. # Find the largest disallowed area to exclude it from the maximum scale bounds.
  410. # This is a very nasty hack. This pretty much only works for UM machines.
  411. # This disallowed area_size needs a -lot- of rework at some point in the future: TODO
  412. if numpy.min(points[:,
  413. 1]) >= 0: # This filters out all areas that have points to the left of the centre. This is done to filter the skirt area.
  414. size = abs(numpy.max(points[:, 1]) - numpy.min(points[:, 1]))
  415. else:
  416. size = 0
  417. self._disallowed_area_size = max(size, self._disallowed_area_size)
  418. return mb.build()
  419. def _updateScaleFactor(self) -> None:
  420. if not self._global_container_stack:
  421. return
  422. scale_xy = 100.0 / max(100.0, self._global_container_stack.getProperty("material_shrinkage_percentage_xy", "value"))
  423. scale_z = 100.0 / max(100.0, self._global_container_stack.getProperty("material_shrinkage_percentage_z" , "value"))
  424. self._scale_vector = Vector(scale_xy, scale_xy, scale_z)
  425. def rebuild(self) -> None:
  426. """Recalculates the build volume & disallowed areas."""
  427. if not self._width or not self._height or not self._depth:
  428. return
  429. if not self._engine_ready:
  430. return
  431. if not self._global_container_stack:
  432. return
  433. if not self._volume_outline_color:
  434. self._updateColors()
  435. min_w = -self._width / 2
  436. max_w = self._width / 2
  437. min_h = 0.0
  438. max_h = self._height
  439. min_d = -self._depth / 2
  440. max_d = self._depth / 2
  441. z_fight_distance = 0.2 # Distance between buildplate and disallowed area meshes to prevent z-fighting
  442. self._grid_mesh = self._buildGridMesh(min_w, max_w, min_h, max_h, min_d, max_d, z_fight_distance)
  443. self.setMeshData(self._buildMesh(min_w, max_w, min_h, max_h, min_d, max_d, z_fight_distance))
  444. # Indication of the machine origin
  445. if self._global_container_stack.getProperty("machine_center_is_zero", "value"):
  446. origin = (Vector(min_w, min_h, min_d) + Vector(max_w, min_h, max_d)) / 2
  447. else:
  448. origin = Vector(min_w, min_h, max_d)
  449. self._origin_mesh = self._buildOriginMesh(origin)
  450. disallowed_area_height = 0.1
  451. self._disallowed_area_size = 0.
  452. self._disallowed_area_mesh = self._buildDisallowedAreaMesh(min_w, max_w, min_h, max_h, min_d, max_d, disallowed_area_height)
  453. self._error_mesh = self._buildErrorMesh(min_w, max_w, min_h, max_h, min_d, max_d, disallowed_area_height)
  454. self._updateScaleFactor()
  455. self._volume_aabb = AxisAlignedBox(
  456. minimum = Vector(min_w, min_h - 1.0, min_d).scale(self._scale_vector),
  457. maximum = Vector(max_w, max_h - self._raft_thickness - self._extra_z_clearance, max_d).scale(self._scale_vector)
  458. )
  459. bed_adhesion_size = self.getEdgeDisallowedSize()
  460. # As this works better for UM machines, we only add the disallowed_area_size for the z direction.
  461. # This is probably wrong in all other cases. TODO!
  462. # The +1 and -1 is added as there is always a bit of extra room required to work properly.
  463. scale_to_max_bounds = AxisAlignedBox(
  464. minimum = Vector(min_w + bed_adhesion_size + 1, min_h, min_d + self._disallowed_area_size - bed_adhesion_size + 1).scale(self._scale_vector),
  465. maximum = Vector(max_w - bed_adhesion_size - 1, max_h - self._raft_thickness - self._extra_z_clearance, max_d - self._disallowed_area_size + bed_adhesion_size - 1).scale(self._scale_vector)
  466. )
  467. self._application.getController().getScene()._maximum_bounds = scale_to_max_bounds # type: ignore
  468. self.updateNodeBoundaryCheck()
  469. def getBoundingBox(self) -> Optional[AxisAlignedBox]:
  470. return self._volume_aabb
  471. def getRaftThickness(self) -> float:
  472. return self._raft_thickness
  473. def _updateRaftThickness(self) -> None:
  474. if not self._global_container_stack:
  475. return
  476. old_raft_thickness = self._raft_thickness
  477. if self._global_container_stack.extruderList:
  478. # This might be called before the extruder stacks have initialised, in which case getting the adhesion_type fails
  479. self._adhesion_type = self._global_container_stack.getProperty("adhesion_type", "value")
  480. self._raft_thickness = 0.0
  481. if self._adhesion_type == "raft":
  482. self._raft_thickness = (
  483. self._global_container_stack.getProperty("raft_base_thickness", "value") +
  484. self._global_container_stack.getProperty("raft_interface_layers", "value") *
  485. self._global_container_stack.getProperty("raft_interface_thickness", "value") +
  486. self._global_container_stack.getProperty("raft_surface_layers", "value") *
  487. self._global_container_stack.getProperty("raft_surface_thickness", "value") +
  488. self._global_container_stack.getProperty("raft_airgap", "value") -
  489. self._global_container_stack.getProperty("layer_0_z_overlap", "value"))
  490. # Rounding errors do not matter, we check if raft_thickness has changed at all
  491. if old_raft_thickness != self._raft_thickness:
  492. self.setPosition(Vector(0, -self._raft_thickness, 0), SceneNode.TransformSpace.World)
  493. self.raftThicknessChanged.emit()
  494. def _calculateExtraZClearance(self, extruders: List["ContainerStack"]) -> float:
  495. if not self._global_container_stack:
  496. return 0
  497. extra_z = 0.0
  498. for extruder in extruders:
  499. if extruder.getProperty("retraction_hop_enabled", "value"):
  500. retraction_hop = extruder.getProperty("retraction_hop", "value")
  501. if extra_z is None or retraction_hop > extra_z:
  502. extra_z = retraction_hop
  503. return extra_z
  504. def _onStackChanged(self):
  505. self._stack_change_timer.start()
  506. def _onStackChangeTimerFinished(self) -> None:
  507. """Update the build volume visualization"""
  508. if self._global_container_stack:
  509. self._global_container_stack.propertyChanged.disconnect(self._onSettingPropertyChanged)
  510. extruders = ExtruderManager.getInstance().getActiveExtruderStacks()
  511. for extruder in extruders:
  512. extruder.propertyChanged.disconnect(self._onSettingPropertyChanged)
  513. self._global_container_stack = self._application.getGlobalContainerStack()
  514. if self._global_container_stack:
  515. self._global_container_stack.propertyChanged.connect(self._onSettingPropertyChanged)
  516. extruders = ExtruderManager.getInstance().getActiveExtruderStacks()
  517. for extruder in extruders:
  518. extruder.propertyChanged.connect(self._onSettingPropertyChanged)
  519. self._width = self._global_container_stack.getProperty("machine_width", "value") * self._scale_vector.x
  520. machine_height = self._global_container_stack.getProperty("machine_height", "value")
  521. if self._global_container_stack.getProperty("print_sequence", "value") == "one_at_a_time" and len(self._scene_objects) > 1:
  522. self._height = min(self._global_container_stack.getProperty("gantry_height", "value") * self._scale_vector.z, machine_height)
  523. if self._height < (machine_height * self._scale_vector.z):
  524. self._build_volume_message.show()
  525. else:
  526. self._build_volume_message.hide()
  527. else:
  528. self._height = self._global_container_stack.getProperty("machine_height", "value")
  529. self._build_volume_message.hide()
  530. self._depth = self._global_container_stack.getProperty("machine_depth", "value") * self._scale_vector.y
  531. self._shape = self._global_container_stack.getProperty("machine_shape", "value")
  532. self._updateDisallowedAreas()
  533. self._updateRaftThickness()
  534. self._extra_z_clearance = self._calculateExtraZClearance(ExtruderManager.getInstance().getUsedExtruderStacks())
  535. if self._engine_ready:
  536. self.rebuild()
  537. camera = Application.getInstance().getController().getCameraTool()
  538. if camera:
  539. diagonal = self.getDiagonalSize()
  540. if diagonal > 1:
  541. # You can zoom out up to 5 times the diagonal. This gives some space around the volume.
  542. camera.setZoomRange(min = 0.1, max = diagonal * 5) # type: ignore
  543. def _onEngineCreated(self) -> None:
  544. self._engine_ready = True
  545. self.rebuild()
  546. def _onSettingChangeTimerFinished(self) -> None:
  547. if not self._global_container_stack:
  548. return
  549. rebuild_me = False
  550. update_disallowed_areas = False
  551. update_raft_thickness = False
  552. update_extra_z_clearance = True
  553. for setting_key in self._changed_settings_since_last_rebuild:
  554. if setting_key == "print_sequence":
  555. machine_height = self._global_container_stack.getProperty("machine_height", "value")
  556. if self._application.getGlobalContainerStack().getProperty("print_sequence", "value") == "one_at_a_time" and len(self._scene_objects) > 1:
  557. self._height = min(self._global_container_stack.getProperty("gantry_height", "value") * self._scale_vector.z, machine_height)
  558. if self._height < (machine_height * self._scale_vector.z):
  559. self._build_volume_message.show()
  560. else:
  561. self._build_volume_message.hide()
  562. else:
  563. self._height = self._global_container_stack.getProperty("machine_height", "value") * self._scale_vector.z
  564. self._build_volume_message.hide()
  565. update_disallowed_areas = True
  566. # sometimes the machine size or shape settings are adjusted on the active machine, we should reflect this
  567. if setting_key in self._machine_settings or setting_key in self._material_size_settings:
  568. self._updateMachineSizeProperties()
  569. update_extra_z_clearance = True
  570. update_disallowed_areas = True
  571. if setting_key in self._disallowed_area_settings:
  572. update_disallowed_areas = True
  573. if setting_key in self._raft_settings:
  574. update_raft_thickness = True
  575. if setting_key in self._extra_z_settings:
  576. update_extra_z_clearance = True
  577. if setting_key in self._limit_to_extruder_settings:
  578. update_disallowed_areas = True
  579. rebuild_me = update_extra_z_clearance or update_disallowed_areas or update_raft_thickness
  580. # We only want to update all of them once.
  581. if update_disallowed_areas:
  582. self._updateDisallowedAreas()
  583. if update_raft_thickness:
  584. self._updateRaftThickness()
  585. if update_extra_z_clearance:
  586. self._extra_z_clearance = self._calculateExtraZClearance(ExtruderManager.getInstance().getUsedExtruderStacks())
  587. if rebuild_me:
  588. self.rebuild()
  589. # We just did a rebuild, reset the list.
  590. self._changed_settings_since_last_rebuild = []
  591. def _onSettingPropertyChanged(self, setting_key: str, property_name: str) -> None:
  592. if property_name != "value":
  593. return
  594. if setting_key not in self._changed_settings_since_last_rebuild:
  595. self._changed_settings_since_last_rebuild.append(setting_key)
  596. self._setting_change_timer.start()
  597. def hasErrors(self) -> bool:
  598. return self._has_errors
  599. def _updateMachineSizeProperties(self) -> None:
  600. if not self._global_container_stack:
  601. return
  602. self._updateScaleFactor()
  603. self._height = self._global_container_stack.getProperty("machine_height", "value") * self._scale_vector.z
  604. self._width = self._global_container_stack.getProperty("machine_width", "value") * self._scale_vector.x
  605. self._depth = self._global_container_stack.getProperty("machine_depth", "value") * self._scale_vector.y
  606. self._shape = self._global_container_stack.getProperty("machine_shape", "value")
  607. def _updateDisallowedAreasAndRebuild(self):
  608. """Calls :py:meth:`cura.BuildVolume._updateDisallowedAreas` and makes sure the changes appear in the scene.
  609. This is required for a signal to trigger the update in one go. The
  610. :py:meth:`cura.BuildVolume._updateDisallowedAreas` method itself shouldn't call
  611. :py:meth:`cura.BuildVolume.rebuild`, since there may be other changes before it needs to be rebuilt,
  612. which would hit performance.
  613. """
  614. self._updateDisallowedAreas()
  615. self._updateRaftThickness()
  616. self._extra_z_clearance = self._calculateExtraZClearance(ExtruderManager.getInstance().getUsedExtruderStacks())
  617. self.rebuild()
  618. def _scaleAreas(self, result_areas: List[Polygon]) -> None:
  619. if self._global_container_stack is None:
  620. return
  621. for i, polygon in enumerate(result_areas):
  622. result_areas[i] = polygon.scale(
  623. 100.0 / max(100.0, self._global_container_stack.getProperty("material_shrinkage_percentage_xy", "value"))
  624. )
  625. def _updateDisallowedAreas(self) -> None:
  626. if not self._global_container_stack:
  627. return
  628. self._error_areas = []
  629. used_extruders = ExtruderManager.getInstance().getUsedExtruderStacks()
  630. self._edge_disallowed_size = None # Force a recalculation
  631. disallowed_border_size = self.getEdgeDisallowedSize()
  632. result_areas = self._computeDisallowedAreasStatic(disallowed_border_size, used_extruders) # Normal machine disallowed areas can always be added.
  633. prime_areas = self._computeDisallowedAreasPrimeBlob(disallowed_border_size, used_extruders)
  634. result_areas_no_brim = self._computeDisallowedAreasStatic(0, used_extruders) # Where the priming is not allowed to happen. This is not added to the result, just for collision checking.
  635. # Check if prime positions intersect with disallowed areas.
  636. for extruder in used_extruders:
  637. extruder_id = extruder.getId()
  638. result_areas[extruder_id].extend(prime_areas[extruder_id])
  639. result_areas_no_brim[extruder_id].extend(prime_areas[extruder_id])
  640. nozzle_disallowed_areas = extruder.getProperty("nozzle_disallowed_areas", "value")
  641. for area in nozzle_disallowed_areas:
  642. polygon = Polygon(numpy.array(area, numpy.float32))
  643. polygon_disallowed_border = polygon.getMinkowskiHull(Polygon.approximatedCircle(disallowed_border_size))
  644. result_areas[extruder_id].append(polygon_disallowed_border) # Don't perform the offset on these.
  645. result_areas_no_brim[extruder_id].append(polygon) # No brim
  646. # Add prime tower location as disallowed area.
  647. if len([x for x in used_extruders if x.isEnabled]) > 1: # No prime tower if only one extruder is enabled
  648. prime_tower_collision = False
  649. prime_tower_areas = self._computeDisallowedAreasPrinted(used_extruders)
  650. for extruder_id in prime_tower_areas:
  651. for area_index, prime_tower_area in enumerate(prime_tower_areas[extruder_id]):
  652. for area in result_areas[extruder_id]:
  653. if prime_tower_area.intersectsPolygon(area) is not None:
  654. prime_tower_collision = True
  655. break
  656. if prime_tower_collision: # Already found a collision.
  657. break
  658. if self._global_container_stack.getProperty("prime_tower_brim_enable", "value") and self._global_container_stack.getProperty("adhesion_type", "value") != "raft":
  659. brim_size = self._calculateBedAdhesionSize(used_extruders, "brim")
  660. # Use 2x the brim size, since we need 1x brim size distance due to the object brim and another
  661. # times the brim due to the brim of the prime tower
  662. prime_tower_areas[extruder_id][area_index] = prime_tower_area.getMinkowskiHull(Polygon.approximatedCircle(2 * brim_size, num_segments = 24))
  663. if not prime_tower_collision:
  664. result_areas[extruder_id].extend(prime_tower_areas[extruder_id])
  665. result_areas_no_brim[extruder_id].extend(prime_tower_areas[extruder_id])
  666. else:
  667. self._error_areas.extend(prime_tower_areas[extruder_id])
  668. self._has_errors = len(self._error_areas) > 0
  669. self._disallowed_areas = []
  670. for extruder_id in result_areas:
  671. self._scaleAreas(result_areas[extruder_id])
  672. self._disallowed_areas.extend(result_areas[extruder_id])
  673. self._disallowed_areas_no_brim = []
  674. for extruder_id in result_areas_no_brim:
  675. self._scaleAreas(result_areas_no_brim[extruder_id])
  676. self._disallowed_areas_no_brim.extend(result_areas_no_brim[extruder_id])
  677. def _computeDisallowedAreasPrinted(self, used_extruders):
  678. """Computes the disallowed areas for objects that are printed with print features.
  679. This means that the brim, travel avoidance and such will be applied to these features.
  680. :return: A dictionary with for each used extruder ID the disallowed areas where that extruder may not print.
  681. """
  682. result = {}
  683. skirt_brim_extruder: ExtruderStack = None
  684. for extruder in used_extruders:
  685. if int(extruder.getProperty("extruder_nr", "value")) == int(self._global_container_stack.getProperty("skirt_brim_extruder_nr", "value")):
  686. skirt_brim_extruder = extruder
  687. result[extruder.getId()] = []
  688. # Currently, the only normally printed object is the prime tower.
  689. if self._global_container_stack.getProperty("prime_tower_enable", "value"):
  690. prime_tower_size = self._global_container_stack.getProperty("prime_tower_size", "value")
  691. machine_width = self._global_container_stack.getProperty("machine_width", "value")
  692. machine_depth = self._global_container_stack.getProperty("machine_depth", "value")
  693. prime_tower_x = self._global_container_stack.getProperty("prime_tower_position_x", "value")
  694. prime_tower_y = - self._global_container_stack.getProperty("prime_tower_position_y", "value")
  695. if not self._global_container_stack.getProperty("machine_center_is_zero", "value"):
  696. prime_tower_x = prime_tower_x - machine_width / 2 #Offset by half machine_width and _depth to put the origin in the front-left.
  697. prime_tower_y = prime_tower_y + machine_depth / 2
  698. if skirt_brim_extruder is not None and self._global_container_stack.getProperty("prime_tower_brim_enable", "value") and self._global_container_stack.getProperty("adhesion_type", "value") != "raft":
  699. brim_size = (
  700. skirt_brim_extruder.getProperty("brim_line_count", "value") *
  701. skirt_brim_extruder.getProperty("skirt_brim_line_width", "value") / 100.0 *
  702. skirt_brim_extruder.getProperty("initial_layer_line_width_factor", "value")
  703. )
  704. prime_tower_x -= brim_size
  705. prime_tower_y += brim_size
  706. radius = prime_tower_size / 2
  707. prime_tower_area = Polygon.approximatedCircle(radius, num_segments = 24)
  708. prime_tower_area = prime_tower_area.translate(prime_tower_x - radius, prime_tower_y - radius)
  709. prime_tower_area = prime_tower_area.getMinkowskiHull(Polygon.approximatedCircle(0))
  710. for extruder in used_extruders:
  711. result[extruder.getId()].append(prime_tower_area) #The prime tower location is the same for each extruder, regardless of offset.
  712. return result
  713. def _computeDisallowedAreasPrimeBlob(self, border_size: float, used_extruders: List["ExtruderStack"]) -> Dict[str, List[Polygon]]:
  714. """Computes the disallowed areas for the prime blobs.
  715. These are special because they are not subject to things like brim or travel avoidance. They do get a dilute
  716. with the border size though because they may not intersect with brims and such of other objects.
  717. :param border_size: The size with which to offset the disallowed areas due to skirt, brim, travel avoid distance
  718. , etc.
  719. :param used_extruders: The extruder stacks to generate disallowed areas for.
  720. :return: A dictionary with for each used extruder ID the prime areas.
  721. """
  722. result = {} # type: Dict[str, List[Polygon]]
  723. if not self._global_container_stack:
  724. return result
  725. machine_width = self._global_container_stack.getProperty("machine_width", "value")
  726. machine_depth = self._global_container_stack.getProperty("machine_depth", "value")
  727. for extruder in used_extruders:
  728. prime_blob_enabled = extruder.getProperty("prime_blob_enable", "value")
  729. prime_x = extruder.getProperty("extruder_prime_pos_x", "value")
  730. prime_y = -extruder.getProperty("extruder_prime_pos_y", "value")
  731. # Ignore extruder prime position if it is not set or if blob is disabled
  732. if (prime_x == 0 and prime_y == 0) or not prime_blob_enabled:
  733. result[extruder.getId()] = []
  734. continue
  735. if not self._global_container_stack.getProperty("machine_center_is_zero", "value"):
  736. prime_x = prime_x - machine_width / 2 # Offset by half machine_width and _depth to put the origin in the front-left.
  737. prime_y = prime_y + machine_depth / 2
  738. prime_polygon = Polygon.approximatedCircle(PRIME_CLEARANCE)
  739. prime_polygon = prime_polygon.getMinkowskiHull(Polygon.approximatedCircle(border_size))
  740. prime_polygon = prime_polygon.translate(prime_x, prime_y)
  741. result[extruder.getId()] = [prime_polygon]
  742. return result
  743. def _computeDisallowedAreasStatic(self, border_size:float, used_extruders: List["ExtruderStack"]) -> Dict[str, List[Polygon]]:
  744. """Computes the disallowed areas that are statically placed in the machine.
  745. It computes different disallowed areas depending on the offset of the extruder. The resulting dictionary will
  746. therefore have an entry for each extruder that is used.
  747. :param border_size: The size with which to offset the disallowed areas due to skirt, brim, travel avoid distance
  748. , etc.
  749. :param used_extruders: The extruder stacks to generate disallowed areas for.
  750. :return: A dictionary with for each used extruder ID the disallowed areas where that extruder may not print.
  751. """
  752. # Convert disallowed areas to polygons and dilate them.
  753. machine_disallowed_polygons = []
  754. if self._global_container_stack is None:
  755. return {}
  756. for area in self._global_container_stack.getProperty("machine_disallowed_areas", "value"):
  757. if len(area) == 0:
  758. continue # Numpy doesn't deal well with 0-length arrays, since it can't determine the dimensionality of them.
  759. polygon = Polygon(numpy.array(area, numpy.float32))
  760. polygon = polygon.getMinkowskiHull(Polygon.approximatedCircle(border_size))
  761. machine_disallowed_polygons.append(polygon)
  762. # For certain machines we don't need to compute disallowed areas for each nozzle.
  763. # So we check here and only do the nozzle offsetting if needed.
  764. nozzle_offsetting_for_disallowed_areas = self._global_container_stack.getMetaDataEntry(
  765. "nozzle_offsetting_for_disallowed_areas", True)
  766. result = {} # type: Dict[str, List[Polygon]]
  767. for extruder in used_extruders:
  768. extruder_id = extruder.getId()
  769. offset_x = extruder.getProperty("machine_nozzle_offset_x", "value")
  770. if offset_x is None:
  771. offset_x = 0
  772. offset_y = extruder.getProperty("machine_nozzle_offset_y", "value")
  773. if offset_y is None:
  774. offset_y = 0
  775. offset_y = -offset_y # Y direction of g-code is the inverse of Y direction of Cura's scene space.
  776. result[extruder_id] = []
  777. for polygon in machine_disallowed_polygons:
  778. result[extruder_id].append(polygon.translate(offset_x, offset_y)) # Compensate for the nozzle offset of this extruder.
  779. # Add the border around the edge of the build volume.
  780. left_unreachable_border = 0
  781. right_unreachable_border = 0
  782. top_unreachable_border = 0
  783. bottom_unreachable_border = 0
  784. # Only do nozzle offsetting if needed
  785. if nozzle_offsetting_for_disallowed_areas:
  786. # The build volume is defined as the union of the area that all extruders can reach, so we need to know
  787. # the relative offset to all extruders.
  788. for other_extruder in ExtruderManager.getInstance().getActiveExtruderStacks():
  789. other_offset_x = other_extruder.getProperty("machine_nozzle_offset_x", "value")
  790. if other_offset_x is None:
  791. other_offset_x = 0
  792. other_offset_y = other_extruder.getProperty("machine_nozzle_offset_y", "value")
  793. if other_offset_y is None:
  794. other_offset_y = 0
  795. other_offset_y = -other_offset_y
  796. left_unreachable_border = min(left_unreachable_border, other_offset_x - offset_x)
  797. right_unreachable_border = max(right_unreachable_border, other_offset_x - offset_x)
  798. top_unreachable_border = min(top_unreachable_border, other_offset_y - offset_y)
  799. bottom_unreachable_border = max(bottom_unreachable_border, other_offset_y - offset_y)
  800. half_machine_width = self._global_container_stack.getProperty("machine_width", "value") / 2
  801. half_machine_depth = self._global_container_stack.getProperty("machine_depth", "value") / 2
  802. if self._shape != "elliptic":
  803. if border_size - left_unreachable_border > 0:
  804. result[extruder_id].append(Polygon(numpy.array([
  805. [-half_machine_width, -half_machine_depth],
  806. [-half_machine_width, half_machine_depth],
  807. [-half_machine_width + border_size - left_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border],
  808. [-half_machine_width + border_size - left_unreachable_border, -half_machine_depth + border_size - top_unreachable_border]
  809. ], numpy.float32)))
  810. if border_size + right_unreachable_border > 0:
  811. result[extruder_id].append(Polygon(numpy.array([
  812. [half_machine_width, half_machine_depth],
  813. [half_machine_width, -half_machine_depth],
  814. [half_machine_width - border_size - right_unreachable_border, -half_machine_depth + border_size - top_unreachable_border],
  815. [half_machine_width - border_size - right_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border]
  816. ], numpy.float32)))
  817. if border_size + bottom_unreachable_border > 0:
  818. result[extruder_id].append(Polygon(numpy.array([
  819. [-half_machine_width, half_machine_depth],
  820. [half_machine_width, half_machine_depth],
  821. [half_machine_width - border_size - right_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border],
  822. [-half_machine_width + border_size - left_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border]
  823. ], numpy.float32)))
  824. if border_size - top_unreachable_border > 0:
  825. result[extruder_id].append(Polygon(numpy.array([
  826. [half_machine_width, -half_machine_depth],
  827. [-half_machine_width, -half_machine_depth],
  828. [-half_machine_width + border_size - left_unreachable_border, -half_machine_depth + border_size - top_unreachable_border],
  829. [half_machine_width - border_size - right_unreachable_border, -half_machine_depth + border_size - top_unreachable_border]
  830. ], numpy.float32)))
  831. else:
  832. sections = 32
  833. arc_vertex = [0, half_machine_depth - border_size]
  834. for i in range(0, sections):
  835. quadrant = math.floor(4 * i / sections)
  836. vertices = []
  837. if quadrant == 0:
  838. vertices.append([-half_machine_width, half_machine_depth])
  839. elif quadrant == 1:
  840. vertices.append([-half_machine_width, -half_machine_depth])
  841. elif quadrant == 2:
  842. vertices.append([half_machine_width, -half_machine_depth])
  843. elif quadrant == 3:
  844. vertices.append([half_machine_width, half_machine_depth])
  845. vertices.append(arc_vertex)
  846. angle = 2 * math.pi * (i + 1) / sections
  847. arc_vertex = [-(half_machine_width - border_size) * math.sin(angle), (half_machine_depth - border_size) * math.cos(angle)]
  848. vertices.append(arc_vertex)
  849. result[extruder_id].append(Polygon(numpy.array(vertices, numpy.float32)))
  850. if border_size > 0:
  851. result[extruder_id].append(Polygon(numpy.array([
  852. [-half_machine_width, -half_machine_depth],
  853. [-half_machine_width, half_machine_depth],
  854. [-half_machine_width + border_size, 0]
  855. ], numpy.float32)))
  856. result[extruder_id].append(Polygon(numpy.array([
  857. [-half_machine_width, half_machine_depth],
  858. [ half_machine_width, half_machine_depth],
  859. [ 0, half_machine_depth - border_size]
  860. ], numpy.float32)))
  861. result[extruder_id].append(Polygon(numpy.array([
  862. [ half_machine_width, half_machine_depth],
  863. [ half_machine_width, -half_machine_depth],
  864. [ half_machine_width - border_size, 0]
  865. ], numpy.float32)))
  866. result[extruder_id].append(Polygon(numpy.array([
  867. [ half_machine_width, -half_machine_depth],
  868. [-half_machine_width, -half_machine_depth],
  869. [ 0, -half_machine_depth + border_size]
  870. ], numpy.float32)))
  871. return result
  872. def _getSettingFromAllExtruders(self, setting_key: str) -> List[Any]:
  873. """Private convenience function to get a setting from every extruder.
  874. For single extrusion machines, this gets the setting from the global stack.
  875. :return: A sequence of setting values, one for each extruder.
  876. """
  877. all_values = ExtruderManager.getInstance().getAllExtruderSettings(setting_key, "value")
  878. all_types = ExtruderManager.getInstance().getAllExtruderSettings(setting_key, "type")
  879. for i, (setting_value, setting_type) in enumerate(zip(all_values, all_types)):
  880. if not setting_value and setting_type in ["int", "float"]:
  881. all_values[i] = 0
  882. return all_values
  883. def _calculateBedAdhesionSize(self, used_extruders, adhesion_override = None):
  884. """Get the bed adhesion size for the global container stack and used extruders
  885. :param adhesion_override: override adhesion type.
  886. Use None to use the global stack default, "none" for no adhesion, "brim" for brim etc.
  887. """
  888. if self._global_container_stack is None:
  889. return None
  890. container_stack = self._global_container_stack
  891. adhesion_type = adhesion_override
  892. if adhesion_type is None:
  893. adhesion_type = container_stack.getProperty("adhesion_type", "value")
  894. # Skirt_brim_line_width is a bit of an odd one out. The primary bit of the skirt/brim is printed
  895. # with the adhesion extruder, but it also prints one extra line by all other extruders. As such, the
  896. # setting does *not* have a limit_to_extruder setting (which means that we can't ask the global extruder what
  897. # the value is.
  898. skirt_brim_extruder_nr = self._global_container_stack.getProperty("skirt_brim_extruder_nr", "value")
  899. try:
  900. skirt_brim_stack = self._global_container_stack.extruderList[int(skirt_brim_extruder_nr)]
  901. except IndexError:
  902. Logger.warning(f"Couldn't find extruder with index '{skirt_brim_extruder_nr}', defaulting to 0 instead.")
  903. skirt_brim_stack = self._global_container_stack.extruderList[0]
  904. skirt_brim_line_width = skirt_brim_stack.getProperty("skirt_brim_line_width", "value")
  905. initial_layer_line_width_factor = skirt_brim_stack.getProperty("initial_layer_line_width_factor", "value")
  906. # Use brim width if brim is enabled OR the prime tower has a brim.
  907. if adhesion_type == "brim":
  908. brim_line_count = skirt_brim_stack.getProperty("brim_line_count", "value")
  909. brim_gap = skirt_brim_stack.getProperty("brim_gap", "value")
  910. bed_adhesion_size = brim_gap + skirt_brim_line_width * brim_line_count * initial_layer_line_width_factor / 100.0
  911. for extruder_stack in used_extruders:
  912. bed_adhesion_size += extruder_stack.getProperty("skirt_brim_line_width", "value") * extruder_stack.getProperty("initial_layer_line_width_factor", "value") / 100.0
  913. # We don't create an additional line for the extruder we're printing the brim with.
  914. bed_adhesion_size -= skirt_brim_line_width * initial_layer_line_width_factor / 100.0
  915. elif adhesion_type == "skirt":
  916. skirt_distance = skirt_brim_stack.getProperty("skirt_gap", "value")
  917. skirt_line_count = skirt_brim_stack.getProperty("skirt_line_count", "value")
  918. bed_adhesion_size = skirt_distance + (
  919. skirt_brim_line_width * skirt_line_count) * initial_layer_line_width_factor / 100.0
  920. for extruder_stack in used_extruders:
  921. bed_adhesion_size += extruder_stack.getProperty("skirt_brim_line_width", "value") * extruder_stack.getProperty("initial_layer_line_width_factor", "value") / 100.0
  922. # We don't create an additional line for the extruder we're printing the skirt with.
  923. bed_adhesion_size -= skirt_brim_line_width * initial_layer_line_width_factor / 100.0
  924. elif adhesion_type == "raft":
  925. bed_adhesion_size = self._global_container_stack.getProperty("raft_margin", "value") # Should refer to the raft extruder if set.
  926. elif adhesion_type == "none":
  927. bed_adhesion_size = 0
  928. else:
  929. raise Exception("Unknown bed adhesion type. Did you forget to update the build volume calculations for your new bed adhesion type?")
  930. max_length_available = 0.5 * min(
  931. self._global_container_stack.getProperty("machine_width", "value"),
  932. self._global_container_stack.getProperty("machine_depth", "value")
  933. )
  934. bed_adhesion_size = min(bed_adhesion_size, max_length_available)
  935. return bed_adhesion_size
  936. def _calculateFarthestShieldDistance(self, container_stack):
  937. farthest_shield_distance = 0
  938. if container_stack.getProperty("draft_shield_enabled", "value"):
  939. farthest_shield_distance = max(farthest_shield_distance, container_stack.getProperty("draft_shield_dist", "value"))
  940. if container_stack.getProperty("ooze_shield_enabled", "value"):
  941. farthest_shield_distance = max(farthest_shield_distance,container_stack.getProperty("ooze_shield_dist", "value"))
  942. return farthest_shield_distance
  943. def _calculateSupportExpansion(self, container_stack):
  944. support_expansion = 0
  945. support_enabled = self._global_container_stack.getProperty("support_enable", "value")
  946. support_offset = self._global_container_stack.getProperty("support_offset", "value")
  947. if support_enabled and support_offset:
  948. support_expansion += support_offset
  949. return support_expansion
  950. def _calculateMoveFromWallRadius(self, used_extruders):
  951. move_from_wall_radius = 0 # Moves that start from outer wall.
  952. for stack in used_extruders:
  953. if stack.getProperty("travel_avoid_other_parts", "value"):
  954. move_from_wall_radius = max(move_from_wall_radius, stack.getProperty("travel_avoid_distance", "value"))
  955. infill_wipe_distance = stack.getProperty("infill_wipe_dist", "value")
  956. num_walls = stack.getProperty("wall_line_count", "value")
  957. if num_walls >= 1: # Infill wipes start from the infill, so subtract the total wall thickness from this.
  958. infill_wipe_distance -= stack.getProperty("wall_line_width_0", "value")
  959. if num_walls >= 2:
  960. infill_wipe_distance -= stack.getProperty("wall_line_width_x", "value") * (num_walls - 1)
  961. move_from_wall_radius = max(move_from_wall_radius, infill_wipe_distance)
  962. return move_from_wall_radius
  963. def getEdgeDisallowedSize(self):
  964. """Calculate the disallowed radius around the edge.
  965. This disallowed radius is to allow for space around the models that is not part of the collision radius,
  966. such as bed adhesion (skirt/brim/raft) and travel avoid distance.
  967. """
  968. if not self._global_container_stack or not self._global_container_stack.extruderList:
  969. return 0
  970. if self._edge_disallowed_size is not None:
  971. return self._edge_disallowed_size
  972. container_stack = self._global_container_stack
  973. used_extruders = ExtruderManager.getInstance().getUsedExtruderStacks()
  974. # If we are printing one at a time, we need to add the bed adhesion size to the disallowed areas of the objects
  975. if container_stack.getProperty("print_sequence", "value") == "one_at_a_time":
  976. return 0.1
  977. bed_adhesion_size = self._calculateBedAdhesionSize(used_extruders)
  978. support_expansion = self._calculateSupportExpansion(self._global_container_stack)
  979. farthest_shield_distance = self._calculateFarthestShieldDistance(self._global_container_stack)
  980. move_from_wall_radius = self._calculateMoveFromWallRadius(used_extruders)
  981. # Now combine our different pieces of data to get the final border size.
  982. # Support expansion is added to the bed adhesion, since the bed adhesion goes around support.
  983. # Support expansion is added to farthest shield distance, since the shields go around support.
  984. self._edge_disallowed_size = max(move_from_wall_radius, support_expansion + farthest_shield_distance, support_expansion + bed_adhesion_size)
  985. return self._edge_disallowed_size
  986. def _clamp(self, value, min_value, max_value):
  987. return max(min(value, max_value), min_value)
  988. _machine_settings = ["machine_width", "machine_depth", "machine_height", "machine_shape", "machine_center_is_zero"]
  989. _skirt_settings = ["adhesion_type", "skirt_gap", "skirt_line_count", "skirt_brim_line_width", "brim_gap", "brim_width", "brim_line_count", "raft_margin", "draft_shield_enabled", "draft_shield_dist", "initial_layer_line_width_factor"]
  990. _raft_settings = ["adhesion_type", "raft_base_thickness", "raft_interface_layers", "raft_interface_thickness", "raft_surface_layers", "raft_surface_thickness", "raft_airgap", "layer_0_z_overlap"]
  991. _extra_z_settings = ["retraction_hop_enabled", "retraction_hop"]
  992. _prime_settings = ["extruder_prime_pos_x", "extruder_prime_pos_y", "prime_blob_enable"]
  993. _tower_settings = ["prime_tower_enable", "prime_tower_size", "prime_tower_position_x", "prime_tower_position_y", "prime_tower_brim_enable"]
  994. _ooze_shield_settings = ["ooze_shield_enabled", "ooze_shield_dist"]
  995. _distance_settings = ["infill_wipe_dist", "travel_avoid_distance", "support_offset", "support_enable", "travel_avoid_other_parts", "travel_avoid_supports", "wall_line_count", "wall_line_width_0", "wall_line_width_x"]
  996. _extruder_settings = ["support_enable", "support_bottom_enable", "support_roof_enable", "support_infill_extruder_nr", "support_extruder_nr_layer_0", "support_bottom_extruder_nr", "support_roof_extruder_nr", "brim_line_count", "skirt_brim_extruder_nr", "raft_base_extruder_nr", "raft_interface_extruder_nr", "raft_surface_extruder_nr", "adhesion_type"] #Settings that can affect which extruders are used.
  997. _limit_to_extruder_settings = ["wall_extruder_nr", "wall_0_extruder_nr", "wall_x_extruder_nr", "top_bottom_extruder_nr", "infill_extruder_nr", "support_infill_extruder_nr", "support_extruder_nr_layer_0", "support_bottom_extruder_nr", "support_roof_extruder_nr", "skirt_brim_extruder_nr", "raft_base_extruder_nr", "raft_interface_extruder_nr", "raft_surface_extruder_nr"]
  998. _material_size_settings = ["material_shrinkage_percentage", "material_shrinkage_percentage_xy", "material_shrinkage_percentage_z"]
  999. _disallowed_area_settings = _skirt_settings + _prime_settings + _tower_settings + _ooze_shield_settings + _distance_settings + _extruder_settings + _material_size_settings