ShapeArray.py 6.0 KB

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