193 lines
11 KiB
Python
193 lines
11 KiB
Python
# PLY fixtures (tools/fixtures.py).
|
|
# tests/gen/ply_scenes.luau scenes for the encoder (an indexed mesh with every attribute kind and custom properties,
|
|
# polygons under a TRS node, a float-colour point cloud, two meshes merged, a mirrored
|
|
# polygon) with the expected vertex properties (names, types, values) and faces, computed
|
|
# here
|
|
# tests/gen/ply.luau cases: PLY files written by plyfile (ascii / binary LE / BE, every property type, odd
|
|
# orders, n-gons up to 300 vertices, face properties and lists, edge / material / tristrips
|
|
# elements, comments, obj_info, point clouds, a 65k-vertex sphere) and by assimp (OFF / OBJ
|
|
# -> PLY), each with reference values from plyfile mapped to the Scene conventions;
|
|
# `ours`: our encoder's output (luau CLI: tools/fixtures/_ply_encode.luau) read back by
|
|
# plyfile and assimp, as verdicts
|
|
import json, math, os, shutil, struct, subprocess, tempfile
|
|
|
|
INPUTS = ["src/Rosetta/model/ply", "tools/fixtures/_ply_reference.py", "tools/fixtures/_ply_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 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 quat(rng):
|
|
q = [rng.uniform(-1, 1) for _ in range(4)]
|
|
ln = math.sqrt(sum(c * c for c in q))
|
|
return [c / ln for c in q]
|
|
|
|
|
|
def scenes(rng):
|
|
out = []
|
|
# an indexed mesh with every attribute kind
|
|
W, H = 5, 4
|
|
n = W * H
|
|
pos = [f32(v) for y in range(H) for x in range(W) for v in (x, y, rng.uniform(-1, 1))]
|
|
nrm = []
|
|
for _ in range(n):
|
|
v = [rng.uniform(-1, 1) for _ in range(3)]
|
|
ln = math.sqrt(sum(c * c for c in v))
|
|
nrm += [f32(c / ln) for c in v]
|
|
col = [rng.randrange(256) for _ in range(n * 4)]
|
|
tex = [f32(rng.random()) for _ in range(n * 2)]
|
|
quality = [f32(rng.uniform(0, 10)) for _ in range(n)]
|
|
label = [rng.randrange(65536) for _ in range(n)]
|
|
idx = []
|
|
for y in range(H - 1):
|
|
for x in range(W - 1):
|
|
a = y * W + x
|
|
idx += [a, a + 1, a + W + 1, a, a + W + 1, a + W]
|
|
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)], "_quality": ["f32", 1, pack("f", quality)], "_label": ["u16", 1, pack("H", label)]}}]}],
|
|
"props": [("x", "<f4", pos[0::3]), ("y", "<f4", pos[1::3]), ("z", "<f4", pos[2::3]), ("nx", "<f4", nrm[0::3]), ("ny", "<f4", nrm[1::3]),
|
|
("nz", "<f4", nrm[2::3]), ("red", "u1", col[0::4]), ("green", "u1", col[1::4]), ("blue", "u1", col[2::4]), ("alpha", "u1", col[3::4]),
|
|
("s", "<f4", tex[0::2]), ("t", "<f4", tex[1::2]), ("label", "<u2", label), ("quality", "<f4", quality)],
|
|
"faces": [idx[i:i + 3] for i in range(0, len(idx), 3)]})
|
|
# polygons under a TRS node (positions transformed: compared with a tolerance)
|
|
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]
|
|
node = {"mesh": 1, "translation": [1, 2, 3], "rotation": quat(rng), "scale": [2, 0.5, 1.5]}
|
|
m = mat_trs(node)
|
|
w = [[f32(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)]
|
|
out.append({"name": "polys", "nodes": [node], "roots": [1], "meshes": [{"prims": [{
|
|
"mode": "polygons", "count": 9, "indices": pack("I", [0, 1, 2, 3, 1, 4, 5, 6, 7, 2, 0, 3, 8]), "faces": pack("I", [4, 6, 3]),
|
|
"attrs": {"POSITION": ["f32", 3, pack("f", pv)]}}]}],
|
|
"props": [("x", "<f4", [p[0] for p in w], 1e-5), ("y", "<f4", [p[1] for p in w], 1e-5), ("z", "<f4", [p[2] for p in w], 1e-5)],
|
|
"faces": [[0, 1, 2, 3], [1, 4, 5, 6, 7, 2], [0, 3, 8]], "transformed": True})
|
|
# a point cloud with float colours (alpha all 1: not written)
|
|
n = 30
|
|
pos = [f32(rng.uniform(-50, 50)) for _ in range(n * 3)]
|
|
col = [f32(rng.random()) if k % 4 != 3 else 1.0 for k 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)]}}]}],
|
|
"props": [("x", "<f4", pos[0::3]), ("y", "<f4", pos[1::3]), ("z", "<f4", pos[2::3]), ("red", "<f4", col[0::4]),
|
|
("green", "<f4", col[1::4]), ("blue", "<f4", col[2::4])]})
|
|
# two meshes merged: the second has no colours (filled with opaque white: alpha not written)
|
|
pa = [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0]
|
|
ca = [10, 20, 30, 255, 40, 50, 60, 255, 70, 80, 90, 255, 100, 110, 120, 255]
|
|
pb = [5, 5, 5, 6, 5, 5, 6, 6, 5, 5, 6, 5.5]
|
|
allp = pa + pb
|
|
allc = ca + [255] * 16
|
|
out.append({"name": "multi", "nodes": [{"mesh": 1}, {"mesh": 2}], "roots": [1, 2], "meshes": [
|
|
{"prims": [{"mode": "triangles", "count": 4, "indices": pack("I", [0, 1, 2, 0, 2, 3]),
|
|
"attrs": {"POSITION": ["f32", 3, pack("f", pa)], "COLOR_0": ["unorm8", 4, bytes(ca)]}}]},
|
|
{"prims": [{"mode": "polygons", "count": 4, "indices": pack("I", [0, 1, 2, 3]), "faces": pack("I", [4]),
|
|
"attrs": {"POSITION": ["f32", 3, pack("f", pb)]}}]}],
|
|
"props": [("x", "<f4", allp[0::3]), ("y", "<f4", allp[1::3]), ("z", "<f4", allp[2::3]), ("red", "u1", allc[0::4]),
|
|
("green", "u1", allc[1::4]), ("blue", "u1", allc[2::4])],
|
|
"faces": [[0, 1, 2], [0, 2, 3], [4, 5, 6, 7]]})
|
|
# a mirrored polygon: the winding reverses (first corner kept)
|
|
pm = [0, 0, 0, 1, 0, 0, 1.5, 1, 0, 0.5, 1.5, 0, -0.5, 1, 0]
|
|
out.append({"name": "mirror", "nodes": [{"mesh": 1, "scale": [-1, 1, 1]}], "roots": [1], "meshes": [{"prims": [{
|
|
"mode": "polygons", "count": 5, "indices": pack("I", [0, 1, 2, 3, 4]), "faces": pack("I", [5]),
|
|
"attrs": {"POSITION": ["f32", 3, pack("f", pm)]}}]}],
|
|
"props": [("x", "<f4", [-v for v in pm[0::3]]), ("y", "<f4", pm[1::3]), ("z", "<f4", pm[2::3])],
|
|
"faces": [[0, 4, 3, 2, 1]], "transformed": True})
|
|
for sc in out:
|
|
sc["props"] = [{"name": p[0], "dtype": p[1], "values": struct.pack("<%d%s" % (len(p[2]), {"<f4": "f", "u1": "B", "<u2": "H"}[p[1]]), *p[2]),
|
|
**({"tol": p[3]} if len(p) > 3 else {})} for p in sc["props"]]
|
|
if "faces" in sc:
|
|
sc["faceSizes"] = pack("I", [len(f) for f in sc["faces"]])
|
|
sc["faceCorners"] = pack("I", [c for f in sc["faces"] for c in f])
|
|
return out
|
|
|
|
|
|
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(47)
|
|
tmp = tempfile.mkdtemp(prefix="formats-ply-")
|
|
try:
|
|
_generate(ctx, rng, tmp)
|
|
finally:
|
|
shutil.rmtree(tmp, ignore_errors=True)
|
|
|
|
|
|
def _generate(ctx, rng, tmp):
|
|
sc = scenes(rng)
|
|
ctx.emit("ply_scenes", sc)
|
|
make = ["cube-le.ply", "colors-be.ply", "ascii-mixed.ply", "points-le.ply", "points-ascii-float.ply", "types-be.ply", "big-le.ply", "tristrips.ply"]
|
|
# assimp conversions: OFF -> PLY (ascii), OBJ -> PLY (binary)
|
|
off = "OFF\n6 3 0\n" + "".join("%r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(6))
|
|
off += "3 0 1 2\n4 1 3 4 2\n3 4 5 2\n"
|
|
obj = "".join("v %r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(8))
|
|
obj += "vn 0 0 1\nf 1//1 2//1 3//1 4//1\nf 5//1 6//1 7//1\nf 1//1 8//1 5//1\n"
|
|
with open(os.path.join(tmp, "in.off"), "w") as f:
|
|
f.write(off)
|
|
with open(os.path.join(tmp, "in.obj"), "w") as f:
|
|
f.write(obj)
|
|
ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, "in.off"), os.path.join(tmp, "assimp-off.ply"), "-fply"])
|
|
ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, "in.obj"), os.path.join(tmp, "assimp-obj-b.ply"), "-fplyb"])
|
|
refs = make + ["assimp-off.ply", "assimp-obj-b.ply"]
|
|
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_ply_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("/")
|
|
s = byname[scene_name]
|
|
fn = "ours-%s-%s.ply" % (scene_name, encoding)
|
|
with open(os.path.join(tmp, fn), "wb") as f:
|
|
f.write(bytes.fromhex(hexdata.strip()))
|
|
ours.append({"name": label, "file": fn, "props": [{**p, "values": p["values"].hex()} for p in s["props"]], "faces": s.get("faces")})
|
|
code = open(os.path.join(ctx.root, "tools", "fixtures", "_ply_reference.py")).read()
|
|
try:
|
|
res = json.loads(ctx.python(["plyfile", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "ref": refs, "ours": ours}).encode()))
|
|
except subprocess.CalledProcessError as e:
|
|
raise RuntimeError("ply reference: " + e.stderr.decode(errors="replace")[-3000:])
|
|
verdicts = []
|
|
for o in ours:
|
|
ok, detail = res["ours"][o["name"]]
|
|
if o["faces"]:
|
|
want = sum(len(f) - 2 for f in o["faces"])
|
|
got = assimp_faces(ctx, os.path.join(tmp, o["file"]))
|
|
if got != want:
|
|
ok, detail = False, "assimp reads %s faces, want %d" % (got, want)
|
|
verdicts.append({"name": o["name"], "ok": ok, "detail": detail})
|
|
cases = []
|
|
for name in refs:
|
|
with open(os.path.join(tmp, name), "rb") as f:
|
|
data = f.read()
|
|
r = res["ref"][name]
|
|
c = {"name": name, "data": data}
|
|
c.update({k: v for k, v in r.items() if v is not None})
|
|
cases.append(c)
|
|
ctx.emit("ply", {"cases": cases, "ours": verdicts})
|