BuildVolume.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. # Copyright (c) 2016 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from cura.Settings.ExtruderManager import ExtruderManager
  4. from UM.Settings.ContainerRegistry import ContainerRegistry
  5. from UM.i18n import i18nCatalog
  6. from UM.Scene.Platform import Platform
  7. from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
  8. from UM.Scene.SceneNode import SceneNode
  9. from UM.Application import Application
  10. from UM.Resources import Resources
  11. from UM.Mesh.MeshBuilder import MeshBuilder
  12. from UM.Math.Vector import Vector
  13. from UM.Math.Matrix import Matrix
  14. from UM.Math.Color import Color
  15. from UM.Math.AxisAlignedBox import AxisAlignedBox
  16. from UM.Math.Polygon import Polygon
  17. from UM.Message import Message
  18. from UM.Signal import Signal
  19. from PyQt5.QtCore import QTimer
  20. from UM.View.RenderBatch import RenderBatch
  21. from UM.View.GL.OpenGL import OpenGL
  22. catalog = i18nCatalog("cura")
  23. import numpy
  24. import math
  25. # Setting for clearance around the prime
  26. PRIME_CLEARANCE = 6.5
  27. ## Build volume is a special kind of node that is responsible for rendering the printable area & disallowed areas.
  28. class BuildVolume(SceneNode):
  29. raftThicknessChanged = Signal()
  30. def __init__(self, parent = None):
  31. super().__init__(parent)
  32. self._volume_outline_color = None
  33. self._x_axis_color = None
  34. self._y_axis_color = None
  35. self._z_axis_color = None
  36. self._disallowed_area_color = None
  37. self._error_area_color = None
  38. self._width = 0
  39. self._height = 0
  40. self._depth = 0
  41. self._shape = ""
  42. self._shader = None
  43. self._origin_mesh = None
  44. self._origin_line_length = 20
  45. self._origin_line_width = 0.5
  46. self._grid_mesh = None
  47. self._grid_shader = None
  48. self._disallowed_areas = []
  49. self._disallowed_area_mesh = None
  50. self._error_areas = []
  51. self._error_mesh = None
  52. self.setCalculateBoundingBox(False)
  53. self._volume_aabb = None
  54. self._raft_thickness = 0.0
  55. self._extra_z_clearance = 0.0
  56. self._adhesion_type = None
  57. self._platform = Platform(self)
  58. self._global_container_stack = None
  59. Application.getInstance().globalContainerStackChanged.connect(self._onStackChanged)
  60. self._onStackChanged()
  61. self._engine_ready = False
  62. Application.getInstance().engineCreatedSignal.connect(self._onEngineCreated)
  63. self._has_errors = False
  64. Application.getInstance().getController().getScene().sceneChanged.connect(self._onSceneChanged)
  65. #Objects loaded at the moment. We are connected to the property changed events of these objects.
  66. self._scene_objects = set()
  67. self._change_timer = QTimer()
  68. self._change_timer.setInterval(100)
  69. self._change_timer.setSingleShot(True)
  70. self._change_timer.timeout.connect(self._onChangeTimerFinished)
  71. self._build_volume_message = Message(catalog.i18nc("@info:status",
  72. "The build volume height has been reduced due to the value of the"
  73. " \"Print Sequence\" setting to prevent the gantry from colliding"
  74. " with printed models."))
  75. # Must be after setting _build_volume_message, apparently that is used in getMachineManager.
  76. # activeQualityChanged is always emitted after setActiveVariant, setActiveMaterial and setActiveQuality.
  77. # Therefore this works.
  78. Application.getInstance().getMachineManager().activeQualityChanged.connect(self._onStackChanged)
  79. # This should also ways work, and it is semantically more correct,
  80. # but it does not update the disallowed areas after material change
  81. Application.getInstance().getMachineManager().activeStackChanged.connect(self._onStackChanged)
  82. def _onSceneChanged(self, source):
  83. if self._global_container_stack:
  84. self._change_timer.start()
  85. def _onChangeTimerFinished(self):
  86. root = Application.getInstance().getController().getScene().getRoot()
  87. new_scene_objects = set(node for node in BreadthFirstIterator(root) if node.callDecoration("isSliceable"))
  88. if new_scene_objects != self._scene_objects:
  89. for node in new_scene_objects - self._scene_objects: #Nodes that were added to the scene.
  90. self._updateNodeListeners(node)
  91. node.decoratorsChanged.connect(self._updateNodeListeners) # Make sure that decoration changes afterwards also receive the same treatment
  92. for node in self._scene_objects - new_scene_objects: #Nodes that were removed from the scene.
  93. per_mesh_stack = node.callDecoration("getStack")
  94. if per_mesh_stack:
  95. per_mesh_stack.propertyChanged.disconnect(self._onSettingPropertyChanged)
  96. active_extruder_changed = node.callDecoration("getActiveExtruderChangedSignal")
  97. if active_extruder_changed is not None:
  98. node.callDecoration("getActiveExtruderChangedSignal").disconnect(self._updateDisallowedAreasAndRebuild)
  99. node.decoratorsChanged.disconnect(self._updateNodeListeners)
  100. self._scene_objects = new_scene_objects
  101. self._onSettingPropertyChanged("print_sequence", "value") # Create fake event, so right settings are triggered.
  102. ## Updates the listeners that listen for changes in per-mesh stacks.
  103. #
  104. # \param node The node for which the decorators changed.
  105. def _updateNodeListeners(self, node):
  106. per_mesh_stack = node.callDecoration("getStack")
  107. if per_mesh_stack:
  108. per_mesh_stack.propertyChanged.connect(self._onSettingPropertyChanged)
  109. active_extruder_changed = node.callDecoration("getActiveExtruderChangedSignal")
  110. if active_extruder_changed is not None:
  111. active_extruder_changed.connect(self._updateDisallowedAreasAndRebuild)
  112. self._updateDisallowedAreasAndRebuild()
  113. def setWidth(self, width):
  114. if width: self._width = width
  115. def setHeight(self, height):
  116. if height: self._height = height
  117. def setDepth(self, depth):
  118. if depth: self._depth = depth
  119. def setShape(self, shape):
  120. if shape: self._shape = shape
  121. def getDisallowedAreas(self):
  122. return self._disallowed_areas
  123. def setDisallowedAreas(self, areas):
  124. self._disallowed_areas = areas
  125. def render(self, renderer):
  126. if not self.getMeshData():
  127. return True
  128. if not self._shader:
  129. self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "default.shader"))
  130. self._grid_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "grid.shader"))
  131. theme = Application.getInstance().getTheme()
  132. self._grid_shader.setUniformValue("u_gridColor0", Color(*theme.getColor("buildplate").getRgb()))
  133. self._grid_shader.setUniformValue("u_gridColor1", Color(*theme.getColor("buildplate_alt").getRgb()))
  134. renderer.queueNode(self, mode = RenderBatch.RenderMode.Lines)
  135. renderer.queueNode(self, mesh = self._origin_mesh)
  136. renderer.queueNode(self, mesh = self._grid_mesh, shader = self._grid_shader, backface_cull = True)
  137. if self._disallowed_area_mesh:
  138. renderer.queueNode(self, mesh = self._disallowed_area_mesh, shader = self._shader, transparent = True, backface_cull = True, sort = -9)
  139. if self._error_mesh:
  140. renderer.queueNode(self, mesh=self._error_mesh, shader=self._shader, transparent=True,
  141. backface_cull=True, sort=-8)
  142. return True
  143. ## For every sliceable node, update node._outside_buildarea
  144. #
  145. def updateNodeBoundaryCheck(self):
  146. root = Application.getInstance().getController().getScene().getRoot()
  147. nodes = list(BreadthFirstIterator(root))
  148. group_nodes = []
  149. build_volume_bounding_box = self.getBoundingBox()
  150. if build_volume_bounding_box:
  151. # It's over 9000!
  152. build_volume_bounding_box = build_volume_bounding_box.set(bottom=-9001)
  153. else:
  154. # No bounding box. This is triggered when running Cura from command line with a model for the first time
  155. # In that situation there is a model, but no machine (and therefore no build volume.
  156. return
  157. for node in nodes:
  158. # Need to check group nodes later
  159. if node.callDecoration("isGroup"):
  160. group_nodes.append(node) # Keep list of affected group_nodes
  161. if node.callDecoration("isSliceable") or node.callDecoration("isGroup"):
  162. node._outside_buildarea = False
  163. bbox = node.getBoundingBox()
  164. # Mark the node as outside the build volume if the bounding box test fails.
  165. if build_volume_bounding_box.intersectsBox(bbox) != AxisAlignedBox.IntersectionResult.FullIntersection:
  166. node._outside_buildarea = True
  167. continue
  168. convex_hull = node.callDecoration("getConvexHull")
  169. if convex_hull:
  170. if not convex_hull.isValid():
  171. return
  172. # Check for collisions between disallowed areas and the object
  173. for area in self.getDisallowedAreas():
  174. overlap = convex_hull.intersectsPolygon(area)
  175. if overlap is None:
  176. continue
  177. node._outside_buildarea = True
  178. continue
  179. # Group nodes should override the _outside_buildarea property of their children.
  180. for group_node in group_nodes:
  181. for child_node in group_node.getAllChildren():
  182. child_node._outside_buildarea = group_node._outside_buildarea
  183. ## Recalculates the build volume & disallowed areas.
  184. def rebuild(self):
  185. if not self._width or not self._height or not self._depth:
  186. return
  187. if not Application.getInstance()._engine:
  188. return
  189. if not self._volume_outline_color:
  190. theme = Application.getInstance().getTheme()
  191. self._volume_outline_color = Color(*theme.getColor("volume_outline").getRgb())
  192. self._x_axis_color = Color(*theme.getColor("x_axis").getRgb())
  193. self._y_axis_color = Color(*theme.getColor("y_axis").getRgb())
  194. self._z_axis_color = Color(*theme.getColor("z_axis").getRgb())
  195. self._disallowed_area_color = Color(*theme.getColor("disallowed_area").getRgb())
  196. self._error_area_color = Color(*theme.getColor("error_area").getRgb())
  197. min_w = -self._width / 2
  198. max_w = self._width / 2
  199. min_h = 0.0
  200. max_h = self._height
  201. min_d = -self._depth / 2
  202. max_d = self._depth / 2
  203. z_fight_distance = 0.2 # Distance between buildplate and disallowed area meshes to prevent z-fighting
  204. if self._shape != "elliptic":
  205. # Outline 'cube' of the build volume
  206. mb = MeshBuilder()
  207. mb.addLine(Vector(min_w, min_h, min_d), Vector(max_w, min_h, min_d), color = self._volume_outline_color)
  208. mb.addLine(Vector(min_w, min_h, min_d), Vector(min_w, max_h, min_d), color = self._volume_outline_color)
  209. mb.addLine(Vector(min_w, max_h, min_d), Vector(max_w, max_h, min_d), color = self._volume_outline_color)
  210. mb.addLine(Vector(max_w, min_h, min_d), Vector(max_w, max_h, min_d), color = self._volume_outline_color)
  211. mb.addLine(Vector(min_w, min_h, max_d), Vector(max_w, min_h, max_d), color = self._volume_outline_color)
  212. mb.addLine(Vector(min_w, min_h, max_d), Vector(min_w, max_h, max_d), color = self._volume_outline_color)
  213. mb.addLine(Vector(min_w, max_h, max_d), Vector(max_w, max_h, max_d), color = self._volume_outline_color)
  214. mb.addLine(Vector(max_w, min_h, max_d), Vector(max_w, max_h, max_d), color = self._volume_outline_color)
  215. mb.addLine(Vector(min_w, min_h, min_d), Vector(min_w, min_h, max_d), color = self._volume_outline_color)
  216. mb.addLine(Vector(max_w, min_h, min_d), Vector(max_w, min_h, max_d), color = self._volume_outline_color)
  217. mb.addLine(Vector(min_w, max_h, min_d), Vector(min_w, max_h, max_d), color = self._volume_outline_color)
  218. mb.addLine(Vector(max_w, max_h, min_d), Vector(max_w, max_h, max_d), color = self._volume_outline_color)
  219. self.setMeshData(mb.build())
  220. # Build plate grid mesh
  221. mb = MeshBuilder()
  222. mb.addQuad(
  223. Vector(min_w, min_h - z_fight_distance, min_d),
  224. Vector(max_w, min_h - z_fight_distance, min_d),
  225. Vector(max_w, min_h - z_fight_distance, max_d),
  226. Vector(min_w, min_h - z_fight_distance, max_d)
  227. )
  228. for n in range(0, 6):
  229. v = mb.getVertex(n)
  230. mb.setVertexUVCoordinates(n, v[0], v[2])
  231. self._grid_mesh = mb.build()
  232. else:
  233. # Bottom and top 'ellipse' of the build volume
  234. aspect = 1.0
  235. scale_matrix = Matrix()
  236. if self._width != 0:
  237. # Scale circular meshes by aspect ratio if width != height
  238. aspect = self._depth / self._width
  239. scale_matrix.compose(scale = Vector(1, 1, aspect))
  240. mb = MeshBuilder()
  241. mb.addArc(max_w, Vector.Unit_Y, center = (0, min_h - z_fight_distance, 0), color = self._volume_outline_color)
  242. mb.addArc(max_w, Vector.Unit_Y, center = (0, max_h, 0), color = self._volume_outline_color)
  243. self.setMeshData(mb.build().getTransformed(scale_matrix))
  244. # Build plate grid mesh
  245. mb = MeshBuilder()
  246. mb.addVertex(0, min_h - z_fight_distance, 0)
  247. mb.addArc(max_w, Vector.Unit_Y, center = Vector(0, min_h - z_fight_distance, 0))
  248. sections = mb.getVertexCount() - 1 # Center point is not an arc section
  249. indices = []
  250. for n in range(0, sections - 1):
  251. indices.append([0, n + 2, n + 1])
  252. mb.addIndices(numpy.asarray(indices, dtype = numpy.int32))
  253. mb.calculateNormals()
  254. for n in range(0, mb.getVertexCount()):
  255. v = mb.getVertex(n)
  256. mb.setVertexUVCoordinates(n, v[0], v[2] * aspect)
  257. self._grid_mesh = mb.build().getTransformed(scale_matrix)
  258. # Indication of the machine origin
  259. if self._global_container_stack.getProperty("machine_center_is_zero", "value"):
  260. origin = (Vector(min_w, min_h, min_d) + Vector(max_w, min_h, max_d)) / 2
  261. else:
  262. origin = Vector(min_w, min_h, max_d)
  263. mb = MeshBuilder()
  264. mb.addCube(
  265. width = self._origin_line_length,
  266. height = self._origin_line_width,
  267. depth = self._origin_line_width,
  268. center = origin + Vector(self._origin_line_length / 2, 0, 0),
  269. color = self._x_axis_color
  270. )
  271. mb.addCube(
  272. width = self._origin_line_width,
  273. height = self._origin_line_length,
  274. depth = self._origin_line_width,
  275. center = origin + Vector(0, self._origin_line_length / 2, 0),
  276. color = self._y_axis_color
  277. )
  278. mb.addCube(
  279. width = self._origin_line_width,
  280. height = self._origin_line_width,
  281. depth = self._origin_line_length,
  282. center = origin - Vector(0, 0, self._origin_line_length / 2),
  283. color = self._z_axis_color
  284. )
  285. self._origin_mesh = mb.build()
  286. disallowed_area_height = 0.1
  287. disallowed_area_size = 0
  288. if self._disallowed_areas:
  289. mb = MeshBuilder()
  290. color = self._disallowed_area_color
  291. for polygon in self._disallowed_areas:
  292. points = polygon.getPoints()
  293. if len(points) == 0:
  294. continue
  295. first = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height, self._clamp(points[0][1], min_d, max_d))
  296. previous_point = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height, self._clamp(points[0][1], min_d, max_d))
  297. for point in points:
  298. new_point = Vector(self._clamp(point[0], min_w, max_w), disallowed_area_height, self._clamp(point[1], min_d, max_d))
  299. mb.addFace(first, previous_point, new_point, color = color)
  300. previous_point = new_point
  301. # Find the largest disallowed area to exclude it from the maximum scale bounds.
  302. # This is a very nasty hack. This pretty much only works for UM machines.
  303. # This disallowed area_size needs a -lot- of rework at some point in the future: TODO
  304. if numpy.min(points[:, 1]) >= 0: # This filters out all areas that have points to the left of the centre. This is done to filter the skirt area.
  305. size = abs(numpy.max(points[:, 1]) - numpy.min(points[:, 1]))
  306. else:
  307. size = 0
  308. disallowed_area_size = max(size, disallowed_area_size)
  309. self._disallowed_area_mesh = mb.build()
  310. else:
  311. self._disallowed_area_mesh = None
  312. if self._error_areas:
  313. mb = MeshBuilder()
  314. for error_area in self._error_areas:
  315. color = self._error_area_color
  316. points = error_area.getPoints()
  317. first = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height,
  318. self._clamp(points[0][1], min_d, max_d))
  319. previous_point = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height,
  320. self._clamp(points[0][1], min_d, max_d))
  321. for point in points:
  322. new_point = Vector(self._clamp(point[0], min_w, max_w), disallowed_area_height,
  323. self._clamp(point[1], min_d, max_d))
  324. mb.addFace(first, previous_point, new_point, color=color)
  325. previous_point = new_point
  326. self._error_mesh = mb.build()
  327. else:
  328. self._error_mesh = None
  329. self._volume_aabb = AxisAlignedBox(
  330. minimum = Vector(min_w, min_h - 1.0, min_d),
  331. maximum = Vector(max_w, max_h - self._raft_thickness - self._extra_z_clearance, max_d))
  332. bed_adhesion_size = self._getEdgeDisallowedSize()
  333. # As this works better for UM machines, we only add the disallowed_area_size for the z direction.
  334. # This is probably wrong in all other cases. TODO!
  335. # The +1 and -1 is added as there is always a bit of extra room required to work properly.
  336. scale_to_max_bounds = AxisAlignedBox(
  337. minimum = Vector(min_w + bed_adhesion_size + 1, min_h, min_d + disallowed_area_size - bed_adhesion_size + 1),
  338. maximum = Vector(max_w - bed_adhesion_size - 1, max_h - self._raft_thickness - self._extra_z_clearance, max_d - disallowed_area_size + bed_adhesion_size - 1)
  339. )
  340. Application.getInstance().getController().getScene()._maximum_bounds = scale_to_max_bounds
  341. self.updateNodeBoundaryCheck()
  342. def getBoundingBox(self):
  343. return self._volume_aabb
  344. def getRaftThickness(self):
  345. return self._raft_thickness
  346. def _updateRaftThickness(self):
  347. old_raft_thickness = self._raft_thickness
  348. self._adhesion_type = self._global_container_stack.getProperty("adhesion_type", "value")
  349. self._raft_thickness = 0.0
  350. if self._adhesion_type == "raft":
  351. self._raft_thickness = (
  352. self._global_container_stack.getProperty("raft_base_thickness", "value") +
  353. self._global_container_stack.getProperty("raft_interface_thickness", "value") +
  354. self._global_container_stack.getProperty("raft_surface_layers", "value") *
  355. self._global_container_stack.getProperty("raft_surface_thickness", "value") +
  356. self._global_container_stack.getProperty("raft_airgap", "value"))
  357. # Rounding errors do not matter, we check if raft_thickness has changed at all
  358. if old_raft_thickness != self._raft_thickness:
  359. self.setPosition(Vector(0, -self._raft_thickness, 0), SceneNode.TransformSpace.World)
  360. self.raftThicknessChanged.emit()
  361. def _updateExtraZClearance(self) -> None:
  362. extra_z = 0.0
  363. extruders = ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())
  364. use_extruders = False
  365. for extruder in extruders:
  366. if extruder.getProperty("retraction_hop_enabled", "value"):
  367. retraction_hop = extruder.getProperty("retraction_hop", "value")
  368. if extra_z is None or retraction_hop > extra_z:
  369. extra_z = retraction_hop
  370. use_extruders = True
  371. if not use_extruders:
  372. # If no extruders, take global value.
  373. if self._global_container_stack.getProperty("retraction_hop_enabled", "value"):
  374. extra_z = self._global_container_stack.getProperty("retraction_hop", "value")
  375. if extra_z != self._extra_z_clearance:
  376. self._extra_z_clearance = extra_z
  377. ## Update the build volume visualization
  378. def _onStackChanged(self):
  379. if self._global_container_stack:
  380. self._global_container_stack.propertyChanged.disconnect(self._onSettingPropertyChanged)
  381. extruders = ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())
  382. for extruder in extruders:
  383. extruder.propertyChanged.disconnect(self._onSettingPropertyChanged)
  384. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  385. if self._global_container_stack:
  386. self._global_container_stack.propertyChanged.connect(self._onSettingPropertyChanged)
  387. extruders = ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())
  388. for extruder in extruders:
  389. extruder.propertyChanged.connect(self._onSettingPropertyChanged)
  390. self._width = self._global_container_stack.getProperty("machine_width", "value")
  391. machine_height = self._global_container_stack.getProperty("machine_height", "value")
  392. if self._global_container_stack.getProperty("print_sequence", "value") == "one_at_a_time" and len(self._scene_objects) > 1:
  393. self._height = min(self._global_container_stack.getProperty("gantry_height", "value"), machine_height)
  394. if self._height < machine_height:
  395. self._build_volume_message.show()
  396. else:
  397. self._build_volume_message.hide()
  398. else:
  399. self._height = self._global_container_stack.getProperty("machine_height", "value")
  400. self._build_volume_message.hide()
  401. self._depth = self._global_container_stack.getProperty("machine_depth", "value")
  402. self._shape = self._global_container_stack.getProperty("machine_shape", "value")
  403. self._updateDisallowedAreas()
  404. self._updateRaftThickness()
  405. if self._engine_ready:
  406. self.rebuild()
  407. def _onEngineCreated(self):
  408. self._engine_ready = True
  409. self.rebuild()
  410. def _onSettingPropertyChanged(self, setting_key, property_name):
  411. if property_name != "value":
  412. return
  413. rebuild_me = False
  414. if setting_key == "print_sequence":
  415. machine_height = self._global_container_stack.getProperty("machine_height", "value")
  416. if Application.getInstance().getGlobalContainerStack().getProperty("print_sequence", "value") == "one_at_a_time" and len(self._scene_objects) > 1:
  417. self._height = min(self._global_container_stack.getProperty("gantry_height", "value"), machine_height)
  418. if self._height < machine_height:
  419. self._build_volume_message.show()
  420. else:
  421. self._build_volume_message.hide()
  422. else:
  423. self._height = self._global_container_stack.getProperty("machine_height", "value")
  424. self._build_volume_message.hide()
  425. rebuild_me = True
  426. if setting_key in self._skirt_settings or setting_key in self._prime_settings or setting_key in self._tower_settings or setting_key == "print_sequence" or setting_key in self._ooze_shield_settings or setting_key in self._distance_settings or setting_key in self._extruder_settings:
  427. self._updateDisallowedAreas()
  428. rebuild_me = True
  429. if setting_key in self._raft_settings:
  430. self._updateRaftThickness()
  431. rebuild_me = True
  432. if setting_key in self._extra_z_settings:
  433. self._updateExtraZClearance()
  434. rebuild_me = True
  435. if rebuild_me:
  436. self.rebuild()
  437. def hasErrors(self):
  438. return self._has_errors
  439. ## Calls _updateDisallowedAreas and makes sure the changes appear in the
  440. # scene.
  441. #
  442. # This is required for a signal to trigger the update in one go. The
  443. # ``_updateDisallowedAreas`` method itself shouldn't call ``rebuild``,
  444. # since there may be other changes before it needs to be rebuilt, which
  445. # would hit performance.
  446. def _updateDisallowedAreasAndRebuild(self):
  447. self._updateDisallowedAreas()
  448. self.rebuild()
  449. def _updateDisallowedAreas(self):
  450. if not self._global_container_stack:
  451. return
  452. self._error_areas = []
  453. extruder_manager = ExtruderManager.getInstance()
  454. used_extruders = extruder_manager.getUsedExtruderStacks()
  455. disallowed_border_size = self._getEdgeDisallowedSize()
  456. if not used_extruders:
  457. # If no extruder is used, assume that the active extruder is used (else nothing is drawn)
  458. if extruder_manager.getActiveExtruderStack():
  459. used_extruders = [extruder_manager.getActiveExtruderStack()]
  460. else:
  461. used_extruders = [self._global_container_stack]
  462. result_areas = self._computeDisallowedAreasStatic(disallowed_border_size, used_extruders) #Normal machine disallowed areas can always be added.
  463. prime_areas = self._computeDisallowedAreasPrime(disallowed_border_size, used_extruders)
  464. prime_disallowed_areas = self._computeDisallowedAreasStatic(0, used_extruders) #Where the priming is not allowed to happen. This is not added to the result, just for collision checking.
  465. #Check if prime positions intersect with disallowed areas.
  466. for extruder in used_extruders:
  467. extruder_id = extruder.getId()
  468. collision = False
  469. for prime_polygon in prime_areas[extruder_id]:
  470. for disallowed_polygon in prime_disallowed_areas[extruder_id]:
  471. if prime_polygon.intersectsPolygon(disallowed_polygon) is not None:
  472. collision = True
  473. break
  474. if collision:
  475. break
  476. #Also check other prime positions (without additional offset).
  477. for other_extruder_id in prime_areas:
  478. if extruder_id == other_extruder_id: #It is allowed to collide with itself.
  479. continue
  480. for other_prime_polygon in prime_areas[other_extruder_id]:
  481. if prime_polygon.intersectsPolygon(other_prime_polygon):
  482. collision = True
  483. break
  484. if collision:
  485. break
  486. if collision:
  487. break
  488. result_areas[extruder_id].extend(prime_areas[extruder_id])
  489. nozzle_disallowed_areas = extruder.getProperty("nozzle_disallowed_areas", "value")
  490. for area in nozzle_disallowed_areas:
  491. polygon = Polygon(numpy.array(area, numpy.float32))
  492. polygon = polygon.getMinkowskiHull(Polygon.approximatedCircle(disallowed_border_size))
  493. result_areas[extruder_id].append(polygon) #Don't perform the offset on these.
  494. # Add prime tower location as disallowed area.
  495. prime_tower_collision = False
  496. prime_tower_areas = self._computeDisallowedAreasPrinted(used_extruders)
  497. for extruder_id in prime_tower_areas:
  498. for prime_tower_area in prime_tower_areas[extruder_id]:
  499. for area in result_areas[extruder_id]:
  500. if prime_tower_area.intersectsPolygon(area) is not None:
  501. prime_tower_collision = True
  502. break
  503. if prime_tower_collision: #Already found a collision.
  504. break
  505. if not prime_tower_collision:
  506. result_areas[extruder_id].extend(prime_tower_areas[extruder_id])
  507. else:
  508. self._error_areas.extend(prime_tower_areas[extruder_id])
  509. self._has_errors = len(self._error_areas) > 0
  510. self._disallowed_areas = []
  511. for extruder_id in result_areas:
  512. self._disallowed_areas.extend(result_areas[extruder_id])
  513. ## Computes the disallowed areas for objects that are printed with print
  514. # features.
  515. #
  516. # This means that the brim, travel avoidance and such will be applied to
  517. # these features.
  518. #
  519. # \return A dictionary with for each used extruder ID the disallowed areas
  520. # where that extruder may not print.
  521. def _computeDisallowedAreasPrinted(self, used_extruders):
  522. result = {}
  523. for extruder in used_extruders:
  524. result[extruder.getId()] = []
  525. #Currently, the only normally printed object is the prime tower.
  526. if ExtruderManager.getInstance().getResolveOrValue("prime_tower_enable") == True:
  527. prime_tower_size = self._global_container_stack.getProperty("prime_tower_size", "value")
  528. machine_width = self._global_container_stack.getProperty("machine_width", "value")
  529. machine_depth = self._global_container_stack.getProperty("machine_depth", "value")
  530. prime_tower_x = self._global_container_stack.getProperty("prime_tower_position_x", "value")
  531. prime_tower_y = - self._global_container_stack.getProperty("prime_tower_position_y", "value")
  532. if not self._global_container_stack.getProperty("machine_center_is_zero", "value"):
  533. prime_tower_x = prime_tower_x - machine_width / 2 #Offset by half machine_width and _depth to put the origin in the front-left.
  534. prime_tower_y = prime_tower_y + machine_depth / 2
  535. prime_tower_area = Polygon([
  536. [prime_tower_x - prime_tower_size, prime_tower_y - prime_tower_size],
  537. [prime_tower_x, prime_tower_y - prime_tower_size],
  538. [prime_tower_x, prime_tower_y],
  539. [prime_tower_x - prime_tower_size, prime_tower_y],
  540. ])
  541. prime_tower_area = prime_tower_area.getMinkowskiHull(Polygon.approximatedCircle(0))
  542. for extruder in used_extruders:
  543. result[extruder.getId()].append(prime_tower_area) #The prime tower location is the same for each extruder, regardless of offset.
  544. return result
  545. ## Computes the disallowed areas for the prime locations.
  546. #
  547. # These are special because they are not subject to things like brim or
  548. # travel avoidance. They do get a dilute with the border size though
  549. # because they may not intersect with brims and such of other objects.
  550. #
  551. # \param border_size The size with which to offset the disallowed areas
  552. # due to skirt, brim, travel avoid distance, etc.
  553. # \param used_extruders The extruder stacks to generate disallowed areas
  554. # for.
  555. # \return A dictionary with for each used extruder ID the prime areas.
  556. def _computeDisallowedAreasPrime(self, border_size, used_extruders):
  557. result = {}
  558. machine_width = self._global_container_stack.getProperty("machine_width", "value")
  559. machine_depth = self._global_container_stack.getProperty("machine_depth", "value")
  560. for extruder in used_extruders:
  561. prime_x = extruder.getProperty("extruder_prime_pos_x", "value")
  562. prime_y = - extruder.getProperty("extruder_prime_pos_y", "value")
  563. #Ignore extruder prime position if it is not set
  564. if prime_x == 0 and prime_y == 0:
  565. result[extruder.getId()] = []
  566. continue
  567. if not self._global_container_stack.getProperty("machine_center_is_zero", "value"):
  568. prime_x = prime_x - machine_width / 2 #Offset by half machine_width and _depth to put the origin in the front-left.
  569. prime_y = prime_y + machine_depth / 2
  570. prime_polygon = Polygon.approximatedCircle(PRIME_CLEARANCE)
  571. prime_polygon = prime_polygon.getMinkowskiHull(Polygon.approximatedCircle(border_size))
  572. prime_polygon = prime_polygon.translate(prime_x, prime_y)
  573. result[extruder.getId()] = [prime_polygon]
  574. return result
  575. ## Computes the disallowed areas that are statically placed in the machine.
  576. #
  577. # It computes different disallowed areas depending on the offset of the
  578. # extruder. The resulting dictionary will therefore have an entry for each
  579. # extruder that is used.
  580. #
  581. # \param border_size The size with which to offset the disallowed areas
  582. # due to skirt, brim, travel avoid distance, etc.
  583. # \param used_extruders The extruder stacks to generate disallowed areas
  584. # for.
  585. # \return A dictionary with for each used extruder ID the disallowed areas
  586. # where that extruder may not print.
  587. def _computeDisallowedAreasStatic(self, border_size, used_extruders):
  588. #Convert disallowed areas to polygons and dilate them.
  589. machine_disallowed_polygons = []
  590. for area in self._global_container_stack.getProperty("machine_disallowed_areas", "value"):
  591. polygon = Polygon(numpy.array(area, numpy.float32))
  592. polygon = polygon.getMinkowskiHull(Polygon.approximatedCircle(border_size))
  593. machine_disallowed_polygons.append(polygon)
  594. result = {}
  595. for extruder in used_extruders:
  596. extruder_id = extruder.getId()
  597. offset_x = extruder.getProperty("machine_nozzle_offset_x", "value")
  598. if offset_x is None:
  599. offset_x = 0
  600. offset_y = extruder.getProperty("machine_nozzle_offset_y", "value")
  601. if offset_y is None:
  602. offset_y = 0
  603. result[extruder_id] = []
  604. for polygon in machine_disallowed_polygons:
  605. result[extruder_id].append(polygon.translate(offset_x, offset_y)) #Compensate for the nozzle offset of this extruder.
  606. #Add the border around the edge of the build volume.
  607. left_unreachable_border = 0
  608. right_unreachable_border = 0
  609. top_unreachable_border = 0
  610. bottom_unreachable_border = 0
  611. #The build volume is defined as the union of the area that all extruders can reach, so we need to know the relative offset to all extruders.
  612. for other_extruder in ExtruderManager.getInstance().getActiveExtruderStacks():
  613. other_offset_x = other_extruder.getProperty("machine_nozzle_offset_x", "value")
  614. other_offset_y = other_extruder.getProperty("machine_nozzle_offset_y", "value")
  615. left_unreachable_border = min(left_unreachable_border, other_offset_x - offset_x)
  616. right_unreachable_border = max(right_unreachable_border, other_offset_x - offset_x)
  617. top_unreachable_border = min(top_unreachable_border, other_offset_y - offset_y)
  618. bottom_unreachable_border = max(bottom_unreachable_border, other_offset_y - offset_y)
  619. half_machine_width = self._global_container_stack.getProperty("machine_width", "value") / 2
  620. half_machine_depth = self._global_container_stack.getProperty("machine_depth", "value") / 2
  621. if self._shape != "elliptic":
  622. if border_size - left_unreachable_border > 0:
  623. result[extruder_id].append(Polygon(numpy.array([
  624. [-half_machine_width, -half_machine_depth],
  625. [-half_machine_width, half_machine_depth],
  626. [-half_machine_width + border_size - left_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border],
  627. [-half_machine_width + border_size - left_unreachable_border, -half_machine_depth + border_size - top_unreachable_border]
  628. ], numpy.float32)))
  629. if border_size + right_unreachable_border > 0:
  630. result[extruder_id].append(Polygon(numpy.array([
  631. [half_machine_width, half_machine_depth],
  632. [half_machine_width, -half_machine_depth],
  633. [half_machine_width - border_size - right_unreachable_border, -half_machine_depth + border_size - top_unreachable_border],
  634. [half_machine_width - border_size - right_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border]
  635. ], numpy.float32)))
  636. if border_size + bottom_unreachable_border > 0:
  637. result[extruder_id].append(Polygon(numpy.array([
  638. [-half_machine_width, half_machine_depth],
  639. [half_machine_width, half_machine_depth],
  640. [half_machine_width - border_size - right_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border],
  641. [-half_machine_width + border_size - left_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border]
  642. ], numpy.float32)))
  643. if border_size - top_unreachable_border > 0:
  644. result[extruder_id].append(Polygon(numpy.array([
  645. [half_machine_width, -half_machine_depth],
  646. [-half_machine_width, -half_machine_depth],
  647. [-half_machine_width + border_size - left_unreachable_border, -half_machine_depth + border_size - top_unreachable_border],
  648. [half_machine_width - border_size - right_unreachable_border, -half_machine_depth + border_size - top_unreachable_border]
  649. ], numpy.float32)))
  650. else:
  651. sections = 32
  652. arc_vertex = [0, half_machine_depth - border_size]
  653. for i in range(0, sections):
  654. quadrant = math.floor(4 * i / sections)
  655. vertices = []
  656. if quadrant == 0:
  657. vertices.append([-half_machine_width, half_machine_depth])
  658. elif quadrant == 1:
  659. vertices.append([-half_machine_width, -half_machine_depth])
  660. elif quadrant == 2:
  661. vertices.append([half_machine_width, -half_machine_depth])
  662. elif quadrant == 3:
  663. vertices.append([half_machine_width, half_machine_depth])
  664. vertices.append(arc_vertex)
  665. angle = 2 * math.pi * (i + 1) / sections
  666. arc_vertex = [-(half_machine_width - border_size) * math.sin(angle), (half_machine_depth - border_size) * math.cos(angle)]
  667. vertices.append(arc_vertex)
  668. result[extruder_id].append(Polygon(numpy.array(vertices, numpy.float32)))
  669. if border_size > 0:
  670. result[extruder_id].append(Polygon(numpy.array([
  671. [-half_machine_width, -half_machine_depth],
  672. [-half_machine_width, half_machine_depth],
  673. [-half_machine_width + border_size, 0]
  674. ], numpy.float32)))
  675. result[extruder_id].append(Polygon(numpy.array([
  676. [-half_machine_width, half_machine_depth],
  677. [ half_machine_width, half_machine_depth],
  678. [ 0, half_machine_depth - border_size]
  679. ], numpy.float32)))
  680. result[extruder_id].append(Polygon(numpy.array([
  681. [ half_machine_width, half_machine_depth],
  682. [ half_machine_width, -half_machine_depth],
  683. [ half_machine_width - border_size, 0]
  684. ], numpy.float32)))
  685. result[extruder_id].append(Polygon(numpy.array([
  686. [ half_machine_width,-half_machine_depth],
  687. [-half_machine_width,-half_machine_depth],
  688. [ 0, -half_machine_depth + border_size]
  689. ], numpy.float32)))
  690. return result
  691. ## Private convenience function to get a setting from the adhesion
  692. # extruder.
  693. #
  694. # \param setting_key The key of the setting to get.
  695. # \param property The property to get from the setting.
  696. # \return The property of the specified setting in the adhesion extruder.
  697. def _getSettingFromAdhesionExtruder(self, setting_key, property = "value"):
  698. return self._getSettingFromExtruder(setting_key, "adhesion_extruder_nr", property)
  699. ## Private convenience function to get a setting from every extruder.
  700. #
  701. # For single extrusion machines, this gets the setting from the global
  702. # stack.
  703. #
  704. # \return A sequence of setting values, one for each extruder.
  705. def _getSettingFromAllExtruders(self, setting_key, property = "value"):
  706. all_values = ExtruderManager.getInstance().getAllExtruderSettings(setting_key, property)
  707. all_types = ExtruderManager.getInstance().getAllExtruderSettings(setting_key, "type")
  708. for i in range(len(all_values)):
  709. if not all_values[i] and (all_types[i] == "int" or all_types[i] == "float"):
  710. all_values[i] = 0
  711. return all_values
  712. ## Private convenience function to get a setting from the support infill
  713. # extruder.
  714. #
  715. # \param setting_key The key of the setting to get.
  716. # \param property The property to get from the setting.
  717. # \return The property of the specified setting in the support infill
  718. # extruder.
  719. def _getSettingFromSupportInfillExtruder(self, setting_key, property = "value"):
  720. return self._getSettingFromExtruder(setting_key, "support_infill_extruder_nr", property)
  721. ## Helper function to get a setting from an extruder specified in another
  722. # setting.
  723. #
  724. # \param setting_key The key of the setting to get.
  725. # \param extruder_setting_key The key of the setting that specifies from
  726. # which extruder to get the setting, if there are multiple extruders.
  727. # \param property The property to get from the setting.
  728. # \return The property of the specified setting in the specified extruder.
  729. def _getSettingFromExtruder(self, setting_key, extruder_setting_key, property = "value"):
  730. multi_extrusion = self._global_container_stack.getProperty("machine_extruder_count", "value") > 1
  731. if not multi_extrusion:
  732. stack = self._global_container_stack
  733. else:
  734. extruder_index = self._global_container_stack.getProperty(extruder_setting_key, "value")
  735. if extruder_index == "-1": # If extruder index is -1 use global instead
  736. stack = self._global_container_stack
  737. else:
  738. extruder_stack_id = ExtruderManager.getInstance().extruderIds[str(extruder_index)]
  739. stack = ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
  740. value = stack.getProperty(setting_key, property)
  741. setting_type = stack.getProperty(setting_key, "type")
  742. if not value and (setting_type == "int" or setting_type == "float"):
  743. return 0
  744. return value
  745. ## Convenience function to calculate the disallowed radius around the edge.
  746. #
  747. # This disallowed radius is to allow for space around the models that is
  748. # not part of the collision radius, such as bed adhesion (skirt/brim/raft)
  749. # and travel avoid distance.
  750. def _getEdgeDisallowedSize(self):
  751. if not self._global_container_stack:
  752. return 0
  753. container_stack = self._global_container_stack
  754. # If we are printing one at a time, we need to add the bed adhesion size to the disallowed areas of the objects
  755. if container_stack.getProperty("print_sequence", "value") == "one_at_a_time":
  756. return 0.1 # Return a very small value, so we do draw disallowed area's near the edges.
  757. adhesion_type = container_stack.getProperty("adhesion_type", "value")
  758. if adhesion_type == "skirt":
  759. skirt_distance = self._getSettingFromAdhesionExtruder("skirt_gap")
  760. skirt_line_count = self._getSettingFromAdhesionExtruder("skirt_line_count")
  761. bed_adhesion_size = skirt_distance + (skirt_line_count * self._getSettingFromAdhesionExtruder("skirt_brim_line_width"))
  762. if len(ExtruderManager.getInstance().getUsedExtruderStacks()) > 1:
  763. adhesion_extruder_nr = int(self._global_container_stack.getProperty("adhesion_extruder_nr", "value"))
  764. extruder_values = ExtruderManager.getInstance().getAllExtruderValues("skirt_brim_line_width")
  765. del extruder_values[adhesion_extruder_nr] # Remove the value of the adhesion extruder nr.
  766. for value in extruder_values:
  767. bed_adhesion_size += value
  768. elif adhesion_type == "brim":
  769. bed_adhesion_size = self._getSettingFromAdhesionExtruder("brim_line_count") * self._getSettingFromAdhesionExtruder("skirt_brim_line_width")
  770. if self._global_container_stack.getProperty("machine_extruder_count", "value") > 1:
  771. adhesion_extruder_nr = int(self._global_container_stack.getProperty("adhesion_extruder_nr", "value"))
  772. extruder_values = ExtruderManager.getInstance().getAllExtruderValues("skirt_brim_line_width")
  773. del extruder_values[adhesion_extruder_nr] # Remove the value of the adhesion extruder nr.
  774. for value in extruder_values:
  775. bed_adhesion_size += value
  776. elif adhesion_type == "raft":
  777. bed_adhesion_size = self._getSettingFromAdhesionExtruder("raft_margin")
  778. elif adhesion_type == "none":
  779. bed_adhesion_size = 0
  780. else:
  781. raise Exception("Unknown bed adhesion type. Did you forget to update the build volume calculations for your new bed adhesion type?")
  782. support_expansion = 0
  783. if self._getSettingFromSupportInfillExtruder("support_offset") and self._global_container_stack.getProperty("support_enable", "value"):
  784. support_expansion += self._getSettingFromSupportInfillExtruder("support_offset")
  785. farthest_shield_distance = 0
  786. if container_stack.getProperty("draft_shield_enabled", "value"):
  787. farthest_shield_distance = max(farthest_shield_distance, container_stack.getProperty("draft_shield_dist", "value"))
  788. if container_stack.getProperty("ooze_shield_enabled", "value"):
  789. farthest_shield_distance = max(farthest_shield_distance, container_stack.getProperty("ooze_shield_dist", "value"))
  790. move_from_wall_radius = 0 # Moves that start from outer wall.
  791. move_from_wall_radius = max(move_from_wall_radius, max(self._getSettingFromAllExtruders("infill_wipe_dist")))
  792. used_extruders = ExtruderManager.getInstance().getUsedExtruderStacks()
  793. avoid_enabled_per_extruder = [stack.getProperty("travel_avoid_other_parts","value") for stack in used_extruders]
  794. travel_avoid_distance_per_extruder = [stack.getProperty("travel_avoid_distance", "value") for stack in used_extruders]
  795. for avoid_other_parts_enabled, avoid_distance in zip(avoid_enabled_per_extruder, travel_avoid_distance_per_extruder): #For each extruder (or just global).
  796. if avoid_other_parts_enabled:
  797. move_from_wall_radius = max(move_from_wall_radius, avoid_distance)
  798. # Now combine our different pieces of data to get the final border size.
  799. # Support expansion is added to the bed adhesion, since the bed adhesion goes around support.
  800. # Support expansion is added to farthest shield distance, since the shields go around support.
  801. border_size = max(move_from_wall_radius, support_expansion + farthest_shield_distance, support_expansion + bed_adhesion_size)
  802. return border_size
  803. def _clamp(self, value, min_value, max_value):
  804. return max(min(value, max_value), min_value)
  805. _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"]
  806. _raft_settings = ["adhesion_type", "raft_base_thickness", "raft_interface_thickness", "raft_surface_layers", "raft_surface_thickness", "raft_airgap"]
  807. _extra_z_settings = ["retraction_hop_enabled", "retraction_hop"]
  808. _prime_settings = ["extruder_prime_pos_x", "extruder_prime_pos_y", "extruder_prime_pos_z"]
  809. _tower_settings = ["prime_tower_enable", "prime_tower_size", "prime_tower_position_x", "prime_tower_position_y"]
  810. _ooze_shield_settings = ["ooze_shield_enabled", "ooze_shield_dist"]
  811. _distance_settings = ["infill_wipe_dist", "travel_avoid_distance", "support_offset", "support_enable", "travel_avoid_other_parts"]
  812. _extruder_settings = ["support_enable", "support_interface_enable", "support_infill_extruder_nr", "support_extruder_nr_layer_0", "support_interface_extruder_nr", "brim_line_count", "adhesion_extruder_nr", "adhesion_type"] #Settings that can affect which extruders are used.