Files
rosetta/tools/fixtures/_off_reference.py
T

33 lines
1.6 KiB
Python

# OFF reference values (run by tools/fixtures/off.py through ctx.python(["trimesh", "numpy"], ...), python -I).
# stdin: JSON {"dir": tmp, "make": [name], "read": [name]}
# stdout: JSON {name (only the files trimesh reads): {"vertices": n, "pos_crc": crc of the f32 vertices, "faces": [[...]] or None (n-gons over 4)}}
# make: OFF files written by trimesh (an icosphere, a capsule)
# read: every file read with trimesh.exchange.off.load_off (positions; faces when all are triangles / quads, the
# only polygons trimesh keeps as they are)
import json, os, sys, zlib
import numpy as np
import trimesh
from trimesh.exchange import off as toff
req = json.load(sys.stdin)
d = req["dir"]
out = {}
for name in req["make"]:
m = trimesh.creation.icosphere(subdivisions=2, radius=3.0) if "ico" in name else trimesh.creation.capsule(height=2.0, radius=0.5)
with open(os.path.join(d, name), "w") as f:
f.write(toff.export_off(m, digits=9))
for name in req["read"]:
try:
with open(os.path.join(d, name), "rb") as f:
r = toff.load_off(f)
except Exception: # noqa: BLE001 - trimesh fails on polygons of more than 4 vertices: no reference then
continue
v = np.asarray(r["vertices"], dtype=np.float64).reshape(-1, 3)
res = {"vertices": len(v), "pos_crc": zlib.crc32(v.astype("<f4").tobytes())}
faces = r.get("faces")
res["tris"] = int(len(faces)) if faces is not None and len(np.shape(faces)) == 2 and np.shape(faces)[1] == 3 else -1
if res["tris"] >= 0:
res["faces"] = [[int(x) for x in f] for f in np.asarray(faces)]
out[name] = res
json.dump(out, sys.stdout)