ws-3d2/usda: model/usda - USD ASCII read / write (+ USDZ read), checked against OpenUSD (pxr), assimp's USD models and Blender exports
Reads stage metadata, xform op stacks (every rotate order, orient, transform, pivots / !invert!, resetXformStack), time samples -> TRS animation, Mesh (all primvar interpolations + indices, GeomSubsets, holes, leftHanded), UsdPreviewSurface / UsdUVTexture / UsdTransform2d materials with inherited bindings, cameras, UsdLux lights, selected variants. USDC returns UNSUPPORTED. Writes Xform / Mesh / GeomSubset / Material / Camera / lights. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
75c677074a
commit
fb7f6359cd
10 files changed
+4539
No files matched your search
@@ -254,6 +254,18 @@ local list: { Entry } = {
|
||||
return require("@formats/model/stl")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "usda",
|
||||
category = "model",
|
||||
path = "model/usda",
|
||||
extensions = { "usda", "usd", "usdz" },
|
||||
mime = { "model/vnd.usda", "model/vnd.usdz+zip" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" },
|
||||
caps = { decode = true, encode = true, materials = true, animation = true, cameras = true, lights = true, polygons = true, vertexColors = true, usdz = "read", usdc = false },
|
||||
load = function()
|
||||
return require("@formats/model/usda")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "vox",
|
||||
category = "model",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in new issue
Block a user