LayerPolygon.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. from UM.Math.Color import Color
  2. from UM.Application import Application
  3. from typing import Any
  4. import numpy
  5. class LayerPolygon:
  6. NoneType = 0
  7. Inset0Type = 1
  8. InsetXType = 2
  9. SkinType = 3
  10. SupportType = 4
  11. SkirtType = 5
  12. InfillType = 6
  13. SupportInfillType = 7
  14. MoveCombingType = 8
  15. MoveRetractionType = 9
  16. SupportInterfaceType = 10
  17. __jump_map = numpy.logical_or(numpy.logical_or(numpy.arange(11) == NoneType, numpy.arange(11) == MoveCombingType), numpy.arange(11) == MoveRetractionType)
  18. ## LayerPolygon, used in ProcessSlicedLayersJob
  19. # \param extruder
  20. # \param line_types array with line_types
  21. # \param data new_points
  22. # \param line_widths array with line widths
  23. # \param line_thicknesses: array with type as index and thickness as value
  24. def __init__(self, extruder, line_types, data, line_widths, line_thicknesses):
  25. self._extruder = extruder
  26. self._types = line_types
  27. self._data = data
  28. self._line_widths = line_widths
  29. self._line_thicknesses = line_thicknesses
  30. self._vertex_begin = 0
  31. self._vertex_end = 0
  32. self._index_begin = 0
  33. self._index_end = 0
  34. self._jump_mask = self.__jump_map[self._types]
  35. self._jump_count = numpy.sum(self._jump_mask)
  36. self._mesh_line_count = len(self._types)-self._jump_count
  37. self._vertex_count = self._mesh_line_count + numpy.sum( self._types[1:] == self._types[:-1])
  38. # Buffering the colors shouldn't be necessary as it is not
  39. # re-used and can save alot of memory usage.
  40. self._color_map = LayerPolygon.getColorMap()
  41. self._colors = self._color_map[self._types]
  42. # When type is used as index returns true if type == LayerPolygon.InfillType or type == LayerPolygon.SkinType or type == LayerPolygon.SupportInfillType
  43. # Should be generated in better way, not hardcoded.
  44. self._isInfillOrSkinTypeMap = numpy.array([0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1], dtype=numpy.bool)
  45. self._build_cache_line_mesh_mask = None
  46. self._build_cache_needed_points = None
  47. def buildCache(self):
  48. # For the line mesh we do not draw Infill or Jumps. Therefore those lines are filtered out.
  49. self._build_cache_line_mesh_mask = numpy.ones(self._jump_mask.shape, dtype=bool)
  50. mesh_line_count = numpy.sum(self._build_cache_line_mesh_mask)
  51. self._index_begin = 0
  52. self._index_end = mesh_line_count
  53. self._build_cache_needed_points = numpy.ones((len(self._types), 2), dtype=numpy.bool)
  54. # Only if the type of line segment changes do we need to add an extra vertex to change colors
  55. self._build_cache_needed_points[1:, 0][:, numpy.newaxis] = self._types[1:] != self._types[:-1]
  56. # Mark points as unneeded if they are of types we don't want in the line mesh according to the calculated mask
  57. numpy.logical_and(self._build_cache_needed_points, self._build_cache_line_mesh_mask, self._build_cache_needed_points )
  58. self._vertex_begin = 0
  59. self._vertex_end = numpy.sum( self._build_cache_needed_points )
  60. ## Set all the arrays provided by the function caller, representing the LayerPolygon
  61. # The arrays are either by vertex or by indices.
  62. #
  63. # \param vertex_offset : determines where to start and end filling the arrays
  64. # \param index_offset : determines where to start and end filling the arrays
  65. # \param vertices : vertex numpy array to be filled
  66. # \param colors : vertex numpy array to be filled
  67. # \param line_dimensions : vertex numpy array to be filled
  68. # \param extruders : vertex numpy array to be filled
  69. # \param line_types : vertex numpy array to be filled
  70. # \param indices : index numpy array to be filled
  71. def build(self, vertex_offset, index_offset, vertices, colors, line_dimensions, extruders, line_types, indices):
  72. if self._build_cache_line_mesh_mask is None or self._build_cache_needed_points is None:
  73. self.buildCache()
  74. line_mesh_mask = self._build_cache_line_mesh_mask
  75. needed_points_list = self._build_cache_needed_points
  76. # Index to the points we need to represent the line mesh. This is constructed by generating simple
  77. # start and end points for each line. For line segment n these are points n and n+1. Row n reads [n n+1]
  78. # Then then the indices for the points we don't need are thrown away based on the pre-calculated list.
  79. index_list = ( numpy.arange(len(self._types)).reshape((-1, 1)) + numpy.array([[0, 1]]) ).reshape((-1, 1))[needed_points_list.reshape((-1, 1))]
  80. # The relative values of begin and end indices have already been set in buildCache, so we only need to offset them to the parents offset.
  81. self._vertex_begin += vertex_offset
  82. self._vertex_end += vertex_offset
  83. # Points are picked based on the index list to get the vertices needed.
  84. vertices[self._vertex_begin:self._vertex_end, :] = self._data[index_list, :]
  85. # Create an array with colors for each vertex and remove the color data for the points that has been thrown away.
  86. colors[self._vertex_begin:self._vertex_end, :] = numpy.tile(self._colors, (1, 2)).reshape((-1, 4))[needed_points_list.ravel()]
  87. # Create an array with line widths for each vertex.
  88. line_dimensions[self._vertex_begin:self._vertex_end, 0] = numpy.tile(self._line_widths, (1, 2)).reshape((-1, 1))[needed_points_list.ravel()][:, 0]
  89. line_dimensions[self._vertex_begin:self._vertex_end, 1] = numpy.tile(self._line_thicknesses, (1, 2)).reshape((-1, 1))[needed_points_list.ravel()][:, 0]
  90. extruders[self._vertex_begin:self._vertex_end] = self._extruder
  91. # Convert type per vertex to type per line
  92. line_types[self._vertex_begin:self._vertex_end] = numpy.tile(self._types, (1, 2)).reshape((-1, 1))[needed_points_list.ravel()][:, 0]
  93. # The relative values of begin and end indices have already been set in buildCache, so we only need to offset them to the parents offset.
  94. self._index_begin += index_offset
  95. self._index_end += index_offset
  96. indices[self._index_begin:self._index_end, :] = numpy.arange(self._index_end-self._index_begin, dtype=numpy.int32).reshape((-1, 1))
  97. # When the line type changes the index needs to be increased by 2.
  98. indices[self._index_begin:self._index_end, :] += numpy.cumsum(needed_points_list[line_mesh_mask.ravel(), 0], dtype=numpy.int32).reshape((-1, 1))
  99. # Each line segment goes from it's starting point p to p+1, offset by the vertex index.
  100. # The -1 is to compensate for the neccecarily True value of needed_points_list[0,0] which causes an unwanted +1 in cumsum above.
  101. indices[self._index_begin:self._index_end, :] += numpy.array([self._vertex_begin - 1, self._vertex_begin])
  102. self._build_cache_line_mesh_mask = None
  103. self._build_cache_needed_points = None
  104. def getColors(self):
  105. return self._colors
  106. def mapLineTypeToColor(self, line_types):
  107. return self._color_map[line_types]
  108. def isInfillOrSkinType(self, line_types):
  109. return self._isInfillOrSkinTypeMap[line_types]
  110. def lineMeshVertexCount(self):
  111. return (self._vertex_end - self._vertex_begin)
  112. def lineMeshElementCount(self):
  113. return (self._index_end - self._index_begin)
  114. @property
  115. def extruder(self):
  116. return self._extruder
  117. @property
  118. def types(self):
  119. return self._types
  120. @property
  121. def data(self):
  122. return self._data
  123. @property
  124. def elementCount(self):
  125. return (self._index_end - self._index_begin) * 2 # The range of vertices multiplied by 2 since each vertex is used twice
  126. @property
  127. def lineWidths(self):
  128. return self._line_widths
  129. @property
  130. def jumpMask(self):
  131. return self._jump_mask
  132. @property
  133. def meshLineCount(self):
  134. return self._mesh_line_count
  135. @property
  136. def jumpCount(self):
  137. return self._jump_count
  138. # Calculate normals for the entire polygon using numpy.
  139. def getNormals(self):
  140. normals = numpy.copy(self._data)
  141. normals[:, 1] = 0.0 # We are only interested in 2D normals
  142. # Calculate the edges between points.
  143. # The call to numpy.roll shifts the entire array by one so that
  144. # we end up subtracting each next point from the current, wrapping
  145. # around. This gives us the edges from the next point to the current
  146. # point.
  147. normals = numpy.diff(normals, 1, 0)
  148. # Calculate the length of each edge using standard Pythagoras
  149. lengths = numpy.sqrt(normals[:, 0] ** 2 + normals[:, 2] ** 2)
  150. # The normal of a 2D vector is equal to its x and y coordinates swapped
  151. # and then x inverted. This code does that.
  152. normals[:, [0, 2]] = normals[:, [2, 0]]
  153. normals[:, 0] *= -1
  154. # Normalize the normals.
  155. normals[:, 0] /= lengths
  156. normals[:, 2] /= lengths
  157. return normals
  158. __color_map = None # type: numpy.ndarray[Any]
  159. ## Gets the instance of the VersionUpgradeManager, or creates one.
  160. @classmethod
  161. def getColorMap(cls):
  162. if cls.__color_map is None:
  163. theme = Application.getInstance().getTheme()
  164. cls.__color_map = numpy.array([
  165. theme.getColor("layerview_none").getRgbF(), # NoneType
  166. theme.getColor("layerview_inset_0").getRgbF(), # Inset0Type
  167. theme.getColor("layerview_inset_x").getRgbF(), # InsetXType
  168. theme.getColor("layerview_skin").getRgbF(), # SkinType
  169. theme.getColor("layerview_support").getRgbF(), # SupportType
  170. theme.getColor("layerview_skirt").getRgbF(), # SkirtType
  171. theme.getColor("layerview_infill").getRgbF(), # InfillType
  172. theme.getColor("layerview_support_infill").getRgbF(), # SupportInfillType
  173. theme.getColor("layerview_move_combing").getRgbF(), # MoveCombingType
  174. theme.getColor("layerview_move_retraction").getRgbF(), # MoveRetractionType
  175. theme.getColor("layerview_support_interface").getRgbF() # SupportInterfaceType
  176. ])
  177. return cls.__color_map