ThreeMFWriter.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Uranium is released under the terms of the LGPLv3 or higher.
  3. from typing import Optional
  4. from UM.Mesh.MeshWriter import MeshWriter
  5. from UM.Math.Vector import Vector
  6. from UM.Logger import Logger
  7. from UM.Math.Matrix import Matrix
  8. from UM.Application import Application
  9. from UM.Scene.SceneNode import SceneNode
  10. from cura.CuraApplication import CuraApplication
  11. import Savitar
  12. import numpy
  13. import datetime
  14. MYPY = False
  15. try:
  16. if not MYPY:
  17. import xml.etree.cElementTree as ET
  18. except ImportError:
  19. Logger.log("w", "Unable to load cElementTree, switching to slower version")
  20. import xml.etree.ElementTree as ET
  21. import zipfile
  22. import UM.Application
  23. from UM.i18n import i18nCatalog
  24. catalog = i18nCatalog("cura")
  25. class ThreeMFWriter(MeshWriter):
  26. def __init__(self):
  27. super().__init__()
  28. self._namespaces = {
  29. "3mf": "http://schemas.microsoft.com/3dmanufacturing/core/2015/02",
  30. "content-types": "http://schemas.openxmlformats.org/package/2006/content-types",
  31. "relationships": "http://schemas.openxmlformats.org/package/2006/relationships",
  32. "cura": "http://software.ultimaker.com/xml/cura/3mf/2015/10"
  33. }
  34. self._unit_matrix_string = self._convertMatrixToString(Matrix())
  35. self._archive = None # type: Optional[zipfile.ZipFile]
  36. self._store_archive = False
  37. def _convertMatrixToString(self, matrix):
  38. result = ""
  39. result += str(matrix._data[0, 0]) + " "
  40. result += str(matrix._data[1, 0]) + " "
  41. result += str(matrix._data[2, 0]) + " "
  42. result += str(matrix._data[0, 1]) + " "
  43. result += str(matrix._data[1, 1]) + " "
  44. result += str(matrix._data[2, 1]) + " "
  45. result += str(matrix._data[0, 2]) + " "
  46. result += str(matrix._data[1, 2]) + " "
  47. result += str(matrix._data[2, 2]) + " "
  48. result += str(matrix._data[0, 3]) + " "
  49. result += str(matrix._data[1, 3]) + " "
  50. result += str(matrix._data[2, 3])
  51. return result
  52. def setStoreArchive(self, store_archive):
  53. """Should we store the archive
  54. Note that if this is true, the archive will not be closed.
  55. The object that set this parameter is then responsible for closing it correctly!
  56. """
  57. self._store_archive = store_archive
  58. def _convertUMNodeToSavitarNode(self, um_node, transformation = Matrix()):
  59. """Convenience function that converts an Uranium SceneNode object to a SavitarSceneNode
  60. :returns: Uranium Scene node.
  61. """
  62. if not isinstance(um_node, SceneNode):
  63. return None
  64. active_build_plate_nr = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  65. if um_node.callDecoration("getBuildPlateNumber") != active_build_plate_nr:
  66. return
  67. savitar_node = Savitar.SceneNode()
  68. savitar_node.setName(um_node.getName())
  69. node_matrix = um_node.getLocalTransformation()
  70. matrix_string = self._convertMatrixToString(node_matrix.preMultiply(transformation))
  71. savitar_node.setTransformation(matrix_string)
  72. mesh_data = um_node.getMeshData()
  73. if mesh_data is not None:
  74. savitar_node.getMeshData().setVerticesFromBytes(mesh_data.getVerticesAsByteArray())
  75. indices_array = mesh_data.getIndicesAsByteArray()
  76. if indices_array is not None:
  77. savitar_node.getMeshData().setFacesFromBytes(indices_array)
  78. else:
  79. savitar_node.getMeshData().setFacesFromBytes(numpy.arange(mesh_data.getVertices().size / 3, dtype=numpy.int32).tostring())
  80. # Handle per object settings (if any)
  81. stack = um_node.callDecoration("getStack")
  82. if stack is not None:
  83. changed_setting_keys = stack.getTop().getAllKeys()
  84. # Ensure that we save the extruder used for this object in a multi-extrusion setup
  85. if stack.getProperty("machine_extruder_count", "value") > 1:
  86. changed_setting_keys.add("extruder_nr")
  87. # Get values for all changed settings & save them.
  88. for key in changed_setting_keys:
  89. savitar_node.setSetting("cura:" + key, str(stack.getProperty(key, "value")))
  90. # Store the metadata.
  91. for key, value in um_node.metadata.items():
  92. savitar_node.setSetting(key, value)
  93. for child_node in um_node.getChildren():
  94. # only save the nodes on the active build plate
  95. if child_node.callDecoration("getBuildPlateNumber") != active_build_plate_nr:
  96. continue
  97. savitar_child_node = self._convertUMNodeToSavitarNode(child_node)
  98. if savitar_child_node is not None:
  99. savitar_node.addChild(savitar_child_node)
  100. return savitar_node
  101. def getArchive(self):
  102. return self._archive
  103. def write(self, stream, nodes, mode = MeshWriter.OutputMode.BinaryMode):
  104. self._archive = None # Reset archive
  105. archive = zipfile.ZipFile(stream, "w", compression = zipfile.ZIP_DEFLATED)
  106. try:
  107. model_file = zipfile.ZipInfo("3D/3dmodel.model")
  108. # Because zipfile is stupid and ignores archive-level compression settings when writing with ZipInfo.
  109. model_file.compress_type = zipfile.ZIP_DEFLATED
  110. # Create content types file
  111. content_types_file = zipfile.ZipInfo("[Content_Types].xml")
  112. content_types_file.compress_type = zipfile.ZIP_DEFLATED
  113. content_types = ET.Element("Types", xmlns = self._namespaces["content-types"])
  114. rels_type = ET.SubElement(content_types, "Default", Extension = "rels", ContentType = "application/vnd.openxmlformats-package.relationships+xml")
  115. model_type = ET.SubElement(content_types, "Default", Extension = "model", ContentType = "application/vnd.ms-package.3dmanufacturing-3dmodel+xml")
  116. # Create _rels/.rels file
  117. relations_file = zipfile.ZipInfo("_rels/.rels")
  118. relations_file.compress_type = zipfile.ZIP_DEFLATED
  119. relations_element = ET.Element("Relationships", xmlns = self._namespaces["relationships"])
  120. model_relation_element = ET.SubElement(relations_element, "Relationship", Target = "/3D/3dmodel.model", Id = "rel0", Type = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel")
  121. savitar_scene = Savitar.Scene()
  122. metadata_to_store = CuraApplication.getInstance().getController().getScene().getMetaData()
  123. for key, value in metadata_to_store.items():
  124. savitar_scene.setMetaDataEntry(key, value)
  125. current_time_string = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  126. if "Application" not in metadata_to_store:
  127. # This might sound a bit strange, but this field should store the original application that created
  128. # the 3mf. So if it was already set, leave it to whatever it was.
  129. savitar_scene.setMetaDataEntry("Application", CuraApplication.getInstance().getApplicationDisplayName())
  130. if "CreationDate" not in metadata_to_store:
  131. savitar_scene.setMetaDataEntry("CreationDate", current_time_string)
  132. savitar_scene.setMetaDataEntry("ModificationDate", current_time_string)
  133. transformation_matrix = Matrix()
  134. transformation_matrix._data[1, 1] = 0
  135. transformation_matrix._data[1, 2] = -1
  136. transformation_matrix._data[2, 1] = 1
  137. transformation_matrix._data[2, 2] = 0
  138. global_container_stack = Application.getInstance().getGlobalContainerStack()
  139. # Second step: 3MF defines the left corner of the machine as center, whereas cura uses the center of the
  140. # build volume.
  141. if global_container_stack:
  142. translation_vector = Vector(x=global_container_stack.getProperty("machine_width", "value") / 2,
  143. y=global_container_stack.getProperty("machine_depth", "value") / 2,
  144. z=0)
  145. translation_matrix = Matrix()
  146. translation_matrix.setByTranslation(translation_vector)
  147. transformation_matrix.preMultiply(translation_matrix)
  148. root_node = UM.Application.Application.getInstance().getController().getScene().getRoot()
  149. for node in nodes:
  150. if node == root_node:
  151. for root_child in node.getChildren():
  152. savitar_node = self._convertUMNodeToSavitarNode(root_child, transformation_matrix)
  153. if savitar_node:
  154. savitar_scene.addSceneNode(savitar_node)
  155. else:
  156. savitar_node = self._convertUMNodeToSavitarNode(node, transformation_matrix)
  157. if savitar_node:
  158. savitar_scene.addSceneNode(savitar_node)
  159. parser = Savitar.ThreeMFParser()
  160. scene_string = parser.sceneToString(savitar_scene)
  161. archive.writestr(model_file, scene_string)
  162. archive.writestr(content_types_file, b'<?xml version="1.0" encoding="UTF-8"?> \n' + ET.tostring(content_types))
  163. archive.writestr(relations_file, b'<?xml version="1.0" encoding="UTF-8"?> \n' + ET.tostring(relations_element))
  164. except Exception as e:
  165. Logger.logException("e", "Error writing zip file")
  166. self.setInformation(catalog.i18nc("@error:zip", "Error writing 3mf file."))
  167. return False
  168. finally:
  169. if not self._store_archive:
  170. archive.close()
  171. else:
  172. self._archive = archive
  173. return True