ws-3d: model/gltf (glTF 2.0 JSON + GLB read/write: accessors of every type incl. normalized/sparse/strided/padded matrices, PBR + KHR_materials_*, KHR_texture_transform, images kept encoded, samplers, cameras, KHR_lights_punctual, skins, animations, morph targets, KHR_mesh_quantization, extras/unknown extensions round trip); Khronos sample assets + gltfpack + assimp fixtures

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 09:02:59 -05:00
1 parent c2bfa471a8
commit 5f07ebcbd7
93 files changed
+5167 -5

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
-- tools/fixtures/_gltf_encode: run by tools/fixtures/gltf.py (luau CLI, repo root): decodes every glTF case with our
-- reader and encodes it with our writer as .glb and as .gltf with an external .bin and image files, printing
-- "<file>\t<hex>" lines for the reference tools (assimp, trimesh) to read back. Files: rt_<case>.glb, rt_<case>.gltf.
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/gltf_cases")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
end
local function hex(s: string): string
local out = table.create(#s)
for i = 1, #s do
out[i] = HEX[string.byte(s, i)]
end
return table.concat(out)
end
for i, c in Cases do
local scene, err = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
if scene then
local glb = assert(Gltf.encode(scene, { binary = true }))
print(string.format("rt_%d.glb\t%s", i, hex(buffer.tostring(glb))))
local files = {}
local gltf = assert(Gltf.encode(scene, { external = true, files = files, name = "rt_" .. i .. ".gltf" }))
print(string.format("rt_%d.gltf\t%s", i, hex(buffer.tostring(gltf))))
for name, data in files do
print(name .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data)))
end
else
print("skipped " .. c.name .. ": " .. tostring(err))
end
end
+13 -5
View File
@@ -1,5 +1,5 @@
# Shared helpers for the model fixture generators (obj.py, gltf.py): reference tools through nix.
# assimp_info(ctx, paths) -> [ { meshes, materials, vertices, faces, nodes, min, max, perMesh = [ { vertices, faces } ] } ]
# assimp_info(ctx, paths, raw?) -> [ { meshes, materials, vertices, faces, nodes, min, max, perMesh = [ { vertices, faces } ] } ]
# trimesh_metrics(ctx, paths) -> [ { area, faces, bounds, volume? } ] (trimesh, process=False, every geometry merged)
# luau_encode(ctx, script) -> { name: bytes }: runs a Luau script (repo-relative, .luaurc aliases) that prints
# "<name>\t<hex>" lines: how a generator gets our encoder's output for the reference tools to read back.
@@ -8,10 +8,15 @@ import json, os, re, subprocess, tempfile, shutil
FLOAT = r"(-?[\d.]+(?:e[-+]?\d+)?|-?nan|-?inf)"
def assimp_info(ctx, paths):
def assimp_info(ctx, paths, raw=False):
# raw: `assimp info -r` (no post-processing: no joined vertices, no merged identical meshes)
out = []
for p in paths:
txt = ctx.nix("assimp", ["assimp", "info", p]).decode("utf-8", "replace")
try:
txt = ctx.nix("assimp", ["assimp", "info", p] + (["-r"] if raw else [])).decode("utf-8", "replace")
except subprocess.CalledProcessError:
out.append({"failed": True})
continue
def num(label):
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
@@ -33,8 +38,11 @@ TRIMESH = r"""
import json, sys, trimesh, numpy as np
res = []
for p in json.loads(sys.stdin.read()):
m = trimesh.load(p, force="mesh", process=False)
d = {"area": float(m.area), "faces": int(len(m.faces)), "bounds": [float(v) for v in np.asarray(m.bounds).ravel()] if len(m.faces) else []}
try:
m = trimesh.load(p, force="mesh", process=False)
d = {"area": float(m.area), "faces": int(len(m.faces)), "bounds": [float(v) for v in np.asarray(m.bounds).ravel()] if len(m.faces) else []}
except Exception as e:
d = {"failed": True}
res.append(d)
print(json.dumps(res))
"""
+115
View File
@@ -0,0 +1,115 @@
# glTF fixtures (tools/fixtures.py): Khronos glTF-Sample-Assets models (tests/fixtures/gltf, licences per model
# folder), gltfpack (meshoptimizer) quantized variants (KHR_mesh_quantization, normalized and integer positions,
# KHR_texture_transform), and files exported by assimp, with reference values from assimp (`assimp info`: meshes, faces,
# bounds, materials, animations, cameras, lights) and trimesh (area, triangles, bounds of the whole scene).
# tests/gen/gltf_cases.luau { name, main, data, files = { uri -> bytes }, assimp, trimesh, like? (the original of a
# quantized variant: compare against its references with a tolerance) }
# tests/gen/gltf_xcheck.luau our encoder's .glb and .gltf for every case (tools/fixtures/_gltf_encode.luau), read back
# by assimp and trimesh: { name, case, assimp, trimesh }
import importlib.util, json, os, struct
INPUTS = ["tests/fixtures/gltf", "src/Formats/model/gltf", "src/Formats/codecs/Json", "src/Formats/codecs/Base64",
"tools/fixtures/_model_ref.py", "tools/fixtures/_gltf_encode.luau"]
def ref_module(ctx):
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def assimp_extra(ctx, path):
# cameras / lights / animations counts from assimp info (the shared helper parses meshes / faces / bounds)
import re, subprocess
try:
txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace")
except subprocess.CalledProcessError:
return {}
out = {}
for label in ("Animations", "Cameras", "Lights", "Bones"):
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
if m:
out[label.lower()] = int(m.group(1))
return out
def ply_torus(R=2.0, r=0.5, a=16, b=8):
import math
vs, fs = [], []
for i in range(a):
for j in range(b):
u, v = 2 * math.pi * i / a, 2 * math.pi * j / b
vs.append(((R + r * math.cos(v)) * math.cos(u), r * math.sin(v), (R + r * math.cos(v)) * math.sin(u)))
for i in range(a):
for j in range(b):
p, q = i * b + j, ((i + 1) % a) * b + j
p2, q2 = i * b + (j + 1) % b, ((i + 1) % a) * b + (j + 1) % b
fs.append((p, p2, q2))
fs.append((p, q2, q))
head = "ply\nformat ascii 1.0\nelement vertex %d\nproperty float x\nproperty float y\nproperty float z\nelement face %d\nproperty list uchar int vertex_indices\nend_header\n" % (len(vs), len(fs))
return (head + "".join("%r %r %r\n" % v for v in vs) + "".join("3 %d %d %d\n" % f for f in fs)).encode()
def generate(ctx):
M = ref_module(ctx)
root = os.path.join(ctx.root, "tests", "fixtures", "gltf")
cases = []
for model in sorted(os.listdir(root)):
for variant in sorted(os.listdir(os.path.join(root, model))):
d = os.path.join(root, model, variant)
if not os.path.isdir(d):
continue
mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")]
if not mains:
continue
files = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}
cases.append({"name": model + "/" + variant, "main": mains[0], "path": os.path.join(d, mains[0]), "files": files})
# gltfpack variants of a few models: default (integer positions + texture transform), -vpn (normalized positions),
# -vpf (float positions, quantized normals / uvs)
tmp = M.tempdir()
for model, variant, main in (("BoxTextured", "glTF", "BoxTextured.gltf"), ("Box", "glTF-Binary", "Box.glb"), ("SimpleSkin", "glTF", "SimpleSkin.gltf"), ("MultiUVTest", "glTF-Binary", "MultiUVTest.glb")):
for flag in ("", "-vpn", "-vpf", "-vpi"):
out = os.path.join(tmp, "%s_q%s.glb" % (model, flag))
args = ["gltfpack", "-i", os.path.join(root, model, variant, main), "-o", out, "-kn", "-km"] + ([flag] if flag else [])
ctx.nix("meshoptimizer", args)
cases.append({"name": "gltfpack/%s%s" % (model, flag), "main": os.path.basename(out), "path": out, "files": {}, "like": model + "/" + variant})
# assimp's glTF exporters
ply = os.path.join(tmp, "torus.ply")
with open(ply, "wb") as f:
f.write(ply_torus())
for ext in ("glb", "gltf"):
out = os.path.join(tmp, "torus_assimp." + ext)
ctx.nix("assimp", ["assimp", "export", ply, out, "-f" + ("glb2" if ext == "glb" else "gltf2")])
files = {}
for f in os.listdir(tmp):
if f.startswith("torus_assimp") and f.endswith(".bin"):
files[f] = open(os.path.join(tmp, f), "rb").read()
cases.append({"name": "assimp/torus." + ext, "main": os.path.basename(out), "path": out, "files": files})
infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True)
tms = M.trimesh_metrics(ctx, [c["path"] for c in cases])
for c, a, t in zip(cases, infos, tms):
a.update(assimp_extra(ctx, c["path"]))
c["assimp"] = a
c["trimesh"] = t
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("gltf_cases", cases)
# the reference tools read our output
ours = M.luau_encode(ctx, "tools/fixtures/_gltf_encode.luau")
xtmp = M.tempdir()
names = []
for name, data in sorted(ours.items()):
with open(os.path.join(xtmp, name), "wb") as f:
f.write(data)
if name.endswith(".glb") or name.endswith(".gltf"):
names.append(name)
paths = [os.path.join(xtmp, n) for n in names]
xi = M.assimp_info(ctx, paths, raw=True)
xt = M.trimesh_metrics(ctx, paths)
out = []
for n, a, t in zip(names, xi, xt):
a.update(assimp_extra(ctx, os.path.join(xtmp, n)))
out.append({"name": n, "case": int(n.split("_")[1].split(".")[0]), "assimp": a, "trimesh": t})
ctx.emit("gltf_xcheck", out)