Bsp.leafAt / contents / pvs point queries; tested on ericw-tools qbsp + vis output in all three Quake 1 layouts.
340 lines
16 KiB
Python
340 lines
16 KiB
Python
# BSP fixtures (tools/fixtures.py): maps written here from the bspfile.h layouts of the Quake / Quake II source
|
|
# releases and the Unofficial Quake 3 Map Specs: two boxes (the world and a brush entity "*1"), faces stored
|
|
# clockwise as the games do (some with side = 1 on a flipped plane), texture vectors, entities.
|
|
# q1 / hl: miptex lump with one embedded texture (Half-Life: with its palette) and one kept in a WAD (offsets 0);
|
|
# q2: texture names (.wal sizes through opts.files);
|
|
# 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", "tools/fixtures/_qbsp.py", "tools/fixtures/map.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("<f", struct.pack("<f", x))[0]
|
|
|
|
|
|
ENTS = b'{\n"classname" "worldspawn"\n"message" "fixture map"\n}\n{\n"classname" "info_player_start"\n"origin" "16 16 24"\n}\n{\n"classname" "func_door"\n"model" "*1"\n}\n\0'
|
|
|
|
|
|
def box(lo, hi):
|
|
# 6 quads, each clockwise seen from outside (the games' winding), with the outward normal
|
|
(x0, y0, z0), (x1, y1, z1) = lo, hi
|
|
return [
|
|
([(x0, y0, z1), (x0, y1, z1), (x1, y1, z1), (x1, y0, z1)], (0, 0, 1)),
|
|
([(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0)], (0, 0, -1)),
|
|
([(x1, y0, z0), (x1, y0, z1), (x1, y1, z1), (x1, y1, z0)], (1, 0, 0)),
|
|
([(x0, y0, z0), (x0, y1, z0), (x0, y1, z1), (x0, y0, z1)], (-1, 0, 0)),
|
|
([(x0, y1, z0), (x1, y1, z0), (x1, y1, z1), (x0, y1, z1)], (0, 1, 0)),
|
|
([(x0, y0, z0), (x0, y0, z1), (x1, y0, z1), (x1, y0, z0)], (0, -1, 0)),
|
|
]
|
|
|
|
|
|
def ccw_fan(poly, n):
|
|
# the decoder's rule: counter-clockwise about the face normal (Newell), fan from the first vertex
|
|
ax = ay = az = 0.0
|
|
k = len(poly)
|
|
for i in range(k):
|
|
(x1, y1, z1), (x2, y2, z2) = poly[i], poly[(i + 1) % k]
|
|
ax += (y1 - y2) * (z1 + z2)
|
|
ay += (z1 - z2) * (x1 + x2)
|
|
az += (x1 - x2) * (y1 + y2)
|
|
order = list(range(k)) if ax * n[0] + ay * n[1] + az * n[2] >= 0 else [0] + [k - i for i in range(1, k)]
|
|
out = []
|
|
for i in range(1, k - 1):
|
|
out += [order[0], order[i], order[i + 1]]
|
|
return out
|
|
|
|
|
|
def brush_map(rng, variant, pal):
|
|
q2 = variant == "q2"
|
|
faces = [(f, 0) for f in box((-64, -64, 0), (64, 64, 128))] + [(f, 1) for f in box((-8, -8, 8), (8, 8, 40))]
|
|
verts, edges, surfedges, planes, texinfo, flist = [], [(0, 0)], [], [], [], []
|
|
vindex = {}
|
|
|
|
def vid(p):
|
|
p = tuple(f32(c) for c in p)
|
|
if p not in vindex:
|
|
vindex[p] = len(verts)
|
|
verts.append(p)
|
|
return vindex[p]
|
|
texnames = ["brick", "door"] if q2 else ["brick", "+0door"]
|
|
sizes = [(16, 8), (8, 8)]
|
|
tis = []
|
|
for t in range(2):
|
|
s = [f32(rng.uniform(-1, 1)) for _ in range(3)] + [f32(rng.uniform(-8, 8))]
|
|
tt = [f32(rng.uniform(-1, 1)) for _ in range(3)] + [f32(rng.uniform(-8, 8))]
|
|
tis.append((s, tt))
|
|
texinfo.append((s, tt, t))
|
|
models = {}
|
|
for i, ((poly, n), model) in enumerate(faces):
|
|
tex = model
|
|
side = i % 3 == 2
|
|
pn = tuple(-c for c in n) if side else n
|
|
planes.append((pn, 0.0))
|
|
first = len(surfedges)
|
|
ids = [vid(p) for p in poly]
|
|
for k in range(len(ids)):
|
|
a, b = ids[k], ids[(k + 1) % len(ids)]
|
|
if k % 2 == 0:
|
|
edges.append((a, b))
|
|
surfedges.append(len(edges) - 1)
|
|
else:
|
|
edges.append((b, a))
|
|
surfedges.append(-(len(edges) - 1))
|
|
flist.append((len(planes) - 1, 1 if side else 0, first, len(ids), tex))
|
|
# expected triangles
|
|
fp = [tuple(f32(c) for c in p) for p in poly]
|
|
s, tt = tis[tex]
|
|
w, h = (sizes[tex] if variant != "q2" else (sizes[tex] if tex == 0 else (1, 1)))
|
|
e = models.setdefault(model, {}).setdefault(texnames[tex], {"pos": [], "uv": [], "nrm": []})
|
|
for c in ccw_fan(fp, n):
|
|
x, y, z = fp[c]
|
|
e["pos"] += [x, y, z]
|
|
e["nrm"] += list(n)
|
|
e["uv"] += [(x * s[0] + y * s[1] + z * s[2] + s[3]) / w, (x * tt[0] + y * tt[1] + z * tt[2] + tt[3]) / h]
|
|
# lumps
|
|
L = {}
|
|
L["entities"] = ENTS
|
|
L["planes"] = b"".join(struct.pack("<4fi", *n, d, 0) for n, d in planes)
|
|
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)
|
|
# 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))
|
|
else:
|
|
L["texinfo"] = b"".join(struct.pack("<8fii", *s, *t, k, 0) for s, t, k in texinfo)
|
|
L["models"] = b"".join(struct.pack("<9f4iiii", *([0.0] * 9), 0, 0, 0, 0, 0, first, 6) for first in (0, 6))
|
|
# miptex: texture 0 embedded (+ palette for HL), texture 1 in a WAD
|
|
mips, crcs = [], []
|
|
w, h = sizes[0]
|
|
pix = bytes(rng.randrange(256) for _ in range(w * h))
|
|
mip = struct.pack("<16sII", texnames[0].encode(), w, h)
|
|
o0 = 40
|
|
o1 = o0 + w * h
|
|
o2 = o1 + w * h // 4
|
|
o3 = o2 + w * h // 16
|
|
mip += struct.pack("<4I", o0, o1, o2, o3) + pix + bytes(w * h // 4 + w * h // 16 + w * h // 64)
|
|
hp = bytes(rng.randrange(256) for _ in range(768))
|
|
if variant == "hl":
|
|
mip += struct.pack("<H", 256) + hp + b"\0\0"
|
|
usepal = hp if variant == "hl" else pal
|
|
crcs.append(zlib.crc32(b"".join(usepal[i * 3:i * 3 + 3] + b"\xff" for i in pix)))
|
|
mip2 = struct.pack("<16sII4I", texnames[1].encode(), 8, 8, 0, 0, 0, 0)
|
|
lump = struct.pack("<ii", 2, 12) + struct.pack("<i", 12 + len(mip)) + mip + mip2
|
|
L["miptex"] = lump
|
|
mips = crcs
|
|
names = (["entities", "planes", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", "leaves",
|
|
"leaffaces", "leafbrushes", "edges", "surfedges", "models", "brushes", "brushsides", "pop", "areas", "areaportals"]
|
|
if q2 else ["entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting",
|
|
"clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models"])
|
|
head = (b"IBSP" + struct.pack("<i", 38)) if q2 else struct.pack("<i", 30 if variant == "hl" else 29)
|
|
off = len(head) + 8 * len(names)
|
|
body, dirs = b"", []
|
|
for n in names:
|
|
d = L.get(n, b"")
|
|
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, "lightmaps": lms}
|
|
if not q2:
|
|
out["textures"] = mips
|
|
else:
|
|
out["wal"] = struct.pack("<32sII", b"brick", 16, 8) + bytes(24)
|
|
return out
|
|
|
|
|
|
def q3_map(rng):
|
|
verts, meshverts, faces = [], [], []
|
|
expect = {}
|
|
def v(p, uv, lm, n, col):
|
|
verts.append((p, uv, lm, n, col))
|
|
return len(verts) - 1
|
|
# 2 polygon quads (shader 0, lightmap 0 / 1), one mesh triangle pair (shader 1), model 1 gets the last
|
|
quads = [([(0, 0, 0), (64, 0, 0), (64, 64, 0), (0, 64, 0)], 0, 0, 0), ([(0, 0, 64), (0, 64, 64), (64, 64, 64), (64, 0, 64)], 0, 1, 0),
|
|
([(8, 8, 8), (8, 8, 24), (24, 8, 24), (24, 8, 8)], 1, 0, 1)]
|
|
for poly, sh, lm, model in quads:
|
|
first = len(verts)
|
|
# the stored order is clockwise seen from the front (Quake III's culling): the normal is minus Newell's
|
|
(ax, ay, az), (bx, by, bz), (cx, cy, cz) = poly[0], poly[1], poly[2]
|
|
u, w = (bx - ax, by - ay, bz - az), (cx - ax, cy - ay, cz - az)
|
|
cr = (u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0])
|
|
ln = math.sqrt(sum(c * c for c in cr))
|
|
nrm = tuple(f32(-c / ln) for c in cr)
|
|
for p in poly:
|
|
v(tuple(f32(c) for c in p), (f32(rng.random()), f32(rng.random())), (f32(rng.random()), f32(rng.random())), nrm, tuple(rng.randrange(256) for _ in range(4)))
|
|
mv = len(meshverts)
|
|
meshverts += [0, 1, 2, 0, 2, 3]
|
|
faces.append((sh, 1 if model == 0 else 3, first, 4, mv, 6, lm))
|
|
e = expect.setdefault(str(model), {}).setdefault("%d:%d" % (sh, lm), {"pos": [], "uv": [], "lm": [], "col": []})
|
|
for tri in ((0, 1, 2), (0, 2, 3)):
|
|
for c in reversed(tri):
|
|
p, uv, lmuv, n, col = verts[first + c]
|
|
e["pos"] += list(p)
|
|
e["uv"] += list(uv)
|
|
e["lm"] += list(lmuv)
|
|
e["col"] += list(col)
|
|
# a flat 3x3 patch over [0, 32] x [0, 32] at z = 100, facing down (clockwise from below: rows along +y)
|
|
first = len(verts)
|
|
for j in range(3):
|
|
for i in range(3):
|
|
v((f32(i * 16.0), f32(j * 16.0), f32(100.0)), (i / 2, j / 2), (0.0, 0.0), (0.0, 0.0, -1.0), (255, 255, 255, 255))
|
|
faces.append((1, 2, first, 9, 0, 0, -1, 3, 3))
|
|
shaders = [b"textures/base/wall", b"textures/base/floor"]
|
|
L = {}
|
|
L["entities"] = ENTS
|
|
L["textures"] = b"".join(struct.pack("<64sii", s, 0, 1) for s in shaders)
|
|
L["planes"] = struct.pack("<4f", 0, 0, 1, 0)
|
|
L["models"] = struct.pack("<6fiiii", *([0.0] * 6), 0, 2, 0, 0) + struct.pack("<6fiiii", *([0.0] * 6), 2, 2, 0, 0)
|
|
# reorder: model 0 = faces 0, 1 (quads of model 0) ... the patch is face 3 (model 1 range is 2..3)
|
|
L["vertexes"] = b"".join(struct.pack("<10f4B", *p, *uv, *lm, *n, *c) for p, uv, lm, n, c in verts)
|
|
L["meshverts"] = b"".join(struct.pack("<i", m) for m in meshverts)
|
|
fb = b""
|
|
for f in faces:
|
|
sh, kind, first, n, mv, nmv, lm = f[:7]
|
|
w, h = (f[7], f[8]) if len(f) > 7 else (0, 0)
|
|
fb += struct.pack("<8i2i2i3f6f3f2i", sh, -1, kind, first, n, mv, nmv, lm, 0, 0, 0, 0, *([0.0] * 12), w, h)
|
|
L["faces"] = fb
|
|
lms = [bytes(rng.randrange(256) for _ in range(128 * 128 * 3)) for _ in range(2)]
|
|
L["lightmaps"] = b"".join(lms)
|
|
names = ["entities", "textures", "planes", "nodes", "leafs", "leaffaces", "leafbrushes", "models", "brushes",
|
|
"brushsides", "vertexes", "meshverts", "effects", "faces", "lightmaps", "lightvols", "visdata"]
|
|
off = 8 + 8 * len(names)
|
|
body, dirs = b"", []
|
|
for n in names:
|
|
d = L.get(n, b"")
|
|
dirs.append((off + len(body), len(d)))
|
|
body += d + b"\0" * ((4 - len(d) % 4) % 4)
|
|
data = b"IBSP" + struct.pack("<i", 46) + b"".join(struct.pack("<ii", *d) for d in dirs) + body
|
|
lmcrc = [zlib.crc32(b"".join(l[k * 3:k * 3 + 3] + b"\xff" for k in range(128 * 128))) for l in lms]
|
|
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)
|
|
pal = bytes(rng.randrange(256) for _ in range(768))
|
|
q1 = brush_map(rng, "q1", pal)
|
|
q1["palette"] = pal
|
|
hl = brush_map(rng, "hl", pal)
|
|
q2 = brush_map(rng, "q2", pal)
|
|
q3 = q3_map(rng)
|
|
zbuf = io.BytesIO()
|
|
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, "ericw": ericw(ctx, rng)})
|