Files

525 lines
19 KiB
Luau

-- model/fbx tests: assimp's FBX models, Blender and assimp exports, against assimp and Blender's importer.
-- Fixtures: tools/fixtures/fbx.py.
local T = require("@tests/T")
local F = require("@rosetta")
local Fbx = require("@rosetta/model/fbx")
local Gltf = require("@rosetta/model/gltf")
local MeshOps = require("@rosetta/ops/MeshOps")
local Bytes = require("@rosetta/core/Bytes")
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/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
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
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)
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
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
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)
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)
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
local box = decode(Cases[2].data)
t:check(box.meshes[1].primitives[1].mode == "triangles", "triangulated by default")
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
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
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()