ThreeMFWriter.py 8.5 KB

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