ThreeMFWriter.py 20 KB

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