ws-game: model/bsp (Quake 1 / Half-Life / Quake II brush maps, Quake III maps with patches and lightmaps, entities); core/Input.sibling (opts.files / opts.resolve lookup shared by mdl / bsp / md5 / vpk; additive)

This commit is contained in:
4DBug committed 2026-10-31 15:01:06 -05:00
1 parent 9b2b50fe75
commit 4932fa7148
11 files changed
+1212 -47

No files matched your search

+15 -3
View File
@@ -374,6 +374,18 @@ local list: { Entry } = {
return require("@formats/model/3mf")
end,
},
{
name = "bsp",
category = "model",
path = "model/bsp",
extensions = { "bsp" },
mime = { "model/x-bsp" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" },
caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" },
load = function()
return require("@formats/model/bsp")
end,
},
{
name = "dae",
category = "model",
@@ -440,7 +452,7 @@ local list: { Entry } = {
path = "model/md5",
extensions = { "md5mesh", "md5anim" },
mime = { "model/x-md5mesh", "model/x-md5anim" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" },
deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/model/Rig" },
caps = { decode = true, encode = false, skins = true, animation = true },
load = function()
return require("@formats/model/md5")
@@ -452,7 +464,7 @@ local list: { Entry } = {
path = "model/mdl",
extensions = { "mdl" },
mime = { "model/x-mdl" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" },
caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true },
load = function()
return require("@formats/model/mdl")
@@ -704,7 +716,7 @@ local list: { Entry } = {
path = "archive/vpk",
extensions = { "vpk" },
mime = { "application/x-vpk" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "core/Md5", "containers/Archive" },
deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" },
caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true },
load = function()
return require("@formats/archive/vpk")
+3 -10
View File
@@ -12,6 +12,7 @@
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Input = require("@formats/core/Input")
local Crc32 = require("@formats/core/Crc32")
local Md5 = require("@formats/core/Md5")
local Archive = require("@formats/containers/Archive")
@@ -22,7 +23,7 @@ local Vpk = {
category = "archive",
extensions = { "vpk" },
mime = { "application/x-vpk" },
deps = { "core/Err", "core/Bytes", "core/Crc32", "core/Md5", "containers/Archive" },
deps = { "core/Err", "core/Bytes", "core/Input", "core/Crc32", "core/Md5", "containers/Archive" },
caps = { decode = true, encode = true, versions = { 1, 2 }, multipart = true },
}
@@ -68,15 +69,7 @@ local function partLoader(opts: DecodeOptions?): (number) -> (buffer?, Err.Err?)
return hit, nil
end
local name = string.format("%s_%03d.vpk", prefix, index)
local data: any = nil
if opts and type(opts.files) == "table" then
data = opts.files[name]
end
if data == nil and opts and type(opts.resolve) == "function" then
local ok, v = pcall(opts.resolve, name)
data = if ok then v else nil
end
local b = Bytes.toBuffer(data)
local b = Input.sibling(opts, name)
if not b then
return nil, Err.new(Err.UNSUPPORTED, "part file " .. name .. " not available (opts.resolve / opts.files)")
end
+20
View File
@@ -59,4 +59,24 @@ function Input.extension(name: string?): string?
return if ext then string.lower(ext) else nil
end
-- sibling(opts, uri) -> buffer | nil: a file the data being decoded refers to (a palette, an animation, an archive
-- part, ...): opts.files[uri] (a buffer or a string), else opts.resolve(uri) (errors in it count as not found)
function Input.sibling(opts: any?, uri: string): buffer?
if type(opts) ~= "table" then
return nil
end
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) == "string" then
return buffer.fromstring(v)
end
return if type(v) == "buffer" then v else nil
end
return Input
+291
View File
@@ -0,0 +1,291 @@
--!strict
-- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps to a Scene: every face (a convex
-- polygon of surface edges) fan-triangulated counter-clockwise about its plane's normal, one primitive per texture
-- per model (model 0 = the world, the others = brush entities "*1", "*2", ... as child nodes), TEXCOORD_0 from the
-- texture vectors (s = v . s.xyz + s.w, divided by the texture size), NORMAL = the plane normal. Textures: Quake /
-- Half-Life embedded mip textures (mip 0) decoded through the palette (Half-Life: each texture's own; Quake: the
-- caller's), textures kept in WAD files as URIs; Quake II textures are external .wal files (URIs; their size from
-- opts.resolve("textures/<name>.wal") when available, else texture coordinates stay in texels: extras.bsp.texels).
-- Written from the Quake specs (bspfile.h of the Quake / Quake II source releases); no code taken.
-- Not supported: lightmaps (light offsets are kept per face in extras), visibility / BSP tree / clip hulls.
local Types = require("@formats/Types")
local Pixels = require("@formats/codecs/image/Pixels")
local Brush = {}
local Scene = Types.Scene
local readi32, readu16, readf32, readu32 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32
local writef32, writeu32 = buffer.writef32, buffer.writeu32
export type Lump = { at: number, size: number }
export type Options = {
palette: buffer?,
wal: ((name: string) -> buffer?)?, -- Quake II: the .wal file of a texture (for its size)
maxPixels: number?,
maxVertices: number?,
}
type Tex = { name: string, width: number, height: number, image: Types.Image?, texels: boolean }
type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number } }
local function cstr(b: buffer, at: number, n: number): string
return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string
end
-- miptex lump (Quake / Half-Life) -> textures
local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer?, maxPixels: number): ({ Tex }?, string?)
local out: { Tex } = {}
if l.size < 4 then
return out, nil
end
local at = base + l.at
local n = readi32(b, at)
if n < 0 or n > 65536 or 4 + n * 4 > l.size then
return nil, "bad miptex lump"
end
local gpal = if pal then Pixels.palette(pal, 0, 256) else nil
for i = 0, n - 1 do
local o = readi32(b, at + 4 + i * 4)
if o < 0 or o + 40 > l.size then
out[i + 1] = { name = "missing" .. i, width = 64, height = 64, image = nil, texels = false }
else
local m = at + o
local name = cstr(b, m, 16)
local w, h, off0 = readu32(b, m + 16), readu32(b, m + 20), readu32(b, m + 24)
local t: Tex = { name = name, width = math.max(w, 1), height = math.max(h, 1), image = nil, texels = false }
if off0 ~= 0 and w > 0 and h > 0 and w * h <= maxPixels then
local px = m + off0
local need = w * h
local palAt = m + readu32(b, m + 36) + (w // 8) * (h // 8) + 2
if o + off0 + need <= l.size then
local p = gpal
if hl then
p = if palAt - at + 768 <= l.size then Pixels.palette(b, palAt, 256) else nil
end
local img = Types.Image.new(w, h)
if p then
Pixels.indexed(b, px, w, 8, img.pixels, w, h, true, p)
else
for k = 0, need - 1 do
writeu32(img.pixels, k * 4, 0xFF000000 + buffer.readu8(b, px + k) * 0x10101)
end
end
img.meta.source = { format = "bsp", miptex = name, palette = p ~= nil }
t.image = img
end
end
out[i + 1] = t
end
end
return out, nil
end
-- decode(b, base, size, lumps, variant, opts) -> Scene | nil, message
-- variant "q1" (29), "hl" (30) or "q2" (38); lumps by name: vertices, edges, surfedges, faces, texinfo, planes,
-- models, miptex (q1 / hl)
function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?)
local q2 = variant == "q2"
local maxPixels = opts and opts.maxPixels or 2 ^ 24
local V, E, SE, Fc, TI, P, M = lumps.vertices, lumps.edges, lumps.surfedges, lumps.faces, lumps.texinfo, lumps.planes, lumps.models
local nV, nE, nSE, nF = V.size // 12, E.size // 4, SE.size // 4, Fc.size // 20
local tiSize = if q2 then 76 else 40
local nTI, nP = TI.size // tiSize, P.size // 20
local mSize = if q2 then 48 else 64
local nM = M.size // mSize
if nF > (opts and opts.maxVertices or 2 ^ 24) then
return nil, "limit: too many faces"
end
-- textures
local texs: { Tex } = {}
local texOf: { number } = {} -- texinfo -> texture index (1-based)
if q2 then
local byName: { [string]: number } = {}
for i = 0, nTI - 1 do
local name = cstr(b, base + TI.at + i * 76 + 40, 32)
local ti = byName[name]
if not ti then
local w, h, texels = 1, 1, true
local wal = opts and opts.wal and opts.wal(name)
if wal and buffer.len(wal) >= 40 then
w, h, texels = math.max(1, readu32(wal, 32)), math.max(1, readu32(wal, 36)), false
end
table.insert(texs, { name = name, width = w, height = h, image = nil, texels = texels })
ti = #texs
byName[name] = ti
end
texOf[i + 1] = ti
end
else
local list, err = miptex(b, base, lumps.miptex, variant == "hl", opts and opts.palette, maxPixels)
if not list then
return nil, err
end
texs = list
for i = 0, nTI - 1 do
local mt = readi32(b, base + TI.at + i * 40 + 32)
texOf[i + 1] = if mt >= 0 and mt < #texs then mt + 1 else 0
end
end
-- faces of each model
local scene = Scene.new()
scene.meta.up = "z"
local faceModel: { number } = {}
local models: { { first: number, count: number, origin: { number } } } = {}
for m = 0, nM - 1 do
local o = base + M.at + m * mSize
local origin = { readf32(b, o + 24), readf32(b, o + 28), readf32(b, o + 32) }
local fo = if q2 then 40 else 56
local first, count = readi32(b, o + fo), readi32(b, o + fo + 4)
table.insert(models, { first = first, count = count, origin = origin })
if first >= 0 and count >= 0 and first + count <= nF then
for f = first, first + count - 1 do
faceModel[f + 1] = faceModel[f + 1] or (m + 1)
end
end
end
if #models == 0 then
table.insert(models, { first = 0, count = nF, origin = { 0, 0, 0 } })
for f = 1, nF do
faceModel[f] = 1
end
end
local batches: { [number]: { [number]: Batch } } = {}
local orders: { [number]: { number } } = {}
local skipped = 0
for f = 0, nF - 1 do
local fo = base + Fc.at + f * 20
local plane, side, firstEdge, numEdges, texinfo = readu16(b, fo), readu16(b, fo + 2), readi32(b, fo + 4), readu16(b, fo + 8), readu16(b, fo + 10)
local model = faceModel[f + 1]
if not model or numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then
skipped += 1
continue
end
-- the polygon
local poly: { number } = {}
local ok = true
for k = 0, numEdges - 1 do
local se = readi32(b, base + SE.at + (firstEdge + k) * 4)
local e = math.abs(se)
if e >= nE then
ok = false
break
end
local v = if se >= 0 then readu16(b, base + E.at + e * 4) else readu16(b, base + E.at + e * 4 + 2)
if v >= nV then
ok = false
break
end
local vo = base + V.at + v * 12
table.insert(poly, readf32(b, vo))
table.insert(poly, readf32(b, vo + 4))
table.insert(poly, readf32(b, vo + 8))
end
if not ok then
skipped += 1
continue
end
local po = base + P.at + plane * 20
local nx, ny, nz = readf32(b, po), readf32(b, po + 4), readf32(b, po + 8)
if side ~= 0 then
nx, ny, nz = -nx, -ny, -nz
end
-- orient counter-clockwise about the normal (Newell's normal of the polygon as stored)
local n = #poly // 3
local ax, ay, az = 0, 0, 0
for k = 0, n - 1 do
local j = (k + 1) % n
local x1, y1, z1 = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3]
local x2, y2, z2 = poly[j * 3 + 1], poly[j * 3 + 2], poly[j * 3 + 3]
ax += (y1 - y2) * (z1 + z2)
ay += (z1 - z2) * (x1 + x2)
az += (x1 - x2) * (y1 + y2)
end
local order: { number } = {}
if ax * nx + ay * ny + az * nz >= 0 then
for k = 0, n - 1 do
order[k + 1] = k
end
else
order[1] = 0
for k = 1, n - 1 do
order[k + 1] = n - k
end
end
local tio = base + TI.at + texinfo * tiSize
local sx, sy, sz, so = readf32(b, tio), readf32(b, tio + 4), readf32(b, tio + 8), readf32(b, tio + 12)
local tx, ty, tz, to = readf32(b, tio + 16), readf32(b, tio + 20), readf32(b, tio + 24), readf32(b, tio + 28)
local ti = texOf[texinfo + 1] or 0
local tex = texs[ti]
local w, h = if tex then tex.width else 1, if tex then tex.height else 1
local bm = batches[model] or {}
batches[model] = bm
local bt = bm[ti]
if not bt then
bt = { tex = ti, pos = {}, nrm = {}, uv = {} }
bm[ti] = bt
local ol = orders[model] or {}
orders[model] = ol
table.insert(ol, ti)
end
local batch: Batch = bt
for k = 2, n - 1 do
for _, c in { order[1], order[k], order[k + 1] } do
local x, y, z = poly[c * 3 + 1], poly[c * 3 + 2], poly[c * 3 + 3]
local pp, nn, uu = batch.pos, batch.nrm, batch.uv
pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z
nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = nx, ny, nz
uu[#uu + 1] = (x * sx + y * sy + z * sz + so) / w
uu[#uu + 1] = (x * tx + y * ty + z * tz + to) / h
end
end
end
-- textures, materials
for i, t in texs do
local tex: Types.Texture = { name = t.name, image = t.image, uri = if t.image then nil else (if q2 then "textures/" .. t.name .. ".wal" else t.name) }
table.insert(scene.textures, tex)
local mat = Scene.material(t.name)
mat.metallic = 0
local extras: any = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } }
mat.extras = extras
mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } :: any
table.insert(scene.materials, mat)
end
-- meshes and nodes
local root: Types.Node = { name = "bsp", children = {} }
table.insert(scene.nodes, root)
scene.roots[1] = 1
for m, mdl in models do
local list = orders[m]
if list then
local mesh: Types.Mesh = { name = if m == 1 then "world" else "*" .. (m - 1), primitives = {} }
for _, ti in list do
local bt = batches[m][ti]
local nv = #bt.pos // 3
local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 4)
for k = 1, nv * 3 do
writef32(pb, (k - 1) * 4, bt.pos[k])
writef32(nb, (k - 1) * 4, bt.nrm[k])
end
for k = 1, nv * 2 do
writef32(ub, (k - 1) * 4, bt.uv[k])
end
for k = 0, nv - 1 do
writeu32(ib, k * 4, k)
end
table.insert(mesh.primitives, {
attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) },
indices = Scene.accessor(ib, "u32", 1, nv),
mode = "triangles" :: any,
material = if ti > 0 then ti else nil,
})
end
table.insert(scene.meshes, mesh)
table.insert(scene.nodes, { name = mesh.name, children = {}, mesh = #scene.meshes, extras = { bsp = { model = m - 1, origin = mdl.origin } } })
table.insert(root.children, #scene.nodes)
end
end
scene.meta.skippedFaces = skipped
return scene, nil
end
return Brush
+261
View File
@@ -0,0 +1,261 @@
--!strict
-- model/bsp/Quake3: Quake III Arena maps (IBSP version 46; Return to Castle Wolfenstein 47 has the same layout) to a
-- Scene: polygon and mesh faces (meshvert triangles, reversed to counter-clockwise), biquadratic patches
-- tessellated (opts.patchLevel subdivisions per 3x3 control patch, default 4), one primitive per shader and lightmap
-- per model (model 0 = the world, the others "*1", ...), POSITION / NORMAL / TEXCOORD_0 (surface) / TEXCOORD_1
-- (lightmap) / COLOR_0 (vertex colours, unorm8); shaders as texture URIs; the 128 x 128 RGB lightmaps as
-- texture.image (material.extras.bsp.lightmap = its texture index, texCoord 1). Billboards (flares) are skipped.
-- Written from the Unofficial Quake 3 Map Specs (Kekoa Proudfoot); no code taken.
local Types = require("@formats/Types")
local Quake3 = {}
local Scene = Types.Scene
local readi32, readf32, readu8 = buffer.readi32, buffer.readf32, buffer.readu8
local writef32, writeu32, writeu8 = buffer.writef32, buffer.writeu32, buffer.writeu8
export type Lump = { at: number, size: number }
export type Options = { patchLevel: number?, maxVertices: number? }
type Batch = { shader: number, lightmap: number, verts: { number } } -- vertex records (indices into the vertex lump, or -1 - k for patch vertices)
local function cstr(b: buffer, at: number, n: number): string
return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string
end
-- decode(b, base, lumps, opts) -> Scene | nil, message
function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: Options?): (Types.Scene?, string?)
local T, M, VX, MV, F, LM = lumps.textures, lumps.models, lumps.vertexes, lumps.meshverts, lumps.faces, lumps.lightmaps
local nT, nM, nV, nMV, nF, nLM = T.size // 72, M.size // 40, VX.size // 44, MV.size // 4, F.size // 104, LM.size // 49152
local level = math.clamp(math.floor(opts and opts.patchLevel or 4), 1, 16)
local maxV = opts and opts.maxVertices or 2 ^ 24
-- patch vertices: 12 floats + 4 colour bytes each, appended as negative ids
local extra: { number } = {}
local function vertex(i: number): { number }
local o = base + VX.at + i * 44
local v = table.create(14, 0)
for k = 0, 9 do
v[k + 1] = readf32(b, o + k * 4)
end
for k = 0, 3 do
v[11 + k] = readu8(b, o + 40 + k)
end
return v
end
local function addExtra(v: { number }): number
for k = 1, 14 do
table.insert(extra, v[k])
end
return -(#extra // 14)
end
local faceModel: { number } = {}
for m = 0, nM - 1 do
local o = base + M.at + m * 40
local first, count = readi32(b, o + 24), readi32(b, o + 28)
if first >= 0 and count >= 0 and first + count <= nF then
for f = first, first + count - 1 do
faceModel[f + 1] = faceModel[f + 1] or (m + 1)
end
end
end
local batches: { [number]: { [string]: Batch } } = {}
local orders: { [number]: { string } } = {}
local counts = { polygons = 0, meshes = 0, patches = 0, billboards = 0, skipped = 0 }
local total = 0
for f = 0, nF - 1 do
local o = base + F.at + f * 104
local shader, kind, first, n, mv, nmv, lm = readi32(b, o), readi32(b, o + 8), readi32(b, o + 12), readi32(b, o + 16), readi32(b, o + 20), readi32(b, o + 24), readi32(b, o + 28)
local model = faceModel[f + 1] or 1
local tris: { number } = {}
if (kind == 1 or kind == 3) and first >= 0 and n >= 0 and first + n <= nV and mv >= 0 and nmv >= 0 and mv + nmv <= nMV then
for k = 0, nmv - 3, 3 do
local ok = true
local tri = {}
for c = 0, 2 do
local idx = readi32(b, base + MV.at + (mv + k + c) * 4)
if idx < 0 or idx >= n then
ok = false
end
tri[c + 1] = first + idx
end
if ok then
table.insert(tris, tri[3])
table.insert(tris, tri[2])
table.insert(tris, tri[1])
end
end
counts[if kind == 1 then "polygons" else "meshes"] += 1
elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then
local w, h = readi32(b, o + 96), readi32(b, o + 100)
if w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n then
counts.patches += 1
local L = level
for py = 0, (h - 1) // 2 - 1 do
for px = 0, (w - 1) // 2 - 1 do
-- the 3x3 control points of this sub-patch
local ctrl: { { number } } = {}
for j = 0, 2 do
for i = 0, 2 do
ctrl[j * 3 + i + 1] = vertex(first + (py * 2 + j) * w + px * 2 + i)
end
end
local grid: { number } = {}
for gy = 0, L do
local tv = gy / L
for gx = 0, L do
local tu = gx / L
local bu = { (1 - tu) ^ 2, 2 * tu * (1 - tu), tu * tu }
local bv = { (1 - tv) ^ 2, 2 * tv * (1 - tv), tv * tv }
local v = table.create(14, 0)
for j = 0, 2 do
for i = 0, 2 do
local wgt = bu[i + 1] * bv[j + 1]
local cp = ctrl[j * 3 + i + 1]
for k = 1, 14 do
v[k] += cp[k] * wgt
end
end
end
local l = math.sqrt(v[8] ^ 2 + v[9] ^ 2 + v[10] ^ 2)
if l > 0 then
v[8], v[9], v[10] = v[8] / l, v[9] / l, v[10] / l
end
grid[gy * (L + 1) + gx + 1] = addExtra(v)
end
end
for gy = 0, L - 1 do
for gx = 0, L - 1 do
local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2]
local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2]
-- counter-clockwise for Quake's clockwise-front control grids
for _, v in { a, d, c2, c2, d, e } do
table.insert(tris, v)
end
end
end
end
end
else
counts.skipped += 1
end
elseif kind == 4 then
counts.billboards += 1
else
counts.skipped += 1
end
total += #tris
if total > maxV then
return nil, "limit: too many vertices"
end
if #tris > 0 then
local key = shader .. ":" .. lm
local bm = batches[model] or {}
batches[model] = bm
local bt = bm[key]
if not bt then
bt = { shader = shader, lightmap = lm, verts = {} }
bm[key] = bt
local ol = orders[model] or {}
orders[model] = ol
table.insert(ol, key)
end
for _, v in tris do
table.insert(bt.verts, v)
end
end
end
local scene = Scene.new()
scene.meta.up = "z"
-- shaders, lightmaps
for i = 0, nT - 1 do
local name = cstr(b, base + T.at + i * 72, 64)
table.insert(scene.textures, { name = name, uri = name })
end
local lmTex: { [number]: number } = {}
for i = 0, nLM - 1 do
local img = Types.Image.new(128, 128)
local o = base + LM.at + i * 49152
for k = 0, 128 * 128 - 1 do
writeu8(img.pixels, k * 4, readu8(b, o + k * 3))
writeu8(img.pixels, k * 4 + 1, readu8(b, o + k * 3 + 1))
writeu8(img.pixels, k * 4 + 2, readu8(b, o + k * 3 + 2))
writeu8(img.pixels, k * 4 + 3, 255)
end
img.meta.source = { format = "bsp", lightmap = i }
table.insert(scene.textures, { name = "lightmap " .. i, image = img })
lmTex[i] = #scene.textures
end
local matOf: { [string]: number } = {}
local root: Types.Node = { name = "bsp", children = {} }
table.insert(scene.nodes, root)
scene.roots[1] = 1
local modelCount = math.max(nM, 1)
for m = 1, modelCount do
local list = orders[m]
if list then
local mesh: Types.Mesh = { name = if m == 1 then "world" else "*" .. (m - 1), primitives = {} }
for _, key in list do
local bt = batches[m][key]
local nv = #bt.verts
local pb, nb, ub, lb, cb, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(nv * 8), buffer.create(nv * 4), buffer.create(nv * 4)
for k, id in bt.verts do
local v: { number }
if id >= 0 then
v = vertex(id)
else
local e = (-id - 1) * 14
v = table.move(extra, e + 1, e + 14, 1, table.create(14, 0)) :: { number }
end
local o = (k - 1)
writef32(pb, o * 12, v[1])
writef32(pb, o * 12 + 4, v[2])
writef32(pb, o * 12 + 8, v[3])
writef32(ub, o * 8, v[4])
writef32(ub, o * 8 + 4, v[5])
writef32(lb, o * 8, v[6])
writef32(lb, o * 8 + 4, v[7])
writef32(nb, o * 12, v[8])
writef32(nb, o * 12 + 4, v[9])
writef32(nb, o * 12 + 8, v[10])
for c = 0, 3 do
writeu8(cb, o * 4 + c, math.clamp(math.floor(v[11 + c] + 0.5), 0, 255))
end
writeu32(ib, o * 4, o)
end
local mi = matOf[key]
if not mi then
local name = if bt.shader >= 0 and bt.shader < nT then scene.textures[bt.shader + 1].name else "noshader"
local mat = Scene.material(name)
mat.metallic = 0
if bt.shader >= 0 and bt.shader < nT then
mat.baseColorTexture = { texture = bt.shader + 1 }
end
local lt = lmTex[bt.lightmap]
mat.extras = { bsp = { lightmap = lt, lightmapTexCoord = if lt then 1 else nil } }
table.insert(scene.materials, mat)
mi = #scene.materials
matOf[key] = mi
end
table.insert(mesh.primitives, {
attributes = {
POSITION = Scene.accessor(pb, "f32", 3, nv),
NORMAL = Scene.accessor(nb, "f32", 3, nv),
TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv),
TEXCOORD_1 = Scene.accessor(lb, "f32", 2, nv),
COLOR_0 = Scene.accessor(cb, "unorm8", 4, nv),
},
indices = Scene.accessor(ib, "u32", 1, nv),
mode = "triangles" :: any,
material = mi,
})
end
table.insert(scene.meshes, mesh)
table.insert(scene.nodes, { name = mesh.name, children = {}, mesh = #scene.meshes, extras = { bsp = { model = m - 1 } } })
table.insert(root.children, #scene.nodes)
end
end
scene.meta.faces = counts
return scene, nil
end
return Quake3
+150
View File
@@ -0,0 +1,150 @@
--!strict
-- model/bsp: compiled game maps read into a Scene: Quake 1 (BSP 29) and Half-Life (BSP 30), Quake II (IBSP 38)
-- through model/bsp/Brush, Quake III Arena / RTCW (IBSP 46 / 47) through model/bsp/Quake3. Each model of the map is a
-- mesh (model 0 "world", brush entities "*1", "*2", ... as nodes), one primitive per texture (and Quake III
-- lightmap). The entities lump is parsed into meta.entities = { { classname = ..., origin = ..., ... } } (strings as
-- stored) with the text in meta.source.entities. Quake textures need the game's palette (gfx/palette.lmp, not
-- redistributable: never built in): opts.palette, else opts.resolve / opts.files["gfx/palette.lmp"], else grey.
-- Quake II .wal sizes come from opts.resolve("textures/<name>.wal") / opts.files. Units are map units, z up.
-- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Input = require("@formats/core/Input")
local Types = require("@formats/Types")
local Brush = require("@formats/model/bsp/Brush")
local Quake3 = require("@formats/model/bsp/Quake3")
-- ------------------------------------------------------------------------------------------------ contract
local Bsp = {
name = "bsp",
category = "model",
extensions = { "bsp" },
mime = { "model/x-bsp" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" },
caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
palette: (buffer | string)?, -- Quake 1: the 768-byte palette
resolve: ((uri: string) -> (buffer | string)?)?,
files: { [string]: buffer | string }?,
patchLevel: number?, -- Quake III patch subdivisions (default 4)
maxPixels: number?, -- default 2^24
maxVertices: number?, -- default 2^24
}
-- ------------------------------------------------------------------------------------------------ constants
local Q1_LUMPS = { "entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting",
"clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models" }
local Q2_LUMPS = { "entities", "planes", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", "leaves",
"leaffaces", "leafbrushes", "edges", "surfedges", "models", "brushes", "brushsides", "pop", "areas", "areaportals" }
local Q3_LUMPS = { "entities", "textures", "planes", "nodes", "leafs", "leaffaces", "leafbrushes", "models", "brushes",
"brushsides", "vertexes", "meshverts", "effects", "faces", "lightmaps", "lightvols", "visdata" }
-- ------------------------------------------------------------------------------------------------ sniff
function Bsp.sniff(r: Bytes.Reader): number
if r:remaining() < 64 then
return 0
end
local m = r:peek(4)
local v = buffer.readi32(r.buf, r.pos + (if m == "IBSP" then 4 else 0))
if m == "IBSP" then
return if v == 38 or v == 46 or v == 47 then 1 else 0.3
end
if v == 29 or v == 30 then
-- no magic: check that the lump directory fits the file
local size = r:remaining()
for i = 0, 14 do
local o, n = buffer.readi32(r.buf, r.pos + 4 + i * 8), buffer.readi32(r.buf, r.pos + 8 + i * 8)
if o < 0 or n < 0 or o + n > size then
return 0
end
end
return 0.6
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
-- the entities text -> { { key = value } }
local function entities(text: string): { { [string]: string } }
local out: { { [string]: string } } = {}
for block in string.gmatch(text, "%b{}") do
local e: { [string]: string } = {}
for k, v in string.gmatch(block, '"([^"]*)"%s*"([^"]*)"') do
e[k] = v
end
table.insert(out, e)
end
return out
end
function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local size = r.limit - r.base
if size < 8 then
return nil, Err.new(Err.TRUNCATED, "header", 0)
end
local b, base = r.buf, r.base
local m = r:peek(4)
local version = buffer.readi32(b, base + (if m == "IBSP" then 4 else 0))
local names: { string }, dir: number, variant: string
if m == "IBSP" and version == 38 then
names, dir, variant = Q2_LUMPS, 8, "q2"
elseif m == "IBSP" and (version == 46 or version == 47) then
names, dir, variant = Q3_LUMPS, 8, "q3"
elseif m ~= "IBSP" and (version == 29 or version == 30) then
names, dir, variant = Q1_LUMPS, 4, if version == 30 then "hl" else "q1"
elseif m == "VBSP" then
return nil, Err.new(Err.UNSUPPORTED, "Source engine VBSP maps", 0)
else
return nil, Err.new(Err.UNSUPPORTED, "BSP version " .. version, 0)
end
if dir + #names * 8 > size then
return nil, Err.new(Err.TRUNCATED, "lump directory", dir)
end
local lumps: { [string]: { at: number, size: number } } = {}
for i, name in names do
local o, n = buffer.readi32(b, base + dir + (i - 1) * 8), buffer.readi32(b, base + dir + (i - 1) * 8 + 4)
if o < 0 or n < 0 or o + n > size then
return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dir + (i - 1) * 8)
end
lumps[name] = { at = o, size = n }
end
local scene: Types.Scene?, msg: string?
if variant == "q3" then
scene, msg = Quake3.decode(b, base, lumps, opts :: any)
else
local pal = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp")
if pal and buffer.len(pal) < 768 then
pal = nil
end
scene, msg = Brush.decode(b, base, lumps, variant, {
palette = pal,
wal = function(name: string): buffer?
return Input.sibling(opts, "textures/" .. name .. ".wal")
end,
maxPixels = opts and opts.maxPixels,
maxVertices = opts and opts.maxVertices,
})
end
if not scene then
return nil, Err.from(msg)
end
local e = lumps.entities
local text = buffer.readstring(b, base + e.at, e.size)
text = string.match(text, "^[^%z]*") :: string
scene.meta.entities = entities(text)
scene.meta.source = {
format = "bsp",
variant = ({ q1 = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant],
version = version,
entities = text,
palette = if variant == "q1" then (opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) else nil,
}
return scene, nil
end
return Bsp
+4 -17
View File
@@ -9,6 +9,7 @@
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Input = require("@formats/core/Input")
local Sniff = require("@formats/core/Sniff")
local Types = require("@formats/Types")
local Read = require("@formats/model/md5/Read")
@@ -19,7 +20,7 @@ local Md5 = {
category = "model",
extensions = { "md5mesh", "md5anim" },
mime = { "model/x-md5mesh", "model/x-md5anim" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types", "codecs/model/Rig" },
deps = { "core/Err", "core/Bytes", "core/Input", "core/Sniff", "Types", "codecs/model/Rig" },
caps = { decode = true, encode = false, skins = true, animation = true },
}
@@ -41,21 +42,6 @@ function Md5.sniff(r: Bytes.Reader): number
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, "%.[^.]*$", ""))
@@ -76,7 +62,8 @@ function Md5.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
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
local got = if type(name) == "string" then Input.sibling(opts, name) else nil
local src = if got then buffer.tostring(got) 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)")
+3 -17
View File
@@ -9,6 +9,7 @@
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Input = require("@formats/core/Input")
local Types = require("@formats/Types")
local Quake = require("@formats/model/mdl/Quake")
local HalfLife = require("@formats/model/mdl/HalfLife")
@@ -19,7 +20,7 @@ local Mdl = {
category = "model",
extensions = { "mdl" },
mime = { "model/x-mdl" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" },
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/model/Mat4", "codecs/model/Rig" },
caps = { decode = true, encode = false, variants = { "quake", "halflife" }, morph = true, skins = true, animation = true },
}
@@ -48,21 +49,6 @@ function Mdl.sniff(r: Bytes.Reader): number
end
-- ------------------------------------------------------------------------------------------------ decode
local function fetch(opts: DecodeOptions?, uri: string): buffer?
if not opts then
return nil
end
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
return Bytes.toBuffer(v)
end
function Mdl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local size = r.limit - r.base
if size < 8 then
@@ -74,7 +60,7 @@ function Mdl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E
if version ~= 6 then
return nil, Err.new(Err.UNSUPPORTED, "Quake MDL version " .. version, 4)
end
local pal = if opts and opts.palette then Bytes.toBuffer(opts.palette) else fetch(opts, "gfx/palette.lmp")
local pal = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp")
if pal and buffer.len(pal) < 768 then
pal = nil
end