-- model/usda tests: OpenUSD-authored stages, assimp's USD models and Blender exports against OpenUSD (pxr). -- Fixtures: tools/fixtures/usda.py. local T = require("@tests/T") local F = require("@rosetta") local Usda = require("@rosetta/model/usda") local Bytes = require("@rosetta/core/Bytes") local Err = require("@rosetta/core/Err") local Types = require("@rosetta/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 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 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 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 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 } 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 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 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 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 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 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) 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 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) 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 -- a scene with several roots gains a "root" prim on the first cycle; after that our text is stable 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) 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) 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 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 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()