From fb7f6359cd1fab264e2e47b418e9ae082b69e383 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:41:47 -0500 Subject: [PATCH] ws-3d2/usda: model/usda - USD ASCII read / write (+ USDZ read), checked against OpenUSD (pxr), assimp's USD models and Blender exports Reads stage metadata, xform op stacks (every rotate order, orient, transform, pivots / !invert!, resetXformStack), time samples -> TRS animation, Mesh (all primvar interpolations + indices, GeomSubsets, holes, leftHanded), UsdPreviewSurface / UsdUVTexture / UsdTransform2d materials with inherited bindings, cameras, UsdLux lights, selected variants. USDC returns UNSUPPORTED. Writes Xform / Mesh / GeomSubset / Material / Camera / lights. Co-Authored-By: Claude Opus 5.5 --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/model/usda/Build.luau | 1396 +++++++++++++++++++++++++++++ src/Formats/model/usda/Parse.luau | 820 +++++++++++++++++ src/Formats/model/usda/Write.luau | 840 +++++++++++++++++ src/Formats/model/usda/init.luau | 221 +++++ tests/model/usda.luau | 547 +++++++++++ tools/fixtures/_usda_encode.luau | 34 + tools/fixtures/_usda_reference.py | 404 +++++++++ tools/fixtures/usda.py | 264 ++++++ 10 files changed, 4539 insertions(+) create mode 100644 src/Formats/model/usda/Build.luau create mode 100644 src/Formats/model/usda/Parse.luau create mode 100644 src/Formats/model/usda/Write.luau create mode 100644 src/Formats/model/usda/init.luau create mode 100644 tests/model/usda.luau create mode 100644 tools/fixtures/_usda_encode.luau create mode 100644 tools/fixtures/_usda_reference.py create mode 100644 tools/fixtures/usda.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 40e275f..5f216ea 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -25,6 +25,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | +| model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | | font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` | | font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d514aa9..ab5dd9e 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -254,6 +254,18 @@ local list: { Entry } = { return require("@formats/model/stl") end, }, + { + name = "usda", + category = "model", + path = "model/usda", + extensions = { "usda", "usd", "usdz" }, + mime = { "model/vnd.usda", "model/vnd.usdz+zip" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + caps = { decode = true, encode = true, materials = true, animation = true, cameras = true, lights = true, polygons = true, vertexColors = true, usdz = "read", usdc = false }, + load = function() + return require("@formats/model/usda") + end, + }, { name = "vox", category = "model", diff --git a/src/Formats/model/usda/Build.luau b/src/Formats/model/usda/Build.luau new file mode 100644 index 0000000..6c3615f --- /dev/null +++ b/src/Formats/model/usda/Build.luau @@ -0,0 +1,1396 @@ +--!strict +-- model/usda/Build: a parsed USDA layer (model/usda/Parse) -> Scene, following the UsdGeom / UsdShade / UsdLux +-- schemas (openusd 26.x documentation). Prims: Xform / Scope / untyped def / over -> nodes (class prims are skipped; +-- Material, Shader, NodeGraph, GeomSubset and scopes holding only those are not nodes); Mesh -> a node with a mesh +-- (one primitive per GeomSubset of the "face" element type + one for the remaining faces), Camera, DistantLight / +-- SphereLight / RectLight / DiskLight / CylinderLight. The selected variant of each variant set is merged into its prim. +-- Transforms: xformOpOrder over translate / scale / rotateX|Y|Z / rotateXYZ (all six orders) / orient / transform, the +-- !invert! prefix and !resetXformStack! (the node becomes a root). Time samples on xform ops -> one animation (the local +-- matrix sampled at the union of the ops' time codes, decomposed into TRS channels; time = code / timeCodesPerSecond); +-- other attributes use their earliest sample (as UsdTimeCode.EarliestTime()). Primvars: st (and every texCoord2f / +-- float2 primvar) -> TEXCOORD_n (v flipped to glTF's top-left origin unless opts.flipV = false), normals, displayColor +-- / displayOpacity -> COLOR_0 (a constant displayColor on an unbound mesh becomes a material instead), with every +-- interpolation (constant / uniform / vertex / varying / faceVarying) and :indices. Faces are fan-triangulated +-- (opts.triangulate = false keeps "polygons"), holeIndices skipped, orientation = "leftHanded" reversed. +-- UsdPreviewSurface materials (inputs resolved through connections to Material / NodeGraph interface inputs) with +-- UsdUVTexture textures (file, wrapS / wrapT, st through UsdPrimvarReader_float2, UsdTransform2d -> +-- KHR_texture_transform), material:binding (inherited down the namespace, also on GeomSubsets). +-- Not supported: composition arcs (references, payloads, inherits, specializes, subLayers: listed in +-- meta.source.unsupported), UsdSkel, blend shapes, BasisCurves / Points / NURBS, instancing, MaterialX networks. +local Types = require("@formats/Types") +local Parse = require("@formats/model/usda/Parse") + +local Build = {} + +type Prim = Parse.Prim +type Prop = Parse.Prop + +local NONE = Parse.NONE +local DEG = math.pi / 180 + +local NOT_NODES = { Material = true, Shader = true, NodeGraph = true, GeomSubset = true, Skeleton = true, SkelAnimation = true, BlendShape = true } +local SKEL = { Skeleton = true, SkelAnimation = true, BlendShape = true } +local LIGHTS = { DistantLight = true, SphereLight = true, RectLight = true, DiskLight = true, CylinderLight = true, DomeLight = true } +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", webp = "image/webp", tga = "image/x-tga", bmp = "image/bmp", exr = "image/x-exr", hdr = "image/vnd.radiance", ktx2 = "image/ktx2", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff", avif = "image/avif" } + +export type Options = { + triangulate: boolean?, + flipV: boolean?, + fetch: ((uri: string) -> buffer?)?, + maxVertices: number?, +} + +-- ------------------------------------------------------------------------------------------------ helpers +local function isArr(v: any): boolean + return type(v) == "table" and v.t == "arr" +end +local function str(v: any): string? + if type(v) == "string" then + return v + elseif type(v) == "table" and (v.t == "id" or v.t == "asset" or v.t == "path") then + return v.v + end + return nil +end +-- a tuple / scalar -> numbers (nil when not numeric) +local function nums(v: any): { number }? + if type(v) == "number" then + return { v } + elseif type(v) == "boolean" then + return { if v then 1 else 0 } + elseif type(v) == "table" and v.t == "tuple" then + local out = {} + for k, x in v.v do + if type(x) == "number" then + out[k] = x + elseif type(x) == "table" and x.t == "tuple" then + for _, y in x.v do + if type(y) ~= "number" then + return nil + end + table.insert(out, y) + end + else + return nil + end + end + return out + elseif type(v) == "table" and v.t == "arr" then + return v.v + end + return nil +end +local function num(v: any): number? + if type(v) == "number" then + return v + elseif type(v) == "boolean" then + return if v then 1 else 0 + end + return nil +end + +-- the value of a property: its default, else its earliest time sample +local function propValue(p: Prop?): any + if not p then + return nil + end + if p.samples and #p.samples.times > 0 then + local best, bi = math.huge, 0 + for k, t in p.samples.times do + if t < best then + best, bi = t, k + end + end + local v = p.samples.values[bi] + if v ~= NONE then + return v + end + end + if p.hasValue and p.value ~= NONE then + return p.value + end + return nil +end + +local function joinPath(parent: string, name: string): string + return if parent == "/" then "/" .. name else parent .. "/" .. name +end + +-- resolve a (possibly relative) Sdf path against the prim path that holds it +local function resolvePath(base: string, p: string): string + if string.sub(p, 1, 1) == "/" then + return p + end + local parts = string.split(base, "/") + local out: { string } = {} + for _, x in parts do + if x ~= "" then + table.insert(out, x) + end + end + for _, x in string.split(p, "/") do + if x == ".." then + table.remove(out) + elseif x ~= "." and x ~= "" then + table.insert(out, x) + end + end + return "/" .. table.concat(out, "/") +end +-- "/a/b.outputs:rgb" -> "/a/b", "outputs:rgb" +local function splitProp(p: string): (string, string?) + local prim, prop = string.match(p, "^(.-)%.([^/]+)$") + if prim and prop then + return prim, prop + end + return p, nil +end + +-- ------------------------------------------------------------------------------------------------ matrices +-- column-major 4x4 (glTF layout = USD's row-major row-vector text order) +local mul = Types.Scene.mul +local function translateM(x: number, y: number, z: number): { number } + return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } +end +local function scaleM(x: number, y: number, z: number): { number } + return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } +end +local function rotM(axis: number, deg: number): { number } + local c, s = math.cos(deg * DEG), math.sin(deg * DEG) + if axis == 1 then + return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 } + elseif axis == 2 then + return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 } + end + return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } +end +local function quatM(x: number, y: number, z: number, w: number): { number } + local l = math.sqrt(x * x + y * y + z * z + w * w) + if l > 0 then + x, y, z, w = x / l, y / l, z / l, w / l + end + return Types.Scene.nodeMatrix({ children = {}, rotation = { x, y, z, w } }) +end +local function inverse(m: { number }): { number }? + local a = m + local inv = table.create(16, 0) + 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] + if det == 0 or det ~= det then + return nil + end + for k = 1, 16 do + inv[k] /= det + end + return inv +end +Build.inverse = inverse + +-- decompose(m) -> translation, rotation (quaternion x y z w), scale (no shear) +local function decompose(m: { number }): ({ number }, { number }, { number }) + local sx = math.sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3]) + local sy = math.sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7]) + local sz = math.sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11]) + local det = m[1] * (m[6] * m[11] - m[7] * m[10]) - m[5] * (m[2] * m[11] - m[3] * m[10]) + m[9] * (m[2] * m[7] - m[3] * m[6]) + if det < 0 then + sx = -sx + end + local function d(v: number, s: number): number + return if s ~= 0 then v / s else 0 + end + local r00, r10, r20 = d(m[1], sx), d(m[2], sx), d(m[3], sx) + local r01, r11, r21 = d(m[5], sy), d(m[6], sy), d(m[7], sy) + local r02, r12, r22 = d(m[9], sz), d(m[10], sz), d(m[11], sz) + local x, y, z, w + local tr = r00 + r11 + r22 + if tr > 0 then + local s = math.sqrt(tr + 1) * 2 + w, x, y, z = 0.25 * s, (r21 - r12) / s, (r02 - r20) / s, (r10 - r01) / s + elseif r00 > r11 and r00 > r22 then + local s = math.sqrt(1 + r00 - r11 - r22) * 2 + w, x, y, z = (r21 - r12) / s, 0.25 * s, (r01 + r10) / s, (r02 + r20) / s + elseif r11 > r22 then + local s = math.sqrt(1 + r11 - r00 - r22) * 2 + w, x, y, z = (r02 - r20) / s, (r01 + r10) / s, 0.25 * s, (r12 + r21) / s + else + local s = math.sqrt(1 + r22 - r00 - r11) * 2 + w, x, y, z = (r10 - r01) / s, (r02 + r20) / s, (r12 + r21) / s, 0.25 * s + end + local l = math.sqrt(x * x + y * y + z * z + w * w) + if l > 0 then + x, y, z, w = x / l, y / l, z / l, w / l + end + return { m[13], m[14], m[15] }, { x, y, z, w }, { sx, sy, sz } +end +Build.decompose = decompose + +-- ------------------------------------------------------------------------------------------------ xform ops +type Op = { kind: string, axes: string?, prop: Prop, invert: boolean } + +-- the op stack of a prim: ops in xformOpOrder, resetXformStack +local function xformOps(p: Prim): ({ Op }, boolean) + local order = p.props.xformOpOrder + local list = order and propValue(order) + local ops: { Op } = {} + local reset = false + if type(list) ~= "table" or list.t ~= "list" then + return ops, false + end + for _, item in list.v do + local name = str(item) + if name == "!resetXformStack!" then + reset = true + table.clear(ops) + elseif name then + local invert = false + if string.sub(name, 1, 8) == "!invert!" then + invert = true + name = string.sub(name, 9) + end + local prop = p.props[name] + local kind = string.match(name, "^xformOp:(%a+)") + if prop and kind then + local axes = string.match(kind, "^rotate([XYZ]+)$") + table.insert(ops, { kind = if axes then "rotate" else kind, axes = axes, prop = prop, invert = invert }) + end + end + end + return ops, reset +end + +local AXIS = { X = 1, Y = 2, Z = 3 } +-- the matrix of one op for a value +local function opMatrix(op: Op, v: any): { number }? + local n = nums(v) + if not n then + return nil + end + local m: { number }? + local k = op.kind + if k == "translate" then + m = translateM(n[1] or 0, n[2] or 0, n[3] or 0) + elseif k == "scale" then + local s1 = n[1] or 1 + m = scaleM(s1, n[2] or s1, n[3] or s1) + elseif k == "orient" then + -- USD quaternions are written (real, i, j, k) + m = quatM(n[2] or 0, n[3] or 0, n[4] or 0, n[1] or 1) + elseif k == "transform" then + if #n ~= 16 then + return nil + end + m = table.clone(n) + elseif k == "rotate" and op.axes then + local axes = op.axes :: string + local r: { number } = Types.Scene.IDENTITY :: any + -- rotateXZY: X first, then Z, then Y: R = Ry * Rz * Rx (column vectors); the value is always (x, y, z) angles + for c = 1, #axes do + local a = AXIS[string.sub(axes, c, c)] + local angle = if #axes == 1 then n[1] or 0 else n[a] or 0 + r = mul(rotM(a, angle), r) + end + m = r + else + return nil + end + if op.invert and m then + m = inverse(m) + end + return m +end + +local function lerpValue(a: any, b: any, f: number, quat: boolean): any + local na, nb = nums(a), nums(b) + if not na or not nb or #na ~= #nb then + return a + end + local out = table.create(#na) + if quat and #na == 4 then + -- (w, x, y, z): slerp through nlerp with the short path + local dot = 0 + for k = 1, 4 do + dot += na[k] * nb[k] + end + local sgn = if dot < 0 then -1 else 1 + for k = 1, 4 do + out[k] = na[k] + (nb[k] * sgn - na[k]) * f + end + return { t = "tuple", v = out } + end + for k = 1, #na do + out[k] = na[k] + (nb[k] - na[k]) * f + end + return { t = "tuple", v = out } +end + +-- an op's value at time code t (samples interpolated linearly, held outside their range) +local function opValueAt(op: Op, t: number?): any + local p = op.prop + local s = p.samples + if t ~= nil and s and #s.times > 0 then + local times, values = s.times, s.values + local lo, hi + for k = 1, #times do + local tk = times[k] + if values[k] ~= NONE then + if tk <= t and (lo == nil or tk > times[lo]) then + lo = k + end + if tk >= t and (hi == nil or tk < times[hi]) then + hi = k + end + end + end + if lo and hi then + if lo == hi or times[hi] == times[lo] then + return values[lo] + end + local f = (t - times[lo]) / (times[hi] - times[lo]) + return lerpValue(values[lo], values[hi], f, op.kind == "orient") + end + return values[lo or hi] + end + return propValue(p) +end + +local function localMatrix(ops: { Op }, t: number?): { number } + local m: { number } = Types.Scene.IDENTITY :: any + for _, op in ops do + local om = opMatrix(op, opValueAt(op, t)) + if om then + m = mul(m, om) + end + end + return m +end +Build.localMatrix = localMatrix + +-- ------------------------------------------------------------------------------------------------ build +function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) + local scene = Types.Scene.new() + local flipV = opts.flipV ~= false + local triangulate = opts.triangulate ~= false + local maxVertices = opts.maxVertices or 2 ^ 25 + local fetch = opts.fetch + local unsupported: { [string]: boolean } = {} + local meta = layer.meta + + -- prim index (variants merged), paths + local byPath: { [string]: Prim } = {} + local parentOf: { [Prim]: string } = {} + local pathOf: { [Prim]: string } = {} + local function merge(p: Prim) + if not p.variantSets then + return + end + local nested: { any }? = nil + local sel = p.meta.variants + local chosen = if type(sel) == "table" and sel.t == "dict" then sel.v else {} + for setName, set in p.variantSets :: any do + local name = str(chosen[setName]) + local body = name and set[name] -- unselected sets contribute nothing + if body then + for _, pn in body.order do + if not p.props[pn] then + p.props[pn] = body.props[pn] + table.insert(p.order, pn) + end + end + for _, c in body.children do + table.insert(p.children, c) + end + for k, v in body.meta do + if p.meta[k] == nil then + p.meta[k] = v + end + end + if body.variantSets then + nested = nested or {} + table.insert(nested :: any, body.variantSets) + end + end + end + p.variantSets = nil + for _, vs in nested or {} do + p.variantSets = vs + merge(p) + end + end + local function index(p: Prim, parent: string, depth: number) + if depth > 200 then + return + end + merge(p) + local path = joinPath(parent, p.name) + pathOf[p] = path + parentOf[p] = parent + local existing = byPath[path] + if existing and existing ~= p then + -- over / def of the same path in one layer: merge into the first spec + for _, pn in p.order do + if not existing.props[pn] then + existing.props[pn] = p.props[pn] + table.insert(existing.order, pn) + end + end + existing.typeName = existing.typeName or p.typeName + if p.specifier == "def" then + existing.specifier = "def" + end + for _, c in p.children do + table.insert(existing.children, c) + end + table.clear(p.children) + p.specifier = "class" -- skipped below + else + byPath[path] = p + end + for _, key in { "references", "payload", "inherits", "specializes" } do + local v = p.meta[key] + if v ~= nil and v ~= NONE then + unsupported[key] = true + end + end + for _, c in p.children do + index(c, path, depth + 1) + end + end + for _, p in layer.prims do + index(p, "/", 1) + end + if meta.subLayers ~= nil then + unsupported.subLayers = true + end + + -- a property of a prim path ("/a/b.inputs:x") + local function propAt(path: string): (Prim?, Prop?) + local pp, pn = splitProp(path) + local prim = byPath[pp] + if not prim or not pn then + return prim, nil + end + return prim, prim.props[pn] + end + + -- --------------------------------------------------------------------------------------------- materials + local texCoordIndex: { [string]: number } = {} + local texCoordCount = 0 + local function texCoordFor(name: string): number + local k = texCoordIndex[name] + if k == nil then + k = texCoordCount + texCoordIndex[name] = k + texCoordCount += 1 + end + return k + end + -- primvar names of every mesh, "st" first, so material readers and meshes agree on TEXCOORD_n + do + local names: { [string]: boolean } = {} + for _, p in byPath do + if p.typeName == "Mesh" then + for pn, pr in p.props do + local nm = string.match(pn, "^primvars:([^:]+)$") + if nm and (pr.typeName == "texCoord2f" or pr.typeName == "float2" or pr.typeName == "texCoord2d" or pr.typeName == "double2" or pr.typeName == "texCoord2h" or pr.typeName == "half2") and pr.array then + names[nm] = true + end + end + end + end + local list = {} + for nm in names do + table.insert(list, nm) + end + table.sort(list, function(a: string, b: string): boolean + local pa = if a == "st" then 0 elseif string.sub(a, 1, 2) == "st" then 1 else 2 + local pb = if b == "st" then 0 elseif string.sub(b, 1, 2) == "st" then 1 else 2 + if pa ~= pb then + return pa < pb + end + return a < b + end) + for _, nm in list do + texCoordFor(nm) + end + end + + -- an input's resolved source: a value, or { shader = Prim, output = name } + type Source = { value: any?, shader: Prim?, output: string? } + local function input(prim: Prim, name: string, depth: number?): Source? + local d = depth or 0 + if d > 32 then + return nil + end + local p = prim.props["inputs:" .. name] + if not p then + return nil + end + if p.connect and #p.connect > 0 then + local target = resolvePath(pathOf[prim] or "/", p.connect[1]) + local tp, tn = splitProp(target) + local tprim = byPath[tp] + if tprim and tn then + local outName = string.match(tn, "^outputs:(.+)$") + local inName = string.match(tn, "^inputs:(.+)$") + if outName and tprim.typeName == "Shader" then + return { shader = tprim, output = outName } + elseif outName then + -- a NodeGraph output: follow its connection + local op = tprim.props[tn] + if op and op.connect and #op.connect > 0 then + local t2 = resolvePath(tp, op.connect[1]) + local sp, sn = splitProp(t2) + local sprim = byPath[sp] + if sprim and sn and string.match(sn, "^outputs:") then + return { shader = sprim, output = string.sub(sn, 9) } + end + end + elseif inName then + local r = input(tprim, inName, d + 1) + if r then + return r + end + end + end + end + local v = propValue(p) + if v ~= nil then + return { value = v } + end + return nil + end + local function shaderId(p: Prim): string? + return str(propValue(p.props["info:id"])) + end + + local textureIndex: { [string]: number } = {} + local WRAP = { ["repeat"] = "repeat", clamp = "clamp", mirror = "mirror", black = "clamp", useMetadata = "repeat" } + -- UsdUVTexture shader -> TextureRef (texture index + texCoord + transform) + local function textureRef(shader: Prim): Types.TextureRef? + if shaderId(shader) ~= "UsdUVTexture" then + return nil + end + local f = input(shader, "file") + local file = f and str(f.value) + if not file or file == "" then + return nil + end + local ws = input(shader, "wrapS") + local wt = input(shader, "wrapT") + local wrapS = WRAP[ws and str(ws.value) or "repeat"] or "repeat" + local wrapT = WRAP[wt and str(wt.value) or "repeat"] or "repeat" + local key = file .. "|" .. wrapS .. "|" .. wrapT + local ti = textureIndex[key] + if not ti then + local tex: Types.Texture = { name = shader.name, uri = file, sampler = { wrapS = wrapS :: any, wrapT = wrapT :: any } } + local ext = string.lower(string.match(file, "%.(%w+)$") or "") + tex.mime = MIME[ext] + local data = fetch and fetch(file) + if not data and string.sub(file, 1, 2) == "./" and fetch then + data = fetch(string.sub(file, 3)) + end + tex.data = data + local extras: { [string]: any } = { path = pathOf[shader] } + local cs = input(shader, "sourceColorSpace") + if cs and str(cs.value) then + extras.sourceColorSpace = str(cs.value) + end + tex.extras = { usd = extras } + table.insert(scene.textures, tex) + ti = #scene.textures + textureIndex[key] = ti + end + local ref: Types.TextureRef = { texture = ti :: number } + -- st: UsdPrimvarReader_float2 (maybe through UsdTransform2d) + local st = input(shader, "st") + local reader = st and st.shader + if reader and shaderId(reader) == "UsdTransform2d" then + local tr: { [string]: any } = {} + local rot = input(reader, "rotation") + local scl = input(reader, "scale") + local off = input(reader, "translation") + if rot and num(rot.value) and num(rot.value) ~= 0 then + tr.rotation = (num(rot.value) :: number) * DEG + end + if scl and nums(scl.value) then + tr.scale = nums(scl.value) + end + if off and nums(off.value) then + tr.offset = nums(off.value) + end + if next(tr) then + ref.transform = tr :: any + end + local inn = input(reader, "in") + reader = inn and inn.shader + end + if reader and string.find(shaderId(reader) or "", "^UsdPrimvarReader") then + local vn = input(reader, "varname") + local name = vn and str(vn.value) + if name then + local k = texCoordFor(name) + if k ~= 0 then + ref.texCoord = k + end + end + end + return ref + end + + local materialIndex: { [string]: number } = {} + local function material(path: string): number? + local mi = materialIndex[path] + if mi ~= nil then + return if mi > 0 then mi else nil + end + local mp = byPath[path] + if not mp or mp.typeName ~= "Material" then + materialIndex[path] = 0 + return nil + end + local mat = Types.Scene.material(mp.name) + mat.baseColor = { 0.18, 0.18, 0.18, 1 } + mat.metallic = 0 + mat.roughness = 0.5 + mat.extras = { usd = { path = path } } + -- the surface shader + local surf = mp.props["outputs:surface"] or mp.props["outputs:usd:surface"] + local shader: Prim? = nil + if surf and surf.connect and #surf.connect > 0 then + local sp = splitProp(resolvePath(path, surf.connect[1])) + shader = byPath[sp] + end + if shader and shaderId(shader) == "UsdPreviewSurface" then + local sh = shader :: Prim + local function value(name: string): any + local s = input(sh, name) + return s and s.value + end + local function tex(name: string): (Types.TextureRef?, Prim?) + local s = input(sh, name) + if s and s.shader then + local ref = textureRef(s.shader) + return ref, if ref then s.shader else nil + end + return nil, nil + end + local dc = nums(value("diffuseColor")) + if dc and #dc >= 3 then + mat.baseColor = { dc[1], dc[2], dc[3], 1 } + end + local dt, dshader = tex("diffuseColor") + if dt then + mat.baseColorTexture = dt + mat.baseColor = { 1, 1, 1, 1 } + local sc = input(dshader :: Prim, "scale") + local s = sc and nums(sc.value) + if s and #s >= 3 then + mat.baseColor = { s[1], s[2], s[3], s[4] or 1 } + end + end + local op = num(value("opacity")) + local ot = tex("opacity") + if op then + mat.baseColor[4] = op + end + local thr = num(value("opacityThreshold")) + if thr and thr > 0 then + mat.alphaMode = "mask" + mat.alphaCutoff = thr + elseif (op and op < 1) or ot then + mat.alphaMode = "blend" + end + local m = num(value("metallic")) + if m then + mat.metallic = m + end + local r = num(value("roughness")) + if r then + mat.roughness = r + end + local mt = tex("metallic") + local rt = tex("roughness") + if rt or mt then + mat.metallicRoughnessTexture = rt or mt + if mt then + mat.metallic = 1 + end + if rt then + mat.roughness = 1 + end + end + local e = nums(value("emissiveColor")) + if e and #e >= 3 then + mat.emissive = { e[1], e[2], e[3] } + end + local et = tex("emissiveColor") + if et then + mat.emissiveTexture = et + mat.emissive = { 1, 1, 1 } + end + local nt = tex("normal") + if nt then + mat.normalTexture = nt + end + local oc = tex("occlusion") + if oc then + mat.occlusionTexture = oc + end + local ext: { [string]: any } = {} + local ior = num(value("ior")) + if ior and ior ~= 1.5 then + ext.KHR_materials_ior = { ior = ior } + end + local cc = num(value("clearcoat")) + if cc and cc > 0 then + ext.KHR_materials_clearcoat = { clearcoatFactor = cc, clearcoatRoughnessFactor = num(value("clearcoatRoughness")) or 0.01 } + end + if next(ext) then + mat.extensions = ext + end + local usd: any = (mat.extras :: any).usd + if num(value("useSpecularWorkflow")) == 1 then + usd.useSpecularWorkflow = true + usd.specularColor = nums(value("specularColor")) + end + elseif shader then + unsupported["shader " .. (shaderId(shader :: Prim) or "?")] = true + end + table.insert(scene.materials, mat) + materialIndex[path] = #scene.materials + return #scene.materials + end + + -- the bound material of a prim (material:binding, inherited from ancestors) + local function binding(prim: Prim, path: string): number? + local p: Prim? = prim + local pp = path + while p do + local rel = p.props["material:binding"] or p.props["material:binding:preview"] or p.props["material:binding:full"] + if rel and rel.value and #rel.value > 0 then + return material(resolvePath(pp, rel.value[1])) + end + if pp == "/" then + break + end + pp = parentOf[p :: Prim] or "/" + p = byPath[pp] + end + return nil + end + + local colorMaterials: { [string]: number } = {} + local function colorMaterial(c: { number }): number + local key = string.format("%.6g,%.6g,%.6g,%.6g", c[1], c[2], c[3], c[4] or 1) + local mi = colorMaterials[key] + if not mi then + local mat = Types.Scene.material("displayColor") + mat.baseColor = { c[1], c[2], c[3], c[4] or 1 } + mat.metallic = 0 + mat.roughness = 0.5 + if (c[4] or 1) < 1 then + mat.alphaMode = "blend" + end + mat.extras = { usd = { displayColor = true } } + table.insert(scene.materials, mat) + mi = #scene.materials + colorMaterials[key] = mi + end + return mi :: number + end + + -- --------------------------------------------------------------------------------------------- meshes + type Primvar = { data: { number }, w: number, interp: string, idx: { number }? } + local function primvar(p: Prop?, defaultInterp: string): Primvar? + if not p then + return nil + end + local v = propValue(p) + if not isArr(v) then + return nil + end + local interp = defaultInterp + if p.meta and str(p.meta.interpolation) then + interp = str(p.meta.interpolation) :: string + end + return { data = v.v, w = v.w, interp = interp } + end + + local function buildMesh(prim: Prim, path: string): (Types.Mesh?, string?) + local pts = propValue(prim.props.points) + local cnt = propValue(prim.props.faceVertexCounts) + local idx = propValue(prim.props.faceVertexIndices) + if not isArr(pts) or pts.w ~= 3 then + return nil, nil + end + local points: { number } = pts.v + local npts = #points // 3 + local counts: { number } = if isArr(cnt) then cnt.v else {} + local indices: { number } = if isArr(idx) then idx.v else {} + local nfaces = #counts + local ncorners = 0 + for f = 1, nfaces do + local c = counts[f] + if c < 0 or c ~= c // 1 then + return nil, "bad faceVertexCounts at " .. path + end + ncorners += c + end + if ncorners ~= #indices then + return nil, "faceVertexCounts and faceVertexIndices disagree at " .. path + end + if ncorners > maxVertices or npts > maxVertices then + return nil, "LIMIT" + end + for k = 1, ncorners do + local v = indices[k] + if v < 0 or v >= npts or v ~= v // 1 then + return nil, "a face vertex index out of range at " .. path + end + end + local faceStart = table.create(nfaces + 1, 0) + do + local acc = 0 + for f = 1, nfaces do + faceStart[f] = acc + acc += counts[f] + end + faceStart[nfaces + 1] = acc + end + -- primvars, validated + local function sizeOk(pv: Primvar): boolean + local n = (if pv.idx then #pv.idx else #pv.data // pv.w) + local want = if pv.interp == "constant" then 1 + elseif pv.interp == "uniform" then nfaces + elseif pv.interp == "faceVarying" then ncorners + else npts + if n < want then + return false + end + if pv.idx then + local m = #pv.data // pv.w + for _, k in pv.idx :: { number } do + if k < 0 or k >= m or k ~= k // 1 then + return false + end + end + end + return #pv.data % pv.w == 0 + end + local function withIndices(pv: Primvar?, name: string): Primvar? + if not pv then + return nil + end + local ip = propValue(prim.props[name .. ":indices"]) + if isArr(ip) and ip.w == 1 then + pv.idx = ip.v + end + if not sizeOk(pv) then + unsupported["mismatched primvar " .. name] = true + return nil + end + return pv + end + local normals = withIndices(primvar(prim.props["primvars:normals"], "vertex"), "primvars:normals") + or withIndices(primvar(prim.props.normals, "vertex"), "normals") + if normals and normals.w ~= 3 then + normals = nil + end + local color = withIndices(primvar(prim.props["primvars:displayColor"], "constant"), "primvars:displayColor") + if color and color.w ~= 3 then + color = nil + end + local opacity = withIndices(primvar(prim.props["primvars:displayOpacity"], "constant"), "primvars:displayOpacity") + if opacity and opacity.w ~= 1 then + opacity = nil + end + local uvs: { [number]: Primvar } = {} + for pn, pr in prim.props do + local nm = string.match(pn, "^primvars:([^:]+)$") + if nm and pr.array and (pr.typeName == "texCoord2f" or pr.typeName == "float2" or pr.typeName == "texCoord2d" or pr.typeName == "double2" or pr.typeName == "texCoord2h" or pr.typeName == "half2") then + local pv = withIndices(primvar(pr, "vertex"), pn) + if pv and pv.w == 2 then + uvs[texCoordFor(nm)] = pv + end + end + end + -- the value of a primvar for (point, face, corner) (0-based), component c + local function get(pv: Primvar, point: number, face: number, corner: number, c: number): number + local e = if pv.interp == "constant" then 0 + elseif pv.interp == "uniform" then face + elseif pv.interp == "faceVarying" then corner + else point + if pv.idx then + e = (pv.idx :: { number })[e + 1] + end + return pv.data[e * pv.w + c + 1] or 0 + end + local perCorner = false + for _, pv in { normals, color, opacity } do + if pv and (pv.interp == "faceVarying" or pv.interp == "uniform") then + perCorner = true + end + end + for _, pv in uvs do + if pv.interp == "faceVarying" or pv.interp == "uniform" then + perCorner = true + end + end + local leftHanded = str(propValue(prim.props.orientation)) == "leftHanded" + -- holes + local hole: { [number]: boolean } = {} + local hv = propValue(prim.props.holeIndices) + if isArr(hv) then + for _, f in hv.v do + hole[f] = true + end + end + -- face sets: GeomSubsets ("face" elements), the rest + local meshMaterial = binding(prim, path) + local constantColor: { number }? = nil + if color and color.interp == "constant" then + constantColor = { get(color, 0, 0, 0, 0), get(color, 0, 0, 0, 1), get(color, 0, 0, 0, 2), if opacity and opacity.interp == "constant" then get(opacity, 0, 0, 0, 0) else 1 } + end + type Set = { faces: { number }, material: number?, name: string? } + local sets: { Set } = {} + local used: { [number]: boolean } = {} + for _, c in prim.children do + if c.typeName == "GeomSubset" and c.specifier ~= "class" then + local et = str(propValue(c.props.elementType)) or "face" + local fi = propValue(c.props.indices) + if et == "face" and isArr(fi) then + local faces = {} + for _, f in fi.v do + if f >= 0 and f < nfaces and f == f // 1 and not used[f] then + used[f] = true + table.insert(faces, f) + end + end + table.sort(faces) + local cpath = joinPath(path, c.name) + local rel = c.props["material:binding"] or c.props["material:binding:preview"] + local mi = if rel and rel.value and #rel.value > 0 then material(resolvePath(cpath, rel.value[1])) else meshMaterial + table.insert(sets, { faces = faces, material = mi, name = c.name }) + end + end + end + do + local rest = {} + for f = 0, nfaces - 1 do + if not used[f] then + table.insert(rest, f) + end + end + if #rest > 0 or #sets == 0 then + table.insert(sets, 1, { faces = rest, material = meshMaterial }) + end + end + local mesh: Types.Mesh = { name = prim.name, primitives = {} } + for _, set in sets do + -- vertices: one per point (vertex-rate data) or per corner + local keyToVert: { [number]: number } = {} + local vp, vf, vc = {}, {}, {} -- point, face, corner per new vertex (0-based) + local nv = 0 + local out: { number } = {} + local faceSizes: { number } = {} + for _, f in set.faces do + local cnt0 = counts[f + 1] + if cnt0 >= 3 and not hole[f] then + local base = faceStart[f + 1] + local verts = table.create(cnt0) + for k = 0, cnt0 - 1 do + local corner = base + k + local point = indices[corner + 1] + local key = if perCorner then corner else point + local v = keyToVert[key] + if not v then + v = nv + keyToVert[key] = v + nv += 1 + vp[nv], vf[nv], vc[nv] = point, f, corner + end + verts[k + 1] = v + end + if leftHanded then + local r = table.create(cnt0) + for k = 1, cnt0 do + r[k] = verts[cnt0 - k + 1] + end + verts = r + end + if triangulate then + for k = 2, cnt0 - 1 do + table.insert(out, verts[1]) + table.insert(out, verts[k]) + table.insert(out, verts[k + 1]) + end + else + for k = 1, cnt0 do + table.insert(out, verts[k]) + end + table.insert(faceSizes, cnt0) + end + end + end + if nv > 0 then + local attrs: { [string]: Types.Accessor } = {} + local pos = Types.Scene.accessor(nil, "f32", 3, nv) + for v = 1, nv do + local p0 = vp[v] * 3 + buffer.writef32(pos.data, (v - 1) * 12, points[p0 + 1]) + buffer.writef32(pos.data, (v - 1) * 12 + 4, points[p0 + 2]) + buffer.writef32(pos.data, (v - 1) * 12 + 8, points[p0 + 3]) + end + attrs.POSITION = pos + local function fill(pv: Primvar, comps: number, flip: boolean): Types.Accessor + local a = Types.Scene.accessor(nil, "f32", comps, nv) + for v = 1, nv do + for c = 0, comps - 1 do + local x = get(pv, vp[v], vf[v], vc[v], c) + if flip and c == 1 then + x = 1 - x + end + buffer.writef32(a.data, ((v - 1) * comps + c) * 4, x) + end + end + return a + end + if normals then + local nrm = fill(normals, 3, false) + if leftHanded then + -- normals follow the authored (left-handed) winding: keep them as authored + end + attrs.NORMAL = nrm + end + for k, pv in uvs do + attrs["TEXCOORD_" .. k] = fill(pv, 2, flipV) + end + local mi = set.material + if color and not constantColor then + -- varying colours -> COLOR_0 (rgb, or rgba with displayOpacity) + if opacity then + local a = Types.Scene.accessor(nil, "f32", 4, nv) + for v = 1, nv do + for c = 0, 2 do + buffer.writef32(a.data, ((v - 1) * 4 + c) * 4, get(color, vp[v], vf[v], vc[v], c)) + end + buffer.writef32(a.data, ((v - 1) * 4 + 3) * 4, get(opacity, vp[v], vf[v], vc[v], 0)) + end + attrs.COLOR_0 = a + else + attrs.COLOR_0 = fill(color, 3, false) + end + elseif constantColor and mi == nil then + mi = colorMaterial(constantColor) + end + local ind = Types.Scene.accessor(nil, "u32", 1, #out) + for k, v in out do + buffer.writeu32(ind.data, (k - 1) * 4, v) + end + local prm: Types.Primitive = { attributes = attrs, indices = ind, mode = if triangulate then "triangles" else "polygons", material = mi } + if not triangulate then + local fa = Types.Scene.accessor(nil, "u32", 1, #faceSizes) + for k, v in faceSizes do + buffer.writeu32(fa.data, (k - 1) * 4, v) + end + prm.faces = fa + end + if set.name then + prm.extras = { usd = { subset = set.name } } + end + local ds = propValue(prim.props.doubleSided) + if mi and (ds == 1 or ds == true) then + local m = mi and scene.materials[mi] + if m then + m.doubleSided = true + end + end + table.insert(mesh.primitives, prm) + end + end + if #mesh.primitives == 0 then + return nil, nil + end + return mesh, nil + end + + -- --------------------------------------------------------------------------------------------- cameras / lights + local function camera(prim: Prim): Types.Camera + local function f(name: string, d: number): number + return num(propValue(prim.props[name])) or d + end + local focal = f("focalLength", 50) + local hap = f("horizontalAperture", 20.955) + local vap = f("verticalAperture", 15.2908) + local clip = nums(propValue(prim.props.clippingRange)) or { 1, 1000000 } + local proj = str(propValue(prim.props.projection)) or "perspective" + if proj == "orthographic" then + return { name = prim.name, type = "orthographic", xmag = hap / 20, ymag = vap / 20, znear = clip[1] or 1, zfar = clip[2] or 1000000 } + end + return { + name = prim.name, + type = "perspective", + yfov = 2 * math.atan(vap / (2 * focal)), + aspect = if vap > 0 then hap / vap else nil, + znear = clip[1] or 1, + zfar = clip[2], + } + end + local function light(prim: Prim): Types.Light + local function f(name: string, d: number): number + return num(propValue(prim.props["inputs:" .. name])) or num(propValue(prim.props[name])) or d + end + local col = nums(propValue(prim.props["inputs:color"])) or nums(propValue(prim.props.color)) or { 1, 1, 1 } + local intensity = f("intensity", 1) * 2 ^ f("exposure", 0) + local l: Types.Light = { name = prim.name, type = "point", color = { col[1] or 1, col[2] or 1, col[3] or 1 }, intensity = intensity } + local t = prim.typeName + local cone = num(propValue(prim.props["inputs:shaping:cone:angle"])) or num(propValue(prim.props["shaping:cone:angle"])) + if t == "DistantLight" then + l.type = "directional" + elseif t == "RectLight" or t == "DiskLight" then + l.type = "spot" + l.outerCone = math.pi / 2 + l.innerCone = 0 + end + if cone and cone < 90 then + local soft = num(propValue(prim.props["inputs:shaping:cone:softness"])) or 0 + l.type = "spot" + l.outerCone = cone * DEG + l.innerCone = math.max(0, cone * DEG * (1 - soft)) + end + return l + end + + -- --------------------------------------------------------------------------------------------- nodes + local tcps = num(meta.timeCodesPerSecond) or num(meta.framesPerSecond) or 24 + if tcps <= 0 then + tcps = 24 + end + local animation: Types.Animation = { name = "usd", channels = {} } + local failure: string? = nil + + local function isNode(p: Prim): boolean + -- class prims are abstract; an over with no def is not defined (UsdStage traversal skips both) + if p.specifier == "class" or p.specifier == "over" or NOT_NODES[p.typeName or ""] then + if SKEL[p.typeName or ""] then + unsupported["UsdSkel (skeletons, skinning, blend shapes)"] = true + end + return false + end + if p.typeName == "Scope" or p.typeName == nil then + -- scopes / untyped prims holding only materials are not nodes + local function hasContent(q: Prim, d: number): boolean + if d > 100 then + return false + end + for _, c in q.children do + if c.specifier ~= "class" and not NOT_NODES[c.typeName or ""] then + if c.typeName ~= nil and c.typeName ~= "Scope" then + return true + end + if hasContent(c, d + 1) then + return true + end + end + end + return false + end + if p.typeName == "Scope" or #p.children > 0 then + return hasContent(p, 0) + end + end + return true + end + + local function node(p: Prim, path: string, parent: number?, depth: number) + if depth > 200 or failure then + return + end + if not isNode(p) then + return + end + local n: Types.Node = { name = p.name, children = {}, extras = { usd = { path = path, type = p.typeName } } } + table.insert(scene.nodes, n) + local ni = #scene.nodes + local ops, reset = xformOps(p) + -- animated ops: the local matrix at the union of their time codes + local times: { number } = {} + do + local seen: { [number]: boolean } = {} + for _, op in ops do + local s = op.prop.samples + if s and #s.times > 1 then + for _, t in s.times do + if not seen[t] then + seen[t] = true + table.insert(times, t) + end + end + end + end + table.sort(times) + end + if #times > 1 then + local count = math.min(#times, 100000) + local tin = Types.Scene.accessor(nil, "f32", 1, count) + local tr = Types.Scene.accessor(nil, "f32", 3, count) + local ro = Types.Scene.accessor(nil, "f32", 4, count) + local sc = Types.Scene.accessor(nil, "f32", 3, count) + local prev: { number }? = nil + for k = 1, count do + local T, R, S = decompose(localMatrix(ops, times[k])) + if prev and prev[1] * R[1] + prev[2] * R[2] + prev[3] * R[3] + prev[4] * R[4] < 0 then + R = { -R[1], -R[2], -R[3], -R[4] } + end + prev = R + buffer.writef32(tin.data, (k - 1) * 4, times[k] / tcps) + for c = 0, 2 do + buffer.writef32(tr.data, ((k - 1) * 3 + c) * 4, T[c + 1]) + buffer.writef32(sc.data, ((k - 1) * 3 + c) * 4, S[c + 1]) + end + for c = 0, 3 do + buffer.writef32(ro.data, ((k - 1) * 4 + c) * 4, R[c + 1]) + end + end + table.insert(animation.channels, { node = ni, path = "translation", input = tin, output = tr, interpolation = "LINEAR" }) + table.insert(animation.channels, { node = ni, path = "rotation", input = tin, output = ro, interpolation = "LINEAR" }) + table.insert(animation.channels, { node = ni, path = "scale", input = tin, output = sc, interpolation = "LINEAR" }) + local T, R, S = decompose(localMatrix(ops, times[1])) + n.translation, n.rotation, n.scale = T, R, S + elseif #ops > 0 then + -- static: TRS when the stack is translate / rotate / scale in that order, else the matrix + local simple = true + local stage = 0 + for _, op in ops do + local st = if op.kind == "translate" then 1 elseif op.kind == "rotate" or op.kind == "orient" then 2 elseif op.kind == "scale" then 3 else 9 + if op.invert or st == 9 or st <= stage or string.find(op.prop.name, "^xformOp:%a+:") then + simple = false + end + stage = st + end + local m = localMatrix(ops, nil) + if simple then + local T, R, S = decompose(m) + local tx = ops[1].kind == "translate" + if tx then + n.translation = T + end + for _, op in ops do + if op.kind == "rotate" or op.kind == "orient" then + n.rotation = R + elseif op.kind == "scale" then + n.scale = S + end + end + -- a negative scale with a rotation is not TRS-representable through decompose: keep the matrix + local back = Types.Scene.nodeMatrix(n) + for k = 1, 16 do + if math.abs(back[k] - m[k]) > 1e-5 * math.max(1, math.abs(m[k])) then + simple = false + break + end + end + if not simple then + n.translation, n.rotation, n.scale = nil, nil, nil + end + end + if not simple then + local identity = true + for k = 1, 16 do + if m[k] ~= Types.Scene.IDENTITY[k] then + identity = false + end + end + if not identity then + n.matrix = m + end + end + end + if reset or parent == nil then + table.insert(scene.roots, ni) + if reset and parent then + (n.extras :: any).usd.resetXformStack = true + end + else + table.insert(scene.nodes[parent].children, ni) + end + local t = p.typeName + if t == "Mesh" then + local mesh, err = buildMesh(p, path) + if err == "LIMIT" then + failure = "LIMIT" + return + elseif err then + failure = err + return + end + if mesh then + table.insert(scene.meshes, mesh) + n.mesh = #scene.meshes + end + elseif t == "Camera" then + table.insert(scene.cameras, camera(p)) + n.camera = #scene.cameras + elseif t and LIGHTS[t] and t ~= "DomeLight" then + table.insert(scene.lights, light(p)) + n.light = #scene.lights + elseif t and t ~= "Xform" and t ~= "Scope" and t ~= "Mesh" and t ~= "DomeLight" and t ~= "SkelRoot" then + unsupported["prim type " .. t] = true + end + for _, c in p.children do + node(c, joinPath(path, c.name), ni, depth + 1) + end + end + + for _, p in layer.prims do + if p.specifier ~= "class" then + node(p, "/" .. p.name, nil, 1) + end + end + if failure then + return nil, failure + end + if #animation.channels > 0 then + table.insert(scene.animations, animation) + end + + -- stage metadata + local up = str(meta.upAxis) + scene.meta.up = if up == "Z" then "z" else "y" + local mpu = num(meta.metersPerUnit) + if mpu and mpu > 0 then + scene.meta.unit = mpu + end + local list = {} + for k in unsupported do + table.insert(list, k) + end + table.sort(list) + scene.meta.source = { + format = "usda", + defaultPrim = str(meta.defaultPrim), + timeCodesPerSecond = tcps, + startTimeCode = num(meta.startTimeCode), + endTimeCode = num(meta.endTimeCode), + doc = str(meta.doc), + unsupported = if #list > 0 then list else nil, + } + return scene, nil +end + +return Build diff --git a/src/Formats/model/usda/Parse.luau b/src/Formats/model/usda/Parse.luau new file mode 100644 index 0000000..99b38e1 --- /dev/null +++ b/src/Formats/model/usda/Parse.luau @@ -0,0 +1,820 @@ +--!strict +-- model/usda/Parse: USD ASCII (Sdf text format, "#usda 1.0") -> a layer of prim specs. New code, from the Sdf text +-- grammar as Pixar's USD writes and reads it: layer metadata, def / over / class prims with metadata, attributes +-- (custom / uniform / varying / config, scalar and array types, defaults, .timeSamples, .connect, metadata), relationships, +-- list ops (prepend / append / add / delete / reorder), variant sets, dictionaries, strings ("", '', triple quoted), +-- asset paths (@...@, @@@...@@@), paths (<...>), comments (#, //, /* */). Numeric arrays (points, indices) take a fast +-- path into flat number arrays. .spline blocks and unknown constructs are skipped by bracket matching. +-- Errors raise a table { usda = message, at = byte offset } inside this module; Parse.layer catches them (pcall) and +-- returns nil, message, offset - nothing escapes. +local Parse = {} + +-- values: numbers, booleans, strings, and these tagged tables +export type Arr = { t: "arr", w: number, v: { number } } -- numeric array, w numbers per element (tuples flattened) +export type Value = any + +export type Prop = { + name: string, + rel: boolean, -- a relationship + typeName: string?, -- "point3f", "token", ... (attributes) + array: boolean?, + uniform: boolean?, + custom: boolean?, + value: Value?, -- the default value (attributes) or the targets (relationships: { path strings }) + hasValue: boolean?, + samples: { times: { number }, values: { Value } }?, + connect: { string }?, -- connection target paths (attributes) + meta: { [string]: Value }?, +} +export type Prim = { + specifier: string, -- "def" | "over" | "class" + typeName: string?, + name: string, + meta: { [string]: Value }, + props: { [string]: Prop }, + order: { string }, -- property names in file order + children: { Prim }, + variantSets: { [string]: { [string]: Prim } }?, -- set -> variant -> a prim body (props / children) +} +export type Layer = { meta: { [string]: Value }, prims: { Prim } } + +local NONE = table.freeze({ t = "none" }) +Parse.NONE = NONE + +local sfind, ssub, sbyte, smatch, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch + +local LISTOPS = { prepend = true, append = true, add = true, delete = true, reorder = true } +local VARIABILITY = { uniform = true, varying = true, config = true } +local MAX_DEPTH = 200 + +local function fail(msg: string, at: number): never + error({ usda = msg, at = at }, 0) +end + +-- the parser over one text; positions are 1-based string indices +local function parser(s: string, maxBytes: number) + local n = #s + local depth = 0 + + -- whitespace and comments (newlines included) + local function ws(i: number): number + while true do + local _, e = sfind(s, "^[ \t\r\n]+", i) + if e then + i = e + 1 + end + local c = sbyte(s, i) + if c == 35 then -- # + local nl = sfind(s, "\n", i, true) + i = if nl then nl + 1 else n + 1 + elseif c == 47 and sbyte(s, i + 1) == 47 then -- // + local nl = sfind(s, "\n", i, true) + i = if nl then nl + 1 else n + 1 + elseif c == 47 and sbyte(s, i + 1) == 42 then -- /* */ + local _, ce = sfind(s, "*/", i + 2, true) + if not ce then + fail("unterminated comment", i) + end + i = (ce :: number) + 1 + else + return i + end + end + end + + local function expect(i: number, ch: string): number + i = ws(i) + if ssub(s, i, i) ~= ch then + fail("expected '" .. ch .. "'", i) + end + return i + 1 + end + + local function ident(i: number): (string?, number) + local a, e = sfind(s, "^[%a_][%w_:]*", i) + if not a then + return nil, i + end + return ssub(s, a, e), (e :: number) + 1 + end + + local ESC = { n = "\n", t = "\t", r = "\r", ["\\"] = "\\", ['"'] = '"', ["'"] = "'", ["0"] = "\0", a = "\a", b = "\b", f = "\f", v = "\v" } + local function unescape(str: string): string + if not sfind(str, "\\", 1, true) then + return str + end + return (string.gsub(str, "\\(x?)(.)", function(x: string, c: string): string + if x == "x" then + return "\\x" .. c -- left alone (rare) + end + return ESC[c] or c + end)) + end + + local function str(i: number): (string, number) + local q = ssub(s, i, i) + if ssub(s, i, i + 2) == q .. q .. q then + local e = sfind(s, q .. q .. q, i + 3, true) + if not e then + fail("unterminated string", i) + end + return unescape(ssub(s, i + 3, (e :: number) - 1)), (e :: number) + 3 + end + local j = i + 1 + while true do + local a = sfind(s, "[\\\n" .. q .. "]", j) + if not a then + fail("unterminated string", i) + end + local c = sbyte(s, a :: number) + if c == 92 then + j = (a :: number) + 2 + elseif c == 10 then + fail("newline in string", a :: number) + else + return unescape(ssub(s, i + 1, (a :: number) - 1)), (a :: number) + 1 + end + end + end + + local function number(i: number): (number?, number) + local a, e = sfind(s, "^[-+]?%d*%.?%d*[eE][-+]?%d+", i) + if not a then + a, e = sfind(s, "^[-+]?%d*%.?%d*", i) + end + if a and (e :: number) >= (a :: number) then + local v = tonumber(ssub(s, a, e)) + if v then + return v, (e :: number) + 1 + end + end + -- inf / -inf / nan + local w, e2 = sfind(s, "^[-+]?%a+", i) + if w then + local word = string.lower(ssub(s, w, e2)) + if word == "inf" or word == "+inf" then + return math.huge, (e2 :: number) + 1 + elseif word == "-inf" then + return -math.huge, (e2 :: number) + 1 + elseif word == "nan" or word == "-nan" or word == "+nan" then + return 0 / 0, (e2 :: number) + 1 + end + end + return nil, i + end + + -- skip a balanced (), [], {} block starting at i (strings and comments respected) + local function skipBalanced(i: number): number + local open = sbyte(s, i) + local level = 0 + while i <= n do + i = ws(i) + local c = sbyte(s, i) + if c == nil then + break + end + if c == 40 or c == 91 or c == 123 then + level += 1 + i += 1 + elseif c == 41 or c == 93 or c == 125 then + level -= 1 + i += 1 + if level == 0 then + return i + end + elseif c == 34 or c == 39 then + local _, j = str(i) + i = j + elseif c == 64 then + local e = sfind(s, "@", i + 1, true) + i = if e then e + 1 else n + 1 + elseif c == 60 then + local e = sfind(s, ">", i + 1, true) + i = if e then e + 1 else n + 1 + else + local _, e = sfind(s, "^[^%(%)%[%]{}\"'@<#/ \t\r\n]+", i) + i = if e then e + 1 else i + 1 + end + end + fail("unbalanced " .. string.char(open or 63), i) + end + + local value: (i: number) -> (Value, number) + local metadata: (i: number) -> ({ [string]: Value }, number) + + -- [ ... ]: the fast path for numeric arrays (flat numbers + tuple width), else a generic list + local function list(i: number): (Value, number) + local close = sfind(s, "]", i + 1, true) + if close then + local body = ssub(s, i + 1, close - 1) + if not sfind(body, "[^%d%s%.,eE%-%+%(%)]") then + local first = smatch(body, "^%s*%(([^%)]*)%)") + local w = 1 + if first then + w = 0 + for _ in gmatch(first, "[^%s,]+") do + w += 1 + end + elseif sfind(body, "[%(%)]") then + w = -1 -- nested tuples: the generic path + end + if w > 0 then + local out: { number } = {} + local k = 0 + local ok = true + for tok in gmatch(body, "[^%s,%(%)]+") do + local v = tonumber(tok) + if not v then + ok = false + break + end + k += 1 + out[k] = v + end + if ok and k % w == 0 then + if k * 8 > maxBytes then + fail("array over the size limit", i) + end + return { t = "arr", w = w, v = out } :: Arr, close + 1 + end + end + end + end + -- generic + local items = {} + i += 1 + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "]" then + i += 1 + break + elseif c == "" then + fail("unterminated list", i) + end + local v + v, i = value(i) + table.insert(items, v) + i = ws(i) + if ssub(s, i, i) == "(" then -- per-item metadata (subLayers offsets, ...) + local _ + _, i = metadata(i) + i = ws(i) + end + c = ssub(s, i, i) + if c == "," then + i += 1 + elseif c ~= "]" then + fail("expected ',' or ']' in a list", i) + end + end + -- all numbers, or all equal-width numeric tuples -> arr + local w: number? = nil + local flat: { number } = {} + for _, it in items do + if type(it) == "number" then + if w and w ~= 1 then + return { t = "list", v = items }, i + end + w = 1 + table.insert(flat, it) + elseif type(it) == "table" and it.t == "tuple" then + local tw = #it.v + if (w and w ~= tw) or tw == 0 then + return { t = "list", v = items }, i + end + w = tw + for _, x in it.v do + if type(x) ~= "number" then + return { t = "list", v = items }, i + end + table.insert(flat, x) + end + else + return { t = "list", v = items }, i + end + end + if w == nil then + return { t = "list", v = items }, i + end + return { t = "arr", w = w, v = flat } :: Arr, i + end + + local function tuple(i: number): (Value, number) + local items = {} + i += 1 + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == ")" then + i += 1 + break + elseif c == "" then + fail("unterminated tuple", i) + end + local v + v, i = value(i) + table.insert(items, v) + i = ws(i) + c = ssub(s, i, i) + if c == "," then + i += 1 + elseif c ~= ")" then + fail("expected ',' or ')' in a tuple", i) + end + end + return { t = "tuple", v = items }, i + end + + -- { type key = value ... } (metadata dictionaries) + local function dict(i: number): (Value, number) + local out: { [string]: Value } = {} + i += 1 + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + i += 1 + break + elseif c == "" then + fail("unterminated dictionary", i) + elseif c == ";" or c == "," then + i += 1 + continue + end + local ty + ty, i = ident(i) + if not ty then + fail("expected a type in a dictionary", i) + end + i = ws(i) + if ssub(s, i, i + 1) == "[]" then + i += 2 + end + i = ws(i) + local key: string? + c = ssub(s, i, i) + if c == '"' or c == "'" then + key, i = str(i) + else + key, i = ident(i) + end + if not key then + fail("expected a key in a dictionary", i) + end + i = expect(i, "=") + local v + v, i = value(i) + out[key :: string] = v + end + return { t = "dict", v = out }, i + end + + function value(i: number): (Value, number) + depth += 1 + if depth > MAX_DEPTH then + fail("nesting too deep", i) + end + i = ws(i) + local c = ssub(s, i, i) + local v: Value + if c == "[" then + v, i = list(i) + elseif c == "(" then + v, i = tuple(i) + elseif c == "{" then + v, i = dict(i) + elseif c == '"' or c == "'" then + v, i = str(i) + elseif c == "@" then + local path + if ssub(s, i, i + 2) == "@@@" then + local e = sfind(s, "@@@", i + 3, true) + if not e then + fail("unterminated asset path", i) + end + path, i = ssub(s, i + 3, (e :: number) - 1), (e :: number) + 3 + else + local e = sfind(s, "@", i + 1, true) + if not e then + fail("unterminated asset path", i) + end + path, i = ssub(s, i + 1, (e :: number) - 1), (e :: number) + 1 + end + local a: { [string]: any } = { t = "asset", v = path } + local j = ws(i) + if ssub(s, j, j) == "<" then -- references = @file@ + local e = sfind(s, ">", j + 1, true) + if not e then + fail("unterminated path", j) + end + a.path = ssub(s, j + 1, (e :: number) - 1) + i = (e :: number) + 1 + end + v = a + elseif c == "<" then + local e = sfind(s, ">", i + 1, true) + if not e then + fail("unterminated path", i) + end + v, i = { t = "path", v = ssub(s, i + 1, (e :: number) - 1) }, (e :: number) + 1 + else + local num, j = number(i) + if num ~= nil then + v, i = num, j + else + local id + id, j = ident(i) + if not id then + fail("expected a value", i) + end + i = j + if id == "None" then + v = NONE + elseif id == "true" then + v = true + elseif id == "false" then + v = false + else + v = { t = "id", v = id } + end + end + end + depth -= 1 + return v, i + end + + -- ( key = value ; "doc" ; prepend key = value ... ) + function metadata(i: number): ({ [string]: Value }, number) + local out: { [string]: Value } = {} + i = expect(i, "(") + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == ")" then + return out, i + 1 + elseif c == "" then + fail("unterminated metadata", i) + elseif c == ";" or c == "," then + i += 1 + continue + elseif c == '"' or c == "'" then + out.doc, i = str(i) + continue + end + local key + key, i = ident(i) + if not key then + fail("expected a metadata key", i) + end + local op: string? = nil + if LISTOPS[key] then + op = key + i = ws(i) + key, i = ident(i) + if not key then + fail("expected a metadata key", i) + end + end + i = ws(i) + if ssub(s, i, i) == "=" then + local v + v, i = value(i + 1) + if op == "delete" then + -- deletions only matter for composition + elseif op and op ~= "reorder" then + -- prepend / append / add: merge into one list + local prev = out[key :: string] + if type(prev) == "table" and prev.t == "list" and type(v) == "table" and v.t == "list" then + for _, x in v.v do + table.insert(prev.v, x) + end + else + out[key :: string] = v + end + else + out[key :: string] = v + end + end + end + end + + -- time samples: { time: value, ... } + local function samples(i: number): ({ times: { number }, values: { Value } }, number) + local times, values = {}, {} + i = expect(i, "{") + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + i += 1 + break + elseif c == "" then + fail("unterminated time samples", i) + elseif c == "," then + i += 1 + continue + end + local t + t, i = number(i) + if t == nil then + fail("expected a time code", i) + end + i = expect(i, ":") + local v + v, i = value(i) + table.insert(times, t) + table.insert(values, v) + end + return { times = times, values = values }, i + end + + local function targets(v: Value): { string } + local out = {} + if type(v) == "table" then + if v.t == "path" then + table.insert(out, v.v) + elseif v.t == "list" then + for _, x in v.v do + if type(x) == "table" and x.t == "path" then + table.insert(out, x.v) + end + end + end + end + return out + end + + local primBody: (i: number, prim: Prim) -> number + + local function newPrim(specifier: string, typeName: string?, name: string): Prim + return { specifier = specifier, typeName = typeName, name = name, meta = {}, props = {}, order = {}, children = {} } + end + + -- def Type "name" ( meta ) { body } + local function prim(i: number, specifier: string): (Prim, number) + i = ws(i) + local typeName: string? = nil + local c = ssub(s, i, i) + if c ~= '"' and c ~= "'" then + typeName, i = ident(i) + if not typeName then + fail("expected a prim type or name", i) + end + i = ws(i) + -- dotted schema names (rare) + while ssub(s, i, i) == "." do + local more + more, i = ident(i + 1) + typeName = (typeName :: string) .. "." .. (more or "") + end + i = ws(i) + end + c = ssub(s, i, i) + if c ~= '"' and c ~= "'" then + fail("expected a prim name", i) + end + local name + name, i = str(i) + local p = newPrim(specifier, typeName, name) + i = ws(i) + if ssub(s, i, i) == "(" then + p.meta, i = metadata(i) + end + i = expect(i, "{") + i = primBody(i, p) + return p, i + end + + -- variantSet "name" = { "variant" ( meta ) { body } ... } + local function variantSet(i: number, p: Prim): number + i = ws(i) + local setName + setName, i = str(i) + i = expect(i, "=") + i = expect(i, "{") + local sets = p.variantSets or {} + p.variantSets = sets + local set = sets[setName] or {} + sets[setName] = set + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + return i + 1 + elseif c ~= '"' and c ~= "'" then + fail("expected a variant name", i) + end + local vname + vname, i = str(i) + local body = newPrim("def", nil, vname) + i = ws(i) + if ssub(s, i, i) == "(" then + body.meta, i = metadata(i) + end + i = expect(i, "{") + i = primBody(i, body) + set[vname] = body + end + end + + -- one property: [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...] + local function property(i: number, first: string, p: Prim): number + local word: string? = first + local op: string? = nil + if LISTOPS[word :: string] then + op = word + i = ws(i) + word, i = ident(i) + end + local custom, uniform = false, false + if word == "custom" then + custom = true + i = ws(i) + word, i = ident(i) + end + if word and VARIABILITY[word] then + uniform = word == "uniform" + i = ws(i) + word, i = ident(i) + end + if not word then + fail("expected a property", i) + end + local isRel = word == "rel" + local typeName: string? = nil + local array = false + if not isRel then + typeName = word + i = ws(i) + if ssub(s, i, i + 1) == "[]" then + array = true + i += 2 + end + end + i = ws(i) + local name + name, i = ident(i) + if not name then + fail("expected a property name", i) + end + local suffix: string? = nil + if ssub(s, i, i) == "." then + suffix, i = ident(i + 1) + end + local prop = p.props[name :: string] + if not prop then + prop = { name = name :: string, rel = isRel } + p.props[name :: string] = prop + table.insert(p.order, name :: string) + end + local pr = prop :: Prop + if typeName then + pr.typeName, pr.array = typeName, array + end + pr.uniform = pr.uniform or uniform or nil + pr.custom = pr.custom or custom or nil + i = ws(i) + if ssub(s, i, i) == "=" then + i = ws(i + 1) + if suffix == "timeSamples" then + pr.samples, i = samples(i) + elseif suffix == "spline" or (suffix ~= nil and suffix ~= "connect" and suffix ~= "default" and ssub(s, i, i) == "{") then + i = skipBalanced(i) + else + local v + v, i = value(i) + if op == "delete" then + -- composition only + elseif suffix == "connect" then + pr.connect = targets(v) + elseif isRel then + pr.value = targets(v) + pr.hasValue = true + else + pr.value = v + pr.hasValue = true + end + end + end + i = ws(i) + if ssub(s, i, i) == "(" then + local m + m, i = metadata(i) + if pr.meta then + for k, v in m do + (pr.meta :: any)[k] = v + end + else + pr.meta = m + end + end + return i + end + + function primBody(i: number, p: Prim): number + depth += 1 + if depth > MAX_DEPTH then + fail("nesting too deep", i) + end + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + depth -= 1 + return i + 1 + elseif c == "" then + fail("unterminated prim", i) + elseif c == ";" then + i += 1 + continue + end + local word, j = ident(i) + if not word then + fail("unexpected character in a prim", i) + end + if word == "def" or word == "over" or word == "class" then + local child + child, i = prim(j, word) + table.insert(p.children, child) + elseif word == "variantSet" then + i = variantSet(j, p) + elseif word == "reorder" then + local k = ws(j) + local w2, k2 = ident(k) + if w2 == "nameChildren" or w2 == "properties" or w2 == "rootPrims" then + k2 = expect(k2, "=") + local _ + _, i = value(k2) + else + i = property(j, word, p) + end + else + i = property(j, word, p) + end + end + end + + -- the whole layer + local function layer(): Layer + local i = 1 + if ssub(s, 1, 3) == "\239\187\191" then + i = 4 + end + if ssub(s, i, i + 4) ~= "#usda" then + fail("not a USDA file (no #usda header)", i) + end + local nl = sfind(s, "\n", i, true) + i = if nl then nl + 1 else n + 1 + local out: Layer = { meta = {}, prims = {} } + i = ws(i) + if ssub(s, i, i) == "(" then + out.meta, i = metadata(i) + end + while true do + i = ws(i) + if i > n then + break + end + local word, j = ident(i) + if word == "def" or word == "over" or word == "class" then + local p + p, i = prim(j, word) + table.insert(out.prims, p) + elseif word == "reorder" then + j = ws(j) + local _ + _, j = ident(j) + j = expect(j, "=") + _, i = value(j) + elseif ssub(s, i, i) == ";" then + i += 1 + else + fail("expected def / over / class", i) + end + end + return out + end + + return layer +end + +-- layer(text, opts?) -> Layer | nil, message, offset (0-based) +function Parse.layer(text: string, maxBytes: number?): (Layer?, string?, number?) + local run = parser(text, maxBytes or 2 ^ 30) + local ok, res = pcall(run) + if ok then + return res, nil, nil + end + if type(res) == "table" and res.usda then + return nil, res.usda, math.max((res.at or 1) - 1, 0) + end + return nil, "parse error: " .. tostring(res), nil +end + +-- version(text) -> the "#usda " string +function Parse.version(text: string): string? + return smatch(text, "^\239?\187?\191?#usda%s+([%d%.]+)") +end + +return Parse diff --git a/src/Formats/model/usda/Write.luau b/src/Formats/model/usda/Write.luau new file mode 100644 index 0000000..a4e53f3 --- /dev/null +++ b/src/Formats/model/usda/Write.luau @@ -0,0 +1,840 @@ +--!strict +-- model/usda/Write: Scene -> USD ASCII text (UsdGeom / UsdShade / UsdLux). New code. +-- Layout: one root prim (the scene's single root node, else an Xform "root" holding every root) as the defaultPrim, +-- a "Looks" scope under it with the materials (UsdPreviewSurface + UsdUVTexture + UsdPrimvarReader_float2, texture +-- transforms as UsdTransform2d), and one prim per node: a node with a mesh is a Mesh prim (its primitives merged, a +-- GeomSubset per primitive when there are several), a node with only a camera / light is that Camera / light prim, +-- other nodes are Xforms (meshes / cameras / lights that cannot share the node's prim become children). Transforms are +-- translate / orient / scale ops (or a transform op for matrices); animation channels (translation / rotation / scale) +-- become time samples on those ops (timeCodesPerSecond 24). TEXCOORD_n -> primvars:st, st1, ... (v flipped back), +-- COLOR_0 -> displayColor (+ displayOpacity), NORMAL -> normals, all "vertex" interpolated. Textures: their uri, or the +-- embedded bytes written into opts.files as _.. Not written: skins, morph targets, weights animation, +-- lines / points primitives (counted in the returned notes). +local Types = require("@formats/Types") + +local Write = {} + +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif", ["image/bmp"] = "bmp", ["image/x-tga"] = "tga", ["image/gif"] = "gif", ["image/tiff"] = "tiff" } +local RAD = 180 / math.pi + +export type Options = { files: { [string]: any }?, name: string?, upAxis: string?, metersPerUnit: number? } + +-- ------------------------------------------------------------------------------------------------ text helpers +local function fmt(x: number): string + if x ~= x then + return "nan" + elseif x == math.huge then + return "inf" + elseif x == -math.huge then + return "-inf" + elseif x == math.floor(x) and math.abs(x) < 1e15 then + return string.format("%d", x) + end + return string.format("%.9g", x) +end +local function tuple(t: { number }): string + local parts = table.create(#t) + for k, v in t do + parts[k] = fmt(v) + end + return "(" .. table.concat(parts, ", ") .. ")" +end +local function quote(s: string): string + return '"' .. string.gsub(s, '[\\"\n]', { ["\\"] = "\\\\", ['"'] = '\\"', ["\n"] = "\\n" }) .. '"' +end +local function asset(s: string): string + if string.find(s, "@", 1, true) then + return "@@@" .. s .. "@@@" + end + return "@" .. s .. "@" +end +-- a valid, sibling-unique prim name +local function namer(): (string?, string) -> string + local used: { [string]: boolean } = {} + return function(name: string?, fallback: string): string + local n = string.gsub(name or "", "[^%w_]", "_") + if n == "" then + n = fallback + end + if string.find(n, "^%d") then + n = "_" .. n + end + local base, k = n, 1 + while used[n] do + k += 1 + n = base .. "_" .. k + end + used[n] = true + return n + end +end + +-- an accessor's elements as numbers (normalized types to floats) +local function values(acc: Types.Accessor?): ({ number }?, number) + if not acc then + return nil, 0 + end + local get = Types.Scene.reader(acc) + if not get then + return nil, 0 + end + local n, c = acc.count, acc.components + local out = table.create(n * c) + for i = 0, n - 1 do + for k = 0, c - 1 do + out[i * c + k + 1] = get(i, k) + end + end + return out, c +end + +-- array literal of tuples ("[(x, y, z), ...]") or scalars +local function arrayText(vals: { number }, width: number, stride: number?, count: number?, map: ((i: number, k: number, v: number) -> number)?): string + local st = stride or width + local n = count or (#vals // st) + local parts = table.create(n) + local buf = table.create(width) + for i = 0, n - 1 do + for k = 1, width do + local v = vals[i * st + k] or 0 + if map then + v = map(i, k, v) + end + buf[k] = fmt(v) + end + parts[i + 1] = if width == 1 then buf[1] else "(" .. table.concat(buf, ", ", 1, width) .. ")" + end + return "[" .. table.concat(parts, ", ") .. "]" +end + +-- ------------------------------------------------------------------------------------------------ primitives +type Merged = { + points: { number }, + counts: { number }, + indices: { number }, + normals: { number }?, + uvs: { [number]: { number } }, + colors: { number }?, -- rgba + hasAlpha: boolean, + subsets: { { faces: { number }, material: number? } }, +} + +-- the triangles / polygons of a primitive as (counts, corner indices into its vertices); nil for lines / points +local function faces(p: Types.Primitive, nverts: number): ({ number }?, { number }?) + local idx: { number } + if p.indices then + idx = (values(p.indices)) or {} + else + idx = table.create(nverts) + for i = 1, nverts do + idx[i] = i - 1 + end + end + local counts, out = {}, {} + local mode = p.mode + if mode == "triangles" or mode == nil then + for k = 1, #idx - 2, 3 do + table.insert(counts, 3) + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + table.insert(out, idx[k + 2]) + end + elseif mode == "polygons" then + local fs = (values(p.faces)) or {} + local at = 1 + for _, n in fs do + if at + n - 1 > #idx then + break + end + table.insert(counts, n) + for k = at, at + n - 1 do + table.insert(out, idx[k]) + end + at += n + end + elseif mode == "triangle_strip" then + for k = 1, #idx - 2 do + local a, b, c = idx[k], idx[k + 1], idx[k + 2] + if k % 2 == 0 then + a, b = b, a + end + table.insert(counts, 3) + table.insert(out, a) + table.insert(out, b) + table.insert(out, c) + end + elseif mode == "triangle_fan" then + for k = 2, #idx - 1 do + table.insert(counts, 3) + table.insert(out, idx[1]) + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + end + else + return nil, nil + end + return counts, out +end + +-- the primitives of a mesh merged into one USD mesh (GeomSubsets per primitive); nil when nothing is writable +local function merge(mesh: Types.Mesh, notes: { [string]: number }): Merged? + local prims: { Types.Primitive } = {} + for _, p in mesh.primitives do + if p.attributes and p.attributes.POSITION and p.attributes.POSITION.components == 3 and p.mode ~= "lines" and p.mode ~= "line_strip" and p.mode ~= "line_loop" and p.mode ~= "points" then + table.insert(prims, p) + else + notes["lines / points primitives"] = (notes["lines / points primitives"] or 0) + 1 + end + if p.targets and #p.targets > 0 then + notes["morph targets"] = (notes["morph targets"] or 0) + 1 + end + end + if #prims == 0 then + return nil + end + -- attributes every primitive has + local all = { NORMAL = true } + local uvSets: { number } = {} + for k = 0, 7 do + local every = true + for _, p in prims do + if not p.attributes["TEXCOORD_" .. k] then + every = false + end + end + if every then + table.insert(uvSets, k) + end + end + local anyColor = false + for _, p in prims do + if not p.attributes.NORMAL or p.attributes.NORMAL.components ~= 3 then + all.NORMAL = false + end + if p.attributes.COLOR_0 then + anyColor = true + end + end + local m: Merged = { points = {}, counts = {}, indices = {}, normals = if all.NORMAL then {} else nil, uvs = {}, colors = if anyColor then {} else nil, hasAlpha = false, subsets = {} } + for _, k in uvSets do + m.uvs[k] = {} + end + local face = 0 + for _, p in prims do + local base = #m.points // 3 + local pos = (values(p.attributes.POSITION)) or {} + local nv = p.attributes.POSITION.count + table.move(pos, 1, nv * 3, #m.points + 1, m.points) + if m.normals then + local nrm = (values(p.attributes.NORMAL)) or {} + table.move(nrm, 1, nv * 3, #m.normals + 1, m.normals) + end + for _, k in uvSets do + local uv, c = values(p.attributes["TEXCOORD_" .. k]) + local dst = m.uvs[k] + for i = 0, nv - 1 do + table.insert(dst, (uv :: { number })[i * c + 1] or 0) + table.insert(dst, (uv :: { number })[i * c + 2] or 0) + end + end + if m.colors then + local col, c = values(p.attributes.COLOR_0) + local dst = m.colors :: { number } + for i = 0, nv - 1 do + if col then + table.insert(dst, col[i * c + 1] or 1) + table.insert(dst, col[i * c + 2] or 1) + table.insert(dst, col[i * c + 3] or 1) + local a = if c >= 4 then col[i * c + 4] or 1 else 1 + if a ~= 1 then + m.hasAlpha = true + end + table.insert(dst, a) + else + table.insert(dst, 1) + table.insert(dst, 1) + table.insert(dst, 1) + table.insert(dst, 1) + end + end + end + local counts, idx = faces(p, nv) + local sub = { faces = {}, material = p.material } + if counts and idx then + local ok = true + for _, v in idx do + if v < 0 or v >= nv then + ok = false + break + end + end + if ok then + for _, c in counts do + table.insert(m.counts, c) + table.insert(sub.faces, face) + face += 1 + end + for _, v in idx do + table.insert(m.indices, v + base) + end + else + notes["out-of-range indices"] = (notes["out-of-range indices"] or 0) + 1 + end + end + table.insert(m.subsets, sub) + end + return m +end + +-- ------------------------------------------------------------------------------------------------ write +function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: number }) + local o: Options = opts or {} + local notes: { [string]: number } = {} + local out: { string } = {} + local function line(depth: number, s: string) + table.insert(out, string.rep(" ", depth) .. s) + end + local nodes = scene.nodes or {} + local roots = scene.roots + if not roots or #roots == 0 then + local child = {} + for _, n in nodes do + for _, c in n.children or {} do + child[c] = true + end + end + roots = {} + for i in nodes do + if not child[i] then + table.insert(roots, i) + end + end + end + if #(scene.skins or {}) > 0 then + notes.skins = #scene.skins + end + local wrap = #roots ~= 1 or (nodes[roots[1]] == nil) + local rootNames = namer() + local rootName = if wrap then "root" else rootNames(nodes[roots[1]].name, "root") + + -- texture files + local base = o.name and string.gsub(string.match(o.name, "([^/\\]+)$") or o.name, "%.[^.]*$", "") or "model" + local texFile: { [number]: string } = {} + for i, tex in scene.textures or {} do + local uri: string? = if tex.uri then (string.gsub(tex.uri, "\\", "/")) else nil + if tex.data and type(o.files) == "table" then + uri = uri or (base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png")) + if string.find(uri :: string, "^data:") or string.find(uri :: string, "^%a+://") then + uri = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png") + end + local files: any = o.files + if files[uri] == nil then + files[uri] = tex.data + end + elseif not uri then + uri = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png") + notes["textures without a file (not written)"] = (notes["textures without a file (not written)"] or 0) + 1 + end + texFile[i] = uri :: string + end + + -- animation: per node, per path -> { times, values (components) } + type Track = { times: { number }, vals: { number }, comps: number } + local tracks: { [number]: { [string]: Track } } = {} + local tcps = 24 + local tMin, tMax = math.huge, -math.huge + for _, anim in scene.animations or {} do + for _, ch in anim.channels or {} do + if ch.path == "weights" then + notes["weights animation"] = (notes["weights animation"] or 0) + 1 + elseif nodes[ch.node] and ch.input and ch.output then + local times = (values(ch.input)) or {} + local vals, comps = values(ch.output) + if vals and #times > 0 then + local stride = comps + local per = #vals // (comps * #times) + -- CUBICSPLINE: in-tangent, value, out-tangent per key: keep the value + local off = if ch.interpolation == "CUBICSPLINE" and per == 3 then comps else 0 + local mult = if ch.interpolation == "CUBICSPLINE" and per == 3 then 3 else 1 + local tv = {} + for k = 0, #times - 1 do + for c = 1, stride do + table.insert(tv, vals[k * comps * mult + off + c] or 0) + end + end + tracks[ch.node] = tracks[ch.node] or {} + tracks[ch.node][ch.path] = { times = times, vals = tv, comps = comps } + for _, t in times do + tMin = math.min(tMin, t * tcps) + tMax = math.max(tMax, t * tcps) + end + end + end + end + end + + -- header + table.insert(out, "#usda 1.0") + table.insert(out, "(") + line(1, "defaultPrim = " .. quote(rootName)) + line(1, 'doc = "formats-luau"') + if tMin <= tMax then + line(1, "endTimeCode = " .. fmt(tMax)) + end + line(1, "metersPerUnit = " .. fmt(o.metersPerUnit or scene.meta.unit or 1)) + if tMin <= tMax then + line(1, "startTimeCode = " .. fmt(tMin)) + line(1, "timeCodesPerSecond = " .. fmt(tcps)) + end + line(1, "upAxis = " .. quote(o.upAxis or (if scene.meta.up == "z" then "Z" else "Y"))) + table.insert(out, ")") + table.insert(out, "") + + local looksPath = "/" .. rootName .. "/Looks" + local matNames = namer() + local matPath: { [number]: string } = {} + for i, mat in scene.materials or {} do + matPath[i] = looksPath .. "/" .. matNames(mat.name, "material_" .. i) + end + + -- xform ops of a node (+ its animation) + local function xform(depth: number, ni: number, n: Types.Node) + local tr = tracks[ni] + local order: { string } = {} + local function samples(track: Track, f: (vals: { number }, at: number) -> string): string + local parts = {} + for k, t in track.times do + table.insert(parts, fmt(t * tcps) .. ": " .. f(track.vals, (k - 1) * track.comps)) + end + return "{ " .. table.concat(parts, ", ") .. " }" + end + local function quat(v: { number }, at: number): string + -- USD writes (real, i, j, k) + return tuple({ v[at + 4] or 1, v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 }) + end + local function vec3(v: { number }, at: number): string + return tuple({ v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 }) + end + local t, r, s = n.translation, n.rotation, n.scale + if n.matrix and #n.matrix == 16 then + if tr then + -- animated: start from the matrix's TRS + local m = n.matrix + local sx = math.sqrt(m[1] ^ 2 + m[2] ^ 2 + m[3] ^ 2) + local sy = math.sqrt(m[5] ^ 2 + m[6] ^ 2 + m[7] ^ 2) + local sz = math.sqrt(m[9] ^ 2 + m[10] ^ 2 + m[11] ^ 2) + t, s = { m[13], m[14], m[15] }, { sx, sy, sz } + r = nil + notes["matrix nodes with animation (rotation reset)"] = (notes["matrix nodes with animation (rotation reset)"] or 0) + 1 + else + local m = n.matrix + line(depth, string.format("matrix4d xformOp:transform = ( %s, %s, %s, %s )", tuple({ m[1], m[2], m[3], m[4] }), tuple({ m[5], m[6], m[7], m[8] }), tuple({ m[9], m[10], m[11], m[12] }), tuple({ m[13], m[14], m[15], m[16] }))) + line(depth, 'uniform token[] xformOpOrder = ["xformOp:transform"]') + return + end + end + if t or (tr and tr.translation) then + if t then + line(depth, "double3 xformOp:translate = " .. tuple({ t[1] or 0, t[2] or 0, t[3] or 0 })) + end + if tr and tr.translation then + line(depth, "double3 xformOp:translate.timeSamples = " .. samples(tr.translation, vec3)) + end + table.insert(order, '"xformOp:translate"') + end + if r or (tr and tr.rotation) then + if r then + line(depth, "quatf xformOp:orient = " .. quat(r, 0)) + end + if tr and tr.rotation then + line(depth, "quatf xformOp:orient.timeSamples = " .. samples(tr.rotation, quat)) + end + table.insert(order, '"xformOp:orient"') + end + if s or (tr and tr.scale) then + if s then + line(depth, "float3 xformOp:scale = " .. tuple({ s[1] or 1, s[2] or 1, s[3] or 1 })) + end + if tr and tr.scale then + line(depth, "float3 xformOp:scale.timeSamples = " .. samples(tr.scale, vec3)) + end + table.insert(order, '"xformOp:scale"') + end + if #order > 0 then + line(depth, "uniform token[] xformOpOrder = [" .. table.concat(order, ", ") .. "]") + end + end + + local function meshBody(depth: number, m: Merged, path: string) + local doubleSided = false + for _, sub in m.subsets do + local mat = sub.material and scene.materials[sub.material] + if mat and mat.doubleSided then + doubleSided = true + end + end + if doubleSided then + line(depth, "uniform bool doubleSided = 1") + end + -- extent + local mn, mx = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for i = 0, #m.points // 3 - 1 do + for c = 1, 3 do + local v = m.points[i * 3 + c] + if v < mn[c] then + mn[c] = v + end + if v > mx[c] then + mx[c] = v + end + end + end + if #m.points > 0 then + line(depth, "float3[] extent = [" .. tuple(mn) .. ", " .. tuple(mx) .. "]") + end + line(depth, "int[] faceVertexCounts = " .. arrayText(m.counts, 1)) + line(depth, "int[] faceVertexIndices = " .. arrayText(m.indices, 1)) + local single = #m.subsets == 1 + if single and m.subsets[1].material and matPath[m.subsets[1].material :: number] then + line(depth, "rel material:binding = <" .. matPath[m.subsets[1].material :: number] .. ">") + end + if m.normals then + line(depth, "normal3f[] normals = " .. arrayText(m.normals, 3) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + end + line(depth, "point3f[] points = " .. arrayText(m.points, 3)) + if m.colors then + line(depth, "color3f[] primvars:displayColor = " .. arrayText(m.colors, 3, 4) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + if m.hasAlpha then + local alpha = {} + for i = 0, #m.colors // 4 - 1 do + alpha[i + 1] = m.colors[i * 4 + 4] + end + line(depth, "float[] primvars:displayOpacity = " .. arrayText(alpha, 1) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + end + end + local uvKeys = {} + for k in m.uvs do + table.insert(uvKeys, k) + end + table.sort(uvKeys) + for _, k in uvKeys do + local name = if k == 0 then "st" else "st" .. k + line(depth, "texCoord2f[] primvars:" .. name .. " = " .. arrayText(m.uvs[k], 2, nil, nil, function(_i: number, c: number, v: number): number + return if c == 2 then 1 - v else v + end) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + end + line(depth, 'uniform token subdivisionScheme = "none"') + if not single then + local names = namer() + for k, sub in m.subsets do + if #sub.faces > 0 then + local mp = sub.material and matPath[sub.material :: number] + table.insert(out, "") + line(depth, 'def GeomSubset "' .. names("subset_" .. k, "subset") .. '"' .. (if mp then ' (\n' .. string.rep(" ", depth + 1) .. 'prepend apiSchemas = ["MaterialBindingAPI"]\n' .. string.rep(" ", depth) .. ")" else "")) + line(depth, "{") + line(depth + 1, 'uniform token elementType = "face"') + line(depth + 1, 'uniform token familyName = "materialBind"') + line(depth + 1, "int[] indices = " .. arrayText(sub.faces, 1)) + if mp then + line(depth + 1, "rel material:binding = <" .. mp .. ">") + end + line(depth, "}") + end + end + end + end + + local function cameraBody(depth: number, c: Types.Camera) + if c.type == "orthographic" then + line(depth, "float2 clippingRange = " .. tuple({ c.znear or 0.01, c.zfar or 1000000 })) + line(depth, "float horizontalAperture = " .. fmt((c.xmag or 1) * 20)) + line(depth, 'token projection = "orthographic"') + line(depth, "float verticalAperture = " .. fmt((c.ymag or 1) * 20)) + return + end + local vap = 24 + local yfov = c.yfov or 0.8 + local focal = vap / (2 * math.tan(yfov / 2)) + line(depth, "float2 clippingRange = " .. tuple({ c.znear or 0.01, c.zfar or 1000000 })) + line(depth, "float focalLength = " .. fmt(focal)) + line(depth, "float horizontalAperture = " .. fmt(vap * (c.aspect or 1))) + line(depth, 'token projection = "perspective"') + line(depth, "float verticalAperture = " .. fmt(vap)) + end + + local LIGHT_TYPE = { directional = "DistantLight", point = "SphereLight", spot = "SphereLight" } + local function lightBody(depth: number, l: Types.Light) + local c = l.color or { 1, 1, 1 } + line(depth, "color3f inputs:color = " .. tuple({ c[1] or 1, c[2] or 1, c[3] or 1 })) + line(depth, "float inputs:intensity = " .. fmt(l.intensity or 1)) + if l.type ~= "directional" then + line(depth, "float inputs:radius = 0") + end + if l.type == "spot" then + local outer = l.outerCone or math.pi / 4 + line(depth, "float inputs:shaping:cone:angle = " .. fmt(outer * RAD)) + line(depth, "float inputs:shaping:cone:softness = " .. fmt(if outer > 0 then 1 - (l.innerCone or 0) / outer else 0)) + end + if l.type ~= "directional" then + line(depth, "bool treatAsPoint = 1") + end + end + local function lightHead(l: Types.Light): string + return if l.type == "spot" then ' (\n%s prepend apiSchemas = ["ShapingAPI"]\n%s)' else "" + end + + local visited: { [number]: boolean } = {} + local function writeNode(depth: number, ni: number, path: string, names: (string?, string) -> string, isRoot: boolean) + local n = nodes[ni] + if not n or visited[ni] then + return + end + visited[ni] = true + local name = if isRoot and not wrap then rootName else names(n.name, "node_" .. ni) + local myPath = path .. "/" .. name + local mesh = n.mesh and scene.meshes[n.mesh] + local merged = mesh and merge(mesh, notes) + local cam = n.camera and scene.cameras[n.camera] + local lig = n.light and scene.lights[n.light] + local kind = "Xform" + local head = "" + local pad = string.rep(" ", depth) + if merged then + kind = "Mesh" + if #merged.subsets == 1 and merged.subsets[1].material and matPath[merged.subsets[1].material :: number] then + head = ' (\n' .. pad .. ' prepend apiSchemas = ["MaterialBindingAPI"]\n' .. pad .. ")" + end + elseif cam and not lig then + kind = "Camera" + elseif lig and not cam then + kind = LIGHT_TYPE[lig.type] or "SphereLight" + local h = lightHead(lig) + head = if h ~= "" then string.format(h, pad, pad) else "" + end + if n.skin then + notes.skins = (notes.skins or 0) + 0 + end + table.insert(out, "") + line(depth, "def " .. kind .. " " .. quote(name) .. head) + line(depth, "{") + xform(depth + 1, ni, n) + if kind == "Mesh" then + meshBody(depth + 1, merged :: Merged, myPath) + elseif kind == "Camera" then + cameraBody(depth + 1, cam :: Types.Camera) + elseif kind ~= "Xform" then + lightBody(depth + 1, lig :: Types.Light) + end + local childNames = namer() + -- a camera / light that did not take the node's prim + if cam and kind ~= "Camera" then + table.insert(out, "") + line(depth + 1, "def Camera " .. quote(childNames(cam.name, "camera"))) + line(depth + 1, "{") + cameraBody(depth + 2, cam) + line(depth + 1, "}") + end + if lig and kind == "Xform" or (lig and kind == "Mesh") or (lig and kind == "Camera") then + local l = lig :: Types.Light + local h = lightHead(l) + local pad2 = string.rep(" ", depth + 1) + table.insert(out, "") + line(depth + 1, "def " .. (LIGHT_TYPE[l.type] or "SphereLight") .. " " .. quote(childNames(l.name, "light")) .. (if h ~= "" then string.format(h, pad2, pad2) else "")) + line(depth + 1, "{") + lightBody(depth + 2, l) + line(depth + 1, "}") + end + if isRoot and not wrap then + Write._looks(out, depth + 1, scene, matPath, texFile, line) + end + for _, c in n.children or {} do + writeNode(depth + 1, c, myPath, childNames, false) + end + line(depth, "}") + end + + if wrap then + line(0, "def Xform " .. quote(rootName)) + line(0, "{") + Write._looks(out, 1, scene, matPath, texFile, line) + local names = namer() + names("Looks", "Looks") + for _, r in roots do + writeNode(1, r, "/" .. rootName, names, false) + end + line(0, "}") + else + writeNode(0, roots[1], "", rootNames, true) + end + table.insert(out, "") + return table.concat(out, "\n"), notes +end + +-- the Looks scope: materials as UsdPreviewSurface networks +function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPath: { [number]: string }, texFile: { [number]: string }, line: (number, string) -> ()) + local mats = scene.materials or {} + if #mats == 0 then + return + end + table.insert(out, "") + line(depth, 'def Scope "Looks"') + line(depth, "{") + for i, mat in mats do + local path = matPath[i] + local mname = string.match(path, "([^/]+)$") :: string + table.insert(out, "") + line(depth + 1, "def Material " .. quote(mname)) + line(depth + 1, "{") + local d = depth + 2 + line(d, "token outputs:surface.connect = <" .. path .. "/PreviewSurface.outputs:surface>") + -- texture nodes (one per distinct ref) + type TexNode = { name: string, ref: Types.TextureRef, color: boolean } + local texNodes: { TexNode } = {} + local function texNode(ref: Types.TextureRef?, color: boolean): string? + if not ref or not texFile[ref.texture] then + return nil + end + for _, tn in texNodes do + if tn.ref == ref or (tn.ref.texture == ref.texture and (tn.ref.texCoord or 0) == (ref.texCoord or 0) and tn.ref.transform == nil and ref.transform == nil and tn.color == color) then + return tn.name + end + end + local name = "Texture_" .. (#texNodes + 1) + table.insert(texNodes, { name = name, ref = ref, color = color }) + return name + end + local bc = mat.baseColor or { 1, 1, 1, 1 } + local blend = mat.alphaMode == "blend" or mat.alphaMode == "mask" + local diffuseTex = texNode(mat.baseColorTexture, true) + local mrTex = texNode(mat.metallicRoughnessTexture, false) + local emTex = texNode(mat.emissiveTexture, true) + local nTex = texNode(mat.normalTexture, false) + local oTex = texNode(mat.occlusionTexture, false) + table.insert(out, "") + line(d, 'def Shader "PreviewSurface"') + line(d, "{") + local e = d + 1 + line(e, 'uniform token info:id = "UsdPreviewSurface"') + if diffuseTex then + line(e, "color3f inputs:diffuseColor.connect = <" .. path .. "/" .. diffuseTex .. ".outputs:rgb>") + else + line(e, "color3f inputs:diffuseColor = " .. tuple({ bc[1] or 1, bc[2] or 1, bc[3] or 1 })) + end + local em = mat.emissive or { 0, 0, 0 } + if emTex then + line(e, "color3f inputs:emissiveColor.connect = <" .. path .. "/" .. emTex .. ".outputs:rgb>") + elseif (em[1] or 0) ~= 0 or (em[2] or 0) ~= 0 or (em[3] or 0) ~= 0 then + line(e, "color3f inputs:emissiveColor = " .. tuple({ em[1] or 0, em[2] or 0, em[3] or 0 })) + end + local ext = mat.extensions or {} + if ext.KHR_materials_clearcoat and type(ext.KHR_materials_clearcoat.clearcoatFactor) == "number" then + line(e, "float inputs:clearcoat = " .. fmt(ext.KHR_materials_clearcoat.clearcoatFactor)) + line(e, "float inputs:clearcoatRoughness = " .. fmt(tonumber(ext.KHR_materials_clearcoat.clearcoatRoughnessFactor) or 0)) + end + if ext.KHR_materials_ior and type(ext.KHR_materials_ior.ior) == "number" then + line(e, "float inputs:ior = " .. fmt(ext.KHR_materials_ior.ior)) + end + if mrTex then + line(e, "float inputs:metallic.connect = <" .. path .. "/" .. mrTex .. ".outputs:b>") + else + line(e, "float inputs:metallic = " .. fmt(mat.metallic or 0)) + end + if nTex then + line(e, "normal3f inputs:normal.connect = <" .. path .. "/" .. nTex .. ".outputs:rgb>") + end + if oTex then + line(e, "float inputs:occlusion.connect = <" .. path .. "/" .. oTex .. ".outputs:r>") + end + if blend and diffuseTex then + line(e, "float inputs:opacity.connect = <" .. path .. "/" .. diffuseTex .. ".outputs:a>") + elseif blend then + line(e, "float inputs:opacity = " .. fmt(bc[4] or 1)) + end + if mat.alphaMode == "mask" then + line(e, "float inputs:opacityThreshold = " .. fmt(mat.alphaCutoff or 0.5)) + end + if mrTex then + line(e, "float inputs:roughness.connect = <" .. path .. "/" .. mrTex .. ".outputs:g>") + else + line(e, "float inputs:roughness = " .. fmt(mat.roughness or 1)) + end + line(e, "token outputs:surface") + line(d, "}") + -- primvar readers per texCoord set, transforms, textures + local readers: { [number]: boolean } = {} + for _, tn in texNodes do + local tc = (tn.ref.transform and tn.ref.transform.texCoord) or tn.ref.texCoord or 0 + if not readers[tc] then + readers[tc] = true + table.insert(out, "") + line(d, 'def Shader "PrimvarReader_' .. tc .. '"') + line(d, "{") + line(d + 1, 'uniform token info:id = "UsdPrimvarReader_float2"') + line(d + 1, "string inputs:varname = " .. quote(if tc == 0 then "st" else "st" .. tc)) + line(d + 1, "float2 outputs:result") + line(d, "}") + end + end + for _, tn in texNodes do + local ref = tn.ref + local tc = (ref.transform and ref.transform.texCoord) or ref.texCoord or 0 + local stSource = path .. "/PrimvarReader_" .. tc .. ".outputs:result" + if ref.transform then + local tr = ref.transform :: any + table.insert(out, "") + line(d, 'def Shader "' .. tn.name .. '_Transform"') + line(d, "{") + line(d + 1, 'uniform token info:id = "UsdTransform2d"') + line(d + 1, "float2 inputs:in.connect = <" .. stSource .. ">") + if tr.rotation then + line(d + 1, "float inputs:rotation = " .. fmt(tr.rotation * RAD)) + end + if tr.scale then + line(d + 1, "float2 inputs:scale = " .. tuple({ tr.scale[1] or 1, tr.scale[2] or 1 })) + end + if tr.offset then + line(d + 1, "float2 inputs:translation = " .. tuple({ tr.offset[1] or 0, tr.offset[2] or 0 })) + end + line(d + 1, "float2 outputs:result") + line(d, "}") + stSource = path .. "/" .. tn.name .. "_Transform.outputs:result" + end + local tex = scene.textures[ref.texture] + local sampler = tex and tex.sampler or {} + table.insert(out, "") + line(d, 'def Shader "' .. tn.name .. '"') + line(d, "{") + line(d + 1, 'uniform token info:id = "UsdUVTexture"') + line(d + 1, "asset inputs:file = " .. asset(texFile[ref.texture])) + if tn.ref == mat.baseColorTexture and ((bc[1] or 1) ~= 1 or (bc[2] or 1) ~= 1 or (bc[3] or 1) ~= 1 or (bc[4] or 1) ~= 1) then + line(d + 1, "float4 inputs:scale = " .. tuple({ bc[1] or 1, bc[2] or 1, bc[3] or 1, bc[4] or 1 })) + end + if tn.ref == mat.normalTexture then + line(d + 1, "float4 inputs:bias = (-1, -1, -1, 0)") + line(d + 1, "float4 inputs:scale = (2, 2, 2, 1)") + end + line(d + 1, 'token inputs:sourceColorSpace = "' .. (if tn.color then "sRGB" else "raw") .. '"') + line(d + 1, "float2 inputs:st.connect = <" .. stSource .. ">") + line(d + 1, 'token inputs:wrapS = "' .. (sampler.wrapS or "repeat") .. '"') + line(d + 1, 'token inputs:wrapT = "' .. (sampler.wrapT or "repeat") .. '"') + line(d + 1, "float outputs:a") + line(d + 1, "float outputs:b") + line(d + 1, "float outputs:g") + line(d + 1, "float outputs:r") + line(d + 1, "float3 outputs:rgb") + line(d, "}") + end + line(depth + 1, "}") + end + line(depth, "}") +end + +return Write diff --git a/src/Formats/model/usda/init.luau b/src/Formats/model/usda/init.luau new file mode 100644 index 0000000..e1b8338 --- /dev/null +++ b/src/Formats/model/usda/init.luau @@ -0,0 +1,221 @@ +--!strict +-- model/usda: USD ASCII layers (.usda, .usd in text form) and USDZ packages holding them. New code, from the Sdf text +-- format and the UsdGeom / UsdShade / UsdLux schema documentation (OpenUSD 26.x); checked against OpenUSD's own +-- reader / writer (pxr) and Blender's USD exporter. +-- Reads: stage metadata (upAxis -> meta.up, metersPerUnit -> meta.unit, defaultPrim, timeCodesPerSecond, start / +-- endTimeCode), the prim tree (def / over; class skipped; selected variants merged), xform op stacks (translate, scale, +-- rotateX/Y/Z, rotateXYZ ... rotateZYX, orient, transform, !invert!, !resetXformStack!) with time samples -> one +-- animation of TRS channels, Mesh (faceVertexCounts / Indices, holes, leftHanded orientation, normals, every +-- texCoord2f primvar -> TEXCOORD_n with st first, displayColor / displayOpacity, all interpolations, :indices, +-- GeomSubsets -> one primitive each), UsdPreviewSurface materials with UsdUVTexture / UsdPrimvarReader_float2 / +-- UsdTransform2d, material:binding (inherited, per subset), Camera, DistantLight / SphereLight (+ ShapingAPI cone -> +-- spot) / RectLight / DiskLight (-> spot lights over a hemisphere). Textures stay encoded: bytes from opts.files / +-- opts.resolve (or the USDZ package) + mime, else just the uri (F.model.loadTextures decodes them). +-- Writes .usda (see model/usda/Write): Xform / Mesh / GeomSubset / Material / Shader / Camera / lights, time samples. +-- Not supported: USDC binary crate files (.usdc, and .usd / USDZ holding one: UNSUPPORTED), composition arcs +-- (references, payloads, inherits, specializes, subLayers: ignored and listed in meta.source.unsupported), UsdSkel +-- skinning, blend shapes, curves / points / NURBS prims, point instancers, MaterialX shading networks, writing USDZ. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Zip = require("@formats/containers/Zip") +local Parse = require("@formats/model/usda/Parse") +local Build = require("@formats/model/usda/Build") +local Write = require("@formats/model/usda/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Usda = { + name = "usda", + category = "model", + extensions = { "usda", "usd", "usdz" }, + mime = { "model/vnd.usda", "model/vnd.usdz+zip" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + caps = { decode = true, encode = true, materials = true, animation = true, cameras = true, lights = true, polygons = true, vertexColors = true, usdz = "read", usdc = false }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate faces (default true); false keeps "polygons" primitives + flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's top-left origin) + resolve: ((uri: string) -> any)?, -- texture files next to the layer (the api sets it for paths) + files: { [string]: any }?, -- or: the files by asset path + maxVertices: number?, -- refuse meshes with more points / face corners (default 2^25) + maxBytes: number?, -- refuse numeric arrays over this many bytes (default 2^30) +} +export type EncodeOptions = { + files: { [string]: any }?, -- receives embedded texture bytes as _. + name: string?, -- the destination's file name (names the texture files) + format: string?, -- "usdz" -> UNSUPPORTED (set by the api from the destination's extension) + upAxis: string?, -- "Y" / "Z" (default: from scene.meta.up) + metersPerUnit: number?, -- default scene.meta.unit or 1 +} + +-- ------------------------------------------------------------------------------------------------ sniff +local function isUsdz(r: Bytes.Reader): boolean + if r:peek(4) ~= "PK\3\4" then + return false + end + -- the first entry is the root layer + local lo, hi = r:peekU8(26), r:peekU8(27) + if lo < 0 or hi < 0 then + return false + end + local nameLen = lo + hi * 256 + local name = string.lower(r:peek(30 + nameLen)) + name = string.sub(name, 31) + return string.find(name, "%.usd[ac]?$") ~= nil +end + +function Usda.sniff(r: Bytes.Reader): number + local head = r:peek(8) + if string.sub(head, 1, 5) == "#usda" or string.sub(head, 1, 8) == "\239\187\191#usda" then + return 1 + end + if head == "PXR-USDC" then + return 0.9 -- recognised so the error says USDC is not supported + end + if isUsdz(r) then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts: DecodeOptions?, package: any): (uri: string) -> buffer? + return function(uri: string): buffer? + local candidates = { uri } + local slashed = string.gsub(uri, "\\", "/") + local stripped = string.gsub(slashed, "^%./", "") + if slashed ~= uri then + table.insert(candidates, slashed) + end + if stripped ~= slashed then + table.insert(candidates, stripped) + end + -- packaged assets: "model.usdz[textures/a.png]" + local inner = string.match(uri, "%[(.+)%]$") + if inner then + table.insert(candidates, inner) + end + for _, u in candidates do + if package then + local data = package:read(u) + if data then + return data + end + end + local v: any = nil + if opts and type(opts.files) == "table" then + v = opts.files[u] + end + if v == nil and opts and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, u) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + elseif type(v) == "buffer" then + return v + end + end + return nil + end +end + +function Usda.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local head = r:peek(8) + if head == "PXR-USDC" then + return nil, Err.new(Err.UNSUPPORTED, "USDC binary crate files (convert with usdcat to .usda)") + end + local text: string + local package: any = nil + local usdz = false + if string.sub(head, 1, 4) == "PK\3\4" then + local archive, zerr = Zip.open(r) + if not archive then + return nil, zerr or Err.new(Err.CORRUPT, "bad USDZ package") + end + local entries = archive:list() + local root = nil + for _, e in entries do + if not e.dir and string.find(string.lower(e.name), "%.usd[ac]?$") then + root = e + break + end + end + if not root then + return nil, Err.new(Err.CORRUPT, "the USDZ package holds no USD layer") + end + local data, rerr = archive:read(root) + if not data then + return nil, rerr + end + if buffer.len(data) >= 8 and buffer.readstring(data, 0, 8) == "PXR-USDC" then + return nil, Err.new(Err.UNSUPPORTED, "USDZ holding a USDC binary crate layer") + end + text = buffer.tostring(data) + package = archive + usdz = true + else + text = buffer.readstring(r.buf, r.base, r.limit - r.base) + end + if not Parse.version(text) then + return nil, Err.new(Err.CORRUPT, "no #usda header") + end + local layer, msg, at = Parse.layer(text, opts and opts.maxBytes) + if not layer then + if msg == "array over the size limit" then + return nil, Err.new(Err.LIMIT, msg :: string, at) + end + local code = if at and at >= #text - 1 then Err.TRUNCATED else Err.CORRUPT + if msg and string.find(msg, "^unterminated") then + code = Err.TRUNCATED + end + return nil, Err.new(code, msg or "parse error", if usdz then nil else at) + end + local scene, err = Build.scene(layer, { + triangulate = opts and opts.triangulate, + flipV = opts and opts.flipV, + maxVertices = opts and opts.maxVertices, + fetch = fetcher(opts, package), + }) + if not scene then + if err == "LIMIT" then + return nil, Err.new(Err.LIMIT, "a mesh over maxVertices") + end + return nil, Err.new(Err.CORRUPT, err or "bad scene") + end + local src: any = scene.meta.source + src.version = Parse.version(text) + src.usdz = usdz or nil + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Usda.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + if opts and opts.format == "usdz" then + return nil, Err.new(Err.UNSUPPORTED, "writing USDZ; write .usda") + end + local ok, text = pcall(Write.text, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(text)) + end + return buffer.fromstring(text :: any), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- parse(text) -> the raw layer (prim specs, properties, metadata) | nil, Err: for prims the Scene does not cover +function Usda.parse(text: string): (Parse.Layer?, Err.Err?) + local layer, msg, at = Parse.layer(text) + if not layer then + return nil, Err.new(Err.CORRUPT, msg or "parse error", at) + end + return layer, nil +end + +return Usda diff --git a/tests/model/usda.luau b/tests/model/usda.luau new file mode 100644 index 0000000..17195ea --- /dev/null +++ b/tests/model/usda.luau @@ -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() diff --git a/tools/fixtures/_usda_encode.luau b/tools/fixtures/_usda_encode.luau new file mode 100644 index 0000000..bd02aac --- /dev/null +++ b/tools/fixtures/_usda_encode.luau @@ -0,0 +1,34 @@ +-- tools/fixtures/_usda_encode: run by tools/fixtures/usda.py (luau CLI, repo root): decodes every USDA case with our +-- reader and writes it back with our writer, printing "\t" lines (case_.usda + the texture files it +-- references) for OpenUSD (pxr) to read back. +local Usda = require("@formats/model/usda") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/usda_cases") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(s: string): string + local out = table.create(#s) + for i = 1, #s do + out[i] = HEX[string.byte(s, i)] + end + return table.concat(out) +end + +for i, c in Cases do + if not c.expect then + local scene = Usda.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }) + if scene then + local files = {} + local out = assert(Usda.encode(scene, { files = files, name = "case_" .. i .. ".usda" })) + print(string.format("case_%d.usda\t%s", i, hex(buffer.tostring(out)))) + for name, data in files do + if not string.find(name, "%.%.") and string.sub(name, 1, 1) ~= "/" then + print(name .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data))) + end + end + end + end +end diff --git a/tools/fixtures/_usda_reference.py b/tools/fixtures/_usda_reference.py new file mode 100644 index 0000000..7da1f71 --- /dev/null +++ b/tools/fixtures/_usda_reference.py @@ -0,0 +1,404 @@ +# OpenUSD (pxr) side of tools/fixtures/usda.py, run by ctx.python(["openusd"], ) with a JSON +# request on stdin: +# {"mode": "author", "dir": d} -> writes the authored test stages into d (usda, plus a usdc and a usdz) and prints +# the file names +# {"mode": "metrics", "paths": [...]} -> prints [ metrics per file ] (see metrics() below) +# {"mode": "convert", "src": a, "dst": b} -> usdc -> usda through Sdf (as usdcat does) +# {"mode": "specs", "paths": [...]} -> the number of prim specs in each layer (parse-only checks) +import json, math, os, struct, sys, zlib +from pxr import Gf, Sdf, Usd, UsdGeom, UsdLux, UsdShade, UsdUtils, Vt + +req = json.loads(sys.stdin.read()) + + +def png(w, h, rgba): + raw = b"".join(b"\0" + bytes(rgba[(y * w) * 4:(y * w + w) * 4]) for y in range(h)) + def chunk(t, d): + return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff) + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"") + + +def cube(stage, path, size=1.0, quads=True): + m = UsdGeom.Mesh.Define(stage, path) + s = size / 2 + pts = [(-s, -s, -s), (s, -s, -s), (s, s, -s), (-s, s, -s), (-s, -s, s), (s, -s, s), (s, s, s), (-s, s, s)] + faces = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)] + m.CreatePointsAttr([Gf.Vec3f(*p) for p in pts]) + if quads: + m.CreateFaceVertexCountsAttr([4] * 6) + m.CreateFaceVertexIndicesAttr([i for f in faces for i in f]) + else: + m.CreateFaceVertexCountsAttr([3] * 12) + m.CreateFaceVertexIndicesAttr([i for f in faces for i in (f[0], f[1], f[2], f[0], f[2], f[3])]) + m.CreateExtentAttr([Gf.Vec3f(-s, -s, -s), Gf.Vec3f(s, s, s)]) + return m + + +def author(d): + names = [] + # 1. transforms: every op kind and order + st = Usd.Stage.CreateInMemory() + UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.y) + UsdGeom.SetStageMetersPerUnit(st, 1.0) + root = UsdGeom.Xform.Define(st, "/World") + st.SetDefaultPrim(root.GetPrim()) + x = UsdGeom.Xform.Define(st, "/World/TRS") + x.AddTranslateOp().Set(Gf.Vec3d(1, 2, 3)) + x.AddRotateXYZOp().Set(Gf.Vec3f(30, 45, 60)) + x.AddScaleOp().Set(Gf.Vec3f(1, 2, 0.5)) + cube(st, "/World/TRS/Cube") + for k, order in enumerate(["XZY", "YXZ", "YZX", "ZXY", "ZYX"]): + x = UsdGeom.Xform.Define(st, "/World/R%s" % order) + x.AddTranslateOp().Set(Gf.Vec3d(k * 3, 0, 0)) + op = x.AddXformOp(getattr(UsdGeom.XformOp, "TypeRotate" + order)) + op.Set(Gf.Vec3f(10 + k, 70, -25)) + cube(st, "/World/R%s/Cube" % order, 0.5) + x = UsdGeom.Xform.Define(st, "/World/Single") + x.AddRotateYOp().Set(33.0) + x.AddRotateXOp().Set(-12.0) + x.AddScaleOp().Set(Gf.Vec3f(2, 2, 2)) + cube(st, "/World/Single/Cube") + x = UsdGeom.Xform.Define(st, "/World/Orient") + x.AddOrientOp().Set(Gf.Quatf(0.9238795, 0, 0.3826834, 0)) + x.AddTranslateOp().Set(Gf.Vec3d(0, 1, 0)) + cube(st, "/World/Orient/Cube") + x = UsdGeom.Xform.Define(st, "/World/Pivot") + x.AddTranslateOp().Set(Gf.Vec3d(5, 0, 0)) + piv = x.AddTranslateOp(opSuffix="pivot") + piv.Set(Gf.Vec3d(1, 1, 0)) + x.AddRotateZOp().Set(90.0) + x.AddTranslateOp(opSuffix="pivot", isInverseOp=True) + cube(st, "/World/Pivot/Cube") + x = UsdGeom.Xform.Define(st, "/World/Matrix") + x.AddTransformOp().Set(Gf.Matrix4d(Gf.Rotation(Gf.Vec3d(1, 1, 0), 40), Gf.Vec3d(-2, 0, 4)) * Gf.Matrix4d().SetScale(Gf.Vec3d(1.5, 1.5, 1.5))) + cube(st, "/World/Matrix/Cube") + r = UsdGeom.Xform.Define(st, "/World/Matrix/Reset") + r.SetResetXformStack(True) + r.AddTranslateOp().Set(Gf.Vec3d(0, -3, 0)) + cube(st, "/World/Matrix/Reset/Cube", 0.25) + neg = UsdGeom.Xform.Define(st, "/World/Negative") + neg.AddScaleOp().Set(Gf.Vec3f(-1, 1, 1)) + cube(st, "/World/Negative/Cube") + names.append(("xforms.usda", st)) + + # 2. primvars, interpolations, holes, orientation, n-gons + st = Usd.Stage.CreateInMemory() + UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.z) + UsdGeom.SetStageMetersPerUnit(st, 0.01) + m = UsdGeom.Mesh.Define(st, "/Grid") + st.SetDefaultPrim(m.GetPrim()) + n = 4 + pts = [Gf.Vec3f(i, j, 0.1 * i * j) for j in range(n + 1) for i in range(n + 1)] + counts, idx = [], [] + for j in range(n): + for i in range(n): + a = j * (n + 1) + i + counts.append(4) + idx += [a, a + 1, a + n + 2, a + n + 1] + # a pentagon and a triangle + pts += [Gf.Vec3f(10, 0, 0), Gf.Vec3f(11, 0, 0), Gf.Vec3f(11.5, 1, 0), Gf.Vec3f(10.5, 2, 0), Gf.Vec3f(9.5, 1, 0)] + b = (n + 1) * (n + 1) + counts += [5, 3] + idx += [b, b + 1, b + 2, b + 3, b + 4, b, b + 2, b + 3] + m.CreatePointsAttr(pts) + m.CreateFaceVertexCountsAttr(counts) + m.CreateFaceVertexIndicesAttr(idx) + m.CreateHoleIndicesAttr([5]) + pv = UsdGeom.PrimvarsAPI(m) + stp = pv.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying) + stp.Set([Gf.Vec2f(0, 0), Gf.Vec2f(1, 0), Gf.Vec2f(1, 1), Gf.Vec2f(0, 1)]) + stp.SetIndices(Vt.IntArray([k % 4 for k in range(len(idx))])) + col = pv.CreatePrimvar("displayColor", Sdf.ValueTypeNames.Color3fArray, UsdGeom.Tokens.uniform) + col.Set([Gf.Vec3f((k % 3) / 2, (k % 5) / 4, 1 - (k % 2)) for k in range(len(counts))]) + op = pv.CreatePrimvar("displayOpacity", Sdf.ValueTypeNames.FloatArray, UsdGeom.Tokens.vertex) + op.Set([0.5 + 0.5 * (k % 2) for k in range(len(pts))]) + uv2 = pv.CreatePrimvar("uv2", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex) + uv2.Set([Gf.Vec2f(p[0] / 12, p[1] / 4) for p in pts]) + m.CreateNormalsAttr([Gf.Vec3f(0, 0, 1)] * len(pts)) + m.SetNormalsInterpolation(UsdGeom.Tokens.vertex) + m2 = cube(st, "/Grid/Left") + m2.CreateOrientationAttr(UsdGeom.Tokens.leftHanded) + UsdGeom.Xformable(m2).AddTranslateOp().Set(Gf.Vec3d(0, 0, 5)) + m3 = cube(st, "/Grid/ConstColor", 2) + UsdGeom.Xformable(m3).AddTranslateOp().Set(Gf.Vec3d(0, 6, 0)) + m3.CreateDisplayColorPrimvar(UsdGeom.Tokens.constant).Set([Gf.Vec3f(0.2, 0.4, 0.8)]) + names.append(("primvars.usda", st)) + + # 3. materials: textures, transforms, subsets, inherited bindings, interface inputs + st = Usd.Stage.CreateInMemory() + UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.y) + root = UsdGeom.Xform.Define(st, "/Root") + st.SetDefaultPrim(root.GetPrim()) + UsdGeom.Scope.Define(st, "/Root/Looks") + + def surface(path, **inputs): + mat = UsdShade.Material.Define(st, path) + sh = UsdShade.Shader.Define(st, path + "/Surface") + sh.CreateIdAttr("UsdPreviewSurface") + for k, v in inputs.items(): + if isinstance(v, tuple): + sh.CreateInput(k, Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*v)) + else: + sh.CreateInput(k, Sdf.ValueTypeNames.Float).Set(v) + mat.CreateSurfaceOutput().ConnectToSource(sh.ConnectableAPI(), "surface") + return mat, sh + + def texture(mat, sh, name, file, varname="st", wrap="repeat", transform=None, iface=False): + path = mat.GetPath().pathString + reader = UsdShade.Shader.Define(st, path + "/" + name + "_Reader") + reader.CreateIdAttr("UsdPrimvarReader_float2") + if iface: + mi = mat.CreateInput("frame:stPrimvarName", Sdf.ValueTypeNames.Token) + mi.Set(varname) + reader.CreateInput("varname", Sdf.ValueTypeNames.Token).ConnectToSource(mi) + else: + reader.CreateInput("varname", Sdf.ValueTypeNames.Token).Set(varname) + src = reader.ConnectableAPI() + if transform: + tr = UsdShade.Shader.Define(st, path + "/" + name + "_Transform") + tr.CreateIdAttr("UsdTransform2d") + tr.CreateInput("in", Sdf.ValueTypeNames.Float2).ConnectToSource(src, "result") + tr.CreateInput("rotation", Sdf.ValueTypeNames.Float).Set(transform[0]) + tr.CreateInput("scale", Sdf.ValueTypeNames.Float2).Set(Gf.Vec2f(*transform[1])) + tr.CreateInput("translation", Sdf.ValueTypeNames.Float2).Set(Gf.Vec2f(*transform[2])) + src = tr.ConnectableAPI() + t = UsdShade.Shader.Define(st, path + "/" + name) + t.CreateIdAttr("UsdUVTexture") + t.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(file) + t.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(src, "result") + t.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set(wrap) + t.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("clamp") + return t.ConnectableAPI() + + red, _ = surface("/Root/Looks/Red", diffuseColor=(0.8, 0.1, 0.1), metallic=0.25, roughness=0.75) + glass, _ = surface("/Root/Looks/Glass", diffuseColor=(0.9, 0.9, 1.0), opacity=0.3, roughness=0.05, ior=1.33) + glow, _ = surface("/Root/Looks/Glow", emissiveColor=(1.0, 0.5, 0.0), opacityThreshold=0.4, opacity=0.9) + tex, tsh = surface("/Root/Looks/Textured", roughness=0.5) + c = texture(tex, tsh, "Diffuse", "./textures/checker.png", iface=True) + tsh.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(c, "rgb") + mr = texture(tex, tsh, "MetalRough", "textures/mr.png", varname="uv2", wrap="mirror", transform=(30.0, (2, 2), (0.25, 0.5))) + tsh.CreateInput("metallic", Sdf.ValueTypeNames.Float).ConnectToSource(mr, "b") + tsh.CreateInput("roughness", Sdf.ValueTypeNames.Float).ConnectToSource(mr, "g") + nrm = texture(tex, tsh, "Normal", "textures/normal.png") + tsh.CreateInput("normal", Sdf.ValueTypeNames.Normal3f).ConnectToSource(nrm, "rgb") + grp = UsdGeom.Xform.Define(st, "/Root/Group") + UsdShade.MaterialBindingAPI.Apply(grp.GetPrim()).Bind(red) + a = cube(st, "/Root/Group/Inherits") + b = cube(st, "/Root/Group/Own") + UsdGeom.Xformable(b).AddTranslateOp().Set(Gf.Vec3d(2, 0, 0)) + UsdShade.MaterialBindingAPI.Apply(b.GetPrim()).Bind(glass) + s = cube(st, "/Root/Subsets", 1.0, quads=False) + UsdGeom.Xformable(s).AddTranslateOp().Set(Gf.Vec3d(0, 3, 0)) + pv = UsdGeom.PrimvarsAPI(s) + pv.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex).Set([Gf.Vec2f((k % 2), (k // 2) % 2) for k in range(8)]) + pv.CreatePrimvar("uv2", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex).Set([Gf.Vec2f((k % 4) / 4, k / 8) for k in range(8)]) + mb = UsdShade.MaterialBindingAPI.Apply(s.GetPrim()) + mb.Bind(glow) + s1 = mb.CreateMaterialBindSubset("top", Vt.IntArray([0, 1, 2, 3])) + UsdShade.MaterialBindingAPI.Apply(s1.GetPrim()).Bind(tex) + s2 = mb.CreateMaterialBindSubset("side", Vt.IntArray([4, 5, 6])) + UsdShade.MaterialBindingAPI.Apply(s2.GetPrim()).Bind(red) + names.append(("materials.usda", st)) + + # 4. cameras and lights + st = Usd.Stage.CreateInMemory() + UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.y) + root = UsdGeom.Xform.Define(st, "/Scene") + st.SetDefaultPrim(root.GetPrim()) + cam = UsdGeom.Camera.Define(st, "/Scene/Persp") + cam.CreateFocalLengthAttr(35) + cam.CreateHorizontalApertureAttr(36) + cam.CreateVerticalApertureAttr(24) + cam.CreateClippingRangeAttr(Gf.Vec2f(0.1, 500)) + UsdGeom.Xformable(cam).AddTranslateOp().Set(Gf.Vec3d(0, 1, 10)) + o = UsdGeom.Camera.Define(st, "/Scene/Ortho") + o.CreateProjectionAttr(UsdGeom.Tokens.orthographic) + o.CreateHorizontalApertureAttr(40) + o.CreateVerticalApertureAttr(30) + UsdLux.DistantLight.Define(st, "/Scene/Sun").CreateIntensityAttr(3) + sp = UsdLux.SphereLight.Define(st, "/Scene/Bulb") + sp.CreateIntensityAttr(50) + sp.CreateColorAttr(Gf.Vec3f(1, 0.8, 0.6)) + sp.CreateExposureAttr(2) + UsdGeom.Xformable(sp).AddTranslateOp().Set(Gf.Vec3d(0, 4, 0)) + spot = UsdLux.SphereLight.Define(st, "/Scene/Spot") + sh = UsdLux.ShapingAPI.Apply(spot.GetPrim()) + sh.CreateShapingConeAngleAttr(30) + sh.CreateShapingConeSoftnessAttr(0.5) + UsdLux.RectLight.Define(st, "/Scene/Panel").CreateIntensityAttr(7) + UsdLux.DiskLight.Define(st, "/Scene/Disk") + cube(st, "/Scene/Floor", 10) + names.append(("camlights.usda", st)) + + # 5. time samples + st = Usd.Stage.CreateInMemory() + st.SetTimeCodesPerSecond(30) + st.SetStartTimeCode(0) + st.SetEndTimeCode(60) + root = UsdGeom.Xform.Define(st, "/Anim") + st.SetDefaultPrim(root.GetPrim()) + x = UsdGeom.Xform.Define(st, "/Anim/Mover") + t = x.AddTranslateOp() + for k, v in ((0, (0, 0, 0)), (30, (4, 1, 0)), (60, (4, 1, -6))): + t.Set(Gf.Vec3d(*v), k) + r = x.AddRotateXYZOp() + for k, v in ((0, (0, 0, 0)), (20, (0, 90, 0)), (45, (30, 180, 10))): + r.Set(Gf.Vec3f(*v), k) + s = x.AddScaleOp() + s.Set(Gf.Vec3f(1, 1, 1)) + cube(st, "/Anim/Mover/Box") + y = UsdGeom.Xform.Define(st, "/Anim/Mover/Child") + q = y.AddOrientOp() + q.Set(Gf.Quatf(1, 0, 0, 0), 0) + q.Set(Gf.Quatf(0.7071068, 0.7071068, 0, 0), 60) + y.AddTranslateOp().Set(Gf.Vec3d(0, 2, 0)) + cube(st, "/Anim/Mover/Child/Box", 0.5) + names.append(("anim.usda", st)) + + out = [] + for name, st in names: + st.GetRootLayer().Export(os.path.join(d, name)) + out.append(name) + os.makedirs(os.path.join(d, "textures"), exist_ok=True) + checker = [] + for yy in range(8): + for xx in range(8): + v = 255 if (xx + yy) % 2 else 40 + checker += [v, v, v, 255] + for f, data in (("checker.png", png(8, 8, checker)), ("mr.png", png(2, 2, [0, 128, 255, 255] * 4)), ("normal.png", png(2, 2, [128, 128, 255, 255] * 4))): + with open(os.path.join(d, "textures", f), "wb") as fh: + fh.write(data) + # a usdc (UNSUPPORTED) and a usdz package of the materials stage + Sdf.Layer.FindOrOpen(os.path.join(d, "xforms.usda")).Export(os.path.join(d, "xforms.usdc")) + out.append("xforms.usdc") + cwd = os.getcwd() + os.chdir(d) + UsdUtils.CreateNewUsdzPackage(Sdf.AssetPath("materials.usda"), "materials.usdz") + os.chdir(cwd) + out.append("materials.usdz") + return out + + +def mat16(m): + return [float(m[i][j]) for i in range(4) for j in range(4)] + + +def metrics(path): + stage = Usd.Stage.Open(path) + if stage is None: + return {"failed": True} + res = { + "upAxis": str(UsdGeom.GetStageUpAxis(stage)), + "metersPerUnit": float(UsdGeom.GetStageMetersPerUnit(stage)) if UsdGeom.StageHasAuthoredMetersPerUnit(stage) else -1.0, + "tcps": float(stage.GetTimeCodesPerSecond()), + "meshes": [], "xforms": [], "materials": [], "cameras": [], "lights": [], "anim": [], + } + t0 = Usd.TimeCode.EarliestTime() + cache = UsdGeom.XformCache(t0) + for prim in stage.Traverse(): + if not prim.IsA(UsdGeom.Xformable): + continue + path_s = prim.GetPath().pathString + world = cache.GetLocalToWorldTransform(prim) + res["xforms"].append({"path": path_s, "type": str(prim.GetTypeName()), "world": mat16(world)}) + x = UsdGeom.Xformable(prim) + times = x.GetTimeSamples() + if len(times) > 1: + samples = [] + for t in times: + samples.append({"time": float(t), "world": mat16(x.ComputeLocalToWorldTransform(t))}) + res["anim"].append({"path": path_s, "samples": samples}) + if prim.IsA(UsdGeom.Mesh): + m = UsdGeom.Mesh(prim) + pts = m.GetPointsAttr().Get(t0) or [] + counts = m.GetFaceVertexCountsAttr().Get(t0) or [] + idx = m.GetFaceVertexIndicesAttr().Get(t0) or [] + holes = set(m.GetHoleIndicesAttr().Get(t0) or []) + wp = [world.Transform(Gf.Vec3d(*p)) for p in pts] + tris, area, at = 0, 0.0, 0 + lo, hi = [math.inf] * 3, [-math.inf] * 3 + for f, c in enumerate(counts): + corners = list(idx[at:at + c]) + at += c + if c < 3 or f in holes: + continue + for k in range(1, c - 1): + a, b, cc = wp[corners[0]], wp[corners[k]], wp[corners[k + 1]] + area += 0.5 * Gf.Cross(b - a, cc - a).GetLength() + tris += 1 + for v in corners: + for j in range(3): + lo[j] = min(lo[j], wp[v][j]) + hi[j] = max(hi[j], wp[v][j]) + mat, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() + subsets = UsdShade.MaterialBindingAPI(prim).GetMaterialBindSubsets() + res["meshes"].append({ + "path": path_s, "triangles": tris, "area": area, "min": lo if tris else [], "max": hi if tris else [], + "material": mat.GetPath().pathString if mat else "", "subsets": len(subsets), + "subsetMaterials": sorted( + (UsdShade.MaterialBindingAPI(sub.GetPrim()).ComputeBoundMaterial()[0].GetPath().pathString if UsdShade.MaterialBindingAPI(sub.GetPrim()).ComputeBoundMaterial()[0] else "") for sub in subsets), + }) + if prim.IsA(UsdGeom.Camera): + c = UsdGeom.Camera(prim) + cr = c.GetClippingRangeAttr().Get(t0) + res["cameras"].append({ + "path": path_s, "projection": str(c.GetProjectionAttr().Get(t0)), "focal": float(c.GetFocalLengthAttr().Get(t0)), + "hap": float(c.GetHorizontalApertureAttr().Get(t0)), "vap": float(c.GetVerticalApertureAttr().Get(t0)), + "near": float(cr[0]), "far": float(cr[1]), + }) + for lt in ("DistantLight", "SphereLight", "RectLight", "DiskLight"): + cls = getattr(UsdLux, lt) + if prim.IsA(cls): + l = cls(prim) + col = l.GetColorAttr().Get(t0) + cone = prim.GetAttribute("inputs:shaping:cone:angle") + res["lights"].append({ + "path": path_s, "type": lt, "intensity": float(l.GetIntensityAttr().Get(t0)) * 2 ** float(l.GetExposureAttr().Get(t0)), + "color": [float(v) for v in col], "cone": float(cone.Get(t0)) if cone and cone.HasAuthoredValue() else -1.0, + }) + for prim in stage.Traverse(): + if not prim.IsA(UsdShade.Material): + continue + mat = UsdShade.Material(prim) + surf = mat.ComputeSurfaceSource() + sh = surf[0] if surf else None + if not sh or sh.GetIdAttr().Get() != "UsdPreviewSurface": + continue + d = {"path": prim.GetPath().pathString, "textures": {}} + for name in ("diffuseColor", "emissiveColor", "metallic", "roughness", "opacity", "opacityThreshold", "ior", "normal", "occlusion"): + inp = sh.GetInput(name) + if not inp: + continue + srcs = inp.GetConnectedSources()[0] if inp.HasConnectedSource() else [] + if srcs: + src = UsdShade.Shader(srcs[0].source.GetPrim()) + f = src.GetInput("file") + if f: + d["textures"][name] = {"file": f.Get().path, "output": str(srcs[0].sourceName)} + else: + v = inp.Get() + if v is not None: + d[name] = [float(x) for x in v] if hasattr(v, "__len__") else float(v) + res["materials"].append(d) + return res + + +mode = req["mode"] +if mode == "author": + print(json.dumps(author(req["dir"]))) +elif mode == "metrics": + print(json.dumps([metrics(p) for p in req["paths"]])) +elif mode == "convert": + Sdf.Layer.FindOrOpen(req["src"]).Export(req["dst"]) + print("[]") +elif mode == "specs": + out = [] + for p in req["paths"]: + layer = Sdf.Layer.FindOrOpen(p) + n = [0] + def visit(path): + if path.IsPrimPath(): + n[0] += 1 + layer.Traverse(Sdf.Path.absoluteRootPath, visit) + out.append(n[0]) + print(json.dumps(out)) diff --git a/tools/fixtures/usda.py b/tools/fixtures/usda.py new file mode 100644 index 0000000..9a9822a --- /dev/null +++ b/tools/fixtures/usda.py @@ -0,0 +1,264 @@ +# USDA fixtures (tools/fixtures.py): stages authored through OpenUSD's own API (pxr, nixpkgs python3Packages.openusd: +# every xform op kind / order, pivots, !resetXformStack!, primvar interpolations + indices, holes, leftHanded, n-gons, +# UsdPreviewSurface + UsdUVTexture / UsdTransform2d / interface inputs, GeomSubsets, inherited bindings, cameras, +# UsdLux lights, time samples; plus a .usdc and a .usdz), assimp's USD test models (models-nonbsd/USD: the .usda files +# and the .usdc ones converted to .usda by Sdf, read from the nixpkgs assimp source, not committed), Blender 5 USD +# exports of glTF sample models (when blender is on PATH), a hand-written file exercising the text grammar, and the +# OpenUSD schema layers (parse-only). Reference values come from pxr (Usd.Stage: world transforms, triangles / area / +# bounds per mesh, bound materials, cameras, lights, xform time samples). +# tests/gen/usda_cases.luau { name, data, files = { uri -> bytes }, ref = pxr metrics | nil, expect = "UNSUPPORTED"? } +# tests/gen/usda_specs.luau { name, data, prims = number of prim specs (Sdf) } +# tests/gen/usda_xcheck.luau our writer's .usda for every case (tools/fixtures/_usda_encode.luau) read back by pxr: +# { name, case, ref } +import json, os, shutil, subprocess, tempfile + +INPUTS = ["src/Formats/model/usda", "tools/fixtures/_usda_reference.py", "tools/fixtures/_usda_encode.luau", + "tools/fixtures/_model_ref.py", "tests/fixtures/gltf"] + +# the text grammar: comments, metadata of every kind, list ops, variants, class / over, dictionaries, strings, +# relative paths, typed values that the Scene ignores +HANDWRITTEN = r'''#usda 1.0 +( + """A layer written by hand: every construct of the text format the reader has to get through.""" + customLayerData = { + string creator = "formats-luau tests" + dictionary nested = { + int[] numbers = [1, 2, 3] + double "quoted key" = 1.5 + } + } + defaultPrim = "Hand" + metersPerUnit = 0.0254 + upAxis = "Z" + timeCodesPerSecond = 24 +) + +# a class (abstract: not a node) and an over of nothing +class "_Template" +{ + float3 xformOp:translate = (100, 100, 100) +} + +def Xform "Hand" ( + kind = "assembly" + doc = 'single quoted doc' + variants = { + string look = "big" + } + prepend variantSets = "look" + customData = { bool flag = true } +) +{ + custom string notes = """multi +line""" // trailing comment + custom asset path = @@@weird@name.png@@@ + custom double[] empty = [] + custom float big = inf + custom float small = -inf + custom token[] tokens = ["a", "b"] + custom rel others = [, <../Hand>] + reorder nameChildren = ["Big", "Tri"] + + def Mesh "Tri" ( active = true ) + { + point3f[] points = [(0,0,0),(1,0,0),(0,1,0)] ; int[] faceVertexCounts = [3] + int[] faceVertexIndices = [0, 1, 2] + double3 xformOp:translate = (1, 0, 0) + uniform token[] xformOpOrder = ["xformOp:translate"] + rel material:binding = <../Looks/Blue> + } + + variantSet "look" = { + "big" (doc = "selected") { + def Mesh "Big" + { + float3 xformOp:scale = (3, 3, 3) + uniform token[] xformOpOrder = ["xformOp:scale"] + point3f[] points = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)] + int[] faceVertexCounts = [4] + int[] faceVertexIndices = [0, 1, 2, 3] + color3f[] primvars:displayColor = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 1)] ( + interpolation = "vertex" + ) + } + } + "small" { + def Mesh "Small" + { + point3f[] points = [(0, 0, 0), (1, 0, 0), (0, 1, 0)] + int[] faceVertexCounts = [3] + int[] faceVertexIndices = [0, 1, 2] + } + } + } + + def Scope "Looks" + { + def Material "Blue" + { + color3f inputs:tint = (0.1, 0.2, 0.9) + token outputs:surface.connect = + + def Shader "Surface" + { + uniform token info:id = "UsdPreviewSurface" + color3f inputs:diffuseColor.connect = + float inputs:roughness = 0.25 + token outputs:surface + } + } + } + + def "Untyped" + { + def Xform "Inner" ( + prepend references = @missing.usda@ + ) + { + matrix4d xformOp:transform.timeSamples = { + 0: ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ), + 10: ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 5, 1) ), + } + uniform token[] xformOpOrder = ["xformOp:transform"] + + def Mesh "Quad" + { + point3f[] points = [(0, 0, 0), (2, 0, 0), (2, 2, 0), (0, 2, 0)] + int[] faceVertexCounts = [4] + int[] faceVertexIndices = [0, 1, 2, 3] + } + } + } +} + +over "Elsewhere" +{ + def Xform "Undefined" + { + double3 xformOp:translate = (0, 0, -1) + uniform token[] xformOpOrder = ["xformOp:translate"] + } +} +''' + +GLTF_MODELS = [("Box", "glTF", "Box.gltf"), ("BoxTextured", "glTF", "BoxTextured.gltf"), ("AnimatedTriangle", "glTF", "AnimatedTriangle.gltf"), + ("Cameras", "glTF", "Cameras.gltf"), ("MultiUVTest", "glTF-Binary", None), ("BoxVertexColors", "glTF-Binary", None)] + +BLENDER = r''' +import bpy, sys +args = sys.argv[sys.argv.index("--") + 1:] +bpy.ops.wm.read_factory_settings(use_empty=True) +bpy.ops.import_scene.gltf(filepath=args[0]) +bpy.ops.wm.usd_export(filepath=args[1], export_materials=True, export_animation=True, relative_paths=True) +''' + + +def pxr(ctx, req): + code = ctx.read("tools/fixtures/_usda_reference.py").decode() + try: + return json.loads(ctx.python(["openusd"], code, input=json.dumps(req).encode())) + except subprocess.CalledProcessError as e: + raise RuntimeError("pxr (%s) failed:\n%s" % (req["mode"], e.stderr.decode(errors="replace")[-3000:])) from None + + +def files_under(d, skip): + out = {} + for root, _, fs in os.walk(d): + for f in fs: + p = os.path.join(root, f) + rel = os.path.relpath(p, d).replace(os.sep, "/") + if rel != skip and not rel.endswith((".usda", ".usdc", ".usdz", ".usd", ".py")): + out[rel] = open(p, "rb").read() + return out + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="formats-usda-") + cases = [] # name, path, files, expect? + # 1. stages authored through pxr + adir = os.path.join(tmp, "authored") + os.makedirs(adir) + for name in pxr(ctx, {"mode": "author", "dir": adir}): + p = os.path.join(adir, name) + c = {"name": "pxr/" + name, "path": p, "files": files_under(adir, name)} + if name.endswith(".usdc"): + c["expect"] = "UNSUPPORTED" + if name.endswith(".usdz"): + c["files"] = {} + c["like"] = "pxr/materials.usda" + cases.append(c) + # 2. hand-written grammar test + hand = os.path.join(tmp, "hand.usda") + with open(hand, "w") as f: + f.write(HANDWRITTEN) + cases.append({"name": "hand.usda", "path": hand, "files": {}}) + # 3. assimp's USD test models (untrusted data: read only, from the nix store) + src = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True).stdout.decode().strip() + usd = os.path.join(src, "test", "models-nonbsd", "USD") + conv = os.path.join(tmp, "assimp") + os.makedirs(conv) + for f in sorted(os.listdir(os.path.join(usd, "usda"))): + if f.endswith(".usda"): + cases.append({"name": "assimp/" + f, "path": os.path.join(usd, "usda", f), "files": files_under(os.path.join(usd, "usda"), f)}) + for d, f in [(os.path.join(usd, "usdc"), x) for x in sorted(os.listdir(os.path.join(usd, "usdc"))) if x.endswith(".usdc")] + [(os.path.join(src, "test", "models", "USD"), "MotionCaptureROM.usdc")]: + dst = os.path.join(conv, f[:-5] + ".usda") + pxr(ctx, {"mode": "convert", "src": os.path.join(d, f), "dst": dst}) + cases.append({"name": "assimp/" + f + " (usdcat)", "path": dst, "files": files_under(d, f)}) + # 4. Blender USD exports of glTF samples + if shutil.which("blender"): + bdir = os.path.join(tmp, "blender") + os.makedirs(bdir) + script = os.path.join(tmp, "blender_export.py") + with open(script, "w") as f: + f.write(BLENDER) + groot = os.path.join(ctx.root, "tests", "fixtures", "gltf") + for model, variant, main in GLTF_MODELS: + d = os.path.join(groot, model, variant) + if not os.path.isdir(d): + continue + main = main or [x for x in sorted(os.listdir(d)) if x.endswith((".gltf", ".glb"))][0] + out = os.path.join(bdir, model, model + ".usda") + os.makedirs(os.path.dirname(out), exist_ok=True) + r = subprocess.run(["blender", "-b", "--factory-startup", "--python", script, "--", os.path.join(d, main), out], capture_output=True) + if r.returncode == 0 and os.path.exists(out): + cases.append({"name": "blender/" + model, "path": out, "files": files_under(os.path.dirname(out), model + ".usda")}) + refs = pxr(ctx, {"mode": "metrics", "paths": [c["path"] for c in cases if "expect" not in c]}) + k = 0 + for c in cases: + if "expect" not in c: + c["ref"] = refs[k] + k += 1 + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("usda_cases", cases) + + # 5. parse-only: OpenUSD's schema layers + usdpkg = ctx.python(["openusd"], "import pxr, os; print(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(pxr.__file__)))))))").decode().strip() + specs = [] + for root, _, fs in os.walk(usdpkg): + for f in fs: + if f.endswith(".usda") and ("usdGeom" in root or "usdShade" in root or "usdLux" in root or "usdSkel" in root): + specs.append(os.path.join(root, f)) + specs = sorted(specs)[:8] + counts = pxr(ctx, {"mode": "specs", "paths": specs}) + ctx.emit("usda_specs", [{"name": os.path.relpath(p, usdpkg), "data": open(p, "rb").read(), "prims": n} for p, n in zip(specs, counts)]) + + # 6. pxr reads our writer's output + exe = shutil.which("luau") + cmd = [exe, "tools/fixtures/_usda_encode.luau"] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_usda_encode.luau"] + res = subprocess.run(cmd, cwd=ctx.root, capture_output=True, check=True) + xdir = os.path.join(tmp, "ours") + os.makedirs(xdir) + mains = [] + for line in res.stdout.decode().split("\n"): + if "\t" in line: + name, hexdata = line.split("\t", 1) + p = os.path.join(xdir, name) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(bytes.fromhex(hexdata.strip())) + if name.endswith(".usda") and "/" not in name: + mains.append(name) + xrefs = pxr(ctx, {"mode": "metrics", "paths": [os.path.join(xdir, n) for n in mains]}) + ctx.emit("usda_xcheck", [{"name": n, "case": int(n[5:].split(".")[0]), "ref": r} for n, r in zip(mains, xrefs)]) + shutil.rmtree(tmp, ignore_errors=True)