GCodeWriter.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. # Copyright (c) 2016 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from UM.Mesh.MeshWriter import MeshWriter
  4. from UM.Logger import Logger
  5. from UM.Application import Application
  6. from UM.Settings.InstanceContainer import InstanceContainer
  7. from cura.Settings.ExtruderManager import ExtruderManager
  8. import re #For escaping characters in the settings.
  9. import json
  10. import copy
  11. ## Writes g-code to a file.
  12. #
  13. # While this poses as a mesh writer, what this really does is take the g-code
  14. # in the entire scene and write it to an output device. Since the g-code of a
  15. # single mesh isn't separable from the rest what with rafts and travel moves
  16. # and all, it doesn't make sense to write just a single mesh.
  17. #
  18. # So this plug-in takes the g-code that is stored in the root of the scene
  19. # node tree, adds a bit of extra information about the profiles and writes
  20. # that to the output device.
  21. class GCodeWriter(MeshWriter):
  22. ## The file format version of the serialised g-code.
  23. #
  24. # It can only read settings with the same version as the version it was
  25. # written with. If the file format is changed in a way that breaks reverse
  26. # compatibility, increment this version number!
  27. version = 3
  28. ## Dictionary that defines how characters are escaped when embedded in
  29. # g-code.
  30. #
  31. # Note that the keys of this dictionary are regex strings. The values are
  32. # not.
  33. escape_characters = {
  34. re.escape("\\"): "\\\\", # The escape character.
  35. re.escape("\n"): "\\n", # Newlines. They break off the comment.
  36. re.escape("\r"): "\\r" # Carriage return. Windows users may need this for visualisation in their editors.
  37. }
  38. def __init__(self):
  39. super().__init__()
  40. ## Writes the g-code for the entire scene to a stream.
  41. #
  42. # Note that even though the function accepts a collection of nodes, the
  43. # entire scene is always written to the file since it is not possible to
  44. # separate the g-code for just specific nodes.
  45. #
  46. # \param stream The stream to write the g-code to.
  47. # \param nodes This is ignored.
  48. # \param mode Additional information on how to format the g-code in the
  49. # file. This must always be text mode.
  50. def write(self, stream, nodes, mode = MeshWriter.OutputMode.TextMode):
  51. if mode != MeshWriter.OutputMode.TextMode:
  52. Logger.log("e", "GCode Writer does not support non-text mode.")
  53. return False
  54. scene = Application.getInstance().getController().getScene()
  55. gcode_list = getattr(scene, "gcode_list")
  56. if gcode_list:
  57. for gcode in gcode_list:
  58. stream.write(gcode)
  59. # Serialise the current container stack and put it at the end of the file.
  60. settings = self._serialiseSettings(Application.getInstance().getGlobalContainerStack())
  61. stream.write(settings)
  62. return True
  63. return False
  64. ## Create a new container with container 2 as base and container 1 written over it.
  65. def _createFlattenedContainerInstance(self, instance_container1, instance_container2):
  66. flat_container = InstanceContainer(instance_container2.getName())
  67. if instance_container1.getDefinition():
  68. flat_container.setDefinition(instance_container1.getDefinition())
  69. else:
  70. flat_container.setDefinition(instance_container2.getDefinition())
  71. flat_container.setMetaData(copy.deepcopy(instance_container2.getMetaData()))
  72. for key in instance_container2.getAllKeys():
  73. flat_container.setProperty(key, "value", instance_container2.getProperty(key, "value"))
  74. for key in instance_container1.getAllKeys():
  75. flat_container.setProperty(key, "value", instance_container1.getProperty(key, "value"))
  76. return flat_container
  77. ## Serialises a container stack to prepare it for writing at the end of the
  78. # g-code.
  79. #
  80. # The settings are serialised, and special characters (including newline)
  81. # are escaped.
  82. #
  83. # \param settings A container stack to serialise.
  84. # \return A serialised string of the settings.
  85. def _serialiseSettings(self, stack):
  86. prefix = ";SETTING_" + str(GCodeWriter.version) + " " # The prefix to put before each line.
  87. prefix_length = len(prefix)
  88. container_with_profile = stack.qualityChanges
  89. if not container_with_profile:
  90. Logger.log("e", "No valid quality profile found, not writing settings to GCode!")
  91. return ""
  92. flat_global_container = self._createFlattenedContainerInstance(stack.getTop(), container_with_profile)
  93. # If the quality changes is not set, we need to set type manually
  94. if flat_global_container.getMetaDataEntry("type", None) is None:
  95. flat_global_container.addMetaDataEntry("type", "quality_changes")
  96. # Ensure that quality_type is set. (Can happen if we have empty quality changes).
  97. if flat_global_container.getMetaDataEntry("quality_type", None) is None:
  98. flat_global_container.addMetaDataEntry("quality_type", stack.findContainer({"type": "quality"}).getMetaDataEntry("quality_type", "normal"))
  99. serialized = flat_global_container.serialize()
  100. data = {"global_quality": serialized}
  101. for extruder in sorted(ExtruderManager.getInstance().getMachineExtruders(stack.getId()), key = lambda k: k.getMetaDataEntry("position")):
  102. extruder_quality = extruder.qualityChanges
  103. if not extruder_quality:
  104. Logger.log("w", "No extruder quality profile found, not writing quality for extruder %s to file!", extruder.getId())
  105. continue
  106. flat_extruder_quality = self._createFlattenedContainerInstance(extruder.getTop(), extruder_quality)
  107. # If the quality changes is not set, we need to set type manually
  108. if flat_extruder_quality.getMetaDataEntry("type", None) is None:
  109. flat_extruder_quality.addMetaDataEntry("type", "quality_changes")
  110. # Ensure that extruder is set. (Can happen if we have empty quality changes).
  111. if flat_extruder_quality.getMetaDataEntry("extruder", None) is None:
  112. flat_extruder_quality.addMetaDataEntry("extruder", extruder.getBottom().getId())
  113. # Ensure that quality_type is set. (Can happen if we have empty quality changes).
  114. if flat_extruder_quality.getMetaDataEntry("quality_type", None) is None:
  115. flat_extruder_quality.addMetaDataEntry("quality_type", extruder.findContainer({"type": "quality"}).getMetaDataEntry("quality_type", "normal"))
  116. extruder_serialized = flat_extruder_quality.serialize()
  117. data.setdefault("extruder_quality", []).append(extruder_serialized)
  118. json_string = json.dumps(data)
  119. # Escape characters that have a special meaning in g-code comments.
  120. pattern = re.compile("|".join(GCodeWriter.escape_characters.keys()))
  121. # Perform the replacement with a regular expression.
  122. escaped_string = pattern.sub(lambda m: GCodeWriter.escape_characters[re.escape(m.group(0))], json_string)
  123. # Introduce line breaks so that each comment is no longer than 80 characters. Prepend each line with the prefix.
  124. result = ""
  125. # Lines have 80 characters, so the payload of each line is 80 - prefix.
  126. for pos in range(0, len(escaped_string), 80 - prefix_length):
  127. result += prefix + escaped_string[pos : pos + 80 - prefix_length] + "\n"
  128. return result