Files
rosetta/tools/fixtures/_ply_reference.py
T

308 lines
14 KiB
Python

# PLY reference values (run by tools/fixtures/ply.py through ctx.python(["plyfile", "numpy"], ...), python -I).
# stdin: JSON {"dir": tmp, "make": [name], "ref": [name], "ours": [{name, file, scene}]}
# stdout: JSON {"ref": {name: {...}}, "ours": {name: [ok, detail]}}
# make: PLY files written by plyfile (every encoding, every property type, odd orders, lists, extra elements)
# ref: every file read with plyfile, mapped to the library's Scene conventions here (independently of the Luau
# code): CRC-32 of each attribute's packed little-endian bytes, the triangulated / polygon indices, face
# properties, raw elements, comments
# ours: our encoder's output read back by plyfile and compared property by property with the scene it came from
import json, os, sys, zlib
import numpy as np
from plyfile import PlyData, PlyElement
req = json.load(sys.stdin)
d = req["dir"]
out = {"ref": {}, "ours": {}}
def path(n):
return os.path.join(d, n)
def crc(a):
return zlib.crc32(np.ascontiguousarray(a).tobytes())
def le(a):
a = np.asarray(a)
return a.astype(a.dtype.newbyteorder("<"))
def sphere(rng, n):
"""a UV sphere with n x n quads (poles as triangle fans): vertices, quads and triangles"""
vs = [(0.0, 0.0, 1.0)]
for i in range(1, n):
th = np.pi * i / n
for j in range(n):
ph = 2 * np.pi * j / n
vs.append((np.sin(th) * np.cos(ph), np.sin(th) * np.sin(ph), np.cos(th)))
vs.append((0.0, 0.0, -1.0))
faces = []
for j in range(n):
faces.append([0, 1 + j, 1 + (j + 1) % n])
for i in range(n - 2):
for j in range(n):
a = 1 + i * n + j
b = 1 + i * n + (j + 1) % n
faces.append([a, a + n, b + n, b])
last = len(vs) - 1
for j in range(n):
a = 1 + (n - 2) * n
faces.append([last, a + (j + 1) % n, a + j])
return np.array(vs) * (1 + 0.05 * rng.random((len(vs), 1))), faces
def faces_el(faces, ct="u1", it="i4", name="vertex_indices", extra=()):
dt = [(name, "O")] + [(n, t) for n, t, _ in extra]
a = np.empty(len(faces), dtype=dt)
a[name] = [np.array(f, dtype=it) for f in faces]
for n, t, vals in extra:
a[n] = vals
return PlyElement.describe(a, "face", len_types={name: ct}, val_types={name: it[1:] if it[0] in "<>" else it})
def make(name):
seed = sum(map(ord, name))
rng = np.random.default_rng(seed)
comments, obj_info = [], []
if name == "cube-le.ply":
v = np.array([(x, y, z) for x in (0, 1) for y in (0, 1) for z in (0, 1)], dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")])
quads = [[0, 1, 3, 2], [4, 6, 7, 5], [0, 4, 5, 1], [2, 3, 7, 6], [0, 2, 6, 4], [1, 5, 7, 3]]
tris = [t for q in quads for t in ([q[0], q[1], q[2]], [q[0], q[2], q[3]])]
els = [PlyElement.describe(v, "vertex"), faces_el(tris)]
text, byte_order = False, "<"
elif name == "colors-be.ply":
pos, faces = sphere(rng, 12)
n = len(pos)
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("nx", "f4"), ("ny", "f4"), ("nz", "f4"), ("red", "u1"),
("green", "u1"), ("blue", "u1"), ("alpha", "u1"), ("quality", "f4"), ("flags", "u2")])
v["x"], v["y"], v["z"] = pos.T
nn = pos / np.linalg.norm(pos, axis=1)[:, None]
v["nx"], v["ny"], v["nz"] = nn.T
for c in ("red", "green", "blue", "alpha"):
v[c] = rng.integers(0, 256, n)
v["quality"] = rng.random(n)
v["flags"] = rng.integers(0, 65536, n)
els = [PlyElement.describe(v, "vertex"), faces_el(faces, "u1", "u4")]
comments = ["made by plyfile", "big endian, quads and triangles"]
text, byte_order = False, ">"
elif name == "ascii-mixed.ply":
n = 40
v = np.empty(n, dtype=[("red", "u1"), ("z", "f8"), ("y", "f8"), ("x", "f8"), ("s", "f4"), ("t", "f4"), ("intensity", "i1"), ("id", "i4")])
v["red"] = rng.integers(0, 256, n)
for c in ("x", "y", "z"):
v[c] = rng.random(n) * 20 - 10
v["s"], v["t"] = rng.random(n), rng.random(n)
v["intensity"] = rng.integers(-128, 128, n)
v["id"] = rng.integers(-2 ** 31, 2 ** 31, n)
faces = [list(rng.choice(n, size=int(rng.integers(3, 7)), replace=False)) for _ in range(25)]
f = faces_el(faces, "u1", "i4", "vertex_index", extra=[("material", "u1", rng.integers(0, 4, 25)), ("weight", "f4", rng.random(25))])
e = np.empty(10, dtype=[("vertex1", "i4"), ("vertex2", "i4"), ("crease", "u1")])
e["vertex1"], e["vertex2"], e["crease"] = rng.integers(0, n, 10), rng.integers(0, n, 10), rng.integers(0, 256, 10)
m = np.empty(3, dtype=[("params", "O"), ("index", "i2")])
m["params"] = [np.array(rng.random(k), dtype="f4") for k in (2, 0, 5)]
m["index"] = [-1, 0, 7]
els = [PlyElement.describe(v, "vertex"), f, PlyElement.describe(e, "edge"),
PlyElement.describe(m, "material", len_types={"params": "u1"}, val_types={"params": "f4"})]
comments = ["ascii with odd property order", ""]
obj_info = ["num_cols 5", "num_rows 8"]
text, byte_order = True, "="
elif name == "points-le.ply":
n = 500
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("red", "u1"), ("green", "u1"), ("blue", "u1")])
for c in ("x", "y", "z"):
v[c] = rng.random(n) * 100
for c in ("red", "green", "blue"):
v[c] = rng.integers(0, 256, n)
els = [PlyElement.describe(v, "vertex")]
text, byte_order = False, "<"
elif name == "points-ascii-float.ply":
n = 60
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4"), ("red", "f4"), ("green", "f4"), ("blue", "f4"), ("u", "f4"), ("v", "f4")])
for c in v.dtype.names:
v[c] = rng.random(n)
els = [PlyElement.describe(v, "vertex")]
text, byte_order = True, "="
elif name == "types-be.ply":
n = 400
types = [("a", "i1"), ("b", "u1"), ("c", "i2"), ("d", "u2"), ("e", "i4"), ("f", "u4"), ("g", "f4"), ("h", "f8")]
v = np.empty(n, dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")] + types)
v["x"], v["y"] = np.cos(np.arange(n) * 2 * np.pi / n), np.sin(np.arange(n) * 2 * np.pi / n)
v["z"] = 0
for nm, t in types:
info = np.iinfo(t) if t[0] in "iu" else None
v[nm] = rng.integers(info.min, info.max, n, endpoint=True, dtype=t) if info else rng.standard_normal(n) * 1e3
faces = [list(range(n - 1, 99, -1)), list(range(0, 100))] # a 300-gon (ushort count) and a 100-gon
els = [PlyElement.describe(v, "vertex"), faces_el(faces, "u2", "i4")]
text, byte_order = False, ">"
elif name == "big-le.ply":
pos, faces = sphere(rng, 180)
tris = [t for q in faces for t in (([q[0], q[1], q[2]], [q[0], q[2], q[3]]) if len(q) == 4 else ([q[0], q[1], q[2]],))]
v = np.empty(len(pos), dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")])
v["x"], v["y"], v["z"] = pos.T
els = [PlyElement.describe(v, "vertex"), faces_el(tris, "u1", "i4")]
text, byte_order = False, "<"
elif name == "tristrips.ply":
v = np.array([(i, i % 2, 0) for i in range(8)], dtype=[("x", "f4"), ("y", "f4"), ("z", "f4")])
s = np.empty(1, dtype=[("vertex_indices", "O")])
s["vertex_indices"] = [np.array([0, 1, 2, 3, 4, -1, 4, 5, 6, 7], dtype="i4")]
els = [PlyElement.describe(v, "vertex"), PlyElement.describe(s, "tristrips", len_types={"vertex_indices": "i4"}, val_types={"vertex_indices": "i4"})]
text, byte_order = False, "<"
else:
raise ValueError(name)
PlyData(els, text=text, byte_order=byte_order, comments=comments, obj_info=obj_info).write(path(name))
for name in req["make"]:
make(name)
ACC = {"i1": "i8", "u1": "u8", "i2": "i16", "u2": "u16", "i4": "i32", "u4": "u32", "f4": "f32", "f8": "f64"}
PAIRS = [("u", "v"), ("s", "t"), ("texture_u", "texture_v"), ("texture_s", "texture_t")]
def kind(a):
return np.dtype(a.dtype).str[1:]
def index_list(f):
for n in ("vertex_indices", "vertex_index"):
if n in f.data.dtype.names and f.properties[[p.name for p in f.properties].index(n)].__class__.__name__ == "PlyListProperty":
return n
return None
def reference(name):
ply = PlyData.read(path(name))
v = ply["vertex"].data
names = v.dtype.names
taken = set()
attrs = {}
def group(attr, cols, acc_type, dt, fill=None):
arr = np.stack([v[c].astype(dt) for c in cols] + ([np.full(len(v), fill, dtype=dt)] if fill is not None else []), axis=1)
attrs[attr] = {"type": acc_type, "components": arr.shape[1], "crc": crc(le(arr))}
taken.update(cols)
if all(c in names for c in "xyz"):
group("POSITION", ["x", "y", "z"], "f32", "<f4")
if all(c in names for c in ("nx", "ny", "nz")) and all(kind(v[c])[0] == "f" for c in ("nx", "ny", "nz")):
group("NORMAL", ["nx", "ny", "nz"], "f32", "<f4")
if all(c in names for c in ("red", "green", "blue")):
cols = ["red", "green", "blue"] + (["alpha"] if "alpha" in names else [])
ks = {"f" if kind(v[c])[0] == "f" else kind(v[c]) for c in cols}
if ks == {"u1"}:
group("COLOR_0", cols, "unorm8", "u1", None if "alpha" in names else 255)
elif ks == {"u2"}:
group("COLOR_0", cols, "unorm16", "<u2", None if "alpha" in names else 65535)
elif ks == {"f"}:
group("COLOR_0", cols, "f32", "<f4", None if "alpha" in names else 1.0)
for a, b in PAIRS:
if a in names and b in names and kind(v[a])[0] == "f" and kind(v[b])[0] == "f":
group("TEXCOORD_0", [a, b], "f32", "<f4")
break
for c in names:
if c not in taken:
attrs["_" + c] = {"type": ACC[kind(v[c])], "components": 1, "crc": crc(le(v[c]))}
encoding = "ascii" if ply.text else ("binary_big_endian" if ply.byte_order == ">" else "binary_little_endian")
res = {"vertices": len(v), "attrs": attrs, "encoding": encoding,
"comments": list(ply.comments), "objInfo": list(ply.obj_info), "order": [e.name for e in ply.elements]}
face = None
if "face" in ply:
f = ply["face"]
il = index_list(f)
if il:
face = f
if face is not None and len(face.data):
lists = [np.asarray(x, dtype=np.int64) for x in face.data[il]]
sizes = [len(x) for x in lists]
corners = np.concatenate(lists) if lists else np.zeros(0, dtype=np.int64)
res["faces"] = len(lists)
res["corners_crc"] = crc(corners.astype("<u4"))
res["sizes_crc"] = crc(np.array(sizes, dtype="<u4"))
tris, fot = [], []
for i, x in enumerate(lists):
for k in range(1, len(x) - 1):
tris += [x[0], x[k], x[k + 1]]
fot.append(i)
res["tri_crc"] = crc(np.array(tris, dtype="<u4"))
res["tris"] = len(tris) // 3
res["fot_crc"] = crc(np.array(fot, dtype="<u4"))
res["allTri"] = all(s == 3 for s in sizes)
fa = {}
for p in face.properties:
if p.name == il:
continue
col = face.data[p.name]
if p.__class__.__name__ == "PlyListProperty":
items = np.concatenate([np.asarray(x) for x in col]) if len(col) else np.zeros(0)
fa[p.name] = {"list": True, "sizes_crc": crc(np.array([len(x) for x in col], dtype="<u4")),
"items_crc": crc(le(np.asarray(items, dtype=np.dtype(p.val_dtype))))}
else:
fa[p.name] = {"type": ACC[kind(col)], "crc": crc(le(col))}
res["faceAttributes"] = fa
else:
res["faces"] = 0
els = []
for e in ply.elements:
if e.name == "vertex" or (face is not None and e is face):
continue
props = []
for p in e.properties:
col = e.data[p.name]
if p.__class__.__name__ == "PlyListProperty":
vd = np.dtype(p.val_dtype)
items = np.concatenate([np.asarray(x, dtype=vd) for x in col]) if len(col) else np.zeros(0, dtype=vd)
props.append({"name": p.name, "list": True, "sizes_crc": crc(np.array([len(x) for x in col], dtype="<u4")),
"values_crc": crc(le(items))})
else:
props.append({"name": p.name, "crc": crc(le(col))})
els.append({"name": e.name, "count": len(e.data), "props": props})
res["elements"] = els
return res
for name in req["ref"]:
out["ref"][name] = reference(name)
# our encoder's output: every expected vertex property (name, kind, values) and the faces
for o in req["ours"]:
name = o["name"]
try:
ply = PlyData.read(path(o["file"]))
v = ply["vertex"].data
ok, detail = True, "%d vertices" % len(v)
want_names = [p["name"] for p in o["props"]]
if list(v.dtype.names) != want_names:
ok, detail = False, "vertex properties %s, want %s" % (list(v.dtype.names), want_names)
else:
for p in o["props"]:
got = np.asarray(v[p["name"]])
want = np.frombuffer(bytes.fromhex(p["values"]), dtype=p["dtype"])
if kind(got) != np.dtype(p["dtype"]).str[1:]:
ok, detail = False, "%s: type %s, want %s" % (p["name"], kind(got), p["dtype"])
break
if p.get("tol"):
if got.shape != want.shape or float(np.abs(got.astype(np.float64) - want).max(initial=0)) > p["tol"]:
ok, detail = False, "%s: values differ" % p["name"]
break
elif not np.array_equal(got, want):
ok, detail = False, "%s: values differ" % p["name"]
break
if ok:
if o.get("faces") is None:
if "face" in ply:
ok, detail = False, "a point cloud with a face element"
else:
f = ply["face"].data
il = "vertex_indices" if "vertex_indices" in f.dtype.names else "vertex_index"
got = [list(map(int, x)) for x in f[il]]
if got != o["faces"]:
ok, detail = False, "faces differ"
else:
detail += ", %d faces" % len(got)
out["ours"][name] = [ok, detail]
except Exception as e: # noqa: BLE001 - a reference failure is a verdict
out["ours"][name] = [False, "plyfile: %s" % e]
json.dump(out, sys.stdout)