-
Notifications
You must be signed in to change notification settings - Fork 2
/
shapely_cam.py
2057 lines (1634 loc) · 68.9 KB
/
shapely_cam.py
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
# Copyright 2022 Xavier
#
# This file is part of pycut.
#
# pycut 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.
#
# pycut 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 pycut. If not, see <http:#www.gnu.org/licenses/>.
import sys
import math
from math import sqrt
from typing import List
from typing import Dict
from typing import Tuple
from typing import Any
from typing import cast
import numpy as np
import matplotlib.pyplot as plt
from shapely_svgpath_io import SvgPath
from val_with_unit import ValWithUnit
import shapely # type: ignore [import-untyped]
import shapely.geometry # type: ignore [import-untyped]
import shapely.ops # type: ignore [import-untyped]
from shapely_utils import ShapelyUtils
from shapely_ext import ShapelyMultiPolygonOffset
from shapely_ext import ShapelyMultiPolygonOffsetInteriors
from shapely_matplotlib import MatplotLibUtils
PI = math.pi
from hsm_nibble import geometry
class CamPath:
"""
CamPath has this format: {
path: Shapely LineString
safe_to_close: Is it safe to close the path without retracting?
}
"""
def __init__(self, path: shapely.geometry.LineString, safe_to_close: bool = True):
# shapely linestring
self.path = path
# is it safe to close the path without retracting?
self.safe_to_close = safe_to_close
class cam:
""" """
@classmethod
def drill(
cls, multipoint: shapely.geometry.MultiPoint, cutter_dia: float
) -> List[CamPath]:
"""
Compute paths for drill operation on Shapely multipoint
"""
cam_paths = []
for point in multipoint.geoms:
pt = point.coords[0]
cam_path = CamPath(shapely.geometry.Point(pt), True)
cam_paths.append(cam_path)
return cam_paths
@classmethod
def peck(
cls, multipoint: shapely.geometry.MultiPoint, cutter_dia: float
) -> List[CamPath]:
"""
Compute paths for peck operation on Shapely multipoint
"""
cam_paths = []
for point in multipoint.geoms:
pt = point.coords[0]
cam_path = CamPath(shapely.geometry.Point(pt), False)
cam_paths.append(cam_path)
return cam_paths
@classmethod
def helix(
cls,
multipolygon: shapely.geometry.MultiPolygon,
cutter_dia: float,
) -> List[CamPath]:
"""
It will be performed from the center of the shape.
The helix drills down until the cut depth.
At each revolution, a cut depth of depth "helix_pitch" is cut in the z direction.
This means, given the cut rate and the helix diameter, the helix plunge rate is calculated
"""
cam_paths = []
for poly in multipolygon.geoms:
pt = poly.centroid
cam_path = CamPath(shapely.geometry.Point(pt), False)
cam_paths.append(cam_path)
return cam_paths
@classmethod
def pocket(
cls,
multipoly: shapely.geometry.MultiPolygon,
cutter_dia: float,
overlap: float,
climb: bool,
) -> List[CamPath]:
"""
Compute paths for pocket operation on Shapely multipolygon.
Returns array of CamPath.
cutter_dia is in "UserUnit" units.
overlap is in the range [0, 1).
"""
pc = PocketCalculator(multipoly, cutter_dia, overlap, climb)
pc.pocket()
return pc.cam_paths
@classmethod
def spirale_pocket(
cls,
svgpaths,
multipoly: shapely.geometry.MultiPolygon,
cutter_dia: float,
overlap: float,
climb: bool,
) -> List[CamPath]:
"""
Compute paths for pocket operation on Shapely multipolygon.
Returns array of CamPath.
cutter_dia is in "UserUnit" units.
overlap is in the range [0, 1).
"""
pc = SpiralePocketCalculator(svgpaths, multipoly, cutter_dia, overlap, climb)
pc.pocket()
return pc.cam_paths
@classmethod
def hsm_nibbler_pocket(
cls,
multipoly: shapely.geometry.MultiPolygon,
cutter_dia: float,
overlap: float,
climb: bool,
) -> List[CamPath]:
"""
Compute paths for pocket operation on Shapely multipolygon.
Returns array of CamPath.
cutter_dia is in "UserUnit" units.
overlap is in the range [0, 1).
"""
pc = NibblePocketCalculator(multipoly, cutter_dia, overlap, climb)
pc.pocket()
return pc.cam_paths
@classmethod
def outline(
cls,
geometry: shapely.geometry.MultiPolygon,
cutter_dia: float,
is_inside: bool,
width: float,
overlap: float,
climb: bool,
) -> List[CamPath]:
"""
Compute paths for outline operation on Shapely geometry "MultiPolygon".
Returns array of CamPath.
cutter_dia and width are in Shapely units.
overlap is in the range [0, 1).
"""
# use lines, not polygons
multiline = ShapelyUtils.multipoly_exteriors_to_multiline(geometry)
current_width = cutter_dia
each_width = cutter_dia * (1 - overlap)
all_paths: List[shapely.geometry.LineString] = []
if is_inside:
# because we always start from the outer ring -> we go "inside"
current = ShapelyUtils.offset_multiline(multiline, cutter_dia / 2, "left")
offset = ShapelyUtils.offset_multiline(
multiline, width - cutter_dia / 2, "left"
)
# bounds = ShapelyUtils.diff(current, offset)
bounds = current
each_offset = each_width
need_reverse = climb
else:
direction = "inner2outer"
# direction = "outer2inner"
if direction == "inner2outer":
# because we always start from the inner ring -> we go "outside"
current = ShapelyUtils.offset_multiline(
multiline, cutter_dia / 2, "right"
)
offset = ShapelyUtils.offset_multiline(
multiline, width - cutter_dia / 2, "right"
)
# bounds = ShapelyUtils.diff(current, offset)
bounds = current
else:
# because we always start from the outer ring -> we go "inside"
current = ShapelyUtils.offset_multiline(
multiline, cutter_dia / 2, "left"
)
offset = ShapelyUtils.offset_multiline(
multiline, width - cutter_dia / 2, "left"
)
# bounds = ShapelyUtils.diff(current, offset)
bounds = current
each_offset = each_width
need_reverse = not climb
# TEST
# all_paths = [p for p in current.geoms]
while current_width <= width:
if need_reverse:
reversed = []
for path in current.geoms:
coords = list(
path.coords
) # is a tuple! JSCUT current reversed in place
coords.reverse()
reversed.append(shapely.geometry.LineString(coords))
all_paths = reversed + all_paths
else:
all_paths = [p for p in current.geoms] + all_paths
next_width = current_width + each_width
if next_width > width and (width - current_width) > 0:
# >>> XAM fix
last_delta = width - current_width
# <<< XAM fix
current = ShapelyUtils.offset_multiline(current, last_delta, "left")
if current:
current = ShapelyUtils.simplify_multiline(current, 0.01)
if current:
if need_reverse:
reversed = []
for path in current.geoms:
coords = list(
path.coords
) # is a tuple! JSCUT current reversed in place
coords.reverse()
reversed.append(shapely.geometry.LineString(coords))
all_paths = reversed + all_paths
else:
all_paths = [p for p in current.geoms] + all_paths
break
current_width = next_width
if not current:
break
current = ShapelyUtils.offset_multiline(
current, each_offset, "left", resolution=16
)
if current:
current = ShapelyUtils.simplify_multiline(current, 0.01)
print("--- next toolpath")
else:
break
if len(all_paths) == 0:
# no possible paths! TODO . inform user
return []
# merge_paths need MultiPolygon
bounds = ShapelyUtils.multiline_to_multipoly(bounds)
return cls.merge_paths(bounds, all_paths)
@classmethod
def outline_opened_paths(
cls,
geometry: shapely.geometry.MultiLineString,
cutter_dia: float,
is_inside: bool,
width: float,
overlap: float,
climb: bool,
) -> List[CamPath]:
"""
Compute paths for outline operation on Shapely geometry "MultiLineString".
Returns array of CamPath.
cutter_dia and width are in Shapely units.
overlap is in the range [0, 1).
"""
# use lines, not polygons
multiline = geometry
current_width = cutter_dia
each_width = cutter_dia * (1 - overlap)
all_paths: List[shapely.geometry.LineString] = []
if is_inside:
# because we always start from the outer ring -> we go "inside"
current = ShapelyUtils.offset_multiline(multiline, 0.0, "left")
offset = ShapelyUtils.offset_multiline(multiline, width - 0.0, "left")
# bounds = ShapelyUtils.diff(current, offset)
bounds = current
each_offset = each_width
need_reverse = climb
else:
direction = "inner2outer"
# direction = "outer2inner"
if direction == "inner2outer":
# because we always start from the inner ring -> we go "outside"
current = ShapelyUtils.offset_multiline(multiline, 0.0, "right")
offset = ShapelyUtils.offset_multiline(multiline, width - 0.0, "right")
# bounds = ShapelyUtils.diff(current, offset)
bounds = current
else:
# because we always start from the outer ring -> we go "inside"
current = ShapelyUtils.offset_multiline(multiline, 0.0, "left")
offset = ShapelyUtils.offset_multiline(multiline, width - 0.0, "left")
# bounds = ShapelyUtils.diff(current, offset)
bounds = current
each_offset = each_width
need_reverse = not climb
# TEST
# all_paths = [p for p in current.geoms]
while True and current_width <= width:
if need_reverse:
reversed = []
for path in current.geoms:
coords = list(
path.coords
) # is a tuple! JSCUT current reversed in place
coords.reverse()
reversed.append(shapely.geometry.LineString(coords))
all_paths = reversed + all_paths
else:
all_paths = [p for p in current.geoms] + all_paths
next_width = current_width + each_width
if next_width > width and (width - current_width) > 0:
# >>> XAM fix
last_delta = width - current_width
# <<< XAM fix
current = ShapelyUtils.offset_multiline(current, last_delta, "left")
if current:
current = ShapelyUtils.simplify_multiline(current, 0.01)
if current:
if need_reverse:
reversed = []
for path in current.geoms:
coords = list(
path.coords
) # is a tuple! JSCUT current reversed in place
coords.reverse()
reversed.append(shapely.geometry.LineString(coords))
all_paths = reversed + all_paths
else:
all_paths = [p for p in current.geoms] + all_paths
break
current_width = next_width
if not current:
break
current = ShapelyUtils.offset_multiline(
current, each_offset, "left", resolution=16
)
if current:
current = ShapelyUtils.simplify_multiline(current, 0.01)
print("--- next toolpath")
else:
break
if len(all_paths) == 0:
# no possible paths! TODO . inform user
return []
# merge_paths need MultiPolygon
bounds = shapely.geometry.MultiPolygon()
return cls.merge_paths(bounds, all_paths, closed_path=False)
@classmethod
def engrave(
cls, geometry: shapely.geometry.MultiPolygon, climb: bool
) -> List[CamPath]:
"""
Compute paths for engrave operation on Shapely multipolygon.
Returns array of CamPath.
"""
# use lines, not polygons
multiline_ext = ShapelyUtils.multipoly_exteriors_to_multiline(geometry)
multiline_int = ShapelyUtils.multipoly_interiors_to_multiline(geometry)
full_line = shapely.ops.linemerge(
list(multiline_ext.geoms) + list(multiline_int.geoms)
)
if full_line.geom_type == "LineString":
cam_paths = [CamPath(full_line, False)]
return cam_paths
all_paths = []
for line in full_line.geoms:
coords = list(line.coords) # JSCUT: path = paths.slice(0)
if not climb:
coords.reverse()
coords.append(coords[0])
all_paths.append(shapely.geometry.LineString(coords))
cam_paths = [CamPath(path, False) for path in all_paths]
return cam_paths
@classmethod
def engrave_opened_paths(
cls, geometry: shapely.geometry.MultiLineString, climb: bool
) -> List[CamPath]:
"""
Compute paths for engrave operation on Shapely multiplinestring.
Returns array of CamPath.
"""
all_paths = []
for line in geometry.geoms:
coords = list(line.coords) # JSCUT: path = paths.slice(0)
if not climb:
coords.reverse()
# coords.append(coords[0]) # what's this ??
all_paths.append(shapely.geometry.LineString(coords))
cam_paths = [CamPath(path, False) for path in all_paths]
return cam_paths
@classmethod
def merge_paths(
cls,
_bounds: shapely.geometry.MultiPolygon,
paths: List[shapely.geometry.LineString],
closed_path=True,
) -> List[CamPath]:
"""
Try to merge paths. A merged path doesn't cross outside of bounds AND the interior polygons
"""
# cnt = MatplotLibUtils.display("mergePath", shapely.geometry.MultiLineString(paths), force=True)
if _bounds and len(_bounds.geoms) > 0:
bounds = _bounds
else:
bounds = shapely.geometry.MultiPolygon()
ext_lines = ShapelyUtils.multipoly_exteriors_to_multiline(bounds)
int_polys = []
for poly in bounds.geoms:
if poly.interiors:
for interior in poly.interiors:
int_poly = shapely.geometry.Polygon(interior)
int_polys.append(int_poly)
if int_polys:
int_multipoly = shapely.geometry.MultiPolygon(int_polys)
else:
int_multipoly = None
# std list
thepaths = [list(path.coords) for path in paths]
paths = thepaths
current_path = paths[0]
path_end_point = current_path[-1]
path_start_point = current_path[0]
# close if start/end points not equal - in case of closed_path geometry -
if closed_path == True:
if (
path_end_point[0] != path_start_point[0]
or path_end_point[1] != path_start_point[1]
):
current_path = current_path + [path_start_point]
current_point = current_path[-1]
paths[0] = [] # empty
merged_paths: List[shapely.geometry.LineString] = []
num_left = len(paths) - 1
while num_left > 0:
closest_path_index = -1
closest_point_index = -1
closest_point_dist = float(sys.maxsize)
for path_index, path in enumerate(paths):
for point_index, point in enumerate(path):
dist = cam.distP(current_point, point)
if dist < closest_point_dist:
closest_path_index = path_index
closest_point_index = point_index
closest_point_dist = dist
path = paths[closest_path_index]
paths[closest_path_index] = [] # empty
num_left -= 1
need_new = ShapelyUtils.crosses(
ext_lines, current_point, path[closest_point_index]
)
if (not need_new) and int_multipoly:
need_new = ShapelyUtils.crosses(
int_multipoly, current_point, path[closest_point_index]
)
# JSCUT path = path.slice(closest_point_index, len(path)).concat(path.slice(0, closest_point_index))
path = path[closest_point_index:] + path[:closest_point_index]
path.append(path[0])
if need_new:
merged_paths.append(current_path)
current_path = path
current_point = current_path[-1]
else:
current_path = current_path + path
current_point = current_path[-1]
merged_paths.append(current_path)
cam_paths: List[CamPath] = []
for path in merged_paths:
safe_to_close = not ShapelyUtils.crosses(bounds, path[0], path[-1])
if closed_path == False:
safe_to_close = False
cam_paths.append(CamPath(shapely.geometry.LineString(path), safe_to_close))
return cam_paths
@staticmethod
def dist(x1: float, y1: float, x2: float, y2: float) -> float:
dx = x2 - x1
dy = y2 - y1
return dx * dx + dy * dy
@staticmethod
def distP(p1: Tuple[int, int], p2: Tuple[int, int]) -> float:
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
return dx * dx + dy * dy
@classmethod
def get_gcode(cls, args) -> List[str]:
"""
Convert paths to gcode. the function assumes that the current Z position is at safeZ.
get_gcode()'s gcode returns Z to this position at the end.
args must have:
optype: Type of Op.
paths: Array of CamPath
ramp: Ramp these paths?
x_offset: Offset X (gcode units)
y_offset: Offset Y (gcode units)
decimal: Number of decimal places to keep in gcode
topZ: Top of area to cut (gcode units)
botZ: Bottom of area to cut (gcode units)
safeZ: Z position to safely move over uncut areas (gcode units)
passdepth: Cut depth for each pass (gcode units)
plunge_feed: Feedrate to plunge cutter (gcode units)
retract_feed: Feedrate to retract cutter (gcode units)
cut_feed: Feedrate for horizontal cuts (gcode units)
rapid_feed: Feedrate for rapid moves (gcode units)
tool_diameter:
helix_pitch: Depth of an helix revolution
helix_plunge_rate: Helix plunge rate
tabs: List of tabs
tabZ: Level below which tabs are to be processed
peckZ: Level to retract when pecking
flip_xy Toggle X with Y
"""
optype = args["optype"]
paths: List[CamPath] = args["paths"]
ramp = args["ramp"]
x_offset = args["x_offset"]
y_offset = args["y_offset"]
decimal = args["decimal"]
topZ = args["topZ"]
botZ = args["botZ"]
safeZ = args["safeZ"]
passdepth = args["passdepth"]
plunge_feed_gcode = " F%d" % args["plunge_feed"]
retract_feed_gcode = " F%d" % args["retract_feed"]
cut_feed_gcode = " F%d" % args["cut_feed"]
rapid_feed_gcode = " F%d" % args["rapid_feed"]
plunge_feed = args["plunge_feed"]
retract_feed = args["retract_feed"]
cut_feed = args["cut_feed"]
rapid_feed = args["rapid_feed"]
tabs = args["tabs"]
tabZ = args["tabZ"]
peckZ = args["peckZ"]
flip_xy = args["flip_xy"]
gcode = []
retract_gcode = [
"; Retract",
"G1 Z" + safeZ.to_fixed(decimal) + f"{rapid_feed_gcode}",
]
retract_for_tab_gcode = [
"; Retract for tab",
"G1 Z" + tabZ.to_fixed(decimal) + f"{rapid_feed_gcode}",
]
retract_for_peck = [
"; Retract for peck",
"G1 Z" + peckZ.to_fixed(decimal) + f"{rapid_feed_gcode}",
]
def get_x(p: Tuple[float, float]):
return p[0] + x_offset
def get_y(p: Tuple[float, float]):
return -p[1] + y_offset
def convert_point(p: Tuple[float, float] | Tuple[float, float, float]):
x = p[0] + x_offset
y = -p[1] + y_offset
if flip_xy is False:
result = (
" X"
+ ValWithUnit(x, "-").to_fixed(decimal)
+ " Y"
+ ValWithUnit(y, "-").to_fixed(decimal)
)
else:
result = (
" X"
+ ValWithUnit(-y, "-").to_fixed(decimal)
+ " Y"
+ ValWithUnit(x, "-").to_fixed(decimal)
)
return result
def convert_point_3D(p: Tuple[float, float, float]):
x = p[0] + x_offset
y = -p[1] + y_offset
z = p[2]
if flip_xy is False:
result = (
" X"
+ ValWithUnit(x, "-").to_fixed(decimal)
+ " Y"
+ ValWithUnit(y, "-").to_fixed(decimal)
+ " Z"
+ ValWithUnit(z, "-").to_fixed(decimal)
)
else:
result = (
" X"
+ ValWithUnit(-y, "-").to_fixed(decimal)
+ " Y"
+ ValWithUnit(x, "-").to_fixed(decimal)
+ " Z"
+ ValWithUnit(z, "-").to_fixed(decimal)
)
return result
# special case
if optype == "Helix":
SEG_LEN = 0.1
tool_diameter = args["tool_diameter"]
helix_outer_radius = args["helix_outer_radius"]
helix_pitch = args["helix_pitch"]
helix_plunge_rate = args["helix_plunge_rate"]
if helix_outer_radius < tool_diameter / 2.0:
helix_outer_radius = tool_diameter / 2.0 + 0.1 # drill
cut_depth = -botZ
for campath in paths:
center = (campath.path.coords.xy[0][0], campath.path.coords.xy[1][0])
circle_travel_radius = helix_outer_radius - tool_diameter / 2.0
circle_travel = 2 * PI * circle_travel_radius
nb_pts_per_revolution = math.floor(circle_travel / SEG_LEN)
nb_helixes = math.floor(cut_depth / helix_pitch)
helix_pitch_last = cut_depth - nb_helixes * helix_pitch
# calculate all the pts with z component
pts: List[Tuple[float, float, float]] = []
# the helix revolutions
for i in range(0, nb_helixes):
for k in range(nb_pts_per_revolution):
x = math.cos(2 * PI * k / nb_pts_per_revolution)
y = math.sin(2 * PI * k / nb_pts_per_revolution)
height = helix_pitch # shorter name
z = -i * height - k * height / nb_pts_per_revolution
xx = center[0] + circle_travel_radius * x
yy = center[1] + circle_travel_radius * y
pts.append((xx, yy, z))
# and the last one
if helix_pitch_last > 0.0:
for k in range(nb_pts_per_revolution):
x = math.cos(2 * PI * k / nb_pts_per_revolution)
y = math.sin(2 * PI * k / nb_pts_per_revolution)
height = helix_pitch
last_height = helix_pitch_last
z = (
-nb_helixes * height
- k * last_height / nb_pts_per_revolution
)
xx = center[0] + circle_travel_radius * x
yy = center[1] + circle_travel_radius * y
pts.append((xx, yy, z))
# and the last flat circle
for k in range(nb_pts_per_revolution + 1):
x = math.cos(2 * PI * k / nb_pts_per_revolution)
y = math.sin(2 * PI * k / nb_pts_per_revolution)
z = -cut_depth
xx = center[0] + circle_travel_radius * x
yy = center[1] + circle_travel_radius * y
pts.append((xx, yy, z))
# the gcode
gcode.append("; Rapid to op center position")
gcode.append("G1" + convert_point(center) + rapid_feed_gcode)
gcode.append("; Slow to op initial position")
pt0 = pts[0]
gcode.append("G1" + convert_point(pt0) + cut_feed_gcode)
for k, pt in enumerate(pts):
if k == 0:
gcode.append(
"G1" + convert_point_3D(pt) + f" F{helix_plunge_rate}"
)
else:
gcode.append("G1" + convert_point_3D(pt))
gcode.extend(retract_gcode)
gcode.append("; Rapid to op center position")
gcode.append("G1" + convert_point(center) + rapid_feed_gcode)
return gcode
# tabs are globals - but maybe this path does not hits any tabs
crosses_tabs = False
# --> crosses_tabs will be fixed later
for path_index, path in enumerate(paths):
orig_path = path.path
if len(orig_path.coords) == 0:
continue
# split the path to cut into many partials paths to avoid tabs areas
tab_separator = TabsSeparator(tabs)
tab_separator.separate(orig_path)
separated_paths = tab_separator.separated_paths
crosses_tabs = tab_separator.crosses_tabs
gcode.append("")
gcode.append(f"; Path {path_index+1}")
currentZ = safeZ
finishedZ = topZ
# need to cut at tabZ if tabs there
exact_tabz_level_done = False
while finishedZ > botZ:
nextZ = max(finishedZ - passdepth, botZ)
if crosses_tabs:
if nextZ == tabZ:
exact_tabz_level_done = True
elif nextZ < tabZ:
# a last cut at the exact tab height withput tabs
if exact_tabz_level_done == False:
nextZ = tabZ
exact_tabz_level_done = True
if currentZ <= tabZ and ((not path.safe_to_close) or crosses_tabs):
if optype == "Peck":
gcode.extend(retract_for_peck)
currentZ = peckZ
else:
gcode.extend(retract_gcode)
currentZ = safeZ
elif currentZ < safeZ and (not path.safe_to_close):
if optype == "Peck":
gcode.extend(retract_for_peck)
currentZ = peckZ
else:
gcode.extend(retract_gcode)
currentZ = safeZ
# check this - what does it mean ???
if not crosses_tabs:
currentZ = finishedZ
else:
currentZ = max(finishedZ, tabZ)
gcode.append("; Rapid to initial position")
gcode.append(
"G1" + convert_point(list(orig_path.coords)[0]) + rapid_feed_gcode
)
in_tabs_height = False
if not crosses_tabs:
in_tabs_height = False
selected_paths = [orig_path]
gcode.append("G1 Z" + ValWithUnit(currentZ, "-").to_fixed(decimal))
else:
if nextZ >= tabZ:
in_tabs_height = False
selected_paths = [orig_path]
gcode.append(
"G1 Z" + ValWithUnit(currentZ, "-").to_fixed(decimal)
)
else:
in_tabs_height = True
selected_paths = separated_paths
for selected_path in selected_paths:
if selected_path.is_empty:
continue
executed_ramp = False
min_plunge_time = (currentZ - nextZ) / plunge_feed
if ramp and min_plunge_time > 0:
min_plunge_time = (currentZ - nextZ) / plunge_feed
ideal_dist = cut_feed * min_plunge_time
total_dist = 0.0
for end in range(1, len(list(selected_path.coords))):
if total_dist > ideal_dist:
break
pt1 = list(selected_path.coords)[end - 1]
pt2 = list(selected_path.coords)[end]
total_dist += 2 * cam.dist(
get_x(pt1), get_y(pt1), get_x(pt2), get_y(pt2)
)
if total_dist > 0:
ramp_path_forw = [
list(selected_path.coords)[k] for k in range(0, end)
]
ramp_path_backw = [
list(selected_path.coords)[k] for k in range(0, end - 1)
]
ramp_path_backw.reverse()
ramp_path = ramp_path_forw + ramp_path_backw
if in_tabs_height:
# move to initial point of partial path
gcode.append(
"; Tab: move to first point of partial path at safe height"
)
gcode.append("G1" + convert_point(ramp_path[1]))
gcode.append("; plunge")
gcode.append(
"G1 Z"
+ ValWithUnit(nextZ, "-").to_fixed(decimal)
+ plunge_feed_gcode
)
gcode.append("; ramp")
executed_ramp = True
dist_travelled = 0.0
for i in range(1, len(ramp_path)):
dist_travelled += cam.dist(
get_x(ramp_path[i - 1]),
get_y(ramp_path[i - 1]),
get_x(ramp_path[i]),
get_y(ramp_path[i]),
)
newZ = currentZ + dist_travelled / total_dist * (
nextZ - currentZ
)
gcode_line_start = (
"G1"
+ convert_point(ramp_path[i])
+ " Z"
+ ValWithUnit(newZ, "-").to_fixed(decimal)
)
if i == 1:
gcode.append(
gcode_line_start
+ " F"
+ ValWithUnit(
math.floor(
min(
total_dist / min_plunge_time,
cut_feed,
)
),
"-",
).to_fixed(decimal)
)
else:
gcode.append(gcode_line_start)
if not in_tabs_height:
if not executed_ramp:
gcode.append("; plunge")
gcode.append(
"G1 Z"
+ ValWithUnit(nextZ, "-").to_fixed(decimal)
+ plunge_feed_gcode
)
if in_tabs_height:
# move to initial point of partial path
gcode.append(
"; Tab: move to first point of partial path at safe height"
)
gcode.append(
"G1" + convert_point(list(selected_path.coords)[0])
)
gcode.append("; plunge")