model/bsp: BSP2 / 2PSB, Quake 1 / 2 / Half-Life lightmap atlas (TEXCOORD_1, .lit), tree / hulls / visibility in meta.bsp

Bsp.leafAt / contents / pvs point queries; tested on ericw-tools qbsp + vis output in all three Quake 1 layouts.
This commit is contained in:
4DBug committed 2026-11-01 19:03:55 -06:00
1 parent 2704653a3e
commit 67e116a6c6
13 files changed
+2556 -375

No files matched your search

+50 -1
View File
@@ -5,7 +5,7 @@
# miptex(name, w, h, rng, palette=None) -> bytes (four mip levels of random indices; WAD3 / BSP 30 add the palette)
# compile(ctx, text, files, qbsp_args, light_args=None, vis=False) -> { bsp, obj?, log }
# read_bsp(data) -> dict of the parsed lumps
import os, shutil, struct, subprocess, tempfile
import math, os, shutil, struct, subprocess, tempfile
Q1_LUMPS = ["entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting",
"clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models"]
@@ -151,3 +151,52 @@ def face_plane(b, f):
if f["side"]:
return (-nx, -ny, -nz, -d)
return (nx, ny, nz, d)
def write_bsp(b, lumps):
# reassembles a Quake 1 family BSP (b from read_bsp: its variant decides the header) from raw lumps
head = {"BSP2": b"BSP2", "2PSB": b"2PSB"}.get(b["variant"]) or struct.pack("<i", int(b["variant"][3:]))
off = len(head) + 8 * len(Q1_LUMPS)
body, dirs = b"", []
for n in Q1_LUMPS:
d = lumps[n]
dirs.append(struct.pack("<ii", off + len(body), len(d)))
body += d + b"\0" * ((4 - len(d) % 4) % 4)
return head + b"".join(dirs) + body
def extents(b, f):
# CalcSurfaceExtents: lightmap size in luxels (16 texels each) and the texture mins
ti = b["texinfo"][f["texinfo"]]
pts = face_points(b, f)
out = []
for j in range(2):
vals = [p[0] * ti[j * 4] + p[1] * ti[j * 4 + 1] + p[2] * ti[j * 4 + 2] + ti[j * 4 + 3] for p in pts]
lo, hi = math.floor(min(vals) / 16), math.ceil(max(vals) / 16)
out.append(hi - lo + 1)
return out
def light(b, rng, rgb=False):
# fills the lighting lump with random luxels at the extents of every face that is not TEX_SPECIAL (the nix light
# has no ray tracing backend); returns the new BSP bytes and { face: (w, h, ofs) }
big = b["variant"] in ("BSP2", "2PSB")
faces = bytearray(b["lumps"]["faces"])
size = 28 if big else 20
data = b""
out = {}
for i, f in enumerate(b["faces"]):
ti = b["texinfo"][f["texinfo"]]
o = i * size + (20 if big else 12)
if ti[9] & 1:
faces[o:o + 8] = bytes([255, 255, 255, 255]) + struct.pack("<i", -1)
continue
w, h = extents(b, f)
ofs = len(data)
data += bytes(rng.randrange(256) for _ in range(w * h * (3 if rgb else 1)))
faces[o:o + 8] = bytes([0, 255, 255, 255]) + struct.pack("<i", ofs)
out[i] = (w, h, ofs)
lumps = dict(b["lumps"])
lumps["faces"] = bytes(faces)
lumps["lighting"] = data
return write_bsp(b, lumps), out
+105 -4
View File
@@ -6,11 +6,14 @@
# q3: polygon, mesh and patch faces, two lightmaps, vertex colours; plus a .pk3 (zip) of it for assimp.
# References: the expected triangles per model and texture (positions, normals, texture coordinates, computed here
# with the documented rules), texture CRCs, entities; assimp's soup of the Quake III map.
# ericw: the room of map.py compiled by ericw-tools (qbsp with hulls + vis) as BSP 29, BSP2 and 2PSB; the lighting lump
# filled here at the extents of CalcSurfaceExtents (the nix light has no ray tracer), plus a .lit; expected: lightmap
# sizes per face, the PVS of every leaf (Mod_DecompressVis), contents at probe points in hulls 0..2 (SV_HullPointContents).
# tests/gen/bsp.luau { q1 = { data, palette, models = { [model] = { [texture] = { pos, uv, nrm } } }, textures,
# entities }, hl = ..., q2 = { ..., wal }, q3 = { ..., lightmaps, patchArea, assimp } }
import importlib.util, io, math, os, struct, zipfile, zlib
INPUTS = ["tools/fixtures/_quake_ref.py"]
INPUTS = ["tools/fixtures/_quake_ref.py", "tools/fixtures/_qbsp.py", "tools/fixtures/map.py"]
def ref(ctx):
@@ -110,7 +113,23 @@ def brush_map(rng, variant, pal):
L["vertices"] = b"".join(struct.pack("<3f", *v) for v in verts)
L["edges"] = b"".join(struct.pack("<2H", *e) for e in edges)
L["surfedges"] = b"".join(struct.pack("<i", s) for s in surfedges)
L["faces"] = b"".join(struct.pack("<HHiHH4Bi", p, sd, fe, ne, ti, 0, 255, 255, 255, -1) for p, sd, fe, ne, ti in flist)
# Half-Life / Quake II: RGB lightmaps at the CalcSurfaceExtents sizes (Quake 1 is covered by the ericw maps)
light, lms, fb = b"", [], b""
for fi, (p, sd, fe, ne, ti) in enumerate(flist):
if variant == "q1":
fb += struct.pack("<HHiHH4Bi", p, sd, fe, ne, ti, 255, 255, 255, 255, -1)
continue
s4, t4 = tis[ti]
pts = [verts[edges[abs(surfedges[fe + k])][0 if surfedges[fe + k] >= 0 else 1]] for k in range(ne)]
size = []
for v in (s4, t4):
vals = [q[0] * v[0] + q[1] * v[1] + q[2] * v[2] + v[3] for q in pts]
size.append(math.ceil(max(vals) / 16) - math.floor(min(vals) / 16) + 1)
lms.append({"face": fi, "w": size[0], "h": size[1], "ofs": len(light)})
fb += struct.pack("<HHiHH4Bi", p, sd, fe, ne, ti, 0, 255, 255, 255, len(light))
light += bytes(rng.randrange(256) for _ in range(size[0] * size[1] * 3))
L["faces"] = fb
L["lighting"] = light
if q2:
L["texinfo"] = b"".join(struct.pack("<8fii32si", *s, *t, 0, 0, texnames[k].encode(), -1) for s, t, k in texinfo)
L["models"] = b"".join(struct.pack("<9fiii", *([0.0] * 9), 0, first, 6) for first in (0, 6))
@@ -148,7 +167,7 @@ def brush_map(rng, variant, pal):
dirs.append((off + len(body), len(d)))
body += d + b"\0" * ((4 - len(d) % 4) % 4)
data = head + b"".join(struct.pack("<ii", *d) for d in dirs) + body
out = {"data": data, "models": {str(k): v for k, v in models.items()}, "names": texnames}
out = {"data": data, "models": {str(k): v for k, v in models.items()}, "names": texnames, "lightmaps": lms}
if not q2:
out["textures"] = mips
else:
@@ -222,6 +241,88 @@ def q3_map(rng):
return {"data": data, "models": expect, "lightmaps": lmcrc, "patchArea": 32.0 * 32.0, "shaders": [s.decode() for s in shaders]}
def load(ctx, name):
spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def pvs(b, leaf):
lf = b["leaves"][leaf]
vis, ofs = b["lumps"]["visibility"], lf[1]
n = b["models"][0][13]
if leaf == 0 or ofs < 0:
return []
bits, i = [], 0
while len(bits) < n and ofs < len(vis):
c = vis[ofs]
if c:
bits += [(c >> k) & 1 for k in range(8)]
ofs += 1
else:
bits += [0] * (8 * vis[ofs + 1])
ofs += 2
return [k + 1 for k in range(n) if k < len(bits) and bits[k]]
def contents(b, hull, p):
def side(plane):
nx, ny, nz, d, _ = b["planes"][plane]
return p[0] * nx + p[1] * ny + p[2] * nz - d
head = b["models"][0][9 + hull]
if hull == 0:
n = head
nn = len(b["nodes"])
while True:
nd = b["nodes"][n]
c = nd[1] if side(nd[0]) >= 0 else nd[2]
if b["variant"] == "bsp29":
c &= 0xFFFF
if c >= nn:
return b["leaves"][65535 - c][0]
elif c < 0:
return b["leaves"][-c - 1][0]
n = c
n = head
nc = len(b["clipnodes"])
while n >= 0:
cn = b["clipnodes"][n]
c = cn[1] if side(cn[0]) >= 0 else cn[2]
if b["variant"] == "bsp29":
c &= 0xFFFF
if c > nc:
c -= 65536
n = c
return n
def ericw(ctx, rng):
H = load(ctx, "_qbsp")
M = load(ctx, "map")
B = load(ctx, "brush")
world, door = M.layout(rng)
wad = H.wad([(n, 0x44, H.miptex(n, w, h, rng)) for n, w, h in M.TEX])
text = M.write(B, "quake", world, door, rng, "tex.wad")
probes = [(0, 0, 220), (-128, -128, 24), (200, 200, 100), (0, 0, 100), (-264, 0, 100), (0, 0, -8), (40, 0, 100),
(-240, -240, 30), (100, -150, 64), (300, 300, 300)]
out = {}
for name, args in (("bsp29", []), ("bsp2", ["-bsp2"]), ("2psb", ["-2psb"])):
res = H.compile(ctx, text, {"tex.wad": wad}, ["-nopercent"] + args, vis=True)
b = H.read_bsp(res["bsp"])
data, lm = H.light(b, rng)
b = H.read_bsp(data)
lit = b"QLIT" + struct.pack("<i", 1) + bytes(rng.randrange(256) for _ in range(len(b["lumps"]["lighting"]) * 3))
out[name] = {
"data": data, "lit": lit,
"lightmaps": [{"face": f, "w": w, "h": h, "ofs": o} for f, (w, h, o) in sorted(lm.items())],
"pvs": [pvs(b, i) for i in range(len(b["leaves"]))],
"probes": [{"p": list(p), "c": [contents(b, h, p) for h in range(3)]} for p in probes],
"faces": len(b["faces"]), "leaves": len(b["leaves"]), "visible": len(b["lumps"]["visibility"]),
}
return out
def generate(ctx):
rng = ctx.rng(101)
R = ref(ctx)
@@ -235,4 +336,4 @@ def generate(ctx):
with zipfile.ZipFile(zbuf, "w") as z:
z.writestr("maps/test.bsp", q3["data"])
q3["assimp"] = R.assimp_soup(ctx, zbuf.getvalue(), "pk3")
ctx.emit("bsp", {"q1": q1, "hl": hl, "q2": q2, "q3": q3})
ctx.emit("bsp", {"q1": q1, "hl": hl, "q2": q2, "q3": q3, "ericw": ericw(ctx, rng)})