ThreeMFWriter.py 22 KB

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