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

+1
View File
@@ -40,6 +40,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| 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 | md2 | .md2 | yes | - | morph: true, animation: true | `tests/model/md2.luau` |
| model | md3 | .md3 | yes | - | morph: true, animation: true, tags: true | `tests/model/md3.luau` |
| model | md5 | .md5mesh .md5anim | yes | - | skins: true, animation: true | `tests/model/md5.luau` |
| model | mdl | .mdl | yes | - | variants: "quake", "halflife", morph: true, skins: true, animation: true | `tests/model/mdl.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` |
+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
+153
View File
@@ -0,0 +1,153 @@
-- model/md5 tests: an .md5mesh and two .md5anim files written by tools/fixtures/md5.py: the bind pose against
-- assimp's triangle soup (positions, texture coordinates) and the writer's exact weighted positions, the joints'
-- model-space pose through the node tree, weights, animations through opts.files / opts.resolve (every frame's
-- parent-relative pose), a standalone .md5anim, missing animations, errors, the fuzz pass.
local T = require("@tests/T")
local F = require("@formats")
local Md5 = require("@formats/model/md5")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Soup = require("@tests/model/_soup")
local Fx = require("@tests/gen/md5")
local t = T.suite("md5")
t:eq(Md5.name, "md5", "name")
local function near(a: { number }, b: { number }, tol: number): boolean
for i = 1, #b do
if math.abs(a[i] - b[i]) > tol * math.max(1, math.abs(b[i])) then
return false
end
end
return true
end
local function sameQ(a: { number }, b: { number }): boolean
return near(a, b, 1e-5) or near(a, { -b[1], -b[2], -b[3], -b[4] }, 1e-5)
end
local M = Fx.mesh
local files = {}
for _, a in Fx.anims do
files[a.name .. ".md5anim"] = a.data
end
local s, err = Md5.decode(Bytes.reader(buffer.fromstring(M.data)), { anims = { "idle.md5anim", "walk.md5anim" }, files = files })
t:check(s, "md5mesh: " .. tostring(err))
t:eq(F.detect(M.data), "md5", "F.detect")
-- 1. geometry
do
local prims = s.meshes[1].primitives
t:eq(#prims, #M.positions, "a primitive per mesh")
for i, p in prims do
local pos = Soup.list(p.attributes.POSITION.data)
t:check(near(pos, M.positions[i], 1e-5), "mesh " .. i .. ": weighted positions exact")
t:eq(p.indices.count, M.tris[i] * 3, "mesh " .. i .. ": triangles")
t:check(near(Soup.list(p.attributes.TEXCOORD_0.data), M.uvs[i], 1e-6), "mesh " .. i .. ": texture coordinates")
t:eq(s.textures[s.materials[p.material].baseColorTexture.texture].uri, "models/test/skin" .. (i - 1), "mesh " .. i .. ": shader")
end
local matched = 0
for mi, m in M.assimp.per do
local nextStart = if M.assimp.per[mi + 1] then M.assimp.per[mi + 1].start else M.assimp.faces
local nf = nextStart - m.start
local apos = Soup.slice(M.assimp.pos, m.start * 9 + 1, nf * 9)
local auv = Soup.slice(M.assimp.uv, m.start * 6 + 1, nf * 6)
for _, p in prims do
if p.indices.count == nf * 3 and Soup.triangles(Soup.list(Soup.positions(p)), apos, 1e-4) then
t:check(Soup.triangles(Soup.uvs(p, 0, true), auv, 1e-5, 2), "texture coordinates against assimp")
matched += 1
break
end
end
end
t:eq(matched, #M.positions, "every mesh matches assimp's bind pose")
end
-- 2. skeleton: the model-space joint poses through the node tree
do
local skin = s.skins[1]
t:eq(#skin.joints, #M.joints, "joints")
local parent = {}
for ni, nd in s.nodes do
for _, c in nd.children do
parent[c] = ni
end
end
local function world(ni: number): { number }
local m = Types.Scene.nodeMatrix(s.nodes[ni])
local p = parent[ni]
return if p then Types.Scene.mul(world(p), m) else m
end
for i, j in M.joints do
local nd = skin.joints[i]
t:eq(s.nodes[nd].name, j.name, "joint name " .. i)
local w = world(nd)
t:check(near({ w[13], w[14], w[15] }, j.pos, 1e-4), "joint " .. j.name .. " model-space position")
end
t:check(s.meshes[1].primitives[1].attributes.JOINTS_0 ~= nil, "skinned")
end
-- 3. animations
local function checkAnim(scene: any, a: any, anim: any, label: string)
t:eq(anim.name, a.name, label .. ": name")
local byNode = {}
for _, ch in anim.channels do
byNode[ch.node .. ch.path] = ch
end
local skin = scene.skins[1]
local ok = true
for f, pose in a.poses do
for ji, jp in pose do
local nd = skin.joints[ji]
local tr, rot = byNode[nd .. "translation"], byNode[nd .. "rotation"]
local tv, qv = {}, {}
for k = 1, 3 do
tv[k] = buffer.readf32(tr.output.data, ((f - 1) * 3 + k - 1) * 4)
end
for k = 1, 4 do
qv[k] = buffer.readf32(rot.output.data, ((f - 1) * 4 + k - 1) * 4)
end
ok = ok and near(tv, jp.t, 1e-5) and sameQ(qv, jp.q)
end
end
t:check(ok, label .. ": every frame's pose")
t:eq(anim.channels[1].input.count, a.frames, label .. ": keys")
t:check(math.abs(buffer.readf32(anim.channels[1].input.data, 4) - 1 / a.rate) < 1e-6, label .. ": frame rate")
end
t:eq(#s.animations, 2, "two animations")
for i, a in Fx.anims do
checkAnim(s, a, s.animations[i], "mesh + " .. a.name)
end
do
local asked = {}
local r = Md5.decode(Bytes.reader(buffer.fromstring(M.data)), {
anims = { "walk.md5anim" },
resolve = function(name: string): string?
table.insert(asked, name)
return files[name]
end,
}) :: any
t:check(r and #r.animations == 1 and asked[1] == "walk.md5anim", "opts.resolve")
local _, e = Md5.decode(Bytes.reader(buffer.fromstring(M.data)), { anims = { "run.md5anim" } })
t:check(e and e.code == Err.UNSUPPORTED, "missing animation")
local skip = Md5.decode(Bytes.reader(buffer.fromstring(M.data)), { anims = { "run.md5anim" }, skipMissing = true }) :: any
t:check(skip and #skip.animations == 0, "skipMissing")
-- a standalone .md5anim
local a = Fx.anims[2]
local alone = Md5.decode(Bytes.reader(buffer.fromstring(a.data)), { name = "models/walk.md5anim" }) :: any
t:check(alone and #alone.skins == 1, "md5anim alone: skeleton")
checkAnim(alone, a, alone.animations[1], "md5anim alone")
t:eq(alone.meta.source.kind, "anim", "md5anim alone: kind")
end
-- 4. errors, fuzz
do
local _, e1 = Md5.decode(Bytes.reader(buffer.fromstring("MD5Version 11\n")))
t:check(e1 and e1.code == Err.UNSUPPORTED, "version 11")
local _, e2 = Md5.decode(Bytes.reader(buffer.fromstring(string.sub(M.data, 1, 900))))
t:check(e2 ~= nil, "truncated: " .. tostring(e2))
end
t:fuzz("decode", function(b: buffer)
return Md5.decode(Bytes.reader(b), { anims = { "idle.md5anim" }, files = files })
end, { M.data, Fx.anims[1].data }, { mutations = 80 })
t:done()
+145
View File
@@ -0,0 +1,145 @@
# Doom 3 MD5 fixtures (tools/fixtures.py): an .md5mesh (random joint hierarchy in model space, two meshes whose
# vertices hang off 1-3 weights) and two .md5anim files (animated component flags, baseframe, frames) written here
# from the format notes; references: assimp's triangle soup of the bind pose (positions, texture coordinates) and
# this writer's own values (bind positions from the weights, joints, every frame's parent-relative pose).
# tests/gen/md5.luau { mesh = { data, joints, positions = { per mesh: { x, y, z, ... } }, tris, assimp },
# anims = { { name, data, frames, rate, poses = { [frame] = { [joint] = { t, q } } } } } }
import importlib.util, math, os, random
INPUTS = ["tools/fixtures/_quake_ref.py"]
def ref(ctx):
spec = importlib.util.spec_from_file_location("_quake_ref", os.path.join(ctx.root, "tools", "fixtures", "_quake_ref.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def r6(v):
return float("%.6f" % v)
def quat_w(x, y, z):
t = 1 - x * x - y * y - z * z
return 0.0 if t < 0 else -math.sqrt(t)
def rand_q(rng):
# a random unit quaternion with w <= 0 (stored as x, y, z)
while True:
q = [rng.uniform(-1, 1) for _ in range(4)]
n = math.sqrt(sum(c * c for c in q))
if n > 0.1:
q = [c / n for c in q]
if q[3] > 0:
q = [-c for c in q]
return [r6(q[0]), r6(q[1]), r6(q[2])]
def rotate(q, v):
qx, qy, qz, qw = q
vx, vy, vz = v
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))
def mesh(rng, njoints=5):
joints = []
lines = ["MD5Version 10", 'commandline "written by tools/fixtures/md5.py"', "", "numJoints %d" % njoints, "numMeshes 2", "", "joints {"]
for i in range(njoints):
parent = -1 if i == 0 else rng.randrange(i)
p = [r6(rng.uniform(-30, 30)) for _ in range(3)]
q = rand_q(rng)
joints.append({"name": "joint%d" % i, "parent": parent + 1, "pos": p, "q": q + [quat_w(*q)]})
lines.append('\t"joint%d"\t%d ( %s ) ( %s )\t\t// comment' % (i, parent, " ".join("%.6f" % c for c in p), " ".join("%.6f" % c for c in q)))
lines.append("}")
positions, tris_all, uvs = [], [], []
for m in range(2):
nverts, ntris = 8 + m * 4, 6 + m * 2
verts, weights = [], []
for v in range(nverts):
k = rng.randrange(1, 4)
ws = [rng.uniform(0.2, 1) for _ in range(k)]
s = sum(ws)
ws = [r6(w / s) for w in ws]
start = len(weights)
for j, w in zip(rng.sample(range(njoints), k), ws): # distinct joints per vertex (assimp 6 crashes on repeats)
weights.append((j, w, [r6(rng.uniform(-5, 5)) for _ in range(3)]))
verts.append(([r6(rng.random()), r6(rng.random())], start, k))
# every vertex in some triangle (assimp 6's MD5 loader corrupts memory on unused vertices)
order = list(range(nverts))
rng.shuffle(order)
tris = [(order[i % nverts], order[(i + 1) % nverts], order[(i + 2) % nverts]) for i in range(0, nverts, 3)]
tris += [tuple(rng.sample(range(nverts), 3)) for _ in range(ntris - len(tris))]
lines += ["", "mesh {", '\tshader "models/test/skin%d"' % m, "", "\tnumverts %d" % nverts]
for i, (st, start, k) in enumerate(verts):
lines.append("\tvert %d ( %.6f %.6f ) %d %d" % (i, st[0], st[1], start, k))
lines.append("\n\tnumtris %d" % ntris)
for i, t in enumerate(tris):
lines.append("\ttri %d %d %d %d" % (i, *t))
lines.append("\n\tnumweights %d" % len(weights))
for i, (j, b, p) in enumerate(weights):
lines.append("\tweight %d %d %.6f ( %s )" % (i, j, b, " ".join("%.6f" % c for c in p)))
lines.append("}")
pos = []
for st, start, k in verts:
acc = [0.0, 0.0, 0.0]
for j, b, p in weights[start:start + k]:
jt = joints[j]
r = rotate(jt["q"], p)
for c in range(3):
acc[c] += (jt["pos"][c] + r[c]) * b
pos += acc
positions.append(pos)
tris_all.append(len(tris))
uvs.append([c for st, s, k in verts for c in st])
return "\n".join(lines) + "\n", {"joints": joints, "positions": positions, "tris": tris_all, "uvs": uvs}
def anim(rng, joints, nframes, rate, name):
nj = len(joints)
flags = [rng.randrange(64) for _ in range(nj)]
base = [[r6(rng.uniform(-10, 10)) for _ in range(3)] + rand_q(rng) for _ in range(nj)]
starts, n = [], 0
for f in flags:
starts.append(n)
n += bin(f).count("1")
lines = ["MD5Version 10", 'commandline ""', "", "numFrames %d" % nframes, "numJoints %d" % nj, "frameRate %d" % rate, "numAnimatedComponents %d" % n, "", "hierarchy {"]
for i, j in enumerate(joints):
lines.append('\t"%s"\t%d %d %d' % (j["name"], j["parent"] - 1, flags[i], starts[i]))
lines += ["}", "", "bounds {"] + ["\t( -1 -1 -1 ) ( 1 1 1 )"] * nframes + ["}", "", "baseframe {"]
for b in base:
lines.append("\t( %s ) ( %s )" % (" ".join("%.6f" % c for c in b[:3]), " ".join("%.6f" % c for c in b[3:])))
lines.append("}")
poses = []
for f in range(nframes):
vals, pose = [], []
for i in range(nj):
v = list(base[i])
for bit in range(6):
if flags[i] & (1 << bit):
if bit < 3:
x = r6(rng.uniform(-10, 10))
else:
x = r6(rng.uniform(-0.5, 0.5))
v[bit] = x
vals.append(x)
pose.append({"t": v[:3], "q": v[3:] + [quat_w(*v[3:])]})
poses.append(pose)
lines += ["", "frame %d {" % f, "\t" + " ".join("%.6f" % x for x in vals), "}"]
return "\n".join(lines) + "\n", {"name": name, "frames": nframes, "rate": rate, "poses": poses}
def generate(ctx):
rng = ctx.rng(97)
R = ref(ctx)
text, info = mesh(rng)
data = text.encode()
info.update({"data": data, "assimp": R.assimp_soup(ctx, data, "md5mesh")})
anims = []
for name, nf, rate in (("idle", 4, 24), ("walk", 7, 30)):
t, a = anim(rng, info["joints"], nf, rate, name)
a["data"] = t.encode()
anims.append(a)
ctx.emit("md5", {"mesh": info, "anims": anims})