ThreeMFReader.py 10 KB

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