GCodeWriter.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. # Copyright (c) 2017 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import re # For escaping characters in the settings.
  4. import json
  5. import copy
  6. from UM.Mesh.MeshWriter import MeshWriter
  7. from UM.Logger import Logger
  8. from UM.Application import Application
  9. from UM.Settings.InstanceContainer import InstanceContainer
  10. from cura.Machines.QualityManager import getMachineDefinitionIDForQualitySearch
  11. from UM.i18n import i18nCatalog
  12. catalog = i18nCatalog("cura")
  13. ## Writes g-code to a file.
  14. #
  15. # While this poses as a mesh writer, what this really does is take the g-code
  16. # in the entire scene and write it to an output device. Since the g-code of a
  17. # single mesh isn't separable from the rest what with rafts and travel moves
  18. # and all, it doesn't make sense to write just a single mesh.
  19. #
  20. # So this plug-in takes the g-code that is stored in the root of the scene
  21. # node tree, adds a bit of extra information about the profiles and writes
  22. # that to the output device.
  23. class GCodeWriter(MeshWriter):
  24. ## The file format version of the serialised g-code.
  25. #
  26. # It can only read settings with the same version as the version it was
  27. # written with. If the file format is changed in a way that breaks reverse
  28. # compatibility, increment this version number!
  29. version = 3
  30. ## Dictionary that defines how characters are escaped when embedded in
  31. # g-code.
  32. #
  33. # Note that the keys of this dictionary are regex strings. The values are
  34. # not.
  35. escape_characters = {
  36. re.escape("\\"): "\\\\", # The escape character.
  37. re.escape("\n"): "\\n", # Newlines. They break off the comment.
  38. re.escape("\r"): "\\r" # Carriage return. Windows users may need this for visualisation in their editors.
  39. }
  40. _setting_keyword = ";SETTING_"
  41. def __init__(self):
  42. super().__init__(add_to_recent_files = False)
  43. self._application = Application.getInstance()
  44. ## Writes the g-code for the entire scene to a stream.
  45. #
  46. # Note that even though the function accepts a collection of nodes, the
  47. # entire scene is always written to the file since it is not possible to
  48. # separate the g-code for just specific nodes.
  49. #
  50. # \param stream The stream to write the g-code to.
  51. # \param nodes This is ignored.
  52. # \param mode Additional information on how to format the g-code in the
  53. # file. This must always be text mode.
  54. def write(self, stream, nodes, mode = MeshWriter.OutputMode.TextMode):
  55. if mode != MeshWriter.OutputMode.TextMode:
  56. Logger.log("e", "GCodeWriter does not support non-text mode.")
  57. self.setInformation(catalog.i18nc("@error:not supported", "GCodeWriter does not support non-text mode."))
  58. return False
  59. active_build_plate = Application.getInstance().getMultiBuildPlateModel().activeBuildPlate
  60. scene = Application.getInstance().getController().getScene()
  61. if not hasattr(scene, "gcode_dict"):
  62. self.setInformation(catalog.i18nc("@warning:status", "Please prepare G-code before exporting."))
  63. return False
  64. gcode_dict = getattr(scene, "gcode_dict")
  65. gcode_list = gcode_dict.get(active_build_plate, None)
  66. if gcode_list is not None:
  67. has_settings = False
  68. for gcode in gcode_list:
  69. if gcode[:len(self._setting_keyword)] == self._setting_keyword:
  70. has_settings = True
  71. stream.write(gcode)
  72. # Serialise the current container stack and put it at the end of the file.
  73. if not has_settings:
  74. settings = self._serialiseSettings(Application.getInstance().getGlobalContainerStack())
  75. stream.write(settings)
  76. return True
  77. self.setInformation(catalog.i18nc("@warning:status", "Please prepare G-code before exporting."))
  78. return False
  79. ## Create a new container with container 2 as base and container 1 written over it.
  80. def _createFlattenedContainerInstance(self, instance_container1, instance_container2):
  81. flat_container = InstanceContainer(instance_container2.getName())
  82. # The metadata includes id, name and definition
  83. flat_container.setMetaData(copy.deepcopy(instance_container2.getMetaData()))
  84. if instance_container1.getDefinition():
  85. flat_container.setDefinition(instance_container1.getDefinition().getId())
  86. for key in instance_container2.getAllKeys():
  87. flat_container.setProperty(key, "value", instance_container2.getProperty(key, "value"))
  88. for key in instance_container1.getAllKeys():
  89. flat_container.setProperty(key, "value", instance_container1.getProperty(key, "value"))
  90. return flat_container
  91. ## Serialises a container stack to prepare it for writing at the end of the
  92. # g-code.
  93. #
  94. # The settings are serialised, and special characters (including newline)
  95. # are escaped.
  96. #
  97. # \param settings A container stack to serialise.
  98. # \return A serialised string of the settings.
  99. def _serialiseSettings(self, stack):
  100. container_registry = self._application.getContainerRegistry()
  101. quality_manager = self._application.getQualityManager()
  102. prefix = self._setting_keyword + str(GCodeWriter.version) + " " # The prefix to put before each line.
  103. prefix_length = len(prefix)
  104. quality_type = stack.quality.getMetaDataEntry("quality_type")
  105. container_with_profile = stack.qualityChanges
  106. if container_with_profile.getId() == "empty_quality_changes":
  107. # If the global quality changes is empty, create a new one
  108. quality_name = container_registry.uniqueName(stack.quality.getName())
  109. container_with_profile = quality_manager._createQualityChanges(quality_type, quality_name, stack, None)
  110. flat_global_container = self._createFlattenedContainerInstance(stack.userChanges, container_with_profile)
  111. # If the quality changes is not set, we need to set type manually
  112. if flat_global_container.getMetaDataEntry("type", None) is None:
  113. flat_global_container.setMetaDataEntry("type", "quality_changes")
  114. # Ensure that quality_type is set. (Can happen if we have empty quality changes).
  115. if flat_global_container.getMetaDataEntry("quality_type", None) is None:
  116. flat_global_container.setMetaDataEntry("quality_type", stack.quality.getMetaDataEntry("quality_type", "normal"))
  117. # Get the machine definition ID for quality profiles
  118. machine_definition_id_for_quality = getMachineDefinitionIDForQualitySearch(stack.definition)
  119. flat_global_container.setMetaDataEntry("definition", machine_definition_id_for_quality)
  120. serialized = flat_global_container.serialize()
  121. data = {"global_quality": serialized}
  122. all_setting_keys = flat_global_container.getAllKeys()
  123. for extruder in sorted(stack.extruders.values(), key = lambda k: int(k.getMetaDataEntry("position"))):
  124. extruder_quality = extruder.qualityChanges
  125. if extruder_quality.getId() == "empty_quality_changes":
  126. # Same story, if quality changes is empty, create a new one
  127. quality_name = container_registry.uniqueName(stack.quality.getName())
  128. extruder_quality = quality_manager._createQualityChanges(quality_type, quality_name, stack, None)
  129. flat_extruder_quality = self._createFlattenedContainerInstance(extruder.userChanges, extruder_quality)
  130. # If the quality changes is not set, we need to set type manually
  131. if flat_extruder_quality.getMetaDataEntry("type", None) is None:
  132. flat_extruder_quality.setMetaDataEntry("type", "quality_changes")
  133. # Ensure that extruder is set. (Can happen if we have empty quality changes).
  134. if flat_extruder_quality.getMetaDataEntry("position", None) is None:
  135. flat_extruder_quality.setMetaDataEntry("position", extruder.getMetaDataEntry("position"))
  136. # Ensure that quality_type is set. (Can happen if we have empty quality changes).
  137. if flat_extruder_quality.getMetaDataEntry("quality_type", None) is None:
  138. flat_extruder_quality.setMetaDataEntry("quality_type", extruder.quality.getMetaDataEntry("quality_type", "normal"))
  139. # Change the default definition
  140. flat_extruder_quality.setMetaDataEntry("definition", machine_definition_id_for_quality)
  141. extruder_serialized = flat_extruder_quality.serialize()
  142. data.setdefault("extruder_quality", []).append(extruder_serialized)
  143. all_setting_keys.update(flat_extruder_quality.getAllKeys())
  144. # Check if there is any profiles
  145. if not all_setting_keys:
  146. Logger.log("i", "No custom settings found, not writing settings to g-code.")
  147. return ""
  148. json_string = json.dumps(data)
  149. # Escape characters that have a special meaning in g-code comments.
  150. pattern = re.compile("|".join(GCodeWriter.escape_characters.keys()))
  151. # Perform the replacement with a regular expression.
  152. escaped_string = pattern.sub(lambda m: GCodeWriter.escape_characters[re.escape(m.group(0))], json_string)
  153. # Introduce line breaks so that each comment is no longer than 80 characters. Prepend each line with the prefix.
  154. result = ""
  155. # Lines have 80 characters, so the payload of each line is 80 - prefix.
  156. for pos in range(0, len(escaped_string), 80 - prefix_length):
  157. result += prefix + escaped_string[pos: pos + 80 - prefix_length] + "\n"
  158. return result