BuildVolume.py 62 KB

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