model/vbsp: Source BSP 19-21 (L4D2 header, LZMA lumps): faces, displacements, static props v4-v13, brush entities, lights, entities, the pak lump as an Archive; KeyValues bench

This commit is contained in:
4DBug committed 2026-11-01 18:53:15 -06:00
1 parent 1c79609ecb
commit 52d2d7ebf9
11 files changed
+1459 -2

No files matched your search

+12
View File
@@ -1034,6 +1034,18 @@ local list: { Entry } = {
return require("@rosetta/model/usda")
end,
},
{
name = "vbsp",
category = "model",
path = "model/vbsp",
extensions = { "bsp" },
mime = { "model/x-vbsp" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "codecs/text/KeyValues", "codecs/model/Mat4", "containers/Zip", "containers/Archive" },
caps = { decode = true, encode = false, versions = { 19, 20, 21 }, displacements = true, staticProps = true, pak = true },
load = function()
return require("@rosetta/model/vbsp")
end,
},
{
name = "vox",
category = "model",
+318
View File
@@ -0,0 +1,318 @@
--!strict
-- model/vbsp/Faces: VBSP faces -> primitives, one per (model, texdata), from public/bspfile.h of the Source SDK 2013
-- (dface_t, texinfo_t, dtexdata_t, ddispinfo_t, CDispVert). Displacements tessellate as CCoreDispInfo::
-- GenerateDispSurf (rows along corner 0 -> 1, columns 0 -> 3, corner 0 nearest startPosition) with the alternating
-- triangle pattern of the SDK's disp tesselation; their normals come from the grid.
local Types = require("@rosetta/Types")
local Faces = {}
local Scene = Types.Scene
local readi32, readu16, readi16, readf32, readu8 = buffer.readi32, buffer.readu16, buffer.readi16, buffer.readf32, buffer.readu8
local writef32, writeu32 = buffer.writef32, buffer.writeu32
local sqrt = math.sqrt
export type Lump = { buf: buffer, at: number, size: number }
export type Input = {
planes: Lump,
vertices: Lump,
edges: Lump,
surfedges: Lump,
faces: Lump,
texinfo: Lump,
texdata: Lump,
models: Lump,
dispinfo: Lump,
dispverts: Lump,
tools: boolean, -- keep nodraw / skip / hint / sky faces
maxVertices: number,
}
export type Group = { model: number, texdata: number, pos: { number }, nrm: { number }, uv: { number }, blend: { number }?, idx: { number } }
-- SURF_SKY2D | SURF_SKY | SURF_NODRAW | SURF_HINT | SURF_SKIP
local TOOL_FLAGS = 0x2 + 0x4 + 0x80 + 0x100 + 0x200
local function cross(ax: number, ay: number, az: number, bx: number, by: number, bz: number): (number, number, number)
return ay * bz - az * by, az * bx - ax * bz, ax * by - ay * bx
end
local function emit(g: Group, x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, v: number): number
local pos, nrm, uv = g.pos, g.nrm, g.uv
local k = #pos
pos[k + 1], pos[k + 2], pos[k + 3] = x, y, z
nrm[k + 1], nrm[k + 2], nrm[k + 3] = nx, ny, nz
local q = #uv
uv[q + 1], uv[q + 2] = u, v
return k // 3
end
-- the 2^power x 2^power quads in the SDK's alternating diagonal pattern
local function dispTriangles(n: number, flip: boolean, base: number, idx: { number })
for i = 0, n - 2 do
for j = 0, n - 2 do
local a = base + i * n + j
local b, c, d = a + n, a + n + 1, a + 1
local tris: { number }
if (i + j) % 2 == 0 then
tris = { a, b, d, b, c, d }
else
tris = { a, b, c, a, c, d }
end
for t = 0, 1 do
local p, q, r = tris[t * 3 + 1], tris[t * 3 + 2], tris[t * 3 + 3]
if flip then
q, r = r, q
end
idx[#idx + 1], idx[#idx + 2], idx[#idx + 3] = p, q, r
end
end
end
end
local function displacement(I: Input, g: Group, d: number, poly: { number }, nx: number, ny: number, nz: number, tex: { number }): string?
local di = I.dispinfo
if (d + 1) * 176 > di.size then
return "dispinfo index out of range"
end
local o = di.at + d * 176
local b = di.buf
local sx, sy, sz = readf32(b, o), readf32(b, o + 4), readf32(b, o + 8)
local vstart, power = readi32(b, o + 12), readi32(b, o + 20)
if power < 1 or power > 4 then
return "displacement power " .. power
end
if #poly ~= 12 then
return nil -- not a quad: the base face is kept
end
local n = 2 ^ power + 1
local dv = I.dispverts
if vstart < 0 or (vstart + n * n) * 20 > dv.size then
return "displacement vertices out of range"
end
local best, bestD = 0, math.huge
for k = 0, 3 do
local dx, dy, dz = poly[k * 3 + 1] - sx, poly[k * 3 + 2] - sy, poly[k * 3 + 3] - sz
local dd = dx * dx + dy * dy + dz * dz
if dd < bestD then
best, bestD = k, dd
end
end
local c: { number } = table.create(12) :: any
for k = 0, 3 do
local s = ((best + k) % 4) * 3
c[k * 3 + 1], c[k * 3 + 2], c[k * 3 + 3] = poly[s + 1], poly[s + 2], poly[s + 3]
end
local P: { number } = table.create(n * n * 3) :: any
local base = #g.pos // 3
local blend = g.blend or {}
g.blend = blend
for i = 0, n - 1 do
local t = i / (n - 1)
local ax, ay, az = c[1] + (c[4] - c[1]) * t, c[2] + (c[5] - c[2]) * t, c[3] + (c[6] - c[3]) * t
local bx, by, bz = c[10] + (c[7] - c[10]) * t, c[11] + (c[8] - c[11]) * t, c[12] + (c[9] - c[12]) * t
for j = 0, n - 1 do
local s = j / (n - 1)
local x, y, z = ax + (bx - ax) * s, ay + (by - ay) * s, az + (bz - az) * s
local vo = dv.at + (vstart + i * n + j) * 20
local dist = readf32(dv.buf, vo + 12)
local k = (i * n + j) * 3
P[k + 1] = x + readf32(dv.buf, vo) * dist
P[k + 2] = y + readf32(dv.buf, vo + 4) * dist
P[k + 3] = z + readf32(dv.buf, vo + 8) * dist
local u = (x * tex[1] + y * tex[2] + z * tex[3] + tex[4]) / tex[9]
local v = (x * tex[5] + y * tex[6] + z * tex[7] + tex[8]) / tex[10]
emit(g, P[k + 1], P[k + 2], P[k + 3], 0, 0, 0, u, v)
blend[base + i * n + j + 1] = math.clamp(readf32(dv.buf, vo + 16) / 255, 0, 1)
end
end
-- grid normals by central differences, facing the base face's side
local ux, uy, uz = cross(c[4] - c[1], c[5] - c[2], c[6] - c[3], c[10] - c[1], c[11] - c[2], c[12] - c[3])
local sign = if ux * nx + uy * ny + uz * nz >= 0 then 1 else -1
local nrm = g.nrm
for i = 0, n - 1 do
local i0, i1 = math.max(i - 1, 0), math.min(i + 1, n - 1)
for j = 0, n - 1 do
local j0, j1 = math.max(j - 1, 0), math.min(j + 1, n - 1)
local a, b2 = (i1 * n + j) * 3, (i0 * n + j) * 3
local e, f = (i * n + j1) * 3, (i * n + j0) * 3
local x, y, z = cross(P[a + 1] - P[b2 + 1], P[a + 2] - P[b2 + 2], P[a + 3] - P[b2 + 3], P[e + 1] - P[f + 1], P[e + 2] - P[f + 2], P[e + 3] - P[f + 3])
local l = sqrt(x * x + y * y + z * z)
if l < 1e-12 then
x, y, z, l = nx, ny, nz, sign
end
local k = (base + i * n + j) * 3
nrm[k + 1], nrm[k + 2], nrm[k + 3] = x * sign / l, y * sign / l, z * sign / l
end
end
-- triangle (0, n, 1) winds along rows x columns: flip it when that does not face the face normal
dispTriangles(n, sign < 0, base, g.idx)
return nil
end
function Faces.build(I: Input): ({ Group }?, string?, number?)
local V, E, SE, F, TI, TD, P = I.vertices, I.edges, I.surfedges, I.faces, I.texinfo, I.texdata, I.planes
local nV, nE, nSE, nF = V.size // 12, E.size // 4, SE.size // 4, F.size // 56
local nTI, nTD, nP = TI.size // 72, TD.size // 32, P.size // 20
local faceModel: { [number]: number } = {}
local M = I.models
for m = 0, M.size // 48 - 1 do
local o = M.at + m * 48
local first, count = readi32(M.buf, o + 40), readi32(M.buf, o + 44)
if first >= 0 and count > 0 and first + count <= nF then
for f = first, first + count - 1 do
if faceModel[f] == nil then
faceModel[f] = m
end
end
end
end
local groups: { Group } = {}
local byKey: { [number]: Group } = {}
local skipped, verts = 0, 0
local poly: { number } = {}
for f = 0, nF - 1 do
local fo = F.at + f * 56
local fb = F.buf
local plane, side = readu16(fb, fo), readu8(fb, fo + 2)
local firstEdge, numEdges = readi32(fb, fo + 4), readi16(fb, fo + 8)
local ti, disp = readi16(fb, fo + 10), readi16(fb, fo + 12)
local model = faceModel[f] or 0
if numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or ti < 0 or ti >= nTI then
skipped += 1
continue
end
local to = TI.at + ti * 72
local flags, td = readi32(TI.buf, to + 64), readi32(TI.buf, to + 68)
if not I.tools and bit32.band(flags, TOOL_FLAGS) ~= 0 then
continue
end
local w, h = 1, 1
if td >= 0 and td < nTD then
w = math.max(readi32(TD.buf, TD.at + td * 32 + 16), 1)
h = math.max(readi32(TD.buf, TD.at + td * 32 + 20), 1)
else
td = -1
end
table.clear(poly)
local ok = true
for k = 0, numEdges - 1 do
local se = readi32(SE.buf, SE.at + (firstEdge + k) * 4)
local e = math.abs(se)
if e >= nE then
ok = false
break
end
local vi = readu16(E.buf, E.at + e * 4 + (if se >= 0 then 0 else 2))
if vi >= nV then
ok = false
break
end
local vo = V.at + vi * 12
poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] = readf32(V.buf, vo), readf32(V.buf, vo + 4), readf32(V.buf, vo + 8)
end
if not ok then
skipped += 1
continue
end
local po = P.at + plane * 20
local nx, ny, nz = readf32(P.buf, po), readf32(P.buf, po + 4), readf32(P.buf, po + 8)
if side ~= 0 then
nx, ny, nz = -nx, -ny, -nz
end
local key = model * 65536 + td + 1
local grp: Group = byKey[key]
if not grp then
grp = { model = model, texdata = td, pos = {}, nrm = {}, uv = {}, blend = nil :: { number }?, idx = {} }
byKey[key] = grp
table.insert(groups, grp)
end
local tex = {
readf32(TI.buf, to), readf32(TI.buf, to + 4), readf32(TI.buf, to + 8), readf32(TI.buf, to + 12),
readf32(TI.buf, to + 16), readf32(TI.buf, to + 20), readf32(TI.buf, to + 24), readf32(TI.buf, to + 28), w, h,
}
local before = #grp.pos
local done = false
if disp >= 0 then
local derr = displacement(I, grp, disp, poly, nx, ny, nz, tex)
if derr then
return nil, derr, fo
end
done = #grp.pos > before
end
if not done then
local n = numEdges
-- Newell's normal against the plane: the stored winding is clockwise from the front
local ax, ay, az = 0, 0, 0
for k = 0, n - 1 do
local a, b = k * 3, ((k + 1) % n) * 3
ax += (poly[a + 2] - poly[b + 2]) * (poly[a + 3] + poly[b + 3])
ay += (poly[a + 3] - poly[b + 3]) * (poly[a + 1] + poly[b + 1])
az += (poly[a + 1] - poly[b + 1]) * (poly[a + 2] + poly[b + 2])
end
local flip = ax * nx + ay * ny + az * nz < 0
local first = -1
for k = 0, n - 1 do
local x, y, z = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3]
local id = emit(grp, x, y, z, nx, ny, nz, (x * tex[1] + y * tex[2] + z * tex[3] + tex[4]) / w, (x * tex[5] + y * tex[6] + z * tex[7] + tex[8]) / h)
if first < 0 then
first = id
end
end
local idx = grp.idx
for k = 1, n - 2 do
local b, c = first + k, first + k + 1
if flip then
b, c = c, b
end
idx[#idx + 1], idx[#idx + 2], idx[#idx + 3] = first, b, c
end
if grp.blend then
for k = before // 3 + 1, #grp.pos // 3 do
grp.blend[k] = 0
end
end
end
verts += (#grp.pos - before) // 3
if verts > I.maxVertices then
return nil, "limit: over maxVertices", fo
end
end
return groups, nil, skipped
end
function Faces.primitive(g: Group, material: number?): Types.Primitive
local nv = #g.pos // 3
local pb, nb, ub = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8)
for k = 1, nv * 3 do
writef32(pb, (k - 1) * 4, g.pos[k])
writef32(nb, (k - 1) * 4, g.nrm[k])
end
for k = 1, nv * 2 do
writef32(ub, (k - 1) * 4, g.uv[k])
end
local ni = #g.idx
local ib = buffer.create(ni * 4)
for k = 1, ni do
writeu32(ib, (k - 1) * 4, g.idx[k])
end
local attrs: { [string]: Types.Accessor } = {
POSITION = Scene.accessor(pb, "f32", 3, nv),
NORMAL = Scene.accessor(nb, "f32", 3, nv),
TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv),
}
if g.blend then
local bb = buffer.create(nv * 4)
for k = 1, nv do
writef32(bb, (k - 1) * 4, g.blend[k] or 0)
end
attrs._BLEND = Scene.accessor(bb, "f32", 1, nv)
end
return {
attributes = attrs,
indices = Scene.accessor(ib, "u32", 1, ni),
mode = "triangles",
material = material,
}
end
return Faces
+90
View File
@@ -0,0 +1,90 @@
--!strict
-- model/vbsp/Props: the static prop game lump ("sprp", StaticPropLump_t versions 4 .. 13 of public/gamebspfile.h and
-- the variants srctools / BSPSource list). The record size is the lump's remainder over the prop count, so the
-- version only picks the optional fields: forced fade scale (v5+), uniform scale (v11 / v12: last f32), x/y/z scale
-- (v13: last 3 f32), u32 leaf indices (v12+).
local Props = {}
local readi32, readu16, readu8, readf32 = buffer.readi32, buffer.readu16, buffer.readu8, buffer.readf32
export type Prop = {
model: string,
origin: { number },
angles: { number }, -- pitch, yaw, roll (degrees)
scale: { number },
skin: number,
solid: number,
flags: number,
fadeMin: number,
fadeMax: number,
fadeScale: number?,
lightingOrigin: { number },
}
function Props.read(b: buffer, at: number, size: number, version: number, maxProps: number): ({ Prop }?, string?)
local e = at + size
local p = at
if p + 4 > e then
return {}, nil
end
local nd = readi32(b, p)
p += 4
if nd < 0 or p + nd * 128 > e then
return nil, "static prop model names past the end"
end
local names: { string } = table.create(nd) :: any
for i = 0, nd - 1 do
names[i + 1] = string.match(buffer.readstring(b, p + i * 128, 128), "^[^%z]*") :: string
end
p += nd * 128
if p + 4 > e then
return nil, "static prop leaves truncated"
end
local nl = readi32(b, p)
p += 4
local leafSize = if version >= 12 then 4 else 2
if nl < 0 or p + nl * leafSize + 4 > e then
return nil, "static prop leaves past the end"
end
p += nl * leafSize
local np = readi32(b, p)
p += 4
if np < 0 or np > maxProps then
return nil, "limit: " .. np .. " static props"
end
local out: { Prop } = table.create(np) :: any
if np == 0 then
return out, nil
end
local rec = (e - p) // np
if rec < 56 then
return nil, "static prop records shorter than 56 bytes"
end
for i = 0, np - 1 do
local o = p + i * rec
local mi = readu16(b, o + 24)
local scale = { 1, 1, 1 }
if version == 13 and rec >= 88 then
scale = { readf32(b, o + rec - 12), readf32(b, o + rec - 8), readf32(b, o + rec - 4) }
elseif (version == 11 or version == 12) and rec >= 80 then
local s = readf32(b, o + rec - 4)
scale = { s, s, s }
end
out[i + 1] = {
model = names[mi + 1] or "",
origin = { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) },
angles = { readf32(b, o + 12), readf32(b, o + 16), readf32(b, o + 20) },
scale = scale,
solid = readu8(b, o + 30),
flags = readu8(b, o + 31),
skin = readi32(b, o + 32),
fadeMin = readf32(b, o + 36),
fadeMax = readf32(b, o + 40),
lightingOrigin = { readf32(b, o + 44), readf32(b, o + 48), readf32(b, o + 52) },
fadeScale = if version >= 5 and rec >= 60 then readf32(b, o + 56) else nil,
}
end
return out, nil
end
return Props
+444
View File
@@ -0,0 +1,444 @@
--!strict
-- model/vbsp: compiled Source engine maps (VBSP 19 / 20 / 21: HL2, TF2, L4D2's lump header, Portal 2 / CS:GO), read,
-- from public/bspfile.h and gamebspfile.h of the Source SDK 2013 (no code taken). Supports: brush faces per bmodel and
-- texdata, displacements, static props (game lump v4 .. v13) as nodes with extras.model, brush entities placed by
-- their origin / angles, point / spot / sun lights, entities (meta.entities), Valve LZMA lumps, the pak lump as a
-- nested Archive (meta.pak). Map units (inches), z up. Not supported: lightmaps, visibility, collision, Xbox 360
-- (big-endian) and Titanfall / Apex rBSP, writing.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Lzma = require("@rosetta/codecs/compress/Lzma")
local KeyValues = require("@rosetta/codecs/text/KeyValues")
local Mat4 = require("@rosetta/codecs/model/Mat4")
local Zip = require("@rosetta/containers/Zip")
local Archive = require("@rosetta/containers/Archive")
local Faces = require("@rosetta/model/vbsp/Faces")
local Props = require("@rosetta/model/vbsp/Props")
-- ------------------------------------------------------------------------------------------------ contract
local Vbsp = {
name = "vbsp",
category = "model",
extensions = { "bsp" },
mime = { "model/x-vbsp" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Lzma", "codecs/text/KeyValues", "codecs/model/Mat4", "containers/Zip", "containers/Archive" },
caps = { decode = true, encode = false, versions = { 19, 20, 21 }, displacements = true, staticProps = true, pak = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
tools: boolean?, -- keep nodraw / skip / hint / sky faces, default false
pak: boolean?, -- meta.pak and textures from it, default true
maxBytes: number?, -- per decompressed lump, default 2^28
maxVertices: number?, -- default 2^24
maxProps: number?, -- default 2^20
}
-- ------------------------------------------------------------------------------------------------ constants
local L = {
ENTITIES = 0, PLANES = 1, TEXDATA = 2, VERTEXES = 3, TEXINFO = 6, FACES = 7, EDGES = 12, SURFEDGES = 13,
MODELS = 14, DISPINFO = 26, DISP_VERTS = 33, GAME_LUMP = 35, PAKFILE = 40, TEXDATA_STRING_DATA = 43,
TEXDATA_STRING_TABLE = 44, FACES_HDR = 58,
}
local HEADER = 8 + 64 * 16 + 4
local SPRP = 0x73707270 -- 'sprp' read as a little-endian i32
-- ------------------------------------------------------------------------------------------------ sniff
function Vbsp.sniff(r: Bytes.Reader): number
if r:remaining() < HEADER or r:peek(4) ~= "VBSP" then
return 0
end
local v = buffer.readi32(r.buf, r.pos + 4)
return if v >= 19 and v <= 21 then 1 else 0.5
end
-- ------------------------------------------------------------------------------------------------ decode
type Lump = Faces.Lump
local function angles(p: number, y: number, r: number): { number }
return Mat4.quat(Mat4.euler(r, p, y, "xyz"))
end
local function qmul(a: { number }, b: { number }): { number }
local ax, ay, az, aw = a[1], a[2], a[3], a[4]
local bx, by, bz, bw = b[1], b[2], b[3], b[4]
return {
aw * bx + ax * bw + ay * bz - az * by,
aw * by - ax * bz + ay * bw + az * bx,
aw * bz + ax * by - ay * bx + az * bw,
aw * bw - ax * bx - ay * by - az * bz,
}
end
local function vec3(s: any): { number }?
if type(s) ~= "string" then
return nil
end
local x, y, z = string.match(s, "^%s*(%S+)%s+(%S+)%s+(%S+)")
local a, b, c = tonumber(x), tonumber(y), tonumber(z)
if a and b and c then
return { a, b, c }
end
return nil
end
-- Valve's LZMA lump: "LZMA", u32 actualSize, u32 lzmaSize, 5 property bytes, the raw stream
local function unlzma(b: buffer, at: number, size: number, maxBytes: number): (buffer?, string?)
if size < 17 then
return nil, "truncated LZMA lump header"
end
local actual, packed = buffer.readu32(b, at + 4), buffer.readu32(b, at + 8)
if actual > maxBytes then
return nil, "limit: LZMA lump of " .. actual .. " bytes"
end
if packed > size - 17 then
return nil, "LZMA lump runs past the end"
end
local props = buffer.create(5)
buffer.copy(props, 0, b, at + 12, 5)
local out, err = Lzma.lzma(b, at + 17, packed, props, actual, { maxBytes = maxBytes })
if not out then
return nil, "LZMA lump: " .. tostring(if type(err) == "table" then err.message else err)
end
return out, nil
end
local function isLzma(b: buffer, at: number, size: number): boolean
return size >= 17 and buffer.readstring(b, at, 4) == "LZMA"
end
local function pakArchive(src: buffer, maxBytes: number): (any, Err.Err?)
local zc, err = Zip.open(src)
if not zc then
return nil, err
end
local a = Archive.new("zip")
for _, e in zc:list() do
local entry: any = {
name = e.name,
size = e.size,
compressedSize = e.compressedSize,
method = if e.method == 0 then "stored" elseif e.method == 8 then "deflate" elseif e.method == 14 then "lzma" else tostring(e.method),
mtime = e.mtime,
dir = e.isDir,
}
entry.load = function(): (buffer?, Err.Err?)
if e.method ~= 14 then
return zc:read(e)
end
-- APPNOTE 5.8.8: u8 major, u8 minor, u16 properties size, properties, then the LZMA stream (CS:GO paks)
local zb = zc.buf
for _, s in Zip._starts(zb, e) do
if s + 9 <= buffer.len(zb) then
local psize = buffer.readu16(zb, s + 2)
local start = s + 4 + psize
local n = math.min(e.compressedSize - 4 - psize, buffer.len(zb) - start)
if psize >= 5 and n > 0 and e.size <= maxBytes then
local props = buffer.create(5)
buffer.copy(props, 0, zb, s + 4, 5)
local out = Lzma.lzma(zb, start, n, props, e.size, { maxBytes = maxBytes })
if out then
return out, nil
end
end
end
end
return nil, Err.new(Err.CORRUPT, e.name .. ": bad LZMA entry")
end
Archive.put(a, entry)
end
a.meta.source = { format = "zip", lump = "pakfile" }
return a, nil
end
local function light(scene: Types.Scene, e: any, class: string): (number?, { number }?)
local l = vec3(e._light)
local rgb: { number } = { 1, 1, 1 }
local intensity = 1
if l then
rgb = { l[1] / 255, l[2] / 255, l[3] / 255 }
local m = type(e._light) == "string" and string.match(e._light, "^%s*%S+%s+%S+%s+%S+%s+(%S+)")
intensity = (m and tonumber(m)) or 200
end
local lt: Types.Light = nil :: any
if class == "light" then
lt = { name = nil :: string?, type = "point", color = rgb, intensity = intensity }
elseif class == "light_spot" then
local outer = tonumber(e._cone) or 45
local inner = tonumber(e._inner_cone) or math.min(30, outer)
lt = { name = nil :: string?, type = "spot", color = rgb, intensity = intensity, innerCone = math.rad(math.min(inner, outer)), outerCone = math.rad(outer) }
else
lt = { name = nil :: string?, type = "directional", color = rgb, intensity = intensity }
end
lt.name = if type(e.targetname) == "string" then e.targetname else class
table.insert(scene.lights, lt :: any)
local ang = vec3(e.angles) or { 0, 0, 0 }
if type(e.pitch) == "string" and tonumber(e.pitch) then
ang[1] = -(tonumber(e.pitch) :: number) -- the FGD's angle_negative_pitch
end
-- the light shines along the entity's forward (+x); a glTF light along -z
return #scene.lights, qmul(angles(ang[1], ang[2], ang[3]), Mat4.axisAngle(0, 1, 0, -90))
end
function Vbsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local o: DecodeOptions = opts or {}
local b, base = r.buf, r.base
local size = r.limit - r.base
if size < HEADER then
return nil, Err.new(Err.TRUNCATED, "header", 0)
end
if buffer.readstring(b, base, 4) ~= "VBSP" then
return nil, Err.new(Err.CORRUPT, "not a VBSP file", 0)
end
local version = buffer.readi32(b, base + 4)
if version < 19 or version > 21 then
return nil, Err.new(Err.UNSUPPORTED, "VBSP version " .. version, 4)
end
local maxBytes = o.maxBytes or 2 ^ 28
-- L4D2 swaps lump_t to { version, fileofs, filelen, fourCC }: the first lump's version is 0 where an offset is >= 1036
local l4d2 = version == 21 and buffer.readu32(b, base + 8) == 0 and buffer.readu32(b, base + 12) >= HEADER
local dir: { { at: number, size: number, version: number, fourcc: number } } = {}
for i = 0, 63 do
local p = base + 8 + i * 16
local a, c, d, f = buffer.readi32(b, p), buffer.readi32(b, p + 4), buffer.readi32(b, p + 8), buffer.readi32(b, p + 12)
local at, n, v = a, c, d
if l4d2 then
v, at, n = a, c, d
end
if n < 0 or at < 0 or (n > 0 and at + n > size) then
return nil, Err.new(Err.TRUNCATED, "lump " .. i .. " past the end", p - base)
end
dir[i] = { at = at, size = n, version = v, fourcc = f }
end
local cache: { [number]: Lump } = {}
local compressed = false
local function lump(i: number): (Lump?, string?)
local c = cache[i]
if c then
return c, nil
end
local d = dir[i]
local out: Lump
if d.size > 0 and isLzma(b, base + d.at, d.size) and i ~= L.PAKFILE and i ~= L.GAME_LUMP then
local u, err = unlzma(b, base + d.at, d.size, maxBytes)
if not u then
return nil, "lump " .. i .. ": " .. tostring(err)
end
compressed = true
out = { buf = u, at = 0, size = buffer.len(u) }
else
out = { buf = b, at = base + d.at, size = d.size }
end
cache[i] = out
return out, nil
end
local need: { [string]: Lump } = {}
for name, idx in { planes = L.PLANES, vertices = L.VERTEXES, edges = L.EDGES, surfedges = L.SURFEDGES, faces = L.FACES, texinfo = L.TEXINFO, texdata = L.TEXDATA, models = L.MODELS, dispinfo = L.DISPINFO, dispverts = L.DISP_VERTS, strings = L.TEXDATA_STRING_DATA, table = L.TEXDATA_STRING_TABLE, entities = L.ENTITIES } :: { [string]: number } do
local lp, err = lump(idx)
if not lp then
return nil, Err.from(err)
end
need[name] = lp
end
if need.faces.size == 0 then
local hdr, err = lump(L.FACES_HDR)
if not hdr then
return nil, Err.from(err)
end
need.faces = hdr
end
local groups, ferr, skipped = Faces.build({
planes = need.planes, vertices = need.vertices, edges = need.edges, surfedges = need.surfedges,
faces = need.faces, texinfo = need.texinfo, texdata = need.texdata, models = need.models,
dispinfo = need.dispinfo, dispverts = need.dispverts, tools = o.tools == true,
maxVertices = o.maxVertices or 2 ^ 24,
})
if not groups then
return nil, Err.from(ferr, skipped and skipped - base)
end
local scene = Types.Scene.new()
scene.meta.up = "z"
scene.meta.unit = 0.0254
local pak: any = nil
local pd = dir[L.PAKFILE]
if o.pak ~= false and pd.size > 0 then
local src = buffer.create(pd.size)
buffer.copy(src, 0, b, base + pd.at, pd.size)
pak = pakArchive(src, maxBytes)
scene.meta.pak = pak
end
-- texdata -> material + texture (materials/<name>.vtf, from the pak when it is there)
local TD, ST, SS = need.texdata, need.table, need.strings
local nTD = TD.size // 32
local matOf: { [number]: number } = {}
local function material(td: number): number?
if td < 0 or td >= nTD then
return nil
end
local m = matOf[td]
if m then
return m
end
local to = TD.at + td * 32
local si = buffer.readi32(TD.buf, to + 12)
local name = "texdata" .. td
if si >= 0 and (si + 1) * 4 <= ST.size then
local off = buffer.readi32(ST.buf, ST.at + si * 4)
if off >= 0 and off < SS.size then
name = string.match(buffer.readstring(SS.buf, SS.at + off, math.min(SS.size - off, 256)), "^[^%z]*") :: string
end
end
local path = "materials/" .. string.lower((string.gsub(name, "\\", "/")))
local tex: Types.Texture = { name = name, uri = path .. ".vtf" }
if pak then
local zc = pak :: any
local ok, data = pcall(zc.read, zc, path .. ".vtf")
if ok and type(data) == "buffer" then
tex.data, tex.mime, tex.uri = data, "image/vnd-valve.source.texture", nil
end
end
table.insert(scene.textures, tex)
local mat = Types.Scene.material(name)
mat.metallic = 0
mat.baseColorTexture = { texture = #scene.textures }
mat.extras = {
vbsp = {
vmt = path .. ".vmt",
width = buffer.readi32(TD.buf, to + 16),
height = buffer.readi32(TD.buf, to + 20),
reflectivity = { buffer.readf32(TD.buf, to), buffer.readf32(TD.buf, to + 4), buffer.readf32(TD.buf, to + 8) },
},
}
table.insert(scene.materials, mat)
matOf[td] = #scene.materials
return #scene.materials
end
local root: Types.Node = { name = "vbsp", children = {} }
table.insert(scene.nodes, root)
scene.roots[1] = 1
local modelNode: { [number]: number } = {}
for _, g in groups do
local node = modelNode[g.model]
if not node then
local name = if g.model == 0 then "world" else "*" .. g.model
table.insert(scene.meshes, { name = name, primitives = {} })
table.insert(scene.nodes, { name = name, children = {}, mesh = #scene.meshes, extras = { vbsp = { model = g.model } } })
node = #scene.nodes
modelNode[g.model] = node
table.insert(root.children, node)
end
local mesh = scene.meshes[scene.nodes[node].mesh :: number]
table.insert(mesh.primitives, Faces.primitive(g, material(g.texdata)))
end
-- entities
local E = need.entities
local text = string.match(buffer.readstring(E.buf, E.at, E.size), "^[^%z]*") :: string
local blocks, eerr = KeyValues.entities(text)
if not blocks then
return nil, Err.new((eerr :: Err.Err).code, "entity lump: " .. (eerr :: Err.Err).message, dir[L.ENTITIES].at)
end
local ents: { any } = table.create(#blocks)
for i, blk in blocks do
local e = KeyValues.toObject(blk)
ents[i] = e
local class = if type(e.classname) == "string" then e.classname else ""
local mdl = if type(e.model) == "string" then string.match(e.model, "^%*(%d+)$") else nil
local mi = mdl and tonumber(mdl)
if mi and mi > 0 and modelNode[mi] then
local node = scene.nodes[modelNode[mi]]
node.name = if type(e.targetname) == "string" then e.targetname else class
local org = vec3(e.origin)
if org then
node.translation = org
end
local ang = vec3(e.angles)
if ang then
node.rotation = angles(ang[1], ang[2], ang[3])
end
local x: any = node.extras
x.vbsp.entity = i
elseif class == "light" or class == "light_spot" or class == "light_environment" then
local li, rot = light(scene, e, class)
table.insert(scene.nodes, { name = scene.lights[li :: number].name, children = {}, light = li, translation = vec3(e.origin), rotation = rot, extras = { vbsp = { entity = i } } })
table.insert(root.children, #scene.nodes)
end
end
scene.meta.entities = ents
-- game lumps
local spVersion: number? = nil
local G = dir[L.GAME_LUMP]
if G.size >= 4 then
local ga = base + G.at
local count = buffer.readi32(b, ga)
if count < 0 or 4 + count * 16 > G.size then
return nil, Err.new(Err.CORRUPT, "game lump directory", G.at)
end
for k = 0, count - 1 do
local eo = ga + 4 + k * 16
local id, flags, ver = buffer.readi32(b, eo), buffer.readu16(b, eo + 4), buffer.readu16(b, eo + 6)
local off, len = buffer.readi32(b, eo + 8), buffer.readi32(b, eo + 12)
if id == SPRP then
if off < 0 or len < 0 or off > size then
return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base)
end
local pb, pat, plen = b, base + off, len
if bit32.band(flags, 1) ~= 0 or isLzma(b, base + off, math.min(size - off, 17)) then
if off + 17 > size then
return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base)
end
local u, err = unlzma(b, base + off, size - off, maxBytes)
if not u then
return nil, Err.from(err, off)
end
pb, pat, plen = u, 0, buffer.len(u)
compressed = true
elseif off + len > size then
return nil, Err.new(Err.TRUNCATED, "static prop lump past the end", eo - base)
end
local props, perr = Props.read(pb, pat, plen :: number, ver, o.maxProps or 2 ^ 20)
if not props then
return nil, Err.from(perr, off)
end
spVersion = ver
for pi, p in props do
local nm = string.match(p.model, "([^/\\]+)%.%w+$") or p.model
table.insert(scene.nodes, {
name = nm,
children = {},
translation = p.origin,
rotation = angles(p.angles[1], p.angles[2], p.angles[3]),
scale = if p.scale[1] ~= 1 or p.scale[2] ~= 1 or p.scale[3] ~= 1 then p.scale else nil,
extras = {
model = p.model,
vbsp = { staticProp = pi, angles = p.angles, skin = p.skin, solid = p.solid, flags = p.flags, fadeMin = p.fadeMin, fadeMax = p.fadeMax, lightingOrigin = p.lightingOrigin },
},
})
table.insert(root.children, #scene.nodes)
end
end
end
end
scene.meta.skippedFaces = skipped
scene.meta.source = {
format = "vbsp",
version = version,
variant = if l4d2 then "l4d2" else "v" .. version,
mapRevision = buffer.readi32(b, base + HEADER - 4),
compressed = compressed,
staticPropVersion = spVersion,
entities = text,
}
return scene, nil
end
return Vbsp