481 lines
20 KiB
Python
481 lines
20 KiB
Python
"""B-rep di un .prt Creo: superfici, contorni e spigoli letti dal file, senza Creo, ed esportati
|
|||
|
|
in STEP per poterli vedere in qualsiasi visualizzatore. Reverse engineering: formato e prove in
|
||
|
|
docs/formato-prt-brep.md.
|
||
|
|
|
||
|
|
python scripts/psb/brep.py <file.prt.N> riepilogo + controllo di coerenza
|
||
|
|
python scripts/psb/brep.py <file.prt.N> --step out.stp esporta il B-rep in STEP
|
||
|
|
python scripts/psb/brep.py <file.prt.N> --check ref.stp confronta, faccia per faccia, con lo STEP di Creo
|
||
|
|
"""
|
||
|
|
import math, os, sys, tempfile
|
||
|
|
|
||
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||
|
|
import prt, psb
|
||
|
|
|
||
|
|
PLANE, CYL, CONE, TORUS, SPL = 34, 36, 37, 38, 40 # geom_type (44 = tab_cyl, non gestito)
|
||
|
|
QUILT = 57 # topol_ref_data.list_type: 57 = quilt, 98 = solido
|
||
|
|
TOL = 1e-4 # mm
|
||
|
|
|
||
|
|
|
||
|
|
# --- lettura ---------------------------------------------------------------
|
||
|
|
def section(d, secs, name):
|
||
|
|
o, l, f = secs[name]
|
||
|
|
if f[2] != '9':
|
||
|
|
raise SystemExit(f"{name} e' di tipo {f[2]} (file Wildfire o sezione cifrata): non leggibile")
|
||
|
|
p, root, e = psb.parse(d[o:o + l])
|
||
|
|
if e is not None:
|
||
|
|
raise SystemExit(f"{name} non letta fino in fondo: {e!r}")
|
||
|
|
return root[1]
|
||
|
|
|
||
|
|
|
||
|
|
def walk(v):
|
||
|
|
if isinstance(v, psb.Node):
|
||
|
|
for n, x in v:
|
||
|
|
yield n, x
|
||
|
|
yield from walk(x)
|
||
|
|
elif isinstance(v, psb.Arr):
|
||
|
|
for x in v:
|
||
|
|
yield from walk(x)
|
||
|
|
|
||
|
|
|
||
|
|
def load(path):
|
||
|
|
"""(superfici, spigoli) della geometria visibile. Gli spigoli stanno tutti in VisibGeom; le
|
||
|
|
superfici quasi: quelle a cui e' agganciato un asse di riferimento stanno in ActDatums, con lo
|
||
|
|
stesso formato e nella stessa catena next_geom_ptr. Si tengono solo quelle con un contorno."""
|
||
|
|
d, secs, _ = prt.load(path)
|
||
|
|
g = section(d, secs, 'VisibGeom').get('active_geom')
|
||
|
|
srf = list(g.get('srf_array') or [])
|
||
|
|
if 'ActDatums' in secs:
|
||
|
|
for n, v in walk(section(d, secs, 'ActDatums')):
|
||
|
|
if n == 'srf_array' and v:
|
||
|
|
srf += v
|
||
|
|
return [s for s in srf if contours(s)], g.get('crv_array') or []
|
||
|
|
|
||
|
|
|
||
|
|
def prim(s):
|
||
|
|
for n, v in s:
|
||
|
|
if n.startswith('srf_prim_ptr'):
|
||
|
|
return v
|
||
|
|
|
||
|
|
|
||
|
|
def contours(s):
|
||
|
|
"""[(primo spigolo, trv, inviluppo UV)]: frst_cntr_ptr e i next_cntr_ptr non nulli (nel file
|
||
|
|
sono una lista concatenata; il parser li rende come campi allo stesso livello)"""
|
||
|
|
return [(v.get('frst_cntr_crv_hdr_ptr'), v.get('trv'), v.get('envlp'))
|
||
|
|
for n, v in s if n in ('frst_cntr_ptr', 'next_cntr_ptr') and v is not None]
|
||
|
|
|
||
|
|
|
||
|
|
# --- geometria -------------------------------------------------------------
|
||
|
|
def sub(a, b):
|
||
|
|
return tuple(x - y for x, y in zip(a, b))
|
||
|
|
|
||
|
|
|
||
|
|
def add(a, b, k=1.0):
|
||
|
|
return tuple(x + k * y for x, y in zip(a, b))
|
||
|
|
|
||
|
|
|
||
|
|
def dot(a, b):
|
||
|
|
return sum(x * y for x, y in zip(a, b))
|
||
|
|
|
||
|
|
|
||
|
|
def cross(a, b):
|
||
|
|
return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])
|
||
|
|
|
||
|
|
|
||
|
|
def norm(a):
|
||
|
|
return math.sqrt(dot(a, a))
|
||
|
|
|
||
|
|
|
||
|
|
def unit(a):
|
||
|
|
n = norm(a)
|
||
|
|
return tuple(x / n for x in a)
|
||
|
|
|
||
|
|
|
||
|
|
def frame(p):
|
||
|
|
"""local_sys -> (asse x, asse y, asse z, origine). Nel file ci sono le RIGHE di R in
|
||
|
|
mondo = origine + R * locale: gli assi locali sono le colonne."""
|
||
|
|
*R, o = p.get('local_sys')
|
||
|
|
return tuple(tuple(R[i][j] for i in range(3)) for j in range(3)) + (tuple(o),)
|
||
|
|
|
||
|
|
|
||
|
|
def xyz(s, u, v):
|
||
|
|
"""punto 3D della superficie s ai parametri (u, v)"""
|
||
|
|
p = prim(s)
|
||
|
|
t = s.get('geom_type')
|
||
|
|
if t == SPL:
|
||
|
|
return bicubic(p, u, v)
|
||
|
|
if t == PLANE:
|
||
|
|
a, b, c = u, v, 0.0
|
||
|
|
elif t == CYL:
|
||
|
|
r = p.get('radius')
|
||
|
|
a, b, c = r * math.cos(u), r * math.sin(u), v
|
||
|
|
elif t == CONE: # vertice nell'origine, v = quota lungo l'asse
|
||
|
|
r = v * math.tan(p.get('half_angle'))
|
||
|
|
a, b, c = r * math.cos(u), r * math.sin(u), v
|
||
|
|
elif t == TORUS: # u attorno all'asse, v attorno al tubo
|
||
|
|
r = p.get('radius1') + p.get('radius2') * math.cos(v)
|
||
|
|
a, b, c = r * math.cos(u), r * math.sin(u), p.get('radius2') * math.sin(v)
|
||
|
|
else:
|
||
|
|
raise ValueError(f"geom_type {t} non gestito")
|
||
|
|
ex, ey, ez, o = frame(p)
|
||
|
|
return tuple(o[i] + a * ex[i] + b * ey[i] + c * ez[i] for i in range(3))
|
||
|
|
|
||
|
|
|
||
|
|
def hermite(t):
|
||
|
|
return (2 * t**3 - 3 * t**2 + 1, -2 * t**3 + 3 * t**2, t**3 - 2 * t**2 + t, t**3 - t**2)
|
||
|
|
|
||
|
|
|
||
|
|
def one_patch(p):
|
||
|
|
if list(p.get('u_params')) != [0.0, 1.0] or list(p.get('v_params')) != [0.0, 1.0]:
|
||
|
|
raise ValueError("splsrf con piu' di una maglia: non gestita")
|
||
|
|
return tuple(p.get(k) for k in ('i_points', 'end_u_tangts', 'end_v_tangts', 'end_uv_deriv'))
|
||
|
|
|
||
|
|
|
||
|
|
def bicubic(p, u, v):
|
||
|
|
"""pezza di Hermite bicubica su una sola maglia; l'angolo (a, b) sta all'indice 2a + b"""
|
||
|
|
P, Tu, Tv, Tuv = one_patch(p)
|
||
|
|
hu, hv = hermite(u), hermite(v)
|
||
|
|
out = []
|
||
|
|
for i in range(3):
|
||
|
|
acc = 0.0
|
||
|
|
for a in range(2):
|
||
|
|
for b in range(2):
|
||
|
|
k = 2 * a + b
|
||
|
|
acc += (hu[a] * hv[b] * P[k][i] + hu[a + 2] * hv[b] * Tu[k][i]
|
||
|
|
+ hu[a] * hv[b + 2] * Tv[k][i] + hu[a + 2] * hv[b + 2] * Tuv[k][i])
|
||
|
|
out.append(acc)
|
||
|
|
return tuple(out)
|
||
|
|
|
||
|
|
|
||
|
|
def bezier_net(p):
|
||
|
|
"""la stessa pezza come 4x4 punti di controllo di Bezier (per lo STEP)"""
|
||
|
|
P, Tu, Tv, Tuv = one_patch(p)
|
||
|
|
net = [[None] * 4 for _ in range(4)]
|
||
|
|
for a in range(2):
|
||
|
|
for b in range(2):
|
||
|
|
k, su, sv = 2 * a + b, 1 - 2 * a, 1 - 2 * b
|
||
|
|
for i, ku in ((3 * a, 0), (3 * a + su, su / 3)):
|
||
|
|
for j, kv in ((3 * b, 0), (3 * b + sv, sv / 3)):
|
||
|
|
net[i][j] = add(add(add(P[k], Tu[k], ku), Tv[k], kv), Tuv[k], ku * kv)
|
||
|
|
return net
|
||
|
|
|
||
|
|
|
||
|
|
# --- topologia -------------------------------------------------------------
|
||
|
|
def loop(S_id, first, C):
|
||
|
|
"""spigoli di un contorno: [(id, lato)]. Ogni spigolo ha due lati (le due superfici che separa);
|
||
|
|
si segue next_crv_hdr_ptr del lato che guarda la superficie S_id fino a tornare al primo."""
|
||
|
|
out, e = [], first
|
||
|
|
while True:
|
||
|
|
c = C[e]
|
||
|
|
k = 0 if c.get('crv_hdr_geom_ptr[0]') == S_id else 1
|
||
|
|
if c.get(f'crv_hdr_geom_ptr[{k}]') != S_id:
|
||
|
|
raise ValueError(f"spigolo {e} non tocca la superficie {S_id}")
|
||
|
|
out.append((e, k))
|
||
|
|
e = c.get(f'next_crv_hdr_ptr[{k}]')
|
||
|
|
if e == first:
|
||
|
|
return out
|
||
|
|
if len(out) > len(C):
|
||
|
|
raise ValueError(f"contorno di {S_id} non chiuso")
|
||
|
|
|
||
|
|
|
||
|
|
def faces(srf, C):
|
||
|
|
"""[(superficie, [contorno esterno, fori...])]: una faccia per contorno esterno (trv = 1),
|
||
|
|
perche' una superficie Creo puo' avere piu' regioni staccate. Un foro (trv = -1) va al
|
||
|
|
contorno esterno piu' piccolo il cui inviluppo UV lo contiene."""
|
||
|
|
out = []
|
||
|
|
for s in srf:
|
||
|
|
groups = [(c, [c]) for c in contours(s) if c[1] == 1]
|
||
|
|
for h in (c for c in contours(s) if c[1] != 1):
|
||
|
|
(a0, b0), (a1, b1) = h[2]
|
||
|
|
inside = [g for g in groups if g[0][2][0][0] - TOL <= a0 and g[0][2][0][1] - TOL <= b0
|
||
|
|
and g[0][2][1][0] + TOL >= a1 and g[0][2][1][1] + TOL >= b1]
|
||
|
|
if not inside:
|
||
|
|
raise ValueError(f"superficie {s.get('geom_id')}: foro senza contorno esterno")
|
||
|
|
min(inside, key=lambda g: (g[0][2][1][0] - g[0][2][0][0]) * (g[0][2][1][1] - g[0][2][0][1]))[1].append(h)
|
||
|
|
out += [(s, [loop(s.get('geom_id'), c[0], C) for c in cl]) for _, cl in groups]
|
||
|
|
return out
|
||
|
|
|
||
|
|
|
||
|
|
def side_points(c, S, k):
|
||
|
|
s = S.get(c.get(f'crv_hdr_geom_ptr[{k}]'))
|
||
|
|
return [xyz(s, q[2 * k], q[2 * k + 1]) for q in c.get('crv_pnt_arr')] if s else None
|
||
|
|
|
||
|
|
|
||
|
|
def edge3d(c, S, n=8):
|
||
|
|
"""polilinea 3D fitta dello spigolo. Il file ha solo campioni (u, v) sulle due superfici: si
|
||
|
|
interpolano in UV (Catmull-Rom) sulla superficie curva, dove cerchi e generatrici sono rette."""
|
||
|
|
# ponytail: fra due superfici curve qualsiasi e' un'approssimazione fra i campioni; se serve
|
||
|
|
# la curva esatta va calcolata l'intersezione delle due superfici
|
||
|
|
sides = [(k, S[c.get(f'crv_hdr_geom_ptr[{k}]')]) for k in (0, 1) if c.get(f'crv_hdr_geom_ptr[{k}]') in S]
|
||
|
|
k, s = min(sides, key=lambda t: {CYL: 0, CONE: 0, TORUS: 0, PLANE: 1}.get(t[1].get('geom_type'), 2))
|
||
|
|
uv = [(q[2 * k], q[2 * k + 1]) for q in c.get('crv_pnt_arr')]
|
||
|
|
m = [sub(uv[min(i + 1, len(uv) - 1)], uv[max(i - 1, 0)]) for i in range(len(uv))]
|
||
|
|
m = [tuple(v / 2 for v in x) if 0 < i < len(uv) - 1 else x for i, x in enumerate(m)]
|
||
|
|
out = []
|
||
|
|
for i in range(len(uv) - 1):
|
||
|
|
for j in range(n):
|
||
|
|
h = hermite(j / n)
|
||
|
|
out.append(tuple(h[0] * uv[i][d] + h[1] * uv[i + 1][d] + h[2] * m[i][d] + h[3] * m[i + 1][d] for d in range(2)))
|
||
|
|
out.append(uv[-1])
|
||
|
|
return [xyz(s, u, v) for u, v in out]
|
||
|
|
|
||
|
|
|
||
|
|
def classify(P):
|
||
|
|
"""('line',) | ('circle', centro, asse, raggio) | None, dai punti della polilinea"""
|
||
|
|
a, b = P[0], P[-1]
|
||
|
|
closed = math.dist(a, b) < TOL
|
||
|
|
if not closed:
|
||
|
|
d = unit(sub(b, a))
|
||
|
|
if all(norm(cross(sub(p, a), d)) < TOL for p in P):
|
||
|
|
return ('line',)
|
||
|
|
if len(P) < 3:
|
||
|
|
return None
|
||
|
|
m, e = (P[len(P) // 3], P[2 * len(P) // 3]) if closed else (P[len(P) // 2], b)
|
||
|
|
ab, ac = sub(m, a), sub(e, a)
|
||
|
|
n = cross(ab, ac)
|
||
|
|
if norm(n) < 1e-9:
|
||
|
|
return None
|
||
|
|
c = add(a, add(tuple(x * dot(ac, ac) for x in cross(n, ab)), cross(ac, n), dot(ab, ab)), 1 / (2 * dot(n, n)))
|
||
|
|
r, n = math.dist(a, c), unit(n)
|
||
|
|
if all(abs(math.dist(p, c) - r) < TOL and abs(dot(sub(p, c), n)) < TOL for p in P):
|
||
|
|
return ('circle', c, n, r) # n orientato cosi' che a -> m -> e sia antiorario
|
||
|
|
return None
|
||
|
|
|
||
|
|
|
||
|
|
# --- STEP ------------------------------------------------------------------
|
||
|
|
def num(x):
|
||
|
|
x = float(f"{x:.12g}") + 0.0
|
||
|
|
if not math.isfinite(x):
|
||
|
|
raise ValueError("numero non decodificato nel B-rep")
|
||
|
|
s = repr(x)
|
||
|
|
if 'e' in s:
|
||
|
|
m, e = s.split('e')
|
||
|
|
s = (m if '.' in m else m + '.') + 'E' + e
|
||
|
|
return s
|
||
|
|
|
||
|
|
|
||
|
|
class Step:
|
||
|
|
def __init__(s):
|
||
|
|
s.out = []
|
||
|
|
|
||
|
|
def add(s, text):
|
||
|
|
s.out.append(text)
|
||
|
|
return f"#{len(s.out)}"
|
||
|
|
|
||
|
|
def pt(s, p):
|
||
|
|
return s.add(f"CARTESIAN_POINT('',({','.join(num(x) for x in p)}))")
|
||
|
|
|
||
|
|
def dir(s, d):
|
||
|
|
return s.add(f"DIRECTION('',({','.join(num(x) for x in d)}))")
|
||
|
|
|
||
|
|
def ax(s, o, z, x):
|
||
|
|
return s.add(f"AXIS2_PLACEMENT_3D('',{s.pt(o)},{s.dir(z)},{s.dir(x)})")
|
||
|
|
|
||
|
|
|
||
|
|
def step_surface(st, s):
|
||
|
|
"""scrive la superficie; ritorna (riferimento, same_sense)"""
|
||
|
|
t, p = s.get('geom_type'), prim(s)
|
||
|
|
(u0, v0), (u1, v1) = s.get('envlp')
|
||
|
|
u, v = (u0 + u1) / 2, (v0 + v1) / 2
|
||
|
|
if t not in (PLANE, CYL, CONE, TORUS, SPL):
|
||
|
|
raise ValueError(f"geom_type {t} non gestito")
|
||
|
|
if t == SPL:
|
||
|
|
net = bezier_net(p)
|
||
|
|
rows = ','.join('(' + ','.join(st.pt(q) for q in row) + ')' for row in net)
|
||
|
|
ref = st.add(f"B_SPLINE_SURFACE_WITH_KNOTS('',3,3,({rows}),.UNSPECIFIED.,.F.,.F.,.F.,(4,4),(4,4),(0.,1.),(0.,1.),.UNSPECIFIED.)")
|
||
|
|
return ref, s.get('orient') == 1
|
||
|
|
ex, ey, ez, o = frame(p)
|
||
|
|
P, h = xyz(s, u, v), 1e-4
|
||
|
|
n = cross(sub(xyz(s, u + h, v), P), sub(xyz(s, u, v + h), P)) # normale naturale di Creo
|
||
|
|
radial = sub(sub(P, o), tuple(x * dot(sub(P, o), ez) for x in ez))
|
||
|
|
if t == PLANE:
|
||
|
|
ref, nstep = st.add(f"PLANE('',{st.ax(o, ez, ex)})"), ez
|
||
|
|
elif t == CYL:
|
||
|
|
ref, nstep = st.add(f"CYLINDRICAL_SURFACE('',{st.ax(o, ez, ex)},{num(p.get('radius'))})"), radial
|
||
|
|
elif t == TORUS:
|
||
|
|
ref = st.add(f"TOROIDAL_SURFACE('',{st.ax(o, ez, ex)},{num(p.get('radius1'))},{num(p.get('radius2'))})")
|
||
|
|
c = add(o, unit(radial), p.get('radius1')) # centro del tubo sotto il punto P
|
||
|
|
nstep = sub(P, c)
|
||
|
|
elif t == CONE:
|
||
|
|
# STEP vuole un raggio > 0 nel punto di piazzamento: lo si mette a meta' della falda usata
|
||
|
|
if abs(v) < 1e-9:
|
||
|
|
raise ValueError(f"cono {s.get('geom_id')}: falda a cavallo del vertice")
|
||
|
|
z = ez if v > 0 else tuple(-x for x in ez)
|
||
|
|
ang = p.get('half_angle')
|
||
|
|
# half_angle puo' essere negativo (raggio v*tan < 0 = stessa falda vista da u + pi): STEP
|
||
|
|
# vuole raggio e angolo positivi, la superficie e' la stessa
|
||
|
|
ref = st.add(f"CONICAL_SURFACE('',{st.ax(add(o, ez, v), z, ex)},{num(abs(v * math.tan(ang)))},{num(abs(ang))})")
|
||
|
|
nstep = radial
|
||
|
|
# orient = 1: il materiale sta dietro la normale naturale. same_sense dice lo stesso della
|
||
|
|
# normale STEP: i due versi si confrontano in un punto della faccia
|
||
|
|
return ref, (s.get('orient') == 1) == (dot(n, nstep) > 0)
|
||
|
|
|
||
|
|
|
||
|
|
def new_step(name):
|
||
|
|
"""Step con l'intestazione di prodotto gia' scritta (#1-#13; #8 = forma, #13 = contesto)"""
|
||
|
|
st = Step()
|
||
|
|
for h in [
|
||
|
|
"APPLICATION_CONTEXT('automotive design')",
|
||
|
|
"APPLICATION_PROTOCOL_DEFINITION('international standard','automotive_design',2000,#1)",
|
||
|
|
"PRODUCT_CONTEXT('',#1,'mechanical')",
|
||
|
|
f"PRODUCT('{name}','{name}','',(#3))",
|
||
|
|
"PRODUCT_DEFINITION_FORMATION('','',#4)",
|
||
|
|
"PRODUCT_DEFINITION_CONTEXT('part definition',#1,'design')",
|
||
|
|
"PRODUCT_DEFINITION('design','',#5,#6)",
|
||
|
|
"PRODUCT_DEFINITION_SHAPE('','',#7)",
|
||
|
|
"(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))",
|
||
|
|
"(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))",
|
||
|
|
"(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())",
|
||
|
|
"UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-3),#9,'distance_accuracy_value','')",
|
||
|
|
"(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#12))"
|
||
|
|
"GLOBAL_UNIT_ASSIGNED_CONTEXT((#9,#10,#11))REPRESENTATION_CONTEXT('',''))",
|
||
|
|
]:
|
||
|
|
st.add(h)
|
||
|
|
return st
|
||
|
|
|
||
|
|
|
||
|
|
def save_step(path, st, name, items, note):
|
||
|
|
rep = st.add(f"SHAPE_REPRESENTATION('',({','.join(items)}),#13)")
|
||
|
|
st.add(f"SHAPE_DEFINITION_REPRESENTATION(#8,{rep})")
|
||
|
|
with open(path, 'w', encoding='ascii') as f:
|
||
|
|
f.write(f"ISO-10303-21;\nHEADER;\nFILE_DESCRIPTION(('{note}'),'2;1');\n"
|
||
|
|
f"FILE_NAME('{name}','',(''),(''),'PrepStep scripts/psb','','');\n"
|
||
|
|
"FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));\nENDSEC;\nDATA;\n")
|
||
|
|
f.writelines(f"#{i}={t};\n" for i, t in enumerate(st.out, 1))
|
||
|
|
f.write("ENDSEC;\nEND-ISO-10303-21;\n")
|
||
|
|
|
||
|
|
|
||
|
|
def write_step(path, srf, crv, name):
|
||
|
|
S = {s.get('geom_id'): s for s in srf}
|
||
|
|
C = {c.get('crv_id'): c for c in crv}
|
||
|
|
st = new_step(name)
|
||
|
|
verts = [] # [(punto, riferimento)]
|
||
|
|
|
||
|
|
def vertex(p):
|
||
|
|
for q, r in verts:
|
||
|
|
if math.dist(p, q) < TOL:
|
||
|
|
return q, r
|
||
|
|
verts.append((p, st.add(f"VERTEX_POINT('',{st.pt(p)})")))
|
||
|
|
return verts[-1]
|
||
|
|
edges, surfs, solid, quilts = {}, {}, [], {} # quilts: id della quilt -> facce
|
||
|
|
|
||
|
|
def edge(eid):
|
||
|
|
if eid not in edges:
|
||
|
|
P = edge3d(C[eid], S)
|
||
|
|
(P[0], a), (P[-1], b) = vertex(P[0]), vertex(P[-1])
|
||
|
|
# se la polilinea fitta non e' una retta o un cerchio, lo si chiede ai soli campioni del
|
||
|
|
# file, che stanno esattamente sulla curva (serve sui bordi liberi: un lato solo, piano)
|
||
|
|
k = classify(P) or (len(P) > 4 * 8 and classify(P[::8]))
|
||
|
|
if k and k[0] == 'line':
|
||
|
|
d = sub(P[-1], P[0])
|
||
|
|
cv = st.add(f"LINE('',{st.pt(P[0])},{st.add(f'VECTOR({chr(39)}{chr(39)},{st.dir(unit(d))},{num(norm(d))})')})")
|
||
|
|
elif k:
|
||
|
|
_, c, n, r = k
|
||
|
|
cv = st.add(f"CIRCLE('',{st.ax(c, n, unit(sub(P[0], c)))},{num(r)})")
|
||
|
|
else:
|
||
|
|
# ponytail: polilinea (B-spline di grado 1), basta per vedere; grado 3 se serve liscia
|
||
|
|
pts = ','.join(st.pt(p) for p in P)
|
||
|
|
mult = ','.join(['2'] + ['1'] * (len(P) - 2) + ['2'])
|
||
|
|
knots = ','.join(num(i) for i in range(len(P)))
|
||
|
|
cv = st.add(f"B_SPLINE_CURVE_WITH_KNOTS('',1,({pts}),.UNSPECIFIED.,.F.,.F.,({mult}),({knots}),.UNSPECIFIED.)")
|
||
|
|
edges[eid] = st.add(f"EDGE_CURVE('',{a},{b},{cv},.T.)")
|
||
|
|
return edges[eid]
|
||
|
|
for s, loops in faces(srf, C):
|
||
|
|
gid = s.get('geom_id')
|
||
|
|
if gid not in surfs:
|
||
|
|
surfs[gid] = step_surface(st, s)
|
||
|
|
bounds = []
|
||
|
|
for i, lp in enumerate(loops):
|
||
|
|
oes = ','.join(st.add(f"ORIENTED_EDGE('',*,*,{edge(e)},{'.T.' if C[e].get('crv_pnt_dir')[k] == 1 else '.F.'})")
|
||
|
|
for e, k in lp)
|
||
|
|
el = st.add(f"EDGE_LOOP('',({oes}))")
|
||
|
|
bounds.append(st.add(f"{'FACE_BOUND' if i else 'FACE_OUTER_BOUND'}('',{el},.T.)"))
|
||
|
|
ref, same = surfs[gid]
|
||
|
|
f = st.add(f"ADVANCED_FACE('',({','.join(bounds)}),{ref},{'.T.' if same else '.F.'})")
|
||
|
|
ref = s.get('topol_ref_data')
|
||
|
|
(quilts.setdefault(ref.get('list_id'), []) if ref.get('list_type') == QUILT else solid).append(f)
|
||
|
|
items = []
|
||
|
|
if solid:
|
||
|
|
closed = st.add(f"CLOSED_SHELL('',({','.join(solid)}))")
|
||
|
|
items.append(st.add(f"MANIFOLD_SOLID_BREP('{name}',{closed})"))
|
||
|
|
if quilts: # un guscio aperto per quilt, come fa Creo
|
||
|
|
opened = ','.join(st.add(f"OPEN_SHELL('',({','.join(fs)}))") for fs in quilts.values())
|
||
|
|
items.append(st.add(f"SHELL_BASED_SURFACE_MODEL('',({opened}))"))
|
||
|
|
save_step(path, st, name, items, 'B-rep letto dal .prt senza Creo')
|
||
|
|
return len(solid), sum(len(fs) for fs in quilts.values())
|
||
|
|
|
||
|
|
|
||
|
|
# --- controlli -------------------------------------------------------------
|
||
|
|
def coherence(srf, crv):
|
||
|
|
"""il vincolo che regge tutto: lo stesso campione, calcolato sulle due superfici che lo
|
||
|
|
spigolo separa, deve dare lo stesso punto. Ritorna (scarto massimo, spigoli fuori tolleranza)."""
|
||
|
|
S = {s.get('geom_id'): s for s in srf}
|
||
|
|
worst, bad = 0.0, []
|
||
|
|
for c in crv:
|
||
|
|
a, b = side_points(c, S, 0), side_points(c, S, 1)
|
||
|
|
if a is None or b is None:
|
||
|
|
continue # bordo libero di una quilt: un lato solo
|
||
|
|
d = max(math.dist(x, y) for x, y in zip(a, b))
|
||
|
|
if not d < TOL:
|
||
|
|
bad.append((c.get('crv_id'), d))
|
||
|
|
elif d > worst:
|
||
|
|
worst = d
|
||
|
|
return worst, bad
|
||
|
|
|
||
|
|
|
||
|
|
def compare(mine, ref):
|
||
|
|
"""confronto fra due STEP: facce abbinate per contorni (estremi degli spigoli, con verso)"""
|
||
|
|
import stepread
|
||
|
|
import collections
|
||
|
|
|
||
|
|
def R(p):
|
||
|
|
return tuple(round(x, 3) + 0.0 for x in p)
|
||
|
|
|
||
|
|
def key(f):
|
||
|
|
return frozenset(frozenset((R(a), R(b)) for a, b, *_ in lp) for lp in f['loops'])
|
||
|
|
A, B = stepread.faces(mine), stepread.faces(ref)
|
||
|
|
idx = {key(f): f for f in B}
|
||
|
|
res = collections.Counter()
|
||
|
|
curves = collections.Counter()
|
||
|
|
for f in A:
|
||
|
|
g = idx.get(key(f))
|
||
|
|
if g is None:
|
||
|
|
res['facce senza corrispondente'] += 1
|
||
|
|
continue
|
||
|
|
res['facce abbinate (stessi contorni, stesso verso)'] += 1
|
||
|
|
res[' stesso tipo di superficie'] += f['surf'] == g['surf']
|
||
|
|
res[' stesso verso (same_sense)'] += f['same'] == g['same']
|
||
|
|
res[' stesso raggio (cilindri)'] += f['surf'] == 'CYLINDRICAL_SURFACE' and abs(f['par'][0] - g['par'][0]) < TOL
|
||
|
|
res[' stessa suddivisione esterno/fori'] += f['outer'] == g['outer'] or sorted(f['outer']) == sorted(g['outer'])
|
||
|
|
ct = {(R(a), R(b)): t for lp in g['loops'] for a, b, t, _ in lp}
|
||
|
|
for lp in f['loops']:
|
||
|
|
for a, b, t, _ in lp:
|
||
|
|
curves[(t.split('_')[0], ct.get((R(a), R(b)), '?').split('_')[0])] += 1
|
||
|
|
print(f"facce: prt {len(A)} step di riferimento {len(B)}")
|
||
|
|
for k, v in res.items():
|
||
|
|
print(f"{k}: {v}")
|
||
|
|
sa, sb = stepread.shells(mine), stepread.shells(ref)
|
||
|
|
print("gusci chiusi/aperti (numero di facce):", {k: [len(x) for x in v] for k, v in sa.items()},
|
||
|
|
"riferimento", {k: [len(x) for x in v] for k, v in sb.items()})
|
||
|
|
print("curve degli spigoli (mia -> riferimento), contate per lato:")
|
||
|
|
for (a, b), v in sorted(curves.items()):
|
||
|
|
print(f" {a:8} -> {b:8} {v}")
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == '__main__':
|
||
|
|
src = sys.argv[1]
|
||
|
|
srf, crv = load(src)
|
||
|
|
C = {c.get('crv_id'): c for c in crv}
|
||
|
|
F = faces(srf, C)
|
||
|
|
worst, bad = coherence(srf, crv)
|
||
|
|
print(f"superfici {len(srf)} facce {len(F)} contorni {sum(len(l) for _, l in F)} spigoli {len(crv)}")
|
||
|
|
print(f"coerenza fra le due superfici di ogni spigolo: scarto massimo {worst:.1e} mm, fuori tolleranza {len(bad)}")
|
||
|
|
for e, d in bad[:20]:
|
||
|
|
print(f" spigolo {e}: scarto {d:.6f}")
|
||
|
|
name = os.path.basename(src).split('.')[0]
|
||
|
|
if '--step' in sys.argv:
|
||
|
|
out = sys.argv[sys.argv.index('--step') + 1]
|
||
|
|
print(f"scritto {out}: facce del solido {'/ della quilt '.join(str(n) + ' ' for n in write_step(out, srf, crv, name))}")
|
||
|
|
if '--check' in sys.argv:
|
||
|
|
tmp = os.path.join(tempfile.mkdtemp(), 'mio.stp')
|
||
|
|
write_step(tmp, srf, crv, name)
|
||
|
|
compare(tmp, sys.argv[sys.argv.index('--check') + 1])
|