-
Notifications
You must be signed in to change notification settings - Fork 7
/
spb_CrvDeviation.py
1635 lines (1278 loc) · 53.3 KB
/
spb_CrvDeviation.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
"""
This script is an alternative to _CrvDeviation.
'0' for LwrLimit, UprLimit, or MaxMinDistToRegard will disable the option.
MaxMinDistToRegard is the lowest value, over which the distances will be ignored.
Send any questions, comments, or script development service needs to
@spb on the McNeel Forums, https://discourse.mcneel.com/
"""
from __future__ import absolute_import, division, print_function, unicode_literals
#! python 2
"""
170927: Created.
...
171204: Now polycurves and polylines are "exploded" into segments. If they are not,
Curve.GetDistancesBetweenCurves sometimes fails or produces erroneous results.
Curves from curve set A are not selectable for set B even though they previously were removed anyway.
...
240903-10: Added optional 2 curve input routine. Removed some functions. Refactored.
Add display conduit similar to _CrvDeviation for when Mode=Abs.
Trialing a UX different than _CrvDeviation for when Mode=Abs,
that gives the user the option to skip leaving marks.
TODO:
Clean code in spb_GDBCs_1Way that eliminates false positives at curve ends.
"""
import Rhino
import Rhino.DocObjects as rd
import Rhino.Geometry as rg
import Rhino.Input as ri
import scriptcontext as sc
from System.Drawing import Color
class Opts():
keys = []
values = {}
names = {}
riOpts = {}
listValues = {}
stickyKeys = {}
key = 'bInputSets'; keys.append(key)
values[key] = False
names[key] = 'Input2'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'Crvs', 'Sets')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bExplodeCrvs'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'fLocAlongCrvTol'; keys.append(key)
values[key] = sc.doc.ModelAbsoluteTolerance
riOpts[key] = ri.Custom.OptionDouble(initialValue=values[key])
# Using ModelUnitSystem in case sc.doc.Name is None.
stickyKeys[key] = '{}({})({})({})'.format(key, __file__, sc.doc.Name, sc.doc.ModelUnitSystem)
key = 'bOnlyPerp'; keys.append(key)
values[key] = True
names[key] = 'ClosestPtType'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'Any', 'OnlyPerp')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'fDist_max_to_regard'; keys.append(key)
names[key] = 'MaxDistToRegard'
values[key] = 200.0 * sc.doc.ModelAbsoluteTolerance
#if sc.doc.ModelUnitSystem == Rhino.UnitSystem.Inches:
# values[key] = 0.125
#elif sc.doc.ModelUnitSystem == Rhino.UnitSystem.Millimeters:
# values[key] = 3.0
#else:
# values[key] = 1000.0 * sc.doc.ModelAbsoluteTolerance
riOpts[key] = ri.Custom.OptionDouble(initialValue=values[key], setLowerLimit=True, limit=0.0)
stickyKeys[key] = '{}({})({})'.format(key, __file__, sc.doc.Name)
key = 'bLimitMode'; keys.append(key)
values[key] = False
names[key] = 'Mode'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'Abs', 'Limit')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'fUprLimit'; keys.append(key)
if sc.doc.ModelUnitSystem == Rhino.UnitSystem.Inches:
values[key] = 0.026
elif sc.doc.ModelUnitSystem == Rhino.UnitSystem.Millimeters:
values[key] = 3.6
else:
values[key] = 1000.0 * sc.doc.ModelAbsoluteTolerance
riOpts[key] = ri.Custom.OptionDouble(initialValue=values[key], setLowerLimit=True, limit=0.0)
stickyKeys[key] = '{}({})({})'.format(key, __file__, sc.doc.Name)
key = 'fLwrLimit'; keys.append(key)
values[key] = (
0.014 if sc.doc.ModelUnitSystem == Rhino.UnitSystem.Inches
else (
2.4 if sc.doc.ModelUnitSystem == Rhino.UnitSystem.Millimeters
else 10.0*sc.doc.ModelAbsoluteTolerance)
)
riOpts[key] = ri.Custom.OptionDouble(initialValue=values[key], setLowerLimit=True, limit=0.0)
stickyKeys[key] = '{}({})({})'.format(key, __file__, sc.doc.Name)
key = 'bMarkMax'; keys.append(key)
values[key] = True
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bMarkMin'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bVerifyAddMarks'; keys.append(key)
values[key] = True
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bAddLine'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bAddDot'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'iDotDecPlaces'; keys.append(key)
values[key] = sc.doc.ModelDistanceDisplayPrecision - 1
riOpts[key] = ri.Custom.OptionInteger(values[key], setLowerLimit=True, limit=0)
stickyKeys[key] = '{}({})({})'.format(key, __file__, sc.doc.Name)
key = 'iDotFontHt'; keys.append(key)
values[key] = 11
riOpts[key] = ri.Custom.OptionInteger(values[key], setLowerLimit=True, limit=3)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bEcho'; keys.append(key)
values[key] = True
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bDebug'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
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 addOption(cls, go, key):
idxOpt = None
if key in cls.riOpts:
if key[0] == 'b':
idxOpt = go.AddOptionToggle(
cls.names[key], cls.riOpts[key])[0]
elif key[0] == 'f':
idxOpt = go.AddOptionDouble(
cls.names[key], cls.riOpts[key])[0]
elif key[0] == 'i':
idxOpt = go.AddOptionInteger(
englishName=cls.names[key], intValue=cls.riOpts[key])[0]
elif key in cls.listValues:
idxOpt = go.AddOptionList(
englishOptionName=cls.names[key],
listValues=cls.listValues[key],
listCurrentIndex=cls.values[key])
else:
print("{} is not a valid key in Opts.".format(key))
return idxOpt
@classmethod
def setValue(cls, key, idxList=None):
if key == 'fLocAlongCrvTol':
if cls.riOpts[key].CurrentValue <= 0.0:
cls.values[key] = cls.riOpts[key].CurrentValue = cls.riOpts[key].InitialValue
sc.sticky[cls.stickyKeys[key]] = cls.values[key]
return
if cls.riOpts[key].CurrentValue <= max((1e-6, 0.001*sc.doc.ModelAbsoluteTolerance)):
cls.values[key] = cls.riOpts[key].CurrentValue = cls.riOpts[key].InitialValue
sc.sticky[cls.stickyKeys[key]] = cls.values[key]
return
if key == 'fUprLimit':
if cls.riOpts[key].CurrentValue < 0.0:
cls.values[key] = cls.riOpts[key].CurrentValue = cls.riOpts[key].InitialValue
cls.values[key] = cls.riOpts[key].CurrentValue
sc.sticky[cls.stickyKeys[key]] = cls.values[key]
if (cls.values[key] > 0.0) and (cls.values[key] > cls.values['fDist_max_to_regard']):
cls.values['fDist_max_to_regard'] = cls.riOpts['fDist_max_to_regard'].CurrentValue = cls.values[key]
sc.sticky[cls.stickyKeys['fDist_max_to_regard']] = cls.values['fDist_max_to_regard']
return
if key == 'fLwrLimit':
if cls.riOpts[key].CurrentValue < 0.0:
cls.values[key] = cls.riOpts[key].CurrentValue = cls.riOpts[key].InitialValue
cls.values[key] = cls.riOpts[key].CurrentValue
sc.sticky[cls.stickyKeys[key]] = cls.values[key]
return
if key in cls.riOpts:
cls.values[key] = cls.riOpts[key].CurrentValue
elif key in cls.listValues:
cls.values[key] = idxList
else:
return
sc.sticky[cls.stickyKeys[key]] = cls.values[key]
def getPreselectedCurves():
gObjs_Preselected = []
for rdObj in sc.doc.Objects.GetSelectedObjects(includeLights=False, includeGrips=False):
gObjs_Preselected.append(rdObj.Id)
if gObjs_Preselected:
gCrvs_Preselected = []
iter = rd.ObjectEnumeratorSettings()
iter.NormalObjects = True
iter.LockedObjects = False
iter.IncludeLights = False
iter.IncludeGrips = False
for rdRhinoObject in sc.doc.Objects.GetObjectList(iter):
if rdRhinoObject.Id in gObjs_Preselected:
if rdRhinoObject.ObjectType == rd.ObjectType.Curve:
gCrvs_Preselected.append(rdRhinoObject.Id)
if len(gCrvs_Preselected) == 2:
if Opts.values['bEcho']:
s = "({} curves".format(len(gCrvs_Preselected))
s += " were preselected and will thus be the selection set.)"
print(s)
return tuple(gCrvs_Preselected)
def _addCommonOptions(go):
idxs_Opts = {}
def addOption(key): idxs_Opts[key] = Opts.addOption(go, key)
addOption('bInputSets')
addOption('bExplodeCrvs')
addOption('fLocAlongCrvTol')
addOption('bOnlyPerp')
addOption('fDist_max_to_regard')
addOption('bLimitMode')
if Opts.values['bLimitMode']:
addOption('fUprLimit')
addOption('fLwrLimit')
else:
addOption('bMarkMax')
addOption('bMarkMin')
if Opts.values['bMarkMax'] or Opts.values['bMarkMin']:
addOption('bVerifyAddMarks')
if (Opts.values['bLimitMode'] or Opts.values['bMarkMax'] or Opts.values['bMarkMin']):
if not Opts.values['bAddLine'] and not Opts.values['bAddDot']:
Opts.riOpts['bAddLine'].CurrentValue = True
Opts.setValue('bAddLine')
Opts.riOpts['bAddDot'].CurrentValue = True
Opts.setValue('bAddDot')
addOption('bAddLine')
addOption('bAddDot')
if Opts.values['bAddDot']:
addOption('iDotDecPlaces')
addOption('iDotFontHt')
addOption('bEcho')
addOption('bDebug')
return idxs_Opts
def getInput_2Crvs():
"""
Get 2 curves with optional input.
"""
go = ri.Custom.GetObject()
go.SetCommandPrompt("Select 2 curves")
go.GeometryFilter = rd.ObjectType.Curve
go.AlreadySelectedObjectSelect = True
go.DeselectAllBeforePostSelect = False # So objects won't be deselected on repeats of While loop.
go.GroupSelect = True
go.EnableClearObjectsOnEntry(False) # Keep objects in go on repeats of While loop.
go.EnableUnselectObjectsOnExit(False)
go.AcceptNumber(True, acceptZero=True)
bPreselectedObjsChecked = False
idxs_Opts = {}
def addOption(key): idxs_Opts[key] = Opts.addOption(go, key)
while True:
if Opts.values['bInputSets']:
go.Dispose()
sc.doc.Objects.UnselectAll()
sc.doc.Views.Redraw()
return getInput_2Sets()
go.ClearCommandOptions()
idxs_Opts.clear()
idxs_Opts.update(_addCommonOptions(go))
res = go.GetMultiple(minimumNumber=2, maximumNumber=2)
# Use bPreselectedObjsChecked so that only selected objects before the
# first call to go.GetMultiple is considered.
if not bPreselectedObjsChecked and go.ObjectsWerePreselected:
bPreselectedObjsChecked = True
go.EnablePreSelect(False, ignoreUnacceptablePreselectedObjects=True)
continue
if res == ri.GetResult.Cancel:
go.Dispose()
return
if res == ri.GetResult.Object:
objrefs = go.Objects()
go.Dispose()
return [objrefs[0].Curve()], [objrefs[1].Curve()]
# An option was selected or a number was entered.
if res == ri.GetResult.Number:
key = 'fLocAlongCrvTol'
Opts.riOpts[key].CurrentValue = go.Number()
Opts.setValue(key)
continue
for key in idxs_Opts:
if go.Option().Index == idxs_Opts[key]:
Opts.setValue(key, go.Option().CurrentListOptionIndex)
break
def getInput_2Sets():
"""
Get 2 sets of curves with optional input.
"""
rgCrvs_lists = [[],[]]
go = ri.Custom.GetObject()
sCommandPromptAdd = 'A', 'B'
go.GeometryFilter = rd.ObjectType.Curve
go.AlreadySelectedObjectSelect = True
go.DeselectAllBeforePostSelect = False # So objects won't be deselected on repeats of While loop.
go.GroupSelect = True
go.EnableClearObjectsOnEntry(False) # Keep objects in go on repeats of While loop.
go.EnableUnselectObjectsOnExit(False)
go.AcceptNumber(True, acceptZero=True)
bPreselectedObjsChecked = False
idxs_Opts = {}
def addOption(key): idxs_Opts[key] = Opts.addOption(go, key)
# Get input for each curve set using a loop.
for iCrvSet in 0,1:
go.SetCommandPrompt("Select curve set {}".format(sCommandPromptAdd[iCrvSet]))
while True:
if not Opts.values['bInputSets']:
go.Dispose()
sc.doc.Objects.UnselectAll()
sc.doc.Views.Redraw()
return getInput_2Crvs()
go.ClearCommandOptions()
idxs_Opts.clear()
idxs_Opts.update(_addCommonOptions(go))
res = go.GetMultiple(minimumNumber=1, maximumNumber=0)
# Use bPreselectedObjsChecked so that only selected objects before the
# first call to go.GetMultiple is considered.
if not bPreselectedObjsChecked and go.ObjectsWerePreselected:
bPreselectedObjsChecked = True
go.EnablePreSelect(False, ignoreUnacceptablePreselectedObjects=True)
continue
if res == ri.GetResult.Cancel:
go.Dispose()
return
if res == ri.GetResult.Object:
break
# An option was selected or a number was entered.
if res == ri.GetResult.Number:
key = 'fLocAlongCrvTol'
Opts.riOpts[key].CurrentValue = go.Number()
Opts.setValue(key)
continue
for key in idxs_Opts:
if go.Option().Index == idxs_Opts[key]:
Opts.setValue(key, go.Option().CurrentListOptionIndex)
break
sc.doc.Objects.UnselectAll()
sc.doc.Views.Redraw()
if go.ObjectCount == 0: return
rgCrvs_lists[iCrvSet] = [o.Geometry() for o in go.Objects()]
if iCrvSet == 0:
gCrvsA = [o.ObjectId for o in go.Objects()]
# Custom geometry filter to only allow selection of curves not in first set.
def curvesNotIn1stSetGeomFilter(rdObj, geom, compIdx):
# TODO: Fix this.
# Wires.
if (
compIdx.Index == -1 and
not isinstance(geom, rg.BrepEdge) and
rdObj.Id not in gCrvsA
):
return True
if isinstance(geom, rg.BrepEdge):
return True
return not rdObj.Id in gCrvsA
go.SetCustomGeometryFilter(curvesNotIn1stSetGeomFilter)
go.Dispose()
# Remove first set of curves from second.
rgCrvs_lists[1] = rgCrvs_lists[1][len(rgCrvs_lists[0]):]
if len(rgCrvs_lists[1]) == 0: return # Second set of objects were not selected.
return tuple(
([rgCrvs_lists[0]]) +
([rgCrvs_lists[1]]) +
[Opts.values[key] for key in Opts.keys])
def isMaxClosestDistBtwn2CrvsWithinTol(rgCrv_A, rgCrv_B, tolerance):
"""
Alternative to Curve.GetDistancesBetweenCurves for better results when
curves contain loops, etc.
Returns:
False (If not within tolerance parameter)
float(Largest deviation found)
"""
def isOutsideOfTolerance(rgC_Cat, rgC_Dog, ts_Cat):
for iT_Cat in xrange(len(ts_Cat)):
t_Cat = ts_Cat[iT_Cat]
pt_Cat = rgC_Cat.PointAt(t_Cat)
bSuccess, t_Dog = rgC_Dog.ClosestPoint(pt_Cat)
if not bSuccess:
raise ValueError("Closest point could not be calculated.")
pt_Dog = rgC_Dog.PointAt(t_Dog)
dist = pt_Cat.DistanceTo(pt_Dog)
if dist > tolerance:
return True
fDevs.append(dist)
return False
fDivLength = 10.0*sc.doc.ModelAbsoluteTolerance
fDevs = []
# First, check span ends.
ts_A = []
for iSpan in range(rgCrv_A.SpanCount):
spanDomain = rgCrv_A.SpanDomain(iSpan)
ts_A.append(spanDomain.T0)
if spanDomain.T1 not in ts_A:
ts_A.append(spanDomain.T1)
if isOutsideOfTolerance(rgCrv_A, rgCrv_B, ts_A):
return False
ts_B = []
for iSpan in range(rgCrv_B.SpanCount):
spanDomain = rgCrv_B.SpanDomain(iSpan)
ts_B.append(spanDomain.T0)
if spanDomain.T1 not in ts_B:
ts_B.append(spanDomain.T1)
if isOutsideOfTolerance(rgCrv_B, rgCrv_A, ts_B):
return False
for M in 1000.0, 10.0:
fDivLength = M * sc.doc.ModelAbsoluteTolerance
ts_A = []
rc = rgCrv_A.DivideByLength(
segmentLength=fDivLength,
includeEnds=True)
if rc:
ts_A = rc
if isOutsideOfTolerance(rgCrv_A, rgCrv_B, ts_A):
return False
ts_B = []
rc = rgCrv_B.DivideByLength(
segmentLength=fDivLength,
includeEnds=True)
if rc:
ts_B = rc
if isOutsideOfTolerance(rgCrv_B, rgCrv_A, ts_B):
return False
return max(fDevs)
def spb_GDBCs_1Way(curve_TestPts, curve_ClosestPt, fLocAlongCrvTol, bOnlyPerp=True, bDebug=False):
"""
Alternative to Curve.GetDistancesBetweenCurves for more accuracy.
Parameters:
curve_TestPts: rg.Curve that will be divided to obtain the testPoints for ClosestPoint.
curve_ClosestPt: rg.Curve that is the object of the ClosestPoint call.
segmentLength: float : Division length of curve_TestPts to obtain some testPoints for ClosestPoint.
bDebug: bool
Returns:
The same as Curve.GetDistancesBetweenCurves:
bool: success
float: maxDistance
float: maxDistanceParameterA
float: maxDistanceParameterB
float: minDistance
float: minDistanceParameterA
float: minDistanceParameterB
"""
segmentLength = 1000.0 * fLocAlongCrvTol
if bDebug:
sEval = "curve_TestPts.Domain.T0"; print(sEval, '=', eval(sEval))
sEval = "curve_ClosestPt.Domain.T1"; print(sEval, '=', eval(sEval))
sEval = "segmentLength"; print(sEval, '=', eval(sEval))
def generate_list_of_curve_parameters_for_ClosestPoint(curve, segmentLength):
if bDebug: print("generate_list_of_curve_parameters_for_ClosestPoint")
ts_Out = []
rc = curve.DivideByLength(
segmentLength=segmentLength,
includeEnds=True)
if rc:
ts_Out.extend(rc)
# For open curve, add the ends of the curve.
if not curve.IsClosed:
# DivideByLength doesn't add the T1 segment
# even when includeEnds == True.
# https://developer.rhino3d.com/api/RhinoCommon/html/M_Rhino_Geometry_Curve_DivideByLength.htm
# shows the parameter labeled as 'includeStart'.
if curve.Domain.T1 not in ts_Out:
ts_Out.append(curve.Domain.T1)
# Add parameters of all knots at full multiplicity.
nc_Temp = curve.ToNurbsCurve()
iK = 0
while iK < nc_Temp.Knots.Count:
sc.escape_test()
m = nc_Temp.Knots.KnotMultiplicity(iK)
if m == nc_Temp.Degree:
k = nc_Temp.Knots[iK]
if k not in ts_Out:
ts_Out.append(k)
iK += m
nc_Temp.Dispose()
if len(ts_Out) != len(set(ts_Out)):
sEval = "len(ts_Out)"; print(sEval, '=', eval(sEval))
sEval = "len(set(ts_Out))"; print(sEval, '=', eval(sEval))
raise ValueError("Duplicate parameters? Check getClosestDistsBtwn2Crvs.")
ts_Out.sort()
if bDebug:
sEval = "ts_Out[:10]"; print(sEval, '=', eval(sEval))
sEval = "ts_Out[-10:]"; print(sEval, '=', eval(sEval))
return ts_Out
ts_A_FullCrv = generate_list_of_curve_parameters_for_ClosestPoint(curve_TestPts, segmentLength)
if bDebug:
sEval = "len(ts_A_FullCrv)"; print(sEval, '=', eval(sEval))
def calc_parameters_and_distances(ts_A_In, curveA, curveB, bOnlyPerp):
if bDebug: print("calc_parameters_and_distances")
ts_B = []
dists_per_ts_A_Out = []
rads_90degs = Rhino.RhinoMath.ToRadians(90.0)
for i_t_A, t_A in enumerate(ts_A_In):
pt_A = curveA.PointAt(t_A)
bSuccess, t_B = curveB.ClosestPoint(pt_A)
if not bSuccess:
raise ValueError("Closest point could not be calculated.")
pt_B = curveB.PointAt(t_B)
v_tan_B = curveB.TangentAt(t_B)
v_dist = pt_A - pt_B
if not bOnlyPerp:
dists_per_ts_A_Out.append(pt_A.DistanceTo(pt_B))
ts_B.append(t_B)
continue
# bOnlyPerp == True
if v_dist.IsTiny():
dists_per_ts_A_Out.append(pt_A.DistanceTo(pt_B))
ts_B.append(t_B)
continue
angle_between = rg.Vector3d.VectorAngle(v_tan_B, v_dist)
angle_from90 = abs(rads_90degs - angle_between)
#if bDebug:
# sEval = "pt_A"; print(sEval, '=', eval(sEval))
# sEval = "pt_B"; print(sEval, '=', eval(sEval))
# sEval = "v_tan_B"; print(sEval, '=', eval(sEval))
# sEval = "v_dist"; print(sEval, '=', eval(sEval))
# sEval = "Rhino.RhinoMath.ToDegrees(angle_between)"; print(sEval, '=', eval(sEval))
# sEval = "Rhino.RhinoMath.ToDegrees(angle_from90)"; print(sEval, '=', eval(sEval))
# sEval = "v_dist.IsTiny()"; print(sEval, '=', eval(sEval))
#if not v_dist.IsTiny():
#sc.doc.Objects.AddPoint(pt_A)
#sc.doc.Objects.AddPoint(pt_B)
if angle_from90 > sc.doc.ModelAngleToleranceRadians:
dists_per_ts_A_Out.append(None)
else:
dists_per_ts_A_Out.append(pt_A.DistanceTo(pt_B))
ts_B.append(t_B)
if bDebug:
sEval = "len(ts_B)"; print(sEval, '=', eval(sEval))
sEval = "len(dists_per_ts_A_Out)"; print(sEval, '=', eval(sEval))
return ts_B, dists_per_ts_A_Out
ts_B, dists_per_ts_A = calc_parameters_and_distances(
ts_A_FullCrv,
curve_TestPts,
curve_ClosestPt,
bOnlyPerp=bOnlyPerp)
if bDebug:
sEval = "len(dists_per_ts_A)"; print(sEval, '=', eval(sEval))
sEval = "dists_per_ts_A[:10]"; print(sEval, '=', eval(sEval))
sEval = "dists_per_ts_A[-10:]"; print(sEval, '=', eval(sEval))
if all(d is None for d in dists_per_ts_A):
return False, [], [], [], [], [], []
# Get max distance.
dist_Max = max(dists_per_ts_A)
idx_MaxDist = dists_per_ts_A.index(dist_Max)
t_A_MaxDist = ts_A_FullCrv[idx_MaxDist]
t_B_MaxDist = ts_B[idx_MaxDist]
if bDebug:
sEval = "dist_Max"; print(sEval, '=', eval(sEval))
sEval = "idx_MaxDist"; print(sEval, '=', eval(sEval))
sEval = "t_A_MaxDist"; print(sEval, '=', eval(sEval))
sEval = "t_B_MaxDist"; print(sEval, '=', eval(sEval))
# Get min distance.
dist_Min = min(d for d in dists_per_ts_A if d is not None)
idx_MinDist = dists_per_ts_A.index(dist_Min)
t_A_MinDist = ts_A_FullCrv[idx_MinDist]
t_B_MinDist = ts_B[idx_MinDist]
if bDebug:
sEval = "dist_Min"; print(sEval, '=', eval(sEval))
sEval = "idx_MinDist"; print(sEval, '=', eval(sEval))
sEval = "t_A_MinDist"; print(sEval, '=', eval(sEval))
sEval = "t_B_MinDist"; print(sEval, '=', eval(sEval))
if bDebug:
print("Iterate in smaller group of division points about the current winner",
"to find a more accurate winner.")
def findMoreAccurateWinner(ts_A_In, curveA, idx_Winner_In, segmentLength_In, fLocAlongCrvTol, bFindMax_NotMin):
if bDebug: print("findMoreAccurateWinner")
ts_A_WIP = ts_A_In[:]
cA_WIP = curveA.Duplicate()
idx_Winner_WIP = idx_Winner_In
segmentLength = segmentLength_In
t_A_Winner = ts_A_WIP[idx_Winner_In]
while True:
sc.escape_test()
segmentLength *= 0.1
if segmentLength < (fLocAlongCrvTol - 1e-6):
break
if bDebug: sEval = "segmentLength"; print(sEval, '=', eval(sEval))
if idx_Winner_WIP > 0:
t0 = ts_A_WIP[idx_Winner_WIP - 1]
else:
t0 = ts_A_WIP[0]
if idx_Winner_WIP < (len(ts_A_WIP) - 1):
t1 = ts_A_WIP[idx_Winner_WIP + 1]
else:
t1 = ts_A_WIP[len(ts_A_WIP) - 1]
if bDebug:
sEval = "t0"; print(sEval, '=', eval(sEval))
sEval = "t1"; print(sEval, '=', eval(sEval))
cA_WIP = cA_WIP.Trim(rg.Interval(t0, t1))
#sc.doc.Objects.AddCurve(cA_WIP); sc.doc.Views.Redraw(); 1/0
if bDebug: sEval = "cA_WIP.GetLength()"; print(sEval, '=', eval(sEval))
ts_A_WIP = generate_list_of_curve_parameters_for_ClosestPoint(cA_WIP, segmentLength)
if bDebug:
sEval = "len(ts_A_WIP)"; print(sEval, '=', eval(sEval))
sEval = "ts_A_WIP[:10]"; print(sEval, '=', eval(sEval))
sEval = "ts_A_WIP[-10:]"; print(sEval, '=', eval(sEval))
ts_B_WIP, dists_per_ts_A_WIP = calc_parameters_and_distances(
ts_A_WIP,
cA_WIP,
curve_ClosestPt,
bOnlyPerp=bOnlyPerp)
# Get winning distance.
if bFindMax_NotMin:
dist_Winner = max(dists_per_ts_A_WIP)
else:
dist_Winner = min(d for d in dists_per_ts_A_WIP if d is not None)
idx_Winner_WIP = dists_per_ts_A_WIP.index(dist_Winner)
t_A_Winner = ts_A_WIP[idx_Winner_WIP]
t_B_Winner = ts_B_WIP[idx_Winner_WIP]
if bDebug:
sEval = "dist_Winner"; print(sEval, '=', eval(sEval))
sEval = "idx_Winner_WIP"; print(sEval, '=', eval(sEval))
sEval = "t_A_Winner"; print(sEval, '=', eval(sEval))
sEval = "t_B_Winner"; print(sEval, '=', eval(sEval))
return dist_Winner, t_A_Winner, t_B_Winner
rc = findMoreAccurateWinner(
ts_A_In=ts_A_FullCrv,
curveA=curve_TestPts,
idx_Winner_In=idx_MaxDist,
segmentLength_In=segmentLength,
fLocAlongCrvTol=fLocAlongCrvTol,
bFindMax_NotMin=True)
dist_Max, t_A_MaxDist, t_B_MaxDist = rc
if dist_Min > 0.0:
rc = findMoreAccurateWinner(
ts_A_In=ts_A_FullCrv,
curveA=curve_TestPts,
idx_Winner_In=idx_MinDist,
segmentLength_In=segmentLength,
fLocAlongCrvTol=fLocAlongCrvTol,
bFindMax_NotMin=False)
dist_Min, t_A_MinDist, t_B_MinDist = rc
if (
dist_Max is not None and
dist_Max > 1e-6 and
((t_A_MaxDist - curve_TestPts.Domain.T0) <= 1e-6)
or
((t_A_MaxDist - curve_TestPts.Domain.T1) <= 1e-6)
):
v_dist = curve_TestPts.PointAt(t_A_MaxDist) - curve_ClosestPt.PointAt(t_B_MaxDist)
if v_dist.IsTiny():
pass
else:
rads_90degs = Rhino.RhinoMath.ToRadians(90.0)
v_tan_A = curve_TestPts.TangentAt(t_A_MaxDist)
angle_between = rg.Vector3d.VectorAngle(v_tan_A, v_dist)
angle_from90 = abs(rads_90degs - angle_between)
if angle_from90 > Rhino.RhinoMath.ToRadians(22.5):
dist_Max = None
t_A_MaxDist = None
t_B_MaxDist = None
if (
dist_Min is not None and
dist_Min > 1e-6 and
((t_A_MinDist - curve_TestPts.Domain.T0) <= 1e-6) or
((t_A_MinDist - curve_TestPts.Domain.T1) <= 1e-6)
):
v_dist = curve_TestPts.PointAt(t_A_MinDist) - curve_ClosestPt.PointAt(t_B_MinDist)
if v_dist.IsTiny():
pass
else:
rads_90degs = Rhino.RhinoMath.ToRadians(90.0)
v_tan_A = curve_TestPts.TangentAt(t_A_MinDist)
angle_between = rg.Vector3d.VectorAngle(v_tan_A, v_dist)
angle_from90 = abs(rads_90degs - angle_between)
if angle_from90 > Rhino.RhinoMath.ToRadians(22.5):
dist_Min = None
t_A_MinDist = None
t_B_MinDist = None
return (
True,
dist_Max,
t_A_MaxDist,
t_B_MaxDist,
dist_Min,
t_A_MinDist,
t_B_MinDist,
)
def spb_GDBCs_BothWays(curveA, curveB, fLocAlongCrvTol=None, bOnlyPerp=True, bDebug=False):
"""
Alternative to Curve.GetDistancesBetweenCurves for more accurate results when
curves contain loops, etc.
Returns:
The same as Curve.GetDistancesBetweenCurves:
bool: success
float: maxDistance
float: maxDistanceParameterA
float: maxDistanceParameterB
float: minDistance
float: minDistanceParameterA
float: minDistanceParameterB
"""
if fLocAlongCrvTol is None:
fLocAlongCrvTol = 100.0*sc.doc.ModelAbsoluteTolerance
if bDebug: sEval = "fLocAlongCrvTol"; print(sEval, '=', eval(sEval))
Rhino.RhinoApp.Wait()
rc = spb_GDBCs_1Way(
curve_TestPts=curveA,
curve_ClosestPt=curveB,
fLocAlongCrvTol=fLocAlongCrvTol,
bOnlyPerp=bOnlyPerp,
bDebug=bDebug)
(
bSuccess_onB,
dist_Max_ClosestPt_on_B,
tA_MaxDist_ClosestPt_on_B,
tB_MaxDist_ClosestPt_on_B,
dist_Min_ClosestPt_on_B,
tA_MinDist_ClosestPt_on_B,
tB_MinDist_ClosestPt_on_B,
) = rc
if bDebug: sEval = "rc"; print(sEval, '=', eval(sEval))
Rhino.RhinoApp.Wait()
# Notice that curveA and curveB are reversed.
rc = spb_GDBCs_1Way(
curve_TestPts=curveB,
curve_ClosestPt=curveA,
fLocAlongCrvTol=fLocAlongCrvTol,
bOnlyPerp=bOnlyPerp,
bDebug=bDebug)
(
bSuccess_onA,
dist_Max_ClosestPt_on_A,
tB_MaxDist_ClosestPt_on_A,
tA_MaxDist_ClosestPt_on_A,
dist_Min_ClosestPt_on_A,
tB_MinDist_ClosestPt_on_A,
tA_MinDist_ClosestPt_on_A,
) = rc
if bDebug: sEval = "rc"; print(sEval, '=', eval(sEval))
if not bSuccess_onA and not bSuccess_onB:
return
if not bSuccess_onA and bSuccess_onB:
dist_Max = dist_Max_ClosestPt_on_B
tA_Max_Out = tA_MaxDist_ClosestPt_on_B
tB_Max_Out = tB_MaxDist_ClosestPt_on_B
dist_Min = dist_Min_ClosestPt_on_B
tA_Min_Out = tA_MinDist_ClosestPt_on_B
tB_Min_Out = tB_MinDist_ClosestPt_on_B
#sc.doc.Objects.AddCurve(curveA)
#sc.doc.Objects.AddCurve(curveB)
#sc.doc.Views.Redraw()
#raise Exception("not bSuccess_onA and bSuccess_onB")
elif bSuccess_onA and not bSuccess_onB:
dist_Max = dist_Max_ClosestPt_on_A
tA_Max_Out = tA_MaxDist_ClosestPt_on_A
tB_Max_Out = tB_MaxDist_ClosestPt_on_A
dist_Min = dist_Min_ClosestPt_on_A
tA_Min_Out = tA_MinDist_ClosestPt_on_A
tB_Min_Out = tB_MinDist_ClosestPt_on_A
#sc.doc.Objects.AddCurve(curveA)
#sc.doc.Objects.AddCurve(curveB)
#sc.doc.Views.Redraw()
#raise Exception("bSuccess_onA and not bSuccess_onB")
else:
if dist_Max_ClosestPt_on_B > dist_Max_ClosestPt_on_A:
dist_Max = dist_Max_ClosestPt_on_B