ThreeMFReader.py 11 KB

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