ConvexHullDecorator.py 20 KB

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