-
Notifications
You must be signed in to change notification settings - Fork 7
/
spb_NurbsCrv_starterFor_approximateCrv.py
421 lines (327 loc) · 12.2 KB
/
spb_NurbsCrv_starterFor_approximateCrv.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
"""
"""
from __future__ import absolute_import, division, print_function, unicode_literals
"""
220905-06, 08-09: Created.
230119: Added support for PolyCurve input.
"""
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
class Opts():
keys = []
values = {}
names = {}
riOpts = {}
listValues = {}
stickyKeys = {}
key = 'iDegree'; keys.append(key)
values[key] = 3
riOpts[key] = ri.Custom.OptionInteger(values[key])
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'iPointCt'; keys.append(key)
values[key] = 4
riOpts[key] = ri.Custom.OptionInteger(values[key])
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bPreserveEndTangentsForNonPolylines'; keys.append(key)
values[key] = True
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
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 == 'iDegree':
if cls.riOpts[key].CurrentValue == cls.values[key]:
# No change.
return
if cls.riOpts[key].CurrentValue <= 0:
cls.riOpts[key].CurrentValue = cls.values[key]
return
else:
cls.values[key] = cls.riOpts[key].CurrentValue
sc.sticky[cls.stickyKeys[key]] = cls.values[key]
cls.values['iPointCt'] = cls.riOpts['iPointCt'].CurrentValue = cls.values['iDegree'] + 1
sc.sticky[cls.stickyKeys['iPointCt']] = cls.values['iPointCt']
return
if key == 'iPointCt':
if cls.riOpts[key].CurrentValue < (cls.values['iDegree'] + 1):
cls.values[key] = cls.riOpts[key].CurrentValue = (cls.values['iDegree'] + 1)
else:
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 getInput():
"""
Get curves with optional input.
"""
go = ri.Custom.GetObject()
go.SetCommandPrompt("Select curves")
go.GeometryFilter = Rhino.DocObjects.ObjectType.Curve
go.AcceptNumber(True, acceptZero=True)
idxs_Opt = {}
def addOption(key): idxs_Opt[key] = Opts.addOption(go, key)
# def customGeometryFilter(rdObj, rgObj, compIdx):
# return not rgObj.IsClosed
#
# go.SetCustomGeometryFilter(customGeometryFilter)
while True:
go.ClearCommandOptions()
idxs_Opt.clear()
addOption('iDegree')
addOption('iPointCt')
addOption('bPreserveEndTangentsForNonPolylines')
addOption('bEcho')
addOption('bDebug')
res = go.GetMultiple(minimumNumber=1, maximumNumber=0)
if res == ri.GetResult.Cancel:
go.Dispose()
return
if res == ri.GetResult.Object:
objrefs = go.Objects()
go.Dispose()
return objrefs
if res == ri.GetResult.Number:
key = 'iDegree'
Opts.riOpts[key].CurrentValue = int(abs(go.Number()))
Opts.setValue(key)
continue
for key in idxs_Opt:
if go.Option().Index == idxs_Opt[key]:
Opts.setValue(key, go.Option().CurrentListOptionIndex)
break
def simplifyPolyline(pl, target_pt_ct=6):
ct_In = pl.Count
if ct_In <= target_pt_ct:
return
min = 0.1 * sc.doc.ModelAbsoluteTolerance
pl_WIP = pl.Duplicate()
ct_Min = ct_In - pl_WIP.ReduceSegments(tolerance=min)
if ct_Min == target_pt_ct:
return pl_WIP
max = 10.0 * min
while True:
sc.escape_test()
pl_WIP = pl.Duplicate()
ct_Max = ct_In - pl_WIP.ReduceSegments(tolerance=max)
if ct_Max == target_pt_ct:
return pl_WIP
elif ct_Max < target_pt_ct:
break
max *= 10.0
while True:
sc.escape_test()
mid = 0.5 * (min + max)
#if abs(mid-min) <= Rhino.RhinoMath.ZeroTolerance:
# return
pl_WIP = pl.Duplicate()
ct_WIP = ct_In - pl_WIP.ReduceSegments(tolerance=mid)
if ct_WIP == target_pt_ct:
return pl_WIP
if ct_WIP > target_pt_ct:
min = mid
elif ct_WIP < target_pt_ct:
max = mid
else:
raise Exception("What?")
if abs(max-min) <= Rhino.RhinoMath.ZeroTolerance:
return
def approximateCurveWithPolyline(crv, target_pt_ct=6):
tol_L = 0.1 * sc.doc.ModelAbsoluteTolerance
plc_WIP = crv.ToPolyline(
tolerance=tol_L,
angleTolerance=0.0,
minimumLength=0.0,
maximumLength=0.0)
ct_tL = plc_WIP.PointCount
if ct_tL == target_pt_ct:
return plc_WIP.ToPolyline()
plc_WIP.Dispose()
tol_H = 10.0 * tol_L
while tol_H < 0.1:
sc.escape_test()
plc_WIP = crv.ToPolyline(
tolerance=tol_H,
angleTolerance=0.0,
minimumLength=0.0,
maximumLength=0.0)
ct_tH = plc_WIP.PointCount
if ct_tH == target_pt_ct:
return plc_WIP.ToPolyline()
elif ct_tH < target_pt_ct:
break
tol_H *= 10.0
if ct_tH > target_pt_ct:
ret = simplifyPolyline(plc_WIP.ToPolyline(), target_pt_ct)
plc_WIP.Dispose()
return ret
plc_WIP.Dispose()
while True:
sc.escape_test()
tol_M = 0.5 * (tol_L + tol_H)
#if abs(tol_M-tol_L) <= Rhino.RhinoMath.ZeroTolerance:
# return
plc_WIP = crv.ToPolyline(
tolerance=tol_M,
angleTolerance=0.0,
minimumLength=0.0,
maximumLength=0.0)
ct_tM = plc_WIP.PointCount
if ct_tM == target_pt_ct:
return plc_WIP.ToPolyline()
if ct_tM > target_pt_ct:
tol_L = tol_M
ct_tL = ct_tM
elif ct_tM < target_pt_ct:
tol_H = tol_M
ct_tH = ct_tM
else:
raise Exception("What?")
plc_WIP.Dispose()
if abs(tol_H-tol_L) <= Rhino.RhinoMath.ZeroTolerance:
plc_Max = crv.ToPolyline(
tolerance=tol_H,
angleTolerance=0.0,
minimumLength=0.0,
maximumLength=0.0)
return plc_Max.ToPolyline()
def samplePointsOnArcCurve(ac, pt_ct):
ts = rg.ArcCurve.DivideByCount(
ac, segmentCount=pt_ct-1, includeEnds=True)
return Rhino.Collections.Point3dList(
[rg.ArcCurve.PointAt(ac, t) for t in ts])
def getStartingCpLocations(rgCrv_In, pt_ct):
if pt_ct == 2:
return rg.Polyline([rgCrv_In.PointAtStart, rgCrv_In.PointAtEnd])
if isinstance(rgCrv_In, rg.PolylineCurve):
pl = rgCrv_In.ToPolyline()
return simplifyPolyline(pl, target_pt_ct=pt_ct)
elif isinstance(rgCrv_In, rg.PolyCurve):
nc = rgCrv_In.ToNurbsCurve()
ret = approximateCurveWithPolyline(nc, target_pt_ct=pt_ct)
nc.Dispose()
return ret
elif isinstance(rgCrv_In, (rg.NurbsCurve, rg.PolyCurve)):
return approximateCurveWithPolyline(rgCrv_In, target_pt_ct=pt_ct)
elif isinstance(rgCrv_In, rg.ArcCurve):
return samplePointsOnArcCurve(rgCrv_In, pt_ct)
def setEndConditions(rgCrv_ToMod, rgCrv_Target, bTanEnds):
if bTanEnds:
bSuccess_Start = rgCrv_ToMod.SetEndCondition(
bSetEnd=False,
continuity=rg.NurbsCurve.NurbsCurveEndConditionType.Tangency,
point=rgCrv_Target.PointAtStart,
tangent=rgCrv_Target.TangentAtStart)
bSuccess_End = rgCrv_ToMod.SetEndCondition(
bSetEnd=True,
continuity=rg.NurbsCurve.NurbsCurveEndConditionType.Tangency,
point=rgCrv_Target.PointAtEnd,
tangent=rgCrv_Target.TangentAtEnd)
else:
bSuccess_Start = rgCrv_ToMod.SetEndCondition(
bSetEnd=False,
continuity=rg.NurbsCurve.NurbsCurveEndConditionType.Position,
point=rgCrv_Target.PointAtStart,
tangent=rg.Vector3d.Unset)
bSuccess_End = rgCrv_ToMod.SetEndCondition(
bSetEnd=True,
continuity=rg.NurbsCurve.NurbsCurveEndConditionType.Position,
point=rgCrv_Target.PointAtEnd,
tangent=rg.Vector3d.Unset)
return bSuccess_Start or bSuccess_End
def createCurve(rgCrv_In, degree, pt_ct, bTanEnds=True):
"""
Parameters:
rgCrv
degree
pt_ct
bPreserveTans: Only for non-polylines
Returns:
"""
points = getStartingCpLocations(rgCrv_In, pt_ct)
if not points: return
if points.Count == pt_ct:
nc = rg.NurbsCurve.Create(periodic=False, degree=degree, points=points)
else:
nc = rg.NurbsCurve.Create(
periodic=False,
degree=degree-(pt_ct-points.Count),
points=points)
nc.IncreaseDegree(degree)
if not bTanEnds:
return nc
if points.Count == 2:
# Nothing else can be done with this curve.
return nc
if degree == 2 and points.Count == 3:
print("TODO: Create parabolic degree 2.")
if not setEndConditions(nc, rgCrv_In, bTanEnds):
print("Failed setting end condition (continuity).")
return
return nc
def main():
objrefs_In = getInput()
if objrefs_In is None: return
iDegree = Opts.values['iDegree']
iPointCt = Opts.values['iPointCt']
bPreserveEndTangentsForNonPolylines = Opts.values['bPreserveEndTangentsForNonPolylines']
bEcho = Opts.values['bEcho']
bDebug = Opts.values['bDebug']
for objref_In in objrefs_In:
rgCrv = objref_In.Curve()
rc_Res = createCurve(
rgCrv,
degree=iDegree,
pt_ct=iPointCt,
bTanEnds=bPreserveEndTangentsForNonPolylines)
if rc_Res:
sc.doc.Objects.AddCurve(rc_Res)
sc.doc.Views.RedrawEnabled = True
if __name__ == '__main__': main()