From 75984be212a2377a584a2c9de2f1ef034477c356 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 18:33:29 -0600 Subject: [PATCH] image/art: Build engine ART tiles (frames per tile, picanm, PALETTE.DAT / LOOKUP.DAT through opts or resolve, shade / palookup remaps), read + write; tested against arttool from the eduke32 source --- README.md | 3 +- docs/FORMATS.md | 1 + src/Rosetta/Registry.luau | 12 + src/Rosetta/image/art/init.luau | 486 ++++++++++++++++++++++++++++++++ tests/image/art.luau | 133 +++++++++ tools/fixtures/_build_ref.py | 106 +++++++ tools/fixtures/art.py | 117 ++++++++ 7 files changed, 857 insertions(+), 1 deletion(-) create mode 100644 src/Rosetta/image/art/init.luau create mode 100644 tests/image/art.luau create mode 100644 tools/fixtures/_build_ref.py create mode 100644 tools/fixtures/art.py diff --git a/README.md b/README.md index 7af4b19..4bd99b2 100644 --- a/README.md +++ b/README.md @@ -44,12 +44,13 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list ## Formats -174 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) +175 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) adds each format's capabilities. | Category | Format | Extensions | Read | Write | |---|---|---|---|---| | Images | ani | .ani | yes | yes | +| Images | art | .art | yes | yes | | Images | blp | .blp | yes | yes | | Images | bmp | .bmp .dib | yes | yes | | Images | dds | .dds | yes | yes | diff --git a/docs/FORMATS.md b/docs/FORMATS.md index f2a9a60..944b262 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -6,6 +6,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | Category | Format | Extensions | Read | Write | Capabilities | Test | |---|---|---|---|---|---|---| | image | ani | .ani | yes | yes | alpha: true, animation: true, frames: true | `tests/image/ani.luau` | +| image | art | .art | yes | yes | alpha: true, palette: true, frames: true, depths: 8 | `tests/image/art.luau` | | image | blp | .blp | yes | yes | alpha: true, variants: "blp1", "blp2", compressions: "jpeg", "palette", "dxt1", "dxt3", "dxt5", "bgra" | `tests/image/blp.luau` | | image | bmp | .bmp .dib | yes | yes | alpha: true, depths: 1, 2, 4, 8, 16, 24, 32, rle: true | `tests/image/bmp.luau` | | image | dds | .dds | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7" | `tests/image/dds.luau` | diff --git a/src/Rosetta/Registry.luau b/src/Rosetta/Registry.luau index 062b60a..9919473 100644 --- a/src/Rosetta/Registry.luau +++ b/src/Rosetta/Registry.luau @@ -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", diff --git a/src/Rosetta/image/art/init.luau b/src/Rosetta/image/art/init.luau new file mode 100644 index 0000000..7cd1d90 --- /dev/null +++ b/src/Rosetta/image/art/init.luau @@ -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 + end + local first, last = readu32(b, p + 8), readu32(b, p + 12) + if last < first or last - first >= 65536 then + return 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: { { number } } = table.create(256) + 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: { number } = table.create(n * 2) + 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: { Types.Frame } = table.create(n) + 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 = img.meta or {} + local src = 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 = 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 diff --git a/tests/image/art.luau b/tests/image/art.luau new file mode 100644 index 0000000..af973e6 --- /dev/null +++ b/tests/image/art.luau @@ -0,0 +1,133 @@ +-- image/art tests against arttool (eduke32 tools) and an independent Python reading (tools/fixtures/art.py): indices, +-- picanm fields, colours through PALETTE.DAT as arttool exports them, shade / palookup remaps, write round trips. +local T = require("@tests/T") +local Art = require("@rosetta/image/art") +local Bytes = require("@rosetta/core/Bytes") +local Err = require("@rosetta/core/Err") +local Fx = require("@tests/gen/art") + +local t = T.suite("art") +t:eq(Art.name, "art", "name") +t:check(Art.caps.decode and Art.caps.encode, "caps") + +local data = buffer.fromstring(Fx.art) +t:eq(Art.sniff(Bytes.reader(data)), 0.9, "sniff") +t:eq(Art.sniff(Bytes.reader(buffer.fromstring("GIF89a........................"))), 0, "sniff other") + +local TYPES = { [0] = "none", "oscillate", "forward", "backward" } +local function s8(v: number): number + return if v >= 128 then v - 256 else v +end + +local nat = assert(Art.decode(Bytes.reader(data), { native = true })) +local img = assert(Art.decode(Bytes.reader(data), { palette = Fx.palette })) +t:eq(#(nat.frames :: any), Fx.last - Fx.start + 1, "one frame per tile") +t:eq(img.meta.source.tileStart, Fx.start, "tileStart") +t:eq(img.meta.source.tileEnd, Fx.last, "tileEnd") +t:check(img.meta.source.palette, "palette used") +t:eq(img.meta.shades.count, 32, "shade tables") +t:check(img.meta.translucency and buffer.len(img.meta.translucency) == 65536, "translucency table") +for i, c in Fx.tiles do + local fn = (nat.frames :: any)[i].image + local fr = (img.frames :: any)[i].image + local label = "tile " .. c.tile + t:eq(fn.meta.tile, c.tile, label .. ": number") + t:eq(fn.width, c.w, label .. ": width") + t:eq(fn.height, c.h, label .. ": height") + local p = fn.meta.picanm + t:eq(p.frames, c.animFrames, label .. ": anim frames") + t:eq(p.type, TYPES[c.animType], label .. ": anim type") + t:eq(p.speed, c.animSpeed, label .. ": anim speed") + t:eq(p.xoffset, s8(c.xofs), label .. ": x offset") + t:eq(p.yoffset, s8(c.yofs), label .. ": y offset") + t:eq(Art.picanmWord(p), c.picanm, label .. ": picanm word") + if c.idx then + t:eq(buffer.tostring(fn.pixels), c.idx, label .. ": indices") + local bad = 0 + for k = 0, c.w * c.h - 1 do + local idx = string.byte(c.idx, k + 1) + local px = fr.pixels + if idx == 255 then + if buffer.readu32(px, k * 4) ~= 0 then + bad += 1 + end + else + for ch = 0, 2 do + if buffer.readu8(px, k * 4 + ch) ~= string.byte(c.rgb, k * 3 + ch + 1) then + bad += 1 + end + end + if buffer.readu8(px, k * 4 + 3) ~= 255 then + bad += 1 + end + end + end + t:eq(bad, 0, label .. ": colours as arttool exports them") + end +end +t:eq(img.width, Fx.tiles[1].w, "top-level image = first non-empty tile") + +-- shade and palookup remaps (index 255 stays transparent) +do + local resolve = function(name: string): buffer? + if name == "PALETTE.DAT" then + return buffer.fromstring(Fx.palette) + elseif name == "LOOKUP.DAT" then + return buffer.fromstring(Fx.lookup) + end + return nil + end + local sh = assert(Art.decode(Bytes.reader(data), { resolve = resolve, native = true, shade = Fx.shade.n, pal = Fx.remap.pal })) + t:check(sh.meta.lookups[1] and sh.meta.lookups[5], "palookups 1 and 5") + t:eq(#sh.meta.altPalettes, 5, "alternate palettes") + local c = Fx.tiles[1] + local fr = (sh.frames :: any)[1].image + local bad = 0 + for k = 0, c.w * c.h - 1 do + local idx = string.byte(c.idx, k + 1) + local want = if idx == 255 then 255 else string.byte(Fx.shade.table, string.byte(Fx.remap.table, idx + 1) + 1) + if buffer.readu8(fr.pixels, k) ~= want then + bad += 1 + end + end + t:eq(bad, 0, "palookup then shade") + local _, e = Art.decode(Bytes.reader(data), { resolve = resolve, pal = 9 }) + t:check(e and e.code == Err.ARG, "missing palookup") + local grey = assert(Art.decode(Bytes.reader(data))) + t:eq(grey.meta.source.palette, false, "no palette: grey ramp") +end + +-- write: native round trip is byte exact; rgba8 maps back through the palette +do + local again = assert(Art.encode(nat)) + t:eq(buffer.tostring(again), Fx.art, "native round trip") + local again2 = assert(Art.encode(img)) + t:eq(buffer.tostring(again2), Fx.art, "rgba8 round trip through the palette") + local pref = assert(Art.encode(nat, { buildart = true })) + t:eq(buffer.readstring(pref, 0, 8), "BUILDART", "BUILDART prefix") + local back = assert(Art.decode(Bytes.reader(pref), { native = true })) + t:check(back.meta.source.buildart, "prefix read") + t:eq(buffer.tostring(assert(Art.encode(back, { buildart = false }))), Fx.art, "prefix round trip") + -- a single image becomes one tile + local one = assert(Art.encode((img.frames :: any)[4].image, { palette = img.meta.palette, tileStart = 100 })) + local d1 = assert(Art.decode(Bytes.reader(one), { native = true })) + t:eq(d1.meta.source.tileStart, 100, "single tile number") + t:eq(buffer.tostring(d1.pixels), Fx.tiles[4].idx, "single tile indices") + local _, e = Art.encode((img.frames :: any)[1].image) + t:check(e and e.code == Err.ARG, "rgba8 without a palette") +end + +-- errors +do + local _, e = Art.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.art, 1, 10)))) + t:check(e and e.code == Err.TRUNCATED, "short header") + local _, e2 = Art.decode(Bytes.reader(data), { maxPixels = 10 }) + t:check(e2 and e2.code == Err.LIMIT, "limit") + local cut = assert(Art.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.art, 1, #Fx.art - 100))))) + t:check(cut.meta.truncated, "truncated pixels flagged") +end + +t:fuzz("decode", function(b: buffer) + return Art.decode(Bytes.reader(b), { palette = Fx.palette }) +end, { Fx.art }, { mutations = 300 }) +t:done() diff --git a/tools/fixtures/_build_ref.py b/tools/fixtures/_build_ref.py new file mode 100644 index 0000000..4286449 --- /dev/null +++ b/tools/fixtures/_build_ref.py @@ -0,0 +1,106 @@ +# Build engine reference tools for the art / buildmap fixtures: arttool (Jonathon Fowler, Artistic License 2.0) and +# map2stl (Ken Silverman) compiled from the nix eduke32 source (nixpkgs#eduke32.src, never committed) with g++ and a +# small compat.h stub written here: stdio and a few B* aliases, a NULL-safe Bfclose, and a DO_FREE_AND_NULL that leaks +# (arttool's Bstring copy constructor frees an uninitialised pointer). Binaries are cached in tests/gen/.buildtools/. +import os, subprocess + +STUB = r""" +#include +#include +#include +#include +#include +#include +#include +#include +#define Bassert assert +#define Bfclose(f) ((f) ? fclose(f) : 0) +#define Bfileno fileno +#define Bfopen fopen +#define Bfprintf fprintf +#define Bfputc fputc +#define Bfread fread +#define Bfseek fseek +#define Bfstat fstat +#define Bftell ftell +#define Bfwrite fwrite +#define Bmalloc malloc +#define Bprintf printf +#define Brealloc realloc +#define Brewind rewind +#define Bstat stat +#define Bstrcat strcat +#define Bstrcmp strcmp +#define Bstrdup strdup +#define Bstrlen strlen +#define BFILE FILE +#define DO_FREE_AND_NULL(x) do { (x) = NULL; } while (0) +#define EDUKE32_PREDICT_FALSE(x) (x) +#define ATTRIBUTE(x) +""" + + +def tools(ctx): + """{"arttool": path, "map2stl": path}""" + out = os.path.join(ctx.gen, ".buildtools") + paths = {n: os.path.join(out, n) for n in ("arttool", "map2stl")} + if all(os.path.exists(p) for p in paths.values()): + return paths + os.makedirs(out, exist_ok=True) + src = subprocess.run(["nix", "build", "--no-link", "--print-out-paths", "nixpkgs#eduke32.src"], capture_output=True, + check=True).stdout.decode().strip().split("\n")[-1] + stub = os.path.join(out, "stub") + os.makedirs(stub, exist_ok=True) + with open(os.path.join(stub, "compat.h"), "w") as f: + f.write(STUB) + for name, path in paths.items(): + ctx.nix("gcc", ["g++", "-O1", "-w", "-funsigned-char", "-I" + stub, os.path.join(src, "source/tools/src/%s.cpp" % name), + "-o", path]) + return paths + + +def pcx_write(w, h, idx, pal): + """8-bit RLE PCX (version 5) of row-major indices with a 256 x RGB palette, as arttool reads it""" + bpl = w + (w & 1) + hd = bytearray(128) + hd[0:4] = bytes([10, 5, 1, 8]) + hd[8:10] = (w - 1).to_bytes(2, "little") + hd[10:12] = (h - 1).to_bytes(2, "little") + hd[65] = 1 + hd[66:68] = bpl.to_bytes(2, "little") + hd[68] = 1 + out = bytearray(hd) + for y in range(h): + row = list(idx[y * w:(y + 1) * w]) + [0] * (bpl - w) + i = 0 + while i < bpl: + v, n = row[i], 1 + while i + n < bpl and n < 63 and row[i + n] == v: + n += 1 + if n > 1 or v >= 0xC0: + out.append(0xC0 | n) + out.append(v) + i += n + out.append(12) + out += bytes(pal) + return bytes(out) + + +def pcx_read(data): + """(w, h, row-major indices, 768-byte palette) of an 8-bit RLE PCX""" + w = int.from_bytes(data[8:10], "little") - int.from_bytes(data[4:6], "little") + 1 + h = int.from_bytes(data[10:12], "little") - int.from_bytes(data[6:8], "little") + 1 + bpl = int.from_bytes(data[66:68], "little") + raw, p = bytearray(), 128 + while len(raw) < bpl * h: + c = data[p] + p += 1 + if c >= 0xC0: + raw += bytes([data[p]]) * (c & 63) + p += 1 + else: + raw.append(c) + idx = bytearray() + for y in range(h): + idx += raw[y * bpl:y * bpl + w] + return w, h, bytes(idx), data[-768:] diff --git a/tools/fixtures/art.py b/tools/fixtures/art.py new file mode 100644 index 0000000..d2ca33a --- /dev/null +++ b/tools/fixtures/art.py @@ -0,0 +1,117 @@ +# Build ART fixtures (tools/fixtures.py). No Duke 3D data (proprietary): a random PALETTE.DAT (256 distinct 6-bit +# colours, 32 shade tables, a translucency table) and LOOKUP.DAT (palookups 1 and 5, five alternate palettes) are +# made here. References, from the nix eduke32 source (tools/fixtures/_build_ref.py): +# - arttool create / addtile builds TILES000.ART (tiles 10..15, two of them empty) from 8-bit PCX files written +# here, with centre offsets and animation fields; `arttool info` gives the per-tile fields; +# - arttool exporttile writes each tile back as PCX through palette.dat (<< 2 scaling): its RGB is the reference; +# - an independent Python reading of the ART bytes (BUILDINF.TXT layout) gives each tile's column-major indices. +# tests/gen/art.luau { art, palette, lookup, start, last, tiles = { { tile, w, h, idx, rgb, xofs, yofs, animType, +# animFrames, animSpeed, picanm } }, shade = { n, table }, remap = { pal, table } } +import os, shutil, struct, subprocess, tempfile, importlib.util + +_spec = importlib.util.spec_from_file_location("_build_ref", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_build_ref.py")) +B = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(B) + +INPUTS = ["tools/fixtures/_build_ref.py"] + + +def palette_dat(rng): + cols, seen = [], set() + while len(cols) < 256: + c = (rng.randrange(64), rng.randrange(64), rng.randrange(64)) + if c not in seen: + seen.add(c) + cols.append(c) + pal = bytes(v for c in cols for v in c) + shades = rng.randbytes(32 * 256) + return pal + struct.pack(" 0: + idx = bytes(cols[x * h + y] for y in range(h) for x in range(w)) + assert idx == made[t] + run("exporttile", str(t)) + pw, ph, pidx, ppal = B.pcx_read(open(os.path.join(tmp, "tile%04d.pcx" % t), "rb").read()) + assert (pw, ph, pidx) == (w, h, idx) + e["idx"] = idx + e["rgb"] = bytes(ppal[v * 3 + k] for v in pidx for k in range(3)) + tiles.append(e) + finally: + shutil.rmtree(tmp) + ctx.emit("art", { + "art": art, "palette": pal_dat, "lookup": lookup, "start": first, "last": last, "tiles": tiles, + "shade": {"n": 7, "table": pal_dat[770 + 7 * 256:770 + 8 * 256]}, + "remap": {"pal": 5, "table": lookup[1 + 257 + 1:1 + 257 + 257]}, + })