ConvexHullDecorator.py 15 KB

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