Nest2DArrange.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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.Logger import Logger
  8. from UM.Math.Matrix import Matrix
  9. from UM.Math.Polygon import Polygon
  10. from UM.Math.Quaternion import Quaternion
  11. from UM.Math.Vector import Vector
  12. from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
  13. from UM.Operations.GroupedOperation import GroupedOperation
  14. from UM.Operations.RotateOperation import RotateOperation
  15. from UM.Operations.TranslateOperation import TranslateOperation
  16. if TYPE_CHECKING:
  17. from UM.Scene.SceneNode import SceneNode
  18. from cura.BuildVolume import BuildVolume
  19. def findNodePlacement(nodes_to_arrange: List["SceneNode"], build_volume: "BuildVolume", fixed_nodes: Optional[List["SceneNode"]] = None, factor = 10000) -> Tuple[bool, List[Item]]:
  20. """
  21. Find placement for a set of scene nodes, but don't actually move them just yet.
  22. :param nodes_to_arrange: The list of nodes that need to be moved.
  23. :param build_volume: The build volume that we want to place the nodes in. It gets size & disallowed areas from this.
  24. :param fixed_nodes: List of nods that should not be moved, but should be used when deciding where the others nodes
  25. are placed.
  26. :param factor: The library that we use is int based. This factor defines how accurate we want it to be.
  27. :return: tuple (found_solution_for_all, node_items)
  28. WHERE
  29. found_solution_for_all: Whether the algorithm found a place on the buildplate for all the objects
  30. node_items: A list of the nodes return by libnest2d, which contain the new positions on the buildplate
  31. """
  32. spacing = int(1.5 * factor) # 1.5mm spacing.
  33. machine_width = build_volume.getWidth()
  34. machine_depth = build_volume.getDepth()
  35. build_plate_bounding_box = Box(machine_width * factor, machine_depth * factor)
  36. if fixed_nodes is None:
  37. fixed_nodes = []
  38. # Add all the items we want to arrange
  39. node_items = []
  40. for node in nodes_to_arrange:
  41. hull_polygon = node.callDecoration("getConvexHull")
  42. if not hull_polygon or hull_polygon.getPoints is None:
  43. Logger.log("w", "Object {} cannot be arranged because it has no convex hull.".format(node.getName()))
  44. continue
  45. converted_points = []
  46. for point in hull_polygon.getPoints():
  47. converted_points.append(Point(int(point[0] * factor), int(point[1] * factor)))
  48. item = Item(converted_points)
  49. node_items.append(item)
  50. # Use a tiny margin for the build_plate_polygon (the nesting doesn't like overlapping disallowed areas)
  51. half_machine_width = 0.5 * machine_width - 1
  52. half_machine_depth = 0.5 * machine_depth - 1
  53. build_plate_polygon = Polygon(numpy.array([
  54. [half_machine_width, -half_machine_depth],
  55. [-half_machine_width, -half_machine_depth],
  56. [-half_machine_width, half_machine_depth],
  57. [half_machine_width, half_machine_depth]
  58. ], numpy.float32))
  59. disallowed_areas = build_volume.getDisallowedAreas()
  60. num_disallowed_areas_added = 0
  61. for area in disallowed_areas:
  62. converted_points = []
  63. # Clip the disallowed areas so that they don't overlap the bounding box (The arranger chokes otherwise)
  64. clipped_area = area.intersectionConvexHulls(build_plate_polygon)
  65. if clipped_area.getPoints() is not None and len(clipped_area.getPoints()) > 2: # numpy array has to be explicitly checked against None
  66. for point in clipped_area.getPoints():
  67. converted_points.append(Point(int(point[0] * factor), int(point[1] * factor)))
  68. disallowed_area = Item(converted_points)
  69. disallowed_area.markAsDisallowedAreaInBin(0)
  70. node_items.append(disallowed_area)
  71. num_disallowed_areas_added += 1
  72. for node in fixed_nodes:
  73. converted_points = []
  74. hull_polygon = node.callDecoration("getConvexHull")
  75. if hull_polygon is not None and hull_polygon.getPoints() is not None and len(hull_polygon.getPoints()) > 2: # numpy array has to be explicitly checked against None
  76. for point in hull_polygon.getPoints():
  77. converted_points.append(Point(point[0] * factor, point[1] * factor))
  78. item = Item(converted_points)
  79. item.markAsFixedInBin(0)
  80. node_items.append(item)
  81. num_disallowed_areas_added += 1
  82. config = NfpConfig()
  83. config.accuracy = 1.0
  84. num_bins = nest(node_items, build_plate_bounding_box, spacing, config)
  85. # Strip the fixed items (previously placed) and the disallowed areas from the results again.
  86. node_items = list(filter(lambda item: not item.isFixed(), node_items))
  87. found_solution_for_all = num_bins == 1
  88. return found_solution_for_all, node_items
  89. def createGroupOperationForArrange(nodes_to_arrange: List["SceneNode"],
  90. build_volume: "BuildVolume",
  91. fixed_nodes: Optional[List["SceneNode"]] = None,
  92. factor = 10000,
  93. add_new_nodes_in_scene: bool = False) -> Tuple[GroupedOperation, int]:
  94. scene_root = Application.getInstance().getController().getScene().getRoot()
  95. found_solution_for_all, node_items = findNodePlacement(nodes_to_arrange, build_volume, fixed_nodes, factor)
  96. not_fit_count = 0
  97. grouped_operation = GroupedOperation()
  98. for node, node_item in zip(nodes_to_arrange, node_items):
  99. if add_new_nodes_in_scene:
  100. grouped_operation.addOperation(AddSceneNodeOperation(node, scene_root))
  101. if node_item.binId() == 0:
  102. # We found a spot for it
  103. rotation_matrix = Matrix()
  104. rotation_matrix.setByRotationAxis(node_item.rotation(), Vector(0, -1, 0))
  105. grouped_operation.addOperation(RotateOperation(node, Quaternion.fromMatrix(rotation_matrix)))
  106. grouped_operation.addOperation(TranslateOperation(node, Vector(node_item.translation().x() / factor, 0,
  107. node_item.translation().y() / factor)))
  108. else:
  109. # We didn't find a spot
  110. grouped_operation.addOperation(
  111. TranslateOperation(node, Vector(200, node.getWorldPosition().y, -not_fit_count * 20), set_position = True))
  112. not_fit_count += 1
  113. return grouped_operation, not_fit_count
  114. def arrange(nodes_to_arrange: List["SceneNode"],
  115. build_volume: "BuildVolume",
  116. fixed_nodes: Optional[List["SceneNode"]] = None,
  117. factor = 10000,
  118. add_new_nodes_in_scene: bool = False) -> bool:
  119. """
  120. Find placement for a set of scene nodes, and move them by using a single grouped operation.
  121. :param nodes_to_arrange: The list of nodes that need to be moved.
  122. :param build_volume: The build volume that we want to place the nodes in. It gets size & disallowed areas from this.
  123. :param fixed_nodes: List of nods that should not be moved, but should be used when deciding where the others nodes
  124. are placed.
  125. :param factor: The library that we use is int based. This factor defines how accuracte we want it to be.
  126. :param add_new_nodes_in_scene: Whether to create new scene nodes before applying the transformations and rotations
  127. :return: found_solution_for_all: Whether the algorithm found a place on the buildplate for all the objects
  128. """
  129. grouped_operation, not_fit_count = createGroupOperationForArrange(nodes_to_arrange, build_volume, fixed_nodes, factor, add_new_nodes_in_scene)
  130. grouped_operation.push()
  131. return not_fit_count == 0