ThreeMFWriter.py 8.4 KB

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