Entities as nodes (keys in extras, brushes as parsed), brushes through codecs/model/Brush, patchDef2 / patchDef3 through codecs/model/Patch, texture sizes from WAD2 / WAD3 / .wal / images; tested against ericw-tools qbsp.
316 lines
11 KiB
Luau
316 lines
11 KiB
Luau
--!strict
|
|
-- model/map: editor .map files of Quake, Half-Life (Valve 220), Quake II (surface / content flags) and Quake III
|
|
-- (brushDef brush primitives, patchDef2; patchDef3 meshes), read and write. Grammar of the qbsp / q3map2 parsers (no
|
|
-- code taken). Brushes become polygons through codecs/model/Brush (optionally CSG'd and merged), patches through
|
|
-- codecs/model/Patch; a mesh per entity with brushes; entities as nodes with their keys in extras. Texture sizes from
|
|
-- opts.textureSizes, the worldspawn's WADs, .wal files or images through resolve; else 64 x 64. Not supported: Doom 3
|
|
-- brushDef3, Build engine maps (binary: model/buildmap), compiling (no BSP, vis or light).
|
|
|
|
-- ------------------------------------------------------------------------------------------------ requires
|
|
local Err = require("@rosetta/core/Err")
|
|
local Bytes = require("@rosetta/core/Bytes")
|
|
local Input = require("@rosetta/core/Input")
|
|
local Types = require("@rosetta/Types")
|
|
local Miptex = require("@rosetta/codecs/image/Miptex")
|
|
local Brush = require("@rosetta/codecs/model/Brush")
|
|
local Parse = require("@rosetta/model/map/Parse")
|
|
local Write = require("@rosetta/model/map/Write")
|
|
local Build = require("@rosetta/model/map/Build")
|
|
|
|
-- ------------------------------------------------------------------------------------------------ contract
|
|
local Map = {
|
|
name = "map",
|
|
category = "model",
|
|
extensions = { "map" },
|
|
mime = { "text/x-quake-map" },
|
|
deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" },
|
|
caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true },
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ types
|
|
export type DecodeOptions = {
|
|
hull: boolean?, -- drop faces inside / touching other brushes of the same entity, default false
|
|
merge: boolean?, -- merge coplanar faces with the same texture projection, default false
|
|
epsilon: number?, -- default 1e-3
|
|
patchLevel: number?, -- patchDef2 segments per sub-patch, default 4
|
|
skip: { string }?, -- texture names left out of the meshes ("clip", "skip", "common/caulk", ...)
|
|
textureSizes: { [string]: { number } }?, -- name -> { width, height }
|
|
resolve: ((uri: string) -> (buffer | string)?)?,
|
|
files: { [string]: buffer | string }?,
|
|
decodeImage: ((buf: buffer) -> (Types.Image?, Err.Err?))?, -- Quake III: texture image sizes
|
|
maxBrushes: number?, -- default 2^20
|
|
maxPolygons: number?, -- default 2^20
|
|
}
|
|
export type EncodeOptions = {
|
|
variant: string?, -- "valve220" converts Quake standard faces to Valve 220 axes; default: as stored
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ sniff
|
|
function Map.sniff(r: Bytes.Reader): number
|
|
local head = r:peek(math.min(r:remaining(), 4096))
|
|
if #head < 2 or string.find(head, "[%z\1-\8\14-\31]") then
|
|
return 0
|
|
end
|
|
if string.sub(head, 1, 3) == "\239\187\191" then
|
|
head = string.sub(head, 4)
|
|
end
|
|
local s = head
|
|
local game = false
|
|
while true do
|
|
local c = string.match(s, "^%s*//[^\n]*\n?()")
|
|
if not c then
|
|
break
|
|
end
|
|
if string.match(s, "^%s*//%s*Game:") then
|
|
game = true
|
|
end
|
|
s = string.sub(s, c :: number)
|
|
end
|
|
local body = string.match(s, '^%s*{%s*"[^"\n]*"%s*"') or string.match(s, "^%s*{%s*{%s*[%(bp]")
|
|
if not body then
|
|
return if game and string.match(s, "^%s*{") then 0.6 else 0
|
|
end
|
|
return if game or string.find(head, '"classname"', 1, true) then 0.9 else 0.6
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ decode
|
|
local function variantOf(m: Parse.Map): string
|
|
local game = string.lower(m.game or "")
|
|
local fmt = string.lower(m.mapFormat or "")
|
|
local q2, valve, q3 = false, false, false
|
|
for _, e in m.entities do
|
|
if e.keys.mapversion == "220" then
|
|
valve = true
|
|
end
|
|
for _, b in e.brushes do
|
|
if b.type ~= "brush" then
|
|
q3 = true
|
|
end
|
|
for _, f in b.faces or {} do
|
|
if f.u then
|
|
valve = true
|
|
elseif f.flags and #f.flags >= 3 then
|
|
q2 = true
|
|
end
|
|
end
|
|
end
|
|
end
|
|
if q3 or string.find(game, "quake 3") or string.find(game, "quake iii") or fmt == "quake3" or fmt == "quake3 (valve)" then
|
|
return "quake3"
|
|
end
|
|
if string.find(game, "quake 2") or string.find(game, "quake ii") or fmt == "quake2" or fmt == "quake2 (valve)" then
|
|
return "quake2"
|
|
end
|
|
if valve or fmt == "valve" then
|
|
return "valve220"
|
|
end
|
|
return if q2 then "quake2" else "quake"
|
|
end
|
|
|
|
local function sizer(m: Parse.Map, variant: string, opts: DecodeOptions?): (name: string) -> (number, number, boolean)
|
|
local cache: { [string]: { number } } = {}
|
|
local wads: { { buf: buffer, lumps: { Miptex.Lump } } }? = nil
|
|
local function loadWads(): { { buf: buffer, lumps: { Miptex.Lump } } }
|
|
local list = {}
|
|
local ws = m.entities[1] and m.entities[1].keys
|
|
local spec = ws and (ws.wad or ws._wad) or ""
|
|
for path in string.gmatch(spec, "[^;]+") do
|
|
local p = string.gsub(path, "\\", "/")
|
|
local b = Input.sibling(opts, p) or Input.sibling(opts, string.match(p, "([^/]+)$") or p)
|
|
if b then
|
|
local lumps = Miptex.wad(b, 0, buffer.len(b))
|
|
if lumps then
|
|
table.insert(list, { buf = b, lumps = lumps })
|
|
end
|
|
end
|
|
end
|
|
return list
|
|
end
|
|
return function(name: string): (number, number, boolean)
|
|
local c = cache[name]
|
|
if c then
|
|
return c[1], c[2], c[3] == 1
|
|
end
|
|
local w: number, h: number = 0, 0
|
|
local given = opts and opts.textureSizes and opts.textureSizes[name]
|
|
if type(given) == "table" and type(given[1]) == "number" and type(given[2]) == "number" then
|
|
w, h = given[1] :: number, given[2] :: number
|
|
elseif variant == "quake" or variant == "valve220" then
|
|
wads = wads or loadWads()
|
|
for i = #(wads :: any), 1, -1 do
|
|
local wd = (wads :: any)[i]
|
|
local l = Miptex.find(wd.lumps, name)
|
|
if l then
|
|
local hd = Miptex.header(wd.buf, l.offset, l.disksize)
|
|
if hd then
|
|
w, h = hd.width, hd.height
|
|
break
|
|
end
|
|
end
|
|
end
|
|
elseif variant == "quake2" then
|
|
local wal = Input.sibling(opts, "textures/" .. name .. ".wal")
|
|
if wal and buffer.len(wal) >= 40 then
|
|
w, h = buffer.readu32(wal, 32), buffer.readu32(wal, 36)
|
|
end
|
|
elseif opts and opts.decodeImage then
|
|
for _, ext in { ".tga", ".jpg", ".png" } do
|
|
local b = Input.sibling(opts, "textures/" .. name .. ext)
|
|
if b then
|
|
local ok, img = pcall(opts.decodeImage :: any, b)
|
|
if ok and img then
|
|
w, h = img.width, img.height
|
|
break
|
|
end
|
|
end
|
|
end
|
|
end
|
|
local fw: number, fh: number = w :: number, h :: number
|
|
local known = fw > 0 and fh > 0
|
|
if not known then
|
|
fw, fh = 64, 64
|
|
end
|
|
cache[name] = { fw, fh, if known then 1 else 0 }
|
|
return fw, fh, known
|
|
end
|
|
end
|
|
|
|
function Map.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
|
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
|
local m, msg, at = Parse.parse(text, opts and opts.maxBrushes)
|
|
if not m then
|
|
return nil, Err.from(msg, at)
|
|
end
|
|
if #m.entities == 0 then
|
|
return nil, Err.new(Err.CORRUPT, "no entities", 0)
|
|
end
|
|
local variant = variantOf(m)
|
|
local scene, err = Build.scene(m, {
|
|
variant = variant,
|
|
size = sizer(m, variant, opts),
|
|
hull = opts and opts.hull,
|
|
merge = opts and opts.merge,
|
|
epsilon = opts and opts.epsilon,
|
|
patchLevel = opts and opts.patchLevel,
|
|
skip = opts and opts.skip,
|
|
maxPolygons = opts and opts.maxPolygons,
|
|
})
|
|
if not scene then
|
|
return nil, Err.from(err)
|
|
end
|
|
local counts = scene.meta.counts
|
|
scene.meta.counts = nil
|
|
scene.meta.source = { format = "map", variant = variant, game = m.game, mapFormat = m.mapFormat, entities = #m.entities, brushes = counts.brushes, patches = counts.patches }
|
|
return scene, nil
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ encode
|
|
local function toValve(f: Parse.Face): Parse.Face
|
|
if f.u or f.matrix then
|
|
return f
|
|
end
|
|
local bf = Build.face(f)
|
|
if not bf or not bf.vecs then
|
|
return f
|
|
end
|
|
local v = bf.vecs
|
|
local out = table.clone(f)
|
|
out.offset = nil
|
|
out.u, out.v = { v[1][1], v[1][2], v[1][3], v[1][4] }, { v[2][1], v[2][2], v[2][3], v[2][4] }
|
|
out.rotation, out.scale = 0, { 1, 1 }
|
|
return out
|
|
end
|
|
|
|
local function fmtNum(x: number): string
|
|
return Write.num(x)
|
|
end
|
|
|
|
function Map.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
|
|
if type(scene) ~= "table" or type(scene.nodes) ~= "table" then
|
|
return nil, Err.new(Err.ARG, "expected a Scene")
|
|
end
|
|
local valve = opts and opts.variant == "valve220"
|
|
local ents: { any } = {}
|
|
for _, node in scene.nodes do
|
|
local ex: any = node.extras
|
|
if type(ex) == "table" and type(ex.keys) == "table" then
|
|
local keys = ex.keys
|
|
local brushes: { Parse.Brush } = if type(ex.brushes) == "table" then ex.brushes else {}
|
|
if node.translation and keys.origin and #brushes == 0 then
|
|
local t = node.translation
|
|
keys = Types.object(table.clone(keys), Types.keys(keys))
|
|
keys.origin = fmtNum(t[1]) .. " " .. fmtNum(t[2]) .. " " .. fmtNum(t[3])
|
|
end
|
|
if valve then
|
|
local conv: { Parse.Brush } = {}
|
|
for _, b in brushes do
|
|
if b.faces then
|
|
local nb = table.clone(b)
|
|
local faces = {}
|
|
for i, f in b.faces do
|
|
faces[i] = toValve(f)
|
|
end
|
|
nb.faces = faces
|
|
table.insert(conv, nb)
|
|
else
|
|
table.insert(conv, b)
|
|
end
|
|
end
|
|
brushes = conv
|
|
if #ents == 0 and keys.mapversion ~= "220" then
|
|
keys = Types.object(table.clone(keys), Types.keys(keys))
|
|
Types.set(keys, "mapversion", "220")
|
|
end
|
|
end
|
|
table.insert(ents, { keys = keys, brushes = brushes })
|
|
end
|
|
end
|
|
if #ents == 0 then
|
|
return nil, Err.new(Err.ARG, "no map entities (nodes with extras.keys, as model/map loads them)")
|
|
end
|
|
local src: any = scene.meta and scene.meta.source
|
|
local fromMap = type(src) == "table" and src.format == "map"
|
|
local text, err = Write.text({
|
|
entities = ents :: { Parse.Entity },
|
|
game = if fromMap then src.game else nil,
|
|
mapFormat = if valve then "Valve" elseif fromMap then src.mapFormat else nil,
|
|
comments = {},
|
|
})
|
|
if not text then
|
|
return nil, Err.new(Err.ARG, err or "bad entity")
|
|
end
|
|
return buffer.fromstring(text), nil
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ extras
|
|
-- the entities as parsed: { entities = { { keys, brushes } }, game, mapFormat }
|
|
function Map.parse(src: buffer | string): (Parse.Map?, Err.Err?)
|
|
local text = if type(src) == "buffer" then buffer.tostring(src) elseif type(src) == "string" then src else nil
|
|
if not text then
|
|
return nil, Err.new(Err.ARG, "expected a buffer or a string")
|
|
end
|
|
local m, msg, at = Parse.parse(text)
|
|
if not m then
|
|
return nil, Err.from(msg, at)
|
|
end
|
|
return m, nil
|
|
end
|
|
|
|
function Map.write(m: Parse.Map): (string?, Err.Err?)
|
|
if type(m) ~= "table" or type(m.entities) ~= "table" then
|
|
return nil, Err.new(Err.ARG, "expected { entities = ... }")
|
|
end
|
|
local text, err = Write.text(m)
|
|
if not text then
|
|
return nil, Err.new(Err.ARG, err or "bad entity")
|
|
end
|
|
return text, nil
|
|
end
|
|
|
|
-- a parsed face -> its Brush face (plane and projection): Brush.uv / Brush.polygons take it
|
|
function Map.face(f: Parse.Face): Brush.Face?
|
|
return Build.face(f)
|
|
end
|
|
|
|
return Map
|