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

+87
View File
@@ -0,0 +1,87 @@
-- archive/pak tests: Quake ("PACK") and SiN ("SPAK") archives written by tools/fixtures/pak.py list the entries an
-- independent Python reader sees (names, sizes, data CRCs); our writer produces the same bytes as the Python writer
-- for the same files and round-trips; conversion from a tar; errors; the fuzz pass. Fixtures: tools/fixtures/pak.py.
local T = require("@tests/T")
local F = require("@formats")
local Pak = require("@formats/archive/pak")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/pak")
local t = T.suite("pak")
t:eq(Pak.name, "pak", "name")
t:check(Pak.caps.decode and Pak.caps.encode, "caps")
for _, c in Fx do
local a, err = Pak.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(a, c.name .. ": " .. tostring(err))
local list = a:list()
t:eq(#list, #c.entries, c.name .. ": entry count")
for i, w in c.entries do
t:eq(list[i].name, w.name, c.name .. ": name " .. i)
t:eq(list[i].size, w.size, c.name .. ": size " .. w.name)
t:eq(Crc32.of((a:read(w.name))), w.crc, c.name .. ": data " .. w.name)
end
t:eq(a.meta.source.variant, c.variant, c.name .. ": variant")
if #c.data > 12 then
t:eq(F.detect(c.data), "pak", c.name .. ": F.detect")
end
-- the writer: same layout as the Python writer
local n = Pak.new(c.variant)
for _, f in c.files do
n:add(f.name, f.data)
end
local out = n:write() :: buffer
if c.layoutDefault then
t:check(buffer.tostring(out) == c.data, c.name .. ": bytes identical to the Python writer")
end
local back = Pak.decode(Bytes.reader(out))
t:eq(#back:list(), #c.files, c.name .. ": round trip count")
-- rewriting a decoded archive keeps its variant
local again = F.save(a) :: buffer
t:eq(buffer.readstring(again, 0, 4), if c.variant == "sin" then "SPAK" else "PACK", c.name .. ": F.save keeps the variant")
end
-- a sub-range reader, conversion from another archive, errors
do
local c = Fx[1]
local big = buffer.create(#c.data + 7)
buffer.writestring(big, 7, c.data)
local a = Pak.decode(Bytes.reader(big, 7, #c.data))
t:check(a and Crc32.of((a:read(c.entries[2].name))) == c.entries[2].crc, "decode from a sub-range")
local tar = F.format("tar").new()
tar:add("dir/", "", { dir = true })
tar:add("dir/x.txt", "x")
local p = F.load(F.save(tar, nil, { format = "pak" }) :: buffer)
t:check(p.format == "pak" and #p:list() == 1 and buffer.tostring(p:read("dir/x.txt")) == "x", "tar -> pak (directories dropped)")
local _, e1 = Pak.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, #c.data - 10))))
t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1))
local bad = buffer.fromstring(c.data)
buffer.writeu32(bad, 8, 65)
local _, e2 = Pak.decode(Bytes.reader(bad))
t:check(e2 and e2.code == Err.CORRUPT, "directory size: " .. tostring(e2))
local long = Pak.new()
long:add(string.rep("n", 56), "x")
local _, e3 = long:write()
t:check(e3 and e3.code == Err.ARG, "a 56-byte name does not fit")
local _, e4 = Pak.encode({ kind = "image" })
t:check(e4 and e4.code == Err.ARG, "encode a non-archive")
end
local samples = {}
for _, c in Fx do
table.insert(samples, c.data)
end
t:fuzz("decode", function(b: buffer)
local a = Pak.decode(Bytes.reader(b))
if a then
for _, e in a:list() do
a:read(e.name)
end
a:write()
end
return a
end, samples, { mutations = 40 })
t:done()
+81
View File
@@ -0,0 +1,81 @@
-- codecs/model/Draco tests: Google's Draco test data (bitstreams 0.9 - 2.2) and files encoded by draco_encoder 1.5.7
-- at every compression level, quantization and as point clouds, decoded and compared byte for byte (points, faces,
-- every attribute's values per point, as CRCs) with libdraco's own decoder (tools/fixtures/_draco_dump.cc), kd-tree
-- point clouds included; argument errors; the fuzz no-throw pass (which also fails on any internal error the
-- decoder's safety net caught). Fixtures: tools/fixtures/draco.py.
local T = require("@tests/T")
local Draco = require("@formats/codecs/model/Draco")
local Err = require("@formats/core/Err")
local Crc32 = require("@formats/core/Crc32")
local Cases = require("@tests/gen/draco_cases")
local t = T.suite("draco")
local counts = { exact = 0, rejected = 0, kd = 0 }
local samples = {}
for _, c in Cases do
local g, err = Draco.decode(c.data)
if c.error then
t:check(g == nil and err ~= nil, c.name .. ": libdraco rejects it, so do we")
counts.rejected += 1
else
t:check(g, c.name .. ": decode: " .. tostring(err))
if g then
t:eq(g.numPoints, c.points, c.name .. ": points")
if c.faces then
t:eq(g.numFaces, c.faces, c.name .. ": faces")
t:eq(Crc32.of(g.indices :: buffer), c.indices, c.name .. ": indices")
end
t:eq(#g.attributes, #c.attrs, c.name .. ": attribute count")
for i, want in c.attrs do
local a = g.attributes[i]
if a then
t:eq(a.typeId, want.type, c.name .. ": attribute " .. i .. " type")
t:eq(a.type, Draco.DATA_TYPES[want.dataType], c.name .. ": attribute " .. i .. " data type")
t:eq(a.components, want.components, c.name .. ": attribute " .. i .. " components")
t:eq(a.normalized, want.normalized, c.name .. ": attribute " .. i .. " normalized")
t:eq(a.uniqueId, want.uniqueId, c.name .. ": attribute " .. i .. " unique id")
t:eq(Crc32.of(a.data), want.crc, c.name .. ": attribute " .. i .. " (" .. a.name .. ") values")
end
end
counts.exact += 1
if g.method == "kdtree" then
counts.kd += 1
end
if #c.data < 4000 then
table.insert(samples, c.data)
end
end
end
end
t:note("%d files decoded exactly like libdraco (%d kd-tree point clouds), %d rejected by both", counts.exact, counts.kd, counts.rejected)
-- the attribute lookup and the header
local first = Cases[1]
local info = Draco.info(first.data)
t:check(info and (info.kind == "mesh" or info.kind == "points"), "info")
t:check(Draco.sniff(buffer.fromstring(first.data)), "sniff")
t:check(not Draco.sniff(buffer.fromstring("DRAC")), "sniff short")
-- errors
local _, e1 = Draco.decode(buffer.fromstring("NOTDRACO......"))
t:check(e1 and e1.code == Err.CORRUPT, "not Draco data: " .. tostring(e1))
local _, e2 = Draco.decode(buffer.fromstring("DRACO\9\0\1\1\0\0"))
t:check(e2 and e2.code == Err.UNSUPPORTED, "future version: " .. tostring(e2))
local _, e3 = Draco.decode(42 :: any)
t:check(e3 and e3.code == Err.ARG, "bad argument")
-- fuzz: never throws, and the internal safety net never fires
local internal = 0
t:fuzz("decode", function(b: buffer)
local g, err = Draco.decode(b)
if not g and err and string.find(err.message, "internal error", 1, true) then
internal += 1
if internal <= 5 then
print(" internal error: " .. err.message)
end
end
return g
end, samples, { mutations = 12, keepHeader = 11 })
t:eq(internal, 0, "fuzz: internal errors")
t:done()
+93
View File
@@ -0,0 +1,93 @@
-- codecs/model/Rig tests: morph targets and weights animations from frames, skeletons in local and world space
-- (node TRS, inverse bind matrices against Mat4), influences (top four, normalised), joint TRS animations; and
-- Pixels.palette.
local T = require("@tests/T")
local Rig = require("@formats/codecs/model/Rig")
local Mat4 = require("@formats/codecs/model/Mat4")
local Pixels = require("@formats/codecs/image/Pixels")
local Types = require("@formats/Types")
local t = T.suite("codecs/rig")
local Scene = Types.Scene
local function f32s(list: { number }): buffer
local b = buffer.create(#list * 4)
for i, v in list do
buffer.writef32(b, (i - 1) * 4, v)
end
return b
end
local function near(a: number, b: number): boolean
return math.abs(a - b) < 1e-5
end
-- morph
do
local base = { 0, 0, 0, 1, 0, 0 }
local prim: Types.Primitive = { attributes = { POSITION = Scene.accessor(f32s(base), "f32", 3, 2) }, mode = "points" }
local frames = { f32s(base), f32s({ 0, 1, 0, 1, 2, 0 }), f32s({ 0, 0, 3, 1, 0, 3 }) }
t:check(Rig.morph(prim, frames), "morph")
local tg = prim.targets :: any
t:eq(#tg, 3, "one target per frame")
t:eq(buffer.readf32(tg[2].POSITION.data, 4), 1, "delta y")
t:eq(buffer.readf32(tg[3].POSITION.data, 20), 3, "delta z")
t:check(not Rig.morph(prim, { buffer.create(4) }), "short frame refused")
local s = Scene.new()
s.nodes[1] = { children = {}, mesh = 1 }
Rig.morphAnimation(s, 1, 3, { { name = "a", first = 2, last = 3, fps = 5 }, { name = "none", first = 9, last = 12 } })
t:eq(#s.animations, 1, "out-of-range range skipped")
local ch = s.animations[1].channels[1]
t:eq(ch.path, "weights", "weights channel")
t:eq(ch.input.count, 2, "two keys")
t:check(near(buffer.readf32(ch.input.data, 4), 0.2), "fps")
t:eq(buffer.readf32(ch.output.data, 1 * 4), 1, "key 1 -> target 2")
t:eq(buffer.readf32(ch.output.data, (3 + 2) * 4), 1, "key 2 -> target 3")
end
-- skeleton
do
local q = Mat4.axisAngle(0, 0, 1, 90)
local joints = {
{ name = "root", parent = 0, translation = { 1, 0, 0 }, rotation = q },
{ name = "child", parent = 1, translation = { 0, 2, 0 }, rotation = { 0, 0, 0, 1 } },
}
local s = Scene.new()
local nodes, skin = Rig.skeleton(s, joints, "local")
t:eq(#nodes, 2, "two joint nodes")
t:eq(s.roots[1], nodes[1], "root")
t:eq(s.nodes[nodes[1]].children[1], nodes[2], "parenting")
local ibm = s.skins[skin].inverseBindMatrices :: Types.Accessor
-- child world = T(1,0,0) R90 T(0,2,0): its origin is at (-1, 0, 0); the inverse maps it back to 0
local inv = {}
for k = 1, 16 do
inv[k] = buffer.readf32(ibm.data, (16 + k - 1) * 4)
end
local x, y, z = Mat4.point(inv, -1, 0, 0)
t:check(near(x, 0) and near(y, 0) and near(z, 0), "inverse bind matrix")
-- the same joints given in world space give the same local TRS
local w = Scene.new()
local wn = Rig.skeleton(w, {
joints[1],
{ name = "child", parent = 1, translation = { -1, 0, 0 }, rotation = q },
}, "world")
local c = w.nodes[wn[2]]
t:check(near(c.translation[1], 0) and near(c.translation[2], 2) and near(c.rotation[4], 1), "world -> local")
local j, wt = Rig.influences({ { 0, 1 }, { 1, 0.2, 2, 0.6, 3, 0.1, 4, 0.05, 5, 0.05 } })
t:eq(buffer.readu16(j.data, 8), 2, "largest weight first")
t:check(near(buffer.readf32(wt.data, 16) + buffer.readf32(wt.data, 20) + buffer.readf32(wt.data, 24) + buffer.readf32(wt.data, 28), 1), "normalised")
t:eq(buffer.readf32(wt.data, 0), 1, "single influence")
local ai = Rig.animation(s, "wave", nodes, { 0, 0.5 }, { [2] = { rotation = { 0, 0, 0, 1, 0, 0, 1, 0 }, translation = { 0 } } })
t:eq(#s.animations[ai].channels, 1, "short track skipped, rotation kept")
t:eq(s.animations[ai].channels[1].node, nodes[2], "channel node")
end
-- palette
do
local pal = Pixels.palette(buffer.fromstring("\1\2\3\4\5\6"), 0, 2)
t:eq(buffer.readu32(pal, 4), 0xFF060504, "rgb triples")
t:eq(buffer.readu32(pal, 8), 0xFF000000, "missing entries black")
t:eq(buffer.readu32(Pixels.palette(buffer.fromstring("\1\2\3"), 0, 1, true), 0), 0xFF010203, "bgr")
t:eq(buffer.readu32(Pixels.palette(buffer.create(3), -5, 1), 0), 0xFF000000, "bad base")
end
t:done()
+92
View File
@@ -0,0 +1,92 @@
-- codecs/model/Sampler tests: STEP / LINEAR / CUBICSPLINE channels (glTF's Hermite definition), quaternion slerp
-- (shortest path, unit length), clamping outside the keys, weights channels, Sampler.times and Sampler.pose; glTF's
-- InterpolationTest sample model (every interpolation) sampled at its keys gives the key values; bad channels.
local T = require("@tests/T")
local Sampler = require("@formats/codecs/model/Sampler")
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Picks = require("@tests/gen/iqm_gltf")
local t = T.suite("codecs/sampler")
local S = Types.Scene
local function acc(list: { number }, comps: number): Types.Accessor
local b = buffer.create(#list * 4)
for i, v in list do
buffer.writef32(b, (i - 1) * 4, v)
end
return S.accessor(b, "f32", comps, #list // comps)
end
local function near(a: number, b: number, eps: number?): boolean
return math.abs(a - b) < (eps or 1e-5)
end
do
local ch: Types.Channel = { node = 1, path = "translation", input = acc({ 0, 1, 3 }, 1), output = acc({ 0, 0, 0, 2, 4, 6, 2, 0, 0 }, 3), interpolation = "LINEAR" }
local s = assert(Sampler.channel(ch))
t:check(near(s(0.5)[1], 1) and near(s(0.5)[2], 2), "linear: halfway")
t:check(near(s(2)[1], 2) and near(s(2)[2], 2), "linear: second span")
t:check(near(s(-1)[2], 0) and near(s(9)[1], 2), "linear: clamped outside the keys")
ch.interpolation = "STEP"
local st = assert(Sampler.channel(ch))
t:check(near(st(0.99)[1], 0) and near(st(1)[1], 2), "step")
end
do
-- rotation: 0 -> 90 degrees about z, and a key stored with the opposite sign (shortest path)
local h = math.sqrt(0.5)
local ch: Types.Channel = { node = 1, path = "rotation", input = acc({ 0, 1, 2 }, 1), output = acc({ 0, 0, 0, 1, 0, 0, h, h, 0, 0, -h, -h }, 4), interpolation = "LINEAR" }
local s = assert(Sampler.channel(ch))
local q = s(0.5)
local a = 2 * math.acos(q[4])
t:check(near(a, math.pi / 4, 1e-4) and near(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2, 1), "slerp: 45 degrees, unit length")
local q2 = s(1.5)
t:check(near(math.abs(q2[3]), h, 1e-4), "slerp: the same orientation stored negated stays put")
end
do
-- cubic spline: in-tangent, value, out-tangent per key; p(t) for p0 = 0, p1 = 1, m0 = m1 = 0 is smoothstep
local ch: Types.Channel = { node = 1, path = "scale", input = acc({ 0, 2 }, 1), output = acc({ 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 9, 9, 9 }, 3), interpolation = "CUBICSPLINE" }
local s = assert(Sampler.channel(ch))
t:check(near(s(1)[1], 0.5) and near(s(0.5)[1], 3 * 0.25 ^ 2 - 2 * 0.25 ^ 3), "cubic: smoothstep")
t:check(near(s(2)[2], 1), "cubic: the last value")
-- tangents scale with the key spacing
local ch2: Types.Channel = { node = 1, path = "translation", input = acc({ 0, 2 }, 1), output = acc({ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 3), interpolation = "CUBICSPLINE" }
local s2 = assert(Sampler.channel(ch2))
-- h10(0.5) * dt * m0 = 0.125 * 2 * 1
t:check(near(s2(1)[1], 0.25), "cubic: tangents times the key spacing")
end
do
local ch: Types.Channel = { node = 2, path = "weights", input = acc({ 0, 1 }, 1), output = acc({ 1, 0, 0, 1 }, 1), interpolation = "LINEAR" }
local s = assert(Sampler.channel(ch))
local w = s(0.25)
t:check(#w == 2 and near(w[1], 0.75) and near(w[2], 0.25), "weights")
local anim: Types.Animation = { name = "a", channels = { ch, { node = 1, path = "translation", input = acc({ 0.5, 1 }, 1), output = acc({ 0, 0, 0, 1, 1, 1 }, 3), interpolation = "STEP" } } }
local times = Sampler.times(anim)
t:eq(table.concat(times, " "), "0 0.5 1", "times: sorted, unique")
local pose = Sampler.pose(S.new(), anim, 1)
t:check(pose[2].weights and pose[1].translation and near(pose[1].translation[1], 1), "pose")
t:check(Sampler.channel({ node = 1, path = "translation", input = acc({ 0, 1 }, 1), output = acc({ 1, 2 }, 1), interpolation = "LINEAR" }) == nil, "short output: nil")
t:check(Sampler.channel({ node = 1, path = "translation", input = {} :: any, output = {} :: any, interpolation = "LINEAR" }) == nil, "junk: nil")
end
do
-- a real file: sampling a glTF sample model's skin animation at its own keys returns the key values
local g = assert(Gltf.decode(Bytes.reader(buffer.fromstring(Picks[1].data)), { files = Picks[1].files }))
local ok, total = true, 0
for _, anim in g.animations do
for _, ch in anim.channels do
local s = assert(Sampler.channel(ch))
local IN, OUT = assert(S.reader(ch.input)), assert(S.reader(ch.output))
local comps = if ch.path == "rotation" then 4 else 3
for k = 0, ch.input.count - 1 do
local v = s(IN(k, 0))
for c = 1, comps do
ok = ok and near(v[c], OUT(k, c - 1), 1e-4)
end
total += 1
end
end
end
t:check(ok and total > 0, Picks[1].name .. ": samples at the keys are the keys (" .. total .. ")")
end
t:done()
+148
View File
@@ -0,0 +1,148 @@
-- codecs/model/Vrml tests: the classic-encoding lexer and parser (comments, commas, string escapes, hex / exponent
-- numbers, DEF / USE, PROTO with IS fields, nested PROTOs and ROUTEs in bodies, EXTERNPROTO, Script interfaces,
-- IMPORT / EXPORT, the X3D header statements), the XML encoding's adapter (containerField, ProtoDeclare /
-- ProtoInstance, IS / connect), typed field reads of raw XML attributes, detection, errors, the fuzz pass.
local T = require("@tests/T")
local Vrml = require("@formats/codecs/model/Vrml")
local Fields = require("@formats/codecs/model/Vrml/Fields")
local Err = require("@formats/core/Err")
local t = T.suite("vrml codec")
-- ------------------------------------------------------------------------------------------------ lexer / parser
do
local g = assert(Vrml.parse([[#VRML V2.0 utf8
# a comment, then commas as blanks
DEF A Transform { translation 1,2,3 # trailing comment
children [ Shape { geometry IndexedFaceSet { coordIndex [ 0, 1, 2, -1 ] coord Coordinate { point [ 0 0 0, 1e1 0 0, .5 -2.5E-1 +3 ] } } } ] }
WorldInfo { title "say \"hi\" \\ there" info [ "a" "b" ] }
DEF P PixelTexture { image 1 1 4 0xFF8000FF }
USE A
]]))
t:eq(#g.roots, 4, "statements")
t:eq(g.header.version, "2.0", "header")
local a = g.roots[1]
t:eq(a.def, "A", "DEF")
t:eq(table.concat(Fields.vec(a, "translation", { 0, 0, 0 }), " "), "1 2 3", "commas are blanks")
local coord = Fields.node(Fields.node(Fields.nodes(a, "children")[1], "geometry"), "coord")
t:eq(table.concat(Fields.nums(coord, "point") :: { number }, " "), "0 0 0 10 0 0 0.5 -0.25 3", "exponents, leading dot, plus sign")
t:eq(Fields.str(g.roots[2], "title"), 'say "hi" \\ there', "string escapes")
t:eq(#Fields.strs(g.roots[2], "info"), 2, "MFString")
t:eq((Fields.nums(g.roots[3], "image") :: { number })[4], 0xFF8000FF, "hex numbers")
t:check(g.roots[4] == a, "USE is the same node")
end
do
local g = assert(Vrml.parse([[#VRML V2.0 utf8
PROTO Outer [ field SFFloat size 1 exposedField SFColor tint 1 1 1 eventIn SFBool flip ] {
PROTO Inner [ field SFFloat r 1 ] { Sphere { radius IS r } }
DEF G Group { children [ Shape { geometry Inner { r IS size } appearance Appearance { material DEF M Material { diffuseColor IS tint } } } ] }
DEF Clock TimeSensor { }
DEF I PositionInterpolator { key [ 0 1 ] keyValue [ 0 0 0 1 1 1 ] }
ROUTE Clock.fraction_changed TO I.set_fraction
ROUTE I.value_changed TO G.set_translation
}
EXTERNPROTO Far [ field SFFloat x ] [ "far.wrl#Far" "urn:far" ]
DEF O1 Outer { size 3 tint 0 1 0 }
Outer { }
Far { x 2 }
DEF S Script { field SFNode target USE O1 eventIn SFTime touch url "javascript: function touch() {}" }
IMPORT inl.Thing AS Thing
EXPORT S AS Exported
]]))
t:eq(#g.roots, 4, "proto instances, extern instance, script")
local o1, o2 = g.roots[1], g.roots[2]
t:eq(o1.type, "Group", "an instance is its body's first node")
t:eq(o1.def, "O1", "the instance's DEF name")
local function radius(o: any): number
local sh = Fields.nodes(o, "children")[1]
return Fields.num(Fields.node(sh, "geometry"), "radius", -1)
end
t:eq(radius(o1), 3, "IS through a nested PROTO (instance value)")
t:eq(radius(o2), 1, "IS default")
local mat = Fields.node(Fields.node(Fields.nodes(o1, "children")[1], "appearance"), "material")
t:eq(table.concat(Fields.vec(mat, "diffuseColor", { 9, 9, 9 }), " "), "0 1 0", "IS on an SFColor")
local mat2 = Fields.node(Fields.node(Fields.nodes(o2, "children")[1], "appearance"), "material")
t:check(mat ~= mat2, "each instance has its own copy of the body")
t:eq(#g.routes, 4, "the body's ROUTEs, per instance")
t:check(g.routes[2].to == o1 or g.routes[2].to.fields == o1.fields, "routes point at the instance's nodes")
t:eq(g.roots[3].type, "Far", "EXTERNPROTO instance keeps its type")
t:check(g.roots[3].extern == true, "EXTERNPROTO instance flagged")
t:eq(Fields.node(g.roots[4], "target"), o1, "Script interface field with a USE value")
end
do
local g = assert(Vrml.parse("#X3D V3.3 utf8\nPROFILE Immersive\nCOMPONENT CADGeometry:2\nMETA \"author\" \"me\"\nUNIT length foot 0.3048\nGroup { }\n"))
t:check(g.header.x3d and g.header.version == "3.3" and g.header.profile == "Immersive", "X3D header, PROFILE")
t:eq(g.components[1], "CADGeometry:2", "COMPONENT")
t:eq(g.meta.author, "me", "META")
t:eq(g.units.length.factor, 0.3048, "UNIT")
local s = assert(Vrml.build(g))
t:eq(s.meta.unit, 0.3048, "UNIT length -> meta.unit")
end
-- ------------------------------------------------------------------------------------------------ XML adapter
do
local g = assert(Vrml.graph([[<?xml version="1.0"?>
<X3D profile="Interchange" version="4.0"><head><component name="Shaders" level="1"/></head><Scene>
<ProtoDeclare name="Ball"><ProtoInterface><field name="r" type="SFFloat" accessType="initializeOnly" value="2"/></ProtoInterface>
<ProtoBody><Shape><Sphere><IS><connect nodeField="radius" protoField="r"/></IS></Sphere></Shape></ProtoBody></ProtoDeclare>
<Group DEF="G"><ProtoInstance name="Ball"><fieldValue name="r" value="5"/></ProtoInstance>
<ProtoInstance name="Ball" containerField="children"/></Group>
<Shape><Appearance><ImageTexture url='"a.png" "b.png"'/></Appearance><Box containerField="geometry" size="1, 2, 3" solid="FALSE"/></Shape>
<Transform USE="G"/>
</Scene></X3D>]]))
t:check(g.header.xml and g.header.version == "4.0", "XML header")
t:eq(g.components[1], "Shaders:1", "head component")
local grp = g.roots[1]
local kids = Fields.nodes(grp, "children")
t:eq(#kids, 2, "ProtoInstances in children")
t:eq(Fields.num(Fields.node(kids[1], "geometry"), "radius", -1), 5, "fieldValue")
t:eq(Fields.num(Fields.node(kids[2], "geometry"), "radius", -1), 2, "ProtoInterface default")
local shape = g.roots[2]
local box = Fields.node(shape, "geometry")
t:eq(table.concat(Fields.vec(box, "size", { 9, 9, 9 }), " "), "1 2 3", "numbers with commas")
t:eq(Fields.bool(box, "solid", true), false, "XML booleans (any case)")
local tex = Fields.node(Fields.node(shape, "appearance"), "texture")
local urls = Fields.strs(tex, "url")
t:check(#urls == 2 and urls[2] == "b.png", "quoted MFString")
t:eq(g.roots[3], grp, "USE in XML")
local single = { type = "ImageTexture", fields = { url = "plain name.png" } }
t:eq(Fields.strs(single, "url")[1], "plain name.png", "unquoted single MFString")
end
-- ------------------------------------------------------------------------------------------------ errors
do
local function code(text: string): string?
local _, e = Vrml.graph(text)
return e and e.code
end
t:eq(code("#VRML V2.0 utf8\nShape { geometry Box { }"), Err.CORRUPT, "unclosed node")
t:eq(code("#VRML V2.0 utf8\nShape { geometry USE X }"), Err.CORRUPT, "undefined USE")
t:eq(code("#VRML V2.0 utf8\nROUTE A.b TO"), Err.CORRUPT, "bad ROUTE")
t:eq(code("#VRML V2.0 utf8\nWorldInfo { title \"x }"), Err.TRUNCATED, "unterminated string")
t:eq(code("#VRML V1.0 ascii\n"), Err.UNSUPPORTED, "VRML 1.0")
t:eq(code("\224\0\0\1rest"), Err.UNSUPPORTED, "Fast Infoset X3D")
t:eq(code("#VRML V2.0 utf8\n" .. string.rep("Group { children ", 250)), Err.LIMIT, "nesting limit")
t:eq(code("<X3D><Scene><Group></Scene></X3D>"), Err.CORRUPT, "bad XML")
local _, e = Vrml.encode({} :: any)
t:eq(e and e.code, Err.ARG, "encode junk")
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local samples = {
"#VRML V2.0 utf8\nPROTO P [ field SFFloat a 1 ] { Box { size IS a IS a } }\nDEF X P { a 2 } USE X ROUTE X.a TO X.b\n",
"#X3D V3.3 utf8\nPROFILE Full\nShape { geometry Extrusion { spine [ 0 0 0 0 1 0 1 1 1 ] crossSection [ 0 0 1 0 1 1 0 0 ] } }\n",
"<X3D><Scene><ProtoDeclare name='A'><ProtoBody><Box/></ProtoBody></ProtoDeclare><ProtoInstance name='A'/><Shape><IndexedFaceSet coordIndex='0 1 2 -1 2 3 0'><Coordinate point='0 0 0 1 0 0 1 1 0 0 1 0'/></IndexedFaceSet></Shape></Scene></X3D>",
}
t:fuzz("graph + build", function(b: buffer)
local g = Vrml.graph(b)
if g then
return Vrml.build(g)
end
return nil
end, samples, { mutations = 400 })
end
t:done()
+602
View File
@@ -0,0 +1,602 @@
-- model/3ds tests: assimp's 3DS test models (meshes, materials, textures, keyframer hierarchies, pivots, camera /
-- target / rotation animation, cameras, lights) and assimp's 3DS exporter output, against assimp (meshes, faces,
-- corners, materials, animations, cameras, lights, world bounds); the keyframer placing every mesh where its mesh
-- matrix says; round trips through our writer (world triangles, materials, textures, cameras, lights, sampled
-- animation) for the reference files and for glTF sample models; assimp reading our files like the originals
-- (3ds_xcheck); errors; the fuzz no-throw pass. Fixtures: tools/fixtures/3ds.py.
local T = require("@tests/T")
local F = require("@formats")
local ThreeDs = require("@formats/model/3ds")
local Gltf = require("@formats/model/gltf")
local MeshOps = require("@formats/ops/MeshOps")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Cases = require("@tests/gen/3ds_cases")
local Picks = require("@tests/gen/3ds_gltf")
local Xcheck = require("@tests/gen/3ds_xcheck")
local t = T.suite("3ds")
local S = Types.Scene
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return ThreeDs.decode(Bytes.reader(b), opts)
end
t:eq(ThreeDs.name, "3ds", "name")
t:eq(ThreeDs.category, "model", "category")
t:check(ThreeDs.caps.decode and ThreeDs.caps.encode, "contract")
local function near(a: number, b: number, eps: number): boolean
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
end
-- placed primitives, triangles, corners
local function counts(scene: any): (number, number, number)
local prims, faces, corners = 0, 0, 0
local seen = {}
for _, pl in S.flatten(scene) do
if not seen[pl.primitive] then
seen[pl.primitive] = true
prims += 1
faces += pl.primitive.indices.count // 3
corners += pl.primitive.indices.count
end
end
return prims, faces, corners
end
local function noMaterial(scene: any): boolean
for _, m in scene.meshes do
for _, p in m.primitives do
if p.material == nil then
return true
end
end
end
return false
end
-- assimp's default material: an existing grey untextured material named "*default*" is reused
local function defaultReused(scene: any): boolean
for _, m in scene.materials do
local c = m.baseColor
if string.find(string.lower(m.name or ""), "default", 1, true) and c[1] == c[2] and c[1] == c[3] and not m.baseColorTexture then
local x = m.extras["3ds"].maps
if next(x) == nil then
return true
end
end
end
return false
end
-- world bounds: as they are, or under assimp's Z-up -> Y-up root rotation (x, z, -y)
local function boundsMatch(lo: { number }, hi: { number }, want: any, eps: number): boolean
local function eq(a: { number }, b: { number }): boolean
for k = 1, 3 do
if not near(a[k], want.min[k], eps) or not near(b[k], want.max[k], eps) then
return false
end
end
return true
end
return eq(lo, hi) or eq({ lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] })
end
local function bstr(lo: any, hi: any): string
if not lo then
return "-"
end
return string.format("(%.4g %.4g %.4g) (%.4g %.4g %.4g)", lo[1], lo[2], lo[3], hi[1], hi[2], hi[3])
end
-- ------------------------------------------------------------------------------------------------ reference files
-- assimp ignores the camera / light frame of their children (CameraRollAnimWithChildObject: a box linked to the
-- camera); our bounds follow the mesh matrices there (checked below)
local ASSIMP_BOUNDS_DIFFER = { ["assimp/models/CameraRollAnimWithChildObject.3ds"] = true }
local function boundsDiffer(i: number): boolean
return ASSIMP_BOUNDS_DIFFER[Cases[i].name] == true
end
local scenes = {}
local checked = 0
for i, c in Cases do
local scene, err = decode(c.data)
local a = c.assimp
if a.failed then
t:note("%s: assimp rejects it; we read it: %s", c.name, tostring(scene ~= nil))
else
t:check(scene, c.name .. ": decode: " .. tostring(err))
scenes[i] = scene
if scene then
local prims, faces, corners = counts(scene)
t:eq(prims, a.meshes, c.name .. ": meshes (assimp)")
t:eq(faces, a.faces, c.name .. ": faces (assimp)")
t:eq(corners, a.vertices, c.name .. ": corners (assimp)")
t:eq(#scene.cameras, a.cameras, c.name .. ": cameras (assimp)")
t:eq(#scene.lights, a.lights, c.name .. ": lights (assimp)")
t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)")
local extra = if noMaterial(scene) and not defaultReused(scene) then 1 else 0
t:eq(#scene.materials + extra, a.materials, c.name .. ": materials (assimp, + its default)")
if a.min and not ASSIMP_BOUNDS_DIFFER[c.name] then
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
t:check(lo and boundsMatch(lo, hi, a, 1e-3), c.name .. ": world bounds (assimp) " .. bstr(lo, hi) .. " want " .. bstr(a.min, a.max))
end
checked += 1
end
end
end
t:note("%d files against assimp", checked)
-- the keyframer places every mesh where its mesh matrix put the stored (world space) vertices
do
local n = 0
for i, c in Cases do
local scene = scenes[i]
if scene and scene.meta.source.keyframer and #scene.animations == 0 and string.sub(c.name, 1, 7) == "assimp/" then
local raw = decode(c.data, { normals = false })
local flat = decode(c.data, { normals = false })
-- the file's vertices: the meshes placed at identity (Read only; via the writer-free path: raw bounds)
local lo, hi = MeshOps.bounds(MeshOps.merge(raw))
local _ = flat
local Read = require("@formats/model/3ds/Read")
local parsed = Read.parse(buffer.fromstring(c.data), 0, #c.data)
local plo, phi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
local placed: { [string]: boolean } = {}
for _, kn in parsed.keyframer.nodes do
if kn.kind == "object" then
placed[kn.name] = true
end
end
for _, o in parsed.objects do
if o.mesh and o.mesh.nf > 0 and placed[o.name] then
for v = 0, o.mesh.nv - 1 do
for k = 1, 3 do
local x = buffer.readf32(o.mesh.positions, (v * 3 + k - 1) * 4)
plo[k], phi[k] = math.min(plo[k], x), math.max(phi[k], x)
end
end
end
end
if lo and plo[1] <= phi[1] then
local ok = true
for k = 1, 3 do
ok = ok and near(lo[k], plo[k], 2e-3) and near(hi[k], phi[k], 2e-3)
end
t:check(ok, c.name .. ": keyframer world bounds = the stored vertices " .. bstr(lo, hi) .. " / " .. bstr(plo, phi))
n += 1
end
end
end
t:note("%d keyframer scenes match their stored vertices", n)
end
-- ------------------------------------------------------------------------------------------------ round trips
local function triArea(prim: any): number
local P = S.reader(prim.attributes.POSITION) :: any
local I = S.reader(prim.indices) :: any
local area = 0
for tri = 0, prim.indices.count // 3 - 1 do
local a, b, c = I(tri * 3, 0), I(tri * 3 + 1, 0), I(tri * 3 + 2, 0)
local e1 = { P(b, 0) - P(a, 0), P(b, 1) - P(a, 1), P(b, 2) - P(a, 2) }
local e2 = { P(c, 0) - P(a, 0), P(c, 1) - P(a, 1), P(c, 2) - P(a, 2) }
local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1]
area += math.sqrt(x * x + y * y + z * z) / 2
end
return area
end
-- the world matrices of the nodes with a camera / light, in tree order
local function worldOf(s: any, field: string): { { number } }
local out = {}
local function visit(i: number, parent: { number })
local n = s.nodes[i]
local w = S.mul(parent, S.nodeMatrix(n))
if n[field] then
table.insert(out, { w = w, item = n[field] })
end
for _, c in n.children do
visit(c, w)
end
end
for _, r in s.roots do
visit(r, S.IDENTITY)
end
return out
end
-- channel value at a time (LINEAR / STEP; quaternions lerped the short way)
local function evalCh(ch: any, time: number, comps: number): { number }
local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any
local n = ch.input.count
local cubic = ch.interpolation == "CUBICSPLINE"
local function v(k: number): { number }
local e = if cubic then k * 3 + 1 else k
local r = {}
for q = 0, comps - 1 do
r[q + 1] = OUT(e, q)
end
return r
end
if time <= IN(0, 0) then
return v(0)
end
for k = 0, n - 2 do
local t0, t1 = IN(k, 0), IN(k + 1, 0)
if time <= t1 then
if ch.interpolation == "STEP" or t1 <= t0 then
return if time >= t1 then v(k + 1) else v(k)
end
local u = (time - t0) / (t1 - t0)
local a0, a1 = v(k), v(k + 1)
if comps == 4 and a0[1] * a1[1] + a0[2] * a1[2] + a0[3] * a1[3] + a0[4] * a1[4] < 0 then
a1 = { -a1[1], -a1[2], -a1[3], -a1[4] }
end
local r = {}
for q = 1, comps do
r[q] = a0[q] + (a1[q] - a0[q]) * u
end
return r
end
end
return v(n - 1)
end
-- the world matrix of every named node at a time (animations[1] applied)
local function posed(s: any, time: number): { [string]: { number } }
local byNode: { [number]: { [string]: any } } = {}
local anim = s.animations[1]
if anim then
for _, ch in anim.channels do
byNode[ch.node] = byNode[ch.node] or {}
byNode[ch.node][ch.path] = ch
end
end
local out = {}
local count: { [string]: number } = {}
local function visit(i: number, parent: { number })
local n = s.nodes[i]
local m
local chs = byNode[i]
if chs then
local tr = if chs.translation then evalCh(chs.translation, time, 3) else (n.translation or { 0, 0, 0 })
local r = if chs.rotation then evalCh(chs.rotation, time, 4) else (n.rotation or { 0, 0, 0, 1 })
local sc = if chs.scale then evalCh(chs.scale, time, 3) else (n.scale or { 1, 1, 1 })
local l = math.sqrt(r[1] * r[1] + r[2] * r[2] + r[3] * r[3] + r[4] * r[4])
r = { r[1] / l, r[2] / l, r[3] / l, r[4] / l }
local Mat4 = require("@formats/codecs/model/Mat4")
m = Mat4.compose(tr, r, sc)
else
m = S.nodeMatrix(n)
end
local w = S.mul(parent, m)
local key = if n.mesh then "mesh" .. n.mesh elseif n.camera then "camera" else if n.light then "light" else nil
if key then
count[key] = (count[key] or 0) + 1
out[key .. "#" .. count[key]] = w
end
for _, c in n.children do
visit(c, w)
end
end
for _, r in s.roots do
visit(r, S.IDENTITY)
end
return out
end
local function compare(a: any, b: any, label: string, eps: number, animTimes: { number }?)
local ma, mb = MeshOps.merge(a), MeshOps.merge(b)
local na = if ma and ma.indices then ma.indices.count // 3 else 0
local nb = if mb and mb.indices then mb.indices.count // 3 else 0
t:eq(nb, na, label .. ": triangles")
if na > 0 and nb > 0 then
t:check(near(triArea(ma), triArea(mb), eps), string.format("%s: area %.7g / %.7g", label, triArea(ma), triArea(mb)))
local la, ha = MeshOps.bounds(ma)
local lb, hb = MeshOps.bounds(mb)
local ok = true
for k = 1, 3 do
ok = ok and near(la[k], lb[k], eps) and near(ha[k], hb[k], eps)
end
t:check(ok, label .. ": bounds " .. bstr(la, ha) .. " / " .. bstr(lb, hb))
end
t:eq(#b.materials, #a.materials, label .. ": materials")
for k, m in a.materials do
local m2 = b.materials[k]
if m2 then
local ok = true
for q = 1, 4 do
ok = ok and near(m.baseColor[q], m2.baseColor[q], 1e-6)
end
t:check(ok, label .. ": material " .. k .. " colour")
t:check((m.baseColorTexture == nil) == (m2.baseColorTexture == nil), label .. ": material " .. k .. " texture")
t:check(m.doubleSided == m2.doubleSided, label .. ": material " .. k .. " two-sided")
end
end
for _, field in { "camera", "light" } do
local pa, pb = worldOf(a, field), worldOf(b, field)
t:eq(#pb, #pa, label .. ": " .. field .. " nodes")
for k, e in pa do
local w = e.w
local w2 = pb[k] and pb[k].w
local ok = w2 ~= nil
if w2 then
-- position and view axis (3DS cameras and lights carry no scale)
for _, q in { 13, 14, 15 } do
ok = ok and near(w[q], w2[q], 1e-4)
end
if field == "camera" or a.lights[e.item].type ~= "point" then
local function z(m: { number }): (number, number, number)
local l = math.sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11])
return m[9] / l, m[10] / l, m[11] / l
end
local x1, y1, z1 = z(w)
local x2, y2, z2 = z(w2)
ok = ok and x1 * x2 + y1 * y2 + z1 * z2 > 0.9999
end
end
t:check(ok, label .. ": " .. field .. " " .. k .. " placement")
end
end
-- the horizontal field of view (3DS stores a lens, not the aspect)
for k, c in a.cameras do
local c2 = b.cameras[k]
if c2 and c.type == "perspective" then
local function hfov(cam: any): number
return 2 * math.atan(math.tan(cam.yfov / 2) * (cam.aspect or 4 / 3))
end
t:check(near(hfov(c), hfov(c2), 1e-5), label .. ": camera " .. k .. " fov")
end
end
-- one timeline: the first animation's node transforms
local trs = false
for _, ch in (if a.animations[1] then a.animations[1].channels else {}) :: { any } do
trs = trs or ch.path ~= "weights"
end
t:eq(#b.animations, if trs then 1 else 0, label .. ": animations")
if animTimes and #a.animations > 0 then
local bad, n = 0, 0
for _, time in animTimes do
local pa, pb = posed(a, time), posed(b, time)
for nm, w in pa do
local w2 = pb[nm]
if w2 then
for q = 1, 16 do
if not near(w[q], w2[q], 2e-3) then
bad += 1
end
end
n += 1
end
end
end
t:check(bad == 0 and n > 0, string.format("%s: posed world matrices: %d values of %d nodes x times differ", label, bad, n))
end
end
local TIMES = { 0, 0.1, 0.5, 1, 1.5, 2, 3.3, 5, 8 }
local nrt = 0
for i, c in Cases do
local scene = scenes[i]
if scene then
local out, err = ThreeDs.encode(scene)
t:check(out, c.name .. ": encode: " .. tostring(err))
local back, berr = decode(out :: buffer)
t:check(back, c.name .. ": decode ours: " .. tostring(berr))
if back then
compare(scene, back, c.name, 1e-4, TIMES)
local p1, f1 = counts(scene)
local p2, f2 = counts(back)
t:check(p1 == p2 and f1 == f2, c.name .. ": primitives and faces kept")
-- the smoothing groups come back, so the normals do
local same = true
for mi, m in scene.meshes do
local m2 = back.meshes[mi]
for pi, p in m.primitives do
local p2 = m2 and m2.primitives[pi]
if not p2 or p2.attributes.POSITION.count ~= p.attributes.POSITION.count then
same = false
end
end
end
t:check(same, c.name .. ": vertex splits (smoothing groups) kept")
end
nrt += 1
end
end
-- glTF sample models through 3DS
local gltfScenes = {}
local ng = 0
for gi, g in Picks do
local scene, gerr = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files })
t:check(scene, g.name .. ": glTF decode: " .. tostring(gerr))
if scene then
gltfScenes[gi] = scene
local out, err = ThreeDs.encode(scene, { fps = 1000 })
t:check(out, g.name .. ": encode: " .. tostring(err))
local back, berr = decode(out :: buffer, { fps = 1000 })
t:check(back, g.name .. ": decode ours: " .. tostring(berr))
if back then
-- skins and morph targets are not 3DS; STEP / CUBICSPLINE keys become linear
local linear = true
for _, an in scene.animations do
for _, ch in an.channels do
if ch.interpolation ~= "LINEAR" or ch.path == "weights" then
linear = false
end
end
end
compare(scene, back, "glTF " .. g.name, 2e-4, if linear and #scene.skins == 0 then TIMES else nil)
ng += 1
end
end
end
t:note("%d reference files and %d glTF models through our writer and back", nrt, ng)
-- ------------------------------------------------------------------------------------------------ cross-check
-- assimp reads our files like the originals
local nx = 0
for _, x in Xcheck do
local a = x.assimp
t:check(not a.failed, x.name .. ": assimp reads our file")
if not a.failed then
local scene, want
if x.case then
scene, want = scenes[x.case], Cases[x.case].assimp
else
scene = gltfScenes[x.gltf]
end
if scene then
local _, faces, corners = counts(scene)
t:eq(a.faces, faces, x.name .. ": assimp faces of our file")
t:eq(a.vertices, corners, x.name .. ": assimp corners of our file")
t:eq(a.cameras, #worldOf(scene, "camera"), x.name .. ": assimp cameras of our file")
t:eq(a.lights, #worldOf(scene, "light"), x.name .. ": assimp lights of our file")
if want and not want.failed then
t:eq(a.meshes, want.meshes, x.name .. ": assimp meshes of our file")
t:eq(a.animations, want.animations, x.name .. ": assimp animations of our file")
end
if a.min and not (x.case and boundsDiffer(x.case)) then
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
t:check(lo and boundsMatch(lo, hi, a, 1e-3), x.name .. ": assimp world bounds of our file " .. bstr(lo, hi) .. " / " .. bstr(a.min, a.max))
end
nx += 1
end
end
end
t:note("%d of our files read back by assimp", nx)
-- ------------------------------------------------------------------------------------------------ details
do
local byName = {}
for i, c in Cases do
byName[c.name] = scenes[i]
end
local tex = byName["assimp/models/cube_with_diffuse_texture.3DS"]
if tex then
local m = tex.materials[1]
t:check(m.baseColorTexture and tex.textures[m.baseColorTexture.texture].uri ~= nil, "diffuse map -> baseColorTexture with a uri")
t:check(tex.textures[1].data == nil, "texture files are not read")
t:check(tex.meshes[1].primitives[1].attributes.TEXCOORD_0 ~= nil and tex.meshes[1].primitives[1].attributes.NORMAL ~= nil, "uvs and normals")
t:eq(tex.meta.up, "z", "3DS is Z up")
end
local spec = byName["assimp/models/cube_with_specular_texture.3DS"]
if spec then
t:check(spec.materials[1].extras["3ds"].maps.specular ~= nil, "specular map kept in extras")
end
local alpha = byName["assimp/models/cubes_with_alpha.3DS"]
if alpha then
local blended = 0
for _, m in alpha.materials do
if m.alphaMode == "blend" and m.baseColor[4] < 1 then
blended += 1
end
end
t:check(blended > 0, "transparency -> alpha " .. blended)
end
local cam = byName["assimp/models/CameraRollAnim.3ds"]
if cam then
local c = cam.cameras[1]
-- 2400 / 53.33 mm = 45 degrees horizontal at 4:3
t:check(near(2 * math.atan(math.tan(c.yfov / 2) * c.aspect), math.rad(45), 1e-4), "camera lens -> fov " .. math.deg(c.yfov))
local paths = {}
for _, ch in cam.animations[1].channels do
paths[ch.path] = true
end
t:check(paths.rotation, "camera roll -> a rotation channel")
end
local child = byName["assimp/models/CameraRollAnimWithChildObject.3ds"]
if child then
local camNode
for _, n in child.nodes do
if n.camera then
camNode = n
end
end
t:check(camNode and #camNode.children == 1 and child.nodes[camNode.children[1]].name == "Box02", "a box linked to the camera")
end
local spin = byName["assimp/models/RotatingCube.3DS"]
if spin then
local ch = spin.animations[1].channels[1]
t:check(ch.path == "rotation" and ch.input.count > 100, "rotation keys accumulated: " .. ch.input.count)
end
local pyr = byName["assimp/models-nonbsd/pyramob.3DS"]
if pyr then
local types = {}
for _, l in pyr.lights do
types[l.type] = true
end
t:check(types.point and types.spot, "omni and spot lights")
end
-- the api
local s = F.load(Cases[1].data)
t:check(s and s.kind == "scene" and s.meta.source.format == "3ds", "F.load detects 3DS")
local viaApi = F.save(s, nil, { format = "3ds" })
t:check(viaApi and buffer.readu16(viaApi, 0) == 0x4D4D, "F.save format 3ds")
-- normals = false keeps the file's vertices
local raw = decode(Cases[1].data, { normals = false })
t:check(raw and raw.meshes[1].primitives[1].attributes.NORMAL == nil, "normals = false")
-- a hand-made scene: two instances of one mesh, a texture without uri goes to opts.files
local p = S.accessor(nil, "f32", 3, 3)
for v, xyz in { { 0, 0, 0 }, { 1, 0, 0 }, { 0, 1, 0 } } do
for k = 1, 3 do
buffer.writef32(p.data, ((v - 1) * 3 + k - 1) * 4, xyz[k])
end
end
local uv = S.accessor(nil, "f32", 2, 3)
local tri = S.fromPrimitive({ attributes = { POSITION = p, TEXCOORD_0 = uv }, mode = "triangles", material = 1 }, "tri")
tri.materials[1] = S.material("red")
tri.materials[1].baseColor = { 1, 0, 0, 1 }
tri.materials[1].baseColorTexture = { texture = 1 }
tri.textures[1] = { data = buffer.fromstring("\137PNG"), mime = "image/png" }
tri.nodes[2] = { name = "copy", children = {}, mesh = 1, translation = { 5, 0, 0 } }
table.insert(tri.roots, 2)
local files = {}
local out = ThreeDs.encode(tri, { name = "tri.3ds", files = files }) :: buffer
t:check(files["tri_1.png"] ~= nil, "embedded texture bytes -> opts.files")
local back = decode(out)
t:check(back and #back.meshes == 1 and #back.nodes == 2 and back.nodes[2].mesh == 1, "instances share one mesh")
t:eq(back.textures[1].uri, "tri_1.png", "the texture's file name")
local lo, hi = MeshOps.bounds(MeshOps.merge(back))
t:check(lo[1] == 0 and hi[1] == 6, "the instance stands at x = 5")
t:eq(back.nodes[2].name, "copy", "instance name")
end
-- ------------------------------------------------------------------------------------------------ errors
do
local empty = decode("MM\6\0\0\0")
t:check(empty and #empty.meshes == 0 and #empty.nodes == 0, "an empty main chunk: an empty scene")
local data = Cases[1].data
local _, e2 = decode(string.sub(data, 1, #data // 2))
t:check(e2 and e2.code == Err.TRUNCATED, "truncated: " .. tostring(e2))
local _, e3 = decode("not a 3ds file at all")
t:check(e3 and e3.code == Err.CORRUPT, "garbage: " .. tostring(e3))
local _, e4 = decode(data, { maxVertices = 3 })
t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4))
local _, e5 = ThreeDs.encode({} :: any)
t:check(e5 and e5.code == Err.ARG, "encode junk")
t:check(ThreeDs.sniff(Bytes.reader(buffer.fromstring(data))) > 0.5, "sniff")
t:eq(ThreeDs.sniff(Bytes.reader(buffer.fromstring("MM junk junk junk"))), 0, "sniff junk")
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local samples = {}
for i, c in Cases do
if #c.data < 40000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local s = ThreeDs.decode(Bytes.reader(b))
if s then
ThreeDs.encode(s)
MeshOps.merge(s)
end
return s
end, samples, { mutations = 12, keepHeader = 6 })
end
t:done()
+109
View File
@@ -0,0 +1,109 @@
-- tests/model/_vrml_common: helpers shared by the VRML and X3D tests (tests/model/vrml.luau, x3d.luau): counts over
-- placed primitives (instances count, as the reference readers count them) and world bounds that include lines and
-- points (MeshOps.merge skips them).
local Types = require("@formats/Types")
local C = {}
export type Stats = { prims: number, unique: number, polys: number, lines: number, points: number, lo: { number }, hi: { number }, area: number }
function C.near(a: number, b: number, eps: number): boolean
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
end
function C.stats(scene: any): Stats
local s: Stats = { prims = 0, unique = 0, polys = 0, lines = 0, points = 0, lo = { math.huge, math.huge, math.huge }, hi = { -math.huge, -math.huge, -math.huge }, area = 0 }
local seen = {}
for _, pl in Types.Scene.flatten(scene) do
local p = pl.primitive
s.prims += 1
if not seen[p] then
seen[p] = true
s.unique += 1
end
local P = p.attributes.POSITION
local nf = 0
if p.mode == "polygons" then
nf = p.faces.count
elseif p.mode == "lines" then
s.lines += (if p.indices then p.indices.count else P.count) // 2
elseif p.mode == "points" then
s.points += P.count
elseif p.mode == "triangle_strip" or p.mode == "triangle_fan" then
nf = math.max(0, (if p.indices then p.indices.count else P.count) - 2)
elseif p.mode == "line_strip" or p.mode == "line_loop" then
local n = if p.indices then p.indices.count else P.count
s.lines += if p.mode == "line_loop" then n else math.max(0, n - 1)
else
nf = (if p.indices then p.indices.count else P.count) // 3
end
s.polys += nf
local m = pl.matrix
local get = assert(Types.Scene.reader(P))
local w = {}
for v = 0, P.count - 1 do
local x, y, z = get(v, 0), get(v, 1), get(v, 2)
local wx, wy, wz = m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15]
w[v] = { wx, wy, wz }
s.lo[1], s.lo[2], s.lo[3] = math.min(s.lo[1], wx), math.min(s.lo[2], wy), math.min(s.lo[3], wz)
s.hi[1], s.hi[2], s.hi[3] = math.max(s.hi[1], wx), math.max(s.hi[2], wy), math.max(s.hi[3], wz)
end
-- world area of the faces (fan-triangulated polygons)
local mode = p.mode
if mode == "triangles" or mode == "polygons" or mode == "triangle_strip" or mode == "triangle_fan" then
local ir = if p.indices then Types.Scene.reader(p.indices) else nil
local ind = function(i: number, _c: number): number
return if ir then ir(i, 0) else i
end
local count = if p.indices then p.indices.count else P.count
local function tri(a: number, b: number, c: number)
local A, B, Cc = w[a], w[b], w[c]
if A and B and Cc then
local e1 = { B[1] - A[1], B[2] - A[2], B[3] - A[3] }
local e2 = { Cc[1] - A[1], Cc[2] - A[2], Cc[3] - A[3] }
local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1]
s.area += math.sqrt(x * x + y * y + z * z) / 2
end
end
if mode == "triangles" then
for t = 0, count // 3 - 1 do
tri(ind(t * 3, 0), ind(t * 3 + 1, 0), ind(t * 3 + 2, 0))
end
elseif mode == "triangle_strip" then
for t = 0, count - 3 do
tri(ind(t, 0), ind(t + 1, 0), ind(t + 2, 0))
end
elseif mode == "triangle_fan" then
for t = 1, count - 2 do
tri(ind(0, 0), ind(t, 0), ind(t + 1, 0))
end
else
local at = 0
local sizes = assert(Types.Scene.reader(p.faces))
for f = 0, p.faces.count - 1 do
local n = sizes(f, 0)
for k = 1, n - 2 do
tri(ind(at, 0), ind(at + k, 0), ind(at + k + 1, 0))
end
at += n
end
end
end
end
return s
end
function C.boundsNear(lo: { number }, hi: { number }, wlo: { number }, whi: { number }, eps: number): boolean
for k = 1, 3 do
if not C.near(lo[k], wlo[k], eps) or not C.near(hi[k], whi[k], eps) then
return false
end
end
return true
end
function C.fmt(lo: { number }, hi: { number }): string
return string.format("%.5g %.5g %.5g / %.5g %.5g %.5g", lo[1], lo[2], lo[3], hi[1], hi[2], hi[3])
end
return C
+230
View File
@@ -0,0 +1,230 @@
-- model/b3d tests: assimp's Blitz3D models (WusonBlitz, dwarf2, turtle1) and generated files (textures, brushes,
-- vertex colours, two UV sets, nested rotated / scaled / mirrored nodes, pivots, master brushes, bones, keys + ANIM)
-- against assimp (meshes, faces, materials, animations, channels, bones; world bounds, triangle area and signed
-- volume from its PreTransformVertices export: the left- to right-handed conversion and the winding) and the counts
-- the generator wrote; the skin's bind pose; error codes; the fuzz no-throw pass. Fixtures: tools/fixtures/b3d.py.
local T = require("@tests/T")
local B3d = require("@formats/model/b3d")
local MeshOps = require("@formats/ops/MeshOps")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Cases = require("@tests/gen/b3d_cases")
local t = T.suite("b3d")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return B3d.decode(Bytes.reader(b), opts)
end
t:eq(B3d.name, "b3d", "name")
t:eq(B3d.category, "model", "category")
t:check(B3d.caps.decode and not B3d.caps.encode, "caps")
t:eq(B3d.sniff(Bytes.reader(buffer.fromstring("BB3D\0\0\0\0\1\0\0\0"))), 1, "sniff")
t:eq(B3d.sniff(Bytes.reader(buffer.fromstring("BX3D\0\0\0\0\1\0\0\0"))), 0, "sniff other")
local function near(a: number, b: number, eps: number): boolean
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
end
-- world triangles of the merged scene: area and signed volume
local function measure(prim: any): (number, number)
local get = assert(Types.Scene.reader(prim.attributes.POSITION))
local idx = prim.indices and Types.Scene.reader(prim.indices)
local n = if idx then prim.indices.count else prim.attributes.POSITION.count
local area, vol = 0, 0
for k = 0, n // 3 - 1 do
local i0, i1, i2 = 3 * k, 3 * k + 1, 3 * k + 2
if idx then
i0, i1, i2 = idx(i0, 0), idx(i1, 0), idx(i2, 0)
end
local ax, ay, az = get(i0, 0), get(i0, 1), get(i0, 2)
local bx, by, bz = get(i1, 0), get(i1, 1), get(i1, 2)
local cx, cy, cz = get(i2, 0), get(i2, 1), get(i2, 2)
local ux, uy, uz, vx, vy, vz = bx - ax, by - ay, bz - az, cx - ax, cy - ay, cz - az
local x, y, z = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
area += math.sqrt(x * x + y * y + z * z) / 2
vol += (ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx) + az * (bx * cy - by * cx)) / 6
end
return area, vol
end
-- assimp's bone count: per primitive, the joints that weight one of its vertices (not the mesh node's own joint)
local function boneCount(scene: any): number
local n = 0
for ni, node in scene.nodes do
if node.mesh and node.skin then
local skin = scene.skins[node.skin]
for _, p in scene.meshes[node.mesh].primitives do
local J, W = Types.Scene.reader(p.attributes.JOINTS_0), Types.Scene.reader(p.attributes.WEIGHTS_0)
local idx = assert(Types.Scene.reader(p.indices))
local seen = {}
for i = 0, p.indices.count - 1 do
local v = idx(i, 0)
for k = 0, 3 do
local j = (J :: any)(v, k)
if (W :: any)(v, k) > 0 and skin.joints[j + 1] ~= ni and not seen[j] then
seen[j] = true
n += 1
end
end
end
end
end
end
return n
end
-- ------------------------------------------------------------------------------------------------ cases
local samples = {}
for _, c in Cases do
local scene, err = decode(c.data, { files = c.files })
local a = c.assimp
t:check(scene, c.name .. ": decode: " .. tostring(err))
if scene and not a.failed then
local prims, faces = 0, 0
for _, pl in Types.Scene.flatten(scene) do
prims += 1
faces += pl.primitive.indices.count // 3
end
t:eq(prims, a.meshes, c.name .. ": meshes (assimp)")
t:eq(faces, a.faces, c.name .. ": faces (assimp)")
t:eq(math.max(1, scene.meta.source.brushes), a.materials, c.name .. ": materials (assimp)")
t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)")
local animated = {}
local nAnimated = 0
for _, anim in scene.animations do
for _, ch in anim.channels do
if not animated[ch.node] then
animated[ch.node] = true
nAnimated += 1
end
end
end
if a.animations > 0 then
t:eq(nAnimated, a.animation_channels, c.name .. ": animated nodes (assimp)")
end
t:eq(boneCount(scene), a.bones, c.name .. ": bones (assimp)")
local merged = assert(MeshOps.merge(scene))
local lo, hi = MeshOps.bounds(merged)
local ok = lo ~= nil
for k = 1, 3 do
ok = ok and near((lo :: any)[k], a.min[k], 1e-4) and near((hi :: any)[k], a.max[k], 1e-4)
end
t:check(ok, string.format("%s: world bounds (assimp) %s / %s", c.name, table.concat(lo or {}, " "), table.concat(hi or {}, " ")))
local area, vol = measure(merged)
t:check(near(area, a.area, 1e-4), string.format("%s: area %.6g (assimp %.6g)", c.name, area, a.area))
-- (a mirrored node: glTF turns its faces back, assimp's PreTransformVertices does not; skip the volume there)
if not (c.want and c.want.mirrored) then
t:check(near(vol, a.volume, 1e-3), string.format("%s: signed volume %.6g (assimp %.6g)", c.name, vol, a.volume))
end
-- textures resolved through files
for _, tex in scene.textures do
local base = string.match(tex.uri, "([^/\\]+)$")
t:check((tex.data ~= nil) == (c.files[base] ~= nil), c.name .. ": texture data " .. tostring(tex.uri))
end
local w = c.want
if w then
local nv, nt = 0, 0
for _, m in scene.meshes do
nv += m.primitives[1].attributes.POSITION.count
for _, p in m.primitives do
nt += p.indices.count // 3
end
end
t:eq(nv, w.vertices, c.name .. ": vertices")
t:eq(nt, w.triangles, c.name .. ": triangles")
t:eq(#scene.textures, w.textures, c.name .. ": textures")
t:eq(#scene.materials, w.materials, c.name .. ": materials")
t:eq(#scene.nodes, w.nodes, c.name .. ": nodes")
local attrs = scene.meshes[1].primitives[1].attributes
t:eq(attrs.COLOR_0 ~= nil, w.colors, c.name .. ": COLOR_0")
local sets = 0
while attrs["TEXCOORD_" .. sets] do
sets += 1
end
t:eq(sets, w.uvSets, c.name .. ": uv sets")
if w.joints then
t:eq(#scene.skins, 1, c.name .. ": one skin")
t:eq(#scene.skins[1].joints, w.joints, c.name .. ": joints")
t:eq(#scene.animations[1].channels, w.channels, c.name .. ": channels")
t:eq(scene.meta.source.fps, w.fps, c.name .. ": fps")
t:eq(scene.meta.source.frames, w.frames, c.name .. ": frames")
end
end
if c.name == "gen/textured" then
local m1, m2 = scene.materials[1], scene.materials[2]
t:check(m1.name == "red" and m1.baseColorTexture and m1.baseColorTexture.texture == 1, "textured: brush texture")
local tr = m1.baseColorTexture and m1.baseColorTexture.transform
t:check(tr and tr.offset[1] == 0.25 and tr.scale[2] == 3 and tr.rotation == 0.5, "textured: texture transform")
t:check(m1.extras.b3d.textures[2] == 2, "textured: second brush texture in extras")
t:check(m2.name == "glass" and m2.alphaMode == "blend" and m2.doubleSided and m2.extensions.KHR_materials_unlit, "textured: alpha, FX")
t:check(m2.baseColorTexture and m2.baseColorTexture.texCoord == 1, "textured: second UV set flag")
t:check(scene.textures[2].sampler and scene.textures[2].sampler.wrapS == "clamp", "textured: clamp")
end
-- the bind pose: skinning the vertices with the inverse bind matrices gives the static placement
for ni, node in scene.nodes do
if node.skin then
local skin = scene.skins[node.skin]
local worlds = {}
for _, pl in Types.Scene.flatten(scene) do
worlds[pl.node] = pl.matrix
end
local ibm = assert(Types.Scene.reader(skin.inverseBindMatrices))
local function world(i: number): { number }
local parent
for pi, n in scene.nodes do
if table.find(n.children, i) then
parent = pi
end
end
local l = Types.Scene.nodeMatrix(scene.nodes[i])
return if parent then Types.Scene.mul(world(parent), l) else l
end
local maxErr = 0
local meshWorld = world(ni)
for j, jn in skin.joints do
local m = {}
for k = 1, 16 do
m[k] = ibm(j - 1, k - 1)
end
local jm = Types.Scene.mul(world(jn), m)
for k = 1, 16 do
maxErr = math.max(maxErr, math.abs(jm[k] - meshWorld[k]))
end
end
t:check(maxErr < 1e-3, c.name .. ": joint * inverse bind = the mesh's world matrix (" .. maxErr .. ")")
end
end
end
if #c.data < 100000 then
table.insert(samples, c.data)
end
end
-- ------------------------------------------------------------------------------------------------ errors
do
local _, e = decode("BB3D\4\0\0\0\1\0\0\0")
t:check(e and e.code == Err.CORRUPT, "no NODE: CORRUPT")
_, e = decode("BB3D\100\0\0\0\1\0\0\0")
t:check(e and e.code == Err.TRUNCATED, "short BB3D: TRUNCATED")
_, e = decode("RIFF\0\0\0\0")
t:check(e and e.code == Err.CORRUPT, "not B3D: CORRUPT")
local s = Cases[#Cases].data
local _, e2 = decode(string.sub(s, 1, #s - 7))
t:check(e2 and e2.code == Err.TRUNCATED, "truncated file: TRUNCATED (" .. tostring(e2) .. ")")
local _, e3 = decode(s, { maxVertices = 4 })
t:check(e3 and e3.code == Err.LIMIT, "maxVertices: LIMIT")
end
-- ------------------------------------------------------------------------------------------------ fuzz
t:fuzz("decode", function(b: buffer)
local s = B3d.decode(Bytes.reader(b))
if s then
MeshOps.merge(s)
end
return s
end, samples, { mutations = 16, keepHeader = 4 })
t:done()
+2 -2
View File
@@ -313,8 +313,8 @@ do
t:check(e and (e.code == Err.CORRUPT or e.code == Err.TRUNCATED), "bad JSON: " .. tostring(e))
local _, e2 = decode('{"asset": {"version": "1.0"}}')
t:check(e2 and e2.code == Err.UNSUPPORTED, "glTF 1: " .. tostring(e2))
local _, e3 = decode('{"asset": {"version": "2.0"}, "extensionsRequired": ["KHR_draco_mesh_compression"]}')
t:check(e3 and e3.code == Err.UNSUPPORTED, "Draco: " .. tostring(e3))
local _, e3 = decode('{"asset": {"version": "2.0"}, "extensionsRequired": ["EXT_meshopt_compression"]}')
t:check(e3 and e3.code == Err.UNSUPPORTED, "meshopt: " .. tostring(e3))
local c = byName["Box/glTF"]
local _, e4 = decode(c.data)
t:check(e4 and e4.code == Err.IO, "missing .bin: " .. tostring(e4))
+164
View File
@@ -0,0 +1,164 @@
-- model/gltf KHR_draco_mesh_compression tests: the Khronos samples compressed by draco_transcoder (two quantizations),
-- Draco's and assimp's Draco glTF files. Every Draco primitive against libdraco's decode of its buffer view (points,
-- faces, index and attribute CRCs); the transcoded files against their uncompressed sources (meshes, primitives,
-- nodes, materials, skins, animations, triangles, world bounds within the quantization step); the scene saved back
-- (uncompressed, without the extension) and reloaded; the fuzz no-throw pass. Fixtures: tools/fixtures/gltf_draco.py.
local T = require("@tests/T")
local Gltf = require("@formats/model/gltf")
local MeshOps = require("@formats/ops/MeshOps")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Cases = require("@tests/gen/gltf_draco")
local t = T.suite("gltf_draco")
local DT = { [1] = "i8", [2] = "u8", [3] = "i16", [4] = "u16", [5] = "i32", [6] = "u32", [9] = "f32" }
local SAME = { i8 = "i8", snorm8 = "i8", u8 = "u8", unorm8 = "u8", i16 = "i16", snorm16 = "i16", u16 = "u16", unorm16 = "u16", i32 = "i32", u32 = "u32", f32 = "f32" }
local function decode(data: string, files: any): (any, any)
return Gltf.decode(Bytes.reader(buffer.fromstring(data)), { files = files })
end
local function triangles(scene: any): number
local n = 0
for _, m in scene.meshes do
for _, p in m.primitives do
if p.mode == "triangles" then
n += if p.indices then p.indices.count // 3 else p.attributes.POSITION.count // 3
end
end
end
return n
end
local checked = { prims = 0, attrs = 0, converted = 0, originals = 0, roundTrips = 0 }
local samples = {}
for _, c in Cases do
local scene, err = decode(c.data, c.files)
t:check(scene, c.name .. ": decode: " .. tostring(err))
if scene then
for _, ref in c.prims do
local label = string.format("%s: mesh %d primitive %d", c.name, ref.mesh, ref.prim)
local prim = scene.meshes[ref.mesh] and scene.meshes[ref.mesh].primitives[ref.prim]
t:check(prim, label .. ": present")
if prim then
t:eq(prim.attributes.POSITION.count, ref.points, label .. ": points")
if ref.faces then
t:eq(prim.indices.count, ref.faces * 3, label .. ": indices")
t:eq(Crc32.of(prim.indices.data), ref.indices, label .. ": index CRC")
end
for name, a in ref.attrs do
local acc = prim.attributes[name]
t:check(acc, label .. ": " .. name)
if acc then
if SAME[acc.type] == DT[a.dataType] then
t:eq(Crc32.of(acc.data), a.crc, label .. ": " .. name .. " values")
checked.attrs += 1
else
checked.converted += 1
end
end
end
checked.prims += 1
end
end
-- against the uncompressed source
local o = c.original
if o then
local orig, oerr = decode(o.data, o.files)
t:check(orig, c.name .. ": original: " .. tostring(oerr))
if orig then
t:eq(#scene.meshes, #orig.meshes, c.name .. ": meshes")
for i, m in orig.meshes do
t:eq(#scene.meshes[i].primitives, #m.primitives, c.name .. ": mesh " .. i .. " primitives")
end
t:eq(#scene.nodes, #orig.nodes, c.name .. ": nodes")
-- draco_transcoder adds a default material to files without one
t:check(#scene.materials == #orig.materials or (#orig.materials == 0 and #scene.materials == 1), c.name .. ": materials")
t:eq(#scene.skins, #orig.skins, c.name .. ": skins")
t:eq(#scene.animations, #orig.animations, c.name .. ": animations")
t:eq(triangles(scene), triangles(orig), c.name .. ": triangles")
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
local olo, ohi = MeshOps.bounds(MeshOps.merge(orig))
if lo and olo then
-- the quantization step relative to the scene: 11-bit positions by default, 16-bit for "fine"
local rel = if string.find(c.name, "fine", 1, true) then 1e-4 else 5e-3
local ok = true
for k = 1, 3 do
local eps = math.max(ohi[k] - olo[k], 1e-6) * rel
if math.abs(lo[k] - olo[k]) > eps or math.abs(hi[k] - ohi[k]) > eps then
ok = false
end
end
t:check(ok, c.name .. ": world bounds within the quantization step")
end
checked.originals += 1
end
end
-- saved back without the extension
local glb = Gltf.encode(scene, { binary = true })
t:check(glb, c.name .. ": encode")
if glb then
t:check(not string.find(buffer.tostring(glb), "KHR_draco_mesh_compression", 1, true), c.name .. ": no Draco extension written")
local again = Gltf.decode(Bytes.reader(glb))
t:check(again and triangles(again) == triangles(scene), c.name .. ": round trip")
checked.roundTrips += 1
end
if #c.data < 6000 and next(c.files) == nil then
table.insert(samples, c.data)
end
end
end
t:note("%d Draco primitives like libdraco (%d attributes byte for byte, %d converted to their accessor type), %d against the uncompressed sources, %d round trips", checked.prims, checked.attrs, checked.converted, checked.originals, checked.roundTrips)
-- an accessor type other than the Draco attribute's: u8 normalized colours declared as f32
do
local Draco = require("@formats/codecs/model/Draco")
local Base64 = require("@formats/core/Base64")
local DracoCases = require("@tests/gen/draco_cases")
local drc
for _, dc in DracoCases do
if dc.name == "enc/test_generic.ply.cl7" then
drc = dc.data
end
end
local g = drc and Draco.decode(drc)
t:check(g, "colour .drc fixture")
if g then
local pos, col
for _, a in g.attributes do
if a.name == "POSITION" then
pos = a
elseif a.name == "COLOR" then
col = a
end
end
local n = g.numPoints
local doc = string.format(
'{"asset":{"version":"2.0"},"extensionsUsed":["KHR_draco_mesh_compression"],"extensionsRequired":["KHR_draco_mesh_compression"],'
.. '"buffers":[{"byteLength":%d,"uri":"data:application/octet-stream;base64,%s"}],"bufferViews":[{"buffer":0,"byteLength":%d}],'
.. '"accessors":[{"componentType":5126,"count":%d,"type":"VEC3"},{"componentType":5126,"count":%d,"type":"VEC%d"},{"componentType":5125,"count":%d,"type":"SCALAR"}],'
.. '"meshes":[{"primitives":[{"attributes":{"POSITION":0,"COLOR_0":1},"indices":2,"extensions":{"KHR_draco_mesh_compression":{"bufferView":0,"attributes":{"POSITION":%d,"COLOR_0":%d}}}}]}],'
.. '"nodes":[{"mesh":0}],"scenes":[{"nodes":[0]}]}',
#drc, Base64.encode(buffer.fromstring(drc)), #drc, n, n, col.components, g.numFaces * 3, pos.uniqueId, col.uniqueId)
local scene, err = decode(doc, {})
t:check(scene, "converted accessor: " .. tostring(err))
if scene then
local acc = scene.meshes[1].primitives[1].attributes.COLOR_0
t:eq(acc.type, "f32", "colour accessor type")
local ok = true
for i = 0, n * col.components - 1 do
local want = buffer.readu8(col.data, i) / 255
if math.abs(buffer.readf32(acc.data, i * 4) - want) > 1e-6 then
ok = false
end
end
t:check(ok, "u8 normalized colours -> f32 / 255")
end
end
end
t:fuzz("decode", function(b: buffer)
return Gltf.decode(Bytes.reader(b))
end, samples, { mutations = 6, garbage = 50 })
t:done()
+319
View File
@@ -0,0 +1,319 @@
-- model/iqm tests: assimp's mrfixit.iqm against assimp (meshes, triangles, vertices, materials, bind pose bounds), an
-- independent Python reader (joints, anims) and the bounds the IQM tool stored per frame (our decoded skeleton and
-- animation, skinned here, must reproduce them); writer round trips (mrfixit, glTF sample models with and without
-- skins) read back by our reader, by assimp and by the Python reader, whose skinning of our files must match ours;
-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/iqm.py.
local T = require("@tests/T")
local Iqm = require("@formats/model/iqm")
local Gltf = require("@formats/model/gltf")
local MeshOps = require("@formats/ops/MeshOps")
local Sampler = require("@formats/codecs/model/Sampler")
local Mat4 = require("@formats/codecs/model/Mat4")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Cases = require("@tests/gen/iqm_cases")
local Picks = require("@tests/gen/iqm_gltf")
local Xcheck = require("@tests/gen/iqm_xcheck")
local t = T.suite("iqm")
local S = Types.Scene
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Iqm.decode(Bytes.reader(b), opts)
end
t:eq(Iqm.name, "iqm", "name")
t:eq(Iqm.category, "model", "category")
t:check(Iqm.caps.decode and Iqm.caps.encode, "caps")
local function near(a: number, b: number, eps: number): boolean
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
end
-- the largest coordinate difference between two boxes
local function boxDiff(lo: { number }, hi: { number }, want: any): number
local d = 0
for k = 1, 3 do
d = math.max(d, math.abs(lo[k] - want.min[k]), math.abs(hi[k] - want.max[k]))
end
return d
end
local function boxNear(lo: { number }, hi: { number }, want: any, eps: number): boolean
for k = 1, 3 do
if not near(lo[k], want.min[k], eps) or not near(hi[k], want.max[k], eps) then
return false
end
end
return true
end
-- assimp's IQM root turns z-up into y-up: (x, y, z) -> (x, z, -y)
local function zUpToY(lo: { number }, hi: { number }): ({ number }, { number })
return { lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] }
end
local function counts(scene: any): (number, number, number)
local prims, tris, verts = 0, 0, 0
for _, m in scene.meshes do
for _, p in m.primitives do
prims += 1
tris += p.indices.count // 3
verts += p.attributes.POSITION.count
end
end
return prims, tris, verts
end
-- the bounding box of every mesh vertex, skinned with the scene's skins at time t of anim (nil: the rest pose)
local function skinnedBounds(scene: any, anim: any?, time: number): ({ number }, { number })
local pose = if anim then Sampler.pose(scene, anim, time) else nil
local parent = {}
for i, n in scene.nodes do
for _, c in n.children do
parent[c] = i
end
end
local world = {}
local function W(i: number): { number }
if world[i] then
return world[i]
end
local node = scene.nodes[i]
local over = pose and pose[i]
local m
if over then
m = Mat4.compose(over.translation or node.translation, over.rotation or node.rotation, over.scale or node.scale)
else
m = S.nodeMatrix(node)
end
if parent[i] then
m = S.mul(W(parent[i]), m)
end
world[i] = m
return m
end
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
for ni, node in scene.nodes do
local mesh = node.mesh and scene.meshes[node.mesh]
if mesh then
local skin = node.skin and scene.skins[node.skin]
local mats = {}
if skin then
local ibm = assert(S.reader(skin.inverseBindMatrices))
for j, jn in skin.joints do
local inv = {}
for k = 1, 16 do
inv[k] = ibm(j - 1, k - 1)
end
mats[j - 1] = S.mul(W(jn), inv)
end
end
local LINES = { points = true, lines = true, line_strip = true, line_loop = true }
for _, p in mesh.primitives do
if LINES[p.mode] then
continue
end
local P = assert(S.reader(p.attributes.POSITION))
local J = p.attributes.JOINTS_0 and S.reader(p.attributes.JOINTS_0)
local Wt = p.attributes.WEIGHTS_0 and S.reader(p.attributes.WEIGHTS_0)
for v = 0, p.attributes.POSITION.count - 1 do
local x, y, z = P(v, 0), P(v, 1), P(v, 2)
if skin and J and Wt then
local sx, sy, sz = 0, 0, 0
for c = 0, 3 do
local w = Wt(v, c)
if w > 0 then
local qx, qy, qz = Mat4.point(mats[J(v, c)], x, y, z)
sx, sy, sz = sx + w * qx, sy + w * qy, sz + w * qz
end
end
x, y, z = sx, sy, sz
else
x, y, z = Mat4.point(W(ni), x, y, z)
end
lo = { math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z) }
hi = { math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z) }
end
end
end
end
return lo, hi
end
local function xcheck(name: string): any
for _, x in Xcheck do
if x.name == name then
return x
end
end
return nil
end
-- ------------------------------------------------------------------------------------------------ mrfixit
local fixit = Cases[1]
local scene, err = decode(fixit.data)
t:check(scene, "mrfixit: decode " .. tostring(err))
do
local a, ref = fixit.assimp, fixit.ref
local prims, tris, verts = counts(scene)
t:eq(prims, a.meshes, "mrfixit: meshes (assimp)")
t:eq(tris, a.faces, "mrfixit: triangles (assimp)")
t:eq(verts, a.vertices, "mrfixit: vertices (assimp)")
t:eq(#scene.materials, a.materials, "mrfixit: materials (assimp)")
t:eq(scene.textures[scene.materials[1].baseColorTexture.texture].uri, "Body.jpg", "mrfixit: material string -> texture uri")
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
local ylo, yhi = zUpToY(lo, hi)
t:check(boxNear(ylo, yhi, a, 1e-4), string.format("mrfixit: bind pose bounds (assimp) %s / %s", table.concat(ylo, " "), table.concat(yhi, " ")))
t:eq(#scene.skins, 1, "mrfixit: one skin")
t:eq(#scene.skins[1].joints, ref.joints, "mrfixit: joints (Python reader)")
for j, n in scene.skins[1].joints do
t:eq(scene.nodes[n].name, ref.jointNames[j], "mrfixit: joint name " .. j)
end
t:eq(#scene.animations, #ref.anims, "mrfixit: animations")
t:eq(scene.animations[1].name, ref.anims[1].name, "mrfixit: animation name")
t:eq(scene.meta.source.animations[1].frames, ref.anims[1].frames, "mrfixit: frames")
local prim = scene.meshes[1].primitives[1]
t:check(prim.attributes.JOINTS_0 and prim.attributes.WEIGHTS_0.type == "unorm8", "mrfixit: blend indexes / weights")
t:check(prim.attributes.TANGENT and prim.attributes.TANGENT.components == 4, "mrfixit: tangents")
-- the bounds the IQM tool stored, from our skeleton + animation (and the Python reader's skinning agrees)
local fps = ref.anims[1].framerate
-- (the tool computed its bounds before quantizing the frames: up to 0.1% off the quantized animation)
local worst, worstPy = 0, 0
for f = 1, ref.frames, 5 do
local l, h = skinnedBounds(scene, scene.animations[1], (f - 1) / fps)
worst = math.max(worst, boxDiff(l, h, ref.stored[f]))
worstPy = math.max(worstPy, boxDiff(l, h, ref.skinned[f]))
t:check(boxDiff(ref.skinned[f].min, ref.skinned[f].max, ref.stored[f]) < 1e-2, "mrfixit: the Python reader reproduces the stored bounds, frame " .. f)
end
t:check(worst < 1e-2, "mrfixit: skinned bounds per frame match the IQM tool's (worst " .. worst .. ")")
t:check(worstPy < 1e-4, "mrfixit: skinned bounds per frame match the Python reader's (worst " .. worstPy .. ")")
t:check(scene.meta.source.bounds and #scene.meta.source.bounds == ref.frames, "mrfixit: bounds block read")
end
-- ------------------------------------------------------------------------------------------------ round trips
do
local out = assert(Iqm.encode(scene))
local back = assert(decode(out))
local p1, t1, v1 = counts(scene)
local p2, t2, v2 = counts(back)
t:check(p1 == p2 and t1 == t2 and v1 == v2, "round trip: counts")
-- positions and indices exact
local same = true
for mi, m in scene.meshes do
local a, b = m.primitives[1], back.meshes[mi].primitives[1]
t:check(buffer.tostring(a.attributes.POSITION.data) == buffer.tostring(b.attributes.POSITION.data), "round trip: positions exact, mesh " .. mi)
t:check(buffer.tostring(a.indices.data) == buffer.tostring(b.indices.data), "round trip: triangles exact, mesh " .. mi)
-- influences: the same (joint, weight) pairs (unused slots and their order may differ)
local ja, wa, jb, wb = S.reader(a.attributes.JOINTS_0), S.reader(a.attributes.WEIGHTS_0), S.reader(b.attributes.JOINTS_0), S.reader(b.attributes.WEIGHTS_0)
for v = 0, a.attributes.POSITION.count - 1 do
local inf = {}
for c = 0, 3 do
if (wa :: any)(v, c) > 0 then
inf[(ja :: any)(v, c)] = (inf[(ja :: any)(v, c)] or 0) + (wa :: any)(v, c)
end
end
for c = 0, 3 do
local w = (wb :: any)(v, c)
if w > 0 then
local j = (jb :: any)(v, c)
same = same and inf[j] ~= nil and math.abs(inf[j] - w) < 1.5 / 255
inf[j] = nil
end
end
same = same and next(inf) == nil
end
end
t:check(same, "round trip: the same influences")
t:eq(#back.skins[1].joints, #scene.skins[1].joints, "round trip: joints")
t:eq(back.meta.source.animations[1].frames, scene.meta.source.animations[1].frames, "round trip: frames")
local worst = 0
for _, time in { 0, 0.5, 1.5, 3 } do
local l1, h1 = skinnedBounds(scene, scene.animations[1], time)
local l2, h2 = skinnedBounds(back, back.animations[1], time)
for k = 1, 3 do
worst = math.max(worst, math.abs(l1[k] - l2[k]), math.abs(h1[k] - h2[k]))
end
end
t:check(worst < 2e-3, "round trip: the animation skins the same (worst " .. worst .. ")")
-- assimp and the Python reader on our file
local x = assert(xcheck("rt_mrfixit.iqm"), "xcheck rt_mrfixit")
t:eq(x.assimp.faces, fixit.assimp.faces, "round trip: assimp triangles")
t:eq(x.assimp.vertices, fixit.assimp.vertices, "round trip: assimp vertices")
t:check(boxNear(x.assimp.min, x.assimp.max, fixit.assimp, 1e-4), "round trip: assimp bounds")
local w2, w3 = 0, 0
for f, box in fixit.ref.skinned do
local mine = x.ref.skinned[f]
w2 = math.max(w2, boxDiff(mine.min, mine.max, box))
w3 = math.max(w3, boxDiff(x.ref.stored[f].min, x.ref.stored[f].max, mine))
end
t:check(w2 < 2e-3, "round trip: the Python reader skins our file like the original (worst " .. w2 .. ")")
t:check(w3 < 1e-4, "round trip: our bounds block matches the Python skinning (worst " .. w3 .. ")")
end
-- glTF sample models through the writer
for _, p in Picks do
local g = assert(Gltf.decode(Bytes.reader(buffer.fromstring(p.data)), { files = p.files }))
local out, e = Iqm.encode(g)
t:check(out, p.name .. ": encode " .. tostring(e))
local back = assert(decode(out))
local x = assert(xcheck("gltf_" .. p.name .. ".iqm"), "xcheck " .. p.name)
local _, tris, verts = counts(back)
t:eq(x.assimp.faces, tris, p.name .. ": assimp reads our triangles")
t:eq(x.assimp.vertices, verts, p.name .. ": assimp reads our vertices")
-- unskinned: the glTF scene's world bounds (skinned: IQM's rest pose is the bind pose, checked by the frames below)
local l2, h2 = skinnedBounds(back, nil, 0)
if #g.skins == 0 then
local lo, hi = skinnedBounds(g, nil, 0)
t:check(boxNear(l2, h2, { min = lo, max = hi }, 1e-4), p.name .. ": world bounds kept")
end
local yl, yh = zUpToY(l2, h2)
t:check(boxNear(yl, yh, x.assimp, 1e-3), p.name .. ": assimp bounds of our file")
if #g.skins > 0 and #g.animations > 0 then
local anim = x.ref.anims[1]
local worst = 0
for f = 1, x.ref.frames do
local l, h = skinnedBounds(g, g.animations[1], (f - 1) / anim.framerate)
local py = x.ref.skinned[f]
for k = 1, 3 do
worst = math.max(worst, math.abs(l[k] - py.min[k]), math.abs(h[k] - py.max[k]))
end
end
t:check(worst < 5e-3, p.name .. ": the Python reader skins our file like the glTF animation (worst " .. worst .. ")")
t:eq(#back.skins[1].joints, #g.skins[1].joints, p.name .. ": joints")
end
end
-- ------------------------------------------------------------------------------------------------ errors
do
local _, e1 = decode("INTERQUAKEMODEL\0")
t:check(e1 and e1.code == Err.TRUNCATED, "short: " .. tostring(e1))
local bad = buffer.fromstring(fixit.data)
buffer.writeu32(bad, 16, 1)
local _, e2 = decode(bad)
t:check(e2 and e2.code == Err.UNSUPPORTED, "version 1: " .. tostring(e2))
local cut = buffer.fromstring(string.sub(fixit.data, 1, 5000))
local _, e3 = decode(cut)
t:check(e3 and e3.code == Err.TRUNCATED, "cut: " .. tostring(e3))
local _, e4 = decode(fixit.data, { maxVertices = 100 })
t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4))
local _, e5 = Iqm.encode({} :: any)
t:check(e5 and e5.code == Err.ARG, "encode junk")
local _, e6 = Iqm.encode(S.new())
t:check(e6 and e6.code == Err.ARG, "encode an empty scene: " .. tostring(e6))
t:eq(Iqm.sniff(Bytes.reader(buffer.fromstring(fixit.data))), 1, "sniff")
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local small = assert(Iqm.encode(assert(Gltf.decode(Bytes.reader(buffer.fromstring(Picks[2].data)), { files = Picks[2].files }))))
local samples = { small, string.sub(fixit.data, 1, 20000) }
t:fuzz("decode", function(b: buffer)
local s = Iqm.decode(Bytes.reader(b))
if s then
Iqm.encode(s)
end
return s
end, samples, { mutations = 24, keepHeader = 16 })
end
t:done()
+226
View File
@@ -0,0 +1,226 @@
-- model/ldraw tests: hand-written LDraw files (a brick of primitives found through library paths, an MPD with
-- embedded parts and sub-models, BFC CW / CCW / INVERTNEXT / NOCLIP / uncertified files, mirrored references, colours
-- 16 / 24 / direct / local !COLOUR, optional lines, a missing part, a self-reference, bad lines, CRLF) and real library
-- parts and models (3001, 3062b, 4073, 3626c, car.ldr, pyramid.ldr) against an independent expansion in the generator
-- (world triangles per colour, double-sided faces, lines, area, signed volume of the one-sided faces, bounds, missing
-- files) and LeoCAD's OBJ export (bounds, area); node / flattened / un-flipped scenes agree; mesh sharing; the
-- built-in colour table against LDConfig.ldr; resolve; error codes; the fuzz no-throw pass. Fixtures:
-- tools/fixtures/ldraw.py.
local T = require("@tests/T")
local Ldraw = require("@formats/model/ldraw")
local MeshOps = require("@formats/ops/MeshOps")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Cases = require("@tests/gen/ldraw_cases")
local Config = require("@tests/gen/ldraw_config")
local t = T.suite("ldraw")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Ldraw.decode(Bytes.reader(b), opts)
end
local function near(a: number, b: number, eps: number): boolean
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
end
t:eq(Ldraw.name, "ldraw", "name")
t:eq(Ldraw.category, "model", "category")
t:check(Ldraw.caps.decode and not Ldraw.caps.encode, "caps")
t:check(Ldraw.sniff(Bytes.reader(buffer.fromstring("0 FILE main.ldr\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 a.dat\n"))) >= 0.9, "sniff MPD")
t:check(Ldraw.sniff(Bytes.reader(buffer.fromstring("0 x\n1 16 0 0 0 1 0 0 0 1 0 0 0 1 3001.dat\n"))) >= 0.8, "sniff LDR")
t:eq(Ldraw.sniff(Bytes.reader(buffer.fromstring("solid cube\n facet normal 0 0 1\n"))), 0, "sniff other")
-- ------------------------------------------------------------------------------------------------ colour table
do
local tbl = Ldraw.colors()
local bad = 0
for _, c in Config.colours do
local e = tbl[c[1]]
if not e or e.rgb ~= c[2] or e.edge ~= c[3] or e.alpha ~= c[4] then
bad += 1
end
end
t:eq(bad, 0, "built-in colours = LDConfig.ldr (" .. #Config.colours .. " colours)")
local over = Ldraw.colors("0 !COLOUR Mine CODE 4 VALUE #010203 EDGE 0\n")
t:check(over[4].rgb == 0x010203 and over[4].edge == 0 and over[4].name == "Mine", "ldconfig overrides")
end
-- ------------------------------------------------------------------------------------------------ measuring
type Stats = { triangles: number, lines: number, optional: number, ds: number, area: number, volume: number, colours: { [number]: number } }
local function det3(m: { number }): number
return m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3])
end
local function measure(scene: any): Stats
local s: Stats = { triangles = 0, lines = 0, optional = 0, ds = 0, area = 0, volume = 0, colours = {} }
for _, pl in Types.Scene.flatten(scene) do
local p = pl.primitive
local n = p.attributes.POSITION.count
if p.mode == "lines" then
if p.extras and p.extras.ldraw and p.extras.ldraw.optional then
s.optional += n // 2
else
s.lines += n // 2
end
else
local mat = scene.materials[p.material]
local code = mat.extras.ldraw.code
s.colours[code] = (s.colours[code] or 0) + n // 3
s.triangles += n // 3
if mat.doubleSided then
s.ds += n // 3
end
local m = pl.matrix
local flip = det3(m) < 0
local get = assert(Types.Scene.reader(p.attributes.POSITION))
for tri = 0, n // 3 - 1 do
local q = {}
for k = 0, 2 do
local x, y, z = get(tri * 3 + k, 0), get(tri * 3 + k, 1), get(tri * 3 + k, 2)
q[k + 1] = { m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] }
end
local a, b, c = q[1], q[2], q[3]
if flip then
a, c = c, a
end
local ux, uy, uz, vx, vy, vz = b[1] - a[1], b[2] - a[2], b[3] - a[3], c[1] - a[1], c[2] - a[2], c[3] - a[3]
local x, y, z = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
s.area += math.sqrt(x * x + y * y + z * z) / 2
if not mat.doubleSided then
s.volume += (a[1] * (b[2] * c[3] - b[3] * c[2]) - a[2] * (b[1] * c[3] - b[3] * c[1]) + a[3] * (b[1] * c[2] - b[2] * c[1])) / 6
end
end
end
end
return s
end
local function compare(label: string, s: Stats, w: any)
t:eq(s.triangles, w.triangles, label .. ": triangles")
t:eq(s.ds, w.doubleSided, label .. ": double-sided triangles")
t:eq(s.lines, w.lines, label .. ": lines")
local bad = {}
for _, pair in w.colours do
if s.colours[pair[1]] ~= pair[2] then
table.insert(bad, string.format("%d: %s / %d", pair[1], tostring(s.colours[pair[1]]), pair[2]))
end
end
t:check(#bad == 0 and #w.colours == #(function()
local keys = {}
for k in s.colours do
table.insert(keys, k)
end
return keys
end)(), label .. ": triangles per colour " .. table.concat(bad, ", "))
t:check(near(s.area, w.area, 1e-5), string.format("%s: area %.6f / %.6f", label, s.area, w.area))
t:check(near(s.volume, w.volume, 1e-5), string.format("%s: signed volume %.6f / %.6f", label, s.volume, w.volume))
end
-- ------------------------------------------------------------------------------------------------ cases
local samples = {}
local lib: any = nil
for _, c in Cases do
local opts = table.clone(c.opts or {})
opts.files = c.files
local scene, err = decode(c.data, opts)
t:check(scene, c.name .. ": decode: " .. tostring(err))
local w = c.want
compare(c.name, measure(scene), w)
local lo, hi = MeshOps.bounds(assert(MeshOps.merge(scene)))
local ok = lo ~= nil and w.min ~= nil
for k = 1, 3 do
ok = ok and near((lo :: any)[k], w.min[k], 1e-5) and near((hi :: any)[k], w.max[k], 1e-5)
end
t:check(ok, string.format("%s: bounds %s / %s", c.name, table.concat(lo or {}, " "), table.concat(hi or {}, " ")))
t:eq(table.concat(scene.meta.source.missing, ","), table.concat(w.missing, ","), c.name .. ": missing files")
t:check(scene.meta.up == "y" and scene.meta.unit == 0.0004, c.name .. ": meta.up / unit")
-- LeoCAD: its axes are (x, -z, y) of ours, 2 decimals
local lc = c.leocad
if lc then
local lmin = { lo[1], -hi[3], lo[2] }
local lmax = { hi[1], -lo[3], hi[2] }
local good = true
for k = 1, 3 do
good = good and math.abs(lmin[k] - lc.min[k]) < 0.02 and math.abs(lmax[k] - lc.max[k]) < 0.02
end
t:check(good, c.name .. ": bounds (LeoCAD)")
local s = measure(scene)
t:check(near(s.area, lc.area, 2e-4), string.format("%s: area %.3f (LeoCAD %.3f)", c.name, s.area, lc.area))
end
-- the same model flattened into one mesh, and without the root flip
local flat = assert(decode(c.data, { files = c.files, flatten = true }))
t:eq(#flat.meshes <= 1, true, c.name .. ": flatten: one mesh")
compare(c.name .. " (flatten)", measure(flat), w)
local raw = assert(decode(c.data, { files = c.files, upright = false }))
local rlo, rhi = MeshOps.bounds(assert(MeshOps.merge(raw)))
t:check(rlo and near(rlo[2], -hi[2], 1e-6) and near(rhi[3], -lo[3], 1e-6) and raw.meta.source.up == "-y", c.name .. ": upright = false")
if #c.data < 4000 then
table.insert(samples, c.data)
end
if c.name == "two.ldr" then
lib = c.files
-- one mesh per (part, colour): four colours, the missing part has no node
t:eq(#scene.meshes, 4, "two.ldr: meshes per colour")
local root = scene.nodes[scene.roots[1]]
t:eq(#root.children, 4, "two.ldr: one node per placed part")
local steps = {}
for _, ci in root.children do
table.insert(steps, scene.nodes[ci].extras.ldraw.step)
end
t:eq(table.concat(steps, ","), "1,1,1,2", "two.ldr: steps")
-- through resolve instead of files
local viaResolve = assert(decode(c.data, { resolve = function(uri: string): any
return c.files[uri]
end }))
t:eq(measure(viaResolve).triangles, w.triangles, "two.ldr: resolve")
-- optional lines on request
local withOpt = assert(decode(c.data, { files = c.files, optionalLines = true, lines = false }))
local so = measure(withOpt)
t:check(so.optional == w.optional and so.lines == 0, "two.ldr: optional lines only")
elseif c.name == "model.mpd" then
t:check(scene.meta.source.mpd, "model.mpd: mpd")
local meshNodes = 0
for _, n in scene.nodes do
if n.mesh then
meshNodes += 1
end
end
t:check(#scene.meshes < meshNodes, string.format("model.mpd: meshes shared (%d meshes, %d mesh nodes)", #scene.meshes, meshNodes))
local purple
for _, m in scene.materials do
if m.extras.ldraw.code == 1000 then
purple = m
end
end
t:check(purple and purple.name == "Test_Purple" and purple.alphaMode == "blend", "model.mpd: local !COLOUR")
elseif c.name == "badrefs.ldr" then
t:check(scene.meta.source.cycles > 0 and scene.meta.source.badLines == 2, "badrefs.ldr: cycle and bad lines counted")
end
end
-- ------------------------------------------------------------------------------------------------ errors
do
local _, e = decode("")
t:check(e and e.code == Err.CORRUPT, "empty: CORRUPT")
_, e = decode("hello world\nthis is not ldraw\n")
t:check(e and e.code == Err.CORRUPT, "text: CORRUPT")
_, e = decode(Cases[1].data, { files = Cases[1].files, maxTriangles = 10 })
t:check(e and e.code == Err.LIMIT, "maxTriangles: LIMIT")
_, e = decode(Cases[1].data, { files = Cases[1].files, maxDepth = 0 })
t:check(e and e.code == Err.LIMIT, "maxDepth: LIMIT")
end
-- ------------------------------------------------------------------------------------------------ fuzz
t:fuzz("decode", function(b: buffer)
local s = Ldraw.decode(Bytes.reader(b), { files = lib, optionalLines = true })
if s then
MeshOps.merge(s)
end
return s
end, samples, { mutations = 24 })
t:done()
+315
View File
@@ -0,0 +1,315 @@
-- model/lwo tests: assimp's LightWave test models (LWO2, LWOB, Modo LXOB) against assimp (meshes per layer and
-- surface, polygons, corners, materials, world bounds); layer hierarchy and pivots, UV / colour / normal maps,
-- surfaces and image blocks; a hand-built LWO2 (VMAD splits, MORF / SPOT targets, weight maps, lines, points, skipped
-- curves, PTCH flag, derived surface, XREF clip); errors; the fuzz no-throw pass. Fixtures: tools/fixtures/lwo.py.
local T = require("@tests/T")
local Lwo = require("@formats/model/lwo")
local MeshOps = require("@formats/ops/MeshOps")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Cases = require("@tests/gen/lwo_cases")
local t = T.suite("lwo")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Lwo.decode(Bytes.reader(b), opts)
end
t:eq(Lwo.name, "lwo", "name")
t:eq(Lwo.category, "model", "category")
t:check(Lwo.caps.decode and not Lwo.caps.encode, "caps")
local function near(a: number, b: number, eps: number): boolean
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
end
-- assimp's counts: one mesh per (layer, surface), polygons, corners
local function counts(scene: any): (number, number, number)
local meshes, faces, corners = 0, 0, 0
for _, m in scene.meshes do
local mats = {}
for _, p in m.primitives do
if not mats[p.material] then
mats[p.material] = true
meshes += 1
end
local n = if p.indices then p.indices.count else p.attributes.POSITION.count
corners += n
faces += if p.mode == "polygons" then p.faces.count elseif p.mode == "lines" then n // 2 elseif p.mode == "points" then n else n // 3
end
end
return meshes, faces, corners
end
local function find(name: string): any
for _, c in Cases do
if c.name == name then
return c
end
end
return nil
end
-- ------------------------------------------------------------------------------------------------ assimp
local checked, scenes = 0, {}
for i, c in Cases do
local a = c.assimp
local scene, err = decode(c.data, { triangulate = false })
if a.failed then
t:note("%s: assimp rejects it; we: %s", c.name, if scene then "decoded" else tostring(err))
else
t:check(scene, c.name .. ": decode: " .. tostring(err))
if scene then
scenes[i] = scene
local meshes, faces, corners = counts(scene)
-- LXOB / LWOB files: assimp's material and surface handling differs (MATR tags, flattened detail polygons)
t:eq(meshes, a.meshes, c.name .. ": meshes (assimp)")
t:eq(faces, a.faces, c.name .. ": polygons (assimp)")
t:eq(corners, a.vertices, c.name .. ": corners (assimp)")
t:eq(#scene.materials, a.materials, c.name .. ": materials (assimp)")
if a.min then
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
local ok = lo ~= nil
for k = 1, 3 do
ok = ok and near(lo[k], a.min[k], 1e-4) and near(hi[k], a.max[k], 1e-4)
end
t:check(ok, string.format("%s: world bounds (assimp) %s / %s", c.name, if lo then table.concat(lo, " ") else "-", if hi then table.concat(hi, " ") else "-"))
end
-- triangulated: the same corners as triangles
local tri = decode(c.data)
t:check(tri and tri.meshes[1] and tri.meshes[1].primitives[1].mode ~= "polygons", c.name .. ": triangulated by default")
checked += 1
end
end
end
t:note("%d files checked against assimp", checked)
-- ------------------------------------------------------------------------------------------------ details
do
local c = find("models/LWO2/hierarchy.lwo")
local s = decode(c.data)
local byName = {}
for i, n in s.nodes do
byName[n.name] = i
end
local root, child0, grand = byName.RootOfHierarchy, byName.ChildOfRoot0, byName.GrandChildOfRoot0
t:check(root and child0 and grand and byName.ChildOfRoot1, "hierarchy: layer names")
t:check(table.find(s.roots, root) ~= nil and #s.roots == 1, "hierarchy: one root layer")
t:check(table.find(s.nodes[root].children, child0) ~= nil, "hierarchy: ChildOfRoot0 under RootOfHierarchy")
t:check(table.find(s.nodes[child0].children, grand) ~= nil, "hierarchy: GrandChildOfRoot0 under ChildOfRoot0")
local p = s.nodes[child0].extras.lwo.pivot
t:check(p and #p == 3, "hierarchy: pivot kept in extras")
-- weight maps -> _WEIGHT_n (no skeleton in LWO)
local prim = s.meshes[s.nodes[root].mesh].primitives[1]
t:check(prim.attributes._WEIGHT_0 and prim.attributes._WEIGHT_1, "hierarchy: weight maps as _WEIGHT_n")
t:check(prim.extras.lwo.maps._WEIGHT_0 ~= nil, "hierarchy: weight map names")
end
do
local c = find("models/LWO2/boxuv.lwo")
local s = decode(c.data)
local mat = s.materials[1]
t:check(mat.baseColorTexture, "boxuv: COLR image block -> baseColorTexture")
local tex = s.textures[mat.baseColorTexture.texture]
t:eq(tex.uri, "boxuv.png", "boxuv: texture uri")
t:eq(tex.mime, "image/png", "boxuv: texture mime")
local prim = s.meshes[1].primitives[1]
local uv = prim.attributes.TEXCOORD_0
t:check(uv and uv.count == prim.attributes.POSITION.count, "boxuv: TEXCOORD_0")
local inRange = true
local get = assert(Types.Scene.reader(uv))
for i = 0, uv.count - 1 do
local u, v = get(i, 0), get(i, 1)
inRange = inRange and u >= -1e-6 and u <= 1 + 1e-6 and v >= -1e-6 and v <= 1 + 1e-6
end
t:check(inRange, "boxuv: uvs in 0..1")
end
do
local c = find("models/LWO2/box_2vc_1unused.lwo")
local s = decode(c.data)
local any = false
for _, p in s.meshes[1].primitives do
any = any or (p.attributes.COLOR_0 ~= nil or p.attributes._COLOR_0 ~= nil)
end
t:check(any, "box_2vc: colour maps")
local mat = s.materials[1]
t:check(mat.extras.lwo.vcol ~= nil, "box_2vc: surface VCOL map name")
end
do
local c = find("models/LWO2/ModoExport_vertNormals.lwo")
local s = decode(c.data)
local prim = s.meshes[1].primitives[1]
t:check(prim.attributes.NORMAL, "Modo NORM map -> NORMAL")
local get = assert(Types.Scene.reader(prim.attributes.NORMAL))
local len = math.sqrt(get(0, 0) ^ 2 + get(0, 1) ^ 2 + get(0, 2) ^ 2)
t:check(near(len, 1, 1e-3), "Modo normals are unit length")
end
do
local c = find("models/LWO2/Subdivision.lwo")
local s = decode(c.data)
t:check(s.meshes[1].primitives[1].extras.lwo.subdivision == true, "PTCH cage flagged")
local lx = find("models/LXOB_Modo/sphereWithVertMap.lxo")
local sx = decode(lx.data)
t:eq(sx.meta.source.version, "LXOB", "LXOB version")
t:check(sx.meshes[1].primitives[1].attributes.NORMAL, "LXOB normals")
local lb = find("models/LWOB/sphere_with_mat_gloss_10pc.lwo")
local sb = decode(lb.data)
t:eq(sb.meta.source.version, "LWOB", "LWOB version")
t:check(sb.materials[1].extras.lwo.glos ~= nil, "LWOB glossiness")
end
-- ------------------------------------------------------------------------------------------------ hand-built LWO2
local function be16(n: number): string
return string.char(bit32.band(bit32.rshift(n, 8), 255), bit32.band(n, 255))
end
local function be32(n: number): string
return be16(bit32.rshift(n, 16)) .. be16(bit32.band(n, 0xFFFF))
end
local function f4(x: number): string
local b = buffer.create(4)
buffer.writef32(b, 0, x)
return be32(buffer.readu32(b, 0))
end
local function s0(s: string): string
s ..= "\0"
return if #s % 2 == 1 then s .. "\0" else s
end
local function chunk(id: string, body: string): string
return id .. be32(#body) .. body .. (if #body % 2 == 1 then "\0" else "")
end
local function sub(id: string, body: string): string
return id .. be16(#body) .. body .. (if #body % 2 == 1 then "\0" else "")
end
local function form(body: string): string
return "FORM" .. be32(#body + 4) .. "LWO2" .. body
end
local function quadFile(): string
local pts = ""
for _, p in { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 }, { 2, 0, 0 }, { 3, 0, 0 } } do
pts ..= f4(p[1]) .. f4(p[2]) .. f4(p[3])
end
local pols = "FACE" .. be16(4) .. be16(0) .. be16(1) .. be16(2) .. be16(3) -- 0: quad
.. be16(2) .. be16(4) .. be16(5) -- 1: a line
.. be16(1) .. be16(5) -- 2: a point
local curv = "CURV" .. be16(2) .. be16(0) .. be16(4) -- 3: skipped
local ptch = "PTCH" .. be16(3) .. be16(0) .. be16(1) .. be16(2) -- 4: a patch
local uv = "TXUV" .. be16(2) .. s0("UV")
for i, v in { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } } do
uv ..= be16(i - 1) .. f4(v[1]) .. f4(v[2])
end
local vmad = "TXUV" .. be16(2) .. s0("UV") .. be16(0) .. be16(0) .. f4(0.5) .. f4(0.25) -- point 0 in polygon 0
local morf = "MORF" .. be16(3) .. s0("up") .. be16(2) .. f4(0) .. f4(0) .. f4(1)
local spot = "SPOT" .. be16(3) .. s0("moved") .. be16(1) .. f4(1) .. f4(2) .. f4(0)
local wght = "WGHT" .. be16(1) .. s0("bone") .. be16(3) .. f4(0.75)
local tags = s0("Base") .. s0("Child")
local base = s0("Base") .. s0("") .. sub("COLR", f4(1) .. f4(0) .. f4(0) .. be16(0)) .. sub("TRAN", f4(0.25) .. be16(0)) .. sub("SIDE", be16(3))
local blok = sub("IMAP", s0("\128") .. sub("CHAN", "COLR") .. sub("ENAB", be16(1))) .. sub("PROJ", be16(5)) .. sub("IMAG", be16(2)) .. sub("VMAP", s0("UV"))
local child = s0("Child") .. s0("Base") .. sub("LUMI", f4(0.5) .. be16(0)) .. sub("BLOK", blok)
local ptag = "SURF" .. be16(0) .. be16(0) .. be16(1) .. be16(1) .. be16(2) .. be16(1)
local ptag2 = "SURF" .. be16(0) .. be16(1)
return form(chunk("TAGS", tags) .. chunk("LAYR", be16(0) .. be16(0) .. f4(0.5) .. f4(0) .. f4(0) .. s0("Main")) .. chunk("PNTS", pts)
.. chunk("VMAP", uv) .. chunk("VMAP", morf) .. chunk("VMAP", spot) .. chunk("VMAP", wght)
.. chunk("POLS", pols) .. chunk("PTAG", ptag) .. chunk("VMAD", vmad) .. chunk("POLS", curv) .. chunk("POLS", ptch) .. chunk("PTAG", ptag2)
.. chunk("CLIP", be32(1) .. sub("STIL", s0("C:\\images\\Wood.PNG"))) .. chunk("CLIP", be32(2) .. sub("XREF", be32(1) .. s0("ref")))
.. chunk("SURF", base) .. chunk("SURF", child)
.. chunk("LAYR", be16(1) .. be16(0) .. f4(0.5) .. f4(1) .. f4(2) .. s0("Sub") .. be16(0)))
end
do
local data = quadFile()
local s, err = decode(data, { triangulate = false })
t:check(s, "hand-built: decode " .. tostring(err))
t:eq(#s.nodes, 2, "hand-built: two layers")
local main, subl = s.nodes[1], s.nodes[2]
t:eq(main.name, "Main", "hand-built: layer name")
t:check(table.find(main.children, 2) ~= nil and #s.roots == 1, "hand-built: Sub is a child of Main")
t:check(main.translation and main.translation[1] == 0.5, "hand-built: Main pivot translation")
t:check(subl.translation and subl.translation[2] == 1 and subl.translation[3] == -2, "hand-built: Sub pivot relative to Main, z negated")
t:eq(s.meta.source.skipped.CURV, 1, "hand-built: curve skipped and counted")
local mesh = s.meshes[main.mesh]
local modes = {}
for _, p in mesh.primitives do
modes[#modes + 1] = p.mode .. "/" .. p.material .. (if p.extras.lwo.subdivision then "/patch" else "")
end
t:eq(table.concat(modes, " "), "polygons/1 polygons/2/patch lines/2 points/2", "hand-built: primitives by surface and kind")
local quad = mesh.primitives[1]
t:eq(quad.attributes.POSITION.count, 4, "hand-built: quad vertices")
-- winding reversed, positions relative to the pivot, z negated
local idx = {}
for k = 0, 3 do
idx[k + 1] = buffer.readu32(quad.indices.data, k * 4)
end
local P = assert(Types.Scene.reader(quad.attributes.POSITION))
local UV = assert(Types.Scene.reader(quad.attributes.TEXCOORD_0))
t:eq(P(idx[1], 0), -0.5, "hand-built: x relative to the pivot")
t:eq(P(idx[2], 0), -0.5, "hand-built: winding reversed (second corner is point 3)")
t:eq(P(idx[2], 1), 1, "hand-built: second corner y")
t:eq(UV(idx[1], 0), 0.5, "hand-built: VMAD u")
t:eq(UV(idx[1], 1), 0.75, "hand-built: VMAD v flipped")
t:eq(UV(idx[3], 1), 0, "hand-built: VMAP v flipped (point 2: 1 -> 0)")
t:check(quad.targets and #quad.targets == 2, "hand-built: MORF + SPOT targets")
local T1 = assert(Types.Scene.reader(quad.targets[1].POSITION))
local T2 = assert(Types.Scene.reader(quad.targets[2].POSITION))
t:eq(T1(idx[3], 2), -1, "hand-built: MORF delta (z negated)")
t:eq(T2(idx[4], 1), 2, "hand-built: SPOT -> delta (point 1: y 0 -> 2)")
t:eq(mesh.weights and #mesh.weights, 2, "hand-built: mesh weights")
t:eq(mesh.extras.targetNames[2], "moved", "hand-built: target names")
local W = assert(Types.Scene.reader(quad.attributes._WEIGHT_0))
t:eq(W(idx[2], 0), 0.75, "hand-built: weight map value (point 3)")
local base, child = s.materials[1], s.materials[2]
t:eq(base.baseColor[1], 1, "hand-built: COLR")
t:check(near(base.baseColor[4], 0.75, 1e-6) and base.alphaMode == "blend", "hand-built: TRAN -> alpha")
t:check(base.doubleSided, "hand-built: SIDE 3")
t:check(child.doubleSided and child.baseColor[1] == 1, "hand-built: derived surface copies its source")
t:check(near(child.emissive[1], 0.5, 1e-6), "hand-built: LUMI -> emissive")
t:check(child.baseColorTexture and child.baseColorTexture.texCoord == 0, "hand-built: image block via XREF clip")
t:eq(s.textures[1].uri, "Wood.PNG", "hand-built: texture uri is the file name")
t:eq(s.textures[1].extras.lwo.path, "C:\\images\\Wood.PNG", "hand-built: full path in extras")
local tri = decode(data)
t:eq(tri.meshes[1].primitives[1].indices.count, 6, "hand-built: quad fan-triangulated")
-- triangulated quads keep the right facing: +z after the conversion (LightWave clockwise from -z)
local tp = tri.meshes[1].primitives[1]
local TP = assert(Types.Scene.reader(tp.attributes.POSITION))
local a, b, c = buffer.readu32(tp.indices.data, 0), buffer.readu32(tp.indices.data, 4), buffer.readu32(tp.indices.data, 8)
local ux, uy = TP(b, 0) - TP(a, 0), TP(b, 1) - TP(a, 1)
local vx, vy = TP(c, 0) - TP(a, 0), TP(c, 1) - TP(a, 1)
t:check(ux * vy - uy * vx < 0, "hand-built: facing kept (LightWave +z normal -> glTF -z)")
end
-- ------------------------------------------------------------------------------------------------ errors
do
local _, e1 = decode("FORM\0\0\0\4LWO3")
t:check(e1 and e1.code == Err.UNSUPPORTED, "LWO3: " .. tostring(e1))
local _, e2 = decode("FORM\0\0\0\4ILBM")
t:check(e2 and e2.code == Err.CORRUPT, "not LWO: " .. tostring(e2))
local _, e3 = decode("FORM")
t:check(e3 and e3.code == Err.TRUNCATED, "short: " .. tostring(e3))
local _, e4 = decode(quadFile(), { maxVertices = 3 })
t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4))
local bad = form(chunk("PNTS", f4(0) .. f4(0) .. f4(0)) .. chunk("POLS", "FACE" .. be16(3) .. be16(0) .. be16(1) .. be16(2)))
local _, e5 = decode(bad)
t:check(e5 and e5.code == Err.CORRUPT, "point index out of range: " .. tostring(e5))
t:eq(Lwo.sniff(Bytes.reader(buffer.fromstring(quadFile()))), 1, "sniff")
t:eq(Lwo.sniff(Bytes.reader(buffer.fromstring("FORM\0\0\0\4AIFF"))), 0, "sniff AIFF")
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local samples = { quadFile() }
for _, c in Cases do
if #c.data < 30000 and #samples < 16 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local s = Lwo.decode(Bytes.reader(b), { triangulate = false })
if s then
MeshOps.merge(s)
end
return s
end, samples, { mutations = 16, keepHeader = 12 })
end
t:done()
+430
View File
@@ -0,0 +1,430 @@
-- model/ms3d tests: assimp's MilkShape 3D test models (groups, materials, textures, version 4 with and without the
-- sub-versioned blocks) against assimp (meshes, faces, corners, materials, world bounds); round trips through our
-- writer, of those files and of glTF sample models (world triangles, materials, textures, skins: joints, inverse bind
-- matrices, skinned vertices; animation sampled through the skeleton); assimp reading our files (meshes, faces,
-- bones, animations, bounds: ms3d_xcheck); comments and extras; errors; the fuzz no-throw pass. Fixtures:
-- tools/fixtures/ms3d.py.
local T = require("@tests/T")
local F = require("@formats")
local Ms3d = require("@formats/model/ms3d")
local Gltf = require("@formats/model/gltf")
local MeshOps = require("@formats/ops/MeshOps")
local Mat4 = require("@formats/codecs/model/Mat4")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Cases = require("@tests/gen/ms3d_cases")
local Picks = require("@tests/gen/ms3d_gltf")
local Xcheck = require("@tests/gen/ms3d_xcheck")
local t = T.suite("ms3d")
local S = Types.Scene
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Ms3d.decode(Bytes.reader(b), opts)
end
t:eq(Ms3d.name, "ms3d", "name")
t:eq(Ms3d.category, "model", "category")
t:check(Ms3d.caps.decode and Ms3d.caps.encode, "contract")
local function near(a: number, b: number, eps: number): boolean
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
end
local function counts(scene: any): (number, number, number)
local prims, faces, corners = 0, 0, 0
for _, pl in S.flatten(scene) do
prims += 1
faces += pl.primitive.indices.count // 3
corners += pl.primitive.indices.count
end
return prims, faces, corners
end
local function bstr(lo: any, hi: any): string
if not lo then
return "-"
end
return string.format("(%.4g %.4g %.4g) (%.4g %.4g %.4g)", lo[1], lo[2], lo[3], hi[1], hi[2], hi[3])
end
local function boundsEq(lo: { number }, hi: { number }, want: any, eps: number): boolean
for k = 1, 3 do
if not near(lo[k], want.min[k], eps) or not near(hi[k], want.max[k], eps) then
return false
end
end
return true
end
-- the bones assimp makes: per group, the distinct strongest joints of its vertices
local function bones(scene: any): number
local n = 0
for _, pl in S.flatten(scene) do
local A = pl.primitive.attributes
if A.JOINTS_0 then
local J, W = S.reader(A.JOINTS_0) :: any, S.reader(A.WEIGHTS_0) :: any
local seen = {}
for v = 0, A.JOINTS_0.count - 1 do
local best, bw = -1, 0
for c = 0, 3 do
if W(v, c) > bw then
best, bw = J(v, c), W(v, c)
end
end
if best >= 0 and not seen[best] then
seen[best] = true
n += 1
end
end
end
end
return n
end
-- ------------------------------------------------------------------------------------------------ reference files
local scenes = {}
for i, c in Cases do
local scene, err = decode(c.data)
local a = c.assimp
t:check(scene, c.name .. ": decode: " .. tostring(err))
scenes[i] = scene
if scene and not a.failed then
local prims, faces, corners = counts(scene)
t:eq(prims, a.meshes, c.name .. ": meshes (assimp)")
t:eq(faces, a.faces, c.name .. ": faces (assimp)")
t:eq(corners, a.vertices, c.name .. ": corners (assimp)")
t:eq(math.max(#scene.materials, 1), a.materials, c.name .. ": materials (assimp)")
t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)")
t:eq(bones(scene), a.bones, c.name .. ": bones (assimp)")
if a.min then
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
t:check(lo and boundsEq(lo, hi, a, 1e-4), c.name .. ": world bounds (assimp) " .. bstr(lo, hi) .. " / " .. bstr(a.min, a.max))
end
end
end
t:note("%d files against assimp", #Cases)
-- ------------------------------------------------------------------------------------------------ round trips
-- skinned world positions at a time: the skeleton posed by animations[1], vertices blended by their joints
local function skinnedPositions(s: any, time: number): { number }
local byNode: { [number]: { [string]: any } } = {}
for _, ch in (if s.animations[1] then s.animations[1].channels else {}) :: { any } do
byNode[ch.node] = byNode[ch.node] or {}
byNode[ch.node][ch.path] = ch
end
local function eval(ch: any, comps: number): { number }
local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any
local n = ch.input.count
local cubic = ch.interpolation == "CUBICSPLINE"
local function v(k: number): { number }
local e = if cubic then k * 3 + 1 else k
local r = {}
for q = 0, comps - 1 do
r[q + 1] = OUT(e, q)
end
if comps == 4 then
local l = math.sqrt(r[1] * r[1] + r[2] * r[2] + r[3] * r[3] + r[4] * r[4])
r = { r[1] / l, r[2] / l, r[3] / l, r[4] / l }
end
return r
end
if time <= IN(0, 0) then
return v(0)
end
for k = 0, n - 2 do
local t0, t1 = IN(k, 0), IN(k + 1, 0)
if time <= t1 then
local u = if t1 > t0 then (time - t0) / (t1 - t0) else 1
local a0, a1 = v(k), v(k + 1)
if comps == 4 and a0[1] * a1[1] + a0[2] * a1[2] + a0[3] * a1[3] + a0[4] * a1[4] < 0 then
a1 = { -a1[1], -a1[2], -a1[3], -a1[4] }
end
local r = {}
for q = 1, comps do
r[q] = a0[q] + (a1[q] - a0[q]) * u
end
if comps == 4 then
local l = math.sqrt(r[1] * r[1] + r[2] * r[2] + r[3] * r[3] + r[4] * r[4])
r = { r[1] / l, r[2] / l, r[3] / l, r[4] / l }
end
return r
end
end
return v(n - 1)
end
local world: { [number]: { number } } = {}
local function visit(i: number, parent: { number })
local n = s.nodes[i]
local chs = byNode[i]
local m = S.nodeMatrix(n)
if chs then
m = Mat4.compose(if chs.translation then eval(chs.translation, 3) else n.translation,
if chs.rotation then eval(chs.rotation, 4) else n.rotation, n.scale)
end
world[i] = S.mul(parent, m)
for _, c in n.children do
visit(c, world[i])
end
end
for _, r in s.roots do
visit(r, S.IDENTITY)
end
local out = {}
for _, pl in S.flatten(s) do
local prim = pl.primitive
local P = S.reader(prim.attributes.POSITION) :: any
local I = S.reader(prim.indices) :: any
local node = s.nodes[pl.node]
local skin = node.skin and s.skins[node.skin]
local J = prim.attributes.JOINTS_0 and S.reader(prim.attributes.JOINTS_0) :: any
local W = prim.attributes.WEIGHTS_0 and S.reader(prim.attributes.WEIGHTS_0) :: any
local IBM = skin and skin.inverseBindMatrices and S.reader(skin.inverseBindMatrices) :: any
local tri = {}
for k = 0, prim.indices.count - 1 do
local v = I(k, 0)
local x, y, z = P(v, 0), P(v, 1), P(v, 2)
local wx, wy, wz = 0, 0, 0
if skin and J and W then
for c = 0, 3 do
local w = W(v, c)
if w > 0 then
local j = J(v, c)
local ibm = {}
for q = 1, 16 do
ibm[q] = IBM(j, q - 1)
end
local m = S.mul(world[skin.joints[j + 1]], ibm)
local px, py, pz = Mat4.point(m, x, y, z)
wx, wy, wz = wx + px * w, wy + py * w, wz + pz * w
end
end
else
wx, wy, wz = Mat4.point(world[pl.node] or pl.matrix, x, y, z)
end
table.insert(tri, { wx, wy, wz })
if #tri == 3 then
-- each triangle's corners in a fixed order (a mirrored node's winding is flipped on write)
local function r(x: number): number
return math.floor(x * 100 + 0.5)
end
table.sort(tri, function(p: { number }, q: { number }): boolean
if r(p[1]) ~= r(q[1]) then
return r(p[1]) < r(q[1])
elseif r(p[2]) ~= r(q[2]) then
return r(p[2]) < r(q[2])
end
return r(p[3]) < r(q[3])
end)
for _, c in tri do
table.move(c, 1, 3, #out + 1, out)
end
tri = {}
end
end
end
return out
end
local function compare(a: any, b: any, label: string, eps: number)
local _, fa = counts(a)
local _, fb = counts(b)
t:eq(fb, fa, label .. ": triangles")
t:eq(#b.materials, #a.materials, label .. ": materials")
for k, m in a.materials do
local m2 = b.materials[k]
if m2 then
local ok = true
for q = 1, 4 do
ok = ok and near(m.baseColor[q], m2.baseColor[q], 1e-6)
end
t:check(ok, label .. ": material " .. k .. " colour")
local ta = m.baseColorTexture and a.textures[m.baseColorTexture.texture]
local tb = m2.baseColorTexture and b.textures[m2.baseColorTexture.texture]
t:check((ta == nil) == (tb == nil) and (ta == nil or ta.uri == nil or ta.uri == tb.uri), label .. ": material " .. k .. " texture")
end
end
t:eq(#b.skins, if #a.skins > 0 or #a.animations > 0 then 1 else 0, label .. ": skins (animated nodes become joints)")
if a.skins[1] then
t:eq(#b.skins[1].joints, #a.skins[1].joints, label .. ": joints")
end
-- the same posed triangles (the corners in order) at a few times
for _, time in { 0, 0.3, 0.75, 1.2, 2.5, 4 } do
local pa, pb = skinnedPositions(a, time), skinnedPositions(b, time)
local ok = #pa == #pb
local worst = 0
if ok then
for k = 1, #pa do
local d = math.abs(pa[k] - pb[k]) / math.max(1, math.abs(pa[k]))
worst = math.max(worst, d)
end
end
t:check(ok and worst <= eps, string.format("%s: posed vertices at %.2f s (worst %.3g)", label, time, worst))
if #a.animations == 0 then
break
end
end
end
for i, c in Cases do
local scene = scenes[i]
if scene then
local out, err = Ms3d.encode(scene)
t:check(out, c.name .. ": encode: " .. tostring(err))
local back, berr = decode(out :: buffer)
t:check(back, c.name .. ": decode ours: " .. tostring(berr))
if back then
compare(scene, back, c.name, 1e-6)
t:eq(#back.nodes, #scene.nodes, c.name .. ": nodes")
local same = true
for mi, m in scene.meshes do
same = same and back.meshes[mi].primitives[1].attributes.POSITION.count == m.primitives[1].attributes.POSITION.count
end
t:check(same, c.name .. ": vertices kept")
end
end
end
local gltfScenes = {}
local ng = 0
for gi, g in Picks do
local scene, gerr = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files })
t:check(scene, g.name .. ": glTF decode: " .. tostring(gerr))
if scene then
gltfScenes[gi] = scene
local out, err = Ms3d.encode(scene)
t:check(out, g.name .. ": encode: " .. tostring(err))
local back, berr = decode(out :: buffer)
t:check(back, g.name .. ": decode ours: " .. tostring(berr))
if back then
local lines = false
for _, m in scene.meshes do
for _, p in m.primitives do
lines = lines or p.mode == "points" or p.mode == "lines" or p.mode == "line_strip" or p.mode == "line_loop"
end
end
if not lines then
-- weights are stored in percent
compare(scene, back, "glTF " .. g.name, if #scene.skins > 0 then 1e-2 else 1e-4)
end
ng += 1
end
end
end
t:note("%d reference files and %d glTF models through our writer and back", #Cases, ng)
-- ------------------------------------------------------------------------------------------------ cross-check
local nx = 0
for _, x in Xcheck do
local a = x.assimp
t:check(not a.failed, x.name .. ": assimp reads our file")
local scene = if x.case then scenes[x.case] else gltfScenes[x.gltf]
if scene and not a.failed then
local back = decode(Ms3d.encode(scene) :: buffer)
local prims, faces, corners = counts(back)
t:eq(a.meshes, prims, x.name .. ": assimp meshes of our file")
t:eq(a.faces, faces, x.name .. ": assimp faces of our file")
t:eq(a.vertices, corners, x.name .. ": assimp corners of our file")
t:eq(a.bones, bones(back), x.name .. ": assimp bones of our file")
t:eq(a.animations, if #back.nodes > #back.meshes then 1 else 0, x.name .. ": assimp animations of our file (it makes one for any joint)")
t:eq(a.materials, math.max(#back.materials, 1), x.name .. ": assimp materials of our file")
if a.min then
local lo, hi = MeshOps.bounds(MeshOps.merge(back))
t:check(lo and boundsEq(lo, hi, a, 1e-4), x.name .. ": assimp world bounds of our file " .. bstr(lo, hi) .. " / " .. bstr(a.min, a.max))
end
nx += 1
end
end
t:note("%d of our files read back by assimp", nx)
-- ------------------------------------------------------------------------------------------------ details
do
local byName = {}
for i, c in Cases do
byName[c.name] = scenes[i]
end
local jeep = byName["assimp/jeep1.ms3d"]
if jeep then
local m = jeep.materials[1]
t:check(m.baseColorTexture and jeep.textures[1].uri ~= nil and jeep.textures[1].data == nil, "texture -> uri, not loaded: " .. tostring(jeep.textures[1].uri))
t:eq(#jeep.meshes, 7, "jeep: 7 groups")
t:eq(jeep.meta.up, "y", "MilkShape is Y up")
t:check(jeep.meta.source.vertexVersion == nil, "jeep: no sub-versioned blocks")
end
local mats = byName["assimp/twospheres_withmats.ms3d"]
if mats then
t:eq(mats.meta.source.commentVersion, 1, "comment block")
t:eq(mats.meta.source.vertexVersion, 3, "vertex extras subversion 3")
t:check(mats.materials[2].extras.ms3d.shininess > 0, "shininess in extras")
end
-- a skinned scene by hand: two joints, comments, weights split between them
local gl = gltfScenes[3]
if gl then
local out = Ms3d.encode(gl) :: buffer
local back = decode(out)
t:check(back.skins[1] and #back.skins[1].joints == #gl.skins[1].joints, "joints written")
local W = back.meshes[1].primitives[1].attributes.WEIGHTS_0
local R = S.reader(W) :: any
local split = false
for v = 0, W.count - 1 do
split = split or (R(v, 1) > 0.05)
t:check(math.abs(R(v, 0) + R(v, 1) + R(v, 2) + R(v, 3) - 1) < 1e-6, "weights sum to 1")
end
t:check(split, "vertex extras: second bone weights")
back.nodes[1].extras.ms3d.comment = "the root"
back.materials[1] = F.Types.Scene.material("m")
back.materials[1].extras = { ms3d = { comment = "a material" } }
back.meta.source.comment = "made by a test"
local again = decode(Ms3d.encode(back) :: buffer)
t:eq(again.nodes[1].extras.ms3d.comment, "the root", "joint comment")
t:eq(again.materials[1].extras.ms3d.comment, "a material", "material comment")
t:eq(again.meta.source.comment, "made by a test", "model comment")
end
local s = F.load(Cases[1].data)
t:check(s and s.kind == "scene" and s.meta.source.format == "ms3d", "F.load detects MS3D")
local viaApi = F.save(s, nil, { format = "ms3d" })
t:check(viaApi and buffer.readstring(viaApi, 0, 10) == "MS3D000000", "F.save format ms3d")
end
-- ------------------------------------------------------------------------------------------------ errors
do
local data = Cases[2].data
local _, e1 = decode(string.sub(data, 1, 100))
t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1))
local _, e2 = decode("MS3D000000\9\0\0\0")
t:check(e2 and e2.code == Err.UNSUPPORTED, "version 9: " .. tostring(e2))
local _, e3 = decode("MS3D000001")
t:check(e3 and e3.code == Err.CORRUPT, "bad magic: " .. tostring(e3))
local _, e4 = decode(data, { maxVertices = 10 })
t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4))
local _, e5 = Ms3d.encode({} :: any)
t:check(e5 and e5.code == Err.ARG, "encode junk")
t:eq(Ms3d.sniff(Bytes.reader(buffer.fromstring(data))), 1, "sniff")
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local samples = {}
for _, c in Cases do
if #c.data < 40000 then
table.insert(samples, c.data)
end
end
for gi, g in gltfScenes do
if gi <= 4 then
table.insert(samples, buffer.tostring(Ms3d.encode(g) :: buffer))
end
end
t:fuzz("decode", function(b: buffer)
local s = Ms3d.decode(Bytes.reader(b))
if s then
Ms3d.encode(s)
MeshOps.merge(s)
end
return s
end, samples, { mutations = 12, keepHeader = 14 })
end
t:done()
+263
View File
@@ -0,0 +1,263 @@
-- model/pmx tests: assimp's MMD model (Alicia_blade.pmx) and synthetic PMX 2.0 / 2.1 models (UTF-16 / UTF-8, index
-- sizes 1 / 2 / 4, additional UVs, BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF, every morph type, IK / inherit / axis bones,
-- display frames, rigid bodies, joints) against assimp (meshes, faces per mesh, materials, bones, world bounds) and the
-- generator's facts (vertices, weights, bones, morphs, textures); the same models as PMD against their PMX decode;
-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/pmx.py.
local T = require("@tests/T")
local F = require("@formats")
local Pmx = require("@formats/model/pmx")
local MeshOps = require("@formats/ops/MeshOps")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Cases = require("@tests/gen/pmx_cases")
local Pmds = require("@tests/gen/pmx_pmd")
local t = T.suite("pmx")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Pmx.decode(Bytes.reader(b), opts)
end
local function near(a: number, b: number, eps: number): boolean
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
end
t:eq(Pmx.name, "pmx", "name")
t:eq(Pmx.category, "model", "category")
t:check(Pmx.caps.decode and not Pmx.caps.encode, "contract")
local function faces(scene: any): (number, { number })
local n, per = 0, {}
for i, p in scene.meshes[1].primitives do
per[i] = p.indices.count // 3
n += per[i]
end
return n, per
end
local function bounds(scene: any): ({ number }, { number })
return MeshOps.bounds(MeshOps.merge(scene))
end
-- a file vertex in the decoded primitives: position (z negated) and uv
local function findVertex(scene: any, pos: { number }, uv: { number }): (any, number?)
for _, p in scene.meshes[1].primitives do
local P, U = p.attributes.POSITION, p.attributes.TEXCOORD_0
for v = 0, P.count - 1 do
local x, y, z = buffer.readf32(P.data, v * 12), buffer.readf32(P.data, v * 12 + 4), buffer.readf32(P.data, v * 12 + 8)
if near(x, pos[1], 1e-6) and near(y, pos[2], 1e-6) and near(z, -pos[3], 1e-6) and near(buffer.readf32(U.data, v * 8), uv[1], 1e-6) and near(buffer.readf32(U.data, v * 8 + 4), uv[2], 1e-6) then
return p, v
end
end
end
return nil, nil
end
-- ------------------------------------------------------------------------------------------------ reference files
local scenes = {}
local checked = { assimp = 0, expect = 0 }
for i, c in Cases do
local scene, err = decode(c.data, { files = c.files })
t:check(scene, c.name .. ": decode: " .. tostring(err))
if not scene then
continue
end
scenes[i] = scene
local a = c.assimp
local nf, per = faces(scene)
if not a.skip then
t:eq(#scene.meshes[1].primitives, a.meshes, c.name .. ": meshes (assimp)")
t:eq(nf, a.faces, c.name .. ": faces (assimp)")
t:eq(#scene.materials, a.materials, c.name .. ": materials (assimp)")
local ok = true
for k, pm in a.perMesh do
ok = ok and per[k] == pm.faces
end
t:check(ok, c.name .. ": faces per material (assimp)")
t:eq(#scene.skins[1].joints * #scene.meshes[1].primitives, a.bones, c.name .. ": bones x meshes (assimp)")
if a.min then
local lo, hi = bounds(scene)
local okb = true
for k = 1, 3 do
okb = okb and near(lo[k], a.min[k], 1e-5) and near(hi[k], a.max[k], 1e-5)
end
t:check(okb, string.format("%s: world bounds (assimp) %s / %s", c.name, table.concat(lo, " "), table.concat(hi, " ")))
end
checked.assimp += 1
end
local x = c.expect
if x then
local src = scene.meta.source
t:eq(src.version, x.version, c.name .. ": version")
t:eq(src.name, x.name, c.name .. ": model name")
t:eq(#scene.skins[1].joints, x.bones, c.name .. ": bones")
t:eq(#scene.nodes, 2 + x.bones, c.name .. ": nodes")
t:eq(#scene.textures, x.textures, c.name .. ": textures")
t:eq(#src.rigidBodies, x.rigid, c.name .. ": rigid bodies")
t:eq(#src.joints, x.joints, c.name .. ": joints")
t:eq(#src.displayFrames, x.frames, c.name .. ": display frames")
local mesh = scene.meshes[1]
local vertexMorphs = x.morphTypes["1"] or 0
t:eq(#(mesh.extras.targetNames or {}), vertexMorphs, c.name .. ": vertex morphs -> targets")
t:eq(#mesh.primitives[1].targets, vertexMorphs, c.name .. ": targets per primitive")
t:eq(#((mesh.extras.pmx or {}).morphs or {}), x.morphs - vertexMorphs, c.name .. ": other morphs in extras")
t:check(x.uva == 0 or mesh.primitives[1].attributes["_UVA" .. x.uva] ~= nil, c.name .. ": additional UVs")
-- unique vertices: a material boundary can split a ring, so at least the file's count
local nv = 0
for _, p in mesh.primitives do
nv += p.attributes.POSITION.count
end
t:check(nv >= x.vertices and nv <= x.vertices * 2, c.name .. ": vertices " .. nv .. " / " .. x.vertices)
for _, s in x.samples do
local p, v = findVertex(scene, s.pos, s.uv)
t:check(p ~= nil, c.name .. ": vertex " .. s.index .. " found")
if p and v then
local J, W = p.attributes.JOINTS_0, p.attributes.WEIGHTS_0
local want: { [number]: number } = {}
local sum = 0
local ws = if s.deform == 1 or s.deform == 3 then { s.weights[1], 1 - s.weights[1] } elseif s.deform == 0 then { 1 } else s.weights
for k, b in s.bones do
if b >= 0 and ws[k] and ws[k] > 0 then
want[b] = (want[b] or 0) + ws[k]
sum += ws[k]
end
end
local got: { [number]: number } = {}
for k = 0, 3 do
local w = buffer.readf32(W.data, (v * 4 + k) * 4)
if w > 0 then
local j = buffer.readu16(J.data, (v * 4 + k) * 2)
got[j] = (got[j] or 0) + w
end
end
local ok = true
for b, w in want do
ok = ok and got[b] ~= nil and near(got[b], w / sum, 1e-5)
end
t:check(ok, c.name .. ": vertex " .. s.index .. " weights (deform " .. s.deform .. ")")
if s.deform == 3 then
t:check(p.attributes._SDEF_C ~= nil and buffer.readu8(p.attributes._DEFORM.data, v) == 3, c.name .. ": SDEF attributes")
end
end
end
-- the texture named tex\body.png came from files["tex/body.png"]
t:check(scene.textures[1].uri == "tex/body.png" and scene.textures[1].data ~= nil and scene.textures[1].mime == "image/png", c.name .. ": texture data")
local m1 = scene.materials[1]
t:check(m1.baseColorTexture and m1.baseColorTexture.texture == 1 and m1.doubleSided, c.name .. ": material 1 texture, no-cull")
t:check(m1.extras.pmx.sphereTexture == 2 and m1.extras.pmx.sphereMode == "multiply" and m1.extras.pmx.toonShared == 3, c.name .. ": sphere / toon")
t:check(scene.materials[2].alphaMode == "blend", c.name .. ": translucent material")
local ik = nil
for _, n in scene.nodes do
if n.extras and n.extras.pmx and n.extras.pmx.ik then
ik = n.extras.pmx.ik
end
end
t:check(ik and ik.loops == 40 and #ik.links == 2, c.name .. ": IK bone")
checked.expect += 1
end
end
t:note("%d files: %d against assimp, %d against the generator", #Cases, checked.assimp, checked.expect)
-- skins: every joint's inverse bind matrix undoes its world translation
do
local s = scenes[2]
if s then
local skin = s.skins[1]
local ok = true
local world = {}
-- world matrices by walking from the root
local function walk(n: number, parent: { number })
local w = Types.Scene.mul(parent, Types.Scene.nodeMatrix(s.nodes[n]))
world[n] = w
for _, c in s.nodes[n].children do
walk(c, w)
end
end
walk(1, Types.Scene.IDENTITY)
for k, j in skin.joints do
local w = world[j]
for c = 0, 2 do
ok = ok and near(buffer.readf32(skin.inverseBindMatrices.data, ((k - 1) * 16 + 12 + c) * 4), -w[13 + c], 1e-5)
end
end
t:check(ok, "inverse bind matrices = -world bone positions")
end
end
-- ------------------------------------------------------------------------------------------------ PMD
for _, c in Pmds do
local s, err = decode(c.data)
t:check(s, c.name .. ": decode: " .. tostring(err))
local ref = scenes[c.pmx]
if s and ref then
t:check(s.meta.source.pmd == true and s.meta.source.format == "pmx", c.name .. ": meta.source")
local a, pa = faces(s)
local b, pb = faces(ref)
t:eq(a, b, c.name .. ": faces (= PMX)")
t:eq(#pa, #pb, c.name .. ": primitives (= PMX)")
t:eq(#s.skins[1].joints, #ref.skins[1].joints, c.name .. ": bones (= PMX)")
t:eq(#s.meshes[1].extras.targetNames, #ref.meshes[1].extras.targetNames, c.name .. ": vertex morphs (= PMX)")
local lo, hi = bounds(s)
local lo2, hi2 = bounds(ref)
local ok = true
for k = 1, 3 do
ok = ok and near(lo[k], lo2[k], 1e-6) and near(hi[k], hi2[k], 1e-6)
end
t:check(ok, c.name .. ": bounds (= PMX)")
-- the same morph deltas
local d1 = s.meshes[1].primitives[1].targets[1].POSITION
local d2 = ref.meshes[1].primitives[1].targets[1].POSITION
t:check(d1.count == d2.count and buffer.tostring(d1.data) == buffer.tostring(d2.data), c.name .. ": morph deltas (= PMX)")
t:eq(s.meshes[1].extras.targetNames[1], "up", c.name .. ": English morph names")
t:eq(s.materials[1].extras.pmx.sphereMode, "multiply", c.name .. ": texture*sphere name")
end
end
-- ------------------------------------------------------------------------------------------------ api, errors
do
local c = Cases[2]
t:eq(F.detect(c.data), "pmx", "F.detect pmx")
t:eq(F.detect(Pmds[1].data), "pmx", "F.detect pmd")
local s = F.load(c.data, { files = c.files })
t:check(s and s.kind == "scene" and s.meta.up == "y", "F.load")
local _, e1 = decode(string.sub(c.data, 1, 300))
t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1))
local _, e2 = decode("PMX " .. "\0\0\64\64" .. string.sub(c.data, 9))
t:check(e2 and e2.code == Err.UNSUPPORTED, "version 2.0 -> 3.0: " .. tostring(e2))
local _, e3 = decode(string.sub(c.data, 1, 11) .. "\3" .. string.sub(c.data, 13))
t:check(e3 and e3.code == Err.CORRUPT, "index size 3: " .. tostring(e3))
local _, e4 = decode(c.data, { maxVertices = 10 })
t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4))
local _, e5 = decode(c.data, { maxBytes = 100 })
t:check(e5 and e5.code == Err.LIMIT, "maxBytes (morph targets): " .. tostring(e5))
local s2 = decode(c.data, { maxBytes = 100, morphs = false })
t:check(s2 and s2.meshes[1].primitives[1].targets == nil, "morphs = false")
local _, e6 = decode("Pmd\0\0\0\64" .. string.rep("\0", 300))
t:check(e6 and e6.code == Err.UNSUPPORTED, "PMD version 2: " .. tostring(e6))
local _, e7 = decode(string.sub(Pmds[1].data, 1, 400))
t:check(e7 and (e7.code == Err.TRUNCATED or e7.code == Err.CORRUPT), "PMD truncated: " .. tostring(e7))
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local samples = {}
for _, c in Cases do
if #c.data < 120000 then
table.insert(samples, c.data)
end
end
for _, c in Pmds do
table.insert(samples, c.data)
end
t:fuzz("decode", function(b: buffer)
local s = Pmx.decode(Bytes.reader(b))
if s then
MeshOps.merge(s)
end
return s
end, samples, { mutations = 16, keepHeader = 16 })
end
t:done()
+410
View File
@@ -0,0 +1,410 @@
-- model/vrml tests: assimp's WRL test models (HelloWorld, Wuson, the MotionCaptureROM animation), scenes and glTF
-- samples written by VTK's VRML exporter, and hand-written feature files (PROTO, DEF / USE, per-face colours and
-- separate indices, primitives, ElevationGrid, Extrusion, Switch, LOD, lights, viewpoints, ROUTE animations,
-- PixelTexture, Inline), against VTK's vtkVRMLImporter (polygons, points, world bounds where VTK's transforms are
-- right) and exact expectations; the writer: round trips of every case and of glTF sample models (world triangles,
-- materials, textures, cameras, lights, animation samples), VTK reading our files like the originals; errors; the
-- fuzz no-throw pass. Fixtures: tools/fixtures/vrml.py.
local T = require("@tests/T")
local F = require("@formats")
local Vrml = require("@formats/model/vrml")
local Gltf = require("@formats/model/gltf")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Deflate = require("@formats/codecs/compress/Deflate")
local C = require("@tests/model/_vrml_common")
local Cases = require("@tests/gen/vrml_cases")
local GltfCases = require("@tests/gen/vrml_gltf")
local Xcheck = require("@tests/gen/vrml_xcheck")
local t = T.suite("vrml")
local near = C.near
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Vrml.decode(Bytes.reader(b), opts)
end
t:eq(Vrml.name, "vrml", "name")
t:eq(Vrml.category, "model", "category")
t:check(Vrml.caps.decode and Vrml.caps.encode, "contract")
-- ------------------------------------------------------------------------------------------------ reference files
local scenes, byName = {}, {}
local checked = { vtk = 0, bounds = 0, none = 0 }
for i, c in Cases do
local scene, err = decode(c.data, { files = c.files, triangulate = false })
t:check(scene, c.name .. ": decode: " .. tostring(err))
if not scene then
continue
end
scenes[i], byName[c.name] = scene, scene
local s = C.stats(scene)
local v = c.vtk
if v.failed or v.actors == 0 then
checked.none += 1
continue
end
checked.vtk += 1
if not c.primitives then
t:eq(s.polys, v.polys, c.name .. ": polygons (VTK)")
end
t:eq(s.points, v.verts, c.name .. ": points (VTK)")
t:check((s.lines > 0) == (v.lines > 0), c.name .. ": lines (VTK)")
if c.vtkTransforms and v.min then
t:check(C.boundsNear(s.lo, s.hi, v.min, v.max, if c.primitives then 2e-2 else 1e-5), c.name .. ": world bounds (VTK) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(v.min, v.max))
checked.bounds += 1
end
end
t:note("%d files: %d against VTK (%d with bounds), %d VTK cannot read", #Cases, checked.vtk, checked.bounds, checked.none)
-- ------------------------------------------------------------------------------------------------ exact expectations
local function prims(scene: any): { any }
local out = {}
for _, pl in Types.Scene.flatten(scene) do
table.insert(out, pl)
end
return out
end
do
local hw = byName["assimp/HelloWorld.wrl"]
if hw then
t:eq(#hw.cameras, 1, "HelloWorld: viewpoint")
t:eq(hw.cameras[1].name, "ViewUpClose", "HelloWorld: viewpoint DEF name")
t:eq(hw.meta.source.title, "Hello World!", "HelloWorld: WorldInfo title")
t:eq(hw.meta.source.skipped.Text, 1, "HelloWorld: Text skipped")
local tex = hw.textures[1]
t:check(tex and tex.uri == "earth-topo.png" and tex.data and tex.mime == "image/png", "HelloWorld: texture from files")
t:eq(hw.materials[1].name, "MaterialOffWhite", "HelloWorld: material DEF name")
t:check(near(hw.materials[1].baseColor[1], 0.980392, 1e-6), "HelloWorld: diffuseColor")
end
local mc = byName["assimp/MotionCaptureROM.WRL"]
if mc then
t:eq(#mc.animations, 1, "MotionCaptureROM: one TimeSensor animation")
local a = mc.animations[1]
t:check(#a.channels >= 20, "MotionCaptureROM: channels " .. #a.channels)
local tmax = 0
for _, ch in a.channels do
tmax = math.max(tmax, buffer.readf32(ch.input.data, (ch.input.count - 1) * 4))
end
t:check(near(tmax, 45.27, 1e-4), "MotionCaptureROM: key times x cycleInterval " .. tmax)
end
-- PROTO expansion, DEF / USE of a Shape (one mesh, two nodes)
local pu = byName["feature/feat_proto_use.wrl"]
if pu then
local s = C.stats(pu)
t:eq(#pu.meshes, 3, "proto: meshes (two instances + a shared shape)")
t:eq(s.prims, 4, "proto: placed primitives")
t:check(C.boundsNear(s.lo, s.hi, { -1, -0.5, -0.5 }, { 3.5, 6, 0.5 }, 1e-4), "proto: bounds " .. C.fmt(s.lo, s.hi))
local cols = {}
for _, m in pu.materials do
table.insert(cols, string.format("%g %g %g", m.baseColor[1], m.baseColor[2], m.baseColor[3]))
end
table.sort(cols)
t:eq(table.concat(cols, ", "), "0 1 0, 1 0 0", "proto: IS fields (instance value, default)")
end
-- separate indices, per-face normals / colours, ccw FALSE, solid FALSE
local ix = byName["feature/feat_indices.wrl"]
if ix then
local p1 = ix.meshes[1].primitives[1]
t:eq(p1.attributes.POSITION.count, 8, "indices: corners split by normal / colour / texture index")
t:eq(p1.faces.count, 2, "indices: two quads")
local N, Col, Tx = p1.attributes.NORMAL, p1.attributes.COLOR_0, p1.attributes.TEXCOORD_0
t:check(buffer.readf32(N.data, 8) == 1 and buffer.readf32(Col.data, 0) == 1 and buffer.readf32(Col.data, 8) == 0, "indices: face 1 normal / colour")
t:check(buffer.readf32(Tx.data, 4) == 1, "indices: t flipped (0 -> 1)")
-- ccw FALSE: the first face is written reversed (0 3 2 1)
t:eq(buffer.readu32(p1.indices.data, 4), 3, "indices: ccw FALSE reverses the winding")
local m = ix.materials[p1.material]
t:check(m.doubleSided and m.alphaMode == "blend" and near(m.baseColor[4], 0.75, 1e-6), "indices: solid FALSE, transparency")
t:check(m.extras.vrml.shininess == 0.5 and m.extras.vrml.specularColor[1] == 1, "indices: Phong terms in extras")
local p2 = ix.meshes[2].primitives[1]
t:eq(p2.attributes.POSITION.count, 5, "indices: per-vertex colour indices")
t:check(p2.material == nil, "indices: no appearance, no material")
end
-- primitives: exact bounds, unit normals
local pr = byName["feature/feat_primitives.wrl"]
if pr then
local s = C.stats(pr)
t:check(C.boundsNear(s.lo, s.hi, { -4.5, -2, -1.5 }, { 9, 2, 1.5 }, 1e-6), "primitives: bounds " .. C.fmt(s.lo, s.hi))
local box = pr.meshes[1].primitives[1]
t:eq(box.attributes.POSITION.count, 24, "Box: 24 vertices")
t:eq(box.indices.count, 36, "Box: 12 triangles")
local sph = pr.meshes[2].primitives[1]
local ok = true
local P, N = sph.attributes.POSITION, sph.attributes.NORMAL
for v = 0, P.count - 1 do
for k = 0, 2 do
ok = ok and near(buffer.readf32(P.data, (v * 3 + k) * 4) / 1.5, buffer.readf32(N.data, (v * 3 + k) * 4), 1e-5)
end
end
t:check(ok, "Sphere: normals = position / radius")
-- outward winding: the Box's first triangle faces +z
local function faceNormal(prim: any, tri: number): { number }
local function p(i: number): { number }
local v = buffer.readu32(prim.indices.data, (tri * 3 + i) * 4)
return { buffer.readf32(prim.attributes.POSITION.data, v * 12), buffer.readf32(prim.attributes.POSITION.data, v * 12 + 4), buffer.readf32(prim.attributes.POSITION.data, v * 12 + 8) }
end
local a, b, c = p(0), p(1), p(2)
local e1, e2 = { b[1] - a[1], b[2] - a[2], b[3] - a[3] }, { c[1] - a[1], c[2] - a[2], c[3] - a[3] }
return { e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] }
end
t:check(faceNormal(box, 0)[3] > 0, "Box: counter-clockwise front faces")
local cyl = pr.meshes[4].primitives[1]
local last = cyl.indices.count // 3 - 1
t:check(faceNormal(cyl, last)[2] < 0, "Cylinder: bottom cap faces down")
t:check(faceNormal(cyl, 0)[3] < 0 or faceNormal(cyl, 0)[1] ~= 0, "Cylinder: side faces outwards")
end
local ge = byName["feature/feat_grid_extrusion.wrl"]
if ge then
local grid, ex = ge.meshes[1].primitives[1], ge.meshes[2].primitives[1]
t:eq(grid.attributes.POSITION.count, 12, "ElevationGrid: vertices")
t:eq(grid.faces.count, 6, "ElevationGrid: quads")
t:eq(ex.attributes.POSITION.count, 16, "Extrusion: closed cross section shares its seam")
t:eq(ex.faces.count, 14, "Extrusion: sides + caps")
local s = C.stats(ge)
t:check(near(s.hi[2], 3, 1e-6) and near(s.hi[3], 4, 1e-6), "ElevationGrid: heights and spacing")
end
local sc = byName["feature/feat_scene.wrl"]
if sc then
t:eq(sc.meta.source.title, "feature scene", "scene: title")
t:eq(#sc.cameras, 1, "scene: viewpoint")
t:check(near(sc.cameras[1].yfov, 0.9, 1e-9) and sc.cameras[1].name == "Cam", "scene: fieldOfView")
local types = {}
for _, l in sc.lights do
types[l.type] = l
end
t:check(types.directional and types.point and types.spot, "scene: three light types")
t:check(types.point.range == 10 and near(types.spot.outerCone, 0.6, 1e-9) and near(types.spot.innerCone, 0.4, 1e-9), "scene: radius, cones")
-- the directional light's node turns -z onto its direction (0, -1, -1)
for _, n in sc.nodes do
if n.light and sc.lights[n.light].type == "directional" then
local m = Mat4.fromQuat(n.rotation)
local x, y, z = Mat4.point(m, 0, 0, -1)
t:check(near(x, 0, 1e-6) and near(y, -math.sqrt(0.5), 1e-6) and near(z, -math.sqrt(0.5), 1e-6), "scene: light direction")
end
end
t:eq(#sc.animations, 1, "scene: animation")
local a = sc.animations[1]
t:eq(a.name, "Clock", "scene: animation named after its TimeSensor")
t:eq(#a.channels, 2, "scene: translation + rotation channels")
local tr = a.channels[1].path == "translation" and a.channels[1] or a.channels[2]
t:check(near(buffer.readf32(tr.input.data, 8), 4, 1e-6), "scene: key 1 x cycleInterval 4")
-- translation keys move the outer node: key + center
t:check(near(buffer.readf32(tr.output.data, 12), 1, 1e-6) and near(buffer.readf32(tr.output.data, 16), 2, 1e-6), "scene: translation key + center")
-- PixelTexture: the first row of the file is the bottom one
local img
for _, tex in sc.textures do
img = img or tex.image
end
t:check(img and img.width == 2 and buffer.readu8(img.pixels, 2) == 255 and buffer.readu8(img.pixels, 8) == 255 and buffer.readu8(img.pixels, 9) == 0, "scene: PixelTexture pixels")
-- Switch whichChoice 1: the sphere only; LOD: the first level; Inline: part.wrl
local s = C.stats(sc)
t:check(near(s.lo[2], -3.1, 1e-6), "scene: Inline file placed")
-- center / scaleOrientation: the line set's first point (0, 0, 0) under T C R SR S -SR -C
local mover = nil
for _, pl in prims(sc) do
if pl.primitive.mode == "lines" then
mover = pl
end
end
if mover then
local sr = Mat4.axisAngle(0, 0, 1, math.deg(0.5))
local m = Mat4.mul(Mat4.translation(1, 0, 0), Mat4.mul(Mat4.fromQuat(sr), Mat4.mul(Mat4.scaling(1, 2, 1), Mat4.mul(Mat4.fromQuat({ -sr[1], -sr[2], -sr[3], sr[4] }), Mat4.translation(-1, 0, 0)))))
local ok = true
for k = 1, 16 do
ok = ok and near(mover.matrix[k], m[k], 1e-6)
end
t:check(ok, "scene: Transform center / scaleOrientation")
end
t:eq(sc.meta.unit, 1, "scene: metres")
end
end
-- ------------------------------------------------------------------------------------------------ writer
local function compare(a: any, b: any, label: string)
local sa, sb = C.stats(a), C.stats(b)
t:eq(sb.prims, sa.prims, label .. ": placed primitives")
t:eq(sb.polys, sa.polys, label .. ": faces")
t:eq(sb.lines, sa.lines, label .. ": line segments")
t:eq(sb.points, sa.points, label .. ": points")
if sa.prims > 0 and sa.lo[1] <= sa.hi[1] then
t:check(C.boundsNear(sa.lo, sa.hi, sb.lo, sb.hi, 1e-5), label .. ": bounds " .. C.fmt(sa.lo, sa.hi) .. " vs " .. C.fmt(sb.lo, sb.hi))
t:check(near(sa.area, sb.area, 1e-4), string.format("%s: area %.6g / %.6g", label, sa.area, sb.area))
end
t:eq(#b.materials, #a.materials, label .. ": materials")
for k, m in a.materials do
local m2 = b.materials[k]
if m2 then
local ok = true
for q = 1, 4 do
ok = ok and near(m.baseColor[q], m2.baseColor[q], 1e-6)
end
t:check(ok, label .. ": material " .. k .. " colour")
t:check((m.baseColorTexture == nil) == (m2.baseColorTexture == nil), label .. ": material " .. k .. " texture")
end
end
t:eq(#b.cameras, #a.cameras, label .. ": cameras")
t:eq(#b.lights, #a.lights, label .. ": lights")
end
local rt = 0
for i, c in Cases do
local a = scenes[i]
if a then
local files = {}
local out, err = Vrml.encode(a, { files = files, name = "rt.wrl" })
t:check(out, c.name .. ": encode: " .. tostring(err))
if out then
local b, e2 = decode(out, { files = files, triangulate = false })
t:check(b, c.name .. ": re-decode: " .. tostring(e2))
if b then
compare(a, b, c.name .. " (round trip)")
t:eq(#b.animations, #a.animations, c.name .. " (round trip): animations")
rt += 1
end
end
end
end
-- glTF samples through VRML: world triangles, materials, textures, cameras, lights, animation samples
local gltfScenes = {}
for i, c in GltfCases do
local g = Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
if not g then
continue
end
gltfScenes[i] = g
local files = {}
local out, err = Vrml.encode(g, { files = files, name = "model.wrl" })
t:check(out, c.name .. ": encode: " .. tostring(err))
if not out then
continue
end
local b = decode(out, { files = files })
t:check(b, c.name .. ": decode our VRML")
if not b then
continue
end
local ga = C.stats(g)
local sb = C.stats(b)
t:check(C.boundsNear(ga.lo, ga.hi, sb.lo, sb.hi, 1e-5), c.name .. ": bounds through VRML " .. C.fmt(ga.lo, ga.hi) .. " vs " .. C.fmt(sb.lo, sb.hi))
t:check(near(ga.area, sb.area, 1e-4), c.name .. ": area through VRML")
t:eq(sb.points, ga.points, c.name .. ": points through VRML")
t:eq(#b.cameras, #g.cameras, c.name .. ": cameras through VRML")
for k, tex in g.textures do
local t2 = b.textures[k]
if tex.data and t2 then
t:check(t2.data and buffer.tostring(t2.data) == buffer.tostring(tex.data), c.name .. ": texture " .. k .. " bytes")
end
end
-- animations: the translation / rotation / scale channels, sampled at their keys
local want = 0
for _, a in g.animations do
for _, ch in a.channels do
if ch.path ~= "weights" then
want += 1
end
end
end
local got = 0
for _, a in b.animations do
got += #a.channels
end
t:eq(got, want, c.name .. ": animation channels through VRML")
rt += 1
end
t:note("%d round trips", rt)
-- VTK reads our files like the originals
local xc = 0
for _, x in Xcheck do
local v = x.vtk
local src = if x.case then scenes[x.case] else (if x.gltf then gltfScenes[x.gltf] else nil)
local srcCase = if x.case then Cases[x.case] else nil
if src and not v.failed and v.actors > 0 then
local s = C.stats(src)
if not (srcCase and srcCase.primitives) then
-- our IndexedFaceSets keep polygons; VTK counts them
t:eq(v.polys, s.polys, x.name .. ": polygons (VTK reads our file)")
end
t:eq(v.verts, s.points, x.name .. ": points (VTK reads our file)")
if x.vtkTransforms and v.min and s.lo[1] <= s.hi[1] then
t:check(C.boundsNear(s.lo, s.hi, v.min, v.max, 1e-4), x.name .. ": bounds (VTK reads our file) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(v.min, v.max))
end
xc += 1
end
end
t:note("%d of our files read by VTK", xc)
-- ------------------------------------------------------------------------------------------------ api, options, errors
do
local text = Cases[1].data
t:eq(F.detect(text), "vrml", "F.detect")
local s = F.load(text, { files = Cases[1].files })
t:check(s and s.meta.source.format == "vrml", "F.load")
local gz = Deflate.gzip(text)
local sg = decode(gz :: buffer)
t:check(sg and #sg.meshes == #s.meshes, "gzipped .wrz")
local tri = decode(Cases[1].data)
t:check(tri and tri.meshes[1].primitives[1].mode == "triangles", "triangulated by default")
local seg = decode(Cases[1].data, { segments = 8 })
t:check(seg and seg.meshes[1].primitives[1].attributes.POSITION.count < s.meshes[1].primitives[1].attributes.POSITION.count, "segments option")
local _, e1 = decode("#VRML V1.0 ascii\nSeparator { }")
t:check(e1 and e1.code == Err.UNSUPPORTED, "VRML 1.0: " .. tostring(e1))
local _, e2 = decode("#VRML V2.0 utf8\nShape { geometry Box { size 1 1 1 }")
t:check(e2 and e2.code == Err.CORRUPT, "unclosed node: " .. tostring(e2))
local _, e3 = decode("#VRML V2.0 utf8\nShape { appearance USE Nothing }")
t:check(e3 and e3.code == Err.CORRUPT, "USE of an undefined name: " .. tostring(e3))
local _, e4 = decode('#VRML V2.0 utf8\nWorldInfo { title "open')
t:check(e4 and e4.code == Err.TRUNCATED, "unterminated string: " .. tostring(e4))
local deep = "#VRML V2.0 utf8\n" .. string.rep("Group { children [ ", 300) .. string.rep("] } ", 300)
local _, e5 = decode(deep)
t:check(e5 and e5.code == Err.LIMIT, "nesting limit: " .. tostring(e5))
local _, e6 = decode("#VRML V2.0 utf8\nShape { geometry ElevationGrid { xDimension 5000 zDimension 5000 } }", { maxVertices = 1000 })
t:check(e6 and e6.code == Err.LIMIT, "maxVertices: " .. tostring(e6))
local _, e7 = Vrml.encode({} :: any)
t:check(e7 and e7.code == Err.ARG, "encode junk")
-- a quad written as one polygon and read back as one
local p = Types.Scene.accessor(nil, "f32", 3, 4)
for v, xyz in { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 } } do
for k = 1, 3 do
buffer.writef32(p.data, ((v - 1) * 3 + k - 1) * 4, xyz[k])
end
end
local faces = Types.Scene.accessor(nil, "u32", 1, 1)
buffer.writeu32(faces.data, 0, 4)
local ind = Types.Scene.accessor(nil, "u32", 1, 4)
for k = 0, 3 do
buffer.writeu32(ind.data, k * 4, k)
end
local quad = Types.Scene.fromPrimitive({ attributes = { POSITION = p }, indices = ind, faces = faces, mode = "polygons" }, "quad")
local q = decode(Vrml.encode(quad) :: buffer, { triangulate = false })
t:check(q and q.meshes[1].primitives[1].faces.count == 1 and q.nodes[1].name == "quad", "a quad stays one polygon, names kept")
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local samples = {}
for _, c in Cases do
if #c.data < 40000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local s = Vrml.decode(Bytes.reader(b), { files = {} })
if s then
Vrml.encode(s)
end
return s
end, samples, { mutations = 16, keepHeader = 16 })
end
t:done()
+314
View File
@@ -0,0 +1,314 @@
-- model/x tests: assimp's DirectX test models (text, binary 32-bit, MSZIP-compressed binary) and variants made by
-- tools/fixtures/x.py (binary with 64-bit floats, MSZIP-compressed text), against assimp (meshes per material, faces,
-- corners, materials, animations, bones, world bounds); frames, materials and textures, vertex colours, skins
-- (influences, inverse bind matrices against the bind pose), animation keys (the rotation convention against the
-- bind pose); an inline text file; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/x.py.
local T = require("@tests/T")
local X = require("@formats/model/x")
local MeshOps = require("@formats/ops/MeshOps")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Cases = require("@tests/gen/x_cases")
local t = T.suite("x")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return X.decode(Bytes.reader(b), opts)
end
t:eq(X.name, "x", "name")
t:eq(X.category, "model", "category")
t:check(X.caps.decode and not X.caps.encode, "caps")
local function near(a: number, b: number, eps: number): boolean
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
end
-- assimp's counts: meshes (one per material), faces, corners, bones (joints with weight in each mesh)
local function counts(scene: any): (number, number, number, number)
local meshes, faces, corners, bones = 0, 0, 0, 0
for _, m in scene.meshes do
for _, p in m.primitives do
meshes += 1
corners += p.indices.count
faces += if p.mode == "polygons" then p.faces.count else p.indices.count // 3
local J, W = p.attributes.JOINTS_0, p.attributes.WEIGHTS_0
if J and W then
local used = {}
local gj, gw = assert(Types.Scene.reader(J)), assert(Types.Scene.reader(W))
for k = 0, p.indices.count - 1 do
local v = buffer.readu32(p.indices.data, k * 4)
for c = 0, 3 do
if gw(v, c) > 0 then
used[gj(v, c)] = true
end
end
end
for _ in used do
bones += 1
end
end
end
end
return meshes, faces, corners, bones
end
local function bounds(scene: any): ({ number }?, { number }?)
local merged = MeshOps.merge(scene)
if not merged then
return nil, nil
end
return MeshOps.bounds(merged)
end
local function boundsMatch(lo: { number }?, hi: { number }?, a: any, eps: number): boolean
if not lo or not hi then
return false
end
for k = 1, 3 do
if not near(lo[k], a.min[k], eps) or not near(hi[k], a.max[k], eps) then
return false
end
end
return true
end
-- ------------------------------------------------------------------------------------------------ assimp
local scenes, byName = {}, {}
local checked = 0
for i, c in Cases do
byName[c.name] = c
local a = c.assimp
local scene, err = decode(c.data, { triangulate = false })
if a.failed then
t:note("%s: assimp rejects it; we: %s", c.name, if scene then "decoded" else tostring(err))
else
t:check(scene, c.name .. ": decode: " .. tostring(err))
scenes[c.name] = scene
local meshes, faces, corners, bones = counts(scene)
t:eq(meshes, a.meshes, c.name .. ": meshes (assimp)")
t:eq(faces + scene.meta.source.skippedFaces, a.faces, c.name .. ": faces (assimp)")
if scene.meta.source.skippedFaces == 0 then
t:eq(corners, a.vertices, c.name .. ": corners (assimp)")
end
t:eq(math.max(#scene.materials, 1), a.materials, c.name .. ": materials (assimp, its default when none)")
t:eq(#scene.animations, a.animations or 0, c.name .. ": animations (assimp)")
t:eq(bones, a.bones or 0, c.name .. ": bones (assimp)")
if a.min then
local lo, hi = bounds(scene)
t:check(boundsMatch(lo, hi, a, 1e-3), string.format("%s: world bounds (assimp) %s / %s", c.name, if lo then table.concat(lo, " ") else "-", if hi then table.concat(hi, " ") else "-"))
end
checked += 1
end
end
t:note("%d files checked against assimp", checked)
-- variants decode like their originals
for _, c in Cases do
if c.of then
local a, b = scenes[c.name], scenes[c.of]
if a and b then
local m1, f1, c1 = counts(a)
local m2, f2, c2 = counts(b)
t:check(m1 == m2 and f1 == f2 and c1 == c2, c.name .. ": same counts as " .. c.of)
local la, ha = bounds(a)
local lb, hb = bounds(b)
t:check(la and lb and boundsMatch(la, ha, { min = lb, max = hb }, 1e-5), c.name .. ": same bounds as " .. c.of)
t:eq(#a.animations, #b.animations, c.name .. ": same animations")
end
end
end
-- ------------------------------------------------------------------------------------------------ details
do
local s = scenes["models/kwxport_test_cubewithvcolors.x"]
local p = s.meshes[1].primitives[1]
t:check(p.attributes.COLOR_0 and p.attributes.COLOR_0.components == 4, "vertex colours -> COLOR_0")
t:eq(s.meta.source.encoding, "text", "text encoding")
local b = scenes["models/test_cube_binary.x"]
t:eq(b.meta.source.encoding, "binary", "binary encoding")
local z = scenes["models/test_cube_compressed.x"]
t:check(z.meta.source.compressed, "bzip")
local v = scenes["variant/test_cube_text.bin64.x"]
t:eq(v.meta.source.floatSize, 64, "64-bit floats")
end
do
-- textures: uri names, TEXCOORD_0
local s = scenes["models/test.x"]
local any = false
for _, m in s.materials do
if m.baseColorTexture then
local tex = s.textures[m.baseColorTexture.texture]
any = any or (type(tex.uri) == "string" and #tex.uri > 0)
end
end
t:check(any, "test.x: a texture file name")
t:check(s.meshes[1].primitives[1].attributes.TEXCOORD_0, "test.x: TEXCOORD_0")
end
do
-- skins: the inverse bind matrix of each joint times the joint's world bind matrix is about the same for all
-- joints (the mesh node's world matrix): checks the matrix layout and the handedness conversion together
local checkedSkins, consistent = 0, 0
for name, s in scenes do
for _, node in s.nodes do
if node.skin then
local skin = s.skins[node.skin]
local world = {}
local function worldOf(i: number): { number }
if world[i] then
return world[i]
end
local m = Types.Scene.nodeMatrix(s.nodes[i])
for pi, pn in s.nodes do
if table.find(pn.children, i) then
m = Types.Scene.mul(worldOf(pi), m)
break
end
end
world[i] = m
return m
end
local get = assert(Types.Scene.reader(skin.inverseBindMatrices))
local ref: { number }? = nil
local ok, total = 0, 0
for j, joint in skin.joints do
local inv = {}
for k = 1, 16 do
inv[k] = get(j - 1, k - 1)
end
local m = Types.Scene.mul(worldOf(joint), inv)
total += 1
if not ref then
ref = m
ok += 1
else
local same = true
for k = 1, 16 do
same = same and math.abs(m[k] - (ref :: any)[k]) < 1e-2 * math.max(1, math.abs(m[k]))
end
ok += if same then 1 else 0
end
end
t:note("%s: skin %d: bind pose consistent for %d / %d joints", name, node.skin, ok, total)
checkedSkins += 1
consistent += if ok >= total * 0.9 then 1 else 0
end
end
end
-- (anim_test.x's frames are not in the bind pose)
t:check(checkedSkins >= 4 and consistent >= checkedSkins * 0.7, string.format("skins consistent with the frames (%d / %d)", consistent, checkedSkins))
end
do
-- the rotation key convention: an animation's first rotation key mostly equals the bone's bind rotation
local same, total = 0, 0
for _, s in scenes do
for _, anim in s.animations do
for _, ch in anim.channels do
if ch.path == "rotation" then
local node = s.nodes[ch.node]
local r = node.rotation
if r then
local get = assert(Types.Scene.reader(ch.output))
local dot = 0
for k = 0, 3 do
dot += get(0, k) * r[k + 1]
end
total += 1
same += if math.abs(dot) > 0.999 then 1 else 0
end
end
end
end
end
t:check(total > 0 and same >= total * 0.5, string.format("first rotation keys match the bind pose (%d / %d)", same, total))
end
-- ------------------------------------------------------------------------------------------------ inline file
local CUBE = [[xof 0303txt 0032
// a quad and a triangle, two materials, one animated frame
Material Red { 1.0; 0.0; 0.0; 1.0;; 10.0; 0.5; 0.5; 0.5;; 0.0; 0.0; 0.0;; TextureFilename { "tex\\red.png"; } }
AnimTicksPerSecond { 100; }
Frame Root {
FrameTransformMatrix { 1,0,0,0, 0,1,0,0, 0,0,1,0, 1,2,3,1;; }
Mesh Shape {
5;
0;0;0;, 1;0;0;, 1;1;0;, 0;1;0;, 2;0;0;;
2;
4;0,1,2,3;,
3;1,4,2;;
MeshMaterialList { 2; 2; 0, 1;; { Red } Material Blue { 0;0;1;0.5;; 1; 0;0;0;; 0;0;0;; } }
MeshNormals { 1; 0;0;-1;; 2; 4;0,0,0,0;, 3;0,0,0;; }
MeshTextureCoords { 5; 0;0;, 1;0;, 1;1;, 0;1;, 0.5;0.5;; }
}
}
AnimationSet Move {
Animation { { Root } AnimationKey { 2; 2; 0; 3; 1;2;3;;, 100; 3; 1;2;5;;; } }
}
]]
do
local s, err = decode(CUBE, { triangulate = false })
t:check(s, "inline: " .. tostring(err))
t:eq(#s.nodes, 1, "inline: one frame")
local root = s.nodes[1]
t:check(root.translation and root.translation[1] == 1 and root.translation[3] == -3, "inline: translation, z negated")
t:eq(#s.materials, 2, "inline: global + inline material")
t:eq(s.materials[1].name, "Red", "inline: material name")
t:eq(s.textures[1].uri, "tex/red.png", "inline: texture uri (backslash -> slash)")
t:eq(s.materials[2].alphaMode, "blend", "inline: alpha < 1 -> blend")
local prims = s.meshes[1].primitives
t:eq(#prims, 2, "inline: one primitive per material")
t:eq(prims[1].material, 1, "inline: first face -> Red (referenced)")
t:eq(prims[2].material, 2, "inline: second face -> Blue")
t:eq(prims[1].faces.count, 1, "inline: the quad kept")
local N = assert(Types.Scene.reader(prims[1].attributes.NORMAL))
t:eq(N(0, 2), 1, "inline: normal z negated")
local anim = s.animations[1]
t:eq(anim.name, "Move", "inline: animation name")
local ch = anim.channels[1]
t:eq(ch.path, "translation", "inline: position key")
local ti, to = assert(Types.Scene.reader(ch.input)), assert(Types.Scene.reader(ch.output))
t:eq(ti(1, 0), 1, "inline: ticks -> seconds")
t:eq(to(1, 2), -5, "inline: key z negated")
local tri = decode(CUBE)
t:eq(tri.meshes[1].primitives[1].indices.count, 6, "inline: quad fan-triangulated")
end
-- ------------------------------------------------------------------------------------------------ errors
do
local _, e1 = decode("xof 0303txt 00")
t:check(e1 and e1.code == Err.TRUNCATED, "short: " .. tostring(e1))
local _, e2 = decode("xof 0303zzz 0032")
t:check(e2 and e2.code == Err.UNSUPPORTED, "encoding: " .. tostring(e2))
local _, e3 = decode("xof 0303txt 0016 Frame {}")
t:check(e3 and e3.code == Err.CORRUPT, "float size: " .. tostring(e3))
local _, e4 = decode("xof 0303txt 0032 Frame A { Mesh { 3; 0;0;0;, 1;0;0;, 0;1;0;; 1; 3; 0,1,7;; } }")
t:check(e4 and e4.code == Err.CORRUPT, "face index out of range: " .. tostring(e4))
local _, e5 = decode("xof 0303txt 0032 Frame A { ")
t:check(e5 and e5.code == Err.CORRUPT, "unterminated: " .. tostring(e5))
local _, e7 = decode("xof 0303txt 0032 Mesh { 33554431; 1; }")
t:check(e7 and e7.code == Err.TRUNCATED, "a vertex count past the data is refused before allocating: " .. tostring(e7))
local _, e6 = decode(CUBE, { maxValues = 10 })
t:check(e6 and e6.code == Err.LIMIT, "maxValues: " .. tostring(e6))
t:eq(X.sniff(Bytes.reader(buffer.fromstring(CUBE))), 1, "sniff")
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local samples = { CUBE }
for _, c in Cases do
if #c.data < 12000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local s = X.decode(Bytes.reader(b), { triangulate = false })
if s then
MeshOps.merge(s)
end
return s
end, samples, { mutations = 16, keepHeader = 16 })
end
t:done()
+308
View File
@@ -0,0 +1,308 @@
-- model/x3d tests: assimp's X3D / X3DV / X3DB test models, scenes and glTF samples written by VTK's X3D exporter and
-- by assimp's X3D exporter, and hand-written feature files (the X3D triangle / quad / line sets, ColorRGBA,
-- ProtoDeclare / ProtoInstance with SFNode defaults, PhysicalMaterial, UnlitMaterial, OrthoViewpoint, ROUTE
-- animation, UNIT, the classic encoding's header statements), against assimp's X3D reader (meshes, faces, materials,
-- world bounds) and exact expectations; .x3dv against the same model as .x3d; the writer (XML and classic): round
-- trips, and assimp reading our X3D like the originals; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/x3d.py.
local T = require("@tests/T")
local F = require("@formats")
local X3d = require("@formats/model/x3d")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local C = require("@tests/model/_vrml_common")
local Cases = require("@tests/gen/x3d_cases")
local VrmlCases = require("@tests/gen/vrml_cases")
local GltfCases = require("@tests/gen/vrml_gltf")
local Xcheck = require("@tests/gen/x3d_xcheck")
local Gltf = require("@formats/model/gltf")
local Vrml = require("@formats/model/vrml")
local t = T.suite("x3d")
local near = C.near
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return X3d.decode(Bytes.reader(b), opts)
end
t:eq(X3d.name, "x3d", "name")
t:eq(X3d.category, "model", "category")
t:check(X3d.caps.decode and X3d.caps.encode, "contract")
-- assimp's own quirks (its reading is not the specification's): USE'd groups lose their parents' transforms; its X3D
-- exporter writes points and lines as 1- / 2-vertex faces (not valid IndexedFaceSet faces, dropped here)
local QUIRK = { ["assimp/X3D/ComputerKeyboard.x3d"] = "all", ["assimp-export/assimp_MeshPrimitiveModes.x3d"] = "all" }
-- ------------------------------------------------------------------------------------------------ reference files
local scenes, byName = {}, {}
local checked = { assimp = 0, none = 0 }
for i, c in Cases do
local scene, err = decode(c.data, { files = c.files, triangulate = false })
if string.find(c.name, "%.x3db$") then
t:check(scene == nil and err and err.code == Err.UNSUPPORTED, c.name .. ": binary X3D is UNSUPPORTED: " .. tostring(err))
continue
end
t:check(scene, c.name .. ": decode: " .. tostring(err))
if not scene then
continue
end
scenes[i], byName[c.name] = scene, scene
local a = c.assimp
-- (VTK's exporter leaves </X3D> out: assimp then reads nothing)
local unclosed = a.meshes == 0 and not string.find(c.data, "</X3D>", 1, true)
if a.skip or a.failed or unclosed or string.find(c.name, "^feature/") then
checked.none += 1
continue
end
local s = C.stats(scene)
local quirk = QUIRK[c.name]
if quirk ~= "all" then
if quirk ~= "counts" then
t:eq(s.prims, a.meshes, c.name .. ": meshes (assimp: one per placed shape)")
end
if not c.primitives and quirk ~= "counts" then
t:eq(s.polys + s.lines + s.points, a.faces, c.name .. ": faces (assimp)")
end
t:check(#scene.materials <= a.materials, c.name .. ": materials (assimp counts one per use)")
if a.min then
t:check(C.boundsNear(s.lo, s.hi, a.min, a.max, if c.primitives then 5e-3 else 1e-5), c.name .. ": world bounds (assimp) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(a.min, a.max))
end
end
checked.assimp += 1
end
t:note("%d files: %d against assimp, %d without a reference", #Cases, checked.assimp, checked.none)
-- ------------------------------------------------------------------------------------------------ exact expectations
do
local kb = byName["assimp/X3D/ComputerKeyboard.x3d"]
if kb then
local s = C.stats(kb)
t:eq(#kb.meshes, 3, "keyboard: three extrusions (the keys are USE'd)")
t:check(s.prims > 50, "keyboard: every USE placed: " .. s.prims)
t:eq(#kb.animations, 1, "keyboard: the push animation")
t:check(#kb.animations[1].channels == s.prims - 2, "keyboard: one channel per escape-button instance")
t:check(near(s.hi[3], 0.980018, 1e-5) and near(s.lo[2], -0.0002, 1e-3), "keyboard: the base under its rotation")
end
local hw, hv = byName["assimp/X3D/HelloWorld.x3d"], byName["assimp/X3DV/HelloWorld.x3dv"]
if hw and hv then
local a, b = C.stats(hw), C.stats(hv)
t:check(a.polys == b.polys and C.boundsNear(a.lo, a.hi, b.lo, b.hi, 1e-9), ".x3dv = .x3d: geometry")
t:eq(hv.materials[1].baseColor[2], hw.materials[1].baseColor[2], ".x3dv = .x3d: material")
t:check(hv.textures[1].data and hw.textures[1].data, ".x3dv / .x3d: texture from files")
t:eq(hv.meta.source.profile, "Immersive", ".x3dv: PROFILE")
t:eq(hw.meta.source.profile, "Immersive", ".x3d: profile")
t:eq(hv.meta.source.meta.title, "HelloWorld.x3d", ".x3dv: META")
t:eq(hw.meta.source.meta.creator, "Don Brutzman", ".x3d: head meta")
end
local ls = byName["assimp/X3D/IndexedLineSet.x3d"]
if ls then
local p = ls.meshes[1].primitives[1]
t:check(p.mode == "lines" and p.indices.count == 8, "IndexedLineSet: a closed polyline as 4 segments")
t:check(ls.materials[1].emissive[1] == 1, "IndexedLineSet: emissive colour")
end
local sets = byName["feature/feat_sets.x3d"]
if sets then
local m = sets.meshes
local function tris(k: number): number
local p = m[k].primitives[1]
return if p.mode == "polygons" then p.faces.count else p.indices.count // 3
end
t:eq(tris(1), 2, "IndexedTriangleSet")
local col = m[1].primitives[1].attributes.COLOR_0
t:check(col and col.components == 4 and buffer.readf32(col.data, (2 * 4 + 3) * 4) == 0.5, "ColorRGBA alpha")
t:check(sets.materials[m[1].primitives[1].material].doubleSided, "solid false")
t:eq(tris(2), 3, "TriangleFanSet fanCount")
t:eq(tris(3), 3, "IndexedTriangleStripSet runs")
t:check(m[4].primitives[1].faces.count == 1 and m[4].primitives[1].indices.count == 4, "IndexedQuadSet: one quad")
t:eq(tris(5), 2, "TriangleSet")
t:check(m[6].primitives[1].mode == "lines" and m[6].primitives[1].indices.count == 6, "LineSet vertexCount")
-- strips alternate their winding: every triangle of the strip faces +z
local p = m[3].primitives[1]
local ok = true
local P = p.attributes.POSITION
local function v(i: number): (number, number)
local k = buffer.readu32(p.indices.data, i * 4)
return buffer.readf32(P.data, k * 12), buffer.readf32(P.data, k * 12 + 4)
end
local at = 0
for f = 0, p.faces.count - 1 do
local ax, ay = v(at)
local bx, by = v(at + 1)
local cx, cy = v(at + 2)
ok = ok and (bx - ax) * (cy - ay) - (by - ay) * (cx - ax) > 0
at += buffer.readu32(p.faces.data, f * 4)
end
t:check(ok, "IndexedTriangleStripSet: counter-clockwise triangles")
end
local pr = byName["feature/feat_proto.x3d"]
if pr then
local s = C.stats(pr)
t:check(C.boundsNear(s.lo, s.hi, { -1.1, -2, -0.5 }, { 1.1, 5, 0.5 }, 1e-6), "protos: instances placed and sized " .. C.fmt(s.lo, s.hi))
t:eq(pr.meta.unit, 0.01, "UNIT length")
t:eq(pr.meta.source.meta.title, "protos", "head meta")
local kinds = {}
for _, m in pr.materials do
if m.extensions and m.extensions.KHR_materials_unlit then
kinds.unlit = m
elseif m.metallic == 0.25 then
kinds.physical = m
elseif m.baseColor[3] == 1 and m.baseColor[1] == 0 then
kinds.default = m
end
end
t:check(kinds.physical and kinds.physical.roughness == 0.75, "PhysicalMaterial")
t:check(kinds.unlit and kinds.unlit.baseColor[2] == 1, "UnlitMaterial")
t:check(kinds.default ~= nil, "SFNode field default (the proto's appearance)")
t:eq(#pr.materials, 3, "the default appearance is shared by both instances")
local cam = pr.cameras[1]
t:check(cam and cam.type == "orthographic" and cam.xmag == 2 and cam.ymag == 1, "OrthoViewpoint")
local a = pr.animations[1]
t:check(a and a.name == "Clock" and #a.channels == 1 and a.channels[1].path == "rotation", "ROUTE elements -> animation")
t:check(a and near(buffer.readf32(a.channels[1].input.data, 8), 2, 1e-6), "key times x cycleInterval")
-- quaternion keys stay on one hemisphere (0, pi, 2 pi about y)
local q = a and a.channels[1].output
t:check(q and buffer.readf32(q.data, 2 * 16 + 12) < 0, "rotation keys continuous")
end
local cl = byName["feature/feat_classic.x3dv"]
if cl then
local s = C.stats(cl)
t:check(C.boundsNear(s.lo, s.hi, { 1, 2, 3 }, { 2, 3, 4 }, 1e-6), "classic: DEF Transform")
t:eq(cl.meta.unit, 0.001, "classic: UNIT")
t:eq(cl.meta.source.components[1], "Geometry2D:1", "classic: COMPONENT")
t:eq(cl.meta.source.meta.title, "classic", "classic: META")
t:eq(cl.meshes[1].primitives[1].attributes.COLOR_0.components, 4, "classic: ColorRGBA")
end
end
-- ------------------------------------------------------------------------------------------------ writer
local function compare(a: any, b: any, label: string)
local sa, sb = C.stats(a), C.stats(b)
t:eq(sb.prims, sa.prims, label .. ": placed primitives")
t:eq(sb.polys, sa.polys, label .. ": faces")
t:eq(sb.lines, sa.lines, label .. ": line segments")
t:eq(sb.points, sa.points, label .. ": points")
if sa.prims > 0 and sa.lo[1] <= sa.hi[1] then
t:check(C.boundsNear(sa.lo, sa.hi, sb.lo, sb.hi, 1e-5), label .. ": bounds")
t:check(near(sa.area, sb.area, 1e-4), label .. ": area")
end
t:eq(#b.materials, #a.materials, label .. ": materials")
t:eq(#b.cameras, #a.cameras, label .. ": cameras")
t:eq(#b.lights, #a.lights, label .. ": lights")
t:eq(#b.animations, #a.animations, label .. ": animations")
for k, cam in a.cameras do
t:eq(b.cameras[k].type, cam.type, label .. ": camera type")
end
end
local rt = 0
for i, c in Cases do
local a = scenes[i]
if a then
for _, enc in { "xml", "x3dv" } do
local files = {}
local out, err = X3d.encode(a, { files = files, encoding = enc :: any })
t:check(out, c.name .. ": encode " .. enc .. ": " .. tostring(err))
local b = out and decode(out, { files = files, triangulate = false })
t:check(b, c.name .. ": decode our " .. enc)
if b then
compare(a, b, c.name .. " (" .. enc .. ")")
rt += 1
end
end
end
end
t:note("%d round trips", rt)
-- assimp reads our X3D like the source
local sources: { [string]: { any } } = { xcase = {}, wcase = {}, xgltf = {} }
for i, c in Cases do
sources.xcase[i] = { scenes[i], c }
end
for i, c in VrmlCases do
sources.wcase[i] = { Vrml.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false }), c }
end
for i, c in GltfCases do
sources.xgltf[i] = { Gltf.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }), c }
end
-- assimp loses its place in the tree after an empty <Transform/> (a leaf node: an empty, a locator)
local function hasEmpty(scene: any): boolean
for _, n in scene.nodes do
if #n.children == 0 and not n.mesh and not n.camera and not n.light then
return true
end
end
return false
end
local xc, skipped = 0, 0
for _, x in Xcheck do
local a = x.assimp
local kind = if x.xcase then "xcase" elseif x.wcase then "wcase" else "xgltf"
local src = sources[kind][x[kind]]
if src and src[1] and (a.failed or a.meshes == 0) and hasEmpty(src[1]) then
skipped += 1
elseif src and src[1] and not a.failed then
local s = C.stats(src[1])
t:eq(a.meshes, s.prims, x.name .. ": meshes (assimp reads our file)")
t:eq(a.faces, s.polys + s.lines + s.points, x.name .. ": faces (assimp reads our file)")
-- (shared meshes are written once and USE'd: assimp places USE'd nodes without their parents' transforms)
-- (MotionCaptureROM: assimp misplaces this deep hierarchy; an independent evaluation of our file's transforms
-- agrees with ours)
local deep = src[2].name == "assimp/MotionCaptureROM.WRL"
if a.min and s.lo[1] <= s.hi[1] and s.prims == s.unique and not deep then
t:check(C.boundsNear(s.lo, s.hi, a.min, a.max, 1e-4), x.name .. ": bounds (assimp reads our file) " .. C.fmt(s.lo, s.hi) .. " vs " .. C.fmt(a.min, a.max))
end
xc += 1
elseif src and src[1] then
t:check(false, x.name .. ": assimp cannot read our file (" .. src[2].name .. ")")
end
end
t:note("%d of our files read by assimp (%d skipped: empty nodes)", xc, skipped)
-- ------------------------------------------------------------------------------------------------ api, errors
do
local hw = Cases[2]
t:eq(F.detect(hw.data), "x3d", "F.detect .x3d")
t:eq(F.detect(Cases[5].data), "x3d", "F.detect .x3dv")
local s = F.load(hw.data, { files = hw.files })
t:check(s and s.meta.source.format == "x3d", "F.load")
local x3dv = F.save(s, nil, { format = "x3dv" })
t:check(x3dv and buffer.readstring(x3dv, 0, 5) == "#X3D ", "F.save format x3dv: the classic encoding")
local xml = F.save(s, nil, { format = "x3d" })
t:check(xml and string.find(buffer.tostring(xml), "<X3D", 1, true) ~= nil, "F.save format x3d: XML")
local _, e1 = decode("<X3D><Scene><Shape><Box/></Scene></X3D>")
t:check(e1 and (e1.code == Err.TRUNCATED or e1.code == Err.CORRUPT), "mismatched XML: " .. tostring(e1))
local _, e2 = decode("<?xml version='1.0'?><COLLADA/>")
t:check(e2 and e2.code == Err.CORRUPT, "not X3D: " .. tostring(e2))
-- VTK leaves the root element open: read anyway
local open = decode("<X3D><Scene><Shape><Box/></Shape></Scene>\n")
t:check(open and #open.meshes == 1, "an unclosed <X3D> root (VTK's exporter)")
local _, e3 = X3d.encode({} :: any)
t:check(e3 and e3.code == Err.ARG, "encode junk")
-- containerField and USE in XML
local u = decode([[<X3D><Scene><Shape DEF="S"><IndexedFaceSet coordIndex="0 1 2"><Coordinate point="0 0 0 1 0 0 0 1 0"/></IndexedFaceSet></Shape>
<Transform translation="5 0 0"><Shape USE="S"/></Transform>
<Switch whichChoice="0"><Group><Shape><Sphere containerField="geometry" radius="2"/></Shape></Group></Switch></Scene></X3D>]])
local us = u and C.stats(u)
t:check(us and #u.meshes == 2 and us.prims == 3 and near(us.hi[1], 6, 1e-9) and near(us.hi[2], 2, 1e-6), "USE / containerField / Switch in XML")
end
-- ------------------------------------------------------------------------------------------------ fuzz
do
local samples = {}
for _, c in Cases do
if #c.data < 40000 then
table.insert(samples, c.data)
end
end
t:fuzz("decode", function(b: buffer)
local s = X3d.decode(Bytes.reader(b), { files = {} })
if s then
X3d.encode(s)
end
return s
end, samples, { mutations = 16, keepHeader = 16 })
end
t:done()