ThreeMFReader.py 10 KB

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