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
@@ -54,6 +54,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` |
|
||||
@@ -127,6 +128,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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("<II", out, 4, dirofs, dirlen)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def read(data):
|
||||
magic, dirofs, dirlen = struct.unpack_from("<4sII", data)
|
||||
nl = {b"PACK": 56, b"SPAK": 120}[magic]
|
||||
out = []
|
||||
for i in range(dirlen // (nl + 8)):
|
||||
name, at, n = struct.unpack_from("<%dsII" % nl, data, dirofs + i * (nl + 8))
|
||||
out.append({"name": name.split(b"\0")[0].decode(), "size": n, "crc": zlib.crc32(data[at:at + n])})
|
||||
return out
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(17)
|
||||
base = [
|
||||
("gfx/palette.lmp", bytes(rng.randrange(256) for _ in range(768))),
|
||||
("maps/start.bsp", rng.randbytes(5000)),
|
||||
("sound/misc/null.wav", b""),
|
||||
("progs/player.mdl", rng.randbytes(1234)),
|
||||
("default.cfg", b"bind w +forward\n"),
|
||||
("a" * 55, b"longest quake name"),
|
||||
]
|
||||
cases = [
|
||||
("quake", "quake", write(base), base),
|
||||
("quake-dir-first", "quake", write(base, dir_first=True, pad=3), base),
|
||||
("empty", "quake", write([]), []),
|
||||
("sin", "sin", write(base + [("models/" + "b" * 100 + ".def", b"sin")], "sin"), base + [("models/" + "b" * 100 + ".def", b"sin")]),
|
||||
]
|
||||
out = []
|
||||
for name, variant, data, files in cases:
|
||||
out.append({"name": name, "variant": variant, "data": data, "entries": read(data),
|
||||
"layoutDefault": not name.endswith("dir-first"),
|
||||
"files": [{"name": n, "data": d} for n, d in files]})
|
||||
ctx.emit("pak", out)
|
||||
Reference in new issue
Block a user