ThreeMFWriter.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. # Copyright (c) 2015-2022 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import json
  4. import re
  5. from typing import Optional, cast, List, Dict, Pattern, Set
  6. from UM.Mesh.MeshWriter import MeshWriter
  7. from UM.Math.Vector import Vector
  8. from UM.Logger import Logger
  9. from UM.Math.Matrix import Matrix
  10. from UM.Application import Application
  11. from UM.Scene.SceneNode import SceneNode
  12. from UM.Settings.ContainerRegistry import ContainerRegistry
  13. from cura.CuraApplication import CuraApplication
  14. from cura.CuraPackageManager import CuraPackageManager
  15. from cura.Settings import CuraContainerStack
  16. from cura.Utils.Threading import call_on_qt_thread
  17. from cura.Snapshot import Snapshot
  18. from PyQt6.QtCore import QBuffer
  19. import pySavitar as Savitar
  20. import numpy
  21. import datetime
  22. MYPY = False
  23. try:
  24. if not MYPY:
  25. import xml.etree.cElementTree as ET
  26. except ImportError:
  27. Logger.log("w", "Unable to load cElementTree, switching to slower version")
  28. import xml.etree.ElementTree as ET
  29. import zipfile
  30. import UM.Application
  31. from UM.i18n import i18nCatalog
  32. catalog = i18nCatalog("cura")
  33. THUMBNAIL_PATH = "Metadata/thumbnail.png"
  34. MODEL_PATH = "3D/3dmodel.model"
  35. PACKAGE_METADATA_PATH = "Cura/packages.json"
  36. class ThreeMFWriter(MeshWriter):
  37. def __init__(self):
  38. super().__init__()
  39. self._namespaces = {
  40. "3mf": "http://schemas.microsoft.com/3dmanufacturing/core/2015/02",
  41. "content-types": "http://schemas.openxmlformats.org/package/2006/content-types",
  42. "relationships": "http://schemas.openxmlformats.org/package/2006/relationships",
  43. "cura": "http://software.ultimaker.com/xml/cura/3mf/2015/10"
  44. }
  45. self._unit_matrix_string = ThreeMFWriter._convertMatrixToString(Matrix())
  46. self._archive: Optional[zipfile.ZipFile] = None
  47. self._store_archive = False
  48. @staticmethod
  49. def _convertMatrixToString(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. @staticmethod
  71. def _convertUMNodeToSavitarNode(um_node, transformation=Matrix()):
  72. """Convenience function that converts an Uranium SceneNode object to a SavitarSceneNode
  73. :returns: Uranium Scene node.
  74. """
  75. if not isinstance(um_node, SceneNode):
  76. return None
  77. active_build_plate_nr = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  78. if um_node.callDecoration("getBuildPlateNumber") != active_build_plate_nr:
  79. return
  80. savitar_node = Savitar.SceneNode()
  81. savitar_node.setName(um_node.getName())
  82. node_matrix = Matrix()
  83. mesh_data = um_node.getMeshData()
  84. # compensate for original center position, if object(s) is/are not around its zero position
  85. if mesh_data is not None:
  86. extents = mesh_data.getExtents()
  87. if extents is not None:
  88. # We use a different coordinate space while writing, so flip Z and Y
  89. center_vector = Vector(extents.center.x, extents.center.z, extents.center.y)
  90. node_matrix.setByTranslation(center_vector)
  91. node_matrix.multiply(um_node.getLocalTransformation())
  92. matrix_string = ThreeMFWriter._convertMatrixToString(node_matrix.preMultiply(transformation))
  93. savitar_node.setTransformation(matrix_string)
  94. if mesh_data is not None:
  95. savitar_node.getMeshData().setVerticesFromBytes(mesh_data.getVerticesAsByteArray())
  96. indices_array = mesh_data.getIndicesAsByteArray()
  97. if indices_array is not None:
  98. savitar_node.getMeshData().setFacesFromBytes(indices_array)
  99. else:
  100. savitar_node.getMeshData().setFacesFromBytes(numpy.arange(mesh_data.getVertices().size / 3, dtype=numpy.int32).tostring())
  101. # Handle per object settings (if any)
  102. stack = um_node.callDecoration("getStack")
  103. if stack is not None:
  104. changed_setting_keys = stack.getTop().getAllKeys()
  105. # Ensure that we save the extruder used for this object in a multi-extrusion setup
  106. if stack.getProperty("machine_extruder_count", "value") > 1:
  107. changed_setting_keys.add("extruder_nr")
  108. # Get values for all changed settings & save them.
  109. for key in changed_setting_keys:
  110. savitar_node.setSetting("cura:" + key, str(stack.getProperty(key, "value")))
  111. # Store the metadata.
  112. for key, value in um_node.metadata.items():
  113. savitar_node.setSetting(key, value)
  114. for child_node in um_node.getChildren():
  115. # only save the nodes on the active build plate
  116. if child_node.callDecoration("getBuildPlateNumber") != active_build_plate_nr:
  117. continue
  118. savitar_child_node = ThreeMFWriter._convertUMNodeToSavitarNode(child_node)
  119. if savitar_child_node is not None:
  120. savitar_node.addChild(savitar_child_node)
  121. return savitar_node
  122. def getArchive(self):
  123. return self._archive
  124. def write(self, stream, nodes, mode = MeshWriter.OutputMode.BinaryMode) -> bool:
  125. self._archive = None # Reset archive
  126. archive = zipfile.ZipFile(stream, "w", compression = zipfile.ZIP_DEFLATED)
  127. try:
  128. model_file = zipfile.ZipInfo(MODEL_PATH)
  129. # Because zipfile is stupid and ignores archive-level compression settings when writing with ZipInfo.
  130. model_file.compress_type = zipfile.ZIP_DEFLATED
  131. # Create content types file
  132. content_types_file = zipfile.ZipInfo("[Content_Types].xml")
  133. content_types_file.compress_type = zipfile.ZIP_DEFLATED
  134. content_types = ET.Element("Types", xmlns = self._namespaces["content-types"])
  135. rels_type = ET.SubElement(content_types, "Default", Extension = "rels", ContentType = "application/vnd.openxmlformats-package.relationships+xml")
  136. model_type = ET.SubElement(content_types, "Default", Extension = "model", ContentType = "application/vnd.ms-package.3dmanufacturing-3dmodel+xml")
  137. # Create _rels/.rels file
  138. relations_file = zipfile.ZipInfo("_rels/.rels")
  139. relations_file.compress_type = zipfile.ZIP_DEFLATED
  140. relations_element = ET.Element("Relationships", xmlns = self._namespaces["relationships"])
  141. model_relation_element = ET.SubElement(relations_element, "Relationship", Target = "/" + MODEL_PATH, Id = "rel0", Type = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel")
  142. # Attempt to add a thumbnail
  143. snapshot = self._createSnapshot()
  144. if snapshot:
  145. thumbnail_buffer = QBuffer()
  146. thumbnail_buffer.open(QBuffer.OpenModeFlag.ReadWrite)
  147. snapshot.save(thumbnail_buffer, "PNG")
  148. thumbnail_file = zipfile.ZipInfo(THUMBNAIL_PATH)
  149. # Don't try to compress snapshot file, because the PNG is pretty much as compact as it will get
  150. archive.writestr(thumbnail_file, thumbnail_buffer.data())
  151. # Add PNG to content types file
  152. thumbnail_type = ET.SubElement(content_types, "Default", Extension="png", ContentType="image/png")
  153. # Add thumbnail relation to _rels/.rels file
  154. thumbnail_relation_element = ET.SubElement(relations_element, "Relationship",
  155. Target="/" + THUMBNAIL_PATH, Id="rel1",
  156. Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/thumbnail")
  157. # Write material metadata
  158. packages_metadata = self._getMaterialPackageMetadata() + self._getPluginPackageMetadata()
  159. self._storeMetadataJson({"packages": packages_metadata}, archive, PACKAGE_METADATA_PATH)
  160. savitar_scene = Savitar.Scene()
  161. scene_metadata = CuraApplication.getInstance().getController().getScene().getMetaData()
  162. for key, value in scene_metadata.items():
  163. savitar_scene.setMetaDataEntry(key, value)
  164. current_time_string = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  165. if "Application" not in scene_metadata:
  166. # This might sound a bit strange, but this field should store the original application that created
  167. # the 3mf. So if it was already set, leave it to whatever it was.
  168. savitar_scene.setMetaDataEntry("Application", CuraApplication.getInstance().getApplicationDisplayName())
  169. if "CreationDate" not in scene_metadata:
  170. savitar_scene.setMetaDataEntry("CreationDate", current_time_string)
  171. savitar_scene.setMetaDataEntry("ModificationDate", current_time_string)
  172. transformation_matrix = Matrix()
  173. transformation_matrix._data[1, 1] = 0
  174. transformation_matrix._data[1, 2] = -1
  175. transformation_matrix._data[2, 1] = 1
  176. transformation_matrix._data[2, 2] = 0
  177. global_container_stack = Application.getInstance().getGlobalContainerStack()
  178. # Second step: 3MF defines the left corner of the machine as center, whereas cura uses the center of the
  179. # build volume.
  180. if global_container_stack:
  181. translation_vector = Vector(x=global_container_stack.getProperty("machine_width", "value") / 2,
  182. y=global_container_stack.getProperty("machine_depth", "value") / 2,
  183. z=0)
  184. translation_matrix = Matrix()
  185. translation_matrix.setByTranslation(translation_vector)
  186. transformation_matrix.preMultiply(translation_matrix)
  187. root_node = UM.Application.Application.getInstance().getController().getScene().getRoot()
  188. for node in nodes:
  189. if node == root_node:
  190. for root_child in node.getChildren():
  191. savitar_node = ThreeMFWriter._convertUMNodeToSavitarNode(root_child, transformation_matrix)
  192. if savitar_node:
  193. savitar_scene.addSceneNode(savitar_node)
  194. else:
  195. savitar_node = self._convertUMNodeToSavitarNode(node, transformation_matrix)
  196. if savitar_node:
  197. savitar_scene.addSceneNode(savitar_node)
  198. parser = Savitar.ThreeMFParser()
  199. scene_string = parser.sceneToString(savitar_scene)
  200. archive.writestr(model_file, scene_string)
  201. archive.writestr(content_types_file, b'<?xml version="1.0" encoding="UTF-8"?> \n' + ET.tostring(content_types))
  202. archive.writestr(relations_file, b'<?xml version="1.0" encoding="UTF-8"?> \n' + ET.tostring(relations_element))
  203. except Exception as error:
  204. Logger.logException("e", "Error writing zip file")
  205. self.setInformation(str(error))
  206. return False
  207. finally:
  208. if not self._store_archive:
  209. archive.close()
  210. else:
  211. self._archive = archive
  212. return True
  213. @staticmethod
  214. def _storeMetadataJson(metadata: Dict[str, List[Dict[str, str]]], archive: zipfile.ZipFile, path: str) -> None:
  215. """Stores metadata inside archive path as json file"""
  216. metadata_file = zipfile.ZipInfo(path)
  217. # We have to set the compress type of each file as well (it doesn't keep the type of the entire archive)
  218. metadata_file.compress_type = zipfile.ZIP_DEFLATED
  219. archive.writestr(metadata_file,
  220. json.dumps(metadata, separators=(", ", ": "), indent=4, skipkeys=True, ensure_ascii=False))
  221. @staticmethod
  222. def _getPluginPackageMetadata() -> List[Dict[str, str]]:
  223. """Get metadata for all backend plugins that are used in the project.
  224. :return: List of material metadata dictionaries.
  225. """
  226. backend_plugin_enum_value_regex = re.compile(
  227. r"PLUGIN::(?P<plugin_id>\w+)@(?P<version>\d+.\d+.\d+)::(?P<value>\w+)")
  228. # This regex parses enum values to find if they contain custom
  229. # backend engine values. These custom enum values are in the format
  230. # PLUGIN::<plugin_id>@<version>::<value>
  231. # where
  232. # - plugin_id is the id of the plugin
  233. # - version is in the semver format
  234. # - value is the value of the enum
  235. plugin_ids = set()
  236. def addPluginIdsInStack(stack: CuraContainerStack) -> None:
  237. for key in stack.getAllKeys():
  238. value = str(stack.getProperty(key, "value"))
  239. for plugin_id, _version, _value in backend_plugin_enum_value_regex.findall(value):
  240. plugin_ids.add(plugin_id)
  241. # Go through all stacks and find all the plugin id contained in the project
  242. global_stack = CuraApplication.getInstance().getMachineManager().activeMachine
  243. addPluginIdsInStack(global_stack)
  244. for container in global_stack.getContainers():
  245. addPluginIdsInStack(container)
  246. for extruder_stack in global_stack.extruderList:
  247. addPluginIdsInStack(extruder_stack)
  248. for container in extruder_stack.getContainers():
  249. addPluginIdsInStack(container)
  250. metadata = {}
  251. package_manager = cast(CuraPackageManager, CuraApplication.getInstance().getPackageManager())
  252. for plugin_id in plugin_ids:
  253. package_data = package_manager.getInstalledPackageInfo(plugin_id)
  254. metadata[plugin_id] = {
  255. "id": plugin_id,
  256. "display_name": package_data.get("display_name") if package_data.get("display_name") else "",
  257. "package_version": package_data.get("package_version") if package_data.get("package_version") else "",
  258. "sdk_version_semver": package_data.get("sdk_version_semver") if package_data.get(
  259. "sdk_version_semver") else "",
  260. "type": "plugin",
  261. }
  262. # Storing in a dict and fetching values to avoid duplicates
  263. return list(metadata.values())
  264. @staticmethod
  265. def _getMaterialPackageMetadata() -> List[Dict[str, str]]:
  266. """Get metadata for installed materials in active extruder stack, this does not include bundled materials.
  267. :return: List of material metadata dictionaries.
  268. """
  269. metadata = {}
  270. package_manager = cast(CuraPackageManager, CuraApplication.getInstance().getPackageManager())
  271. for extruder in CuraApplication.getInstance().getExtruderManager().getActiveExtruderStacks():
  272. if not extruder.isEnabled:
  273. # Don't export materials not in use
  274. continue
  275. if isinstance(extruder.material, type(ContainerRegistry.getInstance().getEmptyInstanceContainer())):
  276. # This is an empty material container, no material to export
  277. continue
  278. if package_manager.isMaterialBundled(extruder.material.getFileName(), extruder.material.getMetaDataEntry("GUID")):
  279. # Don't export bundled materials
  280. continue
  281. package_id = package_manager.getMaterialFilePackageId(extruder.material.getFileName(),
  282. extruder.material.getMetaDataEntry("GUID"))
  283. package_data = package_manager.getInstalledPackageInfo(package_id)
  284. # We failed to find the package for this material
  285. if not package_data:
  286. Logger.info(f"Could not find package for material in extruder {extruder.id}, skipping.")
  287. continue
  288. material_metadata = {
  289. "id": package_id,
  290. "display_name": package_data.get("display_name") if package_data.get("display_name") else "",
  291. "package_version": package_data.get("package_version") if package_data.get("package_version") else "",
  292. "sdk_version_semver": package_data.get("sdk_version_semver") if package_data.get(
  293. "sdk_version_semver") else "",
  294. "type": "material",
  295. }
  296. metadata[package_id] = material_metadata
  297. # Storing in a dict and fetching values to avoid duplicates
  298. return list(metadata.values())
  299. @call_on_qt_thread # must be called from the main thread because of OpenGL
  300. def _createSnapshot(self):
  301. Logger.log("d", "Creating thumbnail image...")
  302. if not CuraApplication.getInstance().isVisible:
  303. Logger.log("w", "Can't create snapshot when renderer not initialized.")
  304. return None
  305. try:
  306. snapshot = Snapshot.snapshot(width=300, height=300)
  307. except:
  308. Logger.logException("w", "Failed to create snapshot image")
  309. return None
  310. return snapshot
  311. @staticmethod
  312. def sceneNodesToString(scene_nodes: [SceneNode]) -> str:
  313. savitar_scene = Savitar.Scene()
  314. for scene_node in scene_nodes:
  315. savitar_node = ThreeMFWriter._convertUMNodeToSavitarNode(scene_node)
  316. savitar_scene.addSceneNode(savitar_node)
  317. parser = Savitar.ThreeMFParser()
  318. scene_string = parser.sceneToString(savitar_scene)
  319. return scene_string