forked from shaise/FreeCAD_SheetMetal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSheetMetalNewUnfolder.py
More file actions
1415 lines (1329 loc) · 61.1 KB
/
Copy pathSheetMetalNewUnfolder.py
File metadata and controls
1415 lines (1329 loc) · 61.1 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
########################################################################
#
# SheetMetalNewUnfolder.py
#
# Copyright 2025 Alex Neufeld <alex.d.neufeld@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2 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 Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
########################################################################
from enum import Enum, auto
from functools import reduce
from itertools import combinations
from math import degrees, log10, pi, radians, sin, tan
from operator import mul as multiply_operator
from statistics import StatisticsError, mode
import FreeCAD
import Part
from FreeCAD import Matrix, Placement, Rotation, Vector
from TechDraw import projectEx as project_shape_to_plane
import SheetMetalTools
try:
import networkx as nx
except ImportError:
FreeCAD.Console.PrintUserError(
"The NetworkX Python package could not be imported. "
"Consider checking that it is installed, "
"or reinstalling the SheetMetal workbench using the addon manager\n"
)
try:
test_graph = nx.Graph
except AttributeError:
FreeCAD.Console.PrintUserError(
"The NetworkX Python package is version "
+ str(nx.__version__)
+ "\n"
+ "Consider checking that it is at least version 3.4.2\n "
)
# We need to VERY CAREFULLY choose multiple different 'epsilon' values
# for different types of numerical comparisons.
#
# Default eps value to use for most numerical approximations.
# This is intentionally larger than OCC's tolerance requirements,
# so that out of tolerance geometry can still be processed
# and then fixed later with cleanup passes
eps = FreeCAD.Base.Precision.approximation()
# This is used instead of 'eps' when comparing angles.
eps_angular = FreeCAD.Base.Precision.angular()
# When running cleanup passes, it will be assumed that points that are
# closer together than this value should be altered to be exactly
# coincident.
fuzz = 1e-3 # <-- 1 / 1000 * 1mm = one micrometer
# This is OCC's upper bound for tolerance errors when building geometry.
# Make sure to use it as an acceptance criterion before passing data
# to OCC!
tol = FreeCAD.Base.Precision.confusion()
# When converting B-Splines to Arcs, use a much larger tolerance value,
# so that we don't end up with too many small segments.
spline2arc_tol = 0.1 # One tenth of one millimeter.
# Used when splitting an edge into a set number of small segments.
discretization_quantity = 10
class EstimateThickness:
"""This class provides helper functions to determine the sheet
thickness of a solid-modelled sheet metal part.
"""
@staticmethod
def from_normal_edges(shp: Part.Shape, selected_face: int) -> float:
"""Get the modal length of all straight edges that share
a vertex with the selected root face, and are oriented in line
with the root faces normal direction. Edges that meet these
criteria usually correspond to the sheet thickness.
"""
num_places = abs(int(log10(eps)))
root_face = shp.Faces[selected_face]
normal = root_face.Surface.Axis
# Checking membership of an edge in a shape directly won't work.
# We must compare via hashCodes instead.
root_face_edge_hashes = [e.hashCode() for e in root_face.Edges]
length_values = []
for v in root_face.Vertexes:
for e in shp.ancestorsOfType(v, Part.Edge):
if (
e.hashCode() not in root_face_edge_hashes
and e.Curve.TypeId == "Part::GeomLine"
and SheetMetalTools.smIsParallel(e.Curve.Direction, normal)
):
length_values.append(round(e.Length, num_places))
try:
thickness_value = mode(length_values)
return thickness_value
except StatisticsError:
return 0.0
@staticmethod
def from_cylinders(shp: Part.Shape) -> float:
"""In a typical sheet metal part, the solid model has lots of bends, each
bend having 2 concentric cylindrical faces. If we take the modal
difference between all possible combinations of radii present in the
subset of shape faces which are cylindrical, we will usually get the
exact thickness of the sheet metal part.
"""
num_places = abs(int(log10(eps)))
curv_map = {}
for face in shp.Faces:
if face.Surface.TypeId == "Part::GeomCylinder":
# Normalize the axis and center-point.
normalized_axis = face.Surface.Axis.normalize()
if normalized_axis.dot(Vector(0, 0, -1)) < 0:
normalized_axis = normalized_axis.negative()
cleaned_axis = Vector(*[round(d, num_places) for d in normalized_axis])
adjusted_center = face.Surface.Center.projectToPlane(Vector(), normalized_axis)
cleaned_center = Vector(*[round(d, num_places) for d in adjusted_center])
key = (*cleaned_axis, *cleaned_center)
if key in curv_map:
curv_map[key].append(face.Surface.Radius)
else:
curv_map[key] = [
face.Surface.Radius,
]
combined_list_of_thicknesses = [
val
for radset in curv_map.values()
if len(radset) > 1
for r1, r2 in combinations(radset, 2)
if (val := abs(r1 - r2)) > eps
]
try:
thickness_value = mode(combined_list_of_thicknesses)
return thickness_value
except StatisticsError:
return 0.0
@staticmethod
def from_face(shape: Part.Shape, selected_face: int) -> float:
ref_face = shape.Faces[selected_face]
# Find all planar faces that are parallel to the chosen face.
candidates = [
f
for f in shape.Faces
if f.hashCode() != ref_face.hashCode()
and f.Surface.TypeId == "Part::GeomPlane"
and SheetMetalTools.smIsParallel(ref_face.Surface.Axis, f.Surface.Axis)
]
if not candidates:
return 0.0
opposite_face = sorted(candidates, key=lambda x: abs(x.Area - ref_face.Area))[0]
return abs(opposite_face.valueAt(0, 0).distanceToPlane(ref_face.Surface.Position,
ref_face.Surface.Axis))
@staticmethod
def using_best_method(shape: Part.Shape, selected_face: int) -> float:
thickness = EstimateThickness.from_normal_edges(shape, selected_face)
if not thickness:
thickness = EstimateThickness.from_face(shape, selected_face)
if not thickness:
thickness = EstimateThickness.from_cylinders(shape)
if not thickness:
errmsg = "Couldn't estimate thickness for shape!"
raise RuntimeError(errmsg)
return thickness
class TangentFaces:
"""This class provides functions to check if brep faces are tangent
to each other. each compare_x_x function accepts two surfaces of a
particular type, and returns a boolean value indicating tangency.
The compare function accepts two faces and selects the correct
compare_x_x function automatically.
"""
@staticmethod
def compare_plane_plane(p1: Part.Plane, p2: Part.Plane) -> bool:
# Returns True if the two planes have similar normals and
# the base point of the first plane is (nearly) coincident with
# the second plane.
return (
SheetMetalTools.smIsParallel(p1.Axis, p2.Axis)
and p1.Position.distanceToPlane(p2.Position, p2.Axis) < eps
)
@staticmethod
def compare_plane_cylinder(p: Part.Plane, c: Part.Cylinder) -> bool:
# Returns True if the cylinder is tangent to the plane
# (there is 'line contact' between the surfaces).
return (
SheetMetalTools.smIsNormal(p.Axis, c.Axis)
and abs(abs(c.Center.distanceToPlane(p.Position, p.Axis)) - c.Radius) < eps
)
@staticmethod
def compare_cylinder_cylinder(c1: Part.Cylinder, c2: Part.Cylinder) -> bool:
# Returns True if the two cylinders have parallel axis' and
# those axis' are separated by a distance of
# approximately r1 + r2.
return (
SheetMetalTools.smIsParallel(c1.Axis, c2.Axis)
and abs(
c1.Center.distanceToLine(c2.Center, c2.Axis) - (c1.Radius + c2.Radius)
)
< eps
)
@staticmethod
def compare_plane_torus(p: Part.Plane, t: Part.Toroid) -> bool:
# Imagine a donut sitting flat on a table.
# That's our tangency condition for a plane and a toroid.
return (
SheetMetalTools.smIsParallel(p.Axis, t.Axis)
and abs(abs(t.Center.distanceToPlane(p.Position, p.Axis)) - t.MinorRadius)
< eps
)
@staticmethod
def compare_cylinder_torus(c: Part.Cylinder, t: Part.Toroid) -> bool:
# If the surfaces are tangent, either we have:
# - a donut inside a circular container, with no gap at the
# container perimeter;
# - a donut shoved onto a shaft with no wiggle room;
# - a cylinder with an axis tangent to the central circle of
# the donut.
return (
SheetMetalTools.smIsParallel(c.Axis, t.Axis)
and c.Center.distanceToLine(t.Center, t.Axis) < eps
and (
abs(c.Radius - abs(t.MajorRadius - t.MinorRadius)) < eps
or abs(c.Radius - abs(t.MajorRadius + t.MinorRadius)) < eps
)
) or (
SheetMetalTools.smIsNormal(c.Axis, t.Axis)
and abs(abs(t.Center.distanceToLine(c.Center, c.Axis)) - t.MajorRadius)
< eps
and abs(c.Radius - t.MinorRadius) < eps
)
@staticmethod
def compare_sphere_sphere(s1: Part.Sphere, s2: Part.Sphere) -> bool:
# Only segments of identical spheres are tangent to each other.
return s1.Center.distanceToPoint(s2.Center) < eps and abs(s1.Radius - s2.Radius) < eps
@staticmethod
def compare_plane_sphere(p: Part.Plane, s: Part.Sphere) -> bool:
# This function will probably never actually return True,
# because a plane and a sphere only ever share a vertex if
# they are tangent to each other.
return abs(abs(s.Center.distanceToPlane(p.Position, p.Axis)) - s.Radius) < eps
@staticmethod
def compare_torus_sphere(t: Part.Toroid, s: Part.Sphere) -> bool:
return (
s.Center.distanceToPoint(t.Center) < eps
and (
abs(t.MajorRadius - t.MinorRadius - s.Radius) < eps
or abs(t.MajorRadius + t.MinorRadius - s.Radius) < eps
)
) or (
abs(s.Radius - t.MinorRadius) < eps
and SheetMetalTools.smIsNormal(t.Axis, s.Center - t.Center)
and abs(t.Center.distanceToPoint(s.Center) - t.MajorRadius) < eps
)
@staticmethod
def compare_torus_torus(t1: Part.Toroid, t2: Part.Toroid) -> bool:
return (
t1.Center.distanceToLine(t2.Center, t2.Axis) < eps
and SheetMetalTools.smIsParallel(t1.Axis, t2.Axis)
and abs(
t1.Center.distanceToPoint(t2.Center) ** 2
+ (t1.MajorRadius - t2.MajorRadius) ** 2
- (t1.MinorRadius + t2.MinorRadius) ** 2
)
< eps
)
@staticmethod
def compare_cylinder_sphere(c: Part.Cylinder, s: Part.Sphere) -> bool:
# The sphere must be sized/positioned like a ball sliding down
# a tube with no wiggle room.
return (
(s.Center.distanceToLine(c.Center, c.Axis) < eps and abs(s.Radius - c.Radius) < eps)
# Point contact case.
or (abs(s.Center.distanceToLine(c.Center, c.Axis) - s.Radius - c.Radius) < eps)
)
@staticmethod
def compare_plane_cone(p: Part.Plane, cn: Part.Cone) -> bool:
return (abs(cn.Apex.distanceToPlane(p.Position, p.Axis)) < eps
and (abs(cn.Axis.getAngle(p.Axis) - abs(cn.SemiAngle) - pi/2) < eps_angular
or abs(cn.Axis.getAngle(p.Axis) + abs(cn.SemiAngle) - pi/2) < eps_angular
)
)
@staticmethod
def compare_cone_cone(cn1: Part.Cone, cn2: Part.Cone) -> bool:
return (cn1.Apex.distanceToPoint(cn2.Apex) < eps
and abs(cn1.Axis.getAngle(cn2.Axis) - cn1.SemiAngle - cn2.SemiAngle) < eps_angular
)
@staticmethod
def compare_sphere_cone(s: Part.Sphere, cn: Part.Cone) -> bool:
return (s.Center.distanceToLine(cn.Apex, cn.Axis) < eps
and (cn.Apex.distanceToPoint(s.Center)*sin(cn.SemiAngle) - s.Radius) < eps
)
@staticmethod
def compare_cylinder_cone(c: Part.Cylinder, cn: Part.Cone) -> bool:
return (abs(cn.Apex.distanceToLine(c.Center, c.Axis) - c.Radius) < eps
and (abs(c.Axis.getAngle(cn.Axis) - cn.SemiAngle) < eps_angular
or abs(pi - c.Axis.getAngle(cn.Axis) - abs(cn.SemiAngle)) < eps_angular
)
)
@staticmethod
def compare_torus_cone(t: Part.Toroid, cn: Part.Cone) -> bool:
return (
SheetMetalTools.smIsParallel(t.Axis, cn.Axis)
and cn.Apex.distanceToLine(t.Center, t.Axis) < eps
and (
abs(
t.MajorRadius / tan(cn.SemiAngle)
- t.MinorRadius / sin(cn.SemiAngle)
- cn.Apex.distanceToPoint(t.Center)
)
< eps
or abs(
t.MajorRadius / tan(cn.SemiAngle)
+ t.MinorRadius / sin(cn.SemiAngle)
- cn.Apex.distanceToPoint(t.Center)
)
< eps
)
)
@staticmethod
def compare_plane_extrusion(p: Part.Plane, ex: Part.SurfaceOfExtrusion) -> bool:
return False # TODO
@staticmethod
def compare_cylinder_extrusion(c: Part.Cylinder, ex: Part.SurfaceOfExtrusion) -> bool:
return False # TODO
@staticmethod
def compare_torus_extrusion(t: Part.Toroid, ex: Part.SurfaceOfExtrusion) -> bool:
return False # TODO
@staticmethod
def compare_sphere_extrusion(s: Part.Sphere, ex: Part.SurfaceOfExtrusion) -> bool:
return False # TODO
@staticmethod
def compare_extrusion_extrusion(
ex1: Part.SurfaceOfExtrusion, ex2: Part.SurfaceOfExtrusion
) -> bool:
return False # TODO
@staticmethod
def compare_extrusion_cone(ex: Part.SurfaceOfExtrusion, cn: Part.Cone) -> bool:
return False # TODO
@staticmethod
def compare(face1: Part.Face, face2: Part.Face) -> bool:
# order types to simplify pattern matching
s1 = face1.Surface
s2 = face2.Surface
type1 = s1.TypeId
type2 = s2.TypeId
order = [
"Part::GeomPlane",
"Part::GeomCylinder",
"Part::GeomToroid",
"Part::GeomSphere",
"Part::GeomSurfaceOfExtrusion",
"Part::GeomCone",
]
needs_swap = (
type1 in order
and type2 in order
and order.index(type1) > order.index(type2)
)
if needs_swap:
s2, s1 = s1, s2
cls = TangentFaces
if s1.TypeId == "Part::GeomPlane":
# Plane.
if s2.TypeId == "Part::GeomPlane":
return cls.compare_plane_plane(s1, s2)
elif s2.TypeId == "Part::GeomCylinder":
return cls.compare_plane_cylinder(s1, s2)
elif s2.TypeId == "Part::GeomToroid":
return cls.compare_plane_torus(s1, s2)
elif s2.TypeId == "Part::GeomSphere":
return cls.compare_plane_sphere(s1, s2)
elif s2.TypeId == "Part::GeomSurfaceOfExtrusion":
return cls.compare_plane_extrusion(s1, s2)
elif s2.TypeId == "Part::GeomCone":
return cls.compare_plane_cone(s1, s2)
# Cylinder.
elif s1.TypeId == "Part::GeomCylinder":
if s2.TypeId == "Part::GeomCylinder":
return cls.compare_cylinder_cylinder(s1, s2)
elif s2.TypeId == "Part::GeomToroid":
return cls.compare_cylinder_torus(s1, s2)
elif s2.TypeId == "Part::GeomSphere":
return cls.compare_cylinder_sphere(s1, s2)
elif s2.TypeId == "Part::GeomSurfaceOfExtrusion":
return cls.compare_cylinder_extrusion(s1, s2)
elif s2.TypeId == "Part::GeomCone":
return cls.compare_cylinder_cone(s1, s2)
elif s1.TypeId == "Part::GeomToroid":
# Torus.
if s2.TypeId == "Part::GeomToroid":
return cls.compare_torus_torus(s1, s2)
elif s2.TypeId == "Part::GeomSphere":
return cls.compare_torus_sphere(s1, s2)
elif s2.TypeId == "Part::GeomSurfaceOfExtrusion":
return cls.compare_torus_extrusion(s1, s2)
elif s2.TypeId == "Part::GeomCone":
return cls.compare_torus_cone(s1, s2)
elif s1.TypeId == "Part::GeomSphere":
# Sphere.
if s2.TypeId == "Part::GeomSphere":
return cls.compare_sphere_sphere(s1, s2)
elif s2.TypeId == "Part::GeomSurfaceOfExtrusion":
return cls.compare_sphere_extrusion(s1, s2)
elif s2.TypeId == "Part::GeomCone":
return cls.compare_sphere_cone(s1, s2)
elif s1.TypeId == "Part::GeomSurfaceOfExtrusion":
# Extrusion.
if s2.TypeId == "Part::GeomSurfaceOfExtrusion":
return cls.compare_extrusion_extrusion(s1, s2)
elif s2.TypeId == "Part::GeomCone":
return cls.compare_extrusion_cone(s1, s2)
elif s1.TypeId == "Part::GeomCone":
# Cone.
if s2.TypeId == "Part::GeomCone":
return cls.compare_cone_cone(s1, s2)
# All other cases.
return False
class UVRef(Enum):
"""Describes reference corner for a rectangular-ish surface patch."""
BOTTOM_LEFT = auto()
BOTTOM_RIGHT = auto()
TOP_LEFT = auto()
TOP_RIGHT = auto()
class BendDirection(Enum):
"""Up is like a tray with a raised lip, down is like the rolled
over edges of a table.
"""
UP = auto()
DOWN = auto()
@staticmethod
def from_face(bent_face: Part.Face):
"""Cylindrical faces may be convex or concave, and the boundary
representation can be forward or reversed. The bend direction
may be determined according to these values.
"""
curv_a, curv_b = bent_face.curvatureAt(0, 0)
if curv_a < 0 and abs(curv_b) < eps:
if bent_face.Orientation == "Forward":
return BendDirection.DOWN
else:
return BendDirection.UP
elif curv_b > 0 and abs(curv_a) < eps:
if bent_face.Orientation == "Forward":
return BendDirection.UP
else:
return BendDirection.DOWN
else:
errmsg = "Unable to determine bend direction from cylindrical face"
raise RuntimeError(errmsg)
class SketchExtraction:
"""Helper functions to produce clean 2D geometry from unfolded shapes."""
@staticmethod
def edges_to_sketch_object(
edges: list[Part.Edge],
object_name: str,
existing_sketches: list[str] = None,
color: str = "#00FF00",
) -> FreeCAD.DocumentObject:
"""Converts a list of edges to an un-constrained sketch object.
This allows the user to more easily make small changes to the
sheet metal cutting pattern when prepping it for fabrication.
"""
cleaned_up_edges = edges # Edge2DCleanup.cleanup_sketch(edges, spline2arc_tol)
# See if there is an existing sketch with the same name,
# use it instead of creating a new one.
if existing_sketches is None:
existing_sketch_name = ""
else:
existing_sketch_name = next(
(item for item in existing_sketches if item.startswith(object_name)), "")
sketch = FreeCAD.ActiveDocument.getObject(existing_sketch_name)
if sketch is not None:
sketch.deleteAllGeometry()
else:
# If there is not already an existing sketch, create one.
sketch = FreeCAD.ActiveDocument.addObject("Sketcher::SketchObject", object_name)
sketch.Placement = Placement()
for edge in cleaned_up_edges:
startpoint = edge.firstVertex().Point
endpoint = edge.lastVertex().Point
curvetype = edge.Curve.TypeId
if curvetype == "Part::GeomLine":
if startpoint.distanceToPoint(endpoint) > eps:
sketch.addGeometry(Part.LineSegment(startpoint, endpoint))
elif curvetype == "Part::GeomCircle":
if startpoint.distanceToPoint(endpoint) < eps:
# Full circle.
sketch.addGeometry(
Part.Circle(edge.Curve.Center, Vector(0, 0, 1), edge.Curve.Radius)
)
else:
# Arc.
pmin, pmax = edge.ParameterRange
midpoint = edge.valueAt(pmin + 0.5 * (pmax - pmin))
sketch.addGeometry(Part.Arc(startpoint, midpoint, endpoint))
else:
errmsg = ("Unusable curve type found during sketch creation: " + curvetype)
raise RuntimeError(errmsg)
sketch.Label = object_name
sketch.recompute()
# If the gui is running, change the color of the sketch lines
# and vertices.
if FreeCAD.GuiUp:
rgb_color = tuple(int(color[i : i + 2], 16) for i in (1, 3, 5))
v = FreeCAD.Version()
if v[0] == "0" and int(v[1]) < 21:
rgb_color = tuple(i / 255 for i in rgb_color)
sketch.ViewObject.LineColor = rgb_color
sketch.ViewObject.PointColor = rgb_color
if hasattr(sketch.ViewObject, "AutoColor"):
sketch.ViewObject.AutoColor = False
return sketch
@staticmethod
def wire_is_a_hole(w: Part.Wire) -> bool:
return (len(w.Edges) == 1
and w.Edges[0].Curve.TypeId == "Part::GeomCircle"
and abs(w.Edges[0].Length - 2 * pi * w.Edges[0].Curve.Radius) < eps
)
@staticmethod
def extract_manually(
unfolded_shape: Part.Shape, normal: Vector
) -> tuple[Part.Shape]:
"""Extract sketch lines from the topmost flattened face."""
# Another approach would be to slice the flattened solid with
# a plane to get a cross-section of the middle of the unfolded
# shape. This would probably be slower, but might be more robust
# in cases where the outerwire is not cleanly defined.
top_face = [
f
for f in unfolded_shape.Faces
if f.normalAt(0, 0).getAngle(normal) < eps_angular
][0]
sketch_profile = top_face.OuterWire
inner_wires = []
hole_wires = []
for w in top_face.Wires:
if w.hashCode() != sketch_profile.hashCode():
if SketchExtraction.wire_is_a_hole(w):
hole_wires.append(w)
else:
inner_wires.append(w)
return sketch_profile, inner_wires, hole_wires
@staticmethod
def extract_with_techdraw(solid: Part.Shape, direction: Vector) -> Part.Shape:
"""Uses functionality from the TechDraw API to project
a 3D shape onto a particular 2D plane.
"""
# this is a slow but robust method of sketch profile extraction
# ref:
# https://github.com/FreeCAD/FreeCAD/blob/main/src/Mod/Draft/draftobjects/shape2dview.py
raw_output = project_shape_to_plane(solid, direction)
edges = [group for group in raw_output[:5] if not group.isNull()]
compound = Part.makeCompound(edges)
return compound
@staticmethod
def move_to_origin(sketch: Part.Compound, root_face: Part.Face) -> Matrix:
"""Given a 2d shape and a reference face, compute a transformation matrix
that aligns the shape's bounding box to the origin of the XY-plane, with
the reference face oriented Z-up and rotated square to the global
coordinate system.
"""
# Find the orientation of the root face that aligns
# the U-direction with the x-axis.
origin = root_face.valueAt(0, 0)
x_axis = root_face.valueAt(1, 0) - origin
z_axis = root_face.normalAt(0, 0)
rotation = Rotation(x_axis, Vector(), z_axis, "ZXY")
alignment_transform = Placement(origin, rotation).toMatrix().inverse()
sketch_aligned_to_xy_plane = sketch.transformed(alignment_transform)
# Move in x and y so that the bounding box is entirely in
# the +x, +y quadrant.
mov_x = -1 * sketch_aligned_to_xy_plane.BoundBox.XMin
mov_y = -1 * sketch_aligned_to_xy_plane.BoundBox.YMin
mov_z = -1 * sketch_aligned_to_xy_plane.BoundBox.ZMin
shift_transform = Placement(Vector(mov_x, mov_y, mov_z), Rotation()).toMatrix()
overall_transform = Matrix()
overall_transform.transform(Vector(), alignment_transform)
overall_transform.transform(Vector(), shift_transform)
return overall_transform
class BendAllowanceCalculator:
def __init__(self) -> None:
self.k_factor_standard = None
self.radius_thickness_values = None
self.k_factor_values = None
@classmethod
def from_single_value(cls, k_factor: float, kfactor_standard: str):
"""One k-factor for all radius:thickness ratios."""
instance = cls()
instance.k_factor_standard = (
cls.KFactorStandard.ANSI if kfactor_standard == "ansi" else cls.KFactorStandard.DIN
)
instance.radius_thickness_values = [1.0, ]
instance.k_factor_values = [k_factor, ]
return instance
def get_k_factor(self, radius: float, thickness: float) -> float:
# If we are below the lowest tabulated value for the radius over
# thickness relation, return the smallest noted k-factor.
r_over_t = radius / thickness
if r_over_t <= self.radius_thickness_values[0]:
kf_val = self.k_factor_values[0]
# Apply similar logic to radius:thickness values greater than
# the largest available.
elif r_over_t >= self.radius_thickness_values[-1]:
kf_val = self.k_factor_values[-1]
# If we are within the range of specified radius: thickness
# values, perform piecewise linear interpolation.
else:
i = 0
while r_over_t <= self.radius_thickness_values[i]:
i += 1
kf1 = self.k_factor_values[i]
kf2 = self.k_factor_values[i + 1]
rt1 = self.radius_thickness_values[i]
rt2 = self.radius_thickness_values[i + 1]
kf_val = kf1 + (kf2 - kf1) * ((r_over_t - rt1) / (rt2 - rt1))
# We use the ansi definition of the k-factor everywhere
# internally.
return self._convert_to_ansi_kfactor(kf_val)
def get_bend_allowance(
self,
bend_direction: BendDirection,
radius: float,
thickness: float,
bend_angle: float,
) -> float:
factor = self.get_k_factor(radius, thickness)
if bend_direction == BendDirection.DOWN:
factor -= 1
bend_allowance = (radius + factor * thickness) * bend_angle
return bend_allowance
class KFactorStandard(Enum):
ANSI = auto()
DIN = auto()
@classmethod
def from_spreadsheet(cls, sheet: FreeCAD.DocumentObject):
instance = cls()
r_t_header = sheet.getContents("A1")
r_t_header = "".join(c for c in r_t_header if c not in "' ").lower()
if r_t_header != "radius/thickness":
errmsg = ("Cell A1 of material definition sheet must "
'be exactly "Radius/Thickness"')
raise ValueError(errmsg)
kf_header = sheet.getContents("B1")
kf_header = "".join(c for c in kf_header if c not in "' -()").lower()
if kf_header == "kfactoransi":
instance.k_factor_standard = cls.KFactorStandard.ANSI
elif kf_header == "kfactordin":
instance.k_factor_standard = cls.KFactorStandard.DIN
else:
errmsg = (
"Cell B1 of material definition sheet must be "
'one of "K-factor (ANSI)" or "K-factor (DIN)"'
)
raise ValueError(errmsg)
# Read cells from the A column until we get to an empty cell.
number_of_columns = 0
radius_thickness_list = []
k_factor_list = []
while sheet.getContents("A" + str(number_of_columns + 2)):
radius_thickness_list.append(sheet.get("A" + str(number_of_columns + 2)))
number_of_columns += 1
# Read corresponding k-factor values from the B column
# and throw an error if we find an empty cell too early.
for i in range(number_of_columns):
if not sheet.getContents("B" + str(i + 2)):
errmsg = (
"material definition sheet has an empty "
f"cell in the K-factors column (cell B{i + 2})"
)
raise ValueError(errmsg)
k_factor_list.append(sheet.get("B" + str(i + 2)))
instance.radius_thickness_values = radius_thickness_list
instance.k_factor_values = k_factor_list
return instance
def _convert_to_ansi_kfactor(self, k_factor: float) -> float:
if self.k_factor_standard == self.KFactorStandard.DIN:
return k_factor / 2.0
else:
return k_factor
class Edge2DCleanup:
"""Many sheet metal fabrication suppliers, as well as CAM systems
and laser cutting software, don't have good support for geometric
primitives other than lines and arcs. This class features tools to
replace bezier curves and other geometry types with lines and arcs.
"""
@staticmethod
def bspline_to_line(curve: Part.Edge) -> tuple[Part.Edge, float]:
p1 = curve.firstVertex().Point
p2 = curve.lastVertex().Point
if p1.distanceToPoint(p2) < eps:
return Part.Edge(), float("inf")
line = Part.makeLine(p1, p2)
max_err = Edge2DCleanup.check_err(curve, line)
return line, max_err
@staticmethod
def check_err(curve1: Part.Edge, curve2: Part.Edge) -> float:
max_err = 0.00
for i in range(discretization_quantity):
curve1_parameter = (curve1.FirstParameter
+ (curve1.LastParameter - curve1.FirstParameter)
* (i + 1)
/ (discretization_quantity + 1)
)
curve2_parameter = (curve2.FirstParameter
+ (curve2.LastParameter - curve2.FirstParameter)
* (i + 1)
/ (discretization_quantity + 1)
)
err = curve1.valueAt(curve1_parameter).distanceToPoint(
curve2.valueAt(curve2_parameter)
)
if err > max_err:
max_err = err
return max_err
@staticmethod
def bspline_to_arc(curve: Part.Edge) -> tuple[Part.Edge, float]:
point1 = curve.firstVertex().Point
point2 = curve.valueAt(
curve.FirstParameter + 0.5 * (curve.LastParameter - curve.FirstParameter)
)
point3 = curve.lastVertex().Point
if point1.distanceToPoint(point3) < eps:
# Full circle.
point4 = curve.valueAt(
curve.FirstParameter
+ 0.25 * (curve.LastParameter - curve.FirstParameter)
)
radius = point1.distanceToPoint(point2) / 2
center = point1 + 0.5 * (point2 - point1)
axis = (point1 - center).cross(point4 - center)
arc = Part.makeCircle(radius, center, axis)
else:
# Partial circle.
arc = Part.Arc(point1, point2, point3).toShape().Edges[0]
max_err = Edge2DCleanup.check_err(curve, arc)
return arc, max_err
@staticmethod
def curve_to_bisected_arcs(edge: Part.Edge, tolerance: float) -> list[Part.Edge]:
"""For a curved edge that isn't a straight line or circular arc,
choose the best available method to convert it to a series of
connected arcs.
"""
if edge.Curve.TypeId == "Part::GeomBSplineCurve":
c = edge.Curve
elif edge.Curve.TypeId == "Part::GeomBezierCurve":
c = edge.Curve.toBSpline()
elif edge.Curve.TypeId in (
"Part::GeomParabola",
"Part::GeomEllipse",
"Part::GeomHyperbola",
):
c = edge.toNurbs().Edges[0].Curve
else:
errmsg = (f"Unhandled curve type found during edge cleanup: {edge.Curve.TypeId}")
raise RuntimeError(errmsg)
arcs = c.toBiArcs(tolerance)
return [a.toShape().Edges[0] for a in arcs]
@staticmethod
def eliminate_bsplines(sketch: list[Part.Edge], tolerance: float) -> list[Part.Edge]:
"""Convert all geometry in the sketch to only straight lines
and arcs.
"""
new_edge_list = []
for edge in sketch:
if edge.Curve.TypeId in ["Part::GeomLine", "Part::GeomCircle"]:
new_edge_list.append(edge)
else:
new_edge, max_err = Edge2DCleanup.bspline_to_line(edge)
if max_err < tolerance:
new_edge_list.append(new_edge)
continue
new_edge, max_err = Edge2DCleanup.bspline_to_arc(edge)
if max_err < tolerance:
new_edge_list.append(new_edge)
continue
new_edge_list.extend(Edge2DCleanup.curve_to_bisected_arcs(edge, tolerance))
return new_edge_list
@staticmethod
def line_xy(p1: Vector, p2: Vector) -> Part.Edge:
"""Flatten a straight line to the XY-plane."""
return Part.makeLine(Vector(p1.x, p1.y, 0.0), Vector(p2.x, p2.y, 0.0))
@staticmethod
def arc_xy(start: Vector, middle: Vector, end: Vector) -> Part.Edge:
"""Flatten a circular arc to the XY-plane."""
return Part.Arc(Vector(start.x, start.y, 0.0), Vector(middle.x, middle.y, 0.0),
Vector(end.x, end.y, 0.0),
).toShape().Edges[0]
@staticmethod
def circle_xy(center: Vector, radius: Vector) -> Part.Edge:
"""Flatten a circle to the XY-plane."""
return Part.Circle(Vector(center.x, center.y, 0.0), Vector(0.0, 0.0, 1.0),
radius,
).toShape().Edges[0]
@staticmethod
def fix_coincidence(edgelist: list[Part.Edge], fuzzvalue: float) -> list[Part.Wire]:
"""Given a list of edges, finds pairs of edges with endpoints
that are nearly (but not exactly) coincident.
Returns:
A list of wires with improved coincidence between edges.
"""
try:
list_of_lists_of_edges = Part.sortEdges(edgelist, fuzzvalue)
except Part.OCCError:
# The optional fuzz-value argument is not available
# in FreeCAD version <= 0.21. Users should not expect good
# results with out-of tolerance shapes if the fuzz argument
# wasn't used.
list_of_lists_of_edges = Part.sortEdges(edgelist)
wires = []
for list_of_edges in list_of_lists_of_edges:
# Skip tiny edge segments.
useable_edges = [e for e in list_of_edges if e.Length > fuzzvalue]
if not useable_edges:
# Skip this edge list entirely if it was made up of
# only tiny segments.
continue
edgeloop_length = len(useable_edges)
if edgeloop_length > 1:
new_edges = []
for i in range(edgeloop_length):
e1 = useable_edges[i % edgeloop_length]
e2 = useable_edges[(i + 1) % edgeloop_length]
e1_start = e1.firstVertex().Point
e1_end = e1.lastVertex().Point
e2_start = e2.firstVertex().Point
e2_end = e2.lastVertex().Point
# This should be the correct error.
err1 = e1_end.distanceToPoint(e2_start)
# But one of these other ones might be the case we
# need to use if Part.sortEdges has failed to do its
# job properly.
err2 = e1_end.distanceToPoint(e2_end)
err3 = e1_start.distanceToPoint(e2_start)
err4 = e1_start.distanceToPoint(e2_end)
if err1 < err2 and err1 < err3 and err1 < err4:
# orientation is End ->*-> Start
startpoint = e1.firstVertex().Point
endpoint = e2.firstVertex().Point
elif err2 < err1 and err2 < err3 and err2 < err4:
# "orientation is End ->*-> End"
startpoint = e1.firstVertex().Point
endpoint = e2.lastVertex().Point
elif err3 < err1 and err3 < err2 and err3 < err4:
# orientation is Start ->*-> Start
startpoint = e1.lastVertex().Point
endpoint = e2.firstVertex().Point
elif err4 < err2 and err4 < err3 and err4 < err1:
# orientation is Start ->*-> End
startpoint = e1.lastVertex().Point
endpoint = e2.lastVertex().Point
else:
# Orientation is ambiguous - the best we can do
# is assume that the edges were sorted
# correctly.
startpoint = e1.firstVertex().Point
endpoint = e2.firstVertex().Point
if e1.Curve.TypeId == "Part::GeomLine":
new_edges.append(Edge2DCleanup.line_xy(startpoint, endpoint))
elif e1.Curve.TypeId == "Part::GeomCircle":
pmin, pmax = e1.ParameterRange
midpoint = e1.valueAt((pmax + pmin) / 2)
new_edges.append(Edge2DCleanup.arc_xy(startpoint, midpoint, endpoint))
else:
errmsg = f"Can't process edge with curve type = {e1.Curve.TypeId}"
raise RuntimeError(errmsg)
w = Part.Wire(new_edges)
wires.append(w)
else:
# Single edge loops.
edge = useable_edges[0]
if edge.Curve.TypeId != "Part::GeomCircle":
errmsg = "Can't process non-circular single-edge loop"
raise RuntimeError(errmsg)
w = Part.Wire([Edge2DCleanup.circle_xy(edge.Curve.Center, edge.Curve.Radius)])
wires.append(w)
return wires
@staticmethod
def merge_segmented_circles(wirelist: list[Part.Wire]) -> list[Part.Wire]:
"""Combine circles that are split into multiple edges so that they
can be recognized as holes properly.
"""
fixed_wire_list = []
for w in wirelist:
if (
len(w.Edges) > 1
and all([e.Curve.TypeId == "Part::GeomCircle" for e in w.Edges])
and all(
[
e.Curve.Center.distanceToPoint(w.Edges[0].Curve.Center) < eps
for e in w.Edges[1:]
]
)
and all(
[
abs(e.Curve.Radius - w.Edges[0].Curve.Radius) < eps
for e in w.Edges[1:]
]
)
):
new_wire = Part.Wire(
[
Edge2DCleanup.circle_xy(
w.Edges[0].Curve.Center, w.Edges[0].Curve.Radius
)
]
)
fixed_wire_list.append(new_wire)
else:
fixed_wire_list.append(w)
return fixed_wire_list
@staticmethod
def clean_and_structure_geometry(edges: list[Part.Edge]) -> list[Part.Wire]:
"""Run all available clean up passes."""
intermediate_result1 = Edge2DCleanup.eliminate_bsplines(edges, spline2arc_tol)
intermediate_result2 = Edge2DCleanup.fix_coincidence(intermediate_result1, fuzz)
result = Edge2DCleanup.merge_segmented_circles(intermediate_result2)
return result
def build_graph_of_tangent_faces(shp: Part.Shape, root: int) -> nx.Graph:
# Created a simple undirected graph object.