ThreeMFWriter.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. # Copyright (c) 2015-2022 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import json
  4. from typing import Optional, cast, List, Dict
  5. from UM.Mesh.MeshWriter import MeshWriter
  6. from UM.Math.Vector import Vector
  7. from UM.Logger import Logger
  8. from UM.Math.Matrix import Matrix
  9. from UM.Application import Application
  10. from UM.Message import Message
  11. from UM.Resources import Resources
  12. from UM.Scene.SceneNode import SceneNode
  13. from UM.Settings.ContainerRegistry import ContainerRegistry
  14. from UM.Settings.EmptyInstanceContainer import EmptyInstanceContainer
  15. from cura.CuraApplication import CuraApplication
  16. from cura.CuraPackageManager import CuraPackageManager
  17. from cura.Utils.Threading import call_on_qt_thread
  18. from cura.Snapshot import Snapshot
  19. from PyQt6.QtCore import QBuffer
  20. import pySavitar as Savitar
  21. import numpy
  22. import datetime
  23. MYPY = False
  24. try:
  25. if not MYPY:
  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. import zipfile
  31. import UM.Application
  32. from UM.i18n import i18nCatalog
  33. catalog = i18nCatalog("cura")
  34. THUMBNAIL_PATH = "Metadata/thumbnail.png"
  35. MODEL_PATH = "3D/3dmodel.model"
  36. PACKAGE_METADATA_PATH = "Cura/packages.json"
  37. class ThreeMFWriter(MeshWriter):
  38. def __init__(self):
  39. super().__init__()
  40. self._namespaces = {
  41. "3mf": "http://schemas.microsoft.com/3dmanufacturing/core/2015/02",
  42. "content-types": "http://schemas.openxmlformats.org/package/2006/content-types",
  43. "relationships": "http://schemas.openxmlformats.org/package/2006/relationships",
  44. "cura": "http://software.ultimaker.com/xml/cura/3mf/2015/10"
  45. }
  46. self._unit_matrix_string = self._convertMatrixToString(Matrix())
  47. self._archive: Optional[zipfile.ZipFile] = None
  48. self._store_archive = False
  49. def _convertMatrixToString(self, matrix):
  50. result = ""
  51. result += str(matrix._data[0, 0]) + " "
  52. result += str(matrix._data[1, 0]) + " "
  53. result += str(matrix._data[2, 0]) + " "
  54. result += str(matrix._data[0, 1]) + " "
  55. result += str(matrix._data[1, 1]) + " "
  56. result += str(matrix._data[2, 1]) + " "
  57. result += str(matrix._data[0, 2]) + " "
  58. result += str(matrix._data[1, 2]) + " "
  59. result += str(matrix._data[2, 2]) + " "
  60. result += str(matrix._data[0, 3]) + " "
  61. result += str(matrix._data[1, 3]) + " "
  62. result += str(matrix._data[2, 3])
  63. return result
  64. def setStoreArchive(self, store_archive):
  65. """Should we store the archive
  66. Note that if this is true, the archive will not be closed.
  67. The object that set this parameter is then responsible for closing it correctly!
  68. """
  69. self._store_archive = store_archive
  70. def _convertUMNodeToSavitarNode(self, um_node, transformation = Matrix()):
  71. """Convenience function that converts an Uranium SceneNode object to a SavitarSceneNode
  72. :returns: Uranium Scene node.
  73. """
  74. if not isinstance(um_node, SceneNode):
  75. return None
  76. active_build_plate_nr = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  77. if um_node.callDecoration("getBuildPlateNumber") != active_build_plate_nr:
  78. return
  79. savitar_node = Savitar.SceneNode()
  80. savitar_node.setName(um_node.getName())
  81. node_matrix = um_node.getLocalTransformation()
  82. matrix_string = self._convertMatrixToString(node_matrix.preMultiply(transformation))
  83. savitar_node.setTransformation(matrix_string)
  84. mesh_data = um_node.getMeshData()
  85. if mesh_data is not None:
  86. savitar_node.getMeshData().setVerticesFromBytes(mesh_data.getVerticesAsByteArray())
  87. indices_array = mesh_data.getIndicesAsByteArray()
  88. if indices_array is not None:
  89. savitar_node.getMeshData().setFacesFromBytes(indices_array)
  90. else:
  91. savitar_node.getMeshData().setFacesFromBytes(numpy.arange(mesh_data.getVertices().size / 3, dtype=numpy.int32).tostring())
  92. # Handle per object settings (if any)
  93. stack = um_node.callDecoration("getStack")
  94. if stack is not None:
  95. changed_setting_keys = stack.getTop().getAllKeys()
  96. # Ensure that we save the extruder used for this object in a multi-extrusion setup
  97. if stack.getProperty("machine_extruder_count", "value") > 1:
  98. changed_setting_keys.add("extruder_nr")
  99. # Get values for all changed settings & save them.
  100. for key in changed_setting_keys:
  101. savitar_node.setSetting("cura:" + key, str(stack.getProperty(key, "value")))
  102. # Store the metadata.
  103. for key, value in um_node.metadata.items():
  104. savitar_node.setSetting(key, value)
  105. for child_node in um_node.getChildren():
  106. # only save the nodes on the active build plate
  107. if child_node.callDecoration("getBuildPlateNumber") != active_build_plate_nr:
  108. continue
  109. savitar_child_node = self._convertUMNodeToSavitarNode(child_node)
  110. if savitar_child_node is not None:
  111. savitar_node.addChild(savitar_child_node)
  112. return savitar_node
  113. def getArchive(self):
  114. return self._archive
  115. def write(self, stream, nodes, mode = MeshWriter.OutputMode.BinaryMode) -> bool:
  116. self._archive = None # Reset archive
  117. archive = zipfile.ZipFile(stream, "w", compression = zipfile.ZIP_DEFLATED)
  118. try:
  119. model_file = zipfile.ZipInfo(MODEL_PATH)
  120. # Because zipfile is stupid and ignores archive-level compression settings when writing with ZipInfo.
  121. model_file.compress_type = zipfile.ZIP_DEFLATED
  122. # Create content types file
  123. content_types_file = zipfile.ZipInfo("[Content_Types].xml")
  124. content_types_file.compress_type = zipfile.ZIP_DEFLATED
  125. content_types = ET.Element("Types", xmlns = self._namespaces["content-types"])
  126. rels_type = ET.SubElement(content_types, "Default", Extension = "rels", ContentType = "application/vnd.openxmlformats-package.relationships+xml")
  127. model_type = ET.SubElement(content_types, "Default", Extension = "model", ContentType = "application/vnd.ms-package.3dmanufacturing-3dmodel+xml")
  128. # Create _rels/.rels file
  129. relations_file = zipfile.ZipInfo("_rels/.rels")
  130. relations_file.compress_type = zipfile.ZIP_DEFLATED
  131. relations_element = ET.Element("Relationships", xmlns = self._namespaces["relationships"])
  132. model_relation_element = ET.SubElement(relations_element, "Relationship", Target = "/" + MODEL_PATH, Id = "rel0", Type = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel")
  133. # Attempt to add a thumbnail
  134. snapshot = self._createSnapshot()
  135. if snapshot:
  136. thumbnail_buffer = QBuffer()
  137. thumbnail_buffer.open(QBuffer.OpenModeFlag.ReadWrite)
  138. snapshot.save(thumbnail_buffer, "PNG")
  139. thumbnail_file = zipfile.ZipInfo(THUMBNAIL_PATH)
  140. # Don't try to compress snapshot file, because the PNG is pretty much as compact as it will get
  141. archive.writestr(thumbnail_file, thumbnail_buffer.data())
  142. # Add PNG to content types file
  143. thumbnail_type = ET.SubElement(content_types, "Default", Extension = "png", ContentType = "image/png")
  144. # Add thumbnail relation to _rels/.rels file
  145. thumbnail_relation_element = ET.SubElement(relations_element, "Relationship", Target = "/" + THUMBNAIL_PATH, Id = "rel1", Type = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail")
  146. # Write material metadata
  147. material_metadata = self._getMaterialPackageMetadata()
  148. self._storeMetadataJson({"packages": material_metadata}, archive, PACKAGE_METADATA_PATH)
  149. savitar_scene = Savitar.Scene()
  150. scene_metadata = CuraApplication.getInstance().getController().getScene().getMetaData()
  151. for key, value in scene_metadata.items():
  152. savitar_scene.setMetaDataEntry(key, value)
  153. current_time_string = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  154. if "Application" not in scene_metadata:
  155. # This might sound a bit strange, but this field should store the original application that created
  156. # the 3mf. So if it was already set, leave it to whatever it was.
  157. savitar_scene.setMetaDataEntry("Application", CuraApplication.getInstance().getApplicationDisplayName())
  158. if "CreationDate" not in scene_metadata:
  159. savitar_scene.setMetaDataEntry("CreationDate", current_time_string)
  160. savitar_scene.setMetaDataEntry("ModificationDate", current_time_string)
  161. transformation_matrix = Matrix()
  162. transformation_matrix._data[1, 1] = 0
  163. transformation_matrix._data[1, 2] = -1
  164. transformation_matrix._data[2, 1] = 1
  165. transformation_matrix._data[2, 2] = 0
  166. global_container_stack = Application.getInstance().getGlobalContainerStack()
  167. # Second step: 3MF defines the left corner of the machine as center, whereas cura uses the center of the
  168. # build volume.
  169. if global_container_stack:
  170. translation_vector = Vector(x=global_container_stack.getProperty("machine_width", "value") / 2,
  171. y=global_container_stack.getProperty("machine_depth", "value") / 2,
  172. z=0)
  173. translation_matrix = Matrix()
  174. translation_matrix.setByTranslation(translation_vector)
  175. transformation_matrix.preMultiply(translation_matrix)
  176. root_node = UM.Application.Application.getInstance().getController().getScene().getRoot()
  177. for node in nodes:
  178. if node == root_node:
  179. for root_child in node.getChildren():
  180. savitar_node = self._convertUMNodeToSavitarNode(root_child, transformation_matrix)
  181. if savitar_node:
  182. savitar_scene.addSceneNode(savitar_node)
  183. else:
  184. savitar_node = self._convertUMNodeToSavitarNode(node, transformation_matrix)
  185. if savitar_node:
  186. savitar_scene.addSceneNode(savitar_node)
  187. parser = Savitar.ThreeMFParser()
  188. scene_string = parser.sceneToString(savitar_scene)
  189. archive.writestr(model_file, scene_string)
  190. archive.writestr(content_types_file, b'<?xml version="1.0" encoding="UTF-8"?> \n' + ET.tostring(content_types))
  191. archive.writestr(relations_file, b'<?xml version="1.0" encoding="UTF-8"?> \n' + ET.tostring(relations_element))
  192. except Exception as e:
  193. Logger.logException("e", "Error writing zip file")
  194. self.setInformation(catalog.i18nc("@error:zip", "Error writing 3mf file."))
  195. return False
  196. finally:
  197. if not self._store_archive:
  198. archive.close()
  199. else:
  200. self._archive = archive
  201. return True
  202. @staticmethod
  203. def _storeMetadataJson(metadata: Dict[str, List[Dict[str, str]]], archive: zipfile.ZipFile, path: str) -> None:
  204. """Stores metadata inside archive path as json file"""
  205. metadata_file = zipfile.ZipInfo(path)
  206. # We have to set the compress type of each file as well (it doesn't keep the type of the entire archive)
  207. metadata_file.compress_type = zipfile.ZIP_DEFLATED
  208. archive.writestr(metadata_file, json.dumps(metadata, separators=(", ", ": "), indent=4, skipkeys=True, ensure_ascii=False))
  209. @staticmethod
  210. def _getMaterialPackageMetadata() -> List[Dict[str, str]]:
  211. """Get metadata for installed materials in active extruder stack, this does not include bundled materials.
  212. :return: List of material metadata dictionaries.
  213. """
  214. metadata = {}
  215. package_manager = cast(CuraPackageManager, CuraApplication.getInstance().getPackageManager())
  216. for extruder in CuraApplication.getInstance().getExtruderManager().getActiveExtruderStacks():
  217. if not extruder.isEnabled:
  218. # Don't export materials not in use
  219. continue
  220. if isinstance(extruder.material, type(ContainerRegistry.getInstance().getEmptyInstanceContainer())):
  221. # This is an empty material container, no material to export
  222. continue
  223. if package_manager.isMaterialBundled(extruder.material.getFileName(), extruder.material.getMetaDataEntry("GUID")):
  224. # Don't export bundled materials
  225. continue
  226. package_id = package_manager.getMaterialFilePackageId(extruder.material.getFileName(), extruder.material.getMetaDataEntry("GUID"))
  227. package_data = package_manager.getInstalledPackageInfo(package_id)
  228. # We failed to find the package for this material
  229. if not package_data:
  230. Logger.info(f"Could not find package for material in extruder {extruder.id}, skipping.")
  231. continue
  232. material_metadata = {"id": package_id,
  233. "display_name": package_data.get("display_name") if package_data.get("display_name") else "",
  234. "package_version": package_data.get("package_version") if package_data.get("package_version") else "",
  235. "sdk_version_semver": package_data.get("sdk_version_semver") if package_data.get("sdk_version_semver") else ""}
  236. metadata[package_id] = material_metadata
  237. # Storing in a dict and fetching values to avoid duplicates
  238. return list(metadata.values())
  239. @call_on_qt_thread # must be called from the main thread because of OpenGL
  240. def _createSnapshot(self):
  241. Logger.log("d", "Creating thumbnail image...")
  242. if not CuraApplication.getInstance().isVisible:
  243. Logger.log("w", "Can't create snapshot when renderer not initialized.")
  244. return None
  245. try:
  246. snapshot = Snapshot.snapshot(width = 300, height = 300)
  247. except:
  248. Logger.logException("w", "Failed to create snapshot image")
  249. return None
  250. return snapshot