Files
prep-step/scripts/psb/tagfit.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

139 lines
4.3 KiB
Python

"""Verifica la tabella dei prefissi dei double (psb.P.PFX, tag 4b-df) con un vincolo geometrico:
il punto di uno spigolo calcolato sulle due superfici adiacenti deve coincidere (brep.py).
Per ogni tag prova i prefissi vicini e sceglie quello che lascia meno punti incoerenti.
python scripts/psb/tagfit.py 9245000212.prt.6 "raw/*.prt.*"
Variabili d'ambiente: TAGS=4b,4c (solo questi tag), SPAN=40 (quanti prefissi provare per lato),
TOL=1e-3 (tolleranza in mm: le intersezioni non analitiche sono precise solo al millesimo).
"""
import sys, os, glob, math, struct, collections
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import psb, brep
class TF(float):
pass
orig = psb.P.rdbl
def rdbl(s):
p0 = s.p
t = s.b[p0]
v = orig(s)
if 0x4b <= t <= 0xdf and not isinstance(v, psb.Unk):
o = TF(v)
o.tag = t
o.pl = bytes(s.b[p0 + 1:p0 + 7])
return o
return v
psb.P.rdbl = rdbl
slots = collections.defaultdict(list) # tag -> [(lista, indice, payload)]
edges = collections.defaultdict(set) # tag -> {indice in E}
E = [] # (spigolo, superfici del file)
def collect(x, found):
"""registra dove stanno i double a prefisso dentro x (liste annidate)"""
for i, v in enumerate(x):
if isinstance(v, TF):
slots[v.tag].append((x, i, v.pl))
found.add(v.tag)
elif isinstance(v, list):
collect(v, found)
def prim_tags(s, cache={}):
k = id(s)
if k not in cache:
f = set()
p = brep.prim(s)
if p is not None:
for j, (n, v) in enumerate(p):
if isinstance(v, list):
collect(v, f)
elif isinstance(v, TF): # scalare (radius, half_angle): lo si porta in lista
box = [v]
p[j] = (n, box)
collect(box, f)
cache[k] = f
return cache[k]
def unbox(v):
return v[0] if isinstance(v, list) and len(v) == 1 and not isinstance(v[0], list) else v
SCALARS = ('radius', 'half_angle', 'radius1', 'radius2')
_get = psb.Node.get
psb.Node.get = lambda s, k, d=None: unbox(_get(s, k, d)) if k in SCALARS else _get(s, k, d)
TOL = float(os.environ.get('TOL', '1e-5'))
def nbad(idx):
n = 0
for i in idx:
c, S = E[i]
try:
a, b = brep.side_points(c, S, 0), brep.side_points(c, S, 1)
except (ValueError, TypeError):
continue
if a is None or b is None:
continue
n += sum(1 for x, y in zip(a, b) if math.dist(x, y) > TOL)
return n
def setpfx(t, hi):
for x, i, pl in slots[t]:
x[i] = struct.unpack('>d', hi.to_bytes(2, 'big') + pl)[0]
files = [g for a in sys.argv[1:] for g in glob.glob(a)]
used = 0
for f in files:
try:
srf, crv = brep.load(f)
except (SystemExit, Exception):
continue
if not srf or not crv:
continue
used += 1
S = {s.get('geom_id'): s for s in srf}
for c in crv:
tags = set()
if c.get('crv_pnt_arr'):
collect(c.get('crv_pnt_arr'), tags)
for k in (0, 1):
s = S.get(c.get(f'crv_hdr_geom_ptr[{k}]'))
if s is not None:
tags |= prim_tags(s)
E.append((c, S))
for t in tags:
edges[t].add(len(E) - 1)
print(f"file con VisibGeom leggibile: {used}/{len(files)} spigoli {len(E)} punti incoerenti all'inizio {nbad(range(len(E)))}")
pfx = dict(psb.P.PFX)
only = {int(x, 16) for x in os.environ.get('TAGS', '').split(',') if x}
span = int(os.environ.get('SPAN', '6'))
for t in sorted(edges):
if only and t not in only:
continue
cur = pfx[t]
score = {}
for hi in range(cur - span, cur + span + 1):
setpfx(t, hi)
score[hi] = nbad(edges[t])
setpfx(t, cur)
best = min(score, key=lambda h: (score[h], abs(h - cur)))
second = min(v for h, v in score.items() if h != best)
verdict = 'PROVATO' if best == cur and second > score[cur] else 'non distinguibile' if best == cur else f'MEGLIO {best:04x} ({score[best]})'
print(f"tag {t:02x} -> {cur:04x} spigoli {len(edges[t]):4} incoerenti {score[cur]:4} miglior alternativa {second:4} {verdict}")
print("tag mai usati da uno spigolo (non verificabili cosi'):",
' '.join(f"{t:02x}" for t in sorted(psb.P.PFX) if t not in edges))