forked from CADacombs/rhinopython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xBrep_splitSurfaceWithCurves.py
945 lines (731 loc) · 31.5 KB
/
xBrep_splitSurfaceWithCurves.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
"""
190530: Created.
191112: Added a function.
191113: Made input of some function more BrepFace focused.
191115: Added more tolerance multipliers.
200130, 0202: Modified output of a function.
200209, 14: Modified debug output.
200303: Now accepts curves with length < resolution and >= ModelAbsoluteTolerance.
200422: Refactored Opts. Added some options. Modified an option default value.
200430: Added bOnlyUseCrvsOnSrf and option to use all normal wires and brep edges.
200505: Bug fix.
200519-23, 26: Refactored. Exported a function to its own script.
200611: Bug fix.
200619: Import-related update.
200625: Now Normal objects are now found in main() instead of a subsequent function.
200629: Refactored.
200701: Bug fix.
200729: Import-related update.
"""
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
import xCurve
import xCurve_sortCurvesOnSurface
import xCurve_splitWithSurfaceEdges
import xBrepObject
class Opts():
keys = []
values = {}
names = {}
riOpts = {}
riAddOpts = {}
stickyKeys = {}
def addOptionDouble(key, names, riOpts):
return lambda getObj: ri.Custom.GetBaseClass.AddOptionDouble(
getObj, englishName=names[key], numberValue=riOpts[key])
def addOptionInteger(key, names, riOpts):
return lambda getObj: ri.Custom.GetBaseClass.AddOptionInteger(
getObj, englishName=names[key], intValue=riOpts[key])
def addOptionList(key, names, listValues, values):
return lambda getObj: ri.Custom.GetBaseClass.AddOptionList(
getObj,
englishOptionName=names[key],
listValues=listValues,
listCurrentIndex=values[key])
def addOptionToggle(key, names, riOpts):
return lambda getObj: ri.Custom.GetBaseClass.AddOptionToggle(
getObj, englishName=names[key], toggleValue=riOpts[key])
key = 'bScanForNakedEdges'; keys.append(key)
values[key] = True
riOpts[key] = ri.Custom.OptionToggle(values[key], 'Off', 'On')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bSelBrep'; keys.append(key)
values[key] = True
names[key] = 'BrepSelMode'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'Edge', 'Brep')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bSplitUnderlyingSrf'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bOnlyUseCrvsOnSrf'; keys.append(key)
values[key] = True
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bSplitToCrvSegs'; keys.append(key)
values[key] = True
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'fTolerance'; keys.append(key)
values[key] = 1.0 * sc.doc.ModelAbsoluteTolerance
riOpts[key] = ri.Custom.OptionDouble(values[key])
riAddOpts[key] = addOptionDouble(key, names, riOpts)
stickyKeys[key] = '{}({})({})'.format(key, __file__, sc.doc.Name)
key = 'bTryOtherTolsOnFail'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bExtract'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bExplode'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bEcho'; keys.append(key)
values[key] = True
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bDebug'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
for key in keys:
if key not in names:
names[key] = key[1:]
# Load sticky.
for key in stickyKeys:
if stickyKeys[key] in sc.sticky:
if key in riOpts:
riOpts[key].CurrentValue = values[key] = sc.sticky[stickyKeys[key]]
else:
values[key] = sc.sticky[stickyKeys[key]]
@classmethod
def setValues(cls):
for key in cls.keys:
if key in cls.riOpts:
cls.values[key] = cls.riOpts[key].CurrentValue
@classmethod
def saveSticky(cls):
for key in cls.stickyKeys:
if key in cls.riOpts:
sc.sticky[cls.stickyKeys[key]] = cls.riOpts[key].CurrentValue
else:
sc.sticky[cls.stickyKeys[key]] = cls.values[key]
def getInput_Faces():
"""Get Brepface with optional input."""
go = ri.Custom.GetObject()
go.SetCommandPrompt("Select faces to split")
go.GeometryFilter = rd.ObjectType.Surface
go.AcceptNumber(enable=True, acceptZero=True)
idxs_Opts = {}
while True:
key = 'bSplitUnderlyingSrf'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
key = 'bOnlyUseCrvsOnSrf'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
key = 'bSplitToCrvSegs'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
key = 'fTolerance'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
key = 'bTryOtherTolsOnFail'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
if not Opts.values['bSplitUnderlyingSrf']:
key = 'bExtract'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
if Opts.values['bSplitUnderlyingSrf'] or Opts.values['bExtract']:
key = 'bExplode'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
key = 'bEcho'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
key = 'bDebug'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
res = go.GetMultiple(minimumNumber=1, maximumNumber=0)
if res == ri.GetResult.Object:
objrefs = go.Objects()
go.Dispose()
return tuple([objrefs] + [Opts.values[key] for key in Opts.keys])
elif res == ri.GetResult.Cancel:
return
# An option was selected or a number was entered.
if res == ri.GetResult.Number:
Opts.riOpts['fTolerance'].CurrentValue = go.Number()
if Opts.riOpts['fTolerance'].CurrentValue < 0.0:
Opts.riOpts['fTolerance'].CurrentValue = Opts.riOpts['fTolerance'].InitialValue
Opts.setValues()
Opts.saveSticky()
go.ClearCommandOptions()
def getInput_TrimmingObjects(objrefs_Face):
"""
Get curves or edges with optional input.
"""
def getBrepIdsAndFaceEdgeIdxs(objrefs_Face):
gBs = []
idxs_Fs_perB = []
for objref_Face in objrefs_Face:
gBrep_withFaceToSplit = rs.coerceguid(objref_Face)
if gBrep_withFaceToSplit in gBs:
iB = gBs.index(gBrep_withFaceToSplit)
idxs_Fs_perB[iB].extend(list(objref_Face.Face().AdjacentEdges()))
else:
gBs.append(gBrep_withFaceToSplit)
idxs_Fs_perB.append(list(objref_Face.Face().AdjacentEdges()))
return gBs, idxs_Fs_perB
gBs_withFsToSplit, idxs_Fs_perB = getBrepIdsAndFaceEdgeIdxs(objrefs_Face)
go = ri.Custom.GetObject()
def notEdgeOfFaceToSplit(rdObj, geom, compIdx):
#print rdObj, geom, compIdx
if compIdx.ComponentIndexType == rg.ComponentIndexType.BrepEdge:
if isinstance(rdObj, rd.BrepObject):
if rdObj.Id in gBs_withFsToSplit:
iB = gBs_withFsToSplit.index(rdObj.Id)
if geom.EdgeIndex in idxs_Fs_perB[iB]:
print "An edge of a face to split was picked and will not be used."
return False
return True
go.SetCustomGeometryFilter(notEdgeOfFaceToSplit)
go.AcceptNothing(True)
go.AcceptNumber(enable=True, acceptZero=True)
go.AlreadySelectedObjectSelect = True
go.DeselectAllBeforePostSelect = False # So objects won't be deselected on repeats of While loop.
go.EnableClearObjectsOnEntry(False)
go.EnableUnselectObjectsOnExit(False)
idxs_Opts = {}
while True:
if Opts.values['bScanForNakedEdges']:
go.SetCommandPromptDefault("Enter for all normal wires and brep naked edges")
else:
go.SetCommandPromptDefault("Enter for all normal wires")
key = 'bScanForNakedEdges'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
key = 'bSelBrep'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
key = 'bSplitUnderlyingSrf'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
key = 'bOnlyUseCrvsOnSrf'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
key = 'bSplitToCrvSegs'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
key = 'fTolerance'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
key = 'bTryOtherTolsOnFail'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
if not Opts.values['bSplitUnderlyingSrf']:
key = 'bExtract'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
if Opts.values['bSplitUnderlyingSrf'] or Opts.values['bExtract']:
key = 'bExplode'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
key = 'bEcho'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
key = 'bDebug'; idxs_Opts[key] = Opts.riAddOpts[key](go)[0]
if Opts.values['bSelBrep']:
go.GeometryFilter = rd.ObjectType.Curve | rd.ObjectType.Brep
go.SubObjectSelect = False
go.SetCommandPrompt("Select curves or breps")
else:
go.GeometryFilter = rd.ObjectType.Curve
go.SubObjectSelect = True
go.SetCommandPrompt("Select curves or edges")
res = go.GetMultiple(minimumNumber=1, maximumNumber=0)
if res == ri.GetResult.Cancel:
return
elif res == ri.GetResult.Nothing:
go.Dispose()
return tuple([[]] + [Opts.values[key] for key in Opts.keys])
elif res == ri.GetResult.Object:
objrefs = go.Objects()
go.Dispose()
return tuple([objrefs] + [Opts.values[key] for key in Opts.keys])
# An option was selected or a number was entered.
if res == ri.GetResult.Number:
Opts.riOpts['fTolerance'].CurrentValue = go.Number()
if Opts.riOpts['fTolerance'].CurrentValue < 0.0:
Opts.riOpts['fTolerance'].CurrentValue = Opts.riOpts['fTolerance'].InitialValue
Opts.setValues()
Opts.saveSticky()
go.ClearCommandOptions()
def getAllNormalObjs(bScanForNakedEdges=True):
rdObjs = []
settings = rd.ObjectEnumeratorSettings()
settings.NormalObjects = True
settings.LockedObjects = False
for rdObj in sc.doc.Objects.GetObjectList(settings):
if rdObj.ObjectType == rd.ObjectType.Curve:
rdObjs.append(rdObj)
elif rdObj.ObjectType == rd.ObjectType.Brep:
if bScanForNakedEdges:
rdObjs.append(rdObj)
return rdObjs
def getFormattedDistance(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 getNakedEdgesOfBrepObject(rdBrep):
"""Using BrepObject instead of rg.Brep to use GUID to avoid brep to split."""
rgEs = []
rgBrep = rdBrep.BrepGeometry
for edge in rgBrep.Edges:
if edge.Valence == rg.EdgeAdjacency.Naked:
rgEs.append(edge)
#
# Keep this in case filtering of brep to face level is reimplemented.
#
## Structure of following conditional is to optimize speed.
#if rdBrep.Id not in gBs_withFsToSplit:
# # Get all naked edges without restriction.
# for edge in rgBrep.Edges:
# if edge.Valence == rg.EdgeAdjacency.Naked:
# rgEs.append(edge)
#else:
# iB = gBs_withFsToSplit.index(rdBrep.Id)
# for edge in rgBrep.Edges:
# if edge.EdgeIndex not in idxs_Fs_perB[iB]:
# if edge.Valence == rg.EdgeAdjacency.Naked:
# rgEs.append(edge)
return rgEs
def splitSurfaceIntoBrep(rgSrf_toSplit, rgCrvs_Splitters, **kwargs):
"""
Parameters:
rgSrf_toSplit: Can be rg.BrepFace or other rg.Surface.
rgCrvs_Splitters
fTolerance
bTryOtherTolsOnFail
bDebug
Returns on success:
rg.Brep
Returns on fail:
None
"""
def getOpt(key): return kwargs[key] if key in kwargs else Opts.values[key]
fTolerance = getOpt('fTolerance')
bTryOtherTolsOnFail = getOpt('bTryOtherTolsOnFail')
bDebug = getOpt('bDebug')
if isinstance(rgSrf_toSplit, rg.BrepFace):
rgFace_toSplit = rgSrf_toSplit
rgBrep_TempForUnderlyingSrf = None
elif isinstance(rgSrf_toSplit, rg.Surface):
rgBrep_TempForUnderlyingSrf = rgSrf_toSplit.ToBrep()
rgFace_toSplit = rgBrep_TempForUnderlyingSrf.Faces[0]
else:
return
# Create tolerance loop.
if bTryOtherTolsOnFail:
fTols_toTry = []
for tolMultiplier in 1.0, 0.5, 2.0, 0.25, 4.0, 0.125, 8.0, 0.0625, 16.0:
tol = tolMultiplier * fTolerance
fTols_toTry.append(tol)
else:
fTols_toTry = fTolerance,
# Split in a tolerance loop.
for fTol_toTry in fTols_toTry:
#
#
rgB_Split = rgFace_toSplit.Split(
curves=rgCrvs_Splitters,
tolerance=fTol_toTry)
#
#
if bDebug: sEval='rgB_Split'; print sEval+':',eval(sEval)
if rgB_Split is None:
if bDebug:
print " Failed at fTol_toTry=={}.".format(
getFormattedDistance(fTol_toTry))
for c in crvs:
sc.doc.Objects.AddCurve(c)
sc.doc.Views.Redraw()
elif rgB_Split.Faces.Count == 1:
if bDebug:
print "BrepFace.Split resulted in a 1-face Brep."
rgB_Split = None
elif rgB_Split.Faces.Count == rgFace_toSplit.Brep.Faces.Count:
if bDebug:
print "BrepFace.Split resulted in a Brep with no additional faces."
rgB_Split = None
else:
if bDebug:
sEval='rgB_Split.IsValid'; print sEval+':',eval(sEval)
sEval='rgB_Split.Faces.Count'; print sEval+':',eval(sEval)
#sc.doc.Objects.AddBrep(rgB_Split); sc.doc.Views.Redraw()
if not rgB_Split.IsValid:
rgB_Split = None
if bDebug or abs(fTol_toTry - fTolerance) > 1e-9:
print " Split successful at a tolerance of {}.".format(
getFormattedDistance(fTol_toTry))
break # out of tolerance loop.
if rgBrep_TempForUnderlyingSrf: rgBrep_TempForUnderlyingSrf.Dispose()
return rgB_Split
def splitFaceOfBrep(rgFace_toSplit, rgCrvs_Splitters, **kwargs):
"""
Parameters:
rgSrf_toSplit: Can be rg.BrepFace or other rg.Surface.
rgCrvs_Splitters
fTolerance
bTryOtherTolsOnFail
bDebug
Returns on success:
rg.Brep
Returns on fail:
None
"""
def getOpt(key): return kwargs[key] if key in kwargs else Opts.values[key]
fTolerance = getOpt('fTolerance')
bTryOtherTolsOnFail = getOpt('bTryOtherTolsOnFail')
bDebug = getOpt('bDebug')
if not isinstance(rgFace_toSplit, rg.BrepFace):
return
if not rgCrvs_Splitters:
return
#for c in rgCrvs_Splitters: sc.doc.Objects.AddCurve(c)
# Create tolerance loop.
if bTryOtherTolsOnFail:
fTols_toTry = []
for tolMultiplier in 1.0, 0.5, 2.0, 0.25, 4.0, 0.125, 8.0, 0.0625, 16.0:
tol = tolMultiplier * fTolerance
fTols_toTry.append(tol)
else:
fTols_toTry = fTolerance,
# Split in a tolerance loop.
for fTol_toTry in fTols_toTry:
#
#
rgB_Split = rgFace_toSplit.Split(
curves=rgCrvs_Splitters,
tolerance=fTol_toTry)
#
#
if bDebug: sEval='rgB_Split'; print sEval+':',eval(sEval)
if rgB_Split is None:
if bDebug:
print " Failed at fTol_toTry=={}.".format(
getFormattedDistance(fTol_toTry))
for c in crvs:
sc.doc.Objects.AddCurve(c)
sc.doc.Views.Redraw()
elif rgB_Split.Faces.Count == rgFace_toSplit.Brep.Faces.Count:
if bDebug:
print "BrepFace.Split resulted in a Brep with no additional faces."
rgB_Split = None
else:
if bDebug:
sEval='rgB_Split.IsValid'; print sEval+':',eval(sEval)
sEval='rgB_Split.Faces.Count'; print sEval+':',eval(sEval)
#sc.doc.Objects.AddBrep(rgB_Split); sc.doc.Views.Redraw()
if not rgB_Split.IsValid:
rgB_Split = None
if bDebug or abs(fTol_toTry - fTolerance) > 1e-9:
print " Split successful at a tolerance of {}.".format(
getFormattedDistance(fTol_toTry))
break # out of tolerance loop.
rgFace_toSplit.Brep.Dispose()
return rgB_Split
def getCurvesToSplitSurface(rgCrvs_tryForSplitters, rgSrf, fTolerance):
"""
Duplicates input curves that are on surface and splits to edges.
"""
rc = xCurve_sortCurvesOnSurface.duplicateCurvesOnSurface(
rgCrvs_tryForSplitters,
rgSrf,
fTolerance=fTolerance)
if not rc: return
(
crvs_CompletelyOnSrf_Closed,
crvs_CompletelyOnSrf_Open,
crvs_PartiallyOnSrf,
) = rc
if not crvs_PartiallyOnSrf:
return (crvs_CompletelyOnSrf_Closed + crvs_CompletelyOnSrf_Open)
# Trim the curves that lie partially on the surface mostly to get rid of the overlapping (Boundary) portions.
rc = xCurve_splitWithSurfaceEdges.splitCurvesWithSurfaceEdges(
rgCrvs_In=crvs_PartiallyOnSrf,
rgSrf_In=rgSrf,
fTolerance=fTolerance)
(
crvs_Trimmed_Interior,
crvs_Trimmed_Boundary,
crvs_Trimmed_Exterior
) = rc
for c in crvs_Trimmed_Boundary + crvs_Trimmed_Exterior: c.Dispose()
for c in crvs_PartiallyOnSrf: c.Dispose()
return (
crvs_CompletelyOnSrf_Closed +
crvs_CompletelyOnSrf_Open +
crvs_Trimmed_Interior
)
def processBrepObjects(objrefs_BrepFace, rhObjs_Splitters, **kwargs):
"""
Parameters:
bSplitUnderlyingSrf
bOnlyUseCrvsOnSrf
bSplitToCrvSegs
fTolerance
bTryOtherTolsOnFail
bExplode
bExtract
bEcho
bDebug
"""
def getOpt(key): return kwargs[key] if key in kwargs else Opts.values[key]
bSplitUnderlyingSrf = getOpt('bSplitUnderlyingSrf')
bOnlyUseCrvsOnSrf = getOpt('bOnlyUseCrvsOnSrf')
bSplitToCrvSegs = getOpt('bSplitToCrvSegs')
fTolerance = getOpt('fTolerance')
bTryOtherTolsOnFail = getOpt('bTryOtherTolsOnFail')
bExplode = getOpt('bExplode')
bExtract = getOpt('bExtract')
bEcho = getOpt('bEcho')
bDebug = getOpt('bDebug')
def getBrepObject(rhObj):
rdObj = rs.coercerhinoobject(rhObj)
if rdObj and (rdObj.ObjectType == rd.ObjectType.Brep):
return rdObj
def getSortedBrepIdsAndFaces(objrefs):
"""
Parameters:
list(objrefs)
Returns:
list(Brep GUIDs)
list(lists(integers of Face indices) per brep)
"""
gBreps_In = []
idxs_Faces_perBrep = []
for o in objrefs:
gBrep_In = o.ObjectId
rdBrep_In = o.Object()
rgBrep_In = o.Brep()
if not rgBrep_In.IsValid:
print "Brep {} is invalid. Fix first.".format(gBrep_In)
rgBrep_In.Dispose()
continue
idx_CompIdx = o.GeometryComponentIndex.Index
if idx_CompIdx == -1:
if gBrep_In in gBreps_In:
idxs_Faces_perBrep[gBreps_In.index(gBrep_In)] = range(rgBrep_In.Faces.Count)
else:
gBreps_In.append(gBrep_In)
idxs_Faces_perBrep.append(range(rgBrep_In.Faces.Count))
else:
rgFace_Brep0 = o.Face()
if gBrep_In in gBreps_In:
if rgFace_Brep0 in idxs_Faces_perBrep[gBreps_In.index(gBrep_In)]:
continue
else:
idxs_Faces_perBrep[gBreps_In.index(gBrep_In)].append(rgFace_Brep0.FaceIndex)
else:
gBreps_In.append(gBrep_In)
idxs_Faces_perBrep.append([rgFace_Brep0.FaceIndex])
return gBreps_In, idxs_Faces_perBrep
def getAllNormalObjsForSplitters():
rgCrvs_CrvObjs = []
rgCrvs_Edges = []
gBreps_ofEdges = []
settings = rd.ObjectEnumeratorSettings()
settings.NormalObjects = True
settings.LockedObjects = False
for rdObj in sc.doc.Objects.GetObjectList(settings):
if rdObj.ObjectType == rd.ObjectType.Curve:
rgCrvs_CrvObjs.append(rdObj.Geometry)
elif rdObj.ObjectType == rd.ObjectType.Brep:
rgNEs = getNakedEdgesOfBrepObject(rdObj)
for rgNE in rgNEs:
rgCrvs_Edges.append(rgNE.DuplicateCurve())
gBreps_ofEdges.append(rdObj.Id)
return rgCrvs_CrvObjs, rgCrvs_Edges, gBreps_ofEdges
def getSelctdObjsForSplitters(rhObjs_CurveOrBrep):
rgCrvs_CrvObjs = []
rgCrvs_Edges = []
gBreps_ofEdges = []
for o in rhObjs_CurveOrBrep:
rdObj = rs.coercerhinoobject(o) # coercecurve returns various rg.Curves, including rg.BrepEdge.
if rdObj.ObjectType == rd.ObjectType.Curve:
rgCrvs_CrvObjs.append(rdObj.Geometry)
elif rdObj.ObjectType == rd.ObjectType.Brep:
rgNEs = getNakedEdgesOfBrepObject(rdObj)
for rgNE in rgNEs:
rgCrvs_Edges.append(rgNE.DuplicateCurve())
gBreps_ofEdges.append(rdObj.Id)
return rgCrvs_CrvObjs, rgCrvs_Edges, gBreps_ofEdges
def splitIndividualFaceOrSurface():
gBs_Added = []
rgCrvs_Splitters_FilteredToBrep = (
rgCrvs_fromCrvObjs +
[c for c, g in zip(rgCrvs_fromEdges, gBreps_ofEdges) if g != gBrep_In])
for iF, idxFace in enumerate(idxs_rgFace_perBrep[iB]):
rgFace_In = rgBrep_In.Faces[idxFace]
rgBrep_1Face_B0 = rgFace_In.DuplicateFace(duplicateMeshes=False)
if bSplitUnderlyingSrf:
srf_toSplit = rgBrep_1Face_B0.Faces[0].UnderlyingSurface()
else:
srf_toSplit = rgBrep_1Face_B0.Faces[0]
if bOnlyUseCrvsOnSrf:
rgCrvs_Splitters_thisFace = getCurvesToSplitSurface(
rgCrvs_Splitters_FilteredToBrep, srf_toSplit, fTolerance)
if bDebug:
for c in rgCrvs_Splitters_thisFace: sc.doc.Objects.AddCurve(c)
else:
rgCrvs_Splitters_thisFace = rgCrvs_Splitters_FilteredToBrep
if bSplitToCrvSegs:
cs_WIP = xCurve.duplicateSegments(
rgCrvs_Splitters_thisFace,
bExplodePolyCrvs=True)
for c in rgCrvs_Splitters_thisFace:
c.Dispose()
rgCrvs_Splitters_thisFace = cs_WIP
rgBrep_Ret_Split = splitSurfaceIntoBrep(
rgSrf_toSplit=srf_toSplit,
rgCrvs_Splitters=rgCrvs_Splitters_thisFace,
fTolerance=fTolerance,
bTryOtherTolsOnFail=bTryOtherTolsOnFail,
bDebug=bDebug)
rgBrep_1Face_B0.Dispose()
if not rgBrep_Ret_Split: continue
rgBs_1F_Ret.append(rgBrep_Ret_Split)
idxFaces_SplitSuccess.append(idxFace)
idxFaces_AddBrepSuccess = []
for i, rgB in enumerate(rgBs_1F_Ret):
bSomeFacesNotAdded = False
if bExplode:
for iF, rgF in enumerate(rgB.Faces):
rgB_1F = rgF.DuplicateFace(True)
gB = sc.doc.Objects.AddBrep(
rgB_1F,
attributes=rdBrep_In.Attributes)
rgB_1F.IsDocumentControlled
rgB_1F.Dispose()
if gB == Guid.Empty:
bSomeFacesNotAdded = True
continue
gBs_Added.append(gB)
if bSomeFacesNotAdded:
print "Some split faces were not added. Check results."
else:
idxFaces_AddBrepSuccess.append(idxFaces_SplitSuccess[i])
else:
gB = sc.doc.Objects.AddBrep(
rgB,
attributes=rdBrep_In.Attributes)
if gB == Guid.Empty:
continue
gBs_Added.append(gB)
idxFaces_AddBrepSuccess.append(idxFaces_SplitSuccess[i])
if idxFaces_AddBrepSuccess:
if rgBrep_In.Faces.Count == 1:
sc.doc.Objects.Delete(objectId=rdBrep_In.Id, quiet=False)
else:
gBs_Remaining = xBrepObject.removeFaces(
rdBrep_In, idxFaces_AddBrepSuccess)
# Remove orginal faces.
if not gBs_Remaining:
print "Remove faces fail!"
else:
print "{} breps remaining from extracted brep.".format(
len(gBs_Remaining))
return gBs_Added
def splitInContextOfEntireBrep():
# rgBrep_Split_WIP is for a full brep, containing both
# the new faces from Split
# and faces that are not supposed to be split.
rgBrep_Split_WIP = rgBrep_In.Duplicate()
rgCrvs_Splitters_FilteredToBrep = (
rgCrvs_fromCrvObjs +
[c for c, g in zip(rgCrvs_fromEdges, gBreps_ofEdges) if g != gBrep_In])
for iF, idxFace in enumerate(idxs_rgFace_perBrep[iB]):
rgFace_toSplit = rgBrep_Split_WIP.Faces[idxFace]
if bOnlyUseCrvsOnSrf:
rgCrvs_Splitters_thisFace = getCurvesToSplitSurface(
rgCrvs_Splitters_FilteredToBrep, rgFace_toSplit, fTolerance)
else:
rgCrvs_Splitters_thisFace = rgCrvs_Splitters_FilteredToBrep
if bSplitToCrvSegs:
cs_WIP = xCurve.duplicateSegments(
rgCrvs_Splitters_thisFace,
bExplodePolyCrvs=True)
for c in rgCrvs_Splitters_thisFace:
c.Dispose()
rgCrvs_Splitters_thisFace = cs_WIP
rgBrep_Ret_Split = splitFaceOfBrep(
rgFace_toSplit=rgFace_toSplit,
rgCrvs_Splitters=rgCrvs_Splitters_thisFace,
bOnlyUseCrvsOnSrf=bOnlyUseCrvsOnSrf,
fTolerance=fTolerance,
bTryOtherTolsOnFail=bTryOtherTolsOnFail,
bDebug=bDebug)
if rgBrep_Ret_Split:
rgBrep_Split_WIP.Dispose()
rgBrep_Split_WIP = rgBrep_Ret_Split
idxFaces_SplitSuccess.append(idxFace)
if not rgBrep_Ret_Split:
return
# Success.
#xBrepObject.replaceFaces(
# gBrep_In,
# idxFaces_SplitSuccess,
#
bReplaced = sc.doc.Objects.Replace(
objectId=gBrep_In, brep=rgBrep_Ret_Split)
if not bReplaced:
print "Brep update fail for {}.".format(gBrep_In)
rgBrep_Ret_Split.Dispose()
return
if bEcho:
s = "Brep was updated."
s += " Face count increased by {} ({} -> {}).".format(
rgBrep_Ret_Split.Faces.Count-ct_Face_B0,
ct_Face_B0,
rgBrep_Ret_Split.Faces.Count)
print s
rgBrep_Ret_Split.Dispose()
return [gBrep_In]
gBreps_In, idxs_rgFace_perBrep = getSortedBrepIdsAndFaces(objrefs_BrepFace)
if not gBreps_In: return
if not rhObjs_Splitters:
rc = getAllNormalObjsForSplitters()
else:
rc = getSelctdObjsForSplitters(rhObjs_Splitters)
if not rc: return
(
rgCrvs_fromCrvObjs,
rgCrvs_fromEdges,
gBreps_ofEdges,
) = rc
gBs_Out = []
if bSplitUnderlyingSrf:
bExtract = True
for iB, gBrep_In in enumerate(gBreps_In):
rdBrep_In = getBrepObject(gBrep_In)
rgBrep_In = rdBrep_In.Geometry
idxFaces_SplitSuccess = []
rgBs_1F_Ret = []
ct_Face_B0 = rgBrep_In.Faces.Count
if bExtract and ct_Face_B0 > 1:
rc = splitIndividualFaceOrSurface()
else:
rc = splitInContextOfEntireBrep()
if rc:
gBs_Out.extend(rc)
return gBs_Out
def main():
rc = getInput_Faces()
if rc is None: return
objrefs_Faces = rc[0]
sc.doc.Objects.UnselectAll()
rc = getInput_TrimmingObjects(objrefs_Faces)
if rc is None: return
rhObjs_Splitters = rc[0]
if not rhObjs_Splitters:
# Get all Normal objects now so before any layer, etc., changes occur during next input.
rhObjs_Splitters = getAllNormalObjs(Opts.values['bScanForNakedEdges'])
if not rhObjs_Splitters:
print "No splitters."
return
Rhino.RhinoApp.SetCommandPrompt("Working ...")
gBreps_Result = processBrepObjects(
objrefs_BrepFace=objrefs_Faces,
rhObjs_Splitters=rhObjs_Splitters,
)
if Opts.values['bEcho']:
if not gBreps_Result:
print "No breps were split."
else:
print "{} new/modified breps resulted from splits.".format(len(gBreps_Result))
sc.doc.Views.Redraw()
if __name__ == '__main__': main()