BuildVolume.py 61 KB

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