From d4affd565eec621c0044bd8846333807092ba56d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:46:25 -0500 Subject: [PATCH] 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)