merge ws/3d3

This commit is contained in:
4DBug committed 2026-10-31 15:39:55 -05:00
commit 47345b2c8f
96 files changed
+24729 -21

No files matched your search

+33
View File
@@ -919,6 +919,19 @@ do
bench("3mf encode", 2, buffer.len(tmf), function()
ThreeMf.encode(scene)
end)
local Wrl = require("@formats/model/vrml")
local X3d = require("@formats/model/x3d")
local wrl = assert(Wrl.encode(scene))
bench("vrml decode (" .. buffer.len(wrl) // 1000 .. " KB)", 2, buffer.len(wrl), function()
Wrl.decode(Bytes.reader(wrl))
end)
bench("vrml encode", 2, buffer.len(wrl), function()
Wrl.encode(scene)
end)
local x3d = assert(X3d.encode(scene))
bench("x3d xml decode (" .. buffer.len(x3d) // 1000 .. " KB)", 2, buffer.len(x3d), function()
X3d.decode(Bytes.reader(x3d))
end)
local V = 128
local grid = Types.Voxels.new(V, V, V)
for z = 0, V - 1 do
@@ -1125,6 +1138,26 @@ do
jitTune(false)
end
end
do
-- Draco (codecs/model/Draco): the Stanford bunny (35k points, 69k faces, Edgebreaker valence, normals) and a UV
-- sphere with seams; MB/s of decoded output (u32 indices + f32 attributes per point), plus triangles per second.
local Draco = require("@formats/codecs/model/Draco")
local DC = require("@tests/gen/draco_cases")
for _, c in DC do
if c.name == "enc/bunny_norm.obj.cl7" or c.name == "enc/uvsphere.obj.cl10" or c.name == "enc/uvsphere.obj.cl0" then
local data = buffer.fromstring(c.data)
local g = assert(Draco.decode(data))
local n = g.numFaces * 12
for _, a in g.attributes do
n += buffer.len(a.data)
end
local dt = bench("draco " .. string.sub(c.name, 5), 3, n, function()
Draco.decode(data)
end)
print(string.format("%-8s %-30s %8.0f triangles/s", runtime, " (" .. g.numFaces .. " faces)", g.numFaces / dt))
end
end
end
do
-- NBT / voxels (ws-voxel): a chunk-like NBT tree (24 sections with packed long arrays, 4000 entity-like compounds)
-- through codecs/text/Nbt (binary and SNBT), 1M packed 5-bit indices, a 64^3 Sponge schematic and Qubicle file
+101
View File
@@ -0,0 +1,101 @@
# 3DS fixtures (tools/fixtures.py): assimp's 3DS test models (test/models/3DS and test/models-nonbsd/3DS: meshes,
# materials, textures, keyframer hierarchies, pivots, rotation / camera / target animation, cameras, lights; read from
# the nixpkgs assimp source, never committed) and files written by assimp's 3DS exporter from glTF sample models, with
# reference values from assimp (`assimp info -r`: meshes, faces, vertices, materials, animations, cameras, lights,
# nodes; world bounds from its PreTransformVertices export). Then our encoder's output (tools/fixtures/_3ds_encode.luau,
# from every case and the glTF models) read back by assimp. (Blender 5's 3DS importer is an extension that is not
# installed by default, so assimp is the only reference.)
# tests/gen/3ds_cases.luau { name, data, assimp }
# tests/gen/3ds_gltf.luau glTF sample models for the writer round trips: { name, data, files }
# tests/gen/3ds_xcheck.luau { name, case? | gltf?, assimp }
import importlib.util, os
INPUTS = ["src/Formats/model/3ds", "tests/fixtures/gltf", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py",
"tools/fixtures/_3ds_encode.luau"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location("_" + name.replace(".", "_"), os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
GLTF = ("Box", "BoxTextured", "BoxVertexColors", "Cameras", "SimpleMeshes", "RiggedSimple", "SimpleSkin", "MultiUVTest",
"NegativeScaleTest", "PointLightIntensityTest", "AnimatedTriangle", "TextureCoordinateTest", "TextureTransformTest",
"InterpolationTest", "LightVisibility")
def reference(ctx, M, X, paths, tmp):
out = []
for p, a in zip(paths, M.assimp_info(ctx, paths, raw=True)):
a.update(X.assimp_extra(ctx, p))
a.pop("min", None)
a.pop("max", None)
a.pop("perMesh", None)
if not a.get("failed"):
a.update(X.ptv_bounds(ctx, p, tmp))
out.append(a)
return out
def generate(ctx):
M = load(ctx, "_model_ref")
X = load(ctx, "fbx")
tmp = M.tempdir()
src = X.assimp_src(ctx)
cases = []
for sub in ("models", "models-nonbsd"):
d = os.path.join(src, "test", sub, "3DS")
for f in sorted(os.listdir(d)):
if f.lower().endswith(".3ds"):
cases.append({"name": "assimp/%s/%s" % (sub, f), "path": os.path.join(d, f)})
# assimp's exporter
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
picks = []
for model in GLTF:
d0 = os.path.join(gl, model)
if not os.path.isdir(d0):
continue
for variant in sorted(os.listdir(d0)):
d = os.path.join(d0, 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
main = os.path.join(d, mains[0])
picks.append({"name": model + "/" + variant, "data": open(main, "rb").read(),
"files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}})
out = os.path.join(tmp, model + ".3ds")
try:
ctx.nix("assimp", ["assimp", "export", main, out, "-f3ds"])
cases.append({"name": "assimp-export/" + model + ".3ds", "path": out})
except Exception:
pass
break
refs = reference(ctx, M, X, [c["path"] for c in cases], tmp)
for c, a in zip(cases, refs):
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("3ds_cases", cases)
ctx.emit("3ds_gltf", picks)
# assimp reads our files
ours = M.luau_encode(ctx, "tools/fixtures/_3ds_encode.luau")
xtmp = M.tempdir()
names = sorted(n for n in ours if n.endswith(".3ds"))
paths = []
for n in names:
p = os.path.join(xtmp, n)
with open(p, "wb") as f:
f.write(ours[n])
paths.append(p)
xs = []
for n, a in zip(names, reference(ctx, M, X, paths, xtmp)):
kind, idx = n[:-4].split("_")
e = {"name": n, "assimp": a}
e["case" if kind == "case" else "gltf"] = int(idx)
xs.append(e)
ctx.emit("3ds_xcheck", xs)
+44
View File
@@ -0,0 +1,44 @@
-- tools/fixtures/_3ds_encode: run by tools/fixtures/3ds.py (luau CLI, repo root): decodes every 3DS case and every
-- glTF sample model with our readers and writes them with our 3DS writer, printing "<file>\t<hex>" lines for assimp
-- to read back. Files: case_<i>.3ds, gltf_<i>.3ds.
local ThreeDs = require("@formats/model/3ds")
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/3ds_cases")
local Picks = require("@tests/gen/3ds_gltf")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
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] = HEX[buffer.readu8(b, i)]
end
return table.concat(out)
end
local function emit(name: string, scene: any)
local out, err = ThreeDs.encode(scene)
if out then
print(name .. "\t" .. hex(out))
else
print("encode failed " .. name .. ": " .. tostring(err))
end
end
for i, c in Cases do
local scene, err = ThreeDs.decode(Bytes.reader(buffer.fromstring(c.data)))
if scene then
emit(string.format("case_%d.3ds", i), scene)
else
print("skipped " .. c.name .. ": " .. tostring(err))
end
end
for i, g in Picks do
local scene = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files })
if scene then
emit(string.format("gltf_%d.3ds", i), scene)
end
end
+44
View File
@@ -0,0 +1,44 @@
// Dumps a decoded Draco file: points, faces and every attribute's per-point bytes (hex), for the fixture generator.
#include "draco/compression/decode.h"
#include <cstdio>
#include <fstream>
#include <iterator>
#include <vector>
static void hex(const uint8_t* p, size_t n) { for (size_t i = 0; i < n; ++i) printf("%02x", p[i]); }
int main(int argc, char** argv) {
std::ifstream f(argv[1], std::ios::binary);
std::vector<char> data((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
draco::DecoderBuffer buf;
buf.Init(data.data(), data.size());
auto type = draco::Decoder::GetEncodedGeometryType(&buf);
if (!type.ok()) { printf("ERROR %s\n", type.status().error_msg()); return 0; }
draco::Decoder dec;
std::unique_ptr<draco::PointCloud> pc;
std::unique_ptr<draco::Mesh> mesh;
if (type.value() == draco::TRIANGULAR_MESH) {
auto r = dec.DecodeMeshFromBuffer(&buf);
if (!r.ok()) { printf("ERROR %s\n", r.status().error_msg()); return 0; }
mesh = std::move(r).value();
} else {
auto r = dec.DecodePointCloudFromBuffer(&buf);
if (!r.ok()) { printf("ERROR %s\n", r.status().error_msg()); return 0; }
pc = std::move(r).value();
}
const draco::PointCloud* g = mesh ? mesh.get() : pc.get();
printf("POINTS %u\n", g->num_points());
if (mesh) {
printf("FACES %u ", mesh->num_faces());
for (draco::FaceIndex fi(0); fi < mesh->num_faces(); ++fi) {
const auto& face = mesh->face(fi);
for (int c = 0; c < 3; ++c) { uint32_t v = face[c].value(); hex((const uint8_t*)&v, 4); }
}
printf("\n");
}
for (int i = 0; i < g->num_attributes(); ++i) {
const draco::PointAttribute* a = g->attribute(i);
printf("ATTR %d %d %d %d %u ", (int)a->attribute_type(), (int)a->data_type(), (int)a->num_components(), a->normalized() ? 1 : 0, a->unique_id());
for (draco::PointIndex p(0); p < g->num_points(); ++p) hex(a->GetAddress(a->mapped_index(p)), a->byte_stride());
printf("\n");
}
return 0;
}
+38
View File
@@ -0,0 +1,38 @@
-- tools/fixtures/_iqm_encode: run by tools/fixtures/iqm.py (luau CLI, repo root): writes mrfixit.iqm back through our
-- reader and writer, and every glTF pick through our writer, printing "<file>\t<hex>" lines for assimp and the
-- Python IQM reader. Files: rt_mrfixit.iqm, gltf_<name>.iqm.
local Iqm = require("@formats/model/iqm")
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/iqm_cases")
local Picks = require("@tests/gen/iqm_gltf")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
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] = HEX[buffer.readu8(b, i)]
end
return table.concat(out)
end
for _, c in Cases do
local scene = assert(Iqm.decode(Bytes.reader(buffer.fromstring(c.data))))
print("rt_mrfixit.iqm\t" .. hex(assert(Iqm.encode(scene))))
end
for _, p in Picks do
local scene, err = Gltf.decode(Bytes.reader(buffer.fromstring(p.data)), { files = p.files })
if scene then
local out, e2 = Iqm.encode(scene)
if out then
print("gltf_" .. p.name .. ".iqm\t" .. hex(out))
else
print("encode failed " .. p.name .. ": " .. tostring(e2))
end
else
print("skipped " .. p.name .. ": " .. tostring(err))
end
end
+113
View File
@@ -0,0 +1,113 @@
# An independent IQM reader for tools/fixtures/iqm.py (plain Python, from the IQM SDK's format description and its
# demo's skinning: joint matrices = pose world * inverse bind world): header counts and the bounding box of the
# skinned vertices for every animation frame, computed from the joints, poses and frames (not from the file's bounds
# block, which it returns too for comparison).
import math, struct
HEADER = ("version filesize flags num_text ofs_text num_meshes ofs_meshes num_vertexarrays num_vertexes ofs_vertexarrays "
"num_triangles ofs_triangles ofs_adjacency num_joints ofs_joints num_poses ofs_poses num_anims ofs_anims num_frames "
"num_framechannels ofs_frames ofs_bounds num_comment ofs_comment num_extensions ofs_extensions").split()
FMT = {0: ("b", 1), 1: ("B", 1), 2: ("h", 2), 3: ("H", 2), 4: ("i", 4), 5: ("I", 4), 7: ("f", 4), 8: ("d", 8)}
def mat(t, q, s):
x, y, z, w = q
n = math.sqrt(x * x + y * y + z * z + w * w) or 1
x, y, z, w = x / n, y / n, z / n, w / n
r = [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
[2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
[2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]]
return [[r[i][0] * s[0], r[i][1] * s[1], r[i][2] * s[2], t[i]] for i in range(3)] + [[0, 0, 0, 1]]
def mul(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 inv(m):
# general 4x4 inverse (Gauss-Jordan)
a = [row[:] + [1 if i == j else 0 for j in range(4)] for i, row in enumerate(m)]
for c in range(4):
p = max(range(c, 4), key=lambda r: abs(a[r][c]))
a[c], a[p] = a[p], a[c]
d = a[c][c] or 1e-30
a[c] = [v / d for v in a[c]]
for r in range(4):
if r != c:
f = a[r][c]
a[r] = [v - f * w for v, w in zip(a[r], a[c])]
return [row[4:] for row in a]
def read(data):
h = dict(zip(HEADER, struct.unpack_from("<27I", data, 16)))
text = data[h["ofs_text"]:h["ofs_text"] + h["num_text"]]
def s(o):
return text[o:text.index(b"\0", o)].decode("latin1")
arrays = {}
for i in range(h["num_vertexarrays"]):
typ, flags, fmt, size, ofs = struct.unpack_from("<5I", data, h["ofs_vertexarrays"] + i * 20)
c, n = FMT[fmt]
vals = struct.unpack_from("<%d%s" % (h["num_vertexes"] * size, c), data, ofs)
arrays[typ] = (fmt, size, vals)
joints = []
for j in range(h["num_joints"]):
v = struct.unpack_from("<Ii10f", data, h["ofs_joints"] + j * 48)
joints.append((s(v[0]), v[1], v[2:5], v[5:9], v[9:12]))
bind = []
for name, parent, t, q, sc in joints:
m = mat(t, q, sc)
bind.append(mul(bind[parent], m) if parent >= 0 else m)
invbind = [inv(m) for m in bind]
poses = []
for p in range(h["num_poses"]):
v = struct.unpack_from("<iI20f", data, h["ofs_poses"] + p * 88)
poses.append((v[0], v[1], v[2:12], v[12:22]))
frames = struct.unpack_from("<%dH" % (h["num_frames"] * h["num_framechannels"]), data, h["ofs_frames"]) if h["num_frames"] else ()
anims = []
for a in range(h["num_anims"]):
v = struct.unpack_from("<3IfI", data, h["ofs_anims"] + a * 20)
anims.append({"name": s(v[0]), "first": v[1], "frames": v[2], "framerate": v[3]})
pos = arrays[0][2]
bi = arrays.get(4)
bw = arrays.get(5)
boxes = []
k = 0
for f in range(h["num_frames"]):
world = []
for i, (parent, mask, off, sc) in enumerate(poses):
ch = list(off)
for c in range(10):
if mask & (1 << c):
ch[c] += frames[k] * sc[c]
k += 1
m = mat(ch[0:3], ch[3:7], ch[7:10])
world.append(mul(world[parent], m) if parent >= 0 else m)
skin = [mul(world[j], invbind[j]) for j in range(len(world))]
lo, hi = [1e30] * 3, [-1e30] * 3
for v in range(h["num_vertexes"]):
x, y, z = pos[v * 3:v * 3 + 3]
if bi and bw:
sx = sy = sz = 0.0
tot = 0.0
for c in range(4):
w = bw[2][v * 4 + c] / 255.0 if bw[0] == 1 else bw[2][v * 4 + c]
if w > 0:
m = skin[bi[2][v * 4 + c]]
sx += w * (m[0][0] * x + m[0][1] * y + m[0][2] * z + m[0][3])
sy += w * (m[1][0] * x + m[1][1] * y + m[1][2] * z + m[1][3])
sz += w * (m[2][0] * x + m[2][1] * y + m[2][2] * z + m[2][3])
tot += w
if tot > 0:
x, y, z = sx, sy, sz
lo = [min(a, b) for a, b in zip(lo, (x, y, z))]
hi = [max(a, b) for a, b in zip(hi, (x, y, z))]
boxes.append({"min": lo, "max": hi})
stored = []
if h["ofs_bounds"]:
for f in range(h["num_frames"]):
v = struct.unpack_from("<8f", data, h["ofs_bounds"] + f * 32)
stored.append({"min": list(v[0:3]), "max": list(v[3:6])})
return {"meshes": h["num_meshes"], "vertexes": h["num_vertexes"], "triangles": h["num_triangles"], "joints": h["num_joints"],
"jointNames": [j[0] for j in joints], "anims": anims, "frames": h["num_frames"], "skinned": boxes, "stored": stored}
+44
View File
@@ -0,0 +1,44 @@
-- tools/fixtures/_ms3d_encode: run by tools/fixtures/ms3d.py (luau CLI, repo root): decodes every MS3D case and every
-- glTF sample model with our readers and writes them with our MS3D writer, printing "<file>\t<hex>" lines for assimp
-- to read back. Files: case_<i>.ms3d, gltf_<i>.ms3d.
local Ms3d = require("@formats/model/ms3d")
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/ms3d_cases")
local Picks = require("@tests/gen/ms3d_gltf")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
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] = HEX[buffer.readu8(b, i)]
end
return table.concat(out)
end
local function emit(name: string, scene: any)
local out, err = Ms3d.encode(scene)
if out then
print(name .. "\t" .. hex(out))
else
print("encode failed " .. name .. ": " .. tostring(err))
end
end
for i, c in Cases do
local scene, err = Ms3d.decode(Bytes.reader(buffer.fromstring(c.data)))
if scene then
emit(string.format("case_%d.ms3d", i), scene)
else
print("skipped " .. c.name .. ": " .. tostring(err))
end
end
for i, g in Picks do
local scene = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files })
if scene then
emit(string.format("gltf_%d.ms3d", i), scene)
end
end
+265
View File
@@ -0,0 +1,265 @@
# A small PMX 2.0 / 2.1 (and PMD 1.0) writer for tools/fixtures/pmx.py: synthetic MikuMikuDance models that use every
# vertex deform type (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), both text encodings, every index size, additional UVs,
# several materials (texture / sphere / toon references), a bone chain with IK / inherit / fixed-axis / local-axis
# bones, every morph type, display frames, rigid bodies and joints. Written from the PMX 2.0 / 2.1 specification notes
# (PmxEditor's "PMX仕様") and the PMD layout; no third-party code.
import math, struct
def f32s(*v):
return struct.pack("<%df" % len(v), *v)
class Pmx:
def __init__(self, version=2.0, utf8=False, sizes=(2, 1, 1, 2, 1, 1), uva=0):
self.version, self.utf8, self.uva = version, utf8, uva
self.vsize, self.tsize, self.msize, self.bsize, self.morsize, self.rsize = sizes
def text(self, s):
b = s.encode("utf-8") if self.utf8 else s.encode("utf-16-le")
return struct.pack("<i", len(b)) + b
def idx(self, v, size, vertex=False):
if vertex:
return struct.pack({1: "<B", 2: "<H", 4: "<i"}[size], v)
return struct.pack({1: "<b", 2: "<h", 4: "<i"}[size], v)
def build(self, m):
out = bytearray(b"PMX ")
out += struct.pack("<f", self.version)
out += bytes([8, 1 if self.utf8 else 0, self.uva, self.vsize, self.tsize, self.msize, self.bsize, self.morsize, self.rsize])
for s in (m["name"], m["nameEn"], m["comment"], m["commentEn"]):
out += self.text(s)
B = lambda i: self.idx(i, self.bsize)
out += struct.pack("<i", len(m["vertices"]))
for v in m["vertices"]:
out += f32s(*v["pos"], *v["normal"], *v["uv"])
for k in range(self.uva):
out += f32s(*v["uva"][k])
kind = v["deform"]
out += bytes([kind])
b, w = v["bones"], v["weights"]
if kind == 0:
out += B(b[0])
elif kind == 1:
out += B(b[0]) + B(b[1]) + f32s(w[0])
elif kind in (2, 4):
out += B(b[0]) + B(b[1]) + B(b[2]) + B(b[3]) + f32s(*w[:4])
else:
out += B(b[0]) + B(b[1]) + f32s(w[0]) + f32s(*v["sdef"][0], *v["sdef"][1], *v["sdef"][2])
out += f32s(v["edge"])
out += struct.pack("<i", len(m["indices"]))
for i in m["indices"]:
out += self.idx(i, self.vsize, True)
out += struct.pack("<i", len(m["textures"]))
for t in m["textures"]:
out += self.text(t)
out += struct.pack("<i", len(m["materials"]))
T = lambda i: self.idx(i, self.tsize)
for mat in m["materials"]:
out += self.text(mat["name"]) + self.text(mat["nameEn"])
out += f32s(*mat["diffuse"], *mat["specular"], mat["power"], *mat["ambient"])
out += bytes([mat["flags"]]) + f32s(*mat["edgeColor"], mat["edgeSize"])
out += T(mat["texture"]) + T(mat["sphere"]) + bytes([mat["sphereMode"], 1 if mat["toonShared"] is not None else 0])
out += bytes([mat["toonShared"]]) if mat["toonShared"] is not None else T(mat["toon"])
out += self.text(mat["memo"]) + struct.pack("<i", mat["count"])
out += struct.pack("<i", len(m["bones"]))
for bn in m["bones"]:
fl = bn["flags"]
out += self.text(bn["name"]) + self.text(bn["nameEn"]) + f32s(*bn["pos"]) + B(bn["parent"]) + struct.pack("<iH", bn["layer"], fl)
out += B(bn["tail"]) if fl & 1 else f32s(*bn["tail"])
if fl & 0x300:
out += B(bn["inherit"][0]) + f32s(bn["inherit"][1])
if fl & 0x400:
out += f32s(*bn["axis"])
if fl & 0x800:
out += f32s(*bn["localX"], *bn["localZ"])
if fl & 0x2000:
out += struct.pack("<i", bn["key"])
if fl & 0x20:
ik = bn["ik"]
out += B(ik["target"]) + struct.pack("<if", ik["loops"], ik["limit"]) + struct.pack("<i", len(ik["links"]))
for ln in ik["links"]:
out += B(ln["bone"]) + bytes([1 if ln.get("min") else 0])
if ln.get("min"):
out += f32s(*ln["min"], *ln["max"])
out += struct.pack("<i", len(m["morphs"]))
V = lambda i: self.idx(i, self.vsize, True)
Mo = lambda i: self.idx(i, self.morsize)
for mo in m["morphs"]:
out += self.text(mo["name"]) + self.text(mo["nameEn"]) + bytes([mo["panel"], mo["type"]]) + struct.pack("<i", len(mo["offsets"]))
for o in mo["offsets"]:
t = mo["type"]
if t in (0, 9):
out += Mo(o[0]) + f32s(o[1])
elif t == 1:
out += V(o[0]) + f32s(*o[1])
elif t == 2:
out += B(o[0]) + f32s(*o[1], *o[2])
elif 3 <= t <= 7:
out += V(o[0]) + f32s(*o[1])
elif t == 8:
out += self.idx(o[0], self.msize) + bytes([o[1]]) + f32s(*o[2])
elif t == 10:
out += self.idx(o[0], self.rsize) + bytes([o[1]]) + f32s(*o[2], *o[3])
out += struct.pack("<i", len(m["frames"]))
for fr in m["frames"]:
out += self.text(fr["name"]) + self.text(fr["nameEn"]) + bytes([fr["special"]]) + struct.pack("<i", len(fr["items"]))
for kind, i in fr["items"]:
out += bytes([kind]) + (B(i) if kind == 0 else Mo(i))
out += struct.pack("<i", len(m["rigid"]))
for rb in m["rigid"]:
out += self.text(rb["name"]) + self.text(rb["nameEn"]) + B(rb["bone"]) + struct.pack("<BHB", rb["group"], rb["mask"], rb["shape"])
out += f32s(*rb["size"], *rb["pos"], *rb["rot"], rb["mass"], 0.5, 0.5, 0.0, 0.5) + bytes([rb["mode"]])
out += struct.pack("<i", len(m["joints"]))
R = lambda i: self.idx(i, self.rsize)
for jn in m["joints"]:
out += self.text(jn["name"]) + self.text(jn["nameEn"]) + bytes([0]) + R(jn["a"]) + R(jn["b"])
out += f32s(*jn["pos"], 0, 0, 0, -1, -1, -1, 1, 1, 1, -0.5, -0.5, -0.5, 0.5, 0.5, 0.5, 0, 0, 0, 0, 0, 0)
if self.version >= 2.1:
out += struct.pack("<i", 0) # no soft bodies
return bytes(out)
def tube(rings=6, seg=8, nbones=4, nmat=3, version=2.0, uva=0, seed=1, deform=None, name="tube", flips=False):
"""a tube along +y: rings of seg vertices, weighted to a bone chain, faces split over nmat materials"""
import random
rnd = random.Random(seed)
kinds = deform or ([0, 1, 2, 3] + ([4] if version >= 2.1 else []))
verts = []
for r in range(rings):
y = r * 2.0
for s in range(seg):
a = 2 * math.pi * s / seg
x, z = math.cos(a) * 1.5, math.sin(a) * 1.5 + 0.25 * r
b0 = min(nbones - 1, r * nbones // rings)
b1 = min(nbones - 1, b0 + 1)
k = kinds[(r * seg + s) % len(kinds)]
w = rnd.random()
if k == 0:
bones, weights = [b0], [1.0]
elif k in (1, 3):
bones, weights = [b0, b1], [w]
else:
ws = [rnd.random() + 0.1 for _ in range(4)]
bones, weights = [b0, b1, max(0, b0 - 1), -1 if k == 2 else nbones - 1], [x / sum(ws) * 0.9 for x in ws]
verts.append({
"pos": (x, y, z), "normal": (math.cos(a), 0.0, math.sin(a)), "uv": (s / seg, r / (rings - 1)),
"uva": [(rnd.random(), rnd.random(), rnd.random(), rnd.random()) for _ in range(uva)],
"deform": k, "bones": bones, "weights": weights, "edge": 1.0,
"sdef": ((0.0, y, 0.0), (0.0, y - 1, 0.0), (0.0, y + 1, 0.0)),
})
faces = []
for r in range(rings - 1):
for s in range(seg):
a, b = r * seg + s, r * seg + (s + 1) % seg
c, d = a + seg, b + seg
faces += [a, c, b, b, c, d]
ntri = len(faces) // 3
counts, left = [], ntri
for k in range(nmat):
n = left if k == nmat - 1 else max(1, ntri // nmat)
counts.append(n * 3)
left -= n
mats = []
for k in range(nmat):
mats.append({
"name": "材質%d" % k, "nameEn": "mat%d" % k, "diffuse": (0.8, 0.2 + 0.2 * k, 0.1, 1.0 if k != 1 else 0.5),
"specular": (0.1, 0.1, 0.1), "power": 5.0 + 10 * k, "ambient": (0.4, 0.1, 0.05), "flags": [0x01 | 0x10, 0x04 | 0x08, 0x02][k % 3],
"edgeColor": (0, 0, 0, 1), "edgeSize": 1.0, "texture": 0 if k == 0 else -1, "sphere": 1 if k == 0 else -1,
"sphereMode": 1 if k == 0 else 0, "toonShared": 3 if k != 2 else None, "toon": 2, "memo": "memo %d" % k, "count": counts[k],
})
bones = []
for i in range(nbones):
fl = 0x1A | (1 if i < nbones - 1 else 0)
b = {"name": "骨%d" % i, "nameEn": "bone%d" % i, "pos": (0.0, i * (rings - 1) * 2.0 / max(1, nbones - 1), 0.25 * i), "parent": i - 1,
"layer": 0, "flags": fl, "tail": i + 1 if i < nbones - 1 else (0.0, 1.0, 0.0)}
if i == 1:
b["flags"] |= 0x100
b["inherit"] = (0, 0.5)
if i == 2:
b["flags"] |= 0x400 | 0x800
b["axis"] = (0.0, 1.0, 0.0)
b["localX"], b["localZ"] = (1.0, 0.0, 0.0), (0.0, 0.0, 1.0)
bones.append(b)
# an IK bone at the end targeting the last chain bone
bones.append({"name": "IK", "nameEn": "leg IK", "pos": (2.0, 0.0, 0.0), "parent": -1, "layer": 1, "flags": 0x1E | 0x20, "tail": (0.0, 0.0, 1.0),
"ik": {"target": nbones - 1, "loops": 40, "limit": 2.0, "links": [{"bone": nbones - 2, "min": (-3.14, 0, 0), "max": (-0.01, 0, 0)}, {"bone": max(0, nbones - 3)}]}})
morphs = [
{"name": "上", "nameEn": "up", "panel": 1, "type": 1, "offsets": [(i, (0.0, 0.5, -0.25)) for i in range(0, len(verts), 3)]},
{"name": "広", "nameEn": "wide", "panel": 2, "type": 1, "offsets": [(i, (0.3, 0.0, 0.1)) for i in range(1, len(verts), 2)]},
{"name": "uv", "nameEn": "uv", "panel": 3, "type": 3, "offsets": [(0, (0.1, 0.2, 0, 0))]},
{"name": "骨", "nameEn": "bonem", "panel": 4, "type": 2, "offsets": [(1, (0, 1, 0), (0, 0, 0, 1))]},
{"name": "材", "nameEn": "matm", "panel": 4, "type": 8, "offsets": [(-1, 0, (1,) * 28)]},
{"name": "群", "nameEn": "group", "panel": 4, "type": 0, "offsets": [(0, 0.5), (1, 1.0)]},
]
if uva:
morphs.append({"name": "uva", "nameEn": "uva1", "panel": 3, "type": 4, "offsets": [(2, (0.5, 0.5, 0.5, 0.5))]})
if version >= 2.1 and flips: # assimp 6 rejects these morph types
morphs.append({"name": "flip", "nameEn": "flip", "panel": 4, "type": 9, "offsets": [(0, 1.0)]})
morphs.append({"name": "imp", "nameEn": "impulse", "panel": 4, "type": 10, "offsets": [(0, 1, (0, 1, 0), (0, 0, 0))]})
frames = [{"name": "Root", "nameEn": "Root", "special": 1, "items": [(0, 0)]},
{"name": "表情", "nameEn": "Exp", "special": 1, "items": [(1, 0), (1, 1)]}]
rigid = [{"name": "rb%d" % i, "nameEn": "rb%d" % i, "bone": i, "group": i, "mask": 0xFFFF, "shape": i % 3, "size": (1, 2, 3),
"pos": (0, i, 0), "rot": (0, 0, 0), "mass": 1.0, "mode": i % 3} for i in range(2)]
joints = [{"name": "j0", "nameEn": "j0", "a": 0, "b": 1, "pos": (0, 1, 0)}]
return {"name": name, "nameEn": name + " en", "comment": "コメント", "commentEn": "comment", "vertices": verts, "indices": faces,
"textures": ["tex\\body.png", "s.sph", "toon.bmp"], "materials": mats, "bones": bones, "morphs": morphs,
"frames": frames, "rigid": rigid, "joints": joints}
def pmd(m):
"""the same model as PMD 1.0 (BDEF2-style weights only, ASCII names, toon list, English names)"""
def name(s, n):
b = s.encode("ascii", "replace")[: n - 1]
return b + b"\0" * (n - len(b))
out = bytearray(b"Pmd") + struct.pack("<f", 1.0) + name(m["nameEn"], 20) + name(m["commentEn"], 256)
out += struct.pack("<I", len(m["vertices"]))
for v in m["vertices"]:
b = v["bones"] + [v["bones"][0]]
w = v["weights"][0] if v["deform"] != 0 else 1.0
out += f32s(*v["pos"], *v["normal"], *v["uv"]) + struct.pack("<HHBB", max(0, b[0]), max(0, b[1]), int(round(w * 100)), 0)
out += struct.pack("<I", len(m["indices"])) + struct.pack("<%dH" % len(m["indices"]), *m["indices"])
out += struct.pack("<I", len(m["materials"]))
for mat in m["materials"]:
tex = m["textures"][mat["texture"]].replace("\\", "/") if mat["texture"] >= 0 else ""
if mat["sphere"] >= 0:
tex += "*" + m["textures"][mat["sphere"]]
out += f32s(*mat["diffuse"], mat["power"], *mat["specular"], *mat["ambient"])
out += struct.pack("<BBI", mat["toonShared"] if mat["toonShared"] is not None else 255, 1 if mat["flags"] & 0x10 else 0, mat["count"]) + name(tex, 20)
bones = m["bones"]
out += struct.pack("<H", len(bones))
for i, bn in enumerate(bones):
tail = bn["tail"] if bn["flags"] & 1 else 0
out += name(bn["nameEn"], 20) + struct.pack("<hhBh", bn["parent"], tail, 2 if bn["flags"] & 0x20 else 0, 0) + f32s(*bn["pos"])
iks = [(i, bn["ik"]) for i, bn in enumerate(bones) if bn["flags"] & 0x20]
out += struct.pack("<H", len(iks))
for i, ik in iks:
out += struct.pack("<HHBHf", i, ik["target"], len(ik["links"]), ik["loops"], ik["limit"] / 4) + struct.pack("<%dH" % len(ik["links"]), *[ln["bone"] for ln in ik["links"]])
# skins: base (every vertex any morph moves, absolute positions) then the vertex morphs relative to the base list
vm = [mo for mo in m["morphs"] if mo["type"] == 1]
base = sorted({o[0] for mo in vm for o in mo["offsets"]})
pos = {v: k for k, v in enumerate(base)}
out += struct.pack("<H", 1 + len(vm) if vm else 0)
if vm:
out += name("base", 20) + struct.pack("<IB", len(base), 0)
for v in base:
out += struct.pack("<I", v) + f32s(*m["vertices"][v]["pos"])
for mo in vm:
out += name(mo["nameEn"], 20) + struct.pack("<IB", len(mo["offsets"]), mo["panel"])
for v, d in mo["offsets"]:
out += struct.pack("<I", pos[v]) + f32s(*d)
out += struct.pack("<B", 0) # skin display list
out += struct.pack("<B", 1) + name("Root", 50) # bone display groups
out += struct.pack("<I", 1) + struct.pack("<HB", 0, 1)
# English names
out += bytes([1]) + name(m["nameEn"], 20) + name(m["commentEn"], 256)
for bn in bones:
out += name(bn["nameEn"], 20)
for mo in vm:
out += name(mo["nameEn"], 20)
out += name("Root", 50)
for k in range(10):
out += name("toon%02d.bmp" % (k + 1), 100)
out += struct.pack("<I", 0) + struct.pack("<I", 0) # rigid bodies, joints
return bytes(out)
+54
View File
@@ -0,0 +1,54 @@
-- tools/fixtures/_vrml_encode: run by tools/fixtures/vrml.py and x3d.py (luau CLI, repo root): decodes every VRML /
-- X3D case and glTF sample with our readers and writes it back with our writers, printing "<file>\t<hex>" lines for
-- VTK (.wrl) and assimp (.x3d) to read back. Files: case_<i>.wrl, gltf_<i>.wrl, xcase_<i>.x3d, xgltf_<i>.x3d.
local Vrml = require("@formats/model/vrml")
local X3d = require("@formats/model/x3d")
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/vrml_cases")
local GltfCases = require("@tests/gen/vrml_gltf")
local ok, X3dCases = pcall(require, "@tests/gen/x3d_cases")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
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] = HEX[buffer.readu8(b, i)]
end
return table.concat(out)
end
local function both(scene: any, wrl: string, x3d: string)
local a = Vrml.encode(scene)
if a then
print(wrl .. "\t" .. hex(a))
end
local b = X3d.encode(scene)
if b then
print(x3d .. "\t" .. hex(b))
end
end
for i, c in Cases do
local scene = Vrml.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false })
if scene then
both(scene, string.format("case_%d.wrl", i), string.format("wcase_%d.x3d", i))
end
end
for i, c in GltfCases do
local scene = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
if scene then
both(scene, string.format("gltf_%d.wrl", i), string.format("xgltf_%d.x3d", i))
end
end
if ok and type(X3dCases) == "table" then
for i, c in X3dCases do
local scene = X3d.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false })
if scene then
both(scene, string.format("xcase_%d.wrl", i), string.format("xcase_%d.x3d", i))
end
end
end
+241
View File
@@ -0,0 +1,241 @@
# Shared helpers for tools/fixtures/vrml.py and x3d.py: VTK (nixpkgs python3 vtk) as the VRML97 reference reader and
# as a writer of more .wrl / .x3d inputs, assimp's X3D reader for .x3d, and the hand-written feature files.
# vtk_read(ctx, paths) -> [ { actors, polys, lines, verts, points, min, max } | { failed } ] (vtkVRMLImporter)
# vtk_export(ctx, outdir, gltf_paths) -> [ (name, wrl path, x3d path) ] (vtkVRMLExporter / vtkX3DExporter scenes)
# FEATURES: { name: VRML97 text } covering PROTO, DEF / USE, Switch, LOD, primitives, per-face colours, separate
# indices, ElevationGrid, Extrusion, ROUTE animation, lights, viewpoints, Inline, PixelTexture
import json
VTK_READ = r"""
import json, os, sys, vtk
vtk.vtkObject.GlobalWarningDisplayOff()
def read(p):
imp = vtk.vtkVRMLImporter(); imp.SetFileName(p)
rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); imp.SetRenderWindow(rw)
imp.Update()
acts = imp.GetRenderer().GetActors(); acts.InitTraversal()
out = {"actors": 0, "polys": 0, "lines": 0, "verts": 0, "points": 0}
lo, hi = [1e30] * 3, [-1e30] * 3
for i in range(acts.GetNumberOfItems()):
a = acts.GetNextActor()
m = a.GetMapper()
if not m:
continue
m.Update()
d = m.GetInput()
if d is None or d.GetNumberOfPoints() == 0:
continue
out["actors"] += 1
out["polys"] += d.GetNumberOfPolys() + d.GetNumberOfStrips()
out["lines"] += d.GetNumberOfLines()
out["verts"] += d.GetNumberOfVerts()
out["points"] += d.GetNumberOfPoints()
# tight world bounds: every point through the actor's matrix (GetBounds boxes the local bounds)
mat = a.GetMatrix()
pts = d.GetPoints()
for j in range(d.GetNumberOfPoints()):
p = pts.GetPoint(j)
w = mat.MultiplyPoint((p[0], p[1], p[2], 1.0))
for k in range(3):
lo[k] = min(lo[k], w[k]); hi[k] = max(hi[k], w[k])
if out["actors"]:
out["min"], out["max"] = lo, hi
return out
# one child process per file: vtkVRMLImporter crashes on some valid files
res = []
for p in json.loads(sys.stdin.read()):
r, w = os.pipe()
pid = os.fork()
if pid == 0:
os.close(r)
try:
data = json.dumps(read(p))
except Exception:
data = json.dumps({"failed": True})
os.write(w, data.encode())
os._exit(0)
os.close(w)
chunks = []
while True:
b = os.read(r, 65536)
if not b:
break
chunks.append(b)
os.close(r)
_, status = os.waitpid(pid, 0)
try:
res.append(json.loads(b"".join(chunks).decode()) if status == 0 else {"failed": True, "crashed": True})
except ValueError:
res.append({"failed": True})
print("RESULT " + json.dumps(res))
"""
VTK_EXPORT = r"""
import json, os, sys, vtk
vtk.vtkObject.GlobalWarningDisplayOff()
args = json.loads(sys.stdin.read())
out, gltfs = args["out"], args["gltf"]
made = []
def export(ren, name):
rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); rw.AddRenderer(ren)
ren.ResetCamera()
w = vtk.vtkVRMLExporter(); w.SetRenderWindow(rw); w.SetFileName(os.path.join(out, name + ".wrl")); w.Write()
x = vtk.vtkX3DExporter(); x.SetRenderWindow(rw); x.SetFileName(os.path.join(out, name + ".x3d")); x.SetBinary(0); x.Write()
made.append(name)
def actor(src, pos=(0, 0, 0), scale=(1, 1, 1), rot=(0, 0, 0), color=None, scalars=False):
m = vtk.vtkPolyDataMapper(); m.SetInputConnection(src.GetOutputPort())
if not scalars:
m.ScalarVisibilityOff()
a = vtk.vtkActor(); a.SetMapper(m); a.SetPosition(*pos); a.SetScale(*scale)
a.RotateX(rot[0]); a.RotateY(rot[1]); a.RotateZ(rot[2])
if color:
a.GetProperty().SetColor(*color)
return a
# 1. primitives as polygon meshes, transformed, coloured, one with point scalars
ren = vtk.vtkRenderer()
s = vtk.vtkSphereSource(); s.SetThetaResolution(16); s.SetPhiResolution(8)
ren.AddActor(actor(s, (1, 2, 3), (2, 2, 2), (30, 0, 0), (0.9, 0.2, 0.1)))
c = vtk.vtkConeSource(); c.SetResolution(12)
ren.AddActor(actor(c, (-3, 0, 1), (1, 3, 1), (0, 45, 10), (0.2, 0.8, 0.3)))
cube = vtk.vtkCubeSource(); cube.SetXLength(2); cube.SetYLength(1); cube.SetZLength(0.5)
ren.AddActor(actor(cube, (0, -2, 0), (1, 1, 1), (0, 0, 20), (0.3, 0.3, 0.9)))
keep = [vtk.vtkSphereSource(), vtk.vtkSphereSource(), vtk.vtkCubeSource()]
el = vtk.vtkElevationFilter(); el.SetInputConnection(keep[0].GetOutputPort()); el.SetLowPoint(0, -0.5, 0); el.SetHighPoint(0, 0.5, 0)
ren.AddActor(actor(el, (4, 4, 0), scalars=True))
light = vtk.vtkLight(); light.SetPosition(5, 5, 5); light.SetFocalPoint(0, 0, 0); light.SetColor(1, 0.9, 0.8)
ren.AddLight(light)
export(ren, "vtk_shapes")
# 2. lines and points
ren = vtk.vtkRenderer()
ls = vtk.vtkLineSource(); ls.SetPoint1(0, 0, 0); ls.SetPoint2(3, 1, 2); ls.SetResolution(5)
ren.AddActor(actor(ls, (1, 0, 0), color=(1, 1, 0)))
pts = vtk.vtkPointSource(); pts.SetNumberOfPoints(40); pts.SetRadius(2); pts.SetCenter(0, 5, 0)
ren.AddActor(actor(pts))
ren.AddActor(actor(keep[2], (0, 0, -4)))
export(ren, "vtk_lines_points")
# 3. a textured plane (PixelTexture) and a strip mesh
ren = vtk.vtkRenderer()
pl = vtk.vtkPlaneSource(); pl.SetResolution(3, 2)
img = vtk.vtkImageCanvasSource2D(); img.SetScalarTypeToUnsignedChar(); img.SetNumberOfScalarComponents(3); img.SetExtent(0, 7, 0, 3, 0, 0)
img.SetDrawColor(200, 30, 30); img.FillBox(0, 7, 0, 3); img.SetDrawColor(20, 30, 200); img.FillBox(0, 3, 0, 1); img.Update()
tex = vtk.vtkTexture(); tex.SetInputConnection(img.GetOutputPort())
a = actor(pl, (0, 0, 1), (4, 2, 1)); a.SetTexture(tex)
ren.AddActor(a)
strip = vtk.vtkStripper(); strip.SetInputConnection(keep[1].GetOutputPort())
ren.AddActor(actor(strip, (0, 3, 0)))
export(ren, "vtk_texture_strips")
# 4. glTF sample models through VTK's glTF importer
for g in gltfs:
try:
imp = vtk.vtkGLTFImporter(); imp.SetFileName(g)
rw = vtk.vtkRenderWindow(); rw.SetOffScreenRendering(1); imp.SetRenderWindow(rw); imp.Update()
name = "vtk_gltf_" + os.path.splitext(os.path.basename(g))[0]
export(imp.GetRenderer(), name)
except Exception:
pass
print("RESULT " + json.dumps(made))
"""
def vtk_xform_ok(data):
"""False when vtkVRMLImporter's transforms are wrong for the file: it ignores center and scaleOrientation"""
import re
return not re.search(rb"\b(center|scaleOrientation)\s+[-+\d.]", data)
def _run(ctx, code, arg):
out = ctx.python(["vtk"], code, input=json.dumps(arg).encode()).decode("utf-8", "replace")
for line in out.split("\n"):
if line.startswith("RESULT "):
return json.loads(line[7:])
raise RuntimeError("vtk script printed no result")
def vtk_read(ctx, paths):
return _run(ctx, VTK_READ, paths) if paths else []
def vtk_export(ctx, outdir, gltfs):
return _run(ctx, VTK_EXPORT, {"out": outdir, "gltf": gltfs})
FEATURES = {
"feat_proto_use.wrl": """#VRML V2.0 utf8
PROTO Brick [ field SFVec3f size 1 1 1 field SFColor col 1 0 0 exposedField SFVec3f where 0 0 0 ] {
Transform { translation IS where children Shape {
appearance Appearance { material Material { diffuseColor IS col } }
geometry Box { size IS size } } }
}
DEF A Brick { size 2 1 1 col 0 1 0 where 0 0 0 }
Brick { where 3 0 0 }
Transform { translation 0 3 0 children [ DEF S Shape { geometry IndexedFaceSet {
coord DEF C Coordinate { point [ 0 0 0, 1 0 0, 1 1 0, 0 1 0 ] } coordIndex [ 0 1 2 3 -1 ] } } ] }
Transform { translation 0 5 0 rotation 0 0 1 1.5708 children USE S }
""",
"feat_indices.wrl": """#VRML V2.0 utf8
# separate normal / colour / texture indices, per-face colours, ccw FALSE, solid FALSE
Shape {
appearance Appearance { material Material { diffuseColor 0.5 0.5 0.5 transparency 0.25 shininess 0.5 specularColor 1 1 1 } }
geometry IndexedFaceSet {
solid FALSE ccw FALSE
coord Coordinate { point [ 0 0 0, 2 0 0, 2 2 0, 0 2 0, 0 0 2, 2 0 2 ] }
coordIndex [ 0 1 2 3 -1, 0 4 5 1 -1 ]
normal Normal { vector [ 0 0 1, 0 -1 0 ] }
normalPerVertex FALSE normalIndex [ 0 1 ]
color Color { color [ 1 0 0, 0 0 1 ] }
colorPerVertex FALSE
texCoord TextureCoordinate { point [ 0 0, 1 0, 1 1, 0 1 ] }
texCoordIndex [ 0 1 2 3 -1, 3 2 1 0 -1 ]
}
}
Shape { geometry IndexedFaceSet {
coord Coordinate { point [ 5 0 0, 6 0 0, 6 1 0, 5 1 0 ] }
coordIndex [ 0 1 2 -1 0 2 3 ]
color Color { color [ 1 0 0, 0 1 0, 0 0 1, 1 1 1 ] } colorIndex [ 3 2 1 -1 0 1 2 -1 ] } }
""",
"feat_primitives.wrl": """#VRML V2.0 utf8
Transform { translation -4 0 0 children Shape { geometry Box { size 1 2 3 } } }
Transform { translation 0 0 0 children Shape { geometry Sphere { radius 1.5 } } }
Transform { translation 4 0 0 children Shape { geometry Cone { bottomRadius 1 height 3 } } }
Transform { translation 8 0 0 scale 2 1 1 children Shape { geometry Cylinder { radius 0.5 height 4 } } }
""",
"feat_grid_extrusion.wrl": """#VRML V2.0 utf8
Shape { geometry ElevationGrid { xDimension 4 zDimension 3 xSpacing 1 zSpacing 2
height [ 0 1 0 1, 1 2 1 0, 0 0 1 3 ] } }
Transform { translation 6 0 0 children Shape { geometry Extrusion {
crossSection [ 1 1, 1 -1, -1 -1, -1 1, 1 1 ] spine [ 0 0 0, 0 1 0, 1 2 0, 2 2 0 ] scale [ 1 1, 0.5 0.5, 0.5 0.5, 1 1 ] } } }
""",
"feat_scene.wrl": """#VRML V2.0 utf8
WorldInfo { title "feature scene" info [ "made for formats-luau" ] }
DEF Cam Viewpoint { position 0 1 8 orientation 0 1 0 0.3 fieldOfView 0.9 description "front" }
DEF Sun DirectionalLight { direction 0 -1 -1 intensity 0.8 color 1 1 0.9 }
DEF Bulb PointLight { location 1 2 3 radius 10 }
DEF Spot SpotLight { location 0 5 0 direction 0 -1 0 cutOffAngle 0.6 beamWidth 0.4 }
DEF Sw Switch { whichChoice 1 choice [
Shape { geometry Box { } }
Transform { translation 0 2 0 children Shape { geometry Sphere { radius 0.5 } } } ] }
LOD { range [ 10 ] level [ Shape { geometry Box { size 0.5 0.5 0.5 } } Shape { geometry Sphere { } } ] }
DEF Mover Transform { center 1 0 0 scaleOrientation 0 0 1 0.5 scale 1 2 1 children [
Shape { geometry IndexedLineSet { coord Coordinate { point [ 0 0 0, 1 0 0, 1 1 0 ] } coordIndex [ 0 1 2 -1 ] color Color { color [ 1 0 0, 0 1 0, 0 0 1 ] } } }
Shape { geometry PointSet { coord Coordinate { point [ 0 0 1, 1 0 1 ] } } } ] }
DEF Clock TimeSensor { cycleInterval 4 loop TRUE }
DEF Path PositionInterpolator { key [ 0 0.5 1 ] keyValue [ 0 0 0, 0 2 0, 0 0 0 ] }
DEF Turn OrientationInterpolator { key [ 0 1 ] keyValue [ 0 1 0 0, 0 1 0 3.14 ] }
ROUTE Clock.fraction_changed TO Path.set_fraction
ROUTE Clock.fraction_changed TO Turn.set_fraction
ROUTE Path.value_changed TO Mover.set_translation
ROUTE Turn.value_changed TO Mover.set_rotation
Shape { appearance Appearance { texture PixelTexture { image 2 2 3 0xFF0000 0x00FF00 0x0000FF 0xFFFFFF } } geometry Box { } }
Inline { url [ "part.wrl" ] }
""",
}
# the Inline target of feat_scene.wrl
INLINE = {"part.wrl": "#VRML V2.0 utf8\nTransform { translation 0 -3 0 children Shape { geometry Box { size 4 0.2 4 } } }\n"}
+204
View File
@@ -0,0 +1,204 @@
# B3D fixtures (tools/fixtures.py): assimp's Blitz3D test models (WusonBlitz, dwarf2, turtle1: read from the nixpkgs
# assimp source, never committed; their textures next to them go into `files`) and B3D files written here (textures
# with transforms and clamp flags, brushes with alpha / FX, vertex colours, two UV sets, nested rotated / scaled nodes,
# pivots, master brushes, bones with weights, KEYS + ANIM), with reference values from assimp: `assimp info -r`
# (meshes, faces, materials, animations, channels, bones) and its PreTransformVertices OBJ export (world bounds,
# triangle area, signed volume: the handedness conversion and winding), plus the counts the generator wrote.
# tests/gen/b3d_cases.luau { name, data, files = { name -> bytes }, assimp = {...}, want? = {...} }
import importlib.util, math, os, re, struct, subprocess
INPUTS = ["tools/fixtures/_model_ref.py"]
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_src():
out = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True)
return out.stdout.decode().strip().split("\n")[-1]
# ---------------------------------------------------------------------------------------------------- B3D writer
def chunk(tag, *parts):
body = b"".join(parts)
return tag.encode() + struct.pack("<I", len(body)) + body
def cstr(s):
return s.encode() + b"\0"
def f32(*v):
return struct.pack("<%df" % len(v), *v)
def i32(*v):
return struct.pack("<%di" % len(v), *v)
def quat_axis(ax, ay, az, deg):
# Blitz3D order: w, x, y, z
l = math.sqrt(ax * ax + ay * ay + az * az)
h = math.radians(deg) / 2
s = math.sin(h) / l
return (math.cos(h), ax * s, ay * s, az * s)
def node(name, pos=(0, 0, 0), scale=(1, 1, 1), rot=(1, 0, 0, 0), *children):
return chunk("NODE", cstr(name), f32(*pos), f32(*scale), f32(*rot), *children)
def box_mesh(sx, sy, sz, flags=0, sets=1, size=2, brushes=(-1,), master=-1):
# 8 corners, 12 triangles; split between the brushes round-robin by face
verts = []
for i in range(8):
x, y, z = (sx if i & 1 else -sx), (sy if i & 2 else -sy), (sz if i & 4 else -sz)
v = f32(x, y, z)
if flags & 1:
l = math.sqrt(x * x + y * y + z * z)
v += f32(x / l, y / l, z / l)
if flags & 2:
v += f32((i & 1) * 1.0, ((i >> 1) & 1) * 1.0, ((i >> 2) & 1) * 1.0, 1.0)
for s in range(sets):
v += f32(*[(i * 0.1 + s + k * 0.5) for k in range(size)])
verts.append(v)
# Blitz3D front faces are clockwise seen from outside (left-handed, Direct3D culling)
quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)]
tris = []
for a, b, c, d in quads:
tris += [(a, b, c), (a, c, d)]
tchunks = []
for k, br in enumerate(brushes):
mine = [t for j, t in enumerate(tris) if j % len(brushes) == k]
tchunks.append(chunk("TRIS", i32(br), b"".join(i32(*t) for t in mine)))
return chunk("MESH", i32(master), chunk("VRTS", i32(flags, sets, size), b"".join(verts)), *tchunks), 8, 12
def textured():
texs = chunk("TEXS", cstr("tex/a.png"), i32(1, 2), f32(0.25, 0.5), f32(2, 3), f32(0.5),
cstr("b.png"), i32(1 | 16 | 32 | 65536, 2), f32(0, 0), f32(1, 1), f32(0))
brus = chunk("BRUS", i32(2),
cstr("red"), f32(1, 0, 0, 1), f32(0.5), i32(1, 0), i32(0, 1),
cstr("glass"), f32(0.2, 0.4, 1, 0.5), f32(0), i32(1, 16 | 1), i32(1, -1))
m1, _, _ = box_mesh(1, 2, 3, flags=3, sets=2, size=2, brushes=(0, 1))
m2, _, _ = box_mesh(0.5, 0.5, 0.5, flags=1, sets=1, size=2, brushes=(-1,), master=1)
child = node("child", (3, 1, -2), (1, 2, 1), quat_axis(0, 1, 1, 50), m2)
root = node("root", (1, 2, 3), (2, 1, 0.5), quat_axis(1, 1, 0, 30), m1, child)
data = chunk("BB3D", i32(1), texs, brus, root)
return data, {"vertices": 16, "triangles": 24, "textures": 2, "materials": 2, "colors": True, "uvSets": 2, "nodes": 2}
def pivots():
m1, _, _ = box_mesh(1, 1, 1, brushes=(-1,))
m2, _, _ = box_mesh(2, 0.5, 1, sets=0, brushes=(-1,))
a = node("a", (5, 0, 0), (1, 1, 1), quat_axis(0, 0, 1, 90), m1)
b = node("b", (0, 0, 5), (-1, 1, 1), quat_axis(0, 1, 0, -45), m2)
pivot = node("pivot", (0, 3, 0), (1, 1, 1), quat_axis(1, 0, 0, 20), a, b)
data = chunk("BB3D", i32(1), node("top", (0, 0, 0), (1, 1, 1), (1, 0, 0, 0), pivot))
return data, {"vertices": 16, "triangles": 24, "textures": 0, "materials": 0, "colors": False, "uvSets": 1, "nodes": 4, "mirrored": True}
def skinned():
# a bar along y: 3 rings of 4 vertices; two bones (nested), each weighting rings; keys on both bones
verts, tris = [], []
for ring in range(3):
for k in range(4):
a = math.radians(90 * k)
verts.append(f32(math.cos(a), ring * 2.0, math.sin(a)))
for ring in range(2):
for k in range(4):
a, b = ring * 4 + k, ring * 4 + (k + 1) % 4
tris += [(a, b + 4, b), (a, a + 4, b + 4)]
mesh = chunk("MESH", i32(-1), chunk("VRTS", i32(0, 0, 0), b"".join(verts)), chunk("TRIS", i32(-1), b"".join(i32(*t) for t in tris)))
w1 = b"".join(i32(v) + f32(1.0 if v < 4 else 0.5) for v in range(8))
w2 = b"".join(i32(v) + f32(0.5 if v < 8 else 1.0) for v in range(4, 12))
keys1 = chunk("KEYS", i32(4), *[i32(f) + f32(*quat_axis(0, 0, 1, f * 10)) for f in (1, 5, 10)])
keys2 = chunk("KEYS", i32(1 | 2), *[i32(f) + f32(0, 2 + f * 0.1, 0) + f32(1, 1 + f * 0.05, 1) for f in (1, 10)])
bone2 = node("bone2", (0, 2, 0), (1, 1, 1), (1, 0, 0, 0), chunk("BONE", w2), keys2)
bone1 = node("bone1", (0, 0, 0), (1, 1, 1), (1, 0, 0, 0), chunk("BONE", w1), keys1, bone2)
root = node("body", (0, 1, 0), (1, 1, 1), quat_axis(0, 1, 0, 15), mesh, bone1, chunk("ANIM", i32(0, 10), f32(25)))
data = chunk("BB3D", i32(1), root)
return data, {"vertices": 12, "triangles": 16, "textures": 0, "materials": 0, "colors": False, "uvSets": 0, "nodes": 3,
"joints": 2, "channels": 3, "fps": 25.0, "frames": 10}
# ---------------------------------------------------------------------------------------------------- references
def info(ctx, path):
try:
txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace")
except subprocess.CalledProcessError:
return {"failed": True}
out = {}
for label in ("Meshes", "Materials", "Faces", "Vertices", "Animations", "Bones", "Animation Channels", "Nodes"):
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
out[label.lower().replace(" ", "_")] = int(m.group(1)) if m else -1
return out
def ptv(ctx, path, tmp):
# world-space triangles from assimp's PreTransformVertices OBJ export: bounds, area, signed volume
out = os.path.join(tmp, "ptv.obj")
ctx.nix("assimp", ["assimp", "export", path, out, "-ptv"])
vs, area, vol = [], 0.0, 0.0
lo, hi = [1e30] * 3, [-1e30] * 3
with open(out) as f:
for line in f:
p = line.split()
if not p:
continue
if p[0] == "v":
v = [float(x) for x in p[1:4]]
vs.append(v)
lo = [min(a, b) for a, b in zip(lo, v)]
hi = [max(a, b) for a, b in zip(hi, v)]
elif p[0] == "f":
idx = [int(x.split("/")[0]) for x in p[1:]]
idx = [i - 1 if i > 0 else len(vs) + i for i in idx]
for k in range(1, len(idx) - 1):
a, b, c = vs[idx[0]], vs[idx[k]], vs[idx[k + 1]]
e1 = [b[j] - a[j] for j in range(3)]
e2 = [c[j] - a[j] for j in range(3)]
cr = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]
area += math.sqrt(sum(x * x for x in cr)) / 2
vol += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6
os.remove(out)
return {"min": lo, "max": hi, "area": area, "volume": vol}
def generate(ctx):
M = ref_module(ctx)
tmp = M.tempdir()
cases = []
src = assimp_src()
for rel in ("models/B3D/WusonBlitz.b3d", "models-nonbsd/B3D/dwarf2.b3d", "models-nonbsd/B3D/turtle1.b3d"):
p = os.path.join(src, "test", rel)
if not os.path.exists(p):
continue
d = os.path.dirname(p)
files = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d))
if f.lower().endswith((".png", ".jpg")) and os.path.getsize(os.path.join(d, f)) < 300000}
cases.append({"name": "assimp/" + rel, "path": p, "files": files})
for name, fn in (("textured", textured), ("pivots", pivots), ("skinned", skinned)):
data, want = fn()
p = os.path.join(tmp, name + ".b3d")
with open(p, "wb") as f:
f.write(data)
files = {"a.png": M_PNG, "b.png": M_PNG} if name == "textured" else {}
cases.append({"name": "gen/" + name, "path": p, "files": files, "want": want})
for c in cases:
a = info(ctx, c["path"])
if not a.get("failed"):
a.update(ptv(ctx, c["path"], tmp))
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("b3d_cases", cases)
# a 1x1 PNG (texture data for the generated files)
M_PNG = bytes.fromhex("89504e470d0a1a0a0000000d4948445200000001000000010806000000"
"1f15c4890000000d49444154789c63f8cfc0f01f0005000201a2b3d6bd0000000049454e44ae426082")
+17
View File
@@ -0,0 +1,17 @@
# Docs inputs for the Draco section of docs/guide/scene.md (tools/fixtures.py, tools/docs_check.py): the Khronos Box
# sample (tests/fixtures/gltf) compressed with KHR_draco_mesh_compression by draco_transcoder 1.5.7 (nix).
# tests/gen/docs_draco.luau { files = { [name] = bytes }, vars = { dracoGlbBytes = "Box_draco.glb" } }
import importlib.util, os, subprocess, tempfile
INPUTS = ["tools/docs_check.py", "tests/fixtures/gltf/Box"]
def generate(ctx):
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
dc = importlib.util.module_from_spec(spec)
spec.loader.exec_module(dc)
draco = subprocess.run(["nix", "build", "nixpkgs#draco", "--no-link", "--print-out-paths"], capture_output=True, check=True).stdout.decode().strip().split("\n")[-1]
out = os.path.join(tempfile.mkdtemp(prefix="formats-docs-draco-"), "Box_draco.glb")
subprocess.run([os.path.join(draco, "bin", "draco_transcoder"), "-i", os.path.join(ctx.root, "tests", "fixtures", "gltf", "Box", "glTF-Binary", "Box.glb"), "-o", out],
capture_output=True, check=True)
dc.emit_inputs(ctx, {"Box_draco.glb": open(out, "rb").read()}, {"dracoGlbBytes": "Box_draco.glb"})
+137
View File
@@ -0,0 +1,137 @@
# Draco fixtures (tools/fixtures.py): every .drc file of Google's Draco test data (bitstreams 0.9 - 2.2, read from the
# nixpkgs draco source, never committed) and files made here by draco_encoder 1.5.7 (nix) from the test data meshes
# and generated ones (a UV sphere with seams, a noisy grid, a coloured PLY), at every compression level (sequential,
# Edgebreaker standard / valence; difference, parallelogram, constrained multi-parallelogram, portable tex coords and
# geometric normal predictions), several quantizations (up to 30 bits) and as point clouds. The reference values come
# from libdraco itself: tools/fixtures/_draco_dump.cc, compiled here against nixpkgs#draco, prints the decoded points,
# faces and each attribute's bytes per point.
# tests/gen/draco_cases.luau { { name, data, error? = true, points, faces, indices = crc, attrs = { { type, dataType,
# components, normalized, uniqueId, crc } } } }
import math, os, subprocess, tempfile, zlib
INPUTS = ["tools/fixtures/_draco_dump.cc"]
def store_path(attr):
out = subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], capture_output=True, check=True)
return out.stdout.decode().strip().split("\n")[-1]
def uv_sphere(rings=12, segs=20):
# an OBJ sphere with a UV seam and poles: vertices shared by position, split by UV
v, vt, vn, f = [], [], [], []
for r in range(rings + 1):
th = math.pi * r / rings
for s in range(segs + 1):
ph = 2 * math.pi * s / segs
x, y, z = math.sin(th) * math.cos(ph), math.cos(th), math.sin(th) * math.sin(ph)
v.append((x, y, z))
vn.append((x, y, z))
vt.append((s / segs, r / rings))
w = segs + 1
for r in range(rings):
for s in range(segs):
a, b, c, d = r * w + s + 1, r * w + s + 2, (r + 1) * w + s + 2, (r + 1) * w + s + 1
if r > 0:
f.append((a, b, c))
if r < rings - 1:
f.append((a, c, d))
out = ["v %.6f %.6f %.6f" % p for p in v] + ["vt %.6f %.6f" % p for p in vt] + ["vn %.6f %.6f %.6f" % p for p in vn]
out += ["f %d/%d/%d %d/%d/%d %d/%d/%d" % (a, a, a, b, b, b, c, c, c) for a, b, c in f]
return "\n".join(out) + "\n"
def noisy_grid(rng, n=24):
# a height field with a hole and per-vertex UVs: boundaries, holes and parallelogram predictions
v, vt, f = [], [], []
for j in range(n):
for i in range(n):
v.append((i * 0.1, rng.uniform(-0.05, 0.05), j * 0.1))
vt.append((i / (n - 1), j / (n - 1)))
for j in range(n - 1):
for i in range(n - 1):
if 8 <= i < 12 and 8 <= j < 12:
continue
a, b, c, d = j * n + i + 1, j * n + i + 2, (j + 1) * n + i + 2, (j + 1) * n + i + 1
f.append((a, b, c))
f.append((a, c, d))
out = ["v %.6f %.6f %.6f" % p for p in v] + ["vt %.6f %.6f" % p for p in vt]
out += ["f %d/%d %d/%d %d/%d" % (a, a, b, b, c, c) for a, b, c in f]
return "\n".join(out) + "\n"
def colored_ply(rng, n=200):
# an ASCII point set / mesh with colours (u8) and a generic float property
pts = [(rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]
faces = [(i, i + 1, i + 2) for i in range(0, n - 2, 3)]
head = ["ply", "format ascii 1.0", "element vertex %d" % n, "property float x", "property float y", "property float z",
"property uchar red", "property uchar green", "property uchar blue", "property uchar alpha",
"element face %d" % len(faces), "property list uchar int vertex_indices", "end_header"]
body = ["%.5f %.5f %.5f %d %d %d %d" % (p[0], p[1], p[2], rng.randrange(256), rng.randrange(256), rng.randrange(256), 255) for p in pts]
body += ["3 %d %d %d" % t for t in faces]
return "\n".join(head + body) + "\n"
def parse_dump(txt):
out = {"attrs": []}
for line in txt.split("\n"):
parts = line.split(" ")
if parts[0] == "ERROR":
return {"error": True}
if parts[0] == "POINTS":
out["points"] = int(parts[1])
elif parts[0] == "FACES":
out["faces"] = int(parts[1])
out["indices"] = zlib.crc32(bytes.fromhex(parts[2] if len(parts) > 2 else ""))
elif parts[0] == "ATTR":
out["attrs"].append({"type": int(parts[1]), "dataType": int(parts[2]), "components": int(parts[3]),
"normalized": parts[4] == "1", "uniqueId": int(parts[5]),
"crc": zlib.crc32(bytes.fromhex(parts[6] if len(parts) > 6 else ""))})
return out
def generate(ctx):
draco = store_path("draco")
src = store_path("draco.src")
testdata = os.path.join(src, "testdata")
tmp = tempfile.mkdtemp(prefix="formats-draco-")
dump = os.path.join(tmp, "dump")
ctx.nix("gcc", ["g++", "-O1", "-std=c++17", "-I" + os.path.join(draco, "include"), os.path.join(ctx.root, "tools", "fixtures", "_draco_dump.cc"),
"-L" + os.path.join(draco, "lib"), "-l:libdraco.a", "-o", dump])
encoder = os.path.join(draco, "bin", "draco_encoder")
files = [] # (name, path)
for f in sorted(os.listdir(testdata)):
if f.endswith(".drc"):
files.append(("testdata/" + f, os.path.join(testdata, f)))
rng = ctx.rng(31)
gen_inputs = {"uvsphere.obj": uv_sphere(), "grid.obj": noisy_grid(rng), "colored.ply": colored_ply(rng)}
for name, text in gen_inputs.items():
with open(os.path.join(tmp, name), "w") as fh:
fh.write(text)
inputs = [(n, os.path.join(tmp, n)) for n in gen_inputs] + [(n, os.path.join(testdata, n)) for n in
("cube_att.obj", "test_nm.obj", "sphere.obj", "cube_quads.obj", "test_generic.ply", "Box.ply")]
variants = [("cl%d" % cl, ["-cl", str(cl)]) for cl in range(11)]
variants += [("q14", ["-qp", "14", "-qt", "12", "-qn", "10"]), ("q20", ["-qp", "20", "-qt", "16", "-qn", "14", "-qg", "12"]),
("q30", ["-qp", "30", "-qt", "30", "-qn", "30", "-qg", "30"]), ("q30cl10", ["-cl", "10", "-qp", "24", "-qt", "24", "-qn", "24"]),
("raw", ["-qp", "0", "-qt", "0", "-qn", "0", "-qg", "0"]), ("meta", ["--metadata"]), ("poly", ["-preserve_polygons"]),
("pc", ["-point_cloud", "-cl", "0"]), ("pckd", ["-point_cloud"])]
for iname, ipath in inputs:
for vname, args in variants:
out = os.path.join(tmp, "%s.%s.drc" % (iname, vname))
r = subprocess.run([encoder, "-i", ipath, "-o", out] + args, capture_output=True)
if r.returncode == 0 and os.path.exists(out):
files.append(("enc/%s.%s" % (iname, vname), out))
# the large bunny once (Edgebreaker valence + normals)
out = os.path.join(tmp, "bunny.drc")
if subprocess.run([encoder, "-i", os.path.join(testdata, "bunny_norm.obj"), "-o", out, "-cl", "7"], capture_output=True).returncode == 0:
files.append(("enc/bunny_norm.obj.cl7", out))
cases = []
for name, path in files:
ref = parse_dump(subprocess.run([dump, path], capture_output=True).stdout.decode())
case = {"name": name, "data": open(path, "rb").read()}
case.update(ref)
cases.append(case)
ctx.emit("draco_cases", cases)
+132
View File
@@ -0,0 +1,132 @@
# glTF + Draco fixtures (tools/fixtures.py): KHR_draco_mesh_compression files. The Khronos samples of
# tests/fixtures/gltf compressed by draco_transcoder 1.5.7 (nix) at its default and at a finer quantization, Draco's
# own glTF test files (Box_Draco.glb, BoxMetaDraco) and assimp's 2CylinderEngine (robot.glb: 12 MB, left out), read from the
# nixpkgs sources and never committed. Reference values: every Draco primitive's buffer view decoded by libdraco
# (tools/fixtures/_draco_dump.cc, compiled against nixpkgs#draco): points, faces, the index and per-attribute CRCs.
# tests/gen/gltf_draco.luau { { name, data, files = { uri -> bytes }, original? = { data, files } (the uncompressed
# source), prims = { { mesh, prim, points, faces, indices, attrs = { [name] = { uniqueId,
# dataType, crc } } } } } }
import json, os, struct, subprocess, tempfile, zlib
INPUTS = ["tests/fixtures/gltf", "tools/fixtures/_draco_dump.cc"]
def store_path(attr):
out = subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], capture_output=True, check=True)
return out.stdout.decode().strip().split("\n")[-1]
def load(path):
# -> (doc, bin, files): the JSON, the GLB binary chunk, the sibling files a .gltf refers to
raw = open(path, "rb").read()
files, binchunk = {}, None
if raw[:4] == b"glTF":
off = 12
doc = None
while off + 8 <= len(raw):
n, kind = struct.unpack_from("<II", raw, off)
chunk = raw[off + 8:off + 8 + n]
if kind == 0x4E4F534A:
doc = json.loads(chunk)
elif kind == 0x004E4942:
binchunk = chunk
off += 8 + n
else:
doc = json.loads(raw)
d = os.path.dirname(path)
for b in doc.get("buffers", []) + doc.get("images", []):
uri = b.get("uri")
if uri and not uri.startswith("data:") and os.path.exists(os.path.join(d, uri)):
files[uri] = open(os.path.join(d, uri), "rb").read()
return doc, binchunk, files
def buffer_bytes(doc, binchunk, files, i):
b = doc["buffers"][i]
uri = b.get("uri")
if uri is None:
return binchunk
if uri.startswith("data:"):
import base64
return base64.b64decode(uri.split(",", 1)[1])
return files[uri]
def references(doc, binchunk, files, dump, tmp):
prims = []
for mi, m in enumerate(doc.get("meshes", [])):
for pi, p in enumerate(m.get("primitives", [])):
ext = p.get("extensions", {}).get("KHR_draco_mesh_compression")
if not ext:
continue
v = doc["bufferViews"][ext["bufferView"]]
data = buffer_bytes(doc, binchunk, files, v["buffer"])
off = v.get("byteOffset", 0)
drc = data[off:off + v["byteLength"]]
path = os.path.join(tmp, "p.drc")
open(path, "wb").write(drc)
lines = subprocess.run([dump, path], capture_output=True).stdout.decode().split("\n")
entry = {"mesh": mi + 1, "prim": pi + 1, "attrs": {}}
by_id = {}
for line in lines:
parts = line.split(" ")
if parts[0] == "POINTS":
entry["points"] = int(parts[1])
elif parts[0] == "FACES":
entry["faces"] = int(parts[1])
entry["indices"] = zlib.crc32(bytes.fromhex(parts[2] if len(parts) > 2 else ""))
elif parts[0] == "ATTR":
by_id[int(parts[5])] = {"dataType": int(parts[2]), "crc": zlib.crc32(bytes.fromhex(parts[6] if len(parts) > 6 else ""))}
for name, uid in ext.get("attributes", {}).items():
if uid in by_id:
a = dict(by_id[uid])
a["uniqueId"] = uid
entry["attrs"][name] = a
prims.append(entry)
return prims
def generate(ctx):
draco = store_path("draco")
dsrc = store_path("draco.src")
asrc = store_path("assimp.src")
tmp = tempfile.mkdtemp(prefix="formats-gltfdraco-")
dump = os.path.join(tmp, "dump")
ctx.nix("gcc", ["g++", "-O1", "-std=c++17", "-I" + os.path.join(draco, "include"), os.path.join(ctx.root, "tools", "fixtures", "_draco_dump.cc"),
"-L" + os.path.join(draco, "lib"), "-l:libdraco.a", "-o", dump])
transcoder = os.path.join(draco, "bin", "draco_transcoder")
sources = [] # (name, path, original path?)
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
for model in sorted(os.listdir(gl)):
d0 = os.path.join(gl, model)
for variant in sorted(os.listdir(d0)):
d = os.path.join(d0, variant)
if not os.path.isdir(d) or "Quantized" in variant:
continue
mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")]
if not mains:
continue
src = os.path.join(d, mains[0])
for q, args in (("default", []), ("fine", ["-qp", "16", "-qt", "14", "-qn", "12", "-qc", "10", "-qw", "12", "-qtg", "10"])):
out = os.path.join(tmp, "%s_%s.glb" % (model, q))
r = subprocess.run([transcoder, "-i", src, "-o", out] + args, capture_output=True)
if r.returncode == 0 and os.path.exists(out):
sources.append(("transcoded/%s/%s" % (model, q), out, src))
break
for name, rel in (("draco/Box_Draco.glb", os.path.join(dsrc, "testdata", "Box", "glTF_Binary", "Box_Draco.glb")),
("draco/BoxMetaDraco.gltf", os.path.join(dsrc, "testdata", "BoxMetaDraco", "glTF", "BoxMetaDraco.gltf")),
("assimp/2CylinderEngine.gltf", os.path.join(asrc, "test", "models", "glTF2", "draco", "2CylinderEngine.gltf"))):
if os.path.exists(rel):
sources.append((name, rel, None))
cases = []
for name, path, orig in sources:
doc, binchunk, files = load(path)
prims = references(doc, binchunk, files, dump, tmp)
if not prims:
continue
case = {"name": name, "data": open(path, "rb").read(), "files": files, "prims": prims}
if orig:
_, _, ofiles = load(orig)
case["original"] = {"data": open(orig, "rb").read(), "files": ofiles}
cases.append(case)
ctx.emit("gltf_draco", cases)
+57
View File
@@ -0,0 +1,57 @@
# Inter-Quake Model fixtures (tools/fixtures.py): assimp's IQM test model (mrfixit.iqm, from the nixpkgs assimp
# source, never committed) with assimp's view of it (`assimp info -r`, PreTransformVertices bounds) and an independent
# Python reading (tools/fixtures/_iqm_reference.py: counts, and the bounds of the skinned vertices per frame computed
# from joints / poses / frames, next to the bounds block the IQM tool stored); glTF sample models (tests/fixtures/gltf)
# for the writer; then our encoder's output (tools/fixtures/_iqm_encode.luau) read back by assimp and the Python reader.
# tests/gen/iqm_cases.luau { name, data, assimp, ref }
# tests/gen/iqm_gltf.luau { name, data, files }
# tests/gen/iqm_xcheck.luau { name, assimp, ref }
import importlib.util, os
INPUTS = ["src/Formats/model/iqm", "src/Formats/codecs/model", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py",
"tools/fixtures/_iqm_reference.py", "tools/fixtures/_iqm_encode.luau", "tests/fixtures/gltf"]
def module(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def info(ctx, M, fbx, path, tmp):
a = M.assimp_info(ctx, [path], raw=True)[0]
for k in ("min", "max", "perMesh"):
a.pop(k, None)
if not a.get("failed"):
a.update(fbx.ptv_bounds(ctx, path, tmp))
return a
def generate(ctx):
M = module(ctx, "_model_ref")
fbx = module(ctx, "fbx")
R = module(ctx, "_iqm_reference")
tmp = M.tempdir()
p = os.path.join(fbx.assimp_src(ctx), "test", "models", "IQM", "mrfixit.iqm")
data = open(p, "rb").read()
ctx.emit("iqm_cases", [{"name": "mrfixit.iqm", "data": data, "assimp": info(ctx, M, fbx, p, tmp), "ref": R.read(data)}])
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
picks = []
for model in ("RiggedSimple", "SimpleSkin", "Box", "BoxTextured", "BoxVertexColors", "MeshPrimitiveModes", "SimpleMeshes"):
d0 = os.path.join(gl, model)
for variant in sorted(os.listdir(d0)) if os.path.isdir(d0) else []:
d = os.path.join(d0, variant)
mains = [f for f in sorted(os.listdir(d)) if f.endswith((".gltf", ".glb"))] if os.path.isdir(d) else []
if mains:
picks.append({"name": model, "data": open(os.path.join(d, mains[0]), "rb").read(),
"files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}})
break
ctx.emit("iqm_gltf", picks)
ours = M.luau_encode(ctx, "tools/fixtures/_iqm_encode.luau")
out = []
for name in sorted(ours):
q = os.path.join(tmp, name)
open(q, "wb").write(ours[name])
out.append({"name": name, "assimp": info(ctx, M, fbx, q, tmp), "ref": R.read(ours[name])})
ctx.emit("iqm_xcheck", out)
+417
View File
@@ -0,0 +1,417 @@
# LDraw fixtures (tools/fixtures.py): hand-written LDraw files (a brick built from primitives that come through
# `files` with library paths, an MPD with embedded sub-files and sub-models, BFC CERTIFY CW / CCW, INVERTNEXT,
# mirrored references, NOCERTIFY / NOCLIP, colour inheritance 16 / 24, direct colours, local !COLOUR definitions,
# optional lines, a missing part) and real parts and the sample models car.ldr / pyramid.ldr from the LDraw parts
# library (complete.zip, CC BY 2.0 / 4.0, the copy nixpkgs' LeoCAD package uses; read from the nix store, never
# committed: each case carries the files it needs). References: an independent expansion written here (world
# triangles after the decoder's root flip, per colour, lines, area, bounds, signed volume of the one-sided faces) and
# LeoCAD's OBJ export (`leocad -obj`: bounds and area of the real models), plus LDConfig.ldr itself for the built-in
# colour table.
# tests/gen/ldraw_cases.luau { name, data, files = { path -> text }, opts?, want = {...}, leocad? = {...} }
# tests/gen/ldraw_config.luau { text = LDConfig.ldr, colours = { { code, rgb, edge, alpha } } }
import math, os, re, subprocess, zipfile
INPUTS = []
def nix_out(attr):
out = subprocess.run(["nix", "build", attr, "--no-link", "--print-out-paths"], capture_output=True, check=True)
return out.stdout.decode().strip().split("\n")[-1]
def library_zip(leocad):
# LeoCAD's wrapper points LEOCAD_LIB at the parts library zip
wrapper = open(os.path.join(leocad, "bin", "leocad"), "rb").read().decode("latin-1")
m = re.search(r"(/nix/store/[^'\" ]*complete\.zip)", wrapper)
return m.group(1) if m else None
# ---------------------------------------------------------------------------------------------------- reference
def norm(name):
return name.strip().replace("\\", "/").lower()
class Ref:
"""an independent LDraw expansion: every triangle in world space (after the root flip y -> -y, z -> -z)"""
PREFIXES = ("", "parts/", "p/", "parts/s/", "models/")
def __init__(self, main, files, colours):
self.files = {norm(k): v for k, v in files.items()}
self.colours = colours # code -> (rgb, edge)
self.mpd = {}
self.missing = set()
self.tris = [] # (colour, ds, (v0, v1, v2))
self.lines = 0
self.optional = 0
text = main
if re.search(r"^\s*0\s+FILE\s", text, re.M):
cur = None
first = None
for line in text.splitlines():
m = re.match(r"^\s*0\s+FILE\s+(.*?)\s*$", line)
if m:
cur = norm(m.group(1))
first = first or cur
self.mpd[cur] = []
continue
if re.match(r"^\s*0\s+NOFILE\b", line):
cur = None
continue
if cur:
self.mpd[cur].append(line)
self.main = "\n".join(self.mpd[first])
else:
self.main = text
org = re.search(r"^\s*0\s+!LDRAW_ORG\s+(\S+)", self.main, re.M)
refs = re.search(r"^\s*1\s", self.main, re.M)
self.main_part = bool(org and "model" not in org.group(1).lower()) or not refs
def lookup(self, name):
n = norm(name)
if n in self.mpd:
return "\n".join(self.mpd[n])
for p in self.PREFIXES:
if p + n in self.files:
return self.files[p + n]
self.missing.add(n)
return None
def colour(self, code, cur):
if code == 16:
return cur
if code == 24:
return self.edge(cur)
return code
def edge(self, c):
if c in self.colours:
e = self.colours[c][1]
return e
return 0x2333333 if c < 0x2000000 else 0x2000000
def walk(self, text, m, colour, inv, certified, depth, model, stack=()):
# model files (the main file, .ldr / .mpd sub-models) do not limit the certification of what they place
if depth > 64:
return
st = {"cw": False, "cert": None, "clip": True, "invert": False}
for raw in text.splitlines():
t = raw.split()
if not t:
continue
if t[0] == "0":
if len(t) >= 3 and t[1] == "!COLOUR":
self.colours.update({k: (v[0], v[1]) for k, v in parse_ldconfig(raw).items()})
if len(t) >= 3 and t[1] == "BFC":
words = [w.upper() for w in t[2:]]
if "NOCERTIFY" in words:
st["cert"] = False
elif "CERTIFY" in words:
st["cert"] = True
if "CW" in words:
st["cw"] = True
if "CCW" in words:
st["cw"] = False
if "NOCLIP" in words:
st["clip"] = False
elif "CLIP" in words:
st["clip"] = True
if "INVERTNEXT" in words:
st["invert"] = True
continue
invert_next = st["invert"]
st["invert"] = False
try:
kind = int(t[0])
code = int(t[1], 0)
cert = certified and st["cert"] is True and st["clip"]
if kind == 1 and len(t) >= 15:
x, y, z, a, b, c, d, e, f, g, h, i = [float(v) for v in t[2:14]]
loc = [[a, b, c, x], [d, e, f, y], [g, h, i, z]]
name = raw.split(None, 14)[14].strip()
if norm(name) in stack:
continue # a file that (indirectly) places itself
sub = self.lookup(name)
if sub is None:
continue
sub_model = norm(name).endswith((".ldr", ".mpd"))
self.walk(sub, mul(m, loc), self.colour(code, colour), inv ^ invert_next,
(True if model else cert), depth + 1, sub_model, stack + (norm(name),))
elif kind in (3, 4) and len(t) >= 2 + 3 * kind:
pts = [apply(m, [float(v) for v in t[2 + 3 * k:5 + 3 * k]]) for k in range(kind)]
if st["cw"] ^ inv ^ (det(m) < 0):
pts = pts[::-1]
col = self.colour(code, colour)
one = cert and not model or (model and st["cert"] is True and st["clip"])
self.tris.append((col, not one, (pts[0], pts[1], pts[2])))
if kind == 4:
self.tris.append((col, not one, (pts[0], pts[2], pts[3])))
elif kind == 2 and len(t) >= 8:
[float(v) for v in t[2:8]]
self.lines += 1
elif kind == 5 and len(t) >= 14:
[float(v) for v in t[2:14]]
self.optional += 1
except ValueError:
pass
def run(self, main_colour=16):
flip = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0]]
self.walk(self.main, flip, main_colour, False, True, 0, not self.main_part)
return self
def summary(self):
per = {}
area, vol = 0.0, 0.0
lo, hi = [1e30] * 3, [-1e30] * 3
for col, ds, (a, b, c) in self.tris:
per[col] = per.get(col, 0) + 1
for p in (a, b, c):
lo = [min(u, v) for u, v in zip(lo, p)]
hi = [max(u, v) for u, v in zip(hi, p)]
area += tri_area(a, b, c)
if not ds:
vol += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6
out = {"triangles": len(self.tris), "lines": self.lines, "optional": self.optional, "area": area, "volume": vol,
"doubleSided": sum(1 for x in self.tris if x[1]),
"colours": [[k, v] for k, v in sorted(per.items())], "missing": sorted(self.missing)}
if self.tris:
out["min"], out["max"] = lo, hi
return out
def mul(m, l):
# 3x4 affine product m * l
r = [[0.0] * 4 for _ in range(3)]
for i in range(3):
for j in range(4):
s = sum(m[i][k] * l[k][j] for k in range(3))
r[i][j] = s + (m[i][3] if j == 3 else 0)
return r
def apply(m, p):
return [m[i][0] * p[0] + m[i][1] * p[1] + m[i][2] * p[2] + m[i][3] for i in range(3)]
def det(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]))
def tri_area(a, b, c):
e1 = [b[i] - a[i] for i in range(3)]
e2 = [c[i] - a[i] for i in range(3)]
x = e1[1] * e2[2] - e1[2] * e2[1]
y = e1[2] * e2[0] - e1[0] * e2[2]
z = e1[0] * e2[1] - e1[1] * e2[0]
return math.sqrt(x * x + y * y + z * z) / 2
def parse_ldconfig(text):
out = {}
for line in text.splitlines():
m = re.match(r"^\s*0\s+!COLOUR\s+(\S+)\s+(.*)$", line)
if not m:
continue
t = m.group(2).split()
kv = {}
for i in range(0, len(t) - 1):
if t[i] in ("CODE", "VALUE", "EDGE", "ALPHA") and t[i] not in kv:
kv[t[i]] = t[i + 1]
code = int(kv["CODE"])
rgb = int(kv["VALUE"][1:], 16)
e = kv["EDGE"]
edge = (0x2000000 | int(e[1:], 16)) if e.startswith("#") else int(e)
out[code] = (rgb, edge, int(kv.get("ALPHA", "255")), m.group(1))
return out
# ---------------------------------------------------------------------------------------------------- hand-written
BOX = """0 a unit box primitive (faces outward, CCW)
0 BFC CERTIFY CCW
4 16 -1 -1 -1 1 -1 -1 1 -1 1 -1 -1 1
4 16 -1 1 -1 -1 1 1 1 1 1 1 1 -1
4 16 -1 -1 -1 -1 -1 1 -1 1 1 -1 1 -1
4 16 1 -1 -1 1 1 -1 1 1 1 1 -1 1
4 16 -1 -1 -1 -1 1 -1 1 1 -1 1 -1 -1
4 16 -1 -1 1 1 -1 1 1 1 1 -1 1 1
2 24 -1 -1 -1 1 -1 -1
2 24 -1 -1 -1 -1 1 -1
5 24 -1 -1 -1 -1 1 -1 1 -1 -1 -1 -1 1
"""
BOX_CW = """0 the same box written clockwise
0 BFC CERTIFY CW
4 16 -1 -1 1 1 -1 1 1 -1 -1 -1 -1 -1
4 16 1 1 -1 1 1 1 -1 1 1 -1 1 -1
4 16 -1 1 -1 -1 1 1 -1 -1 1 -1 -1 -1
4 16 1 -1 1 1 1 1 1 1 -1 1 -1 -1
4 16 1 -1 -1 1 1 -1 -1 1 -1 -1 -1 -1
4 16 -1 1 1 1 1 1 1 -1 1 -1 -1 1
"""
TRI = """0 an uncertified triangle
3 16 0 0 0 1 0 0 0 0 1
"""
# a brick: an outer box, an inner box turned inside out (INVERTNEXT), a mirrored stud box, an uncertified triangle
BRICK = """0 Test Brick 1 x 2
0 Name: testbrick.dat
0 Author: formats-luau
0 !LDRAW_ORG Unofficial_Part
0 BFC CERTIFY CCW
1 16 0 12 0 20 0 0 0 12 0 0 0 10 box.dat
0 BFC INVERTNEXT
1 16 0 14 0 18 0 0 0 10 0 0 0 8 box.dat
1 4 10 -2 0 -6 0 0 0 2 0 0 0 6 s\\stud box.dat
1 16 0 -4 0 1 0 0 0 1 0 0 0 1 48\\cwbox.dat
1 16 0 30 0 5 0 0 0 5 0 0 0 5 tri.dat
"""
PLAIN_LDR = """0 Two bricks
0 Name: two.ldr
1 1 0 0 0 1 0 0 0 1 0 0 0 1 testbrick.dat
1 14 60 -24 0 0 0 1 0 1 0 -1 0 0 testbrick.dat
1 16 -60 0 0 -1 0 0 0 1 0 0 0 1 testbrick.dat
0 STEP
1 0x2FF8000 0 -60 0 1 0 0 0 1 0 0 0 1 testbrick.dat
1 4 0 -90 0 1 0 0 0 1 0 0 0 1 nosuchpart.dat
"""
MPD = """0 FILE main.ldr
0 MPD main
0 Name: main.ldr
0 !COLOUR Test_Purple CODE 1000 VALUE #8000FF EDGE #200040 ALPHA 200
1 16 0 0 0 1 0 0 0 1 0 0 0 1 sub.ldr
1 1000 0 -100 0 1 0 0 0 1 0 0 0 1 sub.ldr
1 2 0 50 50 1 0 0 0 -1 0 0 0 1 Embedded Part.dat
3 24 0 0 0 10 0 0 0 10 0
0 NOFILE
0 FILE sub.ldr
0 a sub-model: two parts and a nested sub-model
1 16 0 0 0 1 0 0 0 1 0 0 0 1 embedded part.dat
1 4 30 0 0 1 0 0 0 1 0 0 0 1 embedded part.dat
1 16 0 0 40 1 0 0 0 1 0 0 0 1 inner.ldr
0 NOFILE
0 FILE inner.ldr
1 0x3FF0000 0 0 0 2 0 0 0 2 0 0 0 2 embedded part.dat
0 FILE Embedded Part.dat
0 !LDRAW_ORG Unofficial_Part
0 BFC CERTIFY CCW
1 16 0 0 0 5 0 0 0 5 0 0 0 5 box.dat
0 BFC NOCLIP
3 24 0 -5 0 5 -5 0 0 -5 5
0 BFC CLIP
4 16 -5 -6 -5 5 -6 -5 5 -6 5 -5 -6 5
"""
BAD_REFS = """0 cycles and bad lines are survived
1 16 0 0 0 1 0 0 0 1 0 0 0 1 loop.dat
1 16 0 0 0 1 0 0 0 1
3 16 0 0 0 1 x 0 0 0 1
4 16 0 0 0 1 0 0 1 1 0 0 1 0
"""
LOOP = "0 a file that calls itself\n3 16 0 0 0 1 0 0 0 1 0\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 loop.dat\n"
LIB = {"parts/box.dat": BOX, "p/s/stud box.dat": BOX, "p/48/cwbox.dat": BOX_CW, "p/tri.dat": TRI,
"parts/testbrick.dat": BRICK, "loop.dat": LOOP}
def hand_cases(colours):
cases = []
def add(name, text, files, opts=None):
ref = Ref(text, files, colours).run()
c = {"name": name, "data": text, "files": files, "want": ref.summary()}
if opts:
c["opts"] = opts
cases.append(c)
add("brick.dat", BRICK, {k: v for k, v in LIB.items() if k != "parts/testbrick.dat"})
add("two.ldr", PLAIN_LDR, dict(LIB))
add("model.mpd", MPD, {"parts/box.dat": BOX})
add("badrefs.ldr", BAD_REFS, {"loop.dat": LOOP})
add("crlf.ldr", PLAIN_LDR.replace("\n", "\r\n"), dict(LIB))
return cases
# ---------------------------------------------------------------------------------------------------- real parts
def closure(z, names, text_of):
"""the library files a set of references needs: { library path -> text }"""
have = {}
index = {}
for n in z.namelist():
if n.startswith("ldraw/") and n.lower().endswith(".dat"):
index[n[6:].lower()] = n
todo = list(names)
while todo:
n = norm(todo.pop())
for p in Ref.PREFIXES:
key = p + n
if key in index:
if key not in have:
t = z.read(index[key]).decode("utf-8", "replace")
have[key] = t
for line in t.splitlines():
parts = line.split(None, 14)
if len(parts) == 15 and parts[0] == "1":
todo.append(parts[14].strip())
break
return have
def leocad_obj(leocad, libzip, path, tmp):
out = os.path.join(tmp, "leocad.obj")
env = dict(os.environ, QT_QPA_PLATFORM="offscreen")
subprocess.run([os.path.join(leocad, "bin", "leocad"), "-l", libzip, path, "-obj", out], env=env, capture_output=True, timeout=300, check=True)
vs, area = [], 0.0
lo, hi = [1e30] * 3, [-1e30] * 3
with open(out) as f:
for line in f:
p = line.split()
if not p:
continue
if p[0] == "v":
v = [float(x) for x in p[1:4]]
vs.append(v)
lo = [min(a, b) for a, b in zip(lo, v)]
hi = [max(a, b) for a, b in zip(hi, v)]
elif p[0] == "f":
idx = [int(x.split("/")[0]) - 1 for x in p[1:]]
for k in range(1, len(idx) - 1):
area += tri_area(vs[idx[0]], vs[idx[k]], vs[idx[k + 1]])
return {"min": lo, "max": hi, "area": area}
def generate(ctx):
import tempfile
tmp = tempfile.mkdtemp(prefix="formats-ldraw-")
leocad = nix_out("nixpkgs#leocad")
libzip = library_zip(leocad)
z = zipfile.ZipFile(libzip)
config = z.read("ldraw/LDConfig.ldr").decode("utf-8")
colours = {k: (v[0], v[1]) for k, v in parse_ldconfig(config).items()}
ctx.emit("ldraw_config", {"text": config, "colours": [[k, v[0], v[1], v[2]] for k, v in sorted(parse_ldconfig(config).items())]})
cases = hand_cases(colours)
# real parts and the library's sample models, with LeoCAD's export
reals = [("3001.dat", None), ("3062b.dat", None), ("4073.dat", None), ("3626c.dat", None), ("car.ldr", "ldraw/models/car.ldr"),
("pyramid.ldr", "ldraw/models/pyramid.ldr")]
for name, member in reals:
if member:
text = z.read(member).decode("utf-8", "replace")
else:
text = "0 one part\n1 4 0 0 0 1 0 0 0 1 0 0 0 1 %s\n" % name
files = closure(z, [l.split(None, 14)[14].strip() for l in text.splitlines() if l.split(None, 14)[:1] == ["1"]], None)
ref = Ref(text, files, colours).run()
c = {"name": "library/" + name, "data": text, "files": files, "want": ref.summary()}
p = os.path.join(tmp, "model.ldr")
with open(p, "w") as f:
f.write(text)
try:
c["leocad"] = leocad_obj(leocad, libzip, p, tmp)
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError):
pass
cases.append(c)
ctx.emit("ldraw_cases", cases)
+41
View File
@@ -0,0 +1,41 @@
# LightWave object fixtures (tools/fixtures.py): assimp's LWO test models (LWO2, LWOB, Modo LXOB; models and
# models-nonbsd, read from the nixpkgs assimp source, never committed) with assimp's view of them (`assimp info -r`:
# meshes, polygons, corners, materials, nodes; world bounds from assimp's PreTransformVertices export).
# tests/gen/lwo_cases.luau { name, data, assimp = { meshes, faces, vertices, materials, nodes, min, max } }
import importlib.util, os
def module(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
INPUTS = ["src/Formats/model/lwo", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"]
def generate(ctx):
M = module(ctx, "_model_ref")
fbx = module(ctx, "fbx") # assimp_src, ptv_bounds
tmp = M.tempdir()
src = fbx.assimp_src(ctx)
cases = []
for sub in ("models/LWO", "models-nonbsd/LWO"):
d0 = os.path.join(src, "test", sub)
for root, _, files in sorted(os.walk(d0)):
for f in sorted(files):
if f.lower().endswith((".lwo", ".lxo")):
p = os.path.join(root, f)
cases.append({"name": sub.split("/")[0] + "/" + os.path.relpath(p, d0), "path": p})
infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True)
for c, a in zip(cases, infos):
a.pop("min", None)
a.pop("max", None)
a.pop("perMesh", None)
if not a.get("failed"):
a.update(fbx.ptv_bounds(ctx, c["path"], tmp))
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("lwo_cases", cases)
+68
View File
@@ -0,0 +1,68 @@
# MS3D fixtures (tools/fixtures.py): assimp's MilkShape 3D test models (test/models/MS3D: groups, materials, textures,
# version 4 with and without the sub-versioned blocks; read from the nixpkgs assimp source, never committed), with
# reference values from assimp (`assimp info -r`: meshes, faces, vertices, materials, animations, bones; world bounds
# from its PreTransformVertices export). No tool writes MS3D with joints, so skins and animation are checked through
# our writer: glTF sample models (skins, animation, textures) written by tools/fixtures/_ms3d_encode.luau and read
# back by assimp.
# tests/gen/ms3d_cases.luau { name, data, assimp }
# tests/gen/ms3d_gltf.luau glTF sample models: { name, data, files }
# tests/gen/ms3d_xcheck.luau { name, case? | gltf?, assimp }
import importlib.util, os
INPUTS = ["src/Formats/model/ms3d", "tests/fixtures/gltf", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py",
"tools/fixtures/3ds.py", "tools/fixtures/_ms3d_encode.luau"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location("_" + name.replace(".", "_"), os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
GLTF = ("Box", "BoxTextured", "SimpleSkin", "RiggedSimple", "SimpleMeshes", "MultiUVTest", "NegativeScaleTest",
"AnimatedTriangle", "TextureCoordinateTest", "MeshPrimitiveModes")
def generate(ctx):
M = load(ctx, "_model_ref")
X = load(ctx, "fbx")
R = load(ctx, "3ds")
tmp = M.tempdir()
d = os.path.join(X.assimp_src(ctx), "test", "models", "MS3D")
cases = [{"name": "assimp/" + f, "path": os.path.join(d, f)} for f in sorted(os.listdir(d)) if f.lower().endswith(".ms3d")]
for c, a in zip(cases, R.reference(ctx, M, X, [c["path"] for c in cases], tmp)):
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("ms3d_cases", cases)
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
picks = []
for model in GLTF:
d0 = os.path.join(gl, model)
if not os.path.isdir(d0):
continue
for variant in sorted(os.listdir(d0)):
dd = os.path.join(d0, variant)
mains = [f for f in sorted(os.listdir(dd)) if f.endswith(".gltf") or f.endswith(".glb")] if os.path.isdir(dd) else []
if mains:
picks.append({"name": model + "/" + variant, "data": open(os.path.join(dd, mains[0]), "rb").read(),
"files": {f: open(os.path.join(dd, f), "rb").read() for f in sorted(os.listdir(dd)) if f != mains[0]}})
break
ctx.emit("ms3d_gltf", picks)
ours = M.luau_encode(ctx, "tools/fixtures/_ms3d_encode.luau")
xtmp = M.tempdir()
names = sorted(n for n in ours if n.endswith(".ms3d"))
paths = []
for n in names:
p = os.path.join(xtmp, n)
with open(p, "wb") as f:
f.write(ours[n])
paths.append(p)
xs = []
for n, a in zip(names, R.reference(ctx, M, X, paths, xtmp)):
kind, idx = n[:-5].split("_")
e = {"name": n, "assimp": a}
e["case" if kind == "case" else "gltf"] = int(idx)
xs.append(e)
ctx.emit("ms3d_xcheck", xs)
+63
View File
@@ -0,0 +1,63 @@
# Quake PAK fixtures (tools/fixtures.py): PAK files written here from the Quake source's dpackheader_t / dpackfile_t
# layout (header, file data in order, directory at the end: the layout id's qpak and most tools write), in the Quake
# ("PACK", 56-byte names) and SiN ("SPAK", 120-byte names) variants, plus one with the directory first and padding
# between files; with the expected entries read back by an independent Python reader here.
# tests/gen/pak.luau { { name, variant, data, entries = { { name, size, crc } }, files = { { name, data } } } }
import struct, zlib
VARIANTS = {"quake": (b"PACK", 56), "sin": (b"SPAK", 120)}
def write(files, variant="quake", dir_first=False, pad=0):
magic, nl = VARIANTS[variant]
dirlen = len(files) * (nl + 8)
out = bytearray(magic + b"\0" * 8)
if dir_first:
dirofs = 12
out += b"\0" * dirlen
offs = []
for name, data in files:
out += b"\xee" * pad
offs.append(len(out))
out += data
if not dir_first:
dirofs = len(out)
out += b"\0" * dirlen
for i, (name, data) in enumerate(files):
struct.pack_into("<%dsII" % nl, out, dirofs + i * (nl + 8), name.encode(), offs[i], len(data))
struct.pack_into("<II", out, 4, dirofs, dirlen)
return bytes(out)
def read(data):
magic, dirofs, dirlen = struct.unpack_from("<4sII", data)
nl = {b"PACK": 56, b"SPAK": 120}[magic]
out = []
for i in range(dirlen // (nl + 8)):
name, at, n = struct.unpack_from("<%dsII" % nl, data, dirofs + i * (nl + 8))
out.append({"name": name.split(b"\0")[0].decode(), "size": n, "crc": zlib.crc32(data[at:at + n])})
return out
def generate(ctx):
rng = ctx.rng(17)
base = [
("gfx/palette.lmp", bytes(rng.randrange(256) for _ in range(768))),
("maps/start.bsp", rng.randbytes(5000)),
("sound/misc/null.wav", b""),
("progs/player.mdl", rng.randbytes(1234)),
("default.cfg", b"bind w +forward\n"),
("a" * 55, b"longest quake name"),
]
cases = [
("quake", "quake", write(base), base),
("quake-dir-first", "quake", write(base, dir_first=True, pad=3), base),
("empty", "quake", write([]), []),
("sin", "sin", write(base + [("models/" + "b" * 100 + ".def", b"sin")], "sin"), base + [("models/" + "b" * 100 + ".def", b"sin")]),
]
out = []
for name, variant, data, files in cases:
out.append({"name": name, "variant": variant, "data": data, "entries": read(data),
"layoutDefault": not name.endswith("dir-first"),
"files": [{"name": n, "data": d} for n, d in files]})
ctx.emit("pak", out)
+77
View File
@@ -0,0 +1,77 @@
# PMX / PMD fixtures (tools/fixtures.py): assimp's MMD test model (test/models-nonbsd/MMD/Alicia_blade.pmx, read from
# the nixpkgs assimp source, never committed) and synthetic models from tools/fixtures/_pmx_writer.py (PMX 2.0 / 2.1,
# UTF-16 / UTF-8, index sizes 1 / 2 / 4, additional UVs, every deform and morph type), with assimp's counts
# (`assimp info -r`: meshes, faces, vertices, materials, bones) and world bounds (assimp's PreTransformVertices
# export), plus the generator's own facts (vertex / bone / morph counts, sample vertices). The same synthetic models as
# PMD 1.0 (no reference reads PMD: the test compares them with the PMX decode).
# tests/gen/pmx_cases.luau { name, data, files = { name -> bytes }, assimp, expect? }
# tests/gen/pmx_pmd.luau { name, data, pmx (the case index of the same model) }
import importlib.util, os, struct, zlib
INPUTS = ["tools/fixtures/_pmx_writer.py", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def tiny_png():
raw = b"".join(b"\0" + bytes([200, 40, 40]) * 2 for _ in range(2))
def chunk(t, d):
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 2, 2, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
def generate(ctx):
M = load(ctx, "_model_ref")
Fbx = load(ctx, "fbx")
W = load(ctx, "_pmx_writer")
tmp = M.tempdir()
cases, pmds = [], []
src = os.path.join(Fbx.assimp_src(ctx), "test", "models-nonbsd", "MMD", "Alicia_blade.pmx")
if os.path.exists(src):
cases.append({"name": "assimp/Alicia_blade.pmx", "path": src, "files": {}})
variants = [
("small_utf16_i1.pmx", dict(version=2.0, utf8=False, sizes=(1, 1, 1, 1, 1, 1), uva=0), dict(rings=4, seg=6, nbones=3, nmat=2)),
("utf8_i2_uva2.pmx", dict(version=2.0, utf8=True, sizes=(2, 2, 2, 2, 2, 2), uva=2), dict(rings=12, seg=16, nbones=5, nmat=3)),
("v21_utf16_i4_uva4.pmx", dict(version=2.1, utf8=False, sizes=(4, 4, 4, 4, 4, 4), uva=4), dict(rings=30, seg=20, nbones=8, nmat=3)),
("v21_utf8_mixed.pmx", dict(version=2.1, utf8=True, sizes=(2, 1, 1, 2, 1, 1), uva=1), dict(rings=8, seg=10, nbones=4, nmat=3, deform=[4, 3, 1], flips=True)),
]
png = tiny_png()
for fname, wopts, topts in variants:
uva = wopts["uva"]
model = W.tube(version=wopts["version"], uva=uva, seed=len(cases), name=fname[:-4], **topts)
data = W.Pmx(**wopts).build(model)
path = os.path.join(tmp, fname)
with open(path, "wb") as f:
f.write(data)
vs = model["vertices"]
samples = []
for i in (0, 1, 2, 3, len(vs) - 1):
v = vs[i]
samples.append({"index": i, "pos": list(v["pos"]), "uv": list(v["uv"]), "deform": v["deform"], "bones": v["bones"], "weights": v["weights"]})
types = {}
for mo in model["morphs"]:
types[str(mo["type"])] = types.get(str(mo["type"]), 0) + 1
expect = {"vertices": len(vs), "bones": len(model["bones"]), "morphs": len(model["morphs"]), "morphTypes": types,
"textures": len(model["textures"]), "uva": uva, "samples": samples, "name": model["name"], "version": wopts["version"],
"rigid": len(model["rigid"]), "joints": len(model["joints"]), "frames": len(model["frames"])}
cases.append({"name": "gen/" + fname, "path": path, "files": {"tex/body.png": png}, "expect": expect})
if wopts["version"] == 2.0 and wopts["sizes"][0] <= 2:
pmds.append({"name": "gen/" + fname[:-4] + ".pmd", "data": W.pmd(model), "pmx": len(cases)})
infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True)
for c, a in zip(cases, infos):
a.update(Fbx.assimp_extra(ctx, c["path"]))
a.pop("min", None)
a.pop("max", None)
a.update(Fbx.ptv_bounds(ctx, c["path"], tmp))
if a.get("failed") and c.get("expect", {}).get("morphTypes", {}).get("9"):
a = {"skip": True} # flip / impulse morphs: assimp's MMD reader stops there
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("pmx_cases", cases)
ctx.emit("pmx_pmd", pmds)
+99
View File
@@ -0,0 +1,99 @@
# VRML97 fixtures (tools/fixtures.py): assimp's WRL test models (test/models/WRL, read from the nixpkgs assimp source,
# never committed; assimp itself is built without its VRML reader), scenes and glTF sample models written by VTK's
# vtkVRMLExporter, and the hand-written feature files of tools/fixtures/_vrml_ref.py, with VTK's vtkVRMLImporter as
# the reference (polygons, lines, world bounds). Then our encoder's output (tools/fixtures/_vrml_encode.luau) read back
# by VTK.
# tests/gen/vrml_cases.luau { name, data, files = { name -> bytes }, vtk, primitives (bool: tessellated shapes) }
# tests/gen/vrml_gltf.luau glTF sample models for the writer round trips: { name, data, files }
# tests/gen/vrml_xcheck.luau { name, case?, gltf?, vtk }
import importlib.util, os, re
INPUTS = ["src/Formats/codecs/model/Vrml", "src/Formats/model/vrml", "tests/fixtures/gltf", "tools/fixtures/_vrml_ref.py",
"tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", "tools/fixtures/_vrml_encode.luau"]
GLTF = ["Box", "BoxTextured", "BoxVertexColors", "Cameras", "MeshPrimitiveModes", "SimpleMeshes", "AnimatedTriangle", "InterpolationTest",
"NegativeScaleTest", "TextureCoordinateTest", "MultiUVTest"]
def load(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def primitives(data):
return bool(re.search(rb"\b(Box|Sphere|Cone|Cylinder|Extrusion|ElevationGrid|Text)\s*\{|<(Box|Sphere|Cone|Cylinder|Extrusion|ElevationGrid|Text)\b", data))
def gltf_picks(ctx):
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
picks = []
for model in GLTF:
d0 = os.path.join(gl, model)
if not os.path.isdir(d0):
continue
for variant in ("glTF", "glTF-Embedded", "glTF-Binary"):
d = os.path.join(d0, 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 mains:
picks.append({"name": model + "/" + variant, "path": os.path.join(d, mains[0]), "data": open(os.path.join(d, mains[0]), "rb").read(),
"files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}})
break
return picks
def generate(ctx):
M = load(ctx, "_model_ref")
Fbx = load(ctx, "fbx")
R = load(ctx, "_vrml_ref")
tmp = M.tempdir()
cases = []
src = os.path.join(Fbx.assimp_src(ctx), "test", "models", "WRL")
for f in sorted(os.listdir(src)):
if f.lower().endswith(".wrl"):
files = {}
if f == "HelloWorld.wrl":
files["earth-topo.png"] = open(os.path.join(src, "earth-topo.png"), "rb").read()
cases.append({"name": "assimp/" + f, "path": os.path.join(src, f), "files": files})
picks = gltf_picks(ctx)
for name in R.vtk_export(ctx, tmp, [p["path"] for p in picks if p["path"].endswith((".gltf", ".glb"))]):
cases.append({"name": "vtk/" + name + ".wrl", "path": os.path.join(tmp, name + ".wrl"), "files": {}})
for name, text in sorted(R.FEATURES.items()):
p = os.path.join(tmp, name)
with open(p, "w") as f:
f.write(text)
cases.append({"name": "feature/" + name, "path": p, "files": dict(R.INLINE)})
for name, text in R.INLINE.items():
with open(os.path.join(tmp, name), "w") as f:
f.write(text)
refs = R.vtk_read(ctx, [c["path"] for c in cases])
for c, v in zip(cases, refs):
c["data"] = open(c["path"], "rb").read()
c["vtk"] = v
c["primitives"] = primitives(c["data"])
c["vtkTransforms"] = R.vtk_xform_ok(c["data"])
del c["path"]
ctx.emit("vrml_cases", cases)
for p in picks:
del p["path"]
ctx.emit("vrml_gltf", picks)
# VTK reads our output
ours = M.luau_encode(ctx, "tools/fixtures/_vrml_encode.luau")
xtmp = M.tempdir()
names = sorted(n for n in ours if n.endswith(".wrl"))
for name, data in ours.items():
with open(os.path.join(xtmp, name), "wb") as f:
f.write(data)
refs = R.vtk_read(ctx, [os.path.join(xtmp, n) for n in names])
out = []
for n, v in zip(names, refs):
e = {"name": n, "vtk": v, "vtkTransforms": R.vtk_xform_ok(ours[n])}
m = re.match(r"(case|gltf)_(\d+)\.wrl$", n)
if m:
e[m.group(1)] = int(m.group(2))
out.append(e)
ctx.emit("vrml_xcheck", out)
+126
View File
@@ -0,0 +1,126 @@
# DirectX .x fixtures (tools/fixtures.py): assimp's X test models (text, binary 32-bit, MSZIP-compressed binary;
# models and models-nonbsd, read from the nixpkgs assimp source, never committed), plus variants made here from the
# text ones: binary with 64-bit floats ("bin 0064") and MSZIP-compressed text ("tzip", per-block raw deflate with
# the previous block as dictionary, as D3DX writes). Reference: assimp (`assimp info -r`: meshes, faces, corners,
# materials, nodes, animations, bones; world bounds from its PreTransformVertices export), on the variants too.
# tests/gen/x_cases.luau { name, data, assimp = { ... } }
import importlib.util, os, re, struct, zlib
INPUTS = ["src/Formats/model/x", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"]
def module(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
TOKEN = re.compile(rb'\s+|//[^\n]*|#[^\n]*|"[^"]*"|<[^>]*>|[{}]|[;,]|[^\s;,{}"]+')
def to_binary64(text):
"""a text .x file -> binary tokens with 64-bit floats (templates dropped; numbers with . or e are floats)"""
body = text[16:]
out = bytearray(b"xof 0303bin 0064")
toks = [t for t in TOKEN.findall(body) if t.strip() and not t.startswith((b"//", b"#"))]
i, nums = 0, []
def flush():
while nums:
isf = nums[0][0]
run = []
while nums and nums[0][0] == isf:
run.append(nums.pop(0)[1])
if isf:
out.extend(struct.pack("<HI", 7, len(run)) + b"".join(struct.pack("<d", v) for v in run))
else:
out.extend(struct.pack("<HI", 6, len(run)) + b"".join(struct.pack("<I", int(v) & 0xFFFFFFFF) for v in run))
while i < len(toks):
t = toks[i]
if t == b"template":
flush()
depth = 0
while i < len(toks):
if toks[i] == b"{":
depth += 1
elif toks[i] == b"}":
depth -= 1
if depth == 0:
break
i += 1
elif t in (b";", b","):
pass
elif t[:1] in b"0123456789-+.":
try:
v = float(t)
except ValueError:
v = 0.0
nums.append((b"." in t or b"e" in t.lower() or b"#" in t, v))
else:
flush()
if t == b"{":
out.extend(struct.pack("<H", 0x0A))
elif t == b"}":
out.extend(struct.pack("<H", 0x0B))
elif t.startswith(b'"'):
s = t[1:-1]
out.extend(struct.pack("<HI", 2, len(s)) + s + struct.pack("<H", 0x14))
elif t.startswith(b"<"):
pass
else:
out.extend(struct.pack("<HI", 1, len(t)) + t)
i += 1
flush()
return bytes(out)
def to_tzip(text):
"""a text .x file -> "tzip": MSZIP blocks of 32 KiB, each raw deflate with the previous block as dictionary"""
body = text[16:]
out = bytearray(b"xof 0303tzip0032") + struct.pack("<I", 0)
data = body
prev = b""
for p in range(0, len(data), 32768):
blk = data[p:p + 32768]
c = zlib.compressobj(9, zlib.DEFLATED, -15, zdict=prev) if prev else zlib.compressobj(9, zlib.DEFLATED, -15)
z = c.compress(blk) + c.flush(zlib.Z_FINISH)
out.extend(struct.pack("<HH", len(blk), len(z) + 2) + b"CK" + z)
prev = blk
struct.pack_into("<I", out, 16, len(data) + 16) # the size counts the 16-byte header (D3DX)
return bytes(out)
def generate(ctx):
M = module(ctx, "_model_ref")
fbx = module(ctx, "fbx")
tmp = M.tempdir()
src = fbx.assimp_src(ctx)
cases = []
for sub in ("models/X", "models-nonbsd/X"):
d0 = os.path.join(src, "test", sub)
for f in sorted(os.listdir(d0)):
p = os.path.join(d0, f)
if os.path.isfile(p) and open(p, "rb").read(4) == b"xof ":
cases.append({"name": sub.split("/")[0] + "/" + f, "path": p})
# variants of the small text files: binary 64-bit floats and tzip
for name in ("test_cube_text.x", "kwxport_test_cubewithvcolors.x", "test.x", "anim_test.x"):
p = os.path.join(src, "test", "models", "X", name)
text = open(p, "rb").read()
for kind, data in (("bin64", to_binary64(text)), ("tzip", to_tzip(text))):
q = os.path.join(tmp, "%s.%s.x" % (name[:-2], kind))
open(q, "wb").write(data)
cases.append({"name": "variant/%s.%s.x" % (name[:-2], kind), "path": q, "of": "models/" + name})
infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True)
for c, a in zip(cases, infos):
a.pop("min", None)
a.pop("max", None)
a.pop("perMesh", None)
if not a.get("failed"):
a.update(fbx.assimp_extra(ctx, c["path"]))
a.update(fbx.ptv_bounds(ctx, c["path"], tmp))
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("x_cases", cases)
+135
View File
@@ -0,0 +1,135 @@
# X3D fixtures (tools/fixtures.py): assimp's X3D / X3DV / X3DB test models (test/models/X3D*, read from the nixpkgs
# assimp source, never committed), scenes and glTF sample models written by VTK's vtkX3DExporter, glTF sample models
# written by assimp's X3D exporter, and hand-written feature files (below), with assimp's X3D reader as the reference
# (`assimp info -r`: meshes, faces, materials; world bounds from its PreTransformVertices export). Then our encoder's
# X3D output (tools/fixtures/_vrml_encode.luau) read back by assimp.
# tests/gen/x3d_cases.luau { name, data, files = { name -> bytes }, assimp, primitives (bool) }
# tests/gen/x3d_xcheck.luau { name, case? / gltf? / wcase?, assimp }
import importlib.util, os, re, subprocess
INPUTS = ["src/Formats/codecs/model/Vrml", "src/Formats/model/x3d", "src/Formats/model/vrml", "tests/fixtures/gltf",
"tools/fixtures/_vrml_ref.py", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", "tools/fixtures/vrml.py",
"tools/fixtures/_vrml_encode.luau"]
FEATURES = {
"feat_sets.x3d": """<?xml version="1.0" encoding="UTF-8"?>
<X3D profile="Interchange" version="3.3"><Scene>
<Transform translation="0 0 0"><Shape><Appearance><Material diffuseColor="1 0 0"/></Appearance>
<IndexedTriangleSet index="0 1 2 0 2 3" solid="false"><Coordinate point="0 0 0 1 0 0 1 1 0 0 1 0"/>
<ColorRGBA color="1 0 0 1 0 1 0 1 0 0 1 0.5 1 1 1 1"/></IndexedTriangleSet></Shape></Transform>
<Transform translation="2 0 0"><Shape><TriangleFanSet fanCount="5"><Coordinate point="0 0 0 1 0 0 1 1 0 0 1 0 -1 1 0"/></TriangleFanSet></Shape></Transform>
<Transform translation="4 0 0"><Shape><IndexedTriangleStripSet index="0 1 2 3 -1 4 5 6"><Coordinate point="0 0 0 1 0 0 0 1 0 1 1 0 0 2 0 1 2 0 0 3 0"/></IndexedTriangleStripSet></Shape></Transform>
<Transform translation="6 0 0"><Shape><IndexedQuadSet index="0 1 2 3"><Coordinate point="0 0 0 1 0 0 1 1 0 0 1 0"/></IndexedQuadSet></Shape></Transform>
<Transform translation="8 0 0"><Shape><TriangleSet><Coordinate point="0 0 0 1 0 0 0 1 0 0 0 1 1 0 1 0 1 1"/></TriangleSet></Shape></Transform>
<Transform translation="0 3 0"><Shape><LineSet vertexCount="3 2"><Coordinate point="0 0 0 1 0 0 1 1 0 2 2 2 3 3 3"/></LineSet></Shape></Transform>
</Scene></X3D>
""",
"feat_proto.x3d": """<?xml version="1.0" encoding="UTF-8"?>
<X3D profile="Immersive" version="3.3"><head><meta name="title" content="protos"/><unit category="length" name="centimetre" conversionFactor="0.01"/></head>
<Scene>
<ProtoDeclare name="Post"><ProtoInterface>
<field name="height" type="SFFloat" accessType="initializeOnly" value="2"/>
<field name="where" type="SFVec3f" accessType="inputOutput" value="0 0 0"/>
<field name="look" type="SFNode" accessType="inputOutput"><Appearance><Material diffuseColor="0 0 1"/></Appearance></field>
</ProtoInterface>
<ProtoBody><Transform><IS><connect nodeField="translation" protoField="where"/></IS>
<Shape><IS><connect nodeField="appearance" protoField="look"/></IS>
<Cylinder radius="0.1"><IS><connect nodeField="height" protoField="height"/></IS></Cylinder></Shape></Transform></ProtoBody>
</ProtoDeclare>
<ProtoInstance name="Post" DEF="P1"><fieldValue name="where" value="1 0 0"/></ProtoInstance>
<ProtoInstance name="Post"><fieldValue name="where" value="-1 0 0"/><fieldValue name="height" value="4"/></ProtoInstance>
<Transform DEF="Spin"><Shape><Appearance><PhysicalMaterial baseColor="0.5 0.5 0.5" metallic="0.25" roughness="0.75"/></Appearance>
<Box size="1 1 1"/></Shape></Transform>
<TimeSensor DEF="Clock" cycleInterval="2" loop="true"/>
<OrientationInterpolator DEF="Rot" key="0 0.5 1" keyValue="0 1 0 0 0 1 0 3.14159 0 1 0 6.28318"/>
<ROUTE fromNode="Clock" fromField="fraction_changed" toNode="Rot" toField="set_fraction"/>
<ROUTE fromNode="Rot" fromField="value_changed" toNode="Spin" toField="set_rotation"/>
<OrthoViewpoint fieldOfView="-2 -1 2 1" position="0 0 5"/>
<Shape><Appearance><UnlitMaterial emissiveColor="0 1 0"/></Appearance><PointSet><Coordinate point="0 5 0 1 5 0"/><Color color="1 0 0 0 1 0"/></PointSet></Shape>
</Scene></X3D>
""",
"feat_classic.x3dv": """#X3D V3.3 utf8
PROFILE Interchange
COMPONENT Geometry2D:1
META "title" "classic"
UNIT length millimetre 0.001
DEF Root Transform { translation 1 2 3 children [
Shape { appearance Appearance { material Material { diffuseColor 0 1 0 } }
geometry IndexedFaceSet { coord Coordinate { point [ 0 0 0 1 0 0 1 1 0 0 1 0 ] } coordIndex [ 0 1 2 3 -1 ]
color ColorRGBA { color [ 1 0 0 1, 0 1 0 1, 0 0 1 1, 1 1 1 0.5 ] } } }
Shape { geometry IndexedTriangleSet { index [ 0 1 2 ] coord Coordinate { point [ 0 0 1 1 0 1 0 1 1 ] } } }
] }
""",
}
def load(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def reference(ctx, M, Fbx, path, tmp):
a = M.assimp_info(ctx, [path], raw=True)[0]
if not a.get("failed"):
a.pop("min", None)
a.pop("max", None)
a.update(Fbx.assimp_extra(ctx, path))
a.update(Fbx.ptv_bounds(ctx, path, tmp))
return a
def generate(ctx):
M = load(ctx, "_model_ref")
Fbx = load(ctx, "fbx")
R = load(ctx, "_vrml_ref")
V = load(ctx, "vrml")
tmp = M.tempdir()
cases = []
root = os.path.join(Fbx.assimp_src(ctx), "test", "models")
for sub in ("X3D", "X3DV", "X3DB"):
d = os.path.join(root, sub)
for f in sorted(os.listdir(d)):
if f.lower().endswith((".x3d", ".x3dv", ".x3db")):
files = {}
if f.startswith("HelloWorld"):
files["earth-topo.png"] = open(os.path.join(d, "earth-topo.png"), "rb").read()
cases.append({"name": "assimp/%s/%s" % (sub, f), "path": os.path.join(d, f), "files": files})
picks = V.gltf_picks(ctx)
for name in R.vtk_export(ctx, tmp, [p["path"] for p in picks]):
cases.append({"name": "vtk/" + name + ".x3d", "path": os.path.join(tmp, name + ".x3d"), "files": {}})
for p in picks:
out = os.path.join(tmp, "assimp_" + p["name"].split("/")[0] + ".x3d")
try:
ctx.nix("assimp", ["assimp", "export", p["path"], out, "-fx3d"])
except subprocess.CalledProcessError:
continue
cases.append({"name": "assimp-export/" + os.path.basename(out), "path": out, "files": dict(p["files"])})
for name, text in sorted(FEATURES.items()):
path = os.path.join(tmp, name)
with open(path, "w") as f:
f.write(text)
cases.append({"name": "feature/" + name, "path": path, "files": {}})
for c in cases:
c["data"] = open(c["path"], "rb").read()
c["primitives"] = V.primitives(c["data"])
c["assimp"] = reference(ctx, M, Fbx, c["path"], tmp) if c["path"].endswith(".x3d") else {"skip": True}
del c["path"]
ctx.emit("x3d_cases", cases)
# assimp reads our X3D output
ours = M.luau_encode(ctx, "tools/fixtures/_vrml_encode.luau")
xtmp = M.tempdir()
out = []
for name in sorted(n for n in ours if n.endswith(".x3d")):
path = os.path.join(xtmp, name)
with open(path, "wb") as f:
# assimp 6 cannot read quoted MFString urls (url='"a.png"', which the X3D encoding requires)
f.write(re.sub(rb'url="&quot;([^&"]*)&quot;"', rb'url="\1"', ours[name]))
e = {"name": name, "assimp": reference(ctx, M, Fbx, path, xtmp)}
m = re.match(r"(xcase|xgltf|wcase)_(\d+)\.x3d$", name)
if m:
e[m.group(1)] = int(m.group(2))
out.append(e)
ctx.emit("x3d_xcheck", out)