From d41d64219a8783b48f74530f6a36f3ea9b84d1b0 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 13:52:17 -0500 Subject: [PATCH 1/8] ws-game: archive/pak (Quake PACK / SiN SPAK read + write); containers/Archive: slice() lazy loader and collect() for simple archive writers (additive) --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 +++ src/Formats/archive/pak/init.luau | 135 ++++++++++++++++++++++++++++ src/Formats/containers/Archive.luau | 31 +++++++ tests/archive/pak.luau | 87 ++++++++++++++++++ tools/fixtures/pak.py | 63 +++++++++++++ 6 files changed, 329 insertions(+) create mode 100644 src/Formats/archive/pak/init.luau create mode 100644 tests/archive/pak.luau create mode 100644 tools/fixtures/pak.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..2c0a5a1 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -53,6 +53,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | archive | br | .br | yes | - | stream: true | `tests/archive/br.luau` | | archive | bz2 | .bz2 .tbz2 .tbz | yes | - | stream: true | `tests/archive/bz2.luau` | | archive | gzip | .gz .tgz .gzip | yes | yes | stream: true | `tests/archive/gzip.luau` | +| archive | pak | .pak .sin | yes | yes | variants: "quake", "sin" | `tests/archive/pak.luau` | | archive | tar | .tar | yes | yes | variants: "ustar", "pax", "gnu" | `tests/archive/tar.luau` | | archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` | | archive | zip | .zip .wsz | yes | yes | methods: "store", "deflate", zip64: true | `tests/archive/zip.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..5000567 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -590,6 +590,18 @@ local list: { Entry } = { return require("@formats/archive/gzip") end, }, + { + name = "pak", + category = "archive", + path = "archive/pak", + extensions = { "pak", "sin" }, + mime = { "application/x-pak" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "quake", "sin" } }, + load = function() + return require("@formats/archive/pak") + end, + }, { name = "tar", category = "archive", diff --git a/src/Formats/archive/pak/init.luau b/src/Formats/archive/pak/init.luau new file mode 100644 index 0000000..cd48140 --- /dev/null +++ b/src/Formats/archive/pak/init.luau @@ -0,0 +1,135 @@ +--!strict +-- archive/pak: Quake / Quake II / Half-Life PAK archives ("PACK": 56-byte names, 64-byte directory entries) and the +-- SiN variant ("SPAK": 120-byte names), read into the standard Archive (entries read lazily: a copy of the stored +-- bytes) and written from any Archive value. Written from the format description in the Quake source release +-- (common.c: dpackheader_t / dpackfile_t) and the Quake specs; no code taken. +-- Not supported: Daikatana's compressed PAK entries. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Archive = require("@formats/containers/Archive") + +-- ------------------------------------------------------------------------------------------------ contract +local Pak = { + name = "pak", + category = "archive", + extensions = { "pak", "sin" }, + mime = { "application/x-pak" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" }, + caps = { decode = true, encode = true, variants = { "quake", "sin" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { maxEntries: number? } -- default 1e6 +export type EncodeOptions = { variant: ("quake" | "sin")? } -- default: the source variant, else "quake" + +-- ------------------------------------------------------------------------------------------------ constants +local VARIANTS = { quake = { magic = "PACK", nameLen = 56 }, sin = { magic = "SPAK", nameLen = 120 } } + +-- ------------------------------------------------------------------------------------------------ sniff +function Pak.sniff(r: Bytes.Reader): number + if r:remaining() < 12 then + return 0 + end + return math.max(Sniff.magic(r, "PACK", 0, 0.9), Sniff.magic(r, "SPAK", 0, 0.9)) +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Pak.encode(archive, opts) +end + +function Pak.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local magic = r:string(4) + local dirOfs, dirLen = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + local variant = if magic == "PACK" then "quake" elseif magic == "SPAK" then "sin" else nil + if not variant then + return nil, Err.new(Err.CORRUPT, "bad magic", 0) + end + local nameLen = VARIANTS[variant].nameLen + local entrySize = nameLen + 8 + local size = r.limit - r.base + if dirOfs + dirLen > size then + return nil, Err.new(Err.TRUNCATED, "directory past the end", 4) + end + if dirLen % entrySize ~= 0 then + return nil, Err.new(Err.CORRUPT, "directory size is not a multiple of " .. entrySize, 8) + end + local count = dirLen // entrySize + if count > (opts and opts.maxEntries or 1e6) then + return nil, Err.new(Err.LIMIT, "too many entries: " .. count) + end + local a = Archive.new("pak", encode) + local d = r:sub(dirOfs, dirLen) + for i = 0, count - 1 do + local name = d:fixed(nameLen) + local at, n = d:u32le(), d:u32le() + if d.err then + return nil, d.err + end + if at + n > size then + return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " past the end", dirOfs + i * entrySize) + end + Archive.put(a, { name = name, size = n, dir = false, method = "store", offset = at, load = Archive.slice(r.buf, r.base + at, n) }) + end + a.meta.source = { format = "pak", variant = variant, entries = count } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Pak.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local items, err = Archive.collect(archive) + if not items then + return nil, err + end + local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source + local variant = opts and opts.variant or (if type(src) == "table" and src.format == "pak" then src.variant else nil) or "quake" + local v = VARIANTS[variant] + if not v then + return nil, Err.new(Err.ARG, "unknown variant " .. tostring(variant)) + end + local files: { { name: string, data: buffer } } = {} + for _, it in items do + if not it.entry.dir then + local name = string.gsub(it.entry.name, "\\", "/") + if #name >= v.nameLen then + return nil, Err.new(Err.ARG, "name longer than " .. (v.nameLen - 1) .. " bytes: " .. name) + end + table.insert(files, { name = name, data = it.data }) + end + end + local w = Bytes.writer() + w:string(v.magic) + w:u32le(0) + w:u32le(0) + local offsets: { number } = {} + for i, f in files do + offsets[i] = w:tell() + w:bytes(f.data) + end + local dirOfs = w:tell() + for i, f in files do + w:string(f.name) + w:fill(0, v.nameLen - #f.name) + w:u32le(offsets[i]) + w:u32le(buffer.len(f.data)) + end + w:setU32le(4, dirOfs) + w:setU32le(8, w:tell() - dirOfs) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- new(variant?) -> an empty PAK Archive: a:add(name, data); a:write() +function Pak.new(variant: ("quake" | "sin")?): any + local a = Archive.new("pak", encode) + a.meta.source = { format = "pak", variant = variant or "quake" } + return a +end + +return Pak diff --git a/src/Formats/containers/Archive.luau b/src/Formats/containers/Archive.luau index ef9a63d..53817b3 100644 --- a/src/Formats/containers/Archive.luau +++ b/src/Formats/containers/Archive.luau @@ -152,6 +152,37 @@ function Archive.entries(value: any): { { entry: Types.ArchiveEntry, read: () -> return out end +-- slice(buf, at, n) -> a loader for Entry.load: a copy of buf[at, at + n) (stored entries of uncompressed archives) +function Archive.slice(buf: buffer, at: number, n: number): () -> (buffer?, Err.Err?) + return function(): (buffer?, Err.Err?) + local out = buffer.create(n) + buffer.copy(out, 0, buf, at, n) + return out, nil + end +end + +-- collect(value) -> { { entry, data } } | nil, Err: every entry of an Archive-shaped value with its bytes read +-- (directories: data = an empty buffer), for writers of simple archives (PAK, WAD, GRP, VPK, ...) +function Archive.collect(value: any): ({ { entry: Types.ArchiveEntry, data: buffer } }?, Err.Err?) + local items = Archive.entries(value) + if not items then + return nil, Err.new(Err.ARG, "expected an Archive") + end + local out: { { entry: Types.ArchiveEntry, data: buffer } } = {} + for _, it in items do + local b: buffer = buffer.create(0) + if not it.entry.dir then + local d, err = it.read() + if not d then + return nil, err or Err.new(Err.CORRUPT, "entry " .. it.entry.name .. ": read failed") + end + b = d + end + table.insert(out, { entry = it.entry, data = b }) + end + return out, nil +end + -- streamName(opts, ext) -> the entry name for a single-stream archive: opts.name without its compression extension -- (".tgz" -> ".tar"), else "data" function Archive.streamName(opts: any?, exts: { string }): string diff --git a/tests/archive/pak.luau b/tests/archive/pak.luau new file mode 100644 index 0000000..6e03040 --- /dev/null +++ b/tests/archive/pak.luau @@ -0,0 +1,87 @@ +-- archive/pak tests: Quake ("PACK") and SiN ("SPAK") archives written by tools/fixtures/pak.py list the entries an +-- independent Python reader sees (names, sizes, data CRCs); our writer produces the same bytes as the Python writer +-- for the same files and round-trips; conversion from a tar; errors; the fuzz pass. Fixtures: tools/fixtures/pak.py. +local T = require("@tests/T") +local F = require("@formats") +local Pak = require("@formats/archive/pak") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/pak") + +local t = T.suite("pak") +t:eq(Pak.name, "pak", "name") +t:check(Pak.caps.decode and Pak.caps.encode, "caps") + +for _, c in Fx do + local a, err = Pak.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(a, c.name .. ": " .. tostring(err)) + local list = a:list() + t:eq(#list, #c.entries, c.name .. ": entry count") + for i, w in c.entries do + t:eq(list[i].name, w.name, c.name .. ": name " .. i) + t:eq(list[i].size, w.size, c.name .. ": size " .. w.name) + t:eq(Crc32.of((a:read(w.name))), w.crc, c.name .. ": data " .. w.name) + end + t:eq(a.meta.source.variant, c.variant, c.name .. ": variant") + if #c.data > 12 then + t:eq(F.detect(c.data), "pak", c.name .. ": F.detect") + end + -- the writer: same layout as the Python writer + local n = Pak.new(c.variant) + for _, f in c.files do + n:add(f.name, f.data) + end + local out = n:write() :: buffer + if c.layoutDefault then + t:check(buffer.tostring(out) == c.data, c.name .. ": bytes identical to the Python writer") + end + local back = Pak.decode(Bytes.reader(out)) + t:eq(#back:list(), #c.files, c.name .. ": round trip count") + -- rewriting a decoded archive keeps its variant + local again = F.save(a) :: buffer + t:eq(buffer.readstring(again, 0, 4), if c.variant == "sin" then "SPAK" else "PACK", c.name .. ": F.save keeps the variant") +end + +-- a sub-range reader, conversion from another archive, errors +do + local c = Fx[1] + local big = buffer.create(#c.data + 7) + buffer.writestring(big, 7, c.data) + local a = Pak.decode(Bytes.reader(big, 7, #c.data)) + t:check(a and Crc32.of((a:read(c.entries[2].name))) == c.entries[2].crc, "decode from a sub-range") + local tar = F.format("tar").new() + tar:add("dir/", "", { dir = true }) + tar:add("dir/x.txt", "x") + local p = F.load(F.save(tar, nil, { format = "pak" }) :: buffer) + t:check(p.format == "pak" and #p:list() == 1 and buffer.tostring(p:read("dir/x.txt")) == "x", "tar -> pak (directories dropped)") + local _, e1 = Pak.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, #c.data - 10)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local bad = buffer.fromstring(c.data) + buffer.writeu32(bad, 8, 65) + local _, e2 = Pak.decode(Bytes.reader(bad)) + t:check(e2 and e2.code == Err.CORRUPT, "directory size: " .. tostring(e2)) + local long = Pak.new() + long:add(string.rep("n", 56), "x") + local _, e3 = long:write() + t:check(e3 and e3.code == Err.ARG, "a 56-byte name does not fit") + local _, e4 = Pak.encode({ kind = "image" }) + t:check(e4 and e4.code == Err.ARG, "encode a non-archive") +end + +local samples = {} +for _, c in Fx do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + local a = Pak.decode(Bytes.reader(b)) + if a then + for _, e in a:list() do + a:read(e.name) + end + a:write() + end + return a +end, samples, { mutations = 40 }) + +t:done() diff --git a/tools/fixtures/pak.py b/tools/fixtures/pak.py new file mode 100644 index 0000000..dca7da8 --- /dev/null +++ b/tools/fixtures/pak.py @@ -0,0 +1,63 @@ +# Quake PAK fixtures (tools/fixtures.py): PAK files written here from the Quake source's dpackheader_t / dpackfile_t +# layout (header, file data in order, directory at the end: the layout id's qpak and most tools write), in the Quake +# ("PACK", 56-byte names) and SiN ("SPAK", 120-byte names) variants, plus one with the directory first and padding +# between files; with the expected entries read back by an independent Python reader here. +# tests/gen/pak.luau { { name, variant, data, entries = { { name, size, crc } }, files = { { name, data } } } } +import struct, zlib + +VARIANTS = {"quake": (b"PACK", 56), "sin": (b"SPAK", 120)} + + +def write(files, variant="quake", dir_first=False, pad=0): + magic, nl = VARIANTS[variant] + dirlen = len(files) * (nl + 8) + out = bytearray(magic + b"\0" * 8) + if dir_first: + dirofs = 12 + out += b"\0" * dirlen + offs = [] + for name, data in files: + out += b"\xee" * pad + offs.append(len(out)) + out += data + if not dir_first: + dirofs = len(out) + out += b"\0" * dirlen + for i, (name, data) in enumerate(files): + struct.pack_into("<%dsII" % nl, out, dirofs + i * (nl + 8), name.encode(), offs[i], len(data)) + struct.pack_into(" Date: Sat, 31 Oct 2026 13:54:43 -0500 Subject: [PATCH 2/8] ws-game: codecs/model/Rig (morph targets + weights animations, skeletons + skins, influences, joint TRS animations for the game model formats); codecs/image/Pixels.palette (RGB / BGR triples -> u32 palette; additive) --- docs/FORMATS.md | 1 + src/Formats/codecs/image/Pixels.luau | 21 +++ src/Formats/codecs/model/Rig.luau | 223 +++++++++++++++++++++++++++ tests/codecs/rig.luau | 93 +++++++++++ 4 files changed, 338 insertions(+) create mode 100644 src/Formats/codecs/model/Rig.luau create mode 100644 tests/codecs/rig.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 2c0a5a1..91a5232 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -127,6 +127,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **model** - codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks + - codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is diff --git a/src/Formats/codecs/image/Pixels.luau b/src/Formats/codecs/image/Pixels.luau index 49cd14f..d8ae224 100644 --- a/src/Formats/codecs/image/Pixels.luau +++ b/src/Formats/codecs/image/Pixels.luau @@ -13,6 +13,27 @@ local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lsh local Pixels = {} +-- palette(src, base, n, bgr?) -> a 256-entry u32 palette for indexed(): n RGB triples (BGR when bgr) at src[base..], +-- opaque; entries past n (or past the end of src) are opaque black. The game formats' 768-byte palettes (PLAYPAL, +-- Quake palette.lmp, Half-Life MDL / WAD3 / BSP 30 textures). +function Pixels.palette(src: buffer, base: number, n: number, bgr: boolean?): buffer + local pal = buffer.create(1024) + local m = if base >= 0 then math.clamp(math.min(n, (buffer.len(src) - base) // 3), 0, 256) else 0 + for i = 0, 255 do + local v = 0xFF000000 + if i < m then + local o = base + i * 3 + local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2) + if bgr then + r, b = b, r + end + v = bor(0xFF000000, lshift(b, 16), lshift(g, 8), r) + end + writeu32(pal, i * 4, v) + end + return pal +end + -- 1, 2, 4 and 8 bpp through a 256-entry u32 palette (pal) function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number, topDown: boolean, pal: buffer) diff --git a/src/Formats/codecs/model/Rig.luau b/src/Formats/codecs/model/Rig.luau new file mode 100644 index 0000000..53bf256 --- /dev/null +++ b/src/Formats/codecs/model/Rig.luau @@ -0,0 +1,223 @@ +--!strict +-- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each +-- format only parses its file: vertex-animation frames as morph targets plus "weights" animations, joint hierarchies +-- as Scene nodes plus a Skin (inverse bind matrices), per-vertex joint influences as JOINTS_0 / WEIGHTS_0, and +-- keyframed joint TRS tracks as animation channels. New in formats-luau. +-- +-- Rig.morph(prim, frames) -- frames[k] = f32 x3 positions: targets[k] = frame k - base +-- Rig.morphAnimation(scene, node, #frames, { { name = "run", first = 41, last = 46, fps = 10 } }, "LINEAR") +-- local nodes, skin = Rig.skeleton(scene, joints, "world") -- joints = { { name, parent (0 = root), t, r, s? } } +-- prim.attributes.JOINTS_0, prim.attributes.WEIGHTS_0 = Rig.influences(lists) -- lists[v] = { j1, w1, j2, w2, ... } +-- Rig.animation(scene, "idle", nodes, times, tracks) -- tracks[j] = { translation = {...}, rotation = {...} } +-- +-- Frames, joints and tracks come from parsed files: the helpers check every count they rely on and never throw. +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") + +local Rig = {} + +local Scene = Types.Scene +local readf32, writef32, writeu16 = buffer.readf32, buffer.writef32, buffer.writeu16 + +export type Joint = { + name: string?, + parent: number, -- 1-based index into the joint list, 0 for a root (parents come before their children) + translation: { number }, + rotation: { number }, -- quaternion x, y, z, w + scale: { number }?, +} +export type Range = { name: string?, first: number, last: number, fps: number? } -- frames first..last (1-based) +export type Track = { translation: { number }?, rotation: { number }?, scale: { number }? } -- flat, one key per time + +-- ------------------------------------------------------------------------------------------------ morph targets +-- morph(prim, frames, normals?, base?) -> (): prim.targets[k] = { POSITION = frames[k] - base positions } (and NORMAL +-- deltas when normals[k] is given), base = prim.attributes.POSITION (and NORMAL). Every frame buffer must hold as +-- many f32 x3 as the base; shorter ones are skipped (false is returned). +function Rig.morph(prim: Types.Primitive, frames: { buffer }, normals: { buffer }?): boolean + local pos = prim.attributes.POSITION + if not pos or pos.type ~= "f32" or pos.components ~= 3 then + return false + end + local nrm = prim.attributes.NORMAL + local n = pos.count * 3 + local targets: { { [string]: Types.Accessor } } = {} + local ok = true + for k, f in frames do + if buffer.len(f) < n * 4 then + ok = false + break + end + local t: { [string]: Types.Accessor } = {} + local d = buffer.create(n * 4) + local base = pos.data + for i = 0, n - 1 do + writef32(d, i * 4, readf32(f, i * 4) - readf32(base, i * 4)) + end + t.POSITION = Scene.accessor(d, "f32", 3, pos.count) + local fn = normals and normals[k] + if nrm and fn and nrm.type == "f32" and buffer.len(fn) >= n * 4 then + local dn = buffer.create(n * 4) + for i = 0, n - 1 do + writef32(dn, i * 4, readf32(fn, i * 4) - readf32(nrm.data, i * 4)) + end + t.NORMAL = Scene.accessor(dn, "f32", 3, pos.count) + end + targets[k] = t + end + if ok then + prim.targets = targets + end + return ok +end + +-- morphAnimation(scene, node, targets, ranges, interpolation?) -> (): one animation per range, a "weights" channel on +-- scene.nodes[node] whose key k (at (k - first) / fps seconds) sets target k to 1 and the others to 0 (LINEAR +-- blends neighbouring frames, as the games do; default "LINEAR"). Ranges out of 1..targets are clamped / skipped. +function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, ranges: { Range }, interpolation: string?) + for _, rg in ranges do + local first, last = math.max(1, math.floor(rg.first)), math.min(targets, math.floor(rg.last)) + if last >= first then + local keys = last - first + 1 + local fps = if rg.fps and rg.fps > 0 then rg.fps else 10 + local times = buffer.create(keys * 4) + local weights = buffer.create(keys * targets * 4) + for k = 0, keys - 1 do + writef32(times, k * 4, k / fps) + writef32(weights, (k * targets + first - 1 + k) * 4, 1) + end + table.insert(scene.animations, { + name = rg.name, + channels = { + { + node = node, + path = "weights" :: any, + input = Scene.accessor(times, "f32", 1, keys), + output = Scene.accessor(weights, "f32", 1, keys * targets), + interpolation = (if interpolation == "STEP" then "STEP" else "LINEAR") :: any, + }, + }, + }) + end + end +end + +-- ------------------------------------------------------------------------------------------------ skeletons +local function trs(j: Joint): { number } + return Mat4.compose(j.translation, j.rotation, j.scale) +end + +-- skeleton(scene, joints, space, root?) -> (joint node indices, skin index): one node per joint (TRS relative to its +-- parent), parented as listed, roots added to scene.roots (or as children of node `root`); a Skin with the inverse +-- bind matrices. space "local": joint TRS are relative to the parent (SMD, MDL); "world": in model space (MD5's +-- bind pose), converted to local here. A parent index that does not come earlier makes the joint a root. +function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "world", root: number?): ({ number }, number) + local n = #joints + local world: { { number } } = {} + local nodes: { number } = {} + for i, j in joints do + local p = if j.parent >= 1 and j.parent < i then j.parent else 0 + local m = trs(j) + local lt, lr, ls = j.translation, j.rotation, j.scale + if space == "world" then + world[i] = m + if p > 0 then + local inv = Mat4.inverse(world[p]) + if inv then + local t, r, s = Mat4.decompose(Mat4.mul(inv, m)) + lt, lr, ls = t, r, s + end + end + else + world[i] = if p > 0 then Mat4.mul(world[p], m) else m + end + local node: Types.Node = { name = j.name, children = {}, translation = table.clone(lt), rotation = table.clone(lr), scale = if ls then table.clone(ls) else nil } + table.insert(scene.nodes, node) + local idx = #scene.nodes + nodes[i] = idx + if p > 0 then + table.insert(scene.nodes[nodes[p]].children, idx) + elseif root and scene.nodes[root] then + table.insert(scene.nodes[root].children, idx) + else + table.insert(scene.roots, idx) + end + end + local ibm = buffer.create(n * 64) + for i = 1, n do + local inv = Mat4.inverseFull(world[i]) or Mat4.identity() + for k = 1, 16 do + writef32(ibm, ((i - 1) * 16 + k - 1) * 4, inv[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, n) + acc.matrix = true + table.insert(scene.skins, { joints = nodes, inverseBindMatrices = acc, skeleton = if n > 0 then nodes[1] else nil }) + return nodes, #scene.skins +end + +-- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with +-- 0-based joint indices (into the skin's joints); the four largest weights are kept and normalised to sum 1. +function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor) + local n = #lists + local jb, wb = buffer.create(n * 8), buffer.create(n * 16) + for v, l in lists do + local pairs_: { { number } } = {} + for k = 1, #l - 1, 2 do + if l[k + 1] > 0 then + table.insert(pairs_, { l[k], l[k + 1] }) + end + end + table.sort(pairs_, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local sum = 0 + for k = 1, math.min(4, #pairs_) do + sum += pairs_[k][2] + end + for k = 1, math.min(4, #pairs_) do + writeu16(jb, ((v - 1) * 4 + k - 1) * 2, math.clamp(pairs_[k][1], 0, 65535)) + writef32(wb, ((v - 1) * 4 + k - 1) * 4, pairs_[k][2] / sum) + end + end + return Scene.accessor(jb, "u16", 4, n), Scene.accessor(wb, "f32", 4, n) +end + +-- ------------------------------------------------------------------------------------------------ animations +local function floats(t: { number }, count: number, comps: number): Types.Accessor? + if #t < count * comps then + return nil + end + local b = buffer.create(count * comps * 4) + for i = 1, count * comps do + writef32(b, (i - 1) * 4, t[i]) + end + return Scene.accessor(b, "f32", comps, count) +end + +-- animation(scene, name, nodes, times, tracks, interpolation?) -> the animation index: tracks[j] (j = index into +-- nodes) holds flat translation (x3) / rotation (quaternion x4) / scale (x3) keys, one per time (seconds); tracks +-- with too few keys are skipped. Default interpolation "LINEAR". +function Rig.animation(scene: Types.Scene, name: string?, nodes: { number }, times: { number }, tracks: { [number]: Track }, interpolation: string?): number + local count = #times + local input = floats(times, count, 1) + local channels: { Types.Channel } = {} + local interp: any = if interpolation == "STEP" then "STEP" else "LINEAR" + if input then + for j, tr in tracks do + local node = nodes[j] + if node then + for _, path in { "translation", "rotation", "scale" } do + local keys = (tr :: any)[path] + local acc = keys and floats(keys, count, if path == "rotation" then 4 else 3) + if acc then + table.insert(channels, { node = node, path = path :: any, input = input, output = acc, interpolation = interp }) + end + end + end + end + end + table.insert(scene.animations, { name = name, channels = channels }) + return #scene.animations +end + +return Rig diff --git a/tests/codecs/rig.luau b/tests/codecs/rig.luau new file mode 100644 index 0000000..6accbd5 --- /dev/null +++ b/tests/codecs/rig.luau @@ -0,0 +1,93 @@ +-- codecs/model/Rig tests: morph targets and weights animations from frames, skeletons in local and world space +-- (node TRS, inverse bind matrices against Mat4), influences (top four, normalised), joint TRS animations; and +-- Pixels.palette. +local T = require("@tests/T") +local Rig = require("@formats/codecs/model/Rig") +local Mat4 = require("@formats/codecs/model/Mat4") +local Pixels = require("@formats/codecs/image/Pixels") +local Types = require("@formats/Types") + +local t = T.suite("codecs/rig") +local Scene = Types.Scene + +local function f32s(list: { number }): buffer + local b = buffer.create(#list * 4) + for i, v in list do + buffer.writef32(b, (i - 1) * 4, v) + end + return b +end +local function near(a: number, b: number): boolean + return math.abs(a - b) < 1e-5 +end + +-- morph +do + local base = { 0, 0, 0, 1, 0, 0 } + local prim: Types.Primitive = { attributes = { POSITION = Scene.accessor(f32s(base), "f32", 3, 2) }, mode = "points" } + local frames = { f32s(base), f32s({ 0, 1, 0, 1, 2, 0 }), f32s({ 0, 0, 3, 1, 0, 3 }) } + t:check(Rig.morph(prim, frames), "morph") + local tg = prim.targets :: any + t:eq(#tg, 3, "one target per frame") + t:eq(buffer.readf32(tg[2].POSITION.data, 4), 1, "delta y") + t:eq(buffer.readf32(tg[3].POSITION.data, 20), 3, "delta z") + t:check(not Rig.morph(prim, { buffer.create(4) }), "short frame refused") + local s = Scene.new() + s.nodes[1] = { children = {}, mesh = 1 } + Rig.morphAnimation(s, 1, 3, { { name = "a", first = 2, last = 3, fps = 5 }, { name = "none", first = 9, last = 12 } }) + t:eq(#s.animations, 1, "out-of-range range skipped") + local ch = s.animations[1].channels[1] + t:eq(ch.path, "weights", "weights channel") + t:eq(ch.input.count, 2, "two keys") + t:check(near(buffer.readf32(ch.input.data, 4), 0.2), "fps") + t:eq(buffer.readf32(ch.output.data, 1 * 4), 1, "key 1 -> target 2") + t:eq(buffer.readf32(ch.output.data, (3 + 2) * 4), 1, "key 2 -> target 3") +end + +-- skeleton +do + local q = Mat4.axisAngle(0, 0, 1, 90) + local joints = { + { name = "root", parent = 0, translation = { 1, 0, 0 }, rotation = q }, + { name = "child", parent = 1, translation = { 0, 2, 0 }, rotation = { 0, 0, 0, 1 } }, + } + local s = Scene.new() + local nodes, skin = Rig.skeleton(s, joints, "local") + t:eq(#nodes, 2, "two joint nodes") + t:eq(s.roots[1], nodes[1], "root") + t:eq(s.nodes[nodes[1]].children[1], nodes[2], "parenting") + local ibm = s.skins[skin].inverseBindMatrices :: Types.Accessor + -- child world = T(1,0,0) R90 T(0,2,0): its origin is at (-1, 0, 0); the inverse maps it back to 0 + local inv = {} + for k = 1, 16 do + inv[k] = buffer.readf32(ibm.data, (16 + k - 1) * 4) + end + local x, y, z = Mat4.point(inv, -1, 0, 0) + t:check(near(x, 0) and near(y, 0) and near(z, 0), "inverse bind matrix") + -- the same joints given in world space give the same local TRS + local w = Scene.new() + local wn = Rig.skeleton(w, { + joints[1], + { name = "child", parent = 1, translation = { -1, 0, 0 }, rotation = q }, + }, "world") + local c = w.nodes[wn[2]] + t:check(near(c.translation[1], 0) and near(c.translation[2], 2) and near(c.rotation[4], 1), "world -> local") + local j, wt = Rig.influences({ { 0, 1 }, { 1, 0.2, 2, 0.6, 3, 0.1, 4, 0.05, 5, 0.05 } }) + t:eq(buffer.readu16(j.data, 8), 2, "largest weight first") + t:check(near(buffer.readf32(wt.data, 16) + buffer.readf32(wt.data, 20) + buffer.readf32(wt.data, 24) + buffer.readf32(wt.data, 28), 1), "normalised") + t:eq(buffer.readf32(wt.data, 0), 1, "single influence") + local ai = Rig.animation(s, "wave", nodes, { 0, 0.5 }, { [2] = { rotation = { 0, 0, 0, 1, 0, 0, 1, 0 }, translation = { 0 } } }) + t:eq(#s.animations[ai].channels, 1, "short track skipped, rotation kept") + t:eq(s.animations[ai].channels[1].node, nodes[2], "channel node") +end + +-- palette +do + local pal = Pixels.palette(buffer.fromstring("\1\2\3\4\5\6"), 0, 2) + t:eq(buffer.readu32(pal, 4), 0xFF060504, "rgb triples") + t:eq(buffer.readu32(pal, 8), 0xFF000000, "missing entries black") + t:eq(buffer.readu32(Pixels.palette(buffer.fromstring("\1\2\3"), 0, 1, true), 0), 0xFF010203, "bgr") + t:eq(buffer.readu32(Pixels.palette(buffer.create(3), -5, 1), 0), 0xFF000000, "bad base") +end + +t:done() From 1aaf8fce68584b70532cb448014bec0afd697146 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:03:52 -0500 Subject: [PATCH 3/8] ws-3d3-b: model/lwo (LightWave LWO2 / LWOB / Modo LXOB read: layers with pivots and parents, polygons, VMAP / VMAD uv / colour / normal / weight / morph maps, surfaces and image blocks); 54 assimp test models match assimp's counts, materials and world bounds --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/model/lwo/Build.luau | 467 ++++++++++++++++++++++++++ src/Formats/model/lwo/Parse.luau | 551 +++++++++++++++++++++++++++++++ src/Formats/model/lwo/init.luau | 86 +++++ tests/model/lwo.luau | 315 ++++++++++++++++++ tools/fixtures/lwo.py | 41 +++ 7 files changed, 1473 insertions(+) create mode 100644 src/Formats/model/lwo/Build.luau create mode 100644 src/Formats/model/lwo/Parse.luau create mode 100644 src/Formats/model/lwo/init.luau create mode 100644 tests/model/lwo.luau create mode 100644 tools/fixtures/lwo.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..4ee62bf 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -38,6 +38,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | 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 | lwo | .lwo .lxo | yes | - | materials: true, polygons: true, vertexColors: true, morphTargets: true | `tests/model/lwo.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` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..79dc5d6 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -410,6 +410,18 @@ local list: { Entry } = { return require("@formats/model/gltf") end, }, + { + name = "lwo", + category = "model", + path = "model/lwo", + extensions = { "lwo", "lxo" }, + mime = { "image/x-lwo", "model/x-lwo" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks" }, + caps = { decode = true, encode = false, materials = true, polygons = true, vertexColors = true, morphTargets = true }, + load = function() + return require("@formats/model/lwo") + end, + }, { name = "obj", category = "model", diff --git a/src/Formats/model/lwo/Build.luau b/src/Formats/model/lwo/Build.luau new file mode 100644 index 0000000..0d62bbd --- /dev/null +++ b/src/Formats/model/lwo/Build.luau @@ -0,0 +1,467 @@ +--!strict +-- model/lwo/Build: a parsed LightWave object (model/lwo/Parse) -> Types.Scene. LightWave is left-handed (y up, z +-- away from the viewer, clockwise front faces): z is negated and the winding reversed, so the scene is glTF's +-- right-handed y-up with counter-clockwise front faces (assimp does the same). One node per layer (translation = its +-- pivot relative to the parent layer's pivot, geometry relative to the pivot, so world positions are the file's), +-- one mesh per layer, one primitive per surface (and per kind: polygons, lines, points; subdivision patches apart, +-- flagged extras.lwo.subdivision). Vertices are shared per point, split where a VMAD gives a corner its own value. +-- Plain code (the caller wraps it in pcall). +local Types = require("@formats/Types") +local Parse = require("@formats/model/lwo/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Group = { material: number, class: string, polys: { number } } -- class: "poly" / "patch" / "line" / "point" + +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff", iff = "image/x-iff" } + +-- ------------------------------------------------------------------------------------------------ materials +local function textureIndex(scene: Types.Scene, cache: { [string]: number }, path: string): number + local hit = cache[path] + if hit then + return hit + end + local norm = string.gsub(path, "\\", "/") + local base = string.match(norm, "([^/:]+)$") or norm + local ext = string.lower(string.match(base, "%.(%w+)$") or "") + table.insert(scene.textures, { name = base, uri = base, mime = MIME[ext], extras = { lwo = { path = path } } }) + cache[path] = #scene.textures + return #scene.textures +end + +local function material(scene: Types.Scene, m: Parse.Model, surf: Parse.Surface, uvSets: { [string]: number }, cache: { [string]: number }): Types.Material + local mat = Scene.material(surf.name) + local v = surf.values + local c = surf.color + local tran = math.clamp(v.TRAN or 0, 0, 1) + mat.baseColor = { c[1], c[2], c[3], 1 - tran } + if tran > 0 then + mat.alphaMode = "blend" + end + mat.metallic = 0 + local gloss = v.GLOS + mat.roughness = if gloss and (v.SPEC or 0) > 0 then math.clamp(1 - gloss, 0, 1) else 1 + local lumi = v.LUMI or 0 + if lumi > 0 then + mat.emissive = { c[1] * lumi, c[2] * lumi, c[3] * lumi } + end + mat.doubleSided = surf.side == 3 + local maps = {} + local blocks = table.clone(surf.blocks) + table.sort(blocks, function(a: Parse.Block, b: Parse.Block): boolean + return a.ordinal < b.ordinal + end) + for _, blk in blocks do + local path = if blk.file then blk.file elseif blk.clip then m.clips[blk.clip] else nil + local entry: { [string]: any } = { kind = blk.kind, channel = blk.channel, enabled = blk.enabled, opacity = blk.opacity, projection = blk.projection, axis = blk.axis, uvmap = blk.uvmap } + if path and (blk.kind == "IMAP" or blk.kind == "TEX") then + local ti = textureIndex(scene, cache, path) + entry.texture = ti + if blk.enabled then + local ref: Types.TextureRef = { texture = ti } + if blk.uvmap and uvSets[blk.uvmap] then + ref.texCoord = uvSets[blk.uvmap] + end + if blk.channel == "COLR" and not mat.baseColorTexture then + mat.baseColorTexture = ref + elseif blk.channel == "LUMI" and not mat.emissiveTexture then + mat.emissiveTexture = ref + if lumi <= 0 then + mat.emissive = { 1, 1, 1 } + end + end + end + end + table.insert(maps, entry) + end + local extras: { [string]: any } = { color = table.clone(c), side = surf.side, maps = maps, source = surf.source } + for k, x in v do + extras[string.lower(k)] = x + end + if surf.vcol then + extras.vcol = surf.vcol.name + end + mat.extras = { lwo = extras } + return mat +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function groupLayer(layer: Parse.Layer, surfaceOf: (number?) -> number): { Group } + local groups: { Group } = {} + local byKey: { [string]: Group } = {} + for i, poly in layer.polys do + local kind = poly.kind + local n = #poly.corners + if (kind == "FACE" or kind == "PTCH" or kind == "SUBD") and n > 0 then + local class = if n == 1 then "point" elseif n == 2 then "line" elseif kind == "FACE" then "poly" else "patch" + local mi = surfaceOf(poly.surf) + local key = mi .. class + local g = byKey[key] + if not g then + g = { material = mi, class = class, polys = {} } + byKey[key] = g + table.insert(groups, g) + end + table.insert(g.polys, i - 1) + end + end + local rank = { poly = 1, patch = 2, line = 3, point = 4 } + table.sort(groups, function(a: Group, b: Group): boolean + if a.material ~= b.material then + return a.material < b.material + end + return rank[a.class] < rank[b.class] + end) + return groups +end + +-- the corners of a face in output order (winding reversed for the handedness change, first corner kept) +local function ordered(corners: { number }): { number } + local n = #corners + local out = table.create(n) + out[1] = corners[1] + for k = 2, n do + out[k] = corners[n - k + 2] + end + return out +end + +type Attr = { map: Parse.Map, name: string, comps: number } + +local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: { Parse.Map }, triangulate: boolean): Types.Primitive + local pts, pivot = layer.pts, layer.pivot + local vertOf: { [number]: number } = {} + local srcPoint: { number } = {} -- vertex (1-based) -> point + local srcPoly: { number } = {} -- vertex -> the polygon whose VMAD values it carries (-1: none) + local indices: { number } = {} + local faces: { number } = {} + local madMaps: { Parse.Map } = {} + for _, a in attrs do + if next(a.map.mad) then + table.insert(madMaps, a.map) + end + end + for _, m in morphs do + if next(m.mad) then + table.insert(madMaps, m) + end + end + local function vertex(f: number, p: number): number + local own = false + for _, m in madMaps do + local row = m.mad[f] + if row and row[p] then + own = true + break + end + end + if not own then + local v = vertOf[p] + if v then + return v + end + end + table.insert(srcPoint, p) + table.insert(srcPoly, if own then f else -1) + local v = #srcPoint - 1 + if not own then + vertOf[p] = v + end + return v + end + for _, f in g.polys do + local corners = ordered(layer.polys[f + 1].corners) + local n = #corners + local vs = table.create(n) + for k = 1, n do + vs[k] = vertex(f, corners[k]) + end + if g.class == "poly" or g.class == "patch" then + if triangulate then + for k = 2, n - 1 do + table.insert(indices, vs[1]) + table.insert(indices, vs[k]) + table.insert(indices, vs[k + 1]) + end + else + table.insert(faces, n) + table.move(vs, 1, n, #indices + 1, indices) + end + else + table.move(vs, 1, n, #indices + 1, indices) + end + end + local nv = #srcPoint + local pos = buffer.create(nv * 12) + for v = 1, nv do + local p = srcPoint[v] * 3 + local o = (v - 1) * 12 + writef32(pos, o, pts[p + 1] - pivot[1]) + writef32(pos, o + 4, pts[p + 2] - pivot[2]) + writef32(pos, o + 8, -(pts[p + 3] - pivot[3])) + end + local attributes: { [string]: Types.Accessor } = { POSITION = Scene.accessor(pos, "f32", 3, nv) } + -- the value of map m for vertex v (1-based), or nil + local function value(m: Parse.Map, v: number): ({ number }?, number?) + local f = srcPoly[v] + if f >= 0 then + local row = m.mad[f] + local hit = row and row[srcPoint[v]] + if hit then + return hit, nil + end + end + local p = srcPoint[v] + if m.has[p] then + return nil, p * m.dims + end + return nil, nil + end + local names: { [string]: string } = {} + for _, a in attrs do + local m, comps = a.map, a.comps + local data = buffer.create(nv * comps * 4) + for v = 1, nv do + local o = (v - 1) * comps * 4 + local direct, at = value(m, v) + local x: { number } = if direct then direct elseif at then { m.vals[at + 1], m.vals[at + 2] or 0, m.vals[at + 3] or 0, m.vals[at + 4] or 1 } else {} + if m.kind == "uv" then + writef32(data, o, x[1] or 0) + writef32(data, o + 4, 1 - (x[2] or 0)) + elseif m.kind == "color" then + writef32(data, o, x[1] or 1) + writef32(data, o + 4, x[2] or 1) + writef32(data, o + 8, x[3] or 1) + writef32(data, o + 12, if m.dims == 4 and x[4] then x[4] else 1) + elseif m.kind == "normal" then + writef32(data, o, x[1] or 0) + writef32(data, o + 4, x[2] or 0) + writef32(data, o + 8, -(x[3] or 0)) + else + writef32(data, o, x[1] or 0) + end + end + attributes[a.name] = Scene.accessor(data, "f32", comps, nv) + names[a.name] = m.name + end + local prim: Types.Primitive = { attributes = attributes, mode = "triangles" } + if #morphs > 0 then + local targets = {} + local targetNames = {} + for _, m in morphs do + local d = buffer.create(nv * 12) + for v = 1, nv do + local direct, at = value(m, v) + local x: { number }? = if direct then direct elseif at then { m.vals[at + 1], m.vals[at + 2], m.vals[at + 3] } else nil + if x then + local p = srcPoint[v] * 3 + local dx, dy, dz = x[1], x[2], x[3] + if m.kind == "spot" then + dx, dy, dz = dx - pts[p + 1], dy - pts[p + 2], dz - pts[p + 3] + end + writef32(d, (v - 1) * 12, dx) + writef32(d, (v - 1) * 12 + 4, dy) + writef32(d, (v - 1) * 12 + 8, -dz) + end + end + table.insert(targets, { POSITION = Scene.accessor(d, "f32", 3, nv) }) + table.insert(targetNames, m.name) + end + prim.targets = targets + names._targets = table.concat(targetNames, "\n") + end + local ib = buffer.create(#indices * 4) + for k, x in indices do + writeu32(ib, (k - 1) * 4, x) + end + prim.indices = Scene.accessor(ib, "u32", 1, #indices) + if g.class == "line" then + prim.mode = "lines" + elseif g.class == "point" then + prim.mode = "points" + elseif not triangulate then + prim.mode = "polygons" + local fb = buffer.create(#faces * 4) + for k, x in faces do + writeu32(fb, (k - 1) * 4, x) + end + prim.faces = Scene.accessor(fb, "u32", 1, #faces) + end + prim.material = g.material + local extras: { [string]: any } = { maps = names } + if g.class == "patch" then + extras.subdivision = true + end + prim.extras = { lwo = extras } + return prim +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.Scene?, string?) + local triangulate = not (opts and opts.triangulate == false) + local scene = Scene.new() + scene.meta.up = "y" + scene.meta.source = { format = "lwo", version = m.version, skipped = m.skipped } + -- texture coordinate sets: every TXUV map name, in order of first appearance, gets one TEXCOORD_n index + local uvSets: { [string]: number } = {} + local nuv = 0 + for _, layer in m.layers do + for _, map in layer.maps do + if map.kind == "uv" and uvSets[map.name] == nil then + uvSets[map.name] = nuv + nuv += 1 + end + end + end + -- materials: one per surface, then one per tag without a surface, then a default one + local texCache: { [string]: number } = {} + local bySurfName: { [string]: number } = {} + for i, surf in m.surfaces do + scene.materials[i] = material(scene, m, surf, uvSets, texCache) + if bySurfName[surf.name] == nil then + bySurfName[surf.name] = i + end + local low = string.lower(surf.name) + if bySurfName[low] == nil then + bySurfName[low] = i + end + end + local tagMat: { [number]: number } = {} + local default: number? = nil + local function surfaceOf(tag: number?): number + if tag ~= nil then + local hit = tagMat[tag] + if hit then + return hit + end + local name = m.tags[tag + 1] + if name then + local mi = bySurfName[name] or bySurfName[string.lower(name)] + if not mi then + table.insert(scene.materials, Scene.material(name)) + mi = #scene.materials + bySurfName[name] = mi + end + tagMat[tag] = mi + return mi + end + end + if not default then + local mat = Scene.material("Default") + mat.baseColor = { 0.6, 0.6, 0.6, 1 } + mat.metallic = 0 + table.insert(scene.materials, mat) + default = #scene.materials + end + return default :: number + end + -- nodes and meshes + local nodeOf: { [number]: number } = {} + local layerOfNode: { Parse.Layer } = {} + for _, layer in m.layers do + local hasGeometry = #layer.polys > 0 + if not (layer.implicit and not hasGeometry) then + local node: Types.Node = { name = layer.name, children = {} } + table.insert(scene.nodes, node) + local ni = #scene.nodes + layerOfNode[ni] = layer + if nodeOf[layer.index] == nil then + nodeOf[layer.index] = ni + end + node.extras = { lwo = { index = layer.index, parent = layer.parent, pivot = table.clone(layer.pivot) } } + local groups = groupLayer(layer, surfaceOf) + if #groups > 0 then + local attrs: { Attr } = {} + local morphs: { Parse.Map } = {} + local hasUv = {} + local maxUv = -1 + for _, map in layer.maps do + if map.kind == "uv" then + hasUv[uvSets[map.name]] = map + maxUv = math.max(maxUv, uvSets[map.name]) + elseif map.kind == "morph" or map.kind == "spot" then + table.insert(morphs, map) + end + end + local empty: Parse.Map = { kind = "uv", name = "", dims = 2, vals = {}, has = {}, mad = {} } + for k = 0, maxUv do + table.insert(attrs, { map = hasUv[k] or empty, name = "TEXCOORD_" .. k, comps = 2 }) + end + local nw, nc, hasNormal = 0, 0, false + for _, map in layer.maps do + if map.kind == "normal" and not hasNormal then + hasNormal = true + table.insert(attrs, { map = map, name = "NORMAL", comps = 3 }) + elseif map.kind == "weight" then + table.insert(attrs, { map = map, name = "_WEIGHT_" .. nw, comps = 1 }) + nw += 1 + end + end + local prims = {} + for _, g in groups do + local mat = scene.materials[g.material] + local vcol = mat and mat.extras and mat.extras.lwo and mat.extras.lwo.vcol + local pa = table.clone(attrs) + nc = 0 + for _, map in layer.maps do + if map.kind == "color" then + if map.name == vcol then + table.insert(pa, { map = map, name = "COLOR_0", comps = 4 }) + else + table.insert(pa, { map = map, name = "_COLOR_" .. nc, comps = 4 }) + nc += 1 + end + end + end + table.insert(prims, primitive(layer, g, pa, morphs, triangulate)) + end + local mesh: Types.Mesh = { name = layer.name, primitives = prims } + if #morphs > 0 then + mesh.weights = table.create(#morphs, 0) + local tn = {} + for _, mp in morphs do + table.insert(tn, mp.name) + end + mesh.extras = { targetNames = tn } + end + table.insert(scene.meshes, mesh) + node.mesh = #scene.meshes + end + end + end + -- the layer hierarchy (parents by layer index; a link that would close a cycle is dropped) + local parentOf: { [number]: number } = {} + for ni, layer in layerOfNode do + local pi = if layer.parent ~= nil then nodeOf[layer.parent] else nil + if pi and pi ~= ni then + local up, steps = pi, 0 + while up and up ~= ni and steps <= #scene.nodes do + up = parentOf[up] + steps += 1 + end + if up ~= ni then + parentOf[ni] = pi + end + end + end + for ni = 1, #scene.nodes do + local layer = layerOfNode[ni] + local pi = parentOf[ni] + local pp = if pi then layerOfNode[pi].pivot else { 0, 0, 0 } + local t = { layer.pivot[1] - pp[1], layer.pivot[2] - pp[2], -(layer.pivot[3] - pp[3]) } + if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then + scene.nodes[ni].translation = t + end + if pi then + table.insert(scene.nodes[pi].children, ni) + else + table.insert(scene.roots, ni) + end + end + return scene, nil +end + +return Build diff --git a/src/Formats/model/lwo/Parse.luau b/src/Formats/model/lwo/Parse.luau new file mode 100644 index 0000000..21d985c --- /dev/null +++ b/src/Formats/model/lwo/Parse.luau @@ -0,0 +1,551 @@ +--!strict +-- model/lwo/Parse: the LightWave object chunks -> layers, tags, surfaces and clips (plain tables; model/lwo/Build +-- makes the Scene). From the LWO2 specification (LightWave 6 "Object Files", Ernie Wright) and the LWOB one (LightWave +-- 5.x), checked against what assimp's LWO importer reads (no code taken). +-- LWO2 / LXOB: TAGS, LAYR (index, pivot, name, parent), PNTS (more than one per layer: later POLS / VMAP indices are +-- relative to the latest), VMAP / VMAD (TXUV, RGB, RGBA, WGHT, MNVW, NORM (Modo), MORF, SPOT; others skipped), POLS +-- (FACE, PTCH, SUBD kept; CURV, BONE, MBAL and unknown types counted and skipped), PTAG (SURF, and MATR in Modo +-- files), SURF (COLR, DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SIDE, SMAN, RIND, VCOL, BLOK image / procedural +-- / gradient / shader blocks with their header and IMAP sub-chunks; derived surfaces), CLIP (STIL, ISEQ, XREF). +-- LWOB: SRFS, PNTS, POLS (detail polygons flattened), SURF (COLR, FLAG, the U2 and V* float values, GLOS, SMAN, +-- CTEX ... TTEX with TIMG / TFLG / TVAL). Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks. +-- Plain code (the caller wraps it in pcall); bad data returns nil, message. +local Bytes = require("@formats/core/Bytes") +local Chunks = require("@formats/containers/Chunks") + +local Parse = {} + +export type Map = { + kind: string, -- "uv" | "color" | "normal" | "weight" | "morph" | "spot" + name: string, + dims: number, + vals: { number }, -- per point: vals[point * dims + c + 1] + has: { [number]: boolean }, + mad: { [number]: { [number]: { number } } }, -- VMAD: mad[poly][point] = values +} +export type Poly = { kind: string, surf: number?, corners: { number } } -- corners: 0-based point indices +export type Layer = { + index: number, + name: string?, + parent: number?, + pivot: { number }, + pts: { number }, -- x, y, z flat + polys: { Poly }, + maps: { Map }, + implicit: boolean?, -- the layer before any LAYR +} +export type Block = { + kind: string, -- IMAP / PROC / GRAD / SHDR, or "TEX" (LWOB) + ordinal: string, + channel: string, -- COLR, DIFF, LUMI, SPEC, GLOS, REFL, TRAN, RIND, TRNL, BUMP + enabled: boolean, + opacity: number, + projection: number?, -- 0 planar, 1 cylindrical, 2 spherical, 3 cubic, 4 front, 5 UV + axis: number?, + clip: number?, + file: string?, -- LWOB: the TIMG path + uvmap: string?, + wrap: { number }?, + negative: boolean?, +} +export type Surface = { + name: string, + values: { [string]: number }, -- COLR is separate; DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SMAN, RIND + color: { number }, + side: number, + vcol: { name: string, kind: string, intensity: number }?, + blocks: { Block }, + source: string?, +} +export type Model = { + version: string, -- "LWO2" | "LWOB" | "LXOB" + tags: { string }, + layers: { Layer }, + surfaces: { Surface }, + clips: { [number]: string }, -- clip index -> path + skipped: { [string]: number }, + corners: number, +} + +local MAP_KINDS: { [string]: string } = { + TXUV = "uv", + RGB = "color", + RGBA = "color", + WGHT = "weight", + MNVW = "weight", + NORM = "normal", + MORF = "morph", + SPOT = "spot", +} + +-- ------------------------------------------------------------------------------------------------ primitives +-- S0: a NUL-terminated string padded to an even length +local function s0(r: Bytes.Reader): string + local start = r.pos + local s = r:cstring() + if (r.pos - start) % 2 == 1 and r.pos < r.limit then + r.pos += 1 + end + return s +end + +-- VX: a variable-length index (2 bytes, or 4 bytes after an 0xFF byte) +local function vx(r: Bytes.Reader): number + if r:peekU8() == 0xFF then + return r:u32be() - 0xFF000000 + end + return r:u16be() +end + +local function id4(r: Bytes.Reader): string + local s = r:string(4) + return (string.gsub(s, " +$", "")) +end + +-- sub-chunks (LWO2: 4-byte id, 2-byte size, padded to even) of [p, e): calls f(id, reader over the body) +local function subchunks(buf: buffer, p: number, e: number, f: (string, Bytes.Reader) -> ()) + while p + 6 <= e do + local id = buffer.readstring(buf, p, 4) + local n = buffer.readu8(buf, p + 4) * 256 + buffer.readu8(buf, p + 5) + local body = p + 6 + local avail = math.min(n, e - body) + f((string.gsub(id, " +$", "")), Bytes.reader(buf, body, avail)) + p = body + n + (n % 2) + end +end + +-- ------------------------------------------------------------------------------------------------ geometry +local function newLayer(index: number): Layer + return { index = index, name = nil, parent = nil, pivot = { 0, 0, 0 }, pts = {}, polys = {}, maps = {} } +end + +local function readPoints(r: Bytes.Reader, layer: Layer, limit: number): string? + local n = r:remaining() // 12 + if #layer.pts // 3 + n > limit then + return "limit: more than " .. limit .. " points" + end + local pts = layer.pts + local k = #pts + for _ = 1, n * 3 do + k += 1 + pts[k] = r:f32be() + end + return nil +end + +-- POLS (LWO2): returns nil or an error +local function readPolys(r: Bytes.Reader, layer: Layer, kind: string, ptBase: number, budget: { number }): string? + local polys = layer.polys + local npts = #layer.pts // 3 + while r:remaining() >= 2 do + local n = bit32.band(r:u16be(), 0x3FF) + local corners = table.create(n) + for i = 1, n do + local p = vx(r) + ptBase + if p >= npts and not r.err then + return "polygon point index " .. p .. " out of range (" .. npts .. " points)" + end + corners[i] = p + end + if r.err then + return "truncated polygon list" + end + budget[1] -= n + if budget[1] < 0 then + return "limit: too many polygon corners" + end + table.insert(polys, { kind = kind, surf = nil, corners = corners }) + end + return nil +end + +-- POLS (LWOB): n, n x U2, surface I2 (negative: detail polygons follow, after a U2 count) +local function readPolysB(r: Bytes.Reader, layer: Layer, budget: { number }): string? + local polys = layer.polys + local npts = #layer.pts // 3 + while r:remaining() >= 4 do + local n = r:u16be() + local corners = table.create(n) + for i = 1, n do + local p = r:u16be() + if p >= npts and not r.err then + return "polygon point index " .. p .. " out of range (" .. npts .. " points)" + end + corners[i] = p + end + local surf = r:i16be() + if r.err then + return "truncated polygon list" + end + if surf < 0 then + surf = -surf + r:u16be() -- the detail polygon count: they follow as ordinary records + end + budget[1] -= n + if budget[1] < 0 then + return "limit: too many polygon corners" + end + if n > 0 then + table.insert(polys, { kind = "FACE", surf = surf - 1, corners = corners }) + end + end + return nil +end + +local function findMap(layer: Layer, kind: string, name: string, dims: number): Map + for _, m in layer.maps do + if m.kind == kind and m.name == name then + return m + end + end + local m: Map = { kind = kind, name = name, dims = dims, vals = {}, has = {}, mad = {} } + table.insert(layer.maps, m) + return m +end + +local function readVmap(r: Bytes.Reader, layer: Layer, perPoly: boolean, ptBase: number, polyBase: number, skipped: { [string]: number }) + local typ = id4(r) + local dims = r:u16be() + local name = s0(r) + local kind = MAP_KINDS[typ] + if r.err or not kind then + skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1 + return + end + local want = if kind == "uv" then 2 elseif kind == "color" then 4 elseif kind == "weight" then 1 else 3 + if dims < 1 or dims > 16 or (kind ~= "color" and dims < want) or (kind == "color" and dims < 3) then + skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1 + return + end + local m = findMap(layer, kind, name, want) + local npts = #layer.pts // 3 + local npolys = #layer.polys + local vals, has, mad = m.vals, m.has, m.mad + while r:remaining() >= 2 do + local p = vx(r) + ptBase + local f = if perPoly then vx(r) + polyBase else -1 + local v = table.create(want, 1) + for c = 1, dims do + local x = r:f32be() + if c <= want then + v[c] = x + end + end + if r.err then + break + end + if p < npts then + if perPoly then + if f < npolys then + local row = mad[f] + if not row then + row = {} + mad[f] = row + end + row[p] = v + end + else + has[p] = true + for c = 1, want do + vals[p * want + c] = v[c] + end + end + end + end +end + +local function readPtag(r: Bytes.Reader, layer: Layer, polyBase: number) + local typ = id4(r) + if typ ~= "SURF" and typ ~= "MATR" then + return + end + local polys = layer.polys + while r:remaining() >= 4 do + local f = vx(r) + polyBase + local tag = r:u16be() + if r.err then + break + end + local poly = polys[f + 1] + if poly then + poly.surf = tag + end + end +end + +-- ------------------------------------------------------------------------------------------------ surfaces +local function newSurface(name: string): Surface + return { name = name, values = {}, color = { 0.78, 0.78, 0.78 }, side = 1, vcol = nil, blocks = {}, source = nil } +end + +local SURF_VALUES = { DIFF = true, LUMI = true, SPEC = true, REFL = true, TRAN = true, TRNL = true, GLOS = true, BUMP = true, SMAN = true, RIND = true } + +local function readBlock(r: Bytes.Reader, surf: Surface) + -- the header sub-chunk: IMAP / PROC / GRAD / SHDR, ordinal string, header sub-chunks + if r:remaining() < 6 then + return + end + local kind = id4(r) + local hn = r:u16be() + local hend = math.min(r.pos + hn, r.limit) + local blk: Block = { kind = kind, ordinal = "", channel = "COLR", enabled = true, opacity = 1 } + local hr = Bytes.reader(r.buf, r.pos, hend - r.pos) + blk.ordinal = s0(hr) + subchunks(r.buf, hr.pos, hend, function(id: string, sr: Bytes.Reader) + if id == "CHAN" then + blk.channel = id4(sr) + elseif id == "ENAB" then + blk.enabled = sr:u16be() ~= 0 + elseif id == "OPAC" then + sr:u16be() + blk.opacity = sr:f32be() + elseif id == "NEGA" then + blk.negative = sr:u16be() ~= 0 + elseif id == "AXIS" then + blk.axis = sr:u16be() + end + end) + subchunks(r.buf, hend + (hn % 2), r.limit, function(id: string, sr: Bytes.Reader) + if id == "PROJ" then + blk.projection = sr:u16be() + elseif id == "AXIS" then + blk.axis = sr:u16be() + elseif id == "IMAG" then + blk.clip = vx(sr) + elseif id == "VMAP" then + blk.uvmap = s0(sr) + elseif id == "WRAP" then + blk.wrap = { sr:u16be(), sr:u16be() } + end + end) + table.insert(surf.blocks, blk) +end + +local function readSurface(r: Bytes.Reader, surfaces: { Surface }) + local name = s0(r) + local source = s0(r) + local surf = newSurface(name) + if source ~= "" then + for _, s in surfaces do + if s.name == source then + surf.values = table.clone(s.values) + surf.color = table.clone(s.color) + surf.side = s.side + surf.vcol = s.vcol + surf.blocks = table.clone(s.blocks) + break + end + end + surf.source = source + end + subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader) + if id == "COLR" then + local c = { sr:f32be(), sr:f32be(), sr:f32be() } + if not sr.err then + surf.color = c + end + elseif SURF_VALUES[id] then + local v = sr:f32be() + if not sr.err then + surf.values[id] = v + end + elseif id == "SIDE" then + surf.side = sr:u16be() + elseif id == "VCOL" then + local intensity = sr:f32be() + vx(sr) + local kind = id4(sr) + local vname = s0(sr) + if not sr.err then + surf.vcol = { name = vname, kind = kind, intensity = intensity } + end + elseif id == "BLOK" then + readBlock(sr, surf) + end + end) + table.insert(surfaces, surf) +end + +-- LWOB surfaces: U2 percentages (256 = 100%), V* floats, texture sub-chunks +local B_VALUES = { DIFF = "DIFF", LUMI = "LUMI", SPEC = "SPEC", REFL = "REFL", TRAN = "TRAN" } +local B_FLOATS = { VDIF = "DIFF", VLUM = "LUMI", VSPC = "SPEC", VRFL = "REFL", VTRN = "TRAN" } +local B_TEX = { CTEX = "COLR", DTEX = "DIFF", STEX = "SPEC", RTEX = "REFL", TTEX = "TRAN", LTEX = "LUMI", BTEX = "BUMP" } +local B_PROJ: { [string]: number } = { Planar = 0, Cylindrical = 1, Spherical = 2, Cubic = 3, Front = 4 } + +local function readSurfaceB(r: Bytes.Reader, surfaces: { Surface }) + local surf = newSurface(s0(r)) + local tex: Block? = nil + subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader) + if id == "COLR" then + local c = { sr:u8() / 255, sr:u8() / 255, sr:u8() / 255 } + if not sr.err then + surf.color = c + end + elseif B_VALUES[id] then + local v = sr:u16be() + if not sr.err and surf.values[B_VALUES[id] .. "!"] == nil then + surf.values[B_VALUES[id]] = v / 256 + end + elseif B_FLOATS[id] then + local v = sr:f32be() + if not sr.err then + surf.values[B_FLOATS[id]] = v + surf.values[B_FLOATS[id] .. "!"] = 1 -- a float value wins over the U2 one + end + elseif id == "GLOS" then + local v = sr:u16be() + if not sr.err then + -- 16, 64, 256, 1024 = low .. very high: as LWO2's 0..1 glossiness + surf.values.GLOS = math.clamp(math.log(math.max(v, 1), 2) / 10, 0, 1) + end + elseif id == "SMAN" then + surf.values.SMAN = sr:f32be() + elseif id == "FLAG" then + local fl = sr:u16be() + if bit32.band(fl, 0x100) ~= 0 then + surf.side = 3 + end + elseif B_TEX[id] then + local desc = sr:cstring() + local proj: number? = nil + for word, v in B_PROJ do + if string.find(desc, word, 1, true) then + proj = v + end + end + local blk: Block = { kind = if string.find(desc, "Image Map", 1, true) then "TEX" else "PROC", ordinal = tostring(#surf.blocks + 1), channel = B_TEX[id], enabled = true, opacity = 1, projection = proj } + table.insert(surf.blocks, blk) + tex = blk + elseif id == "TIMG" and tex then + local path = sr:cstring() + if path ~= "" and path ~= "(none)" then + tex.file = path + end + elseif id == "TFLG" and tex then + local fl = sr:u16be() + tex.axis = if bit32.band(fl, 1) ~= 0 then 0 elseif bit32.band(fl, 2) ~= 0 then 1 else 2 + tex.negative = bit32.band(fl, 16) ~= 0 + elseif id == "TVAL" and tex then + tex.opacity = sr:u16be() / 256 + end + end) + for k in surf.values do + if string.sub(k, -1) == "!" then + surf.values[k] = nil + end + end + table.insert(surfaces, surf) +end + +local function readClip(r: Bytes.Reader, clips: { [number]: string }, refs: { [number]: number }) + local index = r:u32be() + if r.err then + return + end + subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader) + if id == "STIL" then + clips[index] = s0(sr) + elseif id == "ISEQ" then + local digits = sr:u8() + sr:u8() + local offset = sr:i16be() + sr:u16be() + local start = sr:i16be() + sr:u16be() + local prefix = s0(sr) + local suffix = s0(sr) + if not sr.err then + clips[index] = prefix .. string.format("%0" .. math.clamp(digits, 1, 9) .. "d", offset + start) .. suffix + end + elseif id == "XREF" then + refs[index] = sr:u32be() + end + end) +end + +-- ------------------------------------------------------------------------------------------------ the file +-- parse(buf, from, limit, opts) -> Model | nil, message +function Parse.model(buf: buffer, from: number, limit: number, maxCorners: number): (Model?, string?) + local version = buffer.readstring(buf, from + 8, 4) + local declared = bit32.byteswap(buffer.readu32(buf, from + 4)) + local e = math.min(limit, from + 8 + declared) + local model: Model = { version = version, tags = {}, layers = {}, surfaces = {}, clips = {}, skipped = {}, corners = 0 } + local layer = newLayer(0) + layer.implicit = true + table.insert(model.layers, layer) + local ptBase, polyBase = 0, 0 + local budget = { maxCorners } + local refs: { [number]: number } = {} + local lwob = version == "LWOB" + local list = Chunks.walk(buf, from + 12, e, Chunks.IFF) + for _, c in list do + local id = c.id + local r = Bytes.reader(buf, c.offset, c.avail) + local err: string? = nil + if id == "TAGS" or id == "SRFS" then + while r:remaining() > 0 do + table.insert(model.tags, s0(r)) + end + elseif id == "LAYR" and not lwob then + local index = r:u16be() + r:u16be() -- flags (hidden) + local px, py, pz = r:f32be(), r:f32be(), r:f32be() + local name = s0(r) + local parent: number? = if r:remaining() >= 2 then r:u16be() else nil + if r.err then + return nil, "truncated LAYR chunk" + end + if layer.implicit and #layer.pts == 0 and #layer.polys == 0 then + table.remove(model.layers, #model.layers) + end + layer = newLayer(index) + layer.name = name + layer.parent = if parent == 0xFFFF then nil else parent + layer.pivot = { px, py, pz } + table.insert(model.layers, layer) + ptBase, polyBase = 0, 0 + elseif id == "PNTS" then + ptBase = #layer.pts // 3 + err = readPoints(r, layer, maxCorners) + elseif id == "POLS" then + polyBase = #layer.polys + if lwob then + err = readPolysB(r, layer, budget) + else + local kind = id4(r) + if kind == "FACE" or kind == "PTCH" or kind == "SUBD" then + err = readPolys(r, layer, kind, ptBase, budget) + else + -- keep the polygon numbering (PTAG / VMAD refer to it) but skip the geometry + local before = #layer.polys + err = readPolys(r, layer, kind, ptBase, budget) + model.skipped[kind] = (model.skipped[kind] or 0) + #layer.polys - before + end + end + elseif id == "VMAP" or id == "VMAD" then + readVmap(r, layer, id == "VMAD", ptBase, polyBase, model.skipped) + elseif id == "PTAG" then + readPtag(r, layer, polyBase) + elseif id == "SURF" then + if lwob then + readSurfaceB(r, model.surfaces) + else + readSurface(r, model.surfaces) + end + elseif id == "CLIP" then + readClip(r, model.clips, refs) + end + if err then + return nil, err + end + end + for index, target in refs do + if model.clips[index] == nil and model.clips[target] then + model.clips[index] = model.clips[target] + end + end + model.corners = maxCorners - budget[1] + return model, nil +end + +return Parse diff --git a/src/Formats/model/lwo/init.luau b/src/Formats/model/lwo/init.luau new file mode 100644 index 0000000..4b77577 --- /dev/null +++ b/src/Formats/model/lwo/init.luau @@ -0,0 +1,86 @@ +--!strict +-- model/lwo: LightWave objects: LWO2 (LightWave 6+), LWOB (LightWave 5.x) and Modo's LXOB, read only. New code from +-- the LWO2 / LWOB specifications, checked against assimp's LWO importer and test models. +-- Reads layers (one node each: the pivot as translation, parents by layer index), points and polygons (FACE; PTCH / +-- SUBD subdivision cages kept as polygons and flagged extras.lwo.subdivision; CURV, BONE and metaballs skipped and +-- counted in meta.source.skipped; 1- and 2-point polygons as points / lines primitives), vertex maps (VMAP / VMAD: +-- TXUV -> TEXCOORD_n (one set per map name, flipped to glTF's top-left origin), RGB / RGBA -> COLOR_0 for the map the +-- surface's VCOL names and _COLOR_n for the others, Modo NORM -> NORMAL, WGHT / MNVW weight maps -> _WEIGHT_n (LWO has +-- no skeleton to bind them to), MORF / SPOT -> morph targets; the map names are in prim.extras.lwo.maps), surfaces +-- (one material each: COLR -> baseColor, TRAN -> alpha, GLOS / SPEC -> roughness, LUMI -> emissive, SIDE -> +-- doubleSided, every value and texture block in extras.lwo; the first enabled COLR image block -> baseColorTexture, +-- with its UV map as texCoord) and clips (textures keep the file name as uri and the full path in extras.lwo.path: +-- F.model.loadTextures reads them). LightWave's left-handed space becomes glTF's right-handed y up (z negated, winding +-- reversed), as assimp does. Polygons are fan-triangulated unless opts.triangulate = false. +-- Not supported: LWO3, envelopes, procedural / gradient textures (kept as entries in extras.lwo.maps), planar / +-- cylindrical / spherical projections (no UVs are generated), smoothing (no normals are computed). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Parse = require("@formats/model/lwo/Parse") +local Build = require("@formats/model/lwo/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Lwo = { + name = "lwo", + category = "model", + extensions = { "lwo", "lxo" }, + mime = { "image/x-lwo", "model/x-lwo" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks" }, + caps = { decode = true, encode = false, materials = true, polygons = true, vertexColors = true, morphTargets = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives + maxVertices: number?, -- refuse more points / polygon corners (default 2^25) +} + +-- ------------------------------------------------------------------------------------------------ constants +local VERSIONS = { LWO2 = true, LWOB = true, LXOB = true } + +-- ------------------------------------------------------------------------------------------------ sniff +function Lwo.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "FORM" then + return 0 + end + local v = r:peek(4, 8) + return if VERSIONS[v] then 1 elseif v == "LWO3" then 0.8 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Lwo.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + if r.limit - r.base < 12 then + return nil, Err.new(Err.TRUNCATED, "shorter than the FORM header", r.base) + end + if r:peek(4) ~= "FORM" then + return nil, Err.new(Err.CORRUPT, "not an IFF FORM", r.base) + end + local v = r:peek(4, 8) + if v == "LWO3" then + return nil, Err.new(Err.UNSUPPORTED, "LWO3 (LightWave 2018+) objects", r.base + 8) + end + if not VERSIONS[v] then + return nil, Err.new(Err.CORRUPT, "not a LightWave object (FORM type " .. string.format("%q", v) .. ")", r.base + 8) + end + local maxCorners = opts and opts.maxVertices or 2 ^ 25 + local ok, model, msg = pcall(Parse.model, r.buf, r.base, r.limit, maxCorners) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad chunk data: " .. tostring(model)) + end + if not model then + return nil, Err.from(msg) + end + local ok2, scene, msg2 = pcall(Build.scene, model, opts) + if not ok2 then + return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg2) + end + return scene, nil +end + +return Lwo diff --git a/tests/model/lwo.luau b/tests/model/lwo.luau new file mode 100644 index 0000000..36f202b --- /dev/null +++ b/tests/model/lwo.luau @@ -0,0 +1,315 @@ +-- model/lwo tests: assimp's LightWave test models (LWO2, LWOB, Modo LXOB) against assimp (meshes per layer and +-- surface, polygons, corners, materials, world bounds); layer hierarchy and pivots, UV / colour / normal maps, +-- surfaces and image blocks; a hand-built LWO2 (VMAD splits, MORF / SPOT targets, weight maps, lines, points, skipped +-- curves, PTCH flag, derived surface, XREF clip); errors; the fuzz no-throw pass. Fixtures: tools/fixtures/lwo.py. +local T = require("@tests/T") +local Lwo = require("@formats/model/lwo") +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/lwo_cases") + +local t = T.suite("lwo") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Lwo.decode(Bytes.reader(b), opts) +end + +t:eq(Lwo.name, "lwo", "name") +t:eq(Lwo.category, "model", "category") +t:check(Lwo.caps.decode and not Lwo.caps.encode, "caps") + +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 + +-- assimp's counts: one mesh per (layer, surface), polygons, corners +local function counts(scene: any): (number, number, number) + local meshes, faces, corners = 0, 0, 0 + for _, m in scene.meshes do + local mats = {} + for _, p in m.primitives do + if not mats[p.material] then + mats[p.material] = true + meshes += 1 + end + local n = if p.indices then p.indices.count else p.attributes.POSITION.count + corners += n + faces += if p.mode == "polygons" then p.faces.count elseif p.mode == "lines" then n // 2 elseif p.mode == "points" then n else n // 3 + end + end + return meshes, faces, corners +end + +local function find(name: string): any + for _, c in Cases do + if c.name == name then + return c + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ assimp +local checked, scenes = 0, {} +for i, c in Cases do + local a = c.assimp + local scene, err = decode(c.data, { triangulate = false }) + if a.failed then + t:note("%s: assimp rejects it; we: %s", c.name, if scene then "decoded" else tostring(err)) + else + t:check(scene, c.name .. ": decode: " .. tostring(err)) + if scene then + scenes[i] = scene + local meshes, faces, corners = counts(scene) + -- LXOB / LWOB files: assimp's material and surface handling differs (MATR tags, flattened detail polygons) + t:eq(meshes, a.meshes, c.name .. ": meshes (assimp)") + t:eq(faces, a.faces, c.name .. ": polygons (assimp)") + t:eq(corners, a.vertices, c.name .. ": corners (assimp)") + t:eq(#scene.materials, a.materials, c.name .. ": materials (assimp)") + if a.min then + local lo, hi = MeshOps.bounds(MeshOps.merge(scene)) + local ok = lo ~= nil + for k = 1, 3 do + ok = ok and near(lo[k], a.min[k], 1e-4) and near(hi[k], a.max[k], 1e-4) + end + t:check(ok, 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 + -- triangulated: the same corners as triangles + local tri = decode(c.data) + t:check(tri and tri.meshes[1] and tri.meshes[1].primitives[1].mode ~= "polygons", c.name .. ": triangulated by default") + checked += 1 + end + end +end +t:note("%d files checked against assimp", checked) + +-- ------------------------------------------------------------------------------------------------ details +do + local c = find("models/LWO2/hierarchy.lwo") + local s = decode(c.data) + local byName = {} + for i, n in s.nodes do + byName[n.name] = i + end + local root, child0, grand = byName.RootOfHierarchy, byName.ChildOfRoot0, byName.GrandChildOfRoot0 + t:check(root and child0 and grand and byName.ChildOfRoot1, "hierarchy: layer names") + t:check(table.find(s.roots, root) ~= nil and #s.roots == 1, "hierarchy: one root layer") + t:check(table.find(s.nodes[root].children, child0) ~= nil, "hierarchy: ChildOfRoot0 under RootOfHierarchy") + t:check(table.find(s.nodes[child0].children, grand) ~= nil, "hierarchy: GrandChildOfRoot0 under ChildOfRoot0") + local p = s.nodes[child0].extras.lwo.pivot + t:check(p and #p == 3, "hierarchy: pivot kept in extras") + -- weight maps -> _WEIGHT_n (no skeleton in LWO) + local prim = s.meshes[s.nodes[root].mesh].primitives[1] + t:check(prim.attributes._WEIGHT_0 and prim.attributes._WEIGHT_1, "hierarchy: weight maps as _WEIGHT_n") + t:check(prim.extras.lwo.maps._WEIGHT_0 ~= nil, "hierarchy: weight map names") +end +do + local c = find("models/LWO2/boxuv.lwo") + local s = decode(c.data) + local mat = s.materials[1] + t:check(mat.baseColorTexture, "boxuv: COLR image block -> baseColorTexture") + local tex = s.textures[mat.baseColorTexture.texture] + t:eq(tex.uri, "boxuv.png", "boxuv: texture uri") + t:eq(tex.mime, "image/png", "boxuv: texture mime") + local prim = s.meshes[1].primitives[1] + local uv = prim.attributes.TEXCOORD_0 + t:check(uv and uv.count == prim.attributes.POSITION.count, "boxuv: TEXCOORD_0") + local inRange = true + local get = assert(Types.Scene.reader(uv)) + for i = 0, uv.count - 1 do + local u, v = get(i, 0), get(i, 1) + inRange = inRange and u >= -1e-6 and u <= 1 + 1e-6 and v >= -1e-6 and v <= 1 + 1e-6 + end + t:check(inRange, "boxuv: uvs in 0..1") +end +do + local c = find("models/LWO2/box_2vc_1unused.lwo") + local s = decode(c.data) + local any = false + for _, p in s.meshes[1].primitives do + any = any or (p.attributes.COLOR_0 ~= nil or p.attributes._COLOR_0 ~= nil) + end + t:check(any, "box_2vc: colour maps") + local mat = s.materials[1] + t:check(mat.extras.lwo.vcol ~= nil, "box_2vc: surface VCOL map name") +end +do + local c = find("models/LWO2/ModoExport_vertNormals.lwo") + local s = decode(c.data) + local prim = s.meshes[1].primitives[1] + t:check(prim.attributes.NORMAL, "Modo NORM map -> NORMAL") + local get = assert(Types.Scene.reader(prim.attributes.NORMAL)) + local len = math.sqrt(get(0, 0) ^ 2 + get(0, 1) ^ 2 + get(0, 2) ^ 2) + t:check(near(len, 1, 1e-3), "Modo normals are unit length") +end +do + local c = find("models/LWO2/Subdivision.lwo") + local s = decode(c.data) + t:check(s.meshes[1].primitives[1].extras.lwo.subdivision == true, "PTCH cage flagged") + local lx = find("models/LXOB_Modo/sphereWithVertMap.lxo") + local sx = decode(lx.data) + t:eq(sx.meta.source.version, "LXOB", "LXOB version") + t:check(sx.meshes[1].primitives[1].attributes.NORMAL, "LXOB normals") + local lb = find("models/LWOB/sphere_with_mat_gloss_10pc.lwo") + local sb = decode(lb.data) + t:eq(sb.meta.source.version, "LWOB", "LWOB version") + t:check(sb.materials[1].extras.lwo.glos ~= nil, "LWOB glossiness") +end + +-- ------------------------------------------------------------------------------------------------ hand-built LWO2 +local function be16(n: number): string + return string.char(bit32.band(bit32.rshift(n, 8), 255), bit32.band(n, 255)) +end +local function be32(n: number): string + return be16(bit32.rshift(n, 16)) .. be16(bit32.band(n, 0xFFFF)) +end +local function f4(x: number): string + local b = buffer.create(4) + buffer.writef32(b, 0, x) + return be32(buffer.readu32(b, 0)) +end +local function s0(s: string): string + s ..= "\0" + return if #s % 2 == 1 then s .. "\0" else s +end +local function chunk(id: string, body: string): string + return id .. be32(#body) .. body .. (if #body % 2 == 1 then "\0" else "") +end +local function sub(id: string, body: string): string + return id .. be16(#body) .. body .. (if #body % 2 == 1 then "\0" else "") +end +local function form(body: string): string + return "FORM" .. be32(#body + 4) .. "LWO2" .. body +end + +local function quadFile(): string + local pts = "" + for _, p in { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 }, { 2, 0, 0 }, { 3, 0, 0 } } do + pts ..= f4(p[1]) .. f4(p[2]) .. f4(p[3]) + end + local pols = "FACE" .. be16(4) .. be16(0) .. be16(1) .. be16(2) .. be16(3) -- 0: quad + .. be16(2) .. be16(4) .. be16(5) -- 1: a line + .. be16(1) .. be16(5) -- 2: a point + local curv = "CURV" .. be16(2) .. be16(0) .. be16(4) -- 3: skipped + local ptch = "PTCH" .. be16(3) .. be16(0) .. be16(1) .. be16(2) -- 4: a patch + local uv = "TXUV" .. be16(2) .. s0("UV") + for i, v in { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } } do + uv ..= be16(i - 1) .. f4(v[1]) .. f4(v[2]) + end + local vmad = "TXUV" .. be16(2) .. s0("UV") .. be16(0) .. be16(0) .. f4(0.5) .. f4(0.25) -- point 0 in polygon 0 + local morf = "MORF" .. be16(3) .. s0("up") .. be16(2) .. f4(0) .. f4(0) .. f4(1) + local spot = "SPOT" .. be16(3) .. s0("moved") .. be16(1) .. f4(1) .. f4(2) .. f4(0) + local wght = "WGHT" .. be16(1) .. s0("bone") .. be16(3) .. f4(0.75) + local tags = s0("Base") .. s0("Child") + local base = s0("Base") .. s0("") .. sub("COLR", f4(1) .. f4(0) .. f4(0) .. be16(0)) .. sub("TRAN", f4(0.25) .. be16(0)) .. sub("SIDE", be16(3)) + local blok = sub("IMAP", s0("\128") .. sub("CHAN", "COLR") .. sub("ENAB", be16(1))) .. sub("PROJ", be16(5)) .. sub("IMAG", be16(2)) .. sub("VMAP", s0("UV")) + local child = s0("Child") .. s0("Base") .. sub("LUMI", f4(0.5) .. be16(0)) .. sub("BLOK", blok) + local ptag = "SURF" .. be16(0) .. be16(0) .. be16(1) .. be16(1) .. be16(2) .. be16(1) + local ptag2 = "SURF" .. be16(0) .. be16(1) + return form(chunk("TAGS", tags) .. chunk("LAYR", be16(0) .. be16(0) .. f4(0.5) .. f4(0) .. f4(0) .. s0("Main")) .. chunk("PNTS", pts) + .. chunk("VMAP", uv) .. chunk("VMAP", morf) .. chunk("VMAP", spot) .. chunk("VMAP", wght) + .. chunk("POLS", pols) .. chunk("PTAG", ptag) .. chunk("VMAD", vmad) .. chunk("POLS", curv) .. chunk("POLS", ptch) .. chunk("PTAG", ptag2) + .. chunk("CLIP", be32(1) .. sub("STIL", s0("C:\\images\\Wood.PNG"))) .. chunk("CLIP", be32(2) .. sub("XREF", be32(1) .. s0("ref"))) + .. chunk("SURF", base) .. chunk("SURF", child) + .. chunk("LAYR", be16(1) .. be16(0) .. f4(0.5) .. f4(1) .. f4(2) .. s0("Sub") .. be16(0))) +end + +do + local data = quadFile() + local s, err = decode(data, { triangulate = false }) + t:check(s, "hand-built: decode " .. tostring(err)) + t:eq(#s.nodes, 2, "hand-built: two layers") + local main, subl = s.nodes[1], s.nodes[2] + t:eq(main.name, "Main", "hand-built: layer name") + t:check(table.find(main.children, 2) ~= nil and #s.roots == 1, "hand-built: Sub is a child of Main") + t:check(main.translation and main.translation[1] == 0.5, "hand-built: Main pivot translation") + t:check(subl.translation and subl.translation[2] == 1 and subl.translation[3] == -2, "hand-built: Sub pivot relative to Main, z negated") + t:eq(s.meta.source.skipped.CURV, 1, "hand-built: curve skipped and counted") + local mesh = s.meshes[main.mesh] + local modes = {} + for _, p in mesh.primitives do + modes[#modes + 1] = p.mode .. "/" .. p.material .. (if p.extras.lwo.subdivision then "/patch" else "") + end + t:eq(table.concat(modes, " "), "polygons/1 polygons/2/patch lines/2 points/2", "hand-built: primitives by surface and kind") + local quad = mesh.primitives[1] + t:eq(quad.attributes.POSITION.count, 4, "hand-built: quad vertices") + -- winding reversed, positions relative to the pivot, z negated + local idx = {} + for k = 0, 3 do + idx[k + 1] = buffer.readu32(quad.indices.data, k * 4) + end + local P = assert(Types.Scene.reader(quad.attributes.POSITION)) + local UV = assert(Types.Scene.reader(quad.attributes.TEXCOORD_0)) + t:eq(P(idx[1], 0), -0.5, "hand-built: x relative to the pivot") + t:eq(P(idx[2], 0), -0.5, "hand-built: winding reversed (second corner is point 3)") + t:eq(P(idx[2], 1), 1, "hand-built: second corner y") + t:eq(UV(idx[1], 0), 0.5, "hand-built: VMAD u") + t:eq(UV(idx[1], 1), 0.75, "hand-built: VMAD v flipped") + t:eq(UV(idx[3], 1), 0, "hand-built: VMAP v flipped (point 2: 1 -> 0)") + t:check(quad.targets and #quad.targets == 2, "hand-built: MORF + SPOT targets") + local T1 = assert(Types.Scene.reader(quad.targets[1].POSITION)) + local T2 = assert(Types.Scene.reader(quad.targets[2].POSITION)) + t:eq(T1(idx[3], 2), -1, "hand-built: MORF delta (z negated)") + t:eq(T2(idx[4], 1), 2, "hand-built: SPOT -> delta (point 1: y 0 -> 2)") + t:eq(mesh.weights and #mesh.weights, 2, "hand-built: mesh weights") + t:eq(mesh.extras.targetNames[2], "moved", "hand-built: target names") + local W = assert(Types.Scene.reader(quad.attributes._WEIGHT_0)) + t:eq(W(idx[2], 0), 0.75, "hand-built: weight map value (point 3)") + local base, child = s.materials[1], s.materials[2] + t:eq(base.baseColor[1], 1, "hand-built: COLR") + t:check(near(base.baseColor[4], 0.75, 1e-6) and base.alphaMode == "blend", "hand-built: TRAN -> alpha") + t:check(base.doubleSided, "hand-built: SIDE 3") + t:check(child.doubleSided and child.baseColor[1] == 1, "hand-built: derived surface copies its source") + t:check(near(child.emissive[1], 0.5, 1e-6), "hand-built: LUMI -> emissive") + t:check(child.baseColorTexture and child.baseColorTexture.texCoord == 0, "hand-built: image block via XREF clip") + t:eq(s.textures[1].uri, "Wood.PNG", "hand-built: texture uri is the file name") + t:eq(s.textures[1].extras.lwo.path, "C:\\images\\Wood.PNG", "hand-built: full path in extras") + local tri = decode(data) + t:eq(tri.meshes[1].primitives[1].indices.count, 6, "hand-built: quad fan-triangulated") + -- triangulated quads keep the right facing: +z after the conversion (LightWave clockwise from -z) + local tp = tri.meshes[1].primitives[1] + local TP = assert(Types.Scene.reader(tp.attributes.POSITION)) + local a, b, c = buffer.readu32(tp.indices.data, 0), buffer.readu32(tp.indices.data, 4), buffer.readu32(tp.indices.data, 8) + local ux, uy = TP(b, 0) - TP(a, 0), TP(b, 1) - TP(a, 1) + local vx, vy = TP(c, 0) - TP(a, 0), TP(c, 1) - TP(a, 1) + t:check(ux * vy - uy * vx < 0, "hand-built: facing kept (LightWave +z normal -> glTF -z)") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local _, e1 = decode("FORM\0\0\0\4LWO3") + t:check(e1 and e1.code == Err.UNSUPPORTED, "LWO3: " .. tostring(e1)) + local _, e2 = decode("FORM\0\0\0\4ILBM") + t:check(e2 and e2.code == Err.CORRUPT, "not LWO: " .. tostring(e2)) + local _, e3 = decode("FORM") + t:check(e3 and e3.code == Err.TRUNCATED, "short: " .. tostring(e3)) + local _, e4 = decode(quadFile(), { maxVertices = 3 }) + t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4)) + local bad = form(chunk("PNTS", f4(0) .. f4(0) .. f4(0)) .. chunk("POLS", "FACE" .. be16(3) .. be16(0) .. be16(1) .. be16(2))) + local _, e5 = decode(bad) + t:check(e5 and e5.code == Err.CORRUPT, "point index out of range: " .. tostring(e5)) + t:eq(Lwo.sniff(Bytes.reader(buffer.fromstring(quadFile()))), 1, "sniff") + t:eq(Lwo.sniff(Bytes.reader(buffer.fromstring("FORM\0\0\0\4AIFF"))), 0, "sniff AIFF") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = { quadFile() } + for _, c in Cases do + if #c.data < 30000 and #samples < 16 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local s = Lwo.decode(Bytes.reader(b), { triangulate = false }) + if s then + MeshOps.merge(s) + end + return s + end, samples, { mutations = 16, keepHeader = 12 }) +end + +t:done() diff --git a/tools/fixtures/lwo.py b/tools/fixtures/lwo.py new file mode 100644 index 0000000..420bd15 --- /dev/null +++ b/tools/fixtures/lwo.py @@ -0,0 +1,41 @@ +# LightWave object fixtures (tools/fixtures.py): assimp's LWO test models (LWO2, LWOB, Modo LXOB; models and +# models-nonbsd, read from the nixpkgs assimp source, never committed) with assimp's view of them (`assimp info -r`: +# meshes, polygons, corners, materials, nodes; world bounds from assimp's PreTransformVertices export). +# tests/gen/lwo_cases.luau { name, data, assimp = { meshes, faces, vertices, materials, nodes, min, max } } +import importlib.util, os + + +def module(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +INPUTS = ["src/Formats/model/lwo", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"] + + +def generate(ctx): + M = module(ctx, "_model_ref") + fbx = module(ctx, "fbx") # assimp_src, ptv_bounds + tmp = M.tempdir() + src = fbx.assimp_src(ctx) + cases = [] + for sub in ("models/LWO", "models-nonbsd/LWO"): + d0 = os.path.join(src, "test", sub) + for root, _, files in sorted(os.walk(d0)): + for f in sorted(files): + if f.lower().endswith((".lwo", ".lxo")): + p = os.path.join(root, f) + cases.append({"name": sub.split("/")[0] + "/" + os.path.relpath(p, d0), "path": p}) + infos = M.assimp_info(ctx, [c["path"] for c in cases], raw=True) + for c, a in zip(cases, infos): + a.pop("min", None) + a.pop("max", None) + a.pop("perMesh", None) + if not a.get("failed"): + a.update(fbx.ptv_bounds(ctx, c["path"], tmp)) + c["assimp"] = a + c["data"] = open(c["path"], "rb").read() + del c["path"] + ctx.emit("lwo_cases", cases) From 27518c55c53ea1486bf810c9fbfda3eb4b7971d6 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:05:28 -0500 Subject: [PATCH 4/8] ws-3d3-b: model/lwo: typed tables (no new type diagnostic) --- src/Formats/model/lwo/Build.luau | 16 +++++++++------- src/Formats/model/lwo/Parse.luau | 6 +++--- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/src/Formats/model/lwo/Build.luau b/src/Formats/model/lwo/Build.luau index 0d62bbd..6a5ccb1 100644 --- a/src/Formats/model/lwo/Build.luau +++ b/src/Formats/model/lwo/Build.luau @@ -108,7 +108,7 @@ local function groupLayer(layer: Parse.Layer, surfaceOf: (number?) -> number): { table.insert(g.polys, i - 1) end end - local rank = { poly = 1, patch = 2, line = 3, point = 4 } + local rank: { [string]: number } = { poly = 1, patch = 2, line = 3, point = 4 } table.sort(groups, function(a: Group, b: Group): boolean if a.material ~= b.material then return a.material < b.material @@ -121,7 +121,7 @@ end -- the corners of a face in output order (winding reversed for the handedness change, first corner kept) local function ordered(corners: { number }): { number } local n = #corners - local out = table.create(n) + local out = table.create(n) :: { number } out[1] = corners[1] for k = 2, n do out[k] = corners[n - k + 2] @@ -175,7 +175,7 @@ local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: for _, f in g.polys do local corners = ordered(layer.polys[f + 1].corners) local n = #corners - local vs = table.create(n) + local vs = table.create(n) :: { number } for k = 1, n do vs[k] = vertex(f, corners[k]) end @@ -249,8 +249,8 @@ local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: end local prim: Types.Primitive = { attributes = attributes, mode = "triangles" } if #morphs > 0 then - local targets = {} - local targetNames = {} + local targets: { { [string]: Types.Accessor } } = {} + local targetNames: { string } = {} for _, m in morphs do local d = buffer.create(nv * 12) for v = 1, nv do @@ -267,7 +267,8 @@ local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: writef32(d, (v - 1) * 12 + 8, -dz) end end - table.insert(targets, { POSITION = Scene.accessor(d, "f32", 3, nv) }) + local tgt: { [string]: Types.Accessor } = { POSITION = Scene.accessor(d, "f32", 3, nv) } + table.insert(targets, tgt) table.insert(targetNames, m.name) end prim.targets = targets @@ -403,7 +404,8 @@ function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.S local prims = {} for _, g in groups do local mat = scene.materials[g.material] - local vcol = mat and mat.extras and mat.extras.lwo and mat.extras.lwo.vcol + local ex: any = mat and mat.extras + local vcol = ex and ex.lwo and ex.lwo.vcol local pa = table.clone(attrs) nc = 0 for _, map in layer.maps do diff --git a/src/Formats/model/lwo/Parse.luau b/src/Formats/model/lwo/Parse.luau index 21d985c..80d8520 100644 --- a/src/Formats/model/lwo/Parse.luau +++ b/src/Formats/model/lwo/Parse.luau @@ -139,7 +139,7 @@ local function readPolys(r: Bytes.Reader, layer: Layer, kind: string, ptBase: nu local npts = #layer.pts // 3 while r:remaining() >= 2 do local n = bit32.band(r:u16be(), 0x3FF) - local corners = table.create(n) + local corners = table.create(n) :: { number } for i = 1, n do local p = vx(r) + ptBase if p >= npts and not r.err then @@ -165,7 +165,7 @@ local function readPolysB(r: Bytes.Reader, layer: Layer, budget: { number }): st local npts = #layer.pts // 3 while r:remaining() >= 4 do local n = r:u16be() - local corners = table.create(n) + local corners = table.create(n) :: { number } for i = 1, n do local p = r:u16be() if p >= npts and not r.err then @@ -224,7 +224,7 @@ local function readVmap(r: Bytes.Reader, layer: Layer, perPoly: boolean, ptBase: while r:remaining() >= 2 do local p = vx(r) + ptBase local f = if perPoly then vx(r) + polyBase else -1 - local v = table.create(want, 1) + local v = table.create(want, 1) :: { number } for c = 1, dims do local x = r:f32be() if c <= want then From 4f05c89f01afe51eb0a68a3b279b5d9aa0992111 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:17:28 -0500 Subject: [PATCH 5/8] ws-3d3-b: model/x (DirectX .x read: text, binary, MSZIP tzip / bzip, 32 / 64-bit floats; frames, meshes with normals / uvs / colours, materials and textures, skins, animation sets); assimp's test models plus bin 0064 / tzip variants match assimp's counts, bones, animations and world bounds --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/model/x/Build.luau | 560 +++++++++++++++++++++++++++++++++ src/Formats/model/x/Parse.luau | 306 ++++++++++++++++++ src/Formats/model/x/init.luau | 152 +++++++++ tests/model/x.luau | 312 ++++++++++++++++++ tools/fixtures/x.py | 126 ++++++++ 7 files changed, 1469 insertions(+) create mode 100644 src/Formats/model/x/Build.luau create mode 100644 src/Formats/model/x/Parse.luau create mode 100644 src/Formats/model/x/init.luau create mode 100644 tests/model/x.luau create mode 100644 tools/fixtures/x.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 8d51802..998e47b 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -45,6 +45,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | +| model | x | .x | yes | - | text: true, binary: true, compressed: true, materials: true, skins: true, animation: true, polygons: true, vertexColors: true | `tests/model/x.luau` | | cad | step | .step .stp .p21 | yes | yes | complexEntities: true, sections: true, brep: "plugin", tessellate: "plugin" | `tests/cad/step.luau` | | font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` | | font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 4f92213..d44f2b4 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -494,6 +494,18 @@ local list: { Entry } = { return require("@formats/model/vox") end, }, + { + name = "x", + category = "model", + path = "model/x", + extensions = { "x" }, + mime = { "model/x-directx", "text/x-directx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, text = true, binary = true, compressed = true, materials = true, skins = true, animation = true, polygons = true, vertexColors = true }, + load = function() + return require("@formats/model/x") + end, + }, { name = "step", category = "cad", diff --git a/src/Formats/model/x/Build.luau b/src/Formats/model/x/Build.luau new file mode 100644 index 0000000..2acb8f3 --- /dev/null +++ b/src/Formats/model/x/Build.luau @@ -0,0 +1,560 @@ +--!strict +-- model/x/Build: the .x object tree (model/x/Parse) -> Types.Scene, from the DirectX templates' layouts. Direct3D is +-- left-handed (y up, row vectors): z is negated (positions, normals, matrices as S * M * S, keys) and the winding +-- reversed, so the scene is glTF's right-handed y-up with counter-clockwise front faces (assimp does the same). +-- A FrameTransformMatrix (row-vector order) is already column-major for column vectors. Texture coordinates keep +-- Direct3D's top-left origin (glTF's). Plain code (the caller wraps it in pcall). +local Types = require("@formats/Types") +local Mat4 = require("@formats/codecs/model/Mat4") +local Rig = require("@formats/codecs/model/Rig") +local Parse = require("@formats/model/x/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Node = Parse.Node + +-- a cursor over an object's flattened values +type Vals = { v: { any }, i: number } +local function num(c: Vals): number + local x = c.v[c.i] + c.i += 1 + if type(x) ~= "number" then + error("expected a number in the data", 0) + end + return x +end +local function str(c: Vals): string + local x = c.v[c.i] + c.i += 1 + if type(x) ~= "string" then + error("expected a string in the data", 0) + end + return x +end +local function count(c: Vals, limit: number): number + local n = num(c) + if n < 0 or n ~= math.floor(n) or n > limit then + error("bad count " .. n, 0) + end + return n +end + +-- z mirror of a column-major matrix: S * M * S, S = diag(1, 1, -1) +local function mirror(m: { number }): { number } + local o = table.clone(m) + for _, k in { 3, 7, 9, 10, 12, 15 } do + o[k] = -o[k] + end + return o +end + +local function matrix(c: Vals): { number } + local m = table.create(16) :: { number } + for k = 1, 16 do + m[k] = num(c) + end + return mirror(m) +end + +-- ------------------------------------------------------------------------------------------------ materials +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" } + +local function material(scene: Types.Scene, node: Node, texCache: { [string]: number }): Types.Material + local c: Vals = { v = node.vals, i = 1 } + local mat = Scene.material(node.name) + local r, g, b, a = num(c), num(c), num(c), num(c) + local power = num(c) + local sr, sg, sb = num(c), num(c), num(c) + local er, eg, eb = num(c), num(c), num(c) + mat.baseColor = { r, g, b, a } + if a < 1 then + mat.alphaMode = "blend" + end + mat.metallic = 0 + mat.roughness = math.clamp(math.sqrt(2 / (math.max(power, 0) + 2)), 0, 1) + mat.emissive = { er, eg, eb } + local textures = {} + for _, k in node.kids do + local lt = string.lower(k.type) + if lt == "texturefilename" or lt == "normalmapfilename" then + local path = k.vals[1] + if type(path) == "string" and path ~= "" then + path = string.gsub(path, "\\\\", "\\") + local uri = string.gsub(path, "\\", "/") + local ti = texCache[uri] + if not ti then + local base = string.match(uri, "([^/]+)$") or uri + local ext = string.lower(string.match(base, "%.(%w+)$") or "") + table.insert(scene.textures, { name = base, uri = uri, mime = MIME[ext] }) + ti = #scene.textures + texCache[uri] = ti + end + table.insert(textures, uri) + if lt == "normalmapfilename" then + mat.normalTexture = mat.normalTexture or { texture = ti } + else + mat.baseColorTexture = mat.baseColorTexture or { texture = ti } + end + end + end + end + mat.extras = { x = { diffuse = { r, g, b, a }, power = power, specular = { sr, sg, sb }, emissive = { er, eg, eb }, textures = textures } } + return mat +end + +-- ------------------------------------------------------------------------------------------------ meshes +type Bones = { { name: string, matrix: { number } } } +type Ctx = { + scene: Types.Scene, + globalMats: { [string]: number }, + texCache: { [string]: number }, + nodeByName: { [string]: number }, + pendingSkins: { { node: number, bones: Bones } }, + maxVertices: number, + skippedFaces: number, +} + +local function accessorF32(values: { number }, comps: number): Types.Accessor + local n = #values + local b = buffer.create(n * 4) + for i = 1, n do + writef32(b, (i - 1) * 4, values[i]) + end + return Scene.accessor(b, "f32", comps, n // comps) +end + +-- mesh(ctx, meshNode) -> mesh index, the skin's bones (nil: not skinned) | nil (no faces) +local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) + local scene = ctx.scene + local c: Vals = { v = m.vals, i = 1 } + local nv = count(c, ctx.maxVertices) + local pos = table.create(nv * 3) :: { number } + for k = 1, nv * 3 do + pos[k] = num(c) + end + local nf = count(c, ctx.maxVertices) + local faces = table.create(nf) :: { { number } } + local corners = 0 + for f = 1, nf do + local n = count(c, ctx.maxVertices) + corners += n + if corners > ctx.maxVertices then + error("limit: more than " .. ctx.maxVertices .. " face corners", 0) + end + local face = table.create(n) :: { number } + for k = 1, n do + local idx = count(c, 2 ^ 32) + if idx >= nv then + error("face index " .. idx .. " out of range", 0) + end + face[k] = idx + end + faces[f] = face + end + -- the optional data objects + local normals: { number }? = nil + local nfaces: { { number } }? = nil + local uvSets: { { number } } = {} + local colors: { { number } } = {} + local faceMat: { number } = {} + local mats: { number } = {} + local bones: { { name: string, verts: { number }, weights: { number }, matrix: { number } } } = {} + for _, k in m.kids do + local kc: Vals = { v = k.vals, i = 1 } + if k.type == "MeshNormals" then + local nn = count(kc, ctx.maxVertices) + local nr = table.create(nn * 3) :: { number } + for q = 1, nn * 3 do + nr[q] = num(kc) + end + local nnf = count(kc, ctx.maxVertices) + local nfs = table.create(nnf) :: { { number } } + for f = 1, nnf do + local n = count(kc, ctx.maxVertices) + local face = table.create(n) :: { number } + for q = 1, n do + face[q] = count(kc, 2 ^ 32) + end + nfs[f] = face + end + normals, nfaces = nr, nfs + elseif k.type == "MeshTextureCoords" then + local n = count(kc, ctx.maxVertices) + local uv = table.create(n * 2) :: { number } + for q = 1, n * 2 do + uv[q] = num(kc) + end + if n == nv then + table.insert(uvSets, uv) + end + elseif k.type == "MeshVertexColors" then + local n = count(kc, ctx.maxVertices) + local col = table.create(nv * 4, 1) :: { number } + for _ = 1, n do + local idx = count(kc, 2 ^ 32) + local r, g, b, a = num(kc), num(kc), num(kc), num(kc) + if idx < nv then + col[idx * 4 + 1], col[idx * 4 + 2], col[idx * 4 + 3], col[idx * 4 + 4] = r, g, b, a + end + end + table.insert(colors, col) + elseif k.type == "MeshMaterialList" then + count(kc, 2 ^ 20) -- material count (the objects below are authoritative) + local ni = count(kc, ctx.maxVertices) + for q = 1, ni do + faceMat[q] = count(kc, 2 ^ 20) + end + for _, mk in k.kids do + if mk.type == "@ref" then + table.insert(mats, if mk.name then ctx.globalMats[mk.name] or 0 else 0) + elseif mk.type == "Material" then + table.insert(scene.materials, material(scene, mk, ctx.texCache)) + table.insert(mats, #scene.materials) + end + end + elseif k.type == "SkinWeights" then + local name = str(kc) + local n = count(kc, ctx.maxVertices) + local verts = table.create(n) :: { number } + for q = 1, n do + verts[q] = count(kc, 2 ^ 32) + end + local weights = table.create(n) :: { number } + for q = 1, n do + weights[q] = num(kc) + end + table.insert(bones, { name = name, verts = verts, weights = weights, matrix = matrix(kc) }) + end + end + -- material per face (a single index applies to every face) + local function matOf(f: number): number + local mi = if #faceMat == 1 then faceMat[1] else faceMat[f] + return if mi then mi + 1 else 1 + end + -- unique vertices per (position, normal index) + local key: { [number]: number } = {} + local srcPos: { number } = {} + local srcNrm: { number } = {} + local groups: { [number]: { number } } = {} + local order: { number } = {} + local faceSizes: { [number]: { number } } = {} + local nNormals = if normals then #normals // 3 else 0 + for f, face in faces do + local n = #face + if n < 3 then + ctx.skippedFaces += 1 + else + local nface = nfaces and nfaces[f] + local vs = table.create(n) :: { number } + for k = 1, n do + local src = if k == 1 then 1 else n - k + 2 -- winding reversed, first corner kept + local p = face[src] + local q = if nface and nface[src] and nface[src] < nNormals then nface[src] else -1 + local kk = p * (nNormals + 1) + q + 1 + local v = key[kk] + if not v then + table.insert(srcPos, p) + table.insert(srcNrm, q) + v = #srcPos - 1 + key[kk] = v + end + vs[k] = v + end + local mi = matOf(f) + local g = groups[mi] + if not g then + g = {} + groups[mi] = g + faceSizes[mi] = {} + table.insert(order, mi) + end + if triangulate then + for k = 2, n - 1 do + table.insert(g, vs[1]) + table.insert(g, vs[k]) + table.insert(g, vs[k + 1]) + end + else + table.move(vs, 1, n, #g + 1, g) + table.insert(faceSizes[mi], n) + end + end + end + if #order == 0 then + return nil, nil + end + table.sort(order) + -- shared vertex attributes (one vertex buffer for every primitive of the mesh) + local nout = #srcPos + local P = table.create(nout * 3) :: { number } + for v = 1, nout do + local p = srcPos[v] * 3 + P[v * 3 - 2], P[v * 3 - 1], P[v * 3] = pos[p + 1], pos[p + 2], -pos[p + 3] + end + local attributes: { [string]: Types.Accessor } = { POSITION = accessorF32(P, 3) } + if normals then + local N = table.create(nout * 3, 0) :: { number } + for v = 1, nout do + local q = srcNrm[v] + if q >= 0 then + N[v * 3 - 2], N[v * 3 - 1], N[v * 3] = normals[q * 3 + 1], normals[q * 3 + 2], -normals[q * 3 + 3] + end + end + attributes.NORMAL = accessorF32(N, 3) + end + for s, uv in uvSets do + local U = table.create(nout * 2) :: { number } + for v = 1, nout do + local p = srcPos[v] * 2 + U[v * 2 - 1], U[v * 2] = uv[p + 1], uv[p + 2] + end + attributes["TEXCOORD_" .. (s - 1)] = accessorF32(U, 2) + end + for s, col in colors do + local C = table.create(nout * 4) :: { number } + for v = 1, nout do + local p = srcPos[v] * 4 + C[v * 4 - 3], C[v * 4 - 2], C[v * 4 - 1], C[v * 4] = col[p + 1], col[p + 2], col[p + 3], col[p + 4] + end + attributes["COLOR_" .. (s - 1)] = accessorF32(C, 4) + end + if #bones > 0 then + local lists = table.create(nout) :: { { number } } + local byPos: { [number]: { number } } = {} + for j, bone in bones do + for q, vi in bone.verts do + local l = byPos[vi] + if not l then + l = {} + byPos[vi] = l + end + table.insert(l, j - 1) + table.insert(l, bone.weights[q] or 0) + end + end + for v = 1, nout do + lists[v] = byPos[srcPos[v]] or {} + end + attributes.JOINTS_0, attributes.WEIGHTS_0 = Rig.influences(lists) + end + local skinBones: Bones? = nil + if #bones > 0 then + local list: Bones = {} + for _, bone in bones do + table.insert(list, { name = bone.name, matrix = bone.matrix }) + end + skinBones = list + end + local prims: { Types.Primitive } = {} + for _, mi in order do + local idx = groups[mi] + local ib = buffer.create(#idx * 4) + for k, x in idx do + writeu32(ib, (k - 1) * 4, x) + end + local prim: Types.Primitive = { attributes = attributes, indices = Scene.accessor(ib, "u32", 1, #idx), mode = "triangles" } + local mat = mats[mi] + prim.material = if mat and mat > 0 then mat else nil + if not triangulate then + prim.mode = "polygons" + local fs = faceSizes[mi] + local fb = buffer.create(#fs * 4) + for k, x in fs do + writeu32(fb, (k - 1) * 4, x) + end + prim.faces = Scene.accessor(fb, "u32", 1, #fs) + end + table.insert(prims, prim) + end + table.insert(scene.meshes, { name = m.name, primitives = prims }) + return #scene.meshes, skinBones +end + +-- ------------------------------------------------------------------------------------------------ frames +local function frame(ctx: Ctx, f: Node, parent: number?, triangulate: boolean, depth: number) + if depth > 200 then + error("frames nested too deep", 0) + end + local scene = ctx.scene + local node: Types.Node = { name = f.name, children = {} } + table.insert(scene.nodes, node) + local ni = #scene.nodes + if f.name and ctx.nodeByName[f.name] == nil then + ctx.nodeByName[f.name] = ni + end + if parent then + table.insert(scene.nodes[parent].children, ni) + else + table.insert(scene.roots, ni) + end + local first = true + for _, k in f.kids do + if k.type == "FrameTransformMatrix" then + local m = matrix({ v = k.vals, i = 1 }) + local t, r, s = Mat4.decomposeStrict(m) + if t and r and s then + node.translation, node.rotation, node.scale = t, r, s + else + node.matrix = m + end + elseif k.type == "Mesh" then + -- the first mesh on the frame's node, more as child nodes + local mi, bones = mesh(ctx, k, triangulate) + if mi then + local holder = ni + if first then + node.mesh = mi + first = false + else + table.insert(scene.nodes, { name = k.name, children = {}, mesh = mi }) + holder = #scene.nodes + table.insert(node.children, holder) + end + if bones then + table.insert(ctx.pendingSkins, { node = holder, bones = bones }) + end + end + elseif k.type == "Frame" then + frame(ctx, k, ni, triangulate, depth + 1) + end + end +end + +-- ------------------------------------------------------------------------------------------------ animations +local function channel(input: { number }, output: { number }, comps: number, node: number, path: string): Types.Channel + return { node = node, path = path :: any, input = accessorF32(input, 1), output = accessorF32(output, comps), interpolation = "LINEAR" } +end + +local function animationSet(ctx: Ctx, set: Node, tps: number): Types.Animation? + local channels: { Types.Channel } = {} + for _, a in set.kids do + if a.type == "Animation" then + local target: string? = nil + for _, k in a.kids do + if k.type == "@ref" then + target = k.name + end + end + local node = target and ctx.nodeByName[target] + if node then + for _, k in a.kids do + if k.type == "AnimationKey" then + local c: Vals = { v = k.vals, i = 1 } + local kind = num(c) + local nk = count(c, ctx.maxVertices) + local times = table.create(nk) :: { number } + local T, R, S = {}, {}, {} + for q = 1, nk do + times[q] = num(c) / tps + local nvals = count(c, 16) + if kind == 0 and nvals == 4 then + local w, x, y, z = num(c), num(c), num(c), num(c) + -- the file's quaternion is the conjugate (row vectors); mirroring z negates x and y + table.move({ x, y, -z, w }, 1, 4, #R + 1, R) + elseif (kind == 1 or kind == 2) and nvals == 3 then + local x, y, z = num(c), num(c), num(c) + if kind == 1 then + table.move({ x, y, z }, 1, 3, #S + 1, S) + else + table.move({ x, y, -z }, 1, 3, #T + 1, T) + end + elseif (kind == 3 or kind == 4) and nvals == 16 then + local t, r, s = Mat4.decompose(matrix(c)) + table.move(t, 1, 3, #T + 1, T) + table.move(r, 1, 4, #R + 1, R) + table.move(s, 1, 3, #S + 1, S) + else + error("bad animation key (type " .. kind .. ", " .. nvals .. " values)", 0) + end + end + if #T == nk * 3 and nk > 0 then + table.insert(channels, channel(times, T, 3, node, "translation")) + end + if #R == nk * 4 and nk > 0 then + table.insert(channels, channel(times, R, 4, node, "rotation")) + end + if #S == nk * 3 and nk > 0 then + table.insert(channels, channel(times, S, 3, node, "scale")) + end + end + end + end + end + end + if #channels == 0 then + return nil + end + return { name = set.name, channels = channels } +end + +-- ------------------------------------------------------------------------------------------------ scene +function Build.scene(root: Node, opts: { triangulate: boolean?, maxVertices: number? }?): (Types.Scene?, string?) + local triangulate = not (opts and opts.triangulate == false) + local scene = Scene.new() + scene.meta.up = "y" + local ctx: Ctx = { scene = scene, globalMats = {}, texCache = {}, nodeByName = {}, pendingSkins = {}, maxVertices = opts and opts.maxVertices or 2 ^ 25, skippedFaces = 0 } + local tps = 4800 + for _, k in root.kids do + if k.type == "Material" then + table.insert(scene.materials, material(scene, k, ctx.texCache)) + if k.name then + ctx.globalMats[k.name] = #scene.materials + end + elseif k.type == "AnimTicksPerSecond" then + local v = k.vals[1] + if type(v) == "number" and v > 0 then + tps = v + end + end + end + for _, k in root.kids do + if k.type == "Frame" then + frame(ctx, k, nil, triangulate, 0) + elseif k.type == "Mesh" then + local mi, bones = mesh(ctx, k, triangulate) + table.insert(scene.nodes, { name = k.name, children = {}, mesh = mi }) + table.insert(scene.roots, #scene.nodes) + if bones then + table.insert(ctx.pendingSkins, { node = #scene.nodes, bones = bones }) + end + end + end + -- skins: bone names -> frames + for _, ps in ctx.pendingSkins do + local joints: { number } = {} + local ibm = buffer.create(#ps.bones * 64) + for j, bone in ps.bones do + local ni = ctx.nodeByName[bone.name] + if not ni then + -- a bone without a frame: an extra root node keeps the joint numbering + table.insert(scene.nodes, { name = bone.name, children = {} }) + ni = #scene.nodes + table.insert(scene.roots, ni) + ctx.nodeByName[bone.name] = ni + end + joints[j] = ni + for k = 1, 16 do + writef32(ibm, ((j - 1) * 16 + k - 1) * 4, bone.matrix[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, #ps.bones) + acc.matrix = true + table.insert(scene.skins, { joints = joints, inverseBindMatrices = acc }) + scene.nodes[ps.node].skin = #scene.skins + end + for _, k in root.kids do + if k.type == "AnimationSet" then + local anim = animationSet(ctx, k, tps) + if anim then + table.insert(scene.animations, anim) + end + end + end + scene.meta.source = { format = "x", ticksPerSecond = tps, skippedFaces = ctx.skippedFaces } + return scene, nil +end + +return Build diff --git a/src/Formats/model/x/Parse.luau b/src/Formats/model/x/Parse.luau new file mode 100644 index 0000000..e770dd9 --- /dev/null +++ b/src/Formats/model/x/Parse.luau @@ -0,0 +1,306 @@ +--!strict +-- model/x/Parse: DirectX .x data -> a generic object tree, for the text ("txt ") and binary ("bin ") encodings (the +-- caller inflates "tzip" / "bzip" first). From Microsoft's "DirectX File Format Specification" (text grammar and +-- binary tokens), checked against what assimp's XFileParser accepts (no code taken). +-- Every data object becomes { type, name?, vals, kids }: vals holds its members flattened in order (numbers and +-- strings; separators, array brackets and member structure are not kept: model/x/Build knows each template's layout), +-- kids its nested data objects and references ({ name } -> { type = "@ref", name }). Templates are skipped. +-- Text: ; and , separators, // and # comments, quoted strings, s, Blender's "1.#IND00" / "1.#QNAN0" (read as 0). +-- Binary: NAME, STRING, INTEGER, GUID, INTEGER_LIST, FLOAT_LIST (32- or 64-bit floats) and the punctuation and +-- keyword tokens. Plain code (the caller wraps it in pcall); bad data returns nil, message. +local Parse = {} + +export type Node = { type: string, name: string?, vals: { any }, kids: { Node } } + +local readu16, readu32, readf32, readf64, readstring = buffer.readu16, buffer.readu32, buffer.readf32, buffer.readf64, buffer.readstring + +-- a token source: next() -> kind, value. kinds: "{", "}", "id", "num", "str", "guid", "list" (value: { number }), +-- "punct", "eof"; err holds a message after a bad token +type Lexer = { next: () -> (string, any), err: string? } + +local KEYWORDS: { [number]: string } = { + [0x1F] = "template", + [0x28] = "WORD", + [0x29] = "DWORD", + [0x2A] = "FLOAT", + [0x2B] = "DOUBLE", + [0x2C] = "CHAR", + [0x2D] = "UCHAR", + [0x2E] = "SWORD", + [0x2F] = "SDWORD", + [0x30] = "void", + [0x31] = "string", + [0x32] = "unicode", + [0x33] = "cstring", + [0x34] = "array", +} + +-- ------------------------------------------------------------------------------------------------ text +local function textLexer(s: string): Lexer + local lex: Lexer = { next = nil :: any, err = nil } + local p = 1 + local n = #s + lex.next = function(): (string, any) + while true do + local _, e = string.find(s, "^[%s,;]+", p) + if e then + p = e + 1 + end + if p > n then + return "eof", nil + end + local c = string.byte(s, p) + if c == 47 and string.byte(s, p + 1) == 47 or c == 35 then -- // or # + local nl = string.find(s, "[\r\n]", p) + p = if nl then nl + 1 else n + 1 + else + break + end + end + local c = string.byte(s, p) + if c == 123 then + p += 1 + return "{", nil + elseif c == 125 then + p += 1 + return "}", nil + elseif c == 34 then + local q = string.find(s, '"', p + 1, true) + if not q then + lex.err = "unterminated string" + p = n + 1 + return "eof", nil + end + local v = string.sub(s, p + 1, q - 1) + p = q + 1 + return "str", v + elseif c == 60 then + local q = string.find(s, ">", p + 1, true) or n + local v = string.sub(s, p + 1, q - 1) + p = q + 1 + return "guid", v + end + local _, e = string.find(s, '^[^%s,;{}"]+', p) + local tok = string.sub(s, p, e :: number) + p = (e :: number) + 1 + if (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then + return "num", tonumber(tok) or 0 + end + return "id", tok + end + return lex +end + +-- ------------------------------------------------------------------------------------------------ binary +local function binaryLexer(b: buffer, from: number, limit: number, floatSize: number): Lexer + local lex: Lexer = { next = nil :: any, err = nil } + local p = from + local function fail(msg: string): (string, any) + lex.err = msg + p = limit + return "eof", nil + end + lex.next = function(): (string, any) + if p + 2 > limit then + return "eof", nil + end + local tok = readu16(b, p) + p += 2 + if tok == 0x0A then + return "{", nil + elseif tok == 0x0B then + return "}", nil + elseif tok == 1 or tok == 2 then -- NAME / STRING: u32 count, bytes (STRING: then a ; or , token) + if p + 4 > limit then + return fail("truncated name") + end + local len = readu32(b, p) + p += 4 + if len > limit - p then + return fail("truncated name") + end + local v = readstring(b, p, len) + p += len + if tok == 2 then + p = math.min(p + 2, limit) + return "str", v + end + return "id", v + elseif tok == 3 then + if p + 4 > limit then + return fail("truncated integer") + end + local v = readu32(b, p) + p += 4 + return "num", v + elseif tok == 5 then + if p + 16 > limit then + return fail("truncated guid") + end + p += 16 + return "guid", "" + elseif tok == 6 or tok == 7 then + if p + 4 > limit then + return fail("truncated list") + end + local count = readu32(b, p) + p += 4 + local size = if tok == 6 then 4 else floatSize + if count > (limit - p) // size then + return fail("truncated list") + end + local out = table.create(count) :: { number } + if tok == 6 then + for i = 1, count do + out[i] = readu32(b, p) + p += 4 + end + elseif size == 8 then + for i = 1, count do + out[i] = readf64(b, p) + p += 8 + end + else + for i = 1, count do + out[i] = readf32(b, p) + p += 4 + end + end + return "list", out + elseif tok >= 0x0C and tok <= 0x14 then + return "punct", nil + elseif KEYWORDS[tok] then + return "id", KEYWORDS[tok] + end + return fail(string.format("unknown binary token 0x%x", tok)) + end + return lex +end + +-- ------------------------------------------------------------------------------------------------ tree +local function tree(lex: Lexer, maxValues: number): (Node?, string?) + local queue: { { any } } = {} + local function take(): (string, any) + local q = table.remove(queue, 1) + if q then + return q[1], q[2] + end + return lex.next() + end + local function peek(k: number): string + while #queue < k do + local kind, v = lex.next() + table.insert(queue, { kind, v }) + if kind == "eof" then + break + end + end + local q = queue[k] + return if q then q[1] else "eof" + end + local budget = maxValues + -- skips a template / unknown block whose "{" was just read + local function skipBlock(): string? + local depth = 1 + while depth > 0 do + local kind = take() + if kind == "eof" then + return "unexpected end of file in a template" + elseif kind == "{" then + depth += 1 + elseif kind == "}" then + depth -= 1 + end + end + return nil + end + local body: (Node, number) -> string? + -- an object whose type token was read: [name] { ... } + local function object(parent: Node, typ: string, depth: number): string? + local name: string? = nil + local kind, v = take() + if kind ~= "{" then + name = if v ~= nil then tostring(v) else nil + kind = take() + if kind ~= "{" then + return "expected { after " .. typ + end + end + if typ == "template" then + return skipBlock() + end + local node: Node = { type = typ, name = name, vals = {}, kids = {} } + table.insert(parent.kids, node) + return body(node, depth + 1) + end + body = function(node: Node, depth: number): string? + if depth > 200 then + return "objects nested too deep" + end + local vals = node.vals + while true do + local kind, v = take() + if kind == "}" then + return nil + elseif kind == "eof" then + return if depth == 0 then nil else "unexpected end of file in " .. node.type + elseif kind == "num" or kind == "str" then + budget -= 1 + if budget < 0 then + return "limit: more than " .. maxValues .. " values" + end + vals[#vals + 1] = v + elseif kind == "list" then + budget -= #v + if budget < 0 then + return "limit: more than " .. maxValues .. " values" + end + table.move(v, 1, #v, #vals + 1, vals) + elseif kind == "{" then + -- a reference: { name [guid] } + local ref: Node = { type = "@ref", name = nil, vals = {}, kids = {} } + while true do + local k2, v2 = take() + if k2 == "}" then + break + elseif k2 == "eof" then + return "unexpected end of file in a reference" + elseif (k2 == "id" or k2 == "num") and ref.name == nil then + ref.name = tostring(v2) + end + end + table.insert(node.kids, ref) + elseif kind == "id" then + local k1 = peek(1) + if k1 == "{" or (k1 ~= "eof" and k1 ~= "}" and peek(2) == "{") then + local err = object(node, v, depth) + if err then + return err + end + end + -- a lone identifier (an enum value): ignored + end + -- guid / punct: ignored + if lex.err then + return lex.err + end + end + end + local root: Node = { type = "@root", name = nil, vals = {}, kids = {} } + local err = body(root, 0) + if err then + return nil, err + end + if lex.err then + return nil, lex.err + end + return root, nil +end + +-- parse(b, from, limit, binary, floatSize, maxValues) -> root Node | nil, message +function Parse.tree(b: buffer, from: number, limit: number, binary: boolean, floatSize: number, maxValues: number): (Node?, string?) + local lex = if binary then binaryLexer(b, from, limit, floatSize) else textLexer(readstring(b, from, limit - from)) + return tree(lex, maxValues) +end + +return Parse diff --git a/src/Formats/model/x/init.luau b/src/Formats/model/x/init.luau new file mode 100644 index 0000000..183b5e7 --- /dev/null +++ b/src/Formats/model/x/init.luau @@ -0,0 +1,152 @@ +--!strict +-- model/x: DirectX .x files, read only: text ("txt "), binary ("bin ") and MSZIP-compressed ("tzip" / "bzip", +-- through codecs/compress/Deflate), 32- and 64-bit floats. New code from Microsoft's DirectX file format +-- specification and the standard templates, checked against assimp's X importer and test models. +-- Reads the Frame hierarchy (FrameTransformMatrix -> TRS, or a matrix when it has shear), meshes (one primitive per +-- material of MeshMaterialList; MeshNormals with their own face indices (vertices split per position / normal +-- pair), MeshTextureCoords -> TEXCOORD_n, MeshVertexColors -> COLOR_n), materials (inline or referenced global +-- Material objects: face colour -> baseColor, power -> roughness, emissive; TextureFilename -> baseColorTexture, +-- NormalmapFilename -> normalTexture, as uris: F.model.loadTextures reads them; the Phong values in extras.x), +-- SkinWeights (-> a skin per mesh: joints = the named frames, offset matrices as inverse bind matrices, the four +-- strongest influences as JOINTS_0 / WEIGHTS_0) and AnimationSet / Animation / AnimationKey (rotation, scale, +-- position and matrix keys -> channels, AnimTicksPerSecond (default 4800) -> seconds). Templates are skipped. +-- Direct3D's left-handed space becomes glTF's right-handed y up (z negated, winding reversed), as assimp does. +-- Polygons are fan-triangulated unless opts.triangulate = false. Faces of fewer than 3 corners are skipped (counted in +-- meta.source.skippedFaces). +-- Not supported: DeclData / FVFData vertex streams, progressive meshes, patch meshes, 3- and 2-corner key +-- interpolation options (keys are linear). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Deflate = require("@formats/codecs/compress/Deflate") +local Parse = require("@formats/model/x/Parse") +local Build = require("@formats/model/x/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local X = { + name = "x", + category = "model", + extensions = { "x" }, + mime = { "model/x-directx", "text/x-directx" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/model/Mat4", "codecs/model/Rig" }, + caps = { decode = true, encode = false, text = true, binary = true, compressed = true, materials = true, skins = true, animation = true, polygons = true, vertexColors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives + maxVertices: number?, -- refuse more vertices / face corners per mesh (default 2^25) + maxValues: number?, -- refuse files with more numbers than this (default 2^27) + maxBytes: number?, -- refuse compressed files inflating to more (default 2^30) +} + +-- ------------------------------------------------------------------------------------------------ constants +local ENCODINGS = { ["txt "] = "text", ["bin "] = "binary", tzip = "text", bzip = "binary" } +local WINDOW = 32768 + +-- ------------------------------------------------------------------------------------------------ sniff +function X.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "xof " then + return 0 + end + return if ENCODINGS[r:peek(4, 8)] then 1 else 0.5 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- MSZIP: a u32 total size (with the header), then blocks (u16 uncompressed size, u16 compressed size, "CK", deflate data); each block +-- may refer back into the previous block's output. That history is handed to the inflater as a stored block in +-- front of the compressed one (both start on a byte boundary), and cut off the output again. +local function mszip(b: buffer, p: number, limit: number, maxBytes: number): (buffer?, Err.Err?) + if p + 4 > limit then + return nil, Err.new(Err.TRUNCATED, "no MSZIP header", p) + end + local total = math.max(buffer.readu32(b, p) - 16, 0) -- the size counts the 16-byte header + if total > maxBytes then + return nil, Err.new(Err.LIMIT, "inflates to " .. total .. " bytes", p) + end + p += 4 + local out = buffer.create(total) + local o = 0 + while p + 6 <= limit and o < total do + local usize, csize = buffer.readu16(b, p), buffer.readu16(b, p + 2) + if buffer.readstring(b, p + 4, 2) ~= "CK" or csize < 2 then + return nil, Err.new(Err.CORRUPT, "bad MSZIP block", p) + end + local data, dlen = p + 6, math.min(csize - 2, limit - p - 6) + local hist = math.min(o, WINDOW) + local src = buffer.create(5 + hist + dlen) + buffer.writeu8(src, 0, 0) -- BFINAL 0, stored + buffer.writeu16(src, 1, hist) + buffer.writeu16(src, 3, bit32.bxor(hist, 0xFFFF)) + buffer.copy(src, 5, out, o - hist, hist) + buffer.copy(src, 5 + hist, b, data, dlen) + local inflated, err = Deflate.inflate(src) + if not inflated then + return nil, Err.new(err.code, "MSZIP block: " .. err.message, p) + end + local got = buffer.len(inflated) - hist + if got ~= usize or o + got > total then + return nil, Err.new(Err.CORRUPT, "MSZIP block size mismatch", p) + end + buffer.copy(out, o, inflated, hist, got) + o += got + p = data + csize - 2 + end + if o < total then + return nil, Err.new(Err.TRUNCATED, "MSZIP data ends early", p) + end + return out, nil +end + +function X.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local b, base, limit = r.buf, r.base, r.limit + if limit - base < 16 then + return nil, Err.new(Err.TRUNCATED, "shorter than the header", base) + end + if buffer.readstring(b, base, 4) ~= "xof " then + return nil, Err.new(Err.CORRUPT, "no xof header", base) + end + local enc = buffer.readstring(b, base + 8, 4) + local kind = ENCODINGS[enc] + if not kind then + return nil, Err.new(Err.UNSUPPORTED, "encoding " .. string.format("%q", enc), base + 8) + end + local bits = buffer.readstring(b, base + 12, 4) + local floatSize = if bits == "0064" then 8 elseif bits == "0032" then 4 else 0 + if floatSize == 0 then + return nil, Err.new(Err.CORRUPT, "float size " .. string.format("%q", bits), base + 12) + end + local data: buffer, from: number, to: number = b, base + 16, limit + if enc == "tzip" or enc == "bzip" then + local inflated, err = mszip(b, base + 16, limit, opts and opts.maxBytes or 2 ^ 30) + if not inflated then + return nil, err + end + data, from, to = inflated, 0, buffer.len(inflated) + end + local maxValues: number = opts and opts.maxValues or 2 ^ 27 + local ok, root, msg = pcall(Parse.tree, data, from, to :: number, kind == "binary", floatSize, maxValues) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(root)) + end + if not root then + return nil, Err.from(msg) + end + local ok2, scene, msg2 = pcall(Build.scene, root, opts) + if not ok2 then + return nil, Err.from(tostring(scene)) + end + if not scene then + return nil, Err.from(msg2) + end + local src = scene.meta.source :: { [string]: any } + src.version = buffer.readstring(b, base + 4, 4) + src.encoding = kind + src.compressed = enc == "tzip" or enc == "bzip" + src.floatSize = floatSize * 8 + return scene, nil +end + +return X diff --git a/tests/model/x.luau b/tests/model/x.luau new file mode 100644 index 0000000..119cbdc --- /dev/null +++ b/tests/model/x.luau @@ -0,0 +1,312 @@ +-- model/x tests: assimp's DirectX test models (text, binary 32-bit, MSZIP-compressed binary) and variants made by +-- tools/fixtures/x.py (binary with 64-bit floats, MSZIP-compressed text), against assimp (meshes per material, faces, +-- corners, materials, animations, bones, world bounds); frames, materials and textures, vertex colours, skins +-- (influences, inverse bind matrices against the bind pose), animation keys (the rotation convention against the +-- bind pose); an inline text file; errors; the fuzz no-throw pass. Fixtures: tools/fixtures/x.py. +local T = require("@tests/T") +local X = require("@formats/model/x") +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/x_cases") + +local t = T.suite("x") + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return X.decode(Bytes.reader(b), opts) +end + +t:eq(X.name, "x", "name") +t:eq(X.category, "model", "category") +t:check(X.caps.decode and not X.caps.encode, "caps") + +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 + +-- assimp's counts: meshes (one per material), faces, corners, bones (joints with weight in each mesh) +local function counts(scene: any): (number, number, number, number) + local meshes, faces, corners, bones = 0, 0, 0, 0 + for _, m in scene.meshes do + for _, p in m.primitives do + meshes += 1 + corners += p.indices.count + faces += if p.mode == "polygons" then p.faces.count else p.indices.count // 3 + local J, W = p.attributes.JOINTS_0, p.attributes.WEIGHTS_0 + if J and W then + local used = {} + local gj, gw = assert(Types.Scene.reader(J)), assert(Types.Scene.reader(W)) + for k = 0, p.indices.count - 1 do + local v = buffer.readu32(p.indices.data, k * 4) + for c = 0, 3 do + if gw(v, c) > 0 then + used[gj(v, c)] = true + end + end + end + for _ in used do + bones += 1 + end + end + end + end + return meshes, faces, corners, bones +end + +local function bounds(scene: any): ({ number }?, { number }?) + local merged = MeshOps.merge(scene) + if not merged then + return nil, nil + end + return MeshOps.bounds(merged) +end + +local function boundsMatch(lo: { number }?, hi: { number }?, a: any, eps: number): boolean + if not lo or not hi then + return false + end + for k = 1, 3 do + if not near(lo[k], a.min[k], eps) or not near(hi[k], a.max[k], eps) then + return false + end + end + return true +end + +-- ------------------------------------------------------------------------------------------------ assimp +local scenes, byName = {}, {} +local checked = 0 +for i, c in Cases do + byName[c.name] = c + local a = c.assimp + local scene, err = decode(c.data, { triangulate = false }) + if a.failed then + t:note("%s: assimp rejects it; we: %s", c.name, if scene then "decoded" else tostring(err)) + else + t:check(scene, c.name .. ": decode: " .. tostring(err)) + scenes[c.name] = scene + local meshes, faces, corners, bones = counts(scene) + t:eq(meshes, a.meshes, c.name .. ": meshes (assimp)") + t:eq(faces + scene.meta.source.skippedFaces, a.faces, c.name .. ": faces (assimp)") + if scene.meta.source.skippedFaces == 0 then + t:eq(corners, a.vertices, c.name .. ": corners (assimp)") + end + t:eq(math.max(#scene.materials, 1), a.materials, c.name .. ": materials (assimp, its default when none)") + t:eq(#scene.animations, a.animations or 0, c.name .. ": animations (assimp)") + t:eq(bones, a.bones or 0, c.name .. ": bones (assimp)") + if a.min then + local lo, hi = bounds(scene) + t:check(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 += 1 + end +end +t:note("%d files checked against assimp", checked) + +-- variants decode like their originals +for _, c in Cases do + if c.of then + local a, b = scenes[c.name], scenes[c.of] + if a and b then + local m1, f1, c1 = counts(a) + local m2, f2, c2 = counts(b) + t:check(m1 == m2 and f1 == f2 and c1 == c2, c.name .. ": same counts as " .. c.of) + local la, ha = bounds(a) + local lb, hb = bounds(b) + t:check(la and lb and boundsMatch(la, ha, { min = lb, max = hb }, 1e-5), c.name .. ": same bounds as " .. c.of) + t:eq(#a.animations, #b.animations, c.name .. ": same animations") + end + end +end + +-- ------------------------------------------------------------------------------------------------ details +do + local s = scenes["models/kwxport_test_cubewithvcolors.x"] + local p = s.meshes[1].primitives[1] + t:check(p.attributes.COLOR_0 and p.attributes.COLOR_0.components == 4, "vertex colours -> COLOR_0") + t:eq(s.meta.source.encoding, "text", "text encoding") + local b = scenes["models/test_cube_binary.x"] + t:eq(b.meta.source.encoding, "binary", "binary encoding") + local z = scenes["models/test_cube_compressed.x"] + t:check(z.meta.source.compressed, "bzip") + local v = scenes["variant/test_cube_text.bin64.x"] + t:eq(v.meta.source.floatSize, 64, "64-bit floats") +end +do + -- textures: uri names, TEXCOORD_0 + local s = scenes["models/test.x"] + local any = false + for _, m in s.materials do + if m.baseColorTexture then + local tex = s.textures[m.baseColorTexture.texture] + any = any or (type(tex.uri) == "string" and #tex.uri > 0) + end + end + t:check(any, "test.x: a texture file name") + t:check(s.meshes[1].primitives[1].attributes.TEXCOORD_0, "test.x: TEXCOORD_0") +end +do + -- skins: the inverse bind matrix of each joint times the joint's world bind matrix is about the same for all + -- joints (the mesh node's world matrix): checks the matrix layout and the handedness conversion together + local checkedSkins, consistent = 0, 0 + for name, s in scenes do + for _, node in s.nodes do + if node.skin then + local skin = s.skins[node.skin] + local world = {} + local function worldOf(i: number): { number } + if world[i] then + return world[i] + end + local m = Types.Scene.nodeMatrix(s.nodes[i]) + for pi, pn in s.nodes do + if table.find(pn.children, i) then + m = Types.Scene.mul(worldOf(pi), m) + break + end + end + world[i] = m + return m + end + local get = assert(Types.Scene.reader(skin.inverseBindMatrices)) + local ref: { number }? = nil + local ok, total = 0, 0 + for j, joint in skin.joints do + local inv = {} + for k = 1, 16 do + inv[k] = get(j - 1, k - 1) + end + local m = Types.Scene.mul(worldOf(joint), inv) + total += 1 + if not ref then + ref = m + ok += 1 + else + local same = true + for k = 1, 16 do + same = same and math.abs(m[k] - (ref :: any)[k]) < 1e-2 * math.max(1, math.abs(m[k])) + end + ok += if same then 1 else 0 + end + end + t:note("%s: skin %d: bind pose consistent for %d / %d joints", name, node.skin, ok, total) + checkedSkins += 1 + consistent += if ok >= total * 0.9 then 1 else 0 + end + end + end + -- (anim_test.x's frames are not in the bind pose) + t:check(checkedSkins >= 4 and consistent >= checkedSkins * 0.7, string.format("skins consistent with the frames (%d / %d)", consistent, checkedSkins)) +end +do + -- the rotation key convention: an animation's first rotation key mostly equals the bone's bind rotation + local same, total = 0, 0 + for _, s in scenes do + for _, anim in s.animations do + for _, ch in anim.channels do + if ch.path == "rotation" then + local node = s.nodes[ch.node] + local r = node.rotation + if r then + local get = assert(Types.Scene.reader(ch.output)) + local dot = 0 + for k = 0, 3 do + dot += get(0, k) * r[k + 1] + end + total += 1 + same += if math.abs(dot) > 0.999 then 1 else 0 + end + end + end + end + end + t:check(total > 0 and same >= total * 0.5, string.format("first rotation keys match the bind pose (%d / %d)", same, total)) +end + +-- ------------------------------------------------------------------------------------------------ inline file +local CUBE = [[xof 0303txt 0032 +// a quad and a triangle, two materials, one animated frame +Material Red { 1.0; 0.0; 0.0; 1.0;; 10.0; 0.5; 0.5; 0.5;; 0.0; 0.0; 0.0;; TextureFilename { "tex\\red.png"; } } +AnimTicksPerSecond { 100; } +Frame Root { + FrameTransformMatrix { 1,0,0,0, 0,1,0,0, 0,0,1,0, 1,2,3,1;; } + Mesh Shape { + 5; + 0;0;0;, 1;0;0;, 1;1;0;, 0;1;0;, 2;0;0;; + 2; + 4;0,1,2,3;, + 3;1,4,2;; + MeshMaterialList { 2; 2; 0, 1;; { Red } Material Blue { 0;0;1;0.5;; 1; 0;0;0;; 0;0;0;; } } + MeshNormals { 1; 0;0;-1;; 2; 4;0,0,0,0;, 3;0,0,0;; } + MeshTextureCoords { 5; 0;0;, 1;0;, 1;1;, 0;1;, 0.5;0.5;; } + } +} +AnimationSet Move { + Animation { { Root } AnimationKey { 2; 2; 0; 3; 1;2;3;;, 100; 3; 1;2;5;;; } } +} +]] +do + local s, err = decode(CUBE, { triangulate = false }) + t:check(s, "inline: " .. tostring(err)) + t:eq(#s.nodes, 1, "inline: one frame") + local root = s.nodes[1] + t:check(root.translation and root.translation[1] == 1 and root.translation[3] == -3, "inline: translation, z negated") + t:eq(#s.materials, 2, "inline: global + inline material") + t:eq(s.materials[1].name, "Red", "inline: material name") + t:eq(s.textures[1].uri, "tex/red.png", "inline: texture uri (backslash -> slash)") + t:eq(s.materials[2].alphaMode, "blend", "inline: alpha < 1 -> blend") + local prims = s.meshes[1].primitives + t:eq(#prims, 2, "inline: one primitive per material") + t:eq(prims[1].material, 1, "inline: first face -> Red (referenced)") + t:eq(prims[2].material, 2, "inline: second face -> Blue") + t:eq(prims[1].faces.count, 1, "inline: the quad kept") + local N = assert(Types.Scene.reader(prims[1].attributes.NORMAL)) + t:eq(N(0, 2), 1, "inline: normal z negated") + local anim = s.animations[1] + t:eq(anim.name, "Move", "inline: animation name") + local ch = anim.channels[1] + t:eq(ch.path, "translation", "inline: position key") + local ti, to = assert(Types.Scene.reader(ch.input)), assert(Types.Scene.reader(ch.output)) + t:eq(ti(1, 0), 1, "inline: ticks -> seconds") + t:eq(to(1, 2), -5, "inline: key z negated") + local tri = decode(CUBE) + t:eq(tri.meshes[1].primitives[1].indices.count, 6, "inline: quad fan-triangulated") +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local _, e1 = decode("xof 0303txt 00") + t:check(e1 and e1.code == Err.TRUNCATED, "short: " .. tostring(e1)) + local _, e2 = decode("xof 0303zzz 0032") + t:check(e2 and e2.code == Err.UNSUPPORTED, "encoding: " .. tostring(e2)) + local _, e3 = decode("xof 0303txt 0016 Frame {}") + t:check(e3 and e3.code == Err.CORRUPT, "float size: " .. tostring(e3)) + local _, e4 = decode("xof 0303txt 0032 Frame A { Mesh { 3; 0;0;0;, 1;0;0;, 0;1;0;; 1; 3; 0,1,7;; } }") + t:check(e4 and e4.code == Err.CORRUPT, "face index out of range: " .. tostring(e4)) + local _, e5 = decode("xof 0303txt 0032 Frame A { ") + t:check(e5 and e5.code == Err.CORRUPT, "unterminated: " .. tostring(e5)) + local _, e6 = decode(CUBE, { maxValues = 10 }) + t:check(e6 and e6.code == Err.LIMIT, "maxValues: " .. tostring(e6)) + t:eq(X.sniff(Bytes.reader(buffer.fromstring(CUBE))), 1, "sniff") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local samples = { CUBE } + for _, c in Cases do + if #c.data < 12000 then + table.insert(samples, c.data) + end + end + t:fuzz("decode", function(b: buffer) + local s = X.decode(Bytes.reader(b), { triangulate = false }) + if s then + MeshOps.merge(s) + end + return s + end, samples, { mutations = 16, keepHeader = 16 }) +end + +t:done() diff --git a/tools/fixtures/x.py b/tools/fixtures/x.py new file mode 100644 index 0000000..d10bb7e --- /dev/null +++ b/tools/fixtures/x.py @@ -0,0 +1,126 @@ +# DirectX .x fixtures (tools/fixtures.py): assimp's X test models (text, binary 32-bit, MSZIP-compressed binary; +# models and models-nonbsd, read from the nixpkgs assimp source, never committed), plus variants made here from the +# text ones: binary with 64-bit floats ("bin 0064") and MSZIP-compressed text ("tzip", per-block raw deflate with +# the previous block as dictionary, as D3DX writes). Reference: assimp (`assimp info -r`: meshes, faces, corners, +# materials, nodes, animations, bones; world bounds from its PreTransformVertices export), on the variants too. +# tests/gen/x_cases.luau { name, data, assimp = { ... } } +import importlib.util, os, re, struct, zlib + +INPUTS = ["src/Formats/model/x", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py"] + + +def module(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +TOKEN = re.compile(rb'\s+|//[^\n]*|#[^\n]*|"[^"]*"|<[^>]*>|[{}]|[;,]|[^\s;,{}"]+') + + +def to_binary64(text): + """a text .x file -> binary tokens with 64-bit floats (templates dropped; numbers with . or e are floats)""" + body = text[16:] + out = bytearray(b"xof 0303bin 0064") + toks = [t for t in TOKEN.findall(body) if t.strip() and not t.startswith((b"//", b"#"))] + i, nums = 0, [] + + def flush(): + while nums: + isf = nums[0][0] + run = [] + while nums and nums[0][0] == isf: + run.append(nums.pop(0)[1]) + if isf: + out.extend(struct.pack(" "tzip": MSZIP blocks of 32 KiB, each raw deflate with the previous block as dictionary""" + body = text[16:] + out = bytearray(b"xof 0303tzip0032") + struct.pack(" Date: Sat, 31 Oct 2026 14:39:22 -0500 Subject: [PATCH 6/8] ws-3d3-b: model/iqm (Inter-Quake Model v2 read + write: meshes, every vertex array format, joints -> skin, poses / frames / anims -> channels, bounds; writer merges skins, samples and quantizes animations); new codecs/model/Sampler (channel evaluation STEP / LINEAR + slerp / CUBICSPLINE, animation poses at a time) with tests mrfixit.iqm matches assimp and an independent Python IQM reader (its skinning reproduces the bounds the IQM tool stored; ours matches it to 1e-4); round trips and glTF skinned models written by us are skinned identically by the Python reader. --- docs/FORMATS.md | 2 + src/Formats/Registry.luau | 12 + src/Formats/codecs/model/Sampler.luau | 173 +++++++ src/Formats/model/iqm/Read.luau | 359 +++++++++++++ src/Formats/model/iqm/Write.luau | 706 ++++++++++++++++++++++++++ src/Formats/model/iqm/init.luau | 82 +++ tests/codecs/sampler.luau | 92 ++++ tests/model/iqm.luau | 319 ++++++++++++ tools/fixtures/_iqm_encode.luau | 38 ++ tools/fixtures/_iqm_reference.py | 113 +++++ tools/fixtures/iqm.py | 57 +++ 11 files changed, 1953 insertions(+) create mode 100644 src/Formats/codecs/model/Sampler.luau create mode 100644 src/Formats/model/iqm/Read.luau create mode 100644 src/Formats/model/iqm/Write.luau create mode 100644 src/Formats/model/iqm/init.luau create mode 100644 tests/codecs/sampler.luau create mode 100644 tests/model/iqm.luau create mode 100644 tools/fixtures/_iqm_encode.luau create mode 100644 tools/fixtures/_iqm_reference.py create mode 100644 tools/fixtures/iqm.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 998e47b..a352671 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -38,6 +38,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | 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 | iqm | .iqm | yes | yes | materials: true, skins: true, animation: true, vertexColors: true | `tests/model/iqm.luau` | | model | lwo | .lwo .lxo | yes | - | materials: true, polygons: true, vertexColors: true, morphTargets: true | `tests/model/lwo.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` | @@ -130,6 +131,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks - codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each + - codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index d44f2b4..397a3f7 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -410,6 +410,18 @@ local list: { Entry } = { return require("@formats/model/gltf") end, }, + { + name = "iqm", + category = "model", + path = "model/iqm", + extensions = { "iqm" }, + mime = { "model/x-iqm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true, vertexColors = true }, + load = function() + return require("@formats/model/iqm") + end, + }, { name = "lwo", category = "model", diff --git a/src/Formats/codecs/model/Sampler.luau b/src/Formats/codecs/model/Sampler.luau new file mode 100644 index 0000000..df866b9 --- /dev/null +++ b/src/Formats/codecs/model/Sampler.luau @@ -0,0 +1,173 @@ +--!strict +-- codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for +-- rotations, CUBICSPLINE Hermite splines as glTF 2.0 defines them; times before the first / after the last key hold +-- the end values), and the node poses of an animation at a time, for writers of formats that store sampled frames +-- (IQM, MD5, BVH, ...). New in formats-luau. +-- +-- local sample = Sampler.channel(ch) -- nil for an unreadable channel +-- local v = sample(0.5) -- { x, y, z } / { x, y, z, w } / the morph weights +-- local times = Sampler.times(anim) -- every key time of the animation, sorted, unique +-- local pose = Sampler.pose(scene, anim, 0.5) -- pose[node] = { translation?, rotation?, scale?, weights? } +-- +-- Never throws on bad data: unreadable channels are skipped. +local Types = require("@formats/Types") + +local Sampler = {} + +export type Sample = (t: number) -> { number } +export type Pose = { [number]: { [string]: { number } } } + +local function normalize(q: { number }): { number } + local l = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4]) + if l <= 0 then + return { 0, 0, 0, 1 } + end + return { q[1] / l, q[2] / l, q[3] / l, q[4] / l } +end + +local function slerp(a: { number }, b: { number }, s: number): { number } + local d = a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] + local bx, by, bz, bw = b[1], b[2], b[3], b[4] + if d < 0 then + d, bx, by, bz, bw = -d, -bx, -by, -bz, -bw + end + local wa, wb + if d > 0.9995 then + wa, wb = 1 - s, s + else + local th = math.acos(math.min(d, 1)) + local sn = math.sin(th) + wa, wb = math.sin((1 - s) * th) / sn, math.sin(s * th) / sn + end + return normalize({ a[1] * wa + bx * wb, a[2] * wa + by * wb, a[3] * wa + bz * wb, a[4] * wa + bw * wb }) +end + +-- channel(ch) -> sample(t) | nil +function Sampler.channel(ch: Types.Channel): Sample? + local inp, out = ch.input, ch.output + if type(inp) ~= "table" or type(out) ~= "table" then + return nil + end + local IN, OUT = Types.Scene.reader(inp), Types.Scene.reader(out) + local n = inp.count + if not IN or not OUT or n < 1 then + return nil + end + local cubic = ch.interpolation == "CUBICSPLINE" + local per = if cubic then 3 else 1 + local comps: number + if ch.path == "weights" then + comps = (out.count * out.components) // (n * per) + else + comps = if ch.path == "rotation" then 4 else 3 + end + if comps < 1 or out.count * out.components < n * per * comps then + return nil + end + local times = table.create(n) :: { number } + for k = 1, n do + times[k] = IN(k - 1, 0) + end + local oc = out.components + -- element e (0-based, of comps values) of the flat output + local function get(e: number): { number } + local v = table.create(comps) :: { number } + for c = 0, comps - 1 do + local flat = e * comps + c + v[c + 1] = OUT(flat // oc, flat % oc) + end + return v + end + local function value(k: number): { number } -- key k (1-based) + return get(if cubic then (k - 1) * 3 + 1 else k - 1) + end + local rot = ch.path == "rotation" + local step = ch.interpolation == "STEP" + return function(t: number): { number } + if t <= times[1] or n == 1 then + return if rot then normalize(value(1)) else value(1) + end + if t >= times[n] then + return if rot then normalize(value(n)) else value(n) + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if times[mid] <= t then + lo = mid + else + hi = mid + end + end + local dt = times[hi] - times[lo] + local s = if dt > 0 then (t - times[lo]) / dt else 0 + if step then + return if rot then normalize(value(lo)) else value(lo) + end + if cubic then + local p0, m0 = value(lo), get((lo - 1) * 3 + 2) + local p1, m1 = value(hi), get((hi - 1) * 3) + local s2, s3 = s * s, s * s * s + local h00, h10, h01, h11 = 2 * s3 - 3 * s2 + 1, s3 - 2 * s2 + s, -2 * s3 + 3 * s2, s3 - s2 + local v = table.create(comps) :: { number } + for c = 1, comps do + v[c] = h00 * p0[c] + h10 * dt * m0[c] + h01 * p1[c] + h11 * dt * m1[c] + end + return if rot then normalize(v) else v + end + local a, b = value(lo), value(hi) + if rot then + return slerp(normalize(a), normalize(b), s) + end + local v = table.create(comps) :: { number } + for c = 1, comps do + v[c] = a[c] + (b[c] - a[c]) * s + end + return v + end +end + +-- times(anim) -> every key time, sorted and unique +function Sampler.times(anim: Types.Animation): { number } + local seen: { [number]: boolean } = {} + local out: { number } = {} + for _, ch in anim.channels do + local inp = ch.input + local IN = type(inp) == "table" and Types.Scene.reader(inp) + if IN then + for k = 0, inp.count - 1 do + local t = IN(k, 0) + if not seen[t] and t == t then + seen[t] = true + table.insert(out, t) + end + end + end + end + table.sort(out) + return out +end + +-- pose(scene, anim, t, samplers?) -> pose[node] = { [path] = values } for the animated nodes. samplers: a cache table +-- (reuse it across calls for the same animation) +function Sampler.pose(_scene: Types.Scene, anim: Types.Animation, t: number, samplers: { [any]: any }?): Pose + local cache: { [any]: any } = samplers or {} + local pose: Pose = {} + for _, ch in anim.channels do + if cache[ch] == nil then + cache[ch] = Sampler.channel(ch) or false + end + local s: Sample? = cache[ch] or nil + if s then + local p = pose[ch.node] + if not p then + p = {} + pose[ch.node] = p + end + p[ch.path] = s(t) + end + end + return pose +end + +return Sampler diff --git a/src/Formats/model/iqm/Read.luau b/src/Formats/model/iqm/Read.luau new file mode 100644 index 0000000..599091a --- /dev/null +++ b/src/Formats/model/iqm/Read.luau @@ -0,0 +1,359 @@ +--!strict +-- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. From the IQM format description (iqm.txt and +-- iqm.h of the IQM SDK by Lee Salzman, public domain), checked against assimp's IQM importer (no code taken). +-- Every header range is checked against the data before it is read. Plain code (the caller wraps it in pcall). +local Types = require("@formats/Types") +local Rig = require("@formats/codecs/model/Rig") + +local Read = {} + +local Scene = Types.Scene +local readu8, readi8, readu16, readi16, readu32, readi32, readf32, readf64 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64 +local writef32, writeu32, writeu8, writeu16 = buffer.writef32, buffer.writeu32, buffer.writeu8, buffer.writeu16 + +Read.HEADER = { + "version", "filesize", "flags", "num_text", "ofs_text", "num_meshes", "ofs_meshes", "num_vertexarrays", "num_vertexes", + "ofs_vertexarrays", "num_triangles", "ofs_triangles", "ofs_adjacency", "num_joints", "ofs_joints", "num_poses", + "ofs_poses", "num_anims", "ofs_anims", "num_frames", "num_framechannels", "ofs_frames", "ofs_bounds", "num_comment", + "ofs_comment", "num_extensions", "ofs_extensions", +} +Read.SIZES = { [0] = 1, 1, 2, 2, 4, 4, 2, 4, 8 } -- byte, ubyte, short, ushort, int, uint, half, float, double +Read.ARRAYS = { [0] = "position", "texcoord", "normal", "tangent", "blendindexes", "blendweights", "color" } + +local function half(h: number): number + local s = if bit32.band(h, 0x8000) ~= 0 then -1 else 1 + local e = bit32.band(bit32.rshift(h, 10), 0x1F) + local m = bit32.band(h, 0x3FF) + if e == 0 then + return s * m * 2 ^ -24 + elseif e == 31 then + return if m == 0 then s * math.huge else 0 + end + return s * (1 + m / 1024) * 2 ^ (e - 15) +end + +-- the values of one vertex array element range as numbers (normalized = integer formats scaled to 0..1 / -1..1) +local function values(b: buffer, at: number, format: number, n: number, normalized: boolean): { number } + local out = table.create(n) :: { number } + local size = Read.SIZES[format] + for i = 0, n - 1 do + local p = at + i * size + local v: number + if format == 0 then + v = readi8(b, p) + v = if normalized then math.max(v / 127, -1) else v + elseif format == 1 then + v = readu8(b, p) + v = if normalized then v / 255 else v + elseif format == 2 then + v = readi16(b, p) + v = if normalized then math.max(v / 32767, -1) else v + elseif format == 3 then + v = readu16(b, p) + v = if normalized then v / 65535 else v + elseif format == 4 then + v = readi32(b, p) + elseif format == 5 then + v = readu32(b, p) + elseif format == 6 then + v = half(readu16(b, p)) + elseif format == 7 then + v = readf32(b, p) + else + v = readf64(b, p) + end + out[i + 1] = v + end + return out +end + +local function f32acc(vals: { number }, comps: number): Types.Accessor + local d = buffer.create(#vals * 4) + for i, v in vals do + writef32(d, (i - 1) * 4, v) + end + return Scene.accessor(d, "f32", comps, #vals // comps) +end + +local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds" } + +-- scene(b, base, limit, opts) -> Scene | nil, message +function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: number? }?): (Types.Scene?, string?) + local size = limit - base + local H: { [string]: number } = {} + for i, name in Read.HEADER do + H[name] = readu32(b, base + 12 + i * 4) + end + if H.version ~= 2 then + return nil, "unsupported: IQM version " .. H.version .. " (only 2)" + end + if H.filesize > size then + return nil, "truncated: the header says " .. H.filesize .. " bytes, " .. size .. " present" + end + local maxV = opts and opts.maxVertices or 2 ^ 25 + if H.num_vertexes > maxV or H.num_triangles > maxV then + return nil, "limit: more than " .. maxV .. " vertices / triangles" + end + local function range(ofs: number, count: number, each: number, what: string): string? + if count > 0 and (ofs < 124 or count * each > H.filesize or ofs + count * each > H.filesize) then + return "the " .. what .. " lie outside the file" + end + return nil + end + local err = range(H.ofs_text, H.num_text, 1, "text") + or range(H.ofs_meshes, H.num_meshes, 24, "meshes") + or range(H.ofs_vertexarrays, H.num_vertexarrays, 20, "vertex arrays") + or range(H.ofs_triangles, H.num_triangles, 12, "triangles") + or range(H.ofs_joints, H.num_joints, 48, "joints") + or range(H.ofs_poses, H.num_poses, 88, "poses") + or range(H.ofs_anims, H.num_anims, 20, "anims") + or range(H.ofs_frames, H.num_frames * H.num_framechannels, 2, "frames") + or range(H.ofs_bounds, if H.ofs_bounds > 0 then H.num_frames else 0, 32, "bounds") + or range(H.ofs_comment, H.num_comment, 1, "comment") + if err then + return nil, err + end + local text = if H.num_text > 0 then buffer.readstring(b, base + H.ofs_text, H.num_text) else "" + local function str(ofs: number): string + if ofs >= #text then + return "" + end + local z = string.find(text, "\0", ofs + 1, true) + return string.sub(text, ofs + 1, (z or #text + 1) - 1) + end + local scene = Scene.new() + scene.meta.up = "z" + local source: { [string]: any } = { format = "iqm", version = 2, flags = H.flags } + scene.meta.source = source + if H.num_comment > 0 then + source.comment = string.match(buffer.readstring(b, base + H.ofs_comment, H.num_comment), "^[^%z]*") + end + -- vertex arrays (the whole model's vertices; meshes are ranges of them) + local nv = H.num_vertexes + type Array = { kind: string, name: string, format: number, comps: number, offset: number } + local arrays: { Array } = {} + for i = 0, H.num_vertexarrays - 1 do + local p = base + H.ofs_vertexarrays + i * 20 + local typ, format, comps, offset = readu32(b, p), readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16) + local esize = Read.SIZES[format] + if not esize or comps < 1 or comps > 16 then + return nil, "vertex array " .. i .. " has format " .. format .. " / " .. comps .. " components" + end + local e = range(offset, nv, comps * esize, "vertex array " .. i) + if e then + return nil, e + end + local kind = Read.ARRAYS[typ] + local name = if kind then kind else "_" .. (if typ >= 0x10 then str(typ - 0x10) else tostring(typ)) + table.insert(arrays, { kind = kind or "custom", name = name, format = format, comps = comps, offset = base + offset }) + end + -- joints -> nodes + a skin + local jointNodes: { number } = {} + local skin: number? = nil + if H.num_joints > 0 then + local joints: { Rig.Joint } = {} + for j = 0, H.num_joints - 1 do + local p = base + H.ofs_joints + j * 48 + local parent = readi32(b, p + 4) + local f = table.create(10) :: { number } + for k = 0, 9 do + f[k + 1] = readf32(b, p + 8 + k * 4) + end + local q = { f[4], f[5], f[6], f[7] } + local ql = math.sqrt(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2) + q = if ql > 0 then { q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql } else { 0, 0, 0, 1 } + joints[j + 1] = { name = str(readu32(b, p)), parent = parent + 1, translation = { f[1], f[2], f[3] }, rotation = q, scale = { f[8], f[9], f[10] } } + end + jointNodes, skin = Rig.skeleton(scene, joints, "local") + end + -- materials: one per distinct material string (IQM names its texture there) + local matOf: { [string]: number } = {} + local function material(name: string): number? + if name == "" then + return nil + end + local hit = matOf[name] + if hit then + return hit + end + local mat = Scene.material(name) + mat.metallic = 0 + local ext = string.lower(string.match(name, "%.(%w+)$") or "") + table.insert(scene.textures, { name = name, uri = name, mime = MIME[ext] }) + mat.baseColorTexture = { texture = #scene.textures } + table.insert(scene.materials, mat) + matOf[name] = #scene.materials + return #scene.materials + end + -- meshes + for m = 0, H.num_meshes - 1 do + local p = base + H.ofs_meshes + m * 24 + local name, mname = str(readu32(b, p)), str(readu32(b, p + 4)) + local fv, cv, ft, ct = readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16), readu32(b, p + 20) + if fv + cv > nv or ft + ct > H.num_triangles then + return nil, "mesh " .. m .. " points outside the vertex / triangle arrays" + end + local attributes: { [string]: Types.Accessor } = {} + for _, a in arrays do + local esize = Read.SIZES[a.format] + local at = a.offset + fv * a.comps * esize + if a.kind == "blendindexes" then + local vals = values(b, at, a.format, cv * a.comps, false) + local big = a.format ~= 1 + local d = buffer.create(cv * 4 * (if big then 2 else 1)) + for v = 0, cv - 1 do + for c = 0, 3 do + local x = if c < a.comps then vals[v * a.comps + c + 1] else 0 + x = math.clamp(math.floor(x), 0, if big then 65535 else 255) + if big then + writeu16(d, (v * 4 + c) * 2, x) + else + writeu8(d, v * 4 + c, x) + end + end + end + attributes.JOINTS_0 = Scene.accessor(d, if big then "u16" else "u8", 4, cv) + elseif a.kind == "blendweights" or (a.kind == "color" and a.format == 1) then + local vals = values(b, at, a.format, cv * a.comps, true) + local d = buffer.create(cv * 4) + for v = 0, cv - 1 do + for c = 0, 3 do + local x = if c < a.comps then vals[v * a.comps + c + 1] elseif a.kind == "color" and c == 3 then 1 else 0 + writeu8(d, v * 4 + c, math.clamp(math.floor(x * 255 + 0.5), 0, 255)) + end + end + attributes[if a.kind == "color" then "COLOR_0" else "WEIGHTS_0"] = Scene.accessor(d, "unorm8", 4, cv) + else + local vals = values(b, at, a.format, cv * a.comps, true) + local name0 = if a.kind == "position" then "POSITION" elseif a.kind == "texcoord" then "TEXCOORD_0" elseif a.kind == "normal" then "NORMAL" elseif a.kind == "tangent" then "TANGENT" elseif a.kind == "color" then "COLOR_0" else a.name + local want = if a.kind == "position" or a.kind == "normal" then 3 elseif a.kind == "texcoord" then 2 elseif a.kind == "tangent" or a.kind == "color" then 4 else a.comps + if want ~= a.comps then + local fixed = table.create(cv * want, 0) :: { number } + for v = 0, cv - 1 do + for c = 0, want - 1 do + fixed[v * want + c + 1] = if c < a.comps then vals[v * a.comps + c + 1] elseif c == 3 then 1 else 0 + end + end + vals = fixed + end + attributes[name0] = f32acc(vals, want) + end + end + if not attributes.POSITION then + return nil, "no position array" + end + -- triangles: IQM's front faces are clockwise; corners 2 and 3 swap for glTF's counter-clockwise + local ib = buffer.create(ct * 12) + for k = 0, ct - 1 do + local q = base + H.ofs_triangles + (ft + k) * 12 + local a, c2, c3 = readu32(b, q), readu32(b, q + 4), readu32(b, q + 8) + if a < fv or c2 < fv or c3 < fv or a >= fv + cv or c2 >= fv + cv or c3 >= fv + cv then + return nil, "triangle " .. (ft + k) .. " uses a vertex outside mesh " .. m + end + writeu32(ib, k * 12, a - fv) + writeu32(ib, k * 12 + 4, c3 - fv) + writeu32(ib, k * 12 + 8, c2 - fv) + end + local prim: Types.Primitive = { attributes = attributes, indices = Scene.accessor(ib, "u32", 1, ct * 3), mode = "triangles", material = material(mname) } + table.insert(scene.meshes, { name = name, primitives = { prim } }) + local node: Types.Node = { name = name, children = {}, mesh = #scene.meshes } + if skin and attributes.JOINTS_0 then + node.skin = skin + end + table.insert(scene.nodes, node) + table.insert(scene.roots, #scene.nodes) + end + -- animations: frames hold the masked pose channels (offset + value * scale), in pose order + if H.num_anims > 0 and H.num_frames > 0 and H.num_poses > 0 then + local np = H.num_poses + local poses: { { mask: number, offset: { number }, scale: { number } } } = {} + local channels = 0 + for i = 0, np - 1 do + local p = base + H.ofs_poses + i * 88 + local mask = readu32(b, p + 4) + local off, sc = table.create(10) :: { number }, table.create(10) :: { number } + for c = 0, 9 do + off[c + 1] = readf32(b, p + 8 + c * 4) + sc[c + 1] = readf32(b, p + 48 + c * 4) + if bit32.band(mask, bit32.lshift(1, c)) ~= 0 then + channels += 1 + end + end + poses[i + 1] = { mask = mask, offset = off, scale = sc } + end + if channels ~= H.num_framechannels then + return nil, "the poses use " .. channels .. " frame channels, the header says " .. H.num_framechannels + end + -- frame f, pose i -> 10 values + local frameBytes: number = H.num_framechannels * 2 + local framesAt: number = base + H.ofs_frames + local function frame(f: number): { { number } } + local out = table.create(np) :: { { number } } + local q = framesAt + f * frameBytes + for i = 1, np do + local ps = poses[i] + local v = table.create(10) :: { number } + for c = 0, 9 do + local x = ps.offset[c + 1] + if bit32.band(ps.mask, bit32.lshift(1, c)) ~= 0 then + local k: number = ps.scale[c + 1] + x += readu16(b, q) * k + q += 2 + end + v[c + 1] = x + end + out[i] = v + end + return out + end + local anims: { any } = {} + for a = 0, H.num_anims - 1 do + local p = base + H.ofs_anims + a * 20 + local name, first, count, rate, flags = str(readu32(b, p)), readu32(b, p + 4), readu32(b, p + 8), readf32(b, p + 12), readu32(b, p + 16) + if first + count > H.num_frames then + return nil, "animation " .. a .. " uses frames past the end" + end + local fps = if rate > 0 and rate == rate then rate else 30 + local times = table.create(count) :: { number } + local tracks: { [number]: Rig.Track } = {} + for j = 1, math.min(np, #jointNodes) do + tracks[j] = { translation = {}, rotation = {}, scale = {} } + end + for k = 0, count - 1 do + times[k + 1] = k / fps + local fr = frame(first + k) + for j, tr in tracks do + local v = fr[j] + local t, r, s = tr.translation :: { number }, tr.rotation :: { number }, tr.scale :: { number } + table.move(v, 1, 3, #t + 1, t) + local ql = math.sqrt(v[4] ^ 2 + v[5] ^ 2 + v[6] ^ 2 + v[7] ^ 2) + ql = if ql > 0 then ql else 1 + table.move({ v[4] / ql, v[5] / ql, v[6] / ql, v[7] / ql }, 1, 4, #r + 1, r) + table.move(v, 8, 10, #s + 1, s) + end + end + if count > 0 then + Rig.animation(scene, name, jointNodes, times, tracks) + end + table.insert(anims, { name = name, first = first, frames = count, framerate = rate, loop = bit32.band(flags, 1) ~= 0 }) + end + source.animations = anims + end + -- bounds: one box per frame + if H.ofs_bounds > 0 and H.num_frames > 0 then + local boxes = {} + for f = 0, H.num_frames - 1 do + local p = base + H.ofs_bounds + f * 32 + boxes[f + 1] = { + min = { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) }, + max = { readf32(b, p + 12), readf32(b, p + 16), readf32(b, p + 20) }, + xyradius = readf32(b, p + 24), + radius = readf32(b, p + 28), + } + end + source.bounds = boxes + end + return scene, nil +end + +return Read diff --git a/src/Formats/model/iqm/Write.luau b/src/Formats/model/iqm/Write.luau new file mode 100644 index 0000000..df6eaf9 --- /dev/null +++ b/src/Formats/model/iqm/Write.luau @@ -0,0 +1,706 @@ +--!strict +-- model/iqm/Write: Types.Scene -> an Inter-Quake Model (version 2). One IQM mesh per triangle-able primitive (lines +-- and points are skipped), vertex arrays position / texcoord / normal / tangent (f32), blend indexes / weights +-- (u8, the four strongest weights, summing to 255) and colour (u8). The skeleton is the union of the scene's skins +-- (parents before children; a joint's parent is its nearest ancestor that is a joint): bind poses from the inverse +-- bind matrices, so IQM's implied inverse bind matrices are the scene's. Unskinned primitives are baked into world +-- space and, in a skinned model, bound to their nearest joint ancestor (else the first joint). Animations are +-- sampled (codecs/model/Sampler) at their own key spacing when it is uniform, else at opts.framerate (default 30), +-- quantized per pose channel to 16 bits, with per-frame bounds from the skinned vertices. +-- Coordinates are written as they are (IQM is z-up: a y-up scene can be turned with F.ops.mesh.setUp first). +-- Plain code (the caller wraps it in pcall). +local Types = require("@formats/Types") +local Bytes = require("@formats/core/Bytes") +local Mat4 = require("@formats/codecs/model/Mat4") +local Sampler = require("@formats/codecs/model/Sampler") +local Read = require("@formats/model/iqm/Read") + +local Write = {} + +local Scene = Types.Scene +type M4 = { number } + +-- ------------------------------------------------------------------------------------------------ scene walk +-- world matrices (rest pose, or with a pose's overrides) and the parent of every node +local function parents(scene: Types.Scene): { [number]: number } + local parent: { [number]: number } = {} + for i, n in scene.nodes do + for _, c in n.children or {} do + if parent[c] == nil and c ~= i then + parent[c] = i + end + end + end + return parent +end + +local function localMatrix(node: Types.Node, over: { [string]: { number } }?): M4 + if not over then + return Scene.nodeMatrix(node) + end + if node.matrix and #node.matrix == 16 and not (over.translation or over.rotation or over.scale) then + return node.matrix + end + local t, r, s = node.translation, node.rotation, node.scale + if node.matrix and #node.matrix == 16 then + t, r, s = Mat4.decompose(node.matrix) + end + return Mat4.compose(over.translation or t, over.rotation or r, over.scale or s) +end + +local function worlds(scene: Types.Scene, parent: { [number]: number }, pose: Sampler.Pose?): { [number]: M4 } + local world: { [number]: M4 } = {} + local function get(i: number, depth: number): M4 + local w = world[i] + if w then + return w + end + local m = localMatrix(scene.nodes[i], pose and pose[i]) + local p = parent[i] + if p and depth < #scene.nodes then + m = Mat4.mul(get(p, depth + 1), m) + end + world[i] = m + return m + end + for i in scene.nodes do + get(i, 0) + end + return world +end + +-- ------------------------------------------------------------------------------------------------ geometry +-- the triangle corners of a primitive (0-based vertex numbers), or nil for lines / points +local function triangles(prim: Types.Primitive): { number }? + local mode = prim.mode or "triangles" + local nv = prim.attributes.POSITION.count + local idx: { number } = {} + if prim.indices then + local get = Scene.reader(prim.indices) + if not get then + return nil + end + for k = 0, prim.indices.count - 1 do + idx[k + 1] = get(k, 0) + end + else + for k = 0, nv - 1 do + idx[k + 1] = k + end + end + local out: { number } = {} + if mode == "triangles" then + for k = 1, #idx - 2, 3 do + table.move(idx, k, k + 2, #out + 1, out) + end + elseif mode == "triangle_strip" then + for k = 1, #idx - 2 do + if k % 2 == 1 then + table.move({ idx[k], idx[k + 1], idx[k + 2] }, 1, 3, #out + 1, out) + else + table.move({ idx[k + 1], idx[k], idx[k + 2] }, 1, 3, #out + 1, out) + end + end + elseif mode == "triangle_fan" then + for k = 2, #idx - 1 do + table.move({ idx[1], idx[k], idx[k + 1] }, 1, 3, #out + 1, out) + end + elseif mode == "polygons" and prim.faces then + local fget = Scene.reader(prim.faces) + local at = 1 + for f = 0, prim.faces.count - 1 do + local n = if fget then fget(f, 0) else 0 + for k = 1, n - 2 do + table.move({ idx[at], idx[at + k], idx[at + k + 1] }, 1, 3, #out + 1, out) + end + at += n + end + else + return nil + end + for _, v in out do + if v >= nv or v < 0 then + error("index " .. v .. " out of range", 0) + end + end + return out +end + +local function readAll(acc: Types.Accessor?, comps: number, nv: number, default: { number }): { number }? + if not acc then + return nil + end + local get = Scene.reader(acc) + if not get or acc.count < nv then + return nil + end + local out = table.create(nv * comps) :: { number } + for v = 0, nv - 1 do + for c = 0, comps - 1 do + out[v * comps + c + 1] = if c < acc.components then get(v, c) else default[c + 1] + end + end + return out +end + +-- the influences of vertex v: global joint numbers, the 4 strongest, u8 weights summing to 255, as a flat list +local function influences(skin: Types.Skin, jointIndex: { [number]: number }, joints: { number }, weights: { number }, v: number): { number } + local pairs_: { { number } } = {} + for c = 1, 4 do + local w = weights[v * 4 + c] + local node = skin.joints[math.floor(joints[v * 4 + c]) + 1] + if w > 0 and node and jointIndex[node] then + table.insert(pairs_, { jointIndex[node], w }) + end + end + table.sort(pairs_, function(a: { number }, b: { number }): boolean + return a[2] > b[2] + end) + local sum = 0 + for _, pr in pairs_ do + sum += pr[2] + end + local q: { number } = {} + local left = 255 + for k, pr in pairs_ do + q[k] = if sum > 0 then math.floor(pr[2] / sum * 255 + 0.5) else 0 + left -= q[k] + end + if #pairs_ > 0 then + q[1] += left + end + local list: { number } = {} + for k, pr in pairs_ do + if q[k] > 0 then + table.insert(list, pr[1]) + table.insert(list, q[k]) + end + end + return list +end + +-- appends a flat influence list to the blend index / weight arrays (4 slots) +local function push4(bi: { number }, bw: { number }, list: { number }) + local n = #bi + for c = 1, 4 do + bi[n + c] = list[c * 2 - 1] or 0 + bw[n + c] = list[c * 2] or 0 + end +end + +-- ------------------------------------------------------------------------------------------------ writer +type MeshOut = { name: string, material: string, first: number, count: number, tfirst: number, tcount: number } + +function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: string? }?): (buffer?, string?) + local parent = parents(scene) + local rest = worlds(scene, parent, nil) + -- the skeleton: every skin joint, parents first + local isJoint: { [number]: boolean } = {} + local ibmOf: { [number]: M4 } = {} + for _, skin in scene.skins do + local get = skin.inverseBindMatrices and Scene.reader(skin.inverseBindMatrices) + for j, node in skin.joints do + if scene.nodes[node] then + isJoint[node] = true + if get and ibmOf[node] == nil and skin.inverseBindMatrices and skin.inverseBindMatrices.count >= j then + local m = table.create(16) :: M4 + for k = 1, 16 do + m[k] = get(j - 1, k - 1) + end + ibmOf[node] = m + end + end + end + end + -- the skins' joints in order, each after its joint ancestors (IQM wants parents first) + local jointList: { number } = {} + local jointIndex: { [number]: number } = {} -- node -> 0-based joint + local function add(n: number, depth: number) + if jointIndex[n] or depth > #scene.nodes then + return + end + local p = parent[n] + local guard = 0 + while p and not isJoint[p] and guard <= #scene.nodes do + p = parent[p] + guard += 1 + end + if p and isJoint[p] then + add(p, depth + 1) + end + if not jointIndex[n] then + table.insert(jointList, n) + jointIndex[n] = #jointList - 1 + end + end + for _, skin in scene.skins do + for _, n in skin.joints do + if isJoint[n] then + add(n, 0) + end + end + end + if #jointList > 65535 then + return nil, "limit: more than 65535 joints" + end + local function jointParent(n: number): number + local p = parent[n] + local guard = 0 + while p and guard <= #scene.nodes do + if jointIndex[p] then + return jointIndex[p] + end + p = parent[p] + guard += 1 + end + return -1 + end + local bindWorld: { [number]: M4 } = {} + for _, n in jointList do + local ibm = ibmOf[n] + bindWorld[n] = (ibm and Mat4.inverseFull(ibm)) or rest[n] + end + local function poseLocal(n: number, world: { [number]: M4 }): ({ number }, { number }, { number }) + local p = jointParent(n) + local m = world[n] + if p >= 0 then + local inv = Mat4.inverseFull(world[jointList[p + 1]]) + if inv then + m = Mat4.mul(inv, m) + end + end + return Mat4.decompose(m) + end + -- the meshes + local nodeOfMesh: { [number]: number } = {} + local placed: { { node: number, mesh: number } } = {} + local seen: { [number]: boolean } = {} + local function visit(i: number, depth: number) + if seen[i] or depth > #scene.nodes then + return + end + seen[i] = true + local node = scene.nodes[i] + if node.mesh and scene.meshes[node.mesh] then + table.insert(placed, { node = i, mesh = node.mesh }) + nodeOfMesh[node.mesh] = nodeOfMesh[node.mesh] or i + end + for _, c in node.children or {} do + visit(c, depth + 1) + end + end + local roots = scene.roots + if not roots or #roots == 0 then + roots = {} + for i in scene.nodes do + if parent[i] == nil then + table.insert(roots, i) + end + end + end + for _, r in roots do + visit(r, 0) + end + if #placed == 0 and #scene.nodes == 0 then + for mi in scene.meshes do + table.insert(placed, { node = 0, mesh = mi }) + end + end + local hasJoints = #jointList > 0 + local P, TC, N, TG, BI, BW, C = {}, {}, {}, {}, {}, {}, {} + local hasTC, hasN, hasTG, hasC = false, false, false, false + local tris: { number } = {} + local meshes: { MeshOut } = {} + -- every primitive's per-vertex skinning as lists (joint, weight), for the bounds + local skinOf: { { number } } = {} + local nvTotal = 0 + for _, pl in placed do + local node = scene.nodes[pl.node] + local mesh = scene.meshes[pl.mesh] + local skinned = node and node.skin and scene.skins[node.skin] + local world = if pl.node > 0 then rest[pl.node] else Scene.IDENTITY + local nrmM = Mat4.normalMatrix(world) + for pi, prim in mesh.primitives do + local pos = prim.attributes.POSITION + local tri = pos and triangles(prim) + if tri and #tri > 0 then + local nv = pos.count + local first = nvTotal + local positions = readAll(pos, 3, nv, { 0, 0, 0 }) :: { number } + local normals = readAll(prim.attributes.NORMAL, 3, nv, { 0, 0, 1 }) + local tangents = readAll(prim.attributes.TANGENT, 4, nv, { 1, 0, 0, 1 }) + local uvs = readAll(prim.attributes.TEXCOORD_0, 2, nv, { 0, 0 }) + local cols = readAll(prim.attributes.COLOR_0, 4, nv, { 1, 1, 1, 1 }) + local joints = skinned and readAll(prim.attributes.JOINTS_0, 4, nv, { 0, 0, 0, 0 }) + local weights = skinned and readAll(prim.attributes.WEIGHTS_0, 4, nv, { 0, 0, 0, 0 }) + local rigid = -1 + if hasJoints and not (joints and weights) then + local p = if pl.node > 0 then pl.node else nil + local guard = 0 + while p and guard <= #scene.nodes do + if jointIndex[p] then + rigid = jointIndex[p] + break + end + p = parent[p] + guard += 1 + end + rigid = math.max(rigid, 0) + end + local bake = not (joints and weights) + for v = 0, nv - 1 do + local x, y, z = positions[v * 3 + 1], positions[v * 3 + 2], positions[v * 3 + 3] + if bake then + x, y, z = Mat4.point(world, x, y, z) + end + table.move({ x, y, z }, 1, 3, #P + 1, P) + if normals then + local nx, ny, nz = normals[v * 3 + 1], normals[v * 3 + 2], normals[v * 3 + 3] + if bake then + nx, ny, nz = Mat4.point(nrmM, nx, ny, nz) + nx, ny, nz = nx - nrmM[13], ny - nrmM[14], nz - nrmM[15] + local l = math.sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + end + hasN = true + table.move({ nx, ny, nz }, 1, 3, #N + 1, N) + else + table.move({ 0, 0, 1 }, 1, 3, #N + 1, N) + end + if tangents then + local tx, ty, tz = tangents[v * 4 + 1], tangents[v * 4 + 2], tangents[v * 4 + 3] + if bake then + tx, ty, tz = Mat4.point(world, tx, ty, tz) + tx, ty, tz = tx - world[13], ty - world[14], tz - world[15] + end + hasTG = true + table.move({ tx, ty, tz, tangents[v * 4 + 4] }, 1, 4, #TG + 1, TG) + else + table.move({ 1, 0, 0, 1 }, 1, 4, #TG + 1, TG) + end + if uvs then + hasTC = true + table.move(uvs, v * 2 + 1, v * 2 + 2, #TC + 1, TC) + else + table.move({ 0, 0 }, 1, 2, #TC + 1, TC) + end + if cols then + hasC = true + table.move(cols, v * 4 + 1, v * 4 + 4, #C + 1, C) + else + table.move({ 1, 1, 1, 1 }, 1, 4, #C + 1, C) + end + -- influences: global joint numbers, the 4 strongest, u8 weights summing to 255 + local list: { number } + if joints and weights and skinned then + list = influences(skinned, jointIndex, joints, weights, v) + elseif rigid >= 0 then + list = { rigid, 255 } + else + list = {} + end + push4(BI, BW, list) + skinOf[#skinOf + 1] = list + end + -- triangles back to IQM's clockwise order + local tfirst = #tris // 3 + for k = 1, #tri, 3 do + table.move({ first + tri[k], first + tri[k + 2], first + tri[k + 1] }, 1, 3, #tris + 1, tris) + end + local mat = prim.material and scene.materials[prim.material] + local mname = "" + if mat then + local ref = mat.baseColorTexture + local tex = ref and scene.textures[ref.texture] + mname = if tex and tex.uri then tex.uri elseif mat.name then mat.name else "" + end + local name = mesh.name or ("mesh" .. pl.mesh) + if #mesh.primitives > 1 then + name ..= "_" .. pi + end + table.insert(meshes, { name = name, material = mname, first = first, count = nv, tfirst = tfirst, tcount = #tri // 3 }) + nvTotal += nv + end + end + end + if #meshes == 0 then + return nil, "nothing to write: no triangle primitives" + end + -- animation frames + local frames: { { { number } } } = {} -- frames[f][joint] = 10 values + local anims: { { name: string, first: number, count: number, rate: number } } = {} + local frameWorld: { { [number]: M4 } } = {} + if hasJoints then + for ai, anim in scene.animations do + local keys = Sampler.times(anim) + if #keys > 0 then + local rate = opts and opts.framerate + if not rate then + -- the key spacing when uniform (decoded IQM / MD5 animations), else 30 per second + local dt = if #keys > 1 then keys[2] - keys[1] else 0 + local uniform = dt > 0 and math.abs(keys[1] - math.floor(keys[1] / dt + 0.5) * dt) < 1e-4 + for k = 2, #keys do + uniform = uniform and math.abs(keys[k] - keys[k - 1] - dt) < 1e-4 + end + rate = if uniform then 1 / dt else 30 + end + local fps: number = math.clamp(rate :: number, 1e-3, 1e4) + local last = keys[#keys] + local count = math.max(1, math.floor(last * fps + 0.5) + 1) + if count > 100000 then + return nil, "limit: animation " .. ai .. " has more than 100000 frames" + end + local cache = {} + local first = #frames + local prevQ: { [number]: { number } } = {} + for k = 0, count - 1 do + local pose = Sampler.pose(scene, anim, k / fps, cache) + local world = worlds(scene, parent, pose) + local fr = table.create(#jointList) :: { { number } } + for j, n in jointList do + local t, r, s = poseLocal(n, world) + local pq = prevQ[j] + if pq and pq[1] * r[1] + pq[2] * r[2] + pq[3] * r[3] + pq[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + prevQ[j] = r + fr[j] = { t[1], t[2], t[3], r[1], r[2], r[3], r[4], s[1], s[2], s[3] } + end + table.insert(frames, fr) + table.insert(frameWorld, world) + end + table.insert(anims, { name = anim.name or ("anim" .. ai), first = first, count = count, rate = fps }) + end + end + end + -- quantization per pose channel + local masks, offsets, scales = {}, {}, {} + local numChannels = 0 + for j = 1, #jointList do + local lo, hi = table.create(10, math.huge), table.create(10, -math.huge) + for _, fr in frames do + for c = 1, 10 do + lo[c] = math.min(lo[c], fr[j][c]) + hi[c] = math.max(hi[c], fr[j][c]) + end + end + local mask = 0 + local off, sc = table.create(10, 0), table.create(10, 0) + for c = 1, 10 do + if lo[c] <= hi[c] then + off[c] = lo[c] + if hi[c] - lo[c] > 1e-6 then + mask = bit32.bor(mask, bit32.lshift(1, c - 1)) + sc[c] = (hi[c] - lo[c]) / 65535 + numChannels += 1 + end + end + end + masks[j], offsets[j], scales[j] = mask, off, sc + end + -- text + local text = { "\0" } + local textLen = 1 + local textAt: { [string]: number } = { [""] = 0 } + local function str(s: string): number + local hit = textAt[s] + if hit then + return hit + end + s = string.gsub(s, "%z", "") + local at = textLen + table.insert(text, s .. "\0") + textLen += #s + 1 + textAt[s] = at + return at + end + for _, m in meshes do + str(m.name) + str(m.material) + end + for _, n in jointList do + str(scene.nodes[n].name or "") + end + for _, a in anims do + str(a.name) + end + local comment = opts and opts.comment + -- layout + local w = Bytes.writer(124 + nvTotal * 64 + #tris * 4) + local H: { [string]: number } = {} + local function at(): number + return w:tell() + end + w:string("INTERQUAKEMODEL\0") + for _ = 1, 27 do + w:u32le(0) + end + H.ofs_text, H.num_text = at(), textLen + w:string(table.concat(text)) + while at() % 4 ~= 0 do + w:u8(0) + H.num_text += 1 + end + H.ofs_meshes, H.num_meshes = at(), #meshes + for _, m in meshes do + for _, v in { str(m.name), str(m.material), m.first, m.count, m.tfirst, m.tcount } do + w:u32le(v) + end + end + -- vertex arrays: headers, then data + type Arr = { typ: number, format: number, comps: number, data: { number } } + local arrs: { Arr } = { { typ = 0, format = 7, comps = 3, data = P } } + if hasTC then + table.insert(arrs, { typ = 1, format = 7, comps = 2, data = TC }) + end + if hasN then + table.insert(arrs, { typ = 2, format = 7, comps = 3, data = N }) + end + if hasTG then + table.insert(arrs, { typ = 3, format = 7, comps = 4, data = TG }) + end + if hasJoints then + table.insert(arrs, { typ = 4, format = if #jointList > 256 then 3 else 1, comps = 4, data = BI }) + table.insert(arrs, { typ = 5, format = 1, comps = 4, data = BW }) + end + if hasC then + table.insert(arrs, { typ = 6, format = 1, comps = 4, data = C }) + end + H.ofs_vertexarrays, H.num_vertexarrays, H.num_vertexes = at(), #arrs, nvTotal + w:fill(0, #arrs * 20) + local dataAt: { number } = {} + for i, a in arrs do + while at() % 4 ~= 0 do + w:u8(0) + end + dataAt[i] = at() + if a.format == 7 then + for _, v in a.data do + w:f32le(v) + end + elseif a.format == 3 then + for _, v in a.data do + w:u16le(math.clamp(math.floor(v), 0, 65535)) + end + elseif a.typ == 6 then + for _, v in a.data do + w:u8(math.clamp(math.floor(v * 255 + 0.5), 0, 255)) + end + else + for _, v in a.data do + w:u8(math.clamp(math.floor(v), 0, 255)) + end + end + end + while at() % 4 ~= 0 do + w:u8(0) + end + H.ofs_triangles, H.num_triangles = at(), #tris // 3 + for _, v in tris do + w:u32le(v) + end + if hasJoints then + H.ofs_joints, H.num_joints = at(), #jointList + for _, n in jointList do + local p = jointParent(n) + local t, r, s = poseLocal(n, bindWorld) + w:u32le(str(scene.nodes[n].name or "")) + w:u32le(if p < 0 then p + 2 ^ 32 else p) + for _, v in { t[1], t[2], t[3], r[1], r[2], r[3], r[4], s[1], s[2], s[3] } do + w:f32le(v) + end + end + if #frames > 0 then + H.ofs_poses, H.num_poses = at(), #jointList + for j, n in jointList do + local jp = jointParent(n) + w:u32le(if jp < 0 then jp + 2 ^ 32 else jp) + w:u32le(masks[j]) + for c = 1, 10 do + w:f32le(offsets[j][c]) + end + for c = 1, 10 do + w:f32le(scales[j][c]) + end + end + H.ofs_anims, H.num_anims = at(), #anims + for _, a in anims do + w:u32le(str(a.name)) + w:u32le(a.first) + w:u32le(a.count) + w:f32le(a.rate) + w:u32le(0) + end + H.ofs_frames, H.num_frames, H.num_framechannels = at(), #frames, numChannels + for _, fr in frames do + for j = 1, #jointList do + local mask = masks[j] + for c = 1, 10 do + if bit32.band(mask, bit32.lshift(1, c - 1)) ~= 0 then + local q = (fr[j][c] - offsets[j][c]) / scales[j][c] + w:u16le(math.clamp(math.floor(q + 0.5), 0, 65535)) + end + end + end + end + while at() % 4 ~= 0 do + w:u8(0) + end + -- bounds of the skinned vertices per frame + H.ofs_bounds = at() + local skinM = table.create(#jointList) :: { M4 } + for f, world in frameWorld do + for j, n in jointList do + local invBind = Mat4.inverseFull(bindWorld[n]) or Mat4.identity() + skinM[j] = Mat4.mul(world[n], invBind) + end + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local xy, rad = 0, 0 + for v = 0, nvTotal - 1 do + local x, y, z = P[v * 3 + 1], P[v * 3 + 2], P[v * 3 + 3] + local list = skinOf[v + 1] + if #list > 0 then + local sx, sy, sz = 0, 0, 0 + for k = 1, #list - 1, 2 do + local m = skinM[list[k] + 1] + local wt = list[k + 1] / 255 + local px, py, pz = Mat4.point(m, x, y, z) + sx, sy, sz = sx + px * wt, sy + py * wt, sz + pz * wt + end + x, y, z = sx, sy, sz + end + lo = { math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z) } + hi = { math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z) } + xy = math.max(xy, x * x + y * y) + rad = math.max(rad, x * x + y * y + z * z) + end + for _, v in { lo[1], lo[2], lo[3], hi[1], hi[2], hi[3], math.sqrt(xy), math.sqrt(rad) } do + w:f32le(v) + end + local _ = f + end + end + end + if comment and comment ~= "" then + H.ofs_comment, H.num_comment = at(), #comment + 1 + w:string(comment .. "\0") + end + local out = w:finish() + H.version, H.filesize = 2, buffer.len(out) + for i, name in Read.HEADER do + buffer.writeu32(out, 12 + i * 4, H[name] or 0) + end + for i, a in arrs do + local p = H.ofs_vertexarrays + (i - 1) * 20 + buffer.writeu32(out, p, a.typ) + buffer.writeu32(out, p + 4, 0) + buffer.writeu32(out, p + 8, a.format) + buffer.writeu32(out, p + 12, a.comps) + buffer.writeu32(out, p + 16, dataAt[i]) + end + return out, nil +end + +return Write diff --git a/src/Formats/model/iqm/init.luau b/src/Formats/model/iqm/init.luau new file mode 100644 index 0000000..c46a61b --- /dev/null +++ b/src/Formats/model/iqm/init.luau @@ -0,0 +1,82 @@ +--!strict +-- model/iqm: Inter-Quake Model (IQM version 2), read and write. New code from the IQM format description (iqm.txt / +-- iqm.h of Lee Salzman's IQM SDK, public domain); checked against assimp (which reads IQM geometry). +-- Reads meshes (one node + mesh each; material strings -> materials whose baseColorTexture uri is that string, as +-- IQM tools name the texture there), vertex arrays in every IQM format (position, texcoord (top-left origin, as +-- glTF), normal, tangent, blend indexes / weights -> JOINTS_0 / WEIGHTS_0, colour, custom arrays as _), joints +-- (a node each, bind pose TRS, one skin with the inverse bind matrices), poses + frames + anims (16-bit channels +-- dequantized into translation / rotation / scale channels at the anim's frame rate; loop flags and frame ranges in +-- meta.source.animations) and per-frame bounds (meta.source.bounds). IQM's clockwise triangles become glTF's +-- counter-clockwise ones; IQM is z-up (meta.up = "z", nothing is rotated). +-- Writes the same (see model/iqm/Write): any Scene's triangle primitives, skins merged into one skeleton, sampled and +-- quantized animations, bounds. Not supported: IQM version 1, adjacency and extensions (skipped on read, not written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Read = require("@formats/model/iqm/Read") +local Write = require("@formats/model/iqm/Write") + +-- ------------------------------------------------------------------------------------------------ contract +local Iqm = { + name = "iqm", + category = "model", + extensions = { "iqm" }, + mime = { "model/x-iqm" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Sampler" }, + caps = { decode = true, encode = true, materials = true, skins = true, animation = true, vertexColors = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxVertices: number?, -- refuse more vertices or triangles (default 2^25) +} +export type EncodeOptions = { + framerate: number?, -- animation sampling rate (default: the key spacing when uniform, else 30 per second) + comment: string?, -- stored in the comment block +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "INTERQUAKEMODEL\0" + +-- ------------------------------------------------------------------------------------------------ sniff +function Iqm.sniff(r: Bytes.Reader): number + return if r:peek(16) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Iqm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + if r.limit - r.base < 124 then + return nil, Err.new(Err.TRUNCATED, "shorter than the header", r.base) + end + if r:peek(16) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "no INTERQUAKEMODEL magic", r.base) + end + local ok, scene, msg = pcall(Read.scene, r.buf, r.base, r.limit, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "bad model data: " .. tostring(scene)) + end + if not scene then + return nil, Err.from(msg) + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Iqm.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 ok, out, msg = pcall(Write.iqm, scene, opts) + if not ok then + return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out)) + end + if not out then + local e = Err.from(msg) + return nil, Err.new(if e.code == Err.CORRUPT then Err.ARG else e.code, e.message) + end + return out, nil +end + +return Iqm diff --git a/tests/codecs/sampler.luau b/tests/codecs/sampler.luau new file mode 100644 index 0000000..bfdb746 --- /dev/null +++ b/tests/codecs/sampler.luau @@ -0,0 +1,92 @@ +-- codecs/model/Sampler tests: STEP / LINEAR / CUBICSPLINE channels (glTF's Hermite definition), quaternion slerp +-- (shortest path, unit length), clamping outside the keys, weights channels, Sampler.times and Sampler.pose; glTF's +-- InterpolationTest sample model (every interpolation) sampled at its keys gives the key values; bad channels. +local T = require("@tests/T") +local Sampler = require("@formats/codecs/model/Sampler") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Picks = require("@tests/gen/iqm_gltf") + +local t = T.suite("codecs/sampler") +local S = Types.Scene + +local function acc(list: { number }, comps: number): Types.Accessor + local b = buffer.create(#list * 4) + for i, v in list do + buffer.writef32(b, (i - 1) * 4, v) + end + return S.accessor(b, "f32", comps, #list // comps) +end +local function near(a: number, b: number, eps: number?): boolean + return math.abs(a - b) < (eps or 1e-5) +end + +do + local ch: Types.Channel = { node = 1, path = "translation", input = acc({ 0, 1, 3 }, 1), output = acc({ 0, 0, 0, 2, 4, 6, 2, 0, 0 }, 3), interpolation = "LINEAR" } + local s = assert(Sampler.channel(ch)) + t:check(near(s(0.5)[1], 1) and near(s(0.5)[2], 2), "linear: halfway") + t:check(near(s(2)[1], 2) and near(s(2)[2], 2), "linear: second span") + t:check(near(s(-1)[2], 0) and near(s(9)[1], 2), "linear: clamped outside the keys") + ch.interpolation = "STEP" + local st = assert(Sampler.channel(ch)) + t:check(near(st(0.99)[1], 0) and near(st(1)[1], 2), "step") +end +do + -- rotation: 0 -> 90 degrees about z, and a key stored with the opposite sign (shortest path) + local h = math.sqrt(0.5) + local ch: Types.Channel = { node = 1, path = "rotation", input = acc({ 0, 1, 2 }, 1), output = acc({ 0, 0, 0, 1, 0, 0, h, h, 0, 0, -h, -h }, 4), interpolation = "LINEAR" } + local s = assert(Sampler.channel(ch)) + local q = s(0.5) + local a = 2 * math.acos(q[4]) + t:check(near(a, math.pi / 4, 1e-4) and near(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2, 1), "slerp: 45 degrees, unit length") + local q2 = s(1.5) + t:check(near(math.abs(q2[3]), h, 1e-4), "slerp: the same orientation stored negated stays put") +end +do + -- cubic spline: in-tangent, value, out-tangent per key; p(t) for p0 = 0, p1 = 1, m0 = m1 = 0 is smoothstep + local ch: Types.Channel = { node = 1, path = "scale", input = acc({ 0, 2 }, 1), output = acc({ 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 9, 9, 9 }, 3), interpolation = "CUBICSPLINE" } + local s = assert(Sampler.channel(ch)) + t:check(near(s(1)[1], 0.5) and near(s(0.5)[1], 3 * 0.25 ^ 2 - 2 * 0.25 ^ 3), "cubic: smoothstep") + t:check(near(s(2)[2], 1), "cubic: the last value") + -- tangents scale with the key spacing + local ch2: Types.Channel = { node = 1, path = "translation", input = acc({ 0, 2 }, 1), output = acc({ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 3), interpolation = "CUBICSPLINE" } + local s2 = assert(Sampler.channel(ch2)) + -- h10(0.5) * dt * m0 = 0.125 * 2 * 1 + t:check(near(s2(1)[1], 0.25), "cubic: tangents times the key spacing") +end +do + local ch: Types.Channel = { node = 2, path = "weights", input = acc({ 0, 1 }, 1), output = acc({ 1, 0, 0, 1 }, 1), interpolation = "LINEAR" } + local s = assert(Sampler.channel(ch)) + local w = s(0.25) + t:check(#w == 2 and near(w[1], 0.75) and near(w[2], 0.25), "weights") + local anim: Types.Animation = { name = "a", channels = { ch, { node = 1, path = "translation", input = acc({ 0.5, 1 }, 1), output = acc({ 0, 0, 0, 1, 1, 1 }, 3), interpolation = "STEP" } } } + local times = Sampler.times(anim) + t:eq(table.concat(times, " "), "0 0.5 1", "times: sorted, unique") + local pose = Sampler.pose(S.new(), anim, 1) + t:check(pose[2].weights and pose[1].translation and near(pose[1].translation[1], 1), "pose") + t:check(Sampler.channel({ node = 1, path = "translation", input = acc({ 0, 1 }, 1), output = acc({ 1, 2 }, 1), interpolation = "LINEAR" }) == nil, "short output: nil") + t:check(Sampler.channel({ node = 1, path = "translation", input = {} :: any, output = {} :: any, interpolation = "LINEAR" }) == nil, "junk: nil") +end +do + -- a real file: sampling a glTF sample model's skin animation at its own keys returns the key values + local g = assert(Gltf.decode(Bytes.reader(buffer.fromstring(Picks[1].data)), { files = Picks[1].files })) + local ok, total = true, 0 + for _, anim in g.animations do + for _, ch in anim.channels do + local s = assert(Sampler.channel(ch)) + local IN, OUT = assert(S.reader(ch.input)), assert(S.reader(ch.output)) + local comps = if ch.path == "rotation" then 4 else 3 + for k = 0, ch.input.count - 1 do + local v = s(IN(k, 0)) + for c = 1, comps do + ok = ok and near(v[c], OUT(k, c - 1), 1e-4) + end + total += 1 + end + end + end + t:check(ok and total > 0, Picks[1].name .. ": samples at the keys are the keys (" .. total .. ")") +end + +t:done() diff --git a/tests/model/iqm.luau b/tests/model/iqm.luau new file mode 100644 index 0000000..588320e --- /dev/null +++ b/tests/model/iqm.luau @@ -0,0 +1,319 @@ +-- model/iqm tests: assimp's mrfixit.iqm against assimp (meshes, triangles, vertices, materials, bind pose bounds), an +-- independent Python reader (joints, anims) and the bounds the IQM tool stored per frame (our decoded skeleton and +-- animation, skinned here, must reproduce them); writer round trips (mrfixit, glTF sample models with and without +-- skins) read back by our reader, by assimp and by the Python reader, whose skinning of our files must match ours; +-- errors; the fuzz no-throw pass. Fixtures: tools/fixtures/iqm.py. +local T = require("@tests/T") +local Iqm = require("@formats/model/iqm") +local Gltf = require("@formats/model/gltf") +local MeshOps = require("@formats/ops/MeshOps") +local Sampler = require("@formats/codecs/model/Sampler") +local Mat4 = require("@formats/codecs/model/Mat4") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Cases = require("@tests/gen/iqm_cases") +local Picks = require("@tests/gen/iqm_gltf") +local Xcheck = require("@tests/gen/iqm_xcheck") + +local t = T.suite("iqm") +local S = Types.Scene + +local function decode(data: any, opts: any?): (any, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Iqm.decode(Bytes.reader(b), opts) +end + +t:eq(Iqm.name, "iqm", "name") +t:eq(Iqm.category, "model", "category") +t:check(Iqm.caps.decode and Iqm.caps.encode, "caps") + +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 +-- the largest coordinate difference between two boxes +local function boxDiff(lo: { number }, hi: { number }, want: any): number + local d = 0 + for k = 1, 3 do + d = math.max(d, math.abs(lo[k] - want.min[k]), math.abs(hi[k] - want.max[k])) + end + return d +end +local function boxNear(lo: { number }, hi: { number }, want: any, eps: number): boolean + for k = 1, 3 do + if not near(lo[k], want.min[k], eps) or not near(hi[k], want.max[k], eps) then + return false + end + end + return true +end +-- assimp's IQM root turns z-up into y-up: (x, y, z) -> (x, z, -y) +local function zUpToY(lo: { number }, hi: { number }): ({ number }, { number }) + return { lo[1], lo[3], -hi[2] }, { hi[1], hi[3], -lo[2] } +end + +local function counts(scene: any): (number, number, number) + local prims, tris, verts = 0, 0, 0 + for _, m in scene.meshes do + for _, p in m.primitives do + prims += 1 + tris += p.indices.count // 3 + verts += p.attributes.POSITION.count + end + end + return prims, tris, verts +end + +-- the bounding box of every mesh vertex, skinned with the scene's skins at time t of anim (nil: the rest pose) +local function skinnedBounds(scene: any, anim: any?, time: number): ({ number }, { number }) + local pose = if anim then Sampler.pose(scene, anim, time) else nil + local parent = {} + for i, n in scene.nodes do + for _, c in n.children do + parent[c] = i + end + end + local world = {} + local function W(i: number): { number } + if world[i] then + return world[i] + end + local node = scene.nodes[i] + local over = pose and pose[i] + local m + if over then + m = Mat4.compose(over.translation or node.translation, over.rotation or node.rotation, over.scale or node.scale) + else + m = S.nodeMatrix(node) + end + if parent[i] then + m = S.mul(W(parent[i]), m) + end + world[i] = m + return m + end + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for ni, node in scene.nodes do + local mesh = node.mesh and scene.meshes[node.mesh] + if mesh then + local skin = node.skin and scene.skins[node.skin] + local mats = {} + if skin then + local ibm = assert(S.reader(skin.inverseBindMatrices)) + for j, jn in skin.joints do + local inv = {} + for k = 1, 16 do + inv[k] = ibm(j - 1, k - 1) + end + mats[j - 1] = S.mul(W(jn), inv) + end + end + local LINES = { points = true, lines = true, line_strip = true, line_loop = true } + for _, p in mesh.primitives do + if LINES[p.mode] then + continue + end + local P = assert(S.reader(p.attributes.POSITION)) + local J = p.attributes.JOINTS_0 and S.reader(p.attributes.JOINTS_0) + local Wt = p.attributes.WEIGHTS_0 and S.reader(p.attributes.WEIGHTS_0) + for v = 0, p.attributes.POSITION.count - 1 do + local x, y, z = P(v, 0), P(v, 1), P(v, 2) + if skin and J and Wt then + local sx, sy, sz = 0, 0, 0 + for c = 0, 3 do + local w = Wt(v, c) + if w > 0 then + local qx, qy, qz = Mat4.point(mats[J(v, c)], x, y, z) + sx, sy, sz = sx + w * qx, sy + w * qy, sz + w * qz + end + end + x, y, z = sx, sy, sz + else + x, y, z = Mat4.point(W(ni), x, y, z) + end + lo = { math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z) } + hi = { math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z) } + end + end + end + end + return lo, hi +end + +local function xcheck(name: string): any + for _, x in Xcheck do + if x.name == name then + return x + end + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ mrfixit +local fixit = Cases[1] +local scene, err = decode(fixit.data) +t:check(scene, "mrfixit: decode " .. tostring(err)) +do + local a, ref = fixit.assimp, fixit.ref + local prims, tris, verts = counts(scene) + t:eq(prims, a.meshes, "mrfixit: meshes (assimp)") + t:eq(tris, a.faces, "mrfixit: triangles (assimp)") + t:eq(verts, a.vertices, "mrfixit: vertices (assimp)") + t:eq(#scene.materials, a.materials, "mrfixit: materials (assimp)") + t:eq(scene.textures[scene.materials[1].baseColorTexture.texture].uri, "Body.jpg", "mrfixit: material string -> texture uri") + local lo, hi = MeshOps.bounds(MeshOps.merge(scene)) + local ylo, yhi = zUpToY(lo, hi) + t:check(boxNear(ylo, yhi, a, 1e-4), string.format("mrfixit: bind pose bounds (assimp) %s / %s", table.concat(ylo, " "), table.concat(yhi, " "))) + t:eq(#scene.skins, 1, "mrfixit: one skin") + t:eq(#scene.skins[1].joints, ref.joints, "mrfixit: joints (Python reader)") + for j, n in scene.skins[1].joints do + t:eq(scene.nodes[n].name, ref.jointNames[j], "mrfixit: joint name " .. j) + end + t:eq(#scene.animations, #ref.anims, "mrfixit: animations") + t:eq(scene.animations[1].name, ref.anims[1].name, "mrfixit: animation name") + t:eq(scene.meta.source.animations[1].frames, ref.anims[1].frames, "mrfixit: frames") + local prim = scene.meshes[1].primitives[1] + t:check(prim.attributes.JOINTS_0 and prim.attributes.WEIGHTS_0.type == "unorm8", "mrfixit: blend indexes / weights") + t:check(prim.attributes.TANGENT and prim.attributes.TANGENT.components == 4, "mrfixit: tangents") + -- the bounds the IQM tool stored, from our skeleton + animation (and the Python reader's skinning agrees) + local fps = ref.anims[1].framerate + -- (the tool computed its bounds before quantizing the frames: up to 0.1% off the quantized animation) + local worst, worstPy = 0, 0 + for f = 1, ref.frames, 5 do + local l, h = skinnedBounds(scene, scene.animations[1], (f - 1) / fps) + worst = math.max(worst, boxDiff(l, h, ref.stored[f])) + worstPy = math.max(worstPy, boxDiff(l, h, ref.skinned[f])) + t:check(boxDiff(ref.skinned[f].min, ref.skinned[f].max, ref.stored[f]) < 1e-2, "mrfixit: the Python reader reproduces the stored bounds, frame " .. f) + end + t:check(worst < 1e-2, "mrfixit: skinned bounds per frame match the IQM tool's (worst " .. worst .. ")") + t:check(worstPy < 1e-4, "mrfixit: skinned bounds per frame match the Python reader's (worst " .. worstPy .. ")") + t:check(scene.meta.source.bounds and #scene.meta.source.bounds == ref.frames, "mrfixit: bounds block read") +end + +-- ------------------------------------------------------------------------------------------------ round trips +do + local out = assert(Iqm.encode(scene)) + local back = assert(decode(out)) + local p1, t1, v1 = counts(scene) + local p2, t2, v2 = counts(back) + t:check(p1 == p2 and t1 == t2 and v1 == v2, "round trip: counts") + -- positions and indices exact + local same = true + for mi, m in scene.meshes do + local a, b = m.primitives[1], back.meshes[mi].primitives[1] + t:check(buffer.tostring(a.attributes.POSITION.data) == buffer.tostring(b.attributes.POSITION.data), "round trip: positions exact, mesh " .. mi) + t:check(buffer.tostring(a.indices.data) == buffer.tostring(b.indices.data), "round trip: triangles exact, mesh " .. mi) + -- influences: the same (joint, weight) pairs (unused slots and their order may differ) + local ja, wa, jb, wb = S.reader(a.attributes.JOINTS_0), S.reader(a.attributes.WEIGHTS_0), S.reader(b.attributes.JOINTS_0), S.reader(b.attributes.WEIGHTS_0) + for v = 0, a.attributes.POSITION.count - 1 do + local inf = {} + for c = 0, 3 do + if (wa :: any)(v, c) > 0 then + inf[(ja :: any)(v, c)] = (inf[(ja :: any)(v, c)] or 0) + (wa :: any)(v, c) + end + end + for c = 0, 3 do + local w = (wb :: any)(v, c) + if w > 0 then + local j = (jb :: any)(v, c) + same = same and inf[j] ~= nil and math.abs(inf[j] - w) < 1.5 / 255 + inf[j] = nil + end + end + same = same and next(inf) == nil + end + end + t:check(same, "round trip: the same influences") + t:eq(#back.skins[1].joints, #scene.skins[1].joints, "round trip: joints") + t:eq(back.meta.source.animations[1].frames, scene.meta.source.animations[1].frames, "round trip: frames") + local worst = 0 + for _, time in { 0, 0.5, 1.5, 3 } do + local l1, h1 = skinnedBounds(scene, scene.animations[1], time) + local l2, h2 = skinnedBounds(back, back.animations[1], time) + for k = 1, 3 do + worst = math.max(worst, math.abs(l1[k] - l2[k]), math.abs(h1[k] - h2[k])) + end + end + t:check(worst < 2e-3, "round trip: the animation skins the same (worst " .. worst .. ")") + -- assimp and the Python reader on our file + local x = assert(xcheck("rt_mrfixit.iqm"), "xcheck rt_mrfixit") + t:eq(x.assimp.faces, fixit.assimp.faces, "round trip: assimp triangles") + t:eq(x.assimp.vertices, fixit.assimp.vertices, "round trip: assimp vertices") + t:check(boxNear(x.assimp.min, x.assimp.max, fixit.assimp, 1e-4), "round trip: assimp bounds") + local w2, w3 = 0, 0 + for f, box in fixit.ref.skinned do + local mine = x.ref.skinned[f] + w2 = math.max(w2, boxDiff(mine.min, mine.max, box)) + w3 = math.max(w3, boxDiff(x.ref.stored[f].min, x.ref.stored[f].max, mine)) + end + t:check(w2 < 2e-3, "round trip: the Python reader skins our file like the original (worst " .. w2 .. ")") + t:check(w3 < 1e-4, "round trip: our bounds block matches the Python skinning (worst " .. w3 .. ")") +end + +-- glTF sample models through the writer +for _, p in Picks do + local g = assert(Gltf.decode(Bytes.reader(buffer.fromstring(p.data)), { files = p.files })) + local out, e = Iqm.encode(g) + t:check(out, p.name .. ": encode " .. tostring(e)) + local back = assert(decode(out)) + local x = assert(xcheck("gltf_" .. p.name .. ".iqm"), "xcheck " .. p.name) + local _, tris, verts = counts(back) + t:eq(x.assimp.faces, tris, p.name .. ": assimp reads our triangles") + t:eq(x.assimp.vertices, verts, p.name .. ": assimp reads our vertices") + -- unskinned: the glTF scene's world bounds (skinned: IQM's rest pose is the bind pose, checked by the frames below) + local l2, h2 = skinnedBounds(back, nil, 0) + if #g.skins == 0 then + local lo, hi = skinnedBounds(g, nil, 0) + t:check(boxNear(l2, h2, { min = lo, max = hi }, 1e-4), p.name .. ": world bounds kept") + end + local yl, yh = zUpToY(l2, h2) + t:check(boxNear(yl, yh, x.assimp, 1e-3), p.name .. ": assimp bounds of our file") + if #g.skins > 0 and #g.animations > 0 then + local anim = x.ref.anims[1] + local worst = 0 + for f = 1, x.ref.frames do + local l, h = skinnedBounds(g, g.animations[1], (f - 1) / anim.framerate) + local py = x.ref.skinned[f] + for k = 1, 3 do + worst = math.max(worst, math.abs(l[k] - py.min[k]), math.abs(h[k] - py.max[k])) + end + end + t:check(worst < 5e-3, p.name .. ": the Python reader skins our file like the glTF animation (worst " .. worst .. ")") + t:eq(#back.skins[1].joints, #g.skins[1].joints, p.name .. ": joints") + end +end + +-- ------------------------------------------------------------------------------------------------ errors +do + local _, e1 = decode("INTERQUAKEMODEL\0") + t:check(e1 and e1.code == Err.TRUNCATED, "short: " .. tostring(e1)) + local bad = buffer.fromstring(fixit.data) + buffer.writeu32(bad, 16, 1) + local _, e2 = decode(bad) + t:check(e2 and e2.code == Err.UNSUPPORTED, "version 1: " .. tostring(e2)) + local cut = buffer.fromstring(string.sub(fixit.data, 1, 5000)) + local _, e3 = decode(cut) + t:check(e3 and e3.code == Err.TRUNCATED, "cut: " .. tostring(e3)) + local _, e4 = decode(fixit.data, { maxVertices = 100 }) + t:check(e4 and e4.code == Err.LIMIT, "maxVertices: " .. tostring(e4)) + local _, e5 = Iqm.encode({} :: any) + t:check(e5 and e5.code == Err.ARG, "encode junk") + local _, e6 = Iqm.encode(S.new()) + t:check(e6 and e6.code == Err.ARG, "encode an empty scene: " .. tostring(e6)) + t:eq(Iqm.sniff(Bytes.reader(buffer.fromstring(fixit.data))), 1, "sniff") +end + +-- ------------------------------------------------------------------------------------------------ fuzz +do + local small = assert(Iqm.encode(assert(Gltf.decode(Bytes.reader(buffer.fromstring(Picks[2].data)), { files = Picks[2].files })))) + local samples = { small, string.sub(fixit.data, 1, 20000) } + t:fuzz("decode", function(b: buffer) + local s = Iqm.decode(Bytes.reader(b)) + if s then + Iqm.encode(s) + end + return s + end, samples, { mutations = 24, keepHeader = 16 }) +end + +t:done() diff --git a/tools/fixtures/_iqm_encode.luau b/tools/fixtures/_iqm_encode.luau new file mode 100644 index 0000000..388e77f --- /dev/null +++ b/tools/fixtures/_iqm_encode.luau @@ -0,0 +1,38 @@ +-- tools/fixtures/_iqm_encode: run by tools/fixtures/iqm.py (luau CLI, repo root): writes mrfixit.iqm back through our +-- reader and writer, and every glTF pick through our writer, printing "\t" lines for assimp and the +-- Python IQM reader. Files: rt_mrfixit.iqm, gltf_.iqm. +local Iqm = require("@formats/model/iqm") +local Gltf = require("@formats/model/gltf") +local Bytes = require("@formats/core/Bytes") +local Cases = require("@tests/gen/iqm_cases") +local Picks = require("@tests/gen/iqm_gltf") + +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 _, c in Cases do + local scene = assert(Iqm.decode(Bytes.reader(buffer.fromstring(c.data)))) + print("rt_mrfixit.iqm\t" .. hex(assert(Iqm.encode(scene)))) +end +for _, p in Picks do + local scene, err = Gltf.decode(Bytes.reader(buffer.fromstring(p.data)), { files = p.files }) + if scene then + local out, e2 = Iqm.encode(scene) + if out then + print("gltf_" .. p.name .. ".iqm\t" .. hex(out)) + else + print("encode failed " .. p.name .. ": " .. tostring(e2)) + end + else + print("skipped " .. p.name .. ": " .. tostring(err)) + end +end diff --git a/tools/fixtures/_iqm_reference.py b/tools/fixtures/_iqm_reference.py new file mode 100644 index 0000000..b2525a6 --- /dev/null +++ b/tools/fixtures/_iqm_reference.py @@ -0,0 +1,113 @@ +# An independent IQM reader for tools/fixtures/iqm.py (plain Python, from the IQM SDK's format description and its +# demo's skinning: joint matrices = pose world * inverse bind world): header counts and the bounding box of the +# skinned vertices for every animation frame, computed from the joints, poses and frames (not from the file's bounds +# block, which it returns too for comparison). +import math, struct + +HEADER = ("version filesize flags num_text ofs_text num_meshes ofs_meshes num_vertexarrays num_vertexes ofs_vertexarrays " + "num_triangles ofs_triangles ofs_adjacency num_joints ofs_joints num_poses ofs_poses num_anims ofs_anims num_frames " + "num_framechannels ofs_frames ofs_bounds num_comment ofs_comment num_extensions ofs_extensions").split() +FMT = {0: ("b", 1), 1: ("B", 1), 2: ("h", 2), 3: ("H", 2), 4: ("i", 4), 5: ("I", 4), 7: ("f", 4), 8: ("d", 8)} + + +def mat(t, q, s): + x, y, z, w = q + n = math.sqrt(x * x + y * y + z * z + w * w) or 1 + x, y, z, w = x / n, y / n, z / n, w / n + r = [[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)], + [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)], + [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]] + return [[r[i][0] * s[0], r[i][1] * s[1], r[i][2] * s[2], t[i]] for i in range(3)] + [[0, 0, 0, 1]] + + +def mul(a, b): + return [[sum(a[i][k] * b[k][j] for k in range(4)) for j in range(4)] for i in range(4)] + + +def inv(m): + # general 4x4 inverse (Gauss-Jordan) + a = [row[:] + [1 if i == j else 0 for j in range(4)] for i, row in enumerate(m)] + for c in range(4): + p = max(range(c, 4), key=lambda r: abs(a[r][c])) + a[c], a[p] = a[p], a[c] + d = a[c][c] or 1e-30 + a[c] = [v / d for v in a[c]] + for r in range(4): + if r != c: + f = a[r][c] + a[r] = [v - f * w for v, w in zip(a[r], a[c])] + return [row[4:] for row in a] + + +def read(data): + h = dict(zip(HEADER, struct.unpack_from("<27I", data, 16))) + text = data[h["ofs_text"]:h["ofs_text"] + h["num_text"]] + + def s(o): + return text[o:text.index(b"\0", o)].decode("latin1") + arrays = {} + for i in range(h["num_vertexarrays"]): + typ, flags, fmt, size, ofs = struct.unpack_from("<5I", data, h["ofs_vertexarrays"] + i * 20) + c, n = FMT[fmt] + vals = struct.unpack_from("<%d%s" % (h["num_vertexes"] * size, c), data, ofs) + arrays[typ] = (fmt, size, vals) + joints = [] + for j in range(h["num_joints"]): + v = struct.unpack_from("= 0 else m) + invbind = [inv(m) for m in bind] + poses = [] + for p in range(h["num_poses"]): + v = struct.unpack_from("= 0 else m) + skin = [mul(world[j], invbind[j]) for j in range(len(world))] + lo, hi = [1e30] * 3, [-1e30] * 3 + for v in range(h["num_vertexes"]): + x, y, z = pos[v * 3:v * 3 + 3] + if bi and bw: + sx = sy = sz = 0.0 + tot = 0.0 + for c in range(4): + w = bw[2][v * 4 + c] / 255.0 if bw[0] == 1 else bw[2][v * 4 + c] + if w > 0: + m = skin[bi[2][v * 4 + c]] + sx += w * (m[0][0] * x + m[0][1] * y + m[0][2] * z + m[0][3]) + sy += w * (m[1][0] * x + m[1][1] * y + m[1][2] * z + m[1][3]) + sz += w * (m[2][0] * x + m[2][1] * y + m[2][2] * z + m[2][3]) + tot += w + if tot > 0: + x, y, z = sx, sy, sz + lo = [min(a, b) for a, b in zip(lo, (x, y, z))] + hi = [max(a, b) for a, b in zip(hi, (x, y, z))] + boxes.append({"min": lo, "max": hi}) + stored = [] + if h["ofs_bounds"]: + for f in range(h["num_frames"]): + v = struct.unpack_from("<8f", data, h["ofs_bounds"] + f * 32) + stored.append({"min": list(v[0:3]), "max": list(v[3:6])}) + return {"meshes": h["num_meshes"], "vertexes": h["num_vertexes"], "triangles": h["num_triangles"], "joints": h["num_joints"], + "jointNames": [j[0] for j in joints], "anims": anims, "frames": h["num_frames"], "skinned": boxes, "stored": stored} diff --git a/tools/fixtures/iqm.py b/tools/fixtures/iqm.py new file mode 100644 index 0000000..ae2559d --- /dev/null +++ b/tools/fixtures/iqm.py @@ -0,0 +1,57 @@ +# Inter-Quake Model fixtures (tools/fixtures.py): assimp's IQM test model (mrfixit.iqm, from the nixpkgs assimp +# source, never committed) with assimp's view of it (`assimp info -r`, PreTransformVertices bounds) and an independent +# Python reading (tools/fixtures/_iqm_reference.py: counts, and the bounds of the skinned vertices per frame computed +# from joints / poses / frames, next to the bounds block the IQM tool stored); glTF sample models (tests/fixtures/gltf) +# for the writer; then our encoder's output (tools/fixtures/_iqm_encode.luau) read back by assimp and the Python reader. +# tests/gen/iqm_cases.luau { name, data, assimp, ref } +# tests/gen/iqm_gltf.luau { name, data, files } +# tests/gen/iqm_xcheck.luau { name, assimp, ref } +import importlib.util, os + +INPUTS = ["src/Formats/model/iqm", "src/Formats/codecs/model", "tools/fixtures/_model_ref.py", "tools/fixtures/fbx.py", + "tools/fixtures/_iqm_reference.py", "tools/fixtures/_iqm_encode.luau", "tests/fixtures/gltf"] + + +def module(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def info(ctx, M, fbx, path, tmp): + a = M.assimp_info(ctx, [path], raw=True)[0] + for k in ("min", "max", "perMesh"): + a.pop(k, None) + if not a.get("failed"): + a.update(fbx.ptv_bounds(ctx, path, tmp)) + return a + + +def generate(ctx): + M = module(ctx, "_model_ref") + fbx = module(ctx, "fbx") + R = module(ctx, "_iqm_reference") + tmp = M.tempdir() + p = os.path.join(fbx.assimp_src(ctx), "test", "models", "IQM", "mrfixit.iqm") + data = open(p, "rb").read() + ctx.emit("iqm_cases", [{"name": "mrfixit.iqm", "data": data, "assimp": info(ctx, M, fbx, p, tmp), "ref": R.read(data)}]) + gl = os.path.join(ctx.root, "tests", "fixtures", "gltf") + picks = [] + for model in ("RiggedSimple", "SimpleSkin", "Box", "BoxTextured", "BoxVertexColors", "MeshPrimitiveModes", "SimpleMeshes"): + d0 = os.path.join(gl, model) + for variant in sorted(os.listdir(d0)) if os.path.isdir(d0) else []: + d = os.path.join(d0, variant) + mains = [f for f in sorted(os.listdir(d)) if f.endswith((".gltf", ".glb"))] if os.path.isdir(d) else [] + if mains: + picks.append({"name": model, "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("iqm_gltf", picks) + ours = M.luau_encode(ctx, "tools/fixtures/_iqm_encode.luau") + out = [] + for name in sorted(ours): + q = os.path.join(tmp, name) + open(q, "wb").write(ours[name]) + out.append({"name": name, "assimp": info(ctx, M, fbx, q, tmp), "ref": R.read(ours[name])}) + ctx.emit("iqm_xcheck", out) From 1d45c661082bf194aae38190ef01b01f0bbc5c92 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:41:36 -0500 Subject: [PATCH 7/8] ws-3d3-b: docs/guide/scene.md: LWO, .x and IQM (sections with tested snippets, Formats table, intro list) --- docs/guide/scene.md | 82 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 81 insertions(+), 1 deletion(-) diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 525643e..c714ee3 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -1,6 +1,6 @@ # Scene (3D models) and Voxels -Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX) loads as one `Scene`, a structure +Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, LightWave LWO, DirectX .x, IQM) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), PBR materials, textures, cameras, lights, skins and animations. Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`). Editing goes through `F.ops.mesh`. @@ -378,6 +378,83 @@ local vox = assert(F.save(grid, nil, { format = "vox" })) -- a grid alone saves assert(F.load(vox).voxels[1].size[1] == 4) ``` +## LightWave, DirectX and Inter-Quake models + +**LightWave objects** (`.lwo`: LWO2 and the older LWOB; Modo's `.lxo`) give one node per layer (its pivot as the +translation, parents by layer index), one mesh per layer and one primitive per surface. LightWave is left-handed: z is +negated and the winding reversed on load, so the scene is glTF's right-handed y up. UV maps become `TEXCOORD_n` (one +set per map name), the colour map a surface names becomes `COLOR_0`, weight maps `_WEIGHT_n` and morph maps morph +targets (names in `prim.extras.lwo.maps` / `mesh.extras.targetNames`). Surface values and texture blocks are in +`material.extras.lwo`; image textures keep only the file name as `uri` (`F.model.loadTextures` reads them). Subdivision +cages (`PTCH` / `SUBD`) stay polygons with `prim.extras.lwo.subdivision = true`. + +```luau +-- a one-triangle LWO2 file, built by hand (IFF chunks, big-endian) +local function be(n, bytes) + local s = "" + for i = bytes - 1, 0, -1 do + s ..= string.char(bit32.band(bit32.rshift(n, i * 8), 255)) + end + return s +end +local function f4(x) + local b = buffer.create(4) + buffer.writef32(b, 0, x) + return be(buffer.readu32(b, 0), 4) +end +local function chunk(id, body) + return id .. be(#body, 4) .. body +end +local body = "LWO2" .. chunk("TAGS", "Red\0") .. chunk("LAYR", be(0, 4) .. f4(0) .. f4(0) .. f4(0) .. "Body\0\0") + .. chunk("PNTS", f4(0) .. f4(0) .. f4(0) .. f4(1) .. f4(0) .. f4(0) .. f4(0) .. f4(1) .. f4(0)) + .. chunk("POLS", "FACE" .. be(3, 2) .. be(0, 2) .. be(1, 2) .. be(2, 2)) + .. chunk("PTAG", "SURF" .. be(0, 4)) + .. chunk("SURF", "Red\0\0\0" .. "COLR" .. be(14, 2) .. f4(1) .. f4(0) .. f4(0) .. be(0, 2)) +local scene = assert(F.load("FORM" .. be(#body, 4) .. body)) +assert(scene.nodes[1].name == "Body" and scene.meta.source.version == "LWO2") +assert(scene.materials[1].name == "Red" and scene.materials[1].baseColor[1] == 1) +assert(scene.meshes[1].primitives[1].indices.count == 3) +``` + +**DirectX `.x`** files (text, binary and MSZIP-compressed, 32- or 64-bit floats) give the frame hierarchy, one primitive +per material, materials with their texture file names, skins (`SkinWeights`) and animation sets. Direct3D is +left-handed too: z is negated and the winding reversed. Key times are in seconds (`AnimTicksPerSecond`, default 4800). + +```luau +local text = [[xof 0303txt 0032 +Material Wood { 0.8; 0.6; 0.4; 1.0;; 20.0; 0.1; 0.1; 0.1;; 0.0; 0.0; 0.0;; TextureFilename { "wood.png"; } } +Frame Root { + FrameTransformMatrix { 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,5,1;; } + Mesh Tri { 3; 0;0;0;, 1;0;0;, 0;1;0;; 1; 3;0,1,2;; MeshMaterialList { 1; 1; 0;; { Wood } } } +} +]] +local scene = assert(F.load(text, { format = "x" })) +local root = scene.nodes[1] +assert(root.name == "Root" and root.translation[3] == -5) -- z negated +assert(scene.materials[1].name == "Wood") +assert(scene.textures[scene.materials[1].baseColorTexture.texture].uri == "wood.png") +local glb = assert(F.save(scene, nil, { format = "glb" })) +``` + +**IQM** (Inter-Quake Model, version 2) reads and writes meshes, every vertex array, the skeleton (a node per joint and +one skin), animations (dequantized frames as translation / rotation / scale channels, loop flags and frame ranges in +`meta.source.animations`) and per-frame bounds. IQM is z-up (`meta.up = "z"`); nothing is rotated either way. The +writer turns any Scene's triangles into IQM meshes, merges the skins into one skeleton and samples each animation at +its key spacing when uniform (else `opts.framerate`, default 30 frames per second). + +```luau +local S = F.Types.Scene +local pos = S.accessor(nil, "f32", 3, 3) +for i, v in { 0, 0, 0, 1, 0, 0, 0, 1, 0 } do + buffer.writef32(pos.data, (i - 1) * 4, v) +end +local scene = S.fromPrimitive({ attributes = { POSITION = pos }, mode = "triangles" }, "tri") +local iqm = assert(F.save(scene, nil, { format = "iqm" })) +local back = assert(F.load(iqm)) +assert(back.meta.source.format == "iqm" and back.meshes[1].name == "tri") +assert(back.meshes[1].primitives[1].indices.count == 3) +``` + ## Formats | Format | Read | Write | Notes | @@ -392,6 +469,9 @@ assert(F.load(vox).voxels[1].size[1] == 4) | 3MF | yes | yes | | | USDA (+ USDZ read) | yes | yes | | | VOX | yes | yes | voxel grids, scene graph, materials | +| LightWave LWO (LWO2, LWOB, Modo LXOB) | yes | | layers, vertex maps, surfaces; see below | +| DirectX .x (text, binary, MSZIP) | yes | | frames, materials, skins, animation | +| IQM (Inter-Quake Model) | yes | yes | skeleton, skin, sampled animations, bounds | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | Capabilities per format: [FORMATS.md](../FORMATS.md). From 4b9d8e3069c0bc539fda2bebf949358f7c75346d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 15:01:09 -0500 Subject: [PATCH 8/8] ws-3d3-b: model/x: counts past the data are refused before allocating (TRUNCATED) --- src/Formats/model/x/Build.luau | 26 ++++++++++++++++++++------ tests/model/x.luau | 2 ++ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/src/Formats/model/x/Build.luau b/src/Formats/model/x/Build.luau index 2acb8f3..16d41e6 100644 --- a/src/Formats/model/x/Build.luau +++ b/src/Formats/model/x/Build.luau @@ -34,11 +34,25 @@ local function str(c: Vals): string end return x end +-- a non-negative integer (an index) +local function index(c: Vals, limit: number): number + local n = num(c) + if n < 0 or n ~= math.floor(n) or n > limit then + error("bad index " .. n, 0) + end + return n +end + +-- a count of items that follow (each takes at least one value: a count past the data is refused before anything +-- is allocated for it) local function count(c: Vals, limit: number): number local n = num(c) if n < 0 or n ~= math.floor(n) or n > limit then error("bad count " .. n, 0) end + if n > #c.v - c.i + 1 then + error("truncated: a count of " .. n .. " runs past the data", 0) + end return n end @@ -146,7 +160,7 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) end local face = table.create(n) :: { number } for k = 1, n do - local idx = count(c, 2 ^ 32) + local idx = index(c, 2 ^ 32) if idx >= nv then error("face index " .. idx .. " out of range", 0) end @@ -176,7 +190,7 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) local n = count(kc, ctx.maxVertices) local face = table.create(n) :: { number } for q = 1, n do - face[q] = count(kc, 2 ^ 32) + face[q] = index(kc, 2 ^ 32) end nfs[f] = face end @@ -194,7 +208,7 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) local n = count(kc, ctx.maxVertices) local col = table.create(nv * 4, 1) :: { number } for _ = 1, n do - local idx = count(kc, 2 ^ 32) + local idx = index(kc, 2 ^ 32) local r, g, b, a = num(kc), num(kc), num(kc), num(kc) if idx < nv then col[idx * 4 + 1], col[idx * 4 + 2], col[idx * 4 + 3], col[idx * 4 + 4] = r, g, b, a @@ -202,10 +216,10 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) end table.insert(colors, col) elseif k.type == "MeshMaterialList" then - count(kc, 2 ^ 20) -- material count (the objects below are authoritative) + num(kc) -- material count (the objects below are authoritative) local ni = count(kc, ctx.maxVertices) for q = 1, ni do - faceMat[q] = count(kc, 2 ^ 20) + faceMat[q] = index(kc, 2 ^ 20) end for _, mk in k.kids do if mk.type == "@ref" then @@ -220,7 +234,7 @@ local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?) local n = count(kc, ctx.maxVertices) local verts = table.create(n) :: { number } for q = 1, n do - verts[q] = count(kc, 2 ^ 32) + verts[q] = index(kc, 2 ^ 32) end local weights = table.create(n) :: { number } for q = 1, n do diff --git a/tests/model/x.luau b/tests/model/x.luau index 119cbdc..8cc3524 100644 --- a/tests/model/x.luau +++ b/tests/model/x.luau @@ -287,6 +287,8 @@ do t:check(e4 and e4.code == Err.CORRUPT, "face index out of range: " .. tostring(e4)) local _, e5 = decode("xof 0303txt 0032 Frame A { ") t:check(e5 and e5.code == Err.CORRUPT, "unterminated: " .. tostring(e5)) + local _, e7 = decode("xof 0303txt 0032 Mesh { 33554431; 1; }") + t:check(e7 and e7.code == Err.TRUNCATED, "a vertex count past the data is refused before allocating: " .. tostring(e7)) local _, e6 = decode(CUBE, { maxValues = 10 }) t:check(e6 and e6.code == Err.LIMIT, "maxValues: " .. tostring(e6)) t:eq(X.sniff(Bytes.reader(buffer.fromstring(CUBE))), 1, "sniff")