FlavorParser.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import math
  4. import re
  5. from typing import Dict, List, NamedTuple, Optional, Union, Set
  6. import numpy
  7. from UM.Backend import Backend
  8. from UM.Job import Job
  9. from UM.Logger import Logger
  10. from UM.Math.Vector import Vector
  11. from UM.Message import Message
  12. from UM.i18n import i18nCatalog
  13. from cura.CuraApplication import CuraApplication
  14. from cura.LayerDataBuilder import LayerDataBuilder
  15. from cura.LayerDataDecorator import LayerDataDecorator
  16. from cura.LayerPolygon import LayerPolygon
  17. from cura.Scene.CuraSceneNode import CuraSceneNode
  18. from cura.Scene.GCodeListDecorator import GCodeListDecorator
  19. from cura.Settings.ExtruderManager import ExtruderManager
  20. catalog = i18nCatalog("cura")
  21. PositionOptional = NamedTuple("Position", [("x", Optional[float]), ("y", Optional[float]), ("z", Optional[float]), ("f", Optional[float]), ("e", Optional[float])])
  22. Position = NamedTuple("Position", [("x", float), ("y", float), ("z", float), ("f", float), ("e", List[float])])
  23. class FlavorParser:
  24. """This parser is intended to interpret the common firmware codes among all the different flavors"""
  25. def __init__(self) -> None:
  26. CuraApplication.getInstance().hideMessageSignal.connect(self._onHideMessage)
  27. self._cancelled = False
  28. self._message = None # type: Optional[Message]
  29. self._layer_number = 0
  30. self._extruder_number = 0
  31. # All extruder numbers that have been seen
  32. self._extruders_seen = {0} # type: Set[int]
  33. self._clearValues()
  34. self._scene_node = None
  35. # X, Y, Z position, F feedrate and E extruder values are stored
  36. self._position = Position
  37. self._is_layers_in_file = False # Does the Gcode have the layers comment?
  38. self._extruder_offsets = {} # type: Dict[int, List[float]] # Offsets for multi extruders. key is index, value is [x-offset, y-offset]
  39. self._current_layer_thickness = 0.2 # default
  40. self._filament_diameter = 2.85 # default
  41. self._previous_extrusion_value = 0.0 # keep track of the filament retractions
  42. CuraApplication.getInstance().getPreferences().addPreference("gcodereader/show_caution", True)
  43. def _clearValues(self) -> None:
  44. self._extruder_number = 0
  45. self._extrusion_length_offset = [0] # type: List[float]
  46. self._layer_type = LayerPolygon.Inset0Type
  47. self._layer_number = 0
  48. self._previous_z = 0 # type: float
  49. self._layer_data_builder = LayerDataBuilder()
  50. self._is_absolute_positioning = True # It can be absolute (G90) or relative (G91)
  51. self._is_absolute_extrusion = True # It can become absolute (M82, default) or relative (M83)
  52. @staticmethod
  53. def _getValue(line: str, code: str) -> Optional[Union[str, int, float]]:
  54. n = line.find(code)
  55. if n < 0:
  56. return None
  57. n += len(code)
  58. pattern = re.compile("[;\\s]")
  59. match = pattern.search(line, n)
  60. m = match.start() if match is not None else -1
  61. try:
  62. if m < 0:
  63. return line[n:]
  64. return line[n:m]
  65. except:
  66. return None
  67. def _getInt(self, line: str, code: str) -> Optional[int]:
  68. value = self._getValue(line, code)
  69. try:
  70. return int(value) # type: ignore
  71. except:
  72. return None
  73. def _getFloat(self, line: str, code: str) -> Optional[float]:
  74. value = self._getValue(line, code)
  75. try:
  76. return float(value) # type: ignore
  77. except:
  78. return None
  79. def _onHideMessage(self, message: str) -> None:
  80. if message == self._message:
  81. self._cancelled = True
  82. def _createPolygon(self, layer_thickness: float, path: List[List[Union[float, int]]], extruder_offsets: List[float]) -> bool:
  83. countvalid = 0
  84. for point in path:
  85. if point[5] > 0:
  86. countvalid += 1
  87. if countvalid >= 2:
  88. # we know what to do now, no need to count further
  89. continue
  90. if countvalid < 2:
  91. return False
  92. try:
  93. self._layer_data_builder.addLayer(self._layer_number)
  94. self._layer_data_builder.setLayerHeight(self._layer_number, path[0][2])
  95. self._layer_data_builder.setLayerThickness(self._layer_number, layer_thickness)
  96. this_layer = self._layer_data_builder.getLayer(self._layer_number)
  97. if not this_layer:
  98. return False
  99. except ValueError:
  100. return False
  101. count = len(path)
  102. line_types = numpy.empty((count - 1, 1), numpy.int32)
  103. line_widths = numpy.empty((count - 1, 1), numpy.float32)
  104. line_thicknesses = numpy.empty((count - 1, 1), numpy.float32)
  105. line_feedrates = numpy.empty((count - 1, 1), numpy.float32)
  106. line_widths[:, 0] = 0.35 # Just a guess
  107. line_thicknesses[:, 0] = layer_thickness
  108. points = numpy.empty((count, 3), numpy.float32)
  109. extrusion_values = numpy.empty((count, 1), numpy.float32)
  110. i = 0
  111. for point in path:
  112. points[i, :] = [point[0] + extruder_offsets[0], point[2], -point[1] - extruder_offsets[1]]
  113. extrusion_values[i] = point[4]
  114. if i > 0:
  115. line_feedrates[i - 1] = point[3]
  116. line_types[i - 1] = point[5]
  117. if point[5] in [LayerPolygon.MoveCombingType, LayerPolygon.MoveRetractionType]:
  118. line_widths[i - 1] = 0.1
  119. line_thicknesses[i - 1] = 0.0 # Travels are set as zero thickness lines
  120. else:
  121. line_widths[i - 1] = self._calculateLineWidth(points[i], points[i-1], extrusion_values[i], extrusion_values[i-1], layer_thickness)
  122. i += 1
  123. this_poly = LayerPolygon(self._extruder_number, line_types, points, line_widths, line_thicknesses, line_feedrates)
  124. this_poly.buildCache()
  125. this_layer.polygons.append(this_poly)
  126. return True
  127. def _createEmptyLayer(self, layer_number: int) -> None:
  128. self._layer_data_builder.addLayer(layer_number)
  129. self._layer_data_builder.setLayerHeight(layer_number, 0)
  130. self._layer_data_builder.setLayerThickness(layer_number, 0)
  131. def _calculateLineWidth(self, current_point: Position, previous_point: Position, current_extrusion: float, previous_extrusion: float, layer_thickness: float) -> float:
  132. # Area of the filament
  133. Af = (self._filament_diameter / 2) ** 2 * numpy.pi
  134. # Length of the extruded filament
  135. de = current_extrusion - previous_extrusion
  136. # Volume of the extruded filament
  137. dVe = de * Af
  138. # Length of the printed line
  139. dX = numpy.sqrt((current_point[0] - previous_point[0])**2 + (current_point[2] - previous_point[2])**2)
  140. # When the extruder recovers from a retraction, we get zero distance
  141. if dX == 0:
  142. return 0.1
  143. # Area of the printed line. This area is a rectangle
  144. Ae = dVe / dX
  145. # This area is a rectangle with area equal to layer_thickness * layer_width
  146. line_width = Ae / layer_thickness
  147. # A threshold is set to avoid weird paths in the GCode
  148. if line_width > 1.2:
  149. return 0.35
  150. # Prevent showing infinitely wide lines
  151. if line_width < 0.0:
  152. return 0.0
  153. return line_width
  154. def _gCode0(self, position: Position, params: PositionOptional, path: List[List[Union[float, int]]]) -> Position:
  155. x, y, z, f, e = position
  156. if self._is_absolute_positioning:
  157. x = params.x if params.x is not None else x
  158. y = params.y if params.y is not None else y
  159. z = params.z if params.z is not None else z
  160. else:
  161. x += params.x if params.x is not None else 0
  162. y += params.y if params.y is not None else 0
  163. z += params.z if params.z is not None else 0
  164. f = params.f if params.f is not None else f
  165. if params.e is not None:
  166. new_extrusion_value = params.e if self._is_absolute_extrusion else e[self._extruder_number] + params.e
  167. if new_extrusion_value > e[self._extruder_number]:
  168. path.append([x, y, z, f, new_extrusion_value + self._extrusion_length_offset[self._extruder_number], self._layer_type]) # extrusion
  169. self._previous_extrusion_value = new_extrusion_value
  170. else:
  171. path.append([x, y, z, f, new_extrusion_value + self._extrusion_length_offset[self._extruder_number], LayerPolygon.MoveRetractionType]) # retraction
  172. e[self._extruder_number] = new_extrusion_value
  173. # Only when extruding we can determine the latest known "layer height" which is the difference in height between extrusions
  174. # Also, 1.5 is a heuristic for any priming or whatsoever, we skip those.
  175. if z > self._previous_z and (z - self._previous_z < 1.5) and (params.x is not None or params.y is not None):
  176. self._current_layer_thickness = z - self._previous_z # allow a tiny overlap
  177. self._previous_z = z
  178. elif self._previous_extrusion_value > e[self._extruder_number]:
  179. path.append([x, y, z, f, e[self._extruder_number] + self._extrusion_length_offset[self._extruder_number], LayerPolygon.MoveRetractionType])
  180. else:
  181. path.append([x, y, z, f, e[self._extruder_number] + self._extrusion_length_offset[self._extruder_number], LayerPolygon.MoveCombingType])
  182. return self._position(x, y, z, f, e)
  183. # G0 and G1 should be handled exactly the same.
  184. _gCode1 = _gCode0
  185. def _gCode28(self, position: Position, params: PositionOptional, path: List[List[Union[float, int]]]) -> Position:
  186. """Home the head."""
  187. return self._position(
  188. params.x if params.x is not None else position.x,
  189. params.y if params.y is not None else position.y,
  190. params.z if params.z is not None else position.z,
  191. position.f,
  192. position.e)
  193. def _gCode90(self, position: Position, params: PositionOptional, path: List[List[Union[float, int]]]) -> Position:
  194. """Set the absolute positioning"""
  195. self._is_absolute_positioning = True
  196. self._is_absolute_extrusion = True
  197. return position
  198. def _gCode91(self, position: Position, params: PositionOptional, path: List[List[Union[float, int]]]) -> Position:
  199. """Set the relative positioning"""
  200. self._is_absolute_positioning = False
  201. self._is_absolute_extrusion = False
  202. return position
  203. def _gCode92(self, position: Position, params: PositionOptional, path: List[List[Union[float, int]]]) -> Position:
  204. """Reset the current position to the values specified.
  205. For example: G92 X10 will set the X to 10 without any physical motion.
  206. """
  207. if params.e is not None:
  208. # Sometimes a G92 E0 is introduced in the middle of the GCode so we need to keep those offsets for calculate the line_width
  209. self._extrusion_length_offset[self._extruder_number] = position.e[self._extruder_number] - params.e
  210. position.e[self._extruder_number] = params.e
  211. self._previous_extrusion_value = params.e
  212. else:
  213. self._previous_extrusion_value = 0.0
  214. return self._position(
  215. params.x if params.x is not None else position.x,
  216. params.y if params.y is not None else position.y,
  217. params.z if params.z is not None else position.z,
  218. params.f if params.f is not None else position.f,
  219. position.e)
  220. def processGCode(self, G: int, line: str, position: Position, path: List[List[Union[float, int]]]) -> Position:
  221. func = getattr(self, "_gCode%s" % G, None)
  222. line = line.split(";", 1)[0] # Remove comments (if any)
  223. if func is not None:
  224. s = line.upper().split(" ")
  225. x, y, z, f, e = None, None, None, None, None
  226. for item in s[1:]:
  227. if len(item) <= 1:
  228. continue
  229. if item.startswith(";"):
  230. continue
  231. try:
  232. if item[0] == "X":
  233. x = float(item[1:])
  234. elif item[0] == "Y":
  235. y = float(item[1:])
  236. elif item[0] == "Z":
  237. z = float(item[1:])
  238. elif item[0] == "F":
  239. f = float(item[1:]) / 60
  240. elif item[0] == "E":
  241. e = float(item[1:])
  242. except ValueError: # Improperly formatted g-code: Coordinates are not floats.
  243. continue # Skip the command then.
  244. params = PositionOptional(x, y, z, f, e)
  245. return func(position, params, path)
  246. return position
  247. def processTCode(self, T: int, line: str, position: Position, path: List[List[Union[float, int]]]) -> Position:
  248. self._extruder_number = T
  249. if self._extruder_number + 1 > len(position.e):
  250. self._extrusion_length_offset.extend([0] * (self._extruder_number - len(position.e) + 1))
  251. position.e.extend([0] * (self._extruder_number - len(position.e) + 1))
  252. return position
  253. def processMCode(self, M: int, line: str, position: Position, path: List[List[Union[float, int]]]) -> Position:
  254. pass
  255. _type_keyword = ";TYPE:"
  256. _layer_keyword = ";LAYER:"
  257. def _extruderOffsets(self) -> Dict[int, List[float]]:
  258. """For showing correct x, y offsets for each extruder"""
  259. result = {}
  260. for extruder in ExtruderManager.getInstance().getActiveExtruderStacks():
  261. result[int(extruder.getMetaData().get("position", "0"))] = [
  262. extruder.getProperty("machine_nozzle_offset_x", "value"),
  263. extruder.getProperty("machine_nozzle_offset_y", "value")]
  264. return result
  265. #
  266. # CURA-6643
  267. # This function needs the filename so it can be set to the SceneNode. Otherwise, if you load a GCode file and press
  268. # F5, that gcode SceneNode will be removed because it doesn't have a file to be reloaded from.
  269. #
  270. def processGCodeStream(self, stream: str, filename: str) -> Optional["CuraSceneNode"]:
  271. Logger.log("d", "Preparing to load g-code")
  272. self._cancelled = False
  273. # We obtain the filament diameter from the selected extruder to calculate line widths
  274. global_stack = CuraApplication.getInstance().getGlobalContainerStack()
  275. if not global_stack:
  276. return None
  277. self._filament_diameter = global_stack.extruderList[self._extruder_number].getProperty("material_diameter", "value")
  278. scene_node = CuraSceneNode()
  279. gcode_list = []
  280. self._is_layers_in_file = False
  281. self._extruder_offsets = self._extruderOffsets() # dict with index the extruder number. can be empty
  282. ##############################################################################################
  283. ## This part is where the action starts
  284. ##############################################################################################
  285. file_lines = 0
  286. current_line = 0
  287. for line in stream.split("\n"):
  288. file_lines += 1
  289. gcode_list.append(line + "\n")
  290. if not self._is_layers_in_file and line[:len(self._layer_keyword)] == self._layer_keyword:
  291. self._is_layers_in_file = True
  292. file_step = max(math.floor(file_lines / 100), 1)
  293. self._clearValues()
  294. self._message = Message(catalog.i18nc("@info:status", "Parsing G-code"),
  295. lifetime=0,
  296. title = catalog.i18nc("@info:title", "G-code Details"))
  297. assert(self._message is not None) # use for typing purposes
  298. self._message.setProgress(0)
  299. self._message.show()
  300. Logger.log("d", "Parsing g-code...")
  301. current_position = Position(0, 0, 0, 0, [0])
  302. current_path = [] #type: List[List[float]]
  303. min_layer_number = 0
  304. negative_layers = 0
  305. previous_layer = 0
  306. self._previous_extrusion_value = 0.0
  307. for line in stream.split("\n"):
  308. if self._cancelled:
  309. Logger.log("d", "Parsing g-code file cancelled.")
  310. return None
  311. current_line += 1
  312. if current_line % file_step == 0:
  313. self._message.setProgress(math.floor(current_line / file_lines * 100))
  314. Job.yieldThread()
  315. if len(line) == 0:
  316. continue
  317. if line.find(self._type_keyword) == 0:
  318. type = line[len(self._type_keyword):].strip()
  319. if type == "WALL-INNER":
  320. self._layer_type = LayerPolygon.InsetXType
  321. elif type == "WALL-OUTER":
  322. self._layer_type = LayerPolygon.Inset0Type
  323. elif type == "SKIN":
  324. self._layer_type = LayerPolygon.SkinType
  325. elif type == "SKIRT":
  326. self._layer_type = LayerPolygon.SkirtType
  327. elif type == "SUPPORT":
  328. self._layer_type = LayerPolygon.SupportType
  329. elif type == "FILL":
  330. self._layer_type = LayerPolygon.InfillType
  331. elif type == "SUPPORT-INTERFACE":
  332. self._layer_type = LayerPolygon.SupportInterfaceType
  333. elif type == "PRIME-TOWER":
  334. self._layer_type = LayerPolygon.PrimeTowerType
  335. else:
  336. Logger.log("w", "Encountered a unknown type (%s) while parsing g-code.", type)
  337. # When the layer change is reached, the polygon is computed so we have just one layer per extruder
  338. if self._is_layers_in_file and line[:len(self._layer_keyword)] == self._layer_keyword:
  339. try:
  340. layer_number = int(line[len(self._layer_keyword):])
  341. self._createPolygon(self._current_layer_thickness, current_path, self._extruder_offsets.get(self._extruder_number, [0, 0]))
  342. current_path.clear()
  343. # Start the new layer at the end position of the last layer
  344. current_path.append([current_position.x, current_position.y, current_position.z, current_position.f, current_position.e[self._extruder_number], LayerPolygon.MoveCombingType])
  345. # When using a raft, the raft layers are stored as layers < 0, it mimics the same behavior
  346. # as in ProcessSlicedLayersJob
  347. if layer_number < min_layer_number:
  348. min_layer_number = layer_number
  349. if layer_number < 0:
  350. layer_number += abs(min_layer_number)
  351. negative_layers += 1
  352. else:
  353. layer_number += negative_layers
  354. # In case there is a gap in the layer count, empty layers are created
  355. for empty_layer in range(previous_layer + 1, layer_number):
  356. self._createEmptyLayer(empty_layer)
  357. self._layer_number = layer_number
  358. previous_layer = layer_number
  359. except:
  360. pass
  361. # This line is a comment. Ignore it (except for the layer_keyword)
  362. if line.startswith(";"):
  363. continue
  364. G = self._getInt(line, "G")
  365. if G is not None:
  366. # When find a movement, the new position is calculated and added to the current_path, but
  367. # don't need to create a polygon until the end of the layer
  368. current_position = self.processGCode(G, line, current_position, current_path)
  369. continue
  370. # When changing the extruder, the polygon with the stored paths is computed
  371. if line.startswith("T"):
  372. T = self._getInt(line, "T")
  373. if T is not None:
  374. self._extruders_seen.add(T)
  375. self._createPolygon(self._current_layer_thickness, current_path, self._extruder_offsets.get(self._extruder_number, [0, 0]))
  376. current_path.clear()
  377. # When changing tool, store the end point of the previous path, then process the code and finally
  378. # add another point with the new position of the head.
  379. current_path.append([current_position.x, current_position.y, current_position.z, current_position.f, current_position.e[self._extruder_number], LayerPolygon.MoveCombingType])
  380. current_position = self.processTCode(T, line, current_position, current_path)
  381. current_path.append([current_position.x, current_position.y, current_position.z, current_position.f, current_position.e[self._extruder_number], LayerPolygon.MoveCombingType])
  382. if line.startswith("M"):
  383. M = self._getInt(line, "M")
  384. if M is not None:
  385. self.processMCode(M, line, current_position, current_path)
  386. # "Flush" leftovers. Last layer paths are still stored
  387. if len(current_path) > 1:
  388. if self._createPolygon(self._current_layer_thickness, current_path, self._extruder_offsets.get(self._extruder_number, [0, 0])):
  389. self._layer_number += 1
  390. current_path.clear()
  391. material_color_map = numpy.zeros((8, 4), dtype = numpy.float32)
  392. material_color_map[0, :] = [0.0, 0.7, 0.9, 1.0]
  393. material_color_map[1, :] = [0.7, 0.9, 0.0, 1.0]
  394. material_color_map[2, :] = [0.9, 0.0, 0.7, 1.0]
  395. material_color_map[3, :] = [0.7, 0.0, 0.0, 1.0]
  396. material_color_map[4, :] = [0.0, 0.7, 0.0, 1.0]
  397. material_color_map[5, :] = [0.0, 0.0, 0.7, 1.0]
  398. material_color_map[6, :] = [0.3, 0.3, 0.3, 1.0]
  399. material_color_map[7, :] = [0.7, 0.7, 0.7, 1.0]
  400. layer_mesh = self._layer_data_builder.build(material_color_map)
  401. decorator = LayerDataDecorator()
  402. decorator.setLayerData(layer_mesh)
  403. scene_node.addDecorator(decorator)
  404. gcode_list_decorator = GCodeListDecorator()
  405. gcode_list_decorator.setGcodeFileName(filename)
  406. gcode_list_decorator.setGCodeList(gcode_list)
  407. scene_node.addDecorator(gcode_list_decorator)
  408. # gcode_dict stores gcode_lists for a number of build plates.
  409. active_build_plate_id = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  410. gcode_dict = {active_build_plate_id: gcode_list}
  411. CuraApplication.getInstance().getController().getScene().gcode_dict = gcode_dict #type: ignore #Because gcode_dict is generated dynamically.
  412. Logger.log("d", "Finished parsing g-code.")
  413. self._message.hide()
  414. if self._layer_number == 0:
  415. Logger.log("w", "File doesn't contain any valid layers")
  416. if not global_stack.getProperty("machine_center_is_zero", "value"):
  417. machine_width = global_stack.getProperty("machine_width", "value")
  418. machine_depth = global_stack.getProperty("machine_depth", "value")
  419. scene_node.setPosition(Vector(-machine_width / 2, 0, machine_depth / 2))
  420. Logger.log("d", "G-code loading finished.")
  421. if CuraApplication.getInstance().getPreferences().getValue("gcodereader/show_caution"):
  422. caution_message = Message(catalog.i18nc(
  423. "@info:generic",
  424. "Make sure the g-code is suitable for your printer and printer configuration before sending the file to it. The g-code representation may not be accurate."),
  425. lifetime=0,
  426. title = catalog.i18nc("@info:title", "G-code Details"),
  427. message_type = Message.MessageType.WARNING)
  428. caution_message.show()
  429. # The "save/print" button's state is bound to the backend state.
  430. backend = CuraApplication.getInstance().getBackend()
  431. backend.backendStateChange.emit(Backend.BackendState.Disabled)
  432. return scene_node