ThreeMFReader.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from typing import List, Optional, Union, TYPE_CHECKING
  4. import os.path
  5. import zipfile
  6. import numpy
  7. import Savitar
  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 UM.Scene.SceneNode import SceneNode #For typing.
  15. from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType
  16. from cura.CuraApplication import CuraApplication
  17. from cura.Machines.ContainerTree import ContainerTree
  18. from cura.Settings.ExtruderManager import ExtruderManager
  19. from cura.Scene.CuraSceneNode import CuraSceneNode
  20. from cura.Scene.BuildPlateDecorator import BuildPlateDecorator
  21. from cura.Scene.SliceableObjectDecorator import SliceableObjectDecorator
  22. from cura.Scene.ZOffsetDecorator import ZOffsetDecorator
  23. try:
  24. if not TYPE_CHECKING:
  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: str) -> Matrix:
  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 scene node.
  72. # \returns Scene node.
  73. def _convertSavitarNodeToUMNode(self, savitar_node: Savitar.SceneNode) -> Optional[SceneNode]:
  74. self._object_count += 1
  75. node_name = "Object %s" % self._object_count
  76. active_build_plate = CuraApplication.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 = CuraApplication.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 = ContainerTree.getInstance().machines[global_container_stack.definition.getId()].quality_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: str) -> Union[SceneNode, List[SceneNode]]:
  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. if extents is not None:
  150. center_vector = Vector(extents.center.x, extents.center.y, extents.center.z)
  151. transform_matrix.setByTranslation(center_vector)
  152. transform_matrix.multiply(um_node.getLocalTransformation())
  153. um_node.setTransformation(transform_matrix)
  154. global_container_stack = CuraApplication.getInstance().getGlobalContainerStack()
  155. # Create a transformation Matrix to convert from 3mf worldspace into ours.
  156. # First step: flip the y and z axis.
  157. transformation_matrix = Matrix()
  158. transformation_matrix._data[1, 1] = 0
  159. transformation_matrix._data[1, 2] = 1
  160. transformation_matrix._data[2, 1] = -1
  161. transformation_matrix._data[2, 2] = 0
  162. # Second step: 3MF defines the left corner of the machine as center, whereas cura uses the center of the
  163. # build volume.
  164. if global_container_stack:
  165. translation_vector = Vector(x = -global_container_stack.getProperty("machine_width", "value") / 2,
  166. y = -global_container_stack.getProperty("machine_depth", "value") / 2,
  167. z = 0)
  168. translation_matrix = Matrix()
  169. translation_matrix.setByTranslation(translation_vector)
  170. transformation_matrix.multiply(translation_matrix)
  171. # Third step: 3MF also defines a unit, whereas Cura always assumes mm.
  172. scale_matrix = Matrix()
  173. scale_matrix.setByScaleVector(self._getScaleFromUnit(self._unit))
  174. transformation_matrix.multiply(scale_matrix)
  175. # Pre multiply the transformation with the loaded transformation, so the data is handled correctly.
  176. um_node.setTransformation(um_node.getLocalTransformation().preMultiply(transformation_matrix))
  177. # Check if the model is positioned below the build plate and honor that when loading project files.
  178. node_meshdata = um_node.getMeshData()
  179. if node_meshdata is not None:
  180. aabb = node_meshdata.getExtents(um_node.getWorldTransformation())
  181. if aabb is not None:
  182. minimum_z_value = aabb.minimum.y # y is z in transformation coordinates
  183. if minimum_z_value < 0:
  184. um_node.addDecorator(ZOffsetDecorator())
  185. um_node.callDecoration("setZOffset", minimum_z_value)
  186. result.append(um_node)
  187. except Exception:
  188. Logger.logException("e", "An exception occurred in 3mf reader.")
  189. return []
  190. return result
  191. ## Create a scale vector based on a unit string.
  192. # The core spec defines the following:
  193. # * micron
  194. # * millimeter (default)
  195. # * centimeter
  196. # * inch
  197. # * foot
  198. # * meter
  199. def _getScaleFromUnit(self, unit: Optional[str]) -> Vector:
  200. conversion_to_mm = {
  201. "micron": 0.001,
  202. "millimeter": 1,
  203. "centimeter": 10,
  204. "meter": 1000,
  205. "inch": 25.4,
  206. "foot": 304.8
  207. }
  208. if unit is None:
  209. unit = "millimeter"
  210. elif unit not in conversion_to_mm:
  211. Logger.log("w", "Unrecognised unit {unit} used. Assuming mm instead.".format(unit = unit))
  212. unit = "millimeter"
  213. scale = conversion_to_mm[unit]
  214. return Vector(scale, scale, scale)