Files
rosetta/src/Formats/model/usda/Write.luau
T

841 lines
30 KiB
Luau

--!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: { [string]: string } = { ["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) :: { number }
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 {} :: { number }
else
idx = table.create(nverts) :: { number }
for i = 1, nverts do
idx[i] = i - 1
end
end
local counts: { number }, out: { number } = {}, {}
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 :: Types.Accessor).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: string = 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: { [string]: Track? }? = 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 :: Track, 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 :: Track, 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 :: Track, 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: { [string]: string } = { 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: Types.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