/
wires.py
509 lines (437 loc) · 18.7 KB
/
wires.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
# ***************************************************************************
# * Copyright (c) 2009, 2010 Yorik van Havre <yorik@uncreated.net> *
# * Copyright (c) 2009, 2010 Ken Cline <cline@frii.com> *
# * *
# * This file is part of the FreeCAD CAx development system. *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * FreeCAD 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 Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with FreeCAD; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
"""Provides various functions to work with wires."""
## @package wires
# \ingroup draftgeoutils
# \brief Provides various functions to work with wires.
import math
import lazy_loader.lazy_loader as lz
import FreeCAD as App
import DraftVecUtils
import WorkingPlane
import FreeCAD as App
from draftgeoutils.general import geomType, vec, precision
from draftgeoutils.geometry import get_normal
from draftgeoutils.edges import findMidpoint, isLine
# Delay import of module until first use because it is heavy
Part = lz.LazyLoader("Part", globals(), "Part")
## \addtogroup draftgeoutils
# @{
def findWires(edgeslist):
"""Find wires in a list of edges."""
return [Part.Wire(e) for e in Part.sortEdges(edgeslist)]
def findWiresOld2(edgeslist):
"""Find connected wires in the given list of edges."""
def touches(e1, e2):
"""Return True if two edges connect at the edges."""
if len(e1.Vertexes) < 2:
return False
if len(e2.Vertexes) < 2:
return False
if DraftVecUtils.equals(e1.Vertexes[0].Point,
e2.Vertexes[0].Point):
return True
if DraftVecUtils.equals(e1.Vertexes[0].Point,
e2.Vertexes[-1].Point):
return True
if DraftVecUtils.equals(e1.Vertexes[-1].Point,
e2.Vertexes[0].Point):
return True
if DraftVecUtils.equals(e1.Vertexes[-1].Point,
e2.Vertexes[-1].Point):
return True
return False
edges = edgeslist[:]
wires = []
lost = []
while edges:
e = edges[0]
if not wires:
# create first group
edges.remove(e)
wires.append([e])
else:
found = False
for w in wires:
if not found:
for we in w:
if touches(e, we):
edges.remove(e)
w.append(e)
found = True
break
if not found:
if e in lost:
# we already tried this edge, and still nothing
edges.remove(e)
wires.append([e])
lost = []
else:
# put to the end of the list
edges.remove(e)
edges.append(e)
lost.append(e)
nwires = []
for w in wires:
try:
wi = Part.Wire(w)
except Part.OCCError:
print("couldn't join some edges")
else:
nwires.append(wi)
return nwires
def findWiresOld(edges):
"""Return a list of lists containing edges that can be connected.
Find connected edges in the list.
"""
raise DeprecationWarning("This function shouldn't be called anymore. "
"Use findWires() instead")
def verts(shape):
return [shape.Vertexes[0].Point,
shape.Vertexes[-1].Point]
def group(shapes):
shapesIn = shapes[:]
shapesOut = [shapesIn.pop()]
changed = False
for s in shapesIn:
if len(s.Vertexes) < 2:
continue
else:
clean = True
for v in verts(s):
for i in range(len(shapesOut)):
if clean and (v in verts(shapesOut[i])):
shapesOut[i] = Part.Wire(shapesOut[i].Edges
+ s.Edges)
changed = True
clean = False
if clean:
shapesOut.append(s)
return changed, shapesOut
working = True
edgeSet = edges
while working:
result = group(edgeSet)
working = result[0]
edgeSet = result[1]
return result[1]
def flattenWire(wire):
"""Force a wire to get completely flat along its normal."""
n = get_normal(wire)
# for backward compatibility with previous getNormal implementation
if n is None:
n = App.Vector(0, 0, 1)
o = wire.Vertexes[0].Point
plane = WorkingPlane.plane()
plane.alignToPointAndAxis(o, n, 0)
verts = [o]
for v in wire.Vertexes[1:]:
verts.append(plane.projectPoint(v.Point))
if wire.isClosed():
verts.append(o)
w = Part.makePolygon(verts)
return w
def superWire(edgeslist, closed=False):
"""Force a wire between edges that don't have coincident endpoints.
Forces a wire between edges that don't necessarily
have coincident endpoints. If closed=True, the wire will always be closed.
"""
def median(v1, v2):
vd = v2.sub(v1)
vd.scale(0.5, 0.5, 0.5)
return v1.add(vd)
edges = Part.__sortEdges__(edgeslist)
print(edges)
newedges = []
for i in range(len(edges)):
curr = edges[i]
if i == 0:
if closed:
prev = edges[-1]
else:
prev = None
else:
prev = edges[i - 1]
if i == (len(edges) - 1):
if closed:
_next = edges[0]
else:
_next = None
else:
_next = edges[i+1]
print(i, prev, curr, _next)
if prev:
if curr.Vertexes[0].Point == prev.Vertexes[-1].Point:
p1 = curr.Vertexes[0].Point
else:
p1 = median(curr.Vertexes[0].Point, prev.Vertexes[-1].Point)
else:
p1 = curr.Vertexes[0].Point
if _next:
if curr.Vertexes[-1].Point == _next.Vertexes[0].Point:
p2 = _next.Vertexes[0].Point
else:
p2 = median(curr.Vertexes[-1].Point, _next.Vertexes[0].Point)
else:
p2 = curr.Vertexes[-1].Point
if geomType(curr) == "Line":
print("line", p1, p2)
newedges.append(Part.LineSegment(p1, p2).toShape())
elif geomType(curr) == "Circle":
p3 = findMidpoint(curr)
print("arc", p1, p3, p2)
newedges.append(Part.Arc(p1, p3, p2).toShape())
else:
print("Cannot superWire edges that are not lines or arcs")
return None
print(newedges)
return Part.Wire(newedges)
def isReallyClosed(wire):
"""Check if a wire is really closed."""
# TODO yet to find out why not use wire.isClosed() direct,
# in isReallyClosed(wire)
# Remark out below - Found not true if a vertex is used again
# in a wire in sketch (e.g. wire with shape like 'd', 'b', 'g', ...)
# if len(wire.Edges) == len(wire.Vertexes): return True
# Found cases where Wire[-1] are not 'last' vertexes
# e.g. Part.Wire( Part.__sortEdges__(<Rectangle Geometries>.toShape()))
# aboveWire.isClosed() == True, but Wire[-1] are the 3rd vertex
# for the rectangle - use Edges[i].Vertexes[0/1] instead
length = len(wire.Edges)
# Test if it is full circle / ellipse first
if length == 1:
if len(wire.Edges[0].Vertexes) == 1:
return True # This is a closed wire - full circle/ellipse
else:
# TODO Should be False if 1 edge but not single vertex, correct?
# No need to test further below.
return False
# If more than 1 edge, further test below
v1 = wire.Edges[0].Vertexes[0].Point # v1 = wire.Vertexes[0].Point
v2 = wire.Edges[length-1].Vertexes[1].Point # v2 = wire.Vertexes[-1].Point
if DraftVecUtils.equals(v1, v2):
return True
return False
def curvetowire(obj, steps):
"""Discretize the object and return a list of edges."""
points = obj.copy().discretize(steps)
p0 = points[0]
edgelist = []
for p in points[1:]:
edge = Part.makeLine((p0.x, p0.y, p0.z), (p.x, p.y, p.z))
edgelist.append(edge)
p0 = p
return edgelist
def curvetosegment(curve, seglen):
"""Discretize the curve and return a list of edges."""
points = curve.discretize(seglen)
p0 = points[0]
edgelist = []
for p in points[1:]:
edge = Part.makeLine((p0.x, p0.y, p0.z), (p.x, p.y, p.z))
edgelist.append(edge)
p0 = p
return edgelist
def rebaseWire(wire, vidx=0):
"""Return a copy of the wire with the first vertex indicated by the index.
Return a new wire which is a copy of the current wire,
but where the first vertex is the vertex indicated by the given
index vidx, starting from 1.
0 will return an exact copy of the wire.
"""
if vidx < 1:
return wire
if vidx > len(wire.Vertexes):
# print("Vertex index above maximum")
return wire
# This can be done in one step
return Part.Wire(wire.Edges[vidx-1:] + wire.Edges[:vidx-1])
def removeInterVertices(wire):
"""Remove middle vertices from a straight wire and return a new wire.
Remove unneeded vertices, those that are in the middle of a straight line,
from a wire, return a new wire.
"""
_pre = precision()
edges = Part.__sortEdges__(wire.Edges)
nverts = []
def getvec(v1, v2):
if not abs(round(v1.getAngle(v2), _pre) in [0, round(math.pi, _pre)]):
nverts.append(edges[i].Vertexes[-1].Point)
for i in range(len(edges) - 1):
vA = vec(edges[i])
vB = vec(edges[i + 1])
getvec(vA, vB)
vA = vec(edges[-1])
vB = vec(edges[0])
getvec(vA, vB)
if nverts:
if wire.isClosed():
nverts.append(nverts[0])
w = Part.makePolygon(nverts)
return w
else:
return wire
def cleanProjection(shape, tessellate=True, seglength=0.05):
"""Return a compound of edges, optionally tessellate ellipses, splines
and bezcurves.
The function was formerly used to workaround bugs in the projection
algorithm. These bugs have since been fixed. Now the function is only
used when tessellation of ellipses, splines and bezcurves is required
(DXF output and Draft_Shape2DView).
"""
oldedges = shape.Edges
newedges = []
for e in oldedges:
typ = geomType(e)
try:
if typ in ["Line", "Circle"]:
newedges.append(e)
elif typ == "Ellipse":
if tessellate:
newedges.append(Part.Wire(curvetowire(e, seglength)))
else:
newedges.append(e)
elif typ in ["BSplineCurve", "BezierCurve"]:
if isLine(e.Curve):
line = Part.LineSegment(e.Vertexes[0].Point,
e.Vertexes[-1].Point)
newedges.append(line)
elif tessellate:
newedges.append(Part.Wire(curvetowire(e, seglength)))
else:
newedges.append(e)
else:
newedges.append(e)
except Part.OCCError:
print("Debug: error cleaning edge ", e)
return Part.makeCompound(newedges)
def tessellateProjection(shape, seglen):
"""Return projection with BSplines and Ellipses broken into line segments.
Useful for exporting projected views to DXF files.
"""
oldedges = shape.Edges
newedges = []
for e in oldedges:
try:
if geomType(e) == "Line":
newedges.append(e.Curve.toShape())
elif geomType(e) == "Circle":
newedges.append(e.Curve.toShape())
elif geomType(e) == "Ellipse":
newedges.append(Part.Wire(curvetosegment(e, seglen)))
elif geomType(e) == "BSplineCurve":
newedges.append(Part.Wire(curvetosegment(e, seglen)))
else:
newedges.append(e)
except Part.OCCError:
print("Debug: error cleaning edge ", e)
return Part.makeCompound(newedges)
def get_placement_perpendicular_to_wire(wire):
"""Return the placement whose base is the wire's first vertex and it's z axis aligned to the wire's tangent."""
pl = App.Placement()
if wire.Length > 0.0:
pl.Base = wire.OrderedVertexes[0].Point
first_edge = wire.OrderedEdges[0]
if first_edge.Orientation == "Forward":
zaxis = -first_edge.tangentAt(first_edge.FirstParameter)
else:
zaxis = first_edge.tangentAt(first_edge.LastParameter)
pl.Rotation = App.Rotation(App.Vector(1, 0, 0), App.Vector(0, 0, 1), zaxis, "ZYX")
else:
App.Console.PrintError("debug: get_placement_perpendicular_to_wire called with a zero-length wire.\n")
return pl
def get_extended_wire(wire, offset_start, offset_end):
"""Return a wire trimmed (negative offset) or extended (positive offset) at its first vertex, last vertex or both ends.
get_extended_wire(wire, -100.0, 0.0) -> returns a copy of the wire with its first 100 mm removed
get_extended_wire(wire, 0.0, 100.0) -> returns a copy of the wire extended by 100 mm after it's last vertex
"""
if min(offset_start, offset_end, offset_start + offset_end) <= -wire.Length:
App.Console.PrintError("debug: get_extended_wire error, wire's length insufficient for trimming.\n")
return wire
if offset_start < 0: # Trim the wire from the first vertex
offset_start = -offset_start
out_edges = []
for edge in wire.OrderedEdges:
if offset_start >= edge.Length: # Remove entire edge
offset_start -= edge.Length
elif round(offset_start, precision()) > 0: # Split edge, to remove the required length
if edge.Orientation == "Forward":
new_edge = edge.split(edge.getParameterByLength(offset_start)).OrderedEdges[1]
else:
new_edge = edge.split(edge.getParameterByLength(edge.Length - offset_start)).OrderedEdges[0]
new_edge.Placement = edge.Placement # Strangely, edge.split discards the placement and orientation
new_edge.Orientation = edge.Orientation
out_edges.append(new_edge)
offset_start = 0
else: # Keep the remaining entire edges
out_edges.append(edge)
wire = Part.Wire(out_edges)
elif offset_start > 0: # Extend the first edge along its normal
first_edge = wire.OrderedEdges[0]
if first_edge.Orientation == "Forward":
start, end = first_edge.FirstParameter, first_edge.LastParameter
vec = first_edge.tangentAt(start).multiply(offset_start)
else:
start, end = first_edge.LastParameter, first_edge.FirstParameter
vec = -first_edge.tangentAt(start).multiply(offset_start)
if geomType(first_edge) == "Line": # Replace first edge with the extended new edge
new_edge = Part.LineSegment(first_edge.valueAt(start).sub(vec), first_edge.valueAt(end)).toShape()
wire = Part.Wire([new_edge] + wire.OrderedEdges[1:])
else: # Add a straight edge before the first vertex
new_edge = Part.LineSegment(first_edge.valueAt(start).sub(vec), first_edge.valueAt(start)).toShape()
wire = Part.Wire([new_edge] + wire.OrderedEdges)
if offset_end < 0: # Trim the wire from the last vertex
offset_end = -offset_end
out_edges = []
for edge in reversed(wire.OrderedEdges):
if offset_end >= edge.Length: # Remove entire edge
offset_end -= edge.Length
elif round(offset_end, precision()) > 0: # Split edge, to remove the required length
if edge.Orientation == "Forward":
new_edge = edge.split(edge.getParameterByLength(edge.Length - offset_end)).OrderedEdges[0]
else:
new_edge = edge.split(edge.getParameterByLength(offset_end)).OrderedEdges[1]
new_edge.Placement = edge.Placement # Strangely, edge.split discards the placement and orientation
new_edge.Orientation = edge.Orientation
out_edges.insert(0, new_edge)
offset_end = 0
else: # Keep the remaining entire edges
out_edges.insert(0, edge)
wire = Part.Wire(out_edges)
elif offset_end > 0: # Extend the last edge along its normal
last_edge = wire.OrderedEdges[-1]
if last_edge.Orientation == "Forward":
start, end = last_edge.FirstParameter, last_edge.LastParameter
vec = last_edge.tangentAt(end).multiply(offset_end)
else:
start, end = last_edge.LastParameter, last_edge.FirstParameter
vec = -last_edge.tangentAt(end).multiply(offset_end)
if geomType(last_edge) == "Line": # Replace last edge with the extended new edge
new_edge = Part.LineSegment(last_edge.valueAt(start), last_edge.valueAt(end).add(vec)).toShape()
wire = Part.Wire(wire.OrderedEdges[:-1] + [new_edge])
else: # Add a straight edge after the last vertex
new_edge = Part.LineSegment(last_edge.valueAt(end), last_edge.valueAt(end).add(vec)).toShape()
wire = Part.Wire(wire.OrderedEdges + [new_edge])
return wire
## @}