ThreeMFReader.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import os.path
  4. import zipfile
  5. from typing import List, Optional, Union, TYPE_CHECKING, cast
  6. import Savitar
  7. import numpy
  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.MimeTypeDatabase import MimeTypeDatabase, MimeType
  14. from UM.Scene.GroupDecorator import GroupDecorator
  15. from UM.Scene.SceneNode import SceneNode # For typing.
  16. from cura.CuraApplication import CuraApplication
  17. from cura.Machines.ContainerTree import ContainerTree
  18. from cura.Scene.BuildPlateDecorator import BuildPlateDecorator
  19. from cura.Scene.CuraSceneNode import CuraSceneNode
  20. from cura.Scene.SliceableObjectDecorator import SliceableObjectDecorator
  21. from cura.Scene.ZOffsetDecorator import ZOffsetDecorator
  22. from cura.Settings.ExtruderManager import ExtruderManager
  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. class ThreeMFReader(MeshReader):
  30. """Base implementation for reading 3MF files. Has no support for textures. Only loads meshes!"""
  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. def _createMatrixFromTransformationString(self, transformation: str) -> Matrix:
  45. if transformation == "":
  46. return Matrix()
  47. split_transformation = transformation.split()
  48. temp_mat = Matrix()
  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. """
  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. def _convertSavitarNodeToUMNode(self, savitar_node: Savitar.SceneNode, file_name: str = "") -> Optional[SceneNode]:
  72. """Convenience function that converts a SceneNode object (as obtained from libSavitar) to a scene node.
  73. :returns: Scene node.
  74. """
  75. try:
  76. node_name = savitar_node.getName()
  77. node_id = savitar_node.getId()
  78. except AttributeError:
  79. Logger.log("e", "Outdated version of libSavitar detected! Please update to the newest version!")
  80. node_name = ""
  81. node_id = ""
  82. if node_name == "":
  83. if file_name != "":
  84. node_name = os.path.basename(file_name)
  85. else:
  86. node_name = "Object {}".format(node_id)
  87. active_build_plate = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  88. um_node = CuraSceneNode() # This adds a SettingOverrideDecorator
  89. um_node.addDecorator(BuildPlateDecorator(active_build_plate))
  90. um_node.setName(node_name)
  91. um_node.setId(node_id)
  92. transformation = self._createMatrixFromTransformationString(savitar_node.getTransformation())
  93. um_node.setTransformation(transformation)
  94. mesh_builder = MeshBuilder()
  95. data = numpy.fromstring(savitar_node.getMeshData().getFlatVerticesAsBytes(), dtype=numpy.float32)
  96. vertices = numpy.resize(data, (int(data.size / 3), 3))
  97. mesh_builder.setVertices(vertices)
  98. mesh_builder.calculateNormals(fast=True)
  99. if file_name:
  100. # The filename is used to give the user the option to reload the file if it is changed on disk
  101. # It is only set for the root node of the 3mf file
  102. mesh_builder.setFileName(file_name)
  103. mesh_data = mesh_builder.build()
  104. if len(mesh_data.getVertices()):
  105. um_node.setMeshData(mesh_data)
  106. for child in savitar_node.getChildren():
  107. child_node = self._convertSavitarNodeToUMNode(child)
  108. if child_node:
  109. um_node.addChild(child_node)
  110. if um_node.getMeshData() is None and len(um_node.getChildren()) == 0:
  111. return None
  112. settings = savitar_node.getSettings()
  113. # Add the setting override decorator, so we can add settings to this node.
  114. if settings:
  115. global_container_stack = CuraApplication.getInstance().getGlobalContainerStack()
  116. # Ensure the correct next container for the SettingOverride decorator is set.
  117. if global_container_stack:
  118. default_stack = ExtruderManager.getInstance().getExtruderStack(0)
  119. if default_stack:
  120. um_node.callDecoration("setActiveExtruder", default_stack.getId())
  121. # Get the definition & set it
  122. definition_id = ContainerTree.getInstance().machines[global_container_stack.definition.getId()].quality_definition
  123. um_node.callDecoration("getStack").getTop().setDefinition(definition_id)
  124. setting_container = um_node.callDecoration("getStack").getTop()
  125. for key in settings:
  126. setting_value = settings[key]
  127. # Extruder_nr is a special case.
  128. if key == "extruder_nr":
  129. extruder_stack = ExtruderManager.getInstance().getExtruderStack(int(setting_value))
  130. if extruder_stack:
  131. um_node.callDecoration("setActiveExtruder", extruder_stack.getId())
  132. else:
  133. Logger.log("w", "Unable to find extruder in position %s", setting_value)
  134. continue
  135. setting_container.setProperty(key, "value", setting_value)
  136. if len(um_node.getChildren()) > 0 and um_node.getMeshData() is None:
  137. if len(um_node.getAllChildren()) == 1:
  138. # We don't want groups of one, so move the node up one "level"
  139. child_node = um_node.getChildren()[0]
  140. parent_transformation = um_node.getLocalTransformation()
  141. child_transformation = child_node.getLocalTransformation()
  142. child_node.setTransformation(parent_transformation.multiply(child_transformation))
  143. um_node = cast(CuraSceneNode, um_node.getChildren()[0])
  144. else:
  145. group_decorator = GroupDecorator()
  146. um_node.addDecorator(group_decorator)
  147. um_node.setSelectable(True)
  148. if um_node.getMeshData():
  149. # Assuming that all nodes with mesh data are printable objects
  150. # affects (auto) slicing
  151. sliceable_decorator = SliceableObjectDecorator()
  152. um_node.addDecorator(sliceable_decorator)
  153. return um_node
  154. def _read(self, file_name: str) -> Union[SceneNode, List[SceneNode]]:
  155. result = []
  156. # The base object of 3mf is a zipped archive.
  157. try:
  158. archive = zipfile.ZipFile(file_name, "r")
  159. self._base_name = os.path.basename(file_name)
  160. parser = Savitar.ThreeMFParser()
  161. scene_3mf = parser.parse(archive.open("3D/3dmodel.model").read())
  162. self._unit = scene_3mf.getUnit()
  163. for node in scene_3mf.getSceneNodes():
  164. um_node = self._convertSavitarNodeToUMNode(node, file_name)
  165. if um_node is None:
  166. continue
  167. # compensate for original center position, if object(s) is/are not around its zero position
  168. transform_matrix = Matrix()
  169. mesh_data = um_node.getMeshData()
  170. if mesh_data is not None:
  171. extents = mesh_data.getExtents()
  172. if extents is not None:
  173. center_vector = Vector(extents.center.x, extents.center.y, extents.center.z)
  174. transform_matrix.setByTranslation(center_vector)
  175. transform_matrix.multiply(um_node.getLocalTransformation())
  176. um_node.setTransformation(transform_matrix)
  177. global_container_stack = CuraApplication.getInstance().getGlobalContainerStack()
  178. # Create a transformation Matrix to convert from 3mf worldspace into ours.
  179. # First step: flip the y and z axis.
  180. transformation_matrix = Matrix()
  181. transformation_matrix._data[1, 1] = 0
  182. transformation_matrix._data[1, 2] = 1
  183. transformation_matrix._data[2, 1] = -1
  184. transformation_matrix._data[2, 2] = 0
  185. # Second step: 3MF defines the left corner of the machine as center, whereas cura uses the center of the
  186. # build volume.
  187. if global_container_stack:
  188. translation_vector = Vector(x = -global_container_stack.getProperty("machine_width", "value") / 2,
  189. y = -global_container_stack.getProperty("machine_depth", "value") / 2,
  190. z = 0)
  191. translation_matrix = Matrix()
  192. translation_matrix.setByTranslation(translation_vector)
  193. transformation_matrix.multiply(translation_matrix)
  194. # Third step: 3MF also defines a unit, whereas Cura always assumes mm.
  195. scale_matrix = Matrix()
  196. scale_matrix.setByScaleVector(self._getScaleFromUnit(self._unit))
  197. transformation_matrix.multiply(scale_matrix)
  198. # Pre multiply the transformation with the loaded transformation, so the data is handled correctly.
  199. um_node.setTransformation(um_node.getLocalTransformation().preMultiply(transformation_matrix))
  200. # Check if the model is positioned below the build plate and honor that when loading project files.
  201. node_meshdata = um_node.getMeshData()
  202. if node_meshdata is not None:
  203. aabb = node_meshdata.getExtents(um_node.getWorldTransformation())
  204. if aabb is not None:
  205. minimum_z_value = aabb.minimum.y # y is z in transformation coordinates
  206. if minimum_z_value < 0:
  207. um_node.addDecorator(ZOffsetDecorator())
  208. um_node.callDecoration("setZOffset", minimum_z_value)
  209. result.append(um_node)
  210. except Exception:
  211. Logger.logException("e", "An exception occurred in 3mf reader.")
  212. return []
  213. return result
  214. def _getScaleFromUnit(self, unit: Optional[str]) -> Vector:
  215. """Create a scale vector based on a unit string.
  216. .. The core spec defines the following:
  217. * micron
  218. * millimeter (default)
  219. * centimeter
  220. * inch
  221. * foot
  222. * meter
  223. """
  224. conversion_to_mm = {
  225. "micron": 0.001,
  226. "millimeter": 1,
  227. "centimeter": 10,
  228. "meter": 1000,
  229. "inch": 25.4,
  230. "foot": 304.8
  231. }
  232. if unit is None:
  233. unit = "millimeter"
  234. elif unit not in conversion_to_mm:
  235. Logger.log("w", "Unrecognised unit {unit} used. Assuming mm instead.".format(unit = unit))
  236. unit = "millimeter"
  237. scale = conversion_to_mm[unit]
  238. return Vector(scale, scale, scale)