From 80383dcdd72d5ace3454053a736856beba84bf6f Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:33:43 -0500 Subject: [PATCH 1/8] ws-3d2/3mf: model/3mf read / write (core, materials extension: base / colour / texture2d groups, composite, multiproperties; components, production p:path parts, units, metadata); tests against lib3mf 2.5 (its test suite), assimp, trimesh, our output read back by all three; bench lines --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/model/3mf/Read.luau | 598 +++++++++++++++++++++++++++++++ src/Formats/model/3mf/Write.luau | 417 +++++++++++++++++++++ src/Formats/model/3mf/init.luau | 95 +++++ tests/model/3mf.luau | 420 ++++++++++++++++++++++ tools/bench.luau | 8 + tools/fixtures/3mf.py | 111 ++++++ tools/fixtures/_3mf_encode.luau | 28 ++ tools/fixtures/_3mf_reference.py | 115 ++++++ 10 files changed, 1805 insertions(+) create mode 100644 src/Formats/model/3mf/Read.luau create mode 100644 src/Formats/model/3mf/Write.luau create mode 100644 src/Formats/model/3mf/init.luau create mode 100644 tests/model/3mf.luau create mode 100644 tools/fixtures/3mf.py create mode 100644 tools/fixtures/_3mf_encode.luau create mode 100644 tools/fixtures/_3mf_reference.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 40e275f..adcc7bd 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -20,6 +20,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | | audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | +| model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d514aa9..8cf1a77 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -194,6 +194,18 @@ local list: { Entry } = { return require("@formats/audio/wav") end, }, + { + name = "3mf", + category = "model", + path = "model/3mf", + extensions = { "3mf" }, + mime = { "model/3mf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "containers/Zip" }, + caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true }, + load = function() + return require("@formats/model/3mf") + end, + }, { name = "gltf", category = "model", diff --git a/src/Formats/model/3mf/Read.luau b/src/Formats/model/3mf/Read.luau new file mode 100644 index 0000000..710de1c --- /dev/null +++ b/src/Formats/model/3mf/Read.luau @@ -0,0 +1,598 @@ +--!strict +-- model/3mf/Read: a 3MF package (an OPC zip) -> Scene. The root model part from _rels/.rels (fallback: the first +-- *.model under 3D/), other model parts referenced by the production extension's p:path (components and build items), +-- core resources (objects with mesh vertices / triangles, components with transforms), the materials extension +-- (basematerials, colorgroup, texture2d + texture2dgroup, compositematerials blended into one colour per entry, +-- multiproperties resolved through their first layer), build items with transforms -> root nodes, metadata, the unit. +-- Triangles are grouped into one primitive per property (a base material, a colour group, a texture group); colour and +-- texture groups give per-corner COLOR_0 / TEXCOORD_0, so vertices are split where corners of one vertex differ. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Xml = require("@formats/codecs/Xml") +local Zip = require("@formats/containers/Zip") + +local Read = {} + +local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel" +local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 } +Read.UNITS = UNITS +local WRAP = { wrap = "repeat", mirror = "mirror", clamp = "clamp", none = "clamp" } +local MAX_DEPTH = 64 + +local localName = Xml.localName + +-- an attribute by local name (namespaced attributes such as p:path) +local function attr(node: any, name: string): string? + local a = node.attrs + local v = a[name] + if v ~= nil then + return v + end + for k, x in next, a do + if type(k) == "string" and localName(k) == name then + return x + end + end + return nil +end + +local function int(s: string?): number? + local n = if s then tonumber(s) else nil + if n and n == math.floor(n) and n >= 0 then + return n + end + return nil +end + +-- "#RRGGBB" / "#RRGGBBAA" -> { r, g, b, a } sRGB 0..1 +local function hexColor(s: string?): { number }? + if type(s) ~= "string" then + return nil + end + local h = string.match(s, "^%s*#(%x+)%s*$") + if not h or (#h ~= 6 and #h ~= 8) then + return nil + end + local function c(i: number): number + return (tonumber(string.sub(h :: string, i, i + 1), 16) :: number) / 255 + end + return { c(1), c(3), c(5), if #h == 8 then c(7) else 1 } +end +Read.hexColor = hexColor + +function Read.toLinear(c: number): number + if c <= 0.04045 then + return c / 12.92 + end + return ((c + 0.055) / 1.055) ^ 2.4 +end +local toLinear = Read.toLinear + +-- "m00 m01 m02 m10 ... m32" (3MF row-vector convention) -> a column-major glTF matrix, nil for identity / invalid +local function transform(s: string?): ({ number }?, boolean) + if not s then + return nil, true + end + local v = {} + for w in string.gmatch(s, "%S+") do + local n = tonumber(w) + if not n or n ~= n or n == math.huge or n == -math.huge then + return nil, false + end + table.insert(v, n) + end + if #v ~= 12 then + return nil, false + end + local m = { v[1], v[2], v[3], 0, v[4], v[5], v[6], 0, v[7], v[8], v[9], 0, v[10], v[11], v[12], 1 } + for i = 1, 16 do + if m[i] ~= Types.Scene.IDENTITY[i] then + return m, true + end + end + return nil, true +end + +local function normPath(p: string): string + p = string.gsub(p, "\\", "/") + p = string.gsub(p, "^/+", "") + return p +end + +-- one model part parsed into its resources and build +type Model = { path: string, unit: string?, metadata: { [string]: string }, res: { [number]: any }, items: { any }, required: string? } + +local function parseModel(text: string, path: string, opts: any): (Model?, Err.Err?) + local doc, err = Xml.decode(text, { parents = false }) + if not doc then + return nil, err + end + local root = (doc :: any).root + if not root or localName(root.name) ~= "model" then + return nil, Err.new(Err.CORRUPT, path .. ": the root element is not ") + end + local maxV = opts.maxVertices or 2 ^ 25 + local model: Model = { path = path, unit = attr(root, "unit"), metadata = {}, res = {}, items = {}, required = attr(root, "requiredextensions") } + local resources: any = nil + local build: any = nil + for _, ch in Xml.children(root) do + local ln = localName(ch.name) + if ln == "metadata" then + local n = attr(ch, "name") + if n then + model.metadata[n] = Xml.text(ch) + end + elseif ln == "resources" then + resources = ch + elseif ln == "build" then + build = ch + end + end + local total = 0 + if resources then + for _, r in Xml.children(resources) do + local ln = localName(r.name) + local id = int(attr(r, "id")) + if id == nil then + continue + end + if ln == "object" then + local o: any = { kind = "object", id = id, name = attr(r, "name"), type = attr(r, "type") or "model", pid = int(attr(r, "pid")), pindex = int(attr(r, "pindex")), partnumber = attr(r, "partnumber") } + local mesh = Xml.child(r, "mesh") + local comps = Xml.child(r, "components") + if mesh then + local verts = Xml.child(mesh, "vertices") + local tris = Xml.child(mesh, "triangles") + local vl = if verts then Xml.children(verts, "vertex") else {} + local tl = if tris then Xml.children(tris, "triangle") else {} + total += #vl + #tl * 3 + if total > maxV then + return nil, Err.new(Err.LIMIT, "more than " .. maxV .. " vertices / corners") + end + local nv = #vl + local pos = table.create(nv * 3, 0) + for i, v in vl do + local a = v.attrs + local x, y, z = tonumber(a.x), tonumber(a.y), tonumber(a.z) + if not x or not y or not z then + return nil, Err.new(Err.CORRUPT, "object " .. id .. ": bad vertex " .. i) + end + pos[i * 3 - 2], pos[i * 3 - 1], pos[i * 3] = x, y, z + end + local nt = #tl + local tv = table.create(nt * 3, 0) + local tp = table.create(nt * 4, -1) -- pid, p1, p2, p3 (-1 = none) + for i, tri in tl do + local a = tri.attrs + local v1, v2, v3 = int(a.v1), int(a.v2), int(a.v3) + if not v1 or not v2 or not v3 or v1 >= nv or v2 >= nv or v3 >= nv then + return nil, Err.new(Err.CORRUPT, "object " .. id .. ": triangle " .. i .. " has a bad vertex index") + end + tv[i * 3 - 2], tv[i * 3 - 1], tv[i * 3] = v1, v2, v3 + local b = i * 4 - 4 + local pid, p1, p2, p3 = int(a.pid), int(a.p1), int(a.p2), int(a.p3) + tp[b + 1] = pid or -1 + tp[b + 2] = p1 or -1 + tp[b + 3] = p2 or p1 or -1 + tp[b + 4] = p3 or p1 or -1 + end + o.positions, o.tv, o.tp, o.nt = pos, tv, tp, nt + end + if comps then + o.components = {} + for _, c in Xml.children(comps, "component") do + local oid = int(attr(c, "objectid")) + local m, ok = transform(attr(c, "transform")) + if oid and ok then + table.insert(o.components, { objectid = oid, matrix = m, path = attr(c, "path") }) + end + end + end + model.res[id] = o + elseif ln == "basematerials" then + local items = {} + for _, b in Xml.children(r, "base") do + table.insert(items, { name = attr(b, "name"), color = hexColor(attr(b, "displaycolor")) or { 1, 1, 1, 1 }, hex = attr(b, "displaycolor") }) + end + model.res[id] = { kind = "base", id = id, items = items } + elseif ln == "colorgroup" then + local items = {} + for _, c in Xml.children(r, "color") do + table.insert(items, hexColor(attr(c, "color")) or { 1, 1, 1, 1 }) + end + model.res[id] = { kind = "color", id = id, items = items } + elseif ln == "texture2d" then + model.res[id] = { kind = "texture", id = id, path = attr(r, "path"), contenttype = attr(r, "contenttype"), tileu = attr(r, "tilestyleu"), tilev = attr(r, "tilestylev"), filter = attr(r, "filter") } + elseif ln == "texture2dgroup" then + local uvs = {} + for _, c in Xml.children(r, "tex2coord") do + table.insert(uvs, tonumber(attr(c, "u")) or 0) + table.insert(uvs, tonumber(attr(c, "v")) or 0) + end + model.res[id] = { kind = "texgroup", id = id, texid = int(attr(r, "texid")), uvs = uvs, count = #uvs // 2 } + elseif ln == "compositematerials" then + local mats = {} + for w in string.gmatch(attr(r, "matindices") or "", "%S+") do + table.insert(mats, tonumber(w) or 0) + end + local items = {} + for _, c in Xml.children(r, "composite") do + local vals = {} + for w in string.gmatch(attr(c, "values") or "", "%S+") do + table.insert(vals, tonumber(w) or 0) + end + table.insert(items, vals) + end + model.res[id] = { kind = "composite", id = id, matid = int(attr(r, "matid")), matindices = mats, items = items } + elseif ln == "multiproperties" then + local pids = {} + for w in string.gmatch(attr(r, "pids") or "", "%S+") do + table.insert(pids, tonumber(w) or -1) + end + local items = {} + for _, c in Xml.children(r, "multi") do + local ix = {} + for w in string.gmatch(attr(c, "pindices") or "", "%S+") do + table.insert(ix, tonumber(w) or 0) + end + table.insert(items, ix) + end + model.res[id] = { kind = "multi", id = id, pids = pids, items = items } + end + end + end + if build then + for _, it in Xml.children(build, "item") do + local oid = int(attr(it, "objectid")) + local m, ok = transform(attr(it, "transform")) + if oid and ok then + table.insert(model.items, { objectid = oid, matrix = m, path = attr(it, "path"), partnumber = attr(it, "partnumber") }) + end + end + end + return model, nil +end + +-- the root model part's path +local function rootPath(zip: any): string? + local rels = zip:readString("_rels/.rels") + if rels then + local doc = Xml.decode(rels, { parents = false }) + if doc then + for _, rel in Xml.descendants((doc :: any).root or doc, "Relationship") do + local t, target = attr(rel, "Type"), attr(rel, "Target") + if t and target and (t == REL_MODEL or string.find(t, "/3dmodel$")) then + return normPath(target) + end + end + end + end + for _, e in zip:list() do + if not e.isDir and string.find(string.lower(e.name), "%.model$") then + return e.name + end + end + return nil +end + +function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?) + local rootP = rootPath(zip) + if not rootP then + return nil, Err.new(Err.CORRUPT, "no 3D model part in the package") + end + local models: { [string]: Model } = {} + local function getModel(path: string): (Model?, Err.Err?) + local p = normPath(path) + local m = models[p] + if m then + return m, nil + end + local text, err = zip:readString(p) + if not text then + return nil, err or Err.new(Err.CORRUPT, "missing model part " .. p) + end + if string.sub(text, 1, 5) == "%3McF" then + return nil, Err.new(Err.UNSUPPORTED, "secure content extension: " .. p .. " is encrypted / wrapped") + end + local mm, perr = parseModel(text, p, opts) + if not mm then + return nil, perr + end + models[p] = mm + return mm, nil + end + local root, rerr = getModel(rootP) + if not root then + return nil, rerr + end + + local scene = Types.Scene.new() + local unitName = root.unit or "millimeter" + scene.meta.up = "z" + scene.meta.unit = UNITS[unitName] or 1e-3 + scene.meta.metadata = root.metadata + scene.meta.source = { format = "3mf", unit = unitName, part = rootP, requiredExtensions = root.required } + + -- textures and materials (shared across model parts by part path + resource id) + local texCache: { [string]: number } = {} + local function texture(model: Model, id: number): number? + local key = model.path .. "#" .. id + if texCache[key] then + return texCache[key] + end + local r = model.res[id] + if not r or r.kind ~= "texture" or type(r.path) ~= "string" then + return nil + end + local data = zip:read(normPath(r.path)) + local tex: Types.Texture = { + name = r.path, + data = data, + mime = r.contenttype, + uri = r.path, + sampler = { wrapS = WRAP[r.tileu or "wrap"] or "repeat", wrapT = WRAP[r.tilev or "wrap"] or "repeat", filter = if r.filter == "nearest" or r.filter == "linear" then r.filter else nil }, + extras = { ["3mf"] = { id = id, tilestyleu = r.tileu, tilestylev = r.tilev, filter = r.filter } }, + } + table.insert(scene.textures, tex) + texCache[key] = #scene.textures + return #scene.textures + end + local matCache: { [string]: number } = {} + local function addMaterial(key: string, make: () -> Types.Material): number + local i = matCache[key] + if i then + return i + end + table.insert(scene.materials, make()) + matCache[key] = #scene.materials + return #scene.materials + end + local function colorMaterial(name: string?, c: { number }, extras: any): Types.Material + local m = Types.Scene.material(name) + m.baseColor = { toLinear(c[1]), toLinear(c[2]), toLinear(c[3]), c[4] } + m.metallic = 0 + m.roughness = 1 + if c[4] < 1 then + m.alphaMode = "blend" + end + m.extras = { ["3mf"] = extras } + return m + end + + -- property of one corner -> (group key, material index?, kind, resource, index) + local function resolve(model: Model, pid: number, p: number, depth: number?): (string, number?, string, any, number) + local r = model.res[pid] + if not r or p < 0 then + return "none", nil, "none", nil, 0 + end + local k = r.kind + if k == "base" then + local item = r.items[p + 1] + if not item then + return "none", nil, "none", nil, 0 + end + local key = "b" .. model.path .. "#" .. pid .. ":" .. p + return key, addMaterial(key, function() + return colorMaterial(item.name, item.color, { group = pid, index = p, displaycolor = item.hex }) + end), "base", r, p + elseif k == "color" then + return "c" .. model.path .. "#" .. pid, nil, "color", r, p + elseif k == "texgroup" then + local ti = r.texid and texture(model, r.texid) + local mat: number? = nil + if ti then + local mk = "t" .. model.path .. "#" .. (r.texid :: number) + mat = addMaterial(mk, function() + local m = Types.Scene.material("texture " .. tostring(r.texid)) + m.metallic = 0 + m.roughness = 1 + m.baseColorTexture = { texture = ti :: number } + m.extras = { ["3mf"] = { texture = r.texid } } + return m + end) + end + return "t" .. model.path .. "#" .. pid, mat, "tex", r, p + elseif k == "composite" then + local item = r.items[p + 1] + local base = r.matid and model.res[r.matid] + if not item or not base or base.kind ~= "base" then + return "none", nil, "none", nil, 0 + end + local key = "x" .. model.path .. "#" .. pid .. ":" .. p + return key, addMaterial(key, function() + local c, sum = { 0, 0, 0, 0 }, 0 + for j, w in item do + local b = base.items[(r.matindices[j] or 0) + 1] + if b then + for q = 1, 4 do + c[q] += b.color[q] * w + end + sum += w + end + end + if sum > 0 then + for q = 1, 4 do + c[q] /= sum + end + else + c = { 1, 1, 1, 1 } + end + return colorMaterial("composite " .. pid .. ":" .. p, c, { composite = pid, index = p }) + end), "base", r, p + elseif k == "multi" and (depth or 0) < 1 then + local item = r.items[p + 1] + local first = r.pids[1] + if item and first then + return resolve(model, first, item[1] or 0, 1) + end + end + return "none", nil, "none", nil, 0 + end + + -- one Scene mesh per (part, object) with a mesh + local meshCache: { [string]: number } = {} + local function buildMesh(model: Model, o: any): number? + local key = model.path .. "#" .. o.id + local cached = meshCache[key] + if cached ~= nil then + return if cached > 0 then cached else nil + end + local groups: { [string]: any } = {} + local order: { any } = {} + local pos, tv, tp = o.positions, o.tv, o.tp + for t = 0, o.nt - 1 do + local pid = tp[t * 4 + 1] + local ps = { tp[t * 4 + 2], tp[t * 4 + 3], tp[t * 4 + 4] } + if pid < 0 then + pid = o.pid or -1 + if ps[1] < 0 then + local d = o.pindex or (if pid >= 0 then 0 else -1) + ps = { d, d, d } + end + end + local gkey, mat, kind, res, _ = resolve(model, pid, ps[1]) + local g = groups[gkey] + if not g then + g = { kind = kind, res = res, material = mat, vmap = {}, pos = {}, attr = {}, idx = {}, n = 0 } + groups[gkey] = g + table.insert(order, g) + end + for c = 1, 3 do + local v = tv[t * 3 + c] + local vk = v + local pc = 0 + if kind == "color" or kind == "tex" then + pc = ps[c] + local cnt = if kind == "color" then #res.items else res.count + if pc < 0 or pc >= cnt then + pc = ps[1] + end + if pc < 0 or pc >= cnt then + pc = 0 + end + vk = v * (cnt + 1) + pc + end + local ni = g.vmap[vk] + if not ni then + ni = g.n + g.n += 1 + g.vmap[vk] = ni + table.insert(g.pos, pos[v * 3 + 1]) + table.insert(g.pos, pos[v * 3 + 2]) + table.insert(g.pos, pos[v * 3 + 3]) + if kind == "color" then + local col = res.items[pc + 1] or { 1, 1, 1, 1 } + table.insert(g.attr, toLinear(col[1])) + table.insert(g.attr, toLinear(col[2])) + table.insert(g.attr, toLinear(col[3])) + table.insert(g.attr, col[4]) + elseif kind == "tex" then + table.insert(g.attr, res.uvs[pc * 2 + 1] or 0) + table.insert(g.attr, 1 - (res.uvs[pc * 2 + 2] or 0)) + end + end + table.insert(g.idx, ni) + end + end + local mesh: Types.Mesh = { name = o.name, primitives = {}, extras = { ["3mf"] = { id = o.id, part = model.path, type = o.type, partnumber = o.partnumber } } } + for _, g in order do + local n = g.n + local pa = Types.Scene.accessor(nil, "f32", 3, n) + for i, x in g.pos do + buffer.writef32(pa.data, (i - 1) * 4, x) + end + local ia = Types.Scene.accessor(nil, "u32", 1, #g.idx) + for i, x in g.idx do + buffer.writeu32(ia.data, (i - 1) * 4, x) + end + local prim: Types.Primitive = { attributes = { POSITION = pa }, indices = ia, mode = "triangles", material = g.material } + if g.kind == "color" then + local ca = Types.Scene.accessor(nil, "f32", 4, n) + for i, x in g.attr do + buffer.writef32(ca.data, (i - 1) * 4, x) + end + prim.attributes.COLOR_0 = ca + prim.extras = { ["3mf"] = { colorgroup = g.res.id } } + elseif g.kind == "tex" then + local ua = Types.Scene.accessor(nil, "f32", 2, n) + for i, x in g.attr do + buffer.writef32(ua.data, (i - 1) * 4, x) + end + prim.attributes.TEXCOORD_0 = ua + prim.extras = { ["3mf"] = { texture2dgroup = g.res.id } } + end + table.insert(mesh.primitives, prim) + end + if #mesh.primitives == 0 then + meshCache[key] = 0 + return nil + end + table.insert(scene.meshes, mesh) + meshCache[key] = #scene.meshes + return #scene.meshes + end + + -- nodes: one per object instance (build items and components) + local nodeCount = 0 + local maxNodes = opts.maxNodes or 2 ^ 20 + local instantiate: (model: Model, oid: number, matrix: { number }?, depth: number, extra: any) -> (number?, Err.Err?) + function instantiate(model: Model, oid: number, matrix: { number }?, depth: number, extra: any): (number?, Err.Err?) + if depth > MAX_DEPTH then + return nil, Err.new(Err.CORRUPT, "components nested deeper than " .. MAX_DEPTH .. " (a cycle?)") + end + nodeCount += 1 + if nodeCount > maxNodes then + return nil, Err.new(Err.LIMIT, "more than " .. maxNodes .. " object instances") + end + local o = model.res[oid] + if not o or o.kind ~= "object" then + return nil, Err.new(Err.CORRUPT, "no object " .. oid .. " in " .. model.path) + end + local node: Types.Node = { name = o.name, children = {}, matrix = matrix, extras = { ["3mf"] = extra or { objectid = oid } } } + table.insert(scene.nodes, node) + local index = #scene.nodes + if o.positions then + node.mesh = buildMesh(model, o) + end + if o.components then + for _, c in o.components do + local m: Model? = model + if c.path then + local mm, err = getModel(c.path) + if not mm then + return nil, err + end + m = mm + end + local child, err = instantiate(m :: Model, c.objectid, c.matrix, depth + 1, { objectid = c.objectid, path = c.path }) + if not child then + return nil, err + end + table.insert(node.children, child) + end + end + return index, nil + end + for _, it in root.items do + local m: Model? = root + if it.path then + local mm, err = getModel(it.path) + if not mm then + return nil, err + end + m = mm + end + local idx, err = instantiate(m :: Model, it.objectid, it.matrix, 0, { objectid = it.objectid, path = it.path, partnumber = it.partnumber, item = true }) + if not idx then + return nil, err + end + table.insert(scene.roots, idx) + end + return scene, nil +end + +function Read.open(r: any): (any, Err.Err?) + return Zip.open(r) +end + +return Read diff --git a/src/Formats/model/3mf/Write.luau b/src/Formats/model/3mf/Write.luau new file mode 100644 index 0000000..a1f4f4b --- /dev/null +++ b/src/Formats/model/3mf/Write.luau @@ -0,0 +1,417 @@ +--!strict +-- model/3mf/Write: Scene -> a 3MF package. One mesh object per Scene mesh (every triangle primitive: triangles, +-- strips, fans, polygons fan-split; points and lines are skipped), one build item per node with a mesh, carrying the +-- node's world matrix (the hierarchy is flattened). Materials go into one basematerials group (sRGB display colours), +-- primitives with COLOR_0 into a colorgroup, primitives with TEXCOORD_0 and a material whose baseColorTexture has +-- PNG / JPEG bytes into a texture2d + texture2dgroup (the image stored in the package under 3D/Textures/). +-- Units: meta.unit picks the 3MF unit when it is one of them; otherwise millimetres and the build transforms scale. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Xml = require("@formats/codecs/Xml") +local Zip = require("@formats/containers/Zip") + +local Write = {} + +local NS_CORE = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02" +local NS_MAT = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02" +local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel" +local REL_TEXTURE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture" +local UNIT_ORDER = { "micron", "millimeter", "centimeter", "inch", "foot", "meter" } +local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 } +local TEX_EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg" } + +local fmt = string.format +local esc = Xml.escapeAttr + +local function num(x: number): string + if x ~= x or x == math.huge or x == -math.huge then + return "0" + end + if x == math.floor(x) and math.abs(x) < 1e15 then + return fmt("%d", x) + end + return fmt("%.9g", x) +end + +local function toSrgb(c: number): number + c = math.clamp(c, 0, 1) + if c <= 0.0031308 then + return c * 12.92 + end + return 1.055 * c ^ (1 / 2.4) - 0.055 +end + +local function hex(r: number, g: number, b: number, a: number): string + local function q(x: number): number + return math.clamp(math.floor(x * 255 + 0.5), 0, 255) + end + return fmt("#%02X%02X%02X%02X", q(toSrgb(r)), q(toSrgb(g)), q(toSrgb(b)), q(math.clamp(a, 0, 1))) +end + +-- the triangle corner list of a primitive (0-based vertex indices) or nil +local function triangles(prim: any): { number }? + local pos = prim.attributes and prim.attributes.POSITION + if type(pos) ~= "table" then + return nil + end + local n = pos.count + local ix: { number } = {} + if prim.indices then + local get = Types.Scene.reader(prim.indices) + if not get then + return nil + end + for i = 0, prim.indices.count - 1 do + ix[i + 1] = get(i, 0) + end + else + for i = 1, n do + ix[i] = i - 1 + end + end + for _, v in ix do + if v ~= v or v < 0 or v >= n then + return nil + end + end + local mode = prim.mode or "triangles" + local out: { number } = {} + local function tri(a: number, b: number, c: number) + if a ~= b and b ~= c and a ~= c then + table.insert(out, a) + table.insert(out, b) + table.insert(out, c) + end + end + if mode == "triangles" then + for i = 1, #ix - 2, 3 do + tri(ix[i], ix[i + 1], ix[i + 2]) + end + elseif mode == "triangle_strip" then + for i = 1, #ix - 2 do + if i % 2 == 1 then + tri(ix[i], ix[i + 1], ix[i + 2]) + else + tri(ix[i + 1], ix[i], ix[i + 2]) + end + end + elseif mode == "triangle_fan" then + for i = 2, #ix - 1 do + tri(ix[1], ix[i], ix[i + 1]) + end + elseif mode == "polygons" and prim.faces then + local get = Types.Scene.reader(prim.faces) + if not get then + return nil + end + local at = 1 + for f = 0, prim.faces.count - 1 do + local k = get(f, 0) + if at + k - 1 > #ix then + break + end + for j = 1, k - 2 do + tri(ix[at], ix[at + j], ix[at + j + 1]) + end + at += k + end + else + return nil + end + return out +end + +function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?) + local o = opts or {} + local nextId = 0 + local function id(): number + nextId += 1 + return nextId + end + local res: { string } = {} -- resource XML chunks, in definition order + local files: { { name: string, data: buffer, mime: string } } = {} + + -- unit + local unitName: string, scale: number = "millimeter", 1 + local mu: any = scene.meta and scene.meta.unit + if type(o.unit) == "string" and UNITS[o.unit] then + unitName = o.unit + if type(mu) == "number" and mu > 0 then + scale = mu / UNITS[o.unit] + end + elseif type(mu) == "number" and mu > 0 then + local found = false + for _, u in UNIT_ORDER do + if math.abs(UNITS[u] - mu) <= 1e-9 * mu then + unitName, found = u, true + break + end + end + if not found then + scale = mu / 1e-3 + end + end + + -- base materials: one group with every Scene material + local baseId: number? = nil + local nmat = #scene.materials + local defaultBase = nmat -- 0-based index of an extra white "default" base, added when needed + local needDefault = false + if nmat > 0 then + baseId = id() + end + + -- textures used as base colour textures + local texRes: { [number]: number } = {} + local function textureId(ti: number): number? + if texRes[ti] ~= nil then + return if texRes[ti] > 0 then texRes[ti] else nil + end + local tex = scene.textures[ti] + local ext = tex and TEX_EXT[tex.mime or ""] + if not tex or type(tex.data) ~= "buffer" or not ext then + texRes[ti] = 0 + return nil + end + local rid = id() + local name = fmt("3D/Textures/texture_%d.%s", ti, ext :: string) + table.insert(files, { name = name, data = tex.data :: buffer, mime = tex.mime :: string }) + local s = tex.sampler + local function tile(w: string?): string + return if w == "clamp" then "clamp" elseif w == "mirror" then "mirror" else "wrap" + end + local filter = if s and (s.filter == "nearest" or s.filter == "linear") then s.filter else "auto" + table.insert(res, fmt('\t\t\n', rid, esc(name), tex.mime :: string, tile(s and s.wrapS), tile(s and s.wrapT), filter)) + texRes[ti] = rid + return rid + end + + -- objects + local objectOf: { [number]: number } = {} + local objChunks: { string } = {} + for mi, mesh in scene.meshes do + local verts: { string } = {} + local tris: { string } = {} + local base = 0 + local objPid: number?, objP: number? = nil, nil + local anyNone = false + local triList: { { number } } = {} -- { v1, v2, v3, pid | -1, p1, p2, p3 } + for _, prim in mesh.primitives do + local corners = triangles(prim) + if not corners or #corners == 0 then + continue + end + local pos = prim.attributes.POSITION + local getP = Types.Scene.reader(pos) + if not getP then + continue + end + local n = pos.count + for v = 0, n - 1 do + table.insert(verts, fmt('\t\t\t\t\t\n', num(getP(v, 0)), num(if pos.components >= 2 then getP(v, 1) else 0), num(if pos.components >= 3 then getP(v, 2) else 0))) + end + -- properties: texture group, colour group, base material, none + local pid, kind = -1, "none" + local mat = prim.material and scene.materials[prim.material] + local uv = prim.attributes.TEXCOORD_0 + local col = prim.attributes.COLOR_0 + local tref = mat and mat.baseColorTexture + local tid = if tref and uv and (tref.texCoord or 0) == 0 then textureId(tref.texture) else nil + if tid and uv then + local get = Types.Scene.reader(uv) + if get then + pid, kind = id(), "tex" + local parts = { fmt('\t\t\n', pid, tid) } + for v = 0, n - 1 do + table.insert(parts, fmt('\t\t\t\n', num(get(v, 0)), num(1 - get(v, 1)))) + end + table.insert(parts, "\t\t\n") + table.insert(res, table.concat(parts)) + end + end + if kind == "none" and col then + local get = Types.Scene.reader(col) + if get then + pid, kind = id(), "color" + local parts = { fmt('\t\t\n', pid) } + local four = col.components >= 4 + for v = 0, n - 1 do + table.insert(parts, fmt('\t\t\t\n', hex(get(v, 0), get(v, 1), get(v, 2), if four then get(v, 3) else 1))) + end + table.insert(parts, "\t\t\n") + table.insert(res, table.concat(parts)) + end + end + local pindex = -1 + if kind == "none" and baseId and prim.material and scene.materials[prim.material] then + pid, kind, pindex = baseId :: number, "base", prim.material - 1 + end + for i = 1, #corners, 3 do + local a, b, c = corners[i] + base, corners[i + 1] + base, corners[i + 2] + base + if kind == "tex" or kind == "color" then + table.insert(triList, { a, b, c, pid, corners[i], corners[i + 1], corners[i + 2] }) + elseif kind == "base" then + table.insert(triList, { a, b, c, pid, pindex, pindex, pindex }) + else + table.insert(triList, { a, b, c, -1, -1, -1, -1 }) + anyNone = true + end + if objPid == nil and kind ~= "none" then + objPid, objP = pid, if kind == "base" then pindex else corners[i] + end + end + base += n + end + if #triList == 0 then + continue + end + if objPid and anyNone then + needDefault = true + if not baseId then + baseId = id() + end + end + for _, t in triList do + if t[4] < 0 and objPid then + t[4], t[5], t[6], t[7] = baseId :: number, defaultBase, defaultBase, defaultBase + end + if t[4] < 0 then + table.insert(tris, fmt('\t\t\t\t\t\n', t[1], t[2], t[3])) + elseif t[5] == t[6] and t[6] == t[7] then + table.insert(tris, fmt('\t\t\t\t\t\n', t[1], t[2], t[3], t[4], t[5])) + else + table.insert(tris, fmt('\t\t\t\t\t\n', t[1], t[2], t[3], t[4], t[5], t[6], t[7])) + end + end + local oid = id() + objectOf[mi] = oid + local head = fmt('\t\t\n\t\t\t\n\t\t\t\t\n", table.concat(verts), "\t\t\t\t\n\t\t\t\t\n", table.concat(tris), "\t\t\t\t\n\t\t\t\n\t\t\n" })) + table.insert(res, objChunks[#objChunks]) + end + + -- the base material group goes first (its id was taken first) + if baseId then + local parts = { fmt('\t\t\n', baseId) } + for _, m in scene.materials do + local c = m.baseColor or { 1, 1, 1, 1 } + table.insert(parts, fmt('\t\t\t\n', esc(m.name or "material"), hex(c[1] or 1, c[2] or 1, c[3] or 1, c[4] or 1))) + end + if needDefault then + table.insert(parts, '\t\t\t\n') + end + table.insert(parts, "\t\t\n") + table.insert(res, 1, table.concat(parts)) + end + + -- build items: every node with a mesh, at its world matrix + local items: { string } = {} + local seen: { [number]: boolean } = {} + for _, pl in Types.Scene.flatten(scene) do + if seen[pl.node] then + continue + end + seen[pl.node] = true + local oid = objectOf[pl.mesh] + if not oid then + continue + end + local m = pl.matrix + local s = scale + local tr = { m[1] * s, m[2] * s, m[3] * s, m[5] * s, m[6] * s, m[7] * s, m[9] * s, m[10] * s, m[11] * s, m[13] * s, m[14] * s, m[15] * s } + local ident = s == 1 + for i, v in { 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 } do + if tr[i] ~= v then + ident = false + end + end + if ident then + table.insert(items, fmt('\t\t\n', oid)) + else + local ns = table.create(12, "") + for i = 1, 12 do + ns[i] = num(tr[i]) + end + table.insert(items, fmt('\t\t\n', oid, table.concat(ns, " "))) + end + end + + -- metadata + local meta: { string } = {} + local md = scene.meta and scene.meta.metadata + if type(md) == "table" then + local keys: { string } = {} + for k: any, v: any in md do + if type(k) == "string" and (type(v) == "string" or type(v) == "number") then + table.insert(keys, k) + end + end + table.sort(keys) + for _, k in keys do + table.insert(meta, fmt('\t%s\n', esc(k), Xml.escape(tostring(md[k])))) + end + end + + local model = table.concat({ + '\n', + '\n', + table.concat(meta), + "\t\n", + table.concat(res), + "\t\n\t\n", + table.concat(items), + "\t\n\n", + }) + + local types = { '\n\n', + '\t\n', + '\t\n' } + local exts: { [string]: boolean } = {} + for _, f in files do + local e = string.match(f.name, "%.(%w+)$") :: string + if not exts[e] then + exts[e] = true + table.insert(types, fmt('\t\n', e, f.mime)) + end + end + table.insert(types, "\n") + local rels = '\n\n' + .. fmt('\t\n', REL_MODEL) + .. "\n" + + local w = Zip.writer() + local level = o.level or 6 + local method = if level == 0 then "store" else "deflate" + local ok, err = w:add("[Content_Types].xml", table.concat(types), { level = level, method = method }) + if ok then + ok, err = w:add("_rels/.rels", rels, { level = level, method = method }) + end + if ok then + ok, err = w:add("3D/3dmodel.model", model, { level = level, method = method }) + end + if ok and #files > 0 then + local mr = { '\n\n' } + for i, f in files do + table.insert(mr, fmt('\t\n', esc(f.name), i, REL_TEXTURE)) + end + table.insert(mr, "\n") + ok, err = w:add("3D/_rels/3dmodel.model.rels", table.concat(mr), { level = level, method = method }) + for _, f in files do + if ok then + ok, err = w:add(f.name, f.data, { method = "store" }) + end + end + end + if not ok then + return nil, err or Err.new(Err.ARG, "zip writer failed") + end + return w:finish() +end + +return Write diff --git a/src/Formats/model/3mf/init.luau b/src/Formats/model/3mf/init.luau new file mode 100644 index 0000000..025a695 --- /dev/null +++ b/src/Formats/model/3mf/init.luau @@ -0,0 +1,95 @@ +--!strict +-- model/3mf: 3D Manufacturing Format (3MF Consortium core specification 1.3, materials and properties extension 1.2, +-- production extension 1.1 part references). New code. An OPC package (containers/Zip) holding XML model parts +-- (codecs/Xml). +-- Reads: the root model part (_rels/.rels), objects (mesh vertices / triangles; components with transforms, also from +-- other model parts through p:path), build items -> root nodes with their transforms (3MF's row-vector 4x3 matrices +-- become column-major node.matrix), object names / types / part numbers (node / mesh extras["3mf"]), metadata +-- (meta.metadata), the unit (meta.unit in metres; meta.up = "z"), basematerials (-> materials, sRGB display colours +-- made linear), colorgroup (-> COLOR_0, linear RGBA), texture2d + texture2dgroup (-> TEXCOORD_0 with v flipped to +-- glTF's top-left origin, a material with baseColorTexture, the texture kept encoded from its package part: decode it +-- with F.model.loadTextures), compositematerials (one blended colour per composite), multiproperties (their first +-- layer), per-triangle pid / p1 / p2 / p3 and per-object pid / pindex defaults. One primitive per property; vertices +-- are split where a vertex's corners carry different colours / texture coordinates. +-- Writes: one object per mesh (all triangle-like primitives; points / lines skipped), one build item per node with a +-- mesh at its world matrix (the hierarchy is flattened), materials as basematerials, COLOR_0 as colour groups, +-- PNG / JPEG base colour textures as texture2d + texture2dgroup, metadata, the unit (opts.unit or from meta.unit). +-- Not supported: beam lattice, slices, displacement, volumetric and secure content extensions (their elements are +-- ignored; meta.source.requiredExtensions lists what the file declared), thumbnails, normals (3MF has none). + +-- ------------------------------------------------------------------------------------------------ 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 Read = require("@formats/model/3mf/Read") +local Write = require("@formats/model/3mf/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local ThreeMf = { + name = "3mf", + category = "model", + extensions = { "3mf" }, + mime = { "model/3mf" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "containers/Zip" }, + caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxVertices: number?, -- refuse more vertices + triangle corners in total (default 2^25) + maxNodes: number?, -- refuse more object instances (default 2^20) +} +export type EncodeOptions = { + unit: string?, -- "micron" | "millimeter" | "centimeter" | "inch" | "foot" | "meter" (default: from meta.unit, else + -- millimeter); positions are scaled through the build transforms when meta.unit differs + level: number?, -- deflate level for the XML parts (default 6; 0 stores them) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function ThreeMf.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "PK\3\4" then + return 0 + end + -- the central directory sits at the end: look for the model part's name there, then at the start + local n = r:size() + local tail = buffer.readstring(r.buf, r.base + math.max(0, n - 65536), math.min(n, 65536)) + if string.find(tail, "3D/[^/]*%.model") or string.find(tail, "3dmodel.model", 1, true) then + return 0.95 + end + local head = r:peek(256) + if string.find(head, "3D/", 1, true) then + return 0.7 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function ThreeMf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local zip, zerr = Zip.open(r) + if not zip then + return nil, zerr + end + local ok, scene, err = pcall(Read.scene, zip, opts or {}) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad package (" .. tostring(scene) .. ")") + end + return scene, err +end + +-- ------------------------------------------------------------------------------------------------ encode +function ThreeMf.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.meshes) ~= "table" or type(scene.materials) ~= "table" or type(scene.textures) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + if opts and opts.unit ~= nil and not Read.UNITS[opts.unit] then + return nil, Err.new(Err.ARG, "unknown unit " .. tostring(opts.unit)) + end + local ok, out, err = pcall(Write.build, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene (" .. tostring(out) .. ")") + end + return out, err +end + +return ThreeMf diff --git a/tests/model/3mf.luau b/tests/model/3mf.luau new file mode 100644 index 0000000..f2a124a --- /dev/null +++ b/tests/model/3mf.luau @@ -0,0 +1,420 @@ +-- model/3mf tests: the lib3mf test suite and SDK files, assimp's box.3mf and files from assimp's / trimesh's 3MF +-- exporters against lib3mf (world triangles, area, bounds through build items and components; unit), assimp and +-- trimesh; our writer's output read back by lib3mf / assimp / trimesh (3mf_xcheck); round trips through our own reader +-- (materials, vertex colours, textures, hierarchy, units); hand-written packages for per-corner colour / texture +-- groups, composite and multiproperties, components across model parts (p:path), units; error codes; the fuzz +-- no-throw pass. Fixtures: tools/fixtures/3mf.py. +local T = require("@tests/T") +local ThreeMf = require("@formats/model/3mf") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Zip = require("@formats/containers/Zip") +local Cases = require("@tests/gen/3mf_cases") +local Xcheck = require("@tests/gen/3mf_xcheck") + +local t = T.suite("3mf") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return ThreeMf.decode(Bytes.reader(b), opts) +end + +t:eq(ThreeMf.name, "3mf", "name") +t:eq(ThreeMf.category, "model", "category") +t:check(ThreeMf.caps.decode and ThreeMf.caps.encode and ThreeMf.extensions[1] == "3mf", "contract") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +-- world-space triangles, area and bounds of every placed primitive +local function metrics(scene: any): (number, number, { number }, { number }) + local tris, area = 0, 0 + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for _, pl in Types.Scene.flatten(scene) do + local p = pl.primitive + local m = pl.matrix + local pos = p.attributes.POSITION + local W = {} + for i = 0, pos.count - 1 do + local x, y, z = buffer.readf32(pos.data, i * 12), buffer.readf32(pos.data, i * 12 + 4), buffer.readf32(pos.data, i * 12 + 8) + local w = { m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] } + W[i] = w + end + local ind = p.indices + for k = 0, ind.count // 3 - 1 do + local a, b, c = W[buffer.readu32(ind.data, k * 12)], W[buffer.readu32(ind.data, k * 12 + 4)], W[buffer.readu32(ind.data, k * 12 + 8)] + for _, v in { a, b, c } do + for q = 1, 3 do + lo[q] = math.min(lo[q], v[q]) + hi[q] = math.max(hi[q], v[q]) + end + end + local e1 = { b[1] - a[1], b[2] - a[2], b[3] - a[3] } + local e2 = { c[1] - a[1], c[2] - a[2], c[3] - a[3] } + local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + area += math.sqrt(x * x + y * y + z * z) / 2 + tris += 1 + end + end + return tris, area, lo, hi +end + +local function boundsNear(lo: { number }, hi: { number }, rmin: { number }, rmax: { number }): boolean + local ext = 0 + for q = 1, 3 do + ext = math.max(ext, rmax[q] - rmin[q]) + end + local eps = 1e-5 * math.max(ext, 1e-6) + for q = 1, 3 do + if math.abs(lo[q] - rmin[q]) > eps or math.abs(hi[q] - rmax[q]) > eps then + return false + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ reference files +local UNIT_NAMES = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 } +local refCount, rejectedOk, unsupported = 0, 0, 0 +local byIndex = {} +for i, c in Cases do + local scene, err = decode(c.data) + byIndex[i] = scene + local ref = c.lib3mf + if ref.failed then + -- lib3mf rejects these (strict checks we do not make); it is enough not to throw + rejectedOk += 1 + continue + end + if not scene and err and err.code == Err.UNSUPPORTED and string.find(c.name, "SecureContent", 1, true) then + unsupported += 1 -- encrypted / wrapped model parts (the secure content extension) + continue + end + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if not scene then + continue + end + t:eq(scene.meta.source.unit, ref.unit, c.name .. ": unit") + t:eq(scene.meta.unit, UNIT_NAMES[ref.unit], c.name .. ": meta.unit") + t:eq(scene.meta.up, "z", c.name .. ": up") + local tris, area, lo, hi = metrics(scene) + t:eq(tris, ref.triangles, c.name .. ": world triangles (lib3mf)") + t:check(near(area, ref.area, 1e-5), string.format("%s: area %.7g, lib3mf %.7g", c.name, area, ref.area)) + if ref.min then + t:check(boundsNear(lo, hi, ref.min, ref.max), c.name .. ": bounds (lib3mf)") + end + t:check(#scene.textures <= ref.textures, c.name .. ": textures <= lib3mf's texture2d count") + refCount += 1 + -- trimesh reads build items and components the same way (it skips degenerate input) + local tm = c.trimesh + if tm and not tm.failed and tm.faces == tris and tm.faces > 0 then + t:check(near(area, tm.area, 1e-5), c.name .. ": area (trimesh)") + end +end +t:note("%d files: %d against lib3mf, %d rejected by lib3mf (decoded without throwing), %d secure content (UNSUPPORTED)", #Cases, refCount, rejectedOk, unsupported) + +-- ------------------------------------------------------------------------------------------------ our output read back +local xchecked, withTextures = 0, 0 +for _, x in Xcheck do + local c = Cases[x.case] + local ref = c.lib3mf + if not byIndex[x.case] then + continue + end + t:check(not x.lib3mf.failed, x.name .. " (" .. c.name .. "): lib3mf reads our file: " .. tostring(x.lib3mf.failed)) + if not x.lib3mf.failed then + t:eq(x.lib3mf.triangles, ref.triangles, c.name .. ": our file's triangles (lib3mf)") + t:check(near(x.lib3mf.area, ref.area, 1e-5), string.format("%s: our file's area %.7g vs %.7g (lib3mf)", c.name, x.lib3mf.area, ref.area)) + if ref.min then + t:check(boundsNear(x.lib3mf.min, x.lib3mf.max, ref.min, ref.max), c.name .. ": our file's bounds (lib3mf)") + end + t:eq(x.lib3mf.unit, ref.unit, c.name .. ": our file's unit (lib3mf)") + -- the material groups made it: textures, colour groups, base materials + local scene = byIndex[x.case] + local tex, col = 0, 0 + for _, m in scene.meshes do + for _, p in m.primitives do + if p.attributes.TEXCOORD_0 and p.material and scene.materials[p.material].baseColorTexture then + tex += 1 + elseif p.attributes.COLOR_0 then + col += 1 + end + end + end + t:check((tex == 0) == (x.lib3mf.texGroups == 0), c.name .. ": our texture groups (lib3mf)") + t:check(tex == 0 or x.lib3mf.textures > 0, c.name .. ": our textures (lib3mf)") + t:eq(x.lib3mf.colorGroups, col, c.name .. ": our colour groups (lib3mf)") + t:eq(x.lib3mf.baseGroups, if #scene.materials > 0 then 1 else 0, c.name .. ": our base material group (lib3mf)") + if tex > 0 then + withTextures += 1 + end + end + t:check(not x.assimp.failed or c.assimp.failed, c.name .. ": assimp reads our file") + if not x.trimesh.failed and x.trimesh.faces > 0 and not c.trimesh.failed and c.trimesh.faces == x.trimesh.faces then + t:check(near(x.trimesh.area, c.trimesh.area, 1e-5), c.name .. ": our file's area (trimesh)") + end + xchecked += 1 +end +t:note("%d of our files read back by lib3mf / assimp / trimesh like the originals (%d with textures)", xchecked, withTextures) + +-- ------------------------------------------------------------------------------------------------ round trips (ours) +local rts = 0 +for i, c in Cases do + local scene = byIndex[i] + if scene and not c.lib3mf.failed then + local out, err = ThreeMf.encode(scene) + t:check(out, c.name .. ": encode: " .. tostring(err)) + local back, berr = decode(out) + t:check(back, c.name .. ": decode ours: " .. tostring(berr)) + local a1, b1 = metrics(scene) + local a2, b2 = metrics(back) + t:eq(a2, a1, c.name .. ": round trip triangles") + t:check(near(b2, b1, 1e-6), c.name .. ": round trip area") + t:eq(back.meta.unit, scene.meta.unit, c.name .. ": round trip unit") + -- textures: the same bytes + local used = 0 + for _, m in back.materials do + if m.baseColorTexture then + used += 1 + t:check(back.textures[m.baseColorTexture.texture].data ~= nil, c.name .. ": texture bytes") + end + end + rts += 1 + end +end +t:note("%d round trips through our writer", rts) + +-- ------------------------------------------------------------------------------------------------ hand-written packages +local function package(model: string, extra: { [string]: string }?): buffer + local w = Zip.writer() + w:add("[Content_Types].xml", '', { method = "store" }) + w:add("_rels/.rels", '', { method = "store" }) + w:add("3D/3dmodel.model", model, { method = "store" }) + for k, v in extra or {} do + w:add(k, v, { method = "store" }) + end + return (w:finish()) +end +local HEAD = '' +local QUAD = '%s' +local samples = {} + +local function f32s(acc: any): { number } + local out = {} + for i = 0, acc.count * acc.components - 1 do + out[i + 1] = buffer.readf32(acc.data, i * 4) + end + return out +end + +do -- per-corner colours: vertex 0 has two different colours -> split + local xml = string.format(HEAD, "inch") + .. 'quad & co' + .. '' + .. '' .. string.format(QUAD, '') .. '' + .. '' + local pkg = package(xml) + table.insert(samples, pkg) + local s, err = decode(pkg) + t:check(s, "colours: " .. tostring(err)) + t:eq(s.meta.unit, 0.0254, "colours: inch") + t:eq(s.meta.metadata.Title, "quad & co", "colours: metadata") + t:eq(#s.meshes, 1, "colours: one mesh") + local prim = s.meshes[1].primitives[1] + t:eq(#s.meshes[1].primitives, 1, "colours: one primitive") + -- corners: (0,red) (1,green) (2,blue) | (0,blue) (2,blue) (3,blue) -> 5 vertices + t:eq(prim.attributes.POSITION.count, 5, "colours: vertex 0 split by colour") + local col = f32s(prim.attributes.COLOR_0) + t:eq(col[1], 1, "colours: red r (linear)") + t:eq(col[2], 0, "colours: red g") + t:check(math.abs(col[8] - 128 / 255) < 1e-6, "colours: alpha kept linear") + t:eq(s.nodes[1].matrix[13], 10, "colours: transform tx") + t:eq(s.nodes[1].matrix[15], 30, "colours: transform tz") + -- through our writer and back: the same colours + local back = decode((ThreeMf.encode(s))) + local col2 = f32s(back.meshes[1].primitives[1].attributes.COLOR_0) + local same = #col2 == #col + for i = 1, #col do + same = same and math.abs(col[i] - col2[i]) < 1e-6 + end + t:check(same, "colours: round trip exact (8-bit sRGB)") + t:eq(back.meta.metadata.Title, "quad & co", "colours: metadata round trip") + t:eq(back.meta.source.unit, "inch", "colours: unit round trip") +end + +do -- base materials, object defaults, composite, multiproperties, textures + local png = "\137PNG\r\n\26\nfake" + local xml = string.format(HEAD, "millimeter") .. "" + .. '' + .. '' + .. '' + .. '' + .. '' + .. '' .. string.format(QUAD, + '' -- object default: red + .. '' -- texture + .. '' -- composite + .. '' -- multi -> its first layer (base 1 = "half") + .. '') -- half + .. "" + local pkg = package(xml, { ["3D/Texture/a.png"] = png }) + table.insert(samples, pkg) + local s, err = decode(pkg) + t:check(s, "materials: " .. tostring(err)) + local prims = s.meshes[1].primitives + t:eq(#prims, 4, "materials: red, texture, composite, half (multi shares half)") + local red = s.materials[prims[1].material] + t:eq(red.name, "red", "materials: object default pid / pindex") + t:eq(red.baseColor[1], 1, "materials: red") + t:eq(red.extras["3mf"].displaycolor, "#FF0000", "materials: display colour kept") + local tex = s.materials[prims[2].material] + t:check(tex.baseColorTexture and s.textures[tex.baseColorTexture.texture], "materials: texture material") + local tx = s.textures[tex.baseColorTexture.texture] + t:eq(buffer.tostring(tx.data), png, "materials: texture bytes from the package") + t:eq(tx.mime, "image/png", "materials: texture mime") + t:eq(tx.sampler.wrapS, "clamp", "materials: tilestyleu") + t:eq(tx.sampler.wrapT, "mirror", "materials: tilestylev") + t:eq(tx.sampler.filter, "nearest", "materials: filter") + local uv = f32s(prims[2].attributes.TEXCOORD_0) + t:eq(uv[4], 0.75, "materials: v flipped to the top-left origin") + local comp = s.materials[prims[3].material] + local half = (128 / 255 + 0.055) / 1.055 + t:check(math.abs(comp.baseColor[1] - (((1 + 128 / 255) / 2 + 0.055) / 1.055) ^ 2.4) < 1e-6, "materials: composite blends in sRGB") + t:eq(s.materials[prims[4].material].name, "half", "materials: multiproperties -> first layer") + t:eq(prims[4].indices.count, 6, "materials: multi and base 'half' share a primitive") + t:check(math.abs(s.materials[prims[4].material].baseColor[1] - half ^ 2.4) < 1e-6, "materials: sRGB -> linear") + -- round trip: texture + materials survive + local out = assert(ThreeMf.encode(s)) + local back = assert(decode(out)) + local tm = nil + for _, m in back.materials do + if m.baseColorTexture then + tm = m + end + end + t:check(tm and buffer.tostring(back.textures[tm.baseColorTexture.texture].data) == png, "materials: texture round trip") + t:eq(back.textures[1].sampler.wrapS, "clamp", "materials: sampler round trip") + local _, a1 = metrics(s) + local _, a2 = metrics(back) + t:check(near(a1, a2, 1e-6), "materials: area round trip") + local names = {} + for _, m in back.materials do + if m.name then + names[m.name] = true + end + end + t:check(names.red and names.half, "materials: base names round trip") +end + +do -- components, another model part through p:path, nested transforms + local part = string.format(HEAD, "millimeter") .. "" + .. string.format(QUAD, '') .. "" + local xml = string.format(HEAD, "centimeter") .. "" + .. '' .. string.format(QUAD, '') .. "" + .. '' + .. '' + .. '' + local pkg = package(xml, { ["3D/other.model"] = part }) + table.insert(samples, pkg) + local s, err = decode(pkg) + t:check(s, "components: " .. tostring(err)) + t:eq(#s.roots, 2, "components: two build items") + t:eq(#s.meshes, 2, "components: meshes shared between instances") + t:eq(s.nodes[s.roots[1]].name, "group", "components: node names") + t:eq(#s.nodes[s.roots[1]].children, 2, "components: children") + local tris, area, lo, hi = metrics(s) + t:eq(tris, 6, "components: world triangles") + t:check(near(area, 2 * (2 + 1), 1e-9), "components: world area") + t:check(lo[1] == 0 and hi[1] == 6 and hi[3] == 1, "components: nested transforms") + t:eq(s.meta.unit, 0.01, "components: centimetre") + -- the writer flattens the hierarchy into build items + local back = assert(decode((ThreeMf.encode(s)))) + local tris2, area2, lo2, hi2 = metrics(back) + t:eq(tris2, 6, "components: flattened round trip triangles") + t:check(near(area2, area, 1e-9) and lo2[1] == 0 and hi2[1] == 6 and hi2[3] == 1, "components: flattened round trip bounds") + t:eq(back.meta.source.unit, "centimeter", "components: unit round trip") + -- a unit 3MF lacks: scaled into millimetres + s.meta.unit = 0.5 + local scaled = assert(decode((ThreeMf.encode(s)))) + local _, _, _, hi3 = metrics(scaled) + t:eq(scaled.meta.source.unit, "millimeter", "units: millimetres when the scene's unit is not a 3MF unit") + t:check(math.abs(hi3[1] - 3000) < 1e-3, "units: positions scaled through the build transforms") + t:check(select(2, ThreeMf.encode(s, { unit = "parsec" :: any })).code == Err.ARG, "units: bad opts.unit") +end + +do -- a Scene built by hand: strips, fans, polygons, vertex colours + texture coordinates, an unplaced mesh + local s = Types.Scene.new() + local pos = Types.Scene.accessor(nil, "f32", 3, 4) + for i, v in { 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0 } do + buffer.writef32(pos.data, (i - 1) * 4, v) + end + local faces = Types.Scene.accessor(nil, "u32", 1, 1) + buffer.writeu32(faces.data, 0, 4) + local col = Types.Scene.accessor(nil, "unorm8", 3, 4) + buffer.fill(col.data, 0, 255) + s.meshes = { + { primitives = { { attributes = { POSITION = pos }, mode = "triangle_strip" }, { attributes = { POSITION = pos }, mode = "triangle_fan", material = 1 } } }, + { primitives = { { attributes = { POSITION = pos, COLOR_0 = col }, mode = "polygons", faces = faces }, { attributes = { POSITION = pos }, mode = "points" } } }, + } + s.materials = { Types.Scene.material("m") } + s.nodes = { { children = { 2 }, mesh = 1, translation = { 0, 0, 5 } }, { children = {}, mesh = 2, scale = { 2, 2, 2 } } } + s.roots = { 1 } + local out, err = ThreeMf.encode(s, { level = 0 }) + t:check(out, "scene: encode " .. tostring(err)) + table.insert(samples, out) + local back = assert(decode(out)) + local tris, area, _, hi = metrics(back) + t:eq(tris, 6, "scene: strip + fan + polygon triangles (points skipped)") + t:check(near(area, 2 + 4, 1e-9), "scene: area with node transforms") + t:eq(hi[3], 5, "scene: parent translation applied to the child") + t:eq(#back.roots, 2, "scene: one build item per placed mesh") + local m2 = back.meshes[back.nodes[back.roots[2]].mesh] + t:check(m2.primitives[1].attributes.COLOR_0 ~= nil, "scene: vertex colours as a colour group") + t:check(select(2, ThreeMf.encode({} :: any)).code == Err.ARG, "encode: not a scene") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local _, e1 = decode("not a zip at all") + t:check(e1 and e1.code ~= nil, "errors: not a zip") + local w = Zip.writer() + w:add("hello.txt", "hi") + local _, e2 = decode((w:finish())) + t:eq(e2 and e2.code, Err.CORRUPT, "errors: no model part") + local bad = string.format(HEAD, "millimeter") .. '' .. string.format(QUAD, '') .. "" + local _, e3 = decode(package(bad)) + t:eq(e3 and e3.code, Err.CORRUPT, "errors: vertex index out of range") + local cyc = string.format(HEAD, "millimeter") .. '' + local _, e4 = decode(package(cyc)) + t:eq(e4 and e4.code, Err.CORRUPT, "errors: component cycle") + local _, e5 = decode(package(string.format(HEAD, "millimeter") .. "")) + t:eq(e5 and e5.code, Err.CORRUPT, "errors: build item without an object") + local _, e6 = decode(package(string.format(HEAD, "millimeter") .. '' .. string.format(QUAD, "") .. ""), { maxVertices = 2 }) + t:eq(e6 and e6.code, Err.LIMIT, "errors: maxVertices") + table.insert(samples, package(bad)) + table.insert(samples, package(cyc)) + -- sniff + t:eq(ThreeMf.sniff(Bytes.reader(package(bad))), 0.95, "sniff: a 3MF package") + t:eq(ThreeMf.sniff(Bytes.reader((w:finish()))), 0, "sniff: another zip") + t:eq(ThreeMf.sniff(Bytes.reader(buffer.fromstring("solid x"))), 0, "sniff: not a zip") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + for _, c in Cases do + if #c.data < 20000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local s = ThreeMf.decode(Bytes.reader(b)) + if s then + ThreeMf.encode(s) + end + return s + end, samples, { mutations = 12 }) +end + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 710195d..bfc393e 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -451,6 +451,14 @@ do bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function() Ply.decode(Bytes.reader(ply)) end) + local ThreeMf = require("@formats/model/3mf") + local tmf = assert(ThreeMf.encode(scene)) + bench("3mf decode (" .. buffer.len(tmf) // 1000 .. " KB zipped)", 2, buffer.len(tmf), function() + ThreeMf.decode(Bytes.reader(tmf)) + end) + bench("3mf encode", 2, buffer.len(tmf), function() + ThreeMf.encode(scene) + end) local V = 128 local grid = Types.Voxels.new(V, V, V) for z = 0, V - 1 do diff --git a/tools/fixtures/3mf.py b/tools/fixtures/3mf.py new file mode 100644 index 0000000..d763398 --- /dev/null +++ b/tools/fixtures/3mf.py @@ -0,0 +1,111 @@ +# 3MF fixtures (tools/fixtures.py): the lib3mf test suite and SDK example files (nixpkgs#lib3mf.src, read only, never +# committed: core, materials (base / colour / texture / composite / multiproperties), production parts, metadata, +# units, thumbnails, files lib3mf rejects), assimp's box.3mf (nixpkgs#assimp.src), and files written by assimp's and +# trimesh's 3MF exporters, with reference values from lib3mf 2.5 (tools/fixtures/_3mf_reference.py: world-space +# triangles / area / bounds through build items and components, mesh object sizes, material group counts, unit), +# assimp (`assimp info -r`) and trimesh (area, faces). +# tests/gen/3mf_cases.luau { name, data, lib3mf = {...} | { failed }, assimp, trimesh } +# tests/gen/3mf_xcheck.luau our encoder's output for every case (tools/fixtures/_3mf_encode.luau) read back by +# lib3mf / assimp / trimesh: { name, case, lib3mf, assimp, trimesh } +import importlib.util, json, os, subprocess, sys + +INPUTS = ["src/Formats/model/3mf", "src/Formats/codecs/Xml", "src/Formats/containers/Zip", + "tools/fixtures/_3mf_reference.py", "tools/fixtures/_3mf_encode.luau", "tools/fixtures/_model_ref.py"] +MAX_SIZE = 500_000 + + +def ref_module(ctx): + spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def store(attr): + out = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#" + attr], check=True, capture_output=True) + return out.stdout.decode().strip().split("\n")[-1] + + +def lib3mf(ctx, paths): + src, lib = store("lib3mf.src"), store("lib3mf") + res = subprocess.run([sys.executable, "-I", os.path.join(ctx.root, "tools", "fixtures", "_3mf_reference.py"), + os.path.join(src, "Autogenerated", "Bindings", "Python"), os.path.join(lib, "lib", "lib3mf")], + input=json.dumps(paths).encode(), capture_output=True, check=True) + return json.loads(res.stdout) + + +TRIMESH_EXPORT = r""" +import sys, trimesh +m = trimesh.creation.icosphere(subdivisions=2, radius=10.0) +b = trimesh.creation.box(extents=(4, 6, 8)) +b.apply_translation((20, 0, 0)) +s = trimesh.Scene([m, b]) +open(sys.argv[1] if len(sys.argv) > 1 else "/dev/stdout", "wb").write(s.export(file_type="3mf")) +""" + + +def ply_torus(R=20.0, r=5.0, a=24, b=12): + import math + vs, fs = [], [] + for i in range(a): + for j in range(b): + u, v = 2 * math.pi * i / a, 2 * math.pi * j / b + vs.append(((R + r * math.cos(v)) * math.cos(u), (R + r * math.cos(v)) * math.sin(u), r * math.sin(v))) + for i in range(a): + for j in range(b): + p, q = i * b + j, ((i + 1) % a) * b + j + p2, q2 = i * b + (j + 1) % b, ((i + 1) % a) * b + (j + 1) % b + fs.append((p, q2, p2)) + fs.append((p, q, q2)) + head = "ply\nformat ascii 1.0\nelement vertex %d\nproperty float x\nproperty float y\nproperty float z\nelement face %d\nproperty list uchar int vertex_indices\nend_header\n" % (len(vs), len(fs)) + return (head + "".join("%r %r %r\n" % v for v in vs) + "".join("3 %d %d %d\n" % f for f in fs)).encode() + + +def generate(ctx): + M = ref_module(ctx) + src = store("lib3mf.src") + files = [] + for base in ("Tests/TestFiles", "SDK/Examples/Files"): + for d, _, fs in sorted(os.walk(os.path.join(src, base))): + for f in sorted(fs): + p = os.path.join(d, f) + if f.endswith(".3mf") and os.path.getsize(p) <= MAX_SIZE: + files.append(("lib3mf/" + os.path.relpath(p, os.path.join(src, base)), p)) + files.append(("assimp/box.3mf", os.path.join(store("assimp.src"), "test", "models", "3MF", "box.3mf"))) + tmp = M.tempdir() + ply = os.path.join(tmp, "torus.ply") + with open(ply, "wb") as f: + f.write(ply_torus()) + out = os.path.join(tmp, "torus_assimp.3mf") + ctx.nix(["assimp"], ["assimp", "export", ply, out, "-f3mf"]) + files.append(("assimp/torus_export.3mf", out)) + tm = ctx.python(["trimesh", "numpy", "networkx", "lxml"], TRIMESH_EXPORT) + out = os.path.join(tmp, "trimesh_export.3mf") + with open(out, "wb") as f: + f.write(tm) + files.append(("trimesh/export.3mf", out)) + + paths = [p for _, p in files] + refs = lib3mf(ctx, paths) + infos = M.assimp_info(ctx, paths, raw=True) + tms = M.trimesh_metrics(ctx, paths) + cases = [] + for (name, p), r, a, t in zip(files, refs, infos, tms): + cases.append({"name": name, "data": open(p, "rb").read(), "lib3mf": r, "assimp": a, "trimesh": t}) + ctx.emit("3mf_cases", cases) + + # the reference tools read our output + ours = M.luau_encode(ctx, "tools/fixtures/_3mf_encode.luau") + xtmp = M.tempdir() + names = sorted(ours, key=lambda n: int(n.split("_")[1].split(".")[0])) + xp = [] + for n in names: + p = os.path.join(xtmp, n) + with open(p, "wb") as f: + f.write(ours[n]) + xp.append(p) + xr = lib3mf(ctx, xp) + xi = M.assimp_info(ctx, xp, raw=True) + xt = M.trimesh_metrics(ctx, xp) + ctx.emit("3mf_xcheck", [{"name": n, "case": int(n.split("_")[1].split(".")[0]), "lib3mf": r, "assimp": a, "trimesh": t} + for n, r, a, t in zip(names, xr, xi, xt)]) diff --git a/tools/fixtures/_3mf_encode.luau b/tools/fixtures/_3mf_encode.luau new file mode 100644 index 0000000..a31f85a --- /dev/null +++ b/tools/fixtures/_3mf_encode.luau @@ -0,0 +1,28 @@ +-- tools/fixtures/_3mf_encode: run by tools/fixtures/3mf.py (luau CLI, repo root): decodes every 3MF case that lib3mf +-- reads with our reader and encodes it with our writer, printing "rt_.3mf\t" lines for the reference tools +-- (lib3mf, assimp, trimesh) to read back. +local ThreeMf = require("@formats/model/3mf") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/3mf_cases") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(s: string): string + local out = table.create(#s) + for i = 1, #s do + out[i] = HEX[string.byte(s, i)] + end + return table.concat(out) +end + +for i, c in Cases do + if not c.lib3mf.failed then + local scene = ThreeMf.decode(Bytes.reader(buffer.fromstring(c.data))) + if scene then + local out = assert(ThreeMf.encode(scene)) + print(string.format("rt_%d.3mf\t%s", i, hex(buffer.tostring(out)))) + end + end +end diff --git a/tools/fixtures/_3mf_reference.py b/tools/fixtures/_3mf_reference.py new file mode 100644 index 0000000..f87d7d6 --- /dev/null +++ b/tools/fixtures/_3mf_reference.py @@ -0,0 +1,115 @@ +# 3MF reference values through lib3mf's Python binding (ctypes over lib3mf.so; both from nixpkgs), run by 3mf.py as +# `python3 -I _3mf_reference.py < paths.json` -> JSON list, one entry per file: +# { unit, items, meshObjects = [ [vertices, triangles] ... sorted ], triangles, area, min, max (world space, every +# build item through its components), baseGroups, colorGroups, textures, texGroups } or { failed = message } +import json, math, sys + +sys.path.insert(0, sys.argv[1]) +import Lib3MF # noqa: E402 + +W = Lib3MF.Wrapper(sys.argv[2]) +UNITS = {0: "micron", 1: "millimeter", 2: "centimeter", 3: "inch", 4: "foot", 5: "meter"} + + +def mat(t): + f = t.Fields + return [[f[r][c] for c in range(3)] for r in range(4)] + + +def mul(a, b): # row-vector 4x3 affine: p * a * b + out = [] + for r in range(4): + row = [] + for c in range(3): + s = sum(a[r][k] * b[k][c] for k in range(3)) + if r == 3: + s += b[3][c] + row.append(s) + out.append(row) + return out + + +IDENT = [[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 0, 0]] + + +def count(it): + n = 0 + while it.MoveNext(): + n += 1 + return n + + +def info(path): + model = W.CreateModel() + reader = model.QueryReader("3mf") + reader.SetStrictModeActive(False) + reader.ReadFromFile(path) + res = {"unit": UNITS.get(model.GetUnit().value if hasattr(model.GetUnit(), "value") else model.GetUnit(), "?")} + meshes = [] + it = model.GetMeshObjects() + while it.MoveNext(): + m = it.GetCurrentMeshObject() + meshes.append([m.GetVertexCount(), m.GetTriangleCount()]) + res["meshObjects"] = sorted(meshes) + tot = {"tri": 0, "area": 0.0, "min": [math.inf] * 3, "max": [-math.inf] * 3} + + def place(rid, M, depth): + if depth > 32: + return + try: + mo = model.GetMeshObjectByID(rid) + except Exception: + mo = None + if mo is not None: + verts = mo.GetVertices() + tris = mo.GetTriangleIndices() + P = [] + for v in verts: + x, y, z = v.Coordinates[0], v.Coordinates[1], v.Coordinates[2] + P.append([x * M[0][c] + y * M[1][c] + z * M[2][c] + M[3][c] for c in range(3)]) + for p in P: + for c in range(3): + tot["min"][c] = min(tot["min"][c], p[c]) + tot["max"][c] = max(tot["max"][c], p[c]) + for t in tris: + a, b, c = (P[i] for i in t.Indices) + e1 = [b[k] - a[k] for k in range(3)] + e2 = [c[k] - a[k] for k in range(3)] + cx = e1[1] * e2[2] - e1[2] * e2[1] + cy = e1[2] * e2[0] - e1[0] * e2[2] + cz = e1[0] * e2[1] - e1[1] * e2[0] + tot["area"] += math.sqrt(cx * cx + cy * cy + cz * cz) / 2 + tot["tri"] += 1 + return + co = model.GetComponentsObjectByID(rid) + for i in range(co.GetComponentCount()): + comp = co.GetComponent(i) + T = mat(comp.GetTransform()) if comp.HasTransform() else IDENT + place(comp.GetObjectResourceID(), mul(T, M), depth + 1) + + items = model.GetBuildItems() + n = 0 + while items.MoveNext(): + bi = items.GetCurrent() + n += 1 + T = mat(bi.GetObjectTransform()) if bi.HasObjectTransform() else IDENT + place(bi.GetObjectResourceID(), T, 0) + res["items"] = n + res["triangles"] = tot["tri"] + res["area"] = tot["area"] + if tot["tri"]: + res["min"], res["max"] = tot["min"], tot["max"] + res["baseGroups"] = count(model.GetBaseMaterialGroups()) + res["colorGroups"] = count(model.GetColorGroups()) + res["textures"] = count(model.GetTexture2Ds()) + res["texGroups"] = count(model.GetTexture2DGroups()) + return res + + +out = [] +for p in json.loads(sys.stdin.read()): + try: + out.append(info(p)) + except Exception as e: # noqa: BLE001 + out.append({"failed": str(e)[:200]}) +print(json.dumps(out)) From 443a7e45cbc4a279fb5f13e6f97ffc75447b235a Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:33:58 -0500 Subject: [PATCH 2/8] ws-3d2/step: cad/step (ISO 10303-21 read/write + injected B-rep plug-in) - src/Formats/cad/step: Part 21 editions 1-3 parsed into Types.Cad fully in-library (header, named DATA sections, complex instances, every parameter kind, string escapes to UTF-8, comments, ANCHOR/REFERENCE/SIGNATURE kept raw); writer round-trips at the entity level (integral reals keep their real-ness via a list metatable mark). - B-rep plug-in: a small injected table { read, write, tessellate } (or brep-luau's { Step, StepBrep, StepWrite, Tess } as is), taken from opts.brep / opts.plugins.brep; Step.toBodies / fromBodies / tessellate (-> Scene, z up, mm). - Types.luau: StepEntity gains optional parts (complex instances) and section (edition 3); backward compatible. - init.luau (api): withHooks also passes opts.plugins = F.plugins to decoders/encoders unless given; new facades F.cad.toBodies / fromBodies / tessellate (pass F.plugins, pcall, Err-wrapped). Backward compatible. - tests/cad/step.luau + tools/fixtures/step.py: OCCT (gmsh) generated and public STEP files, Python census, OCCT reads our output back, brep-luau through a generated tests/gen/.luaurc alias (luau only), fuzz. - tools/bench.luau: step parse / write lines. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/Types.luau | 4 +- src/Formats/cad/step/Brep.luau | 248 +++++++++++++ src/Formats/cad/step/Parse.luau | 573 +++++++++++++++++++++++++++++++ src/Formats/cad/step/Write.luau | 252 ++++++++++++++ src/Formats/cad/step/init.luau | 412 ++++++++++++++++++++++ src/Formats/init.luau | 31 +- tests/cad/step.luau | 392 +++++++++++++++++++++ tools/bench.luau | 19 + tools/fixtures/_step_encode.luau | 27 ++ tools/fixtures/step.py | 185 ++++++++++ 12 files changed, 2154 insertions(+), 2 deletions(-) create mode 100644 src/Formats/cad/step/Brep.luau create mode 100644 src/Formats/cad/step/Parse.luau create mode 100644 src/Formats/cad/step/Write.luau create mode 100644 src/Formats/cad/step/init.luau create mode 100644 tests/cad/step.luau create mode 100644 tools/fixtures/_step_encode.luau create mode 100644 tools/fixtures/step.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 40e275f..0d46299 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -26,6 +26,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | +| cad | step | .step .stp .p21 | yes | yes | complexEntities: true, sections: true, brep: "plugin", tessellate: "plugin" | `tests/cad/step.luau` | | font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` | | font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` | | font | woff | .woff | yes | - | outlines: "truetype", "cff" | `tests/font/woff.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d514aa9..1cbc445 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -266,6 +266,18 @@ local list: { Entry } = { return require("@formats/model/vox") end, }, + { + name = "step", + category = "cad", + path = "cad/step", + extensions = { "step", "stp", "p21" }, + mime = { "model/step", "application/step", "application/p21" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, + load = function() + return require("@formats/cad/step") + end, + }, { name = "bmfont", category = "font", diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 6464e98..66eeba6 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -561,7 +561,9 @@ end -- ------------------------------------------------------------------------------------------------ Cad -- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Formats.plugins.brep) -export type StepEntity = { id: number, type: string, args: { any } } +-- complex (external mapping) instances: type = "COMPLEX", args = {}, parts = { { type, args } } in file order; +-- section = the DATA section index when a file has more than one (edition 3) +export type StepEntity = { id: number, type: string, args: { any }, parts: { { type: string, args: { any } } }?, section: number? } export type Cad = { kind: "cad", schema: string, -- "AP203", "AP214", "AP242", ... diff --git a/src/Formats/cad/step/Brep.luau b/src/Formats/cad/step/Brep.luau new file mode 100644 index 0000000..2d44ef7 --- /dev/null +++ b/src/Formats/cad/step/Brep.luau @@ -0,0 +1,248 @@ +--!strict +-- cad/step/Brep: the injected B-rep plug-in (Formats.plugins.brep; formats-luau never requires a kernel). Normalises +-- the plug-in table, calls it under pcall (kernels throw on bad geometry) and turns its tessellated meshes into a +-- Scene. Interpreted on purpose: the plug-in's errors unwind through here. +-- +-- The interface (every function may throw; results are checked): +-- read(text: string, opts) -> { bodies = { Body }, stats = { ... }? } STEP text -> B-rep bodies (body.name?, +-- body.color? = Color3 | { r, g, b } | { 1, 2, 3 }) +-- write(bodies: { Body }, opts) -> string bodies -> STEP text +-- tessellate(body: Body, opts) -> { positions = { vector | {x, y, z} }, normals = { ... }?, indices = { 1-based +-- triples }, faceOf = { [triangle] = Face (face.color?) }? } +-- or brep-luau's modules as they are: { Step = , StepBrep = , StepWrite = , Tess = } (adapted here: read = +-- StepBrep.read(Step.parse(text)), write = StepWrite.write with options.colors from body.color, tessellate = Tess.body). +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") + +local Brep = {} + +export type Plugin = { + read: (text: string, opts: any) -> any, + write: ((bodies: { any }, opts: any) -> string)?, + tessellate: ((body: any, opts: any) -> any)?, +} + +local function rgbOf(c: any): (number?, number?, number?) + if c == nil then + return nil, nil, nil + end + local ok, r, g, b = pcall(function(): (any, any, any) + if type(c) == "table" then + return c.r or c.R or c[1], c.g or c.G or c[2], c.b or c.B or c[3] + end + return (c :: any).R, (c :: any).G, (c :: any).B -- Color3 + end) + if ok and type(r) == "number" and type(g) == "number" and type(b) == "number" then + return r, g, b + end + return nil, nil, nil +end + +-- plugin(p) -> the normalised interface, or nil + the reason +function Brep.plugin(p: any): (Plugin?, string?) + if type(p) ~= "table" then + return nil, "needs the B-rep plug-in (Formats.plugins.brep = { read, write, tessellate }, e.g. brep-luau's { Step, StepBrep, StepWrite, Tess })" + end + if type(p.read) == "function" then + return { + read = p.read, + write = if type(p.write) == "function" then p.write else nil, + tessellate = if type(p.tessellate) == "function" then p.tessellate else nil, + }, nil + end + local S, SB, SW, Tess = p.Step, p.StepBrep, p.StepWrite, p.Tess + if type(S) == "table" and type(SB) == "table" and type(S.parse) == "function" and type(SB.read) == "function" then + return { + read = function(text: string, opts: any): any + return SB.read(S.parse(text), opts) + end, + write = if type(SW) == "table" and type(SW.write) == "function" + then function(bodies: { any }, opts: any): string + local o = if type(opts) == "table" then table.clone(opts) else {} + if o.colors == nil then + local colors = {} + for i, b in bodies do + local r, g, bl = rgbOf(type(b) == "table" and b.color or nil) + if r then + colors[i] = { r, g, bl } + end + end + o.colors = colors + end + return SW.write(bodies, o) + end + else nil, + tessellate = if type(Tess) == "table" and type(Tess.body) == "function" + then function(body: any, opts: any): any + return Tess.body(body, opts) + end + else nil, + }, nil + end + return nil, "the B-rep plug-in has neither read() nor brep-luau's Step + StepBrep modules" +end + +-- find(opts) -> the plug-in from opts.brep or opts.plugins.brep +function Brep.find(opts: any): (Plugin?, Err.Err?) + local p = nil + if type(opts) == "table" then + p = opts.brep + if p == nil and type(opts.plugins) == "table" then + p = opts.plugins.brep + end + end + local plug, why = Brep.plugin(p) + if not plug then + return nil, Err.new(Err.UNSUPPORTED, why :: string) + end + return plug, nil +end + +-- read(plug, text, opts) -> bodies, result | nil, Err +function Brep.read(plug: Plugin, text: string, opts: any): (({ any })?, any, Err.Err?) + local ok, res = pcall(plug.read, text, opts) + if not ok then + return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to read: " .. tostring(res)) + end + if type(res) ~= "table" or type(res.bodies) ~= "table" then + return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in's read returned no bodies") + end + return res.bodies, res, nil +end + +-- write(plug, bodies, opts) -> text | nil, Err +function Brep.write(plug: Plugin, bodies: { any }, opts: any): (string?, Err.Err?) + local w = plug.write + if not w then + return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no write()") + end + local ok, res = pcall(w, bodies, opts) + if not ok then + return nil, Err.new(Err.ARG, "the B-rep plug-in failed to write: " .. tostring(res)) + end + if type(res) ~= "string" then + return nil, Err.new(Err.ARG, "the B-rep plug-in's write returned no text") + end + return res, nil +end + +local function xyz(p: any): (number, number, number) + if type(p) == "table" then + return tonumber(p.x or p.X or p[1]) or 0, tonumber(p.y or p.Y or p[2]) or 0, tonumber(p.z or p.Z or p[3]) or 0 + end + return (p :: any).X, (p :: any).Y, (p :: any).Z -- vector / Vector3 +end + +local function linear(c: number): number + c = math.clamp(c, 0, 1) + return if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4 +end + +-- scene(plug, bodies, opts) -> Scene: one node + mesh per body, one primitive per face colour (materials shared by +-- colour; baseColor = the STEP colour converted from sRGB to linear, extras.color = the colour as written) +function Brep.scene(plug: Plugin, bodies: { any }, opts: any): (Types.Scene?, Err.Err?) + local tess = plug.tessellate + if not tess then + return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no tessellate()") + end + local scene = Types.Scene.new() + scene.meta.up = "z" + scene.meta.unit = 0.001 + local tessOpts = if type(opts) == "table" and type(opts.tess) == "table" + then opts.tess + else { chord = if type(opts) == "table" and type(opts.chord) == "number" then opts.chord else 0.05 } + local matByKey: { [string]: number } = {} + local function material(r: number?, g: number?, b: number?): number + local key = if r then string.format("%.6f,%.6f,%.6f", r, g :: number, b :: number) else "default" + local m = matByKey[key] + if m then + return m + end + local mat = Types.Scene.material(if r then "step_" .. #scene.materials + 1 else "default") + if r then + mat.baseColor = { linear(r), linear(g :: number), linear(b :: number), 1 } + mat.extras = { color = { r, g, b } } + else + mat.baseColor = { 0.6, 0.6, 0.6, 1 } + end + mat.metallic, mat.roughness = 0, 0.5 + table.insert(scene.materials, mat) + matByKey[key] = #scene.materials + return #scene.materials + end + for bi, body in bodies do + local ok, mesh = pcall(tess, body, tessOpts) + if not ok then + return nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to tessellate body " .. bi .. ": " .. tostring(mesh)) + end + if type(mesh) ~= "table" or type(mesh.positions) ~= "table" or type(mesh.indices) ~= "table" then + return nil, Err.new(Err.CORRUPT, "the B-rep plug-in's tessellate returned no mesh") + end + local cok, prims = pcall(function(): { Types.Primitive } + local P, N, I = mesh.positions, mesh.normals, mesh.indices + local nv = #P + local pos = Types.Scene.accessor(nil, "f32", 3, nv) + local nrm = if type(N) == "table" and #N == nv then Types.Scene.accessor(nil, "f32", 3, nv) else nil + for i = 1, nv do + local x, y, z = xyz(P[i]) + buffer.writef32(pos.data, (i - 1) * 12, x) + buffer.writef32(pos.data, (i - 1) * 12 + 4, y) + buffer.writef32(pos.data, (i - 1) * 12 + 8, z) + if nrm then + local a, b, c = xyz(N[i]) + buffer.writef32(nrm.data, (i - 1) * 12, a) + buffer.writef32(nrm.data, (i - 1) * 12 + 4, b) + buffer.writef32(nrm.data, (i - 1) * 12 + 8, c) + end + end + local br, bg, bb = rgbOf(type(body) == "table" and body.color or nil) + -- triangles grouped by colour, in first-seen order + local groups: { { mat: number, tris: { number } } } = {} + local byMat: { [number]: { mat: number, tris: { number } } } = {} + local faceOf = if type(mesh.faceOf) == "table" then mesh.faceOf else {} + local nt = #I // 3 + for t = 1, nt do + local f = faceOf[t] + local r, g, b = rgbOf(type(f) == "table" and f.color or nil) + if not r then + r, g, b = br, bg, bb + end + local m = material(r, g, b) + local grp = byMat[m] + if not grp then + grp = { mat = m, tris = {} } + byMat[m] = grp + table.insert(groups, grp) + end + table.insert(grp.tris, t) + end + local out: { Types.Primitive } = {} + for _, grp in groups do + local idx = Types.Scene.accessor(nil, "u32", 1, #grp.tris * 3) + for k, t in grp.tris do + for c = 0, 2 do + local v = (tonumber(I[(t - 1) * 3 + c + 1]) or 1) - 1 + buffer.writeu32(idx.data, ((k - 1) * 3 + c) * 4, math.clamp(v, 0, math.max(nv - 1, 0))) + end + end + local attrs: { [string]: Types.Accessor } = { POSITION = pos } + if nrm then + attrs.NORMAL = nrm + end + table.insert(out, { attributes = attrs, indices = idx, mode = "triangles" :: any, material = grp.mat }) + end + return out + end) + if not cok then + return nil, Err.new(Err.CORRUPT, "bad tessellation of body " .. bi .. ": " .. tostring(prims)) + end + local name = if type(body) == "table" and type(body.name) == "string" then body.name else "body_" .. bi + table.insert(scene.meshes, { name = name, primitives = prims }) + table.insert(scene.nodes, { name = name, children = {}, mesh = #scene.meshes }) + table.insert(scene.roots, #scene.nodes) + end + scene.meta.source = { format = "step", tessellated = true, bodies = #bodies } + return scene, nil +end + +return Brep diff --git a/src/Formats/cad/step/Parse.luau b/src/Formats/cad/step/Parse.luau new file mode 100644 index 0000000..1a86bf3 --- /dev/null +++ b/src/Formats/cad/step/Parse.luau @@ -0,0 +1,573 @@ +--!strict +--!native +-- cad/step/Parse: ISO 10303-21 (STEP physical file, editions 1-3) text -> header + entity instances. A single pass +-- over the text: comments, the HEADER section, any number of DATA sections (edition 3 `DATA('name', ('schema'));`), +-- ANCHOR / REFERENCE / SIGNATURE sections kept as raw text, simple and complex (external mapping) instances, every +-- parameter kind (integer, real, string with its \S\ \X\ \X2\ \X4\ escapes decoded to UTF-8, enumeration, binary, +-- entity reference, $, *, list, typed parameter). Never throws: failures return nil, message, offset. +-- +-- Values: numbers; strings; { enum = "T" }; { ref = 12 }; { binary = "0FF" }; { typed = "LENGTH_MEASURE", value = v }; +-- lists as arrays; NULL / DERIVED sentinels (from the caller). A real literal with an integral value (`0.`, `1.E2`) +-- is recorded in the metatable of the list (or typed table) holding it (`__reals = { [index | "value"] = true }`), so +-- the writer prints it back as a real; integral numbers without that mark are written as integers. +local Parse = {} + +local sbyte, ssub, sfind, schar, floor = string.byte, string.sub, string.find, string.char, math.floor + +local MAX_DEPTH = 100 + +export type Ctx = { + s: string, + n: number, + err: string?, + errAt: number?, + null: any, + derived: any, +} + +local function fail(ctx: Ctx, msg: string, at: number): nil + if not ctx.err then + ctx.err, ctx.errAt = msg, at + end + return nil +end + +-- the next position that is not white space or inside a /* comment */ (n + 1 at the end; an open comment -> error) +local function skip(ctx: Ctx, i: number): number + local s, n = ctx.s, ctx.n + while i <= n do + local c = sbyte(s, i) + if c == 32 or c == 10 or c == 13 or c == 9 or c == 12 then + i += 1 + elseif c == 47 and sbyte(s, i + 1) == 42 then + local _, e = sfind(s, "*/", i + 2, true) + if not e then + fail(ctx, "unterminated comment", i) + return n + 1 + end + i = e + 1 + else + return i + end + end + return i +end + +local function isAlpha(c: number): boolean + return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 +end +local function isWord(c: number): boolean + return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or (c >= 48 and c <= 57) +end + +-- keyword at i ([!]A-Z_ A-Z0-9_*) -> word, next; nil when there is none +local function keyword(ctx: Ctx, i: number): (string?, number) + local s, n = ctx.s, ctx.n + local j = i + if j <= n and sbyte(s, j) == 33 then -- '!' user-defined + j += 1 + end + if j > n or not isAlpha(sbyte(s, j) :: number) then + return nil, i + end + j += 1 + while j <= n and isWord(sbyte(s, j) :: number) do + j += 1 + end + return string.upper(ssub(s, i, j - 1)), j +end + +-- UTF-8 of a code point +local function utf8char(cp: number): string + if cp < 0x80 then + return schar(cp) + elseif cp < 0x800 then + return schar(0xC0 + floor(cp / 64), 0x80 + cp % 64) + elseif cp < 0x10000 then + return schar(0xE0 + floor(cp / 4096), 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64) + elseif cp < 0x110000 then + return schar(0xF0 + floor(cp / 262144), 0x80 + floor(cp / 4096) % 64, 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64) + end + return "\239\191\189" +end +Parse.utf8char = utf8char + +local function hexAt(s: string, i: number, k: number): number? + local h = ssub(s, i, i + k - 1) + if #h ~= k or sfind(h, "[^%x]") then + return nil + end + return tonumber(h, 16) +end + +-- the text between the quotes of a string literal -> its value ('' -> ', \\ -> \, \S\c, \X\hh, \X2\..\X0\, \X4\..\X0\, +-- \P?\ page switches ignored: every page reads as ISO 8859-1). Bytes >= 0x80 written raw (common, though not allowed) +-- pass through. +function Parse.unescape(raw: string): string + if not sfind(raw, "[\\']") then + return raw + end + local out = {} + local i, n = 1, #raw + local plain = 1 + while i <= n do + local c = sbyte(raw, i) + if c == 39 then -- '' -> ' + table.insert(out, ssub(raw, plain, i)) + i += 2 + plain = i + elseif c == 92 then + table.insert(out, ssub(raw, plain, i - 1)) + local d = sbyte(raw, i + 1) + if d == 92 then + table.insert(out, "\\") + i += 2 + elseif d == 83 and sbyte(raw, i + 2) == 92 and i + 3 <= n then -- \S\c + table.insert(out, utf8char(((sbyte(raw, i + 3) :: number) + 128) % 256)) + i += 4 + elseif d == 80 and sbyte(raw, i + 3) == 92 then -- \P?\ code page + i += 4 + elseif d == 88 and sbyte(raw, i + 2) == 92 then -- \X\hh + local h = hexAt(raw, i + 3, 2) + if h then + table.insert(out, utf8char(h)) + i += 5 + else + table.insert(out, "\\") + i += 1 + end + elseif d == 88 and (sbyte(raw, i + 2) == 50 or sbyte(raw, i + 2) == 52) and sbyte(raw, i + 3) == 92 then + local k = if sbyte(raw, i + 2) == 50 then 4 else 8 + local j = i + 4 + local hi: number? = nil + while j <= n do + if sbyte(raw, j) == 92 then + break + end + local cp = hexAt(raw, j, k) + if not cp then + break + end + if k == 4 and cp >= 0xD800 and cp < 0xDC00 then + hi = cp + elseif k == 4 and hi and cp >= 0xDC00 and cp < 0xE000 then + table.insert(out, utf8char(0x10000 + (hi - 0xD800) * 1024 + (cp - 0xDC00))) + hi = nil + else + table.insert(out, utf8char(cp)) + hi = nil + end + j += k + end + if ssub(raw, j, j + 3) == "\\X0\\" then + j += 4 + end + i = j + else + table.insert(out, "\\") + i += 1 + end + plain = i + else + i += 1 + end + end + table.insert(out, ssub(raw, plain, n)) + return table.concat(out) +end + +local function markReal(t: { [any]: any }, key: any) + local mt: any = getmetatable(t) + if not mt then + mt = { __reals = {} } + setmetatable(t, mt) + end + mt.__reals[key] = true +end + +-- one parameter at i -> value, next, integralReal (nil value + ctx.err on failure) +local value: (ctx: Ctx, i: number, depth: number) -> (any, number, boolean) + +local function list(ctx: Ctx, i: number, depth: number): ({ any }?, number) + -- i is just past "(" + local s = ctx.s + local out = {} + i = skip(ctx, i) + if sbyte(s, i) == 41 then + return out, i + 1 + end + local k = 0 + while true do + local v, j, intReal = value(ctx, i, depth + 1) + if v == nil then + return nil, j + end + k += 1 + out[k] = v + if intReal then + markReal(out, k) + end + j = skip(ctx, j) + local c = sbyte(s, j) + if c == 44 then + i = skip(ctx, j + 1) + elseif c == 41 then + return out, j + 1 + elseif c == nil then + return fail(ctx, "truncated list", j), j + else + return fail(ctx, "expected , or ) in a list", j), j + end + end +end +Parse.list = list + +value = function(ctx: Ctx, i: number, depth: number): (any, number, boolean) + if depth > MAX_DEPTH then + return fail(ctx, "lists nested too deeply", i), i, false + end + local s = ctx.s + i = skip(ctx, i) + local c = sbyte(s, i) + if c == nil then + return fail(ctx, "truncated parameter", i), i, false + elseif c == 35 then -- #ref + local _, e = sfind(s, "^%d+", i + 1) + if not e then + return fail(ctx, "bad entity reference", i), i, false + end + return { ref = tonumber(ssub(s, i + 1, e)) }, e + 1, false + elseif c == 39 then -- 'string' + local j = i + 1 + while true do + local q = sfind(s, "'", j, true) + if not q then + return fail(ctx, "unterminated string", i), i, false + end + if sbyte(s, q + 1) == 39 then + j = q + 2 + else + return Parse.unescape(ssub(s, i + 1, q - 1)), q + 1, false + end + end + elseif c == 36 then + return ctx.null, i + 1, false + elseif c == 42 then + return ctx.derived, i + 1, false + elseif c == 40 then + local l, j = list(ctx, i + 1, depth) + return l, j, false + elseif c == 46 then -- .ENUM. + local _, e = sfind(s, "^[%a_][%w_]*%.", i + 1) + if not e then + return fail(ctx, "bad enumeration", i), i, false + end + return { enum = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false + elseif c == 34 then -- "binary" + local _, e = sfind(s, "^[0-3]%x*\"", i + 1) + if not e then + return fail(ctx, "bad binary literal", i), i, false + end + return { binary = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false + elseif (c >= 48 and c <= 57) or c == 45 or c == 43 then + local _, e = sfind(s, "^[+-]?%d*%.?%d*[eE]?[+-]?%d*", i) + local tok = ssub(s, i, e :: number) + local num = tonumber(if c == 43 then ssub(tok, 2) else tok) + if num == nil then + -- "1.E" without digits and the like + local core = string.match(tok, "^[+-]?%d*%.?%d*") + num = core and tonumber(if c == 43 then ssub(core, 2) else core) + if num == nil then + return fail(ctx, "bad number", i), i, false + end + e = i + #(core :: string) - 1 + end + local real = sfind(tok, "[.eE]") ~= nil + local nv = num :: number + return nv, (e :: number) + 1, real and nv == floor(nv) and nv == nv + elseif isAlpha(c) or c == 33 then -- typed parameter NAME(value) + local word, j = keyword(ctx, i) + j = skip(ctx, j) + if word == nil or sbyte(s, j) ~= 40 then + return fail(ctx, "expected a parameter", i), i, false + end + local v, k, intReal = value(ctx, j + 1, depth + 1) + if v == nil then + return nil, k, false + end + k = skip(ctx, k) + if sbyte(s, k) ~= 41 then + return fail(ctx, "expected ) after a typed parameter", k), k, false + end + local t = { typed = word, value = v } + if intReal then + markReal(t, "value") + end + return t, k + 1, false + end + return fail(ctx, "unexpected character " .. string.format("%q", schar(c)), i), i, false +end +Parse.value = value + +-- the simple record at i: NAME(params) -> type, args, next +local function record(ctx: Ctx, i: number): (string?, { any }?, number) + local word, j = keyword(ctx, i) + if not word then + return fail(ctx, "expected an entity name", i), nil, i + end + j = skip(ctx, j) + if sbyte(ctx.s, j) ~= 40 then + return fail(ctx, "expected ( after " .. word, j), nil, j + end + local args, k = list(ctx, j + 1, 0) + if not args then + return nil, nil, k + end + return word, args, k +end + +-- expect(ctx, i, ch) -> next position after ch (skipping blanks), or nil +local function expect(ctx: Ctx, i: number, ch: number, what: string): number? + i = skip(ctx, i) + if sbyte(ctx.s, i) ~= ch then + if i > ctx.n then + return fail(ctx, "truncated: expected " .. what, i) + end + return fail(ctx, "expected " .. what, i) + end + return i + 1 +end + +local function at(s: string, i: number, word: string): boolean + return ssub(s, i, i + #word - 1) == word +end + +export type Result = { + header: { [string]: { any } }, + headerOrder: { string }, + entities: { [number]: any }, + count: number, + sections: { { name: any?, schema: any? } }, + extra: { { name: string, text: string } }, + duplicates: number, + terminated: boolean, +} + +-- parse(s, opts) -> Result | nil, message, offset (1-based position in s) +function Parse.parse(s: string, null: any, derived: any, maxEntities: number): (Result?, string?, number?) + local ctx: Ctx = { s = s, n = #s, err = nil, errAt = nil, null = null, derived = derived } + local res: Result = { + header = {}, + headerOrder = {}, + entities = {}, + count = 0, + sections = {}, + extra = {}, + duplicates = 0, + terminated = false, + } + local i = skip(ctx, 1) + if not at(s, i, "ISO-10303-21") then + return nil, "no ISO-10303-21 magic", i + end + local ni = expect(ctx, i + 12, 59, ";") + if not ni then + return nil, ctx.err, ctx.errAt + end + i = ni + local sawData = false + while true do + i = skip(ctx, i) + if ctx.err then + return nil, ctx.err, ctx.errAt + end + if i > ctx.n then + if not sawData then + return nil, "truncated: no DATA section", i + end + break + end + if at(s, i, "END-ISO-10303-21") then + res.terminated = true + local e = expect(ctx, i + 16, 59, ";") + if not e then + return nil, ctx.err, ctx.errAt + end + break + end + local word, j = keyword(ctx, i) + if word == "HEADER" then + local e = expect(ctx, j, 59, ";") + if not e then + return nil, ctx.err, ctx.errAt + end + i = e + while true do + i = skip(ctx, i) + if at(s, i, "ENDSEC") then + local e2 = expect(ctx, i + 6, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + i = e2 + break + end + if i > ctx.n then + return nil, "truncated header", i + end + local t, args, k = record(ctx, i) + if not t then + return nil, ctx.err, ctx.errAt + end + local e2 = expect(ctx, k, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + if res.header[t] == nil then + table.insert(res.headerOrder, t) + end + res.header[t] = args :: { any } + i = e2 + end + elseif word == "DATA" then + sawData = true + local sec: { name: any?, schema: any? } = {} + j = skip(ctx, j) + if sbyte(s, j) == 40 then + local params, k = list(ctx, j + 1, 0) + if not params then + return nil, ctx.err, ctx.errAt + end + sec.name, sec.schema = params[1], params[2] + j = k + end + table.insert(res.sections, sec) + local secIndex = #res.sections + local e = expect(ctx, j, 59, ";") + if not e then + return nil, ctx.err, ctx.errAt + end + i = e + while true do + i = skip(ctx, i) + if ctx.err then + return nil, ctx.err, ctx.errAt + end + local c = sbyte(s, i) + if c == nil then + return nil, "truncated: the DATA section has no ENDSEC", i + end + if c ~= 35 then + if at(s, i, "ENDSEC") then + local e2 = expect(ctx, i + 6, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + i = e2 + break + end + return nil, "expected an entity instance (#id = ...)", i + end + local _, idEnd = sfind(s, "^%d+", i + 1) + if not idEnd then + return nil, "bad entity instance name", i + end + local id = tonumber(ssub(s, i + 1, idEnd)) :: number + local k = expect(ctx, idEnd + 1, 61, "=") + if not k then + return nil, ctx.err, ctx.errAt + end + k = skip(ctx, k) + local ent: any + if sbyte(s, k) == 40 then -- complex instance (A(..) B(..)) + local parts = {} + k = skip(ctx, k + 1) + while sbyte(s, k) ~= 41 do + if k > ctx.n then + return nil, "truncated complex instance", k + end + local t, args, k2 = record(ctx, k) + if not t then + return nil, ctx.err, ctx.errAt + end + table.insert(parts, { type = t, args = args }) + k = skip(ctx, k2) + end + if #parts == 0 then + return nil, "empty complex instance", k + end + ent = { id = id, type = "COMPLEX", args = {}, parts = parts } + k += 1 + else + local t, args, k2 = record(ctx, k) + if not t then + return nil, ctx.err, ctx.errAt + end + ent = { id = id, type = t, args = args } + k = k2 + end + local e2 = expect(ctx, k, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + if secIndex > 1 then + ent.section = secIndex + end + if res.entities[id] then + res.duplicates += 1 + else + res.count += 1 + if res.count > maxEntities then + return nil, "LIMIT", i + end + end + res.entities[id] = ent + i = e2 + end + elseif word == "ANCHOR" or word == "REFERENCE" or word == "SIGNATURE" then + -- kept as raw text (to the ENDSEC outside strings) + local k = j + local stop: number? = nil + while k <= ctx.n do + local c = sbyte(s, k) + if c == 39 then + local q = k + 1 + while true do + local p = sfind(s, "'", q, true) + if not p then + return nil, "unterminated string", k + end + if sbyte(s, p + 1) == 39 then + q = p + 2 + else + k = p + 1 + break + end + end + elseif c == 69 and at(s, k, "ENDSEC") then + stop = k + break + else + k += 1 + end + end + if not stop then + return nil, "truncated " .. word .. " section", i + end + table.insert(res.extra, { name = word, text = ssub(s, j, stop - 1) }) + local e2 = expect(ctx, stop + 6, 59, ";") + if not e2 then + return nil, ctx.err, ctx.errAt + end + i = e2 + else + return nil, "unknown section " .. tostring(word), i + end + end + if not sawData then + return nil, "no DATA section", i + end + return res, nil, nil +end + +return Parse diff --git a/src/Formats/cad/step/Write.luau b/src/Formats/cad/step/Write.luau new file mode 100644 index 0000000..0045126 --- /dev/null +++ b/src/Formats/cad/step/Write.luau @@ -0,0 +1,252 @@ +--!strict +--!native +-- cad/step/Write: header + entity instances -> ISO 10303-21 text. Values as cad/step/Parse produces them; strings +-- re-escaped (' -> '', \ -> \\, UTF-8 outside printable ASCII -> \X2\..\X0\ / \X4\..\X0\, control bytes and invalid +-- UTF-8 -> \X\hh), reals printed with the fewest digits (15..17) that read back to the same double. Never throws: +-- failures return nil, message. +local Write = {} + +local sformat, sbyte, ssub, sfind, floor, huge = string.format, string.byte, string.sub, string.find, math.floor, math.huge + +local MAX_DEPTH = 100 + +-- the shortest %g form that reads back exactly, in Part 21 syntax (a '.' always, upper-case E) +function Write.real(v: number): string? + if v ~= v or v == huge or v == -huge then + return nil + end + local s = sformat("%.15g", v) + if tonumber(s) ~= v then + s = sformat("%.16g", v) + if tonumber(s) ~= v then + s = sformat("%.17g", v) + end + end + s = string.upper(s) + local e = sfind(s, "E", 1, true) + if not sfind(s, ".", 1, true) then + if e then + s = ssub(s, 1, e - 1) .. "." .. ssub(s, e) + else + s ..= "." + end + end + return s +end + +local HEX = "0123456789ABCDEF" +local function hex(v: number, k: number): string + local out = table.create(k) + for i = k, 1, -1 do + local d = v % 16 + out[i] = ssub(HEX, d + 1, d + 1) + v = floor(v / 16) + end + return table.concat(out) +end + +-- a string's Part 21 literal (with the quotes) +function Write.str(s: string): string + if not sfind(s, "[^ -&(-[%]^-~]") then -- printable ASCII without ' and \ + return "'" .. s .. "'" + end + local out = { "'" } + local i, n = 1, #s + local wide: number? = nil -- 4 (\X2\) or 8 (\X4\) while in an extended run + local function close() + if wide then + table.insert(out, "\\X0\\") + wide = nil + end + end + while i <= n do + local c = sbyte(s, i) :: number + if c >= 32 and c < 127 then + close() + if c == 39 then + table.insert(out, "''") + elseif c == 92 then + table.insert(out, "\\\\") + else + table.insert(out, string.char(c)) + end + i += 1 + else + -- a UTF-8 sequence -> code point + local cp: number? = nil + local len = 1 + if c >= 0xC2 and c < 0xE0 then + local c2 = sbyte(s, i + 1) + if c2 and c2 >= 0x80 and c2 < 0xC0 then + cp, len = (c - 0xC0) * 64 + (c2 - 0x80), 2 + end + elseif c >= 0xE0 and c < 0xF0 then + local c2, c3 = sbyte(s, i + 1, i + 2) + if c2 and c3 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 then + local v = (c - 0xE0) * 4096 + (c2 - 0x80) * 64 + (c3 - 0x80) + if v >= 0x800 and (v < 0xD800 or v >= 0xE000) then + cp, len = v, 3 + end + end + elseif c >= 0xF0 and c < 0xF5 then + local c2, c3, c4 = sbyte(s, i + 1, i + 3) + if c2 and c3 and c4 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 and c4 >= 0x80 and c4 < 0xC0 then + local v = (c - 0xF0) * 262144 + (c2 - 0x80) * 4096 + (c3 - 0x80) * 64 + (c4 - 0x80) + if v >= 0x10000 and v < 0x110000 then + cp, len = v, 4 + end + end + end + if cp == nil then + close() + table.insert(out, "\\X\\" .. hex(c, 2)) + i += 1 + else + local k = if cp >= 0x10000 then 8 else 4 + if wide ~= k then + close() + table.insert(out, if k == 4 then "\\X2\\" else "\\X4\\") + wide = k + end + table.insert(out, hex(cp, k)) + i += len + end + end + end + close() + table.insert(out, "'") + return table.concat(out) +end + +local function isName(s: any): boolean + return type(s) == "string" and sfind(s, "^!?[%a_][%w_]*$") ~= nil +end +Write.isName = isName + +export type Ctx = { out: { string }, null: any, derived: any, err: string? } + +local value: (ctx: Ctx, v: any, real: boolean, depth: number) -> boolean + +local function reals(t: any): { [any]: boolean }? + local mt = getmetatable(t) + return if type(mt) == "table" and type(mt.__reals) == "table" then mt.__reals else nil +end + +local function list(ctx: Ctx, t: { any }, depth: number): boolean + local out = ctx.out + table.insert(out, "(") + local marks = reals(t) + local n = #t + for i = 1, n do + if i > 1 then + table.insert(out, ",") + end + if not value(ctx, t[i], marks ~= nil and marks[i] == true, depth + 1) then + return false + end + end + table.insert(out, ")") + return true +end +Write.list = list + +value = function(ctx: Ctx, v: any, real: boolean, depth: number): boolean + local out = ctx.out + if depth > MAX_DEPTH then + ctx.err = "values nested too deeply (or a cycle)" + return false + end + local tv = type(v) + if tv == "number" then + if not real and v == floor(v) and v > -2 ^ 53 and v < 2 ^ 53 then + table.insert(out, sformat("%.0f", v)) + return true + end + local r = Write.real(v) + if not r then + ctx.err = "a number that STEP cannot hold (nan / inf)" + return false + end + table.insert(out, r) + return true + elseif tv == "string" then + table.insert(out, Write.str(v)) + return true + elseif tv == "boolean" then + table.insert(out, if v then ".T." else ".F.") + return true + elseif tv == "table" then + if v == ctx.null then + table.insert(out, "$") + return true + elseif v == ctx.derived then + table.insert(out, "*") + return true + end + local ref = v.ref + if ref ~= nil then + if type(ref) ~= "number" or ref ~= floor(ref) or ref < 0 then + ctx.err = "bad entity reference " .. tostring(ref) + return false + end + table.insert(out, sformat("#%.0f", ref)) + return true + end + local enum = v.enum + if enum ~= nil then + if type(enum) ~= "string" or not sfind(enum, "^[%a_][%w_]*$") then + ctx.err = "bad enumeration " .. tostring(enum) + return false + end + table.insert(out, "." .. string.upper(enum) .. ".") + return true + end + local bin = v.binary + if bin ~= nil then + if type(bin) ~= "string" or not sfind(bin, "^[0-3]%x*$") then + ctx.err = "bad binary literal" + return false + end + table.insert(out, "\"" .. string.upper(bin) .. "\"") + return true + end + local typed = v.typed + if typed ~= nil then + if not isName(typed) then + ctx.err = "bad typed parameter name " .. tostring(typed) + return false + end + if v.value == nil then + ctx.err = "typed parameter " .. typed .. " without a value" + return false + end + local marks = reals(v) + table.insert(out, string.upper(typed) .. "(") + if not value(ctx, v.value, marks ~= nil and marks.value == true, depth + 1) then + return false + end + table.insert(out, ")") + return true + end + return list(ctx, v, depth) + end + ctx.err = "cannot write a " .. tv .. " value" + return false +end +Write.value = value + +-- record(ctx, type, args) -> appends TYPE(args) +function Write.record(ctx: Ctx, t: any, args: any): boolean + if not isName(t) then + ctx.err = "bad entity type " .. tostring(t) + return false + end + if type(args) ~= "table" then + ctx.err = "entity " .. t .. " without an args list" + return false + end + table.insert(ctx.out, string.upper(t)) + return list(ctx, args, 0) +end + +return Write diff --git a/src/Formats/cad/step/init.luau b/src/Formats/cad/step/init.luau new file mode 100644 index 0000000..1062a7a --- /dev/null +++ b/src/Formats/cad/step/init.luau @@ -0,0 +1,412 @@ +--!strict +-- cad/step: STEP physical files (ISO 10303-21 editions 1-3, "Part 21": AP203 / AP214 / AP242 and any other schema). +-- New code. Reads and writes the entity graph (Types.Cad) fully in-library: the header (FILE_DESCRIPTION / FILE_NAME / +-- FILE_SCHEMA + any other header entity), every DATA section (edition 3 named sections: entity.section), simple and +-- complex instances (type "COMPLEX", parts = { { type, args } }), every parameter kind: integers and reals (numbers; +-- integral reals such as `0.` keep their real-ness through a metatable mark, see Parse), strings (escapes decoded to +-- UTF-8: \S\ \X\ \X2\ \X4\, '' and \\), { enum = "T" } (.T. / .F. booleans too), { ref = id }, { binary = "0FF" }, +-- { typed = "LENGTH_MEASURE", value = v }, lists, Step.NULL ($) and Step.DERIVED (*), comments; ANCHOR / REFERENCE / +-- SIGNATURE sections kept as raw text (meta.source.extra) and written back. parse -> write -> parse gives the same +-- entities. Writes one instance per line in id order, strings escaped as Part 21 requires (\X2\ for non-ASCII). +-- +-- B-rep bodies and tessellation come from an injected kernel, never required by formats-luau: +-- F.plugins.brep = { read = fn(text, opts) -> { bodies, stats? }, write = fn(bodies, opts) -> text, +-- tessellate = fn(body, opts) -> { positions, normals?, indices (1-based), faceOf? } } +-- or brep-luau's modules as they are: F.plugins.brep = { Step = , StepBrep = , StepWrite = , Tess = } +-- (the full contract is in cad/step/Brep). Step.toBodies(cad, opts) / Step.fromBodies(bodies, opts) / +-- Step.tessellate(cad | bodies, opts) take it from opts.brep or opts.plugins.brep; F.cad.toBodies / fromBodies / +-- tessellate pass F.plugins. Tessellated scenes: one node + mesh per body, one primitive per face colour, z up, +-- millimetres (meta.unit = 0.001). +-- Not supported: STEP-XML (ISO 10303-28), compressed .stpZ, edition 3 value instances (#NAME, @constants: CORRUPT), +-- code pages other than ISO 8859-1 in \S\ escapes (\P?\ is ignored). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Parse = require("@formats/cad/step/Parse") +local Write = require("@formats/cad/step/Write") +local Brep = require("@formats/cad/step/Brep") + +-- ------------------------------------------------------------------------------------------------ contract +local Step = { + name = "step", + category = "cad", + extensions = { "step", "stp", "p21" }, + mime = { "model/step", "application/step", "application/p21" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxBytes: number?, -- refuse larger files (default 2^30) + maxEntities: number?, -- refuse more instances (default 2^24) +} +export type EncodeOptions = { + schema: string?, -- "AP203" | "AP214" | "AP242" | a schema name: overrides the header's FILE_SCHEMA + name: string?, -- FILE_NAME name (default: the header's, else "model") + timestamp: string?, -- FILE_NAME time_stamp when the header has none (default "1970-01-01T00:00:00") + crlf: boolean?, -- CRLF line ends (default LF) +} +export type BrepOptions = { + brep: any?, -- the plug-in (else opts.plugins.brep) + plugins: { [string]: any }?, + chord: number?, -- tessellation sag in millimetres (default 0.05); opts.tess = the kernel's own options instead + tess: { [string]: any }?, +} + +-- ------------------------------------------------------------------------------------------------ constants +Step.NULL = table.freeze({ null = true }) -- $ +Step.DERIVED = table.freeze({ derived = true }) -- * + +local SCHEMAS = { + AP203 = "CONFIG_CONTROL_DESIGN", + AP214 = "AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }", + AP242 = "AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }", +} +Step.SCHEMAS = SCHEMAS + +-- a FILE_SCHEMA name -> "AP203" | "AP214" | "AP242" | the name itself +local function schemaOf(name: string): string + local n = string.upper(string.match(name, "^%s*([^%s{]+)") or name) + if n == "CONFIG_CONTROL_DESIGN" or string.find(n, "^AP203") then + return "AP203" + elseif n == "AUTOMOTIVE_DESIGN" or n == "AUTOMOTIVE_DESIGN_CC2" or string.find(n, "^AP214") then + return "AP214" + elseif string.find(n, "^AP242") then + return "AP242" + end + return n +end +Step.schemaOf = schemaOf + +-- ------------------------------------------------------------------------------------------------ sniff +function Step.sniff(r: Bytes.Reader): number + local head = r:peek(256) + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + head = string.gsub(head, "^%s*/%*.-%*/", "") + if string.find(head, "^%s*ISO%-10303%-21%s*;") then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Step.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Cad?, Err.Err?) + local size = r.limit - r.base + if size > (opts and opts.maxBytes or 2 ^ 30) then + return nil, Err.new(Err.LIMIT, "file over maxBytes") + end + local s = buffer.readstring(r.buf, r.base, size) + local bom = 0 + if string.sub(s, 1, 3) == "\239\187\191" then + s = string.sub(s, 4) + bom = 3 + end + local res, msg, at = Parse.parse(s, Step.NULL, Step.DERIVED, opts and opts.maxEntities or 2 ^ 24) + if not res then + local off = if at then r.base + bom + at - 1 else nil + if msg == "LIMIT" then + return nil, Err.new(Err.LIMIT, "more entity instances than maxEntities", off) + end + local m = msg or "parse error" + if string.find(m, "^truncated") or string.find(m, "^unterminated") or (at and at > #s) then + return nil, Err.new(Err.TRUNCATED, m, off) + end + return nil, Err.new(Err.CORRUPT, m, off) + end + local fs = res.header.FILE_SCHEMA + local schemaName = if fs and type(fs[1]) == "table" and type(fs[1][1]) == "string" then fs[1][1] else "" + local cad: Types.Cad = { + kind = "cad", + schema = if schemaName ~= "" then schemaOf(schemaName) else "unknown", + header = res.header, + entities = res.entities, + meta = { + count = res.count, + headerOrder = res.headerOrder, + source = { + format = "step", + schemaName = schemaName, + sections = res.sections, + extra = if #res.extra > 0 then res.extra else nil, + duplicates = if res.duplicates > 0 then res.duplicates else nil, + terminated = res.terminated, + }, + }, + } + return cad, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function headerArgs(cad: Types.Cad, o: EncodeOptions): { [string]: { any } } + local h = if type(cad.header) == "table" then cad.header else {} + local out: { [string]: { any } } = {} + for k, v in h do + out[k] = v + end + if type(out.FILE_DESCRIPTION) ~= "table" then + out.FILE_DESCRIPTION = { { "formats-luau" }, "2;1" } + end + if type(out.FILE_NAME) ~= "table" then + out.FILE_NAME = { o.name or "model", o.timestamp or "1970-01-01T00:00:00", { "" }, { "" }, "formats-luau", "formats-luau", "" } + end + local schema = o.schema or (if type(out.FILE_SCHEMA) ~= "table" then cad.schema else nil) + if schema then + out.FILE_SCHEMA = { { SCHEMAS[schema] or schema } } + end + return out +end + +function Step.encode(cad: Types.Cad, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(cad) ~= "table" or cad.kind ~= "cad" or type(cad.entities) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Cad (kind = \"cad\", entities)") + end + local o: EncodeOptions = opts or {} + local nl = if o.crlf then "\r\n" else "\n" + local ctx: Write.Ctx = { out = {}, null = Step.NULL, derived = Step.DERIVED, err = nil } + local out = ctx.out + table.insert(out, "ISO-10303-21;" .. nl .. "HEADER;" .. nl) + local header = headerArgs(cad, o) + local order = { "FILE_DESCRIPTION", "FILE_NAME", "FILE_SCHEMA" } + local seen = { FILE_DESCRIPTION = true, FILE_NAME = true, FILE_SCHEMA = true } + local meta: any = if type(cad.meta) == "table" then cad.meta else {} + local rest = {} + for _, k in (if type(meta.headerOrder) == "table" then meta.headerOrder else {}) do + if type(k) == "string" and header[k] and not seen[k] then + seen[k] = true + table.insert(order, k) + end + end + for k in header do + if type(k) == "string" and not seen[k] then + table.insert(rest, k) + end + end + table.sort(rest) + for _, k in rest do + table.insert(order, k) + end + for _, k in order do + if not Write.record(ctx, k, header[k]) then + return nil, Err.new(Err.ARG, "header " .. tostring(k) .. ": " .. tostring(ctx.err)) + end + table.insert(out, ";" .. nl) + end + table.insert(out, "ENDSEC;" .. nl) + local source = if type(meta.source) == "table" then meta.source else {} + if type(source.extra) == "table" then + for _, x in source.extra do + if type(x) == "table" and type(x.name) == "string" and type(x.text) == "string" then + table.insert(out, x.name .. x.text .. "ENDSEC;" .. nl) + end + end + end + -- entities by section, in id order + local ids = {} + for id, e in cad.entities do + if type(id) ~= "number" or id ~= math.floor(id) or id < 0 or type(e) ~= "table" then + return nil, Err.new(Err.ARG, "entity ids must be non-negative integers (" .. tostring(id) .. ")") + end + table.insert(ids, id) + end + table.sort(ids) + local sections = if type(source.sections) == "table" and #source.sections > 1 then source.sections else { {} } + for si, sec in sections do + if #sections > 1 then + table.insert(out, "DATA") + local params = {} + if sec.name ~= nil then + params[1] = sec.name + params[2] = if sec.schema ~= nil then sec.schema else {} + if not Write.list(ctx, params, 0) then + return nil, Err.new(Err.ARG, "section " .. si .. ": " .. tostring(ctx.err)) + end + end + table.insert(out, ";" .. nl) + else + table.insert(out, "DATA;" .. nl) + end + for _, id in ids do + local e: any = cad.entities[id] + local esec = if type(e.section) == "number" then e.section else 1 + if #sections == 1 or esec == si or (si == 1 and (esec < 1 or esec > #sections)) then + table.insert(out, string.format("#%.0f=", id)) + if e.type == "COMPLEX" or type(e.parts) == "table" then + if type(e.parts) ~= "table" or #e.parts == 0 then + return nil, Err.new(Err.ARG, "#" .. id .. ": a complex instance without parts") + end + table.insert(out, "(") + for _, p in e.parts do + if type(p) ~= "table" or not Write.record(ctx, p.type, p.args) then + return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err or "bad part")) + end + end + table.insert(out, ")") + elseif not Write.record(ctx, e.type, e.args) then + return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err)) + end + table.insert(out, ";" .. nl) + end + end + table.insert(out, "ENDSEC;" .. nl) + end + table.insert(out, "END-ISO-10303-21;" .. nl) + return buffer.fromstring(table.concat(out)), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- get(cad, id | { ref = id }) -> the entity +function Step.get(cad: Types.Cad, id: any): Types.StepEntity? + if type(id) == "table" then + id = id.ref + end + return cad.entities[id] +end + +-- ids(cad) -> the instance ids in ascending order +function Step.ids(cad: Types.Cad): { number } + local out = {} + for id in cad.entities do + table.insert(out, id) + end + table.sort(out) + return out +end + +-- byType(cad, "ADVANCED_FACE") -> the ids of the instances of that type (complex ones with such a part too), ascending +function Step.byType(cad: Types.Cad, name: string): { number } + local n = string.upper(name) + local out = {} + for id, e in cad.entities do + if e.type == n then + table.insert(out, id) + elseif e.parts then + for _, p in e.parts do + if p.type == n then + table.insert(out, id) + break + end + end + end + end + table.sort(out) + return out +end + +-- part(entity, "TYPE") -> the args of that type (the entity's own, or one part of a complex instance) +function Step.part(e: Types.StepEntity?, name: string): { any }? + if not e then + return nil + end + if e.type == name then + return e.args + end + if e.parts then + for _, p in e.parts do + if p.type == name then + return p.args + end + end + end + return nil +end + +-- add(cad, type, args) -> id: a new instance after the highest id +function Step.add(cad: Types.Cad, type: string, args: { any }): number + local top = 0 + for id in cad.entities do + if id > top then + top = id + end + end + local id = top + 1 + cad.entities[id] = { id = id, type = string.upper(type), args = args } + cad.meta.count = (cad.meta.count or 0) + 1 + return id +end + +-- real(list, index) -> list: marks list[index] as a real (an integral value is then written `3.`, not `3`) +function Step.real(t: { [any]: any }, key: any): { [any]: any } + local mt: any = getmetatable(t) + if not mt then + mt = { __reals = {} } + setmetatable(t, mt) + end + mt.__reals[key] = true + return t +end + +-- new(schema?) -> an empty Cad ("AP214" by default) +function Step.new(schema: string?): Types.Cad + return { kind = "cad", schema = schema or "AP214", header = {}, entities = {}, meta = { count = 0 } } +end + +-- plugin(p) -> the normalised B-rep plug-in interface (see cad/step/Brep) | nil, reason +Step.plugin = Brep.plugin + +local function textOf(cad: Types.Cad): (string?, Err.Err?) + local buf, err = Step.encode(cad) + if not buf then + return nil, err + end + return buffer.tostring(buf), nil +end + +-- toBodies(cad, opts) -> bodies, result (the plug-in's read result: stats, warnings, ...) | nil, Err +function Step.toBodies(cad: Types.Cad, opts: BrepOptions?): (({ any })?, any) + local plug, perr = Brep.find(opts) + if not plug then + return nil, perr + end + local text, err = textOf(cad) + if not text then + return nil, err + end + local bodies, res, rerr = Brep.read(plug, text, opts) + if not bodies then + return nil, rerr + end + return bodies, res +end + +-- fromBodies(bodies, opts) -> Cad (the plug-in writes STEP text, parsed here) | nil, Err +function Step.fromBodies(bodies: { any }, opts: BrepOptions?): (Types.Cad?, Err.Err?) + if type(bodies) ~= "table" then + return nil, Err.new(Err.ARG, "needs a list of bodies") + end + local plug, perr = Brep.find(opts) + if not plug then + return nil, perr + end + local text, err = Brep.write(plug, bodies, opts) + if not text then + return nil, err + end + return Step.decode(Bytes.reader(buffer.fromstring(text))) +end + +-- tessellate(cad | bodies, opts) -> Scene (one node + mesh per body, z up, millimetres) | nil, Err +function Step.tessellate(value: any, opts: BrepOptions?): (Types.Scene?, Err.Err?) + local plug, perr = Brep.find(opts) + if not plug then + return nil, perr + end + local bodies = value + if type(value) == "table" and value.kind == "cad" then + local b, err = Step.toBodies(value, opts) + if not b then + return nil, err + end + bodies = b + end + if type(bodies) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Cad or a list of bodies") + end + return Brep.scene(plug, bodies, opts) +end + +return Step diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 19fd6c7..d4e6dbe 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -255,11 +255,15 @@ end -- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) -> -- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for -- the embedded parts) when called directly. +-- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own. local function withHooks(o: Options): Options - if o.decodeImage ~= nil and o.encodeImage ~= nil then + if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil then return o end local c = table.clone(o) + if c.plugins == nil then + c.plugins = F.plugins + end if c.decodeImage == nil then c.decodeImage = function(b: buffer): (any, Err.Err?) return F.load(b, { category = "image" }) @@ -539,6 +543,31 @@ for category in Types.CATEGORIES do end F.data.null = Types.null +-- F.cad.toBodies(cad, opts?) -> bodies, result | nil, Err; F.cad.fromBodies(bodies, opts?) -> Cad | nil, Err; +-- F.cad.tessellate(cad | bodies, opts?) -> Scene | nil, Err: cad/step's B-rep calls with the injected kernel +-- (F.plugins.brep, unless opts.brep / opts.plugins is given). Without a plug-in they return Err.UNSUPPORTED. +for _, fn in { "toBodies", "fromBodies", "tessellate" } do + local name: string = fn + F.cad[name] = function(value: any, opts: Options?): (any, any) + local o = if opts then table.clone(opts) else {} + if o.plugins == nil then + o.plugins = F.plugins + end + local m, err = F.format("step") + if not m then + return nil, err + end + local ok, a, b = pcall(m[name], value, o) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, name .. " threw: " .. tostring(a)), "step") + end + if a == nil and type(b) == "table" and b.code then + return nil, Err.wrap(b, "step") + end + return a, b + end +end + -- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or -- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images -- themselves (a format does not require another format); this is the lazy step at the api layer. Textures whose diff --git a/tests/cad/step.luau b/tests/cad/step.luau new file mode 100644 index 0000000..0ebfb4b --- /dev/null +++ b/tests/cad/step.luau @@ -0,0 +1,392 @@ +-- cad/step tests: STEP files written by OCCT (solids modelled in gmsh's OpenCASCADE kernel) and public sample files, +-- against an independent Python Part 21 census (instances, count per type); our writer's output read back by OCCT +-- (solids, volume, faces, area, bounding box equal to the originals); parse -> write -> parse equality; every +-- parameter kind and string escape, complex instances, edition 3 sections, comments; the api (F.load / F.save / +-- F.cad.*); the B-rep plug-in path through brep-luau (luau CLI only: the alias in tests/gen/.luaurc) against OCCT's +-- volumes and bounds, and a custom plug-in table; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/step.py. +local T = require("@tests/T") +local F = require("@formats") +local Step = require("@formats/cad/step") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Cases = require("@tests/gen/step_cases") + +local t = T.suite("step") + +local function decode(s: string, opts: any?): (any, any) + return Step.decode(Bytes.reader(buffer.fromstring(s)), opts) +end +local function encode(cad: any, opts: any?): string + local b, err = Step.encode(cad, opts) + t:check(b, "encode: " .. tostring(err)) + return if b then buffer.tostring(b) else "" +end +local function near(a: number, b: number, rel: number): boolean + return math.abs(a - b) <= rel * math.max(1, math.abs(a), math.abs(b)) +end + +-- 1. contract +t:eq(Step.name, "step", "name") +t:eq(Step.category, "cad", "category") +t:check(Step.caps.decode and Step.caps.encode and table.find(Step.extensions, "stp"), "contract") + +-- deep equality of two decoded values (buffers, the real marks of lists included) +local function same(a: any, b: any, path: string, depth: number?): (boolean, string) + local d = depth or 0 + if type(a) ~= "table" or type(b) ~= "table" then + return a == b, path + end + if a == b then + return true, path + end + if d > 60 then + return false, path .. " (too deep)" + end + for k, v in a do + local ok, where = same(v, b[k], path .. "." .. tostring(k), d + 1) + if not ok then + return false, where + end + end + for k in b do + if a[k] == nil then + return false, path .. "." .. tostring(k) .. " (extra)" + end + end + local ma, mb = getmetatable(a), getmetatable(b) + local ra = ma and ma.__reals or {} + local rb = mb and mb.__reals or {} + for k in ra do + if not rb[k] then + return false, path .. "[" .. tostring(k) .. "] real mark" + end + end + for k in rb do + if not ra[k] then + return false, path .. "[" .. tostring(k) .. "] real mark (extra)" + end + end + return true, path +end + +-- 2. fixtures: census, round trips; OCCT read our output like the original +local decoded = {} +local samples = {} +local t0 = T.clock() +local bytes = 0 +for i, c in Cases do + local cad, err = decode(c.data) + t:check(cad, c.name .. ": decode: " .. tostring(err)) + decoded[i] = cad + bytes += #c.data + t:eq(cad.meta.count, c.census.count, c.name .. ": instances (census)") + local types = {} + for _, e in cad.entities do + types[e.type] = (types[e.type] or 0) + 1 + end + for ty, n in c.census.types do + t:eq(types[ty], n, c.name .. ": " .. ty .. " count") + end + for ty in types do + t:check(c.census.types[ty], c.name .. ": no extra type " .. ty) + end + local text = encode(cad) + local again = decode(text) + t:check(again, c.name .. ": our output decodes") + local ok, where = same(cad.entities, again.entities, "entities") + t:check(ok, c.name .. ": round trip differs at " .. where) + t:eq(encode(again), text, c.name .. ": write is stable") + t:check(same(cad.header, again.header, "header"), c.name .. ": header round trip") + if c.occt and not c.occt.failed then + t:check(c.ours and not c.ours.failed, c.name .. ": OCCT reads our output") + t:eq(c.ours.solids, c.occt.solids, c.name .. ": OCCT solids of our output") + t:eq(c.ours.faces, c.occt.faces, c.name .. ": OCCT faces of our output") + t:check(near(c.ours.volume, c.occt.volume, 1e-9), c.name .. ": OCCT volume of our output") + t:check(near(c.ours.area, c.occt.area, 1e-9), c.name .. ": OCCT area of our output") + end + if #samples < 4 and #c.data < 40000 then + table.insert(samples, buffer.fromstring(c.data)) + end +end +local dt = T.clock() - t0 +t:note("%d files (%.1f MB): census, OCCT read-back, round trips (%.2f s)", #Cases, bytes / 1e6, dt) + +-- 3. every parameter kind, escapes, complex instances, sections, comments +local CRAFT = [[ +ISO-10303-21; /* a comment */ +HEADER; +FILE_DESCRIPTION(('test'),'2;1'); +FILE_NAME('craft.stp','2024-01-01T00:00:00',('A \X2\00C9\X0\crivain'),(''),'','',''); +FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }')); +ENDSEC; +DATA; +#1=CARTESIAN_POINT('',(0.,1.5,-2.E-3)); +#2 = DIRECTION ( 'd' , ( 1. , 0. , 0. ) ) ; +#3=FOO('It''s','back\\slash','\S\i','\X\E9t\X\E9','\X2\03B103B2\X0\ ok','\X4\0001F600\X0\',.T.,.UNSPECIFIED.,$,*,#1, + "0FF",LENGTH_MEASURE(2.),POSITIVE_LENGTH_MEASURE(3.5),(1,2,(3,4.)),(),-7,+8,1.E2); +#10=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNIT_ASSIGNED_CONTEXT((#11))REPRESENTATION_CONTEXT('c','3D')); +#11=(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.)); +/* comment between instances */ +#12=!USER_DEFINED(1); +ENDSEC; +END-ISO-10303-21; +]] +local cad, err = decode(CRAFT) +t:check(cad, "craft: " .. tostring(err)) +t:eq(cad.schema, "AP214", "craft: schema") +t:eq(cad.meta.count, 6, "craft: count") +t:eq(cad.header.FILE_NAME[3][1], "A Écrivain", "craft: header \\X2\\") +local p = cad.entities[1] +t:eq(p.type, "CARTESIAN_POINT", "craft: type") +t:eq(p.args[2][3], -2e-3, "craft: real") +t:check(getmetatable(p.args[2]).__reals[1] and getmetatable(p.args[2]).__reals[2] == nil, "craft: integral real marked") +t:eq(cad.entities[2].args[1], "d", "craft: spaced instance") +local a = cad.entities[3].args +t:eq(a[1], "It's", "craft: ''") +t:eq(a[2], "back\\slash", "craft: \\\\") +t:eq(a[3], "é", "craft: \\S\\") +t:eq(a[4], "été", "craft: \\X\\") +t:eq(a[5], "αβ ok", "craft: \\X2\\") +t:eq(a[6], "😀", "craft: \\X4\\") +t:eq(a[7].enum, "T", "craft: boolean") +t:eq(a[8].enum, "UNSPECIFIED", "craft: enum") +t:eq(a[9], Step.NULL, "craft: $") +t:eq(a[10], Step.DERIVED, "craft: *") +t:eq(a[11].ref, 1, "craft: ref") +t:eq(Step.get(cad, a[11]), p, "craft: get(ref)") +t:eq(a[12].binary, "0FF", "craft: binary") +t:eq(a[13].typed, "LENGTH_MEASURE", "craft: typed") +t:eq(a[13].value, 2, "craft: typed value") +t:eq(a[14].value, 3.5, "craft: typed real") +t:eq(a[15][3][2], 4, "craft: nested list") +t:eq(#a[16], 0, "craft: empty list") +t:eq(a[17], -7, "craft: negative integer") +t:eq(a[18], 8, "craft: +integer") +t:eq(a[19], 100, "craft: 1.E2") +local cx = cad.entities[10] +t:eq(cx.type, "COMPLEX", "craft: complex") +t:eq(#cx.parts, 3, "craft: complex parts") +t:eq(Step.part(cx, "GEOMETRIC_REPRESENTATION_CONTEXT")[1], 3, "craft: part()") +t:eq(Step.part(cad.entities[11], "SI_UNIT")[2].enum, "METRE", "craft: SI_UNIT part") +t:eq(cad.entities[12].type, "!USER_DEFINED", "craft: user-defined entity") +t:eq(#Step.byType(cad, "SI_UNIT"), 1, "craft: byType through complex parts") +local text = encode(cad) +t:check(string.find(text, "#3=FOO('It''s','back\\\\slash','\\X2\\00E9\\X0\\'", 1, true), "craft: strings re-escaped") +t:check(string.find(text, "'\\X4\\0001F600\\X0\\'", 1, true), "craft: \\X4\\ written") +t:check(string.find(text, "CARTESIAN_POINT('',(0.,1.5,-0.002))", 1, true), "craft: reals written") +t:check(string.find(text, "LENGTH_MEASURE(2.)", 1, true), "craft: typed integral real") +t:check(string.find(text, "(1,2,(3,4.)),(),-7,8,100.);", 1, true), "craft: integers and lists") +t:check(string.find(text, "#10=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNIT_ASSIGNED_CONTEXT((#11))", 1, true), "craft: complex written") +local back = decode(text) +t:check(back and same(cad.entities, back.entities, "entities"), "craft: round trip") +t:eq(back.header.FILE_NAME[3][1], "A Écrivain", "craft: header round trip") + +-- edition 3: named DATA sections, ANCHOR section kept raw +local ED3 = [[ISO-10303-21; +HEADER; +FILE_DESCRIPTION((''),'3;1'); +FILE_NAME('','',(''),(''),'','',''); +FILE_SCHEMA(('CONFIG_CONTROL_DESIGN','OTHER_SCHEMA')); +ENDSEC; +ANCHOR; + = #1; +ENDSEC; +DATA('first',('CONFIG_CONTROL_DESIGN')); +#1=A(1); +ENDSEC; +DATA('second',('OTHER_SCHEMA')); +#2=B('x;y',#1); +ENDSEC; +END-ISO-10303-21; +]] +local e3, e3err = decode(ED3) +t:check(e3, "ed3: " .. tostring(e3err)) +t:eq(e3.schema, "AP203", "ed3: schema") +t:eq(#e3.meta.source.sections, 2, "ed3: sections") +t:eq(e3.entities[2].section, 2, "ed3: entity section") +t:eq(e3.entities[2].args[1], "x;y", "ed3: ; inside a string") +t:eq(e3.meta.source.extra[1].name, "ANCHOR", "ed3: anchor kept") +local e3text = encode(e3) +t:check(string.find(e3text, "DATA('second',('OTHER_SCHEMA'));\n#2=B('x;y',#1);", 1, true), "ed3: sections written") +t:check(string.find(e3text, "ANCHOR;\n = #1;\nENDSEC;", 1, true), "ed3: anchor written") +local e3b = decode(e3text) +t:check(e3b and same(e3.entities, e3b.entities, "e"), "ed3: round trip") + +-- 4. building a file +local new = Step.new("AP242") +local pt = Step.add(new, "cartesian_point", { "origin", Step.real({ 0, 0, 1.25 }, 1) }) +Step.add(new, "VERTEX_POINT", { "", { ref = pt } }) +local ntext = encode(new, { name = "built.stp" }) +t:check(string.find(ntext, "FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }'));", 1, true), "new: schema") +t:check(string.find(ntext, "#1=CARTESIAN_POINT('origin',(0.,0,1.25));\n#2=VERTEX_POINT('',#1);", 1, true), "new: instances") +t:eq(decode(ntext).schema, "AP242", "new: decodes") +local _, bad = Step.encode({ kind = "cad", entities = { [1] = { id = 1, type = "X", args = { 0 / 0 } } }, header = {}, meta = {} }) +t:eq(bad and bad.code, Err.ARG, "encode: nan -> ARG") +local _, bad2 = Step.encode({ kind = "cad", entities = { [1] = { id = 1, type = "bad type", args = {} } }, header = {}, meta = {} }) +t:eq(bad2 and bad2.code, Err.ARG, "encode: bad type -> ARG") +local cyc = {} +cyc[1] = cyc +local _, bad3 = Step.encode({ kind = "cad", entities = { [1] = { id = 1, type = "X", args = cyc } }, header = {}, meta = {} }) +t:eq(bad3 and bad3.code, Err.ARG, "encode: cycle -> ARG") +local _, bad4 = Step.encode({ kind = "image" } :: any) +t:eq(bad4 and bad4.code, Err.ARG, "encode: not a Cad") + +-- 5. errors and sniff +local function code(s: string, opts: any?): string? + local v, e = decode(s, opts) + return if v then nil else e.code +end +t:eq(code("hello"), Err.CORRUPT, "no magic") +t:eq(code(string.sub(CRAFT, 1, 400)), Err.TRUNCATED, "truncated") +t:eq(code("ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=A(1,;\nENDSEC;\nEND-ISO-10303-21;"), Err.CORRUPT, "bad list") +t:eq(code("ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=A('x);\nENDSEC;\n"), Err.TRUNCATED, "open string") +t:eq(code(CRAFT, { maxEntities = 3 }), Err.LIMIT, "maxEntities") +t:eq(code(CRAFT, { maxBytes = 100 }), Err.LIMIT, "maxBytes") +t:eq(code("ISO-10303-21;\nHEADER;\nENDSEC;\n"), Err.TRUNCATED, "no DATA") +local deep = "ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=A(" .. string.rep("(", 500) .. string.rep(")", 500) .. ");\nENDSEC;\n" +t:eq(code(deep), Err.CORRUPT, "nesting limit") +t:eq(Step.sniff(Bytes.reader(buffer.fromstring(CRAFT))), 1, "sniff") +t:eq(Step.sniff(Bytes.reader(buffer.fromstring("\239\187\191/* x */ ISO-10303-21;"))), 1, "sniff: BOM + comment") +t:eq(Step.sniff(Bytes.reader(buffer.fromstring("ISO-10303-28"))), 0, "sniff: other") + +-- 6. the api +local loaded, lerr = F.load(CRAFT) +t:check(loaded and loaded.kind == "cad", "F.load: " .. tostring(lerr)) +t:eq(F.detect(CRAFT), "step", "F.detect") +local saved = F.save(loaded) +t:check(type(saved) == "buffer" and decode(buffer.tostring(saved)).meta.count == 6, "F.save (source format)") +local _, nop = Step.toBodies(loaded) +t:eq(nop and nop.code, Err.UNSUPPORTED, "toBodies without a plug-in") +local _, nop2 = F.cad.tessellate(loaded) +t:eq(nop2 and nop2.code, Err.UNSUPPORTED, "F.cad.tessellate without a plug-in") + +-- 7. the plug-in: a custom interface table +local calls = {} +local fake = { + read = function(text: string, _opts: any): any + calls.read = #text + return { bodies = { { name = "tri", color = { 1, 0, 0 } } }, stats = { solids = 1 } } + end, + write = function(bodies: { any }, _opts: any): string + calls.write = #bodies + return CRAFT + end, + tessellate = function(_body: any, _opts: any): any + return { positions = { { 0, 0, 0 }, { x = 1, y = 0, z = 0 }, { 0, 1, 0 }, { 0, 0, 1 } }, indices = { 1, 3, 2, 1, 2, 4, 1, 4, 3, 2, 3, 4 } } + end, +} +local fb, finfo = Step.toBodies(loaded, { brep = fake }) +t:check(fb and #fb == 1 and finfo.stats.solids == 1 and calls.read > 0, "custom plug-in: toBodies") +local fc = Step.fromBodies({ {} }, { plugins = { brep = fake } }) +t:check(fc and fc.kind == "cad" and calls.write == 1, "custom plug-in: fromBodies") +local fs, fserr = Step.tessellate(loaded, { brep = fake }) +t:check(fs and fs.kind == "scene", "custom plug-in: tessellate: " .. tostring(fserr)) +t:eq(fs.meta.up, "z", "scene: z up") +t:eq(fs.meta.unit, 0.001, "scene: millimetres") +t:eq(fs.meshes[1].name, "tri", "scene: body name") +t:eq(fs.materials[fs.meshes[1].primitives[1].material].extras.color[1], 1, "scene: body colour") +t:eq(fs.meshes[1].primitives[1].indices.count, 12, "scene: indices") +local throwing = { read = function(): any + error("kernel failure") +end } +local _, terr = Step.toBodies(loaded, { brep = throwing }) +t:eq(terr and terr.code, Err.CORRUPT, "plug-in that throws -> Err") +F.plugins.brep = fake +local fapi = F.cad.tessellate(loaded) +t:check(fapi and fapi.kind == "scene", "F.cad.tessellate through F.plugins") +F.plugins.brep = nil + +-- 8. brep-luau (luau CLI: tests/gen/.luaurc aliases it; LuaJIT has no `vector` type: skipped) +local function volume(scene: any): (number, { number }) + local v = 0 + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for _, m in scene.meshes do + for _, pr in m.primitives do + local pos, ind = pr.attributes.POSITION.data, pr.indices.data + local function P(i: number, k: number): number + return buffer.readf32(pos, (i * 3 + k) * 4) + end + for tri = 0, pr.indices.count // 3 - 1 do + local ia, ib, ic = buffer.readu32(ind, tri * 12), buffer.readu32(ind, tri * 12 + 4), buffer.readu32(ind, tri * 12 + 8) + local ax, ay, az = P(ia, 0), P(ia, 1), P(ia, 2) + local bx, by, bz = P(ib, 0), P(ib, 1), P(ib, 2) + local cx2, cy, cz = P(ic, 0), P(ic, 1), P(ic, 2) + v += (ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx2) + az * (bx * cy - by * cx2)) / 6 + for _, q in { { ax, ay, az }, { bx, by, bz }, { cx2, cy, cz } } do + for k = 1, 3 do + lo[k] = math.min(lo[k], q[k]) + hi[k] = math.max(hi[k], q[k]) + end + end + end + end + end + return v, { lo[1], lo[2], lo[3], hi[1], hi[2], hi[3] } +end + +local brepOk, brep = false, nil +if T.runtime == "luau" then + local ok, mods = pcall(require, "@tests/gen/step_brep") + brepOk, brep = ok and type(mods) == "table", mods +end +if brepOk then + local plug = { Step = brep.Step, StepBrep = brep.StepBrep, StepWrite = brep.StepWrite, Tess = brep.Tess } + local n = 0 + for i, c in Cases do + -- the gmsh solids and the small public part (the 2 MB sample takes too long to tessellate here) + if decoded[i] and c.occt and not c.occt.failed and #c.data < 400000 then + local scene, serr = Step.tessellate(decoded[i], { brep = plug, tess = { chord = 0.01, angle = 0.05 } }) + t:check(scene, c.name .. ": tessellate: " .. tostring(serr)) + if scene then + local bodies = Step.toBodies(decoded[i], { brep = plug }) + t:eq(#bodies, c.occt.solids, c.name .. ": solids (OCCT)") + local v, bb = volume(scene) + -- brep-luau reading the original text directly: our parse + write must not change what the kernel sees + local direct = brep.StepBrep.read(brep.Step.parse(c.data)).bodies + local dv, leaks = 0, 0 + for _, b in direct do + local m = brep.Tess.body(b, { chord = 0.01, angle = 0.05 }) + dv += brep.Tess.volume(m) + leaks += brep.Tess.leaks(m) + end + t:check(near(v, dv, 1e-6), string.format("%s: volume %.4f, brep-luau on the original %.4f", c.name, v, dv)) + if leaks == 0 then + t:check(near(v, c.occt.volume, 2e-3), string.format("%s: volume %.3f, OCCT %.3f", c.name, v, c.occt.volume)) + else + t:note("%s: brep-luau's tessellation leaks (%d open edges): volume %.1f vs OCCT %.1f not compared", c.name, leaks, v, c.occt.volume) + end + for k = 1, 6 do + -- (OCCT's box is not tight around curved faces: ours must lie inside it) + local inside = if k <= 3 then bb[k] >= c.occt.bbox[k] - 0.05 else bb[k] <= c.occt.bbox[k] + 0.05 + t:check(inside, string.format("%s: bounds[%d] %.4f, OCCT %.4f", c.name, k, bb[k], c.occt.bbox[k])) + end + n += 1 + end + end + end + -- kernel bodies -> our Cad -> our text -> bodies again + local M = brep.M + local part = brep.Boolean.subtract(brep.Build.box(M.v(0, 0, 0), M.v(40, 30, 5)), brep.Build.cylinder(M.v(20, 15, -1), 6, 7))[1] + part.color = { r = 0.2, g = 0.5, b = 0.9 } + local built, berr = F.cad.fromBodies({ part }, { brep = plug }) + t:check(built and built.kind == "cad" and #Step.byType(built, "ADVANCED_FACE") >= 7, "fromBodies: " .. tostring(berr)) + local again2 = decode(encode(built)) + local scene2 = Step.tessellate(again2, { brep = plug, chord = 0.01 }) + local v2 = volume(scene2) + local want = brep.Tess.volume(brep.Tess.body(part, { chord = 0.01 })) + t:check(near(v2, want, 1e-3), string.format("fromBodies round trip: volume %.3f, kernel %.3f", v2, want)) + t:check(near(v2, 40 * 30 * 5 - math.pi * 36 * 5, 2e-3), "fromBodies round trip: analytic volume") + local col = scene2.materials[scene2.meshes[1].primitives[1].material].extras.color + t:check(col and near(col[1], 0.2, 1e-6) and near(col[3], 0.9, 1e-6), "fromBodies round trip: colour") + t:note("brep-luau plug-in: %d files tessellated against OCCT, bodies -> STEP -> bodies", n) +else + t:note("brep-luau plug-in part skipped (%s)", if T.runtime ~= "luau" then "LuaJIT: no vector type" else "no ~/dev/luau/brep-luau") +end + +-- 9. fuzz +table.insert(samples, buffer.fromstring(CRAFT)) +table.insert(samples, buffer.fromstring(ED3)) +t:fuzz("decode", function(b: buffer): any + return Step.decode(Bytes.reader(b)) +end, samples, { keepHeader = 13 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 710195d..0d68d9a 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -535,3 +535,22 @@ do Webp.encode(img, { effort = 1 }) end) end +do + -- STEP (tools/fixtures/step.py): the largest case, parse and write + local Step = require("@formats/cad/step") + local SC = require("@tests/gen/step_cases") + local big = SC[1] + for _, c in SC do + if #c.data > #big.data then + big = c + end + end + local data = buffer.fromstring(big.data) + local cad = assert(Step.decode(Bytes.reader(data))) + bench(string.format("step parse (%.1f MB)", #big.data / 1e6), 3, #big.data, function() + Step.decode(Bytes.reader(data)) + end) + bench("step write", 3, #big.data, function() + Step.encode(cad) + end) +end diff --git a/tools/fixtures/_step_encode.luau b/tools/fixtures/_step_encode.luau new file mode 100644 index 0000000..b11c247 --- /dev/null +++ b/tools/fixtures/_step_encode.luau @@ -0,0 +1,27 @@ +-- tools/fixtures/_step_encode: run by tools/fixtures/step.py (luau CLI, repo root): decodes every STEP case with our +-- reader and writes it back with our writer, printing "case_.step\t" lines for OCCT (through gmsh) to read. +local Step = require("@formats/cad/step") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/step_cases") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(s: string): string + local out = table.create(#s) + for i = 1, #s do + out[i] = HEX[string.byte(s, i)] + end + return table.concat(out) +end + +for i, c in Cases do + local cad, err = Step.decode(Bytes.reader(buffer.fromstring(c.data))) + if cad then + local out = assert(Step.encode(cad)) + print(string.format("case_%d.step\t%s", i, hex(buffer.tostring(out)))) + else + print("skipped " .. c.name .. ": " .. tostring(err)) + end +end diff --git a/tools/fixtures/step.py b/tools/fixtures/step.py new file mode 100644 index 0000000..3c2099a --- /dev/null +++ b/tools/fixtures/step.py @@ -0,0 +1,185 @@ +# STEP fixtures (tools/fixtures.py): solids modelled in gmsh's OpenCASCADE kernel and written as STEP by OCCT +# (gmsh -0 x.geo -o x.step), plus public STEP files fetched at fixture time into a fresh temporary directory +# (untrusted input, only read; skipped when offline). Reference values: +# - a Part 21 instance census by an independent Python tokenizer (instance count, count per entity type), +# - OCCT through gmsh's Python API: number of solids, total volume, number of faces, total area, bounding box. +# Our writer's output (tools/fixtures/_step_encode.luau re-encodes every case) is read back by OCCT through gmsh too. +# tests/gen/step_cases.luau { name, data, census = { count, types = { TYPE = n } }, occt = { solids, volume, +# faces, area, bbox }, ours = occt values of our re-encoded file } +# tests/gen/step_brep.luau brep-luau's modules ({ Step, StepBrep, StepWrite, Tess, Build, Boolean, M }) through the +# tests/gen/.luaurc alias "brep" (only when ~/dev/luau/brep-luau, or $BREP_LUAU, exists; luau CLI only) +import json, os, re, shutil, subprocess, tempfile, urllib.request + +INPUTS = ["src/Formats/cad/step", "tools/fixtures/_step_encode.luau"] + +GEO = { + "plate": """Box(1) = {0,0,0, 40,30,5}; +Cylinder(2) = {20,15,-1, 0,0,7, 6}; +BooleanDifference{ Volume{1}; Delete; }{ Volume{2}; Delete; }""", + "sphere": "Sphere(1) = {0,0,0, 10};", + "torus": "Torus(1) = {0,0,0, 20, 5};", + "cone": "Cone(1) = {0,0,0, 0,0,12, 6, 2};", + "two_boxes": """Box(1) = {0,0,0, 10,10,10}; +Box(2) = {20,0,0, 5,5,30};""", + "bracket": """Box(1) = {0,0,0, 60,40,8}; +Box(2) = {0,0,0, 8,40,50}; +BooleanUnion{ Volume{1}; Delete; }{ Volume{2}; Delete; } +Cylinder(3) = {30,20,-1, 0,0,10, 7}; +Sphere(4) = {4,20,35, 9}; +BooleanDifference{ Volume{1}; Delete; }{ Volume{3,4}; Delete; }""", +} + +URLS = { + # build123d documentation example (Apache-2.0) + "nema17_bracket": "https://raw.githubusercontent.com/gumyr/build123d/dev/docs/topology_selection/examples/nema-17-bracket.step", + # pythonocc-demos sample model (parse + OCCT reference only; not committed) + "ventilator": "https://raw.githubusercontent.com/tpaviot/pythonocc-demos/master/assets/models/Ventilator.stp", +} +MAX_FETCH = 4 << 20 + +OCCT = r""" +import json, sys, gmsh +gmsh.initialize() +gmsh.option.setNumber("General.Terminal", 0) +res = [] +for p in json.loads(sys.stdin.read()): + try: + gmsh.clear() + gmsh.model.occ.importShapes(p) + gmsh.model.occ.synchronize() + vols = gmsh.model.getEntities(3) + faces = gmsh.model.getEntities(2) + bb = gmsh.model.getBoundingBox(-1, -1) + res.append({"solids": len(vols), "volume": sum(gmsh.model.occ.getMass(3, t) for _, t in vols), + "faces": len(faces), "area": sum(gmsh.model.occ.getMass(2, t) for _, t in faces), "bbox": list(bb)}) + except Exception as e: + res.append({"failed": True}) +print(json.dumps(res)) +""" + + +def census(text): + # an independent Part 21 tokenizer: comments and strings removed, statements split at ';' + out = [] + i, n = 0, len(text) + while i < n: + c = text[i] + if c == "'": + j = i + 1 + while True: + j = text.index("'", j) + if j + 1 < n and text[j + 1] == "'": + j += 2 + else: + break + out.append("''") + i = j + 1 + elif c == "/" and text.startswith("/*", i): + i = text.index("*/", i + 2) + 2 + else: + out.append(c) + i += 1 + clean = "".join(out) + data = clean[clean.index("DATA"):] + types = {} + count = 0 + for st in data.split(";"): + m = re.match(r"\s*#(\d+)\s*=\s*(\(|[A-Za-z_][A-Za-z0-9_]*)", st) + if m: + count += 1 + t = "COMPLEX" if m.group(2) == "(" else m.group(2).upper() + types[t] = types.get(t, 0) + 1 + return {"count": count, "types": types} + + +def occt(ctx, paths): + expr = "with import {}; python3.withPackages (p: [p.gmsh])" + cmd = ["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", OCCT] + res = subprocess.run(cmd, input=json.dumps(paths).encode(), capture_output=True, check=True) + return json.loads(res.stdout) + + +def luau(ctx, script): + exe = shutil.which("luau") + cmd = [exe, script] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script] + res = subprocess.run(cmd, cwd=ctx.root, capture_output=True, check=True) + files = {} + for line in res.stdout.decode().split("\n"): + if "\t" in line: + name, hexdata = line.split("\t", 1) + files[name] = bytes.fromhex(hexdata.strip()) + return files + + +def brep(ctx): + root = os.environ.get("BREP_LUAU") or os.path.expanduser("~/dev/luau/brep-luau") + rc = os.path.join(ctx.gen, ".luaurc") + mod = os.path.join(ctx.gen, "step_brep.luau") + if not os.path.exists(os.path.join(root, "src", "step", "StepBrep.luau")): + for p in (rc, mod): + if os.path.exists(p): + os.remove(p) + ctx.emit("step_brep", False) + return + with open(rc, "w") as f: + json.dump({"aliases": {"brep": os.path.join(os.path.abspath(root), "src")}}, f) + path = os.path.join(ctx.gen, "step_brep.luau") + with open(path, "w") as f: + f.write("-- generated by tools/fixtures.py (tools/fixtures/step.py) - do not edit\n" + "-- brep-luau through the tests/gen/.luaurc alias \"brep\" (luau CLI only)\n" + "return {\n" + "\tStep = require(\"@brep/step/Step\"),\n" + "\tStepBrep = require(\"@brep/step/StepBrep\"),\n" + "\tStepWrite = require(\"@brep/kernel/StepWrite\"),\n" + "\tTess = require(\"@brep/kernel/Tess\"),\n" + "\tBuild = require(\"@brep/kernel/Build\"),\n" + "\tBoolean = require(\"@brep/kernel/Boolean\"),\n" + "\tM = require(\"@brep/kernel/Math\"),\n" + "}\n") + ctx.outputs.append(path) + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="formats-step-") + cases = [] + for name, geo in GEO.items(): + g = os.path.join(tmp, name + ".geo") + with open(g, "w") as f: + f.write('SetFactory("OpenCASCADE");\n' + geo + "\n") + out = os.path.join(tmp, name + ".step") + ctx.nix("gmsh", ["gmsh", "-0", g, "-o", out]) + cases.append({"name": "gmsh/" + name, "path": out}) + fetched = tempfile.mkdtemp(prefix="formats-step-fetch-") + for name, url in URLS.items(): + dst = os.path.join(fetched, name + ".step") + try: + with urllib.request.urlopen(url, timeout=30) as r: + data = r.read(MAX_FETCH + 1) + if len(data) > MAX_FETCH: + continue + with open(dst, "wb") as f: + f.write(data) + cases.append({"name": "public/" + name, "path": dst, "public": True}) + except Exception: + pass + refs = occt(ctx, [c["path"] for c in cases]) + for c, r in zip(cases, refs): + c["data"] = open(c["path"], "rb").read() + c["census"] = census(c["data"].decode("latin-1")) + c["occt"] = r + # our writer's output of every case, read back by OCCT + ctx.emit("step_cases", [{k: v for k, v in c.items() if k != "path"} for c in cases]) + ours = luau(ctx, "tools/fixtures/_step_encode.luau") + xtmp = tempfile.mkdtemp(prefix="formats-step-ours-") + paths = [] + for i in range(len(cases)): + data = ours.get("case_%d.step" % (i + 1)) + p = os.path.join(xtmp, "case_%d.step" % (i + 1)) + with open(p, "wb") as f: + f.write(data or b"") + paths.append(p) + back = occt(ctx, paths) + for c, r in zip(cases, back): + c["ours"] = r + ctx.emit("step_cases", [{k: v for k, v in c.items() if k != "path"} for c in cases]) + brep(ctx) From 788d0b5332d5d465d84093882851cf3917dd9c7d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:41:27 -0500 Subject: [PATCH 3/8] ws-3d2/dae: model/dae (Collada 1.4/1.5 + .zae) read: geometry (all primitive kinds, shared offsets), common-profile materials + images, node tree (all transform elements, instance_node), skin + morph controllers, cameras, lights, animations resampled to TRS channels (clips); write: Collada 1.4.1 / .zae (meshes, materials, images, nodes, cameras, lights). Tests against assimp's Collada models (nixpkgs assimp.src at fixture time), assimp exports of glTF samples vs their originals, assimp reading our output, round trips, fuzz --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/model/dae/Math.luau | 188 +++ src/Formats/model/dae/Read.luau | 1879 ++++++++++++++++++++++++++++++ src/Formats/model/dae/Write.luau | 376 ++++++ src/Formats/model/dae/init.luau | 206 ++++ tests/model/dae.luau | 581 +++++++++ tools/fixtures/_dae_encode.luau | 36 + tools/fixtures/dae.py | 106 ++ 9 files changed, 3385 insertions(+) create mode 100644 src/Formats/model/dae/Math.luau create mode 100644 src/Formats/model/dae/Read.luau create mode 100644 src/Formats/model/dae/Write.luau create mode 100644 src/Formats/model/dae/init.luau create mode 100644 tests/model/dae.luau create mode 100644 tools/fixtures/_dae_encode.luau create mode 100644 tools/fixtures/dae.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 40e275f..6560539 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -20,6 +20,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | | audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | +| model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d514aa9..bd40fa6 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -194,6 +194,18 @@ local list: { Entry } = { return require("@formats/audio/wav") end, }, + { + name = "dae", + category = "model", + path = "model/dae", + extensions = { "dae", "zae" }, + mime = { "model/vnd.collada+xml", "model/vnd.collada+zip" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Base64", "containers/Zip" }, + caps = { decode = true, encode = true, materials = true, polygons = true, skins = true, morphTargets = true, animation = true, cameras = true, lights = true, zae = true }, + load = function() + return require("@formats/model/dae") + end, + }, { name = "gltf", category = "model", diff --git a/src/Formats/model/dae/Math.luau b/src/Formats/model/dae/Math.luau new file mode 100644 index 0000000..594a53b --- /dev/null +++ b/src/Formats/model/dae/Math.luau @@ -0,0 +1,188 @@ +--!strict +-- model/dae/Math: the matrix helpers the Collada reader and writer share. Matrices are flat arrays of 16 in glTF's +-- column-major order (Collada writes row-major: fromRows / toRows convert). Quaternions are { x, y, z, w }. +local DaeMath = {} + +local sqrt, abs, rad, sin, cos = math.sqrt, math.abs, math.rad, math.sin, math.cos + +function DaeMath.identity(): { number } + return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } +end + +-- fromRows(v, at?) -> column-major from 16 row-major values starting at v[at] (default 1) +function DaeMath.fromRows(v: { number }, at: number?): { number } + local o = (at or 1) - 1 + local m = table.create(16, 0) + for r = 0, 3 do + for c = 0, 3 do + m[c * 4 + r + 1] = v[o + r * 4 + c + 1] or (if r == c then 1 else 0) + end + end + return m +end + +function DaeMath.toRows(m: { number }): { number } + local v = table.create(16, 0) + for r = 0, 3 do + for c = 0, 3 do + v[r * 4 + c + 1] = m[c * 4 + r + 1] + end + end + return v +end + +function DaeMath.mul(a: { number }, b: { number }): { number } + local m = table.create(16, 0) + for col = 0, 3 do + for row = 0, 3 do + local s = 0 + for k = 0, 3 do + s += a[k * 4 + row + 1] * b[col * 4 + k + 1] + end + m[col * 4 + row + 1] = s + end + end + return m +end + +function DaeMath.translation(x: number, y: number, z: number): { number } + return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } +end + +function DaeMath.scaling(x: number, y: number, z: number): { number } + return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } +end + +-- axisAngle(x, y, z, degrees) -> quaternion +function DaeMath.axisAngle(x: number, y: number, z: number, degrees: number): { number } + local l = sqrt(x * x + y * y + z * z) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + local h = rad(degrees) / 2 + local s = sin(h) / l + return { x * s, y * s, z * s, cos(h) } +end + +function DaeMath.quatMatrix(q: { number }): { number } + local x, y, z, w = q[1], q[2], q[3], q[4] + local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z + return { + 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0, + 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0, + 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0, + 0, 0, 0, 1, + } +end + +local function cross(a: { number }, b: { number }): { number } + return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] } +end +local function norm(a: { number }): { number } + local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3]) + if l < 1e-20 then + return { 0, 0, 0 } + end + return { a[1] / l, a[2] / l, a[3] / l } +end + +-- lookat(eye, interest, up) -> the placement of an object at eye whose -Z looks at interest +function DaeMath.lookat(v: { number }): { number } + local ex, ey, ez = v[1] or 0, v[2] or 0, v[3] or 0 + local z = norm({ ex - (v[4] or 0), ey - (v[5] or 0), ez - (v[6] or 0) }) + local x = norm(cross({ v[7] or 0, v[8] or 1, v[9] or 0 }, z)) + local y = cross(z, x) + return { x[1], x[2], x[3], 0, y[1], y[2], y[3], 0, z[1], z[2], z[3], 0, ex, ey, ez, 1 } +end + +-- skew(angle, rotation axis, translation axis) (RenderMan's skew) +function DaeMath.skew(v: { number }): { number } + local a = rad(v[1] or 0) + local r = norm({ v[2] or 0, v[3] or 0, v[4] or 0 }) + local t = norm({ v[5] or 0, v[6] or 0, v[7] or 0 }) + local s = math.tan(a) + local m = DaeMath.identity() + -- M = I + s * t * r^T (column-major: m[col*4 + row]) + for row = 0, 2 do + for col = 0, 2 do + m[col * 4 + row + 1] += s * t[row + 1] * r[col + 1] + end + end + return m +end + +-- decompose(m) -> translation, rotation, scale | nil (shear, a projective row, or a singular matrix) +function DaeMath.decompose(m: { number }): ({ number }?, { number }?, { number }?) + if abs(m[4]) > 1e-6 or abs(m[8]) > 1e-6 or abs(m[12]) > 1e-6 or abs(m[16] - 1) > 1e-6 then + return nil, nil, nil + end + local c1 = { m[1], m[2], m[3] } + local c2 = { m[5], m[6], m[7] } + local c3 = { m[9], m[10], m[11] } + local sx = sqrt(c1[1] * c1[1] + c1[2] * c1[2] + c1[3] * c1[3]) + local sy = sqrt(c2[1] * c2[1] + c2[2] * c2[2] + c2[3] * c2[3]) + local sz = sqrt(c3[1] * c3[1] + c3[2] * c3[2] + c3[3] * c3[3]) + if sx < 1e-12 or sy < 1e-12 or sz < 1e-12 then + return nil, nil, nil + end + local x, y, z = { c1[1] / sx, c1[2] / sx, c1[3] / sx }, { c2[1] / sy, c2[2] / sy, c2[3] / sy }, { c3[1] / sz, c3[2] / sz, c3[3] / sz } + local dxy = x[1] * y[1] + x[2] * y[2] + x[3] * y[3] + local dxz = x[1] * z[1] + x[2] * z[2] + x[3] * z[3] + local dyz = y[1] * z[1] + y[2] * z[2] + y[3] * z[3] + if abs(dxy) > 1e-4 or abs(dxz) > 1e-4 or abs(dyz) > 1e-4 then + return nil, nil, nil + end + local cr = cross(x, y) + if cr[1] * z[1] + cr[2] * z[2] + cr[3] * z[3] < 0 then + sx = -sx + x = { -x[1], -x[2], -x[3] } + end + -- rotation matrix (columns x, y, z) -> quaternion + local m00, m01, m02 = x[1], y[1], z[1] + local m10, m11, m12 = x[2], y[2], z[2] + local m20, m21, m22 = x[3], y[3], z[3] + local tr = m00 + m11 + m22 + local qx, qy, qz, qw + if tr > 0 then + local s = sqrt(tr + 1) * 2 + qw, qx, qy, qz = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s + elseif m00 > m11 and m00 > m22 then + local s = sqrt(1 + m00 - m11 - m22) * 2 + qw, qx, qy, qz = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s + elseif m11 > m22 then + local s = sqrt(1 + m11 - m00 - m22) * 2 + qw, qx, qy, qz = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s + else + local s = sqrt(1 + m22 - m00 - m11) * 2 + qw, qx, qy, qz = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4 + end + local l = sqrt(qx * qx + qy * qy + qz * qz + qw * qw) + return { m[13], m[14], m[15] }, { qx / l, qy / l, qz / l, qw / l }, { sx, sy, sz } +end + +-- transformPoint / transformDir (column-major m) +function DaeMath.point(m: { number }, x: number, y: number, z: number): (number, number, number) + return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] +end + +-- the inverse transpose of the upper 3x3 (for normals), as a column-major 4x4 +function DaeMath.normalMatrix(m: { number }): { number } + local a, b, c = m[1], m[5], m[9] + local d, e, f = m[2], m[6], m[10] + local g, h, i = m[3], m[7], m[11] + local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g + local det = a * A + b * B + c * C + if abs(det) < 1e-30 then + return DaeMath.identity() + end + local k = 1 / det + -- inverse = adj / det; its transpose has rows = cofactors + return { + A * k, B * k, C * k, 0, + -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0, + (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0, + 0, 0, 0, 1, + } +end + +return DaeMath diff --git a/src/Formats/model/dae/Read.luau b/src/Formats/model/dae/Read.luau new file mode 100644 index 0000000..82bbb59 --- /dev/null +++ b/src/Formats/model/dae/Read.luau @@ -0,0 +1,1879 @@ +--!strict +-- model/dae/Read: a parsed Collada document (codecs/Xml DOM) -> Scene. Geometry (triangles / polylist / polygons / +-- lines / linestrips / tristrips / trifans with shared input offsets, de-indexed per index tuple), common-profile +-- materials (phong / blinn / lambert / constant -> PBR + extras.phong) with their sampler2D / surface / image chains, +-- images (kept encoded through the fetch callback, or embedded hex ), the visual scene's node tree (matrix / +-- translate / rotate / scale / lookat / skew, instance_node, several instances per node as child nodes), skin +-- controllers (bind shape applied, inverse bind matrices, the 4 strongest weights), morph controllers (targets as +-- deltas), cameras, lights (ambient lights as node extras) and animations (every channel on a node's transform +-- elements, resampled at the union of the key times (plus subdivisions of large rotations) into glTF-style TRS +-- channels; one animation per animation clip, else one for the file). +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Xml = require("@formats/codecs/Xml") +local Base64 = require("@formats/codecs/Base64") +local M = require("@formats/model/dae/Math") + +local Read = {} + +export type Fetch = (uri: string) -> buffer? + +local Scene = Types.Scene +local find, sub, gmatch, match, lower, upper = string.find, string.sub, string.gmatch, string.match, string.lower, string.upper +local children, child, text = Xml.children, Xml.child, Xml.text + +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/tga", bmp = "image/bmp", gif = "image/gif", webp = "image/webp", dds = "image/vnd-ms.dds", tif = "image/tiff", tiff = "image/tiff", ktx2 = "image/ktx2", hdr = "image/vnd.radiance", exr = "image/x-exr", psd = "image/vnd.adobe.photoshop" } +local WRAP = { WRAP = "repeat", MIRROR = "mirror", CLAMP = "clamp", BORDER = "clamp", MIRROR_ONCE = "mirror", NONE = "clamp" } +local PARAM_SIZE = { float2 = 2, float3 = 3, float4 = 4, float2x2 = 4, float3x3 = 9, float4x4 = 16, int2 = 2, int3 = 3, int4 = 4 } +local MEMBER = { X = 1, Y = 2, Z = 3, ANGLE = 4, W = 4, R = 1, G = 2, B = 3, A = 4, S = 1, T = 2, U = 1, V = 2, P = 3, Q = 4 } + +-- ------------------------------------------------------------------------------------------------ helpers +local function numbers(s: string, limit: number): ({ number }?, string?) + local out = {} + local n = 0 + for w in gmatch(s, "[^%s]+") do + n += 1 + if n > limit then + return nil, "array over the limit" + end + local v = tonumber(w) + if v == nil and find(w, ",", 1, true) and not find(w, ".", 1, true) then + v = tonumber((string.gsub(w, ",", "."))) -- decimal commas (some 3ds Max exporters) + end + if v == nil then + local lw = lower(w) + v = if lw == "nan" or lw == "-nan" or lw == "1.#qnan" or lw == "-1.#ind" then 0 elseif lw == "inf" or lw == "1.#inf" then math.huge elseif lw == "-inf" or lw == "-1.#inf" then -math.huge elseif lw == "true" then 1 elseif lw == "false" then 0 else 0 + end + out[n] = v :: number + end + return out, nil +end +local function words(s: string): { string } + local out = {} + for w in gmatch(s, "[^%s]+") do + table.insert(out, w) + end + return out +end +local function attr(node: any, name: string): string? + local v = node and node.attrs and node.attrs[name] + return if type(v) == "string" then v else nil +end +local function urlId(url: string?): string? + if not url then + return nil + end + return match(url, "^#(.*)$") or url +end +local function lname(node: any): string + return Xml.localName(node.name) +end +local function numText(node: any, default: number): number + if not node then + return default + end + return tonumber(match(text(node), "[^%s]+") or "") or default +end +local function color(node: any): { number }? + local c = node and child(node, "color") + if not c then + return nil + end + local v = numbers(text(c), 16) or {} + return { v[1] or 0, v[2] or 0, v[3] or 0, v[4] or 1 } +end + +type Ctx = { + doc: any, + ids: { [string]: any }, + fetch: Fetch, + scene: Types.Scene, + limit: number, + vertices: number, + flipV: boolean, + triangulate: boolean, + sources: { [any]: any }, + materials: { [string]: number }, + textures: { [string]: number }, + images: { [string]: any }, + meshes: { [string]: number }, + skins: { [string]: number }, + posIndex: { [any]: { number } }, + nodeOf: { [string]: { number } }, -- collada node id -> scene nodes + info: { [number]: any }, -- scene node -> { el, xf, sid, cid } + pendingSkins: { any }, + skipped: { [string]: number }, + err: string?, + depth: number, +} + +local function skip(C: Ctx, what: string) + C.skipped[what] = (C.skipped[what] or 0) + 1 +end + +-- ------------------------------------------------------------------------------------------------ sources +-- source(el) -> { data = flat numbers or strings, comps, count } (only the accessor's named params) +local function readSource(C: Ctx, el: any): any + local cached = C.sources[el] + if cached ~= nil then + return cached or nil + end + C.sources[el] = false + local arrEl: any = nil + local strings = false + for _, ch in children(el) do + local n = lname(ch) + if n == "float_array" or n == "int_array" or n == "bool_array" then + arrEl = ch + elseif n == "Name_array" or n == "IDREF_array" or n == "SIDREF_array" or n == "token_array" then + arrEl, strings = ch, true + end + end + local values: { any } = {} + if arrEl then + if strings then + values = words(text(arrEl)) + else + local v, e = numbers(text(arrEl), C.limit) + if not v then + C.err = e + return nil + end + values = v + end + end + local tc = child(el, "technique_common") + local acc = tc and child(tc, "accessor") + local out: any + if not acc then + out = { data = values, comps = 1, count = #values } + else + local count = tonumber(attr(acc, "count") or "") or 0 + local stride = tonumber(attr(acc, "stride") or "") or 1 + local offset = tonumber(attr(acc, "offset") or "") or 0 + local picks = {} + local pos = 0 + local anyNamed = false + for _, p in children(acc, "param") do + if attr(p, "name") then + anyNamed = true + end + end + for _, p in children(acc, "param") do + local w = PARAM_SIZE[attr(p, "type") or ""] or 1 + if attr(p, "name") or not anyNamed then + for k = 0, w - 1 do + table.insert(picks, pos + k) + end + end + pos += w + end + if #picks == 0 then + for k = 0, stride - 1 do + table.insert(picks, k) + end + end + if stride < 1 or count < 0 or count * stride > C.limit * 16 then + C.err = "bad accessor" + return nil + end + count = math.min(count, math.max(0, (#values - offset) // math.max(stride, 1))) + local comps = #picks + local data = table.create(count * comps) + local n = 0 + for i = 0, count - 1 do + local base = offset + i * stride + 1 + for _, k in picks do + n += 1 + data[n] = values[base + k] or 0 + end + end + out = { data = data, comps = comps, count = count } + end + C.sources[el] = out + return out +end + +local function sourceById(C: Ctx, url: string?): any + local id = urlId(url) + local el = id and C.ids[id] + if not el or lname(el) ~= "source" then + return nil + end + return readSource(C, el) +end + +-- ------------------------------------------------------------------------------------------------ images, materials +local function fetchImage(C: Ctx, ref: string): (buffer?, string) + local uri = ref + uri = string.gsub(uri, "^file:///(%a:)", "%1") + uri = string.gsub(uri, "^file://", "") + local data = C.fetch(uri) + if not data then + local decoded = string.gsub(uri, "%%(%x%x)", function(h: string): string + return string.char(tonumber(h, 16) :: number) + end) + data = C.fetch(decoded) + if not data then + local base = match(decoded, "([^/\\]+)$") + if base and base ~= decoded then + data = C.fetch(base) + end + end + end + return data, uri +end + +local function image(C: Ctx, id: string): any + local cached = C.images[id] + if cached ~= nil then + return cached or nil + end + C.images[id] = false + local el = C.ids[id] + if not el or lname(el) ~= "image" then + return nil + end + local img: any = { name = attr(el, "name") or id } + local init = child(el, "init_from") + local hex: any = child(el, "data") + if init then + local ref = child(init, "ref") + local s = match(text(ref or init), "^%s*(.-)%s*$") or "" + if s ~= "" then + if sub(s, 1, 5) == "data:" then + local d, mime = Base64.decodeDataUri(s) + if d then + img.data, img.mime = d, mime + end + else + local d, uri = fetchImage(C, s) + img.data, img.uri = d, uri + local ext = match(uri, "%.([%w]+)$") + img.mime = ext and MIME[lower(ext)] + end + end + hex = hex or child(init, "hex") + end + if hex and not img.data then + local h = string.gsub(text(hex), "%s+", "") + if #h % 2 == 0 and not find(h, "[^%x]") then + local b = buffer.create(#h // 2) + for i = 0, #h // 2 - 1 do + buffer.writeu8(b, i, tonumber(sub(h, i * 2 + 1, i * 2 + 2), 16) :: number) + end + img.data = b + local fmt = attr(hex, "format") or attr(el, "format") + img.mime = fmt and MIME[lower(fmt)] + end + end + if img.data and not img.mime then + local b = img.data + if buffer.len(b) >= 4 then + local m4 = buffer.readstring(b, 0, 4) + img.mime = if m4 == "\137PNG" then "image/png" elseif sub(m4, 1, 3) == "\255\216\255" then "image/jpeg" else nil + end + end + C.images[id] = img + return img +end + +-- the effect's newparams by sid (this level and the profile's) +local function newparams(effect: any, profile: any, technique: any): { [string]: any } + local out = {} + for _, scope in { effect, profile, technique } do + if scope then + for _, np in children(scope, "newparam") do + local sid = attr(np, "sid") + if sid then + out[sid] = np + end + end + end + end + return out +end + +-- texture(effect params, sampler sid) -> scene texture index +local function texture(C: Ctx, params: { [string]: any }, samplerSid: string): number? + local np = params[samplerSid] + local imageId: string? = nil + local sampler: any = nil + if np then + local s2d = child(np, "sampler2D") or child(np, "samplerCUBE") or child(np, "sampler3D") + if s2d then + sampler = s2d + local inst = child(s2d, "instance_image") + if inst then + imageId = urlId(attr(inst, "url")) + else + local src = child(s2d, "source") + local surfNp = src and params[match(text(src), "^%s*(.-)%s*$") or ""] + local surf = surfNp and child(surfNp, "surface") + local init = surf and child(surf, "init_from") + if init then + imageId = match(text(init), "^%s*(.-)%s*$") + end + end + else + local surf = child(np, "surface") + local init = surf and child(surf, "init_from") + if init then + imageId = match(text(init), "^%s*(.-)%s*$") + end + end + else + -- many exporters reference the image id directly + imageId = samplerSid + end + if not imageId then + return nil + end + local key = imageId .. "|" .. samplerSid + local cached = C.textures[key] + if cached then + return cached + end + local img = image(C, imageId) + if not img then + return nil + end + local tex: Types.Texture = { name = img.name, data = img.data, mime = img.mime, uri = img.uri } + if sampler then + local ws, wt = child(sampler, "wrap_s"), child(sampler, "wrap_t") + local mag = child(sampler, "magfilter") + local smp: Types.Sampler = {} + if ws then + smp.wrapS = WRAP[upper(match(text(ws), "[%w_]+") or "")] :: any + end + if wt then + smp.wrapT = WRAP[upper(match(text(wt), "[%w_]+") or "")] :: any + end + if mag then + local f = upper(match(text(mag), "[%w_]+") or "") + smp.filter = if f == "NEAREST" then "nearest" elseif f == "LINEAR" then "linear" else nil + end + if next(smp) then + tex.sampler = smp + end + end + table.insert(C.scene.textures, tex) + local idx = #C.scene.textures + C.textures[key] = idx + return idx +end + +-- one colour-or-texture parameter of a common technique +local function param(C: Ctx, params: { [string]: any }, el: any, uvsets: { [string]: number }): (any, any) + if not el then + return nil, nil + end + local c = color(el) + local f = child(el, "float") + local tx = child(el, "texture") + local ref: any = nil + if tx then + local ti = texture(C, params, attr(tx, "texture") or "") + if ti then + ref = { texture = ti } + local set = uvsets[attr(tx, "texcoord") or ""] + if set and set > 0 then + ref.texCoord = set + end + end + end + if c then + return c, ref + elseif f then + return numText(f, 0), ref + end + local pr = child(el, "param") + if pr then + local np = params[attr(pr, "ref") or ""] + local v = np and (child(np, "float4") or child(np, "float3") or child(np, "float")) + if v then + local nums = numbers(text(v), 16) or {} + if #nums == 1 then + return nums[1], ref + end + return { nums[1] or 0, nums[2] or 0, nums[3] or 0, nums[4] or 1 }, ref + end + end + return nil, ref +end + +local function material(C: Ctx, id: string, uvsets: { [string]: number }): number? + local cached = C.materials[id] + if cached then + return cached + end + local el = C.ids[id] + if not el or lname(el) ~= "material" then + return nil + end + local mat = Scene.material(attr(el, "name") or id) + mat.metallic = 0 + local inst = child(el, "instance_effect") + local effect = inst and C.ids[urlId(attr(inst, "url")) or ""] + local phong: { [string]: any } = {} + if effect and lname(effect) == "effect" then + local profile = child(effect, "profile_COMMON") + local tech = profile and child(profile, "technique") + local shader: any = nil + if tech then + for _, ch in children(tech) do + local n = lname(ch) + if n == "phong" or n == "blinn" or n == "lambert" or n == "constant" then + shader = ch + phong.model = n + break + end + end + end + local params = newparams(effect, profile, tech) + if shader then + local diffuse, dtex = param(C, params, child(shader, "diffuse"), uvsets) + local emission, etex = param(C, params, child(shader, "emission"), uvsets) + local ambient, atex = param(C, params, child(shader, "ambient"), uvsets) + local specular, stex = param(C, params, child(shader, "specular"), uvsets) + local shininess = param(C, params, child(shader, "shininess"), uvsets) + local reflective = param(C, params, child(shader, "reflective"), uvsets) + local reflectivity = param(C, params, child(shader, "reflectivity"), uvsets) + local transparentEl = child(shader, "transparent") + local transparent, ttex = param(C, params, transparentEl, uvsets) + local transparency = param(C, params, child(shader, "transparency"), uvsets) + local ior = param(C, params, child(shader, "index_of_refraction"), uvsets) + phong.diffuse, phong.diffuseTexture = diffuse, dtex + phong.emission, phong.emissionTexture = emission, etex + phong.ambient, phong.ambientTexture = ambient, atex + phong.specular, phong.specularTexture = specular, stex + phong.shininess, phong.reflective, phong.reflectivity = shininess, reflective, reflectivity + phong.transparent, phong.transparentTexture, phong.transparency = transparent, ttex, transparency + phong.indexOfRefraction = ior + if type(diffuse) == "table" then + mat.baseColor = { diffuse[1], diffuse[2], diffuse[3], 1 } -- its alpha is not opacity (exporters write 0) + end + if phong.model == "constant" and type(emission) == "table" then + mat.baseColor = { emission[1], emission[2], emission[3], 1 } + mat.extensions = { KHR_materials_unlit = {} } + end + if dtex then + mat.baseColorTexture = dtex + if type(diffuse) ~= "table" then + mat.baseColor = { 1, 1, 1, 1 } + end + end + if type(emission) == "table" and phong.model ~= "constant" then + mat.emissive = { emission[1], emission[2], emission[3] } + end + if etex then + mat.emissiveTexture = etex + mat.emissive = { 1, 1, 1 } + end + if type(shininess) == "number" then + mat.roughness = math.clamp(math.sqrt(2 / (math.max(shininess, 0) + 2)), 0, 1) + end + -- opacity (Collada 1.4.1 spec section 7: A_ONE (default) uses transparent.a, RGB_ZERO the luminance) + if transparentEl and (type(transparent) == "table" or type(transparency) == "number") then + local mode = attr(transparentEl, "opaque") or "A_ONE" + local tv = if type(transparency) == "number" then transparency else 1 + local tc: any = if type(transparent) == "table" then transparent else { 1, 1, 1, 1 } + local a: number + if mode == "RGB_ZERO" then + a = 1 - tv * (tc[1] * 0.212671 + tc[2] * 0.71516 + tc[3] * 0.072169) + elseif mode == "A_ZERO" then + a = 1 - tv * tc[4] + elseif mode == "RGB_ONE" then + a = tv * (tc[1] * 0.212671 + tc[2] * 0.71516 + tc[3] * 0.072169) + else + a = tv * tc[4] + end + a = math.clamp(a, 0, 1) + if a < 0.999 and a > 0.001 then + mat.baseColor[4] = a + mat.alphaMode = "blend" + end + phong.opacity = a + end + if ttex then + mat.alphaMode = "blend" + end + end + -- FCOLLADA / MAX3D / OpenCOLLADA extras: bump maps and double sidedness + for _, scope in { tech, profile, effect } do + if scope then + for _, ex in children(scope, "extra") do + for _, tq in children(ex, "technique") do + local bump = child(tq, "bump") + if bump and not mat.normalTexture then + local _, btex = param(C, params, bump, uvsets) + if btex then + mat.normalTexture = btex + end + end + local ds = child(tq, "double_sided") + if ds and numText(ds, 0) ~= 0 then + mat.doubleSided = true + end + end + end + end + end + end + mat.extras = { phong = phong } + table.insert(C.scene.materials, mat) + local idx = #C.scene.materials + C.materials[id] = idx + return idx +end + +-- ------------------------------------------------------------------------------------------------ geometry +type Input = { semantic: string, source: any, offset: number, set: number } + +-- the inputs of a primitive element (VERTEX expanded into the inputs) +local function inputs(C: Ctx, prim: any, verticesEl: any): ({ Input }, number) + local out: { Input } = {} + local stride = 0 + for _, inp in children(prim, "input") do + local sem = upper(attr(inp, "semantic") or "") + local offset = tonumber(attr(inp, "offset") or "") or 0 + local set = tonumber(attr(inp, "set") or "") or 0 + if offset + 1 > stride then + stride = offset + 1 + end + if sem == "VERTEX" then + local vel = C.ids[urlId(attr(inp, "source")) or ""] or verticesEl + if vel and lname(vel) == "vertices" then + for _, vin in children(vel, "input") do + local vs = upper(attr(vin, "semantic") or "") + local src = sourceById(C, attr(vin, "source")) + if src then + table.insert(out, { semantic = vs, source = src, offset = offset, set = tonumber(attr(vin, "set") or "") or set }) + end + end + end + else + local src = sourceById(C, attr(inp, "source")) + if src then + table.insert(out, { semantic = sem, source = src, offset = offset, set = set }) + end + end + end + return out, math.max(stride, 1) +end + +-- faces(primEl, kind, stride) -> corner list (tuple starts into the concatenated p), face sizes, mode +local function corners(C: Ctx, prim: any, kind: string, stride: number): ({ number }?, { number }?, { number }?, string) + local p: { number } = {} + local faces: { number } = {} + local starts: { number } = {} + local function addP(el: any): (number, number) + local v, e = numbers(text(el), C.limit) + if not v then + C.err = e + return 0, 0 + end + local base = #p + table.move(v, 1, #v, base + 1, p) + return base // stride, #v // stride + end + if kind == "triangles" or kind == "lines" then + local per = if kind == "triangles" then 3 else 2 + local pe = child(prim, "p") + if pe then + local _, n = addP(pe) + local count = math.min(tonumber(attr(prim, "count") or "") or n // per, n // per) + for f = 0, count - 1 do + table.insert(faces, per) + for k = 0, per - 1 do + table.insert(starts, f * per + k) + end + end + end + return p, faces, starts, kind + elseif kind == "polylist" then + local pe = child(prim, "p") + local vc = child(prim, "vcount") + if pe and vc then + local _, n = addP(pe) + local counts = numbers(text(vc), C.limit) or {} + local at = 0 + for _, c in counts do + c = math.floor(c) + if c < 0 or at + c > n then + break + end + table.insert(faces, c) + for k = 0, c - 1 do + table.insert(starts, at + k) + end + at += c + end + end + return p, faces, starts, "polygons" + elseif kind == "polygons" then + local list = children(prim, "p") + for _, ph in children(prim, "ph") do + local outer = child(ph, "p") + if outer then + table.insert(list, outer) + end + skip(C, "polygon holes") + end + for _, pe in list do + local first, n = addP(pe) + if n > 0 then + table.insert(faces, n) + for k = 0, n - 1 do + table.insert(starts, first + k) + end + end + end + return p, faces, starts, "polygons" + elseif kind == "linestrips" then + for _, pe in children(prim, "p") do + local first, n = addP(pe) + for k = 0, n - 2 do + table.insert(faces, 2) + table.insert(starts, first + k) + table.insert(starts, first + k + 1) + end + end + return p, faces, starts, "lines" + elseif kind == "tristrips" or kind == "trifans" then + for _, pe in children(prim, "p") do + local first, n = addP(pe) + for k = 0, n - 3 do + table.insert(faces, 3) + if kind == "trifans" then + table.insert(starts, first) + table.insert(starts, first + k + 1) + table.insert(starts, first + k + 2) + elseif k % 2 == 0 then + table.insert(starts, first + k) + table.insert(starts, first + k + 1) + table.insert(starts, first + k + 2) + else + table.insert(starts, first + k + 1) + table.insert(starts, first + k) + table.insert(starts, first + k + 2) + end + end + end + return p, faces, starts, "triangles" + end + return nil, nil, nil, kind +end + +local PRIMS = { triangles = true, polylist = true, polygons = true, lines = true, linestrips = true, tristrips = true, trifans = true } + +type Built = { prim: Types.Primitive, symbol: string?, texSets: { number }, posIndex: { number } } + +-- one primitive element -> Primitive (+ the source position index of each output vertex, for skins / morphs) +local function buildPrim(C: Ctx, prim: any, verticesEl: any, kind: string): Built? + local ins, stride = inputs(C, prim, verticesEl) + local p, faces, starts, mode = corners(C, prim, kind, stride) + if C.err or not p or not faces or not starts then + return nil + end + local posIn: Input? = nil + for _, i in ins do + if i.semantic == "POSITION" then + posIn = i + break + end + end + if not posIn then + skip(C, "primitives without positions") + return nil + end + -- attribute names + local named: { { input: Input, name: string, comps: number } } = {} + local texSets: { number } = {} + local texInputs: { Input } = {} + local colorN, normalSeen = 0, false + for _, i in ins do + if i.semantic == "TEXCOORD" then + table.insert(texInputs, i) + end + end + table.sort(texInputs, function(a: Input, b: Input): boolean + if a.set ~= b.set then + return a.set < b.set + end + return a.offset < b.offset + end) + for k, i in texInputs do + texSets[k] = i.set + table.insert(named, { input = i, name = "TEXCOORD_" .. (k - 1), comps = 2 }) + end + for _, i in ins do + local s = i.semantic + local comps = math.min(i.source.comps, 4) + if s == "POSITION" then + if i == posIn then + table.insert(named, { input = i, name = "POSITION", comps = 3 }) + end + elseif s == "NORMAL" then + table.insert(named, { input = i, name = if normalSeen then "_NORMAL" .. i.set else "NORMAL", comps = 3 }) + normalSeen = true + elseif s == "COLOR" then + table.insert(named, { input = i, name = "COLOR_" .. colorN, comps = if comps >= 4 then 4 else 3 }) + colorN += 1 + elseif s ~= "TEXCOORD" then + table.insert(named, { input = i, name = "_" .. s .. (if i.set ~= 0 then tostring(i.set) else ""), comps = math.max(comps, 1) }) + end + end + -- de-index + local np = #p + local keyOf: { [any]: number } = {} + local tuples: { number } = {} -- the first p index of each output vertex's tuple + local corner = table.create(#starts) + local count = 0 + for ci, s in starts do + local base = s * stride + if base + stride > np then + C.err = "index list too short" + return nil + end + local key: any + if stride == 1 then + key = p[base + 1] + else + key = table.concat(p, ",", base + 1, base + stride) + end + local v = keyOf[key] + if not v then + v = count + count += 1 + keyOf[key] = v + tuples[count] = base + end + corner[ci] = v + end + C.vertices += count + if C.vertices > C.limit then + C.err = "over the vertex limit" + return nil + end + local attributes: { [string]: Types.Accessor } = {} + local posIndex = table.create(count, 0) + for _, a in named do + local src = a.input.source + local comps, scomps = a.comps, src.comps + local data, n = src.data, src.count + local buf = buffer.create(count * comps * 4) + local off = a.input.offset + 1 + local isTex = sub(a.name, 1, 9) == "TEXCOORD_" + local isPos = a.name == "POSITION" + for v = 0, count - 1 do + local idx = p[tuples[v + 1] + off] + if idx == nil or idx < 0 or idx >= n or idx ~= idx // 1 then + C.err = "index out of range" + return nil + end + if isPos then + posIndex[v + 1] = idx + end + local at = idx * scomps + for k = 1, comps do + local x = if k <= scomps then data[at + k] else (if k == 4 then 1 else 0) + if type(x) ~= "number" then + x = 0 + end + if isTex and k == 2 and C.flipV then + x = 1 - x + end + buffer.writef32(buf, (v * comps + k - 1) * 4, x) + end + end + attributes[a.name] = Scene.accessor(buf, "f32", comps, count) + end + local nc = #corner + local out: Types.Primitive = { attributes = attributes, mode = "triangles" } + if mode == "polygons" then + local allTri = true + for _, f in faces do + if f ~= 3 then + allTri = false + break + end + end + if allTri then + mode = "triangles" + elseif C.triangulate then + -- fan triangulation + local tri = {} + local at = 0 + for _, f in faces do + for k = 1, f - 2 do + table.insert(tri, corner[at + 1]) + table.insert(tri, corner[at + k + 1]) + table.insert(tri, corner[at + k + 2]) + end + at += f + end + corner, nc, mode = tri, #tri, "triangles" + else + local fb = buffer.create(#faces * 4) + for i, f in faces do + buffer.writeu32(fb, (i - 1) * 4, f) + end + out.faces = Scene.accessor(fb, "u32", 1, #faces) + end + end + out.mode = mode :: any + local ib = buffer.create(nc * 4) + for i = 1, nc do + buffer.writeu32(ib, (i - 1) * 4, corner[i]) + end + out.indices = Scene.accessor(ib, "u32", 1, nc) + return { prim = out, symbol = attr(prim, "material"), texSets = texSets, posIndex = posIndex } +end + +-- geometry(el) -> the built primitives (cached per geometry element) +local function geometry(C: Ctx, el: any): { Built }? + local cached = C.posIndex[el] + if cached then + return cached :: any + end + local mesh = child(el, "mesh") or child(el, "convex_mesh") + if not mesh then + if child(el, "spline") or child(el, "brep") then + skip(C, "spline / brep geometry") + end + return nil + end + local verticesEl = child(mesh, "vertices") + local out: { Built } = {} + for _, ch in children(mesh) do + local n = lname(ch) + if PRIMS[n] then + local b = buildPrim(C, ch, verticesEl, n) + if C.err then + return nil + end + if b then + table.insert(out, b) + end + end + end + C.posIndex[el] = out :: any + return out +end + +-- the material bindings of an instance: symbol -> material id, and semantic -> texcoord set +local function bindings(node: any): ({ [string]: string }, { [string]: { [string]: number } }) + local syms: { [string]: string } = {} + local sets: { [string]: { [string]: number } } = {} + local bm = node and child(node, "bind_material") + local tc = bm and child(bm, "technique_common") + if tc then + for _, im in children(tc, "instance_material") do + local sym, target = attr(im, "symbol"), urlId(attr(im, "target")) + if sym and target then + syms[sym] = target + local s = {} + for _, bvi in children(im, "bind_vertex_input") do + local sem = attr(bvi, "semantic") + if sem then + s[sem] = tonumber(attr(bvi, "input_set") or "") or 0 + end + end + sets[sym] = s + end + end + end + return syms, sets +end + +local function copyAccessor(a: Types.Accessor): Types.Accessor + local b = buffer.create(buffer.len(a.data)) + buffer.copy(b, 0, a.data) + return Scene.accessor(b, a.type, a.components, a.count) +end + +-- mesh(geometry element, instance element, skin?) -> scene mesh index +local function meshFor(C: Ctx, geomEl: any, inst: any, key: string, bindShape: { number }?): (number?, { Built }?) + local syms, sets = bindings(inst) + local parts = { key } + for s, t in syms do + table.insert(parts, s .. "=" .. t) + end + table.sort(parts) + local k = table.concat(parts, ";") + local built = geometry(C, geomEl) + if not built or #built == 0 then + return nil, nil + end + local cached = C.meshes[k] + if cached then + return cached, built + end + local mesh: Types.Mesh = { name = attr(geomEl, "name") or attr(geomEl, "id"), primitives = {} } + for _, b in built do + local prim = b.prim + if bindShape then + -- skinned: the bind shape matrix applied to positions and normals (a copy: the geometry may be shared) + local attrs = table.clone(prim.attributes) + local pos = copyAccessor(attrs.POSITION) + for v = 0, pos.count - 1 do + local x, y, z = buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8) + x, y, z = M.point(bindShape, x, y, z) + buffer.writef32(pos.data, v * 12, x) + buffer.writef32(pos.data, v * 12 + 4, y) + buffer.writef32(pos.data, v * 12 + 8, z) + end + attrs.POSITION = pos + if attrs.NORMAL then + local nm = M.normalMatrix(bindShape) + local nrm = copyAccessor(attrs.NORMAL) + for v = 0, nrm.count - 1 do + local x, y, z = buffer.readf32(nrm.data, v * 12), buffer.readf32(nrm.data, v * 12 + 4), buffer.readf32(nrm.data, v * 12 + 8) + x, y, z = nm[1] * x + nm[5] * y + nm[9] * z, nm[2] * x + nm[6] * y + nm[10] * z, nm[3] * x + nm[7] * y + nm[11] * z + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + buffer.writef32(nrm.data, v * 12, x) + buffer.writef32(nrm.data, v * 12 + 4, y) + buffer.writef32(nrm.data, v * 12 + 8, z) + end + attrs.NORMAL = nrm + end + prim = table.clone(prim) + prim.attributes = attrs + else + prim = table.clone(prim) + end + local sym = b.symbol + local target = sym and (syms[sym] or (if C.ids[sym] and lname(C.ids[sym]) == "material" then sym else nil)) + if not target then + -- no (or an unbound) symbol and a single binding: that one (MakeHuman leaves out the symbol) + local only, n = nil, 0 + for s2 in syms do + only, n = s2, n + 1 + end + if n == 1 then + sym = only + target = syms[only :: string] + end + end + if target then + -- texcoord semantic -> TEXCOORD_n index among this primitive's sets + local uv: { [string]: number } = {} + for sem, set in (sym and sets[sym]) or {} do + uv[sem] = (table.find(b.texSets, set) or 1) - 1 + end + prim.material = material(C, target, uv) + end + table.insert(mesh.primitives, prim) + end + table.insert(C.scene.meshes, mesh) + local idx = #C.scene.meshes + C.meshes[k] = idx + return idx, built +end + +-- morph controller -> mesh with targets (deltas) +local function morphMesh(C: Ctx, ctrl: any, morph: any, inst: any): number? + local base = C.ids[urlId(attr(morph, "source")) or ""] + if not base or lname(base) ~= "geometry" then + return nil + end + local idx, built = meshFor(C, base, inst, "morph:" .. (attr(ctrl, "id") or ""), nil) + if not idx or not built then + return nil + end + local mesh = C.scene.meshes[idx] + if mesh.weights then + return idx + end + local relative = upper(attr(morph, "method") or "NORMALIZED") == "RELATIVE" + local targetsEl = child(morph, "targets") + local targetIds: { string } = {} + local weights: { number } = {} + if targetsEl then + for _, inp in children(targetsEl, "input") do + local sem = upper(attr(inp, "semantic") or "") + local src = sourceById(C, attr(inp, "source")) + if src and sem == "MORPH_TARGET" then + for _, v in src.data do + table.insert(targetIds, tostring(v)) + end + elseif src and sem == "MORPH_WEIGHT" then + for _, v in src.data do + table.insert(weights, if type(v) == "number" then v else 0) + end + end + end + end + local tbuilt: { { Built } } = {} + for _, tid in targetIds do + local g = C.ids[tid] + local tb = g and lname(g) == "geometry" and geometry(C, g) + if not tb or #tb ~= #built then + skip(C, "morph targets with another topology") + return idx + end + table.insert(tbuilt, tb) + end + for pi, prim in mesh.primitives do + local targets = {} + for ti, tb in tbuilt do + local tp = tb[pi].prim + local t: { [string]: Types.Accessor } = {} + for _, name in { "POSITION", "NORMAL" } do + local a, b = prim.attributes[name], tp.attributes[name] + if a and b and a.count == b.count then + local d = buffer.create(a.count * 12) + for i = 0, a.count * 3 - 1 do + local bv = buffer.readf32(b.data, i * 4) + buffer.writef32(d, i * 4, if relative then bv else bv - buffer.readf32(a.data, i * 4)) + end + t[name] = Scene.accessor(d, "f32", 3, a.count) + end + end + targets[ti] = t + end + prim.targets = targets + end + mesh.weights = weights + return idx +end + +-- ------------------------------------------------------------------------------------------------ cameras, lights +local function camera(C: Ctx, el: any): number? + local optics = child(el, "optics") + local tc = optics and child(optics, "technique_common") + if not tc then + return nil + end + local cam: Types.Camera + local persp, ortho = child(tc, "perspective"), child(tc, "orthographic") + if persp then + local xfov, yfov = child(persp, "xfov"), child(persp, "yfov") + local aspect = child(persp, "aspect_ratio") + local ar = if aspect then numText(aspect, 1) else nil + local yf: number + if yfov then + yf = math.rad(numText(yfov, 45)) + elseif xfov and ar then + yf = 2 * math.atan(math.tan(math.rad(numText(xfov, 45)) / 2) / ar) + else + yf = math.rad(numText(xfov, 45)) + end + if xfov and yfov and not ar then + local tx, ty = math.tan(math.rad(numText(xfov, 45)) / 2), math.tan(yf / 2) + ar = if ty > 0 then tx / ty else nil + end + cam = { name = attr(el, "name") or attr(el, "id"), type = "perspective", yfov = yf, aspect = ar, znear = numText(child(persp, "znear"), 0.1), zfar = numText(child(persp, "zfar"), 1000) } + elseif ortho then + local xm, ym = child(ortho, "xmag"), child(ortho, "ymag") + local ar = numText(child(ortho, "aspect_ratio"), 1) + local x = if xm then numText(xm, 1) else numText(ym, 1) * ar + local y = if ym then numText(ym, 1) else numText(xm, 1) / ar + cam = { name = attr(el, "name") or attr(el, "id"), type = "orthographic", xmag = x, ymag = y, znear = numText(child(ortho, "znear"), 0.1), zfar = numText(child(ortho, "zfar"), 1000) } + else + return nil + end + table.insert(C.scene.cameras, cam) + return #C.scene.cameras +end + +-- light(el) -> light index, or nil and the ambient colour +local function light(C: Ctx, el: any): (number?, { number }?) + local tc = child(el, "technique_common") + if not tc then + return nil, nil + end + local amb = child(tc, "ambient") + if amb then + return nil, color(amb) or { 1, 1, 1, 1 } + end + local kinds = { directional = "directional", point = "point", spot = "spot" } + for k, t in kinds do + local l = child(tc, k) + if l then + local c = color(l) or { 1, 1, 1 } + local lt: Types.Light = { name = attr(el, "name") or attr(el, "id"), type = t :: any, color = { c[1], c[2], c[3] }, intensity = 1 } + if t == "spot" then + local fa = numText(child(l, "falloff_angle"), 180) + lt.outerCone = math.clamp(math.rad(fa) / 2, 0, math.pi / 2) + lt.innerCone = 0 + end + table.insert(C.scene.lights, lt) + local idx = #C.scene.lights + if t ~= "directional" then + lt.extras = { + dae = { + constantAttenuation = numText(child(l, "constant_attenuation"), 1), + linearAttenuation = numText(child(l, "linear_attenuation"), 0), + quadraticAttenuation = numText(child(l, "quadratic_attenuation"), 0), + falloffExponent = if t == "spot" then numText(child(l, "falloff_exponent"), 0) else nil, + }, + } :: any + end + return idx, nil + end + end + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ nodes +local XFORMS = { matrix = 16, translate = 3, rotate = 4, scale = 3, lookat = 9, skew = 7 } + +-- the matrix of one transform element's values +local function xfMatrix(kind: string, v: { number }): { number } + if kind == "matrix" then + return M.fromRows(v) + elseif kind == "translate" then + return M.translation(v[1] or 0, v[2] or 0, v[3] or 0) + elseif kind == "rotate" then + return M.quatMatrix(M.axisAngle(v[1] or 0, v[2] or 0, v[3] or 1, v[4] or 0)) + elseif kind == "scale" then + return M.scaling(v[1] or 1, v[2] or 1, v[3] or 1) + elseif kind == "lookat" then + return M.lookat(v) + elseif kind == "skew" then + return M.skew(v) + end + return M.identity() +end + +local function compose(xf: { any }): { number } + local m = M.identity() + for _, x in xf do + m = M.mul(m, xfMatrix(x.kind, x.values)) + end + return m +end + +local function setTransform(node: Types.Node, m: { number }) + local t, r, s = M.decompose(m) + node.translation, node.rotation, node.scale, node.matrix = nil, nil, nil, nil + if t and r and s then + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + node.translation = t + end + if math.abs(r[4]) < 1 - 1e-9 then + node.rotation = r + end + if math.abs(s[1] - 1) > 1e-7 or math.abs(s[2] - 1) > 1e-7 or math.abs(s[3] - 1) > 1e-7 then + node.scale = s + end + else + for i = 1, 16 do + if math.abs(m[i] - M.identity()[i]) > 0 then + node.matrix = m + break + end + end + end +end + +local visitNode: (C: Ctx, el: any) -> number? + +local function addChild(C: Ctx, parent: Types.Node, node: Types.Node): number + table.insert(C.scene.nodes, node) + local idx = #C.scene.nodes + table.insert(parent.children, idx) + return idx +end + +-- the instances of a node: the first of each kind on the node itself, the rest on child nodes +local function instances(C: Ctx, el: any, node: Types.Node, idx: number) + local function slot(kind: string, name: string?): (Types.Node, number) + local n: any = node + if n[kind] == nil then + return node, idx + end + local extra: Types.Node = { name = name, children = {} } + return extra, addChild(C, node, extra) + end + for _, ch in children(el) do + local n = lname(ch) + if n == "instance_geometry" then + local g = C.ids[urlId(attr(ch, "url")) or ""] + if g and lname(g) == "geometry" then + local mi = meshFor(C, g, ch, "geom:" .. (attr(g, "id") or ""), nil) + if C.err then + return + end + if mi then + local target = slot("mesh", attr(g, "name")) + target.mesh = mi + end + end + elseif n == "instance_controller" then + local ctrl = C.ids[urlId(attr(ch, "url")) or ""] + local skinEl = ctrl and child(ctrl, "skin") + local morph = ctrl and child(ctrl, "morph") + if skinEl then + -- the skin's source may be a morph controller + local src = C.ids[urlId(attr(skinEl, "source")) or ""] + local morphEl = src and lname(src) == "controller" and child(src, "morph") + if morphEl then + src = C.ids[urlId(attr(morphEl, "source")) or ""] + skip(C, "skins over morph controllers (morph dropped)") + end + if src and lname(src) == "geometry" then + local bsm = child(skinEl, "bind_shape_matrix") + local bind = if bsm then M.fromRows(numbers(text(bsm), 16) or {}) else nil + local mi, built = meshFor(C, src, ch, "skin:" .. (attr(ctrl, "id") or ""), bind) + if C.err then + return + end + if mi and built then + local target, ti = slot("mesh", attr(ctrl, "name")) + target.mesh = mi + local roots = {} + for _, sk in children(ch, "skeleton") do + table.insert(roots, urlId(match(text(sk), "^%s*(.-)%s*$"))) + end + table.insert(C.pendingSkins, { node = ti, ctrl = ctrl, skin = skinEl, mesh = mi, built = built, roots = roots, bind = bind }) + end + end + elseif morph then + local mi = morphMesh(C, ctrl, morph, ch) + if C.err then + return + end + if mi then + local target = slot("mesh", attr(ctrl, "name")) + target.mesh = mi + target.weights = C.scene.meshes[mi].weights + end + end + elseif n == "instance_camera" then + local cel = C.ids[urlId(attr(ch, "url")) or ""] + local ci = cel and lname(cel) == "camera" and camera(C, cel) + if ci then + local target = slot("camera", C.scene.cameras[ci].name) + target.camera = ci + end + elseif n == "instance_light" then + local lel = C.ids[urlId(attr(ch, "url")) or ""] + if lel and lname(lel) == "light" then + local li, ambient = light(C, lel) + if li then + local target = slot("light", C.scene.lights[li].name) + target.light = li + elseif ambient then + local ex: any = node.extras or {} + ex.dae = ex.dae or {} + ex.dae.ambientLight = ambient + node.extras = ex + end + end + elseif n == "instance_node" then + local target = C.ids[urlId(attr(ch, "url")) or ""] + if target and lname(target) == "node" then + local ci = visitNode(C, target) + if ci then + table.insert(node.children, ci) + end + end + end + end +end + +visitNode = function(C: Ctx, el: any): number? + if C.depth > 256 or #C.scene.nodes > C.limit then + C.err = "node tree too deep or too large (instance_node cycle?)" + return nil + end + C.depth += 1 + local xf = {} + for _, ch in children(el) do + local n = lname(ch) + local want = XFORMS[n] + if want then + local v = numbers(text(ch), 64) or {} + table.insert(xf, { kind = n, sid = attr(ch, "sid"), values = v }) + end + end + local node: Types.Node = { name = attr(el, "name") or attr(el, "id"), children = {} } + setTransform(node, compose(xf)) + table.insert(C.scene.nodes, node) + local idx = #C.scene.nodes + local id = attr(el, "id") + C.info[idx] = { xf = xf, sid = attr(el, "sid"), id = id, joint = upper(attr(el, "type") or "") == "JOINT" } + if id then + C.nodeOf[id] = C.nodeOf[id] or {} + table.insert(C.nodeOf[id], idx) + end + if upper(attr(el, "type") or "") == "JOINT" then + node.extras = { dae = { joint = true, sid = attr(el, "sid") } } :: any + end + instances(C, el, node, idx) + for _, ch in children(el, "node") do + if C.err then + break + end + local ci = visitNode(C, ch) + if ci then + table.insert(node.children, ci) + end + end + C.depth -= 1 + return idx +end + +-- ------------------------------------------------------------------------------------------------ skins +-- the scene node for a joint name: by sid below the skeleton roots, else by sid / id / name anywhere +local function findJoint(C: Ctx, name: string, roots: { number }, byId: boolean): number? + local nodes = C.scene.nodes + local function search(i: number, depth: number): number? + if depth > 300 then + return nil + end + local inf = C.info[i] + if inf and (inf.sid == name or (byId and inf.id == name)) then + return i + end + for _, c in nodes[i].children do + local r = search(c, depth + 1) + if r then + return r + end + end + return nil + end + for _, r in roots do + local f = search(r, 0) + if f then + return f + end + end + for i in nodes do + local inf = C.info[i] + if inf and (inf.sid == name or inf.id == name) then + return i + end + end + for i, n in nodes do + if n.name == name then + return i + end + end + return nil +end + +local function resolveSkins(C: Ctx) + local cache: { [string]: number } = {} + for _, ps in C.pendingSkins do + local skinEl = ps.skin + local jointsEl = child(skinEl, "joints") + local names: { string } = {} + local byId = false + local ibm: any = nil + if jointsEl then + for _, inp in children(jointsEl, "input") do + local sem = upper(attr(inp, "semantic") or "") + local srcEl = C.ids[urlId(attr(inp, "source")) or ""] + local src = srcEl and lname(srcEl) == "source" and readSource(C, srcEl) + if src and sem == "JOINT" then + for _, v in src.data do + table.insert(names, tostring(v)) + end + byId = child(srcEl, "IDREF_array") ~= nil + elseif src and sem == "INV_BIND_MATRIX" then + ibm = src + end + end + end + local roots: { number } = {} + for _, r in ps.roots do + for _, ni in C.nodeOf[r] or {} do + table.insert(roots, ni) + end + end + local jointNodes: { number } = {} + local ok = #names > 0 + for i, nm in names do + local j = findJoint(C, nm, roots, byId) + if not j then + ok = false + break + end + jointNodes[i] = j + end + if not ok then + skip(C, "skins with unresolved joints") + continue + end + local key = (attr(ps.ctrl, "id") or "") .. "|" .. table.concat(jointNodes, ",") + local si = cache[key] + if not si then + local skin: Types.Skin = { name = attr(ps.ctrl, "name") or attr(ps.ctrl, "id"), joints = jointNodes } + if ps.bind then + local sk: any = skin + sk.extras = { dae = { bindShapeMatrix = ps.bind } } -- already applied to the mesh's positions / normals + end + if ibm and ibm.comps == 16 and ibm.count >= #names then + local b = buffer.create(#names * 64) + for i = 0, #names - 1 do + local cm = M.fromRows(ibm.data, i * 16 + 1) + for k = 1, 16 do + buffer.writef32(b, (i * 16 + k - 1) * 4, cm[k]) + end + end + local acc = Scene.accessor(b, "f32", 16, #names) + acc.matrix = true + skin.inverseBindMatrices = acc + end + if roots[1] then + skin.skeleton = roots[1] + end + table.insert(C.scene.skins, skin) + si = #C.scene.skins + cache[key] = si + end + C.scene.nodes[ps.node].skin = si + -- vertex weights -> JOINTS_0 / WEIGHTS_0 (once per mesh) + local mesh = C.scene.meshes[ps.mesh] + if mesh.primitives[1] and mesh.primitives[1].attributes.JOINTS_0 then + continue + end + local vw = child(skinEl, "vertex_weights") + if not vw then + continue + end + local jOff, wOff, wSrc = 0, 1, nil + local stride = 1 + for _, inp in children(vw, "input") do + local sem = upper(attr(inp, "semantic") or "") + local off = tonumber(attr(inp, "offset") or "") or 0 + stride = math.max(stride, off + 1) + if sem == "JOINT" then + jOff = off + elseif sem == "WEIGHT" then + wOff = off + wSrc = sourceById(C, attr(inp, "source")) + end + end + local vcount = numbers(text(child(vw, "vcount") or ""), C.limit) or {} + local v = numbers(text(child(vw, "v") or ""), C.limit * 8) or {} + local wdata = wSrc and wSrc.data or {} + local per: { { number } } = {} -- position index -> { j1, w1, j2, w2, ... } strongest 4 + local at = 0 + for pi, c in vcount do + local list = {} + for _ = 1, math.floor(c) do + local j, w = v[at + jOff + 1], v[at + wOff + 1] + at += stride + local wv = if w then wdata[w + 1] else nil + if j and j >= 0 and j < #names and type(wv) == "number" and wv > 0 then + table.insert(list, { j, wv }) + end + end + table.sort(list, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local total = 0 + for k = 1, math.min(4, #list) do + total += list[k][2] + end + local e = {} + for k = 1, math.min(4, #list) do + e[k * 2 - 1], e[k * 2] = list[k][1], list[k][2] / total + end + per[pi] = e + end + for pi, prim in mesh.primitives do + local posIndex = ps.built[pi] and ps.built[pi].posIndex + local n = prim.attributes.POSITION.count + if posIndex and #posIndex == n then + local jt = if #names < 256 then "u8" else "u16" + local js = if jt == "u8" then 1 else 2 + local jb = buffer.create(n * 4 * js) + local wb = buffer.create(n * 16) + for vi = 0, n - 1 do + local e = per[posIndex[vi + 1] + 1] + for k = 0, 3 do + local j, w = 0, 0 + if e and e[k * 2 + 1] then + j, w = e[k * 2 + 1], e[k * 2 + 2] + end + if js == 1 then + buffer.writeu8(jb, vi * 4 + k, j) + else + buffer.writeu16(jb, (vi * 4 + k) * 2, j) + end + buffer.writef32(wb, (vi * 4 + k) * 4, w) + end + end + prim.attributes.JOINTS_0 = Scene.accessor(jb, jt, 4, n) + prim.attributes.WEIGHTS_0 = Scene.accessor(wb, "f32", 4, n) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ animations +type Curve = { input: { number }, output: { number }, stride: number, interp: { string }, member: number?, xf: any } + +local function sample(c: Curve, t: number): { number } + local inp, out, st = c.input, c.output, c.stride + local n = #inp + local function at(i: number): { number } + local r = table.create(st) + for k = 1, st do + r[k] = out[(i - 1) * st + k] or 0 + end + return r + end + if n == 0 then + return {} + end + if t <= inp[1] then + return at(1) + end + if t >= inp[n] then + return at(n) + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if inp[mid] <= t then + lo = mid + else + hi = mid + end + end + local a, b = at(lo), at(hi) + if c.interp[lo] == "STEP" then + return a + end + local span = inp[hi] - inp[lo] + local f = if span > 0 then (t - inp[lo]) / span else 0 + for k = 1, st do + a[k] += (b[k] - a[k]) * f + end + return a +end + +-- resolve "id/sid/sid.member" or "id/sid(i)(j)" to a node's transform element +local function target(C: Ctx, s: string): ({ number }?, any, number?) + -- the id may contain dots (assimp writes "Bone.001/matrix"); sids cannot, so the member starts after the last "/" + local id, sids = match(s, "^([^/]*)/(.*)$") + if not id then + return nil, nil, nil + end + local spath, rest = match(sids, "^([^%.%(]*)(.*)$") + if not spath then + return nil, nil, nil + end + local parts = string.split(id .. "/" .. spath, "/") + local nodes = C.nodeOf[parts[1]] + if not nodes or #parts < 2 then + return nil, nil, nil + end + local sid = parts[#parts] + local info = C.info[nodes[1]] + local xf: any = nil + for _, x in info.xf do + if x.sid == sid then + xf = x + break + end + end + if not xf then + return nil, nil, nil + end + local member: number? = nil + if rest and rest ~= "" then + local m1 = match(rest, "^%.(.+)$") + if m1 then + member = MEMBER[upper(m1)] + if not member then + return nil, nil, nil + end + else + local i, j = match(rest, "^%((%d+)%)%((%d+)%)$") + if i then + member = tonumber(i) :: number * 4 + tonumber(j) :: number + 1 + else + local k = match(rest, "^%((%d+)%)$") + if not k then + return nil, nil, nil + end + member = tonumber(k) :: number + 1 + end + end + end + return nodes, xf, member +end + +-- the channels of one (recursively) -> curves grouped by node +local function collect(C: Ctx, anim: any, byNode: { [number]: { Curve } }, order: { number }, depth: number) + if depth > 64 then + return + end + for _, ch in children(anim, "channel") do + local smp = C.ids[urlId(attr(ch, "source")) or ""] + local nodes, xf, member = target(C, attr(ch, "target") or "") + if smp and lname(smp) == "sampler" and nodes and xf then + local input, output, interp: any = nil, nil, nil + for _, inp in children(smp, "input") do + local sem = upper(attr(inp, "semantic") or "") + local src = sourceById(C, attr(inp, "source")) + if sem == "INPUT" then + input = src + elseif sem == "OUTPUT" then + output = src + elseif sem == "INTERPOLATION" then + interp = src + end + end + if input and output and input.count > 0 then + local stride = if member then 1 else #xf.values + local ins = {} + for i = 1, input.count do + local x = input.data[(i - 1) * input.comps + 1] + ins[i] = if type(x) == "number" then x else 0 + end + local outs = output.data + if #outs >= input.count * stride then + local ip = {} + if interp then + for i = 1, input.count do + ip[i] = upper(tostring(interp.data[i] or "LINEAR")) + end + end + local curve: Curve = { input = ins, output = outs, stride = stride, interp = ip, member = member, xf = xf } + for _, ni in nodes do + if not byNode[ni] then + byNode[ni] = {} + table.insert(order, ni) + end + table.insert(byNode[ni], curve) + end + end + end + elseif not (nodes and xf) then + skip(C, "animation channels on other targets") + end + end + for _, sub2 in children(anim, "animation") do + collect(C, sub2, byNode, order, depth + 1) + end +end + +local function bake(C: Ctx, name: string?, byNode: { [number]: { Curve } }, order: { number }): Types.Animation? + local channels: { Types.Channel } = {} + for _, ni in order do + local curves = byNode[ni] + local info = C.info[ni] + -- the union of the key times, plus subdivisions of rotations over 90 degrees + local set: { [number]: boolean } = {} + local times: { number } = {} + local function add(t: number) + if not set[t] then + set[t] = true + table.insert(times, t) + end + end + for _, c in curves do + for i, t in c.input do + add(t) + if i > 1 and c.xf.kind == "rotate" and (c.member == 4 or c.member == nil) then + local k = if c.member then 1 else 4 + local a, b = c.output[(i - 2) * c.stride + k] or 0, c.output[(i - 1) * c.stride + k] or 0 + local steps = math.min(math.ceil(math.abs(b - a) / 90), 64) + for s = 1, steps - 1 do + add(c.input[i - 1] + (t - c.input[i - 1]) * s / steps) + end + end + end + if #times > C.limit then + return nil + end + end + table.sort(times) + local n = #times + local tb, rb, sb = buffer.create(n * 12), buffer.create(n * 16), buffer.create(n * 12) + local prev: { number }? = nil + for i, t in times do + -- this time's values of each animated element + local xf = {} + for k, x in info.xf do + xf[k] = { kind = x.kind, values = table.clone(x.values) } + end + for _, c in curves do + local v = sample(c, t) + local k = table.find(info.xf, c.xf) + if k then + local vals = xf[k].values + if c.member then + vals[c.member] = v[1] or 0 + else + for j = 1, #v do + vals[j] = v[j] + end + end + end + end + local tr, ro, sc = M.decompose(compose(xf)) + tr, ro, sc = tr or { 0, 0, 0 }, ro or { 0, 0, 0, 1 }, sc or { 1, 1, 1 } + if prev and prev[1] * ro[1] + prev[2] * ro[2] + prev[3] * ro[3] + prev[4] * ro[4] < 0 then + ro = { -ro[1], -ro[2], -ro[3], -ro[4] } + end + prev = ro + for k = 1, 3 do + buffer.writef32(tb, ((i - 1) * 3 + k - 1) * 4, tr[k]) + buffer.writef32(sb, ((i - 1) * 3 + k - 1) * 4, sc[k]) + end + for k = 1, 4 do + buffer.writef32(rb, ((i - 1) * 4 + k - 1) * 4, ro[k]) + end + end + local ib = buffer.create(n * 4) + for i, t in times do + buffer.writef32(ib, (i - 1) * 4, t) + end + local input = Scene.accessor(ib, "f32", 1, n) + table.insert(channels, { node = ni, path = "translation", input = input, output = Scene.accessor(tb, "f32", 3, n), interpolation = "LINEAR" }) + table.insert(channels, { node = ni, path = "rotation", input = input, output = Scene.accessor(rb, "f32", 4, n), interpolation = "LINEAR" }) + table.insert(channels, { node = ni, path = "scale", input = input, output = Scene.accessor(sb, "f32", 3, n), interpolation = "LINEAR" }) + -- the node is now TRS-driven + local node = C.scene.nodes[ni] + if node.matrix then + setTransform(node, node.matrix) + end + end + if #channels == 0 then + return nil + end + return { name = name, channels = channels } +end + +local function animations(C: Ctx, root: any) + local libs = children(root, "library_animations") + if #libs == 0 then + return + end + local clipsLib = child(root, "library_animation_clips") + local clips = clipsLib and children(clipsLib, "animation_clip") or {} + if #clips > 0 then + for _, clip in clips do + local byNode, order = {}, {} + for _, ia in children(clip, "instance_animation") do + local a = C.ids[urlId(attr(ia, "url")) or ""] + if a and lname(a) == "animation" then + collect(C, a, byNode, order, 0) + end + end + local anim = bake(C, attr(clip, "name") or attr(clip, "id"), byNode, order) + if anim then + table.insert(C.scene.animations, anim) + end + end + return + end + local byNode, order = {}, {} + local name: string? = nil + local count = 0 + for _, lib in libs do + for _, a in children(lib, "animation") do + collect(C, a, byNode, order, 0) + count += 1 + name = name or attr(a, "name") or attr(a, "id") + end + end + local anim = bake(C, if count == 1 then name else nil, byNode, order) + if anim then + table.insert(C.scene.animations, anim) + end +end + +-- ------------------------------------------------------------------------------------------------ scene +function Read.scene(doc: any, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?) + local root = doc and doc.root + if not root or lname(root) ~= "COLLADA" then + return nil, Err.new(Err.CORRUPT, "no root element") + end + local scene = Scene.new() + local C: Ctx = { + doc = doc, + ids = {}, + fetch = fetch, + scene = scene, + limit = opts and opts.maxVertices or 2 ^ 25, + vertices = 0, + flipV = not (opts and opts.flipV == false), + triangulate = not (opts and opts.triangulate == false), + sources = {}, + materials = {}, + textures = {}, + images = {}, + meshes = {}, + skins = {}, + posIndex = {}, + nodeOf = {}, + info = {}, + pendingSkins = {}, + skipped = {}, + err = nil, + depth = 0, + } + for _, el in Xml.descendants(root) do + local id = el.attrs.id + -- duplicate ids: the first one, unless it is empty (some exporters write before the real one) + if type(id) == "string" and (C.ids[id] == nil or #C.ids[id].children == 0) then + C.ids[id] = el + end + end + -- asset: up axis, unit + local asset = child(root, "asset") + local up = asset and child(asset, "up_axis") + local upAxis = if up then upper(match(text(up), "[%w_]+") or "Y_UP") else "Y_UP" + scene.meta.up = if upAxis == "Z_UP" then "z" elseif upAxis == "X_UP" then "x" :: any else "y" + local unit = asset and child(asset, "unit") + local meter = unit and attr(unit, "meter") + scene.meta.unit = if meter then tonumber(meter) or tonumber((string.gsub(meter, ",", "."))) or 1 else 1 + -- the instanced visual scene (else the first one) + local vsId: string? = nil + local sceneEl = child(root, "scene") + local ivs = sceneEl and child(sceneEl, "instance_visual_scene") + if ivs then + vsId = urlId(attr(ivs, "url")) + end + local vs = vsId and C.ids[vsId] + if not vs or lname(vs) ~= "visual_scene" then + local lib = child(root, "library_visual_scenes") + vs = lib and child(lib, "visual_scene") + end + if vs then + for _, n in children(vs, "node") do + local idx = visitNode(C, n) + if C.err then + break + end + if idx then + table.insert(scene.roots, idx) + end + end + end + if C.err then + return nil, Err.new(if find(C.err :: string, "limit", 1, true) then Err.LIMIT else Err.CORRUPT, C.err :: string) + end + resolveSkins(C) + animations(C, root) + if C.err then + return nil, Err.new(Err.CORRUPT, C.err :: string) + end + local contributor = asset and child(asset, "contributor") + local tool = contributor and child(contributor, "authoring_tool") + scene.meta.source = { + format = "dae", + version = attr(root, "version"), + upAxis = upAxis, + authoringTool = if tool then text(tool) else nil, + skipped = if next(C.skipped) then C.skipped else nil, + } + return scene, nil +end + +return Read diff --git a/src/Formats/model/dae/Write.luau b/src/Formats/model/dae/Write.luau new file mode 100644 index 0000000..86e6d2a --- /dev/null +++ b/src/Formats/model/dae/Write.luau @@ -0,0 +1,376 @@ +--!strict +-- model/dae/Write: Scene -> Collada 1.4.1 text. One per mesh primitive (triangles, lines or polylist; strips +-- and fans unrolled into triangles, points skipped) with POSITION / NORMAL / TEXCOORD_n (V flipped back) / COLOR_n +-- sources sharing one index; common-profile phong (or lambert / constant) effects from the PBR material and its +-- extras.phong; images as files (opts.files), their uri, or data: URIs; the node tree as row-major ; cameras; +-- lights. Not written: skins, morph targets, animations. +local Types = require("@formats/Types") +local Xml = require("@formats/codecs/Xml") +local Base64 = require("@formats/codecs/Base64") +local M = require("@formats/model/dae/Math") + +local Write = {} + +local Scene = Types.Scene +local format, concat = string.format, table.concat +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/tga"] = "tga", ["image/bmp"] = "bmp", ["image/gif"] = "gif" } + +local function f(v: number): string + if v ~= v or v == math.huge or v == -math.huge then + return "0" + end + if v == math.floor(v) and math.abs(v) < 1e15 then + return format("%d", v) + end + return format("%.9g", v) +end +local function list(v: { number }): string + local out = table.create(#v) + for i, x in v do + out[i] = f(x) + end + return concat(out, " ") +end +local function esc(s: string): string + return Xml.escapeAttr(s) +end +local function nameAttr(s: string?): string + return if s then ' name="' .. esc(s) .. '"' else "" +end + +-- triangle / line corner lists of a primitive (0-based vertex indices) and the element kind +local function corners(prim: Types.Primitive): ({ number }?, string?, { number }?) + local n = prim.attributes.POSITION.count + local idx: { number } = {} + if prim.indices then + local get = Scene.reader(prim.indices) + if not get then + return nil, nil, nil + end + for i = 0, prim.indices.count - 1 do + idx[i + 1] = get(i, 0) + end + else + for i = 0, n - 1 do + idx[i + 1] = i + end + end + for _, i in idx do + if i < 0 or i >= n then + return nil, nil, nil + end + end + local mode = prim.mode or "triangles" + if mode == "triangles" then + local m = #idx - #idx % 3 + return table.move(idx, 1, m, 1, {}), "triangles", nil + elseif mode == "triangle_strip" or mode == "triangle_fan" then + local out = {} + for k = 1, #idx - 2 do + if mode == "triangle_fan" then + table.insert(out, idx[1]) + table.insert(out, idx[k + 1]) + table.insert(out, idx[k + 2]) + elseif k % 2 == 1 then + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + table.insert(out, idx[k + 2]) + else + table.insert(out, idx[k + 1]) + table.insert(out, idx[k]) + table.insert(out, idx[k + 2]) + end + end + return out, "triangles", nil + elseif mode == "lines" then + local m = #idx - #idx % 2 + return table.move(idx, 1, m, 1, {}), "lines", nil + elseif mode == "line_strip" or mode == "line_loop" then + local out = {} + for k = 1, #idx - 1 do + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + end + if mode == "line_loop" and #idx > 2 then + table.insert(out, idx[#idx]) + table.insert(out, idx[1]) + end + return out, "lines", nil + elseif mode == "polygons" and prim.faces then + local get = Scene.reader(prim.faces) + if not get then + return nil, nil, nil + end + local sizes = {} + local total = 0 + for i = 0, prim.faces.count - 1 do + sizes[i + 1] = get(i, 0) + total += sizes[i + 1] + end + if total ~= #idx then + return nil, nil, nil + end + return idx, "polylist", sizes + end + return nil, nil, nil +end + +local function source(out: { string }, id: string, acc: Types.Accessor, comps: number, params: { string }, flipV: boolean) + local get = Scene.reader(acc) + if not get then + return + end + local vals = table.create(acc.count * comps) + local n = 0 + for i = 0, acc.count - 1 do + for c = 0, comps - 1 do + n += 1 + local v = if c < acc.components then get(i, c) else (if c == 3 then 1 else 0) + if flipV and c == 1 then + v = 1 - v + end + vals[n] = f(v) + end + end + table.insert(out, format('%s', id, id, n, concat(vals, " "))) + local ps = {} + for c = 1, comps do + ps[c] = format('', params[c] or "V") + end + table.insert(out, format('%s\n', id, acc.count, comps, concat(ps))) +end + +local function colorEl(tag: string, c: { number }?, tex: string?, uv: number?): string + if tex then + return format('<%s>', tag, tex, uv or 0, tag) + end + local v = c or { 0, 0, 0, 1 } + return format("<%s>%s %s %s %s", tag, f(v[1] or 0), f(v[2] or 0), f(v[3] or 0), f(v[4] or 1), tag) +end + +function Write.build(scene: Types.Scene, opts: any?): string? + local files = opts and type(opts.files) == "table" and opts.files or nil + local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + local flipV = not (opts and opts.flipV == false) + local out: { string } = {} + local function w(s: string) + table.insert(out, s) + end + w('\n\n') + local meta = scene.meta or {} + local up = if meta.up == "z" then "Z_UP" elseif meta.up == "x" then "X_UP" else "Y_UP" + w(format('formats-luau1970-01-01T00:00:00Z1970-01-01T00:00:00Z%s\n', f(meta.unit or 1), up)) + -- images + local imageId: { [number]: string } = {} + if #scene.textures > 0 then + w("\n") + for i, tex in scene.textures do + local uri: string? = nil + if tex.data then + if files then + uri = format("%s_%d.%s", base, i, EXT[tex.mime or ""] or "png") + files[uri :: string] = tex.data + else + uri = Base64.dataUri(tex.data, tex.mime or "image/png") + end + elseif tex.uri then + uri = tex.uri + end + if uri then + local id = "image" .. i + imageId[i] = id + w(format('%s\n', id, nameAttr(tex.name), Xml.escape(uri :: string))) + end + end + w("\n") + end + -- effects + materials + if #scene.materials > 0 then + w("\n") + for i, mat in scene.materials do + local ph: any = mat.extras and mat.extras.phong or {} + local params = {} + local function texParam(ref: Types.TextureRef?): (string?, number?) + if not ref or not imageId[ref.texture] then + return nil, nil + end + local sid = "tex" .. ref.texture + if not params[sid] then + params[sid] = true + table.insert(params, format('%s%s-surface', sid, imageId[ref.texture], sid, sid)) + end + return sid, ref.texCoord + end + local dtex, duv = texParam(mat.baseColorTexture) + local etex, euv = texParam(mat.emissiveTexture) + local ntex, nuv = texParam(mat.normalTexture) + local unlit = mat.extensions and mat.extensions.KHR_materials_unlit ~= nil + local model = if unlit then "constant" elseif ph.model == "lambert" then "lambert" else "phong" + local body = {} + local bc = mat.baseColor + if unlit then + table.insert(body, colorEl("emission", { bc[1], bc[2], bc[3], 1 }, nil, nil)) + else + table.insert(body, colorEl("emission", if type(ph.emission) == "table" then ph.emission else { mat.emissive[1], mat.emissive[2], mat.emissive[3], 1 }, etex, euv)) + table.insert(body, colorEl("ambient", if type(ph.ambient) == "table" then ph.ambient else { 0, 0, 0, 1 }, nil, nil)) + table.insert(body, colorEl("diffuse", { bc[1], bc[2], bc[3], 1 }, dtex, duv)) + if model == "phong" then + table.insert(body, colorEl("specular", if type(ph.specular) == "table" then ph.specular else { 0, 0, 0, 1 }, nil, nil)) + local sh = if type(ph.shininess) == "number" then ph.shininess else math.max(2 / math.max((mat.roughness or 1) ^ 2, 1e-4) - 2, 0) + table.insert(body, format("%s", f(sh))) + end + end + if (bc[4] or 1) < 1 then + table.insert(body, '1 1 1 1') + table.insert(body, format("%s", f(bc[4]))) + end + local extra = "" + if ntex or mat.doubleSided then + extra = "" .. (if ntex then format('', ntex, nuv or 0) else "") .. (if mat.doubleSided then "1" else "") .. "" + end + w(format('%s<%s>%s%s\n', i, concat(params), model, concat(body), model, extra)) + end + w("\n\n") + for i, mat in scene.materials do + w(format('\n', i, nameAttr(mat.name), i)) + end + w("\n") + end + -- geometries: one per primitive + local geoms: { [number]: { { id: string, material: number?, sets: number } } } = {} + w("\n") + for mi, mesh in scene.meshes do + geoms[mi] = {} + for pi, prim in mesh.primitives do + local pos = prim.attributes and prim.attributes.POSITION + if not pos then + continue + end + local idx, kind, sizes = corners(prim) + if not idx or not kind or #idx == 0 then + continue + end + local id = format("mesh%d-%d", mi, pi) + w(format('\n', id, nameAttr(mesh.name))) + source(out, id .. "-positions", pos, 3, { "X", "Y", "Z" }, false) + local ins = { format('', id) } + if prim.attributes.NORMAL then + source(out, id .. "-normals", prim.attributes.NORMAL, 3, { "X", "Y", "Z" }, false) + table.insert(ins, format('', id)) + end + local sets = 0 + for k = 0, 7 do + local a = prim.attributes["TEXCOORD_" .. k] + if not a then + break + end + source(out, format("%s-uv%d", id, k), a, 2, { "S", "T" }, flipV) + table.insert(ins, format('', id, k, k)) + sets += 1 + end + for k = 0, 7 do + local a = prim.attributes["COLOR_" .. k] + if not a then + break + end + local c = if a.components >= 4 then 4 else 3 + source(out, format("%s-color%d", id, k), a, c, { "R", "G", "B", "A" }, false) + table.insert(ins, format('', id, k, k)) + end + w(format('\n', id, id)) + local matAttr = if prim.material and scene.materials[prim.material] then format(' material="m%d"', prim.material) else "" + local count = if kind == "triangles" then #idx // 3 elseif kind == "lines" then #idx // 2 else #(sizes :: { number }) + w(format('<%s count="%d"%s>%s', kind, count, matAttr, concat(ins))) + if sizes then + w("" .. list(sizes) .. "") + end + w("

" .. list(idx) .. "

\n
\n") + table.insert(geoms[mi], { id = id, material = if matAttr ~= "" then prim.material else nil, sets = sets }) + end + end + w("
\n") + -- cameras / lights + if #scene.cameras > 0 then + w("\n") + for i, cam in scene.cameras do + local body: string + if cam.type == "orthographic" then + body = format("%s%s%s%s", f(cam.xmag or 1), f(cam.ymag or 1), f(cam.znear or 0.1), f(cam.zfar or 1000)) + else + body = format("%s%s%s%s", f(math.deg(cam.yfov or 0.8)), if cam.aspect then format("%s", f(cam.aspect)) else "", f(cam.znear or 0.1), f(cam.zfar or 1000)) + end + w(format('%s\n', i, nameAttr(cam.name), body)) + end + w("\n") + end + if #scene.lights > 0 then + w("\n") + for i, l in scene.lights do + local c = l.color or { 1, 1, 1 } + local k = l.intensity or 1 + local col = format("%s %s %s", f(c[1] * k), f(c[2] * k), f(c[3] * k)) + local body = if l.type == "spot" then format("%s100%s0", col, f(math.deg(l.outerCone or math.pi / 4) * 2)) + elseif l.type == "point" then format("%s100", col) + else format("%s", col) + w(format('%s\n', i, nameAttr(l.name), body)) + end + w("\n") + end + -- the node tree + w('\n') + local seen: { [number]: boolean } = {} + local function node(i: number, depth: number) + local n = scene.nodes[i] + if not n or seen[i] or depth > 512 then + return + end + seen[i] = true + w(format('%s', i, nameAttr(n.name), list(M.toRows(Scene.nodeMatrix(n))))) + if n.mesh and geoms[n.mesh] then + for _, g in geoms[n.mesh] do + if g.material then + local binds = {} + for k = 0, g.sets - 1 do + table.insert(binds, format('', k, k)) + end + w(format('%s', g.id, g.material, g.material, concat(binds))) + else + w(format('', g.id)) + end + end + end + if n.camera and scene.cameras[n.camera] then + w(format('', n.camera)) + end + if n.light and scene.lights[n.light] then + w(format('', n.light)) + end + w("\n") + for _, c in n.children or {} do + node(c, depth + 1) + end + w("\n") + end + local roots = scene.roots + if not roots or #roots == 0 then + local isChild = {} + for _, n in scene.nodes do + for _, c in n.children or {} do + isChild[c] = true + end + end + roots = {} + for i in scene.nodes do + if not isChild[i] then + table.insert(roots, i) + end + end + end + for _, r in roots do + node(r, 0) + end + w('\n\n
\n') + return concat(out) +end + +return Write diff --git a/src/Formats/model/dae/init.luau b/src/Formats/model/dae/init.luau new file mode 100644 index 0000000..1e245b1 --- /dev/null +++ b/src/Formats/model/dae/init.luau @@ -0,0 +1,206 @@ +--!strict +-- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos COLLADA specifications; .dae XML, and .zae: a zip holding the .dae, its +-- manifest.xml and the images). New code. +-- Reads: geometry ( triangles / polylist / polygons / lines / linestrips / tristrips / trifans with shared input +-- offsets, de-indexed per index tuple; n-gons fan-triangulated unless opts.triangulate = false keeps "polygons"), +-- common-profile materials (phong / blinn / lambert / constant -> PBR baseColor / emissive / roughness from shininess / +-- alpha from transparent + transparency; every Phong term kept in material.extras.phong; FCOLLADA / MAX3D bump -> +-- normalTexture, double_sided), images through newparam sampler2D -> surface -> image (1.4) or instance_image (1.5), +-- kept encoded (opts.resolve / opts.files, embedded hex , data: URIs), the instanced visual scene (matrix / +-- translate / rotate / scale / lookat / skew; instance_geometry / controller / camera / light / node; extra instances +-- of a node become child nodes), skin controllers (bind_shape_matrix applied to the mesh, joints by sid under +-- or by id / name, INV_BIND_MATRIX, JOINTS_0 / WEIGHTS_0 from the 4 strongest weights, normalized), morph +-- controllers (targets as POSITION / NORMAL deltas, weights), cameras (perspective: yfov from xfov / aspect; +-- orthographic), lights (directional / point / spot; attenuation in light.extras.dae; ambient lights as +-- node.extras.dae.ambientLight), animations (channels on node transform elements: whole elements, .X / .ANGLE +-- members, matrix (i)(j) elements; resampled at the union of their key times, rotations over 90 degrees subdivided, +-- into glTF TRS channels; one animation per animation_clip, else one for the file). meta.up = the up_axis ("y" / "z" +-- / "x"), meta.unit = unit meter; the data is never rotated or scaled. TEXCOORD_n V is flipped to glTF's top-left +-- origin (opts.flipV = false keeps Collada's). +-- Writes: Collada 1.4.1 (see model/dae/Write: meshes, materials, images, nodes, cameras, lights), or a .zae. +-- Not supported: / geometry, polygon holes (: the outer loop only), Bezier / Hermite curves +-- (sampled linearly at their keys), animations of non-transform targets, physics / kinematics / FX profiles other than +-- COMMON (counted in meta.source.skipped). Writing skins, morphs and animations. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Xml = require("@formats/codecs/Xml") +local Zip = require("@formats/containers/Zip") +local Read = require("@formats/model/dae/Read") +local Write = require("@formats/model/dae/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Dae = { + name = "dae", + category = "model", + extensions = { "dae", "zae" }, + mime = { "model/vnd.collada+xml", "model/vnd.collada+zip" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Base64", "containers/Zip" }, + caps = { decode = true, encode = true, materials = true, polygons = true, skins = true, morphTargets = true, animation = true, cameras = true, lights = true, zae = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + resolve: ((uri: string) -> any)?, -- image files (buffer or string); the api sets it for paths + files: { [string]: any }?, -- or: the files by uri / base name + triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives + flipV: boolean?, -- TEXCOORD_n v = 1 - v (default true: glTF's convention) + maxVertices: number?, -- refuse more output vertices / array values (default 2^25) +} +export type EncodeOptions = { + files: { [string]: any }?, -- receives the texture images (else they are written as data: URIs or their uri) + name: string?, -- the destination's file name (names the image files) + flipV: boolean?, -- default true (the inverse of decode) + format: string?, -- "zae" writes a zip (manifest.xml + model.dae + images); the api passes the extension +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Dae.sniff(r: Bytes.Reader): number + local head = r:peek(2048) + if string.sub(head, 1, 4) == "PK\3\4" then + local nlen = string.byte(head, 27) or 0 + local name = string.lower(string.sub(head, 31, 30 + nlen)) + if string.find(name, "%.dae$") or name == "manifest.xml" then + return 0.95 + end + return 0 + end + -- UTF-16 files: drop the zero bytes + if string.find(string.sub(head, 1, 4), "\0", 1, true) then + head = string.gsub(head, "%z", "") + end + if string.find(head, ", else the first .dae entry +local function zae(r: Bytes.Reader): (any, string?, Err.Err?) + local zip, err = Zip.open(r) + if not zip then + return nil, nil, err + end + local main: string? = nil + local manifest = zip:readString("manifest.xml") + if manifest then + local d = Xml.decode(manifest) + local rootEl = d and d.root and Xml.child(d.root, "dae_root") + if rootEl then + main = string.match(Xml.text(rootEl), "^%s*(.-)%s*$") + main = main and string.gsub(main, "^%./", "") + end + end + if not main or not zip:find(main) then + main = nil + for _, e in zip:list() do + if string.find(string.lower(e.name), "%.dae$") then + main = e.name + break + end + end + end + if not main then + return nil, nil, Err.new(Err.CORRUPT, "zae without a .dae") + end + local text, rerr = zip:readString(main) + if not text then + return nil, nil, rerr + end + return zip, text, nil +end + +function Dae.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text: string + local zip: any = nil + if r:peek(4) == "PK\3\4" then + local z, t, err = zae(r) + if not z then + return nil, err + end + zip, text = z, t :: string + else + text = buffer.readstring(r.buf, r.base, r.limit - r.base) + end + local doc, xerr = Xml.decode(text) + if not doc then + return nil, xerr + end + local scene, err = Read.scene(doc, fetcher(opts, zip), opts) + if not scene then + return nil, err + end + if zip and scene.meta.source then + scene.meta.source.zae = true + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Dae.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.meshes) ~= "table" or type(scene.nodes) ~= "table" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + if opts and opts.format == "zae" then + -- a zip: manifest.xml, the .dae and its images + local files = {} + local o = table.clone(opts) + o.files = files + o.name = "model.dae" + local text = Write.build(scene, o) + if not text then + return nil, Err.new(Err.ARG, "the scene could not be written") + end + local w = Zip.writer() + w:add("manifest.xml", '\n./model.dae\n') + w:add("model.dae", text) + local names = {} + for name in files do + table.insert(names, name) + end + table.sort(names) + for _, name in names do + w:add(name, files[name], { method = "store" }) + end + return w:finish() + end + local text = Write.build(scene, opts) + if not text then + return nil, Err.new(Err.ARG, "the scene could not be written") + end + return buffer.fromstring(text), nil +end + +return Dae diff --git a/tests/model/dae.luau b/tests/model/dae.luau new file mode 100644 index 0000000..d27e246 --- /dev/null +++ b/tests/model/dae.luau @@ -0,0 +1,581 @@ +-- model/dae tests: assimp's Collada test models (triangles / polylist / polygons / tristrips, UTF-16 and BOM files, +-- decimal commas, 2 UV sets, vertex colours, instance_node, cameras, lights, nested / clipped / full-rotation +-- animations, skins, .zae) and glTF samples exported by assimp's Collada exporter, against `assimp info -r` (meshes, +-- faces, bounds in assimp's space, materials, animations, cameras, lights), and against the glTF originals read by +-- model/gltf (skinned rest-pose bounds, joints, every LINEAR animation key); our writer's output read back by assimp +-- (dae_xcheck) and by us (round trips, .dae and .zae); polygons kept with triangulate = false; textures decoded lazily +-- at the api layer; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/dae.py. +local T = require("@tests/T") +local F = require("@formats") +local Dae = require("@formats/model/dae") +local Gltf = require("@formats/model/gltf") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/dae_cases") +local Xcheck = require("@tests/gen/dae_xcheck") + +local Scene = Types.Scene +local t = T.suite("dae") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Dae.decode(Bytes.reader(b), opts) +end + +t:eq(Dae.name, "dae", "name") +t:eq(Dae.category, "model", "category") +t:check(Dae.caps.decode and Dae.caps.encode and table.find(Dae.extensions, "zae"), "contract") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end +local function nearV(a: { number }, b: { number }, eps: number): boolean + for i = 1, #b do + if not near(a[i], b[i], eps) then + return false + end + end + return #a == #b +end +local function fmt(v: { number }?): string + if not v then + return "-" + end + return string.format("(%.4g %.4g %.4g)", v[1], v[2], v[3]) +end + +-- assimp's counts: one mesh per primitive reached (instances of one primitive once), faces as stored +local function counts(scene: any): (number, number) + local prims, faces = 0, 0 + local seen = {} + for _, pl in Scene.flatten(scene) do + if not seen[pl.primitive] then + seen[pl.primitive] = true + local p = pl.primitive + prims += 1 + if p.mode == "polygons" then + faces += p.faces.count + elseif p.mode == "triangles" then + faces += p.indices.count // 3 + elseif p.mode == "lines" then + faces += p.indices.count // 2 + end + end + end + return prims, faces +end + +local function inverse(m: { number }): { number } + -- general 4x4 inverse (column-major; cofactors) + local inv = table.create(16, 0) + local a = m + inv[1] = a[6] * a[11] * a[16] - a[6] * a[12] * a[15] - a[10] * a[7] * a[16] + a[10] * a[8] * a[15] + a[14] * a[7] * a[12] - a[14] * a[8] * a[11] + inv[5] = -a[5] * a[11] * a[16] + a[5] * a[12] * a[15] + a[9] * a[7] * a[16] - a[9] * a[8] * a[15] - a[13] * a[7] * a[12] + a[13] * a[8] * a[11] + inv[9] = a[5] * a[10] * a[16] - a[5] * a[12] * a[14] - a[9] * a[6] * a[16] + a[9] * a[8] * a[14] + a[13] * a[6] * a[12] - a[13] * a[8] * a[10] + inv[13] = -a[5] * a[10] * a[15] + a[5] * a[11] * a[14] + a[9] * a[6] * a[15] - a[9] * a[7] * a[14] - a[13] * a[6] * a[11] + a[13] * a[7] * a[10] + inv[2] = -a[2] * a[11] * a[16] + a[2] * a[12] * a[15] + a[10] * a[3] * a[16] - a[10] * a[4] * a[15] - a[14] * a[3] * a[12] + a[14] * a[4] * a[11] + inv[6] = a[1] * a[11] * a[16] - a[1] * a[12] * a[15] - a[9] * a[3] * a[16] + a[9] * a[4] * a[15] + a[13] * a[3] * a[12] - a[13] * a[4] * a[11] + inv[10] = -a[1] * a[10] * a[16] + a[1] * a[12] * a[14] + a[9] * a[2] * a[16] - a[9] * a[4] * a[14] - a[13] * a[2] * a[12] + a[13] * a[4] * a[10] + inv[14] = a[1] * a[10] * a[15] - a[1] * a[11] * a[14] - a[9] * a[2] * a[15] + a[9] * a[3] * a[14] + a[13] * a[2] * a[11] - a[13] * a[3] * a[10] + inv[3] = a[2] * a[7] * a[16] - a[2] * a[8] * a[15] - a[6] * a[3] * a[16] + a[6] * a[4] * a[15] + a[14] * a[3] * a[8] - a[14] * a[4] * a[7] + inv[7] = -a[1] * a[7] * a[16] + a[1] * a[8] * a[15] + a[5] * a[3] * a[16] - a[5] * a[4] * a[15] - a[13] * a[3] * a[8] + a[13] * a[4] * a[7] + inv[11] = a[1] * a[6] * a[16] - a[1] * a[8] * a[14] - a[5] * a[2] * a[16] + a[5] * a[4] * a[14] + a[13] * a[2] * a[8] - a[13] * a[4] * a[6] + inv[15] = -a[1] * a[6] * a[15] + a[1] * a[7] * a[14] + a[5] * a[2] * a[15] - a[5] * a[3] * a[14] - a[13] * a[2] * a[7] + a[13] * a[3] * a[6] + inv[4] = -a[2] * a[7] * a[12] + a[2] * a[8] * a[11] + a[6] * a[3] * a[12] - a[6] * a[4] * a[11] - a[10] * a[3] * a[8] + a[10] * a[4] * a[7] + inv[8] = a[1] * a[7] * a[12] - a[1] * a[8] * a[11] - a[5] * a[3] * a[12] + a[5] * a[4] * a[11] + a[9] * a[3] * a[8] - a[9] * a[4] * a[7] + inv[12] = -a[1] * a[6] * a[12] + a[1] * a[8] * a[10] + a[5] * a[2] * a[12] - a[5] * a[4] * a[10] - a[9] * a[2] * a[8] + a[9] * a[4] * a[6] + inv[16] = a[1] * a[6] * a[11] - a[1] * a[7] * a[10] - a[5] * a[2] * a[11] + a[5] * a[3] * a[10] + a[9] * a[2] * a[7] - a[9] * a[3] * a[6] + local det = a[1] * inv[1] + a[2] * inv[5] + a[3] * inv[9] + a[4] * inv[13] + for i = 1, 16 do + inv[i] /= det + end + return inv +end + +local function grow(lo: { number }, hi: { number }, x: number, y: number, z: number) + lo[1], lo[2], lo[3] = math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z) + hi[1], hi[2], hi[3] = math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z) +end +local function apply(m: { number }, x: number, y: number, z: number): (number, number, number) + return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] +end + +-- the bounds `assimp info` prints: its Collada importer puts the up-axis rotation and unit scale on the root node, +-- and Info.cpp accumulates node transforms as local * parent (sic); skinned meshes without their bind shape matrix +local function assimpBounds(scene: any, written: boolean?): ({ number }?, { number }?) + local u = scene.meta.unit or 1 + local root = if scene.meta.up == "z" then { u, 0, 0, 0, 0, 0, -u, 0, 0, u, 0, 0, 0, 0, 0, 1 } + elseif scene.meta.up == "x" then { 0, u, 0, 0, -u, 0, 0, 0, 0, 0, u, 0, 0, 0, 0, 1 } + else { u, 0, 0, 0, 0, u, 0, 0, 0, 0, u, 0, 0, 0, 0, 1 } + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local seen = {} + local function visit(i: number, parent: { number }) + local n = scene.nodes[i] + if seen[i] then + return + end + seen[i] = true + local m = Scene.mul(Scene.nodeMatrix(n), parent) + local mesh = n.mesh and scene.meshes[n.mesh] + if mesh then + local mm = m + local skin = n.skin and scene.skins[n.skin] + if skin and not written and skin.extras and skin.extras.dae and skin.extras.dae.bindShapeMatrix then + mm = Scene.mul(m, inverse(skin.extras.dae.bindShapeMatrix)) + end + for _, p in mesh.primitives do + local pos = p.attributes.POSITION + for v = 0, pos.count - 1 do + grow(lo, hi, apply(mm, buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8))) + end + end + end + for _, c in n.children do + visit(c, m) + end + end + for _, r in scene.roots do + visit(r, root) + end + if lo[1] > hi[1] then + return nil, nil + end + return lo, hi +end + +-- world matrices (correct order) of every node +local function worlds(scene: any): { [number]: { number } } + local w = {} + local function visit(i: number, parent: { number }) + if w[i] then + return + end + w[i] = Scene.mul(parent, Scene.nodeMatrix(scene.nodes[i])) + for _, c in scene.nodes[i].children do + visit(c, w[i]) + end + end + for _, r in scene.roots do + visit(r, Scene.IDENTITY) + end + return w +end + +-- bounds of the rest pose with skins applied (glTF semantics: skinned vertices = sum w * world(joint) * ibm * v) +local function posedBounds(scene: any): ({ number }?, { number }?) + local w = worlds(scene) + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for ni, m in w do + local n = scene.nodes[ni] + local mesh = n.mesh and scene.meshes[n.mesh] + if mesh then + local skin = n.skin and scene.skins[n.skin] + local jm = {} + if skin then + local ibm = skin.inverseBindMatrices and Scene.reader(skin.inverseBindMatrices) + for j, jn in skin.joints do + local inv = table.create(16, 0) + for k = 1, 16 do + inv[k] = if ibm then ibm(j - 1, k - 1) else (if k % 5 == 1 then 1 else 0) + end + jm[j - 1] = Scene.mul(w[jn] or Scene.IDENTITY, inv) + end + end + for _, p in mesh.primitives do + local pos = p.attributes.POSITION + local J = skin and p.attributes.JOINTS_0 and Scene.reader(p.attributes.JOINTS_0) + local W = skin and p.attributes.WEIGHTS_0 and Scene.reader(p.attributes.WEIGHTS_0) + for v = 0, pos.count - 1 do + local x, y, z = buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8) + if J and W then + local sx, sy, sz = 0, 0, 0 + for k = 0, 3 do + local wt = W(v, k) + if wt > 0 then + local px, py, pz = apply(jm[J(v, k)] or Scene.IDENTITY, x, y, z) + sx, sy, sz = sx + wt * px, sy + wt * py, sz + wt * pz + end + end + grow(lo, hi, sx, sy, sz) + else + grow(lo, hi, apply(m, x, y, z)) + end + end + end + end + end + if lo[1] > hi[1] then + return nil, nil + end + return lo, hi +end + +local function lightCount(scene: any): number + local n = #scene.lights + for _, node in scene.nodes do + if node.extras and node.extras.dae and node.extras.dae.ambientLight then + n += 1 + end + end + return n +end + +-- a channel's value at time tm (LINEAR; rotations nlerped) +local function channelAt(ch: any, tm: number): { number } + local inp, out = Scene.reader(ch.input) :: any, Scene.reader(ch.output) :: any + local n, c = ch.input.count, ch.output.components + local function at(i: number): { number } + local r = {} + for k = 0, c - 1 do + r[k + 1] = out(i, k) + end + return r + end + if tm <= inp(0, 0) then + return at(0) + end + for i = 1, n - 1 do + local t1 = inp(i, 0) + if tm <= t1 + 1e-6 then + local t0 = inp(i - 1, 0) + local f = if t1 > t0 then math.clamp((tm - t0) / (t1 - t0), 0, 1) else 1 + local a, b = at(i - 1), at(i) + for k = 1, c do + a[k] += (b[k] - a[k]) * f + end + return a + end + end + return at(n - 1) +end + +local checked = { assimp = 0, bounds = 0, gltf = 0, keys = 0, roundTrips = 0, xcheck = 0 } +local decoded: { [number]: any } = {} +local samples: { string } = {} +for i, c in Cases do + local scene, err = decode(c.data, { files = c.files, triangulate = false }) + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if not scene then + continue + end + t:eq(scene.meta.source.format, "dae", c.name .. ": source") + local ref = c.assimp + local prims, faces = counts(scene) + if ref and not ref.failed then + -- assimp builds a placeholder skeleton mesh for scenes without meshes + if prims > 0 then + t:eq(prims, ref.meshes, c.name .. ": meshes (assimp)") + t:eq(faces, ref.faces, c.name .. ": faces (assimp)") + local lo, hi = assimpBounds(scene) + local ok = lo ~= nil and hi ~= nil and nearV(lo :: any, ref.min, 2e-4) and nearV(hi :: any, ref.max, 2e-4) + t:check(ok, string.format("%s: bounds %s %s, assimp %s %s", c.name, fmt(lo), fmt(hi), fmt(ref.min), fmt(ref.max))) + checked.bounds += 1 + -- assimp adds a default material when a mesh has none + t:check(ref.materials - #scene.materials == 0 or ref.materials - #scene.materials == 1, c.name .. ": materials (assimp)") + end + t:eq(#scene.cameras, ref.cameras, c.name .. ": cameras (assimp)") + t:eq(lightCount(scene), ref.lights, c.name .. ": lights (assimp)") + t:eq(#scene.animations, ref.animations, c.name .. ": animations (assimp)") + checked.assimp += 1 + end + -- against the glTF original of an assimp export + if c.gltf then + local g, gerr = Gltf.decode(Bytes.reader(buffer.fromstring(c.gltf)), { files = c.gltfFiles }) + t:check(g, c.name .. ": gltf original: " .. tostring(gerr)) + if g then + local glo, ghi = posedBounds(g) + local lo, hi = posedBounds(scene) + -- assimp's exporter folds a root Z-up rotation node of the source into Z_UP + if lo and hi and scene.meta.up == "z" then + lo, hi = { lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] } + end + t:check(lo and glo and nearV(lo, glo, 1e-4) and nearV(hi :: any, ghi :: any, 1e-4), string.format("%s: posed bounds %s %s, glTF %s %s", c.name, fmt(lo), fmt(hi), fmt(glo), fmt(ghi))) + t:eq(#scene.skins, #g.skins, c.name .. ": skins") + if #g.skins > 0 and #scene.skins > 0 then + t:eq(#scene.skins[1].joints, #g.skins[1].joints, c.name .. ": joints") + end + -- every LINEAR key of the original, evaluated on our resampled channels (nodes matched by name) + local byName = {} + for ni, n in scene.nodes do + if n.name then + byName[n.name] = byName[n.name] or ni + end + end + -- assimp's Collada exporter writes key times in milliseconds (its glTF importer's ticks per second) + local function maxTime(sc: any): number + local m = 0 + for _, a in sc.animations do + for _, ch in a.channels do + m = math.max(m, buffer.readf32(ch.input.data, (ch.input.count - 1) * 4)) + end + end + return m + end + local gmax, omax = maxTime(g), maxTime(scene) + local tscale = if gmax > 0 and near(omax / gmax, 1000, 1e-3) then 1000 else 1 + -- (files assimp cannot read back: its exporter left out animation sources; their channels are dropped) + for _, ga in if ref and not ref.failed then g.animations else {} do + for _, gc in ga.channels do + local gname = g.nodes[gc.node].name + local ni = gname and byName[gname] + if gc.interpolation == "LINEAR" and gc.path ~= "weights" and ni then + local ours = nil + for _, a in scene.animations do + for _, ch in a.channels do + if ch.node == ni and ch.path == gc.path then + ours = ch + end + end + end + t:check(ours, c.name .. ": animated " .. gname .. " " .. gc.path) + if ours then + local gin, gout = Scene.reader(gc.input) :: any, Scene.reader(gc.output) :: any + for k = 0, gc.input.count - 1 do + local want = {} + for q = 0, gc.output.components - 1 do + want[q + 1] = gout(k, q) + end + local got = channelAt(ours, gin(k, 0) * tscale) + local ok + if gc.path == "rotation" then + local d = math.abs(got[1] * want[1] + got[2] * want[2] + got[3] * want[3] + got[4] * want[4]) + ok = d > 1 - 1e-4 + else + ok = nearV(got, want, 1e-4) + end + t:check(ok, string.format("%s: %s %s at %g", c.name, gname, gc.path, gin(k, 0))) + checked.keys += 1 + end + end + end + end + end + checked.gltf += 1 + end + end + -- the full rotations file: no resampled step over 90 degrees + if string.find(c.name, "full_rotations", 1, true) then + local worst = 1 + for _, a in scene.animations do + for _, ch in a.channels do + if ch.path == "rotation" then + local r = Scene.reader(ch.output) :: any + for k = 1, ch.output.count - 1 do + local d = 0 + for q = 0, 3 do + d += r(k, q) * r(k - 1, q) + end + worst = math.min(worst, d) + end + end + end + end + t:check(worst >= math.cos(math.rad(45)) - 1e-6, "full rotations: subdivided (worst dot " .. worst .. ")") + end + -- round trip through our writer (.dae, and .zae for a few) + local tri = decode(c.data, { files = c.files }) + decoded[i] = tri + local files = {} + local out, eerr = Dae.encode(tri, { files = files, name = "rt.dae" }) + t:check(out, c.name .. ": encode: " .. tostring(eerr)) + if out then + local back, berr = decode(out, { files = files }) + t:check(back, c.name .. ": re-decode: " .. tostring(berr)) + if back then + local p1, f1 = counts(tri) + local p2, f2 = counts(back) + t:eq(p2, p1, c.name .. ": round trip meshes") + t:eq(f2, f1, c.name .. ": round trip faces") + local lo1, hi1 = MeshOps.bounds(tri) + local lo2, hi2 = MeshOps.bounds(back) + t:check((lo1 == nil and lo2 == nil) or (lo1 and lo2 and nearV(lo2, lo1, 1e-5) and nearV(hi2 :: any, hi1 :: any, 1e-5)), c.name .. ": round trip bounds") + t:eq(#back.materials, #tri.materials, c.name .. ": round trip materials") + t:eq(#back.cameras, #tri.cameras, c.name .. ": round trip cameras") + t:eq(#back.lights, #tri.lights, c.name .. ": round trip lights") + t:eq(#back.textures, #tri.textures, c.name .. ": round trip textures") + for ti, tex in tri.textures do + local bt = back.textures[ti] + if tex.data and bt then + t:check(bt.data and buffer.tostring(bt.data) == buffer.tostring(tex.data), c.name .. ": round trip texture " .. ti) + end + end + for mi, m in tri.materials do + local bm = back.materials[mi] + t:check(bm and nearV(bm.baseColor, m.baseColor, 1e-6), c.name .. ": round trip baseColor " .. mi) + end + checked.roundTrips += 1 + end + end + if #c.data < 20000 then + table.insert(samples, c.data) + end +end + +-- assimp reads what we wrote like the source +for _, x in Xcheck do + local src = decoded[x.case] + local ref = x.assimp + t:check(ref and not ref.failed, x.name .. ": assimp reads our file") + if src and ref and not ref.failed then + local prims, faces = counts(src) + if prims > 0 then + t:eq(ref.meshes, prims, x.name .. ": meshes (assimp, ours)") + t:eq(ref.faces, faces, x.name .. ": faces (assimp, ours)") + local lo, hi = assimpBounds(src, true) -- our writer bakes the bind shape (it writes no skins) + t:check(lo and nearV(lo, ref.min, 2e-4) and nearV(hi :: any, ref.max, 2e-4), string.format("%s: bounds %s %s, assimp %s %s", x.name, fmt(lo), fmt(hi), fmt(ref.min), fmt(ref.max))) + end + t:eq(ref.cameras, #src.cameras, x.name .. ": cameras (assimp, ours)") + t:eq(ref.lights, #src.lights, x.name .. ": lights (assimp, ours)") + checked.xcheck += 1 + end +end + +-- polygons: kept or fan-triangulated +local function case(name: string): any + for i, c in Cases do + if string.find(c.name, name, 1, true) then + return c, i + end + end + return nil, nil +end +do + local c = case("ConcavePolygon") + if c then + local s = decode(c.data, { triangulate = false }) + local p = s.meshes[1].primitives[1] + t:eq(p.mode, "polygons", "polygons kept") + local corners = 0 + local get = Scene.reader(p.faces) :: any + for k = 0, p.faces.count - 1 do + corners += get(k, 0) - 2 + end + local s2 = decode(c.data) + t:eq(s2.meshes[1].primitives[1].mode, "triangles", "polygons triangulated") + t:eq(s2.meshes[1].primitives[1].indices.count // 3, corners, "fan triangle count") + local tri = MeshOps.triangulate(p) + t:check(tri and tri.indices.count // 3 == corners, "MeshOps ear-clips the kept polygon") + end +end + +-- materials and textures (duck: blinn, a TGA diffuse texture; decoded at the api layer) +do + local c = case("assimp/duck.dae") + if c then + local s = decode(c.data, { files = c.files }) + local m = s.materials[1] + local ti = m.baseColorTexture and m.baseColorTexture.texture + local tex = ti and s.textures[ti] + t:check(tex and tex.data, "duck: diffuse texture bytes") + t:eq(tex and tex.mime, "image/tga", "duck: texture mime") + t:check(m.extras.phong.model == "blinn" and type(m.extras.phong.shininess) == "number", "duck: phong extras") + local _, errs = F.model.loadTextures(s) + t:check(tex and tex.image and tex.image.width > 0 and errs[ti :: number] == nil, "duck: texture decoded lazily") + -- without the image files: the uri stays, no data + local s2 = decode(c.data) + t:check(ti and s2.textures[ti].data == nil and s2.textures[ti].uri == "./duckCM.tga", "duck: uri without files") + local cam = s.cameras[1] + t:check(cam.type == "perspective" and cam.yfov > 0 and cam.yfov < math.pi, "duck: camera") + t:eq(s.meta.up, "y", "duck: up axis") + end + local z = case("assimp/duck.zae") + if z then + local s = decode(z.data) + t:check(s.textures[1] and s.textures[1].data, "zae: texture read from the zip") + t:check(Dae.sniff(Bytes.reader(buffer.fromstring(z.data))) > 0.9, "zae sniff") + local zb = Dae.encode(s, { format = "zae" }) + local back = zb and decode(zb) + t:check(back and back.textures[1] and back.textures[1].data and buffer.len(back.textures[1].data) == buffer.len(s.textures[1].data), "zae round trip with the texture") + end + local l = case("assimp/lights.dae") + if l then + local s = decode(l.data) + local kinds = {} + for _, li in s.lights do + kinds[li.type] = (kinds[li.type] or 0) + 1 + end + t:check(kinds.point == 2 and kinds.directional == 1 and kinds.spot == 1, "lights: kinds") + t:eq(lightCount(s) - #s.lights, 1, "lights: one ambient") + end + local u = case("cube_UTF16LE") + if u then + t:eq(Dae.sniff(Bytes.reader(buffer.fromstring(u.data))), 1, "UTF-16 sniff") + end + local k = case("kwxport") + if k then + local s = decode(k.data) + t:check(s.meta.up == "z" and near(s.meta.unit, 0.0254, 1e-9), "kwxport: Z_UP, inches") + t:check(s.meshes[1].primitives[1].attributes.COLOR_0 ~= nil, "kwxport: vertex colours") + end + local uv2 = case("cube_with_2UVs") + if uv2 then + local s = decode(uv2.data) + local a = s.meshes[1].primitives[1].attributes + t:check(a.TEXCOORD_0 and a.TEXCOORD_1, "2 UV sets") + end + local clips = case("library_animation_clips") + if clips then + local s = decode(clips.data) + t:check(#s.animations == 2 and s.animations[1].name ~= nil, "animation clips named") + t:check(#s.skins >= 1 and s.skins[1].inverseBindMatrices ~= nil, "clips: skin with inverse bind matrices") + local p = s.meshes[s.nodes[(function() + for i, n in s.nodes do + if n.skin then + return i + end + end + return 1 + end)()].mesh].primitives[1] + local w = Scene.reader(p.attributes.WEIGHTS_0) :: any + local okSum = true + for v = 0, p.attributes.WEIGHTS_0.count - 1 do + local sum = w(v, 0) + w(v, 1) + w(v, 2) + w(v, 3) + if sum > 0 and math.abs(sum - 1) > 1e-5 then + okSum = false + end + end + t:check(okSum, "clips: weights normalized") + end +end + +-- api: F.load by content / extension +do + local c = case("cube_tristrips") + if c then + local s, err = F.load(c.data) + t:check(s and s.meta.source.format == "dae", "F.load: " .. tostring(err)) + local out = F.save(s, nil, { format = "dae" }) + t:check(out and string.find(buffer.tostring(out), "') + t:check(e1 and e1.code == Err.CORRUPT, "not COLLADA: CORRUPT") + local _, e2 = decode('') + t:check(e2 and (e2.code == Err.TRUNCATED or e2.code == Err.CORRUPT), "unclosed XML") + local bad = [[ +0 0 0 +

0 0 7

+
]] + local _, e3 = decode(bad) + t:check(e3 and e3.code == Err.CORRUPT, "index out of range: CORRUPT") + local _, e4 = decode(string.gsub(bad, "0 0 7", "0 0 0"), { maxVertices = 0 }) + t:check(e4 and e4.code == Err.LIMIT, "maxVertices: LIMIT") + local ok = decode((string.gsub(bad, "0 0 7", "0 0 0"))) + t:check(ok and #ok.meshes == 1 and ok.meshes[1].primitives[1].attributes.POSITION.count == 1, "minimal file") + local _, e5 = Dae.encode({} :: any) + t:check(e5 and e5.code == Err.ARG, "encode: ARG") + t:eq(Dae.sniff(Bytes.reader(buffer.fromstring(""))), 0, "sniff: other XML") + table.insert(samples, (string.gsub(bad, "0 0 7", "0 0 0"))) +end + +t:note("%d cases: %d against assimp (%d bounds), %d against their glTF originals (%d animation keys), %d round trips", #Cases, checked.assimp, checked.bounds, checked.gltf, checked.keys, checked.roundTrips) +t:note("%d of our files read back by assimp like the sources", checked.xcheck) +t:fuzz("decode", function(b: buffer) + return Dae.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tools/fixtures/_dae_encode.luau b/tools/fixtures/_dae_encode.luau new file mode 100644 index 0000000..120b76c --- /dev/null +++ b/tools/fixtures/_dae_encode.luau @@ -0,0 +1,36 @@ +-- tools/fixtures/_dae_encode: run by tools/fixtures/dae.py (luau CLI, repo root): decodes every Collada case with our +-- reader and encodes it with our writer (rt_.dae + its image files, and rt_.zae for the first cases), +-- printing "\t" lines for assimp to read back. +local Dae = require("@formats/model/dae") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/dae_cases") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(s: string): string + local out = table.create(#s) + for i = 1, #s do + out[i] = HEX[string.byte(s, i)] + end + return table.concat(out) +end + +for i, c in Cases do + local scene, err = Dae.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }) + if scene then + local files = {} + local dae = assert(Dae.encode(scene, { files = files, name = "rt_" .. i .. ".dae" })) + print(string.format("rt_%d.dae\t%s", i, hex(buffer.tostring(dae)))) + for name, data in files do + print(name .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data))) + end + if i <= 3 then + local zae = assert(Dae.encode(scene, { format = "zae" })) + print(string.format("rt_%d.zae\t%s", i, hex(buffer.tostring(zae)))) + end + else + print("skipped " .. c.name .. ": " .. tostring(err)) + end +end diff --git a/tools/fixtures/dae.py b/tools/fixtures/dae.py new file mode 100644 index 0000000..e8c4430 --- /dev/null +++ b/tools/fixtures/dae.py @@ -0,0 +1,106 @@ +# Collada fixtures (tools/fixtures.py): assimp's Collada test models (read from the nixpkgs assimp source at fixture +# time, never committed: test/models/Collada, licences in that folder's licence.md), glTF sample models converted to +# .dae by assimp's Collada exporter (skins, animations, cameras, textures), with reference values from `assimp info -r` +# (meshes, faces, vertices, bounds, materials, animations, cameras, lights, bones). Blender 5 has no Collada support. +# tests/gen/dae_cases.luau { name, main, data, files = { name -> bytes }, assimp, gltf? + gltfFiles? (the original +# of an assimp export: the test compares skins and animations with it) } +# tests/gen/dae_xcheck.luau our encoder's .dae of every case (tools/fixtures/_dae_encode.luau) read back by assimp: +# { name, case, assimp } +import importlib.util, os, re, subprocess + +INPUTS = ["src/Formats/model/dae", "src/Formats/codecs/Xml", "tools/fixtures/_model_ref.py", "tools/fixtures/_dae_encode.luau", + "tests/fixtures/gltf"] + + +def ref_module(ctx): + spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def assimp_src(): + out = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True) + return out.stdout.decode().strip().split("\n")[-1] + + +def info(ctx, M, path): + a = M.assimp_info(ctx, [path], raw=True)[0] + try: + txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace") + except subprocess.CalledProcessError: + return {"failed": True} + for label in ("Animations", "Cameras", "Lights", "Bones", "Materials"): + m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M) + if m: + a[label.lower()] = int(m.group(1)) + # assimp's root node transform (its Collada importer bakes up axis / unit conversion into it): not reported by + # `assimp info`; the test applies the conversion itself + return a + + +IMAGE_EXT = (".jpg", ".jpeg", ".png", ".tga", ".bmp") + + +def generate(ctx): + M = ref_module(ctx) + src = os.path.join(assimp_src(), "test", "models", "Collada") + cases = [] + images = {f: os.path.join(src, f) for f in sorted(os.listdir(src)) if f.lower().endswith(IMAGE_EXT)} + for f in sorted(os.listdir(src)): + if not (f.lower().endswith(".dae") or f.lower().endswith(".zae")) or "_triangulate" in f: + continue # the *_triangulate files are the same models again (fixture size) + path = os.path.join(src, f) + data = open(path, "rb").read() + files = {} + text = data.decode("latin-1") + for im, ip in images.items(): + if im in text: + files[im] = open(ip, "rb").read() + cases.append({"name": "assimp/" + f, "main": f, "path": path, "files": files}) + # glTF samples -> assimp's Collada exporter + tmp = M.tempdir() + groot = os.path.join(ctx.root, "tests", "fixtures", "gltf") + for model, variant, main in (("SimpleSkin", "glTF", "SimpleSkin.gltf"), ("RiggedSimple", "glTF-Binary", "RiggedSimple.glb"), + ("BoxTextured", "glTF", "BoxTextured.gltf"), ("AnimatedTriangle", "glTF", "AnimatedTriangle.gltf"), + ("Cameras", "glTF", "Cameras.gltf"), ("BoxVertexColors", "glTF-Binary", "BoxVertexColors.glb"), + ("SimpleMeshes", "glTF", "SimpleMeshes.gltf"), ("InterpolationTest", "glTF-Binary", "InterpolationTest.glb"), + ("MultiUVTest", "glTF-Binary", "MultiUVTest.glb")): + d = os.path.join(groot, model, variant) + if not os.path.exists(os.path.join(d, main)): + continue + out = os.path.join(tmp, model + ".dae") + try: + ctx.nix("assimp", ["assimp", "export", os.path.join(d, main), out, "-fcollada"]) + except subprocess.CalledProcessError: + continue + files = {} + text = open(out, "rb").read().decode("latin-1") + for f in os.listdir(tmp): + if f.lower().endswith(IMAGE_EXT) and f in text: + files[f] = open(os.path.join(tmp, f), "rb").read() + for f in os.listdir(d): + if f.lower().endswith(IMAGE_EXT) and f in text: + files[f] = open(os.path.join(d, f), "rb").read() + orig = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != main} + cases.append({"name": "assimp-export/" + model, "main": model + ".dae", "path": out, "files": files, + "gltf": open(os.path.join(d, main), "rb").read(), "gltfFiles": orig}) + for c in cases: + c["assimp"] = info(ctx, M, c["path"]) + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("dae_cases", cases) + + # assimp reads our output + ours = M.luau_encode(ctx, "tools/fixtures/_dae_encode.luau") + xtmp = M.tempdir() + names = [] + for name, data in sorted(ours.items()): + with open(os.path.join(xtmp, name), "wb") as f: + f.write(data) + if name.endswith(".dae") or name.endswith(".zae"): + names.append(name) + out = [] + for n in names: + out.append({"name": n, "case": int(n.split("_")[1].split(".")[0]), "assimp": info(ctx, M, os.path.join(xtmp, n))}) + ctx.emit("dae_xcheck", out) From 3e658042e337cf56f8674c434b31faa25579f680 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:41:47 -0500 Subject: [PATCH 4/8] 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. --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/model/usda/Build.luau | 1396 +++++++++++++++++++++++++++++ src/Formats/model/usda/Parse.luau | 820 +++++++++++++++++ src/Formats/model/usda/Write.luau | 840 +++++++++++++++++ src/Formats/model/usda/init.luau | 221 +++++ tests/model/usda.luau | 547 +++++++++++ tools/fixtures/_usda_encode.luau | 34 + tools/fixtures/_usda_reference.py | 404 +++++++++ tools/fixtures/usda.py | 264 ++++++ 10 files changed, 4539 insertions(+) create mode 100644 src/Formats/model/usda/Build.luau create mode 100644 src/Formats/model/usda/Parse.luau create mode 100644 src/Formats/model/usda/Write.luau create mode 100644 src/Formats/model/usda/init.luau create mode 100644 tests/model/usda.luau create mode 100644 tools/fixtures/_usda_encode.luau create mode 100644 tools/fixtures/_usda_reference.py create mode 100644 tools/fixtures/usda.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 40e275f..5f216ea 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -25,6 +25,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | +| model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | | font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` | | font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d514aa9..ab5dd9e 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -254,6 +254,18 @@ local list: { Entry } = { return require("@formats/model/stl") end, }, + { + name = "usda", + category = "model", + path = "model/usda", + extensions = { "usda", "usd", "usdz" }, + mime = { "model/vnd.usda", "model/vnd.usdz+zip" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + caps = { decode = true, encode = true, materials = true, animation = true, cameras = true, lights = true, polygons = true, vertexColors = true, usdz = "read", usdc = false }, + load = function() + return require("@formats/model/usda") + end, + }, { name = "vox", category = "model", diff --git a/src/Formats/model/usda/Build.luau b/src/Formats/model/usda/Build.luau new file mode 100644 index 0000000..6c3615f --- /dev/null +++ b/src/Formats/model/usda/Build.luau @@ -0,0 +1,1396 @@ +--!strict +-- model/usda/Build: a parsed USDA layer (model/usda/Parse) -> Scene, following the UsdGeom / UsdShade / UsdLux +-- schemas (openusd 26.x documentation). Prims: Xform / Scope / untyped def / over -> nodes (class prims are skipped; +-- Material, Shader, NodeGraph, GeomSubset and scopes holding only those are not nodes); Mesh -> a node with a mesh +-- (one primitive per GeomSubset of the "face" element type + one for the remaining faces), Camera, DistantLight / +-- SphereLight / RectLight / DiskLight / CylinderLight. The selected variant of each variant set is merged into its prim. +-- Transforms: xformOpOrder over translate / scale / rotateX|Y|Z / rotateXYZ (all six orders) / orient / transform, the +-- !invert! prefix and !resetXformStack! (the node becomes a root). Time samples on xform ops -> one animation (the local +-- matrix sampled at the union of the ops' time codes, decomposed into TRS channels; time = code / timeCodesPerSecond); +-- other attributes use their earliest sample (as UsdTimeCode.EarliestTime()). Primvars: st (and every texCoord2f / +-- float2 primvar) -> TEXCOORD_n (v flipped to glTF's top-left origin unless opts.flipV = false), normals, displayColor +-- / displayOpacity -> COLOR_0 (a constant displayColor on an unbound mesh becomes a material instead), with every +-- interpolation (constant / uniform / vertex / varying / faceVarying) and :indices. Faces are fan-triangulated +-- (opts.triangulate = false keeps "polygons"), holeIndices skipped, orientation = "leftHanded" reversed. +-- UsdPreviewSurface materials (inputs resolved through connections to Material / NodeGraph interface inputs) with +-- UsdUVTexture textures (file, wrapS / wrapT, st through UsdPrimvarReader_float2, UsdTransform2d -> +-- KHR_texture_transform), material:binding (inherited down the namespace, also on GeomSubsets). +-- Not supported: composition arcs (references, payloads, inherits, specializes, subLayers: listed in +-- meta.source.unsupported), UsdSkel, blend shapes, BasisCurves / Points / NURBS, instancing, MaterialX networks. +local Types = require("@formats/Types") +local Parse = require("@formats/model/usda/Parse") + +local Build = {} + +type Prim = Parse.Prim +type Prop = Parse.Prop + +local NONE = Parse.NONE +local DEG = math.pi / 180 + +local NOT_NODES = { Material = true, Shader = true, NodeGraph = true, GeomSubset = true, Skeleton = true, SkelAnimation = true, BlendShape = true } +local SKEL = { Skeleton = true, SkelAnimation = true, BlendShape = true } +local LIGHTS = { DistantLight = true, SphereLight = true, RectLight = true, DiskLight = true, CylinderLight = true, DomeLight = true } +local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", webp = "image/webp", tga = "image/x-tga", bmp = "image/bmp", exr = "image/x-exr", hdr = "image/vnd.radiance", ktx2 = "image/ktx2", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff", avif = "image/avif" } + +export type Options = { + triangulate: boolean?, + flipV: boolean?, + fetch: ((uri: string) -> buffer?)?, + maxVertices: number?, +} + +-- ------------------------------------------------------------------------------------------------ helpers +local function isArr(v: any): boolean + return type(v) == "table" and v.t == "arr" +end +local function str(v: any): string? + if type(v) == "string" then + return v + elseif type(v) == "table" and (v.t == "id" or v.t == "asset" or v.t == "path") then + return v.v + end + return nil +end +-- a tuple / scalar -> numbers (nil when not numeric) +local function nums(v: any): { number }? + if type(v) == "number" then + return { v } + elseif type(v) == "boolean" then + return { if v then 1 else 0 } + elseif type(v) == "table" and v.t == "tuple" then + local out = {} + for k, x in v.v do + if type(x) == "number" then + out[k] = x + elseif type(x) == "table" and x.t == "tuple" then + for _, y in x.v do + if type(y) ~= "number" then + return nil + end + table.insert(out, y) + end + else + return nil + end + end + return out + elseif type(v) == "table" and v.t == "arr" then + return v.v + end + return nil +end +local function num(v: any): number? + if type(v) == "number" then + return v + elseif type(v) == "boolean" then + return if v then 1 else 0 + end + return nil +end + +-- the value of a property: its default, else its earliest time sample +local function propValue(p: Prop?): any + if not p then + return nil + end + if p.samples and #p.samples.times > 0 then + local best, bi = math.huge, 0 + for k, t in p.samples.times do + if t < best then + best, bi = t, k + end + end + local v = p.samples.values[bi] + if v ~= NONE then + return v + end + end + if p.hasValue and p.value ~= NONE then + return p.value + end + return nil +end + +local function joinPath(parent: string, name: string): string + return if parent == "/" then "/" .. name else parent .. "/" .. name +end + +-- resolve a (possibly relative) Sdf path against the prim path that holds it +local function resolvePath(base: string, p: string): string + if string.sub(p, 1, 1) == "/" then + return p + end + local parts = string.split(base, "/") + local out: { string } = {} + for _, x in parts do + if x ~= "" then + table.insert(out, x) + end + end + for _, x in string.split(p, "/") do + if x == ".." then + table.remove(out) + elseif x ~= "." and x ~= "" then + table.insert(out, x) + end + end + return "/" .. table.concat(out, "/") +end +-- "/a/b.outputs:rgb" -> "/a/b", "outputs:rgb" +local function splitProp(p: string): (string, string?) + local prim, prop = string.match(p, "^(.-)%.([^/]+)$") + if prim and prop then + return prim, prop + end + return p, nil +end + +-- ------------------------------------------------------------------------------------------------ matrices +-- column-major 4x4 (glTF layout = USD's row-major row-vector text order) +local mul = Types.Scene.mul +local function translateM(x: number, y: number, z: number): { number } + return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } +end +local function scaleM(x: number, y: number, z: number): { number } + return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } +end +local function rotM(axis: number, deg: number): { number } + local c, s = math.cos(deg * DEG), math.sin(deg * DEG) + if axis == 1 then + return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 } + elseif axis == 2 then + return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 } + end + return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } +end +local function quatM(x: number, y: number, z: number, w: number): { number } + local l = math.sqrt(x * x + y * y + z * z + w * w) + if l > 0 then + x, y, z, w = x / l, y / l, z / l, w / l + end + return Types.Scene.nodeMatrix({ children = {}, rotation = { x, y, z, w } }) +end +local function inverse(m: { number }): { number }? + local a = m + local inv = table.create(16, 0) + inv[1] = a[6] * a[11] * a[16] - a[6] * a[12] * a[15] - a[10] * a[7] * a[16] + a[10] * a[8] * a[15] + a[14] * a[7] * a[12] - a[14] * a[8] * a[11] + inv[5] = -a[5] * a[11] * a[16] + a[5] * a[12] * a[15] + a[9] * a[7] * a[16] - a[9] * a[8] * a[15] - a[13] * a[7] * a[12] + a[13] * a[8] * a[11] + inv[9] = a[5] * a[10] * a[16] - a[5] * a[12] * a[14] - a[9] * a[6] * a[16] + a[9] * a[8] * a[14] + a[13] * a[6] * a[12] - a[13] * a[8] * a[10] + inv[13] = -a[5] * a[10] * a[15] + a[5] * a[11] * a[14] + a[9] * a[6] * a[15] - a[9] * a[7] * a[14] - a[13] * a[6] * a[11] + a[13] * a[7] * a[10] + inv[2] = -a[2] * a[11] * a[16] + a[2] * a[12] * a[15] + a[10] * a[3] * a[16] - a[10] * a[4] * a[15] - a[14] * a[3] * a[12] + a[14] * a[4] * a[11] + inv[6] = a[1] * a[11] * a[16] - a[1] * a[12] * a[15] - a[9] * a[3] * a[16] + a[9] * a[4] * a[15] + a[13] * a[3] * a[12] - a[13] * a[4] * a[11] + inv[10] = -a[1] * a[10] * a[16] + a[1] * a[12] * a[14] + a[9] * a[2] * a[16] - a[9] * a[4] * a[14] - a[13] * a[2] * a[12] + a[13] * a[4] * a[10] + inv[14] = a[1] * a[10] * a[15] - a[1] * a[11] * a[14] - a[9] * a[2] * a[15] + a[9] * a[3] * a[14] + a[13] * a[2] * a[11] - a[13] * a[3] * a[10] + inv[3] = a[2] * a[7] * a[16] - a[2] * a[8] * a[15] - a[6] * a[3] * a[16] + a[6] * a[4] * a[15] + a[14] * a[3] * a[8] - a[14] * a[4] * a[7] + inv[7] = -a[1] * a[7] * a[16] + a[1] * a[8] * a[15] + a[5] * a[3] * a[16] - a[5] * a[4] * a[15] - a[13] * a[3] * a[8] + a[13] * a[4] * a[7] + inv[11] = a[1] * a[6] * a[16] - a[1] * a[8] * a[14] - a[5] * a[2] * a[16] + a[5] * a[4] * a[14] + a[13] * a[2] * a[8] - a[13] * a[4] * a[6] + inv[15] = -a[1] * a[6] * a[15] + a[1] * a[7] * a[14] + a[5] * a[2] * a[15] - a[5] * a[3] * a[14] - a[13] * a[2] * a[7] + a[13] * a[3] * a[6] + inv[4] = -a[2] * a[7] * a[12] + a[2] * a[8] * a[11] + a[6] * a[3] * a[12] - a[6] * a[4] * a[11] - a[10] * a[3] * a[8] + a[10] * a[4] * a[7] + inv[8] = a[1] * a[7] * a[12] - a[1] * a[8] * a[11] - a[5] * a[3] * a[12] + a[5] * a[4] * a[11] + a[9] * a[3] * a[8] - a[9] * a[4] * a[7] + inv[12] = -a[1] * a[6] * a[12] + a[1] * a[8] * a[10] + a[5] * a[2] * a[12] - a[5] * a[4] * a[10] - a[9] * a[2] * a[8] + a[9] * a[4] * a[6] + inv[16] = a[1] * a[6] * a[11] - a[1] * a[7] * a[10] - a[5] * a[2] * a[11] + a[5] * a[3] * a[10] + a[9] * a[2] * a[7] - a[9] * a[3] * a[6] + local det = a[1] * inv[1] + a[2] * inv[5] + a[3] * inv[9] + a[4] * inv[13] + if det == 0 or det ~= det then + return nil + end + for k = 1, 16 do + inv[k] /= det + end + return inv +end +Build.inverse = inverse + +-- decompose(m) -> translation, rotation (quaternion x y z w), scale (no shear) +local function decompose(m: { number }): ({ number }, { number }, { number }) + local sx = math.sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3]) + local sy = math.sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7]) + local sz = math.sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11]) + local det = m[1] * (m[6] * m[11] - m[7] * m[10]) - m[5] * (m[2] * m[11] - m[3] * m[10]) + m[9] * (m[2] * m[7] - m[3] * m[6]) + if det < 0 then + sx = -sx + end + local function d(v: number, s: number): number + return if s ~= 0 then v / s else 0 + end + local r00, r10, r20 = d(m[1], sx), d(m[2], sx), d(m[3], sx) + local r01, r11, r21 = d(m[5], sy), d(m[6], sy), d(m[7], sy) + local r02, r12, r22 = d(m[9], sz), d(m[10], sz), d(m[11], sz) + local x, y, z, w + local tr = r00 + r11 + r22 + if tr > 0 then + local s = math.sqrt(tr + 1) * 2 + w, x, y, z = 0.25 * s, (r21 - r12) / s, (r02 - r20) / s, (r10 - r01) / s + elseif r00 > r11 and r00 > r22 then + local s = math.sqrt(1 + r00 - r11 - r22) * 2 + w, x, y, z = (r21 - r12) / s, 0.25 * s, (r01 + r10) / s, (r02 + r20) / s + elseif r11 > r22 then + local s = math.sqrt(1 + r11 - r00 - r22) * 2 + w, x, y, z = (r02 - r20) / s, (r01 + r10) / s, 0.25 * s, (r12 + r21) / s + else + local s = math.sqrt(1 + r22 - r00 - r11) * 2 + w, x, y, z = (r10 - r01) / s, (r02 + r20) / s, (r12 + r21) / s, 0.25 * s + end + local l = math.sqrt(x * x + y * y + z * z + w * w) + if l > 0 then + x, y, z, w = x / l, y / l, z / l, w / l + end + return { m[13], m[14], m[15] }, { x, y, z, w }, { sx, sy, sz } +end +Build.decompose = decompose + +-- ------------------------------------------------------------------------------------------------ xform ops +type Op = { kind: string, axes: string?, prop: Prop, invert: boolean } + +-- the op stack of a prim: ops in xformOpOrder, resetXformStack +local function xformOps(p: Prim): ({ Op }, boolean) + local order = p.props.xformOpOrder + local list = order and propValue(order) + local ops: { Op } = {} + local reset = false + if type(list) ~= "table" or list.t ~= "list" then + return ops, false + end + for _, item in list.v do + local name = str(item) + if name == "!resetXformStack!" then + reset = true + table.clear(ops) + elseif name then + local invert = false + if string.sub(name, 1, 8) == "!invert!" then + invert = true + name = string.sub(name, 9) + end + local prop = p.props[name] + local kind = string.match(name, "^xformOp:(%a+)") + if prop and kind then + local axes = string.match(kind, "^rotate([XYZ]+)$") + table.insert(ops, { kind = if axes then "rotate" else kind, axes = axes, prop = prop, invert = invert }) + end + end + end + return ops, reset +end + +local AXIS = { X = 1, Y = 2, Z = 3 } +-- the matrix of one op for a value +local function opMatrix(op: Op, v: any): { number }? + local n = nums(v) + if not n then + return nil + end + local m: { number }? + local k = op.kind + if k == "translate" then + m = translateM(n[1] or 0, n[2] or 0, n[3] or 0) + elseif k == "scale" then + local s1 = n[1] or 1 + m = scaleM(s1, n[2] or s1, n[3] or s1) + elseif k == "orient" then + -- USD quaternions are written (real, i, j, k) + m = quatM(n[2] or 0, n[3] or 0, n[4] or 0, n[1] or 1) + elseif k == "transform" then + if #n ~= 16 then + return nil + end + m = table.clone(n) + elseif k == "rotate" and op.axes then + local axes = op.axes :: string + local r: { number } = Types.Scene.IDENTITY :: any + -- rotateXZY: X first, then Z, then Y: R = Ry * Rz * Rx (column vectors); the value is always (x, y, z) angles + for c = 1, #axes do + local a = AXIS[string.sub(axes, c, c)] + local angle = if #axes == 1 then n[1] or 0 else n[a] or 0 + r = mul(rotM(a, angle), r) + end + m = r + else + return nil + end + if op.invert and m then + m = inverse(m) + end + return m +end + +local function lerpValue(a: any, b: any, f: number, quat: boolean): any + local na, nb = nums(a), nums(b) + if not na or not nb or #na ~= #nb then + return a + end + local out = table.create(#na) + if quat and #na == 4 then + -- (w, x, y, z): slerp through nlerp with the short path + local dot = 0 + for k = 1, 4 do + dot += na[k] * nb[k] + end + local sgn = if dot < 0 then -1 else 1 + for k = 1, 4 do + out[k] = na[k] + (nb[k] * sgn - na[k]) * f + end + return { t = "tuple", v = out } + end + for k = 1, #na do + out[k] = na[k] + (nb[k] - na[k]) * f + end + return { t = "tuple", v = out } +end + +-- an op's value at time code t (samples interpolated linearly, held outside their range) +local function opValueAt(op: Op, t: number?): any + local p = op.prop + local s = p.samples + if t ~= nil and s and #s.times > 0 then + local times, values = s.times, s.values + local lo, hi + for k = 1, #times do + local tk = times[k] + if values[k] ~= NONE then + if tk <= t and (lo == nil or tk > times[lo]) then + lo = k + end + if tk >= t and (hi == nil or tk < times[hi]) then + hi = k + end + end + end + if lo and hi then + if lo == hi or times[hi] == times[lo] then + return values[lo] + end + local f = (t - times[lo]) / (times[hi] - times[lo]) + return lerpValue(values[lo], values[hi], f, op.kind == "orient") + end + return values[lo or hi] + end + return propValue(p) +end + +local function localMatrix(ops: { Op }, t: number?): { number } + local m: { number } = Types.Scene.IDENTITY :: any + for _, op in ops do + local om = opMatrix(op, opValueAt(op, t)) + if om then + m = mul(m, om) + end + end + return m +end +Build.localMatrix = localMatrix + +-- ------------------------------------------------------------------------------------------------ build +function Build.scene(layer: Parse.Layer, opts: Options): (Types.Scene?, string?) + local scene = Types.Scene.new() + local flipV = opts.flipV ~= false + local triangulate = opts.triangulate ~= false + local maxVertices = opts.maxVertices or 2 ^ 25 + local fetch = opts.fetch + local unsupported: { [string]: boolean } = {} + local meta = layer.meta + + -- prim index (variants merged), paths + local byPath: { [string]: Prim } = {} + local parentOf: { [Prim]: string } = {} + local pathOf: { [Prim]: string } = {} + local function merge(p: Prim) + if not p.variantSets then + return + end + local nested: { any }? = nil + local sel = p.meta.variants + local chosen = if type(sel) == "table" and sel.t == "dict" then sel.v else {} + for setName, set in p.variantSets :: any do + local name = str(chosen[setName]) + local body = name and set[name] -- unselected sets contribute nothing + if body then + for _, pn in body.order do + if not p.props[pn] then + p.props[pn] = body.props[pn] + table.insert(p.order, pn) + end + end + for _, c in body.children do + table.insert(p.children, c) + end + for k, v in body.meta do + if p.meta[k] == nil then + p.meta[k] = v + end + end + if body.variantSets then + nested = nested or {} + table.insert(nested :: any, body.variantSets) + end + end + end + p.variantSets = nil + for _, vs in nested or {} do + p.variantSets = vs + merge(p) + end + end + local function index(p: Prim, parent: string, depth: number) + if depth > 200 then + return + end + merge(p) + local path = joinPath(parent, p.name) + pathOf[p] = path + parentOf[p] = parent + local existing = byPath[path] + if existing and existing ~= p then + -- over / def of the same path in one layer: merge into the first spec + for _, pn in p.order do + if not existing.props[pn] then + existing.props[pn] = p.props[pn] + table.insert(existing.order, pn) + end + end + existing.typeName = existing.typeName or p.typeName + if p.specifier == "def" then + existing.specifier = "def" + end + for _, c in p.children do + table.insert(existing.children, c) + end + table.clear(p.children) + p.specifier = "class" -- skipped below + else + byPath[path] = p + end + for _, key in { "references", "payload", "inherits", "specializes" } do + local v = p.meta[key] + if v ~= nil and v ~= NONE then + unsupported[key] = true + end + end + for _, c in p.children do + index(c, path, depth + 1) + end + end + for _, p in layer.prims do + index(p, "/", 1) + end + if meta.subLayers ~= nil then + unsupported.subLayers = true + end + + -- a property of a prim path ("/a/b.inputs:x") + local function propAt(path: string): (Prim?, Prop?) + local pp, pn = splitProp(path) + local prim = byPath[pp] + if not prim or not pn then + return prim, nil + end + return prim, prim.props[pn] + end + + -- --------------------------------------------------------------------------------------------- materials + local texCoordIndex: { [string]: number } = {} + local texCoordCount = 0 + local function texCoordFor(name: string): number + local k = texCoordIndex[name] + if k == nil then + k = texCoordCount + texCoordIndex[name] = k + texCoordCount += 1 + end + return k + end + -- primvar names of every mesh, "st" first, so material readers and meshes agree on TEXCOORD_n + do + local names: { [string]: boolean } = {} + for _, p in byPath do + if p.typeName == "Mesh" then + for pn, pr in p.props do + local nm = string.match(pn, "^primvars:([^:]+)$") + if nm and (pr.typeName == "texCoord2f" or pr.typeName == "float2" or pr.typeName == "texCoord2d" or pr.typeName == "double2" or pr.typeName == "texCoord2h" or pr.typeName == "half2") and pr.array then + names[nm] = true + end + end + end + end + local list = {} + for nm in names do + table.insert(list, nm) + end + table.sort(list, function(a: string, b: string): boolean + local pa = if a == "st" then 0 elseif string.sub(a, 1, 2) == "st" then 1 else 2 + local pb = if b == "st" then 0 elseif string.sub(b, 1, 2) == "st" then 1 else 2 + if pa ~= pb then + return pa < pb + end + return a < b + end) + for _, nm in list do + texCoordFor(nm) + end + end + + -- an input's resolved source: a value, or { shader = Prim, output = name } + type Source = { value: any?, shader: Prim?, output: string? } + local function input(prim: Prim, name: string, depth: number?): Source? + local d = depth or 0 + if d > 32 then + return nil + end + local p = prim.props["inputs:" .. name] + if not p then + return nil + end + if p.connect and #p.connect > 0 then + local target = resolvePath(pathOf[prim] or "/", p.connect[1]) + local tp, tn = splitProp(target) + local tprim = byPath[tp] + if tprim and tn then + local outName = string.match(tn, "^outputs:(.+)$") + local inName = string.match(tn, "^inputs:(.+)$") + if outName and tprim.typeName == "Shader" then + return { shader = tprim, output = outName } + elseif outName then + -- a NodeGraph output: follow its connection + local op = tprim.props[tn] + if op and op.connect and #op.connect > 0 then + local t2 = resolvePath(tp, op.connect[1]) + local sp, sn = splitProp(t2) + local sprim = byPath[sp] + if sprim and sn and string.match(sn, "^outputs:") then + return { shader = sprim, output = string.sub(sn, 9) } + end + end + elseif inName then + local r = input(tprim, inName, d + 1) + if r then + return r + end + end + end + end + local v = propValue(p) + if v ~= nil then + return { value = v } + end + return nil + end + local function shaderId(p: Prim): string? + return str(propValue(p.props["info:id"])) + end + + local textureIndex: { [string]: number } = {} + local WRAP = { ["repeat"] = "repeat", clamp = "clamp", mirror = "mirror", black = "clamp", useMetadata = "repeat" } + -- UsdUVTexture shader -> TextureRef (texture index + texCoord + transform) + local function textureRef(shader: Prim): Types.TextureRef? + if shaderId(shader) ~= "UsdUVTexture" then + return nil + end + local f = input(shader, "file") + local file = f and str(f.value) + if not file or file == "" then + return nil + end + local ws = input(shader, "wrapS") + local wt = input(shader, "wrapT") + local wrapS = WRAP[ws and str(ws.value) or "repeat"] or "repeat" + local wrapT = WRAP[wt and str(wt.value) or "repeat"] or "repeat" + local key = file .. "|" .. wrapS .. "|" .. wrapT + local ti = textureIndex[key] + if not ti then + local tex: Types.Texture = { name = shader.name, uri = file, sampler = { wrapS = wrapS :: any, wrapT = wrapT :: any } } + local ext = string.lower(string.match(file, "%.(%w+)$") or "") + tex.mime = MIME[ext] + local data = fetch and fetch(file) + if not data and string.sub(file, 1, 2) == "./" and fetch then + data = fetch(string.sub(file, 3)) + end + tex.data = data + local extras: { [string]: any } = { path = pathOf[shader] } + local cs = input(shader, "sourceColorSpace") + if cs and str(cs.value) then + extras.sourceColorSpace = str(cs.value) + end + tex.extras = { usd = extras } + table.insert(scene.textures, tex) + ti = #scene.textures + textureIndex[key] = ti + end + local ref: Types.TextureRef = { texture = ti :: number } + -- st: UsdPrimvarReader_float2 (maybe through UsdTransform2d) + local st = input(shader, "st") + local reader = st and st.shader + if reader and shaderId(reader) == "UsdTransform2d" then + local tr: { [string]: any } = {} + local rot = input(reader, "rotation") + local scl = input(reader, "scale") + local off = input(reader, "translation") + if rot and num(rot.value) and num(rot.value) ~= 0 then + tr.rotation = (num(rot.value) :: number) * DEG + end + if scl and nums(scl.value) then + tr.scale = nums(scl.value) + end + if off and nums(off.value) then + tr.offset = nums(off.value) + end + if next(tr) then + ref.transform = tr :: any + end + local inn = input(reader, "in") + reader = inn and inn.shader + end + if reader and string.find(shaderId(reader) or "", "^UsdPrimvarReader") then + local vn = input(reader, "varname") + local name = vn and str(vn.value) + if name then + local k = texCoordFor(name) + if k ~= 0 then + ref.texCoord = k + end + end + end + return ref + end + + local materialIndex: { [string]: number } = {} + local function material(path: string): number? + local mi = materialIndex[path] + if mi ~= nil then + return if mi > 0 then mi else nil + end + local mp = byPath[path] + if not mp or mp.typeName ~= "Material" then + materialIndex[path] = 0 + return nil + end + local mat = Types.Scene.material(mp.name) + mat.baseColor = { 0.18, 0.18, 0.18, 1 } + mat.metallic = 0 + mat.roughness = 0.5 + mat.extras = { usd = { path = path } } + -- the surface shader + local surf = mp.props["outputs:surface"] or mp.props["outputs:usd:surface"] + local shader: Prim? = nil + if surf and surf.connect and #surf.connect > 0 then + local sp = splitProp(resolvePath(path, surf.connect[1])) + shader = byPath[sp] + end + if shader and shaderId(shader) == "UsdPreviewSurface" then + local sh = shader :: Prim + local function value(name: string): any + local s = input(sh, name) + return s and s.value + end + local function tex(name: string): (Types.TextureRef?, Prim?) + local s = input(sh, name) + if s and s.shader then + local ref = textureRef(s.shader) + return ref, if ref then s.shader else nil + end + return nil, nil + end + local dc = nums(value("diffuseColor")) + if dc and #dc >= 3 then + mat.baseColor = { dc[1], dc[2], dc[3], 1 } + end + local dt, dshader = tex("diffuseColor") + if dt then + mat.baseColorTexture = dt + mat.baseColor = { 1, 1, 1, 1 } + local sc = input(dshader :: Prim, "scale") + local s = sc and nums(sc.value) + if s and #s >= 3 then + mat.baseColor = { s[1], s[2], s[3], s[4] or 1 } + end + end + local op = num(value("opacity")) + local ot = tex("opacity") + if op then + mat.baseColor[4] = op + end + local thr = num(value("opacityThreshold")) + if thr and thr > 0 then + mat.alphaMode = "mask" + mat.alphaCutoff = thr + elseif (op and op < 1) or ot then + mat.alphaMode = "blend" + end + local m = num(value("metallic")) + if m then + mat.metallic = m + end + local r = num(value("roughness")) + if r then + mat.roughness = r + end + local mt = tex("metallic") + local rt = tex("roughness") + if rt or mt then + mat.metallicRoughnessTexture = rt or mt + if mt then + mat.metallic = 1 + end + if rt then + mat.roughness = 1 + end + end + local e = nums(value("emissiveColor")) + if e and #e >= 3 then + mat.emissive = { e[1], e[2], e[3] } + end + local et = tex("emissiveColor") + if et then + mat.emissiveTexture = et + mat.emissive = { 1, 1, 1 } + end + local nt = tex("normal") + if nt then + mat.normalTexture = nt + end + local oc = tex("occlusion") + if oc then + mat.occlusionTexture = oc + end + local ext: { [string]: any } = {} + local ior = num(value("ior")) + if ior and ior ~= 1.5 then + ext.KHR_materials_ior = { ior = ior } + end + local cc = num(value("clearcoat")) + if cc and cc > 0 then + ext.KHR_materials_clearcoat = { clearcoatFactor = cc, clearcoatRoughnessFactor = num(value("clearcoatRoughness")) or 0.01 } + end + if next(ext) then + mat.extensions = ext + end + local usd: any = (mat.extras :: any).usd + if num(value("useSpecularWorkflow")) == 1 then + usd.useSpecularWorkflow = true + usd.specularColor = nums(value("specularColor")) + end + elseif shader then + unsupported["shader " .. (shaderId(shader :: Prim) or "?")] = true + end + table.insert(scene.materials, mat) + materialIndex[path] = #scene.materials + return #scene.materials + end + + -- the bound material of a prim (material:binding, inherited from ancestors) + local function binding(prim: Prim, path: string): number? + local p: Prim? = prim + local pp = path + while p do + local rel = p.props["material:binding"] or p.props["material:binding:preview"] or p.props["material:binding:full"] + if rel and rel.value and #rel.value > 0 then + return material(resolvePath(pp, rel.value[1])) + end + if pp == "/" then + break + end + pp = parentOf[p :: Prim] or "/" + p = byPath[pp] + end + return nil + end + + local colorMaterials: { [string]: number } = {} + local function colorMaterial(c: { number }): number + local key = string.format("%.6g,%.6g,%.6g,%.6g", c[1], c[2], c[3], c[4] or 1) + local mi = colorMaterials[key] + if not mi then + local mat = Types.Scene.material("displayColor") + mat.baseColor = { c[1], c[2], c[3], c[4] or 1 } + mat.metallic = 0 + mat.roughness = 0.5 + if (c[4] or 1) < 1 then + mat.alphaMode = "blend" + end + mat.extras = { usd = { displayColor = true } } + table.insert(scene.materials, mat) + mi = #scene.materials + colorMaterials[key] = mi + end + return mi :: number + end + + -- --------------------------------------------------------------------------------------------- meshes + type Primvar = { data: { number }, w: number, interp: string, idx: { number }? } + local function primvar(p: Prop?, defaultInterp: string): Primvar? + if not p then + return nil + end + local v = propValue(p) + if not isArr(v) then + return nil + end + local interp = defaultInterp + if p.meta and str(p.meta.interpolation) then + interp = str(p.meta.interpolation) :: string + end + return { data = v.v, w = v.w, interp = interp } + end + + local function buildMesh(prim: Prim, path: string): (Types.Mesh?, string?) + local pts = propValue(prim.props.points) + local cnt = propValue(prim.props.faceVertexCounts) + local idx = propValue(prim.props.faceVertexIndices) + if not isArr(pts) or pts.w ~= 3 then + return nil, nil + end + local points: { number } = pts.v + local npts = #points // 3 + local counts: { number } = if isArr(cnt) then cnt.v else {} + local indices: { number } = if isArr(idx) then idx.v else {} + local nfaces = #counts + local ncorners = 0 + for f = 1, nfaces do + local c = counts[f] + if c < 0 or c ~= c // 1 then + return nil, "bad faceVertexCounts at " .. path + end + ncorners += c + end + if ncorners ~= #indices then + return nil, "faceVertexCounts and faceVertexIndices disagree at " .. path + end + if ncorners > maxVertices or npts > maxVertices then + return nil, "LIMIT" + end + for k = 1, ncorners do + local v = indices[k] + if v < 0 or v >= npts or v ~= v // 1 then + return nil, "a face vertex index out of range at " .. path + end + end + local faceStart = table.create(nfaces + 1, 0) + do + local acc = 0 + for f = 1, nfaces do + faceStart[f] = acc + acc += counts[f] + end + faceStart[nfaces + 1] = acc + end + -- primvars, validated + local function sizeOk(pv: Primvar): boolean + local n = (if pv.idx then #pv.idx else #pv.data // pv.w) + local want = if pv.interp == "constant" then 1 + elseif pv.interp == "uniform" then nfaces + elseif pv.interp == "faceVarying" then ncorners + else npts + if n < want then + return false + end + if pv.idx then + local m = #pv.data // pv.w + for _, k in pv.idx :: { number } do + if k < 0 or k >= m or k ~= k // 1 then + return false + end + end + end + return #pv.data % pv.w == 0 + end + local function withIndices(pv: Primvar?, name: string): Primvar? + if not pv then + return nil + end + local ip = propValue(prim.props[name .. ":indices"]) + if isArr(ip) and ip.w == 1 then + pv.idx = ip.v + end + if not sizeOk(pv) then + unsupported["mismatched primvar " .. name] = true + return nil + end + return pv + end + local normals = withIndices(primvar(prim.props["primvars:normals"], "vertex"), "primvars:normals") + or withIndices(primvar(prim.props.normals, "vertex"), "normals") + if normals and normals.w ~= 3 then + normals = nil + end + local color = withIndices(primvar(prim.props["primvars:displayColor"], "constant"), "primvars:displayColor") + if color and color.w ~= 3 then + color = nil + end + local opacity = withIndices(primvar(prim.props["primvars:displayOpacity"], "constant"), "primvars:displayOpacity") + if opacity and opacity.w ~= 1 then + opacity = nil + end + local uvs: { [number]: Primvar } = {} + for pn, pr in prim.props do + local nm = string.match(pn, "^primvars:([^:]+)$") + if nm and pr.array and (pr.typeName == "texCoord2f" or pr.typeName == "float2" or pr.typeName == "texCoord2d" or pr.typeName == "double2" or pr.typeName == "texCoord2h" or pr.typeName == "half2") then + local pv = withIndices(primvar(pr, "vertex"), pn) + if pv and pv.w == 2 then + uvs[texCoordFor(nm)] = pv + end + end + end + -- the value of a primvar for (point, face, corner) (0-based), component c + local function get(pv: Primvar, point: number, face: number, corner: number, c: number): number + local e = if pv.interp == "constant" then 0 + elseif pv.interp == "uniform" then face + elseif pv.interp == "faceVarying" then corner + else point + if pv.idx then + e = (pv.idx :: { number })[e + 1] + end + return pv.data[e * pv.w + c + 1] or 0 + end + local perCorner = false + for _, pv in { normals, color, opacity } do + if pv and (pv.interp == "faceVarying" or pv.interp == "uniform") then + perCorner = true + end + end + for _, pv in uvs do + if pv.interp == "faceVarying" or pv.interp == "uniform" then + perCorner = true + end + end + local leftHanded = str(propValue(prim.props.orientation)) == "leftHanded" + -- holes + local hole: { [number]: boolean } = {} + local hv = propValue(prim.props.holeIndices) + if isArr(hv) then + for _, f in hv.v do + hole[f] = true + end + end + -- face sets: GeomSubsets ("face" elements), the rest + local meshMaterial = binding(prim, path) + local constantColor: { number }? = nil + if color and color.interp == "constant" then + constantColor = { get(color, 0, 0, 0, 0), get(color, 0, 0, 0, 1), get(color, 0, 0, 0, 2), if opacity and opacity.interp == "constant" then get(opacity, 0, 0, 0, 0) else 1 } + end + type Set = { faces: { number }, material: number?, name: string? } + local sets: { Set } = {} + local used: { [number]: boolean } = {} + for _, c in prim.children do + if c.typeName == "GeomSubset" and c.specifier ~= "class" then + local et = str(propValue(c.props.elementType)) or "face" + local fi = propValue(c.props.indices) + if et == "face" and isArr(fi) then + local faces = {} + for _, f in fi.v do + if f >= 0 and f < nfaces and f == f // 1 and not used[f] then + used[f] = true + table.insert(faces, f) + end + end + table.sort(faces) + local cpath = joinPath(path, c.name) + local rel = c.props["material:binding"] or c.props["material:binding:preview"] + local mi = if rel and rel.value and #rel.value > 0 then material(resolvePath(cpath, rel.value[1])) else meshMaterial + table.insert(sets, { faces = faces, material = mi, name = c.name }) + end + end + end + do + local rest = {} + for f = 0, nfaces - 1 do + if not used[f] then + table.insert(rest, f) + end + end + if #rest > 0 or #sets == 0 then + table.insert(sets, 1, { faces = rest, material = meshMaterial }) + end + end + local mesh: Types.Mesh = { name = prim.name, primitives = {} } + for _, set in sets do + -- vertices: one per point (vertex-rate data) or per corner + local keyToVert: { [number]: number } = {} + local vp, vf, vc = {}, {}, {} -- point, face, corner per new vertex (0-based) + local nv = 0 + local out: { number } = {} + local faceSizes: { number } = {} + for _, f in set.faces do + local cnt0 = counts[f + 1] + if cnt0 >= 3 and not hole[f] then + local base = faceStart[f + 1] + local verts = table.create(cnt0) + for k = 0, cnt0 - 1 do + local corner = base + k + local point = indices[corner + 1] + local key = if perCorner then corner else point + local v = keyToVert[key] + if not v then + v = nv + keyToVert[key] = v + nv += 1 + vp[nv], vf[nv], vc[nv] = point, f, corner + end + verts[k + 1] = v + end + if leftHanded then + local r = table.create(cnt0) + for k = 1, cnt0 do + r[k] = verts[cnt0 - k + 1] + end + verts = r + end + if triangulate then + for k = 2, cnt0 - 1 do + table.insert(out, verts[1]) + table.insert(out, verts[k]) + table.insert(out, verts[k + 1]) + end + else + for k = 1, cnt0 do + table.insert(out, verts[k]) + end + table.insert(faceSizes, cnt0) + end + end + end + if nv > 0 then + local attrs: { [string]: Types.Accessor } = {} + local pos = Types.Scene.accessor(nil, "f32", 3, nv) + for v = 1, nv do + local p0 = vp[v] * 3 + buffer.writef32(pos.data, (v - 1) * 12, points[p0 + 1]) + buffer.writef32(pos.data, (v - 1) * 12 + 4, points[p0 + 2]) + buffer.writef32(pos.data, (v - 1) * 12 + 8, points[p0 + 3]) + end + attrs.POSITION = pos + local function fill(pv: Primvar, comps: number, flip: boolean): Types.Accessor + local a = Types.Scene.accessor(nil, "f32", comps, nv) + for v = 1, nv do + for c = 0, comps - 1 do + local x = get(pv, vp[v], vf[v], vc[v], c) + if flip and c == 1 then + x = 1 - x + end + buffer.writef32(a.data, ((v - 1) * comps + c) * 4, x) + end + end + return a + end + if normals then + local nrm = fill(normals, 3, false) + if leftHanded then + -- normals follow the authored (left-handed) winding: keep them as authored + end + attrs.NORMAL = nrm + end + for k, pv in uvs do + attrs["TEXCOORD_" .. k] = fill(pv, 2, flipV) + end + local mi = set.material + if color and not constantColor then + -- varying colours -> COLOR_0 (rgb, or rgba with displayOpacity) + if opacity then + local a = Types.Scene.accessor(nil, "f32", 4, nv) + for v = 1, nv do + for c = 0, 2 do + buffer.writef32(a.data, ((v - 1) * 4 + c) * 4, get(color, vp[v], vf[v], vc[v], c)) + end + buffer.writef32(a.data, ((v - 1) * 4 + 3) * 4, get(opacity, vp[v], vf[v], vc[v], 0)) + end + attrs.COLOR_0 = a + else + attrs.COLOR_0 = fill(color, 3, false) + end + elseif constantColor and mi == nil then + mi = colorMaterial(constantColor) + end + local ind = Types.Scene.accessor(nil, "u32", 1, #out) + for k, v in out do + buffer.writeu32(ind.data, (k - 1) * 4, v) + end + local prm: Types.Primitive = { attributes = attrs, indices = ind, mode = if triangulate then "triangles" else "polygons", material = mi } + if not triangulate then + local fa = Types.Scene.accessor(nil, "u32", 1, #faceSizes) + for k, v in faceSizes do + buffer.writeu32(fa.data, (k - 1) * 4, v) + end + prm.faces = fa + end + if set.name then + prm.extras = { usd = { subset = set.name } } + end + local ds = propValue(prim.props.doubleSided) + if mi and (ds == 1 or ds == true) then + local m = mi and scene.materials[mi] + if m then + m.doubleSided = true + end + end + table.insert(mesh.primitives, prm) + end + end + if #mesh.primitives == 0 then + return nil, nil + end + return mesh, nil + end + + -- --------------------------------------------------------------------------------------------- cameras / lights + local function camera(prim: Prim): Types.Camera + local function f(name: string, d: number): number + return num(propValue(prim.props[name])) or d + end + local focal = f("focalLength", 50) + local hap = f("horizontalAperture", 20.955) + local vap = f("verticalAperture", 15.2908) + local clip = nums(propValue(prim.props.clippingRange)) or { 1, 1000000 } + local proj = str(propValue(prim.props.projection)) or "perspective" + if proj == "orthographic" then + return { name = prim.name, type = "orthographic", xmag = hap / 20, ymag = vap / 20, znear = clip[1] or 1, zfar = clip[2] or 1000000 } + end + return { + name = prim.name, + type = "perspective", + yfov = 2 * math.atan(vap / (2 * focal)), + aspect = if vap > 0 then hap / vap else nil, + znear = clip[1] or 1, + zfar = clip[2], + } + end + local function light(prim: Prim): Types.Light + local function f(name: string, d: number): number + return num(propValue(prim.props["inputs:" .. name])) or num(propValue(prim.props[name])) or d + end + local col = nums(propValue(prim.props["inputs:color"])) or nums(propValue(prim.props.color)) or { 1, 1, 1 } + local intensity = f("intensity", 1) * 2 ^ f("exposure", 0) + local l: Types.Light = { name = prim.name, type = "point", color = { col[1] or 1, col[2] or 1, col[3] or 1 }, intensity = intensity } + local t = prim.typeName + local cone = num(propValue(prim.props["inputs:shaping:cone:angle"])) or num(propValue(prim.props["shaping:cone:angle"])) + if t == "DistantLight" then + l.type = "directional" + elseif t == "RectLight" or t == "DiskLight" then + l.type = "spot" + l.outerCone = math.pi / 2 + l.innerCone = 0 + end + if cone and cone < 90 then + local soft = num(propValue(prim.props["inputs:shaping:cone:softness"])) or 0 + l.type = "spot" + l.outerCone = cone * DEG + l.innerCone = math.max(0, cone * DEG * (1 - soft)) + end + return l + end + + -- --------------------------------------------------------------------------------------------- nodes + local tcps = num(meta.timeCodesPerSecond) or num(meta.framesPerSecond) or 24 + if tcps <= 0 then + tcps = 24 + end + local animation: Types.Animation = { name = "usd", channels = {} } + local failure: string? = nil + + local function isNode(p: Prim): boolean + -- class prims are abstract; an over with no def is not defined (UsdStage traversal skips both) + if p.specifier == "class" or p.specifier == "over" or NOT_NODES[p.typeName or ""] then + if SKEL[p.typeName or ""] then + unsupported["UsdSkel (skeletons, skinning, blend shapes)"] = true + end + return false + end + if p.typeName == "Scope" or p.typeName == nil then + -- scopes / untyped prims holding only materials are not nodes + local function hasContent(q: Prim, d: number): boolean + if d > 100 then + return false + end + for _, c in q.children do + if c.specifier ~= "class" and not NOT_NODES[c.typeName or ""] then + if c.typeName ~= nil and c.typeName ~= "Scope" then + return true + end + if hasContent(c, d + 1) then + return true + end + end + end + return false + end + if p.typeName == "Scope" or #p.children > 0 then + return hasContent(p, 0) + end + end + return true + end + + local function node(p: Prim, path: string, parent: number?, depth: number) + if depth > 200 or failure then + return + end + if not isNode(p) then + return + end + local n: Types.Node = { name = p.name, children = {}, extras = { usd = { path = path, type = p.typeName } } } + table.insert(scene.nodes, n) + local ni = #scene.nodes + local ops, reset = xformOps(p) + -- animated ops: the local matrix at the union of their time codes + local times: { number } = {} + do + local seen: { [number]: boolean } = {} + for _, op in ops do + local s = op.prop.samples + if s and #s.times > 1 then + for _, t in s.times do + if not seen[t] then + seen[t] = true + table.insert(times, t) + end + end + end + end + table.sort(times) + end + if #times > 1 then + local count = math.min(#times, 100000) + local tin = Types.Scene.accessor(nil, "f32", 1, count) + local tr = Types.Scene.accessor(nil, "f32", 3, count) + local ro = Types.Scene.accessor(nil, "f32", 4, count) + local sc = Types.Scene.accessor(nil, "f32", 3, count) + local prev: { number }? = nil + for k = 1, count do + local T, R, S = decompose(localMatrix(ops, times[k])) + if prev and prev[1] * R[1] + prev[2] * R[2] + prev[3] * R[3] + prev[4] * R[4] < 0 then + R = { -R[1], -R[2], -R[3], -R[4] } + end + prev = R + buffer.writef32(tin.data, (k - 1) * 4, times[k] / tcps) + for c = 0, 2 do + buffer.writef32(tr.data, ((k - 1) * 3 + c) * 4, T[c + 1]) + buffer.writef32(sc.data, ((k - 1) * 3 + c) * 4, S[c + 1]) + end + for c = 0, 3 do + buffer.writef32(ro.data, ((k - 1) * 4 + c) * 4, R[c + 1]) + end + end + table.insert(animation.channels, { node = ni, path = "translation", input = tin, output = tr, interpolation = "LINEAR" }) + table.insert(animation.channels, { node = ni, path = "rotation", input = tin, output = ro, interpolation = "LINEAR" }) + table.insert(animation.channels, { node = ni, path = "scale", input = tin, output = sc, interpolation = "LINEAR" }) + local T, R, S = decompose(localMatrix(ops, times[1])) + n.translation, n.rotation, n.scale = T, R, S + elseif #ops > 0 then + -- static: TRS when the stack is translate / rotate / scale in that order, else the matrix + local simple = true + local stage = 0 + for _, op in ops do + local st = if op.kind == "translate" then 1 elseif op.kind == "rotate" or op.kind == "orient" then 2 elseif op.kind == "scale" then 3 else 9 + if op.invert or st == 9 or st <= stage or string.find(op.prop.name, "^xformOp:%a+:") then + simple = false + end + stage = st + end + local m = localMatrix(ops, nil) + if simple then + local T, R, S = decompose(m) + local tx = ops[1].kind == "translate" + if tx then + n.translation = T + end + for _, op in ops do + if op.kind == "rotate" or op.kind == "orient" then + n.rotation = R + elseif op.kind == "scale" then + n.scale = S + end + end + -- a negative scale with a rotation is not TRS-representable through decompose: keep the matrix + local back = Types.Scene.nodeMatrix(n) + for k = 1, 16 do + if math.abs(back[k] - m[k]) > 1e-5 * math.max(1, math.abs(m[k])) then + simple = false + break + end + end + if not simple then + n.translation, n.rotation, n.scale = nil, nil, nil + end + end + if not simple then + local identity = true + for k = 1, 16 do + if m[k] ~= Types.Scene.IDENTITY[k] then + identity = false + end + end + if not identity then + n.matrix = m + end + end + end + if reset or parent == nil then + table.insert(scene.roots, ni) + if reset and parent then + (n.extras :: any).usd.resetXformStack = true + end + else + table.insert(scene.nodes[parent].children, ni) + end + local t = p.typeName + if t == "Mesh" then + local mesh, err = buildMesh(p, path) + if err == "LIMIT" then + failure = "LIMIT" + return + elseif err then + failure = err + return + end + if mesh then + table.insert(scene.meshes, mesh) + n.mesh = #scene.meshes + end + elseif t == "Camera" then + table.insert(scene.cameras, camera(p)) + n.camera = #scene.cameras + elseif t and LIGHTS[t] and t ~= "DomeLight" then + table.insert(scene.lights, light(p)) + n.light = #scene.lights + elseif t and t ~= "Xform" and t ~= "Scope" and t ~= "Mesh" and t ~= "DomeLight" and t ~= "SkelRoot" then + unsupported["prim type " .. t] = true + end + for _, c in p.children do + node(c, joinPath(path, c.name), ni, depth + 1) + end + end + + for _, p in layer.prims do + if p.specifier ~= "class" then + node(p, "/" .. p.name, nil, 1) + end + end + if failure then + return nil, failure + end + if #animation.channels > 0 then + table.insert(scene.animations, animation) + end + + -- stage metadata + local up = str(meta.upAxis) + scene.meta.up = if up == "Z" then "z" else "y" + local mpu = num(meta.metersPerUnit) + if mpu and mpu > 0 then + scene.meta.unit = mpu + end + local list = {} + for k in unsupported do + table.insert(list, k) + end + table.sort(list) + scene.meta.source = { + format = "usda", + defaultPrim = str(meta.defaultPrim), + timeCodesPerSecond = tcps, + startTimeCode = num(meta.startTimeCode), + endTimeCode = num(meta.endTimeCode), + doc = str(meta.doc), + unsupported = if #list > 0 then list else nil, + } + return scene, nil +end + +return Build diff --git a/src/Formats/model/usda/Parse.luau b/src/Formats/model/usda/Parse.luau new file mode 100644 index 0000000..99b38e1 --- /dev/null +++ b/src/Formats/model/usda/Parse.luau @@ -0,0 +1,820 @@ +--!strict +-- model/usda/Parse: USD ASCII (Sdf text format, "#usda 1.0") -> a layer of prim specs. New code, from the Sdf text +-- grammar as Pixar's USD writes and reads it: layer metadata, def / over / class prims with metadata, attributes +-- (custom / uniform / varying / config, scalar and array types, defaults, .timeSamples, .connect, metadata), relationships, +-- list ops (prepend / append / add / delete / reorder), variant sets, dictionaries, strings ("", '', triple quoted), +-- asset paths (@...@, @@@...@@@), paths (<...>), comments (#, //, /* */). Numeric arrays (points, indices) take a fast +-- path into flat number arrays. .spline blocks and unknown constructs are skipped by bracket matching. +-- Errors raise a table { usda = message, at = byte offset } inside this module; Parse.layer catches them (pcall) and +-- returns nil, message, offset - nothing escapes. +local Parse = {} + +-- values: numbers, booleans, strings, and these tagged tables +export type Arr = { t: "arr", w: number, v: { number } } -- numeric array, w numbers per element (tuples flattened) +export type Value = any + +export type Prop = { + name: string, + rel: boolean, -- a relationship + typeName: string?, -- "point3f", "token", ... (attributes) + array: boolean?, + uniform: boolean?, + custom: boolean?, + value: Value?, -- the default value (attributes) or the targets (relationships: { path strings }) + hasValue: boolean?, + samples: { times: { number }, values: { Value } }?, + connect: { string }?, -- connection target paths (attributes) + meta: { [string]: Value }?, +} +export type Prim = { + specifier: string, -- "def" | "over" | "class" + typeName: string?, + name: string, + meta: { [string]: Value }, + props: { [string]: Prop }, + order: { string }, -- property names in file order + children: { Prim }, + variantSets: { [string]: { [string]: Prim } }?, -- set -> variant -> a prim body (props / children) +} +export type Layer = { meta: { [string]: Value }, prims: { Prim } } + +local NONE = table.freeze({ t = "none" }) +Parse.NONE = NONE + +local sfind, ssub, sbyte, smatch, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch + +local LISTOPS = { prepend = true, append = true, add = true, delete = true, reorder = true } +local VARIABILITY = { uniform = true, varying = true, config = true } +local MAX_DEPTH = 200 + +local function fail(msg: string, at: number): never + error({ usda = msg, at = at }, 0) +end + +-- the parser over one text; positions are 1-based string indices +local function parser(s: string, maxBytes: number) + local n = #s + local depth = 0 + + -- whitespace and comments (newlines included) + local function ws(i: number): number + while true do + local _, e = sfind(s, "^[ \t\r\n]+", i) + if e then + i = e + 1 + end + local c = sbyte(s, i) + if c == 35 then -- # + local nl = sfind(s, "\n", i, true) + i = if nl then nl + 1 else n + 1 + elseif c == 47 and sbyte(s, i + 1) == 47 then -- // + local nl = sfind(s, "\n", i, true) + i = if nl then nl + 1 else n + 1 + elseif c == 47 and sbyte(s, i + 1) == 42 then -- /* */ + local _, ce = sfind(s, "*/", i + 2, true) + if not ce then + fail("unterminated comment", i) + end + i = (ce :: number) + 1 + else + return i + end + end + end + + local function expect(i: number, ch: string): number + i = ws(i) + if ssub(s, i, i) ~= ch then + fail("expected '" .. ch .. "'", i) + end + return i + 1 + end + + local function ident(i: number): (string?, number) + local a, e = sfind(s, "^[%a_][%w_:]*", i) + if not a then + return nil, i + end + return ssub(s, a, e), (e :: number) + 1 + end + + local ESC = { n = "\n", t = "\t", r = "\r", ["\\"] = "\\", ['"'] = '"', ["'"] = "'", ["0"] = "\0", a = "\a", b = "\b", f = "\f", v = "\v" } + local function unescape(str: string): string + if not sfind(str, "\\", 1, true) then + return str + end + return (string.gsub(str, "\\(x?)(.)", function(x: string, c: string): string + if x == "x" then + return "\\x" .. c -- left alone (rare) + end + return ESC[c] or c + end)) + end + + local function str(i: number): (string, number) + local q = ssub(s, i, i) + if ssub(s, i, i + 2) == q .. q .. q then + local e = sfind(s, q .. q .. q, i + 3, true) + if not e then + fail("unterminated string", i) + end + return unescape(ssub(s, i + 3, (e :: number) - 1)), (e :: number) + 3 + end + local j = i + 1 + while true do + local a = sfind(s, "[\\\n" .. q .. "]", j) + if not a then + fail("unterminated string", i) + end + local c = sbyte(s, a :: number) + if c == 92 then + j = (a :: number) + 2 + elseif c == 10 then + fail("newline in string", a :: number) + else + return unescape(ssub(s, i + 1, (a :: number) - 1)), (a :: number) + 1 + end + end + end + + local function number(i: number): (number?, number) + local a, e = sfind(s, "^[-+]?%d*%.?%d*[eE][-+]?%d+", i) + if not a then + a, e = sfind(s, "^[-+]?%d*%.?%d*", i) + end + if a and (e :: number) >= (a :: number) then + local v = tonumber(ssub(s, a, e)) + if v then + return v, (e :: number) + 1 + end + end + -- inf / -inf / nan + local w, e2 = sfind(s, "^[-+]?%a+", i) + if w then + local word = string.lower(ssub(s, w, e2)) + if word == "inf" or word == "+inf" then + return math.huge, (e2 :: number) + 1 + elseif word == "-inf" then + return -math.huge, (e2 :: number) + 1 + elseif word == "nan" or word == "-nan" or word == "+nan" then + return 0 / 0, (e2 :: number) + 1 + end + end + return nil, i + end + + -- skip a balanced (), [], {} block starting at i (strings and comments respected) + local function skipBalanced(i: number): number + local open = sbyte(s, i) + local level = 0 + while i <= n do + i = ws(i) + local c = sbyte(s, i) + if c == nil then + break + end + if c == 40 or c == 91 or c == 123 then + level += 1 + i += 1 + elseif c == 41 or c == 93 or c == 125 then + level -= 1 + i += 1 + if level == 0 then + return i + end + elseif c == 34 or c == 39 then + local _, j = str(i) + i = j + elseif c == 64 then + local e = sfind(s, "@", i + 1, true) + i = if e then e + 1 else n + 1 + elseif c == 60 then + local e = sfind(s, ">", i + 1, true) + i = if e then e + 1 else n + 1 + else + local _, e = sfind(s, "^[^%(%)%[%]{}\"'@<#/ \t\r\n]+", i) + i = if e then e + 1 else i + 1 + end + end + fail("unbalanced " .. string.char(open or 63), i) + end + + local value: (i: number) -> (Value, number) + local metadata: (i: number) -> ({ [string]: Value }, number) + + -- [ ... ]: the fast path for numeric arrays (flat numbers + tuple width), else a generic list + local function list(i: number): (Value, number) + local close = sfind(s, "]", i + 1, true) + if close then + local body = ssub(s, i + 1, close - 1) + if not sfind(body, "[^%d%s%.,eE%-%+%(%)]") then + local first = smatch(body, "^%s*%(([^%)]*)%)") + local w = 1 + if first then + w = 0 + for _ in gmatch(first, "[^%s,]+") do + w += 1 + end + elseif sfind(body, "[%(%)]") then + w = -1 -- nested tuples: the generic path + end + if w > 0 then + local out: { number } = {} + local k = 0 + local ok = true + for tok in gmatch(body, "[^%s,%(%)]+") do + local v = tonumber(tok) + if not v then + ok = false + break + end + k += 1 + out[k] = v + end + if ok and k % w == 0 then + if k * 8 > maxBytes then + fail("array over the size limit", i) + end + return { t = "arr", w = w, v = out } :: Arr, close + 1 + end + end + end + end + -- generic + local items = {} + i += 1 + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "]" then + i += 1 + break + elseif c == "" then + fail("unterminated list", i) + end + local v + v, i = value(i) + table.insert(items, v) + i = ws(i) + if ssub(s, i, i) == "(" then -- per-item metadata (subLayers offsets, ...) + local _ + _, i = metadata(i) + i = ws(i) + end + c = ssub(s, i, i) + if c == "," then + i += 1 + elseif c ~= "]" then + fail("expected ',' or ']' in a list", i) + end + end + -- all numbers, or all equal-width numeric tuples -> arr + local w: number? = nil + local flat: { number } = {} + for _, it in items do + if type(it) == "number" then + if w and w ~= 1 then + return { t = "list", v = items }, i + end + w = 1 + table.insert(flat, it) + elseif type(it) == "table" and it.t == "tuple" then + local tw = #it.v + if (w and w ~= tw) or tw == 0 then + return { t = "list", v = items }, i + end + w = tw + for _, x in it.v do + if type(x) ~= "number" then + return { t = "list", v = items }, i + end + table.insert(flat, x) + end + else + return { t = "list", v = items }, i + end + end + if w == nil then + return { t = "list", v = items }, i + end + return { t = "arr", w = w, v = flat } :: Arr, i + end + + local function tuple(i: number): (Value, number) + local items = {} + i += 1 + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == ")" then + i += 1 + break + elseif c == "" then + fail("unterminated tuple", i) + end + local v + v, i = value(i) + table.insert(items, v) + i = ws(i) + c = ssub(s, i, i) + if c == "," then + i += 1 + elseif c ~= ")" then + fail("expected ',' or ')' in a tuple", i) + end + end + return { t = "tuple", v = items }, i + end + + -- { type key = value ... } (metadata dictionaries) + local function dict(i: number): (Value, number) + local out: { [string]: Value } = {} + i += 1 + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + i += 1 + break + elseif c == "" then + fail("unterminated dictionary", i) + elseif c == ";" or c == "," then + i += 1 + continue + end + local ty + ty, i = ident(i) + if not ty then + fail("expected a type in a dictionary", i) + end + i = ws(i) + if ssub(s, i, i + 1) == "[]" then + i += 2 + end + i = ws(i) + local key: string? + c = ssub(s, i, i) + if c == '"' or c == "'" then + key, i = str(i) + else + key, i = ident(i) + end + if not key then + fail("expected a key in a dictionary", i) + end + i = expect(i, "=") + local v + v, i = value(i) + out[key :: string] = v + end + return { t = "dict", v = out }, i + end + + function value(i: number): (Value, number) + depth += 1 + if depth > MAX_DEPTH then + fail("nesting too deep", i) + end + i = ws(i) + local c = ssub(s, i, i) + local v: Value + if c == "[" then + v, i = list(i) + elseif c == "(" then + v, i = tuple(i) + elseif c == "{" then + v, i = dict(i) + elseif c == '"' or c == "'" then + v, i = str(i) + elseif c == "@" then + local path + if ssub(s, i, i + 2) == "@@@" then + local e = sfind(s, "@@@", i + 3, true) + if not e then + fail("unterminated asset path", i) + end + path, i = ssub(s, i + 3, (e :: number) - 1), (e :: number) + 3 + else + local e = sfind(s, "@", i + 1, true) + if not e then + fail("unterminated asset path", i) + end + path, i = ssub(s, i + 1, (e :: number) - 1), (e :: number) + 1 + end + local a: { [string]: any } = { t = "asset", v = path } + local j = ws(i) + if ssub(s, j, j) == "<" then -- references = @file@ + local e = sfind(s, ">", j + 1, true) + if not e then + fail("unterminated path", j) + end + a.path = ssub(s, j + 1, (e :: number) - 1) + i = (e :: number) + 1 + end + v = a + elseif c == "<" then + local e = sfind(s, ">", i + 1, true) + if not e then + fail("unterminated path", i) + end + v, i = { t = "path", v = ssub(s, i + 1, (e :: number) - 1) }, (e :: number) + 1 + else + local num, j = number(i) + if num ~= nil then + v, i = num, j + else + local id + id, j = ident(i) + if not id then + fail("expected a value", i) + end + i = j + if id == "None" then + v = NONE + elseif id == "true" then + v = true + elseif id == "false" then + v = false + else + v = { t = "id", v = id } + end + end + end + depth -= 1 + return v, i + end + + -- ( key = value ; "doc" ; prepend key = value ... ) + function metadata(i: number): ({ [string]: Value }, number) + local out: { [string]: Value } = {} + i = expect(i, "(") + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == ")" then + return out, i + 1 + elseif c == "" then + fail("unterminated metadata", i) + elseif c == ";" or c == "," then + i += 1 + continue + elseif c == '"' or c == "'" then + out.doc, i = str(i) + continue + end + local key + key, i = ident(i) + if not key then + fail("expected a metadata key", i) + end + local op: string? = nil + if LISTOPS[key] then + op = key + i = ws(i) + key, i = ident(i) + if not key then + fail("expected a metadata key", i) + end + end + i = ws(i) + if ssub(s, i, i) == "=" then + local v + v, i = value(i + 1) + if op == "delete" then + -- deletions only matter for composition + elseif op and op ~= "reorder" then + -- prepend / append / add: merge into one list + local prev = out[key :: string] + if type(prev) == "table" and prev.t == "list" and type(v) == "table" and v.t == "list" then + for _, x in v.v do + table.insert(prev.v, x) + end + else + out[key :: string] = v + end + else + out[key :: string] = v + end + end + end + end + + -- time samples: { time: value, ... } + local function samples(i: number): ({ times: { number }, values: { Value } }, number) + local times, values = {}, {} + i = expect(i, "{") + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + i += 1 + break + elseif c == "" then + fail("unterminated time samples", i) + elseif c == "," then + i += 1 + continue + end + local t + t, i = number(i) + if t == nil then + fail("expected a time code", i) + end + i = expect(i, ":") + local v + v, i = value(i) + table.insert(times, t) + table.insert(values, v) + end + return { times = times, values = values }, i + end + + local function targets(v: Value): { string } + local out = {} + if type(v) == "table" then + if v.t == "path" then + table.insert(out, v.v) + elseif v.t == "list" then + for _, x in v.v do + if type(x) == "table" and x.t == "path" then + table.insert(out, x.v) + end + end + end + end + return out + end + + local primBody: (i: number, prim: Prim) -> number + + local function newPrim(specifier: string, typeName: string?, name: string): Prim + return { specifier = specifier, typeName = typeName, name = name, meta = {}, props = {}, order = {}, children = {} } + end + + -- def Type "name" ( meta ) { body } + local function prim(i: number, specifier: string): (Prim, number) + i = ws(i) + local typeName: string? = nil + local c = ssub(s, i, i) + if c ~= '"' and c ~= "'" then + typeName, i = ident(i) + if not typeName then + fail("expected a prim type or name", i) + end + i = ws(i) + -- dotted schema names (rare) + while ssub(s, i, i) == "." do + local more + more, i = ident(i + 1) + typeName = (typeName :: string) .. "." .. (more or "") + end + i = ws(i) + end + c = ssub(s, i, i) + if c ~= '"' and c ~= "'" then + fail("expected a prim name", i) + end + local name + name, i = str(i) + local p = newPrim(specifier, typeName, name) + i = ws(i) + if ssub(s, i, i) == "(" then + p.meta, i = metadata(i) + end + i = expect(i, "{") + i = primBody(i, p) + return p, i + end + + -- variantSet "name" = { "variant" ( meta ) { body } ... } + local function variantSet(i: number, p: Prim): number + i = ws(i) + local setName + setName, i = str(i) + i = expect(i, "=") + i = expect(i, "{") + local sets = p.variantSets or {} + p.variantSets = sets + local set = sets[setName] or {} + sets[setName] = set + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + return i + 1 + elseif c ~= '"' and c ~= "'" then + fail("expected a variant name", i) + end + local vname + vname, i = str(i) + local body = newPrim("def", nil, vname) + i = ws(i) + if ssub(s, i, i) == "(" then + body.meta, i = metadata(i) + end + i = expect(i, "{") + i = primBody(i, body) + set[vname] = body + end + end + + -- one property: [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...] + local function property(i: number, first: string, p: Prim): number + local word: string? = first + local op: string? = nil + if LISTOPS[word :: string] then + op = word + i = ws(i) + word, i = ident(i) + end + local custom, uniform = false, false + if word == "custom" then + custom = true + i = ws(i) + word, i = ident(i) + end + if word and VARIABILITY[word] then + uniform = word == "uniform" + i = ws(i) + word, i = ident(i) + end + if not word then + fail("expected a property", i) + end + local isRel = word == "rel" + local typeName: string? = nil + local array = false + if not isRel then + typeName = word + i = ws(i) + if ssub(s, i, i + 1) == "[]" then + array = true + i += 2 + end + end + i = ws(i) + local name + name, i = ident(i) + if not name then + fail("expected a property name", i) + end + local suffix: string? = nil + if ssub(s, i, i) == "." then + suffix, i = ident(i + 1) + end + local prop = p.props[name :: string] + if not prop then + prop = { name = name :: string, rel = isRel } + p.props[name :: string] = prop + table.insert(p.order, name :: string) + end + local pr = prop :: Prop + if typeName then + pr.typeName, pr.array = typeName, array + end + pr.uniform = pr.uniform or uniform or nil + pr.custom = pr.custom or custom or nil + i = ws(i) + if ssub(s, i, i) == "=" then + i = ws(i + 1) + if suffix == "timeSamples" then + pr.samples, i = samples(i) + elseif suffix == "spline" or (suffix ~= nil and suffix ~= "connect" and suffix ~= "default" and ssub(s, i, i) == "{") then + i = skipBalanced(i) + else + local v + v, i = value(i) + if op == "delete" then + -- composition only + elseif suffix == "connect" then + pr.connect = targets(v) + elseif isRel then + pr.value = targets(v) + pr.hasValue = true + else + pr.value = v + pr.hasValue = true + end + end + end + i = ws(i) + if ssub(s, i, i) == "(" then + local m + m, i = metadata(i) + if pr.meta then + for k, v in m do + (pr.meta :: any)[k] = v + end + else + pr.meta = m + end + end + return i + end + + function primBody(i: number, p: Prim): number + depth += 1 + if depth > MAX_DEPTH then + fail("nesting too deep", i) + end + while true do + i = ws(i) + local c = ssub(s, i, i) + if c == "}" then + depth -= 1 + return i + 1 + elseif c == "" then + fail("unterminated prim", i) + elseif c == ";" then + i += 1 + continue + end + local word, j = ident(i) + if not word then + fail("unexpected character in a prim", i) + end + if word == "def" or word == "over" or word == "class" then + local child + child, i = prim(j, word) + table.insert(p.children, child) + elseif word == "variantSet" then + i = variantSet(j, p) + elseif word == "reorder" then + local k = ws(j) + local w2, k2 = ident(k) + if w2 == "nameChildren" or w2 == "properties" or w2 == "rootPrims" then + k2 = expect(k2, "=") + local _ + _, i = value(k2) + else + i = property(j, word, p) + end + else + i = property(j, word, p) + end + end + end + + -- the whole layer + local function layer(): Layer + local i = 1 + if ssub(s, 1, 3) == "\239\187\191" then + i = 4 + end + if ssub(s, i, i + 4) ~= "#usda" then + fail("not a USDA file (no #usda header)", i) + end + local nl = sfind(s, "\n", i, true) + i = if nl then nl + 1 else n + 1 + local out: Layer = { meta = {}, prims = {} } + i = ws(i) + if ssub(s, i, i) == "(" then + out.meta, i = metadata(i) + end + while true do + i = ws(i) + if i > n then + break + end + local word, j = ident(i) + if word == "def" or word == "over" or word == "class" then + local p + p, i = prim(j, word) + table.insert(out.prims, p) + elseif word == "reorder" then + j = ws(j) + local _ + _, j = ident(j) + j = expect(j, "=") + _, i = value(j) + elseif ssub(s, i, i) == ";" then + i += 1 + else + fail("expected def / over / class", i) + end + end + return out + end + + return layer +end + +-- layer(text, opts?) -> Layer | nil, message, offset (0-based) +function Parse.layer(text: string, maxBytes: number?): (Layer?, string?, number?) + local run = parser(text, maxBytes or 2 ^ 30) + local ok, res = pcall(run) + if ok then + return res, nil, nil + end + if type(res) == "table" and res.usda then + return nil, res.usda, math.max((res.at or 1) - 1, 0) + end + return nil, "parse error: " .. tostring(res), nil +end + +-- version(text) -> the "#usda " string +function Parse.version(text: string): string? + return smatch(text, "^\239?\187?\191?#usda%s+([%d%.]+)") +end + +return Parse diff --git a/src/Formats/model/usda/Write.luau b/src/Formats/model/usda/Write.luau new file mode 100644 index 0000000..a4e53f3 --- /dev/null +++ b/src/Formats/model/usda/Write.luau @@ -0,0 +1,840 @@ +--!strict +-- model/usda/Write: Scene -> USD ASCII text (UsdGeom / UsdShade / UsdLux). New code. +-- Layout: one root prim (the scene's single root node, else an Xform "root" holding every root) as the defaultPrim, +-- a "Looks" scope under it with the materials (UsdPreviewSurface + UsdUVTexture + UsdPrimvarReader_float2, texture +-- transforms as UsdTransform2d), and one prim per node: a node with a mesh is a Mesh prim (its primitives merged, a +-- GeomSubset per primitive when there are several), a node with only a camera / light is that Camera / light prim, +-- other nodes are Xforms (meshes / cameras / lights that cannot share the node's prim become children). Transforms are +-- translate / orient / scale ops (or a transform op for matrices); animation channels (translation / rotation / scale) +-- become time samples on those ops (timeCodesPerSecond 24). TEXCOORD_n -> primvars:st, st1, ... (v flipped back), +-- COLOR_0 -> displayColor (+ displayOpacity), NORMAL -> normals, all "vertex" interpolated. Textures: their uri, or the +-- embedded bytes written into opts.files as _.. Not written: skins, morph targets, weights animation, +-- lines / points primitives (counted in the returned notes). +local Types = require("@formats/Types") + +local Write = {} + +local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif", ["image/bmp"] = "bmp", ["image/x-tga"] = "tga", ["image/gif"] = "gif", ["image/tiff"] = "tiff" } +local RAD = 180 / math.pi + +export type Options = { files: { [string]: any }?, name: string?, upAxis: string?, metersPerUnit: number? } + +-- ------------------------------------------------------------------------------------------------ text helpers +local function fmt(x: number): string + if x ~= x then + return "nan" + elseif x == math.huge then + return "inf" + elseif x == -math.huge then + return "-inf" + elseif x == math.floor(x) and math.abs(x) < 1e15 then + return string.format("%d", x) + end + return string.format("%.9g", x) +end +local function tuple(t: { number }): string + local parts = table.create(#t) + for k, v in t do + parts[k] = fmt(v) + end + return "(" .. table.concat(parts, ", ") .. ")" +end +local function quote(s: string): string + return '"' .. string.gsub(s, '[\\"\n]', { ["\\"] = "\\\\", ['"'] = '\\"', ["\n"] = "\\n" }) .. '"' +end +local function asset(s: string): string + if string.find(s, "@", 1, true) then + return "@@@" .. s .. "@@@" + end + return "@" .. s .. "@" +end +-- a valid, sibling-unique prim name +local function namer(): (string?, string) -> string + local used: { [string]: boolean } = {} + return function(name: string?, fallback: string): string + local n = string.gsub(name or "", "[^%w_]", "_") + if n == "" then + n = fallback + end + if string.find(n, "^%d") then + n = "_" .. n + end + local base, k = n, 1 + while used[n] do + k += 1 + n = base .. "_" .. k + end + used[n] = true + return n + end +end + +-- an accessor's elements as numbers (normalized types to floats) +local function values(acc: Types.Accessor?): ({ number }?, number) + if not acc then + return nil, 0 + end + local get = Types.Scene.reader(acc) + if not get then + return nil, 0 + end + local n, c = acc.count, acc.components + local out = table.create(n * c) + for i = 0, n - 1 do + for k = 0, c - 1 do + out[i * c + k + 1] = get(i, k) + end + end + return out, c +end + +-- array literal of tuples ("[(x, y, z), ...]") or scalars +local function arrayText(vals: { number }, width: number, stride: number?, count: number?, map: ((i: number, k: number, v: number) -> number)?): string + local st = stride or width + local n = count or (#vals // st) + local parts = table.create(n) + local buf = table.create(width) + for i = 0, n - 1 do + for k = 1, width do + local v = vals[i * st + k] or 0 + if map then + v = map(i, k, v) + end + buf[k] = fmt(v) + end + parts[i + 1] = if width == 1 then buf[1] else "(" .. table.concat(buf, ", ", 1, width) .. ")" + end + return "[" .. table.concat(parts, ", ") .. "]" +end + +-- ------------------------------------------------------------------------------------------------ primitives +type Merged = { + points: { number }, + counts: { number }, + indices: { number }, + normals: { number }?, + uvs: { [number]: { number } }, + colors: { number }?, -- rgba + hasAlpha: boolean, + subsets: { { faces: { number }, material: number? } }, +} + +-- the triangles / polygons of a primitive as (counts, corner indices into its vertices); nil for lines / points +local function faces(p: Types.Primitive, nverts: number): ({ number }?, { number }?) + local idx: { number } + if p.indices then + idx = (values(p.indices)) or {} + else + idx = table.create(nverts) + for i = 1, nverts do + idx[i] = i - 1 + end + end + local counts, out = {}, {} + local mode = p.mode + if mode == "triangles" or mode == nil then + for k = 1, #idx - 2, 3 do + table.insert(counts, 3) + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + table.insert(out, idx[k + 2]) + end + elseif mode == "polygons" then + local fs = (values(p.faces)) or {} + local at = 1 + for _, n in fs do + if at + n - 1 > #idx then + break + end + table.insert(counts, n) + for k = at, at + n - 1 do + table.insert(out, idx[k]) + end + at += n + end + elseif mode == "triangle_strip" then + for k = 1, #idx - 2 do + local a, b, c = idx[k], idx[k + 1], idx[k + 2] + if k % 2 == 0 then + a, b = b, a + end + table.insert(counts, 3) + table.insert(out, a) + table.insert(out, b) + table.insert(out, c) + end + elseif mode == "triangle_fan" then + for k = 2, #idx - 1 do + table.insert(counts, 3) + table.insert(out, idx[1]) + table.insert(out, idx[k]) + table.insert(out, idx[k + 1]) + end + else + return nil, nil + end + return counts, out +end + +-- the primitives of a mesh merged into one USD mesh (GeomSubsets per primitive); nil when nothing is writable +local function merge(mesh: Types.Mesh, notes: { [string]: number }): Merged? + local prims: { Types.Primitive } = {} + for _, p in mesh.primitives do + if p.attributes and p.attributes.POSITION and p.attributes.POSITION.components == 3 and p.mode ~= "lines" and p.mode ~= "line_strip" and p.mode ~= "line_loop" and p.mode ~= "points" then + table.insert(prims, p) + else + notes["lines / points primitives"] = (notes["lines / points primitives"] or 0) + 1 + end + if p.targets and #p.targets > 0 then + notes["morph targets"] = (notes["morph targets"] or 0) + 1 + end + end + if #prims == 0 then + return nil + end + -- attributes every primitive has + local all = { NORMAL = true } + local uvSets: { number } = {} + for k = 0, 7 do + local every = true + for _, p in prims do + if not p.attributes["TEXCOORD_" .. k] then + every = false + end + end + if every then + table.insert(uvSets, k) + end + end + local anyColor = false + for _, p in prims do + if not p.attributes.NORMAL or p.attributes.NORMAL.components ~= 3 then + all.NORMAL = false + end + if p.attributes.COLOR_0 then + anyColor = true + end + end + local m: Merged = { points = {}, counts = {}, indices = {}, normals = if all.NORMAL then {} else nil, uvs = {}, colors = if anyColor then {} else nil, hasAlpha = false, subsets = {} } + for _, k in uvSets do + m.uvs[k] = {} + end + local face = 0 + for _, p in prims do + local base = #m.points // 3 + local pos = (values(p.attributes.POSITION)) or {} + local nv = p.attributes.POSITION.count + table.move(pos, 1, nv * 3, #m.points + 1, m.points) + if m.normals then + local nrm = (values(p.attributes.NORMAL)) or {} + table.move(nrm, 1, nv * 3, #m.normals + 1, m.normals) + end + for _, k in uvSets do + local uv, c = values(p.attributes["TEXCOORD_" .. k]) + local dst = m.uvs[k] + for i = 0, nv - 1 do + table.insert(dst, (uv :: { number })[i * c + 1] or 0) + table.insert(dst, (uv :: { number })[i * c + 2] or 0) + end + end + if m.colors then + local col, c = values(p.attributes.COLOR_0) + local dst = m.colors :: { number } + for i = 0, nv - 1 do + if col then + table.insert(dst, col[i * c + 1] or 1) + table.insert(dst, col[i * c + 2] or 1) + table.insert(dst, col[i * c + 3] or 1) + local a = if c >= 4 then col[i * c + 4] or 1 else 1 + if a ~= 1 then + m.hasAlpha = true + end + table.insert(dst, a) + else + table.insert(dst, 1) + table.insert(dst, 1) + table.insert(dst, 1) + table.insert(dst, 1) + end + end + end + local counts, idx = faces(p, nv) + local sub = { faces = {}, material = p.material } + if counts and idx then + local ok = true + for _, v in idx do + if v < 0 or v >= nv then + ok = false + break + end + end + if ok then + for _, c in counts do + table.insert(m.counts, c) + table.insert(sub.faces, face) + face += 1 + end + for _, v in idx do + table.insert(m.indices, v + base) + end + else + notes["out-of-range indices"] = (notes["out-of-range indices"] or 0) + 1 + end + end + table.insert(m.subsets, sub) + end + return m +end + +-- ------------------------------------------------------------------------------------------------ write +function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: number }) + local o: Options = opts or {} + local notes: { [string]: number } = {} + local out: { string } = {} + local function line(depth: number, s: string) + table.insert(out, string.rep(" ", depth) .. s) + end + local nodes = scene.nodes or {} + local roots = scene.roots + if not roots or #roots == 0 then + local child = {} + for _, n in nodes do + for _, c in n.children or {} do + child[c] = true + end + end + roots = {} + for i in nodes do + if not child[i] then + table.insert(roots, i) + end + end + end + if #(scene.skins or {}) > 0 then + notes.skins = #scene.skins + end + local wrap = #roots ~= 1 or (nodes[roots[1]] == nil) + local rootNames = namer() + local rootName = if wrap then "root" else rootNames(nodes[roots[1]].name, "root") + + -- texture files + local base = o.name and string.gsub(string.match(o.name, "([^/\\]+)$") or o.name, "%.[^.]*$", "") or "model" + local texFile: { [number]: string } = {} + for i, tex in scene.textures or {} do + local uri: string? = if tex.uri then (string.gsub(tex.uri, "\\", "/")) else nil + if tex.data and type(o.files) == "table" then + uri = uri or (base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png")) + if string.find(uri :: string, "^data:") or string.find(uri :: string, "^%a+://") then + uri = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png") + end + local files: any = o.files + if files[uri] == nil then + files[uri] = tex.data + end + elseif not uri then + uri = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png") + notes["textures without a file (not written)"] = (notes["textures without a file (not written)"] or 0) + 1 + end + texFile[i] = uri :: string + end + + -- animation: per node, per path -> { times, values (components) } + type Track = { times: { number }, vals: { number }, comps: number } + local tracks: { [number]: { [string]: Track } } = {} + local tcps = 24 + local tMin, tMax = math.huge, -math.huge + for _, anim in scene.animations or {} do + for _, ch in anim.channels or {} do + if ch.path == "weights" then + notes["weights animation"] = (notes["weights animation"] or 0) + 1 + elseif nodes[ch.node] and ch.input and ch.output then + local times = (values(ch.input)) or {} + local vals, comps = values(ch.output) + if vals and #times > 0 then + local stride = comps + local per = #vals // (comps * #times) + -- CUBICSPLINE: in-tangent, value, out-tangent per key: keep the value + local off = if ch.interpolation == "CUBICSPLINE" and per == 3 then comps else 0 + local mult = if ch.interpolation == "CUBICSPLINE" and per == 3 then 3 else 1 + local tv = {} + for k = 0, #times - 1 do + for c = 1, stride do + table.insert(tv, vals[k * comps * mult + off + c] or 0) + end + end + tracks[ch.node] = tracks[ch.node] or {} + tracks[ch.node][ch.path] = { times = times, vals = tv, comps = comps } + for _, t in times do + tMin = math.min(tMin, t * tcps) + tMax = math.max(tMax, t * tcps) + end + end + end + end + end + + -- header + table.insert(out, "#usda 1.0") + table.insert(out, "(") + line(1, "defaultPrim = " .. quote(rootName)) + line(1, 'doc = "formats-luau"') + if tMin <= tMax then + line(1, "endTimeCode = " .. fmt(tMax)) + end + line(1, "metersPerUnit = " .. fmt(o.metersPerUnit or scene.meta.unit or 1)) + if tMin <= tMax then + line(1, "startTimeCode = " .. fmt(tMin)) + line(1, "timeCodesPerSecond = " .. fmt(tcps)) + end + line(1, "upAxis = " .. quote(o.upAxis or (if scene.meta.up == "z" then "Z" else "Y"))) + table.insert(out, ")") + table.insert(out, "") + + local looksPath = "/" .. rootName .. "/Looks" + local matNames = namer() + local matPath: { [number]: string } = {} + for i, mat in scene.materials or {} do + matPath[i] = looksPath .. "/" .. matNames(mat.name, "material_" .. i) + end + + -- xform ops of a node (+ its animation) + local function xform(depth: number, ni: number, n: Types.Node) + local tr = tracks[ni] + local order: { string } = {} + local function samples(track: Track, f: (vals: { number }, at: number) -> string): string + local parts = {} + for k, t in track.times do + table.insert(parts, fmt(t * tcps) .. ": " .. f(track.vals, (k - 1) * track.comps)) + end + return "{ " .. table.concat(parts, ", ") .. " }" + end + local function quat(v: { number }, at: number): string + -- USD writes (real, i, j, k) + return tuple({ v[at + 4] or 1, v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 }) + end + local function vec3(v: { number }, at: number): string + return tuple({ v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 }) + end + local t, r, s = n.translation, n.rotation, n.scale + if n.matrix and #n.matrix == 16 then + if tr then + -- animated: start from the matrix's TRS + local m = n.matrix + local sx = math.sqrt(m[1] ^ 2 + m[2] ^ 2 + m[3] ^ 2) + local sy = math.sqrt(m[5] ^ 2 + m[6] ^ 2 + m[7] ^ 2) + local sz = math.sqrt(m[9] ^ 2 + m[10] ^ 2 + m[11] ^ 2) + t, s = { m[13], m[14], m[15] }, { sx, sy, sz } + r = nil + notes["matrix nodes with animation (rotation reset)"] = (notes["matrix nodes with animation (rotation reset)"] or 0) + 1 + else + local m = n.matrix + line(depth, string.format("matrix4d xformOp:transform = ( %s, %s, %s, %s )", tuple({ m[1], m[2], m[3], m[4] }), tuple({ m[5], m[6], m[7], m[8] }), tuple({ m[9], m[10], m[11], m[12] }), tuple({ m[13], m[14], m[15], m[16] }))) + line(depth, 'uniform token[] xformOpOrder = ["xformOp:transform"]') + return + end + end + if t or (tr and tr.translation) then + if t then + line(depth, "double3 xformOp:translate = " .. tuple({ t[1] or 0, t[2] or 0, t[3] or 0 })) + end + if tr and tr.translation then + line(depth, "double3 xformOp:translate.timeSamples = " .. samples(tr.translation, vec3)) + end + table.insert(order, '"xformOp:translate"') + end + if r or (tr and tr.rotation) then + if r then + line(depth, "quatf xformOp:orient = " .. quat(r, 0)) + end + if tr and tr.rotation then + line(depth, "quatf xformOp:orient.timeSamples = " .. samples(tr.rotation, quat)) + end + table.insert(order, '"xformOp:orient"') + end + if s or (tr and tr.scale) then + if s then + line(depth, "float3 xformOp:scale = " .. tuple({ s[1] or 1, s[2] or 1, s[3] or 1 })) + end + if tr and tr.scale then + line(depth, "float3 xformOp:scale.timeSamples = " .. samples(tr.scale, vec3)) + end + table.insert(order, '"xformOp:scale"') + end + if #order > 0 then + line(depth, "uniform token[] xformOpOrder = [" .. table.concat(order, ", ") .. "]") + end + end + + local function meshBody(depth: number, m: Merged, path: string) + local doubleSided = false + for _, sub in m.subsets do + local mat = sub.material and scene.materials[sub.material] + if mat and mat.doubleSided then + doubleSided = true + end + end + if doubleSided then + line(depth, "uniform bool doubleSided = 1") + end + -- extent + local mn, mx = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for i = 0, #m.points // 3 - 1 do + for c = 1, 3 do + local v = m.points[i * 3 + c] + if v < mn[c] then + mn[c] = v + end + if v > mx[c] then + mx[c] = v + end + end + end + if #m.points > 0 then + line(depth, "float3[] extent = [" .. tuple(mn) .. ", " .. tuple(mx) .. "]") + end + line(depth, "int[] faceVertexCounts = " .. arrayText(m.counts, 1)) + line(depth, "int[] faceVertexIndices = " .. arrayText(m.indices, 1)) + local single = #m.subsets == 1 + if single and m.subsets[1].material and matPath[m.subsets[1].material :: number] then + line(depth, "rel material:binding = <" .. matPath[m.subsets[1].material :: number] .. ">") + end + if m.normals then + line(depth, "normal3f[] normals = " .. arrayText(m.normals, 3) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + end + line(depth, "point3f[] points = " .. arrayText(m.points, 3)) + if m.colors then + line(depth, "color3f[] primvars:displayColor = " .. arrayText(m.colors, 3, 4) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + if m.hasAlpha then + local alpha = {} + for i = 0, #m.colors // 4 - 1 do + alpha[i + 1] = m.colors[i * 4 + 4] + end + line(depth, "float[] primvars:displayOpacity = " .. arrayText(alpha, 1) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + end + end + local uvKeys = {} + for k in m.uvs do + table.insert(uvKeys, k) + end + table.sort(uvKeys) + for _, k in uvKeys do + local name = if k == 0 then "st" else "st" .. k + line(depth, "texCoord2f[] primvars:" .. name .. " = " .. arrayText(m.uvs[k], 2, nil, nil, function(_i: number, c: number, v: number): number + return if c == 2 then 1 - v else v + end) .. " (") + line(depth + 1, 'interpolation = "vertex"') + line(depth, ")") + end + line(depth, 'uniform token subdivisionScheme = "none"') + if not single then + local names = namer() + for k, sub in m.subsets do + if #sub.faces > 0 then + local mp = sub.material and matPath[sub.material :: number] + table.insert(out, "") + line(depth, 'def GeomSubset "' .. names("subset_" .. k, "subset") .. '"' .. (if mp then ' (\n' .. string.rep(" ", depth + 1) .. 'prepend apiSchemas = ["MaterialBindingAPI"]\n' .. string.rep(" ", depth) .. ")" else "")) + line(depth, "{") + line(depth + 1, 'uniform token elementType = "face"') + line(depth + 1, 'uniform token familyName = "materialBind"') + line(depth + 1, "int[] indices = " .. arrayText(sub.faces, 1)) + if mp then + line(depth + 1, "rel material:binding = <" .. mp .. ">") + end + line(depth, "}") + end + end + end + end + + local function cameraBody(depth: number, c: Types.Camera) + if c.type == "orthographic" then + line(depth, "float2 clippingRange = " .. tuple({ c.znear or 0.01, c.zfar or 1000000 })) + line(depth, "float horizontalAperture = " .. fmt((c.xmag or 1) * 20)) + line(depth, 'token projection = "orthographic"') + line(depth, "float verticalAperture = " .. fmt((c.ymag or 1) * 20)) + return + end + local vap = 24 + local yfov = c.yfov or 0.8 + local focal = vap / (2 * math.tan(yfov / 2)) + line(depth, "float2 clippingRange = " .. tuple({ c.znear or 0.01, c.zfar or 1000000 })) + line(depth, "float focalLength = " .. fmt(focal)) + line(depth, "float horizontalAperture = " .. fmt(vap * (c.aspect or 1))) + line(depth, 'token projection = "perspective"') + line(depth, "float verticalAperture = " .. fmt(vap)) + end + + local LIGHT_TYPE = { directional = "DistantLight", point = "SphereLight", spot = "SphereLight" } + local function lightBody(depth: number, l: Types.Light) + local c = l.color or { 1, 1, 1 } + line(depth, "color3f inputs:color = " .. tuple({ c[1] or 1, c[2] or 1, c[3] or 1 })) + line(depth, "float inputs:intensity = " .. fmt(l.intensity or 1)) + if l.type ~= "directional" then + line(depth, "float inputs:radius = 0") + end + if l.type == "spot" then + local outer = l.outerCone or math.pi / 4 + line(depth, "float inputs:shaping:cone:angle = " .. fmt(outer * RAD)) + line(depth, "float inputs:shaping:cone:softness = " .. fmt(if outer > 0 then 1 - (l.innerCone or 0) / outer else 0)) + end + if l.type ~= "directional" then + line(depth, "bool treatAsPoint = 1") + end + end + local function lightHead(l: Types.Light): string + return if l.type == "spot" then ' (\n%s prepend apiSchemas = ["ShapingAPI"]\n%s)' else "" + end + + local visited: { [number]: boolean } = {} + local function writeNode(depth: number, ni: number, path: string, names: (string?, string) -> string, isRoot: boolean) + local n = nodes[ni] + if not n or visited[ni] then + return + end + visited[ni] = true + local name = if isRoot and not wrap then rootName else names(n.name, "node_" .. ni) + local myPath = path .. "/" .. name + local mesh = n.mesh and scene.meshes[n.mesh] + local merged = mesh and merge(mesh, notes) + local cam = n.camera and scene.cameras[n.camera] + local lig = n.light and scene.lights[n.light] + local kind = "Xform" + local head = "" + local pad = string.rep(" ", depth) + if merged then + kind = "Mesh" + if #merged.subsets == 1 and merged.subsets[1].material and matPath[merged.subsets[1].material :: number] then + head = ' (\n' .. pad .. ' prepend apiSchemas = ["MaterialBindingAPI"]\n' .. pad .. ")" + end + elseif cam and not lig then + kind = "Camera" + elseif lig and not cam then + kind = LIGHT_TYPE[lig.type] or "SphereLight" + local h = lightHead(lig) + head = if h ~= "" then string.format(h, pad, pad) else "" + end + if n.skin then + notes.skins = (notes.skins or 0) + 0 + end + table.insert(out, "") + line(depth, "def " .. kind .. " " .. quote(name) .. head) + line(depth, "{") + xform(depth + 1, ni, n) + if kind == "Mesh" then + meshBody(depth + 1, merged :: Merged, myPath) + elseif kind == "Camera" then + cameraBody(depth + 1, cam :: Types.Camera) + elseif kind ~= "Xform" then + lightBody(depth + 1, lig :: Types.Light) + end + local childNames = namer() + -- a camera / light that did not take the node's prim + if cam and kind ~= "Camera" then + table.insert(out, "") + line(depth + 1, "def Camera " .. quote(childNames(cam.name, "camera"))) + line(depth + 1, "{") + cameraBody(depth + 2, cam) + line(depth + 1, "}") + end + if lig and kind == "Xform" or (lig and kind == "Mesh") or (lig and kind == "Camera") then + local l = lig :: Types.Light + local h = lightHead(l) + local pad2 = string.rep(" ", depth + 1) + table.insert(out, "") + line(depth + 1, "def " .. (LIGHT_TYPE[l.type] or "SphereLight") .. " " .. quote(childNames(l.name, "light")) .. (if h ~= "" then string.format(h, pad2, pad2) else "")) + line(depth + 1, "{") + lightBody(depth + 2, l) + line(depth + 1, "}") + end + if isRoot and not wrap then + Write._looks(out, depth + 1, scene, matPath, texFile, line) + end + for _, c in n.children or {} do + writeNode(depth + 1, c, myPath, childNames, false) + end + line(depth, "}") + end + + if wrap then + line(0, "def Xform " .. quote(rootName)) + line(0, "{") + Write._looks(out, 1, scene, matPath, texFile, line) + local names = namer() + names("Looks", "Looks") + for _, r in roots do + writeNode(1, r, "/" .. rootName, names, false) + end + line(0, "}") + else + writeNode(0, roots[1], "", rootNames, true) + end + table.insert(out, "") + return table.concat(out, "\n"), notes +end + +-- the Looks scope: materials as UsdPreviewSurface networks +function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPath: { [number]: string }, texFile: { [number]: string }, line: (number, string) -> ()) + local mats = scene.materials or {} + if #mats == 0 then + return + end + table.insert(out, "") + line(depth, 'def Scope "Looks"') + line(depth, "{") + for i, mat in mats do + local path = matPath[i] + local mname = string.match(path, "([^/]+)$") :: string + table.insert(out, "") + line(depth + 1, "def Material " .. quote(mname)) + line(depth + 1, "{") + local d = depth + 2 + line(d, "token outputs:surface.connect = <" .. path .. "/PreviewSurface.outputs:surface>") + -- texture nodes (one per distinct ref) + type TexNode = { name: string, ref: Types.TextureRef, color: boolean } + local texNodes: { TexNode } = {} + local function texNode(ref: Types.TextureRef?, color: boolean): string? + if not ref or not texFile[ref.texture] then + return nil + end + for _, tn in texNodes do + if tn.ref == ref or (tn.ref.texture == ref.texture and (tn.ref.texCoord or 0) == (ref.texCoord or 0) and tn.ref.transform == nil and ref.transform == nil and tn.color == color) then + return tn.name + end + end + local name = "Texture_" .. (#texNodes + 1) + table.insert(texNodes, { name = name, ref = ref, color = color }) + return name + end + local bc = mat.baseColor or { 1, 1, 1, 1 } + local blend = mat.alphaMode == "blend" or mat.alphaMode == "mask" + local diffuseTex = texNode(mat.baseColorTexture, true) + local mrTex = texNode(mat.metallicRoughnessTexture, false) + local emTex = texNode(mat.emissiveTexture, true) + local nTex = texNode(mat.normalTexture, false) + local oTex = texNode(mat.occlusionTexture, false) + table.insert(out, "") + line(d, 'def Shader "PreviewSurface"') + line(d, "{") + local e = d + 1 + line(e, 'uniform token info:id = "UsdPreviewSurface"') + if diffuseTex then + line(e, "color3f inputs:diffuseColor.connect = <" .. path .. "/" .. diffuseTex .. ".outputs:rgb>") + else + line(e, "color3f inputs:diffuseColor = " .. tuple({ bc[1] or 1, bc[2] or 1, bc[3] or 1 })) + end + local em = mat.emissive or { 0, 0, 0 } + if emTex then + line(e, "color3f inputs:emissiveColor.connect = <" .. path .. "/" .. emTex .. ".outputs:rgb>") + elseif (em[1] or 0) ~= 0 or (em[2] or 0) ~= 0 or (em[3] or 0) ~= 0 then + line(e, "color3f inputs:emissiveColor = " .. tuple({ em[1] or 0, em[2] or 0, em[3] or 0 })) + end + local ext = mat.extensions or {} + if ext.KHR_materials_clearcoat and type(ext.KHR_materials_clearcoat.clearcoatFactor) == "number" then + line(e, "float inputs:clearcoat = " .. fmt(ext.KHR_materials_clearcoat.clearcoatFactor)) + line(e, "float inputs:clearcoatRoughness = " .. fmt(tonumber(ext.KHR_materials_clearcoat.clearcoatRoughnessFactor) or 0)) + end + if ext.KHR_materials_ior and type(ext.KHR_materials_ior.ior) == "number" then + line(e, "float inputs:ior = " .. fmt(ext.KHR_materials_ior.ior)) + end + if mrTex then + line(e, "float inputs:metallic.connect = <" .. path .. "/" .. mrTex .. ".outputs:b>") + else + line(e, "float inputs:metallic = " .. fmt(mat.metallic or 0)) + end + if nTex then + line(e, "normal3f inputs:normal.connect = <" .. path .. "/" .. nTex .. ".outputs:rgb>") + end + if oTex then + line(e, "float inputs:occlusion.connect = <" .. path .. "/" .. oTex .. ".outputs:r>") + end + if blend and diffuseTex then + line(e, "float inputs:opacity.connect = <" .. path .. "/" .. diffuseTex .. ".outputs:a>") + elseif blend then + line(e, "float inputs:opacity = " .. fmt(bc[4] or 1)) + end + if mat.alphaMode == "mask" then + line(e, "float inputs:opacityThreshold = " .. fmt(mat.alphaCutoff or 0.5)) + end + if mrTex then + line(e, "float inputs:roughness.connect = <" .. path .. "/" .. mrTex .. ".outputs:g>") + else + line(e, "float inputs:roughness = " .. fmt(mat.roughness or 1)) + end + line(e, "token outputs:surface") + line(d, "}") + -- primvar readers per texCoord set, transforms, textures + local readers: { [number]: boolean } = {} + for _, tn in texNodes do + local tc = (tn.ref.transform and tn.ref.transform.texCoord) or tn.ref.texCoord or 0 + if not readers[tc] then + readers[tc] = true + table.insert(out, "") + line(d, 'def Shader "PrimvarReader_' .. tc .. '"') + line(d, "{") + line(d + 1, 'uniform token info:id = "UsdPrimvarReader_float2"') + line(d + 1, "string inputs:varname = " .. quote(if tc == 0 then "st" else "st" .. tc)) + line(d + 1, "float2 outputs:result") + line(d, "}") + end + end + for _, tn in texNodes do + local ref = tn.ref + local tc = (ref.transform and ref.transform.texCoord) or ref.texCoord or 0 + local stSource = path .. "/PrimvarReader_" .. tc .. ".outputs:result" + if ref.transform then + local tr = ref.transform :: any + table.insert(out, "") + line(d, 'def Shader "' .. tn.name .. '_Transform"') + line(d, "{") + line(d + 1, 'uniform token info:id = "UsdTransform2d"') + line(d + 1, "float2 inputs:in.connect = <" .. stSource .. ">") + if tr.rotation then + line(d + 1, "float inputs:rotation = " .. fmt(tr.rotation * RAD)) + end + if tr.scale then + line(d + 1, "float2 inputs:scale = " .. tuple({ tr.scale[1] or 1, tr.scale[2] or 1 })) + end + if tr.offset then + line(d + 1, "float2 inputs:translation = " .. tuple({ tr.offset[1] or 0, tr.offset[2] or 0 })) + end + line(d + 1, "float2 outputs:result") + line(d, "}") + stSource = path .. "/" .. tn.name .. "_Transform.outputs:result" + end + local tex = scene.textures[ref.texture] + local sampler = tex and tex.sampler or {} + table.insert(out, "") + line(d, 'def Shader "' .. tn.name .. '"') + line(d, "{") + line(d + 1, 'uniform token info:id = "UsdUVTexture"') + line(d + 1, "asset inputs:file = " .. asset(texFile[ref.texture])) + if tn.ref == mat.baseColorTexture and ((bc[1] or 1) ~= 1 or (bc[2] or 1) ~= 1 or (bc[3] or 1) ~= 1 or (bc[4] or 1) ~= 1) then + line(d + 1, "float4 inputs:scale = " .. tuple({ bc[1] or 1, bc[2] or 1, bc[3] or 1, bc[4] or 1 })) + end + if tn.ref == mat.normalTexture then + line(d + 1, "float4 inputs:bias = (-1, -1, -1, 0)") + line(d + 1, "float4 inputs:scale = (2, 2, 2, 1)") + end + line(d + 1, 'token inputs:sourceColorSpace = "' .. (if tn.color then "sRGB" else "raw") .. '"') + line(d + 1, "float2 inputs:st.connect = <" .. stSource .. ">") + line(d + 1, 'token inputs:wrapS = "' .. (sampler.wrapS or "repeat") .. '"') + line(d + 1, 'token inputs:wrapT = "' .. (sampler.wrapT or "repeat") .. '"') + line(d + 1, "float outputs:a") + line(d + 1, "float outputs:b") + line(d + 1, "float outputs:g") + line(d + 1, "float outputs:r") + line(d + 1, "float3 outputs:rgb") + line(d, "}") + end + line(depth + 1, "}") + end + line(depth, "}") +end + +return Write diff --git a/src/Formats/model/usda/init.luau b/src/Formats/model/usda/init.luau new file mode 100644 index 0000000..e1b8338 --- /dev/null +++ b/src/Formats/model/usda/init.luau @@ -0,0 +1,221 @@ +--!strict +-- model/usda: USD ASCII layers (.usda, .usd in text form) and USDZ packages holding them. New code, from the Sdf text +-- format and the UsdGeom / UsdShade / UsdLux schema documentation (OpenUSD 26.x); checked against OpenUSD's own +-- reader / writer (pxr) and Blender's USD exporter. +-- Reads: stage metadata (upAxis -> meta.up, metersPerUnit -> meta.unit, defaultPrim, timeCodesPerSecond, start / +-- endTimeCode), the prim tree (def / over; class skipped; selected variants merged), xform op stacks (translate, scale, +-- rotateX/Y/Z, rotateXYZ ... rotateZYX, orient, transform, !invert!, !resetXformStack!) with time samples -> one +-- animation of TRS channels, Mesh (faceVertexCounts / Indices, holes, leftHanded orientation, normals, every +-- texCoord2f primvar -> TEXCOORD_n with st first, displayColor / displayOpacity, all interpolations, :indices, +-- GeomSubsets -> one primitive each), UsdPreviewSurface materials with UsdUVTexture / UsdPrimvarReader_float2 / +-- UsdTransform2d, material:binding (inherited, per subset), Camera, DistantLight / SphereLight (+ ShapingAPI cone -> +-- spot) / RectLight / DiskLight (-> spot lights over a hemisphere). Textures stay encoded: bytes from opts.files / +-- opts.resolve (or the USDZ package) + mime, else just the uri (F.model.loadTextures decodes them). +-- Writes .usda (see model/usda/Write): Xform / Mesh / GeomSubset / Material / Shader / Camera / lights, time samples. +-- Not supported: USDC binary crate files (.usdc, and .usd / USDZ holding one: UNSUPPORTED), composition arcs +-- (references, payloads, inherits, specializes, subLayers: ignored and listed in meta.source.unsupported), UsdSkel +-- skinning, blend shapes, curves / points / NURBS prims, point instancers, MaterialX shading networks, writing USDZ. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Zip = require("@formats/containers/Zip") +local Parse = require("@formats/model/usda/Parse") +local Build = require("@formats/model/usda/Build") +local Write = require("@formats/model/usda/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Usda = { + name = "usda", + category = "model", + extensions = { "usda", "usd", "usdz" }, + mime = { "model/vnd.usda", "model/vnd.usdz+zip" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" }, + caps = { decode = true, encode = true, materials = true, animation = true, cameras = true, lights = true, polygons = true, vertexColors = true, usdz = "read", usdc = false }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate faces (default true); false keeps "polygons" primitives + flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's top-left origin) + resolve: ((uri: string) -> any)?, -- texture files next to the layer (the api sets it for paths) + files: { [string]: any }?, -- or: the files by asset path + maxVertices: number?, -- refuse meshes with more points / face corners (default 2^25) + maxBytes: number?, -- refuse numeric arrays over this many bytes (default 2^30) +} +export type EncodeOptions = { + files: { [string]: any }?, -- receives embedded texture bytes as _. + name: string?, -- the destination's file name (names the texture files) + format: string?, -- "usdz" -> UNSUPPORTED (set by the api from the destination's extension) + upAxis: string?, -- "Y" / "Z" (default: from scene.meta.up) + metersPerUnit: number?, -- default scene.meta.unit or 1 +} + +-- ------------------------------------------------------------------------------------------------ sniff +local function isUsdz(r: Bytes.Reader): boolean + if r:peek(4) ~= "PK\3\4" then + return false + end + -- the first entry is the root layer + local lo, hi = r:peekU8(26), r:peekU8(27) + if lo < 0 or hi < 0 then + return false + end + local nameLen = lo + hi * 256 + local name = string.lower(r:peek(30 + nameLen)) + name = string.sub(name, 31) + return string.find(name, "%.usd[ac]?$") ~= nil +end + +function Usda.sniff(r: Bytes.Reader): number + local head = r:peek(8) + if string.sub(head, 1, 5) == "#usda" or string.sub(head, 1, 8) == "\239\187\191#usda" then + return 1 + end + if head == "PXR-USDC" then + return 0.9 -- recognised so the error says USDC is not supported + end + if isUsdz(r) then + return 0.95 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts: DecodeOptions?, package: any): (uri: string) -> buffer? + return function(uri: string): buffer? + local candidates = { uri } + local slashed = string.gsub(uri, "\\", "/") + local stripped = string.gsub(slashed, "^%./", "") + if slashed ~= uri then + table.insert(candidates, slashed) + end + if stripped ~= slashed then + table.insert(candidates, stripped) + end + -- packaged assets: "model.usdz[textures/a.png]" + local inner = string.match(uri, "%[(.+)%]$") + if inner then + table.insert(candidates, inner) + end + for _, u in candidates do + if package then + local data = package:read(u) + if data then + return data + end + end + local v: any = nil + if opts and type(opts.files) == "table" then + v = opts.files[u] + end + if v == nil and opts and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, u) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + elseif type(v) == "buffer" then + return v + end + end + return nil + end +end + +function Usda.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local head = r:peek(8) + if head == "PXR-USDC" then + return nil, Err.new(Err.UNSUPPORTED, "USDC binary crate files (convert with usdcat to .usda)") + end + local text: string + local package: any = nil + local usdz = false + if string.sub(head, 1, 4) == "PK\3\4" then + local archive, zerr = Zip.open(r) + if not archive then + return nil, zerr or Err.new(Err.CORRUPT, "bad USDZ package") + end + local entries = archive:list() + local root = nil + for _, e in entries do + if not e.dir and string.find(string.lower(e.name), "%.usd[ac]?$") then + root = e + break + end + end + if not root then + return nil, Err.new(Err.CORRUPT, "the USDZ package holds no USD layer") + end + local data, rerr = archive:read(root) + if not data then + return nil, rerr + end + if buffer.len(data) >= 8 and buffer.readstring(data, 0, 8) == "PXR-USDC" then + return nil, Err.new(Err.UNSUPPORTED, "USDZ holding a USDC binary crate layer") + end + text = buffer.tostring(data) + package = archive + usdz = true + else + text = buffer.readstring(r.buf, r.base, r.limit - r.base) + end + if not Parse.version(text) then + return nil, Err.new(Err.CORRUPT, "no #usda header") + end + local layer, msg, at = Parse.layer(text, opts and opts.maxBytes) + if not layer then + if msg == "array over the size limit" then + return nil, Err.new(Err.LIMIT, msg :: string, at) + end + local code = if at and at >= #text - 1 then Err.TRUNCATED else Err.CORRUPT + if msg and string.find(msg, "^unterminated") then + code = Err.TRUNCATED + end + return nil, Err.new(code, msg or "parse error", if usdz then nil else at) + end + local scene, err = Build.scene(layer, { + triangulate = opts and opts.triangulate, + flipV = opts and opts.flipV, + maxVertices = opts and opts.maxVertices, + fetch = fetcher(opts, package), + }) + if not scene then + if err == "LIMIT" then + return nil, Err.new(Err.LIMIT, "a mesh over maxVertices") + end + return nil, Err.new(Err.CORRUPT, err or "bad scene") + end + local src: any = scene.meta.source + src.version = Parse.version(text) + src.usdz = usdz or nil + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Usda.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or scene.kind ~= "scene" then + return nil, Err.new(Err.ARG, "needs a Scene") + end + if opts and opts.format == "usdz" then + return nil, Err.new(Err.UNSUPPORTED, "writing USDZ; write .usda") + end + local ok, text = pcall(Write.text, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(text)) + end + return buffer.fromstring(text :: any), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- parse(text) -> the raw layer (prim specs, properties, metadata) | nil, Err: for prims the Scene does not cover +function Usda.parse(text: string): (Parse.Layer?, Err.Err?) + local layer, msg, at = Parse.layer(text) + if not layer then + return nil, Err.new(Err.CORRUPT, msg or "parse error", at) + end + return layer, nil +end + +return Usda diff --git a/tests/model/usda.luau b/tests/model/usda.luau new file mode 100644 index 0000000..17195ea --- /dev/null +++ b/tests/model/usda.luau @@ -0,0 +1,547 @@ +-- model/usda tests: stages authored with OpenUSD's API (every xform op kind / order, pivots, resetXformStack, +-- primvar interpolations, holes, leftHanded, n-gons, UsdPreviewSurface networks, GeomSubsets, inherited bindings, +-- cameras, lights, time samples, a USDZ package, a USDC file), a hand-written grammar test, assimp's USD models +-- (usda + usdc converted by Sdf), Blender 5 exports of glTF samples - all against OpenUSD (pxr: world transforms, +-- triangles, area and bounds per mesh, bound materials, PreviewSurface inputs and textures, cameras, lights, xform time +-- samples); OpenUSD's schema layers parse-only (prim spec counts); round trips through our writer (stable text) and +-- pxr reading our output (usda_xcheck); the api; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/usda.py. +local T = require("@tests/T") +local F = require("@formats") +local Usda = require("@formats/model/usda") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/usda_cases") +local Specs = require("@tests/gen/usda_specs") +local Xcheck = require("@tests/gen/usda_xcheck") + +local t = T.suite("usda") +local Scene = Types.Scene + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Usda.decode(Bytes.reader(b), opts) +end + +t:eq(Usda.name, "usda", "name") +t:eq(Usda.category, "model", "category") +t:check(Usda.caps.decode and Usda.caps.encode and table.find(Usda.extensions, "usdz"), "contract") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end +local function nearAll(a: { number }, b: { number }, eps: number): boolean + if #a ~= #b then + return false + end + for k = 1, #a do + if not near(a[k], b[k], eps) then + return false + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ scene helpers +-- a node's channels evaluated at time s (seconds): translation / rotation / scale overrides +local function animated(scene: any, s: number?): { [number]: any } + local out: { [number]: any } = {} + if not s then + return out + end + for _, anim in scene.animations do + for _, ch in anim.channels do + local n = ch.input.count + local get = Scene.reader(ch.output) :: any + local comps = ch.output.components + local k = 0 + for i = 0, n - 1 do + if buffer.readf32(ch.input.data, i * 4) <= s + 1e-6 then + k = i + end + end + local t0 = buffer.readf32(ch.input.data, k * 4) + local f = 0 + if k < n - 1 then + local t1 = buffer.readf32(ch.input.data, (k + 1) * 4) + f = math.clamp((s - t0) / (t1 - t0), 0, 1) + end + local v = {} + for c = 0, comps - 1 do + local a = get(k, c) + local b = if k < n - 1 then get(k + 1, c) else a + v[c + 1] = a + (b - a) * f + end + out[ch.node] = out[ch.node] or {} + out[ch.node][ch.path] = v + end + end + return out +end + +-- world matrices of every node (at animation time s when given) +local function worlds(scene: any, s: number?): { [number]: { number } } + local over = animated(scene, s) + local out: { [number]: { number } } = {} + local function visit(i: number, parent: { number }) + local n = scene.nodes[i] + if not n or out[i] then + return + end + local o = over[i] + local m + if o then + m = Scene.nodeMatrix({ children = {}, translation = o.translation or n.translation, rotation = o.rotation or n.rotation, scale = o.scale or n.scale }) + else + m = Scene.nodeMatrix(n) + end + local w = Scene.mul(parent, m) + out[i] = w + for _, c in n.children do + visit(c, w) + end + end + for _, r in scene.roots do + visit(r, Scene.IDENTITY :: any) + end + return out +end + +local function byPath(scene: any): { [string]: number } + local out = {} + for i, n in scene.nodes do + local u = n.extras and n.extras.usd + if u and u.path then + out[u.path] = i + end + end + return out +end + +-- triangles, world area and bounds of a node's mesh (or of everything: node = nil) +local function geometry(scene: any, ws: { [number]: { number } }, only: number?): (number, number, { number }, { number }) + local tris, area = 0, 0 + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for i, n in scene.nodes do + if n.mesh and (only == nil or only == i) and ws[i] then + local m = ws[i] + for _, p in scene.meshes[n.mesh].primitives do + local pos = p.attributes.POSITION + local function P(v: number): { number } + local x, y, z = buffer.readf32(pos.data, v * 12), buffer.readf32(pos.data, v * 12 + 4), buffer.readf32(pos.data, v * 12 + 8) + return { m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15] } + end + local ind = p.indices + for k = 0, ind.count // 3 - 1 do + local a, b, c = P(buffer.readu32(ind.data, k * 12)), P(buffer.readu32(ind.data, k * 12 + 4)), P(buffer.readu32(ind.data, k * 12 + 8)) + local e1 = { b[1] - a[1], b[2] - a[2], b[3] - a[3] } + local e2 = { c[1] - a[1], c[2] - a[2], c[3] - a[3] } + local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + area += math.sqrt(x * x + y * y + z * z) / 2 + tris += 1 + for _, q in { a, b, c } do + for j = 1, 3 do + lo[j] = math.min(lo[j], q[j]) + hi[j] = math.max(hi[j], q[j]) + end + end + end + end + end + end + return tris, area, lo, hi +end + +-- pxr's totals over every mesh +local function refTotals(ref: any): (number, number, { number }, { number }) + local tris, area = 0, 0 + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for _, m in ref.meshes do + tris += m.triangles + area += m.area + if #m.min == 3 then + for j = 1, 3 do + lo[j] = math.min(lo[j], m.min[j]) + hi[j] = math.max(hi[j], m.max[j]) + end + end + end + return tris, area, lo, hi +end + +local LIGHT_TYPES = { DistantLight = "directional", SphereLight = "point", RectLight = "spot", DiskLight = "spot" } +local SKIP_TYPES = { Skeleton = true, SkelRoot = true } + +-- ------------------------------------------------------------------------------------------------ against pxr +local decoded: { [number]: any } = {} +local counts = { xforms = 0, meshes = 0, materials = 0, cameras = 0, lights = 0, samples = 0, textures = 0 } +for ci, c in Cases do + local scene, err = decode(c.data, { files = c.files }) + if c.expect then + t:check(scene == nil and err and err.code == Err[c.expect], c.name .. ": " .. c.expect .. " (" .. tostring(err) .. ")") + continue + end + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if not scene then + continue + end + decoded[ci] = scene + local ref = c.ref + t:eq(scene.meta.up, string.lower(ref.upAxis), c.name .. ": up axis") + if ref.metersPerUnit > 0 then + t:check(scene.meta.unit and near(scene.meta.unit, ref.metersPerUnit, 1e-9), c.name .. ": metersPerUnit") + else + t:eq(scene.meta.unit, nil, c.name .. ": no metersPerUnit") + end + local paths = byPath(scene) + local ws = worlds(scene) + -- transforms: every xformable pxr sees is a node with the same world matrix + for _, x in ref.xforms do + if not SKIP_TYPES[x.type] then + local ni = paths[x.path] + t:check(ni, c.name .. ": node " .. x.path) + if ni then + t:check(nearAll(ws[ni], x.world, 1e-4), c.name .. ": world matrix of " .. x.path) + counts.xforms += 1 + end + end + end + -- meshes + for _, m in ref.meshes do + local ni = paths[m.path] + local node = ni and scene.nodes[ni] + if node and m.triangles > 0 then + t:check(node.mesh, c.name .. ": mesh at " .. m.path) + local tris, area, lo, hi = geometry(scene, ws, ni) + t:eq(tris, m.triangles, c.name .. ": triangles of " .. m.path) + t:check(near(area, m.area, 1e-4), string.format("%s: area of %s %.6g, pxr %.6g", c.name, m.path, area, m.area)) + t:check(nearAll(lo, m.min, 1e-4) and nearAll(hi, m.max, 1e-4), c.name .. ": bounds of " .. m.path) + -- bound materials (whole mesh, then subsets) + local mesh = scene.meshes[node.mesh] + local whole, subs = nil, {} + for _, p in mesh.primitives do + local mat = p.material and scene.materials[p.material] + local mp = mat and mat.extras and mat.extras.usd and mat.extras.usd.path or "" + if p.extras and p.extras.usd and p.extras.usd.subset then + table.insert(subs, mp) + else + whole = mp + end + end + if m.material ~= "" and whole then + t:eq(whole, m.material, c.name .. ": material of " .. m.path) + end + table.sort(subs) + t:eq(table.concat(subs, ","), table.concat(m.subsetMaterials, ","), c.name .. ": subset materials of " .. m.path) + counts.meshes += 1 + end + end + -- cameras + for _, cam in ref.cameras do + local ni = paths[cam.path] + local camera = ni and scene.nodes[ni].camera and scene.cameras[scene.nodes[ni].camera] + t:check(camera, c.name .. ": camera " .. cam.path) + if camera then + if cam.projection == "orthographic" then + t:check(camera.type == "orthographic" and near(camera.xmag, cam.hap / 20, 1e-6) and near(camera.ymag, cam.vap / 20, 1e-6), c.name .. ": ortho camera") + else + t:check(near(camera.yfov, 2 * math.atan(cam.vap / (2 * cam.focal)), 1e-5), c.name .. ": yfov of " .. cam.path) + t:check(near(camera.aspect, cam.hap / cam.vap, 1e-5), c.name .. ": aspect of " .. cam.path) + end + t:check(near(camera.znear, cam.near, 1e-5) and near(camera.zfar, cam.far, 1e-5), c.name .. ": clipping of " .. cam.path) + counts.cameras += 1 + end + end + -- lights + for _, l in ref.lights do + local ni = paths[l.path] + local light = ni and scene.nodes[ni].light and scene.lights[scene.nodes[ni].light] + t:check(light, c.name .. ": light " .. l.path) + if light then + local want = if l.cone > 0 and l.cone < 90 then "spot" else LIGHT_TYPES[l.type] + t:eq(light.type, want, c.name .. ": light type of " .. l.path) + t:check(near(light.intensity, l.intensity, 1e-5) and nearAll(light.color, l.color, 1e-5), c.name .. ": light values of " .. l.path) + if want == "spot" and l.cone > 0 then + t:check(near(light.outerCone, math.rad(l.cone), 1e-5), c.name .. ": cone of " .. l.path) + end + counts.lights += 1 + end + end + -- materials + local mats = {} + for _, m in scene.materials do + if m.extras and m.extras.usd and m.extras.usd.path then + mats[m.extras.usd.path] = m + end + end + for _, rm in ref.materials do + local m = mats[rm.path] + if m then -- only bound materials become Scene materials + local tx = rm.textures + if rm.diffuseColor and not tx.diffuseColor then + t:check(nearAll({ m.baseColor[1], m.baseColor[2], m.baseColor[3] }, rm.diffuseColor, 1e-6), c.name .. ": diffuse of " .. rm.path) + end + if rm.metallic and not tx.metallic then + t:check(near(m.metallic, rm.metallic, 1e-6), c.name .. ": metallic of " .. rm.path) + end + if rm.roughness and not tx.roughness then + t:check(near(m.roughness, rm.roughness, 1e-6), c.name .. ": roughness of " .. rm.path) + end + if rm.emissiveColor and not tx.emissiveColor then + t:check(nearAll(m.emissive, rm.emissiveColor, 1e-6), c.name .. ": emissive of " .. rm.path) + end + if rm.opacity and not tx.opacity then + t:check(near(m.baseColor[4], rm.opacity, 1e-6), c.name .. ": opacity of " .. rm.path) + if rm.opacityThreshold and rm.opacityThreshold > 0 then + t:check(m.alphaMode == "mask" and near(m.alphaCutoff, rm.opacityThreshold, 1e-6), c.name .. ": alpha mask of " .. rm.path) + elseif rm.opacity < 1 then + t:eq(m.alphaMode, "blend", c.name .. ": alpha blend of " .. rm.path) + end + end + local function texFile(ref: any): string? + local tex = ref and scene.textures[ref.texture] + return tex and tex.uri + end + for input, field in { diffuseColor = "baseColorTexture", normal = "normalTexture", emissiveColor = "emissiveTexture", occlusion = "occlusionTexture", roughness = "metallicRoughnessTexture", metallic = "metallicRoughnessTexture" } do + if tx[input] then + t:eq(texFile(m[field]), tx[input].file, c.name .. ": " .. input .. " texture of " .. rm.path) + counts.textures += 1 + end + end + counts.materials += 1 + end + end + -- xform time samples + for _, a in ref.anim do + local ni = paths[a.path] + for _, smp in a.samples do + local w = worlds(scene, smp.time / ref.tcps) + t:check(ni and nearAll(w[ni], smp.world, 1e-4), string.format("%s: %s at time %g", c.name, a.path, smp.time)) + counts.samples += 1 + end + end + -- textures with their file at hand carry its bytes + for _, tex in scene.textures do + local want = c.files[tex.uri] or c.files[(string.gsub(string.gsub(tex.uri, "\\", "/"), "^%./", ""))] or (c.like ~= nil) + if want then + t:check(tex.data and buffer.len(tex.data) > 0, c.name .. ": texture bytes for " .. tex.uri) + end + end +end +t:note("%d files against pxr: %d transforms, %d meshes, %d materials (%d textures), %d cameras, %d lights, %d time samples", #Cases, counts.xforms, counts.meshes, counts.materials, counts.textures, counts.cameras, counts.lights, counts.samples) + +-- ------------------------------------------------------------------------------------------------ specific facts +do + local hand + for ci, c in Cases do + if c.name == "hand.usda" then + hand = decoded[ci] + end + end + local p = byPath(hand) + t:check(p["/Hand/Big"] and not p["/Hand/Small"] and not p["/_Template"] and not p["/Elsewhere/Undefined"], "hand: selected variant, no class / undefined over") + t:check(p["/Hand/Untyped/Inner/Quad"] and not p["/Hand/Looks"], "hand: untyped prims are nodes, material scopes are not") + t:check(table.find(hand.meta.source.unsupported, "references"), "hand: references reported unsupported") + t:eq(hand.meta.source.defaultPrim, "Hand", "hand: defaultPrim") + local tri = hand.nodes[p["/Hand/Tri"]] + local mat = hand.materials[hand.meshes[tri.mesh].primitives[1].material] + t:check(nearAll(mat.baseColor, { 0.1, 0.2, 0.9, 1 }, 1e-6), "hand: diffuse through a Material interface input + relative paths") + local big = hand.meshes[hand.nodes[p["/Hand/Big"]].mesh].primitives[1] + t:check(big.attributes.COLOR_0 and big.attributes.COLOR_0.count == 4, "hand: vertex displayColor -> COLOR_0") + local layer = Usda.parse(Cases[1].data) + t:check(layer and #layer.prims == 1 and layer.meta.defaultPrim == "World", "parse: the raw layer") +end +do + local prim + for ci, c in Cases do + if c.name == "pxr/primvars.usda" then + prim = decoded[ci] + end + end + local p = byPath(prim) + local grid = prim.meshes[prim.nodes[p["/Grid"]].mesh].primitives[1] + t:check(grid.attributes.TEXCOORD_0 and grid.attributes.TEXCOORD_1 and grid.attributes.NORMAL and grid.attributes.COLOR_0.components == 4, "primvars: st, uv2, normals, colour + opacity") + local cc = prim.meshes[prim.nodes[p["/Grid/ConstColor"]].mesh].primitives[1] + t:check(cc.attributes.COLOR_0 == nil and nearAll(prim.materials[cc.material].baseColor, { 0.2, 0.4, 0.8, 1 }, 1e-6), "primvars: constant displayColor -> material") + local poly = decode(Cases[2].data, { triangulate = false }) + local pg = poly.meshes[1].primitives[1] + t:check(pg.mode == "polygons" and pg.faces.count == 17, "primvars: polygons kept (16 quads + pentagon + triangle - 1 hole)") + -- the texture transform on the materials stage + local mats + for ci, c in Cases do + if c.name == "pxr/materials.usda" then + mats = decoded[ci] + end + end + for _, m in mats.materials do + if m.name == "Textured" then + local mr = m.metallicRoughnessTexture + t:check(mr and mr.texCoord == 1 and mr.transform and near(mr.transform.rotation, math.rad(30), 1e-6), "materials: uv2 + UsdTransform2d -> texCoord 1 + KHR_texture_transform") + t:eq(mats.textures[mr.texture].sampler.wrapS, "mirror", "materials: wrapS") + end + end +end + +-- ------------------------------------------------------------------------------------------------ parse-only +for _, s in Specs do + local layer, err = Usda.parse(s.data) + t:check(layer, s.name .. ": parse: " .. tostring(err)) + if layer then + local n = 0 + local function count(list: { any }) + for _, p in list do + n += 1 + count(p.children) + end + end + count(layer.prims) + t:eq(n, s.prims, s.name .. ": prim specs (Sdf)") + end +end +t:note("%d OpenUSD schema layers parsed", #Specs) + +-- ------------------------------------------------------------------------------------------------ round trips +local rt = 0 +local texts: { [number]: string } = {} +for ci = 1, #Cases do + local scene = decoded[ci] + if not scene then + continue + end + local name = Cases[ci].name + local files = {} + local out, err = Usda.encode(scene, { files = files, name = "rt.usda" }) + t:check(out, name .. ": encode: " .. tostring(err)) + if out then + texts[ci] = buffer.tostring(out) + local back, berr = decode(out, { files = files }) + t:check(back, name .. ": decode our output: " .. tostring(berr)) + if back then + local a1, a2, a3, a4 = geometry(scene, worlds(scene)) + local b1, b2, b3, b4 = geometry(back, worlds(back)) + t:eq(b1, a1, name .. ": round trip triangles") + t:check(near(b2, a2, 1e-5) and (a1 == 0 or (nearAll(b3, a3, 1e-5) and nearAll(b4, a4, 1e-5))), name .. ": round trip area / bounds") + t:eq(#back.materials, #scene.materials, name .. ": round trip materials") + t:eq(#back.cameras, #scene.cameras, name .. ": round trip cameras") + t:eq(#back.lights, #scene.lights, name .. ": round trip lights") + t:eq(#back.animations, #scene.animations, name .. ": round trip animations") + t:eq(back.meta.up, scene.meta.up, name .. ": round trip up axis") + for k, m in scene.materials do + local b = back.materials[k] + t:check(b and nearAll(b.baseColor, m.baseColor, 1e-6) and near(b.metallic, m.metallic, 1e-6) and near(b.roughness, m.roughness, 1e-6) and b.alphaMode == m.alphaMode and (b.baseColorTexture ~= nil) == (m.baseColorTexture ~= nil), name .. ": round trip material " .. k) + end + -- animated geometry at every key time + if #scene.animations > 0 then + local ch = scene.animations[1].channels[1] + for i = 0, ch.input.count - 1 do + local s = buffer.readf32(ch.input.data, i * 4) + local _, x2, x3 = geometry(scene, worlds(scene, s)) + local _, y2, y3 = geometry(back, worlds(back, s)) + t:check(near(x2, y2, 1e-4) and nearAll(x3, y3, 1e-4), string.format("%s: round trip animation at %g s", name, s)) + end + end + -- our text is stable: after one cycle (a scene with several roots gains a "root" prim), writing what we + -- read from our own output gives the same text + local again = Usda.encode(back, { files = {}, name = "rt.usda" }) :: buffer + local third = Usda.encode((decode(again)), { files = {}, name = "rt.usda" }) :: buffer + t:eq(buffer.tostring(third), buffer.tostring(again), name .. ": stable text") + rt += 1 + end + end +end +t:note("%d round trips", rt) + +-- ------------------------------------------------------------------------------------------------ pxr reads our output +local xc = 0 +for _, x in Xcheck do + local scene = decoded[x.case] + local ref = x.ref + local name = Cases[x.case].name .. " -> ours" + t:check(scene and not ref.failed, name .. ": pxr opens our file") + if scene and not ref.failed then + local a1, a2, a3, a4 = geometry(scene, worlds(scene)) + local r1, r2, r3, r4 = refTotals(ref) + t:eq(r1, a1, name .. ": triangles (pxr)") + t:check(near(r2, a2, 1e-4), string.format("%s: area %.6g, pxr %.6g", name, a2, r2)) + if a1 > 0 then + t:check(nearAll(r3, a3, 1e-4) and nearAll(r4, a4, 1e-4), name .. ": bounds (pxr)") + end + t:eq(#ref.materials, #scene.materials, name .. ": materials (pxr)") + t:eq(#ref.cameras, #scene.cameras, name .. ": cameras (pxr)") + t:eq(#ref.lights, #scene.lights, name .. ": lights (pxr)") + t:eq(string.lower(ref.upAxis), scene.meta.up, name .. ": up axis (pxr)") + -- every material's values as pxr reads them + local want, got = {}, {} + for _, m in scene.materials do + table.insert(want, string.format("%.4f %.4f %.4f", if m.metallicRoughnessTexture then -1 else m.metallic, if m.metallicRoughnessTexture then -1 else m.roughness, if m.baseColorTexture then -1 else m.baseColor[1])) + end + for _, m in ref.materials do + table.insert(got, string.format("%.4f %.4f %.4f", if m.textures.metallic then -1 else m.metallic or 0, if m.textures.roughness then -1 else m.roughness or 0.5, if m.textures.diffuseColor then -1 else (m.diffuseColor or { 0.18 })[1])) + end + table.sort(want) + table.sort(got) + t:eq(table.concat(got, ";"), table.concat(want, ";"), name .. ": material values (pxr)") + -- animated nodes: each pxr sample matches one of our nodes at that time + for _, a in ref.anim do + for _, smp in a.samples do + local w = worlds(scene, smp.time / ref.tcps) + local found = false + for _, m in w do + if nearAll(m, smp.world, 1e-4) then + found = true + break + end + end + t:check(found, string.format("%s: %s at %g (pxr)", name, a.path, smp.time)) + end + end + xc += 1 + end +end +t:note("%d of our files read back by pxr like the originals", xc) + +-- ------------------------------------------------------------------------------------------------ api +do + local scene, err = F.model.load(Cases[1].data) + t:check(scene and scene.meta.source.format == "usda", "api: F.model.load sniffs usda: " .. tostring(err)) + local s = F.saveString(scene, { format = "usda" }) + t:check(s and string.sub(s, 1, 9) == "#usda 1.0", "api: F.saveString usda") + local _, zerr = F.save(scene, nil, { format = "usdz" }) + t:check(zerr and zerr.code == Err.UNSUPPORTED, "api: usdz writing unsupported") + t:eq(F.detect(Cases[1].data), "usda", "api: detect") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local _, e1 = decode("#usda 1.0\ndef Xform \"a\" {\n") + t:check(e1 and e1.code == Err.TRUNCATED, "truncated prim: " .. tostring(e1)) + local _, e2 = decode("#usda 1.0\ndef Xform \"a\" { float x = ] }\n") + t:check(e2 and e2.code == Err.CORRUPT, "bad value: " .. tostring(e2)) + local _, e3 = decode("hello") + t:check(e3 and e3.code == Err.CORRUPT, "no header") + local _, e4 = decode("#usda 1.0\ndef Mesh \"m\" { point3f[] points = [(0,0,0)] int[] faceVertexCounts = [3] int[] faceVertexIndices = [0, 1, 2] }") + t:check(e4 and e4.code == Err.CORRUPT, "index out of range: " .. tostring(e4)) + local _, e5 = decode(Cases[1].data, { maxVertices = 4 }) + t:check(e5 and e5.code == Err.LIMIT, "maxVertices") + local _, e6 = Usda.encode({ kind = "image" } :: any) + t:check(e6 and e6.code == Err.ARG, "encode a non-scene") + local deep = "#usda 1.0\ndef \"a\" { custom float x = " .. string.rep("(", 500) .. "1" .. string.rep(")", 500) .. " }" + local _, e7 = decode(deep) + t:check(e7 and e7.code == Err.CORRUPT, "nesting limit") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +local samples = {} +for _, c in Cases do + if #c.data < 40000 then + table.insert(samples, c.data) + end +end +t:fuzz("decode", function(b: buffer) + local s = decode(b) + if s then + Usda.encode(s) + end + return s +end, samples, { mutations = 24, keepHeader = 10 }) +t:done() diff --git a/tools/fixtures/_usda_encode.luau b/tools/fixtures/_usda_encode.luau new file mode 100644 index 0000000..bd02aac --- /dev/null +++ b/tools/fixtures/_usda_encode.luau @@ -0,0 +1,34 @@ +-- tools/fixtures/_usda_encode: run by tools/fixtures/usda.py (luau CLI, repo root): decodes every USDA case with our +-- reader and writes it back with our writer, printing "\t" lines (case_.usda + the texture files it +-- references) for OpenUSD (pxr) to read back. +local Usda = require("@formats/model/usda") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/usda_cases") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(s: string): string + local out = table.create(#s) + for i = 1, #s do + out[i] = HEX[string.byte(s, i)] + end + return table.concat(out) +end + +for i, c in Cases do + if not c.expect then + local scene = Usda.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files }) + if scene then + local files = {} + local out = assert(Usda.encode(scene, { files = files, name = "case_" .. i .. ".usda" })) + print(string.format("case_%d.usda\t%s", i, hex(buffer.tostring(out)))) + for name, data in files do + if not string.find(name, "%.%.") and string.sub(name, 1, 1) ~= "/" then + print(name .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data))) + end + end + end + end +end diff --git a/tools/fixtures/_usda_reference.py b/tools/fixtures/_usda_reference.py new file mode 100644 index 0000000..7da1f71 --- /dev/null +++ b/tools/fixtures/_usda_reference.py @@ -0,0 +1,404 @@ +# OpenUSD (pxr) side of tools/fixtures/usda.py, run by ctx.python(["openusd"], ) with a JSON +# request on stdin: +# {"mode": "author", "dir": d} -> writes the authored test stages into d (usda, plus a usdc and a usdz) and prints +# the file names +# {"mode": "metrics", "paths": [...]} -> prints [ metrics per file ] (see metrics() below) +# {"mode": "convert", "src": a, "dst": b} -> usdc -> usda through Sdf (as usdcat does) +# {"mode": "specs", "paths": [...]} -> the number of prim specs in each layer (parse-only checks) +import json, math, os, struct, sys, zlib +from pxr import Gf, Sdf, Usd, UsdGeom, UsdLux, UsdShade, UsdUtils, Vt + +req = json.loads(sys.stdin.read()) + + +def png(w, h, rgba): + raw = b"".join(b"\0" + bytes(rgba[(y * w) * 4:(y * w + w) * 4]) for y in range(h)) + def chunk(t, d): + return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff) + return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"") + + +def cube(stage, path, size=1.0, quads=True): + m = UsdGeom.Mesh.Define(stage, path) + s = size / 2 + pts = [(-s, -s, -s), (s, -s, -s), (s, s, -s), (-s, s, -s), (-s, -s, s), (s, -s, s), (s, s, s), (-s, s, s)] + faces = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)] + m.CreatePointsAttr([Gf.Vec3f(*p) for p in pts]) + if quads: + m.CreateFaceVertexCountsAttr([4] * 6) + m.CreateFaceVertexIndicesAttr([i for f in faces for i in f]) + else: + m.CreateFaceVertexCountsAttr([3] * 12) + m.CreateFaceVertexIndicesAttr([i for f in faces for i in (f[0], f[1], f[2], f[0], f[2], f[3])]) + m.CreateExtentAttr([Gf.Vec3f(-s, -s, -s), Gf.Vec3f(s, s, s)]) + return m + + +def author(d): + names = [] + # 1. transforms: every op kind and order + st = Usd.Stage.CreateInMemory() + UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.y) + UsdGeom.SetStageMetersPerUnit(st, 1.0) + root = UsdGeom.Xform.Define(st, "/World") + st.SetDefaultPrim(root.GetPrim()) + x = UsdGeom.Xform.Define(st, "/World/TRS") + x.AddTranslateOp().Set(Gf.Vec3d(1, 2, 3)) + x.AddRotateXYZOp().Set(Gf.Vec3f(30, 45, 60)) + x.AddScaleOp().Set(Gf.Vec3f(1, 2, 0.5)) + cube(st, "/World/TRS/Cube") + for k, order in enumerate(["XZY", "YXZ", "YZX", "ZXY", "ZYX"]): + x = UsdGeom.Xform.Define(st, "/World/R%s" % order) + x.AddTranslateOp().Set(Gf.Vec3d(k * 3, 0, 0)) + op = x.AddXformOp(getattr(UsdGeom.XformOp, "TypeRotate" + order)) + op.Set(Gf.Vec3f(10 + k, 70, -25)) + cube(st, "/World/R%s/Cube" % order, 0.5) + x = UsdGeom.Xform.Define(st, "/World/Single") + x.AddRotateYOp().Set(33.0) + x.AddRotateXOp().Set(-12.0) + x.AddScaleOp().Set(Gf.Vec3f(2, 2, 2)) + cube(st, "/World/Single/Cube") + x = UsdGeom.Xform.Define(st, "/World/Orient") + x.AddOrientOp().Set(Gf.Quatf(0.9238795, 0, 0.3826834, 0)) + x.AddTranslateOp().Set(Gf.Vec3d(0, 1, 0)) + cube(st, "/World/Orient/Cube") + x = UsdGeom.Xform.Define(st, "/World/Pivot") + x.AddTranslateOp().Set(Gf.Vec3d(5, 0, 0)) + piv = x.AddTranslateOp(opSuffix="pivot") + piv.Set(Gf.Vec3d(1, 1, 0)) + x.AddRotateZOp().Set(90.0) + x.AddTranslateOp(opSuffix="pivot", isInverseOp=True) + cube(st, "/World/Pivot/Cube") + x = UsdGeom.Xform.Define(st, "/World/Matrix") + x.AddTransformOp().Set(Gf.Matrix4d(Gf.Rotation(Gf.Vec3d(1, 1, 0), 40), Gf.Vec3d(-2, 0, 4)) * Gf.Matrix4d().SetScale(Gf.Vec3d(1.5, 1.5, 1.5))) + cube(st, "/World/Matrix/Cube") + r = UsdGeom.Xform.Define(st, "/World/Matrix/Reset") + r.SetResetXformStack(True) + r.AddTranslateOp().Set(Gf.Vec3d(0, -3, 0)) + cube(st, "/World/Matrix/Reset/Cube", 0.25) + neg = UsdGeom.Xform.Define(st, "/World/Negative") + neg.AddScaleOp().Set(Gf.Vec3f(-1, 1, 1)) + cube(st, "/World/Negative/Cube") + names.append(("xforms.usda", st)) + + # 2. primvars, interpolations, holes, orientation, n-gons + st = Usd.Stage.CreateInMemory() + UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.z) + UsdGeom.SetStageMetersPerUnit(st, 0.01) + m = UsdGeom.Mesh.Define(st, "/Grid") + st.SetDefaultPrim(m.GetPrim()) + n = 4 + pts = [Gf.Vec3f(i, j, 0.1 * i * j) for j in range(n + 1) for i in range(n + 1)] + counts, idx = [], [] + for j in range(n): + for i in range(n): + a = j * (n + 1) + i + counts.append(4) + idx += [a, a + 1, a + n + 2, a + n + 1] + # a pentagon and a triangle + pts += [Gf.Vec3f(10, 0, 0), Gf.Vec3f(11, 0, 0), Gf.Vec3f(11.5, 1, 0), Gf.Vec3f(10.5, 2, 0), Gf.Vec3f(9.5, 1, 0)] + b = (n + 1) * (n + 1) + counts += [5, 3] + idx += [b, b + 1, b + 2, b + 3, b + 4, b, b + 2, b + 3] + m.CreatePointsAttr(pts) + m.CreateFaceVertexCountsAttr(counts) + m.CreateFaceVertexIndicesAttr(idx) + m.CreateHoleIndicesAttr([5]) + pv = UsdGeom.PrimvarsAPI(m) + stp = pv.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.faceVarying) + stp.Set([Gf.Vec2f(0, 0), Gf.Vec2f(1, 0), Gf.Vec2f(1, 1), Gf.Vec2f(0, 1)]) + stp.SetIndices(Vt.IntArray([k % 4 for k in range(len(idx))])) + col = pv.CreatePrimvar("displayColor", Sdf.ValueTypeNames.Color3fArray, UsdGeom.Tokens.uniform) + col.Set([Gf.Vec3f((k % 3) / 2, (k % 5) / 4, 1 - (k % 2)) for k in range(len(counts))]) + op = pv.CreatePrimvar("displayOpacity", Sdf.ValueTypeNames.FloatArray, UsdGeom.Tokens.vertex) + op.Set([0.5 + 0.5 * (k % 2) for k in range(len(pts))]) + uv2 = pv.CreatePrimvar("uv2", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex) + uv2.Set([Gf.Vec2f(p[0] / 12, p[1] / 4) for p in pts]) + m.CreateNormalsAttr([Gf.Vec3f(0, 0, 1)] * len(pts)) + m.SetNormalsInterpolation(UsdGeom.Tokens.vertex) + m2 = cube(st, "/Grid/Left") + m2.CreateOrientationAttr(UsdGeom.Tokens.leftHanded) + UsdGeom.Xformable(m2).AddTranslateOp().Set(Gf.Vec3d(0, 0, 5)) + m3 = cube(st, "/Grid/ConstColor", 2) + UsdGeom.Xformable(m3).AddTranslateOp().Set(Gf.Vec3d(0, 6, 0)) + m3.CreateDisplayColorPrimvar(UsdGeom.Tokens.constant).Set([Gf.Vec3f(0.2, 0.4, 0.8)]) + names.append(("primvars.usda", st)) + + # 3. materials: textures, transforms, subsets, inherited bindings, interface inputs + st = Usd.Stage.CreateInMemory() + UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.y) + root = UsdGeom.Xform.Define(st, "/Root") + st.SetDefaultPrim(root.GetPrim()) + UsdGeom.Scope.Define(st, "/Root/Looks") + + def surface(path, **inputs): + mat = UsdShade.Material.Define(st, path) + sh = UsdShade.Shader.Define(st, path + "/Surface") + sh.CreateIdAttr("UsdPreviewSurface") + for k, v in inputs.items(): + if isinstance(v, tuple): + sh.CreateInput(k, Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*v)) + else: + sh.CreateInput(k, Sdf.ValueTypeNames.Float).Set(v) + mat.CreateSurfaceOutput().ConnectToSource(sh.ConnectableAPI(), "surface") + return mat, sh + + def texture(mat, sh, name, file, varname="st", wrap="repeat", transform=None, iface=False): + path = mat.GetPath().pathString + reader = UsdShade.Shader.Define(st, path + "/" + name + "_Reader") + reader.CreateIdAttr("UsdPrimvarReader_float2") + if iface: + mi = mat.CreateInput("frame:stPrimvarName", Sdf.ValueTypeNames.Token) + mi.Set(varname) + reader.CreateInput("varname", Sdf.ValueTypeNames.Token).ConnectToSource(mi) + else: + reader.CreateInput("varname", Sdf.ValueTypeNames.Token).Set(varname) + src = reader.ConnectableAPI() + if transform: + tr = UsdShade.Shader.Define(st, path + "/" + name + "_Transform") + tr.CreateIdAttr("UsdTransform2d") + tr.CreateInput("in", Sdf.ValueTypeNames.Float2).ConnectToSource(src, "result") + tr.CreateInput("rotation", Sdf.ValueTypeNames.Float).Set(transform[0]) + tr.CreateInput("scale", Sdf.ValueTypeNames.Float2).Set(Gf.Vec2f(*transform[1])) + tr.CreateInput("translation", Sdf.ValueTypeNames.Float2).Set(Gf.Vec2f(*transform[2])) + src = tr.ConnectableAPI() + t = UsdShade.Shader.Define(st, path + "/" + name) + t.CreateIdAttr("UsdUVTexture") + t.CreateInput("file", Sdf.ValueTypeNames.Asset).Set(file) + t.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(src, "result") + t.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set(wrap) + t.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("clamp") + return t.ConnectableAPI() + + red, _ = surface("/Root/Looks/Red", diffuseColor=(0.8, 0.1, 0.1), metallic=0.25, roughness=0.75) + glass, _ = surface("/Root/Looks/Glass", diffuseColor=(0.9, 0.9, 1.0), opacity=0.3, roughness=0.05, ior=1.33) + glow, _ = surface("/Root/Looks/Glow", emissiveColor=(1.0, 0.5, 0.0), opacityThreshold=0.4, opacity=0.9) + tex, tsh = surface("/Root/Looks/Textured", roughness=0.5) + c = texture(tex, tsh, "Diffuse", "./textures/checker.png", iface=True) + tsh.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(c, "rgb") + mr = texture(tex, tsh, "MetalRough", "textures/mr.png", varname="uv2", wrap="mirror", transform=(30.0, (2, 2), (0.25, 0.5))) + tsh.CreateInput("metallic", Sdf.ValueTypeNames.Float).ConnectToSource(mr, "b") + tsh.CreateInput("roughness", Sdf.ValueTypeNames.Float).ConnectToSource(mr, "g") + nrm = texture(tex, tsh, "Normal", "textures/normal.png") + tsh.CreateInput("normal", Sdf.ValueTypeNames.Normal3f).ConnectToSource(nrm, "rgb") + grp = UsdGeom.Xform.Define(st, "/Root/Group") + UsdShade.MaterialBindingAPI.Apply(grp.GetPrim()).Bind(red) + a = cube(st, "/Root/Group/Inherits") + b = cube(st, "/Root/Group/Own") + UsdGeom.Xformable(b).AddTranslateOp().Set(Gf.Vec3d(2, 0, 0)) + UsdShade.MaterialBindingAPI.Apply(b.GetPrim()).Bind(glass) + s = cube(st, "/Root/Subsets", 1.0, quads=False) + UsdGeom.Xformable(s).AddTranslateOp().Set(Gf.Vec3d(0, 3, 0)) + pv = UsdGeom.PrimvarsAPI(s) + pv.CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex).Set([Gf.Vec2f((k % 2), (k // 2) % 2) for k in range(8)]) + pv.CreatePrimvar("uv2", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.vertex).Set([Gf.Vec2f((k % 4) / 4, k / 8) for k in range(8)]) + mb = UsdShade.MaterialBindingAPI.Apply(s.GetPrim()) + mb.Bind(glow) + s1 = mb.CreateMaterialBindSubset("top", Vt.IntArray([0, 1, 2, 3])) + UsdShade.MaterialBindingAPI.Apply(s1.GetPrim()).Bind(tex) + s2 = mb.CreateMaterialBindSubset("side", Vt.IntArray([4, 5, 6])) + UsdShade.MaterialBindingAPI.Apply(s2.GetPrim()).Bind(red) + names.append(("materials.usda", st)) + + # 4. cameras and lights + st = Usd.Stage.CreateInMemory() + UsdGeom.SetStageUpAxis(st, UsdGeom.Tokens.y) + root = UsdGeom.Xform.Define(st, "/Scene") + st.SetDefaultPrim(root.GetPrim()) + cam = UsdGeom.Camera.Define(st, "/Scene/Persp") + cam.CreateFocalLengthAttr(35) + cam.CreateHorizontalApertureAttr(36) + cam.CreateVerticalApertureAttr(24) + cam.CreateClippingRangeAttr(Gf.Vec2f(0.1, 500)) + UsdGeom.Xformable(cam).AddTranslateOp().Set(Gf.Vec3d(0, 1, 10)) + o = UsdGeom.Camera.Define(st, "/Scene/Ortho") + o.CreateProjectionAttr(UsdGeom.Tokens.orthographic) + o.CreateHorizontalApertureAttr(40) + o.CreateVerticalApertureAttr(30) + UsdLux.DistantLight.Define(st, "/Scene/Sun").CreateIntensityAttr(3) + sp = UsdLux.SphereLight.Define(st, "/Scene/Bulb") + sp.CreateIntensityAttr(50) + sp.CreateColorAttr(Gf.Vec3f(1, 0.8, 0.6)) + sp.CreateExposureAttr(2) + UsdGeom.Xformable(sp).AddTranslateOp().Set(Gf.Vec3d(0, 4, 0)) + spot = UsdLux.SphereLight.Define(st, "/Scene/Spot") + sh = UsdLux.ShapingAPI.Apply(spot.GetPrim()) + sh.CreateShapingConeAngleAttr(30) + sh.CreateShapingConeSoftnessAttr(0.5) + UsdLux.RectLight.Define(st, "/Scene/Panel").CreateIntensityAttr(7) + UsdLux.DiskLight.Define(st, "/Scene/Disk") + cube(st, "/Scene/Floor", 10) + names.append(("camlights.usda", st)) + + # 5. time samples + st = Usd.Stage.CreateInMemory() + st.SetTimeCodesPerSecond(30) + st.SetStartTimeCode(0) + st.SetEndTimeCode(60) + root = UsdGeom.Xform.Define(st, "/Anim") + st.SetDefaultPrim(root.GetPrim()) + x = UsdGeom.Xform.Define(st, "/Anim/Mover") + t = x.AddTranslateOp() + for k, v in ((0, (0, 0, 0)), (30, (4, 1, 0)), (60, (4, 1, -6))): + t.Set(Gf.Vec3d(*v), k) + r = x.AddRotateXYZOp() + for k, v in ((0, (0, 0, 0)), (20, (0, 90, 0)), (45, (30, 180, 10))): + r.Set(Gf.Vec3f(*v), k) + s = x.AddScaleOp() + s.Set(Gf.Vec3f(1, 1, 1)) + cube(st, "/Anim/Mover/Box") + y = UsdGeom.Xform.Define(st, "/Anim/Mover/Child") + q = y.AddOrientOp() + q.Set(Gf.Quatf(1, 0, 0, 0), 0) + q.Set(Gf.Quatf(0.7071068, 0.7071068, 0, 0), 60) + y.AddTranslateOp().Set(Gf.Vec3d(0, 2, 0)) + cube(st, "/Anim/Mover/Child/Box", 0.5) + names.append(("anim.usda", st)) + + out = [] + for name, st in names: + st.GetRootLayer().Export(os.path.join(d, name)) + out.append(name) + os.makedirs(os.path.join(d, "textures"), exist_ok=True) + checker = [] + for yy in range(8): + for xx in range(8): + v = 255 if (xx + yy) % 2 else 40 + checker += [v, v, v, 255] + for f, data in (("checker.png", png(8, 8, checker)), ("mr.png", png(2, 2, [0, 128, 255, 255] * 4)), ("normal.png", png(2, 2, [128, 128, 255, 255] * 4))): + with open(os.path.join(d, "textures", f), "wb") as fh: + fh.write(data) + # a usdc (UNSUPPORTED) and a usdz package of the materials stage + Sdf.Layer.FindOrOpen(os.path.join(d, "xforms.usda")).Export(os.path.join(d, "xforms.usdc")) + out.append("xforms.usdc") + cwd = os.getcwd() + os.chdir(d) + UsdUtils.CreateNewUsdzPackage(Sdf.AssetPath("materials.usda"), "materials.usdz") + os.chdir(cwd) + out.append("materials.usdz") + return out + + +def mat16(m): + return [float(m[i][j]) for i in range(4) for j in range(4)] + + +def metrics(path): + stage = Usd.Stage.Open(path) + if stage is None: + return {"failed": True} + res = { + "upAxis": str(UsdGeom.GetStageUpAxis(stage)), + "metersPerUnit": float(UsdGeom.GetStageMetersPerUnit(stage)) if UsdGeom.StageHasAuthoredMetersPerUnit(stage) else -1.0, + "tcps": float(stage.GetTimeCodesPerSecond()), + "meshes": [], "xforms": [], "materials": [], "cameras": [], "lights": [], "anim": [], + } + t0 = Usd.TimeCode.EarliestTime() + cache = UsdGeom.XformCache(t0) + for prim in stage.Traverse(): + if not prim.IsA(UsdGeom.Xformable): + continue + path_s = prim.GetPath().pathString + world = cache.GetLocalToWorldTransform(prim) + res["xforms"].append({"path": path_s, "type": str(prim.GetTypeName()), "world": mat16(world)}) + x = UsdGeom.Xformable(prim) + times = x.GetTimeSamples() + if len(times) > 1: + samples = [] + for t in times: + samples.append({"time": float(t), "world": mat16(x.ComputeLocalToWorldTransform(t))}) + res["anim"].append({"path": path_s, "samples": samples}) + if prim.IsA(UsdGeom.Mesh): + m = UsdGeom.Mesh(prim) + pts = m.GetPointsAttr().Get(t0) or [] + counts = m.GetFaceVertexCountsAttr().Get(t0) or [] + idx = m.GetFaceVertexIndicesAttr().Get(t0) or [] + holes = set(m.GetHoleIndicesAttr().Get(t0) or []) + wp = [world.Transform(Gf.Vec3d(*p)) for p in pts] + tris, area, at = 0, 0.0, 0 + lo, hi = [math.inf] * 3, [-math.inf] * 3 + for f, c in enumerate(counts): + corners = list(idx[at:at + c]) + at += c + if c < 3 or f in holes: + continue + for k in range(1, c - 1): + a, b, cc = wp[corners[0]], wp[corners[k]], wp[corners[k + 1]] + area += 0.5 * Gf.Cross(b - a, cc - a).GetLength() + tris += 1 + for v in corners: + for j in range(3): + lo[j] = min(lo[j], wp[v][j]) + hi[j] = max(hi[j], wp[v][j]) + mat, _ = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() + subsets = UsdShade.MaterialBindingAPI(prim).GetMaterialBindSubsets() + res["meshes"].append({ + "path": path_s, "triangles": tris, "area": area, "min": lo if tris else [], "max": hi if tris else [], + "material": mat.GetPath().pathString if mat else "", "subsets": len(subsets), + "subsetMaterials": sorted( + (UsdShade.MaterialBindingAPI(sub.GetPrim()).ComputeBoundMaterial()[0].GetPath().pathString if UsdShade.MaterialBindingAPI(sub.GetPrim()).ComputeBoundMaterial()[0] else "") for sub in subsets), + }) + if prim.IsA(UsdGeom.Camera): + c = UsdGeom.Camera(prim) + cr = c.GetClippingRangeAttr().Get(t0) + res["cameras"].append({ + "path": path_s, "projection": str(c.GetProjectionAttr().Get(t0)), "focal": float(c.GetFocalLengthAttr().Get(t0)), + "hap": float(c.GetHorizontalApertureAttr().Get(t0)), "vap": float(c.GetVerticalApertureAttr().Get(t0)), + "near": float(cr[0]), "far": float(cr[1]), + }) + for lt in ("DistantLight", "SphereLight", "RectLight", "DiskLight"): + cls = getattr(UsdLux, lt) + if prim.IsA(cls): + l = cls(prim) + col = l.GetColorAttr().Get(t0) + cone = prim.GetAttribute("inputs:shaping:cone:angle") + res["lights"].append({ + "path": path_s, "type": lt, "intensity": float(l.GetIntensityAttr().Get(t0)) * 2 ** float(l.GetExposureAttr().Get(t0)), + "color": [float(v) for v in col], "cone": float(cone.Get(t0)) if cone and cone.HasAuthoredValue() else -1.0, + }) + for prim in stage.Traverse(): + if not prim.IsA(UsdShade.Material): + continue + mat = UsdShade.Material(prim) + surf = mat.ComputeSurfaceSource() + sh = surf[0] if surf else None + if not sh or sh.GetIdAttr().Get() != "UsdPreviewSurface": + continue + d = {"path": prim.GetPath().pathString, "textures": {}} + for name in ("diffuseColor", "emissiveColor", "metallic", "roughness", "opacity", "opacityThreshold", "ior", "normal", "occlusion"): + inp = sh.GetInput(name) + if not inp: + continue + srcs = inp.GetConnectedSources()[0] if inp.HasConnectedSource() else [] + if srcs: + src = UsdShade.Shader(srcs[0].source.GetPrim()) + f = src.GetInput("file") + if f: + d["textures"][name] = {"file": f.Get().path, "output": str(srcs[0].sourceName)} + else: + v = inp.Get() + if v is not None: + d[name] = [float(x) for x in v] if hasattr(v, "__len__") else float(v) + res["materials"].append(d) + return res + + +mode = req["mode"] +if mode == "author": + print(json.dumps(author(req["dir"]))) +elif mode == "metrics": + print(json.dumps([metrics(p) for p in req["paths"]])) +elif mode == "convert": + Sdf.Layer.FindOrOpen(req["src"]).Export(req["dst"]) + print("[]") +elif mode == "specs": + out = [] + for p in req["paths"]: + layer = Sdf.Layer.FindOrOpen(p) + n = [0] + def visit(path): + if path.IsPrimPath(): + n[0] += 1 + layer.Traverse(Sdf.Path.absoluteRootPath, visit) + out.append(n[0]) + print(json.dumps(out)) diff --git a/tools/fixtures/usda.py b/tools/fixtures/usda.py new file mode 100644 index 0000000..9a9822a --- /dev/null +++ b/tools/fixtures/usda.py @@ -0,0 +1,264 @@ +# USDA fixtures (tools/fixtures.py): stages authored through OpenUSD's own API (pxr, nixpkgs python3Packages.openusd: +# every xform op kind / order, pivots, !resetXformStack!, primvar interpolations + indices, holes, leftHanded, n-gons, +# UsdPreviewSurface + UsdUVTexture / UsdTransform2d / interface inputs, GeomSubsets, inherited bindings, cameras, +# UsdLux lights, time samples; plus a .usdc and a .usdz), assimp's USD test models (models-nonbsd/USD: the .usda files +# and the .usdc ones converted to .usda by Sdf, read from the nixpkgs assimp source, not committed), Blender 5 USD +# exports of glTF sample models (when blender is on PATH), a hand-written file exercising the text grammar, and the +# OpenUSD schema layers (parse-only). Reference values come from pxr (Usd.Stage: world transforms, triangles / area / +# bounds per mesh, bound materials, cameras, lights, xform time samples). +# tests/gen/usda_cases.luau { name, data, files = { uri -> bytes }, ref = pxr metrics | nil, expect = "UNSUPPORTED"? } +# tests/gen/usda_specs.luau { name, data, prims = number of prim specs (Sdf) } +# tests/gen/usda_xcheck.luau our writer's .usda for every case (tools/fixtures/_usda_encode.luau) read back by pxr: +# { name, case, ref } +import json, os, shutil, subprocess, tempfile + +INPUTS = ["src/Formats/model/usda", "tools/fixtures/_usda_reference.py", "tools/fixtures/_usda_encode.luau", + "tools/fixtures/_model_ref.py", "tests/fixtures/gltf"] + +# the text grammar: comments, metadata of every kind, list ops, variants, class / over, dictionaries, strings, +# relative paths, typed values that the Scene ignores +HANDWRITTEN = r'''#usda 1.0 +( + """A layer written by hand: every construct of the text format the reader has to get through.""" + customLayerData = { + string creator = "formats-luau tests" + dictionary nested = { + int[] numbers = [1, 2, 3] + double "quoted key" = 1.5 + } + } + defaultPrim = "Hand" + metersPerUnit = 0.0254 + upAxis = "Z" + timeCodesPerSecond = 24 +) + +# a class (abstract: not a node) and an over of nothing +class "_Template" +{ + float3 xformOp:translate = (100, 100, 100) +} + +def Xform "Hand" ( + kind = "assembly" + doc = 'single quoted doc' + variants = { + string look = "big" + } + prepend variantSets = "look" + customData = { bool flag = true } +) +{ + custom string notes = """multi +line""" // trailing comment + custom asset path = @@@weird@name.png@@@ + custom double[] empty = [] + custom float big = inf + custom float small = -inf + custom token[] tokens = ["a", "b"] + custom rel others = [, <../Hand>] + reorder nameChildren = ["Big", "Tri"] + + def Mesh "Tri" ( active = true ) + { + point3f[] points = [(0,0,0),(1,0,0),(0,1,0)] ; int[] faceVertexCounts = [3] + int[] faceVertexIndices = [0, 1, 2] + double3 xformOp:translate = (1, 0, 0) + uniform token[] xformOpOrder = ["xformOp:translate"] + rel material:binding = <../Looks/Blue> + } + + variantSet "look" = { + "big" (doc = "selected") { + def Mesh "Big" + { + float3 xformOp:scale = (3, 3, 3) + uniform token[] xformOpOrder = ["xformOp:scale"] + point3f[] points = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)] + int[] faceVertexCounts = [4] + int[] faceVertexIndices = [0, 1, 2, 3] + color3f[] primvars:displayColor = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (1, 1, 1)] ( + interpolation = "vertex" + ) + } + } + "small" { + def Mesh "Small" + { + point3f[] points = [(0, 0, 0), (1, 0, 0), (0, 1, 0)] + int[] faceVertexCounts = [3] + int[] faceVertexIndices = [0, 1, 2] + } + } + } + + def Scope "Looks" + { + def Material "Blue" + { + color3f inputs:tint = (0.1, 0.2, 0.9) + token outputs:surface.connect = + + def Shader "Surface" + { + uniform token info:id = "UsdPreviewSurface" + color3f inputs:diffuseColor.connect = + float inputs:roughness = 0.25 + token outputs:surface + } + } + } + + def "Untyped" + { + def Xform "Inner" ( + prepend references = @missing.usda@ + ) + { + matrix4d xformOp:transform.timeSamples = { + 0: ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1) ), + 10: ( (1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 5, 1) ), + } + uniform token[] xformOpOrder = ["xformOp:transform"] + + def Mesh "Quad" + { + point3f[] points = [(0, 0, 0), (2, 0, 0), (2, 2, 0), (0, 2, 0)] + int[] faceVertexCounts = [4] + int[] faceVertexIndices = [0, 1, 2, 3] + } + } + } +} + +over "Elsewhere" +{ + def Xform "Undefined" + { + double3 xformOp:translate = (0, 0, -1) + uniform token[] xformOpOrder = ["xformOp:translate"] + } +} +''' + +GLTF_MODELS = [("Box", "glTF", "Box.gltf"), ("BoxTextured", "glTF", "BoxTextured.gltf"), ("AnimatedTriangle", "glTF", "AnimatedTriangle.gltf"), + ("Cameras", "glTF", "Cameras.gltf"), ("MultiUVTest", "glTF-Binary", None), ("BoxVertexColors", "glTF-Binary", None)] + +BLENDER = r''' +import bpy, sys +args = sys.argv[sys.argv.index("--") + 1:] +bpy.ops.wm.read_factory_settings(use_empty=True) +bpy.ops.import_scene.gltf(filepath=args[0]) +bpy.ops.wm.usd_export(filepath=args[1], export_materials=True, export_animation=True, relative_paths=True) +''' + + +def pxr(ctx, req): + code = ctx.read("tools/fixtures/_usda_reference.py").decode() + try: + return json.loads(ctx.python(["openusd"], code, input=json.dumps(req).encode())) + except subprocess.CalledProcessError as e: + raise RuntimeError("pxr (%s) failed:\n%s" % (req["mode"], e.stderr.decode(errors="replace")[-3000:])) from None + + +def files_under(d, skip): + out = {} + for root, _, fs in os.walk(d): + for f in fs: + p = os.path.join(root, f) + rel = os.path.relpath(p, d).replace(os.sep, "/") + if rel != skip and not rel.endswith((".usda", ".usdc", ".usdz", ".usd", ".py")): + out[rel] = open(p, "rb").read() + return out + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="formats-usda-") + cases = [] # name, path, files, expect? + # 1. stages authored through pxr + adir = os.path.join(tmp, "authored") + os.makedirs(adir) + for name in pxr(ctx, {"mode": "author", "dir": adir}): + p = os.path.join(adir, name) + c = {"name": "pxr/" + name, "path": p, "files": files_under(adir, name)} + if name.endswith(".usdc"): + c["expect"] = "UNSUPPORTED" + if name.endswith(".usdz"): + c["files"] = {} + c["like"] = "pxr/materials.usda" + cases.append(c) + # 2. hand-written grammar test + hand = os.path.join(tmp, "hand.usda") + with open(hand, "w") as f: + f.write(HANDWRITTEN) + cases.append({"name": "hand.usda", "path": hand, "files": {}}) + # 3. assimp's USD test models (untrusted data: read only, from the nix store) + src = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True).stdout.decode().strip() + usd = os.path.join(src, "test", "models-nonbsd", "USD") + conv = os.path.join(tmp, "assimp") + os.makedirs(conv) + for f in sorted(os.listdir(os.path.join(usd, "usda"))): + if f.endswith(".usda"): + cases.append({"name": "assimp/" + f, "path": os.path.join(usd, "usda", f), "files": files_under(os.path.join(usd, "usda"), f)}) + for d, f in [(os.path.join(usd, "usdc"), x) for x in sorted(os.listdir(os.path.join(usd, "usdc"))) if x.endswith(".usdc")] + [(os.path.join(src, "test", "models", "USD"), "MotionCaptureROM.usdc")]: + dst = os.path.join(conv, f[:-5] + ".usda") + pxr(ctx, {"mode": "convert", "src": os.path.join(d, f), "dst": dst}) + cases.append({"name": "assimp/" + f + " (usdcat)", "path": dst, "files": files_under(d, f)}) + # 4. Blender USD exports of glTF samples + if shutil.which("blender"): + bdir = os.path.join(tmp, "blender") + os.makedirs(bdir) + script = os.path.join(tmp, "blender_export.py") + with open(script, "w") as f: + f.write(BLENDER) + groot = os.path.join(ctx.root, "tests", "fixtures", "gltf") + for model, variant, main in GLTF_MODELS: + d = os.path.join(groot, model, variant) + if not os.path.isdir(d): + continue + main = main or [x for x in sorted(os.listdir(d)) if x.endswith((".gltf", ".glb"))][0] + out = os.path.join(bdir, model, model + ".usda") + os.makedirs(os.path.dirname(out), exist_ok=True) + r = subprocess.run(["blender", "-b", "--factory-startup", "--python", script, "--", os.path.join(d, main), out], capture_output=True) + if r.returncode == 0 and os.path.exists(out): + cases.append({"name": "blender/" + model, "path": out, "files": files_under(os.path.dirname(out), model + ".usda")}) + refs = pxr(ctx, {"mode": "metrics", "paths": [c["path"] for c in cases if "expect" not in c]}) + k = 0 + for c in cases: + if "expect" not in c: + c["ref"] = refs[k] + k += 1 + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("usda_cases", cases) + + # 5. parse-only: OpenUSD's schema layers + usdpkg = ctx.python(["openusd"], "import pxr, os; print(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(pxr.__file__)))))))").decode().strip() + specs = [] + for root, _, fs in os.walk(usdpkg): + for f in fs: + if f.endswith(".usda") and ("usdGeom" in root or "usdShade" in root or "usdLux" in root or "usdSkel" in root): + specs.append(os.path.join(root, f)) + specs = sorted(specs)[:8] + counts = pxr(ctx, {"mode": "specs", "paths": specs}) + ctx.emit("usda_specs", [{"name": os.path.relpath(p, usdpkg), "data": open(p, "rb").read(), "prims": n} for p, n in zip(specs, counts)]) + + # 6. pxr reads our writer's output + exe = shutil.which("luau") + cmd = [exe, "tools/fixtures/_usda_encode.luau"] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_usda_encode.luau"] + res = subprocess.run(cmd, cwd=ctx.root, capture_output=True, check=True) + xdir = os.path.join(tmp, "ours") + os.makedirs(xdir) + mains = [] + for line in res.stdout.decode().split("\n"): + if "\t" in line: + name, hexdata = line.split("\t", 1) + p = os.path.join(xdir, name) + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p, "wb") as f: + f.write(bytes.fromhex(hexdata.strip())) + if name.endswith(".usda") and "/" not in name: + mains.append(name) + xrefs = pxr(ctx, {"mode": "metrics", "paths": [os.path.join(xdir, n) for n in mains]}) + ctx.emit("usda_xcheck", [{"name": n, "case": int(n[5:].split(".")[0]), "ref": r} for n, r in zip(mains, xrefs)]) + shutil.rmtree(tmp, ignore_errors=True) From d4affd565eec621c0044bd8846333807092ba56d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:46:25 -0500 Subject: [PATCH 5/8] ws-3d2/fbx: model/fbx (binary 7.x + ASCII read, binary 7.4 / 7.5 + ASCII write): node tree, Objects / Connections -> Scene (full transform model, layer elements, materials, textures, skins, blend shapes, animation stacks, cameras, lights); tests against assimp + Blender, round trips, fuzz; bench lines --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/model/fbx/Ascii.luau | 274 +++++ src/Formats/model/fbx/Binary.luau | 461 +++++++++ src/Formats/model/fbx/Read.luau | 1383 ++++++++++++++++++++++++++ src/Formats/model/fbx/Write.luau | 996 +++++++++++++++++++ src/Formats/model/fbx/Xform.luau | 200 ++++ src/Formats/model/fbx/init.luau | 177 ++++ tests/model/fbx.luau | 542 ++++++++++ tools/bench.luau | 15 + tools/fixtures/_fbx_blender.py | 94 ++ tools/fixtures/_fbx_blender_stats.py | 31 + tools/fixtures/_fbx_encode.luau | 38 + tools/fixtures/fbx.py | 179 ++++ 14 files changed, 4403 insertions(+) create mode 100644 src/Formats/model/fbx/Ascii.luau create mode 100644 src/Formats/model/fbx/Binary.luau create mode 100644 src/Formats/model/fbx/Read.luau create mode 100644 src/Formats/model/fbx/Write.luau create mode 100644 src/Formats/model/fbx/Xform.luau create mode 100644 src/Formats/model/fbx/init.luau create mode 100644 tests/model/fbx.luau create mode 100644 tools/fixtures/_fbx_blender.py create mode 100644 tools/fixtures/_fbx_blender_stats.py create mode 100644 tools/fixtures/_fbx_encode.luau create mode 100644 tools/fixtures/fbx.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 40e275f..b22a2cb 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -20,6 +20,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | | audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | +| model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d514aa9..a0eb883 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -194,6 +194,18 @@ local list: { Entry } = { return require("@formats/audio/wav") end, }, + { + name = "fbx", + category = "model", + path = "model/fbx", + extensions = { "fbx" }, + mime = { "application/vnd.autodesk.fbx", "model/fbx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "core/Base64" }, + caps = { decode = true, encode = true, binary = true, ascii = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true }, + load = function() + return require("@formats/model/fbx") + end, + }, { name = "gltf", category = "model", diff --git a/src/Formats/model/fbx/Ascii.luau b/src/Formats/model/fbx/Ascii.luau new file mode 100644 index 0000000..318b1b7 --- /dev/null +++ b/src/Formats/model/fbx/Ascii.luau @@ -0,0 +1,274 @@ +--!strict +-- model/fbx/Ascii: the ASCII FBX node tree reader and writer (7.x: "Name: value, value, ... { children }", ';' +-- comments, "*N { a: ... }" arrays, " in strings). Produces the same Node / Array values as model/fbx/Binary +-- (arrays as f64 buffers; integers longer than 15 digits stay strings so ids are exact). Never throws. +local Base64 = require("@formats/core/Base64") + +local Ascii = {} + +type Node = { name: string, props: { any }, children: { Node } } + +local sbyte, sfind, ssub = string.byte, string.find, string.sub +local MAX_DEPTH = 128 + +local function isNameStart(c: number): boolean + return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 +end + +-- parse(text) -> root node (children = the top-level nodes), version | nil, message, offset +function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, number?) + local maxBytes = opts and opts.maxBytes or 2 ^ 30 + local n = #text + local i = 1 + local total = 0 + + local function skip() + while i <= n do + local c = sbyte(text, i) + if c == 59 then -- ; comment + local e = sfind(text, "\n", i, true) + i = if e then e + 1 else n + 1 + elseif c == 32 or c == 9 or c == 10 or c == 13 then + i += 1 + else + return + end + end + end + + -- at i: a name followed by ':'? -> name, the index after ':' + local function nameAt(): (string?, number) + local c = sbyte(text, i) + if not c or not isNameStart(c) then + return nil, i + end + local s, e = sfind(text, "^[%w_|%-]+", i) + if not s then + return nil, i + end + local j = (e :: number) + 1 + while j <= n do + local d = sbyte(text, j) + if d == 32 or d == 9 then + j += 1 + else + break + end + end + if sbyte(text, j) == 58 then + return ssub(text, i, e :: number), j + 1 + end + return nil, i + end + + -- the values of one node (after the ':'), up to a new name, '{' or '}' + local function values(): ({ any }?, string?) + local props = {} + while true do + skip() + if i > n then + return props + end + local c = sbyte(text, i) + if c == 44 then -- , + i += 1 + elseif c == 123 or c == 125 then + return props + elseif c == 34 then -- " + local e = sfind(text, "\"", i + 1, true) + if not e then + return nil, "unterminated string" + end + local s = ssub(text, i + 1, e - 1) + if sfind(s, "&", 1, true) then + s = string.gsub(s, """, "\"") + end + table.insert(props, s) + i = e + 1 + elseif c == 42 then -- *N + local s, e = sfind(text, "^%*%d+", i) + if not s then + return nil, "bad array length" + end + table.insert(props, { star = tonumber(ssub(text, i + 1, e :: number)) }) + i = (e :: number) + 1 + elseif (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then + local s, e = sfind(text, "^[-+%deE.]+", i) + local tok = ssub(text, i, e :: number) + local v = tonumber(tok) + if v == nil then + -- "1.#INF", "-1.#IND", "nan": special floats + local s2, e2 = sfind(text, "^[-+%w.#]+", i) + tok = ssub(text, i, e2 :: number) + local low = string.lower(tok) + if sfind(low, "inf", 1, true) then + v = if sbyte(tok, 1) == 45 then -math.huge else math.huge + else + v = 0 / 0 + end + e = e2 + local _ = s2 + elseif #tok > 15 and not sfind(tok, "[.eE]") then + v = (if sbyte(tok, 1) == 45 then "L-" else "L") .. string.gsub(tok, "^[-+]", "") :: any + end + local _ = s + table.insert(props, v) + i = (e :: number) + 1 + else + local nm = nameAt() + if nm then + return props + end + local s, e = sfind(text, "^[%w_]+", i) + if not s then + return nil, string.format("unexpected character %q", ssub(text, i, i)) + end + table.insert(props, ssub(text, i, e :: number)) + i = (e :: number) + 1 + end + end + end + + local function nodes(depth: number, into: { Node }): string? + while true do + skip() + if i > n then + return if depth > 0 then "unterminated {" else nil + end + if sbyte(text, i) == 125 then + if depth == 0 then + return "unbalanced }" + end + i += 1 + return nil + end + local name, j = nameAt() + if not name then + return string.format("expected a node name at %q", ssub(text, i, i + 10)) + end + i = j + local props, err = values() + if not props then + return err + end + local node: Node = { name = name, props = props, children = {} } + skip() + if sbyte(text, i) == 123 then + if depth >= MAX_DEPTH then + return "nodes nested too deep" + end + i += 1 + local e = nodes(depth + 1, node.children) + if e then + return e + end + end + -- "*N { a: v, v, ... }" -> an Array + local p1 = props[1] + if #props == 1 and type(p1) == "table" and p1.star then + local a = node.children[1] + local count = if a and a.name == "a" then #a.props else 0 + total += count * 8 + if total > maxBytes then + return "limit:arrays over " .. maxBytes .. " bytes" + end + local data = buffer.create(count * 8) + for k = 1, count do + local v = (a :: Node).props[k] + buffer.writef64(data, (k - 1) * 8, if type(v) == "number" then v else (tonumber(v) or 0)) + end + node.props = { { array = true, type = "d", count = count, data = data } } + node.children = {} + end + table.insert(into, node) + end + end + + local root: Node = { name = "", props = {}, children = {} } + local err = nodes(0, root.children) + if err then + return nil, err, i - 1 + end + local version = nil + for _, c in root.children do + if c.name == "FBXHeaderExtension" then + for _, d in c.children do + if d.name == "FBXVersion" then + version = d.props[1] + end + end + end + end + return root, version, nil +end + +-- ------------------------------------------------------------------------------------------------ writer +local function fmt(v: number): string + if v == math.floor(v) and math.abs(v) < 1e15 then + return string.format("%d", v) + end + if v ~= v then + return "0" + end + return string.format("%.17g", v) +end + +-- write(root) -> string: the ASCII form of a tree (the same node shapes Binary.write takes) +function Ascii.write(root: any, version: number?): string + local out = { string.format("; FBX %d.%d.0 project file\n; Created by formats-luau\n\n", (version or 7400) // 1000, (version or 7400) % 1000 // 100) } + local function node(nd: any, indent: string) + local parts = {} + local arr = nil + for _, v in nd.props do + local tv = type(v) + if tv == "number" then + table.insert(parts, fmt(v)) + elseif tv == "boolean" then + table.insert(parts, if v then "T" else "F") + elseif tv == "string" then + if string.sub(v, 1, 1) == "L" and string.find(v, "^L%-?%d+$") then + table.insert(parts, string.sub(v, 2)) + else + local nm, cls = string.match(v, "^(.-)%z\1(.*)$") + local sv = if nm then cls .. "::" .. nm else v + table.insert(parts, "\"" .. string.gsub(sv, "\"", """) .. "\"") + end + elseif tv == "table" and v.array then + arr = v + elseif tv == "buffer" then + -- raw bytes (Video Content): base64, split into lines as the FBX SDK writes them + local b64 = Base64.encode(v) + local chunks = {} + for k = 1, #b64, 2048 do + table.insert(chunks, "\"" .. string.sub(b64, k, k + 2047) .. "\"") + end + table.insert(parts, if #chunks > 0 then table.concat(chunks, ",\n") else "\"\"") + end + end + if arr then + local vals = table.create(arr.count) + for k = 0, arr.count - 1 do + vals[k + 1] = fmt(buffer.readf64(arr.data, k * 8)) + end + table.insert(out, string.format("%s%s: *%d {\n%s\ta: %s\n%s}\n", indent, nd.name, arr.count, indent, table.concat(vals, ","), indent)) + return + end + table.insert(out, indent .. nd.name .. ": " .. table.concat(parts, ", ")) + local ch = nd.children + if ch and #ch > 0 then + table.insert(out, " {\n") + for _, c in ch do + node(c, indent .. "\t") + end + table.insert(out, indent .. "}\n") + else + table.insert(out, "\n") + end + end + for _, c in root.children do + node(c, "") + end + return table.concat(out) +end + +return Ascii diff --git a/src/Formats/model/fbx/Binary.luau b/src/Formats/model/fbx/Binary.luau new file mode 100644 index 0000000..9ae5683 --- /dev/null +++ b/src/Formats/model/fbx/Binary.luau @@ -0,0 +1,461 @@ +--!strict +--!native +-- model/fbx/Binary: the binary FBX node tree reader and writer (versions 7.x: 32-bit node records before 7500, 64-bit +-- from 7500). From the format as documented by Blender's io_scene_fbx (encode_bin.py / parse_fbx.py) and assimp's +-- FBXBinaryTokenizer. Arrays (f, d, l, i, b) are inflated with codecs/Deflate when compressed and kept as Tree.Array +-- values (every element as an f64; 64-bit integers past 2^53 lose precision there); scalar L values past 2^53 become +-- the string "L" so ids stay exact. Never throws: errors are returned (nil, message, offset). +local Deflate = require("@formats/codecs/Deflate") + +local Binary = {} + +export type Node = { name: string, props: { any }, children: { Node } } +export type Array = { array: true, type: string, count: number, data: buffer } + +local MAGIC = "Kaydara FBX Binary \0" +Binary.MAGIC = MAGIC +local FOOT_ID = "\250\188\171\9\208\200\212\102\177\118\251\131\28\247\38\126" +local FOOT_MAGIC = "\248\90\140\106\222\245\217\126\236\233\12\227\117\143\41\11" +local MAX_DEPTH = 128 + +local readu8, readu32, readi32, readf32, readf64, readi16 = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64, buffer.readi16 +local writef64 = buffer.writef64 + +-- a signed 64-bit integer at p: a number when exact (|v| < 2^53), else "L<16 hex digits>" +local function i64(b: buffer, p: number, asString: boolean): any + local lo, hi = readu32(b, p), readu32(b, p + 4) + if hi >= 0x80000000 then + local v = (hi - 4294967296) * 4294967296 + lo + if v >= -9007199254740991 or not asString then + return v + end + else + if hi < 0x200000 or not asString then + return hi * 4294967296 + lo + end + end + return string.format("L%08x%08x", hi, lo) +end +Binary.i64 = i64 + +local ELEM = { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 } + +-- the elements of a raw array (n elements of type t at p) as f64s +local function toF64(t: string, src: buffer, p: number, n: number): buffer + local out = buffer.create(n * 8) + if t == "d" then + buffer.copy(out, 0, src, p, n * 8) + elseif t == "f" then + for k = 0, n - 1 do + writef64(out, k * 8, readf32(src, p + k * 4)) + end + elseif t == "i" then + for k = 0, n - 1 do + writef64(out, k * 8, readi32(src, p + k * 4)) + end + elseif t == "l" then + for k = 0, n - 1 do + local lo, hi = readu32(src, p + k * 8), readu32(src, p + k * 8 + 4) + writef64(out, k * 8, if hi >= 0x80000000 then (hi - 4294967296) * 4294967296 + lo else hi * 4294967296 + lo) + end + else + for k = 0, n - 1 do + writef64(out, k * 8, readu8(src, p + k)) + end + end + return out +end + +-- parse(buf, base, limit, opts?) -> root node (name "", children = the top-level nodes), version | nil, message, offset +function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: number? }?): (Node?, any, number?) + local maxBytes = opts and opts.maxBytes or 2 ^ 30 + if limit - base < 27 or buffer.readstring(b, base, 21) ~= MAGIC then + return nil, "not a binary FBX", base + end + local version = readu32(b, base + 23) + if version < 7000 or version >= 10000 then + return nil, "unsupported:FBX version " .. version, base + 23 + end + local wide = version >= 7500 + local head = if wide then 25 else 13 + local total = 0 + + local function props(p: number, n: number, stop: number): ({ any }?, any) + local out = table.create(math.min(n, 64)) + for k = 1, n do + if p >= stop then + return nil, "property list runs past its record" + end + local c = readu8(b, p) + p += 1 + local v: any + if c == 89 then -- Y + if p + 2 > stop then return nil, "truncated property" end + v = readi16(b, p) + p += 2 + elseif c == 67 then -- C + if p + 1 > stop then return nil, "truncated property" end + v = readu8(b, p) ~= 0 + p += 1 + elseif c == 73 then -- I + if p + 4 > stop then return nil, "truncated property" end + v = readi32(b, p) + p += 4 + elseif c == 70 then -- F + if p + 4 > stop then return nil, "truncated property" end + v = readf32(b, p) + p += 4 + elseif c == 68 then -- D + if p + 8 > stop then return nil, "truncated property" end + v = readf64(b, p) + p += 8 + elseif c == 76 then -- L + if p + 8 > stop then return nil, "truncated property" end + v = i64(b, p, true) + p += 8 + elseif c == 83 or c == 82 then -- S, R + if p + 4 > stop then return nil, "truncated property" end + local len = readu32(b, p) + p += 4 + if len > stop - p then return nil, "string runs past its record" end + if c == 83 then + v = buffer.readstring(b, p, len) + else + local raw = buffer.create(len) + buffer.copy(raw, 0, b, p, len) + v = raw + end + p += len + elseif c == 102 or c == 100 or c == 108 or c == 105 or c == 98 or c == 99 then -- f d l i b c + if p + 12 > stop then return nil, "truncated array header" end + local count, enc, clen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8) + p += 12 + local t = string.char(c) + local es = ELEM[t] + if clen > stop - p then return nil, "array runs past its record" end + total += count * 8 + if total > maxBytes then return nil, "limit:arrays over " .. maxBytes .. " bytes" end + local data: buffer + if enc == 0 then + if clen < count * es then return nil, "raw array shorter than its count" end + data = toF64(t, b, p, count) + elseif enc == 1 then + local raw, err = Deflate.zlib(b, p, clen, count * es) + if not raw then + return nil, "array: " .. tostring(if type(err) == "table" then err.message else err) + end + data = toF64(t, raw, 0, count) + else + return nil, "unknown array encoding " .. enc + end + p += clen + v = { array = true, type = t, count = count, data = data } + else + return nil, string.format("unknown property type 0x%02x", c) + end + out[k] = v + end + return out, p + end + + -- one node record at p: node | false (the null record), next offset | nil, message, offset + local function node(p: number, stop: number, depth: number): (any, any, number?) + if p + head > stop then + return nil, "truncated node record", p + end + local endOff, nprops, plen, nlen + if wide then + endOff = readu32(b, p) + readu32(b, p + 4) * 4294967296 + nprops = readu32(b, p + 8) + readu32(b, p + 12) * 4294967296 + plen = readu32(b, p + 16) + readu32(b, p + 20) * 4294967296 + nlen = readu8(b, p + 24) + else + endOff, nprops, plen, nlen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8), readu8(b, p + 12) + end + if endOff == 0 then + return false, p + head + end + local e = base + endOff + if e > stop or e < p + head + nlen + plen then + return nil, "node end offset out of range", p + end + if nprops > plen then + return nil, "more properties than bytes", p + end + local q = p + head + local name = buffer.readstring(b, q, nlen) + q += nlen + local pl, nq = props(q, nprops, q + plen) + if not pl then + return nil, nq, q + end + q += plen + local children: { Node } = {} + if q < e then + if depth >= MAX_DEPTH then + return nil, "nodes nested too deep", p + end + while q < e do + local child, nx, off = node(q, e, depth + 1) + if child == nil then + return nil, nx, off + end + q = nx + if child == false then + break + end + table.insert(children, child) + end + end + return { name = name, props = pl, children = children }, e + end + + local root: Node = { name = "", props = {}, children = {} } + local p = base + 27 + while p < limit do + local n, nx, off = node(p, limit, 0) + if n == nil then + if #root.children > 0 and p + head > limit then + break -- a file cut right after its last node: keep what was read + end + return nil, nx, off + end + if n == false then + break + end + table.insert(root.children, n) + p = nx + end + return root, version, nil +end + +-- ------------------------------------------------------------------------------------------------ writer +-- write(root, version?) -> buffer: the children of root as a binary FBX file (default version 7400, the 32-bit +-- record layout; 7500+ writes 64-bit records). Values: numbers are written as D unless the node gives a type hint +-- (node.types = "ILDS..." one character per property), booleans as C, strings as S, buffers as R, Arrays by their +-- type (compressed with zlib when longer than 32 elements, unless compress = false). +export type WNode = { name: string, props: { any }, children: { WNode }?, types: string? } + +local function sizeHint(n: WNode): number + local s = 32 + #n.name + for _, v in n.props do + if type(v) == "string" then + s += 5 + #v + elseif type(v) == "buffer" then + s += 5 + buffer.len(v) + elseif type(v) == "table" then + s += 13 + (v.count or 0) * 8 + else + s += 9 + end + end + for _, c in n.children or {} do + s += sizeHint(c) + end + return s +end + +function Binary.write(root: WNode, version: number?, compress: boolean?): buffer + local zip = compress ~= false + local ver = version or 7400 + local wide = ver >= 7500 + local head = if wide then 25 else 13 + local cap = sizeHint(root) + 256 + local out = buffer.create(cap) + local pos = 0 + local function ensure(n: number) + if pos + n > cap then + while pos + n > cap do + cap *= 2 + end + local nb = buffer.create(cap) + buffer.copy(nb, 0, out, 0, pos) + out = nb + end + end + local function u8(v: number) + ensure(1) + buffer.writeu8(out, pos, v) + pos += 1 + end + local function u32(v: number) + ensure(4) + buffer.writeu32(out, pos, v) + pos += 4 + end + local function i64w(v: number) + ensure(8) + local hi = math.floor(v / 4294967296) + local lo = v - hi * 4294967296 + buffer.writeu32(out, pos, lo) + buffer.writeu32(out, pos + 4, hi % 4294967296) + pos += 8 + end + local function str(s: string) + ensure(#s) + buffer.writestring(out, pos, s) + pos += #s + end + local function bytes(src: buffer) + local n = buffer.len(src) + ensure(n) + buffer.copy(out, pos, src, 0, n) + pos += n + end + local function array(a: any) + local t, n, d = a.type, a.count, a.data + local es = ELEM[t] or 8 + local raw = buffer.create(n * es) + if a.raw then + buffer.copy(raw, 0, a.raw, 0, math.min(buffer.len(a.raw), n * es)) + else + for k = 0, n - 1 do + local v = readf64(d, k * 8) + if t == "d" then + writef64(raw, k * 8, v) + elseif t == "f" then + buffer.writef32(raw, k * 4, v) + elseif t == "i" then + buffer.writei32(raw, k * 4, v) + elseif t == "b" then + buffer.writeu8(raw, k, if v ~= 0 then 1 else 0) + else + local hi = math.floor(v / 4294967296) + buffer.writeu32(raw, k * 8, v - hi * 4294967296) + buffer.writeu32(raw, k * 8 + 4, hi % 4294967296) + end + end + end + u8(string.byte(t)) + u32(n) + if zip and n > 32 then + local z = Deflate.zlibCompress(raw, { level = 6 }) + if z then + u32(1) + u32(buffer.len(z)) + bytes(z) + return + end + end + u32(0) + u32(n * es) + bytes(raw) + end + local function setOff(at: number, v: number) + if wide then + buffer.writeu32(out, at, v % 4294967296) + buffer.writeu32(out, at + 4, math.floor(v / 4294967296)) + else + buffer.writeu32(out, at, v) + end + end + local function nullRecord() + ensure(head) + buffer.fill(out, pos, 0, head) + pos += head + end + local function node(n: WNode) + local start = pos + ensure(head) + buffer.fill(out, pos, 0, head) + pos += head + buffer.writeu8(out, start + head - 1, #n.name) + str(n.name) + local pstart = pos + local hints = n.types or "" + for k, v in n.props do + local h = string.sub(hints, k, k) + local tv = type(v) + if tv == "number" then + if h == "I" then + u8(73) + ensure(4) + buffer.writei32(out, pos, v) + pos += 4 + elseif h == "L" then + u8(76) + i64w(v) + elseif h == "F" then + u8(70) + ensure(4) + buffer.writef32(out, pos, v) + pos += 4 + elseif h == "Y" then + u8(89) + ensure(2) + buffer.writei16(out, pos, v) + pos += 2 + else + u8(68) + ensure(8) + writef64(out, pos, v) + pos += 8 + end + elseif tv == "boolean" then + u8(67) + u8(if v then 1 else 0) + elseif tv == "string" then + if string.sub(v, 1, 1) == "L" and h == "L" and #v == 17 then + u8(76) + local hi, lo = tonumber(string.sub(v, 2, 9), 16) or 0, tonumber(string.sub(v, 10, 17), 16) or 0 + u32(lo) + u32(hi) + else + u8(83) + u32(#v) + str(v) + end + elseif tv == "buffer" then + u8(82) + u32(buffer.len(v)) + bytes(v) + elseif tv == "table" and v.array then + array(v) + else + u8(83) + u32(0) + end + end + local plen = pos - pstart + local children = n.children + if children and #children > 0 then + for _, c in children do + node(c) + end + nullRecord() + elseif #n.props == 0 then + nullRecord() + end + setOff(start, pos) + if wide then + setOff(start + 8, #n.props) + setOff(start + 16, plen) + else + buffer.writeu32(out, start + 4, #n.props) + buffer.writeu32(out, start + 8, plen) + end + end + str(MAGIC) + u8(0x1A) + u8(0) + u32(ver) + for _, c in root.children or {} do + node(c) + end + nullRecord() + str(FOOT_ID) + str("\0\0\0\0") + local pad = ((pos + 15) // 16) * 16 - pos + if pad == 0 then + pad = 16 + end + str(string.rep("\0", pad)) + u32(ver) + str(string.rep("\0", 120)) + str(FOOT_MAGIC) + local res = buffer.create(pos) + buffer.copy(res, 0, out, 0, pos) + return res +end + +return Binary diff --git a/src/Formats/model/fbx/Read.luau b/src/Formats/model/fbx/Read.luau new file mode 100644 index 0000000..79b515d --- /dev/null +++ b/src/Formats/model/fbx/Read.luau @@ -0,0 +1,1383 @@ +--!strict +-- model/fbx/Read: an FBX 7.x node tree (model/fbx/Binary or model/fbx/Ascii) -> Scene. Objects + Connections -> +-- nodes (Model, with the full FBX transform: pre / post rotation, pivots, offsets, rotation order, geometric +-- transform baked into the mesh data), meshes (polygons, layer elements for normals / uvs / colours / materials in +-- every mapping (ByPolygonVertex, ByVertice, ByPolygon, AllSame) and reference (Direct, IndexToDirect) mode, one +-- primitive per material, vertices unwelded per polygon corner as assimp does), materials (Phong / Lambert and the +-- 3ds Max Physical / PBR compound -> PBR fields + extras.fbx), textures (embedded Video content kept encoded, or file +-- references through the fetch callback), skins (Skin + Cluster deformers -> JOINTS_0 / WEIGHTS_0, inverse bind +-- matrices), blend shapes (BlendShape / BlendShapeChannel / Shape -> morph targets), animation stacks (every layer's +-- curve nodes on Lcl Translation / Rotation / Scaling and DeformPercent, sampled at the union of key times (or +-- opts.sampleRate) and turned into glTF channels through the node transform), cameras and lights (on a child node +-- turning glTF's -Z forward into FBX's +X camera / -Y light axis). Property templates from Definitions supply defaults. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Base64 = require("@formats/core/Base64") +local Xform = require("@formats/model/fbx/Xform") + +local Read = {} + +type Node = { name: string, props: { any }, children: { Node } } +type Array = { array: true, type: string, count: number, data: buffer } +type Obj = { id: any, node: Node, name: string, class: string, sub: string, props: { [string]: { any } } } +type Conn = { id: any, prop: string? } +export type Fetch = (uri: string) -> buffer? + +local TICKS = 46186158000 -- FBX time units per second +Read.TICKS = TICKS + +-- ------------------------------------------------------------------------------------------------ tree helpers +local function child(n: Node?, name: string): Node? + if not n then + return nil + end + for _, c in n.children do + if c.name == name then + return c + end + end + return nil +end +Read.child = child + +local function value(n: Node?, name: string): any + local c = child(n, name) + return c and c.props[1] +end + +local function isArray(v: any): boolean + return type(v) == "table" and v.array == true +end + +-- the array under n. (or inline numbers: old ASCII files) +local function array(n: Node?, name: string): Array? + local c = child(n, name) + if not c then + return nil + end + local p = c.props[1] + if isArray(p) then + return p + end + local count = 0 + for _, v in c.props do + if type(v) == "number" then + count += 1 + end + end + if count == 0 then + return nil + end + local data = buffer.create(count * 8) + local k = 0 + for _, v in c.props do + if type(v) == "number" then + buffer.writef64(data, k * 8, v) + k += 1 + end + end + return { array = true, type = "d", count = count, data = data } +end + +local function at(a: Array, i: number): number + if i < 0 or i >= a.count then + return 0 + end + return buffer.readf64(a.data, i * 8) +end + +-- "Name\0\1Class" (binary) / "Class::Name" (ASCII) -> name +local function objectName(s: any): string + if type(s) ~= "string" then + return "" + end + local nm = string.match(s, "^(.-)%z\1") + if nm then + return nm + end + local _, rest = string.match(s, "^(%w+)::(.*)$") + if rest then + return rest + end + return s +end +Read.objectName = objectName + +-- Properties70 (P: name, type, label, flags, values...) -> { [name] = { type, v1, v2, ... } } +local function properties(n: Node?, into: { [string]: { any } }?): { [string]: { any } } + local out = into or {} + local p70 = child(n, "Properties70") + if p70 then + for _, p in p70.children do + local nm = p.props[1] + if p.name == "P" and type(nm) == "string" then + local v = { p.props[2] } + for k = 5, #p.props do + v[k - 3] = p.props[k] + end + out[nm] = v + end + end + end + return out +end +Read.properties = properties + +local function pnum(props: { [string]: { any } }, name: string, default: number): number + local p = props[name] + local v = p and p[2] + if type(v) == "number" then + return v + elseif type(v) == "boolean" then + return if v then 1 else 0 + end + return default +end +local function pvec(props: { [string]: { any } }, name: string, default: { number }): { number } + local p = props[name] + if p and type(p[2]) == "number" and type(p[3]) == "number" and type(p[4]) == "number" then + return { p[2], p[3], p[4] } + end + return table.clone(default) +end +local function pstr(props: { [string]: { any } }, name: string): string? + local p = props[name] + local v = p and p[2] + return if type(v) == "string" then v else nil +end + +-- ------------------------------------------------------------------------------------------------ scene +function Read.scene(root: Node, version: number, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?) + local triangulate = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local sampleRate = opts and type(opts.sampleRate) == "number" and opts.sampleRate > 0 and opts.sampleRate or nil + local maxVertices = opts and opts.maxVertices or 2 ^ 25 + local scene = Types.Scene.new() + + -- property templates (Definitions/ObjectType/PropertyTemplate) by object class + local templates: { [string]: { [string]: { any } } } = {} + local defs = child(root, "Definitions") + if defs then + for _, ot in defs.children do + if ot.name == "ObjectType" and type(ot.props[1]) == "string" then + local pt = child(ot, "PropertyTemplate") + if pt then + templates[ot.props[1]] = properties(pt) + end + end + end + end + + -- objects + local objects: { [any]: Obj } = {} + local order: { Obj } = {} + local objs = child(root, "Objects") + if not objs then + return nil, Err.new(Err.CORRUPT, "no Objects section") + end + for _, n in objs.children do + local id = n.props[1] + if (type(id) == "number" or type(id) == "string") and objects[id] == nil then + local base = templates[n.name] + local props = properties(n, if base then table.clone(base) else nil) + local o: Obj = { id = id, node = n, name = objectName(n.props[2]), class = n.name, sub = if type(n.props[3]) == "string" then n.props[3] else "", props = props } + objects[id] = o + table.insert(order, o) + end + end + + -- connections: children (sources) of each parent, parents of each child, in file order + local kids: { [any]: { Conn } } = {} + local parents: { [any]: { Conn } } = {} + local conns = child(root, "Connections") + if conns then + for _, c in conns.children do + if c.name == "C" or c.name == "Connect" then + local src, dst = c.props[2], c.props[3] + local prop = if type(c.props[4]) == "string" then c.props[4] else nil + if src ~= nil and dst ~= nil and type(src) ~= "table" and type(dst) ~= "table" then + kids[dst] = kids[dst] or {} + table.insert(kids[dst], { id = src, prop = prop }) + parents[src] = parents[src] or {} + table.insert(parents[src], { id = dst, prop = prop }) + end + end + end + end + local function sources(id: any, class: string?, sub: string?): { Obj } + local out = {} + for _, c in kids[id] or {} do + local o = objects[c.id] + if o and (class == nil or o.class == class) and (sub == nil or o.sub == sub) then + table.insert(out, o) + end + end + return out + end + local function sourcesProp(id: any): { { obj: Obj, prop: string? } } + local out = {} + for _, c in kids[id] or {} do + local o = objects[c.id] + if o then + table.insert(out, { obj = o, prop = c.prop }) + end + end + return out + end + local function targets(id: any, class: string?): { { obj: Obj, prop: string? } } + local out = {} + for _, c in parents[id] or {} do + local o = objects[c.id] + if o and (class == nil or o.class == class) then + table.insert(out, { obj = o, prop = c.prop }) + end + end + return out + end + + -- global settings + local gs = properties(child(root, "GlobalSettings")) + local upAxis = pnum(gs, "UpAxis", 1) + local unitScale = pnum(gs, "UnitScaleFactor", 1) + scene.meta.up = if upAxis == 2 then "z" else "y" + scene.meta.unit = unitScale / 100 + local frameRates = { [1] = 120, [2] = 100, [3] = 60, [4] = 50, [5] = 48, [6] = 30, [7] = 30, [8] = 29.97, [9] = 29.97, [10] = 25, [11] = 24, [13] = 96, [14] = 72, [15] = 59.94, [17] = 119.88 } + local timeMode = pnum(gs, "TimeMode", 0) + local fps = if timeMode == 14 then pnum(gs, "CustomFrameRate", 24) else frameRates[timeMode] or 24 + + -- ------------------------------------------------------------------------------------------ textures + local textureIndex: { [any]: number } = {} + local function mimeOf(data: buffer?, name: string?): string? + if data and buffer.len(data) >= 4 then + local h = buffer.readstring(data, 0, 4) + if h == "\137PNG" then + return "image/png" + elseif string.sub(h, 1, 3) == "\255\216\255" then + return "image/jpeg" + elseif string.sub(h, 1, 2) == "BM" then + return "image/bmp" + elseif h == "DDS " then + return "image/vnd-ms.dds" + elseif h == "RIFF" then + return "image/webp" + end + end + local ext = name and string.lower(string.match(name, "%.(%w+)$") or "") or "" + local M = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds", tif = "image/tiff", tiff = "image/tiff", webp = "image/webp", gif = "image/gif", psd = "image/vnd.adobe.photoshop" } + return M[ext] + end + local function content(v: Node?): buffer? + if not v then + return nil + end + local c = child(v, "Content") + if not c then + return nil + end + for _, p in c.props do + if type(p) == "buffer" and buffer.len(p) > 0 then + return p + end + end + -- ASCII: base64 strings (possibly split into several) + local parts = {} + for _, p in c.props do + if type(p) == "string" then + table.insert(parts, p) + end + end + local s = table.concat(parts) + if #s > 0 then + local d = Base64.decode(s) + if d and buffer.len(d) > 0 then + return d + end + end + return nil + end + local function texture(o: Obj): number + local have = textureIndex[o.id] + if have then + return have + end + local n = o.node + local rel = value(n, "RelativeFilename") + local file = value(n, "FileName") or value(n, "Filename") + local data: buffer? = nil + local video: Obj? = sources(o.id, "Video")[1] + if video then + data = content(video.node) + rel = rel or value(video.node, "RelativeFilename") + file = file or value(video.node, "Filename") or value(video.node, "FileName") + end + local uri: string? = nil + if type(rel) == "string" and rel ~= "" then + uri = (string.gsub(rel, "\\", "/")) + elseif type(file) == "string" and file ~= "" then + uri = (string.gsub(file, "\\", "/")) + end + if not data and uri then + data = fetch(uri :: string) + if not data then + local base = string.match(uri :: string, "([^/]+)$") + if base and base ~= uri then + data = fetch(base) + end + end + end + local tex: Types.Texture = { name = o.name, data = data, uri = if data and video and content(video.node) then nil else uri, mime = mimeOf(data, uri) } + local wrapU, wrapV = pnum(o.props, "WrapModeU", 0), pnum(o.props, "WrapModeV", 0) + if wrapU ~= 0 or wrapV ~= 0 then + tex.sampler = { wrapS = if wrapU == 1 then "clamp" else "repeat", wrapT = if wrapV == 1 then "clamp" else "repeat" } + end + tex.extras = { fbx = { uri = uri, uvSet = pstr(o.props, "UVSet") } } + table.insert(scene.textures, tex) + textureIndex[o.id] = #scene.textures + return #scene.textures + end + local function texRef(o: Obj): Types.TextureRef? + local tobj = o + if o.class == "LayeredTexture" then + local t = sources(o.id, "Texture")[1] + if not t then + return nil + end + tobj = t + end + local ref: Types.TextureRef = { texture = texture(tobj) } + local tr, sc = pvec(tobj.props, "Translation", { 0, 0, 0 }), pvec(tobj.props, "Scaling", { 1, 1, 1 }) + local rot = pvec(tobj.props, "Rotation", { 0, 0, 0 }) + if tr[1] ~= 0 or tr[2] ~= 0 or sc[1] ~= 1 or sc[2] ~= 1 or rot[3] ~= 0 then + ref.transform = { offset = { tr[1], tr[2] }, scale = { sc[1], sc[2] }, rotation = rot[3] * math.pi / 180 } + end + return ref + end + + -- ------------------------------------------------------------------------------------------ materials + local materialIndex: { [any]: number } = {} + local function material(o: Obj): number + local have = materialIndex[o.id] + if have then + return have + end + local p = o.props + local m = Types.Scene.material(o.name) + local shading = value(o.node, "ShadingModel") + local diffuse = pvec(p, "DiffuseColor", pvec(p, "Diffuse", { 0.8, 0.8, 0.8 })) + local dfac = pnum(p, "DiffuseFactor", 1) + local emissive = pvec(p, "EmissiveColor", pvec(p, "Emissive", { 0, 0, 0 })) + local efac = pnum(p, "EmissiveFactor", 1) + local shininess = pnum(p, "ShininessExponent", pnum(p, "Shininess", 20)) + local opacity: number + if p.Opacity then + opacity = pnum(p, "Opacity", 1) + else + local tc = pvec(p, "TransparentColor", { 1, 1, 1 }) + opacity = 1 - pnum(p, "TransparencyFactor", 0) * (tc[1] + tc[2] + tc[3]) / 3 + end + opacity = math.clamp(opacity, 0, 1) + m.baseColor = { diffuse[1] * dfac, diffuse[2] * dfac, diffuse[3] * dfac, opacity } + m.emissive = { emissive[1] * efac, emissive[2] * efac, emissive[3] * efac } + m.metallic = 0 + m.roughness = math.clamp(math.sqrt(2 / (math.max(shininess, 0) + 2)), 0, 1) + if opacity < 1 then + m.alphaMode = "blend" + end + -- 3ds Max Physical / PBR materials + local pbr = p["3dsMax|main|basecolor"] or p["3dsMax|Parameters|base_color"] + if pbr then + local prefix = if p["3dsMax|main|basecolor"] then "3dsMax|main|" else "3dsMax|Parameters|" + local bc = pbr + if type(bc[2]) == "number" then + m.baseColor = { bc[2], bc[3] or 1, bc[4] or 1, if type(bc[5]) == "number" then bc[5] else 1 } + end + m.metallic = pnum(p, prefix .. "metalness", 0) + m.roughness = pnum(p, prefix .. "roughness", 1) + if pnum(p, prefix .. "useGlossiness", 0) == 1 or pnum(p, prefix .. "roughness_inv", 0) == 1 then + m.roughness = 1 - pnum(p, prefix .. "glossiness", 1 - m.roughness) + end + local ec = p[prefix .. "emit_color"] or p[prefix .. "emission_color"] + if ec and type(ec[2]) == "number" then + local k = pnum(p, prefix .. "emission", 1) + m.emissive = { ec[2] * k, (ec[3] or 0) * k, (ec[4] or 0) * k } + end + end + local extras: { [string]: any } = { + shadingModel = if type(shading) == "string" then string.lower(shading) else pstr(p, "ShadingModel"), + diffuse = diffuse, + diffuseFactor = dfac, + ambient = pvec(p, "AmbientColor", pvec(p, "Ambient", { 0, 0, 0 })), + ambientFactor = pnum(p, "AmbientFactor", 1), + specular = pvec(p, "SpecularColor", pvec(p, "Specular", { 0.2, 0.2, 0.2 })), + specularFactor = pnum(p, "SpecularFactor", 1), + shininess = shininess, + emissive = emissive, + emissiveFactor = efac, + opacity = opacity, + reflection = pvec(p, "ReflectionColor", { 0, 0, 0 }), + reflectionFactor = pnum(p, "ReflectionFactor", 0), + bumpFactor = pnum(p, "BumpFactor", 1), + textures = {}, + } + for _, s in sourcesProp(o.id) do + local cls = s.obj.class + if (cls == "Texture" or cls == "LayeredTexture") and s.prop then + local ref = texRef(s.obj) + if ref then + local prop = s.prop :: string + local lp = string.lower(prop) + extras.textures[prop] = ref.texture + if lp == "diffusecolor" or string.find(lp, "base_?color_map") or lp == "maya|basecolor" or lp == "maya|texturebasecolor" then + m.baseColorTexture = m.baseColorTexture or ref + elseif lp == "normalmap" or lp == "bump" or string.find(lp, "norm_map") or string.find(lp, "bump_map") or lp == "maya|normalcamera" then + m.normalTexture = m.normalTexture or ref + elseif lp == "emissivecolor" or string.find(lp, "emit_color_map") or string.find(lp, "emission_map") then + m.emissiveTexture = m.emissiveTexture or ref + if m.emissive[1] == 0 and m.emissive[2] == 0 and m.emissive[3] == 0 then + m.emissive = { 1, 1, 1 } + end + elseif string.find(lp, "ao_map") then + m.occlusionTexture = m.occlusionTexture or ref + end + end + end + end + if not next(extras.textures) then + extras.textures = nil + end + m.extras = { fbx = extras } + table.insert(scene.materials, m) + materialIndex[o.id] = #scene.materials + return #scene.materials + end + + -- ------------------------------------------------------------------------------------------ nodes + local models: { Obj } = {} + local nodeOf: { [any]: number } = {} + for _, o in order do + if o.class == "Model" then + table.insert(models, o) + local nd: Types.Node = { name = o.name, children = {} } + table.insert(scene.nodes, nd) + nodeOf[o.id] = #scene.nodes + end + end + if #models > maxVertices then + return nil, Err.new(Err.LIMIT, "too many models") + end + local function xprops(o: Obj, over: { [string]: { number } }?): Xform.Props + local p = o.props + local function g(name: string, key: string, default: { number }): { number } + if over and over[key] then + return over[key] + end + return pvec(p, name, default) + end + return { + T = g("Lcl Translation", "T", { 0, 0, 0 }), + R = g("Lcl Rotation", "R", { 0, 0, 0 }), + S = g("Lcl Scaling", "S", { 1, 1, 1 }), + Rpre = pvec(p, "PreRotation", { 0, 0, 0 }), + Rpost = pvec(p, "PostRotation", { 0, 0, 0 }), + Roff = pvec(p, "RotationOffset", { 0, 0, 0 }), + Rp = pvec(p, "RotationPivot", { 0, 0, 0 }), + Soff = pvec(p, "ScalingOffset", { 0, 0, 0 }), + Sp = pvec(p, "ScalingPivot", { 0, 0, 0 }), + order = pnum(p, "RotationOrder", 0), + } + end + local localM: { [number]: Xform.M4 } = {} + for _, o in models do + local ni = nodeOf[o.id] + local nd = scene.nodes[ni] + local m = Xform.localMatrix(xprops(o)) + localM[ni] = m + local t, r, s = Xform.decompose(m) + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + nd.translation = t + end + if r[1] ~= 0 or r[2] ~= 0 or r[3] ~= 0 or r[4] ~= 1 then + nd.rotation = r + end + if s[1] ~= 1 or s[2] ~= 1 or s[3] ~= 1 then + nd.scale = s + end + nd.extras = { fbx = { type = o.sub, id = o.id } } + -- parent + local parentModel: Obj? = nil + for _, t2 in targets(o.id, "Model") do + parentModel = t2.obj + break + end + local pi = parentModel and nodeOf[parentModel.id] + if pi and pi ~= ni then + table.insert(scene.nodes[pi].children, ni) + else + table.insert(scene.roots, ni) + end + end + -- break parent cycles (a node reachable from itself is not a valid tree): cut children already placed + do + local placed: { [number]: boolean } = {} + local function visit(i: number) + placed[i] = true + local nd = scene.nodes[i] + local keepKids = {} + for _, c in nd.children do + if not placed[c] then + table.insert(keepKids, c) + visit(c) + end + end + nd.children = keepKids + end + for _, r in scene.roots do + visit(r) + end + for i in scene.nodes do + if not placed[i] then + -- part of a parent cycle: make it a root + table.insert(scene.roots, i) + visit(i) + end + end + end + -- world matrices (rest pose) + local worldM: { [number]: Xform.M4 } = {} + local function world(i: number, parent: Xform.M4) + worldM[i] = Xform.mul(parent, localM[i] or Xform.identity()) + for _, c in scene.nodes[i].children do + if not worldM[c] then + world(c, worldM[i]) + end + end + end + for _, r in scene.roots do + world(r, Xform.identity()) + end + + -- ------------------------------------------------------------------------------------------ meshes + local corners = 0 + -- per geometry: skin (control point -> { joint node, weight }) and blend shape channels + local function skinOf(geo: Obj): ({ { { number } } }?, Types.Skin?) + local skin = sources(geo.id, "Deformer", "Skin")[1] + if not skin then + return nil, nil + end + local perCp: { { { number } } } = {} + local joints: { number } = {} + local ibms: { Xform.M4 } = {} + for _, cl in sources(skin.id, "Deformer", "Cluster") do + local bone = sources(cl.id, "Model")[1] + local bi = bone and nodeOf[bone.id] + if bi then + local ji = #joints + 1 + joints[ji] = bi + local idx, w = array(cl.node, "Indexes"), array(cl.node, "Weights") + local T, TL = array(cl.node, "Transform"), array(cl.node, "TransformLink") + local tm = Xform.identity() + if T and T.count >= 16 then + for k = 1, 16 do + tm[k] = at(T, k - 1) + end + end + local tl: Xform.M4? = nil + if TL and TL.count >= 16 then + tl = {} + for k = 1, 16 do + (tl :: any)[k] = at(TL, k - 1) + end + else + tl = worldM[bi] + end + local inv = Xform.inverse(tl :: Xform.M4) or Xform.identity() + ibms[ji] = Xform.mul(inv, tm) + if idx and w then + for k = 0, math.min(idx.count, w.count) - 1 do + local cp = at(idx, k) + local wt = at(w, k) + if cp >= 0 and cp == math.floor(cp) and cp < maxVertices and wt > 0 then + local l = perCp[cp + 1] + if not l then + l = {} + perCp[cp + 1] = l + end + table.insert(l, { ji - 1, wt }) + end + end + end + end + end + if #joints == 0 then + return nil, nil + end + local ibm = buffer.create(#joints * 64) + for j, m in ibms do + for k = 1, 16 do + buffer.writef32(ibm, (j - 1) * 64 + (k - 1) * 4, m[k]) + end + end + local acc = Types.Scene.accessor(ibm, "f32", 16, #joints) + acc.matrix = true + return perCp, { name = skin.name, joints = joints, inverseBindMatrices = acc } + end + type Shape = { name: string, channel: Obj, weight: number, idx: Array?, dv: Array?, dn: Array? } + local function shapesOf(geo: Obj): { Shape } + local out = {} + for _, bs in sources(geo.id, "Deformer", "BlendShape") do + for _, ch in sources(bs.id, "Deformer", "BlendShapeChannel") do + local shapes = sources(ch.id, "Geometry") + local sh = shapes[#shapes] -- in-betweens: the full (last) shape + if sh then + table.insert(out, { + name = ch.name ~= "" and ch.name or sh.name, + channel = ch, + weight = pnum(ch.props, "DeformPercent", 0) / 100, + idx = array(sh.node, "Indexes"), + dv = array(sh.node, "Vertices"), + dn = array(sh.node, "Normals"), + }) + end + end + end + return out + end + + local meshCache: { [string]: number } = {} + local shapeChannels: { [number]: { Obj } } = {} -- mesh index -> blend shape channel objects (for weights curves) + local nodeSkin: { [number]: number } = {} + local skinCache: { [any]: number } = {} + + local function buildMesh(geo: Obj, mats: { number }, G: Xform.M4?): (number?, Err.Err?) + local g = geo.node + local verts = array(g, "Vertices") + local pvi = array(g, "PolygonVertexIndex") + if not verts or not pvi then + return nil, nil + end + local ncp = verts.count // 3 + local nc = pvi.count + corners += nc + if corners > maxVertices or ncp > maxVertices then + return nil, Err.new(Err.LIMIT, "over " .. maxVertices .. " vertices") + end + -- polygons: corner -> control point, polygon of each corner, polygon starts + local cp = table.create(nc, 0) + local polyOf = table.create(nc, 0) + local starts: { number } = { 0 } + local np = 0 + for c = 0, nc - 1 do + local v = at(pvi, c) + local last = v < 0 + if last then + v = -v - 1 + end + if v >= ncp or v ~= math.floor(v) then + v = 0 + end + cp[c + 1] = v + polyOf[c + 1] = np + if last then + np += 1 + starts[np + 1] = c + 1 + end + end + if starts[np + 1] ~= nc then + -- the last polygon has no end marker + np += 1 + starts[np + 1] = nc + end + -- layer elements + type Elem = { data: Array, index: Array?, mapping: string, comps: number, name: string?, order: number } + local function elems(kind: string, dataName: string, indexName: string, comps: number): { Elem } + local out: { Elem } = {} + for _, c in g.children do + if c.name == kind then + local data = array(c, dataName) + local mapping = value(c, "MappingInformationType") + local ref = value(c, "ReferenceInformationType") + local index = if ref == "IndexToDirect" or ref == "Index" then array(c, indexName) or array(c, dataName .. "Index") else nil + if kind == "LayerElementMaterial" then + index = data + end + if data and type(mapping) == "string" then + table.insert(out, { data = data, index = index, mapping = mapping, comps = comps, name = value(c, "Name"), order = if type(c.props[1]) == "number" then c.props[1] else #out }) + end + end + end + table.sort(out, function(a: Elem, b: Elem): boolean + return a.order < b.order + end) + return out + end + -- the data element of a corner (c 0-based), or -1 + local function lookup(e: Elem, c: number): number + local m = e.mapping + local i + if m == "ByPolygonVertex" then + i = c + elseif m == "ByVertice" or m == "ByVertex" then + i = cp[c + 1] + elseif m == "ByPolygon" then + i = polyOf[c + 1] + elseif m == "AllSame" then + i = 0 + else + return -1 + end + if e.index and e.data ~= e.index then + if i >= (e.index :: Array).count then + return -1 + end + i = at(e.index :: Array, i) + end + if i < 0 or (i + 1) * e.comps > e.data.count then + return -1 + end + return i + end + local normals = elems("LayerElementNormal", "Normals", "NormalsIndex", 3) + local uvs = elems("LayerElementUV", "UV", "UVIndex", 2) + local colors = elems("LayerElementColor", "Colors", "ColorIndex", 4) + local tangents = elems("LayerElementTangent", "Tangents", "TangentsIndex", 3) + local matEl = elems("LayerElementMaterial", "Materials", "Materials", 1)[1] + -- the normals index name varies ("NormalsIndex" / "NormalIndex") + for _, e in normals do + if not e.index then + local c = nil + for _, x in g.children do + if x.name == "LayerElementNormal" then + c = x + break + end + end + local r = c and value(c, "ReferenceInformationType") + if r == "IndexToDirect" then + e.index = array(c, "NormalIndex") + end + end + end + -- polygons by material slot + local groups: { [number]: { number } } = {} + local slots: { number } = {} + for p = 0, np - 1 do + local slot = 0 + if matEl then + local c0 = starts[p + 1] + local i = if matEl.mapping == "AllSame" then 0 else p + if matEl.mapping == "ByPolygonVertex" then + i = c0 + end + slot = at(matEl.data, i) + if slot < 0 or slot ~= math.floor(slot) then + slot = 0 + end + end + local grp = groups[slot] + if not grp then + grp = {} + groups[slot] = grp + table.insert(slots, slot) + end + table.insert(grp, p) + end + table.sort(slots) + local perCp, skin = skinOf(geo) + local shapes = shapesOf(geo) + local N3: Xform.M4? = nil -- normal matrix (inverse transpose of G) + if G then + local inv = Xform.inverse(G) + if inv then + N3 = { inv[1], inv[5], inv[9], 0, inv[2], inv[6], inv[10], 0, inv[3], inv[7], inv[11], 0, 0, 0, 0, 1 } + end + end + local mesh: Types.Mesh = { name = geo.name, primitives = {} } + local function v3(dst: buffer, o: number, x: number, y: number, z: number, M: Xform.M4?, w: number) + if M then + x, y, z = M[1] * x + M[5] * y + M[9] * z + M[13] * w, M[2] * x + M[6] * y + M[10] * z + M[14] * w, M[3] * x + M[7] * y + M[11] * z + M[15] * w + end + buffer.writef32(dst, o, x) + buffer.writef32(dst, o + 4, y) + buffer.writef32(dst, o + 8, z) + end + local skipped = 0 + for _, slot in slots do + local polys = groups[slot] + local nv = 0 + local ntri = 0 + for _, p in polys do + local k = starts[p + 2] - starts[p + 1] + if k >= 3 or not triangulate then + nv += k + ntri += math.max(k - 2, 0) + else + skipped += 1 + end + end + if nv > 0 then + local pos = buffer.create(nv * 12) + local nrm = if normals[1] then buffer.create(nv * 12) else nil + local tan = if tangents[1] then buffer.create(nv * 16) else nil + local uvb: { buffer } = {} + for k = 1, #uvs do + uvb[k] = buffer.create(nv * 8) + end + local colb: { buffer } = {} + for k = 1, #colors do + colb[k] = buffer.create(nv * 16) + end + local joints = if perCp then buffer.create(nv * 8) else nil + local weights = if perCp then buffer.create(nv * 16) else nil + local tgt: { { [string]: Types.Accessor } } = {} + local shapeData: { { pos: buffer, nrm: buffer?, map: { [number]: number } } } = {} + for si, sh in shapes do + local map: { [number]: number } = {} + if sh.idx then + for k = 0, sh.idx.count - 1 do + map[at(sh.idx, k)] = k + end + end + shapeData[si] = { pos = buffer.create(nv * 12), nrm = if sh.dn and nrm then buffer.create(nv * 12) else nil, map = map } + end + local faces = if not triangulate then buffer.create(#polys * 4) else nil + local idx = buffer.create((if triangulate then ntri * 3 else nv) * 4) + local v = 0 + local ti = 0 + local fi = 0 + for _, p in polys do + local c0, c1 = starts[p + 1], starts[p + 2] + local k = c1 - c0 + if k >= 3 or not triangulate then + local first = v + for c = c0, c1 - 1 do + local i = cp[c + 1] + v3(pos, v * 12, at(verts, i * 3), at(verts, i * 3 + 1), at(verts, i * 3 + 2), G, 1) + if nrm then + local d = lookup(normals[1], c) + local e = normals[1].data + if d >= 0 then + v3(nrm, v * 12, at(e, d * 3), at(e, d * 3 + 1), at(e, d * 3 + 2), N3, 0) + end + end + if tan then + local d = lookup(tangents[1], c) + local e = tangents[1].data + if d >= 0 then + v3(tan, v * 16, at(e, d * 3), at(e, d * 3 + 1), at(e, d * 3 + 2), G, 0) + buffer.writef32(tan, v * 16 + 12, 1) + end + end + for u, e in uvs do + local d = lookup(e, c) + if d >= 0 then + local uu, vv = at(e.data, d * 2), at(e.data, d * 2 + 1) + buffer.writef32(uvb[u], v * 8, uu) + buffer.writef32(uvb[u], v * 8 + 4, if flipV then 1 - vv else vv) + end + end + for u, e in colors do + local d = lookup(e, c) + local b = colb[u] + if d >= 0 then + for q = 0, 3 do + buffer.writef32(b, v * 16 + q * 4, at(e.data, d * 4 + q)) + end + else + buffer.writef32(b, v * 16 + 12, 1) + end + end + if perCp and joints and weights then + local l = perCp[i + 1] + if l then + if #l > 4 then + table.sort(l, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + end + local sum = 0 + for q = 1, math.min(#l, 4) do + sum += l[q][2] + end + for q = 1, math.min(#l, 4) do + buffer.writeu16(joints, v * 8 + (q - 1) * 2, l[q][1]) + buffer.writef32(weights, v * 16 + (q - 1) * 4, if sum > 0 then l[q][2] / sum else 0) + end + end + end + for si, sd in shapeData do + local sh = shapes[si] + local k2 = sd.map[i] + if k2 and sh.dv then + v3(sd.pos, v * 12, at(sh.dv, k2 * 3), at(sh.dv, k2 * 3 + 1), at(sh.dv, k2 * 3 + 2), G, 0) + if sd.nrm and sh.dn then + v3(sd.nrm, v * 12, at(sh.dn, k2 * 3), at(sh.dn, k2 * 3 + 1), at(sh.dn, k2 * 3 + 2), N3, 0) + end + end + end + if not triangulate then + buffer.writeu32(idx, v * 4, v) + end + v += 1 + end + if triangulate then + for q = 1, k - 2 do + buffer.writeu32(idx, ti * 4, first) + buffer.writeu32(idx, ti * 4 + 4, first + q) + buffer.writeu32(idx, ti * 4 + 8, first + q + 1) + ti += 3 + end + elseif faces then + buffer.writeu32(faces, fi * 4, k) + fi += 1 + end + end + end + local attrs: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) } + if nrm then + attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv) + end + if tan then + attrs.TANGENT = Types.Scene.accessor(tan, "f32", 4, nv) + end + for u, b in uvb do + attrs["TEXCOORD_" .. (u - 1)] = Types.Scene.accessor(b, "f32", 2, nv) + end + for u, b in colb do + attrs["COLOR_" .. (u - 1)] = Types.Scene.accessor(b, "f32", 4, nv) + end + if joints and weights then + attrs.JOINTS_0 = Types.Scene.accessor(joints, "u16", 4, nv) + attrs.WEIGHTS_0 = Types.Scene.accessor(weights, "f32", 4, nv) + end + for si, sd in shapeData do + local t: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(sd.pos, "f32", 3, nv) } + if sd.nrm then + t.NORMAL = Types.Scene.accessor(sd.nrm, "f32", 3, nv) + end + tgt[si] = t + end + local prim: Types.Primitive = { + attributes = attrs, + indices = Types.Scene.accessor(idx, "u32", 1, if triangulate then ntri * 3 else nv), + mode = if triangulate then "triangles" else "polygons", + faces = if faces then Types.Scene.accessor(faces, "u32", 1, #polys) else nil, + material = mats[slot + 1], + targets = if #tgt > 0 then tgt else nil, + } + table.insert(mesh.primitives, prim) + end + end + if #mesh.primitives == 0 then + return nil, nil + end + local names = {} + for k, uv in uvs do + names[k] = uv.name + end + mesh.extras = { fbx = { id = geo.id, uvSets = names, skippedPolygons = if skipped > 0 then skipped else nil } } + if #shapes > 0 then + local w, tn, chans = {}, {}, {} + for si, sh in shapes do + w[si] = sh.weight + tn[si] = sh.name + chans[si] = sh.channel + end + mesh.weights = w + ;(mesh.extras :: any).targetNames = tn + table.insert(scene.meshes, mesh) + shapeChannels[#scene.meshes] = chans + else + table.insert(scene.meshes, mesh) + end + local mi = #scene.meshes + if skin then + skinCache[geo.id] = skinCache[geo.id] or (function(): number + table.insert(scene.skins, skin) + return #scene.skins + end)() + end + return mi, nil + end + + local orient = math.sqrt(0.5) + for _, o in models do + local ni = nodeOf[o.id] + local nd = scene.nodes[ni] + -- materials of the model, in connection order + local mats: { number } = {} + for _, m in sources(o.id, "Material") do + table.insert(mats, material(m)) + end + -- geometric transform (not inherited: baked into the mesh) + local gt = pvec(o.props, "GeometricTranslation", { 0, 0, 0 }) + local gr = pvec(o.props, "GeometricRotation", { 0, 0, 0 }) + local gsc = pvec(o.props, "GeometricScaling", { 1, 1, 1 }) + local G: Xform.M4? = nil + if gt[1] ~= 0 or gt[2] ~= 0 or gt[3] ~= 0 or gr[1] ~= 0 or gr[2] ~= 0 or gr[3] ~= 0 or gsc[1] ~= 1 or gsc[2] ~= 1 or gsc[3] ~= 1 then + G = Xform.mul(Xform.translate(gt[1], gt[2], gt[3]), Xform.mul(Xform.euler(gr[1], gr[2], gr[3], 0), Xform.scale(gsc[1], gsc[2], gsc[3]))) + end + for _, geo in sources(o.id, "Geometry") do + if geo.sub == "Mesh" or geo.sub == "" then + local key = tostring(geo.id) .. "|" .. table.concat(mats, ",") .. "|" .. (if G then table.concat(G :: any, ",") else "") + local mi = meshCache[key] + if mi == nil then + local m, err = buildMesh(geo, mats, G) + if err then + return nil, err + end + if m then + meshCache[key] = m + mi = m + end + end + if mi then + if nd.mesh == nil then + nd.mesh = mi + if skinCache[geo.id] then + nd.skin = skinCache[geo.id] + end + nd.weights = scene.meshes[mi].weights and table.clone(scene.meshes[mi].weights :: { number }) + else + -- a second geometry on the same model: a child node + table.insert(scene.nodes, { name = o.name, children = {}, mesh = mi, skin = skinCache[geo.id] }) + table.insert(nd.children, #scene.nodes) + end + nodeSkin[ni] = skinCache[geo.id] + end + end + end + -- cameras and lights: on a child node rotated from glTF's -Z forward to FBX's axis + for _, a in sources(o.id, "NodeAttribute") do + local p = a.props + if a.sub == "Camera" then + local ortho = pnum(p, "CameraProjectionType", 0) == 1 + local aw, ah = pnum(p, "AspectWidth", 0), pnum(p, "AspectHeight", 0) + local fw, fh = pnum(p, "FilmWidth", 0.816), pnum(p, "FilmHeight", 0.612) + local aspect = if aw > 0 and ah > 0 then aw / ah elseif fh > 0 then fw / fh else 4 / 3 + local cam: Types.Camera + local near, far = pnum(p, "NearPlane", 10), pnum(p, "FarPlane", 4000) + if ortho then + local zoom = pnum(p, "OrthoZoom", 1) + cam = { name = a.name ~= "" and a.name or o.name, type = "orthographic", xmag = zoom * aspect, ymag = zoom, znear = near, zfar = far } + else + local focal = pnum(p, "FocalLength", 0) + local hfov + if focal > 0 and fw > 0 then + hfov = 2 * math.atan(fw * 25.4 / (2 * focal)) + else + hfov = pnum(p, "FieldOfView", 40) * math.pi / 180 + end + local yfov = 2 * math.atan(math.tan(hfov / 2) / aspect) + cam = { name = a.name ~= "" and a.name or o.name, type = "perspective", yfov = yfov, aspect = aspect, znear = near, zfar = far } + end + table.insert(scene.cameras, cam) + table.insert(scene.nodes, { name = o.name .. "_camera", children = {}, camera = #scene.cameras, rotation = { 0, -orient, 0, orient }, extras = { fbx = { orientation = "camera" } } }) + table.insert(nd.children, #scene.nodes) + elseif a.sub == "Light" then + local lt = pnum(p, "LightType", 0) + local col = pvec(p, "Color", { 1, 1, 1 }) + local light: Types.Light = { + name = a.name ~= "" and a.name or o.name, + type = if lt == 1 then "directional" elseif lt == 2 then "spot" else "point", + color = col, + intensity = pnum(p, "Intensity", 100) / 100, + } + if lt == 2 then + local outer = pnum(p, "OuterAngle", pnum(p, "Cone angle", 45)) + local inner = pnum(p, "InnerAngle", pnum(p, "HotSpot", 0)) + light.outerCone = math.clamp(outer / 2, 0, 90) * math.pi / 180 + light.innerCone = math.clamp(math.min(inner, outer) / 2, 0, 90) * math.pi / 180 + end + if pnum(p, "EnableFarAttenuation", 0) == 1 then + light.range = pnum(p, "FarAttenuationEnd", 0) + end + table.insert(scene.lights, light) + table.insert(scene.nodes, { name = o.name .. "_light", children = {}, light = #scene.lights, rotation = { -orient, 0, 0, orient }, extras = { fbx = { orientation = "light", lightType = lt } } }) + table.insert(nd.children, #scene.nodes) + end + end + end + + -- ------------------------------------------------------------------------------------------ animation + type Curve = { times: { number }, values: { number }, flags: { number }, slopes: { { number } }? } + local curveCache: { [any]: Curve } = {} + local function curve(o: Obj): Curve? + local have = curveCache[o.id] + if have then + return have + end + local kt, kv = array(o.node, "KeyTime"), array(o.node, "KeyValueFloat") + if not kt or not kv then + return nil + end + local n = math.min(kt.count, kv.count) + if n == 0 then + return nil + end + local times, values = table.create(n, 0), table.create(n, 0) + for k = 0, n - 1 do + times[k + 1] = at(kt, k) / TICKS + values[k + 1] = at(kv, k) + end + -- per-key attribute flags (expanded through KeyAttrRefCount) + local fl, rc, df = array(o.node, "KeyAttrFlags"), array(o.node, "KeyAttrRefCount"), array(o.node, "KeyAttrDataFloat") + local flags = table.create(n, 4) + local slopes: { { number } } = {} + if fl and rc then + local key = 1 + for a = 0, math.min(fl.count, rc.count) - 1 do + local f = at(fl, a) + local cnt = at(rc, a) + for _ = 1, math.min(cnt, n - key + 1) do + flags[key] = f + if df and df.count >= (a + 1) * 4 then + slopes[key] = { at(df, a * 4), at(df, a * 4 + 1) } + end + key += 1 + end + end + end + local c: Curve = { times = times, values = values, flags = flags, slopes = slopes } + curveCache[o.id] = c + return c + end + local function eval(c: Curve, t: number): number + local ts, vs = c.times, c.values + local n = #ts + if t <= ts[1] then + return vs[1] + elseif t >= ts[n] then + return vs[n] + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if ts[mid] <= t then + lo = mid + else + hi = mid + end + end + local dt = ts[hi] - ts[lo] + if dt <= 0 then + return vs[hi] + end + local u = (t - ts[lo]) / dt + local f = bit32.band(c.flags[lo] or 4, 0x0E) + if f == 2 then + return vs[lo] + elseif f == 8 and c.slopes and c.slopes[lo] then + local s = (c.slopes :: { { number } })[lo] + local m0, m1 = s[1] * dt, s[2] * dt + local u2, u3 = u * u, u * u * u + return (2 * u3 - 3 * u2 + 1) * vs[lo] + (u3 - 2 * u2 + u) * m0 + (-2 * u3 + 3 * u2) * vs[hi] + (u3 - u2) * m1 + end + return vs[lo] + (vs[hi] - vs[lo]) * u + end + local function allConstant(cs: { Curve }): boolean + for _, c in cs do + for k = 1, #c.times - 1 do + if bit32.band(c.flags[k] or 4, 0x0E) ~= 2 then + return false + end + end + end + return true + end + local function sampleTimes(cs: { Curve }): { number } + local set: { [number]: boolean } = {} + local out: { number } = {} + local tmin, tmax = math.huge, -math.huge + for _, c in cs do + for _, t in c.times do + tmin, tmax = math.min(tmin, t), math.max(tmax, t) + if not set[t] then + set[t] = true + table.insert(out, t) + end + end + end + if sampleRate and tmax > tmin then + local steps = math.min(math.ceil((tmax - tmin) * sampleRate), 100000) + for k = 0, steps do + local t = tmin + (tmax - tmin) * k / steps + if not set[t] then + set[t] = true + table.insert(out, t) + end + end + end + table.sort(out) + return out + end + local function f32acc(vals: { number }, comps: number): Types.Accessor + local n = #vals // comps + local b = buffer.create(#vals * 4) + for k, v in vals do + buffer.writef32(b, (k - 1) * 4, v) + end + return Types.Scene.accessor(b, "f32", comps, n) + end + local PROPS = { ["Lcl Translation"] = "T", ["Lcl Rotation"] = "R", ["Lcl Scaling"] = "S" } + for _, stack in order do + if stack.class == "AnimationStack" then + local anim: Types.Animation = { name = stack.name, channels = {} } + -- model id -> { T/R/S -> { axis -> curve } , defaults } + type Track = { curves: { [string]: { [number]: Curve } }, defaults: { [string]: { number } } } + local tracks: { [any]: Track } = {} + local trackOrder: { any } = {} + local morph: { [any]: Curve } = {} -- blend shape channel id -> DeformPercent curve + local layers = sources(stack.id, "AnimationLayer") + for _, layer in layers do + for _, cn in sources(layer.id, "AnimationCurveNode") do + for _, tgt in targets(cn.id) do + local key = tgt.prop and PROPS[tgt.prop] + if key and tgt.obj.class == "Model" and nodeOf[tgt.obj.id] then + local tr = tracks[tgt.obj.id] + if not tr then + tr = { curves = {}, defaults = {} } + tracks[tgt.obj.id] = tr + table.insert(trackOrder, tgt.obj.id) + end + if not tr.curves[key] then + local axes: { [number]: Curve } = {} + for _, s in sourcesProp(cn.id) do + if s.obj.class == "AnimationCurve" and s.prop then + local ax = if string.find(s.prop, "X$") then 1 elseif string.find(s.prop, "Y$") then 2 elseif string.find(s.prop, "Z$") then 3 else nil + local c = ax and curve(s.obj) + if ax and c then + axes[ax] = c + end + end + end + if next(axes) then + tr.curves[key] = axes + tr.defaults[key] = { pnum(cn.props, "d|X", 0), pnum(cn.props, "d|Y", 0), pnum(cn.props, "d|Z", 0) } + end + end + elseif tgt.prop == "DeformPercent" and tgt.obj.class == "Deformer" then + for _, s in sources(cn.id, "AnimationCurve") do + local c = curve(s) + if c and not morph[tgt.obj.id] then + morph[tgt.obj.id] = c + end + end + end + end + end + end + for _, id in trackOrder do + local tr = tracks[id] + local o = objects[id] + local ni = nodeOf[id] + local cs: { Curve } = {} + for _, axes in tr.curves do + for _, c in pairs(axes) do + table.insert(cs, c) + end + end + local times = sampleTimes(cs) + if #times > 0 then + local base = xprops(o) + local T, R, S = {}, {}, {} + local prevQ: { number }? = nil + for _, t in times do + local over: { [string]: { number } } = {} + for key, axes in tr.curves do + local stat = (base :: any)[key] + local v = table.clone(stat) + for ax = 1, 3 do + local c = axes[ax] + if c then + v[ax] = eval(c, t) + end + end + over[key] = v + end + local tt, rr, ss = Xform.decompose(Xform.localMatrix(xprops(o, over))) + if prevQ and rr[1] * prevQ[1] + rr[2] * prevQ[2] + rr[3] * prevQ[3] + rr[4] * prevQ[4] < 0 then + rr = { -rr[1], -rr[2], -rr[3], -rr[4] } + end + prevQ = rr + table.move(tt, 1, 3, #T + 1, T) + table.move(rr, 1, 4, #R + 1, R) + table.move(ss, 1, 3, #S + 1, S) + end + local input = f32acc(times, 1) + local interp: any = if allConstant(cs) then "STEP" else "LINEAR" + local nd = scene.nodes[ni] + local function varies(vals: { number }, comps: number, rest: { number }): boolean + for k = 0, #vals // comps - 1 do + for q = 1, comps do + if math.abs(vals[k * comps + q] - rest[q]) > 1e-6 then + return true + end + end + end + return false + end + if tr.curves.T or varies(T, 3, nd.translation or { 0, 0, 0 }) then + table.insert(anim.channels, { node = ni, path = "translation", input = input, output = f32acc(T, 3), interpolation = interp }) + end + if tr.curves.R or varies(R, 4, nd.rotation or { 0, 0, 0, 1 }) then + table.insert(anim.channels, { node = ni, path = "rotation", input = input, output = f32acc(R, 4), interpolation = interp }) + end + if tr.curves.S or varies(S, 3, nd.scale or { 1, 1, 1 }) then + table.insert(anim.channels, { node = ni, path = "scale", input = input, output = f32acc(S, 3), interpolation = interp }) + end + end + end + -- morph target weights: every node whose mesh has an animated blend shape channel + if next(morph) then + for ni, nd in scene.nodes do + local chans = nd.mesh and shapeChannels[nd.mesh] + if chans then + local cs: { Curve } = {} + for _, ch in chans do + if morph[ch.id] then + table.insert(cs, morph[ch.id]) + end + end + if #cs > 0 then + local times = sampleTimes(cs) + local out = {} + for _, t in times do + for _, ch in chans do + local c = morph[ch.id] + table.insert(out, (if c then eval(c, t) else pnum(ch.props, "DeformPercent", 0)) / 100) + end + end + local acc = f32acc(out, 1) + table.insert(anim.channels, { node = ni, path = "weights", input = f32acc(times, 1), output = acc, interpolation = if allConstant(cs) then "STEP" else "LINEAR" }) + end + end + end + end + if #anim.channels > 0 then + table.insert(scene.animations, anim) + end + end + end + + -- ------------------------------------------------------------------------------------------ meta + local header = child(root, "FBXHeaderExtension") + local creator = value(root, "Creator") or value(header, "Creator") + scene.meta.source = { + format = "fbx", + version = version, + creator = if type(creator) == "string" then creator else nil, + upAxis = upAxis, + upAxisSign = pnum(gs, "UpAxisSign", 1), + frontAxis = pnum(gs, "FrontAxis", 2), + frontAxisSign = pnum(gs, "FrontAxisSign", 1), + coordAxis = pnum(gs, "CoordAxis", 0), + coordAxisSign = pnum(gs, "CoordAxisSign", 1), + unitScaleFactor = unitScale, + originalUnitScaleFactor = pnum(gs, "OriginalUnitScaleFactor", unitScale), + frameRate = fps, + } + local _ = nodeSkin + return scene, nil +end + +return Read diff --git a/src/Formats/model/fbx/Write.luau b/src/Formats/model/fbx/Write.luau new file mode 100644 index 0000000..060af47 --- /dev/null +++ b/src/Formats/model/fbx/Write.luau @@ -0,0 +1,996 @@ +--!strict +-- model/fbx/Write: Scene -> an FBX 7.4 node tree (model/fbx/Binary.write / Ascii.write serialize it). Property types +-- follow what Blender's and the FBX SDK's readers check (ids L, ints I, doubles D, KTime L, arrays d / i / l / f). +-- Nodes -> Model (Mesh / Null / LimbNode / Camera / Light) with Lcl T / R (Euler XYZ degrees) / S; meshes -> one +-- Geometry (primitives merged; triangles, polygons, strips and fans; control points = the Scene vertices; normals +-- ByVertice, uvs and colours ByPolygonVertex IndexToDirect, materials ByPolygon); materials -> Phong Material; +-- textures -> Texture + Video (Content embedded); skins -> Skin + Cluster deformers + BindPose; morph targets -> +-- BlendShape / BlendShapeChannel / Shape; animations -> AnimationStack / Layer / CurveNode / Curve. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Xform = require("@formats/model/fbx/Xform") + +local Write = {} + +type WNode = { name: string, props: { any }, children: { WNode }?, types: string? } + +local TICKS = 46186158000 +local ORIENT_INV = { camera = { 0, 90, 0 }, light = { 90, 0, 0 } } + +local function N(name: string, types: string, props: { any }, children: { WNode }?): WNode + return { name = name, types = types, props = props, children = children } +end +local function arr(t: string, list: { number }): any + local n = #list + local d = buffer.create(n * 8) + for k = 1, n do + buffer.writef64(d, (k - 1) * 8, list[k]) + end + return { array = true, type = t, count = n, data = d } +end +-- P: name, type, label, flags, values (vt: one type character per value) +local function P(name: string, ptype: string, label: string, flags: string, vt: string, ...: any): WNode + return { name = "P", types = "SSSS" .. vt, props = { name, ptype, label, flags, ... } } +end +local function Pvec(name: string, ptype: string, label: string, v: { number }): WNode + return P(name, ptype, label, "A", "DDD", v[1], v[2], v[3]) +end +local function Pcolor(name: string, v: { number }): WNode + return P(name, "Color", "", "A", "DDD", v[1] or 0, v[2] or 0, v[3] or 0) +end +local function Pnum(name: string, v: number): WNode + return P(name, "Number", "", "A", "D", v) +end +local function Pint(name: string, v: number): WNode + return P(name, "int", "Integer", "", "I", v) +end +local function Penum(name: string, v: number): WNode + return P(name, "enum", "", "", "I", v) +end +local function Pdouble(name: string, v: number): WNode + return P(name, "double", "Number", "", "D", v) +end +local function Ptime(name: string, v: number): WNode + return P(name, "KTime", "Time", "", "L", v) +end +local function cls(name: string?, class: string): string + return (name or "") .. "\0\1" .. class +end + +local function accessorReader(acc: Types.Accessor?): ((i: number, c: number) -> number)? + if not acc then + return nil + end + return Types.Scene.reader(acc) +end + +-- primitive -> triangles / polygons as a list of corner lists (vertex indices, 0-based) +local function faces(prim: Types.Primitive): { { number } }? + local pos = prim.attributes.POSITION + if not pos then + return nil + end + local n = pos.count + local idx = accessorReader(prim.indices) + local count = if prim.indices then prim.indices.count else n + local function I(k: number): number + return if idx then idx(k, 0) else k + end + local out: { { number } } = {} + local mode = prim.mode or "triangles" + if mode == "triangles" then + for k = 0, count // 3 - 1 do + table.insert(out, { I(k * 3), I(k * 3 + 1), I(k * 3 + 2) }) + end + elseif mode == "polygons" and prim.faces then + local f = accessorReader(prim.faces) + local p = 0 + if f then + for k = 0, prim.faces.count - 1 do + local sz = f(k, 0) + if p + sz > count then + break + end + local poly = table.create(sz) + for q = 0, sz - 1 do + poly[q + 1] = I(p + q) + end + p += sz + table.insert(out, poly) + end + end + elseif mode == "triangle_strip" then + for k = 0, count - 3 do + local a, b, c = I(k), I(k + 1), I(k + 2) + if k % 2 == 1 then + a, b = b, a + end + table.insert(out, { a, b, c }) + end + elseif mode == "triangle_fan" then + for k = 1, count - 2 do + table.insert(out, { I(0), I(k), I(k + 1) }) + end + else + return nil -- points / lines: not written + end + for _, f in out do + for q, v in f do + if v < 0 or v >= n then + f[q] = 0 + end + end + end + return out +end + +function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?) + local flipV = not (opts and opts.flipV == false) + local embed = not (opts and opts.embedTextures == false) + local nextId = 1000000 + local function id(): number + nextId += 1 + return nextId + end + local objects: { WNode } = {} + local conns: { WNode } = {} + local counts: { [string]: number } = {} + local function add(class: string, node: WNode) + table.insert(objects, node) + counts[class] = (counts[class] or 0) + 1 + end + local function OO(child: number, parent: number) + table.insert(conns, N("C", "SLL", { "OO", child, parent })) + end + local function OP(child: number, parent: number, prop: string) + table.insert(conns, N("C", "SLLS", { "OP", child, parent, prop })) + end + local nodes = scene.nodes or {} + + -- ------------------------------------------------------------------------------------------ textures + local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/x-tga"] = "tga", ["image/vnd-ms.dds"] = "dds", ["image/tiff"] = "tif" } + local texIds: { [number]: number } = {} + local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model" + for ti, tex in scene.textures or {} do + local file = tex.uri or (base .. "_" .. (tex.name or tostring(ti)) .. "." .. (EXT[tex.mime or ""] or "png")) + local tname = tex.name or ("Texture" .. ti) + local vid, tid = id(), id() + local vchildren = { + N("Type", "S", { "Clip" }), + N("Properties70", "", {}, { P("Path", "KString", "XRefUrl", "", "S", file) }), + N("UseMipMap", "I", { 0 }), + N("Filename", "S", { file }), + N("RelativeFilename", "S", { file }), + } + if embed and tex.data then + table.insert(vchildren, N("Content", "R", { tex.data })) + end + add("Video", N("Video", "LSS", { vid, cls(tname, "Video"), "Clip" }, vchildren)) + local tp = { P("UseMaterial", "bool", "", "", "I", 1) } + local smp = tex.sampler + if smp and smp.wrapS == "clamp" then + table.insert(tp, Penum("WrapModeU", 1)) + end + if smp and smp.wrapT == "clamp" then + table.insert(tp, Penum("WrapModeV", 1)) + end + add("Texture", N("Texture", "LSS", { tid, cls(tname, "Texture"), "" }, { + N("Type", "S", { "TextureVideoClip" }), + N("Version", "I", { 202 }), + N("TextureName", "S", { cls(tname, "Texture") }), + N("Properties70", "", {}, tp), + N("Media", "S", { cls(tname, "Video") }), + N("FileName", "S", { file }), + N("RelativeFilename", "S", { file }), + N("ModelUVTranslation", "DD", { 0, 0 }), + N("ModelUVScaling", "DD", { 1, 1 }), + N("Texture_Alpha_Source", "S", { "None" }), + N("Cropping", "IIII", { 0, 0, 0, 0 }), + })) + OO(vid, tid) + texIds[ti] = tid + end + + -- ------------------------------------------------------------------------------------------ materials + local matIds: { [number]: number } = {} + for mi, m in scene.materials or {} do + local x = m.extras and (m.extras :: any).fbx or {} + local bc = m.baseColor or { 1, 1, 1, 1 } + local alpha = bc[4] or 1 + local rough = math.clamp(m.roughness or 1, 0.02, 1) + local shin = if type(x.shininess) == "number" then x.shininess else 2 / (rough * rough) - 2 + local em = m.emissive or { 0, 0, 0 } + local spec = if type(x.specular) == "table" then x.specular else { 0.2, 0.2, 0.2 } + local pid = id() + local props = { + Pcolor("AmbientColor", if type(x.ambient) == "table" then x.ambient else { 0, 0, 0 }), + Pnum("AmbientFactor", if type(x.ambientFactor) == "number" then x.ambientFactor else 1), + Pcolor("DiffuseColor", { bc[1], bc[2], bc[3] }), + Pnum("DiffuseFactor", 1), + Pcolor("EmissiveColor", em), + Pnum("EmissiveFactor", 1), + Pcolor("SpecularColor", spec), + Pnum("SpecularFactor", if type(x.specularFactor) == "number" then x.specularFactor else 1), + Pnum("Shininess", shin), + Pnum("ShininessExponent", shin), + Pcolor("TransparentColor", { 1, 1, 1 }), + Pnum("TransparencyFactor", 1 - alpha), + Pnum("Opacity", alpha), + Pcolor("ReflectionColor", if type(x.reflection) == "table" then x.reflection else { 0, 0, 0 }), + Pnum("ReflectionFactor", if type(x.reflectionFactor) == "number" then x.reflectionFactor else 0), + } + add("Material", N("Material", "LSS", { pid, cls(m.name or ("Material" .. mi), "Material"), "" }, { + N("Version", "I", { 102 }), + N("ShadingModel", "S", { if type(x.shadingModel) == "string" and x.shadingModel ~= "unknown" then x.shadingModel else "phong" }), + N("MultiLayer", "I", { 0 }), + N("Properties70", "", {}, props), + })) + matIds[mi] = pid + local function link(ref: Types.TextureRef?, prop: string) + local t = ref and texIds[ref.texture] + if t then + OP(t, pid, prop) + end + end + link(m.baseColorTexture, "DiffuseColor") + link(m.normalTexture, "NormalMap") + link(m.emissiveTexture, "EmissiveColor") + -- the other textures the FBX material had (specular, metalness, ... maps), under their property names + local linked = { + [m.baseColorTexture and m.baseColorTexture.texture or -1] = true, + [m.normalTexture and m.normalTexture.texture or -1] = true, + [m.emissiveTexture and m.emissiveTexture.texture or -1] = true, + } + if type(x.textures) == "table" then + local props = {} + for prop in x.textures do + table.insert(props, prop) + end + table.sort(props) + for _, prop in props do + local ti = x.textures[prop] + if type(ti) == "number" and not linked[ti] and texIds[ti] then + linked[ti] = true + OP(texIds[ti], pid, prop) + end + end + end + end + + -- ------------------------------------------------------------------------------------------ models + local modelIds: { [number]: number } = {} + local skip: { [number]: boolean } = {} + local attrHost: { [number]: number } = {} -- orientation node -> its parent node (the attribute moves there) + local parentOf: { [number]: number } = {} + for i, nd in nodes do + for _, c in nd.children or {} do + if parentOf[c] == nil and c ~= i then + parentOf[c] = i + end + end + end + local jointSet: { [number]: boolean } = {} + for _, s in scene.skins or {} do + for _, j in s.joints do + jointSet[j] = true + end + end + for i, nd in nodes do + local o = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.orientation + local p = parentOf[i] + if o and p and (nd.camera or nd.light) and #(nd.children or {}) == 0 and not nd.mesh and not nodes[p].camera and not nodes[p].light then + skip[i] = true + attrHost[i] = p + end + end + -- world matrices (rest pose) for clusters and the bind pose + local worldM: { [number]: Xform.M4 } = {} + local visiting: { [number]: boolean } = {} + local function world(i: number): Xform.M4 + if worldM[i] then + return worldM[i] + end + if visiting[i] then + return Xform.identity() + end + visiting[i] = true + local nd = nodes[i] + local l = if nd.matrix and #nd.matrix == 16 then nd.matrix else Xform.compose(nd.translation, nd.rotation, nd.scale) + local p = parentOf[i] + local w = if p then Xform.mul(world(p), l) else l + worldM[i] = w + return w + end + local function trs(nd: Types.Node): ({ number }, { number }, { number }) + if nd.matrix and #nd.matrix == 16 then + return Xform.decompose(nd.matrix) + end + return nd.translation or { 0, 0, 0 }, nd.rotation or { 0, 0, 0, 1 }, nd.scale or { 1, 1, 1 } + end + local function model(name: string, sub: string, t: { number }, r: { number }, s: { number }): number + local mid = id() + add("Model", N("Model", "LSS", { mid, cls(name, "Model"), sub }, { + N("Version", "I", { 232 }), + N("Properties70", "", {}, { + Penum("RotationOrder", 0), + Penum("InheritType", 1), + Pint("DefaultAttributeIndex", 0), + Pvec("Lcl Translation", "Lcl Translation", "", t), + Pvec("Lcl Rotation", "Lcl Rotation", "", r), + Pvec("Lcl Scaling", "Lcl Scaling", "", s), + }), + N("Shading", "C", { true }), + N("Culling", "S", { "CullingOff" }), + })) + return mid + end + local function attribute(nd: Types.Node, mid: number, nodeName: string) + if nd.camera and scene.cameras[nd.camera] then + local c = scene.cameras[nd.camera] + local aid = id() + local aspect = c.aspect or 4 / 3 + local fh = 0.612 + local fw = fh * aspect + local props + if c.type == "orthographic" then + props = { Penum("CameraProjectionType", 1), Pdouble("OrthoZoom", c.ymag or 1), Pdouble("AspectWidth", aspect * 100), Pdouble("AspectHeight", 100), Pdouble("NearPlane", c.znear or 0.1), Pdouble("FarPlane", c.zfar or 1000), Pdouble("FilmWidth", fw), Pdouble("FilmHeight", fh) } + else + local yfov = c.yfov or 0.8 + local hfov = 2 * math.atan(math.tan(yfov / 2) * aspect) + local focal = fw * 25.4 / (2 * math.tan(hfov / 2)) + props = { + Penum("CameraProjectionType", 0), + Penum("ApertureMode", 1), + P("FieldOfView", "FieldOfView", "", "A", "D", hfov * 180 / math.pi), + P("FocalLength", "Number", "", "A", "D", focal), + Pdouble("FilmWidth", fw), + Pdouble("FilmHeight", fh), + Penum("AspectRatioMode", 0), + Pdouble("AspectWidth", aspect * 100), + Pdouble("AspectHeight", 100), + Pdouble("NearPlane", c.znear or 0.1), + Pdouble("FarPlane", c.zfar or 1000), + } + end + add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(c.name or nodeName, "NodeAttribute"), "Camera" }, { + N("Properties70", "", {}, props), + N("TypeFlags", "S", { "Camera" }), + N("GeometryVersion", "I", { 124 }), + })) + OO(aid, mid) + elseif nd.light and scene.lights[nd.light] then + local l = scene.lights[nd.light] + local aid = id() + local lt = if l.type == "directional" then 1 elseif l.type == "spot" then 2 else 0 + local props = { + Penum("LightType", lt), + Pcolor("Color", l.color or { 1, 1, 1 }), + Pnum("Intensity", (l.intensity or 1) * 100), + P("CastLight", "bool", "", "", "I", 1), + } + if lt == 2 then + table.insert(props, Pnum("InnerAngle", (l.innerCone or 0) * 360 / math.pi)) + table.insert(props, Pnum("OuterAngle", (l.outerCone or math.pi / 4) * 360 / math.pi)) + end + if l.range then + table.insert(props, P("EnableFarAttenuation", "bool", "", "", "I", 1)) + table.insert(props, Pnum("FarAttenuationEnd", l.range)) + end + add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(l.name or nodeName, "NodeAttribute"), "Light" }, { + N("Properties70", "", {}, props), + N("TypeFlags", "S", { "Light" }), + N("GeometryVersion", "I", { 124 }), + })) + OO(aid, mid) + end + end + for i, nd in nodes do + if not skip[i] then + local t, r, s = trs(nd) + local euler = Xform.eulerXYZ(r) + local ftype = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.type + local sub = if nd.mesh then "Mesh" elseif jointSet[i] or ftype == "LimbNode" then "LimbNode" else "Null" + -- an orientation child folded into this node gives it its attribute + local folded: number? = nil + for c, host in pairs(attrHost) do -- pairs: a sparse integer map (compat __iter takes it for an array) + if host == i then + folded = c + end + end + if not nd.mesh and folded then + sub = if nodes[folded].camera then "Camera" else "Light" + end + local mid = model(nd.name or ("Node" .. i), sub, t, euler, s) + modelIds[i] = mid + if sub == "LimbNode" then + local aid = id() + add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(nd.name, "NodeAttribute"), "LimbNode" }, { N("TypeFlags", "S", { "Skeleton" }) })) + OO(aid, mid) + end + if folded then + attribute(nodes[folded], mid, nd.name or "") + end + if nd.camera or nd.light then + -- a glTF-oriented camera / light: an FBX-oriented child model carries it + local kind = if nd.camera then "camera" else "light" + local cmid = model((nd.name or "") .. "_" .. kind, if nd.camera then "Camera" else "Light", { 0, 0, 0 }, ORIENT_INV[kind], { 1, 1, 1 }) + OO(cmid, mid) + attribute(nd, cmid, nd.name or "") + end + end + end + for i in nodes do + local mid = modelIds[i] + if mid then + local p = parentOf[i] + local pm = p and modelIds[p] + OO(mid, pm or 0) + end + end + + -- ------------------------------------------------------------------------------------------ geometry + local geoIds: { [number]: number } = {} + local geoSlots: { [number]: { number } } = {} -- mesh -> material indices by slot + local geoVerts: { [number]: { { prim: Types.Primitive, offset: number } } } = {} + local geoChannels: any = {} -- mesh index -> blend shape channel ids (for weights animation) + local geoCount: { [number]: number } = {} + local function geometry(mi: number): number? + if geoIds[mi] then + return geoIds[mi] + end + local mesh = scene.meshes[mi] + if not mesh then + return nil + end + local V, PVI, NRM, MATS = {}, {}, {}, {} + local UV: { [number]: { number } } = {} + local UVI: { [number]: { number } } = {} + local COL: { [number]: { number } } = {} + local COLI: { [number]: { number } } = {} + local slots: { number } = {} + local slotOf: { [number]: number } = {} + local hasN = false + local nuv, ncol = 0, 0 + for _, prim in mesh.primitives do + for k = 0, 7 do + if prim.attributes["TEXCOORD_" .. k] then + nuv = math.max(nuv, k + 1) + end + if prim.attributes["COLOR_" .. k] then + ncol = math.max(ncol, k + 1) + end + end + if prim.attributes.NORMAL then + hasN = true + end + end + for k = 1, nuv do + UV[k], UVI[k] = {}, {} + end + for k = 1, ncol do + COL[k], COLI[k] = {}, {} + end + local layout = {} + local offset = 0 + for _, prim in mesh.primitives do + local fs = faces(prim) + local pos = prim.attributes.POSITION + local R = accessorReader(pos) + if fs and R and pos then + table.insert(layout, { prim = prim, offset = offset }) + local n = pos.count + for v = 0, n - 1 do + table.insert(V, R(v, 0)) + table.insert(V, R(v, 1)) + table.insert(V, R(v, 2)) + end + local NR = accessorReader(prim.attributes.NORMAL) + if hasN then + for v = 0, n - 1 do + if NR then + table.insert(NRM, NR(v, 0)) + table.insert(NRM, NR(v, 1)) + table.insert(NRM, NR(v, 2)) + else + table.insert(NRM, 0) + table.insert(NRM, 0) + table.insert(NRM, 1) + end + end + end + local uvBase: { number } = {} + for k = 1, nuv do + uvBase[k] = #UV[k] // 2 + local T = accessorReader(prim.attributes["TEXCOORD_" .. (k - 1)]) + for v = 0, n - 1 do + local u, w = 0, 0 + if T then + u, w = T(v, 0), T(v, 1) + end + table.insert(UV[k], u) + table.insert(UV[k], if flipV then 1 - w else w) + end + end + local colBase: { number } = {} + for k = 1, ncol do + colBase[k] = #COL[k] // 4 + local acc = prim.attributes["COLOR_" .. (k - 1)] + local C = accessorReader(acc) + local comps = acc and acc.components or 4 + for v = 0, n - 1 do + table.insert(COL[k], if C then C(v, 0) else 1) + table.insert(COL[k], if C then C(v, 1) else 1) + table.insert(COL[k], if C then C(v, 2) else 1) + table.insert(COL[k], if C and comps >= 4 then C(v, 3) else 1) + end + end + local mat = prim.material or 0 + local slot = slotOf[mat] + if slot == nil then + table.insert(slots, mat) + slot = #slots - 1 + slotOf[mat] = slot + end + for _, f in fs do + for q, v in f do + local cp = v + offset + table.insert(PVI, if q == #f then -cp - 1 else cp) + for k = 1, nuv do + table.insert(UVI[k], uvBase[k] + v) + end + for k = 1, ncol do + table.insert(COLI[k], colBase[k] + v) + end + end + table.insert(MATS, slot) + end + offset += n + end + end + if #PVI == 0 then + return nil + end + local gid = id() + local ch: { WNode } = { + N("Properties70", "", {}, {}), + N("GeometryVersion", "I", { 124 }), + N("Vertices", "", { arr("d", V) }), + N("PolygonVertexIndex", "", { arr("i", PVI) }), + } + local layer0: { WNode } = { N("Version", "I", { 100 }) } + if hasN then + table.insert(ch, N("LayerElementNormal", "I", { 0 }, { + N("Version", "I", { 101 }), + N("Name", "S", { "" }), + N("MappingInformationType", "S", { "ByVertice" }), + N("ReferenceInformationType", "S", { "Direct" }), + N("Normals", "", { arr("d", NRM) }), + })) + table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementNormal" }), N("TypedIndex", "I", { 0 }) })) + end + local extraLayers: { WNode } = {} + local uvNames = mesh.extras and (mesh.extras :: any).fbx and (mesh.extras :: any).fbx.uvSets or {} + for k = 1, nuv do + table.insert(ch, N("LayerElementUV", "I", { k - 1 }, { + N("Version", "I", { 101 }), + N("Name", "S", { if type(uvNames[k]) == "string" then uvNames[k] else (if k == 1 then "UVMap" else "UVMap" .. k) }), + N("MappingInformationType", "S", { "ByPolygonVertex" }), + N("ReferenceInformationType", "S", { "IndexToDirect" }), + N("UV", "", { arr("d", UV[k]) }), + N("UVIndex", "", { arr("i", UVI[k]) }), + })) + local le = N("LayerElement", "", {}, { N("Type", "S", { "LayerElementUV" }), N("TypedIndex", "I", { k - 1 }) }) + if k == 1 then + table.insert(layer0, le) + else + table.insert(extraLayers, N("Layer", "I", { k - 1 }, { N("Version", "I", { 100 }), le })) + end + end + for k = 1, ncol do + table.insert(ch, N("LayerElementColor", "I", { k - 1 }, { + N("Version", "I", { 101 }), + N("Name", "S", { "Col" .. (if k > 1 then tostring(k) else "") }), + N("MappingInformationType", "S", { "ByPolygonVertex" }), + N("ReferenceInformationType", "S", { "IndexToDirect" }), + N("Colors", "", { arr("d", COL[k]) }), + N("ColorIndex", "", { arr("i", COLI[k]) }), + })) + if k == 1 then + table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementColor" }), N("TypedIndex", "I", { 0 }) })) + end + end + local anyMat = false + for _, m in slots do + if m ~= 0 and matIds[m] then + anyMat = true + end + end + if anyMat then + local allSame = #slots == 1 + table.insert(ch, N("LayerElementMaterial", "I", { 0 }, { + N("Version", "I", { 101 }), + N("Name", "S", { "" }), + N("MappingInformationType", "S", { if allSame then "AllSame" else "ByPolygon" }), + N("ReferenceInformationType", "S", { "IndexToDirect" }), + N("Materials", "", { arr("i", if allSame then { 0 } else MATS) }), + })) + table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementMaterial" }), N("TypedIndex", "I", { 0 }) })) + end + table.insert(ch, N("Layer", "I", { 0 }, layer0)) + for _, l in extraLayers do + table.insert(ch, l) + end + add("Geometry", N("Geometry", "LSS", { gid, cls(mesh.name or ("Mesh" .. mi), "Geometry"), "Mesh" }, ch)) + geoIds[mi] = gid + geoSlots[mi] = if anyMat then slots else {} + geoVerts[mi] = layout + geoCount[mi] = offset + -- morph targets + local prims = mesh.primitives + local ntargets = 0 + for _, l in layout do + ntargets = math.max(ntargets, if l.prim.targets then #(l.prim.targets :: any) else 0) + end + if ntargets > 0 then + local bsid = id() + add("Deformer", N("Deformer", "LSS", { bsid, cls(mesh.name, "Deformer"), "BlendShape" }, { N("Version", "I", { 100 }) })) + OO(bsid, gid) + local names = mesh.extras and (mesh.extras :: any).targetNames or {} + for t = 1, ntargets do + local IDX, DV, DN = {}, {}, {} + local anyN = false + for _, l in layout do + local tg = l.prim.targets and (l.prim.targets :: any)[t] + if tg and tg.NORMAL then + anyN = true + end + end + for _, l in layout do + local tg = l.prim.targets and (l.prim.targets :: any)[t] + local TP = tg and accessorReader(tg.POSITION) + local TN = tg and accessorReader(tg.NORMAL) + if TP then + for v = 0, l.prim.attributes.POSITION.count - 1 do + local x, y, z = TP(v, 0), TP(v, 1), TP(v, 2) + local nx, ny, nz = 0, 0, 0 + if TN then + nx, ny, nz = TN(v, 0), TN(v, 1), TN(v, 2) + end + if x ~= 0 or y ~= 0 or z ~= 0 or nx ~= 0 or ny ~= 0 or nz ~= 0 then + table.insert(IDX, l.offset + v) + table.insert(DV, x) + table.insert(DV, y) + table.insert(DV, z) + if anyN then + table.insert(DN, nx) + table.insert(DN, ny) + table.insert(DN, nz) + end + end + end + end + end + local tname = if type(names[t]) == "string" then names[t] else ("Target" .. t) + local chid, shid = id(), id() + local w = mesh.weights and mesh.weights[t] or 0 + add("Deformer", N("Deformer", "LSS", { chid, cls(tname, "SubDeformer"), "BlendShapeChannel" }, { + N("Version", "I", { 100 }), + N("DeformPercent", "D", { w * 100 }), + N("FullWeights", "", { arr("d", { 100 }) }), + N("Properties70", "", {}, { Pnum("DeformPercent", w * 100) }), + })) + local shch = { N("Version", "I", { 100 }), N("Indexes", "", { arr("i", IDX) }), N("Vertices", "", { arr("d", DV) }) } + if anyN then + table.insert(shch, N("Normals", "", { arr("d", DN) })) + end + add("Geometry", N("Geometry", "LSS", { shid, cls(tname, "Geometry"), "Shape" }, shch)) + OO(chid, bsid) + OO(shid, chid) + local gc: any = geoChannels + gc[mi] = gc[mi] or {} + gc[mi][t] = chid + end + end + local _ = prims + return gid + end + + local poseNodes: { WNode } = {} + local posed: { [number]: boolean } = {} + local function pose(mid: number, m: Xform.M4) + if posed[mid] then + return + end + posed[mid] = true + table.insert(poseNodes, N("PoseNode", "", {}, { N("Node", "L", { mid }), N("Matrix", "", { arr("d", m) }) })) + end + local skinned: { [string]: boolean } = {} + for i, nd in nodes do + local mid = modelIds[i] + if nd.mesh and mid then + local gid = geometry(nd.mesh) + if gid then + OO(gid, mid) + for _, m in geoSlots[nd.mesh] do + local pm = matIds[m] + if pm then + OO(pm, mid) + end + end + -- skin: one Skin per (geometry, skin) + local skin = nd.skin and scene.skins[nd.skin] + local key = tostring(gid) .. ":" .. tostring(nd.skin) + if skin and not skinned[key] then + skinned[key] = true + local sid = id() + add("Deformer", N("Deformer", "LSS", { sid, cls(nd.name, "Deformer"), "Skin" }, { N("Version", "I", { 101 }), N("Link_DeformAcuracy", "D", { 50 }) })) + OO(sid, gid) + local meshWorld = world(i) + pose(mid, meshWorld) + local ibm = accessorReader(skin.inverseBindMatrices) + -- per joint: control points and weights + local perJoint: { { idx: { number }, w: { number } } } = {} + for j in skin.joints do + perJoint[j] = { idx = {}, w = {} } + end + for _, l in geoVerts[nd.mesh] do + local J = accessorReader(l.prim.attributes.JOINTS_0) + local W = accessorReader(l.prim.attributes.WEIGHTS_0) + if J and W then + for v = 0, l.prim.attributes.POSITION.count - 1 do + for q = 0, 3 do + local j, w = J(v, q), W(v, q) + local pj = perJoint[j + 1] + if w > 0 and pj then + table.insert(pj.idx, l.offset + v) + table.insert(pj.w, w) + end + end + end + end + end + for j, ji in skin.joints do + local jm = modelIds[ji] + if jm then + local IB = Xform.identity() + if ibm and skin.inverseBindMatrices and j <= skin.inverseBindMatrices.count then + for k = 1, 16 do + IB[k] = ibm(j - 1, k - 1) + end + end + local inv = Xform.inverse(IB) or Xform.identity() + local link = Xform.mul(meshWorld, inv) + local cid = id() + add("Deformer", N("Deformer", "LSS", { cid, cls(nodes[ji].name, "SubDeformer"), "Cluster" }, { + N("Version", "I", { 100 }), + N("UserData", "SS", { "", "" }), + N("Indexes", "", { arr("i", perJoint[j].idx) }), + N("Weights", "", { arr("d", perJoint[j].w) }), + N("Transform", "", { arr("d", meshWorld) }), + N("TransformLink", "", { arr("d", link) }), + })) + OO(cid, sid) + OO(jm, cid) + pose(jm, link) + end + end + end + end + end + end + if #poseNodes > 0 then + local pch = { N("Type", "S", { "BindPose" }), N("Version", "I", { 100 }), N("NbPoseNodes", "I", { #poseNodes }) } + for _, pn in poseNodes do + table.insert(pch, pn) + end + add("Pose", N("Pose", "LSS", { id(), cls("BindPose", "Pose"), "BindPose" }, pch)) + end + + -- ------------------------------------------------------------------------------------------ animations + local tmin, tmax = math.huge, -math.huge + local function curveNode(name: string, layer: number, target: number, prop: string, comps: { { number } }, times: { number }, labels: { string }, step: boolean) + local cnid = id() + local p = {} + for k, lab in labels do + table.insert(p, Pnum("d|" .. lab, comps[k][1] or 0)) + end + add("AnimationCurveNode", N("AnimationCurveNode", "LSS", { cnid, cls(name, "AnimCurveNode"), "" }, { N("Properties70", "", {}, p) })) + OO(cnid, layer) + OP(cnid, target, prop) + local ticks = table.create(#times, 0) + for k, t in times do + ticks[k] = math.floor(t * TICKS + 0.5) + end + for k, lab in labels do + local cid = id() + local df = buffer.create(32) + buffer.writeu32(df, 8, 218434821) + local dfa = { array = true, type = "f", count = 4, data = buffer.create(32) } + buffer.writef64(dfa.data, 16, buffer.readf32(df, 8)) + add("AnimationCurve", N("AnimationCurve", "LSS", { cid, cls("", "AnimCurve"), "" }, { + N("Default", "D", { comps[k][1] or 0 }), + N("KeyVer", "I", { 4009 }), + N("KeyTime", "", { arr("l", ticks) }), + N("KeyValueFloat", "", { arr("f", comps[k]) }), + N("KeyAttrFlags", "", { arr("i", { if step then 0x00000002 else 0x00000104 }) }), + N("KeyAttrDataFloat", "", { dfa }), + N("KeyAttrRefCount", "", { arr("i", { #times }) }), + })) + OP(cid, cnid, "d|" .. lab) + end + end + local PATH = { translation = { "T", "Lcl Translation", 3 }, rotation = { "R", "Lcl Rotation", 4 }, scale = { "S", "Lcl Scaling", 3 } } + for ai, anim in scene.animations or {} do + local stid, lid = id(), id() + local astart, astop = math.huge, -math.huge + local layerNodes = {} + for _, ch in anim.channels do + local mid = modelIds[ch.node] + local IN = accessorReader(ch.input) + local OUT = accessorReader(ch.output) + local spec = PATH[ch.path] + if IN and OUT and ch.input.count > 0 and mid and (spec or ch.path == "weights") then + local n = ch.input.count + local times = table.create(n, 0) + for k = 0, n - 1 do + times[k + 1] = IN(k, 0) + astart, astop = math.min(astart, times[k + 1]), math.max(astop, times[k + 1]) + end + local cubic = ch.interpolation == "CUBICSPLINE" + local step = ch.interpolation == "STEP" + if spec then + local comps = spec[3] + local function val(k: number, c: number): number + local e = if cubic then k * 3 + 1 else k + if e >= ch.output.count then + return 0 + end + return OUT(e, c) + end + local X, Y, Z = table.create(n, 0), table.create(n, 0), table.create(n, 0) + local prev: { number }? = nil + for k = 0, n - 1 do + local v + if comps == 4 then + local q = { val(k, 0), val(k, 1), val(k, 2), val(k, 3) } + local ql = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + if ql > 0 then + q = { q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql } + else + q = { 0, 0, 0, 1 } + end + v = Xform.eulerXYZ(q) + if prev then + for a = 1, 3 do + while v[a] - prev[a] > 180 do + v[a] -= 360 + end + while v[a] - prev[a] < -180 do + v[a] += 360 + end + end + end + prev = v + else + v = { val(k, 0), val(k, 1), val(k, 2) } + end + X[k + 1], Y[k + 1], Z[k + 1] = v[1], v[2], v[3] + end + table.insert(layerNodes, { spec[1], lid, mid, spec[2], { X, Y, Z }, times, { "X", "Y", "Z" }, step }) + else + -- weights: one DeformPercent curve per blend shape channel of the node's mesh + local nd = nodes[ch.node] + local gc: any = geoChannels + local chans = nd.mesh and gc[nd.mesh] + if chans then + local nt = #chans + for t = 1, nt do + local vals = table.create(n, 0) + for k = 0, n - 1 do + local e = if cubic then (k * 3 + 1) * nt + (t - 1) else k * nt + (t - 1) + vals[k + 1] = if e < ch.output.count then OUT(e, 0) * 100 else 0 + end + table.insert(layerNodes, { "DeformPercent", lid, chans[t], "DeformPercent", { vals }, times, { "DeformPercent" }, step }) + end + end + end + end + end + if astart > astop then + astart, astop = 0, 0 + end + tmin, tmax = math.min(tmin, astart), math.max(tmax, astop) + add("AnimationStack", N("AnimationStack", "LSS", { stid, cls(if anim.name and anim.name ~= "" then anim.name else ("Animation" .. ai), "AnimStack"), "" }, { + N("Properties70", "", {}, { + Ptime("LocalStart", math.floor(astart * TICKS + 0.5)), + Ptime("LocalStop", math.floor(astop * TICKS + 0.5)), + Ptime("ReferenceStart", math.floor(astart * TICKS + 0.5)), + Ptime("ReferenceStop", math.floor(astop * TICKS + 0.5)), + }), + })) + add("AnimationLayer", N("AnimationLayer", "LSS", { lid, cls("BaseLayer", "AnimLayer"), "" }, { N("Properties70", "", {}, {}) })) + OO(lid, stid) + for _, ln in layerNodes do + curveNode(ln[1], ln[2], ln[3], ln[4], ln[5], ln[6], ln[7], ln[8]) + end + end + if tmin > tmax then + tmin, tmax = 0, 0 + end + + -- ------------------------------------------------------------------------------------------ document + local meta = scene.meta or {} + local src = type(meta.source) == "table" and meta.source or {} + local up = if meta.up == "z" then 2 else 1 + local upSign, front, frontSign, coord, coordSign = 1, 2, 1, 0, 1 + if up == 2 then + front, frontSign = 1, -1 + end + if src.format == "fbx" and src.upAxis == up then + upSign = src.upAxisSign or upSign + front, frontSign = src.frontAxis or front, src.frontAxisSign or frontSign + coord, coordSign = src.coordAxis or coord, src.coordAxisSign or coordSign + end + local unitScale = if type(meta.unit) == "number" and meta.unit > 0 then meta.unit * 100 else 1 + local creator = opts and opts.creator or "formats-luau" + local defs: { WNode } = { N("Version", "I", { 100 }) } + local total = 1 + local CLASSES = { "Model", "Geometry", "Material", "Texture", "Video", "Deformer", "Pose", "NodeAttribute", "AnimationStack", "AnimationLayer", "AnimationCurveNode", "AnimationCurve" } + for _, c in CLASSES do + total += counts[c] or 0 + end + table.insert(defs, N("Count", "I", { total })) + table.insert(defs, N("ObjectType", "S", { "GlobalSettings" }, { N("Count", "I", { 1 }) })) + for _, c in CLASSES do + if counts[c] then + table.insert(defs, N("ObjectType", "S", { c }, { N("Count", "I", { counts[c] }) })) + end + end + local docId = id() + local root: WNode = { name = "", props = {}, children = { + N("FBXHeaderExtension", "", {}, { + N("FBXHeaderVersion", "I", { 1003 }), + N("FBXVersion", "I", { opts and opts.version or 7400 }), + N("CreationTimeStamp", "", {}, { + N("Version", "I", { 1000 }), N("Year", "I", { 1970 }), N("Month", "I", { 1 }), N("Day", "I", { 1 }), + N("Hour", "I", { 0 }), N("Minute", "I", { 0 }), N("Second", "I", { 0 }), N("Millisecond", "I", { 0 }), + }), + N("Creator", "S", { creator }), + }), + N("FileId", "R", { buffer.fromstring("(\179*\235\182$\204\194\191\200\176*\169+\252\241") }), + N("CreationTime", "S", { "1970-01-01 10:00:00:000" }), + N("Creator", "S", { creator }), + N("GlobalSettings", "", {}, { + N("Version", "I", { 1000 }), + N("Properties70", "", {}, { + Pint("UpAxis", up), Pint("UpAxisSign", upSign), Pint("FrontAxis", front), Pint("FrontAxisSign", frontSign), + Pint("CoordAxis", coord), Pint("CoordAxisSign", coordSign), Pint("OriginalUpAxis", up), Pint("OriginalUpAxisSign", upSign), + Pdouble("UnitScaleFactor", unitScale), Pdouble("OriginalUnitScaleFactor", unitScale), + P("AmbientColor", "ColorRGB", "Color", "", "DDD", 0, 0, 0), + P("DefaultCamera", "KString", "", "", "S", "Producer Perspective"), + Penum("TimeMode", 6), + Penum("TimeProtocol", 2), + Penum("SnapOnFrameMode", 0), + Ptime("TimeSpanStart", math.floor(tmin * TICKS + 0.5)), + Ptime("TimeSpanStop", math.floor(tmax * TICKS + 0.5)), + Pdouble("CustomFrameRate", -1), + }), + }), + N("Documents", "", {}, { + N("Count", "I", { 1 }), + N("Document", "LSS", { docId, "Scene", "Scene" }, { + N("Properties70", "", {}, { P("SourceObject", "object", "", "", ""), P("ActiveAnimStackName", "KString", "", "", "S", "") }), + N("RootNode", "L", { 0 }), + }), + }), + N("References", "", {}, {}), + N("Definitions", "", {}, defs), + N("Objects", "", {}, objects), + N("Connections", "", {}, conns), + N("Takes", "", {}, { N("Current", "S", { "" }) }), + } } + local _ = Err + return root, nil +end + +return Write diff --git a/src/Formats/model/fbx/Xform.luau b/src/Formats/model/fbx/Xform.luau new file mode 100644 index 0000000..a4d734d --- /dev/null +++ b/src/Formats/model/fbx/Xform.luau @@ -0,0 +1,200 @@ +--!strict +-- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): the local matrix of a Model +-- node T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1, Euler rotations in degrees in the six +-- orders, column-major 4x4 matrices (flat arrays of 16, translation at 13..15 as glTF and FBX store them), inverse, +-- TRS decomposition (quaternion x, y, z, w) and Euler XYZ from a quaternion (the writer). +local Xform = {} + +export type M4 = { number } + +local rad = math.pi / 180 + +function Xform.identity(): M4 + return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } +end + +function Xform.mul(a: M4, b: M4): M4 + local m = table.create(16, 0) + for col = 0, 3 do + for row = 0, 3 do + m[col * 4 + row + 1] = a[row + 1] * b[col * 4 + 1] + a[4 + row + 1] * b[col * 4 + 2] + a[8 + row + 1] * b[col * 4 + 3] + a[12 + row + 1] * b[col * 4 + 4] + end + end + return m +end + +function Xform.translate(x: number, y: number, z: number): M4 + return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 } +end + +function Xform.scale(x: number, y: number, z: number): M4 + return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 } +end + +local function rx(a: number): M4 + local c, s = math.cos(a), math.sin(a) + return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 } +end +local function ry(a: number): M4 + local c, s = math.cos(a), math.sin(a) + return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 } +end +local function rz(a: number): M4 + local c, s = math.cos(a), math.sin(a) + return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } +end + +-- FBX RotationOrder: 0 XYZ (R = Rz * Ry * Rx: X applied first), 1 XZY, 2 YZX, 3 YXZ, 4 ZXY, 5 ZYX, 6 spheric (= XYZ) +local ORDERS = { [0] = "xyz", "xzy", "yzx", "yxz", "zxy", "zyx", "xyz" } +function Xform.euler(x: number, y: number, z: number, order: number?): M4 + local o = ORDERS[order or 0] or "xyz" + local R = { x = rx(x * rad), y = ry(y * rad), z = rz(z * rad) } + local a, b, c = string.sub(o, 1, 1), string.sub(o, 2, 2), string.sub(o, 3, 3) + return Xform.mul(R[c], Xform.mul(R[b], R[a])) +end + +-- inverse of an affine matrix (general 3x3 part) | nil when singular +function Xform.inverse(m: M4): M4? + local a, b, c = m[1], m[5], m[9] + local d, e, f = m[2], m[6], m[10] + local g, h, i = m[3], m[7], m[11] + local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g + local det = a * A + b * B + c * C + if det == 0 or det ~= det then + return nil + end + local k = 1 / det + local r = { + A * k, B * k, C * k, 0, + -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0, + (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0, + 0, 0, 0, 1, + } + local tx, ty, tz = m[13], m[14], m[15] + r[13] = -(r[1] * tx + r[5] * ty + r[9] * tz) + r[14] = -(r[2] * tx + r[6] * ty + r[10] * tz) + r[15] = -(r[3] * tx + r[7] * ty + r[11] * tz) + return r +end + +-- the local matrix of a node from its (already defaulted) FBX properties p: vectors of 3 numbers +export type Props = { + T: { number }, R: { number }, S: { number }, + Rpre: { number }, Rpost: { number }, Roff: { number }, Rp: { number }, Soff: { number }, Sp: { number }, + order: number, +} +local function isZero(v: { number }): boolean + return v[1] == 0 and v[2] == 0 and v[3] == 0 +end +function Xform.localMatrix(p: Props): M4 + local m = Xform.translate(p.T[1] + p.Roff[1] + p.Rp[1], p.T[2] + p.Roff[2] + p.Rp[2], p.T[3] + p.Roff[3] + p.Rp[3]) + if not isZero(p.Rpre) then + m = Xform.mul(m, Xform.euler(p.Rpre[1], p.Rpre[2], p.Rpre[3], 0)) + end + m = Xform.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order)) + if not isZero(p.Rpost) then + local post = Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0) + -- the inverse of a rotation is its transpose + local tr = { post[1], post[5], post[9], 0, post[2], post[6], post[10], 0, post[3], post[7], post[11], 0, 0, 0, 0, 1 } + m = Xform.mul(m, tr) + end + m = Xform.mul(m, Xform.translate(-p.Rp[1] + p.Soff[1] + p.Sp[1], -p.Rp[2] + p.Soff[2] + p.Sp[2], -p.Rp[3] + p.Soff[3] + p.Sp[3])) + m = Xform.mul(m, Xform.scale(p.S[1], p.S[2], p.S[3])) + if not isZero(p.Sp) then + m = Xform.mul(m, Xform.translate(-p.Sp[1], -p.Sp[2], -p.Sp[3])) + end + return m +end + +-- quaternion (x, y, z, w) of a pure rotation matrix +local function quat(m: M4): { number } + local m00, m01, m02 = m[1], m[5], m[9] + local m10, m11, m12 = m[2], m[6], m[10] + local m20, m21, m22 = m[3], m[7], m[11] + local tr = m00 + m11 + m22 + local x, y, z, w + if tr > 0 then + local s = math.sqrt(tr + 1) * 2 + w, x, y, z = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s + elseif m00 > m11 and m00 > m22 then + local s = math.sqrt(math.max(1 + m00 - m11 - m22, 1e-30)) * 2 + w, x, y, z = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s + elseif m11 > m22 then + local s = math.sqrt(math.max(1 + m11 - m00 - m22, 1e-30)) * 2 + w, x, y, z = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s + else + local s = math.sqrt(math.max(1 + m22 - m00 - m11, 1e-30)) * 2 + w, x, y, z = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4 + end + local n = math.sqrt(x * x + y * y + z * z + w * w) + if n == 0 or n ~= n then + return { 0, 0, 0, 1 } + end + return { x / n, y / n, z / n, w / n } +end +Xform.quat = quat + +-- decompose(m) -> translation, rotation (quaternion), scale (a negative determinant flips the x scale) +function Xform.decompose(m: M4): ({ number }, { number }, { number }) + local t = { m[13], m[14], m[15] } + local sx = math.sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3]) + local sy = math.sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7]) + local sz = math.sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11]) + local det = m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3]) + if det < 0 then + sx = -sx + end + local ix = if sx ~= 0 then 1 / sx else 0 + local iy = if sy ~= 0 then 1 / sy else 0 + local iz = if sz ~= 0 then 1 / sz else 0 + local r = { m[1] * ix, m[2] * ix, m[3] * ix, 0, m[5] * iy, m[6] * iy, m[7] * iy, 0, m[9] * iz, m[10] * iz, m[11] * iz, 0, 0, 0, 0, 1 } + return t, quat(r), { sx, sy, sz } +end + +-- the rotation matrix of a quaternion +function Xform.fromQuat(q: { number }): M4 + local x, y, z, w = q[1], q[2], q[3], q[4] + local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z + return { + 1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0, + 2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0, + 2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0, + 0, 0, 0, 1, + } +end + +-- Euler XYZ degrees (R = Rz * Ry * Rx) of a quaternion +function Xform.eulerXYZ(q: { number }): { number } + local m = Xform.fromQuat(q) + -- m[3] = r20 = -sin(y) + local sy = -m[3] + sy = math.clamp(sy, -1, 1) + local y = math.asin(sy) + local x, z + if math.abs(sy) < 0.9999999 then + x = math.atan2(m[7], m[11]) + z = math.atan2(m[2], m[1]) + else + x = math.atan2(-m[10], m[6]) + z = 0 + end + return { x / rad, y / rad, z / rad } +end + +-- TRS -> matrix (glTF semantics) +function Xform.compose(t: { number }?, r: { number }?, s: { number }?): M4 + local m = if r then Xform.fromQuat(r) else Xform.identity() + if s then + for k = 0, 2 do + m[k * 4 + 1] *= s[k + 1] + m[k * 4 + 2] *= s[k + 1] + m[k * 4 + 3] *= s[k + 1] + end + end + if t then + m[13], m[14], m[15] = t[1], t[2], t[3] + end + return m +end + +return Xform diff --git a/src/Formats/model/fbx/init.luau b/src/Formats/model/fbx/init.luau new file mode 100644 index 0000000..27e1983 --- /dev/null +++ b/src/Formats/model/fbx/init.luau @@ -0,0 +1,177 @@ +--!strict +-- model/fbx: Autodesk FBX 7.x, binary (7.0 - 7.7: 32-bit records before 7500, 64-bit after; zlib-compressed arrays +-- through codecs/Deflate) and ASCII. New code, from the format as reverse engineered by Blender's io_scene_fbx and +-- assimp's FBX importer, and the FBX SDK's documentation of the transform model. +-- Reads: the node tree (Fbx.tree), then Objects / Connections -> Scene: Model nodes with the full transform (Lcl +-- T / R / S, pre / post rotation, rotation / scaling pivots and offsets, the six rotation orders; geometric transforms +-- baked into the mesh), meshes (polygons fan-triangulated by default or kept as "polygons"; layer elements for normals, +-- tangents, uvs (TEXCOORD_n, flipped to glTF's top-left origin), colours and materials in every mapping and reference +-- mode), Phong / Lambert materials (-> PBR approximations + the Phong values in extras.fbx) and 3ds Max Physical PBR +-- materials, textures (embedded Video content kept encoded, or the file through opts.resolve / opts.files), skins +-- (clusters -> JOINTS_0 / WEIGHTS_0, the 4 strongest influences, inverse bind matrices), blend shapes (morph targets +-- + weights), animation stacks (curves on T / R / S and DeformPercent sampled at their keys, or opts.sampleRate, and +-- turned into glTF translation / rotation / scale / weights channels), cameras and lights (on child nodes oriented for +-- glTF's -Z forward axis), the axis system and unit (meta.up, meta.unit = UnitScaleFactor / 100; nothing is rotated). +-- Writes binary FBX 7.4 (or ASCII with opts.ascii): the node hierarchy, meshes (one Geometry per mesh, its primitives +-- as material slots; normals, uvs, colours), Phong materials (extras.fbx when present, else from the PBR fields), +-- textures (embedded as Video content when texture.data is set, else a file reference), skins (Skin / Cluster + +-- BindPose), morph targets (BlendShape channels) and animations (one stack per animation; rotation channels as Euler +-- XYZ curves). Readable by assimp, Blender and the FBX SDK. +-- Not supported: FBX 6.x and older (UNSUPPORTED), NURBS / patch / line geometry (skipped), constraints, layered +-- animation blending (the first layer that animates a property wins), cubic curve tangents on write (keys are linear). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Binary = require("@formats/model/fbx/Binary") +local Ascii = require("@formats/model/fbx/Ascii") +local Read = require("@formats/model/fbx/Read") +local Write = require("@formats/model/fbx/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Fbx = { + name = "fbx", + category = "model", + extensions = { "fbx" }, + mime = { "application/vnd.autodesk.fbx", "model/fbx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "core/Base64" }, + caps = { decode = true, encode = true, binary = true, ascii = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives + flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's convention) + sampleRate: number?, -- also sample animation curves at this many samples per second (default: their keys only) + resolve: ((uri: string) -> any)?, -- external texture files (the api sets it for paths) + files: { [string]: any }?, -- or: the files by name + maxBytes: number?, -- refuse arrays over this many bytes in total (default 2^30) + maxVertices: number?, -- refuse more polygon corners (default 2^25) +} +export type EncodeOptions = { + ascii: boolean?, -- write ASCII FBX (default binary) + version: number?, -- 7400 (default) or 7500 (64-bit records) + flipV: boolean?, -- default true (the inverse of decode) + embedTextures: boolean?, -- embed texture.data as Video content (default true) + compress: boolean?, -- zlib-compress arrays over 32 elements (default true; false writes ~3x faster, ~2x bigger) + name: string?, -- the destination's file name (names textures without a uri) + creator: string?, +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = Binary.MAGIC + +-- ------------------------------------------------------------------------------------------------ sniff +function Fbx.sniff(r: Bytes.Reader): number + if r:peek(21) == MAGIC then + return 1 + end + local head = r:peek(2048) + if string.find(head, "FBXHeaderExtension:", 1, true) then + return 0.95 + end + if string.find(head, "^; FBX %d") then + return 0.8 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function fetcher(opts: DecodeOptions?): Read.Fetch + return function(uri: string): buffer? + if not opts then + return nil + end + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil + end +end + +local function toErr(msg: any, offset: number?): Err.Err + local s = tostring(msg) + local code = Err.CORRUPT + if string.sub(s, 1, 12) == "unsupported:" then + code, s = Err.UNSUPPORTED, string.sub(s, 13) + elseif string.sub(s, 1, 6) == "limit:" then + code, s = Err.LIMIT, string.sub(s, 7) + elseif string.find(s, "truncated", 1, true) or string.find(s, "runs past", 1, true) then + code = Err.TRUNCATED + end + return Err.new(code, s, offset) +end + +-- tree(r, opts?) -> the node tree { name = "", children = { { name, props, children } } }, version, binary | nil, Err. +-- Property values: numbers, booleans, strings, buffers (raw), Arrays { array = true, type, count, data = f64 buffer }. +function Fbx.tree(r: Bytes.Reader, opts: DecodeOptions?): (any, any, boolean?) + if r:peek(21) == MAGIC then + local root, version, off = Binary.parse(r.buf, r.base, r.limit, opts) + if not root then + return nil, toErr(version, off) + end + return root, version, true + end + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local root, version, off = Ascii.parse(text, opts) + if not root then + return nil, toErr(version, off and r.base + off) + end + if type(version) ~= "number" then + return nil, Err.new(Err.CORRUPT, "no FBXHeaderExtension / FBXVersion") + end + if version < 7000 then + return nil, Err.new(Err.UNSUPPORTED, "FBX version " .. version .. " (only 7.x)") + end + return root, version, false +end + +function Fbx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local root, version, binary = Fbx.tree(r, opts) + if not root then + return nil, version + end + -- the scene builder is plain (not native) code: a bug there must not escape as an error + local ok, scene, err = pcall(Read.scene, root, version, fetcher(opts), opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad object graph: " .. tostring(scene)) + end + if not scene then + return nil, err + end + scene.meta.source.binary = binary + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Fbx.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 + local version = opts and opts.version or 7400 + if version ~= 7400 and version ~= 7500 then + return nil, Err.new(Err.ARG, "version must be 7400 or 7500") + end + local ok, root, err = pcall(Write.tree, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(root)) + end + if not root then + return nil, err + end + if opts and opts.ascii then + return buffer.fromstring(Ascii.write(root, version)), nil + end + return Binary.write(root, version, not (opts and opts.compress == false)), nil +end + +return Fbx diff --git a/tests/model/fbx.luau b/tests/model/fbx.luau new file mode 100644 index 0000000..abc8bf6 --- /dev/null +++ b/tests/model/fbx.luau @@ -0,0 +1,542 @@ +-- model/fbx tests: assimp's FBX test models (binary 7.4 / 7.5, ASCII 7.4 - 7.7, embedded textures, skeletons, +-- animation), Blender's exporter (materials, textures, colours, skin, shape keys, animation, camera, lights) and +-- assimp's exporters (binary and ASCII), against assimp (meshes, polygons, vertices, world bounds, materials, +-- animations, cameras, lights) and Blender's importer (meshes, polygons, materials, bones, shape keys, cameras, +-- lights, images); round trips through our writer (binary and ASCII) and glTF sample models through FBX (world +-- triangles, materials, textures, skins, morph targets, sampled animation, cameras, lights); assimp and Blender +-- reading our files like the originals (fbx_xcheck); errors; the fuzz no-throw pass. Fixtures: tools/fixtures/fbx.py. +local T = require("@tests/T") +local F = require("@formats") +local Fbx = require("@formats/model/fbx") +local Gltf = require("@formats/model/gltf") +local MeshOps = require("@formats/ops/MeshOps") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/fbx_cases") +local Xcheck = require("@tests/gen/fbx_xcheck") +local GltfCases = require("@tests/gen/fbx_gltf") + +local t = T.suite("fbx") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Fbx.decode(Bytes.reader(b), opts) +end + +t:eq(Fbx.name, "fbx", "name") +t:eq(Fbx.category, "model", "category") +t:check(Fbx.caps.decode and Fbx.caps.encode, "contract") + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +local function triArea(prim: any): number + local pos, ind = prim.attributes.POSITION, prim.indices + if not ind then + return 0 + end + local area = 0 + local function P(i: number, k: number): number + return buffer.readf32(pos.data, (i * 3 + k) * 4) + end + for tri = 0, ind.count // 3 - 1 do + local a, b, c = buffer.readu32(ind.data, tri * 12), buffer.readu32(ind.data, tri * 12 + 4), buffer.readu32(ind.data, tri * 12 + 8) + local e1 = { P(b, 0) - P(a, 0), P(b, 1) - P(a, 1), P(b, 2) - P(a, 2) } + local e2 = { P(c, 0) - P(a, 0), P(c, 1) - P(a, 1), P(c, 2) - P(a, 2) } + local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1] + area += math.sqrt(x * x + y * y + z * z) / 2 + end + return area +end + +-- assimp-like counts: placed primitives, polygons, corners +local function counts(scene: any): (number, number, number) + local prims, faces, verts = 0, 0, 0 + local seen = {} + for _, pl in Types.Scene.flatten(scene) do + if not seen[pl.primitive] then + seen[pl.primitive] = true + prims += 1 + faces += if pl.primitive.faces then pl.primitive.faces.count else pl.primitive.indices.count // 3 + verts += pl.primitive.attributes.POSITION.count + end + end + return prims, faces, verts +end + +local function noMaterial(scene: any): boolean + for _, m in scene.meshes do + for _, p in m.primitives do + if p.material == nil then + return true + end + end + end + return false +end + +local function stats(scene: any): { [string]: number } + local s = { meshNodes = 0, limbs = 0, shapes = 0, textures = #scene.textures, cameras = #scene.cameras, lights = #scene.lights } + for _, n in scene.nodes do + if n.mesh then + s.meshNodes += 1 + end + if n.extras and n.extras.fbx and n.extras.fbx.type == "LimbNode" then + s.limbs += 1 + end + end + for _, m in scene.meshes do + s.shapes += if m.weights then #m.weights else 0 + end + return s +end + +-- world bounds, also under assimp's Z-up -> Y-up root conversion (x, z, -y) +local function boundsMatch(lo: { number }, hi: { number }, want: any, eps: number): boolean + local function eq(a: { number }, b: { number }, c: { number }, d: { number }): boolean + for k = 1, 3 do + if not near(a[k], c[k], eps) or not near(b[k], d[k], eps) then + return false + end + end + return true + end + if eq(lo, hi, want.min, want.max) then + return true + end + return eq({ lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] }, want.min, want.max) +end + +-- ------------------------------------------------------------------------------------------------ reference files +local checked = { assimp = 0, blender = 0, roundTrips = 0, failed = 0 } +local scenes = {} +for i, c in Cases do + local scene, err = decode(c.data, { files = c.files, triangulate = false }) + local a = c.assimp + if a.failed then + t:check(scene == nil and err ~= nil, c.name .. ": assimp rejects it, so do we") + checked.failed += 1 + else + t:check(scene, c.name .. ": decode: " .. tostring(err)) + scenes[i] = scene + local prims, faces, verts = counts(scene) + t:eq(prims, a.meshes, c.name .. ": meshes (assimp)") + t:eq(faces, a.faces, c.name .. ": polygons (assimp)") + t:eq(verts, a.vertices, c.name .. ": vertices (assimp)") + t:eq(#scene.cameras, a.cameras, c.name .. ": cameras (assimp)") + t:eq(#scene.lights, a.lights, c.name .. ": lights (assimp)") + t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)") + t:eq(#scene.materials + (if noMaterial(scene) then 1 else 0), a.materials, c.name .. ": materials (assimp, + its default)") + if a.min then + local lo, hi = MeshOps.bounds(MeshOps.merge(scene)) + t:check(lo and boundsMatch(lo, hi, a, 1e-3), string.format("%s: world bounds (assimp) %s %s", c.name, if lo then table.concat(lo, " ") else "-", if hi then table.concat(hi, " ") else "-")) + end + checked.assimp += 1 + local b = c.blender + if b and not b.failed then + local s = stats(scene) + t:eq(s.meshNodes, b.meshes, c.name .. ": mesh objects (Blender)") + t:eq(faces, b.polygons, c.name .. ": polygons (Blender)") + t:eq(#scene.materials, b.materials, c.name .. ": materials (Blender)") + t:eq(s.limbs, b.bones, c.name .. ": bones (Blender)") + t:eq(s.shapes, b.shapeKeys, c.name .. ": shape keys (Blender)") + t:eq(s.cameras, b.cameras, c.name .. ": cameras (Blender)") + t:eq(s.lights, b.lights, c.name .. ": lights (Blender)") + t:eq(s.textures, b.images, c.name .. ": textures (Blender)") + t:check((#scene.animations > 0) == (b.actions > 0), c.name .. ": animated (Blender)") + checked.blender += 1 + end + end +end +t:note("%d files: %d against assimp, %d against Blender, %d rejected by both", #Cases, checked.assimp, checked.blender, checked.failed) + +-- ------------------------------------------------------------------------------------------------ round trips +-- world triangles (area, count, bounds), materials, textures, skins, morph targets, animation samples, cameras, lights +local function compare(a: any, b: any, label: string, eps: number) + local ma, mb = MeshOps.merge(a), MeshOps.merge(b) + local na = if ma and ma.indices then ma.indices.count // 3 else 0 + local nb = if mb and mb.indices then mb.indices.count // 3 else 0 + t:eq(nb, na, label .. ": triangles") + if na > 0 and nb > 0 then + t:check(near(triArea(ma), triArea(mb), eps), string.format("%s: area %.7g / %.7g", label, triArea(ma), triArea(mb))) + local la, ha = MeshOps.bounds(ma) + local lb, hb = MeshOps.bounds(mb) + local ok = true + for k = 1, 3 do + ok = ok and near(la[k], lb[k], eps) and near(ha[k], hb[k], eps) + end + t:check(ok, label .. ": bounds") + end + t:eq(#b.materials, #a.materials, label .. ": materials") + for k, m in a.materials do + local m2 = b.materials[k] + if m2 then + local ok = true + for q = 1, 4 do + ok = ok and near(m.baseColor[q], m2.baseColor[q], 1e-6) + end + t:check(ok, label .. ": material " .. k .. " colour") + t:check((m.baseColorTexture == nil) == (m2.baseColorTexture == nil), label .. ": material " .. k .. " texture") + end + end + t:eq(#b.textures, #a.textures, label .. ": textures") + for k, tex in a.textures do + local t2 = b.textures[k] + if tex.data and t2 then + t:check(t2.data and buffer.tostring(t2.data) == buffer.tostring(tex.data), label .. ": texture " .. k .. " bytes") + end + end + t:eq(#b.skins, #a.skins, label .. ": skins") + for k, s in a.skins do + local s2 = b.skins[k] + if s2 then + t:eq(#s2.joints, #s.joints, label .. ": skin joints") + end + end + local function targets(s: any): number + local n = 0 + for _, m in s.meshes do + n += if m.weights then #m.weights else 0 + end + return n + end + t:eq(targets(b), targets(a), label .. ": morph targets") + t:eq(#b.cameras, #a.cameras, label .. ": cameras") + t:eq(#b.lights, #a.lights, label .. ": lights") + -- cameras / lights: the same world placement (forward axis included) + local function placed(s: any, field: string): { { number } } + local out = {} + local function visit(i: number, parent: { number }, seen: { [number]: boolean }) + if seen[i] then + return + end + seen[i] = true + local n = s.nodes[i] + local w = Types.Scene.mul(parent, Types.Scene.nodeMatrix(n)) + if n[field] then + out[n[field]] = w + end + for _, c in n.children do + visit(c, w, seen) + end + end + local seen = {} + for _, r in s.roots do + visit(r, Types.Scene.IDENTITY, seen) + end + return out + end + for _, field in { "camera", "light" } do + local pa, pb = placed(a, field), placed(b, field) + for k, w in pa do + local w2 = pb[k] + local ok = w2 ~= nil + if w2 then + for q = 1, 16 do + ok = ok and math.abs(w[q] - w2[q]) <= eps * math.max(1, math.abs(w[q])) + end + end + t:check(ok, label .. ": " .. field .. " " .. k .. " world matrix") + end + end + -- animations: every channel of b sampled against a (LINEAR / STEP / CUBICSPLINE values at the keys of b) + t:eq(#b.animations, #a.animations, label .. ": animations") + local function evalCh(ch: any, time: number, comps: number): { number } + local IN, OUT = Types.Scene.reader(ch.input) :: any, Types.Scene.reader(ch.output) :: any + local n = ch.input.count + local cubic = ch.interpolation == "CUBICSPLINE" + local function v(k: number): { number } + local e = if cubic then k * 3 + 1 else k + local r = {} + for q = 0, comps - 1 do + r[q + 1] = OUT(e, q) + end + return r + end + if time <= IN(0, 0) then + return v(0) + end + for k = 0, n - 2 do + local t0, t1 = IN(k, 0), IN(k + 1, 0) + if time <= t1 then + if ch.interpolation == "STEP" or t1 <= t0 then + return if time >= t1 then v(k + 1) else v(k) + end + local u = (time - t0) / (t1 - t0) + local a0, a1 = v(k), v(k + 1) + if comps == 4 and ch.path == "rotation" and a0[1] * a1[1] + a0[2] * a1[2] + a0[3] * a1[3] + a0[4] * a1[4] < 0 then + a1 = { -a1[1], -a1[2], -a1[3], -a1[4] } + end + local r = {} + for q = 1, comps do + r[q] = a0[q] + (a1[q] - a0[q]) * u + end + return r + end + end + return v(n - 1) + end + for ai, an in a.animations do + local bn = b.animations[ai] + if bn then + -- channels by node name + path + local byKey = {} + for _, ch in an.channels do + byKey[(a.nodes[ch.node].name or "") .. "/" .. ch.path] = ch + end + local bad, n = 0, 0 + for _, ch in bn.channels do + local key = (b.nodes[ch.node].name or "") .. "/" .. ch.path + local orig = byKey[key] + local comps = if ch.path == "rotation" then 4 elseif ch.path == "weights" then ch.output.count // ch.input.count else 3 + if orig then + local IN = Types.Scene.reader(ch.input) :: any + for k = 0, ch.input.count - 1 do + local time = IN(k, 0) + local want = evalCh(orig, time, comps) + local got = evalCh(ch, time, comps) + local dot = 0 + for q = 1, comps do + dot += want[q] * got[q] + end + local sign = if ch.path == "rotation" and dot < 0 then -1 else 1 + for q = 1, comps do + if math.abs(got[q] * sign - want[q]) > 1e-3 * math.max(1, math.abs(want[q])) then + bad += 1 + end + end + n += 1 + end + end + end + t:check(bad == 0, string.format("%s: animation %d: %d of %d samples differ", label, ai, bad, n)) + end + end +end + +for i, c in Cases do + local scene = scenes[i] + if scene then + for _, ascii in { false, true } do + local out, err = Fbx.encode(scene, { ascii = ascii }) + t:check(out, c.name .. ": encode: " .. tostring(err)) + local back, berr = decode(out :: buffer, { triangulate = false }) + t:check(back, c.name .. ": decode ours: " .. tostring(berr)) + if back then + compare(scene, back, c.name .. (if ascii then " (ascii)" else ""), 1e-5) + t:eq(#back.nodes, #scene.nodes, c.name .. ": nodes") + local p1, f1, v1 = counts(scene) + local p2, f2, v2 = counts(back) + t:check(p1 == p2 and f1 == f2 and v1 == v2, c.name .. ": polygons kept") + end + end + checked.roundTrips += 1 + end +end + +-- glTF sample models through FBX +local ng = 0 +for _, g in GltfCases do + local scene, gerr = Gltf.decode(Bytes.reader(buffer.fromstring(g.data)), { files = g.files }) + t:check(scene, g.name .. ": glTF decode: " .. tostring(gerr)) + if scene then + local out, err = Fbx.encode(scene) + t:check(out, g.name .. ": encode: " .. tostring(err)) + local back, berr = decode(out :: buffer) + t:check(back, g.name .. ": decode ours: " .. tostring(berr)) + if back then + -- glTF points / lines are not written + local lines = false + for _, m in scene.meshes do + for _, p in m.primitives do + if p.mode == "points" or p.mode == "lines" or p.mode == "line_strip" or p.mode == "line_loop" then + lines = true + end + end + end + if not lines then + compare(scene, back, "glTF " .. g.name, 2e-5) + end + ng += 1 + end + end +end +t:note("%d round trips of the reference files (binary + ASCII), %d glTF models through FBX", checked.roundTrips, ng) + +-- ------------------------------------------------------------------------------------------------ cross-check +-- assimp and Blender read our files like the originals +local nx = 0 +for _, x in Xcheck do + local c = Cases[x.case] + local a, ca = x.assimp, c.assimp + local scene = scenes[x.case] + if not ca.failed and scene then + local _, faces = counts(scene) + t:check(not a.failed, x.name .. ": assimp reads our file") + t:eq(a.meshes, ca.meshes, x.name .. ": assimp meshes of our file (" .. c.name .. ")") + t:eq(a.faces, faces, x.name .. ": assimp polygons of our file (" .. c.name .. ")") + t:eq(a.cameras, ca.cameras, x.name .. ": assimp cameras of our file") + t:eq(a.lights, ca.lights, x.name .. ": assimp lights of our file") + t:eq(a.animations, ca.animations, x.name .. ": assimp animations of our file") + t:eq(a.bones, ca.bones, x.name .. ": assimp bones of our file") + if a.min and ca.min then + local ok = true + for k = 1, 3 do + ok = ok and near(a.min[k], ca.min[k], 1e-4) and near(a.max[k], ca.max[k], 1e-4) + end + t:check(ok, x.name .. ": assimp world bounds of our file (" .. c.name .. ")") + end + local b, cb = x.blender, c.blender + if b and cb and not cb.failed then + t:check(not b.failed, x.name .. ": Blender reads our file: " .. tostring(b.failed)) + if not b.failed then + for _, k in { "meshes", "polygons", "materials", "bones", "shapeKeys", "cameras", "lights", "images" } do + t:eq(b[k], cb[k], x.name .. ": Blender " .. k .. " of our file (" .. c.name .. ")") + end + t:check((b.actions > 0) == (cb.actions > 0), x.name .. ": Blender actions of our file") + end + end + nx += 1 + end +end +t:note("%d of our files read back by assimp / Blender like the originals", nx) + +-- ------------------------------------------------------------------------------------------------ details +do + local byName = {} + for i, c in Cases do + byName[c.name] = scenes[i] + end + local cube = byName["blender/blender_cube.fbx"] + if cube then + local tex = cube.textures[1] + t:check(tex and tex.data and tex.mime == "image/png", "Blender cube: embedded PNG kept encoded") + local _, errs = F.model.loadTextures(cube) + t:check(tex.image and tex.image.width == 8 and next(errs) == nil, "F.model.loadTextures decodes the embedded PNG") + local red = cube.materials[1] + t:check(red.name == "Red" and red.baseColorTexture and red.extras.fbx.shadingModel ~= nil, "material with a texture + Phong extras") + local prim = cube.meshes[1].primitives[1] + t:check(prim.attributes.COLOR_0 and prim.attributes.TEXCOORD_0 and prim.attributes.NORMAL, "colours, uvs, normals") + t:eq(cube.meta.up, "y", "Blender writes Y up") + t:check(near(cube.meta.unit, 0.01, 1e-9), "unit: centimetres") + end + local skin = byName["blender/blender_skin.fbx"] + if skin then + local m = skin.meshes[1] + local p = m.primitives[1] + t:check(#skin.skins == 1 and #skin.skins[1].joints == 2 and p.attributes.JOINTS_0 and p.attributes.WEIGHTS_0, "skin: joints and weights") + t:check(m.weights and #m.weights == 1 and m.weights[1] >= 0 and m.weights[1] <= 1 and p.targets and p.targets[1].POSITION, "shape key: a morph target and its weight") + local paths = {} + for _, ch in skin.animations[1].channels do + paths[ch.path] = true + end + t:check(paths.rotation and paths.weights, "animation: rotation and morph weights channels") + -- weights sum to 1 + local W = Types.Scene.reader(p.attributes.WEIGHTS_0) :: any + local ok = true + for v = 0, p.attributes.WEIGHTS_0.count - 1 do + local s = W(v, 0) + W(v, 1) + W(v, 2) + W(v, 3) + ok = ok and (math.abs(s - 1) < 1e-5 or s == 0) + end + t:check(ok, "skin weights normalized") + end + local cl = byName["blender/blender_camlight.fbx"] + if cl then + local types = {} + for _, l in cl.lights do + types[l.type] = true + end + t:check(types.point and types.directional and types.spot, "point, directional, spot lights") + local cam = cl.cameras[1] + -- Blender's 35 mm lens on a 36 mm sensor, 16:9 render + t:check(cam.type == "perspective" and cam.yfov > 0.3 and cam.yfov < 1.2, "camera fov " .. cam.yfov) + end + local pbr = byName["assimp/maxPbrMaterial_metalRough.fbx"] + if pbr then + local m = pbr.materials[1] + t:check(near(m.metallic, 0.25, 1e-6) and near(m.roughness, 0.5, 1e-6), "3ds Max PBR material: metalness / roughness") + end + local emb = byName["assimp/embedded_ascii/box.FBX"] + if emb then + t:check(emb.textures[1] and emb.textures[1].data and emb.meta.source.binary == false, "ASCII: base64 embedded texture") + t:eq(emb.meta.up, "z", "3ds Max: Z up") + end + -- polygons kept / triangulated + local box = decode(Cases[2].data) + t:check(box.meshes[1].primitives[1].mode == "triangles", "triangulated by default") + -- through the api + local s = F.load(Cases[2].data) + t:check(s and s.kind == "scene" and s.meta.source.format == "fbx", "F.load detects binary FBX") + local viaApi = F.save(s, nil, { format = "fbx" }) + t:check(viaApi and buffer.readstring(viaApi, 0, 18) == "Kaydara FBX Binary", "F.save format fbx") + -- a 7.5 (64-bit records) file + local v75 = Fbx.encode(s, { version = 7500 }) :: buffer + local b75 = decode(v75) + t:check(b75 and b75.meta.source.version == 7500 and #b75.meshes == #s.meshes, "7.5 records") + -- a scene made by hand: a quad as polygons, written and read back as one polygon + local p = Types.Scene.accessor(nil, "f32", 3, 4) + for v, xyz in { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 } } do + for k = 1, 3 do + buffer.writef32(p.data, ((v - 1) * 3 + k - 1) * 4, xyz[k]) + end + end + local faces = Types.Scene.accessor(nil, "u32", 1, 1) + buffer.writeu32(faces.data, 0, 4) + local ind = Types.Scene.accessor(nil, "u32", 1, 4) + for k = 0, 3 do + buffer.writeu32(ind.data, k * 4, k) + end + local quad = Types.Scene.fromPrimitive({ attributes = { POSITION = p }, indices = ind, faces = faces, mode = "polygons" }, "quad") + local qb = decode(Fbx.encode(quad) :: buffer, { triangulate = false }) + t:check(qb and qb.meshes[1].primitives[1].faces.count == 1 and qb.meshes[1].primitives[1].indices.count == 4, "a quad stays one polygon") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local _, e1 = decode("; FBX 6.1.0 project file\nFBXHeaderExtension: {\n\tFBXVersion: 6100\n}\n") + t:check(e1 and e1.code == Err.UNSUPPORTED, "FBX 6: " .. tostring(e1)) + local bin = Cases[2].data + local _, e2 = decode(string.sub(bin, 1, 200)) + t:check(e2 and (e2.code == Err.TRUNCATED or e2.code == Err.CORRUPT), "truncated: " .. tostring(e2)) + local _, e3 = decode(string.sub(bin, 1, 23) .. "\100\25\0\0" .. string.sub(bin, 28)) + t:check(e3 and e3.code == Err.UNSUPPORTED, "binary version 6500: " .. tostring(e3)) + local _, e4 = decode("FBXHeaderExtension: { FBXVersion: 7400 }\nObjects: {") + t:check(e4 and e4.code == Err.CORRUPT, "unterminated ASCII: " .. tostring(e4)) + local _, e5 = decode("FBXHeaderExtension: { FBXVersion: 7400 }\n") + t:check(e5 and e5.code == Err.CORRUPT, "no Objects: " .. tostring(e5)) + local _, e6 = decode(bin, { maxBytes = 100 }) + t:check(e6 and e6.code == Err.LIMIT, "maxBytes: " .. tostring(e6)) + local _, e7 = Fbx.encode({} :: any) + t:check(e7 and e7.code == Err.ARG, "encode junk") + local _, e8 = Fbx.encode(Types.Scene.new(), { version = 6100 }) + t:check(e8 and e8.code == Err.ARG, "encode version 6100") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = {} + for i, c in Cases do + if #c.data < 60000 then + table.insert(samples, c.data) + end + local s = scenes[i] + if s and #samples < 24 then + local a = Fbx.encode(s, { ascii = true }) + if a and buffer.len(a) < 60000 then + table.insert(samples, buffer.tostring(a)) + end + end + end + t:fuzz("decode", function(b: buffer) + local s = Fbx.decode(Bytes.reader(b)) + if s then + Fbx.encode(s) + MeshOps.merge(s) + end + return s + end, samples, { mutations = 12, keepHeader = 27 }) +end + +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index 710195d..686cd01 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -451,6 +451,21 @@ do bench("ply binary decode (" .. buffer.len(ply) // 1000 .. " KB)", 5, buffer.len(ply), function() Ply.decode(Bytes.reader(ply)) end) + local Fbx = require("@formats/model/fbx") + local fbx = assert(Fbx.encode(scene)) + bench("fbx binary decode (" .. buffer.len(fbx) // 1000 .. " KB)", 3, buffer.len(fbx), function() + Fbx.decode(Bytes.reader(fbx)) + end) + bench("fbx binary encode (zlib arrays)", 2, buffer.len(fbx), function() + Fbx.encode(scene) + end) + bench("fbx binary encode (raw arrays)", 3, buffer.len(fbx), function() + Fbx.encode(scene, { compress = false }) + end) + local fbxa = assert(Fbx.encode(scene, { ascii = true })) + bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function() + Fbx.decode(Bytes.reader(fbxa)) + end) local V = 128 local grid = Types.Voxels.new(V, V, V) for z = 0, V - 1 do diff --git a/tools/fixtures/_fbx_blender.py b/tools/fixtures/_fbx_blender.py new file mode 100644 index 0000000..c03c1a8 --- /dev/null +++ b/tools/fixtures/_fbx_blender.py @@ -0,0 +1,94 @@ +# tools/fixtures/_fbx_blender: run by tools/fixtures/fbx.py inside Blender (blender -b --python -- ): builds +# test scenes (textured cube with two materials, vertex colours and a child; a skinned, animated cylinder with a +# shape key; a camera and three lights) and exports each to binary FBX 7.4. +import bpy, sys, os, math +out = sys.argv[sys.argv.index("--") + 1] +def reset(): + bpy.ops.wm.read_factory_settings(use_empty=True) +def export(name, **kw): + bpy.ops.export_scene.fbx(filepath=os.path.join(out, name), **kw) + +# 1. textured cube: material, uv, vertex colours, packed image +reset() +bpy.ops.mesh.primitive_cube_add(size=2, location=(1, 2, 3), rotation=(0.3, 0.2, 0.1)) +cube = bpy.context.object +cube.name = "Cube" +mesh = cube.data +mesh.color_attributes.new("Col", "BYTE_COLOR", "CORNER") +for i, d in enumerate(mesh.color_attributes["Col"].data): + d.color = ((i % 3) / 2, (i % 5) / 4, (i % 7) / 6, 1) +img = bpy.data.images.new("checker", 8, 8) +img.pixels = [((x + y) % 2) * 1.0 if c < 3 else 1.0 for y in range(8) for x in range(8) for c in range(4)] +img.filepath_raw = os.path.join(out, "checker.png") +img.file_format = "PNG" +img.save() +img.pack() +mat = bpy.data.materials.new("Red") +mat.use_nodes = True +bsdf = mat.node_tree.nodes["Principled BSDF"] +bsdf.inputs["Base Color"].default_value = (0.8, 0.1, 0.1, 1) +bsdf.inputs["Roughness"].default_value = 0.4 +tex = mat.node_tree.nodes.new("ShaderNodeTexImage") +tex.image = img +mat.node_tree.links.new(tex.outputs["Color"], bsdf.inputs["Base Color"]) +mesh.materials.append(mat) +mat2 = bpy.data.materials.new("Blue") +mat2.diffuse_color = (0.1, 0.1, 0.9, 1) +mesh.materials.append(mat2) +for i, p in enumerate(mesh.polygons): + p.material_index = i % 2 +bpy.ops.mesh.primitive_uv_sphere_add(segments=12, ring_count=6, location=(-3, 0, 0)) +bpy.context.object.name = "Sphere" +bpy.context.object.parent = cube +export("blender_cube.fbx", path_mode="COPY", embed_textures=True) + +# 2. skinned, animated mesh with shape keys +reset() +bpy.ops.object.armature_add(location=(0, 0, 0)) +arm = bpy.context.object +arm.name = "Rig" +bpy.ops.object.mode_set(mode="EDIT") +b0 = arm.data.edit_bones[0] +b0.name = "root" +b0.head, b0.tail = (0, 0, 0), (0, 0, 1) +b1 = arm.data.edit_bones.new("tip") +b1.head, b1.tail, b1.parent = (0, 0, 1), (0, 0, 2), b0 +bpy.ops.object.mode_set(mode="OBJECT") +bpy.ops.mesh.primitive_cylinder_add(vertices=8, depth=2, radius=0.3, location=(0, 0, 1)) +cyl = bpy.context.object +cyl.name = "Body" +bpy.ops.object.mode_set(mode="EDIT") +bpy.ops.mesh.subdivide(number_cuts=3) +bpy.ops.object.mode_set(mode="OBJECT") +cyl.shape_key_add(name="Basis") +sk = cyl.shape_key_add(name="Fat") +for v in sk.data: + v.co.x *= 1.5 + v.co.y *= 1.5 +sk.value = 0.25 +cyl.select_set(True) +arm.select_set(True) +bpy.context.view_layer.objects.active = arm +bpy.ops.object.parent_set(type="ARMATURE_AUTO") +bpy.context.scene.frame_start, bpy.context.scene.frame_end = 1, 20 +bpy.ops.object.mode_set(mode="POSE") +pb = arm.pose.bones["tip"] +pb.rotation_mode = "XYZ" +for f, a in ((1, 0), (10, 0.8), (20, 0)): + pb.rotation_euler = (a, 0, 0) + pb.keyframe_insert("rotation_euler", frame=f) +bpy.ops.object.mode_set(mode="OBJECT") +for f, v in ((1, 0), (20, 1)): + sk.value = v + sk.keyframe_insert("value", frame=f) +export("blender_skin.fbx", add_leaf_bones=False, bake_anim=True) + +# 3. camera and lights +reset() +bpy.ops.object.camera_add(location=(0, -5, 1), rotation=(math.pi / 2, 0, 0)) +bpy.context.object.data.lens = 35 +for kind, loc in (("POINT", (1, 0, 3)), ("SUN", (0, 0, 5)), ("SPOT", (2, 2, 2))): + bpy.ops.object.light_add(type=kind, location=loc) + bpy.context.object.data.energy = 10 +bpy.ops.mesh.primitive_plane_add(size=4) +export("blender_camlight.fbx") diff --git a/tools/fixtures/_fbx_blender_stats.py b/tools/fixtures/_fbx_blender_stats.py new file mode 100644 index 0000000..0d43d21 --- /dev/null +++ b/tools/fixtures/_fbx_blender_stats.py @@ -0,0 +1,31 @@ +# tools/fixtures/_fbx_blender_stats: run by tools/fixtures/fbx.py inside Blender (blender -b --python -- ): imports each FBX with Blender's importer and prints one JSON line "STATS " with per file +# counts: mesh objects, polygons, vertices, materials, bones, actions, shape keys, cameras, lights, images; or +# {"failed": message}. +import bpy, sys, json +paths = json.loads(sys.argv[sys.argv.index("--") + 1]) +res = [] +for p in paths: + bpy.ops.wm.read_factory_settings(use_empty=True) + try: + r = bpy.ops.import_scene.fbx(filepath=p) + if "FINISHED" not in r: + raise RuntimeError(str(r)) + except Exception as e: + res.append({"failed": str(e)[:200]}) + continue + obs = bpy.context.scene.objects + meshes = [o for o in obs if o.type == "MESH"] + res.append({ + "meshes": len(meshes), + "polygons": sum(len(o.data.polygons) for o in meshes), + "vertices": sum(len(o.data.vertices) for o in meshes), + "materials": len([m for m in bpy.data.materials if m.users > 0]), + "bones": sum(len(o.data.bones) for o in obs if o.type == "ARMATURE"), + "actions": len(bpy.data.actions), + "shapeKeys": sum(len(o.data.shape_keys.key_blocks) - 1 for o in meshes if o.data.shape_keys), + "cameras": len([o for o in obs if o.type == "CAMERA"]), + "lights": len([o for o in obs if o.type == "LIGHT"]), + "images": len([i for i in bpy.data.images if i.users > 0]), + }) +print("STATS " + json.dumps(res)) diff --git a/tools/fixtures/_fbx_encode.luau b/tools/fixtures/_fbx_encode.luau new file mode 100644 index 0000000..c37d033 --- /dev/null +++ b/tools/fixtures/_fbx_encode.luau @@ -0,0 +1,38 @@ +-- tools/fixtures/_fbx_encode: run by tools/fixtures/fbx.py (luau CLI, repo root): decodes every FBX case with our +-- reader and writes it back with our writer (binary 7.4, and ASCII for every third case), printing "\t" +-- lines for assimp and Blender to read back. Files: rt_.fbx (binary), rt_.a.fbx (ASCII). +local Fbx = require("@formats/model/fbx") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/fbx_cases") + +local HEX = {} +for i = 0, 255 do + HEX[i] = string.format("%02x", i) +end +local function hex(b: buffer): string + local out = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + out[i + 1] = HEX[buffer.readu8(b, i)] + end + return table.concat(out) +end + +for i, c in Cases do + local scene, err = Fbx.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files, triangulate = false }) + if scene then + local bin, e2 = Fbx.encode(scene) + if bin then + print(string.format("rt_%d.fbx\t%s", i, hex(bin))) + else + print("encode failed " .. c.name .. ": " .. tostring(e2)) + end + if i % 3 == 0 then + local a = Fbx.encode(scene, { ascii = true }) + if a then + print(string.format("rt_%d.a.fbx\t%s", i, hex(a))) + end + end + else + print("skipped " .. c.name .. ": " .. tostring(err)) + end +end diff --git a/tools/fixtures/fbx.py b/tools/fixtures/fbx.py new file mode 100644 index 0000000..726ea2a --- /dev/null +++ b/tools/fixtures/fbx.py @@ -0,0 +1,179 @@ +# FBX fixtures (tools/fixtures.py): assimp's FBX test models (binary 7.4 / 7.5, ASCII 7.4 / 7.5 / 7.7, embedded +# textures, skeletons, animation; read from the nixpkgs assimp source, never committed), scenes exported by Blender +# (tools/fixtures/_fbx_blender.py: materials, textures, vertex colours, skin, shape keys, animation, camera, lights) +# and by assimp's FBX exporters (binary and ASCII), with reference values from assimp (`assimp info -r`: meshes, +# faces, vertices, bounds, materials, animations, cameras, lights, bones) and Blender's importer +# (tools/fixtures/_fbx_blender_stats.py). Then our encoder's output (tools/fixtures/_fbx_encode.luau) read back by +# assimp and Blender. +# tests/gen/fbx_cases.luau { name, data, files = { name -> bytes }, assimp, blender? } +# tests/gen/fbx_xcheck.luau { name, case, assimp, blender? } +# tests/gen/fbx_gltf.luau glTF sample models (tests/fixtures/gltf) for the writer round trips: { name, data, files } +import importlib.util, json, os, shutil, subprocess + +INPUTS = ["src/Formats/model/fbx", "tests/fixtures/gltf", "src/Formats/codecs/Deflate", "tools/fixtures/_model_ref.py", + "tools/fixtures/_fbx_blender.py", "tools/fixtures/_fbx_blender_stats.py", "tools/fixtures/_fbx_encode.luau"] + + +def ref_module(ctx): + spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def assimp_extra(ctx, path): + import re + try: + txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace") + except subprocess.CalledProcessError: + return {} + out = {} + for label in ("Animations", "Cameras", "Lights", "Bones", "Animation Channels"): + m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M) + if m: + out[label.lower().replace(" ", "_")] = int(m.group(1)) + return out + + +def ptv_bounds(ctx, path, tmp): + # world-space bounds: assimp's PreTransformVertices output (`assimp info` multiplies node matrices in the wrong + # order for nested nodes, so its own bounds are not used) + out = os.path.join(tmp, "ptv.obj") + try: + ctx.nix("assimp", ["assimp", "export", path, out, "-ptv"]) + lo, hi = [1e30] * 3, [-1e30] * 3 + with open(out) as f: + for line in f: + if line.startswith("v "): + v = [float(x) for x in line.split()[1:4]] + lo = [min(a, b) for a, b in zip(lo, v)] + hi = [max(a, b) for a, b in zip(hi, v)] + os.remove(out) + return {"min": lo, "max": hi} if lo[0] <= hi[0] else {} + except (subprocess.CalledProcessError, OSError, ValueError): + return {} + + +def blender(): + return shutil.which("blender") + + +def blender_stats(ctx, paths): + exe = blender() + if not exe or not paths: + return [None] * len(paths) + script = os.path.join(ctx.root, "tools", "fixtures", "_fbx_blender_stats.py") + try: + res = subprocess.run([exe, "-b", "--factory-startup", "--python", script, "--", json.dumps(paths)], + capture_output=True, timeout=900) + except (subprocess.TimeoutExpired, OSError): + return [None] * len(paths) + for line in res.stdout.decode("utf-8", "replace").split("\n"): + if line.startswith("STATS "): + return json.loads(line[6:]) + return [None] * len(paths) + + +def assimp_src(ctx): + out = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True) + return out.stdout.decode().strip().split("\n")[-1] + + +def generate(ctx): + M = ref_module(ctx) + tmp = M.tempdir() + cases = [] + # assimp's test models (read only) + src = os.path.join(assimp_src(ctx), "test", "models", "FBX") + for root, _, files in sorted(os.walk(src)): + for f in sorted(files): + if f.lower().endswith(".fbx"): + p = os.path.join(root, f) + cases.append({"name": "assimp/" + os.path.relpath(p, src), "path": p, "files": {}}) + # Blender's exporter + exe = blender() + if exe: + bdir = os.path.join(tmp, "blender") + os.makedirs(bdir) + subprocess.run([exe, "-b", "--factory-startup", "--python", os.path.join(ctx.root, "tools", "fixtures", "_fbx_blender.py"), "--", bdir], + capture_output=True, check=True, timeout=600) + for f in sorted(os.listdir(bdir)): + if f.endswith(".fbx"): + cases.append({"name": "blender/" + f, "path": os.path.join(bdir, f), "files": {}}) + # assimp's exporters: binary and ASCII, from a few glTF sample models (skin, morph, textures) and a PLY torus + gl = os.path.join(ctx.root, "tests", "fixtures", "gltf") + for model, variant, main in (("SimpleSkin", "glTF", "SimpleSkin.gltf"), ("BoxTextured", "glTF", "BoxTextured.gltf"), + ("RiggedSimple", "glTF-Binary", "RiggedSimple.glb"), ("Cameras", "glTF", "Cameras.gltf"), + ("BoxVertexColors", "glTF-Binary", "BoxVertexColors.glb")): + inp = os.path.join(gl, model, variant, main) + if not os.path.exists(inp): + continue + for fmt in ("fbx", "fbxa"): + out = os.path.join(tmp, "%s_%s.fbx" % (model, fmt)) + try: + ctx.nix("assimp", ["assimp", "export", inp, out, "-f" + fmt]) + except subprocess.CalledProcessError: + continue + cases.append({"name": "assimp-export/%s.%s" % (model, fmt), "path": out, "files": {}}) + paths = [c["path"] for c in cases] + infos = M.assimp_info(ctx, paths, raw=True) + bl = blender_stats(ctx, paths) + for c, a, b in zip(cases, infos, bl): + a.update(assimp_extra(ctx, c["path"])) + a.pop("min", None) + a.pop("max", None) + a.update(ptv_bounds(ctx, c["path"], tmp)) + c["assimp"] = a + if b: + c["blender"] = b + c["data"] = open(c["path"], "rb").read() + # sibling files a model refers to (textures next to it) + d = os.path.dirname(c["path"]) + for f in sorted(os.listdir(d)): + if f.lower().endswith((".png", ".jpg", ".jpeg", ".tga")) and os.path.getsize(os.path.join(d, f)) < 300000: + c["files"][f] = open(os.path.join(d, f), "rb").read() + del c["path"] + ctx.emit("fbx_cases", cases) + + # glTF sample models for the writer round trips (glTF -> FBX -> Scene, compared with the glTF scene) + picks = [] + for model in ("Box", "BoxTextured", "BoxVertexColors", "SimpleSkin", "RiggedSimple", "SimpleMorph", "AnimatedMorphCube", + "Cameras", "MultiUVTest", "InterpolationTest", "NegativeScaleTest", "PointLightIntensityTest", + "AnimatedTriangle", "TextureCoordinateTest", "MeshPrimitiveModes", "SimpleMeshes"): + d0 = os.path.join(gl, model) + if not os.path.isdir(d0): + continue + for variant in sorted(os.listdir(d0)): + d = os.path.join(d0, variant) + if not os.path.isdir(d): + continue + mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")] + if mains: + picks.append({"name": model + "/" + variant, "data": open(os.path.join(d, mains[0]), "rb").read(), + "files": {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d)) if f != mains[0]}}) + break + ctx.emit("fbx_gltf", picks) + + # the reference tools read our output + ours = M.luau_encode(ctx, "tools/fixtures/_fbx_encode.luau") + xtmp = M.tempdir() + names = sorted(n for n in ours if n.endswith(".fbx")) + for name, data in ours.items(): + with open(os.path.join(xtmp, name), "wb") as f: + f.write(data) + xpaths = [os.path.join(xtmp, n) for n in names] + xi = M.assimp_info(ctx, xpaths, raw=True) + bin_paths = [p for p in xpaths if not p.endswith(".a.fbx")] # Blender reads binary FBX only + xb_bin = dict(zip(bin_paths, blender_stats(ctx, bin_paths))) + xb = [xb_bin.get(p) for p in xpaths] + out = [] + for n, p, a, b in zip(names, xpaths, xi, xb): + a.update(assimp_extra(ctx, p)) + a.pop("min", None) + a.pop("max", None) + a.update(ptv_bounds(ctx, p, xtmp)) + e = {"name": n, "case": int(n.split("_")[1].split(".")[0]), "assimp": a} + if b: + e["blender"] = b + out.append(e) + ctx.emit("fbx_xcheck", out) From 336ff99505d008b773fef0d4ce08741db212a962 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:55:03 -0500 Subject: [PATCH 6/8] ws-3d2/fbx: header: compress option, reference tools named --- src/Formats/model/fbx/init.luau | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Formats/model/fbx/init.luau b/src/Formats/model/fbx/init.luau index 27e1983..fa47b1a 100644 --- a/src/Formats/model/fbx/init.luau +++ b/src/Formats/model/fbx/init.luau @@ -16,7 +16,7 @@ -- as material slots; normals, uvs, colours), Phong materials (extras.fbx when present, else from the PBR fields), -- textures (embedded as Video content when texture.data is set, else a file reference), skins (Skin / Cluster + -- BindPose), morph targets (BlendShape channels) and animations (one stack per animation; rotation channels as Euler --- XYZ curves). Readable by assimp, Blender and the FBX SDK. +-- XYZ curves; arrays zlib-compressed unless opts.compress = false). Checked with assimp and Blender (not the FBX SDK). -- Not supported: FBX 6.x and older (UNSUPPORTED), NURBS / patch / line geometry (skipped), constraints, layered -- animation blending (the first layer that animates a property wins), cubic curve tangents on write (keys are linear). From 08ea206447e455093f81c785b0dab11e23d20042 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:56:39 -0500 Subject: [PATCH 7/8] compat: __iter walks 1..#t skipping holes (sparse integer maps / arrays with holes visited fully on LuaJIT, as in Luau) --- compat/luajit.lua | 17 ++++++++++++++++- tests/compat.luau | 21 +++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/compat/luajit.lua b/compat/luajit.lua index c5b1813..72cb133 100644 --- a/compat/luajit.lua +++ b/compat/luajit.lua @@ -404,13 +404,28 @@ do end -- ---------------------------------------------------------------------------------------------------- __iter +local function arrayIter(s, i) + local t, n = s[1], s[2] + i = i + 1 + local v = t[i] + while v == nil and i < n do + i = i + 1 + v = t[i] + end + if v ~= nil then return i, v end +end function M.__iter(t, s, c) if rawtype(t) == "function" then return t, s, c end if rawtype(t) ~= "table" then error("attempt to iterate over a " .. M.type(t) .. " value", 2) end local mt = getmetatable(t) if rawtype(mt) == "table" and mt.__iter then return mt.__iter(t) end local n = #t - if n > 0 and t[0] == nil and next(t, n) == nil then return ipairs(t) end -- LuaJIT keeps t[0] in the array part + -- every key is an integer in 1..n (next(t, n) == nil: nothing after n in the array part, an empty hash part; + -- LuaJIT keeps t[0] in the array part, so check it): walk 1..n skipping holes. #t is any border, so sparse maps + -- such as {[6] = a, [7] = b} (n = 7, t[1] == nil) and arrays with holes visit every key, as in Luau. + if n > 0 and t[0] == nil and next(t, n) == nil then + return arrayIter, { t, n }, 0 + end return next, t, nil end diff --git a/tests/compat.luau b/tests/compat.luau index 2883d58..bfba55a 100644 --- a/tests/compat.luau +++ b/tests/compat.luau @@ -299,4 +299,25 @@ do -- float reads: NaNs with a payload come back as the canonical NaN (LuaJIT: n t:eq(buffer.readf64(b, 8), -2.25, "f64 normal") end +do -- generalized iteration visits every key of sparse integer maps and arrays with holes (LuaJIT array-part borders) + local function collect(t) + local ks = {} + for k, v in t do + table.insert(ks, tostring(k) .. "=" .. tostring(v)) + end + table.sort(ks) + return table.concat(ks, ",") + end + local sparse = {} + sparse[6] = "a" + sparse[7] = "b" + t:eq(collect(sparse), "6=a,7=b", "sparse integer map") + local holes = { 1, 2, 3, 4 } + holes[2] = nil + t:eq(collect(holes), "1=1,3=3,4=4", "array with a hole") + t:eq(collect({ 10, 20, 30 }), "1=10,2=20,3=30", "dense array") + t:eq(collect({ [0] = "z", "a" }), "0=z,1=a", "index 0") + t:eq(collect({ "a", x = 1 }), "1=a,x=1", "mixed") +end + t:done() From 52a34f50eda97ad9282ab0e95ac952eeed3dc6cb Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 10:22:56 -0500 Subject: [PATCH 8/8] merge ws/video: resolve init.luau (openAudio + plugins hooks, cad and video facades) --- src/Formats/init.luau | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 3d956a7..57d5dcc 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -259,16 +259,7 @@ end -- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) -> -- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for -- the embedded parts) when called directly. -<<<<<<< HEAD -- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own. -local function withHooks(o: Options): Options - if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil then - return o - end - local c = table.clone(o) - if c.plugins == nil then - c.plugins = F.plugins -======= -- -- Audio tracks of video containers: opts.openAudio(demuxer, track) -> audio Decoder | nil, Err. The track's packets -- become a stream an audio format reads (containers/AudioWrap: PCM -> WAV, Opus / Vorbis -> Ogg, AAC -> ADTS, MP3 / @@ -288,13 +279,15 @@ local function openAudio(demuxer: any, track: any): (any, Err.Err?) end local function withHooks(o: Options): Options - if o.decodeImage ~= nil and o.encodeImage ~= nil and o.openAudio ~= nil then + if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil and o.openAudio ~= nil then return o end local c = table.clone(o) + if c.plugins == nil then + c.plugins = F.plugins + end if c.openAudio == nil then c.openAudio = openAudio ->>>>>>> ws/video end if c.decodeImage == nil then c.decodeImage = function(b: buffer): (any, Err.Err?) @@ -598,7 +591,6 @@ for category in Types.CATEGORIES do end F.data.null = Types.null -<<<<<<< HEAD -- F.cad.toBodies(cad, opts?) -> bodies, result | nil, Err; F.cad.fromBodies(bodies, opts?) -> Cad | nil, Err; -- F.cad.tessellate(cad | bodies, opts?) -> Scene | nil, Err: cad/step's B-rep calls with the injected kernel -- (F.plugins.brep, unless opts.brep / opts.plugins is given). Without a plug-in they return Err.UNSUPPORTED. @@ -623,7 +615,6 @@ for _, fn in { "toBodies", "fromBodies", "tessellate" } do return a, b end end -======= -- F.video.fromImage(img, opts?) -> a frames-backed VideoDecoder: an animated GIF / APNG / WebP (img.frames, composited -- onto full canvases by ImageOps.coalesce) or a still image (one frame). opts.rgba is accepted (frames are rgba8). F.video.fromImage = function(img: any, opts: Options?): (any, Err.Err?) @@ -658,7 +649,6 @@ F.video.fromFrames = function(images: any, delays: any?, opts: Options?): (any, end -- F.video.codecs: the video codec registry (codecs/Video: register / entry / fromFourcc / fromMatroska / decoder) F.video.codecs = Video ->>>>>>> ws/video -- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or -- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images