Files
prep-step/scripts/psb/fltfit.py
T
davideandClaude Opus 5.5 3396df6be0 Leggi il solido dei .prt ed esportalo in STEP senza Creo
- scripts/psb/brep.py: B-rep esatto da VisibGeom/ActDatums riscritto in
  STEP; coincide faccia per faccia con lo STEP di Creo su due campioni.
- scripts/psb/mesh.py: STEP sfaccettato dalla mesh di SolidPrimdata, per
  i file Wildfire in cui VisibGeom e' cifrata.
- psb.py: tabella dei double corretta (modi a 3/6 byte, prefissi con
  buchi, costanti 04 e 0d, tag ee); tabella dei float a 81 voci, i tag
  ignoti non ricevono piu' un valore inventato; struct dichiarate sotto
  due id.
- tagfit.py, fltfit.py, stepread.py: verifica delle tabelle con vincoli
  geometrici e confronto con lo STEP di Creo.
- docs: nuovo formato-prt-brep.md e lettura-prt-asm.md; correzioni in
  formato-psb.md (3.4) e formato-prt-geometria.md (assi di local_sys =
  colonne); history.md con regressioni e punti aperti.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:00:51 +01:00

194 lines
6.8 KiB
Python

"""Ricostruisce la tabella dei prefissi dei float (psb.P.FPFX, tag 50-df) dalla mesh di
SolidPrimdata, con due vincoli: ogni normale e' unitaria, ogni vertice sta su una superficie
dello STEP esportato da Creo dallo stesso modello (o, senza STEP, sul piano della sua striscia).
python scripts/psb/fltfit.py <file.prt.N> <file.stp> [altre coppie ...]
Al posto dello STEP si puo' mettere '-': di quel file si usano solo le normali.
Stampa per ogni tag il prefisso scelto, quante volte e' stato messo alla prova e quante
alternative lo spiegano altrettanto bene (0 = provato).
"""
import math, os, struct, sys, collections
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import psb, mesh, stepread
TOL = 3e-4 # mm: i vertici sono float a 32 bit
class TF(float):
pass
_rflt = psb.P.rflt
def rflt(s):
p = s.p
v = _rflt(s)
t = s.b[p]
if 0x50 <= t <= 0xdf:
o = TF(0.0 if isinstance(v, psb.Unk) else v)
o.tag, o.pl = t, bytes(s.b[p + 1:p + 3])
return o
return v
psb.P.rflt = rflt
def val(x, pfx):
"""valore del float x con la tabella pfx; None se il suo tag non ha ancora un prefisso"""
if not isinstance(x, TF):
return float(x)
hi = pfx.get(x.tag)
return None if hi is None else struct.unpack('>f', hi.to_bytes(2, 'big') + x.pl)[0]
def surfaces(path):
out = []
for f in stepread.faces(path):
if f['surf'] == 'PLANE':
out.append(('p', f['o'], f['z']))
elif f['surf'] == 'CYLINDRICAL_SURFACE':
out.append(('c', f['o'], f['z'], f['par'][0]))
elif f['surf'] == 'CONICAL_SURFACE':
a = f['par'][1]
out.append(('k', f['o'], f['z'], f['par'][0], math.tan(math.radians(a) if a > 1.6 else a)))
return list(set(out))
def wire(path):
"""(vertici, cerchi) dello STEP: i vertici della mesh stanno quasi tutti sul bordo delle facce,
cioe' su un vertice o su uno spigolo circolare. E' un vincolo molto piu' stretto di "sta su
una superficie", che per una faccia piana lascia libera la coordinata ignota."""
E = stepread.parse(path)
def pt(r):
return tuple(E[r[1]][1][1])
verts = [pt(a[1]) for n, a in E.values() if n == 'VERTEX_POINT']
circles = []
for n, a in E.values():
if n == 'CIRCLE':
ax = E[a[1][1]][1]
circles.append((pt(ax[1]), tuple(E[ax[2][1]][1][1]), a[2]))
return verts, circles
def on_wire(p, W, tol):
verts, circles = W
for q in verts:
if abs(p[0] - q[0]) < tol and abs(p[1] - q[1]) < tol and abs(p[2] - q[2]) < tol:
return True
for c, z, r in circles:
d = (p[0] - c[0], p[1] - c[1], p[2] - c[2])
h = d[0] * z[0] + d[1] * z[1] + d[2] * z[2]
if abs(h) < tol and abs(math.sqrt(max(0.0, d[0] * d[0] + d[1] * d[1] + d[2] * d[2] - h * h)) - r) < tol:
return True
return False
def on_surface(p, S, tol):
for s in S:
d = (p[0] - s[1][0], p[1] - s[1][1], p[2] - s[1][2])
h = d[0] * s[2][0] + d[1] * s[2][1] + d[2] * s[2][2]
if s[0] == 'p':
if abs(h) < tol:
return True
continue
r = math.sqrt(max(0.0, d[0] * d[0] + d[1] * d[1] + d[2] * d[2] - h * h))
if s[0] == 'c' and abs(r - s[3]) < tol:
return True
if s[0] == 'k' and (abs(r - (s[3] + h * s[4])) < tol or abs(r - (s[3] - h * s[4])) < tol):
return True
return False
def candidates(t, pfx):
"""50-a3 positivi, a4-df negativi. Tutte le voci trovate finora crescono in modulo con il tag:
un tag ignoto si cerca fra i vicini noti (e' cio' che decide i casi con due soluzioni)"""
neg = t >= 0xa4
lo, hi = (0xb000, 0xc500) if neg else (0x3000, 0x4500)
for k, v in pfx.items():
if (k >= 0xa4) == neg:
if k < t:
lo = max(lo, v + 1)
elif k > t:
hi = min(hi, v - 1)
return range(lo, hi + 1)
def main(args):
V, N = [], [] # vertici e normali: liste di 3 float (alcuni TF), con le superfici
for prt_path, stp in zip(args[::2], args[1::2]):
S = (surfaces(stp), wire(stp)) if stp != '-' else None
try:
G = mesh.groups(mesh.load(prt_path))
except SystemExit:
continue
for lod, strips in G:
for s in strips:
for n, p in s:
N.append(n)
if S: # senza STEP ('-') contano solo le normali
V.append((p, S))
pfx = dict(psb.P.FKNOWN)
use = collections.defaultdict(list)
for i, n in enumerate(N):
for x in n:
if isinstance(x, TF):
use[x.tag].append(('n', i))
for i, (p, S) in enumerate(V):
for x in p:
if isinstance(x, TF):
use[x.tag].append(('v', i))
report, debug = {}, {}
for rnd in range(6):
changed = False
for t in sorted(use):
if t in pfx and t in report:
continue
score = collections.Counter()
tests = 0
cands = [pfx[t]] if t in pfx else candidates(t, pfx)
trial = dict(pfx)
for kind, i in use[t]:
item = N[i] if kind == 'n' else V[i][0]
if any(isinstance(x, TF) and x.tag != t and x.tag not in pfx for x in item):
continue # dipende da un altro tag ancora ignoto: piu' tardi
tests += 1
for c in cands:
trial[t] = c
q = [val(x, trial) for x in item]
if kind == 'n':
ok = abs(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] - 1) < 2e-5
else:
ok = on_surface(q, V[i][1][0], TOL) and (2 if on_wire(q, V[i][1][1], TOL) else 1)
score[c] += ok
if not tests:
continue
best, n = score.most_common(1)[0] if score else (None, 0)
ties = sum(1 for c, v in score.items() if v == n) - 1
debug[t] = f"prove {tests}, migliori {[(hex(c), v) for c, v in score.most_common(4)]}"
if t in pfx:
report[t] = (pfx[t], tests, score[pfx[t]], 0, 'gia nota')
elif n >= 1 and ties == 0 and n >= 0.9 * tests:
pfx[t] = best
report[t] = (best, tests, n, ties, 'trovata')
changed = True
if not changed:
break
for t in sorted(use):
if t in report:
hi, tests, n, ties, how = report[t]
print(f"tag {t:02x} -> {hi:04x} prove {tests:4} riuscite {n:4} {how}")
else:
print(f"tag {t:02x} -> ? usato {len(use[t])} volte, non determinato", debug.get(t, ''))
print("FKNOWN = {" + ', '.join(f"0x{t:02x}: 0x{v:04x}" for t, v in sorted(pfx.items())) + "}")
if __name__ == '__main__':
main(sys.argv[1:])