ShapeArray.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import numpy
  4. import copy
  5. from typing import Optional, Tuple, TYPE_CHECKING
  6. from UM.Math.Polygon import Polygon
  7. if TYPE_CHECKING:
  8. from UM.Scene.SceneNode import SceneNode
  9. ## Polygon representation as an array for use with Arrange
  10. class ShapeArray:
  11. def __init__(self, arr: numpy.array, offset_x: float, offset_y: float, scale: float = 1) -> None:
  12. self.arr = arr
  13. self.offset_x = offset_x
  14. self.offset_y = offset_y
  15. self.scale = scale
  16. ## Instantiate from a bunch of vertices
  17. # \param vertices
  18. # \param scale scale the coordinates
  19. @classmethod
  20. def fromPolygon(cls, vertices: numpy.array, scale: float = 1) -> "ShapeArray":
  21. # scale
  22. vertices = vertices * scale
  23. # flip y, x -> x, y
  24. flip_vertices = numpy.zeros((vertices.shape))
  25. flip_vertices[:, 0] = vertices[:, 1]
  26. flip_vertices[:, 1] = vertices[:, 0]
  27. flip_vertices = flip_vertices[::-1]
  28. # offset, we want that all coordinates have positive values
  29. offset_y = int(numpy.amin(flip_vertices[:, 0]))
  30. offset_x = int(numpy.amin(flip_vertices[:, 1]))
  31. flip_vertices[:, 0] = numpy.add(flip_vertices[:, 0], -offset_y)
  32. flip_vertices[:, 1] = numpy.add(flip_vertices[:, 1], -offset_x)
  33. shape = numpy.array([int(numpy.amax(flip_vertices[:, 0])), int(numpy.amax(flip_vertices[:, 1]))])
  34. shape[numpy.where(shape == 0)] = 1
  35. arr = cls.arrayFromPolygon(shape, flip_vertices)
  36. if not numpy.ndarray.any(arr):
  37. # set at least 1 pixel
  38. arr[0][0] = 1
  39. return cls(arr, offset_x, offset_y)
  40. ## Instantiate an offset and hull ShapeArray from a scene node.
  41. # \param node source node where the convex hull must be present
  42. # \param min_offset offset for the offset ShapeArray
  43. # \param scale scale the coordinates
  44. @classmethod
  45. def fromNode(cls, node: "SceneNode", min_offset: float, scale: float = 0.5, include_children: bool = False) -> Tuple[Optional["ShapeArray"], Optional["ShapeArray"]]:
  46. transform = node._transformation
  47. transform_x = transform._data[0][3]
  48. transform_y = transform._data[2][3]
  49. hull_verts = node.callDecoration("getConvexHull")
  50. # If a model is too small then it will not contain any points
  51. if hull_verts is None or not hull_verts.getPoints().any():
  52. return None, None
  53. # For one_at_a_time printing you need the convex hull head.
  54. hull_head_verts = node.callDecoration("getConvexHullHead") or hull_verts
  55. if hull_head_verts is None:
  56. hull_head_verts = Polygon()
  57. # If the child-nodes are included, adjust convex hulls as well:
  58. if include_children:
  59. children = node.getAllChildren()
  60. if not children is None:
  61. for child in children:
  62. # 'Inefficient' combination of convex hulls through known code rather than mess it up:
  63. child_hull = child.callDecoration("getConvexHull")
  64. if not child_hull is None:
  65. hull_verts = hull_verts.unionConvexHulls(child_hull)
  66. child_hull_head = child.callDecoration("getConvexHullHead") or child_hull
  67. if not child_hull_head is None:
  68. hull_head_verts = hull_head_verts.unionConvexHulls(child_hull_head)
  69. offset_verts = hull_head_verts.getMinkowskiHull(Polygon.approximatedCircle(min_offset))
  70. offset_points = copy.deepcopy(offset_verts._points) # x, y
  71. offset_points[:, 0] = numpy.add(offset_points[:, 0], -transform_x)
  72. offset_points[:, 1] = numpy.add(offset_points[:, 1], -transform_y)
  73. offset_shape_arr = ShapeArray.fromPolygon(offset_points, scale = scale)
  74. hull_points = copy.deepcopy(hull_verts._points)
  75. hull_points[:, 0] = numpy.add(hull_points[:, 0], -transform_x)
  76. hull_points[:, 1] = numpy.add(hull_points[:, 1], -transform_y)
  77. hull_shape_arr = ShapeArray.fromPolygon(hull_points, scale = scale) # x, y
  78. return offset_shape_arr, hull_shape_arr
  79. ## Create np.array with dimensions defined by shape
  80. # Fills polygon defined by vertices with ones, all other values zero
  81. # Only works correctly for convex hull vertices
  82. # Originally from: http://stackoverflow.com/questions/37117878/generating-a-filled-polygon-inside-a-numpy-array
  83. # \param shape numpy format shape, [x-size, y-size]
  84. # \param vertices
  85. @classmethod
  86. def arrayFromPolygon(cls, shape: Tuple[int, int], vertices: numpy.array) -> numpy.array:
  87. base_array = numpy.zeros(shape, dtype = numpy.int32) # Initialize your array of zeros
  88. fill = numpy.ones(base_array.shape) * True # Initialize boolean array defining shape fill
  89. # Create check array for each edge segment, combine into fill array
  90. for k in range(vertices.shape[0]):
  91. check_array = cls._check(vertices[k - 1], vertices[k], base_array)
  92. if check_array is not None:
  93. fill = numpy.all([fill, check_array], axis=0)
  94. # Set all values inside polygon to one
  95. base_array[fill] = 1
  96. return base_array
  97. ## Return indices that mark one side of the line, used by arrayFromPolygon
  98. # Uses the line defined by p1 and p2 to check array of
  99. # input indices against interpolated value
  100. # Returns boolean array, with True inside and False outside of shape
  101. # Originally from: http://stackoverflow.com/questions/37117878/generating-a-filled-polygon-inside-a-numpy-array
  102. # \param p1 2-tuple with x, y for point 1
  103. # \param p2 2-tuple with x, y for point 2
  104. # \param base_array boolean array to project the line on
  105. @classmethod
  106. def _check(cls, p1: numpy.array, p2: numpy.array, base_array: numpy.array) -> Optional[numpy.array]:
  107. if p1[0] == p2[0] and p1[1] == p2[1]:
  108. return None
  109. idxs = numpy.indices(base_array.shape) # Create 3D array of indices
  110. p1 = p1.astype(float)
  111. p2 = p2.astype(float)
  112. if p2[0] == p1[0]:
  113. sign = numpy.sign(p2[1] - p1[1])
  114. return idxs[1] * sign
  115. if p2[1] == p1[1]:
  116. sign = numpy.sign(p2[0] - p1[0])
  117. return idxs[1] * sign
  118. # Calculate max column idx for each row idx based on interpolated line between two points
  119. max_col_idx = (idxs[0] - p1[0]) / (p2[0] - p1[0]) * (p2[1] - p1[1]) + p1[1]
  120. sign = numpy.sign(p2[0] - p1[0])
  121. return idxs[1] * sign <= max_col_idx * sign