ws-game: archive/wad (IWAD / PWAD read + write; lumps with namespaces and maps; flats / pictures / composed textures as Images via PLAYPAL; maps as Scenes: triangulated sector floors / ceilings, walls with vanilla alignment, things); codecs/model/Polygon (2D polygons with holes -> triangles); licenses: Freedoom (fixture source only)
This commit is contained in:
1 parent
eac069f7dc
commit
5ec3121f65
11 files changed
+1823
No files matched your search
@@ -626,6 +626,18 @@ local list: { Entry } = {
|
||||
return require("@formats/archive/tar")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "wad",
|
||||
category = "archive",
|
||||
path = "archive/wad",
|
||||
extensions = { "wad" },
|
||||
mime = { "application/x-doom" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" },
|
||||
caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } },
|
||||
load = function()
|
||||
return require("@formats/archive/wad")
|
||||
end,
|
||||
},
|
||||
{
|
||||
name = "xz",
|
||||
category = "archive",
|
||||
|
||||
@@ -0,0 +1,441 @@
|
||||
--!strict
|
||||
-- archive/wad/Map: a Doom / Heretic / Hexen map (the binary lumps after a map marker: THINGS, LINEDEFS, SIDEDEFS,
|
||||
-- VERTEXES, SECTORS; Hexen format when BEHAVIOR is present) parsed into plain tables (Map.parse) and built into a
|
||||
-- Scene (Map.scene): sector floors and ceilings (sector outlines chained from the linedefs, triangulated with
|
||||
-- codecs/model/Polygon), walls (one-sided middles; lower / upper walls and masked middles of two-sided lines, the
|
||||
-- sky hack between two sky ceilings) with the vanilla texture alignment (x / y offsets, upper / lower unpegged), one
|
||||
-- primitive per flat / wall texture, things as child nodes standing on their sector's floor. Units are map units, z
|
||||
-- up. Written from the Unofficial Doom Specs and the Hexen specs; no code taken. UDMF (TEXTMAP) maps are not
|
||||
-- supported.
|
||||
local Types = require("@formats/Types")
|
||||
local Polygon = require("@formats/codecs/model/Polygon")
|
||||
|
||||
local Map = {}
|
||||
|
||||
local Scene = Types.Scene
|
||||
local readu8, readi16, readu16 = buffer.readu8, buffer.readi16, buffer.readu16
|
||||
local writef32, writeu32 = buffer.writef32, buffer.writeu32
|
||||
|
||||
export type Lump = { buf: buffer, at: number, size: number }
|
||||
export type Thing = { x: number, y: number, z: number?, angle: number, type: number, flags: number, tid: number?, special: number?, args: { number }? }
|
||||
export type Linedef = { v1: number, v2: number, flags: number, special: number, tag: number?, args: { number }?, front: number?, back: number? }
|
||||
export type Sidedef = { xoff: number, yoff: number, upper: string, lower: string, middle: string, sector: number }
|
||||
export type Sector = { floor: number, ceiling: number, floorFlat: string, ceilingFlat: string, light: number, special: number, tag: number }
|
||||
export type MapData = {
|
||||
format: "doom" | "hexen",
|
||||
things: { Thing },
|
||||
linedefs: { Linedef },
|
||||
sidedefs: { Sidedef },
|
||||
vertices: { number }, -- x1, y1, x2, y2, ...
|
||||
sectors: { Sector },
|
||||
}
|
||||
-- texture sizes / images by kind ("flat" | "texture") and name: what the WAD knows
|
||||
export type Textures = {
|
||||
size: (kind: string, name: string) -> (number?, number?),
|
||||
image: ((kind: string, name: string) -> Types.Image?)?,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ parse
|
||||
local function name8(b: buffer, at: number): string
|
||||
local s = buffer.readstring(b, at, 8)
|
||||
local z = string.find(s, "\0", 1, true)
|
||||
return string.upper(if z then string.sub(s, 1, z - 1) else s)
|
||||
end
|
||||
|
||||
local function side(v: number): number?
|
||||
return if v == 0xFFFF then nil else v + 1
|
||||
end
|
||||
|
||||
-- parse(lumps, hexen) -> MapData | nil, message: lumps = { THINGS, LINEDEFS, SIDEDEFS, VERTEXES, SECTORS } (Lump)
|
||||
function Map.parse(lumps: { [string]: Lump }, hexen: boolean): (MapData?, string?)
|
||||
for _, k in { "LINEDEFS", "SIDEDEFS", "VERTEXES", "SECTORS" } do
|
||||
if not lumps[k] then
|
||||
return nil, "map has no " .. k
|
||||
end
|
||||
end
|
||||
local m: MapData = { format = if hexen then "hexen" else "doom", things = {}, linedefs = {}, sidedefs = {}, vertices = {}, sectors = {} }
|
||||
local v = lumps.VERTEXES
|
||||
for i = 0, v.size // 4 - 1 do
|
||||
table.insert(m.vertices, readi16(v.buf, v.at + i * 4))
|
||||
table.insert(m.vertices, readi16(v.buf, v.at + i * 4 + 2))
|
||||
end
|
||||
local s = lumps.SECTORS
|
||||
for i = 0, s.size // 26 - 1 do
|
||||
local o = s.at + i * 26
|
||||
table.insert(m.sectors, {
|
||||
floor = readi16(s.buf, o),
|
||||
ceiling = readi16(s.buf, o + 2),
|
||||
floorFlat = name8(s.buf, o + 4),
|
||||
ceilingFlat = name8(s.buf, o + 12),
|
||||
light = readi16(s.buf, o + 20),
|
||||
special = readu16(s.buf, o + 22),
|
||||
tag = readu16(s.buf, o + 24),
|
||||
})
|
||||
end
|
||||
local sd = lumps.SIDEDEFS
|
||||
for i = 0, sd.size // 30 - 1 do
|
||||
local o = sd.at + i * 30
|
||||
table.insert(m.sidedefs, {
|
||||
xoff = readi16(sd.buf, o),
|
||||
yoff = readi16(sd.buf, o + 2),
|
||||
upper = name8(sd.buf, o + 4),
|
||||
lower = name8(sd.buf, o + 12),
|
||||
middle = name8(sd.buf, o + 20),
|
||||
sector = readu16(sd.buf, o + 28) + 1,
|
||||
})
|
||||
end
|
||||
local l = lumps.LINEDEFS
|
||||
local ls = if hexen then 16 else 14
|
||||
for i = 0, l.size // ls - 1 do
|
||||
local o = l.at + i * ls
|
||||
local b = l.buf
|
||||
if hexen then
|
||||
table.insert(m.linedefs, {
|
||||
v1 = readu16(b, o) + 1,
|
||||
v2 = readu16(b, o + 2) + 1,
|
||||
flags = readu16(b, o + 4),
|
||||
special = readu8(b, o + 6),
|
||||
args = { readu8(b, o + 7), readu8(b, o + 8), readu8(b, o + 9), readu8(b, o + 10), readu8(b, o + 11) },
|
||||
front = side(readu16(b, o + 12)),
|
||||
back = side(readu16(b, o + 14)),
|
||||
})
|
||||
else
|
||||
table.insert(m.linedefs, {
|
||||
v1 = readu16(b, o) + 1,
|
||||
v2 = readu16(b, o + 2) + 1,
|
||||
flags = readu16(b, o + 4),
|
||||
special = readu16(b, o + 6),
|
||||
tag = readu16(b, o + 8),
|
||||
front = side(readu16(b, o + 10)),
|
||||
back = side(readu16(b, o + 12)),
|
||||
})
|
||||
end
|
||||
end
|
||||
local t = lumps.THINGS
|
||||
if t then
|
||||
local ts = if hexen then 20 else 10
|
||||
for i = 0, t.size // ts - 1 do
|
||||
local o = t.at + i * ts
|
||||
local b = t.buf
|
||||
if hexen then
|
||||
table.insert(m.things, {
|
||||
tid = readi16(b, o),
|
||||
x = readi16(b, o + 2),
|
||||
y = readi16(b, o + 4),
|
||||
z = readi16(b, o + 6),
|
||||
angle = readi16(b, o + 8),
|
||||
type = readu16(b, o + 10),
|
||||
flags = readu16(b, o + 12),
|
||||
special = readu8(b, o + 14),
|
||||
args = { readu8(b, o + 15), readu8(b, o + 16), readu8(b, o + 17), readu8(b, o + 18), readu8(b, o + 19) },
|
||||
})
|
||||
else
|
||||
table.insert(m.things, {
|
||||
x = readi16(b, o),
|
||||
y = readi16(b, o + 2),
|
||||
angle = readi16(b, o + 4),
|
||||
type = readu16(b, o + 6),
|
||||
flags = readu16(b, o + 8),
|
||||
})
|
||||
end
|
||||
end
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sector outlines
|
||||
-- loops(m) -> loops[sector] = { { vertex ids } }: each sector's edges (front sides v1 -> v2, back sides v2 -> v1;
|
||||
-- lines with the sector on both sides left out) chained into closed loops, taking the sharpest right turn at forks;
|
||||
-- chains that do not close are dropped
|
||||
local function loops(m: MapData): { [number]: { { number } } }
|
||||
local edges: { [number]: { { number } } } = {}
|
||||
local nv = #m.vertices // 2
|
||||
local function add(sec: number, a: number, b: number)
|
||||
local e = edges[sec] or {}
|
||||
edges[sec] = e
|
||||
table.insert(e, { a, b })
|
||||
end
|
||||
for _, ld in m.linedefs do
|
||||
if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then
|
||||
local fs = ld.front and m.sidedefs[ld.front]
|
||||
local bs = ld.back and m.sidedefs[ld.back]
|
||||
local f = fs and fs.sector
|
||||
local b = bs and bs.sector
|
||||
if f ~= b then
|
||||
if f and m.sectors[f] then
|
||||
add(f, ld.v1, ld.v2)
|
||||
end
|
||||
if b and m.sectors[b] then
|
||||
add(b, ld.v2, ld.v1)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local V = m.vertices
|
||||
local out: { [number]: { { number } } } = {}
|
||||
for sec, list in edges do
|
||||
local from: { [number]: { number } } = {}
|
||||
for i, e in list do
|
||||
local l = from[e[1]] or {}
|
||||
from[e[1]] = l
|
||||
table.insert(l, i)
|
||||
end
|
||||
local used: { [number]: boolean } = {}
|
||||
local res: { { number } } = {}
|
||||
for start = 1, #list do
|
||||
if not used[start] then
|
||||
used[start] = true
|
||||
local loop = { list[start][1] }
|
||||
local cur = start
|
||||
local closed = false
|
||||
for _ = 1, #list do
|
||||
local e = list[cur]
|
||||
local at = e[2]
|
||||
if at == loop[1] then
|
||||
closed = true
|
||||
break
|
||||
end
|
||||
table.insert(loop, at)
|
||||
local cands = from[at]
|
||||
local best, bestT = nil :: number?, math.huge
|
||||
if cands then
|
||||
local ix, iy = V[at * 2 - 1] - V[e[1] * 2 - 1], V[at * 2] - V[e[1] * 2]
|
||||
for _, c in cands do
|
||||
if not used[c] then
|
||||
local n2 = list[c][2]
|
||||
local ox, oy = V[n2 * 2 - 1] - V[at * 2 - 1], V[n2 * 2] - V[at * 2]
|
||||
local t = math.atan2(ix * oy - iy * ox, ix * ox + iy * oy)
|
||||
if t < bestT then
|
||||
best, bestT = c, t
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
if not best then
|
||||
break
|
||||
end
|
||||
used[best] = true
|
||||
cur = best
|
||||
end
|
||||
if closed and #loop >= 3 then
|
||||
table.insert(res, loop)
|
||||
end
|
||||
end
|
||||
end
|
||||
out[sec] = res
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function insideLoop(V: { number }, loop: { number }, x: number, y: number): boolean
|
||||
local c = false
|
||||
local n = #loop
|
||||
local j = n
|
||||
for i = 1, n do
|
||||
local ax, ay = V[loop[i] * 2 - 1], V[loop[i] * 2]
|
||||
local bx, by = V[loop[j] * 2 - 1], V[loop[j] * 2]
|
||||
if (ay > y) ~= (by > y) and x < (bx - ax) * (y - ay) / (by - ay) + ax then
|
||||
c = not c
|
||||
end
|
||||
j = i
|
||||
end
|
||||
return c
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ scene
|
||||
type Batch = { kind: string, name: string, pos: { number }, nrm: { number }, uv: { number } }
|
||||
|
||||
local LOWER_UNPEGGED, UPPER_UNPEGGED, TWO_SIDED = 16, 8, 4
|
||||
|
||||
-- scene(m, tex, name) -> Scene
|
||||
function Map.scene(m: MapData, tex: Textures, name: string?): Types.Scene
|
||||
local batches: { [string]: Batch } = {}
|
||||
local order: { string } = {}
|
||||
local function batch(kind: string, tname: string): Batch
|
||||
local key = kind .. ":" .. tname
|
||||
local b = batches[key]
|
||||
if not b then
|
||||
b = { kind = kind, name = tname, pos = {}, nrm = {}, uv = {} }
|
||||
batches[key] = b
|
||||
table.insert(order, key)
|
||||
end
|
||||
return b
|
||||
end
|
||||
local function vert(b: Batch, x: number, y: number, z: number, nx: number, ny: number, nz: number, u: number, v: number)
|
||||
local p, n, t = b.pos, b.nrm, b.uv
|
||||
p[#p + 1], p[#p + 2], p[#p + 3] = x, y, z
|
||||
n[#n + 1], n[#n + 2], n[#n + 3] = nx, ny, nz
|
||||
t[#t + 1], t[#t + 2] = u, v
|
||||
end
|
||||
local V = m.vertices
|
||||
local nv = #V // 2
|
||||
-- floors and ceilings
|
||||
local secLoops = loops(m)
|
||||
for sec, ls in secLoops do
|
||||
local s = m.sectors[sec]
|
||||
local flat: { { number } } = {}
|
||||
for li, loop in ls do
|
||||
local f: { number } = {}
|
||||
for _, vi in loop do
|
||||
table.insert(f, V[vi * 2 - 1])
|
||||
table.insert(f, V[vi * 2])
|
||||
end
|
||||
flat[li] = f
|
||||
end
|
||||
local tris = Polygon.triangulate(flat)
|
||||
for pass = 1, 2 do
|
||||
local tname = if pass == 1 then s.floorFlat else s.ceilingFlat
|
||||
local fw, fh = tex.size("flat", tname)
|
||||
local w, h = fw or 64, fh or 64
|
||||
local z = if pass == 1 then s.floor else s.ceiling
|
||||
local b = batch("flat", tname)
|
||||
local nz = if pass == 1 then 1 else -1
|
||||
for k = 1, #tris, 6 do
|
||||
for c = 0, 2 do
|
||||
local cc = if pass == 1 then c else 2 - c
|
||||
local loop = ls[tris[k + cc * 2]]
|
||||
local vi = loop[tris[k + cc * 2 + 1]]
|
||||
local x, y = V[vi * 2 - 1], V[vi * 2]
|
||||
vert(b, x, y, z, 0, 0, nz, x / w, -y / h)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- walls
|
||||
local function quad(tname: string, x1: number, y1: number, x2: number, y2: number, zb: number, zt: number, xoff: number, len: number, texTop: number, yoff: number)
|
||||
if tname == "-" or tname == "" or zt <= zb then
|
||||
return
|
||||
end
|
||||
local tw, th = tex.size("texture", tname)
|
||||
local w, h = tw or 64, th or 128
|
||||
local b = batch("texture", tname)
|
||||
local dx, dy = x2 - x1, y2 - y1
|
||||
local l = math.sqrt(dx * dx + dy * dy)
|
||||
local nx, ny = dy / l, -dx / l
|
||||
local u0, u1 = xoff / w, (xoff + len) / w
|
||||
local vb, vt = (texTop - zb + yoff) / h, (texTop - zt + yoff) / h
|
||||
vert(b, x1, y1, zb, nx, ny, 0, u0, vb)
|
||||
vert(b, x2, y2, zb, nx, ny, 0, u1, vb)
|
||||
vert(b, x2, y2, zt, nx, ny, 0, u1, vt)
|
||||
vert(b, x1, y1, zb, nx, ny, 0, u0, vb)
|
||||
vert(b, x2, y2, zt, nx, ny, 0, u1, vt)
|
||||
vert(b, x1, y1, zt, nx, ny, 0, u0, vt)
|
||||
end
|
||||
for _, ld in m.linedefs do
|
||||
if ld.v1 >= 1 and ld.v1 <= nv and ld.v2 >= 1 and ld.v2 <= nv and ld.v1 ~= ld.v2 then
|
||||
local ax, ay, bx, by = V[ld.v1 * 2 - 1], V[ld.v1 * 2], V[ld.v2 * 2 - 1], V[ld.v2 * 2]
|
||||
local len = math.sqrt((bx - ax) ^ 2 + (by - ay) ^ 2)
|
||||
for sideN = 1, 2 do
|
||||
local sdi = if sideN == 1 then ld.front else ld.back
|
||||
local odi = if sideN == 1 then ld.back else ld.front
|
||||
local sd = sdi and m.sidedefs[sdi]
|
||||
local me = sd and m.sectors[sd.sector]
|
||||
if sd and me then
|
||||
local x1, y1, x2, y2 = ax, ay, bx, by
|
||||
if sideN == 2 then
|
||||
x1, y1, x2, y2 = bx, by, ax, ay
|
||||
end
|
||||
local od = odi and m.sidedefs[odi]
|
||||
local other = od and m.sectors[od.sector]
|
||||
if not other then
|
||||
local th = select(2, tex.size("texture", sd.middle)) or 128
|
||||
local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.floor + th else me.ceiling
|
||||
quad(sd.middle, x1, y1, x2, y2, me.floor, me.ceiling, sd.xoff, len, top, sd.yoff)
|
||||
else
|
||||
if other.floor > me.floor then
|
||||
local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then me.ceiling else other.floor
|
||||
quad(sd.lower, x1, y1, x2, y2, me.floor, other.floor, sd.xoff, len, top, sd.yoff)
|
||||
end
|
||||
local sky = string.sub(me.ceilingFlat, 1, 5) == "F_SKY" and string.sub(other.ceilingFlat, 1, 5) == "F_SKY"
|
||||
if other.ceiling < me.ceiling and not sky then
|
||||
local th = select(2, tex.size("texture", sd.upper)) or 128
|
||||
local top = if bit32.band(ld.flags, UPPER_UNPEGGED) ~= 0 then me.ceiling else other.ceiling + th
|
||||
quad(sd.upper, x1, y1, x2, y2, other.ceiling, me.ceiling, sd.xoff, len, top, sd.yoff)
|
||||
end
|
||||
if sd.middle ~= "-" and sd.middle ~= "" and bit32.band(ld.flags, TWO_SIDED) ~= 0 then
|
||||
local th = select(2, tex.size("texture", sd.middle)) or 128
|
||||
local lo, hi = math.max(me.floor, other.floor), math.min(me.ceiling, other.ceiling)
|
||||
local top = if bit32.band(ld.flags, LOWER_UNPEGGED) ~= 0 then lo + th else hi
|
||||
quad(sd.middle, x1, y1, x2, y2, math.max(lo, top + sd.yoff - th), math.min(hi, top + sd.yoff), sd.xoff, len, top, sd.yoff)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
-- the scene
|
||||
local scene = Scene.new()
|
||||
scene.meta.up = "z"
|
||||
local mesh: Types.Mesh = { name = name, primitives = {} }
|
||||
local texIndex: { [string]: number } = {}
|
||||
for _, key in order do
|
||||
local b = batches[key]
|
||||
local n = #b.pos // 3
|
||||
if n > 0 then
|
||||
local pb, nb, ub, ib = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4)
|
||||
for i = 1, n * 3 do
|
||||
writef32(pb, (i - 1) * 4, b.pos[i])
|
||||
writef32(nb, (i - 1) * 4, b.nrm[i])
|
||||
end
|
||||
for i = 1, n * 2 do
|
||||
writef32(ub, (i - 1) * 4, b.uv[i])
|
||||
end
|
||||
for i = 0, n - 1 do
|
||||
writeu32(ib, i * 4, i)
|
||||
end
|
||||
local ti = texIndex[key]
|
||||
if not ti then
|
||||
table.insert(scene.textures, { name = b.name, uri = b.name, image = if tex.image then tex.image(b.kind, b.name) else nil, extras = { wad = { kind = b.kind } } })
|
||||
ti = #scene.textures
|
||||
texIndex[key] = ti
|
||||
end
|
||||
local mat = Scene.material(b.name)
|
||||
mat.metallic = 0
|
||||
mat.baseColorTexture = { texture = ti }
|
||||
mat.extras = { wad = { kind = b.kind } }
|
||||
table.insert(scene.materials, mat)
|
||||
table.insert(mesh.primitives, {
|
||||
attributes = {
|
||||
POSITION = Scene.accessor(pb, "f32", 3, n),
|
||||
NORMAL = Scene.accessor(nb, "f32", 3, n),
|
||||
TEXCOORD_0 = Scene.accessor(ub, "f32", 2, n),
|
||||
},
|
||||
indices = Scene.accessor(ib, "u32", 1, n),
|
||||
mode = "triangles" :: any,
|
||||
material = #scene.materials,
|
||||
extras = { wad = { kind = b.kind, texture = b.name } },
|
||||
})
|
||||
end
|
||||
end
|
||||
table.insert(scene.meshes, mesh)
|
||||
scene.nodes[1] = { name = name, children = {}, mesh = 1 }
|
||||
scene.roots[1] = 1
|
||||
-- things, on the floor of the sector under them
|
||||
for i, th in m.things do
|
||||
local z = th.z or 0
|
||||
for sec, ls in secLoops do
|
||||
local inside = false
|
||||
for _, loop in ls do
|
||||
if insideLoop(V, loop, th.x, th.y) then
|
||||
inside = not inside
|
||||
end
|
||||
end
|
||||
if inside then
|
||||
z += m.sectors[sec].floor
|
||||
break
|
||||
end
|
||||
end
|
||||
local a = math.rad(th.angle) / 2
|
||||
table.insert(scene.nodes, {
|
||||
name = "thing " .. i,
|
||||
children = {},
|
||||
translation = { th.x, th.y, z },
|
||||
rotation = { 0, 0, math.sin(a), math.cos(a) },
|
||||
extras = { thing = { type = th.type, angle = th.angle, flags = th.flags, tid = th.tid, special = th.special, args = th.args } },
|
||||
})
|
||||
table.insert(scene.nodes[1].children, #scene.nodes)
|
||||
end
|
||||
return scene
|
||||
end
|
||||
|
||||
return Map
|
||||
@@ -0,0 +1,109 @@
|
||||
--!strict
|
||||
--!native
|
||||
-- archive/wad/Picture: Doom graphics lumps to rgba8 through a u32 palette (Pixels.palette of PLAYPAL): the column
|
||||
-- "picture" format of patches, sprites and menu graphics (width, height, left / top offsets, column offsets, posts of
|
||||
-- topdelta / length / pad / pixels / pad; DeePsea tall patches: a topdelta not above the previous one is relative)
|
||||
-- and raw flats (64 x 64, 64 x 128, 128 x 128, 256 x 256, Heretic's 64 x 65 / 64 x 200 and any w x 64 strip).
|
||||
-- Transparent picture pixels are 0 (alpha 0). Written from the Unofficial Doom Specs and the Doom source release's
|
||||
-- r_data.c description; no code taken. Never throws: every read is checked against the lump's end.
|
||||
local readu8, readu16, readi16, readu32, writeu32 = buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.writeu32
|
||||
|
||||
local Picture = {}
|
||||
|
||||
-- valid(b, at, n) -> width, height, left, top when the lump looks like a picture (every column offset inside it)
|
||||
function Picture.header(b: buffer, at: number, n: number): (number?, number, number, number)
|
||||
if n < 8 then
|
||||
return nil, 0, 0, 0
|
||||
end
|
||||
local w, h = readu16(b, at), readu16(b, at + 2)
|
||||
if w == 0 or h == 0 or w > 4096 or h > 4096 or 8 + w * 4 > n then
|
||||
return nil, 0, 0, 0
|
||||
end
|
||||
for x = 0, w - 1 do
|
||||
local o = readu32(b, at + 8 + x * 4)
|
||||
if o < 8 + w * 4 or o >= n then
|
||||
return nil, 0, 0, 0
|
||||
end
|
||||
end
|
||||
return w, h, readi16(b, at + 4), readi16(b, at + 6)
|
||||
end
|
||||
|
||||
-- decode(b, at, n, pal, out) -> true | false, message: the picture's pixels into out (w * h * 4 bytes, zeroed)
|
||||
function Picture.decode(b: buffer, at: number, n: number, pal: buffer, out: buffer, w: number, h: number): (boolean, string?)
|
||||
local stop = at + n
|
||||
for x = 0, w - 1 do
|
||||
local p = at + readu32(b, at + 8 + x * 4)
|
||||
local top = -1
|
||||
while true do
|
||||
if p >= stop then
|
||||
return false, "column " .. x .. " runs past the end"
|
||||
end
|
||||
local delta = readu8(b, p)
|
||||
if delta == 255 then
|
||||
break
|
||||
end
|
||||
if p + 3 > stop then
|
||||
return false, "post header past the end"
|
||||
end
|
||||
local len = readu8(b, p + 1)
|
||||
top = if delta <= top then top + delta else delta
|
||||
if p + 4 + len > stop then
|
||||
return false, "post past the end"
|
||||
end
|
||||
local src = p + 3
|
||||
for k = 0, len - 1 do
|
||||
local y = top + k
|
||||
if y < h then
|
||||
writeu32(out, (y * w + x) * 4, readu32(pal, readu8(b, src + k) * 4))
|
||||
end
|
||||
end
|
||||
p += 4 + len
|
||||
end
|
||||
end
|
||||
return true, nil
|
||||
end
|
||||
|
||||
-- flatSize(n) -> width, height of a raw flat of n bytes (nil when no shape fits)
|
||||
function Picture.flatSize(n: number): (number?, number)
|
||||
if n == 4096 then
|
||||
return 64, 64
|
||||
elseif n == 4160 then
|
||||
return 64, 64 -- Heretic / Hexen: 64 x 65, the last row is padding
|
||||
elseif n == 8192 then
|
||||
return 64, 128
|
||||
elseif n == 12800 then
|
||||
return 64, 200 -- Heretic / Hexen scrolling flats
|
||||
end
|
||||
local s = math.floor(math.sqrt(n) + 0.5)
|
||||
if s * s == n and s > 0 then
|
||||
return s, s
|
||||
end
|
||||
if n > 0 and n % 64 == 0 then
|
||||
return 64, n // 64
|
||||
end
|
||||
return nil, 0
|
||||
end
|
||||
|
||||
-- flat(b, at, w, h, pal, out): raw indexes, row by row
|
||||
function Picture.flat(b: buffer, at: number, w: number, h: number, pal: buffer, out: buffer)
|
||||
for i = 0, w * h - 1 do
|
||||
writeu32(out, i * 4, readu32(pal, readu8(b, at + i) * 4))
|
||||
end
|
||||
end
|
||||
|
||||
-- blit(src, sw, sh, dst, dw, dh, ox, oy): the non-transparent pixels of an rgba8 image onto another at (ox, oy),
|
||||
-- clipped (composite wall textures from patches)
|
||||
function Picture.blit(src: buffer, sw: number, sh: number, dst: buffer, dw: number, dh: number, ox: number, oy: number)
|
||||
local x0, x1 = math.max(0, -ox), math.min(sw, dw - ox) - 1
|
||||
for y = math.max(0, -oy), math.min(sh, dh - oy) - 1 do
|
||||
local so, d = y * sw, (y + oy) * dw + ox
|
||||
for x = x0, x1 do
|
||||
local v = readu32(src, (so + x) * 4)
|
||||
if v ~= 0 then
|
||||
writeu32(dst, (d + x) * 4, v)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return Picture
|
||||
@@ -0,0 +1,474 @@
|
||||
--!strict
|
||||
-- archive/wad: Doom-engine WAD files (IWAD / PWAD: Doom, Heretic, Hexen, Strife, Freedoom, ...), read into the
|
||||
-- standard Archive and written from any Archive value, plus the lumps as game data:
|
||||
-- Wad.lumps(a) every lump in file order with its namespace (sprites / patches / flats / ...) and map
|
||||
-- Wad.palette(a, i?) PLAYPAL palette i (default 0) as a u32 palette buffer
|
||||
-- Wad.image(a, name) a flat, patch, sprite or graphic (the column picture format) as an rgba8 Image
|
||||
-- (meta.offset = { left, top } for pictures; transparent pixels alpha 0)
|
||||
-- Wad.texture(a, name) a wall texture composed from its patches (TEXTURE1 / TEXTURE2 + PNAMES)
|
||||
-- Wad.maps(a) Wad.mapData(a, name) Wad.map(a, name, opts)
|
||||
-- the maps; their things / linedefs / sidedefs / vertices / sectors as tables; a Scene
|
||||
-- (floors, ceilings and walls per texture, things as nodes: archive/wad/Map)
|
||||
-- Entry names: the lump names, except lumps of a map, named "<map>/<lump>" ("MAP01/THINGS"), and later lumps
|
||||
-- repeating an earlier name, named "<name>~<n>" (n = 2, 3, ...), so every entry is unique; writing strips both again
|
||||
-- (the last path component, without its "~n", upper-cased, at most 8 bytes). Written from the Unofficial Doom
|
||||
-- Specs (Matthew Fell) and the Doom source release's w_wad.c / r_data.c description; no code taken.
|
||||
-- Not supported: UDMF (TEXTMAP) map geometry (its lumps are listed and readable), Strife's TEXTURE format variant,
|
||||
-- big-endian (Jaguar) WADs, compressed Jaguar lumps.
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ requires
|
||||
local Err = require("@formats/core/Err")
|
||||
local Bytes = require("@formats/core/Bytes")
|
||||
local Types = require("@formats/Types")
|
||||
local Archive = require("@formats/containers/Archive")
|
||||
local Pixels = require("@formats/codecs/image/Pixels")
|
||||
local Picture = require("@formats/archive/wad/Picture")
|
||||
local Map = require("@formats/archive/wad/Map")
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ contract
|
||||
local Wad = {
|
||||
name = "wad",
|
||||
category = "archive",
|
||||
extensions = { "wad" },
|
||||
mime = { "application/x-doom" },
|
||||
deps = { "core/Err", "core/Bytes", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/model/Polygon" },
|
||||
caps = { decode = true, encode = true, images = true, maps = true, variants = { "iwad", "pwad" } },
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ types
|
||||
export type DecodeOptions = { maxEntries: number? } -- default 1e6
|
||||
export type EncodeOptions = { type: ("IWAD" | "PWAD")? } -- default: the source's, else "PWAD"
|
||||
export type Lump = {
|
||||
name: string, -- the lump name as stored (upper case)
|
||||
entry: string, -- the Archive entry name
|
||||
index: number, -- 1-based position in the directory
|
||||
offset: number,
|
||||
size: number,
|
||||
namespace: string?, -- "sprites" | "patches" | "flats" | "colormaps" | "textures" (between *_START / *_END markers)
|
||||
map: string?, -- the map this lump belongs to
|
||||
marker: boolean?, -- a zero-size marker (F_START, MAP01, ...)
|
||||
}
|
||||
export type MapOptions = {
|
||||
textures: boolean?, -- build texture images (flats / composed wall textures) into scene.textures (default true)
|
||||
palette: number?, -- PLAYPAL palette index (default 0)
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ constants
|
||||
local MAP_LUMPS: { [string]: boolean } = {
|
||||
THINGS = true, LINEDEFS = true, SIDEDEFS = true, VERTEXES = true, SEGS = true, SSECTORS = true, NODES = true,
|
||||
SECTORS = true, REJECT = true, BLOCKMAP = true, BEHAVIOR = true, SCRIPTS = true, LEAFS = true, LIGHTS = true,
|
||||
MACROS = true, GL_VERT = true, GL_SEGS = true, GL_SSECT = true, GL_NODES = true, GL_PVS = true,
|
||||
}
|
||||
-- namespace markers: first letter(s) before _START / _END
|
||||
local NAMESPACES: { [string]: string } = { S = "sprites", SS = "sprites", P = "patches", PP = "patches", P1 = "patches", P2 = "patches",
|
||||
P3 = "patches", F = "flats", FF = "flats", F1 = "flats", F2 = "flats", F3 = "flats", C = "colormaps",
|
||||
TX = "textures", HI = "hires", A = "acs", V = "voices" }
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ sniff
|
||||
function Wad.sniff(r: Bytes.Reader): number
|
||||
if r:remaining() < 12 then
|
||||
return 0
|
||||
end
|
||||
local m = r:peek(4)
|
||||
if m ~= "IWAD" and m ~= "PWAD" then
|
||||
return 0
|
||||
end
|
||||
return 0.9
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ decode
|
||||
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
|
||||
return Wad.encode(archive, opts)
|
||||
end
|
||||
|
||||
local function nameAt(b: buffer, at: number): string
|
||||
local s = buffer.readstring(b, at, 8)
|
||||
local z = string.find(s, "\0", 1, true)
|
||||
return string.upper(if z then string.sub(s, 1, z - 1) else s)
|
||||
end
|
||||
|
||||
function Wad.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
|
||||
local kind = r:string(4)
|
||||
local count, dirOfs = r:i32le(), r:i32le()
|
||||
if r.err then
|
||||
return nil, r.err
|
||||
end
|
||||
if kind ~= "IWAD" and kind ~= "PWAD" then
|
||||
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
|
||||
end
|
||||
local size = r.limit - r.base
|
||||
if count < 0 or dirOfs < 0 then
|
||||
return nil, Err.new(Err.CORRUPT, "negative directory field", 4)
|
||||
end
|
||||
if count > (opts and opts.maxEntries or 1e6) then
|
||||
return nil, Err.new(Err.LIMIT, "too many lumps: " .. count)
|
||||
end
|
||||
if dirOfs + count * 16 > size then
|
||||
return nil, Err.new(Err.TRUNCATED, "directory past the end", 8)
|
||||
end
|
||||
local a = Archive.new("wad", encode)
|
||||
local lumps: { Lump } = {}
|
||||
local seen: { [string]: number } = {}
|
||||
local b = r.buf
|
||||
local ns: string? = nil
|
||||
local map: string? = nil
|
||||
local udmf = false
|
||||
for i = 0, count - 1 do
|
||||
local o = r.base + dirOfs + i * 16
|
||||
local at, n = buffer.readi32(b, o), buffer.readi32(b, o + 4)
|
||||
local name = nameAt(b, o + 8)
|
||||
if n < 0 or at < 0 or (n > 0 and at + n > size) then
|
||||
return nil, Err.new(Err.TRUNCATED, "lump " .. name .. " past the end", dirOfs + i * 16)
|
||||
end
|
||||
-- map membership: a lump followed by THINGS (binary) or TEXTMAP (UDMF) starts a map
|
||||
local nextName = if i + 1 < count then nameAt(b, o + 24) else ""
|
||||
local inMap: string? = nil
|
||||
if map then
|
||||
if udmf then
|
||||
inMap = map
|
||||
if name == "ENDMAP" then
|
||||
map = nil
|
||||
end
|
||||
elseif MAP_LUMPS[name] then
|
||||
inMap = map
|
||||
else
|
||||
map = nil
|
||||
end
|
||||
end
|
||||
local isMapMarker = not inMap and (nextName == "THINGS" or nextName == "TEXTMAP")
|
||||
if isMapMarker then
|
||||
map, udmf = name, nextName == "TEXTMAP"
|
||||
end
|
||||
-- namespaces
|
||||
local marker: boolean = false
|
||||
local pre = string.match(name, "^(%w+)_START$")
|
||||
local post = string.match(name, "^(%w+)_END$")
|
||||
if pre and NAMESPACES[pre] then
|
||||
ns = NAMESPACES[pre]
|
||||
marker = true
|
||||
elseif post and NAMESPACES[post] then
|
||||
ns = if #post > 1 and NAMESPACES[string.sub(post, 1, 1)] == ns and (string.match(post, "%d$")) then ns else nil
|
||||
marker = true
|
||||
end
|
||||
local entry = if inMap then inMap .. "/" .. name else name
|
||||
local k = seen[entry]
|
||||
if k then
|
||||
k += 1
|
||||
seen[entry] = k
|
||||
entry = entry .. "~" .. k
|
||||
else
|
||||
seen[entry] = 1
|
||||
end
|
||||
local lump: Lump = { name = name, entry = entry, index = i + 1, offset = at, size = n, namespace = if marker then nil else ns, map = inMap, marker = (n == 0 and (marker or isMapMarker)) or nil }
|
||||
table.insert(lumps, lump)
|
||||
Archive.put(a, { name = entry, size = n, dir = false, method = "store", lump = name, namespace = lump.namespace, map = inMap, load = Archive.slice(b, r.base + at, n) })
|
||||
end
|
||||
a.meta.source = { format = "wad", type = kind, lumps = count }
|
||||
a.meta.wad = { lumps = lumps, buf = b, base = r.base }
|
||||
return a, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ encode
|
||||
function Wad.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
|
||||
local items, err = Archive.collect(archive)
|
||||
if not items then
|
||||
return nil, err
|
||||
end
|
||||
local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source
|
||||
local kind = opts and opts.type or (if type(src) == "table" and src.format == "wad" then src.type else nil) or "PWAD"
|
||||
if kind ~= "IWAD" and kind ~= "PWAD" then
|
||||
return nil, Err.new(Err.ARG, "type must be IWAD or PWAD")
|
||||
end
|
||||
local list: { { name: string, data: buffer } } = {}
|
||||
for _, it in items do
|
||||
if not it.entry.dir then
|
||||
local base = string.match(it.entry.name, "([^/\\]*)$") or it.entry.name
|
||||
base = string.upper((string.gsub(base, "~%d+$", "")))
|
||||
if #base > 8 or #base == 0 then
|
||||
return nil, Err.new(Err.ARG, "lump name must be 1..8 bytes: " .. it.entry.name)
|
||||
end
|
||||
table.insert(list, { name = base, data = it.data })
|
||||
end
|
||||
end
|
||||
local w = Bytes.writer()
|
||||
w:string(kind)
|
||||
w:u32le(#list)
|
||||
w:u32le(0)
|
||||
local offs: { number } = {}
|
||||
for i, l in list do
|
||||
offs[i] = w:tell()
|
||||
w:bytes(l.data)
|
||||
end
|
||||
local dirOfs = w:tell()
|
||||
for i, l in list do
|
||||
w:u32le(offs[i])
|
||||
w:u32le(buffer.len(l.data))
|
||||
w:string(l.name)
|
||||
w:fill(0, 8 - #l.name)
|
||||
end
|
||||
w:setU32le(8, dirOfs)
|
||||
return w:finish(), nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ extras
|
||||
local function info(a: any): any
|
||||
return type(a) == "table" and type(a.meta) == "table" and a.meta.wad or nil
|
||||
end
|
||||
|
||||
-- the last lump named name (PWAD order: later lumps override), preferring namespace ns when given
|
||||
local function find(w: any, name: string, ns: string?): Lump?
|
||||
local up = string.upper(name)
|
||||
local best: Lump? = nil
|
||||
for _, l in w.lumps do
|
||||
if l.name == up and not l.map then
|
||||
if ns == nil or l.namespace == ns then
|
||||
best = l
|
||||
elseif not best then
|
||||
best = l
|
||||
end
|
||||
end
|
||||
end
|
||||
if best and ns and best.namespace ~= ns then
|
||||
for _, l in w.lumps do
|
||||
if l.name == up and l.namespace == ns then
|
||||
best = l
|
||||
end
|
||||
end
|
||||
end
|
||||
return best
|
||||
end
|
||||
|
||||
-- new(type?) -> an empty WAD Archive ("PWAD" by default): a:add(name, data); a:write()
|
||||
function Wad.new(kind: ("IWAD" | "PWAD")?): any
|
||||
local a = Archive.new("wad", encode)
|
||||
a.meta.source = { format = "wad", type = kind or "PWAD" }
|
||||
return a
|
||||
end
|
||||
|
||||
-- lumps(a) -> { Lump } in directory order (nil when a is not a decoded WAD)
|
||||
function Wad.lumps(a: any): { Lump }?
|
||||
local w = info(a)
|
||||
return w and w.lumps
|
||||
end
|
||||
|
||||
-- palette(a, index?) -> a 256-entry u32 palette (Pixels layout) from PLAYPAL | nil, Err
|
||||
function Wad.palette(a: any, index: number?): (buffer?, Err.Err?)
|
||||
local w = info(a)
|
||||
if not w then
|
||||
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
|
||||
end
|
||||
local l = find(w, "PLAYPAL")
|
||||
local i = index or 0
|
||||
if not l or l.size < (i + 1) * 768 then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "no PLAYPAL palette " .. i)
|
||||
end
|
||||
return Pixels.palette(w.buf, w.base + l.offset + i * 768, 256), nil
|
||||
end
|
||||
|
||||
-- image(a, name, opts?) -> an rgba8 Image of a flat (in the flats namespace) or a picture (patch, sprite, graphic)
|
||||
-- | nil, Err. opts.palette: the PLAYPAL index (default 0); opts.kind: "flat" | "picture" to force the decoding.
|
||||
function Wad.image(a: any, name: string, opts: { palette: number?, kind: string? }?): (Types.Image?, Err.Err?)
|
||||
local w = info(a)
|
||||
if not w then
|
||||
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
|
||||
end
|
||||
local kind = opts and opts.kind
|
||||
local l = find(w, name, if kind == "flat" then "flats" else nil)
|
||||
if not l then
|
||||
return nil, Err.new(Err.ARG, "no lump named " .. tostring(name))
|
||||
end
|
||||
local pal, perr = Wad.palette(a, opts and opts.palette)
|
||||
if not pal then
|
||||
return nil, perr
|
||||
end
|
||||
local at = w.base + l.offset
|
||||
local pw, ph, left, top = Picture.header(w.buf, at, l.size)
|
||||
local asFlat = kind == "flat" or (kind ~= "picture" and (l.namespace == "flats" or not pw))
|
||||
if asFlat then
|
||||
local fw, fh = Picture.flatSize(l.size)
|
||||
if not fw then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "lump " .. l.name .. " is neither a picture nor a flat")
|
||||
end
|
||||
local img = Types.Image.new(fw, fh)
|
||||
Picture.flat(w.buf, at, fw, fh, pal, img.pixels)
|
||||
img.meta.source = { format = "wad", kind = "flat", lump = l.name }
|
||||
return img, nil
|
||||
end
|
||||
if not pw then
|
||||
return nil, Err.new(Err.CORRUPT, "lump " .. l.name .. " is not a valid picture")
|
||||
end
|
||||
local img = Types.Image.new(pw, ph)
|
||||
local ok, msg = Picture.decode(w.buf, at, l.size, pal, img.pixels, pw, ph)
|
||||
if not ok then
|
||||
return nil, Err.from(msg, l.offset)
|
||||
end
|
||||
img.meta.offset = { left, top }
|
||||
img.meta.source = { format = "wad", kind = "picture", lump = l.name, left = left, top = top }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- the texture definitions (TEXTURE1 + TEXTURE2 with PNAMES): name -> { width, height, patches = { { x, y, patch } } }
|
||||
local function textureDefs(w: any): { [string]: any }
|
||||
if w.textures then
|
||||
return w.textures
|
||||
end
|
||||
local defs: { [string]: any } = {}
|
||||
w.textures = defs
|
||||
local pn = find(w, "PNAMES")
|
||||
local names: { string } = {}
|
||||
if pn and pn.size >= 4 then
|
||||
local at = w.base + pn.offset
|
||||
local n = math.min(buffer.readi32(w.buf, at), (pn.size - 4) // 8)
|
||||
for i = 0, n - 1 do
|
||||
names[i + 1] = nameAt(w.buf, at + 4 + i * 8)
|
||||
end
|
||||
end
|
||||
for _, tl in { "TEXTURE1", "TEXTURE2" } do
|
||||
local l = find(w, tl)
|
||||
if l and l.size >= 4 then
|
||||
local r = Bytes.reader(w.buf, w.base + l.offset, l.size)
|
||||
local n = r:i32le()
|
||||
if n > 0 and n * 4 <= l.size - 4 then
|
||||
for i = 0, n - 1 do
|
||||
r:seek(4 + i * 4)
|
||||
local o = r:i32le()
|
||||
if o > 0 and o + 22 <= l.size then
|
||||
r:seek(o)
|
||||
local tname = string.upper(r:fixed(8))
|
||||
r:skip(4)
|
||||
local tw, th = r:i16le(), r:i16le()
|
||||
r:skip(4)
|
||||
local pc = r:i16le()
|
||||
local patches = {}
|
||||
for _ = 1, math.max(0, pc) do
|
||||
local px, py, pi = r:i16le(), r:i16le(), r:i16le()
|
||||
r:skip(4)
|
||||
if names[pi + 1] then
|
||||
table.insert(patches, { x = px, y = py, patch = names[pi + 1] })
|
||||
end
|
||||
end
|
||||
if not r.err and tw > 0 and th > 0 and defs[tname] == nil then
|
||||
defs[tname] = { width = tw, height = th, patches = patches }
|
||||
end
|
||||
r.err = nil
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return defs
|
||||
end
|
||||
|
||||
-- texture(a, name, opts?) -> the composed rgba8 Image of a wall texture | nil, Err (opts.palette)
|
||||
function Wad.texture(a: any, name: string, opts: { palette: number? }?): (Types.Image?, Err.Err?)
|
||||
local w = info(a)
|
||||
if not w then
|
||||
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
|
||||
end
|
||||
local def = textureDefs(w)[string.upper(name)]
|
||||
if not def then
|
||||
return nil, Err.new(Err.ARG, "no texture named " .. tostring(name))
|
||||
end
|
||||
if def.width * def.height > 4096 * 4096 then
|
||||
return nil, Err.new(Err.LIMIT, "texture too big")
|
||||
end
|
||||
local img = Types.Image.new(def.width, def.height)
|
||||
for _, p in def.patches do
|
||||
local pimg = Wad.image(a, p.patch, { palette = opts and opts.palette, kind = "picture" })
|
||||
if pimg then
|
||||
Picture.blit(pimg.pixels, pimg.width, pimg.height, img.pixels, def.width, def.height, p.x, p.y)
|
||||
end
|
||||
end
|
||||
img.meta.source = { format = "wad", kind = "texture", texture = string.upper(name), patches = #def.patches }
|
||||
return img, nil
|
||||
end
|
||||
|
||||
-- maps(a) -> { map names } in file order
|
||||
function Wad.maps(a: any): { string }
|
||||
local w = info(a)
|
||||
local out: { string } = {}
|
||||
if w then
|
||||
local seen: { [string]: boolean } = {}
|
||||
for _, l in w.lumps do
|
||||
if l.map and not seen[l.map] then
|
||||
seen[l.map] = true
|
||||
table.insert(out, l.map)
|
||||
end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
-- mapData(a, name) -> Map.MapData (things, linedefs, sidedefs, vertices, sectors as tables, 1-based references)
|
||||
function Wad.mapData(a: any, name: string): (Map.MapData?, Err.Err?)
|
||||
local w = info(a)
|
||||
if not w then
|
||||
return nil, Err.new(Err.ARG, "expected a decoded WAD archive")
|
||||
end
|
||||
local up = string.upper(name)
|
||||
local lumps: { [string]: Map.Lump } = {}
|
||||
for _, l in w.lumps do
|
||||
if l.map == up and lumps[l.name] == nil then
|
||||
lumps[l.name] = { buf = w.buf, at = w.base + l.offset, size = l.size }
|
||||
end
|
||||
end
|
||||
if not next(lumps) then
|
||||
return nil, Err.new(Err.ARG, "no map named " .. tostring(name))
|
||||
end
|
||||
if lumps.TEXTMAP then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "UDMF (TEXTMAP) maps")
|
||||
end
|
||||
local m, msg = Map.parse(lumps, lumps.BEHAVIOR ~= nil)
|
||||
if not m then
|
||||
return nil, Err.from(msg)
|
||||
end
|
||||
return m, nil
|
||||
end
|
||||
|
||||
-- map(a, name, opts?) -> a Scene of the map (z up, map units): one primitive per flat / wall texture (materials and
|
||||
-- textures named after them; texture.image when opts.textures ~= false and the WAD holds it), things as child nodes
|
||||
-- (extras.thing = { type, angle, flags, ... }); meta.source.map = the MapData
|
||||
function Wad.map(a: any, name: string, opts: MapOptions?): (Types.Scene?, Err.Err?)
|
||||
local m, err = Wad.mapData(a, name)
|
||||
if not m then
|
||||
return nil, err
|
||||
end
|
||||
local w = info(a)
|
||||
local defs = textureDefs(w)
|
||||
local images = not (opts and opts.textures == false)
|
||||
local cache: { [string]: any } = {}
|
||||
local pal = opts and opts.palette
|
||||
local function image(kind: string, tname: string): Types.Image?
|
||||
local key = kind .. ":" .. tname
|
||||
local c = cache[key]
|
||||
if c == nil then
|
||||
local img = if kind == "flat" then Wad.image(a, tname, { kind = "flat", palette = pal }) else Wad.texture(a, tname, { palette = pal })
|
||||
c = img or false
|
||||
cache[key] = c
|
||||
end
|
||||
return if c then c else nil
|
||||
end
|
||||
local tex: Map.Textures = {
|
||||
size = function(kind: string, tname: string): (number?, number?)
|
||||
if kind == "texture" then
|
||||
local d = defs[tname]
|
||||
if d then
|
||||
return d.width, d.height
|
||||
end
|
||||
return nil, nil
|
||||
end
|
||||
local l = find(w, tname, "flats")
|
||||
if l then
|
||||
local fw, fh = Picture.flatSize(l.size)
|
||||
return fw, fh
|
||||
end
|
||||
return nil, nil
|
||||
end,
|
||||
image = if images then image else nil,
|
||||
}
|
||||
local scene = Map.scene(m, tex, string.upper(name))
|
||||
scene.meta.source = { format = "wad", map = string.upper(name), mapFormat = m.format, things = #m.things, linedefs = #m.linedefs, sectors = #m.sectors, vertices = #m.vertices // 2 }
|
||||
return scene, nil
|
||||
end
|
||||
|
||||
return Wad
|
||||
@@ -0,0 +1,248 @@
|
||||
--!strict
|
||||
-- codecs/model/Polygon: 2D polygons with holes to triangles, for formats that store regions as outlines (Doom map
|
||||
-- sectors, ...). Loops are classified by nesting (a loop inside an odd number of other loops is a hole of the
|
||||
-- smallest loop around it), oriented, each hole bridged to its outer loop at a mutually visible vertex, then the
|
||||
-- result is ear-clipped (reflex-vertex test; a polygon that never yields a clean ear clips its least bad corner so
|
||||
-- every input terminates). New in formats-luau, after the classic "ear clipping with hole bridging" method
|
||||
-- (D. Eberly, Triangulation by Ear Clipping); no code taken.
|
||||
--
|
||||
-- local tris = Polygon.triangulate({ { 0, 0, 10, 0, 10, 10, 0, 10 }, { 2, 2, 4, 2, 4, 4, 2, 4 } })
|
||||
-- -- tris = { loop, index, loop, index, loop, index, ... }: three corners per triangle, each a (loop, vertex) pair
|
||||
-- -- (1-based), counter-clockwise
|
||||
--
|
||||
-- Never throws; degenerate loops (fewer than 3 points, zero area) are ignored.
|
||||
local Polygon = {}
|
||||
|
||||
type Pt = { x: number, y: number, loop: number, index: number }
|
||||
|
||||
local function area(pts: { Pt }): number
|
||||
local a = 0
|
||||
local n = #pts
|
||||
for i = 1, n do
|
||||
local p, q = pts[i], pts[i % n + 1]
|
||||
a += p.x * q.y - q.x * p.y
|
||||
end
|
||||
return a / 2
|
||||
end
|
||||
|
||||
local function inside(pts: { Pt }, x: number, y: number): boolean
|
||||
local c = false
|
||||
local n = #pts
|
||||
local j = n
|
||||
for i = 1, n do
|
||||
local a, b = pts[i], pts[j]
|
||||
if (a.y > y) ~= (b.y > y) and x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x then
|
||||
c = not c
|
||||
end
|
||||
j = i
|
||||
end
|
||||
return c
|
||||
end
|
||||
|
||||
local function cross(o: Pt, a: Pt, b: Pt): number
|
||||
return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x)
|
||||
end
|
||||
|
||||
-- segments p1-p2 and q1-q2 cross properly (touching at an endpoint does not count)
|
||||
local function crosses(p1: Pt, p2: Pt, q1: Pt, q2: Pt): boolean
|
||||
if (p1.x == q1.x and p1.y == q1.y) or (p1.x == q2.x and p1.y == q2.y) or (p2.x == q1.x and p2.y == q1.y) or (p2.x == q2.x and p2.y == q2.y) then
|
||||
return false
|
||||
end
|
||||
local d1, d2 = cross(q1, q2, p1), cross(q1, q2, p2)
|
||||
local d3, d4 = cross(p1, p2, q1), cross(p1, p2, q2)
|
||||
return ((d1 > 0 and d2 < 0) or (d1 < 0 and d2 > 0)) and ((d3 > 0 and d4 < 0) or (d3 < 0 and d4 > 0))
|
||||
end
|
||||
|
||||
local function visible(m: Pt, v: Pt, rings: { { Pt } }): boolean
|
||||
for _, r in rings do
|
||||
local n = #r
|
||||
for i = 1, n do
|
||||
if crosses(m, v, r[i], r[i % n + 1]) then
|
||||
return false
|
||||
end
|
||||
end
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
-- splice hole h into ring outer (both oriented: outer counter-clockwise, hole clockwise) at mutually visible
|
||||
-- vertices; others = every ring the bridge must not cross
|
||||
local function bridge(outer: { Pt }, h: { Pt }, others: { { Pt } }): { Pt }
|
||||
local mi = 1
|
||||
for i, p in h do
|
||||
if p.x > h[mi].x then
|
||||
mi = i
|
||||
end
|
||||
end
|
||||
local m = h[mi]
|
||||
local best, bestD = 0, math.huge
|
||||
for pass = 1, 2 do
|
||||
for i, v in outer do
|
||||
if pass == 2 or v.x >= m.x then
|
||||
local d = (v.x - m.x) ^ 2 + (v.y - m.y) ^ 2
|
||||
if d < bestD and visible(m, v, others) then
|
||||
best, bestD = i, d
|
||||
end
|
||||
end
|
||||
end
|
||||
if best > 0 then
|
||||
break
|
||||
end
|
||||
end
|
||||
if best == 0 then
|
||||
best = 1
|
||||
end
|
||||
local out: { Pt } = {}
|
||||
for i = 1, best do
|
||||
table.insert(out, outer[i])
|
||||
end
|
||||
local n = #h
|
||||
for k = 0, n do
|
||||
table.insert(out, h[(mi - 1 + k) % n + 1])
|
||||
end
|
||||
for i = best, #outer do
|
||||
table.insert(out, outer[i])
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function inTri(a: Pt, b: Pt, c: Pt, p: Pt): boolean
|
||||
return cross(a, b, p) >= 0 and cross(b, c, p) >= 0 and cross(c, a, p) >= 0
|
||||
end
|
||||
|
||||
-- ear clipping of one counter-clockwise ring
|
||||
local function clip(ring: { Pt }, out: { number })
|
||||
local pts = table.clone(ring)
|
||||
local guard = #pts * #pts + 16
|
||||
while #pts > 3 and guard > 0 do
|
||||
guard -= 1
|
||||
local n = #pts
|
||||
local found, bestI, bestScore = 0, 1, -math.huge
|
||||
for i = 1, n do
|
||||
local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1]
|
||||
local cr = cross(a, b, c)
|
||||
if cr > 0 then
|
||||
local ok = true
|
||||
for k = 1, n do
|
||||
local p = pts[k]
|
||||
if p ~= a and p ~= b and p ~= c and not (p.x == b.x and p.y == b.y) and not (p.x == a.x and p.y == a.y) and not (p.x == c.x and p.y == c.y) and inTri(a, b, c, p) then
|
||||
ok = false
|
||||
break
|
||||
end
|
||||
end
|
||||
if ok then
|
||||
found = i
|
||||
break
|
||||
end
|
||||
end
|
||||
if cr > bestScore then
|
||||
bestI, bestScore = i, cr
|
||||
end
|
||||
end
|
||||
local i = if found > 0 then found else bestI
|
||||
local a, b, c = pts[(i - 2) % n + 1], pts[i], pts[i % n + 1]
|
||||
if cross(a, b, c) ~= 0 then
|
||||
table.insert(out, a.loop)
|
||||
table.insert(out, a.index)
|
||||
table.insert(out, b.loop)
|
||||
table.insert(out, b.index)
|
||||
table.insert(out, c.loop)
|
||||
table.insert(out, c.index)
|
||||
end
|
||||
table.remove(pts, i)
|
||||
end
|
||||
if #pts == 3 and cross(pts[1], pts[2], pts[3]) > 0 then
|
||||
for k = 1, 3 do
|
||||
table.insert(out, pts[k].loop)
|
||||
table.insert(out, pts[k].index)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
-- triangulate(loops) -> { loop, index, ... }: loops[i] = { x1, y1, x2, y2, ... } (closed implicitly)
|
||||
function Polygon.triangulate(loops: { { number } }): { number }
|
||||
local rings: { { Pt } } = {}
|
||||
local areas: { number } = {}
|
||||
for li, l in loops do
|
||||
local pts: { Pt } = {}
|
||||
for k = 1, #l - 1, 2 do
|
||||
local x, y = l[k], l[k + 1]
|
||||
if type(x) == "number" and type(y) == "number" and x == x and y == y then
|
||||
table.insert(pts, { x = x, y = y, loop = li, index = (k + 1) // 2 })
|
||||
end
|
||||
end
|
||||
local a = if #pts >= 3 then area(pts) else 0
|
||||
if a ~= 0 then
|
||||
table.insert(rings, pts)
|
||||
table.insert(areas, math.abs(a))
|
||||
if a < 0 then -- counter-clockwise for now; holes are flipped below
|
||||
local r: { Pt } = {}
|
||||
for k = #pts, 1, -1 do
|
||||
table.insert(r, pts[k])
|
||||
end
|
||||
rings[#rings] = r
|
||||
end
|
||||
end
|
||||
end
|
||||
-- nesting: the parent of a ring is the smallest ring containing its first point
|
||||
local n = #rings
|
||||
local depth, parent = table.create(n, 0), table.create(n, 0)
|
||||
for i = 1, n do
|
||||
local p = rings[i][1]
|
||||
for j = 1, n do
|
||||
if j ~= i and areas[j] > areas[i] and inside(rings[j], p.x, p.y) then
|
||||
depth[i] += 1
|
||||
if parent[i] == 0 or areas[j] < areas[parent[i]] then
|
||||
parent[i] = j
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
local holes: { [number]: { number } } = {}
|
||||
for i = 1, n do
|
||||
if depth[i] % 2 == 1 and parent[i] > 0 then
|
||||
local list = holes[parent[i]] or {}
|
||||
holes[parent[i]] = list
|
||||
table.insert(list, i)
|
||||
end
|
||||
end
|
||||
local out: { number } = {}
|
||||
for i = 1, n do
|
||||
if depth[i] % 2 == 0 then
|
||||
local ring = rings[i]
|
||||
local hs = holes[i]
|
||||
if hs then
|
||||
table.sort(hs, function(a: number, b: number): boolean
|
||||
local ma, mb = -math.huge, -math.huge
|
||||
for _, p in rings[a] do
|
||||
ma = math.max(ma, p.x)
|
||||
end
|
||||
for _, p in rings[b] do
|
||||
mb = math.max(mb, p.x)
|
||||
end
|
||||
return ma > mb
|
||||
end)
|
||||
local flipped: { { Pt } } = {}
|
||||
for _, h in hs do
|
||||
local r: { Pt } = {}
|
||||
local src = rings[h]
|
||||
for k = #src, 1, -1 do
|
||||
table.insert(r, src[k])
|
||||
end
|
||||
table.insert(flipped, r)
|
||||
end
|
||||
for k, h in flipped do
|
||||
local others: { { Pt } } = { ring }
|
||||
for k2 = k + 1, #flipped do
|
||||
table.insert(others, flipped[k2])
|
||||
end
|
||||
ring = bridge(ring, h, others)
|
||||
end
|
||||
end
|
||||
clip(ring, out)
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
return Polygon
|
||||
Reference in new issue
Block a user