ThreeMFReader.py 13 KB

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