344 lines
16 KiB
Python
344 lines
16 KiB
Python
# OFF fixtures (tools/fixtures.py).
|
|
# tests/gen/off_scenes.luau scenes for the encoder (STCNOFF mesh, polygons under a TRS node, a float-colour point
|
|
# cloud, polygons with face colours) with the expected file content, computed here
|
|
# tests/gen/off.luau cases: OFF files written by trimesh and by hand here (COFF with integer / float colours,
|
|
# RGB / RGBA, NOFF, STOFF, STCNOFF, face colours of both kinds, colormap indices, comments
|
|
# everywhere, counts on the header line, CRLF and tabs, n-gons, a point cloud), with the
|
|
# values they were written from (positions cross-checked with trimesh's OFF reader);
|
|
# `ours`: our encoder's output (luau CLI: tools/fixtures/_off_encode.luau) read back by
|
|
# trimesh, assimp and a small reader here, as verdicts
|
|
import json, math, os, shutil, struct, subprocess, tempfile, zlib
|
|
|
|
INPUTS = ["src/Rosetta/model/off", "tools/fixtures/_off_reference.py", "tools/fixtures/_off_encode.luau"]
|
|
|
|
|
|
def f32(x):
|
|
return struct.unpack("<f", struct.pack("<f", x))[0]
|
|
|
|
|
|
def pack(fmt, vals):
|
|
return struct.pack("<%d%s" % (len(vals), fmt), *vals)
|
|
|
|
|
|
def crc(b):
|
|
return zlib.crc32(b)
|
|
|
|
|
|
def fan(faces):
|
|
tris, fot = [], []
|
|
for i, f in enumerate(faces):
|
|
for k in range(1, len(f) - 1):
|
|
tris += [f[0], f[k], f[k + 1]]
|
|
fot.append(i)
|
|
return tris, fot
|
|
|
|
|
|
def random_faces(rng, nv, nf, sizes=(3, 4, 5, 6)):
|
|
out = []
|
|
for _ in range(nf):
|
|
s = rng.choice(sizes)
|
|
out.append(rng.sample(range(nv), s))
|
|
return out
|
|
|
|
|
|
def colour_tokens(rng, kind, comps):
|
|
if kind == "int":
|
|
vals = [rng.randrange(256) for _ in range(comps)]
|
|
return [str(v) for v in vals], vals
|
|
vals = [round(rng.random(), 6) for _ in range(comps)]
|
|
return ["%.6f" % v for v in vals], vals
|
|
|
|
|
|
def colour_bytes(kind, vals_list, comps_list):
|
|
"""the expected COLOR_0 / faceColors bytes (unorm8 x4 or f32 x4; missing alpha / colour = full)"""
|
|
out = b""
|
|
for vals, comps in zip(vals_list, comps_list):
|
|
if kind == "int":
|
|
v = list(vals) + [255] * (4 - len(vals))
|
|
out += bytes(v)
|
|
else:
|
|
v = list(vals) + [1.0] * (4 - len(vals))
|
|
out += pack("f", v)
|
|
return out
|
|
|
|
|
|
def make_case(rng, name, nv, faces, normals=False, st=False, vcol=None, fcol=None, style=None):
|
|
"""an OFF file and the values it holds. vcol / fcol = (kind "int" | "float" | "map", comps)"""
|
|
style = style or {}
|
|
kw = ("ST" if st else "") + ("C" if vcol else "") + ("N" if normals else "") + "OFF"
|
|
nl = "\r\n" if style.get("crlf") else "\n"
|
|
sep = "\t" if style.get("tabs") else " "
|
|
lines = []
|
|
if style.get("comments"):
|
|
lines.append("# a comment before the keyword")
|
|
if style.get("inline"):
|
|
lines.append("%s %d %d 0" % (kw, nv, len(faces)))
|
|
else:
|
|
lines.append(kw + (" # keyword" if style.get("comments") else ""))
|
|
if style.get("comments"):
|
|
lines += ["", "# counts next"]
|
|
lines.append("%d %d %d" % (nv, len(faces), 0))
|
|
pos, nrm, tex, vc_vals, vc_comps = [], [], [], [], []
|
|
for i in range(nv):
|
|
p = [f32(rng.uniform(-10, 10)) for _ in range(3)]
|
|
pos += p
|
|
toks = [repr(c) for c in p]
|
|
if normals:
|
|
v = [rng.uniform(-1, 1) for _ in range(3)]
|
|
ln = math.sqrt(sum(c * c for c in v))
|
|
n = [f32(c / ln) for c in v]
|
|
nrm += n
|
|
toks += [repr(c) for c in n]
|
|
if vcol:
|
|
comps = vcol[1] if vcol[1] != "mixed" else rng.choice((3, 4))
|
|
ct, cv = colour_tokens(rng, vcol[0], comps)
|
|
toks += ct
|
|
vc_vals.append(cv)
|
|
vc_comps.append(comps)
|
|
if st:
|
|
t = [f32(rng.random()) for _ in range(2)]
|
|
tex += t
|
|
toks += [repr(c) for c in t]
|
|
line = sep.join(toks)
|
|
if style.get("comments") and i % 3 == 0:
|
|
line += " # vertex %d" % i
|
|
lines.append(line)
|
|
if style.get("comments") and i == 1:
|
|
lines.append("")
|
|
lines.append(" # an indented comment line")
|
|
fc_vals, fc_comps, any_fc, colormap = [], [], False, False
|
|
for i, f in enumerate(faces):
|
|
toks = [str(len(f))] + [str(x) for x in f]
|
|
if fcol and not (fcol[1] == "some" and i % 3 == 1):
|
|
if fcol[0] == "map":
|
|
toks.append(str(rng.randrange(16)))
|
|
colormap = True
|
|
fc_vals.append([])
|
|
fc_comps.append(0)
|
|
else:
|
|
comps = 4 if fcol[1] in (4, "some") else 3
|
|
ct, cv = colour_tokens(rng, fcol[0], comps)
|
|
toks += ct
|
|
fc_vals.append(cv)
|
|
fc_comps.append(comps)
|
|
any_fc = True
|
|
else:
|
|
fc_vals.append([])
|
|
fc_comps.append(0)
|
|
lines.append(sep.join(toks))
|
|
data = (nl.join(lines) + nl).encode()
|
|
exp = {"name": name, "data": data, "keyword": kw, "vertices": nv, "faces": len(faces), "pos_crc": crc(pack("f", pos))}
|
|
if normals:
|
|
exp["nrm_crc"] = crc(pack("f", nrm))
|
|
if st:
|
|
exp["tex_crc"] = crc(pack("f", tex))
|
|
if vcol:
|
|
exp["color"] = {"type": "unorm8" if vcol[0] == "int" else "f32", "crc": crc(colour_bytes(vcol[0], vc_vals, vc_comps))}
|
|
if any_fc:
|
|
exp["faceColors"] = {"type": "unorm8" if fcol[0] == "int" else "f32", "crc": crc(colour_bytes(fcol[0], fc_vals, fc_comps))}
|
|
if colormap:
|
|
exp["colormap"] = True
|
|
tris, fot = fan(faces)
|
|
exp["allTri"] = all(len(f) == 3 for f in faces)
|
|
exp["tris"] = len(tris) // 3
|
|
exp["tri_crc"] = crc(pack("I", tris))
|
|
exp["fot_crc"] = crc(pack("I", fot))
|
|
exp["corners_crc"] = crc(pack("I", [c for f in faces for c in f]))
|
|
exp["sizes_crc"] = crc(pack("I", [len(f) for f in faces]))
|
|
return exp
|
|
|
|
|
|
def handmade(rng):
|
|
cases = []
|
|
cases.append(make_case(rng, "coff-int.off", 30, random_faces(rng, 30, 20), vcol=("int", 4), fcol=("int", 3), style={"comments": True}))
|
|
cases.append(make_case(rng, "coff-float-rgb.off", 25, random_faces(rng, 25, 12, (3, 4)), vcol=("float", 3), fcol=("float", 4)))
|
|
cases.append(make_case(rng, "coff-mixed-alpha.off", 12, random_faces(rng, 12, 6, (3,)), vcol=("int", "mixed")))
|
|
cases.append(make_case(rng, "noff.off", 20, random_faces(rng, 20, 10, (3,)), normals=True))
|
|
cases.append(make_case(rng, "stoff.off", 16, random_faces(rng, 16, 9), st=True, style={"tabs": True}))
|
|
cases.append(make_case(rng, "stcnoff.off", 18, random_faces(rng, 18, 11), normals=True, st=True, vcol=("int", 4), fcol=("int", "some")))
|
|
cases.append(make_case(rng, "inline-crlf.off", 10, random_faces(rng, 10, 5, (3, 4)), style={"inline": True, "crlf": True}))
|
|
cases.append(make_case(rng, "colormap.off", 9, random_faces(rng, 9, 4, (3, 4)), fcol=("map", 1)))
|
|
cases.append(make_case(rng, "points.off", 40, []))
|
|
cases.append(make_case(rng, "big-ngon.off", 300, [list(range(300)), list(range(0, 300, 7))]))
|
|
return cases
|
|
|
|
|
|
# --- encoder scenes
|
|
def mat_trs(node):
|
|
x, y, z, w = node.get("rotation", [0, 0, 0, 1])
|
|
sx, sy, sz = node.get("scale", [1, 1, 1])
|
|
tx, ty, tz = node.get("translation", [0, 0, 0])
|
|
r = [
|
|
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
|
|
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
|
|
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
|
|
]
|
|
return [[r[i][0] * sx, r[i][1] * sy, r[i][2] * sz, (tx, ty, tz)[i]] for i in range(3)]
|
|
|
|
|
|
def scenes(rng):
|
|
out = []
|
|
n = 12
|
|
pos = [f32(rng.uniform(-5, 5)) for _ in range(n * 3)]
|
|
nrm = [f32(rng.uniform(-1, 1)) for _ in range(n * 3)]
|
|
col = [rng.randrange(256) for _ in range(n * 4)]
|
|
tex = [f32(rng.random()) for _ in range(n * 2)]
|
|
idx = [rng.randrange(n) for _ in range(30)]
|
|
faces = [idx[i:i + 3] for i in range(0, 30, 3)]
|
|
vlines = [pos[i * 3:i * 3 + 3] + nrm[i * 3:i * 3 + 3] + col[i * 4:i * 4 + 4] + tex[i * 2:i * 2 + 2] for i in range(n)]
|
|
out.append({"name": "mesh", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
|
|
"mode": "triangles", "count": n, "indices": pack("I", idx),
|
|
"attrs": {"POSITION": ["f32", 3, pack("f", pos)], "NORMAL": ["f32", 3, pack("f", nrm)], "COLOR_0": ["unorm8", 4, bytes(col)],
|
|
"TEXCOORD_0": ["f32", 2, pack("f", tex)]}}]}],
|
|
"encodings": {"default": {"keyword": "STCNOFF", "vertices": vlines, "faces": faces},
|
|
"plain": {"keyword": "OFF", "vertices": [v[:3] for v in vlines], "faces": faces}}})
|
|
pv = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 2, 0, 0, 3, 0.5, 0, 2.5, 1.5, 0.2, 1.5, 1.2, 0.1, 0, 0, 1]
|
|
q = [rng.uniform(-1, 1) for _ in range(4)]
|
|
ln = math.sqrt(sum(c * c for c in q))
|
|
node = {"mesh": 1, "translation": [1, 2, 3], "rotation": [c / ln for c in q], "scale": [2, 0.5, 1.5]}
|
|
m = mat_trs(node)
|
|
w = [[m[i][0] * pv[k * 3] + m[i][1] * pv[k * 3 + 1] + m[i][2] * pv[k * 3 + 2] + m[i][3] for i in range(3)] for k in range(9)]
|
|
pf = [[0, 1, 2, 3], [1, 4, 5, 6, 7, 2], [0, 3, 8]]
|
|
out.append({"name": "polys", "nodes": [node], "roots": [1], "meshes": [{"prims": [{
|
|
"mode": "polygons", "count": 9, "indices": pack("I", [c for f in pf for c in f]), "faces": pack("I", [len(f) for f in pf]),
|
|
"attrs": {"POSITION": ["f32", 3, pack("f", pv)]}}]}],
|
|
"encodings": {"default": {"keyword": "OFF", "vertices": w, "faces": pf, "tol": 1e-5}}})
|
|
n = 20
|
|
pos = [f32(rng.uniform(-50, 50)) for _ in range(n * 3)]
|
|
col = [f32(rng.random()) for _ in range(n * 4)]
|
|
out.append({"name": "cloud", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
|
|
"mode": "points", "count": n, "attrs": {"POSITION": ["f32", 3, pack("f", pos)], "COLOR_0": ["f32", 4, pack("f", col)]}}]}],
|
|
"encodings": {"default": {"keyword": "COFF", "vertices": [pos[i * 3:i * 3 + 3] + col[i * 4:i * 4 + 4] for i in range(n)], "faces": []}}})
|
|
# face colours on planar polygons (assimp triangulates non-planar ones its own way)
|
|
pf = [[0, 1, 2, 3], [1, 4, 5, 6, 7, 2], [0, 3, 8]]
|
|
pos = [f32(v) for v in pv]
|
|
fc = [rng.randrange(256) for _ in range(12)]
|
|
out.append({"name": "facecolors", "nodes": [{"mesh": 1}], "roots": [1], "meshes": [{"prims": [{
|
|
"mode": "polygons", "count": 9, "indices": pack("I", [c for f in pf for c in f]), "faces": pack("I", [len(f) for f in pf]),
|
|
"attrs": {"POSITION": ["f32", 3, pack("f", pos)]}, "faceColors": bytes(fc)}]}],
|
|
"encodings": {"default": {"keyword": "OFF", "vertices": [pos[i * 3:i * 3 + 3] for i in range(9)], "faces": pf,
|
|
"faceColors": [fc[i * 4:i * 4 + 4] for i in range(3)]}}})
|
|
return out
|
|
|
|
|
|
def parse_off(text):
|
|
"""a small OFF reader for checking our output: keyword, vertex rows (numbers), faces, face colour rows"""
|
|
rows = []
|
|
for line in text.split("\n"):
|
|
line = line.split("#", 1)[0].strip()
|
|
if line:
|
|
rows.append(line.split())
|
|
kw = rows[0][0]
|
|
nv, nf = int(rows[1][0]), int(rows[1][1])
|
|
verts = [[float(x) for x in r] for r in rows[2:2 + nv]]
|
|
faces, fcols = [], []
|
|
for r in rows[2 + nv:2 + nv + nf]:
|
|
k = int(r[0])
|
|
faces.append([int(x) for x in r[1:1 + k]])
|
|
fcols.append([float(x) for x in r[1 + k:]])
|
|
return kw, verts, faces, fcols, len(rows) == 2 + nv + nf
|
|
|
|
|
|
def check_ours(text, want):
|
|
kw, verts, faces, fcols, exact_rows = parse_off(text)
|
|
if kw != want["keyword"]:
|
|
return False, "keyword %s, want %s" % (kw, want["keyword"])
|
|
if not exact_rows:
|
|
return False, "extra or missing rows"
|
|
if len(verts) != len(want["vertices"]):
|
|
return False, "vertex count"
|
|
tol = want.get("tol", 0)
|
|
for got, exp in zip(verts, want["vertices"]):
|
|
if len(got) != len(exp):
|
|
return False, "vertex row length %d, want %d" % (len(got), len(exp))
|
|
for g, e in zip(got, exp):
|
|
if (abs(f32(g) - f32(e)) > tol * max(1, abs(e))) if tol else f32(g) != f32(e):
|
|
return False, "vertex value %r, want %r" % (g, e)
|
|
if faces != want["faces"]:
|
|
return False, "faces differ"
|
|
if "faceColors" in want:
|
|
if [list(map(int, c)) for c in fcols] != want["faceColors"]:
|
|
return False, "face colours differ"
|
|
elif any(fcols):
|
|
return False, "unexpected face colours"
|
|
return True, "%d vertices, %d faces" % (len(verts), len(faces))
|
|
|
|
|
|
def luau_cmd():
|
|
exe = shutil.which("luau")
|
|
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
|
|
|
|
|
|
def assimp_faces(ctx, path):
|
|
txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace")
|
|
for line in txt.split("\n"):
|
|
if line.startswith("Faces:"):
|
|
return int(line.split()[1])
|
|
return None
|
|
|
|
|
|
def generate(ctx):
|
|
rng = ctx.rng(53)
|
|
tmp = tempfile.mkdtemp(prefix="formats-off-")
|
|
try:
|
|
_generate(ctx, rng, tmp)
|
|
finally:
|
|
shutil.rmtree(tmp, ignore_errors=True)
|
|
|
|
|
|
def _generate(ctx, rng, tmp):
|
|
sc = scenes(rng)
|
|
ctx.emit("off_scenes", sc)
|
|
cases = handmade(rng)
|
|
for c in cases:
|
|
with open(os.path.join(tmp, c["name"]), "wb") as f:
|
|
f.write(c["data"])
|
|
make = ["trimesh-ico.off", "trimesh-capsule.off"]
|
|
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_off_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
|
|
ours = []
|
|
byname = {s["name"]: s for s in sc}
|
|
for line in enc.split("\n"):
|
|
if not line.strip():
|
|
continue
|
|
label, hexdata = line.split(" ", 1)
|
|
scene_name, encoding = label.split("/")
|
|
fn = "ours-%s-%s.off" % (scene_name, encoding)
|
|
data = bytes.fromhex(hexdata.strip())
|
|
with open(os.path.join(tmp, fn), "wb") as f:
|
|
f.write(data)
|
|
ours.append((label, fn, data, byname[scene_name]["encodings"][encoding]))
|
|
names = [c["name"] for c in cases if c["vertices"] > 0] + make + [o[1] for o in ours]
|
|
code = open(os.path.join(ctx.root, "tools", "fixtures", "_off_reference.py")).read()
|
|
try:
|
|
ref = json.loads(ctx.python(["trimesh", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "read": names}).encode()))
|
|
except subprocess.CalledProcessError as e:
|
|
raise RuntimeError("off reference: " + e.stderr.decode(errors="replace")[-3000:])
|
|
# trimesh agrees with the values the files were written from
|
|
for c in cases:
|
|
r = ref.get(c["name"])
|
|
if r:
|
|
assert r["vertices"] == c["vertices"] and r["pos_crc"] == c["pos_crc"], c["name"]
|
|
for name in make:
|
|
with open(os.path.join(tmp, name), "rb") as f:
|
|
data = f.read()
|
|
r = ref[name]
|
|
tris = [x for f in r["faces"] for x in f]
|
|
cases.append({"name": name, "data": data, "keyword": "OFF", "vertices": r["vertices"], "faces": r["tris"], "pos_crc": r["pos_crc"],
|
|
"allTri": True, "tris": r["tris"], "tri_crc": crc(pack("I", tris)), "corners_crc": crc(pack("I", tris)),
|
|
"sizes_crc": crc(pack("I", [3] * r["tris"]))})
|
|
verdicts = []
|
|
for label, fn, data, want in ours:
|
|
ok, detail = check_ours(data.decode(), want)
|
|
r = ref.get(fn)
|
|
if ok and r and not want.get("tol"):
|
|
exp = pack("f", [c for v in want["vertices"] for c in v[:3]])
|
|
if r["pos_crc"] != crc(exp):
|
|
ok, detail = False, "trimesh reads other positions"
|
|
if ok and want["faces"]:
|
|
got = assimp_faces(ctx, os.path.join(tmp, fn))
|
|
exp_f = sum(len(f) - 2 for f in want["faces"])
|
|
if got != exp_f:
|
|
ok, detail = False, "assimp reads %s faces, want %d" % (got, exp_f)
|
|
verdicts.append({"name": label, "ok": ok, "detail": detail})
|
|
ctx.emit("off", {"cases": cases, "ours": verdicts})
|