Files
rosetta/src/Rosetta/model/vbsp/init.luau
T
2026-11-01 18:59:58 -06:00

445 lines
17 KiB
Luau

--!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", "codecs/model/Displacement", "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