merge ws/game af4488d (codecs/model/Rig) for the IQM / X skins and animations
This commit is contained in:
commit
29be8113b4
9 files changed
+667
No files matched your search
@@ -602,6 +602,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",
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user