merge ws/3d2
This commit is contained in:
commit
17c00a15df
45 files changed
+16368
-2
No files matched your search
@@ -0,0 +1,392 @@
|
||||
-- cad/step tests: STEP files written by OCCT (solids modelled in gmsh's OpenCASCADE kernel) and public sample files,
|
||||
-- against an independent Python Part 21 census (instances, count per type); our writer's output read back by OCCT
|
||||
-- (solids, volume, faces, area, bounding box equal to the originals); parse -> write -> parse equality; every
|
||||
-- parameter kind and string escape, complex instances, edition 3 sections, comments; the api (F.load / F.save /
|
||||
-- F.cad.*); the B-rep plug-in path through brep-luau (luau CLI only: the alias in tests/gen/.luaurc) against OCCT's
|
||||
-- volumes and bounds, and a custom plug-in table; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/step.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Step = require("@formats/cad/step")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Cases = require("@tests/gen/step_cases")
|
||||
|
||||
local t = T.suite("step")
|
||||
|
||||
local function decode(s: string, opts: any?): (any, any)
|
||||
return Step.decode(Bytes.reader(buffer.fromstring(s)), opts)
|
||||
end
|
||||
local function encode(cad: any, opts: any?): string
|
||||
local b, err = Step.encode(cad, opts)
|
||||
t:check(b, "encode: " .. tostring(err))
|
||||
return if b then buffer.tostring(b) else ""
|
||||
end
|
||||
local function near(a: number, b: number, rel: number): boolean
|
||||
return math.abs(a - b) <= rel * math.max(1, math.abs(a), math.abs(b))
|
||||
end
|
||||
|
||||
-- 1. contract
|
||||
t:eq(Step.name, "step", "name")
|
||||
t:eq(Step.category, "cad", "category")
|
||||
t:check(Step.caps.decode and Step.caps.encode and table.find(Step.extensions, "stp"), "contract")
|
||||
|
||||
-- deep equality of two decoded values (buffers, the real marks of lists included)
|
||||
local function same(a: any, b: any, path: string, depth: number?): (boolean, string)
|
||||
local d = depth or 0
|
||||
if type(a) ~= "table" or type(b) ~= "table" then
|
||||
return a == b, path
|
||||
end
|
||||
if a == b then
|
||||
return true, path
|
||||
end
|
||||
if d > 60 then
|
||||
return false, path .. " (too deep)"
|
||||
end
|
||||
for k, v in a do
|
||||
local ok, where = same(v, b[k], path .. "." .. tostring(k), d + 1)
|
||||
if not ok then
|
||||
return false, where
|
||||
end
|
||||
end
|
||||
for k in b do
|
||||
if a[k] == nil then
|
||||
return false, path .. "." .. tostring(k) .. " (extra)"
|
||||
end
|
||||
end
|
||||
local ma, mb = getmetatable(a), getmetatable(b)
|
||||
local ra = ma and ma.__reals or {}
|
||||
local rb = mb and mb.__reals or {}
|
||||
for k in ra do
|
||||
if not rb[k] then
|
||||
return false, path .. "[" .. tostring(k) .. "] real mark"
|
||||
end
|
||||
end
|
||||
for k in rb do
|
||||
if not ra[k] then
|
||||
return false, path .. "[" .. tostring(k) .. "] real mark (extra)"
|
||||
end
|
||||
end
|
||||
return true, path
|
||||
end
|
||||
|
||||
-- 2. fixtures: census, round trips; OCCT read our output like the original
|
||||
local decoded = {}
|
||||
local samples = {}
|
||||
local t0 = T.clock()
|
||||
local bytes = 0
|
||||
for i, c in Cases do
|
||||
local cad, err = decode(c.data)
|
||||
t:check(cad, c.name .. ": decode: " .. tostring(err))
|
||||
decoded[i] = cad
|
||||
bytes += #c.data
|
||||
t:eq(cad.meta.count, c.census.count, c.name .. ": instances (census)")
|
||||
local types = {}
|
||||
for _, e in cad.entities do
|
||||
types[e.type] = (types[e.type] or 0) + 1
|
||||
end
|
||||
for ty, n in c.census.types do
|
||||
t:eq(types[ty], n, c.name .. ": " .. ty .. " count")
|
||||
end
|
||||
for ty in types do
|
||||
t:check(c.census.types[ty], c.name .. ": no extra type " .. ty)
|
||||
end
|
||||
local text = encode(cad)
|
||||
local again = decode(text)
|
||||
t:check(again, c.name .. ": our output decodes")
|
||||
local ok, where = same(cad.entities, again.entities, "entities")
|
||||
t:check(ok, c.name .. ": round trip differs at " .. where)
|
||||
t:eq(encode(again), text, c.name .. ": write is stable")
|
||||
t:check(same(cad.header, again.header, "header"), c.name .. ": header round trip")
|
||||
if c.occt and not c.occt.failed then
|
||||
t:check(c.ours and not c.ours.failed, c.name .. ": OCCT reads our output")
|
||||
t:eq(c.ours.solids, c.occt.solids, c.name .. ": OCCT solids of our output")
|
||||
t:eq(c.ours.faces, c.occt.faces, c.name .. ": OCCT faces of our output")
|
||||
t:check(near(c.ours.volume, c.occt.volume, 1e-9), c.name .. ": OCCT volume of our output")
|
||||
t:check(near(c.ours.area, c.occt.area, 1e-9), c.name .. ": OCCT area of our output")
|
||||
end
|
||||
if #samples < 4 and #c.data < 40000 then
|
||||
table.insert(samples, buffer.fromstring(c.data))
|
||||
end
|
||||
end
|
||||
local dt = T.clock() - t0
|
||||
t:note("%d files (%.1f MB): census, OCCT read-back, round trips (%.2f s)", #Cases, bytes / 1e6, dt)
|
||||
|
||||
-- 3. every parameter kind, escapes, complex instances, sections, comments
|
||||
local CRAFT = [[
|
||||
ISO-10303-21; /* a comment */
|
||||
HEADER;
|
||||
FILE_DESCRIPTION(('test'),'2;1');
|
||||
FILE_NAME('craft.stp','2024-01-01T00:00:00',('A \X2\00C9\X0\crivain'),(''),'','','');
|
||||
FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));
|
||||
ENDSEC;
|
||||
DATA;
|
||||
#1=CARTESIAN_POINT('',(0.,1.5,-2.E-3));
|
||||
#2 = DIRECTION ( 'd' , ( 1. , 0. , 0. ) ) ;
|
||||
#3=FOO('It''s','back\\slash','\S\i','\X\E9t\X\E9','\X2\03B103B2\X0\ ok','\X4\0001F600\X0\',.T.,.UNSPECIFIED.,$,*,#1,
|
||||
"0FF",LENGTH_MEASURE(2.),POSITIVE_LENGTH_MEASURE(3.5),(1,2,(3,4.)),(),-7,+8,1.E2);
|
||||
#10=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNIT_ASSIGNED_CONTEXT((#11))REPRESENTATION_CONTEXT('c','3D'));
|
||||
#11=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.));
|
||||
/* comment between instances */
|
||||
#12=!USER_DEFINED(1);
|
||||
ENDSEC;
|
||||
END-ISO-10303-21;
|
||||
]]
|
||||
local cad, err = decode(CRAFT)
|
||||
t:check(cad, "craft: " .. tostring(err))
|
||||
t:eq(cad.schema, "AP214", "craft: schema")
|
||||
t:eq(cad.meta.count, 6, "craft: count")
|
||||
t:eq(cad.header.FILE_NAME[3][1], "A Écrivain", "craft: header \\X2\\")
|
||||
local p = cad.entities[1]
|
||||
t:eq(p.type, "CARTESIAN_POINT", "craft: type")
|
||||
t:eq(p.args[2][3], -2e-3, "craft: real")
|
||||
t:check(getmetatable(p.args[2]).__reals[1] and getmetatable(p.args[2]).__reals[2] == nil, "craft: integral real marked")
|
||||
t:eq(cad.entities[2].args[1], "d", "craft: spaced instance")
|
||||
local a = cad.entities[3].args
|
||||
t:eq(a[1], "It's", "craft: ''")
|
||||
t:eq(a[2], "back\\slash", "craft: \\\\")
|
||||
t:eq(a[3], "é", "craft: \\S\\")
|
||||
t:eq(a[4], "été", "craft: \\X\\")
|
||||
t:eq(a[5], "αβ ok", "craft: \\X2\\")
|
||||
t:eq(a[6], "😀", "craft: \\X4\\")
|
||||
t:eq(a[7].enum, "T", "craft: boolean")
|
||||
t:eq(a[8].enum, "UNSPECIFIED", "craft: enum")
|
||||
t:eq(a[9], Step.NULL, "craft: $")
|
||||
t:eq(a[10], Step.DERIVED, "craft: *")
|
||||
t:eq(a[11].ref, 1, "craft: ref")
|
||||
t:eq(Step.get(cad, a[11]), p, "craft: get(ref)")
|
||||
t:eq(a[12].binary, "0FF", "craft: binary")
|
||||
t:eq(a[13].typed, "LENGTH_MEASURE", "craft: typed")
|
||||
t:eq(a[13].value, 2, "craft: typed value")
|
||||
t:eq(a[14].value, 3.5, "craft: typed real")
|
||||
t:eq(a[15][3][2], 4, "craft: nested list")
|
||||
t:eq(#a[16], 0, "craft: empty list")
|
||||
t:eq(a[17], -7, "craft: negative integer")
|
||||
t:eq(a[18], 8, "craft: +integer")
|
||||
t:eq(a[19], 100, "craft: 1.E2")
|
||||
local cx = cad.entities[10]
|
||||
t:eq(cx.type, "COMPLEX", "craft: complex")
|
||||
t:eq(#cx.parts, 3, "craft: complex parts")
|
||||
t:eq(Step.part(cx, "GEOMETRIC_REPRESENTATION_CONTEXT")[1], 3, "craft: part()")
|
||||
t:eq(Step.part(cad.entities[11], "SI_UNIT")[2].enum, "METRE", "craft: SI_UNIT part")
|
||||
t:eq(cad.entities[12].type, "!USER_DEFINED", "craft: user-defined entity")
|
||||
t:eq(#Step.byType(cad, "SI_UNIT"), 1, "craft: byType through complex parts")
|
||||
local text = encode(cad)
|
||||
t:check(string.find(text, "#3=FOO('It''s','back\\\\slash','\\X2\\00E9\\X0\\'", 1, true), "craft: strings re-escaped")
|
||||
t:check(string.find(text, "'\\X4\\0001F600\\X0\\'", 1, true), "craft: \\X4\\ written")
|
||||
t:check(string.find(text, "CARTESIAN_POINT('',(0.,1.5,-0.002))", 1, true), "craft: reals written")
|
||||
t:check(string.find(text, "LENGTH_MEASURE(2.)", 1, true), "craft: typed integral real")
|
||||
t:check(string.find(text, "(1,2,(3,4.)),(),-7,8,100.);", 1, true), "craft: integers and lists")
|
||||
t:check(string.find(text, "#10=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNIT_ASSIGNED_CONTEXT((#11))", 1, true), "craft: complex written")
|
||||
local back = decode(text)
|
||||
t:check(back and same(cad.entities, back.entities, "entities"), "craft: round trip")
|
||||
t:eq(back.header.FILE_NAME[3][1], "A Écrivain", "craft: header round trip")
|
||||
|
||||
-- edition 3: named DATA sections, ANCHOR section kept raw
|
||||
local ED3 = [[ISO-10303-21;
|
||||
HEADER;
|
||||
FILE_DESCRIPTION((''),'3;1');
|
||||
FILE_NAME('','',(''),(''),'','','');
|
||||
FILE_SCHEMA(('CONFIG_CONTROL_DESIGN','OTHER_SCHEMA'));
|
||||
ENDSEC;
|
||||
ANCHOR;
|
||||
<http://example.org/a> = #1;
|
||||
ENDSEC;
|
||||
DATA('first',('CONFIG_CONTROL_DESIGN'));
|
||||
#1=A(1);
|
||||
ENDSEC;
|
||||
DATA('second',('OTHER_SCHEMA'));
|
||||
#2=B('x;y',#1);
|
||||
ENDSEC;
|
||||
END-ISO-10303-21;
|
||||
]]
|
||||
local e3, e3err = decode(ED3)
|
||||
t:check(e3, "ed3: " .. tostring(e3err))
|
||||
t:eq(e3.schema, "AP203", "ed3: schema")
|
||||
t:eq(#e3.meta.source.sections, 2, "ed3: sections")
|
||||
t:eq(e3.entities[2].section, 2, "ed3: entity section")
|
||||
t:eq(e3.entities[2].args[1], "x;y", "ed3: ; inside a string")
|
||||
t:eq(e3.meta.source.extra[1].name, "ANCHOR", "ed3: anchor kept")
|
||||
local e3text = encode(e3)
|
||||
t:check(string.find(e3text, "DATA('second',('OTHER_SCHEMA'));\n#2=B('x;y',#1);", 1, true), "ed3: sections written")
|
||||
t:check(string.find(e3text, "ANCHOR;\n<http://example.org/a> = #1;\nENDSEC;", 1, true), "ed3: anchor written")
|
||||
local e3b = decode(e3text)
|
||||
t:check(e3b and same(e3.entities, e3b.entities, "e"), "ed3: round trip")
|
||||
|
||||
-- 4. building a file
|
||||
local new = Step.new("AP242")
|
||||
local pt = Step.add(new, "cartesian_point", { "origin", Step.real({ 0, 0, 1.25 }, 1) })
|
||||
Step.add(new, "VERTEX_POINT", { "", { ref = pt } })
|
||||
local ntext = encode(new, { name = "built.stp" })
|
||||
t:check(string.find(ntext, "FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }'));", 1, true), "new: schema")
|
||||
t:check(string.find(ntext, "#1=CARTESIAN_POINT('origin',(0.,0,1.25));\n#2=VERTEX_POINT('',#1);", 1, true), "new: instances")
|
||||
t:eq(decode(ntext).schema, "AP242", "new: decodes")
|
||||
local _, bad = Step.encode({ kind = "cad", entities = { [1] = { id = 1, type = "X", args = { 0 / 0 } } }, header = {}, meta = {} })
|
||||
t:eq(bad and bad.code, Err.ARG, "encode: nan -> ARG")
|
||||
local _, bad2 = Step.encode({ kind = "cad", entities = { [1] = { id = 1, type = "bad type", args = {} } }, header = {}, meta = {} })
|
||||
t:eq(bad2 and bad2.code, Err.ARG, "encode: bad type -> ARG")
|
||||
local cyc = {}
|
||||
cyc[1] = cyc
|
||||
local _, bad3 = Step.encode({ kind = "cad", entities = { [1] = { id = 1, type = "X", args = cyc } }, header = {}, meta = {} })
|
||||
t:eq(bad3 and bad3.code, Err.ARG, "encode: cycle -> ARG")
|
||||
local _, bad4 = Step.encode({ kind = "image" } :: any)
|
||||
t:eq(bad4 and bad4.code, Err.ARG, "encode: not a Cad")
|
||||
|
||||
-- 5. errors and sniff
|
||||
local function code(s: string, opts: any?): string?
|
||||
local v, e = decode(s, opts)
|
||||
return if v then nil else e.code
|
||||
end
|
||||
t:eq(code("hello"), Err.CORRUPT, "no magic")
|
||||
t:eq(code(string.sub(CRAFT, 1, 400)), Err.TRUNCATED, "truncated")
|
||||
t:eq(code("ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=A(1,;\nENDSEC;\nEND-ISO-10303-21;"), Err.CORRUPT, "bad list")
|
||||
t:eq(code("ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=A('x);\nENDSEC;\n"), Err.TRUNCATED, "open string")
|
||||
t:eq(code(CRAFT, { maxEntities = 3 }), Err.LIMIT, "maxEntities")
|
||||
t:eq(code(CRAFT, { maxBytes = 100 }), Err.LIMIT, "maxBytes")
|
||||
t:eq(code("ISO-10303-21;\nHEADER;\nENDSEC;\n"), Err.TRUNCATED, "no DATA")
|
||||
local deep = "ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=A(" .. string.rep("(", 500) .. string.rep(")", 500) .. ");\nENDSEC;\n"
|
||||
t:eq(code(deep), Err.CORRUPT, "nesting limit")
|
||||
t:eq(Step.sniff(Bytes.reader(buffer.fromstring(CRAFT))), 1, "sniff")
|
||||
t:eq(Step.sniff(Bytes.reader(buffer.fromstring("\239\187\191/* x */ ISO-10303-21;"))), 1, "sniff: BOM + comment")
|
||||
t:eq(Step.sniff(Bytes.reader(buffer.fromstring("ISO-10303-28"))), 0, "sniff: other")
|
||||
|
||||
-- 6. the api
|
||||
local loaded, lerr = F.load(CRAFT)
|
||||
t:check(loaded and loaded.kind == "cad", "F.load: " .. tostring(lerr))
|
||||
t:eq(F.detect(CRAFT), "step", "F.detect")
|
||||
local saved = F.save(loaded)
|
||||
t:check(type(saved) == "buffer" and decode(buffer.tostring(saved)).meta.count == 6, "F.save (source format)")
|
||||
local _, nop = Step.toBodies(loaded)
|
||||
t:eq(nop and nop.code, Err.UNSUPPORTED, "toBodies without a plug-in")
|
||||
local _, nop2 = F.cad.tessellate(loaded)
|
||||
t:eq(nop2 and nop2.code, Err.UNSUPPORTED, "F.cad.tessellate without a plug-in")
|
||||
|
||||
-- 7. the plug-in: a custom interface table
|
||||
local calls = {}
|
||||
local fake = {
|
||||
read = function(text: string, _opts: any): any
|
||||
calls.read = #text
|
||||
return { bodies = { { name = "tri", color = { 1, 0, 0 } } }, stats = { solids = 1 } }
|
||||
end,
|
||||
write = function(bodies: { any }, _opts: any): string
|
||||
calls.write = #bodies
|
||||
return CRAFT
|
||||
end,
|
||||
tessellate = function(_body: any, _opts: any): any
|
||||
return { positions = { { 0, 0, 0 }, { x = 1, y = 0, z = 0 }, { 0, 1, 0 }, { 0, 0, 1 } }, indices = { 1, 3, 2, 1, 2, 4, 1, 4, 3, 2, 3, 4 } }
|
||||
end,
|
||||
}
|
||||
local fb, finfo = Step.toBodies(loaded, { brep = fake })
|
||||
t:check(fb and #fb == 1 and finfo.stats.solids == 1 and calls.read > 0, "custom plug-in: toBodies")
|
||||
local fc = Step.fromBodies({ {} }, { plugins = { brep = fake } })
|
||||
t:check(fc and fc.kind == "cad" and calls.write == 1, "custom plug-in: fromBodies")
|
||||
local fs, fserr = Step.tessellate(loaded, { brep = fake })
|
||||
t:check(fs and fs.kind == "scene", "custom plug-in: tessellate: " .. tostring(fserr))
|
||||
t:eq(fs.meta.up, "z", "scene: z up")
|
||||
t:eq(fs.meta.unit, 0.001, "scene: millimetres")
|
||||
t:eq(fs.meshes[1].name, "tri", "scene: body name")
|
||||
t:eq(fs.materials[fs.meshes[1].primitives[1].material].extras.color[1], 1, "scene: body colour")
|
||||
t:eq(fs.meshes[1].primitives[1].indices.count, 12, "scene: indices")
|
||||
local throwing = { read = function(): any
|
||||
error("kernel failure")
|
||||
end }
|
||||
local _, terr = Step.toBodies(loaded, { brep = throwing })
|
||||
t:eq(terr and terr.code, Err.CORRUPT, "plug-in that throws -> Err")
|
||||
F.plugins.brep = fake
|
||||
local fapi = F.cad.tessellate(loaded)
|
||||
t:check(fapi and fapi.kind == "scene", "F.cad.tessellate through F.plugins")
|
||||
F.plugins.brep = nil
|
||||
|
||||
-- 8. brep-luau (luau CLI: tests/gen/.luaurc aliases it; LuaJIT has no `vector` type: skipped)
|
||||
local function volume(scene: any): (number, { number })
|
||||
local v = 0
|
||||
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
|
||||
for _, m in scene.meshes do
|
||||
for _, pr in m.primitives do
|
||||
local pos, ind = pr.attributes.POSITION.data, pr.indices.data
|
||||
local function P(i: number, k: number): number
|
||||
return buffer.readf32(pos, (i * 3 + k) * 4)
|
||||
end
|
||||
for tri = 0, pr.indices.count // 3 - 1 do
|
||||
local ia, ib, ic = buffer.readu32(ind, tri * 12), buffer.readu32(ind, tri * 12 + 4), buffer.readu32(ind, tri * 12 + 8)
|
||||
local ax, ay, az = P(ia, 0), P(ia, 1), P(ia, 2)
|
||||
local bx, by, bz = P(ib, 0), P(ib, 1), P(ib, 2)
|
||||
local cx2, cy, cz = P(ic, 0), P(ic, 1), P(ic, 2)
|
||||
v += (ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx2) + az * (bx * cy - by * cx2)) / 6
|
||||
for _, q in { { ax, ay, az }, { bx, by, bz }, { cx2, cy, cz } } do
|
||||
for k = 1, 3 do
|
||||
lo[k] = math.min(lo[k], q[k])
|
||||
hi[k] = math.max(hi[k], q[k])
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return v, { lo[1], lo[2], lo[3], hi[1], hi[2], hi[3] }
|
||||
end
|
||||
|
||||
local brepOk, brep = false, nil
|
||||
if T.runtime == "luau" then
|
||||
local ok, mods = pcall(require, "@tests/gen/step_brep")
|
||||
brepOk, brep = ok and type(mods) == "table", mods
|
||||
end
|
||||
if brepOk then
|
||||
local plug = { Step = brep.Step, StepBrep = brep.StepBrep, StepWrite = brep.StepWrite, Tess = brep.Tess }
|
||||
local n = 0
|
||||
for i, c in Cases do
|
||||
-- the gmsh solids and the small public part (the 2 MB sample takes too long to tessellate here)
|
||||
if decoded[i] and c.occt and not c.occt.failed and #c.data < 400000 then
|
||||
local scene, serr = Step.tessellate(decoded[i], { brep = plug, tess = { chord = 0.01, angle = 0.05 } })
|
||||
t:check(scene, c.name .. ": tessellate: " .. tostring(serr))
|
||||
if scene then
|
||||
local bodies = Step.toBodies(decoded[i], { brep = plug })
|
||||
t:eq(#bodies, c.occt.solids, c.name .. ": solids (OCCT)")
|
||||
local v, bb = volume(scene)
|
||||
-- brep-luau reading the original text directly: our parse + write must not change what the kernel sees
|
||||
local direct = brep.StepBrep.read(brep.Step.parse(c.data)).bodies
|
||||
local dv, leaks = 0, 0
|
||||
for _, b in direct do
|
||||
local m = brep.Tess.body(b, { chord = 0.01, angle = 0.05 })
|
||||
dv += brep.Tess.volume(m)
|
||||
leaks += brep.Tess.leaks(m)
|
||||
end
|
||||
t:check(near(v, dv, 1e-6), string.format("%s: volume %.4f, brep-luau on the original %.4f", c.name, v, dv))
|
||||
if leaks == 0 then
|
||||
t:check(near(v, c.occt.volume, 2e-3), string.format("%s: volume %.3f, OCCT %.3f", c.name, v, c.occt.volume))
|
||||
else
|
||||
t:note("%s: brep-luau's tessellation leaks (%d open edges): volume %.1f vs OCCT %.1f not compared", c.name, leaks, v, c.occt.volume)
|
||||
end
|
||||
for k = 1, 6 do
|
||||
-- (OCCT's box is not tight around curved faces: ours must lie inside it)
|
||||
local inside = if k <= 3 then bb[k] >= c.occt.bbox[k] - 0.05 else bb[k] <= c.occt.bbox[k] + 0.05
|
||||
t:check(inside, string.format("%s: bounds[%d] %.4f, OCCT %.4f", c.name, k, bb[k], c.occt.bbox[k]))
|
||||
end
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
-- kernel bodies -> our Cad -> our text -> bodies again
|
||||
local M = brep.M
|
||||
local part = brep.Boolean.subtract(brep.Build.box(M.v(0, 0, 0), M.v(40, 30, 5)), brep.Build.cylinder(M.v(20, 15, -1), 6, 7))[1]
|
||||
part.color = { r = 0.2, g = 0.5, b = 0.9 }
|
||||
local built, berr = F.cad.fromBodies({ part }, { brep = plug })
|
||||
t:check(built and built.kind == "cad" and #Step.byType(built, "ADVANCED_FACE") >= 7, "fromBodies: " .. tostring(berr))
|
||||
local again2 = decode(encode(built))
|
||||
local scene2 = Step.tessellate(again2, { brep = plug, chord = 0.01 })
|
||||
local v2 = volume(scene2)
|
||||
local want = brep.Tess.volume(brep.Tess.body(part, { chord = 0.01 }))
|
||||
t:check(near(v2, want, 1e-3), string.format("fromBodies round trip: volume %.3f, kernel %.3f", v2, want))
|
||||
t:check(near(v2, 40 * 30 * 5 - math.pi * 36 * 5, 2e-3), "fromBodies round trip: analytic volume")
|
||||
local col = scene2.materials[scene2.meshes[1].primitives[1].material].extras.color
|
||||
t:check(col and near(col[1], 0.2, 1e-6) and near(col[3], 0.9, 1e-6), "fromBodies round trip: colour")
|
||||
t:note("brep-luau plug-in: %d files tessellated against OCCT, bodies -> STEP -> bodies", n)
|
||||
else
|
||||
t:note("brep-luau plug-in part skipped (%s)", if T.runtime ~= "luau" then "LuaJIT: no vector type" else "no ~/dev/luau/brep-luau")
|
||||
end
|
||||
|
||||
-- 9. fuzz
|
||||
table.insert(samples, buffer.fromstring(CRAFT))
|
||||
table.insert(samples, buffer.fromstring(ED3))
|
||||
t:fuzz("decode", function(b: buffer): any
|
||||
return Step.decode(Bytes.reader(b))
|
||||
end, samples, { keepHeader = 13 })
|
||||
t:done()
|
||||
@@ -0,0 +1,420 @@
|
||||
-- model/3mf tests: the lib3mf test suite and SDK files, assimp's box.3mf and files from assimp's / trimesh's 3MF
|
||||
-- exporters against lib3mf (world triangles, area, bounds through build items and components; unit), assimp and
|
||||
-- trimesh; our writer's output read back by lib3mf / assimp / trimesh (3mf_xcheck); round trips through our own reader
|
||||
-- (materials, vertex colours, textures, hierarchy, units); hand-written packages for per-corner colour / texture
|
||||
-- groups, composite and multiproperties, components across model parts (p:path), units; error codes; the fuzz
|
||||
-- no-throw pass. Fixtures: tools/fixtures/3mf.py.
|
||||
local T = require("@tests/T")
|
||||
local ThreeMf = require("@formats/model/3mf")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Zip = require("@formats/containers/Zip")
|
||||
local Cases = require("@tests/gen/3mf_cases")
|
||||
local Xcheck = require("@tests/gen/3mf_xcheck")
|
||||
|
||||
local t = T.suite("3mf")
|
||||
|
||||
local function decode(data: any, opts: any?): (any, any)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
return ThreeMf.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
t:eq(ThreeMf.name, "3mf", "name")
|
||||
t:eq(ThreeMf.category, "model", "category")
|
||||
t:check(ThreeMf.caps.decode and ThreeMf.caps.encode and ThreeMf.extensions[1] == "3mf", "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
|
||||
|
||||
-- world-space triangles, area and bounds of every placed primitive
|
||||
local function metrics(scene: any): (number, number, { number }, { number })
|
||||
local tris, area = 0, 0
|
||||
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
|
||||
for _, pl in Types.Scene.flatten(scene) do
|
||||
local p = pl.primitive
|
||||
local m = pl.matrix
|
||||
local pos = p.attributes.POSITION
|
||||
local W = {}
|
||||
for i = 0, pos.count - 1 do
|
||||
local x, y, z = buffer.readf32(pos.data, i * 12), buffer.readf32(pos.data, i * 12 + 4), buffer.readf32(pos.data, i * 12 + 8)
|
||||
local w = { 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[i] = w
|
||||
end
|
||||
local ind = p.indices
|
||||
for k = 0, ind.count // 3 - 1 do
|
||||
local a, b, c = W[buffer.readu32(ind.data, k * 12)], W[buffer.readu32(ind.data, k * 12 + 4)], W[buffer.readu32(ind.data, k * 12 + 8)]
|
||||
for _, v in { a, b, c } do
|
||||
for q = 1, 3 do
|
||||
lo[q] = math.min(lo[q], v[q])
|
||||
hi[q] = math.max(hi[q], v[q])
|
||||
end
|
||||
end
|
||||
local e1 = { b[1] - a[1], b[2] - a[2], b[3] - a[3] }
|
||||
local e2 = { c[1] - a[1], c[2] - a[2], c[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]
|
||||
area += math.sqrt(x * x + y * y + z * z) / 2
|
||||
tris += 1
|
||||
end
|
||||
end
|
||||
return tris, area, lo, hi
|
||||
end
|
||||
|
||||
local function boundsNear(lo: { number }, hi: { number }, rmin: { number }, rmax: { number }): boolean
|
||||
local ext = 0
|
||||
for q = 1, 3 do
|
||||
ext = math.max(ext, rmax[q] - rmin[q])
|
||||
end
|
||||
local eps = 1e-5 * math.max(ext, 1e-6)
|
||||
for q = 1, 3 do
|
||||
if math.abs(lo[q] - rmin[q]) > eps or math.abs(hi[q] - rmax[q]) > eps then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ reference files
|
||||
local UNIT_NAMES = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 }
|
||||
local refCount, rejectedOk, unsupported = 0, 0, 0
|
||||
local byIndex = {}
|
||||
for i, c in Cases do
|
||||
local scene, err = decode(c.data)
|
||||
byIndex[i] = scene
|
||||
local ref = c.lib3mf
|
||||
if ref.failed then
|
||||
-- lib3mf rejects these (strict checks we do not make); it is enough not to throw
|
||||
rejectedOk += 1
|
||||
continue
|
||||
end
|
||||
if not scene and err and err.code == Err.UNSUPPORTED and string.find(c.name, "SecureContent", 1, true) then
|
||||
unsupported += 1 -- encrypted / wrapped model parts (the secure content extension)
|
||||
continue
|
||||
end
|
||||
t:check(scene, c.name .. ": decode: " .. tostring(err))
|
||||
if not scene then
|
||||
continue
|
||||
end
|
||||
t:eq(scene.meta.source.unit, ref.unit, c.name .. ": unit")
|
||||
t:eq(scene.meta.unit, UNIT_NAMES[ref.unit], c.name .. ": meta.unit")
|
||||
t:eq(scene.meta.up, "z", c.name .. ": up")
|
||||
local tris, area, lo, hi = metrics(scene)
|
||||
t:eq(tris, ref.triangles, c.name .. ": world triangles (lib3mf)")
|
||||
t:check(near(area, ref.area, 1e-5), string.format("%s: area %.7g, lib3mf %.7g", c.name, area, ref.area))
|
||||
if ref.min then
|
||||
t:check(boundsNear(lo, hi, ref.min, ref.max), c.name .. ": bounds (lib3mf)")
|
||||
end
|
||||
t:check(#scene.textures <= ref.textures, c.name .. ": textures <= lib3mf's texture2d count")
|
||||
refCount += 1
|
||||
-- trimesh reads build items and components the same way (it skips degenerate input)
|
||||
local tm = c.trimesh
|
||||
if tm and not tm.failed and tm.faces == tris and tm.faces > 0 then
|
||||
t:check(near(area, tm.area, 1e-5), c.name .. ": area (trimesh)")
|
||||
end
|
||||
end
|
||||
t:note("%d files: %d against lib3mf, %d rejected by lib3mf (decoded without throwing), %d secure content (UNSUPPORTED)", #Cases, refCount, rejectedOk, unsupported)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ our output read back
|
||||
local xchecked, withTextures = 0, 0
|
||||
for _, x in Xcheck do
|
||||
local c = Cases[x.case]
|
||||
local ref = c.lib3mf
|
||||
if not byIndex[x.case] then
|
||||
continue
|
||||
end
|
||||
t:check(not x.lib3mf.failed, x.name .. " (" .. c.name .. "): lib3mf reads our file: " .. tostring(x.lib3mf.failed))
|
||||
if not x.lib3mf.failed then
|
||||
t:eq(x.lib3mf.triangles, ref.triangles, c.name .. ": our file's triangles (lib3mf)")
|
||||
t:check(near(x.lib3mf.area, ref.area, 1e-5), string.format("%s: our file's area %.7g vs %.7g (lib3mf)", c.name, x.lib3mf.area, ref.area))
|
||||
if ref.min then
|
||||
t:check(boundsNear(x.lib3mf.min, x.lib3mf.max, ref.min, ref.max), c.name .. ": our file's bounds (lib3mf)")
|
||||
end
|
||||
t:eq(x.lib3mf.unit, ref.unit, c.name .. ": our file's unit (lib3mf)")
|
||||
-- the material groups made it: textures, colour groups, base materials
|
||||
local scene = byIndex[x.case]
|
||||
local tex, col = 0, 0
|
||||
for _, m in scene.meshes do
|
||||
for _, p in m.primitives do
|
||||
if p.attributes.TEXCOORD_0 and p.material and scene.materials[p.material].baseColorTexture then
|
||||
tex += 1
|
||||
elseif p.attributes.COLOR_0 then
|
||||
col += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check((tex == 0) == (x.lib3mf.texGroups == 0), c.name .. ": our texture groups (lib3mf)")
|
||||
t:check(tex == 0 or x.lib3mf.textures > 0, c.name .. ": our textures (lib3mf)")
|
||||
t:eq(x.lib3mf.colorGroups, col, c.name .. ": our colour groups (lib3mf)")
|
||||
t:eq(x.lib3mf.baseGroups, if #scene.materials > 0 then 1 else 0, c.name .. ": our base material group (lib3mf)")
|
||||
if tex > 0 then
|
||||
withTextures += 1
|
||||
end
|
||||
end
|
||||
t:check(not x.assimp.failed or c.assimp.failed, c.name .. ": assimp reads our file")
|
||||
if not x.trimesh.failed and x.trimesh.faces > 0 and not c.trimesh.failed and c.trimesh.faces == x.trimesh.faces then
|
||||
t:check(near(x.trimesh.area, c.trimesh.area, 1e-5), c.name .. ": our file's area (trimesh)")
|
||||
end
|
||||
xchecked += 1
|
||||
end
|
||||
t:note("%d of our files read back by lib3mf / assimp / trimesh like the originals (%d with textures)", xchecked, withTextures)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ round trips (ours)
|
||||
local rts = 0
|
||||
for i, c in Cases do
|
||||
local scene = byIndex[i]
|
||||
if scene and not c.lib3mf.failed then
|
||||
local out, err = ThreeMf.encode(scene)
|
||||
t:check(out, c.name .. ": encode: " .. tostring(err))
|
||||
local back, berr = decode(out)
|
||||
t:check(back, c.name .. ": decode ours: " .. tostring(berr))
|
||||
local a1, b1 = metrics(scene)
|
||||
local a2, b2 = metrics(back)
|
||||
t:eq(a2, a1, c.name .. ": round trip triangles")
|
||||
t:check(near(b2, b1, 1e-6), c.name .. ": round trip area")
|
||||
t:eq(back.meta.unit, scene.meta.unit, c.name .. ": round trip unit")
|
||||
-- textures: the same bytes
|
||||
local used = 0
|
||||
for _, m in back.materials do
|
||||
if m.baseColorTexture then
|
||||
used += 1
|
||||
t:check(back.textures[m.baseColorTexture.texture].data ~= nil, c.name .. ": texture bytes")
|
||||
end
|
||||
end
|
||||
rts += 1
|
||||
end
|
||||
end
|
||||
t:note("%d round trips through our writer", rts)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ hand-written packages
|
||||
local function package(model: string, extra: { [string]: string }?): buffer
|
||||
local w = Zip.writer()
|
||||
w:add("[Content_Types].xml", '<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml"/></Types>', { method = "store" })
|
||||
w:add("_rels/.rels", '<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Target="/3D/3dmodel.model" Id="r0" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/></Relationships>', { method = "store" })
|
||||
w:add("3D/3dmodel.model", model, { method = "store" })
|
||||
for k, v in extra or {} do
|
||||
w:add(k, v, { method = "store" })
|
||||
end
|
||||
return (w:finish())
|
||||
end
|
||||
local HEAD = '<?xml version="1.0" encoding="UTF-8"?><model unit="%s" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02" xmlns:m="http://schemas.microsoft.com/3dmanufacturing/material/2015/02" xmlns:p="http://schemas.microsoft.com/3dmanufacturing/production/2015/06">'
|
||||
local QUAD = '<mesh><vertices><vertex x="0" y="0" z="0"/><vertex x="1" y="0" z="0"/><vertex x="1" y="1" z="0"/><vertex x="0" y="1" z="0"/></vertices><triangles>%s</triangles></mesh>'
|
||||
local samples = {}
|
||||
|
||||
local function f32s(acc: any): { number }
|
||||
local out = {}
|
||||
for i = 0, acc.count * acc.components - 1 do
|
||||
out[i + 1] = buffer.readf32(acc.data, i * 4)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
do -- per-corner colours: vertex 0 has two different colours -> split
|
||||
local xml = string.format(HEAD, "inch")
|
||||
.. '<metadata name="Title">quad & co</metadata><resources>'
|
||||
.. '<m:colorgroup id="1"><m:color color="#FF0000"/><m:color color="#00FF0080"/><m:color color="#0000FF"/></m:colorgroup>'
|
||||
.. '<object id="2" type="model" name="q">' .. string.format(QUAD, '<triangle v1="0" v2="1" v3="2" pid="1" p1="0" p2="1" p3="2"/><triangle v1="0" v2="2" v3="3" pid="1" p1="2"/>') .. '</object>'
|
||||
.. '</resources><build><item objectid="2" transform="1 0 0 0 1 0 0 0 1 10 20 30"/></build></model>'
|
||||
local pkg = package(xml)
|
||||
table.insert(samples, pkg)
|
||||
local s, err = decode(pkg)
|
||||
t:check(s, "colours: " .. tostring(err))
|
||||
t:eq(s.meta.unit, 0.0254, "colours: inch")
|
||||
t:eq(s.meta.metadata.Title, "quad & co", "colours: metadata")
|
||||
t:eq(#s.meshes, 1, "colours: one mesh")
|
||||
local prim = s.meshes[1].primitives[1]
|
||||
t:eq(#s.meshes[1].primitives, 1, "colours: one primitive")
|
||||
-- corners: (0,red) (1,green) (2,blue) | (0,blue) (2,blue) (3,blue) -> 5 vertices
|
||||
t:eq(prim.attributes.POSITION.count, 5, "colours: vertex 0 split by colour")
|
||||
local col = f32s(prim.attributes.COLOR_0)
|
||||
t:eq(col[1], 1, "colours: red r (linear)")
|
||||
t:eq(col[2], 0, "colours: red g")
|
||||
t:check(math.abs(col[8] - 128 / 255) < 1e-6, "colours: alpha kept linear")
|
||||
t:eq(s.nodes[1].matrix[13], 10, "colours: transform tx")
|
||||
t:eq(s.nodes[1].matrix[15], 30, "colours: transform tz")
|
||||
-- through our writer and back: the same colours
|
||||
local back = decode((ThreeMf.encode(s)))
|
||||
local col2 = f32s(back.meshes[1].primitives[1].attributes.COLOR_0)
|
||||
local same = #col2 == #col
|
||||
for i = 1, #col do
|
||||
same = same and math.abs(col[i] - col2[i]) < 1e-6
|
||||
end
|
||||
t:check(same, "colours: round trip exact (8-bit sRGB)")
|
||||
t:eq(back.meta.metadata.Title, "quad & co", "colours: metadata round trip")
|
||||
t:eq(back.meta.source.unit, "inch", "colours: unit round trip")
|
||||
end
|
||||
|
||||
do -- base materials, object defaults, composite, multiproperties, textures
|
||||
local png = "\137PNG\r\n\26\nfake"
|
||||
local xml = string.format(HEAD, "millimeter") .. "<resources>"
|
||||
.. '<basematerials id="1"><base name="red" displaycolor="#FF0000"/><base name="half" displaycolor="#808080FF"/></basematerials>'
|
||||
.. '<m:texture2d id="3" path="/3D/Texture/a.png" contenttype="image/png" tilestyleu="clamp" tilestylev="mirror" filter="nearest"/>'
|
||||
.. '<m:texture2dgroup id="4" texid="3"><m:tex2coord u="0" v="0"/><m:tex2coord u="1" v="0.25"/><m:tex2coord u="1" v="1"/></m:texture2dgroup>'
|
||||
.. '<m:compositematerials id="5" matid="1" matindices="0 1"><m:composite values="0.5 0.5"/></m:compositematerials>'
|
||||
.. '<m:multiproperties id="6" pids="1 4"><m:multi pindices="1 0"/></m:multiproperties>'
|
||||
.. '<object id="7" type="model" pid="1" pindex="0">' .. string.format(QUAD,
|
||||
'<triangle v1="0" v2="1" v3="2"/>' -- object default: red
|
||||
.. '<triangle v1="0" v2="2" v3="3" pid="4" p1="0" p2="1" p3="2"/>' -- texture
|
||||
.. '<triangle v1="1" v2="2" v3="3" pid="5" p1="0"/>' -- composite
|
||||
.. '<triangle v1="0" v2="1" v3="3" pid="6" p1="0"/>' -- multi -> its first layer (base 1 = "half")
|
||||
.. '<triangle v1="0" v2="3" v3="2" pid="1" p1="1"/>') -- half
|
||||
.. "</object></resources><build><item objectid=\"7\"/></build></model>"
|
||||
local pkg = package(xml, { ["3D/Texture/a.png"] = png })
|
||||
table.insert(samples, pkg)
|
||||
local s, err = decode(pkg)
|
||||
t:check(s, "materials: " .. tostring(err))
|
||||
local prims = s.meshes[1].primitives
|
||||
t:eq(#prims, 4, "materials: red, texture, composite, half (multi shares half)")
|
||||
local red = s.materials[prims[1].material]
|
||||
t:eq(red.name, "red", "materials: object default pid / pindex")
|
||||
t:eq(red.baseColor[1], 1, "materials: red")
|
||||
t:eq(red.extras["3mf"].displaycolor, "#FF0000", "materials: display colour kept")
|
||||
local tex = s.materials[prims[2].material]
|
||||
t:check(tex.baseColorTexture and s.textures[tex.baseColorTexture.texture], "materials: texture material")
|
||||
local tx = s.textures[tex.baseColorTexture.texture]
|
||||
t:eq(buffer.tostring(tx.data), png, "materials: texture bytes from the package")
|
||||
t:eq(tx.mime, "image/png", "materials: texture mime")
|
||||
t:eq(tx.sampler.wrapS, "clamp", "materials: tilestyleu")
|
||||
t:eq(tx.sampler.wrapT, "mirror", "materials: tilestylev")
|
||||
t:eq(tx.sampler.filter, "nearest", "materials: filter")
|
||||
local uv = f32s(prims[2].attributes.TEXCOORD_0)
|
||||
t:eq(uv[4], 0.75, "materials: v flipped to the top-left origin")
|
||||
local comp = s.materials[prims[3].material]
|
||||
local half = (128 / 255 + 0.055) / 1.055
|
||||
t:check(math.abs(comp.baseColor[1] - (((1 + 128 / 255) / 2 + 0.055) / 1.055) ^ 2.4) < 1e-6, "materials: composite blends in sRGB")
|
||||
t:eq(s.materials[prims[4].material].name, "half", "materials: multiproperties -> first layer")
|
||||
t:eq(prims[4].indices.count, 6, "materials: multi and base 'half' share a primitive")
|
||||
t:check(math.abs(s.materials[prims[4].material].baseColor[1] - half ^ 2.4) < 1e-6, "materials: sRGB -> linear")
|
||||
-- round trip: texture + materials survive
|
||||
local out = assert(ThreeMf.encode(s))
|
||||
local back = assert(decode(out))
|
||||
local tm = nil
|
||||
for _, m in back.materials do
|
||||
if m.baseColorTexture then
|
||||
tm = m
|
||||
end
|
||||
end
|
||||
t:check(tm and buffer.tostring(back.textures[tm.baseColorTexture.texture].data) == png, "materials: texture round trip")
|
||||
t:eq(back.textures[1].sampler.wrapS, "clamp", "materials: sampler round trip")
|
||||
local _, a1 = metrics(s)
|
||||
local _, a2 = metrics(back)
|
||||
t:check(near(a1, a2, 1e-6), "materials: area round trip")
|
||||
local names = {}
|
||||
for _, m in back.materials do
|
||||
if m.name then
|
||||
names[m.name] = true
|
||||
end
|
||||
end
|
||||
t:check(names.red and names.half, "materials: base names round trip")
|
||||
end
|
||||
|
||||
do -- components, another model part through p:path, nested transforms
|
||||
local part = string.format(HEAD, "millimeter") .. "<resources><object id=\"1\" type=\"model\" name=\"leaf\">"
|
||||
.. string.format(QUAD, '<triangle v1="0" v2="1" v3="2"/><triangle v1="0" v2="2" v3="3"/>') .. "</object></resources><build/></model>"
|
||||
local xml = string.format(HEAD, "centimeter") .. "<resources>"
|
||||
.. '<object id="1" type="model" name="local">' .. string.format(QUAD, '<triangle v1="0" v2="1" v3="2"/>') .. "</object>"
|
||||
.. '<object id="2" type="model" name="group"><components><component objectid="1" transform="2 0 0 0 2 0 0 0 2 0 0 0"/>'
|
||||
.. '<component objectid="1" p:path="/3D/other.model" transform="1 0 0 0 1 0 0 0 1 5 0 0"/></components></object>'
|
||||
.. '</resources><build><item objectid="2" transform="1 0 0 0 1 0 0 0 1 0 0 1"/><item objectid="2"/></build></model>'
|
||||
local pkg = package(xml, { ["3D/other.model"] = part })
|
||||
table.insert(samples, pkg)
|
||||
local s, err = decode(pkg)
|
||||
t:check(s, "components: " .. tostring(err))
|
||||
t:eq(#s.roots, 2, "components: two build items")
|
||||
t:eq(#s.meshes, 2, "components: meshes shared between instances")
|
||||
t:eq(s.nodes[s.roots[1]].name, "group", "components: node names")
|
||||
t:eq(#s.nodes[s.roots[1]].children, 2, "components: children")
|
||||
local tris, area, lo, hi = metrics(s)
|
||||
t:eq(tris, 6, "components: world triangles")
|
||||
t:check(near(area, 2 * (2 + 1), 1e-9), "components: world area")
|
||||
t:check(lo[1] == 0 and hi[1] == 6 and hi[3] == 1, "components: nested transforms")
|
||||
t:eq(s.meta.unit, 0.01, "components: centimetre")
|
||||
-- the writer flattens the hierarchy into build items
|
||||
local back = assert(decode((ThreeMf.encode(s))))
|
||||
local tris2, area2, lo2, hi2 = metrics(back)
|
||||
t:eq(tris2, 6, "components: flattened round trip triangles")
|
||||
t:check(near(area2, area, 1e-9) and lo2[1] == 0 and hi2[1] == 6 and hi2[3] == 1, "components: flattened round trip bounds")
|
||||
t:eq(back.meta.source.unit, "centimeter", "components: unit round trip")
|
||||
-- a unit 3MF lacks: scaled into millimetres
|
||||
s.meta.unit = 0.5
|
||||
local scaled = assert(decode((ThreeMf.encode(s))))
|
||||
local _, _, _, hi3 = metrics(scaled)
|
||||
t:eq(scaled.meta.source.unit, "millimeter", "units: millimetres when the scene's unit is not a 3MF unit")
|
||||
t:check(math.abs(hi3[1] - 3000) < 1e-3, "units: positions scaled through the build transforms")
|
||||
t:check(select(2, ThreeMf.encode(s, { unit = "parsec" :: any })).code == Err.ARG, "units: bad opts.unit")
|
||||
end
|
||||
|
||||
do -- a Scene built by hand: strips, fans, polygons, vertex colours + texture coordinates, an unplaced mesh
|
||||
local s = Types.Scene.new()
|
||||
local pos = Types.Scene.accessor(nil, "f32", 3, 4)
|
||||
for i, v in { 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0 } do
|
||||
buffer.writef32(pos.data, (i - 1) * 4, v)
|
||||
end
|
||||
local faces = Types.Scene.accessor(nil, "u32", 1, 1)
|
||||
buffer.writeu32(faces.data, 0, 4)
|
||||
local col = Types.Scene.accessor(nil, "unorm8", 3, 4)
|
||||
buffer.fill(col.data, 0, 255)
|
||||
s.meshes = {
|
||||
{ primitives = { { attributes = { POSITION = pos }, mode = "triangle_strip" }, { attributes = { POSITION = pos }, mode = "triangle_fan", material = 1 } } },
|
||||
{ primitives = { { attributes = { POSITION = pos, COLOR_0 = col }, mode = "polygons", faces = faces }, { attributes = { POSITION = pos }, mode = "points" } } },
|
||||
}
|
||||
s.materials = { Types.Scene.material("m") }
|
||||
s.nodes = { { children = { 2 }, mesh = 1, translation = { 0, 0, 5 } }, { children = {}, mesh = 2, scale = { 2, 2, 2 } } }
|
||||
s.roots = { 1 }
|
||||
local out, err = ThreeMf.encode(s, { level = 0 })
|
||||
t:check(out, "scene: encode " .. tostring(err))
|
||||
table.insert(samples, out)
|
||||
local back = assert(decode(out))
|
||||
local tris, area, _, hi = metrics(back)
|
||||
t:eq(tris, 6, "scene: strip + fan + polygon triangles (points skipped)")
|
||||
t:check(near(area, 2 + 4, 1e-9), "scene: area with node transforms")
|
||||
t:eq(hi[3], 5, "scene: parent translation applied to the child")
|
||||
t:eq(#back.roots, 2, "scene: one build item per placed mesh")
|
||||
local m2 = back.meshes[back.nodes[back.roots[2]].mesh]
|
||||
t:check(m2.primitives[1].attributes.COLOR_0 ~= nil, "scene: vertex colours as a colour group")
|
||||
t:check(select(2, ThreeMf.encode({} :: any)).code == Err.ARG, "encode: not a scene")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ errors
|
||||
do
|
||||
local _, e1 = decode("not a zip at all")
|
||||
t:check(e1 and e1.code ~= nil, "errors: not a zip")
|
||||
local w = Zip.writer()
|
||||
w:add("hello.txt", "hi")
|
||||
local _, e2 = decode((w:finish()))
|
||||
t:eq(e2 and e2.code, Err.CORRUPT, "errors: no model part")
|
||||
local bad = string.format(HEAD, "millimeter") .. '<resources><object id="1">' .. string.format(QUAD, '<triangle v1="0" v2="1" v3="9"/>') .. "</object></resources><build><item objectid=\"1\"/></build></model>"
|
||||
local _, e3 = decode(package(bad))
|
||||
t:eq(e3 and e3.code, Err.CORRUPT, "errors: vertex index out of range")
|
||||
local cyc = string.format(HEAD, "millimeter") .. '<resources><object id="1"><components><component objectid="2"/></components></object><object id="2"><components><component objectid="1"/></components></object></resources><build><item objectid="1"/></build></model>'
|
||||
local _, e4 = decode(package(cyc))
|
||||
t:eq(e4 and e4.code, Err.CORRUPT, "errors: component cycle")
|
||||
local _, e5 = decode(package(string.format(HEAD, "millimeter") .. "<resources/><build><item objectid=\"3\"/></build></model>"))
|
||||
t:eq(e5 and e5.code, Err.CORRUPT, "errors: build item without an object")
|
||||
local _, e6 = decode(package(string.format(HEAD, "millimeter") .. '<resources><object id="1">' .. string.format(QUAD, "") .. "</object></resources><build/></model>"), { maxVertices = 2 })
|
||||
t:eq(e6 and e6.code, Err.LIMIT, "errors: maxVertices")
|
||||
table.insert(samples, package(bad))
|
||||
table.insert(samples, package(cyc))
|
||||
-- sniff
|
||||
t:eq(ThreeMf.sniff(Bytes.reader(package(bad))), 0.95, "sniff: a 3MF package")
|
||||
t:eq(ThreeMf.sniff(Bytes.reader((w:finish()))), 0, "sniff: another zip")
|
||||
t:eq(ThreeMf.sniff(Bytes.reader(buffer.fromstring("solid x"))), 0, "sniff: not a zip")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fuzz
|
||||
do
|
||||
for _, c in Cases do
|
||||
if #c.data < 20000 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local s = ThreeMf.decode(Bytes.reader(b))
|
||||
if s then
|
||||
ThreeMf.encode(s)
|
||||
end
|
||||
return s
|
||||
end, samples, { mutations = 12 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,581 @@
|
||||
-- model/dae tests: assimp's Collada test models (triangles / polylist / polygons / tristrips, UTF-16 and BOM files,
|
||||
-- decimal commas, 2 UV sets, vertex colours, instance_node, cameras, lights, nested / clipped / full-rotation
|
||||
-- animations, skins, .zae) and glTF samples exported by assimp's Collada exporter, against `assimp info -r` (meshes,
|
||||
-- faces, bounds in assimp's space, materials, animations, cameras, lights), and against the glTF originals read by
|
||||
-- model/gltf (skinned rest-pose bounds, joints, every LINEAR animation key); our writer's output read back by assimp
|
||||
-- (dae_xcheck) and by us (round trips, .dae and .zae); polygons kept with triangulate = false; textures decoded lazily
|
||||
-- at the api layer; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/dae.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Dae = require("@formats/model/dae")
|
||||
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/dae_cases")
|
||||
local Xcheck = require("@tests/gen/dae_xcheck")
|
||||
|
||||
local Scene = Types.Scene
|
||||
local t = T.suite("dae")
|
||||
|
||||
local function decode(data: any, opts: any?): (any, any)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
return Dae.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
t:eq(Dae.name, "dae", "name")
|
||||
t:eq(Dae.category, "model", "category")
|
||||
t:check(Dae.caps.decode and Dae.caps.encode and table.find(Dae.extensions, "zae"), "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 nearV(a: { number }, b: { number }, eps: number): boolean
|
||||
for i = 1, #b do
|
||||
if not near(a[i], b[i], eps) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return #a == #b
|
||||
end
|
||||
local function fmt(v: { number }?): string
|
||||
if not v then
|
||||
return "-"
|
||||
end
|
||||
return string.format("(%.4g %.4g %.4g)", v[1], v[2], v[3])
|
||||
end
|
||||
|
||||
-- assimp's counts: one mesh per primitive reached (instances of one primitive once), faces as stored
|
||||
local function counts(scene: any): (number, number)
|
||||
local prims, faces = 0, 0
|
||||
local seen = {}
|
||||
for _, pl in Scene.flatten(scene) do
|
||||
if not seen[pl.primitive] then
|
||||
seen[pl.primitive] = true
|
||||
local p = pl.primitive
|
||||
prims += 1
|
||||
if p.mode == "polygons" then
|
||||
faces += p.faces.count
|
||||
elseif p.mode == "triangles" then
|
||||
faces += p.indices.count // 3
|
||||
elseif p.mode == "lines" then
|
||||
faces += p.indices.count // 2
|
||||
end
|
||||
end
|
||||
end
|
||||
return prims, faces
|
||||
end
|
||||
|
||||
local function inverse(m: { number }): { number }
|
||||
-- general 4x4 inverse (column-major; cofactors)
|
||||
local inv = table.create(16, 0)
|
||||
local a = m
|
||||
inv[1] = a[6] * a[11] * a[16] - a[6] * a[12] * a[15] - a[10] * a[7] * a[16] + a[10] * a[8] * a[15] + a[14] * a[7] * a[12] - a[14] * a[8] * a[11]
|
||||
inv[5] = -a[5] * a[11] * a[16] + a[5] * a[12] * a[15] + a[9] * a[7] * a[16] - a[9] * a[8] * a[15] - a[13] * a[7] * a[12] + a[13] * a[8] * a[11]
|
||||
inv[9] = a[5] * a[10] * a[16] - a[5] * a[12] * a[14] - a[9] * a[6] * a[16] + a[9] * a[8] * a[14] + a[13] * a[6] * a[12] - a[13] * a[8] * a[10]
|
||||
inv[13] = -a[5] * a[10] * a[15] + a[5] * a[11] * a[14] + a[9] * a[6] * a[15] - a[9] * a[7] * a[14] - a[13] * a[6] * a[11] + a[13] * a[7] * a[10]
|
||||
inv[2] = -a[2] * a[11] * a[16] + a[2] * a[12] * a[15] + a[10] * a[3] * a[16] - a[10] * a[4] * a[15] - a[14] * a[3] * a[12] + a[14] * a[4] * a[11]
|
||||
inv[6] = a[1] * a[11] * a[16] - a[1] * a[12] * a[15] - a[9] * a[3] * a[16] + a[9] * a[4] * a[15] + a[13] * a[3] * a[12] - a[13] * a[4] * a[11]
|
||||
inv[10] = -a[1] * a[10] * a[16] + a[1] * a[12] * a[14] + a[9] * a[2] * a[16] - a[9] * a[4] * a[14] - a[13] * a[2] * a[12] + a[13] * a[4] * a[10]
|
||||
inv[14] = a[1] * a[10] * a[15] - a[1] * a[11] * a[14] - a[9] * a[2] * a[15] + a[9] * a[3] * a[14] + a[13] * a[2] * a[11] - a[13] * a[3] * a[10]
|
||||
inv[3] = a[2] * a[7] * a[16] - a[2] * a[8] * a[15] - a[6] * a[3] * a[16] + a[6] * a[4] * a[15] + a[14] * a[3] * a[8] - a[14] * a[4] * a[7]
|
||||
inv[7] = -a[1] * a[7] * a[16] + a[1] * a[8] * a[15] + a[5] * a[3] * a[16] - a[5] * a[4] * a[15] - a[13] * a[3] * a[8] + a[13] * a[4] * a[7]
|
||||
inv[11] = a[1] * a[6] * a[16] - a[1] * a[8] * a[14] - a[5] * a[2] * a[16] + a[5] * a[4] * a[14] + a[13] * a[2] * a[8] - a[13] * a[4] * a[6]
|
||||
inv[15] = -a[1] * a[6] * a[15] + a[1] * a[7] * a[14] + a[5] * a[2] * a[15] - a[5] * a[3] * a[14] - a[13] * a[2] * a[7] + a[13] * a[3] * a[6]
|
||||
inv[4] = -a[2] * a[7] * a[12] + a[2] * a[8] * a[11] + a[6] * a[3] * a[12] - a[6] * a[4] * a[11] - a[10] * a[3] * a[8] + a[10] * a[4] * a[7]
|
||||
inv[8] = a[1] * a[7] * a[12] - a[1] * a[8] * a[11] - a[5] * a[3] * a[12] + a[5] * a[4] * a[11] + a[9] * a[3] * a[8] - a[9] * a[4] * a[7]
|
||||
inv[12] = -a[1] * a[6] * a[12] + a[1] * a[8] * a[10] + a[5] * a[2] * a[12] - a[5] * a[4] * a[10] - a[9] * a[2] * a[8] + a[9] * a[4] * a[6]
|
||||
inv[16] = a[1] * a[6] * a[11] - a[1] * a[7] * a[10] - a[5] * a[2] * a[11] + a[5] * a[3] * a[10] + a[9] * a[2] * a[7] - a[9] * a[3] * a[6]
|
||||
local det = a[1] * inv[1] + a[2] * inv[5] + a[3] * inv[9] + a[4] * inv[13]
|
||||
for i = 1, 16 do
|
||||
inv[i] /= det
|
||||
end
|
||||
return inv
|
||||
end
|
||||
|
||||
local function grow(lo: { number }, hi: { number }, x: number, y: number, z: number)
|
||||
lo[1], lo[2], lo[3] = math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z)
|
||||
hi[1], hi[2], hi[3] = math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z)
|
||||
end
|
||||
local function apply(m: { number }, x: number, y: number, z: number): (number, number, number)
|
||||
return 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
|
||||
|
||||
-- the bounds `assimp info` prints: its Collada importer puts the up-axis rotation and unit scale on the root node,
|
||||
-- and Info.cpp accumulates node transforms as local * parent (sic); skinned meshes without their bind shape matrix
|
||||
local function assimpBounds(scene: any, written: boolean?): ({ number }?, { number }?)
|
||||
local u = scene.meta.unit or 1
|
||||
local root = if scene.meta.up == "z" then { u, 0, 0, 0, 0, 0, -u, 0, 0, u, 0, 0, 0, 0, 0, 1 }
|
||||
elseif scene.meta.up == "x" then { 0, u, 0, 0, -u, 0, 0, 0, 0, 0, u, 0, 0, 0, 0, 1 }
|
||||
else { u, 0, 0, 0, 0, u, 0, 0, 0, 0, u, 0, 0, 0, 0, 1 }
|
||||
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
|
||||
local seen = {}
|
||||
local function visit(i: number, parent: { number })
|
||||
local n = scene.nodes[i]
|
||||
if seen[i] then
|
||||
return
|
||||
end
|
||||
seen[i] = true
|
||||
local m = Scene.mul(Scene.nodeMatrix(n), parent)
|
||||
local mesh = n.mesh and scene.meshes[n.mesh]
|
||||
if mesh then
|
||||
local mm = m
|
||||
local skin = n.skin and scene.skins[n.skin]
|
||||
if skin and not written and skin.extras and skin.extras.dae and skin.extras.dae.bindShapeMatrix then
|
||||
mm = Scene.mul(m, inverse(skin.extras.dae.bindShapeMatrix))
|
||||
end
|
||||
for _, p in mesh.primitives do
|
||||
local pos = p.attributes.POSITION
|
||||
for v = 0, pos.count - 1 do
|
||||
grow(lo, hi, apply(mm, buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8)))
|
||||
end
|
||||
end
|
||||
end
|
||||
for _, c in n.children do
|
||||
visit(c, m)
|
||||
end
|
||||
end
|
||||
for _, r in scene.roots do
|
||||
visit(r, root)
|
||||
end
|
||||
if lo[1] > hi[1] then
|
||||
return nil, nil
|
||||
end
|
||||
return lo, hi
|
||||
end
|
||||
|
||||
-- world matrices (correct order) of every node
|
||||
local function worlds(scene: any): { [number]: { number } }
|
||||
local w = {}
|
||||
local function visit(i: number, parent: { number })
|
||||
if w[i] then
|
||||
return
|
||||
end
|
||||
w[i] = Scene.mul(parent, Scene.nodeMatrix(scene.nodes[i]))
|
||||
for _, c in scene.nodes[i].children do
|
||||
visit(c, w[i])
|
||||
end
|
||||
end
|
||||
for _, r in scene.roots do
|
||||
visit(r, Scene.IDENTITY)
|
||||
end
|
||||
return w
|
||||
end
|
||||
|
||||
-- bounds of the rest pose with skins applied (glTF semantics: skinned vertices = sum w * world(joint) * ibm * v)
|
||||
local function posedBounds(scene: any): ({ number }?, { number }?)
|
||||
local w = worlds(scene)
|
||||
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
|
||||
for ni, m in w do
|
||||
local n = scene.nodes[ni]
|
||||
local mesh = n.mesh and scene.meshes[n.mesh]
|
||||
if mesh then
|
||||
local skin = n.skin and scene.skins[n.skin]
|
||||
local jm = {}
|
||||
if skin then
|
||||
local ibm = skin.inverseBindMatrices and Scene.reader(skin.inverseBindMatrices)
|
||||
for j, jn in skin.joints do
|
||||
local inv = table.create(16, 0)
|
||||
for k = 1, 16 do
|
||||
inv[k] = if ibm then ibm(j - 1, k - 1) else (if k % 5 == 1 then 1 else 0)
|
||||
end
|
||||
jm[j - 1] = Scene.mul(w[jn] or Scene.IDENTITY, inv)
|
||||
end
|
||||
end
|
||||
for _, p in mesh.primitives do
|
||||
local pos = p.attributes.POSITION
|
||||
local J = skin and p.attributes.JOINTS_0 and Scene.reader(p.attributes.JOINTS_0)
|
||||
local W = skin and p.attributes.WEIGHTS_0 and Scene.reader(p.attributes.WEIGHTS_0)
|
||||
for v = 0, pos.count - 1 do
|
||||
local x, y, z = buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8)
|
||||
if J and W then
|
||||
local sx, sy, sz = 0, 0, 0
|
||||
for k = 0, 3 do
|
||||
local wt = W(v, k)
|
||||
if wt > 0 then
|
||||
local px, py, pz = apply(jm[J(v, k)] or Scene.IDENTITY, x, y, z)
|
||||
sx, sy, sz = sx + wt * px, sy + wt * py, sz + wt * pz
|
||||
end
|
||||
end
|
||||
grow(lo, hi, sx, sy, sz)
|
||||
else
|
||||
grow(lo, hi, apply(m, x, y, z))
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if lo[1] > hi[1] then
|
||||
return nil, nil
|
||||
end
|
||||
return lo, hi
|
||||
end
|
||||
|
||||
local function lightCount(scene: any): number
|
||||
local n = #scene.lights
|
||||
for _, node in scene.nodes do
|
||||
if node.extras and node.extras.dae and node.extras.dae.ambientLight then
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
return n
|
||||
end
|
||||
|
||||
-- a channel's value at time tm (LINEAR; rotations nlerped)
|
||||
local function channelAt(ch: any, tm: number): { number }
|
||||
local inp, out = Scene.reader(ch.input) :: any, Scene.reader(ch.output) :: any
|
||||
local n, c = ch.input.count, ch.output.components
|
||||
local function at(i: number): { number }
|
||||
local r = {}
|
||||
for k = 0, c - 1 do
|
||||
r[k + 1] = out(i, k)
|
||||
end
|
||||
return r
|
||||
end
|
||||
if tm <= inp(0, 0) then
|
||||
return at(0)
|
||||
end
|
||||
for i = 1, n - 1 do
|
||||
local t1 = inp(i, 0)
|
||||
if tm <= t1 + 1e-6 then
|
||||
local t0 = inp(i - 1, 0)
|
||||
local f = if t1 > t0 then math.clamp((tm - t0) / (t1 - t0), 0, 1) else 1
|
||||
local a, b = at(i - 1), at(i)
|
||||
for k = 1, c do
|
||||
a[k] += (b[k] - a[k]) * f
|
||||
end
|
||||
return a
|
||||
end
|
||||
end
|
||||
return at(n - 1)
|
||||
end
|
||||
|
||||
local checked = { assimp = 0, bounds = 0, gltf = 0, keys = 0, roundTrips = 0, xcheck = 0 }
|
||||
local decoded: { [number]: any } = {}
|
||||
local samples: { string } = {}
|
||||
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
|
||||
t:eq(scene.meta.source.format, "dae", c.name .. ": source")
|
||||
local ref = c.assimp
|
||||
local prims, faces = counts(scene)
|
||||
if ref and not ref.failed then
|
||||
-- assimp builds a placeholder skeleton mesh for scenes without meshes
|
||||
if prims > 0 then
|
||||
t:eq(prims, ref.meshes, c.name .. ": meshes (assimp)")
|
||||
t:eq(faces, ref.faces, c.name .. ": faces (assimp)")
|
||||
local lo, hi = assimpBounds(scene)
|
||||
local ok = lo ~= nil and hi ~= nil and nearV(lo :: any, ref.min, 2e-4) and nearV(hi :: any, ref.max, 2e-4)
|
||||
t:check(ok, string.format("%s: bounds %s %s, assimp %s %s", c.name, fmt(lo), fmt(hi), fmt(ref.min), fmt(ref.max)))
|
||||
checked.bounds += 1
|
||||
-- assimp adds a default material when a mesh has none
|
||||
t:check(ref.materials - #scene.materials == 0 or ref.materials - #scene.materials == 1, c.name .. ": materials (assimp)")
|
||||
end
|
||||
t:eq(#scene.cameras, ref.cameras, c.name .. ": cameras (assimp)")
|
||||
t:eq(lightCount(scene), ref.lights, c.name .. ": lights (assimp)")
|
||||
t:eq(#scene.animations, ref.animations, c.name .. ": animations (assimp)")
|
||||
checked.assimp += 1
|
||||
end
|
||||
-- against the glTF original of an assimp export
|
||||
if c.gltf then
|
||||
local g, gerr = Gltf.decode(Bytes.reader(buffer.fromstring(c.gltf)), { files = c.gltfFiles })
|
||||
t:check(g, c.name .. ": gltf original: " .. tostring(gerr))
|
||||
if g then
|
||||
local glo, ghi = posedBounds(g)
|
||||
local lo, hi = posedBounds(scene)
|
||||
-- assimp's exporter folds a root Z-up rotation node of the source into <up_axis>Z_UP</up_axis>
|
||||
if lo and hi and scene.meta.up == "z" then
|
||||
lo, hi = { lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] }
|
||||
end
|
||||
t:check(lo and glo and nearV(lo, glo, 1e-4) and nearV(hi :: any, ghi :: any, 1e-4), string.format("%s: posed bounds %s %s, glTF %s %s", c.name, fmt(lo), fmt(hi), fmt(glo), fmt(ghi)))
|
||||
t:eq(#scene.skins, #g.skins, c.name .. ": skins")
|
||||
if #g.skins > 0 and #scene.skins > 0 then
|
||||
t:eq(#scene.skins[1].joints, #g.skins[1].joints, c.name .. ": joints")
|
||||
end
|
||||
-- every LINEAR key of the original, evaluated on our resampled channels (nodes matched by name)
|
||||
local byName = {}
|
||||
for ni, n in scene.nodes do
|
||||
if n.name then
|
||||
byName[n.name] = byName[n.name] or ni
|
||||
end
|
||||
end
|
||||
-- assimp's Collada exporter writes key times in milliseconds (its glTF importer's ticks per second)
|
||||
local function maxTime(sc: any): number
|
||||
local m = 0
|
||||
for _, a in sc.animations do
|
||||
for _, ch in a.channels do
|
||||
m = math.max(m, buffer.readf32(ch.input.data, (ch.input.count - 1) * 4))
|
||||
end
|
||||
end
|
||||
return m
|
||||
end
|
||||
local gmax, omax = maxTime(g), maxTime(scene)
|
||||
local tscale = if gmax > 0 and near(omax / gmax, 1000, 1e-3) then 1000 else 1
|
||||
-- (files assimp cannot read back: its exporter left out animation sources; their channels are dropped)
|
||||
for _, ga in if ref and not ref.failed then g.animations else {} do
|
||||
for _, gc in ga.channels do
|
||||
local gname = g.nodes[gc.node].name
|
||||
local ni = gname and byName[gname]
|
||||
if gc.interpolation == "LINEAR" and gc.path ~= "weights" and ni then
|
||||
local ours = nil
|
||||
for _, a in scene.animations do
|
||||
for _, ch in a.channels do
|
||||
if ch.node == ni and ch.path == gc.path then
|
||||
ours = ch
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check(ours, c.name .. ": animated " .. gname .. " " .. gc.path)
|
||||
if ours then
|
||||
local gin, gout = Scene.reader(gc.input) :: any, Scene.reader(gc.output) :: any
|
||||
for k = 0, gc.input.count - 1 do
|
||||
local want = {}
|
||||
for q = 0, gc.output.components - 1 do
|
||||
want[q + 1] = gout(k, q)
|
||||
end
|
||||
local got = channelAt(ours, gin(k, 0) * tscale)
|
||||
local ok
|
||||
if gc.path == "rotation" then
|
||||
local d = math.abs(got[1] * want[1] + got[2] * want[2] + got[3] * want[3] + got[4] * want[4])
|
||||
ok = d > 1 - 1e-4
|
||||
else
|
||||
ok = nearV(got, want, 1e-4)
|
||||
end
|
||||
t:check(ok, string.format("%s: %s %s at %g", c.name, gname, gc.path, gin(k, 0)))
|
||||
checked.keys += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
checked.gltf += 1
|
||||
end
|
||||
end
|
||||
-- the full rotations file: no resampled step over 90 degrees
|
||||
if string.find(c.name, "full_rotations", 1, true) then
|
||||
local worst = 1
|
||||
for _, a in scene.animations do
|
||||
for _, ch in a.channels do
|
||||
if ch.path == "rotation" then
|
||||
local r = Scene.reader(ch.output) :: any
|
||||
for k = 1, ch.output.count - 1 do
|
||||
local d = 0
|
||||
for q = 0, 3 do
|
||||
d += r(k, q) * r(k - 1, q)
|
||||
end
|
||||
worst = math.min(worst, d)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check(worst >= math.cos(math.rad(45)) - 1e-6, "full rotations: subdivided (worst dot " .. worst .. ")")
|
||||
end
|
||||
-- round trip through our writer (.dae, and .zae for a few)
|
||||
local tri = decode(c.data, { files = c.files })
|
||||
decoded[i] = tri
|
||||
local files = {}
|
||||
local out, eerr = Dae.encode(tri, { files = files, name = "rt.dae" })
|
||||
t:check(out, c.name .. ": encode: " .. tostring(eerr))
|
||||
if out then
|
||||
local back, berr = decode(out, { files = files })
|
||||
t:check(back, c.name .. ": re-decode: " .. tostring(berr))
|
||||
if back then
|
||||
local p1, f1 = counts(tri)
|
||||
local p2, f2 = counts(back)
|
||||
t:eq(p2, p1, c.name .. ": round trip meshes")
|
||||
t:eq(f2, f1, c.name .. ": round trip faces")
|
||||
local lo1, hi1 = MeshOps.bounds(tri)
|
||||
local lo2, hi2 = MeshOps.bounds(back)
|
||||
t:check((lo1 == nil and lo2 == nil) or (lo1 and lo2 and nearV(lo2, lo1, 1e-5) and nearV(hi2 :: any, hi1 :: any, 1e-5)), c.name .. ": round trip bounds")
|
||||
t:eq(#back.materials, #tri.materials, c.name .. ": round trip materials")
|
||||
t:eq(#back.cameras, #tri.cameras, c.name .. ": round trip cameras")
|
||||
t:eq(#back.lights, #tri.lights, c.name .. ": round trip lights")
|
||||
t:eq(#back.textures, #tri.textures, c.name .. ": round trip textures")
|
||||
for ti, tex in tri.textures do
|
||||
local bt = back.textures[ti]
|
||||
if tex.data and bt then
|
||||
t:check(bt.data and buffer.tostring(bt.data) == buffer.tostring(tex.data), c.name .. ": round trip texture " .. ti)
|
||||
end
|
||||
end
|
||||
for mi, m in tri.materials do
|
||||
local bm = back.materials[mi]
|
||||
t:check(bm and nearV(bm.baseColor, m.baseColor, 1e-6), c.name .. ": round trip baseColor " .. mi)
|
||||
end
|
||||
checked.roundTrips += 1
|
||||
end
|
||||
end
|
||||
if #c.data < 20000 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
end
|
||||
|
||||
-- assimp reads what we wrote like the source
|
||||
for _, x in Xcheck do
|
||||
local src = decoded[x.case]
|
||||
local ref = x.assimp
|
||||
t:check(ref and not ref.failed, x.name .. ": assimp reads our file")
|
||||
if src and ref and not ref.failed then
|
||||
local prims, faces = counts(src)
|
||||
if prims > 0 then
|
||||
t:eq(ref.meshes, prims, x.name .. ": meshes (assimp, ours)")
|
||||
t:eq(ref.faces, faces, x.name .. ": faces (assimp, ours)")
|
||||
local lo, hi = assimpBounds(src, true) -- our writer bakes the bind shape (it writes no skins)
|
||||
t:check(lo and nearV(lo, ref.min, 2e-4) and nearV(hi :: any, ref.max, 2e-4), string.format("%s: bounds %s %s, assimp %s %s", x.name, fmt(lo), fmt(hi), fmt(ref.min), fmt(ref.max)))
|
||||
end
|
||||
t:eq(ref.cameras, #src.cameras, x.name .. ": cameras (assimp, ours)")
|
||||
t:eq(ref.lights, #src.lights, x.name .. ": lights (assimp, ours)")
|
||||
checked.xcheck += 1
|
||||
end
|
||||
end
|
||||
|
||||
-- polygons: kept or fan-triangulated
|
||||
local function case(name: string): any
|
||||
for i, c in Cases do
|
||||
if string.find(c.name, name, 1, true) then
|
||||
return c, i
|
||||
end
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
do
|
||||
local c = case("ConcavePolygon")
|
||||
if c then
|
||||
local s = decode(c.data, { triangulate = false })
|
||||
local p = s.meshes[1].primitives[1]
|
||||
t:eq(p.mode, "polygons", "polygons kept")
|
||||
local corners = 0
|
||||
local get = Scene.reader(p.faces) :: any
|
||||
for k = 0, p.faces.count - 1 do
|
||||
corners += get(k, 0) - 2
|
||||
end
|
||||
local s2 = decode(c.data)
|
||||
t:eq(s2.meshes[1].primitives[1].mode, "triangles", "polygons triangulated")
|
||||
t:eq(s2.meshes[1].primitives[1].indices.count // 3, corners, "fan triangle count")
|
||||
local tri = MeshOps.triangulate(p)
|
||||
t:check(tri and tri.indices.count // 3 == corners, "MeshOps ear-clips the kept polygon")
|
||||
end
|
||||
end
|
||||
|
||||
-- materials and textures (duck: blinn, a TGA diffuse texture; decoded at the api layer)
|
||||
do
|
||||
local c = case("assimp/duck.dae")
|
||||
if c then
|
||||
local s = decode(c.data, { files = c.files })
|
||||
local m = s.materials[1]
|
||||
local ti = m.baseColorTexture and m.baseColorTexture.texture
|
||||
local tex = ti and s.textures[ti]
|
||||
t:check(tex and tex.data, "duck: diffuse texture bytes")
|
||||
t:eq(tex and tex.mime, "image/tga", "duck: texture mime")
|
||||
t:check(m.extras.phong.model == "blinn" and type(m.extras.phong.shininess) == "number", "duck: phong extras")
|
||||
local _, errs = F.model.loadTextures(s)
|
||||
t:check(tex and tex.image and tex.image.width > 0 and errs[ti :: number] == nil, "duck: texture decoded lazily")
|
||||
-- without the image files: the uri stays, no data
|
||||
local s2 = decode(c.data)
|
||||
t:check(ti and s2.textures[ti].data == nil and s2.textures[ti].uri == "./duckCM.tga", "duck: uri without files")
|
||||
local cam = s.cameras[1]
|
||||
t:check(cam.type == "perspective" and cam.yfov > 0 and cam.yfov < math.pi, "duck: camera")
|
||||
t:eq(s.meta.up, "y", "duck: up axis")
|
||||
end
|
||||
local z = case("assimp/duck.zae")
|
||||
if z then
|
||||
local s = decode(z.data)
|
||||
t:check(s.textures[1] and s.textures[1].data, "zae: texture read from the zip")
|
||||
t:check(Dae.sniff(Bytes.reader(buffer.fromstring(z.data))) > 0.9, "zae sniff")
|
||||
local zb = Dae.encode(s, { format = "zae" })
|
||||
local back = zb and decode(zb)
|
||||
t:check(back and back.textures[1] and back.textures[1].data and buffer.len(back.textures[1].data) == buffer.len(s.textures[1].data), "zae round trip with the texture")
|
||||
end
|
||||
local l = case("assimp/lights.dae")
|
||||
if l then
|
||||
local s = decode(l.data)
|
||||
local kinds = {}
|
||||
for _, li in s.lights do
|
||||
kinds[li.type] = (kinds[li.type] or 0) + 1
|
||||
end
|
||||
t:check(kinds.point == 2 and kinds.directional == 1 and kinds.spot == 1, "lights: kinds")
|
||||
t:eq(lightCount(s) - #s.lights, 1, "lights: one ambient")
|
||||
end
|
||||
local u = case("cube_UTF16LE")
|
||||
if u then
|
||||
t:eq(Dae.sniff(Bytes.reader(buffer.fromstring(u.data))), 1, "UTF-16 sniff")
|
||||
end
|
||||
local k = case("kwxport")
|
||||
if k then
|
||||
local s = decode(k.data)
|
||||
t:check(s.meta.up == "z" and near(s.meta.unit, 0.0254, 1e-9), "kwxport: Z_UP, inches")
|
||||
t:check(s.meshes[1].primitives[1].attributes.COLOR_0 ~= nil, "kwxport: vertex colours")
|
||||
end
|
||||
local uv2 = case("cube_with_2UVs")
|
||||
if uv2 then
|
||||
local s = decode(uv2.data)
|
||||
local a = s.meshes[1].primitives[1].attributes
|
||||
t:check(a.TEXCOORD_0 and a.TEXCOORD_1, "2 UV sets")
|
||||
end
|
||||
local clips = case("library_animation_clips")
|
||||
if clips then
|
||||
local s = decode(clips.data)
|
||||
t:check(#s.animations == 2 and s.animations[1].name ~= nil, "animation clips named")
|
||||
t:check(#s.skins >= 1 and s.skins[1].inverseBindMatrices ~= nil, "clips: skin with inverse bind matrices")
|
||||
local p = s.meshes[s.nodes[(function()
|
||||
for i, n in s.nodes do
|
||||
if n.skin then
|
||||
return i
|
||||
end
|
||||
end
|
||||
return 1
|
||||
end)()].mesh].primitives[1]
|
||||
local w = Scene.reader(p.attributes.WEIGHTS_0) :: any
|
||||
local okSum = true
|
||||
for v = 0, p.attributes.WEIGHTS_0.count - 1 do
|
||||
local sum = w(v, 0) + w(v, 1) + w(v, 2) + w(v, 3)
|
||||
if sum > 0 and math.abs(sum - 1) > 1e-5 then
|
||||
okSum = false
|
||||
end
|
||||
end
|
||||
t:check(okSum, "clips: weights normalized")
|
||||
end
|
||||
end
|
||||
|
||||
-- api: F.load by content / extension
|
||||
do
|
||||
local c = case("cube_tristrips")
|
||||
if c then
|
||||
local s, err = F.load(c.data)
|
||||
t:check(s and s.meta.source.format == "dae", "F.load: " .. tostring(err))
|
||||
local out = F.save(s, nil, { format = "dae" })
|
||||
t:check(out and string.find(buffer.tostring(out), "<COLLADA", 1, true), "F.save dae")
|
||||
end
|
||||
end
|
||||
|
||||
-- errors
|
||||
do
|
||||
local _, e1 = decode('<?xml version="1.0"?><root/>')
|
||||
t:check(e1 and e1.code == Err.CORRUPT, "not COLLADA: CORRUPT")
|
||||
local _, e2 = decode('<COLLADA version="1.4.1"><library_geometries>')
|
||||
t:check(e2 and (e2.code == Err.TRUNCATED or e2.code == Err.CORRUPT), "unclosed XML")
|
||||
local bad = [[<COLLADA version="1.4.1"><library_geometries><geometry id="g"><mesh>
|
||||
<source id="p"><float_array id="pa" count="3">0 0 0</float_array><technique_common><accessor source="#pa" count="1" stride="3"><param name="X" type="float"/><param name="Y" type="float"/><param name="Z" type="float"/></accessor></technique_common></source>
|
||||
<vertices id="v"><input semantic="POSITION" source="#p"/></vertices><triangles count="1"><input semantic="VERTEX" source="#v" offset="0"/><p>0 0 7</p></triangles></mesh></geometry></library_geometries>
|
||||
<library_visual_scenes><visual_scene id="s"><node id="n"><instance_geometry url="#g"/></node></visual_scene></library_visual_scenes><scene><instance_visual_scene url="#s"/></scene></COLLADA>]]
|
||||
local _, e3 = decode(bad)
|
||||
t:check(e3 and e3.code == Err.CORRUPT, "index out of range: CORRUPT")
|
||||
local _, e4 = decode(string.gsub(bad, "0 0 7", "0 0 0"), { maxVertices = 0 })
|
||||
t:check(e4 and e4.code == Err.LIMIT, "maxVertices: LIMIT")
|
||||
local ok = decode((string.gsub(bad, "0 0 7", "0 0 0")))
|
||||
t:check(ok and #ok.meshes == 1 and ok.meshes[1].primitives[1].attributes.POSITION.count == 1, "minimal file")
|
||||
local _, e5 = Dae.encode({} :: any)
|
||||
t:check(e5 and e5.code == Err.ARG, "encode: ARG")
|
||||
t:eq(Dae.sniff(Bytes.reader(buffer.fromstring("<svg/>"))), 0, "sniff: other XML")
|
||||
table.insert(samples, (string.gsub(bad, "0 0 7", "0 0 0")))
|
||||
end
|
||||
|
||||
t:note("%d cases: %d against assimp (%d bounds), %d against their glTF originals (%d animation keys), %d round trips", #Cases, checked.assimp, checked.bounds, checked.gltf, checked.keys, checked.roundTrips)
|
||||
t:note("%d of our files read back by assimp like the sources", checked.xcheck)
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
return Dae.decode(Bytes.reader(b))
|
||||
end, samples)
|
||||
t:done()
|
||||
@@ -0,0 +1,542 @@
|
||||
-- model/fbx tests: assimp's FBX test models (binary 7.4 / 7.5, ASCII 7.4 - 7.7, embedded textures, skeletons,
|
||||
-- animation), Blender's exporter (materials, textures, colours, skin, shape keys, animation, camera, lights) and
|
||||
-- assimp's exporters (binary and ASCII), against assimp (meshes, polygons, vertices, world bounds, materials,
|
||||
-- animations, cameras, lights) and Blender's importer (meshes, polygons, materials, bones, shape keys, cameras,
|
||||
-- lights, images); round trips through our writer (binary and ASCII) and glTF sample models through FBX (world
|
||||
-- triangles, materials, textures, skins, morph targets, sampled animation, cameras, lights); assimp and Blender
|
||||
-- reading our files like the originals (fbx_xcheck); errors; the fuzz no-throw pass. Fixtures: tools/fixtures/fbx.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Fbx = require("@formats/model/fbx")
|
||||
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/fbx_cases")
|
||||
local Xcheck = require("@tests/gen/fbx_xcheck")
|
||||
local GltfCases = require("@tests/gen/fbx_gltf")
|
||||
|
||||
local t = T.suite("fbx")
|
||||
|
||||
local function decode(data: any, opts: any?): (any, any)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
return Fbx.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
t:eq(Fbx.name, "fbx", "name")
|
||||
t:eq(Fbx.category, "model", "category")
|
||||
t:check(Fbx.caps.decode and Fbx.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 triArea(prim: any): number
|
||||
local pos, ind = prim.attributes.POSITION, prim.indices
|
||||
if not ind then
|
||||
return 0
|
||||
end
|
||||
local area = 0
|
||||
local function P(i: number, k: number): number
|
||||
return buffer.readf32(pos.data, (i * 3 + k) * 4)
|
||||
end
|
||||
for tri = 0, ind.count // 3 - 1 do
|
||||
local a, b, c = buffer.readu32(ind.data, tri * 12), buffer.readu32(ind.data, tri * 12 + 4), buffer.readu32(ind.data, tri * 12 + 8)
|
||||
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
|
||||
|
||||
-- assimp-like counts: placed primitives, polygons, corners
|
||||
local function counts(scene: any): (number, number, number)
|
||||
local prims, faces, verts = 0, 0, 0
|
||||
local seen = {}
|
||||
for _, pl in Types.Scene.flatten(scene) do
|
||||
if not seen[pl.primitive] then
|
||||
seen[pl.primitive] = true
|
||||
prims += 1
|
||||
faces += if pl.primitive.faces then pl.primitive.faces.count else pl.primitive.indices.count // 3
|
||||
verts += pl.primitive.attributes.POSITION.count
|
||||
end
|
||||
end
|
||||
return prims, faces, verts
|
||||
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
|
||||
|
||||
local function stats(scene: any): { [string]: number }
|
||||
local s = { meshNodes = 0, limbs = 0, shapes = 0, textures = #scene.textures, cameras = #scene.cameras, lights = #scene.lights }
|
||||
for _, n in scene.nodes do
|
||||
if n.mesh then
|
||||
s.meshNodes += 1
|
||||
end
|
||||
if n.extras and n.extras.fbx and n.extras.fbx.type == "LimbNode" then
|
||||
s.limbs += 1
|
||||
end
|
||||
end
|
||||
for _, m in scene.meshes do
|
||||
s.shapes += if m.weights then #m.weights else 0
|
||||
end
|
||||
return s
|
||||
end
|
||||
|
||||
-- world bounds, also under assimp's Z-up -> Y-up root conversion (x, z, -y)
|
||||
local function boundsMatch(lo: { number }, hi: { number }, want: any, eps: number): boolean
|
||||
local function eq(a: { number }, b: { number }, c: { number }, d: { number }): boolean
|
||||
for k = 1, 3 do
|
||||
if not near(a[k], c[k], eps) or not near(b[k], d[k], eps) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
if eq(lo, hi, want.min, want.max) then
|
||||
return true
|
||||
end
|
||||
return eq({ lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] }, want.min, want.max)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ reference files
|
||||
local checked = { assimp = 0, blender = 0, roundTrips = 0, failed = 0 }
|
||||
local scenes = {}
|
||||
for i, c in Cases do
|
||||
local scene, err = decode(c.data, { files = c.files, triangulate = false })
|
||||
local a = c.assimp
|
||||
if a.failed then
|
||||
t:check(scene == nil and err ~= nil, c.name .. ": assimp rejects it, so do we")
|
||||
checked.failed += 1
|
||||
else
|
||||
t:check(scene, c.name .. ": decode: " .. tostring(err))
|
||||
scenes[i] = scene
|
||||
local prims, faces, verts = counts(scene)
|
||||
t:eq(prims, a.meshes, c.name .. ": meshes (assimp)")
|
||||
t:eq(faces, a.faces, c.name .. ": polygons (assimp)")
|
||||
t:eq(verts, a.vertices, c.name .. ": vertices (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)")
|
||||
t:eq(#scene.materials + (if noMaterial(scene) then 1 else 0), a.materials, c.name .. ": materials (assimp, + its default)")
|
||||
if a.min then
|
||||
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
|
||||
t:check(lo and 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.assimp += 1
|
||||
local b = c.blender
|
||||
if b and not b.failed then
|
||||
local s = stats(scene)
|
||||
t:eq(s.meshNodes, b.meshes, c.name .. ": mesh objects (Blender)")
|
||||
t:eq(faces, b.polygons, c.name .. ": polygons (Blender)")
|
||||
t:eq(#scene.materials, b.materials, c.name .. ": materials (Blender)")
|
||||
t:eq(s.limbs, b.bones, c.name .. ": bones (Blender)")
|
||||
t:eq(s.shapes, b.shapeKeys, c.name .. ": shape keys (Blender)")
|
||||
t:eq(s.cameras, b.cameras, c.name .. ": cameras (Blender)")
|
||||
t:eq(s.lights, b.lights, c.name .. ": lights (Blender)")
|
||||
t:eq(s.textures, b.images, c.name .. ": textures (Blender)")
|
||||
t:check((#scene.animations > 0) == (b.actions > 0), c.name .. ": animated (Blender)")
|
||||
checked.blender += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:note("%d files: %d against assimp, %d against Blender, %d rejected by both", #Cases, checked.assimp, checked.blender, checked.failed)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ round trips
|
||||
-- world triangles (area, count, bounds), materials, textures, skins, morph targets, animation samples, cameras, lights
|
||||
local function compare(a: any, b: any, label: string, eps: 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")
|
||||
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.textures, #a.textures, label .. ": textures")
|
||||
for k, tex in a.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), label .. ": texture " .. k .. " bytes")
|
||||
end
|
||||
end
|
||||
t:eq(#b.skins, #a.skins, label .. ": skins")
|
||||
for k, s in a.skins do
|
||||
local s2 = b.skins[k]
|
||||
if s2 then
|
||||
t:eq(#s2.joints, #s.joints, label .. ": skin joints")
|
||||
end
|
||||
end
|
||||
local function targets(s: any): number
|
||||
local n = 0
|
||||
for _, m in s.meshes do
|
||||
n += if m.weights then #m.weights else 0
|
||||
end
|
||||
return n
|
||||
end
|
||||
t:eq(targets(b), targets(a), label .. ": morph targets")
|
||||
t:eq(#b.cameras, #a.cameras, label .. ": cameras")
|
||||
t:eq(#b.lights, #a.lights, label .. ": lights")
|
||||
-- cameras / lights: the same world placement (forward axis included)
|
||||
local function placed(s: any, field: string): { { number } }
|
||||
local out = {}
|
||||
local function visit(i: number, parent: { number }, seen: { [number]: boolean })
|
||||
if seen[i] then
|
||||
return
|
||||
end
|
||||
seen[i] = true
|
||||
local n = s.nodes[i]
|
||||
local w = Types.Scene.mul(parent, Types.Scene.nodeMatrix(n))
|
||||
if n[field] then
|
||||
out[n[field]] = w
|
||||
end
|
||||
for _, c in n.children do
|
||||
visit(c, w, seen)
|
||||
end
|
||||
end
|
||||
local seen = {}
|
||||
for _, r in s.roots do
|
||||
visit(r, Types.Scene.IDENTITY, seen)
|
||||
end
|
||||
return out
|
||||
end
|
||||
for _, field in { "camera", "light" } do
|
||||
local pa, pb = placed(a, field), placed(b, field)
|
||||
for k, w in pa do
|
||||
local w2 = pb[k]
|
||||
local ok = w2 ~= nil
|
||||
if w2 then
|
||||
for q = 1, 16 do
|
||||
ok = ok and math.abs(w[q] - w2[q]) <= eps * math.max(1, math.abs(w[q]))
|
||||
end
|
||||
end
|
||||
t:check(ok, label .. ": " .. field .. " " .. k .. " world matrix")
|
||||
end
|
||||
end
|
||||
-- animations: every channel of b sampled against a (LINEAR / STEP / CUBICSPLINE values at the keys of b)
|
||||
t:eq(#b.animations, #a.animations, label .. ": animations")
|
||||
local function evalCh(ch: any, time: number, comps: number): { number }
|
||||
local IN, OUT = Types.Scene.reader(ch.input) :: any, Types.Scene.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 ch.path == "rotation" 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
|
||||
for ai, an in a.animations do
|
||||
local bn = b.animations[ai]
|
||||
if bn then
|
||||
-- channels by node name + path
|
||||
local byKey = {}
|
||||
for _, ch in an.channels do
|
||||
byKey[(a.nodes[ch.node].name or "") .. "/" .. ch.path] = ch
|
||||
end
|
||||
local bad, n = 0, 0
|
||||
for _, ch in bn.channels do
|
||||
local key = (b.nodes[ch.node].name or "") .. "/" .. ch.path
|
||||
local orig = byKey[key]
|
||||
local comps = if ch.path == "rotation" then 4 elseif ch.path == "weights" then ch.output.count // ch.input.count else 3
|
||||
if orig then
|
||||
local IN = Types.Scene.reader(ch.input) :: any
|
||||
for k = 0, ch.input.count - 1 do
|
||||
local time = IN(k, 0)
|
||||
local want = evalCh(orig, time, comps)
|
||||
local got = evalCh(ch, time, comps)
|
||||
local dot = 0
|
||||
for q = 1, comps do
|
||||
dot += want[q] * got[q]
|
||||
end
|
||||
local sign = if ch.path == "rotation" and dot < 0 then -1 else 1
|
||||
for q = 1, comps do
|
||||
if math.abs(got[q] * sign - want[q]) > 1e-3 * math.max(1, math.abs(want[q])) then
|
||||
bad += 1
|
||||
end
|
||||
end
|
||||
n += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:check(bad == 0, string.format("%s: animation %d: %d of %d samples differ", label, ai, bad, n))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
for i, c in Cases do
|
||||
local scene = scenes[i]
|
||||
if scene then
|
||||
for _, ascii in { false, true } do
|
||||
local out, err = Fbx.encode(scene, { ascii = ascii })
|
||||
t:check(out, c.name .. ": encode: " .. tostring(err))
|
||||
local back, berr = decode(out :: buffer, { triangulate = false })
|
||||
t:check(back, c.name .. ": decode ours: " .. tostring(berr))
|
||||
if back then
|
||||
compare(scene, back, c.name .. (if ascii then " (ascii)" else ""), 1e-5)
|
||||
t:eq(#back.nodes, #scene.nodes, c.name .. ": nodes")
|
||||
local p1, f1, v1 = counts(scene)
|
||||
local p2, f2, v2 = counts(back)
|
||||
t:check(p1 == p2 and f1 == f2 and v1 == v2, c.name .. ": polygons kept")
|
||||
end
|
||||
end
|
||||
checked.roundTrips += 1
|
||||
end
|
||||
end
|
||||
|
||||
-- glTF sample models through FBX
|
||||
local ng = 0
|
||||
for _, g in GltfCases 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
|
||||
local out, err = Fbx.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
|
||||
-- glTF points / lines are not written
|
||||
local lines = false
|
||||
for _, m in scene.meshes do
|
||||
for _, p in m.primitives do
|
||||
if p.mode == "points" or p.mode == "lines" or p.mode == "line_strip" or p.mode == "line_loop" then
|
||||
lines = true
|
||||
end
|
||||
end
|
||||
end
|
||||
if not lines then
|
||||
compare(scene, back, "glTF " .. g.name, 2e-5)
|
||||
end
|
||||
ng += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:note("%d round trips of the reference files (binary + ASCII), %d glTF models through FBX", checked.roundTrips, ng)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ cross-check
|
||||
-- assimp and Blender read our files like the originals
|
||||
local nx = 0
|
||||
for _, x in Xcheck do
|
||||
local c = Cases[x.case]
|
||||
local a, ca = x.assimp, c.assimp
|
||||
local scene = scenes[x.case]
|
||||
if not ca.failed and scene then
|
||||
local _, faces = counts(scene)
|
||||
t:check(not a.failed, x.name .. ": assimp reads our file")
|
||||
t:eq(a.meshes, ca.meshes, x.name .. ": assimp meshes of our file (" .. c.name .. ")")
|
||||
t:eq(a.faces, faces, x.name .. ": assimp polygons of our file (" .. c.name .. ")")
|
||||
t:eq(a.cameras, ca.cameras, x.name .. ": assimp cameras of our file")
|
||||
t:eq(a.lights, ca.lights, x.name .. ": assimp lights of our file")
|
||||
t:eq(a.animations, ca.animations, x.name .. ": assimp animations of our file")
|
||||
t:eq(a.bones, ca.bones, x.name .. ": assimp bones of our file")
|
||||
if a.min and ca.min then
|
||||
local ok = true
|
||||
for k = 1, 3 do
|
||||
ok = ok and near(a.min[k], ca.min[k], 1e-4) and near(a.max[k], ca.max[k], 1e-4)
|
||||
end
|
||||
t:check(ok, x.name .. ": assimp world bounds of our file (" .. c.name .. ")")
|
||||
end
|
||||
local b, cb = x.blender, c.blender
|
||||
if b and cb and not cb.failed then
|
||||
t:check(not b.failed, x.name .. ": Blender reads our file: " .. tostring(b.failed))
|
||||
if not b.failed then
|
||||
for _, k in { "meshes", "polygons", "materials", "bones", "shapeKeys", "cameras", "lights", "images" } do
|
||||
t:eq(b[k], cb[k], x.name .. ": Blender " .. k .. " of our file (" .. c.name .. ")")
|
||||
end
|
||||
t:check((b.actions > 0) == (cb.actions > 0), x.name .. ": Blender actions of our file")
|
||||
end
|
||||
end
|
||||
nx += 1
|
||||
end
|
||||
end
|
||||
t:note("%d of our files read back by assimp / Blender like the originals", nx)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ details
|
||||
do
|
||||
local byName = {}
|
||||
for i, c in Cases do
|
||||
byName[c.name] = scenes[i]
|
||||
end
|
||||
local cube = byName["blender/blender_cube.fbx"]
|
||||
if cube then
|
||||
local tex = cube.textures[1]
|
||||
t:check(tex and tex.data and tex.mime == "image/png", "Blender cube: embedded PNG kept encoded")
|
||||
local _, errs = F.model.loadTextures(cube)
|
||||
t:check(tex.image and tex.image.width == 8 and next(errs) == nil, "F.model.loadTextures decodes the embedded PNG")
|
||||
local red = cube.materials[1]
|
||||
t:check(red.name == "Red" and red.baseColorTexture and red.extras.fbx.shadingModel ~= nil, "material with a texture + Phong extras")
|
||||
local prim = cube.meshes[1].primitives[1]
|
||||
t:check(prim.attributes.COLOR_0 and prim.attributes.TEXCOORD_0 and prim.attributes.NORMAL, "colours, uvs, normals")
|
||||
t:eq(cube.meta.up, "y", "Blender writes Y up")
|
||||
t:check(near(cube.meta.unit, 0.01, 1e-9), "unit: centimetres")
|
||||
end
|
||||
local skin = byName["blender/blender_skin.fbx"]
|
||||
if skin then
|
||||
local m = skin.meshes[1]
|
||||
local p = m.primitives[1]
|
||||
t:check(#skin.skins == 1 and #skin.skins[1].joints == 2 and p.attributes.JOINTS_0 and p.attributes.WEIGHTS_0, "skin: joints and weights")
|
||||
t:check(m.weights and #m.weights == 1 and m.weights[1] >= 0 and m.weights[1] <= 1 and p.targets and p.targets[1].POSITION, "shape key: a morph target and its weight")
|
||||
local paths = {}
|
||||
for _, ch in skin.animations[1].channels do
|
||||
paths[ch.path] = true
|
||||
end
|
||||
t:check(paths.rotation and paths.weights, "animation: rotation and morph weights channels")
|
||||
-- weights sum to 1
|
||||
local W = Types.Scene.reader(p.attributes.WEIGHTS_0) :: any
|
||||
local ok = true
|
||||
for v = 0, p.attributes.WEIGHTS_0.count - 1 do
|
||||
local s = W(v, 0) + W(v, 1) + W(v, 2) + W(v, 3)
|
||||
ok = ok and (math.abs(s - 1) < 1e-5 or s == 0)
|
||||
end
|
||||
t:check(ok, "skin weights normalized")
|
||||
end
|
||||
local cl = byName["blender/blender_camlight.fbx"]
|
||||
if cl then
|
||||
local types = {}
|
||||
for _, l in cl.lights do
|
||||
types[l.type] = true
|
||||
end
|
||||
t:check(types.point and types.directional and types.spot, "point, directional, spot lights")
|
||||
local cam = cl.cameras[1]
|
||||
-- Blender's 35 mm lens on a 36 mm sensor, 16:9 render
|
||||
t:check(cam.type == "perspective" and cam.yfov > 0.3 and cam.yfov < 1.2, "camera fov " .. cam.yfov)
|
||||
end
|
||||
local pbr = byName["assimp/maxPbrMaterial_metalRough.fbx"]
|
||||
if pbr then
|
||||
local m = pbr.materials[1]
|
||||
t:check(near(m.metallic, 0.25, 1e-6) and near(m.roughness, 0.5, 1e-6), "3ds Max PBR material: metalness / roughness")
|
||||
end
|
||||
local emb = byName["assimp/embedded_ascii/box.FBX"]
|
||||
if emb then
|
||||
t:check(emb.textures[1] and emb.textures[1].data and emb.meta.source.binary == false, "ASCII: base64 embedded texture")
|
||||
t:eq(emb.meta.up, "z", "3ds Max: Z up")
|
||||
end
|
||||
-- polygons kept / triangulated
|
||||
local box = decode(Cases[2].data)
|
||||
t:check(box.meshes[1].primitives[1].mode == "triangles", "triangulated by default")
|
||||
-- through the api
|
||||
local s = F.load(Cases[2].data)
|
||||
t:check(s and s.kind == "scene" and s.meta.source.format == "fbx", "F.load detects binary FBX")
|
||||
local viaApi = F.save(s, nil, { format = "fbx" })
|
||||
t:check(viaApi and buffer.readstring(viaApi, 0, 18) == "Kaydara FBX Binary", "F.save format fbx")
|
||||
-- a 7.5 (64-bit records) file
|
||||
local v75 = Fbx.encode(s, { version = 7500 }) :: buffer
|
||||
local b75 = decode(v75)
|
||||
t:check(b75 and b75.meta.source.version == 7500 and #b75.meshes == #s.meshes, "7.5 records")
|
||||
-- a scene made by hand: a quad as polygons, written and read back as one polygon
|
||||
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 qb = decode(Fbx.encode(quad) :: buffer, { triangulate = false })
|
||||
t:check(qb and qb.meshes[1].primitives[1].faces.count == 1 and qb.meshes[1].primitives[1].indices.count == 4, "a quad stays one polygon")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ errors
|
||||
do
|
||||
local _, e1 = decode("; FBX 6.1.0 project file\nFBXHeaderExtension: {\n\tFBXVersion: 6100\n}\n")
|
||||
t:check(e1 and e1.code == Err.UNSUPPORTED, "FBX 6: " .. tostring(e1))
|
||||
local bin = Cases[2].data
|
||||
local _, e2 = decode(string.sub(bin, 1, 200))
|
||||
t:check(e2 and (e2.code == Err.TRUNCATED or e2.code == Err.CORRUPT), "truncated: " .. tostring(e2))
|
||||
local _, e3 = decode(string.sub(bin, 1, 23) .. "\100\25\0\0" .. string.sub(bin, 28))
|
||||
t:check(e3 and e3.code == Err.UNSUPPORTED, "binary version 6500: " .. tostring(e3))
|
||||
local _, e4 = decode("FBXHeaderExtension: { FBXVersion: 7400 }\nObjects: {")
|
||||
t:check(e4 and e4.code == Err.CORRUPT, "unterminated ASCII: " .. tostring(e4))
|
||||
local _, e5 = decode("FBXHeaderExtension: { FBXVersion: 7400 }\n")
|
||||
t:check(e5 and e5.code == Err.CORRUPT, "no Objects: " .. tostring(e5))
|
||||
local _, e6 = decode(bin, { maxBytes = 100 })
|
||||
t:check(e6 and e6.code == Err.LIMIT, "maxBytes: " .. tostring(e6))
|
||||
local _, e7 = Fbx.encode({} :: any)
|
||||
t:check(e7 and e7.code == Err.ARG, "encode junk")
|
||||
local _, e8 = Fbx.encode(Types.Scene.new(), { version = 6100 })
|
||||
t:check(e8 and e8.code == Err.ARG, "encode version 6100")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fuzz
|
||||
do
|
||||
local samples = {}
|
||||
for i, c in Cases do
|
||||
if #c.data < 60000 then
|
||||
table.insert(samples, c.data)
|
||||
end
|
||||
local s = scenes[i]
|
||||
if s and #samples < 24 then
|
||||
local a = Fbx.encode(s, { ascii = true })
|
||||
if a and buffer.len(a) < 60000 then
|
||||
table.insert(samples, buffer.tostring(a))
|
||||
end
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(b: buffer)
|
||||
local s = Fbx.decode(Bytes.reader(b))
|
||||
if s then
|
||||
Fbx.encode(s)
|
||||
MeshOps.merge(s)
|
||||
end
|
||||
return s
|
||||
end, samples, { mutations = 12, keepHeader = 27 })
|
||||
end
|
||||
|
||||
t:done()
|
||||
@@ -0,0 +1,547 @@
|
||||
-- model/usda tests: stages authored with OpenUSD's API (every xform op kind / order, pivots, resetXformStack,
|
||||
-- primvar interpolations, holes, leftHanded, n-gons, UsdPreviewSurface networks, GeomSubsets, inherited bindings,
|
||||
-- cameras, lights, time samples, a USDZ package, a USDC file), a hand-written grammar test, assimp's USD models
|
||||
-- (usda + usdc converted by Sdf), Blender 5 exports of glTF samples - all against OpenUSD (pxr: world transforms,
|
||||
-- triangles, area and bounds per mesh, bound materials, PreviewSurface inputs and textures, cameras, lights, xform time
|
||||
-- samples); OpenUSD's schema layers parse-only (prim spec counts); round trips through our writer (stable text) and
|
||||
-- pxr reading our output (usda_xcheck); the api; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/usda.py.
|
||||
local T = require("@tests/T")
|
||||
local F = require("@formats")
|
||||
local Usda = require("@formats/model/usda")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Cases = require("@tests/gen/usda_cases")
|
||||
local Specs = require("@tests/gen/usda_specs")
|
||||
local Xcheck = require("@tests/gen/usda_xcheck")
|
||||
|
||||
local t = T.suite("usda")
|
||||
local Scene = Types.Scene
|
||||
|
||||
local function decode(data: any, opts: any?): (any, any)
|
||||
local b = if type(data) == "string" then buffer.fromstring(data) else data
|
||||
return Usda.decode(Bytes.reader(b), opts)
|
||||
end
|
||||
|
||||
t:eq(Usda.name, "usda", "name")
|
||||
t:eq(Usda.category, "model", "category")
|
||||
t:check(Usda.caps.decode and Usda.caps.encode and table.find(Usda.extensions, "usdz"), "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 nearAll(a: { number }, b: { number }, eps: number): boolean
|
||||
if #a ~= #b then
|
||||
return false
|
||||
end
|
||||
for k = 1, #a do
|
||||
if not near(a[k], b[k], eps) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ scene helpers
|
||||
-- a node's channels evaluated at time s (seconds): translation / rotation / scale overrides
|
||||
local function animated(scene: any, s: number?): { [number]: any }
|
||||
local out: { [number]: any } = {}
|
||||
if not s then
|
||||
return out
|
||||
end
|
||||
for _, anim in scene.animations do
|
||||
for _, ch in anim.channels do
|
||||
local n = ch.input.count
|
||||
local get = Scene.reader(ch.output) :: any
|
||||
local comps = ch.output.components
|
||||
local k = 0
|
||||
for i = 0, n - 1 do
|
||||
if buffer.readf32(ch.input.data, i * 4) <= s + 1e-6 then
|
||||
k = i
|
||||
end
|
||||
end
|
||||
local t0 = buffer.readf32(ch.input.data, k * 4)
|
||||
local f = 0
|
||||
if k < n - 1 then
|
||||
local t1 = buffer.readf32(ch.input.data, (k + 1) * 4)
|
||||
f = math.clamp((s - t0) / (t1 - t0), 0, 1)
|
||||
end
|
||||
local v = {}
|
||||
for c = 0, comps - 1 do
|
||||
local a = get(k, c)
|
||||
local b = if k < n - 1 then get(k + 1, c) else a
|
||||
v[c + 1] = a + (b - a) * f
|
||||
end
|
||||
out[ch.node] = out[ch.node] or {}
|
||||
out[ch.node][ch.path] = v
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- world matrices of every node (at animation time s when given)
|
||||
local function worlds(scene: any, s: number?): { [number]: { number } }
|
||||
local over = animated(scene, s)
|
||||
local out: { [number]: { number } } = {}
|
||||
local function visit(i: number, parent: { number })
|
||||
local n = scene.nodes[i]
|
||||
if not n or out[i] then
|
||||
return
|
||||
end
|
||||
local o = over[i]
|
||||
local m
|
||||
if o then
|
||||
m = Scene.nodeMatrix({ children = {}, translation = o.translation or n.translation, rotation = o.rotation or n.rotation, scale = o.scale or n.scale })
|
||||
else
|
||||
m = Scene.nodeMatrix(n)
|
||||
end
|
||||
local w = Scene.mul(parent, m)
|
||||
out[i] = w
|
||||
for _, c in n.children do
|
||||
visit(c, w)
|
||||
end
|
||||
end
|
||||
for _, r in scene.roots do
|
||||
visit(r, Scene.IDENTITY :: any)
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function byPath(scene: any): { [string]: number }
|
||||
local out = {}
|
||||
for i, n in scene.nodes do
|
||||
local u = n.extras and n.extras.usd
|
||||
if u and u.path then
|
||||
out[u.path] = i
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- triangles, world area and bounds of a node's mesh (or of everything: node = nil)
|
||||
local function geometry(scene: any, ws: { [number]: { number } }, only: number?): (number, number, { number }, { number })
|
||||
local tris, area = 0, 0
|
||||
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
|
||||
for i, n in scene.nodes do
|
||||
if n.mesh and (only == nil or only == i) and ws[i] then
|
||||
local m = ws[i]
|
||||
for _, p in scene.meshes[n.mesh].primitives do
|
||||
local pos = p.attributes.POSITION
|
||||
local function P(v: number): { number }
|
||||
local x, y, z = buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8)
|
||||
return { 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 ind = p.indices
|
||||
for k = 0, ind.count // 3 - 1 do
|
||||
local a, b, c = P(buffer.readu32(ind.data, k * 12)), P(buffer.readu32(ind.data, k * 12 + 4)), P(buffer.readu32(ind.data, k * 12 + 8))
|
||||
local e1 = { b[1] - a[1], b[2] - a[2], b[3] - a[3] }
|
||||
local e2 = { c[1] - a[1], c[2] - a[2], c[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]
|
||||
area += math.sqrt(x * x + y * y + z * z) / 2
|
||||
tris += 1
|
||||
for _, q in { a, b, c } do
|
||||
for j = 1, 3 do
|
||||
lo[j] = math.min(lo[j], q[j])
|
||||
hi[j] = math.max(hi[j], q[j])
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return tris, area, lo, hi
|
||||
end
|
||||
|
||||
-- pxr's totals over every mesh
|
||||
local function refTotals(ref: any): (number, number, { number }, { number })
|
||||
local tris, area = 0, 0
|
||||
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
|
||||
for _, m in ref.meshes do
|
||||
tris += m.triangles
|
||||
area += m.area
|
||||
if #m.min == 3 then
|
||||
for j = 1, 3 do
|
||||
lo[j] = math.min(lo[j], m.min[j])
|
||||
hi[j] = math.max(hi[j], m.max[j])
|
||||
end
|
||||
end
|
||||
end
|
||||
return tris, area, lo, hi
|
||||
end
|
||||
|
||||
local LIGHT_TYPES = { DistantLight = "directional", SphereLight = "point", RectLight = "spot", DiskLight = "spot" }
|
||||
local SKIP_TYPES = { Skeleton = true, SkelRoot = true }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ against pxr
|
||||
local decoded: { [number]: any } = {}
|
||||
local counts = { xforms = 0, meshes = 0, materials = 0, cameras = 0, lights = 0, samples = 0, textures = 0 }
|
||||
for ci, c in Cases do
|
||||
local scene, err = decode(c.data, { files = c.files })
|
||||
if c.expect then
|
||||
t:check(scene == nil and err and err.code == Err[c.expect], c.name .. ": " .. c.expect .. " (" .. tostring(err) .. ")")
|
||||
continue
|
||||
end
|
||||
t:check(scene, c.name .. ": decode: " .. tostring(err))
|
||||
if not scene then
|
||||
continue
|
||||
end
|
||||
decoded[ci] = scene
|
||||
local ref = c.ref
|
||||
t:eq(scene.meta.up, string.lower(ref.upAxis), c.name .. ": up axis")
|
||||
if ref.metersPerUnit > 0 then
|
||||
t:check(scene.meta.unit and near(scene.meta.unit, ref.metersPerUnit, 1e-9), c.name .. ": metersPerUnit")
|
||||
else
|
||||
t:eq(scene.meta.unit, nil, c.name .. ": no metersPerUnit")
|
||||
end
|
||||
local paths = byPath(scene)
|
||||
local ws = worlds(scene)
|
||||
-- transforms: every xformable pxr sees is a node with the same world matrix
|
||||
for _, x in ref.xforms do
|
||||
if not SKIP_TYPES[x.type] then
|
||||
local ni = paths[x.path]
|
||||
t:check(ni, c.name .. ": node " .. x.path)
|
||||
if ni then
|
||||
t:check(nearAll(ws[ni], x.world, 1e-4), c.name .. ": world matrix of " .. x.path)
|
||||
counts.xforms += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
-- meshes
|
||||
for _, m in ref.meshes do
|
||||
local ni = paths[m.path]
|
||||
local node = ni and scene.nodes[ni]
|
||||
if node and m.triangles > 0 then
|
||||
t:check(node.mesh, c.name .. ": mesh at " .. m.path)
|
||||
local tris, area, lo, hi = geometry(scene, ws, ni)
|
||||
t:eq(tris, m.triangles, c.name .. ": triangles of " .. m.path)
|
||||
t:check(near(area, m.area, 1e-4), string.format("%s: area of %s %.6g, pxr %.6g", c.name, m.path, area, m.area))
|
||||
t:check(nearAll(lo, m.min, 1e-4) and nearAll(hi, m.max, 1e-4), c.name .. ": bounds of " .. m.path)
|
||||
-- bound materials (whole mesh, then subsets)
|
||||
local mesh = scene.meshes[node.mesh]
|
||||
local whole, subs = nil, {}
|
||||
for _, p in mesh.primitives do
|
||||
local mat = p.material and scene.materials[p.material]
|
||||
local mp = mat and mat.extras and mat.extras.usd and mat.extras.usd.path or ""
|
||||
if p.extras and p.extras.usd and p.extras.usd.subset then
|
||||
table.insert(subs, mp)
|
||||
else
|
||||
whole = mp
|
||||
end
|
||||
end
|
||||
if m.material ~= "" and whole then
|
||||
t:eq(whole, m.material, c.name .. ": material of " .. m.path)
|
||||
end
|
||||
table.sort(subs)
|
||||
t:eq(table.concat(subs, ","), table.concat(m.subsetMaterials, ","), c.name .. ": subset materials of " .. m.path)
|
||||
counts.meshes += 1
|
||||
end
|
||||
end
|
||||
-- cameras
|
||||
for _, cam in ref.cameras do
|
||||
local ni = paths[cam.path]
|
||||
local camera = ni and scene.nodes[ni].camera and scene.cameras[scene.nodes[ni].camera]
|
||||
t:check(camera, c.name .. ": camera " .. cam.path)
|
||||
if camera then
|
||||
if cam.projection == "orthographic" then
|
||||
t:check(camera.type == "orthographic" and near(camera.xmag, cam.hap / 20, 1e-6) and near(camera.ymag, cam.vap / 20, 1e-6), c.name .. ": ortho camera")
|
||||
else
|
||||
t:check(near(camera.yfov, 2 * math.atan(cam.vap / (2 * cam.focal)), 1e-5), c.name .. ": yfov of " .. cam.path)
|
||||
t:check(near(camera.aspect, cam.hap / cam.vap, 1e-5), c.name .. ": aspect of " .. cam.path)
|
||||
end
|
||||
t:check(near(camera.znear, cam.near, 1e-5) and near(camera.zfar, cam.far, 1e-5), c.name .. ": clipping of " .. cam.path)
|
||||
counts.cameras += 1
|
||||
end
|
||||
end
|
||||
-- lights
|
||||
for _, l in ref.lights do
|
||||
local ni = paths[l.path]
|
||||
local light = ni and scene.nodes[ni].light and scene.lights[scene.nodes[ni].light]
|
||||
t:check(light, c.name .. ": light " .. l.path)
|
||||
if light then
|
||||
local want = if l.cone > 0 and l.cone < 90 then "spot" else LIGHT_TYPES[l.type]
|
||||
t:eq(light.type, want, c.name .. ": light type of " .. l.path)
|
||||
t:check(near(light.intensity, l.intensity, 1e-5) and nearAll(light.color, l.color, 1e-5), c.name .. ": light values of " .. l.path)
|
||||
if want == "spot" and l.cone > 0 then
|
||||
t:check(near(light.outerCone, math.rad(l.cone), 1e-5), c.name .. ": cone of " .. l.path)
|
||||
end
|
||||
counts.lights += 1
|
||||
end
|
||||
end
|
||||
-- materials
|
||||
local mats = {}
|
||||
for _, m in scene.materials do
|
||||
if m.extras and m.extras.usd and m.extras.usd.path then
|
||||
mats[m.extras.usd.path] = m
|
||||
end
|
||||
end
|
||||
for _, rm in ref.materials do
|
||||
local m = mats[rm.path]
|
||||
if m then -- only bound materials become Scene materials
|
||||
local tx = rm.textures
|
||||
if rm.diffuseColor and not tx.diffuseColor then
|
||||
t:check(nearAll({ m.baseColor[1], m.baseColor[2], m.baseColor[3] }, rm.diffuseColor, 1e-6), c.name .. ": diffuse of " .. rm.path)
|
||||
end
|
||||
if rm.metallic and not tx.metallic then
|
||||
t:check(near(m.metallic, rm.metallic, 1e-6), c.name .. ": metallic of " .. rm.path)
|
||||
end
|
||||
if rm.roughness and not tx.roughness then
|
||||
t:check(near(m.roughness, rm.roughness, 1e-6), c.name .. ": roughness of " .. rm.path)
|
||||
end
|
||||
if rm.emissiveColor and not tx.emissiveColor then
|
||||
t:check(nearAll(m.emissive, rm.emissiveColor, 1e-6), c.name .. ": emissive of " .. rm.path)
|
||||
end
|
||||
if rm.opacity and not tx.opacity then
|
||||
t:check(near(m.baseColor[4], rm.opacity, 1e-6), c.name .. ": opacity of " .. rm.path)
|
||||
if rm.opacityThreshold and rm.opacityThreshold > 0 then
|
||||
t:check(m.alphaMode == "mask" and near(m.alphaCutoff, rm.opacityThreshold, 1e-6), c.name .. ": alpha mask of " .. rm.path)
|
||||
elseif rm.opacity < 1 then
|
||||
t:eq(m.alphaMode, "blend", c.name .. ": alpha blend of " .. rm.path)
|
||||
end
|
||||
end
|
||||
local function texFile(ref: any): string?
|
||||
local tex = ref and scene.textures[ref.texture]
|
||||
return tex and tex.uri
|
||||
end
|
||||
for input, field in { diffuseColor = "baseColorTexture", normal = "normalTexture", emissiveColor = "emissiveTexture", occlusion = "occlusionTexture", roughness = "metallicRoughnessTexture", metallic = "metallicRoughnessTexture" } do
|
||||
if tx[input] then
|
||||
t:eq(texFile(m[field]), tx[input].file, c.name .. ": " .. input .. " texture of " .. rm.path)
|
||||
counts.textures += 1
|
||||
end
|
||||
end
|
||||
counts.materials += 1
|
||||
end
|
||||
end
|
||||
-- xform time samples
|
||||
for _, a in ref.anim do
|
||||
local ni = paths[a.path]
|
||||
for _, smp in a.samples do
|
||||
local w = worlds(scene, smp.time / ref.tcps)
|
||||
t:check(ni and nearAll(w[ni], smp.world, 1e-4), string.format("%s: %s at time %g", c.name, a.path, smp.time))
|
||||
counts.samples += 1
|
||||
end
|
||||
end
|
||||
-- textures with their file at hand carry its bytes
|
||||
for _, tex in scene.textures do
|
||||
local want = c.files[tex.uri] or c.files[(string.gsub(string.gsub(tex.uri, "\\", "/"), "^%./", ""))] or (c.like ~= nil)
|
||||
if want then
|
||||
t:check(tex.data and buffer.len(tex.data) > 0, c.name .. ": texture bytes for " .. tex.uri)
|
||||
end
|
||||
end
|
||||
end
|
||||
t:note("%d files against pxr: %d transforms, %d meshes, %d materials (%d textures), %d cameras, %d lights, %d time samples", #Cases, counts.xforms, counts.meshes, counts.materials, counts.textures, counts.cameras, counts.lights, counts.samples)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ specific facts
|
||||
do
|
||||
local hand
|
||||
for ci, c in Cases do
|
||||
if c.name == "hand.usda" then
|
||||
hand = decoded[ci]
|
||||
end
|
||||
end
|
||||
local p = byPath(hand)
|
||||
t:check(p["/Hand/Big"] and not p["/Hand/Small"] and not p["/_Template"] and not p["/Elsewhere/Undefined"], "hand: selected variant, no class / undefined over")
|
||||
t:check(p["/Hand/Untyped/Inner/Quad"] and not p["/Hand/Looks"], "hand: untyped prims are nodes, material scopes are not")
|
||||
t:check(table.find(hand.meta.source.unsupported, "references"), "hand: references reported unsupported")
|
||||
t:eq(hand.meta.source.defaultPrim, "Hand", "hand: defaultPrim")
|
||||
local tri = hand.nodes[p["/Hand/Tri"]]
|
||||
local mat = hand.materials[hand.meshes[tri.mesh].primitives[1].material]
|
||||
t:check(nearAll(mat.baseColor, { 0.1, 0.2, 0.9, 1 }, 1e-6), "hand: diffuse through a Material interface input + relative paths")
|
||||
local big = hand.meshes[hand.nodes[p["/Hand/Big"]].mesh].primitives[1]
|
||||
t:check(big.attributes.COLOR_0 and big.attributes.COLOR_0.count == 4, "hand: vertex displayColor -> COLOR_0")
|
||||
local layer = Usda.parse(Cases[1].data)
|
||||
t:check(layer and #layer.prims == 1 and layer.meta.defaultPrim == "World", "parse: the raw layer")
|
||||
end
|
||||
do
|
||||
local prim
|
||||
for ci, c in Cases do
|
||||
if c.name == "pxr/primvars.usda" then
|
||||
prim = decoded[ci]
|
||||
end
|
||||
end
|
||||
local p = byPath(prim)
|
||||
local grid = prim.meshes[prim.nodes[p["/Grid"]].mesh].primitives[1]
|
||||
t:check(grid.attributes.TEXCOORD_0 and grid.attributes.TEXCOORD_1 and grid.attributes.NORMAL and grid.attributes.COLOR_0.components == 4, "primvars: st, uv2, normals, colour + opacity")
|
||||
local cc = prim.meshes[prim.nodes[p["/Grid/ConstColor"]].mesh].primitives[1]
|
||||
t:check(cc.attributes.COLOR_0 == nil and nearAll(prim.materials[cc.material].baseColor, { 0.2, 0.4, 0.8, 1 }, 1e-6), "primvars: constant displayColor -> material")
|
||||
local poly = decode(Cases[2].data, { triangulate = false })
|
||||
local pg = poly.meshes[1].primitives[1]
|
||||
t:check(pg.mode == "polygons" and pg.faces.count == 17, "primvars: polygons kept (16 quads + pentagon + triangle - 1 hole)")
|
||||
-- the texture transform on the materials stage
|
||||
local mats
|
||||
for ci, c in Cases do
|
||||
if c.name == "pxr/materials.usda" then
|
||||
mats = decoded[ci]
|
||||
end
|
||||
end
|
||||
for _, m in mats.materials do
|
||||
if m.name == "Textured" then
|
||||
local mr = m.metallicRoughnessTexture
|
||||
t:check(mr and mr.texCoord == 1 and mr.transform and near(mr.transform.rotation, math.rad(30), 1e-6), "materials: uv2 + UsdTransform2d -> texCoord 1 + KHR_texture_transform")
|
||||
t:eq(mats.textures[mr.texture].sampler.wrapS, "mirror", "materials: wrapS")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ parse-only
|
||||
for _, s in Specs do
|
||||
local layer, err = Usda.parse(s.data)
|
||||
t:check(layer, s.name .. ": parse: " .. tostring(err))
|
||||
if layer then
|
||||
local n = 0
|
||||
local function count(list: { any })
|
||||
for _, p in list do
|
||||
n += 1
|
||||
count(p.children)
|
||||
end
|
||||
end
|
||||
count(layer.prims)
|
||||
t:eq(n, s.prims, s.name .. ": prim specs (Sdf)")
|
||||
end
|
||||
end
|
||||
t:note("%d OpenUSD schema layers parsed", #Specs)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ round trips
|
||||
local rt = 0
|
||||
local texts: { [number]: string } = {}
|
||||
for ci = 1, #Cases do
|
||||
local scene = decoded[ci]
|
||||
if not scene then
|
||||
continue
|
||||
end
|
||||
local name = Cases[ci].name
|
||||
local files = {}
|
||||
local out, err = Usda.encode(scene, { files = files, name = "rt.usda" })
|
||||
t:check(out, name .. ": encode: " .. tostring(err))
|
||||
if out then
|
||||
texts[ci] = buffer.tostring(out)
|
||||
local back, berr = decode(out, { files = files })
|
||||
t:check(back, name .. ": decode our output: " .. tostring(berr))
|
||||
if back then
|
||||
local a1, a2, a3, a4 = geometry(scene, worlds(scene))
|
||||
local b1, b2, b3, b4 = geometry(back, worlds(back))
|
||||
t:eq(b1, a1, name .. ": round trip triangles")
|
||||
t:check(near(b2, a2, 1e-5) and (a1 == 0 or (nearAll(b3, a3, 1e-5) and nearAll(b4, a4, 1e-5))), name .. ": round trip area / bounds")
|
||||
t:eq(#back.materials, #scene.materials, name .. ": round trip materials")
|
||||
t:eq(#back.cameras, #scene.cameras, name .. ": round trip cameras")
|
||||
t:eq(#back.lights, #scene.lights, name .. ": round trip lights")
|
||||
t:eq(#back.animations, #scene.animations, name .. ": round trip animations")
|
||||
t:eq(back.meta.up, scene.meta.up, name .. ": round trip up axis")
|
||||
for k, m in scene.materials do
|
||||
local b = back.materials[k]
|
||||
t:check(b and nearAll(b.baseColor, m.baseColor, 1e-6) and near(b.metallic, m.metallic, 1e-6) and near(b.roughness, m.roughness, 1e-6) and b.alphaMode == m.alphaMode and (b.baseColorTexture ~= nil) == (m.baseColorTexture ~= nil), name .. ": round trip material " .. k)
|
||||
end
|
||||
-- animated geometry at every key time
|
||||
if #scene.animations > 0 then
|
||||
local ch = scene.animations[1].channels[1]
|
||||
for i = 0, ch.input.count - 1 do
|
||||
local s = buffer.readf32(ch.input.data, i * 4)
|
||||
local _, x2, x3 = geometry(scene, worlds(scene, s))
|
||||
local _, y2, y3 = geometry(back, worlds(back, s))
|
||||
t:check(near(x2, y2, 1e-4) and nearAll(x3, y3, 1e-4), string.format("%s: round trip animation at %g s", name, s))
|
||||
end
|
||||
end
|
||||
-- our text is stable: after one cycle (a scene with several roots gains a "root" prim), writing what we
|
||||
-- read from our own output gives the same text
|
||||
local again = Usda.encode(back, { files = {}, name = "rt.usda" }) :: buffer
|
||||
local third = Usda.encode((decode(again)), { files = {}, name = "rt.usda" }) :: buffer
|
||||
t:eq(buffer.tostring(third), buffer.tostring(again), name .. ": stable text")
|
||||
rt += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
t:note("%d round trips", rt)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ pxr reads our output
|
||||
local xc = 0
|
||||
for _, x in Xcheck do
|
||||
local scene = decoded[x.case]
|
||||
local ref = x.ref
|
||||
local name = Cases[x.case].name .. " -> ours"
|
||||
t:check(scene and not ref.failed, name .. ": pxr opens our file")
|
||||
if scene and not ref.failed then
|
||||
local a1, a2, a3, a4 = geometry(scene, worlds(scene))
|
||||
local r1, r2, r3, r4 = refTotals(ref)
|
||||
t:eq(r1, a1, name .. ": triangles (pxr)")
|
||||
t:check(near(r2, a2, 1e-4), string.format("%s: area %.6g, pxr %.6g", name, a2, r2))
|
||||
if a1 > 0 then
|
||||
t:check(nearAll(r3, a3, 1e-4) and nearAll(r4, a4, 1e-4), name .. ": bounds (pxr)")
|
||||
end
|
||||
t:eq(#ref.materials, #scene.materials, name .. ": materials (pxr)")
|
||||
t:eq(#ref.cameras, #scene.cameras, name .. ": cameras (pxr)")
|
||||
t:eq(#ref.lights, #scene.lights, name .. ": lights (pxr)")
|
||||
t:eq(string.lower(ref.upAxis), scene.meta.up, name .. ": up axis (pxr)")
|
||||
-- every material's values as pxr reads them
|
||||
local want, got = {}, {}
|
||||
for _, m in scene.materials do
|
||||
table.insert(want, string.format("%.4f %.4f %.4f", if m.metallicRoughnessTexture then -1 else m.metallic, if m.metallicRoughnessTexture then -1 else m.roughness, if m.baseColorTexture then -1 else m.baseColor[1]))
|
||||
end
|
||||
for _, m in ref.materials do
|
||||
table.insert(got, string.format("%.4f %.4f %.4f", if m.textures.metallic then -1 else m.metallic or 0, if m.textures.roughness then -1 else m.roughness or 0.5, if m.textures.diffuseColor then -1 else (m.diffuseColor or { 0.18 })[1]))
|
||||
end
|
||||
table.sort(want)
|
||||
table.sort(got)
|
||||
t:eq(table.concat(got, ";"), table.concat(want, ";"), name .. ": material values (pxr)")
|
||||
-- animated nodes: each pxr sample matches one of our nodes at that time
|
||||
for _, a in ref.anim do
|
||||
for _, smp in a.samples do
|
||||
local w = worlds(scene, smp.time / ref.tcps)
|
||||
local found = false
|
||||
for _, m in w do
|
||||
if nearAll(m, smp.world, 1e-4) then
|
||||
found = true
|
||||
break
|
||||
end
|
||||
end
|
||||
t:check(found, string.format("%s: %s at %g (pxr)", name, a.path, smp.time))
|
||||
end
|
||||
end
|
||||
xc += 1
|
||||
end
|
||||
end
|
||||
t:note("%d of our files read back by pxr like the originals", xc)
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ api
|
||||
do
|
||||
local scene, err = F.model.load(Cases[1].data)
|
||||
t:check(scene and scene.meta.source.format == "usda", "api: F.model.load sniffs usda: " .. tostring(err))
|
||||
local s = F.saveString(scene, { format = "usda" })
|
||||
t:check(s and string.sub(s, 1, 9) == "#usda 1.0", "api: F.saveString usda")
|
||||
local _, zerr = F.save(scene, nil, { format = "usdz" })
|
||||
t:check(zerr and zerr.code == Err.UNSUPPORTED, "api: usdz writing unsupported")
|
||||
t:eq(F.detect(Cases[1].data), "usda", "api: detect")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ errors
|
||||
do
|
||||
local _, e1 = decode("#usda 1.0\ndef Xform \"a\" {\n")
|
||||
t:check(e1 and e1.code == Err.TRUNCATED, "truncated prim: " .. tostring(e1))
|
||||
local _, e2 = decode("#usda 1.0\ndef Xform \"a\" { float x = ] }\n")
|
||||
t:check(e2 and e2.code == Err.CORRUPT, "bad value: " .. tostring(e2))
|
||||
local _, e3 = decode("hello")
|
||||
t:check(e3 and e3.code == Err.CORRUPT, "no header")
|
||||
local _, e4 = decode("#usda 1.0\ndef Mesh \"m\" { point3f[] points = [(0,0,0)] int[] faceVertexCounts = [3] int[] faceVertexIndices = [0, 1, 2] }")
|
||||
t:check(e4 and e4.code == Err.CORRUPT, "index out of range: " .. tostring(e4))
|
||||
local _, e5 = decode(Cases[1].data, { maxVertices = 4 })
|
||||
t:check(e5 and e5.code == Err.LIMIT, "maxVertices")
|
||||
local _, e6 = Usda.encode({ kind = "image" } :: any)
|
||||
t:check(e6 and e6.code == Err.ARG, "encode a non-scene")
|
||||
local deep = "#usda 1.0\ndef \"a\" { custom float x = " .. string.rep("(", 500) .. "1" .. string.rep(")", 500) .. " }"
|
||||
local _, e7 = decode(deep)
|
||||
t:check(e7 and e7.code == Err.CORRUPT, "nesting limit")
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ fuzz
|
||||
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 = decode(b)
|
||||
if s then
|
||||
Usda.encode(s)
|
||||
end
|
||||
return s
|
||||
end, samples, { mutations = 24, keepHeader = 10 })
|
||||
t:done()
|
||||
Reference in new issue
Block a user