ws-game: model/md5 (Doom 3 md5mesh + md5anim: skeleton, weighted bind pose, skin, animations via opts.anims / resolve / files; standalone md5anim)

This commit is contained in:
4DBug committed 2026-10-31 14:52:15 -05:00
1 parent 08045ba813
commit 9b2b50fe75
6 files changed
+847

No files matched your search

+12
View File
@@ -434,6 +434,18 @@ local list: { Entry } = {
return require("@formats/model/md3")
end,
},
{
name = "md5",
category = "model",
path = "model/md5",
extensions = { "md5mesh", "md5anim" },
mime = { "model/x-md5mesh", "model/x-md5anim" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" },
caps = { decode = true, encode = false, skins = true, animation = true },
load = function()
return require("@formats/model/md5")
end,
},
{
name = "mdl",
category = "model",
+440
View File
@@ -0,0 +1,440 @@
--!strict
-- model/md5/Read: Doom 3 / Quake 4 MD5 text (MD5Version 10) to Scenes. md5mesh: joints (model-space bind pose:
-- position + unit quaternion with w = -sqrt(1 - x² - y² - z²)) -> joint nodes and a Skin, each mesh -> a primitive
-- (positions from the weights in the bind pose, normals computed, texture coordinates as stored, triangles reversed
-- to counter-clockwise, JOINTS_0 / WEIGHTS_0 from the weights), its shader -> a material / texture URI. md5anim:
-- hierarchy + baseframe (parent-relative) + frames of animated components -> translation / rotation channels at
-- frameRate, applied to the joint nodes of the same names. Written from the format notes of the Doom 3 modding
-- community (modwiki "MD5 (file format)", David Henry's "The MD5 Mesh and Animation Formats"); no code taken.
local Types = require("@formats/Types")
local Rig = require("@formats/codecs/model/Rig")
local Read = {}
local Scene = Types.Scene
local writef32, writeu32 = buffer.writef32, buffer.writeu32
export type Options = { maxVertices: number? }
-- ------------------------------------------------------------------------------------------------ tokens
type Lexer = { text: string, pos: number, err: string? }
local function token(L: Lexer): string?
local s = L.text
while true do
local a = string.find(s, "%S", L.pos)
if not a then
L.pos = #s + 1
return nil
end
if string.sub(s, a, a + 1) == "//" then
local nl = string.find(s, "\n", a, true)
L.pos = if nl then nl + 1 else #s + 1
else
L.pos = a
break
end
end
local c = string.sub(s, L.pos, L.pos)
if c == '"' then
local e = string.find(s, '"', L.pos + 1, true)
if not e then
L.err = "unterminated string"
L.pos = #s + 1
return nil
end
local v = string.sub(s, L.pos + 1, e - 1)
L.pos = e + 1
return '"' .. v
end
if c == "(" or c == ")" or c == "{" or c == "}" then
L.pos += 1
return c
end
local e = string.find(s, '[%s(){}"]', L.pos) or (#s + 1)
local v = string.sub(s, L.pos, e - 1)
L.pos = e
return v
end
local function num(L: Lexer): number
local t = token(L)
local v = t and tonumber(t)
if not v then
L.err = L.err or ("expected a number, got " .. tostring(t))
return 0
end
return v
end
local function str(L: Lexer): string
local t = token(L)
if not t or string.sub(t, 1, 1) ~= '"' then
L.err = L.err or ("expected a string, got " .. tostring(t))
return ""
end
return string.sub(t, 2)
end
local function expect(L: Lexer, want: string)
local t = token(L)
if t ~= want then
L.err = L.err or ("expected " .. want .. ", got " .. tostring(t))
end
end
local function vec(L: Lexer, n: number): { number }
expect(L, "(")
local v = table.create(n, 0)
for i = 1, n do
v[i] = num(L)
end
expect(L, ")")
return v
end
-- the unit quaternion from its x, y, z (w <= 0, as id's tools store it)
local function quat(x: number, y: number, z: number): { number }
local t = 1 - x * x - y * y - z * z
return { x, y, z, if t < 0 then 0 else -math.sqrt(t) }
end
local function rotate(q: { number }, vx: number, vy: number, vz: number): (number, number, number)
local qx, qy, qz, qw = q[1], q[2], q[3], q[4]
-- v + 2 w (q x v) + 2 q x (q x v)
local tx, ty, tz = 2 * (qy * vz - qz * vy), 2 * (qz * vx - qx * vz), 2 * (qx * vy - qy * vx)
return vx + qw * tx + (qy * tz - qz * ty), vy + qw * ty + (qz * tx - qx * tz), vz + qw * tz + (qx * ty - qy * tx)
end
-- ------------------------------------------------------------------------------------------------ md5mesh
type MeshJoint = { name: string, parent: number, pos: { number }, q: { number } }
-- mesh(text, opts) -> Scene, joint node indices by name | nil, message
function Read.mesh(text: string, opts: Options?): (Types.Scene?, any)
local L: Lexer = { text = text, pos = 1, err = nil }
local joints: { MeshJoint } = {}
local scene = Scene.new()
scene.meta.up = "z"
local root: Types.Node = { name = "md5", children = {} }
table.insert(scene.nodes, root)
scene.roots[1] = 1
local version: number? = nil
local mesh: Types.Mesh = { primitives = {} }
local maxV = opts and opts.maxVertices or 2 ^ 24
local total = 0
local skinIndex = 0
local nodes: { number } = {}
while not L.err do
local t = token(L)
if not t then
break
end
if t == "MD5Version" then
version = num(L)
elseif t == "commandline" then
str(L)
elseif t == "numJoints" or t == "numMeshes" then
num(L)
elseif t == "joints" then
expect(L, "{")
while not L.err do
local s = token(L)
if s == "}" then
break
end
if not s or string.sub(s, 1, 1) ~= '"' then
return nil, "bad joint line"
end
local parent = num(L)
local p, q = vec(L, 3), vec(L, 3)
table.insert(joints, { name = string.sub(s, 2), parent = parent + 1, pos = p, q = quat(q[1], q[2], q[3]) })
end
local list: { Rig.Joint } = {}
for i, j in joints do
list[i] = { name = j.name, parent = j.parent, translation = j.pos, rotation = j.q }
end
local n, si = Rig.skeleton(scene, list, "world", 1)
nodes, skinIndex = n, si
elseif t == "mesh" then
expect(L, "{")
local shader = ""
local verts: { { number } } = {} -- s, t, startWeight, countWeight
local tris: { number } = {}
local weights: { { number } } = {} -- joint, bias, x, y, z
while not L.err do
local k = token(L)
if k == "}" then
break
elseif k == "shader" then
shader = str(L)
elseif k == "numverts" or k == "numtris" or k == "numweights" then
local n = num(L)
total += if k == "numverts" then n else 0
if total > maxV then
return nil, "limit: too many vertices"
end
elseif k == "vert" then
local i = num(L)
local st = vec(L, 2)
verts[i + 1] = { st[1], st[2], num(L), num(L) }
elseif k == "tri" then
num(L)
local a, b, c = num(L), num(L), num(L)
table.insert(tris, c)
table.insert(tris, b)
table.insert(tris, a)
elseif k == "weight" then
local i = num(L)
local j, bias = num(L), num(L)
local p = vec(L, 3)
weights[i + 1] = { j, bias, p[1], p[2], p[3] }
else
return nil, "unknown mesh keyword " .. tostring(k)
end
end
local nv = #verts
local pos, uv = buffer.create(nv * 12), buffer.create(nv * 8)
local lists: { { number } } = {}
for vi = 1, nv do
local v = verts[vi]
if not v then
return nil, "missing vert " .. (vi - 1)
end
local x, y, z = 0, 0, 0
local l: { number } = {}
for w = v[3] + 1, v[3] + v[4] do
local wt = weights[w]
local j = wt and joints[wt[1] + 1]
if not wt or not j then
return nil, "vert " .. (vi - 1) .. ": bad weight " .. (w - 1)
end
local rx, ry, rz = rotate(j.q, wt[3], wt[4], wt[5])
x += (j.pos[1] + rx) * wt[2]
y += (j.pos[2] + ry) * wt[2]
z += (j.pos[3] + rz) * wt[2]
table.insert(l, wt[1])
table.insert(l, wt[2])
end
writef32(pos, (vi - 1) * 12, x)
writef32(pos, (vi - 1) * 12 + 4, y)
writef32(pos, (vi - 1) * 12 + 8, z)
writef32(uv, (vi - 1) * 8, v[1])
writef32(uv, (vi - 1) * 8 + 4, v[2])
lists[vi] = l
end
for _, ix in tris do
if ix < 0 or ix >= nv then
return nil, "triangle index out of range"
end
end
local ib = buffer.create(#tris * 4)
for i, ix in tris do
writeu32(ib, (i - 1) * 4, ix)
end
local attrs: { [string]: Types.Accessor } = {
POSITION = Scene.accessor(pos, "f32", 3, nv),
NORMAL = Scene.accessor(Rig.normals(pos, nv, tris), "f32", 3, nv),
TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv),
}
if #joints > 0 then
attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists)
end
local mat = Scene.material(shader)
mat.metallic = 0
table.insert(scene.textures, { name = shader, uri = shader })
mat.baseColorTexture = { texture = #scene.textures }
table.insert(scene.materials, mat)
table.insert(mesh.primitives, { attributes = attrs, indices = Scene.accessor(ib, "u32", 1, #tris), mode = "triangles" :: any, material = #scene.materials })
else
return nil, "unknown keyword " .. t
end
end
if L.err then
return nil, L.err
end
if version ~= 10 then
return nil, if version then "unsupported: MD5Version " .. version else "no MD5Version"
end
if #mesh.primitives > 0 then
table.insert(scene.meshes, mesh)
table.insert(scene.nodes, { name = "mesh", children = {}, mesh = #scene.meshes, skin = if #joints > 0 then skinIndex else nil })
table.insert(root.children, #scene.nodes)
end
local byName: { [string]: number } = {}
for i, j in joints do
byName[j.name] = nodes[i]
end
scene.meta.source = { format = "md5", kind = "mesh", joints = #joints, meshes = #mesh.primitives }
return scene, byName
end
-- ------------------------------------------------------------------------------------------------ md5anim
export type Anim = {
frameRate: number,
frames: number,
joints: { { name: string, parent: number } },
base: { { number } }, -- per joint: px py pz qx qy qz
tracks: { Rig.Track }, -- per joint: translation / rotation keys, one per frame
}
-- anim(text) -> Anim | nil, message
function Read.anim(text: string): (Anim?, string?)
local L: Lexer = { text = text, pos = 1, err = nil }
local a: Anim = { frameRate = 24, frames = 0, joints = {}, base = {}, tracks = {} }
local hier: { { number } } = {} -- flags, startIndex
local version: number? = nil
local nComp = 0
local frames: { { number } } = {}
while not L.err do
local t = token(L)
if not t then
break
end
if t == "MD5Version" then
version = num(L)
elseif t == "commandline" then
str(L)
elseif t == "numFrames" then
a.frames = num(L)
elseif t == "numJoints" then
num(L)
elseif t == "frameRate" then
a.frameRate = num(L)
elseif t == "numAnimatedComponents" then
nComp = num(L)
if nComp < 0 or nComp > 2 ^ 20 then
return nil, "bad numAnimatedComponents"
end
elseif t == "hierarchy" then
expect(L, "{")
while not L.err do
local s = token(L)
if s == "}" then
break
end
if not s or string.sub(s, 1, 1) ~= '"' then
return nil, "bad hierarchy line"
end
local parent, flags, start = num(L), num(L), num(L)
table.insert(a.joints, { name = string.sub(s, 2), parent = parent + 1 })
table.insert(hier, { flags, start })
end
elseif t == "bounds" then
expect(L, "{")
while not L.err do
local s = token(L)
if s == "}" or s == nil then
break
end
end
elseif t == "baseframe" then
expect(L, "{")
while not L.err do
local s = token(L)
if s == "}" then
break
end
if s ~= "(" then
return nil, "bad baseframe line"
end
L.pos -= 1
local p, q = vec(L, 3), vec(L, 3)
table.insert(a.base, { p[1], p[2], p[3], q[1], q[2], q[3] })
end
elseif t == "frame" then
local fi = num(L)
expect(L, "{")
local vals = table.create(nComp, 0)
for k = 1, nComp do
vals[k] = num(L)
end
expect(L, "}")
if fi < 0 or fi > 2 ^ 20 then
return nil, "bad frame index"
end
frames[fi + 1] = vals
else
return nil, "unknown keyword " .. t
end
end
if L.err then
return nil, L.err
end
if version ~= 10 then
return nil, if version then "unsupported: MD5Version " .. version else "no MD5Version"
end
if #a.base ~= #a.joints then
return nil, "baseframe and hierarchy disagree"
end
for f = 1, a.frames do
if not frames[f] then
return nil, "missing frame " .. (f - 1)
end
end
for j, h in hier do
local tr: { number }, rot: { number } = {}, {}
local flags, start = h[1], h[2]
for f = 1, a.frames do
local v = table.clone(a.base[j])
local k = start + 1
for bit = 0, 5 do
if bit32.band(flags, bit32.lshift(1, bit)) ~= 0 then
v[bit + 1] = frames[f][k] or v[bit + 1]
k += 1
end
end
table.insert(tr, v[1])
table.insert(tr, v[2])
table.insert(tr, v[3])
local q = quat(v[4], v[5], v[6])
for c = 1, 4 do
table.insert(rot, q[c])
end
end
a.tracks[j] = { translation = tr, rotation = rot }
end
return a, nil
end
-- addAnim(scene, nodes by joint name, anim, name) -> channels added
function Read.addAnim(scene: Types.Scene, byName: { [string]: number }, a: Anim, name: string): number
local nodes: { number } = {}
local tracks: { [number]: Rig.Track } = {}
for j, jt in a.joints do
local nd = byName[jt.name]
if nd then
table.insert(nodes, nd)
tracks[#nodes] = a.tracks[j]
end
end
local times: { number } = {}
local rate = if a.frameRate > 0 then a.frameRate else 24
for f = 1, a.frames do
times[f] = (f - 1) / rate
end
local ai = Rig.animation(scene, name, nodes, times, tracks, "LINEAR")
return #scene.animations[ai].channels
end
-- animScene(a, name) -> a Scene of the animation's skeleton (baseframe pose) with the animation
function Read.animScene(a: Anim, name: string): Types.Scene
local scene = Scene.new()
scene.meta.up = "z"
table.insert(scene.nodes, { name = "md5", children = {} })
scene.roots[1] = 1
local list: { Rig.Joint } = {}
for j, jt in a.joints do
local b = a.base[j]
list[j] = { name = jt.name, parent = jt.parent, translation = { b[1], b[2], b[3] }, rotation = quat(b[4], b[5], b[6]) }
end
local nodes = Rig.skeleton(scene, list, "local", 1)
local byName: { [string]: number } = {}
for j, jt in a.joints do
byName[jt.name] = nodes[j]
end
Read.addAnim(scene, byName, a, name)
scene.meta.source = { format = "md5", kind = "anim", joints = #a.joints, frames = a.frames, frameRate = a.frameRate }
return scene
end
return Read
+96
View File
@@ -0,0 +1,96 @@
--!strict
-- model/md5: Doom 3 / Quake 4 MD5 models (MD5Version 10 text): .md5mesh (skeleton, skin, meshes) and .md5anim
-- (skeletal animation), read into a Scene through model/md5/Read. A .md5mesh loads its animations from
-- opts.anims = { "idle.md5anim", ... } (each found through opts.files[name] or opts.resolve(name); joints matched by
-- name; the animation is named after the file without its extension); a missing one fails with UNSUPPORTED unless
-- opts.skipMissing. A .md5anim alone loads as its skeleton (baseframe pose) with the animation. Units are Doom
-- units, z up. Not supported: writing, .md5camera.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Sniff = require("@formats/core/Sniff")
local Types = require("@formats/Types")
local Read = require("@formats/model/md5/Read")
-- ------------------------------------------------------------------------------------------------ contract
local Md5 = {
name = "md5",
category = "model",
extensions = { "md5mesh", "md5anim" },
mime = { "model/x-md5mesh", "model/x-md5anim" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" },
caps = { decode = true, encode = false, skins = true, animation = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
anims: { string }?, -- .md5anim files to load with a .md5mesh
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
skipMissing: boolean?, -- ignore animations that cannot be found (default false: UNSUPPORTED)
name: string?, -- the file name (names a standalone animation)
maxVertices: number?, -- default 2^24
}
-- ------------------------------------------------------------------------------------------------ sniff
function Md5.sniff(r: Bytes.Reader): number
local head = Sniff.text(r, 512, true)
head = string.gsub(head, "^//[^\n]*\n%s*", "")
return if string.match(head, "^MD5Version%s+%d+") then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function fetch(opts: DecodeOptions, uri: string): string?
local v: any = nil
if type(opts.files) == "table" then
v = opts.files[uri]
end
if v == nil and type(opts.resolve) == "function" then
local ok, got = pcall(opts.resolve, uri)
v = if ok then got else nil
end
if type(v) == "buffer" then
return buffer.tostring(v)
end
return if type(v) == "string" then v else nil
end
local function stem(name: string): string
local base = string.match(name, "([^/\\]+)$") or name
return (string.gsub(base, "%.[^.]*$", ""))
end
function Md5.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local text = Sniff.dropBom(r:string(r:remaining()))
if string.find(text, "numAnimatedComponents", 1, true) then
local a, msg = Read.anim(text)
if not a then
return nil, Err.from(msg)
end
return Read.animScene(a, if opts and type(opts.name) == "string" then stem(opts.name) else "animation"), nil
end
local scene, byName = Read.mesh(text, opts :: any)
if not scene then
return nil, Err.from(byName)
end
if opts and type(opts.anims) == "table" then
for _, name in opts.anims do
local src = if type(name) == "string" then fetch(opts, name) else nil
if not src then
if not opts.skipMissing then
return nil, Err.new(Err.UNSUPPORTED, "animation " .. tostring(name) .. " not available (opts.resolve / opts.files)")
end
else
local a, msg = Read.anim(Sniff.dropBom(src))
if not a then
return nil, Err.from("animation " .. name .. ": " .. tostring(msg))
end
Read.addAnim(scene, byName, a, stem(name))
end
end
end
return scene, nil
end
return Md5