ThreeMFReader.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import os.path
  4. import zipfile
  5. import numpy
  6. import Savitar
  7. from UM.Application import Application
  8. from UM.Logger import Logger
  9. from UM.Math.Matrix import Matrix
  10. from UM.Math.Vector import Vector
  11. from UM.Mesh.MeshBuilder import MeshBuilder
  12. from UM.Mesh.MeshReader import MeshReader
  13. from UM.Scene.GroupDecorator import GroupDecorator
  14. from cura.Settings.ExtruderManager import ExtruderManager
  15. from cura.Scene.CuraSceneNode import CuraSceneNode
  16. from cura.Scene.BuildPlateDecorator import BuildPlateDecorator
  17. from cura.Scene.SliceableObjectDecorator import SliceableObjectDecorator
  18. from cura.Scene.ZOffsetDecorator import ZOffsetDecorator
  19. from cura.Machines.QualityManager import getMachineDefinitionIDForQualitySearch
  20. MYPY = False
  21. try:
  22. if not MYPY:
  23. import xml.etree.cElementTree as ET
  24. except ImportError:
  25. Logger.log("w", "Unable to load cElementTree, switching to slower version")
  26. import xml.etree.ElementTree as ET
  27. ## Base implementation for reading 3MF files. Has no support for textures. Only loads meshes!
  28. class ThreeMFReader(MeshReader):
  29. def __init__(self):
  30. super().__init__()
  31. self._supported_extensions = [".3mf"]
  32. self._root = None
  33. self._base_name = ""
  34. self._unit = None
  35. self._object_count = 0 # Used to name objects as there is no node name yet.
  36. def _createMatrixFromTransformationString(self, transformation):
  37. if transformation == "":
  38. return Matrix()
  39. splitted_transformation = transformation.split()
  40. ## Transformation is saved as:
  41. ## M00 M01 M02 0.0
  42. ## M10 M11 M12 0.0
  43. ## M20 M21 M22 0.0
  44. ## M30 M31 M32 1.0
  45. ## We switch the row & cols as that is how everyone else uses matrices!
  46. temp_mat = Matrix()
  47. # Rotation & Scale
  48. temp_mat._data[0, 0] = splitted_transformation[0]
  49. temp_mat._data[1, 0] = splitted_transformation[1]
  50. temp_mat._data[2, 0] = splitted_transformation[2]
  51. temp_mat._data[0, 1] = splitted_transformation[3]
  52. temp_mat._data[1, 1] = splitted_transformation[4]
  53. temp_mat._data[2, 1] = splitted_transformation[5]
  54. temp_mat._data[0, 2] = splitted_transformation[6]
  55. temp_mat._data[1, 2] = splitted_transformation[7]
  56. temp_mat._data[2, 2] = splitted_transformation[8]
  57. # Translation
  58. temp_mat._data[0, 3] = splitted_transformation[9]
  59. temp_mat._data[1, 3] = splitted_transformation[10]
  60. temp_mat._data[2, 3] = splitted_transformation[11]
  61. return temp_mat
  62. ## Convenience function that converts a SceneNode object (as obtained from libSavitar) to a Uranium scene node.
  63. # \returns Uranium scene node.
  64. def _convertSavitarNodeToUMNode(self, savitar_node):
  65. self._object_count += 1
  66. node_name = "Object %s" % self._object_count
  67. active_build_plate = Application.getInstance().getMultiBuildPlateModel().activeBuildPlate
  68. um_node = CuraSceneNode() # This adds a SettingOverrideDecorator
  69. um_node.addDecorator(BuildPlateDecorator(active_build_plate))
  70. um_node.setName(node_name)
  71. transformation = self._createMatrixFromTransformationString(savitar_node.getTransformation())
  72. um_node.setTransformation(transformation)
  73. mesh_builder = MeshBuilder()
  74. data = numpy.fromstring(savitar_node.getMeshData().getFlatVerticesAsBytes(), dtype=numpy.float32)
  75. vertices = numpy.resize(data, (int(data.size / 3), 3))
  76. mesh_builder.setVertices(vertices)
  77. mesh_builder.calculateNormals(fast=True)
  78. mesh_data = mesh_builder.build()
  79. if len(mesh_data.getVertices()):
  80. um_node.setMeshData(mesh_data)
  81. for child in savitar_node.getChildren():
  82. child_node = self._convertSavitarNodeToUMNode(child)
  83. if child_node:
  84. um_node.addChild(child_node)
  85. if um_node.getMeshData() is None and len(um_node.getChildren()) == 0:
  86. return None
  87. settings = savitar_node.getSettings()
  88. # Add the setting override decorator, so we can add settings to this node.
  89. if settings:
  90. global_container_stack = Application.getInstance().getGlobalContainerStack()
  91. # Ensure the correct next container for the SettingOverride decorator is set.
  92. if global_container_stack:
  93. default_stack = ExtruderManager.getInstance().getExtruderStack(0)
  94. if default_stack:
  95. um_node.callDecoration("setActiveExtruder", default_stack.getId())
  96. # Get the definition & set it
  97. definition_id = getMachineDefinitionIDForQualitySearch(global_container_stack.definition)
  98. um_node.callDecoration("getStack").getTop().setDefinition(definition_id)
  99. setting_container = um_node.callDecoration("getStack").getTop()
  100. for key in settings:
  101. setting_value = settings[key]
  102. # Extruder_nr is a special case.
  103. if key == "extruder_nr":
  104. extruder_stack = ExtruderManager.getInstance().getExtruderStack(int(setting_value))
  105. if extruder_stack:
  106. um_node.callDecoration("setActiveExtruder", extruder_stack.getId())
  107. else:
  108. Logger.log("w", "Unable to find extruder in position %s", setting_value)
  109. continue
  110. setting_container.setProperty(key, "value", setting_value)
  111. if len(um_node.getChildren()) > 0 and um_node.getMeshData() is None:
  112. group_decorator = GroupDecorator()
  113. um_node.addDecorator(group_decorator)
  114. um_node.setSelectable(True)
  115. if um_node.getMeshData():
  116. # Assuming that all nodes with mesh data are printable objects
  117. # affects (auto) slicing
  118. sliceable_decorator = SliceableObjectDecorator()
  119. um_node.addDecorator(sliceable_decorator)
  120. return um_node
  121. def read(self, file_name):
  122. result = []
  123. self._object_count = 0 # Used to name objects as there is no node name yet.
  124. # The base object of 3mf is a zipped archive.
  125. try:
  126. archive = zipfile.ZipFile(file_name, "r")
  127. self._base_name = os.path.basename(file_name)
  128. parser = Savitar.ThreeMFParser()
  129. scene_3mf = parser.parse(archive.open("3D/3dmodel.model").read())
  130. self._unit = scene_3mf.getUnit()
  131. for node in scene_3mf.getSceneNodes():
  132. um_node = self._convertSavitarNodeToUMNode(node)
  133. if um_node is None:
  134. continue
  135. # compensate for original center position, if object(s) is/are not around its zero position
  136. transform_matrix = Matrix()
  137. mesh_data = um_node.getMeshData()
  138. if mesh_data is not None:
  139. extents = mesh_data.getExtents()
  140. center_vector = Vector(extents.center.x, extents.center.y, extents.center.z)
  141. transform_matrix.setByTranslation(center_vector)
  142. transform_matrix.multiply(um_node.getLocalTransformation())
  143. um_node.setTransformation(transform_matrix)
  144. global_container_stack = Application.getInstance().getGlobalContainerStack()
  145. # Create a transformation Matrix to convert from 3mf worldspace into ours.
  146. # First step: flip the y and z axis.
  147. transformation_matrix = Matrix()
  148. transformation_matrix._data[1, 1] = 0
  149. transformation_matrix._data[1, 2] = 1
  150. transformation_matrix._data[2, 1] = -1
  151. transformation_matrix._data[2, 2] = 0
  152. # Second step: 3MF defines the left corner of the machine as center, whereas cura uses the center of the
  153. # build volume.
  154. if global_container_stack:
  155. translation_vector = Vector(x=-global_container_stack.getProperty("machine_width", "value") / 2,
  156. y=-global_container_stack.getProperty("machine_depth", "value") / 2,
  157. z=0)
  158. translation_matrix = Matrix()
  159. translation_matrix.setByTranslation(translation_vector)
  160. transformation_matrix.multiply(translation_matrix)
  161. # Third step: 3MF also defines a unit, whereas Cura always assumes mm.
  162. scale_matrix = Matrix()
  163. scale_matrix.setByScaleVector(self._getScaleFromUnit(self._unit))
  164. transformation_matrix.multiply(scale_matrix)
  165. # Pre multiply the transformation with the loaded transformation, so the data is handled correctly.
  166. um_node.setTransformation(um_node.getLocalTransformation().preMultiply(transformation_matrix))
  167. # Check if the model is positioned below the build plate and honor that when loading project files.
  168. if um_node.getMeshData() is not None:
  169. minimum_z_value = um_node.getMeshData().getExtents(um_node.getWorldTransformation()).minimum.y # y is z in transformation coordinates
  170. if minimum_z_value < 0:
  171. um_node.addDecorator(ZOffsetDecorator())
  172. um_node.callDecoration("setZOffset", minimum_z_value)
  173. result.append(um_node)
  174. except Exception:
  175. Logger.logException("e", "An exception occurred in 3mf reader.")
  176. return []
  177. return result
  178. ## Create a scale vector based on a unit string.
  179. # The core spec defines the following:
  180. # * micron
  181. # * millimeter (default)
  182. # * centimeter
  183. # * inch
  184. # * foot
  185. # * meter
  186. def _getScaleFromUnit(self, unit):
  187. if unit is None:
  188. unit = "millimeter"
  189. if unit == "micron":
  190. scale = 0.001
  191. elif unit == "millimeter":
  192. scale = 1
  193. elif unit == "centimeter":
  194. scale = 10
  195. elif unit == "inch":
  196. scale = 25.4
  197. elif unit == "foot":
  198. scale = 304.8
  199. elif unit == "meter":
  200. scale = 1000
  201. else:
  202. Logger.log("w", "Unrecognised unit %s used. Assuming mm instead", unit)
  203. scale = 1
  204. return Vector(scale, scale, scale)