diff --git a/README.md b/README.md index 143cb55..4da9347 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list ## Formats -180 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) +186 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 | @@ -61,11 +61,13 @@ adds each format's capabilities. | Images | ilbm | .iff .ilbm .lbm .pbm | yes | yes | | Images | jpeg | .jpg .jpeg .jpe .jfif | yes | yes | | Images | ktx | .ktx2 .ktx | yes | yes | +| Images | lmp | .lmp | yes | yes | | Images | pcx | .pcx .pcc .dcx | yes | yes | | Images | png | .png .apng | yes | yes | | Images | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes | | Images | qoi | .qoi | yes | yes | | Images | sgi | .sgi .rgb .rgba .bw .int .inta | yes | yes | +| Images | spr | .spr | yes | yes | | Images | sunras | .ras .sun .rs .im1 .im8 .im24 .im32 | yes | yes | | Images | tga | .tga .icb .vda .vst .tpic | yes | yes | | Images | tiff | .tif .tiff | yes | yes | @@ -118,6 +120,7 @@ adds each format's capabilities. | 3D models | iqm | .iqm | yes | yes | | 3D models | ldraw | .ldr .mpd .dat | yes | - | | 3D models | lwo | .lwo .lxo | yes | - | +| 3D models | map | .map | yes | yes | | 3D models | mca | .mca .mcr | yes | - | | 3D models | md2 | .md2 | yes | - | | 3D models | md3 | .md3 | yes | - | @@ -178,6 +181,7 @@ adds each format's capabilities. | Archives | uu | .uu .uue .xxe .b64 | yes | yes | | Archives | vpk | .vpk | yes | yes | | Archives | wad | .wad | yes | yes | +| Archives | wad2 | .wad | yes | yes | | Archives | xz | .xz .txz .lzma | yes | - | | Archives | yenc | .yenc .ync | yes | yes | | Archives | z | .z .taz .tz | yes | yes | @@ -191,6 +195,8 @@ adds each format's capabilities. | Data | msgpack | .msgpack .mpk | yes | yes | | Data | nbt | .nbt .dat .mcstructure .dat_old | yes | yes | | Data | plist | .plist | yes | yes | +| Data | q3shader | .shader | yes | yes | +| Data | q3skin | .skin | yes | yes | | Data | snbt | .snbt | yes | yes | | Data | toml | .toml | yes | yes | | Data | tres | .tres | yes | yes | @@ -243,8 +249,8 @@ Shared by the formats, not loadable on their own (`src/Rosetta/codecs//` | compress | Brotli, Bzip2, Deflate, Explode, Lz4, Lzh, Lzma, Lzw, Lzx, PackBits, Quantum, UnixCompress, Xxh32, Zstd | | entropy | Huffman, RangeCoder | | font | Bitmap, Cff, GlyphNames, TrueType | -| image | Bcn, Blend, Dct, Etc, Half, Jpeg, Pixels, Quantize, Raster, Texel, Texture, Vp8, Vp8L, Yuv | -| model | Draco, Mat4, MeshFlatten, Minecraft, Polygon, Rbx, Rig, Sampler, Vrml | +| image | Bcn, Blend, Dct, Etc, Half, Jpeg, Miptex, Pixels, Quantize, Raster, Texel, Texture, Vp8, Vp8L, Yuv | +| model | Brush, Draco, Mat4, MeshFlatten, Minecraft, Patch, Polygon, Rbx, Rig, Sampler, Vrml | | text | GodotVariant, Json, Nbt, Text, Url, Xml | | video | Dsp, H263, H264, Legacy, Mpeg1, Mpeg2, Theora, Video | | containers | Archive, AudioWrap, Avi, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip | diff --git a/build/Rosetta.luau b/build/Rosetta.luau index 17f6ee9..138993c 100644 --- a/build/Rosetta.luau +++ b/build/Rosetta.luau @@ -1028,6 +1028,18 @@ local list: { Entry } = { return __include("image/ktx") end, }, + { + name = "lmp", + category = "image", + path = "image/lmp", + extensions = { "lmp" }, + mime = { "image/x-quake-lmp" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 }, variants = { "qpic", "palette", "colormap" } }, + load = function() + return __include("image/lmp") + end, + }, { name = "pcx", category = "image", @@ -1088,6 +1100,18 @@ local list: { Entry } = { return __include("image/sgi") end, }, + { + name = "spr", + category = "image", + path = "image/spr", + extensions = { "spr" }, + mime = { "image/x-quake-sprite" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, alpha = true, animation = true, variants = { "quake", "halflife", "spr32" } }, + load = function() + return __include("image/spr") + end, + }, { name = "sunras", category = "image", @@ -1622,8 +1646,8 @@ local list: { Entry } = { path = "model/bsp", extensions = { "bsp" }, mime = { "model/x-bsp" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, - caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" }, + caps = { decode = true, encode = false, variants = { "quake", "bsp2", "2psb", "halflife", "quake2", "quake3" }, lightmaps = true, collision = true, visibility = true }, load = function() return __include("model/bsp") end, @@ -1700,6 +1724,18 @@ local list: { Entry } = { return __include("model/lwo") end, }, + { + name = "map", + category = "model", + path = "model/map", + extensions = { "map" }, + mime = { "text/x-quake-map" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" }, + caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true }, + load = function() + return __include("model/map") + end, + }, { name = "mca", category = "model", @@ -2420,6 +2456,18 @@ local list: { Entry } = { return __include("archive/wad") end, }, + { + name = "wad2", + category = "archive", + path = "archive/wad2", + extensions = { "wad" }, + mime = { "application/x-quake-wad" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, images = true, variants = { "wad2", "wad3" } }, + load = function() + return __include("archive/wad2") + end, + }, { name = "xz", category = "archive", @@ -2576,6 +2624,30 @@ local list: { Entry } = { return __include("data/plist") end, }, + { + name = "q3shader", + category = "data", + path = "data/q3shader", + extensions = { "shader" }, + mime = { "text/x-quake3-shader" }, + deps = { "core/Err", "core/Bytes" }, + caps = { decode = true, encode = true }, + load = function() + return __include("data/q3shader") + end, + }, + { + name = "q3skin", + category = "data", + path = "data/q3skin", + extensions = { "skin" }, + mime = { "text/x-quake3-skin" }, + deps = { "core/Err", "core/Bytes" }, + caps = { decode = true, encode = true }, + load = function() + return __include("data/q3skin") + end, + }, { name = "snbt", category = "data", @@ -11807,6 +11879,288 @@ end return Picture end +__FILES["archive/wad2"] = function() + +-- archive/wad2: Quake WAD2 and Half-Life WAD3 texture / graphics WADs (wad.h of the Quake source, the GoldSrc WAD3 +-- layout; no code taken), read and write. Lumps by name (repeats "~"); Wad2.image decodes miptex, qpic, +-- conchars, palette and GoldSrc font lumps through codecs/image/Miptex (Quake 1 needs a palette: the WAD's own +-- "palette" lump, opts.palette or gfx/palette.lmp through files / resolve; else grey). Not supported: compressed lumps. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Archive = __include("containers/Archive") +local Pixels = __include("codecs/image/Pixels") +local Miptex = __include("codecs/image/Miptex") + +-- ------------------------------------------------------------------------------------------------ contract +local Wad2 = { + name = "wad2", + category = "archive", + extensions = { "wad" }, + mime = { "application/x-quake-wad" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, images = true, variants = { "wad2", "wad3" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { maxEntries: number? } -- default 1e6 +type EncodeOptions = { variant: ("wad2" | "wad3")? } -- default: the source's, else wad3 when a lump is type 0x43 +type ImageOptions = { + palette: (buffer | string)?, -- 768 bytes (Quake 1) + mip: number?, -- miptex level 0..3, default 0 + keyed: boolean?, -- index 255 transparent; default: qpics, conchars and '{' textures + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, +} +type AddOptions = { + kind: ("miptex" | "qpic")?, -- default "miptex" + palette: (buffer | string)?, -- 768 bytes; required for WAD2 lumps, made by median cut for WAD3 without it +} + +-- ------------------------------------------------------------------------------------------------ constants +local T = Miptex.TYPES + +-- ------------------------------------------------------------------------------------------------ sniff +function Wad2.sniff(r: Bytes.Reader): number + if r:remaining() < 12 then + return 0 + end + local m = r:peek(4) + return if m == "WAD2" or m == "WAD3" then 0.9 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Wad2.encode(archive, opts) +end + +function Wad2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local size = r.limit - r.base + local lumps, msg, magic = Miptex.wad(r.buf, r.base, size, opts and opts.maxEntries) + if not lumps then + return nil, Err.from(msg, 0) + end + local a = Archive.new("wad2", encode) + local seen: { [string]: number } = {} + for _, l in lumps do + if l.compression ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "compressed lump " .. l.name) + end + local entry = l.name + local k = seen[string.lower(entry)] + if k then + seen[string.lower(entry)] = k + 1 + entry = entry .. "~" .. (k + 1) + else + seen[string.lower(entry)] = 1 + end + Archive.put(a, { name = entry, size = l.disksize, dir = false, method = "store", type = l.type, lump = l.name, load = Archive.slice(r.buf, r.base + l.offset, l.disksize) }) + end + a.meta.source = { format = "wad2", variant = string.lower(magic :: string), lumps = #lumps } + a.meta.wad2 = { buf = r.buf, base = r.base, lumps = lumps, goldsrc = magic == "WAD3" } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function guessType(name: string, data: buffer, goldsrc: boolean): number + local n = buffer.len(data) + if string.lower(name) == "palette" and n == 768 then + return T.palette + end + if n >= 40 then + local w, h = buffer.readu32(data, 16), buffer.readu32(data, 20) + if w > 0 and h > 0 and w < 65536 and h < 65536 and buffer.readu32(data, 24) == 40 then + return if goldsrc then 0x43 else T.miptex + end + end + if n >= 8 then + local w, h = buffer.readu32(data, 0), buffer.readu32(data, 4) + if w > 0 and h > 0 and 8 + w * h <= n then + return T.qpic + end + end + return T.miptex +end + +function Wad2.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 variant = opts and opts.variant or (if type(src) == "table" and src.format == "wad2" then src.variant else nil) + if not variant then + variant = "wad2" + for _, it in items do + if (it.entry :: any).type == 0x43 then + variant = "wad3" + end + end + end + if variant ~= "wad2" and variant ~= "wad3" then + return nil, Err.new(Err.ARG, "variant must be wad2 or wad3") + end + local list: { { name: string, data: buffer, type: number } } = {} + for _, it in items do + if not it.entry.dir then + local e: any = it.entry + local name = e.lump or string.gsub(string.match(e.name, "([^/\\]*)$") or e.name, "~%d+$", "") + if #name == 0 or #name > 15 then + return nil, Err.new(Err.ARG, "lump name must be 1..15 bytes: " .. e.name) + end + local typ = if type(e.type) == "number" then e.type else guessType(name, it.data, variant == "wad3") + table.insert(list, { name = name, data = it.data, type = typ }) + end + end + local w = Bytes.writer() + w:string(if variant == "wad3" then "WAD3" else "WAD2") + w:u32le(#list) + w:u32le(0) + local offs: { number } = {} + for i, l in list do + offs[i] = w:tell() + w:bytes(l.data) + w:fill(0, (4 - buffer.len(l.data) % 4) % 4) + end + local dir = w:tell() + for i, l in list do + w:u32le(offs[i]) + w:u32le(buffer.len(l.data)) + w:u32le(buffer.len(l.data)) + w:u8(l.type) + w:u8(0) + w:u16le(0) + w:string(l.name) + w:fill(0, 16 - #l.name) + end + w:setU32le(8, dir) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +local function info(a: any): any + return type(a) == "table" and type(a.meta) == "table" and a.meta.wad2 or nil +end + +function Wad2.new(variant: ("wad2" | "wad3")?): any + local a = Archive.new("wad2", encode) + a.meta.source = { format = "wad2", variant = variant or "wad2" } + return a +end + +function Wad2.lumps(a: any): { Miptex.Lump }? + local w = info(a) + return w and w.lumps +end + +-- the WAD's own "palette" lump (gfx.wad) as a 1024-byte rgba8 palette +function Wad2.palette(a: any): buffer? + local w = info(a) + local l = w and Miptex.find(w.lumps, "palette") + if l and l.disksize >= 768 then + return Pixels.palette(w.buf, w.base + l.offset, 256) + end + return nil +end + +function Wad2.image(a: any, name: string, opts: ImageOptions?): (Types.Image?, Err.Err?) + local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD2 / WAD3 archive") + end + local l = Miptex.find(w.lumps, tostring(name)) + if not l then + return nil, Err.new(Err.ARG, "no lump named " .. tostring(name)) + end + local b, at, size = w.buf, w.base + l.offset, l.disksize + local pal: buffer? = nil + if not w.goldsrc then + local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else nil + if raw and buffer.len(raw) >= 768 then + pal = Pixels.palette(raw, 0, 256) + else + pal = Wad2.palette(a) + if not pal then + local lmp = Input.sibling(opts, "gfx/palette.lmp") + pal = if lmp and buffer.len(lmp) >= 768 then Pixels.palette(lmp, 0, 256) else nil + end + end + end + local keyed: boolean? = if opts then opts.keyed else nil + local img: Types.Image?, msg: string? + local kind: string + if l.type == T.palette and size >= 768 then + kind = "palette" + local out = Types.Image.new(16, 16) + buffer.copy(out.pixels, 0, Pixels.palette(b, at, 256), 0, 1024) + img = out + elseif string.lower(l.name) == "conchars" and size == 128 * 128 then + -- gfx.wad's console font: raw 128 x 128 pixels, no header, index 0 transparent + kind = "conchars" + local out = Types.Image.new(128, 128) + Pixels.indexed(b, at, 128, 8, out.pixels, 128, 128, true, Pixels.keyed(pal or Pixels.grey(), if keyed == false then -1 else 0)) + img = out + elseif l.type == T.qpic then + kind = "qpic" + img, msg = Miptex.qpic(b, at, size, { palette = pal, goldsrc = w.goldsrc, keyed = keyed } :: any) + elseif l.type == T.font and w.goldsrc and size >= 16 + 1024 then + -- GoldSrc qfont_t: width (256), height, rowcount, rowheight, charinfo[256] (u16 offset, u16 width), pixels, palette + kind = "font" + local fw, fh = buffer.readu32(b, at), buffer.readu32(b, at + 4) + local p = 16 + 1024 + fw * fh + if fw == 0 or fh == 0 or fw * fh > 2 ^ 24 or p + 2 > size then + return nil, Err.new(Err.CORRUPT, "bad font lump " .. l.name, l.offset) + end + local n = buffer.readu16(b, at + p) + local fpal = if n > 0 and n <= 256 and p + 2 + n * 3 <= size then Pixels.palette(b, at + p + 2, n) else Pixels.grey() + local out = Types.Image.new(fw, fh) + Pixels.indexed(b, at + 16 + 1024, fw, 8, out.pixels, fw, fh, true, if keyed == false then fpal else Pixels.keyed(fpal, 255)) + local glyphs = {} + for c = 0, 255 do + glyphs[c + 1] = { offset = buffer.readu16(b, at + 16 + c * 4), width = buffer.readu16(b, at + 18 + c * 4) } + end + out.meta.font = { rows = buffer.readu32(b, at + 8), rowHeight = buffer.readu32(b, at + 12), glyphs = glyphs } + img = out + else + kind = "miptex" + img, msg = Miptex.decode(b, at, size, { palette = pal, goldsrc = w.goldsrc, mip = if opts then opts.mip else nil, keyed = keyed } :: any) + end + if not img then + return nil, Err.from(msg, l.offset) + end + img.meta.source = { format = "wad2", kind = kind, lump = l.name, type = l.type, palette = w.goldsrc or pal ~= nil } + return img, nil +end + +-- adds an rgba8 image as a miptex (sizes multiples of 16) or qpic lump; WAD3 lumps carry their own palette +function Wad2.addImage(a: any, name: string, img: Types.Image, opts: AddOptions?): (boolean, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" then + return false, Err.new(Err.ARG, "expected an rgba8 Image") + end + local src = type(a) == "table" and type(a.meta) == "table" and a.meta.source + local goldsrc = type(src) == "table" and src.variant == "wad3" + local raw = opts and opts.palette and Bytes.toBuffer(opts.palette) + local pal = if raw and buffer.len(raw) >= 768 then Pixels.palette(raw, 0, 256) else nil + local kind = opts and opts.kind or "miptex" + local data, msg + if kind == "qpic" then + data, msg = Miptex.encodeQpic(img, pal, goldsrc) + else + data, msg = Miptex.encode(img, name, pal, goldsrc) + end + if not data then + return false, Err.new(Err.ARG, msg or "cannot encode") + end + Archive.put(a, { name = name, size = buffer.len(data), dir = false, method = "store", lump = name, data = data, + type = if kind == "qpic" then T.qpic elseif goldsrc then 0x43 else T.miptex }) + return true, nil +end + +return Wad2 +end __FILES["archive/xz"] = function() -- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") as single-stream archives (codecs/compress/Lzma). @@ -69892,12 +70246,313 @@ end return Yuv end +__FILES["codecs/image/Miptex"] = function() + +-- codecs/image/Miptex: Quake / GoldSrc mip textures and the WAD2 / WAD3 lump directory, read and write. +-- miptex_t of bspfile.h: name[16], width, height, offsets[4], four 8-bit mip levels; GoldSrc adds u16 count + count * 3 +-- palette bytes after mip 3. wad.h: "WAD2" / "WAD3", numlumps, infotableofs; 32-byte lumpinfo_t. No code taken. +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") +local Quantize = __include("codecs/image/Quantize") + +local Miptex = {} + +local readu8, readu32, readi32 = buffer.readu8, buffer.readu32, buffer.readi32 + +type Header = { name: string, width: number, height: number, offsets: { number } } +type Lump = { name: string, offset: number, disksize: number, size: number, type: number, compression: number } +type DecodeOptions = { + palette: buffer?, -- 1024-byte rgba8 palette (Pixels.palette) when the texture has none of its own + goldsrc: boolean?, -- read the palette stored after mip 3 + mip: number?, -- 0..3, default 0 + keyed: boolean?, -- index 255 transparent; default: names starting with '{' + maxPixels: number?, -- default 2^24 +} + +-- lumpinfo_t types (wad.h TYP_*; WAD3: 0x43 is a miptex with its palette, 0x46 a font) +Miptex.TYPES = table.freeze({ palette = 0x40, qtex = 0x41, qpic = 0x42, sound = 0x43, miptex = 0x44, font = 0x46 }) + +local function cstr(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +function Miptex.header(b: buffer, at: number, size: number): (Header?, string?) + if at < 0 or size < 40 or at + 40 > buffer.len(b) then + return nil, "truncated miptex header" + end + local w, h = readu32(b, at + 16), readu32(b, at + 20) + local offs = { readu32(b, at + 24), readu32(b, at + 28), readu32(b, at + 32), readu32(b, at + 36) } + return { name = cstr(b, at, 16), width = w, height = h, offsets = offs }, nil +end + +-- the GoldSrc palette after mip 3, as a 1024-byte rgba8 palette, or nil when it is missing / out of range +function Miptex.ownPalette(b: buffer, at: number, size: number, hd: Header): buffer? + local w, h = hd.width, hd.height + local p = hd.offsets[4] + (w // 8) * (h // 8) + if hd.offsets[4] == 0 or p + 2 > size then + return nil + end + local n = buffer.readu16(b, at + p) + if n == 0 or n > 256 or p + 2 + n * 3 > size then + return nil + end + return Pixels.palette(b, at + p + 2, n) +end + +-- decodes one mip level to rgba8; without pixels (offsets 0: the texture lives in a WAD) returns nil, "external" +function Miptex.decode(b: buffer, at: number, size: number, opts: DecodeOptions?): (Types.Image?, string?) + local hd, err = Miptex.header(b, at, size) + if not hd then + return nil, err + end + local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, 3) + local w, h = hd.width // (2 ^ mip), hd.height // (2 ^ mip) + if hd.width == 0 or hd.height == 0 or w == 0 or h == 0 then + return nil, "empty miptex" + end + if hd.width * hd.height > (opts and opts.maxPixels or 2 ^ 24) then + return nil, "limit: miptex " .. hd.width .. " x " .. hd.height + end + local off = hd.offsets[mip + 1] + if off == 0 then + return nil, "external" + end + if off + w * h > size or at + off + w * h > buffer.len(b) then + return nil, "truncated miptex pixels" + end + local own = if opts and opts.goldsrc then Miptex.ownPalette(b, at, size, hd) else nil + local pal = own or (opts and opts.palette) or Pixels.grey() + local keyed = if opts and opts.keyed ~= nil then opts.keyed else string.sub(hd.name, 1, 1) == "{" + if keyed then + pal = Pixels.keyed(pal, 255) + end + local img = Types.Image.new(w, h) + Pixels.indexed(b, at + off, w, 8, img.pixels, w, h, true, pal) + img.meta.source = { format = "miptex", name = hd.name, mip = mip, palette = own ~= nil or (opts ~= nil and opts.palette ~= nil), keyed = keyed or nil } + return img, nil +end + +local function halve(px: buffer, w: number, h: number): (buffer, number, number) + local w2, h2 = math.max(1, w // 2), math.max(1, h // 2) + local out = buffer.create(w2 * h2 * 4) + for y = 0, h2 - 1 do + for x = 0, w2 - 1 do + for c = 0, 3 do + local s = 0 + for dy = 0, 1 do + for dx = 0, 1 do + local sx, sy = math.min(x * 2 + dx, w - 1), math.min(y * 2 + dy, h - 1) + s += readu8(px, (sy * w + sx) * 4 + c) + end + end + buffer.writeu8(out, (y * w2 + x) * 4 + c, (s + 2) // 4) + end + end + end + return out, w2, h2 +end + +-- an rgba8 image -> a miptex_t with four mip levels (box filtered, mapped to the nearest palette entry); goldsrc +-- appends the palette. palette: 1024-byte rgba8; without it (GoldSrc only) a 256-colour median-cut palette is made. +function Miptex.encode(img: Types.Image, name: string, palette: buffer?, goldsrc: boolean?): (buffer?, string?) + local w, h = img.width, img.height + if w <= 0 or h <= 0 or w % 16 ~= 0 or h % 16 ~= 0 then + return nil, "miptex sizes must be multiples of 16" + end + if #name > 15 then + return nil, "miptex name over 15 bytes" + end + if not palette and not goldsrc then + return nil, "a Quake miptex needs a palette" + end + local keyed = string.sub(name, 1, 1) == "{" + local _, colors = Miptex.indices(img, palette, keyed) + if keyed and not palette then + colors[256] = { 0, 0, 255, 255 } -- GoldSrc '{' textures: index 255 is the (blue) key colour + end + local pal1024 = palette or buffer.create(1024) + if not palette then + for i, c in colors do + buffer.writeu32(pal1024, (i - 1) * 4, 0xFF000000 + c[3] * 65536 + c[2] * 256 + c[1]) + end + end + local levels: { buffer } = {} + local px, lw, lh = img.pixels, w, h + for m = 0, 3 do + if m > 0 then + px, lw, lh = halve(px, lw, lh) + end + local lvl = { kind = "image", width = lw, height = lh, format = "rgba8", pixels = px, loops = 0, meta = {} } :: any + levels[m + 1] = (Miptex.indices(lvl, pal1024, keyed)) + end + local total = 40 + for _, l in levels do + total += buffer.len(l) + end + local palAt = total + if goldsrc then + total += 2 + 768 + 2 + end + local out = buffer.create(total) + buffer.writestring(out, 0, name) + buffer.writeu32(out, 16, w) + buffer.writeu32(out, 20, h) + local o = 40 + for m, l in levels do + buffer.writeu32(out, 24 + (m - 1) * 4, o) + buffer.copy(out, o, l) + o += buffer.len(l) + end + if goldsrc then + buffer.writeu16(out, palAt, 256) + for i = 0, 255 do + local c = colors[i + 1] or { 0, 0, 0 } + buffer.writeu8(out, palAt + 2 + i * 3, c[1]) + buffer.writeu8(out, palAt + 3 + i * 3, c[2]) + buffer.writeu8(out, palAt + 4 + i * 3, c[3]) + end + end + return out, nil +end + +-- the lump directory of a WAD2 / WAD3 file (offsets relative to base), or nil, message +function Miptex.wad(b: buffer, base: number, size: number, maxLumps: number?): ({ Lump }?, string?, string?) + if size < 12 or base + 12 > buffer.len(b) then + return nil, "truncated header", nil + end + local magic = buffer.readstring(b, base, 4) + if magic ~= "WAD2" and magic ~= "WAD3" then + return nil, "bad magic", nil + end + local n, dir = readi32(b, base + 4), readi32(b, base + 8) + if n < 0 or dir < 0 then + return nil, "negative directory field", nil + end + if n > (maxLumps or 1e6) then + return nil, "limit: too many lumps: " .. n, nil + end + if dir + n * 32 > size then + return nil, "truncated directory past the end", nil + end + local out: { Lump } = {} + for i = 0, n - 1 do + local o = base + dir + i * 32 + local at, disk, full = readi32(b, o), readi32(b, o + 4), readi32(b, o + 8) + if at < 0 or disk < 0 or at + disk > size then + return nil, "truncated lump past the end", nil + end + out[i + 1] = { name = cstr(b, o + 16, 16), offset = at, disksize = disk, size = full, type = readu8(b, o + 12), compression = readu8(b, o + 13) } + end + return out, nil, magic +end + +-- the lump named name (case-insensitive, the last one wins as in W_GetLumpinfo) +function Miptex.find(lumps: { Lump }, name: string): Lump? + local want = string.lower(name) + local best: Lump? = nil + for _, l in lumps do + if string.lower(l.name) == want then + best = l + end + end + return best +end + +-- qpic (Quake .lmp / WAD2 type 0x42: u32 width, height, 8-bit pixels; GoldSrc adds u16 count + count * 3 palette bytes) +-- -> rgba8. keyed: index 255 transparent (Quake's Draw_TransPic), default true +function Miptex.qpic(b: buffer, at: number, size: number, opts: DecodeOptions?): (Types.Image?, string?) + if size < 8 or at < 0 or at + 8 > buffer.len(b) then + return nil, "truncated qpic header" + end + local w, h = readu32(b, at), readu32(b, at + 4) + if w == 0 or h == 0 then + return nil, "empty qpic" + end + if w * h > (opts and opts.maxPixels or 2 ^ 24) then + return nil, "limit: qpic " .. w .. " x " .. h + end + if 8 + w * h > size or at + 8 + w * h > buffer.len(b) then + return nil, "truncated qpic pixels" + end + local own: buffer? = nil + if opts and opts.goldsrc then + local p = 8 + w * h + if p + 2 <= size then + local n = buffer.readu16(b, at + p) + if n > 0 and n <= 256 and p + 2 + n * 3 <= size then + own = Pixels.palette(b, at + p + 2, n) + end + end + end + local pal = own or (opts and opts.palette) or Pixels.grey() + local keyed = if opts and opts.keyed ~= nil then opts.keyed else true + if keyed then + pal = Pixels.keyed(pal, 255) + end + local img = Types.Image.new(w, h) + Pixels.indexed(b, at + 8, w, 8, img.pixels, w, h, true, pal) + img.meta.source = { format = "qpic", palette = own ~= nil or (opts ~= nil and opts.palette ~= nil), keyed = keyed or nil } + return img, nil +end + +-- palette indices of an rgba8 image (nearest entry; alpha < 128 -> 255 when keyed and the image has any) and the +-- palette used +function Miptex.indices(img: Types.Image, palette: buffer?, keyed: boolean): (buffer, { { number } }) + if keyed then + local any = false + for k = 0, img.width * img.height - 1 do + if readu8(img.pixels, k * 4 + 3) < 128 then + any = true + break + end + end + keyed = any + end + local colors = if palette then Pixels.colorList(palette) else Quantize.palette(img.pixels, img.width, img.height, if keyed then 255 else 256) + local idx = Quantize.map(img.pixels, img.width, img.height, colors, { transparentIndex = if keyed and palette then 255 else nil }) + if keyed then + for k = 0, img.width * img.height - 1 do + if readu8(img.pixels, k * 4 + 3) < 128 then + buffer.writeu8(idx, k, 255) + end + end + end + return idx, colors +end + +-- an rgba8 image -> qpic bytes (goldsrc: with its palette, made by median cut when none is given) +function Miptex.encodeQpic(img: Types.Image, palette: buffer?, goldsrc: boolean?, keyed: boolean?): (buffer?, string?) + if not palette and not goldsrc then + return nil, "a Quake qpic needs a palette" + end + local w, h = img.width, img.height + local idx, colors = Miptex.indices(img, palette, keyed ~= false) + local out = buffer.create(8 + w * h + (if goldsrc then 2 + 768 else 0)) + buffer.writeu32(out, 0, w) + buffer.writeu32(out, 4, h) + buffer.copy(out, 8, idx, 0, w * h) + if goldsrc then + local p = 8 + w * h + buffer.writeu16(out, p, 256) + for i = 0, 255 do + local c = colors[i + 1] or { 0, 0, 0 } + buffer.writeu8(out, p + 2 + i * 3, c[1]) + buffer.writeu8(out, p + 3 + i * 3, c[2]) + buffer.writeu8(out, p + 4 + i * 3, c[3]) + end + end + return out, nil +end + +return Miptex +end __FILES["codecs/image/Pixels"] = @native function() --- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB. --- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8. From bmp-luau b86aed6 (same author); the encoder loops are new. +-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB, and palette helpers. +-- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8; palettes: keyed index (Quake 255), grey ramp, Quake colormap light +-- levels. From bmp-luau b86aed6 (same author); the encoder loops and palette helpers are new. local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8 local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift @@ -70154,6 +70809,61 @@ end return list, alpha end +-- a 256-entry rgba8 palette (u32 LE per entry) with entry i = { i, i, i, 255 } +@native function Pixels.grey(): buffer + local pal = buffer.create(1024) + for i = 0, 255 do + writeu32(pal, i * 4, 0xFF000000 + i * 0x10101) + end + return pal +end + +-- a copy of a 1024-byte palette with entry index transparent (alpha 0, colour kept as Pillow does; Quake / GoldSrc: +-- index 255 of sprites, qpics and '{' textures) +@native function Pixels.keyed(pal: buffer, index: number): buffer + local out = buffer.create(1024) + buffer.copy(out, 0, pal, 0, math.min(buffer.len(pal), 1024)) + if index >= 0 and index < 256 then + writeu8(out, index * 4 + 3, 0) + end + return out +end + +-- palette (1024 bytes) -> { { r, g, b, a } } for codecs/image/Quantize +@native function Pixels.colorList(pal: buffer, n: number?): { { number } } + local out: { { number } } = {} + for i = 0, math.clamp(n or 256, 0, buffer.len(pal) // 4) - 1 do + out[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) } + end + return out +end + +-- Quake colormap.lmp: rows of 256 palette indices, row 0 brightest .. 63 darkest (32 = unlit); the palette for one +-- light level, or nil past the end of the map +@native function Pixels.colormap(pal: buffer, cmap: buffer, base: number, row: number): buffer? + local o = base + row * 256 + if row < 0 or base < 0 or o + 256 > buffer.len(cmap) then + return nil + end + local out = buffer.create(1024) + for i = 0, 255 do + writeu32(out, i * 4, readu32(pal, readu8(cmap, o + i) * 4)) + end + return out +end + +-- rgba8 palette (1024 bytes) -> 3 * n bytes R, G, B (the Quake / GoldSrc palette layout) +@native function Pixels.paletteBytes(pal: buffer, n: number?): buffer + local m = math.clamp(n or 256, 0, 256) + local out = buffer.create(m * 3) + for i = 0, m - 1 do + writeu8(out, i * 3, readu8(pal, i * 4)) + writeu8(out, i * 3 + 1, readu8(pal, i * 4 + 1)) + writeu8(out, i * 3 + 2, readu8(pal, i * 4 + 2)) + end + return out +end + return Pixels end __FILES["codecs/image/Quantize"] = @native function() @@ -76720,6 +77430,646 @@ end return Yuv end +__FILES["codecs/model/Brush"] = @native function() + + + +-- codecs/model/Brush: convex plane brushes -> polygons and Scene primitives, with Quake-family texture projection. +-- As qbsp (Quake / ericw-tools; no code taken): a big square on every plane (inside n . p <= d) clipped by the others. +-- Projections: Quake standard (TextureAxisFromPlane + rotate / scale / shift), Valve 220 (explicit U / V axes), Quake +-- III brush primitives (q3map2 ComputeAxisBase + 2 x 3 matrix). Options: merge coplanar faces with one projection +-- (qbsp TryMerge), drop face parts inside / touching other brushes (qbsp CSGFaces; earlier brushes win coplanar ties). +local Types = __include("Types") + +local Brush = {} + +local abs, sqrt, floor, sin, cos, atan2, min, max = math.abs, math.sqrt, math.floor, math.sin, math.cos, math.atan2, math.min, math.max +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Plane = { number } -- nx, ny, nz, d (unit normal pointing out of the brush) +type Face = { + plane: Plane, + texture: string?, + vecs: { { number } }?, -- 2 x 4: s = p . vecs[1].xyz + vecs[1][4] in texels (Quake standard / Valve 220) + bp: { { number } }?, -- 2 x 3 brush-primitive matrix: s = bp[1] . (p . texS, p . texT, 1) in texture widths + [string]: any, +} +type Polygon = { + brush: number, + face: number, + points: { number }, -- x, y, z per corner, counter-clockwise seen from the front + normal: { number }, +} +type Options = { + epsilon: number?, -- plane side tolerance, default 1e-3 + size: number?, -- half size of the starting winding, default 2^17 + merge: boolean?, -- merge coplanar faces with the same texture projection, default false + hull: boolean?, -- drop face parts inside / touching other brushes, default false + maxPolygons: number?, -- default 2^20 +} +type Built = { texture: string, primitive: Types.Primitive } + +-- TextureAxisFromPlane's baseaxis table (normal, s axis, t axis per row): floor, ceiling, west, east, south, north +local BASEAXIS = { + { 0, 0, 1 }, { 1, 0, 0 }, { 0, -1, 0 }, + { 0, 0, -1 }, { 1, 0, 0 }, { 0, -1, 0 }, + { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, + { -1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, + { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, + { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, +} + +@native local function snap(x: number): number + local r = floor(x + 0.5) + return if abs(x - r) < 1e-6 then r else x +end + +-- qbsp PlaneFromPoints: normal = (p1 - p2) x (p3 - p2), the brush lies behind it; nil when the points are colinear +@native function Brush.planeFromPoints(a: { number }, b: { number }, c: { number }): Plane? + local ux, uy, uz = a[1] - b[1], a[2] - b[2], a[3] - b[3] + local vx, vy, vz = c[1] - b[1], c[2] - b[2], c[3] - b[3] + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l < 1e-12 then + return nil + end + nx, ny, nz = nx / l, ny / l, nz / l + return { nx, ny, nz, b[1] * nx + b[2] * ny + b[3] * nz } +end + +-- the base axis row (0..5) of TextureAxisFromPlane: the first with the largest dot product (strictly greater) +@native function Brush.baseAxis(n: { number }): number + local best, axis = 0, 0 + for i = 0, 5 do + local a = BASEAXIS[i * 3 + 1] + local d = n[1] * a[1] + n[2] * a[2] + n[3] * a[3] + if d > best then + best, axis = d, i + end + end + return axis +end + +-- Quake standard texture vectors (texels): offsets, rotation (degrees), scales (0 = 1) +@native function Brush.quakeVecs(n: { number }, xoff: number, yoff: number, rot: number, xscale: number, yscale: number): { { number } } + local axis = Brush.baseAxis(n) + local s0, t0 = BASEAXIS[axis * 3 + 2], BASEAXIS[axis * 3 + 3] + local vecs = { { s0[1], s0[2], s0[3] }, { t0[1], t0[2], t0[3] } } + local sinv, cosv + if rot == 0 then + sinv, cosv = 0, 1 + elseif rot == 90 then + sinv, cosv = 1, 0 + elseif rot == 180 then + sinv, cosv = 0, -1 + elseif rot == 270 then + sinv, cosv = -1, 0 + else + local ang = rot / 180 * math.pi + sinv, cosv = sin(ang), cos(ang) + end + local sv = if vecs[1][1] ~= 0 then 1 elseif vecs[1][2] ~= 0 then 2 else 3 + local tv = if vecs[2][1] ~= 0 then 1 elseif vecs[2][2] ~= 0 then 2 else 3 + for i = 1, 2 do + local v = vecs[i] + local ns = cosv * v[sv] - sinv * v[tv] + local nt = sinv * v[sv] + cosv * v[tv] + v[sv], v[tv] = ns, nt + end + local sc = { if xscale == 0 then 1 else xscale, if yscale == 0 then 1 else yscale } + for i = 1, 2 do + local v = vecs[i] + v[1], v[2], v[3] = v[1] / sc[i], v[2] / sc[i], v[3] / sc[i] + end + vecs[1][4], vecs[2][4] = xoff, yoff + return vecs +end + +-- Valve 220: u / v = axis (x, y, z, offset); the rotation is already in the axes +@native function Brush.valveVecs(u: { number }, v: { number }, xscale: number, yscale: number): { { number } } + local su, sv = if xscale == 0 then 1 else xscale, if yscale == 0 then 1 else yscale + return { { u[1] / su, u[2] / su, u[3] / su, u[4] }, { v[1] / sv, v[2] / sv, v[3] / sv, v[4] } } +end + +-- q3map2 ComputeAxisBase: the texture plane axes of a brush-primitive face +@native function Brush.axisBase(normal: { number }): ({ number }, { number }) + local nx, ny, nz = normal[1], normal[2], normal[3] + nx = if abs(nx) < 1e-6 then 0 else nx + ny = if abs(ny) < 1e-6 then 0 else ny + nz = if abs(nz) < 1e-6 then 0 else nz + local rotY = -atan2(nz, sqrt(ny * ny + nx * nx)) + local rotZ = atan2(ny, nx) + return { -sin(rotZ), cos(rotZ), 0 }, { -sin(rotY) * cos(rotZ), -sin(rotY) * sin(rotZ), -cos(rotY) } +end + +-- brush primitives -> texel vectors for a w x h texture (ericw-tools SetTexinfo_BrushPrimitives) +@native function Brush.bpVecs(normal: { number }, m: { { number } }, w: number, h: number): { { number } } + local tx, ty = Brush.axisBase(normal) + local out = {} + for i, size in { w, h } do + local r = m[i] + out[i] = { size * (tx[1] * r[1] + ty[1] * r[2]), size * (tx[2] * r[1] + ty[2] * r[2]), size * (tx[3] * r[1] + ty[3] * r[2]), size * r[3] } + end + return out +end + +-- texel vectors -> brush primitives (the inverse of bpVecs for vectors lying in the face plane) +@native function Brush.vecsToBp(normal: { number }, vecs: { { number } }, w: number, h: number): { { number } } + local tx, ty = Brush.axisBase(normal) + local out = {} + for i, size in { w, h } do + local v = vecs[i] + out[i] = { + (v[1] * tx[1] + v[2] * tx[2] + v[3] * tx[3]) / size, + (v[1] * ty[1] + v[2] * ty[2] + v[3] * ty[3]) / size, + v[4] / size, + } + end + return out +end + +-- texture coordinates of a point on a face, in texture widths / heights (glTF uv: t grows down the image) +@native function Brush.uv(face: Face, x: number, y: number, z: number, w: number, h: number): (number, number) + local bp = face.bp + if bp then + local tx, ty = Brush.axisBase(face.plane) + local a = x * tx[1] + y * tx[2] + z * tx[3] + local b = x * ty[1] + y * ty[2] + z * ty[3] + return bp[1][1] * a + bp[1][2] * b + bp[1][3], bp[2][1] * a + bp[2][2] * b + bp[2][3] + end + local v = face.vecs + if v then + local s, t = v[1], v[2] + return (x * s[1] + y * s[2] + z * s[3] + s[4]) / w, (x * t[1] + y * t[2] + z * t[3] + t[4]) / h + end + return 0, 0 +end + +-- qbsp BaseWindingForPlane: a square of half size `size` on the plane, counter-clockwise seen from the front +@native function Brush.baseWinding(p: Plane, size: number): { number } + local nx, ny, nz, d = p[1], p[2], p[3], p[4] + local ax, ay, az = abs(nx), abs(ny), abs(nz) + local ux, uy, uz = 0, 0, 1 + if az >= ax and az >= ay then + ux, uy, uz = 1, 0, 0 + end + local dv = ux * nx + uy * ny + uz * nz + ux, uy, uz = ux - dv * nx, uy - dv * ny, uz - dv * nz + local l = sqrt(ux * ux + uy * uy + uz * uz) + ux, uy, uz = ux / l * size, uy / l * size, uz / l * size + -- right = up x n, so right x up = n: right -> up turns counter-clockwise about n + local rx, ry, rz = (uy * nz - uz * ny), (uz * nx - ux * nz), (ux * ny - uy * nx) + local ox, oy, oz = nx * d, ny * d, nz * d + return { + ox - rx - ux, oy - ry - uy, oz - rz - uz, + ox + rx - ux, oy + ry - uy, oz + rz - uz, + ox + rx + ux, oy + ry + uy, oz + rz + uz, + ox - rx + ux, oy - ry + uy, oz - rz + uz, + } +end + +-- splits a polygon by a plane: the parts in front and behind (nil when empty), and whether it lies on the plane +@native function Brush.split(pts: { number }, p: Plane, eps: number): ({ number }?, { number }?, boolean) + local n = #pts // 3 + local nx, ny, nz, d = p[1], p[2], p[3], p[4] + local dist = table.create(n, 0) :: { number } + local side = table.create(n, 0) :: { number } + local front, back = 0, 0 + for i = 0, n - 1 do + local v = pts[i * 3 + 1] * nx + pts[i * 3 + 2] * ny + pts[i * 3 + 3] * nz - d + dist[i + 1] = v + if v > eps then + side[i + 1] = 1 + front += 1 + elseif v < -eps then + side[i + 1] = -1 + back += 1 + end + end + if front == 0 and back == 0 then + return nil, nil, true + end + if front == 0 then + return nil, pts, false + end + if back == 0 then + return pts, nil, false + end + local f: { number }, b: { number } = {}, {} + for i = 0, n - 1 do + local j = (i + 1) % n + local x, y, z = pts[i * 3 + 1], pts[i * 3 + 2], pts[i * 3 + 3] + local si = side[i + 1] + if si >= 0 then + f[#f + 1], f[#f + 2], f[#f + 3] = x, y, z + end + if si <= 0 then + b[#b + 1], b[#b + 2], b[#b + 3] = x, y, z + end + local sj = side[j + 1] + if si ~= 0 and sj ~= 0 and si ~= sj then + local t = dist[i + 1] / (dist[i + 1] - dist[j + 1]) + local mx, my, mz = x + t * (pts[j * 3 + 1] - x), y + t * (pts[j * 3 + 2] - y), z + t * (pts[j * 3 + 3] - z) + -- exact on axis-aligned planes, as qbsp + if nx == 1 then + mx = d + elseif nx == -1 then + mx = -d + end + if ny == 1 then + my = d + elseif ny == -1 then + my = -d + end + if nz == 1 then + mz = d + elseif nz == -1 then + mz = -d + end + f[#f + 1], f[#f + 2], f[#f + 3] = mx, my, mz + b[#b + 1], b[#b + 2], b[#b + 3] = mx, my, mz + end + end + return (if #f >= 9 then f else nil), (if #b >= 9 then b else nil), false +end + +-- removes repeated and colinear corners; nil when fewer than 3 remain +@native local function clean(pts: { number }, eps: number): { number }? + local out: { number } = {} + local n = #pts // 3 + for i = 0, n - 1 do + local x, y, z = snap(pts[i * 3 + 1]), snap(pts[i * 3 + 2]), snap(pts[i * 3 + 3]) + local m = #out + if m < 3 or abs(out[m - 2] - x) > eps or abs(out[m - 1] - y) > eps or abs(out[m] - z) > eps then + out[m + 1], out[m + 2], out[m + 3] = x, y, z + end + end + while #out >= 6 and abs(out[1] - out[#out - 2]) <= eps and abs(out[2] - out[#out - 1]) <= eps and abs(out[3] - out[#out]) <= eps do + out[#out], out[#out - 1], out[#out - 2] = nil, nil, nil + end + -- colinear corners + local changed = true + while changed and #out >= 9 do + changed = false + local k = #out // 3 + for i = 0, k - 1 do + local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 + local ux, uy, uz = out[b + 1] - out[a + 1], out[b + 2] - out[a + 2], out[b + 3] - out[a + 3] + local vx, vy, vz = out[c + 1] - out[b + 1], out[c + 2] - out[b + 2], out[c + 3] - out[b + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) + if lu * lv == 0 or sqrt(cx * cx + cy * cy + cz * cz) <= 1e-9 * lu * lv then + table.remove(out, b + 3) + table.remove(out, b + 2) + table.remove(out, b + 1) + changed = true + break + end + end + end + return if #out >= 9 then out else nil +end + +@native local function samePlane(a: Plane, b: Plane, eps: number): boolean + return abs(a[1] - b[1]) < 1e-5 and abs(a[2] - b[2]) < 1e-5 and abs(a[3] - b[3]) < 1e-5 and abs(a[4] - b[4]) < eps +end + +@native local function oppositePlane(a: Plane, b: Plane, eps: number): boolean + return abs(a[1] + b[1]) < 1e-5 and abs(a[2] + b[2]) < 1e-5 and abs(a[3] + b[3]) < 1e-5 and abs(a[4] + b[4]) < eps +end + +-- one polygon per plane of a convex brush (nil for planes clipped away or repeating an earlier plane) +@native function Brush.windings(planes: { Plane }, opts: Options?): { { number }? } + local eps = opts and opts.epsilon or 1e-3 + local size = opts and opts.size or 2 ^ 17 + local out: { { number }? } = {} + for i, p in planes do + local w: { number }? = Brush.baseWinding(p, size) + for j, q in planes do + if not w then + break + end + if j ~= i then + if samePlane(p, q, eps) then + if j < i then + w = nil + end + else + local _, back, on = Brush.split(w, q, eps) + w = if on then nil else back + end + end + end + out[i] = if w then clean(w, eps) else nil + end + return out +end + +@native local function bounds(polys: { Polygon }): { number } + local b = { math.huge, math.huge, math.huge, -math.huge, -math.huge, -math.huge } + for _, p in polys do + local pts = p.points + for k = 0, #pts // 3 - 1 do + for c = 1, 3 do + local v = pts[k * 3 + c] + b[c] = min(b[c], v) + b[c + 3] = max(b[c + 3], v) + end + end + end + return b +end + +-- the parts of pts (on plane `own` of brush a) outside brush b +@native local function outside(pts: { number }, own: Plane, a: number, b: number, planes: { Plane }, eps: number): { { number } } + local kept: { { number } } = {} + local inside: { number }? = pts + for _, q in planes do + if not inside then + break + end + if samePlane(own, q, eps) then + if a < b then + return { pts } + end + elseif not oppositePlane(own, q, eps) then + local front, back = Brush.split(inside, q, eps) + if front then + table.insert(kept, front) + end + inside = back + end + end + return kept +end + +@native local function faceKey(f: Face): string + local parts = { f.texture or "" } + for _, m in { f.vecs, f.bp } do + if m then + for _, row in m do + for _, v in row do + table.insert(parts, string.format("%.6g", v)) + end + end + end + end + return table.concat(parts, " ") +end + +@native local function convex(pts: { number }, n: { number }, eps: number): boolean + local k = #pts // 3 + for i = 0, k - 1 do + local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 + local ux, uy, uz = pts[b + 1] - pts[a + 1], pts[b + 2] - pts[a + 2], pts[b + 3] - pts[a + 3] + local vx, vy, vz = pts[c + 1] - pts[b + 1], pts[c + 2] - pts[b + 2], pts[c + 3] - pts[b + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) + if (cx * n[1] + cy * n[2] + cz * n[3]) < -eps * max(lu, lv, 1) then + return false + end + end + return true +end + +-- qbsp TryMerge: two polygons sharing an edge (in opposite directions) -> their union, when convex +@native local function tryMerge(f1: { number }, f2: { number }, n: { number }, eps: number): { number }? + local n1, n2 = #f1 // 3, #f2 // 3 + for i = 0, n1 - 1 do + local i2 = (i + 1) % n1 + for j = 0, n2 - 1 do + local j2 = (j + 1) % n2 + local match = true + for c = 1, 3 do + if abs(f1[i * 3 + c] - f2[j2 * 3 + c]) > eps or abs(f1[i2 * 3 + c] - f2[j * 3 + c]) > eps then + match = false + break + end + end + if match then + local out: { number } = {} + for k = 0, n1 - 1 do + local s = ((i2 + k) % n1) * 3 + out[#out + 1], out[#out + 2], out[#out + 3] = f1[s + 1], f1[s + 2], f1[s + 3] + end + for k = 2, n2 - 1 do + local s = ((j + k) % n2) * 3 + out[#out + 1], out[#out + 2], out[#out + 3] = f2[s + 1], f2[s + 2], f2[s + 3] + end + local c = clean(out, eps) + if c and convex(c, n, eps) then + return c + end + return nil + end + end + end + return nil +end + +@native local function mergeAll(polys: { Polygon }, faces: { [number]: { Face } }, eps: number): { Polygon } + local groups: { [string]: { Polygon } } = {} + local order: { string } = {} + for _, p in polys do + local f = faces[p.brush][p.face] + local pl = f.plane + local key = string.format("%.5f %.5f %.5f %.3f|", pl[1], pl[2], pl[3], pl[4]) .. faceKey(f) + local g = groups[key] + if not g then + g = {} + groups[key] = g + table.insert(order, key) + end + table.insert(g, p) + end + local out: { Polygon } = {} + for _, key in order do + local g = groups[key] + local changed = true + while changed do + changed = false + for a = 1, #g do + for b = a + 1, #g do + local m = tryMerge(g[a].points, g[b].points, g[a].normal, eps) + if m then + g[a] = { brush = g[a].brush, face = g[a].face, points = m, normal = g[a].normal } + table.remove(g, b) + changed = true + break + end + end + if changed then + break + end + end + end + for _, p in g do + table.insert(out, p) + end + end + return out +end + +-- every brush's faces -> polygons (brushes[i] is a list of faces); nil, message past opts.maxPolygons +@native function Brush.polygons(brushes: { { Face } }, opts: Options?): ({ Polygon }?, string?) + local eps = opts and opts.epsilon or 1e-3 + local limit = opts and opts.maxPolygons or 2 ^ 20 + local per: { { Polygon } } = {} + local planesOf: { { Plane } } = {} + local count = 0 + for bi, faces in brushes do + local planes: { Plane } = {} + for fi, f in faces do + planes[fi] = f.plane + end + planesOf[bi] = planes + local list: { Polygon } = {} + local ws = Brush.windings(planes, opts) + for fi = 1, #faces do + local w = ws[fi] + if w then + table.insert(list, { brush = bi, face = fi, points = w, normal = { planes[fi][1], planes[fi][2], planes[fi][3] } }) + end + end + per[bi] = list + count += #list + if count > limit then + return nil, "limit: too many brush faces" + end + end + local all: { Polygon } = {} + if opts and opts.hull then + local boxes: { { number } } = {} + for bi = 1, #brushes do + boxes[bi] = bounds(per[bi]) + end + for bi = 1, #brushes do + for _, p in per[bi] do + local frags: { { number } } = { p.points } + local own = brushes[bi][p.face].plane + local pb = bounds({ p }) + for bj = 1, #brushes do + if #frags == 0 then + break + end + local ob = boxes[bj] + if bj ~= bi and #per[bj] > 0 and pb[1] <= ob[4] + eps and pb[4] >= ob[1] - eps and pb[2] <= ob[5] + eps + and pb[5] >= ob[2] - eps and pb[3] <= ob[6] + eps and pb[6] >= ob[3] - eps then + local nextFrags: { { number } } = {} + for _, fr in frags do + for _, kept in outside(fr, own, bi, bj, planesOf[bj], eps) do + table.insert(nextFrags, kept) + end + end + frags = nextFrags + if #frags > limit then + return nil, "limit: too many brush fragments" + end + end + end + for _, fr in frags do + local c = clean(fr, eps) + if c then + table.insert(all, { brush = p.brush, face = p.face, points = c, normal = p.normal }) + end + end + end + end + else + for bi = 1, #brushes do + for _, p in per[bi] do + table.insert(all, p) + end + end + end + if opts and opts.merge then + all = mergeAll(all, brushes, eps) + end + return all, nil +end + +-- polygon area (for checks against compilers) +@native function Brush.area(pts: { number }): number + local n = #pts // 3 + local ax, ay, az = 0, 0, 0 + for k = 1, n - 2 do + local ux, uy, uz = pts[k * 3 + 1] - pts[1], pts[k * 3 + 2] - pts[2], pts[k * 3 + 3] - pts[3] + local vx, vy, vz = pts[k * 3 + 4] - pts[1], pts[k * 3 + 5] - pts[2], pts[k * 3 + 6] - pts[3] + ax += uy * vz - uz * vy + ay += uz * vx - ux * vz + az += ux * vy - uy * vx + end + return sqrt(ax * ax + ay * ay + az * az) / 2 +end + +-- polygons -> one indexed triangle primitive per texture, in order of first use. size(name) gives a texture's +-- width, height (texel projections divide by them) +@native function Brush.primitives(polys: { Polygon }, brushes: { { Face } }, size: (name: string) -> (number, number)): { Built } + type Acc = { texture: string, pos: { number }, nrm: { number }, uv: { number }, idx: { number } } + local byTex: { [string]: Acc } = {} + local order: { Acc } = {} + local sizes: { [string]: { number } } = {} + for _, p in polys do + local f = brushes[p.brush][p.face] + local name = f.texture or "" + local acc = byTex[name] + if not acc then + acc = { texture = name, pos = {}, nrm = {}, uv = {}, idx = {} } + byTex[name] = acc + table.insert(order, acc) + end + local sz = sizes[name] + if not sz then + local w, h = size(name) + sz = { math.max(w, 1), math.max(h, 1) } + sizes[name] = sz + end + local a: Acc = acc + local pts = p.points + local n = #pts // 3 + local base = #a.pos // 3 + for k = 0, n - 1 do + local x, y, z = pts[k * 3 + 1], pts[k * 3 + 2], pts[k * 3 + 3] + local pp, nn, uu = a.pos, a.nrm, a.uv + pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z + nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = p.normal[1], p.normal[2], p.normal[3] + local u, v = Brush.uv(f, x, y, z, sz[1], sz[2]) + uu[#uu + 1], uu[#uu + 2] = u, v + end + local ii = a.idx + for k = 1, n - 2 do + ii[#ii + 1], ii[#ii + 2], ii[#ii + 3] = base, base + k, base + k + 1 + end + end + local out: { Built } = {} + for _, a in order do + local nv, ni = #a.pos // 3, #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + local S = Types.Scene + table.insert(out, { + texture = a.texture, + primitive = { + attributes = { POSITION = S.accessor(pb, "f32", 3, nv), NORMAL = S.accessor(nb, "f32", 3, nv), TEXCOORD_0 = S.accessor(ub, "f32", 2, nv) }, + indices = S.accessor(ib, "u32", 1, ni), + mode = "triangles" :: "triangles", + }, + }) + end + return out +end + +return Brush +end __FILES["codecs/model/Draco"] = function() -- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). @@ -82385,6 +83735,130 @@ end return Packed end +__FILES["codecs/model/Patch"] = @native function() + + + +-- codecs/model/Patch: Quake III / Doom 3 Bezier patches (control grids) -> evaluated grids, triangles, normals. +-- A w x h grid (w, h odd, >= 3) is a mesh of 3 x 3 biquadratic sub-patches (Unofficial Quake 3 Map Specs; patchDef2 / +-- patchDef3), evaluated at fixed segments per sub-patch and axis (patchDef3's explicit subdivisions; Quake III's adaptive +-- subdivision is not reproduced). Shared edges are evaluated once. +local Patch = {} + +local sqrt = math.sqrt + +@native function Patch.valid(w: number, h: number, n: number): boolean + return w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n +end + +-- ctrl: w * h points of comps numbers, row-major (row j holds points j * w .. j * w + w - 1); returns the evaluated grid +-- (gw * gh points of comps numbers, row-major) and its size; nil when the grid is not w x h odd or a limit is passed +@native function Patch.grid(ctrl: { number }, w: number, h: number, comps: number, levelU: number, levelV: number, maxPoints: number?): ({ number }?, number, number) + local lu, lv = math.max(1, math.floor(levelU)), math.max(1, math.floor(levelV)) + if not Patch.valid(w, h, #ctrl // comps) or #ctrl ~= w * h * comps then + return nil, 0, 0 + end + local px, py = (w - 1) // 2, (h - 1) // 2 + local gw, gh = px * lu + 1, py * lv + 1 + if gw * gh > (maxPoints or 2 ^ 24) then + return nil, 0, 0 + end + local out = table.create(gw * gh * comps, 0) :: { number } + for gy = 0, gh - 1 do + local sy = math.min(gy // lv, py - 1) + local tv = (gy - sy * lv) / lv + local bv0, bv1, bv2 = (1 - tv) * (1 - tv), 2 * tv * (1 - tv), tv * tv + for gx = 0, gw - 1 do + local sx = math.min(gx // lu, px - 1) + local tu = (gx - sx * lu) / lu + local bu0, bu1, bu2 = (1 - tu) * (1 - tu), 2 * tu * (1 - tu), tu * tu + local o = (gy * gw + gx) * comps + for j = 0, 2 do + local bv = if j == 0 then bv0 elseif j == 1 then bv1 else bv2 + local row = ((sy * 2 + j) * w + sx * 2) * comps + for i = 0, 2 do + local wgt = bv * (if i == 0 then bu0 elseif i == 1 then bu1 else bu2) + local c = row + i * comps + for k = 1, comps do + out[o + k] += ctrl[c + k] * wgt + end + end + end + end + end + return out, gw, gh +end + +-- 0-based triangle indices over a gw x gh grid; Quake's control grids are clockwise-front, these are counter-clockwise +@native function Patch.triangles(gw: number, gh: number): { number } + local out = table.create(math.max(0, (gw - 1) * (gh - 1) * 6)) :: { number } + for gy = 0, gh - 2 do + for gx = 0, gw - 2 do + local a, b = gy * gw + gx, gy * gw + gx + 1 + local d, e = a + gw, b + gw + local n = #out + out[n + 1], out[n + 2], out[n + 3] = a, d, b + out[n + 4], out[n + 5], out[n + 6] = b, d, e + end + end + return out +end + +-- renormalizes the vec3 at component offset at (0-based) of every point +@native function Patch.normalize(pts: { number }, comps: number, at: number) + for o = 0, #pts - comps, comps do + local x, y, z = pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] = x / l, y / l, z / l + end + end +end + +-- unit normals (3 per point) of the evaluated grid from the positions (components 1..3), facing the front of +-- Patch.triangles; points where the surface degenerates take a neighbour's normal +@native function Patch.normals(pts: { number }, comps: number, gw: number, gh: number): { number } + local out = table.create(gw * gh * 3, 0) :: { number } + @native local function at(x: number, y: number, k: number): number + return pts[(y * gw + x) * comps + k] + end + for gy = 0, gh - 1 do + local y0, y1 = math.max(gy - 1, 0), math.min(gy + 1, gh - 1) + for gx = 0, gw - 1 do + local x0, x1 = math.max(gx - 1, 0), math.min(gx + 1, gw - 1) + local ux, uy, uz = at(x1, gy, 1) - at(x0, gy, 1), at(x1, gy, 2) - at(x0, gy, 2), at(x1, gy, 3) - at(x0, gy, 3) + local vx, vy, vz = at(gx, y1, 1) - at(gx, y0, 1), at(gx, y1, 2) - at(gx, y0, 2), at(gx, y1, 3) - at(gx, y0, 3) + local nx, ny, nz = vy * uz - vz * uy, vz * ux - vx * uz, vx * uy - vy * ux + local l = sqrt(nx * nx + ny * ny + nz * nz) + local o = (gy * gw + gx) * 3 + if l > 1e-12 then + out[o + 1], out[o + 2], out[o + 3] = nx / l, ny / l, nz / l + end + end + end + for _ = 1, 2 do + for i = 0, gw * gh - 1 do + local o = i * 3 + if out[o + 1] == 0 and out[o + 2] == 0 and out[o + 3] == 0 then + local x, y = i % gw, i // gw + for _, d in { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 }, { 1, 1 }, { -1, -1 }, { 1, -1 }, { -1, 1 } } do + local nx2, ny2 = x + d[1], y + d[2] + if nx2 >= 0 and nx2 < gw and ny2 >= 0 and ny2 < gh then + local q = (ny2 * gw + nx2) * 3 + if out[q + 1] ~= 0 or out[q + 2] ~= 0 or out[q + 3] ~= 0 then + out[o + 1], out[o + 2], out[o + 3] = out[q + 1], out[q + 2], out[q + 3] + break + end + end + end + end + end + end + return out +end + +return Patch +end __FILES["codecs/model/Polygon"] = function() -- codecs/model/Polygon: 2D polygons with holes to triangles by hole bridging and ear clipping. New code. @@ -120046,6 +121520,341 @@ end return Binary end +__FILES["data/q3shader"] = function() + +-- data/q3shader: Quake III shader scripts (.shader; the Quake III Arena Shader Manual, tr_shader.c tokenizing: no code +-- taken), read and write. A script is a list of shaders { name, directives, stages }; a directive is its tokens +-- ({ "surfaceparm", "nolightmap" }, one line each), a stage is a list of directives. Keywords keep their case. +-- Comments (// and /* */) are dropped. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +-- ------------------------------------------------------------------------------------------------ contract +local Q3Shader = { + name = "q3shader", + category = "data", + extensions = { "shader" }, + mime = { "text/x-quake3-shader" }, + deps = { "core/Err", "core/Bytes" }, + caps = { decode = true, encode = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Directive = { string } +type Shader = { name: string, directives: { Directive }, stages: { { Directive } } } +type EncodeOptions = { indent: string? } -- default "\t" + +-- ------------------------------------------------------------------------------------------------ constants +local KEYWORDS = { "surfaceparm", "map", "clampmap", "animmap", "blendfunc", "rgbgen", "alphagen", "tcgen", "tcmod", + "cull", "deformvertexes", "qer_editorimage", "nopicmip", "nomipmaps", "skyparms", "q3map_", "depthwrite", "alphafunc" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Q3Shader.sniff(r: Bytes.Reader): number + local head = r:peek(math.min(r:remaining(), 2048)) + if #head < 4 or string.find(head, "[%z\1-\8\14-\31]") then + return 0 + end + local s = string.gsub(string.gsub(head, "/%*.-%*/", " "), "//[^\n]*", "") + if not string.match(s, "^%s*[^%s{}\"]+%s*{") then + return 0 + end + local lower = string.lower(s) + for _, k in KEYWORDS do + if string.find(lower, "%f[%w_]" .. k) then + return 0.7 + end + end + return 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the token lines of a script; braces are lines of their own +local function lex(text: string): ({ { string } }?, string?) + local lines: { { string } } = {} + local cur: { string } = {} + local i, n = 1, #text + local function flush() + if #cur > 0 then + table.insert(lines, cur) + cur = {} + end + end + while i <= n do + local c = string.sub(text, i, i) + if c == "\n" then + flush() + i += 1 + elseif string.match(c, "%s") then + i += 1 + elseif string.sub(text, i, i + 1) == "//" then + local e = string.find(text, "\n", i, true) + i = e or n + 1 + elseif string.sub(text, i, i + 1) == "/*" then + local _, e = string.find(text, "*/", i + 2, true) + if not e then + return nil, "unterminated comment" + end + for _ in string.gmatch(string.sub(text, i, e), "\n") do + flush() + end + i = e + 1 + elseif c == "{" or c == "}" then + flush() + table.insert(lines, { c }) + i += 1 + elseif c == '"' then + local e = string.find(text, '"', i + 1, true) + if not e then + return nil, "unterminated string" + end + table.insert(cur, string.sub(text, i + 1, e - 1)) + i = e + 1 + else + local _, e = string.find(text, "^[^%s{}\"]+", i) + local stop = e :: number + local tok = string.sub(text, i, stop) + local cm = string.find(tok, "//", 1, true) + if cm and cm > 1 then + tok = string.sub(tok, 1, cm - 1) + stop = i + cm - 2 + end + table.insert(cur, tok) + i = stop + 1 + end + end + flush() + return lines, nil +end + +function Q3Shader.decode(r: Bytes.Reader): ({ Shader }?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local lines, msg = lex(text) + if not lines then + return nil, Err.new(Err.CORRUPT, msg or "bad script") + end + local out: { Shader } = {} + local k = 1 + while k <= #lines do + local l = lines[k] + if #l ~= 1 or l[1] == "{" or l[1] == "}" then + return nil, Err.new(Err.CORRUPT, "expected a shader name, got '" .. table.concat(l, " ") .. "'") + end + local sh: Shader = { name = l[1], directives = {}, stages = {} } + k += 1 + if not lines[k] or lines[k][1] ~= "{" then + return nil, Err.new(Err.CORRUPT, "expected '{' after " .. sh.name) + end + k += 1 + local stage: { Directive }? = nil + local closed = false + while k <= #lines do + local d = lines[k] + k += 1 + if d[1] == "{" then + if stage then + return nil, Err.new(Err.CORRUPT, "nested stage in " .. sh.name) + end + stage = {} + elseif d[1] == "}" then + if stage then + table.insert(sh.stages, stage) + stage = nil + else + closed = true + break + end + elseif stage then + table.insert(stage, d) + else + table.insert(sh.directives, d) + end + end + if not closed then + return nil, Err.new(Err.TRUNCATED, "shader " .. sh.name .. " not closed") + end + table.insert(out, sh) + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function tokens(d: any): (string?, string?) + if type(d) ~= "table" or #d == 0 then + return nil, "a directive is a list of strings" + end + local parts = {} + for _, t in d do + local s = tostring(t) + if s == "" or string.find(s, "[%s{}]") then + if string.find(s, '"', 1, true) or string.find(s, "\n") then + return nil, "token cannot hold quotes or line breaks: " .. s + end + s = '"' .. s .. '"' + end + table.insert(parts, s) + end + return table.concat(parts, " "), nil +end + +function Q3Shader.encode(list: { Shader }, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(list) ~= "table" then + return nil, Err.new(Err.ARG, "expected a list of shaders") + end + local ind = opts and opts.indent or "\t" + local out: { string } = {} + for _, sh in list do + if type(sh) ~= "table" or type(sh.name) ~= "string" or sh.name == "" or string.find(sh.name, "[%s{}\"]") then + return nil, Err.new(Err.ARG, "a shader needs a name without spaces") + end + table.insert(out, sh.name) + table.insert(out, "{") + for _, d in sh.directives or {} do + local line, e = tokens(d) + if not line then + return nil, Err.new(Err.ARG, e or "bad directive") + end + table.insert(out, ind .. line) + end + for _, st in sh.stages or {} do + table.insert(out, ind .. "{") + for _, d in st do + local line, e = tokens(d) + if not line then + return nil, Err.new(Err.ARG, e or "bad directive") + end + table.insert(out, ind .. ind .. line) + end + table.insert(out, ind .. "}") + end + table.insert(out, "}") + table.insert(out, "") + end + return buffer.fromstring(table.concat(out, "\n")), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- the shader named name (case-insensitive, as the game looks them up) +function Q3Shader.find(list: { Shader }, name: string): Shader? + local want = string.lower(name) + for _, sh in list do + if string.lower(sh.name) == want then + return sh + end + end + return nil +end + +-- the first directive starting with keyword (case-insensitive) in a shader or stage directive list +function Q3Shader.directive(list: { Directive }, keyword: string): Directive? + local want = string.lower(keyword) + for _, d in list do + if string.lower(d[1] or "") == want then + return d + end + end + return nil +end + +return Q3Shader +end +__FILES["data/q3skin"] = function() + +-- data/q3skin: Quake III model skins (.skin: "surface,shader" lines, "tag_*," for tags; tr_image.c RE_RegisterSkin, no +-- code taken), read and write. Decodes to a list of { surface, shader } in file order (shader "" for tags). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +-- ------------------------------------------------------------------------------------------------ contract +local Q3Skin = { + name = "q3skin", + category = "data", + extensions = { "skin" }, + mime = { "text/x-quake3-skin" }, + deps = { "core/Err", "core/Bytes" }, + caps = { decode = true, encode = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type Entry = { surface: string, shader: string } + +-- ------------------------------------------------------------------------------------------------ sniff +function Q3Skin.sniff(r: Bytes.Reader): number + local head = r:peek(math.min(r:remaining(), 1024)) + if #head < 3 or string.find(head, "[%z\1-\8\14-\31]") then + return 0 + end + local lines, good, paths = 0, 0, 0 + for line in string.gmatch(head, "[^\r\n]+") do + if not string.match(line, "^%s*$") then + lines += 1 + local surface, shader = string.match(line, "^%s*([%w_%-]+)%s*,%s*([^,%s]*)%s*$") + if surface and shader == "" and string.sub(string.lower(surface), 1, 4) == "tag_" then + good += 1 + elseif shader and string.find(shader, "/", 1, true) then + good += 1 + paths += 1 + end + end + end + return if lines > 0 and good == lines and paths > 0 then 0.5 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Q3Skin.decode(r: Bytes.Reader): ({ Entry }?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local out: { Entry } = {} + local n = 0 + for line in string.gmatch(text, "[^\r\n]+") do + n += 1 + local s = string.match(line, "^%s*(.-)%s*$") :: string + if s ~= "" and string.sub(s, 1, 2) ~= "//" then + local surface, shader = string.match(s, "^([^,]-)%s*,%s*(.-)$") + if not surface or surface == "" then + return nil, Err.new(Err.CORRUPT, "line " .. n .. ": expected surface,shader") + end + table.insert(out, { surface = surface, shader = shader :: string }) + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Q3Skin.encode(list: { Entry }): (buffer?, Err.Err?) + if type(list) ~= "table" then + return nil, Err.new(Err.ARG, "expected a list of { surface, shader }") + end + local out: { string } = {} + for _, e in list do + if type(e) ~= "table" or type(e.surface) ~= "string" or e.surface == "" or string.find(e.surface, "[,\r\n]") then + return nil, Err.new(Err.ARG, "a skin entry needs a surface name without commas") + end + local sh = if e.shader == nil then "" else tostring(e.shader) + if string.find(sh, "[,\r\n]") then + return nil, Err.new(Err.ARG, "a shader path cannot hold commas or line breaks") + end + table.insert(out, e.surface .. "," .. sh) + end + table.insert(out, "") + return buffer.fromstring(table.concat(out, "\n")), nil +end + +-- the shader of a surface (case-insensitive) +function Q3Skin.shader(list: { Entry }, surface: string): string? + local want = string.lower(surface) + for _, e in list do + if string.lower(e.surface) == want then + return e.shader + end + end + return nil +end + +return Q3Skin +end __FILES["data/snbt"] = function() -- data/snbt: stringified NBT over codecs/text/Nbt. Supports: parse to data/nbt's values, compact or indented print. @@ -132642,6 +134451,139 @@ end return Ktx end +__FILES["image/lmp"] = function() + +-- image/lmp: Quake .lmp lumps (wad.h / draw.c of the Quake source; no code taken), read and write: qpic pictures (u32 +-- width, height, 8-bit pixels; index 255 transparent), palette.lmp (768 bytes: a 16 x 16 swatch) and colormap.lmp (64 +-- light levels x 256: a 256 x 64 image). Pictures and colormaps need Quake's palette, which is never embedded (GPL): +-- opts.palette or gfx/palette.lmp through files / resolve; else grey (meta.source.palette = false). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") +local Miptex = __include("codecs/image/Miptex") + +-- ------------------------------------------------------------------------------------------------ contract +local Lmp = { + name = "lmp", + category = "image", + extensions = { "lmp" }, + mime = { "image/x-quake-lmp" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 }, variants = { "qpic", "palette", "colormap" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + palette: (buffer | string)?, -- 768 bytes + kind: ("qpic" | "palette" | "colormap")?, -- default: from the size + keyed: boolean?, -- qpic index 255 transparent, default true + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + maxPixels: number?, -- default 2^24 +} +type EncodeOptions = { + palette: (buffer | string)?, -- 768 bytes: required for qpics + kind: ("qpic" | "palette")?, -- default "qpic"; "palette" writes a 16 x 16 swatch as 768 bytes + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, +} + +-- ------------------------------------------------------------------------------------------------ sniff +local function kindOf(r: Bytes.Reader): string? + local n = r:remaining() + if n == 768 then + return "palette" + elseif n == 16385 or n == 16384 then + return "colormap" + end + if n < 9 then + return nil + end + local w, h = buffer.readu32(r.buf, r.pos), buffer.readu32(r.buf, r.pos + 4) + if w > 0 and h > 0 and w <= 4096 and h <= 4096 and 8 + w * h == n then + return "qpic" + end + return nil +end + +function Lmp.sniff(r: Bytes.Reader): number + local k = kindOf(r) + return if k == "qpic" then 0.3 elseif k then 0.05 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function palette(opts: any?): buffer? + local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp") + if raw and buffer.len(raw) >= 768 then + return Pixels.palette(raw, 0, 256) + end + return nil +end + +function Lmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local kind = opts and opts.kind or kindOf(r) + local b, at, n = r.buf, r.base, r.limit - r.base + if kind == "palette" then + if n < 768 then + return nil, Err.new(Err.TRUNCATED, "palette", 0) + end + local img = Types.Image.new(16, 16) + buffer.copy(img.pixels, 0, Pixels.palette(b, at, 256), 0, 1024) + local list = Pixels.colorList(img.pixels) + img.meta.palette = list + img.meta.source = { format = "lmp", kind = "palette" } + return img, nil + end + local pal = palette(opts) + if kind == "colormap" then + local rows = math.min(64, n // 256) + if rows < 1 then + return nil, Err.new(Err.TRUNCATED, "colormap", 0) + end + local img = Types.Image.new(256, rows) + Pixels.indexed(b, at, 256, 8, img.pixels, 256, rows, true, pal or Pixels.grey()) + img.meta.source = { format = "lmp", kind = "colormap", palette = pal ~= nil } + return img, nil + end + if kind ~= "qpic" and n >= 8 then + kind = "qpic" + end + local img, msg = Miptex.qpic(b, at, n, { palette = pal, keyed = opts and opts.keyed, maxPixels = opts and opts.maxPixels }) + if not img then + return nil, Err.from(msg, 0) + end + img.meta.source = { format = "lmp", kind = "qpic", palette = pal ~= nil, keyed = (opts == nil or opts.keyed ~= false) or nil } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Lmp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected an rgba8 Image") + end + if opts and opts.kind == "palette" then + if img.width * img.height < 256 then + return nil, Err.new(Err.ARG, "a palette needs 256 pixels (16 x 16)") + end + return Pixels.paletteBytes(img.pixels, 256), nil + end + local pal = palette(opts) + if not pal then + return nil, Err.new(Err.ARG, "a qpic needs Quake's palette (opts.palette or gfx/palette.lmp; it is not embedded)") + end + local out, msg = Miptex.encodeQpic(img, pal, false, true) + if not out then + return nil, Err.new(Err.ARG, msg or "cannot encode") + end + return out, nil +end + +return Lmp +end __FILES["image/pcx"] = function() -- image/pcx: ZSoft PC Paintbrush (ZSoft "Technical Reference Manual" header and RLE). Supports: 1-bit, 1-bit x 2..4 @@ -135173,6 +137115,319 @@ end return Sgi end +__FILES["image/spr"] = function() + +-- image/spr: Quake (IDSP 1), Half-Life (IDSP 2, own palette, texture formats) and DarkPlaces SPR32 (IDSP 32, rgba) +-- sprites, read and write (spritegn.h of the Quake source, the GoldSrc sprite layout; no code taken). Frames and frame +-- groups become Image frames on one canvas around the sprite origin (meta.origin); group intervals give the delays. +-- Quake sprites need Quake's palette (opts.palette or gfx/palette.lmp through files / resolve; never embedded). +-- Not supported: Quake II sprites (IDS2: frames are separate .pcx files). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") +local Miptex = __include("codecs/image/Miptex") + +-- ------------------------------------------------------------------------------------------------ contract +local Spr = { + name = "spr", + category = "image", + extensions = { "spr" }, + mime = { "image/x-quake-sprite" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, alpha = true, animation = true, variants = { "quake", "halflife", "spr32" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + palette: (buffer | string)?, -- Quake: 768 bytes + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + maxPixels: number?, -- per frame, default 2^24 + maxFrames: number?, -- default 4096 +} +type EncodeOptions = { + version: number?, -- 2 (Half-Life, default), 1 (Quake: needs opts.palette) or 32 (rgba) + palette: (buffer | string)?, + type: number?, -- orientation: 0 parallel upright, 1 facing upright, 2 parallel (default), 3 oriented, 4 parallel oriented + texFormat: number?, -- Half-Life: 0 normal, 1 additive, 2 index alpha, 3 alpha test (default: 3 when any pixel is transparent) + delay: number?, -- seconds per frame when the image has none, default 0.1 +} + +-- ------------------------------------------------------------------------------------------------ constants +local TEX_FORMATS = { [0] = "normal", "additive", "indexalpha", "alphatest" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Spr.sniff(r: Bytes.Reader): number + if r:remaining() < 36 or r:peek(4) ~= "IDSP" then + return 0 + end + local v = buffer.readi32(r.buf, r.pos + 4) + return if v == 1 or v == 2 or v == 32 then 1 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Raw = { x: number, y: number, w: number, h: number, at: number, delay: number } + +function Spr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + if r:string(4) ~= "IDSP" then + return nil, r.err or Err.new(Err.CORRUPT, "bad magic", 0) + end + local version = r:i32le() + if version ~= 1 and version ~= 2 and version ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, "sprite version " .. tostring(version), 4) + end + local stype = r:i32le() + local texFormat = if version == 2 then r:i32le() else 3 + local radius = r:f32le() + local mw, mh, nframes = r:i32le(), r:i32le(), r:i32le() + local beam, sync = r:f32le(), r:i32le() + if r.err then + return nil, r.err + end + local maxFrames = opts and opts.maxFrames or 4096 + local maxPixels = opts and opts.maxPixels or 2 ^ 24 + if nframes < 1 or nframes > maxFrames then + return nil, Err.new(if nframes < 1 then Err.CORRUPT else Err.LIMIT, "frame count " .. nframes, 24) + end + local pal: buffer + local own = false + if version == 2 then + local n = r:u16le() + if r.err then + return nil, r.err + end + if n < 1 or n > 256 or not r:need(n * 3) then + return nil, r.err or Err.new(Err.CORRUPT, "palette size " .. n, r:tell() - 2) + end + pal = Pixels.palette(r.buf, r.pos, n) + r:skip(n * 3) + own = true + else + local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp") + own = raw ~= nil and buffer.len(raw) >= 768 + pal = if raw and own then Pixels.palette(raw, 0, 256) else Pixels.grey() + end + local bpp = if version == 32 then 4 else 1 + local raws: { Raw } = {} + local groups: { { type: string, count: number } } = {} + local function single(delay: number): Err.Err? + local x, y, w, h = r:i32le(), r:i32le(), r:i32le(), r:i32le() + if r.err then + return r.err + end + if w < 1 or h < 1 then + return Err.new(Err.CORRUPT, "frame size " .. w .. " x " .. h, r:tell() - 8) + end + if w * h > maxPixels then + return Err.new(Err.LIMIT, "frame " .. w .. " x " .. h) + end + if not r:need(w * h * bpp) then + return r.err + end + table.insert(raws, { x = x, y = y, w = w, h = h, at = r.pos, delay = delay }) + r:skip(w * h * bpp) + return nil + end + for _ = 1, nframes do + local ft = r:i32le() + if r.err then + return nil, r.err + end + if ft == 0 then + local e = single(0.1) + if e then + return nil, e + end + table.insert(groups, { type = "single", count = 1 }) + else + local n = r:i32le() + if r.err then + return nil, r.err + end + if n < 1 or #raws + n > maxFrames then + return nil, Err.new(if n < 1 then Err.CORRUPT else Err.LIMIT, "group of " .. n .. " frames", r:tell() - 4) + end + local ivs = {} + for k = 1, n do + ivs[k] = r:f32le() + end + if r.err then + return nil, r.err + end + for k = 1, n do + -- intervals are cumulative end times (R_GetSpriteFrame) + local e = single(math.max(0, ivs[k] - (if k > 1 then ivs[k - 1] else 0))) + if e then + return nil, e + end + end + table.insert(groups, { type = "group", count = n }) + end + end + local minX: number, maxX: number, minY: number, maxY: number = math.huge, -math.huge, math.huge, -math.huge + for _, f in raws do + minX = math.min(minX, f.x) + maxX = math.max(maxX, f.x + f.w) + maxY = math.max(maxY, f.y) + minY = math.min(minY, f.y - f.h) + end + local cw, ch = maxX - minX, maxY - minY + if cw * ch > maxPixels then + return nil, Err.new(Err.LIMIT, "canvas " .. cw .. " x " .. ch) + end + local fpal = pal + if version ~= 2 or texFormat == 3 then + fpal = Pixels.keyed(pal, 255) + end + local b = r.buf + local frames: { any } = {} + for _, f in raws do + local img = Types.Image.new(f.w, f.h) + if version == 32 then + buffer.copy(img.pixels, 0, b, f.at, f.w * f.h * 4) + elseif version == 2 and texFormat == 2 then + -- index alpha: the colour is the last palette entry, the index is the alpha + local c = bit32.band(buffer.readu32(pal, 255 * 4), 0xFFFFFF) + for k = 0, f.w * f.h - 1 do + buffer.writeu32(img.pixels, k * 4, c + buffer.readu8(b, f.at + k) * 0x1000000) + end + else + Pixels.indexed(b, f.at, f.w, 8, img.pixels, f.w, f.h, true, fpal) + end + table.insert(frames, { image = img, delay = f.delay, x = f.x - minX, y = maxY - f.y, dispose = "background", blend = "source" }) + end + local out = Types.Image.new(cw, ch) + local f1 = frames[1] + for yy = 0, f1.image.height - 1 do + buffer.copy(out.pixels, ((f1.y + yy) * cw + f1.x) * 4, f1.image.pixels, yy * f1.image.width * 4, f1.image.width * 4) + end + out.frames = if #frames > 1 then frames else nil + out.loops = 0 + out.meta.origin = { -minX, maxY } + out.meta.source = { + format = "spr", version = version, type = stype, texFormat = if version == 2 then TEX_FORMATS[texFormat] or texFormat else nil, + radius = radius, width = mw, height = mh, beamLength = beam, sync = sync, groups = groups, + palette = own, origins = (function() + local o = {} + for i, f in raws do + o[i] = { f.x, f.y } + end + return o + end)(), + } + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Spr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected an rgba8 Image") + end + local version = opts and opts.version or 2 + if version ~= 1 and version ~= 2 and version ~= 32 then + return nil, Err.new(Err.ARG, "version must be 1, 2 or 32") + end + local list: { { image: Types.Image, x: number, y: number, delay: number } } = {} + if img.frames and #img.frames > 0 then + for _, f in img.frames do + if f.image.format ~= "rgba8" then + return nil, Err.new(Err.ARG, "frames must be rgba8") + end + table.insert(list, { image = f.image, x = f.x, y = f.y, delay = f.delay }) + end + else + table.insert(list, { image = img, x = 0, y = 0, delay = opts and opts.delay or 0.1 }) + end + local origin = img.meta and img.meta.origin or { img.width // 2, img.height // 2 } + local mw: number, mh: number, alpha = 0, 0, false + for _, f in list do + mw = math.max(mw, f.image.width) + mh = math.max(mh, f.image.height) + local px = f.image.pixels + for k = 0, f.image.width * f.image.height - 1 do + if buffer.readu8(px, k * 4 + 3) < 128 then + alpha = true + break + end + end + end + local pal: buffer? = nil + if version == 1 then + local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else nil + if not raw or buffer.len(raw) < 768 then + return nil, Err.new(Err.ARG, "a Quake sprite needs Quake's palette (opts.palette; it is not embedded)") + end + pal = Pixels.palette(raw, 0, 256) + elseif version == 2 then + local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else nil + if raw and buffer.len(raw) >= 768 then + pal = Pixels.palette(raw, 0, 256) + else + -- one palette for every frame: the frames side by side + local tw = 0 + for _, f in list do + tw += f.image.width + end + local strip = Types.Image.new(tw, mh) + local x0 = 0 + for _, f in list do + for yy = 0, f.image.height - 1 do + buffer.copy(strip.pixels, (yy * tw + x0) * 4, f.image.pixels, yy * f.image.width * 4, f.image.width * 4) + end + x0 += f.image.width + end + local _, colors = Miptex.indices(strip, nil, alpha) + local p = buffer.create(1024) + for i, c in colors do + buffer.writeu32(p, (i - 1) * 4, 0xFF000000 + c[3] * 65536 + c[2] * 256 + c[1]) + end + if alpha then + buffer.writeu32(p, 255 * 4, 0xFFFF0000) -- the alpha-test key: blue + end + pal = p + end + end + local texFormat = opts and opts.texFormat or (if alpha then 3 else 0) + local w = Bytes.writer() + w:string("IDSP") + w:u32le(version) + w:u32le(opts and opts.type or 2) + if version == 2 then + w:u32le(texFormat) + end + w:f32le(math.sqrt(mw * mw + mh * mh) / 2) + w:u32le(mw) + w:u32le(mh) + w:u32le(#list) + w:f32le(0) + w:u32le(0) + if version == 2 then + w:u16le(256) + w:bytes(Pixels.paletteBytes(pal :: buffer, 256)) + end + for _, f in list do + local fw, fh = f.image.width, f.image.height + w:u32le(0) + w:u32le(bit32.band(f.x - origin[1], 0xFFFFFFFF)) + w:u32le(bit32.band(origin[2] - f.y, 0xFFFFFFFF)) + w:u32le(fw) + w:u32le(fh) + if version == 32 then + w:bytes(f.image.pixels, 0, fw * fh * 4) + else + local idx = Miptex.indices(f.image, pal, alpha and texFormat == 3 or version == 1) + w:bytes(idx, 0, fw * fh) + end + end + return w:finish(), nil +end + +return Spr +end __FILES["image/sunras"] = function() -- image/sunras: Sun Raster (rasterfile(5), SunOS ). Supports: 1-bit (0 = white without a colour map), @@ -145936,17 +148191,20 @@ return Read end __FILES["model/bsp"] = function() --- model/bsp: compiled game maps, read: Quake 1 (BSP 29), Half-Life (BSP 30), Quake II (IBSP 38), Quake III / RTCW --- (IBSP 46 / 47). Quake textures need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up. --- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing. +-- model/bsp: compiled game maps, read: Quake 1 (BSP 29, BSP2, 2PSB), Half-Life (BSP 30), Quake II (IBSP 38), Quake III +-- / RTCW (IBSP 46 / 47). Lightmaps (Quake 1 / 2 / Half-Life: one atlas, Quake III: its pages) as TEXCOORD_1; the tree, +-- collision hulls / brushes and visibility in meta.bsp with point queries (Bsp.leafAt / contents / pvs). Quake textures +-- need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up. Not supported: Source engine VBSP, +-- light styles other than the first, BSPX lumps, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Input = __include("core/Input") local Types = __include("Types") -local Brush = __include("model/bsp/Brush") +local Quake = __include("model/bsp/Quake") local Quake3 = __include("model/bsp/Quake3") +local Tree = __include("model/bsp/Tree") -- ------------------------------------------------------------------------------------------------ contract local Bsp = { @@ -145954,8 +148212,8 @@ local Bsp = { category = "model", extensions = { "bsp" }, mime = { "model/x-bsp" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, - caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" }, + caps = { decode = true, encode = false, variants = { "quake", "bsp2", "2psb", "halflife", "quake2", "quake3" }, lightmaps = true, collision = true, visibility = true }, } -- ------------------------------------------------------------------------------------------------ types @@ -145964,6 +148222,10 @@ type DecodeOptions = { resolve: ((uri: string) -> (buffer | string)?)?, files: { [string]: buffer | string }?, patchLevel: number?, -- default 4 + lit: (buffer | string)?, -- Quake 1: the map's .lit file (coloured light); also found as ".lit" through files / resolve + lightmaps: boolean?, -- default true + tree: boolean?, -- meta.bsp (tree, hulls, visibility), default true + name: string?, -- the file name (finds the .lit) maxPixels: number?, -- default 2^24 maxVertices: number?, -- default 2^24 } @@ -145983,6 +148245,9 @@ function Bsp.sniff(r: Bytes.Reader): number end local m = r:peek(4) local v = buffer.readi32(r.buf, r.pos + (if m == "IBSP" then 4 else 0)) + if m == "BSP2" or m == "2PSB" then + v = 29 + end if m == "IBSP" then return if v == 38 or v == 46 or v == 47 then 1 else 0.3 end @@ -146025,6 +148290,8 @@ function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E names, dir, variant = Q2_LUMPS, 8, "q2" elseif m == "IBSP" and (version == 46 or version == 47) then names, dir, variant = Q3_LUMPS, 8, "q3" + elseif m == "BSP2" or m == "2PSB" then + names, dir, variant = Q1_LUMPS, 4, string.lower(m) elseif m ~= "IBSP" and (version == 29 or version == 30) then names, dir, variant = Q1_LUMPS, 4, if version == 30 then "hl" else "q1" elseif m == "VBSP" then @@ -146051,13 +148318,15 @@ function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if pal and buffer.len(pal) < 768 then pal = nil end - scene, msg = Brush.decode(b, base, lumps, variant, { + scene, msg = Quake.decode(b, base, lumps, variant, { palette = pal, wal = function(name: string): buffer? return Input.sibling(opts, "textures/" .. name .. ".wal") end, maxPixels = opts and opts.maxPixels, maxVertices = opts and opts.maxVertices, + lit = if opts and opts.lit then Bytes.toBuffer(opts.lit) else (if opts and opts.name then Input.sibling(opts, (string.gsub(opts.name :: string, "%.[^./\\]*$", "")) .. ".lit") else nil), + lightmaps = opts and opts.lightmaps, }) end if not scene then @@ -146069,28 +148338,129 @@ function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E scene.meta.entities = entities(text) scene.meta.source = { format = "bsp", - variant = ({ q1 = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant], + variant = ({ q1 = "quake", bsp2 = "quake", ["2psb"] = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant], + layout = if variant == "bsp2" then "BSP2" elseif variant == "2psb" then "2PSB" else nil, version = version, entities = text, - palette = if variant == "q1" then (opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) else nil, + palette = if variant == "q1" or variant == "bsp2" or variant == "2psb" then (opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) else nil, } + if not (opts and opts.tree == false) then + local tree, terr = Tree.read(b, base, lumps, variant) + if not tree then + return nil, Err.from(terr) + end + scene.meta.bsp = tree + end return scene, nil end +-- ------------------------------------------------------------------------------------------------ extras +local function tree(scene: any): Tree.Data? + return type(scene) == "table" and type(scene.meta) == "table" and scene.meta.bsp or nil +end + +-- the leaf (0-based) at a point, in the tree of a model (0 = the world) +function Bsp.leafAt(scene: Types.Scene, x: number, y: number, z: number, model: number?): number? + local d = tree(scene) + return if d then Tree.leafAt(d, x, y, z, model) else nil +end + +-- the contents at a point: Quake 1 CONTENTS_* (-1 empty, -2 solid, ...; hull 0 point, 1 player, 2 shambler, 3 crouch +-- in Half-Life), Quake II / III contents bits +function Bsp.contents(scene: Types.Scene, x: number, y: number, z: number, hull: number?, model: number?): number? + local d = tree(scene) + return if d then Tree.contents(d, x, y, z, hull, model) else nil +end + +-- the leaves (0-based) potentially visible from a leaf; nil when the map has no visibility data +function Bsp.pvs(scene: Types.Scene, leaf: number): { number }? + local d = tree(scene) + return if d then Tree.pvs(d, leaf) else nil +end + return Bsp end -__FILES["model/bsp/Brush"] = function() +__FILES["model/bsp/Lightmap"] = function() --- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from bspfile.h of the --- Quake / Quake II source releases (no code taken). Texture coordinates: s = v . s.xyz + s.w, divided by the texture --- size. +-- model/bsp/Lightmap: packs face lightmaps (w x h luxels each) into one atlas, shelf by shelf, tallest first, each +-- with a one-luxel border that repeats its edge (bilinear filtering stays inside the face). +local Lightmap = {} + +type Rect = { x: number, y: number, w: number, h: number } -- x, y: the first luxel inside the border + +-- nil, message past maxPixels +function Lightmap.pack(sizes: { { number } }, maxPixels: number): (number, number, { Rect }?, string?) + local area, widest = 0, 1 + for _, s in sizes do + area += (s[1] + 2) * (s[2] + 2) + widest = math.max(widest, s[1] + 2) + end + local W = 64 + while W * W < area * 1.2 and W < 4096 do + W *= 2 + end + W = math.max(W, widest) + local order = table.create(#sizes) :: { number } + for i = 1, #sizes do + order[i] = i + end + table.sort(order, function(a: number, b: number): boolean + local ha, hb = sizes[a][2], sizes[b][2] + if ha ~= hb then + return ha > hb + end + return a < b + end) + local out = table.create(#sizes) :: { Rect } + local x, y, rowH = 0, 0, 0 + for _, i in order do + local w, h = sizes[i][1] + 2, sizes[i][2] + 2 + if x + w > W then + x, y, rowH = 0, y + rowH, 0 + end + out[i] = { x = x + 1, y = y + 1, w = sizes[i][1], h = sizes[i][2] } + x += w + rowH = math.max(rowH, h) + end + local H = math.max(1, y + rowH) + if W * H > maxPixels then + return 0, 0, nil, "limit: lightmap atlas " .. W .. " x " .. H + end + return W, H, out, nil +end + +-- copies the outermost luxels of a rect into its border (rgba8 pixels, atlas width W) +function Lightmap.border(px: buffer, W: number, r: Rect) + local function copy(dx: number, dy: number, sx: number, sy: number) + buffer.writeu32(px, (dy * W + dx) * 4, buffer.readu32(px, (sy * W + sx) * 4)) + end + for yy = r.y, r.y + r.h - 1 do + copy(r.x - 1, yy, r.x, yy) + copy(r.x + r.w, yy, r.x + r.w - 1, yy) + end + for xx = r.x - 1, r.x + r.w do + copy(xx, r.y - 1, xx, r.y) + copy(xx, r.y + r.h, xx, r.y + r.h - 1) + end +end + +return Lightmap +end +__FILES["model/bsp/Quake"] = function() + +-- model/bsp/Quake: Quake 1 (BSP 29, BSP2, 2PSB), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from +-- bspfile.h of the Quake / Quake II source releases and ericw-tools (BSP2 / 2PSB; no code taken). Texture coordinates: +-- s = v . s.xyz + s.w over the texture size; lightmaps (style 0) packed into one atlas as TEXCOORD_1, extents as +-- CalcSurfaceExtents (16 texels per luxel). local Types = __include("Types") local Pixels = __include("codecs/image/Pixels") +local Lightmap = __include("model/bsp/Lightmap") +local Miptex = __include("codecs/image/Miptex") -local Brush = {} +local Quake = {} local Scene = Types.Scene -local readi32, readu16, readf32, readu32 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32 +local readi32, readu16, readf32, readu32, readu8 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32, buffer.readu8 local writef32, writeu32 = buffer.writef32, buffer.writeu32 type Lump = { at: number, size: number } @@ -146099,10 +148469,12 @@ type Options = { wal: ((name: string) -> buffer?)?, -- Quake II: a texture's .wal file (for its size) maxPixels: number?, maxVertices: number?, + lit: buffer?, -- Quake 1 coloured light (.lit: "QLIT", version 1, RGB per luxel) + lightmaps: boolean?, -- default true } type Tex = { name: string, width: number, height: number, image: Types.Image?, texels: boolean } -type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number } } +type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number }, lm: { number } } -- lm: face, s, t per vertex local function cstr(b: buffer, at: number, n: number): string return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string @@ -146118,34 +148490,18 @@ local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer if n < 0 or n > 65536 or 4 + n * 4 > l.size then return nil, "bad miptex lump" end - local gpal = if pal then Pixels.palette(pal, 0, 256) else nil + local gpal = if pal and not hl then Pixels.palette(pal, 0, 256) else nil for i = 0, n - 1 do local o = readi32(b, at + 4 + i * 4) - if o < 0 or o + 40 > l.size then + local hd = if o >= 0 and o + 40 <= l.size then Miptex.header(b, at + o, l.size - o) else nil + if not hd then out[i + 1] = { name = "missing" .. i, width = 64, height = 64, image = nil, texels = false } else - local m = at + o - local name = cstr(b, m, 16) - local w, h, off0 = readu32(b, m + 16), readu32(b, m + 20), readu32(b, m + 24) - local t: Tex = { name = name, width = math.max(w, 1), height = math.max(h, 1), image = nil, texels = false } - if off0 ~= 0 and w > 0 and h > 0 and w * h <= maxPixels then - local px = m + off0 - local need = w * h - local palAt = m + readu32(b, m + 36) + (w // 8) * (h // 8) + 2 - if o + off0 + need <= l.size then - local p = gpal - if hl then - p = if palAt - at + 768 <= l.size then Pixels.palette(b, palAt, 256) else nil - end - local img = Types.Image.new(w, h) - if p then - Pixels.indexed(b, px, w, 8, img.pixels, w, h, true, p) - else - for k = 0, need - 1 do - writeu32(img.pixels, k * 4, 0xFF000000 + buffer.readu8(b, px + k) * 0x10101) - end - end - img.meta.source = { format = "bsp", miptex = name, palette = p ~= nil } + local t: Tex = { name = hd.name, width = math.max(hd.width, 1), height = math.max(hd.height, 1), image = nil, texels = false } + if hd.offsets[1] ~= 0 and hd.width * hd.height <= maxPixels then + local img = Miptex.decode(b, at + o, l.size - o, { palette = gpal, goldsrc = hl, keyed = false, maxPixels = maxPixels }) + if img then + img.meta.source = { format = "bsp", miptex = hd.name, palette = img.meta.source and img.meta.source.palette } t.image = img end end @@ -146155,11 +148511,14 @@ local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer return out, nil end -function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?) +function Quake.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?) local q2 = variant == "q2" + local big = variant == "bsp2" or variant == "2psb" local maxPixels = opts and opts.maxPixels or 2 ^ 24 local V, E, SE, Fc, TI, P, M = lumps.vertices, lumps.edges, lumps.surfedges, lumps.faces, lumps.texinfo, lumps.planes, lumps.models - local nV, nE, nSE, nF = V.size // 12, E.size // 4, SE.size // 4, Fc.size // 20 + local fSize: number = if big then 28 else 20 + local eSize: number = if big then 8 else 4 + local nV, nE, nSE, nF = V.size // 12, E.size // eSize, SE.size // 4, Fc.size // fSize local tiSize = if q2 then 76 else 40 local nTI, nP = TI.size // tiSize, P.size // 20 local mSize = if q2 then 48 else 64 @@ -146222,11 +148581,28 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian local batches: { [number]: { [number]: Batch } } = {} local orders: { [number]: { number } } = {} local skipped = 0 + -- lightmaps: record 1 = a white luxel (sky / liquids), 2 = black (unlit faces), then one per lit face + local LT = lumps.lighting + local useLight = LT.size > 0 and not (opts and opts.lightmaps == false) + local rgb = variant == "hl" or q2 + local lit = opts and opts.lit + if lit and (buffer.len(lit) < 8 or buffer.readstring(lit, 0, 4) ~= "QLIT" or buffer.readi32(lit, 4) ~= 1) then + lit = nil + end + local lmSizes: { { number } } = { { 1, 1 }, { 1, 1 } } + local lmFaces: { { face: number, ofs: number, smin: number, tmin: number, styles: number } } = { { face = -1, ofs = -1, smin = 0, tmin = 0, styles = 0 }, { face = -1, ofs = -1, smin = 0, tmin = 0, styles = 0 } } + local lumaTotal = 0 for f = 0, nF - 1 do - local fo = base + Fc.at + f * 20 - local plane, side, firstEdge, numEdges, texinfo = readu16(b, fo), readu16(b, fo + 2), readi32(b, fo + 4), readu16(b, fo + 8), readu16(b, fo + 10) + local fo = base + Fc.at + f * fSize + local plane = if big then readi32(b, fo) else readu16(b, fo) + local side = if big then readi32(b, fo + 4) else readu16(b, fo + 2) + local firstEdge = if big then readi32(b, fo + 8) else readi32(b, fo + 4) + local numEdges = if big then readi32(b, fo + 12) else readu16(b, fo + 8) + local texinfo = if big then readi32(b, fo + 16) else readu16(b, fo + 10) + local styles = if big then fo + 20 else fo + 12 + local lightofs = if big then readi32(b, fo + 24) else readi32(b, fo + 16) local model = faceModel[f + 1] - if not model or numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then + if not model or numEdges < 3 or plane < 0 or texinfo < 0 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then skipped += 1 continue end @@ -146239,7 +148615,13 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian ok = false break end - local v = if se >= 0 then readu16(b, base + E.at + e * 4) else readu16(b, base + E.at + e * 4 + 2) + local eo = base + E.at + e * eSize + local v + if big then + v = if se >= 0 then readu32(b, eo) else readu32(b, eo + 4) + else + v = if se >= 0 then readu16(b, eo) else readu16(b, eo + 2) + end if v >= nV then ok = false break @@ -146283,6 +148665,37 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian local tio = base + TI.at + texinfo * tiSize local sx, sy, sz, so = readf32(b, tio), readf32(b, tio + 4), readf32(b, tio + 8), readf32(b, tio + 12) local tx, ty, tz, to = readf32(b, tio + 16), readf32(b, tio + 20), readf32(b, tio + 24), readf32(b, tio + 28) + local rec = 2 + if useLight then + local tflags = readi32(b, tio + (if q2 then 32 else 36)) + local special = if q2 then bit32.band(tflags, 0x8C) ~= 0 else bit32.band(tflags, 1) ~= 0 + if special then + rec = 1 + elseif lightofs >= 0 then + local smin: number, smax: number, tmin: number, tmax: number = math.huge, -math.huge, math.huge, -math.huge + for k = 0, n - 1 do + local x, y, z = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] + local sv, tv = x * sx + y * sy + z * sz + so, x * tx + y * ty + z * tz + to + smin, smax = math.min(smin, sv), math.max(smax, sv) + tmin, tmax = math.min(tmin, tv), math.max(tmax, tv) + end + local bs, bt0 = math.floor(smin / 16), math.floor(tmin / 16) + local lw, lh = math.ceil((smax :: number) / 16) - bs + 1, math.ceil((tmax :: number) / 16) - bt0 + 1 + local ns = 0 + for k = 0, 3 do + if readu8(b, styles + k) ~= 255 then + ns += 1 + end + end + local bytes = lw * lh * (if rgb then 3 else 1) + lumaTotal += lw * lh + if ns > 0 and lw > 0 and lh > 0 and lw <= 256 and lh <= 256 and lightofs + bytes <= LT.size and lumaTotal <= maxPixels then + table.insert(lmSizes, { lw, lh }) + table.insert(lmFaces, { face = f, ofs = lightofs, smin = bs * 16, tmin = bt0 * 16, styles = ns }) + rec = #lmFaces + end + end + end local ti = texOf[texinfo + 1] or 0 local tex = texs[ti] local w, h = if tex then tex.width else 1, if tex then tex.height else 1 @@ -146290,7 +148703,7 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian batches[model] = bm local bt = bm[ti] if not bt then - bt = { tex = ti, pos = {}, nrm = {}, uv = {} } + bt = { tex = ti, pos = {}, nrm = {}, uv = {}, lm = {} } bm[ti] = bt local ol = orders[model] or {} orders[model] = ol @@ -146303,21 +148716,69 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian local pp, nn, uu = batch.pos, batch.nrm, batch.uv pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = nx, ny, nz - uu[#uu + 1] = (x * sx + y * sy + z * sz + so) / w - uu[#uu + 1] = (x * tx + y * ty + z * tz + to) / h + local sv, tv = x * sx + y * sy + z * sz + so, x * tx + y * ty + z * tz + to + uu[#uu + 1] = sv / w + uu[#uu + 1] = tv / h + local ll = batch.lm + ll[#ll + 1], ll[#ll + 2], ll[#ll + 3] = rec, sv, tv end end end + local atlasW, atlasH, rects = 0, 0, nil :: { Lightmap.Rect }? + local lmTex: number? = nil + local atlas: Types.Image? = nil + if useLight and #lmFaces > 2 then + local W, H, rs, err = Lightmap.pack(lmSizes, maxPixels) + if not rs then + return nil, err + end + atlasW, atlasH, rects = W, H, rs + local img = Types.Image.new(W, H) + local px = img.pixels + local la = base + LT.at + buffer.writeu32(px, (rs[1].y * W + rs[1].x) * 4, 0xFFFFFFFF) + buffer.writeu32(px, (rs[2].y * W + rs[2].x) * 4, 0xFF000000) + local placed = {} + for i = 3, #lmFaces do + local lf, r = lmFaces[i], rs[i] + for yy = 0, r.h - 1 do + for xx = 0, r.w - 1 do + local k = yy * r.w + xx + local cr: number, cg: number, cb: number = 0, 0, 0 + if rgb then + local o = la + lf.ofs + k * 3 + cr, cg, cb = readu8(b, o), readu8(b, o + 1), readu8(b, o + 2) + elseif lit and 8 + (lf.ofs + k) * 3 + 3 <= buffer.len(lit) then + local o = 8 + (lf.ofs + k) * 3 + cr, cg, cb = readu8(lit, o), readu8(lit, o + 1), readu8(lit, o + 2) + else + local v = readu8(b, la + lf.ofs + k) + cr, cg, cb = v, v, v + end + writeu32(px, ((r.y + yy) * W + r.x + xx) * 4, 0xFF000000 + (cb :: number) * 65536 + (cg :: number) * 256 + (cr :: number)) + end + end + table.insert(placed, { face = lf.face, x = r.x, y = r.y, w = r.w, h = r.h, styles = lf.styles }) + end + for i = 1, #lmFaces do + Lightmap.border(px, W, rs[i]) + end + img.meta.source = { format = "bsp", lightmap = "atlas", coloured = rgb or lit ~= nil } + atlas = img + scene.meta.lightmaps = placed + lmTex = #texs + 1 + end for i, t in texs do local tex: Types.Texture = { name = t.name, image = t.image, uri = if t.image then nil else (if q2 then "textures/" .. t.name .. ".wal" else t.name) } table.insert(scene.textures, tex) local mat = Scene.material(t.name) mat.metallic = 0 - local extras: any = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } - mat.extras = extras - mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } :: any + mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height, lightmap = lmTex, lightmapTexCoord = if lmTex then 1 else nil } } :: any table.insert(scene.materials, mat) end + if atlas then + table.insert(scene.textures, { name = "lightmap", image = atlas }) + end local root: Types.Node = { name = "bsp", children = {} } table.insert(scene.nodes, root) scene.roots[1] = 1 @@ -146339,8 +148800,23 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian for k = 0, nv - 1 do writeu32(ib, k * 4, k) end + local attrs: { [string]: Types.Accessor } = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) } + if rects then + local lb = buffer.create(nv * 8) + for k = 0, nv - 1 do + local rec, sv, tv = bt.lm[k * 3 + 1], bt.lm[k * 3 + 2], bt.lm[k * 3 + 3] + local r, lf = rects[rec], lmFaces[rec] + local lu, lv = r.x + 0.5, r.y + 0.5 + if rec > 2 then + lu, lv = r.x + (sv - lf.smin) / 16 + 0.5, r.y + (tv - lf.tmin) / 16 + 0.5 + end + writef32(lb, k * 8, lu / atlasW) + writef32(lb, k * 8 + 4, lv / atlasH) + end + attrs.TEXCOORD_1 = Scene.accessor(lb, "f32", 2, nv) + end table.insert(mesh.primitives, { - attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }, + attributes = attrs, indices = Scene.accessor(ib, "u32", 1, nv), mode = "triangles" :: any, material = if ti > 0 then ti else nil, @@ -146355,13 +148831,15 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian return scene, nil end -return Brush +return Quake end __FILES["model/bsp/Quake3"] = function() -- model/bsp/Quake3: Quake III Arena maps (IBSP 46; RTCW 47 has the same layout) -> Scene, from the Unofficial Quake 3 --- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped. +-- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped; patches +-- through codecs/model/Patch. local Types = __include("Types") +local Patch = __include("codecs/model/Patch") local Quake3 = {} @@ -146441,52 +148919,23 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: counts[if kind == 1 then "polygons" else "meshes"] += 1 elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then local w, h = readi32(b, o + 96), readi32(b, o + 100) - if w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n then + if Patch.valid(w, h, n) then counts.patches += 1 - local L = level - for py = 0, (h - 1) // 2 - 1 do - for px = 0, (w - 1) // 2 - 1 do - local ctrl: { { number } } = {} - for j = 0, 2 do - for i = 0, 2 do - ctrl[j * 3 + i + 1] = vertex(first + (py * 2 + j) * w + px * 2 + i) - end - end - local grid: { number } = {} - for gy = 0, L do - local tv = gy / L - for gx = 0, L do - local tu = gx / L - local bu = { (1 - tu) ^ 2, 2 * tu * (1 - tu), tu * tu } - local bv = { (1 - tv) ^ 2, 2 * tv * (1 - tv), tv * tv } - local v = table.create(14, 0) - for j = 0, 2 do - for i = 0, 2 do - local wgt = bu[i + 1] * bv[j + 1] - local cp = ctrl[j * 3 + i + 1] - for k = 1, 14 do - v[k] += cp[k] * wgt - end - end - end - local l = math.sqrt(v[8] ^ 2 + v[9] ^ 2 + v[10] ^ 2) - if l > 0 then - v[8], v[9], v[10] = v[8] / l, v[9] / l, v[10] / l - end - grid[gy * (L + 1) + gx + 1] = addExtra(v) - end - end - for gy = 0, L - 1 do - for gx = 0, L - 1 do - local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2] - local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2] - -- Quake's control grids are clockwise-front - for _, v in { a, d, c2, c2, d, e } do - table.insert(tris, v) - end - end - end - end + local ctrl = table.create(n * 14, 0) :: { number } + for k = 0, n - 1 do + table.move(vertex(first + k), 1, 14, k * 14 + 1, ctrl) + end + local pts, gw, gh = Patch.grid(ctrl, w, h, 14, level, level, maxV) + if not pts then + return nil, "limit: too many patch vertices" + end + Patch.normalize(pts, 14, 7) + local ids = table.create(gw * gh) :: { number } + for k = 0, gw * gh - 1 do + ids[k + 1] = addExtra(table.move(pts, k * 14 + 1, k * 14 + 14, 1, table.create(14, 0)) :: { number }) + end + for _, v in Patch.triangles(gw, gh) do + table.insert(tris, ids[v + 1]) end else counts.skipped += 1 @@ -146612,6 +149061,394 @@ end return Quake3 end +__FILES["model/bsp/Tree"] = function() + +-- model/bsp/Tree: the BSP tree, collision hulls and visibility of Quake 1 / BSP2 / 2PSB / Half-Life / Quake II / Quake +-- III maps as tables (bspfile.h layouts; Unofficial Quake 3 Map Specs), plus point queries: the leaf and contents at a +-- point (Quake 1 hulls 0..3 through nodes / clipnodes as SV_HullPointContents; Quake II leaf contents; Quake III the +-- contents of the leaf's brushes) and the potentially visible set of a leaf (run-length zero bytes, as Mod_DecompressVis). +local Tree = {} + +local readi32, readu16, readi16, readf32, readu8, readu32 = buffer.readi32, buffer.readu16, buffer.readi16, buffer.readf32, buffer.readu8, buffer.readu32 + +type Lump = { at: number, size: number } +type Plane = { normal: { number }, dist: number, type: number? } +type Node = { plane: number, children: { number }, mins: { number }, maxs: { number }, firstFace: number?, numFaces: number? } -- children: >= 0 node, < 0 leaf -(child + 1) +type Leaf = { + contents: number?, + cluster: number?, + area: number?, + visofs: number?, + mins: { number }, + maxs: { number }, + firstFace: number?, + numFaces: number?, + firstBrush: number?, + numBrushes: number?, + ambient: { number }?, +} +type ClipNode = { plane: number, children: { number } } -- children: >= 0 clipnode, < 0 contents +type Model = { mins: { number }, maxs: { number }, origin: { number }?, headnodes: { number }, visleafs: number?, firstFace: number, numFaces: number } +type Brush = { firstSide: number, numSides: number, contents: number } +type Side = { plane: number, texinfo: number } +type Data = { + variant: string, + planes: { Plane }, + nodes: { Node }, + leaves: { Leaf }, + clipnodes: { ClipNode }?, + models: { Model }, + brushes: { Brush }?, + brushSides: { Side }?, + leafBrushes: { number }?, + leafFaces: { number }?, + visibility: buffer?, -- the raw lump + numClusters: number?, + clusterBytes: number?, -- Quake III bytes per cluster vector +} + +local function v3(b: buffer, o: number, kind: string): { number } + if kind == "f" then + return { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) } + elseif kind == "i" then + return { readi32(b, o), readi32(b, o + 4), readi32(b, o + 8) } + end + return { readi16(b, o), readi16(b, o + 2), readi16(b, o + 4) } +end + +local function slice(b: buffer, base: number, l: Lump): buffer? + if l.size <= 0 then + return nil + end + local out = buffer.create(l.size) + buffer.copy(out, 0, b, base + l.at, l.size) + return out +end + +-- nil, message past maxItems +function Tree.read(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, maxItems: number?): (Data?, string?) + local limit = maxItems or 2 ^ 22 + local q2, q3 = variant == "q2", variant == "q3" + local bsp2, rmq = variant == "bsp2", variant == "2psb" + local d: Data = { variant = variant, planes = {}, nodes = {}, leaves = {}, models = {} } + local function count(l: Lump?, size: number): number + return if l then l.size // size else 0 + end + local P = lumps.planes + local pSize = if q3 then 16 else 20 + local np = count(P, pSize) + if np > limit then + return nil, "limit: too many planes" + end + for i = 0, np - 1 do + local o = base + P.at + i * pSize + d.planes[i + 1] = { normal = v3(b, o, "f"), dist = readf32(b, o + 12), type = if q3 then nil else readi32(b, o + 16) } + end + local N = lumps.nodes + local nSize = if q3 then 36 elseif q2 then 28 elseif bsp2 then 44 elseif rmq then 32 else 24 + local nn = count(N, nSize) + if nn > limit then + return nil, "limit: too many nodes" + end + for i = 0, nn - 1 do + local o = base + N.at + i * nSize + local node: any + if q3 or q2 or bsp2 or rmq then + local bk = if q3 then "i" elseif bsp2 then "f" else "s" + local bs = if bk == "s" then 6 else 12 + node = { plane = readi32(b, o), children = { readi32(b, o + 4), readi32(b, o + 8) }, mins = v3(b, o + 12, bk), maxs = v3(b, o + 12 + bs, bk) } + if not q3 then + local fo = o + 12 + bs * 2 + if q2 then + node.firstFace, node.numFaces = readu16(b, fo), readu16(b, fo + 2) + else + node.firstFace, node.numFaces = readu32(b, fo), readu32(b, fo + 4) + end + end + else + local c = {} + for k = 0, 1 do + local p = readu16(b, o + 4 + k * 2) + c[k + 1] = if p < nn then p else -(65535 - p) - 1 -- Quakespasm Mod_LoadNodes_S: leaf 65535 - p + end + node = { plane = readi32(b, o), children = c, mins = v3(b, o + 8, "s"), maxs = v3(b, o + 14, "s"), firstFace = readu16(b, o + 20), numFaces = readu16(b, o + 22) } + end + d.nodes[i + 1] = node + end + local L = lumps.leaves or lumps.leafs + local lSize = if q3 then 48 elseif q2 then 28 elseif bsp2 then 44 elseif rmq then 32 else 28 + local nl = count(L, lSize) + if nl > limit then + return nil, "limit: too many leaves" + end + for i = 0, nl - 1 do + local o = base + L.at + i * lSize + local leaf: any + if q3 then + leaf = { cluster = readi32(b, o), area = readi32(b, o + 4), mins = v3(b, o + 8, "i"), maxs = v3(b, o + 20, "i"), + firstFace = readi32(b, o + 32), numFaces = readi32(b, o + 36), firstBrush = readi32(b, o + 40), numBrushes = readi32(b, o + 44) } + elseif q2 then + leaf = { contents = readi32(b, o), cluster = readi16(b, o + 4), area = readi16(b, o + 6), mins = v3(b, o + 8, "s"), maxs = v3(b, o + 14, "s"), + firstFace = readu16(b, o + 20), numFaces = readu16(b, o + 22), firstBrush = readu16(b, o + 24), numBrushes = readu16(b, o + 26) } + else + local bk = if bsp2 then "f" else "s" + local bs = if bsp2 then 12 else 6 + local fo = o + 8 + bs * 2 + local big = bsp2 or rmq + leaf = { contents = readi32(b, o), visofs = readi32(b, o + 4), mins = v3(b, o + 8, bk), maxs = v3(b, o + 8 + bs, bk), + firstFace = if big then readu32(b, fo) else readu16(b, fo), numFaces = if big then readu32(b, fo + 4) else readu16(b, fo + 2) } + local ao = fo + (if big then 8 else 4) + leaf.ambient = { readu8(b, ao), readu8(b, ao + 1), readu8(b, ao + 2), readu8(b, ao + 3) } + end + d.leaves[i + 1] = leaf + end + if not q2 and not q3 then + local C = lumps.clipnodes + local cSize = if bsp2 or rmq then 12 else 8 + local nc = count(C, cSize) + if nc > limit then + return nil, "limit: too many clipnodes" + end + local cl: { ClipNode } = {} + for i = 0, nc - 1 do + local o = base + C.at + i * cSize + local c + if cSize == 12 then + c = { readi32(b, o + 4), readi32(b, o + 8) } + else + c = {} + for k = 0, 1 do + local p = readu16(b, o + 4 + k * 2) + c[k + 1] = if p > nc then p - 65536 else p -- Quakespasm Mod_LoadClipnodes + end + end + cl[i + 1] = { plane = readi32(b, o), children = c } + end + d.clipnodes = cl + end + local M = lumps.models + local mSize = if q3 then 40 elseif q2 then 48 else 64 + for i = 0, count(M, mSize) - 1 do + local o = base + M.at + i * mSize + local m: any + if q3 then + m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), headnodes = { 0 }, firstFace = readi32(b, o + 24), numFaces = readi32(b, o + 28) } + elseif q2 then + m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), origin = v3(b, o + 24, "f"), headnodes = { readi32(b, o + 36) }, firstFace = readi32(b, o + 40), numFaces = readi32(b, o + 44) } + else + m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), origin = v3(b, o + 24, "f"), + headnodes = { readi32(b, o + 36), readi32(b, o + 40), readi32(b, o + 44), readi32(b, o + 48) }, + visleafs = readi32(b, o + 52), firstFace = readi32(b, o + 56), numFaces = readi32(b, o + 60) } + end + d.models[i + 1] = m + end + if q2 or q3 then + local B, S = lumps.brushes, lumps.brushsides + local nb, ns = count(B, 12), count(S, if q3 then 8 else 4) + if nb > limit or ns > limit then + return nil, "limit: too many brushes" + end + local brushes: { Brush }, sides: { Side } = {}, {} + for i = 0, nb - 1 do + local o = base + B.at + i * 12 + brushes[i + 1] = { firstSide = readi32(b, o), numSides = readi32(b, o + 4), contents = readi32(b, o + 8) } -- Quake III: a texture index + end + for i = 0, ns - 1 do + if q3 then + local o = base + S.at + i * 8 + sides[i + 1] = { plane = readi32(b, o), texinfo = readi32(b, o + 4) } + else + local o = base + S.at + i * 4 + sides[i + 1] = { plane = readu16(b, o), texinfo = readi16(b, o + 2) } + end + end + d.brushes, d.brushSides = brushes, sides + local LB = lumps.leafbrushes + local lbs: { number } = {} + for i = 0, count(LB, if q3 then 4 else 2) - 1 do + lbs[i + 1] = if q3 then readi32(b, base + LB.at + i * 4) else readu16(b, base + LB.at + i * 2) + end + d.leafBrushes = lbs + if q3 then + -- brush contents come from the texture's contents flags + local T = lumps.textures + local nt = count(T, 72) + for _, br in brushes do + local t = br.contents + br.contents = if t >= 0 and t < nt then readi32(b, base + T.at + t * 72 + 68) else 0 + end + end + end + local VL = lumps.visibility or lumps.visdata + d.visibility = if VL then slice(b, base, VL) else nil + local vis = d.visibility + if vis and q2 and buffer.len(vis) >= 4 then + d.numClusters = readi32(vis, 0) + elseif vis and q3 and buffer.len(vis) >= 8 then + d.numClusters, d.clusterBytes = readi32(vis, 0), readi32(vis, 4) + end + return d, nil +end + +local function side(d: Data, plane: number, x: number, y: number, z: number): number + local p = d.planes[plane + 1] + if not p then + return 0 + end + local n = p.normal + return x * n[1] + y * n[2] + z * n[3] - p.dist +end + +-- the leaf (0-based) at a point, walking the tree of model (0-based, default 0) +function Tree.leafAt(d: Data, x: number, y: number, z: number, model: number?): number? + local m = d.models[(model or 0) + 1] + local node = if m then m.headnodes[1] else 0 + for _ = 1, #d.nodes + 1 do + if node < 0 then + return -node - 1 + end + local nd = d.nodes[node + 1] + if not nd then + return nil + end + node = if side(d, nd.plane, x, y, z) >= 0 then nd.children[1] else nd.children[2] + end + return nil +end + +-- Quake 1: CONTENTS_* (-1 empty, -2 solid, -3 water, -4 slime, -5 lava, -6 sky) in hull 0..3; Quake II: the leaf's +-- CONTENTS_* bits; Quake III: the contents bits of the brushes holding the point +function Tree.contents(d: Data, x: number, y: number, z: number, hull: number?, model: number?): number? + local h = hull or 0 + if (d.variant == "q1" or d.variant == "hl" or d.variant == "bsp2" or d.variant == "2psb") and h > 0 then + local m = d.models[(model or 0) + 1] + local cl = d.clipnodes or {} + local node = if m then m.headnodes[h + 1] or -1 else -1 + for _ = 1, #cl + 1 do + if node < 0 then + return node + end + local c = cl[node + 1] + if not c then + return nil + end + node = if side(d, c.plane, x, y, z) >= 0 then c.children[1] else c.children[2] + end + return nil + end + local leaf = Tree.leafAt(d, x, y, z, model) + local lf = leaf and d.leaves[leaf + 1] + if not lf then + return nil + end + if d.variant ~= "q3" then + return lf.contents + end + local out = 0 + local lbs: { number }, brushes: { Brush }, sides: { Side } = d.leafBrushes or {}, d.brushes or {}, d.brushSides or {} + local fb: number, nb: number = lf.firstBrush or 0, lf.numBrushes or 0 + for k = fb, fb + nb - 1 do + local br = brushes[(lbs[k + 1] or -1) + 1] + if br then + local inside = true + for s = br.firstSide, br.firstSide + br.numSides - 1 do + local sd = sides[s + 1] + if not sd or side(d, sd.plane, x, y, z) > 0 then + inside = false + break + end + end + if inside then + out = bit32.bor(out, br.contents) + end + end + end + return out +end + +local function decompress(vis: buffer, at: number, bytes: number, out: { boolean }) + local n = buffer.len(vis) + local i = 0 + while i < bytes and at < n do + local c = readu8(vis, at) + if c ~= 0 then + for bit = 0, 7 do + if bit32.band(c, bit32.lshift(1, bit)) ~= 0 then + out[i * 8 + bit + 1] = true + end + end + i += 1 + at += 1 + else + if at + 1 >= n then + break + end + i += readu8(vis, at + 1) + at += 2 + end + end +end + +-- the leaves (0-based, sorted) potentially visible from a leaf; nil without visibility data (everything visible) +function Tree.pvs(d: Data, leaf: number): { number }? + local lf = d.leaves[leaf + 1] + local vis = d.visibility + if not lf or not vis then + return nil + end + local out: { number } = {} + if d.variant == "q2" or d.variant == "q3" then + local nc = d.numClusters or 0 + local c = lf.cluster or -1 + if c < 0 or c >= nc then + return out + end + local bits: { boolean } = {} + if d.variant == "q2" then + if 4 + nc * 8 > buffer.len(vis) then + return nil + end + decompress(vis, readi32(vis, 4 + c * 8), (nc + 7) // 8, bits) + else + local sz = d.clusterBytes or 0 + local o = 8 + c * sz + for k = 0, sz - 1 do + if o + k < buffer.len(vis) then + local v = readu8(vis, o + k) + for bit = 0, 7 do + if bit32.band(v, bit32.lshift(1, bit)) ~= 0 then + bits[k * 8 + bit + 1] = true + end + end + end + end + end + for i, l in d.leaves do + local cl = l.cluster or -1 + if cl >= 0 and bits[cl + 1] then + table.insert(out, i - 1) + end + end + return out + end + -- Quake 1: bit k = leaf k + 1 (leaf 0 is the shared solid leaf), visleafs bits + local visofs = lf.visofs or -1 + if leaf == 0 or visofs < 0 then + return out + end + local n = d.models[1] and d.models[1].visleafs or (#d.leaves - 1) + local bits: { boolean } = {} + decompress(vis, visofs, (n + 7) // 8, bits) + for k = 0, n - 1 do + if bits[k + 1] then + table.insert(out, k + 1) + end + end + return out +end + +return Tree +end __FILES["model/dae"] = function() -- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos specifications; .dae XML, .zae zip with manifest.xml). Supports: geometry, @@ -157217,6 +160054,1097 @@ end return Parse end +__FILES["model/map"] = function() + +-- model/map: editor .map files of Quake, Half-Life (Valve 220), Quake II (surface / content flags) and Quake III +-- (brushDef brush primitives, patchDef2; patchDef3 meshes), read and write. Grammar of the qbsp / q3map2 parsers (no +-- code taken). Brushes become polygons through codecs/model/Brush (optionally CSG'd and merged), patches through +-- codecs/model/Patch; a mesh per entity with brushes; entities as nodes with their keys in extras. Texture sizes from +-- opts.textureSizes, the worldspawn's WADs, .wal files or images through resolve; else 64 x 64. Not supported: Doom 3 +-- brushDef3, Build engine maps (binary: model/buildmap), compiling (no BSP, vis or light). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Miptex = __include("codecs/image/Miptex") +local Brush = __include("codecs/model/Brush") +local Parse = __include("model/map/Parse") +local Write = __include("model/map/Write") +local Build = __include("model/map/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Map = { + name = "map", + category = "model", + extensions = { "map" }, + mime = { "text/x-quake-map" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" }, + caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + hull: boolean?, -- drop faces inside / touching other brushes of the same entity, default false + merge: boolean?, -- merge coplanar faces with the same texture projection, default false + epsilon: number?, -- default 1e-3 + patchLevel: number?, -- patchDef2 segments per sub-patch, default 4 + skip: { string }?, -- texture names left out of the meshes ("clip", "skip", "common/caulk", ...) + textureSizes: { [string]: { number } }?, -- name -> { width, height } + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + decodeImage: ((buf: buffer) -> (Types.Image?, Err.Err?))?, -- Quake III: texture image sizes + maxBrushes: number?, -- default 2^20 + maxPolygons: number?, -- default 2^20 +} +type EncodeOptions = { + variant: string?, -- "valve220" converts Quake standard faces to Valve 220 axes; default: as stored +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Map.sniff(r: Bytes.Reader): number + local head = r:peek(math.min(r:remaining(), 4096)) + if #head < 2 or string.find(head, "[%z\1-\8\14-\31]") then + return 0 + end + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + local s = head + local game = false + while true do + local c = string.match(s, "^%s*//[^\n]*\n?()") + if not c then + break + end + if string.match(s, "^%s*//%s*Game:") then + game = true + end + s = string.sub(s, c :: number) + end + local body = string.match(s, '^%s*{%s*"[^"\n]*"%s*"') or string.match(s, "^%s*{%s*{%s*[%(bp]") + if not body then + return if game and string.match(s, "^%s*{") then 0.6 else 0 + end + return if game or string.find(head, '"classname"', 1, true) then 0.9 else 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function variantOf(m: Parse.Map): string + local game = string.lower(m.game or "") + local fmt = string.lower(m.mapFormat or "") + local q2, valve, q3 = false, false, false + for _, e in m.entities do + if e.keys.mapversion == "220" then + valve = true + end + for _, b in e.brushes do + if b.type ~= "brush" then + q3 = true + end + for _, f in b.faces or {} do + if f.u then + valve = true + elseif f.flags and #f.flags >= 3 then + q2 = true + end + end + end + end + if q3 or string.find(game, "quake 3") or string.find(game, "quake iii") or fmt == "quake3" or fmt == "quake3 (valve)" then + return "quake3" + end + if string.find(game, "quake 2") or string.find(game, "quake ii") or fmt == "quake2" or fmt == "quake2 (valve)" then + return "quake2" + end + if valve or fmt == "valve" then + return "valve220" + end + return if q2 then "quake2" else "quake" +end + +local function sizer(m: Parse.Map, variant: string, opts: DecodeOptions?): (name: string) -> (number, number, boolean) + local cache: { [string]: { number } } = {} + local wads: { { buf: buffer, lumps: { Miptex.Lump } } }? = nil + local function loadWads(): { { buf: buffer, lumps: { Miptex.Lump } } } + local list = {} + local ws = m.entities[1] and m.entities[1].keys + local spec = ws and (ws.wad or ws._wad) or "" + for path in string.gmatch(spec, "[^;]+") do + local p = string.gsub(path, "\\", "/") + local b = Input.sibling(opts, p) or Input.sibling(opts, string.match(p, "([^/]+)$") or p) + if b then + local lumps = Miptex.wad(b, 0, buffer.len(b)) + if lumps then + table.insert(list, { buf = b, lumps = lumps }) + end + end + end + return list + end + return function(name: string): (number, number, boolean) + local c = cache[name] + if c then + return c[1], c[2], c[3] == 1 + end + local w: number, h: number = 0, 0 + local given = opts and opts.textureSizes and opts.textureSizes[name] + if type(given) == "table" and type(given[1]) == "number" and type(given[2]) == "number" then + w, h = given[1] :: number, given[2] :: number + elseif variant == "quake" or variant == "valve220" then + wads = wads or loadWads() + for i = #(wads :: any), 1, -1 do + local wd = (wads :: any)[i] + local l = Miptex.find(wd.lumps, name) + if l then + local hd = Miptex.header(wd.buf, l.offset, l.disksize) + if hd then + w, h = hd.width, hd.height + break + end + end + end + elseif variant == "quake2" then + local wal = Input.sibling(opts, "textures/" .. name .. ".wal") + if wal and buffer.len(wal) >= 40 then + w, h = buffer.readu32(wal, 32), buffer.readu32(wal, 36) + end + elseif opts and opts.decodeImage then + for _, ext in { ".tga", ".jpg", ".png" } do + local b = Input.sibling(opts, "textures/" .. name .. ext) + if b then + local ok, img = pcall(opts.decodeImage :: any, b) + if ok and img then + w, h = img.width, img.height + break + end + end + end + end + local fw: number, fh: number = w :: number, h :: number + local known = fw > 0 and fh > 0 + if not known then + fw, fh = 64, 64 + end + cache[name] = { fw, fh, if known then 1 else 0 } + return fw, fh, known + end +end + +function Map.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local m, msg, at = Parse.parse(text, opts and opts.maxBrushes) + if not m then + return nil, Err.from(msg, at) + end + if #m.entities == 0 then + return nil, Err.new(Err.CORRUPT, "no entities", 0) + end + local variant = variantOf(m) + local scene, err = Build.scene(m, { + variant = variant, + size = sizer(m, variant, opts), + hull = opts and opts.hull, + merge = opts and opts.merge, + epsilon = opts and opts.epsilon, + patchLevel = opts and opts.patchLevel, + skip = opts and opts.skip, + maxPolygons = opts and opts.maxPolygons, + }) + if not scene then + return nil, Err.from(err) + end + local counts = scene.meta.counts + scene.meta.counts = nil + scene.meta.source = { format = "map", variant = variant, game = m.game, mapFormat = m.mapFormat, entities = #m.entities, brushes = counts.brushes, patches = counts.patches } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function toValve(f: Parse.Face): Parse.Face + if f.u or f.matrix then + return f + end + local bf = Build.face(f) + if not bf or not bf.vecs then + return f + end + local v = bf.vecs + local out = table.clone(f) + out.offset = nil + out.u, out.v = { v[1][1], v[1][2], v[1][3], v[1][4] }, { v[2][1], v[2][2], v[2][3], v[2][4] } + out.rotation, out.scale = 0, { 1, 1 } + return out +end + +local function fmtNum(x: number): string + return Write.num(x) +end + +function Map.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or type(scene.nodes) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local valve = opts and opts.variant == "valve220" + local ents: { any } = {} + for _, node in scene.nodes do + local ex: any = node.extras + if type(ex) == "table" and type(ex.keys) == "table" then + local keys = ex.keys + local brushes: { Parse.Brush } = if type(ex.brushes) == "table" then ex.brushes else {} + if node.translation and keys.origin and #brushes == 0 then + local t = node.translation + keys = Types.object(table.clone(keys), Types.keys(keys)) + keys.origin = fmtNum(t[1]) .. " " .. fmtNum(t[2]) .. " " .. fmtNum(t[3]) + end + if valve then + local conv: { Parse.Brush } = {} + for _, b in brushes do + if b.faces then + local nb = table.clone(b) + local faces = {} + for i, f in b.faces do + faces[i] = toValve(f) + end + nb.faces = faces + table.insert(conv, nb) + else + table.insert(conv, b) + end + end + brushes = conv + if #ents == 0 and keys.mapversion ~= "220" then + keys = Types.object(table.clone(keys), Types.keys(keys)) + Types.set(keys, "mapversion", "220") + end + end + table.insert(ents, { keys = keys, brushes = brushes }) + end + end + if #ents == 0 then + return nil, Err.new(Err.ARG, "no map entities (nodes with extras.keys, as model/map loads them)") + end + local src: any = scene.meta and scene.meta.source + local fromMap = type(src) == "table" and src.format == "map" + local text, err = Write.text({ + entities = ents :: { Parse.Entity }, + game = if fromMap then src.game else nil, + mapFormat = if valve then "Valve" elseif fromMap then src.mapFormat else nil, + comments = {}, + }) + if not text then + return nil, Err.new(Err.ARG, err or "bad entity") + end + return buffer.fromstring(text), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- the entities as parsed: { entities = { { keys, brushes } }, game, mapFormat } +function Map.parse(src: buffer | string): (Parse.Map?, Err.Err?) + local text = if type(src) == "buffer" then buffer.tostring(src) elseif type(src) == "string" then src else nil + if not text then + return nil, Err.new(Err.ARG, "expected a buffer or a string") + end + local m, msg, at = Parse.parse(text) + if not m then + return nil, Err.from(msg, at) + end + return m, nil +end + +function Map.write(m: Parse.Map): (string?, Err.Err?) + if type(m) ~= "table" or type(m.entities) ~= "table" then + return nil, Err.new(Err.ARG, "expected { entities = ... }") + end + local text, err = Write.text(m) + if not text then + return nil, Err.new(Err.ARG, err or "bad entity") + end + return text, nil +end + +-- a parsed face -> its Brush face (plane and projection): Brush.uv / Brush.polygons take it +function Map.face(f: Parse.Face): Brush.Face? + return Build.face(f) +end + +return Map +end +__FILES["model/map/Build"] = function() + +-- model/map/Build: parsed entities -> Scene: brushes through codecs/model/Brush, patches through codecs/model/Patch, +-- a mesh per entity with brushes, a primitive per texture, entities as nodes (keys in extras), z up, map units. +local Types = __include("Types") +local Brush = __include("codecs/model/Brush") +local Patch = __include("codecs/model/Patch") +local Parse = __include("model/map/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +type Options = { + variant: string, -- "quake" | "valve220" | "quake2" | "quake3" + size: (name: string) -> (number, number, boolean), -- width, height, known + hull: boolean?, + merge: boolean?, + epsilon: number?, + patchLevel: number?, + skip: { string }?, + maxPolygons: number?, +} + +function Build.face(f: Parse.Face): Brush.Face? + local p = f.points + local plane = Brush.planeFromPoints({ p[1], p[2], p[3] }, { p[4], p[5], p[6] }, { p[7], p[8], p[9] }) + if not plane then + return nil + end + local out: Brush.Face = { plane = plane, texture = f.texture } + if f.matrix then + out.bp = f.matrix + elseif f.u and f.v then + local sc = f.scale or { 1, 1 } + out.vecs = Brush.valveVecs(f.u, f.v, sc[1], sc[2]) + else + local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 } + out.vecs = Brush.quakeVecs(plane, o[1], o[2], f.rotation or 0, sc[1], sc[2]) + end + return out +end + +type Acc = { pos: { number }, nrm: { number }, uv: { number }, idx: { number } } + +local function patchPrim(b: Parse.Brush, level: number, acc: Acc): boolean + local size, pts = b.size :: { number }, b.points :: { number } + local w: number, h: number = size[1] :: number, size[2] :: number + if not Patch.valid(w, h, #pts // 5) then + return false + end + -- file order is column by column (q3map2 ParsePatch: verts[i * width + j] for column j, point i) + local ctrl = table.create(w * h * 5, 0) :: { number } + for j = 0, w - 1 do + for i = 0, h - 1 do + table.move(pts, (j * h + i) * 5 + 1, (j * h + i) * 5 + 5, (i * w + j) * 5 + 1, ctrl) + end + end + local params: { number } = b.params or {} + local explicit = b.type == "patchDef3" + local lu: number = if explicit then math.max(1, params[1] or 1) else level + local lv: number = if explicit then math.max(1, params[2] or 1) else level + local g, gw, gh = Patch.grid(ctrl, w, h, 5, lu, lv) + if not g then + return false + end + local nrm = Patch.normals(g, 5, gw, gh) + local base = #acc.pos // 3 + for k = 0, gw * gh - 1 do + local o = k * 5 + table.insert(acc.pos, g[o + 1]) + table.insert(acc.pos, g[o + 2]) + table.insert(acc.pos, g[o + 3]) + table.insert(acc.uv, g[o + 4]) + table.insert(acc.uv, g[o + 5]) + table.insert(acc.nrm, nrm[k * 3 + 1]) + table.insert(acc.nrm, nrm[k * 3 + 2]) + table.insert(acc.nrm, nrm[k * 3 + 3]) + end + for _, v in Patch.triangles(gw, gh) do + table.insert(acc.idx, base + v) + end + return true +end + +local function primitive(a: Acc): Types.Primitive + local nv, ni = #a.pos // 3, #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + return { + attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }, + indices = Scene.accessor(ib, "u32", 1, ni), + mode = "triangles", + } +end + +local function vec3(s: string?): { number }? + if not s then + return nil + end + local x, y, z = string.match(s, "^%s*(%S+)%s+(%S+)%s+(%S+)") + local a, b, c = tonumber(x), tonumber(y), tonumber(z) + if a and b and c then + return { a, b, c } + end + return nil +end + +function Build.scene(map: Parse.Map, o: Options): (Types.Scene?, string?) + local scene = Scene.new() + scene.meta.up = "z" + local skip: { [string]: boolean } = {} + for _, n in o.skip or {} do + skip[string.lower(n)] = true + end + local matOf: { [string]: number } = {} + local function material(name: string): number + local m = matOf[name] + if m then + return m + end + local w, h, known = o.size(name) + local uri = name + if o.variant == "quake2" then + uri = "textures/" .. name .. ".wal" + elseif o.variant == "quake3" then + uri = "textures/" .. name + end + table.insert(scene.textures, { name = name, uri = uri }) + local mat = Scene.material(name) + mat.metallic = 0 + mat.baseColorTexture = { texture = #scene.textures } + mat.extras = { map = { width = w, height = h, sizeKnown = known } } + table.insert(scene.materials, mat) + matOf[name] = #scene.materials + return #scene.materials + end + local root: Types.Node = { name = "map", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local skipped = { faces = 0, patches = 0 } + local counts = { brushes = 0, patches = 0 } + local entities: { { [string]: string } } = {} + local polyTotal = 0 + for ei, ent in map.entities do + local keys = ent.keys + table.insert(entities, keys) + local node: Types.Node = { name = keys.targetname or keys.classname or ("entity " .. (ei - 1)), children = {}, + extras = { classname = keys.classname, keys = keys, brushes = ent.brushes, entity = ei - 1 } } + local brushes: { { Brush.Face } } = {} + local patchAcc: { [string]: Acc } = {} + local patchOrder: { string } = {} + for _, b in ent.brushes do + if b.faces then + counts.brushes += 1 + local faces: { Brush.Face } = {} + for _, f in b.faces do + local bf = Build.face(f) + if bf then + table.insert(faces, bf) + else + skipped.faces += 1 + end + end + table.insert(brushes, faces) + else + counts.patches += 1 + local tex = b.texture or "" + if not skip[string.lower(tex)] then + local acc = patchAcc[tex] + if not acc then + acc = { pos = {}, nrm = {}, uv = {}, idx = {} } + patchAcc[tex] = acc + table.insert(patchOrder, tex) + end + if not patchPrim(b, o.patchLevel or 4, acc :: Acc) then + skipped.patches += 1 + end + end + end + end + local prims: { Types.Primitive } = {} + if #brushes > 0 then + local polys, err = Brush.polygons(brushes, { hull = o.hull, merge = o.merge, epsilon = o.epsilon, maxPolygons = o.maxPolygons }) + if not polys then + return nil, err + end + polyTotal += #polys + if polyTotal > (o.maxPolygons or 2 ^ 20) then + return nil, "limit: too many polygons" + end + local kept: { Brush.Polygon } = {} + for _, p in polys do + local t = brushes[p.brush][p.face].texture or "" + if not skip[string.lower(t)] then + table.insert(kept, p) + end + end + local built = Brush.primitives(kept, brushes, function(name: string): (number, number) + local m = scene.materials[material(name)] + local e = (m.extras :: any).map + return e.width, e.height + end) + for _, bt in built do + bt.primitive.material = material(bt.texture) + table.insert(prims, bt.primitive) + end + end + for _, tex in patchOrder do + local acc = patchAcc[tex] + if #acc.idx > 0 then + local prim = primitive(acc) + prim.material = material(tex) + table.insert(prims, prim) + end + end + if #prims > 0 then + table.insert(scene.meshes, { name = node.name, primitives = prims }) + node.mesh = #scene.meshes + elseif #ent.brushes == 0 then + node.translation = vec3(keys.origin) + end + table.insert(scene.nodes, node) + table.insert(root.children, #scene.nodes) + end + scene.meta.entities = entities + scene.meta.skipped = skipped + scene.meta.counts = counts + return scene, nil +end + +return Build +end +__FILES["model/map/Parse"] = function() + +-- model/map/Parse: .map text -> entities (key / value pairs in order, brushes and patches as written). Grammar of the +-- Quake / Quake II / Half-Life (Valve 220) / Quake III editors (qbsp / q3map2 map parsers; no code taken). +local Types = __include("Types") + +local Parse = {} + +type Face = { + points: { number }, -- 3 points: x, y, z each + texture: string, + offset: { number }?, -- Quake standard: x, y offset + rotation: number?, -- standard / Valve 220 (degrees) + scale: { number }?, -- standard / Valve 220 + u: { number }?, -- Valve 220: axis x, y, z, offset + v: { number }?, + matrix: { { number } }?, -- Quake III brush primitives: 2 x 3 + flags: { number }?, -- trailing numbers: Quake II / III contents, surface flags, value (Hexen II: light) +} +type Brush = { + type: string, -- "brush" | "brushDef" | "patchDef2" | "patchDef3" + faces: { Face }?, + texture: string?, -- patches + size: { number }?, -- patches: width, height (columns, points per column as written) + params: { number }?, -- patches: the header numbers after width, height + points: { number }?, -- patches: 5 numbers (x, y, z, s, t) per control point, in file order (column by column) +} +type Entity = { keys: { [string]: string }, brushes: { Brush } } -- keys: an ordered object (Types.object) +type Map = { entities: { Entity }, game: string?, mapFormat: string?, comments: { string } } + +type St = { s: string, pos: number, n: number, comments: { string } } + +local function skip(st: St) + local s = st.s + while true do + local p = string.find(s, "[^%s]", st.pos) + if not p then + st.pos = st.n + 1 + return + end + if string.sub(s, p, p + 1) == "//" then + local e = string.find(s, "\n", p, true) or st.n + table.insert(st.comments, (string.gsub(string.sub(s, p + 2, e), "^%s*(.-)%s*$", "%1"))) + st.pos = e + 1 + else + st.pos = p + return + end + end +end + +local function peek(st: St): string + skip(st) + return string.sub(st.s, st.pos, st.pos) +end + +local function expect(st: St, c: string): string? + if peek(st) ~= c then + return "expected '" .. c .. "' at " .. (st.pos - 1) + end + st.pos += 1 + return nil +end + +local function word(st: St): string? + skip(st) + local a, b = string.find(st.s, "^[^%s]+", st.pos) + if not a then + return nil + end + st.pos = (b :: number) + 1 + return string.sub(st.s, a, b) +end + +local function number(st: St): number? + skip(st) + local a, b = string.find(st.s, "^[^%s%(%)%[%]{}]+", st.pos) + if not a then + return nil + end + local v = tonumber(string.sub(st.s, a, b)) + if v then + st.pos = (b :: number) + 1 + end + return v +end + +local function quoted(st: St): string? + if peek(st) ~= '"' then + return nil + end + local e = string.find(st.s, '"', st.pos + 1, true) + if not e then + return nil + end + local v = string.sub(st.s, st.pos + 1, e - 1) + st.pos = e + 1 + return v +end + +local function numbers(st: St, n: number, out: { number }): string? + for _ = 1, n do + local v = number(st) + if not v then + return "expected a number at " .. (st.pos - 1) + end + table.insert(out, v) + end + return nil +end + +local function vec(st: St, n: number, open: string, close: string): ({ number }?, string?) + local e = expect(st, open) + if e then + return nil, e + end + local out = {} + e = numbers(st, n, out) + if e then + return nil, e + end + e = expect(st, close) + if e then + return nil, e + end + return out, nil +end + +local function trailing(st: St): { number }? + local out: { number } = {} + while true do + local c = peek(st) + if not string.match(c, "[%d%-%+%.]") then + break + end + local v = number(st) + if not v then + break + end + table.insert(out, v) + end + return if #out > 0 then out else nil +end + +local function plane(st: St): ({ number }?, string?) + local pts: { number } = {} + for _ = 1, 3 do + local p, e = vec(st, 3, "(", ")") + if not p then + return nil, e + end + table.move(p, 1, 3, #pts + 1, pts) + end + return pts, nil +end + +local function face(st: St, bp: boolean): (Face?, string?) + local pts, e = plane(st) + if not pts then + return nil, e + end + local f: Face = { points = pts, texture = "" } + if bp then + e = expect(st, "(") + if e then + return nil, e + end + local r1, e1 = vec(st, 3, "(", ")") + if not r1 then + return nil, e1 + end + local r2, e2 = vec(st, 3, "(", ")") + if not r2 then + return nil, e2 + end + e = expect(st, ")") + if e then + return nil, e + end + f.matrix = { r1, r2 } + end + local tex = word(st) + if not tex then + return nil, "expected a texture name at " .. (st.pos - 1) + end + f.texture = tex + if not bp then + if peek(st) == "[" then + local u, eu = vec(st, 4, "[", "]") + if not u then + return nil, eu + end + local v, ev = vec(st, 4, "[", "]") + if not v then + return nil, ev + end + local rest = {} + e = numbers(st, 3, rest) + if e then + return nil, e + end + f.u, f.v, f.rotation, f.scale = u, v, rest[1], { rest[2], rest[3] } + else + local rest = {} + e = numbers(st, 5, rest) + if e then + return nil, e + end + f.offset, f.rotation, f.scale = { rest[1], rest[2] }, rest[3], { rest[4], rest[5] } + end + end + f.flags = trailing(st) + return f, nil +end + +local function patch(st: St, kind: string, maxPoints: number): (Brush?, string?) + local e = expect(st, "{") + if e then + return nil, e + end + local tex = word(st) + if not tex then + return nil, "expected a patch texture" + end + local hn = if kind == "patchDef3" then 7 else 5 + local head, eh = vec(st, hn, "(", ")") + if not head then + return nil, eh + end + local w, h = head[1], head[2] + if w ~= math.floor(w) or h ~= math.floor(h) or w < 1 or h < 1 or w * h > maxPoints then + return nil, "bad patch size " .. w .. " x " .. h + end + local pts: { number } = {} + e = expect(st, "(") + if e then + return nil, e + end + for _ = 1, w do + e = expect(st, "(") + if e then + return nil, e + end + for _ = 1, h do + local p, ep = vec(st, 5, "(", ")") + if not p then + return nil, ep + end + table.move(p, 1, 5, #pts + 1, pts) + end + e = expect(st, ")") + if e then + return nil, e + end + end + e = expect(st, ")") + if e then + return nil, e + end + e = expect(st, "}") + if e then + return nil, e + end + return { type = kind, texture = tex, size = { w, h }, params = { table.unpack(head, 3) }, points = pts }, nil +end + +local function brush(st: St, maxPoints: number): (Brush?, string?) + local c = peek(st) + if c == "(" then + local faces: { Face } = {} + while peek(st) == "(" do + local f, e = face(st, false) + if not f then + return nil, e + end + table.insert(faces, f) + end + local e = expect(st, "}") + if e then + return nil, e + end + return { type = "brush", faces = faces }, nil + end + if c == "}" then + st.pos += 1 + return { type = "brush", faces = {} }, nil + end + local kw = word(st) + local out: any, err: string? + if kw == "brushDef" then + local e = expect(st, "{") + if e then + return nil, e + end + local faces: { Face } = {} + while peek(st) == "(" do + local f, ef = face(st, true) + if not f then + return nil, ef + end + table.insert(faces, f) + end + e = expect(st, "}") + if e then + return nil, e + end + out = { type = "brushDef", faces = faces } + elseif kw == "patchDef2" or kw == "patchDef3" then + out, err = patch(st, kw, maxPoints) + if not out then + return nil, err + end + elseif kw == "brushDef3" then + return nil, "unsupported: Doom 3 / Quake 4 brushDef3" + else + return nil, "unexpected '" .. tostring(kw) .. "' in a brush at " .. (st.pos - 1) + end + local e = expect(st, "}") + if e then + return nil, e + end + return out, nil +end + +function Parse.parse(s: string, maxBrushes: number?): (Map?, string?, number?) + local st: St = { s = s, pos = 1, n = #s, comments = {} } + if string.sub(s, 1, 3) == "\239\187\191" then + st.pos = 4 + end + local limit = maxBrushes or 2 ^ 20 + local count = 0 + local ents: { Entity } = {} + while peek(st) ~= "" do + local at = st.pos - 1 + local e = expect(st, "{") + if e then + return nil, e, at + end + local keys: { [string]: string } = {} + local order: { string } = {} + local brushes: { Brush } = {} + while true do + local c = peek(st) + if c == "}" then + st.pos += 1 + break + elseif c == '"' then + local k = quoted(st) + local v = quoted(st) + if not k or not v then + return nil, "bad key / value at " .. (st.pos - 1), st.pos - 1 + end + if keys[k] == nil then + table.insert(order, k) + end + keys[k] = v + elseif c == "{" then + st.pos += 1 + local b, eb = brush(st, limit) + if not b then + return nil, eb, st.pos - 1 + end + count += 1 + if count > limit then + return nil, "limit: too many brushes", st.pos - 1 + end + table.insert(brushes, b) + elseif c == "" then + return nil, "truncated entity", st.pos - 1 + else + return nil, "unexpected '" .. c .. "' in an entity at " .. (st.pos - 1), st.pos - 1 + end + end + table.insert(ents, { keys = Types.object(keys, order) :: { [string]: string }, brushes = brushes }) + end + local game, fmt + for _, c in st.comments do + game = game or string.match(c, "^Game:%s*(.-)%s*$") + fmt = fmt or string.match(c, "^Format:%s*(.-)%s*$") + end + return { entities = ents, game = game, mapFormat = fmt, comments = st.comments }, nil, nil +end + +return Parse +end +__FILES["model/map/Write"] = function() + +-- model/map/Write: entities (model/map/Parse's layout) -> .map text in the editors' layout (TrenchBroom / Radiant: +-- one face per line, numbers in their shortest exact form). +local Types = __include("Types") +local Parse = __include("model/map/Parse") + +local Write = {} + +function Write.num(x: number): string + if x ~= x or x == math.huge or x == -math.huge then + return "0" + end + if x == math.floor(x) and math.abs(x) < 2 ^ 53 then + return string.format("%d", x) + end + for p = 6, 17 do + local s = string.format("%." .. p .. "g", x) + if tonumber(s) == x then + return s + end + end + return string.format("%.17g", x) +end + +local function nums(t: { number }, a: number, b: number): string + local out = table.create(b - a + 1) :: { string } + for i = a, b do + out[#out + 1] = Write.num(t[i] or 0) + end + return table.concat(out, " ") +end + +local function faceLine(f: Parse.Face, bp: boolean): (string?, string?) + local p = f.points + if type(p) ~= "table" or #p < 9 or type(f.texture) ~= "string" or f.texture == "" or string.find(f.texture, "%s") then + return nil, "a face needs 9 point numbers and a texture name without spaces" + end + local parts: { string } = { "( " .. nums(p, 1, 3) .. " ) ( " .. nums(p, 4, 6) .. " ) ( " .. nums(p, 7, 9) .. " )" } + if bp then + local m = f.matrix + if not m or not m[1] or not m[2] then + return nil, "a brushDef face needs a texture matrix" + end + table.insert(parts, "( ( " .. nums(m[1], 1, 3) .. " ) ( " .. nums(m[2], 1, 3) .. " ) )") + table.insert(parts, f.texture) + elseif f.u and f.v then + local sc = f.scale or { 1, 1 } + table.insert(parts, f.texture) + table.insert(parts, "[ " .. nums(f.u, 1, 4) .. " ] [ " .. nums(f.v, 1, 4) .. " ] " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2)) + else + local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 } + table.insert(parts, f.texture) + table.insert(parts, nums(o, 1, 2) .. " " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2)) + end + if f.flags and #f.flags > 0 then + table.insert(parts, nums(f.flags, 1, #f.flags)) + end + return table.concat(parts, " "), nil +end + +local function patchText(b: Parse.Brush, out: { string }): string? + local size, pts = b.size, b.points + if not size or not pts or type(b.texture) ~= "string" then + return "a patch needs a texture, a size and control points" + end + local w, h = size[1], size[2] + if #pts < w * h * 5 then + return "a patch needs width * height * 5 control numbers" + end + local params = b.params or {} + local nParams = if b.type == "patchDef3" then 5 else 3 + table.insert(out, b.type) + table.insert(out, "{") + table.insert(out, b.texture) + table.insert(out, "( " .. Write.num(w) .. " " .. Write.num(h) .. " " .. nums(params, 1, nParams) .. " )") + table.insert(out, "(") + for i = 0, w - 1 do + local row = { "(" } + for j = 0, h - 1 do + local o = (i * h + j) * 5 + table.insert(row, "( " .. nums(pts, o + 1, o + 5) .. " )") + end + table.insert(row, ")") + table.insert(out, table.concat(row, " ")) + end + table.insert(out, ")") + table.insert(out, "}") + return nil +end + +function Write.text(map: Parse.Map): (string?, string?) + local out: { string } = {} + if map.game then + table.insert(out, "// Game: " .. map.game) + end + if map.mapFormat then + table.insert(out, "// Format: " .. map.mapFormat) + end + for ei, ent in map.entities do + table.insert(out, "// entity " .. (ei - 1)) + table.insert(out, "{") + for _, k in Types.keys(ent.keys) do + local v = ent.keys[k] + if v ~= nil then + if string.find(k, '"', 1, true) or string.find(tostring(v), '"', 1, true) or string.find(k, "[\r\n]") or string.find(tostring(v), "[\r\n]") then + return nil, "keys and values cannot hold quotes or line breaks: " .. k + end + table.insert(out, '"' .. k .. '" "' .. tostring(v) .. '"') + end + end + for bi, b in ent.brushes or {} do + table.insert(out, "// brush " .. (bi - 1)) + table.insert(out, "{") + if b.type == "patchDef2" or b.type == "patchDef3" then + local e = patchText(b, out) + if e then + return nil, e + end + else + local bp = b.type == "brushDef" + if bp then + table.insert(out, "brushDef") + table.insert(out, "{") + end + for _, f in b.faces or {} do + local line, e = faceLine(f, bp) + if not line then + return nil, e + end + table.insert(out, line) + end + if bp then + table.insert(out, "}") + end + end + table.insert(out, "}") + end + table.insert(out, "}") + end + table.insert(out, "") + return table.concat(out, "\n"), nil +end + +return Write +end __FILES["model/mca"] = function() -- model/mca: Minecraft Anvil region files (wiki "Region file format", "Chunk format"), read-only. Supports: gzip, zlib, diff --git a/build/Rosetta.luau.linemap.json b/build/Rosetta.luau.linemap.json index cdbb126..40498ac 100644 --- a/build/Rosetta.luau.linemap.json +++ b/build/Rosetta.luau.linemap.json @@ -1,544 +1,553 @@ [ [27, "src/Rosetta/init.luau"], [871, "src/Rosetta/Registry.luau"], -[3004, "src/Rosetta/Types.luau"], -[4087, "src/Rosetta/archive/7z/init.luau"], -[4472, "src/Rosetta/archive/7z/Header.luau"], -[4999, "src/Rosetta/archive/adf/init.luau"], -[5281, "src/Rosetta/archive/applesingle/init.luau"], -[5467, "src/Rosetta/archive/ar/init.luau"], -[5870, "src/Rosetta/archive/arj/init.luau"], -[6080, "src/Rosetta/archive/binhex/init.luau"], -[6329, "src/Rosetta/archive/br/init.luau"], -[6404, "src/Rosetta/archive/bz2/init.luau"], -[6468, "src/Rosetta/archive/cab/init.luau"], -[6881, "src/Rosetta/archive/cab/Sum.luau"], -[6922, "src/Rosetta/archive/cpio/init.luau"], -[7090, "src/Rosetta/archive/d64/init.luau"], -[7504, "src/Rosetta/archive/fat/init.luau"], -[7626, "src/Rosetta/archive/grp/init.luau"], -[7740, "src/Rosetta/archive/gzip/init.luau"], -[7925, "src/Rosetta/archive/iso/init.luau"], -[7997, "src/Rosetta/archive/lha/init.luau"], -[8422, "src/Rosetta/archive/lz4/init.luau"], -[8766, "src/Rosetta/archive/macbinary/init.luau"], -[8964, "src/Rosetta/archive/mpq/init.luau"], -[9370, "src/Rosetta/archive/mpq/Crypt.luau"], -[9435, "src/Rosetta/archive/pak/init.luau"], -[9569, "src/Rosetta/archive/rpm/init.luau"], -[9893, "src/Rosetta/archive/tar/init.luau"], -[10011, "src/Rosetta/archive/unitypackage/init.luau"], -[10248, "src/Rosetta/archive/uu/init.luau"], -[10518, "src/Rosetta/archive/vpk/init.luau"], -[10829, "src/Rosetta/archive/wad/init.luau"], -[11279, "src/Rosetta/archive/wad/Map.luau"], -[11709, "src/Rosetta/archive/wad/Picture.luau"], -[11811, "src/Rosetta/archive/xz/init.luau"], -[11911, "src/Rosetta/archive/yenc/init.luau"], -[12183, "src/Rosetta/archive/z/init.luau"], -[12279, "src/Rosetta/archive/zip/init.luau"], -[12498, "src/Rosetta/archive/zoo/init.luau"], -[12694, "src/Rosetta/archive/zst/init.luau"], -[12758, "src/Rosetta/audio/aac/init.luau"], -[12964, "src/Rosetta/audio/ac3/init.luau"], -[13110, "src/Rosetta/audio/adpcm/init.luau"], -[13255, "src/Rosetta/audio/adx/init.luau"], -[13486, "src/Rosetta/audio/aiff/init.luau"], -[13877, "src/Rosetta/audio/ape/init.luau"], -[14005, "src/Rosetta/audio/au/init.luau"], -[14166, "src/Rosetta/audio/brstm/init.luau"], -[14457, "src/Rosetta/audio/caf/init.luau"], -[15119, "src/Rosetta/audio/flac/init.luau"], -[15267, "src/Rosetta/audio/flac/Meta.luau"], -[15489, "src/Rosetta/audio/flac/Stream.luau"], -[15859, "src/Rosetta/audio/m4a/init.luau"], -[16193, "src/Rosetta/audio/mp3/init.luau"], -[16453, "src/Rosetta/audio/mp3/Index.luau"], -[16644, "src/Rosetta/audio/mp3/Stream.luau"], -[16871, "src/Rosetta/audio/mp3/Tags.luau"], -[17183, "src/Rosetta/audio/mpc/init.luau"], -[17277, "src/Rosetta/audio/opus/init.luau"], -[17655, "src/Rosetta/audio/opus/Encode.luau"], -[17766, "src/Rosetta/audio/qoa/init.luau"], -[17946, "src/Rosetta/audio/tta/init.luau"], -[18064, "src/Rosetta/audio/vag/init.luau"], -[18287, "src/Rosetta/audio/voc/init.luau"], -[18562, "src/Rosetta/audio/vorbis/init.luau"], -[19016, "src/Rosetta/audio/vorbis/Encode.luau"], -[19829, "src/Rosetta/audio/wav/init.luau"], -[20450, "src/Rosetta/audio/wav/Codecs.luau"], -[20616, "src/Rosetta/audio/wavpack/init.luau"], -[20823, "src/Rosetta/cad/step/init.luau"], -[21205, "src/Rosetta/cad/step/Brep.luau"], -[21440, "src/Rosetta/cad/step/Parse.luau"], -[21997, "src/Rosetta/cad/step/Write.luau"], -[22245, "src/Rosetta/codecs/audio/Aac/init.luau"], -[22564, "src/Rosetta/codecs/audio/Aac/Decode.luau"], -[23447, "src/Rosetta/codecs/audio/Aac/Tables.luau"], -[23782, "src/Rosetta/codecs/audio/Ac3/init.luau"], -[23941, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], -[24826, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], -[24927, "src/Rosetta/codecs/audio/Adpcm/init.luau"], -[25681, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], -[25983, "src/Rosetta/codecs/audio/Alac/init.luau"], -[26217, "src/Rosetta/codecs/audio/Alac/Decode.luau"], -[26636, "src/Rosetta/codecs/audio/Alac/Encode.luau"], -[27048, "src/Rosetta/codecs/audio/Ape/init.luau"], -[27263, "src/Rosetta/codecs/audio/Ape/Decode.luau"], -[28024, "src/Rosetta/codecs/audio/ApeTag.luau"], -[28121, "src/Rosetta/codecs/audio/Flac/init.luau"], -[28132, "src/Rosetta/codecs/audio/Flac/Encode.luau"], -[29081, "src/Rosetta/codecs/audio/Flac/Frame.luau"], -[29678, "src/Rosetta/codecs/audio/Hively/init.luau"], -[29874, "src/Rosetta/codecs/audio/Hively/Load.luau"], -[30123, "src/Rosetta/codecs/audio/Hively/Player.luau"], -[31081, "src/Rosetta/codecs/audio/Hively/Tables.luau"], -[31300, "src/Rosetta/codecs/audio/Mdct/init.luau"], -[31484, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], -[31693, "src/Rosetta/codecs/audio/MidiRender.luau"], -[32039, "src/Rosetta/codecs/audio/Mpa/init.luau"], -[32053, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], -[32112, "src/Rosetta/codecs/audio/Mpa/Core.luau"], -[33715, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], -[34007, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], -[34392, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], -[35033, "src/Rosetta/codecs/audio/Mpa/Header.luau"], -[35174, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], -[35400, "src/Rosetta/codecs/audio/Musepack/init.luau"], -[35745, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], -[36626, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], -[37004, "src/Rosetta/codecs/audio/Opus/init.luau"], -[37018, "src/Rosetta/codecs/audio/Opus/Celt.luau"], -[38865, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], -[39930, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], -[39990, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], -[40450, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], -[40787, "src/Rosetta/codecs/audio/Opus/Packet.luau"], -[41020, "src/Rosetta/codecs/audio/Opus/Silk.luau"], -[43056, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], -[43430, "src/Rosetta/codecs/audio/Pcm/init.luau"], -[43693, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], -[43990, "src/Rosetta/codecs/audio/Qoa/init.luau"], -[44272, "src/Rosetta/codecs/audio/Resample/init.luau"], -[44631, "src/Rosetta/codecs/audio/SoundFont/init.luau"], -[44685, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], -[44828, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], -[45341, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], -[46122, "src/Rosetta/codecs/audio/Stream.luau"], -[46283, "src/Rosetta/codecs/audio/Tracker/init.luau"], -[46765, "src/Rosetta/codecs/audio/Tracker/Load.luau"], -[47043, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], -[47212, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], -[47340, "src/Rosetta/codecs/audio/Tracker/Player.luau"], -[49328, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], -[49444, "src/Rosetta/codecs/audio/Tta/init.luau"], -[49561, "src/Rosetta/codecs/audio/Tta/Decode.luau"], -[49813, "src/Rosetta/codecs/audio/Vorbis/init.luau"], -[49826, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], -[50210, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], -[50776, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], -[51197, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], -[51236, "src/Rosetta/codecs/audio/VorbisComment.luau"], -[51288, "src/Rosetta/codecs/audio/WavPack/init.luau"], -[51510, "src/Rosetta/codecs/audio/WavPack/Block.luau"], -[52965, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], -[53028, "src/Rosetta/codecs/compress/Brotli/init.luau"], -[53115, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], -[54084, "src/Rosetta/codecs/compress/Brotli/Static.luau"], -[54952, "src/Rosetta/codecs/compress/Bzip2/init.luau"], -[55000, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], -[55516, "src/Rosetta/codecs/compress/Deflate/init.luau"], -[55842, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], -[56262, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], -[56697, "src/Rosetta/codecs/compress/Explode.luau"], -[56893, "src/Rosetta/codecs/compress/Lz4.luau"], -[57162, "src/Rosetta/codecs/compress/Lzh/init.luau"], -[57766, "src/Rosetta/codecs/compress/Lzma/init.luau"], -[58306, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], -[58344, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], -[58817, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], -[58993, "src/Rosetta/codecs/compress/Lzw/init.luau"], -[59261, "src/Rosetta/codecs/compress/Lzx.luau"], -[59695, "src/Rosetta/codecs/compress/PackBits.luau"], -[59785, "src/Rosetta/codecs/compress/Quantum.luau"], -[60022, "src/Rosetta/codecs/compress/UnixCompress.luau"], -[60326, "src/Rosetta/codecs/compress/Xxh32.luau"], -[60395, "src/Rosetta/codecs/compress/Zstd/init.luau"], -[60452, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], -[61410, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], -[61562, "src/Rosetta/codecs/entropy/Huffman.luau"], -[61844, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], -[61855, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], -[62069, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], -[62313, "src/Rosetta/codecs/font/Bitmap.luau"], -[62514, "src/Rosetta/codecs/font/Cff/init.luau"], -[63155, "src/Rosetta/codecs/font/GlyphNames.luau"], -[63305, "src/Rosetta/codecs/font/TrueType/init.luau"], -[63619, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], -[64011, "src/Rosetta/codecs/font/TrueType/Tables.luau"], -[64513, "src/Rosetta/codecs/image/Bcn/init.luau"], -[64620, "src/Rosetta/codecs/image/Bcn/Decode.luau"], -[65109, "src/Rosetta/codecs/image/Bcn/Encode.luau"], -[65538, "src/Rosetta/codecs/image/Blend.luau"], -[65917, "src/Rosetta/codecs/image/Dct/init.luau"], -[66298, "src/Rosetta/codecs/image/Etc.luau"], -[66596, "src/Rosetta/codecs/image/Half.luau"], -[66665, "src/Rosetta/codecs/image/Jpeg/init.luau"], -[67019, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], -[67427, "src/Rosetta/codecs/image/Jpeg/Color.luau"], -[67664, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], -[68424, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], -[69305, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], -[69751, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], -[69829, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], -[69896, "src/Rosetta/codecs/image/Pixels.luau"], -[70160, "src/Rosetta/codecs/image/Quantize/init.luau"], -[70619, "src/Rosetta/codecs/image/Raster.luau"], -[71316, "src/Rosetta/codecs/image/Texel.luau"], -[71689, "src/Rosetta/codecs/image/Texture.luau"], -[71834, "src/Rosetta/codecs/image/Vp8/init.luau"], -[71964, "src/Rosetta/codecs/image/Vp8/Decode.luau"], -[73920, "src/Rosetta/codecs/image/Vp8/Predict.luau"], -[74179, "src/Rosetta/codecs/image/Vp8/Tables.luau"], -[74428, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], -[74547, "src/Rosetta/codecs/image/Vp8L/init.luau"], -[74651, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], -[75504, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], -[76456, "src/Rosetta/codecs/image/Yuv.luau"], -[76724, "src/Rosetta/codecs/model/Draco/init.luau"], -[77056, "src/Rosetta/codecs/model/Draco/Attributes.luau"], -[77525, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], -[78714, "src/Rosetta/codecs/model/Draco/Int64.luau"], -[78863, "src/Rosetta/codecs/model/Draco/KdTree.luau"], -[79222, "src/Rosetta/codecs/model/Draco/Predict.luau"], -[80184, "src/Rosetta/codecs/model/Draco/Reader.luau"], -[80658, "src/Rosetta/codecs/model/Mat4.luau"], -[80917, "src/Rosetta/codecs/model/MeshFlatten.luau"], -[81445, "src/Rosetta/codecs/model/Minecraft/init.luau"], -[81997, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], -[82076, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], -[82183, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], -[82389, "src/Rosetta/codecs/model/Polygon.luau"], -[82623, "src/Rosetta/codecs/model/Rbx/init.luau"], -[82860, "src/Rosetta/codecs/model/Rbx/Binary.luau"], -[83614, "src/Rosetta/codecs/model/Rig.luau"], -[83857, "src/Rosetta/codecs/model/Sampler.luau"], -[84017, "src/Rosetta/codecs/model/Vrml/init.luau"], -[84165, "src/Rosetta/codecs/model/Vrml/Build.luau"], -[84739, "src/Rosetta/codecs/model/Vrml/Fields.luau"], -[84902, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], -[85651, "src/Rosetta/codecs/model/Vrml/Parse.luau"], -[86173, "src/Rosetta/codecs/model/Vrml/Write.luau"], -[86900, "src/Rosetta/codecs/model/Vrml/Xml.luau"], -[87132, "src/Rosetta/codecs/text/Json/init.luau"], -[87401, "src/Rosetta/codecs/text/Json/Decode.luau"], -[87815, "src/Rosetta/codecs/text/Json/Encode.luau"], -[88117, "src/Rosetta/codecs/text/Nbt/init.luau"], -[88470, "src/Rosetta/codecs/text/Nbt/Binary.luau"], -[89162, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], -[89802, "src/Rosetta/codecs/text/Nbt/Value.luau"], -[90040, "src/Rosetta/codecs/text/Text/init.luau"], -[90131, "src/Rosetta/codecs/text/Url/init.luau"], -[90336, "src/Rosetta/codecs/text/Xml/init.luau"], -[90739, "src/Rosetta/codecs/text/Xml/Parse.luau"], -[91479, "src/Rosetta/codecs/video/Dsp.luau"], -[92202, "src/Rosetta/codecs/video/H263/init.luau"], -[92358, "src/Rosetta/codecs/video/H263/Decoder.luau"], -[93216, "src/Rosetta/codecs/video/H263/Tables.luau"], -[93419, "src/Rosetta/codecs/video/H264/init.luau"], -[93792, "src/Rosetta/codecs/video/H264/Bitstream.luau"], -[94067, "src/Rosetta/codecs/video/H264/Cabac.luau"], -[95198, "src/Rosetta/codecs/video/H264/Cavlc.luau"], -[95966, "src/Rosetta/codecs/video/H264/Deblock.luau"], -[96224, "src/Rosetta/codecs/video/H264/Decoder.luau"], -[97233, "src/Rosetta/codecs/video/H264/Inter.luau"], -[97487, "src/Rosetta/codecs/video/H264/Intra.luau"], -[97894, "src/Rosetta/codecs/video/H264/Mb.luau"], -[98800, "src/Rosetta/codecs/video/H264/Params.luau"], -[99247, "src/Rosetta/codecs/video/H264/Slice.luau"], -[99498, "src/Rosetta/codecs/video/H264/Tables.luau"], -[99539, "src/Rosetta/codecs/video/H264/Transform.luau"], -[99704, "src/Rosetta/codecs/video/Legacy/init.luau"], -[99902, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], -[100199, "src/Rosetta/codecs/video/Legacy/Flic.luau"], -[100566, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], -[100684, "src/Rosetta/codecs/video/Legacy/Picture.luau"], -[100792, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], -[101065, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], -[101460, "src/Rosetta/codecs/video/Legacy/Smc.luau"], -[101637, "src/Rosetta/codecs/video/Mpeg1/init.luau"], -[101649, "src/Rosetta/codecs/video/Mpeg2/init.luau"], -[102016, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], -[103523, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], -[103662, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], -[103800, "src/Rosetta/codecs/video/Theora/init.luau"], -[104063, "src/Rosetta/codecs/video/Theora/Decoder.luau"], -[105327, "src/Rosetta/codecs/video/Theora/Header.luau"], -[105690, "src/Rosetta/codecs/video/Video/init.luau"], -[106247, "src/Rosetta/codecs/video/Video/Source.luau"], -[106532, "src/Rosetta/containers/Archive.luau"], -[106799, "src/Rosetta/containers/AudioWrap.luau"], -[107302, "src/Rosetta/containers/Avi/init.luau"], -[107854, "src/Rosetta/containers/Chunks.luau"], -[107989, "src/Rosetta/containers/Cpio.luau"], -[108417, "src/Rosetta/containers/Demux.luau"], -[108692, "src/Rosetta/containers/Ebml/init.luau"], -[109005, "src/Rosetta/containers/Fat.luau"], -[109693, "src/Rosetta/containers/Iso9660.luau"], -[110198, "src/Rosetta/containers/IsoBmff/init.luau"], -[110368, "src/Rosetta/containers/IsoBmff/Box.luau"], -[110556, "src/Rosetta/containers/IsoBmff/Demux.luau"], -[111401, "src/Rosetta/containers/IsoBmff/Meta.luau"], -[111922, "src/Rosetta/containers/IsoBmff/Mux.luau"], -[112438, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], -[112555, "src/Rosetta/containers/MacFile.luau"], -[112704, "src/Rosetta/containers/MpegEs.luau"], -[112870, "src/Rosetta/containers/MpegPs/init.luau"], -[113090, "src/Rosetta/containers/MpegTs/init.luau"], -[113882, "src/Rosetta/containers/Ogg/init.luau"], -[114307, "src/Rosetta/containers/Ogg/Mux.luau"], -[114502, "src/Rosetta/containers/Ogg/Page.luau"], -[114671, "src/Rosetta/containers/Riff/init.luau"], -[114988, "src/Rosetta/containers/Tar.luau"], -[115402, "src/Rosetta/containers/Zip/init.luau"], -[116034, "src/Rosetta/core/Adler32.luau"], -[116080, "src/Rosetta/core/Base64.luau"], -[116239, "src/Rosetta/core/Bits.luau"], -[116532, "src/Rosetta/core/Bytes.luau"], -[117059, "src/Rosetta/core/Crc16.luau"], -[117111, "src/Rosetta/core/Crc32.luau"], -[117223, "src/Rosetta/core/Err.luau"], -[117305, "src/Rosetta/core/Input.luau"], -[117381, "src/Rosetta/core/Md5.luau"], -[117540, "src/Rosetta/core/Sniff.luau"], -[117569, "src/Rosetta/data/cbor/init.luau"], -[117668, "src/Rosetta/data/cbor/Codec.luau"], -[118237, "src/Rosetta/data/csv/init.luau"], -[118549, "src/Rosetta/data/ini/init.luau"], -[118795, "src/Rosetta/data/json/init.luau"], -[118887, "src/Rosetta/data/msgpack/init.luau"], -[118976, "src/Rosetta/data/msgpack/Codec.luau"], -[119418, "src/Rosetta/data/nbt/init.luau"], -[119477, "src/Rosetta/data/plist/init.luau"], -[119783, "src/Rosetta/data/plist/Binary.luau"], -[120050, "src/Rosetta/data/snbt/init.luau"], -[120113, "src/Rosetta/data/toml/init.luau"], -[120180, "src/Rosetta/data/toml/Decode.luau"], -[120808, "src/Rosetta/data/toml/Encode.luau"], -[121017, "src/Rosetta/data/xml/init.luau"], -[121073, "src/Rosetta/data/yaml/init.luau"], -[121146, "src/Rosetta/data/yaml/Emit.luau"], -[121436, "src/Rosetta/data/yaml/Parse.luau"], -[122729, "src/Rosetta/font/bdf/init.luau"], -[123018, "src/Rosetta/font/bmfont/init.luau"], -[123445, "src/Rosetta/font/bmfont/Parse.luau"], -[123898, "src/Rosetta/font/eot/init.luau"], -[124130, "src/Rosetta/font/fon/init.luau"], -[124413, "src/Rosetta/font/hershey/init.luau"], -[124608, "src/Rosetta/font/pcf/init.luau"], -[124888, "src/Rosetta/font/psf/init.luau"], -[125208, "src/Rosetta/font/ttf/init.luau"], -[125259, "src/Rosetta/font/type1/init.luau"], -[125618, "src/Rosetta/font/type1/Charstring.luau"], -[125896, "src/Rosetta/font/woff/init.luau"], -[126028, "src/Rosetta/font/woff2/init.luau"], -[126085, "src/Rosetta/font/woff2/Rebuild.luau"], -[126625, "src/Rosetta/host/init.luau"], -[126670, "src/Rosetta/host/Love.luau"], -[126813, "src/Rosetta/host/LuaJIT.luau"], -[126863, "src/Rosetta/host/Luau.luau"], -[126886, "src/Rosetta/host/Roblox.luau"], -[127245, "src/Rosetta/image/ani/init.luau"], -[127425, "src/Rosetta/image/blp/init.luau"], -[127683, "src/Rosetta/image/bmp/init.luau"], -[128098, "src/Rosetta/image/dds/init.luau"], -[128581, "src/Rosetta/image/exr/init.luau"], -[129341, "src/Rosetta/image/exr/Codec.luau"], -[129452, "src/Rosetta/image/exr/Piz.luau"], -[129809, "src/Rosetta/image/gif/init.luau"], -[130325, "src/Rosetta/image/gif/Decode.luau"], -[130388, "src/Rosetta/image/hdr/init.luau"], -[130617, "src/Rosetta/image/hdr/Codec.luau"], -[130828, "src/Rosetta/image/icns/init.luau"], -[131159, "src/Rosetta/image/ico/init.luau"], -[131436, "src/Rosetta/image/ico/Dib.luau"], -[131531, "src/Rosetta/image/ilbm/init.luau"], -[131850, "src/Rosetta/image/jpeg/init.luau"], -[131986, "src/Rosetta/image/ktx/init.luau"], -[132646, "src/Rosetta/image/pcx/init.luau"], -[132910, "src/Rosetta/image/png/init.luau"], -[133490, "src/Rosetta/image/png/Apng.luau"], -[133570, "src/Rosetta/image/png/Decode.luau"], -[133810, "src/Rosetta/image/png/Encode.luau"], -[133965, "src/Rosetta/image/pnm/init.luau"], -[134343, "src/Rosetta/image/pnm/Codec.luau"], -[134620, "src/Rosetta/image/qoi/init.luau"], -[134742, "src/Rosetta/image/qoi/Codec.luau"], -[134892, "src/Rosetta/image/sgi/init.luau"], -[135177, "src/Rosetta/image/sunras/init.luau"], -[135423, "src/Rosetta/image/tga/init.luau"], -[135693, "src/Rosetta/image/tga/Codec.luau"], -[135845, "src/Rosetta/image/tiff/init.luau"], -[136672, "src/Rosetta/image/tiff/Pixels.luau"], -[137062, "src/Rosetta/image/tim/init.luau"], -[137304, "src/Rosetta/image/vtf/init.luau"], -[137539, "src/Rosetta/image/webp/init.luau"], -[138149, "src/Rosetta/image/webp/Alpha.luau"], -[138225, "src/Rosetta/image/webp/Anim.luau"], -[138380, "src/Rosetta/image/xbm/init.luau"], -[138541, "src/Rosetta/image/xpm/init.luau"], -[138809, "src/Rosetta/image/xpm/Names.luau"], -[138865, "src/Rosetta/layered/aseprite/init.luau"], -[139603, "src/Rosetta/layered/ora/init.luau"], -[139890, "src/Rosetta/layered/psd/init.luau"], -[140625, "src/Rosetta/layered/psd/Channels.luau"], -[140977, "src/Rosetta/model/3ds/init.luau"], -[141060, "src/Rosetta/model/3ds/Build.luau"], -[141707, "src/Rosetta/model/3ds/Read.luau"], -[142203, "src/Rosetta/model/3ds/Write.luau"], -[143008, "src/Rosetta/model/3mf/init.luau"], -[143090, "src/Rosetta/model/3mf/Read.luau"], -[143678, "src/Rosetta/model/3mf/Write.luau"], -[144083, "src/Rosetta/model/ase/init.luau"], -[144206, "src/Rosetta/model/ase/Build.luau"], -[144780, "src/Rosetta/model/ase/Parse.luau"], -[144849, "src/Rosetta/model/ase/Write.luau"], -[145312, "src/Rosetta/model/b3d/init.luau"], -[145367, "src/Rosetta/model/b3d/Read.luau"], -[145938, "src/Rosetta/model/bsp/init.luau"], -[146083, "src/Rosetta/model/bsp/Brush.luau"], -[146361, "src/Rosetta/model/bsp/Quake3.luau"], -[146616, "src/Rosetta/model/dae/init.luau"], -[146805, "src/Rosetta/model/dae/Math.luau"], -[146852, "src/Rosetta/model/dae/Read.luau"], -[148702, "src/Rosetta/model/dae/Write.luau"], -[149071, "src/Rosetta/model/fbx/init.luau"], -[149219, "src/Rosetta/model/fbx/Ascii.luau"], -[149489, "src/Rosetta/model/fbx/Binary.luau"], -[149944, "src/Rosetta/model/fbx/Read.luau"], -[151306, "src/Rosetta/model/fbx/Write.luau"], -[152291, "src/Rosetta/model/fbx/Xform.luau"], -[152332, "src/Rosetta/model/gltf/init.luau"], -[152569, "src/Rosetta/model/gltf/Pack.luau"], -[152638, "src/Rosetta/model/gltf/Read.luau"], -[153369, "src/Rosetta/model/gltf/Write.luau"], -[154049, "src/Rosetta/model/iqm/init.luau"], -[154125, "src/Rosetta/model/iqm/Read.luau"], -[154480, "src/Rosetta/model/iqm/Write.luau"], -[155167, "src/Rosetta/model/ldraw/init.luau"], -[155245, "src/Rosetta/model/ldraw/Colors.luau"], -[155563, "src/Rosetta/model/ldraw/Read.luau"], -[156140, "src/Rosetta/model/lwo/init.luau"], -[156216, "src/Rosetta/model/lwo/Build.luau"], -[156678, "src/Rosetta/model/lwo/Parse.luau"], -[157221, "src/Rosetta/model/mca/init.luau"], -[157563, "src/Rosetta/model/mca/Chunk.luau"], -[157696, "src/Rosetta/model/mca/Lz4Block.luau"], -[157766, "src/Rosetta/model/md2/init.luau"], -[157965, "src/Rosetta/model/md3/init.luau"], -[158193, "src/Rosetta/model/md5/init.luau"], -[158274, "src/Rosetta/model/md5/Read.luau"], -[158707, "src/Rosetta/model/mdl/init.luau"], -[158789, "src/Rosetta/model/mdl/HalfLife.luau"], -[159117, "src/Rosetta/model/mdl/Quake.luau"], -[159335, "src/Rosetta/model/ms3d/init.luau"], -[159407, "src/Rosetta/model/ms3d/Read.luau"], -[159853, "src/Rosetta/model/ms3d/Write.luau"], -[160322, "src/Rosetta/model/obj/init.luau"], -[161064, "src/Rosetta/model/obj/Mtl.luau"], -[161351, "src/Rosetta/model/off/init.luau"], -[161813, "src/Rosetta/model/ply/init.luau"], -[162918, "src/Rosetta/model/ply/Binary.luau"], -[163119, "src/Rosetta/model/pmx/init.luau"], -[163188, "src/Rosetta/model/pmx/Build.luau"], -[163484, "src/Rosetta/model/pmx/Pmd.luau"], -[163819, "src/Rosetta/model/pmx/Read.luau"], -[164223, "src/Rosetta/model/qb/init.luau"], -[164616, "src/Rosetta/model/rbxm/init.luau"], -[165208, "src/Rosetta/model/rbxmx/init.luau"], -[165861, "src/Rosetta/model/robloxmesh/init.luau"], -[166520, "src/Rosetta/model/robloxmesh/Parse.luau"], -[166977, "src/Rosetta/model/robloxmesh/Write.luau"], -[167086, "src/Rosetta/model/schematic/init.luau"], -[167407, "src/Rosetta/model/schematic/Common.luau"], -[167527, "src/Rosetta/model/schematic/Litematic.luau"], -[167738, "src/Rosetta/model/schematic/Mcedit.luau"], -[167982, "src/Rosetta/model/schematic/Sponge.luau"], -[168111, "src/Rosetta/model/smd/init.luau"], -[168178, "src/Rosetta/model/smd/Read.luau"], -[168447, "src/Rosetta/model/smd/Write.luau"], -[168690, "src/Rosetta/model/stl/init.luau"], -[169140, "src/Rosetta/model/stl/Decode.luau"], -[169214, "src/Rosetta/model/usda/init.luau"], -[169423, "src/Rosetta/model/usda/Build.luau"], -[170701, "src/Rosetta/model/usda/Parse.luau"], -[171499, "src/Rosetta/model/usda/Write.luau"], -[172316, "src/Rosetta/model/vox/init.luau"], -[173202, "src/Rosetta/model/vox/Grid.luau"], -[173259, "src/Rosetta/model/vrml/init.luau"], -[173325, "src/Rosetta/model/x/init.luau"], -[173455, "src/Rosetta/model/x/Build.luau"], -[174018, "src/Rosetta/model/x/Parse.luau"], -[174315, "src/Rosetta/model/x3d/init.luau"], -[174393, "src/Rosetta/music/669/init.luau"], -[174599, "src/Rosetta/music/ahx/init.luau"], -[174650, "src/Rosetta/music/far/init.luau"], -[174879, "src/Rosetta/music/hmp/init.luau"], -[175143, "src/Rosetta/music/hvl/init.luau"], -[175194, "src/Rosetta/music/it/init.luau"], -[175612, "src/Rosetta/music/it/Itsex.luau"], -[175728, "src/Rosetta/music/med/init.luau"], -[176375, "src/Rosetta/music/midi/init.luau"], -[176518, "src/Rosetta/music/midi/Smf.luau"], -[176929, "src/Rosetta/music/mod/init.luau"], -[177282, "src/Rosetta/music/mtm/init.luau"], -[177504, "src/Rosetta/music/mus/init.luau"], -[177661, "src/Rosetta/music/okt/init.luau"], -[177942, "src/Rosetta/music/ptm/init.luau"], -[178164, "src/Rosetta/music/s3m/init.luau"], -[178400, "src/Rosetta/music/sf2/init.luau"], -[178443, "src/Rosetta/music/stm/init.luau"], -[178674, "src/Rosetta/music/ult/init.luau"], -[178978, "src/Rosetta/music/umx/init.luau"], -[179194, "src/Rosetta/music/xm/init.luau"], -[179755, "src/Rosetta/music/xmi/init.luau"], -[179963, "src/Rosetta/ops/AudioOps.luau"], -[180412, "src/Rosetta/ops/ImageOps/init.luau"], -[181056, "src/Rosetta/ops/ImageOps/Kernels.luau"], -[181566, "src/Rosetta/ops/LayerOps.luau"], -[181659, "src/Rosetta/ops/MeshOps/init.luau"], -[182695, "src/Rosetta/ops/MeshOps/Greedy.luau"], -[182862, "src/Rosetta/ops/MusicOps.luau"], -[183210, "src/Rosetta/playlist/m3u/init.luau"], -[183563, "src/Rosetta/playlist/pls/init.luau"], -[183741, "src/Rosetta/playlist/xspf/init.luau"], -[183944, "src/Rosetta/subtitle/ass/init.luau"], -[184388, "src/Rosetta/subtitle/srt/init.luau"], -[184561, "src/Rosetta/subtitle/vtt/init.luau"], -[184764, "src/Rosetta/vector/svg/init.luau"], -[184850, "src/Rosetta/vector/svg/Parse.luau"], -[185596, "src/Rosetta/vector/svg/PathData.luau"], -[185964, "src/Rosetta/vector/svg/Render.luau"], -[186381, "src/Rosetta/vector/svg/Style.luau"], -[186753, "src/Rosetta/vector/svg/Write.luau"], -[186953, "src/Rosetta/vector/tiled/init.luau"], -[187133, "src/Rosetta/vector/tiled/Data.luau"], -[187284, "src/Rosetta/vector/tiled/Tmj.luau"], -[187915, "src/Rosetta/vector/tiled/Tmx.luau"], -[188527, "src/Rosetta/video/avi/init.luau"], -[188821, "src/Rosetta/video/fli/init.luau"], -[188972, "src/Rosetta/video/flv/init.luau"], -[189356, "src/Rosetta/video/flv/Amf.luau"], -[189514, "src/Rosetta/video/flv/Mux.luau"], -[189795, "src/Rosetta/video/h264/init.luau"], -[189934, "src/Rosetta/video/mkv/init.luau"], -[190090, "src/Rosetta/video/mkv/Mux.luau"], -[190369, "src/Rosetta/video/mkv/Parse.luau"], -[191090, "src/Rosetta/video/mp4/init.luau"], -[191418, "src/Rosetta/video/mpegps/init.luau"], -[191605, "src/Rosetta/video/mpegts/init.luau"], -[191843, "src/Rosetta/video/ogv/init.luau"], -[192238, "src/Rosetta/video/smk/init.luau"], -[192547, "src/Rosetta/video/smk/Audio.luau"], -[192667, "src/Rosetta/video/y4m/init.luau"] +[3052, "src/Rosetta/Types.luau"], +[4135, "src/Rosetta/archive/7z/init.luau"], +[4520, "src/Rosetta/archive/7z/Header.luau"], +[5047, "src/Rosetta/archive/adf/init.luau"], +[5329, "src/Rosetta/archive/applesingle/init.luau"], +[5515, "src/Rosetta/archive/ar/init.luau"], +[5918, "src/Rosetta/archive/arj/init.luau"], +[6128, "src/Rosetta/archive/binhex/init.luau"], +[6377, "src/Rosetta/archive/br/init.luau"], +[6452, "src/Rosetta/archive/bz2/init.luau"], +[6516, "src/Rosetta/archive/cab/init.luau"], +[6929, "src/Rosetta/archive/cab/Sum.luau"], +[6970, "src/Rosetta/archive/cpio/init.luau"], +[7138, "src/Rosetta/archive/d64/init.luau"], +[7552, "src/Rosetta/archive/fat/init.luau"], +[7674, "src/Rosetta/archive/grp/init.luau"], +[7788, "src/Rosetta/archive/gzip/init.luau"], +[7973, "src/Rosetta/archive/iso/init.luau"], +[8045, "src/Rosetta/archive/lha/init.luau"], +[8470, "src/Rosetta/archive/lz4/init.luau"], +[8814, "src/Rosetta/archive/macbinary/init.luau"], +[9012, "src/Rosetta/archive/mpq/init.luau"], +[9418, "src/Rosetta/archive/mpq/Crypt.luau"], +[9483, "src/Rosetta/archive/pak/init.luau"], +[9617, "src/Rosetta/archive/rpm/init.luau"], +[9941, "src/Rosetta/archive/tar/init.luau"], +[10059, "src/Rosetta/archive/uu/init.luau"], +[10329, "src/Rosetta/archive/vpk/init.luau"], +[10640, "src/Rosetta/archive/wad/init.luau"], +[11090, "src/Rosetta/archive/wad/Map.luau"], +[11520, "src/Rosetta/archive/wad/Picture.luau"], +[11622, "src/Rosetta/archive/wad2/init.luau"], +[11904, "src/Rosetta/archive/xz/init.luau"], +[12004, "src/Rosetta/archive/yenc/init.luau"], +[12276, "src/Rosetta/archive/z/init.luau"], +[12372, "src/Rosetta/archive/zip/init.luau"], +[12591, "src/Rosetta/archive/zoo/init.luau"], +[12787, "src/Rosetta/archive/zst/init.luau"], +[12851, "src/Rosetta/audio/aac/init.luau"], +[13057, "src/Rosetta/audio/ac3/init.luau"], +[13203, "src/Rosetta/audio/adpcm/init.luau"], +[13348, "src/Rosetta/audio/adx/init.luau"], +[13579, "src/Rosetta/audio/aiff/init.luau"], +[13970, "src/Rosetta/audio/ape/init.luau"], +[14098, "src/Rosetta/audio/au/init.luau"], +[14259, "src/Rosetta/audio/brstm/init.luau"], +[14550, "src/Rosetta/audio/caf/init.luau"], +[15212, "src/Rosetta/audio/flac/init.luau"], +[15360, "src/Rosetta/audio/flac/Meta.luau"], +[15582, "src/Rosetta/audio/flac/Stream.luau"], +[15952, "src/Rosetta/audio/m4a/init.luau"], +[16286, "src/Rosetta/audio/mp3/init.luau"], +[16546, "src/Rosetta/audio/mp3/Index.luau"], +[16737, "src/Rosetta/audio/mp3/Stream.luau"], +[16964, "src/Rosetta/audio/mp3/Tags.luau"], +[17276, "src/Rosetta/audio/mpc/init.luau"], +[17370, "src/Rosetta/audio/opus/init.luau"], +[17748, "src/Rosetta/audio/opus/Encode.luau"], +[17859, "src/Rosetta/audio/qoa/init.luau"], +[18039, "src/Rosetta/audio/tta/init.luau"], +[18157, "src/Rosetta/audio/vag/init.luau"], +[18380, "src/Rosetta/audio/voc/init.luau"], +[18655, "src/Rosetta/audio/vorbis/init.luau"], +[19109, "src/Rosetta/audio/vorbis/Encode.luau"], +[19922, "src/Rosetta/audio/wav/init.luau"], +[20543, "src/Rosetta/audio/wav/Codecs.luau"], +[20709, "src/Rosetta/audio/wavpack/init.luau"], +[20916, "src/Rosetta/cad/step/init.luau"], +[21298, "src/Rosetta/cad/step/Brep.luau"], +[21533, "src/Rosetta/cad/step/Parse.luau"], +[22090, "src/Rosetta/cad/step/Write.luau"], +[22338, "src/Rosetta/codecs/audio/Aac/init.luau"], +[22657, "src/Rosetta/codecs/audio/Aac/Decode.luau"], +[23540, "src/Rosetta/codecs/audio/Aac/Tables.luau"], +[23875, "src/Rosetta/codecs/audio/Ac3/init.luau"], +[24034, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], +[24919, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], +[25020, "src/Rosetta/codecs/audio/Adpcm/init.luau"], +[25774, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], +[26076, "src/Rosetta/codecs/audio/Alac/init.luau"], +[26310, "src/Rosetta/codecs/audio/Alac/Decode.luau"], +[26729, "src/Rosetta/codecs/audio/Alac/Encode.luau"], +[27141, "src/Rosetta/codecs/audio/Ape/init.luau"], +[27356, "src/Rosetta/codecs/audio/Ape/Decode.luau"], +[28117, "src/Rosetta/codecs/audio/ApeTag.luau"], +[28214, "src/Rosetta/codecs/audio/Flac/init.luau"], +[28225, "src/Rosetta/codecs/audio/Flac/Encode.luau"], +[29174, "src/Rosetta/codecs/audio/Flac/Frame.luau"], +[29771, "src/Rosetta/codecs/audio/Hively/init.luau"], +[29967, "src/Rosetta/codecs/audio/Hively/Load.luau"], +[30216, "src/Rosetta/codecs/audio/Hively/Player.luau"], +[31174, "src/Rosetta/codecs/audio/Hively/Tables.luau"], +[31393, "src/Rosetta/codecs/audio/Mdct/init.luau"], +[31577, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], +[31786, "src/Rosetta/codecs/audio/MidiRender.luau"], +[32132, "src/Rosetta/codecs/audio/Mpa/init.luau"], +[32146, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], +[32205, "src/Rosetta/codecs/audio/Mpa/Core.luau"], +[33808, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], +[34100, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], +[34485, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], +[35126, "src/Rosetta/codecs/audio/Mpa/Header.luau"], +[35267, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], +[35493, "src/Rosetta/codecs/audio/Musepack/init.luau"], +[35838, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], +[36719, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[37097, "src/Rosetta/codecs/audio/Opus/init.luau"], +[37111, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[38958, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[40023, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[40083, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[40543, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[40880, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[41113, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[43149, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[43523, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[43786, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[44083, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[44365, "src/Rosetta/codecs/audio/Resample/init.luau"], +[44724, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[44778, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[44921, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[45434, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[46215, "src/Rosetta/codecs/audio/Stream.luau"], +[46376, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[46858, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[47136, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[47305, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[47433, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[49421, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[49537, "src/Rosetta/codecs/audio/Tta/init.luau"], +[49654, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[49906, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[49919, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[50303, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[50869, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[51290, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[51329, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[51381, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[51603, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[53058, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[53121, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[53208, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[54177, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[55045, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[55093, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[55609, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[55935, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[56355, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[56790, "src/Rosetta/codecs/compress/Explode.luau"], +[56986, "src/Rosetta/codecs/compress/Lz4.luau"], +[57255, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[57859, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[58399, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[58437, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[58910, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[59086, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[59354, "src/Rosetta/codecs/compress/Lzx.luau"], +[59788, "src/Rosetta/codecs/compress/PackBits.luau"], +[59878, "src/Rosetta/codecs/compress/Quantum.luau"], +[60115, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[60419, "src/Rosetta/codecs/compress/Xxh32.luau"], +[60488, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[60545, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[61503, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[61655, "src/Rosetta/codecs/entropy/Huffman.luau"], +[61937, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[61948, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[62162, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[62406, "src/Rosetta/codecs/font/Bitmap.luau"], +[62607, "src/Rosetta/codecs/font/Cff/init.luau"], +[63248, "src/Rosetta/codecs/font/GlyphNames.luau"], +[63398, "src/Rosetta/codecs/font/TrueType/init.luau"], +[63712, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[64104, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[64606, "src/Rosetta/codecs/image/Bcn/init.luau"], +[64713, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[65202, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[65631, "src/Rosetta/codecs/image/Blend.luau"], +[66010, "src/Rosetta/codecs/image/Dct/init.luau"], +[66391, "src/Rosetta/codecs/image/Etc.luau"], +[66689, "src/Rosetta/codecs/image/Half.luau"], +[66758, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[67112, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[67520, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[67757, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[68517, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[69398, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[69844, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[69922, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[69989, "src/Rosetta/codecs/image/Miptex.luau"], +[70289, "src/Rosetta/codecs/image/Pixels.luau"], +[70609, "src/Rosetta/codecs/image/Quantize/init.luau"], +[71068, "src/Rosetta/codecs/image/Raster.luau"], +[71765, "src/Rosetta/codecs/image/Texel.luau"], +[72138, "src/Rosetta/codecs/image/Texture.luau"], +[72283, "src/Rosetta/codecs/image/Vp8/init.luau"], +[72413, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[74369, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[74628, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[74877, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[74996, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[75100, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[75953, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[76905, "src/Rosetta/codecs/image/Yuv.luau"], +[77173, "src/Rosetta/codecs/model/Brush.luau"], +[77813, "src/Rosetta/codecs/model/Draco/init.luau"], +[78145, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[78614, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[79803, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[79952, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[80311, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[81273, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[81747, "src/Rosetta/codecs/model/Mat4.luau"], +[82006, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[82534, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[83086, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[83165, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[83272, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[83478, "src/Rosetta/codecs/model/Patch.luau"], +[83602, "src/Rosetta/codecs/model/Polygon.luau"], +[83836, "src/Rosetta/codecs/model/Rbx/init.luau"], +[84073, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[84827, "src/Rosetta/codecs/model/Rig.luau"], +[85070, "src/Rosetta/codecs/model/Sampler.luau"], +[85230, "src/Rosetta/codecs/model/Vrml/init.luau"], +[85378, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[85952, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[86115, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[86864, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[87386, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[88113, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[88345, "src/Rosetta/codecs/text/Json/init.luau"], +[88614, "src/Rosetta/codecs/text/Json/Decode.luau"], +[89028, "src/Rosetta/codecs/text/Json/Encode.luau"], +[89330, "src/Rosetta/codecs/text/Nbt/init.luau"], +[89683, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[90375, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[91015, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[91253, "src/Rosetta/codecs/text/Text/init.luau"], +[91344, "src/Rosetta/codecs/text/Url/init.luau"], +[91549, "src/Rosetta/codecs/text/Xml/init.luau"], +[91952, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[92692, "src/Rosetta/codecs/video/Dsp.luau"], +[93415, "src/Rosetta/codecs/video/H263/init.luau"], +[93571, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[94429, "src/Rosetta/codecs/video/H263/Tables.luau"], +[94632, "src/Rosetta/codecs/video/H264/init.luau"], +[95005, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[95280, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[96411, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[97179, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[97437, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[98446, "src/Rosetta/codecs/video/H264/Inter.luau"], +[98700, "src/Rosetta/codecs/video/H264/Intra.luau"], +[99107, "src/Rosetta/codecs/video/H264/Mb.luau"], +[100013, "src/Rosetta/codecs/video/H264/Params.luau"], +[100460, "src/Rosetta/codecs/video/H264/Slice.luau"], +[100711, "src/Rosetta/codecs/video/H264/Tables.luau"], +[100752, "src/Rosetta/codecs/video/H264/Transform.luau"], +[100917, "src/Rosetta/codecs/video/Legacy/init.luau"], +[101115, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[101412, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[101779, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[101897, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[102005, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[102278, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[102673, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[102850, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[102862, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[103229, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[104736, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[104875, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[105013, "src/Rosetta/codecs/video/Theora/init.luau"], +[105276, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[106540, "src/Rosetta/codecs/video/Theora/Header.luau"], +[106903, "src/Rosetta/codecs/video/Video/init.luau"], +[107460, "src/Rosetta/codecs/video/Video/Source.luau"], +[107745, "src/Rosetta/containers/Archive.luau"], +[108012, "src/Rosetta/containers/AudioWrap.luau"], +[108515, "src/Rosetta/containers/Avi/init.luau"], +[109067, "src/Rosetta/containers/Chunks.luau"], +[109202, "src/Rosetta/containers/Cpio.luau"], +[109630, "src/Rosetta/containers/Demux.luau"], +[109905, "src/Rosetta/containers/Ebml/init.luau"], +[110218, "src/Rosetta/containers/Fat.luau"], +[110906, "src/Rosetta/containers/Iso9660.luau"], +[111411, "src/Rosetta/containers/IsoBmff/init.luau"], +[111581, "src/Rosetta/containers/IsoBmff/Box.luau"], +[111769, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[112614, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[113135, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[113651, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[113768, "src/Rosetta/containers/MacFile.luau"], +[113917, "src/Rosetta/containers/MpegEs.luau"], +[114083, "src/Rosetta/containers/MpegPs/init.luau"], +[114303, "src/Rosetta/containers/MpegTs/init.luau"], +[115095, "src/Rosetta/containers/Ogg/init.luau"], +[115520, "src/Rosetta/containers/Ogg/Mux.luau"], +[115715, "src/Rosetta/containers/Ogg/Page.luau"], +[115884, "src/Rosetta/containers/Riff/init.luau"], +[116201, "src/Rosetta/containers/Tar.luau"], +[116615, "src/Rosetta/containers/Zip/init.luau"], +[117247, "src/Rosetta/core/Adler32.luau"], +[117293, "src/Rosetta/core/Base64.luau"], +[117452, "src/Rosetta/core/Bits.luau"], +[117745, "src/Rosetta/core/Bytes.luau"], +[118272, "src/Rosetta/core/Crc16.luau"], +[118324, "src/Rosetta/core/Crc32.luau"], +[118436, "src/Rosetta/core/Err.luau"], +[118518, "src/Rosetta/core/Input.luau"], +[118594, "src/Rosetta/core/Md5.luau"], +[118753, "src/Rosetta/core/Sniff.luau"], +[118782, "src/Rosetta/data/cbor/init.luau"], +[118881, "src/Rosetta/data/cbor/Codec.luau"], +[119450, "src/Rosetta/data/csv/init.luau"], +[119762, "src/Rosetta/data/ini/init.luau"], +[120008, "src/Rosetta/data/json/init.luau"], +[120100, "src/Rosetta/data/msgpack/init.luau"], +[120189, "src/Rosetta/data/msgpack/Codec.luau"], +[120631, "src/Rosetta/data/nbt/init.luau"], +[120690, "src/Rosetta/data/plist/init.luau"], +[120996, "src/Rosetta/data/plist/Binary.luau"], +[121263, "src/Rosetta/data/q3shader/init.luau"], +[121502, "src/Rosetta/data/q3skin/init.luau"], +[121598, "src/Rosetta/data/snbt/init.luau"], +[121661, "src/Rosetta/data/toml/init.luau"], +[121728, "src/Rosetta/data/toml/Decode.luau"], +[122356, "src/Rosetta/data/toml/Encode.luau"], +[122565, "src/Rosetta/data/xml/init.luau"], +[122621, "src/Rosetta/data/yaml/init.luau"], +[122694, "src/Rosetta/data/yaml/Emit.luau"], +[122984, "src/Rosetta/data/yaml/Parse.luau"], +[124277, "src/Rosetta/font/bdf/init.luau"], +[124566, "src/Rosetta/font/bmfont/init.luau"], +[124993, "src/Rosetta/font/bmfont/Parse.luau"], +[125446, "src/Rosetta/font/eot/init.luau"], +[125678, "src/Rosetta/font/fon/init.luau"], +[125961, "src/Rosetta/font/hershey/init.luau"], +[126156, "src/Rosetta/font/pcf/init.luau"], +[126436, "src/Rosetta/font/psf/init.luau"], +[126756, "src/Rosetta/font/ttf/init.luau"], +[126807, "src/Rosetta/font/type1/init.luau"], +[127166, "src/Rosetta/font/type1/Charstring.luau"], +[127444, "src/Rosetta/font/woff/init.luau"], +[127576, "src/Rosetta/font/woff2/init.luau"], +[127633, "src/Rosetta/font/woff2/Rebuild.luau"], +[128173, "src/Rosetta/host/init.luau"], +[128218, "src/Rosetta/host/Love.luau"], +[128361, "src/Rosetta/host/LuaJIT.luau"], +[128411, "src/Rosetta/host/Luau.luau"], +[128434, "src/Rosetta/host/Roblox.luau"], +[128793, "src/Rosetta/image/ani/init.luau"], +[128973, "src/Rosetta/image/blp/init.luau"], +[129231, "src/Rosetta/image/bmp/init.luau"], +[129646, "src/Rosetta/image/dds/init.luau"], +[130129, "src/Rosetta/image/exr/init.luau"], +[130889, "src/Rosetta/image/exr/Codec.luau"], +[131000, "src/Rosetta/image/exr/Piz.luau"], +[131357, "src/Rosetta/image/gif/init.luau"], +[131873, "src/Rosetta/image/gif/Decode.luau"], +[131936, "src/Rosetta/image/hdr/init.luau"], +[132165, "src/Rosetta/image/hdr/Codec.luau"], +[132376, "src/Rosetta/image/icns/init.luau"], +[132707, "src/Rosetta/image/ico/init.luau"], +[132984, "src/Rosetta/image/ico/Dib.luau"], +[133079, "src/Rosetta/image/ilbm/init.luau"], +[133398, "src/Rosetta/image/jpeg/init.luau"], +[133534, "src/Rosetta/image/ktx/init.luau"], +[134194, "src/Rosetta/image/lmp/init.luau"], +[134327, "src/Rosetta/image/pcx/init.luau"], +[134591, "src/Rosetta/image/png/init.luau"], +[135171, "src/Rosetta/image/png/Apng.luau"], +[135251, "src/Rosetta/image/png/Decode.luau"], +[135491, "src/Rosetta/image/png/Encode.luau"], +[135646, "src/Rosetta/image/pnm/init.luau"], +[136024, "src/Rosetta/image/pnm/Codec.luau"], +[136301, "src/Rosetta/image/qoi/init.luau"], +[136423, "src/Rosetta/image/qoi/Codec.luau"], +[136573, "src/Rosetta/image/sgi/init.luau"], +[136858, "src/Rosetta/image/spr/init.luau"], +[137171, "src/Rosetta/image/sunras/init.luau"], +[137417, "src/Rosetta/image/tga/init.luau"], +[137687, "src/Rosetta/image/tga/Codec.luau"], +[137839, "src/Rosetta/image/tiff/init.luau"], +[138666, "src/Rosetta/image/tiff/Pixels.luau"], +[139056, "src/Rosetta/image/tim/init.luau"], +[139298, "src/Rosetta/image/vtf/init.luau"], +[139533, "src/Rosetta/image/webp/init.luau"], +[140143, "src/Rosetta/image/webp/Alpha.luau"], +[140219, "src/Rosetta/image/webp/Anim.luau"], +[140374, "src/Rosetta/image/xbm/init.luau"], +[140535, "src/Rosetta/image/xpm/init.luau"], +[140803, "src/Rosetta/image/xpm/Names.luau"], +[140859, "src/Rosetta/layered/aseprite/init.luau"], +[141597, "src/Rosetta/layered/ora/init.luau"], +[141884, "src/Rosetta/layered/psd/init.luau"], +[142619, "src/Rosetta/layered/psd/Channels.luau"], +[142971, "src/Rosetta/model/3ds/init.luau"], +[143054, "src/Rosetta/model/3ds/Build.luau"], +[143701, "src/Rosetta/model/3ds/Read.luau"], +[144197, "src/Rosetta/model/3ds/Write.luau"], +[145002, "src/Rosetta/model/3mf/init.luau"], +[145084, "src/Rosetta/model/3mf/Read.luau"], +[145672, "src/Rosetta/model/3mf/Write.luau"], +[146077, "src/Rosetta/model/b3d/init.luau"], +[146132, "src/Rosetta/model/b3d/Read.luau"], +[146703, "src/Rosetta/model/bsp/init.luau"], +[146894, "src/Rosetta/model/bsp/Lightmap.luau"], +[146960, "src/Rosetta/model/bsp/Quake.luau"], +[147347, "src/Rosetta/model/bsp/Quake3.luau"], +[147575, "src/Rosetta/model/bsp/Tree.luau"], +[147963, "src/Rosetta/model/dae/init.luau"], +[148152, "src/Rosetta/model/dae/Math.luau"], +[148199, "src/Rosetta/model/dae/Read.luau"], +[150049, "src/Rosetta/model/dae/Write.luau"], +[150418, "src/Rosetta/model/fbx/init.luau"], +[150566, "src/Rosetta/model/fbx/Ascii.luau"], +[150836, "src/Rosetta/model/fbx/Binary.luau"], +[151291, "src/Rosetta/model/fbx/Read.luau"], +[152653, "src/Rosetta/model/fbx/Write.luau"], +[153638, "src/Rosetta/model/fbx/Xform.luau"], +[153679, "src/Rosetta/model/gltf/init.luau"], +[153916, "src/Rosetta/model/gltf/Pack.luau"], +[153985, "src/Rosetta/model/gltf/Read.luau"], +[154716, "src/Rosetta/model/gltf/Write.luau"], +[155396, "src/Rosetta/model/iqm/init.luau"], +[155472, "src/Rosetta/model/iqm/Read.luau"], +[155827, "src/Rosetta/model/iqm/Write.luau"], +[156514, "src/Rosetta/model/ldraw/init.luau"], +[156592, "src/Rosetta/model/ldraw/Colors.luau"], +[156910, "src/Rosetta/model/ldraw/Read.luau"], +[157487, "src/Rosetta/model/lwo/init.luau"], +[157563, "src/Rosetta/model/lwo/Build.luau"], +[158025, "src/Rosetta/model/lwo/Parse.luau"], +[158568, "src/Rosetta/model/map/init.luau"], +[158885, "src/Rosetta/model/map/Build.luau"], +[159128, "src/Rosetta/model/map/Parse.luau"], +[159513, "src/Rosetta/model/map/Write.luau"], +[159659, "src/Rosetta/model/mca/init.luau"], +[160001, "src/Rosetta/model/mca/Chunk.luau"], +[160134, "src/Rosetta/model/mca/Lz4Block.luau"], +[160204, "src/Rosetta/model/md2/init.luau"], +[160403, "src/Rosetta/model/md3/init.luau"], +[160631, "src/Rosetta/model/md5/init.luau"], +[160712, "src/Rosetta/model/md5/Read.luau"], +[161145, "src/Rosetta/model/mdl/init.luau"], +[161227, "src/Rosetta/model/mdl/HalfLife.luau"], +[161555, "src/Rosetta/model/mdl/Quake.luau"], +[161773, "src/Rosetta/model/ms3d/init.luau"], +[161845, "src/Rosetta/model/ms3d/Read.luau"], +[162291, "src/Rosetta/model/ms3d/Write.luau"], +[162760, "src/Rosetta/model/obj/init.luau"], +[163502, "src/Rosetta/model/obj/Mtl.luau"], +[163789, "src/Rosetta/model/off/init.luau"], +[164251, "src/Rosetta/model/ply/init.luau"], +[165356, "src/Rosetta/model/ply/Binary.luau"], +[165557, "src/Rosetta/model/pmx/init.luau"], +[165626, "src/Rosetta/model/pmx/Build.luau"], +[165922, "src/Rosetta/model/pmx/Pmd.luau"], +[166257, "src/Rosetta/model/pmx/Read.luau"], +[166661, "src/Rosetta/model/qb/init.luau"], +[167054, "src/Rosetta/model/rbxm/init.luau"], +[167646, "src/Rosetta/model/rbxmx/init.luau"], +[168299, "src/Rosetta/model/robloxmesh/init.luau"], +[168958, "src/Rosetta/model/robloxmesh/Parse.luau"], +[169415, "src/Rosetta/model/robloxmesh/Write.luau"], +[169524, "src/Rosetta/model/schematic/init.luau"], +[169845, "src/Rosetta/model/schematic/Common.luau"], +[169965, "src/Rosetta/model/schematic/Litematic.luau"], +[170176, "src/Rosetta/model/schematic/Mcedit.luau"], +[170420, "src/Rosetta/model/schematic/Sponge.luau"], +[170549, "src/Rosetta/model/smd/init.luau"], +[170616, "src/Rosetta/model/smd/Read.luau"], +[170885, "src/Rosetta/model/smd/Write.luau"], +[171128, "src/Rosetta/model/stl/init.luau"], +[171578, "src/Rosetta/model/stl/Decode.luau"], +[171652, "src/Rosetta/model/usda/init.luau"], +[171861, "src/Rosetta/model/usda/Build.luau"], +[173139, "src/Rosetta/model/usda/Parse.luau"], +[173937, "src/Rosetta/model/usda/Write.luau"], +[174754, "src/Rosetta/model/vox/init.luau"], +[175640, "src/Rosetta/model/vox/Grid.luau"], +[175697, "src/Rosetta/model/vrml/init.luau"], +[175763, "src/Rosetta/model/x/init.luau"], +[175893, "src/Rosetta/model/x/Build.luau"], +[176456, "src/Rosetta/model/x/Parse.luau"], +[176753, "src/Rosetta/model/x3d/init.luau"], +[176831, "src/Rosetta/music/669/init.luau"], +[177037, "src/Rosetta/music/ahx/init.luau"], +[177088, "src/Rosetta/music/far/init.luau"], +[177317, "src/Rosetta/music/hmp/init.luau"], +[177581, "src/Rosetta/music/hvl/init.luau"], +[177632, "src/Rosetta/music/it/init.luau"], +[178050, "src/Rosetta/music/it/Itsex.luau"], +[178166, "src/Rosetta/music/med/init.luau"], +[178813, "src/Rosetta/music/midi/init.luau"], +[178956, "src/Rosetta/music/midi/Smf.luau"], +[179367, "src/Rosetta/music/mod/init.luau"], +[179720, "src/Rosetta/music/mtm/init.luau"], +[179942, "src/Rosetta/music/mus/init.luau"], +[180099, "src/Rosetta/music/okt/init.luau"], +[180380, "src/Rosetta/music/ptm/init.luau"], +[180602, "src/Rosetta/music/s3m/init.luau"], +[180838, "src/Rosetta/music/sf2/init.luau"], +[180881, "src/Rosetta/music/stm/init.luau"], +[181112, "src/Rosetta/music/ult/init.luau"], +[181416, "src/Rosetta/music/umx/init.luau"], +[181632, "src/Rosetta/music/xm/init.luau"], +[182193, "src/Rosetta/music/xmi/init.luau"], +[182401, "src/Rosetta/ops/AudioOps.luau"], +[182850, "src/Rosetta/ops/ImageOps/init.luau"], +[183494, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[184004, "src/Rosetta/ops/LayerOps.luau"], +[184097, "src/Rosetta/ops/MeshOps/init.luau"], +[185133, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[185300, "src/Rosetta/ops/MusicOps.luau"], +[185648, "src/Rosetta/playlist/m3u/init.luau"], +[186001, "src/Rosetta/playlist/pls/init.luau"], +[186179, "src/Rosetta/playlist/xspf/init.luau"], +[186382, "src/Rosetta/subtitle/ass/init.luau"], +[186826, "src/Rosetta/subtitle/srt/init.luau"], +[186999, "src/Rosetta/subtitle/vtt/init.luau"], +[187202, "src/Rosetta/vector/svg/init.luau"], +[187288, "src/Rosetta/vector/svg/Parse.luau"], +[188034, "src/Rosetta/vector/svg/PathData.luau"], +[188402, "src/Rosetta/vector/svg/Render.luau"], +[188819, "src/Rosetta/vector/svg/Style.luau"], +[189191, "src/Rosetta/vector/svg/Write.luau"], +[189391, "src/Rosetta/vector/tiled/init.luau"], +[189571, "src/Rosetta/vector/tiled/Data.luau"], +[189722, "src/Rosetta/vector/tiled/Tmj.luau"], +[190353, "src/Rosetta/vector/tiled/Tmx.luau"], +[190965, "src/Rosetta/video/avi/init.luau"], +[191259, "src/Rosetta/video/fli/init.luau"], +[191410, "src/Rosetta/video/flv/init.luau"], +[191794, "src/Rosetta/video/flv/Amf.luau"], +[191952, "src/Rosetta/video/flv/Mux.luau"], +[192233, "src/Rosetta/video/h264/init.luau"], +[192372, "src/Rosetta/video/mkv/init.luau"], +[192528, "src/Rosetta/video/mkv/Mux.luau"], +[192807, "src/Rosetta/video/mkv/Parse.luau"], +[193528, "src/Rosetta/video/mp4/init.luau"], +[193856, "src/Rosetta/video/mpegps/init.luau"], +[194043, "src/Rosetta/video/mpegts/init.luau"], +[194281, "src/Rosetta/video/ogv/init.luau"], +[194676, "src/Rosetta/video/smk/init.luau"], +[194985, "src/Rosetta/video/smk/Audio.luau"], +[195105, "src/Rosetta/video/y4m/init.luau"] ] diff --git a/build/rosetta.lua b/build/rosetta.lua index 5135f32..ed94ec2 100644 --- a/build/rosetta.lua +++ b/build/rosetta.lua @@ -1661,6 +1661,18 @@ local list= { return __include("image/ktx") end, }, + { + name = "lmp", + category = "image", + path = "image/lmp", + extensions = { "lmp" }, + mime = { "image/x-quake-lmp" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 }, variants = { "qpic", "palette", "colormap" } }, + load = function() + return __include("image/lmp") + end, + }, { name = "pcx", category = "image", @@ -1721,6 +1733,18 @@ local list= { return __include("image/sgi") end, }, + { + name = "spr", + category = "image", + path = "image/spr", + extensions = { "spr" }, + mime = { "image/x-quake-sprite" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, alpha = true, animation = true, variants = { "quake", "halflife", "spr32" } }, + load = function() + return __include("image/spr") + end, + }, { name = "sunras", category = "image", @@ -2255,8 +2279,8 @@ local list= { path = "model/bsp", extensions = { "bsp" }, mime = { "model/x-bsp" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, - caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" }, + caps = { decode = true, encode = false, variants = { "quake", "bsp2", "2psb", "halflife", "quake2", "quake3" }, lightmaps = true, collision = true, visibility = true }, load = function() return __include("model/bsp") end, @@ -2333,6 +2357,18 @@ local list= { return __include("model/lwo") end, }, + { + name = "map", + category = "model", + path = "model/map", + extensions = { "map" }, + mime = { "text/x-quake-map" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" }, + caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true }, + load = function() + return __include("model/map") + end, + }, { name = "mca", category = "model", @@ -3053,6 +3089,18 @@ local list= { return __include("archive/wad") end, }, + { + name = "wad2", + category = "archive", + path = "archive/wad2", + extensions = { "wad" }, + mime = { "application/x-quake-wad" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, images = true, variants = { "wad2", "wad3" } }, + load = function() + return __include("archive/wad2") + end, + }, { name = "xz", category = "archive", @@ -3209,6 +3257,30 @@ local list= { return __include("data/plist") end, }, + { + name = "q3shader", + category = "data", + path = "data/q3shader", + extensions = { "shader" }, + mime = { "text/x-quake3-shader" }, + deps = { "core/Err", "core/Bytes" }, + caps = { decode = true, encode = true }, + load = function() + return __include("data/q3shader") + end, + }, + { + name = "q3skin", + category = "data", + path = "data/q3skin", + extensions = { "skin" }, + mime = { "text/x-quake3-skin" }, + deps = { "core/Err", "core/Bytes" }, + caps = { decode = true, encode = true }, + load = function() + return __include("data/q3skin") + end, + }, { name = "snbt", category = "data", @@ -12440,6 +12512,288 @@ end return Picture end +__FILES["archive/wad2"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- archive/wad2: Quake WAD2 and Half-Life WAD3 texture / graphics WADs (wad.h of the Quake source, the GoldSrc WAD3 +-- layout; no code taken), read and write. Lumps by name (repeats "~"); Wad2.image decodes miptex, qpic, +-- conchars, palette and GoldSrc font lumps through codecs/image/Miptex (Quake 1 needs a palette: the WAD's own +-- "palette" lump, opts.palette or gfx/palette.lmp through files / resolve; else grey). Not supported: compressed lumps. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Archive = __include("containers/Archive") +local Pixels = __include("codecs/image/Pixels") +local Miptex = __include("codecs/image/Miptex") + +-- ------------------------------------------------------------------------------------------------ contract +local Wad2 = { + name = "wad2", + category = "archive", + extensions = { "wad" }, + mime = { "application/x-quake-wad" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, images = true, variants = { "wad2", "wad3" } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + +local T = Miptex.TYPES + +-- ------------------------------------------------------------------------------------------------ sniff +function Wad2.sniff(r) +if r:remaining() < 12 then + return 0 + end + local m = r:peek(4) + return (m == "WAD2" or m == "WAD3" )and 0.9 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive, opts) +return Wad2.encode(archive, opts) +end + +function Wad2.decode(r, opts) +local size = r.limit - r.base + local lumps, msg, magic = Miptex.wad(r.buf, r.base, size, opts and opts.maxEntries) + if not lumps then + return nil, Err.from(msg, 0) + end + local a = Archive.new("wad2", encode) + local seen= {} + for _, l in __iter(lumps) do + if l.compression ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "compressed lump " .. l.name) + end + local entry = l.name + local k = seen[string.lower(entry)] + if k then + seen[string.lower(entry)] = k + 1 + entry = entry .. "~" .. (k + 1) + else + seen[string.lower(entry)] = 1 + end + Archive.put(a, { name = entry, size = l.disksize, dir = false, method = "store", type = l.type, lump = l.name, load = Archive.slice(r.buf, r.base + l.offset, l.disksize) }) + end + a.meta.source = { format = "wad2", variant = string.lower(magic ), lumps = #lumps } + a.meta.wad2 = { buf = r.buf, base = r.base, lumps = lumps, goldsrc = magic == "WAD3" } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function guessType(name, data, goldsrc) +local n = buffer.len(data) + if string.lower(name) == "palette" and n == 768 then + return T.palette + end + if n >= 40 then + local w, h = buffer.readu32(data, 16), buffer.readu32(data, 20) + if w > 0 and h > 0 and w < 65536 and h < 65536 and buffer.readu32(data, 24) == 40 then + return goldsrc and 0x43 or T.miptex + end + end + if n >= 8 then + local w, h = buffer.readu32(data, 0), buffer.readu32(data, 4) + if w > 0 and h > 0 and 8 + w * h <= n then + return T.qpic + end + end + return T.miptex +end + +function Wad2.encode(archive, opts) +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 variant = opts and opts.variant or ((type(src) == "table" and src.format == "wad2" and{src.variant }or{nil})[1]) + if not variant then + variant = "wad2" + for _, it in __iter(items) do + if (it.entry ).type == 0x43 then + variant = "wad3" + end + end + end + if variant ~= "wad2" and variant ~= "wad3" then + return nil, Err.new(Err.ARG, "variant must be wad2 or wad3") + end + local list= {} + for _, it in __iter(items) do + if not it.entry.dir then + local e= it.entry + local name = e.lump or string.gsub(string.match(e.name, "([^/\\]*)$") or e.name, "~%d+$", "") + if #name == 0 or #name > 15 then + return nil, Err.new(Err.ARG, "lump name must be 1..15 bytes: " .. e.name) + end + local typ = (type(e.type) == "number" and{e.type }or{(guessType(name, it.data, variant == "wad3") +)})[1] table.insert(list, { name = name, data = it.data, type = typ }) + end + end + local w = Bytes.writer() + w:string(variant == "wad3" and"WAD3" or"WAD2") + w:u32le(#list) + w:u32le(0) + local offs= {} + for i, l in __iter(list) do + offs[i] = w:tell() + w:bytes(l.data) + w:fill(0, (4 - buffer.len(l.data) % 4) % 4) + end + local dir = w:tell() + for i, l in __iter(list) do + w:u32le(offs[i]) + w:u32le(buffer.len(l.data)) + w:u32le(buffer.len(l.data)) + w:u8(l.type) + w:u8(0) + w:u16le(0) + w:string(l.name) + w:fill(0, 16 - #l.name) + end + w:setU32le(8, dir) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +local function info(a) +return type(a) == "table" and type(a.meta) == "table" and a.meta.wad2 or nil +end + +function Wad2.new(variant) +local a = Archive.new("wad2", encode) + a.meta.source = { format = "wad2", variant = variant or "wad2" } + return a +end + +function Wad2.lumps(a) +local w = info(a) + return w and w.lumps +end + +-- the WAD's own "palette" lump (gfx.wad) as a 1024-byte rgba8 palette +function Wad2.palette(a) +local w = info(a) + local l = w and Miptex.find(w.lumps, "palette") + if l and l.disksize >= 768 then + return Pixels.palette(w.buf, w.base + l.offset, 256) + end + return nil +end + +function Wad2.image(a, name, opts) +local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD2 / WAD3 archive") + end + local l = Miptex.find(w.lumps, tostring(name)) + if not l then + return nil, Err.new(Err.ARG, "no lump named " .. tostring(name)) + end + local b, at, size = w.buf, w.base + l.offset, l.disksize + local pal= nil + if not w.goldsrc then + local raw = (opts and opts.palette and{(Bytes.toBuffer(opts.palette) )}or{nil +})[1] if raw and buffer.len(raw) >= 768 then + pal = Pixels.palette(raw, 0, 256) + else + pal = Wad2.palette(a) + if not pal then + local lmp = Input.sibling(opts, "gfx/palette.lmp") + pal = (lmp and buffer.len(lmp) >= 768 and{(Pixels.palette(lmp, 0, 256) )}or{nil +})[1] end + end + end + local keyed= (opts and{opts.keyed }or{nil +})[1] local img, msg +local kind +if l.type == T.palette and size >= 768 then + kind = "palette" + local out = Types.Image.new(16, 16) + buffer.copy(out.pixels, 0, Pixels.palette(b, at, 256), 0, 1024) + img = out + elseif string.lower(l.name) == "conchars" and size == 128 * 128 then + -- gfx.wad's console font: raw 128 x 128 pixels, no header, index 0 transparent + kind = "conchars" + local out = Types.Image.new(128, 128) + Pixels.indexed(b, at, 128, 8, out.pixels, 128, 128, true, Pixels.keyed(pal or Pixels.grey(), keyed == false and-1 or 0)) + img = out + elseif l.type == T.qpic then + kind = "qpic" + img, msg = Miptex.qpic(b, at, size, { palette = pal, goldsrc = w.goldsrc, keyed = keyed } ) + elseif l.type == T.font and w.goldsrc and size >= 16 + 1024 then + -- GoldSrc qfont_t: width (256), height, rowcount, rowheight, charinfo[256] (u16 offset, u16 width), pixels, palette + kind = "font" + local fw, fh = buffer.readu32(b, at), buffer.readu32(b, at + 4) + local p = 16 + 1024 + fw * fh + if fw == 0 or fh == 0 or fw * fh > 2 ^ 24 or p + 2 > size then + return nil, Err.new(Err.CORRUPT, "bad font lump " .. l.name, l.offset) + end + local n = buffer.readu16(b, at + p) + local fpal = (n > 0 and n <= 256 and p + 2 + n * 3 <= size and{(Pixels.palette(b, at + p + 2, n) )}or{(Pixels.grey() +)})[1] local out = Types.Image.new(fw, fh) + Pixels.indexed(b, at + 16 + 1024, fw, 8, out.pixels, fw, fh, true, (keyed == false and{fpal }or{(Pixels.keyed(fpal, 255))})[1]) + local glyphs = {} + for c = 0, 255 do + glyphs[c + 1] = { offset = buffer.readu16(b, at + 16 + c * 4), width = buffer.readu16(b, at + 18 + c * 4) } + end + out.meta.font = { rows = buffer.readu32(b, at + 8), rowHeight = buffer.readu32(b, at + 12), glyphs = glyphs } + img = out + else + kind = "miptex" + img, msg = Miptex.decode(b, at, size, { palette = pal, goldsrc = w.goldsrc, mip = (opts and{opts.mip }or{nil})[1], keyed = keyed } ) + end + if not img then + return nil, Err.from(msg, l.offset) + end + img.meta.source = { format = "wad2", kind = kind, lump = l.name, type = l.type, palette = w.goldsrc or pal ~= nil } + return img, nil +end + +-- adds an rgba8 image as a miptex (sizes multiples of 16) or qpic lump; WAD3 lumps carry their own palette +function Wad2.addImage(a, name, img, opts) +if type(img) ~= "table" or img.format ~= "rgba8" then + return false, Err.new(Err.ARG, "expected an rgba8 Image") + end + local src = type(a) == "table" and type(a.meta) == "table" and a.meta.source + local goldsrc = type(src) == "table" and src.variant == "wad3" + local raw = opts and opts.palette and Bytes.toBuffer(opts.palette) + local pal = (raw and buffer.len(raw) >= 768 and{(Pixels.palette(raw, 0, 256) )}or{nil +})[1] local kind = opts and opts.kind or "miptex" + local data, msg + if kind == "qpic" then + data, msg = Miptex.encodeQpic(img, pal, goldsrc) + else + data, msg = Miptex.encode(img, name, pal, goldsrc) + end + if not data then + return false, Err.new(Err.ARG, msg or "cannot encode") + end + Archive.put(a, { name = name, size = buffer.len(data), dir = false, method = "store", lump = name, data = data, + type = (kind == "qpic" and{T.qpic }or{goldsrc and 0x43 or T.miptex })[1]}) + return true, nil +end + +return Wad2 +end __FILES["archive/xz"] = function() local __compat = __compat local buffer = __compat.buffer --!strict -- archive/xz: .xz (xz file format 1.2) and .lzma ("LZMA alone") as single-stream archives (codecs/compress/Lzma). @@ -70525,12 +70879,313 @@ end return Yuv end +__FILES["codecs/image/Miptex"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- codecs/image/Miptex: Quake / GoldSrc mip textures and the WAD2 / WAD3 lump directory, read and write. +-- miptex_t of bspfile.h: name[16], width, height, offsets[4], four 8-bit mip levels; GoldSrc adds u16 count + count * 3 +-- palette bytes after mip 3. wad.h: "WAD2" / "WAD3", numlumps, infotableofs; 32-byte lumpinfo_t. No code taken. +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") +local Quantize = __include("codecs/image/Quantize") + +local Miptex = {} + +local readu8, readu32, readi32 = buffer.readu8, buffer.readu32, buffer.readi32 + +-- lumpinfo_t types (wad.h TYP_*; WAD3: 0x43 is a miptex with its palette, 0x46 a font) + + + + + + + + + + +Miptex.TYPES = table.freeze({ palette = 0x40, qtex = 0x41, qpic = 0x42, sound = 0x43, miptex = 0x44, font = 0x46 }) + +local function cstr(b, at, n) +return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) +end + +function Miptex.header(b, at, size) +if at < 0 or size < 40 or at + 40 > buffer.len(b) then + return nil, "truncated miptex header" + end + local w, h = readu32(b, at + 16), readu32(b, at + 20) + local offs = { readu32(b, at + 24), readu32(b, at + 28), readu32(b, at + 32), readu32(b, at + 36) } + return { name = cstr(b, at, 16), width = w, height = h, offsets = offs }, nil +end + +-- the GoldSrc palette after mip 3, as a 1024-byte rgba8 palette, or nil when it is missing / out of range +function Miptex.ownPalette(b, at, size, hd) +local w, h = hd.width, hd.height + local p = hd.offsets[4] + (math.floor(w / 8)) * (math.floor(h / 8)) + if hd.offsets[4] == 0 or p + 2 > size then + return nil + end + local n = buffer.readu16(b, at + p) + if n == 0 or n > 256 or p + 2 + n * 3 > size then + return nil + end + return Pixels.palette(b, at + p + 2, n) +end + +-- decodes one mip level to rgba8; without pixels (offsets 0: the texture lives in a WAD) returns nil, "external" +function Miptex.decode(b, at, size, opts) +local hd, err = Miptex.header(b, at, size) + if not hd then + return nil, err + end + local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, 3) + local w, h = math.floor(hd.width / (2 ^ mip)), math.floor(hd.height / (2 ^ mip) +) if hd.width == 0 or hd.height == 0 or w == 0 or h == 0 then + return nil, "empty miptex" + end + if hd.width * hd.height > (opts and opts.maxPixels or 2 ^ 24) then + return nil, "limit: miptex " .. hd.width .. " x " .. hd.height + end + local off = hd.offsets[mip + 1] + if off == 0 then + return nil, "external" + end + if off + w * h > size or at + off + w * h > buffer.len(b) then + return nil, "truncated miptex pixels" + end + local own = (opts and opts.goldsrc and{(Miptex.ownPalette(b, at, size, hd) )}or{nil +})[1] local pal = own or (opts and opts.palette) or Pixels.grey() + local keyed = (opts and opts.keyed ~= nil and{opts.keyed }or{(string.sub(hd.name, 1, 1) == "{" +)})[1] if keyed then + pal = Pixels.keyed(pal, 255) + end + local img = Types.Image.new(w, h) + Pixels.indexed(b, at + off, w, 8, img.pixels, w, h, true, pal) + img.meta.source = { format = "miptex", name = hd.name, mip = mip, palette = own ~= nil or (opts ~= nil and opts.palette ~= nil), keyed = keyed or nil } + return img, nil +end + +local function halve(px, w, h) +local w2, h2 = math.max(1, math.floor(w / 2)), math.max(1, math.floor(h / 2)) + local out = buffer.create(w2 * h2 * 4) + for y = 0, h2 - 1 do + for x = 0, w2 - 1 do + for c = 0, 3 do + local s = 0 + for dy = 0, 1 do + for dx = 0, 1 do + local sx, sy = math.min(x * 2 + dx, w - 1), math.min(y * 2 + dy, h - 1) + s =s+ readu8(px, (sy * w + sx) * 4 + c) + end + end + buffer.writeu8(out, (y * w2 + x) * 4 + c, math.floor((s + 2) / 4)) + end + end + end + return out, w2, h2 +end + +-- an rgba8 image -> a miptex_t with four mip levels (box filtered, mapped to the nearest palette entry); goldsrc +-- appends the palette. palette: 1024-byte rgba8; without it (GoldSrc only) a 256-colour median-cut palette is made. +function Miptex.encode(img, name, palette, goldsrc) +local w, h = img.width, img.height + if w <= 0 or h <= 0 or w % 16 ~= 0 or h % 16 ~= 0 then + return nil, "miptex sizes must be multiples of 16" + end + if #name > 15 then + return nil, "miptex name over 15 bytes" + end + if not palette and not goldsrc then + return nil, "a Quake miptex needs a palette" + end + local keyed = string.sub(name, 1, 1) == "{" + local _, colors = Miptex.indices(img, palette, keyed) + if keyed and not palette then + colors[256] = { 0, 0, 255, 255 } -- GoldSrc '{' textures: index 255 is the (blue) key colour + end + local pal1024 = palette or buffer.create(1024) + if not palette then + for i, c in __iter(colors) do + buffer.writeu32(pal1024, (i - 1) * 4, 0xFF000000 + c[3] * 65536 + c[2] * 256 + c[1]) + end + end + local levels= {} + local px, lw, lh = img.pixels, w, h + for m = 0, 3 do + if m > 0 then + px, lw, lh = halve(px, lw, lh) + end + local lvl = { kind = "image", width = lw, height = lh, format = "rgba8", pixels = px, loops = 0, meta = {} } +levels[m + 1] = (Miptex.indices(lvl, pal1024, keyed)) + end + local total = 40 + for _, l in __iter(levels) do + total =total+ buffer.len(l) + end + local palAt = total + if goldsrc then + total =total+ (2 + 768 + 2 +) end + local out = buffer.create(total) + buffer.writestring(out, 0, name) + buffer.writeu32(out, 16, w) + buffer.writeu32(out, 20, h) + local o = 40 + for m, l in __iter(levels) do + buffer.writeu32(out, 24 + (m - 1) * 4, o) + buffer.copy(out, o, l) + o =o+ buffer.len(l) + end + if goldsrc then + buffer.writeu16(out, palAt, 256) + for i = 0, 255 do + local c = colors[i + 1] or { 0, 0, 0 } + buffer.writeu8(out, palAt + 2 + i * 3, c[1]) + buffer.writeu8(out, palAt + 3 + i * 3, c[2]) + buffer.writeu8(out, palAt + 4 + i * 3, c[3]) + end + end + return out, nil +end + +-- the lump directory of a WAD2 / WAD3 file (offsets relative to base), or nil, message +function Miptex.wad(b, base, size, maxLumps) +if size < 12 or base + 12 > buffer.len(b) then + return nil, "truncated header", nil + end + local magic = buffer.readstring(b, base, 4) + if magic ~= "WAD2" and magic ~= "WAD3" then + return nil, "bad magic", nil + end + local n, dir = readi32(b, base + 4), readi32(b, base + 8) + if n < 0 or dir < 0 then + return nil, "negative directory field", nil + end + if n > (maxLumps or 1e6) then + return nil, "limit: too many lumps: " .. n, nil + end + if dir + n * 32 > size then + return nil, "truncated directory past the end", nil + end + local out= {} + for i = 0, n - 1 do + local o = base + dir + i * 32 + local at, disk, full = readi32(b, o), readi32(b, o + 4), readi32(b, o + 8) + if at < 0 or disk < 0 or at + disk > size then + return nil, "truncated lump past the end", nil + end + out[i + 1] = { name = cstr(b, o + 16, 16), offset = at, disksize = disk, size = full, type = readu8(b, o + 12), compression = readu8(b, o + 13) } + end + return out, nil, magic +end + +-- the lump named name (case-insensitive, the last one wins as in W_GetLumpinfo) +function Miptex.find(lumps, name) +local want = string.lower(name) + local best= nil + for _, l in __iter(lumps) do + if string.lower(l.name) == want then + best = l + end + end + return best +end + +-- qpic (Quake .lmp / WAD2 type 0x42: u32 width, height, 8-bit pixels; GoldSrc adds u16 count + count * 3 palette bytes) +-- -> rgba8. keyed: index 255 transparent (Quake's Draw_TransPic), default true +function Miptex.qpic(b, at, size, opts) +if size < 8 or at < 0 or at + 8 > buffer.len(b) then + return nil, "truncated qpic header" + end + local w, h = readu32(b, at), readu32(b, at + 4) + if w == 0 or h == 0 then + return nil, "empty qpic" + end + if w * h > (opts and opts.maxPixels or 2 ^ 24) then + return nil, "limit: qpic " .. w .. " x " .. h + end + if 8 + w * h > size or at + 8 + w * h > buffer.len(b) then + return nil, "truncated qpic pixels" + end + local own= nil + if opts and opts.goldsrc then + local p = 8 + w * h + if p + 2 <= size then + local n = buffer.readu16(b, at + p) + if n > 0 and n <= 256 and p + 2 + n * 3 <= size then + own = Pixels.palette(b, at + p + 2, n) + end + end + end + local pal = own or (opts and opts.palette) or Pixels.grey() + local keyed = (opts and opts.keyed ~= nil and{opts.keyed }or{true +})[1] if keyed then + pal = Pixels.keyed(pal, 255) + end + local img = Types.Image.new(w, h) + Pixels.indexed(b, at + 8, w, 8, img.pixels, w, h, true, pal) + img.meta.source = { format = "qpic", palette = own ~= nil or (opts ~= nil and opts.palette ~= nil), keyed = keyed or nil } + return img, nil +end + +-- palette indices of an rgba8 image (nearest entry; alpha < 128 -> 255 when keyed and the image has any) and the +-- palette used +function Miptex.indices(img, palette, keyed) +if keyed then + local any = false + for k = 0, img.width * img.height - 1 do + if readu8(img.pixels, k * 4 + 3) < 128 then + any = true + break + end + end + keyed = any + end + local colors = (palette and{(Pixels.colorList(palette) )}or{(Quantize.palette(img.pixels, img.width, img.height, keyed and 255 or 256) +)})[1] local idx = Quantize.map(img.pixels, img.width, img.height, colors, { transparentIndex = keyed and palette and 255 or nil }) + if keyed then + for k = 0, img.width * img.height - 1 do + if readu8(img.pixels, k * 4 + 3) < 128 then + buffer.writeu8(idx, k, 255) + end + end + end + return idx, colors +end + +-- an rgba8 image -> qpic bytes (goldsrc: with its palette, made by median cut when none is given) +function Miptex.encodeQpic(img, palette, goldsrc, keyed) +if not palette and not goldsrc then + return nil, "a Quake qpic needs a palette" + end + local w, h = img.width, img.height + local idx, colors = Miptex.indices(img, palette, keyed ~= false) + local out = buffer.create(8 + w * h + (goldsrc and 2 + 768 or 0)) + buffer.writeu32(out, 0, w) + buffer.writeu32(out, 4, h) + buffer.copy(out, 8, idx, 0, w * h) + if goldsrc then + local p = 8 + w * h + buffer.writeu16(out, p, 256) + for i = 0, 255 do + local c = colors[i + 1] or { 0, 0, 0 } + buffer.writeu8(out, p + 2 + i * 3, c[1]) + buffer.writeu8(out, p + 3 + i * 3, c[2]) + buffer.writeu8(out, p + 4 + i * 3, c[3]) + end + end + return out, nil +end + +return Miptex +end __FILES["codecs/image/Pixels"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict --!native --!optimize 2 --- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB. --- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8. From bmp-luau b86aed6 (same author); the encoder loops are new. +-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB, and palette helpers. +-- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8; palettes: keyed index (Quake 255), grey ramp, Quake colormap light +-- levels. From bmp-luau b86aed6 (same author); the encoder loops and palette helpers are new. local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8 local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift @@ -70787,6 +71442,61 @@ local seen= {} return list, alpha end +-- a 256-entry rgba8 palette (u32 LE per entry) with entry i = { i, i, i, 255 } +function Pixels.grey() +local pal = buffer.create(1024) + for i = 0, 255 do + writeu32(pal, i * 4, 0xFF000000 + i * 0x10101) + end + return pal +end + +-- a copy of a 1024-byte palette with entry index transparent (alpha 0, colour kept as Pillow does; Quake / GoldSrc: +-- index 255 of sprites, qpics and '{' textures) +function Pixels.keyed(pal, index) +local out = buffer.create(1024) + buffer.copy(out, 0, pal, 0, math.min(buffer.len(pal), 1024)) + if index >= 0 and index < 256 then + writeu8(out, index * 4 + 3, 0) + end + return out +end + +-- palette (1024 bytes) -> { { r, g, b, a } } for codecs/image/Quantize +function Pixels.colorList(pal, n) +local out= {} + for i = 0, math.clamp(n or 256, 0, math.floor(buffer.len(pal) / 4)) - 1 do + out[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) } + end + return out +end + +-- Quake colormap.lmp: rows of 256 palette indices, row 0 brightest .. 63 darkest (32 = unlit); the palette for one +-- light level, or nil past the end of the map +function Pixels.colormap(pal, cmap, base, row) +local o = base + row * 256 + if row < 0 or base < 0 or o + 256 > buffer.len(cmap) then + return nil + end + local out = buffer.create(1024) + for i = 0, 255 do + writeu32(out, i * 4, readu32(pal, readu8(cmap, o + i) * 4)) + end + return out +end + +-- rgba8 palette (1024 bytes) -> 3 * n bytes R, G, B (the Quake / GoldSrc palette layout) +function Pixels.paletteBytes(pal, n) +local m = math.clamp(n or 256, 0, 256) + local out = buffer.create(m * 3) + for i = 0, m - 1 do + writeu8(out, i * 3, readu8(pal, i * 4)) + writeu8(out, i * 3 + 1, readu8(pal, i * 4 + 1)) + writeu8(out, i * 3 + 2, readu8(pal, i * 4 + 2)) + end + return out +end + return Pixels end __FILES["codecs/image/Quantize"] = function() @@ -77353,6 +78063,646 @@ end return Yuv end +__FILES["codecs/model/Brush"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/model/Brush: convex plane brushes -> polygons and Scene primitives, with Quake-family texture projection. +-- As qbsp (Quake / ericw-tools; no code taken): a big square on every plane (inside n . p <= d) clipped by the others. +-- Projections: Quake standard (TextureAxisFromPlane + rotate / scale / shift), Valve 220 (explicit U / V axes), Quake +-- III brush primitives (q3map2 ComputeAxisBase + 2 x 3 matrix). Options: merge coplanar faces with one projection +-- (qbsp TryMerge), drop face parts inside / touching other brushes (qbsp CSGFaces; earlier brushes win coplanar ties). +local Types = __include("Types") + +local Brush = {} + +local abs, sqrt, floor, sin, cos, atan2, min, max = math.abs, math.sqrt, math.floor, math.sin, math.cos, math.atan2, math.min, math.max +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +-- TextureAxisFromPlane's baseaxis table (normal, s axis, t axis per row): floor, ceiling, west, east, south, north + + + + + + + + + + + + + + + + + + + + + + + +local BASEAXIS = { + { 0, 0, 1 }, { 1, 0, 0 }, { 0, -1, 0 }, + { 0, 0, -1 }, { 1, 0, 0 }, { 0, -1, 0 }, + { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, + { -1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, + { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, + { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, +} + +local function snap(x) +local r = floor(x + 0.5) + return (abs(x - r) < 1e-6 and{r }or{x +})[1]end + +-- qbsp PlaneFromPoints: normal = (p1 - p2) x (p3 - p2), the brush lies behind it; nil when the points are colinear +function Brush.planeFromPoints(a, b, c) +local ux, uy, uz = a[1] - b[1], a[2] - b[2], a[3] - b[3] + local vx, vy, vz = c[1] - b[1], c[2] - b[2], c[3] - b[3] + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l < 1e-12 then + return nil + end + nx, ny, nz = nx / l, ny / l, nz / l + return { nx, ny, nz, b[1] * nx + b[2] * ny + b[3] * nz } +end + +-- the base axis row (0..5) of TextureAxisFromPlane: the first with the largest dot product (strictly greater) +function Brush.baseAxis(n) +local best, axis = 0, 0 + for i = 0, 5 do + local a = BASEAXIS[i * 3 + 1] + local d = n[1] * a[1] + n[2] * a[2] + n[3] * a[3] + if d > best then + best, axis = d, i + end + end + return axis +end + +-- Quake standard texture vectors (texels): offsets, rotation (degrees), scales (0 = 1) +function Brush.quakeVecs(n, xoff, yoff, rot, xscale, yscale) +local axis = Brush.baseAxis(n) + local s0, t0 = BASEAXIS[axis * 3 + 2], BASEAXIS[axis * 3 + 3] + local vecs = { { s0[1], s0[2], s0[3] }, { t0[1], t0[2], t0[3] } } + local sinv, cosv + if rot == 0 then + sinv, cosv = 0, 1 + elseif rot == 90 then + sinv, cosv = 1, 0 + elseif rot == 180 then + sinv, cosv = 0, -1 + elseif rot == 270 then + sinv, cosv = -1, 0 + else + local ang = rot / 180 * math.pi + sinv, cosv = sin(ang), cos(ang) + end + local sv = vecs[1][1] ~= 0 and 1 or(vecs[1][2] ~= 0 and 2 or 3 +) local tv = vecs[2][1] ~= 0 and 1 or(vecs[2][2] ~= 0 and 2 or 3 +) for i = 1, 2 do + local v = vecs[i] + local ns = cosv * v[sv] - sinv * v[tv] + local nt = sinv * v[sv] + cosv * v[tv] + v[sv], v[tv] = ns, nt + end + local sc = { xscale == 0 and 1 or xscale, yscale == 0 and 1 or yscale } + for i = 1, 2 do + local v = vecs[i] + v[1], v[2], v[3] = v[1] / sc[i], v[2] / sc[i], v[3] / sc[i] + end + vecs[1][4], vecs[2][4] = xoff, yoff + return vecs +end + +-- Valve 220: u / v = axis (x, y, z, offset); the rotation is already in the axes +function Brush.valveVecs(u, v, xscale, yscale) +local su, sv = xscale == 0 and 1 or xscale, yscale == 0 and 1 or yscale + return { { u[1] / su, u[2] / su, u[3] / su, u[4] }, { v[1] / sv, v[2] / sv, v[3] / sv, v[4] } } +end + +-- q3map2 ComputeAxisBase: the texture plane axes of a brush-primitive face +function Brush.axisBase(normal) +local nx, ny, nz = normal[1], normal[2], normal[3] + nx = abs(nx) < 1e-6 and 0 or nx + ny = abs(ny) < 1e-6 and 0 or ny + nz = abs(nz) < 1e-6 and 0 or nz + local rotY = -atan2(nz, sqrt(ny * ny + nx * nx)) + local rotZ = atan2(ny, nx) + return { -sin(rotZ), cos(rotZ), 0 }, { -sin(rotY) * cos(rotZ), -sin(rotY) * sin(rotZ), -cos(rotY) } +end + +-- brush primitives -> texel vectors for a w x h texture (ericw-tools SetTexinfo_BrushPrimitives) +function Brush.bpVecs(normal, m, w, h) +local tx, ty = Brush.axisBase(normal) + local out = {} + for i, size in __iter({ w, h }) do + local r = m[i] + out[i] = { size * (tx[1] * r[1] + ty[1] * r[2]), size * (tx[2] * r[1] + ty[2] * r[2]), size * (tx[3] * r[1] + ty[3] * r[2]), size * r[3] } + end + return out +end + +-- texel vectors -> brush primitives (the inverse of bpVecs for vectors lying in the face plane) +function Brush.vecsToBp(normal, vecs, w, h) +local tx, ty = Brush.axisBase(normal) + local out = {} + for i, size in __iter({ w, h }) do + local v = vecs[i] + out[i] = { + (v[1] * tx[1] + v[2] * tx[2] + v[3] * tx[3]) / size, + (v[1] * ty[1] + v[2] * ty[2] + v[3] * ty[3]) / size, + v[4] / size, + } + end + return out +end + +-- texture coordinates of a point on a face, in texture widths / heights (glTF uv: t grows down the image) +function Brush.uv(face, x, y, z, w, h) +local bp = face.bp + if bp then + local tx, ty = Brush.axisBase(face.plane) + local a = x * tx[1] + y * tx[2] + z * tx[3] + local b = x * ty[1] + y * ty[2] + z * ty[3] + return bp[1][1] * a + bp[1][2] * b + bp[1][3], bp[2][1] * a + bp[2][2] * b + bp[2][3] + end + local v = face.vecs + if v then + local s, t = v[1], v[2] + return (x * s[1] + y * s[2] + z * s[3] + s[4]) / w, (x * t[1] + y * t[2] + z * t[3] + t[4]) / h + end + return 0, 0 +end + +-- qbsp BaseWindingForPlane: a square of half size `size` on the plane, counter-clockwise seen from the front +function Brush.baseWinding(p, size) +local nx, ny, nz, d = p[1], p[2], p[3], p[4] + local ax, ay, az = abs(nx), abs(ny), abs(nz) + local ux, uy, uz = 0, 0, 1 + if az >= ax and az >= ay then + ux, uy, uz = 1, 0, 0 + end + local dv = ux * nx + uy * ny + uz * nz + ux, uy, uz = ux - dv * nx, uy - dv * ny, uz - dv * nz + local l = sqrt(ux * ux + uy * uy + uz * uz) + ux, uy, uz = ux / l * size, uy / l * size, uz / l * size + -- right = up x n, so right x up = n: right -> up turns counter-clockwise about n + local rx, ry, rz = (uy * nz - uz * ny), (uz * nx - ux * nz), (ux * ny - uy * nx) + local ox, oy, oz = nx * d, ny * d, nz * d + return { + ox - rx - ux, oy - ry - uy, oz - rz - uz, + ox + rx - ux, oy + ry - uy, oz + rz - uz, + ox + rx + ux, oy + ry + uy, oz + rz + uz, + ox - rx + ux, oy - ry + uy, oz - rz + uz, + } +end + +-- splits a polygon by a plane: the parts in front and behind (nil when empty), and whether it lies on the plane +function Brush.split(pts, p, eps) +local n = math.floor(#pts / 3 +) local nx, ny, nz, d = p[1], p[2], p[3], p[4] + local dist = (table.create(n, 0) ) +local side = (table.create(n, 0) ) +local front, back = 0, 0 + for i = 0, n - 1 do + local v = pts[i * 3 + 1] * nx + pts[i * 3 + 2] * ny + pts[i * 3 + 3] * nz - d + dist[i + 1] = v + if v > eps then + side[i + 1] = 1 + front =front+ 1 + elseif v < -eps then + side[i + 1] = -1 + back =back+ 1 + end + end + if front == 0 and back == 0 then + return nil, nil, true + end + if front == 0 then + return nil, pts, false + end + if back == 0 then + return pts, nil, false + end + local f, b= {}, {} + for i = 0, n - 1 do + local j = (i + 1) % n + local x, y, z = pts[i * 3 + 1], pts[i * 3 + 2], pts[i * 3 + 3] + local si = side[i + 1] + if si >= 0 then + f[#f + 1], f[#f + 2], f[#f + 3] = x, y, z + end + if si <= 0 then + b[#b + 1], b[#b + 2], b[#b + 3] = x, y, z + end + local sj = side[j + 1] + if si ~= 0 and sj ~= 0 and si ~= sj then + local t = dist[i + 1] / (dist[i + 1] - dist[j + 1]) + local mx, my, mz = x + t * (pts[j * 3 + 1] - x), y + t * (pts[j * 3 + 2] - y), z + t * (pts[j * 3 + 3] - z) + -- exact on axis-aligned planes, as qbsp + if nx == 1 then + mx = d + elseif nx == -1 then + mx = -d + end + if ny == 1 then + my = d + elseif ny == -1 then + my = -d + end + if nz == 1 then + mz = d + elseif nz == -1 then + mz = -d + end + f[#f + 1], f[#f + 2], f[#f + 3] = mx, my, mz + b[#b + 1], b[#b + 2], b[#b + 3] = mx, my, mz + end + end + return ((#f >= 9 and{f }or{nil})[1]), ((#b >= 9 and{b }or{nil})[1]), false +end + +-- removes repeated and colinear corners; nil when fewer than 3 remain +local function clean(pts, eps) +local out= {} + local n = math.floor(#pts / 3 +) for i = 0, n - 1 do + local x, y, z = snap(pts[i * 3 + 1]), snap(pts[i * 3 + 2]), snap(pts[i * 3 + 3]) + local m = #out + if m < 3 or abs(out[m - 2] - x) > eps or abs(out[m - 1] - y) > eps or abs(out[m] - z) > eps then + out[m + 1], out[m + 2], out[m + 3] = x, y, z + end + end + while #out >= 6 and abs(out[1] - out[#out - 2]) <= eps and abs(out[2] - out[#out - 1]) <= eps and abs(out[3] - out[#out]) <= eps do + out[#out], out[#out - 1], out[#out - 2] = nil, nil, nil + end + -- colinear corners + local changed = true + while changed and #out >= 9 do + changed = false + local k = math.floor(#out / 3 +) for i = 0, k - 1 do + local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 + local ux, uy, uz = out[b + 1] - out[a + 1], out[b + 2] - out[a + 2], out[b + 3] - out[a + 3] + local vx, vy, vz = out[c + 1] - out[b + 1], out[c + 2] - out[b + 2], out[c + 3] - out[b + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) + if lu * lv == 0 or sqrt(cx * cx + cy * cy + cz * cz) <= 1e-9 * lu * lv then + table.remove(out, b + 3) + table.remove(out, b + 2) + table.remove(out, b + 1) + changed = true + break + end + end + end + return (#out >= 9 and{out }or{nil +})[1]end + +local function samePlane(a, b, eps) +return abs(a[1] - b[1]) < 1e-5 and abs(a[2] - b[2]) < 1e-5 and abs(a[3] - b[3]) < 1e-5 and abs(a[4] - b[4]) < eps +end + +local function oppositePlane(a, b, eps) +return abs(a[1] + b[1]) < 1e-5 and abs(a[2] + b[2]) < 1e-5 and abs(a[3] + b[3]) < 1e-5 and abs(a[4] + b[4]) < eps +end + +-- one polygon per plane of a convex brush (nil for planes clipped away or repeating an earlier plane) +function Brush.windings(planes, opts) +local eps = opts and opts.epsilon or 1e-3 + local size = opts and opts.size or 2 ^ 17 + local out= {} + for i, p in __iter(planes) do + local w= Brush.baseWinding(p, size) + for j, q in __iter(planes) do + if not w then + break + end + if j ~= i then + if samePlane(p, q, eps) then + if j < i then + w = nil + end + else + local _, back, on = Brush.split(w, q, eps) + w = (on and{nil }or{back +})[1] end + end + end + out[i] = (w and{(clean(w, eps) )}or{nil +})[1] end + return out +end + +local function bounds(polys) +local b = { math.huge, math.huge, math.huge, -math.huge, -math.huge, -math.huge } + for _, p in __iter(polys) do + local pts = p.points + for k = 0, math.floor(#pts / 3 )- 1 do + for c = 1, 3 do + local v = pts[k * 3 + c] + b[c] = min(b[c], v) + b[c + 3] = max(b[c + 3], v) + end + end + end + return b +end + +-- the parts of pts (on plane `own` of brush a) outside brush b +local function outside(pts, own, a, b, planes, eps) +local kept= {} + local inside= pts + for _, q in __iter(planes) do + if not inside then + break + end + if samePlane(own, q, eps) then + if a < b then + return { pts } + end + elseif not oppositePlane(own, q, eps) then + local front, back = Brush.split(inside, q, eps) + if front then + table.insert(kept, front) + end + inside = back + end + end + return kept +end + +local function faceKey(f) +local parts = { f.texture or "" } + for _, m in __iter({ f.vecs, f.bp }) do + if m then + for _, row in __iter(m) do + for _, v in __iter(row) do + table.insert(parts, string.format("%.6g", v)) + end + end + end + end + return table.concat(parts, " ") +end + +local function convex(pts, n, eps) +local k = math.floor(#pts / 3 +) for i = 0, k - 1 do + local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 + local ux, uy, uz = pts[b + 1] - pts[a + 1], pts[b + 2] - pts[a + 2], pts[b + 3] - pts[a + 3] + local vx, vy, vz = pts[c + 1] - pts[b + 1], pts[c + 2] - pts[b + 2], pts[c + 3] - pts[b + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) + if (cx * n[1] + cy * n[2] + cz * n[3]) < -eps * max(lu, lv, 1) then + return false + end + end + return true +end + +-- qbsp TryMerge: two polygons sharing an edge (in opposite directions) -> their union, when convex +local function tryMerge(f1, f2, n, eps) +local n1, n2 = math.floor(#f1 / 3), math.floor(#f2 / 3 +) for i = 0, n1 - 1 do + local i2 = (i + 1) % n1 + for j = 0, n2 - 1 do + local j2 = (j + 1) % n2 + local match = true + for c = 1, 3 do + if abs(f1[i * 3 + c] - f2[j2 * 3 + c]) > eps or abs(f1[i2 * 3 + c] - f2[j * 3 + c]) > eps then + match = false + break + end + end + if match then + local out= {} + for k = 0, n1 - 1 do + local s = ((i2 + k) % n1) * 3 + out[#out + 1], out[#out + 2], out[#out + 3] = f1[s + 1], f1[s + 2], f1[s + 3] + end + for k = 2, n2 - 1 do + local s = ((j + k) % n2) * 3 + out[#out + 1], out[#out + 2], out[#out + 3] = f2[s + 1], f2[s + 2], f2[s + 3] + end + local c = clean(out, eps) + if c and convex(c, n, eps) then + return c + end + return nil + end + end + end + return nil +end + +local function mergeAll(polys, faces, eps) +local groups= {} + local order= {} + for _, p in __iter(polys) do + local f = faces[p.brush][p.face] + local pl = f.plane + local key = string.format("%.5f %.5f %.5f %.3f|", pl[1], pl[2], pl[3], pl[4]) .. faceKey(f) + local g = groups[key] + if not g then + g = {} + groups[key] = g + table.insert(order, key) + end + table.insert(g, p) + end + local out= {} + for _, key in __iter(order) do + local g = groups[key] + local changed = true + while changed do + changed = false + for a = 1, #g do + for b = a + 1, #g do + local m = tryMerge(g[a].points, g[b].points, g[a].normal, eps) + if m then + g[a] = { brush = g[a].brush, face = g[a].face, points = m, normal = g[a].normal } + table.remove(g, b) + changed = true + break + end + end + if changed then + break + end + end + end + for _, p in __iter(g) do + table.insert(out, p) + end + end + return out +end + +-- every brush's faces -> polygons (brushes[i] is a list of faces); nil, message past opts.maxPolygons +function Brush.polygons(brushes, opts) +local eps = opts and opts.epsilon or 1e-3 + local limit = opts and opts.maxPolygons or 2 ^ 20 + local per= {} + local planesOf= {} + local count = 0 + for bi, faces in __iter(brushes) do + local planes= {} + for fi, f in __iter(faces) do + planes[fi] = f.plane + end + planesOf[bi] = planes + local list= {} + local ws = Brush.windings(planes, opts) + for fi = 1, #faces do + local w = ws[fi] + if w then + table.insert(list, { brush = bi, face = fi, points = w, normal = { planes[fi][1], planes[fi][2], planes[fi][3] } }) + end + end + per[bi] = list + count =count+ #list + if count > limit then + return nil, "limit: too many brush faces" + end + end + local all= {} + if opts and opts.hull then + local boxes= {} + for bi = 1, #brushes do + boxes[bi] = bounds(per[bi]) + end + for bi = 1, #brushes do + for _, p in __iter(per[bi]) do + local frags= { p.points } + local own = brushes[bi][p.face].plane + local pb = bounds({ p }) + for bj = 1, #brushes do + if #frags == 0 then + break + end + local ob = boxes[bj] + if bj ~= bi and #per[bj] > 0 and pb[1] <= ob[4] + eps and pb[4] >= ob[1] - eps and pb[2] <= ob[5] + eps + and pb[5] >= ob[2] - eps and pb[3] <= ob[6] + eps and pb[6] >= ob[3] - eps then + local nextFrags= {} + for _, fr in __iter(frags) do + for _, kept in __iter(outside(fr, own, bi, bj, planesOf[bj], eps)) do + table.insert(nextFrags, kept) + end + end + frags = nextFrags + if #frags > limit then + return nil, "limit: too many brush fragments" + end + end + end + for _, fr in __iter(frags) do + local c = clean(fr, eps) + if c then + table.insert(all, { brush = p.brush, face = p.face, points = c, normal = p.normal }) + end + end + end + end + else + for bi = 1, #brushes do + for _, p in __iter(per[bi]) do + table.insert(all, p) + end + end + end + if opts and opts.merge then + all = mergeAll(all, brushes, eps) + end + return all, nil +end + +-- polygon area (for checks against compilers) +function Brush.area(pts) +local n = math.floor(#pts / 3 +) local ax, ay, az = 0, 0, 0 + for k = 1, n - 2 do + local ux, uy, uz = pts[k * 3 + 1] - pts[1], pts[k * 3 + 2] - pts[2], pts[k * 3 + 3] - pts[3] + local vx, vy, vz = pts[k * 3 + 4] - pts[1], pts[k * 3 + 5] - pts[2], pts[k * 3 + 6] - pts[3] + ax =ax+ (uy * vz - uz * vy +) ay =ay+ (uz * vx - ux * vz +) az =az+ (ux * vy - uy * vx +) end + return sqrt(ax * ax + ay * ay + az * az) / 2 +end + +-- polygons -> one indexed triangle primitive per texture, in order of first use. size(name) gives a texture's +-- width, height (texel projections divide by them) +function Brush.primitives(polys, brushes, size) + +local byTex= {} + local order= {} + local sizes= {} + for _, p in __iter(polys) do + local f = brushes[p.brush][p.face] + local name = f.texture or "" + local acc = byTex[name] + if not acc then + acc = { texture = name, pos = {}, nrm = {}, uv = {}, idx = {} } + byTex[name] = acc + table.insert(order, acc) + end + local sz = sizes[name] + if not sz then + local w, h = size(name) + sz = { math.max(w, 1), math.max(h, 1) } + sizes[name] = sz + end + local a= acc + local pts = p.points + local n = math.floor(#pts / 3 +) local base = math.floor(#a.pos / 3 +) for k = 0, n - 1 do + local x, y, z = pts[k * 3 + 1], pts[k * 3 + 2], pts[k * 3 + 3] + local pp, nn, uu = a.pos, a.nrm, a.uv + pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z + nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = p.normal[1], p.normal[2], p.normal[3] + local u, v = Brush.uv(f, x, y, z, sz[1], sz[2]) + uu[#uu + 1], uu[#uu + 2] = u, v + end + local ii = a.idx + for k = 1, n - 2 do + ii[#ii + 1], ii[#ii + 2], ii[#ii + 3] = base, base + k, base + k + 1 + end + end + local out= {} + for _, a in __iter(order) do + local nv, ni = math.floor(#a.pos / 3), #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + local S = Types.Scene + table.insert(out, { + texture = a.texture, + primitive = { + attributes = { POSITION = S.accessor(pb, "f32", 3, nv), NORMAL = S.accessor(nb, "f32", 3, nv), TEXCOORD_0 = S.accessor(ub, "f32", 2, nv) }, + indices = S.accessor(ib, "u32", 1, ni), + mode = "triangles" , + }, + }) + end + return out +end + +return Brush +end __FILES["codecs/model/Draco"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). @@ -83018,6 +84368,130 @@ end return Packed end +__FILES["codecs/model/Patch"] = function() +local __compat = __compat local __iter = __compat.__iter --!strict +--!native +--!optimize 2 +-- codecs/model/Patch: Quake III / Doom 3 Bezier patches (control grids) -> evaluated grids, triangles, normals. +-- A w x h grid (w, h odd, >= 3) is a mesh of 3 x 3 biquadratic sub-patches (Unofficial Quake 3 Map Specs; patchDef2 / +-- patchDef3), evaluated at fixed segments per sub-patch and axis (patchDef3's explicit subdivisions; Quake III's adaptive +-- subdivision is not reproduced). Shared edges are evaluated once. +local Patch = {} + +local sqrt = math.sqrt + +function Patch.valid(w, h, n) +return w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n +end + +-- ctrl: w * h points of comps numbers, row-major (row j holds points j * w .. j * w + w - 1); returns the evaluated grid +-- (gw * gh points of comps numbers, row-major) and its size; nil when the grid is not w x h odd or a limit is passed +function Patch.grid(ctrl, w, h, comps, levelU, levelV, maxPoints) +local lu, lv = math.max(1, math.floor(levelU)), math.max(1, math.floor(levelV)) + if not Patch.valid(w, h, math.floor(#ctrl / comps)) or #ctrl ~= w * h * comps then + return nil, 0, 0 + end + local px, py = math.floor((w - 1) / 2), math.floor((h - 1) / 2 +) local gw, gh = px * lu + 1, py * lv + 1 + if gw * gh > (maxPoints or 2 ^ 24) then + return nil, 0, 0 + end + local out = (table.create(gw * gh * comps, 0) ) +for gy = 0, gh - 1 do + local sy = math.min(math.floor(gy / lv), py - 1) + local tv = (gy - sy * lv) / lv + local bv0, bv1, bv2 = (1 - tv) * (1 - tv), 2 * tv * (1 - tv), tv * tv + for gx = 0, gw - 1 do + local sx = math.min(math.floor(gx / lu), px - 1) + local tu = (gx - sx * lu) / lu + local bu0, bu1, bu2 = (1 - tu) * (1 - tu), 2 * tu * (1 - tu), tu * tu + local o = (gy * gw + gx) * comps + for j = 0, 2 do + local bv = (j == 0 and{bv0 }or{(j == 1 and{bv1 }or{bv2 +})[1]})[1] local row = ((sy * 2 + j) * w + sx * 2) * comps + for i = 0, 2 do + local wgt = bv * ((i == 0 and{bu0 }or{(i == 1 and{bu1 }or{bu2})[1]})[1]) + local c = row + i * comps + for k = 1, comps do +do local __DARKLUA_VAR=o + k out[__DARKLUA_VAR]=out[__DARKLUA_VAR]+ ctrl[c + k] * wgt +end end + end + end + end + end + return out, gw, gh +end + +-- 0-based triangle indices over a gw x gh grid; Quake's control grids are clockwise-front, these are counter-clockwise +function Patch.triangles(gw, gh) +local out = (table.create(math.max(0, (gw - 1) * (gh - 1) * 6)) ) +for gy = 0, gh - 2 do + for gx = 0, gw - 2 do + local a, b = gy * gw + gx, gy * gw + gx + 1 + local d, e = a + gw, b + gw + local n = #out + out[n + 1], out[n + 2], out[n + 3] = a, d, b + out[n + 4], out[n + 5], out[n + 6] = b, d, e + end + end + return out +end + +-- renormalizes the vec3 at component offset at (0-based) of every point +function Patch.normalize(pts, comps, at) + for o = 0, #pts - comps, comps do + local x, y, z = pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] = x / l, y / l, z / l + end + end +end + +-- unit normals (3 per point) of the evaluated grid from the positions (components 1..3), facing the front of +-- Patch.triangles; points where the surface degenerates take a neighbour's normal +function Patch.normals(pts, comps, gw, gh) +local out = (table.create(gw * gh * 3, 0) ) +local function at(x, y, k) +return pts[(y * gw + x) * comps + k] + end + for gy = 0, gh - 1 do + local y0, y1 = math.max(gy - 1, 0), math.min(gy + 1, gh - 1) + for gx = 0, gw - 1 do + local x0, x1 = math.max(gx - 1, 0), math.min(gx + 1, gw - 1) + local ux, uy, uz = at(x1, gy, 1) - at(x0, gy, 1), at(x1, gy, 2) - at(x0, gy, 2), at(x1, gy, 3) - at(x0, gy, 3) + local vx, vy, vz = at(gx, y1, 1) - at(gx, y0, 1), at(gx, y1, 2) - at(gx, y0, 2), at(gx, y1, 3) - at(gx, y0, 3) + local nx, ny, nz = vy * uz - vz * uy, vz * ux - vx * uz, vx * uy - vy * ux + local l = sqrt(nx * nx + ny * ny + nz * nz) + local o = (gy * gw + gx) * 3 + if l > 1e-12 then + out[o + 1], out[o + 2], out[o + 3] = nx / l, ny / l, nz / l + end + end + end + for _ = 1, 2 do + for i = 0, gw * gh - 1 do + local o = i * 3 + if out[o + 1] == 0 and out[o + 2] == 0 and out[o + 3] == 0 then + local x, y = i % gw, math.floor(i / gw +) for _, d in __iter({ { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 }, { 1, 1 }, { -1, -1 }, { 1, -1 }, { -1, 1 } }) do + local nx2, ny2 = x + d[1], y + d[2] + if nx2 >= 0 and nx2 < gw and ny2 >= 0 and ny2 < gh then + local q = (ny2 * gw + nx2) * 3 + if out[q + 1] ~= 0 or out[q + 2] ~= 0 or out[q + 3] ~= 0 then + out[o + 1], out[o + 2], out[o + 3] = out[q + 1], out[q + 2], out[q + 3] + break + end + end + end + end + end + end + return out +end + +return Patch +end __FILES["codecs/model/Polygon"] = function() local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict -- codecs/model/Polygon: 2D polygons with holes to triangles by hole bridging and ear clipping. New code. @@ -120679,6 +122153,341 @@ end return Binary end +__FILES["data/q3shader"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- data/q3shader: Quake III shader scripts (.shader; the Quake III Arena Shader Manual, tr_shader.c tokenizing: no code +-- taken), read and write. A script is a list of shaders { name, directives, stages }; a directive is its tokens +-- ({ "surfaceparm", "nolightmap" }, one line each), a stage is a list of directives. Keywords keep their case. +-- Comments (// and /* */) are dropped. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +-- ------------------------------------------------------------------------------------------------ contract +local Q3Shader = { + name = "q3shader", + category = "data", + extensions = { "shader" }, + mime = { "text/x-quake3-shader" }, + deps = { "core/Err", "core/Bytes" }, + caps = { decode = true, encode = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + +local KEYWORDS = { "surfaceparm", "map", "clampmap", "animmap", "blendfunc", "rgbgen", "alphagen", "tcgen", "tcmod", + "cull", "deformvertexes", "qer_editorimage", "nopicmip", "nomipmaps", "skyparms", "q3map_", "depthwrite", "alphafunc" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Q3Shader.sniff(r) +local head = r:peek(math.min(r:remaining(), 2048)) + if #head < 4 or string.find(head, "[%z\1-\8\14-\31]") then + return 0 + end + local s = string.gsub(string.gsub(head, "/%*.-%*/", " "), "//[^\n]*", "") + if not string.match(s, "^%s*[^%s{}\"]+%s*{") then + return 0 + end + local lower = string.lower(s) + for _, k in __iter(KEYWORDS) do + if string.find(lower, "%f[%w_]" .. k) then + return 0.7 + end + end + return 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the token lines of a script; braces are lines of their own +local function lex(text) +local lines= {} + local cur= {} + local i, n = 1, #text + local function flush() + if #cur > 0 then + table.insert(lines, cur) + cur = {} + end + end + while i <= n do + local c = string.sub(text, i, i) + if c == "\n" then + flush() + i =i+ 1 + elseif string.match(c, "%s") then + i =i+ 1 + elseif string.sub(text, i, i + 1) == "//" then + local e = string.find(text, "\n", i, true) + i = e or n + 1 + elseif string.sub(text, i, i + 1) == "/*" then + local _, e = string.find(text, "*/", i + 2, true) + if not e then + return nil, "unterminated comment" + end + for _ in __iter(string.gmatch(string.sub(text, i, e), "\n")) do + flush() + end + i = e + 1 + elseif c == "{" or c == "}" then + flush() + table.insert(lines, { c }) + i =i+ 1 + elseif c == '"' then + local e = string.find(text, '"', i + 1, true) + if not e then + return nil, "unterminated string" + end + table.insert(cur, string.sub(text, i + 1, e - 1)) + i = e + 1 + else + local _, e = string.find(text, "^[^%s{}\"]+", i) + local stop = e +local tok = string.sub(text, i, stop) + local cm = string.find(tok, "//", 1, true) + if cm and cm > 1 then + tok = string.sub(tok, 1, cm - 1) + stop = i + cm - 2 + end + table.insert(cur, tok) + i = stop + 1 + end + end + flush() + return lines, nil +end + +function Q3Shader.decode(r) +local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local lines, msg = lex(text) + if not lines then + return nil, Err.new(Err.CORRUPT, msg or "bad script") + end + local out= {} + local k = 1 + while k <= #lines do + local l = lines[k] + if #l ~= 1 or l[1] == "{" or l[1] == "}" then + return nil, Err.new(Err.CORRUPT, "expected a shader name, got '" .. table.concat(l, " ") .. "'") + end + local sh= { name = l[1], directives = {}, stages = {} } + k =k+ 1 + if not lines[k] or lines[k][1] ~= "{" then + return nil, Err.new(Err.CORRUPT, "expected '{' after " .. sh.name) + end + k =k+ 1 + local stage= nil + local closed = false + while k <= #lines do + local d = lines[k] + k =k+ 1 + if d[1] == "{" then + if stage then + return nil, Err.new(Err.CORRUPT, "nested stage in " .. sh.name) + end + stage = {} + elseif d[1] == "}" then + if stage then + table.insert(sh.stages, stage) + stage = nil + else + closed = true + break + end + elseif stage then + table.insert(stage, d) + else + table.insert(sh.directives, d) + end + end + if not closed then + return nil, Err.new(Err.TRUNCATED, "shader " .. sh.name .. " not closed") + end + table.insert(out, sh) + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function tokens(d) +if type(d) ~= "table" or #d == 0 then + return nil, "a directive is a list of strings" + end + local parts = {} + for _, t in __iter(d) do + local s = tostring(t) + if s == "" or string.find(s, "[%s{}]") then + if string.find(s, '"', 1, true) or string.find(s, "\n") then + return nil, "token cannot hold quotes or line breaks: " .. s + end + s = '"' .. s .. '"' + end + table.insert(parts, s) + end + return table.concat(parts, " "), nil +end + +function Q3Shader.encode(list, opts) +if type(list) ~= "table" then + return nil, Err.new(Err.ARG, "expected a list of shaders") + end + local ind = opts and opts.indent or "\t" + local out= {} + for _, sh in __iter(list) do + if type(sh) ~= "table" or type(sh.name) ~= "string" or sh.name == "" or string.find(sh.name, "[%s{}\"]") then + return nil, Err.new(Err.ARG, "a shader needs a name without spaces") + end + table.insert(out, sh.name) + table.insert(out, "{") + for _, d in __iter(sh.directives or {}) do + local line, e = tokens(d) + if not line then + return nil, Err.new(Err.ARG, e or "bad directive") + end + table.insert(out, ind .. line) + end + for _, st in __iter(sh.stages or {}) do + table.insert(out, ind .. "{") + for _, d in __iter(st) do + local line, e = tokens(d) + if not line then + return nil, Err.new(Err.ARG, e or "bad directive") + end + table.insert(out, ind .. ind .. line) + end + table.insert(out, ind .. "}") + end + table.insert(out, "}") + table.insert(out, "") + end + return buffer.fromstring(table.concat(out, "\n")), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- the shader named name (case-insensitive, as the game looks them up) +function Q3Shader.find(list, name) +local want = string.lower(name) + for _, sh in __iter(list) do + if string.lower(sh.name) == want then + return sh + end + end + return nil +end + +-- the first directive starting with keyword (case-insensitive) in a shader or stage directive list +function Q3Shader.directive(list, keyword) +local want = string.lower(keyword) + for _, d in __iter(list) do + if string.lower(d[1] or "") == want then + return d + end + end + return nil +end + +return Q3Shader +end +__FILES["data/q3skin"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- data/q3skin: Quake III model skins (.skin: "surface,shader" lines, "tag_*," for tags; tr_image.c RE_RegisterSkin, no +-- code taken), read and write. Decodes to a list of { surface, shader } in file order (shader "" for tags). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") + +-- ------------------------------------------------------------------------------------------------ contract +local Q3Skin = { + name = "q3skin", + category = "data", + extensions = { "skin" }, + mime = { "text/x-quake3-skin" }, + deps = { "core/Err", "core/Bytes" }, + caps = { decode = true, encode = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + +function Q3Skin.sniff(r) +local head = r:peek(math.min(r:remaining(), 1024)) + if #head < 3 or string.find(head, "[%z\1-\8\14-\31]") then + return 0 + end + local lines, good, paths = 0, 0, 0 + for line in __iter(string.gmatch(head, "[^\r\n]+")) do + if not string.match(line, "^%s*$") then + lines =lines+ 1 + local surface, shader = string.match(line, "^%s*([%w_%-]+)%s*,%s*([^,%s]*)%s*$") + if surface and shader == "" and string.sub(string.lower(surface), 1, 4) == "tag_" then + good =good+ 1 + elseif shader and string.find(shader, "/", 1, true) then + good =good+ 1 + paths =paths+ 1 + end + end + end + return lines > 0 and good == lines and paths > 0 and 0.5 or 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Q3Skin.decode(r) +local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local out= {} + local n = 0 + for line in __iter(string.gmatch(text, "[^\r\n]+")) do + n =n+ 1 + local s = (string.match(line, "^%s*(.-)%s*$") ) +if s ~= "" and string.sub(s, 1, 2) ~= "//" then + local surface, shader = string.match(s, "^([^,]-)%s*,%s*(.-)$") + if not surface or surface == "" then + return nil, Err.new(Err.CORRUPT, "line " .. n .. ": expected surface,shader") + end + table.insert(out, { surface = surface, shader = shader }) + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Q3Skin.encode(list) +if type(list) ~= "table" then + return nil, Err.new(Err.ARG, "expected a list of { surface, shader }") + end + local out= {} + for _, e in __iter(list) do + if type(e) ~= "table" or type(e.surface) ~= "string" or e.surface == "" or string.find(e.surface, "[,\r\n]") then + return nil, Err.new(Err.ARG, "a skin entry needs a surface name without commas") + end + local sh = e.shader == nil and"" or tostring(e.shader) + if string.find(sh, "[,\r\n]") then + return nil, Err.new(Err.ARG, "a shader path cannot hold commas or line breaks") + end + table.insert(out, e.surface .. "," .. sh) + end + table.insert(out, "") + return buffer.fromstring(table.concat(out, "\n")), nil +end + +-- the shader of a surface (case-insensitive) +function Q3Skin.shader(list, surface) +local want = string.lower(surface) + for _, e in __iter(list) do + if string.lower(e.surface) == want then + return e.shader + end + end + return nil +end + +return Q3Skin +end __FILES["data/snbt"] = function() local __compat = __compat local buffer = __compat.buffer --!strict -- data/snbt: stringified NBT over codecs/text/Nbt. Supports: parse to data/nbt's values, compact or indented print. @@ -133275,6 +135084,139 @@ end return Ktx end +__FILES["image/lmp"] = function() +local __compat = __compat local buffer, type = __compat.buffer, __compat.type --!strict +-- image/lmp: Quake .lmp lumps (wad.h / draw.c of the Quake source; no code taken), read and write: qpic pictures (u32 +-- width, height, 8-bit pixels; index 255 transparent), palette.lmp (768 bytes: a 16 x 16 swatch) and colormap.lmp (64 +-- light levels x 256: a 256 x 64 image). Pictures and colormaps need Quake's palette, which is never embedded (GPL): +-- opts.palette or gfx/palette.lmp through files / resolve; else grey (meta.source.palette = false). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") +local Miptex = __include("codecs/image/Miptex") + +-- ------------------------------------------------------------------------------------------------ contract +local Lmp = { + name = "lmp", + category = "image", + extensions = { "lmp" }, + mime = { "image/x-quake-lmp" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 }, variants = { "qpic", "palette", "colormap" } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + + + +local function kindOf(r) +local n = r:remaining() + if n == 768 then + return "palette" + elseif n == 16385 or n == 16384 then + return "colormap" + end + if n < 9 then + return nil + end + local w, h = buffer.readu32(r.buf, r.pos), buffer.readu32(r.buf, r.pos + 4) + if w > 0 and h > 0 and w <= 4096 and h <= 4096 and 8 + w * h == n then + return "qpic" + end + return nil +end + +function Lmp.sniff(r) +local k = kindOf(r) + return k == "qpic" and 0.3 or(k and 0.05 or 0 +)end + +-- ------------------------------------------------------------------------------------------------ decode +local function palette(opts) +local raw = (opts and opts.palette and{(Bytes.toBuffer(opts.palette) )}or{(Input.sibling(opts, "gfx/palette.lmp") +)})[1] if raw and buffer.len(raw) >= 768 then + return Pixels.palette(raw, 0, 256) + end + return nil +end + +function Lmp.decode(r, opts) +local kind = opts and opts.kind or kindOf(r) + local b, at, n = r.buf, r.base, r.limit - r.base + if kind == "palette" then + if n < 768 then + return nil, Err.new(Err.TRUNCATED, "palette", 0) + end + local img = Types.Image.new(16, 16) + buffer.copy(img.pixels, 0, Pixels.palette(b, at, 256), 0, 1024) + local list = Pixels.colorList(img.pixels) + img.meta.palette = list + img.meta.source = { format = "lmp", kind = "palette" } + return img, nil + end + local pal = palette(opts) + if kind == "colormap" then + local rows = math.min(64, math.floor(n / 256)) + if rows < 1 then + return nil, Err.new(Err.TRUNCATED, "colormap", 0) + end + local img = Types.Image.new(256, rows) + Pixels.indexed(b, at, 256, 8, img.pixels, 256, rows, true, pal or Pixels.grey()) + img.meta.source = { format = "lmp", kind = "colormap", palette = pal ~= nil } + return img, nil + end + if kind ~= "qpic" and n >= 8 then + kind = "qpic" + end + local img, msg = Miptex.qpic(b, at, n, { palette = pal, keyed = opts and opts.keyed, maxPixels = opts and opts.maxPixels }) + if not img then + return nil, Err.from(msg, 0) + end + img.meta.source = { format = "lmp", kind = "qpic", palette = pal ~= nil, keyed = (opts == nil or opts.keyed ~= false) or nil } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Lmp.encode(img, opts) +if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected an rgba8 Image") + end + if opts and opts.kind == "palette" then + if img.width * img.height < 256 then + return nil, Err.new(Err.ARG, "a palette needs 256 pixels (16 x 16)") + end + return Pixels.paletteBytes(img.pixels, 256), nil + end + local pal = palette(opts) + if not pal then + return nil, Err.new(Err.ARG, "a qpic needs Quake's palette (opts.palette or gfx/palette.lmp; it is not embedded)") + end + local out, msg = Miptex.encodeQpic(img, pal, false, true) + if not out then + return nil, Err.new(Err.ARG, msg or "cannot encode") + end + return out, nil +end + +return Lmp +end __FILES["image/pcx"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- image/pcx: ZSoft PC Paintbrush (ZSoft "Technical Reference Manual" header and RLE). Supports: 1-bit, 1-bit x 2..4 @@ -135806,6 +137748,319 @@ end return Sgi end +__FILES["image/spr"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- image/spr: Quake (IDSP 1), Half-Life (IDSP 2, own palette, texture formats) and DarkPlaces SPR32 (IDSP 32, rgba) +-- sprites, read and write (spritegn.h of the Quake source, the GoldSrc sprite layout; no code taken). Frames and frame +-- groups become Image frames on one canvas around the sprite origin (meta.origin); group intervals give the delays. +-- Quake sprites need Quake's palette (opts.palette or gfx/palette.lmp through files / resolve; never embedded). +-- Not supported: Quake II sprites (IDS2: frames are separate .pcx files). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Pixels = __include("codecs/image/Pixels") +local Miptex = __include("codecs/image/Miptex") + +-- ------------------------------------------------------------------------------------------------ contract +local Spr = { + name = "spr", + category = "image", + extensions = { "spr" }, + mime = { "image/x-quake-sprite" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, alpha = true, animation = true, variants = { "quake", "halflife", "spr32" } }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ constants + + + + + + + + + + + + + + + + +local TEX_FORMATS = { [0] = "normal", "additive", "indexalpha", "alphatest" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Spr.sniff(r) +if r:remaining() < 36 or r:peek(4) ~= "IDSP" then + return 0 + end + local v = buffer.readi32(r.buf, r.pos + 4) + return (v == 1 or v == 2 or v == 32 )and 1 or 0.3 +end +-- ------------------------------------------------------------------------------------------------ decode + + + +function Spr.decode(r, opts) +if r:string(4) ~= "IDSP" then + return nil, r.err or Err.new(Err.CORRUPT, "bad magic", 0) + end + local version = r:i32le() + if version ~= 1 and version ~= 2 and version ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, "sprite version " .. tostring(version), 4) + end + local stype = r:i32le() + local texFormat = (version == 2 and{(r:i32le() )}or{3 +})[1] local radius = r:f32le() + local mw, mh, nframes = r:i32le(), r:i32le(), r:i32le() + local beam, sync = r:f32le(), r:i32le() + if r.err then + return nil, r.err + end + local maxFrames = opts and opts.maxFrames or 4096 + local maxPixels = opts and opts.maxPixels or 2 ^ 24 + if nframes < 1 or nframes > maxFrames then + return nil, Err.new((nframes < 1 and{Err.CORRUPT }or{Err.LIMIT})[1], "frame count " .. nframes, 24) + end + local pal +local own = false + if version == 2 then + local n = r:u16le() + if r.err then + return nil, r.err + end + if n < 1 or n > 256 or not r:need(n * 3) then + return nil, r.err or Err.new(Err.CORRUPT, "palette size " .. n, r:tell() - 2) + end + pal = Pixels.palette(r.buf, r.pos, n) + r:skip(n * 3) + own = true + else + local raw = (opts and opts.palette and{(Bytes.toBuffer(opts.palette) )}or{(Input.sibling(opts, "gfx/palette.lmp") +)})[1] own = raw ~= nil and buffer.len(raw) >= 768 + pal = (raw and own and{(Pixels.palette(raw, 0, 256) )}or{(Pixels.grey() +)})[1] end + local bpp = version == 32 and 4 or 1 + local raws= {} + local groups= {} + local function single(delay) +local x, y, w, h = r:i32le(), r:i32le(), r:i32le(), r:i32le() + if r.err then + return r.err + end + if w < 1 or h < 1 then + return Err.new(Err.CORRUPT, "frame size " .. w .. " x " .. h, r:tell() - 8) + end + if w * h > maxPixels then + return Err.new(Err.LIMIT, "frame " .. w .. " x " .. h) + end + if not r:need(w * h * bpp) then + return r.err + end + table.insert(raws, { x = x, y = y, w = w, h = h, at = r.pos, delay = delay }) + r:skip(w * h * bpp) + return nil + end + for _ = 1, nframes do + local ft = r:i32le() + if r.err then + return nil, r.err + end + if ft == 0 then + local e = single(0.1) + if e then + return nil, e + end + table.insert(groups, { type = "single", count = 1 }) + else + local n = r:i32le() + if r.err then + return nil, r.err + end + if n < 1 or #raws + n > maxFrames then + return nil, Err.new((n < 1 and{Err.CORRUPT }or{Err.LIMIT})[1], "group of " .. n .. " frames", r:tell() - 4) + end + local ivs = {} + for k = 1, n do + ivs[k] = r:f32le() + end + if r.err then + return nil, r.err + end + for k = 1, n do + -- intervals are cumulative end times (R_GetSpriteFrame) + local e = single(math.max(0, ivs[k] - ((k > 1 and{ivs[k - 1] }or{0})[1]))) + if e then + return nil, e + end + end + table.insert(groups, { type = "group", count = n }) + end + end + local minX, maxX, minY, maxY= math.huge, -math.huge, math.huge, -math.huge + for _, f in __iter(raws) do + minX = math.min(minX, f.x) + maxX = math.max(maxX, f.x + f.w) + maxY = math.max(maxY, f.y) + minY = math.min(minY, f.y - f.h) + end + local cw, ch = maxX - minX, maxY - minY + if cw * ch > maxPixels then + return nil, Err.new(Err.LIMIT, "canvas " .. cw .. " x " .. ch) + end + local fpal = pal + if version ~= 2 or texFormat == 3 then + fpal = Pixels.keyed(pal, 255) + end + local b = r.buf + local frames= {} + for _, f in __iter(raws) do + local img = Types.Image.new(f.w, f.h) + if version == 32 then + buffer.copy(img.pixels, 0, b, f.at, f.w * f.h * 4) + elseif version == 2 and texFormat == 2 then + -- index alpha: the colour is the last palette entry, the index is the alpha + local c = bit32.band(buffer.readu32(pal, 255 * 4), 0xFFFFFF) + for k = 0, f.w * f.h - 1 do + buffer.writeu32(img.pixels, k * 4, c + buffer.readu8(b, f.at + k) * 0x1000000) + end + else + Pixels.indexed(b, f.at, f.w, 8, img.pixels, f.w, f.h, true, fpal) + end + table.insert(frames, { image = img, delay = f.delay, x = f.x - minX, y = maxY - f.y, dispose = "background", blend = "source" }) + end + local out = Types.Image.new(cw, ch) + local f1 = frames[1] + for yy = 0, f1.image.height - 1 do + buffer.copy(out.pixels, ((f1.y + yy) * cw + f1.x) * 4, f1.image.pixels, yy * f1.image.width * 4, f1.image.width * 4) + end + out.frames = (#frames > 1 and{frames }or{nil +})[1] out.loops = 0 + out.meta.origin = { -minX, maxY } + out.meta.source = { + format = "spr", version = version, type = stype, texFormat = (version == 2 and{TEX_FORMATS[texFormat] or texFormat }or{nil})[1], + radius = radius, width = mw, height = mh, beamLength = beam, sync = sync, groups = groups, + palette = own, origins = (function() + local o = {} + for i, f in __iter(raws) do + o[i] = { f.x, f.y } + end + return o + end)(), + } + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Spr.encode(img, opts) +if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected an rgba8 Image") + end + local version = opts and opts.version or 2 + if version ~= 1 and version ~= 2 and version ~= 32 then + return nil, Err.new(Err.ARG, "version must be 1, 2 or 32") + end + local list= {} + if img.frames and #img.frames > 0 then + for _, f in __iter(img.frames) do + if f.image.format ~= "rgba8" then + return nil, Err.new(Err.ARG, "frames must be rgba8") + end + table.insert(list, { image = f.image, x = f.x, y = f.y, delay = f.delay }) + end + else + table.insert(list, { image = img, x = 0, y = 0, delay = opts and opts.delay or 0.1 }) + end + local origin = img.meta and img.meta.origin or { math.floor(img.width / 2), math.floor(img.height / 2 )} + local mw, mh, alpha = 0, 0, false + for _, f in __iter(list) do + mw = math.max(mw, f.image.width) + mh = math.max(mh, f.image.height) + local px = f.image.pixels + for k = 0, f.image.width * f.image.height - 1 do + if buffer.readu8(px, k * 4 + 3) < 128 then + alpha = true + break + end + end + end + local pal= nil + if version == 1 then + local raw = (opts and opts.palette and{(Bytes.toBuffer(opts.palette) )}or{nil +})[1] if not raw or buffer.len(raw) < 768 then + return nil, Err.new(Err.ARG, "a Quake sprite needs Quake's palette (opts.palette; it is not embedded)") + end + pal = Pixels.palette(raw, 0, 256) + elseif version == 2 then + local raw = (opts and opts.palette and{(Bytes.toBuffer(opts.palette) )}or{nil +})[1] if raw and buffer.len(raw) >= 768 then + pal = Pixels.palette(raw, 0, 256) + else + -- one palette for every frame: the frames side by side + local tw = 0 + for _, f in __iter(list) do + tw =tw+ f.image.width + end + local strip = Types.Image.new(tw, mh) + local x0 = 0 + for _, f in __iter(list) do + for yy = 0, f.image.height - 1 do + buffer.copy(strip.pixels, (yy * tw + x0) * 4, f.image.pixels, yy * f.image.width * 4, f.image.width * 4) + end + x0 =x0+ f.image.width + end + local _, colors = Miptex.indices(strip, nil, alpha) + local p = buffer.create(1024) + for i, c in __iter(colors) do + buffer.writeu32(p, (i - 1) * 4, 0xFF000000 + c[3] * 65536 + c[2] * 256 + c[1]) + end + if alpha then + buffer.writeu32(p, 255 * 4, 0xFFFF0000) -- the alpha-test key: blue + end + pal = p + end + end + local texFormat = opts and opts.texFormat or (alpha and 3 or 0) + local w = Bytes.writer() + w:string("IDSP") + w:u32le(version) + w:u32le(opts and opts.type or 2) + if version == 2 then + w:u32le(texFormat) + end + w:f32le(math.sqrt(mw * mw + mh * mh) / 2) + w:u32le(mw) + w:u32le(mh) + w:u32le(#list) + w:f32le(0) + w:u32le(0) + if version == 2 then + w:u16le(256) + w:bytes(Pixels.paletteBytes(pal , 256)) + end + for _, f in __iter(list) do + local fw, fh = f.image.width, f.image.height + w:u32le(0) + w:u32le(bit32.band(f.x - origin[1], 0xFFFFFFFF)) + w:u32le(bit32.band(origin[2] - f.y, 0xFFFFFFFF)) + w:u32le(fw) + w:u32le(fh) + if version == 32 then + w:bytes(f.image.pixels, 0, fw * fh * 4) + else + local idx = Miptex.indices(f.image, pal, alpha and texFormat == 3 or version == 1) + w:bytes(idx, 0, fw * fh) + end + end + return w:finish(), nil +end + +return Spr +end __FILES["image/sunras"] = function() local __compat = __compat local buffer, bit32, type = __compat.buffer, __compat.bit32, __compat.type --!strict -- image/sunras: Sun Raster (rasterfile(5), SunOS ). Supports: 1-bit (0 = white without a colour map), @@ -146568,18 +148823,21 @@ end return Read end __FILES["model/bsp"] = function() -local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- model/bsp: compiled game maps, read: Quake 1 (BSP 29), Half-Life (BSP 30), Quake II (IBSP 38), Quake III / RTCW --- (IBSP 46 / 47). Quake textures need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up. --- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing. +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/bsp: compiled game maps, read: Quake 1 (BSP 29, BSP2, 2PSB), Half-Life (BSP 30), Quake II (IBSP 38), Quake III +-- / RTCW (IBSP 46 / 47). Lightmaps (Quake 1 / 2 / Half-Life: one atlas, Quake III: its pages) as TEXCOORD_1; the tree, +-- collision hulls / brushes and visibility in meta.bsp with point queries (Bsp.leafAt / contents / pvs). Quake textures +-- need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up. Not supported: Source engine VBSP, +-- light styles other than the first, BSPX lumps, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = __include("core/Err") local Bytes = __include("core/Bytes") local Input = __include("core/Input") local Types = __include("Types") -local Brush = __include("model/bsp/Brush") +local Quake = __include("model/bsp/Quake") local Quake3 = __include("model/bsp/Quake3") +local Tree = __include("model/bsp/Tree") -- ------------------------------------------------------------------------------------------------ contract local Bsp = { @@ -146587,8 +148845,8 @@ local Bsp = { category = "model", extensions = { "bsp" }, mime = { "model/x-bsp" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, - caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" }, + caps = { decode = true, encode = false, variants = { "quake", "bsp2", "2psb", "halflife", "quake2", "quake3" }, lightmaps = true, collision = true, visibility = true }, } -- ------------------------------------------------------------------------------------------------ types -- ------------------------------------------------------------------------------------------------ constants @@ -146602,6 +148860,10 @@ local Bsp = { + + + + local Q1_LUMPS = { "entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", "clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models" } local Q2_LUMPS = { "entities", "planes", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", "leaves", @@ -146616,6 +148878,9 @@ if r:remaining() < 64 then end local m = r:peek(4) local v = buffer.readi32(r.buf, r.pos + (m == "IBSP" and 4 or 0)) + if m == "BSP2" or m == "2PSB" then + v = 29 + end if m == "IBSP" then return (v == 38 or v == 46 or v == 47 )and 1 or 0.3 end @@ -146658,6 +148923,8 @@ if m == "IBSP" and version == 38 then names, dir, variant = Q2_LUMPS, 8, "q2" elseif m == "IBSP" and (version == 46 or version == 47) then names, dir, variant = Q3_LUMPS, 8, "q3" + elseif m == "BSP2" or m == "2PSB" then + names, dir, variant = Q1_LUMPS, 4, string.lower(m) elseif m ~= "IBSP" and (version == 29 or version == 30) then names, dir, variant = Q1_LUMPS, 4, version == 30 and"hl" or"q1" elseif m == "VBSP" then @@ -146684,13 +148951,15 @@ if variant == "q3" then )})[1] if pal and buffer.len(pal) < 768 then pal = nil end - scene, msg = Brush.decode(b, base, lumps, variant, { + scene, msg = Quake.decode(b, base, lumps, variant, { palette = pal, wal = function(name) return Input.sibling(opts, "textures/" .. name .. ".wal") end, maxPixels = opts and opts.maxPixels, maxVertices = opts and opts.maxVertices, + lit = (opts and opts.lit and{(Bytes.toBuffer(opts.lit) )}or{((opts and opts.name and{(Input.sibling(opts, (string.gsub(opts.name , "%.[^./\\]*$", "")) .. ".lit") )}or{nil})[1])})[1], + lightmaps = opts and opts.lightmaps, }) end if not scene then @@ -146702,28 +148971,129 @@ return Input.sibling(opts, "textures/" .. name .. ".wal") scene.meta.entities = entities(text) scene.meta.source = { format = "bsp", - variant = ({ q1 = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } )[variant], + variant = ({ q1 = "quake", bsp2 = "quake", ["2psb"] = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } )[variant], + layout = variant == "bsp2" and"BSP2" or(variant == "2psb" and"2PSB" or nil), version = version, entities = text, - palette = (variant == "q1" and{(opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) }or{nil})[1], + palette = ((variant == "q1" or variant == "bsp2" or variant == "2psb" )and{(opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) }or{nil})[1], } + if not (opts and opts.tree == false) then + local tree, terr = Tree.read(b, base, lumps, variant) + if not tree then + return nil, Err.from(terr) + end + scene.meta.bsp = tree + end return scene, nil end +-- ------------------------------------------------------------------------------------------------ extras +local function tree(scene) +return type(scene) == "table" and type(scene.meta) == "table" and scene.meta.bsp or nil +end + +-- the leaf (0-based) at a point, in the tree of a model (0 = the world) +function Bsp.leafAt(scene, x, y, z, model) +local d = tree(scene) + return (d and{(Tree.leafAt(d, x, y, z, model) )}or{nil +})[1]end + +-- the contents at a point: Quake 1 CONTENTS_* (-1 empty, -2 solid, ...; hull 0 point, 1 player, 2 shambler, 3 crouch +-- in Half-Life), Quake II / III contents bits +function Bsp.contents(scene, x, y, z, hull, model) +local d = tree(scene) + return (d and{(Tree.contents(d, x, y, z, hull, model) )}or{nil +})[1]end + +-- the leaves (0-based) potentially visible from a leaf; nil when the map has no visibility data +function Bsp.pvs(scene, leaf) +local d = tree(scene) + return (d and{(Tree.pvs(d, leaf) )}or{nil +})[1]end + return Bsp end -__FILES["model/bsp/Brush"] = function() +__FILES["model/bsp/Lightmap"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict --- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from bspfile.h of the --- Quake / Quake II source releases (no code taken). Texture coordinates: s = v . s.xyz + s.w, divided by the texture --- size. +-- model/bsp/Lightmap: packs face lightmaps (w x h luxels each) into one atlas, shelf by shelf, tallest first, each +-- with a one-luxel border that repeats its edge (bilinear filtering stays inside the face). +local Lightmap = {} + +-- nil, message past maxPixels + + +function Lightmap.pack(sizes, maxPixels) +local area, widest = 0, 1 + for _, s in __iter(sizes) do + area =area+ (s[1] + 2) * (s[2] + 2) + widest = math.max(widest, s[1] + 2) + end + local W = 64 + while W * W < area * 1.2 and W < 4096 do + W =W* 2 + end + W = math.max(W, widest) + local order = (table.create(#sizes) ) +for i = 1, #sizes do + order[i] = i + end + table.sort(order, function(a, b) +local ha, hb = sizes[a][2], sizes[b][2] + if ha ~= hb then + return ha > hb + end + return a < b + end) + local out = (table.create(#sizes) ) +local x, y, rowH = 0, 0, 0 + for _, i in __iter(order) do + local w, h = sizes[i][1] + 2, sizes[i][2] + 2 + if x + w > W then + x, y, rowH = 0, y + rowH, 0 + end + out[i] = { x = x + 1, y = y + 1, w = sizes[i][1], h = sizes[i][2] } + x =x+ w + rowH = math.max(rowH, h) + end + local H = math.max(1, y + rowH) + if W * H > maxPixels then + return 0, 0, nil, "limit: lightmap atlas " .. W .. " x " .. H + end + return W, H, out, nil +end + +-- copies the outermost luxels of a rect into its border (rgba8 pixels, atlas width W) +function Lightmap.border(px, W, r) + local function copy(dx, dy, sx, sy) + buffer.writeu32(px, (dy * W + dx) * 4, buffer.readu32(px, (sy * W + sx) * 4)) + end + for yy = r.y, r.y + r.h - 1 do + copy(r.x - 1, yy, r.x, yy) + copy(r.x + r.w, yy, r.x + r.w - 1, yy) + end + for xx = r.x - 1, r.x + r.w do + copy(xx, r.y - 1, xx, r.y) + copy(xx, r.y + r.h, xx, r.y + r.h - 1) + end +end + +return Lightmap +end +__FILES["model/bsp/Quake"] = function() +local __compat = __compat local buffer, bit32, __iter = __compat.buffer, __compat.bit32, __compat.__iter --!strict +-- model/bsp/Quake: Quake 1 (BSP 29, BSP2, 2PSB), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from +-- bspfile.h of the Quake / Quake II source releases and ericw-tools (BSP2 / 2PSB; no code taken). Texture coordinates: +-- s = v . s.xyz + s.w over the texture size; lightmaps (style 0) packed into one atlas as TEXCOORD_1, extents as +-- CalcSurfaceExtents (16 texels per luxel). local Types = __include("Types") local Pixels = __include("codecs/image/Pixels") +local Lightmap = __include("model/bsp/Lightmap") +local Miptex = __include("codecs/image/Miptex") -local Brush = {} +local Quake = {} local Scene = Types.Scene -local readi32, readu16, readf32, readu32 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32 +local readi32, readu16, readf32, readu32, readu8 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32, buffer.readu8 local writef32, writeu32 = buffer.writef32, buffer.writeu32 @@ -146737,6 +149107,8 @@ local writef32, writeu32 = buffer.writef32, buffer.writeu32 + + local function cstr(b, at, n) return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) end @@ -146751,34 +149123,18 @@ local out= {} if n < 0 or n > 65536 or 4 + n * 4 > l.size then return nil, "bad miptex lump" end - local gpal = (pal and{(Pixels.palette(pal, 0, 256) )}or{nil + local gpal = (pal and not hl and{(Pixels.palette(pal, 0, 256) )}or{nil })[1] for i = 0, n - 1 do local o = readi32(b, at + 4 + i * 4) - if o < 0 or o + 40 > l.size then + local hd = (o >= 0 and o + 40 <= l.size and{(Miptex.header(b, at + o, l.size - o) )}or{nil +})[1] if not hd then out[i + 1] = { name = "missing" .. i, width = 64, height = 64, image = nil, texels = false } else - local m = at + o - local name = cstr(b, m, 16) - local w, h, off0 = readu32(b, m + 16), readu32(b, m + 20), readu32(b, m + 24) - local t= { name = name, width = math.max(w, 1), height = math.max(h, 1), image = nil, texels = false } - if off0 ~= 0 and w > 0 and h > 0 and w * h <= maxPixels then - local px = m + off0 - local need = w * h - local palAt = m + readu32(b, m + 36) + (math.floor(w / 8)) * (math.floor(h / 8)) + 2 - if o + off0 + need <= l.size then - local p = gpal - if hl then - p = (palAt - at + 768 <= l.size and{(Pixels.palette(b, palAt, 256) )}or{nil -})[1] end - local img = Types.Image.new(w, h) - if p then - Pixels.indexed(b, px, w, 8, img.pixels, w, h, true, p) - else - for k = 0, need - 1 do - writeu32(img.pixels, k * 4, 0xFF000000 + buffer.readu8(b, px + k) * 0x10101) - end - end - img.meta.source = { format = "bsp", miptex = name, palette = p ~= nil } + local t= { name = hd.name, width = math.max(hd.width, 1), height = math.max(hd.height, 1), image = nil, texels = false } + if hd.offsets[1] ~= 0 and hd.width * hd.height <= maxPixels then + local img = Miptex.decode(b, at + o, l.size - o, { palette = gpal, goldsrc = hl, keyed = false, maxPixels = maxPixels }) + if img then + img.meta.source = { format = "bsp", miptex = hd.name, palette = img.meta.source and img.meta.source.palette } t.image = img end end @@ -146788,11 +149144,14 @@ local out= {} return out, nil end -function Brush.decode(b, base, lumps, variant, opts) +function Quake.decode(b, base, lumps, variant, opts) local q2 = variant == "q2" + local big = variant == "bsp2" or variant == "2psb" local maxPixels = opts and opts.maxPixels or 2 ^ 24 local V, E, SE, Fc, TI, P, M = lumps.vertices, lumps.edges, lumps.surfedges, lumps.faces, lumps.texinfo, lumps.planes, lumps.models - local nV, nE, nSE, nF = math.floor(V.size / 12), math.floor(E.size / 4), math.floor(SE.size / 4), math.floor(Fc.size / 20 + local fSize= big and 28 or 20 + local eSize= big and 8 or 4 + local nV, nE, nSE, nF = math.floor(V.size / 12), math.floor(E.size / eSize), math.floor(SE.size / 4), math.floor(Fc.size / fSize ) local tiSize = q2 and 76 or 40 local nTI, nP = math.floor(TI.size / tiSize), math.floor(P.size / 20 ) local mSize = q2 and 48 or 64 @@ -146855,13 +149214,30 @@ local q2 = variant == "q2" local batches= {} local orders= {} local skipped = 0 + -- lightmaps: record 1 = a white luxel (sky / liquids), 2 = black (unlit faces), then one per lit face + local LT = lumps.lighting + local useLight = LT.size > 0 and not (opts and opts.lightmaps == false) + local rgb = variant == "hl" or q2 + local lit = opts and opts.lit + if lit and (buffer.len(lit) < 8 or buffer.readstring(lit, 0, 4) ~= "QLIT" or buffer.readi32(lit, 4) ~= 1) then + lit = nil + end + local lmSizes= { { 1, 1 }, { 1, 1 } } + local lmFaces= { { face = -1, ofs = -1, smin = 0, tmin = 0, styles = 0 }, { face = -1, ofs = -1, smin = 0, tmin = 0, styles = 0 } } + local lumaTotal = 0 for f = 0, nF - 1 do -local __DARKLUA_CONTINUE_8=false repeat local fo = base + Fc.at + f * 20 - local plane, side, firstEdge, numEdges, texinfo = readu16(b, fo), readu16(b, fo + 2), readi32(b, fo + 4), readu16(b, fo + 8), readu16(b, fo + 10) - local model = faceModel[f + 1] - if not model or numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then +local __DARKLUA_CONTINUE_7=false repeat local fo = base + Fc.at + f * fSize + local plane = (big and{(readi32(b, fo) )}or{(readu16(b, fo) +)})[1] local side = (big and{(readi32(b, fo + 4) )}or{(readu16(b, fo + 2) +)})[1] local firstEdge = (big and{(readi32(b, fo + 8) )}or{(readi32(b, fo + 4) +)})[1] local numEdges = (big and{(readi32(b, fo + 12) )}or{(readu16(b, fo + 8) +)})[1] local texinfo = (big and{(readi32(b, fo + 16) )}or{(readu16(b, fo + 10) +)})[1] local styles = (big and((fo + 20 ))or((fo + 12 +))) local lightofs = (big and{(readi32(b, fo + 24) )}or{(readi32(b, fo + 16) +)})[1] local model = faceModel[f + 1] + if not model or numEdges < 3 or plane < 0 or texinfo < 0 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then skipped =skipped+ 1 -__DARKLUA_CONTINUE_8=true break +__DARKLUA_CONTINUE_7=true break end local poly= {} local ok = true @@ -146872,8 +149248,14 @@ __DARKLUA_CONTINUE_8=true break ok = false break end - local v = (se >= 0 and{(readu16(b, base + E.at + e * 4) )}or{(readu16(b, base + E.at + e * 4 + 2) -)})[1] if v >= nV then + local eo = base + E.at + e * eSize + local v + if big then + v = (se >= 0 and{(readu32(b, eo) )}or{(readu32(b, eo + 4) +)})[1] else + v = (se >= 0 and{(readu16(b, eo) )}or{(readu16(b, eo + 2) +)})[1] end + if v >= nV then ok = false break end @@ -146884,7 +149266,7 @@ __DARKLUA_CONTINUE_8=true break end if not ok then skipped =skipped+ 1 -__DARKLUA_CONTINUE_8=true break +__DARKLUA_CONTINUE_7=true break end local po = base + P.at + plane * 20 local nx, ny, nz = readf32(b, po), readf32(b, po + 4), readf32(b, po + 8) @@ -146916,6 +149298,37 @@ __DARKLUA_CONTINUE_8=true break local tio = base + TI.at + texinfo * tiSize local sx, sy, sz, so = readf32(b, tio), readf32(b, tio + 4), readf32(b, tio + 8), readf32(b, tio + 12) local tx, ty, tz, to = readf32(b, tio + 16), readf32(b, tio + 20), readf32(b, tio + 24), readf32(b, tio + 28) + local rec = 2 + if useLight then + local tflags = readi32(b, tio + (q2 and 32 or 36)) + local special = (q2 and{(bit32.band(tflags, 0x8C) ~= 0 )}or{(bit32.band(tflags, 1) ~= 0 +)})[1] if special then + rec = 1 + elseif lightofs >= 0 then + local smin, smax, tmin, tmax= math.huge, -math.huge, math.huge, -math.huge + for k = 0, n - 1 do + local x, y, z = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] + local sv, tv = x * sx + y * sy + z * sz + so, x * tx + y * ty + z * tz + to + smin, smax = math.min(smin, sv), math.max(smax, sv) + tmin, tmax = math.min(tmin, tv), math.max(tmax, tv) + end + local bs, bt0 = math.floor(smin / 16), math.floor(tmin / 16) + local lw, lh = math.ceil((smax ) / 16) - bs + 1, math.ceil((tmax ) / 16) - bt0 + 1 + local ns = 0 + for k = 0, 3 do + if readu8(b, styles + k) ~= 255 then + ns =ns+ 1 + end + end + local bytes = lw * lh * (rgb and 3 or 1) + lumaTotal =lumaTotal+ lw * lh + if ns > 0 and lw > 0 and lh > 0 and lw <= 256 and lh <= 256 and lightofs + bytes <= LT.size and lumaTotal <= maxPixels then + table.insert(lmSizes, { lw, lh }) + table.insert(lmFaces, { face = f, ofs = lightofs, smin = bs * 16, tmin = bt0 * 16, styles = ns }) + rec = #lmFaces + end + end + end local ti = texOf[texinfo + 1] or 0 local tex = texs[ti] local w, h = (tex and{tex.width }or{1})[1], (tex and{tex.height }or{1 @@ -146923,7 +149336,7 @@ __DARKLUA_CONTINUE_8=true break batches[model] = bm local bt = bm[ti] if not bt then - bt = { tex = ti, pos = {}, nrm = {}, uv = {} } + bt = { tex = ti, pos = {}, nrm = {}, uv = {}, lm = {} } bm[ti] = bt local ol = orders[model] or {} orders[model] = ol @@ -146936,21 +149349,69 @@ __DARKLUA_CONTINUE_8=true break local pp, nn, uu = batch.pos, batch.nrm, batch.uv pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = nx, ny, nz - uu[#uu + 1] = (x * sx + y * sy + z * sz + so) / w - uu[#uu + 1] = (x * tx + y * ty + z * tz + to) / h + local sv, tv = x * sx + y * sy + z * sz + so, x * tx + y * ty + z * tz + to + uu[#uu + 1] = sv / w + uu[#uu + 1] = tv / h + local ll = batch.lm + ll[#ll + 1], ll[#ll + 2], ll[#ll + 3] = rec, sv, tv end end -__DARKLUA_CONTINUE_8=true until true if not __DARKLUA_CONTINUE_8 then break end end +__DARKLUA_CONTINUE_7=true until true if not __DARKLUA_CONTINUE_7 then break end end + local atlasW, atlasH, rects = 0, 0, nil +local lmTex= nil + local atlas= nil + if useLight and #lmFaces > 2 then + local W, H, rs, err = Lightmap.pack(lmSizes, maxPixels) + if not rs then + return nil, err + end + atlasW, atlasH, rects = W, H, rs + local img = Types.Image.new(W, H) + local px = img.pixels + local la = base + LT.at + buffer.writeu32(px, (rs[1].y * W + rs[1].x) * 4, 0xFFFFFFFF) + buffer.writeu32(px, (rs[2].y * W + rs[2].x) * 4, 0xFF000000) + local placed = {} + for i = 3, #lmFaces do + local lf, r = lmFaces[i], rs[i] + for yy = 0, r.h - 1 do + for xx = 0, r.w - 1 do + local k = yy * r.w + xx + local cr, cg, cb= 0, 0, 0 + if rgb then + local o = la + lf.ofs + k * 3 + cr, cg, cb = readu8(b, o), readu8(b, o + 1), readu8(b, o + 2) + elseif lit and 8 + (lf.ofs + k) * 3 + 3 <= buffer.len(lit) then + local o = 8 + (lf.ofs + k) * 3 + cr, cg, cb = readu8(lit, o), readu8(lit, o + 1), readu8(lit, o + 2) + else + local v = readu8(b, la + lf.ofs + k) + cr, cg, cb = v, v, v + end + writeu32(px, ((r.y + yy) * W + r.x + xx) * 4, 0xFF000000 + (cb ) * 65536 + (cg ) * 256 + (cr )) + end + end + table.insert(placed, { face = lf.face, x = r.x, y = r.y, w = r.w, h = r.h, styles = lf.styles }) + end + for i = 1, #lmFaces do + Lightmap.border(px, W, rs[i]) + end + img.meta.source = { format = "bsp", lightmap = "atlas", coloured = rgb or lit ~= nil } + atlas = img + scene.meta.lightmaps = placed + lmTex = #texs + 1 + end for i, t in __iter(texs) do local tex= { name = t.name, image = t.image, uri = (t.image and{nil }or{((q2 and(("textures/" .. t.name .. ".wal" ))or(t.name))) })[1]} table.insert(scene.textures, tex) local mat = Scene.material(t.name) mat.metallic = 0 - local extras= { bsp = { texels = t.texels and true or nil, width = t.width, height = t.height } } - mat.extras = extras - mat.extras = { bsp = { texels = t.texels and true or nil, width = t.width, height = t.height } } + mat.extras = { bsp = { texels = t.texels and true or nil, width = t.width, height = t.height, lightmap = lmTex, lightmapTexCoord = lmTex and 1 or nil } } table.insert(scene.materials, mat) end + if atlas then + table.insert(scene.textures, { name = "lightmap", image = atlas }) + end local root= { name = "bsp", children = {} } table.insert(scene.nodes, root) scene.roots[1] = 1 @@ -146972,8 +149433,23 @@ table.insert(scene.materials, mat) for k = 0, nv - 1 do writeu32(ib, k * 4, k) end + local attrs= { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) } + if rects then + local lb = buffer.create(nv * 8) + for k = 0, nv - 1 do + local rec, sv, tv = bt.lm[k * 3 + 1], bt.lm[k * 3 + 2], bt.lm[k * 3 + 3] + local r, lf = rects[rec], lmFaces[rec] + local lu, lv = r.x + 0.5, r.y + 0.5 + if rec > 2 then + lu, lv = r.x + (sv - lf.smin) / 16 + 0.5, r.y + (tv - lf.tmin) / 16 + 0.5 + end + writef32(lb, k * 8, lu / atlasW) + writef32(lb, k * 8 + 4, lv / atlasH) + end + attrs.TEXCOORD_1 = Scene.accessor(lb, "f32", 2, nv) + end table.insert(mesh.primitives, { - attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }, + attributes = attrs, indices = Scene.accessor(ib, "u32", 1, nv), mode = "triangles" , material = (ti > 0 and{ti }or{nil})[1], @@ -146988,13 +149464,15 @@ table.insert(scene.materials, mat) return scene, nil end -return Brush +return Quake end __FILES["model/bsp/Quake3"] = function() local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict -- model/bsp/Quake3: Quake III Arena maps (IBSP 46; RTCW 47 has the same layout) -> Scene, from the Unofficial Quake 3 --- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped. +-- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped; patches +-- through codecs/model/Patch. local Types = __include("Types") +local Patch = __include("codecs/model/Patch") local Quake3 = {} @@ -147074,52 +149552,23 @@ for k = 1, 14 do do local __DARKLUA_VAR=kind == 1 and"polygons" or"meshes" counts[__DARKLUA_VAR]=counts[__DARKLUA_VAR]+ 1 end elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then local w, h = readi32(b, o + 96), readi32(b, o + 100) - if w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n then + if Patch.valid(w, h, n) then counts.patches =counts.patches+ 1 - local L = level - for py = 0, math.floor((h - 1) / 2 )- 1 do - for px = 0, math.floor((w - 1) / 2 )- 1 do - local ctrl= {} - for j = 0, 2 do - for i = 0, 2 do - ctrl[j * 3 + i + 1] = vertex(first + (py * 2 + j) * w + px * 2 + i) - end - end - local grid= {} - for gy = 0, L do - local tv = gy / L - for gx = 0, L do - local tu = gx / L - local bu = { (1 - tu) ^ 2, 2 * tu * (1 - tu), tu * tu } - local bv = { (1 - tv) ^ 2, 2 * tv * (1 - tv), tv * tv } - local v = table.create(14, 0) - for j = 0, 2 do - for i = 0, 2 do - local wgt = bu[i + 1] * bv[j + 1] - local cp = ctrl[j * 3 + i + 1] - for k = 1, 14 do - v[k]=v[k]+ cp[k] * wgt - end - end - end - local l = math.sqrt(v[8] ^ 2 + v[9] ^ 2 + v[10] ^ 2) - if l > 0 then - v[8], v[9], v[10] = v[8] / l, v[9] / l, v[10] / l - end - grid[gy * (L + 1) + gx + 1] = addExtra(v) - end - end - for gy = 0, L - 1 do - for gx = 0, L - 1 do - local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2] - local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2] - -- Quake's control grids are clockwise-front - for _, v in __iter({ a, d, c2, c2, d, e }) do - table.insert(tris, v) - end - end - end - end + local ctrl = (table.create(n * 14, 0) ) +for k = 0, n - 1 do + table.move(vertex(first + k), 1, 14, k * 14 + 1, ctrl) + end + local pts, gw, gh = Patch.grid(ctrl, w, h, 14, level, level, maxV) + if not pts then + return nil, "limit: too many patch vertices" + end + Patch.normalize(pts, 14, 7) + local ids = (table.create(gw * gh) ) +for k = 0, gw * gh - 1 do + ids[k + 1] = addExtra((table.move(pts, k * 14 + 1, k * 14 + 14, 1, table.create(14, 0)) )) + end + for _, v in __iter(Patch.triangles(gw, gh)) do + table.insert(tris, ids[v + 1]) end else counts.skipped =counts.skipped+ 1 @@ -147245,6 +149694,394 @@ end return Quake3 end +__FILES["model/bsp/Tree"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- model/bsp/Tree: the BSP tree, collision hulls and visibility of Quake 1 / BSP2 / 2PSB / Half-Life / Quake II / Quake +-- III maps as tables (bspfile.h layouts; Unofficial Quake 3 Map Specs), plus point queries: the leaf and contents at a +-- point (Quake 1 hulls 0..3 through nodes / clipnodes as SV_HullPointContents; Quake II leaf contents; Quake III the +-- contents of the leaf's brushes) and the potentially visible set of a leaf (run-length zero bytes, as Mod_DecompressVis). +local Tree = {} + +local readi32, readu16, readi16, readf32, readu8, readu32 = buffer.readi32, buffer.readu16, buffer.readi16, buffer.readf32, buffer.readu8, buffer.readu32 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function v3(b, o, kind) +if kind == "f" then + return { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) } + elseif kind == "i" then + return { readi32(b, o), readi32(b, o + 4), readi32(b, o + 8) } + end + return { readi16(b, o), readi16(b, o + 2), readi16(b, o + 4) } +end + +local function slice(b, base, l) +if l.size <= 0 then + return nil + end + local out = buffer.create(l.size) + buffer.copy(out, 0, b, base + l.at, l.size) + return out +end + +-- nil, message past maxItems +function Tree.read(b, base, lumps, variant, maxItems) +local limit = maxItems or 2 ^ 22 + local q2, q3 = variant == "q2", variant == "q3" + local bsp2, rmq = variant == "bsp2", variant == "2psb" + local d= { variant = variant, planes = {}, nodes = {}, leaves = {}, models = {} } + local function count(l, size) +return (l and{(math.floor(l.size / size ))}or{0 +})[1] end + local P = lumps.planes + local pSize = q3 and 16 or 20 + local np = count(P, pSize) + if np > limit then + return nil, "limit: too many planes" + end + for i = 0, np - 1 do + local o = base + P.at + i * pSize + d.planes[i + 1] = { normal = v3(b, o, "f"), dist = readf32(b, o + 12), type = (q3 and{nil }or{(readi32(b, o + 16) )})[1]} + end + local N = lumps.nodes + local nSize = q3 and 36 or(q2 and 28 or(bsp2 and 44 or(rmq and 32 or 24 +))) local nn = count(N, nSize) + if nn > limit then + return nil, "limit: too many nodes" + end + for i = 0, nn - 1 do + local o = base + N.at + i * nSize + local node +if q3 or q2 or bsp2 or rmq then + local bk = q3 and"i" or(bsp2 and"f" or"s" +) local bs = bk == "s" and 6 or 12 + node = { plane = readi32(b, o), children = { readi32(b, o + 4), readi32(b, o + 8) }, mins = v3(b, o + 12, bk), maxs = v3(b, o + 12 + bs, bk) } + if not q3 then + local fo = o + 12 + bs * 2 + if q2 then + node.firstFace, node.numFaces = readu16(b, fo), readu16(b, fo + 2) + else + node.firstFace, node.numFaces = readu32(b, fo), readu32(b, fo + 4) + end + end + else + local c = {} + for k = 0, 1 do + local p = readu16(b, o + 4 + k * 2) + c[k + 1] = (p < nn and{p }or{(-(65535 - p) - 1 -- Quakespasm Mod_LoadNodes_S: leaf 65535 - p +)})[1] end + node = { plane = readi32(b, o), children = c, mins = v3(b, o + 8, "s"), maxs = v3(b, o + 14, "s"), firstFace = readu16(b, o + 20), numFaces = readu16(b, o + 22) } + end + d.nodes[i + 1] = node + end + local L = lumps.leaves or lumps.leafs + local lSize = q3 and 48 or(q2 and 28 or(bsp2 and 44 or(rmq and 32 or 28 +))) local nl = count(L, lSize) + if nl > limit then + return nil, "limit: too many leaves" + end + for i = 0, nl - 1 do + local o = base + L.at + i * lSize + local leaf +if q3 then + leaf = { cluster = readi32(b, o), area = readi32(b, o + 4), mins = v3(b, o + 8, "i"), maxs = v3(b, o + 20, "i"), + firstFace = readi32(b, o + 32), numFaces = readi32(b, o + 36), firstBrush = readi32(b, o + 40), numBrushes = readi32(b, o + 44) } + elseif q2 then + leaf = { contents = readi32(b, o), cluster = readi16(b, o + 4), area = readi16(b, o + 6), mins = v3(b, o + 8, "s"), maxs = v3(b, o + 14, "s"), + firstFace = readu16(b, o + 20), numFaces = readu16(b, o + 22), firstBrush = readu16(b, o + 24), numBrushes = readu16(b, o + 26) } + else + local bk = bsp2 and"f" or"s" + local bs = bsp2 and 12 or 6 + local fo = o + 8 + bs * 2 + local big = bsp2 or rmq + leaf = { contents = readi32(b, o), visofs = readi32(b, o + 4), mins = v3(b, o + 8, bk), maxs = v3(b, o + 8 + bs, bk), + firstFace = (big and{(readu32(b, fo) )}or{(readu16(b, fo))})[1], numFaces = (big and{(readu32(b, fo + 4) )}or{(readu16(b, fo + 2) )})[1]} + local ao = fo + (big and 8 or 4) + leaf.ambient = { readu8(b, ao), readu8(b, ao + 1), readu8(b, ao + 2), readu8(b, ao + 3) } + end + d.leaves[i + 1] = leaf + end + if not q2 and not q3 then + local C = lumps.clipnodes + local cSize = (bsp2 or rmq )and 12 or 8 + local nc = count(C, cSize) + if nc > limit then + return nil, "limit: too many clipnodes" + end + local cl= {} + for i = 0, nc - 1 do + local o = base + C.at + i * cSize + local c + if cSize == 12 then + c = { readi32(b, o + 4), readi32(b, o + 8) } + else + c = {} + for k = 0, 1 do + local p = readu16(b, o + 4 + k * 2) + c[k + 1] = (p > nc and((p - 65536 ))or(p -- Quakespasm Mod_LoadClipnodes +)) end + end + cl[i + 1] = { plane = readi32(b, o), children = c } + end + d.clipnodes = cl + end + local M = lumps.models + local mSize = q3 and 40 or(q2 and 48 or 64 +) for i = 0, count(M, mSize) - 1 do + local o = base + M.at + i * mSize + local m +if q3 then + m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), headnodes = { 0 }, firstFace = readi32(b, o + 24), numFaces = readi32(b, o + 28) } + elseif q2 then + m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), origin = v3(b, o + 24, "f"), headnodes = { readi32(b, o + 36) }, firstFace = readi32(b, o + 40), numFaces = readi32(b, o + 44) } + else + m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), origin = v3(b, o + 24, "f"), + headnodes = { readi32(b, o + 36), readi32(b, o + 40), readi32(b, o + 44), readi32(b, o + 48) }, + visleafs = readi32(b, o + 52), firstFace = readi32(b, o + 56), numFaces = readi32(b, o + 60) } + end + d.models[i + 1] = m + end + if q2 or q3 then + local B, S = lumps.brushes, lumps.brushsides + local nb, ns = count(B, 12), count(S, q3 and 8 or 4) + if nb > limit or ns > limit then + return nil, "limit: too many brushes" + end + local brushes, sides= {}, {} + for i = 0, nb - 1 do + local o = base + B.at + i * 12 + brushes[i + 1] = { firstSide = readi32(b, o), numSides = readi32(b, o + 4), contents = readi32(b, o + 8) } -- Quake III: a texture index + end + for i = 0, ns - 1 do + if q3 then + local o = base + S.at + i * 8 + sides[i + 1] = { plane = readi32(b, o), texinfo = readi32(b, o + 4) } + else + local o = base + S.at + i * 4 + sides[i + 1] = { plane = readu16(b, o), texinfo = readi16(b, o + 2) } + end + end + d.brushes, d.brushSides = brushes, sides + local LB = lumps.leafbrushes + local lbs= {} + for i = 0, count(LB, q3 and 4 or 2) - 1 do + lbs[i + 1] = (q3 and{(readi32(b, base + LB.at + i * 4) )}or{(readu16(b, base + LB.at + i * 2) +)})[1] end + d.leafBrushes = lbs + if q3 then + -- brush contents come from the texture's contents flags + local T = lumps.textures + local nt = count(T, 72) + for _, br in __iter(brushes) do + local t = br.contents + br.contents = (t >= 0 and t < nt and{(readi32(b, base + T.at + t * 72 + 68) )}or{0 +})[1] end + end + end + local VL = lumps.visibility or lumps.visdata + d.visibility = (VL and{(slice(b, base, VL) )}or{nil +})[1] local vis = d.visibility + if vis and q2 and buffer.len(vis) >= 4 then + d.numClusters = readi32(vis, 0) + elseif vis and q3 and buffer.len(vis) >= 8 then + d.numClusters, d.clusterBytes = readi32(vis, 0), readi32(vis, 4) + end + return d, nil +end + +local function side(d, plane, x, y, z) +local p = d.planes[plane + 1] + if not p then + return 0 + end + local n = p.normal + return x * n[1] + y * n[2] + z * n[3] - p.dist +end + +-- the leaf (0-based) at a point, walking the tree of model (0-based, default 0) +function Tree.leafAt(d, x, y, z, model) +local m = d.models[(model or 0) + 1] + local node = (m and{m.headnodes[1] }or{0 +})[1] for _ = 1, #d.nodes + 1 do + if node < 0 then + return -node - 1 + end + local nd = d.nodes[node + 1] + if not nd then + return nil + end + node = (side(d, nd.plane, x, y, z) >= 0 and{nd.children[1] }or{nd.children[2] +})[1] end + return nil +end + +-- Quake 1: CONTENTS_* (-1 empty, -2 solid, -3 water, -4 slime, -5 lava, -6 sky) in hull 0..3; Quake II: the leaf's +-- CONTENTS_* bits; Quake III: the contents bits of the brushes holding the point +function Tree.contents(d, x, y, z, hull, model) +local h = hull or 0 + if (d.variant == "q1" or d.variant == "hl" or d.variant == "bsp2" or d.variant == "2psb") and h > 0 then + local m = d.models[(model or 0) + 1] + local cl = d.clipnodes or {} + local node = (m and{m.headnodes[h + 1] or -1 }or{(-1 +)})[1] for _ = 1, #cl + 1 do + if node < 0 then + return node + end + local c = cl[node + 1] + if not c then + return nil + end + node = (side(d, c.plane, x, y, z) >= 0 and{c.children[1] }or{c.children[2] +})[1] end + return nil + end + local leaf = Tree.leafAt(d, x, y, z, model) + local lf = leaf and d.leaves[leaf + 1] + if not lf then + return nil + end + if d.variant ~= "q3" then + return lf.contents + end + local out = 0 + local lbs, brushes, sides= d.leafBrushes or {}, d.brushes or {}, d.brushSides or {} + local fb, nb= lf.firstBrush or 0, lf.numBrushes or 0 + for k = fb, fb + nb - 1 do + local br = brushes[(lbs[k + 1] or -1) + 1] + if br then + local inside = true + for s = br.firstSide, br.firstSide + br.numSides - 1 do + local sd = sides[s + 1] + if not sd or side(d, sd.plane, x, y, z) > 0 then + inside = false + break + end + end + if inside then + out = bit32.bor(out, br.contents) + end + end + end + return out +end + +local function decompress(vis, at, bytes, out) + local n = buffer.len(vis) + local i = 0 + while i < bytes and at < n do + local c = readu8(vis, at) + if c ~= 0 then + for bit = 0, 7 do + if bit32.band(c, bit32.lshift(1, bit)) ~= 0 then + out[i * 8 + bit + 1] = true + end + end + i =i+ 1 + at =at+ 1 + else + if at + 1 >= n then + break + end + i =i+ readu8(vis, at + 1) + at =at+ 2 + end + end +end + +-- the leaves (0-based, sorted) potentially visible from a leaf; nil without visibility data (everything visible) +function Tree.pvs(d, leaf) +local lf = d.leaves[leaf + 1] + local vis = d.visibility + if not lf or not vis then + return nil + end + local out= {} + if d.variant == "q2" or d.variant == "q3" then + local nc = d.numClusters or 0 + local c = lf.cluster or -1 + if c < 0 or c >= nc then + return out + end + local bits= {} + if d.variant == "q2" then + if 4 + nc * 8 > buffer.len(vis) then + return nil + end + decompress(vis, readi32(vis, 4 + c * 8), math.floor((nc + 7) / 8), bits) + else + local sz = d.clusterBytes or 0 + local o = 8 + c * sz + for k = 0, sz - 1 do + if o + k < buffer.len(vis) then + local v = readu8(vis, o + k) + for bit = 0, 7 do + if bit32.band(v, bit32.lshift(1, bit)) ~= 0 then + bits[k * 8 + bit + 1] = true + end + end + end + end + end + for i, l in __iter(d.leaves) do + local cl = l.cluster or -1 + if cl >= 0 and bits[cl + 1] then + table.insert(out, i - 1) + end + end + return out + end + -- Quake 1: bit k = leaf k + 1 (leaf 0 is the shared solid leaf), visleafs bits + local visofs = lf.visofs or -1 + if leaf == 0 or visofs < 0 then + return out + end + local n = d.models[1] and d.models[1].visleafs or (#d.leaves - 1) + local bits= {} + decompress(vis, visofs, math.floor((n + 7) / 8), bits) + for k = 0, n - 1 do + if bits[k + 1] then + table.insert(out, k + 1) + end + end + return out +end + +return Tree +end __FILES["model/dae"] = function() local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict -- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos specifications; .dae XML, .zae zip with manifest.xml). Supports: geometry, @@ -157850,6 +160687,1097 @@ end return Parse end +__FILES["model/map"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/map: editor .map files of Quake, Half-Life (Valve 220), Quake II (surface / content flags) and Quake III +-- (brushDef brush primitives, patchDef2; patchDef3 meshes), read and write. Grammar of the qbsp / q3map2 parsers (no +-- code taken). Brushes become polygons through codecs/model/Brush (optionally CSG'd and merged), patches through +-- codecs/model/Patch; a mesh per entity with brushes; entities as nodes with their keys in extras. Texture sizes from +-- opts.textureSizes, the worldspawn's WADs, .wal files or images through resolve; else 64 x 64. Not supported: Doom 3 +-- brushDef3, Build engine maps (binary: model/buildmap), compiling (no BSP, vis or light). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Input = __include("core/Input") +local Types = __include("Types") +local Miptex = __include("codecs/image/Miptex") +local Brush = __include("codecs/model/Brush") +local Parse = __include("model/map/Parse") +local Write = __include("model/map/Write") +local Build = __include("model/map/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Map = { + name = "map", + category = "model", + extensions = { "map" }, + mime = { "text/x-quake-map" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" }, + caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff + + + + + + + + + + + + + + + + + + +function Map.sniff(r) +local head = r:peek(math.min(r:remaining(), 4096)) + if #head < 2 or string.find(head, "[%z\1-\8\14-\31]") then + return 0 + end + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + local s = head + local game = false + while true do + local c = string.match(s, "^%s*//[^\n]*\n?()") + if not c then + break + end + if string.match(s, "^%s*//%s*Game:") then + game = true + end + s = string.sub(s, c ) + end + local body = string.match(s, '^%s*{%s*"[^"\n]*"%s*"') or string.match(s, "^%s*{%s*{%s*[%(bp]") + if not body then + return game and string.match(s, "^%s*{") and 0.6 or 0 + end + return (game or string.find(head, '"classname"', 1, true) )and 0.9 or 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function variantOf(m) +local game = string.lower(m.game or "") + local fmt = string.lower(m.mapFormat or "") + local q2, valve, q3 = false, false, false + for _, e in __iter(m.entities) do + if e.keys.mapversion == "220" then + valve = true + end + for _, b in __iter(e.brushes) do + if b.type ~= "brush" then + q3 = true + end + for _, f in __iter(b.faces or {}) do + if f.u then + valve = true + elseif f.flags and #f.flags >= 3 then + q2 = true + end + end + end + end + if q3 or string.find(game, "quake 3") or string.find(game, "quake iii") or fmt == "quake3" or fmt == "quake3 (valve)" then + return "quake3" + end + if string.find(game, "quake 2") or string.find(game, "quake ii") or fmt == "quake2" or fmt == "quake2 (valve)" then + return "quake2" + end + if valve or fmt == "valve" then + return "valve220" + end + return q2 and"quake2" or"quake" +end + +local function sizer(m, variant, opts) +local cache= {} + local wads= nil + local function loadWads() +local list = {} + local ws = m.entities[1] and m.entities[1].keys + local spec = ws and (ws.wad or ws._wad) or "" + for path in __iter(string.gmatch(spec, "[^;]+")) do + local p = string.gsub(path, "\\", "/") + local b = Input.sibling(opts, p) or Input.sibling(opts, string.match(p, "([^/]+)$") or p) + if b then + local lumps = Miptex.wad(b, 0, buffer.len(b)) + if lumps then + table.insert(list, { buf = b, lumps = lumps }) + end + end + end + return list + end + return function(name) +local c = cache[name] + if c then + return c[1], c[2], c[3] == 1 + end + local w, h= 0, 0 + local given = opts and opts.textureSizes and opts.textureSizes[name] + if type(given) == "table" and type(given[1]) == "number" and type(given[2]) == "number" then + w, h = given[1] , given[2] +elseif variant == "quake" or variant == "valve220" then + wads = wads or loadWads() + for i = #(wads ), 1, -1 do + local wd = (wads )[i] + local l = Miptex.find(wd.lumps, name) + if l then + local hd = Miptex.header(wd.buf, l.offset, l.disksize) + if hd then + w, h = hd.width, hd.height + break + end + end + end + elseif variant == "quake2" then + local wal = Input.sibling(opts, "textures/" .. name .. ".wal") + if wal and buffer.len(wal) >= 40 then + w, h = buffer.readu32(wal, 32), buffer.readu32(wal, 36) + end + elseif opts and opts.decodeImage then + for _, ext in __iter({ ".tga", ".jpg", ".png" }) do + local b = Input.sibling(opts, "textures/" .. name .. ext) + if b then + local ok, img = pcall(opts.decodeImage , b) + if ok and img then + w, h = img.width, img.height + break + end + end + end + end + local fw, fh= w , h +local known = fw > 0 and fh > 0 + if not known then + fw, fh = 64, 64 + end + cache[name] = { fw, fh, known and 1 or 0 } + return fw, fh, known + end +end + +function Map.decode(r, opts) +local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local m, msg, at = Parse.parse(text, opts and opts.maxBrushes) + if not m then + return nil, Err.from(msg, at) + end + if #m.entities == 0 then + return nil, Err.new(Err.CORRUPT, "no entities", 0) + end + local variant = variantOf(m) + local scene, err = Build.scene(m, { + variant = variant, + size = sizer(m, variant, opts), + hull = opts and opts.hull, + merge = opts and opts.merge, + epsilon = opts and opts.epsilon, + patchLevel = opts and opts.patchLevel, + skip = opts and opts.skip, + maxPolygons = opts and opts.maxPolygons, + }) + if not scene then + return nil, Err.from(err) + end + local counts = scene.meta.counts + scene.meta.counts = nil + scene.meta.source = { format = "map", variant = variant, game = m.game, mapFormat = m.mapFormat, entities = #m.entities, brushes = counts.brushes, patches = counts.patches } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function toValve(f) +if f.u or f.matrix then + return f + end + local bf = Build.face(f) + if not bf or not bf.vecs then + return f + end + local v = bf.vecs + local out = table.clone(f) + out.offset = nil + out.u, out.v = { v[1][1], v[1][2], v[1][3], v[1][4] }, { v[2][1], v[2][2], v[2][3], v[2][4] } + out.rotation, out.scale = 0, { 1, 1 } + return out +end + +local function fmtNum(x) +return Write.num(x) +end + +function Map.encode(scene, opts) +if type(scene) ~= "table" or type(scene.nodes) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local valve = opts and opts.variant == "valve220" + local ents= {} + for _, node in __iter(scene.nodes) do + local ex= node.extras + if type(ex) == "table" and type(ex.keys) == "table" then + local keys = ex.keys + local brushes= (type(ex.brushes) == "table" and{ex.brushes }or{{} +})[1] if node.translation and keys.origin and #brushes == 0 then + local t = node.translation + keys = Types.object(table.clone(keys), Types.keys(keys)) + keys.origin = fmtNum(t[1]) .. " " .. fmtNum(t[2]) .. " " .. fmtNum(t[3]) + end + if valve then + local conv= {} + for _, b in __iter(brushes) do + if b.faces then + local nb = table.clone(b) + local faces = {} + for i, f in __iter(b.faces) do + faces[i] = toValve(f) + end + nb.faces = faces + table.insert(conv, nb) + else + table.insert(conv, b) + end + end + brushes = conv + if #ents == 0 and keys.mapversion ~= "220" then + keys = Types.object(table.clone(keys), Types.keys(keys)) + Types.set(keys, "mapversion", "220") + end + end + table.insert(ents, { keys = keys, brushes = brushes }) + end + end + if #ents == 0 then + return nil, Err.new(Err.ARG, "no map entities (nodes with extras.keys, as model/map loads them)") + end + local src= scene.meta and scene.meta.source + local fromMap = type(src) == "table" and src.format == "map" + local text, err = Write.text({ + entities = ents , + game = (fromMap and{src.game }or{nil})[1], + mapFormat = valve and"Valve" or(fromMap and{src.mapFormat }or{nil})[1], + comments = {}, + }) + if not text then + return nil, Err.new(Err.ARG, err or "bad entity") + end + return buffer.fromstring(text), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- the entities as parsed: { entities = { { keys, brushes } }, game, mapFormat } +function Map.parse(src) +local text = (type(src) == "buffer" and{(buffer.tostring(src) )}or{(type(src) == "string" and{src }or{nil +})[1]})[1] if not text then + return nil, Err.new(Err.ARG, "expected a buffer or a string") + end + local m, msg, at = Parse.parse(text) + if not m then + return nil, Err.from(msg, at) + end + return m, nil +end + +function Map.write(m) +if type(m) ~= "table" or type(m.entities) ~= "table" then + return nil, Err.new(Err.ARG, "expected { entities = ... }") + end + local text, err = Write.text(m) + if not text then + return nil, Err.new(Err.ARG, err or "bad entity") + end + return text, nil +end + +-- a parsed face -> its Brush face (plane and projection): Brush.uv / Brush.polygons take it +function Map.face(f) +return Build.face(f) +end + +return Map +end +__FILES["model/map/Build"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!strict +-- model/map/Build: parsed entities -> Scene: brushes through codecs/model/Brush, patches through codecs/model/Patch, +-- a mesh per entity with brushes, a primitive per texture, entities as nodes (keys in extras), z up, map units. +local Types = __include("Types") +local Brush = __include("codecs/model/Brush") +local Patch = __include("codecs/model/Patch") +local Parse = __include("model/map/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + + + + + + + + + + + + +function Build.face(f) +local p = f.points + local plane = Brush.planeFromPoints({ p[1], p[2], p[3] }, { p[4], p[5], p[6] }, { p[7], p[8], p[9] }) + if not plane then + return nil + end + local out= { plane = plane, texture = f.texture } + if f.matrix then + out.bp = f.matrix + elseif f.u and f.v then + local sc = f.scale or { 1, 1 } + out.vecs = Brush.valveVecs(f.u, f.v, sc[1], sc[2]) + else + local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 } + out.vecs = Brush.quakeVecs(plane, o[1], o[2], f.rotation or 0, sc[1], sc[2]) + end + return out +end + + + +local function patchPrim(b, level, acc) +local size, pts = b.size , b.points +local w, h= size[1] , size[2] +if not Patch.valid(w, h, math.floor(#pts / 5)) then + return false + end + -- file order is column by column (q3map2 ParsePatch: verts[i * width + j] for column j, point i) + local ctrl = (table.create(w * h * 5, 0) ) +for j = 0, w - 1 do + for i = 0, h - 1 do + table.move(pts, (j * h + i) * 5 + 1, (j * h + i) * 5 + 5, (i * w + j) * 5 + 1, ctrl) + end + end + local params= b.params or {} + local explicit = b.type == "patchDef3" + local lu= (explicit and{(math.max(1, params[1] or 1) )}or{level +})[1] local lv= (explicit and{(math.max(1, params[2] or 1) )}or{level +})[1] local g, gw, gh = Patch.grid(ctrl, w, h, 5, lu, lv) + if not g then + return false + end + local nrm = Patch.normals(g, 5, gw, gh) + local base = math.floor(#acc.pos / 3 +) for k = 0, gw * gh - 1 do + local o = k * 5 + table.insert(acc.pos, g[o + 1]) + table.insert(acc.pos, g[o + 2]) + table.insert(acc.pos, g[o + 3]) + table.insert(acc.uv, g[o + 4]) + table.insert(acc.uv, g[o + 5]) + table.insert(acc.nrm, nrm[k * 3 + 1]) + table.insert(acc.nrm, nrm[k * 3 + 2]) + table.insert(acc.nrm, nrm[k * 3 + 3]) + end + for _, v in __iter(Patch.triangles(gw, gh)) do + table.insert(acc.idx, base + v) + end + return true +end + +local function primitive(a) +local nv, ni = math.floor(#a.pos / 3), #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + return { + attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }, + indices = Scene.accessor(ib, "u32", 1, ni), + mode = "triangles", + } +end + +local function vec3(s) +if not s then + return nil + end + local x, y, z = string.match(s, "^%s*(%S+)%s+(%S+)%s+(%S+)") + local a, b, c = tonumber(x), tonumber(y), tonumber(z) + if a and b and c then + return { a, b, c } + end + return nil +end + +function Build.scene(map, o) +local scene = Scene.new() + scene.meta.up = "z" + local skip= {} + for _, n in __iter(o.skip or {}) do + skip[string.lower(n)] = true + end + local matOf= {} + local function material(name) +local m = matOf[name] + if m then + return m + end + local w, h, known = o.size(name) + local uri = name + if o.variant == "quake2" then + uri = "textures/" .. name .. ".wal" + elseif o.variant == "quake3" then + uri = "textures/" .. name + end + table.insert(scene.textures, { name = name, uri = uri }) + local mat = Scene.material(name) + mat.metallic = 0 + mat.baseColorTexture = { texture = #scene.textures } + mat.extras = { map = { width = w, height = h, sizeKnown = known } } + table.insert(scene.materials, mat) + matOf[name] = #scene.materials + return #scene.materials + end + local root= { name = "map", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local skipped = { faces = 0, patches = 0 } + local counts = { brushes = 0, patches = 0 } + local entities= {} + local polyTotal = 0 + for ei, ent in __iter(map.entities) do + local keys = ent.keys + table.insert(entities, keys) + local node= { name = keys.targetname or keys.classname or ("entity " .. (ei - 1)), children = {}, + extras = { classname = keys.classname, keys = keys, brushes = ent.brushes, entity = ei - 1 } } + local brushes= {} + local patchAcc= {} + local patchOrder= {} + for _, b in __iter(ent.brushes) do + if b.faces then + counts.brushes =counts.brushes+ 1 + local faces= {} + for _, f in __iter(b.faces) do + local bf = Build.face(f) + if bf then + table.insert(faces, bf) + else + skipped.faces =skipped.faces+ 1 + end + end + table.insert(brushes, faces) + else + counts.patches =counts.patches+ 1 + local tex = b.texture or "" + if not skip[string.lower(tex)] then + local acc = patchAcc[tex] + if not acc then + acc = { pos = {}, nrm = {}, uv = {}, idx = {} } + patchAcc[tex] = acc + table.insert(patchOrder, tex) + end + if not patchPrim(b, o.patchLevel or 4, acc ) then + skipped.patches =skipped.patches+ 1 + end + end + end + end + local prims= {} + if #brushes > 0 then + local polys, err = Brush.polygons(brushes, { hull = o.hull, merge = o.merge, epsilon = o.epsilon, maxPolygons = o.maxPolygons }) + if not polys then + return nil, err + end + polyTotal =polyTotal+ #polys + if polyTotal > (o.maxPolygons or 2 ^ 20) then + return nil, "limit: too many polygons" + end + local kept= {} + for _, p in __iter(polys) do + local t = brushes[p.brush][p.face].texture or "" + if not skip[string.lower(t)] then + table.insert(kept, p) + end + end + local built = Brush.primitives(kept, brushes, function(name) +local m = scene.materials[material(name)] + local e = (m.extras ).map + return e.width, e.height + end) + for _, bt in __iter(built) do + bt.primitive.material = material(bt.texture) + table.insert(prims, bt.primitive) + end + end + for _, tex in __iter(patchOrder) do + local acc = patchAcc[tex] + if #acc.idx > 0 then + local prim = primitive(acc) + prim.material = material(tex) + table.insert(prims, prim) + end + end + if #prims > 0 then + table.insert(scene.meshes, { name = node.name, primitives = prims }) + node.mesh = #scene.meshes + elseif #ent.brushes == 0 then + node.translation = vec3(keys.origin) + end + table.insert(scene.nodes, node) + table.insert(root.children, #scene.nodes) + end + scene.meta.entities = entities + scene.meta.skipped = skipped + scene.meta.counts = counts + return scene, nil +end + +return Build +end +__FILES["model/map/Parse"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- model/map/Parse: .map text -> entities (key / value pairs in order, brushes and patches as written). Grammar of the +-- Quake / Quake II / Half-Life (Valve 220) / Quake III editors (qbsp / q3map2 map parsers; no code taken). +local Types = __include("Types") + +local Parse = {} + + + + + + + + + + + + + + + + + + + + + + + + + +local function skip(st) + local s = st.s + while true do + local p = string.find(s, "[^%s]", st.pos) + if not p then + st.pos = st.n + 1 + return + end + if string.sub(s, p, p + 1) == "//" then + local e = string.find(s, "\n", p, true) or st.n + table.insert(st.comments, (string.gsub(string.sub(s, p + 2, e), "^%s*(.-)%s*$", "%1"))) + st.pos = e + 1 + else + st.pos = p + return + end + end +end + +local function peek(st) +skip(st) + return string.sub(st.s, st.pos, st.pos) +end + +local function expect(st, c) +if peek(st) ~= c then + return "expected '" .. c .. "' at " .. (st.pos - 1) + end + st.pos =st.pos+ 1 + return nil +end + +local function word(st) +skip(st) + local a, b = string.find(st.s, "^[^%s]+", st.pos) + if not a then + return nil + end + st.pos = (b ) + 1 + return string.sub(st.s, a, b) +end + +local function number(st) +skip(st) + local a, b = string.find(st.s, "^[^%s%(%)%[%]{}]+", st.pos) + if not a then + return nil + end + local v = tonumber(string.sub(st.s, a, b)) + if v then + st.pos = (b ) + 1 + end + return v +end + +local function quoted(st) +if peek(st) ~= '"' then + return nil + end + local e = string.find(st.s, '"', st.pos + 1, true) + if not e then + return nil + end + local v = string.sub(st.s, st.pos + 1, e - 1) + st.pos = e + 1 + return v +end + +local function numbers(st, n, out) +for _ = 1, n do + local v = number(st) + if not v then + return "expected a number at " .. (st.pos - 1) + end + table.insert(out, v) + end + return nil +end + +local function vec(st, n, open, close) +local e = expect(st, open) + if e then + return nil, e + end + local out = {} + e = numbers(st, n, out) + if e then + return nil, e + end + e = expect(st, close) + if e then + return nil, e + end + return out, nil +end + +local function trailing(st) +local out= {} + while true do + local c = peek(st) + if not string.match(c, "[%d%-%+%.]") then + break + end + local v = number(st) + if not v then + break + end + table.insert(out, v) + end + return (#out > 0 and{out }or{nil +})[1]end + +local function plane(st) +local pts= {} + for _ = 1, 3 do + local p, e = vec(st, 3, "(", ")") + if not p then + return nil, e + end + table.move(p, 1, 3, #pts + 1, pts) + end + return pts, nil +end + +local function face(st, bp) +local pts, e = plane(st) + if not pts then + return nil, e + end + local f= { points = pts, texture = "" } + if bp then + e = expect(st, "(") + if e then + return nil, e + end + local r1, e1 = vec(st, 3, "(", ")") + if not r1 then + return nil, e1 + end + local r2, e2 = vec(st, 3, "(", ")") + if not r2 then + return nil, e2 + end + e = expect(st, ")") + if e then + return nil, e + end + f.matrix = { r1, r2 } + end + local tex = word(st) + if not tex then + return nil, "expected a texture name at " .. (st.pos - 1) + end + f.texture = tex + if not bp then + if peek(st) == "[" then + local u, eu = vec(st, 4, "[", "]") + if not u then + return nil, eu + end + local v, ev = vec(st, 4, "[", "]") + if not v then + return nil, ev + end + local rest = {} + e = numbers(st, 3, rest) + if e then + return nil, e + end + f.u, f.v, f.rotation, f.scale = u, v, rest[1], { rest[2], rest[3] } + else + local rest = {} + e = numbers(st, 5, rest) + if e then + return nil, e + end + f.offset, f.rotation, f.scale = { rest[1], rest[2] }, rest[3], { rest[4], rest[5] } + end + end + f.flags = trailing(st) + return f, nil +end + +local function patch(st, kind, maxPoints) +local e = expect(st, "{") + if e then + return nil, e + end + local tex = word(st) + if not tex then + return nil, "expected a patch texture" + end + local hn = kind == "patchDef3" and 7 or 5 + local head, eh = vec(st, hn, "(", ")") + if not head then + return nil, eh + end + local w, h = head[1], head[2] + if w ~= math.floor(w) or h ~= math.floor(h) or w < 1 or h < 1 or w * h > maxPoints then + return nil, "bad patch size " .. w .. " x " .. h + end + local pts= {} + e = expect(st, "(") + if e then + return nil, e + end + for _ = 1, w do + e = expect(st, "(") + if e then + return nil, e + end + for _ = 1, h do + local p, ep = vec(st, 5, "(", ")") + if not p then + return nil, ep + end + table.move(p, 1, 5, #pts + 1, pts) + end + e = expect(st, ")") + if e then + return nil, e + end + end + e = expect(st, ")") + if e then + return nil, e + end + e = expect(st, "}") + if e then + return nil, e + end + return { type = kind, texture = tex, size = { w, h }, params = { table.unpack(head, 3) }, points = pts }, nil +end + +local function brush(st, maxPoints) +local c = peek(st) + if c == "(" then + local faces= {} + while peek(st) == "(" do + local f, e = face(st, false) + if not f then + return nil, e + end + table.insert(faces, f) + end + local e = expect(st, "}") + if e then + return nil, e + end + return { type = "brush", faces = faces }, nil + end + if c == "}" then + st.pos =st.pos+ 1 + return { type = "brush", faces = {} }, nil + end + local kw = word(st) + local out, err +if kw == "brushDef" then + local e = expect(st, "{") + if e then + return nil, e + end + local faces= {} + while peek(st) == "(" do + local f, ef = face(st, true) + if not f then + return nil, ef + end + table.insert(faces, f) + end + e = expect(st, "}") + if e then + return nil, e + end + out = { type = "brushDef", faces = faces } + elseif kw == "patchDef2" or kw == "patchDef3" then + out, err = patch(st, kw, maxPoints) + if not out then + return nil, err + end + elseif kw == "brushDef3" then + return nil, "unsupported: Doom 3 / Quake 4 brushDef3" + else + return nil, "unexpected '" .. tostring(kw) .. "' in a brush at " .. (st.pos - 1) + end + local e = expect(st, "}") + if e then + return nil, e + end + return out, nil +end + +function Parse.parse(s, maxBrushes) +local st= { s = s, pos = 1, n = #s, comments = {} } + if string.sub(s, 1, 3) == "\239\187\191" then + st.pos = 4 + end + local limit = maxBrushes or 2 ^ 20 + local count = 0 + local ents= {} + while peek(st) ~= "" do + local at = st.pos - 1 + local e = expect(st, "{") + if e then + return nil, e, at + end + local keys= {} + local order= {} + local brushes= {} + while true do + local c = peek(st) + if c == "}" then + st.pos =st.pos+ 1 + break + elseif c == '"' then + local k = quoted(st) + local v = quoted(st) + if not k or not v then + return nil, "bad key / value at " .. (st.pos - 1), st.pos - 1 + end + if keys[k] == nil then + table.insert(order, k) + end + keys[k] = v + elseif c == "{" then + st.pos =st.pos+ 1 + local b, eb = brush(st, limit) + if not b then + return nil, eb, st.pos - 1 + end + count =count+ 1 + if count > limit then + return nil, "limit: too many brushes", st.pos - 1 + end + table.insert(brushes, b) + elseif c == "" then + return nil, "truncated entity", st.pos - 1 + else + return nil, "unexpected '" .. c .. "' in an entity at " .. (st.pos - 1), st.pos - 1 + end + end + table.insert(ents, { keys = (Types.object(keys, order) ), brushes = brushes }) + end + local game, fmt + for _, c in __iter(st.comments) do + game = game or string.match(c, "^Game:%s*(.-)%s*$") + fmt = fmt or string.match(c, "^Format:%s*(.-)%s*$") + end + return { entities = ents, game = game, mapFormat = fmt, comments = st.comments }, nil, nil +end + +return Parse +end +__FILES["model/map/Write"] = function() +local __compat = __compat local type, __iter = __compat.type, __compat.__iter --!strict +-- model/map/Write: entities (model/map/Parse's layout) -> .map text in the editors' layout (TrenchBroom / Radiant: +-- one face per line, numbers in their shortest exact form). +local Types = __include("Types") +local Parse = __include("model/map/Parse") + +local Write = {} + +function Write.num(x) +if x ~= x or x == math.huge or x == -math.huge then + return "0" + end + if x == math.floor(x) and math.abs(x) < 2 ^ 53 then + return string.format("%d", x) + end + for p = 6, 17 do + local s = string.format("%." .. p .. "g", x) + if tonumber(s) == x then + return s + end + end + return string.format("%.17g", x) +end + +local function nums(t, a, b) +local out = (table.create(b - a + 1) ) +for i = a, b do + out[#out + 1] = Write.num(t[i] or 0) + end + return table.concat(out, " ") +end + +local function faceLine(f, bp) +local p = f.points + if type(p) ~= "table" or #p < 9 or type(f.texture) ~= "string" or f.texture == "" or string.find(f.texture, "%s") then + return nil, "a face needs 9 point numbers and a texture name without spaces" + end + local parts= { "( " .. nums(p, 1, 3) .. " ) ( " .. nums(p, 4, 6) .. " ) ( " .. nums(p, 7, 9) .. " )" } + if bp then + local m = f.matrix + if not m or not m[1] or not m[2] then + return nil, "a brushDef face needs a texture matrix" + end + table.insert(parts, "( ( " .. nums(m[1], 1, 3) .. " ) ( " .. nums(m[2], 1, 3) .. " ) )") + table.insert(parts, f.texture) + elseif f.u and f.v then + local sc = f.scale or { 1, 1 } + table.insert(parts, f.texture) + table.insert(parts, "[ " .. nums(f.u, 1, 4) .. " ] [ " .. nums(f.v, 1, 4) .. " ] " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2)) + else + local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 } + table.insert(parts, f.texture) + table.insert(parts, nums(o, 1, 2) .. " " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2)) + end + if f.flags and #f.flags > 0 then + table.insert(parts, nums(f.flags, 1, #f.flags)) + end + return table.concat(parts, " "), nil +end + +local function patchText(b, out) +local size, pts = b.size, b.points + if not size or not pts or type(b.texture) ~= "string" then + return "a patch needs a texture, a size and control points" + end + local w, h = size[1], size[2] + if #pts < w * h * 5 then + return "a patch needs width * height * 5 control numbers" + end + local params = b.params or {} + local nParams = b.type == "patchDef3" and 5 or 3 + table.insert(out, b.type) + table.insert(out, "{") + table.insert(out, b.texture) + table.insert(out, "( " .. Write.num(w) .. " " .. Write.num(h) .. " " .. nums(params, 1, nParams) .. " )") + table.insert(out, "(") + for i = 0, w - 1 do + local row = { "(" } + for j = 0, h - 1 do + local o = (i * h + j) * 5 + table.insert(row, "( " .. nums(pts, o + 1, o + 5) .. " )") + end + table.insert(row, ")") + table.insert(out, table.concat(row, " ")) + end + table.insert(out, ")") + table.insert(out, "}") + return nil +end + +function Write.text(map) +local out= {} + if map.game then + table.insert(out, "// Game: " .. map.game) + end + if map.mapFormat then + table.insert(out, "// Format: " .. map.mapFormat) + end + for ei, ent in __iter(map.entities) do + table.insert(out, "// entity " .. (ei - 1)) + table.insert(out, "{") + for _, k in __iter(Types.keys(ent.keys)) do + local v = ent.keys[k] + if v ~= nil then + if string.find(k, '"', 1, true) or string.find(tostring(v), '"', 1, true) or string.find(k, "[\r\n]") or string.find(tostring(v), "[\r\n]") then + return nil, "keys and values cannot hold quotes or line breaks: " .. k + end + table.insert(out, '"' .. k .. '" "' .. tostring(v) .. '"') + end + end + for bi, b in __iter(ent.brushes or {}) do + table.insert(out, "// brush " .. (bi - 1)) + table.insert(out, "{") + if b.type == "patchDef2" or b.type == "patchDef3" then + local e = patchText(b, out) + if e then + return nil, e + end + else + local bp = b.type == "brushDef" + if bp then + table.insert(out, "brushDef") + table.insert(out, "{") + end + for _, f in __iter(b.faces or {}) do + local line, e = faceLine(f, bp) + if not line then + return nil, e + end + table.insert(out, line) + end + if bp then + table.insert(out, "}") + end + end + table.insert(out, "}") + end + table.insert(out, "}") + end + table.insert(out, "") + return table.concat(out, "\n"), nil +end + +return Write +end __FILES["model/mca"] = function() local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict -- model/mca: Minecraft Anvil region files (wiki "Region file format", "Chunk format"), read-only. Supports: gzip, zlib, diff --git a/build/rosetta.lua.linemap.json b/build/rosetta.lua.linemap.json index 23ac1bb..9e8a636 100644 --- a/build/rosetta.lua.linemap.json +++ b/build/rosetta.lua.linemap.json @@ -1,544 +1,553 @@ [ [660, "src/Rosetta/init.luau"], [1504, "src/Rosetta/Registry.luau"], -[3637, "src/Rosetta/Types.luau"], -[4720, "src/Rosetta/archive/7z/init.luau"], -[5105, "src/Rosetta/archive/7z/Header.luau"], -[5632, "src/Rosetta/archive/adf/init.luau"], -[5914, "src/Rosetta/archive/applesingle/init.luau"], -[6100, "src/Rosetta/archive/ar/init.luau"], -[6503, "src/Rosetta/archive/arj/init.luau"], -[6713, "src/Rosetta/archive/binhex/init.luau"], -[6962, "src/Rosetta/archive/br/init.luau"], -[7037, "src/Rosetta/archive/bz2/init.luau"], -[7101, "src/Rosetta/archive/cab/init.luau"], -[7514, "src/Rosetta/archive/cab/Sum.luau"], -[7555, "src/Rosetta/archive/cpio/init.luau"], -[7723, "src/Rosetta/archive/d64/init.luau"], -[8137, "src/Rosetta/archive/fat/init.luau"], -[8259, "src/Rosetta/archive/grp/init.luau"], -[8373, "src/Rosetta/archive/gzip/init.luau"], -[8558, "src/Rosetta/archive/iso/init.luau"], -[8630, "src/Rosetta/archive/lha/init.luau"], -[9055, "src/Rosetta/archive/lz4/init.luau"], -[9399, "src/Rosetta/archive/macbinary/init.luau"], -[9597, "src/Rosetta/archive/mpq/init.luau"], -[10003, "src/Rosetta/archive/mpq/Crypt.luau"], -[10068, "src/Rosetta/archive/pak/init.luau"], -[10202, "src/Rosetta/archive/rpm/init.luau"], -[10526, "src/Rosetta/archive/tar/init.luau"], -[10644, "src/Rosetta/archive/unitypackage/init.luau"], -[10881, "src/Rosetta/archive/uu/init.luau"], -[11151, "src/Rosetta/archive/vpk/init.luau"], -[11462, "src/Rosetta/archive/wad/init.luau"], -[11912, "src/Rosetta/archive/wad/Map.luau"], -[12342, "src/Rosetta/archive/wad/Picture.luau"], -[12444, "src/Rosetta/archive/xz/init.luau"], -[12544, "src/Rosetta/archive/yenc/init.luau"], -[12816, "src/Rosetta/archive/z/init.luau"], -[12912, "src/Rosetta/archive/zip/init.luau"], -[13131, "src/Rosetta/archive/zoo/init.luau"], -[13327, "src/Rosetta/archive/zst/init.luau"], -[13391, "src/Rosetta/audio/aac/init.luau"], -[13597, "src/Rosetta/audio/ac3/init.luau"], -[13743, "src/Rosetta/audio/adpcm/init.luau"], -[13888, "src/Rosetta/audio/adx/init.luau"], -[14119, "src/Rosetta/audio/aiff/init.luau"], -[14510, "src/Rosetta/audio/ape/init.luau"], -[14638, "src/Rosetta/audio/au/init.luau"], -[14799, "src/Rosetta/audio/brstm/init.luau"], -[15090, "src/Rosetta/audio/caf/init.luau"], -[15752, "src/Rosetta/audio/flac/init.luau"], -[15900, "src/Rosetta/audio/flac/Meta.luau"], -[16122, "src/Rosetta/audio/flac/Stream.luau"], -[16492, "src/Rosetta/audio/m4a/init.luau"], -[16826, "src/Rosetta/audio/mp3/init.luau"], -[17086, "src/Rosetta/audio/mp3/Index.luau"], -[17277, "src/Rosetta/audio/mp3/Stream.luau"], -[17504, "src/Rosetta/audio/mp3/Tags.luau"], -[17816, "src/Rosetta/audio/mpc/init.luau"], -[17910, "src/Rosetta/audio/opus/init.luau"], -[18288, "src/Rosetta/audio/opus/Encode.luau"], -[18399, "src/Rosetta/audio/qoa/init.luau"], -[18579, "src/Rosetta/audio/tta/init.luau"], -[18697, "src/Rosetta/audio/vag/init.luau"], -[18920, "src/Rosetta/audio/voc/init.luau"], -[19195, "src/Rosetta/audio/vorbis/init.luau"], -[19649, "src/Rosetta/audio/vorbis/Encode.luau"], -[20462, "src/Rosetta/audio/wav/init.luau"], -[21083, "src/Rosetta/audio/wav/Codecs.luau"], -[21249, "src/Rosetta/audio/wavpack/init.luau"], -[21456, "src/Rosetta/cad/step/init.luau"], -[21838, "src/Rosetta/cad/step/Brep.luau"], -[22073, "src/Rosetta/cad/step/Parse.luau"], -[22630, "src/Rosetta/cad/step/Write.luau"], -[22878, "src/Rosetta/codecs/audio/Aac/init.luau"], -[23197, "src/Rosetta/codecs/audio/Aac/Decode.luau"], -[24080, "src/Rosetta/codecs/audio/Aac/Tables.luau"], -[24415, "src/Rosetta/codecs/audio/Ac3/init.luau"], -[24574, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], -[25459, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], -[25560, "src/Rosetta/codecs/audio/Adpcm/init.luau"], -[26314, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], -[26616, "src/Rosetta/codecs/audio/Alac/init.luau"], -[26850, "src/Rosetta/codecs/audio/Alac/Decode.luau"], -[27269, "src/Rosetta/codecs/audio/Alac/Encode.luau"], -[27681, "src/Rosetta/codecs/audio/Ape/init.luau"], -[27896, "src/Rosetta/codecs/audio/Ape/Decode.luau"], -[28657, "src/Rosetta/codecs/audio/ApeTag.luau"], -[28754, "src/Rosetta/codecs/audio/Flac/init.luau"], -[28765, "src/Rosetta/codecs/audio/Flac/Encode.luau"], -[29714, "src/Rosetta/codecs/audio/Flac/Frame.luau"], -[30311, "src/Rosetta/codecs/audio/Hively/init.luau"], -[30507, "src/Rosetta/codecs/audio/Hively/Load.luau"], -[30756, "src/Rosetta/codecs/audio/Hively/Player.luau"], -[31714, "src/Rosetta/codecs/audio/Hively/Tables.luau"], -[31933, "src/Rosetta/codecs/audio/Mdct/init.luau"], -[32117, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], -[32326, "src/Rosetta/codecs/audio/MidiRender.luau"], -[32672, "src/Rosetta/codecs/audio/Mpa/init.luau"], -[32686, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], -[32745, "src/Rosetta/codecs/audio/Mpa/Core.luau"], -[34348, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], -[34640, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], -[35025, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], -[35666, "src/Rosetta/codecs/audio/Mpa/Header.luau"], -[35807, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], -[36033, "src/Rosetta/codecs/audio/Musepack/init.luau"], -[36378, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], -[37259, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], -[37637, "src/Rosetta/codecs/audio/Opus/init.luau"], -[37651, "src/Rosetta/codecs/audio/Opus/Celt.luau"], -[39498, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], -[40563, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], -[40623, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], -[41083, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], -[41420, "src/Rosetta/codecs/audio/Opus/Packet.luau"], -[41653, "src/Rosetta/codecs/audio/Opus/Silk.luau"], -[43689, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], -[44063, "src/Rosetta/codecs/audio/Pcm/init.luau"], -[44326, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], -[44623, "src/Rosetta/codecs/audio/Qoa/init.luau"], -[44905, "src/Rosetta/codecs/audio/Resample/init.luau"], -[45264, "src/Rosetta/codecs/audio/SoundFont/init.luau"], -[45318, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], -[45461, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], -[45974, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], -[46755, "src/Rosetta/codecs/audio/Stream.luau"], -[46916, "src/Rosetta/codecs/audio/Tracker/init.luau"], -[47398, "src/Rosetta/codecs/audio/Tracker/Load.luau"], -[47676, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], -[47845, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], -[47973, "src/Rosetta/codecs/audio/Tracker/Player.luau"], -[49961, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], -[50077, "src/Rosetta/codecs/audio/Tta/init.luau"], -[50194, "src/Rosetta/codecs/audio/Tta/Decode.luau"], -[50446, "src/Rosetta/codecs/audio/Vorbis/init.luau"], -[50459, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], -[50843, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], -[51409, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], -[51830, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], -[51869, "src/Rosetta/codecs/audio/VorbisComment.luau"], -[51921, "src/Rosetta/codecs/audio/WavPack/init.luau"], -[52143, "src/Rosetta/codecs/audio/WavPack/Block.luau"], -[53598, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], -[53661, "src/Rosetta/codecs/compress/Brotli/init.luau"], -[53748, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], -[54717, "src/Rosetta/codecs/compress/Brotli/Static.luau"], -[55585, "src/Rosetta/codecs/compress/Bzip2/init.luau"], -[55633, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], -[56149, "src/Rosetta/codecs/compress/Deflate/init.luau"], -[56475, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], -[56895, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], -[57330, "src/Rosetta/codecs/compress/Explode.luau"], -[57526, "src/Rosetta/codecs/compress/Lz4.luau"], -[57795, "src/Rosetta/codecs/compress/Lzh/init.luau"], -[58399, "src/Rosetta/codecs/compress/Lzma/init.luau"], -[58939, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], -[58977, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], -[59450, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], -[59626, "src/Rosetta/codecs/compress/Lzw/init.luau"], -[59894, "src/Rosetta/codecs/compress/Lzx.luau"], -[60328, "src/Rosetta/codecs/compress/PackBits.luau"], -[60418, "src/Rosetta/codecs/compress/Quantum.luau"], -[60655, "src/Rosetta/codecs/compress/UnixCompress.luau"], -[60959, "src/Rosetta/codecs/compress/Xxh32.luau"], -[61028, "src/Rosetta/codecs/compress/Zstd/init.luau"], -[61085, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], -[62043, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], -[62195, "src/Rosetta/codecs/entropy/Huffman.luau"], -[62477, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], -[62488, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], -[62702, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], -[62946, "src/Rosetta/codecs/font/Bitmap.luau"], -[63147, "src/Rosetta/codecs/font/Cff/init.luau"], -[63788, "src/Rosetta/codecs/font/GlyphNames.luau"], -[63938, "src/Rosetta/codecs/font/TrueType/init.luau"], -[64252, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], -[64644, "src/Rosetta/codecs/font/TrueType/Tables.luau"], -[65146, "src/Rosetta/codecs/image/Bcn/init.luau"], -[65253, "src/Rosetta/codecs/image/Bcn/Decode.luau"], -[65742, "src/Rosetta/codecs/image/Bcn/Encode.luau"], -[66171, "src/Rosetta/codecs/image/Blend.luau"], -[66550, "src/Rosetta/codecs/image/Dct/init.luau"], -[66931, "src/Rosetta/codecs/image/Etc.luau"], -[67229, "src/Rosetta/codecs/image/Half.luau"], -[67298, "src/Rosetta/codecs/image/Jpeg/init.luau"], -[67652, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], -[68060, "src/Rosetta/codecs/image/Jpeg/Color.luau"], -[68297, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], -[69057, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], -[69938, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], -[70384, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], -[70462, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], -[70529, "src/Rosetta/codecs/image/Pixels.luau"], -[70793, "src/Rosetta/codecs/image/Quantize/init.luau"], -[71252, "src/Rosetta/codecs/image/Raster.luau"], -[71949, "src/Rosetta/codecs/image/Texel.luau"], -[72322, "src/Rosetta/codecs/image/Texture.luau"], -[72467, "src/Rosetta/codecs/image/Vp8/init.luau"], -[72597, "src/Rosetta/codecs/image/Vp8/Decode.luau"], -[74553, "src/Rosetta/codecs/image/Vp8/Predict.luau"], -[74812, "src/Rosetta/codecs/image/Vp8/Tables.luau"], -[75061, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], -[75180, "src/Rosetta/codecs/image/Vp8L/init.luau"], -[75284, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], -[76137, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], -[77089, "src/Rosetta/codecs/image/Yuv.luau"], -[77357, "src/Rosetta/codecs/model/Draco/init.luau"], -[77689, "src/Rosetta/codecs/model/Draco/Attributes.luau"], -[78158, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], -[79347, "src/Rosetta/codecs/model/Draco/Int64.luau"], -[79496, "src/Rosetta/codecs/model/Draco/KdTree.luau"], -[79855, "src/Rosetta/codecs/model/Draco/Predict.luau"], -[80817, "src/Rosetta/codecs/model/Draco/Reader.luau"], -[81291, "src/Rosetta/codecs/model/Mat4.luau"], -[81550, "src/Rosetta/codecs/model/MeshFlatten.luau"], -[82078, "src/Rosetta/codecs/model/Minecraft/init.luau"], -[82630, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], -[82709, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], -[82816, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], -[83022, "src/Rosetta/codecs/model/Polygon.luau"], -[83256, "src/Rosetta/codecs/model/Rbx/init.luau"], -[83493, "src/Rosetta/codecs/model/Rbx/Binary.luau"], -[84247, "src/Rosetta/codecs/model/Rig.luau"], -[84490, "src/Rosetta/codecs/model/Sampler.luau"], -[84650, "src/Rosetta/codecs/model/Vrml/init.luau"], -[84798, "src/Rosetta/codecs/model/Vrml/Build.luau"], -[85372, "src/Rosetta/codecs/model/Vrml/Fields.luau"], -[85535, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], -[86284, "src/Rosetta/codecs/model/Vrml/Parse.luau"], -[86806, "src/Rosetta/codecs/model/Vrml/Write.luau"], -[87533, "src/Rosetta/codecs/model/Vrml/Xml.luau"], -[87765, "src/Rosetta/codecs/text/Json/init.luau"], -[88034, "src/Rosetta/codecs/text/Json/Decode.luau"], -[88448, "src/Rosetta/codecs/text/Json/Encode.luau"], -[88750, "src/Rosetta/codecs/text/Nbt/init.luau"], -[89103, "src/Rosetta/codecs/text/Nbt/Binary.luau"], -[89795, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], -[90435, "src/Rosetta/codecs/text/Nbt/Value.luau"], -[90673, "src/Rosetta/codecs/text/Text/init.luau"], -[90764, "src/Rosetta/codecs/text/Url/init.luau"], -[90969, "src/Rosetta/codecs/text/Xml/init.luau"], -[91372, "src/Rosetta/codecs/text/Xml/Parse.luau"], -[92112, "src/Rosetta/codecs/video/Dsp.luau"], -[92835, "src/Rosetta/codecs/video/H263/init.luau"], -[92991, "src/Rosetta/codecs/video/H263/Decoder.luau"], -[93849, "src/Rosetta/codecs/video/H263/Tables.luau"], -[94052, "src/Rosetta/codecs/video/H264/init.luau"], -[94425, "src/Rosetta/codecs/video/H264/Bitstream.luau"], -[94700, "src/Rosetta/codecs/video/H264/Cabac.luau"], -[95831, "src/Rosetta/codecs/video/H264/Cavlc.luau"], -[96599, "src/Rosetta/codecs/video/H264/Deblock.luau"], -[96857, "src/Rosetta/codecs/video/H264/Decoder.luau"], -[97866, "src/Rosetta/codecs/video/H264/Inter.luau"], -[98120, "src/Rosetta/codecs/video/H264/Intra.luau"], -[98527, "src/Rosetta/codecs/video/H264/Mb.luau"], -[99433, "src/Rosetta/codecs/video/H264/Params.luau"], -[99880, "src/Rosetta/codecs/video/H264/Slice.luau"], -[100131, "src/Rosetta/codecs/video/H264/Tables.luau"], -[100172, "src/Rosetta/codecs/video/H264/Transform.luau"], -[100337, "src/Rosetta/codecs/video/Legacy/init.luau"], -[100535, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], -[100832, "src/Rosetta/codecs/video/Legacy/Flic.luau"], -[101199, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], -[101317, "src/Rosetta/codecs/video/Legacy/Picture.luau"], -[101425, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], -[101698, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], -[102093, "src/Rosetta/codecs/video/Legacy/Smc.luau"], -[102270, "src/Rosetta/codecs/video/Mpeg1/init.luau"], -[102282, "src/Rosetta/codecs/video/Mpeg2/init.luau"], -[102649, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], -[104156, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], -[104295, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], -[104433, "src/Rosetta/codecs/video/Theora/init.luau"], -[104696, "src/Rosetta/codecs/video/Theora/Decoder.luau"], -[105960, "src/Rosetta/codecs/video/Theora/Header.luau"], -[106323, "src/Rosetta/codecs/video/Video/init.luau"], -[106880, "src/Rosetta/codecs/video/Video/Source.luau"], -[107165, "src/Rosetta/containers/Archive.luau"], -[107432, "src/Rosetta/containers/AudioWrap.luau"], -[107935, "src/Rosetta/containers/Avi/init.luau"], -[108487, "src/Rosetta/containers/Chunks.luau"], -[108622, "src/Rosetta/containers/Cpio.luau"], -[109050, "src/Rosetta/containers/Demux.luau"], -[109325, "src/Rosetta/containers/Ebml/init.luau"], -[109638, "src/Rosetta/containers/Fat.luau"], -[110326, "src/Rosetta/containers/Iso9660.luau"], -[110831, "src/Rosetta/containers/IsoBmff/init.luau"], -[111001, "src/Rosetta/containers/IsoBmff/Box.luau"], -[111189, "src/Rosetta/containers/IsoBmff/Demux.luau"], -[112034, "src/Rosetta/containers/IsoBmff/Meta.luau"], -[112555, "src/Rosetta/containers/IsoBmff/Mux.luau"], -[113071, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], -[113188, "src/Rosetta/containers/MacFile.luau"], -[113337, "src/Rosetta/containers/MpegEs.luau"], -[113503, "src/Rosetta/containers/MpegPs/init.luau"], -[113723, "src/Rosetta/containers/MpegTs/init.luau"], -[114515, "src/Rosetta/containers/Ogg/init.luau"], -[114940, "src/Rosetta/containers/Ogg/Mux.luau"], -[115135, "src/Rosetta/containers/Ogg/Page.luau"], -[115304, "src/Rosetta/containers/Riff/init.luau"], -[115621, "src/Rosetta/containers/Tar.luau"], -[116035, "src/Rosetta/containers/Zip/init.luau"], -[116667, "src/Rosetta/core/Adler32.luau"], -[116713, "src/Rosetta/core/Base64.luau"], -[116872, "src/Rosetta/core/Bits.luau"], -[117165, "src/Rosetta/core/Bytes.luau"], -[117692, "src/Rosetta/core/Crc16.luau"], -[117744, "src/Rosetta/core/Crc32.luau"], -[117856, "src/Rosetta/core/Err.luau"], -[117938, "src/Rosetta/core/Input.luau"], -[118014, "src/Rosetta/core/Md5.luau"], -[118173, "src/Rosetta/core/Sniff.luau"], -[118202, "src/Rosetta/data/cbor/init.luau"], -[118301, "src/Rosetta/data/cbor/Codec.luau"], -[118870, "src/Rosetta/data/csv/init.luau"], -[119182, "src/Rosetta/data/ini/init.luau"], -[119428, "src/Rosetta/data/json/init.luau"], -[119520, "src/Rosetta/data/msgpack/init.luau"], -[119609, "src/Rosetta/data/msgpack/Codec.luau"], -[120051, "src/Rosetta/data/nbt/init.luau"], -[120110, "src/Rosetta/data/plist/init.luau"], -[120416, "src/Rosetta/data/plist/Binary.luau"], -[120683, "src/Rosetta/data/snbt/init.luau"], -[120746, "src/Rosetta/data/toml/init.luau"], -[120813, "src/Rosetta/data/toml/Decode.luau"], -[121441, "src/Rosetta/data/toml/Encode.luau"], -[121650, "src/Rosetta/data/xml/init.luau"], -[121706, "src/Rosetta/data/yaml/init.luau"], -[121779, "src/Rosetta/data/yaml/Emit.luau"], -[122069, "src/Rosetta/data/yaml/Parse.luau"], -[123362, "src/Rosetta/font/bdf/init.luau"], -[123651, "src/Rosetta/font/bmfont/init.luau"], -[124078, "src/Rosetta/font/bmfont/Parse.luau"], -[124531, "src/Rosetta/font/eot/init.luau"], -[124763, "src/Rosetta/font/fon/init.luau"], -[125046, "src/Rosetta/font/hershey/init.luau"], -[125241, "src/Rosetta/font/pcf/init.luau"], -[125521, "src/Rosetta/font/psf/init.luau"], -[125841, "src/Rosetta/font/ttf/init.luau"], -[125892, "src/Rosetta/font/type1/init.luau"], -[126251, "src/Rosetta/font/type1/Charstring.luau"], -[126529, "src/Rosetta/font/woff/init.luau"], -[126661, "src/Rosetta/font/woff2/init.luau"], -[126718, "src/Rosetta/font/woff2/Rebuild.luau"], -[127258, "src/Rosetta/host/init.luau"], -[127303, "src/Rosetta/host/Love.luau"], -[127446, "src/Rosetta/host/LuaJIT.luau"], -[127496, "src/Rosetta/host/Luau.luau"], -[127519, "src/Rosetta/host/Roblox.luau"], -[127878, "src/Rosetta/image/ani/init.luau"], -[128058, "src/Rosetta/image/blp/init.luau"], -[128316, "src/Rosetta/image/bmp/init.luau"], -[128731, "src/Rosetta/image/dds/init.luau"], -[129214, "src/Rosetta/image/exr/init.luau"], -[129974, "src/Rosetta/image/exr/Codec.luau"], -[130085, "src/Rosetta/image/exr/Piz.luau"], -[130442, "src/Rosetta/image/gif/init.luau"], -[130958, "src/Rosetta/image/gif/Decode.luau"], -[131021, "src/Rosetta/image/hdr/init.luau"], -[131250, "src/Rosetta/image/hdr/Codec.luau"], -[131461, "src/Rosetta/image/icns/init.luau"], -[131792, "src/Rosetta/image/ico/init.luau"], -[132069, "src/Rosetta/image/ico/Dib.luau"], -[132164, "src/Rosetta/image/ilbm/init.luau"], -[132483, "src/Rosetta/image/jpeg/init.luau"], -[132619, "src/Rosetta/image/ktx/init.luau"], -[133279, "src/Rosetta/image/pcx/init.luau"], -[133543, "src/Rosetta/image/png/init.luau"], -[134123, "src/Rosetta/image/png/Apng.luau"], -[134203, "src/Rosetta/image/png/Decode.luau"], -[134443, "src/Rosetta/image/png/Encode.luau"], -[134598, "src/Rosetta/image/pnm/init.luau"], -[134976, "src/Rosetta/image/pnm/Codec.luau"], -[135253, "src/Rosetta/image/qoi/init.luau"], -[135375, "src/Rosetta/image/qoi/Codec.luau"], -[135525, "src/Rosetta/image/sgi/init.luau"], -[135810, "src/Rosetta/image/sunras/init.luau"], -[136056, "src/Rosetta/image/tga/init.luau"], -[136326, "src/Rosetta/image/tga/Codec.luau"], -[136478, "src/Rosetta/image/tiff/init.luau"], -[137305, "src/Rosetta/image/tiff/Pixels.luau"], -[137695, "src/Rosetta/image/tim/init.luau"], -[137937, "src/Rosetta/image/vtf/init.luau"], -[138172, "src/Rosetta/image/webp/init.luau"], -[138782, "src/Rosetta/image/webp/Alpha.luau"], -[138858, "src/Rosetta/image/webp/Anim.luau"], -[139013, "src/Rosetta/image/xbm/init.luau"], -[139174, "src/Rosetta/image/xpm/init.luau"], -[139442, "src/Rosetta/image/xpm/Names.luau"], -[139498, "src/Rosetta/layered/aseprite/init.luau"], -[140236, "src/Rosetta/layered/ora/init.luau"], -[140523, "src/Rosetta/layered/psd/init.luau"], -[141258, "src/Rosetta/layered/psd/Channels.luau"], -[141610, "src/Rosetta/model/3ds/init.luau"], -[141693, "src/Rosetta/model/3ds/Build.luau"], -[142340, "src/Rosetta/model/3ds/Read.luau"], -[142836, "src/Rosetta/model/3ds/Write.luau"], -[143641, "src/Rosetta/model/3mf/init.luau"], -[143723, "src/Rosetta/model/3mf/Read.luau"], -[144311, "src/Rosetta/model/3mf/Write.luau"], -[144716, "src/Rosetta/model/ase/init.luau"], -[144839, "src/Rosetta/model/ase/Build.luau"], -[145413, "src/Rosetta/model/ase/Parse.luau"], -[145482, "src/Rosetta/model/ase/Write.luau"], -[145945, "src/Rosetta/model/b3d/init.luau"], -[146000, "src/Rosetta/model/b3d/Read.luau"], -[146571, "src/Rosetta/model/bsp/init.luau"], -[146716, "src/Rosetta/model/bsp/Brush.luau"], -[146994, "src/Rosetta/model/bsp/Quake3.luau"], -[147249, "src/Rosetta/model/dae/init.luau"], -[147438, "src/Rosetta/model/dae/Math.luau"], -[147485, "src/Rosetta/model/dae/Read.luau"], -[149335, "src/Rosetta/model/dae/Write.luau"], -[149704, "src/Rosetta/model/fbx/init.luau"], -[149852, "src/Rosetta/model/fbx/Ascii.luau"], -[150122, "src/Rosetta/model/fbx/Binary.luau"], -[150577, "src/Rosetta/model/fbx/Read.luau"], -[151939, "src/Rosetta/model/fbx/Write.luau"], -[152924, "src/Rosetta/model/fbx/Xform.luau"], -[152965, "src/Rosetta/model/gltf/init.luau"], -[153202, "src/Rosetta/model/gltf/Pack.luau"], -[153271, "src/Rosetta/model/gltf/Read.luau"], -[154002, "src/Rosetta/model/gltf/Write.luau"], -[154682, "src/Rosetta/model/iqm/init.luau"], -[154758, "src/Rosetta/model/iqm/Read.luau"], -[155113, "src/Rosetta/model/iqm/Write.luau"], -[155800, "src/Rosetta/model/ldraw/init.luau"], -[155878, "src/Rosetta/model/ldraw/Colors.luau"], -[156196, "src/Rosetta/model/ldraw/Read.luau"], -[156773, "src/Rosetta/model/lwo/init.luau"], -[156849, "src/Rosetta/model/lwo/Build.luau"], -[157311, "src/Rosetta/model/lwo/Parse.luau"], -[157854, "src/Rosetta/model/mca/init.luau"], -[158196, "src/Rosetta/model/mca/Chunk.luau"], -[158329, "src/Rosetta/model/mca/Lz4Block.luau"], -[158399, "src/Rosetta/model/md2/init.luau"], -[158598, "src/Rosetta/model/md3/init.luau"], -[158826, "src/Rosetta/model/md5/init.luau"], -[158907, "src/Rosetta/model/md5/Read.luau"], -[159340, "src/Rosetta/model/mdl/init.luau"], -[159422, "src/Rosetta/model/mdl/HalfLife.luau"], -[159750, "src/Rosetta/model/mdl/Quake.luau"], -[159968, "src/Rosetta/model/ms3d/init.luau"], -[160040, "src/Rosetta/model/ms3d/Read.luau"], -[160486, "src/Rosetta/model/ms3d/Write.luau"], -[160955, "src/Rosetta/model/obj/init.luau"], -[161697, "src/Rosetta/model/obj/Mtl.luau"], -[161984, "src/Rosetta/model/off/init.luau"], -[162446, "src/Rosetta/model/ply/init.luau"], -[163551, "src/Rosetta/model/ply/Binary.luau"], -[163752, "src/Rosetta/model/pmx/init.luau"], -[163821, "src/Rosetta/model/pmx/Build.luau"], -[164117, "src/Rosetta/model/pmx/Pmd.luau"], -[164452, "src/Rosetta/model/pmx/Read.luau"], -[164856, "src/Rosetta/model/qb/init.luau"], -[165249, "src/Rosetta/model/rbxm/init.luau"], -[165841, "src/Rosetta/model/rbxmx/init.luau"], -[166494, "src/Rosetta/model/robloxmesh/init.luau"], -[167153, "src/Rosetta/model/robloxmesh/Parse.luau"], -[167610, "src/Rosetta/model/robloxmesh/Write.luau"], -[167719, "src/Rosetta/model/schematic/init.luau"], -[168040, "src/Rosetta/model/schematic/Common.luau"], -[168160, "src/Rosetta/model/schematic/Litematic.luau"], -[168371, "src/Rosetta/model/schematic/Mcedit.luau"], -[168615, "src/Rosetta/model/schematic/Sponge.luau"], -[168744, "src/Rosetta/model/smd/init.luau"], -[168811, "src/Rosetta/model/smd/Read.luau"], -[169080, "src/Rosetta/model/smd/Write.luau"], -[169323, "src/Rosetta/model/stl/init.luau"], -[169773, "src/Rosetta/model/stl/Decode.luau"], -[169847, "src/Rosetta/model/usda/init.luau"], -[170056, "src/Rosetta/model/usda/Build.luau"], -[171334, "src/Rosetta/model/usda/Parse.luau"], -[172132, "src/Rosetta/model/usda/Write.luau"], -[172949, "src/Rosetta/model/vox/init.luau"], -[173835, "src/Rosetta/model/vox/Grid.luau"], -[173892, "src/Rosetta/model/vrml/init.luau"], -[173958, "src/Rosetta/model/x/init.luau"], -[174088, "src/Rosetta/model/x/Build.luau"], -[174651, "src/Rosetta/model/x/Parse.luau"], -[174948, "src/Rosetta/model/x3d/init.luau"], -[175026, "src/Rosetta/music/669/init.luau"], -[175232, "src/Rosetta/music/ahx/init.luau"], -[175283, "src/Rosetta/music/far/init.luau"], -[175512, "src/Rosetta/music/hmp/init.luau"], -[175776, "src/Rosetta/music/hvl/init.luau"], -[175827, "src/Rosetta/music/it/init.luau"], -[176245, "src/Rosetta/music/it/Itsex.luau"], -[176361, "src/Rosetta/music/med/init.luau"], -[177008, "src/Rosetta/music/midi/init.luau"], -[177151, "src/Rosetta/music/midi/Smf.luau"], -[177562, "src/Rosetta/music/mod/init.luau"], -[177915, "src/Rosetta/music/mtm/init.luau"], -[178137, "src/Rosetta/music/mus/init.luau"], -[178294, "src/Rosetta/music/okt/init.luau"], -[178575, "src/Rosetta/music/ptm/init.luau"], -[178797, "src/Rosetta/music/s3m/init.luau"], -[179033, "src/Rosetta/music/sf2/init.luau"], -[179076, "src/Rosetta/music/stm/init.luau"], -[179307, "src/Rosetta/music/ult/init.luau"], -[179611, "src/Rosetta/music/umx/init.luau"], -[179827, "src/Rosetta/music/xm/init.luau"], -[180388, "src/Rosetta/music/xmi/init.luau"], -[180596, "src/Rosetta/ops/AudioOps.luau"], -[181045, "src/Rosetta/ops/ImageOps/init.luau"], -[181689, "src/Rosetta/ops/ImageOps/Kernels.luau"], -[182199, "src/Rosetta/ops/LayerOps.luau"], -[182292, "src/Rosetta/ops/MeshOps/init.luau"], -[183328, "src/Rosetta/ops/MeshOps/Greedy.luau"], -[183495, "src/Rosetta/ops/MusicOps.luau"], -[183843, "src/Rosetta/playlist/m3u/init.luau"], -[184196, "src/Rosetta/playlist/pls/init.luau"], -[184374, "src/Rosetta/playlist/xspf/init.luau"], -[184577, "src/Rosetta/subtitle/ass/init.luau"], -[185021, "src/Rosetta/subtitle/srt/init.luau"], -[185194, "src/Rosetta/subtitle/vtt/init.luau"], -[185397, "src/Rosetta/vector/svg/init.luau"], -[185483, "src/Rosetta/vector/svg/Parse.luau"], -[186229, "src/Rosetta/vector/svg/PathData.luau"], -[186597, "src/Rosetta/vector/svg/Render.luau"], -[187014, "src/Rosetta/vector/svg/Style.luau"], -[187386, "src/Rosetta/vector/svg/Write.luau"], -[187586, "src/Rosetta/vector/tiled/init.luau"], -[187766, "src/Rosetta/vector/tiled/Data.luau"], -[187917, "src/Rosetta/vector/tiled/Tmj.luau"], -[188548, "src/Rosetta/vector/tiled/Tmx.luau"], -[189160, "src/Rosetta/video/avi/init.luau"], -[189454, "src/Rosetta/video/fli/init.luau"], -[189605, "src/Rosetta/video/flv/init.luau"], -[189989, "src/Rosetta/video/flv/Amf.luau"], -[190147, "src/Rosetta/video/flv/Mux.luau"], -[190428, "src/Rosetta/video/h264/init.luau"], -[190567, "src/Rosetta/video/mkv/init.luau"], -[190723, "src/Rosetta/video/mkv/Mux.luau"], -[191002, "src/Rosetta/video/mkv/Parse.luau"], -[191723, "src/Rosetta/video/mp4/init.luau"], -[192051, "src/Rosetta/video/mpegps/init.luau"], -[192238, "src/Rosetta/video/mpegts/init.luau"], -[192476, "src/Rosetta/video/ogv/init.luau"], -[192871, "src/Rosetta/video/smk/init.luau"], -[193180, "src/Rosetta/video/smk/Audio.luau"], -[193300, "src/Rosetta/video/y4m/init.luau"] +[3685, "src/Rosetta/Types.luau"], +[4768, "src/Rosetta/archive/7z/init.luau"], +[5153, "src/Rosetta/archive/7z/Header.luau"], +[5680, "src/Rosetta/archive/adf/init.luau"], +[5962, "src/Rosetta/archive/applesingle/init.luau"], +[6148, "src/Rosetta/archive/ar/init.luau"], +[6551, "src/Rosetta/archive/arj/init.luau"], +[6761, "src/Rosetta/archive/binhex/init.luau"], +[7010, "src/Rosetta/archive/br/init.luau"], +[7085, "src/Rosetta/archive/bz2/init.luau"], +[7149, "src/Rosetta/archive/cab/init.luau"], +[7562, "src/Rosetta/archive/cab/Sum.luau"], +[7603, "src/Rosetta/archive/cpio/init.luau"], +[7771, "src/Rosetta/archive/d64/init.luau"], +[8185, "src/Rosetta/archive/fat/init.luau"], +[8307, "src/Rosetta/archive/grp/init.luau"], +[8421, "src/Rosetta/archive/gzip/init.luau"], +[8606, "src/Rosetta/archive/iso/init.luau"], +[8678, "src/Rosetta/archive/lha/init.luau"], +[9103, "src/Rosetta/archive/lz4/init.luau"], +[9447, "src/Rosetta/archive/macbinary/init.luau"], +[9645, "src/Rosetta/archive/mpq/init.luau"], +[10051, "src/Rosetta/archive/mpq/Crypt.luau"], +[10116, "src/Rosetta/archive/pak/init.luau"], +[10250, "src/Rosetta/archive/rpm/init.luau"], +[10574, "src/Rosetta/archive/tar/init.luau"], +[10692, "src/Rosetta/archive/uu/init.luau"], +[10962, "src/Rosetta/archive/vpk/init.luau"], +[11273, "src/Rosetta/archive/wad/init.luau"], +[11723, "src/Rosetta/archive/wad/Map.luau"], +[12153, "src/Rosetta/archive/wad/Picture.luau"], +[12255, "src/Rosetta/archive/wad2/init.luau"], +[12537, "src/Rosetta/archive/xz/init.luau"], +[12637, "src/Rosetta/archive/yenc/init.luau"], +[12909, "src/Rosetta/archive/z/init.luau"], +[13005, "src/Rosetta/archive/zip/init.luau"], +[13224, "src/Rosetta/archive/zoo/init.luau"], +[13420, "src/Rosetta/archive/zst/init.luau"], +[13484, "src/Rosetta/audio/aac/init.luau"], +[13690, "src/Rosetta/audio/ac3/init.luau"], +[13836, "src/Rosetta/audio/adpcm/init.luau"], +[13981, "src/Rosetta/audio/adx/init.luau"], +[14212, "src/Rosetta/audio/aiff/init.luau"], +[14603, "src/Rosetta/audio/ape/init.luau"], +[14731, "src/Rosetta/audio/au/init.luau"], +[14892, "src/Rosetta/audio/brstm/init.luau"], +[15183, "src/Rosetta/audio/caf/init.luau"], +[15845, "src/Rosetta/audio/flac/init.luau"], +[15993, "src/Rosetta/audio/flac/Meta.luau"], +[16215, "src/Rosetta/audio/flac/Stream.luau"], +[16585, "src/Rosetta/audio/m4a/init.luau"], +[16919, "src/Rosetta/audio/mp3/init.luau"], +[17179, "src/Rosetta/audio/mp3/Index.luau"], +[17370, "src/Rosetta/audio/mp3/Stream.luau"], +[17597, "src/Rosetta/audio/mp3/Tags.luau"], +[17909, "src/Rosetta/audio/mpc/init.luau"], +[18003, "src/Rosetta/audio/opus/init.luau"], +[18381, "src/Rosetta/audio/opus/Encode.luau"], +[18492, "src/Rosetta/audio/qoa/init.luau"], +[18672, "src/Rosetta/audio/tta/init.luau"], +[18790, "src/Rosetta/audio/vag/init.luau"], +[19013, "src/Rosetta/audio/voc/init.luau"], +[19288, "src/Rosetta/audio/vorbis/init.luau"], +[19742, "src/Rosetta/audio/vorbis/Encode.luau"], +[20555, "src/Rosetta/audio/wav/init.luau"], +[21176, "src/Rosetta/audio/wav/Codecs.luau"], +[21342, "src/Rosetta/audio/wavpack/init.luau"], +[21549, "src/Rosetta/cad/step/init.luau"], +[21931, "src/Rosetta/cad/step/Brep.luau"], +[22166, "src/Rosetta/cad/step/Parse.luau"], +[22723, "src/Rosetta/cad/step/Write.luau"], +[22971, "src/Rosetta/codecs/audio/Aac/init.luau"], +[23290, "src/Rosetta/codecs/audio/Aac/Decode.luau"], +[24173, "src/Rosetta/codecs/audio/Aac/Tables.luau"], +[24508, "src/Rosetta/codecs/audio/Ac3/init.luau"], +[24667, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], +[25552, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], +[25653, "src/Rosetta/codecs/audio/Adpcm/init.luau"], +[26407, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], +[26709, "src/Rosetta/codecs/audio/Alac/init.luau"], +[26943, "src/Rosetta/codecs/audio/Alac/Decode.luau"], +[27362, "src/Rosetta/codecs/audio/Alac/Encode.luau"], +[27774, "src/Rosetta/codecs/audio/Ape/init.luau"], +[27989, "src/Rosetta/codecs/audio/Ape/Decode.luau"], +[28750, "src/Rosetta/codecs/audio/ApeTag.luau"], +[28847, "src/Rosetta/codecs/audio/Flac/init.luau"], +[28858, "src/Rosetta/codecs/audio/Flac/Encode.luau"], +[29807, "src/Rosetta/codecs/audio/Flac/Frame.luau"], +[30404, "src/Rosetta/codecs/audio/Hively/init.luau"], +[30600, "src/Rosetta/codecs/audio/Hively/Load.luau"], +[30849, "src/Rosetta/codecs/audio/Hively/Player.luau"], +[31807, "src/Rosetta/codecs/audio/Hively/Tables.luau"], +[32026, "src/Rosetta/codecs/audio/Mdct/init.luau"], +[32210, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], +[32419, "src/Rosetta/codecs/audio/MidiRender.luau"], +[32765, "src/Rosetta/codecs/audio/Mpa/init.luau"], +[32779, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], +[32838, "src/Rosetta/codecs/audio/Mpa/Core.luau"], +[34441, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], +[34733, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], +[35118, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], +[35759, "src/Rosetta/codecs/audio/Mpa/Header.luau"], +[35900, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], +[36126, "src/Rosetta/codecs/audio/Musepack/init.luau"], +[36471, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], +[37352, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[37730, "src/Rosetta/codecs/audio/Opus/init.luau"], +[37744, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[39591, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[40656, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[40716, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[41176, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[41513, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[41746, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[43782, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[44156, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[44419, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[44716, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[44998, "src/Rosetta/codecs/audio/Resample/init.luau"], +[45357, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[45411, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[45554, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[46067, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[46848, "src/Rosetta/codecs/audio/Stream.luau"], +[47009, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[47491, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[47769, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[47938, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[48066, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[50054, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[50170, "src/Rosetta/codecs/audio/Tta/init.luau"], +[50287, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[50539, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[50552, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[50936, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[51502, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[51923, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[51962, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[52014, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[52236, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[53691, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[53754, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[53841, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[54810, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[55678, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[55726, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[56242, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[56568, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[56988, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[57423, "src/Rosetta/codecs/compress/Explode.luau"], +[57619, "src/Rosetta/codecs/compress/Lz4.luau"], +[57888, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[58492, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[59032, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[59070, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[59543, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[59719, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[59987, "src/Rosetta/codecs/compress/Lzx.luau"], +[60421, "src/Rosetta/codecs/compress/PackBits.luau"], +[60511, "src/Rosetta/codecs/compress/Quantum.luau"], +[60748, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[61052, "src/Rosetta/codecs/compress/Xxh32.luau"], +[61121, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[61178, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[62136, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[62288, "src/Rosetta/codecs/entropy/Huffman.luau"], +[62570, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[62581, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[62795, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[63039, "src/Rosetta/codecs/font/Bitmap.luau"], +[63240, "src/Rosetta/codecs/font/Cff/init.luau"], +[63881, "src/Rosetta/codecs/font/GlyphNames.luau"], +[64031, "src/Rosetta/codecs/font/TrueType/init.luau"], +[64345, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[64737, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[65239, "src/Rosetta/codecs/image/Bcn/init.luau"], +[65346, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[65835, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[66264, "src/Rosetta/codecs/image/Blend.luau"], +[66643, "src/Rosetta/codecs/image/Dct/init.luau"], +[67024, "src/Rosetta/codecs/image/Etc.luau"], +[67322, "src/Rosetta/codecs/image/Half.luau"], +[67391, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[67745, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[68153, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[68390, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[69150, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[70031, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[70477, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[70555, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[70622, "src/Rosetta/codecs/image/Miptex.luau"], +[70922, "src/Rosetta/codecs/image/Pixels.luau"], +[71242, "src/Rosetta/codecs/image/Quantize/init.luau"], +[71701, "src/Rosetta/codecs/image/Raster.luau"], +[72398, "src/Rosetta/codecs/image/Texel.luau"], +[72771, "src/Rosetta/codecs/image/Texture.luau"], +[72916, "src/Rosetta/codecs/image/Vp8/init.luau"], +[73046, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[75002, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[75261, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[75510, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[75629, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[75733, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[76586, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[77538, "src/Rosetta/codecs/image/Yuv.luau"], +[77806, "src/Rosetta/codecs/model/Brush.luau"], +[78446, "src/Rosetta/codecs/model/Draco/init.luau"], +[78778, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[79247, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[80436, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[80585, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[80944, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[81906, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[82380, "src/Rosetta/codecs/model/Mat4.luau"], +[82639, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[83167, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[83719, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[83798, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[83905, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[84111, "src/Rosetta/codecs/model/Patch.luau"], +[84235, "src/Rosetta/codecs/model/Polygon.luau"], +[84469, "src/Rosetta/codecs/model/Rbx/init.luau"], +[84706, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[85460, "src/Rosetta/codecs/model/Rig.luau"], +[85703, "src/Rosetta/codecs/model/Sampler.luau"], +[85863, "src/Rosetta/codecs/model/Vrml/init.luau"], +[86011, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[86585, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[86748, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[87497, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[88019, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[88746, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[88978, "src/Rosetta/codecs/text/Json/init.luau"], +[89247, "src/Rosetta/codecs/text/Json/Decode.luau"], +[89661, "src/Rosetta/codecs/text/Json/Encode.luau"], +[89963, "src/Rosetta/codecs/text/Nbt/init.luau"], +[90316, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[91008, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[91648, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[91886, "src/Rosetta/codecs/text/Text/init.luau"], +[91977, "src/Rosetta/codecs/text/Url/init.luau"], +[92182, "src/Rosetta/codecs/text/Xml/init.luau"], +[92585, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[93325, "src/Rosetta/codecs/video/Dsp.luau"], +[94048, "src/Rosetta/codecs/video/H263/init.luau"], +[94204, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[95062, "src/Rosetta/codecs/video/H263/Tables.luau"], +[95265, "src/Rosetta/codecs/video/H264/init.luau"], +[95638, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[95913, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[97044, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[97812, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[98070, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[99079, "src/Rosetta/codecs/video/H264/Inter.luau"], +[99333, "src/Rosetta/codecs/video/H264/Intra.luau"], +[99740, "src/Rosetta/codecs/video/H264/Mb.luau"], +[100646, "src/Rosetta/codecs/video/H264/Params.luau"], +[101093, "src/Rosetta/codecs/video/H264/Slice.luau"], +[101344, "src/Rosetta/codecs/video/H264/Tables.luau"], +[101385, "src/Rosetta/codecs/video/H264/Transform.luau"], +[101550, "src/Rosetta/codecs/video/Legacy/init.luau"], +[101748, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[102045, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[102412, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[102530, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[102638, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[102911, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[103306, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[103483, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[103495, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[103862, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[105369, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[105508, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[105646, "src/Rosetta/codecs/video/Theora/init.luau"], +[105909, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[107173, "src/Rosetta/codecs/video/Theora/Header.luau"], +[107536, "src/Rosetta/codecs/video/Video/init.luau"], +[108093, "src/Rosetta/codecs/video/Video/Source.luau"], +[108378, "src/Rosetta/containers/Archive.luau"], +[108645, "src/Rosetta/containers/AudioWrap.luau"], +[109148, "src/Rosetta/containers/Avi/init.luau"], +[109700, "src/Rosetta/containers/Chunks.luau"], +[109835, "src/Rosetta/containers/Cpio.luau"], +[110263, "src/Rosetta/containers/Demux.luau"], +[110538, "src/Rosetta/containers/Ebml/init.luau"], +[110851, "src/Rosetta/containers/Fat.luau"], +[111539, "src/Rosetta/containers/Iso9660.luau"], +[112044, "src/Rosetta/containers/IsoBmff/init.luau"], +[112214, "src/Rosetta/containers/IsoBmff/Box.luau"], +[112402, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[113247, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[113768, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[114284, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[114401, "src/Rosetta/containers/MacFile.luau"], +[114550, "src/Rosetta/containers/MpegEs.luau"], +[114716, "src/Rosetta/containers/MpegPs/init.luau"], +[114936, "src/Rosetta/containers/MpegTs/init.luau"], +[115728, "src/Rosetta/containers/Ogg/init.luau"], +[116153, "src/Rosetta/containers/Ogg/Mux.luau"], +[116348, "src/Rosetta/containers/Ogg/Page.luau"], +[116517, "src/Rosetta/containers/Riff/init.luau"], +[116834, "src/Rosetta/containers/Tar.luau"], +[117248, "src/Rosetta/containers/Zip/init.luau"], +[117880, "src/Rosetta/core/Adler32.luau"], +[117926, "src/Rosetta/core/Base64.luau"], +[118085, "src/Rosetta/core/Bits.luau"], +[118378, "src/Rosetta/core/Bytes.luau"], +[118905, "src/Rosetta/core/Crc16.luau"], +[118957, "src/Rosetta/core/Crc32.luau"], +[119069, "src/Rosetta/core/Err.luau"], +[119151, "src/Rosetta/core/Input.luau"], +[119227, "src/Rosetta/core/Md5.luau"], +[119386, "src/Rosetta/core/Sniff.luau"], +[119415, "src/Rosetta/data/cbor/init.luau"], +[119514, "src/Rosetta/data/cbor/Codec.luau"], +[120083, "src/Rosetta/data/csv/init.luau"], +[120395, "src/Rosetta/data/ini/init.luau"], +[120641, "src/Rosetta/data/json/init.luau"], +[120733, "src/Rosetta/data/msgpack/init.luau"], +[120822, "src/Rosetta/data/msgpack/Codec.luau"], +[121264, "src/Rosetta/data/nbt/init.luau"], +[121323, "src/Rosetta/data/plist/init.luau"], +[121629, "src/Rosetta/data/plist/Binary.luau"], +[121896, "src/Rosetta/data/q3shader/init.luau"], +[122135, "src/Rosetta/data/q3skin/init.luau"], +[122231, "src/Rosetta/data/snbt/init.luau"], +[122294, "src/Rosetta/data/toml/init.luau"], +[122361, "src/Rosetta/data/toml/Decode.luau"], +[122989, "src/Rosetta/data/toml/Encode.luau"], +[123198, "src/Rosetta/data/xml/init.luau"], +[123254, "src/Rosetta/data/yaml/init.luau"], +[123327, "src/Rosetta/data/yaml/Emit.luau"], +[123617, "src/Rosetta/data/yaml/Parse.luau"], +[124910, "src/Rosetta/font/bdf/init.luau"], +[125199, "src/Rosetta/font/bmfont/init.luau"], +[125626, "src/Rosetta/font/bmfont/Parse.luau"], +[126079, "src/Rosetta/font/eot/init.luau"], +[126311, "src/Rosetta/font/fon/init.luau"], +[126594, "src/Rosetta/font/hershey/init.luau"], +[126789, "src/Rosetta/font/pcf/init.luau"], +[127069, "src/Rosetta/font/psf/init.luau"], +[127389, "src/Rosetta/font/ttf/init.luau"], +[127440, "src/Rosetta/font/type1/init.luau"], +[127799, "src/Rosetta/font/type1/Charstring.luau"], +[128077, "src/Rosetta/font/woff/init.luau"], +[128209, "src/Rosetta/font/woff2/init.luau"], +[128266, "src/Rosetta/font/woff2/Rebuild.luau"], +[128806, "src/Rosetta/host/init.luau"], +[128851, "src/Rosetta/host/Love.luau"], +[128994, "src/Rosetta/host/LuaJIT.luau"], +[129044, "src/Rosetta/host/Luau.luau"], +[129067, "src/Rosetta/host/Roblox.luau"], +[129426, "src/Rosetta/image/ani/init.luau"], +[129606, "src/Rosetta/image/blp/init.luau"], +[129864, "src/Rosetta/image/bmp/init.luau"], +[130279, "src/Rosetta/image/dds/init.luau"], +[130762, "src/Rosetta/image/exr/init.luau"], +[131522, "src/Rosetta/image/exr/Codec.luau"], +[131633, "src/Rosetta/image/exr/Piz.luau"], +[131990, "src/Rosetta/image/gif/init.luau"], +[132506, "src/Rosetta/image/gif/Decode.luau"], +[132569, "src/Rosetta/image/hdr/init.luau"], +[132798, "src/Rosetta/image/hdr/Codec.luau"], +[133009, "src/Rosetta/image/icns/init.luau"], +[133340, "src/Rosetta/image/ico/init.luau"], +[133617, "src/Rosetta/image/ico/Dib.luau"], +[133712, "src/Rosetta/image/ilbm/init.luau"], +[134031, "src/Rosetta/image/jpeg/init.luau"], +[134167, "src/Rosetta/image/ktx/init.luau"], +[134827, "src/Rosetta/image/lmp/init.luau"], +[134960, "src/Rosetta/image/pcx/init.luau"], +[135224, "src/Rosetta/image/png/init.luau"], +[135804, "src/Rosetta/image/png/Apng.luau"], +[135884, "src/Rosetta/image/png/Decode.luau"], +[136124, "src/Rosetta/image/png/Encode.luau"], +[136279, "src/Rosetta/image/pnm/init.luau"], +[136657, "src/Rosetta/image/pnm/Codec.luau"], +[136934, "src/Rosetta/image/qoi/init.luau"], +[137056, "src/Rosetta/image/qoi/Codec.luau"], +[137206, "src/Rosetta/image/sgi/init.luau"], +[137491, "src/Rosetta/image/spr/init.luau"], +[137804, "src/Rosetta/image/sunras/init.luau"], +[138050, "src/Rosetta/image/tga/init.luau"], +[138320, "src/Rosetta/image/tga/Codec.luau"], +[138472, "src/Rosetta/image/tiff/init.luau"], +[139299, "src/Rosetta/image/tiff/Pixels.luau"], +[139689, "src/Rosetta/image/tim/init.luau"], +[139931, "src/Rosetta/image/vtf/init.luau"], +[140166, "src/Rosetta/image/webp/init.luau"], +[140776, "src/Rosetta/image/webp/Alpha.luau"], +[140852, "src/Rosetta/image/webp/Anim.luau"], +[141007, "src/Rosetta/image/xbm/init.luau"], +[141168, "src/Rosetta/image/xpm/init.luau"], +[141436, "src/Rosetta/image/xpm/Names.luau"], +[141492, "src/Rosetta/layered/aseprite/init.luau"], +[142230, "src/Rosetta/layered/ora/init.luau"], +[142517, "src/Rosetta/layered/psd/init.luau"], +[143252, "src/Rosetta/layered/psd/Channels.luau"], +[143604, "src/Rosetta/model/3ds/init.luau"], +[143687, "src/Rosetta/model/3ds/Build.luau"], +[144334, "src/Rosetta/model/3ds/Read.luau"], +[144830, "src/Rosetta/model/3ds/Write.luau"], +[145635, "src/Rosetta/model/3mf/init.luau"], +[145717, "src/Rosetta/model/3mf/Read.luau"], +[146305, "src/Rosetta/model/3mf/Write.luau"], +[146710, "src/Rosetta/model/b3d/init.luau"], +[146765, "src/Rosetta/model/b3d/Read.luau"], +[147336, "src/Rosetta/model/bsp/init.luau"], +[147527, "src/Rosetta/model/bsp/Lightmap.luau"], +[147593, "src/Rosetta/model/bsp/Quake.luau"], +[147980, "src/Rosetta/model/bsp/Quake3.luau"], +[148208, "src/Rosetta/model/bsp/Tree.luau"], +[148596, "src/Rosetta/model/dae/init.luau"], +[148785, "src/Rosetta/model/dae/Math.luau"], +[148832, "src/Rosetta/model/dae/Read.luau"], +[150682, "src/Rosetta/model/dae/Write.luau"], +[151051, "src/Rosetta/model/fbx/init.luau"], +[151199, "src/Rosetta/model/fbx/Ascii.luau"], +[151469, "src/Rosetta/model/fbx/Binary.luau"], +[151924, "src/Rosetta/model/fbx/Read.luau"], +[153286, "src/Rosetta/model/fbx/Write.luau"], +[154271, "src/Rosetta/model/fbx/Xform.luau"], +[154312, "src/Rosetta/model/gltf/init.luau"], +[154549, "src/Rosetta/model/gltf/Pack.luau"], +[154618, "src/Rosetta/model/gltf/Read.luau"], +[155349, "src/Rosetta/model/gltf/Write.luau"], +[156029, "src/Rosetta/model/iqm/init.luau"], +[156105, "src/Rosetta/model/iqm/Read.luau"], +[156460, "src/Rosetta/model/iqm/Write.luau"], +[157147, "src/Rosetta/model/ldraw/init.luau"], +[157225, "src/Rosetta/model/ldraw/Colors.luau"], +[157543, "src/Rosetta/model/ldraw/Read.luau"], +[158120, "src/Rosetta/model/lwo/init.luau"], +[158196, "src/Rosetta/model/lwo/Build.luau"], +[158658, "src/Rosetta/model/lwo/Parse.luau"], +[159201, "src/Rosetta/model/map/init.luau"], +[159518, "src/Rosetta/model/map/Build.luau"], +[159761, "src/Rosetta/model/map/Parse.luau"], +[160146, "src/Rosetta/model/map/Write.luau"], +[160292, "src/Rosetta/model/mca/init.luau"], +[160634, "src/Rosetta/model/mca/Chunk.luau"], +[160767, "src/Rosetta/model/mca/Lz4Block.luau"], +[160837, "src/Rosetta/model/md2/init.luau"], +[161036, "src/Rosetta/model/md3/init.luau"], +[161264, "src/Rosetta/model/md5/init.luau"], +[161345, "src/Rosetta/model/md5/Read.luau"], +[161778, "src/Rosetta/model/mdl/init.luau"], +[161860, "src/Rosetta/model/mdl/HalfLife.luau"], +[162188, "src/Rosetta/model/mdl/Quake.luau"], +[162406, "src/Rosetta/model/ms3d/init.luau"], +[162478, "src/Rosetta/model/ms3d/Read.luau"], +[162924, "src/Rosetta/model/ms3d/Write.luau"], +[163393, "src/Rosetta/model/obj/init.luau"], +[164135, "src/Rosetta/model/obj/Mtl.luau"], +[164422, "src/Rosetta/model/off/init.luau"], +[164884, "src/Rosetta/model/ply/init.luau"], +[165989, "src/Rosetta/model/ply/Binary.luau"], +[166190, "src/Rosetta/model/pmx/init.luau"], +[166259, "src/Rosetta/model/pmx/Build.luau"], +[166555, "src/Rosetta/model/pmx/Pmd.luau"], +[166890, "src/Rosetta/model/pmx/Read.luau"], +[167294, "src/Rosetta/model/qb/init.luau"], +[167687, "src/Rosetta/model/rbxm/init.luau"], +[168279, "src/Rosetta/model/rbxmx/init.luau"], +[168932, "src/Rosetta/model/robloxmesh/init.luau"], +[169591, "src/Rosetta/model/robloxmesh/Parse.luau"], +[170048, "src/Rosetta/model/robloxmesh/Write.luau"], +[170157, "src/Rosetta/model/schematic/init.luau"], +[170478, "src/Rosetta/model/schematic/Common.luau"], +[170598, "src/Rosetta/model/schematic/Litematic.luau"], +[170809, "src/Rosetta/model/schematic/Mcedit.luau"], +[171053, "src/Rosetta/model/schematic/Sponge.luau"], +[171182, "src/Rosetta/model/smd/init.luau"], +[171249, "src/Rosetta/model/smd/Read.luau"], +[171518, "src/Rosetta/model/smd/Write.luau"], +[171761, "src/Rosetta/model/stl/init.luau"], +[172211, "src/Rosetta/model/stl/Decode.luau"], +[172285, "src/Rosetta/model/usda/init.luau"], +[172494, "src/Rosetta/model/usda/Build.luau"], +[173772, "src/Rosetta/model/usda/Parse.luau"], +[174570, "src/Rosetta/model/usda/Write.luau"], +[175387, "src/Rosetta/model/vox/init.luau"], +[176273, "src/Rosetta/model/vox/Grid.luau"], +[176330, "src/Rosetta/model/vrml/init.luau"], +[176396, "src/Rosetta/model/x/init.luau"], +[176526, "src/Rosetta/model/x/Build.luau"], +[177089, "src/Rosetta/model/x/Parse.luau"], +[177386, "src/Rosetta/model/x3d/init.luau"], +[177464, "src/Rosetta/music/669/init.luau"], +[177670, "src/Rosetta/music/ahx/init.luau"], +[177721, "src/Rosetta/music/far/init.luau"], +[177950, "src/Rosetta/music/hmp/init.luau"], +[178214, "src/Rosetta/music/hvl/init.luau"], +[178265, "src/Rosetta/music/it/init.luau"], +[178683, "src/Rosetta/music/it/Itsex.luau"], +[178799, "src/Rosetta/music/med/init.luau"], +[179446, "src/Rosetta/music/midi/init.luau"], +[179589, "src/Rosetta/music/midi/Smf.luau"], +[180000, "src/Rosetta/music/mod/init.luau"], +[180353, "src/Rosetta/music/mtm/init.luau"], +[180575, "src/Rosetta/music/mus/init.luau"], +[180732, "src/Rosetta/music/okt/init.luau"], +[181013, "src/Rosetta/music/ptm/init.luau"], +[181235, "src/Rosetta/music/s3m/init.luau"], +[181471, "src/Rosetta/music/sf2/init.luau"], +[181514, "src/Rosetta/music/stm/init.luau"], +[181745, "src/Rosetta/music/ult/init.luau"], +[182049, "src/Rosetta/music/umx/init.luau"], +[182265, "src/Rosetta/music/xm/init.luau"], +[182826, "src/Rosetta/music/xmi/init.luau"], +[183034, "src/Rosetta/ops/AudioOps.luau"], +[183483, "src/Rosetta/ops/ImageOps/init.luau"], +[184127, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[184637, "src/Rosetta/ops/LayerOps.luau"], +[184730, "src/Rosetta/ops/MeshOps/init.luau"], +[185766, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[185933, "src/Rosetta/ops/MusicOps.luau"], +[186281, "src/Rosetta/playlist/m3u/init.luau"], +[186634, "src/Rosetta/playlist/pls/init.luau"], +[186812, "src/Rosetta/playlist/xspf/init.luau"], +[187015, "src/Rosetta/subtitle/ass/init.luau"], +[187459, "src/Rosetta/subtitle/srt/init.luau"], +[187632, "src/Rosetta/subtitle/vtt/init.luau"], +[187835, "src/Rosetta/vector/svg/init.luau"], +[187921, "src/Rosetta/vector/svg/Parse.luau"], +[188667, "src/Rosetta/vector/svg/PathData.luau"], +[189035, "src/Rosetta/vector/svg/Render.luau"], +[189452, "src/Rosetta/vector/svg/Style.luau"], +[189824, "src/Rosetta/vector/svg/Write.luau"], +[190024, "src/Rosetta/vector/tiled/init.luau"], +[190204, "src/Rosetta/vector/tiled/Data.luau"], +[190355, "src/Rosetta/vector/tiled/Tmj.luau"], +[190986, "src/Rosetta/vector/tiled/Tmx.luau"], +[191598, "src/Rosetta/video/avi/init.luau"], +[191892, "src/Rosetta/video/fli/init.luau"], +[192043, "src/Rosetta/video/flv/init.luau"], +[192427, "src/Rosetta/video/flv/Amf.luau"], +[192585, "src/Rosetta/video/flv/Mux.luau"], +[192866, "src/Rosetta/video/h264/init.luau"], +[193005, "src/Rosetta/video/mkv/init.luau"], +[193161, "src/Rosetta/video/mkv/Mux.luau"], +[193440, "src/Rosetta/video/mkv/Parse.luau"], +[194161, "src/Rosetta/video/mp4/init.luau"], +[194489, "src/Rosetta/video/mpegps/init.luau"], +[194676, "src/Rosetta/video/mpegts/init.luau"], +[194914, "src/Rosetta/video/ogv/init.luau"], +[195309, "src/Rosetta/video/smk/init.luau"], +[195618, "src/Rosetta/video/smk/Audio.luau"], +[195738, "src/Rosetta/video/y4m/init.luau"] ] diff --git a/docs/FORMATS.md b/docs/FORMATS.md index e47a002..43386b5 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -17,11 +17,13 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | image | ilbm | .iff .ilbm .lbm .pbm | yes | yes | alpha: true, palette: true, depths: 1, 2, 3, 4, 5, 6, 7, 8, 24, 32 | `tests/image/ilbm.luau` | | image | jpeg | .jpg .jpeg .jpe .jfif | yes | yes | lossy: true, alpha: false, depths: 8, 12, progressive: true, arithmetic: true | `tests/image/jpeg.luau` | | image | ktx | .ktx2 .ktx | yes | yes | alpha: true, float: true, mipmaps: true, cubemap: true, compressed: "bc1", "bc2", "bc3", "bc4", "bc5", "bc6h", "bc7", "etc1", "etc2", "eac" | `tests/image/ktx.luau` | +| image | lmp | .lmp | yes | yes | alpha: true, depths: 8, variants: "qpic", "palette", "colormap" | `tests/image/lmp.luau` | | image | pcx | .pcx .pcc .dcx | yes | yes | alpha: true, palette: true, depths: 1, 2, 4, 8, 24, 32 | `tests/image/pcx.luau` | | image | png | .png .apng | yes | yes | animation: true, alpha: true, depths: 1, 2, 4, 8, 16 | `tests/image/png.luau` | | image | pnm | .pnm .pbm .pgm .ppm .pam .pfm | yes | yes | alpha: true, depths: 1, 8, 16, 32, float: true | `tests/image/pnm.luau` | | image | qoi | .qoi | yes | yes | alpha: true, depths: 8 | `tests/image/qoi.luau` | | image | sgi | .sgi .rgb .rgba .bw .int .inta | yes | yes | alpha: true, depths: 8, 16 | `tests/image/sgi.luau` | +| image | spr | .spr | yes | yes | alpha: true, animation: true, variants: "quake", "halflife", "spr32" | `tests/image/spr.luau` | | image | sunras | .ras .sun .rs .im1 .im8 .im24 .im32 | yes | yes | alpha: true, palette: true, depths: 1, 8, 24, 32 | `tests/image/sunras.luau` | | image | tga | .tga .icb .vda .vst .tpic | yes | yes | alpha: true, palette: true, depths: 8, 15, 16, 24, 32 | `tests/image/tga.luau` | | image | tiff | .tif .tiff | yes | yes | alpha: true, pages: true, depths: 1, 2, 4, 8, 16, 32, float: true | `tests/image/tiff.luau` | @@ -66,7 +68,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | ase | .ase .ask | yes | yes | text: true, materials: true, cameras: true, lights: true, vertexColors: true | `tests/model/ase.luau` | | model | b3d | .b3d | yes | - | materials: true, textures: true, skins: true, animation: true, colors: true | `tests/model/b3d.luau` | -| model | bsp | .bsp | yes | - | variants: "quake", "halflife", "quake2", "quake3", lightmaps: "quake3" | `tests/model/bsp.luau` | +| model | bsp | .bsp | yes | - | variants: "quake", "bsp2", "2psb", "halflife", "quake2", "quake3", lightmaps: true, collision: true, visibility: true | `tests/model/bsp.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, draco: true | `tests/model/gltf.luau` | @@ -74,6 +76,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | iqm | .iqm | yes | yes | materials: true, skins: true, animation: true, vertexColors: true | `tests/model/iqm.luau` | | model | ldraw | .ldr .mpd .dat | yes | - | materials: true, lines: true, instancing: true | `tests/model/ldraw.luau` | | model | lwo | .lwo .lxo | yes | - | materials: true, polygons: true, vertexColors: true, morphTargets: true | `tests/model/lwo.luau` | +| model | map | .map | yes | yes | variants: "quake", "valve220", "quake2", "quake3", patches: true | `tests/model/map.luau` | | model | mca | .mca .mcr | yes | - | voxels: true, blocks: true | `tests/model/mca.luau` | | model | md2 | .md2 | yes | - | morph: true, animation: true | `tests/model/md2.luau` | | model | md3 | .md3 | yes | - | morph: true, animation: true, tags: true | `tests/model/md3.luau` | @@ -134,6 +137,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | archive | uu | .uu .uue .xxe .b64 | yes | yes | variants: "uu", "xx", "base64" | `tests/archive/uu.luau` | | archive | vpk | .vpk | yes | yes | versions: 1, 2, multipart: true | `tests/archive/vpk.luau` | | archive | wad | .wad | yes | yes | images: true, maps: true, variants: "iwad", "pwad" | `tests/archive/wad.luau` | +| archive | wad2 | .wad | yes | yes | images: true, variants: "wad2", "wad3" | `tests/archive/wad2.luau` | | archive | xz | .xz .txz .lzma | yes | - | stream: true, filters: "lzma2", "lzma", "delta", "x86", "powerpc", "arm", "armthumb", "sparc", "arm64" | `tests/archive/xz.luau` | | archive | yenc | .yenc .ync | yes | yes | multipart: true | `tests/archive/yenc.luau` | | archive | z | .z .taz .tz | yes | yes | stream: true, bits: 9, 16 | `tests/archive/z.luau` | @@ -147,6 +151,8 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | data | msgpack | .msgpack .mpk | yes | yes | binary: true, ordered: true | `tests/data/msgpack.luau` | | data | nbt | .nbt .dat .mcstructure .dat_old | yes | yes | binary: true, ordered: true, typed: true | `tests/data/nbt.luau` | | data | plist | .plist | yes | yes | binary: "read", ordered: true | `tests/data/plist.luau` | +| data | q3shader | .shader | yes | yes | | `tests/data/q3shader.luau` | +| data | q3skin | .skin | yes | yes | | `tests/data/q3skin.luau` | | data | snbt | .snbt | yes | yes | ordered: true, typed: true | `tests/data/snbt.luau` | | data | toml | .toml | yes | yes | ordered: true, dates: true | `tests/data/toml.luau` | | data | tres | .tres | yes | yes | ordered: true | `tests/data/tres.luau` | @@ -242,7 +248,8 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/image/Etc: ETC1 / ETC2 / EAC block texture decoding (Khronos Data Format Specification 1.3, section 21). - codecs/image/Half: IEEE 754 binary16 <-> number (round to nearest even, overflow to infinity). New in rosetta. - codecs/image/Jpeg: the JPEG codec (ITU T.81), bit-exact with libjpeg-turbo's djpeg and byte-identical with cjpeg. - - codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB. + - codecs/image/Miptex: Quake / GoldSrc mip textures and the WAD2 / WAD3 lump directory, read and write. + - codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB, and palette helpers. - codecs/image/Quantize: palette quantization of rgba8 pixels (median cut or octree, Floyd-Steinberg dithering). - codecs/image/Raster: an antialiased scanline rasterizer (nonzero / even-odd) for line and Bézier paths, plus a stroker. - codecs/image/Texel: uncompressed GPU texel formats -> the standard pixel formats. New in rosetta. @@ -251,10 +258,12 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/image/Vp8L: WebP lossless (VP8L, RFC 9649 section 3). - codecs/image/Yuv: planar 4:2:0 Y'CbCr <-> rgba8, BT.601 / BT.709, limited or full range. - **model** + - codecs/model/Brush: convex plane brushes -> polygons and Scene primitives, with Quake-family texture projection. - codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7). - codecs/model/Mat4: 4x4 matrix (column-major, glTF / Types.Scene layout) and quaternion { x, y, z, w } helpers. - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). - codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code. + - codecs/model/Patch: Quake III / Doom 3 Bezier patches (control grids) -> evaluated grids, triangles, normals. - codecs/model/Polygon: 2D polygons with holes to triangles by hole bridging and ear clipping. New code. - codecs/model/Rbx: the Roblox instance tree and property values shared by model/rbxm and model/rbxmx. - codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...). New code. diff --git a/docs/STYLE.md b/docs/STYLE.md index aa6f630..d5109cd 100644 --- a/docs/STYLE.md +++ b/docs/STYLE.md @@ -29,13 +29,13 @@ src/Rosetta/ codecs// codecs (layer 3) generic algorithms, by domain: compress/ Brotli Bzip2 Deflate Explode Lz4 Lzh Lzma Lzw Lzx PackBits Quantum UnixCompress Xxh32 Zstd entropy/ Huffman RangeCoder - image/ Bcn Blend Dct Etc Half Jpeg Pixels Quantize Raster Texel Texture Vp8 Vp8L Yuv + image/ Bcn Blend Dct Etc Half Jpeg Miptex Pixels Quantize Raster Texel Texture Vp8 Vp8L Yuv audio/ Aac Ac3 Adpcm Alac Ape ApeTag Flac Hively Mdct MidiRender Mpa Musepack Opus Pcm Qoa Resample SoundFont Stream Tracker Tta Vorbis VorbisComment WavPack video/ Dsp H263 H264 Legacy Mpeg1 Mpeg2 Theora Video (the video codec registry) text/ GodotVariant Json Nbt Text Url Xml font/ Bitmap Cff GlyphNames TrueType - model/ Draco Mat4 MeshFlatten Minecraft Polygon Rbx Rig Sampler Vrml + model/ Brush Draco Mat4 MeshFlatten Minecraft Patch Polygon Rbx Rig Sampler Vrml host/ host (layer 2) runtime adapters; only the api uses them Types.luau types (layer 1) standard types + constructors core/ core (layer 0) Adler32 Base64 Bits Bytes Crc16 Crc32 Err Input @@ -242,6 +242,8 @@ them. Anything generic goes down a layer and is called: | GPU texture pixels (BCn, ETC / EAC, uncompressed texel layouts, half floats) | `codecs/image/Texture` (`Bcn`, `Etc`, `Texel`, `Half`) | | animation channels sampled at a time; game-model frames, joints and skins -> Scene | `codecs/model/Sampler`, `codecs/model/Rig` | | polygons with holes -> triangles | `codecs/model/Polygon` | +| plane brushes -> polygons (CSG hull, coplanar merge, Quake / Valve 220 / brush-primitive texturing); Bezier patches | `codecs/model/Brush`, `codecs/model/Patch` | +| Quake / GoldSrc mip textures, WAD2 / WAD3 directories; palettes (keyed index, grey, colormap) | `codecs/image/Miptex`, `codecs/image/Pixels` | | NBT / SNBT values; Minecraft block states and colours | `codecs/text/Nbt`, `codecs/model/Minecraft` | | Roblox instance trees and property values | `codecs/model/Rbx` | | bitmap fonts as a Font; PostScript glyph names | `codecs/font/Bitmap`, `codecs/font/GlyphNames` | diff --git a/docs/guide/archive.md b/docs/guide/archive.md index 5c91743..7eb3b4d 100644 --- a/docs/guide/archive.md +++ b/docs/guide/archive.md @@ -232,6 +232,28 @@ local data = assert(Wad.mapData(wad, "E1M1")) assert(#data.sectors == 2 and #data.things == 2) ``` +Quake's and Half-Life's texture WADs (WAD2 / WAD3, format `wad2`; Doom's IWAD / PWAD is `wad`) list their lumps +by name; `image` decodes miptex textures (any mip level), qpic pictures, the console font and the palette lump. Quake 1 +lumps use the WAD's own `palette` lump (gfx.wad), `palette` or `gfx/palette.lmp` through `files` / `resolve` (Quake's +palette is not redistributable, so rosetta never embeds it); WAD3 lumps carry their own. `addImage` writes images +back as lumps (WAD3: with a palette made by median cut): + +```luau +local Wad2 = F.format("wad2") +local gfx = assert(F.archive.load(gfxWadBytes)) +assert(gfx.format == "wad2" and gfx.meta.source.variant == "wad2") +local brick = assert(Wad2.image(gfx, "brick")) -- through the WAD's palette lump +local small = assert(Wad2.image(gfx, "brick", { mip = 2 })) -- 8 x 8 +assert(brick.width == 32 and small.width == 8) +local disc = assert(Wad2.image(gfx, "disc")) -- a qpic: index 255 transparent +assert(disc.meta.source.kind == "qpic") + +local hl = Wad2.new("wad3") +assert(Wad2.addImage(hl, "{FENCE", brick)) -- '{' textures key index 255 +local wad3 = assert(F.save(hl)) +assert(F.archive.load(wad3).meta.source.variant == "wad3") +``` + VPK directories (`pak01_dir.vpk`) hold small files themselves and point to numbered part files for the rest; pass those through `files` or `resolve` (loading a path does it for you): diff --git a/docs/guide/data.md b/docs/guide/data.md index de0b935..e0ce906 100644 --- a/docs/guide/data.md +++ b/docs/guide/data.md @@ -329,6 +329,25 @@ local text = assert(F.saveString(res, { format = "tres" })) assert(string.find(text, "metallic = 0.5", 1, true) and string.find(text, "roughness = 1.0", 1, true)) ``` +## Quake III shaders and skins + +Quake III `.shader` scripts load as a list of shaders: `{ name, directives, stages }`, each directive its tokens +(`{ "surfaceparm", "nolightmap" }`), each stage a list of directives; they write back. `.skin` files (format +`q3skin`) are lists of `{ surface, shader }` (tags have an empty shader). + +```luau +local Q3Shader = F.format("q3shader") +local shaders = assert(F.data.load(shaderText, { format = "q3shader" })) +local wall = assert(Q3Shader.find(shaders, "textures/base_wall/metalfloor_wall_10")) +assert(Q3Shader.directive(wall.directives, "surfaceparm")[2] == "metalsteps") +assert(wall.stages[1][1][2] == "$lightmap" and #wall.stages == 2) +local again = assert(F.saveString(shaders, { format = "q3shader" })) +assert(#assert(F.data.load(again, { format = "q3shader" })) == #shaders) + +local skin = assert(F.data.load(skinText, { format = "q3skin" })) +assert(F.format("q3skin").shader(skin, "h_head") == "models/players/sarge/band.tga") +``` + ## Save and convert Data values have no `kind`, so saving needs `opts.format` or a destination extension (an `XmlNode` document too): diff --git a/docs/guide/image.md b/docs/guide/image.md index 46d3463..0062787 100644 --- a/docs/guide/image.md +++ b/docs/guide/image.md @@ -214,8 +214,28 @@ local small = assert(F.image.load(vtfBytes, { mip = 1 })) -- or face = n (cub assert(F.detect(tim) == "tim") ``` -Doom's graphics come from WAD lumps rather than files: `F.format("wad").image(wad, name)` (see -[archive.md](archive.md#game-archives)). +Quake's `.lmp` pictures (qpics), `palette.lmp` and `colormap.lmp`, and Quake / Half-Life sprites (`.spr`) load +too. Quake pictures and sprites are 8-bit images over Quake's palette, which is not redistributable: pass it as +`palette` (768 bytes) or as `gfx/palette.lmp` through `files` / `resolve` (without it they load grey, +`meta.source.palette = false`). Half-Life sprites carry their own palette. Sprite frames are `img.frames` on one +canvas around the sprite's origin (`meta.origin`); frame groups give the delays. + +```luau +local disc = assert(F.image.load(discLmpBytes, { name = "disc.lmp", palette = quakePaletteBytes })) +assert(disc.width == 24 and disc.meta.source.palette) -- index 255 is transparent +local pal = assert(F.image.load(quakePaletteBytes, { format = "lmp" })) -- a 16 x 16 swatch +assert(#pal.meta.palette == 256) +local back = assert(F.save(disc, nil, { format = "lmp", palette = quakePaletteBytes })) +assert(buffer.len(back) == buffer.len(discLmpBytes)) + +local flame = assert(F.image.load(flameSprBytes)) -- Half-Life: its own palette +assert(#flame.frames == 3 and flame.meta.source.texFormat == "alphatest") +local spr = assert(F.save(flame, nil, { format = "spr" })) -- version 2; version = 1 (Quake) needs palette +assert(#F.image.load(spr).frames == 3) +``` + +Doom's graphics come from WAD lumps rather than files: `F.format("wad").image(wad, name)`, and Quake / Half-Life +textures from WAD2 / WAD3: `F.format("wad2").image(wad, name)` (see [archive.md](archive.md#game-archives)). ## Formats diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 145ca1b..2097fbb 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -469,7 +469,7 @@ Game model formats load as Scenes too, with what games need: skins (joints + inv | MDL (Quake 1, Half-Life 1) | Quake: skins decoded through the palette; Half-Life: bones, body parts, textures with their own palettes | Quake: morph targets per frame group; Half-Life: every sequence | | MD5 (Doom 3 `.md5mesh` / `.md5anim`) | skeleton, weighted meshes, shaders as URIs | the `.md5anim` files named in `anims` | | SMD (Valve, read + write) | skeleton, weight links, a primitive per material | the skeleton frames | -| BSP (Quake 1 / 2 / 3, Half-Life) | each model a mesh, a primitive per texture (and Quake III lightmap); entities in `meta.entities` | - | +| BSP (Quake 1 / 2 / 3, Half-Life; BSP2, 2PSB) | each model a mesh, a primitive per texture; lightmaps as `TEXCOORD_1`; entities in `meta.entities`; tree, hulls and PVS in `meta.bsp` | - | ```luau local tank = assert(F.model.load(md2Bytes)) @@ -507,6 +507,64 @@ local again = assert(F.save(barney, nil, { format = "smd" })) -- SMD writes ba assert(F.model.load(again).skins[1]) ``` +## Quake maps: editor `.map` and compiled BSP + +`model/map` reads and writes the editor maps of Quake, Half-Life (Valve 220), Quake II (with content / surface flags) +and Quake III (`brushDef` brush primitives, `patchDef2` / `patchDef3` patches). Every entity is a node (child of the +`map` root) with `extras.classname`, `extras.keys` (an ordered object) and `extras.brushes` (the brushes as written); +entities with brushes get a mesh, a primitive per texture. Point entities stand at their `origin`. Brushes become +polygons the way qbsp builds them (`codecs/model/Brush`; tested against ericw-tools); `hull = true` drops the faces +inside or touching other brushes of the same entity, `merge = true` merges coplanar faces. Texture coordinates need +texture sizes: they come from `textureSizes`, the worldspawn's WADs (`"wad"` key), Quake II `.wal` files or Quake III +images (with `decodeImage`) through `files` / `resolve`; unknown textures count as 64 x 64 +(`material.extras.map.sizeKnown = false`). + +```luau +local Map = F.format("map") +local room = assert(F.model.load(roomMapText, { files = { ["gfx/tex.wad"] = texWadBytes }, hull = true })) +assert(room.meta.source.variant == "quake" and room.meta.up == "z") +local world = room.nodes[2] -- node 1 is the "map" root +assert(world.extras.classname == "worldspawn" and world.mesh) +local door = room.nodes[3] +assert(door.name == "door1" and door.extras.keys.angle == "90") +assert(room.materials[1].extras.map.sizeKnown) -- sizes from the WAD +local start = room.nodes[4] -- a point entity at its origin +assert(start.translation[1] == -128) + +start.translation = { 0, 0, 24 } -- edit and write back +door.extras.keys.speed = "200" +local text = buffer.tostring(assert(F.save(room, nil, { format = "map" }))) +assert(string.find(text, '"origin" "0 0 24"', 1, true)) +local valve = assert(F.save(room, nil, { format = "map", variant = "valve220" })) -- Quake standard -> Valve 220 axes +assert(F.model.load(valve).meta.source.variant == "valve220") +local parsed = assert(Map.parse(roomMapText)) -- the raw entities: keys, brushes, faces as written +assert(#parsed.entities == 4 and parsed.entities[1].brushes[1].faces[1].texture) +``` + +Compiled `.bsp` maps carry what the engines need beyond the triangles. Quake 1 (BSP 29, BSP2, 2PSB), Half-Life and +Quake II lightmaps (the first light style) are packed into one atlas texture named `"lightmap"`, mapped by +`TEXCOORD_1` and named by each material's `extras.bsp.lightmap` (Quake III keeps its own 128 x 128 pages). Coloured +Quake light comes from the map's `.lit` (`lit`, or `.lit` through `files` / `resolve` with `name`). The BSP tree, +the collision hulls (Quake 1 clipnodes, Quake II / III brushes) and the visibility data are tables in `meta.bsp`, +with point queries on the format module: + +```luau +local Bsp = F.format("bsp") +local map = assert(F.model.load(roomBspBytes)) +assert(map.meta.source.variant == "quake") +local prim = map.meshes[1].primitives[1] +assert(prim.attributes.TEXCOORD_1) -- lightmap coordinates +local atlas = map.textures[map.materials[prim.material].extras.bsp.lightmap] +assert(atlas.name == "lightmap" and atlas.image.width > 0) +assert(Bsp.contents(map, -128, -128, 100) == -1) -- CONTENTS_EMPTY in the room +assert(Bsp.contents(map, 0, 0, -8) == -2) -- CONTENTS_SOLID: the floor +assert(Bsp.contents(map, -250, 0, 100, 1) == -2) -- hull 1 (player size) touches the wall +local here = assert(Bsp.leafAt(map, -128, -128, 24)) +local seen = assert(Bsp.pvs(map, here)) -- leaves potentially visible from here +assert(table.find(seen, Bsp.leafAt(map, 0, 0, 220))) +assert(#map.meta.bsp.planes > 0 and #map.meta.bsp.clipnodes > 0) +``` + ## Blitz3D (B3D) `.b3d` files (Blitz3D, also written by many old game tools) load read-only. The node tree keeps its names and TRS; @@ -801,7 +859,8 @@ surfaces with positions, normals, tangents, colours, two UV sets) and StandardMa | VRML97 (WRL / WRZ) | yes | yes | primitives, PROTO, Inline, ROUTE animations, cameras, lights | | X3D (XML / classic) | yes | yes | the VRML reader plus the X3D triangle / quad / line sets; no binary `.x3db` | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | -| MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above | +| MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above; BSP lightmaps, hulls, PVS: "Quake maps" | +| Quake / Half-Life / Quake II / Quake III `.map` | yes | yes | entities as nodes, brushes CSG'd, patches: see "Quake maps" | | SMD | yes | yes | Valve studiomdl data | | Godot `.tscn` / `.escn` | yes | yes (`.tscn`) | Node3D trees, ArrayMesh and primitive meshes, StandardMaterial3D, cameras, lights, instances; 2D nodes in extras | | ASE (3ds Max ASCII) | yes | yes | Multi/Sub-Object materials, texture channels, vertex colours, normals, helpers, cameras, lights; no animation; Z up | diff --git a/src/Rosetta/Registry.luau b/src/Rosetta/Registry.luau index 7be9095..079e0ca 100644 --- a/src/Rosetta/Registry.luau +++ b/src/Rosetta/Registry.luau @@ -158,6 +158,18 @@ local list: { Entry } = { return require("@rosetta/image/ktx") end, }, + { + name = "lmp", + category = "image", + path = "image/lmp", + extensions = { "lmp" }, + mime = { "image/x-quake-lmp" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 }, variants = { "qpic", "palette", "colormap" } }, + load = function() + return require("@rosetta/image/lmp") + end, + }, { name = "pcx", category = "image", @@ -218,6 +230,18 @@ local list: { Entry } = { return require("@rosetta/image/sgi") end, }, + { + name = "spr", + category = "image", + path = "image/spr", + extensions = { "spr" }, + mime = { "image/x-quake-sprite" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, alpha = true, animation = true, variants = { "quake", "halflife", "spr32" } }, + load = function() + return require("@rosetta/image/spr") + end, + }, { name = "sunras", category = "image", @@ -752,8 +776,8 @@ local list: { Entry } = { path = "model/bsp", extensions = { "bsp" }, mime = { "model/x-bsp" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, - caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" }, + caps = { decode = true, encode = false, variants = { "quake", "bsp2", "2psb", "halflife", "quake2", "quake3" }, lightmaps = true, collision = true, visibility = true }, load = function() return require("@rosetta/model/bsp") end, @@ -842,6 +866,18 @@ local list: { Entry } = { return require("@rosetta/model/lwo") end, }, + { + name = "map", + category = "model", + path = "model/map", + extensions = { "map" }, + mime = { "text/x-quake-map" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" }, + caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true }, + load = function() + return require("@rosetta/model/map") + end, + }, { name = "mca", category = "model", @@ -1562,6 +1598,18 @@ local list: { Entry } = { return require("@rosetta/archive/wad") end, }, + { + name = "wad2", + category = "archive", + path = "archive/wad2", + extensions = { "wad" }, + mime = { "application/x-quake-wad" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, images = true, variants = { "wad2", "wad3" } }, + load = function() + return require("@rosetta/archive/wad2") + end, + }, { name = "xz", category = "archive", @@ -1718,6 +1766,30 @@ local list: { Entry } = { return require("@rosetta/data/plist") end, }, + { + name = "q3shader", + category = "data", + path = "data/q3shader", + extensions = { "shader" }, + mime = { "text/x-quake3-shader" }, + deps = { "core/Err", "core/Bytes" }, + caps = { decode = true, encode = true }, + load = function() + return require("@rosetta/data/q3shader") + end, + }, + { + name = "q3skin", + category = "data", + path = "data/q3skin", + extensions = { "skin" }, + mime = { "text/x-quake3-skin" }, + deps = { "core/Err", "core/Bytes" }, + caps = { decode = true, encode = true }, + load = function() + return require("@rosetta/data/q3skin") + end, + }, { name = "snbt", category = "data", diff --git a/src/Rosetta/archive/wad2/init.luau b/src/Rosetta/archive/wad2/init.luau new file mode 100644 index 0000000..97e843a --- /dev/null +++ b/src/Rosetta/archive/wad2/init.luau @@ -0,0 +1,280 @@ +--!strict +-- archive/wad2: Quake WAD2 and Half-Life WAD3 texture / graphics WADs (wad.h of the Quake source, the GoldSrc WAD3 +-- layout; no code taken), read and write. Lumps by name (repeats "~"); Wad2.image decodes miptex, qpic, +-- conchars, palette and GoldSrc font lumps through codecs/image/Miptex (Quake 1 needs a palette: the WAD's own +-- "palette" lump, opts.palette or gfx/palette.lmp through files / resolve; else grey). Not supported: compressed lumps. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@rosetta/core/Err") +local Bytes = require("@rosetta/core/Bytes") +local Input = require("@rosetta/core/Input") +local Types = require("@rosetta/Types") +local Archive = require("@rosetta/containers/Archive") +local Pixels = require("@rosetta/codecs/image/Pixels") +local Miptex = require("@rosetta/codecs/image/Miptex") + +-- ------------------------------------------------------------------------------------------------ contract +local Wad2 = { + name = "wad2", + category = "archive", + extensions = { "wad" }, + mime = { "application/x-quake-wad" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "containers/Archive", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, images = true, variants = { "wad2", "wad3" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { maxEntries: number? } -- default 1e6 +export type EncodeOptions = { variant: ("wad2" | "wad3")? } -- default: the source's, else wad3 when a lump is type 0x43 +export type ImageOptions = { + palette: (buffer | string)?, -- 768 bytes (Quake 1) + mip: number?, -- miptex level 0..3, default 0 + keyed: boolean?, -- index 255 transparent; default: qpics, conchars and '{' textures + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, +} +export type AddOptions = { + kind: ("miptex" | "qpic")?, -- default "miptex" + palette: (buffer | string)?, -- 768 bytes; required for WAD2 lumps, made by median cut for WAD3 without it +} + +-- ------------------------------------------------------------------------------------------------ constants +local T = Miptex.TYPES + +-- ------------------------------------------------------------------------------------------------ sniff +function Wad2.sniff(r: Bytes.Reader): number + if r:remaining() < 12 then + return 0 + end + local m = r:peek(4) + return if m == "WAD2" or m == "WAD3" then 0.9 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function encode(archive: any, opts: any?): (buffer?, Err.Err?) + return Wad2.encode(archive, opts) +end + +function Wad2.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local size = r.limit - r.base + local lumps, msg, magic = Miptex.wad(r.buf, r.base, size, opts and opts.maxEntries) + if not lumps then + return nil, Err.from(msg, 0) + end + local a = Archive.new("wad2", encode) + local seen: { [string]: number } = {} + for _, l in lumps do + if l.compression ~= 0 then + return nil, Err.new(Err.UNSUPPORTED, "compressed lump " .. l.name) + end + local entry = l.name + local k = seen[string.lower(entry)] + if k then + seen[string.lower(entry)] = k + 1 + entry = entry .. "~" .. (k + 1) + else + seen[string.lower(entry)] = 1 + end + Archive.put(a, { name = entry, size = l.disksize, dir = false, method = "store", type = l.type, lump = l.name, load = Archive.slice(r.buf, r.base + l.offset, l.disksize) }) + end + a.meta.source = { format = "wad2", variant = string.lower(magic :: string), lumps = #lumps } + a.meta.wad2 = { buf = r.buf, base = r.base, lumps = lumps, goldsrc = magic == "WAD3" } + return a, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function guessType(name: string, data: buffer, goldsrc: boolean): number + local n = buffer.len(data) + if string.lower(name) == "palette" and n == 768 then + return T.palette + end + if n >= 40 then + local w, h = buffer.readu32(data, 16), buffer.readu32(data, 20) + if w > 0 and h > 0 and w < 65536 and h < 65536 and buffer.readu32(data, 24) == 40 then + return if goldsrc then 0x43 else T.miptex + end + end + if n >= 8 then + local w, h = buffer.readu32(data, 0), buffer.readu32(data, 4) + if w > 0 and h > 0 and 8 + w * h <= n then + return T.qpic + end + end + return T.miptex +end + +function Wad2.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 variant = opts and opts.variant or (if type(src) == "table" and src.format == "wad2" then src.variant else nil) + if not variant then + variant = "wad2" + for _, it in items do + if (it.entry :: any).type == 0x43 then + variant = "wad3" + end + end + end + if variant ~= "wad2" and variant ~= "wad3" then + return nil, Err.new(Err.ARG, "variant must be wad2 or wad3") + end + local list: { { name: string, data: buffer, type: number } } = {} + for _, it in items do + if not it.entry.dir then + local e: any = it.entry + local name = e.lump or string.gsub(string.match(e.name, "([^/\\]*)$") or e.name, "~%d+$", "") + if #name == 0 or #name > 15 then + return nil, Err.new(Err.ARG, "lump name must be 1..15 bytes: " .. e.name) + end + local typ = if type(e.type) == "number" then e.type else guessType(name, it.data, variant == "wad3") + table.insert(list, { name = name, data = it.data, type = typ }) + end + end + local w = Bytes.writer() + w:string(if variant == "wad3" then "WAD3" else "WAD2") + w:u32le(#list) + w:u32le(0) + local offs: { number } = {} + for i, l in list do + offs[i] = w:tell() + w:bytes(l.data) + w:fill(0, (4 - buffer.len(l.data) % 4) % 4) + end + local dir = w:tell() + for i, l in list do + w:u32le(offs[i]) + w:u32le(buffer.len(l.data)) + w:u32le(buffer.len(l.data)) + w:u8(l.type) + w:u8(0) + w:u16le(0) + w:string(l.name) + w:fill(0, 16 - #l.name) + end + w:setU32le(8, dir) + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +local function info(a: any): any + return type(a) == "table" and type(a.meta) == "table" and a.meta.wad2 or nil +end + +function Wad2.new(variant: ("wad2" | "wad3")?): any + local a = Archive.new("wad2", encode) + a.meta.source = { format = "wad2", variant = variant or "wad2" } + return a +end + +function Wad2.lumps(a: any): { Miptex.Lump }? + local w = info(a) + return w and w.lumps +end + +-- the WAD's own "palette" lump (gfx.wad) as a 1024-byte rgba8 palette +function Wad2.palette(a: any): buffer? + local w = info(a) + local l = w and Miptex.find(w.lumps, "palette") + if l and l.disksize >= 768 then + return Pixels.palette(w.buf, w.base + l.offset, 256) + end + return nil +end + +function Wad2.image(a: any, name: string, opts: ImageOptions?): (Types.Image?, Err.Err?) + local w = info(a) + if not w then + return nil, Err.new(Err.ARG, "expected a decoded WAD2 / WAD3 archive") + end + local l = Miptex.find(w.lumps, tostring(name)) + if not l then + return nil, Err.new(Err.ARG, "no lump named " .. tostring(name)) + end + local b, at, size = w.buf, w.base + l.offset, l.disksize + local pal: buffer? = nil + if not w.goldsrc then + local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else nil + if raw and buffer.len(raw) >= 768 then + pal = Pixels.palette(raw, 0, 256) + else + pal = Wad2.palette(a) + if not pal then + local lmp = Input.sibling(opts, "gfx/palette.lmp") + pal = if lmp and buffer.len(lmp) >= 768 then Pixels.palette(lmp, 0, 256) else nil + end + end + end + local keyed: boolean? = if opts then opts.keyed else nil + local img: Types.Image?, msg: string? + local kind: string + if l.type == T.palette and size >= 768 then + kind = "palette" + local out = Types.Image.new(16, 16) + buffer.copy(out.pixels, 0, Pixels.palette(b, at, 256), 0, 1024) + img = out + elseif string.lower(l.name) == "conchars" and size == 128 * 128 then + -- gfx.wad's console font: raw 128 x 128 pixels, no header, index 0 transparent + kind = "conchars" + local out = Types.Image.new(128, 128) + Pixels.indexed(b, at, 128, 8, out.pixels, 128, 128, true, Pixels.keyed(pal or Pixels.grey(), if keyed == false then -1 else 0)) + img = out + elseif l.type == T.qpic then + kind = "qpic" + img, msg = Miptex.qpic(b, at, size, { palette = pal, goldsrc = w.goldsrc, keyed = keyed } :: any) + elseif l.type == T.font and w.goldsrc and size >= 16 + 1024 then + -- GoldSrc qfont_t: width (256), height, rowcount, rowheight, charinfo[256] (u16 offset, u16 width), pixels, palette + kind = "font" + local fw, fh = buffer.readu32(b, at), buffer.readu32(b, at + 4) + local p = 16 + 1024 + fw * fh + if fw == 0 or fh == 0 or fw * fh > 2 ^ 24 or p + 2 > size then + return nil, Err.new(Err.CORRUPT, "bad font lump " .. l.name, l.offset) + end + local n = buffer.readu16(b, at + p) + local fpal = if n > 0 and n <= 256 and p + 2 + n * 3 <= size then Pixels.palette(b, at + p + 2, n) else Pixels.grey() + local out = Types.Image.new(fw, fh) + Pixels.indexed(b, at + 16 + 1024, fw, 8, out.pixels, fw, fh, true, if keyed == false then fpal else Pixels.keyed(fpal, 255)) + local glyphs = {} + for c = 0, 255 do + glyphs[c + 1] = { offset = buffer.readu16(b, at + 16 + c * 4), width = buffer.readu16(b, at + 18 + c * 4) } + end + out.meta.font = { rows = buffer.readu32(b, at + 8), rowHeight = buffer.readu32(b, at + 12), glyphs = glyphs } + img = out + else + kind = "miptex" + img, msg = Miptex.decode(b, at, size, { palette = pal, goldsrc = w.goldsrc, mip = if opts then opts.mip else nil, keyed = keyed } :: any) + end + if not img then + return nil, Err.from(msg, l.offset) + end + img.meta.source = { format = "wad2", kind = kind, lump = l.name, type = l.type, palette = w.goldsrc or pal ~= nil } + return img, nil +end + +-- adds an rgba8 image as a miptex (sizes multiples of 16) or qpic lump; WAD3 lumps carry their own palette +function Wad2.addImage(a: any, name: string, img: Types.Image, opts: AddOptions?): (boolean, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" then + return false, Err.new(Err.ARG, "expected an rgba8 Image") + end + local src = type(a) == "table" and type(a.meta) == "table" and a.meta.source + local goldsrc = type(src) == "table" and src.variant == "wad3" + local raw = opts and opts.palette and Bytes.toBuffer(opts.palette) + local pal = if raw and buffer.len(raw) >= 768 then Pixels.palette(raw, 0, 256) else nil + local kind = opts and opts.kind or "miptex" + local data, msg + if kind == "qpic" then + data, msg = Miptex.encodeQpic(img, pal, goldsrc) + else + data, msg = Miptex.encode(img, name, pal, goldsrc) + end + if not data then + return false, Err.new(Err.ARG, msg or "cannot encode") + end + Archive.put(a, { name = name, size = buffer.len(data), dir = false, method = "store", lump = name, data = data, + type = if kind == "qpic" then T.qpic elseif goldsrc then 0x43 else T.miptex }) + return true, nil +end + +return Wad2 diff --git a/src/Rosetta/codecs/image/Miptex.luau b/src/Rosetta/codecs/image/Miptex.luau new file mode 100644 index 0000000..fb5dc31 --- /dev/null +++ b/src/Rosetta/codecs/image/Miptex.luau @@ -0,0 +1,298 @@ +--!strict +-- codecs/image/Miptex: Quake / GoldSrc mip textures and the WAD2 / WAD3 lump directory, read and write. +-- miptex_t of bspfile.h: name[16], width, height, offsets[4], four 8-bit mip levels; GoldSrc adds u16 count + count * 3 +-- palette bytes after mip 3. wad.h: "WAD2" / "WAD3", numlumps, infotableofs; 32-byte lumpinfo_t. No code taken. +local Types = require("@rosetta/Types") +local Pixels = require("@rosetta/codecs/image/Pixels") +local Quantize = require("@rosetta/codecs/image/Quantize") + +local Miptex = {} + +local readu8, readu32, readi32 = buffer.readu8, buffer.readu32, buffer.readi32 + +export type Header = { name: string, width: number, height: number, offsets: { number } } +export type Lump = { name: string, offset: number, disksize: number, size: number, type: number, compression: number } +export type DecodeOptions = { + palette: buffer?, -- 1024-byte rgba8 palette (Pixels.palette) when the texture has none of its own + goldsrc: boolean?, -- read the palette stored after mip 3 + mip: number?, -- 0..3, default 0 + keyed: boolean?, -- index 255 transparent; default: names starting with '{' + maxPixels: number?, -- default 2^24 +} + +-- lumpinfo_t types (wad.h TYP_*; WAD3: 0x43 is a miptex with its palette, 0x46 a font) +Miptex.TYPES = table.freeze({ palette = 0x40, qtex = 0x41, qpic = 0x42, sound = 0x43, miptex = 0x44, font = 0x46 }) + +local function cstr(b: buffer, at: number, n: number): string + return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string +end + +function Miptex.header(b: buffer, at: number, size: number): (Header?, string?) + if at < 0 or size < 40 or at + 40 > buffer.len(b) then + return nil, "truncated miptex header" + end + local w, h = readu32(b, at + 16), readu32(b, at + 20) + local offs = { readu32(b, at + 24), readu32(b, at + 28), readu32(b, at + 32), readu32(b, at + 36) } + return { name = cstr(b, at, 16), width = w, height = h, offsets = offs }, nil +end + +-- the GoldSrc palette after mip 3, as a 1024-byte rgba8 palette, or nil when it is missing / out of range +function Miptex.ownPalette(b: buffer, at: number, size: number, hd: Header): buffer? + local w, h = hd.width, hd.height + local p = hd.offsets[4] + (w // 8) * (h // 8) + if hd.offsets[4] == 0 or p + 2 > size then + return nil + end + local n = buffer.readu16(b, at + p) + if n == 0 or n > 256 or p + 2 + n * 3 > size then + return nil + end + return Pixels.palette(b, at + p + 2, n) +end + +-- decodes one mip level to rgba8; without pixels (offsets 0: the texture lives in a WAD) returns nil, "external" +function Miptex.decode(b: buffer, at: number, size: number, opts: DecodeOptions?): (Types.Image?, string?) + local hd, err = Miptex.header(b, at, size) + if not hd then + return nil, err + end + local mip = math.clamp(math.floor(opts and opts.mip or 0), 0, 3) + local w, h = hd.width // (2 ^ mip), hd.height // (2 ^ mip) + if hd.width == 0 or hd.height == 0 or w == 0 or h == 0 then + return nil, "empty miptex" + end + if hd.width * hd.height > (opts and opts.maxPixels or 2 ^ 24) then + return nil, "limit: miptex " .. hd.width .. " x " .. hd.height + end + local off = hd.offsets[mip + 1] + if off == 0 then + return nil, "external" + end + if off + w * h > size or at + off + w * h > buffer.len(b) then + return nil, "truncated miptex pixels" + end + local own = if opts and opts.goldsrc then Miptex.ownPalette(b, at, size, hd) else nil + local pal = own or (opts and opts.palette) or Pixels.grey() + local keyed = if opts and opts.keyed ~= nil then opts.keyed else string.sub(hd.name, 1, 1) == "{" + if keyed then + pal = Pixels.keyed(pal, 255) + end + local img = Types.Image.new(w, h) + Pixels.indexed(b, at + off, w, 8, img.pixels, w, h, true, pal) + img.meta.source = { format = "miptex", name = hd.name, mip = mip, palette = own ~= nil or (opts ~= nil and opts.palette ~= nil), keyed = keyed or nil } + return img, nil +end + +local function halve(px: buffer, w: number, h: number): (buffer, number, number) + local w2, h2 = math.max(1, w // 2), math.max(1, h // 2) + local out = buffer.create(w2 * h2 * 4) + for y = 0, h2 - 1 do + for x = 0, w2 - 1 do + for c = 0, 3 do + local s = 0 + for dy = 0, 1 do + for dx = 0, 1 do + local sx, sy = math.min(x * 2 + dx, w - 1), math.min(y * 2 + dy, h - 1) + s += readu8(px, (sy * w + sx) * 4 + c) + end + end + buffer.writeu8(out, (y * w2 + x) * 4 + c, (s + 2) // 4) + end + end + end + return out, w2, h2 +end + +-- an rgba8 image -> a miptex_t with four mip levels (box filtered, mapped to the nearest palette entry); goldsrc +-- appends the palette. palette: 1024-byte rgba8; without it (GoldSrc only) a 256-colour median-cut palette is made. +function Miptex.encode(img: Types.Image, name: string, palette: buffer?, goldsrc: boolean?): (buffer?, string?) + local w, h = img.width, img.height + if w <= 0 or h <= 0 or w % 16 ~= 0 or h % 16 ~= 0 then + return nil, "miptex sizes must be multiples of 16" + end + if #name > 15 then + return nil, "miptex name over 15 bytes" + end + if not palette and not goldsrc then + return nil, "a Quake miptex needs a palette" + end + local keyed = string.sub(name, 1, 1) == "{" + local _, colors = Miptex.indices(img, palette, keyed) + if keyed and not palette then + colors[256] = { 0, 0, 255, 255 } -- GoldSrc '{' textures: index 255 is the (blue) key colour + end + local pal1024 = palette or buffer.create(1024) + if not palette then + for i, c in colors do + buffer.writeu32(pal1024, (i - 1) * 4, 0xFF000000 + c[3] * 65536 + c[2] * 256 + c[1]) + end + end + local levels: { buffer } = {} + local px, lw, lh = img.pixels, w, h + for m = 0, 3 do + if m > 0 then + px, lw, lh = halve(px, lw, lh) + end + local lvl = { kind = "image", width = lw, height = lh, format = "rgba8", pixels = px, loops = 0, meta = {} } :: any + levels[m + 1] = (Miptex.indices(lvl, pal1024, keyed)) + end + local total = 40 + for _, l in levels do + total += buffer.len(l) + end + local palAt = total + if goldsrc then + total += 2 + 768 + 2 + end + local out = buffer.create(total) + buffer.writestring(out, 0, name) + buffer.writeu32(out, 16, w) + buffer.writeu32(out, 20, h) + local o = 40 + for m, l in levels do + buffer.writeu32(out, 24 + (m - 1) * 4, o) + buffer.copy(out, o, l) + o += buffer.len(l) + end + if goldsrc then + buffer.writeu16(out, palAt, 256) + for i = 0, 255 do + local c = colors[i + 1] or { 0, 0, 0 } + buffer.writeu8(out, palAt + 2 + i * 3, c[1]) + buffer.writeu8(out, palAt + 3 + i * 3, c[2]) + buffer.writeu8(out, palAt + 4 + i * 3, c[3]) + end + end + return out, nil +end + +-- the lump directory of a WAD2 / WAD3 file (offsets relative to base), or nil, message +function Miptex.wad(b: buffer, base: number, size: number, maxLumps: number?): ({ Lump }?, string?, string?) + if size < 12 or base + 12 > buffer.len(b) then + return nil, "truncated header", nil + end + local magic = buffer.readstring(b, base, 4) + if magic ~= "WAD2" and magic ~= "WAD3" then + return nil, "bad magic", nil + end + local n, dir = readi32(b, base + 4), readi32(b, base + 8) + if n < 0 or dir < 0 then + return nil, "negative directory field", nil + end + if n > (maxLumps or 1e6) then + return nil, "limit: too many lumps: " .. n, nil + end + if dir + n * 32 > size then + return nil, "truncated directory past the end", nil + end + local out: { Lump } = {} + for i = 0, n - 1 do + local o = base + dir + i * 32 + local at, disk, full = readi32(b, o), readi32(b, o + 4), readi32(b, o + 8) + if at < 0 or disk < 0 or at + disk > size then + return nil, "truncated lump past the end", nil + end + out[i + 1] = { name = cstr(b, o + 16, 16), offset = at, disksize = disk, size = full, type = readu8(b, o + 12), compression = readu8(b, o + 13) } + end + return out, nil, magic +end + +-- the lump named name (case-insensitive, the last one wins as in W_GetLumpinfo) +function Miptex.find(lumps: { Lump }, name: string): Lump? + local want = string.lower(name) + local best: Lump? = nil + for _, l in lumps do + if string.lower(l.name) == want then + best = l + end + end + return best +end + +-- qpic (Quake .lmp / WAD2 type 0x42: u32 width, height, 8-bit pixels; GoldSrc adds u16 count + count * 3 palette bytes) +-- -> rgba8. keyed: index 255 transparent (Quake's Draw_TransPic), default true +function Miptex.qpic(b: buffer, at: number, size: number, opts: DecodeOptions?): (Types.Image?, string?) + if size < 8 or at < 0 or at + 8 > buffer.len(b) then + return nil, "truncated qpic header" + end + local w, h = readu32(b, at), readu32(b, at + 4) + if w == 0 or h == 0 then + return nil, "empty qpic" + end + if w * h > (opts and opts.maxPixels or 2 ^ 24) then + return nil, "limit: qpic " .. w .. " x " .. h + end + if 8 + w * h > size or at + 8 + w * h > buffer.len(b) then + return nil, "truncated qpic pixels" + end + local own: buffer? = nil + if opts and opts.goldsrc then + local p = 8 + w * h + if p + 2 <= size then + local n = buffer.readu16(b, at + p) + if n > 0 and n <= 256 and p + 2 + n * 3 <= size then + own = Pixels.palette(b, at + p + 2, n) + end + end + end + local pal = own or (opts and opts.palette) or Pixels.grey() + local keyed = if opts and opts.keyed ~= nil then opts.keyed else true + if keyed then + pal = Pixels.keyed(pal, 255) + end + local img = Types.Image.new(w, h) + Pixels.indexed(b, at + 8, w, 8, img.pixels, w, h, true, pal) + img.meta.source = { format = "qpic", palette = own ~= nil or (opts ~= nil and opts.palette ~= nil), keyed = keyed or nil } + return img, nil +end + +-- palette indices of an rgba8 image (nearest entry; alpha < 128 -> 255 when keyed and the image has any) and the +-- palette used +function Miptex.indices(img: Types.Image, palette: buffer?, keyed: boolean): (buffer, { { number } }) + if keyed then + local any = false + for k = 0, img.width * img.height - 1 do + if readu8(img.pixels, k * 4 + 3) < 128 then + any = true + break + end + end + keyed = any + end + local colors = if palette then Pixels.colorList(palette) else Quantize.palette(img.pixels, img.width, img.height, if keyed then 255 else 256) + local idx = Quantize.map(img.pixels, img.width, img.height, colors, { transparentIndex = if keyed and palette then 255 else nil }) + if keyed then + for k = 0, img.width * img.height - 1 do + if readu8(img.pixels, k * 4 + 3) < 128 then + buffer.writeu8(idx, k, 255) + end + end + end + return idx, colors +end + +-- an rgba8 image -> qpic bytes (goldsrc: with its palette, made by median cut when none is given) +function Miptex.encodeQpic(img: Types.Image, palette: buffer?, goldsrc: boolean?, keyed: boolean?): (buffer?, string?) + if not palette and not goldsrc then + return nil, "a Quake qpic needs a palette" + end + local w, h = img.width, img.height + local idx, colors = Miptex.indices(img, palette, keyed ~= false) + local out = buffer.create(8 + w * h + (if goldsrc then 2 + 768 else 0)) + buffer.writeu32(out, 0, w) + buffer.writeu32(out, 4, h) + buffer.copy(out, 8, idx, 0, w * h) + if goldsrc then + local p = 8 + w * h + buffer.writeu16(out, p, 256) + for i = 0, 255 do + local c = colors[i + 1] or { 0, 0, 0 } + buffer.writeu8(out, p + 2 + i * 3, c[1]) + buffer.writeu8(out, p + 3 + i * 3, c[2]) + buffer.writeu8(out, p + 4 + i * 3, c[3]) + end + end + return out, nil +end + +return Miptex diff --git a/src/Rosetta/codecs/image/Pixels.luau b/src/Rosetta/codecs/image/Pixels.luau index 30a15a8..b41ce33 100644 --- a/src/Rosetta/codecs/image/Pixels.luau +++ b/src/Rosetta/codecs/image/Pixels.luau @@ -1,8 +1,9 @@ --!strict --!native --!optimize 2 --- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB. --- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8. From bmp-luau b86aed6 (same author); the encoder loops are new. +-- codecs/image/Pixels: row loops between packed pixel layouts and rgba8 for BMP / DIB, and palette helpers. +-- Indexed, BGR(A), 5-5-5, bit masks, RLE4 / RLE8; palettes: keyed index (Quake 255), grey ramp, Quake colormap light +-- levels. From bmp-luau b86aed6 (same author); the encoder loops and palette helpers are new. local readu8, readu16, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu32, buffer.writeu8 local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lshift @@ -259,4 +260,59 @@ function Pixels.colours(src: buffer, n: number, max: number): ({ number }, boole return list, alpha end +-- a 256-entry rgba8 palette (u32 LE per entry) with entry i = { i, i, i, 255 } +function Pixels.grey(): buffer + local pal = buffer.create(1024) + for i = 0, 255 do + writeu32(pal, i * 4, 0xFF000000 + i * 0x10101) + end + return pal +end + +-- a copy of a 1024-byte palette with entry index transparent (alpha 0, colour kept as Pillow does; Quake / GoldSrc: +-- index 255 of sprites, qpics and '{' textures) +function Pixels.keyed(pal: buffer, index: number): buffer + local out = buffer.create(1024) + buffer.copy(out, 0, pal, 0, math.min(buffer.len(pal), 1024)) + if index >= 0 and index < 256 then + writeu8(out, index * 4 + 3, 0) + end + return out +end + +-- palette (1024 bytes) -> { { r, g, b, a } } for codecs/image/Quantize +function Pixels.colorList(pal: buffer, n: number?): { { number } } + local out: { { number } } = {} + for i = 0, math.clamp(n or 256, 0, buffer.len(pal) // 4) - 1 do + out[i + 1] = { readu8(pal, i * 4), readu8(pal, i * 4 + 1), readu8(pal, i * 4 + 2), readu8(pal, i * 4 + 3) } + end + return out +end + +-- Quake colormap.lmp: rows of 256 palette indices, row 0 brightest .. 63 darkest (32 = unlit); the palette for one +-- light level, or nil past the end of the map +function Pixels.colormap(pal: buffer, cmap: buffer, base: number, row: number): buffer? + local o = base + row * 256 + if row < 0 or base < 0 or o + 256 > buffer.len(cmap) then + return nil + end + local out = buffer.create(1024) + for i = 0, 255 do + writeu32(out, i * 4, readu32(pal, readu8(cmap, o + i) * 4)) + end + return out +end + +-- rgba8 palette (1024 bytes) -> 3 * n bytes R, G, B (the Quake / GoldSrc palette layout) +function Pixels.paletteBytes(pal: buffer, n: number?): buffer + local m = math.clamp(n or 256, 0, 256) + local out = buffer.create(m * 3) + for i = 0, m - 1 do + writeu8(out, i * 3, readu8(pal, i * 4)) + writeu8(out, i * 3 + 1, readu8(pal, i * 4 + 1)) + writeu8(out, i * 3 + 2, readu8(pal, i * 4 + 2)) + end + return out +end + return Pixels diff --git a/src/Rosetta/codecs/model/Brush.luau b/src/Rosetta/codecs/model/Brush.luau new file mode 100644 index 0000000..a76dfb3 --- /dev/null +++ b/src/Rosetta/codecs/model/Brush.luau @@ -0,0 +1,638 @@ +--!strict +--!native +--!optimize 2 +-- codecs/model/Brush: convex plane brushes -> polygons and Scene primitives, with Quake-family texture projection. +-- As qbsp (Quake / ericw-tools; no code taken): a big square on every plane (inside n . p <= d) clipped by the others. +-- Projections: Quake standard (TextureAxisFromPlane + rotate / scale / shift), Valve 220 (explicit U / V axes), Quake +-- III brush primitives (q3map2 ComputeAxisBase + 2 x 3 matrix). Options: merge coplanar faces with one projection +-- (qbsp TryMerge), drop face parts inside / touching other brushes (qbsp CSGFaces; earlier brushes win coplanar ties). +local Types = require("@rosetta/Types") + +local Brush = {} + +local abs, sqrt, floor, sin, cos, atan2, min, max = math.abs, math.sqrt, math.floor, math.sin, math.cos, math.atan2, math.min, math.max +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +export type Plane = { number } -- nx, ny, nz, d (unit normal pointing out of the brush) +export type Face = { + plane: Plane, + texture: string?, + vecs: { { number } }?, -- 2 x 4: s = p . vecs[1].xyz + vecs[1][4] in texels (Quake standard / Valve 220) + bp: { { number } }?, -- 2 x 3 brush-primitive matrix: s = bp[1] . (p . texS, p . texT, 1) in texture widths + [string]: any, +} +export type Polygon = { + brush: number, + face: number, + points: { number }, -- x, y, z per corner, counter-clockwise seen from the front + normal: { number }, +} +export type Options = { + epsilon: number?, -- plane side tolerance, default 1e-3 + size: number?, -- half size of the starting winding, default 2^17 + merge: boolean?, -- merge coplanar faces with the same texture projection, default false + hull: boolean?, -- drop face parts inside / touching other brushes, default false + maxPolygons: number?, -- default 2^20 +} +export type Built = { texture: string, primitive: Types.Primitive } + +-- TextureAxisFromPlane's baseaxis table (normal, s axis, t axis per row): floor, ceiling, west, east, south, north +local BASEAXIS = { + { 0, 0, 1 }, { 1, 0, 0 }, { 0, -1, 0 }, + { 0, 0, -1 }, { 1, 0, 0 }, { 0, -1, 0 }, + { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, + { -1, 0, 0 }, { 0, 1, 0 }, { 0, 0, -1 }, + { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, + { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, -1 }, +} + +local function snap(x: number): number + local r = floor(x + 0.5) + return if abs(x - r) < 1e-6 then r else x +end + +-- qbsp PlaneFromPoints: normal = (p1 - p2) x (p3 - p2), the brush lies behind it; nil when the points are colinear +function Brush.planeFromPoints(a: { number }, b: { number }, c: { number }): Plane? + local ux, uy, uz = a[1] - b[1], a[2] - b[2], a[3] - b[3] + local vx, vy, vz = c[1] - b[1], c[2] - b[2], c[3] - b[3] + local nx, ny, nz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l < 1e-12 then + return nil + end + nx, ny, nz = nx / l, ny / l, nz / l + return { nx, ny, nz, b[1] * nx + b[2] * ny + b[3] * nz } +end + +-- the base axis row (0..5) of TextureAxisFromPlane: the first with the largest dot product (strictly greater) +function Brush.baseAxis(n: { number }): number + local best, axis = 0, 0 + for i = 0, 5 do + local a = BASEAXIS[i * 3 + 1] + local d = n[1] * a[1] + n[2] * a[2] + n[3] * a[3] + if d > best then + best, axis = d, i + end + end + return axis +end + +-- Quake standard texture vectors (texels): offsets, rotation (degrees), scales (0 = 1) +function Brush.quakeVecs(n: { number }, xoff: number, yoff: number, rot: number, xscale: number, yscale: number): { { number } } + local axis = Brush.baseAxis(n) + local s0, t0 = BASEAXIS[axis * 3 + 2], BASEAXIS[axis * 3 + 3] + local vecs = { { s0[1], s0[2], s0[3] }, { t0[1], t0[2], t0[3] } } + local sinv, cosv + if rot == 0 then + sinv, cosv = 0, 1 + elseif rot == 90 then + sinv, cosv = 1, 0 + elseif rot == 180 then + sinv, cosv = 0, -1 + elseif rot == 270 then + sinv, cosv = -1, 0 + else + local ang = rot / 180 * math.pi + sinv, cosv = sin(ang), cos(ang) + end + local sv = if vecs[1][1] ~= 0 then 1 elseif vecs[1][2] ~= 0 then 2 else 3 + local tv = if vecs[2][1] ~= 0 then 1 elseif vecs[2][2] ~= 0 then 2 else 3 + for i = 1, 2 do + local v = vecs[i] + local ns = cosv * v[sv] - sinv * v[tv] + local nt = sinv * v[sv] + cosv * v[tv] + v[sv], v[tv] = ns, nt + end + local sc = { if xscale == 0 then 1 else xscale, if yscale == 0 then 1 else yscale } + for i = 1, 2 do + local v = vecs[i] + v[1], v[2], v[3] = v[1] / sc[i], v[2] / sc[i], v[3] / sc[i] + end + vecs[1][4], vecs[2][4] = xoff, yoff + return vecs +end + +-- Valve 220: u / v = axis (x, y, z, offset); the rotation is already in the axes +function Brush.valveVecs(u: { number }, v: { number }, xscale: number, yscale: number): { { number } } + local su, sv = if xscale == 0 then 1 else xscale, if yscale == 0 then 1 else yscale + return { { u[1] / su, u[2] / su, u[3] / su, u[4] }, { v[1] / sv, v[2] / sv, v[3] / sv, v[4] } } +end + +-- q3map2 ComputeAxisBase: the texture plane axes of a brush-primitive face +function Brush.axisBase(normal: { number }): ({ number }, { number }) + local nx, ny, nz = normal[1], normal[2], normal[3] + nx = if abs(nx) < 1e-6 then 0 else nx + ny = if abs(ny) < 1e-6 then 0 else ny + nz = if abs(nz) < 1e-6 then 0 else nz + local rotY = -atan2(nz, sqrt(ny * ny + nx * nx)) + local rotZ = atan2(ny, nx) + return { -sin(rotZ), cos(rotZ), 0 }, { -sin(rotY) * cos(rotZ), -sin(rotY) * sin(rotZ), -cos(rotY) } +end + +-- brush primitives -> texel vectors for a w x h texture (ericw-tools SetTexinfo_BrushPrimitives) +function Brush.bpVecs(normal: { number }, m: { { number } }, w: number, h: number): { { number } } + local tx, ty = Brush.axisBase(normal) + local out = {} + for i, size in { w, h } do + local r = m[i] + out[i] = { size * (tx[1] * r[1] + ty[1] * r[2]), size * (tx[2] * r[1] + ty[2] * r[2]), size * (tx[3] * r[1] + ty[3] * r[2]), size * r[3] } + end + return out +end + +-- texel vectors -> brush primitives (the inverse of bpVecs for vectors lying in the face plane) +function Brush.vecsToBp(normal: { number }, vecs: { { number } }, w: number, h: number): { { number } } + local tx, ty = Brush.axisBase(normal) + local out = {} + for i, size in { w, h } do + local v = vecs[i] + out[i] = { + (v[1] * tx[1] + v[2] * tx[2] + v[3] * tx[3]) / size, + (v[1] * ty[1] + v[2] * ty[2] + v[3] * ty[3]) / size, + v[4] / size, + } + end + return out +end + +-- texture coordinates of a point on a face, in texture widths / heights (glTF uv: t grows down the image) +function Brush.uv(face: Face, x: number, y: number, z: number, w: number, h: number): (number, number) + local bp = face.bp + if bp then + local tx, ty = Brush.axisBase(face.plane) + local a = x * tx[1] + y * tx[2] + z * tx[3] + local b = x * ty[1] + y * ty[2] + z * ty[3] + return bp[1][1] * a + bp[1][2] * b + bp[1][3], bp[2][1] * a + bp[2][2] * b + bp[2][3] + end + local v = face.vecs + if v then + local s, t = v[1], v[2] + return (x * s[1] + y * s[2] + z * s[3] + s[4]) / w, (x * t[1] + y * t[2] + z * t[3] + t[4]) / h + end + return 0, 0 +end + +-- qbsp BaseWindingForPlane: a square of half size `size` on the plane, counter-clockwise seen from the front +function Brush.baseWinding(p: Plane, size: number): { number } + local nx, ny, nz, d = p[1], p[2], p[3], p[4] + local ax, ay, az = abs(nx), abs(ny), abs(nz) + local ux, uy, uz = 0, 0, 1 + if az >= ax and az >= ay then + ux, uy, uz = 1, 0, 0 + end + local dv = ux * nx + uy * ny + uz * nz + ux, uy, uz = ux - dv * nx, uy - dv * ny, uz - dv * nz + local l = sqrt(ux * ux + uy * uy + uz * uz) + ux, uy, uz = ux / l * size, uy / l * size, uz / l * size + -- right = up x n, so right x up = n: right -> up turns counter-clockwise about n + local rx, ry, rz = (uy * nz - uz * ny), (uz * nx - ux * nz), (ux * ny - uy * nx) + local ox, oy, oz = nx * d, ny * d, nz * d + return { + ox - rx - ux, oy - ry - uy, oz - rz - uz, + ox + rx - ux, oy + ry - uy, oz + rz - uz, + ox + rx + ux, oy + ry + uy, oz + rz + uz, + ox - rx + ux, oy - ry + uy, oz - rz + uz, + } +end + +-- splits a polygon by a plane: the parts in front and behind (nil when empty), and whether it lies on the plane +function Brush.split(pts: { number }, p: Plane, eps: number): ({ number }?, { number }?, boolean) + local n = #pts // 3 + local nx, ny, nz, d = p[1], p[2], p[3], p[4] + local dist = table.create(n, 0) :: { number } + local side = table.create(n, 0) :: { number } + local front, back = 0, 0 + for i = 0, n - 1 do + local v = pts[i * 3 + 1] * nx + pts[i * 3 + 2] * ny + pts[i * 3 + 3] * nz - d + dist[i + 1] = v + if v > eps then + side[i + 1] = 1 + front += 1 + elseif v < -eps then + side[i + 1] = -1 + back += 1 + end + end + if front == 0 and back == 0 then + return nil, nil, true + end + if front == 0 then + return nil, pts, false + end + if back == 0 then + return pts, nil, false + end + local f: { number }, b: { number } = {}, {} + for i = 0, n - 1 do + local j = (i + 1) % n + local x, y, z = pts[i * 3 + 1], pts[i * 3 + 2], pts[i * 3 + 3] + local si = side[i + 1] + if si >= 0 then + f[#f + 1], f[#f + 2], f[#f + 3] = x, y, z + end + if si <= 0 then + b[#b + 1], b[#b + 2], b[#b + 3] = x, y, z + end + local sj = side[j + 1] + if si ~= 0 and sj ~= 0 and si ~= sj then + local t = dist[i + 1] / (dist[i + 1] - dist[j + 1]) + local mx, my, mz = x + t * (pts[j * 3 + 1] - x), y + t * (pts[j * 3 + 2] - y), z + t * (pts[j * 3 + 3] - z) + -- exact on axis-aligned planes, as qbsp + if nx == 1 then + mx = d + elseif nx == -1 then + mx = -d + end + if ny == 1 then + my = d + elseif ny == -1 then + my = -d + end + if nz == 1 then + mz = d + elseif nz == -1 then + mz = -d + end + f[#f + 1], f[#f + 2], f[#f + 3] = mx, my, mz + b[#b + 1], b[#b + 2], b[#b + 3] = mx, my, mz + end + end + return (if #f >= 9 then f else nil), (if #b >= 9 then b else nil), false +end + +-- removes repeated and colinear corners; nil when fewer than 3 remain +local function clean(pts: { number }, eps: number): { number }? + local out: { number } = {} + local n = #pts // 3 + for i = 0, n - 1 do + local x, y, z = snap(pts[i * 3 + 1]), snap(pts[i * 3 + 2]), snap(pts[i * 3 + 3]) + local m = #out + if m < 3 or abs(out[m - 2] - x) > eps or abs(out[m - 1] - y) > eps or abs(out[m] - z) > eps then + out[m + 1], out[m + 2], out[m + 3] = x, y, z + end + end + while #out >= 6 and abs(out[1] - out[#out - 2]) <= eps and abs(out[2] - out[#out - 1]) <= eps and abs(out[3] - out[#out]) <= eps do + out[#out], out[#out - 1], out[#out - 2] = nil, nil, nil + end + -- colinear corners + local changed = true + while changed and #out >= 9 do + changed = false + local k = #out // 3 + for i = 0, k - 1 do + local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 + local ux, uy, uz = out[b + 1] - out[a + 1], out[b + 2] - out[a + 2], out[b + 3] - out[a + 3] + local vx, vy, vz = out[c + 1] - out[b + 1], out[c + 2] - out[b + 2], out[c + 3] - out[b + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) + if lu * lv == 0 or sqrt(cx * cx + cy * cy + cz * cz) <= 1e-9 * lu * lv then + table.remove(out, b + 3) + table.remove(out, b + 2) + table.remove(out, b + 1) + changed = true + break + end + end + end + return if #out >= 9 then out else nil +end + +local function samePlane(a: Plane, b: Plane, eps: number): boolean + return abs(a[1] - b[1]) < 1e-5 and abs(a[2] - b[2]) < 1e-5 and abs(a[3] - b[3]) < 1e-5 and abs(a[4] - b[4]) < eps +end + +local function oppositePlane(a: Plane, b: Plane, eps: number): boolean + return abs(a[1] + b[1]) < 1e-5 and abs(a[2] + b[2]) < 1e-5 and abs(a[3] + b[3]) < 1e-5 and abs(a[4] + b[4]) < eps +end + +-- one polygon per plane of a convex brush (nil for planes clipped away or repeating an earlier plane) +function Brush.windings(planes: { Plane }, opts: Options?): { { number }? } + local eps = opts and opts.epsilon or 1e-3 + local size = opts and opts.size or 2 ^ 17 + local out: { { number }? } = {} + for i, p in planes do + local w: { number }? = Brush.baseWinding(p, size) + for j, q in planes do + if not w then + break + end + if j ~= i then + if samePlane(p, q, eps) then + if j < i then + w = nil + end + else + local _, back, on = Brush.split(w, q, eps) + w = if on then nil else back + end + end + end + out[i] = if w then clean(w, eps) else nil + end + return out +end + +local function bounds(polys: { Polygon }): { number } + local b = { math.huge, math.huge, math.huge, -math.huge, -math.huge, -math.huge } + for _, p in polys do + local pts = p.points + for k = 0, #pts // 3 - 1 do + for c = 1, 3 do + local v = pts[k * 3 + c] + b[c] = min(b[c], v) + b[c + 3] = max(b[c + 3], v) + end + end + end + return b +end + +-- the parts of pts (on plane `own` of brush a) outside brush b +local function outside(pts: { number }, own: Plane, a: number, b: number, planes: { Plane }, eps: number): { { number } } + local kept: { { number } } = {} + local inside: { number }? = pts + for _, q in planes do + if not inside then + break + end + if samePlane(own, q, eps) then + if a < b then + return { pts } + end + elseif not oppositePlane(own, q, eps) then + local front, back = Brush.split(inside, q, eps) + if front then + table.insert(kept, front) + end + inside = back + end + end + return kept +end + +local function faceKey(f: Face): string + local parts = { f.texture or "" } + for _, m in { f.vecs, f.bp } do + if m then + for _, row in m do + for _, v in row do + table.insert(parts, string.format("%.6g", v)) + end + end + end + end + return table.concat(parts, " ") +end + +local function convex(pts: { number }, n: { number }, eps: number): boolean + local k = #pts // 3 + for i = 0, k - 1 do + local a, b, c = ((i + k - 1) % k) * 3, i * 3, ((i + 1) % k) * 3 + local ux, uy, uz = pts[b + 1] - pts[a + 1], pts[b + 2] - pts[a + 2], pts[b + 3] - pts[a + 3] + local vx, vy, vz = pts[c + 1] - pts[b + 1], pts[c + 2] - pts[b + 2], pts[c + 3] - pts[b + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + local lu, lv = sqrt(ux * ux + uy * uy + uz * uz), sqrt(vx * vx + vy * vy + vz * vz) + if (cx * n[1] + cy * n[2] + cz * n[3]) < -eps * max(lu, lv, 1) then + return false + end + end + return true +end + +-- qbsp TryMerge: two polygons sharing an edge (in opposite directions) -> their union, when convex +local function tryMerge(f1: { number }, f2: { number }, n: { number }, eps: number): { number }? + local n1, n2 = #f1 // 3, #f2 // 3 + for i = 0, n1 - 1 do + local i2 = (i + 1) % n1 + for j = 0, n2 - 1 do + local j2 = (j + 1) % n2 + local match = true + for c = 1, 3 do + if abs(f1[i * 3 + c] - f2[j2 * 3 + c]) > eps or abs(f1[i2 * 3 + c] - f2[j * 3 + c]) > eps then + match = false + break + end + end + if match then + local out: { number } = {} + for k = 0, n1 - 1 do + local s = ((i2 + k) % n1) * 3 + out[#out + 1], out[#out + 2], out[#out + 3] = f1[s + 1], f1[s + 2], f1[s + 3] + end + for k = 2, n2 - 1 do + local s = ((j + k) % n2) * 3 + out[#out + 1], out[#out + 2], out[#out + 3] = f2[s + 1], f2[s + 2], f2[s + 3] + end + local c = clean(out, eps) + if c and convex(c, n, eps) then + return c + end + return nil + end + end + end + return nil +end + +local function mergeAll(polys: { Polygon }, faces: { [number]: { Face } }, eps: number): { Polygon } + local groups: { [string]: { Polygon } } = {} + local order: { string } = {} + for _, p in polys do + local f = faces[p.brush][p.face] + local pl = f.plane + local key = string.format("%.5f %.5f %.5f %.3f|", pl[1], pl[2], pl[3], pl[4]) .. faceKey(f) + local g = groups[key] + if not g then + g = {} + groups[key] = g + table.insert(order, key) + end + table.insert(g, p) + end + local out: { Polygon } = {} + for _, key in order do + local g = groups[key] + local changed = true + while changed do + changed = false + for a = 1, #g do + for b = a + 1, #g do + local m = tryMerge(g[a].points, g[b].points, g[a].normal, eps) + if m then + g[a] = { brush = g[a].brush, face = g[a].face, points = m, normal = g[a].normal } + table.remove(g, b) + changed = true + break + end + end + if changed then + break + end + end + end + for _, p in g do + table.insert(out, p) + end + end + return out +end + +-- every brush's faces -> polygons (brushes[i] is a list of faces); nil, message past opts.maxPolygons +function Brush.polygons(brushes: { { Face } }, opts: Options?): ({ Polygon }?, string?) + local eps = opts and opts.epsilon or 1e-3 + local limit = opts and opts.maxPolygons or 2 ^ 20 + local per: { { Polygon } } = {} + local planesOf: { { Plane } } = {} + local count = 0 + for bi, faces in brushes do + local planes: { Plane } = {} + for fi, f in faces do + planes[fi] = f.plane + end + planesOf[bi] = planes + local list: { Polygon } = {} + local ws = Brush.windings(planes, opts) + for fi = 1, #faces do + local w = ws[fi] + if w then + table.insert(list, { brush = bi, face = fi, points = w, normal = { planes[fi][1], planes[fi][2], planes[fi][3] } }) + end + end + per[bi] = list + count += #list + if count > limit then + return nil, "limit: too many brush faces" + end + end + local all: { Polygon } = {} + if opts and opts.hull then + local boxes: { { number } } = {} + for bi = 1, #brushes do + boxes[bi] = bounds(per[bi]) + end + for bi = 1, #brushes do + for _, p in per[bi] do + local frags: { { number } } = { p.points } + local own = brushes[bi][p.face].plane + local pb = bounds({ p }) + for bj = 1, #brushes do + if #frags == 0 then + break + end + local ob = boxes[bj] + if bj ~= bi and #per[bj] > 0 and pb[1] <= ob[4] + eps and pb[4] >= ob[1] - eps and pb[2] <= ob[5] + eps + and pb[5] >= ob[2] - eps and pb[3] <= ob[6] + eps and pb[6] >= ob[3] - eps then + local nextFrags: { { number } } = {} + for _, fr in frags do + for _, kept in outside(fr, own, bi, bj, planesOf[bj], eps) do + table.insert(nextFrags, kept) + end + end + frags = nextFrags + if #frags > limit then + return nil, "limit: too many brush fragments" + end + end + end + for _, fr in frags do + local c = clean(fr, eps) + if c then + table.insert(all, { brush = p.brush, face = p.face, points = c, normal = p.normal }) + end + end + end + end + else + for bi = 1, #brushes do + for _, p in per[bi] do + table.insert(all, p) + end + end + end + if opts and opts.merge then + all = mergeAll(all, brushes, eps) + end + return all, nil +end + +-- polygon area (for checks against compilers) +function Brush.area(pts: { number }): number + local n = #pts // 3 + local ax, ay, az = 0, 0, 0 + for k = 1, n - 2 do + local ux, uy, uz = pts[k * 3 + 1] - pts[1], pts[k * 3 + 2] - pts[2], pts[k * 3 + 3] - pts[3] + local vx, vy, vz = pts[k * 3 + 4] - pts[1], pts[k * 3 + 5] - pts[2], pts[k * 3 + 6] - pts[3] + ax += uy * vz - uz * vy + ay += uz * vx - ux * vz + az += ux * vy - uy * vx + end + return sqrt(ax * ax + ay * ay + az * az) / 2 +end + +-- polygons -> one indexed triangle primitive per texture, in order of first use. size(name) gives a texture's +-- width, height (texel projections divide by them) +function Brush.primitives(polys: { Polygon }, brushes: { { Face } }, size: (name: string) -> (number, number)): { Built } + type Acc = { texture: string, pos: { number }, nrm: { number }, uv: { number }, idx: { number } } + local byTex: { [string]: Acc } = {} + local order: { Acc } = {} + local sizes: { [string]: { number } } = {} + for _, p in polys do + local f = brushes[p.brush][p.face] + local name = f.texture or "" + local acc = byTex[name] + if not acc then + acc = { texture = name, pos = {}, nrm = {}, uv = {}, idx = {} } + byTex[name] = acc + table.insert(order, acc) + end + local sz = sizes[name] + if not sz then + local w, h = size(name) + sz = { math.max(w, 1), math.max(h, 1) } + sizes[name] = sz + end + local a: Acc = acc + local pts = p.points + local n = #pts // 3 + local base = #a.pos // 3 + for k = 0, n - 1 do + local x, y, z = pts[k * 3 + 1], pts[k * 3 + 2], pts[k * 3 + 3] + local pp, nn, uu = a.pos, a.nrm, a.uv + pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z + nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = p.normal[1], p.normal[2], p.normal[3] + local u, v = Brush.uv(f, x, y, z, sz[1], sz[2]) + uu[#uu + 1], uu[#uu + 2] = u, v + end + local ii = a.idx + for k = 1, n - 2 do + ii[#ii + 1], ii[#ii + 2], ii[#ii + 3] = base, base + k, base + k + 1 + end + end + local out: { Built } = {} + for _, a in order do + local nv, ni = #a.pos // 3, #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + local S = Types.Scene + table.insert(out, { + texture = a.texture, + primitive = { + attributes = { POSITION = S.accessor(pb, "f32", 3, nv), NORMAL = S.accessor(nb, "f32", 3, nv), TEXCOORD_0 = S.accessor(ub, "f32", 2, nv) }, + indices = S.accessor(ib, "u32", 1, ni), + mode = "triangles" :: "triangles", + }, + }) + end + return out +end + +return Brush diff --git a/src/Rosetta/codecs/model/Patch.luau b/src/Rosetta/codecs/model/Patch.luau new file mode 100644 index 0000000..188dc00 --- /dev/null +++ b/src/Rosetta/codecs/model/Patch.luau @@ -0,0 +1,122 @@ +--!strict +--!native +--!optimize 2 +-- codecs/model/Patch: Quake III / Doom 3 Bezier patches (control grids) -> evaluated grids, triangles, normals. +-- A w x h grid (w, h odd, >= 3) is a mesh of 3 x 3 biquadratic sub-patches (Unofficial Quake 3 Map Specs; patchDef2 / +-- patchDef3), evaluated at fixed segments per sub-patch and axis (patchDef3's explicit subdivisions; Quake III's adaptive +-- subdivision is not reproduced). Shared edges are evaluated once. +local Patch = {} + +local sqrt = math.sqrt + +function Patch.valid(w: number, h: number, n: number): boolean + return w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n +end + +-- ctrl: w * h points of comps numbers, row-major (row j holds points j * w .. j * w + w - 1); returns the evaluated grid +-- (gw * gh points of comps numbers, row-major) and its size; nil when the grid is not w x h odd or a limit is passed +function Patch.grid(ctrl: { number }, w: number, h: number, comps: number, levelU: number, levelV: number, maxPoints: number?): ({ number }?, number, number) + local lu, lv = math.max(1, math.floor(levelU)), math.max(1, math.floor(levelV)) + if not Patch.valid(w, h, #ctrl // comps) or #ctrl ~= w * h * comps then + return nil, 0, 0 + end + local px, py = (w - 1) // 2, (h - 1) // 2 + local gw, gh = px * lu + 1, py * lv + 1 + if gw * gh > (maxPoints or 2 ^ 24) then + return nil, 0, 0 + end + local out = table.create(gw * gh * comps, 0) :: { number } + for gy = 0, gh - 1 do + local sy = math.min(gy // lv, py - 1) + local tv = (gy - sy * lv) / lv + local bv0, bv1, bv2 = (1 - tv) * (1 - tv), 2 * tv * (1 - tv), tv * tv + for gx = 0, gw - 1 do + local sx = math.min(gx // lu, px - 1) + local tu = (gx - sx * lu) / lu + local bu0, bu1, bu2 = (1 - tu) * (1 - tu), 2 * tu * (1 - tu), tu * tu + local o = (gy * gw + gx) * comps + for j = 0, 2 do + local bv = if j == 0 then bv0 elseif j == 1 then bv1 else bv2 + local row = ((sy * 2 + j) * w + sx * 2) * comps + for i = 0, 2 do + local wgt = bv * (if i == 0 then bu0 elseif i == 1 then bu1 else bu2) + local c = row + i * comps + for k = 1, comps do + out[o + k] += ctrl[c + k] * wgt + end + end + end + end + end + return out, gw, gh +end + +-- 0-based triangle indices over a gw x gh grid; Quake's control grids are clockwise-front, these are counter-clockwise +function Patch.triangles(gw: number, gh: number): { number } + local out = table.create(math.max(0, (gw - 1) * (gh - 1) * 6)) :: { number } + for gy = 0, gh - 2 do + for gx = 0, gw - 2 do + local a, b = gy * gw + gx, gy * gw + gx + 1 + local d, e = a + gw, b + gw + local n = #out + out[n + 1], out[n + 2], out[n + 3] = a, d, b + out[n + 4], out[n + 5], out[n + 6] = b, d, e + end + end + return out +end + +-- renormalizes the vec3 at component offset at (0-based) of every point +function Patch.normalize(pts: { number }, comps: number, at: number) + for o = 0, #pts - comps, comps do + local x, y, z = pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + pts[o + at + 1], pts[o + at + 2], pts[o + at + 3] = x / l, y / l, z / l + end + end +end + +-- unit normals (3 per point) of the evaluated grid from the positions (components 1..3), facing the front of +-- Patch.triangles; points where the surface degenerates take a neighbour's normal +function Patch.normals(pts: { number }, comps: number, gw: number, gh: number): { number } + local out = table.create(gw * gh * 3, 0) :: { number } + local function at(x: number, y: number, k: number): number + return pts[(y * gw + x) * comps + k] + end + for gy = 0, gh - 1 do + local y0, y1 = math.max(gy - 1, 0), math.min(gy + 1, gh - 1) + for gx = 0, gw - 1 do + local x0, x1 = math.max(gx - 1, 0), math.min(gx + 1, gw - 1) + local ux, uy, uz = at(x1, gy, 1) - at(x0, gy, 1), at(x1, gy, 2) - at(x0, gy, 2), at(x1, gy, 3) - at(x0, gy, 3) + local vx, vy, vz = at(gx, y1, 1) - at(gx, y0, 1), at(gx, y1, 2) - at(gx, y0, 2), at(gx, y1, 3) - at(gx, y0, 3) + local nx, ny, nz = vy * uz - vz * uy, vz * ux - vx * uz, vx * uy - vy * ux + local l = sqrt(nx * nx + ny * ny + nz * nz) + local o = (gy * gw + gx) * 3 + if l > 1e-12 then + out[o + 1], out[o + 2], out[o + 3] = nx / l, ny / l, nz / l + end + end + end + for _ = 1, 2 do + for i = 0, gw * gh - 1 do + local o = i * 3 + if out[o + 1] == 0 and out[o + 2] == 0 and out[o + 3] == 0 then + local x, y = i % gw, i // gw + for _, d in { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 }, { 1, 1 }, { -1, -1 }, { 1, -1 }, { -1, 1 } } do + local nx2, ny2 = x + d[1], y + d[2] + if nx2 >= 0 and nx2 < gw and ny2 >= 0 and ny2 < gh then + local q = (ny2 * gw + nx2) * 3 + if out[q + 1] ~= 0 or out[q + 2] ~= 0 or out[q + 3] ~= 0 then + out[o + 1], out[o + 2], out[o + 3] = out[q + 1], out[q + 2], out[q + 3] + break + end + end + end + end + end + end + return out +end + +return Patch diff --git a/src/Rosetta/data/q3shader/init.luau b/src/Rosetta/data/q3shader/init.luau new file mode 100644 index 0000000..3efaad5 --- /dev/null +++ b/src/Rosetta/data/q3shader/init.luau @@ -0,0 +1,237 @@ +--!strict +-- data/q3shader: Quake III shader scripts (.shader; the Quake III Arena Shader Manual, tr_shader.c tokenizing: no code +-- taken), read and write. A script is a list of shaders { name, directives, stages }; a directive is its tokens +-- ({ "surfaceparm", "nolightmap" }, one line each), a stage is a list of directives. Keywords keep their case. +-- Comments (// and /* */) are dropped. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@rosetta/core/Err") +local Bytes = require("@rosetta/core/Bytes") + +-- ------------------------------------------------------------------------------------------------ contract +local Q3Shader = { + name = "q3shader", + category = "data", + extensions = { "shader" }, + mime = { "text/x-quake3-shader" }, + deps = { "core/Err", "core/Bytes" }, + caps = { decode = true, encode = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Directive = { string } +export type Shader = { name: string, directives: { Directive }, stages: { { Directive } } } +export type EncodeOptions = { indent: string? } -- default "\t" + +-- ------------------------------------------------------------------------------------------------ constants +local KEYWORDS = { "surfaceparm", "map", "clampmap", "animmap", "blendfunc", "rgbgen", "alphagen", "tcgen", "tcmod", + "cull", "deformvertexes", "qer_editorimage", "nopicmip", "nomipmaps", "skyparms", "q3map_", "depthwrite", "alphafunc" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Q3Shader.sniff(r: Bytes.Reader): number + local head = r:peek(math.min(r:remaining(), 2048)) + if #head < 4 or string.find(head, "[%z\1-\8\14-\31]") then + return 0 + end + local s = string.gsub(string.gsub(head, "/%*.-%*/", " "), "//[^\n]*", "") + if not string.match(s, "^%s*[^%s{}\"]+%s*{") then + return 0 + end + local lower = string.lower(s) + for _, k in KEYWORDS do + if string.find(lower, "%f[%w_]" .. k) then + return 0.7 + end + end + return 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the token lines of a script; braces are lines of their own +local function lex(text: string): ({ { string } }?, string?) + local lines: { { string } } = {} + local cur: { string } = {} + local i, n = 1, #text + local function flush() + if #cur > 0 then + table.insert(lines, cur) + cur = {} + end + end + while i <= n do + local c = string.sub(text, i, i) + if c == "\n" then + flush() + i += 1 + elseif string.match(c, "%s") then + i += 1 + elseif string.sub(text, i, i + 1) == "//" then + local e = string.find(text, "\n", i, true) + i = e or n + 1 + elseif string.sub(text, i, i + 1) == "/*" then + local _, e = string.find(text, "*/", i + 2, true) + if not e then + return nil, "unterminated comment" + end + for _ in string.gmatch(string.sub(text, i, e), "\n") do + flush() + end + i = e + 1 + elseif c == "{" or c == "}" then + flush() + table.insert(lines, { c }) + i += 1 + elseif c == '"' then + local e = string.find(text, '"', i + 1, true) + if not e then + return nil, "unterminated string" + end + table.insert(cur, string.sub(text, i + 1, e - 1)) + i = e + 1 + else + local _, e = string.find(text, "^[^%s{}\"]+", i) + local stop = e :: number + local tok = string.sub(text, i, stop) + local cm = string.find(tok, "//", 1, true) + if cm and cm > 1 then + tok = string.sub(tok, 1, cm - 1) + stop = i + cm - 2 + end + table.insert(cur, tok) + i = stop + 1 + end + end + flush() + return lines, nil +end + +function Q3Shader.decode(r: Bytes.Reader): ({ Shader }?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local lines, msg = lex(text) + if not lines then + return nil, Err.new(Err.CORRUPT, msg or "bad script") + end + local out: { Shader } = {} + local k = 1 + while k <= #lines do + local l = lines[k] + if #l ~= 1 or l[1] == "{" or l[1] == "}" then + return nil, Err.new(Err.CORRUPT, "expected a shader name, got '" .. table.concat(l, " ") .. "'") + end + local sh: Shader = { name = l[1], directives = {}, stages = {} } + k += 1 + if not lines[k] or lines[k][1] ~= "{" then + return nil, Err.new(Err.CORRUPT, "expected '{' after " .. sh.name) + end + k += 1 + local stage: { Directive }? = nil + local closed = false + while k <= #lines do + local d = lines[k] + k += 1 + if d[1] == "{" then + if stage then + return nil, Err.new(Err.CORRUPT, "nested stage in " .. sh.name) + end + stage = {} + elseif d[1] == "}" then + if stage then + table.insert(sh.stages, stage) + stage = nil + else + closed = true + break + end + elseif stage then + table.insert(stage, d) + else + table.insert(sh.directives, d) + end + end + if not closed then + return nil, Err.new(Err.TRUNCATED, "shader " .. sh.name .. " not closed") + end + table.insert(out, sh) + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function tokens(d: any): (string?, string?) + if type(d) ~= "table" or #d == 0 then + return nil, "a directive is a list of strings" + end + local parts = {} + for _, t in d do + local s = tostring(t) + if s == "" or string.find(s, "[%s{}]") then + if string.find(s, '"', 1, true) or string.find(s, "\n") then + return nil, "token cannot hold quotes or line breaks: " .. s + end + s = '"' .. s .. '"' + end + table.insert(parts, s) + end + return table.concat(parts, " "), nil +end + +function Q3Shader.encode(list: { Shader }, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(list) ~= "table" then + return nil, Err.new(Err.ARG, "expected a list of shaders") + end + local ind = opts and opts.indent or "\t" + local out: { string } = {} + for _, sh in list do + if type(sh) ~= "table" or type(sh.name) ~= "string" or sh.name == "" or string.find(sh.name, "[%s{}\"]") then + return nil, Err.new(Err.ARG, "a shader needs a name without spaces") + end + table.insert(out, sh.name) + table.insert(out, "{") + for _, d in sh.directives or {} do + local line, e = tokens(d) + if not line then + return nil, Err.new(Err.ARG, e or "bad directive") + end + table.insert(out, ind .. line) + end + for _, st in sh.stages or {} do + table.insert(out, ind .. "{") + for _, d in st do + local line, e = tokens(d) + if not line then + return nil, Err.new(Err.ARG, e or "bad directive") + end + table.insert(out, ind .. ind .. line) + end + table.insert(out, ind .. "}") + end + table.insert(out, "}") + table.insert(out, "") + end + return buffer.fromstring(table.concat(out, "\n")), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- the shader named name (case-insensitive, as the game looks them up) +function Q3Shader.find(list: { Shader }, name: string): Shader? + local want = string.lower(name) + for _, sh in list do + if string.lower(sh.name) == want then + return sh + end + end + return nil +end + +-- the first directive starting with keyword (case-insensitive) in a shader or stage directive list +function Q3Shader.directive(list: { Directive }, keyword: string): Directive? + local want = string.lower(keyword) + for _, d in list do + if string.lower(d[1] or "") == want then + return d + end + end + return nil +end + +return Q3Shader diff --git a/src/Rosetta/data/q3skin/init.luau b/src/Rosetta/data/q3skin/init.luau new file mode 100644 index 0000000..1b37c0f --- /dev/null +++ b/src/Rosetta/data/q3skin/init.luau @@ -0,0 +1,94 @@ +--!strict +-- data/q3skin: Quake III model skins (.skin: "surface,shader" lines, "tag_*," for tags; tr_image.c RE_RegisterSkin, no +-- code taken), read and write. Decodes to a list of { surface, shader } in file order (shader "" for tags). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@rosetta/core/Err") +local Bytes = require("@rosetta/core/Bytes") + +-- ------------------------------------------------------------------------------------------------ contract +local Q3Skin = { + name = "q3skin", + category = "data", + extensions = { "skin" }, + mime = { "text/x-quake3-skin" }, + deps = { "core/Err", "core/Bytes" }, + caps = { decode = true, encode = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type Entry = { surface: string, shader: string } + +-- ------------------------------------------------------------------------------------------------ sniff +function Q3Skin.sniff(r: Bytes.Reader): number + local head = r:peek(math.min(r:remaining(), 1024)) + if #head < 3 or string.find(head, "[%z\1-\8\14-\31]") then + return 0 + end + local lines, good, paths = 0, 0, 0 + for line in string.gmatch(head, "[^\r\n]+") do + if not string.match(line, "^%s*$") then + lines += 1 + local surface, shader = string.match(line, "^%s*([%w_%-]+)%s*,%s*([^,%s]*)%s*$") + if surface and shader == "" and string.sub(string.lower(surface), 1, 4) == "tag_" then + good += 1 + elseif shader and string.find(shader, "/", 1, true) then + good += 1 + paths += 1 + end + end + end + return if lines > 0 and good == lines and paths > 0 then 0.5 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function Q3Skin.decode(r: Bytes.Reader): ({ Entry }?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local out: { Entry } = {} + local n = 0 + for line in string.gmatch(text, "[^\r\n]+") do + n += 1 + local s = string.match(line, "^%s*(.-)%s*$") :: string + if s ~= "" and string.sub(s, 1, 2) ~= "//" then + local surface, shader = string.match(s, "^([^,]-)%s*,%s*(.-)$") + if not surface or surface == "" then + return nil, Err.new(Err.CORRUPT, "line " .. n .. ": expected surface,shader") + end + table.insert(out, { surface = surface, shader = shader :: string }) + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Q3Skin.encode(list: { Entry }): (buffer?, Err.Err?) + if type(list) ~= "table" then + return nil, Err.new(Err.ARG, "expected a list of { surface, shader }") + end + local out: { string } = {} + for _, e in list do + if type(e) ~= "table" or type(e.surface) ~= "string" or e.surface == "" or string.find(e.surface, "[,\r\n]") then + return nil, Err.new(Err.ARG, "a skin entry needs a surface name without commas") + end + local sh = if e.shader == nil then "" else tostring(e.shader) + if string.find(sh, "[,\r\n]") then + return nil, Err.new(Err.ARG, "a shader path cannot hold commas or line breaks") + end + table.insert(out, e.surface .. "," .. sh) + end + table.insert(out, "") + return buffer.fromstring(table.concat(out, "\n")), nil +end + +-- the shader of a surface (case-insensitive) +function Q3Skin.shader(list: { Entry }, surface: string): string? + local want = string.lower(surface) + for _, e in list do + if string.lower(e.surface) == want then + return e.shader + end + end + return nil +end + +return Q3Skin diff --git a/src/Rosetta/image/lmp/init.luau b/src/Rosetta/image/lmp/init.luau new file mode 100644 index 0000000..8127063 --- /dev/null +++ b/src/Rosetta/image/lmp/init.luau @@ -0,0 +1,131 @@ +--!strict +-- image/lmp: Quake .lmp lumps (wad.h / draw.c of the Quake source; no code taken), read and write: qpic pictures (u32 +-- width, height, 8-bit pixels; index 255 transparent), palette.lmp (768 bytes: a 16 x 16 swatch) and colormap.lmp (64 +-- light levels x 256: a 256 x 64 image). Pictures and colormaps need Quake's palette, which is never embedded (GPL): +-- opts.palette or gfx/palette.lmp through files / resolve; else grey (meta.source.palette = false). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@rosetta/core/Err") +local Bytes = require("@rosetta/core/Bytes") +local Input = require("@rosetta/core/Input") +local Types = require("@rosetta/Types") +local Pixels = require("@rosetta/codecs/image/Pixels") +local Miptex = require("@rosetta/codecs/image/Miptex") + +-- ------------------------------------------------------------------------------------------------ contract +local Lmp = { + name = "lmp", + category = "image", + extensions = { "lmp" }, + mime = { "image/x-quake-lmp" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, alpha = true, depths = { 8 }, variants = { "qpic", "palette", "colormap" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + palette: (buffer | string)?, -- 768 bytes + kind: ("qpic" | "palette" | "colormap")?, -- default: from the size + keyed: boolean?, -- qpic index 255 transparent, default true + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + maxPixels: number?, -- default 2^24 +} +export type EncodeOptions = { + palette: (buffer | string)?, -- 768 bytes: required for qpics + kind: ("qpic" | "palette")?, -- default "qpic"; "palette" writes a 16 x 16 swatch as 768 bytes + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, +} + +-- ------------------------------------------------------------------------------------------------ sniff +local function kindOf(r: Bytes.Reader): string? + local n = r:remaining() + if n == 768 then + return "palette" + elseif n == 16385 or n == 16384 then + return "colormap" + end + if n < 9 then + return nil + end + local w, h = buffer.readu32(r.buf, r.pos), buffer.readu32(r.buf, r.pos + 4) + if w > 0 and h > 0 and w <= 4096 and h <= 4096 and 8 + w * h == n then + return "qpic" + end + return nil +end + +function Lmp.sniff(r: Bytes.Reader): number + local k = kindOf(r) + return if k == "qpic" then 0.3 elseif k then 0.05 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function palette(opts: any?): buffer? + local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp") + if raw and buffer.len(raw) >= 768 then + return Pixels.palette(raw, 0, 256) + end + return nil +end + +function Lmp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + local kind = opts and opts.kind or kindOf(r) + local b, at, n = r.buf, r.base, r.limit - r.base + if kind == "palette" then + if n < 768 then + return nil, Err.new(Err.TRUNCATED, "palette", 0) + end + local img = Types.Image.new(16, 16) + buffer.copy(img.pixels, 0, Pixels.palette(b, at, 256), 0, 1024) + local list = Pixels.colorList(img.pixels) + img.meta.palette = list + img.meta.source = { format = "lmp", kind = "palette" } + return img, nil + end + local pal = palette(opts) + if kind == "colormap" then + local rows = math.min(64, n // 256) + if rows < 1 then + return nil, Err.new(Err.TRUNCATED, "colormap", 0) + end + local img = Types.Image.new(256, rows) + Pixels.indexed(b, at, 256, 8, img.pixels, 256, rows, true, pal or Pixels.grey()) + img.meta.source = { format = "lmp", kind = "colormap", palette = pal ~= nil } + return img, nil + end + if kind ~= "qpic" and n >= 8 then + kind = "qpic" + end + local img, msg = Miptex.qpic(b, at, n, { palette = pal, keyed = opts and opts.keyed, maxPixels = opts and opts.maxPixels }) + if not img then + return nil, Err.from(msg, 0) + end + img.meta.source = { format = "lmp", kind = "qpic", palette = pal ~= nil, keyed = (opts == nil or opts.keyed ~= false) or nil } + return img, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Lmp.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected an rgba8 Image") + end + if opts and opts.kind == "palette" then + if img.width * img.height < 256 then + return nil, Err.new(Err.ARG, "a palette needs 256 pixels (16 x 16)") + end + return Pixels.paletteBytes(img.pixels, 256), nil + end + local pal = palette(opts) + if not pal then + return nil, Err.new(Err.ARG, "a qpic needs Quake's palette (opts.palette or gfx/palette.lmp; it is not embedded)") + end + local out, msg = Miptex.encodeQpic(img, pal, false, true) + if not out then + return nil, Err.new(Err.ARG, msg or "cannot encode") + end + return out, nil +end + +return Lmp diff --git a/src/Rosetta/image/spr/init.luau b/src/Rosetta/image/spr/init.luau new file mode 100644 index 0000000..f2f8b06 --- /dev/null +++ b/src/Rosetta/image/spr/init.luau @@ -0,0 +1,311 @@ +--!strict +-- image/spr: Quake (IDSP 1), Half-Life (IDSP 2, own palette, texture formats) and DarkPlaces SPR32 (IDSP 32, rgba) +-- sprites, read and write (spritegn.h of the Quake source, the GoldSrc sprite layout; no code taken). Frames and frame +-- groups become Image frames on one canvas around the sprite origin (meta.origin); group intervals give the delays. +-- Quake sprites need Quake's palette (opts.palette or gfx/palette.lmp through files / resolve; never embedded). +-- Not supported: Quake II sprites (IDS2: frames are separate .pcx files). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@rosetta/core/Err") +local Bytes = require("@rosetta/core/Bytes") +local Input = require("@rosetta/core/Input") +local Types = require("@rosetta/Types") +local Pixels = require("@rosetta/codecs/image/Pixels") +local Miptex = require("@rosetta/codecs/image/Miptex") + +-- ------------------------------------------------------------------------------------------------ contract +local Spr = { + name = "spr", + category = "image", + extensions = { "spr" }, + mime = { "image/x-quake-sprite" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex" }, + caps = { decode = true, encode = true, alpha = true, animation = true, variants = { "quake", "halflife", "spr32" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + palette: (buffer | string)?, -- Quake: 768 bytes + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + maxPixels: number?, -- per frame, default 2^24 + maxFrames: number?, -- default 4096 +} +export type EncodeOptions = { + version: number?, -- 2 (Half-Life, default), 1 (Quake: needs opts.palette) or 32 (rgba) + palette: (buffer | string)?, + type: number?, -- orientation: 0 parallel upright, 1 facing upright, 2 parallel (default), 3 oriented, 4 parallel oriented + texFormat: number?, -- Half-Life: 0 normal, 1 additive, 2 index alpha, 3 alpha test (default: 3 when any pixel is transparent) + delay: number?, -- seconds per frame when the image has none, default 0.1 +} + +-- ------------------------------------------------------------------------------------------------ constants +local TEX_FORMATS = { [0] = "normal", "additive", "indexalpha", "alphatest" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Spr.sniff(r: Bytes.Reader): number + if r:remaining() < 36 or r:peek(4) ~= "IDSP" then + return 0 + end + local v = buffer.readi32(r.buf, r.pos + 4) + return if v == 1 or v == 2 or v == 32 then 1 else 0.3 +end + +-- ------------------------------------------------------------------------------------------------ decode +type Raw = { x: number, y: number, w: number, h: number, at: number, delay: number } + +function Spr.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?) + if r:string(4) ~= "IDSP" then + return nil, r.err or Err.new(Err.CORRUPT, "bad magic", 0) + end + local version = r:i32le() + if version ~= 1 and version ~= 2 and version ~= 32 then + return nil, Err.new(Err.UNSUPPORTED, "sprite version " .. tostring(version), 4) + end + local stype = r:i32le() + local texFormat = if version == 2 then r:i32le() else 3 + local radius = r:f32le() + local mw, mh, nframes = r:i32le(), r:i32le(), r:i32le() + local beam, sync = r:f32le(), r:i32le() + if r.err then + return nil, r.err + end + local maxFrames = opts and opts.maxFrames or 4096 + local maxPixels = opts and opts.maxPixels or 2 ^ 24 + if nframes < 1 or nframes > maxFrames then + return nil, Err.new(if nframes < 1 then Err.CORRUPT else Err.LIMIT, "frame count " .. nframes, 24) + end + local pal: buffer + local own = false + if version == 2 then + local n = r:u16le() + if r.err then + return nil, r.err + end + if n < 1 or n > 256 or not r:need(n * 3) then + return nil, r.err or Err.new(Err.CORRUPT, "palette size " .. n, r:tell() - 2) + end + pal = Pixels.palette(r.buf, r.pos, n) + r:skip(n * 3) + own = true + else + local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else Input.sibling(opts, "gfx/palette.lmp") + own = raw ~= nil and buffer.len(raw) >= 768 + pal = if raw and own then Pixels.palette(raw, 0, 256) else Pixels.grey() + end + local bpp = if version == 32 then 4 else 1 + local raws: { Raw } = {} + local groups: { { type: string, count: number } } = {} + local function single(delay: number): Err.Err? + local x, y, w, h = r:i32le(), r:i32le(), r:i32le(), r:i32le() + if r.err then + return r.err + end + if w < 1 or h < 1 then + return Err.new(Err.CORRUPT, "frame size " .. w .. " x " .. h, r:tell() - 8) + end + if w * h > maxPixels then + return Err.new(Err.LIMIT, "frame " .. w .. " x " .. h) + end + if not r:need(w * h * bpp) then + return r.err + end + table.insert(raws, { x = x, y = y, w = w, h = h, at = r.pos, delay = delay }) + r:skip(w * h * bpp) + return nil + end + for _ = 1, nframes do + local ft = r:i32le() + if r.err then + return nil, r.err + end + if ft == 0 then + local e = single(0.1) + if e then + return nil, e + end + table.insert(groups, { type = "single", count = 1 }) + else + local n = r:i32le() + if r.err then + return nil, r.err + end + if n < 1 or #raws + n > maxFrames then + return nil, Err.new(if n < 1 then Err.CORRUPT else Err.LIMIT, "group of " .. n .. " frames", r:tell() - 4) + end + local ivs = {} + for k = 1, n do + ivs[k] = r:f32le() + end + if r.err then + return nil, r.err + end + for k = 1, n do + -- intervals are cumulative end times (R_GetSpriteFrame) + local e = single(math.max(0, ivs[k] - (if k > 1 then ivs[k - 1] else 0))) + if e then + return nil, e + end + end + table.insert(groups, { type = "group", count = n }) + end + end + local minX: number, maxX: number, minY: number, maxY: number = math.huge, -math.huge, math.huge, -math.huge + for _, f in raws do + minX = math.min(minX, f.x) + maxX = math.max(maxX, f.x + f.w) + maxY = math.max(maxY, f.y) + minY = math.min(minY, f.y - f.h) + end + local cw, ch = maxX - minX, maxY - minY + if cw * ch > maxPixels then + return nil, Err.new(Err.LIMIT, "canvas " .. cw .. " x " .. ch) + end + local fpal = pal + if version ~= 2 or texFormat == 3 then + fpal = Pixels.keyed(pal, 255) + end + local b = r.buf + local frames: { any } = {} + for _, f in raws do + local img = Types.Image.new(f.w, f.h) + if version == 32 then + buffer.copy(img.pixels, 0, b, f.at, f.w * f.h * 4) + elseif version == 2 and texFormat == 2 then + -- index alpha: the colour is the last palette entry, the index is the alpha + local c = bit32.band(buffer.readu32(pal, 255 * 4), 0xFFFFFF) + for k = 0, f.w * f.h - 1 do + buffer.writeu32(img.pixels, k * 4, c + buffer.readu8(b, f.at + k) * 0x1000000) + end + else + Pixels.indexed(b, f.at, f.w, 8, img.pixels, f.w, f.h, true, fpal) + end + table.insert(frames, { image = img, delay = f.delay, x = f.x - minX, y = maxY - f.y, dispose = "background", blend = "source" }) + end + local out = Types.Image.new(cw, ch) + local f1 = frames[1] + for yy = 0, f1.image.height - 1 do + buffer.copy(out.pixels, ((f1.y + yy) * cw + f1.x) * 4, f1.image.pixels, yy * f1.image.width * 4, f1.image.width * 4) + end + out.frames = if #frames > 1 then frames else nil + out.loops = 0 + out.meta.origin = { -minX, maxY } + out.meta.source = { + format = "spr", version = version, type = stype, texFormat = if version == 2 then TEX_FORMATS[texFormat] or texFormat else nil, + radius = radius, width = mw, height = mh, beamLength = beam, sync = sync, groups = groups, + palette = own, origins = (function() + local o = {} + for i, f in raws do + o[i] = { f.x, f.y } + end + return o + end)(), + } + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function Spr.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(img) ~= "table" or img.format ~= "rgba8" or type(img.pixels) ~= "buffer" then + return nil, Err.new(Err.ARG, "expected an rgba8 Image") + end + local version = opts and opts.version or 2 + if version ~= 1 and version ~= 2 and version ~= 32 then + return nil, Err.new(Err.ARG, "version must be 1, 2 or 32") + end + local list: { { image: Types.Image, x: number, y: number, delay: number } } = {} + if img.frames and #img.frames > 0 then + for _, f in img.frames do + if f.image.format ~= "rgba8" then + return nil, Err.new(Err.ARG, "frames must be rgba8") + end + table.insert(list, { image = f.image, x = f.x, y = f.y, delay = f.delay }) + end + else + table.insert(list, { image = img, x = 0, y = 0, delay = opts and opts.delay or 0.1 }) + end + local origin = img.meta and img.meta.origin or { img.width // 2, img.height // 2 } + local mw: number, mh: number, alpha = 0, 0, false + for _, f in list do + mw = math.max(mw, f.image.width) + mh = math.max(mh, f.image.height) + local px = f.image.pixels + for k = 0, f.image.width * f.image.height - 1 do + if buffer.readu8(px, k * 4 + 3) < 128 then + alpha = true + break + end + end + end + local pal: buffer? = nil + if version == 1 then + local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else nil + if not raw or buffer.len(raw) < 768 then + return nil, Err.new(Err.ARG, "a Quake sprite needs Quake's palette (opts.palette; it is not embedded)") + end + pal = Pixels.palette(raw, 0, 256) + elseif version == 2 then + local raw = if opts and opts.palette then Bytes.toBuffer(opts.palette) else nil + if raw and buffer.len(raw) >= 768 then + pal = Pixels.palette(raw, 0, 256) + else + -- one palette for every frame: the frames side by side + local tw = 0 + for _, f in list do + tw += f.image.width + end + local strip = Types.Image.new(tw, mh) + local x0 = 0 + for _, f in list do + for yy = 0, f.image.height - 1 do + buffer.copy(strip.pixels, (yy * tw + x0) * 4, f.image.pixels, yy * f.image.width * 4, f.image.width * 4) + end + x0 += f.image.width + end + local _, colors = Miptex.indices(strip, nil, alpha) + local p = buffer.create(1024) + for i, c in colors do + buffer.writeu32(p, (i - 1) * 4, 0xFF000000 + c[3] * 65536 + c[2] * 256 + c[1]) + end + if alpha then + buffer.writeu32(p, 255 * 4, 0xFFFF0000) -- the alpha-test key: blue + end + pal = p + end + end + local texFormat = opts and opts.texFormat or (if alpha then 3 else 0) + local w = Bytes.writer() + w:string("IDSP") + w:u32le(version) + w:u32le(opts and opts.type or 2) + if version == 2 then + w:u32le(texFormat) + end + w:f32le(math.sqrt(mw * mw + mh * mh) / 2) + w:u32le(mw) + w:u32le(mh) + w:u32le(#list) + w:f32le(0) + w:u32le(0) + if version == 2 then + w:u16le(256) + w:bytes(Pixels.paletteBytes(pal :: buffer, 256)) + end + for _, f in list do + local fw, fh = f.image.width, f.image.height + w:u32le(0) + w:u32le(bit32.band(f.x - origin[1], 0xFFFFFFFF)) + w:u32le(bit32.band(origin[2] - f.y, 0xFFFFFFFF)) + w:u32le(fw) + w:u32le(fh) + if version == 32 then + w:bytes(f.image.pixels, 0, fw * fh * 4) + else + local idx = Miptex.indices(f.image, pal, alpha and texFormat == 3 or version == 1) + w:bytes(idx, 0, fw * fh) + end + end + return w:finish(), nil +end + +return Spr diff --git a/src/Rosetta/model/bsp/Lightmap.luau b/src/Rosetta/model/bsp/Lightmap.luau new file mode 100644 index 0000000..b2cb5ab --- /dev/null +++ b/src/Rosetta/model/bsp/Lightmap.luau @@ -0,0 +1,64 @@ +--!strict +-- model/bsp/Lightmap: packs face lightmaps (w x h luxels each) into one atlas, shelf by shelf, tallest first, each +-- with a one-luxel border that repeats its edge (bilinear filtering stays inside the face). +local Lightmap = {} + +export type Rect = { x: number, y: number, w: number, h: number } -- x, y: the first luxel inside the border + +-- nil, message past maxPixels +function Lightmap.pack(sizes: { { number } }, maxPixels: number): (number, number, { Rect }?, string?) + local area, widest = 0, 1 + for _, s in sizes do + area += (s[1] + 2) * (s[2] + 2) + widest = math.max(widest, s[1] + 2) + end + local W = 64 + while W * W < area * 1.2 and W < 4096 do + W *= 2 + end + W = math.max(W, widest) + local order = table.create(#sizes) :: { number } + for i = 1, #sizes do + order[i] = i + end + table.sort(order, function(a: number, b: number): boolean + local ha, hb = sizes[a][2], sizes[b][2] + if ha ~= hb then + return ha > hb + end + return a < b + end) + local out = table.create(#sizes) :: { Rect } + local x, y, rowH = 0, 0, 0 + for _, i in order do + local w, h = sizes[i][1] + 2, sizes[i][2] + 2 + if x + w > W then + x, y, rowH = 0, y + rowH, 0 + end + out[i] = { x = x + 1, y = y + 1, w = sizes[i][1], h = sizes[i][2] } + x += w + rowH = math.max(rowH, h) + end + local H = math.max(1, y + rowH) + if W * H > maxPixels then + return 0, 0, nil, "limit: lightmap atlas " .. W .. " x " .. H + end + return W, H, out, nil +end + +-- copies the outermost luxels of a rect into its border (rgba8 pixels, atlas width W) +function Lightmap.border(px: buffer, W: number, r: Rect) + local function copy(dx: number, dy: number, sx: number, sy: number) + buffer.writeu32(px, (dy * W + dx) * 4, buffer.readu32(px, (sy * W + sx) * 4)) + end + for yy = r.y, r.y + r.h - 1 do + copy(r.x - 1, yy, r.x, yy) + copy(r.x + r.w, yy, r.x + r.w - 1, yy) + end + for xx = r.x - 1, r.x + r.w do + copy(xx, r.y - 1, xx, r.y) + copy(xx, r.y + r.h, xx, r.y + r.h - 1) + end +end + +return Lightmap diff --git a/src/Rosetta/model/bsp/Brush.luau b/src/Rosetta/model/bsp/Quake.luau similarity index 50% rename from src/Rosetta/model/bsp/Brush.luau rename to src/Rosetta/model/bsp/Quake.luau index f745199..a0b1081 100644 --- a/src/Rosetta/model/bsp/Brush.luau +++ b/src/Rosetta/model/bsp/Quake.luau @@ -1,14 +1,17 @@ --!strict --- model/bsp/Brush: Quake 1 (BSP 29), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from bspfile.h of the --- Quake / Quake II source releases (no code taken). Texture coordinates: s = v . s.xyz + s.w, divided by the texture --- size. +-- model/bsp/Quake: Quake 1 (BSP 29, BSP2, 2PSB), Half-Life (BSP 30) and Quake II (IBSP 38) maps -> Scene, from +-- bspfile.h of the Quake / Quake II source releases and ericw-tools (BSP2 / 2PSB; no code taken). Texture coordinates: +-- s = v . s.xyz + s.w over the texture size; lightmaps (style 0) packed into one atlas as TEXCOORD_1, extents as +-- CalcSurfaceExtents (16 texels per luxel). local Types = require("@rosetta/Types") local Pixels = require("@rosetta/codecs/image/Pixels") +local Lightmap = require("@rosetta/model/bsp/Lightmap") +local Miptex = require("@rosetta/codecs/image/Miptex") -local Brush = {} +local Quake = {} local Scene = Types.Scene -local readi32, readu16, readf32, readu32 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32 +local readi32, readu16, readf32, readu32, readu8 = buffer.readi32, buffer.readu16, buffer.readf32, buffer.readu32, buffer.readu8 local writef32, writeu32 = buffer.writef32, buffer.writeu32 export type Lump = { at: number, size: number } @@ -17,10 +20,12 @@ export type Options = { wal: ((name: string) -> buffer?)?, -- Quake II: a texture's .wal file (for its size) maxPixels: number?, maxVertices: number?, + lit: buffer?, -- Quake 1 coloured light (.lit: "QLIT", version 1, RGB per luxel) + lightmaps: boolean?, -- default true } type Tex = { name: string, width: number, height: number, image: Types.Image?, texels: boolean } -type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number } } +type Batch = { tex: number, pos: { number }, nrm: { number }, uv: { number }, lm: { number } } -- lm: face, s, t per vertex local function cstr(b: buffer, at: number, n: number): string return (string.match(buffer.readstring(b, at, n), "^[^%z]*")) :: string @@ -36,34 +41,18 @@ local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer if n < 0 or n > 65536 or 4 + n * 4 > l.size then return nil, "bad miptex lump" end - local gpal = if pal then Pixels.palette(pal, 0, 256) else nil + local gpal = if pal and not hl then Pixels.palette(pal, 0, 256) else nil for i = 0, n - 1 do local o = readi32(b, at + 4 + i * 4) - if o < 0 or o + 40 > l.size then + local hd = if o >= 0 and o + 40 <= l.size then Miptex.header(b, at + o, l.size - o) else nil + if not hd then out[i + 1] = { name = "missing" .. i, width = 64, height = 64, image = nil, texels = false } else - local m = at + o - local name = cstr(b, m, 16) - local w, h, off0 = readu32(b, m + 16), readu32(b, m + 20), readu32(b, m + 24) - local t: Tex = { name = name, width = math.max(w, 1), height = math.max(h, 1), image = nil, texels = false } - if off0 ~= 0 and w > 0 and h > 0 and w * h <= maxPixels then - local px = m + off0 - local need = w * h - local palAt = m + readu32(b, m + 36) + (w // 8) * (h // 8) + 2 - if o + off0 + need <= l.size then - local p = gpal - if hl then - p = if palAt - at + 768 <= l.size then Pixels.palette(b, palAt, 256) else nil - end - local img = Types.Image.new(w, h) - if p then - Pixels.indexed(b, px, w, 8, img.pixels, w, h, true, p) - else - for k = 0, need - 1 do - writeu32(img.pixels, k * 4, 0xFF000000 + buffer.readu8(b, px + k) * 0x10101) - end - end - img.meta.source = { format = "bsp", miptex = name, palette = p ~= nil } + local t: Tex = { name = hd.name, width = math.max(hd.width, 1), height = math.max(hd.height, 1), image = nil, texels = false } + if hd.offsets[1] ~= 0 and hd.width * hd.height <= maxPixels then + local img = Miptex.decode(b, at + o, l.size - o, { palette = gpal, goldsrc = hl, keyed = false, maxPixels = maxPixels }) + if img then + img.meta.source = { format = "bsp", miptex = hd.name, palette = img.meta.source and img.meta.source.palette } t.image = img end end @@ -73,11 +62,14 @@ local function miptex(b: buffer, base: number, l: Lump, hl: boolean, pal: buffer return out, nil end -function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?) +function Quake.decode(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, opts: Options?): (Types.Scene?, string?) local q2 = variant == "q2" + local big = variant == "bsp2" or variant == "2psb" local maxPixels = opts and opts.maxPixels or 2 ^ 24 local V, E, SE, Fc, TI, P, M = lumps.vertices, lumps.edges, lumps.surfedges, lumps.faces, lumps.texinfo, lumps.planes, lumps.models - local nV, nE, nSE, nF = V.size // 12, E.size // 4, SE.size // 4, Fc.size // 20 + local fSize: number = if big then 28 else 20 + local eSize: number = if big then 8 else 4 + local nV, nE, nSE, nF = V.size // 12, E.size // eSize, SE.size // 4, Fc.size // fSize local tiSize = if q2 then 76 else 40 local nTI, nP = TI.size // tiSize, P.size // 20 local mSize = if q2 then 48 else 64 @@ -140,11 +132,28 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian local batches: { [number]: { [number]: Batch } } = {} local orders: { [number]: { number } } = {} local skipped = 0 + -- lightmaps: record 1 = a white luxel (sky / liquids), 2 = black (unlit faces), then one per lit face + local LT = lumps.lighting + local useLight = LT.size > 0 and not (opts and opts.lightmaps == false) + local rgb = variant == "hl" or q2 + local lit = opts and opts.lit + if lit and (buffer.len(lit) < 8 or buffer.readstring(lit, 0, 4) ~= "QLIT" or buffer.readi32(lit, 4) ~= 1) then + lit = nil + end + local lmSizes: { { number } } = { { 1, 1 }, { 1, 1 } } + local lmFaces: { { face: number, ofs: number, smin: number, tmin: number, styles: number } } = { { face = -1, ofs = -1, smin = 0, tmin = 0, styles = 0 }, { face = -1, ofs = -1, smin = 0, tmin = 0, styles = 0 } } + local lumaTotal = 0 for f = 0, nF - 1 do - local fo = base + Fc.at + f * 20 - local plane, side, firstEdge, numEdges, texinfo = readu16(b, fo), readu16(b, fo + 2), readi32(b, fo + 4), readu16(b, fo + 8), readu16(b, fo + 10) + local fo = base + Fc.at + f * fSize + local plane = if big then readi32(b, fo) else readu16(b, fo) + local side = if big then readi32(b, fo + 4) else readu16(b, fo + 2) + local firstEdge = if big then readi32(b, fo + 8) else readi32(b, fo + 4) + local numEdges = if big then readi32(b, fo + 12) else readu16(b, fo + 8) + local texinfo = if big then readi32(b, fo + 16) else readu16(b, fo + 10) + local styles = if big then fo + 20 else fo + 12 + local lightofs = if big then readi32(b, fo + 24) else readi32(b, fo + 16) local model = faceModel[f + 1] - if not model or numEdges < 3 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then + if not model or numEdges < 3 or plane < 0 or texinfo < 0 or firstEdge < 0 or firstEdge + numEdges > nSE or plane >= nP or texinfo >= nTI then skipped += 1 continue end @@ -157,7 +166,13 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian ok = false break end - local v = if se >= 0 then readu16(b, base + E.at + e * 4) else readu16(b, base + E.at + e * 4 + 2) + local eo = base + E.at + e * eSize + local v + if big then + v = if se >= 0 then readu32(b, eo) else readu32(b, eo + 4) + else + v = if se >= 0 then readu16(b, eo) else readu16(b, eo + 2) + end if v >= nV then ok = false break @@ -201,6 +216,37 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian local tio = base + TI.at + texinfo * tiSize local sx, sy, sz, so = readf32(b, tio), readf32(b, tio + 4), readf32(b, tio + 8), readf32(b, tio + 12) local tx, ty, tz, to = readf32(b, tio + 16), readf32(b, tio + 20), readf32(b, tio + 24), readf32(b, tio + 28) + local rec = 2 + if useLight then + local tflags = readi32(b, tio + (if q2 then 32 else 36)) + local special = if q2 then bit32.band(tflags, 0x8C) ~= 0 else bit32.band(tflags, 1) ~= 0 + if special then + rec = 1 + elseif lightofs >= 0 then + local smin: number, smax: number, tmin: number, tmax: number = math.huge, -math.huge, math.huge, -math.huge + for k = 0, n - 1 do + local x, y, z = poly[k * 3 + 1], poly[k * 3 + 2], poly[k * 3 + 3] + local sv, tv = x * sx + y * sy + z * sz + so, x * tx + y * ty + z * tz + to + smin, smax = math.min(smin, sv), math.max(smax, sv) + tmin, tmax = math.min(tmin, tv), math.max(tmax, tv) + end + local bs, bt0 = math.floor(smin / 16), math.floor(tmin / 16) + local lw, lh = math.ceil((smax :: number) / 16) - bs + 1, math.ceil((tmax :: number) / 16) - bt0 + 1 + local ns = 0 + for k = 0, 3 do + if readu8(b, styles + k) ~= 255 then + ns += 1 + end + end + local bytes = lw * lh * (if rgb then 3 else 1) + lumaTotal += lw * lh + if ns > 0 and lw > 0 and lh > 0 and lw <= 256 and lh <= 256 and lightofs + bytes <= LT.size and lumaTotal <= maxPixels then + table.insert(lmSizes, { lw, lh }) + table.insert(lmFaces, { face = f, ofs = lightofs, smin = bs * 16, tmin = bt0 * 16, styles = ns }) + rec = #lmFaces + end + end + end local ti = texOf[texinfo + 1] or 0 local tex = texs[ti] local w, h = if tex then tex.width else 1, if tex then tex.height else 1 @@ -208,7 +254,7 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian batches[model] = bm local bt = bm[ti] if not bt then - bt = { tex = ti, pos = {}, nrm = {}, uv = {} } + bt = { tex = ti, pos = {}, nrm = {}, uv = {}, lm = {} } bm[ti] = bt local ol = orders[model] or {} orders[model] = ol @@ -221,21 +267,69 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian local pp, nn, uu = batch.pos, batch.nrm, batch.uv pp[#pp + 1], pp[#pp + 2], pp[#pp + 3] = x, y, z nn[#nn + 1], nn[#nn + 2], nn[#nn + 3] = nx, ny, nz - uu[#uu + 1] = (x * sx + y * sy + z * sz + so) / w - uu[#uu + 1] = (x * tx + y * ty + z * tz + to) / h + local sv, tv = x * sx + y * sy + z * sz + so, x * tx + y * ty + z * tz + to + uu[#uu + 1] = sv / w + uu[#uu + 1] = tv / h + local ll = batch.lm + ll[#ll + 1], ll[#ll + 2], ll[#ll + 3] = rec, sv, tv end end end + local atlasW, atlasH, rects = 0, 0, nil :: { Lightmap.Rect }? + local lmTex: number? = nil + local atlas: Types.Image? = nil + if useLight and #lmFaces > 2 then + local W, H, rs, err = Lightmap.pack(lmSizes, maxPixels) + if not rs then + return nil, err + end + atlasW, atlasH, rects = W, H, rs + local img = Types.Image.new(W, H) + local px = img.pixels + local la = base + LT.at + buffer.writeu32(px, (rs[1].y * W + rs[1].x) * 4, 0xFFFFFFFF) + buffer.writeu32(px, (rs[2].y * W + rs[2].x) * 4, 0xFF000000) + local placed = {} + for i = 3, #lmFaces do + local lf, r = lmFaces[i], rs[i] + for yy = 0, r.h - 1 do + for xx = 0, r.w - 1 do + local k = yy * r.w + xx + local cr: number, cg: number, cb: number = 0, 0, 0 + if rgb then + local o = la + lf.ofs + k * 3 + cr, cg, cb = readu8(b, o), readu8(b, o + 1), readu8(b, o + 2) + elseif lit and 8 + (lf.ofs + k) * 3 + 3 <= buffer.len(lit) then + local o = 8 + (lf.ofs + k) * 3 + cr, cg, cb = readu8(lit, o), readu8(lit, o + 1), readu8(lit, o + 2) + else + local v = readu8(b, la + lf.ofs + k) + cr, cg, cb = v, v, v + end + writeu32(px, ((r.y + yy) * W + r.x + xx) * 4, 0xFF000000 + (cb :: number) * 65536 + (cg :: number) * 256 + (cr :: number)) + end + end + table.insert(placed, { face = lf.face, x = r.x, y = r.y, w = r.w, h = r.h, styles = lf.styles }) + end + for i = 1, #lmFaces do + Lightmap.border(px, W, rs[i]) + end + img.meta.source = { format = "bsp", lightmap = "atlas", coloured = rgb or lit ~= nil } + atlas = img + scene.meta.lightmaps = placed + lmTex = #texs + 1 + end for i, t in texs do local tex: Types.Texture = { name = t.name, image = t.image, uri = if t.image then nil else (if q2 then "textures/" .. t.name .. ".wal" else t.name) } table.insert(scene.textures, tex) local mat = Scene.material(t.name) mat.metallic = 0 - local extras: any = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } - mat.extras = extras - mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height } } :: any + mat.extras = { bsp = { texels = if t.texels then true else nil, width = t.width, height = t.height, lightmap = lmTex, lightmapTexCoord = if lmTex then 1 else nil } } :: any table.insert(scene.materials, mat) end + if atlas then + table.insert(scene.textures, { name = "lightmap", image = atlas }) + end local root: Types.Node = { name = "bsp", children = {} } table.insert(scene.nodes, root) scene.roots[1] = 1 @@ -257,8 +351,23 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian for k = 0, nv - 1 do writeu32(ib, k * 4, k) end + local attrs: { [string]: Types.Accessor } = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) } + if rects then + local lb = buffer.create(nv * 8) + for k = 0, nv - 1 do + local rec, sv, tv = bt.lm[k * 3 + 1], bt.lm[k * 3 + 2], bt.lm[k * 3 + 3] + local r, lf = rects[rec], lmFaces[rec] + local lu, lv = r.x + 0.5, r.y + 0.5 + if rec > 2 then + lu, lv = r.x + (sv - lf.smin) / 16 + 0.5, r.y + (tv - lf.tmin) / 16 + 0.5 + end + writef32(lb, k * 8, lu / atlasW) + writef32(lb, k * 8 + 4, lv / atlasH) + end + attrs.TEXCOORD_1 = Scene.accessor(lb, "f32", 2, nv) + end table.insert(mesh.primitives, { - attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }, + attributes = attrs, indices = Scene.accessor(ib, "u32", 1, nv), mode = "triangles" :: any, material = if ti > 0 then ti else nil, @@ -273,4 +382,4 @@ function Brush.decode(b: buffer, base: number, lumps: { [string]: Lump }, varian return scene, nil end -return Brush +return Quake diff --git a/src/Rosetta/model/bsp/Quake3.luau b/src/Rosetta/model/bsp/Quake3.luau index de8c1a4..0c149b8 100644 --- a/src/Rosetta/model/bsp/Quake3.luau +++ b/src/Rosetta/model/bsp/Quake3.luau @@ -1,7 +1,9 @@ --!strict -- model/bsp/Quake3: Quake III Arena maps (IBSP 46; RTCW 47 has the same layout) -> Scene, from the Unofficial Quake 3 --- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped. +-- Map Specs (Kekoa Proudfoot; no code taken). Lightmaps are 128 x 128 RGB; billboards (flares) are skipped; patches +-- through codecs/model/Patch. local Types = require("@rosetta/Types") +local Patch = require("@rosetta/codecs/model/Patch") local Quake3 = {} @@ -81,52 +83,23 @@ function Quake3.decode(b: buffer, base: number, lumps: { [string]: Lump }, opts: counts[if kind == 1 then "polygons" else "meshes"] += 1 elseif kind == 2 and first >= 0 and n >= 0 and first + n <= nV then local w, h = readi32(b, o + 96), readi32(b, o + 100) - if w >= 3 and h >= 3 and w % 2 == 1 and h % 2 == 1 and w * h == n then + if Patch.valid(w, h, n) then counts.patches += 1 - local L = level - for py = 0, (h - 1) // 2 - 1 do - for px = 0, (w - 1) // 2 - 1 do - local ctrl: { { number } } = {} - for j = 0, 2 do - for i = 0, 2 do - ctrl[j * 3 + i + 1] = vertex(first + (py * 2 + j) * w + px * 2 + i) - end - end - local grid: { number } = {} - for gy = 0, L do - local tv = gy / L - for gx = 0, L do - local tu = gx / L - local bu = { (1 - tu) ^ 2, 2 * tu * (1 - tu), tu * tu } - local bv = { (1 - tv) ^ 2, 2 * tv * (1 - tv), tv * tv } - local v = table.create(14, 0) - for j = 0, 2 do - for i = 0, 2 do - local wgt = bu[i + 1] * bv[j + 1] - local cp = ctrl[j * 3 + i + 1] - for k = 1, 14 do - v[k] += cp[k] * wgt - end - end - end - local l = math.sqrt(v[8] ^ 2 + v[9] ^ 2 + v[10] ^ 2) - if l > 0 then - v[8], v[9], v[10] = v[8] / l, v[9] / l, v[10] / l - end - grid[gy * (L + 1) + gx + 1] = addExtra(v) - end - end - for gy = 0, L - 1 do - for gx = 0, L - 1 do - local a, c2 = grid[gy * (L + 1) + gx + 1], grid[gy * (L + 1) + gx + 2] - local d, e = grid[(gy + 1) * (L + 1) + gx + 1], grid[(gy + 1) * (L + 1) + gx + 2] - -- Quake's control grids are clockwise-front - for _, v in { a, d, c2, c2, d, e } do - table.insert(tris, v) - end - end - end - end + local ctrl = table.create(n * 14, 0) :: { number } + for k = 0, n - 1 do + table.move(vertex(first + k), 1, 14, k * 14 + 1, ctrl) + end + local pts, gw, gh = Patch.grid(ctrl, w, h, 14, level, level, maxV) + if not pts then + return nil, "limit: too many patch vertices" + end + Patch.normalize(pts, 14, 7) + local ids = table.create(gw * gh) :: { number } + for k = 0, gw * gh - 1 do + ids[k + 1] = addExtra(table.move(pts, k * 14 + 1, k * 14 + 14, 1, table.create(14, 0)) :: { number }) + end + for _, v in Patch.triangles(gw, gh) do + table.insert(tris, ids[v + 1]) end else counts.skipped += 1 diff --git a/src/Rosetta/model/bsp/Tree.luau b/src/Rosetta/model/bsp/Tree.luau new file mode 100644 index 0000000..2a91955 --- /dev/null +++ b/src/Rosetta/model/bsp/Tree.luau @@ -0,0 +1,386 @@ +--!strict +-- model/bsp/Tree: the BSP tree, collision hulls and visibility of Quake 1 / BSP2 / 2PSB / Half-Life / Quake II / Quake +-- III maps as tables (bspfile.h layouts; Unofficial Quake 3 Map Specs), plus point queries: the leaf and contents at a +-- point (Quake 1 hulls 0..3 through nodes / clipnodes as SV_HullPointContents; Quake II leaf contents; Quake III the +-- contents of the leaf's brushes) and the potentially visible set of a leaf (run-length zero bytes, as Mod_DecompressVis). +local Tree = {} + +local readi32, readu16, readi16, readf32, readu8, readu32 = buffer.readi32, buffer.readu16, buffer.readi16, buffer.readf32, buffer.readu8, buffer.readu32 + +export type Lump = { at: number, size: number } +export type Plane = { normal: { number }, dist: number, type: number? } +export type Node = { plane: number, children: { number }, mins: { number }, maxs: { number }, firstFace: number?, numFaces: number? } -- children: >= 0 node, < 0 leaf -(child + 1) +export type Leaf = { + contents: number?, + cluster: number?, + area: number?, + visofs: number?, + mins: { number }, + maxs: { number }, + firstFace: number?, + numFaces: number?, + firstBrush: number?, + numBrushes: number?, + ambient: { number }?, +} +export type ClipNode = { plane: number, children: { number } } -- children: >= 0 clipnode, < 0 contents +export type Model = { mins: { number }, maxs: { number }, origin: { number }?, headnodes: { number }, visleafs: number?, firstFace: number, numFaces: number } +export type Brush = { firstSide: number, numSides: number, contents: number } +export type Side = { plane: number, texinfo: number } +export type Data = { + variant: string, + planes: { Plane }, + nodes: { Node }, + leaves: { Leaf }, + clipnodes: { ClipNode }?, + models: { Model }, + brushes: { Brush }?, + brushSides: { Side }?, + leafBrushes: { number }?, + leafFaces: { number }?, + visibility: buffer?, -- the raw lump + numClusters: number?, + clusterBytes: number?, -- Quake III bytes per cluster vector +} + +local function v3(b: buffer, o: number, kind: string): { number } + if kind == "f" then + return { readf32(b, o), readf32(b, o + 4), readf32(b, o + 8) } + elseif kind == "i" then + return { readi32(b, o), readi32(b, o + 4), readi32(b, o + 8) } + end + return { readi16(b, o), readi16(b, o + 2), readi16(b, o + 4) } +end + +local function slice(b: buffer, base: number, l: Lump): buffer? + if l.size <= 0 then + return nil + end + local out = buffer.create(l.size) + buffer.copy(out, 0, b, base + l.at, l.size) + return out +end + +-- nil, message past maxItems +function Tree.read(b: buffer, base: number, lumps: { [string]: Lump }, variant: string, maxItems: number?): (Data?, string?) + local limit = maxItems or 2 ^ 22 + local q2, q3 = variant == "q2", variant == "q3" + local bsp2, rmq = variant == "bsp2", variant == "2psb" + local d: Data = { variant = variant, planes = {}, nodes = {}, leaves = {}, models = {} } + local function count(l: Lump?, size: number): number + return if l then l.size // size else 0 + end + local P = lumps.planes + local pSize = if q3 then 16 else 20 + local np = count(P, pSize) + if np > limit then + return nil, "limit: too many planes" + end + for i = 0, np - 1 do + local o = base + P.at + i * pSize + d.planes[i + 1] = { normal = v3(b, o, "f"), dist = readf32(b, o + 12), type = if q3 then nil else readi32(b, o + 16) } + end + local N = lumps.nodes + local nSize = if q3 then 36 elseif q2 then 28 elseif bsp2 then 44 elseif rmq then 32 else 24 + local nn = count(N, nSize) + if nn > limit then + return nil, "limit: too many nodes" + end + for i = 0, nn - 1 do + local o = base + N.at + i * nSize + local node: any + if q3 or q2 or bsp2 or rmq then + local bk = if q3 then "i" elseif bsp2 then "f" else "s" + local bs = if bk == "s" then 6 else 12 + node = { plane = readi32(b, o), children = { readi32(b, o + 4), readi32(b, o + 8) }, mins = v3(b, o + 12, bk), maxs = v3(b, o + 12 + bs, bk) } + if not q3 then + local fo = o + 12 + bs * 2 + if q2 then + node.firstFace, node.numFaces = readu16(b, fo), readu16(b, fo + 2) + else + node.firstFace, node.numFaces = readu32(b, fo), readu32(b, fo + 4) + end + end + else + local c = {} + for k = 0, 1 do + local p = readu16(b, o + 4 + k * 2) + c[k + 1] = if p < nn then p else -(65535 - p) - 1 -- Quakespasm Mod_LoadNodes_S: leaf 65535 - p + end + node = { plane = readi32(b, o), children = c, mins = v3(b, o + 8, "s"), maxs = v3(b, o + 14, "s"), firstFace = readu16(b, o + 20), numFaces = readu16(b, o + 22) } + end + d.nodes[i + 1] = node + end + local L = lumps.leaves or lumps.leafs + local lSize = if q3 then 48 elseif q2 then 28 elseif bsp2 then 44 elseif rmq then 32 else 28 + local nl = count(L, lSize) + if nl > limit then + return nil, "limit: too many leaves" + end + for i = 0, nl - 1 do + local o = base + L.at + i * lSize + local leaf: any + if q3 then + leaf = { cluster = readi32(b, o), area = readi32(b, o + 4), mins = v3(b, o + 8, "i"), maxs = v3(b, o + 20, "i"), + firstFace = readi32(b, o + 32), numFaces = readi32(b, o + 36), firstBrush = readi32(b, o + 40), numBrushes = readi32(b, o + 44) } + elseif q2 then + leaf = { contents = readi32(b, o), cluster = readi16(b, o + 4), area = readi16(b, o + 6), mins = v3(b, o + 8, "s"), maxs = v3(b, o + 14, "s"), + firstFace = readu16(b, o + 20), numFaces = readu16(b, o + 22), firstBrush = readu16(b, o + 24), numBrushes = readu16(b, o + 26) } + else + local bk = if bsp2 then "f" else "s" + local bs = if bsp2 then 12 else 6 + local fo = o + 8 + bs * 2 + local big = bsp2 or rmq + leaf = { contents = readi32(b, o), visofs = readi32(b, o + 4), mins = v3(b, o + 8, bk), maxs = v3(b, o + 8 + bs, bk), + firstFace = if big then readu32(b, fo) else readu16(b, fo), numFaces = if big then readu32(b, fo + 4) else readu16(b, fo + 2) } + local ao = fo + (if big then 8 else 4) + leaf.ambient = { readu8(b, ao), readu8(b, ao + 1), readu8(b, ao + 2), readu8(b, ao + 3) } + end + d.leaves[i + 1] = leaf + end + if not q2 and not q3 then + local C = lumps.clipnodes + local cSize = if bsp2 or rmq then 12 else 8 + local nc = count(C, cSize) + if nc > limit then + return nil, "limit: too many clipnodes" + end + local cl: { ClipNode } = {} + for i = 0, nc - 1 do + local o = base + C.at + i * cSize + local c + if cSize == 12 then + c = { readi32(b, o + 4), readi32(b, o + 8) } + else + c = {} + for k = 0, 1 do + local p = readu16(b, o + 4 + k * 2) + c[k + 1] = if p > nc then p - 65536 else p -- Quakespasm Mod_LoadClipnodes + end + end + cl[i + 1] = { plane = readi32(b, o), children = c } + end + d.clipnodes = cl + end + local M = lumps.models + local mSize = if q3 then 40 elseif q2 then 48 else 64 + for i = 0, count(M, mSize) - 1 do + local o = base + M.at + i * mSize + local m: any + if q3 then + m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), headnodes = { 0 }, firstFace = readi32(b, o + 24), numFaces = readi32(b, o + 28) } + elseif q2 then + m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), origin = v3(b, o + 24, "f"), headnodes = { readi32(b, o + 36) }, firstFace = readi32(b, o + 40), numFaces = readi32(b, o + 44) } + else + m = { mins = v3(b, o, "f"), maxs = v3(b, o + 12, "f"), origin = v3(b, o + 24, "f"), + headnodes = { readi32(b, o + 36), readi32(b, o + 40), readi32(b, o + 44), readi32(b, o + 48) }, + visleafs = readi32(b, o + 52), firstFace = readi32(b, o + 56), numFaces = readi32(b, o + 60) } + end + d.models[i + 1] = m + end + if q2 or q3 then + local B, S = lumps.brushes, lumps.brushsides + local nb, ns = count(B, 12), count(S, if q3 then 8 else 4) + if nb > limit or ns > limit then + return nil, "limit: too many brushes" + end + local brushes: { Brush }, sides: { Side } = {}, {} + for i = 0, nb - 1 do + local o = base + B.at + i * 12 + brushes[i + 1] = { firstSide = readi32(b, o), numSides = readi32(b, o + 4), contents = readi32(b, o + 8) } -- Quake III: a texture index + end + for i = 0, ns - 1 do + if q3 then + local o = base + S.at + i * 8 + sides[i + 1] = { plane = readi32(b, o), texinfo = readi32(b, o + 4) } + else + local o = base + S.at + i * 4 + sides[i + 1] = { plane = readu16(b, o), texinfo = readi16(b, o + 2) } + end + end + d.brushes, d.brushSides = brushes, sides + local LB = lumps.leafbrushes + local lbs: { number } = {} + for i = 0, count(LB, if q3 then 4 else 2) - 1 do + lbs[i + 1] = if q3 then readi32(b, base + LB.at + i * 4) else readu16(b, base + LB.at + i * 2) + end + d.leafBrushes = lbs + if q3 then + -- brush contents come from the texture's contents flags + local T = lumps.textures + local nt = count(T, 72) + for _, br in brushes do + local t = br.contents + br.contents = if t >= 0 and t < nt then readi32(b, base + T.at + t * 72 + 68) else 0 + end + end + end + local VL = lumps.visibility or lumps.visdata + d.visibility = if VL then slice(b, base, VL) else nil + local vis = d.visibility + if vis and q2 and buffer.len(vis) >= 4 then + d.numClusters = readi32(vis, 0) + elseif vis and q3 and buffer.len(vis) >= 8 then + d.numClusters, d.clusterBytes = readi32(vis, 0), readi32(vis, 4) + end + return d, nil +end + +local function side(d: Data, plane: number, x: number, y: number, z: number): number + local p = d.planes[plane + 1] + if not p then + return 0 + end + local n = p.normal + return x * n[1] + y * n[2] + z * n[3] - p.dist +end + +-- the leaf (0-based) at a point, walking the tree of model (0-based, default 0) +function Tree.leafAt(d: Data, x: number, y: number, z: number, model: number?): number? + local m = d.models[(model or 0) + 1] + local node = if m then m.headnodes[1] else 0 + for _ = 1, #d.nodes + 1 do + if node < 0 then + return -node - 1 + end + local nd = d.nodes[node + 1] + if not nd then + return nil + end + node = if side(d, nd.plane, x, y, z) >= 0 then nd.children[1] else nd.children[2] + end + return nil +end + +-- Quake 1: CONTENTS_* (-1 empty, -2 solid, -3 water, -4 slime, -5 lava, -6 sky) in hull 0..3; Quake II: the leaf's +-- CONTENTS_* bits; Quake III: the contents bits of the brushes holding the point +function Tree.contents(d: Data, x: number, y: number, z: number, hull: number?, model: number?): number? + local h = hull or 0 + if (d.variant == "q1" or d.variant == "hl" or d.variant == "bsp2" or d.variant == "2psb") and h > 0 then + local m = d.models[(model or 0) + 1] + local cl = d.clipnodes or {} + local node = if m then m.headnodes[h + 1] or -1 else -1 + for _ = 1, #cl + 1 do + if node < 0 then + return node + end + local c = cl[node + 1] + if not c then + return nil + end + node = if side(d, c.plane, x, y, z) >= 0 then c.children[1] else c.children[2] + end + return nil + end + local leaf = Tree.leafAt(d, x, y, z, model) + local lf = leaf and d.leaves[leaf + 1] + if not lf then + return nil + end + if d.variant ~= "q3" then + return lf.contents + end + local out = 0 + local lbs: { number }, brushes: { Brush }, sides: { Side } = d.leafBrushes or {}, d.brushes or {}, d.brushSides or {} + local fb: number, nb: number = lf.firstBrush or 0, lf.numBrushes or 0 + for k = fb, fb + nb - 1 do + local br = brushes[(lbs[k + 1] or -1) + 1] + if br then + local inside = true + for s = br.firstSide, br.firstSide + br.numSides - 1 do + local sd = sides[s + 1] + if not sd or side(d, sd.plane, x, y, z) > 0 then + inside = false + break + end + end + if inside then + out = bit32.bor(out, br.contents) + end + end + end + return out +end + +local function decompress(vis: buffer, at: number, bytes: number, out: { boolean }) + local n = buffer.len(vis) + local i = 0 + while i < bytes and at < n do + local c = readu8(vis, at) + if c ~= 0 then + for bit = 0, 7 do + if bit32.band(c, bit32.lshift(1, bit)) ~= 0 then + out[i * 8 + bit + 1] = true + end + end + i += 1 + at += 1 + else + if at + 1 >= n then + break + end + i += readu8(vis, at + 1) + at += 2 + end + end +end + +-- the leaves (0-based, sorted) potentially visible from a leaf; nil without visibility data (everything visible) +function Tree.pvs(d: Data, leaf: number): { number }? + local lf = d.leaves[leaf + 1] + local vis = d.visibility + if not lf or not vis then + return nil + end + local out: { number } = {} + if d.variant == "q2" or d.variant == "q3" then + local nc = d.numClusters or 0 + local c = lf.cluster or -1 + if c < 0 or c >= nc then + return out + end + local bits: { boolean } = {} + if d.variant == "q2" then + if 4 + nc * 8 > buffer.len(vis) then + return nil + end + decompress(vis, readi32(vis, 4 + c * 8), (nc + 7) // 8, bits) + else + local sz = d.clusterBytes or 0 + local o = 8 + c * sz + for k = 0, sz - 1 do + if o + k < buffer.len(vis) then + local v = readu8(vis, o + k) + for bit = 0, 7 do + if bit32.band(v, bit32.lshift(1, bit)) ~= 0 then + bits[k * 8 + bit + 1] = true + end + end + end + end + end + for i, l in d.leaves do + local cl = l.cluster or -1 + if cl >= 0 and bits[cl + 1] then + table.insert(out, i - 1) + end + end + return out + end + -- Quake 1: bit k = leaf k + 1 (leaf 0 is the shared solid leaf), visleafs bits + local visofs = lf.visofs or -1 + if leaf == 0 or visofs < 0 then + return out + end + local n = d.models[1] and d.models[1].visleafs or (#d.leaves - 1) + local bits: { boolean } = {} + decompress(vis, visofs, (n + 7) // 8, bits) + for k = 0, n - 1 do + if bits[k + 1] then + table.insert(out, k + 1) + end + end + return out +end + +return Tree diff --git a/src/Rosetta/model/bsp/init.luau b/src/Rosetta/model/bsp/init.luau index 02ae8d9..40e568a 100644 --- a/src/Rosetta/model/bsp/init.luau +++ b/src/Rosetta/model/bsp/init.luau @@ -1,15 +1,18 @@ --!strict --- model/bsp: compiled game maps, read: Quake 1 (BSP 29), Half-Life (BSP 30), Quake II (IBSP 38), Quake III / RTCW --- (IBSP 46 / 47). Quake textures need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up. --- Not supported: Source engine VBSP, Quake 1/2 lightmaps, visibility and collision data, writing. +-- model/bsp: compiled game maps, read: Quake 1 (BSP 29, BSP2, 2PSB), Half-Life (BSP 30), Quake II (IBSP 38), Quake III +-- / RTCW (IBSP 46 / 47). Lightmaps (Quake 1 / 2 / Half-Life: one atlas, Quake III: its pages) as TEXCOORD_1; the tree, +-- collision hulls / brushes and visibility in meta.bsp with point queries (Bsp.leafAt / contents / pvs). Quake textures +-- need the game's palette (gfx/palette.lmp, not redistributable). Map units, z up. Not supported: Source engine VBSP, +-- light styles other than the first, BSPX lumps, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Input = require("@rosetta/core/Input") local Types = require("@rosetta/Types") -local Brush = require("@rosetta/model/bsp/Brush") +local Quake = require("@rosetta/model/bsp/Quake") local Quake3 = require("@rosetta/model/bsp/Quake3") +local Tree = require("@rosetta/model/bsp/Tree") -- ------------------------------------------------------------------------------------------------ contract local Bsp = { @@ -17,8 +20,8 @@ local Bsp = { category = "model", extensions = { "bsp" }, mime = { "model/x-bsp" }, - deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels" }, - caps = { decode = true, encode = false, variants = { "quake", "halflife", "quake2", "quake3" }, lightmaps = "quake3" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Pixels", "codecs/image/Miptex", "codecs/model/Patch" }, + caps = { decode = true, encode = false, variants = { "quake", "bsp2", "2psb", "halflife", "quake2", "quake3" }, lightmaps = true, collision = true, visibility = true }, } -- ------------------------------------------------------------------------------------------------ types @@ -27,6 +30,10 @@ export type DecodeOptions = { resolve: ((uri: string) -> (buffer | string)?)?, files: { [string]: buffer | string }?, patchLevel: number?, -- default 4 + lit: (buffer | string)?, -- Quake 1: the map's .lit file (coloured light); also found as ".lit" through files / resolve + lightmaps: boolean?, -- default true + tree: boolean?, -- meta.bsp (tree, hulls, visibility), default true + name: string?, -- the file name (finds the .lit) maxPixels: number?, -- default 2^24 maxVertices: number?, -- default 2^24 } @@ -46,6 +53,9 @@ function Bsp.sniff(r: Bytes.Reader): number end local m = r:peek(4) local v = buffer.readi32(r.buf, r.pos + (if m == "IBSP" then 4 else 0)) + if m == "BSP2" or m == "2PSB" then + v = 29 + end if m == "IBSP" then return if v == 38 or v == 46 or v == 47 then 1 else 0.3 end @@ -88,6 +98,8 @@ function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E names, dir, variant = Q2_LUMPS, 8, "q2" elseif m == "IBSP" and (version == 46 or version == 47) then names, dir, variant = Q3_LUMPS, 8, "q3" + elseif m == "BSP2" or m == "2PSB" then + names, dir, variant = Q1_LUMPS, 4, string.lower(m) elseif m ~= "IBSP" and (version == 29 or version == 30) then names, dir, variant = Q1_LUMPS, 4, if version == 30 then "hl" else "q1" elseif m == "VBSP" then @@ -114,13 +126,15 @@ function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E if pal and buffer.len(pal) < 768 then pal = nil end - scene, msg = Brush.decode(b, base, lumps, variant, { + scene, msg = Quake.decode(b, base, lumps, variant, { palette = pal, wal = function(name: string): buffer? return Input.sibling(opts, "textures/" .. name .. ".wal") end, maxPixels = opts and opts.maxPixels, maxVertices = opts and opts.maxVertices, + lit = if opts and opts.lit then Bytes.toBuffer(opts.lit) else (if opts and opts.name then Input.sibling(opts, (string.gsub(opts.name :: string, "%.[^./\\]*$", "")) .. ".lit") else nil), + lightmaps = opts and opts.lightmaps, }) end if not scene then @@ -132,12 +146,44 @@ function Bsp.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.E scene.meta.entities = entities(text) scene.meta.source = { format = "bsp", - variant = ({ q1 = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant], + variant = ({ q1 = "quake", bsp2 = "quake", ["2psb"] = "quake", hl = "halflife", q2 = "quake2", q3 = "quake3" } :: { [string]: string })[variant], + layout = if variant == "bsp2" then "BSP2" elseif variant == "2psb" then "2PSB" else nil, version = version, entities = text, - palette = if variant == "q1" then (opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) else nil, + palette = if variant == "q1" or variant == "bsp2" or variant == "2psb" then (opts ~= nil and (opts.palette ~= nil or Input.sibling(opts, "gfx/palette.lmp") ~= nil)) else nil, } + if not (opts and opts.tree == false) then + local tree, terr = Tree.read(b, base, lumps, variant) + if not tree then + return nil, Err.from(terr) + end + scene.meta.bsp = tree + end return scene, nil end +-- ------------------------------------------------------------------------------------------------ extras +local function tree(scene: any): Tree.Data? + return type(scene) == "table" and type(scene.meta) == "table" and scene.meta.bsp or nil +end + +-- the leaf (0-based) at a point, in the tree of a model (0 = the world) +function Bsp.leafAt(scene: Types.Scene, x: number, y: number, z: number, model: number?): number? + local d = tree(scene) + return if d then Tree.leafAt(d, x, y, z, model) else nil +end + +-- the contents at a point: Quake 1 CONTENTS_* (-1 empty, -2 solid, ...; hull 0 point, 1 player, 2 shambler, 3 crouch +-- in Half-Life), Quake II / III contents bits +function Bsp.contents(scene: Types.Scene, x: number, y: number, z: number, hull: number?, model: number?): number? + local d = tree(scene) + return if d then Tree.contents(d, x, y, z, hull, model) else nil +end + +-- the leaves (0-based) potentially visible from a leaf; nil when the map has no visibility data +function Bsp.pvs(scene: Types.Scene, leaf: number): { number }? + local d = tree(scene) + return if d then Tree.pvs(d, leaf) else nil +end + return Bsp diff --git a/src/Rosetta/model/map/Build.luau b/src/Rosetta/model/map/Build.luau new file mode 100644 index 0000000..cde0d0a --- /dev/null +++ b/src/Rosetta/model/map/Build.luau @@ -0,0 +1,241 @@ +--!strict +-- model/map/Build: parsed entities -> Scene: brushes through codecs/model/Brush, patches through codecs/model/Patch, +-- a mesh per entity with brushes, a primitive per texture, entities as nodes (keys in extras), z up, map units. +local Types = require("@rosetta/Types") +local Brush = require("@rosetta/codecs/model/Brush") +local Patch = require("@rosetta/codecs/model/Patch") +local Parse = require("@rosetta/model/map/Parse") + +local Build = {} + +local Scene = Types.Scene +local writef32, writeu32 = buffer.writef32, buffer.writeu32 + +export type Options = { + variant: string, -- "quake" | "valve220" | "quake2" | "quake3" + size: (name: string) -> (number, number, boolean), -- width, height, known + hull: boolean?, + merge: boolean?, + epsilon: number?, + patchLevel: number?, + skip: { string }?, + maxPolygons: number?, +} + +function Build.face(f: Parse.Face): Brush.Face? + local p = f.points + local plane = Brush.planeFromPoints({ p[1], p[2], p[3] }, { p[4], p[5], p[6] }, { p[7], p[8], p[9] }) + if not plane then + return nil + end + local out: Brush.Face = { plane = plane, texture = f.texture } + if f.matrix then + out.bp = f.matrix + elseif f.u and f.v then + local sc = f.scale or { 1, 1 } + out.vecs = Brush.valveVecs(f.u, f.v, sc[1], sc[2]) + else + local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 } + out.vecs = Brush.quakeVecs(plane, o[1], o[2], f.rotation or 0, sc[1], sc[2]) + end + return out +end + +type Acc = { pos: { number }, nrm: { number }, uv: { number }, idx: { number } } + +local function patchPrim(b: Parse.Brush, level: number, acc: Acc): boolean + local size, pts = b.size :: { number }, b.points :: { number } + local w: number, h: number = size[1] :: number, size[2] :: number + if not Patch.valid(w, h, #pts // 5) then + return false + end + -- file order is column by column (q3map2 ParsePatch: verts[i * width + j] for column j, point i) + local ctrl = table.create(w * h * 5, 0) :: { number } + for j = 0, w - 1 do + for i = 0, h - 1 do + table.move(pts, (j * h + i) * 5 + 1, (j * h + i) * 5 + 5, (i * w + j) * 5 + 1, ctrl) + end + end + local params: { number } = b.params or {} + local explicit = b.type == "patchDef3" + local lu: number = if explicit then math.max(1, params[1] or 1) else level + local lv: number = if explicit then math.max(1, params[2] or 1) else level + local g, gw, gh = Patch.grid(ctrl, w, h, 5, lu, lv) + if not g then + return false + end + local nrm = Patch.normals(g, 5, gw, gh) + local base = #acc.pos // 3 + for k = 0, gw * gh - 1 do + local o = k * 5 + table.insert(acc.pos, g[o + 1]) + table.insert(acc.pos, g[o + 2]) + table.insert(acc.pos, g[o + 3]) + table.insert(acc.uv, g[o + 4]) + table.insert(acc.uv, g[o + 5]) + table.insert(acc.nrm, nrm[k * 3 + 1]) + table.insert(acc.nrm, nrm[k * 3 + 2]) + table.insert(acc.nrm, nrm[k * 3 + 3]) + end + for _, v in Patch.triangles(gw, gh) do + table.insert(acc.idx, base + v) + end + return true +end + +local function primitive(a: Acc): Types.Primitive + local nv, ni = #a.pos // 3, #a.idx + local pb, nb, ub, ib = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8), buffer.create(ni * 4) + for k = 1, nv * 3 do + writef32(pb, (k - 1) * 4, a.pos[k]) + writef32(nb, (k - 1) * 4, a.nrm[k]) + end + for k = 1, nv * 2 do + writef32(ub, (k - 1) * 4, a.uv[k]) + end + for k = 1, ni do + writeu32(ib, (k - 1) * 4, a.idx[k]) + end + return { + attributes = { POSITION = Scene.accessor(pb, "f32", 3, nv), NORMAL = Scene.accessor(nb, "f32", 3, nv), TEXCOORD_0 = Scene.accessor(ub, "f32", 2, nv) }, + indices = Scene.accessor(ib, "u32", 1, ni), + mode = "triangles", + } +end + +local function vec3(s: string?): { number }? + if not s then + return nil + end + local x, y, z = string.match(s, "^%s*(%S+)%s+(%S+)%s+(%S+)") + local a, b, c = tonumber(x), tonumber(y), tonumber(z) + if a and b and c then + return { a, b, c } + end + return nil +end + +function Build.scene(map: Parse.Map, o: Options): (Types.Scene?, string?) + local scene = Scene.new() + scene.meta.up = "z" + local skip: { [string]: boolean } = {} + for _, n in o.skip or {} do + skip[string.lower(n)] = true + end + local matOf: { [string]: number } = {} + local function material(name: string): number + local m = matOf[name] + if m then + return m + end + local w, h, known = o.size(name) + local uri = name + if o.variant == "quake2" then + uri = "textures/" .. name .. ".wal" + elseif o.variant == "quake3" then + uri = "textures/" .. name + end + table.insert(scene.textures, { name = name, uri = uri }) + local mat = Scene.material(name) + mat.metallic = 0 + mat.baseColorTexture = { texture = #scene.textures } + mat.extras = { map = { width = w, height = h, sizeKnown = known } } + table.insert(scene.materials, mat) + matOf[name] = #scene.materials + return #scene.materials + end + local root: Types.Node = { name = "map", children = {} } + table.insert(scene.nodes, root) + scene.roots[1] = 1 + local skipped = { faces = 0, patches = 0 } + local counts = { brushes = 0, patches = 0 } + local entities: { { [string]: string } } = {} + local polyTotal = 0 + for ei, ent in map.entities do + local keys = ent.keys + table.insert(entities, keys) + local node: Types.Node = { name = keys.targetname or keys.classname or ("entity " .. (ei - 1)), children = {}, + extras = { classname = keys.classname, keys = keys, brushes = ent.brushes, entity = ei - 1 } } + local brushes: { { Brush.Face } } = {} + local patchAcc: { [string]: Acc } = {} + local patchOrder: { string } = {} + for _, b in ent.brushes do + if b.faces then + counts.brushes += 1 + local faces: { Brush.Face } = {} + for _, f in b.faces do + local bf = Build.face(f) + if bf then + table.insert(faces, bf) + else + skipped.faces += 1 + end + end + table.insert(brushes, faces) + else + counts.patches += 1 + local tex = b.texture or "" + if not skip[string.lower(tex)] then + local acc = patchAcc[tex] + if not acc then + acc = { pos = {}, nrm = {}, uv = {}, idx = {} } + patchAcc[tex] = acc + table.insert(patchOrder, tex) + end + if not patchPrim(b, o.patchLevel or 4, acc :: Acc) then + skipped.patches += 1 + end + end + end + end + local prims: { Types.Primitive } = {} + if #brushes > 0 then + local polys, err = Brush.polygons(brushes, { hull = o.hull, merge = o.merge, epsilon = o.epsilon, maxPolygons = o.maxPolygons }) + if not polys then + return nil, err + end + polyTotal += #polys + if polyTotal > (o.maxPolygons or 2 ^ 20) then + return nil, "limit: too many polygons" + end + local kept: { Brush.Polygon } = {} + for _, p in polys do + local t = brushes[p.brush][p.face].texture or "" + if not skip[string.lower(t)] then + table.insert(kept, p) + end + end + local built = Brush.primitives(kept, brushes, function(name: string): (number, number) + local m = scene.materials[material(name)] + local e = (m.extras :: any).map + return e.width, e.height + end) + for _, bt in built do + bt.primitive.material = material(bt.texture) + table.insert(prims, bt.primitive) + end + end + for _, tex in patchOrder do + local acc = patchAcc[tex] + if #acc.idx > 0 then + local prim = primitive(acc) + prim.material = material(tex) + table.insert(prims, prim) + end + end + if #prims > 0 then + table.insert(scene.meshes, { name = node.name, primitives = prims }) + node.mesh = #scene.meshes + elseif #ent.brushes == 0 then + node.translation = vec3(keys.origin) + end + table.insert(scene.nodes, node) + table.insert(root.children, #scene.nodes) + end + scene.meta.entities = entities + scene.meta.skipped = skipped + scene.meta.counts = counts + return scene, nil +end + +return Build diff --git a/src/Rosetta/model/map/Parse.luau b/src/Rosetta/model/map/Parse.luau new file mode 100644 index 0000000..cc18e3a --- /dev/null +++ b/src/Rosetta/model/map/Parse.luau @@ -0,0 +1,383 @@ +--!strict +-- model/map/Parse: .map text -> entities (key / value pairs in order, brushes and patches as written). Grammar of the +-- Quake / Quake II / Half-Life (Valve 220) / Quake III editors (qbsp / q3map2 map parsers; no code taken). +local Types = require("@rosetta/Types") + +local Parse = {} + +export type Face = { + points: { number }, -- 3 points: x, y, z each + texture: string, + offset: { number }?, -- Quake standard: x, y offset + rotation: number?, -- standard / Valve 220 (degrees) + scale: { number }?, -- standard / Valve 220 + u: { number }?, -- Valve 220: axis x, y, z, offset + v: { number }?, + matrix: { { number } }?, -- Quake III brush primitives: 2 x 3 + flags: { number }?, -- trailing numbers: Quake II / III contents, surface flags, value (Hexen II: light) +} +export type Brush = { + type: string, -- "brush" | "brushDef" | "patchDef2" | "patchDef3" + faces: { Face }?, + texture: string?, -- patches + size: { number }?, -- patches: width, height (columns, points per column as written) + params: { number }?, -- patches: the header numbers after width, height + points: { number }?, -- patches: 5 numbers (x, y, z, s, t) per control point, in file order (column by column) +} +export type Entity = { keys: { [string]: string }, brushes: { Brush } } -- keys: an ordered object (Types.object) +export type Map = { entities: { Entity }, game: string?, mapFormat: string?, comments: { string } } + +type St = { s: string, pos: number, n: number, comments: { string } } + +local function skip(st: St) + local s = st.s + while true do + local p = string.find(s, "[^%s]", st.pos) + if not p then + st.pos = st.n + 1 + return + end + if string.sub(s, p, p + 1) == "//" then + local e = string.find(s, "\n", p, true) or st.n + table.insert(st.comments, (string.gsub(string.sub(s, p + 2, e), "^%s*(.-)%s*$", "%1"))) + st.pos = e + 1 + else + st.pos = p + return + end + end +end + +local function peek(st: St): string + skip(st) + return string.sub(st.s, st.pos, st.pos) +end + +local function expect(st: St, c: string): string? + if peek(st) ~= c then + return "expected '" .. c .. "' at " .. (st.pos - 1) + end + st.pos += 1 + return nil +end + +local function word(st: St): string? + skip(st) + local a, b = string.find(st.s, "^[^%s]+", st.pos) + if not a then + return nil + end + st.pos = (b :: number) + 1 + return string.sub(st.s, a, b) +end + +local function number(st: St): number? + skip(st) + local a, b = string.find(st.s, "^[^%s%(%)%[%]{}]+", st.pos) + if not a then + return nil + end + local v = tonumber(string.sub(st.s, a, b)) + if v then + st.pos = (b :: number) + 1 + end + return v +end + +local function quoted(st: St): string? + if peek(st) ~= '"' then + return nil + end + local e = string.find(st.s, '"', st.pos + 1, true) + if not e then + return nil + end + local v = string.sub(st.s, st.pos + 1, e - 1) + st.pos = e + 1 + return v +end + +local function numbers(st: St, n: number, out: { number }): string? + for _ = 1, n do + local v = number(st) + if not v then + return "expected a number at " .. (st.pos - 1) + end + table.insert(out, v) + end + return nil +end + +local function vec(st: St, n: number, open: string, close: string): ({ number }?, string?) + local e = expect(st, open) + if e then + return nil, e + end + local out = {} + e = numbers(st, n, out) + if e then + return nil, e + end + e = expect(st, close) + if e then + return nil, e + end + return out, nil +end + +local function trailing(st: St): { number }? + local out: { number } = {} + while true do + local c = peek(st) + if not string.match(c, "[%d%-%+%.]") then + break + end + local v = number(st) + if not v then + break + end + table.insert(out, v) + end + return if #out > 0 then out else nil +end + +local function plane(st: St): ({ number }?, string?) + local pts: { number } = {} + for _ = 1, 3 do + local p, e = vec(st, 3, "(", ")") + if not p then + return nil, e + end + table.move(p, 1, 3, #pts + 1, pts) + end + return pts, nil +end + +local function face(st: St, bp: boolean): (Face?, string?) + local pts, e = plane(st) + if not pts then + return nil, e + end + local f: Face = { points = pts, texture = "" } + if bp then + e = expect(st, "(") + if e then + return nil, e + end + local r1, e1 = vec(st, 3, "(", ")") + if not r1 then + return nil, e1 + end + local r2, e2 = vec(st, 3, "(", ")") + if not r2 then + return nil, e2 + end + e = expect(st, ")") + if e then + return nil, e + end + f.matrix = { r1, r2 } + end + local tex = word(st) + if not tex then + return nil, "expected a texture name at " .. (st.pos - 1) + end + f.texture = tex + if not bp then + if peek(st) == "[" then + local u, eu = vec(st, 4, "[", "]") + if not u then + return nil, eu + end + local v, ev = vec(st, 4, "[", "]") + if not v then + return nil, ev + end + local rest = {} + e = numbers(st, 3, rest) + if e then + return nil, e + end + f.u, f.v, f.rotation, f.scale = u, v, rest[1], { rest[2], rest[3] } + else + local rest = {} + e = numbers(st, 5, rest) + if e then + return nil, e + end + f.offset, f.rotation, f.scale = { rest[1], rest[2] }, rest[3], { rest[4], rest[5] } + end + end + f.flags = trailing(st) + return f, nil +end + +local function patch(st: St, kind: string, maxPoints: number): (Brush?, string?) + local e = expect(st, "{") + if e then + return nil, e + end + local tex = word(st) + if not tex then + return nil, "expected a patch texture" + end + local hn = if kind == "patchDef3" then 7 else 5 + local head, eh = vec(st, hn, "(", ")") + if not head then + return nil, eh + end + local w, h = head[1], head[2] + if w ~= math.floor(w) or h ~= math.floor(h) or w < 1 or h < 1 or w * h > maxPoints then + return nil, "bad patch size " .. w .. " x " .. h + end + local pts: { number } = {} + e = expect(st, "(") + if e then + return nil, e + end + for _ = 1, w do + e = expect(st, "(") + if e then + return nil, e + end + for _ = 1, h do + local p, ep = vec(st, 5, "(", ")") + if not p then + return nil, ep + end + table.move(p, 1, 5, #pts + 1, pts) + end + e = expect(st, ")") + if e then + return nil, e + end + end + e = expect(st, ")") + if e then + return nil, e + end + e = expect(st, "}") + if e then + return nil, e + end + return { type = kind, texture = tex, size = { w, h }, params = { table.unpack(head, 3) }, points = pts }, nil +end + +local function brush(st: St, maxPoints: number): (Brush?, string?) + local c = peek(st) + if c == "(" then + local faces: { Face } = {} + while peek(st) == "(" do + local f, e = face(st, false) + if not f then + return nil, e + end + table.insert(faces, f) + end + local e = expect(st, "}") + if e then + return nil, e + end + return { type = "brush", faces = faces }, nil + end + if c == "}" then + st.pos += 1 + return { type = "brush", faces = {} }, nil + end + local kw = word(st) + local out: any, err: string? + if kw == "brushDef" then + local e = expect(st, "{") + if e then + return nil, e + end + local faces: { Face } = {} + while peek(st) == "(" do + local f, ef = face(st, true) + if not f then + return nil, ef + end + table.insert(faces, f) + end + e = expect(st, "}") + if e then + return nil, e + end + out = { type = "brushDef", faces = faces } + elseif kw == "patchDef2" or kw == "patchDef3" then + out, err = patch(st, kw, maxPoints) + if not out then + return nil, err + end + elseif kw == "brushDef3" then + return nil, "unsupported: Doom 3 / Quake 4 brushDef3" + else + return nil, "unexpected '" .. tostring(kw) .. "' in a brush at " .. (st.pos - 1) + end + local e = expect(st, "}") + if e then + return nil, e + end + return out, nil +end + +function Parse.parse(s: string, maxBrushes: number?): (Map?, string?, number?) + local st: St = { s = s, pos = 1, n = #s, comments = {} } + if string.sub(s, 1, 3) == "\239\187\191" then + st.pos = 4 + end + local limit = maxBrushes or 2 ^ 20 + local count = 0 + local ents: { Entity } = {} + while peek(st) ~= "" do + local at = st.pos - 1 + local e = expect(st, "{") + if e then + return nil, e, at + end + local keys: { [string]: string } = {} + local order: { string } = {} + local brushes: { Brush } = {} + while true do + local c = peek(st) + if c == "}" then + st.pos += 1 + break + elseif c == '"' then + local k = quoted(st) + local v = quoted(st) + if not k or not v then + return nil, "bad key / value at " .. (st.pos - 1), st.pos - 1 + end + if keys[k] == nil then + table.insert(order, k) + end + keys[k] = v + elseif c == "{" then + st.pos += 1 + local b, eb = brush(st, limit) + if not b then + return nil, eb, st.pos - 1 + end + count += 1 + if count > limit then + return nil, "limit: too many brushes", st.pos - 1 + end + table.insert(brushes, b) + elseif c == "" then + return nil, "truncated entity", st.pos - 1 + else + return nil, "unexpected '" .. c .. "' in an entity at " .. (st.pos - 1), st.pos - 1 + end + end + table.insert(ents, { keys = Types.object(keys, order) :: { [string]: string }, brushes = brushes }) + end + local game, fmt + for _, c in st.comments do + game = game or string.match(c, "^Game:%s*(.-)%s*$") + fmt = fmt or string.match(c, "^Format:%s*(.-)%s*$") + end + return { entities = ents, game = game, mapFormat = fmt, comments = st.comments }, nil, nil +end + +return Parse diff --git a/src/Rosetta/model/map/Write.luau b/src/Rosetta/model/map/Write.luau new file mode 100644 index 0000000..47ce084 --- /dev/null +++ b/src/Rosetta/model/map/Write.luau @@ -0,0 +1,144 @@ +--!strict +-- model/map/Write: entities (model/map/Parse's layout) -> .map text in the editors' layout (TrenchBroom / Radiant: +-- one face per line, numbers in their shortest exact form). +local Types = require("@rosetta/Types") +local Parse = require("@rosetta/model/map/Parse") + +local Write = {} + +function Write.num(x: number): string + if x ~= x or x == math.huge or x == -math.huge then + return "0" + end + if x == math.floor(x) and math.abs(x) < 2 ^ 53 then + return string.format("%d", x) + end + for p = 6, 17 do + local s = string.format("%." .. p .. "g", x) + if tonumber(s) == x then + return s + end + end + return string.format("%.17g", x) +end + +local function nums(t: { number }, a: number, b: number): string + local out = table.create(b - a + 1) :: { string } + for i = a, b do + out[#out + 1] = Write.num(t[i] or 0) + end + return table.concat(out, " ") +end + +local function faceLine(f: Parse.Face, bp: boolean): (string?, string?) + local p = f.points + if type(p) ~= "table" or #p < 9 or type(f.texture) ~= "string" or f.texture == "" or string.find(f.texture, "%s") then + return nil, "a face needs 9 point numbers and a texture name without spaces" + end + local parts: { string } = { "( " .. nums(p, 1, 3) .. " ) ( " .. nums(p, 4, 6) .. " ) ( " .. nums(p, 7, 9) .. " )" } + if bp then + local m = f.matrix + if not m or not m[1] or not m[2] then + return nil, "a brushDef face needs a texture matrix" + end + table.insert(parts, "( ( " .. nums(m[1], 1, 3) .. " ) ( " .. nums(m[2], 1, 3) .. " ) )") + table.insert(parts, f.texture) + elseif f.u and f.v then + local sc = f.scale or { 1, 1 } + table.insert(parts, f.texture) + table.insert(parts, "[ " .. nums(f.u, 1, 4) .. " ] [ " .. nums(f.v, 1, 4) .. " ] " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2)) + else + local o, sc = f.offset or { 0, 0 }, f.scale or { 1, 1 } + table.insert(parts, f.texture) + table.insert(parts, nums(o, 1, 2) .. " " .. Write.num(f.rotation or 0) .. " " .. nums(sc, 1, 2)) + end + if f.flags and #f.flags > 0 then + table.insert(parts, nums(f.flags, 1, #f.flags)) + end + return table.concat(parts, " "), nil +end + +local function patchText(b: Parse.Brush, out: { string }): string? + local size, pts = b.size, b.points + if not size or not pts or type(b.texture) ~= "string" then + return "a patch needs a texture, a size and control points" + end + local w, h = size[1], size[2] + if #pts < w * h * 5 then + return "a patch needs width * height * 5 control numbers" + end + local params = b.params or {} + local nParams = if b.type == "patchDef3" then 5 else 3 + table.insert(out, b.type) + table.insert(out, "{") + table.insert(out, b.texture) + table.insert(out, "( " .. Write.num(w) .. " " .. Write.num(h) .. " " .. nums(params, 1, nParams) .. " )") + table.insert(out, "(") + for i = 0, w - 1 do + local row = { "(" } + for j = 0, h - 1 do + local o = (i * h + j) * 5 + table.insert(row, "( " .. nums(pts, o + 1, o + 5) .. " )") + end + table.insert(row, ")") + table.insert(out, table.concat(row, " ")) + end + table.insert(out, ")") + table.insert(out, "}") + return nil +end + +function Write.text(map: Parse.Map): (string?, string?) + local out: { string } = {} + if map.game then + table.insert(out, "// Game: " .. map.game) + end + if map.mapFormat then + table.insert(out, "// Format: " .. map.mapFormat) + end + for ei, ent in map.entities do + table.insert(out, "// entity " .. (ei - 1)) + table.insert(out, "{") + for _, k in Types.keys(ent.keys) do + local v = ent.keys[k] + if v ~= nil then + if string.find(k, '"', 1, true) or string.find(tostring(v), '"', 1, true) or string.find(k, "[\r\n]") or string.find(tostring(v), "[\r\n]") then + return nil, "keys and values cannot hold quotes or line breaks: " .. k + end + table.insert(out, '"' .. k .. '" "' .. tostring(v) .. '"') + end + end + for bi, b in ent.brushes or {} do + table.insert(out, "// brush " .. (bi - 1)) + table.insert(out, "{") + if b.type == "patchDef2" or b.type == "patchDef3" then + local e = patchText(b, out) + if e then + return nil, e + end + else + local bp = b.type == "brushDef" + if bp then + table.insert(out, "brushDef") + table.insert(out, "{") + end + for _, f in b.faces or {} do + local line, e = faceLine(f, bp) + if not line then + return nil, e + end + table.insert(out, line) + end + if bp then + table.insert(out, "}") + end + end + table.insert(out, "}") + end + table.insert(out, "}") + end + table.insert(out, "") + return table.concat(out, "\n"), nil +end + +return Write diff --git a/src/Rosetta/model/map/init.luau b/src/Rosetta/model/map/init.luau new file mode 100644 index 0000000..10b6841 --- /dev/null +++ b/src/Rosetta/model/map/init.luau @@ -0,0 +1,315 @@ +--!strict +-- model/map: editor .map files of Quake, Half-Life (Valve 220), Quake II (surface / content flags) and Quake III +-- (brushDef brush primitives, patchDef2; patchDef3 meshes), read and write. Grammar of the qbsp / q3map2 parsers (no +-- code taken). Brushes become polygons through codecs/model/Brush (optionally CSG'd and merged), patches through +-- codecs/model/Patch; a mesh per entity with brushes; entities as nodes with their keys in extras. Texture sizes from +-- opts.textureSizes, the worldspawn's WADs, .wal files or images through resolve; else 64 x 64. Not supported: Doom 3 +-- brushDef3, Build engine maps (binary: model/buildmap), compiling (no BSP, vis or light). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@rosetta/core/Err") +local Bytes = require("@rosetta/core/Bytes") +local Input = require("@rosetta/core/Input") +local Types = require("@rosetta/Types") +local Miptex = require("@rosetta/codecs/image/Miptex") +local Brush = require("@rosetta/codecs/model/Brush") +local Parse = require("@rosetta/model/map/Parse") +local Write = require("@rosetta/model/map/Write") +local Build = require("@rosetta/model/map/Build") + +-- ------------------------------------------------------------------------------------------------ contract +local Map = { + name = "map", + category = "model", + extensions = { "map" }, + mime = { "text/x-quake-map" }, + deps = { "core/Err", "core/Bytes", "core/Input", "Types", "codecs/image/Miptex", "codecs/model/Brush", "codecs/model/Patch" }, + caps = { decode = true, encode = true, variants = { "quake", "valve220", "quake2", "quake3" }, patches = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + hull: boolean?, -- drop faces inside / touching other brushes of the same entity, default false + merge: boolean?, -- merge coplanar faces with the same texture projection, default false + epsilon: number?, -- default 1e-3 + patchLevel: number?, -- patchDef2 segments per sub-patch, default 4 + skip: { string }?, -- texture names left out of the meshes ("clip", "skip", "common/caulk", ...) + textureSizes: { [string]: { number } }?, -- name -> { width, height } + resolve: ((uri: string) -> (buffer | string)?)?, + files: { [string]: buffer | string }?, + decodeImage: ((buf: buffer) -> (Types.Image?, Err.Err?))?, -- Quake III: texture image sizes + maxBrushes: number?, -- default 2^20 + maxPolygons: number?, -- default 2^20 +} +export type EncodeOptions = { + variant: string?, -- "valve220" converts Quake standard faces to Valve 220 axes; default: as stored +} + +-- ------------------------------------------------------------------------------------------------ sniff +function Map.sniff(r: Bytes.Reader): number + local head = r:peek(math.min(r:remaining(), 4096)) + if #head < 2 or string.find(head, "[%z\1-\8\14-\31]") then + return 0 + end + if string.sub(head, 1, 3) == "\239\187\191" then + head = string.sub(head, 4) + end + local s = head + local game = false + while true do + local c = string.match(s, "^%s*//[^\n]*\n?()") + if not c then + break + end + if string.match(s, "^%s*//%s*Game:") then + game = true + end + s = string.sub(s, c :: number) + end + local body = string.match(s, '^%s*{%s*"[^"\n]*"%s*"') or string.match(s, "^%s*{%s*{%s*[%(bp]") + if not body then + return if game and string.match(s, "^%s*{") then 0.6 else 0 + end + return if game or string.find(head, '"classname"', 1, true) then 0.9 else 0.6 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function variantOf(m: Parse.Map): string + local game = string.lower(m.game or "") + local fmt = string.lower(m.mapFormat or "") + local q2, valve, q3 = false, false, false + for _, e in m.entities do + if e.keys.mapversion == "220" then + valve = true + end + for _, b in e.brushes do + if b.type ~= "brush" then + q3 = true + end + for _, f in b.faces or {} do + if f.u then + valve = true + elseif f.flags and #f.flags >= 3 then + q2 = true + end + end + end + end + if q3 or string.find(game, "quake 3") or string.find(game, "quake iii") or fmt == "quake3" or fmt == "quake3 (valve)" then + return "quake3" + end + if string.find(game, "quake 2") or string.find(game, "quake ii") or fmt == "quake2" or fmt == "quake2 (valve)" then + return "quake2" + end + if valve or fmt == "valve" then + return "valve220" + end + return if q2 then "quake2" else "quake" +end + +local function sizer(m: Parse.Map, variant: string, opts: DecodeOptions?): (name: string) -> (number, number, boolean) + local cache: { [string]: { number } } = {} + local wads: { { buf: buffer, lumps: { Miptex.Lump } } }? = nil + local function loadWads(): { { buf: buffer, lumps: { Miptex.Lump } } } + local list = {} + local ws = m.entities[1] and m.entities[1].keys + local spec = ws and (ws.wad or ws._wad) or "" + for path in string.gmatch(spec, "[^;]+") do + local p = string.gsub(path, "\\", "/") + local b = Input.sibling(opts, p) or Input.sibling(opts, string.match(p, "([^/]+)$") or p) + if b then + local lumps = Miptex.wad(b, 0, buffer.len(b)) + if lumps then + table.insert(list, { buf = b, lumps = lumps }) + end + end + end + return list + end + return function(name: string): (number, number, boolean) + local c = cache[name] + if c then + return c[1], c[2], c[3] == 1 + end + local w: number, h: number = 0, 0 + local given = opts and opts.textureSizes and opts.textureSizes[name] + if type(given) == "table" and type(given[1]) == "number" and type(given[2]) == "number" then + w, h = given[1] :: number, given[2] :: number + elseif variant == "quake" or variant == "valve220" then + wads = wads or loadWads() + for i = #(wads :: any), 1, -1 do + local wd = (wads :: any)[i] + local l = Miptex.find(wd.lumps, name) + if l then + local hd = Miptex.header(wd.buf, l.offset, l.disksize) + if hd then + w, h = hd.width, hd.height + break + end + end + end + elseif variant == "quake2" then + local wal = Input.sibling(opts, "textures/" .. name .. ".wal") + if wal and buffer.len(wal) >= 40 then + w, h = buffer.readu32(wal, 32), buffer.readu32(wal, 36) + end + elseif opts and opts.decodeImage then + for _, ext in { ".tga", ".jpg", ".png" } do + local b = Input.sibling(opts, "textures/" .. name .. ext) + if b then + local ok, img = pcall(opts.decodeImage :: any, b) + if ok and img then + w, h = img.width, img.height + break + end + end + end + end + local fw: number, fh: number = w :: number, h :: number + local known = fw > 0 and fh > 0 + if not known then + fw, fh = 64, 64 + end + cache[name] = { fw, fh, if known then 1 else 0 } + return fw, fh, known + end +end + +function Map.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local text = buffer.readstring(r.buf, r.base, r.limit - r.base) + local m, msg, at = Parse.parse(text, opts and opts.maxBrushes) + if not m then + return nil, Err.from(msg, at) + end + if #m.entities == 0 then + return nil, Err.new(Err.CORRUPT, "no entities", 0) + end + local variant = variantOf(m) + local scene, err = Build.scene(m, { + variant = variant, + size = sizer(m, variant, opts), + hull = opts and opts.hull, + merge = opts and opts.merge, + epsilon = opts and opts.epsilon, + patchLevel = opts and opts.patchLevel, + skip = opts and opts.skip, + maxPolygons = opts and opts.maxPolygons, + }) + if not scene then + return nil, Err.from(err) + end + local counts = scene.meta.counts + scene.meta.counts = nil + scene.meta.source = { format = "map", variant = variant, game = m.game, mapFormat = m.mapFormat, entities = #m.entities, brushes = counts.brushes, patches = counts.patches } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function toValve(f: Parse.Face): Parse.Face + if f.u or f.matrix then + return f + end + local bf = Build.face(f) + if not bf or not bf.vecs then + return f + end + local v = bf.vecs + local out = table.clone(f) + out.offset = nil + out.u, out.v = { v[1][1], v[1][2], v[1][3], v[1][4] }, { v[2][1], v[2][2], v[2][3], v[2][4] } + out.rotation, out.scale = 0, { 1, 1 } + return out +end + +local function fmtNum(x: number): string + return Write.num(x) +end + +function Map.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?) + if type(scene) ~= "table" or type(scene.nodes) ~= "table" then + return nil, Err.new(Err.ARG, "expected a Scene") + end + local valve = opts and opts.variant == "valve220" + local ents: { any } = {} + for _, node in scene.nodes do + local ex: any = node.extras + if type(ex) == "table" and type(ex.keys) == "table" then + local keys = ex.keys + local brushes: { Parse.Brush } = if type(ex.brushes) == "table" then ex.brushes else {} + if node.translation and keys.origin and #brushes == 0 then + local t = node.translation + keys = Types.object(table.clone(keys), Types.keys(keys)) + keys.origin = fmtNum(t[1]) .. " " .. fmtNum(t[2]) .. " " .. fmtNum(t[3]) + end + if valve then + local conv: { Parse.Brush } = {} + for _, b in brushes do + if b.faces then + local nb = table.clone(b) + local faces = {} + for i, f in b.faces do + faces[i] = toValve(f) + end + nb.faces = faces + table.insert(conv, nb) + else + table.insert(conv, b) + end + end + brushes = conv + if #ents == 0 and keys.mapversion ~= "220" then + keys = Types.object(table.clone(keys), Types.keys(keys)) + Types.set(keys, "mapversion", "220") + end + end + table.insert(ents, { keys = keys, brushes = brushes }) + end + end + if #ents == 0 then + return nil, Err.new(Err.ARG, "no map entities (nodes with extras.keys, as model/map loads them)") + end + local src: any = scene.meta and scene.meta.source + local fromMap = type(src) == "table" and src.format == "map" + local text, err = Write.text({ + entities = ents :: { Parse.Entity }, + game = if fromMap then src.game else nil, + mapFormat = if valve then "Valve" elseif fromMap then src.mapFormat else nil, + comments = {}, + }) + if not text then + return nil, Err.new(Err.ARG, err or "bad entity") + end + return buffer.fromstring(text), nil +end + +-- ------------------------------------------------------------------------------------------------ extras +-- the entities as parsed: { entities = { { keys, brushes } }, game, mapFormat } +function Map.parse(src: buffer | string): (Parse.Map?, Err.Err?) + local text = if type(src) == "buffer" then buffer.tostring(src) elseif type(src) == "string" then src else nil + if not text then + return nil, Err.new(Err.ARG, "expected a buffer or a string") + end + local m, msg, at = Parse.parse(text) + if not m then + return nil, Err.from(msg, at) + end + return m, nil +end + +function Map.write(m: Parse.Map): (string?, Err.Err?) + if type(m) ~= "table" or type(m.entities) ~= "table" then + return nil, Err.new(Err.ARG, "expected { entities = ... }") + end + local text, err = Write.text(m) + if not text then + return nil, Err.new(Err.ARG, err or "bad entity") + end + return text, nil +end + +-- a parsed face -> its Brush face (plane and projection): Brush.uv / Brush.polygons take it +function Map.face(f: Parse.Face): Brush.Face? + return Build.face(f) +end + +return Map diff --git a/tests/archive/wad2.luau b/tests/archive/wad2.luau new file mode 100644 index 0000000..e831dd6 --- /dev/null +++ b/tests/archive/wad2.luau @@ -0,0 +1,95 @@ +-- archive/wad2 tests: WAD2 / WAD3 lumps, miptex / qpic / conchars / font / palette images against pixels decoded in +-- the fixture, ericw-tools qbsp's copy of a miptex, write round trips, adding images, errors, the fuzz pass. +-- Fixtures: tools/fixtures/wad2.py. +local T = require("@tests/T") +local F = require("@rosetta") +local Wad2 = require("@rosetta/archive/wad2") +local Miptex = require("@rosetta/codecs/image/Miptex") +local Bytes = require("@rosetta/core/Bytes") +local Crc32 = require("@rosetta/core/Crc32") +local Err = require("@rosetta/core/Err") +local Fx = require("@tests/gen/wad2") + +local t = T.suite("wad2") +t:eq(Wad2.name, "wad2", "name") + +for _, v in { "wad2", "wad3" } do + local c = Fx[v] + t:eq(F.detect(c.data), "wad2", v .. ": F.detect") + local a, err = Wad2.decode(Bytes.reader(buffer.fromstring(c.data))) + t:check(a, v .. ": " .. tostring(err)) + t:eq(a.meta.source.variant, v, v .. ": variant") + local names = {} + for _, e in a:list() do + table.insert(names, e.name) + end + t:eq(table.concat(names, ","), table.concat(c.names, ","), v .. ": lump names in order") + for name, want in c.images do + local img, ierr = Wad2.image(a, name) + t:check(img, v .. ": image " .. name .. ": " .. tostring(ierr)) + t:eq(img.width .. "x" .. img.height, want.w .. "x" .. want.h, v .. ": " .. name .. " size") + t:eq(Crc32.of(img.pixels), want.crc, v .. ": " .. name .. " pixels") + t:eq(img.meta.source.kind, want.kind, v .. ": " .. name .. " kind") + if want.mip2 then + local m2 = assert(Wad2.image(a, name, { mip = 2 })) + t:eq(Crc32.of(m2.pixels), want.mip2, v .. ": " .. name .. " mip 2") + end + end + -- write: the same lumps back + local out = assert(F.save(a)) + local b = assert(Wad2.decode(Bytes.reader(out))) + t:eq(b.meta.source.variant, v, v .. ": variant kept") + for _, e in a:list() do + t:check(buffer.tostring(assert(a:read(e.name))) == buffer.tostring(assert(b:read(e.name))), v .. ": round trip " .. e.name) + t:eq((b:list()[1] :: any).type, (a:list()[1] :: any).type, v .. ": lump types kept") + end +end + +do + local a = assert(Wad2.decode(Bytes.reader(buffer.fromstring(Fx.wad2.data)))) + t:eq(Wad2.image(a, "palette").width, 16, "palette lump as a 16 x 16 image") + t:check(Wad2.palette(a) ~= nil, "the WAD's palette") + -- an explicit palette wins over the WAD's + local grey = string.rep("\0", 768) + local g = assert(Wad2.image(a, "brick", { palette = grey })) + t:eq(buffer.readu32(g.pixels, 0), 0xFF000000, "explicit palette") + -- qbsp copied brick into the BSP: same pixels + local m = assert(Miptex.decode(buffer.fromstring(Fx.bsp.miptex), 0, #Fx.bsp.miptex, { palette = Wad2.palette(a) })) + t:eq(Crc32.of(m.pixels), Fx.wad2.images.brick.crc, "qbsp's copy of the miptex") + -- adding images: palette colours map back exactly + local brick = assert(Wad2.image(a, "brick")) + local n = Wad2.new("wad2") + t:check(Wad2.addImage(n, "copy", brick, { palette = Fx.wad2.palette }), "addImage miptex") + t:check(Wad2.addImage(n, "pic", brick, { palette = Fx.wad2.palette, kind = "qpic" }), "addImage qpic") + local _, e1 = Wad2.addImage(n, "odd", F.ops.image.new(10, 10), { palette = Fx.wad2.palette }) + t:check(e1 and e1.code == Err.ARG, "miptex sizes: multiples of 16") + local _, e2 = Wad2.addImage(n, "nopal", brick) + t:check(e2 and e2.code == Err.ARG, "WAD2 needs a palette") + local nb = assert(Wad2.decode(Bytes.reader(assert(F.save(n))))) + t:eq(Crc32.of(assert(Wad2.image(nb, "copy", { palette = Fx.wad2.palette })).pixels), Fx.wad2.images.brick.crc, "added miptex decodes the same") + t:eq(Crc32.of(assert(Wad2.image(nb, "pic", { palette = Fx.wad2.palette, keyed = false })).pixels), Fx.wad2.images.brick.crc, "added qpic decodes the same") + -- WAD3: its own palette from median cut (at most 256 colours: exact) + local w3 = assert(Wad2.decode(Bytes.reader(buffer.fromstring(Fx.wad3.data)))) + local crete = assert(Wad2.image(w3, "crete")) + local n3 = Wad2.new("wad3") + t:check(Wad2.addImage(n3, "CRETE2", crete), "addImage into WAD3") + local d3 = assert(Wad2.decode(Bytes.reader(assert(F.save(n3))))) + t:eq(d3.meta.source.variant, "wad3", "WAD3 written") + t:eq(Crc32.of(assert(Wad2.image(d3, "CRETE2")).pixels), Fx.wad3.images.CRETE.crc, "WAD3 miptex with a made palette") + t:check(assert(Wad2.image(w3, "CONCHARS")).meta.font.glyphs[66].width == 8, "font glyph table") + local _, e3 = Wad2.image(w3, "missing") + t:check(e3 and e3.code == Err.ARG, "missing lump") + local _, e4 = Wad2.decode(Bytes.reader(buffer.fromstring(string.sub(Fx.wad2.data, 1, 20)))) + t:check(e4 and e4.code == Err.TRUNCATED, "truncated directory: " .. tostring(e4)) +end + +t:fuzz("decode", function(b: buffer) + local a = Wad2.decode(Bytes.reader(b)) + if a then + for _, e in a:list() do + Wad2.image(a, e.name) + end + end + return a +end, { Fx.wad2.data, Fx.wad3.data }, { mutations = 80 }) +t:done() diff --git a/tests/codecs/brush.luau b/tests/codecs/brush.luau new file mode 100644 index 0000000..174a3b1 --- /dev/null +++ b/tests/codecs/brush.luau @@ -0,0 +1,224 @@ +-- codecs/model/Brush tests: random overlapping brushes in Quake standard / Valve 220 / brush-primitive projections +-- against ericw-tools qbsp -nofill (face area per plane after CSG, texture coordinates at every compiled corner); +-- merging, the primitive builder, the fuzz pass. Fixtures: tools/fixtures/brush.py. +local T = require("@tests/T") +local Brush = require("@rosetta/codecs/model/Brush") +local Types = require("@rosetta/Types") +local Fx = require("@tests/gen/brush") + +local t = T.suite("brush") + +local function faceOf(rec: any): Brush.Face? + local p = rec.pts + local plane = Brush.planeFromPoints({ p[1], p[2], p[3] }, { p[4], p[5], p[6] }, { p[7], p[8], p[9] }) + if not plane then + return nil + end + local a = rec.args + local f: Brush.Face = { plane = plane, texture = rec.tex } + if rec.kind == "standard" then + f.vecs = Brush.quakeVecs(plane, a[1], a[2], a[3], a[4], a[5]) + elseif rec.kind == "valve" then + f.vecs = Brush.valveVecs({ a[1], a[2], a[3], a[4] }, { a[5], a[6], a[7], a[8] }, a[10], a[11]) + else + f.bp = { { a[1], a[2], a[3] }, { a[4], a[5], a[6] } } + end + return f +end + +local function key(n: { number }): string + local function r(x: number, k: number): number + return math.floor(x * k + 0.5) + end + return string.format("%d %d %d %d", r(n[1], 1000), r(n[2], 1000), r(n[3], 1000), r(n[4], 100)) +end + +local function inside(pts: { number }, n: { number }, x: number, y: number, z: number, tol: number): boolean + local k = #pts // 3 + for i = 0, k - 1 do + local j = (i + 1) % k + local ex, ey, ez = pts[j * 3 + 1] - pts[i * 3 + 1], pts[j * 3 + 2] - pts[i * 3 + 2], pts[j * 3 + 3] - pts[i * 3 + 3] + -- inward edge normal = n x e (counter-clockwise polygons) + local ix, iy, iz = n[2] * ez - n[3] * ey, n[3] * ex - n[1] * ez, n[1] * ey - n[2] * ex + local l = math.sqrt(ix * ix + iy * iy + iz * iz) + if l > 0 and ((x - pts[i * 3 + 1]) * ix + (y - pts[i * 3 + 2]) * iy + (z - pts[i * 3 + 3]) * iz) / l < -tol then + return false + end + end + return true +end + +for kind, m in Fx do + local brushes: { { Brush.Face } } = {} + for _, b in m.brushes do + local faces = {} + for _, rec in b do + table.insert(faces, assert(faceOf(rec))) + end + table.insert(brushes, faces) + end + local polys = assert(Brush.polygons(brushes, { hull = true })) + -- area per plane: ours after CSG = qbsp's faces (split by its BSP, merged, subdivided) + local ours, theirs = {}, {} + for _, p in polys do + local k = key(brushes[p.brush][p.face].plane) + ours[k] = (ours[k] or 0) + Brush.area(p.points) + end + for _, f in m.faces do + local k = key(f.plane) + theirs[k] = (theirs[k] or 0) + Brush.area(f.pts) + end + local bad = 0 + for k, a in theirs do + if math.abs((ours[k] or 0) - a) > 0.05 then + bad += 1 + t:note("%s: plane %s area %s, qbsp %s", kind, k, tostring(ours[k]), tostring(a)) + end + end + for k in ours do + if not theirs[k] then + bad += 1 + t:note("%s: plane %s only in ours", kind, k) + end + end + t:eq(bad, 0, kind .. ": face area per plane matches qbsp") + -- every compiled corner lies on one of our polygons with the same texture, and maps to the same texels + local miss, off, worst = 0, 0, 0 + local corners = 0 + for _, f in m.faces do + local pk = key(f.plane) + for c = 0, #f.pts // 3 - 1 do + local x, y, z = f.pts[c * 3 + 1], f.pts[c * 3 + 2], f.pts[c * 3 + 3] + corners += 1 + local s = f.vecs[1] * x + f.vecs[2] * y + f.vecs[3] * z + f.vecs[4] + local tt = f.vecs[5] * x + f.vecs[6] * y + f.vecs[7] * z + f.vecs[8] + local found = false + local best = math.huge + for _, p in polys do + local face = brushes[p.brush][p.face] + if face.texture == f.tex and key(face.plane) == pk and inside(p.points, p.normal, x, y, z, 0.02) then + found = true + local size = m.sizes[f.tex] + local u, v = Brush.uv(face, x, y, z, size[1], size[2]) + best = math.min(best, math.max(math.abs(u * size[1] - s), math.abs(v * size[2] - tt))) + end + end + if not found then + miss += 1 + local any = {} + for _, p in polys do + local face = brushes[p.brush][p.face] + if key(face.plane) == pk and inside(p.points, p.normal, x, y, z, 0.02) then + table.insert(any, face.texture .. "#" .. p.brush) + end + end + t:note("%s miss %s %s %s on %s tex %s: ours %s", kind, x, y, z, pk, f.tex, table.concat(any, ",")) + elseif best > 0.02 then + off += 1 + t:note("%s off %s %s %s on %s tex %s best %s vecs %s", kind, x, y, z, pk, f.tex, best, table.concat(f.vecs, " ")) + worst = math.max(worst, best) + end + end + end + t:eq(miss, 0, kind .. ": every qbsp corner is on one of our faces (" .. corners .. " corners)") + t:eq(off, 0, kind .. ": texture coordinates match qbsp's texinfo (worst " .. worst .. " texels)") + -- primitives: counter-clockwise about the face normals, one per texture + local built = Brush.primitives(polys, brushes, function(name: string) + local s = m.sizes[name] + return s[1], s[2] + end) + local seen, wrong = {}, 0 + for _, b in built do + t:check(not seen[b.texture], kind .. ": one primitive per texture " .. b.texture) + seen[b.texture] = true + local prim = b.primitive + local pos = Types.Scene.reader(prim.attributes.POSITION) :: any + local nrm = Types.Scene.reader(prim.attributes.NORMAL) :: any + local idx = prim.indices :: Types.Accessor + for k = 0, idx.count - 1, 3 do + local i0, i1, i2 = buffer.readu32(idx.data, k * 4), buffer.readu32(idx.data, k * 4 + 4), buffer.readu32(idx.data, k * 4 + 8) + local ux, uy, uz = pos(i1, 0) - pos(i0, 0), pos(i1, 1) - pos(i0, 1), pos(i1, 2) - pos(i0, 2) + local vx, vy, vz = pos(i2, 0) - pos(i0, 0), pos(i2, 1) - pos(i0, 1), pos(i2, 2) - pos(i0, 2) + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + if cx * nrm(i0, 0) + cy * nrm(i0, 1) + cz * nrm(i0, 2) <= 0 then + wrong += 1 + end + end + end + t:eq(wrong, 0, kind .. ": triangles counter-clockwise about their normals") + -- merging keeps the area per plane + local merged = assert(Brush.polygons(brushes, { hull = true, merge = true })) + t:check(#merged <= #polys, kind .. ": merge does not add polygons") + local after = {} + for _, p in merged do + local k = key(brushes[p.brush][p.face].plane) + after[k] = (after[k] or 0) + Brush.area(p.points) + end + local drift = 0 + for k, a in ours do + drift = math.max(drift, math.abs((after[k] or 0) - a)) + end + t:check(drift < 1e-6, kind .. ": merged area per plane unchanged") +end + +-- two touching cubes merge into one box: 6 faces, no inner faces +do + local function cube(x0: number, x1: number): { Brush.Face } + local f = {} + for _, p in { { 1, 0, 0, x1 }, { -1, 0, 0, -x0 }, { 0, 1, 0, 64 }, { 0, -1, 0, 0 }, { 0, 0, 1, 64 }, { 0, 0, -1, 0 } } do + table.insert(f, { plane = p, texture = "t", vecs = Brush.quakeVecs(p, 0, 0, 0, 1, 1) }) + end + return f + end + local polys = assert(Brush.polygons({ cube(0, 64), cube(64, 128) }, { hull = true, merge = true })) + t:eq(#polys, 6, "touching cubes: 6 merged faces") + local area = 0 + for _, p in polys do + area += Brush.area(p.points) + end + t:eq(area, 2 * 128 * 64 * 2 + 2 * 64 * 64, "touching cubes: surface area") + local plain = assert(Brush.polygons({ cube(0, 64), cube(64, 128) })) + t:eq(#plain, 12, "without hull / merge: every face") + t:check(Brush.planeFromPoints({ 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 }) == nil, "colinear points: no plane") + -- Quake standard with exact rotations, against TextureAxisFromPlane by hand: a floor, rotated 90 degrees + local v = Brush.quakeVecs({ 0, 0, 1, 0 }, 8, 4, 90, 2, 1) + t:eq(v[1][1] .. " " .. v[1][2] .. " " .. v[1][4], "0 0.5 8", "rotated floor s axis") + t:eq(v[2][1] .. " " .. v[2][2] .. " " .. v[2][4], "1 0 4", "rotated floor t axis") + -- brush primitives <-> texel vectors + local n = { 0.6, 0, 0.8, 10 } + local bp = { { 0.01, 0.02, 0.5 }, { -0.03, 0.004, 0.25 } } + local back = Brush.vecsToBp(n, Brush.bpVecs(n, bp, 64, 32), 64, 32) + local err = 0 + for i = 1, 2 do + for j = 1, 3 do + err = math.max(err, math.abs(back[i][j] - bp[i][j])) + end + end + t:check(err < 1e-12, "bpVecs / vecsToBp round trip") +end + +-- fuzz: random planes never throw +do + local rand = T.rng(5) + local threw = 0 + for _ = 1, 200 do + local faces = {} + for _ = 1, 1 + rand(10) do + local p = { rand(2001) / 1000 - 1, rand(2001) / 1000 - 1, rand(2001) / 1000 - 1, rand(200) - 100 } + table.insert(faces, { plane = p, texture = "x", vecs = { { 1, 0, 0, 0 }, { 0, 1, 0, 0 } } }) + end + local ok = pcall(function() + local polys = Brush.polygons({ faces, faces }, { hull = true, merge = true }) + if polys then + Brush.primitives(polys, { faces, faces }, function() + return 64, 64 + end) + end + end) + if not ok then + threw += 1 + end + end + t:eq(threw, 0, "random planes never throw") +end +t:done() diff --git a/tests/codecs/patch.luau b/tests/codecs/patch.luau new file mode 100644 index 0000000..1989e66 --- /dev/null +++ b/tests/codecs/patch.luau @@ -0,0 +1,85 @@ +-- codecs/model/Patch tests: biquadratic Bezier evaluation against the closed form, shared sub-patch edges, triangle +-- winding and normals, explicit (patchDef3-style) subdivisions per axis, the fuzz pass. +local T = require("@tests/T") +local Patch = require("@rosetta/codecs/model/Patch") + +local t = T.suite("patch") + +-- a 5 x 3 grid (two sub-patches along u): x = column * 8, y = row * 8, z = a bump on the middle control row +local ctrl = {} +for j = 0, 2 do + for i = 0, 4 do + table.insert(ctrl, i * 8) + table.insert(ctrl, j * 8) + table.insert(ctrl, if j == 1 then 16 else 0) + end +end +local pts, gw, gh = Patch.grid(ctrl, 5, 3, 3, 4, 2) +t:check(pts ~= nil, "grid") +t:eq(gw, 9, "width: 2 sub-patches x 4 segments + 1") +t:eq(gh, 3, "height: 2 segments + 1") +local p = pts :: { number } +-- z(v) = 2 v (1 - v) * 16 on every column (the bump is constant along u); x is linear in u +local worst = 0 +for gy = 0, gh - 1 do + local v = gy / 2 + for gx = 0, gw - 1 do + local o = (gy * gw + gx) * 3 + worst = math.max(worst, math.abs(p[o + 1] - gx * 4), math.abs(p[o + 2] - v * 16), math.abs(p[o + 3] - 32 * v * (1 - v))) + end +end +t:check(worst < 1e-12, "closed form (worst " .. worst .. ")") +-- corners interpolate the control points +t:eq(p[1] .. " " .. p[2] .. " " .. p[3], "0 0 0", "first corner") +local last = (gw * gh - 1) * 3 +t:eq(p[last + 1] .. " " .. p[last + 2] .. " " .. p[last + 3], "32 16 0", "last corner") + +local tris = Patch.triangles(gw, gh) +t:eq(#tris, (gw - 1) * (gh - 1) * 6, "two triangles per cell") +local nrm = Patch.normals(p, 3, gw, gh) +local bad = 0 +for k = 1, #tris, 3 do + local a, b, c = tris[k] * 3, tris[k + 1] * 3, tris[k + 2] * 3 + local ux, uy, uz = p[b + 1] - p[a + 1], p[b + 2] - p[a + 2], p[b + 3] - p[a + 3] + local vx, vy, vz = p[c + 1] - p[a + 1], p[c + 2] - p[a + 2], p[c + 3] - p[a + 3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + if cx * nrm[a + 1] + cy * nrm[a + 2] + cz * nrm[a + 3] <= 0 then + bad += 1 + end +end +t:eq(bad, 0, "normals face the front of the triangles") + +-- extra components (texture coordinates) interpolate too; normalize renormalizes a vec3 +local flat = {} +for j = 0, 2 do + for i = 0, 2 do + for _, v in { i, j, 0, i / 2, j / 2, 0, 0, 2 } do + table.insert(flat, v) + end + end +end +local q, qw, qh = Patch.grid(flat, 3, 3, 8, 3, 5) +t:eq(qw * qh, 4 * 6, "explicit subdivisions per axis") +Patch.normalize(q :: { number }, 8, 5) +t:eq((q :: { number })[8], 1, "renormalized normal") +t:eq((q :: { number })[(qw * qh - 1) * 8 + 4], 1, "texture coordinate at the far corner") + +t:check(Patch.grid({ 1, 2, 3 }, 2, 2, 3, 4, 4) == nil, "even grid: nil") +t:check(Patch.grid(ctrl, 5, 3, 3, 1000, 1000, 1000) == nil, "point limit: nil") + +t:fuzz("grid", function(b: buffer) + local n = buffer.len(b) + local w = 1 + 2 * (if n > 0 then buffer.readu8(b, 0) % 4 else 1) + local h = 1 + 2 * (if n > 1 then buffer.readu8(b, 1) % 4 else 1) + local c = {} + for k = 0, n - 1 do + table.insert(c, buffer.readu8(b, k) - 128) + end + local g, gw2, gh2 = Patch.grid(c, w, h, 3, 1 + n % 5, 1 + n % 3) + if g then + Patch.normals(g, 3, gw2, gh2) + Patch.triangles(gw2, gh2) + end + return g +end, { buffer.create(27), buffer.create(45), buffer.create(75) }) +t:done() diff --git a/tests/data/q3shader.luau b/tests/data/q3shader.luau new file mode 100644 index 0000000..0813e34 --- /dev/null +++ b/tests/data/q3shader.luau @@ -0,0 +1,57 @@ +-- data/q3shader tests: shader scripts against an independent tokenizer (tools/fixtures/q3shader.py), write round +-- trips, lookups, errors, the fuzz pass. +local T = require("@tests/T") +local F = require("@rosetta") +local Q3Shader = require("@rosetta/data/q3shader") +local Bytes = require("@rosetta/core/Bytes") +local Err = require("@rosetta/core/Err") +local Fx = require("@tests/gen/q3shader") + +local t = T.suite("q3shader") +t:eq(Q3Shader.name, "q3shader", "name") + +local function dump(v: any): string + if type(v) ~= "table" then + return tostring(v) + end + local parts = {} + if v.name then + table.insert(parts, "name=" .. v.name) + table.insert(parts, "d=" .. dump(v.directives)) + table.insert(parts, "s=" .. dump(v.stages)) + elseif v.surface then + table.insert(parts, v.surface .. "=" .. v.shader) + else + for _, x in v do + table.insert(parts, dump(x)) + end + end + return "{" .. table.concat(parts, "|") .. "}" +end + +local samples = {} +for i, c in Fx.scripts do + t:eq(F.detect(c.text), "q3shader", "script " .. i .. ": F.detect") + local list, err = Q3Shader.decode(Bytes.reader(buffer.fromstring(c.text))) + t:check(list, "script " .. i .. ": " .. tostring(err)) + t:eq(dump(list), dump(c.shaders), "script " .. i .. ": structure") + local out = assert(Q3Shader.encode(list :: any)) + t:eq(dump(Q3Shader.decode(Bytes.reader(out))), dump(c.shaders), "script " .. i .. ": round trip") + table.insert(samples, c.text) +end +do + local list = assert(Q3Shader.decode(Bytes.reader(buffer.fromstring(Fx.scripts[2].text)))) + local sky = assert(Q3Shader.find(list, "TEXTURES/SKIES/HELLSKY")) + t:eq(assert(Q3Shader.directive(sky.directives, "skyparms"))[2], "env/hell sky", "quoted token") + t:eq(#sky.stages, 1, "stage on brace lines") + local again = assert(F.data.load(Fx.scripts[1].text)) + t:eq(#again, 2, "F.data.load") + local _, e1 = Q3Shader.decode(Bytes.reader(buffer.fromstring("textures/x\n{\n{\nmap a\n"))) + t:check(e1 and e1.code == Err.TRUNCATED, "unclosed shader") + local _, e2 = Q3Shader.encode({ { name = "has space", directives = {}, stages = {} } } :: any) + t:check(e2 and e2.code == Err.ARG, "bad name") +end +t:fuzz("decode", function(b: buffer) + return Q3Shader.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tests/data/q3skin.luau b/tests/data/q3skin.luau new file mode 100644 index 0000000..3cea417 --- /dev/null +++ b/tests/data/q3skin.luau @@ -0,0 +1,36 @@ +-- data/q3skin tests: Quake III .skin files against tools/fixtures/q3shader.py's parse, write round trips, lookup, +-- errors, the fuzz pass. +local T = require("@tests/T") +local F = require("@rosetta") +local Q3Skin = require("@rosetta/data/q3skin") +local Bytes = require("@rosetta/core/Bytes") +local Err = require("@rosetta/core/Err") +local Fx = require("@tests/gen/q3shader") + +local t = T.suite("q3skin") +t:eq(Q3Skin.name, "q3skin", "name") + +local function dump(list: any): string + local parts = {} + for _, e in list do + table.insert(parts, e.surface .. "=" .. e.shader) + end + return table.concat(parts, "|") +end + +for i, c in Fx.skins do + local list, err = Q3Skin.decode(Bytes.reader(buffer.fromstring(c.text))) + t:check(list, "skin " .. i .. ": " .. tostring(err)) + t:eq(dump(list), dump(c.entries), "skin " .. i .. ": entries") + t:eq(dump(Q3Skin.decode(Bytes.reader(assert(Q3Skin.encode(list :: any))))), dump(c.entries), "skin " .. i .. ": round trip") + t:eq(F.detect(c.text, { name = "x.skin" }), "q3skin", "skin " .. i .. ": F.detect") +end +t:eq(Q3Skin.shader(assert(Q3Skin.decode(Bytes.reader(buffer.fromstring(Fx.skins[1].text)))), "H_HEAD"), "models/players/sarge/band.tga", "skin lookup") +local _, e1 = Q3Skin.encode({ { surface = "a,b", shader = "x" } }) +t:check(e1 and e1.code == Err.ARG, "comma in a surface name") +local _, e2 = Q3Skin.decode(Bytes.reader(buffer.fromstring("no comma here\n"))) +t:check(e2 and e2.code == Err.CORRUPT, "line without a comma") +t:fuzz("decode", function(b: buffer) + return Q3Skin.decode(Bytes.reader(b)) +end, { Fx.skins[1].text, Fx.skins[2].text }) +t:done() diff --git a/tests/image/lmp.luau b/tests/image/lmp.luau new file mode 100644 index 0000000..1da2628 --- /dev/null +++ b/tests/image/lmp.luau @@ -0,0 +1,48 @@ +-- image/lmp tests: qpic pictures, palette.lmp and colormap.lmp against Pillow (tools/fixtures/lmp.py), the palette +-- through files, the grey fallback, the qpic writer round trip, errors, the fuzz pass. +local T = require("@tests/T") +local F = require("@rosetta") +local Lmp = require("@rosetta/image/lmp") +local Bytes = require("@rosetta/core/Bytes") +local Crc32 = require("@rosetta/core/Crc32") +local Err = require("@rosetta/core/Err") +local Fx = require("@tests/gen/lmp") + +local t = T.suite("lmp") +t:eq(Lmp.name, "lmp", "name") + +local samples = {} +for _, p in Fx.pics do + local img, err = Lmp.decode(Bytes.reader(buffer.fromstring(p.data)), { palette = Fx.palette }) + t:check(img, p.name .. ": " .. tostring(err)) + t:eq(img.width .. "x" .. img.height, p.w .. "x" .. p.h, p.name .. ": size") + t:eq(Crc32.of(img.pixels), p.crc, p.name .. ": pixels = Pillow (index 255 transparent)") + local opaque = assert(Lmp.decode(Bytes.reader(buffer.fromstring(p.data)), { files = { ["gfx/palette.lmp"] = Fx.palette }, keyed = false })) + t:eq(Crc32.of(opaque.pixels), p.crcOpaque, p.name .. ": opaque, palette through files") + t:eq(opaque.meta.source.palette, true, p.name .. ": palette found") + -- write back: the palette colours map to the same indices + local out = assert(Lmp.encode(img, { palette = Fx.palette })) + t:check(buffer.tostring(out) == p.data, p.name .. ": writer gives the same bytes") + table.insert(samples, p.data) +end +do + local p = Fx.pics[2] + t:eq(F.detect(p.data, { name = "conback.lmp" }), "lmp", "F.detect by size + extension") + local grey = assert(Lmp.decode(Bytes.reader(buffer.fromstring(p.data)))) + t:eq(grey.meta.source.palette, false, "no palette: grey") + local cm = assert(Lmp.decode(Bytes.reader(buffer.fromstring(Fx.colormap.data)), { palette = Fx.palette })) + t:eq(cm.width .. "x" .. cm.height, "256x64", "colormap size") + t:eq(Crc32.of(cm.pixels), Fx.colormap.crc, "colormap = Pillow") + local pal = assert(Lmp.decode(Bytes.reader(buffer.fromstring(Fx.palette)))) + t:eq(Crc32.of(pal.pixels), Fx.palcrc, "palette.lmp swatch = Pillow") + t:eq(#pal.meta.palette, 256, "palette entries") + t:check(buffer.tostring(assert(Lmp.encode(pal, { kind = "palette" }))) == Fx.palette, "palette round trip") + local _, e1 = Lmp.encode(grey) + t:check(e1 and e1.code == Err.ARG, "qpic writer needs the palette") + local _, e2 = Lmp.decode(Bytes.reader(buffer.fromstring(string.sub(p.data, 1, 30))), { kind = "qpic" }) + t:check(e2 and e2.code == Err.CORRUPT or e2 and e2.code == Err.TRUNCATED, "truncated qpic: " .. tostring(e2)) +end +t:fuzz("decode", function(b: buffer) + return Lmp.decode(Bytes.reader(b), { palette = Fx.palette, kind = "qpic" }) +end, samples) +t:done() diff --git a/tests/image/spr.luau b/tests/image/spr.luau new file mode 100644 index 0000000..6d288df --- /dev/null +++ b/tests/image/spr.luau @@ -0,0 +1,67 @@ +-- image/spr tests: Quake / Half-Life (alpha test, index alpha, normal) / SPR32 sprites against the frames written by +-- tools/fixtures/spr.py (pixels, canvas positions from the origins, group delays), the writer round trips (versions 1, +-- 2 and 32), errors, the fuzz pass. +local T = require("@tests/T") +local F = require("@rosetta") +local Spr = require("@rosetta/image/spr") +local Bytes = require("@rosetta/core/Bytes") +local Crc32 = require("@rosetta/core/Crc32") +local Err = require("@rosetta/core/Err") +local Fx = require("@tests/gen/spr") + +local t = T.suite("spr") +t:eq(Spr.name, "spr", "name") + +local samples = {} +for _, s in Fx.sprites do + t:eq(F.detect(s.data), "spr", s.name .. ": F.detect") + local img, err = Spr.decode(Bytes.reader(buffer.fromstring(s.data)), { palette = Fx.palette }) + t:check(img, s.name .. ": " .. tostring(err)) + t:eq(img.width .. "x" .. img.height, s.w .. "x" .. s.h, s.name .. ": canvas") + t:eq(img.meta.origin[1] .. " " .. img.meta.origin[2], s.origin[1] .. " " .. s.origin[2], s.name .. ": origin") + local frames = img.frames or { { image = img, x = 0, y = 0, delay = 0.1 } } + t:eq(#frames, #s.frames, s.name .. ": frames") + for i, want in s.frames do + local f = frames[i] + t:eq(f.x .. "," .. f.y .. " " .. f.image.width .. "x" .. f.image.height, want.x .. "," .. want.y .. " " .. want.w .. "x" .. want.h, s.name .. ": frame " .. i .. " placement") + t:eq(Crc32.of(f.image.pixels), want.crc, s.name .. ": frame " .. i .. " pixels") + t:check(math.abs(f.delay - want.delay) < 1e-6, s.name .. ": frame " .. i .. " delay") + end + t:eq(img.meta.source.version, s.version, s.name .. ": version") + -- write in the same version and read back the same frames + local out, eerr = Spr.encode(img, { version = s.version, palette = if s.version == 2 then Fx.hlpalette else Fx.palette, texFormat = s.tex }) + t:check(out, s.name .. ": encode " .. tostring(eerr)) + local back = assert(Spr.decode(Bytes.reader(out :: buffer), { palette = Fx.palette })) + local bf = back.frames or { { image = back, x = 0, y = 0 } } + local same = #bf == #frames + for i, f in frames do + local g = bf[i] + same = same and g and g.x == f.x and g.y == f.y + if s.version == 32 or s.version == 1 or s.tex == 0 or s.tex == 3 then + same = same and Crc32.of(g.image.pixels) == Crc32.of(f.image.pixels) + end + end + t:check(same, s.name .. ": round trip keeps frames, placement and pixels") + table.insert(samples, s.data) +end +do + local q = Fx.sprites[1] + local img = assert(Spr.decode(Bytes.reader(buffer.fromstring(q.data)), { palette = Fx.palette })) + -- Half-Life from a Quake sprite: a made palette + local hl = assert(Spr.encode(img)) + local back = assert(Spr.decode(Bytes.reader(hl))) + t:eq(back.meta.source.version, 2, "default version 2") + t:eq(back.meta.source.texFormat, "alphatest", "transparent pixels: alpha test") + local grey = assert(Spr.decode(Bytes.reader(buffer.fromstring(q.data)))) + t:eq(grey.meta.source.palette, false, "Quake sprite without a palette: grey") + local _, e1 = Spr.encode(img, { version = 1 }) + t:check(e1 and e1.code == Err.ARG, "version 1 needs a palette") + local _, e2 = Spr.decode(Bytes.reader(buffer.fromstring("IDS2" .. string.rep("\0", 40)))) + t:check(e2 and e2.code == Err.CORRUPT, "Quake II sprite: not IDSP") + local _, e3 = Spr.decode(Bytes.reader(buffer.fromstring(string.sub(q.data, 1, 60))), { palette = Fx.palette }) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated: " .. tostring(e3)) +end +t:fuzz("decode", function(b: buffer) + return Spr.decode(Bytes.reader(b), { palette = Fx.palette }) +end, samples) +t:done() diff --git a/tests/model/bsp.luau b/tests/model/bsp.luau index 358cc5a..4a72e60 100644 --- a/tests/model/bsp.luau +++ b/tests/model/bsp.luau @@ -90,6 +90,40 @@ do t:eq(grey.meta.source.palette, false, "q1 without a palette: grey") end +-- Half-Life / Quake II RGB lightmaps +for _, name in { "hl", "q2" } do + local c = Fx[name] + local s = assert(Bsp.decode(Bytes.reader(buffer.fromstring(c.data)))) :: any + local data = buffer.fromstring(c.data) + local la = buffer.readi32(data, (if name == "q2" then 8 + 7 * 8 else 4 + 8 * 8)) + local atlas + for _, tx in s.textures do + if tx.name == "lightmap" then + atlas = tx.image + end + end + local placed = {} + for _, r in s.meta.lightmaps do + placed[r.face] = r + end + local bad = 0 + for _, want in c.lightmaps do + local r = placed[want.face] + if not r or r.w ~= want.w or r.h ~= want.h then + bad += 1 + else + for k = 0, want.w * want.h - 1 do + local px = buffer.readu32(atlas.pixels, ((r.y + k // want.w) * atlas.width + r.x + k % want.w) * 4) + local o = la + want.ofs + k * 3 + if px ~= 0xFF000000 + buffer.readu8(data, o + 2) * 65536 + buffer.readu8(data, o + 1) * 256 + buffer.readu8(data, o) then + bad += 1 + end + end + end + end + t:check(#c.lightmaps == 12 and bad == 0, name .. ": RGB lightmaps (" .. bad .. " wrong)") +end + do local q2 = brush("q2", Fx.q2, { files = { ["textures/brick.wal"] = Fx.q2.wal } }) t:eq(q2.textures[1].uri, "textures/brick.wal", "q2: .wal URI") @@ -214,4 +248,129 @@ do end t:eq(threw, 0, "q3: mutated lumps never throw") end +-- ericw-tools maps: BSP 29 / BSP2 / 2PSB, lightmap atlas, .lit, visibility and hulls +do + local base: any = nil + for _, name in { "bsp29", "bsp2", "2psb" } do + local c = Fx.ericw[name] + local s, err = Bsp.decode(Bytes.reader(buffer.fromstring(c.data)), { lit = c.lit }) + t:check(s, name .. ": " .. tostring(err)) + local sc = s :: any + t:eq(F.detect(c.data), "bsp", name .. ": F.detect") + t:eq(sc.meta.source.variant, "quake", name .. ": variant") + t:eq(sc.meta.source.layout, ({ bsp29 = nil, bsp2 = "BSP2", ["2psb"] = "2PSB" } :: any)[name], name .. ": layout") + t:eq(sc.meta.skippedFaces, 0, name .. ": every face read") + -- the same compile in three layouts: the same triangles + local all = {} + for _, mesh in sc.meshes do + for _, p in mesh.primitives do + for _, x in Soup.list(Soup.positions(p)) do + table.insert(all, x) + end + end + end + if base then + t:check(near(all, base, 0), name .. ": geometry equals BSP 29's") + else + base = all + end + -- lightmaps: sizes as CalcSurfaceExtents, luxels copied from the lump (coloured from the .lit) + local placed = {} + for _, r in sc.meta.lightmaps do + placed[r.face] = r + end + local atlas + for _, tx in sc.textures do + if tx.name == "lightmap" then + atlas = tx.image + end + end + t:check(atlas ~= nil, name .. ": lightmap atlas") + local data = buffer.fromstring(c.data) + local litBuf = buffer.fromstring(c.lit) + local sizeBad, pixBad = 0, 0 + for _, want in c.lightmaps do + local r = placed[want.face] + if not r or r.w ~= want.w or r.h ~= want.h then + sizeBad += 1 + else + for k = 0, want.w * want.h - 1, 7 do + local x, y = r.x + k % want.w, r.y + k // want.w + local px = buffer.readu32(atlas.pixels, (y * atlas.width + x) * 4) + local o = 8 + (want.ofs + k) * 3 + local exp = 0xFF000000 + buffer.readu8(litBuf, o + 2) * 65536 + buffer.readu8(litBuf, o + 1) * 256 + buffer.readu8(litBuf, o) + if px ~= exp then + pixBad += 1 + end + end + end + end + t:eq(sizeBad, 0, name .. ": lightmap sizes (" .. #c.lightmaps .. " faces)") + t:eq(pixBad, 0, name .. ": lightmap luxels from the .lit") + local _ = data + local prim = sc.meshes[1].primitives[1] + t:check(prim.attributes.TEXCOORD_1 ~= nil, name .. ": TEXCOORD_1") + local mat = sc.materials[prim.material] + t:eq(sc.textures[mat.extras.bsp.lightmap].name, "lightmap", name .. ": material names the atlas") + local lu = Types.Scene.reader(prim.attributes.TEXCOORD_1) :: any + local inRange = true + for k = 0, prim.attributes.TEXCOORD_1.count - 1 do + if lu(k, 0) < 0 or lu(k, 0) > 1 or lu(k, 1) < 0 or lu(k, 1) > 1 then + inRange = false + end + end + t:check(inRange, name .. ": lightmap coordinates inside the atlas") + local grey = assert(Bsp.decode(Bytes.reader(buffer.fromstring(c.data)))) :: any + local gr + for _, r in grey.meta.lightmaps do + if r.face == c.lightmaps[1].face then + gr = r + end + end + local gimg + for _, tx in grey.textures do + if tx.name == "lightmap" then + gimg = tx.image + end + end + local v = buffer.readu8(data, 0) + local _ = v + local px = buffer.readu32(gimg.pixels, (gr.y * gimg.width + gr.x) * 4) + t:eq(bit32.band(px, 0xFF), bit32.band(bit32.rshift(px, 8), 0xFF), name .. ": without .lit: grey luxels") + -- visibility as vis wrote it + t:eq(#sc.meta.bsp.leaves, c.leaves, name .. ": leaves") + local pvsBad = 0 + for leaf, want in c.pvs do + local got = Bsp.pvs(sc, leaf - 1) or {} + if table.concat(got, ",") ~= table.concat(want, ",") then + pvsBad += 1 + end + end + t:eq(pvsBad, 0, name .. ": PVS of every leaf") + t:check(c.visible > 0, name .. ": vis ran") + -- contents in the point hull and the clipping hulls + local cBad = 0 + for _, pr in c.probes do + for h = 0, 2 do + local got = Bsp.contents(sc, pr.p[1], pr.p[2], pr.p[3], h) + if got ~= pr.c[h + 1] then + cBad += 1 + t:note("%s: contents at %s hull %d: %s, want %s", name, table.concat(pr.p, " "), h, tostring(got), tostring(pr.c[h + 1])) + end + end + end + t:eq(cBad, 0, name .. ": contents at the probes") + t:eq(Bsp.contents(sc, -128, -128, 100, 0), -1, name .. ": the room is empty") + t:eq(Bsp.contents(sc, 0, 0, 100, 0), -2, name .. ": the pillar is solid") + t:eq(Bsp.contents(sc, -250, 0, 100, 1), -2, name .. ": hull 1 is solid near a wall") + t:eq(Bsp.contents(sc, 0, 0, -8, 0), -2, name .. ": the floor is solid") + local leaf = Bsp.leafAt(sc, -128, -128, 24) + t:check(leaf and leaf > 0, name .. ": player start leaf") + local seen = Bsp.pvs(sc, leaf :: number) or {} + t:check(table.find(seen, Bsp.leafAt(sc, 0, 0, 220) :: number) ~= nil, name .. ": the light's leaf is visible from the start") + end + t:fuzz("bsp2", function(b: buffer) + return Bsp.decode(Bytes.reader(b), { lit = Fx.ericw.bsp2.lit }) + end, { Fx.ericw.bsp2.data, Fx.ericw["2psb"].data, Fx.ericw.bsp29.data }, { mutations = 60 }) +end t:done() diff --git a/tests/model/map.luau b/tests/model/map.luau new file mode 100644 index 0000000..1710320 --- /dev/null +++ b/tests/model/map.luau @@ -0,0 +1,325 @@ +-- model/map tests: Quake / Valve 220 / Quake II / Quake III .map files against ericw-tools qbsp (CSG'd face area per +-- plane and texture coordinates at every compiled corner, per entity), texture sizes from WAD2 / WAD3 / .wal through +-- files, the patchDef2 against a Bezier evaluation, entities as nodes, write round trips, errors, the fuzz pass. +-- Fixtures: tools/fixtures/map.py. +local T = require("@tests/T") +local F = require("@rosetta") +local MapFmt = require("@rosetta/model/map") +local Bytes = require("@rosetta/core/Bytes") +local Err = require("@rosetta/core/Err") +local Types = require("@rosetta/Types") +local Fx = require("@tests/gen/map") + +local t = T.suite("map") +t:eq(MapFmt.name, "map", "name") + +local function r(x: number, k: number): number + return math.floor(x * k + 0.5) +end +local function key(nx: number, ny: number, nz: number, d: number): string + return string.format("%d %d %d %d", r(nx, 1000), r(ny, 1000), r(nz, 1000), r(d, 100)) +end + +type Tri = { p: { number }, uv: { number }, n: { number }, tex: string } + +local function triangles(s: any, mesh: any): { Tri } + local out: { Tri } = {} + for _, p in mesh.primitives do + local pos = Types.Scene.reader(p.attributes.POSITION) :: any + local uv = Types.Scene.reader(p.attributes.TEXCOORD_0) :: any + local nrm = Types.Scene.reader(p.attributes.NORMAL) :: any + local tex = s.materials[p.material].name + for k = 0, p.indices.count - 1, 3 do + local tri: Tri = { p = {}, uv = {}, n = {}, tex = tex } + for c = 0, 2 do + local v = buffer.readu32(p.indices.data, (k + c) * 4) + for a = 0, 2 do + table.insert(tri.p, pos(v, a)) + end + table.insert(tri.uv, uv(v, 0)) + table.insert(tri.uv, uv(v, 1)) + if c == 0 then + tri.n = { nrm(v, 0), nrm(v, 1), nrm(v, 2) } + end + end + table.insert(out, tri) + end + end + return out +end + +local function area(p: { number }): number + local ux, uy, uz = p[4] - p[1], p[5] - p[2], p[6] - p[3] + local vx, vy, vz = p[7] - p[1], p[8] - p[2], p[9] - p[3] + local cx, cy, cz = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx + return math.sqrt(cx * cx + cy * cy + cz * cz) / 2 +end + +local function polyArea(p: { number }): number + local a = 0 + for k = 1, #p // 3 - 2 do + a += area({ p[1], p[2], p[3], p[k * 3 + 1], p[k * 3 + 2], p[k * 3 + 3], p[k * 3 + 4], p[k * 3 + 5], p[k * 3 + 6] }) + end + return a +end + +-- barycentric coordinates of x on the triangle's plane (nil when outside) +local function bary(tri: Tri, x: number, y: number, z: number): (number?, number?) + local p = tri.p + local ux, uy, uz = p[4] - p[1], p[5] - p[2], p[6] - p[3] + local vx, vy, vz = p[7] - p[1], p[8] - p[2], p[9] - p[3] + local wx, wy, wz = x - p[1], y - p[2], z - p[3] + local uu, uv, vv = ux * ux + uy * uy + uz * uz, ux * vx + uy * vy + uz * vz, vx * vx + vy * vy + vz * vz + local wu, wv = wx * ux + wy * uy + wz * uz, wx * vx + wy * vy + wz * vz + local den = uu * vv - uv * uv + if den == 0 then + return nil, nil + end + local b = (vv * wu - uv * wv) / den + local c = (uu * wv - uv * wu) / den + local tol = 1e-4 + if b < -tol or c < -tol or b + c > 1 + tol then + return nil, nil + end + return b, c +end + +local function compare(label: string, s: any, model: string, faces: any) + local node + for _, n in s.nodes do + if n.extras and n.extras.entity == tonumber(model) then + node = n + end + end + t:check(node and node.mesh, label .. ": entity " .. model .. " has a mesh") + local tris = {} + for _, tri in triangles(s, s.meshes[node.mesh]) do + if tri.tex ~= "base/curve" then -- the patch: qbsp has no patches + table.insert(tris, tri) + end + end + local ours, theirs = {}, {} + for _, tri in tris do + local n = tri.n + local k = key(n[1], n[2], n[3], n[1] * tri.p[1] + n[2] * tri.p[2] + n[3] * tri.p[3]) + ours[k] = (ours[k] or 0) + area(tri.p) + end + for _, f in faces do + local k = key(f.plane[1], f.plane[2], f.plane[3], f.plane[4]) + theirs[k] = (theirs[k] or 0) + polyArea(f.pts) + end + local bad = 0 + for k, a in theirs do + if math.abs((ours[k] or 0) - a) > 0.05 then + bad += 1 + t:note("%s model %s plane %s: %s vs qbsp %s", label, model, k, tostring(ours[k]), tostring(a)) + end + end + for k in ours do + if not theirs[k] then + bad += 1 + end + end + t:eq(bad, 0, label .. ": model " .. model .. " face area per plane") + local miss, off = 0, 0 + for _, f in faces do + local fk = key(f.plane[1], f.plane[2], f.plane[3], f.plane[4]) + for c = 0, #f.pts // 3 - 1 do + local x, y, z = f.pts[c * 3 + 1], f.pts[c * 3 + 2], f.pts[c * 3 + 3] + local s0 = (f.vecs[1] * x + f.vecs[2] * y + f.vecs[3] * z + f.vecs[4]) / f.size[1] + local t0 = (f.vecs[5] * x + f.vecs[6] * y + f.vecs[7] * z + f.vecs[8]) / f.size[2] + local found, best = false, math.huge + for _, tri in tris do + local n = tri.n + if tri.tex == f.tex and key(n[1], n[2], n[3], n[1] * tri.p[1] + n[2] * tri.p[2] + n[3] * tri.p[3]) == fk then + local b, cc = bary(tri, x, y, z) + if b and cc then + found = true + local u = tri.uv[1] + b * (tri.uv[3] - tri.uv[1]) + cc * (tri.uv[5] - tri.uv[1]) + local v = tri.uv[2] + b * (tri.uv[4] - tri.uv[2]) + cc * (tri.uv[6] - tri.uv[2]) + best = math.min(best, math.max(math.abs(u - s0) * f.size[1], math.abs(v - t0) * f.size[2])) + end + end + end + if not found then + miss += 1 + if miss <= 3 then + local on = {} + for _, tri in tris do + local n = tri.n + if key(n[1], n[2], n[3], n[1] * tri.p[1] + n[2] * tri.p[2] + n[3] * tri.p[3]) == fk then + table.insert(on, tri.tex) + end + end + t:note("%s model %s: corner %s %s %s (%s) on %s, ours there: %s", label, model, x, y, z, f.tex, fk, table.concat(on, ",")) + end + elseif best > 0.05 then + off += 1 + end + end + end + t:eq(miss, 0, label .. ": model " .. model .. " every qbsp corner on one of our triangles") + t:eq(off, 0, label .. ": model " .. model .. " texture coordinates match qbsp") +end + +for _, label in { "quake", "valve", "quake2", "quake3" } do + local c = Fx[label] + t:eq(F.detect(c.text), "map", label .. ": F.detect") + local s, err = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { files = c.files, hull = true }) + t:check(s, label .. ": " .. tostring(err)) + local scene = s :: any + t:eq(scene.meta.source.variant, ({ quake = "quake", valve = "valve220", quake2 = "quake2", quake3 = "quake3" } :: any)[label], label .. ": variant") + t:eq(scene.meta.up, "z", label .. ": z up") + for model, faces in c.models do + compare(label, scene, model, faces) + end + -- texture sizes found in the WAD / .wal files (Quake III needs images: 64 x 64 without decodeImage) + for _, m in scene.materials do + local want = c.sizes[m.name] + if want and label ~= "quake3" then + t:check(m.extras.map.width == want[1] and m.extras.map.height == want[2] and m.extras.map.sizeKnown, label .. ": size of " .. m.name) + end + end + -- entities: nodes with their keys in order + t:eq(#scene.meta.entities, 4, label .. ": entities") + local door = scene.nodes[3] + t:eq(door.name, "door1", label .. ": brush entity named by targetname") + t:eq(door.extras.classname, "func_door", label .. ": classname") + t:eq(table.concat(Types.keys(door.extras.keys), ","), "classname,targetname,angle", label .. ": key order") + local start = scene.nodes[4] + t:eq(start.translation and table.concat(start.translation, " "), "-128 -128 24", label .. ": point entity at its origin") + t:check(start.mesh == nil, label .. ": point entity without a mesh") + -- round trip: write, read again, same entities and geometry + local out, eerr = MapFmt.encode(scene) + t:check(out, label .. ": encode " .. tostring(eerr)) + local again = MapFmt.decode(Bytes.reader(out :: buffer), { files = c.files, hull = true }) :: any + t:check(again ~= nil, label .. ": reload") + local a1, a2 = MapFmt.parse(c.text) :: any, MapFmt.parse(out :: buffer) :: any + local same = #a1.entities == #a2.entities + for i, e in a1.entities do + local e2 = a2.entities[i] + same = same and e2 ~= nil and #e.brushes == #e2.brushes + for k, v in e.keys do + same = same and e2.keys[k] == v + end + for bi, b in e.brushes do + local b2 = e2.brushes[bi] + same = same and b.type == b2.type and #(b.faces or {}) == #(b2.faces or {}) + for fi, f in b.faces or {} do + local f2 = b2.faces[fi] + same = same and f.texture == f2.texture and table.concat(f.points, " ") == table.concat(f2.points, " ") + for _, fld in { "offset", "scale", "u", "v", "flags" } do + same = same and table.concat((f :: any)[fld] or {}, " ") == table.concat((f2 :: any)[fld] or {}, " ") + end + same = same and f.rotation == f2.rotation + if f.matrix then + same = same and table.concat(f.matrix[1], " ") == table.concat(f2.matrix[1], " ") and table.concat(f.matrix[2], " ") == table.concat(f2.matrix[2], " ") + end + end + if b.points then + same = same and table.concat(b.points, " ") == table.concat(b2.points, " ") + end + end + end + t:check(same, label .. ": write -> parse gives the same entities, brushes and faces") + t:eq(again.meta.source.variant, scene.meta.source.variant, label .. ": variant survives the round trip") + t:eq(#again.meshes, #scene.meshes, label .. ": meshes survive the round trip") +end + +-- the Quake III patch: our grid = the Bezier evaluation +do + local c = Fx.quake3 + local s = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { files = c.files }) :: any + t:eq(s.meta.source.patches, 1, "quake3: one patch") + local prim + for _, p in s.meshes[1].primitives do + if s.materials[p.material].name == "base/curve" then + prim = p + end + end + t:check(prim, "quake3: patch primitive") + local pos = Types.Scene.reader(prim.attributes.POSITION) :: any + local uv = Types.Scene.reader(prim.attributes.TEXCOORD_0) :: any + t:eq(prim.attributes.POSITION.count, c.patch.w * c.patch.h, "quake3: grid size") + local worst = 0 + for k = 0, c.patch.w * c.patch.h - 1 do + for a = 0, 2 do + worst = math.max(worst, math.abs(pos(k, a) - c.patch.grid[k * 5 + a + 1])) + end + worst = math.max(worst, math.abs(uv(k, 0) - c.patch.grid[k * 5 + 4]) * 64, math.abs(uv(k, 1) - c.patch.grid[k * 5 + 5]) * 64) + end + t:check(worst < 1e-4, "quake3: patch points match the Bezier evaluation (" .. worst .. ")") + t:eq(s.textures[s.materials[prim.material].baseColorTexture.texture].uri, "textures/base/curve", "quake3: texture URI") + local lean = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { patchLevel = 1, skip = { "brick" } }) :: any + for _, p in lean.meshes[1].primitives do + t:check(lean.materials[p.material].name ~= "brick", "skip: brick left out") + end +end + +-- options and conversions +do + local c = Fx.quake + local merged = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { files = c.files, hull = true, merge = true }) :: any + local plain = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { files = c.files }) :: any + local function count(sc: any): number + local n = 0 + for _, p in sc.meshes[1].primitives do + n += p.indices.count + end + return n + end + t:check(count(merged) < count(plain), "hull + merge: fewer triangles than every face") + t:eq(plain.materials[1].extras.map.sizeKnown, true, "sizes from the worldspawn WAD") + local nowad = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text))) :: any + t:eq(nowad.materials[1].extras.map.width, 64, "no WAD: 64 x 64") + local sized = MapFmt.decode(Bytes.reader(buffer.fromstring(c.text)), { textureSizes = { brick = { 8, 8 } } }) :: any + for _, m in sized.materials do + if m.name == "brick" then + t:eq(m.extras.map.width, 8, "textureSizes") + end + end + -- Quake standard -> Valve 220: same texture coordinates + local valve = assert(MapFmt.encode(plain, { variant = "valve220" })) + local v = MapFmt.decode(Bytes.reader(valve), { files = c.files }) :: any + t:eq(v.meta.source.variant, "valve220", "converted to Valve 220") + local u1 = Types.Scene.reader(plain.meshes[1].primitives[1].attributes.TEXCOORD_0) :: any + local u2 = Types.Scene.reader(v.meshes[1].primitives[1].attributes.TEXCOORD_0) :: any + local worst = 0 + for k = 0, plain.meshes[1].primitives[1].attributes.TEXCOORD_0.count - 1 do + worst = math.max(worst, math.abs(u1(k, 0) - u2(k, 0)), math.abs(u1(k, 1) - u2(k, 1))) + end + t:check(worst < 1e-5, "Valve 220 conversion keeps the texture coordinates (" .. worst .. ")") + -- edits: a moved point entity writes its new origin + plain.nodes[4].translation = { 1, 2, 3 } + local moved = MapFmt.parse(assert(MapFmt.encode(plain))) :: any + t:eq(moved.entities[3].keys.origin, "1 2 3", "moved entity origin") + -- through the api + local viaApi = assert(F.model.load(c.text, { files = c.files })) + t:eq(viaApi.meta.source.format, "map", "F.model.load") + local saved = assert(F.save(viaApi, nil, { format = "map" })) + t:check(buffer.len(saved) > 100, "F.save as map") +end + +-- sniffing and errors +do + local build = buffer.create(64) + buffer.writeu32(build, 0, 7) + t:eq(MapFmt.sniff(Bytes.reader(build)), 0, "Build engine (binary) .map: not ours") + t:eq(MapFmt.sniff(Bytes.reader(buffer.fromstring('{"classname": "x"}'))), 0, "JSON: not a map") + t:check(MapFmt.sniff(Bytes.reader(buffer.fromstring('{\n"classname" "worldspawn"\n}'))) > 0.5, "minimal map") + local _, e1 = MapFmt.decode(Bytes.reader(buffer.fromstring('{ "classname" "worldspawn" { ( 0 0 0 ) ( 1 0 0 ) brick'))) + t:check(e1 and e1.code == Err.CORRUPT, "truncated face: " .. tostring(e1)) + local _, e2 = MapFmt.decode(Bytes.reader(buffer.fromstring('{ "classname" "worldspawn" { brushDef3 { } } }'))) + t:check(e2 and e2.code == Err.UNSUPPORTED, "Doom 3 brushDef3: unsupported") + local _, e3 = MapFmt.encode(Types.Scene.new()) + t:check(e3 and e3.code == Err.ARG, "encode without entities") + local bad = assert(MapFmt.decode(Bytes.reader(buffer.fromstring(Fx.quake.text)))) :: any + bad.nodes[2].extras.keys.message = 'a "quoted" value' + local _, e4 = MapFmt.encode(bad) + t:check(e4 and e4.code == Err.ARG, "quotes in a value") +end + +t:fuzz("decode", function(b: buffer) + return MapFmt.decode(Bytes.reader(b), { hull = true, merge = true }) +end, { buffer.fromstring(Fx.quake.text), buffer.fromstring(Fx.quake3.text), buffer.fromstring(Fx.valve.text) }, { mutations = 60, garbage = 20 }) +t:done() diff --git a/tools/bench.luau b/tools/bench.luau index c44889a..cc2a2a4 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1902,3 +1902,24 @@ do jitTune(false) end end + +-- ws-quake: .map brushes to polygons (codecs/model/Brush clip + CSG hull + merge; MB/s of map text) and a compiled +-- BSP with its lightmap atlas and tree (MB/s of file); fixtures tools/fixtures/map.py, tools/fixtures/bsp.py +do + local MapFmt = require("@rosetta/model/map") + local BspFmt = require("@rosetta/model/bsp") + local Bytes = require("@rosetta/core/Bytes") + local MF = require("@tests/gen/map") + local BF = require("@tests/gen/bsp") + local text = buffer.fromstring(MF.quake.text) + bench("map decode (brushes)", 5, buffer.len(text), function() + assert(MapFmt.decode(Bytes.reader(text), { files = MF.quake.files })) + end) + bench("map decode (hull + merge)", 5, buffer.len(text), function() + assert(MapFmt.decode(Bytes.reader(text), { files = MF.quake.files, hull = true, merge = true })) + end) + local bsp = buffer.fromstring(BF.ericw.bsp29.data) + bench("bsp decode (lightmaps, tree)", 5, buffer.len(bsp), function() + assert(BspFmt.decode(Bytes.reader(bsp))) + end) +end diff --git a/tools/fixtures/_qbsp.py b/tools/fixtures/_qbsp.py new file mode 100644 index 0000000..d8127b4 --- /dev/null +++ b/tools/fixtures/_qbsp.py @@ -0,0 +1,202 @@ +# Shared helpers for the Quake map fixtures (brush.py, map.py, bsp.py, wad2.py): WAD2 / WAD3 writing, running +# ericw-tools (qbsp, light, vis from nixpkgs) on a .map, and a reader of the Quake 1 family BSP files they write +# (BSP 29, BSP2, 2PSB: layouts from bspfile.h of the Quake source release and ericw-tools; no code taken). +# wad(lumps, magic) -> bytes: lumps = [(name, type, data)] +# miptex(name, w, h, rng, palette=None) -> bytes (four mip levels of random indices; WAD3 / BSP 30 add the palette) +# compile(ctx, text, files, qbsp_args, light_args=None, vis=False) -> { bsp, obj?, log } +# read_bsp(data) -> dict of the parsed lumps +import math, os, shutil, struct, subprocess, tempfile + +Q1_LUMPS = ["entities", "planes", "miptex", "vertices", "visibility", "nodes", "texinfo", "faces", "lighting", + "clipnodes", "leaves", "marksurfaces", "edges", "surfedges", "models"] + + +def wad(lumps, magic=b"WAD2"): + body = b"" + dirs = [] + for name, typ, data in lumps: + dirs.append(struct.pack("> m, h >> m + px = pixels[m] if pixels else bytes(rng.randrange(256) for _ in range(lw * lh)) + offs.append(o) + levels.append(px) + o += lw * lh + out += struct.pack("<4I", *offs) + b"".join(levels) + if palette is not None: + out += struct.pack("= 4: + n = struct.unpack_from("= 0 else e[1]]) + return pts + + +def face_plane(b, f): + nx, ny, nz, d, _ = b["planes"][f["plane"]] + if f["side"]: + return (-nx, -ny, -nz, -d) + return (nx, ny, nz, d) + + +def write_bsp(b, lumps): + # reassembles a Quake 1 family BSP (b from read_bsp: its variant decides the header) from raw lumps + head = {"BSP2": b"BSP2", "2PSB": b"2PSB"}.get(b["variant"]) or struct.pack(" 0: + return (p3, p2, p1) + return (p1, p2, p3) + + +def box_faces(lo, hi): + (x0, y0, z0), (x1, y1, z1) = lo, hi + return [ + ((x0, y0, z0), (x0, y0 + 1, z0), (x0, y0, z0 + 1)), + ((x1, y1, z1), (x1, y1, z1 + 1), (x1, y1 + 1, z1)), + ((x0, y0, z0), (x0, y0, z0 + 1), (x0 + 1, y0, z0)), + ((x1, y1, z1), (x1 + 1, y1, z1), (x1, y1, z1 + 1)), + ((x0, y0, z0), (x0 + 1, y0, z0), (x0, y0 + 1, z0)), + ((x1, y1, z1), (x1, y1 + 1, z1), (x1 + 1, y1, z1)), + ] + + +def brushes(rng): + out = [] + for i in range(14): + lo = tuple(rng.randrange(-8, 6) * 16 for _ in range(3)) + hi = tuple(lo[k] + rng.randrange(2, 7) * 16 for k in range(3)) + faces = box_faces(lo, hi) + center = tuple((lo[k] + hi[k]) / 2 for k in range(3)) + for _ in range(rng.randrange(0, 3)): + corner = tuple(rng.choice((lo[k], hi[k])) for k in range(3)) + pts = [] + for k in range(3): + p = list(corner) + size = hi[k] - lo[k] + step = rng.randrange(4, size // 2 + 1) + p[k] += step if corner[k] == lo[k] else -step + pts.append(tuple(p)) + faces.append(oriented(pts[0], pts[1], pts[2], center)) + out.append(faces) + return out + + +def num(x): + s = ("%.6f" % x).rstrip("0").rstrip(".") + return "0" if s in ("-0", "") else s + + +def projection(rng, kind): + if kind == "standard": + return [rng.randrange(-64, 65), rng.randrange(-64, 65), rng.choice([0, 90, 180, 270, 15, 30, 45, 33.5]), + rng.choice([1, 0.5, 2, -1, 0.25, 1.5]), rng.choice([1, 0.5, 2, -1, 0.75])] + if kind == "valve": + u = [round(rng.uniform(-1, 1), 4) for _ in range(3)] + v = [round(rng.uniform(-1, 1), 4) for _ in range(3)] + return u + [rng.randrange(-32, 33)] + v + [rng.randrange(-32, 33), 0, rng.choice([1, 0.5, 2, -1]), rng.choice([1, 0.25, 2])] + while True: # qbsp replaces a singular matrix by the default projection + m = [rng.randrange(-8, 9) / 256, rng.randrange(-8, 9) / 256, rng.randrange(-16, 17) / 16, + rng.randrange(-8, 9) / 256, rng.randrange(-8, 9) / 256, rng.randrange(-16, 17) / 16] + if m[0] * m[4] - m[1] * m[3] != 0: + return m + + +def face_line(kind, pts, tex, a): + p = " ".join("( %s )" % " ".join(num(c) for c in q) for q in pts) + if kind == "standard": + return "%s %s %s" % (p, tex, " ".join(num(x) for x in a)) + if kind == "valve": + return "%s %s [ %s ] [ %s ] %s" % (p, tex, " ".join(num(x) for x in a[0:4]), " ".join(num(x) for x in a[4:8]), + " ".join(num(x) for x in a[8:11])) + return "%s ( ( %s ) ( %s ) ) %s 0 0 0" % (p, " ".join(num(x) for x in a[0:3]), " ".join(num(x) for x in a[3:6]), tex) + + +def write_map(kind, bl, rng): + lines = ["// Game: Quake", "{", '"classname" "worldspawn"', '"wad" "tex.wad"'] + if kind == "valve": + lines.append('"mapversion" "220"') + recs = [] + for faces in bl: + lines.append("{") + if kind == "bp": + lines.append("brushDef") + lines.append("{") + rec = [] + for pts in faces: + tex = rng.choice(TEXTURES)[0] + a = projection(rng, kind) + lines.append(face_line(kind, pts, tex, a)) + rec.append({"pts": [float(c) for q in pts for c in q], "tex": tex, "kind": kind, "args": [float(x) for x in a]}) + if kind == "bp": + lines.append("}") + lines.append("}") + recs.append(rec) + lines += ["}", "{", '"classname" "info_player_start"', '"origin" "0 0 0"', "}", ""] + return "\n".join(lines), recs + + +def generate(ctx): + H = helper(ctx) + rng = ctx.rng(777) + lumps = [(n, 0x44, H.miptex(n, w, h, rng)) for n, w, h in TEXTURES] + w2 = H.wad(lumps) + out = {} + for kind in ("standard", "valve", "bp"): + bl = brushes(rng) + text, recs = write_map(kind, bl, rng) + res = H.compile(ctx, text, {"tex.wad": w2}, ["-nofill", "-noclip", "-nopercent"]) + b = H.read_bsp(res["bsp"]) + world = b["models"][0] + first, count = world[14], world[15] + faces = [] + for f in b["faces"][first:first + count]: + ti = b["texinfo"][f["texinfo"]] + tex = b["textures"][ti[8]][0] + faces.append({"plane": list(H.face_plane(b, f)), "pts": [c for p in H.face_points(b, f) for c in p], + "tex": tex, "vecs": list(ti[0:8])}) + out[kind] = {"brushes": recs, "sizes": {n: [w, h] for n, w, h in TEXTURES}, "faces": faces, "map": text} + ctx.emit("brush", out) diff --git a/tools/fixtures/bsp.py b/tools/fixtures/bsp.py index c745159..f5bae2d 100644 --- a/tools/fixtures/bsp.py +++ b/tools/fixtures/bsp.py @@ -6,11 +6,14 @@ # q3: polygon, mesh and patch faces, two lightmaps, vertex colours; plus a .pk3 (zip) of it for assimp. # References: the expected triangles per model and texture (positions, normals, texture coordinates, computed here # with the documented rules), texture CRCs, entities; assimp's soup of the Quake III map. +# ericw: the room of map.py compiled by ericw-tools (qbsp with hulls + vis) as BSP 29, BSP2 and 2PSB; the lighting lump +# filled here at the extents of CalcSurfaceExtents (the nix light has no ray tracer), plus a .lit; expected: lightmap +# sizes per face, the PVS of every leaf (Mod_DecompressVis), contents at probe points in hulls 0..2 (SV_HullPointContents). # tests/gen/bsp.luau { q1 = { data, palette, models = { [model] = { [texture] = { pos, uv, nrm } } }, textures, # entities }, hl = ..., q2 = { ..., wal }, q3 = { ..., lightmaps, patchArea, assimp } } import importlib.util, io, math, os, struct, zipfile, zlib -INPUTS = ["tools/fixtures/_quake_ref.py"] +INPUTS = ["tools/fixtures/_quake_ref.py", "tools/fixtures/_qbsp.py", "tools/fixtures/map.py"] def ref(ctx): @@ -110,7 +113,23 @@ def brush_map(rng, variant, pal): L["vertices"] = b"".join(struct.pack("<3f", *v) for v in verts) L["edges"] = b"".join(struct.pack("<2H", *e) for e in edges) L["surfedges"] = b"".join(struct.pack("= 0 else 1]] for k in range(ne)] + size = [] + for v in (s4, t4): + vals = [q[0] * v[0] + q[1] * v[1] + q[2] * v[2] + v[3] for q in pts] + size.append(math.ceil(max(vals) / 16) - math.floor(min(vals) / 16) + 1) + lms.append({"face": fi, "w": size[0], "h": size[1], "ofs": len(light)}) + fb += struct.pack("> k) & 1 for k in range(8)] + ofs += 1 + else: + bits += [0] * (8 * vis[ofs + 1]) + ofs += 2 + return [k + 1 for k in range(n) if k < len(bits) and bits[k]] + + +def contents(b, hull, p): + def side(plane): + nx, ny, nz, d, _ = b["planes"][plane] + return p[0] * nx + p[1] * ny + p[2] * nz - d + head = b["models"][0][9 + hull] + if hull == 0: + n = head + nn = len(b["nodes"]) + while True: + nd = b["nodes"][n] + c = nd[1] if side(nd[0]) >= 0 else nd[2] + if b["variant"] == "bsp29": + c &= 0xFFFF + if c >= nn: + return b["leaves"][65535 - c][0] + elif c < 0: + return b["leaves"][-c - 1][0] + n = c + n = head + nc = len(b["clipnodes"]) + while n >= 0: + cn = b["clipnodes"][n] + c = cn[1] if side(cn[0]) >= 0 else cn[2] + if b["variant"] == "bsp29": + c &= 0xFFFF + if c > nc: + c -= 65536 + n = c + return n + + +def ericw(ctx, rng): + H = load(ctx, "_qbsp") + M = load(ctx, "map") + B = load(ctx, "brush") + world, door = M.layout(rng) + wad = H.wad([(n, 0x44, H.miptex(n, w, h, rng)) for n, w, h in M.TEX]) + text = M.write(B, "quake", world, door, rng, "tex.wad") + probes = [(0, 0, 220), (-128, -128, 24), (200, 200, 100), (0, 0, 100), (-264, 0, 100), (0, 0, -8), (40, 0, 100), + (-240, -240, 30), (100, -150, 64), (300, 300, 300)] + out = {} + for name, args in (("bsp29", []), ("bsp2", ["-bsp2"]), ("2psb", ["-2psb"])): + res = H.compile(ctx, text, {"tex.wad": wad}, ["-nopercent"] + args, vis=True) + b = H.read_bsp(res["bsp"]) + data, lm = H.light(b, rng) + b = H.read_bsp(data) + lit = b"QLIT" + struct.pack("> m) * (32 >> m))) for m in range(4)] + files["gfx.wad"] = H.wad([("palette", 0x40, pal), ("disc", 0x42, files["disc.lmp"]), + ("brick", 0x44, H.miptex("brick", 32, 32, rng, pixels=mips))]) + S = mod(ctx, "spr") + files["flame.spr"] = S.sprite(rng, 2, [("single", (-16, 16, 32, 32)), ("group", [0.1, 0.2], [(-8, 8, 16, 16), (-8, 8, 16, 16)])], pal)["data"] + Q = mod(ctx, "q3shader") + files["base.shader"] = Q.SCRIPTS[0] + files["sarge.skin"] = Q.SKINS[0] + check.emit_inputs(ctx, files, { + "roomMapText": "room.map", "texWadBytes": "tex.wad", "roomBspBytes": "room.bsp", "quakePaletteBytes": "palette.lmp", + "discLmpBytes": "disc.lmp", "gfxWadBytes": "gfx.wad", "flameSprBytes": "flame.spr", "shaderText": "base.shader", + "skinText": "sarge.skin", + }) diff --git a/tools/fixtures/lmp.py b/tools/fixtures/lmp.py new file mode 100644 index 0000000..d5a7817 --- /dev/null +++ b/tools/fixtures/lmp.py @@ -0,0 +1,39 @@ +# image/lmp fixtures (tools/fixtures.py): qpic .lmp pictures, a palette.lmp and a colormap.lmp written from wad.h / +# draw.c; reference rgba from Pillow (a "P" image with the palette, index 255 transparent for qpics). The palette is +# random: Quake's own is GPL and never committed. +# tests/gen/lmp.luau { palette, pics = { { name, data, w, h, crc, crcOpaque } }, colormap = { data, crc }, palcrc } +import json, struct, zlib + +CODE = r""" +import json, sys, zlib, io +from PIL import Image +job = json.loads(sys.stdin.read()) +out = {} +pal = bytes.fromhex(job["pal"]) +for k, (w, h, hexpix, key) in job["imgs"].items(): + im = Image.frombytes("P", (w, h), bytes.fromhex(hexpix)) + im.putpalette(pal) + if key is not None: + im.info["transparency"] = key + out[k] = zlib.crc32(im.convert("RGBA").tobytes()) +print(json.dumps(out)) +""" + + +def generate(ctx): + rng = ctx.rng(31) + pal = bytes(rng.randrange(256) for _ in range(768)) + imgs, pics = {}, [] + for name, w, h in (("disc", 24, 24), ("conback", 64, 40), ("num_0", 24, 24), ("wide", 3, 1)): + pix = bytes(rng.randrange(256) for _ in range(w * h)) + imgs[name] = [w, h, pix.hex(), 255] + imgs[name + "_o"] = [w, h, pix.hex(), None] + pics.append({"name": name, "data": struct.pack(" tex.wad (WAD2) +# valve: the same layout in Valve 220 with a WAD3 named by a Windows path +# quake2: Quake II faces with contents / flags / value; sizes from textures/.wal +# quake3: brushDef faces + a patchDef2 (qbsp compiles the brushes of a copy without the patch; the patch reference is +# evaluated here: biquadratic Bezier, 4 segments per sub-patch) +# tests/gen/map.luau { [name] = { text, files = { [name] = bytes }, models = { [model] = { faces } }, sizes, patch? } } +import importlib.util, os + +INPUTS = ["tools/fixtures/_qbsp.py", "tools/fixtures/brush.py"] + +TEX = [("brick", 64, 32), ("metal", 32, 128), ("wood", 128, 64), ("+0lava", 64, 64), ("stone", 16, 16)] + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location(name, os.path.join(ctx.root, "tools", "fixtures", name + ".py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def layout(rng): + world = [] + # room [-256, 256] x [-256, 256] x [0, 256], walls 16 thick + lo, hi = (-256, -256, 0), (256, 256, 256) + t = 16 + world.append(((lo[0] - t, lo[1] - t, lo[2] - t), (hi[0] + t, hi[1] + t, lo[2]))) + world.append(((lo[0] - t, lo[1] - t, hi[2]), (hi[0] + t, hi[1] + t, hi[2] + t))) + world.append(((lo[0] - t, lo[1] - t, lo[2]), (lo[0], hi[1] + t, hi[2]))) + world.append(((hi[0], lo[1] - t, lo[2]), (hi[0] + t, hi[1] + t, hi[2]))) + world.append(((lo[0], lo[1] - t, lo[2]), (hi[0], lo[1], hi[2]))) + world.append(((lo[0], hi[1], lo[2]), (hi[0], hi[1] + t, hi[2]))) + world.append(((-32, -32, 0), (32, 32, 192))) # pillar standing on the floor + world.append(((64, 64, -8), (160, 128, 48))) # a box sunk into the floor + door = [((100, -200, 0), (116, -120, 128))] + return world, door + + +def faces_for(B, box, rng, kind): + out = [] + for pts in B.box_faces(*box): + tex = rng.choice(TEX)[0] + out.append((pts, tex, B.projection(rng, "bp" if kind == "quake3" else ("valve" if kind == "valve" else "standard")))) + return out + + +def face_text(B, kind, pts, tex, a, flags): + k = {"quake": "standard", "quake2": "standard", "valve": "valve", "quake3": "bp"}[kind] + line = B.face_line(k, pts, tex, a) + if kind == "quake3": + line = line[: -len(" 0 0 0")] + " " + " ".join(str(x) for x in flags) + elif kind == "quake2": + line += " " + " ".join(str(x) for x in flags) + return line + + +def write(B, kind, world, door, rng, wadkey, patch=None): + head = {"quake": "// Game: Quake\n// Format: Standard\n", "valve": "// Game: Half-Life\n// Format: Valve\n", + "quake2": "// Game: Quake 2\n// Format: Quake2\n", "quake3": "// Game: Quake 3\n// Format: Quake3\n"}[kind] + lines = [head + "{", '"classname" "worldspawn"', '"message" "fixture room"'] + if wadkey: + lines.append('"wad" "%s"' % wadkey) + if kind == "valve": + lines.append('"mapversion" "220"') + for box in world: + lines.append("{") + if kind == "quake3": + lines += ["brushDef", "{"] + for pts, tex, a in faces_for(B, box, rng, kind): + lines.append(face_text(B, kind, pts, tex, a, [0, rng.randrange(0, 4), 0])) + if kind == "quake3": + lines.append("}") + lines.append("}") + if patch: + lines.append(patch) + lines += ["}", "{", '"classname" "func_door"', '"targetname" "door1"', '"angle" "90"'] + for box in door: + lines.append("{") + if kind == "quake3": + lines += ["brushDef", "{"] + for pts, tex, a in faces_for(B, box, rng, kind): + lines.append(face_text(B, kind, pts, tex, a, [1, 0, 5])) + if kind == "quake3": + lines.append("}") + lines.append("}") + lines += ["}", "{", '"classname" "info_player_start"', '"origin" "-128 -128 24"', '"angle" "45"', "}", + "{", '"classname" "light"', '"origin" "0 0 200"', '"light" "300"', "}", ""] + return "\n".join(lines) + + +def bezier_patch(w, h, ctrl, level): + # ctrl[(i * w + j)] row-major (row i, column j) of (x, y, z, s, t); quadratic Bezier per 3 x 3 sub-patch + px, py = (w - 1) // 2, (h - 1) // 2 + gw, gh = px * level + 1, py * level + 1 + out = [] + for gy in range(gh): + sy = min(gy // level, py - 1) + tv = (gy - sy * level) / level + bv = [(1 - tv) ** 2, 2 * tv * (1 - tv), tv * tv] + for gx in range(gw): + sx = min(gx // level, px - 1) + tu = (gx - sx * level) / level + bu = [(1 - tu) ** 2, 2 * tu * (1 - tu), tu * tu] + p = [0.0] * 5 + for j in range(3): + for i in range(3): + c = ctrl[(sy * 2 + j) * w + sx * 2 + i] + for k in range(5): + p[k] += c[k] * bu[i] * bv[j] + out.append(p) + return out, gw, gh + + +def compile_faces(H, ctx, text, files): + res = H.compile(ctx, text, files, ["-nofill", "-noclip", "-nopercent"]) + b = H.read_bsp(res["bsp"]) + models = {} + for mi, m in enumerate(b["models"]): + first, count = m[14], m[15] + faces = [] + for f in b["faces"][first:first + count]: + ti = b["texinfo"][f["texinfo"]] + name, w, h = b["textures"][ti[8]] + assert name and w and h, "qbsp did not find the texture WAD" + faces.append({"plane": list(H.face_plane(b, f)), "pts": [c for p in H.face_points(b, f) for c in p], + "tex": name, "vecs": list(ti[0:8]), "size": [w, h]}) + models[str(mi)] = faces + return models + + +def generate(ctx): + H = load(ctx, "_qbsp") + B = load(ctx, "brush") + rng = ctx.rng(4242) + world, door = layout(rng) + out = {} + wad2 = H.wad([(n, 0x44, H.miptex(n, w, h, rng)) for n, w, h in TEX]) + pal = bytes(rng.randrange(256) for _ in range(768)) + wad3 = H.wad([(n, 0x43, H.miptex(n, w, h, rng, pal)) for n, w, h in TEX], b"WAD3") + sizes = {n: [w, h] for n, w, h in TEX} + # quake + text = write(B, "quake", world, door, rng, "gfx/tex.wad") + out["quake"] = {"text": text, "files": {"gfx/tex.wad": wad2}, "models": compile_faces(H, ctx, text.replace("gfx/tex.wad", "tex.wad"), {"tex.wad": wad2}), "sizes": sizes} + # valve 220 with a WAD3 under a Windows path + text = write(B, "valve", world, door, rng, "\\half-life\\valve\\tex3.wad") + qtext = text.replace("\\half-life\\valve\\tex3.wad", "tex3.wad") + out["valve"] = {"text": text, "files": {"tex3.wad": wad3}, "models": compile_faces(H, ctx, qtext, {"tex3.wad": wad3}), "sizes": sizes} + # quake 2: .wal sizes (qbsp is given the same sizes through a WAD of the same names) + text = write(B, "quake2", world, door, rng, None) + wals = {} + for n, w, h in TEX: + wals["textures/" + n + ".wal"] = (n.encode() + b"\0" * (32 - len(n))) + w.to_bytes(4, "little") + h.to_bytes(4, "little") + bytes(60) + qtext = text.replace('"message" "fixture room"', '"message" "fixture room"\n"wad" "tex.wad"') + out["quake2"] = {"text": text, "files": wals, "models": compile_faces(H, ctx, qtext, {"tex.wad": wad2}), "sizes": sizes} + # quake 3: brushDef + a 5 x 3 patch + W, Hh = 5, 3 + ctrl = [] + for i in range(Hh): + for j in range(W): + ctrl.append([-200 + j * 40, 100 + i * 50, 64 + (48 if i == 1 else 0) + (24 if j % 2 else 0), j / 4, i / 2]) + rows = [] + for j in range(W): # file order: column by column + rows.append("( " + " ".join("( %s )" % " ".join(B.num(x) for x in ctrl[i * W + j]) for i in range(Hh)) + " )") + patch = "{\npatchDef2\n{\nbase/curve\n( %d %d 0 0 0 )\n(\n%s\n)\n}\n}" % (W, Hh, "\n".join(rows)) + text = write(B, "quake3", world, door, rng, "tex.wad", patch) + plain = text.replace(patch + "\n", "") + grid, gw, gh = bezier_patch(W, Hh, ctrl, 4) + out["quake3"] = {"text": text, "files": {"tex.wad": wad2}, "models": compile_faces(H, ctx, plain, {"tex.wad": wad2}), "sizes": sizes, + "patch": {"grid": [c for p in grid for c in p], "w": gw, "h": gh}} + ctx.emit("map", out) diff --git a/tools/fixtures/q3shader.py b/tools/fixtures/q3shader.py new file mode 100644 index 0000000..aa4e15a --- /dev/null +++ b/tools/fixtures/q3shader.py @@ -0,0 +1,117 @@ +# data/q3shader and data/q3skin fixtures (tools/fixtures.py): shader scripts in the style of the Quake III Arena +# Shader Manual (comments, quoted tokens, braces on their own lines or not, several stages) and .skin files; reference +# structure from an independent tokenizer here (COM_ParseExt rules: tokens per line, // and /* */ comments). +# tests/gen/q3shader.luau { scripts = { { text, shaders = { { name, directives, stages } } } }, skins = { { text, entries } } } +import re + +SCRIPTS = [ + """// base walls +textures/base_wall/metalfloor_wall_10 +{ + qer_editorimage textures/base_wall/metalfloor_wall_10.tga + surfaceparm metalsteps + { + map $lightmap + rgbGen identity + } + { + map textures/base_wall/metalfloor_wall_10.tga + blendFunc GL_DST_COLOR GL_ZERO + rgbGen identity + } +} + +textures/sfx/flame1 { + surfaceparm nolightmap + cull none /* both sides */ + q3map_surfacelight 2500 + { + animMap 10 textures/sfx/flame1.tga textures/sfx/flame2.tga textures/sfx/flame3.tga + blendFunc GL_ONE GL_ONE + tcMod scale 1 1 // per frame + } +} +""", + """/* + * a sky and a quoted path + */ +textures/skies/hellsky +{ + skyparms "env/hell sky" 512 - + surfaceparm noimpact + surfaceparm sky + { map textures/skies/clouds.tga + tcMod scroll 0.05 0.06 } +} +models/players/sarge/band +{ + deformVertexes wave 100 sin 0 2 0 1 + { + map models/players/sarge/band.tga + alphaFunc GE128 + depthWrite + } +} +""", +] + +SKINS = [ + "tag_head,\ntag_torso,\nh_head,models/players/sarge/band.tga\nh_cap,models/players/sarge/cigar.tga\n", + "u_torso,models/players/sarge/default.tga\r\nl_legs,models/players/sarge/default.tga\r\n", +] + + +def tokenize(text): + text = re.sub(r"/\*.*?\*/", lambda m: "\n" * m.group(0).count("\n"), text, flags=re.S) + lines = [] + for raw in text.split("\n"): + raw = raw.split("//")[0] if '"' not in raw else raw + cur = [] + for m in re.finditer(r'"([^"]*)"|([{}])|([^\s{}"]+)', raw): + if m.group(2): + if cur: + lines.append(cur) + cur = [] + lines.append([m.group(2)]) + else: + cur.append(m.group(1) if m.group(1) is not None else m.group(3)) + if cur: + lines.append(cur) + return lines + + +def parse(text): + lines = tokenize(text) + out, k = [], 0 + while k < len(lines): + sh = {"name": lines[k][0], "directives": [], "stages": []} + k += 2 + stage = None + while True: + d = lines[k] + k += 1 + if d == ["{"]: + stage = [] + elif d == ["}"]: + if stage is None: + break + sh["stages"].append(stage) + stage = None + elif stage is not None: + stage.append(d) + else: + sh["directives"].append(d) + out.append(sh) + return out + + +def generate(ctx): + skins = [] + for s in SKINS: + entries = [] + for line in s.replace("\r", "").split("\n"): + if line.strip(): + a, b = line.split(",", 1) + entries.append({"surface": a.strip(), "shader": b.strip()}) + skins.append({"text": s, "entries": entries}) + ctx.emit("q3shader", {"scripts": [{"text": s, "shaders": parse(s)} for s in SCRIPTS], "skins": skins}) diff --git a/tools/fixtures/spr.py b/tools/fixtures/spr.py new file mode 100644 index 0000000..5f67b0a --- /dev/null +++ b/tools/fixtures/spr.py @@ -0,0 +1,82 @@ +# image/spr fixtures (tools/fixtures.py): sprites written from spritegn.h (Quake IDSP 1: two single frames and a +# group of three; Half-Life IDSP 2 with its palette, alpha test and index alpha; DarkPlaces SPR32); expected frame +# pixels (rgba CRCs), canvas positions from the frame origins, and group delays from the cumulative intervals. +# tests/gen/spr.luau { palette, sprites = { { name, data, version, w, h, origin, frames = { { x, y, w, h, crc, delay } } } } } +import struct, zlib + + +def frame_bytes(rng, w, h, bpp): + return bytes(rng.randrange(256) for _ in range(w * h * bpp)) + + +def rgba(pix, pal, key=None, mode=None): + out = bytearray() + for i in pix: + if mode == "indexalpha": + out += pal[255 * 3:255 * 3 + 3] + bytes([i]) + elif key is not None and i == key: + out += pal[i * 3:i * 3 + 3] + b"\0" + else: + out += pal[i * 3:i * 3 + 3] + b"\xff" + return zlib.crc32(bytes(out)) + + +def sprite(rng, version, layout, pal, tex=3): + # layout: list of ("single", (ox, oy, w, h)) or ("group", [intervals], [(ox, oy, w, h)]) + singles = [] + body = b"" + frames = [] + for item in layout: + if item[0] == "single": + body += struct.pack(" palette, 255 or 0 keyed); +# plus the WAD2 compiled into a map by ericw-tools qbsp (it reads the miptex lumps: the BSP's copies must match). +# tests/gen/wad2.luau { wad2 = { data, palette, images = { [name] = { w, h, crc, kind } } }, wad3 = ..., bsp } +import importlib.util, os, struct, zlib + +INPUTS = ["tools/fixtures/_qbsp.py"] + + +def helper(ctx): + spec = importlib.util.spec_from_file_location("_qbsp", os.path.join(ctx.root, "tools", "fixtures", "_qbsp.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def rgba(pix, pal, key=None): + out = bytearray() + for i in pix: + if key is not None and i == key: + out += pal[i * 3:i * 3 + 3] + b"\0" + else: + out += pal[i * 3:i * 3 + 3] + b"\xff" + return zlib.crc32(bytes(out)) + + +def generate(ctx): + H = helper(ctx) + rng = ctx.rng(22) + pal = bytes(rng.randrange(256) for _ in range(768)) + images = {} + lumps = [("palette", 0x40, pal)] + con = bytes(rng.randrange(256) for _ in range(128 * 128)) + lumps.append(("conchars", 0x44, con)) + images["conchars"] = {"w": 128, "h": 128, "crc": rgba(con, pal, 0), "kind": "conchars"} + qw, qh = 24, 10 + qp = bytes(rng.randrange(256) for _ in range(qw * qh)) + lumps.append(("disc", 0x42, struct.pack("> m) * (h >> m))) for m in range(4)] + lumps.append((name, 0x44, H.miptex(name, w, h, rng, pixels=mips))) + images[name] = {"w": w, "h": h, "crc": rgba(mips[0], pal, 255 if name[0] == "{" else None), "kind": "miptex", + "mip2": rgba(mips[2], pal, 255 if name[0] == "{" else None)} + wad2 = H.wad(lumps) + out = {"wad2": {"data": wad2, "palette": pal, "images": images, "names": [l[0] for l in lumps]}} + # WAD3 + images3 = {} + lumps3 = [] + for name, w, h in (("CRETE", 32, 32), ("{GRATE", 16, 32)): + p3 = bytes(rng.randrange(256) for _ in range(768)) + mips = [bytes(rng.randrange(256) for _ in range((w >> m) * (h >> m))) for m in range(4)] + lumps3.append((name, 0x43, H.miptex(name, w, h, rng, p3, pixels=mips))) + images3[name] = {"w": w, "h": h, "crc": rgba(mips[0], p3, 255 if name[0] == "{" else None), "kind": "miptex"} + p3 = bytes(rng.randrange(256) for _ in range(768)) + qp = bytes(rng.randrange(256) for _ in range(20 * 12)) + lumps3.append(("LOGO", 0x42, struct.pack("