MakerbotWriter.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. # Copyright (c) 2023 UltiMaker
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from io import StringIO, BufferedIOBase
  4. import json
  5. from typing import cast, List, Optional, Dict, Tuple
  6. from zipfile import BadZipFile, ZipFile, ZIP_DEFLATED
  7. import pyDulcificum as du
  8. from PyQt6.QtCore import QBuffer
  9. from UM.Logger import Logger
  10. from UM.Math.AxisAlignedBox import AxisAlignedBox
  11. from UM.Mesh.MeshWriter import MeshWriter
  12. from UM.MimeTypeDatabase import MimeTypeDatabase, MimeType
  13. from UM.PluginRegistry import PluginRegistry
  14. from UM.Scene.SceneNode import SceneNode
  15. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  16. from UM.i18n import i18nCatalog
  17. from cura.CuraApplication import CuraApplication
  18. from cura.Snapshot import Snapshot
  19. from cura.Utils.Threading import call_on_qt_thread
  20. from cura.CuraVersion import ConanInstalls
  21. catalog = i18nCatalog("cura")
  22. class MakerbotWriter(MeshWriter):
  23. """A file writer that writes '.makerbot' files."""
  24. def __init__(self) -> None:
  25. super().__init__(add_to_recent_files=False)
  26. Logger.info(f"Using PyDulcificum: {du.__version__}")
  27. MimeTypeDatabase.addMimeType(
  28. MimeType(
  29. name="application/x-makerbot",
  30. comment="Makerbot Toolpath Package",
  31. suffixes=["makerbot"]
  32. )
  33. )
  34. MimeTypeDatabase.addMimeType(
  35. MimeType(
  36. name="application/x-makerbot-sketch",
  37. comment="Makerbot Toolpath Package",
  38. suffixes=["makerbot"]
  39. )
  40. )
  41. _PNG_FORMAT = [
  42. {"prefix": "isometric_thumbnail", "width": 120, "height": 120},
  43. {"prefix": "isometric_thumbnail", "width": 320, "height": 320},
  44. {"prefix": "isometric_thumbnail", "width": 640, "height": 640},
  45. {"prefix": "thumbnail", "width": 90, "height": 90},
  46. ]
  47. _PNG_FORMAT_METHOD = [
  48. {"prefix": "thumbnail", "width": 140, "height": 106},
  49. {"prefix": "thumbnail", "width": 212, "height": 300},
  50. {"prefix": "thumbnail", "width": 960, "height": 1460},
  51. ]
  52. _META_VERSION = "3.0.0"
  53. # must be called from the main thread because of OpenGL
  54. @staticmethod
  55. @call_on_qt_thread
  56. def _createThumbnail(width: int, height: int) -> Optional[QBuffer]:
  57. if not CuraApplication.getInstance().isVisible:
  58. Logger.warning("Can't create snapshot when renderer not initialized.")
  59. return
  60. try:
  61. snapshot = Snapshot.isometricSnapshot(width, height)
  62. thumbnail_buffer = QBuffer()
  63. thumbnail_buffer.open(QBuffer.OpenModeFlag.WriteOnly)
  64. snapshot.save(thumbnail_buffer, "PNG")
  65. return thumbnail_buffer
  66. except:
  67. Logger.logException("w", "Failed to create snapshot image")
  68. return None
  69. def write(self, stream: BufferedIOBase, nodes: List[SceneNode], mode=MeshWriter.OutputMode.BinaryMode) -> bool:
  70. metadata, file_format = self._getMeta(nodes)
  71. if mode != MeshWriter.OutputMode.BinaryMode:
  72. Logger.log("e", "MakerbotWriter does not support text mode.")
  73. self.setInformation(catalog.i18nc("@error:not supported", "MakerbotWriter does not support text mode."))
  74. return False
  75. # The GCodeWriter plugin is always available since it is in the "required" list of plugins.
  76. gcode_writer = PluginRegistry.getInstance().getPluginObject("GCodeWriter")
  77. if gcode_writer is None:
  78. Logger.log("e", "Could not find the GCodeWriter plugin, is it disabled?.")
  79. self.setInformation(
  80. catalog.i18nc("@error:load", "Could not load GCodeWriter plugin. Try to re-enable the plugin."))
  81. return False
  82. gcode_writer = cast(MeshWriter, gcode_writer)
  83. gcode_text_io = StringIO()
  84. success = gcode_writer.write(gcode_text_io, None)
  85. filename, filedata = "", ""
  86. # Writing the g-code failed. Then I can also not write the gzipped g-code.
  87. if not success:
  88. self.setInformation(gcode_writer.getInformation())
  89. return False
  90. match file_format:
  91. case "application/x-makerbot-sketch":
  92. filename, filedata = "print.gcode", gcode_text_io.getvalue()
  93. self._PNG_FORMATS = self._PNG_FORMAT
  94. case "application/x-makerbot":
  95. filename, filedata = "print.jsontoolpath", du.gcode_2_miracle_jtp(gcode_text_io.getvalue())
  96. self._PNG_FORMATS = self._PNG_FORMAT + self._PNG_FORMAT_METHOD
  97. case _:
  98. raise Exception("Unsupported Mime type")
  99. png_files = []
  100. for png_format in self._PNG_FORMATS:
  101. width, height, prefix = png_format["width"], png_format["height"], png_format["prefix"]
  102. thumbnail_buffer = self._createThumbnail(width, height)
  103. if thumbnail_buffer is None:
  104. Logger.warning(f"Could not create thumbnail of size {width}x{height}.")
  105. continue
  106. png_files.append({
  107. "file": f"{prefix}_{width}x{height}.png",
  108. "data": thumbnail_buffer.data(),
  109. })
  110. try:
  111. with ZipFile(stream, "w", compression=ZIP_DEFLATED) as zip_stream:
  112. zip_stream.writestr("meta.json", json.dumps(metadata, indent=4))
  113. zip_stream.writestr(filename, filedata)
  114. for png_file in png_files:
  115. file, data = png_file["file"], png_file["data"]
  116. zip_stream.writestr(file, data)
  117. except (IOError, OSError, BadZipFile) as ex:
  118. Logger.log("e", f"Could not write to (.makerbot) file because: '{ex}'.")
  119. self.setInformation(catalog.i18nc("@error", "MakerbotWriter could not save to the designated path."))
  120. return False
  121. return True
  122. def _getMeta(self, root_nodes: List[SceneNode]) -> Tuple[Dict[str, any], str]:
  123. application = CuraApplication.getInstance()
  124. machine_manager = application.getMachineManager()
  125. global_stack = machine_manager.activeMachine
  126. extruders = global_stack.extruderList
  127. nodes = []
  128. for root_node in root_nodes:
  129. for node in DepthFirstIterator(root_node):
  130. if not getattr(node, "_outside_buildarea", False):
  131. if node.callDecoration(
  132. "isSliceable") and node.getMeshData() and node.isVisible() and not node.callDecoration(
  133. "isNonThumbnailVisibleMesh"):
  134. nodes.append(node)
  135. meta = dict()
  136. # This is a bit of a "hack", the mime type should be passed through with the export writer but
  137. # since this is not the case we get the mime type from the global stack instead
  138. file_format = global_stack.definition.getMetaDataEntry("file_formats")
  139. meta["bot_type"] = global_stack.definition.getMetaDataEntry("reference_machine_id")
  140. bounds: Optional[AxisAlignedBox] = None
  141. for node in nodes:
  142. node_bounds = node.getBoundingBox()
  143. if node_bounds is None:
  144. continue
  145. if bounds is None:
  146. bounds = node_bounds
  147. else:
  148. bounds = bounds + node_bounds
  149. if file_format == "application/x-makerbot-sketch":
  150. bounds = None
  151. if bounds is not None:
  152. meta["bounding_box"] = {
  153. "x_min": bounds.left,
  154. "x_max": bounds.right,
  155. "y_min": bounds.back,
  156. "y_max": bounds.front,
  157. "z_min": bounds.bottom,
  158. "z_max": bounds.top,
  159. }
  160. material_bed_temperature = global_stack.getProperty("material_bed_temperature", "value")
  161. meta["platform_temperature"] = material_bed_temperature
  162. build_volume_temperature = global_stack.getProperty("build_volume_temperature", "value")
  163. meta["build_plane_temperature"] = build_volume_temperature
  164. print_information = application.getPrintInformation()
  165. meta["commanded_duration_s"] = int(print_information.currentPrintTime)
  166. meta["duration_s"] = int(print_information.currentPrintTime)
  167. material_lengths = list(map(meterToMillimeter, print_information.materialLengths))
  168. meta["extrusion_distance_mm"] = material_lengths[0]
  169. meta["extrusion_distances_mm"] = material_lengths
  170. meta["extrusion_mass_g"] = print_information.materialWeights[0]
  171. meta["extrusion_masses_g"] = print_information.materialWeights
  172. meta["uuid"] = print_information.slice_uuid
  173. materials = [extruder.material.getMetaData().get("reference_material_id") for extruder in extruders]
  174. meta["material"] = materials[0]
  175. meta["materials"] = materials
  176. materials_temps = [extruder.getProperty("default_material_print_temperature", "value") for extruder in
  177. extruders]
  178. meta["extruder_temperature"] = materials_temps[0]
  179. meta["extruder_temperatures"] = materials_temps
  180. meta["model_counts"] = [{"count": len(nodes), "name": "instance0"}]
  181. tool_types = [extruder.variant.getMetaDataEntry("reference_extruder_id") for extruder in extruders]
  182. meta["tool_type"] = tool_types[0]
  183. meta["tool_types"] = tool_types
  184. meta["version"] = MakerbotWriter._META_VERSION
  185. meta["preferences"] = dict()
  186. bounds = application.getBuildVolume().getBoundingBox()
  187. meta["preferences"]["instance0"] = {
  188. "machineBounds": [bounds.right, bounds.back, bounds.left, bounds.front] if bounds is not None else None,
  189. "printMode": CuraApplication.getInstance().getIntentManager().currentIntentCategory,
  190. }
  191. meta["miracle_config"] = {"gaggles": {str(node.getName()): {} for node in nodes}}
  192. version_info = dict()
  193. cura_engine_info = ConanInstalls.get("curaengine", {"version": "unknown", "revision": "unknown"})
  194. version_info["curaengine_version"] = cura_engine_info["version"]
  195. version_info["curaengine_commit_hash"] = cura_engine_info["revision"]
  196. dulcificum_info = ConanInstalls.get("dulcificum", {"version": "unknown", "revision": "unknown"})
  197. version_info["dulcificum_version"] = dulcificum_info["version"]
  198. version_info["dulcificum_commit_hash"] = dulcificum_info["revision"]
  199. version_info["makerbot_writer_version"] = self.getVersion()
  200. version_info["pyDulcificum_version"] = du.__version__
  201. # Add engine plugin information to the metadata
  202. for name, package_info in ConanInstalls.items():
  203. if not name.startswith("curaengine_"):
  204. continue
  205. version_info[f"{name}_version"] = package_info["version"]
  206. version_info[f"{name}_commit_hash"] = package_info["revision"]
  207. # Add version info to the main metadata, but also to "miracle_config"
  208. # so that it shows up in analytics
  209. meta["miracle_config"].update(version_info)
  210. meta.update(version_info)
  211. # TODO add the following instructions
  212. # num_tool_changes
  213. # num_z_layers
  214. # num_z_transitions
  215. # platform_temperature
  216. # total_commands
  217. return meta, file_format
  218. def meterToMillimeter(value: float) -> float:
  219. """Converts a value in meters to millimeters."""
  220. return value * 1000.0