-
Notifications
You must be signed in to change notification settings - Fork 7
/
spb_Brep_repairWizard.py
1815 lines (1383 loc) · 63.8 KB
/
spb_Brep_repairWizard.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
"""
160705-160728: Created.
...
191022-1121: Rewritten with major updates. Removed most of the previous revision notes.
191213: Import-related update.
200129: Added JoinNakedEdges.
200130: Now maximum edge tolerance is used for finding matching bounding boxes from split.
Added routine to remove slits from faces.
Now rebuilds edges of remaining brep before extracting those to be rebuilt.
200202-24: Further development.
200313-14: Printed feedback change.
200319, 0520,21, 26, 0619, 0701,29, 1211: Import-related update.
210122: Bug fixes.
210426, 220118, 220315
220317: Imported a function. Import-related update.
TODO:
Continuing replacing xBrepFace_trimToNakedEdges with other modules.
Add variable for correctEdgeTols?
"""
import Rhino
import Rhino.DocObjects as rd
import Rhino.Geometry as rg
import Rhino.Input as ri
import rhinoscriptsyntax as rs
import scriptcontext as sc
from System import Guid
from System.Diagnostics import Stopwatch
from System.Drawing import Color
import Eto.Drawing as drawing
import Eto.Forms as forms
import xBrep_correctEdgeTolerances
import xBrep_edgeDeviations
import xBrep_facesWithShortBorderLength
import xBrep_findFaceByBorderBoundingBox
import xBrep_invalid
import xBrep_join
import xBrep_nakedEdgeLoop
import xBrep_rebuildEdges
import spb_Brep_sliverFaces
import xBrep_smallAreaFaces
import xBrep_splitSurfaceWithCurves
import xBrepObject
import xCurve
import xSurface
stopwatch = Stopwatch() # Will just use the same instance for all tests.
class Opts:
data = (
('sBrepSelPool', 'Selection',
('All normal srfs/polysrfs ', 'Selection',)),
('bRetrim_Bad', True, 'and retrim',),
('bFind_SlowArea', True, 'Area compute time (seconds) > ',),
('fSeconds_forArea', 1.0, ''),
('bCorrectETols', True, 'Correct edge tol. error > (% of absolute tol.)'),
('fPercent_EdgeTolMismatchTol', 100.0,''),
('bRemoveSlits', True, 'Remove single-edged slits'),
('bRebuildEs_perETol', True, 'Rebuild edges whose deviation > '),
('fTol_EdgeForRebuild', 1.0*sc.doc.ModelAbsoluteTolerance,''),
('bShrinkBeforeUntrim', True, 'Shrink surfaces before trimming',),
('bDelSmall', True, 'Delete faces < ',),
('fTol_Small', 2.0*sc.doc.ModelAbsoluteTolerance, ''),
('bJoin', True, 'Join breps',),
('fTol_EdgeForJoin', 2.0*sc.doc.ModelAbsoluteTolerance, 'Tolerance '),
('bRetrim_GoodMonoface', False, 'Retrim good monofaces remaining after initial join'),
('bMergeEdges', True, 'Merge all edges if solid result',),
('bDebug', False, 'Debug mode',),
)
# TODO: Add to list?
# 'All in document' to 'sBrepSelPool'
# ('bSlitEdge', True, 'Coincident non-seam edges (slits)'),
keys = []
values = {}
sDialogTexts = {}
stickyKeys = {}
for key, value, text in data:
if key[0] == 'b':
values[key] = value
sDialogTexts[key] = text
stickyKeys[key] = '{}({})'.format(key, __file__)
elif key[0] == 's':
values[key] = value
sDialogTexts[key] = text
stickyKeys[key] = '{}({})'.format(key, __file__)
elif key[0] == 'f':
values[key] = value
sDialogTexts[key] = text
stickyKeys[key] = '{}({})({})'.format(key, __file__, sc.doc.Name)
else:
print "{} not supported.".format(key)
continue
keys.append(key)
class RepairBrepDialog(forms.Dialog[bool]):
def __init__(self):
# Load sticky.
for key in Opts.stickyKeys:
if Opts.stickyKeys[key] in sc.sticky:
Opts.values[key] = sc.sticky[Opts.stickyKeys[key]]
# Initialize dialog box
self.Title = 'Repair Brep (Surface and/or Polysurface)'
self.Padding = drawing.Padding(10)
self.Resizable = False
self.divider = forms.Label()
#self.divider.Text = ''
self.divider.Height = 2
self.divider.BackgroundColor = drawing.Colors.Gray
self.radioButtonList = {}
self.checkBoxes = {}
self.labels = {}
self.textBoxes = {}
for key in Opts.keys:
if key[0] == 'b':
self.checkBoxes[key] = forms.CheckBox(Text=Opts.sDialogTexts[key])
self.checkBoxes[key].Checked = Opts.values[key]
elif key[0] == 's':
self.radioButtonList[key] = forms.RadioButtonList()
self.radioButtonList[key].DataStore = Opts.sDialogTexts[key]
self.radioButtonList[key].SelectedIndex = Opts.sDialogTexts[key].index(Opts.values[key])
if key[0] == 'f':
self.labels[key] = forms.Label(Text=Opts.sDialogTexts[key])
self.textBoxes[key] = forms.TextBox(Text=str(Opts.values[key]))
self.checkBoxes['bFind_SlowArea'].CheckedChanged += self.onChange_bSlowArea
self.textBoxes['fSeconds_forArea'].TextChanged += self.onChange_fSeconds_forArea
self.checkBoxes['bRebuildEs_perETol'].CheckedChanged += self.onChange_bRebuildEs_perETol
self.textBoxes['fTol_EdgeForRebuild'].TextChanged += self.onChange_fTol_EdgeForRetrim
self.checkBoxes['bDelSmall'].CheckedChanged += self.onChange_bDelSmall
self.textBoxes['fTol_Small'].TextChanged += self.onChange_fTol_Small
self.checkBoxes['bJoin'].CheckedChanged += self.onChange_bJoin
self.textBoxes['fTol_EdgeForJoin'].TextChanged += self.onChange_fTol_EdgeForJoin
self.DefaultButton = forms.Button(Text = 'OK')
self.DefaultButton.Click += self.onOkButtonClick
self.AbortButton = forms.Button(Text = 'Cancel')
self.AbortButton.Click += self.onCancelButtonClick
layout = forms.DynamicLayout()
layout.Spacing = drawing.Size(5, 5)
#layout.AddSeparateRow()
key = 'sBrepSelPool'
self.radioButtonList[key].Orientation = forms.Orientation.Horizontal
layout.AddSeparateRow("Process: ", self.radioButtonList[key])
layout.AddSeparateRow("")
layout.AddSeparateRow("Extract ", self.checkBoxes['bRetrim_Bad'], ":")
dummyCB = forms.CheckBox(Text="Invalid")
dummyCB.Checked = True
dummyCB.Enabled = False
layout.AddSeparateRow(dummyCB)
dummyCB = forms.CheckBox(Text="Whose area cannot be computed")
dummyCB.Checked = True
dummyCB.Enabled = False
layout.AddSeparateRow(dummyCB)
layout.AddSeparateRow(self.checkBoxes['bFind_SlowArea'], None,
self.textBoxes['fSeconds_forArea'])
layout.AddSeparateRow("")
layout.AddSeparateRow("Additional actions:")
layout.AddSeparateRow(self.checkBoxes['bCorrectETols'], None,
self.textBoxes['fPercent_EdgeTolMismatchTol'])
layout.AddSeparateRow(self.checkBoxes['bRemoveSlits'])
layout.AddSeparateRow(self.checkBoxes['bRebuildEs_perETol'], None,
self.textBoxes['fTol_EdgeForRebuild'])
#layout.AddRow(self.checkBoxes['bShrinkBeforeUntrim'])
layout.AddSeparateRow(self.checkBoxes['bDelSmall'], None,
self.textBoxes['fTol_Small'])
layout.AddSeparateRow(self.checkBoxes['bJoin'], None,
"Tolerance: ",
self.textBoxes['fTol_EdgeForJoin'])
layout.AddSeparateRow(None, self.checkBoxes['bRetrim_GoodMonoface'],None)
layout.AddSeparateRow("")
layout.AddSeparateRow(self.checkBoxes['bDebug'])
layout.AddSeparateRow(None, self.DefaultButton, None, self.AbortButton, None)
#layout.AddRow(self.okButton, self.cancelButton)
# Set the dialog content
self.Content = layout
def onChange_bSlowArea(self, sender, e):
self.textBoxes['fSeconds_forArea'].Enabled = self.checkBoxes['bFind_SlowArea'].Checked
def onChange_fSeconds_forArea(self, sender, e):
try:
float(self.textBoxes['fSeconds_forArea'].Text)
self.textBoxes['fSeconds_forArea'].BackgroundColor = drawing.SystemColors.ControlBackground
except:
self.textBoxes['fSeconds_forArea'].BackgroundColor = drawing.Colors.Red
def onChange_bRebuildEs_perETol(self, sender, e):
self.textBoxes['fTol_EdgeForRebuild'].Enabled = self.checkBoxes['bRebuildEs_perETol'].Checked
def onChange_fTol_EdgeForRetrim(self, sender, e):
try:
float(self.textBoxes['fTol_EdgeForRebuild'].Text)
self.textBoxes['fTol_EdgeForRebuild'].BackgroundColor = drawing.SystemColors.ControlBackground
except:
self.textBoxes['fTol_EdgeForRebuild'].BackgroundColor = drawing.Colors.Red
def onChange_bDelSmall(self, sender, e):
self.textBoxes['fTol_Small'].Enabled = self.checkBoxes['bDelSmall'].Checked
def onChange_fTol_Small(self, sender, e):
try:
float(self.textBoxes['fTol_Small'].Text)
self.textBoxes['fTol_Small'].BackgroundColor = drawing.SystemColors.ControlBackground
except:
self.textBoxes['fTol_Small'].BackgroundColor = drawing.Colors.Red
def onChange_bJoin(self, sender, e):
self.textBoxes['fTol_EdgeForJoin'].Enabled = self.checkBoxes['bJoin'].Checked
def onChange_fTol_EdgeForJoin(self, sender, e):
try:
float(self.textBoxes['fTol_EdgeForJoin'].Text)
self.textBoxes['fTol_EdgeForJoin'].BackgroundColor = drawing.SystemColors.ControlBackground
except:
self.textBoxes['fTol_EdgeForJoin'].BackgroundColor = drawing.Colors.Red
def onCancelButtonClick(self, sender, e):
self.Close(False)
def onOkButtonClick(self, sender, e):
# Save values.
for key in Opts.keys:
if key in self.checkBoxes:
Opts.values[key] = self.checkBoxes[key].Checked
elif key in self.radioButtonList:
Opts.values[key] = (
Opts.sDialogTexts[key][self.radioButtonList[key].SelectedIndex]
)
elif key in self.textBoxes:
try:
Opts.values[key] = float(self.textBoxes[key].Text)
except:
print "Invalid input for tolerance." \
" {} will be used instead.".format(Opts.values[key])
# Save sticky.
for key in Opts.keys:
if key in Opts.stickyKeys:
sc.sticky[Opts.stickyKeys[key]] = Opts.values[key]
self.Close(True)
def getInput():
go = ri.Custom.GetObject()
go.SetCommandPrompt("Select breps")
go.GeometryFilter = rd.ObjectType.Brep
# optD_Overlap_MinAllowed = ri.Custom.OptionDouble(
# fOverlap_MinAllowed, True, Rhino.RhinoMath.ZeroTolerance)
# optT_AddDots = ri.Custom.OptionToggle(bAddDot, 'No', 'Yes')
# optI_DotSize = ri.Custom.OptionInteger(iDotHeight, True, 3)
# optT_Extract = ri.Custom.OptionToggle(bExtract, 'No', 'Yes')
# go.AddOptionDouble('MinimumEdgeOverlapAllowed', optD_Overlap_MinAllowed)
# go.AddOptionToggle('AddTextDots', optT_AddDots)
# if optT_AddDots.CurrentValue:
# go.AddOptionInteger('TextDotHeight', optI_DotSize)
# go.AddOptionToggle('ExtractFaces', optT_Extract)
go.EnableClearObjectsOnEntry(False)
go.AlreadySelectedObjectSelect = True
go.DeselectAllBeforePostSelect = False
go.EnableUnselectObjectsOnExit(False)
go.SubObjectSelect = False
# go.AcceptNumber(True, False)
while True:
res = go.GetMultiple(minimumNumber=1, maximumNumber=0)
if res == ri.GetResult.Cancel:
go.Dispose()
return
elif res == ri.GetResult.Object:
objrefs = go.Objects()
go.Dispose()
return objrefs
def processBrepObjects(rdBreps, **kwargs):
"""
"""
gBreps = {} # Placed here so it can be found more easily in debugger.
def getOpt(key): return kwargs[key] if key in kwargs else Opts.values[key]
bRetrim_Bad = getOpt('bRetrim_Bad')
bFind_SlowArea = getOpt('bFind_SlowArea')
fSeconds_forArea = getOpt('fSeconds_forArea')
bCorrectETols = getOpt('bCorrectETols')
fPercent_EdgeTolMismatchTol = getOpt('fPercent_EdgeTolMismatchTol')
bRemoveSlits = getOpt('bRemoveSlits')
bRebuildEs_perETol = getOpt('bRebuildEs_perETol')
fTol_EdgeForRebuild = getOpt('fTol_EdgeForRebuild')
fTol_EdgeForJoin = getOpt('fTol_EdgeForJoin')
bShrinkBeforeUntrim = getOpt('bShrinkBeforeUntrim')
bDelSmall = getOpt('bDelSmall')
fTol_Small = getOpt('fTol_Small')
bJoin = getOpt('bJoin')
bRetrim_GoodMonoface = getOpt('bRetrim_GoodMonoface')
bMergeEdges = getOpt('bMergeEdges')
bDebug = getOpt('bDebug')
def coerceList(obj):
try: out = list(set(obj))
except: out = [obj]
return out
def coerceSurface(rhObj):
if isinstance(rhObj, rg.Surface):
return rhObj
elif isinstance(rhObj, rg.GeometryBase):
geom = rhObj
elif isinstance(rhObj, rd.ObjRef):
#print rhObj.GeometryComponentIndex.ComponentIndexType
geom = rhObj.Geometry()
elif isinstance(rhObj, Guid):
rdObj = sc.doc.Objects.FindId(rhObj) if Rhino.RhinoApp.ExeVersion >= 6 else sc.doc.Objects.Find(rhObj)
geom = rdObj.Geometry
else:
return
srf = None
if isinstance(geom, rg.BrepFace):
srf = geom.UnderlyingSurface()
elif isinstance(geom, rg.Surface):
srf = geom
elif isinstance(geom, rg.Brep):
if geom.Faces.Count == 1:
srf = geom.Faces[0].UnderlyingSurface()
return srf
def getBrepGeom(rhObj):
if isinstance(rhObj, rg.GeometryBase):
geom = rhObj
guid = None
elif isinstance(rhObj, rd.ObjRef):
geom = rhObj.Geometry()
guid = rhObj.ObjectId
elif isinstance(rhObj, Guid):
rdObj = sc.doc.Objects.FindId(rhObj) if Rhino.RhinoApp.ExeVersion >= 6 else sc.doc.Objects.Find(rhObj)
if rdObj is None:
print rhObj
pass
geom = rdObj.Geometry
guid = rdObj.Id
elif isinstance(rhObj, rd.BrepObject):
rdObj = rhObj
geom = rdObj.Geometry
guid = rdObj.Id
else:
return
if not isinstance(geom, rg.Brep):
print "Not a brep: {}".format(guid)
return
return geom
def coerceRhinoObject(rhObj):
"""
'Deleted objects cannot be found by id.'
(https://developer.rhino3d.com/api/RhinoCommon/html/M_Rhino_DocObjects_Tables_ObjectTable_FindId.htm)
"""
rdObj = None
if isinstance(rhObj, rd.RhinoObject):
rdObj = rhObj
elif isinstance(rhObj, rd.ObjRef):
rdObj = rhObj.Object()
elif isinstance(rhObj, Guid):
rdObj = sc.doc.Objects.FindId(rhObj) if Rhino.RhinoApp.ExeVersion >= 6 else sc.doc.Objects.Find(rhObj)
return rdObj
def coerceBrepObject(rhObj):
rdObj = coerceRhinoObject(rhObj)
if rdObj and (rdObj.ObjectType == rd.ObjectType.Brep):
return rdObj
def cleanBrepList(toClean, alsoRemove=None):
"""
Recreates list of GUIDS with dict key of toClean
without duplicates, deleted breps, breps in dict key of alsoRemove.
"""
# Remove duplicates.
gBreps[toClean] = list(set(gBreps[toClean]))
# Remove GUIDs of deleted Breps.
# None from coerceBrepObject means that the Brep was deleted.
gBreps[toClean] = [gB for gB in gBreps[toClean] if coerceBrepObject(gB) is not None]
# Remove any GUIDs found in gBreps[alsoRemove].
if alsoRemove and gBreps[alsoRemove]:
gBreps[toClean] = [gB for gB in gBreps[toClean] if gB not in gBreps[alsoRemove]]
def getGuidsToProcess(rdBreps):
gBs = []
len_rhBs0 = len(rdBreps)
idxs_AtTenths = [int(round(0.1*i*len_rhBs0,0)) for i in range(10)]
for iB, rdObj_Brep in enumerate(rdBreps):
if sc.escape_test(False):
print "Searching interrupted by user."
return
if len_rhBs0 > 10:
if iB in idxs_AtTenths:
Rhino.RhinoApp.SetCommandPrompt(
"Processed {:d}% of {} breps ...".format(
int(100.0 * (iB+1) / len_rhBs0), len_rhBs0))
elif len_rhBs0 > 1:
Rhino.RhinoApp.SetCommandPrompt(
"Processing {} of {} breps ...".format(
iB+1, len_rhBs0))
else:
Rhino.RhinoApp.SetCommandPrompt("Processing single brep ...")
rdBrep0 = coerceBrepObject(rdObj_Brep)
if not rdBrep0:
print "Non-brep DocObject passed to processBrepObjects."
continue
gBs.append(rdBrep0.Id)
return gBs
def colorRed(gObjs):
gObjs = coerceList(gObjs)
for gObj in gObjs:
rdObj = coerceRhinoObject(gObj)
attr = rdObj.Attributes
attr.ColorSource = rd.ObjectColorSource.ColorFromObject
attr.ObjectColor = Color.Red
rdObj.CommitChanges()
def formatDistance(fDistance):
if fDistance is None: return "(No deviation provided)"
if fDistance < 0.001:
return "{:.2e}".format(fDistance)
else:
return "{:.{}f}".format(fDistance, sc.doc.ModelDistanceDisplayPrecision)
def removeMicroEdges(searchUs):
sc.escape_test()
if bEchoCmdPrompt:
sCmdPrompt0 = "Removing micro edges ..."
Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
sc.doc.Views.RedrawEnabled = False
for gBrep in gBreps[searchUs] if isinstance(searchUs, str) else searchUs:
sc.doc.Objects.Select(gBrep)
Rhino.RhinoApp.RunScript("_NoEcho _RemoveAllNakedMicroEdges _Echo", echo=False)
sc.doc.Objects.UnselectAll()
sc.doc.Views.RedrawEnabled = True
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0 + " done.")
def extractInvalidFaces(keySearchUs, keyExtracted):
if bEchoCmdPrompt:
sCmdPrompt0 = "Searching for invalid faces ..."
Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
sc.escape_test()
if keyExtracted not in gBreps: gBreps[keyExtracted] = []
rc = xBrep_invalid.extractBadFaces(
gBreps[keySearchUs],
bEcho=bDebug,
bDebug=bDebug)
if not rc:
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0 + " done.")
return
gBs_Bad, gBs_Good = rc
# In case a micro edge is the problem.
for gBrep in gBs_Bad:
removeMicroEdges(gBs_Bad)
for i in reversed(range(len(gBs_Bad))):
if xBrep_invalid.isValid(gBs_Bad[i]):
gBs_Good.append(gBs_Bad[i])
del gBs_Bad[i]
print "MicroEdge(s) found" \
" after extracting invalid faces." \
" Moved Good brep from Bad list to Good."
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
if bDebug:
print "extractInvalidFaces:" \
" len(extracted) len(remaining): {}, {}".format(
len(gBs_Bad), len(gBs_Good))
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
if len(gBs_Bad) or bDebug:
print "{} invalid faces found in {} {} breps.".format(
len(gBs_Bad), len(gBreps[keySearchUs]), keySearchUs)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
if gBs_Bad:
gBreps[keyExtracted].extend(gBs_Bad)
gBreps[keySearchUs].extend(gBs_Good)
cleanBrepList(keyExtracted)
cleanBrepList(keySearchUs, keyExtracted)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0 + " done.")
def correctEdgeTols(keySearchUs):
if bEchoCmdPrompt:
sCmdPrompt0 = "Searching for edges" \
" whose tolerances don't match their actual edge deviations ..."
Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
sc.escape_test()
iCt_Removed = 0
gCorrected = xBrep_correctEdgeTolerances.processBrepObjects(
gBreps[keySearchUs],
fPercentOfMAT=fPercent_EdgeTolMismatchTol,
bAddDot=False,
bEcho=False,
bDebug=bDebug,
)
if len(gCorrected) or bDebug:
s = "{} out of {} {} breps".format(
len(gCorrected), len(gBreps[keySearchUs]), keySearchUs)
s += " had some edge tolerances that were corrected."
print s
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0 + " done.")
def removeSlitsFromFaces(keySearchUs):
if bEchoCmdPrompt:
sCmdPrompt0 = "Searching for faces containing slit trims ..."
Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
sc.escape_test()
iCt_Removed = 0
for gB in gBreps[keySearchUs]:
rgB = getBrepGeom(gB)
if rgB.Faces.RemoveSlits():
xBrepObject.replaceGeometry(gB, rgB)
iCt_Removed += 1
rgB.Dispose()
if iCt_Removed or bDebug:
print "{} out of {} {} breps had slit trims removed.".format(
iCt_Removed, len(gBreps[keySearchUs]), keySearchUs)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0 + " done.")
def extractFacesWithEdgeTolError(keySearchUs, keyExtracted):
if bEchoCmdPrompt:
sCmdPrompt0 = "Searching for faces with any " \
"actual edge deviations not" \
" matching BrepEdge.Tolerance values ..."
Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
sc.escape_test()
if keyExtracted not in gBreps: gBreps[keyExtracted] = []
gBs_1Fs_Found = []
gBs_Remaining_Good = []
iCt_BrepsFound = 0
for gB in gBreps[keySearchUs]:
rgB = getBrepGeom(gB)
rgB.Compact()
devs = xBrep_edgeDeviations.getDeviations(rgB)
idx_Fs_Found = []
for iE in range(rgB.Edges.Count):
if devs[iE] is None:
# TODO: Better handling of None?
idx_Fs_Found.extend(rgB.Edges[iE].AdjacentFaces())
elif (
devs[iE] <= (0.01*fPercent_EdgeTolMismatchTol) * sc.doc.ModelAbsoluteTolerance and
rgB.Edges[iE].Tolerance <= (0.01*fPercent_EdgeTolMismatchTol) * sc.doc.ModelAbsoluteTolerance
):
pass
elif (
abs(devs[iE] - rgB.Edges[iE].Tolerance) >
(0.01*fPercent_EdgeTolMismatchTol) * sc.doc.ModelAbsoluteTolerance
):
idx_Fs_Found.extend(rgB.Edges[iE].AdjacentFaces())
if not idx_Fs_Found:
rgB.Dispose()
continue
iCt_BrepsFound += 1
idx_Fs_Found = sorted(set(idx_Fs_Found))
rc = xBrepObject.extractFaces(
gB,
idx_Fs_Found,
bAddOnlyMonofaces=True,
bRetainLayer=True,
bRetainColor=True,
bEcho=False
)
if not rc:
rgB.Dispose()
continue
gBs_Bad_Extracted, gBs_Good_Remaining = rc
gBs_1Fs_Found.extend(gBs_Bad_Extracted)
gBs_Remaining_Good.extend(gBs_Good_Remaining)
rgB.Dispose()
if len(gBs_1Fs_Found) or bDebug:
s = "{} faces extracted in {} {} breps".format(
len(gBs_1Fs_Found), iCt_BrepsFound, keySearchUs)
s += " with at least one edge tolerance over"
s += " {:.1f}% of tolerance per BrepEdge.".format(
fPercent_EdgeTolMismatchTol)
print s
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
if gBs_1Fs_Found:
gBreps[keyExtracted].extend(gBs_1Fs_Found)
cleanBrepList(keyExtracted)
gBreps[keySearchUs].extend(gBs_Remaining_Good)
cleanBrepList(keySearchUs, keyExtracted)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0 + " done.")
def retrimFaceSrfsWithExistingEdges(keyRetrimUs):
if bEchoCmdPrompt:
sCmdPrompt0 = "Retrimming face underlying surfaces with existing edges ..."
Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
sc.escape_test()
iCt_Replaced = 0
gs_SingleBrepReturn = []
gs_MultiBrepReturn = []
for gB in gBreps[keyRetrimUs]:
NEs = rs.coercebrep(gB).DuplicateNakedEdgeCurves(outer=True, inner=True)
rc = xBrep_splitSurfaceWithCurves.processBrepObjects(
[gB],
NEs,
bSplitUnderlyingSrf=False,
bOnlyUseCrvsOnSrf=False,
bSplitToCrvSegs=True,
fTolerance=sc.doc.ModelAbsoluteTolerance,
bTryOtherTolsOnFail=True,
bExplode=False,
bExtract=False,
bEcho=bDebug,
bDebug=bDebug)
if not rc: continue
gB_Split = rc[0]
rc = xBrep_findFaceByBorderBoundingBox.processBrepObject(
gB_Split,
NEs,
fTolerance=sc.doc.ModelAbsoluteTolerance,
bDelOtherFacesNotExtract=True,
bEcho=bDebug,
bDebug=bDebug)
if not rc: continue
iCt_Replaced += 1
if isinstance(rc, Guid):
gs_SingleBrepReturn.append(rc)
elif isinstance(rc, list):
if len(rc) > 1:
gs_MultiBrepReturn.extend(rc)
#rc = xBrepFace_trimToNakedEdges.processObjectsWithSrfs(
# gB,
# rhBreps_UseNakedEdges=NEs,
# bSplitFullSurface=True,
# fSplitTol=sc.doc.ModelAbsoluteTolerance,
# bExtractModifiedFace=False,
# bDelTrimmingBrep=False,
# bEcho=bDebug,
# bDebug=bDebug)
#if not rc: continue
#iCt_Replaced += 1
#if len(rc) > 1:
# gs_MultiBrepReturn.extend(rc)
if gs_SingleBrepReturn:
gBreps[keyRetrimUs].extend(gs_SingleBrepReturn)
if gs_MultiBrepReturn:
gBreps[keyRetrimUs].extend(gs_MultiBrepReturn)
cleanBrepList(keyRetrimUs)
if iCt_Replaced or bDebug:
s = "{} monofaces replaced".format(iCt_Replaced)
s += " in {} breps".format(keyRetrimUs)
print s
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0 + " done.")
def rebuildFacesWithLargeEdgeTol(keySearchUs):
if bEchoCmdPrompt:
sCmdPrompt0 = "Rebuilding faces with large edge tolerances ..."
Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
sc.escape_test()
rc = xBrep_rebuildEdges.processBrepObjects(
gBreps[keySearchUs],
fRebuildNakedTol=fTol_EdgeForRebuild,
bEcho=bDebug if len(gBreps[keySearchUs]) <= 10 else False,
bDebug=bDebug,
)
if len(rc) or bDebug:
print "{} out of {} {} breps had their edges rebuilt.".format(
len(rc), len(gBreps[keySearchUs]), keySearchUs)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0 + " done.")
def extractBadAreaFaces(keySearchUs, keyExtracted):
if bEchoCmdPrompt:
sCmdPrompt0 = "Searching for bad-area faces ..."
Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
sc.escape_test()
def findBadAreaFaces(rgBrep, fTime_MaxTol, bDebug=False):
# Check whether brep is invalid.
# if not rgBrep.IsValid:
# print "Brep is invalid and will be skipped. " \
# "_ExtractBadSrf and repair the bad faces first."
# if bDebug: sPrint = 'rgBrep.IsValid'; print sPrint + ':', eval(sPrint)
# return [], []
idxFs_No = []
idxFs_Slow = []
for iF in range(rgBrep.Faces.Count):
rgBrep_1Face = rgBrep.Faces[iF].DuplicateFace(False)
stopwatch.Restart()
area = rgBrep_1Face.GetArea()
stopwatch.Stop()
timeElapsed = stopwatch.Elapsed.TotalSeconds
if area == 0: # Not None, for no area compute.
idxFs_No.append(iF)
elif fTime_MaxTol and timeElapsed > fTime_MaxTol:
idxFs_Slow.append(iF)
rgBrep_1Face.Dispose()
return idxFs_No + idxFs_Slow
gBs_Bad = []
gBs_Good = []
for gBrep in gBreps[keySearchUs]:
rgBrep = getBrepGeom(gBrep)
rgBrep.Compact()
rc = findBadAreaFaces(
rgBrep=rgBrep,
fTime_MaxTol=fSeconds_forArea if bFind_SlowArea else None,
)
rgBrep.Dispose()
if not rc: continue
idx_Faces = rc
rc = xBrepObject.extractFaces(
gBrep,
idx_Faces,
bAddOnlyMonofaces=True,
bRetainLayer=True,
bRetainColor=True,
bEcho=False
)
if not rc: continue
gBs_Bad, gBs_Good = rc
# In case a micro edge is the problem.
removeMicroEdges(gBs_Bad)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
for i in reversed(range(len(gBs_Bad))):
rgBrep = getBrepGeom(gBs_Bad[i])
findBadAreaFaces(
rgBrep=rgBrep,
fTime_MaxTol=fSeconds_forArea if bFind_SlowArea else None,
)
rgBrep.Dispose()
if not rc:
gBs_Good.append(gBs_Bad[i])
del gBs_Bad[i]
print "Moved Good brep from Bad list to Good."
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
if len(gBs_Bad) or bDebug:
print "{} bad area faces (that are otherwise valid) found in {} {} breps.".format(
len(gBs_Bad), len(gBreps[keySearchUs]), keySearchUs)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
if gBs_Bad:
gBreps[keyExtracted].extend(gBs_Bad)
cleanBrepList(keyExtracted)
gBreps[keySearchUs].extend(gBs_Good)
cleanBrepList(keySearchUs, keyExtracted)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0 + " done.")
def deleteShortBorderFaces(keySearchUs):
if bEchoCmdPrompt:
sCmdPrompt0 = "Searching for short-border faces ..."
Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
sc.escape_test()
rc = xBrep_facesWithShortBorderLength.processBrepObjects(
gBreps[keySearchUs],
fMaxLength=2.01*fTol_Small,
bExtract=True,
bEcho=False,
bDebug=False)
if not rc:
print "xBrep_facesWithShortBorderLength returned None."
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0 + " done.")
return []
gBs_Short, gBs_RemainingFromExtract = rc
iCt_Deleted = 0
for gB in gBs_Short:
bSuccess = sc.doc.Objects.Delete(objectId=gB, quiet=False)
if bSuccess: iCt_Deleted += 1
if iCt_Deleted or bDebug:
print "{} short border faces deleted in {} {} breps.".format(
iCt_Deleted, len(gBreps[keySearchUs]), keySearchUs)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
# Why?
#gBs_RemainingFromExtract = [gB for gBs in gBs_RemainingFromExtract for gB in gBs]
if iCt_Deleted:
if gBs_RemainingFromExtract:
gBreps[keySearchUs].extend(gBs_RemainingFromExtract)
cleanBrepList(keySearchUs)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0 + " done.")
def deleteSliverFaces(keySearchUs):
if bEchoCmdPrompt:
sCmdPrompt0 = "Searching for sliver faces ..."
Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
sc.escape_test()
iCt_Deleted = 0
gBs_RemainingFromExtract = []
for gBrep in gBreps[keySearchUs]:
rgBrep = getBrepGeom(gBrep)
rc = spb_Brep_sliverFaces.getFaces(
rgBrep,
fOverlap_MinAllowed=fTol_Small,
)
iCt_Faces = rgBrep.Faces.Count
rgBrep.Dispose()
idx_rgFaces_Found = rc[0]
if not idx_rgFaces_Found: continue
rc = xBrepObject.removeFaces(gBrep, idx_rgFaces_Found)
if rc is None:
print "{} sliver faces could not be deleted.".format(len(idx_rgFaces_Found))
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
else:
iCt_Deleted += len(idx_rgFaces_Found)
gBs_RemainingFromExtract.extend(rc)
if iCt_Deleted or bDebug:
print "{} sliver faces deleted in {} {} breps.".format(
iCt_Deleted, len(gBreps[keySearchUs]), keySearchUs)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0)
if iCt_Deleted:
if gBs_RemainingFromExtract:
gBreps[keySearchUs].extend(gBs_RemainingFromExtract)
cleanBrepList(keySearchUs)
if bEchoCmdPrompt: Rhino.RhinoApp.SetCommandPrompt(sCmdPrompt0 + " done.")
def deleteSmallAreaFaces(keySearchUs):
if bEchoCmdPrompt:
sCmdPrompt0 = "Searching for small area faces ..."