forked from GeekDetour/BrickLayers
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbricklayers.py
More file actions
executable file
·2223 lines (1784 loc) · 102 KB
/
bricklayers.py
File metadata and controls
executable file
·2223 lines (1784 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
__version__ = "v0.2.0-17-g865fe50" # Updated by GitHub Actions
# Brick Layers by Geek Detour
# Interlocking Layers Post-Processing Script for PrusaSlicer, OrcaSlicer, and BambuStudio
#
# Copyright (C) 2025 Everson Siqueira, Geek Detour
#
# You can support my work on Patreon:
# - https://www.patreon.com/c/GeekDetour
# I really appreciate your help!
#
#
#
# IMPORTANT SETTINGS on your Slicer:
#
# - "Inner/Outer" is the BEST setting for Walls Printing Order.
# "Outer/Inner" works 'most of the time', but there could be glitches.
# "Inner/Outer/Inner" is NOT recommended.
# But don't worry: use Inner/Outer and Brick Layers basically delivers
# what you expected from Inner/Outer/Inner.
#
# - PrusaSlicer: "Arachne" and "Classic" engines work equally well :)
# If you really need Arachne, PrusaSlicer is the way to go.
#
# - OrcaSlicer: "Classic" engine works very well :)
# "Arachne" doesn't always generate consistent loop order for inner-walls :(
# https://github.com/SoftFever/OrcaSlicer/issues/884
# I tried circumventing the problem, but it was increasing the complexity a lot!
#
# - BambuStudio: "Classic" engine works very well :)
# "Arachne" has the same unpredictable loop order variations as OrcaSlicer
# 'Cancel Object' still needs specific implementation for Bambu Printers
#
#
# About Brick Layers:
# - https://youtu.be/9IdNA_hWiyE
# "Brick Layers: Stronger 3D Prints TODAY - instead of 2040"
# - https://www.patreon.com/posts/115566868
# "Brick Layers": Slicers can have it Today (instead of 2040)"
# - https://youtu.be/qqJOa46OTTs (* about this script *)
# "Brick Layers for everybody: Prusa Slicer, Orca Slicer and Bambu Studio"
#
# This Script transforms the arrangement of the perimeter beads on a GCode file,
# converting the Rectangular arrangement into a Hexagonal arrangement.
#
# The Hexagonal 3D Printing pattern is Public Domain, since 2016.
# Batchelder: US005653925A (1995), EP0852760B1 (1996)
#
#
# Special thanks to my fellow YouTubers:
#
# - Stefan Hermann, "CNC Kitchen"
# - Dr. Igor Gaspar, "My Tech Fun"
# - Roman Tenger, "TenTech"
#
#
#
# This program is free software: you can redistribute it and/or modify
#
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# Repository:
# - https://github.com/GeekDetour/BrickLayers
# LOGGING:
import logging
logger = logging.getLogger(__name__)
from typing import Dict
class ObjectEntry:
"""Stores the Name of the objects being printed, as a lightweight single object reference"""
_registry: Dict[str, "ObjectEntry"] = {}
def __init__(self, name: str):
self.name = name # Store the unique name
def __repr__(self):
return f"ObjectEntry({self.name})"
@classmethod
def entry_from_name(cls, name: str) -> "ObjectEntry":
"""Retrieves an ObjectEntry from the registry or creates a new one if not present."""
if name not in cls._registry:
cls._registry[name] = cls(name)
return cls._registry[name]
@classmethod
def clear_registry(cls):
"""Clears all stored ObjectEntry instances from the registry."""
cls._registry.clear()
import math
from typing import NamedTuple
class Point(NamedTuple):
"""Point For all calculations"""
x: float
y: float
@staticmethod
def distance_between_points(s_from, s_to):
"""Calculates Euclidean distance between two states, using .x and .y properties."""
dx = s_to.x - s_from.x
dy = s_to.y - s_from.y
return math.sqrt(dx * dx + dy * dy)
@staticmethod
def point_along_line_forward(p_from, p_to, desired_distance):
"""Find a point `desired_distance` forward from p_from toward p_to.
p_from and p_to must have .x and .y attributes (NamedTuple, State, etc.).
Returns a new plain Point.
"""
dx = p_to.x - p_from.x
dy = p_to.y - p_from.y
full_length = math.sqrt(dx * dx + dy * dy)
if full_length <= 0.0:
# No movement — just return p_from as a point
return Point(p_from.x, p_from.y)
# Fraction of the full line we want to move forward
fraction = desired_distance / full_length
# New point forward along the line
new_x = p_from.x + dx * fraction
new_y = p_from.y + dy * fraction
return Point(new_x, new_y)
@staticmethod
def point_along_line_backward(from_pos, to_pos, distance):
# Same as forward, but the "from" and "to" are swapped.
direction = ((from_pos.x - to_pos.x), (from_pos.y - to_pos.y))
length = math.sqrt(direction[0]**2 + direction[1]**2)
if length < 1e-6:
return to_pos # No movement possible (tiny segment)
scale = distance / length
new_x = to_pos.x + direction[0] * scale
new_y = to_pos.y + direction[1] * scale
return Point(new_x, new_y)
class GCodeState(NamedTuple):
"""Printing State"""
x: float
y: float
z: float
e: float
f: float
retracted: float
width: float
absolute_positioning: bool
relative_extrusion: bool
is_moving: bool
is_extruding: bool
is_retracting: bool
just_started_extruding: bool
just_stopped_extruding: bool
class GCodeFeatureState(NamedTuple):
"""Feature State"""
layer: int
z: float
height: float
layer_change: bool
current_object: ObjectEntry
current_type: str
last_type: str
overhang_perimeter: bool
internal_perimeter: bool
external_perimeter: bool
justgotinside_internal_perimeter: bool
justleft_internal_perimeter: bool
justgotinside_external_perimeter: bool
just_changed_type: bool
wiping: bool
wipe_willfinish: bool
wipe_justfinished: bool
capture_height: bool
class GCodeStateBBox:
"""Bounding-Box calculator to detect non-concentric loops.
This implementation is highly efficient, using simple vertical and horizontal calculations
instead of computing the Euclidean distance from centers (which would require a square root operation)."""
__slots__ = ('min_x', 'max_x', 'min_y', 'max_y') # Minimalist and memory-efficient!
def __init__(self):
self.min_x = float('inf')
self.max_x = float('-inf')
self.min_y = float('inf')
self.max_y = float('-inf')
def compute(self, state: GCodeState):
"""Feeds a point into the bounding box, updating its min/max values."""
x = state.x
y = state.y
if self.min_x == float('inf'): # First point ever
self.min_x = x - 0.1 # Expand opposite sides to ensure nonzero size
self.max_x = x + 0.1
self.min_y = y - 0.1
self.max_y = y + 0.1
else:
self.min_x = min(self.min_x, x)
self.max_x = max(self.max_x, x)
self.min_y = min(self.min_y, y)
self.max_y = max(self.max_y, y)
def contains(self, other) -> bool:
"""Checks if this bounding box fully contains another bounding box."""
return (
self.min_x <= other.min_x and # This box starts before the other on X-axis
self.max_x >= other.max_x and # This box ends after the other on X-axis
self.min_y <= other.min_y and # This box starts before the other on Y-axis
self.max_y >= other.max_y # This box ends after the other on Y-axis
)
def get_center(self):
"""Returns the center (midpoint) of the bounding box."""
return ((self.min_x + self.max_x) / 2, (self.min_y + self.max_y) / 2)
def get_size(self):
"""Returns the width and height of the bounding box."""
return (self.max_x - self.min_x, self.max_y - self.min_y)
def copy_from(self, other: "GCodeStateBBox"):
"""Copies bounding box values from another BBox instance."""
self.min_x = other.min_x
self.max_x = other.max_x
self.min_y = other.min_y
self.max_y = other.max_y
def reset(self):
"""Resets the bounding box to its initial infinite state."""
self.min_x = float('inf')
self.max_x = float('-inf')
self.min_y = float('inf')
self.max_y = float('-inf')
def __repr__(self):
"""Returns a dictionary representation of the bounding box for easy debugging."""
center_x, center_y = self.get_center()
width, height = self.get_size()
return f"GCodeStateBBox(center_x={center_x:.3f}, center_y={center_y:.3f}, width={width:.3f}, height={height:.3f})"
from typing import Optional
class GCodeLine:
"""Encapusates one GCode line, plus print states and a reference to which Printing Object the line belongs
It can contain a calculated `looporder` and concentric loops have the same 'contentric_grop' number
"""
__slots__ = ('gcode', 'previous', 'current', 'object', 'looporder', 'concentric_group')
def __init__(self, gcode: str, previous: Optional[GCodeState] = None,
current: Optional[GCodeState] = None, object_ref: Optional[ObjectEntry] = None, looporder: Optional[int] = None, concentric_group: Optional[int] = None):
self.gcode = gcode
self.previous = previous
self.current = current
self.object = object_ref # Stores a reference (pointer) to ObjectEntry
self.looporder = looporder
self.concentric_group = concentric_group
def __repr__(self):
return (f"GCodeLine(command='{self.gcode}', "
f"previous={self.previous}, current={self.current}, object={self.object}, looporder={self.looporder}, concentric_group={self.concentric_group})")
def to_gcode(self) -> str:
return self.gcode
@staticmethod
def from_gcode(gcode: str, previous: Optional[GCodeState] = None, current: Optional[GCodeState] = None, object_ref: Optional[ObjectEntry] = None) -> "GCodeLine":
"""Creates a GCodeLine instance from a raw G-code line without modifications. That should inclute a \\n at the very end"""
return GCodeLine(gcode, previous, current, object_ref)
class GCodeFeature:
"""
GCodeFeature: A state tracker for parsing G-code and identifying print features.
This class analyzes G-code lines to detect and classify different print features, such as
internal/external perimeters, overhangs, layer changes, and wiping commands. It maintains
a compact internal state using `__slots__` for efficient memory usage.
### Key Responsibilities:
- Tracks **layer height (Z), layer changes, and print feature types**.
- Identifies whether a segment is an **internal or external perimeter**, ensuring independence
from slicer-specific terminology (e.g., PrusaSlicer vs. OrcaSlicer).
- Detects **overhang walls**, which are currently exclusive to OrcaSlicer.
- Recognizes **wipe movements** (`;WIPE_START`, `;WIPE_END`) and manages their transitions.
- Monitors **object changes** when switching between printed objects.
- Efficiently captures **layer height information** while avoiding redundant updates.
### Parsing Behavior:
- G-code comments like `;TYPE:xxx` define different print features.
- Special markers such as `;LAYER_CHANGE` and `;Z:` update layer state.
- Wiping operations are handled by tracking their start and end points.
- When the print ends (`;END of PRINT`), the state resets accordingly.
"""
__slots__ = ('layer', 'z', 'height', 'layer_change', 'current_object', 'current_type', 'last_type', 'overhang_perimeter', 'internal_perimeter', 'external_perimeter', 'justgotinside_internal_perimeter', 'justleft_internal_perimeter', 'justgotinside_external_perimeter', 'just_changed_type', 'wiping', 'wipe_willfinish', 'wipe_justfinished', 'capture_height')
DEF_TYPES = (";TYPE:", "; FEATURE: ") # tupple, for line.startswith
DEF_INNERPERIMETERS = {"Perimeter", "Inner wall"} # set, for fast equality check
DEF_OUTERPERIMETERS = {"External perimeter", "Outer wall"}
DEF_OVERHANGPERIMETERS = {"Overhang wall"}
DEF_WIPESTARTS = {";WIPE_START", "; WIPE_START"}
DEF_WIPEENDS = {";WIPE_END", "; WIPE_END"}
DEF_LAYERCHANGES = {";LAYER_CHANGE", "; CHANGE_LAYER"}
DEF_LAYER_HEIGHTS = (";HEIGHT:", "; LAYER_HEIGHT: ") # tupple, for line.startswith
DEF_LAYER_ZS = (";Z:", "; Z_HEIGHT: ") # tupple, for line.startswith
DEF_START_PRINTING_OBJECTS = ("; printing object ", "; start printing object, ")
DEF_STOP_PRINTING_OBJECTS = ("; stop printing object ", "; stop printing object, ")
SANE_INNERPERIMETER = "internal_perimeter"
SANE_OUTERPERIMETER = "external_perimeter"
SANE_OVERHANGPERIMETER = "overhang_perimeter"
# Must be detected and set once:
internal_perimeter_type = None
external_perimeter_type = None
const_wipe_start = None
const_wipe_end = None
const_printingobject_start = None
const_printingobject_stop = None
const_layer_change = None
const_layer_height = None
const_layer_z = None
def __init__(self):
self.layer = 0
self.z = 0.0
self.height = 0.0
self.layer_change = False
self.current_object: Optional[ObjectEntry] = None
self.current_type = ""
self.last_type = ""
self.overhang_perimeter = False
self.internal_perimeter = False
self.external_perimeter = False
self.justgotinside_internal_perimeter = False
self.justleft_internal_perimeter = False
self.justgotinside_external_perimeter = False
self.just_changed_type = False
self.wiping = False
self.wipe_willfinish = False
self.wipe_justfinished = True
self.capture_height = True
def parse_gcode_line(self, line):
"""
Captures a Feature definition
Ex: Perimeter, External perimeter, Internal infill, etc...
Anything that begins the line as: ;TYPE:xxx
"""
strippedline = line.strip()
# Change Detection:
old_internal_perimeter = self.internal_perimeter
# Reseting
self.just_changed_type = False
self.justgotinside_internal_perimeter = False
self.justgotinside_external_perimeter = False
self.justleft_internal_perimeter = False
self.wipe_justfinished = False
self.layer_change = False
if self.wipe_willfinish:
self.wiping = False
self.wipe_justfinished = True
self.wipe_willfinish = False
# This fuction (so far) only checks things that start with ";SOMETHING"
if line and line[0] != ";":
return self # no point in proceed checking further
if line.startswith(self.DEF_TYPES):
old_type = self.current_type
self.just_changed_type = True # TODO: revise
#new_type = line.split(";TYPE:")[1].strip()
for prefix in self.DEF_TYPES:
if line.startswith(prefix):
new_type = line[len(prefix):].strip()
break
if new_type in self.DEF_INNERPERIMETERS:
if self.internal_perimeter_type is None:
type(self).internal_perimeter_type = line
self.current_type = self.SANE_INNERPERIMETER #sanitizing to be independent of PrusaSlicer, OrcaSlicer or BambuStudio
if not self.internal_perimeter:
self.justgotinside_internal_perimeter = True
self.internal_perimeter = True
self.external_perimeter = False
self.overhang_perimeter = False
elif new_type in self.DEF_OUTERPERIMETERS:
if self.external_perimeter_type is None:
type(self).external_perimeter_type = line
self.current_type = self.SANE_OUTERPERIMETER #sanitizing to be independent of PrusaSlicer, OrcaSlicer or BambuStudio
if not self.external_perimeter:
self.justgotinside_external_perimeter = True
self.external_perimeter = True
self.internal_perimeter = False
self.overhang_perimeter = False
elif new_type in self.DEF_OVERHANGPERIMETERS: # OrcaSlicer only, so far...
self.current_type = self.SANE_OVERHANGPERIMETER
self.overhang_perimeter = True
else:
self.internal_perimeter = False
self.external_perimeter = False
self.overhang_perimeter = False
self.current_type = new_type
if old_internal_perimeter and not self.internal_perimeter:
self.justleft_internal_perimeter = True
elif strippedline in self.DEF_WIPESTARTS:
self.wiping = True
if self.const_wipe_start is None:
for prefix in self.DEF_WIPESTARTS:
if strippedline.startswith(prefix):
type(self).const_wipe_start = prefix + "\n"
break
elif strippedline in self.DEF_WIPEENDS:
self.wipe_willfinish = True
if self.const_wipe_end is None:
for prefix in self.DEF_WIPEENDS:
if strippedline.startswith(prefix):
type(self).const_wipe_end = prefix + "\n"
break
elif strippedline.startswith(self.DEF_START_PRINTING_OBJECTS):
for prefix in self.DEF_START_PRINTING_OBJECTS:
if strippedline.startswith(prefix):
object_name = strippedline[len(prefix):]
break
# Captures the right 'start object' flavor used in the file being parsed
if self.const_printingobject_start is None:
type(self).const_printingobject_start = prefix
# Assigns a pointer to the lastly object being printed:
self.current_object = ObjectEntry.entry_from_name(object_name)
elif self.const_printingobject_stop is None and strippedline.startswith(self.DEF_STOP_PRINTING_OBJECTS):
# Just captures the right 'stop object' flavor used in the file being parsed
for prefix in self.DEF_STOP_PRINTING_OBJECTS:
if strippedline.startswith(prefix):
break
type(self).const_printingobject_stop = prefix
elif strippedline in self.DEF_LAYERCHANGES:
if self.const_layer_change is None:
for prefix in self.DEF_LAYERCHANGES:
if strippedline.startswith(prefix):
type(self).const_layer_change = line
break
self.layer_change = True
self.internal_perimeter = False # THIS IS TECHNICALLY WRONG! Sometimes OrcaSlicer just continues the previous Type on a new layer!
self.external_perimeter = False # THIS IS TECHNICALLY WRONG! Sometimes OrcaSlicer just continues the previous Type on a new layer!
self.layer += 1
self.capture_height = True # I need to capture only once per layer.
#elif line.startswith(";Z:"):
elif strippedline.startswith(self.DEF_LAYER_ZS):
for prefix in self.DEF_LAYER_ZS:
if strippedline.startswith(prefix):
self.z = float(strippedline[len(prefix):])
break
if self.const_layer_z is None:
type(self).const_layer_z = prefix
#elif line.startswith(";HEIGHT:"):
elif strippedline.startswith(self.DEF_LAYER_HEIGHTS):
if self.capture_height:
for prefix in self.DEF_LAYER_HEIGHTS:
if strippedline.startswith(prefix):
self.height = float(strippedline[len(prefix):])
self.capture_height = False
break
if self.const_layer_height is None:
type(self).const_layer_height = prefix
if not self.just_changed_type:
self.last_type = self.current_type # Allows for feature change.
return self
def get_state(self):
"""Returns a dictionary representation of the feature state."""
return GCodeFeatureState(
layer=self.layer,
z=self.z,
height=self.height,
layer_change=self.layer_change,
current_object=self.current_object,
current_type=self.current_type,
last_type=self.last_type,
overhang_perimeter=self.overhang_perimeter,
internal_perimeter=self.internal_perimeter,
external_perimeter=self.external_perimeter,
justgotinside_internal_perimeter=self.justgotinside_internal_perimeter,
justleft_internal_perimeter=self.justleft_internal_perimeter,
justgotinside_external_perimeter=self.justgotinside_external_perimeter,
just_changed_type=self.just_changed_type,
wiping=self.wiping,
wipe_willfinish=self.wipe_willfinish,
wipe_justfinished=self.wipe_justfinished,
capture_height=self.capture_height
)
class GCodeSimulator:
"""
GCodeSimulator: A lightweight G-code state tracker.
This class interprets individual G-code lines, updating a simulated state that reflects
the machine's movement, extrusion, and positioning. It calculates state changes when parsing
gcode lines, updating key parameters such as X, Y, Z coordinates, extrusion (E), and feed rate (F).
### Features:
- Supports both **absolute (G90)** and **relative (G91)** positioning.
- Tracks **extrusion mode** (absolute M82 / relative M83).
- Identifies **movement commands (G0, G1, G2, G3)**, updating values accordingly.
- Detects **maximum travel and retraction speeds** encountered in the parsed G-code.
- Makes it easy to know track changes in extrusion sequences (just_stopped_extruding)
- Also accounts for the WIDTH (used just on the preview of slicers: `;WIDTH:x.xx`)
- Provides a snapshot of the current state via `get_state()`.
It uses `__slots__` to minimize memory overhead, and make it efficient for parsing large G-code files.
"""
__slots__ = ('x', 'y', 'z', 'e', 'f', 'retracted', 'width', 'absolute_positioning', 'relative_extrusion', 'is_moving', 'is_extruding', 'is_retracting', 'just_started_extruding', 'just_stopped_extruding', 'travel_speed', 'wipe_speed', 'retraction_speed', 'detraction_speed', 'retraction_length')
DEF_WIDTHS = (";WIDTH:", "; LINE_WIDTH: ") # tupple, for line.startswith
# Must be detected and set once:
const_width = None
def __init__(self, initial_state=None):
self.x, self.y, self.z, self.e, self.f, self.retracted, self.width = 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
self.absolute_positioning = True # Default mode is absolute (G90)
self.relative_extrusion = False # Default extrusion mode is absolute (M82)
self.is_moving = False # Tracks whether movement is happening
self.is_extruding = False # Tracks whether extrusion is happening
self.is_retracting = False # Tracks whether extrusion is happening
self.just_started_extruding = False
self.just_stopped_extruding = False # Tracks whether a MOVEMENT doesn't extrude, right after another MOVEMENT that was extruding
self.travel_speed = 0
self.wipe_speed = 0
self.retraction_speed = 0
self.detraction_speed = 0
self.retraction_length = 0
if initial_state:
self.set_state(initial_state)
def parse_gcode_line(self, rawline):
stripline = rawline.strip()
line = stripline
if not line: # Skip empty lines
return self
#Reset
self.just_stopped_extruding = False
# Remove inline comments
line = line.partition(';')[0]
if line:
parts = line.split()
command = parts[0]
if command in ('G0', 'G1', 'G2', 'G3'):
# Remember old extruding state for transitions
old_extruding = self.is_extruding
# Reset line flags
self.is_extruding = False
self.is_retracting = False
self.just_stopped_extruding = False
# Movement commands
abs_pos = self.absolute_positioning
rel_ext = self.relative_extrusion
old_x, old_y, old_z, old_e = self.x, self.y, self.z, self.e
new_x, new_y, new_z = self.x, self.y, self.z
new_e, new_f = self.e, self.f
has_x, has_y, has_z, has_e, has_f = False, False, False, False, False
for arg in parts[1:]:
axis = arg[0]
# Skip I/J if arcs
if axis in ('I', 'J'):
continue
val = float(arg[1:])
if axis == 'X':
new_x = val if abs_pos else (self.x + val)
has_x = True
elif axis == 'Y':
new_y = val if abs_pos else (self.y + val)
has_y = True
elif axis == 'Z':
new_z = val if abs_pos else (self.z + val)
has_z = True
elif axis == 'E':
# E can be absolute or relative
if rel_ext:
new_e = self.e + val
else:
new_e = val
has_e = True
elif axis == 'F':
new_f = val
has_f = True
# Detect if there is actual X/Y/Z movement
x_move = (new_x != old_x)
y_move = (new_y != old_y)
z_move = (new_z != old_z)
had_a_movement_change = x_move or y_move or z_move # In this very line
just_feed_rate = ( has_f and not (has_x or has_y or has_z) )
if (has_x or has_y or has_z):
# Update positions
self.x, self.y, self.z = new_x, new_y, new_z
self.e, self.f = new_e, new_f
extruding = False
retracting = False
extruded = new_e - old_e
if extruded > 0:
extruding = True
self.is_extruding = True
elif extruded < 0:
retracting = True
self.is_retracting = True
self.retracted += extruded
if self.retracted + 0.0001 > 0:
self.retracted = 0.0
# Detect Maximum Travel Speed:
if had_a_movement_change and new_e == old_e and self.travel_speed < new_f:
self.travel_speed = new_f
logger.debug(f"travel_speed: {new_f}, gcode: {line}")
# Detect Retraction Length:
if not had_a_movement_change and retracting and abs(extruded) > self.retraction_length: # and self.retraction_speed < new_f:
#self.retraction_speed = new_f
self.retraction_length = abs(extruded)
logger.debug(f"retraction_speed: {new_f}, gcode: {line}, retraction_length: {self.retraction_length}, old_e: {old_e}, new_e: {new_e}")
if had_a_movement_change:
self.is_moving = True
elif extruded != 0 and not had_a_movement_change:
self.is_moving = False
if (not just_feed_rate):
# Transitional Marker:
self.just_started_extruding = (extruding and not old_extruding and had_a_movement_change)
# Transitional Marker:
if old_extruding and not self.is_extruding:
self.just_stopped_extruding = True
elif command == 'G90':
self.absolute_positioning = True
elif command == 'G91':
self.absolute_positioning = False
elif command == 'M82':
self.relative_extrusion = False
elif command == 'M83':
self.relative_extrusion = True
elif command == 'G92':
# Set axis positions (e.g. G92 X10 Y20 E0)
for arg in parts[1:]:
axis = arg[0].upper()
if axis in "XYZE":
val = float(arg[1:])
setattr(self, axis.lower(), val)
if self.e == 0:
self.retracted = 0
elif stripline.startswith(self.DEF_WIDTHS):
for prefix in self.DEF_WIDTHS:
if stripline.startswith(prefix):
self.width = float(stripline[len(prefix):])
break
if self.const_width is None:
type(self).const_width = prefix
return self
def get_state(self):
return GCodeState(
x=self.x,
y=self.y,
z=self.z,
e=self.e,
f=self.f,
retracted=self.retracted,
width=self.width,
absolute_positioning=self.absolute_positioning,
relative_extrusion=self.relative_extrusion,
is_moving=self.is_moving,
is_extruding=self.is_extruding,
is_retracting=self.is_retracting,
just_started_extruding=self.just_started_extruding,
just_stopped_extruding=self.just_stopped_extruding
)
def set_state(self, state: GCodeState):
if not isinstance(state, GCodeState):
raise TypeError("Expected a GCodeState instance")
self.x = state.x
self.y = state.y
self.z = state.z
self.e = state.e
self.f = state.f
self.retracted = state.retracted
self.width = state.width
self.absolute_positioning = state.absolute_positioning
self.relative_extrusion = state.relative_extrusion
self.is_moving = state.is_moving
self.is_extruding = state.is_extruding
self.is_retracting= state.is_retracting
self.is_extruding_and_moving = state.is_extruding_and_moving
self.just_started_extruding = state.just_started_extruding
self.just_stopped_extruding = state.just_stopped_extruding
def reset_state(self):
self.x, self.y, self.z, self.e, self.f, self.retracted, self.width = 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
self.absolute_positioning = True
self.relative_extrusion = False
self.is_moving = False
self.is_extruding = False
self.is_retracting = False
self.is_extruding_and_moving = False
self.just_started_extruding = False
self.just_stopped_extruding = False
self.travel_speed = 0
self.wipe_speed = 0
self.retraction_speed = 0
self.detraction_speed = 0
self.retraction_length = 0
class LoopNode:
"""Temporary structure to track nesting relationships of LOOPS during processing."""
__slots__ = ('around_hole', 'depth', 'boundingbox', 'order', 'looplines', 'kids')
concentric = 0 # Centralized variable to be incremented, so every group of tightly nested loops have the same one. No branch should have the same number.
def __init__(self, order, boundingbox, looplines):
self.around_hole = False
self.depth = 0 # Assigned later
self.boundingbox = boundingbox
self.order = order # The index of the original groups list, to be able to elaborate a 'moving' list based on that order.
self.looplines = looplines # the ORIGINAL list of lines (It is referenced on other structures)
self.kids = []
def propagate(self, boolean_list, depth = 0, myconcentric = None):
if myconcentric is None:
LoopNode.concentric += 1
myconcentric = LoopNode.concentric
self.depth = depth
total_kids = len(self.kids)
if total_kids == 1:
# use the same concentric as the parent node:
kid_depth = self.kids[0].propagate(boolean_list, depth + 1, LoopNode.concentric)
elif total_kids > 1:
for kid in self.kids:
LoopNode.concentric += 1 # Increment the unique counter
kid_depth = kid.propagate(boolean_list, depth + 1, LoopNode.concentric) # Each branch needs a unique number
if self.around_hole:
if total_kids == 0:
# Around a hole, this is the loop closest to the external perimeter:
self.depth = 0
depth = 0
elif kid_depth is not None: #TODO: investigate cases in which a hole would not return depth
self.depth = kid_depth
depth = kid_depth
# Update boolean list based on depth rule
if (depth + 1) % 2:
boolean_list[self.order] = True
# This is the real place these values will change things:
for line in self.looplines:
line.looporder = depth # `looporder`: property of a "GCodeLine" instance
line.concentric_group = myconcentric # `concentric_group`: property of "GCodeLine"
if self.around_hole:
return depth + 1
def __repr__(self):
keys_to_include = {"gcode"}
return (f"LoopNode(around_hole={self.around_hole} , order={self.order}, depth={self.depth}, "
f"kids={self.kids}, "
f"looplines={len(self.looplines)}" # [line.gcode for line in self.looplines]
#f"looplines={brick_to_serializable(self.looplines, keys_to_include)}"
)
def brick_dump(text, obj, keys_to_include=None):
if not hasattr(brick_dump, "_json"):
import json
brick_dump._json = json # Cache it in a function attribute
return(f"{text}:\n{brick_dump._json.dumps(brick_to_serializable(obj, keys_to_include), indent=4)}\n\n")
def brick_to_serializable(obj, keys_to_include=None):
"""Recursively converts objects into JSON-serializable structures, including only specified keys.
Allows json.dumps(obj) on many of the objects of this module, for easier debugging.
"""
if keys_to_include is None:
keys_to_include = set()
# Serializes GCodeLine:
if isinstance(obj, GCodeLine):
if len(keys_to_include) == 1:
first_key = next(iter(keys_to_include)) # Get the single key correctly
return getattr(obj, first_key) # Return its value
else:
return {key: getattr(obj, key) for key in obj.__slots__ if key in keys_to_include}
# Serializes LoopNode:
elif isinstance(obj, LoopNode):
return {
"around_hole": obj.around_hole,
"order": obj.order,
"depth": obj.depth,
"kids": [brick_to_serializable(kid, keys_to_include) for kid in obj.kids], # Recursively serialize kids
"looplines": len(obj.looplines) # Serialize looplines
}
# Handle lists, tuples, and sets (process each item)
elif isinstance(obj, (list, tuple, set)):
return [brick_to_serializable(item, keys_to_include) for item in obj]
# Handle dictionaries (convert values recursively)
elif isinstance(obj, dict):
return {key: brick_to_serializable(value, keys_to_include) for key, value in obj.items()}
# Base case: return the object if it’s already serializable
return obj
from typing import Callable, Optional
class BrickLayersProcessor:
"""
BrickLayersProcessor: G-Code Post-Processor for Brick Layering.
This class modifies G-code to implement the Brick Layers technique, improving part
strength by redistributing inner perimeters across multiple layers. It processes
G-code line by line, adjusting extrusion values and modifying movement paths based
on detected features and geometric constraints.
### Features:
- **Layer-Based Processing:**
- Starts processing at a configurable layer (`start_at_layer`).
- Allows exclusion of specific layers (`layers_to_ignore`).
- Detects and handles layer changes (`;LAYER_CHANGE`).
- **Extrusion Adjustments:**
- Applies a global extrusion multiplier (`extrusion_global_multiplier`).
- Supports absolute and relative extrusion modes.
- **Internal Perimeter Redistribution:**
- Identifies **non-concentric inner perimeters** (orphaned loops).
- Groups inner loops into concentric and non-concentric sets.
- Moves selected loops to a higher layer for improved adhesion.
- **Retraction and Travel Optimizations:**
- Detects **maximum travel and retraction speeds**.
- Inserts retractions and travel moves when necessary
- Implements it's own 'Wiping'
- **G-Code Feature Detection:**
- Identifies feature types (`;TYPE:`) such as internal/external perimeters and infill.
- Normalizes slicer-specific naming (e.g., PrusaSlicer vs. OrcaSlicer).
- Captures object changes for Cancel Objects (`; printing object`).
- **Progress Reporting:**
- Supports an optional **progress callback** (`progress_callback`).
- Provides updates on bytes processed, layers, and line counts.
Optimized for efficiency using **line-by-line processing**, for processing Big Gcode files
"""
def __init__(self, extrusion_global_multiplier: float = 1.05, start_at_layer: int = 3, layers_to_ignore = None, verbosity: int = 0, progress_callback: Optional[Callable[[dict], None]] = None):
self.extrusion_global_multiplier = extrusion_global_multiplier
self.start_at_layer = start_at_layer
self.layers_to_ignore = layers_to_ignore
self.verbosity = verbosity
self.progress_callback = progress_callback
self.yield_objects = False
self.justcalculate = False # If True, just perform calculations but doesn't generate the brick-layering
self.experimental_arcflick = False # If True, turns On "ARC Flick" after wiping, an experiment to free the nozzle from stringing
self.travel_threshold = 3 #mm If the distance to move between points is smaller than this, don't wipe, just move.
self.wipe_distance = 2.5 #mm Total distance we want to wipe
self.travel_zhop = 0.4 #mm Vertical distance to move up when traveling to distante points
def set_progress_callback(self, callback: Callable[[dict], None]):
"""Sets the progress callback function."""
self.progress_callback = callback
# Processing Progress:
# Which is delegated to an external function
# You can write your own progress function without changing this class!
def update_progress(self, bytesprocessed: int, text: str, linecount: int, layercount: int):
if self.progress_callback:
self.progress_callback({
"bytesprocessed": bytesprocessed,
"text": text,
"linecount": linecount,
"layercount": layercount,
"verbosity": self.verbosity
})
@staticmethod
def new_line_from_multiplier(myline, extrusion_multiplier):
# Calculates the Relative Extrusion based on the absolute extrusion values of the simulator
e_val = myline.current.e - myline.previous.e
# Apply multipliers:
e_val = e_val * extrusion_multiplier
parts = myline.gcode.split() # Split the line into components
for i, part in enumerate(parts):
if part.startswith("E"): # Found the extrusion value
parts[i] = f"E{e_val:.5f}" # Replace only the E value
break # No need to keep looking
command = " ".join(parts) # Reconstruct the G-code line
myline.gcode = command + "\n"
return myline # keeps the states, just change the actual gcode string
def retraction_to_state(self, target_state, simulator):
# Abandoned in favor of `wipe_movement`
gcode_list = []
# You can tweak the ration between how much is retracted while stopped, and then while traveling:
from_gcode = GCodeLine.from_gcode
stopped_pull = simulator.retraction_length * 0.85 # 90% first, stopped
moving_pull = simulator.retraction_length * 0.15 # 10% while travelling
gcode_list.append(from_gcode(f"G1 E-{stopped_pull:.2f} F{int(simulator.retraction_speed)} ; BRICK: Retraction \n"))
gcode_list.append(from_gcode(f"G1 X{target_state.x} Y{target_state.y} E-{moving_pull:.2f} F{int(simulator.travel_speed)} ; BRICK: Retraction Travel\n"))
gcode_list.append(from_gcode(f"G1 E{simulator.retraction_length:.2f} F{int(simulator.detraction_speed)} ; BRICK: Urnetract\n"))
gcode_list.append(from_gcode(f"G1 F{int(target_state.f)} ; BRICK: Feed Rate\n"))
return gcode_list
def wipe_movement(self, loop, target_state, simulator, feature, z = None):
"""
Process a loop to calculate a wiping path (repeating part of the already-printed loop while retracting).