ConvexHullDecorator.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. # Copyright (c) 2020 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from PyQt6.QtCore import QTimer
  4. from UM.Application import Application
  5. from UM.Math.Polygon import Polygon
  6. from UM.Scene.SceneNodeDecorator import SceneNodeDecorator
  7. from UM.Settings.ContainerRegistry import ContainerRegistry
  8. from cura.Settings.ExtruderManager import ExtruderManager
  9. from cura.Scene import ConvexHullNode
  10. import numpy
  11. from typing import TYPE_CHECKING, Any, Optional
  12. if TYPE_CHECKING:
  13. from UM.Scene.SceneNode import SceneNode
  14. from cura.Settings.GlobalStack import GlobalStack
  15. from UM.Mesh.MeshData import MeshData
  16. from UM.Math.Matrix import Matrix
  17. class ConvexHullDecorator(SceneNodeDecorator):
  18. """The convex hull decorator is a scene node decorator that adds the convex hull functionality to a scene node.
  19. If a scene node has a convex hull decorator, it will have a shadow in which other objects can not be printed.
  20. """
  21. def __init__(self) -> None:
  22. super().__init__()
  23. self._convex_hull_node = None # type: Optional["SceneNode"]
  24. self._init2DConvexHullCache()
  25. self._global_stack = None # type: Optional[GlobalStack]
  26. # Make sure the timer is created on the main thread
  27. self._recompute_convex_hull_timer = None # type: Optional[QTimer]
  28. self._timer_scheduled_to_be_created = False
  29. from cura.CuraApplication import CuraApplication
  30. if CuraApplication.getInstance() is not None:
  31. self._timer_scheduled_to_be_created = True
  32. CuraApplication.getInstance().callLater(self.createRecomputeConvexHullTimer)
  33. self._raft_thickness = 0.0
  34. self._build_volume = CuraApplication.getInstance().getBuildVolume()
  35. self._build_volume.raftThicknessChanged.connect(self._onChanged)
  36. CuraApplication.getInstance().globalContainerStackChanged.connect(self._onGlobalStackChanged)
  37. controller = CuraApplication.getInstance().getController()
  38. controller.toolOperationStarted.connect(self._onChanged)
  39. controller.toolOperationStopped.connect(self._onChanged)
  40. #CuraApplication.getInstance().sceneBoundingBoxChanged.connect(self._onChanged)
  41. self._root = Application.getInstance().getController().getScene().getRoot()
  42. self._onGlobalStackChanged()
  43. def createRecomputeConvexHullTimer(self) -> None:
  44. self._recompute_convex_hull_timer = QTimer()
  45. self._recompute_convex_hull_timer.setInterval(200)
  46. self._recompute_convex_hull_timer.setSingleShot(True)
  47. self._recompute_convex_hull_timer.timeout.connect(self.recomputeConvexHull)
  48. def setNode(self, node: "SceneNode") -> None:
  49. previous_node = self._node
  50. # Disconnect from previous node signals
  51. if previous_node is not None and node is not previous_node:
  52. previous_node.boundingBoxChanged.disconnect(self._onChanged)
  53. super().setNode(node)
  54. node.boundingBoxChanged.connect(self._onChanged)
  55. per_object_stack = node.callDecoration("getStack")
  56. if per_object_stack:
  57. per_object_stack.propertyChanged.connect(self._onSettingValueChanged)
  58. self._onChanged()
  59. def __deepcopy__(self, memo):
  60. """Force that a new (empty) object is created upon copy."""
  61. return ConvexHullDecorator()
  62. def getAdhesionArea(self) -> Optional[Polygon]:
  63. """The polygon representing the 2D adhesion area.
  64. If no adhesion is used, the regular convex hull is returned
  65. """
  66. if self._node is None:
  67. return None
  68. hull = self._compute2DConvexHull()
  69. if hull is None:
  70. return None
  71. return self._add2DAdhesionMargin(hull)
  72. def getConvexHull(self) -> Optional[Polygon]:
  73. """Get the unmodified 2D projected convex hull of the node (if any)
  74. In case of one-at-a-time, this includes adhesion and head+fans clearance
  75. """
  76. if self._node is None:
  77. return None
  78. if self._node.callDecoration("isNonPrintingMesh"):
  79. return None
  80. # Parent can be None if node is just loaded.
  81. if self._isSingularOneAtATimeNode():
  82. hull = self.getConvexHullHeadFull()
  83. if hull is None:
  84. return None
  85. hull = self._add2DAdhesionMargin(hull)
  86. return hull
  87. return self._compute2DConvexHull()
  88. def getConvexHullHeadFull(self) -> Optional[Polygon]:
  89. """For one at the time this is the convex hull of the node with the full head size
  90. In case of printing all at once this is None.
  91. """
  92. if self._node is None:
  93. return None
  94. if self._isSingularOneAtATimeNode():
  95. return self._compute2DConvexHeadFull()
  96. return None
  97. @staticmethod
  98. def hasGroupAsParent(node: "SceneNode") -> bool:
  99. parent = node.getParent()
  100. if parent is None:
  101. return False
  102. return bool(parent.callDecoration("isGroup"))
  103. def getConvexHullHead(self) -> Optional[Polygon]:
  104. """Get convex hull of the object + head size
  105. In case of printing all at once this is None.
  106. For one at the time this is area with intersection of mirrored head
  107. """
  108. if self._node is None:
  109. return None
  110. if self._node.callDecoration("isNonPrintingMesh"):
  111. return None
  112. if self._isSingularOneAtATimeNode():
  113. head_with_fans = self._compute2DConvexHeadMin()
  114. if head_with_fans is None:
  115. return None
  116. head_with_fans_with_adhesion_margin = self._add2DAdhesionMargin(head_with_fans)
  117. return head_with_fans_with_adhesion_margin
  118. return None
  119. def getConvexHullBoundary(self) -> Optional[Polygon]:
  120. """Get convex hull of the node
  121. In case of printing all at once this None??
  122. For one at the time this is the area without the head.
  123. """
  124. if self._node is None:
  125. return None
  126. if self._node.callDecoration("isNonPrintingMesh"):
  127. return None
  128. if self._isSingularOneAtATimeNode():
  129. # Printing one at a time and it's not an object in a group
  130. return self._compute2DConvexHull()
  131. return None
  132. def getPrintingArea(self) -> Optional[Polygon]:
  133. """Get the buildplate polygon where will be printed
  134. In case of printing all at once this is the same as convex hull (no individual adhesion)
  135. For one at the time this includes the adhesion area
  136. """
  137. if self._isSingularOneAtATimeNode():
  138. # In one-at-a-time mode, every printed object gets it's own adhesion
  139. printing_area = self.getAdhesionArea()
  140. else:
  141. printing_area = self.getConvexHull()
  142. return printing_area
  143. def recomputeConvexHullDelayed(self) -> None:
  144. """The same as recomputeConvexHull, but using a timer if it was set."""
  145. if self._recompute_convex_hull_timer is not None:
  146. self._recompute_convex_hull_timer.start()
  147. else:
  148. from cura.CuraApplication import CuraApplication
  149. if not self._timer_scheduled_to_be_created:
  150. # The timer is not created and we never scheduled it. Time to create it now!
  151. CuraApplication.getInstance().callLater(self.createRecomputeConvexHullTimer)
  152. # Now we know for sure that the timer has been scheduled for creation, so we can try this again.
  153. CuraApplication.getInstance().callLater(self.recomputeConvexHullDelayed)
  154. def recomputeConvexHull(self) -> None:
  155. if self._node is None or not self.__isDescendant(self._root, self._node):
  156. if self._convex_hull_node:
  157. # Convex hull node still exists, but the node is removed or no longer in the scene.
  158. self._convex_hull_node.setParent(None)
  159. self._convex_hull_node = None
  160. return
  161. if self._convex_hull_node:
  162. self._convex_hull_node.setParent(None)
  163. hull_node = ConvexHullNode.ConvexHullNode(self._node, self.getPrintingArea(), self._raft_thickness, self._root)
  164. self._convex_hull_node = hull_node
  165. def _onSettingValueChanged(self, key: str, property_name: str) -> None:
  166. if property_name != "value": # Not the value that was changed.
  167. return
  168. if key in self._affected_settings:
  169. self._onChanged()
  170. if key in self._influencing_settings:
  171. self._init2DConvexHullCache() # Invalidate the cache.
  172. self._onChanged()
  173. def _init2DConvexHullCache(self) -> None:
  174. # Cache for the group code path in _compute2DConvexHull()
  175. self._2d_convex_hull_group_child_polygon = None # type: Optional[Polygon]
  176. self._2d_convex_hull_group_result = None # type: Optional[Polygon]
  177. # Cache for the mesh code path in _compute2DConvexHull()
  178. self._2d_convex_hull_mesh = None # type: Optional[MeshData]
  179. self._2d_convex_hull_mesh_world_transform = None # type: Optional[Matrix]
  180. self._2d_convex_hull_mesh_result = None # type: Optional[Polygon]
  181. def _compute2DConvexHull(self) -> Optional[Polygon]:
  182. if self._node is None:
  183. return None
  184. if self._node.callDecoration("isGroup"):
  185. points = numpy.zeros((0, 2), dtype = numpy.int32)
  186. for child in self._node.getChildren():
  187. child_hull = child.callDecoration("_compute2DConvexHull")
  188. if child_hull:
  189. try:
  190. points = numpy.append(points, child_hull.getPoints(), axis = 0)
  191. except ValueError:
  192. pass
  193. if points.size < 3:
  194. return None
  195. child_polygon = Polygon(points)
  196. # Check the cache
  197. if child_polygon == self._2d_convex_hull_group_child_polygon:
  198. return self._2d_convex_hull_group_result
  199. convex_hull = child_polygon.getConvexHull() #First calculate the normal convex hull around the points.
  200. offset_hull = self._offsetHull(convex_hull) #Then apply the offset from the settings.
  201. # Store the result in the cache
  202. self._2d_convex_hull_group_child_polygon = child_polygon
  203. self._2d_convex_hull_group_result = offset_hull
  204. return offset_hull
  205. else:
  206. convex_hull = Polygon([])
  207. offset_hull = Polygon([])
  208. mesh = self._node.getMeshData()
  209. if mesh is None:
  210. return Polygon([]) # Node has no mesh data, so just return an empty Polygon.
  211. world_transform = self._node.getWorldTransformation(copy = True)
  212. # Check the cache
  213. if mesh is self._2d_convex_hull_mesh and world_transform == self._2d_convex_hull_mesh_world_transform:
  214. return self._offsetHull(self._2d_convex_hull_mesh_result)
  215. vertex_data = mesh.getConvexHullTransformedVertices(world_transform)
  216. # Don't use data below 0.
  217. # TODO; We need a better check for this as this gives poor results for meshes with long edges.
  218. # Do not throw away vertices: the convex hull may be too small and objects can collide.
  219. # vertex_data = vertex_data[vertex_data[:,1] >= -0.01]
  220. if vertex_data is not None and len(vertex_data) >= 4: # type: ignore # mypy and numpy don't play along well just yet.
  221. # Round the vertex data to 1/10th of a mm, then remove all duplicate vertices
  222. # This is done to greatly speed up further convex hull calculations as the convex hull
  223. # becomes much less complex when dealing with highly detailed models.
  224. vertex_data = numpy.round(vertex_data, 1)
  225. vertex_data = vertex_data[:, [0, 2]] # Drop the Y components to project to 2D.
  226. # Grab the set of unique points.
  227. #
  228. # This basically finds the unique rows in the array by treating them as opaque groups of bytes
  229. # which are as long as the 2 float64s in each row, and giving this view to numpy.unique() to munch.
  230. # See http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array
  231. vertex_byte_view = numpy.ascontiguousarray(vertex_data).view(
  232. numpy.dtype((numpy.void, vertex_data.dtype.itemsize * vertex_data.shape[1])))
  233. _, idx = numpy.unique(vertex_byte_view, return_index = True)
  234. vertex_data = vertex_data[idx] # Select the unique rows by index.
  235. hull = Polygon(vertex_data)
  236. if len(vertex_data) >= 3:
  237. convex_hull = hull.getConvexHull()
  238. offset_hull = self._offsetHull(convex_hull)
  239. # Store the result in the cache
  240. self._2d_convex_hull_mesh = mesh
  241. self._2d_convex_hull_mesh_world_transform = world_transform
  242. self._2d_convex_hull_mesh_result = convex_hull
  243. return offset_hull
  244. def _getHeadAndFans(self) -> Polygon:
  245. if not self._global_stack:
  246. return Polygon()
  247. polygon = Polygon(numpy.array(self._global_stack.getHeadAndFansCoordinates(), numpy.float32))
  248. offset_x = self._getSettingProperty("machine_nozzle_offset_x", "value")
  249. offset_y = self._getSettingProperty("machine_nozzle_offset_y", "value")
  250. return polygon.translate(-offset_x, -offset_y)
  251. def _compute2DConvexHeadFull(self) -> Optional[Polygon]:
  252. convex_hull = self._compute2DConvexHull()
  253. if convex_hull:
  254. return convex_hull.getMinkowskiHull(self._getHeadAndFans())
  255. return None
  256. def _compute2DConvexHeadMin(self) -> Optional[Polygon]:
  257. head_and_fans = self._getHeadAndFans()
  258. mirrored = head_and_fans.mirror([0, 0], [0, 1]).mirror([0, 0], [1, 0]) # Mirror horizontally & vertically.
  259. head_and_fans = self._getHeadAndFans().intersectionConvexHulls(mirrored)
  260. # Min head hull is used for the push free
  261. convex_hull = self._compute2DConvexHull()
  262. if convex_hull:
  263. return convex_hull.getMinkowskiHull(head_and_fans)
  264. return None
  265. def _add2DAdhesionMargin(self, poly: Polygon) -> Polygon:
  266. """Compensate given 2D polygon with adhesion margin
  267. :return: 2D polygon with added margin
  268. """
  269. if not self._global_stack:
  270. return Polygon()
  271. # Compensate for raft/skirt/brim
  272. # Add extra margin depending on adhesion type
  273. adhesion_type = self._global_stack.getProperty("adhesion_type", "value")
  274. max_length_available = 0.5 * min(
  275. self._getSettingProperty("machine_width", "value"),
  276. self._getSettingProperty("machine_depth", "value")
  277. )
  278. if adhesion_type == "raft":
  279. extra_margin = min(max_length_available, max(0, self._getSettingProperty("raft_margin", "value")))
  280. elif adhesion_type == "brim":
  281. extra_margin = min(max_length_available, max(0, self._getSettingProperty("brim_line_count", "value") * self._getSettingProperty("skirt_brim_line_width", "value")))
  282. elif adhesion_type == "none":
  283. extra_margin = 0
  284. elif adhesion_type == "skirt":
  285. extra_margin = min(max_length_available, max(
  286. 0, self._getSettingProperty("skirt_gap", "value") +
  287. self._getSettingProperty("skirt_line_count", "value") * self._getSettingProperty("skirt_brim_line_width", "value")))
  288. else:
  289. raise Exception("Unknown bed adhesion type. Did you forget to update the convex hull calculations for your new bed adhesion type?")
  290. # Adjust head_and_fans with extra margin
  291. if extra_margin > 0:
  292. extra_margin_polygon = Polygon.approximatedCircle(extra_margin)
  293. poly = poly.getMinkowskiHull(extra_margin_polygon)
  294. return poly
  295. def _offsetHull(self, convex_hull: Polygon) -> Polygon:
  296. """Offset the convex hull with settings that influence the collision area.
  297. :param convex_hull: Polygon of the original convex hull.
  298. :return: New Polygon instance that is offset with everything that
  299. influences the collision area.
  300. """
  301. # Shrinkage compensation.
  302. if not self._global_stack: # Should never happen.
  303. return convex_hull
  304. scale_factor = self._global_stack.getProperty("material_shrinkage_percentage_xy", "value") / 100.0
  305. result = convex_hull
  306. if scale_factor != 1.0 and scale_factor > 0 and not self.getNode().callDecoration("isGroup"):
  307. center = None
  308. if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time":
  309. # Find the root node that's placed in the scene; the root of the mesh group.
  310. ancestor = self.getNode()
  311. while ancestor.getParent() != self._root and ancestor.getParent() is not None:
  312. ancestor = ancestor.getParent()
  313. center = ancestor.getBoundingBox().center
  314. else:
  315. # Find the bounding box of the entire scene, which is all one mesh group then.
  316. aabb = None
  317. for printed_node in self._root.getChildren():
  318. if not printed_node.callDecoration("isSliceable") and not printed_node.callDecoration("isGroup"):
  319. continue # Not a printed node.
  320. if aabb is None:
  321. aabb = printed_node.getBoundingBox()
  322. else:
  323. aabb = aabb + printed_node.getBoundingBox()
  324. if aabb:
  325. center = aabb.center
  326. if center:
  327. result = convex_hull.scale(scale_factor, [center.x, center.z]) # Yes, use Z instead of Y. Mixed conventions there with how the OpenGL coordinates are transmitted.
  328. # Horizontal expansion.
  329. horizontal_expansion = max(
  330. self._getSettingProperty("xy_offset", "value"),
  331. self._getSettingProperty("xy_offset_layer_0", "value")
  332. )
  333. # Mold.
  334. mold_width = 0
  335. if self._getSettingProperty("mold_enabled", "value"):
  336. mold_width = self._getSettingProperty("mold_width", "value")
  337. hull_offset = horizontal_expansion + mold_width
  338. if hull_offset > 0: #TODO: Implement Minkowski subtraction for if the offset < 0.
  339. expansion_polygon = Polygon(numpy.array([
  340. [-hull_offset, -hull_offset],
  341. [-hull_offset, hull_offset],
  342. [hull_offset, hull_offset],
  343. [hull_offset, -hull_offset]
  344. ], numpy.float32))
  345. return result.getMinkowskiHull(expansion_polygon)
  346. else:
  347. return result
  348. def _onChanged(self, *args) -> None:
  349. self._raft_thickness = self._build_volume.getRaftThickness()
  350. self.recomputeConvexHullDelayed()
  351. def _onGlobalStackChanged(self) -> None:
  352. if self._global_stack:
  353. self._global_stack.propertyChanged.disconnect(self._onSettingValueChanged)
  354. self._global_stack.containersChanged.disconnect(self._onChanged)
  355. extruders = ExtruderManager.getInstance().getActiveExtruderStacks()
  356. for extruder in extruders:
  357. extruder.propertyChanged.disconnect(self._onSettingValueChanged)
  358. self._global_stack = Application.getInstance().getGlobalContainerStack()
  359. if self._global_stack:
  360. self._global_stack.propertyChanged.connect(self._onSettingValueChanged)
  361. self._global_stack.containersChanged.connect(self._onChanged)
  362. extruders = ExtruderManager.getInstance().getActiveExtruderStacks()
  363. for extruder in extruders:
  364. extruder.propertyChanged.connect(self._onSettingValueChanged)
  365. self._onChanged()
  366. def _getSettingProperty(self, setting_key: str, prop: str = "value") -> Any:
  367. """Private convenience function to get a setting from the correct extruder (as defined by limit_to_extruder property)."""
  368. if self._global_stack is None or self._node is None:
  369. return None
  370. per_mesh_stack = self._node.callDecoration("getStack")
  371. if per_mesh_stack:
  372. return per_mesh_stack.getProperty(setting_key, prop)
  373. extruder_index = self._global_stack.getProperty(setting_key, "limit_to_extruder")
  374. if extruder_index == "-1":
  375. # No limit_to_extruder
  376. extruder_stack_id = self._node.callDecoration("getActiveExtruder")
  377. if not extruder_stack_id:
  378. # Decoration doesn't exist
  379. extruder_stack_id = ExtruderManager.getInstance().extruderIds["0"]
  380. extruder_stack = ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
  381. return extruder_stack.getProperty(setting_key, prop)
  382. else:
  383. # Limit_to_extruder is set. The global stack handles this then
  384. return self._global_stack.getProperty(setting_key, prop)
  385. def __isDescendant(self, root: "SceneNode", node: Optional["SceneNode"]) -> bool:
  386. """Returns True if node is a descendant or the same as the root node."""
  387. if node is None:
  388. return False
  389. if root is node:
  390. return True
  391. return self.__isDescendant(root, node.getParent())
  392. def _isSingularOneAtATimeNode(self) -> bool:
  393. """True if print_sequence is one_at_a_time and _node is not part of a group"""
  394. if self._node is None:
  395. return False
  396. return self._global_stack is not None \
  397. and self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" \
  398. and not self.hasGroupAsParent(self._node)
  399. _affected_settings = [
  400. "adhesion_type", "raft_margin", "print_sequence",
  401. "skirt_gap", "skirt_line_count", "skirt_brim_line_width", "skirt_distance", "brim_line_count"]
  402. _influencing_settings = {"xy_offset", "xy_offset_layer_0", "mold_enabled", "mold_width", "anti_overhang_mesh", "infill_mesh", "cutting_mesh", "material_shrinkage_percentage_xy"}
  403. """Settings that change the convex hull.
  404. If these settings change, the convex hull should be recalculated.
  405. """