/
PathSurfaceSupport.py
2686 lines (2354 loc) · 98 KB
/
PathSurfaceSupport.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
# -*- coding: utf-8 -*-
# ***************************************************************************
# * Copyright (c) 2020 russ4262 <russ4262@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 (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * 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 Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
from __future__ import print_function
__title__ = "Path Surface Support Module"
__author__ = "russ4262 (Russell Johnson)"
__url__ = "http://www.freecadweb.org"
__doc__ = "Support functions and classes for 3D Surface and Waterline operations."
__contributors__ = ""
import FreeCAD
from PySide import QtCore
import Path
import PathScripts.PathLog as PathLog
import PathScripts.PathUtils as PathUtils
import PathScripts.PathOpTools as PathOpTools
import math
# lazily loaded modules
from lazy_loader.lazy_loader import LazyLoader
# MeshPart = LazyLoader('MeshPart', globals(), 'MeshPart')
Part = LazyLoader('Part', globals(), 'Part')
PathLog.setLevel(PathLog.Level.INFO, PathLog.thisModule())
# PathLog.trackModule(PathLog.thisModule())
# Qt translation handling
def translate(context, text, disambig=None):
return QtCore.QCoreApplication.translate(context, text, disambig)
class PathGeometryGenerator:
'''Creates a path geometry shape from an assigned pattern for conversion to tool paths.
PathGeometryGenerator(obj, shape, pattern)
`obj` is the operation object, `shape` is the horizontal planar shape object,
and `pattern` is the name of the geometric pattern to apply.
First, call the getCenterOfPattern() method for the CenterOfMass for patterns allowing a custom center.
Next, call the generatePathGeometry() method to request the path geometry shape.'''
# Register valid patterns here by name
# Create a corresponding processing method below. Precede the name with an underscore(_)
patterns = ('Circular', 'CircularZigZag', 'Line', 'Offset', 'Spiral', 'ZigZag')
def __init__(self, obj, shape, pattern):
'''__init__(obj, shape, pattern)... Instantiate PathGeometryGenerator class.
Required arguments are the operation object, horizontal planar shape, and pattern name.'''
self.debugObjectsGroup = False
self.pattern = 'None'
self.shape = None
self.pathGeometry = None
self.rawGeoList = None
self.centerOfMass = None
self.centerofPattern = None
self.deltaX = None
self.deltaY = None
self.deltaC = None
self.halfDiag = None
self.halfPasses = None
self.obj = obj
self.toolDiam = float(obj.ToolController.Tool.Diameter)
self.cutOut = self.toolDiam * (float(obj.StepOver) / 100.0)
self.wpc = Part.makeCircle(2.0) # make circle for workplane
# validate requested pattern
if pattern in self.patterns:
if hasattr(self, '_' + pattern):
self.pattern = pattern
if shape.BoundBox.ZMin != 0.0:
shape.translate(FreeCAD.Vector(0.0, 0.0, 0.0 - shape.BoundBox.ZMin))
if shape.BoundBox.ZLength > 1.0e-8:
msg = translate('PathSurfaceSupport',
'Shape appears to not be horizontal planar.')
msg += ' ZMax == {} mm.\n'.format(shape.BoundBox.ZMax)
FreeCAD.Console.PrintWarning(msg)
else:
self.shape = shape
self._prepareConstants()
def _prepareConstants(self):
# Compute weighted center of mass of all faces combined
if self.pattern in ['Circular', 'CircularZigZag', 'Spiral']:
if self.obj.PatternCenterAt == 'CenterOfMass':
fCnt = 0
totArea = 0.0
zeroCOM = FreeCAD.Vector(0.0, 0.0, 0.0)
for F in self.shape.Faces:
comF = F.CenterOfMass
areaF = F.Area
totArea += areaF
fCnt += 1
zeroCOM = zeroCOM.add(FreeCAD.Vector(comF.x, comF.y, 0.0).multiply(areaF))
if fCnt == 0:
msg = translate('PathSurfaceSupport',
'Cannot calculate the Center Of Mass.')
msg += ' ' + translate('PathSurfaceSupport',
'Using Center of Boundbox instead.') + '\n'
FreeCAD.Console.PrintError(msg)
bbC = self.shape.BoundBox.Center
zeroCOM = FreeCAD.Vector(bbC.x, bbC.y, 0.0)
else:
avgArea = totArea / fCnt
zeroCOM.multiply(1 / fCnt)
zeroCOM.multiply(1 / avgArea)
self.centerOfMass = FreeCAD.Vector(zeroCOM.x, zeroCOM.y, 0.0)
self.centerOfPattern = self._getPatternCenter()
else:
bbC = self.shape.BoundBox.Center
self.centerOfPattern = FreeCAD.Vector(bbC.x, bbC.y, 0.0)
# get X, Y, Z spans; Compute center of rotation
self.deltaX = self.shape.BoundBox.XLength
self.deltaY = self.shape.BoundBox.YLength
self.deltaC = self.shape.BoundBox.DiagonalLength # math.sqrt(self.deltaX**2 + self.deltaY**2)
lineLen = self.deltaC + (2.0 * self.toolDiam) # Line length to span boundbox diag with 2x cutter diameter extra on each end
self.halfDiag = math.ceil(lineLen / 2.0)
cutPasses = math.ceil(lineLen / self.cutOut) + 1 # Number of lines(passes) required to cover boundbox diagonal
self.halfPasses = math.ceil(cutPasses / 2.0)
# Public methods
def setDebugObjectsGroup(self, tmpGrpObject):
'''setDebugObjectsGroup(tmpGrpObject)...
Pass the temporary object group to show temporary construction objects'''
self.debugObjectsGroup = tmpGrpObject
def getCenterOfPattern(self):
'''getCenterOfPattern()...
Returns the Center Of Mass for the current class instance.'''
return self.centerOfPattern
def generatePathGeometry(self):
'''generatePathGeometry()...
Call this function to obtain the path geometry shape, generated by this class.'''
if self.pattern == 'None':
return False
if self.shape is None:
return False
cmd = 'self._' + self.pattern + '()'
exec(cmd)
if self.obj.CutPatternReversed is True:
self.rawGeoList.reverse()
# Create compound object to bind all lines in Lineset
geomShape = Part.makeCompound(self.rawGeoList)
# Position and rotate the Line and ZigZag geometry
if self.pattern in ['Line', 'ZigZag']:
if self.obj.CutPatternAngle != 0.0:
geomShape.Placement.Rotation = FreeCAD.Rotation(FreeCAD.Vector(0, 0, 1), self.obj.CutPatternAngle)
bbC = self.shape.BoundBox.Center
geomShape.Placement.Base = FreeCAD.Vector(bbC.x, bbC.y, 0.0 - geomShape.BoundBox.ZMin)
if self.debugObjectsGroup:
F = FreeCAD.ActiveDocument.addObject('Part::Feature', 'tmpGeometrySet')
F.Shape = geomShape
F.purgeTouched()
self.debugObjectsGroup.addObject(F)
if self.pattern == 'Offset':
return geomShape
# Identify intersection of cross-section face and lineset
cmnShape = self.shape.common(geomShape)
if self.debugObjectsGroup:
F = FreeCAD.ActiveDocument.addObject('Part::Feature', 'tmpPathGeometry')
F.Shape = cmnShape
F.purgeTouched()
self.debugObjectsGroup.addObject(F)
return cmnShape
# Cut pattern methods
def _Circular(self):
GeoSet = list()
radialPasses = self._getRadialPasses()
minRad = self.toolDiam * 0.45
siX3 = 3 * self.obj.SampleInterval.Value
minRadSI = (siX3 / 2.0) / math.pi
if minRad < minRadSI:
minRad = minRadSI
PathLog.debug(' -centerOfPattern: {}'.format(self.centerOfPattern))
# Make small center circle to start pattern
if self.obj.StepOver > 50:
circle = Part.makeCircle(minRad, self.centerOfPattern)
GeoSet.append(circle)
for lc in range(1, radialPasses + 1):
rad = (lc * self.cutOut)
if rad >= minRad:
circle = Part.makeCircle(rad, self.centerOfPattern)
GeoSet.append(circle)
# Efor
self.rawGeoList = GeoSet
def _CircularZigZag(self):
self._Circular() # Use _Circular generator
def _Line(self):
GeoSet = list()
centRot = FreeCAD.Vector(0.0, 0.0, 0.0) # Bottom left corner of face/selection/model
# Create end points for set of lines to intersect with cross-section face
pntTuples = list()
for lc in range((-1 * (self.halfPasses - 1)), self.halfPasses + 1):
x1 = centRot.x - self.halfDiag
x2 = centRot.x + self.halfDiag
y1 = centRot.y + (lc * self.cutOut)
# y2 = y1
p1 = FreeCAD.Vector(x1, y1, 0.0)
p2 = FreeCAD.Vector(x2, y1, 0.0)
pntTuples.append((p1, p2))
# Convert end points to lines
for (p1, p2) in pntTuples:
line = Part.makeLine(p1, p2)
GeoSet.append(line)
self.rawGeoList = GeoSet
def _Offset(self):
self.rawGeoList = self._extractOffsetFaces()
def _Spiral(self):
GeoSet = list()
SEGS = list()
draw = True
loopRadians = 0.0 # Used to keep track of complete loops/cycles
sumRadians = 0.0
loopCnt = 0
segCnt = 0
twoPi = 2.0 * math.pi
maxDist = math.ceil(self.cutOut * self._getRadialPasses()) # self.halfDiag
move = self.centerOfPattern # Use to translate the center of the spiral
lastPoint = FreeCAD.Vector(0.0, 0.0, 0.0)
# Set tool properties and calculate cutout
cutOut = self.cutOut / twoPi
segLen = self.obj.SampleInterval.Value # CutterDiameter / 10.0 # SampleInterval.Value
stepAng = segLen / ((loopCnt + 1) * self.cutOut) # math.pi / 18.0 # 10 degrees
stopRadians = maxDist / cutOut
if self.obj.CutPatternReversed:
if self.obj.CutMode == 'Conventional':
getPoint = self._makeOppSpiralPnt
else:
getPoint = self._makeRegSpiralPnt
while draw:
radAng = sumRadians + stepAng
p1 = lastPoint
p2 = getPoint(move, cutOut, radAng) # cutOut is 'b' in the equation r = b * radAng
sumRadians += stepAng # Increment sumRadians
loopRadians += stepAng # Increment loopRadians
if loopRadians > twoPi:
loopCnt += 1
loopRadians -= twoPi
stepAng = segLen / ((loopCnt + 1) * self.cutOut) # adjust stepAng with each loop/cycle
segCnt += 1
lastPoint = p2
if sumRadians > stopRadians:
draw = False
# Create line and show in Object tree
lineSeg = Part.makeLine(p2, p1)
SEGS.append(lineSeg)
# Ewhile
SEGS.reverse()
else:
if self.obj.CutMode == 'Climb':
getPoint = self._makeOppSpiralPnt
else:
getPoint = self._makeRegSpiralPnt
while draw:
radAng = sumRadians + stepAng
p1 = lastPoint
p2 = getPoint(move, cutOut, radAng) # cutOut is 'b' in the equation r = b * radAng
sumRadians += stepAng # Increment sumRadians
loopRadians += stepAng # Increment loopRadians
if loopRadians > twoPi:
loopCnt += 1
loopRadians -= twoPi
stepAng = segLen / ((loopCnt + 1) * self.cutOut) # adjust stepAng with each loop/cycle
segCnt += 1
lastPoint = p2
if sumRadians > stopRadians:
draw = False
# Create line and show in Object tree
lineSeg = Part.makeLine(p1, p2)
SEGS.append(lineSeg)
# Ewhile
# Eif
spiral = Part.Wire([ls.Edges[0] for ls in SEGS])
GeoSet.append(spiral)
self.rawGeoList = GeoSet
def _ZigZag(self):
self._Line() # Use _Line generator
# Support methods
def _getPatternCenter(self):
centerAt = self.obj.PatternCenterAt
if centerAt == 'CenterOfMass':
cntrPnt = FreeCAD.Vector(self.centerOfMass.x, self.centerOfMass.y, 0.0)
elif centerAt == 'CenterOfBoundBox':
cent = self.shape.BoundBox.Center
cntrPnt = FreeCAD.Vector(cent.x, cent.y, 0.0)
elif centerAt == 'XminYmin':
cntrPnt = FreeCAD.Vector(self.shape.BoundBox.XMin, self.shape.BoundBox.YMin, 0.0)
elif centerAt == 'Custom':
cntrPnt = FreeCAD.Vector(self.obj.PatternCenterCustom.x, self.obj.PatternCenterCustom.y, 0.0)
# Update centerOfPattern point
if centerAt != 'Custom':
self.obj.PatternCenterCustom = cntrPnt
self.centerOfPattern = cntrPnt
return cntrPnt
def _getRadialPasses(self):
# recalculate number of passes, if need be
radialPasses = self.halfPasses
if self.obj.PatternCenterAt != 'CenterOfBoundBox':
# make 4 corners of boundbox in XY plane, find which is greatest distance to new circular center
EBB = self.shape.BoundBox
CORNERS = [
FreeCAD.Vector(EBB.XMin, EBB.YMin, 0.0),
FreeCAD.Vector(EBB.XMin, EBB.YMax, 0.0),
FreeCAD.Vector(EBB.XMax, EBB.YMax, 0.0),
FreeCAD.Vector(EBB.XMax, EBB.YMin, 0.0),
]
dMax = 0.0
for c in range(0, 4):
dist = CORNERS[c].sub(self.centerOfPattern).Length
if dist > dMax:
dMax = dist
diag = dMax + (2.0 * self.toolDiam) # Line length to span boundbox diag with 2x cutter diameter extra on each end
radialPasses = math.ceil(diag / self.cutOut) + 1 # Number of lines(passes) required to cover boundbox diagonal
return radialPasses
def _makeRegSpiralPnt(self, move, b, radAng):
x = b * radAng * math.cos(radAng)
y = b * radAng * math.sin(radAng)
return FreeCAD.Vector(x, y, 0.0).add(move)
def _makeOppSpiralPnt(self, move, b, radAng):
x = b * radAng * math.cos(radAng)
y = b * radAng * math.sin(radAng)
return FreeCAD.Vector(-1 * x, y, 0.0).add(move)
def _extractOffsetFaces(self):
PathLog.debug('_extractOffsetFaces()')
wires = list()
shape = self.shape
offset = 0.0 # Start right at the edge of cut area
direction = 0
loop_cnt = 0
def _get_direction(w):
if PathOpTools._isWireClockwise(w):
return 1
return -1
def _reverse_wire(w):
rev_list = list()
for e in w.Edges:
rev_list.append(PathUtils.reverseEdge(e))
rev_list.reverse()
# return Part.Wire(Part.__sortEdges__(rev_list))
return Part.Wire(rev_list)
while True:
offsetArea = PathUtils.getOffsetArea(shape, offset, plane=self.wpc)
if not offsetArea:
# Area fully consumed
break
# set initial cut direction
if direction == 0:
first_face_wire = offsetArea.Faces[0].Wires[0]
direction = _get_direction(first_face_wire)
if self.obj.CutMode == 'Climb':
if direction == 1:
direction = -1
else:
if direction == -1:
direction = 1
# Correct cut direction for `Conventional` cuts
if self.obj.CutMode == 'Conventional':
if loop_cnt == 1:
direction = direction * -1
# process each wire within face
for f in offsetArea.Faces:
wire_cnt = 0
for w in f.Wires:
use_direction = direction
if wire_cnt > 0:
# swap direction for internal features
use_direction = direction * -1
wire_direction = _get_direction(w)
# Process wire
if wire_direction == use_direction:
# direction is correct
wires.append(w)
else:
# incorrect direction, so reverse wire
rw = _reverse_wire(w)
wires.append(rw)
offset -= self.cutOut
loop_cnt += 1
return wires
# Eclass
class ProcessSelectedFaces:
"""ProcessSelectedFaces(JOB, obj) class.
This class processes the `obj.Base` object for selected geometery.
Calling the preProcessModel(module) method returns
two compound objects as a tuple: (FACES, VOIDS) or False."""
def __init__(self, JOB, obj):
self.modelSTLs = list()
self.profileShapes = list()
self.tempGroup = False
self.showDebugObjects = False
self.checkBase = False
self.module = None
self.radius = None
self.depthParams = None
self.msgNoFaces = translate('PathSurfaceSupport',
'Face selection is unavailable for Rotational scans.') + '\n'
self.msgNoFaces += ' ' + translate('PathSurfaceSupport',
'Ignoring selected faces.') + '\n'
self.JOB = JOB
self.obj = obj
self.profileEdges = 'None'
if hasattr(obj, 'ProfileEdges'):
self.profileEdges = obj.ProfileEdges
# Setup STL, model type, and bound box containers for each model in Job
for m in range(0, len(JOB.Model.Group)):
self.modelSTLs.append(False)
self.profileShapes.append(False)
# make circle for workplane
self.wpc = Part.makeCircle(2.0)
def PathSurface(self):
if self.obj.Base:
if len(self.obj.Base) > 0:
self.checkBase = True
if self.obj.ScanType == 'Rotational':
self.checkBase = False
FreeCAD.Console.PrintWarning(self.msgNoFaces)
def PathWaterline(self):
if self.obj.Base:
if len(self.obj.Base) > 0:
self.checkBase = True
if self.obj.Algorithm in ['OCL Dropcutter', 'Experimental']:
self.checkBase = False
FreeCAD.Console.PrintWarning(self.msgNoFaces)
# public class methods
def setShowDebugObjects(self, grpObj, val):
self.tempGroup = grpObj
self.showDebugObjects = val
def preProcessModel(self, module):
PathLog.debug('preProcessModel()')
if not self._isReady(module):
return False
FACES = list()
VOIDS = list()
fShapes = list()
vShapes = list()
GRP = self.JOB.Model.Group
lenGRP = len(GRP)
proceed = False
# Crete place holders for each base model in Job
for m in range(0, lenGRP):
FACES.append(False)
VOIDS.append(False)
fShapes.append(False)
vShapes.append(False)
# The user has selected subobjects from the base. Pre-Process each.
if self.checkBase:
PathLog.debug(' -obj.Base exists. Pre-processing for selected faces.')
(hasFace, hasVoid) = self._identifyFacesAndVoids(FACES, VOIDS) # modifies FACES and VOIDS
hasGeometry = True if hasFace or hasVoid else False
# Cycle through each base model, processing faces for each
for m in range(0, lenGRP):
base = GRP[m]
(mFS, mVS, mPS) = self._preProcessFacesAndVoids(base, FACES[m], VOIDS[m])
fShapes[m] = mFS
vShapes[m] = mVS
self.profileShapes[m] = mPS
if mFS or mVS:
proceed = True
if hasGeometry and not proceed:
return False
else:
PathLog.debug(' -No obj.Base data.')
for m in range(0, lenGRP):
self.modelSTLs[m] = True
# Process each model base, as a whole, as needed
for m in range(0, lenGRP):
if self.modelSTLs[m] and not fShapes[m]:
PathLog.debug(' -Pre-processing {} as a whole.'.format(GRP[m].Label))
if self.obj.BoundBox == 'BaseBoundBox':
base = GRP[m]
elif self.obj.BoundBox == 'Stock':
base = self.JOB.Stock
pPEB = self._preProcessEntireBase(base, m)
if pPEB is False:
msg = translate('PathSurfaceSupport',
'Failed to pre-process base as a whole.') + '\n'
FreeCAD.Console.PrintError(msg)
else:
(fcShp, prflShp) = pPEB
if fcShp:
if fcShp is True:
PathLog.debug(' -fcShp is True.')
fShapes[m] = True
else:
fShapes[m] = [fcShp]
if prflShp:
if fcShp:
PathLog.debug('vShapes[{}]: {}'.format(m, vShapes[m]))
if vShapes[m]:
PathLog.debug(' -Cutting void from base profile shape.')
adjPS = prflShp.cut(vShapes[m][0])
self.profileShapes[m] = [adjPS]
else:
PathLog.debug(' -vShapes[m] is False.')
self.profileShapes[m] = [prflShp]
else:
PathLog.debug(' -Saving base profile shape.')
self.profileShapes[m] = [prflShp]
PathLog.debug('self.profileShapes[{}]: {}'.format(m, self.profileShapes[m]))
# Efor
return (fShapes, vShapes)
# private class methods
def _isReady(self, module):
'''_isReady(module)... Internal method.
Checks if required attributes are available for processing obj.Base (the Base Geometry).'''
PathLog.debug('ProcessSelectedFaces _isReady({})'.format(module))
if hasattr(self, module):
self.module = module
modMethod = getattr(self, module) # gets the attribute only
modMethod() # executes as method
else:
PathLog.error('PSF._isReady() no "{}" method.'.format(module))
return False
if not self.radius:
PathLog.error('PSF._isReady() no cutter radius available.')
return False
if not self.depthParams:
PathLog.error('PSF._isReady() no depth params available.')
return False
return True
def _identifyFacesAndVoids(self, F, V):
TUPS = list()
GRP = self.JOB.Model.Group
lenGRP = len(GRP)
hasFace = False
hasVoid = False
# Separate selected faces into (base, face) tuples and flag model(s) for STL creation
for (bs, SBS) in self.obj.Base:
for sb in SBS:
# Flag model for STL creation
mdlIdx = None
for m in range(0, lenGRP):
if bs is GRP[m]:
self.modelSTLs[m] = True
mdlIdx = m
break
TUPS.append((mdlIdx, bs, sb)) # (model idx, base, sub)
# Apply `AvoidXFaces` value
faceCnt = len(TUPS)
add = faceCnt - self.obj.AvoidLastX_Faces
for bst in range(0, faceCnt):
(m, base, sub) = TUPS[bst]
shape = getattr(base.Shape, sub)
if isinstance(shape, Part.Face):
faceIdx = int(sub[4:]) - 1
if bst < add:
if F[m] is False:
F[m] = list()
F[m].append((shape, faceIdx))
PathLog.debug('.. Cutting {}'.format(sub))
hasFace = True
else:
if V[m] is False:
V[m] = list()
V[m].append((shape, faceIdx))
PathLog.debug('.. Avoiding {}'.format(sub))
hasVoid = True
return (hasFace, hasVoid)
def _preProcessFacesAndVoids(self, base, FCS, VDS):
mFS = False
mVS = False
mPS = False
mIFS = list()
if FCS:
isHole = False
if self.obj.HandleMultipleFeatures == 'Collectively':
cont = True
PathLog.debug(
'Attempting to get cross-section of collective faces.')
outFCS, ifL = self.findUnifiedRegions(FCS)
if self.obj.InternalFeaturesCut and ifL:
ifL = list() # clear avoid shape list
if len(outFCS) == 0:
msg = translate(
'PathSurfaceSupport',
'Cannot process selected faces. Check horizontal '
'surface exposure.')
FreeCAD.Console.PrintError(msg + '\n')
cont = False
else:
cfsL = Part.makeCompound(outFCS)
# Handle profile edges request
if cont and self.profileEdges != 'None':
PathLog.debug('.. include Profile Edge')
ofstVal = self._calculateOffsetValue(isHole)
psOfst = PathUtils.getOffsetArea(cfsL,
ofstVal,
plane=self.wpc)
if psOfst:
mPS = [psOfst]
if self.profileEdges == 'Only':
mFS = True
cont = False
else:
cont = False
if cont:
if self.showDebugObjects:
T = FreeCAD.ActiveDocument.addObject('Part::Feature', 'tmpCollectiveShape')
T.Shape = cfsL
T.purgeTouched()
self.tempGroup.addObject(T)
ofstVal = self._calculateOffsetValue(isHole)
faceOfstShp = PathUtils.getOffsetArea(
cfsL, ofstVal, plane=self.wpc)
if not faceOfstShp:
msg = translate('PathSurfaceSupport',
'Failed to create offset face.') + '\n'
FreeCAD.Console.PrintError(msg)
cont = False
if cont:
lenIfL = len(ifL)
if not self.obj.InternalFeaturesCut:
if lenIfL == 0:
PathLog.debug(' -No internal features saved.')
else:
if lenIfL == 1:
casL = ifL[0]
else:
casL = Part.makeCompound(ifL)
if self.showDebugObjects:
C = FreeCAD.ActiveDocument.addObject('Part::Feature', 'tmpCompoundIntFeat')
C.Shape = casL
C.purgeTouched()
self.tempGroup.addObject(C)
ofstVal = self._calculateOffsetValue(isHole=True)
intOfstShp = PathUtils.getOffsetArea(
casL, ofstVal, plane=self.wpc)
mIFS.append(intOfstShp)
mFS = [faceOfstShp]
# Eif
elif self.obj.HandleMultipleFeatures == 'Individually':
for (fcshp, fcIdx) in FCS:
cont = True
fNum = fcIdx + 1
outerFace = False
gUR, ifL = self.findUnifiedRegions(FCS)
if len(gUR) > 0:
outerFace = gUR[0]
if self.obj.InternalFeaturesCut:
ifL = list() # avoid shape list
if outerFace:
PathLog.debug('Attempting to create offset face of Face{}'.format(fNum))
if self.profileEdges != 'None':
ofstVal = self._calculateOffsetValue(isHole)
psOfst = PathUtils.getOffsetArea(
outerFace, ofstVal, plane=self.wpc)
if psOfst:
if mPS is False:
mPS = list()
mPS.append(psOfst)
if self.profileEdges == 'Only':
if mFS is False:
mFS = list()
mFS.append(True)
cont = False
else:
cont = False
if cont:
ofstVal = self._calculateOffsetValue(isHole)
faceOfstShp = PathUtils.getOffsetArea(
outerFace, ofstVal, plane=self.wpc)
lenIfl = len(ifL)
if self.obj.InternalFeaturesCut is False and lenIfl > 0:
if lenIfl == 1:
casL = ifL[0]
else:
casL = Part.makeCompound(ifL)
ofstVal = self._calculateOffsetValue(isHole=True)
intOfstShp = PathUtils.getOffsetArea(
casL, ofstVal, plane=self.wpc)
mIFS.append(intOfstShp)
# faceOfstShp = faceOfstShp.cut(intOfstShp)
if mFS is False:
mFS = list()
mFS.append(faceOfstShp)
# Eif
# Efor
# Eif
# Eif
if len(mIFS) > 0:
if mVS is False:
mVS = list()
for ifs in mIFS:
mVS.append(ifs)
if VDS:
PathLog.debug('Processing avoid faces.')
cont = True
isHole = False
outFCS, intFEAT = self.findUnifiedRegions(VDS)
if self.obj.InternalFeaturesCut:
intFEAT = list()
lenOtFcs = len(outFCS)
if lenOtFcs == 0:
cont = False
else:
if lenOtFcs == 1:
avoid = outFCS[0]
else:
avoid = Part.makeCompound(outFCS)
if self.showDebugObjects:
P = FreeCAD.ActiveDocument.addObject('Part::Feature', 'tmpVoidEnvelope')
P.Shape = avoid
P.purgeTouched()
self.tempGroup.addObject(P)
if cont:
if self.showDebugObjects:
P = FreeCAD.ActiveDocument.addObject('Part::Feature', 'tmpVoidCompound')
P.Shape = avoid
P.purgeTouched()
self.tempGroup.addObject(P)
ofstVal = self._calculateOffsetValue(isHole, isVoid=True)
avdOfstShp = PathUtils.getOffsetArea(avoid,
ofstVal,
plane=self.wpc)
if avdOfstShp is False:
msg = translate('PathSurfaceSupport',
'Failed to create collective offset avoid face.')
FreeCAD.Console.PrintError(msg + '\n')
cont = False
if cont:
avdShp = avdOfstShp
if not self.obj.AvoidLastX_InternalFeatures and len(intFEAT) > 0:
if len(intFEAT) > 1:
ifc = Part.makeCompound(intFEAT)
else:
ifc = intFEAT[0]
ofstVal = self._calculateOffsetValue(isHole=True)
ifOfstShp = PathUtils.getOffsetArea(ifc,
ofstVal,
plane=self.wpc)
if ifOfstShp is False:
msg = translate('PathSurfaceSupport',
'Failed to create collective offset avoid internal features.') + '\n'
FreeCAD.Console.PrintError(msg)
else:
avdShp = avdOfstShp.cut(ifOfstShp)
if mVS is False:
mVS = list()
mVS.append(avdShp)
return (mFS, mVS, mPS)
def _preProcessEntireBase(self, base, m):
cont = True
isHole = False
prflShp = False
# Create envelope, extract cross-section and make offset co-planar shape
# baseEnv = PathUtils.getEnvelope(base.Shape, subshape=None, depthparams=self.depthParams)
try:
baseEnv = PathUtils.getEnvelope(partshape=base.Shape, subshape=None, depthparams=self.depthParams) # Produces .Shape
except Exception as ee:
PathLog.error(str(ee))
shell = base.Shape.Shells[0]
solid = Part.makeSolid(shell)
try:
baseEnv = PathUtils.getEnvelope(partshape=solid, subshape=None, depthparams=self.depthParams) # Produces .Shape
except Exception as eee:
PathLog.error(str(eee))
cont = False
if cont:
csFaceShape = getShapeSlice(baseEnv)
if csFaceShape is False:
csFaceShape = getCrossSection(baseEnv)
if csFaceShape is False:
csFaceShape = getSliceFromEnvelope(baseEnv)
if csFaceShape is False:
PathLog.debug('Failed to slice baseEnv shape.')
cont = False
if cont and self.profileEdges != 'None':
PathLog.debug(' -Attempting profile geometry for model base.')
ofstVal = self._calculateOffsetValue(isHole)
psOfst = PathUtils.getOffsetArea(csFaceShape,
ofstVal,
plane=self.wpc)
if psOfst:
if self.profileEdges == 'Only':
return (True, psOfst)
prflShp = psOfst
else:
cont = False
if cont:
ofstVal = self._calculateOffsetValue(isHole)
faceOffsetShape = PathUtils.getOffsetArea(csFaceShape, ofstVal,
plane=self.wpc)
if faceOffsetShape is False:
PathLog.debug('getOffsetArea() failed for entire base.')
else:
faceOffsetShape.translate(FreeCAD.Vector(0.0, 0.0, 0.0 - faceOffsetShape.BoundBox.ZMin))
return (faceOffsetShape, prflShp)
return False
def _calculateOffsetValue(self, isHole, isVoid=False):
'''_calculateOffsetValue(self.obj, isHole, isVoid) ... internal function.
Calculate the offset for the Path.Area() function.'''
self.JOB = PathUtils.findParentJob(self.obj)
# We need to offset by at least our linear tessellation deflection
# (default GeometryTolerance / 4) to avoid false retracts at the
# boundaries.
tolrnc = max(self.JOB.GeometryTolerance.Value / 10.0,
self.obj.LinearDeflection.Value)
if isVoid is False:
if isHole is True:
offset = -1 * self.obj.InternalFeaturesAdjustment.Value
offset += self.radius + tolrnc
else:
offset = -1 * self.obj.BoundaryAdjustment.Value
if self.obj.BoundaryEnforcement is True:
offset += self.radius + tolrnc
else:
offset -= self.radius + tolrnc
offset = 0.0 - offset
else:
offset = -1 * self.obj.BoundaryAdjustment.Value
offset += self.radius + tolrnc
return offset
def findUnifiedRegions(
self,
shapeAndIndexTuples,
useAreaImplementation=True):
"""Wrapper around area and wire based region unification
implementations."""
PathLog.debug('findUnifiedRegions()')
# Allow merging of faces within the LinearDeflection tolerance.
tolerance = self.obj.LinearDeflection.Value
# Default: normal to Z=1 (XY plane), at Z=0
try:
# Use Area based implementation
shapes = Part.makeCompound([t[0] for t in shapeAndIndexTuples])
outlineShape = PathUtils.getOffsetArea(
shapes,
# Make the outline very slightly smaller, to avoid creating
# small edges in the cut with the hole-preserving projection.
0.0 - tolerance / 10,
removeHoles=True, # Outline has holes filled in
tolerance=tolerance,
plane=self.wpc)
projectionShape = PathUtils.getOffsetArea(
shapes,
# Make the projection very slightly larger
tolerance / 10,
removeHoles=False, # Projection has holes preserved
tolerance=tolerance,
plane=self.wpc)
internalShape = outlineShape.cut(projectionShape)
# Filter out tiny faces, usually artifacts around the perimeter of
# the cut.
minArea = (10 * tolerance)**2
internalFaces = [
f for f in internalShape.Faces if f.Area > minArea
]
if internalFaces:
internalFaces = Part.makeCompound(internalFaces)
return ([outlineShape], [internalFaces])
except Exception as e:
PathLog.warning(
"getOffsetArea failed: {}; Using FindUnifiedRegions.".format(
e))
# Use face-unifying class
FUR = FindUnifiedRegions(shapeAndIndexTuples, tolerance)
if self.showDebugObjects:
FUR.setTempGroup(self.tempGroup)
return (FUR.getUnifiedRegions(), FUR.getInternalFeatures)
# Eclass
# Functions for getting a shape envelope and cross-section
def getExtrudedShape(wire):
PathLog.debug('getExtrudedShape()')
wBB = wire.BoundBox
extFwd = math.floor(2.0 * wBB.ZLength) + 10.0
try:
shell = wire.extrude(FreeCAD.Vector(0.0, 0.0, extFwd))
except Exception as ee:
PathLog.error(' -extrude wire failed: \n{}'.format(ee))
return False