merge ws/build

This commit is contained in:
4DBug committed 2026-11-01 19:18:53 -06:00
commit 9ae847d2a3
22 files changed
+6770 -1123

No files matched your search

+24
View File
@@ -26,6 +26,18 @@ local list: { Entry } = {
return require("@rosetta/image/ani")
end,
},
{
name = "art",
category = "image",
path = "image/art",
extensions = { "art" },
mime = { "image/x-build-art" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels", "codecs/image/Quantize" },
caps = { decode = true, encode = true, alpha = true, palette = true, frames = true, depths = { 8 } },
load = function()
return require("@rosetta/image/art")
end,
},
{
name = "blp",
category = "image",
@@ -746,6 +758,18 @@ local list: { Entry } = {
return require("@rosetta/model/bsp")
end,
},
{
name = "buildmap",
category = "model",
path = "model/buildmap",
extensions = { "map" },
mime = { "application/x-build-map" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Polygon" },
caps = { decode = true, encode = true, sprites = true, slopes = true },
load = function()
return require("@rosetta/model/buildmap")
end,
},
{
name = "dae",
category = "model",
+486
View File
@@ -0,0 +1,486 @@
--!strict
-- image/art: Build engine ART tile files (TILES000.ART ...), from Ken Silverman's BUILDINF.TXT and the eduke32 wiki
-- ("ART format"); no code taken. Supports: version 1 with the optional "BUILDART" prefix, every tile as a frame (tile
-- order, empty tiles 0 x 0), picanm animation / centre fields, PALETTE.DAT (6-bit VGA, shade tables, translucency
-- table) and LOOKUP.DAT palookups through opts / resolve; writes ART from gray8 indices or rgba8 mapped to the palette.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
local Quantize = require("@rosetta/codecs/image/Quantize")
-- ------------------------------------------------------------------------------------------------ contract
local Art = {
name = "art",
category = "image",
extensions = { "art" },
mime = { "image/x-build-art" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/image/Pixels", "codecs/image/Quantize" },
caps = { decode = true, encode = true, alpha = true, palette = true, frames = true, depths = { 8 } },
}
-- ------------------------------------------------------------------------------------------------ types
export type PaletteSource = buffer | string | { { number } } -- PALETTE.DAT bytes, or 8-bit { r, g, b[, a] } entries
export type DecodeOptions = {
palette: PaletteSource?, -- default opts.resolve("PALETTE.DAT"); without one, a grey ramp (meta.source.palette = false)
lookup: (buffer | string)?, -- LOOKUP.DAT bytes; default opts.resolve("LOOKUP.DAT")
shade: number?, -- shade table of PALETTE.DAT applied to the indices (0 = none, default)
pal: number?, -- LOOKUP.DAT palookup applied before the shade (0 = none, default)
native: boolean?, -- gray8 palette indices instead of rgba8
resolve: ((uri: string) -> buffer?)?,
maxPixels: number?, -- all tiles together, default 2^26
}
export type Picanm = {
frames: number, -- bits 0-5
type: "none" | "oscillate" | "forward" | "backward", -- bits 6-7
xoffset: number, -- bits 8-15, signed
yoffset: number, -- bits 16-23, signed
speed: number, -- bits 24-27: a frame lasts 2^speed ticks of 120 Hz
extra: number, -- bits 28-31
}
export type EncodeOptions = {
palette: PaletteSource?, -- for rgba8 frames; default img.meta.palette
tileStart: number?, -- default img.meta.source.tileStart, else the first frame's meta.tile, else 0
numtiles: number?, -- the legacy header field; default img.meta.source.numtiles, else 0
buildart: boolean?, -- write the "BUILDART" prefix (eduke32); default img.meta.source.buildart
}
-- ------------------------------------------------------------------------------------------------ constants
local TYPES = { "none", "oscillate", "forward", "backward" }
local TYPE_INDEX = { none = 0, oscillate = 1, forward = 2, backward = 3 }
local TRANSPARENT = 255
local readu8, readu16, readu32, readi16 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi16
-- ------------------------------------------------------------------------------------------------ sniff
local function header(b: buffer, o: number, limit: number): (number?, number?, number?, number?, boolean?)
local p = o
local prefixed = false
if limit - p >= 8 and buffer.readstring(b, p, 8) == "BUILDART" then
p += 8
prefixed = true
end
if limit - p < 16 or readu32(b, p) ~= 1 then
return nil, nil, nil, nil, nil
end
local first, last = readu32(b, p + 8), readu32(b, p + 12)
if last < first or last - first >= 65536 then
return nil, nil, nil, nil, nil
end
return p + 16, first, last, readu32(b, p + 4), prefixed
end
function Art.sniff(r: Bytes.Reader): number
local at, first, last = header(r.buf, r.base, r.limit)
if not at or not first or not last then
return 0
end
local n = last - first + 1
local p = at :: number
if r.limit - p < n * 8 then
return 0
end
local total = 0
for i = 0, n - 1 do
local w, h = readi16(r.buf, p + i * 2), readi16(r.buf, p + n * 2 + i * 2)
if w < 0 or h < 0 then
return 0
end
total += w * h
end
local size = p + n * 8 + total - r.base
local have = r.limit - r.base
return if size == have then 0.9 elseif size < have and have - size < 4096 then 0.5 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function bytesOf(v: any): buffer?
if type(v) == "buffer" then
return v
elseif type(v) == "string" then
return buffer.fromstring(v)
end
return nil
end
local function fetch(opts: DecodeOptions, key: string, file: string): buffer?
local v = bytesOf((opts :: any)[key])
if v then
return v
end
local resolve = opts.resolve
if type(resolve) == "function" then
for _, name in { file, string.lower(file) } do
local ok, res = pcall(resolve, name)
local b = if ok then bytesOf(res) else nil
if b then
return b
end
end
end
return nil
end
-- palette as 256 u32 rgba words; PALETTE.DAT stores 6-bit components, scaled << 2 as the engine and arttool do
local function makePalette(src: any, dat: buffer?): buffer
if type(src) == "table" then
local tri = buffer.create(768)
for i = 0, 255 do
local c = src[i + 1]
if type(c) == "table" then
for k = 1, 3 do
buffer.writeu8(tri, i * 3 + k - 1, math.clamp(math.floor(tonumber(c[k]) or 0), 0, 255))
end
end
end
return Pixels.palette(tri, 0, 256)
end
if dat and buffer.len(dat) >= 768 then
local tri = buffer.create(768)
for i = 0, 767 do
buffer.writeu8(tri, i, bit32.band(readu8(dat, i), 63) * 4)
end
return Pixels.palette(tri, 0, 256)
end
local tri = buffer.create(768)
for i = 0, 767 do
buffer.writeu8(tri, i, i // 3)
end
return Pixels.palette(tri, 0, 256)
end
local function paletteList(pal: buffer): { { number } }
local list = table.create(256) :: { { number } }
for i = 0, 255 do
local v = readu32(pal, i * 4)
list[i + 1] = { bit32.band(v, 255), bit32.band(bit32.rshift(v, 8), 255), bit32.band(bit32.rshift(v, 16), 255), 255 }
end
return list
end
-- PALETTE.DAT: 768 palette bytes, u16 numshades, numshades x 256 shade table, 65536-byte translucency table
local function shadeTables(dat: buffer): (number, buffer?, buffer?)
local n = buffer.len(dat)
if n < 770 then
return 0, nil, nil
end
local count = readu16(dat, 768)
if count == 0 or 770 + count * 256 > n then
return 0, nil, nil
end
local tables = buffer.create(count * 256)
buffer.copy(tables, 0, dat, 770, count * 256)
local tr: buffer? = nil
local at = 770 + count * 256
if at + 65536 <= n then
local t = buffer.create(65536)
buffer.copy(t, 0, dat, at, 65536)
tr = t
end
return count, tables, tr
end
-- LOOKUP.DAT: u8 count, count x (u8 palnum, 256-byte remap), then up to 5 alternate 768-byte palettes (Duke 3D)
local function lookups(dat: buffer): ({ [number]: buffer }, { buffer })
local n = buffer.len(dat)
local out: { [number]: buffer } = {}
local alts: { buffer } = {}
if n < 1 then
return out, alts
end
local count = readu8(dat, 0)
local p = 1
for _ = 1, count do
if p + 257 > n then
return out, alts
end
local t = buffer.create(256)
buffer.copy(t, 0, dat, p + 1, 256)
out[readu8(dat, p)] = t
p += 257
end
while p + 768 <= n and #alts < 5 do
local a = buffer.create(768)
buffer.copy(a, 0, dat, p, 768)
table.insert(alts, a)
p += 768
end
return out, alts
end
local function picanm(v: number): Picanm
local function s8(x: number): number
return if x >= 128 then x - 256 else x
end
return {
frames = bit32.band(v, 63),
type = TYPES[bit32.band(bit32.rshift(v, 6), 3) + 1] :: any,
xoffset = s8(bit32.band(bit32.rshift(v, 8), 255)),
yoffset = s8(bit32.band(bit32.rshift(v, 16), 255)),
speed = bit32.band(bit32.rshift(v, 24), 15),
extra = bit32.rshift(v, 28),
}
end
function Art.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
local o: DecodeOptions = opts or {}
local b, base, limit = r.buf, r.base, r.limit
local at, first, last, numtiles, prefixed = header(b, base, limit)
if not at or not first or not last then
if limit - base < 16 then
return nil, Err.new(Err.TRUNCATED, "short header", base)
end
return nil, Err.new(Err.CORRUPT, "not an ART file (version 1, first <= last tile)", base)
end
local n = last - first + 1
local p = at :: number
if limit - p < n * 8 then
return nil, Err.new(Err.TRUNCATED, "tile tables", p)
end
local maxPixels = o.maxPixels or 2 ^ 26
local sizes = table.create(n * 2) :: { number }
local total = 0
for i = 0, n - 1 do
local w, h = readi16(b, p + i * 2), readi16(b, p + n * 2 + i * 2)
if w < 0 or h < 0 then
return nil, Err.new(Err.CORRUPT, string.format("tile %d has a negative size", first + i), p + i * 2)
end
sizes[i * 2 + 1], sizes[i * 2 + 2] = w, h
total += w * h
end
if total > maxPixels then
return nil, Err.new(Err.LIMIT, string.format("%d pixels is over the %d pixel limit", total, maxPixels))
end
local datStart = p + n * 8
local palDat = fetch(o, "palette", "PALETTE.DAT")
local pal = makePalette(if type(o.palette) == "table" then o.palette else nil, palDat)
local hasPalette = type(o.palette) == "table" or (palDat ~= nil and buffer.len(palDat) >= 768)
local remap: buffer? = nil
local numShades, shades, translucency = 0, nil :: buffer?, nil :: buffer?
if palDat then
numShades, shades, translucency = shadeTables(palDat)
end
local lookDat = fetch(o, "lookup", "LOOKUP.DAT")
local looks, alts = {} :: { [number]: buffer }, {} :: { buffer }
if lookDat then
looks, alts = lookups(lookDat)
end
local palNum = math.floor(tonumber(o.pal) or 0)
if palNum ~= 0 then
local t = looks[palNum]
if not t then
return nil, Err.new(Err.ARG, string.format("palookup %d is not in LOOKUP.DAT", palNum))
end
remap = t
end
local shade = math.floor(tonumber(o.shade) or 0)
local shadeAt = -1
if shade ~= 0 then
if not shades or shade < 0 or shade >= numShades then
return nil, Err.new(Err.ARG, string.format("shade %d is not in PALETTE.DAT", shade))
end
shadeAt = shade * 256
end
local native = o.native == true
local frames = table.create(n) :: { Types.Frame }
local truncated = false
local q = datStart
local main: Types.Image? = nil
for i = 0, n - 1 do
local w, h = sizes[i * 2 + 1], sizes[i * 2 + 2]
local img = Types.Image.new(w, h, if native then "gray8" else "rgba8")
local px = img.pixels
local avail = math.clamp(limit - q, 0, w * h)
if avail < w * h then
truncated = true
end
-- pixels are stored column by column
for x = 0, w - 1 do
local col = q + x * h
for y = 0, h - 1 do
local k = x * h + y
local idx = if k < avail then readu8(b, col + y) else TRANSPARENT
local out = idx
if idx ~= TRANSPARENT then
if remap then
out = readu8(remap, out)
end
if shades and shadeAt >= 0 then
out = readu8(shades, shadeAt + out)
end
end
if native then
buffer.writeu8(px, y * w + x, out)
elseif idx == TRANSPARENT then
buffer.writeu32(px, (y * w + x) * 4, 0)
else
buffer.writeu32(px, (y * w + x) * 4, readu32(pal, out * 4))
end
end
end
q += w * h
local anm = readu32(b, p + n * 4 + i * 4)
img.meta.tile = first + i
img.meta.picanm = picanm(anm)
img.meta.source = { format = "art", picanm = anm }
table.insert(frames, { image = img, delay = 0, x = 0, y = 0, dispose = "none", blend = "source" } :: Types.Frame)
if not main and w > 0 then
main = img
end
end
local top = main or Types.Image.new(0, 0, if native then "gray8" else "rgba8")
local img = Types.Image.new(top.width, top.height, top.format)
buffer.copy(img.pixels, 0, top.pixels)
img.frames = frames
img.meta.palette = paletteList(pal)
img.meta.tile = top.meta.tile
img.meta.picanm = top.meta.picanm
if shades then
img.meta.shades = { count = numShades, data = shades }
end
if translucency then
img.meta.translucency = translucency
end
if next(looks) then
img.meta.lookups = looks
end
if #alts > 0 then
img.meta.altPalettes = alts
end
if truncated then
img.meta.truncated = true
end
img.meta.source = {
format = "art",
bitDepth = 8,
colorType = "palette",
version = 1,
numtiles = numtiles,
tileStart = first,
tileEnd = last,
buildart = prefixed,
palette = hasPalette,
trailing = math.max(0, limit - q),
}
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function picanmWord(m: any, fallback: number?): number
if type(m) ~= "table" then
return fallback or 0
end
local function u8(v: any): number
return math.floor(tonumber(v) or 0) % 256
end
local t = TYPE_INDEX[m.type] or 0
return bit32.bor(
bit32.band(math.floor(tonumber(m.frames) or 0), 63),
bit32.lshift(t, 6),
bit32.lshift(u8(m.xoffset), 8),
bit32.lshift(u8(m.yoffset), 16),
bit32.lshift(bit32.band(math.floor(tonumber(m.speed) or 0), 15), 24),
bit32.lshift(bit32.band(math.floor(tonumber(m.extra) or 0), 15), 28)
)
end
function Art.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, "needs an Image")
end
local o: EncodeOptions = opts or {}
local list: { Types.Image } = {}
if type(img.frames) == "table" and #img.frames > 0 then
for _, f in img.frames do
if type(f) ~= "table" or type(f.image) ~= "table" then
return nil, Err.new(Err.ARG, "bad frame")
end
table.insert(list, f.image)
end
else
list[1] = img
end
local meta: any = img.meta or {}
local src: any = meta.source or {}
local palSrc: any = o.palette or meta.palette
local palList: { { number } }? = nil
if palSrc ~= nil then
if type(palSrc) == "table" then
palList = palSrc
else
local dat = bytesOf(palSrc)
if not dat or buffer.len(dat) < 768 then
return nil, Err.new(Err.ARG, "palette must be PALETTE.DAT bytes or a list of colours")
end
palList = paletteList(makePalette(nil, dat))
end
end
local first = math.floor(tonumber(o.tileStart) or tonumber(src.tileStart) or tonumber(list[1].meta and list[1].meta.tile) or 0)
if first < 0 or first + #list - 1 > 0xFFFFFFFF then
return nil, Err.new(Err.ARG, "bad tileStart")
end
local n = #list
local total = 0
for i, t in list do
local w, h = t.width, t.height
if type(w) ~= "number" or type(h) ~= "number" or w < 0 or h < 0 or w > 32767 or h > 32767 or type(t.pixels) ~= "buffer" then
return nil, Err.new(Err.ARG, string.format("frame %d: size must be 0..32767", i))
end
if w * h > 0 then
if t.format == "rgba8" then
if not palList then
return nil, Err.new(Err.ARG, "rgba8 tiles need a palette (opts.palette or meta.palette)")
end
elseif t.format ~= "gray8" then
return nil, Err.new(Err.ARG, string.format("frame %d: needs rgba8 or gray8 (indices)", i))
end
if buffer.len(t.pixels) < w * h * (if t.format == "rgba8" then 4 else 1) then
return nil, Err.new(Err.ARG, string.format("frame %d: short pixel buffer", i))
end
end
total += w * h
end
local prefixed = if o.buildart ~= nil then o.buildart == true else src.buildart == true
local out = Bytes.writer((if prefixed then 8 else 0) + 16 + n * 8 + total)
if prefixed then
out:string("BUILDART")
end
out:u32le(1)
out:u32le(math.floor(tonumber(o.numtiles) or tonumber(src.numtiles) or 0) % 2 ^ 32)
out:u32le(first)
out:u32le(first + n - 1)
for _, t in list do
out:u16le(t.width)
end
for _, t in list do
out:u16le(t.height)
end
for _, t in list do
local m: any = t.meta or {}
out:u32le(picanmWord(m.picanm, m.source and tonumber(m.source.picanm)))
end
for _, t in list do
local w, h = t.width, t.height
if w * h > 0 then
local idx: buffer
if t.format == "rgba8" then
idx = Quantize.map(t.pixels, w, h, palList :: { { number } }, { transparentIndex = TRANSPARENT })
else
idx = t.pixels
end
for x = 0, w - 1 do
for y = 0, h - 1 do
out:u8(readu8(idx, y * w + x))
end
end
end
end
return out:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ extras
Art.picanm = picanm
Art.picanmWord = picanmWord
return Art
+401
View File
@@ -0,0 +1,401 @@
--!strict
-- model/buildmap/Geometry: Build map tables to a Scene. Slopes after BUILDINF.TXT (heinum: z rises heinum / 4096 per
-- unit across the first wall, z units 16 to an xy unit); walls split at red walls into upper / lower parts and clipped
-- where they cross, as Ken Silverman's map2stl does; texture coordinates approximate the engine's (xrepeat * 8 pixels
-- across a wall, 128 z units per pixel at yrepeat 8, 16 units per floor pixel). New code.
local Types = require("@rosetta/Types")
local Polygon = require("@rosetta/codecs/model/Polygon")
local Geometry = {}
local Scene = Types.Scene
export type Sector = { [string]: number }
export type Wall = { [string]: number }
export type Map = {
version: number,
x: number,
y: number,
z: number,
ang: number, -- 2048 = a full turn, 0 = +x, 512 = +y
cursectnum: number,
sectors: { Sector }, -- raw fields, indices 0-based as in the file
walls: { Wall },
sprites: { { [string]: number } },
trailing: buffer?, -- bytes after the sprites (kept for the writer)
}
export type Options = {
scale: number?, -- world units per Build xy unit, default 1 (z is divided by 16 first)
tiles: { [number]: any }?, -- tile number -> Image or { width, height }: texture sizes for the UVs, images attached
skyWalls: boolean?, -- keep upper / lower walls between two parallaxed ceilings / floors; default false
}
local PARALLAX, SLOPED, SWAP_XY, SMOOSH, FLIP_X, FLIP_Y, RELATIVE = 1, 2, 4, 8, 16, 32, 64
local W_BOTTOM_SWAP, W_ALIGN_BOTTOM, W_FLIP_X, W_MASKED, W_FLIP_Y = 2, 4, 8, 16, 256
local YAX_BIT = 1024
local band = bit32.band
-- ------------------------------------------------------------------------------------------------ queries
function Geometry.slopeZ(map: Map, sector: number, floor: boolean, x: number, y: number): number
local s = map.sectors[sector + 1]
if not s then
return 0
end
local z = if floor then s.floorz else s.ceilingz
local stat = if floor then s.floorstat else s.ceilingstat
local heinum = if floor then s.floorheinum else s.ceilingheinum
if band(stat, SLOPED) == 0 or heinum == 0 then
return z
end
local w0 = map.walls[s.wallptr + 1]
local w1 = w0 and map.walls[w0.point2 + 1]
if not w1 then
return z
end
local dx, dy = w1.x - w0.x, w1.y - w0.y
local len = math.sqrt(dx * dx + dy * dy)
if len == 0 then
return z
end
return z + heinum * (dx * (y - w0.y) - dy * (x - w0.x)) / (len * 256)
end
-- the sector's wall loops (0-based wall indices, following point2); loops that leave the sector or do not close are dropped
function Geometry.loops(map: Map, sector: number): { { number } }
local s = map.sectors[sector + 1]
local out: { { number } } = {}
if not s then
return out
end
local first, last = s.wallptr, s.wallptr + s.wallnum - 1
local seen: { [number]: boolean } = {}
for start = first, last do
if not seen[start] then
local loop: { number } = {}
local w = start
local ok = false
for _ = 0, s.wallnum do
if w < first or w > last or seen[w] then
break
end
local wall = map.walls[w + 1]
if not wall then
break
end
seen[w] = true
table.insert(loop, w)
w = wall.point2
if w == start then
ok = true
break
end
end
if ok and #loop >= 3 then
table.insert(out, loop)
end
end
end
return out
end
-- v9 room over room (eduke32 YAX): bunch numbers in the x panning of a ceiling / floor flagged 1024; walls flagged
-- 1024 / 2048 keep the linked wall in lotag (ceiling) / extra (floor)
function Geometry.yax(map: Map)
for _, s in map.sectors do
if band(s.ceilingstat, YAX_BIT) ~= 0 then
s.ceilingbunch = s.ceilingxpanning
end
if band(s.floorstat, YAX_BIT) ~= 0 then
s.floorbunch = s.floorxpanning
end
end
for _, w in map.walls do
if band(w.cstat, YAX_BIT) ~= 0 then
w.yaxceilingwall = w.lotag
end
if band(w.cstat, YAX_BIT * 2) ~= 0 then
w.yaxfloorwall = w.extra
end
end
end
-- ------------------------------------------------------------------------------------------------ scene
type Batch = { kind: string, tile: number, data: { number }, n: number } -- data: x y z nx ny nz u v per vertex
function Geometry.scene(map: Map, opts: Options): Types.Scene
local scale = tonumber(opts.scale) or 1
local tiles = if type(opts.tiles) == "table" then opts.tiles else nil
local skyWalls = opts.skyWalls == true
local walls, sectors = map.walls, map.sectors
local batches: { [string]: Batch } = {}
local order: { Batch } = {}
local function tileSize(tile: number): (number, number)
local t = tiles and tiles[tile]
local w, h = if type(t) == "table" then tonumber(t.width) else nil, if type(t) == "table" then tonumber(t.height) else nil
return if w and w > 0 then w else 64, if h and h > 0 then h else 64
end
local function batch(kind: string, tile: number): Batch
local key = kind .. ":" .. tile
local b = batches[key]
if not b then
b = { kind = kind, tile = tile, data = {}, n = 0 }
batches[key] = b
table.insert(order, b)
end
return b
end
local function emit(b: Batch, v: { number })
local d = b.data
local k = #d
for i = 1, 8 do
d[k + i] = v[i]
end
b.n += 1
end
local function world(x: number, y: number, z: number): (number, number, number)
return x * scale, -y * scale, -z / 16 * scale
end
local function tri(b: Batch, a: { number }, c: { number }, d: { number })
-- a / c / d: Build x, y, z, u, v
local ax, ay, az = world(a[1], a[2], a[3])
local cx, cy, cz = world(c[1], c[2], c[3])
local dx, dy, dz = world(d[1], d[2], d[3])
local ux, uy, uz = cx - ax, cy - ay, cz - az
local vx, vy, vz = dx - ax, dy - ay, dz - az
local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
local l = math.sqrt(nx * nx + ny * ny + nz * nz)
if l == 0 then
return
end
nx, ny, nz = nx / l, ny / l, nz / l
emit(b, { ax, ay, az, nx, ny, nz, a[4], a[5] })
emit(b, { cx, cy, cz, nx, ny, nz, c[4], c[5] })
emit(b, { dx, dy, dz, nx, ny, nz, d[4], d[5] })
end
-- floors and ceilings
local secLoops: { { { number } } } = {}
for si, s in sectors do
local ls = Geometry.loops(map, si - 1)
secLoops[si] = ls
local flat: { { number } } = {}
for li, loop in ls do
local f: { number } = {}
for _, w in loop do
table.insert(f, walls[w + 1].x)
table.insert(f, -walls[w + 1].y)
end
flat[li] = f
end
local tris = Polygon.triangulate(flat)
for pass = 1, 2 do
local isFloor = pass == 1
local stat = if isFloor then s.floorstat else s.ceilingstat
if not (map.version == 9 and band(stat, YAX_BIT) ~= 0) then
local tile = if isFloor then s.floorpicnum else s.ceilingpicnum
local tw, th = tileSize(tile)
local texel = if band(stat, SMOOSH) ~= 0 then 8 else 16
local xpan = (if isFloor then s.floorxpanning else s.ceilingxpanning) * tw / 256
local ypan = (if isFloor then s.floorypanning else s.ceilingypanning) * th / 256
local ox, oy, ex, ey = 0, 0, 1, 0
if band(stat, RELATIVE) ~= 0 then
local w0 = walls[s.wallptr + 1]
local w1 = w0 and walls[w0.point2 + 1]
if w1 then
local dx, dy = w1.x - w0.x, w1.y - w0.y
local len = math.sqrt(dx * dx + dy * dy)
if len > 0 then
ox, oy, ex, ey = w0.x, w0.y, dx / len, dy / len
end
end
end
local b = batch(if isFloor then "floor" else "ceiling", tile)
local function corner(li: number, vi: number): { number }
local w = walls[ls[li][vi] + 1]
local x, y = w.x, w.y
local lx, ly = (x - ox) * ex + (y - oy) * ey, (y - oy) * ex - (x - ox) * ey
if band(stat, SWAP_XY) ~= 0 then
lx, ly = ly, lx
end
if band(stat, FLIP_X) ~= 0 then
lx = -lx
end
if band(stat, FLIP_Y) ~= 0 then
ly = -ly
end
return { x, y, Geometry.slopeZ(map, si - 1, isFloor, x, y), (lx / texel + xpan) / tw, (ly / texel + ypan) / th }
end
for k = 1, #tris, 6 do
local a, c, d = corner(tris[k], tris[k + 1]), corner(tris[k + 2], tris[k + 3]), corner(tris[k + 4], tris[k + 5])
if isFloor then
tri(b, a, c, d)
else
tri(b, a, d, c)
end
end
end
end
end
-- walls: (x1, y1) -> (x2, y2) with the sector on the right; top / bottom z at both ends, z down
local function part(kind: string, tile: number, w: Wall, x1: number, y1: number, x2: number, y2: number, t1: number, t2: number, b1: number, b2: number, anchor: number, fromBottom: boolean)
local h1, h2 = b1 - t1, b2 - t2
if h1 <= 0 and h2 <= 0 then
return
end
local tw, th = tileSize(tile)
local flipX, flipY = band(w.cstat, W_FLIP_X) ~= 0, band(w.cstat, W_FLIP_Y) ~= 0
local span = w.xrepeat * 8
local function v(t: number, z: number): { number }
local u = (w.xpanning + (if flipX then 1 - t else t) * span) / tw
local px = (z - anchor) * w.yrepeat / 1024 + w.ypanning * th / 256 + (if fromBottom then th else 0)
local vv = px / th
return { x1 + (x2 - x1) * t, y1 + (y2 - y1) * t, z, u, if flipY then -vv else vv }
end
local b = batch(kind, tile)
if h1 > 0 and h2 > 0 then
local p1b, p2b, p2t, p1t = v(0, b1), v(1, b2), v(1, t2), v(0, t1)
tri(b, p1b, p2b, p2t)
tri(b, p1b, p2t, p1t)
elseif h1 > 0 then
local f = h1 / (h1 - h2)
tri(b, v(0, b1), v(f, t1 + (t2 - t1) * f), v(0, t1))
else
local f = h1 / (h1 - h2)
tri(b, v(f, t1 + (t2 - t1) * f), v(1, b2), v(1, t2))
end
end
for si, s in sectors do
local me = si - 1
for _, loop in secLoops[si] do
for _, wi in loop do
local w = walls[wi + 1]
local w2 = walls[w.point2 + 1]
local x1, y1, x2, y2 = w.x, w.y, w2.x, w2.y
local c1, c2 = Geometry.slopeZ(map, me, false, x1, y1), Geometry.slopeZ(map, me, false, x2, y2)
local f1, f2 = Geometry.slopeZ(map, me, true, x1, y1), Geometry.slopeZ(map, me, true, x2, y2)
local ns = w.nextsector
local other = if ns >= 0 then sectors[ns + 1] else nil
if not other then
local fromBottom = band(w.cstat, W_ALIGN_BOTTOM) ~= 0
part("wall", w.picnum, w, x1, y1, x2, y2, c1, c2, f1, f2, if fromBottom then s.floorz else s.ceilingz, fromBottom)
else
local oc1, oc2 = Geometry.slopeZ(map, ns, false, x1, y1), Geometry.slopeZ(map, ns, false, x2, y2)
local of1, of2 = Geometry.slopeZ(map, ns, true, x1, y1), Geometry.slopeZ(map, ns, true, x2, y2)
local aligned = band(w.cstat, W_ALIGN_BOTTOM) ~= 0
if skyWalls or band(s.ceilingstat, PARALLAX) == 0 or band(other.ceilingstat, PARALLAX) == 0 then
part("wall", w.picnum, w, x1, y1, x2, y2, c1, c2, oc1, oc2, if aligned then s.ceilingz else other.ceilingz, not aligned)
end
if skyWalls or band(s.floorstat, PARALLAX) == 0 or band(other.floorstat, PARALLAX) == 0 then
local lw = w
if band(w.cstat, W_BOTTOM_SWAP) ~= 0 and walls[w.nextwall + 1] then
lw = walls[w.nextwall + 1]
end
part("wall", lw.picnum, lw, x1, y1, x2, y2, of1, of2, f1, f2, if aligned then s.ceilingz else other.floorz, false)
end
if band(w.cstat, W_MASKED) ~= 0 then
local fromBottom = aligned
part("masked", w.overpicnum, w, x1, y1, x2, y2, math.max(c1, oc1), math.max(c2, oc2), math.min(f1, of1), math.min(f2, of2),
if fromBottom then math.min(s.floorz, other.floorz) else math.max(s.ceilingz, other.ceilingz), fromBottom)
end
end
end
end
end
-- the mesh: a primitive per (kind, tile), a material per tile (masked walls their own, alpha-masked)
local scene = Scene.new()
scene.meta.up = "z"
local mesh: Types.Mesh = { name = "map", primitives = {} }
local texIndex: { [number]: number } = {}
local matIndex: { [string]: number } = {}
for _, b in order do
local n = b.n
if n > 0 then
local pos, nrm, uv, idx = buffer.create(n * 12), buffer.create(n * 12), buffer.create(n * 8), buffer.create(n * 4)
local d = b.data
for i = 0, n - 1 do
local k = i * 8
buffer.writef32(pos, i * 12, d[k + 1])
buffer.writef32(pos, i * 12 + 4, d[k + 2])
buffer.writef32(pos, i * 12 + 8, d[k + 3])
buffer.writef32(nrm, i * 12, d[k + 4])
buffer.writef32(nrm, i * 12 + 4, d[k + 5])
buffer.writef32(nrm, i * 12 + 8, d[k + 6])
buffer.writef32(uv, i * 8, d[k + 7])
buffer.writef32(uv, i * 8 + 4, d[k + 8])
buffer.writeu32(idx, i * 4, i)
end
local ti = texIndex[b.tile]
if not ti then
local t = tiles and tiles[b.tile]
table.insert(scene.textures, {
name = "tile" .. b.tile,
uri = "tile" .. b.tile,
image = if type(t) == "table" and t.kind == "image" then t else nil,
extras = { build = { tile = b.tile } },
})
ti = #scene.textures
texIndex[b.tile] = ti
end
local masked = b.kind == "masked"
local mkey = (if masked then "m" else "s") .. b.tile
local mi = matIndex[mkey]
if not mi then
local mat = Scene.material("tile" .. b.tile)
mat.metallic = 0
mat.baseColorTexture = { texture = ti }
if masked then
mat.alphaMode = "mask"
mat.doubleSided = true
end
mat.extras = { build = { tile = b.tile } }
table.insert(scene.materials, mat)
mi = #scene.materials
matIndex[mkey] = mi
end
table.insert(mesh.primitives, {
attributes = {
POSITION = Scene.accessor(pos, "f32", 3, n),
NORMAL = Scene.accessor(nrm, "f32", 3, n),
TEXCOORD_0 = Scene.accessor(uv, "f32", 2, n),
},
indices = Scene.accessor(idx, "u32", 1, n),
mode = "triangles" :: any,
material = mi,
extras = { build = { kind = b.kind, tile = b.tile } },
})
end
end
table.insert(scene.meshes, mesh)
local root: Types.Node = { name = "map", children = {}, mesh = 1 }
scene.nodes[1] = root
scene.roots[1] = 1
local function yaw(ang: number): { number }
local a = -ang * math.pi / 2048
return { 0, 0, math.sin(a), math.cos(a) }
end
local sx, sy, sz = world(map.x, map.y, map.z)
table.insert(scene.nodes, {
name = "start",
children = {},
translation = { sx, sy, sz },
rotation = yaw(map.ang),
extras = { build = { start = true, sector = map.cursectnum } },
})
table.insert(root.children, #scene.nodes)
for i, sp in map.sprites do
local px, py, pz = world(sp.x, sp.y, sp.z)
table.insert(scene.nodes, {
name = "sprite " .. (i - 1),
children = {},
translation = { px, py, pz },
rotation = yaw(sp.ang),
extras = { build = { tile = sp.picnum, sprite = sp } },
})
table.insert(root.children, #scene.nodes)
end
return scene
end
return Geometry
+270
View File
@@ -0,0 +1,270 @@
--!strict
-- model/buildmap: Build engine maps (.map versions 7-9: Duke Nukem 3D, Shadow Warrior, eduke32), from Ken Silverman's
-- BUILDINF.TXT and the eduke32 wiki ("MAP format"); no code taken. Supports: sectors, walls, sprites as raw tables
-- (meta.build), a Scene (sloped floors / ceilings, walls with upper / lower parts at red walls, masked walls, sprites
-- as nodes), v9 room-over-room fields, trailing bytes; writes the raw tables back. Not supported: v5 / v6, Blood's
-- encrypted BLM maps, the eduke32 text format (v10).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Geometry = require("@rosetta/model/buildmap/Geometry")
-- ------------------------------------------------------------------------------------------------ contract
local BuildMap = {
name = "buildmap",
category = "model",
extensions = { "map" },
mime = { "application/x-build-map" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Polygon" },
caps = { decode = true, encode = true, sprites = true, slopes = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type Sector = Geometry.Sector
export type Wall = Geometry.Wall
export type Sprite = { [string]: number }
export type Map = Geometry.Map
export type DecodeOptions = Geometry.Options & {
maxBytes: number?, -- default 2^28
}
export type EncodeOptions = {
version: number?, -- 7, 8 or 9; default map.version
}
-- ------------------------------------------------------------------------------------------------ constants
-- field name, size (1 / -1 = u8 / i8, 2 / -2 = u16 / i16, -4 = i32), BUILDINF.TXT order
local SECTOR = {
{ "wallptr", -2 }, { "wallnum", -2 }, { "ceilingz", -4 }, { "floorz", -4 }, { "ceilingstat", -2 }, { "floorstat", -2 },
{ "ceilingpicnum", -2 }, { "ceilingheinum", -2 }, { "ceilingshade", -1 }, { "ceilingpal", 1 }, { "ceilingxpanning", 1 },
{ "ceilingypanning", 1 }, { "floorpicnum", -2 }, { "floorheinum", -2 }, { "floorshade", -1 }, { "floorpal", 1 },
{ "floorxpanning", 1 }, { "floorypanning", 1 }, { "visibility", 1 }, { "filler", 1 }, { "lotag", -2 }, { "hitag", -2 },
{ "extra", -2 },
}
local WALL = {
{ "x", -4 }, { "y", -4 }, { "point2", -2 }, { "nextwall", -2 }, { "nextsector", -2 }, { "cstat", -2 }, { "picnum", -2 },
{ "overpicnum", -2 }, { "shade", -1 }, { "pal", 1 }, { "xrepeat", 1 }, { "yrepeat", 1 }, { "xpanning", 1 },
{ "ypanning", 1 }, { "lotag", -2 }, { "hitag", -2 }, { "extra", -2 },
}
local SPRITE = {
{ "x", -4 }, { "y", -4 }, { "z", -4 }, { "cstat", -2 }, { "picnum", -2 }, { "shade", -1 }, { "pal", 1 }, { "clipdist", 1 },
{ "filler", 1 }, { "xrepeat", 1 }, { "yrepeat", 1 }, { "xoffset", -1 }, { "yoffset", -1 }, { "sectnum", -2 },
{ "statnum", -2 }, { "ang", -2 }, { "owner", -2 }, { "xvel", -2 }, { "yvel", -2 }, { "zvel", -2 }, { "lotag", -2 },
{ "hitag", -2 }, { "extra", -2 },
}
local SECTOR_SIZE, WALL_SIZE, SPRITE_SIZE = 40, 32, 44
local HEADER = 22 -- version, posx, posy, posz, ang, cursectnum, then u16 numsectors at 20
local readu16 = buffer.readu16
-- ------------------------------------------------------------------------------------------------ sniff
local function layout(b: buffer, o: number, limit: number): (number?, number?, number?, number?)
if limit - o < HEADER then
return nil, nil, nil, nil
end
local ns = readu16(b, o + 20)
local p = o + HEADER + ns * SECTOR_SIZE
if p + 2 > limit then
return nil, nil, nil, nil
end
local nw = readu16(b, p)
p += 2 + nw * WALL_SIZE
if p + 2 > limit then
return nil, nil, nil, nil
end
local nsp = readu16(b, p)
p += 2 + nsp * SPRITE_SIZE
return ns, nw, nsp, p
end
function BuildMap.sniff(r: Bytes.Reader): number
local b, o, limit = r.buf, r.base, r.limit
if limit - o < HEADER then
return 0
end
local v = buffer.readu32(b, o)
if v ~= 7 and v ~= 8 and v ~= 9 then
return 0
end
local ns, _, _, stop = layout(b, o, limit)
if not ns or not stop or stop > limit then
return 0
end
return if stop == limit then 0.9 else 0.5
end
-- ------------------------------------------------------------------------------------------------ decode
local function readRecord(b: buffer, p: number, fields: { any }): { [string]: number }
local rec: { [string]: number } = {}
for _, f in fields do
local size = f[2]
local v
if size == 1 then
v = buffer.readu8(b, p)
elseif size == -1 then
v = buffer.readi8(b, p)
elseif size == 2 then
v = readu16(b, p)
elseif size == -2 then
v = buffer.readi16(b, p)
else
v = buffer.readi32(b, p)
end
rec[f[1]] = v
p += math.abs(size)
end
return rec
end
function BuildMap.parse(r: Bytes.Reader, opts: DecodeOptions?): (Map?, Err.Err?)
local b, o, limit = r.buf, r.base, r.limit
if limit - o < 4 then
return nil, Err.new(Err.TRUNCATED, "short header", o)
end
if buffer.readstring(b, o, 4) == "BLM\26" then
return nil, Err.new(Err.UNSUPPORTED, "Blood maps (BLM, encrypted) are not supported", o)
end
if buffer.readstring(b, o, 4) == "--ED" then
return nil, Err.new(Err.UNSUPPORTED, "eduke32 text maps (version 10) are not supported", o)
end
local version = buffer.readu32(b, o)
if version == 5 or version == 6 then
return nil, Err.new(Err.UNSUPPORTED, string.format("map version %d (only 7-9)", version), o)
elseif version < 7 or version > 9 then
return nil, Err.new(Err.CORRUPT, string.format("not a Build map (version %d)", version), o)
end
local maxBytes = opts and opts.maxBytes or 2 ^ 28
if limit - o > maxBytes then
return nil, Err.new(Err.LIMIT, string.format("%d bytes is over the %d byte limit", limit - o, maxBytes))
end
local ns, nw, nsp, stop = layout(b, o, limit)
if not ns or not nw or not nsp or not stop or stop > limit then
return nil, Err.new(Err.TRUNCATED, "sector / wall / sprite tables end early", o)
end
local map: Map = {
version = version,
x = buffer.readi32(b, o + 4),
y = buffer.readi32(b, o + 8),
z = buffer.readi32(b, o + 12),
ang = buffer.readi16(b, o + 16),
cursectnum = buffer.readi16(b, o + 18),
sectors = table.create(ns) :: { Sector },
walls = table.create(nw) :: { Wall },
sprites = table.create(nsp) :: { Sprite },
}
local p = o + HEADER
for i = 1, ns do
local s = readRecord(b, p, SECTOR) :: any
if s.wallptr < 0 or s.wallnum < 0 or s.wallptr + s.wallnum > nw then
return nil, Err.new(Err.CORRUPT, string.format("sector %d: walls %d + %d out of range", i - 1, s.wallptr, s.wallnum), p)
end
map.sectors[i] = s
p += SECTOR_SIZE
end
p += 2
for i = 1, nw do
map.walls[i] = readRecord(b, p, WALL) :: any
p += WALL_SIZE
end
p += 2
for i = 1, nsp do
map.sprites[i] = readRecord(b, p, SPRITE)
p += SPRITE_SIZE
end
if stop < limit then
local t = buffer.create(limit - stop)
buffer.copy(t, 0, b, stop, limit - stop)
map.trailing = t
end
if version == 9 then
Geometry.yax(map)
end
return map, nil
end
function BuildMap.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local map, err = BuildMap.parse(r, opts)
if not map then
return nil, err
end
return BuildMap.scene(map, opts), nil
end
function BuildMap.scene(map: Map, opts: Geometry.Options?): Types.Scene
local scene = Geometry.scene(map, opts or {})
scene.meta.build = map
scene.meta.source = {
format = "buildmap",
version = map.version,
sectors = #map.sectors,
walls = #map.walls,
sprites = #map.sprites,
}
return scene
end
-- ------------------------------------------------------------------------------------------------ encode
local function writeRecord(out: Bytes.Writer, rec: { [string]: any }, fields: { any }): string?
for _, f in fields do
local v = rec[f[1]]
if type(v) ~= "number" or v ~= v then
return f[1]
end
local size = math.abs(f[2])
local n = math.floor(v)
if size == 1 then
out:u8(n % 256)
elseif size == 2 then
out:u16le(n % 65536)
else
out:u32le(n % 4294967296)
end
end
return nil
end
function BuildMap.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local map = if type(value) == "table" and type(value.meta) == "table" and value.meta.build then value.meta.build else value
if type(map) ~= "table" or type(map.sectors) ~= "table" or type(map.walls) ~= "table" or type(map.sprites) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Scene from model/buildmap (meta.build) or a map table")
end
local version = math.floor(tonumber(opts and opts.version) or tonumber(map.version) or 7)
if version < 7 or version > 9 then
return nil, Err.new(Err.ARG, "version must be 7, 8 or 9")
end
local ns, nw, nsp = #map.sectors, #map.walls, #map.sprites
if ns > 65535 or nw > 65535 or nsp > 65535 then
return nil, Err.new(Err.ARG, "at most 65535 sectors / walls / sprites")
end
local trailing = if type(map.trailing) == "buffer" then map.trailing else nil
local out = Bytes.writer(HEADER + 6 + ns * SECTOR_SIZE + nw * WALL_SIZE + nsp * SPRITE_SIZE + (if trailing then buffer.len(trailing) else 0))
out:u32le(version)
for _, k in { "x", "y", "z" } do
out:u32le(math.floor(tonumber(map[k]) or 0) % 4294967296)
end
out:u16le(math.floor(tonumber(map.ang) or 0) % 65536)
out:u16le(math.floor(tonumber(map.cursectnum) or 0) % 65536)
for _, part in { { map.sectors, SECTOR, "sector" }, { map.walls, WALL, "wall" }, { map.sprites, SPRITE, "sprite" } } do
local list = part[1] :: { any }
out:u16le(#list)
for i, rec in list do
if type(rec) ~= "table" then
return nil, Err.new(Err.ARG, string.format("%s %d is not a table", part[3] :: string, i - 1))
end
local bad = writeRecord(out, rec, part[2] :: { any })
if bad then
return nil, Err.new(Err.ARG, string.format("%s %d: field %s is not a number", part[3] :: string, i - 1, bad))
end
end
end
if trailing then
out:bytes(trailing)
end
return out:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ extras
BuildMap.slopeZ = Geometry.slopeZ
BuildMap.loops = Geometry.loops
return BuildMap