ConvexHullDecorator.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. # Copyright (c) 2016 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from UM.Application import Application
  4. from UM.Math.Polygon import Polygon
  5. from UM.Scene.SceneNodeDecorator import SceneNodeDecorator
  6. from UM.Settings.ContainerRegistry import ContainerRegistry
  7. from cura.Settings.ExtruderManager import ExtruderManager
  8. from . import ConvexHullNode
  9. import numpy
  10. ## The convex hull decorator is a scene node decorator that adds the convex hull functionality to a scene node.
  11. # If a scene node has a convex hull decorator, it will have a shadow in which other objects can not be printed.
  12. class ConvexHullDecorator(SceneNodeDecorator):
  13. def __init__(self):
  14. super().__init__()
  15. self._convex_hull_node = None
  16. self._init2DConvexHullCache()
  17. self._global_stack = None
  18. self._raft_thickness = 0.0
  19. # For raft thickness, DRY
  20. self._build_volume = Application.getInstance().getBuildVolume()
  21. self._build_volume.raftThicknessChanged.connect(self._onChanged)
  22. Application.getInstance().globalContainerStackChanged.connect(self._onGlobalStackChanged)
  23. Application.getInstance().getController().toolOperationStarted.connect(self._onChanged)
  24. Application.getInstance().getController().toolOperationStopped.connect(self._onChanged)
  25. self._onGlobalStackChanged()
  26. def setNode(self, node):
  27. previous_node = self._node
  28. # Disconnect from previous node signals
  29. if previous_node is not None and node is not previous_node:
  30. previous_node.transformationChanged.disconnect(self._onChanged)
  31. previous_node.parentChanged.disconnect(self._onChanged)
  32. super().setNode(node)
  33. self._node.transformationChanged.connect(self._onChanged)
  34. self._node.parentChanged.connect(self._onChanged)
  35. self._onChanged()
  36. ## Force that a new (empty) object is created upon copy.
  37. def __deepcopy__(self, memo):
  38. return ConvexHullDecorator()
  39. ## Get the unmodified 2D projected convex hull of the node
  40. def getConvexHull(self):
  41. if self._node is None:
  42. return None
  43. if getattr(self._node, "_non_printing_mesh", False):
  44. # infill_mesh, cutting_mesh and anti_overhang_mesh do not need a convex hull
  45. # node._non_printing_mesh is set in SettingOverrideDecorator
  46. return None
  47. hull = self._compute2DConvexHull()
  48. if self._global_stack and self._node:
  49. # Parent can be None if node is just loaded.
  50. if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" and (self._node.getParent() is None or not self._node.getParent().callDecoration("isGroup")):
  51. hull = hull.getMinkowskiHull(Polygon(numpy.array(self._global_stack.getProperty("machine_head_polygon", "value"), numpy.float32)))
  52. hull = self._add2DAdhesionMargin(hull)
  53. return hull
  54. ## Get the convex hull of the node with the full head size
  55. def getConvexHullHeadFull(self):
  56. if self._node is None:
  57. return None
  58. return self._compute2DConvexHeadFull()
  59. ## Get convex hull of the object + head size
  60. # In case of printing all at once this is the same as the convex hull.
  61. # For one at the time this is area with intersection of mirrored head
  62. def getConvexHullHead(self):
  63. if self._node is None:
  64. return None
  65. if self._global_stack:
  66. if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" and (self._node.getParent() is None or not self._node.getParent().callDecoration("isGroup")):
  67. head_with_fans = self._compute2DConvexHeadMin()
  68. head_with_fans_with_adhesion_margin = self._add2DAdhesionMargin(head_with_fans)
  69. return head_with_fans_with_adhesion_margin
  70. return None
  71. ## Get convex hull of the node
  72. # In case of printing all at once this is the same as the convex hull.
  73. # For one at the time this is the area without the head.
  74. def getConvexHullBoundary(self):
  75. if self._node is None:
  76. return None
  77. if self._global_stack:
  78. if self._global_stack.getProperty("print_sequence", "value") == "one_at_a_time" and (self._node.getParent() is None or not self._node.getParent().callDecoration("isGroup")):
  79. # Printing one at a time and it's not an object in a group
  80. return self._compute2DConvexHull()
  81. return None
  82. def recomputeConvexHull(self):
  83. controller = Application.getInstance().getController()
  84. root = controller.getScene().getRoot()
  85. if self._node is None or controller.isToolOperationActive() or not self.__isDescendant(root, self._node):
  86. if self._convex_hull_node:
  87. self._convex_hull_node.setParent(None)
  88. self._convex_hull_node = None
  89. return
  90. convex_hull = self.getConvexHull()
  91. if self._convex_hull_node:
  92. self._convex_hull_node.setParent(None)
  93. hull_node = ConvexHullNode.ConvexHullNode(self._node, convex_hull, self._raft_thickness, root)
  94. self._convex_hull_node = hull_node
  95. def _onSettingValueChanged(self, key, property_name):
  96. if property_name != "value": #Not the value that was changed.
  97. return
  98. if key in self._affected_settings:
  99. self._onChanged()
  100. if key in self._influencing_settings:
  101. self._init2DConvexHullCache() #Invalidate the cache.
  102. self._onChanged()
  103. def _init2DConvexHullCache(self):
  104. # Cache for the group code path in _compute2DConvexHull()
  105. self._2d_convex_hull_group_child_polygon = None
  106. self._2d_convex_hull_group_result = None
  107. # Cache for the mesh code path in _compute2DConvexHull()
  108. self._2d_convex_hull_mesh = None
  109. self._2d_convex_hull_mesh_world_transform = None
  110. self._2d_convex_hull_mesh_result = None
  111. def _compute2DConvexHull(self):
  112. if self._node.callDecoration("isGroup"):
  113. points = numpy.zeros((0, 2), dtype=numpy.int32)
  114. for child in self._node.getChildren():
  115. child_hull = child.callDecoration("_compute2DConvexHull")
  116. if child_hull:
  117. points = numpy.append(points, child_hull.getPoints(), axis = 0)
  118. if points.size < 3:
  119. return None
  120. child_polygon = Polygon(points)
  121. # Check the cache
  122. if child_polygon == self._2d_convex_hull_group_child_polygon:
  123. return self._2d_convex_hull_group_result
  124. convex_hull = child_polygon.getConvexHull() #First calculate the normal convex hull around the points.
  125. offset_hull = self._offsetHull(convex_hull) #Then apply the offset from the settings.
  126. # Store the result in the cache
  127. self._2d_convex_hull_group_child_polygon = child_polygon
  128. self._2d_convex_hull_group_result = offset_hull
  129. return offset_hull
  130. else:
  131. offset_hull = None
  132. mesh = None
  133. world_transform = None
  134. if self._node.getMeshData():
  135. mesh = self._node.getMeshData()
  136. world_transform = self._node.getWorldTransformation()
  137. # Check the cache
  138. if mesh is self._2d_convex_hull_mesh and world_transform == self._2d_convex_hull_mesh_world_transform:
  139. return self._2d_convex_hull_mesh_result
  140. vertex_data = mesh.getConvexHullTransformedVertices(world_transform)
  141. # Don't use data below 0.
  142. # TODO; We need a better check for this as this gives poor results for meshes with long edges.
  143. # Do not throw away vertices: the convex hull may be too small and objects can collide.
  144. # vertex_data = vertex_data[vertex_data[:,1] >= -0.01]
  145. if len(vertex_data) >= 4:
  146. # Round the vertex data to 1/10th of a mm, then remove all duplicate vertices
  147. # This is done to greatly speed up further convex hull calculations as the convex hull
  148. # becomes much less complex when dealing with highly detailed models.
  149. vertex_data = numpy.round(vertex_data, 1)
  150. vertex_data = vertex_data[:, [0, 2]] # Drop the Y components to project to 2D.
  151. # Grab the set of unique points.
  152. #
  153. # This basically finds the unique rows in the array by treating them as opaque groups of bytes
  154. # which are as long as the 2 float64s in each row, and giving this view to numpy.unique() to munch.
  155. # See http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array
  156. vertex_byte_view = numpy.ascontiguousarray(vertex_data).view(
  157. numpy.dtype((numpy.void, vertex_data.dtype.itemsize * vertex_data.shape[1])))
  158. _, idx = numpy.unique(vertex_byte_view, return_index=True)
  159. vertex_data = vertex_data[idx] # Select the unique rows by index.
  160. hull = Polygon(vertex_data)
  161. if len(vertex_data) >= 3:
  162. convex_hull = hull.getConvexHull()
  163. offset_hull = self._offsetHull(convex_hull)
  164. else:
  165. return Polygon([]) # Node has no mesh data, so just return an empty Polygon.
  166. # Store the result in the cache
  167. self._2d_convex_hull_mesh = mesh
  168. self._2d_convex_hull_mesh_world_transform = world_transform
  169. self._2d_convex_hull_mesh_result = offset_hull
  170. return offset_hull
  171. def _getHeadAndFans(self):
  172. return Polygon(numpy.array(self._global_stack.getProperty("machine_head_with_fans_polygon", "value"), numpy.float32))
  173. def _compute2DConvexHeadFull(self):
  174. return self._compute2DConvexHull().getMinkowskiHull(self._getHeadAndFans())
  175. def _compute2DConvexHeadMin(self):
  176. headAndFans = self._getHeadAndFans()
  177. mirrored = headAndFans.mirror([0, 0], [0, 1]).mirror([0, 0], [1, 0]) # Mirror horizontally & vertically.
  178. head_and_fans = self._getHeadAndFans().intersectionConvexHulls(mirrored)
  179. # Min head hull is used for the push free
  180. min_head_hull = self._compute2DConvexHull().getMinkowskiHull(head_and_fans)
  181. return min_head_hull
  182. ## Compensate given 2D polygon with adhesion margin
  183. # \return 2D polygon with added margin
  184. def _add2DAdhesionMargin(self, poly):
  185. # Compensate for raft/skirt/brim
  186. # Add extra margin depending on adhesion type
  187. adhesion_type = self._global_stack.getProperty("adhesion_type", "value")
  188. if adhesion_type == "raft":
  189. extra_margin = max(0, self._getSettingProperty("raft_margin", "value"))
  190. elif adhesion_type == "brim":
  191. extra_margin = max(0, self._getSettingProperty("brim_line_count", "value") * self._getSettingProperty("skirt_brim_line_width", "value"))
  192. elif adhesion_type == "none":
  193. extra_margin = 0
  194. elif adhesion_type == "skirt":
  195. extra_margin = max(
  196. 0, self._getSettingProperty("skirt_gap", "value") +
  197. self._getSettingProperty("skirt_line_count", "value") * self._getSettingProperty("skirt_brim_line_width", "value"))
  198. else:
  199. raise Exception("Unknown bed adhesion type. Did you forget to update the convex hull calculations for your new bed adhesion type?")
  200. # adjust head_and_fans with extra margin
  201. if extra_margin > 0:
  202. extra_margin_polygon = Polygon.approximatedCircle(extra_margin)
  203. poly = poly.getMinkowskiHull(extra_margin_polygon)
  204. return poly
  205. ## Offset the convex hull with settings that influence the collision area.
  206. #
  207. # \param convex_hull Polygon of the original convex hull.
  208. # \return New Polygon instance that is offset with everything that
  209. # influences the collision area.
  210. def _offsetHull(self, convex_hull):
  211. horizontal_expansion = max(
  212. self._getSettingProperty("xy_offset", "value"),
  213. self._getSettingProperty("xy_offset_layer_0", "value")
  214. )
  215. mold_width = 0
  216. if self._getSettingProperty("mold_enabled", "value"):
  217. mold_width = self._getSettingProperty("mold_width", "value")
  218. hull_offset = horizontal_expansion + mold_width
  219. if hull_offset > 0: #TODO: Implement Minkowski subtraction for if the offset < 0.
  220. expansion_polygon = Polygon(numpy.array([
  221. [-hull_offset, -hull_offset],
  222. [-hull_offset, hull_offset],
  223. [hull_offset, hull_offset],
  224. [hull_offset, -hull_offset]
  225. ], numpy.float32))
  226. return convex_hull.getMinkowskiHull(expansion_polygon)
  227. else:
  228. return convex_hull
  229. def _onChanged(self, *args):
  230. self._raft_thickness = self._build_volume.getRaftThickness()
  231. self.recomputeConvexHull()
  232. def _onGlobalStackChanged(self):
  233. if self._global_stack:
  234. self._global_stack.propertyChanged.disconnect(self._onSettingValueChanged)
  235. self._global_stack.containersChanged.disconnect(self._onChanged)
  236. extruders = ExtruderManager.getInstance().getMachineExtruders(self._global_stack.getId())
  237. for extruder in extruders:
  238. extruder.propertyChanged.disconnect(self._onSettingValueChanged)
  239. self._global_stack = Application.getInstance().getGlobalContainerStack()
  240. if self._global_stack:
  241. self._global_stack.propertyChanged.connect(self._onSettingValueChanged)
  242. self._global_stack.containersChanged.connect(self._onChanged)
  243. extruders = ExtruderManager.getInstance().getMachineExtruders(self._global_stack.getId())
  244. for extruder in extruders:
  245. extruder.propertyChanged.connect(self._onSettingValueChanged)
  246. self._onChanged()
  247. ## Private convenience function to get a setting from the correct extruder (as defined by limit_to_extruder property).
  248. def _getSettingProperty(self, setting_key, prop = "value"):
  249. per_mesh_stack = self._node.callDecoration("getStack")
  250. if per_mesh_stack:
  251. return per_mesh_stack.getProperty(setting_key, prop)
  252. extruder_index = self._global_stack.getProperty(setting_key, "limit_to_extruder")
  253. if extruder_index == "-1":
  254. # No limit_to_extruder
  255. extruder_stack_id = self._node.callDecoration("getActiveExtruder")
  256. if not extruder_stack_id:
  257. # Decoration doesn't exist
  258. extruder_stack_id = ExtruderManager.getInstance().extruderIds["0"]
  259. extruder_stack = ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
  260. return extruder_stack.getProperty(setting_key, prop)
  261. else:
  262. # Limit_to_extruder is set. The global stack handles this then
  263. return self._global_stack.getProperty(setting_key, prop)
  264. ## Returns true if node is a descendant or the same as the root node.
  265. def __isDescendant(self, root, node):
  266. if node is None:
  267. return False
  268. if root is node:
  269. return True
  270. return self.__isDescendant(root, node.getParent())
  271. _affected_settings = [
  272. "adhesion_type", "raft_margin", "print_sequence",
  273. "skirt_gap", "skirt_line_count", "skirt_brim_line_width", "skirt_distance", "brim_line_count"]
  274. ## Settings that change the convex hull.
  275. #
  276. # If these settings change, the convex hull should be recalculated.
  277. _influencing_settings = {"xy_offset", "xy_offset_layer_0", "mold_enabled", "mold_width"}