diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 5edd33d..0949122 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -38,6 +38,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | | 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 | 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` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 482b6aa..5309578 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -410,6 +410,18 @@ local list: { Entry } = { return require("@formats/model/gltf") end, }, + { + name = "md2", + category = "model", + path = "model/md2", + extensions = { "md2" }, + mime = { "model/x-md2" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true }, + load = function() + return require("@formats/model/md2") + end, + }, { name = "obj", category = "model", diff --git a/src/Formats/codecs/model/Rig.luau b/src/Formats/codecs/model/Rig.luau index 53bf256..89bd35f 100644 --- a/src/Formats/codecs/model/Rig.luau +++ b/src/Formats/codecs/model/Rig.luau @@ -101,6 +101,39 @@ function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, r end end +-- normals(pos, count, indices) -> f32 x3 buffer: smooth vertex normals (area-weighted face normals, normalised) of a +-- triangle list (indices: 0-based, three per triangle; out-of-range triangles are skipped). For formats whose stored +-- normals cannot be used (Quake's precomputed normal table is not redistributable here). +function Rig.normals(pos: buffer, count: number, indices: { number }): buffer + local out = buffer.create(count * 12) + local acc = table.create(count * 3, 0) + for k = 1, #indices - 2, 3 do + local a, b, c = indices[k], indices[k + 1], indices[k + 2] + if a >= 0 and b >= 0 and c >= 0 and a < count and b < count and c < count then + local ax, ay, az = readf32(pos, a * 12), readf32(pos, a * 12 + 4), readf32(pos, a * 12 + 8) + local ux, uy, uz = readf32(pos, b * 12) - ax, readf32(pos, b * 12 + 4) - ay, readf32(pos, b * 12 + 8) - az + local vx, vy, vz = readf32(pos, c * 12) - ax, readf32(pos, c * 12 + 4) - ay, readf32(pos, c * 12 + 8) - az + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + for _, v in { a, b, c } do + acc[v * 3 + 1] += nx + acc[v * 3 + 2] += ny + acc[v * 3 + 3] += nz + end + end + end + for v = 0, count - 1 do + local x, y, z = acc[v * 3 + 1], acc[v * 3 + 2], acc[v * 3 + 3] + local l = math.sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + writef32(out, v * 12, x) + writef32(out, v * 12 + 4, y) + writef32(out, v * 12 + 8, z) + end + return out +end + -- ------------------------------------------------------------------------------------------------ skeletons local function trs(j: Joint): { number } return Mat4.compose(j.translation, j.rotation, j.scale) diff --git a/src/Formats/model/md2/init.luau b/src/Formats/model/md2/init.luau new file mode 100644 index 0000000..cc241fb --- /dev/null +++ b/src/Formats/model/md2/init.luau @@ -0,0 +1,209 @@ +--!strict +-- model/md2: Quake II MD2 models ("IDP2" version 8), read into a Scene. Written from the MD2 format description in the +-- Quake II source release (qfiles.h: dmdl_t) and the "MD2 file format" notes (David Henry); no code taken. +-- Decode: one primitive: the triangles (welded on (vertex, texture coordinate) pairs; MD2 front faces are clockwise, +-- the indices are reversed to counter-clockwise as glTF wants), POSITION of frame opts.frame (default 1), +-- TEXCOORD_0 = s / skinwidth, t / skinheight (top-left origin), NORMAL computed from the geometry (the stored +-- indexes into Quake's normal table are kept as meta.source.normalIndexes = false: that table is not +-- redistributable here); every frame as a morph target (codecs/model/Rig: weight k = 1 shows frame k) and one +-- animation per frame-name group ("run1".."run6" -> "run", 10 frames per second, LINEAR); the skins as texture +-- URIs (the first is the material's base colour texture; mesh.extras.skins lists all). Units are Quake units, z up. +-- meta.source = { format, frames, frameNames, skinWidth, skinHeight }. +-- Not supported: the GL command list (the triangles carry the same geometry), writing. + +-- ------------------------------------------------------------------------------------------------ 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 Rig = require("@formats/codecs/model/Rig") + +-- ------------------------------------------------------------------------------------------------ contract +local Md2 = { + name = "md2", + category = "model", + extensions = { "md2" }, + mime = { "model/x-md2" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" }, + caps = { decode = true, encode = false, morph = true, animation = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + frame: number?, -- the frame used as the base POSITION (1-based, default 1) + morph: boolean?, -- every frame as a morph target + the animations (default true) + fps: number?, -- animation frame rate (default 10) + maxVertices: number?, -- frames x vertices (default 2^24) +} + +-- ------------------------------------------------------------------------------------------------ constants +local Scene = Types.Scene +local readu8, readu16, readi16, readf32, writef32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readf32, buffer.writef32, buffer.writeu32 + +-- ------------------------------------------------------------------------------------------------ sniff +function Md2.sniff(r: Bytes.Reader): number + if r:remaining() < 68 then + return 0 + end + return if Sniff.magic(r, "IDP2") == 1 and r:peekU8(4) == 8 then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- group frame names by their name without trailing digits, in file order +local function groups(names: { string }, fps: number): { Rig.Range } + local out: { Rig.Range } = {} + for i, n in names do + local stem = string.match(n, "^(.-)_?%d*$") or n + if stem == "" then + stem = n + end + local last = out[#out] + if last and last.name == stem and last.last == i - 1 then + last.last = i + else + table.insert(out, { name = stem, first = i, last = i, fps = fps }) + end + end + return out +end + +function Md2.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local size = r.limit - r.base + if not r:match("IDP2") then + return nil, Err.new(if size < 4 then Err.TRUNCATED else Err.CORRUPT, "bad magic", 0) + end + local h: { number } = {} + for i = 1, 16 do + h[i] = r:i32le() + end + if r.err then + return nil, r.err + end + local version, sw, sh, frameSize, nSkins, nXyz, nSt, nTris, _, nFrames, oSkins, oSt, oTris, oFrames = table.unpack(h, 1, 14) + if version ~= 8 then + return nil, Err.new(Err.UNSUPPORTED, "MD2 version " .. version, 4) + end + if nSkins < 0 or nXyz <= 0 or nSt < 0 or nTris < 0 or nFrames <= 0 or sw < 0 or sh < 0 then + return nil, Err.new(Err.CORRUPT, "bad counts", 8) + end + if nFrames * nXyz > (opts and opts.maxVertices or 2 ^ 24) then + return nil, Err.new(Err.LIMIT, "too many vertices") + end + local function inside(o: number, n: number): boolean + return o >= 0 and n >= 0 and o + n <= size + end + if not (inside(oSkins, nSkins * 64) and inside(oSt, nSt * 4) and inside(oTris, nTris * 12) and inside(oFrames, nFrames * frameSize)) then + return nil, Err.new(Err.TRUNCATED, "a section runs past the end", 44) + end + if frameSize < 40 + nXyz * 4 then + return nil, Err.new(Err.CORRUPT, "frame size too small", 16) + end + local b, base = r.buf, r.base + -- skins + local skins: { string } = {} + for i = 0, nSkins - 1 do + local s = buffer.readstring(b, base + oSkins + i * 64, 64) + table.insert(skins, (string.match(s, "^[^%z]*")) :: string) + end + -- weld (xyz, st) pairs + local key: { [number]: number } = {} + local vx: { number }, vst: { number } = {}, {} + local indices: { number } = {} + for t = 0, nTris - 1 do + local o = base + oTris + t * 12 + local corner: { number } = {} + for c = 0, 2 do + local xi, si = readu16(b, o + c * 2), readu16(b, o + 6 + c * 2) + if xi >= nXyz or (nSt > 0 and si >= nSt) then + return nil, Err.new(Err.CORRUPT, "triangle " .. t .. " index out of range", oTris + t * 12) + end + local k = xi * 65536 + si + local v = key[k] + if not v then + table.insert(vx, xi) + table.insert(vst, si) + v = #vx - 1 + key[k] = v + end + corner[c + 1] = v + end + table.insert(indices, corner[3]) + table.insert(indices, corner[2]) + table.insert(indices, corner[1]) + end + local nv = #vx + local uv = buffer.create(nv * 8) + for i = 1, nv do + if nSt > 0 then + local o = base + oSt + vst[i] * 4 + writef32(uv, (i - 1) * 8, readi16(b, o) / math.max(sw, 1)) + writef32(uv, (i - 1) * 8 + 4, readi16(b, o + 2) / math.max(sh, 1)) + end + end + -- frames + local frames: { buffer } = {} + local normals: { buffer } = {} + local names: { string } = {} + local morph = not (opts and opts.morph == false) + local want = math.clamp(math.floor(opts and opts.frame or 1), 1, nFrames) + for f = 1, nFrames do + if morph or f == want then + local o = base + oFrames + (f - 1) * frameSize + local sx, sy, sz = readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) + local tx, ty, tz = readf32(b, o + 12), readf32(b, o + 16), readf32(b, o + 20) + local pos = buffer.create(nv * 12) + for i = 1, nv do + local p = o + 40 + vx[i] * 4 + writef32(pos, (i - 1) * 12, readu8(b, p) * sx + tx) + writef32(pos, (i - 1) * 12 + 4, readu8(b, p + 1) * sy + ty) + writef32(pos, (i - 1) * 12 + 8, readu8(b, p + 2) * sz + tz) + end + frames[f] = pos + normals[f] = Rig.normals(pos, nv, indices) + end + local nm = buffer.readstring(b, base + oFrames + (f - 1) * frameSize + 24, 16) + names[f] = (string.match(nm, "^[^%z]*")) :: string + end + local ib = buffer.create(#indices * 4) + for i, v in indices do + writeu32(ib, (i - 1) * 4, v) + end + local prim: Types.Primitive = { + attributes = { + POSITION = Scene.accessor(frames[want], "f32", 3, nv), + NORMAL = Scene.accessor(normals[want], "f32", 3, nv), + TEXCOORD_0 = Scene.accessor(uv, "f32", 2, nv), + }, + indices = Scene.accessor(ib, "u32", 1, #indices), + mode = "triangles", + } + local scene = Scene.new() + scene.meta.up = "z" + if #skins > 0 then + for _, s in skins do + table.insert(scene.textures, { name = s, uri = s }) + end + local mat = Scene.material(skins[1]) + mat.metallic = 0 + mat.baseColorTexture = { texture = 1 } + table.insert(scene.materials, mat) + prim.material = 1 + end + scene.meshes[1] = { primitives = { prim }, extras = { skins = skins } } + scene.nodes[1] = { children = {}, mesh = 1 } + scene.roots[1] = 1 + if morph then + local fr: { buffer } = {} + for f = 1, nFrames do + fr[f] = frames[f] + end + Rig.morph(prim, fr, normals) + local w = table.create(nFrames, 0) + scene.meshes[1].weights = w + Rig.morphAnimation(scene, 1, nFrames, groups(names, opts and opts.fps or 10), "LINEAR") + end + scene.meta.source = { format = "md2", frames = nFrames, frameNames = names, skinWidth = sw, skinHeight = sh, normalIndexes = false } + return scene, nil +end + +return Md2 diff --git a/tests/model/_soup.luau b/tests/model/_soup.luau new file mode 100644 index 0000000..e47d142 --- /dev/null +++ b/tests/model/_soup.luau @@ -0,0 +1,51 @@ +-- tests/model/_soup: helpers for the game model tests: a primitive's triangle soup (positions, morph target frames, +-- texture coordinates in index order) and a tolerant comparison against assimp's soup. +local Types = require("@formats/Types") + +local Soup = {} + +-- positions(prim, target?) -> f32 x3 buffer of the corners in index order (target k adds morph target k's deltas) +function Soup.positions(prim: any, target: number?): buffer + local pos = Types.Scene.reader(prim.attributes.POSITION) :: any + local d = if target then Types.Scene.reader(prim.targets[target].POSITION) :: any else nil + local idx = prim.indices + local n = idx.count + local out = buffer.create(n * 12) + for k = 0, n - 1 do + local v = buffer.readu32(idx.data, k * 4) + for c = 0, 2 do + buffer.writef32(out, k * 12 + c * 4, pos(v, c) + (if d then d(v, c) else 0)) + end + end + return out +end + +-- uvs(prim, set?, flip?) -> { u, v, ... } of the corners in index order (flip: v -> 1 - v, assimp's convention) +function Soup.uvs(prim: any, set: number?, flip: boolean?): { number } + local tc = Types.Scene.reader(prim.attributes["TEXCOORD_" .. (set or 0)]) :: any + local idx = prim.indices + local out = {} + for k = 0, idx.count - 1 do + local v = buffer.readu32(idx.data, k * 4) + table.insert(out, tc(v, 0)) + table.insert(out, if flip then 1 - tc(v, 1) else tc(v, 1)) + end + return out +end + +-- close(a: buffer f32 | {number}, b: {number}, tol) -> true | false, first index that differs +function Soup.close(a: any, b: { number }, tol: number): (boolean, number?) + local n = if type(a) == "buffer" then buffer.len(a) // 4 else #a + if n ~= #b then + return false, -1 + end + for i = 1, n do + local x = if type(a) == "buffer" then buffer.readf32(a, (i - 1) * 4) else a[i] + if math.abs(x - b[i]) > tol * math.max(1, math.abs(b[i])) then + return false, i + end + end + return true, nil +end + +return Soup diff --git a/tests/model/md2.luau b/tests/model/md2.luau new file mode 100644 index 0000000..61322c9 --- /dev/null +++ b/tests/model/md2.luau @@ -0,0 +1,83 @@ +-- model/md2 tests: MD2 files written by tools/fixtures/md2.py decode to assimp's frame-0 triangle soup (positions, +-- texture coordinates) and to the writer's exact positions for every frame (base + morph target deltas), frame +-- groups as animations, skins as texture URIs, opts.frame / morph = false, errors, the fuzz pass. +local T = require("@tests/T") +local F = require("@formats") +local Md2 = require("@formats/model/md2") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Soup = require("@tests/model/_soup") +local Fx = require("@tests/gen/md2") + +local t = T.suite("md2") +t:eq(Md2.name, "md2", "name") + +for _, c in Fx do + local s, err = Md2.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(s, c.name .. ": " .. tostring(err)) + t:eq(F.detect(c.data), "md2", c.name .. ": F.detect") + local prim = s.meshes[1].primitives[1] + t:eq(prim.indices.count, c.tris * 3, c.name .. ": triangles") + -- assimp, frame 0 + local ok, at = Soup.close(Soup.positions(prim), c.assimp.pos, 1e-5) + t:check(ok, c.name .. ": positions against assimp (" .. tostring(at) .. ")") + local uok, uat = Soup.close(Soup.uvs(prim, 0, true), c.assimp.uv, 1e-6) + t:check(uok, c.name .. ": texture coordinates against assimp (" .. tostring(uat) .. ")") + -- every frame, exact + t:eq(Crc32.of(Soup.positions(prim)), c.crcs[1], c.name .. ": frame 1 exact") + for k = 1, c.frames do + local f = Soup.positions(prim, k) + -- base + delta in f32 can differ from the frame by an ulp; compare to the decoded frame directly + local frame = Md2.decode(Bytes.reader(buffer.fromstring(c.data)), { frame = k, morph = false }) :: any + t:eq(Crc32.of(Soup.positions(frame.meshes[1].primitives[1])), c.crcs[k], c.name .. ": frame " .. k .. " exact (opts.frame)") + local fok = Soup.close(f, (function() + local list = {} + local fp = Soup.positions(frame.meshes[1].primitives[1]) + for i = 0, buffer.len(fp) // 4 - 1 do + list[i + 1] = buffer.readf32(fp, i * 4) + end + return list + end)(), 1e-5) + t:check(fok, c.name .. ": morph target " .. k .. " = frame " .. k) + end + -- animations from the frame names + local groups = {} + for _, a in s.animations do + table.insert(groups, a.name) + end + t:eq(#s.meshes[1].weights, c.frames, c.name .. ": one weight per frame") + t:eq(s.meta.source.frameNames[1], c.names[1], c.name .. ": frame names") + if c.name == "monster" then + t:eq(table.concat(groups, ","), "stand,run,attack,pain", c.name .. ": animation groups") + t:eq(s.animations[2].channels[1].input.count, 4, c.name .. ": run has 4 keys") + end + -- skins + t:eq(#s.textures, #c.skins, c.name .. ": skins") + if #c.skins > 0 then + t:eq(s.textures[1].uri, c.skins[1], c.name .. ": skin uri") + t:eq(s.materials[prim.material].baseColorTexture.texture, 1, c.name .. ": material") + end + t:eq(s.meta.up, "z", c.name .. ": z up") +end + +do + local c = Fx[1] + local lean = Md2.decode(Bytes.reader(buffer.fromstring(c.data)), { morph = false }) :: any + t:check(lean.meshes[1].primitives[1].targets == nil and #lean.animations == 0, "morph = false") + local _, e1 = Md2.decode(Bytes.reader(buffer.fromstring(string.sub(c.data, 1, 300)))) + t:check(e1 and e1.code == Err.TRUNCATED, "truncated: " .. tostring(e1)) + local bad = buffer.fromstring(c.data) + buffer.writei32(bad, 4, 7) + local _, e2 = Md2.decode(Bytes.reader(bad)) + t:check(e2 and e2.code == Err.UNSUPPORTED, "version 7") +end + +local samples = {} +for _, c in Fx do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + return Md2.decode(Bytes.reader(b)) +end, samples, { mutations = 80 }) +t:done() diff --git a/tools/fixtures/_quake_ref.py b/tools/fixtures/_quake_ref.py new file mode 100644 index 0000000..e76ea82 --- /dev/null +++ b/tools/fixtures/_quake_ref.py @@ -0,0 +1,35 @@ +# Shared helpers for the Quake-family model fixtures (md2.py, md3.py, mdl.py): assimp's triangle soup. +# assimp_soup(ctx, data, ext) -> { pos = [floats], uv = [floats], meshes, faces } | { failed = True }: every triangle +# mesh of `assimp export -f assjson`, faces in order, each face's corners in assimp's index order (positions x3, +# texture coordinates u, v of set 0) +import json, os, shutil, subprocess, tempfile + + +def assimp_soup(ctx, data, ext): + tmp = tempfile.mkdtemp(prefix="formats-quake-") + try: + src = os.path.join(tmp, "in." + ext) + open(src, "wb").write(data) + out = os.path.join(tmp, "out.json") + try: + ctx.nix("assimp", ["assimp", "export", src, out, "-f", "assjson"]) + except subprocess.CalledProcessError: + return {"failed": True} + j = json.load(open(out)) + finally: + shutil.rmtree(tmp) + pos, uv, faces, meshes = [], [], 0, 0 + for m in j.get("meshes", []): + if m.get("primitivetypes") != 4: + continue + meshes += 1 + v = m["vertices"] + t = (m.get("texturecoords") or [[]])[0] + nc = (m.get("numuvcomponents") or [2])[0] + for f in m["faces"]: + faces += 1 + for i in f: + pos += v[i * 3:i * 3 + 3] + if t: + uv += t[i * nc:i * nc + 2] + return {"pos": pos, "uv": uv, "faces": faces, "meshes": meshes} diff --git a/tools/fixtures/md2.py b/tools/fixtures/md2.py new file mode 100644 index 0000000..5d09e49 --- /dev/null +++ b/tools/fixtures/md2.py @@ -0,0 +1,75 @@ +# Quake II MD2 fixtures (tools/fixtures.py): MD2 files written here from the dmdl_t layout (random frames with +# scale / translate, distinct-vertex triangles, texture coordinates, skins, frame names in groups); references: +# assimp's triangle soup of frame 0 (positions, texture coordinates: assimp flips v) and this writer's own exact +# positions of every frame (CRC-32 of the f32 soup in our corner order: reversed to counter-clockwise). +# tests/gen/md2.luau { { name, data, frames = n, names, skins, tris, crcs = { per frame }, assimp = { pos, uv } } } +import importlib.util, os, struct, zlib + +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 f32(x): + return struct.unpack("