Tue, 19 Jan 2021 20:45:09 +0100
updated main files to new github master version
15 | 1 | #!/usr/bin/env python |
2 | # This file is copied from GCoder. | |
3 | # | |
4 | # GCoder is free software: you can redistribute it and/or modify | |
5 | # it under the terms of the GNU General Public License as published by | |
6 | # the Free Software Foundation, either version 3 of the License, or | |
7 | # (at your option) any later version. | |
8 | # | |
9 | # GCoder is distributed in the hope that it will be useful, | |
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 | # GNU General Public License for more details. | |
13 | # | |
14 | # You should have received a copy of the GNU General Public License | |
15 | # along with Printrun. If not, see <http://www.gnu.org/licenses/>. | |
16 | ||
17 | import sys | |
18 | import re | |
19 | import math | |
20 | import datetime | |
21 | import logging | |
22 | from array import array | |
23 | ||
24 | gcode_parsed_args = ["x", "y", "e", "f", "z", "i", "j"] | |
25 | gcode_parsed_nonargs = ["g", "t", "m", "n"] | |
26 | to_parse = "".join(gcode_parsed_args + gcode_parsed_nonargs) | |
27 | gcode_exp = re.compile("\([^\(\)]*\)|;.*|[/\*].*\n|([%s])([-+]?[0-9]*\.?[0-9]*)" % to_parse) | |
28 | gcode_strip_comment_exp = re.compile("\([^\(\)]*\)|;.*|[/\*].*\n") | |
29 | m114_exp = re.compile("\([^\(\)]*\)|[/\*].*\n|([XYZ]):?([-+]?[0-9]*\.?[0-9]*)") | |
30 | specific_exp = "(?:\([^\(\)]*\))|(?:;.*)|(?:[/\*].*\n)|(%s[-+]?[0-9]*\.?[0-9]*)" | |
31 | move_gcodes = ["G0", "G1", "G2", "G3"] | |
32 | ||
33 | class PyLine(object): | |
34 | ||
35 | __slots__ = ('x', 'y', 'z', 'e', 'f', 'i', 'j', | |
36 | 'raw', 'command', 'is_move', | |
37 | 'relative', 'relative_e', | |
38 | 'current_x', 'current_y', 'current_z', 'extruding', | |
39 | 'current_tool', | |
40 | 'gcview_end_vertex') | |
41 | ||
42 | def __init__(self, l): | |
43 | self.raw = l | |
44 | ||
45 | def __getattr__(self, name): | |
46 | return None | |
47 | ||
48 | class PyLightLine(object): | |
49 | ||
50 | __slots__ = ('raw', 'command') | |
51 | ||
52 | def __init__(self, l): | |
53 | self.raw = l | |
54 | ||
55 | def __getattr__(self, name): | |
56 | return None | |
57 | ||
58 | try: | |
59 | import gcoder_line | |
60 | Line = gcoder_line.GLine | |
61 | LightLine = gcoder_line.GLightLine | |
62 | except Exception, e: | |
63 | logging.warning("Memory-efficient GCoder implementation unavailable: %s" % e) | |
64 | Line = PyLine | |
65 | LightLine = PyLightLine | |
66 | ||
67 | def find_specific_code(line, code): | |
68 | exp = specific_exp % code | |
69 | bits = [bit for bit in re.findall(exp, line.raw) if bit] | |
70 | if not bits: return None | |
71 | else: return float(bits[0][1:]) | |
72 | ||
73 | def S(line): | |
74 | return find_specific_code(line, "S") | |
75 | ||
76 | def P(line): | |
77 | return find_specific_code(line, "P") | |
78 | ||
79 | def split(line): | |
80 | split_raw = gcode_exp.findall(line.raw.lower()) | |
81 | if split_raw and split_raw[0][0] == "n": | |
82 | del split_raw[0] | |
83 | if not split_raw: | |
84 | line.command = line.raw | |
85 | line.is_move = False | |
86 | logging.warning("raw G-Code line \"%s\" could not be parsed" % line.raw) | |
87 | return [line.raw] | |
88 | command = split_raw[0] | |
89 | line.command = command[0].upper() + command[1] | |
90 | line.is_move = line.command in move_gcodes | |
91 | return split_raw | |
92 | ||
93 | def parse_coordinates(line, split_raw, imperial = False, force = False): | |
94 | # Not a G-line, we don't want to parse its arguments | |
95 | if not force and line.command[0] != "G": | |
96 | return | |
97 | unit_factor = 25.4 if imperial else 1 | |
98 | for bit in split_raw: | |
99 | code = bit[0] | |
100 | if code not in gcode_parsed_nonargs and bit[1]: | |
101 | setattr(line, code, unit_factor * float(bit[1])) | |
102 | ||
103 | class Layer(list): | |
104 | ||
105 | __slots__ = ("duration", "z") | |
106 | ||
107 | def __init__(self, lines, z = None): | |
108 | super(Layer, self).__init__(lines) | |
109 | self.z = z | |
110 | ||
111 | class GCode(object): | |
112 | ||
113 | line_class = Line | |
114 | ||
115 | lines = None | |
116 | layers = None | |
117 | all_layers = None | |
118 | layer_idxs = None | |
119 | line_idxs = None | |
120 | append_layer = None | |
121 | append_layer_id = None | |
122 | ||
123 | imperial = False | |
124 | relative = False | |
125 | relative_e = False | |
126 | current_tool = 0 | |
127 | # Home position: current absolute position counted from machine origin | |
128 | home_x = 0 | |
129 | home_y = 0 | |
130 | home_z = 0 | |
131 | # Current position: current absolute position counted from machine origin | |
132 | current_x = 0 | |
133 | current_y = 0 | |
134 | current_z = 0 | |
135 | # For E this is the absolute position from machine start | |
136 | current_e = 0 | |
137 | current_e_multi=[0] | |
138 | total_e = 0 | |
139 | total_e_multi=[0] | |
140 | max_e = 0 | |
141 | max_e_multi=[0] | |
142 | # Current feedrate | |
143 | current_f = 0 | |
144 | # Offset: current offset between the machine origin and the machine current | |
145 | # absolute coordinate system (as shifted by G92s) | |
146 | offset_x = 0 | |
147 | offset_y = 0 | |
148 | offset_z = 0 | |
149 | offset_e = 0 | |
150 | offset_e_multi = [0] | |
151 | ||
152 | # Expected behavior: | |
153 | # - G28 X => X axis is homed, offset_x <- 0, current_x <- home_x | |
154 | # - G92 Xk => X axis does not move, so current_x does not change | |
155 | # and offset_x <- current_x - k, | |
156 | # - absolute G1 Xk => X axis moves, current_x <- offset_x + k | |
157 | # How to get... | |
158 | # current abs X from machine origin: current_x | |
159 | # current abs X in machine current coordinate system: current_x - offset_x | |
160 | ||
161 | filament_length = None | |
162 | filament_length_multi=[0] | |
163 | duration = None | |
164 | xmin = None | |
165 | xmax = None | |
166 | ymin = None | |
167 | ymax = None | |
168 | zmin = None | |
169 | zmax = None | |
170 | width = None | |
171 | depth = None | |
172 | height = None | |
173 | ||
174 | est_layer_height = None | |
175 | ||
176 | # abs_x is the current absolute X in machine current coordinate system | |
177 | # (after the various G92 transformations) and can be used to store the | |
178 | # absolute position of the head at a given time | |
179 | def _get_abs_x(self): | |
180 | return self.current_x - self.offset_x | |
181 | abs_x = property(_get_abs_x) | |
182 | ||
183 | def _get_abs_y(self): | |
184 | return self.current_y - self.offset_y | |
185 | abs_y = property(_get_abs_y) | |
186 | ||
187 | def _get_abs_z(self): | |
188 | return self.current_z - self.offset_z | |
189 | abs_z = property(_get_abs_z) | |
190 | ||
191 | def _get_abs_e(self): | |
192 | return self.current_e - self.offset_e | |
193 | abs_e = property(_get_abs_e) | |
194 | ||
195 | def _get_abs_e_multi(self,i): | |
196 | return self.current_e_multi[i] - self.offset_e_multi[i] | |
197 | abs_e = property(_get_abs_e) | |
198 | ||
199 | def _get_abs_pos(self): | |
200 | return (self.abs_x, self.abs_y, self.abs_z) | |
201 | abs_pos = property(_get_abs_pos) | |
202 | ||
203 | def _get_current_pos(self): | |
204 | return (self.current_x, self.current_y, self.current_z) | |
205 | current_pos = property(_get_current_pos) | |
206 | ||
207 | def _get_home_pos(self): | |
208 | return (self.home_x, self.home_y, self.home_z) | |
209 | ||
210 | def _set_home_pos(self, home_pos): | |
211 | if home_pos: | |
212 | self.home_x, self.home_y, self.home_z = home_pos | |
213 | home_pos = property(_get_home_pos, _set_home_pos) | |
214 | ||
215 | def _get_layers_count(self): | |
216 | return len(self.all_zs) | |
217 | layers_count = property(_get_layers_count) | |
218 | ||
219 | def __init__(self, data = None, home_pos = None, | |
220 | layer_callback = None, deferred = False): | |
221 | if not deferred: | |
222 | self.prepare(data, home_pos, layer_callback) | |
223 | ||
224 | def prepare(self, data = None, home_pos = None, layer_callback = None): | |
225 | self.home_pos = home_pos | |
226 | if data: | |
227 | line_class = self.line_class | |
228 | self.lines = [line_class(l2) for l2 in | |
229 | (l.strip() for l in data) | |
230 | if l2] | |
231 | self._preprocess(build_layers = True, | |
232 | layer_callback = layer_callback) | |
233 | else: | |
234 | self.lines = [] | |
235 | self.append_layer_id = 0 | |
236 | self.append_layer = Layer([]) | |
237 | self.all_layers = [self.append_layer] | |
238 | self.all_zs = set() | |
239 | self.layers = {} | |
240 | self.layer_idxs = array('I', []) | |
241 | self.line_idxs = array('I', []) | |
242 | ||
243 | def __len__(self): | |
244 | return len(self.line_idxs) | |
245 | ||
246 | def __iter__(self): | |
247 | return self.lines.__iter__() | |
248 | ||
249 | def prepend_to_layer(self, commands, layer_idx): | |
250 | # Prepend commands in reverse order | |
251 | commands = [c.strip() for c in commands[::-1] if c.strip()] | |
252 | layer = self.all_layers[layer_idx] | |
253 | # Find start index to append lines | |
254 | # and end index to append new indices | |
255 | start_index = self.layer_idxs.index(layer_idx) | |
256 | for i in range(start_index, len(self.layer_idxs)): | |
257 | if self.layer_idxs[i] != layer_idx: | |
258 | end_index = i | |
259 | break | |
260 | else: | |
261 | end_index = i + 1 | |
262 | end_line = self.line_idxs[end_index - 1] | |
263 | for i, command in enumerate(commands): | |
264 | gline = Line(command) | |
265 | # Split to get command | |
266 | split(gline) | |
267 | # Force is_move to False | |
268 | gline.is_move = False | |
269 | # Insert gline at beginning of layer | |
270 | layer.insert(0, gline) | |
271 | # Insert gline at beginning of list | |
272 | self.lines.insert(start_index, gline) | |
273 | # Update indices arrays & global gcodes list | |
274 | self.layer_idxs.insert(end_index + i, layer_idx) | |
275 | self.line_idxs.insert(end_index + i, end_line + i + 1) | |
276 | return commands[::-1] | |
277 | ||
278 | def rewrite_layer(self, commands, layer_idx): | |
279 | # Prepend commands in reverse order | |
280 | commands = [c.strip() for c in commands[::-1] if c.strip()] | |
281 | layer = self.all_layers[layer_idx] | |
282 | # Find start index to append lines | |
283 | # and end index to append new indices | |
284 | start_index = self.layer_idxs.index(layer_idx) | |
285 | for i in range(start_index, len(self.layer_idxs)): | |
286 | if self.layer_idxs[i] != layer_idx: | |
287 | end_index = i | |
288 | break | |
289 | else: | |
290 | end_index = i + 1 | |
291 | self.layer_idxs = self.layer_idxs[:start_index] + array('I', len(commands) * [layer_idx]) + self.layer_idxs[end_index:] | |
292 | self.line_idxs = self.line_idxs[:start_index] + array('I', range(len(commands))) + self.line_idxs[end_index:] | |
293 | del self.lines[start_index:end_index] | |
294 | del layer[:] | |
295 | for i, command in enumerate(commands): | |
296 | gline = Line(command) | |
297 | # Split to get command | |
298 | split(gline) | |
299 | # Force is_move to False | |
300 | gline.is_move = False | |
301 | # Insert gline at beginning of layer | |
302 | layer.insert(0, gline) | |
303 | # Insert gline at beginning of list | |
304 | self.lines.insert(start_index, gline) | |
305 | return commands[::-1] | |
306 | ||
307 | def append(self, command, store = True): | |
308 | command = command.strip() | |
309 | if not command: | |
310 | return | |
311 | gline = Line(command) | |
312 | self._preprocess([gline]) | |
313 | if store: | |
314 | self.lines.append(gline) | |
315 | self.append_layer.append(gline) | |
316 | self.layer_idxs.append(self.append_layer_id) | |
317 | self.line_idxs.append(len(self.append_layer)) | |
318 | return gline | |
319 | ||
320 | def _preprocess(self, lines = None, build_layers = False, | |
321 | layer_callback = None): | |
322 | """Checks for imperial/relativeness settings and tool changes""" | |
323 | if not lines: | |
324 | lines = self.lines | |
325 | imperial = self.imperial | |
326 | relative = self.relative | |
327 | relative_e = self.relative_e | |
328 | current_tool = self.current_tool | |
329 | current_x = self.current_x | |
330 | current_y = self.current_y | |
331 | current_z = self.current_z | |
332 | offset_x = self.offset_x | |
333 | offset_y = self.offset_y | |
334 | offset_z = self.offset_z | |
335 | ||
336 | # Extrusion computation | |
337 | current_e = self.current_e | |
338 | offset_e = self.offset_e | |
339 | total_e = self.total_e | |
340 | max_e = self.max_e | |
341 | ||
342 | current_e_multi = self.current_e_multi[current_tool] | |
343 | offset_e_multi = self.offset_e_multi[current_tool] | |
344 | total_e_multi = self.total_e_multi[current_tool] | |
345 | max_e_multi = self.max_e_multi[current_tool] | |
346 | ||
347 | # Store this one out of the build_layers scope for efficiency | |
348 | cur_layer_has_extrusion = False | |
349 | ||
350 | # Initialize layers and other global computations | |
351 | if build_layers: | |
352 | # Bounding box computation | |
353 | xmin = float("inf") | |
354 | ymin = float("inf") | |
355 | zmin = 0 | |
356 | xmax = float("-inf") | |
357 | ymax = float("-inf") | |
358 | zmax = float("-inf") | |
359 | # Also compute extrusion-only values | |
360 | xmin_e = float("inf") | |
361 | ymin_e = float("inf") | |
362 | xmax_e = float("-inf") | |
363 | ymax_e = float("-inf") | |
364 | ||
365 | # Duration estimation | |
366 | # TODO: | |
367 | # get device caps from firmware: max speed, acceleration/axis | |
368 | # (including extruder) | |
369 | # calculate the maximum move duration accounting for above ;) | |
370 | lastx = lasty = lastz = laste = lastf = 0.0 | |
371 | lastdx = 0 | |
372 | lastdy = 0 | |
373 | x = y = e = f = 0.0 | |
374 | currenttravel = 0.0 | |
375 | moveduration = 0.0 | |
376 | totalduration = 0.0 | |
377 | acceleration = 2000.0 # mm/s^2 | |
378 | layerbeginduration = 0.0 | |
379 | ||
380 | # Initialize layers | |
381 | all_layers = self.all_layers = [] | |
382 | all_zs = self.all_zs = set() | |
383 | layer_idxs = self.layer_idxs = [] | |
384 | line_idxs = self.line_idxs = [] | |
385 | ||
386 | layer_id = 0 | |
387 | layer_line = 0 | |
388 | ||
389 | last_layer_z = None | |
390 | prev_z = None | |
391 | prev_base_z = (None, None) | |
392 | cur_z = None | |
393 | cur_lines = [] | |
394 | ||
395 | if self.line_class != Line: | |
396 | get_line = lambda l: Line(l.raw) | |
397 | else: | |
398 | get_line = lambda l: l | |
399 | for true_line in lines: | |
400 | # # Parse line | |
401 | # Use a heavy copy of the light line to preprocess | |
402 | line = get_line(true_line) | |
403 | split_raw = split(line) | |
404 | if line.command: | |
405 | # Update properties | |
406 | if line.is_move: | |
407 | line.relative = relative | |
408 | line.relative_e = relative_e | |
409 | line.current_tool = current_tool | |
410 | elif line.command == "G20": | |
411 | imperial = True | |
412 | elif line.command == "G21": | |
413 | imperial = False | |
414 | elif line.command == "G90": | |
415 | relative = False | |
416 | relative_e = False | |
417 | elif line.command == "G91": | |
418 | relative = True | |
419 | relative_e = True | |
420 | elif line.command == "M82": | |
421 | relative_e = False | |
422 | elif line.command == "M83": | |
423 | relative_e = True | |
424 | elif line.command[0] == "T": | |
425 | current_tool = int(line.command[1:]) | |
426 | while(current_tool+1>len(self.current_e_multi)): | |
427 | self.current_e_multi+=[0] | |
428 | self.offset_e_multi+=[0] | |
429 | self.total_e_multi+=[0] | |
430 | self.max_e_multi+=[0] | |
431 | current_e_multi = self.current_e_multi[current_tool] | |
432 | offset_e_multi = self.offset_e_multi[current_tool] | |
433 | total_e_multi = self.total_e_multi[current_tool] | |
434 | max_e_multi = self.max_e_multi[current_tool] | |
435 | ||
436 | ||
437 | if line.command[0] == "G": | |
438 | parse_coordinates(line, split_raw, imperial) | |
439 | ||
440 | # Compute current position | |
441 | if line.is_move: | |
442 | x = line.x | |
443 | y = line.y | |
444 | z = line.z | |
445 | ||
446 | if line.f is not None: | |
447 | self.current_f = line.f | |
448 | ||
449 | if line.relative: | |
450 | x = current_x + (x or 0) | |
451 | y = current_y + (y or 0) | |
452 | z = current_z + (z or 0) | |
453 | else: | |
454 | if x is not None: x = x + offset_x | |
455 | if y is not None: y = y + offset_y | |
456 | if z is not None: z = z + offset_z | |
457 | ||
458 | if x is not None: current_x = x | |
459 | if y is not None: current_y = y | |
460 | if z is not None: current_z = z | |
461 | ||
462 | elif line.command == "G28": | |
463 | home_all = not any([line.x, line.y, line.z]) | |
464 | if home_all or line.x is not None: | |
465 | offset_x = 0 | |
466 | current_x = self.home_x | |
467 | if home_all or line.y is not None: | |
468 | offset_y = 0 | |
469 | current_y = self.home_y | |
470 | if home_all or line.z is not None: | |
471 | offset_z = 0 | |
472 | current_z = self.home_z | |
473 | ||
474 | elif line.command == "G92": | |
475 | if line.x is not None: offset_x = current_x - line.x | |
476 | if line.y is not None: offset_y = current_y - line.y | |
477 | if line.z is not None: offset_z = current_z - line.z | |
478 | ||
479 | line.current_x = current_x | |
480 | line.current_y = current_y | |
481 | line.current_z = current_z | |
482 | ||
483 | # # Process extrusion | |
484 | if line.e is not None: | |
485 | if line.is_move: | |
486 | if line.relative_e: | |
487 | line.extruding = line.e > 0 | |
488 | total_e += line.e | |
489 | current_e += line.e | |
490 | total_e_multi += line.e | |
491 | current_e_multi += line.e | |
492 | else: | |
493 | new_e = line.e + offset_e | |
494 | line.extruding = new_e > current_e | |
495 | total_e += new_e - current_e | |
496 | current_e = new_e | |
497 | new_e_multi = line.e + offset_e_multi | |
498 | total_e_multi += new_e_multi - current_e_multi | |
499 | current_e_multi = new_e_multi | |
500 | ||
501 | max_e = max(max_e, total_e) | |
502 | max_e_multi=max(max_e_multi, total_e_multi) | |
503 | cur_layer_has_extrusion |= line.extruding | |
504 | elif line.command == "G92": | |
505 | offset_e = current_e - line.e | |
506 | offset_e_multi = current_e_multi - line.e | |
507 | ||
508 | self.current_e_multi[current_tool]=current_e_multi | |
509 | self.offset_e_multi[current_tool]=offset_e_multi | |
510 | self.max_e_multi[current_tool]=max_e_multi | |
511 | self.total_e_multi[current_tool]=total_e_multi | |
512 | ||
513 | # # Create layers and perform global computations | |
514 | if build_layers: | |
515 | # Update bounding box | |
516 | if line.is_move: | |
517 | if line.extruding: | |
518 | if line.current_x is not None: | |
519 | xmin_e = min(xmin_e, line.current_x) | |
520 | xmax_e = max(xmax_e, line.current_x) | |
521 | if line.current_y is not None: | |
522 | ymin_e = min(ymin_e, line.current_y) | |
523 | ymax_e = max(ymax_e, line.current_y) | |
524 | if max_e <= 0: | |
525 | if line.current_x is not None: | |
526 | xmin = min(xmin, line.current_x) | |
527 | xmax = max(xmax, line.current_x) | |
528 | if line.current_y is not None: | |
529 | ymin = min(ymin, line.current_y) | |
530 | ymax = max(ymax, line.current_y) | |
531 | ||
532 | # Compute duration | |
533 | if line.command == "G0" or line.command == "G1": | |
534 | x = line.x if line.x is not None else lastx | |
535 | y = line.y if line.y is not None else lasty | |
536 | z = line.z if line.z is not None else lastz | |
537 | e = line.e if line.e is not None else laste | |
538 | # mm/s vs mm/m => divide by 60 | |
539 | f = line.f / 60.0 if line.f is not None else lastf | |
540 | ||
541 | # given last feedrate and current feedrate calculate the | |
542 | # distance needed to achieve current feedrate. | |
543 | # if travel is longer than req'd distance, then subtract | |
544 | # distance to achieve full speed, and add the time it took | |
545 | # to get there. | |
546 | # then calculate the time taken to complete the remaining | |
547 | # distance | |
548 | ||
549 | # FIXME: this code has been proven to be super wrong when 2 | |
550 | # subsquent moves are in opposite directions, as requested | |
551 | # speed is constant but printer has to fully decellerate | |
552 | # and reaccelerate | |
553 | # The following code tries to fix it by forcing a full | |
554 | # reacceleration if this move is in the opposite direction | |
555 | # of the previous one | |
556 | dx = x - lastx | |
557 | dy = y - lasty | |
558 | if dx * lastdx + dy * lastdy <= 0: | |
559 | lastf = 0 | |
560 | ||
561 | currenttravel = math.hypot(dx, dy) | |
562 | if currenttravel == 0: | |
563 | if line.z is not None: | |
564 | currenttravel = abs(line.z) if line.relative else abs(line.z - lastz) | |
565 | elif line.e is not None: | |
566 | currenttravel = abs(line.e) if line.relative_e else abs(line.e - laste) | |
567 | # Feedrate hasn't changed, no acceleration/decceleration planned | |
568 | if f == lastf: | |
569 | moveduration = currenttravel / f if f != 0 else 0. | |
570 | else: | |
571 | # FIXME: review this better | |
572 | # this looks wrong : there's little chance that the feedrate we'll decelerate to is the previous feedrate | |
573 | # shouldn't we instead look at three consecutive moves ? | |
574 | distance = 2 * abs(((lastf + f) * (f - lastf) * 0.5) / acceleration) # multiply by 2 because we have to accelerate and decelerate | |
575 | if distance <= currenttravel and lastf + f != 0 and f != 0: | |
576 | moveduration = 2 * distance / (lastf + f) # This is distance / mean(lastf, f) | |
577 | moveduration += (currenttravel - distance) / f | |
578 | else: | |
579 | moveduration = 2 * currenttravel / (lastf + f) # This is currenttravel / mean(lastf, f) | |
580 | # FIXME: probably a little bit optimistic, but probably a much better estimate than the previous one: | |
581 | # moveduration = math.sqrt(2 * distance / acceleration) # probably buggy : not taking actual travel into account | |
582 | ||
583 | lastdx = dx | |
584 | lastdy = dy | |
585 | ||
586 | totalduration += moveduration | |
587 | ||
588 | lastx = x | |
589 | lasty = y | |
590 | lastz = z | |
591 | laste = e | |
592 | lastf = f | |
593 | elif line.command == "G4": | |
594 | moveduration = P(line) | |
595 | if moveduration: | |
596 | moveduration /= 1000.0 | |
597 | totalduration += moveduration | |
598 | ||
599 | # FIXME : looks like this needs to be tested with "lift Z on move" | |
600 | if line.z is not None: | |
601 | if line.command == "G92": | |
602 | cur_z = line.z | |
603 | elif line.is_move: | |
604 | if line.relative and cur_z is not None: | |
605 | cur_z += line.z | |
606 | else: | |
607 | cur_z = line.z | |
608 | ||
609 | # FIXME: the logic behind this code seems to work, but it might be | |
610 | # broken | |
611 | if cur_z != prev_z: | |
612 | if prev_z is not None and last_layer_z is not None: | |
613 | offset = self.est_layer_height if self.est_layer_height else 0.01 | |
614 | if abs(prev_z - last_layer_z) < offset: | |
615 | if self.est_layer_height is None: | |
616 | zs = sorted([l.z for l in all_layers if l.z is not None]) | |
617 | heights = [round(zs[i + 1] - zs[i], 3) for i in range(len(zs) - 1)] | |
618 | heights = [height for height in heights if height] | |
619 | if len(heights) >= 2: self.est_layer_height = heights[1] | |
620 | elif heights: self.est_layer_height = heights[0] | |
621 | else: self.est_layer_height = 0.1 | |
622 | base_z = round(prev_z - (prev_z % self.est_layer_height), 2) | |
623 | else: | |
624 | base_z = round(prev_z, 2) | |
625 | else: | |
626 | base_z = prev_z | |
627 | ||
628 | if base_z != prev_base_z: | |
629 | new_layer = Layer(cur_lines, base_z) | |
630 | new_layer.duration = totalduration - layerbeginduration | |
631 | layerbeginduration = totalduration | |
632 | all_layers.append(new_layer) | |
633 | if cur_layer_has_extrusion and prev_z not in all_zs: | |
634 | all_zs.add(prev_z) | |
635 | cur_lines = [] | |
636 | cur_layer_has_extrusion = False | |
637 | layer_id += 1 | |
638 | layer_line = 0 | |
639 | last_layer_z = base_z | |
640 | if layer_callback is not None: | |
641 | layer_callback(self, len(all_layers) - 1) | |
642 | ||
643 | prev_base_z = base_z | |
644 | ||
645 | if build_layers: | |
646 | cur_lines.append(true_line) | |
647 | layer_idxs.append(layer_id) | |
648 | line_idxs.append(layer_line) | |
649 | layer_line += 1 | |
650 | prev_z = cur_z | |
651 | # ## Loop done | |
652 | ||
653 | # Store current status | |
654 | self.imperial = imperial | |
655 | self.relative = relative | |
656 | self.relative_e = relative_e | |
657 | self.current_tool = current_tool | |
658 | self.current_x = current_x | |
659 | self.current_y = current_y | |
660 | self.current_z = current_z | |
661 | self.offset_x = offset_x | |
662 | self.offset_y = offset_y | |
663 | self.offset_z = offset_z | |
664 | self.current_e = current_e | |
665 | self.offset_e = offset_e | |
666 | self.max_e = max_e | |
667 | self.total_e = total_e | |
668 | self.current_e_multi[current_tool]=current_e_multi | |
669 | self.offset_e_multi[current_tool]=offset_e_multi | |
670 | self.max_e_multi[current_tool]=max_e_multi | |
671 | self.total_e_multi[current_tool]=total_e_multi | |
672 | ||
673 | ||
674 | # Finalize layers | |
675 | if build_layers: | |
676 | if cur_lines: | |
677 | new_layer = Layer(cur_lines, prev_z) | |
678 | new_layer.duration = totalduration - layerbeginduration | |
679 | layerbeginduration = totalduration | |
680 | all_layers.append(new_layer) | |
681 | if cur_layer_has_extrusion and prev_z not in all_zs: | |
682 | all_zs.add(prev_z) | |
683 | ||
684 | self.append_layer_id = len(all_layers) | |
685 | self.append_layer = Layer([]) | |
686 | self.append_layer.duration = 0 | |
687 | all_layers.append(self.append_layer) | |
688 | self.layer_idxs = array('I', layer_idxs) | |
689 | self.line_idxs = array('I', line_idxs) | |
690 | ||
691 | # Compute bounding box | |
692 | all_zs = self.all_zs.union(set([zmin])).difference(set([None])) | |
693 | zmin = min(all_zs) | |
694 | zmax = max(all_zs) | |
695 | ||
696 | self.filament_length = self.max_e | |
697 | while len(self.filament_length_multi)<len(self.max_e_multi): | |
698 | self.filament_length_multi+=[0] | |
699 | for i in enumerate(self.max_e_multi): | |
700 | self.filament_length_multi[i[0]]=i[1] | |
701 | ||
702 | ||
703 | if self.filament_length > 0: | |
704 | self.xmin = xmin_e if not math.isinf(xmin_e) else 0 | |
705 | self.xmax = xmax_e if not math.isinf(xmax_e) else 0 | |
706 | self.ymin = ymin_e if not math.isinf(ymin_e) else 0 | |
707 | self.ymax = ymax_e if not math.isinf(ymax_e) else 0 | |
708 | else: | |
709 | self.xmin = xmin if not math.isinf(xmin) else 0 | |
710 | self.xmax = xmax if not math.isinf(xmax) else 0 | |
711 | self.ymin = ymin if not math.isinf(ymin) else 0 | |
712 | self.ymax = ymax if not math.isinf(ymax) else 0 | |
713 | self.zmin = zmin if not math.isinf(zmin) else 0 | |
714 | self.zmax = zmax if not math.isinf(zmax) else 0 | |
715 | self.width = self.xmax - self.xmin | |
716 | self.depth = self.ymax - self.ymin | |
717 | self.height = self.zmax - self.zmin | |
718 | ||
719 | # Finalize duration | |
720 | totaltime = datetime.timedelta(seconds = int(totalduration)) | |
721 | self.duration = totaltime | |
722 | ||
723 | def idxs(self, i): | |
724 | return self.layer_idxs[i], self.line_idxs[i] | |
725 | ||
726 | def estimate_duration(self): | |
727 | return self.layers_count, self.duration | |
728 | ||
729 | class LightGCode(GCode): | |
730 | line_class = LightLine | |
731 | ||
732 | def main(): | |
733 | if len(sys.argv) < 2: | |
734 | print "usage: %s filename.gcode" % sys.argv[0] | |
735 | return | |
736 | ||
737 | print "Line object size:", sys.getsizeof(Line("G0 X0")) | |
738 | print "Light line object size:", sys.getsizeof(LightLine("G0 X0")) | |
739 | gcode = GCode(open(sys.argv[1], "rU")) | |
740 | ||
741 | print "Dimensions:" | |
742 | xdims = (gcode.xmin, gcode.xmax, gcode.width) | |
743 | print "\tX: %0.02f - %0.02f (%0.02f)" % xdims | |
744 | ydims = (gcode.ymin, gcode.ymax, gcode.depth) | |
745 | print "\tY: %0.02f - %0.02f (%0.02f)" % ydims | |
746 | zdims = (gcode.zmin, gcode.zmax, gcode.height) | |
747 | print "\tZ: %0.02f - %0.02f (%0.02f)" % zdims | |
748 | print "Filament used: %0.02fmm" % gcode.filament_length | |
749 | for i in enumerate(gcode.filament_length_multi): | |
750 | print "E%d %0.02fmm" % (i[0],i[1]) | |
751 | print "Number of layers: %d" % gcode.layers_count | |
752 | print "Estimated duration: %s" % gcode.estimate_duration()[1] | |
753 | ||
754 | if __name__ == '__main__': | |
755 | main() |