forked from tpaviot/pythonocc-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathedge.py
More file actions
566 lines (475 loc) · 18.1 KB
/
edge.py
File metadata and controls
566 lines (475 loc) · 18.1 KB
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
##Copyright 2008-2015 Jelle Feringa (jelleferinga@gmail.com)
##
##This file is part of pythonOCC.
##
##pythonOCC is free software: you can redistribute it and/or modify
##it under the terms of the GNU Lesser General Public License as published by
##the Free Software Foundation, either version 3 of the License, or
##(at your option) any later version.
##
##pythonOCC is distributed in the hope that it will be useful,
##but WITHOUT ANY WARRANTY; without even the implied warranty of
##MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
##GNU Lesser General Public License for more details.
##
##You should have received a copy of the GNU Lesser General Public License
##along with pythonOCC. If not, see <http://www.gnu.org/licenses/>
from OCC.BRepAdaptor import BRepAdaptor_Curve, BRepAdaptor_HCurve
from OCC.GCPnts import GCPnts_UniformAbscissa
from OCC.Geom import Geom_OffsetCurve, Geom_TrimmedCurve
from OCC.TopExp import topexp
from OCC.TopoDS import TopoDS_Edge, TopoDS_Vertex, TopoDS_Face
from OCC.gp import *
from OCC.GeomLProp import GeomLProp_CurveTool
from OCC.BRepLProp import BRepLProp_CLProps
from OCC.GeomLib import geomlib
from OCC.GCPnts import GCPnts_AbscissaPoint
from OCC.GeomAPI import GeomAPI_ProjectPointOnCurve
from OCC.ShapeAnalysis import ShapeAnalysis_Edge
from OCC.BRep import *
# high-level
from Common import vertex2pnt, minimum_distance
from Construct import make_edge, fix_continuity
from Context import assert_isdone
from vertex import Vertex
from types_lut import geom_lut
from base import KbeObject
class IntersectCurve(object):
def __init__(self, instance):
self.instance = instance
def intersect(self, other, disp, tolerance=1e-2):
'''Intersect self with a point, curve, edge, face, solid
method wraps dealing with the various topologies
'''
if isinstance(other, TopoDS_Face):
from OCC.BRepIntCurveSurface import BRepIntCurveSurface_Inter
face_curve_intersect = BRepIntCurveSurface_Inter()
face_curve_intersect.Init(other, self.instance.adaptor.Curve(), tolerance)
pnts = []
while face_curve_intersect.More():
face_curve_intersect.Next()
pnts.append(face_curve_intersect.Pnt())
return pnts
class DiffGeomCurve(object):
def __init__(self, instance):
self.instance = instance
self._local_props = BRepLProp_CLProps(self.instance.adaptor, 2, self.instance.tolerance)
# initialize with random parameter: 0
@property
def _curvature(self):
return self._local_props
def radius(self, u):
'''returns the radius at u
'''
# NOT SO SURE IF THIS IS THE SAME THING!!!
self._curvature.SetParameter(u)
pnt = gp_Pnt()
self._curvature.CentreOfCurvature(pnt)
return pnt
def curvature(self, u):
# ugly
self._curvature.SetParameter(u)
return self._curvature.Curvature()
def tangent(self, u):
'''sets or gets ( iff vector ) the tangency at the u parameter
tangency can be constrained so when setting the tangency,
you're constrainting it in fact
'''
self._curvature.SetParameter(u)
if self._curvature.IsTangentDefined():
ddd = gp_Dir()
self._curvature.Tangent(ddd)
return ddd
else:
raise ValueError('no tangent defined')
def normal(self, u):
'''returns the normal at u
computes the main normal if no normal is found
see:
www.opencascade.org/org/forum/thread_645+&cd=10&hl=nl&ct=clnk&gl=nl
'''
try:
self._curvature.SetParameter(u)
ddd = gp_Dir()
self._curvature.Normal(ddd)
return ddd
except:
raise ValueError('no normal was found')
def derivative(self, u, n):
'''
returns n derivatives at parameter b
'''
self._curvature.SetParameter(u)
deriv = {1: self._curvature.D1,
2: self._curvature.D2,
3: self._curvature.D3,
}
try:
return deriv[n]
except KeyError:
raise AssertionError('n of derivative is one of [1,2,3]')
def points_from_tangential_deflection(self):
pass
#===========================================================================
# Curve.Construct
#===========================================================================
class ConstructFromCurve():
def __init__(self, instance):
self.instance = instance
def make_face(self):
'''returns a brep face iff self.closed()
'''
raise NotImplementedError
def make_offset(self, offset, vec):
'''
returns an offsetted curve
@param offset: the distance between self.crv and the curve to offset
@param vec: offset direction
'''
return Geom_OffsetCurve(self.instance.h_crv, offset, vec)
def approximate_on_surface(self):
'''
approximation of a curve on surface
'''
raise NotImplementedError
class Edge(TopoDS_Edge, KbeObject):
def __init__(self, edge):
assert isinstance(edge, TopoDS_Edge), 'need a TopoDS_Edge, got a %s' % edge.__class__
assert not edge.IsNull()
super(Edge, self).__init__()
KbeObject.__init__(self, 'edge')
# we need to copy the base shape using the following three
# lines
assert self.IsNull()
self.TShape(edge.TShape())
self.Location(edge.Location())
self.Orientation(edge.Orientation())
assert not self.IsNull()
# tracking state
self._local_properties_init = False
self._curvature_init = False
self._geometry_lookup_init = False
self._curve_handle = None
self._curve = None
self._adaptor = None
self._adaptor_handle = None
# instantiating cooperative classes
# cooperative classes are distinct through CamelCaps from
# normal method -> pep8
self.DiffGeom = DiffGeomCurve(self)
self.Intersect = IntersectCurve(self)
self.Construct = ConstructFromCurve(self)
#self.graphic = GraphicCurve(self)
# GeomLProp object
self._curvature = None
def is_closed(self):
return self.adaptor.IsClosed()
def is_periodic(self):
return self.adaptor.IsPeriodic()
def is_rational(self):
return self.adaptor.IsRational()
def continuity(self):
return self.adaptor.Continuity
def degree(self):
if 'line' in self.type:
return 1
elif 'curve' in self.type:
return self.adaptor.Degree()
else:
# hyperbola, parabola, circle
return 2
def nb_knots(self):
return self.adaptor.NbKnots()
def nb_poles(self):
return self.adaptor.NbPoles()
@property
def curve(self):
if self._curve is not None and not self.is_dirty:
pass
else:
self._curve_handle = BRep_Tool().Curve(self)[0]
self._curve = self._curve_handle.GetObject()
return self._curve
@property
def curve_handle(self):
if self._curve_handle is not None and not self.is_dirty:
pass
else:
self.curve
return self._curve_handle
@property
def adaptor(self):
if self._adaptor is not None and not self.is_dirty:
pass
else:
self._adaptor = BRepAdaptor_Curve(self)
self._adaptor_handle = BRepAdaptor_HCurve(self._adaptor)
return self._adaptor
@property
def adaptor_handle(self):
if self._adaptor_handle is not None and not self.is_dirty:
pass
else:
self.adaptor
return self._adaptor_handle
@property
def geom_curve_handle(self):
"""
:return: Handle_Geom_Curve adapted from `self`
"""
if self._adaptor_handle is not None and not self.is_dirty:
pass
else:
self.adaptor
return self._adaptor.Curve().Curve()
@property
def type(self):
return geom_lut[self.adaptor.Curve().GetType()]
def pcurve(self, face):
"""
computes the 2d parametric spline that lies on the surface of the face
:return: Geom2d_Curve, u, v
"""
crv, u, v = BRep_Tool().CurveOnSurface(self, face)
return crv.GetObject(), u, v
def _local_properties(self):
self._lprops_curve_tool = GeomLProp_CurveTool()
self._local_properties_init = True
def domain(self):
'''returns the u,v domain of the curve'''
return self.adaptor.FirstParameter(), self.adaptor.LastParameter()
def project(self, other):
'''projects self with a point, curve, edge, face, solid
method wraps dealing with the various topologies
'''
raise NotImplementedError
#===========================================================================
# Curve.GlobalProperties
#===========================================================================
def length(self, lbound=None, ubound=None, tolerance=1e-5):
'''returns the curve length
if either lbound | ubound | both are given, than the length
of the curve will be measured over that interval
'''
_min, _max = self.domain()
if _min < self.adaptor.FirstParameter():
raise ValueError('the lbound argument is lower than the first parameter of the curve: %s ' % (self.adaptor.FirstParameter()))
if _max > self.adaptor.LastParameter():
raise ValueError('the ubound argument is greater than the last parameter of the curve: %s ' % (self.adaptor.LastParameter()))
lbound = _min if lbound is None else lbound
ubound = _max if ubound is None else ubound
return GCPnts_AbscissaPoint().Length(self.adaptor, lbound, ubound, tolerance)
#===========================================================================
# Curve.modify
#===========================================================================
def trim(self, lbound, ubound, periodic=False):
'''
trim the curve
@param lbound:
@param ubound:
'''
a, b = sorted([lbound, ubound])
tr = Geom_TrimmedCurve(self.adaptor.Curve().Curve(), a, b).GetHandle()
return Edge(make_edge(tr))
def extend_by_point(self, pnt, degree=3, beginning=True):
'''extends the curve to point
does not extend if the degree of self.curve > 3
@param pnt:
@param degree:
@param beginning:
'''
if self.degree > 3:
raise ValueError('to extend you self.curve should be <= 3, is %s' % (self.degree))
return geomlib.ExtendCurveToPoint(self.curve, pnt, degree, beginning)
#===========================================================================
# Curve.
#===========================================================================
def closest(self, other):
return minimum_distance(self, other)
def project_vertex(self, pnt_or_vertex):
''' returns the closest orthogonal project on `pnt` on edge
'''
if isinstance(pnt_or_vertex, TopoDS_Vertex):
pnt_or_vertex = vertex2pnt(pnt_or_vertex)
poc = GeomAPI_ProjectPointOnCurve(pnt_or_vertex, self.curve_handle)
return poc.LowerDistanceParameter(), poc.NearestPoint()
def distance_on_curve(self, distance, close_parameter, estimate_parameter, check_seam=True):
'''returns the parameter if there is a parameter
on the curve with a distance length from u
raises OutOfBoundary if no such parameter exists
'''
ccc = GCPnts_AbscissaPoint(self.adaptor, distance, close_parameter, estimate_parameter, 1e-5)
with assert_isdone(ccc, 'couldnt compute distance on curve'):
return ccc.Parameter()
def mid_point(self):
"""
:return: the parameter at the mid point of the curve, and
its corresponding gp_Pnt
"""
_min, _max = self.domain()
_mid = (_min+_max) / 2.
return _mid, self.adaptor.Value(_mid)
def divide_by_number_of_points(self, n_pts, lbound=None, ubound=None):
'''returns a nested list of parameters and points on the edge
at the requested interval [(param, gp_Pnt),...]
'''
_lbound, _ubound = self.domain()
if lbound:
_lbound = lbound
elif ubound:
_ubound = ubound
# minimally two points or a Standard_ConstructionError is raised
if n_pts <= 1:
n_pts = 2
try:
npts = GCPnts_UniformAbscissa(self.adaptor, n_pts, _lbound, _ubound)
except:
print "Warning : GCPnts_UniformAbscissa failed"
if npts.IsDone():
tmp = []
for i in xrange(1, npts.NbPoints()+1):
param = npts.Parameter(i)
pnt = self.adaptor.Value(param)
tmp.append((param, pnt))
return tmp
else:
return None
@property
def weight(self, indx):
'''descriptor sets or gets the weight of a control point at the index
'''
#TODO self.curve has to be generalized to a bspline for this...
raise NotImplementedError
def control_pt_coord(self, indx):
#TODO confused; vertices != control points
'''descriptor setting or getting the coordinate of a
control point at indx'''
raise NotImplementedError
def greville_points(self):
#TODO confused; vertices != greville points
'''descriptor setting or getting the coordinate
of a control point at indx'''
raise NotImplementedError
def control_point(self, indx, pt=None):
'''gets or sets the coordinate of the control point
'''
raise NotImplementedError
def __eq__(self, other):
if hasattr(other, 'topo'):
return self.IsEqual(other)
else:
return self.IsEqual(other)
def __ne__(self, other):
return not(self.__eq__(other))
def first_vertex(self):
# TODO: should return Vertex, not TopoDS_Vertex
return topexp.FirstVertex(self)
def last_vertex(self):
return topexp.LastVertex(self)
def common_vertex(self, edge):
vert = TopoDS_Vertex()
if topexp.CommonVertex(self, edge, vert):
return vert
else:
return False
def as_vec(self):
if self.is_line():
first, last = map(vertex2pnt, [self.first_vertex(), self.last_vertex()])
return gp_Vec(first, last)
else:
raise ValueError("edge is not a line, hence no meaningful vector can be returned")
#===========================================================================
# Curve.
#===========================================================================
def parameter_to_point(self, u):
'''returns the coordinate at parameter u
'''
return self.adaptor.Value(u)
def point_to_parameter(self, coord):
'''returns the parameters / pnt on edge at world coordinate `coord`
'''
raise NotImplementedError
def transform(self, transform):
'''affine transform
'''
raise NotImplementedError
def fix_continuity(self, continuity):
"""
splits an edge to achieve a level of continuity
:param continuity: GeomAbs_C*
"""
return fix_continuity(self, continuity)
def continuity_to_another_curve(self, other):
'''returns continuity between self and another curve
'''
raise NotImplementedError
def continuity_from_faces(self, f1, f2):
return BRep_Tool_Continuity(self, f1, f2)
#===========================================================================
# Curve.loop
#===========================================================================
def iter_control_points(self):
'''iterator over the control points
'''
raise NotImplementedError
def iter_weights(self):
'''iterator over the weights
'''
raise NotImplementedError
#===========================================================================
# Curve.
#===========================================================================
def is_trimmed(self):
'''checks if curve is trimmed
check if the underlying geom type is trimmed
'''
raise NotImplementedError
def is_line(self, tolerance=None):
'''checks if the curve is planar within a tolerance
'''
if self.nb_knots() == 2 and self.nb_poles() == 2:
return True
else:
return False
def is_seam(self, face):
"""
:return: True if the edge has two pcurves on one surface
( in the case of a sphere for example... )
"""
sae = ShapeAnalysis_Edge()
return sae.IsSeam(self, face)
def is_edge_on_face(self, face):
'''checks whether curve lies on a surface or a face
'''
return ShapeAnalysis_Edge().HasPCurve(self, face)
def on_edge(self, edge):
'''checks if the curve lies on an edge or a border
'''
raise NotImplementedError
#===========================================================================
# Curve.graphic
#===========================================================================
def show(self, poles=False, vertices=False, knots=False):
'''
poles, knots, should render all slightly different.
here's how...
http://www.opencascade.org/org/forum/thread_1125/
'''
show = super(Edge, self).show()
def update(self, context):
'''updates the graphic presentation when called
'''
raise NotImplementedError
@property
def color(self, *rgb):
'''color descriptor for the curve
'''
raise NotImplementedError
if __name__ == '__main__':
from OCC.BRepPrimAPI import *
from Topology import Topo
b = BRepPrimAPI_MakeBox(10, 20, 30).Shape()
t = Topo(b)
ed = t.edges().next()
my_e = Edge(ed)
print(my_e.tolerance)