ws-3d: model/stl (ASCII + binary, VisCAM / Magics colours), model/ply (ASCII + binary LE/BE, arbitrary properties, point clouds, raw extra elements), model/off (OFF/COFF/NOFF/STOFF, face colours), read + write; codecs/MeshFlatten (Scene -> one world-space mesh for the mesh-only writers, shared instead of a copy per format); tests vs assimp / trimesh / plyfile, reference tools reading our output

This commit is contained in:
4DBug committed 2026-10-31 09:02:59 -05:00
1 parent fb909438a5
commit 35891a06d1
18 files changed
+5408

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
-- tools/fixtures/_off_encode.luau: run by tools/fixtures/off.py under the luau CLI (no file I/O): encodes the scenes of
-- tests/gen/off_scenes with each listed option set ("default" = {}, "plain" = no colours / normals / texcoords) and
-- prints "<scene>/<encoding> <hex>" lines, which the fixture step hands to trimesh, assimp and its own reader.
local Off = require("@formats/model/off")
local Types = require("@formats/Types")
local Scenes = require("@tests/gen/off_scenes")
local function build(spec: any): Types.Scene
local scene = Types.Scene.new()
for i, m in spec.meshes do
local prims = {}
for _, p in m.prims do
local attrs = {}
for name, a in p.attrs do
attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count)
end
local prim: any = { attributes = attrs, mode = p.mode }
if p.indices then
prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4)
end
if p.faces then
prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4)
end
if p.faceColors then
prim.extras = { faceColors = Types.Scene.accessor(buffer.fromstring(p.faceColors), "unorm8", 4, #p.faceColors // 4) }
end
table.insert(prims, prim)
end
scene.meshes[i] = { primitives = prims }
end
for i, n in spec.nodes do
scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix }
end
scene.roots = spec.roots
return scene
end
local function hex(b: buffer): string
local out = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
out[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(out)
end
local OPTS: { [string]: any } = { default = {}, plain = { colors = false, normals = false, texcoords = false } }
for _, spec in Scenes do
local scene = build(spec)
for e in spec.encodings do
local b, err = Off.encode(scene, OPTS[e])
if not b then
error(spec.name .. "/" .. e .. ": " .. tostring(err))
end
print(spec.name .. "/" .. e .. " " .. hex(b))
end
end
+32
View File
@@ -0,0 +1,32 @@
# 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)
+52
View File
@@ -0,0 +1,52 @@
-- tools/fixtures/_ply_encode.luau: run by tools/fixtures/ply.py under the luau CLI (no file I/O): encodes the scenes of
-- tests/gen/ply_scenes in the three encodings and prints "<scene>/<encoding> <hex>" lines, which the fixture step
-- hands to plyfile and assimp.
local Ply = require("@formats/model/ply")
local Types = require("@formats/Types")
local Scenes = require("@tests/gen/ply_scenes")
local function build(spec: any): Types.Scene
local scene = Types.Scene.new()
for i, m in spec.meshes do
local prims = {}
for _, p in m.prims do
local attrs = {}
for name, a in p.attrs do
attrs[name] = Types.Scene.accessor(buffer.fromstring(a[3]), a[1], a[2], p.count)
end
local prim: any = { attributes = attrs, mode = p.mode }
if p.indices then
prim.indices = Types.Scene.accessor(buffer.fromstring(p.indices), "u32", 1, #p.indices // 4)
end
if p.faces then
prim.faces = Types.Scene.accessor(buffer.fromstring(p.faces), "u32", 1, #p.faces // 4)
end
table.insert(prims, prim)
end
scene.meshes[i] = { primitives = prims }
end
for i, n in spec.nodes do
scene.nodes[i] = { mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix }
end
scene.roots = spec.roots
return scene
end
local function hex(b: buffer): string
local out = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
out[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(out)
end
for _, spec in Scenes do
local scene = build(spec)
for _, e in { "ascii", "binary_little_endian", "binary_big_endian" } do
local b, err = Ply.encode(scene, { format = e })
if not b then
error(spec.name .. "/" .. e .. ": " .. tostring(err))
end
print(spec.name .. "/" .. e .. " " .. hex(b))
end
end
+307
View File
@@ -0,0 +1,307 @@
# 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)
+56
View File
@@ -0,0 +1,56 @@
-- tools/fixtures/_stl_encode.luau: run by tools/fixtures/stl.py under the luau CLI (no file I/O): encodes the scenes of
-- tests/gen/stl_scenes with every encoding they list and prints "<scene>/<encoding> <hex>" lines, which the fixture
-- step hands to trimesh and assimp.
local Stl = require("@formats/model/stl")
local Types = require("@formats/Types")
local Scenes = require("@tests/gen/stl_scenes")
local function acc(s: string, t: string, comps: number, count: number): Types.Accessor
return Types.Scene.accessor(buffer.fromstring(s), t, comps, count)
end
local function build(spec: any): Types.Scene
local scene = Types.Scene.new()
for i, m in spec.meshes do
local prims = {}
for _, p in m.prims do
local prim: any = { attributes = { POSITION = acc(p.pos, p.posType or "f32", 3, p.count) }, mode = p.mode }
if p.indices then
prim.indices = acc(p.indices, "u32", 1, #p.indices // 4)
end
if p.faces then
prim.faces = acc(p.faces, "u32", 1, #p.faces // 4)
end
if p.color then
prim.attributes.COLOR_0 = acc(p.color, "unorm8", 4, p.count)
end
table.insert(prims, prim)
end
scene.meshes[i] = { name = m.name, primitives = prims }
end
for i, n in spec.nodes do
scene.nodes[i] = { name = n.name, mesh = n.mesh, children = n.children or {}, translation = n.translation, rotation = n.rotation, scale = n.scale, matrix = n.matrix }
end
scene.roots = spec.roots
return scene
end
local function hex(b: buffer): string
local out = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
out[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(out)
end
local OPTS: { [string]: any } = { binary = {}, ascii = { ascii = true }, viscam = { colors = "viscam" }, magics = { colors = "magics" } }
for _, spec in Scenes do
local scene = build(spec)
for _, e in spec.encodings do
local b, err = Stl.encode(scene, OPTS[e])
if not b then
error(spec.name .. "/" .. e .. ": " .. tostring(err))
end
print(spec.name .. "/" .. e .. " " .. hex(b))
end
end
+112
View File
@@ -0,0 +1,112 @@
# STL reference values (run by tools/fixtures/stl.py through ctx.python(["trimesh", "numpy"], ...), python -I).
# stdin: JSON {"dir": tmp, "make": [[name, kind, file_type, seed]], "ref": [name], "ours": [{name, file, ...}]}
# stdout: JSON {"ref": {name: {...}}, "ours": {name: [ok, detail]}}
# make: meshes made and exported by trimesh itself (binary / ascii STL)
# ref: every file read with trimesh.exchange.stl.load_stl (the raw arrays, no processing): facet count, CRC-32 of
# the f32 triangle vertices / facet normals (as the file has them), area, bounds, the raw attribute words
# ours: our encoder's output read back by trimesh and compared with the expected world-space triangles
import json, os, sys, zlib
import numpy as np
import trimesh
from trimesh.exchange import stl as tstl
req = json.load(sys.stdin)
d = req["dir"]
out = {"ref": {}, "ours": {}}
def path(n):
return os.path.join(d, n)
for name, kind, ftype, seed in req["make"]:
rng = np.random.default_rng(seed)
if kind == "icosphere":
m = trimesh.creation.icosphere(subdivisions=3, radius=2.5)
elif kind == "box":
m = trimesh.creation.box(extents=(1.5, 2.0, 0.25))
elif kind == "capsule":
m = trimesh.creation.capsule(height=3.0, radius=0.7)
else:
tri = (rng.random((1500, 3, 3)) * 200 - 100).astype(np.float32)
m = trimesh.Trimesh(vertices=tri.reshape(-1, 3), faces=np.arange(4500).reshape(-1, 3), process=False)
data = m.export(file_type=ftype)
with open(path(name), "wb") as f:
f.write(data.encode() if isinstance(data, str) else data)
def load(name):
with open(path(name), "rb") as f:
r = tstl.load_stl(f)
if "geometry" in r: # several solids
parts = list(r["geometry"].values())
if not parts:
return np.zeros((0, 3)), np.zeros((0, 3), dtype=np.int64), np.zeros((0, 3)), None
vs, fs, ns, off = [], [], [], 0
for g in parts:
vs.append(g["vertices"])
fs.append(np.asarray(g["faces"]) + off)
ns.append(g["face_normals"])
off += len(g["vertices"])
# trimesh does not read normals written on the "outer loop" line: no normals then
nrm = None if any(x is None for x in ns) else np.concatenate(ns)
return np.concatenate(vs), np.concatenate(fs), nrm, None
attr = r.get("face_attributes", {}).get("stl")
return np.asarray(r["vertices"]), np.asarray(r["faces"]), np.asarray(r["face_normals"]), attr
def crc(a, dt):
return zlib.crc32(np.ascontiguousarray(np.asarray(a).astype(dt)).tobytes())
for name in req["ref"]:
v, f, n, attr = load(name)
tri = v[f].astype(np.float32) # (n, 3, 3)
m = trimesh.Trimesh(vertices=v, faces=f, process=False)
res = {
"facets": int(len(f)),
"pos_crc": crc(tri, "<f4"),
"area": float(m.area) if len(f) else 0.0,
"bounds": [float(x) for x in (m.bounds.reshape(-1) if len(f) else np.zeros(6))],
}
if n is not None:
res["nrm_crc"] = crc(np.repeat(np.asarray(n, dtype=np.float32), 3, axis=0), "<f4")
if attr is not None:
res["attr"] = [int(x) for x in attr]
out["ref"][name] = res
# our encoder's files
for o in req["ours"]:
name = o["name"]
try:
v, f, n, attr = load(o["file"])
tri = v[f].astype(np.float32).reshape(-1, 9)
want = np.frombuffer(bytes.fromhex(o["expect"]), dtype="<f4").reshape(-1, 9)
if tri.shape != want.shape:
out["ours"][name] = [False, "facet count %s, want %s" % (tri.shape, want.shape)]
continue
tol = 0 if o["exact"] else 1e-5 * max(1.0, float(np.abs(want).max()))
err = float(np.abs(tri.astype(np.float64) - want.astype(np.float64)).max()) if len(want) else 0.0
if err > tol:
out["ours"][name] = [False, "positions differ by %g" % err]
continue
# the stored facet normals: the right-hand rule normal of each triangle
t = want.astype(np.float64).reshape(-1, 3, 3)
cn = np.cross(t[:, 1] - t[:, 0], t[:, 2] - t[:, 0])
ln = np.linalg.norm(cn, axis=1)
cn[ln > 0] /= ln[ln > 0, None]
nerr = float(np.abs(np.asarray(n, dtype=np.float64) - cn).max()) if len(want) else 0.0
if nerr > 1e-4:
out["ours"][name] = [False, "facet normals differ by %g" % nerr]
continue
if "colors" in o:
want_words = o["colors"]
got = [int(x) for x in attr] if attr is not None else []
if got != want_words:
out["ours"][name] = [False, "attribute words differ"]
continue
out["ours"][name] = [True, "%d facets, max error %g" % (len(want), err)]
except Exception as e: # noqa: BLE001 - a reference failure is a verdict
out["ours"][name] = [False, "trimesh: %s" % e]
json.dump(out, sys.stdout)
+343
View File
@@ -0,0 +1,343 @@
# 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/Formats/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})
+192
View File
@@ -0,0 +1,192 @@
# 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/Formats/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})
+383
View File
@@ -0,0 +1,383 @@
# STL fixtures (tools/fixtures.py).
# tests/gen/stl_scenes.luau scenes for the encoder (indexed grid with colours, polygons under a TRS node, a node tree
# with a matrix, a mirror and u16 positions) with the expected world-space triangle soup
# (computed here with numpy) and the expected colour attribute words
# tests/gen/stl.luau cases: STL files made by trimesh (binary / ascii), by assimp (obj / ply -> stl / stlb)
# and by hand here (binary starting with "solid", VisCAM and Magics colours, raw attribute
# words, odd ASCII: case, tabs, CRLF, several solids, quads, no endsolid, trailing bytes,
# empty), each with reference values from trimesh's raw STL reader (facets, CRC-32 of the
# f32 vertices and normals, area, bounds, attribute words); `ours`: our encoder's output
# (run through the luau CLI: tools/fixtures/_stl_encode.luau) read back by trimesh and
# assimp, as verdicts
import json, math, os, shutil, struct, subprocess, tempfile, zlib
INPUTS = ["src/Formats/model/stl", "tools/fixtures/_stl_reference.py", "tools/fixtures/_stl_encode.luau"]
def f32(x):
return struct.unpack("<f", struct.pack("<f", x))[0]
def binary_stl(header, tris, normals=None, attrs=None, extra=b""):
out = bytearray(header.ljust(80, b"\0")[:80])
out += struct.pack("<I", len(tris))
for i, t in enumerate(tris):
n = normals[i] if normals else (0.0, 0.0, 0.0)
out += struct.pack("<3f", *n)
for v in t:
out += struct.pack("<3f", *v)
out += struct.pack("<H", attrs[i] if attrs else 0)
return bytes(out) + extra
def rand_tris(rng, n, scale=10.0):
return [[tuple(f32(rng.uniform(-scale, scale)) for _ in range(3)) for _ in range(3)] for _ in range(n)]
def unit_normal(t):
ux, uy, uz = (t[1][k] - t[0][k] for k in range(3))
vx, vy, vz = (t[2][k] - t[0][k] for k in range(3))
n = (uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx)
ln = math.sqrt(sum(c * c for c in n)) or 1.0
return tuple(f32(c / ln) for c in n)
def x8(v):
return (v * 255 + 15) // 31
def to5(c):
return (c * 31 + 127) // 255
def soup_bytes(tris):
return b"".join(struct.pack("<3f", *v) for t in tris for v in t)
def crc(b):
return zlib.crc32(b)
# --- hand-made files: (name, data, expected) where expected holds what trimesh cannot tell us
def handmade(rng):
cases = []
tris = rand_tris(rng, 12)
cases.append(("bin-solid-header.stl", binary_stl(b"solid this is binary all the same", tris, [unit_normal(t) for t in tris]), {}))
# VisCAM: bit 15 = valid, red high; some facets invalid
tris = rand_tris(rng, 40)
words, cols = [], []
for i in range(40):
r, g, b = rng.randrange(32), rng.randrange(32), rng.randrange(32)
if i % 7 == 3:
words.append(rng.randrange(0x8000)) # not valid: the default (opaque white)
cols.append((255, 255, 255, 255))
else:
words.append(0x8000 | r << 10 | g << 5 | b)
cols.append((x8(r), x8(g), x8(b), 255))
cases.append(("viscam.stl", binary_stl(b"VisCAM colours", tris, None, words), {"colors": "viscam", "cols": cols}))
# Magics: COLOR= object colour, bit 15 clear = own colour, red low
tris = rand_tris(rng, 40)
dc = (200, 100, 50, 180)
header = b"magics part COLOR=" + bytes(dc) + b",MATERIAL=" + bytes(range(12))
words, cols = [], []
for i in range(40):
r, g, b = rng.randrange(32), rng.randrange(32), rng.randrange(32)
if i % 5 == 0:
words.append(0x8000 | rng.randrange(0x8000))
cols.append(dc)
else:
words.append(r | g << 5 | b << 10)
cols.append((x8(r), x8(g), x8(b), 255))
cases.append(("magics.stl", binary_stl(header, tris, None, words), {"colors": "magics", "cols": cols, "defaultColor": list(dc)}))
# raw attribute words (no colour convention)
tris = rand_tris(rng, 9)
words = [rng.randrange(1, 0x8000) for _ in range(9)]
cases.append(("attrs.stl", binary_stl(b"attribute words", tris, None, words), {"words": words}))
cases.append(("bin-empty.stl", binary_stl(b"empty", []), {}))
# ASCII oddities: case, tabs, CRLF, exponents, two solids (one unnamed), blank lines
t1, t2 = rand_tris(rng, 3), rand_tris(rng, 2)
s = "SOLID first part\r\n"
for t in t1:
s += "\tFACET NORMAL %.6e %.6e %.6e\r\n\t\tOUTER LOOP\r\n" % unit_normal(t)
for v in t:
s += "\t\t\tVERTEX %.9g\t%.9e %r\r\n" % (v[0], v[1], v[2])
s += "\t\tENDLOOP\r\n\tENDFACET\r\n\r\n"
s += "ENDSOLID first part\r\n\nsolid\n"
for t in t2:
s += "facet normal %r %r %r outer loop\n" % unit_normal(t)
s += " ".join("vertex %r %r %r" % v for v in t) + "\nendloop endfacet\n"
s += "endsolid\n"
normals = [tuple(f32(float("%.6e" % c)) for c in unit_normal(t)) for t in t1] + [unit_normal(t) for t in t2]
cases.append(("ascii-odd.stl", s.encode(), {"solids": ["first part", ""], "solidFacets": [3, 2], "normals": normals}))
# a quad facet (fan-triangulated: trimesh cannot read it, the expectation is computed here)
q = [(0.0, 0.0, 0.0), (2.0, 0.0, 0.0), (2.0, 1.0, 0.0), (0.0, 1.0, 0.5)]
s = "solid quad\nfacet normal 0 0 1\nouter loop\n" + "".join("vertex %r %r %r\n" % v for v in q) + "endloop\nendfacet\nendsolid quad\n"
qt = [[q[0], q[1], q[2]], [q[0], q[2], q[3]]]
cases.append(("ascii-quad.stl", s.encode(), {"self": True, "tris": qt, "normals": [(0.0, 0.0, 1.0)] * 2}))
# no final endsolid
t3 = rand_tris(rng, 2)
s = "solid open\n" + "".join("facet normal 0 0 0\nouter loop\n" + "".join("vertex %r %r %r\n" % v for v in t) + "endloop\nendfacet\n" for t in t3)
cases.append(("ascii-noend.stl", s.encode(), {"self": True, "tris": t3, "normals": [(0.0, 0.0, 0.0)] * 2}))
# binary with trailing bytes (size != 84 + 50 n: trimesh refuses, we tolerate)
t4 = rand_tris(rng, 5)
n4 = [unit_normal(t) for t in t4]
cases.append(("bin-trailing.stl", binary_stl(b"trailing junk", t4, n4, extra=b"JUNK!!!"), {"self": True, "tris": t4, "normals": n4}))
return cases
# --- encoder scenes (also used by tests/model/stl.luau for round trips)
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 mmul(a, b):
return [[sum(a[i][k] * b[k][j] for k in range(4)) for j in range(4)] for i in range(4)]
def det3(m):
return (m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
+ m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]))
EYE = [[1.0 if i == j else 0.0 for j in range(4)] for i in range(4)]
def mat_trs(node):
"""row-major 4x4 of a node (glTF: column-major matrix, or T * R * S)"""
if "matrix" in node:
c = node["matrix"]
return [[c[j * 4 + i] for j in range(4)] for i in range(4)]
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[0][0] * sx, r[0][1] * sy, r[0][2] * sz, tx], [r[1][0] * sx, r[1][1] * sy, r[1][2] * sz, ty],
[r[2][0] * sx, r[2][1] * sy, r[2][2] * sz, tz], [0.0, 0.0, 0.0, 1.0]]
def unpack(fmt, data):
n = len(data) // struct.calcsize("<" + fmt)
return list(struct.unpack("<%d%s" % (n, fmt), data))
def expected_soup(sc):
"""world-space triangles (fan-triangulated polygons, reversed winding under a mirror) as f32 bytes, and the
colour of each facet's first vertex"""
out, cols = [], []
def prim_tris(p):
n = p["count"]
flat = unpack("H" if p.get("posType") == "u16" else "f", p["pos"])
pos = [flat[i * 3:i * 3 + 3] for i in range(n)]
idx = unpack("I", p["indices"]) if "indices" in p else list(range(n))
if p["mode"] == "polygons":
tris, at = [], 0
for s in unpack("I", p["faces"]):
for k in range(1, s - 1):
tris.append((idx[at], idx[at + k], idx[at + k + 1]))
at += s
else:
tris = [tuple(idx[i:i + 3]) for i in range(0, len(idx) - len(idx) % 3, 3)]
return pos, tris
def walk(ni, parent):
node = sc["nodes"][ni - 1]
has = any(k in node for k in ("matrix", "translation", "rotation", "scale"))
m = mmul(parent, mat_trs(node)) if has else parent
if "mesh" in node:
for p in sc["meshes"][node["mesh"] - 1]["prims"]:
pos, tris = prim_tris(p)
flip = det3(m) < 0
w = [[m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2] + m[i][3] for i in range(3)] for v in pos]
col = p.get("color")
for a, b, c in tris:
if flip:
b, c = c, b
out.append(w[a] + w[b] + w[c])
if col is not None:
cols.append(tuple(col[a * 4:a * 4 + 4]))
for c in node.get("children", []):
walk(c, m)
for r in sc["roots"]:
walk(r, EYE)
return b"".join(struct.pack("<9f", *t) for t in out), cols
def pack(fmt, vals):
return struct.pack("<%d%s" % (len(vals), fmt), *vals)
def scenes(rng):
out = []
# grid: indexed, colours on 5-bit steps, no transform
W, H = 7, 6
pos = [v for y in range(H) for x in range(W) for v in (x * 0.5, y * 0.5, rng.uniform(-1, 1))]
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]
col = bytes(v for _ in range(W * H) for v in (x8(rng.randrange(32)), x8(rng.randrange(32)), x8(rng.randrange(32)), 255))
out.append({"name": "grid", "nodes": [{"mesh": 1, "name": "grid"}], "roots": [1], "meshes": [{"name": "grid", "prims": [
{"mode": "triangles", "count": W * H, "pos": pack("f", pos), "indices": pack("I", idx), "color": col}]}],
"encodings": ["binary", "ascii", "viscam", "magics"]})
# polygons under a TRS node
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]
corners = [0, 1, 2, 3, 1, 4, 5, 6, 7, 2, 0, 3, 8]
out.append({"name": "polys", "nodes": [{"mesh": 1, "translation": [1, 2, 3], "rotation": quat(rng), "scale": [2, 0.5, 1.5]}], "roots": [1],
"meshes": [{"name": "polys", "prims": [{"mode": "polygons", "count": 9, "pos": pack("f", pv),
"indices": pack("I", corners), "faces": pack("I", [4, 6, 3])}]}],
"encodings": ["binary", "ascii"]})
# a node tree: a matrix root, a mirrored child (winding flips), a child without its own transform, u16 positions,
# a soup without indices
soup = [rng.uniform(-3, 3) for _ in range(45)]
u16 = [rng.randrange(0, 100) for _ in range(18)]
c, s = math.cos(0.7), math.sin(0.7)
m = [c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 5, -2, 0.5, 1] # column-major: rotate about z, translate
out.append({"name": "tree", "nodes": [
{"mesh": 2, "matrix": m, "children": [2, 3]},
{"mesh": 1, "scale": [-1, 1, 1], "translation": [0, 0, 1]},
{"mesh": 3, "name": "plain"},
], "roots": [1], "meshes": [
{"name": "soup", "prims": [{"mode": "triangles", "count": 15, "pos": pack("f", soup)}]},
{"name": "u16", "prims": [{"mode": "triangles", "count": 6, "posType": "u16", "pos": pack("H", u16),
"indices": pack("I", [0, 1, 2, 2, 3, 4, 4, 5, 0, 1, 3, 5])}]},
{"name": "pair", "prims": [{"mode": "triangles", "count": 4, "pos": pack("f", [0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0.25]),
"indices": pack("I", [0, 1, 2, 0, 2, 3])}]},
], "encodings": ["binary", "ascii"]})
for sc in out:
soup_b, cols = expected_soup(sc)
sc["expect"] = soup_b
sc["exact"] = sc["name"] == "grid"
if cols:
sc["viscamWords"] = [0x8000 | to5(r) << 10 | to5(g) << 5 | to5(b) for r, g, b, _ in cols]
sc["magicsWords"] = [to5(r) | to5(g) << 5 | to5(b) << 10 for r, g, b, _ in cols]
return out
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def assimp_info(ctx, path):
txt = ctx.nix("assimp", ["assimp", "info", path]).decode(errors="replace")
faces = verts = None
for line in txt.split("\n"):
if line.startswith("Faces:"):
faces = int(line.split()[1])
if line.startswith("Vertices:"):
verts = int(line.split()[1])
return faces, verts
def generate(ctx):
rng = ctx.rng(31)
tmp = tempfile.mkdtemp(prefix="formats-stl-")
try:
_generate(ctx, rng, tmp)
finally:
shutil.rmtree(tmp, ignore_errors=True)
def _generate(ctx, rng, tmp):
# scenes first: the encoder script reads them
sc = scenes(rng)
ctx.emit("stl_scenes", sc)
files = {}
hand = handmade(rng)
for name, data, _ in hand:
files[name] = data
# assimp conversions: an OBJ with quads and a PLY -> ASCII and binary STL
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(12))
obj += "f 1 2 3 4\nf 5 6 7\nf 8 9 10 11 12\nf 2 4 6\n"
ply = "ply\nformat ascii 1.0\nelement vertex 5\nproperty float x\nproperty float y\nproperty float z\nelement face 3\nproperty list uchar int vertex_indices\nend_header\n"
ply += "".join("%r %r %r\n" % (f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5)), f32(rng.uniform(-5, 5))) for _ in range(5))
ply += "3 0 1 2\n4 0 2 3 4\n3 4 3 1\n"
with open(os.path.join(tmp, "in.obj"), "w") as f:
f.write(obj)
with open(os.path.join(tmp, "in.ply"), "w") as f:
f.write(ply)
for src, dst, fid in (("in.obj", "assimp-obj.stl", "stl"), ("in.obj", "assimp-obj-b.stl", "stlb"), ("in.ply", "assimp-ply-b.stl", "stlb")):
ctx.nix("assimp", ["assimp", "export", os.path.join(tmp, src), os.path.join(tmp, dst), "-f" + fid])
for name, data in files.items():
with open(os.path.join(tmp, name), "wb") as f:
f.write(data)
make = [["trimesh-icosphere.stl", "icosphere", "stl", 1], ["trimesh-icosphere-ascii.stl", "icosphere", "stl_ascii", 1],
["trimesh-box.stl", "box", "stl", 2], ["trimesh-capsule-ascii.stl", "capsule", "stl_ascii", 3],
["trimesh-soup.stl", "soup", "stl", 4], ["trimesh-soup-ascii.stl", "soup", "stl_ascii", 5]]
refnames = [m[0] for m in make] + ["assimp-obj.stl", "assimp-obj-b.stl", "assimp-ply-b.stl"]
refnames += [n for n, _, e in hand if not e.get("self")]
# our encoder's output (the luau CLI prints "<scene>/<encoding> <hex>" lines)
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_stl_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.stl" % (scene_name, encoding)
with open(os.path.join(tmp, fn), "wb") as f:
f.write(bytes.fromhex(hexdata.strip()))
o = {"name": label, "file": fn, "expect": s["expect"].hex(), "exact": s["exact"]}
if encoding == "viscam":
o["colors"] = s["viscamWords"]
elif encoding == "magics":
o["colors"] = s["magicsWords"]
ours.append(o)
code = open(os.path.join(ctx.root, "tools", "fixtures", "_stl_reference.py")).read()
try:
res = json.loads(ctx.python(["trimesh", "numpy"], code, input=json.dumps({"dir": tmp, "make": make, "ref": refnames, "ours": ours}).encode()))
except subprocess.CalledProcessError as e:
raise RuntimeError("stl reference: " + e.stderr.decode(errors="replace")[-3000:])
verdicts = []
for o in ours:
ok, detail = res["ours"][o["name"]]
# assimp reads it too
faces, _ = assimp_info(ctx, os.path.join(tmp, o["file"]))
want = len(bytes.fromhex(o["expect"])) // 36
if faces != want:
ok, detail = False, "assimp reads %s faces, want %d" % (faces, want)
verdicts.append({"name": o["name"], "ok": ok, "detail": detail})
cases = []
for name in refnames:
with open(os.path.join(tmp, name), "rb") as f:
data = f.read()
r = res["ref"][name]
c = {"name": name, "data": data, "facets": r["facets"], "pos_crc": r["pos_crc"], "area": r["area"], "bounds": r["bounds"]}
extra = next((e for n, _, e in hand if n == name), {})
if "nrm_crc" in r:
c["nrm_crc"] = r["nrm_crc"]
elif "normals" in extra: # the normals written here (%.6e / repr of f32 values, read as f32)
c["nrm_crc"] = crc(b"".join(struct.pack("<3f", *n) * 3 for n in extra["normals"]))
if "cols" in extra:
c["colors"] = extra["colors"]
c["col_crc"] = crc(b"".join(bytes(col) * 3 for col in extra["cols"]))
# the colour words trimesh read must be the ones written
assert r.get("attr") is not None
if "defaultColor" in extra:
c["defaultColor"] = extra["defaultColor"]
if "words" in extra:
assert r["attr"] == extra["words"]
c["attr_crc"] = crc(struct.pack("<%dH" % len(extra["words"]), *extra["words"]))
if "solids" in extra:
c["solids"] = extra["solids"]
c["solidFacets"] = extra["solidFacets"]
c["binary"] = not data.lstrip()[:5].lower() == b"solid" or (len(data) >= 84 and 84 + 50 * struct.unpack("<I", data[80:84])[0] == len(data))
cases.append(c)
for name, data, e in hand:
if e.get("self"):
tris = e["tris"]
cases.append({"name": name, "data": data, "facets": len(tris), "pos_crc": crc(soup_bytes(tris)),
"nrm_crc": crc(b"".join(struct.pack("<3f", *n) * 3 for n in e["normals"])),
"binary": not data.startswith(b"solid")})
ctx.emit("stl", {"cases": cases, "ours": verdicts})