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()