Merge branch 'ws/3d2-usda' into ws/3d2

This commit is contained in:
4DBug committed 2026-10-31 09:47:00 -05:00
commit a4751298ed
10 files changed
+4539

No files matched your search

+1
View File
@@ -28,6 +28,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` |
+12
View File
@@ -290,6 +290,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",
File diff suppressed because it is too large. Load diff
+820
View File
@@ -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@</prim>
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 <version>" string
function Parse.version(text: string): string?
return smatch(text, "^\239?\187?\191?#usda%s+([%d%.]+)")
end
return Parse
+840
View File
@@ -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 <name>_<n>.<ext>. 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
+221
View File
@@ -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>_<n>.<ext>
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
+547
View File
@@ -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()
+34
View File
@@ -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 "<file>\t<hex>" lines (case_<n>.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
+404
View File
@@ -0,0 +1,404 @@
# OpenUSD (pxr) side of tools/fixtures/usda.py, run by ctx.python(["openusd"], <this file's text>) 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))
+264
View File
@@ -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 = @@@[email protected]@@@
custom double[] empty = []
custom float big = inf
custom float small = -inf
custom token[] tokens = ["a", "b"]
custom rel others = [</Hand/Big>, <../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 = <Surface.outputs:surface>
def Shader "Surface"
{
uniform token info:id = "UsdPreviewSurface"
color3f inputs:diffuseColor.connect = </Hand/Looks/Blue.inputs:tint>
float inputs:roughness = 0.25
token outputs:surface
}
}
}
def "Untyped"
{
def Xform "Inner" (
prepend references = @missing.usda@</Thing>
)
{
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)