Nest2DArrange.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # Copyright (c) 2020 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import numpy
  4. from pynest2d import Point, Box, Item, NfpConfig, nest
  5. from typing import List, TYPE_CHECKING, Optional, Tuple
  6. from UM.Application import Application
  7. from UM.Decorators import deprecated
  8. from UM.Logger import Logger
  9. from UM.Math.Matrix import Matrix
  10. from UM.Math.Polygon import Polygon
  11. from UM.Math.Quaternion import Quaternion
  12. from UM.Math.Vector import Vector
  13. from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
  14. from UM.Operations.GroupedOperation import GroupedOperation
  15. from UM.Operations.RotateOperation import RotateOperation
  16. from UM.Operations.TranslateOperation import TranslateOperation
  17. from cura.Arranging.Arranger import Arranger
  18. if TYPE_CHECKING:
  19. from UM.Scene.SceneNode import SceneNode
  20. from cura.BuildVolume import BuildVolume
  21. class Nest2DArrange(Arranger):
  22. def __init__(self,
  23. nodes_to_arrange: List["SceneNode"],
  24. build_volume: "BuildVolume",
  25. fixed_nodes: Optional[List["SceneNode"]] = None,
  26. *,
  27. factor: int = 10000,
  28. lock_rotation: bool = False):
  29. """
  30. :param nodes_to_arrange: The list of nodes that need to be moved.
  31. :param build_volume: The build volume that we want to place the nodes in. It gets size & disallowed areas from this.
  32. :param fixed_nodes: List of nods that should not be moved, but should be used when deciding where the others nodes
  33. are placed.
  34. :param factor: The library that we use is int based. This factor defines how accuracte we want it to be.
  35. :param lock_rotation: If set to true the orientation of the object will remain the same
  36. """
  37. super().__init__()
  38. self._nodes_to_arrange = nodes_to_arrange
  39. self._build_volume = build_volume
  40. self._fixed_nodes = fixed_nodes
  41. self._factor = factor
  42. self._lock_rotation = lock_rotation
  43. def findNodePlacement(self) -> Tuple[bool, List[Item]]:
  44. spacing = int(1.5 * self._factor) # 1.5mm spacing.
  45. machine_width = self._build_volume.getWidth()
  46. machine_depth = self._build_volume.getDepth()
  47. build_plate_bounding_box = Box(int(machine_width * self._factor), int(machine_depth * self._factor))
  48. if self._fixed_nodes is None:
  49. self._fixed_nodes = []
  50. # Add all the items we want to arrange
  51. node_items = []
  52. for node in self._nodes_to_arrange:
  53. hull_polygon = node.callDecoration("getConvexHull")
  54. if not hull_polygon or hull_polygon.getPoints is None:
  55. Logger.log("w", "Object {} cannot be arranged because it has no convex hull.".format(node.getName()))
  56. continue
  57. converted_points = []
  58. for point in hull_polygon.getPoints():
  59. converted_points.append(Point(int(point[0] * self._factor), int(point[1] * self._factor)))
  60. item = Item(converted_points)
  61. node_items.append(item)
  62. # Use a tiny margin for the build_plate_polygon (the nesting doesn't like overlapping disallowed areas)
  63. half_machine_width = 0.5 * machine_width - 1
  64. half_machine_depth = 0.5 * machine_depth - 1
  65. build_plate_polygon = Polygon(numpy.array([
  66. [half_machine_width, -half_machine_depth],
  67. [-half_machine_width, -half_machine_depth],
  68. [-half_machine_width, half_machine_depth],
  69. [half_machine_width, half_machine_depth]
  70. ], numpy.float32))
  71. disallowed_areas = self._build_volume.getDisallowedAreas()
  72. num_disallowed_areas_added = 0
  73. for area in disallowed_areas:
  74. converted_points = []
  75. # Clip the disallowed areas so that they don't overlap the bounding box (The arranger chokes otherwise)
  76. clipped_area = area.intersectionConvexHulls(build_plate_polygon)
  77. if clipped_area.getPoints() is not None and len(
  78. clipped_area.getPoints()) > 2: # numpy array has to be explicitly checked against None
  79. for point in clipped_area.getPoints():
  80. converted_points.append(Point(int(point[0] * self._factor), int(point[1] * self._factor)))
  81. disallowed_area = Item(converted_points)
  82. disallowed_area.markAsDisallowedAreaInBin(0)
  83. node_items.append(disallowed_area)
  84. num_disallowed_areas_added += 1
  85. for node in self._fixed_nodes:
  86. converted_points = []
  87. hull_polygon = node.callDecoration("getConvexHull")
  88. if hull_polygon is not None and hull_polygon.getPoints() is not None and len(
  89. hull_polygon.getPoints()) > 2: # numpy array has to be explicitly checked against None
  90. for point in hull_polygon.getPoints():
  91. converted_points.append(Point(int(point[0] * self._factor), int(point[1] * self._factor)))
  92. item = Item(converted_points)
  93. item.markAsFixedInBin(0)
  94. node_items.append(item)
  95. num_disallowed_areas_added += 1
  96. config = NfpConfig()
  97. config.accuracy = 1.0
  98. config.alignment = NfpConfig.Alignment.DONT_ALIGN
  99. if self._lock_rotation:
  100. config.rotations = [0.0]
  101. num_bins = nest(node_items, build_plate_bounding_box, spacing, config)
  102. # Strip the fixed items (previously placed) and the disallowed areas from the results again.
  103. node_items = list(filter(lambda item: not item.isFixed(), node_items))
  104. found_solution_for_all = num_bins == 1
  105. return found_solution_for_all, node_items
  106. def createGroupOperationForArrange(self, add_new_nodes_in_scene: bool = False) -> Tuple[GroupedOperation, int]:
  107. scene_root = Application.getInstance().getController().getScene().getRoot()
  108. found_solution_for_all, node_items = self.findNodePlacement()
  109. not_fit_count = 0
  110. grouped_operation = GroupedOperation()
  111. for node, node_item in zip(self._nodes_to_arrange, node_items):
  112. if add_new_nodes_in_scene:
  113. grouped_operation.addOperation(AddSceneNodeOperation(node, scene_root))
  114. if node_item.binId() == 0:
  115. # We found a spot for it
  116. rotation_matrix = Matrix()
  117. rotation_matrix.setByRotationAxis(node_item.rotation(), Vector(0, -1, 0))
  118. grouped_operation.addOperation(RotateOperation(node, Quaternion.fromMatrix(rotation_matrix)))
  119. grouped_operation.addOperation(
  120. TranslateOperation(node, Vector(node_item.translation().x() / self._factor, 0,
  121. node_item.translation().y() / self._factor)))
  122. else:
  123. # We didn't find a spot
  124. grouped_operation.addOperation(
  125. TranslateOperation(node, Vector(200, node.getWorldPosition().y, -not_fit_count * 20), set_position = True))
  126. not_fit_count += 1
  127. return grouped_operation, not_fit_count
  128. @deprecated("Use the Nest2DArrange class instead")
  129. def findNodePlacement(nodes_to_arrange: List["SceneNode"], build_volume: "BuildVolume",
  130. fixed_nodes: Optional[List["SceneNode"]] = None, factor=10000) -> Tuple[bool, List[Item]]:
  131. arranger = Nest2DArrange(nodes_to_arrange, build_volume, fixed_nodes, factor=factor)
  132. return arranger.findNodePlacement()
  133. @deprecated("Use the Nest2DArrange class instead")
  134. def createGroupOperationForArrange(nodes_to_arrange: List["SceneNode"],
  135. build_volume: "BuildVolume",
  136. fixed_nodes: Optional[List["SceneNode"]] = None,
  137. factor=10000,
  138. add_new_nodes_in_scene: bool = False) -> Tuple[GroupedOperation, int]:
  139. arranger = Nest2DArrange(nodes_to_arrange, build_volume, fixed_nodes, factor=factor)
  140. return arranger.createGroupOperationForArrange(add_new_nodes_in_scene=add_new_nodes_in_scene)
  141. @deprecated("Use the Nest2DArrange class instead")
  142. def arrange(nodes_to_arrange: List["SceneNode"],
  143. build_volume: "BuildVolume",
  144. fixed_nodes: Optional[List["SceneNode"]] = None,
  145. factor=10000,
  146. add_new_nodes_in_scene: bool = False) -> bool:
  147. arranger = Nest2DArrange(nodes_to_arrange, build_volume, fixed_nodes, factor=factor)
  148. return arranger.arrange(add_new_nodes_in_scene=add_new_nodes_in_scene)