From 998177e5ab7f83d97ac9fb37f452e4a01d37f7b1 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:12:46 -0500 Subject: [PATCH 1/7] ws-voxel: codecs/text/Nbt (NBT Java / Bedrock / network varint, SNBT parse + print, typed values), data/nbt, data/snbt Shared change: codecs/compress/Deflate gains Deflate.peek(buf, off, len, n) (the first n inflated bytes of a gzip / zlib / raw stream, for sniffing gzip-wrapped NBT) through a backward-compatible prefix flag on Inflate.raw; gunzip's header parsing moved into a local helper both use. --- docs/FORMATS.md | 3 + src/Formats/Registry.luau | 24 + .../codecs/compress/Deflate/Inflate.luau | 14 +- src/Formats/codecs/compress/Deflate/init.luau | 90 ++- src/Formats/codecs/text/Nbt/Binary.luau | 698 ++++++++++++++++++ src/Formats/codecs/text/Nbt/Snbt.luau | 649 ++++++++++++++++ src/Formats/codecs/text/Nbt/Value.luau | 256 +++++++ src/Formats/codecs/text/Nbt/init.luau | 380 ++++++++++ src/Formats/data/nbt/init.luau | 60 ++ src/Formats/data/snbt/init.luau | 63 ++ tests/codecs/deflate.luau | 19 + tests/codecs/nbt.luau | 256 +++++++ tests/data/nbt.luau | 60 ++ tests/data/snbt.luau | 47 ++ tools/fixtures/nbt.py | 152 ++++ 15 files changed, 2745 insertions(+), 26 deletions(-) create mode 100644 src/Formats/codecs/text/Nbt/Binary.luau create mode 100644 src/Formats/codecs/text/Nbt/Snbt.luau create mode 100644 src/Formats/codecs/text/Nbt/Value.luau create mode 100644 src/Formats/codecs/text/Nbt/init.luau create mode 100644 src/Formats/data/nbt/init.luau create mode 100644 src/Formats/data/snbt/init.luau create mode 100644 tests/codecs/nbt.luau create mode 100644 tests/data/nbt.luau create mode 100644 tests/data/snbt.luau create mode 100644 tools/fixtures/nbt.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 0a41a66..51b3d3b 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -62,7 +62,9 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | data | ini | .ini .cfg .conf .inf .desktop | yes | yes | ordered: true | `tests/data/ini.luau` | | data | json | .json .jsonl .ndjson .geojson | yes | yes | ordered: true, streaming: true | `tests/data/json.luau` | | 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 | 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 | xml | .xml .xsd .xsl .xslt .rss .atom .xhtml | yes | yes | namespaces: true, streaming: true | `tests/data/xml.luau` | | data | yaml | .yaml .yml | yes | yes | ordered: true, multiDocument: true, anchors: true | `tests/data/yaml.luau` | @@ -128,6 +130,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. + - codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, - codecs/text/Text: text decoding helpers for the text formats: a UTF-8 BOM is stripped, text that is not valid UTF-8 is - codecs/text/Url: RFC 3986 reference resolution (section 5.2), the classification of a playlist / manifest location (URL, - codecs/text/Xml: XML 1.0 parse (DOM and pull events) and serialize, the engine data/xml, SVG, DAE, 3MF, TMX, plist, ... diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..b7c814e 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -698,6 +698,18 @@ local list: { Entry } = { return require("@formats/data/msgpack") end, }, + { + name = "nbt", + category = "data", + path = "data/nbt", + extensions = { "nbt", "dat", "mcstructure", "dat_old" }, + mime = { "application/x-minecraft-nbt" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, binary = true, ordered = true, typed = true }, + load = function() + return require("@formats/data/nbt") + end, + }, { name = "plist", category = "data", @@ -710,6 +722,18 @@ local list: { Entry } = { return require("@formats/data/plist") end, }, + { + name = "snbt", + category = "data", + path = "data/snbt", + extensions = { "snbt" }, + mime = { "text/x-minecraft-snbt" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, ordered = true, typed = true }, + load = function() + return require("@formats/data/snbt") + end, + }, { name = "toml", category = "data", diff --git a/src/Formats/codecs/compress/Deflate/Inflate.luau b/src/Formats/codecs/compress/Deflate/Inflate.luau index 449e1db..456464f 100644 --- a/src/Formats/codecs/compress/Deflate/Inflate.luau +++ b/src/Formats/codecs/compress/Deflate/Inflate.luau @@ -62,9 +62,10 @@ local function grow(out: buffer, op: number, need: number): (buffer, number) end -- Inflate src[start, endpos) into a buffer. cap: initial output capacity; exact: true = the output must fit in --- cap bytes (an error otherwise), false = grow as needed. +-- cap bytes (an error otherwise), false = grow as needed. prefix (with exact): stop at cap instead of failing and +-- return what was inflated so far (at most cap bytes; Deflate.peek, for sniffing). -- Returns out, outLen, consumedEnd (the input offset just past the final block) or nil, message. -function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean): (buffer?, any, number?) +function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, exact: boolean, prefix: boolean?): (buffer?, any, number?) local out = bcreate(cap) local op = 0 local pos = start @@ -123,6 +124,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex end if op + n > cap then if exact then + if prefix then + return out, op, pos + end return nil, "output larger than expected" end out, cap = grow(out, op, op + n) @@ -295,6 +299,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex if sym < 256 then if op >= cap then if exact then + if prefix then + return out, op, pos + end return nil, "output larger than expected" end out, cap = grow(out, op, op + 1) @@ -388,6 +395,9 @@ function Inflate.raw(src: buffer, start: number, endpos: number, cap: number, ex end if op + len > cap then if exact then + if prefix then + return out, op, pos + end return nil, "output larger than expected" end out, cap = grow(out, op, op + len) diff --git a/src/Formats/codecs/compress/Deflate/init.luau b/src/Formats/codecs/compress/Deflate/init.luau index 37a529b..fd25c71 100644 --- a/src/Formats/codecs/compress/Deflate/init.luau +++ b/src/Formats/codecs/compress/Deflate/init.luau @@ -9,6 +9,7 @@ -- local out, err = Deflate.zlib(buf) -- checks the Adler-32 -- local out, err = Deflate.gunzip(buf) -- checks CRC-32 + ISIZE, concatenates members -- local z = Deflate.compress(buf, { level = 6 }) -- raw deflate; also zlibCompress / gzip +-- local head = Deflate.peek(buf, nil, nil, 512) -- the first 512 inflated bytes of gzip / zlib / raw -- -- Never throws: bad data and bad arguments return nil, Err (core/Err codes TRUNCATED / CORRUPT / CHECKSUM / ARG). local Err = require("@formats/core/Err") @@ -101,6 +102,36 @@ function Deflate.zlib(buf: buffer | string, offset: number?, length: number?, ex return out, consumed + 4 end +-- gzipBody(b, p, e) -> the offset of a gzip member's deflate data (past FEXTRA / FNAME / FCOMMENT / FHCRC) | nil, Err +local function gzipBody(b: buffer, p: number, e: number): (number?, Err.Err?) + local flg = buffer.readu8(b, p + 3) + if flg >= 0x20 then + return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3) + end + local q = p + 10 + if bit32.band(flg, 4) ~= 0 then -- FEXTRA + if q + 2 > e then + return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + end + q += 2 + buffer.readu16(b, q) + end + for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated + if bit32.band(flg, bit) ~= 0 then + while q < e and buffer.readu8(b, q) ~= 0 do + q += 1 + end + q += 1 + end + end + if bit32.band(flg, 2) ~= 0 then -- FHCRC + q += 2 + end + if q >= e then + return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + end + return q, nil +end + -- gunzip(buf, offset?, length?) -> buffer | nil, Err. Members are concatenated; trailing data after a member that is -- not another gzip member (zero padding, garbage) is ignored, as gzip -d does. function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): (buffer?, Err.Err?) @@ -127,30 +158,9 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): if buffer.readu8(b, p + 2) ~= 8 then return nil, Err.new(Err.UNSUPPORTED, "gzip: unknown compression method", p + 2) end - local flg = buffer.readu8(b, p + 3) - if flg >= 0x20 then - return nil, Err.new(Err.CORRUPT, "gzip: reserved flags set", p + 3) - end - local q = p + 10 - if bit32.band(flg, 4) ~= 0 then -- FEXTRA - if q + 2 > e then - return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) - end - q += 2 + buffer.readu16(b, q) - end - for _, bit in { 8, 16 } do -- FNAME, FCOMMENT: zero-terminated - if bit32.band(flg, bit) ~= 0 then - while q < e and buffer.readu8(b, q) ~= 0 do - q += 1 - end - q += 1 - end - end - if bit32.band(flg, 2) ~= 0 then -- FHCRC - q += 2 - end - if q >= e then - return nil, Err.new(Err.TRUNCATED, "gzip: truncated header", q) + local q, herr = gzipBody(b, p, e) + if not q then + return nil, herr end local out, consumed = Deflate.inflate(b, q, e - q) if not out then @@ -191,6 +201,38 @@ function Deflate.gunzip(buf: buffer | string, offset: number?, length: number?): return res, nil end +-- peek(buf, offset?, length?, n) -> buffer | nil, Err: the first n bytes (fewer when the stream is shorter, or up to +-- 258 fewer at a match boundary) a gzip member, zlib stream or raw deflate stream inflates to, without inflating +-- the rest or checking checksums: for sniffing compressed files cheaply. +function Deflate.peek(buf: buffer | string, offset: number?, length: number?, n: number): (buffer?, Err.Err?) + local b, o, l, aerr = args("Deflate.peek", buf, offset, length) + if not b then + return nil, aerr + end + if type(n) ~= "number" or n < 1 then + return nil, Err.new(Err.ARG, "Deflate.peek: bad size " .. tostring(n)) + end + local e = o + l + local q = o + if l >= 18 and buffer.readu8(b, o) == 0x1f and buffer.readu8(b, o + 1) == 0x8b and buffer.readu8(b, o + 2) == 8 then + local herr + q, herr = gzipBody(b, o, e) + if not q then + return nil, herr + end + elseif l >= 6 then + local cmf, flg = buffer.readu8(b, o), buffer.readu8(b, o + 1) + if cmf % 16 == 8 and cmf // 16 <= 7 and (cmf * 256 + flg) % 31 == 0 and bit32.band(flg, 0x20) == 0 then + q = o + 2 + end + end + local out, k = Inflate.raw(b, q :: number, e, n, true, true) + if not out then + return nil, inflateErr(tostring(k), q) + end + return shrink(out, k), nil +end + export type CompressOptions = { level: number?, -- 0 (stored) .. 9 (best); default 6 } diff --git a/src/Formats/codecs/text/Nbt/Binary.luau b/src/Formats/codecs/text/Nbt/Binary.luau new file mode 100644 index 0000000..0ecbfd2 --- /dev/null +++ b/src/Formats/codecs/text/Nbt/Binary.luau @@ -0,0 +1,698 @@ +--!strict +-- codecs/text/Nbt/Binary: binary NBT read and write, from the Minecraft wiki "NBT format" page and wiki.vg "NBT". +-- New code. Three encodings: big-endian (Java Edition files; strings in Java's modified UTF-8, converted to and from +-- UTF-8), little-endian (Bedrock files; UTF-8) and Bedrock's network form (little-endian with zigzag varints for int / +-- long and varint lengths). All thirteen tag types; values per codecs/text/Nbt/Value. Lengths are checked against +-- the bytes left before anything is allocated, and nesting is limited (opts.maxDepth, default 512 like Minecraft). +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Value = require("@formats/codecs/text/Nbt/Value") + +local Binary = {} + +export type Options = { + endian: ("big" | "little")?, -- default "big" (Java) + varint: boolean?, -- Bedrock network NBT (little-endian, varint ints / lengths); implies endian = "little" + nameless: boolean?, -- the root tag has no name (Java network NBT since 1.20.2) + maxDepth: number?, -- nesting limit (default 512) + name: string?, -- write: the root name (default "") +} + +local readu8, readi8, readu32, readi16 = buffer.readu8, buffer.readi8, buffer.readu32, buffer.readi16 +local readf32, readf64, writeu32, readstring = buffer.readf32, buffer.readf64, buffer.writeu32, buffer.readstring +local byteswap = bit32.byteswap +local TWO32 = 4294967296 +local NAMES, IDS = Value.NAMES, Value.IDS +local newTag = Value.TagMeta + +type State = { b: buffer, p: number, e: number, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number, err: string?, scratch: buffer } + +-- ------------------------------------------------------------------------------------------------ modified UTF-8 +-- Java's DataOutput strings: U+0000 as C0 80, supplementary characters as two 3-byte surrogates (CESU-8) +local function fromModified(s: string): string + if not string.find(s, "[\192\237]") then + return s + end + local out = {} + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 0xC0 and string.byte(s, i + 1) == 0x80 then + table.insert(out, "\0") + i += 2 + elseif c == 0xED and i + 5 <= n then + local b2, b3, c4, b5, b6 = string.byte(s, i + 1, i + 5) + if b2 >= 0xA0 and b2 <= 0xAF and c4 == 0xED and b5 >= 0xB0 and b5 <= 0xBF then + local hiS = 0xD000 + (b2 - 0x80) * 64 + (b3 - 0x80) + local loS = 0xD000 + (b5 - 0x80) * 64 + (b6 - 0x80) + table.insert(out, utf8.char(0x10000 + (hiS - 0xD800) * 1024 + (loS - 0xDC00))) + i += 6 + else + table.insert(out, string.char(c)) + i += 1 + end + else + local j = string.find(s, "[\192\237]", i + 1) or n + 1 + table.insert(out, string.sub(s, i, j - 1)) + i = j + end + end + return table.concat(out) +end + +local function toModified(s: string): string + if not string.find(s, "[%z\240-\244]") then + return s + end + local out = {} + local i, n = 1, #s + while i <= n do + local c = string.byte(s, i) + if c == 0 then + table.insert(out, "\192\128") + i += 1 + elseif c >= 0xF0 and c <= 0xF4 and i + 3 <= n then + local b2, b3, b4 = string.byte(s, i + 1, i + 3) + local cp = (c - 0xF0) * 262144 + (b2 - 0x80) * 4096 + (b3 - 0x80) * 64 + (b4 - 0x80) - 0x10000 + local hiS, loS = 0xD800 + cp // 1024, 0xDC00 + cp % 1024 + table.insert(out, string.char(0xED, 0x80 + (hiS - 0xD000) // 64, 0x80 + hiS % 64)) + table.insert(out, string.char(0xED, 0x80 + (loS - 0xD000) // 64, 0x80 + loS % 64)) + i += 4 + else + local j = string.find(s, "[%z\240-\244]", i + 1) or n + 1 + table.insert(out, string.sub(s, i, j - 1)) + i = j + end + end + return table.concat(out) +end +Binary.fromModified = fromModified +Binary.toModified = toModified + +-- ------------------------------------------------------------------------------------------------ read +local function fail(s: State, msg: string): nil + if not s.err then + s.err = msg + end + s.p = s.e + return nil +end + +local function need(s: State, n: number): boolean + if s.p + n > s.e then + fail(s, "truncated") + return false + end + return true +end + +local function u8(s: State): number + if not need(s, 1) then + return 0 + end + local v = readu8(s.b, s.p) + s.p += 1 + return v +end + +local function varuint(s: State): number -- up to 32 bits (5 bytes) + local v, mul = 0, 1 + for _ = 1, 5 do + if not need(s, 1) then + return 0 + end + local c = readu8(s.b, s.p) + s.p += 1 + v += (c % 128) * mul + if c < 128 then + return v % TWO32 + end + mul *= 128 + end + fail(s, "varint too long") + return 0 +end + +local function i16(s: State): number + if not need(s, 2) then + return 0 + end + local p = s.p + s.p = p + 2 + if s.le then + return readi16(s.b, p) + end + local v = readu8(s.b, p) * 256 + readu8(s.b, p + 1) + return if v >= 32768 then v - 65536 else v +end + +local function u32raw(s: State): number + if not need(s, 4) then + return 0 + end + local p = s.p + s.p = p + 4 + local v = readu32(s.b, p) + return if s.le then v else byteswap(v) +end + +local function i32(s: State): number + if s.net then + local n = varuint(s) + return if n % 2 == 0 then n // 2 else -(n + 1) // 2 + end + local v = u32raw(s) + return if v >= 0x80000000 then v - TWO32 else v +end + +-- a length: i32 (zigzag varint in network NBT) +local function len(s: State): number + return i32(s) +end + +local function i64(s: State): (number, number) -- hi, lo + if s.net then + local lo, hi, sh = 0, 0, 0 + while true do + if sh >= 70 or not need(s, 1) then + fail(s, "varint too long") + return 0, 0 + end + local c = readu8(s.b, s.p) + s.p += 1 + local d = c % 128 + if sh < 32 then + local x = d * 2 ^ sh + lo += x % TWO32 + hi = (hi + x // TWO32) % TWO32 + else + hi = (hi + d * 2 ^ (sh - 32)) % TWO32 + end + sh += 7 + if c < 128 then + break + end + end + local odd = lo % 2 == 1 + lo = lo // 2 + (hi % 2) * 0x80000000 + hi = hi // 2 + if odd then + hi, lo = TWO32 - 1 - hi, TWO32 - 1 - lo + end + return hi, lo + end + if s.le then + local lo = u32raw(s) + return u32raw(s), lo + end + local hi = u32raw(s) + return hi, u32raw(s) +end + +local function f32(s: State): number + local v = u32raw(s) + writeu32(s.scratch, 0, v) + return readf32(s.scratch, 0) +end + +local function f64(s: State): number + local hi, lo + if s.le then + lo = u32raw(s) + hi = u32raw(s) + else + hi = u32raw(s) + lo = u32raw(s) + end + writeu32(s.scratch, 0, lo) + writeu32(s.scratch, 4, hi) + return readf64(s.scratch, 0) +end + +local function str(s: State): string + local n + if s.net then + n = varuint(s) + else + n = i16(s) % 65536 + end + if not need(s, n) then + return "" + end + local v = readstring(s.b, s.p, n) + s.p += n + return if s.java then fromModified(v) else v +end + +local function tag(name: string, v: any): any + return setmetatable({ type = name, value = v }, newTag) +end + +-- the smallest encoded size of one element, to bound list lengths before allocating +local MIN = { [0] = 0, 1, 2, 4, 8, 4, 8, 4, 2, 5, 1, 4, 4 } +local MIN_NET = { [0] = 0, 1, 2, 1, 1, 4, 8, 1, 1, 2, 1, 1, 1 } + +local payload: (State, number) -> any + +local function count(s: State, n: number, size: number): boolean + if n < 0 then + fail(s, "negative length " .. n) + return false + end + if n * size > s.e - s.p then + fail(s, "truncated: " .. n .. " elements past the end") + return false + end + return true +end + +payload = function(s: State, id: number): any + if id == 3 then + return i32(s) + elseif id == 8 then + return str(s) + elseif id == 10 then + s.depth += 1 + if s.depth > s.maxDepth then + return fail(s, "limit: nested deeper than " .. s.maxDepth) + end + local o, keys = {}, {} + while true do + local t = u8(s) + if s.err then + return nil + end + if t == 0 then + break + end + if t > 12 then + return fail(s, "bad tag type " .. t) + end + local k = str(s) + local v = payload(s, t) + if s.err then + return nil + end + if o[k] == nil then + table.insert(keys, k) + end + o[k] = v + end + s.depth -= 1 + return Types.object(o, keys) + elseif id == 1 then + if not need(s, 1) then + return nil + end + s.p += 1 + return tag("byte", readi8(s.b, s.p - 1)) + elseif id == 2 then + return tag("short", i16(s)) + elseif id == 4 then + local hi, lo = i64(s) + return tag("long", Value.fromHiLo(hi, lo)) + elseif id == 5 then + return tag("float", f32(s)) + elseif id == 6 then + return tag("double", f64(s)) + elseif id == 7 then + local n = len(s) + if not count(s, n, 1) then + return nil + end + local out = buffer.create(n) + buffer.copy(out, 0, s.b, s.p, n) + s.p += n + return out + elseif id == 9 then + local et = u8(s) + local n = len(s) + if s.err then + return nil + end + if et > 12 then + return fail(s, "bad list element type " .. et) + end + if et == 0 and n > 0 then + return fail(s, "list of end tags with " .. n .. " elements") + end + if not count(s, n, (if s.net then MIN_NET else MIN)[et]) then + return nil + end + s.depth += 1 + if s.depth > s.maxDepth then + return fail(s, "limit: nested deeper than " .. s.maxDepth) + end + local out = table.create(n) + for i = 1, n do + local v = payload(s, et) + if s.err then + return nil + end + out[i] = v + end + s.depth -= 1 + Value.setListType(out, NAMES[et]) + return out + elseif id == 11 then + local n = len(s) + if not count(s, n, if s.net then 1 else 4) then + return nil + end + local out = table.create(n) + for i = 1, n do + out[i] = i32(s) + end + return tag("intArray", out) + elseif id == 12 then + local n = len(s) + if not count(s, n, if s.net then 1 else 8) then + return nil + end + local out = buffer.create(n * 8) + if s.net then + for i = 0, n - 1 do + local hi, lo = i64(s) + writeu32(out, i * 8, lo) + writeu32(out, i * 8 + 4, hi) + end + elseif s.le then + buffer.copy(out, 0, s.b, s.p, n * 8) + s.p += n * 8 + else + local b, p = s.b, s.p + for i = 0, n - 1 do + local q = p + i * 8 + writeu32(out, i * 8 + 4, byteswap(readu32(b, q))) + writeu32(out, i * 8, byteswap(readu32(b, q + 4))) + end + s.p = p + n * 8 + end + return tag("longArray", out) + end + return fail(s, "bad tag type " .. id) +end + +-- read(buf, pos, limit, opts?) -> value, rootName, endPos | nil, message, at +function Binary.read(b: buffer, pos: number, limit: number, opts: Options?): (any, any, number?) + local o: Options = opts or {} + local net = o.varint == true + local le = net or o.endian == "little" + local s: State = { + b = b, + p = pos, + e = limit, + le = le, + net = net, + java = not le, + depth = 0, + maxDepth = o.maxDepth or 512, + err = nil, + scratch = buffer.create(8), + } + local id = u8(s) + if s.err then + return nil, s.err, pos + end + if id == 0 or id > 12 then + return nil, "bad root tag type " .. id, pos + end + local name = if o.nameless then "" else str(s) + local v = payload(s, id) + if s.err then + return nil, s.err, s.p + end + return v, name, s.p +end + +-- ------------------------------------------------------------------------------------------------ write +type WState = { w: Bytes.Writer, le: boolean, net: boolean, java: boolean, depth: number, maxDepth: number } + +local function wvaruint(w: Bytes.Writer, v: number) + v %= TWO32 + while v >= 128 do + w:u8(v % 128 + 128) + v //= 128 + end + w:u8(v) +end + +local function wi32(ws: WState, v: number) + v %= TWO32 -- two's complement + if ws.net then + local sv = if v >= 0x80000000 then v - TWO32 else v + wvaruint(ws.w, if sv >= 0 then sv * 2 else -sv * 2 - 1) + elseif ws.le then + ws.w:u32le(v) + else + ws.w:u32be(v) + end +end + +local function wi16(ws: WState, v: number) + v %= 65536 + if ws.le then + ws.w:u16le(v) + else + ws.w:u16be(v) + end +end + +local function wi64(ws: WState, hi: number, lo: number) + if ws.net then + -- zigzag: (n << 1) ^ (n >> 63) + local neg = hi >= 0x80000000 + local zh = (hi * 2) % TWO32 + (if lo >= 0x80000000 then 1 else 0) + local zl = (lo * 2) % TWO32 + if neg then + zh, zl = TWO32 - 1 - zh, TWO32 - 1 - zl + end + while zh > 0 or zl >= 128 do + ws.w:u8(zl % 128 + 128) + zl = zl // 128 + (zh % 128) * 0x2000000 + zh //= 128 + end + ws.w:u8(zl) + elseif ws.le then + ws.w:u32le(lo) + ws.w:u32le(hi) + else + ws.w:u32be(hi) + ws.w:u32be(lo) + end +end + +local function wstr(ws: WState, s: string): string? + local v = if ws.java then toModified(s) else s + if ws.net then + wvaruint(ws.w, #v) + else + if #v > 65535 then + return "string longer than 65535 bytes" + end + wi16(ws, #v) + end + ws.w:string(v) + return nil +end + +local function integer(v: any, lo: number, hi: number, what: string): (number?, string?) + local n = if type(v) == "boolean" then (if v then 1 else 0) else v + if type(n) ~= "number" or n % 1 ~= 0 or n < lo or n > hi then + return nil, "bad " .. what .. " value " .. tostring(n) + end + return n, nil +end + +local wpayload: (WState, string, any) -> string? + +local function wlist(ws: WState, v: { any }): string? + local lt = Value.listType(v) + local n = #v + local wrap = false + if not lt then + if n == 0 then + lt = "end" + else + local t1, e1 = Value.typeOf(v[1]) + if not t1 then + return e1 + end + lt = t1 + end + end + for i = 1, n do + local t, e = Value.typeOf(v[i]) + if not t then + return e + end + if t ~= lt then + wrap = true -- mixed element types: every element becomes a compound { [""] = value }, as Minecraft does + end + end + if wrap then + lt = "compound" + end + if lt == "end" and n > 0 then + return "a list of end tags cannot hold elements" + end + ws.w:u8(IDS[lt :: string]) + wi32(ws, n) + for i = 1, n do + local x = v[i] + if wrap and Value.typeOf(x) ~= "compound" then + x = Types.object({ [""] = x }, { "" }) + end + local e = wpayload(ws, lt :: string, x) + if e then + return e + end + end + return nil +end + +wpayload = function(ws: WState, t: string, v: any): string? + local w = ws.w + local x = if Value.isTag(v) then v.value else v + if t == "int" then + local n, e = integer(x, -2147483648, 4294967295, "int") + if not n then + return e + end + wi32(ws, n) + elseif t == "string" then + if type(x) ~= "string" then + return "bad string value" + end + return wstr(ws, x) + elseif t == "compound" then + ws.depth += 1 + if ws.depth > ws.maxDepth then + return "nested deeper than " .. ws.maxDepth .. " (a cycle?)" + end + for _, k in Types.keys(v) do + if type(k) ~= "string" then + return "compound key " .. tostring(k) .. " is not a string" + end + local c = v[k] + local ct, e = Value.typeOf(c) + if not ct then + return e .. " (key " .. k .. ")" + end + w:u8(IDS[ct :: string]) + e = wstr(ws, k) + if e then + return e + end + e = wpayload(ws, ct :: string, c) + if e then + return e + end + end + w:u8(0) + ws.depth -= 1 + elseif t == "list" then + ws.depth += 1 + if ws.depth > ws.maxDepth then + return "nested deeper than " .. ws.maxDepth .. " (a cycle?)" + end + local e = wlist(ws, v) + if e then + return e + end + ws.depth -= 1 + elseif t == "byte" then + local n, e = integer(x, -128, 255, "byte") + if not n then + return e + end + w:u8(n % 256) + elseif t == "short" then + local n, e = integer(x, -32768, 65535, "short") + if not n then + return e + end + wi16(ws, n) + elseif t == "long" then + local hi, lo = Value.toHiLo(x) + if not hi then + return "bad long value " .. tostring(x) + end + wi64(ws, hi, lo :: number) + elseif t == "float" or t == "double" then + if type(x) ~= "number" then + return "bad " .. t .. " value " .. tostring(x) + end + if t == "float" then + if ws.le then + w:f32le(x) + else + w:f32be(x) + end + elseif ws.le then + w:f64le(x) + else + w:f64be(x) + end + elseif t == "byteArray" then + if type(x) ~= "buffer" then + return "bad byteArray value" + end + wi32(ws, buffer.len(x)) + w:bytes(x) + elseif t == "intArray" then + if type(x) ~= "table" then + return "bad intArray value" + end + wi32(ws, #x) + for i = 1, #x do + local n, e = integer(x[i], -2147483648, 4294967295, "intArray element") + if not n then + return e + end + wi32(ws, n) + end + elseif t == "longArray" then + if type(x) ~= "buffer" or buffer.len(x) % 8 ~= 0 then + return "bad longArray value (a buffer of 8-byte little-endian longs)" + end + local n = buffer.len(x) // 8 + wi32(ws, n) + if ws.le and not ws.net then + w:bytes(x) + else + for i = 0, n - 1 do + wi64(ws, buffer.readu32(x, i * 8 + 4), buffer.readu32(x, i * 8)) + end + end + else + return "cannot write tag type " .. t + end + return nil +end + +-- write(value, opts?) -> buffer | nil, message +function Binary.write(v: any, opts: Options?): (buffer?, string?) + local o: Options = opts or {} + local net = o.varint == true + local le = net or o.endian == "little" + local t, e = Value.typeOf(v) + if not t then + return nil, e + end + local ws: WState = { w = Bytes.writer(1024), le = le, net = net, java = not le, depth = 0, maxDepth = o.maxDepth or 512 } + ws.w:u8(IDS[t :: string]) + if not o.nameless then + e = wstr(ws, o.name or "") + if e then + return nil, e + end + end + e = wpayload(ws, t :: string, v) + if e then + return nil, e + end + return ws.w:finish(), nil +end + +return Binary diff --git a/src/Formats/codecs/text/Nbt/Snbt.luau b/src/Formats/codecs/text/Nbt/Snbt.luau new file mode 100644 index 0000000..7dcc0f3 --- /dev/null +++ b/src/Formats/codecs/text/Nbt/Snbt.luau @@ -0,0 +1,649 @@ +--!strict +-- codecs/text/Nbt/Snbt: stringified NBT (the text form of /data and /give), parse and print. New code, from the +-- Minecraft wiki "NBT format" SNBT section (Java 1.21.5 grammar). Parses: compounds, lists, [B; ...] [I; ...] [L; ...] +-- arrays, quoted strings ('...' / "..." with \\ \' \" \n \t \r \b \f \s \xNN \uNNNN \UNNNNNNNN escapes) and unquoted +-- strings, numbers with b / s / i / l / f / d suffixes (any case, signed / unsigned s / u prefix), underscores, hex +-- 0x and binary 0b integers, exponents, true / false (bytes 1 / 0), NaN / Infinity with a float suffix, trailing +-- commas. Not supported: the 1.21.5 operations bool(...) / uuid(...) and \N{name} escapes. Prints Minecraft's +-- compact form (or indented); floats print as the shortest text that reads back to the same value. +local Types = require("@formats/Types") +local Value = require("@formats/codecs/text/Nbt/Value") + +local Snbt = {} + +export type ParseOptions = { maxDepth: number? } +export type PrintOptions = { + indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact) + quote: string?, -- the string quote, '"' (default) or "'"; the other one is used when it needs fewer escapes +} + +local byte, sub, find = string.byte, string.sub, string.find +local TWO32 = 4294967296 + +local function tag(name: string, v: any): any + return setmetatable({ type = name, value = v }, Value.TagMeta) +end + +-- ------------------------------------------------------------------------------------------------ parse +type P = { s: string, i: number, n: number, err: string?, at: number, depth: number, maxDepth: number } + +local function fail(p: P, msg: string): nil + if not p.err then + p.err, p.at = msg, p.i + end + p.i = p.n + 1 + return nil +end + +local function ws(p: P) + local _, e = find(p.s, "^%s*", p.i) + p.i = (e :: number) + 1 +end + +local function isUnquoted(c: number): boolean + return (c >= 48 and c <= 57) or (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or c == 45 or c == 46 or c == 43 +end + +local ESC: { [string]: string } = { ["\\"] = "\\", ["'"] = "'", ['"'] = '"', n = "\n", t = "\t", r = "\r", b = "\b", f = "\f", s = " " } + +local function quoted(p: P): string? + local q = sub(p.s, p.i, p.i) + p.i += 1 + local out = {} + while true do + local j = find(p.s, if q == '"' then '["\\]' else "['\\]", p.i) + if not j then + return fail(p, "unterminated string") + end + table.insert(out, sub(p.s, p.i, j - 1)) + if sub(p.s, j, j) == q then + p.i = j + 1 + return table.concat(out) + end + local c = sub(p.s, j + 1, j + 1) + if ESC[c] then + table.insert(out, ESC[c]) + p.i = j + 2 + elseif c == "x" or c == "u" or c == "U" then + local nd = if c == "x" then 2 elseif c == "u" then 4 else 8 + local hex = sub(p.s, j + 2, j + 1 + nd) + if #hex ~= nd or find(hex, "[^%x]") then + p.i = j + return fail(p, "bad \\" .. c .. " escape") + end + local cp = tonumber(hex, 16) :: number + if cp > 0x10FFFF or (cp >= 0xD800 and cp <= 0xDFFF) then + p.i = j + return fail(p, "bad code point in \\" .. c .. " escape") + end + table.insert(out, utf8.char(cp)) + p.i = j + 2 + nd + else + p.i = j + return fail(p, "bad escape \\" .. c) + end + end +end + +-- number text -> a value, or nil when it is not a number (then it is an unquoted string) +local INT_RANGE: { [string]: { number } } = { + b = { -128, 127, 255 }, + s = { -32768, 32767, 65535 }, + i = { -2147483648, 2147483647, 4294967295 }, +} +local INT_NAME = { b = "byte", s = "short", i = "int", l = "long" } + +local function integer(t: string): any + local sign, body = string.match(t, "^([+-]?)(.+)$") + body = string.gsub(body :: string, "_", "") :: string + local radix, digits, suffix = 10, body, "" + local low = string.lower(body) + local m, sfx + if sub(low, 1, 2) == "0x" then + -- b and s are hex digits: a byte / short suffix needs its signedness (0x7Fsb, 0xFFub) + m, sfx = string.match(sub(body, 3), "^(%x+)([sSuU][bBsSiIlL])$") + if not m then + m, sfx = string.match(sub(body, 3), "^(%x+)([iIlL]?)$") + end + if not m then + return nil + end + radix = 16 + elseif sub(low, 1, 2) == "0b" then + m, sfx = string.match(sub(body, 3), "^([01]+)([sSuU]?[bBsSiIlL]?)$") + if m then + radix = 2 + end + end + if not m then + m, sfx = string.match(body, "^(%d+)([sSuU]?[bBsSiIlL]?)$") + if not m then + return nil + end + end + digits, suffix = m :: string, string.lower(sfx :: string) + local unsigned = false + if #suffix == 2 then + unsigned = sub(suffix, 1, 1) == "u" + suffix = sub(suffix, 2) + elseif suffix == "u" then + return nil + end + if suffix == "" then + suffix = "i" + end + if unsigned and sign == "-" then + return nil + end + -- the magnitude as (hi, lo) + local hi, lo = 0, 0 + for k = 1, #digits do + local c = byte(digits, k) + local d = if c <= 57 then c - 48 elseif c >= 97 then c - 87 else c - 55 + local x = lo * radix + d + local carry = x // TWO32 + lo = x - carry * TWO32 + hi = hi * radix + carry + if hi >= TWO32 then + return nil + end + end + if suffix == "l" then + local neg = sign == "-" + if radix == 10 then + if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or not neg)) then + return nil + end + end + if neg and (hi > 0 or lo > 0) then + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 + end + return tag("long", Value.fromHiLo(hi, lo)) + end + if hi > 0 then + return nil + end + local r = INT_RANGE[suffix] + local v = lo + if sign == "-" then + v = -v + end + if radix ~= 10 and not unsigned and sign ~= "-" and v > r[2] and v <= r[3] then + v -= r[3] + 1 -- hex / binary literals wrap into the signed range (0xFFb = -1b) + elseif unsigned then + if v > r[3] then + return nil + end + if v > r[2] then + v -= r[3] + 1 + end + end + if v < r[1] or v > r[2] then + return nil + end + if suffix == "i" then + return v + end + return tag(INT_NAME[suffix], v) +end + +local function number(t: string): any + local low = string.lower(t) + if low == "true" then + return tag("byte", 1) + elseif low == "false" then + return tag("byte", 0) + end + local sfx = sub(low, -1) + local special = string.match(low, "^([+-]?)infinity[fd]$") + if special then + return tag(if sfx == "f" then "float" else "double", if special == "-" then -math.huge else math.huge) + elseif low == "nanf" or low == "nand" then + return tag(if sfx == "f" then "float" else "double", 0 / 0) + end + local iv = integer(t) + if iv ~= nil then + return iv + end + local body = string.gsub(t, "_", "") + local m, fs = string.match(body, "^([+-]?[%d%.]+[eE]?[+-]?%d*)([fFdD]?)$") + if not m then + return nil + end + -- mantissa digits[.digits] or .digits, an optional exponent; without a fraction or an exponent a suffix is needed + local mant, ex = string.match(m :: string, "^(.-)([eE][+-]?%d+)$") + if not mant then + mant = m + end + if not (string.match(mant :: string, "^[+-]?%d+%.?%d*$") or string.match(mant :: string, "^[+-]?%.%d+$")) then + return nil + end + if fs == "" and not ex and not find(mant :: string, ".", 1, true) then + return nil + end + local v = tonumber(m) + if not v then + return nil + end + if string.lower(fs :: string) == "f" then + local b = buffer.create(4) + buffer.writef32(b, 0, v) + return tag("float", buffer.readf32(b, 0)) + end + return tag("double", v) +end + +local parseValue: (P) -> any + +local function token(p: P): string + local j = p.i + while j <= p.n and isUnquoted(byte(p.s, j)) do + j += 1 + end + local t = sub(p.s, p.i, j - 1) + p.i = j + return t +end + +local function key(p: P): string? + ws(p) + local c = sub(p.s, p.i, p.i) + if c == '"' or c == "'" then + return quoted(p) + end + local t = token(p) + if t == "" then + return fail(p, "expected a key") + end + return t +end + +local ARRAY = { B = "byte", I = "int", L = "long" } + +local function array(p: P, kind: string): any + local items = {} + ws(p) + if sub(p.s, p.i, p.i) ~= "]" then + while true do + ws(p) + local at = p.i + local t = token(p) + local v = if t ~= "" then number(t) else nil + local vt = Value.typeOf(v) + if v == nil or (vt ~= "byte" and vt ~= "short" and vt ~= "int" and vt ~= "long") then + p.i = at + return fail(p, "expected an integer in a " .. kind .. " array") + end + local x: any = if Value.isTag(v) then (v :: any).value else v + if kind == "byte" and (x < -128 or x > 127) or kind == "int" and vt == "long" then + p.i = at + return fail(p, "value out of range in a " .. kind .. " array") + end + table.insert(items, x) + ws(p) + local c = sub(p.s, p.i, p.i) + p.i += 1 + if c == "]" then + break + elseif c ~= "," then + p.i -= 1 + return fail(p, "expected , or ]") + end + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i += 1 + break + end + end + else + p.i += 1 + end + if kind == "byte" then + local b = buffer.create(#items) + for i, x in items do + buffer.writei8(b, i - 1, x) + end + return b + elseif kind == "int" then + return tag("intArray", items) + end + return Value.longArray(items) +end + +parseValue = function(p: P): any + ws(p) + if p.i > p.n then + return fail(p, "expected a value") + end + local c = sub(p.s, p.i, p.i) + if c == "{" then + p.depth += 1 + if p.depth > p.maxDepth then + return fail(p, "limit: nested deeper than " .. p.maxDepth) + end + p.i += 1 + local o, keys = {}, {} + ws(p) + if sub(p.s, p.i, p.i) == "}" then + p.i += 1 + else + while true do + local k = key(p) + if p.err then + return nil + end + ws(p) + if sub(p.s, p.i, p.i) ~= ":" then + return fail(p, "expected :") + end + p.i += 1 + local v = parseValue(p) + if p.err then + return nil + end + if o[k :: string] == nil then + table.insert(keys, k) + end + o[k :: string] = v + ws(p) + local d = sub(p.s, p.i, p.i) + p.i += 1 + if d == "}" then + break + elseif d ~= "," then + p.i -= 1 + return fail(p, "expected , or }") + end + ws(p) + if sub(p.s, p.i, p.i) == "}" then + p.i += 1 + break + end + end + end + p.depth -= 1 + return Types.object(o, keys) + elseif c == "[" then + p.depth += 1 + if p.depth > p.maxDepth then + return fail(p, "limit: nested deeper than " .. p.maxDepth) + end + p.i += 1 + local kind = string.match(p.s, "^%s*([BIL])%s*;", p.i) + if kind then + local _, e = find(p.s, "^%s*[BIL]%s*;", p.i) + p.i = (e :: number) + 1 + local v = array(p, ARRAY[kind]) + p.depth -= 1 + return v + end + local items = {} + local lt: string? = nil + local mixed = false + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i += 1 + else + while true do + local v = parseValue(p) + if p.err then + return nil + end + local t = Value.typeOf(v) + if lt == nil then + lt = t + elseif t ~= lt then + mixed = true + end + table.insert(items, v) + ws(p) + local d = sub(p.s, p.i, p.i) + p.i += 1 + if d == "]" then + break + elseif d ~= "," then + p.i -= 1 + return fail(p, "expected , or ]") + end + ws(p) + if sub(p.s, p.i, p.i) == "]" then + p.i += 1 + break + end + end + end + p.depth -= 1 + if not mixed then + Value.setListType(items, lt or "end") + end + return items + elseif c == '"' or c == "'" then + return quoted(p) + end + local at = p.i + local t = token(p) + if t == "" then + return fail(p, "unexpected character " .. string.format("%q", c)) + end + local v = number(t) + if v == nil then + if string.match(t, "^[+-]?%d[%d_]*[sSuU]?[bBsSiIlL]$") then + p.i = at + return fail(p, "number out of range: " .. t) + end + return t + end + return v +end + +-- parse(text, opts?) -> value | nil, message, position (1-based) +function Snbt.parse(s: string, opts: ParseOptions?): (any, string?, number?) + local p: P = { s = s, i = 1, n = #s, err = nil, at = 1, depth = 0, maxDepth = (opts and opts.maxDepth) or 512 } + local v = parseValue(p) + if p.err then + return nil, p.err, p.at + end + ws(p) + if p.i <= p.n then + return nil, "trailing characters after the value", p.i + end + return v, nil, nil +end + +-- ------------------------------------------------------------------------------------------------ print +local function shortest(v: number, single: boolean): string + if v ~= v then + return "NaN" + elseif v == math.huge then + return "Infinity" + elseif v == -math.huge then + return "-Infinity" + end + local b = buffer.create(4) + if single then + buffer.writef32(b, 0, v) + v = buffer.readf32(b, 0) + end + local s = "" + for digits = if single then 6 else 15, 17 do + s = string.format("%." .. digits .. "g", v) + local back = tonumber(s) :: number + if single then + buffer.writef32(b, 0, back) + back = buffer.readf32(b, 0) + end + if back == v then + break + end + end + if not find(s, "[%.eEn]") then + s ..= ".0" + end + return s +end +Snbt.shortest = shortest + +local function quote(s: string, q: string): string + local other = if q == '"' then "'" else '"' + local _, nq = string.gsub(s, q, "") + local _, no = string.gsub(s, other, "") + if nq > no then + q = other + end + local e = string.gsub(s, "[\\" .. q .. "%c]", function(c: string): string + if c == "\\" or c == q then + return "\\" .. c + elseif c == "\n" then + return "\\n" + elseif c == "\t" then + return "\\t" + elseif c == "\r" then + return "\\r" + end + return string.format("\\x%02x", byte(c)) + end) + return q .. e .. q +end + +local function keyText(k: string, q: string): string + if k ~= "" and not find(k, "[^%w_%-%.%+]") then + return k + end + return quote(k, q) +end + +type Pr = { out: { string }, indent: string?, q: string, depth: number } + +local printValue: (Pr, any, number) -> string? + +local function scalar(v: any, q: string): string? + local tv = type(v) + if tv == "number" then + if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then + return string.format("%d", v) + end + return shortest(v, false) .. "d" + elseif tv == "string" then + return quote(v, q) + elseif tv == "boolean" then + return if v then "1b" else "0b" + elseif Value.isTag(v) then + local t, x = v.type, v.value + if t == "byte" then + return string.format("%db", x) + elseif t == "short" then + return string.format("%ds", x) + elseif t == "int" then + return string.format("%d", x) + elseif t == "long" then + return (if type(x) == "string" then x else string.format("%d", x)) .. "L" + elseif t == "float" then + return shortest(x, true) .. "f" + elseif t == "double" then + return shortest(x, false) .. "d" + elseif t == "string" then + return quote(x, q) + end + end + return nil +end + +local function seq(pr: Pr, head: string, items: { string }, close: string) + if pr.indent and #items > 0 then + local pad = string.rep(pr.indent, pr.depth) + table.insert(pr.out, head .. "\n" .. pad .. pr.indent .. table.concat(items, ",\n" .. pad .. pr.indent) .. "\n" .. pad .. close) + else + table.insert(pr.out, head .. table.concat(items, if pr.indent then ", " else ",") .. close) + end +end + +local function sub1(pr: Pr, v: any): (string?, string?) + local inner: Pr = { out = {}, indent = pr.indent, q = pr.q, depth = pr.depth + 1 } + local e = printValue(inner, v, inner.depth) + if e then + return nil, e + end + return table.concat(inner.out), nil +end + +printValue = function(pr: Pr, v: any, depth: number): string? + if depth > 512 then + return "nested deeper than 512 (a cycle?)" + end + local s = scalar(v, pr.q) + if s then + table.insert(pr.out, s) + return nil + end + local t, terr = Value.typeOf(v) + if not t then + return terr + end + if t == "byteArray" then + local items = table.create(buffer.len(v)) :: { string } + for i = 0, buffer.len(v) - 1 do + items[i + 1] = buffer.readi8(v, i) .. "b" + end + seq(pr, "[B;", items, "]") + elseif t == "intArray" then + local items = {} + for i, x in v.value do + items[i] = string.format("%d", x) + end + seq(pr, "[I;", items, "]") + elseif t == "longArray" then + local items = {} + for i, x in Value.longs(v) do + items[i] = (if type(x) == "string" then x else string.format("%d", x)) .. "L" + end + seq(pr, "[L;", items, "]") + elseif t == "list" then + local items: { string } = {} + for i = 1, #v do + local x, e = sub1(pr, v[i]) + if e then + return e + end + items[i] = x :: string + end + seq(pr, "[", items, "]") + else + local items = {} + for _, k in Types.keys(v) do + if type(k) ~= "string" then + return "compound key " .. tostring(k) .. " is not a string" + end + local x, e = sub1(pr, v[k]) + if e then + return e + end + table.insert(items, keyText(k, pr.q) .. (if pr.indent then ": " else ":") .. (x :: string)) + end + seq(pr, "{", items, "}") + end + return nil +end + +-- print(value, opts?) -> text | nil, message +function Snbt.print(v: any, opts: PrintOptions?): (string?, string?) + local o: PrintOptions = opts or {} + local ind = o.indent + local pr: Pr = { + out = {}, + indent = if type(ind) == "number" then string.rep(" ", ind) elseif type(ind) == "string" then ind else nil, + q = if o.quote == "'" then "'" else '"', + depth = 0, + } + local e = printValue(pr, v, 0) + if e then + return nil, e + end + return table.concat(pr.out), nil +end + +Value.print = function(v: any): string + return Snbt.print(v) or "?" +end + +return Snbt diff --git a/src/Formats/codecs/text/Nbt/Value.luau b/src/Formats/codecs/text/Nbt/Value.luau new file mode 100644 index 0000000..2c0bb17 --- /dev/null +++ b/src/Formats/codecs/text/Nbt/Value.luau @@ -0,0 +1,256 @@ +--!strict +-- codecs/text/Nbt/Value: the NBT value model shared by the binary and SNBT codecs. New code. +-- Plain Luau values with typed numbers, so a decode / encode round trip is exact: +-- int -> number string -> string byteArray -> buffer +-- compound -> Types.object (key order kept) list -> array (element type in Value.listType) +-- byte / short / long / float / double / intArray / longArray -> a tag { type = "", value = ... } with a +-- metatable (tostring gives SNBT): long values are numbers when exact (|v| <= 2^53), else their exact decimal +-- text; intArray value = { numbers }; longArray value = a buffer of little-endian two's complement int64s. +-- Inputs are lenient: a plain number writes as int when integral and in int range, else double; true / false as +-- byte 1 / 0; a plain table with string keys as a compound. +local Types = require("@formats/Types") + +local Value = {} + +-- tag ids (the binary format) <-> names +Value.NAMES = { + [0] = "end", + "byte", + "short", + "int", + "long", + "float", + "double", + "byteArray", + "string", + "list", + "compound", + "intArray", + "longArray", +} :: { [number]: string } +Value.IDS = {} :: { [string]: number } +for id = 0, 12 do + Value.IDS[Value.NAMES[id]] = id +end + +export type Tag = { type: string, value: any } + +local TagMeta: { [string]: any } = {} +Value.TagMeta = TagMeta +-- the SNBT printer, filled in by codecs/text/Nbt (Value is below the printer) +Value.print = function(v: any): string + return tostring(v.value) +end +TagMeta.__tostring = function(v: any): string + return Value.print(v) +end +TagMeta.__eq = function(a: any, b: any): boolean + if a.type ~= b.type then + return false + end + local x, y = a.value, b.value + if type(x) == "buffer" and type(y) == "buffer" then + return buffer.tostring(x) == buffer.tostring(y) + elseif type(x) == "table" and type(y) == "table" then + if #x ~= #y then + return false + end + for i = 1, #x do + if x[i] ~= y[i] then + return false + end + end + return true + end + return x == y +end + +local listTypes: { [any]: string } = setmetatable({}, { __mode = "k" }) :: any + +-- ------------------------------------------------------------------------------------------------ 64-bit integers +local TWO32 = 4294967296 + +-- fromHiLo(hi, lo) -> a long value: a number when exact, else the exact decimal text (hi, lo: u32 halves of the +-- two's complement int64) +function Value.fromHiLo(hi: number, lo: number): number | string + local s = if hi >= 0x80000000 then hi - TWO32 else hi + if s >= -0x200000 and s < 0x200000 then + return s * TWO32 + lo + end + local neg = s < 0 + if neg then -- magnitude = 2^64 - v + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 + end + local parts = {} + while hi > 0 or lo > 0 do -- divide (hi, lo) by 10^4: r * 2^32 + lo < 10^4 * 2^32 stays exact, ql < 2^32 + local qh = hi // 10000 + local x = (hi - qh * 10000) * TWO32 + lo + local ql = x // 10000 + local d = x - ql * 10000 + hi, lo = qh, ql + table.insert(parts, 1, string.format(if hi > 0 or lo > 0 then "%04d" else "%d", d)) + end + return (if neg then "-" else "") .. table.concat(parts) +end + +-- toHiLo(v) -> hi, lo (u32 halves) | nil: v a whole number in int64 range or its decimal text +function Value.toHiLo(v: any): (number?, number?) + if type(v) == "number" then + if v % 1 ~= 0 or v < -9223372036854775808 or v >= 9223372036854775808 then + return nil, nil + end + local hi = v // TWO32 + local lo = v - hi * TWO32 + return hi % TWO32, lo + elseif type(v) == "string" then + local neg, digits = string.match(v, "^(%-?)(%d+)$") + if not digits or #digits > 19 then + return nil, nil + end + local hi, lo = 0, 0 + for i = 1, #digits do + local x = lo * 10 + (string.byte(digits, i) - 48) + local carry = x // TWO32 + lo = x - carry * TWO32 + hi = hi * 10 + carry + end + if hi > 0x80000000 or (hi == 0x80000000 and (lo > 0 or neg == "")) then + return nil, nil + end + if neg == "-" and (hi > 0 or lo > 0) then + lo = (TWO32 - lo) % TWO32 + hi = (TWO32 - 1 - hi + (if lo == 0 then 1 else 0)) % TWO32 + end + return hi, lo + end + return nil, nil +end + +-- ------------------------------------------------------------------------------------------------ constructors +local function tag(name: string, v: any): Tag + return setmetatable({ type = name, value = v }, TagMeta) :: any +end +function Value.byte(n: number): Tag + return tag("byte", n) +end +function Value.short(n: number): Tag + return tag("short", n) +end +function Value.int(n: number): number + return n +end +-- long(n | "decimal") -> a long tag (decimal text within 2^53 becomes a number) +function Value.long(v: number | string): Tag + if type(v) == "string" then + local hi, lo = Value.toHiLo(v) + if hi then + v = Value.fromHiLo(hi, lo :: number) + end + end + return tag("long", v) +end +local f32 = buffer.create(4) +-- float(n) -> a float tag holding n rounded to single precision +function Value.float(n: number): Tag + buffer.writef32(f32, 0, n) + return tag("float", buffer.readf32(f32, 0)) +end +function Value.double(n: number): Tag + return tag("double", n) +end +function Value.intArray(t: { number }?): Tag + return tag("intArray", t or {}) +end +-- longArray(values | buffer) -> a longArray tag (values: numbers / decimal texts; a buffer: 8 bytes each, LE) +function Value.longArray(t: { any } | buffer | nil): Tag + if type(t) == "buffer" then + return tag("longArray", t) + end + local list: { any } = (t or {}) :: any + local b = buffer.create(#list * 8) + for i, x in list do + local hi, lo = Value.toHiLo(x) + buffer.writeu32(b, (i - 1) * 8, lo or 0) + buffer.writeu32(b, (i - 1) * 8 + 4, hi or 0) + end + return tag("longArray", b) +end +-- longs(longArray) -> { number | string }: the elements as long values +function Value.longs(a: Tag): { number | string } + local b: buffer = a.value + local out = table.create(buffer.len(b) // 8) :: { number | string } + for i = 0, buffer.len(b) // 8 - 1 do + out[i + 1] = Value.fromHiLo(buffer.readu32(b, i * 8 + 4), buffer.readu32(b, i * 8)) + end + return out +end +-- list(typeName, items?) -> items marked as a list of that element type (an empty list keeps its type) +function Value.list(name: string, items: { any }?): { any } + local t = items or {} + listTypes[t] = name + return t +end +function Value.compound(t: { [string]: any }?, keys: { string }?): { [string]: any } + return Types.object(t, keys) +end +-- listType(t) -> the element type name recorded for a list (decoded, or made by Value.list) +function Value.listType(t: any): string? + return listTypes[t] +end +function Value.setListType(t: any, name: string) + listTypes[t] = name +end +function Value.isTag(v: any): boolean + return type(v) == "table" and getmetatable(v) == TagMeta +end + +-- typeOf(v) -> the tag name v writes as, or nil + why +function Value.typeOf(v: any): (string?, string?) + local tv = type(v) + if tv == "number" then + return if v % 1 == 0 and v >= -2147483648 and v <= 2147483647 then "int" else "double", nil + elseif tv == "string" then + return "string", nil + elseif tv == "boolean" then + return "byte", nil + elseif tv == "buffer" then + return "byteArray", nil + elseif tv == "table" then + if getmetatable(v) == TagMeta then + local n = v.type + if Value.IDS[n] == nil or n == "end" or n == "list" or n == "compound" or n == "string" or n == "int" or n == "byteArray" then + if n == "int" or n == "string" or n == "byteArray" then + return n, nil + end + return nil, "bad tag type " .. tostring(n) + end + return n, nil + elseif Types.isObject(v) then + return "compound", nil + elseif listTypes[v] or v[1] ~= nil or next(v) == nil then + return "list", nil + end + return "compound", nil + end + return nil, "cannot write a " .. tv .. " as NBT" +end + +-- number(v) -> the numeric value of a number or numeric tag (long texts through tonumber: approximate) +function Value.number(v: any): number? + if type(v) == "number" then + return v + elseif type(v) == "boolean" then + return if v then 1 else 0 + elseif Value.isTag(v) then + local x = v.value + if type(x) == "number" then + return x + elseif type(x) == "string" then + return tonumber(x) + end + end + return nil +end + +return Value diff --git a/src/Formats/codecs/text/Nbt/init.luau b/src/Formats/codecs/text/Nbt/init.luau new file mode 100644 index 0000000..3245410 --- /dev/null +++ b/src/Formats/codecs/text/Nbt/init.luau @@ -0,0 +1,380 @@ +--!strict +-- codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, +-- model/schematic and model/mca use. New code (Minecraft wiki "NBT format", wiki.vg "NBT"). +-- Binary: Java big-endian (modified UTF-8 strings), Bedrock little-endian (with or without the 8-byte level.dat +-- header) and Bedrock network NBT (varints), every tag type; files may be gzip or zlib compressed (codecs/compress/ +-- Deflate). SNBT: parse and print (codecs/text/Nbt/Snbt). Values are plain Luau with typed numbers +-- (codecs/text/Nbt/Value): int -> number, string -> string, byteArray -> buffer, compound -> Types.object (key order +-- kept), list -> array, the other numeric and array tags -> { type, value } tags, so round trips are exact. +-- +-- local Nbt = require("@formats/codecs/text/Nbt") +-- local v, info = Nbt.decode(buf) -- a file: compression and edition detected; info = how it was stored +-- print(v.Data.LevelName, v.Data.Time.value) -- int / string plain; long / byte / ... tags have .value +-- v.Data.Difficulty = Nbt.byte(2) +-- local out = Nbt.encode(v) -- written the way it was read (Nbt.info(v)), or opts +-- local text = Nbt.print(v) -- SNBT: {Data:{Difficulty:2b,...}} +-- local w = Nbt.parse('{pos:[I;1,2,3],name:"x"}') +-- local raw, name, endPos = Nbt.read(buf, 0, nil, { endian = "little" }) -- one uncompressed tag +-- +-- Never throws: bad data and bad values return nil, Err. +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Deflate = require("@formats/codecs/compress/Deflate") +local Value = require("@formats/codecs/text/Nbt/Value") +local Binary = require("@formats/codecs/text/Nbt/Binary") +local Snbt = require("@formats/codecs/text/Nbt/Snbt") + +local Nbt = {} + +export type Tag = Value.Tag +export type Info = { + name: string, -- the root tag's name + endian: "big" | "little", + varint: boolean?, -- Bedrock network NBT + compression: "gzip" | "zlib" | "none", + header: number?, -- Bedrock level.dat: the storage version from the 8-byte header +} +export type DecodeOptions = { + endian: ("big" | "little")?, -- default: detected (Java big-endian first) + varint: boolean?, -- Bedrock network NBT + nameless: boolean?, -- no root name (Java network NBT since 1.20.2) + maxDepth: number?, -- nesting limit (default 512) + maxBytes: number?, -- refuse compressed data that inflates past this (default 2^28) +} +export type EncodeOptions = { + endian: ("big" | "little")?, -- default: Nbt.info(value).endian, else "big" + varint: boolean?, + nameless: boolean?, + name: string?, -- the root name (default: Nbt.info(value).name, else "") + compression: ("gzip" | "zlib" | "none")?, -- default: Nbt.info(value).compression, else gzip for big-endian + header: number?, -- write the Bedrock level.dat header with this version + level: number?, -- deflate level 0..9 (default 6) +} + +Nbt.TAG = Value.IDS -- name -> id +Nbt.TAG_NAMES = Value.NAMES -- id -> name +Nbt.byte = Value.byte +Nbt.short = Value.short +Nbt.int = Value.int +Nbt.long = Value.long +Nbt.float = Value.float +Nbt.double = Value.double +Nbt.intArray = Value.intArray +Nbt.longArray = Value.longArray +Nbt.longs = Value.longs +Nbt.list = Value.list +Nbt.listType = Value.listType +Nbt.compound = Value.compound +Nbt.typeOf = Value.typeOf +Nbt.isTag = Value.isTag +Nbt.number = Value.number +Nbt.fromHiLo = Value.fromHiLo +Nbt.toHiLo = Value.toHiLo + +local infos: { [any]: Info } = setmetatable({}, { __mode = "k" }) :: any + +-- info(value) -> how a decoded root was stored (nil for values not from decode) +function Nbt.info(v: any): Info? + return if type(v) == "table" then infos[v] else nil +end +-- setInfo(value, info): what encode uses as defaults +function Nbt.setInfo(v: any, info: Info) + if type(v) == "table" then + infos[v] = info + end +end + +-- read(buf, offset?, length?, opts?) -> value, rootName, endOffset | nil, Err: one uncompressed root tag +function Nbt.read(buf: buffer | string, offset: number?, length: number?, opts: DecodeOptions?): (any, any, number?) + local b, o, l, aerr = Bytes.span("Nbt.read", buf, offset, length) + if not b then + return nil, aerr + end + local v, name, at = Binary.read(b, o, o + l, opts :: any) + if v == nil then + return nil, Err.from(name, (at or o) - o) + end + return v, name, at +end + +-- write(value, opts?) -> buffer | nil, Err: one uncompressed root tag +function Nbt.write(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local out, e = Binary.write(v, opts :: any) + if not out then + return nil, Err.new(Err.ARG, tostring(e)) + end + return out, nil +end + +-- unwrap(buf, offset?, length?, maxBytes?) -> data, start, end, compression | nil, Err: gzip / zlib detected by magic +function Nbt.unwrap(buf: buffer | string, offset: number?, length: number?, maxBytes: number?): (buffer?, any, number?, string?) + local b, o, l, aerr = Bytes.span("Nbt.unwrap", buf, offset, length) + if not b then + return nil, aerr + end + local c0 = if l >= 2 then buffer.readu8(b, o) else 0 + local c1 = if l >= 2 then buffer.readu8(b, o + 1) else 0 + local out, err, comp + if c0 == 0x1f and c1 == 0x8b then + out, err = Deflate.gunzip(b, o, l) + comp = "gzip" + elseif c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0 then + out, err = Deflate.zlib(b, o, l) + comp = "zlib" + else + return b, o, o + l, "none" + end + if not out then + return nil, err + end + if buffer.len(out) > (maxBytes or 2 ^ 28) then + return nil, Err.new(Err.LIMIT, "inflates to " .. buffer.len(out) .. " bytes, over maxBytes") + end + return out, 0, buffer.len(out), comp +end + +export type Peek = { + compression: string, -- "gzip" | "zlib" | "none" + endian: "big" | "little", + header: boolean, -- a Bedrock level.dat header + rootType: string, -- "compound" (or "list") + name: string, -- the root name + firstType: string?, -- the first child of a root compound (type and name; "end" when empty), when peeked + firstName: string?, + head: buffer, -- the first (up to 1024) uncompressed bytes +} + +local function plausibleName(b: buffer, p: number, n: number): string? + if p + n > buffer.len(b) or n > 256 then + return nil + end + local s = buffer.readstring(b, p, n) + if string.find(s, "[%z\1-\31\127]") then + return nil + end + return s +end + +-- peek(buf, offset?, length?) -> Peek | nil: whether the bytes look like an NBT file (inflating at most 1 KiB of a +-- gzip / zlib stream), and its root's name and first child: what format sniffs look at. Never fails loudly. +function Nbt.peek(buf: buffer, offset: number?, length: number?): Peek? + local o = offset or 0 + local l = length or (buffer.len(buf) - o) + if l < 3 then + return nil + end + local c0, c1 = buffer.readu8(buf, o), buffer.readu8(buf, o + 1) + local head: buffer + local comp = "none" + if c0 == 0x1f and c1 == 0x8b or (c0 % 16 == 8 and c0 < 0x80 and (c0 * 256 + c1) % 31 == 0) then + local h = Deflate.peek(buf, o, l, 1024) + if not h then + return nil + end + head, comp = h, if c0 == 0x1f then "gzip" else "zlib" + else + local n = math.min(l, 1024) + head = buffer.create(n) + buffer.copy(head, 0, buf, o, n) + end + local hn = buffer.len(head) + local function at(p: number, endian: string, header: boolean): Peek? + if p + 3 > hn then + return nil + end + local t = buffer.readu8(head, p) + if t ~= 10 and t ~= 9 then + return nil + end + local function u16(q: number): number + local a, b = buffer.readu8(head, q), buffer.readu8(head, q + 1) + return if endian == "big" then a * 256 + b else b * 256 + a + end + local nl = u16(p + 1) + local name = plausibleName(head, p + 3, nl) + if not name then + return nil + end + local res: Peek = { compression = comp, endian = endian :: any, header = header, rootType = Value.NAMES[t], name = name, head = head } + local q = p + 3 + nl + if t == 10 and q < hn then + local ft = buffer.readu8(head, q) + if ft > 12 then + return nil + end + if ft == 0 then + res.firstType = "end" -- an empty root compound + elseif q + 3 <= hn then + local fname = plausibleName(head, q + 3, u16(q + 1)) + if fname == nil and q + 3 + u16(q + 1) <= hn then + return nil + end + res.firstType, res.firstName = Value.NAMES[ft], fname + end + end + return res + end + if hn >= 12 and buffer.readu32(head, 4) == (if comp == "none" then l else -1) - 8 then + local r = at(8, "little", true) + if r then + return r + end + end + return at(0, "big", false) or at(0, "little", false) +end + +-- decode(buf | string, opts?, offset?, length?) -> value, Info | nil, Err: a whole NBT file (gzip / zlib / raw; Java +-- or Bedrock) +function Nbt.decode(buf: buffer | string, opts: DecodeOptions?, offset: number?, length: number?): (any, any) + local o: DecodeOptions = opts or {} + local b, s, e, comp = Nbt.unwrap(buf, offset, length, o.maxBytes) + if not b then + return nil, s + end + local data: buffer, start: number, stop: number = b, s, e :: number + local function try(endian: string, from: number, varint: boolean?): (any, any, number?) + return Binary.read(data, from, stop, { endian = endian :: any, varint = varint, nameless = o.nameless, maxDepth = o.maxDepth }) + end + local header: number? = nil + local v, name, at + if o.varint then + v, name, at = try("little", start, true) + elseif o.endian then + local from = start + if o.endian == "little" and stop - start >= 8 and buffer.readu32(data, start + 4) == stop - start - 8 then + header, from = buffer.readu32(data, start), start + 8 + end + v, name, at = try(o.endian, from) + else + -- Bedrock level.dat: version, length (u32le), then little-endian NBT + if stop - start >= 9 and buffer.readu32(data, start + 4) == stop - start - 8 and buffer.readu8(data, start + 8) == 10 then + v, name, at = try("little", start + 8) + if v ~= nil then + header = buffer.readu32(data, start) + o = table.clone(o) + o.endian = "little" + end + end + if v == nil then + local bv, bn, ba = try("big", start) + if bv ~= nil and ba == stop then + v, name, at, o = bv, bn, ba, table.clone(o) + o.endian = "big" + else + local lv, ln, la = try("little", start) + if lv ~= nil and (la == stop or bv == nil) then + v, name, at, o = lv, ln, la, table.clone(o) + o.endian = "little" + elseif bv ~= nil then + v, name, at, o = bv, bn, ba, table.clone(o) + o.endian = "big" + else + v, name, at = nil, bn, ba + end + end + end + end + if v == nil then + return nil, Err.from(name, (at or start) - start) + end + local info: Info = { + name = name, + endian = if o.varint or o.endian == "little" then "little" else "big", + varint = if o.varint then true else nil, + compression = comp :: any, + header = header, + } + if type(v) == "table" then + infos[v] = info + end + return v, info +end + +-- encode(value, opts?) -> buffer | nil, Err: a whole NBT file +function Nbt.encode(v: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local info = Nbt.info(v) + local endian = o.endian or (info and info.endian) or "big" + local varint = if o.varint ~= nil then o.varint else (info and info.varint) + local raw, e = Binary.write(v, { + endian = endian, + varint = varint, + nameless = o.nameless, + name = o.name or (info and info.name) or "", + }) + if not raw then + return nil, Err.new(Err.ARG, tostring(e)) + end + local header = if o.header ~= nil then o.header else (info and info.header) + if header then + local h = buffer.create(buffer.len(raw) + 8) + buffer.writeu32(h, 0, header) + buffer.writeu32(h, 4, buffer.len(raw)) + buffer.copy(h, 8, raw) + raw = h + end + local comp = o.compression or (info and info.compression) or (if endian == "big" then "gzip" else "none") + if comp == "gzip" then + return Deflate.gzip(raw, { level = o.level }) + elseif comp == "zlib" then + return Deflate.zlibCompress(raw, { level = o.level }) + elseif comp ~= "none" then + return nil, Err.new(Err.ARG, "unknown compression " .. tostring(comp)) + end + return raw, nil +end + +-- parse(text, opts?) -> value | nil, Err: SNBT +function Nbt.parse(text: string | buffer, opts: Snbt.ParseOptions?): (any, Err.Err?) + local s = if type(text) == "buffer" then buffer.tostring(text) else text + if type(s) ~= "string" then + return nil, Err.new(Err.ARG, "Nbt.parse: text must be a string") + end + local v, e, at = Snbt.parse(s, opts) + if v == nil then + return nil, Err.from(e, (at or 1) - 1) + end + return v, nil +end + +-- print(value, opts?) -> text | nil, Err: SNBT (compact, or opts.indent) +function Nbt.print(v: any, opts: Snbt.PrintOptions?): (string?, Err.Err?) + local s, e = Snbt.print(v, opts) + if not s then + return nil, Err.new(Err.ARG, tostring(e)) + end + return s, nil +end + +-- get(value, path) -> the value at a dotted path ("Data.Player.Pos[1]"; list indices 0-based like Minecraft's) +function Nbt.get(v: any, path: string): any + local cur = v + for part in string.gmatch(path, "[^%.]+") do + local k, rest = string.match(part, "^([^%[]*)(.*)$") + if k ~= "" then + if type(cur) ~= "table" or Value.isTag(cur) then + return nil + end + cur = cur[k] + end + for idx in string.gmatch(rest :: string, "%[(%-?%d+)%]") do + local i = tonumber(idx) :: number + if type(cur) == "table" and not Value.isTag(cur) then + cur = cur[i + 1] + elseif Value.isTag(cur) and type(cur.value) == "table" then + cur = cur.value[i + 1] + elseif type(cur) == "buffer" and i >= 0 and i < buffer.len(cur) then + cur = buffer.readi8(cur, i) + else + return nil + end + end + end + return cur +end + +Nbt.object = Types.object +Nbt.shortest = Snbt.shortest + +return Nbt diff --git a/src/Formats/data/nbt/init.luau b/src/Formats/data/nbt/init.luau new file mode 100644 index 0000000..407aed8 --- /dev/null +++ b/src/Formats/data/nbt/init.luau @@ -0,0 +1,60 @@ +--!strict +-- data/nbt: Minecraft NBT files (.nbt structures, level.dat / playerdata .dat, servers.dat, Bedrock .mcstructure and +-- level.dat), a thin format over codecs/text/Nbt (which see for the value mapping). Supports: Java big-endian and +-- Bedrock little-endian NBT (the level.dat 8-byte header too; network varint NBT with opts.varint), gzip / zlib / +-- uncompressed, every tag type, exact round trips (Nbt.info(value) remembers the root name, edition, compression +-- and header; encode writes it back the same way unless opts say otherwise). Text SNBT: data/snbt. +-- Not supported: nothing in the format. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Nbt = require("@formats/codecs/text/Nbt") + +-- ------------------------------------------------------------------------------------------------ contract +local NbtFormat = { + name = "nbt", + category = "data", + extensions = { "nbt", "dat", "mcstructure", "dat_old" }, + mime = { "application/x-minecraft-nbt" }, + deps = { "core/Err", "core/Bytes", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, binary = true, ordered = true, typed = true }, +} + +export type DecodeOptions = Nbt.DecodeOptions +export type EncodeOptions = Nbt.EncodeOptions + +-- ------------------------------------------------------------------------------------------------ sniff +function NbtFormat.sniff(r: Bytes.Reader): number + local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p or p.rootType ~= "compound" then + return 0 + end + if p.compression ~= "none" then + return if p.firstType then 1 else 0.5 -- gzip wrapped NBT: ties with archive/gzip go to the extension + end + return if p.firstType and p.firstName then 0.6 else 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +function NbtFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local v, info = Nbt.decode(r.buf, opts, r.base, r.limit - r.base) + if v == nil then + return nil, info + end + return v, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +function NbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if value == nil then + return nil, Err.new(Err.ARG, "nothing to encode") + end + return Nbt.encode(value, opts) +end + +-- ------------------------------------------------------------------------------------------------ extras +NbtFormat.info = Nbt.info -- how a decoded value was stored: { name, endian, compression, header?, varint? } +NbtFormat.Nbt = Nbt + +return NbtFormat diff --git a/src/Formats/data/snbt/init.luau b/src/Formats/data/snbt/init.luau new file mode 100644 index 0000000..a128f3e --- /dev/null +++ b/src/Formats/data/snbt/init.luau @@ -0,0 +1,63 @@ +--!strict +-- data/snbt: stringified NBT text (Minecraft commands, datapacks, .snbt structure files), a thin format over +-- codecs/text/Nbt (which see for the value mapping and grammar). Supports: parse to the same typed values data/nbt +-- gives (convert between the two freely), print compact (Minecraft's form) or indented (opts.indent). +-- Not supported: the 1.21.5 bool(...) / uuid(...) operations. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Sniff = require("@formats/core/Sniff") +local Nbt = require("@formats/codecs/text/Nbt") + +-- ------------------------------------------------------------------------------------------------ contract +local SnbtFormat = { + name = "snbt", + category = "data", + extensions = { "snbt" }, + mime = { "text/x-minecraft-snbt" }, + deps = { "core/Err", "core/Bytes", "core/Sniff", "codecs/text/Nbt" }, + caps = { decode = true, encode = true, ordered = true, typed = true }, +} + +export type DecodeOptions = { maxDepth: number? } +export type EncodeOptions = { + indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact) + quote: string?, -- '"' (default) or "'" +} + +-- ------------------------------------------------------------------------------------------------ sniff +function SnbtFormat.sniff(r: Bytes.Reader): number + -- SNBT has what JSON never has: unquoted keys, typed numbers (1b, 2.5f), [I; arrays, single-quoted strings + local head = Sniff.text(r, 512, true) + local first = string.sub(head, 1, 1) + if first ~= "{" and first ~= "[" then + return 0 + end + if string.find(head, "[{,]%s*[%a_][%w_%-%.%+]*%s*:") or string.find(head, "%d[bBsSlLfFdD]%s*[,}%]]") + or string.find(head, "%[[BIL]%s*;") or string.find(head, "[:,%[]%s*'") + then + return 0.7 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function SnbtFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) + local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base)) + return Nbt.parse(text, opts) +end + +-- ------------------------------------------------------------------------------------------------ encode +function SnbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + if value == nil then + return nil, Err.new(Err.ARG, "nothing to encode") + end + local s, e = Nbt.print(value, opts) + if not s then + return nil, e + end + return buffer.fromstring(s), nil +end + +return SnbtFormat diff --git a/tests/codecs/deflate.luau b/tests/codecs/deflate.luau index d9ee80a..319dfdc 100644 --- a/tests/codecs/deflate.luau +++ b/tests/codecs/deflate.luau @@ -169,4 +169,23 @@ do end, samples, { mutations = 3, garbage = 300 }) end +-- peek: the first bytes of a gzip / zlib / raw stream without inflating the rest +do + local src = buffer.create(100000) + for i = 0, 99999 do + buffer.writeu8(src, i, (i * 7 + (i // 97)) % 251) + end + local want = buffer.readstring(src, 0, 1000) + for _, kind in { "gzip", "zlibCompress", "compress" } do + local z = assert((Deflate :: any)[kind](src)) :: buffer + local head = assert(Deflate.peek(z, nil, nil, 1000)) + t:check(buffer.len(head) <= 1000 and buffer.len(head) >= 1000 - 258, "peek " .. kind .. " size") + t:eq(buffer.tostring(head), string.sub(want, 1, buffer.len(head)), "peek " .. kind .. " bytes") + end + local small = assert(Deflate.peek(assert(Deflate.gzip(buffer.fromstring("hello"))), nil, nil, 1000)) + t:eq(buffer.tostring(small), "hello", "peek a short stream") + local _, e = Deflate.peek(buffer.fromstring("\31\139\8\0\0\0\0\0\0\3\255\255\255\255\255\255\255\255"), nil, nil, 10) + t:check(e ~= nil, "peek bad data") +end + t:done() diff --git a/tests/codecs/nbt.luau b/tests/codecs/nbt.luau new file mode 100644 index 0000000..ba602a3 --- /dev/null +++ b/tests/codecs/nbt.luau @@ -0,0 +1,256 @@ +-- codecs/text/Nbt tests: random trees written by Python's nbtlib (Java big-endian, Bedrock little-endian, gzip, zlib, +-- the level.dat header) decode to nbtlib's typed values (a canonical dump), re-encode to nbtlib's exact bytes in both +-- byte orders, nbtlib's SNBT (indented and compact) parses to the same values and our SNBT reads back exactly; +-- Bedrock network varint NBT; modified UTF-8; long extremes; SNBT grammar details; peek; errors; the fuzz pass. +-- Fixtures: tools/fixtures/nbt.py. +local T = require("@tests/T") +local Nbt = require("@formats/codecs/text/Nbt") +local Types = require("@formats/Types") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/nbt") + +local t = T.suite("nbt") + +local function hexOf(b: buffer, o: number, n: number, rev: boolean): string + local parts = {} + for i = 0, n - 1 do + parts[i + 1] = string.format("%02x", buffer.readu8(b, if rev then o + n - 1 - i else o + i)) + end + return table.concat(parts) +end + +-- the canonical dump tools/fixtures/nbt.py writes +local function canon(v: any): string + local ty = Nbt.typeOf(v) + local x = if Nbt.isTag(v) then v.value else v + if ty == "byte" or ty == "short" or ty == "int" or ty == "long" then + local n = if type(x) == "boolean" then (if x then 1 else 0) else x + return string.sub(ty :: string, 1, 1) .. (if type(n) == "string" then n else string.format("%d", n)) + elseif ty == "float" then + local b = buffer.create(4) + buffer.writef32(b, 0, x) + return "f" .. hexOf(b, 0, 4, true) + elseif ty == "double" then + local b = buffer.create(8) + buffer.writef64(b, 0, x) + return "d" .. hexOf(b, 0, 8, true) + elseif ty == "string" then + return "S" .. #x .. ":" .. x + elseif ty == "byteArray" then + return "B" .. hexOf(x, 0, buffer.len(x), false) + elseif ty == "intArray" then + local p = {} + for i, n in x do + p[i] = string.format("%d", n) + end + return "I[" .. table.concat(p, ",") .. "]" + elseif ty == "longArray" then + local p = {} + for i, n in Nbt.longs(v) do + p[i] = if type(n) == "string" then n else string.format("%d", n) + end + return "L[" .. table.concat(p, ",") .. "]" + elseif ty == "list" then + local p = {} + for i, e in v do + p[i] = canon(e) + end + return "[" .. (Nbt.listType(v) or "?") .. "|" .. table.concat(p, ",") .. "]" + end + local p = {} + for _, k in Types.keys(v) do + table.insert(p, #k .. ":" .. k .. "=" .. canon(v[k])) + end + return "{" .. table.concat(p, ";") .. "}" +end + +local function same(a: buffer, b: string): boolean + return buffer.tostring(a) == b +end + +-- 1. nbtlib trees +for _, c in Fx.cases do + local v, info = Nbt.decode(c.raw) + t:check(v ~= nil, c.name .. ": decode " .. tostring(info)) + t:eq(canon(v), c.canon, c.name .. ": value") + t:eq(info.name, c.root, c.name .. ": root name") + t:check(info.endian == "big" and info.compression == "none", c.name .. ": info") + local out = Nbt.encode(v) :: buffer + t:check(out and same(out, c.raw), c.name .. ": same bytes (big-endian)") + local le = Nbt.encode(v, { endian = "little" }) :: buffer + t:check(le and same(le, c.little), c.name .. ": same bytes (little-endian)") + for _, k in { "little", "gzip", "zlib", "header" } do + local w, wi = Nbt.decode(c[k]) + t:check(w ~= nil, c.name .. ": decode " .. k .. " " .. tostring(wi)) + t:eq(canon(w), c.canon, c.name .. ": " .. k .. " value") + if #c.raw > 4 then -- an empty compound with an empty name reads the same either way + t:eq(wi.endian, if k == "little" or k == "header" then "little" else "big", c.name .. ": " .. k .. " endian") + end + t:eq(wi.compression, if k == "gzip" or k == "zlib" then k else "none", c.name .. ": " .. k .. " compression") + -- written back the same way it was read + local again = Nbt.encode(w) :: buffer + local w2, wi2 = Nbt.decode(again) + t:eq(canon(w2), c.canon, c.name .. ": " .. k .. " round trip") + t:eq(wi2.compression, wi.compression, c.name .. ": " .. k .. " keeps compression") + t:eq(wi2.header, wi.header, c.name .. ": " .. k .. " keeps the header") + if k == "header" then + t:eq(wi.header, c.version, c.name .. ": header version") + t:check(same(again, c.header), c.name .. ": header same bytes") + end + end + -- SNBT: nbtlib's text parses to the same values (an empty list's type is not in the text); ours reads back + -- exactly (both forms) + local function untyped(s: string): string + return (string.gsub(s, "%[%a+|%]", "[|]")) + end + for _, k in { "snbt", "compact" } do + local s, e = Nbt.parse(c[k]) + t:check(s ~= nil, c.name .. ": parse " .. k .. " " .. tostring(e)) + t:eq(untyped(canon(s)), untyped(c.canon), c.name .. ": " .. k .. " value") + end + for _, o in { {}, { indent = 2 }, { quote = "'" } } do + local text = Nbt.print(v, o) :: string + local back, e = Nbt.parse(text) + t:check(back ~= nil, c.name .. ": our SNBT parses " .. tostring(e)) + t:eq(untyped(canon(back)), untyped(c.canon), c.name .. ": our SNBT round trip") + end +end + +-- 2. Bedrock network NBT +for i, c in Fx.net do + local v, info = Nbt.decode(c.data, { varint = true }) + t:check(v ~= nil, "net " .. i .. ": " .. tostring(info)) + t:eq(canon(v), c.canon, "net " .. i .. ": value") + t:check(same(Nbt.encode(v, { varint = true }) :: buffer, c.data), "net " .. i .. ": same bytes") +end + +-- 3. details +do + -- longs: exact past 2^53, both directions + for _, s in { "9223372036854775807", "-9223372036854775808", "9007199254740993", "-9007199254740993", "4294967296", "-1" } do + local hi, lo = Nbt.toHiLo(s) + t:check(hi ~= nil, "toHiLo " .. s) + t:eq(tostring(Nbt.fromHiLo(hi :: number, lo :: number)), s, "long text " .. s) + end + t:eq(Nbt.toHiLo("9223372036854775808"), nil, "long overflow") + t:eq(Nbt.long("12").value, 12, "small long text becomes a number") + -- modified UTF-8: NUL as C0 80 and U+1F600 as a surrogate pair in Java files, plain UTF-8 in Bedrock ones + local v = Nbt.compound({ s = "a\0b\u{1F600}" }, { "s" }) + local big = Nbt.write(v) :: buffer + t:check(string.find(buffer.tostring(big), "a\192\128b\237\160\189\237\184\128", 1, true) ~= nil, "modified UTF-8 out") + t:eq((Nbt.read(big)).s, "a\0b\u{1F600}", "modified UTF-8 in") + local little = Nbt.write(v, { endian = "little" }) :: buffer + t:check(string.find(buffer.tostring(little), "a\0b\u{1F600}", 1, true) ~= nil, "Bedrock strings are UTF-8") + -- lenient inputs: plain numbers, booleans, plain tables + local p = Nbt.read(Nbt.write({ a = 1.5, b = true, c = { 1, 2 }, d = {}, e = 2 ^ 40 }) :: buffer) + t:check(p.a.type == "double" and p.b.type == "byte" and p.b.value == 1, "plain number / boolean") + t:check(Nbt.listType(p.c) == "int" and Nbt.listType(p.d) == "end" and p.e.type == "double", "plain lists") + -- mixed lists are wrapped in compounds, as Minecraft 1.21.5 does + local m = Nbt.read(Nbt.write({ l = { 1, "x" } }) :: buffer) + t:check(Nbt.listType(m.l) == "compound" and m.l[1][""] == 1 and m.l[2][""] == "x", "heterogeneous list") + -- empty typed list keeps its type + local et = Nbt.read(Nbt.write({ l = Nbt.list("compound") }) :: buffer) + t:eq(Nbt.listType(et.l), "compound", "empty typed list") + -- tostring of tags is SNBT; == compares type and value + t:eq(tostring(Nbt.byte(3)), "3b", "tostring byte") + t:eq(tostring(Nbt.float(0.1)), "0.1f", "tostring float (shortest)") + t:check(Nbt.short(5) == Nbt.short(5) and Nbt.short(5) ~= Nbt.int(5) :: any, "tag equality") + -- get + local g = assert(Nbt.parse("{Data:{Pos:[1.0d,2.5d,3.0d],Inv:[{id:\"x\"}]}}")) + t:eq(Nbt.get(g, "Data.Pos[1]").value, 2.5, "get list element") + t:eq(Nbt.get(g, "Data.Inv[0].id"), "x", "get nested") + t:eq(Nbt.get(g, "Data.Missing.x"), nil, "get missing") +end + +-- 4. SNBT grammar +do + local cases: { { string } } = { + { "1b", "byte:1" }, { "-5S", "short:-5" }, { "7", "int:7" }, { "7i", "int:7" }, { "1_000", "int:1000" }, + { "123L", "long:123" }, { "0x1F", "int:31" }, { "0xFFub", "byte:-1" }, { "0x7Fsb", "byte:127" }, + { "0b101", "int:5" }, { "0b", "byte:0" }, { "200ub", "byte:-56" }, { "1.5", "double:1.5" }, { ".5f", "float:0.5" }, + { "2e3", "double:2000" }, { "3f", "float:3" }, { "4D", "double:4" }, { "true", "byte:1" }, { "false", "byte:0" }, + { "abc", "string:abc" }, { "1.2.3", "string:1.2.3" }, { "'it''", "" }, { "'a\\'b'", "string:a'b" }, + { '"\\u00e9\\x41\\n"', "string:\u{e9}A\n" }, { "-Infinityd", "double:-inf" }, + } + for _, c in cases do + local v = Nbt.parse(c[1]) + if c[2] == "" then + t:eq(v, nil, "snbt " .. c[1] .. " fails") + else + local ty = Nbt.typeOf(v) :: string + local x = Nbt.number(v) + local got = ty .. ":" .. (if ty == "string" then v elseif x == -math.huge then "-inf" else string.format("%.17g", x :: number)) + t:eq(got, c[2], "snbt " .. c[1]) + end + end + local a = assert(Nbt.parse("[B; 1b, -2b, 3]")) + t:check(typeof(a) == "buffer" and buffer.len(a) == 3 and buffer.readi8(a, 1) == -2, "byte array") + local ia = assert(Nbt.parse("[I;]")) + t:check(ia.type == "intArray" and #ia.value == 0, "empty int array") + local la = assert(Nbt.parse("[L; -9223372036854775808L, 5L]")) + t:eq(Nbt.longs(la)[1], "-9223372036854775808", "long array extreme") + local tc = assert(Nbt.parse("{a:1,b:[1,2,],}")) + t:check(tc.a == 1 and #tc.b == 2, "trailing commas") + t:eq(Nbt.print(assert(Nbt.parse('{"a b":1,c:"say \\"hi\\""}'))), "{\"a b\":1,c:'say \"hi\"'}", "quoting") + local _, e1 = Nbt.parse("{a:1") + t:check(e1 and e1.code == Err.CORRUPT, "unterminated compound") + local _, e2 = Nbt.parse("{a:300b}") + t:check(e2 and e2.code == Err.CORRUPT, "byte out of range") + local _, e3 = Nbt.parse(string.rep("[", 600) .. string.rep("]", 600)) + t:check(e3 and e3.code == Err.LIMIT, "depth limit") +end + +-- 5. peek +do + local c = Fx.cases[2] + for _, k in { "raw", "gzip", "zlib", "header" } do + local p = Nbt.peek(buffer.fromstring(c[k])) + t:check(p ~= nil and p.name == c.root and p.rootType == "compound", "peek " .. k) + end + t:eq(Nbt.peek(buffer.fromstring("hello world")), nil, "peek text") +end + +-- 6. errors +do + local _, e = Nbt.decode("\10\0\0\1\0\1a") + t:check(e and e.code == Err.TRUNCATED, "truncated") + local _, e2 = Nbt.decode("\13\0\0") + t:check(e2 and e2.code == Err.CORRUPT, "bad root type") + local _, e3 = Nbt.decode("\10\0\0\9\0\1l\1\127\255\255\255") + t:check(e3 and e3.code == Err.TRUNCATED, "huge list length") + local deep = {} + local cur = deep + for _ = 1, 600 do + local n = {} + cur.x = n + cur = n + end + local _, e4 = Nbt.encode(deep) + t:check(e4 and e4.code == Err.ARG, "encode depth") + local _, e5 = Nbt.encode({ a = Nbt.byte(300) }) + t:check(e5 and e5.code == Err.ARG, "encode byte range") + local _, e6 = Nbt.encode({ a = function() end }) + t:check(e6 and e6.code == Err.ARG, "encode function") +end + +-- 7. fuzz +local samples = {} +for i = 1, 8 do + table.insert(samples, Fx.cases[i].raw) + table.insert(samples, Fx.cases[i].little) +end +table.insert(samples, Fx.cases[3].gzip) +t:fuzz("decode", function(b: buffer) + return Nbt.decode(b) +end, samples) +t:fuzz("decode varint", function(b: buffer) + return Nbt.decode(b, { varint = true }) +end, { Fx.net[1].data, Fx.net[2].data }) +local texts = {} +for i = 1, 6 do + table.insert(texts, Fx.cases[i].compact) +end +t:fuzz("parse", function(b: buffer) + return Nbt.parse(buffer.tostring(b)) +end, texts) +t:done() diff --git a/tests/data/nbt.luau b/tests/data/nbt.luau new file mode 100644 index 0000000..3268473 --- /dev/null +++ b/tests/data/nbt.luau @@ -0,0 +1,60 @@ +-- data/nbt tests: the contract, nbtlib files through the api (F.load / F.save, NBT -> SNBT -> NBT), detection by +-- content and extension, exact round trips (root name, edition, compression and the Bedrock header kept), error +-- codes, and the fuzz pass. The engine itself: tests/codecs/nbt.luau; SNBT files: tests/data/snbt.luau. +-- Fixtures: tools/fixtures/nbt.py. +local T = require("@tests/T") +local F = require("@formats") +local NbtF = require("@formats/data/nbt") +local SnbtF = require("@formats/data/snbt") +local Nbt = require("@formats/codecs/text/Nbt") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/nbt") + +local t = T.suite("data/nbt") + +t:eq(NbtF.name, "nbt", "name") +t:eq(SnbtF.name, "snbt", "snbt name") +t:check(NbtF.caps.decode and NbtF.caps.encode and SnbtF.caps.decode and SnbtF.caps.encode, "caps") + +for i = 1, 12 do + local c = Fx.cases[i] + local v = F.load(c.gzip, { name = "level.dat" }) + t:check(v ~= nil, c.name .. ": F.load gzip") + local text = assert(F.saveString(v, { format = "snbt" })) + local back = assert(F.load(text, { format = "snbt" })) + t:eq(Nbt.print(back), Nbt.print(v), c.name .. ": NBT -> SNBT -> value") + local again = assert(F.save(v, nil, { format = "nbt" })) :: buffer + t:eq(buffer.readu8(again, 0), 0x1f, c.name .. ": saved gzip like the source") + t:eq(Nbt.print(F.load(again, { format = "nbt" })), Nbt.print(v), c.name .. ": saved file reads back") + t:eq(Nbt.info(F.load(again, { format = "nbt" })).name, c.root, c.name .. ": root name kept") + local raw = assert(F.save(v, nil, { format = "nbt", compression = "none" })) :: buffer + t:eq(buffer.tostring(raw), c.raw, c.name .. ": uncompressed = nbtlib's bytes") + local le = assert(F.load(c.header, { format = "nbt" })) + t:eq(buffer.tostring(assert(F.save(le, nil, { format = "nbt" })) :: buffer), c.header, c.name .. ": Bedrock level.dat same bytes") +end + +-- detection +do + local c = Fx.cases[3] + t:eq(F.detect(c.gzip, { name = "level.dat" }), "nbt", "detect gzip .dat") + t:eq(F.detect(c.raw, { name = "x.nbt" }), "nbt", "detect raw .nbt") +end + +-- errors +do + local _, e = NbtF.decode(Bytes.reader(buffer.fromstring("\10\0\0\1"))) + t:check(e and e.code == Err.TRUNCATED, "truncated") + local _, e3 = NbtF.encode(nil :: any) + t:check(e3 and e3.code == Err.ARG, "encode nil") +end + +local samples = {} +for i = 1, 6 do + table.insert(samples, Fx.cases[i].raw) + table.insert(samples, Fx.cases[i].header) +end +t:fuzz("decode", function(b: buffer) + return NbtF.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tests/data/snbt.luau b/tests/data/snbt.luau new file mode 100644 index 0000000..9b88fee --- /dev/null +++ b/tests/data/snbt.luau @@ -0,0 +1,47 @@ +-- data/snbt tests: the contract, nbtlib's SNBT text (indented and compact) through the api, conversion to and from +-- binary NBT (F.convert), detection against JSON, options (indent, quote), error codes, and the fuzz pass. The +-- grammar itself: tests/codecs/nbt.luau. Fixtures: tools/fixtures/nbt.py. +local T = require("@tests/T") +local F = require("@formats") +local SnbtF = require("@formats/data/snbt") +local Nbt = require("@formats/codecs/text/Nbt") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/nbt") + +local t = T.suite("data/snbt") + +t:eq(SnbtF.name, "snbt", "name") +t:check(SnbtF.caps.decode and SnbtF.caps.encode, "caps") + +for i = 1, 12 do + local c = Fx.cases[i] + local v = assert(F.load(c.snbt, { format = "snbt" })) + local bin = assert(F.convert(c.compact, "nbt", { format = "snbt", compression = "none" })) :: buffer + t:eq(Nbt.print(assert(Nbt.decode(bin))), Nbt.print(v), c.name .. ": SNBT -> NBT") + local text = assert(F.convert(c.raw, "snbt", { format = "nbt" })) :: buffer + t:eq(Nbt.print(assert(Nbt.parse(text))), Nbt.print(v), c.name .. ": NBT -> SNBT") + local pretty = assert(F.saveString(v, { format = "snbt", indent = "\t" })) + t:eq(Nbt.print(assert(F.load(pretty, { format = "snbt" }))), Nbt.print(v), c.name .. ": indented") +end + +do + t:eq(F.detect("{DataVersion:3465,size:[I;1,2,3]}"), "snbt", "detect snbt") + t:eq(F.detect('{"a": 1}'), "json", "json is not snbt") + t:eq(F.detect('{"a": 1b}'), "snbt", "typed number") + t:eq(F.detect(Fx.cases[3].compact, { name = "x.snbt" }), "snbt", "detect .snbt") + t:eq(F.saveString(Nbt.parse("{a:'x'}"), { format = "snbt", quote = "'" }), "{a:'x'}", "quote option") + local _, e = SnbtF.decode(Bytes.reader(buffer.fromstring("{a:"))) + t:check(e and e.code == Err.CORRUPT, "corrupt") + local _, e2 = SnbtF.encode({ a = function() end } :: any) + t:check(e2 and e2.code == Err.ARG, "encode a function") +end + +local texts = {} +for i = 1, 6 do + table.insert(texts, Fx.cases[i].snbt) +end +t:fuzz("decode", function(b: buffer) + return SnbtF.decode(Bytes.reader(b)) +end, texts) +t:done() diff --git a/tools/fixtures/nbt.py b/tools/fixtures/nbt.py new file mode 100644 index 0000000..4bb2364 --- /dev/null +++ b/tools/fixtures/nbt.py @@ -0,0 +1,152 @@ +# codecs/text/Nbt + data/nbt + data/snbt fixtures: random NBT trees (every tag type, nested lists / compounds, long +# extremes, BMP strings) written by Python's nbtlib (through nix) in Java big-endian and Bedrock little-endian, raw / +# gzip / zlib / with the Bedrock level.dat header, with nbtlib's SNBT text (indented and compact) and a canonical +# dump of the typed values; plus Bedrock network (varint) NBT from a small encoder here (nbtlib has none). +# tests/gen/nbt.luau { cases = { { name, raw, little, gzip, zlib, header, canon, snbt, compact, root } }, +# net = { { data, canon } } } +# canon: b s i l f d S: B I[a,b] L[a,b] +# [|a,b] {:=;...} (tests/codecs/nbt.luau computes the same text) + +BODY = r''' +import nbtlib, pickle, random, struct, sys, io, gzip, zlib +from nbtlib import Byte, Short, Int, Long, Float, Double, String, List, Compound, ByteArray, IntArray, LongArray +import numpy as np +rng = random.Random(7) +NAMES = {"Byte": "byte", "Short": "short", "Int": "int", "Long": "long", "Float": "float", "Double": "double", + "ByteArray": "byteArray", "String": "string", "List": "list", "Compound": "compound", "IntArray": "intArray", + "LongArray": "longArray", "End": "end"} +ALPH = "abcXYZ019_-.+ :\"'\\\n\t{}[],;é中ü" +def rstr(n=None): + n = rng.choice([0, 1, 4, 12, 40]) if n is None else n + return "".join(rng.choice(ALPH) for _ in range(n)) +def rkey(): + return rng.choice(["", "a", "Name", "x y", "id", "Data", rstr(rng.randrange(1, 8))]) +def scalar(kind): + if kind == "byte": return Byte(rng.choice([-128, -1, 0, 1, 127, rng.randrange(-128, 128)])) + if kind == "short": return Short(rng.choice([-32768, 32767, rng.randrange(-32768, 32768)])) + if kind == "int": return Int(rng.choice([-2**31, 2**31 - 1, 0, rng.randrange(-2**31, 2**31)])) + if kind == "long": return Long(rng.choice([-2**63, 2**63 - 1, 2**53, -2**53 - 1, 1, rng.randrange(-2**63, 2**63), rng.randrange(-2**40, 2**40)])) + if kind == "float": return Float(struct.unpack(">f", struct.pack(">f", rng.choice([0.0, -0.0, 1.5, 0.1, 3.4e38, 1e-40, rng.uniform(-1e6, 1e6)])))[0]) + if kind == "double": return Double(rng.choice([0.0, 1.0, -2.5, 0.1, 1e300, 5e-324, 1e15, 1e16, 123456789.123, rng.uniform(-1e9, 1e9)])) + if kind == "string": return String(rstr()) + if kind == "byteArray": return ByteArray([rng.randrange(-128, 128) for _ in range(rng.choice([0, 1, 5, 300]))]) + if kind == "intArray": return IntArray([rng.randrange(-2**31, 2**31) for _ in range(rng.choice([0, 1, 4, 50]))]) + if kind == "longArray": return LongArray([rng.choice([-2**63, 2**63 - 1, rng.randrange(-2**63, 2**63), rng.randrange(-100, 100)]) for _ in range(rng.choice([0, 1, 3, 40]))]) +KINDS = ["byte", "short", "int", "long", "float", "double", "string", "byteArray", "intArray", "longArray"] +CLS = {"byte": Byte, "short": Short, "int": Int, "long": Long, "float": Float, "double": Double, "string": String, + "byteArray": ByteArray, "intArray": IntArray, "longArray": LongArray} +def value(d): + r = rng.random() + if d >= 4 or r < 0.55: + return scalar(rng.choice(KINDS)) + if r < 0.8: + k = rng.choice(KINDS + ["compound", "list"]) + n = rng.choice([0, 1, 3, 8]) + if k == "compound": + return List[Compound]([compound(d + 1) for _ in range(n)]) + if k == "list": + return List[List]([List[Int]([Int(i) for i in range(rng.randrange(3))]) for _ in range(n)]) + return List[CLS[k]]([scalar(k) for _ in range(n)]) + return compound(d + 1) +def compound(d): + c = Compound() + for _ in range(rng.choice([0, 1, 3, 6, 10])): + c[rkey()] = value(d) + return c +def canon(t): + n = type(t).__name__ + if n.startswith("List"): n = "List" + if n == "Byte": return "b%d" % int(t) + if n == "Short": return "s%d" % int(t) + if n == "Int": return "i%d" % int(t) + if n == "Long": return "l%d" % int(t) + if n == "Float": return "f" + struct.pack(">f", float(t)).hex() + if n == "Double": return "d" + struct.pack(">d", float(t)).hex() + if n == "String": + b = str(t).encode("utf-8") + return "S%d:%s" % (len(b), str(t)) + if n == "ByteArray": return "B" + np.asarray(t, dtype=np.int8).tobytes().hex() + if n == "IntArray": return "I[" + ",".join(str(int(x)) for x in t) + "]" + if n == "LongArray": return "L[" + ",".join(str(int(x)) for x in t) + "]" + if n == "List": + return "[" + NAMES[t.subtype.__name__] + "|" + ",".join(canon(x) for x in t) + "]" + if n in ("Compound", "File"): + return "{" + ";".join("%d:%s=%s" % (len(k.encode()), k, canon(v)) for k, v in t.items()) + "}" + raise TypeError(n) +def raw(root, name, order): + f = io.BytesIO() + f.write(b"\x0a") + nbtlib.tag.write_string(name, f, order) + root.write(f, byteorder=order) + return f.getvalue() +cases = [] +for i in range(60): + root = compound(0) + if i == 0: + root = Compound() + name = rng.choice(["", "", "Schematic", "root", "é"]) + big, little = raw(root, name, "big"), raw(root, name, "little") + # nbtlib's own file loader must read back what we hand it (a sanity check of the writer here) + back = nbtlib.File.parse(io.BytesIO(big)) + assert canon(back) == canon(root) + header = struct.pack(">= 7 + if n: out.append(b | 0x80) + else: + out.append(b); return bytes(out) +def zz32(v): return uvar(((v << 1) ^ (v >> 31)) & 0xffffffff) +def zz64(v): return uvar(((v << 1) ^ (v >> 63)) & 0xffffffffffffffff) +def nstr(s): + b = s.encode(); return uvar(len(b)) + b +IDS = {"end": 0, "byte": 1, "short": 2, "int": 3, "long": 4, "float": 5, "double": 6, "byteArray": 7, "string": 8, + "list": 9, "compound": 10, "intArray": 11, "longArray": 12} +def kind(t): + n = type(t).__name__ + if n.startswith("List"): n = "List" + return NAMES[n] +def net(t): + k = kind(t) + if k == "byte": return struct.pack(" Date: Sat, 31 Oct 2026 14:25:41 -0500 Subject: [PATCH 2/7] ws-voxel: wip: codecs/model/Minecraft, model/schematic, Types.Voxels blocks / colors --- src/Formats/Types.luau | 12 + .../codecs/model/Minecraft/Colors.luau | 81 +++ .../codecs/model/Minecraft/Legacy.luau | 111 ++++ .../codecs/model/Minecraft/Packed.luau | 220 ++++++++ src/Formats/codecs/model/Minecraft/init.luau | 500 ++++++++++++++++++ src/Formats/model/schematic/Common.luau | 202 +++++++ src/Formats/model/schematic/Litematic.luau | 215 ++++++++ src/Formats/model/schematic/Mcedit.luau | 213 ++++++++ src/Formats/model/schematic/Sponge.luau | 131 +++++ src/Formats/model/schematic/init.luau | 309 +++++++++++ tools/fixtures/schematic.py | 243 +++++++++ 11 files changed, 2237 insertions(+) create mode 100644 src/Formats/codecs/model/Minecraft/Colors.luau create mode 100644 src/Formats/codecs/model/Minecraft/Legacy.luau create mode 100644 src/Formats/codecs/model/Minecraft/Packed.luau create mode 100644 src/Formats/codecs/model/Minecraft/init.luau create mode 100644 src/Formats/model/schematic/Common.luau create mode 100644 src/Formats/model/schematic/Litematic.luau create mode 100644 src/Formats/model/schematic/Mcedit.luau create mode 100644 src/Formats/model/schematic/Sponge.luau create mode 100644 src/Formats/model/schematic/init.luau create mode 100644 tools/fixtures/schematic.py diff --git a/src/Formats/Types.luau b/src/Formats/Types.luau index 63e3d79..55b983e 100644 --- a/src/Formats/Types.luau +++ b/src/Formats/Types.luau @@ -360,6 +360,18 @@ export type Voxels = { data: buffer, -- size x * y * z bytes, cell (x, y, z) at x + sx * (y + sy * z) palette: { { number } }, -- palette[i] = { r, g, b, a } 0..255 (sRGB) for i = 1 .. 255 (shared between a file's models) materials: { [number]: VoxelMaterial }?, -- by palette index + -- block grids (Minecraft schematics / regions): the exact block state of every cell, data / palette being its + -- colour view (block colours from a default table) + blocks: VoxelBlocks?, + -- true-colour grids (Qubicle): the exact 32-bit colour of every cell as r, g, b, a bytes (u32 little-endian, + -- a = 0 empty), data / palette being an indexed view of it + colors: buffer?, +} +export type VoxelBlocks = { + palette: { string }, -- block states ("minecraft:oak_stairs[facing=east,half=bottom]"), palette[1] is index 0 + data: buffer, -- u16 little-endian per cell (same cell order as Voxels.data): 0-based index into palette + blockEntities: { any }?, -- the format's block entity records (NBT compounds; positions relative to the grid) + entities: { any }?, -- entity records (NBT compounds) } local Voxels = {} -- new(sx, sy, sz, palette?) -> an empty grid (the palette defaults to grey ramps: callers set their own) diff --git a/src/Formats/codecs/model/Minecraft/Colors.luau b/src/Formats/codecs/model/Minecraft/Colors.luau new file mode 100644 index 0000000..1d66576 --- /dev/null +++ b/src/Formats/codecs/model/Minecraft/Colors.luau @@ -0,0 +1,81 @@ +--!strict +-- codecs/model/Minecraft/Colors: the built-in default colour of Minecraft blocks, for showing block grids as coloured +-- voxels. Hand-made for this library (approximate average colours picked by eye; no game assets or wiki tables were +-- copied): exact block names, then families by dye colour and wood type; codecs/model/Minecraft resolves stairs / +-- slabs / walls / ... to their base block and falls back to keywords. Format: name=rrggbb or name=rrggbbaa. +local Colors = {} + +Colors.BLOCKS = [[ +stone=7d7d7d granite=956756 polished_granite=9a6a59 diorite=bcbcbc polished_diorite=c0c0c2 andesite=888889 +polished_andesite=848686 grass_block=6d9a3f dirt=866043 coarse_dirt=77553b podzol=5b3f18 rooted_dirt=90674c +mud=3c3a3d cobblestone=7a7a7a bedrock=555555 sand=dbcf9f red_sand=be6621 gravel=837f7e suspicious_sand=d6c996 +suspicious_gravel=817c7b sandstone=d8cb9b chiseled_sandstone=d8ca9b cut_sandstone=d9cd9e smooth_sandstone=dfd5a5 +red_sandstone=b5621f cut_red_sandstone=bc6620 chiseled_red_sandstone=b7601e smooth_red_sandstone=b5621f +sponge=c3c04a wet_sponge=aaab3c glass=c0f5fe50 tinted_glass=2c262ec0 lapis_block=1f438c gold_block=f6d03d +iron_block=dcdcdc diamond_block=62ede4 emerald_block=2acb57 redstone_block=af1805 coal_block=101010 +netherite_block=433e40 copper_block=c06c50 exposed_copper=a17e68 weathered_copper=6c9a6f oxidized_copper=52a284 +cut_copper=bf6b51 raw_iron_block=a6896b raw_gold_block=dda92e raw_copper_block=9a6a4e amethyst_block=8562b8 +budding_amethyst=84609f bricks=976253 bookshelf=75603d chiseled_bookshelf=b29159 mossy_cobblestone=6e7660 +obsidian=0f0a18 crying_obsidian=200a3c tnt=db4130 spawner=24364a chest=a0742d trapped_chest=a0742d +ender_chest=2a3b3c crafting_table=81633c furnace=6d6d6d snow=f9fefe snow_block=f9fefe powder_snow=f8fdfd +ice=92b8fec8 packed_ice=8db4fa blue_ice=74a7fd frosted_ice=8cb4fac8 clay=a0a6b3 pumpkin=c6761a +carved_pumpkin=c27118 jack_o_lantern=d79a32 netherrack=612626 soul_sand=513e32 soul_soil=4b3a2e basalt=505055 +polished_basalt=636367 smooth_basalt=48484e glowstone=ab8354 magma_block=8e3f1f nether_bricks=2c1518 +red_nether_bricks=450709 cracked_nether_bricks=281417 chiseled_nether_bricks=2f171c nether_wart_block=720202 +warped_wart_block=167879 end_stone=dbdea0 end_stone_bricks=dae0a2 purpur_block=a97ea9 purpur_pillar=ab81ab +prismarine=63a29a prismarine_bricks=63ab9e dark_prismarine=335b4b sea_lantern=acc7be hay_block=a68b0c +terracotta=985e43 quartz_block=ebe5de smooth_quartz=ece6df quartz_bricks=eae5dd quartz_pillar=ebe6e0 +chiseled_quartz_block=e7e2da smooth_stone=9e9e9e stone_bricks=7a7979 mossy_stone_bricks=737969 +cracked_stone_bricks=767676 chiseled_stone_bricks=777777 deepslate=505053 cobbled_deepslate=4d4d51 +polished_deepslate=484849 deepslate_bricks=474747 cracked_deepslate_bricks=414141 deepslate_tiles=373737 +cracked_deepslate_tiles=343434 chiseled_deepslate=363637 reinforced_deepslate=505350 tuff=6c6d67 +polished_tuff=626a63 tuff_bricks=626660 calcite=dfe0dc dripstone_block=866b5c pointed_dripstone=816757 +moss_block=596d2d moss_carpet=596d2d pale_moss_block=6b7069 melon=6f9118 cactus=587f28 sugar_cane=95c165 +bamboo=5d8f1e bamboo_block=7f9030 stripped_bamboo_block=c0ad50 water=3f76e4b4 bubble_column=3f76e4b4 +lava=cf5b14 short_grass=5b8a32 grass=5b8a32 tall_grass=5b8a32 fern=586e30 large_fern=586e30 dead_bush=6b4f29 +vine=3c6e18 glow_lichen=708079 lily_pad=208030 seagrass=307b16 tall_seagrass=307b16 kelp=3b7f22 +kelp_plant=3b7f22 dried_kelp_block=323b27 red_mushroom_block=c82e2d brown_mushroom_block=957051 +mushroom_stem=cbc4b9 red_mushroom=d84a3e brown_mushroom=9a7759 slime_block=6fc05bc8 honey_block=fba92fc8 +honeycomb_block=e5941e bone_block=e1ddc9 shroomlight=f19346 target=e2aa9e respawn_anchor=4b1e86 +lodestone=939599 blackstone=2a2328 polished_blackstone=35303b polished_blackstone_bricks=302a32 +cracked_polished_blackstone_bricks=2c2629 chiseled_polished_blackstone=35303b gilded_blackstone=382b26 +crimson_nylium=831f1f warped_nylium=2b7265 crimson_roots=7e0812 warped_roots=148a7c packed_mud=8e6b50 +mud_bricks=89684f sculk=0d1e24 sculk_catalyst=2d3a3b sculk_sensor=074654 sculk_shrieker=c6cdab +redstone_lamp=5f361e note_block=58392a jukebox=5d4030 beacon=75dcd7 observer=626262 piston=9a8d6c +sticky_piston=8b9c66 piston_head=9a8d6c dispenser=7a7a7a dropper=7a7a7a hopper=434343 anvil=444444 +chipped_anvil=444444 damaged_anvil=444444 cauldron=4a4a4a rail=7d6c4b powered_rail=8a6d3e detector_rail=7b6853 +activator_rail=74574b ladder=7c5f35 scaffolding=aa8449 lantern=6a5b54 soul_lantern=4a6366 campfire=6e5638 +soul_campfire=4e5d5d barrel=86643b smoker=5a5853 blast_furnace=6c6b6b cartography_table=685032 +fletching_table=c5b485 smithing_table=39394a loom=8e7965 stonecutter=7b7672 grindstone=8e8e8e composter=704a26 +beehive=b8945b bee_nest=c5964b farmland=8f6646 dirt_path=94793f mycelium=6f6365 torch=ffd80060 +wall_torch=ffd80060 soul_torch=6be1e360 redstone_torch=c0210f60 redstone_wire=9e0b0060 lever=6e6e6e60 +cobweb=e4e9ea80 iron_bars=8b8d8b90 chain=3a404e90 end_rod=e0d8d0 chorus_plant=5e395e chorus_flower=977a97 +dragon_egg=0c0910 end_portal_frame=5b7860 enchanting_table=813838 brewing_stand=7a654f flower_pot=7d4536 +cake=f8dede conduit=9f8b71 lectern=ad8a54 bell=fdd533 decorated_pot=8f4f35 crafter=7a6c64 +trial_spawner=3b4a55 vault=46545c heavy_core=4c5056 command_block=b5886c chain_command_block=829f8f +repeating_command_block=8370b0 structure_block=58475b jigsaw=50455a +dandelion=e0c41c poppy=c42b1a blue_orchid=2aa8d0 allium=b878e8 azure_bluet=dfe6d7 red_tulip=c43b1b +orange_tulip=e07e1b white_tulip=e0e8db pink_tulip=e8b8d8 oxeye_daisy=e8e8c8 cornflower=4f76d8 +lily_of_the_valley=e8e8e8 wither_rose=2a2c18 sunflower=f0c71d lilac=b88cb8 rose_bush=b02a1e peony=e8b8e0 +torchflower=d9b14e pitcher_plant=7a97c8 pink_petals=f0b8d0 spore_blossom=d066a8 azalea=5f7a2c +flowering_azalea=7c6b6e sweet_berry_bush=3f6a2f cocoa=8c5428 wheat=a99c30 carrots=4a9a1e potatoes=4c9a2a +beetroots=5a8a2a nether_wart=8a1818 crimson_fungus=8a2525 warped_fungus=2a7a6e twisting_vines=148a7c +weeping_vines=8a1414 hanging_roots=a17561 big_dripleaf=6b8f34 small_dripleaf=6b8f34 cave_vines=5a6d23 +frogspawn=66605ca0 sniffer_egg=8a5045 turtle_egg=dcd8b8 sea_pickle=6a7030 mangrove_roots=4b3c27 +muddy_mangrove_roots=46413a ochre_froglight=f6e8a6 verdant_froglight=dcf0d6 pearlescent_froglight=f1e1ea +creaking_heart=5a4a3c resin_block=d9661c resin_bricks=ce5a1a +]] + +-- wool-like colour of each dye, then concrete and terracotta (same order as Colors.DYES) +Colors.DYES = { "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black" } +Colors.WOOL = "e9ecec f07613 bd44b3 3aafd9 f8c527 70b919 ed8dac 3e4447 8e8e86 158991 792aac 35399d 724728 546d1b a12722 141519" +Colors.CONCRETE = "cfd5d6 e06100 a9309f 2389c6 f0af15 5ea818 d5658e 36393d 7d7d73 157788 64209c 2c2e8f 603b1f 495b24 8e2020 080a0f" +Colors.TERRACOTTA = "d1b2a1 a15325 95576c 716c89 ba8523 677534 a14e4e 392a23 876a61 575b5b 764656 4a3b5b 4d3323 4c532a 8f3d2e 251610" + +-- wood types: planks, bark (log / wood), leaves +Colors.WOODS = { "oak", "spruce", "birch", "jungle", "acacia", "dark_oak", "mangrove", "cherry", "pale_oak", "bamboo", "crimson", "warped" } +Colors.PLANKS = "a2834f 735531 c0af79 a07351 a85a32 432b14 763631 e3b3ad e4d9d3 c1ad50 653147 2b6963" +Colors.BARK = "6d5533 3a2510 d8d7d2 55441a 676157 3e2f17 543a26 371b22 524a46 7f9030 5c1919 3a3a4d" +Colors.LEAVES = "4a7a20 3d5d3d 5f8a3c 3f8a1c 4b7a1e 3c6a18 4b8a28 e5adc2 878d76 5d8f1e 831f1f 2b7265" + +return Colors diff --git a/src/Formats/codecs/model/Minecraft/Legacy.luau b/src/Formats/codecs/model/Minecraft/Legacy.luau new file mode 100644 index 0000000..9d1348e --- /dev/null +++ b/src/Formats/codecs/model/Minecraft/Legacy.luau @@ -0,0 +1,111 @@ +--!strict +-- codecs/model/Minecraft/Legacy: numeric block ids of Minecraft before 1.13 (the .schematic format, Anvil chunks with +-- Blocks / Data arrays), from the Minecraft wiki "Java Edition data values/Pre-flattening" page (facts, not code): +-- the 1.12 name of every id, and how the data value picks a variant for the blocks whose colour or wood depends on it +-- (the modern name of that variant: wool 14 -> red_wool, planks 2 -> birch_planks). +local Legacy = {} + +local function words(s: string): { string } + local out = {} + for w in string.gmatch(s, "%S+") do + table.insert(out, w) + end + return out +end + +-- ids 0 .. 255 (NAMES[id + 1]), "-" = unused +Legacy.NAMES = words([[air stone grass dirt cobblestone planks sapling bedrock flowing_water water flowing_lava +lava sand gravel gold_ore iron_ore coal_ore log leaves sponge glass lapis_ore lapis_block dispenser sandstone noteblock +bed golden_rail detector_rail sticky_piston web tallgrass deadbush piston piston_head wool piston_extension +yellow_flower red_flower brown_mushroom red_mushroom gold_block iron_block double_stone_slab stone_slab brick_block tnt +bookshelf mossy_cobblestone obsidian torch fire mob_spawner oak_stairs chest redstone_wire diamond_ore diamond_block +crafting_table wheat farmland furnace lit_furnace standing_sign wooden_door ladder rail stone_stairs wall_sign lever +stone_pressure_plate iron_door wooden_pressure_plate redstone_ore lit_redstone_ore unlit_redstone_torch redstone_torch +stone_button snow_layer ice snow cactus clay reeds jukebox fence pumpkin netherrack soul_sand glowstone portal +lit_pumpkin cake unpowered_repeater powered_repeater stained_glass trapdoor monster_egg stonebrick +brown_mushroom_block red_mushroom_block iron_bars glass_pane melon_block pumpkin_stem melon_stem vine fence_gate +brick_stairs stone_brick_stairs mycelium waterlily nether_brick nether_brick_fence nether_brick_stairs nether_wart +enchanting_table brewing_stand cauldron end_portal end_portal_frame end_stone dragon_egg redstone_lamp +lit_redstone_lamp double_wooden_slab wooden_slab cocoa sandstone_stairs emerald_ore ender_chest tripwire_hook tripwire +emerald_block spruce_stairs birch_stairs jungle_stairs command_block beacon cobblestone_wall flower_pot carrots +potatoes wooden_button skull anvil trapped_chest light_weighted_pressure_plate heavy_weighted_pressure_plate +unpowered_comparator powered_comparator daylight_detector redstone_block quartz_ore hopper quartz_block quartz_stairs +activator_rail dropper stained_hardened_clay stained_glass_pane leaves2 log2 acacia_stairs dark_oak_stairs slime +barrier iron_trapdoor prismarine sea_lantern hay_block carpet hardened_clay coal_block packed_ice double_plant +standing_banner wall_banner daylight_detector_inverted red_sandstone red_sandstone_stairs double_stone_slab2 +stone_slab2 spruce_fence_gate birch_fence_gate jungle_fence_gate dark_oak_fence_gate acacia_fence_gate spruce_fence +birch_fence jungle_fence dark_oak_fence acacia_fence spruce_door birch_door jungle_door acacia_door dark_oak_door +end_rod chorus_plant chorus_flower purpur_block purpur_pillar purpur_stairs purpur_double_slab purpur_slab end_bricks +beetroots grass_path end_gateway repeating_command_block chain_command_block frosted_ice magma nether_wart_block +red_nether_brick bone_block structure_void observer white_shulker_box orange_shulker_box magenta_shulker_box +light_blue_shulker_box yellow_shulker_box lime_shulker_box pink_shulker_box gray_shulker_box silver_shulker_box +cyan_shulker_box purple_shulker_box blue_shulker_box brown_shulker_box green_shulker_box red_shulker_box +black_shulker_box white_glazed_terracotta orange_glazed_terracotta magenta_glazed_terracotta +light_blue_glazed_terracotta yellow_glazed_terracotta lime_glazed_terracotta pink_glazed_terracotta +gray_glazed_terracotta silver_glazed_terracotta cyan_glazed_terracotta purple_glazed_terracotta +blue_glazed_terracotta brown_glazed_terracotta green_glazed_terracotta red_glazed_terracotta black_glazed_terracotta +concrete concrete_powder - - structure_block]]) + +-- legacy names whose modern name differs (data value not involved; only one-to-one renames, so the way back is exact: +-- lit_furnace, powered_repeater, ... keep their legacy names) +Legacy.RENAMED = { + grass = "grass_block", brick_block = "bricks", stonebrick = "stone_bricks", hardened_clay = "terracotta", + melon_block = "melon", lit_pumpkin = "jack_o_lantern", slime = "slime_block", magma = "magma_block", + red_nether_brick = "red_nether_bricks", nether_brick = "nether_bricks", end_bricks = "end_stone_bricks", + mob_spawner = "spawner", web = "cobweb", snow_layer = "snow", snow = "snow_block", noteblock = "note_block", + quartz_ore = "nether_quartz_ore", reeds = "sugar_cane", waterlily = "lily_pad", flowing_water = "water", + flowing_lava = "lava", tallgrass = "short_grass", grass_path = "dirt_path", double_stone_slab = "smooth_stone", + stone_slab = "smooth_stone_slab", deadbush = "dead_bush", yellow_flower = "dandelion", + + fence = "oak_fence", fence_gate = "oak_fence_gate", + wooden_door = "oak_door", trapdoor = "oak_trapdoor", wooden_pressure_plate = "oak_pressure_plate", + wooden_button = "oak_button", stone_stairs = "cobblestone_stairs", standing_sign = "oak_sign", + wall_sign = "oak_wall_sign", golden_rail = "powered_rail", portal = "nether_portal", piston_extension = "moving_piston", + + silver_shulker_box = "light_gray_shulker_box", silver_glazed_terracotta = "light_gray_glazed_terracotta", + + monster_egg = "infested_stone", + standing_banner = "white_banner", wall_banner = "white_wall_banner", skull = "skeleton_skull", + bed = "red_bed", +} + +-- legacy names whose data value selects the variant: the modern names by data value (0-based) +local DYED = "white orange magenta light_blue yellow lime pink gray light_gray cyan purple blue brown green red black" +local function dyed(suffix: string): { string } + local out = {} + for i, d in words(DYED) do + out[i] = d .. "_" .. suffix + end + return out +end +Legacy.VARIANTS = { + stone = { "stone", "granite", "polished_granite", "diorite", "polished_diorite", "andesite", "polished_andesite" }, + dirt = { "dirt", "coarse_dirt", "podzol" }, + planks = { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks" }, + wooden_slab = { "oak_slab", "spruce_slab", "birch_slab", "jungle_slab", "acacia_slab", "dark_oak_slab" }, + sapling = { "oak_sapling", "spruce_sapling", "birch_sapling", "jungle_sapling", "acacia_sapling", "dark_oak_sapling" }, + sand = { "sand", "red_sand" }, + log = { "oak_log", "spruce_log", "birch_log", "jungle_log" }, -- data % 4 + log2 = { "acacia_log", "dark_oak_log" }, + leaves = { "oak_leaves", "spruce_leaves", "birch_leaves", "jungle_leaves" }, + leaves2 = { "acacia_leaves", "dark_oak_leaves" }, + sponge = { "sponge", "wet_sponge" }, + sandstone = { "sandstone", "chiseled_sandstone", "cut_sandstone" }, + red_sandstone = { "red_sandstone", "chiseled_red_sandstone", "cut_red_sandstone" }, + stonebrick = { "stone_bricks", "mossy_stone_bricks", "cracked_stone_bricks", "chiseled_stone_bricks" }, + quartz_block = { "quartz_block", "chiseled_quartz_block", "quartz_pillar" }, + prismarine = { "prismarine", "prismarine_bricks", "dark_prismarine" }, + cobblestone_wall = { "cobblestone_wall", "mossy_cobblestone_wall" }, + red_flower = { "poppy", "blue_orchid", "allium", "azure_bluet", "red_tulip", "orange_tulip", "white_tulip", "pink_tulip", "oxeye_daisy" }, + double_plant = { "sunflower", "lilac", "tall_grass", "large_fern", "rose_bush", "peony" }, + wool = dyed("wool"), + carpet = dyed("carpet"), + stained_glass = dyed("stained_glass"), + stained_glass_pane = dyed("stained_glass_pane"), + stained_hardened_clay = dyed("terracotta"), + concrete = dyed("concrete"), + concrete_powder = dyed("concrete_powder"), +} +Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 } + +return Legacy diff --git a/src/Formats/codecs/model/Minecraft/Packed.luau b/src/Formats/codecs/model/Minecraft/Packed.luau new file mode 100644 index 0000000..75cbf83 --- /dev/null +++ b/src/Formats/codecs/model/Minecraft/Packed.luau @@ -0,0 +1,220 @@ +--!strict +--!native +--!optimize 2 +-- codecs/model/Minecraft/Packed: Minecraft's packed index arrays. New code, from the Minecraft wiki "Chunk format" and +-- the Sponge / Litematica schematic specs: long arrays (little-endian int64s as codecs/text/Nbt keeps them) holding +-- bits-wide indices either spanning long boundaries (Litematica, chunks before 1.16) or not (chunks since 1.16: +-- floor(64 / bits) per long, the rest padding), and the varint byte arrays of Sponge schematics. Indices are written +-- to / read from u16 little-endian buffers. Every access is bounds-checked first; never throws. +local Packed = {} + +local readu8, readu16, readu32 = buffer.readu8, buffer.readu16, buffer.readu32 +local writeu8, writeu16 = buffer.writeu8, buffer.writeu16 +local extract, band, rshift, lshift, bor = bit32.extract, bit32.band, bit32.rshift, bit32.lshift, bit32.bor + +-- longsNeeded(count, bits, spanning) -> the number of longs a packed array of count indices takes +function Packed.longsNeeded(count: number, bits: number, spanning: boolean): number + if spanning then + return (count * bits + 63) // 64 + end + local per = 64 // bits + return (count + per - 1) // per +end + +-- unpack(longs, bits, count, spanning, out, max) -> true | false, message: count indices into out (u16 LE, from byte +-- 0); an index >= max is an error. bits 1 .. 16. +function Packed.unpack(longs: buffer, bits: number, count: number, spanning: boolean, out: buffer, max: number): (boolean, string?) + if bits < 1 or bits > 16 then + return false, "unsupported: " .. bits .. "-bit packed indices" + end + local need = Packed.longsNeeded(count, bits, spanning) + if buffer.len(longs) < need * 8 then + return false, "packed array too short (" .. buffer.len(longs) // 8 .. " longs, need " .. need .. ")" + end + if buffer.len(out) < count * 2 then + return false, "output too small" + end + -- a copy with 4 bytes of padding, so every 32-bit read stays in range + local n = need * 8 + local src = buffer.create(n + 4) + buffer.copy(src, 0, longs, 0, n) + if spanning then + local p = 0 + for i = 0, count - 1 do + local v = extract(readu32(src, rshift(p, 3)), band(p, 7), bits) + if v >= max then + return false, "index " .. v .. " past the palette (" .. max .. ")" + end + writeu16(out, i * 2, v) + p += bits + end + else + local per = 64 // bits + local i = 0 + local base = 0 + while i < count do + local p = 0 + for _ = 1, per do + if i >= count then + break + end + local v = extract(readu32(src, base + rshift(p, 3)), band(p, 7), bits) + if v >= max then + return false, "index " .. v .. " past the palette (" .. max .. ")" + end + writeu16(out, i * 2, v) + i += 1 + p += bits + end + base += 8 + end + end + return true, nil +end + +-- pack(indices, count, bits, spanning) -> longs buffer (little-endian int64s): the inverse of unpack +function Packed.pack(indices: buffer, count: number, bits: number, spanning: boolean): buffer + local need = Packed.longsNeeded(count, bits, spanning) + local out = buffer.create(need * 8 + 4) + local per = 64 // bits + for i = 0, count - 1 do + local v = readu16(indices, i * 2) + local p = if spanning then i * bits else (i // per) * 64 + (i % per) * bits + local at = rshift(p, 3) + local sh = band(p, 7) + -- OR the value in byte by byte (up to 3 bytes for 16 bits at a shift of 7) + local x = lshift(v, sh) + for k = 0, 2 do + local bits8 = band(rshift(x, k * 8), 0xff) + if bits8 ~= 0 then + writeu8(out, at + k, bor(readu8(out, at + k), bits8)) + end + end + end + local res = buffer.create(need * 8) + buffer.copy(res, 0, out, 0, need * 8) + return res +end + +-- bitsFor(n, min) -> bits for indices 0 .. n - 1 (at least min) +function Packed.bitsFor(n: number, min: number): number + local b = min + while lshift(1, b) < n and b < 31 do + b += 1 + end + return b +end + +-- varints(src, offset, length, count, out, max) -> true | false, message: count unsigned LEB128 varints (Sponge +-- BlockData) into out (u16 LE) +function Packed.varints(src: buffer, offset: number, length: number, count: number, out: buffer, max: number): (boolean, string?) + if buffer.len(out) < count * 2 or offset + length > buffer.len(src) then + return false, "bad varint array arguments" + end + local p, e = offset, offset + length + for i = 0, count - 1 do + local v, sh = 0, 0 + while true do + if p >= e then + return false, "truncated: block data ends after " .. i .. " of " .. count .. " entries" + end + local c = readu8(src, p) + p += 1 + v += band(c, 0x7f) * 2 ^ sh + if c < 128 then + break + end + sh += 7 + if sh > 28 then + return false, "varint too long" + end + end + if v >= max then + return false, "index " .. v .. " past the palette (" .. max .. ")" + end + writeu16(out, i * 2, v) + end + return true, nil +end + +-- toVarints(indices, count) -> buffer: count u16 indices as unsigned LEB128 varints +function Packed.toVarints(indices: buffer, count: number): buffer + local out = buffer.create(count * 3) + local p = 0 + for i = 0, count - 1 do + local v = readu16(indices, i * 2) + while v >= 128 do + writeu8(out, p, band(v, 0x7f) + 128) + p += 1 + v = rshift(v, 7) + end + writeu8(out, p, v) + p += 1 + end + local res = buffer.create(p) + buffer.copy(res, 0, out, 0, p) + return res +end + +-- nibble(src, offset, i, highFirst) -> the 4-bit value i of a nibble array (Minecraft: low nibble first; WorldEdit's +-- AddBlocks: high nibble first) +function Packed.nibble(src: buffer, offset: number, i: number, highFirst: boolean): number + local b = readu8(src, offset + rshift(i, 1)) + local odd = band(i, 1) == 1 + if odd == highFirst then + return band(b, 15) + end + return rshift(b, 4) +end + +-- setNibble(dst, offset, i, v, highFirst) +function Packed.setNibble(dst: buffer, offset: number, i: number, v: number, highFirst: boolean) + local at = offset + rshift(i, 1) + local b = readu8(dst, at) + local odd = band(i, 1) == 1 + if odd == highFirst then + writeu8(dst, at, bor(band(b, 0xf0), band(v, 15))) + else + writeu8(dst, at, bor(band(b, 0x0f), lshift(band(v, 15), 4))) + end +end + +-- fromYzx(src, sx, sy, sz, dst?, ox?, oy?, oz?, dsx?, dsy?) -> dst: u16 cells in Minecraft's order (x fastest, then +-- z, then y: schematics, chunk sections) to Types.Voxels order (x, then y, then z), into dst (default a new +-- sx * sy * sz grid) at cell offset (ox, oy, oz) of a dsx * dsy * ... grid. The caller checks the ranges. +function Packed.fromYzx(src: buffer, sx: number, sy: number, sz: number, dst: buffer?, ox: number?, oy: number?, oz: number?, dsx: number?, dsy: number?): buffer + local out = dst or buffer.create(sx * sy * sz * 2) + local bx, by, bz = ox or 0, oy or 0, oz or 0 + local wx, wy = dsx or sx, dsy or sy + local i = 0 + for y = 0, sy - 1 do + for z = 0, sz - 1 do + local d = (bx + wx * ((by + y) + wy * (bz + z))) * 2 + for _ = 0, sx - 1 do + writeu16(out, d, readu16(src, i)) + i += 2 + d += 2 + end + end + end + return out +end + +-- toYzx(src, sx, sy, sz) -> buffer: Types.Voxels order to Minecraft's (the inverse of fromYzx) +function Packed.toYzx(src: buffer, sx: number, sy: number, sz: number): buffer + local out = buffer.create(sx * sy * sz * 2) + local i = 0 + for y = 0, sy - 1 do + for z = 0, sz - 1 do + local s = (sx * (y + sy * z)) * 2 + for _ = 0, sx - 1 do + writeu16(out, i, readu16(src, s)) + i += 2 + s += 2 + end + end + end + return out +end + +return Packed diff --git a/src/Formats/codecs/model/Minecraft/init.luau b/src/Formats/codecs/model/Minecraft/init.luau new file mode 100644 index 0000000..ded3ef3 --- /dev/null +++ b/src/Formats/codecs/model/Minecraft/init.luau @@ -0,0 +1,500 @@ +--!strict +-- codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code. +-- Block states ("minecraft:oak_stairs[facing=east,half=bottom]": parse / format / NBT compound form), the default +-- block colour table (codecs/model/Minecraft/Colors, hand-made) with fallbacks by family, the pre-1.13 numeric ids +-- (codecs/model/Minecraft/Legacy), packed index arrays (codecs/model/Minecraft/Packed), and the bridge between block +-- grids and Types.Voxels: voxels.blocks holds the exact states (u16 indices into a state palette), voxels.data / +-- palette their colours; writing a grid without blocks picks the block nearest in colour for each palette colour. +-- +-- local Mc = require("@formats/codecs/model/Minecraft") +-- local name, props = Mc.parseState("minecraft:oak_log[axis=y]") -- "minecraft:oak_log", { { "axis", "y" } } +-- local rgba = Mc.color("minecraft:red_wool") -- { r, g, b, a } | nil for air +-- local v = Mc.voxels(sx, sy, sz, states, indices) -- a Types.Voxels with .blocks +-- local states, indices = Mc.blocksOf(v) -- back (or chosen by colour) +local Types = require("@formats/Types") +local Nbt = require("@formats/codecs/text/Nbt") +local Colors = require("@formats/codecs/model/Minecraft/Colors") +local Legacy = require("@formats/codecs/model/Minecraft/Legacy") +local Packed = require("@formats/codecs/model/Minecraft/Packed") + +local Minecraft = {} + +Minecraft.Packed = Packed +Minecraft.Legacy = Legacy + +-- ------------------------------------------------------------------------------------------------ block states +-- parseState(s) -> name (namespace added when missing), props { { key, value } } in their order +function Minecraft.parseState(s: string): (string, { { string } }) + local name, rest = string.match(s, "^%s*([^%[%s]*)%s*(.*)$") + local n = name or "" + if n ~= "" and not string.find(n, ":", 1, true) then + n = "minecraft:" .. n + end + local props = {} + local body = rest and string.match(rest :: string, "^%[(.*)%]%s*$") + if body then + for pair in string.gmatch(body, "[^,]+") do + local k, v = string.match(pair, "^%s*([^=%s]+)%s*=%s*(.-)%s*$") + if k then + table.insert(props, { k, v :: string }) + end + end + end + return n, props +end + +-- stateString(name, props?) -> "name[k=v,...]" (props { { k, v } } in order, or a map: keys sorted) +function Minecraft.stateString(name: string, props: { any }?): string + if not props or next(props) == nil then + return name + end + local parts = {} + if props[1] ~= nil then + for _, kv in props do + table.insert(parts, kv[1] .. "=" .. tostring(kv[2])) + end + else + for _, k in Types.keys(props) do + table.insert(parts, tostring(k) .. "=" .. tostring((props :: any)[k])) + end + end + return name .. "[" .. table.concat(parts, ",") .. "]" +end + +-- stateFromNbt(compound) -> the state string of a palette entry { Name, Properties? } (litematic, chunk sections) +function Minecraft.stateFromNbt(c: any): string? + if type(c) ~= "table" or type(c.Name) ~= "string" then + return nil + end + local props = {} + if type(c.Properties) == "table" then + for _, k in Types.keys(c.Properties) do + local v = c.Properties[k] + table.insert(props, { k, if type(v) == "string" then v else tostring(Nbt.number(v) or v) }) + end + end + return Minecraft.stateString(c.Name, props) +end + +-- stateToNbt(state) -> { Name, Properties? } (a Types.object; Properties in the state's order) +function Minecraft.stateToNbt(s: string): { [string]: any } + local name, props = Minecraft.parseState(s) + local c = Types.object({ Name = name }, { "Name" }) + if #props > 0 then + local p, keys = {}, {} + for _, kv in props do + p[kv[1]] = kv[2] + table.insert(keys, kv[1]) + end + Types.set(c, "Properties", Types.object(p, keys)) + end + return c +end + +-- baseName(state) -> the name without namespace and properties ("minecraft:oak_log[axis=y]" -> "oak_log") +function Minecraft.baseName(s: string): string + local name = string.match(s, "^%s*([^%[%s]*)") or "" + return string.match(name, ":(.*)$") or name +end + +local AIR = { air = true, cave_air = true, void_air = true, structure_void = true, light = true, barrier = true, moving_piston = true } +-- isAir(state) -> true for blocks that are not drawn (air, cave_air, void_air, structure_void, light, barrier) +function Minecraft.isAir(s: string): boolean + return AIR[Minecraft.baseName(s)] == true +end + +-- ------------------------------------------------------------------------------------------------ colours +local function hex(h: string): { number } + local c = { tonumber(string.sub(h, 1, 2), 16) or 0, tonumber(string.sub(h, 3, 4), 16) or 0, tonumber(string.sub(h, 5, 6), 16) or 0, 255 } + if #h >= 8 then + c[4] = tonumber(string.sub(h, 7, 8), 16) or 255 + end + return c +end +local function list(s: string): { { number } } + local out = {} + for h in string.gmatch(s, "%x+") do + table.insert(out, hex(h)) + end + return out +end + +local EXACT: { [string]: { number } } = {} +for name, h in string.gmatch(Colors.BLOCKS, "([%w_]+)=(%x+)") do + EXACT[name] = hex(h) +end +local WOOL, CONCRETE, TERRACOTTA = list(Colors.WOOL), list(Colors.CONCRETE), list(Colors.TERRACOTTA) +local PLANKS, BARK, LEAVES = list(Colors.PLANKS), list(Colors.BARK), list(Colors.LEAVES) +-- longest prefixes first, so light_blue wins over blue and dark_oak over oak +local function byLength(names: { string }): { { any } } + local out = {} + for i, n in names do + table.insert(out, { n, i }) + end + table.sort(out, function(a, b) + return #a[1] > #b[1] + end) + return out +end +local DYES, WOODS = byLength(Colors.DYES), byLength(Colors.WOODS) +local SUFFIXES = { + "_wall_hanging_sign", "_hanging_sign", "_wall_sign", "_sign", "_fence_gate", "_fence", "_pressure_plate", "_button", + "_trapdoor", "_door", "_stairs", "_slab", "_wall", "_pane", "_carpet", "_wall_banner", "_banner", "_bars", +} +local PREFIXES = { "waxed_", "potted_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" } +local CORAL = { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") } +local FALLBACK = hex("909090") + +local function mix(c: { number }, w: { number }, t: number): { number } + return { math.floor(c[1] + (w[1] - c[1]) * t + 0.5), math.floor(c[2] + (w[2] - c[2]) * t + 0.5), math.floor(c[3] + (w[3] - c[3]) * t + 0.5), c[4] } +end + +local resolve: (string, number) -> { number }? + +local function family(n: string): { number }? + for _, d in DYES do + local pre = d[1] .. "_" + if string.sub(n, 1, #pre) == pre then + local rest = string.sub(n, #pre + 1) + local i = d[2] + if rest == "concrete" then + return CONCRETE[i] + elseif rest == "concrete_powder" then + return mix(CONCRETE[i], { 255, 255, 255, 255 }, 0.2) + elseif rest == "terracotta" then + return TERRACOTTA[i] + elseif string.find(rest, "glass", 1, true) then + local c = table.clone(WOOL[i]) + c[4] = 0x80 + return c + end + return WOOL[i] + end + end + local stripped = string.match(n, "^stripped_(.*)$") + for _, w in WOODS do + local pre = w[1] .. "_" + local m = stripped or n + if string.sub(m, 1, #pre) == pre then + local rest = string.sub(m, #pre + 1) + local i = w[2] + if stripped then + return PLANKS[i] + elseif rest == "log" or rest == "wood" or rest == "stem" or rest == "hyphae" then + return BARK[i] + elseif rest == "leaves" or rest == "sapling" or rest == "propagule" then + return LEAVES[i] + elseif rest == "block" and w[1] == "bamboo" then + return EXACT.bamboo_block + end + return PLANKS[i] + end + end + return nil +end + +local function keywords(n: string): { number }? + if string.find(n, "copper", 1, true) then + return if string.find(n, "oxidized", 1, true) then EXACT.oxidized_copper + elseif string.find(n, "weathered", 1, true) then EXACT.weathered_copper + elseif string.find(n, "exposed", 1, true) then EXACT.exposed_copper + else EXACT.copper_block + elseif string.find(n, "coral", 1, true) then + if string.find(n, "dead", 1, true) then + return hex("857e79") + end + for k, c in CORAL do + if string.find(n, k, 1, true) then + return c + end + end + elseif string.find(n, "_ore$") then + return if string.find(n, "deepslate", 1, true) then EXACT.deepslate + elseif string.find(n, "nether", 1, true) then EXACT.netherrack + else EXACT.stone + end + for _, k in { "deepslate", "blackstone", "sandstone", "prismarine", "purpur", "quartz", "glass", "ice", "stone", "brick", "nether", "end", "mushroom", "grass", "candle", "head", "skull", "rail", "sign", "tulip", "orchid" } do + if string.find(n, k, 1, true) then + local alias = ({ glass = "glass", ice = "ice", stone = "stone", brick = "bricks", nether = "nether_bricks", ["end"] = "end_stone", mushroom = "mushroom_stem", grass = "short_grass", candle = "white_wool", head = "polished_andesite", skull = "bone_block", rail = "rail", sign = "oak_planks", tulip = "red_tulip", orchid = "blue_orchid", deepslate = "deepslate", blackstone = "blackstone", sandstone = "sandstone", prismarine = "prismarine", purpur = "purpur_block", quartz = "quartz_block" } :: any)[k] + return EXACT[alias] + end + end + return nil +end + +resolve = function(n: string, depth: number): { number }? + if depth > 4 then + return nil + end + local c = EXACT[n] + if c then + return c + end + local renamed = Legacy.RENAMED[n] + if renamed then + return resolve(renamed, depth + 1) + end + for _, p in PREFIXES do + if string.sub(n, 1, #p) == p then + return resolve(string.sub(n, #p + 1), depth + 1) + end + end + c = family(n) + if c then + return c + end + for _, sfx in SUFFIXES do + if #n > #sfx and string.sub(n, -#sfx) == sfx then + local base = string.sub(n, 1, #n - #sfx) + for _, form in { base, base .. "s", base .. "_block", base .. "_planks" } do + local fc = EXACT[form] or family(form) + if fc then + return fc + end + end + return resolve(base, depth + 1) + end + end + return keywords(n) +end + +local cache: { [string]: { number } | false } = {} +-- color(state) -> { r, g, b, a } (0..255) | nil for air-like blocks: the default colour table, families, keywords +function Minecraft.color(s: string): { number }? + local hit = cache[s] + if hit ~= nil then + return hit or nil + end + local name, props = Minecraft.parseState(s) + local n = string.match(name, ":(.*)$") or name + local res: { number }? = nil + if not AIR[n] then + -- pre-1.13 names whose data value picks the variant + local variants = Legacy.VARIANTS[n] or (if n == "double_wooden_slab" then Legacy.VARIANTS.planks else nil) + if variants then + local data = 0 + for _, kv in props do + if kv[1] == "data" then + data = tonumber(kv[2]) or 0 + end + end + local v = variants[data % (Legacy.MASK[n] or 16) + 1] or variants[1] + res = resolve(v, 0) + end + res = res or resolve(n, 0) or FALLBACK + end + cache[s] = res or false + return res +end + +-- ------------------------------------------------------------------------------------------------ legacy ids +local REVERSE: { [string]: { number } }? = nil +local function reverse(): { [string]: { number } } + if REVERSE then + return REVERSE + end + local r: { [string]: { number } } = {} + local byName: { [string]: number } = {} + for i, n in Legacy.NAMES do + if n ~= "-" then + byName[n] = i - 1 + end + end + for legacy, modern in Legacy.RENAMED do + r[modern] = { byName[legacy], 0 } + end + for legacy, variants in Legacy.VARIANTS do + for d, v in variants do + if r[v] == nil then + r[v] = { byName[legacy], d - 1 } + end + end + end + for n, id in byName do + if r[n] == nil then + r[n] = { id, 0 } + end + end + REVERSE = r + return r +end + +-- legacyState(id, data) -> the state string for a pre-1.13 block (variant names where the data value picks one, the +-- rest of the data value kept as [data=N] so legacyId gives it back exactly) +function Minecraft.legacyState(id: number, data: number): string + local n = Legacy.NAMES[id + 1] + if n == nil or n == "-" then + return "minecraft:legacy_" .. id .. (if data ~= 0 then "[data=" .. data .. "]" else "") + end + local variants = Legacy.VARIANTS[n] + if variants then + local idx = data % (Legacy.MASK[n] or 16) + local v = variants[idx + 1] + if v then + return "minecraft:" .. v .. (if data ~= idx then "[data=" .. data .. "]" else "") + end + end + return "minecraft:" .. (Legacy.RENAMED[n] or n) .. (if data ~= 0 then "[data=" .. data .. "]" else "") +end + +-- legacyId(state) -> id, data | nil: the inverse of legacyState (modern names that exist before 1.13 too; their +-- properties are not converted to data values) +function Minecraft.legacyId(s: string): (number?, number?) + local name, props = Minecraft.parseState(s) + local n = string.match(name, ":(.*)$") or name + local id: number?, data = nil, 0 + local lid = string.match(n, "^legacy_(%d+)$") + if lid then + id = tonumber(lid) + else + local e = reverse()[n] + if e then + id, data = e[1], e[2] + end + end + if id == nil then + return nil, nil + end + for _, kv in props do + if kv[1] == "data" then + data = (tonumber(kv[2]) or data) % 16 + end + end + return id, data +end + +-- ------------------------------------------------------------------------------------------------ voxels +-- voxels(sx, sy, sz, states, indices, opts?) -> Types.Voxels: indices (u16 LE per cell in Voxels order: x fastest, +-- then y, then z) into states; data / palette from the block colours (air -> 0; up to 255 colours, more merge into +-- the nearest one) +function Minecraft.voxels(sx: number, sy: number, sz: number, states: { string }, indices: buffer): Types.Voxels + local v = Types.Voxels.new(sx, sy, sz) + local lut = buffer.create(#states) + local slots: { [string]: number } = {} + local used = 0 + for i, s in states do + local c = Minecraft.color(s) + local slot = 0 + if c then + local key = string.format("%d,%d,%d,%d", c[1], c[2], c[3], c[4]) + slot = slots[key] + if not slot then + if used < 255 then + used += 1 + slot = used + v.palette[slot] = { c[1], c[2], c[3], c[4] } + else + local best, bd = 1, math.huge + for k = 1, 255 do + local p = v.palette[k] + local d = (p[1] - c[1]) ^ 2 + (p[2] - c[2]) ^ 2 + (p[3] - c[3]) ^ 2 + (p[4] - c[4]) ^ 2 + if d < bd then + best, bd = k, d + end + end + slot = best + end + slots[key] = slot + end + end + buffer.writeu8(lut, i - 1, slot) + end + local n = sx * sy * sz + local data, nstates = v.data, #states + for i = 0, n - 1 do + local s = buffer.readu16(indices, i * 2) + buffer.writeu8(data, i, if s < nstates then buffer.readu8(lut, s) else 0) + end + v.blocks = { palette = states, data = indices } + return v +end + +-- the blocks a colour grid is written with: full blocks of distinct colours (and stained glass for translucent ones) +local CANDIDATES: { { any } }? = nil +local function candidates(): { { any } } + if CANDIDATES then + return CANDIDATES + end + local out = {} + for _, d in Colors.DYES do + for _, kind in { "wool", "concrete", "terracotta" } do + local s = "minecraft:" .. d .. "_" .. kind + table.insert(out, { s, Minecraft.color(s) }) + end + end + for _, w in Colors.WOODS do + local s = "minecraft:" .. w .. "_planks" + table.insert(out, { s, Minecraft.color(s) }) + end + for _, n in { "stone", "cobblestone", "bricks", "sand", "red_sand", "dirt", "grass_block", "gravel", "deepslate", "sandstone", "quartz_block", "obsidian", "netherrack", "end_stone", "prismarine", "dark_prismarine", "snow_block", "gold_block", "iron_block", "diamond_block", "emerald_block", "lapis_block", "redstone_block", "coal_block", "glowstone", "sponge", "melon", "pumpkin", "hay_block", "bone_block", "clay", "packed_ice", "nether_bricks", "purpur_block", "andesite", "diorite", "granite", "calcite", "tuff", "blackstone", "mud", "moss_block", "amethyst_block", "copper_block", "oxidized_copper" } do + local s = "minecraft:" .. n + table.insert(out, { s, Minecraft.color(s) }) + end + CANDIDATES = out + return out +end + +-- nearestBlock(rgba) -> the block state whose default colour is nearest (translucent colours -> stained glass) +function Minecraft.nearestBlock(c: { number }): string + local a = c[4] or 255 + if a < 200 then + local best, bd = "minecraft:glass", math.huge + for i, d in Colors.DYES do + local w = WOOL[i] + local dist = (w[1] - c[1]) ^ 2 + (w[2] - c[2]) ^ 2 + (w[3] - c[3]) ^ 2 + if dist < bd then + best, bd = "minecraft:" .. d .. "_stained_glass", dist + end + end + return best + end + local best, bd = "minecraft:stone", math.huge + for _, cand in candidates() do + local k = cand[2] + local dist = (k[1] - c[1]) ^ 2 + (k[2] - c[2]) ^ 2 + (k[3] - c[3]) ^ 2 + if dist < bd then + best, bd = cand[1], dist + end + end + return best +end + +-- blocksOf(voxels) -> states, indices (u16 LE per cell): voxels.blocks when present (checked), else a block per +-- palette colour (nearestBlock; cell 0 -> "minecraft:air" at index 0) | nil, message +function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any) + local n = v.size[1] * v.size[2] * v.size[3] + local b = v.blocks + if b then + if type(b.palette) ~= "table" or type(b.data) ~= "buffer" or buffer.len(b.data) < n * 2 then + return nil, "voxels.blocks must hold a palette and a u16 per cell" + end + if #b.palette == 0 or #b.palette > 65536 then + return nil, "voxels.blocks.palette must have 1 .. 65536 states" + end + return b.palette, b.data + end + local states = { "minecraft:air" } + local slotOf: { [number]: number } = { [0] = 0 } + local byState: { [string]: number } = { ["minecraft:air"] = 0 } + local out = buffer.create(n * 2) + local data = v.data + for i = 0, n - 1 do + local p = buffer.readu8(data, i) + local s = slotOf[p] + if s == nil then + local col = v.palette[p] or { 128, 128, 128, 255 } + local st = Minecraft.nearestBlock(col) + s = byState[st] + if s == nil then + table.insert(states, st) + s = #states - 1 + byState[st] = s + end + slotOf[p] = s + end + buffer.writeu16(out, i * 2, s :: number) + end + return states, out +end + +return Minecraft diff --git a/src/Formats/model/schematic/Common.luau b/src/Formats/model/schematic/Common.luau new file mode 100644 index 0000000..e9f49c5 --- /dev/null +++ b/src/Formats/model/schematic/Common.luau @@ -0,0 +1,202 @@ +--!strict +-- model/schematic/Common: what the three schematic flavours share: the region record they read into and write from, +-- NBT field access with type checks, and block entities in one shape ({ pos = { x, y, z }, id, data }: Sponge v3's, +-- converted from / to MCEdit's and Litematica's flat { x, y, z, id, ... } and Sponge v2's { Pos, Id, ... }). +local Types = require("@formats/Types") +local Nbt = require("@formats/codecs/text/Nbt") + +local Common = {} + +-- a block region: indices are u16 per cell in Types.Voxels order (x fastest, then y, then z) into states +export type Region = { + name: string?, + size: { number }, -- x, y, z cells + position: { number }, -- the minimum corner relative to the schematic origin + states: { string }, + indices: buffer, + blockEntities: { any }, + entities: { any }, +} + +-- int(v) -> the integer value of an NBT number (byte / short / int / long tag or plain number) | nil +function Common.int(v: any): number? + local n = Nbt.number(v) + if n == nil or n ~= n or n % 1 ~= 0 then + return nil + end + return n +end + +-- dims(a, b, c, max) -> sx, sy, sz | nil, message: positive sizes whose product stays under max cells +function Common.dims(a: any, b: any, c: any, max: number): (number?, any, number?) + local x, y, z = Common.int(a), Common.int(b), Common.int(c) + if not x or not y or not z then + return nil, "missing or non-integer size", nil + end + if x < 0 or y < 0 or z < 0 then + return nil, "negative size", nil + end + if x * y * z > max then + return nil, "limit: " .. x .. " x " .. y .. " x " .. z .. " cells is over maxCells", nil + end + return x, y, z +end + +-- ints(v) -> the numbers of an intArray tag or a list of numbers | nil +function Common.ints(v: any): { number }? + if Nbt.isTag(v) and v.type == "intArray" then + return v.value + elseif type(v) == "table" and not Nbt.isTag(v) and v[1] ~= nil then + local out = {} + for i, x in v do + out[i] = Nbt.number(x) or 0 + end + return out + end + return nil +end + +local function rest(c: any, skip: { [string]: boolean }): { [string]: any } + local out, keys = {}, {} + for _, k in Types.keys(c) do + if not skip[k] then + out[k] = c[k] + table.insert(keys, k) + end + end + return Types.object(out, keys) +end + +local FLAT_SKIP = { x = true, y = true, z = true, id = true } +local POS_SKIP = { Pos = true, Id = true } + +-- blockEntity(c, style) -> the common shape of one record: style "flat" (MCEdit, Litematica), "pos" (Sponge v1 / v2), +-- "data" (Sponge v3) +function Common.blockEntity(c: any, style: string): any + if type(c) ~= "table" or Nbt.isTag(c) then + return nil + end + if style == "flat" then + return { pos = { Common.int(c.x) or 0, Common.int(c.y) or 0, Common.int(c.z) or 0 }, id = if type(c.id) == "string" then c.id else nil, data = rest(c, FLAT_SKIP) } + end + local p = Common.ints(c.Pos) or { 0, 0, 0 } + local data = if style == "data" then (if type(c.Data) == "table" then c.Data else Types.object()) else rest(c, POS_SKIP) + return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = if type(c.Id) == "string" then c.Id else nil, data = data } +end + +-- flatBlockEntity(be, style) -> the record in a flavour's shape (the inverse of blockEntity) +function Common.flatBlockEntity(be: any, style: string): any + local o = Types.object() + local data = if type(be.data) == "table" then be.data else Types.object() + if style == "flat" then + Types.set(o, "x", be.pos[1]) + Types.set(o, "y", be.pos[2]) + Types.set(o, "z", be.pos[3]) + if be.id then + Types.set(o, "id", be.id) + end + for _, k in Types.keys(data) do + if not FLAT_SKIP[k] then + Types.set(o, k, data[k]) + end + end + return o + end + Types.set(o, "Pos", Nbt.intArray({ be.pos[1], be.pos[2], be.pos[3] })) + if be.id then + Types.set(o, "Id", be.id) + end + if style == "data" then + Types.set(o, "Data", data) + else + for _, k in Types.keys(data) do + if not POS_SKIP[k] then + Types.set(o, k, data[k]) + end + end + end + return o +end + +-- list(v) -> v when it is an NBT list (array), else an empty list +function Common.list(v: any): { any } + if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then + return v + end + return {} +end + +-- compound({ { key, value } }) -> a Types.object with these keys in this order (nil values skipped) +function Common.compound(fields: { { any } }): { [string]: any } + local o, keys = {}, {} + for _, kv in fields do + if kv[2] ~= nil then + o[kv[1]] = kv[2] + table.insert(keys, kv[1]) + end + end + return Types.object(o, keys) +end + +-- merge(base, fields, drop?) -> a compound of fields ({ { key, value } }, nil values left out) laid out in base's key +-- order (a decoded source compound: its other keys are kept, except those in drop), new keys after +function Common.merge(base: any, fields: { { any } }, drop: { [string]: boolean }?): { [string]: any } + if type(base) ~= "table" or not Types.isObject(base) then + return Common.compound(fields) + end + local mine: { [string]: any } = {} + local present: { [string]: boolean } = {} + for _, kv in fields do + present[kv[1]] = true + mine[kv[1]] = kv[2] + end + local out = {} + for _, k in Types.keys(base) do + if present[k] then + if mine[k] ~= nil then + table.insert(out, { k, mine[k] }) + end + elseif not (drop and drop[k]) then + table.insert(out, { k, base[k] }) + end + end + local seen: { [string]: boolean } = {} + for _, kv in out do + seen[kv[1]] = true + end + for _, kv in fields do + if not seen[kv[1]] and kv[2] ~= nil then + table.insert(out, kv) + end + end + return Common.compound(out) +end + +-- dedupe(states, indices, n) -> states, indices with every state once (indices remapped when needed) +function Common.dedupe(states: { string }, indices: buffer, n: number): ({ string }, buffer) + local first: { [string]: number } = {} + local remap: { number } = {} + local out: { string } = {} + local dup = false + for i, s in states do + local at = first[s] + if at == nil then + table.insert(out, s) + at = #out - 1 + first[s] = at + else + dup = true + end + remap[i] = at + end + if not dup then + return states, indices + end + local res = buffer.create(n * 2) + for i = 0, n - 1 do + buffer.writeu16(res, i * 2, remap[buffer.readu16(indices, i * 2) + 1] or 0) + end + return out, res +end + +return Common diff --git a/src/Formats/model/schematic/Litematic.luau b/src/Formats/model/schematic/Litematic.luau new file mode 100644 index 0000000..f4ea4c5 --- /dev/null +++ b/src/Formats/model/schematic/Litematic.luau @@ -0,0 +1,215 @@ +--!strict +-- model/schematic/Litematic: Litematica's .litematic, from the mod's sources (LitematicaSchematic, +-- LitematicaBitArray) as documented by the litemapy project: Metadata (name, author, description, enclosing size, +-- counts, times, preview), several named Regions with a Position and a Size that may be negative, a block-state +-- palette (index 0 = air) and BlockStates packed spanning long boundaries (at least 2 bits), TileEntities (relative +-- to the region's minimum corner), Entities and pending ticks (kept as they are). +local Types = require("@formats/Types") +local Nbt = require("@formats/codecs/text/Nbt") +local Mc = require("@formats/codecs/model/Minecraft") +local Common = require("@formats/model/schematic/Common") + +local Litematic = {} + +local Packed = Mc.Packed + +local function xyz(c: any): { number }? + if type(c) ~= "table" then + return nil + end + local x, y, z = Common.int(c.x), Common.int(c.y), Common.int(c.z) + if not x or not y or not z then + return nil + end + return { x, y, z } +end + +local function vec(v: { number }): any + return Common.compound({ { "x", v[1] }, { "y", v[2] }, { "z", v[3] } }) +end + +-- read(root, maxCells) -> { Region }, extra | nil, message +function Litematic.read(root: any, maxCells: number): ({ Common.Region }?, any) + if not Types.isObject(root.Regions) then + return nil, "no Regions" + end + local out: { Common.Region } = {} + local total = 0 + local raw: { [string]: any } = {} + for _, name in Types.keys(root.Regions) do + local reg = root.Regions[name] + if type(reg) ~= "table" then + return nil, "region " .. name .. " is not a compound" + end + local pos, size = xyz(reg.Position), xyz(reg.Size) + if not pos or not size then + return nil, "region " .. name .. ": no Position / Size" + end + local ax, ay, az = math.abs(size[1]), math.abs(size[2]), math.abs(size[3]) + local sx, sy, sz = Common.dims(ax, ay, az, maxCells - total) + if not sx then + return nil, "region " .. name .. ": " .. tostring(sy) + end + total += ax * ay * az + local states: { string } = {} + for i, c in Common.list(reg.BlockStatePalette) do + local st = Mc.stateFromNbt(c) + if not st then + return nil, "region " .. name .. ": bad palette entry " .. i + end + states[i] = st + end + if #states == 0 then + states[1] = "minecraft:air" + end + local n = ax * ay * az + local yzx = buffer.create(n * 2) + local bs = reg.BlockStates + if n > 0 then + if not (Nbt.isTag(bs) and bs.type == "longArray") then + return nil, "region " .. name .. ": no BlockStates" + end + local bits = Packed.bitsFor(#states, 2) + local ok, e = Packed.unpack(bs.value, bits, n, true, yzx, #states) + if not ok then + return nil, "region " .. name .. ": " .. tostring(e) + end + end + local bes = {} + for _, c in Common.list(reg.TileEntities) do + local be = Common.blockEntity(c, "flat") + if be then + table.insert(bes, be) + end + end + table.insert(out, { + name = name, + size = { ax, ay, az }, + position = { + pos[1] + (if size[1] < 0 then size[1] + 1 else 0), + pos[2] + (if size[2] < 0 then size[2] + 1 else 0), + pos[3] + (if size[3] < 0 then size[3] + 1 else 0), + }, + states = states, + indices = Packed.fromYzx(yzx, ax, ay, az), + blockEntities = bes, + entities = Common.list(reg.Entities), + }) + raw[name] = reg + end + return out, { + version = Common.int(root.Version), + subVersion = Common.int(root.SubVersion), + dataVersion = Common.int(root.MinecraftDataVersion), + metadata = root.Metadata, + regions = raw, + } +end + +-- write(regions, version, dataVersion, base?, name?) -> the root compound | nil, message. base: the decoded root +-- (Metadata fields and each region's Position / Size signs and pending ticks are kept) +function Litematic.write(regions: { Common.Region }, version: number, dataVersion: number, base: any, title: string?): (any, string?) + local baseRegions = if type(base) == "table" and Types.isObject(base.Regions) then base.Regions else nil + local regs, order = {}, {} + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + local blocks, volume = 0, 0 + for i, r in regions do + local name = r.name or ("Region" .. (if i == 1 then "" else tostring(i))) + while regs[name] ~= nil do + name ..= "_" + end + local sx, sy, sz = r.size[1], r.size[2], r.size[3] + local n = sx * sy * sz + local states, indices = Common.dedupe(r.states, r.indices, n) + if states[1] ~= "minecraft:air" then + -- Litematica keeps air at index 0 + local at = table.find(states, "minecraft:air") + local shifted = buffer.create(n * 2) + local nst = table.clone(states) + if at then + nst[1], nst[at] = states[at], states[1] + else + table.insert(nst, 1, "minecraft:air") + end + for c = 0, n - 1 do + local v = buffer.readu16(indices, c * 2) + local w = if at then (if v == 0 then at - 1 elseif v == at - 1 then 0 else v) else v + 1 + buffer.writeu16(shifted, c * 2, w) + end + states, indices = nst, shifted + end + local palette = Nbt.list("compound") + for k, st in states do + palette[k] = Mc.stateToNbt(st) + end + local airLike: { [number]: boolean } = {} + for k, st in states do + airLike[k - 1] = Mc.isAir(st) + end + for c = 0, n - 1 do + if not airLike[buffer.readu16(indices, c * 2)] then + blocks += 1 + end + end + volume += n + local bits = Packed.bitsFor(#states, 2) + local longs = Packed.pack(Packed.toYzx(indices, sx, sy, sz), n, bits, true) + local tiles = Nbt.list("compound") + for _, be in r.blockEntities do + table.insert(tiles, Common.flatBlockEntity(be, "flat")) + end + local p = r.position + local pos, size = { p[1], p[2], p[3] }, { sx, sy, sz } + local b = if baseRegions then baseRegions[name] else nil + local bsize = if type(b) == "table" then xyz(b.Size) else nil + if bsize and math.abs(bsize[1]) == sx and math.abs(bsize[2]) == sy and math.abs(bsize[3]) == sz then + -- keep the source's corner and signs + for k = 1, 3 do + if bsize[k] < 0 then + size[k] = bsize[k] + pos[k] = p[k] - bsize[k] - 1 + end + end + end + for k = 1, 3 do + lo[k] = math.min(lo[k], p[k]) + hi[k] = math.max(hi[k], p[k] + r.size[k]) + end + regs[name] = Common.merge(b, { + { "BlockStatePalette", palette }, + { "BlockStates", Nbt.longArray(longs) }, + { "Entities", if #r.entities > 0 then r.entities else Nbt.list("compound") }, + { "PendingBlockTicks", if type(b) == "table" then b.PendingBlockTicks else Nbt.list("compound") }, + { "PendingFluidTicks", if type(b) == "table" then b.PendingFluidTicks else Nbt.list("compound") }, + { "Position", vec(pos) }, + { "Size", vec(size) }, + { "TileEntities", tiles }, + }) + table.insert(order, name) + end + if #order == 0 then + lo, hi = { 0, 0, 0 }, { 0, 0, 0 } + end + local bm = if type(base) == "table" and type(base.Metadata) == "table" then base.Metadata else nil + local metadata = Common.merge(bm, { + { "EnclosingSize", vec({ hi[1] - lo[1], hi[2] - lo[2], hi[3] - lo[3] }) }, + { "Author", if bm and bm.Author then bm.Author else "" }, + { "Description", if bm and bm.Description then bm.Description else "" }, + { "Name", title or (if bm and bm.Name then bm.Name else "Unnamed") }, + { "RegionCount", #order }, + { "TimeCreated", if bm and bm.TimeCreated then bm.TimeCreated else Nbt.long(0) }, + { "TimeModified", if bm and bm.TimeModified then bm.TimeModified else Nbt.long(0) }, + { "TotalBlocks", blocks }, + { "TotalVolume", volume }, + }) + local regions_ = Types.object(regs, order) + return Common.merge(base, { + { "MinecraftDataVersion", dataVersion }, + { "Version", version }, + { "SubVersion", if type(base) == "table" and base.SubVersion ~= nil then base.SubVersion elseif version >= 6 then 1 else nil }, + { "Metadata", metadata }, + { "Regions", regions_ }, + }), nil +end + +return Litematic diff --git a/src/Formats/model/schematic/Mcedit.luau b/src/Formats/model/schematic/Mcedit.luau new file mode 100644 index 0000000..d320037 --- /dev/null +++ b/src/Formats/model/schematic/Mcedit.luau @@ -0,0 +1,213 @@ +--!strict +-- model/schematic/Mcedit: the MCEdit / WorldEdit .schematic layout (Minecraft before 1.13), from the Minecraft wiki +-- "Schematic file format" page: Width / Height / Length, Blocks + Data (+ WorldEdit's AddBlocks high nibbles, high +-- nibble first), Materials = "Alpha", TileEntities, Entities, WEOffset*, and the SchematicaMapping / BlockIDs name +-- tables of Schematica and MCEdit-Unified. Block ids become state strings through codecs/model/Minecraft +-- (legacyState: wool 14 -> minecraft:red_wool) and back (legacyId; blocks unknown before 1.13 become the legacy block +-- nearest in colour). +local Types = require("@formats/Types") +local Nbt = require("@formats/codecs/text/Nbt") +local Mc = require("@formats/codecs/model/Minecraft") +local Common = require("@formats/model/schematic/Common") + +local Mcedit = {} + +local Packed = Mc.Packed + +-- read(root, maxCells) -> { Region }, extra | nil, message +function Mcedit.read(root: any, maxCells: number): ({ Common.Region }?, any) + local blocks = root.Blocks + if type(blocks) ~= "buffer" then + return nil, "no Blocks byte array" + end + local function u16(v: any): any + local n = Common.int(v) + return if n and n < 0 then n + 65536 else n + end + local sx, sy, sz = Common.dims(u16(root.Width), u16(root.Height), u16(root.Length), maxCells) + if not sx then + return nil, sy + end + local n = sx * sy :: number * (sz :: number) + if buffer.len(blocks) < n then + return nil, "truncated: Blocks has " .. buffer.len(blocks) .. " bytes for " .. n .. " cells" + end + local data = if type(root.Data) == "buffer" and buffer.len(root.Data) >= n then root.Data else nil + local add = if type(root.AddBlocks) == "buffer" and buffer.len(root.AddBlocks) >= (n + 1) // 2 then root.AddBlocks else nil + -- id -> name tables of Schematica (name -> id) and MCEdit-Unified (id text -> name) + local names: { [number]: string } = {} + if Types.isObject(root.SchematicaMapping) then + for _, k in Types.keys(root.SchematicaMapping) do + local id = Common.int(root.SchematicaMapping[k]) + if id then + names[id] = k + end + end + end + if Types.isObject(root.BlockIDs) then + for _, k in Types.keys(root.BlockIDs) do + local id = tonumber(k) + if id and type(root.BlockIDs[k]) == "string" then + names[id] = root.BlockIDs[k] + end + end + end + local function state(id: number, d: number): string + local name = names[id] + if name then + local base = string.match(name, "^minecraft:(.*)$") or (if string.find(name, ":", 1, true) then nil else name) + if base then + local std = table.find(Mc.Legacy.NAMES, base) + if std then + return Mc.legacyState(std - 1, d) + end + end + return Mc.stateString(if string.find(name, ":", 1, true) then name else "minecraft:" .. name, if d ~= 0 then { { "data", tostring(d) } } else nil) + end + return Mc.legacyState(id, d) + end + local slots: { [number]: number } = {} + local states: { string } = {} + local yzx = buffer.create(n * 2) + for i = 0, n - 1 do + local id = buffer.readu8(blocks, i) + if add then + id += Packed.nibble(add, 0, i, true) * 256 + end + local d = if data then buffer.readu8(data, i) % 16 else 0 + local key = id * 16 + d + local s = slots[key] + if not s then + table.insert(states, state(id, d)) + s = #states - 1 + slots[key] = s + end + buffer.writeu16(yzx, i * 2, s :: number) + end + local bes = {} + for _, c in Common.list(root.TileEntities) do + local be = Common.blockEntity(c, "flat") + if be then + table.insert(bes, be) + end + end + return { + { + name = nil, + size = { sx, sy, sz }, + position = { Common.int(root.WEOffsetX) or 0, Common.int(root.WEOffsetY) or 0, Common.int(root.WEOffsetZ) or 0 }, + states = states, + indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number), + blockEntities = bes, + entities = Common.list(root.Entities), + }, + }, + { materials = root.Materials } +end + +-- the legacy blocks a colour can become (full blocks of distinct colours) +local CANDIDATES: { { any } }? = nil +local function candidates(): { { any } } + if CANDIDATES then + return CANDIDATES + end + local out = {} + local function add(id: number, d: number) + local c = Mc.color(Mc.legacyState(id, d)) + if c then + table.insert(out, { id, d, c }) + end + end + for d = 0, 15 do + add(35, d) -- wool + add(159, d) -- stained clay + add(251, d) -- concrete + end + for d = 0, 5 do + add(5, d) -- planks + end + for _, id in { 1, 2, 3, 4, 7, 12, 13, 24, 41, 42, 45, 48, 49, 57, 80, 82, 87, 88, 89, 98, 121, 133, 152, 155, 168, 172, 173, 174, 179, 201, 216 } do + add(id, 0) + end + CANDIDATES = out + return out +end + +local function nearest(state: string): (number, number) + local c = Mc.color(state) + if not c then + return 0, 0 + end + if c[4] < 200 then + return 20, 0 -- glass + end + local bid, bd, best = 1, 0, math.huge + for _, k in candidates() do + local kc = k[3] + local dist = (kc[1] - c[1]) ^ 2 + (kc[2] - c[2]) ^ 2 + (kc[3] - c[3]) ^ 2 + if dist < best then + bid, bd, best = k[1], k[2], dist + end + end + return bid, bd +end + +-- write(region, base?) -> the root compound (named "Schematic") | nil, message. base: a decoded root whose other +-- fields are kept +function Mcedit.write(r: Common.Region, base: any): (any, string?) + local sx, sy, sz = r.size[1], r.size[2], r.size[3] + if sx > 65535 or sy > 65535 or sz > 65535 then + return nil, "a .schematic is at most 65535 cells on each axis" + end + local n = sx * sy * sz + local ids, datas = table.create(#r.states), table.create(#r.states) + local high = false + for i, s in r.states do + local id, d = Mc.legacyId(s) + if id == nil then + id, d = nearest(s) + end + ids[i], datas[i] = id, d + if (id :: number) > 255 then + high = true + end + end + local yzx = Packed.toYzx(r.indices, sx, sy, sz) + local blocks, data = buffer.create(n), buffer.create(n) + local add = if high then buffer.create((n + 1) // 2) else nil + for i = 0, n - 1 do + local s = buffer.readu16(yzx, i * 2) + 1 + local id = ids[s] or 0 + buffer.writeu8(blocks, i, id % 256) + buffer.writeu8(data, i, datas[s] or 0) + if add then + Packed.setNibble(add, 0, i, id // 256, true) + end + end + local tiles = Nbt.list("compound") + for _, be in r.blockEntities do + table.insert(tiles, Common.flatBlockEntity(be, "flat")) + end + local ents = if #r.entities > 0 then r.entities else Nbt.list("compound") + local fields = { + { "Width", Nbt.short(sx) }, + { "Height", Nbt.short(sy) }, + { "Length", Nbt.short(sz) }, + { "Materials", "Alpha" }, + { "Blocks", blocks }, + { "Data", data }, + { "AddBlocks", add }, + { "Entities", ents }, + { "TileEntities", tiles }, + } + local p = r.position + if p[1] ~= 0 or p[2] ~= 0 or p[3] ~= 0 or (type(base) == "table" and base.WEOffsetX ~= nil) then + table.insert(fields, { "WEOffsetX", p[1] }) + table.insert(fields, { "WEOffsetY", p[2] }) + table.insert(fields, { "WEOffsetZ", p[3] }) + end + local root = Common.merge(base, fields, { SchematicaMapping = true, BlockIDs = true, Add = true }) + return root, nil +end + +return Mcedit diff --git a/src/Formats/model/schematic/Sponge.luau b/src/Formats/model/schematic/Sponge.luau new file mode 100644 index 0000000..47f344f --- /dev/null +++ b/src/Formats/model/schematic/Sponge.luau @@ -0,0 +1,131 @@ +--!strict +-- model/schematic/Sponge: the Sponge schematic format (.schem: WorldEdit 7+, FAWE, Amulet), from the +-- SpongePowered/Schematic-Specification documents for versions 1, 2 and 3: Width / Height / Length, Offset, the +-- block-state Palette with varint BlockData (v1 / v2) or the Blocks container (v3), block entities (TileEntities / +-- BlockEntities, v3 with Data), Entities, Metadata, DataVersion; biomes are kept as they are. +local Types = require("@formats/Types") +local Nbt = require("@formats/codecs/text/Nbt") +local Mc = require("@formats/codecs/model/Minecraft") +local Common = require("@formats/model/schematic/Common") + +local Sponge = {} + +local Packed = Mc.Packed + +-- read(s, maxCells) -> { Region }, extra | nil, message. s: the Schematic compound (v3: the root's Schematic child) +function Sponge.read(s: any, maxCells: number): ({ Common.Region }?, any) + local version = Common.int(s.Version) or 1 + local function u16(v: any): any + local n = Common.int(v) + return if n and n < 0 then n + 65536 else n + end + local sx, sy, sz = Common.dims(u16(s.Width), u16(s.Height), u16(s.Length), maxCells) + if not sx then + return nil, sy + end + local container = if version >= 3 then s.Blocks else s + if version >= 3 and type(container) ~= "table" then + return nil, "no Blocks container" + end + local palette = if version >= 3 then container.Palette else s.Palette + local data = if version >= 3 then container.Data else s.BlockData + if not Types.isObject(palette) then + return nil, "no block palette" + end + if type(data) ~= "buffer" then + return nil, "no block data" + end + local states: { string } = {} + local max = -1 + for _, k in Types.keys(palette) do + local i = Common.int(palette[k]) + if i == nil or i < 0 or i > 65535 then + return nil, "bad palette index for " .. k + end + states[i + 1] = k + if i > max then + max = i + end + end + for i = 1, max + 1 do + if states[i] == nil then + states[i] = "minecraft:air" + end + end + local n = sx * sy :: number * (sz :: number) + local yzx = buffer.create(n * 2) + local ok, e = Packed.varints(data, 0, buffer.len(data), n, yzx, max + 1) + if not ok then + return nil, e + end + local bes = {} + local raw = if version >= 3 then container.BlockEntities elseif version == 2 then s.BlockEntities else s.TileEntities + for _, c in Common.list(raw) do + local be = Common.blockEntity(c, if version >= 3 then "data" else "pos") + if be then + table.insert(bes, be) + end + end + local off = Common.ints(s.Offset) or { 0, 0, 0 } + return { + { + name = nil, + size = { sx, sy, sz }, + position = { off[1] or 0, off[2] or 0, off[3] or 0 }, + states = states, + indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number), + blockEntities = bes, + entities = Common.list(s.Entities), + }, + }, + { version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata } +end + +-- write(region, version, dataVersion, base?) -> the Schematic compound (v3: the caller wraps it in the root) | nil, +-- message. base: the decoded Schematic compound whose other fields (Metadata, Biomes, ...) are kept +function Sponge.write(r: Common.Region, version: number, dataVersion: number, base: any): (any, string?) + local sx, sy, sz = r.size[1], r.size[2], r.size[3] + if sx > 65535 or sy > 65535 or sz > 65535 then + return nil, "a Sponge schematic is at most 65535 cells on each axis" + end + local n = sx * sy * sz + local states, indices = Common.dedupe(r.states, r.indices, n) + local palette, keys = {}, {} + for i, st in states do + palette[st] = i - 1 + keys[i] = st + end + local pal = Types.object(palette, keys) + local data = Packed.toVarints(Packed.toYzx(indices, sx, sy, sz), n) + local bes = Nbt.list("compound") + for _, be in r.blockEntities do + table.insert(bes, Common.flatBlockEntity(be, if version >= 3 then "data" else "pos")) + end + local ents = if #r.entities > 0 then r.entities else nil + local off = Nbt.intArray({ r.position[1], r.position[2], r.position[3] }) + local fields: { { any } } = { + { "Version", version }, + { "DataVersion", if version >= 2 then dataVersion else nil }, + { "Width", Nbt.short(sx) }, + { "Height", Nbt.short(sy) }, + { "Length", Nbt.short(sz) }, + { "Offset", off }, + } + if version >= 3 then + local blocksBase = if type(base) == "table" then base.Blocks else nil + table.insert(fields, { "Blocks", Common.merge(blocksBase, { { "Palette", pal }, { "Data", data }, { "BlockEntities", bes } }) }) + table.insert(fields, { "Entities", ents }) + else + table.insert(fields, { "PaletteMax", #states }) + table.insert(fields, { "Palette", pal }) + table.insert(fields, { "BlockData", data }) + table.insert(fields, { if version == 2 then "BlockEntities" else "TileEntities", bes }) + table.insert(fields, { "Entities", if version == 2 then ents else nil }) + end + -- the other version's block fields never carry over + local drop = if version >= 3 then { PaletteMax = true, Palette = true, BlockData = true, BlockEntities = true, TileEntities = true } + else { Blocks = true, Biomes = true, TileEntities = version ~= 1, BlockEntities = version == 1 } + return Common.merge(base, fields, drop :: any), nil +end + +return Sponge diff --git a/src/Formats/model/schematic/init.luau b/src/Formats/model/schematic/init.luau new file mode 100644 index 0000000..4d0db36 --- /dev/null +++ b/src/Formats/model/schematic/init.luau @@ -0,0 +1,309 @@ +--!strict +-- model/schematic: Minecraft schematics: MCEdit / WorldEdit .schematic (before 1.13), Sponge .schem (versions 1, 2, 3: +-- WorldEdit 7+) and Litematica .litematic, read and write. New code over codecs/text/Nbt (gzip NBT) and +-- codecs/model/Minecraft (block states, colours, legacy ids, packed arrays); the layouts: model/schematic/Mcedit, +-- Sponge, Litematic. +-- decode -> a Scene (meta.up = "y", one unit = one block): scene.voxels holds one Types.Voxels per region (a .litematic +-- has several), each with voxels.blocks (the exact block states, u16 per cell, plus block entities and entities as +-- NBT) and data / palette coloured from the default block colour table; a node per region places it (translation = +-- the region's minimum corner: Sponge Offset, WorldEdit WEOffset, Litematica Position). meta.source keeps the +-- variant, version, DataVersion, Metadata and the whole root NBT (source.nbt). +-- encode <- a Scene with voxels or one Types.Voxels: opts.variant (or the file name's extension, or the source's) +-- "schem" (default, version 3) / "schematic" / "litematic". Grids without blocks (a .vox) get, per palette colour, +-- the block nearest in colour. Several regions are merged into one grid for .schem / .schematic. Fields of the +-- source that are not blocks (Metadata, biomes, pending ticks, ...) are written back when the variant is the same. +-- Not supported: converting block properties to pre-1.13 data values (legacy writes keep the data a state came with +-- or 0), Sponge biome conversion between versions, rotated nodes (only translations place a grid). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Nbt = require("@formats/codecs/text/Nbt") +local Mc = require("@formats/codecs/model/Minecraft") +local Common = require("@formats/model/schematic/Common") +local Mcedit = require("@formats/model/schematic/Mcedit") +local Sponge = require("@formats/model/schematic/Sponge") +local Litematic = require("@formats/model/schematic/Litematic") + +-- ------------------------------------------------------------------------------------------------ contract +local Schematic = { + name = "schematic", + category = "model", + extensions = { "schem", "schematic", "litematic" }, + mime = { "application/x-minecraft-schematic" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Nbt", "codecs/model/Minecraft" }, + caps = { decode = true, encode = true, voxels = true, blocks = true, variants = { "schem", "schematic", "litematic" } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxCells: number?, -- refuse schematics with more cells in total (default 2^26) + maxBytes: number?, -- refuse NBT that inflates past this (default 2^28) +} +export type EncodeOptions = { + variant: ("schem" | "schematic" | "litematic")?, -- default: the extension of opts.name, the source's, else "schem" + version: number?, -- Sponge 1 / 2 / 3 (default 3, or the source's), Litematica version (default 6, or the source's) + dataVersion: number?, -- Minecraft's DataVersion (default the source's, else 3953 = 1.21) + name: string?, -- the file name (its extension picks the variant); for .litematic also the default Metadata.Name + title: string?, -- .litematic Metadata.Name + compression: ("gzip" | "zlib" | "none")?, -- default gzip, as every tool writes them + level: number?, -- deflate level +} + +-- ------------------------------------------------------------------------------------------------ constants +local DEFAULT_DATA_VERSION = 3953 +local LITEMATIC_HINTS = { "Regions", "EnclosingSize", "RegionCount", "TotalVolume", "MinecraftDataVersion" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Schematic.sniff(r: Bytes.Reader): number + local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p or p.rootType ~= "compound" or p.endian ~= "big" then + return 0 + end + if p.name == "Schematic" or (p.firstName == "Schematic" and p.firstType == "compound") then + return 1 + end + local head = buffer.tostring(p.head) + for _, h in LITEMATIC_HINTS do + if string.find(head, string.char(0, #h) .. h, 1, true) then + return 1 + end + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- variantOf(root, name) -> "schem" | "schematic" | "litematic", the compound holding the Sponge fields | nil +local function variantOf(root: any): (string?, any) + if type(root) ~= "table" or not Types.isObject(root) then + return nil, nil + end + if Types.isObject(root.Regions) then + return "litematic", root + end + if Types.isObject(root.Schematic) and (Common.int(root.Schematic.Version) or 0) >= 3 then + return "schem", root.Schematic + end + if root.Version ~= nil and (root.Palette ~= nil or root.BlockData ~= nil) then + return "schem", root + end + if type(root.Blocks) == "buffer" then + return "schematic", root + end + return nil, nil +end + +function Schematic.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: DecodeOptions = opts or {} + local root, info = Nbt.decode(r.buf, { maxBytes = o.maxBytes, endian = "big" }, r.base, r.limit - r.base) + if root == nil then + return nil, info + end + local variant, s = variantOf(root) + if not variant then + return nil, Err.new(Err.CORRUPT, "not a schematic (no Regions, Schematic / Palette or Blocks)") + end + local maxCells = o.maxCells or 2 ^ 26 + local regions, extra + if variant == "litematic" then + regions, extra = Litematic.read(s, maxCells) + elseif variant == "schem" then + regions, extra = Sponge.read(s, maxCells) + else + regions, extra = Mcedit.read(s, maxCells) + end + if not regions then + return nil, Err.from(extra) + end + local scene = Types.Scene.new() + scene.voxels = {} + for i, reg in regions do + local v = Mc.voxels(reg.size[1], reg.size[2], reg.size[3], reg.states, reg.indices) + v.name = reg.name + local b = v.blocks :: Types.VoxelBlocks + b.blockEntities = reg.blockEntities + b.entities = reg.entities + table.insert(scene.voxels :: { Types.Voxels }, v) + table.insert(scene.nodes, { name = reg.name, children = {}, voxels = i, translation = { reg.position[1], reg.position[2], reg.position[3] } }) + table.insert(scene.roots, #scene.nodes) + end + scene.meta.up = "y" + scene.meta.unit = 1 + local src: { [string]: any } = { format = "schematic", variant = variant, nbt = root, rootName = info.name, compression = info.compression } + for k, v in extra do + src[k] = v + end + scene.meta.source = src :: any + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function regionsOf(value: any): ({ Common.Region }?, string?) + local out: { Common.Region } = {} + local function add(v: Types.Voxels, pos: { number }, name: string?): string? + if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then + return "expected Types.Voxels grids" + end + local states, indices = Mc.blocksOf(v) + if not states then + return indices + end + local b = v.blocks + table.insert(out, { + name = name or v.name, + size = { v.size[1], v.size[2], v.size[3] }, + position = { math.floor(pos[1] + 0.5), math.floor(pos[2] + 0.5), math.floor(pos[3] + 0.5) }, + states = states, + indices = indices, + blockEntities = if b and b.blockEntities then b.blockEntities else {}, + entities = if b and b.entities then b.entities else {}, + }) + return nil + end + if type(value) == "table" and value.kind == "voxels" then + local e = add(value, { 0, 0, 0 }, nil) + return if e then nil else out, e + end + if type(value) ~= "table" or value.kind ~= "scene" or type(value.voxels) ~= "table" or #value.voxels == 0 then + return nil, "expected a Scene with voxels or a Types.Voxels" + end + local placed = false + local function walk(i: number, base: { number }, depth: number): string? + local node = value.nodes[i] + if type(node) ~= "table" or depth > 64 then + return nil + end + local t = node.translation or { 0, 0, 0 } + local p = { base[1] + (t[1] or 0), base[2] + (t[2] or 0), base[3] + (t[3] or 0) } + if node.voxels and value.voxels[node.voxels] then + placed = true + local e = add(value.voxels[node.voxels], p, node.name) + if e then + return e + end + end + for _, c in node.children or {} do + local e = walk(c, p, depth + 1) + if e then + return e + end + end + return nil + end + for _, root in value.roots or {} do + local e = walk(root, { 0, 0, 0 }, 0) + if e then + return nil, e + end + end + if not placed then + for _, v in value.voxels do + local e = add(v, { 0, 0, 0 }, nil) + if e then + return nil, e + end + end + end + return out, nil +end + +-- merge(regions) -> one region covering them all (air where none is) +local function merge(regions: { Common.Region }): Common.Region + if #regions == 1 then + return regions[1] + end + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for _, r in regions do + for k = 1, 3 do + lo[k] = math.min(lo[k], r.position[k]) + hi[k] = math.max(hi[k], r.position[k] + r.size[k]) + end + end + local sx, sy, sz = hi[1] - lo[1], hi[2] - lo[2], hi[3] - lo[3] + local states = { "minecraft:air" } + local out = buffer.create(sx * sy * sz * 2) + local bes, ents = {}, {} + for _, r in regions do + local base = #states + for _, st in r.states do + table.insert(states, st) + end + local rx, ry, rz = r.size[1], r.size[2], r.size[3] + local ox, oy, oz = r.position[1] - lo[1], r.position[2] - lo[2], r.position[3] - lo[3] + for z = 0, rz - 1 do + for y = 0, ry - 1 do + local s = (rx * (y + ry * z)) * 2 + local d = (ox + sx * ((oy + y) + sy * (oz + z))) * 2 + for _ = 0, rx - 1 do + buffer.writeu16(out, d, buffer.readu16(r.indices, s) + base) + s += 2 + d += 2 + end + end + end + for _, be in r.blockEntities do + table.insert(bes, { pos = { be.pos[1] + ox, be.pos[2] + oy, be.pos[3] + oz }, id = be.id, data = be.data }) + end + for _, e in r.entities do + table.insert(ents, e) + end + end + local st, idx = Common.dedupe(states, out, sx * sy * sz) + return { name = regions[1].name, size = { sx, sy, sz }, position = lo, states = st, indices = idx, blockEntities = bes, entities = ents } +end + +function Schematic.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local regions, rerr = regionsOf(value) + if not regions then + return nil, Err.new(Err.ARG, tostring(rerr)) + end + local src = if type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" and value.meta.source.format == "schematic" then value.meta.source else nil + local ext = if o.name then string.lower(string.match(o.name, "%.([%w]+)$") or "") else nil + local key = o.format and string.lower(o.format) + local variant = o.variant + or (if ext == "schem" or ext == "schematic" or ext == "litematic" then ext else nil) + or (if key == "schem" or key == "litematic" then key else nil) + or (src and src.variant) + or "schem" + if variant ~= "schem" and variant ~= "schematic" and variant ~= "litematic" then + return nil, Err.new(Err.ARG, "unknown variant " .. tostring(variant)) + end + local same = src ~= nil and src.variant == variant + local base = if same then (src :: any).nbt else nil + local dataVersion = o.dataVersion or (src and src.dataVersion) or DEFAULT_DATA_VERSION + local root, rootName, e + if variant == "litematic" then + local version = o.version or (if same then (src :: any).version else nil) or 6 + local title = o.title or (if o.name then string.match(o.name, "([^/\\]-)%.[%w]+$") else nil) + root, e = Litematic.write(regions, version, dataVersion, base, title) + rootName = "" + elseif variant == "schem" then + local version = o.version or (if same then (src :: any).version else nil) or 3 + if version ~= 1 and version ~= 2 and version ~= 3 then + return nil, Err.new(Err.ARG, "Sponge schematic version must be 1, 2 or 3") + end + local sameVersion = same and (src :: any).version == version + local inner = if sameVersion and base then (if version >= 3 then base.Schematic else base) else nil + local sch + sch, e = Sponge.write(merge(regions), version, dataVersion, inner) + if sch and version >= 3 then + root, rootName = Common.merge(if sameVersion then base else nil, { { "Schematic", sch } }), "" + else + root, rootName = sch, "Schematic" + end + else + root, e = Mcedit.write(merge(regions), base) + rootName = "Schematic" + end + if not root then + return nil, Err.new(Err.ARG, tostring(e)) + end + if same and (src :: any).rootName ~= nil then + rootName = (src :: any).rootName + end + return Nbt.encode(root, { name = rootName, endian = "big", compression = o.compression or "gzip", level = o.level }) +end + +return Schematic diff --git a/tools/fixtures/schematic.py b/tools/fixtures/schematic.py new file mode 100644 index 0000000..7996ad6 --- /dev/null +++ b/tools/fixtures/schematic.py @@ -0,0 +1,243 @@ +# model/schematic fixtures: schematics written by reference code through nix, with every cell's block state, and our +# encoder's output read back by the same reference code. +# .litematic: Python's litemapy (several regions, a negative size, a 40-state palette), a tile entity added with +# nbtlib; .schem v2: litemapy's Region.to_sponge_nbt (+ a block entity); .schem v1 / v3 and the legacy +# MCEdit .schematic (ids + data, WorldEdit AddBlocks, a SchematicaMapping table): nbtlib, by the specs. +# tests/gen/schematic.luau { cases = { { name, data, variant, version, regions = { { name, min = {x,y,z}, +# size = {x,y,z}, cells = "state\n..." (Voxels order: x, then y, then z) or legacy = +# { id*16+data per cell } } }, blockEntities = n, ... } } } +# tests/gen/schematic_ours.luau { [name] = { regions = { { name, min, size, cells } } } }: our encodings +# (tools/fixtures/_schematic_encode.luau) read back by litemapy / nbtlib +import importlib.util, os, pickle, subprocess, sys + +INPUTS = ["src/Formats/model/schematic", "src/Formats/codecs/model/Minecraft", "src/Formats/codecs/text/Nbt", "tools/fixtures/_schematic_encode.luau"] + +_spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_model_ref.py")) +R = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(R) + +COMMON = r''' +import nbtlib, pickle, random, struct, sys, io, gzip, os, tempfile +from nbtlib import Byte, Short, Int, Long, Float, Double, String, List, Compound, ByteArray, IntArray, LongArray +import numpy as np +from litemapy import Schematic, Region, BlockState +def state_of(bs): + # a litemapy BlockState as the state string, properties in the NBT order + t = bs.to_nbt() + props = t.get("Properties") + if props: + return str(t["Name"]) + "[" + ",".join("%s=%s" % (k, str(v)) for k, v in props.items()) + "]" + return str(t["Name"]) +def region_cells(reg): + xs, ys, zs = list(reg.range_x()), list(reg.range_y()), list(reg.range_z()) + out = [] + for z in zs: + for y in ys: + for x in xs: + out.append(state_of(reg[x, y, z])) + return out +def region_info(name, reg): + return {"name": name, "min": [reg.min_schem_x(), reg.min_schem_y(), reg.min_schem_z()], + "size": [abs(reg.width), abs(reg.height), abs(reg.length)], "cells": "\n".join(region_cells(reg))} +def sponge_cells(s): + # Sponge v1 / v2 / v3 compound -> min, size, cells + v = int(s.get("Version", 1)) + w, h, l = int(s["Width"]) & 0xffff, int(s["Height"]) & 0xffff, int(s["Length"]) & 0xffff + blocks = s["Blocks"] if v >= 3 else s + pal = blocks["Palette"] + data = bytes(np.asarray(blocks["Data"] if v >= 3 else blocks["BlockData"], dtype=np.int8).tobytes()) + names = {int(i): k for k, i in pal.items()} + idx, p = [], 0 + while len(idx) < w * h * l: + val, sh = 0, 0 + while True: + c = data[p]; p += 1 + val |= (c & 0x7f) << sh + sh += 7 + if c < 128: break + idx.append(val) + cells = [] + for z in range(l): + for y in range(h): + for x in range(w): + cells.append(names[idx[x + z * w + y * w * l]]) + off = list(s["Offset"]) if "Offset" in s else [0, 0, 0] + return {"name": "", "min": [int(o) for o in off], "size": [w, h, l], "cells": "\n".join(cells)} +''' + +BODY = COMMON + r''' +rng = random.Random(11) +STATES = ["minecraft:air", "minecraft:stone", "minecraft:red_wool", "minecraft:glass", "minecraft:oak_planks", + "minecraft:water[level=0]", "minecraft:grass_block[snowy=false]", "minecraft:oak_log[axis=y]", + "minecraft:oak_stairs[facing=east,half=bottom,shape=straight,waterlogged=false]", + "minecraft:chest[facing=north,type=single,waterlogged=false]", "minecraft:spruce_slab[type=top,waterlogged=false]", + "minecraft:lantern[hanging=true,waterlogged=false]"] +COLOURS = ["white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", + "purple", "blue", "brown", "green", "red", "black"] +BIG = ["minecraft:%s_%s" % (c, k) for c in COLOURS for k in ("wool", "concrete", "terracotta")] +def bs(s): + if "[" in s: + name, rest = s.split("[", 1) + props = dict(kv.split("=") for kv in rest[:-1].split(",")) + return BlockState(name, **props) + return BlockState(s) +def fill(reg, states): + for x in reg.range_x(): + for y in reg.range_y(): + for z in reg.range_z(): + reg[x, y, z] = bs(rng.choice(states)) +cases = [] +tmp = tempfile.mkdtemp() +# 1. litematic: three regions (one with negative sizes, one with a 40-state palette) +main = Region(0, 0, 0, 6, 5, 4); fill(main, STATES) +neg = Region(10, 2, -3, -4, 3, -5); fill(neg, STATES[:6]) +big = Region(-20, 0, 0, 7, 3, 5); fill(big, BIG) +sch = Schematic(name="Test", author="formats-luau", description="fixture", regions={"main": main, "neg": neg, "big": big}) +path = os.path.join(tmp, "t.litematic") +sch.save(path) +f = nbtlib.load(path) +# a tile entity, as Litematica stores them (relative to the region's minimum corner) +f["Regions"]["main"]["TileEntities"].append(Compound({"x": Int(1), "y": Int(0), "z": Int(2), "id": String("minecraft:chest"), "Items": List[Compound]([])})) +f.save(path) +data = open(path, "rb").read() +cases.append({"name": "litemapy", "variant": "litematic", "version": 6, "data": data, "blockEntities": 1, + "regions": [region_info(n, r) for n, r in Schematic.load(path).regions.items()]}) +# 2. schem v2 from litemapy (+ a block entity) +reg = Region(0, 0, 0, 5, 4, 6); fill(reg, STATES) +sp = reg.to_sponge_nbt(mc_version=3465) +sp["BlockEntities"].append(Compound({"Pos": IntArray([1, 2, 3]), "Id": String("minecraft:chest"), "Items": List[Compound]([])})) +path = os.path.join(tmp, "v2.schem") +sp.save(path, gzipped=True) +data = open(path, "rb").read() +cases.append({"name": "sponge2", "variant": "schem", "version": 2, "data": data, "blockEntities": 1, "regions": [sponge_cells(nbtlib.load(path))]}) +# 3. schem v3 / v1 by the spec (nbtlib), a palette past 128 states (two-byte varints) +def varints(idx): + out = bytearray() + for v in idx: + while v >= 128: + out.append((v & 0x7f) | 0x80); v >>= 7 + out.append(v) + return bytes(out) +def sponge(version, w, h, l, states, offset): + pal = {s: i for i, s in enumerate(states)} + idx = [rng.randrange(len(states)) for _ in range(w * h * l)] + data = ByteArray(np.frombuffer(varints(idx), dtype=np.int8)) + palc = Compound({s: Int(i) for s, i in pal.items()}) + if version >= 3: + s = Compound({"Version": Int(3), "DataVersion": Int(3953), "Width": Short(w), "Height": Short(h), "Length": Short(l), + "Offset": IntArray(offset), "Metadata": Compound({"Name": String("v3"), "Date": Long(1700000000000)}), + "Blocks": Compound({"Palette": palc, "Data": data, "BlockEntities": List[Compound]([ + Compound({"Pos": IntArray([0, 1, 2]), "Id": String("minecraft:chest"), "Data": Compound({"Items": List[Compound]([])})})])}), + "Biomes": Compound({"Palette": Compound({"minecraft:plains": Int(0)}), "Data": ByteArray([0] * (w * h * l))}), + "Entities": List[Compound]([Compound({"Pos": List[Double]([Double(1.5), Double(0.0), Double(2.5)]), "Id": String("minecraft:pig"), "Data": Compound({})})])}) + return nbtlib.File({"Schematic": s}, root_name=""), s + s = Compound({"Version": Int(1), "Width": Short(w), "Height": Short(h), "Length": Short(l), "Offset": IntArray(offset), + "PaletteMax": Int(len(states)), "Palette": palc, "BlockData": data, + "TileEntities": List[Compound]([Compound({"Pos": IntArray([0, 0, 0]), "Id": String("minecraft:chest"), "Items": List[Compound]([])})])}) + return nbtlib.File(s, root_name="Schematic"), s +stairs = ["minecraft:oak_stairs[facing=%s,half=%s,shape=%s,waterlogged=false]" % (f_, h_, s_) + for f_ in ("north", "south", "east", "west") for h_ in ("top", "bottom") + for s_ in ("straight", "inner_left", "inner_right", "outer_left", "outer_right")] +for name, version, states, size, off in [("sponge3", 3, ["minecraft:air"] + BIG + stairs + STATES[1:], (9, 7, 8), [-4, 1, 7]), + ("sponge1", 1, STATES, (4, 3, 5), [0, 0, 0])]: + f, s = sponge(version, size[0], size[1], size[2], states, off) + path = os.path.join(tmp, name + ".schem") + f.save(path, gzipped=True) + data = open(path, "rb").read() + cases.append({"name": name, "variant": "schem", "version": version, "data": data, "blockEntities": 1, "regions": [sponge_cells(s)]}) +# 4. MCEdit .schematic: legacy ids and data values (WorldEdit AddBlocks; a Schematica name table) +LEGACY = [(0, 0), (1, 0), (1, 3), (35, 14), (35, 0), (5, 2), (17, 5), (53, 3), (20, 0), (98, 1), (159, 11), (251, 4), (44, 9), (2, 0)] +for name, ids, add, mapping in [("mcedit", LEGACY, False, False), ("worldedit_add", LEGACY + [(300, 2), (4000, 0)], True, False), + ("schematica", LEGACY, False, True)]: + w, h, l = 5, 4, 3 + n = w * h * l + cells = [rng.choice(ids) for _ in range(n)] # in file order (x + z*w + y*w*l) + blocks = bytes(c[0] & 0xff for c in cells) + datas = bytes(c[1] for c in cells) + root = Compound({"Width": Short(w), "Height": Short(h), "Length": Short(l), "Materials": String("Alpha"), + "Blocks": ByteArray(np.frombuffer(blocks, dtype=np.int8)), "Data": ByteArray(np.frombuffer(datas, dtype=np.int8)), + "Entities": List[Compound]([]), + "TileEntities": List[Compound]([Compound({"x": Int(1), "y": Int(1), "z": Int(1), "id": String("Chest"), "Items": List[Compound]([])})]), + "WEOffsetX": Int(-2), "WEOffsetY": Int(0), "WEOffsetZ": Int(3)}) + if add: + nib = bytearray((n + 1) // 2) + for i, c in enumerate(cells): + hi = c[0] >> 8 + nib[i >> 1] |= (hi << 4) if i % 2 == 0 else hi # high nibble first (WorldEdit) + root["AddBlocks"] = ByteArray(np.frombuffer(bytes(nib), dtype=np.int8)) + if mapping: + root["SchematicaMapping"] = Compound({"minecraft:stone": Short(1), "minecraft:wool": Short(35), "minecraft:planks": Short(5), + "minecraft:log": Short(17), "minecraft:oak_stairs": Short(53), "minecraft:air": Short(0), + "minecraft:glass": Short(20), "minecraft:stonebrick": Short(98), + "minecraft:stained_hardened_clay": Short(159), "minecraft:concrete": Short(251), + "minecraft:stone_slab": Short(44), "minecraft:grass": Short(2)}) + path = os.path.join(tmp, name + ".schematic") + nbtlib.File(root, root_name="Schematic").save(path, gzipped=True) + legacy = [] + for z in range(l): + for y in range(h): + for x in range(w): + c = cells[x + z * w + y * w * l] + legacy.append(c[0] * 16 + c[1]) + cases.append({"name": name, "variant": "schematic", "version": 0, "data": open(path, "rb").read(), "blockEntities": 1, + "regions": [{"name": "", "min": [-2, 0, 3], "size": [w, h, l], "legacy": legacy}]}) +sys.stdout.buffer.write(pickle.dumps(cases, protocol=4)) +''' + +# our encodings read back: litematic by litemapy, schem v2 by litemapy's from_sponge_nbt, every Sponge version and +# the MCEdit layout by nbtlib +READ_BACK = COMMON + r''' +files = pickle.loads(sys.stdin.buffer.read()) +tmp = tempfile.mkdtemp() +out = {} +for name, data in files.items(): + path = os.path.join(tmp, name) + open(path, "wb").write(data) + f = nbtlib.load(path) + if name.endswith(".litematic"): + s = Schematic.load(path) + out[name] = {"regions": [region_info(n, r) for n, r in s.regions.items()], "author": s.author, "name": s.name} + elif name.endswith(".schem"): + s = f["Schematic"] if "Schematic" in f and "Version" not in f else f + regs = [sponge_cells(s)] + res = {"regions": regs, "version": int(s["Version"])} + if int(s["Version"]) == 2: + reg, mc = Region.from_sponge_nbt(nbtlib.load(path)) + cells = region_cells(reg) + res["litemapy"] = "\n".join(cells) + out[name] = res + else: + w, h, l = int(f["Width"]), int(f["Height"]), int(f["Length"]) + blocks = np.asarray(f["Blocks"], dtype=np.uint8) + datas = np.asarray(f["Data"], dtype=np.uint8) + add = np.asarray(f["AddBlocks"], dtype=np.uint8) if "AddBlocks" in f else None + legacy = [] + for z in range(l): + for y in range(h): + for x in range(w): + i = x + z * w + y * w * l + bid = int(blocks[i]) + if add is not None: + bid |= ((int(add[i >> 1]) >> (4 if i % 2 == 0 else 0)) & 15) << 8 + legacy.append(bid * 16 + int(datas[i])) + out[name] = {"regions": [{"name": "", "min": [int(f.get("WEOffsetX", 0)), int(f.get("WEOffsetY", 0)), int(f.get("WEOffsetZ", 0))], "size": [w, h, l], "legacy": legacy}]} +sys.stdout.buffer.write(pickle.dumps(out, protocol=4)) +''' + + +def run(ctx, packages, body, input=None): + try: + return ctx.python(packages, body, input=input) + except subprocess.CalledProcessError as e: + raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:]) + + +def generate(ctx): + cases = pickle.loads(run(ctx, ["nbtlib", "litemapy", "numpy"], BODY)) + ctx.emit("schematic", {"cases": cases}) + try: + files = R.luau_encode(ctx, "tools/fixtures/_schematic_encode.luau") + except subprocess.CalledProcessError as e: + raise RuntimeError("our encoder failed:\n" + (e.stderr or b"").decode(errors="replace")[-3000:] + (e.stdout or b"").decode(errors="replace")[-2000:]) + ours = pickle.loads(run(ctx, ["nbtlib", "litemapy", "numpy"], READ_BACK, input=pickle.dumps(files))) + ctx.emit("schematic_ours", ours) From 7fc5d3f5f0ffb40b84abcf7c97f1d7b6607222da Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:26:01 -0500 Subject: [PATCH 3/7] regenerate registry after merging master --- docs/FORMATS.md | 2 ++ src/Formats/Registry.luau | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 1a67408..9f9bed5 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -41,6 +41,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | +| model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | **missing** | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | @@ -128,6 +129,7 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain: - **model** - codecs/model/Mat4: 4x4 matrix and quaternion helpers for the model formats: column-major flat arrays of 16 - codecs/model/MeshFlatten: a Scene to one world-space mesh, for the writers of mesh-only formats (STL, PLY, OFF). Walks + - codecs/model/Minecraft: what Minecraft's voxel formats share (model/schematic, model/mca). New code. - **text** - codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code. - codecs/text/Nbt: Minecraft's Named Binary Tag format and its text form SNBT, the engine data/nbt, data/snbt, diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 61a19b4..6e4d13f 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -446,6 +446,18 @@ local list: { Entry } = { return require("@formats/model/ply") end, }, + { + name = "schematic", + category = "model", + path = "model/schematic", + extensions = { "schem", "schematic", "litematic" }, + mime = { "application/x-minecraft-schematic" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Nbt", "codecs/model/Minecraft" }, + caps = { decode = true, encode = true, voxels = true, blocks = true, variants = { "schem", "schematic", "litematic" } }, + load = function() + return require("@formats/model/schematic") + end, + }, { name = "stl", category = "model", From fea56f4391449c67799d73b8c01b2d36a34f54c4 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:37:43 -0500 Subject: [PATCH 4/7] ws-voxel: model/schematic (.schem v1-3, .schematic, .litematic read + write), codecs/model/Minecraft (block states, default colours, legacy ids, packed arrays) Types change (backward compatible): Types.Voxels gains optional blocks (VoxelBlocks: exact block states as u16 indices into a state palette, block entities, entities) and colors (exact u32 RGBA per cell). --- docs/FORMATS.md | 2 +- .../codecs/model/Minecraft/Legacy.luau | 15 +- src/Formats/codecs/model/Minecraft/init.luau | 12 +- src/Formats/model/schematic/Common.luau | 6 +- src/Formats/model/schematic/Mcedit.luau | 56 ++++- src/Formats/model/schematic/Sponge.luau | 10 +- src/Formats/model/schematic/init.luau | 37 ++- tests/codecs/minecraft.luau | 155 ++++++++++++ tests/model/schematic.luau | 221 ++++++++++++++++++ tools/fixtures/_schematic_encode.luau | 49 ++++ tools/fixtures/schematic.py | 1 + 11 files changed, 524 insertions(+), 40 deletions(-) create mode 100644 tests/codecs/minecraft.luau create mode 100644 tests/model/schematic.luau create mode 100644 tools/fixtures/_schematic_encode.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 9f9bed5..dedbd74 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -41,7 +41,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | -| model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | **missing** | +| model | schematic | .schem .schematic .litematic | yes | yes | voxels: true, blocks: true, variants: "schem", "schematic", "litematic" | `tests/model/schematic.luau` | | model | stl | .stl | yes | yes | ascii: true, binary: true, colors: true, indexed: false | `tests/model/stl.luau` | | model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` | | model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` | diff --git a/src/Formats/codecs/model/Minecraft/Legacy.luau b/src/Formats/codecs/model/Minecraft/Legacy.luau index 9d1348e..51f834d 100644 --- a/src/Formats/codecs/model/Minecraft/Legacy.luau +++ b/src/Formats/codecs/model/Minecraft/Legacy.luau @@ -53,21 +53,18 @@ Legacy.RENAMED = { melon_block = "melon", lit_pumpkin = "jack_o_lantern", slime = "slime_block", magma = "magma_block", red_nether_brick = "red_nether_bricks", nether_brick = "nether_bricks", end_bricks = "end_stone_bricks", mob_spawner = "spawner", web = "cobweb", snow_layer = "snow", snow = "snow_block", noteblock = "note_block", - quartz_ore = "nether_quartz_ore", reeds = "sugar_cane", waterlily = "lily_pad", flowing_water = "water", - flowing_lava = "lava", tallgrass = "short_grass", grass_path = "dirt_path", double_stone_slab = "smooth_stone", - stone_slab = "smooth_stone_slab", deadbush = "dead_bush", yellow_flower = "dandelion", - + quartz_ore = "nether_quartz_ore", reeds = "sugar_cane", waterlily = "lily_pad", + tallgrass = "short_grass", grass_path = "dirt_path", double_stone_slab = "smooth_stone", + stone_slab = "smooth_stone_slab", deadbush = "dead_bush", yellow_flower = "dandelion", fence = "oak_fence", fence_gate = "oak_fence_gate", wooden_door = "oak_door", trapdoor = "oak_trapdoor", wooden_pressure_plate = "oak_pressure_plate", wooden_button = "oak_button", stone_stairs = "cobblestone_stairs", standing_sign = "oak_sign", wall_sign = "oak_wall_sign", golden_rail = "powered_rail", portal = "nether_portal", piston_extension = "moving_piston", - silver_shulker_box = "light_gray_shulker_box", silver_glazed_terracotta = "light_gray_glazed_terracotta", - monster_egg = "infested_stone", standing_banner = "white_banner", wall_banner = "white_wall_banner", skull = "skeleton_skull", bed = "red_bed", -} +} :: { [string]: string } -- legacy names whose data value selects the variant: the modern names by data value (0-based) local DYED = "white orange magenta light_blue yellow lime pink gray light_gray cyan purple blue brown green red black" @@ -105,7 +102,7 @@ Legacy.VARIANTS = { stained_hardened_clay = dyed("terracotta"), concrete = dyed("concrete"), concrete_powder = dyed("concrete_powder"), -} -Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 } +} :: { [string]: { string } } +Legacy.MASK = { log = 4, log2 = 4, leaves = 4, leaves2 = 4, sapling = 8, wooden_slab = 8, quartz_block = 8, double_plant = 8 } :: { [string]: number } return Legacy diff --git a/src/Formats/codecs/model/Minecraft/init.luau b/src/Formats/codecs/model/Minecraft/init.luau index ded3ef3..5e31c3b 100644 --- a/src/Formats/codecs/model/Minecraft/init.luau +++ b/src/Formats/codecs/model/Minecraft/init.luau @@ -121,18 +121,18 @@ end local EXACT: { [string]: { number } } = {} for name, h in string.gmatch(Colors.BLOCKS, "([%w_]+)=(%x+)") do - EXACT[name] = hex(h) + EXACT[name :: string] = hex(h :: string) end local WOOL, CONCRETE, TERRACOTTA = list(Colors.WOOL), list(Colors.CONCRETE), list(Colors.TERRACOTTA) local PLANKS, BARK, LEAVES = list(Colors.PLANKS), list(Colors.BARK), list(Colors.LEAVES) -- longest prefixes first, so light_blue wins over blue and dark_oak over oak local function byLength(names: { string }): { { any } } - local out = {} + local out: { { any } } = {} for i, n in names do table.insert(out, { n, i }) end - table.sort(out, function(a, b) - return #a[1] > #b[1] + table.sort(out, function(a: { any }, b: { any }): boolean + return #(a[1] :: string) > #(b[1] :: string) end) return out end @@ -141,8 +141,8 @@ local SUFFIXES = { "_wall_hanging_sign", "_hanging_sign", "_wall_sign", "_sign", "_fence_gate", "_fence", "_pressure_plate", "_button", "_trapdoor", "_door", "_stairs", "_slab", "_wall", "_pane", "_carpet", "_wall_banner", "_banner", "_bars", } -local PREFIXES = { "waxed_", "potted_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" } -local CORAL = { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") } +local PREFIXES = { "waxed_", "potted_", "flowing_", "infested_", "lit_", "unlit_", "unpowered_", "powered_", "chipped_", "damaged_" } +local CORAL: { [string]: { number } } = { tube = hex("3157d0"), brain = hex("cf5b9f"), bubble = hex("a118a0"), fire = hex("a6252f"), horn = hex("d8c53e") } local FALLBACK = hex("909090") local function mix(c: { number }, w: { number }, t: number): { number } diff --git a/src/Formats/model/schematic/Common.luau b/src/Formats/model/schematic/Common.luau index e9f49c5..ee1002a 100644 --- a/src/Formats/model/schematic/Common.luau +++ b/src/Formats/model/schematic/Common.luau @@ -46,9 +46,9 @@ end function Common.ints(v: any): { number }? if Nbt.isTag(v) and v.type == "intArray" then return v.value - elseif type(v) == "table" and not Nbt.isTag(v) and v[1] ~= nil then - local out = {} - for i, x in v do + elseif type(v) == "table" and not Nbt.isTag(v) and (v :: any)[1] ~= nil then + local out: { number } = {} + for i, x in v :: { any } do out[i] = Nbt.number(x) or 0 end return out diff --git a/src/Formats/model/schematic/Mcedit.luau b/src/Formats/model/schematic/Mcedit.luau index d320037..c9b5805 100644 --- a/src/Formats/model/schematic/Mcedit.luau +++ b/src/Formats/model/schematic/Mcedit.luau @@ -91,18 +91,18 @@ function Mcedit.read(root: any, maxCells: number): ({ Common.Region }?, any) table.insert(bes, be) end end - return { + local regions: { Common.Region } = { { name = nil, - size = { sx, sy, sz }, + size = { sx, sy :: number, sz :: number }, position = { Common.int(root.WEOffsetX) or 0, Common.int(root.WEOffsetY) or 0, Common.int(root.WEOffsetZ) or 0 }, states = states, indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number), blockEntities = bes, entities = Common.list(root.Entities), }, - }, - { materials = root.Materials } + } + return regions, { materials = root.Materials } end -- the legacy blocks a colour can become (full blocks of distinct colours) @@ -160,14 +160,50 @@ function Mcedit.write(r: Common.Region, base: any): (any, string?) return nil, "a .schematic is at most 65535 cells on each axis" end local n = sx * sy * sz - local ids, datas = table.create(#r.states), table.create(#r.states) + -- the source's name tables (Schematica / MCEdit-Unified) give the ids for the names they list + local map: { [string]: number } = {} + if type(base) == "table" then + if Types.isObject(base.SchematicaMapping) then + for _, k in Types.keys(base.SchematicaMapping) do + local id = Common.int(base.SchematicaMapping[k]) + if id then + map[k] = id + end + end + end + if Types.isObject(base.BlockIDs) then + for _, k in Types.keys(base.BlockIDs) do + local id = tonumber(k) + if id and type(base.BlockIDs[k]) == "string" then + map[base.BlockIDs[k]] = id + end + end + end + end + local ids, datas = table.create(#r.states) :: { number }, table.create(#r.states) :: { number } local high = false for i, s in r.states do local id, d = Mc.legacyId(s) - if id == nil then - id, d = nearest(s) + if id ~= nil then + local lname = Mc.Legacy.NAMES[id + 1] + local mapped = lname and map["minecraft:" .. lname] + if mapped then + id = mapped + end + else + local name, props = Mc.parseState(s) + if map[name] then + id, d = map[name], 0 + for _, kv in props do + if kv[1] == "data" then + d = (tonumber(kv[2]) or 0) % 16 + end + end + else + id, d = nearest(s) + end end - ids[i], datas[i] = id, d + ids[i], datas[i] = id :: number, d :: number if (id :: number) > 255 then high = true end @@ -189,7 +225,7 @@ function Mcedit.write(r: Common.Region, base: any): (any, string?) table.insert(tiles, Common.flatBlockEntity(be, "flat")) end local ents = if #r.entities > 0 then r.entities else Nbt.list("compound") - local fields = { + local fields: { { any } } = { { "Width", Nbt.short(sx) }, { "Height", Nbt.short(sy) }, { "Length", Nbt.short(sz) }, @@ -206,7 +242,7 @@ function Mcedit.write(r: Common.Region, base: any): (any, string?) table.insert(fields, { "WEOffsetY", p[2] }) table.insert(fields, { "WEOffsetZ", p[3] }) end - local root = Common.merge(base, fields, { SchematicaMapping = true, BlockIDs = true, Add = true }) + local root = Common.merge(base, fields, { Add = true }) return root, nil end diff --git a/src/Formats/model/schematic/Sponge.luau b/src/Formats/model/schematic/Sponge.luau index 47f344f..c939d1a 100644 --- a/src/Formats/model/schematic/Sponge.luau +++ b/src/Formats/model/schematic/Sponge.luau @@ -67,18 +67,18 @@ function Sponge.read(s: any, maxCells: number): ({ Common.Region }?, any) end end local off = Common.ints(s.Offset) or { 0, 0, 0 } - return { + local regions: { Common.Region } = { { name = nil, - size = { sx, sy, sz }, + size = { sx, sy :: number, sz :: number }, position = { off[1] or 0, off[2] or 0, off[3] or 0 }, states = states, indices = Packed.fromYzx(yzx, sx, sy :: number, sz :: number), blockEntities = bes, entities = Common.list(s.Entities), }, - }, - { version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata } + } + return regions, { version = version, dataVersion = Common.int(s.DataVersion), metadata = s.Metadata } end -- write(region, version, dataVersion, base?) -> the Schematic compound (v3: the caller wraps it in the root) | nil, @@ -101,7 +101,7 @@ function Sponge.write(r: Common.Region, version: number, dataVersion: number, ba for _, be in r.blockEntities do table.insert(bes, Common.flatBlockEntity(be, if version >= 3 then "data" else "pos")) end - local ents = if #r.entities > 0 then r.entities else nil + local ents = if #r.entities > 0 then r.entities else Nbt.list("compound") -- optional, but readers expect it local off = Nbt.intArray({ r.position[1], r.position[2], r.position[3] }) local fields: { { any } } = { { "Version", version }, diff --git a/src/Formats/model/schematic/init.luau b/src/Formats/model/schematic/init.luau index 4d0db36..b844efa 100644 --- a/src/Formats/model/schematic/init.luau +++ b/src/Formats/model/schematic/init.luau @@ -49,11 +49,22 @@ export type EncodeOptions = { title: string?, -- .litematic Metadata.Name compression: ("gzip" | "zlib" | "none")?, -- default gzip, as every tool writes them level: number?, -- deflate level + format: string?, -- set by the api: the format key the encoder was picked by ("schem", "litematic", ...) } -- ------------------------------------------------------------------------------------------------ constants local DEFAULT_DATA_VERSION = 3953 local LITEMATIC_HINTS = { "Regions", "EnclosingSize", "RegionCount", "TotalVolume", "MinecraftDataVersion" } +local SPONGE_HINTS = { "BlockData", "PaletteMax" } -- v1 / v2 fields (some writers leave the root unnamed) + +local function hinted(head: string, hints: { string }): boolean + for _, h in hints do + if string.find(head, string.char(0, #h) .. h, 1, true) then + return true + end + end + return false +end -- ------------------------------------------------------------------------------------------------ sniff function Schematic.sniff(r: Bytes.Reader): number @@ -65,12 +76,25 @@ function Schematic.sniff(r: Bytes.Reader): number return 1 end local head = buffer.tostring(p.head) - for _, h in LITEMATIC_HINTS do - if string.find(head, string.char(0, #h) .. h, 1, true) then - return 1 - end + return if hinted(head, LITEMATIC_HINTS) or hinted(head, SPONGE_HINTS) then 1 else 0 +end + +-- variant(r) -> "schem" | "litematic" | "schematic" | nil: the flavour, for F.detect (from the first inflated bytes) +function Schematic.variant(r: Bytes.Reader): string? + local p = Nbt.peek(r.buf, r.base, r.limit - r.base) + if not p then + return nil end - return 0 + if p.firstName == "Schematic" then + return "schem" + end + local head = buffer.tostring(p.head) + if hinted(head, LITEMATIC_HINTS) then + return "litematic" + elseif hinted(head, SPONGE_HINTS) or (p.name == "Schematic" and hinted(head, { "Palette", "Version" })) then + return "schem" + end + return if p.name == "Schematic" then "schematic" else nil end -- ------------------------------------------------------------------------------------------------ decode @@ -114,7 +138,8 @@ function Schematic.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, regions, extra = Mcedit.read(s, maxCells) end if not regions then - return nil, Err.from(extra) + local msg = tostring(extra) + return nil, Err.from(msg, nil, if string.find(msg, "limit: ", 1, true) then "limit" else nil) end local scene = Types.Scene.new() scene.voxels = {} diff --git a/tests/codecs/minecraft.luau b/tests/codecs/minecraft.luau new file mode 100644 index 0000000..e8afa7a --- /dev/null +++ b/tests/codecs/minecraft.luau @@ -0,0 +1,155 @@ +-- codecs/model/Minecraft tests: packed index arrays (spanning and not, 1..16 bits, against a bit-by-bit reference), +-- Sponge varints, nibble arrays, YZX reordering, block-state strings and their NBT form, every legacy id / data pair +-- through legacyState / legacyId, colours (air, families, fallbacks), voxels / blocksOf and nearest-colour blocks. +-- The formats using it: tests/model/schematic.luau, tests/model/mca.luau. +local T = require("@tests/T") +local Mc = require("@formats/codecs/model/Minecraft") +local Types = require("@formats/Types") + +local t = T.suite("minecraft") +local P = Mc.Packed +local rand = T.rng(3) + +-- 1. packed arrays against a reference that walks the bits one at a time +local function refBit(longs: buffer, p: number): number + return bit32.extract(buffer.readu8(longs, p // 8), p % 8, 1) +end +for bits = 1, 16 do + for _, spanning in { true, false } do + local count = 100 + rand(300) + local max = math.min(2 ^ bits, 70000) + local idx = buffer.create(count * 2) + for i = 0, count - 1 do + buffer.writeu16(idx, i * 2, rand(max)) + end + local longs = P.pack(idx, count, bits, spanning) + t:eq(buffer.len(longs), P.longsNeeded(count, bits, spanning) * 8, bits .. " bits: size") + local per = 64 // bits + local bad = 0 + for i = 0, count - 1 do + local p = if spanning then i * bits else (i // per) * 64 + (i % per) * bits + local v = 0 + for k = 0, bits - 1 do + v += refBit(longs, p + k) * 2 ^ k + end + if v ~= buffer.readu16(idx, i * 2) then + bad += 1 + end + end + t:eq(bad, 0, bits .. " bits " .. tostring(spanning) .. ": layout") + local back = buffer.create(count * 2) + local ok, e = P.unpack(longs, bits, count, spanning, back, max) + t:check(ok, tostring(e)) + t:eq(buffer.tostring(back), buffer.tostring(idx), bits .. " bits " .. tostring(spanning) .. ": round trip") + end +end +do + local out = buffer.create(40) + t:check(not P.unpack(buffer.create(8), 4, 20, false, out, 16), "too few longs") + local l = P.pack(buffer.fromstring("\5\0"), 1, 4, false) + t:check(not P.unpack(l, 4, 1, false, out, 3), "index past the palette") + t:eq(P.bitsFor(17, 4), 5, "bitsFor") + t:eq(P.bitsFor(1, 2), 2, "bitsFor minimum") +end + +-- 2. varints, nibbles, YZX +do + local idx = buffer.create(400) + for i = 0, 199 do + buffer.writeu16(idx, i * 2, (i * 997) % 20000) + end + local v = P.toVarints(idx, 200) + local back = buffer.create(400) + t:check(P.varints(v, 0, buffer.len(v), 200, back, 20000), "varints") + t:eq(buffer.tostring(back), buffer.tostring(idx), "varints round trip") + t:check(not P.varints(v, 0, buffer.len(v) - 1, 200, back, 20000), "varints truncated") + local nib = buffer.create(2) + P.setNibble(nib, 0, 0, 0xA, true) + P.setNibble(nib, 0, 1, 0x3, true) + P.setNibble(nib, 0, 2, 0x7, false) + t:eq(buffer.readu8(nib, 0), 0xA3, "high nibble first") + t:eq(buffer.readu8(nib, 1), 0x07, "low nibble first") + t:eq(P.nibble(nib, 0, 1, true), 3, "read nibble") + local sx, sy, sz = 3, 4, 5 + local yzx = buffer.create(sx * sy * sz * 2) + for y = 0, sy - 1 do + for z = 0, sz - 1 do + for x = 0, sx - 1 do + buffer.writeu16(yzx, (x + z * sx + y * sx * sz) * 2, x * 100 + y * 10 + z) + end + end + end + local vox = P.fromYzx(yzx, sx, sy, sz) + t:eq(buffer.readu16(vox, (2 + sx * (3 + sy * 4)) * 2), 234, "fromYzx") + t:eq(buffer.tostring(P.toYzx(vox, sx, sy, sz)), buffer.tostring(yzx), "toYzx") +end + +-- 3. states +do + local name, props = Mc.parseState("oak_log[axis=y, foo = bar]") + t:eq(name, "minecraft:oak_log", "namespace added") + t:eq(#props, 2, "props") + t:eq(Mc.stateString(name, props), "minecraft:oak_log[axis=y,foo=bar]", "stateString") + local c = Mc.stateToNbt("minecraft:chest[facing=north,type=single]") + t:eq(table.concat(Types.keys(c.Properties), ","), "facing,type", "NBT property order") + t:eq(Mc.stateFromNbt(c), "minecraft:chest[facing=north,type=single]", "stateFromNbt") + t:eq(Mc.baseName("minecraft:stone"), "stone", "baseName") + t:check(Mc.isAir("minecraft:cave_air") and not Mc.isAir("minecraft:stone"), "isAir") +end + +-- 4. legacy ids: every id / data pair reads back exactly +do + local bad = 0 + for id = 0, 255 do + for d = 0, 15 do + local s = Mc.legacyState(id, d) + local i2, d2 = Mc.legacyId(s) + if i2 ~= id or d2 ~= d then + bad += 1 + end + end + end + t:eq(bad, 0, "legacy round trip") + t:eq(Mc.legacyState(35, 14), "minecraft:red_wool", "wool 14") + t:eq(Mc.legacyState(5, 2), "minecraft:birch_planks", "planks 2") + t:eq(Mc.legacyState(17, 5), "minecraft:spruce_log[data=5]", "log axis bits kept") + t:eq(select(1, Mc.legacyId("minecraft:white_concrete")), 251, "modern name -> legacy id") +end + +-- 5. colours +do + t:eq(Mc.color("minecraft:air"), nil, "air") + local function hex(s: string): string + local c = Mc.color(s) :: { number } + return string.format("%02x%02x%02x%02x", c[1], c[2], c[3], c[4]) + end + t:eq(hex("minecraft:stone"), "7d7d7dff", "exact") + t:eq(hex("minecraft:stone_brick_stairs[facing=east]"), hex("minecraft:stone_bricks"), "stairs -> base") + t:eq(hex("minecraft:red_concrete"), "8e2020ff", "dye family") + t:eq(hex("minecraft:dark_oak_log"), "3e2f17ff", "wood bark") + t:eq(string.sub(hex("minecraft:red_stained_glass"), 7, 8), "80", "stained glass translucent") + t:eq(hex("minecraft:wool[data=14]"), hex("minecraft:red_wool"), "legacy data colour") + t:eq(hex("mod:something_odd"), "909090ff", "fallback") +end + +-- 6. voxels / blocksOf +do + local states = { "minecraft:air", "minecraft:stone", "minecraft:red_wool", "minecraft:stone" } + local idx = buffer.create(8 * 2) + for i = 0, 7 do + buffer.writeu16(idx, i * 2, i % 4) + end + local v = Mc.voxels(2, 2, 2, states, idx) + t:eq(buffer.readu8(v.data, 0), 0, "air -> 0") + t:eq(buffer.readu8(v.data, 1), buffer.readu8(v.data, 3), "same colour, same index") + t:check(buffer.readu8(v.data, 2) ~= buffer.readu8(v.data, 1), "different colours") + local s2, i2 = Mc.blocksOf(v) + t:check(s2 == states and i2 == idx, "blocksOf keeps the blocks") + local g = Types.Voxels.new(2, 1, 1) + g.palette[7] = { 240, 118, 19, 255 } + buffer.writeu8(g.data, 1, 7) + local s3, i3 = Mc.blocksOf(g) + t:eq((s3 :: { string })[buffer.readu16(i3, 2) + 1], "minecraft:orange_wool", "nearest block by colour") + t:eq((s3 :: { string })[buffer.readu16(i3, 0) + 1], "minecraft:air", "empty -> air") +end +t:done() diff --git a/tests/model/schematic.luau b/tests/model/schematic.luau new file mode 100644 index 0000000..8508c99 --- /dev/null +++ b/tests/model/schematic.luau @@ -0,0 +1,221 @@ +-- model/schematic tests: .litematic files written by litemapy (several regions, negative sizes, a 40-state palette, +-- tile entities), Sponge .schem v2 (litemapy) and v1 / v3 (nbtlib, by the spec; two-byte varints), MCEdit +-- .schematic (legacy ids + data, WorldEdit AddBlocks, a Schematica name table): every cell's block state, placement, +-- block entities; our re-encodings give the same NBT for the same variant, and the reference readers (litemapy / +-- nbtlib, in the fixture step) read our output, across variants and from colour-only grids, to the same cells; +-- detection, the api, error codes and the fuzz pass. Fixtures: tools/fixtures/schematic.py. +local T = require("@tests/T") +local F = require("@formats") +local Schematic = require("@formats/model/schematic") +local Mc = require("@formats/codecs/model/Minecraft") +local Nbt = require("@formats/codecs/text/Nbt") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/schematic") +local Ours = require("@tests/gen/schematic_ours") + +local t = T.suite("schematic") + +t:eq(Schematic.name, "schematic", "name") +t:check(Schematic.caps.decode and Schematic.caps.encode, "caps") + +local function dec(data: string | buffer, opts: any?): (Types.Scene?, any) + local b = if type(data) == "string" then buffer.fromstring(data) else data + return Schematic.decode(Bytes.reader(b), opts) +end + +-- the region record of node i: { name, min, size, cells (state per cell, "\n"-joined), legacy (id * 16 + data) } +local function regions(scene: Types.Scene): { any } + local out = {} + for _, node in scene.nodes do + local v = (scene.voxels :: { Types.Voxels })[node.voxels :: number] + local b = v.blocks :: Types.VoxelBlocks + local n = v.size[1] * v.size[2] * v.size[3] + local cells, legacy = table.create(n), table.create(n) + for i = 0, n - 1 do + local st = b.palette[buffer.readu16(b.data, i * 2) + 1] + cells[i + 1] = st + local id, d = Mc.legacyId(st) + legacy[i + 1] = if id then id * 16 + (d :: number) else -1 + end + local tr = node.translation :: { number } + table.insert(out, { name = node.name, min = tr, size = v.size, cells = table.concat(cells, "\n"), legacy = legacy, voxels = v, blockEntities = #(b.blockEntities or {}) }) + end + return out +end + +local function sameRegion(got: any, want: any, label: string) + t:eq(got.size[1] .. "," .. got.size[2] .. "," .. got.size[3], want.size[1] .. "," .. want.size[2] .. "," .. want.size[3], label .. ": size") + t:eq(got.min[1] .. "," .. got.min[2] .. "," .. got.min[3], want.min[1] .. "," .. want.min[2] .. "," .. want.min[3], label .. ": minimum corner") + if want.cells then + t:eq(got.cells, want.cells, label .. ": cells") + else + local bad = 0 + for i, x in want.legacy do + if got.legacy[i] ~= x then + bad += 1 + end + end + t:eq(bad, 0, label .. ": legacy ids") + end +end + +-- 1. reference files +local decoded: { [string]: Types.Scene } = {} +for _, c in Fx.cases do + local scene, err = dec(c.data) + t:check(scene ~= nil, c.name .. ": " .. tostring(err)) + local s = scene :: Types.Scene + decoded[c.name] = s + t:eq(s.meta.source.variant, c.variant, c.name .. ": variant") + if c.version > 0 then + t:eq(s.meta.source.version, c.version, c.name .. ": version") + end + local regs = regions(s) + t:eq(#regs, #c.regions, c.name .. ": regions") + local bes = 0 + for i, want in c.regions do + sameRegion(regs[i], want, c.name .. " region " .. i) + if want.name ~= "" then + t:eq(regs[i].name, want.name, c.name .. " region " .. i .. ": name") + end + bes += regs[i].blockEntities + end + t:eq(bes, c.blockEntities, c.name .. ": block entities") + -- colours: air is empty, the rest coloured from the default table + local v = regs[1].voxels + local b = v.blocks + for i = 0, v.size[1] * v.size[2] * v.size[3] - 1 do + local st = b.palette[buffer.readu16(b.data, i * 2) + 1] + local idx = buffer.readu8(v.data, i) + if Mc.isAir(st) ~= (idx == 0) then + t:check(false, c.name .. ": cell " .. i .. " colour index " .. idx .. " for " .. st) + end + if idx > 0 then + local col, p = Mc.color(st) :: { number }, v.palette[idx] + if col[1] ~= p[1] or col[2] ~= p[2] or col[3] ~= p[3] then + t:check(false, c.name .. ": cell " .. i .. " colour of " .. st) + end + end + end + -- the same variant again: the same NBT (every field), the same cells + local out, eerr = Schematic.encode(s) + t:check(out ~= nil, c.name .. ": encode " .. tostring(eerr)) + local again = assert(dec(out :: buffer)) + t:eq(Nbt.print(again.meta.source.nbt), Nbt.print(s.meta.source.nbt), c.name .. ": same NBT") + t:eq(again.meta.source.rootName, s.meta.source.rootName, c.name .. ": root name") + for i, r in regions(again) do + sameRegion(r, regs[i], c.name .. " again region " .. i) + end + -- api: detection by content (the flavour) and loading + t:eq(F.detect(c.data), c.variant, c.name .. ": F.detect") + local viaApi = F.load(c.data) + t:check(viaApi and viaApi.kind == "scene", c.name .. ": F.load") +end + +-- 2. our encodings read back by litemapy / nbtlib (fixture step) +local outputs: { [string]: () -> (buffer?, any) } = {} +local function colorGrid(): Types.Voxels + local v = Types.Voxels.new(4, 3, 2) + v.palette[1] = { 160, 40, 35, 255 } + v.palette[2] = { 125, 125, 125, 255 } + v.palette[3] = { 60, 110, 230, 120 } + for i = 0, 4 * 3 * 2 - 1 do + buffer.writeu8(v.data, i, i % 4) + end + return v +end +outputs["litemapy.litematic"] = function() return Schematic.encode(decoded.litemapy) end +outputs["litemapy.schem"] = function() return Schematic.encode(decoded.litemapy, { variant = "schem", version = 2 }) end +outputs["sponge2.schem"] = function() return Schematic.encode(decoded.sponge2) end +outputs["sponge2.litematic"] = function() return Schematic.encode(decoded.sponge2, { variant = "litematic" }) end +outputs["sponge3.schem"] = function() return Schematic.encode(decoded.sponge3) end +outputs["sponge3v2.schem"] = function() return Schematic.encode(decoded.sponge3, { version = 2 }) end +outputs["sponge1.schem"] = function() return Schematic.encode(decoded.sponge1) end +outputs["mcedit.schematic"] = function() return Schematic.encode(decoded.mcedit) end +outputs["worldedit_add.schematic"] = function() return Schematic.encode(decoded.worldedit_add) end +outputs["sponge2.schematic"] = function() return Schematic.encode(decoded.sponge2, { variant = "schematic" }) end +outputs["mcedit.schem"] = function() return Schematic.encode(decoded.mcedit, { variant = "schem" }) end +outputs["colors.schem"] = function() return Schematic.encode(colorGrid()) end +outputs["colors.litematic"] = function() return Schematic.encode(colorGrid(), { variant = "litematic" }) end +outputs["colors.schematic"] = function() return Schematic.encode(colorGrid(), { variant = "schematic" }) end +local count = 0 +for name, ref in Ours do + local make = outputs[name] + t:check(make ~= nil, name .. ": known output") + local mine = assert(dec(assert(make()))) + local regs = regions(mine) + t:eq(#regs, #ref.regions, name .. ": regions read back") + for i, want in ref.regions do + sameRegion(regs[i], want, name .. " (reference) region " .. i) + end + if ref.litemapy then + t:eq(ref.litemapy, regs[1].cells, name .. ": litemapy's Sponge reader") + end + count += 1 +end +t:eq(count, 14, "every output checked") +-- the source cells survive the conversions +do + local function cellsVia(name: string): string + return regions(assert(dec(assert(outputs[name]()))))[1].cells + end + t:eq(cellsVia("sponge2.litematic"), regions(decoded.sponge2)[1].cells, "schem -> litematic cells") + t:eq(cellsVia("sponge3v2.schem"), regions(decoded.sponge3)[1].cells, "v3 -> v2 cells") + local legacy = regions(assert(dec(assert(outputs["mcedit.schem"]()))))[1].legacy + local src = regions(decoded.mcedit)[1].legacy + t:eq(table.concat(legacy, ","), table.concat(src, ","), "schematic -> schem keeps legacy states") + -- litematic -> schem merges the regions into one grid covering them all + local merged = regions(assert(dec(assert(outputs["litemapy.schem"]()))))[1] + t:eq(merged.size[1] .. "," .. merged.size[2] .. "," .. merged.size[3], "31,5,12", "merged size") + -- colour grid -> blocks by colour + local cg = regions(assert(dec(assert(outputs["colors.schem"]()))))[1] + local first = string.split(cg.cells, "\n") + t:eq(first[1], "minecraft:air", "empty cell -> air") + t:eq(first[2], "minecraft:red_wool", "red -> red wool") + t:eq(first[4], "minecraft:light_blue_stained_glass", "translucent blue -> stained glass") +end + +-- 3. through the api +do + local scene = assert(F.load(Fx.cases[1].data, { name = "x.litematic" })) + local schem = assert(F.save(scene, nil, { format = "schem" })) :: buffer + t:eq(F.detect(schem), "schem", "F.save format = schem") + local lite = assert(F.save(scene, nil, { format = "litematic" })) :: buffer + t:eq(F.detect(lite), "litematic", "F.save format = litematic") + local legacy = assert(F.save(scene, nil, { format = "schematic", variant = "schematic" })) :: buffer + t:eq(F.detect(legacy), "schematic", "variant schematic") + t:eq(F.detect(legacy, { name = "a.schematic" }), "schematic", "detect with a name") + -- a vox-like grid without blocks through F.save + local g = Types.Voxels.new(2, 2, 2) + buffer.writeu8(g.data, 0, 5) + t:check(F.save(g, nil, { format = "schem" }) ~= nil, "save a bare Voxels") +end + +-- 4. errors +do + local _, e1 = dec(assert(Nbt.encode(Nbt.compound({ a = 1 }, { "a" })))) + t:check(e1 and e1.code == Err.CORRUPT, "not a schematic") + local _, e2 = dec(Fx.cases[1].data, { maxCells = 10 }) + t:check(e2 and e2.code == Err.LIMIT, "maxCells") + local _, e3 = Schematic.encode({ kind = "scene" } :: any) + t:check(e3 and e3.code == Err.ARG, "encode without voxels") + local _, e4 = Schematic.encode(colorGrid(), { variant = "x" :: any }) + t:check(e4 and e4.code == Err.ARG, "unknown variant") + local bad = Nbt.compound({ Width = Nbt.short(4), Height = Nbt.short(4), Length = Nbt.short(4), Blocks = buffer.create(10) }, { "Width", "Height", "Length", "Blocks" }) + local _, e5 = dec(assert(Nbt.encode(bad, { name = "Schematic" }))) + t:check(e5 and e5.code == Err.TRUNCATED, "short Blocks") +end + +-- 5. fuzz (the uncompressed NBT too, so mutations reach the layouts, not just gzip's CRC) +local samples = {} +for _, c in Fx.cases do + local s = assert(dec(c.data)) + table.insert(samples, (assert(Nbt.encode(s.meta.source.nbt, { name = s.meta.source.rootName, compression = "none" })))) +end +table.insert(samples, Fx.cases[1].data) +t:fuzz("decode", function(b: buffer) + return Schematic.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tools/fixtures/_schematic_encode.luau b/tools/fixtures/_schematic_encode.luau new file mode 100644 index 0000000..1f09645 --- /dev/null +++ b/tools/fixtures/_schematic_encode.luau @@ -0,0 +1,49 @@ +-- tools/fixtures/schematic.py helper: our model/schematic encoder's output for the reference readers (litemapy, +-- nbtlib). Prints "\t" lines. Inputs: the decoded fixtures of tests/gen/schematic, plus grids built here. +local Schematic = require("@formats/model/schematic") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/schematic") + +local function hex(b: buffer): string + local t = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(t) +end + +local function emit(name: string, b: buffer?, e: any) + if not b then + error(name .. ": " .. tostring(e)) + end + print(name .. "\t" .. hex(b)) +end + +local byName = {} +for _, c in Fx.cases do + byName[c.name] = assert(Schematic.decode(Bytes.reader(buffer.fromstring(c.data)))) +end +-- same variant (fields kept), and across variants +emit("litemapy.litematic", Schematic.encode(byName.litemapy)) +emit("litemapy.schem", Schematic.encode(byName.litemapy, { variant = "schem", version = 2 })) +emit("sponge2.schem", Schematic.encode(byName.sponge2)) +emit("sponge2.litematic", Schematic.encode(byName.sponge2, { variant = "litematic" })) +emit("sponge3.schem", Schematic.encode(byName.sponge3)) +emit("sponge3v2.schem", Schematic.encode(byName.sponge3, { version = 2 })) +emit("sponge1.schem", Schematic.encode(byName.sponge1)) +emit("mcedit.schematic", Schematic.encode(byName.mcedit)) +emit("worldedit_add.schematic", Schematic.encode(byName.worldedit_add)) +emit("sponge2.schematic", Schematic.encode(byName.sponge2, { variant = "schematic" })) +emit("mcedit.schem", Schematic.encode(byName.mcedit, { variant = "schem" })) +-- a colour grid (no block states): each palette colour becomes the block nearest in colour +local v = Types.Voxels.new(4, 3, 2) +v.palette[1] = { 160, 40, 35, 255 } +v.palette[2] = { 125, 125, 125, 255 } +v.palette[3] = { 60, 110, 230, 120 } +for i = 0, 4 * 3 * 2 - 1 do + buffer.writeu8(v.data, i, i % 4) +end +emit("colors.schem", Schematic.encode(v)) +emit("colors.litematic", Schematic.encode(v, { variant = "litematic" })) +emit("colors.schematic", Schematic.encode(v, { variant = "schematic" })) diff --git a/tools/fixtures/schematic.py b/tools/fixtures/schematic.py index 7996ad6..e44d80c 100644 --- a/tools/fixtures/schematic.py +++ b/tools/fixtures/schematic.py @@ -119,6 +119,7 @@ def varints(idx): out.append(v) return bytes(out) def sponge(version, w, h, l, states, offset): + states = list(dict.fromkeys(states)) pal = {s: i for i, s in enumerate(states)} idx = [rng.randrange(len(states)) for _ in range(w * h * l)] data = ByteArray(np.frombuffer(varints(idx), dtype=np.int8)) From 286d193f144b4ad6b7b9530024f596665c169d6b Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:47:05 -0500 Subject: [PATCH 5/7] ws-voxel: model/mca (Anvil regions read-only: gzip / zlib / LZ4Block / stored / external .mcc chunks; 1.18+, 1.13-1.17 and pre-1.13 chunk layouts) into Voxels with exact block states; block entity shapes moved into codecs/model/Minecraft --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/codecs/model/Minecraft/init.luau | 87 +++++ src/Formats/model/mca/Chunk.luau | 135 +++++++ src/Formats/model/mca/Lz4Block.luau | 70 ++++ src/Formats/model/mca/init.luau | 355 +++++++++++++++++++ src/Formats/model/schematic/Common.luau | 86 +---- tests/model/mca.luau | 148 ++++++++ tools/fixtures/mca.py | 218 ++++++++++++ 9 files changed, 1032 insertions(+), 80 deletions(-) create mode 100644 src/Formats/model/mca/Chunk.luau create mode 100644 src/Formats/model/mca/Lz4Block.luau create mode 100644 src/Formats/model/mca/init.luau create mode 100644 tests/model/mca.luau create mode 100644 tools/fixtures/mca.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 3ffa1a8..702f9a2 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -38,6 +38,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | 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 | `tests/model/gltf.luau` | +| model | mca | .mca .mcr | yes | - | voxels: true, blocks: true | `tests/model/mca.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 43dcd3c..ac05da1 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -410,6 +410,18 @@ local list: { Entry } = { return require("@formats/model/gltf") end, }, + { + name = "mca", + category = "model", + path = "model/mca", + extensions = { "mca", "mcr" }, + mime = { "application/x-minecraft-region" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/text/Nbt", "codecs/model/Minecraft", "codecs/compress/Lz4" }, + caps = { decode = true, encode = false, voxels = true, blocks = true }, + load = function() + return require("@formats/model/mca") + end, + }, { name = "obj", category = "model", diff --git a/src/Formats/codecs/model/Minecraft/init.luau b/src/Formats/codecs/model/Minecraft/init.luau index 5e31c3b..634757b 100644 --- a/src/Formats/codecs/model/Minecraft/init.luau +++ b/src/Formats/codecs/model/Minecraft/init.luau @@ -497,4 +497,91 @@ function Minecraft.blocksOf(v: Types.Voxels): ({ string }?, any) return states, out end +-- ------------------------------------------------------------------------------------------------ block entities +-- Block entity records in one shape, { pos = { x, y, z }, id, data } (Sponge v3's), from / to the flat +-- { x, y, z, id, ... } of MCEdit, Litematica and chunks, and Sponge v1 / v2's { Pos, Id, ... }. +local function int(v: any): number? + local n = Nbt.number(v) + if n == nil or n ~= n or n % 1 ~= 0 then + return nil + end + return n +end +local function ints(v: any): { number }? + if Nbt.isTag(v) and v.type == "intArray" then + return v.value + elseif type(v) == "table" and not Nbt.isTag(v) and (v :: any)[1] ~= nil then + local out: { number } = {} + for i, x in v :: { any } do + out[i] = Nbt.number(x) or 0 + end + return out + end + return nil +end +Minecraft.int = int -- the integer value of an NBT number | nil +Minecraft.ints = ints -- the numbers of an intArray or a list | nil + +local function rest(c: any, skip: { [string]: boolean }): { [string]: any } + local out, keys = {}, {} + for _, k in Types.keys(c) do + if not skip[k] then + out[k] = c[k] + table.insert(keys, k) + end + end + return Types.object(out, keys) +end + +local FLAT_SKIP = { x = true, y = true, z = true, id = true } +local POS_SKIP = { Pos = true, Id = true } + +-- blockEntity(c, style) -> the common shape of one record: style "flat" (MCEdit, Litematica), "pos" (Sponge v1 / v2), +-- "data" (Sponge v3) +function Minecraft.blockEntity(c: any, style: string): any + if type(c) ~= "table" or Nbt.isTag(c) then + return nil + end + if style == "flat" then + return { pos = { int(c.x) or 0, int(c.y) or 0, int(c.z) or 0 }, id = if type(c.id) == "string" then c.id else nil, data = rest(c, FLAT_SKIP) } + end + local p = ints(c.Pos) or { 0, 0, 0 } + local data = if style == "data" then (if type(c.Data) == "table" then c.Data else Types.object()) else rest(c, POS_SKIP) + return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = if type(c.Id) == "string" then c.Id else nil, data = data } +end + +-- flatBlockEntity(be, style) -> the record in a flavour's shape (the inverse of blockEntity) +function Minecraft.flatBlockEntity(be: any, style: string): any + local o = Types.object() + local data = if type(be.data) == "table" then be.data else Types.object() + if style == "flat" then + Types.set(o, "x", be.pos[1]) + Types.set(o, "y", be.pos[2]) + Types.set(o, "z", be.pos[3]) + if be.id then + Types.set(o, "id", be.id) + end + for _, k in Types.keys(data) do + if not FLAT_SKIP[k] then + Types.set(o, k, data[k]) + end + end + return o + end + Types.set(o, "Pos", Nbt.intArray({ be.pos[1], be.pos[2], be.pos[3] })) + if be.id then + Types.set(o, "Id", be.id) + end + if style == "data" then + Types.set(o, "Data", data) + else + for _, k in Types.keys(data) do + if not POS_SKIP[k] then + Types.set(o, k, data[k]) + end + end + end + return o +end + return Minecraft diff --git a/src/Formats/model/mca/Chunk.luau b/src/Formats/model/mca/Chunk.luau new file mode 100644 index 0000000..75764a4 --- /dev/null +++ b/src/Formats/model/mca/Chunk.luau @@ -0,0 +1,135 @@ +--!strict +-- model/mca/Chunk: the blocks of one Anvil chunk's NBT, from the Minecraft wiki "Chunk format" page, in the three +-- layouts it has had: 1.18+ (root sections[] with block_states { palette, data }, non-spanning packing, at least +-- 4 bits, yPos), 1.13 - 1.17 (Level.Sections[] with Palette + BlockStates, spanning before DataVersion 2529 = +-- 20w17a), and before 1.13 (Level.Sections[] with Blocks / Add / Data nibble arrays, numeric ids through +-- codecs/model/Minecraft legacyState). Each section is 16 x 16 x 16 cells in Minecraft's order (x, then z, then y). +local Types = require("@formats/Types") +local Nbt = require("@formats/codecs/text/Nbt") +local Mc = require("@formats/codecs/model/Minecraft") + +local Chunk = {} + +local Packed = Mc.Packed + +export type Section = { y: number, states: { string }, cells: buffer } -- cells: u16 per cell, 4096, x-z-y order +export type Blocks = { + x: number, -- chunk coordinates (xPos / zPos) + z: number, + dataVersion: number?, + sections: { Section }, + blockEntities: { any }, -- the chunk's records as they are (absolute x, y, z) + entities: { any }, -- entities stored in the chunk (before 1.17) +} + +local function int(v: any): number? + local n = Nbt.number(v) + return if n and n == n and n % 1 == 0 then n else nil +end + +local function list(v: any): { any } + return if type(v) == "table" and not Nbt.isTag(v) and not Types.isObject(v) then v else {} +end + +-- a palette section (1.13+): states from the palette compounds, cells from the packed array +local function paletted(y: number, palette: { any }, data: any, minBits: number, spanning: boolean): (Section?, string?) + local states = table.create(#palette) :: { string } + for i, c in palette do + local s = Mc.stateFromNbt(c) + if not s then + return nil, "section " .. y .. ": bad palette entry " .. i + end + states[i] = s + end + if #states == 0 then + return nil, nil + end + local cells = buffer.create(8192) + if #states > 1 or data ~= nil then + if not (Nbt.isTag(data) and data.type == "longArray") then + return nil, "section " .. y .. ": no block state data" + end + local bits = Packed.bitsFor(#states, minBits) + local ok, e = Packed.unpack(data.value, bits, 4096, spanning, cells, #states) + if not ok then + return nil, "section " .. y .. ": " .. tostring(e) + end + end + return { y = y, states = states, cells = cells }, nil +end + +-- blocks(root) -> Blocks | nil, message: the sections of a decoded chunk +function Chunk.blocks(root: any): (Blocks?, string?) + if type(root) ~= "table" or not Types.isObject(root) then + return nil, "chunk NBT is not a compound" + end + local dv = int(root.DataVersion) + local level = if Types.isObject(root.Level) then root.Level else root + local x, z = int(level.xPos), int(level.zPos) + if not x or not z then + return nil, "chunk without xPos / zPos" + end + local out: Blocks = { x = x, z = z, dataVersion = dv, sections = {}, blockEntities = {}, entities = list(level.Entities) } + if root.sections ~= nil then + -- 1.18+ + for _, s in list(root.sections) do + local y = int(s.Y) + local bs = s.block_states + if y and type(bs) == "table" and not Nbt.isTag(bs) then + local sec, e = paletted(y, list(bs.palette), bs.data, 4, false) + if e then + return nil, e + end + if sec then + table.insert(out.sections, sec) + end + end + end + out.blockEntities = list(root.block_entities) + return out, nil + end + for _, s in list(level.Sections) do + local y = int(s.Y) + if y then + if s.Palette ~= nil then + local sec, e = paletted(y, list(s.Palette), s.BlockStates, 4, (dv or 0) < 2529) + if e then + return nil, e + end + if sec then + table.insert(out.sections, sec) + end + elseif type(s.Blocks) == "buffer" then + local blocks = s.Blocks :: buffer + if buffer.len(blocks) < 4096 then + return nil, "section " .. y .. ": short Blocks array" + end + local data = if type(s.Data) == "buffer" and buffer.len(s.Data) >= 2048 then s.Data else nil + local add = if type(s.Add) == "buffer" and buffer.len(s.Add) >= 2048 then s.Add else nil + local slots: { [number]: number } = {} + local states: { string } = {} + local cells = buffer.create(8192) + for i = 0, 4095 do + local id = buffer.readu8(blocks, i) + if add then + id += Packed.nibble(add, 0, i, false) * 256 + end + local d = if data then Packed.nibble(data, 0, i, false) else 0 + local key = id * 16 + d + local slot = slots[key] + if not slot then + table.insert(states, Mc.legacyState(id, d)) + slot = #states - 1 + slots[key] = slot + end + buffer.writeu16(cells, i * 2, slot :: number) + end + table.insert(out.sections, { y = y, states = states, cells = cells }) + end + end + end + out.blockEntities = list(level.TileEntities) + return out, nil +end + +return Chunk diff --git a/src/Formats/model/mca/Lz4Block.luau b/src/Formats/model/mca/Lz4Block.luau new file mode 100644 index 0000000..de5d700 --- /dev/null +++ b/src/Formats/model/mca/Lz4Block.luau @@ -0,0 +1,70 @@ +--!strict +-- model/mca/Lz4Block: the lz4-java LZ4BlockOutputStream framing Minecraft (24w04a+) uses for compression type 4 +-- chunks, from lz4-java's LZ4BlockOutputStream source: blocks of "LZ4Block", a token (method 0x10 raw / 0x20 LZ4 | +-- level), compressed and decompressed lengths and an XXH32 checksum (little-endian i32s; not verified), then the +-- block, each block independent; an empty block ends the stream. The blocks decode through codecs/compress/Lz4. +local Lz4 = require("@formats/codecs/compress/Lz4") + +local Lz4Block = {} + +local MAGIC = "LZ4Block" + +-- decode(buf, offset, length, maxBytes) -> buffer | nil, message +function Lz4Block.decode(b: buffer, offset: number, length: number, maxBytes: number): (buffer?, string?) + local p, e = offset, offset + length + local parts, total = {}, 0 + while true do + if p + 21 > e then + if #parts > 0 and p >= e then + break -- some writers stop without the empty end block + end + return nil, "truncated LZ4 block header" + end + if buffer.readstring(b, p, 8) ~= MAGIC then + return nil, "bad LZ4Block magic" + end + local token = buffer.readu8(b, p + 8) + local clen, dlen = buffer.readi32(b, p + 9), buffer.readi32(b, p + 13) + p += 21 + local method = token // 16 * 16 + if clen < 0 or dlen < 0 or p + clen > e then + return nil, "truncated LZ4 block" + end + if dlen == 0 and clen == 0 then + break + end + total += dlen + if total > maxBytes then + return nil, "limit: chunk inflates past maxBytes" + end + if method == 0x10 then + if clen ~= dlen then + return nil, "raw LZ4 block length mismatch" + end + local out = buffer.create(dlen) + buffer.copy(out, 0, b, p, clen) + table.insert(parts, out) + elseif method == 0x20 then + local out, err = Lz4.decompress(b, p, clen, dlen) + if not out then + return nil, "LZ4: " .. tostring(err and err.message) + end + table.insert(parts, out) + else + return nil, "unsupported: LZ4Block method " .. method + end + p += clen + end + if #parts == 1 then + return parts[1], nil + end + local res = buffer.create(total) + local w = 0 + for _, part in parts do + buffer.copy(res, w, part) + w += buffer.len(part) + end + return res, nil +end + +return Lz4Block diff --git a/src/Formats/model/mca/init.luau b/src/Formats/model/mca/init.luau new file mode 100644 index 0000000..c5d1558 --- /dev/null +++ b/src/Formats/model/mca/init.luau @@ -0,0 +1,355 @@ +--!strict +-- model/mca: Minecraft Anvil region files (r...mca: 32 x 32 chunks), read-only. New code, from the Minecraft +-- wiki "Region file format" and "Chunk format" pages. Supports: the location / timestamp header, chunk payloads +-- compressed with gzip, zlib (codecs/compress/Deflate), LZ4 (lz4-java block streams, 24w04a+: model/mca/Lz4Block over +-- codecs/compress/Lz4) or stored, external .mcc chunks through opts.resolve, and every chunk layout: 1.18+ sections, +-- 1.13 - 1.17 palettes (spanning and not) and pre-1.13 numeric ids (model/mca/Chunk). +-- decode -> a Scene (meta.up = "y", one unit = one block) with one Types.Voxels covering the chosen chunks +-- (opts.chunks, opts.area; by default every chunk, between the lowest and highest section holding blocks) with +-- voxels.blocks (exact states, block entities relative to the grid), placed by its node at the world position of its +-- minimum corner. meta.source.chunks lists every chunk read (local and world coordinates, timestamp, compression, +-- DataVersion) with its whole NBT (chunk.nbt; opts.keepNbt = false drops it). Mca.list / Mca.chunk read the header +-- and one chunk's NBT without building voxels. +-- Not supported: writing; custom (127) chunk compression; LZ4 checksums are not verified; entities stored in the +-- separate entities/ region files (1.17+) are another file (load it with Mca.chunk). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Deflate = require("@formats/codecs/compress/Deflate") +local Nbt = require("@formats/codecs/text/Nbt") +local Mc = require("@formats/codecs/model/Minecraft") +local Chunk = require("@formats/model/mca/Chunk") +local Lz4Block = require("@formats/model/mca/Lz4Block") + +-- ------------------------------------------------------------------------------------------------ contract +local Mca = { + name = "mca", + category = "model", + extensions = { "mca", "mcr" }, + mime = { "application/x-minecraft-region" }, + deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/text/Nbt", "codecs/model/Minecraft", "codecs/compress/Lz4" }, + caps = { decode = true, encode = false, voxels = true, blocks = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + chunks: { { number } }?, -- only these chunks: { { x, z } } local coordinates 0 .. 31 (default all) + area: { number }?, -- only blocks inside { minX, minY, minZ, maxX, maxY, maxZ } (world coordinates, inclusive) + maxCells: number?, -- refuse grids with more cells (default 2^25: pick chunks or an area for big regions) + maxBytes: number?, -- refuse a chunk that inflates past this (default 2^26) + keepNbt: boolean?, -- keep each chunk's NBT in meta.source.chunks[i].nbt (default true) + region: { number }?, -- the region's coordinates { x, z } (default: from opts.name "r...mca"), for .mcc files + name: string?, -- the file name (the api fills it in) + resolve: ((string) -> buffer?)?, -- reads a sibling file: external chunks c...mcc +} +export type Entry = { + x: number, -- local chunk coordinates 0 .. 31 + z: number, + sector: number, -- 4 KiB sector of the chunk + sectors: number, + timestamp: number, -- seconds since 1970 +} + +-- ------------------------------------------------------------------------------------------------ constants +local COMPRESSION = { [1] = "gzip", [2] = "zlib", [3] = "none", [4] = "lz4", [127] = "custom" } + +-- ------------------------------------------------------------------------------------------------ sniff +function Mca.sniff(r: Bytes.Reader): number + local n = r.limit - r.base + if n < 8192 then + return 0 + end + local sectors = (n + 4095) // 4096 + local used, b = 0, r.buf + for i = 0, 1023 do + local e = bit32.byteswap(buffer.readu32(b, r.base + i * 4)) + if e ~= 0 then + local off, cnt = e // 256, e % 256 + if off < 2 or cnt == 0 or off + cnt > sectors then + return 0 + end + used += 1 + if used == 1 then + local p = r.base + off * 4096 + if p + 5 > r.limit then + return 0 + end + local c = buffer.readu8(b, p + 4) % 128 + if COMPRESSION[c] == nil then + return 0 + end + end + end + end + return if used > 0 then 0.8 else 0.2 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- list(r) -> { Entry } | nil, Err: the chunks present in the region (location and timestamp tables) +function Mca.list(r: Bytes.Reader): ({ Entry }?, Err.Err?) + local n = r.limit - r.base + if n < 8192 then + return nil, Err.new(Err.TRUNCATED, "region header is 8192 bytes, file has " .. n) + end + local out: { Entry } = {} + for i = 0, 1023 do + local e = bit32.byteswap(buffer.readu32(r.buf, r.base + i * 4)) + if e ~= 0 then + table.insert(out, { + x = i % 32, + z = i // 32, + sector = e // 256, + sectors = e % 256, + timestamp = bit32.byteswap(buffer.readu32(r.buf, r.base + 4096 + i * 4)), + }) + end + end + return out, nil +end + +local function regionCoords(o: DecodeOptions): (number?, number?) + if o.region then + return o.region[1], o.region[2] + end + if o.name then + local x, z = string.match(o.name, "r%.(%-?%d+)%.(%-?%d+)%.mc[ar]$") + if x then + return tonumber(x), tonumber(z) + end + end + return nil, nil +end + +-- payload(r, e, o) -> the chunk's uncompressed NBT bytes, compression name | nil, Err +local function payload(r: Bytes.Reader, e: Entry, o: DecodeOptions): (buffer?, any) + local p = r.base + e.sector * 4096 + if p + 5 > r.limit then + return nil, Err.new(Err.TRUNCATED, string.format("chunk %d,%d starts past the end", e.x, e.z), p - r.base) + end + local len = bit32.byteswap(buffer.readu32(r.buf, p)) + local ctype = buffer.readu8(r.buf, p + 4) + local data: buffer, start: number, size: number = r.buf, p + 5, len - 1 + if ctype >= 128 then + -- stored in c...mcc next to the region (whole file = the compressed payload) + local rx, rz = regionCoords(o) + if not o.resolve or rx == nil then + return nil, Err.new(Err.UNSUPPORTED, string.format("chunk %d,%d is in an external .mcc file (pass opts.resolve and the region coordinates)", e.x, e.z)) + end + local name = string.format("c.%d.%d.mcc", (rx :: number) * 32 + e.x, (rz :: number) * 32 + e.z) + local ext = o.resolve(name) + if type(ext) ~= "buffer" then + return nil, Err.new(Err.IO, "cannot read " .. name) + end + data, start, size = ext, 0, buffer.len(ext) + ctype -= 128 + elseif len < 1 or p + 4 + len > r.limit then + return nil, Err.new(Err.TRUNCATED, string.format("chunk %d,%d runs past the end", e.x, e.z), p - r.base) + end + local comp = COMPRESSION[ctype] + local maxBytes = o.maxBytes or 2 ^ 26 + local out, err + if comp == "gzip" then + out, err = Deflate.gunzip(data, start, size) + elseif comp == "zlib" then + out, err = Deflate.zlib(data, start, size) + elseif comp == "none" then + out = buffer.create(size :: number) + buffer.copy(out, 0, data, start, size) + elseif comp == "lz4" then + local msg + out, msg = Lz4Block.decode(data, start, size :: number, maxBytes) + if not out then + err = Err.from(msg, start - r.base) + end + else + return nil, Err.new(Err.UNSUPPORTED, string.format("chunk %d,%d: compression type %d", e.x, e.z, ctype)) + end + if not out then + return nil, err + end + if buffer.len(out) > maxBytes then + return nil, Err.new(Err.LIMIT, string.format("chunk %d,%d inflates past maxBytes", e.x, e.z)) + end + return out, comp +end + +-- chunk(r, x, z, opts?) -> the chunk's NBT root, compression | nil, Err (nil, nil when the chunk is absent) +function Mca.chunk(r: Bytes.Reader, x: number, z: number, opts: DecodeOptions?): (any, any) + local o: DecodeOptions = opts or {} + if x < 0 or x > 31 or z < 0 or z > 31 or x % 1 ~= 0 or z % 1 ~= 0 then + return nil, Err.new(Err.ARG, "chunk coordinates are 0 .. 31") + end + local entries, lerr = Mca.list(r) + if not entries then + return nil, lerr + end + for _, e in entries do + if e.x == x and e.z == z then + local raw, comp = payload(r, e, o) + if not raw then + return nil, comp + end + local v, info = Nbt.decode(raw, { endian = "big", maxBytes = o.maxBytes }) + if v == nil then + return nil, info + end + return v, comp + end + end + return nil, nil +end + +function Mca.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: DecodeOptions = opts or {} + local entries, lerr = Mca.list(r) + if not entries then + return nil, lerr + end + local want: { [number]: boolean }? = nil + if o.chunks then + local w: { [number]: boolean } = {} + for _, c in o.chunks do + w[(c[1] or 0) + 32 * (c[2] or 0)] = true + end + want = w + end + local area = o.area + if area and #area ~= 6 then + return nil, Err.new(Err.ARG, "area is { minX, minY, minZ, maxX, maxY, maxZ }") + end + local keep = o.keepNbt ~= false + local chunks: { Chunk.Blocks } = {} + local infos = {} + for _, e in entries do + if not want or want[e.x + 32 * e.z] then + local raw, comp = payload(r, e, o) + if not raw then + return nil, comp + end + local v, info = Nbt.decode(raw, { endian = "big", maxBytes = o.maxBytes }) + if v == nil then + return nil, Err.new(info.code, string.format("chunk %d,%d: %s", e.x, e.z, info.message)) + end + local blocks, berr = Chunk.blocks(v) + if not blocks then + return nil, Err.from(string.format("chunk %d,%d: %s", e.x, e.z, tostring(berr))) + end + local inArea = not area or (blocks.x * 16 <= area[4] and blocks.x * 16 + 15 >= area[1] and blocks.z * 16 <= area[6] and blocks.z * 16 + 15 >= area[3]) + if inArea then + table.insert(chunks, blocks) + table.insert(infos, { x = e.x, z = e.z, worldX = blocks.x, worldZ = blocks.z, timestamp = e.timestamp, compression = comp, dataVersion = blocks.dataVersion, nbt = if keep then v else nil }) + end + end + end + -- the bounds: chunks in x / z, sections holding anything but air in y, cut to the area + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for _, c in chunks do + lo[1], hi[1] = math.min(lo[1], c.x * 16), math.max(hi[1], c.x * 16 + 15) + lo[3], hi[3] = math.min(lo[3], c.z * 16), math.max(hi[3], c.z * 16 + 15) + for _, s in c.sections do + local solid = false + for _, st in s.states do + if not Mc.isAir(st) then + solid = true + break + end + end + if solid then + lo[2], hi[2] = math.min(lo[2], s.y * 16), math.max(hi[2], s.y * 16 + 15) + end + end + end + if area then + for k = 1, 3 do + lo[k], hi[k] = math.max(lo[k], area[k]), math.min(hi[k], area[k + 3]) + if area[k] > area[k + 3] then + return nil, Err.new(Err.ARG, "area minimum past its maximum") + end + end + if lo[2] == math.huge then + lo[2], hi[2] = area[2], area[5] + end + end + if lo[2] == math.huge then + lo[2], hi[2] = 0, -1 -- no blocks at all + end + if #chunks == 0 then + lo, hi = { 0, 0, 0 }, { -1, -1, -1 } + end + local sx, sy, sz = math.max(0, hi[1] - lo[1] + 1), math.max(0, hi[2] - lo[2] + 1), math.max(0, hi[3] - lo[3] + 1) + local n = sx * sy * sz + if n > (o.maxCells or 2 ^ 25) then + return nil, Err.new(Err.LIMIT, string.format("%d x %d x %d cells is over maxCells: choose opts.chunks or opts.area", sx, sy, sz)) + end + -- one palette for the grid (air first), each section copied in through a remap table + local states = { "minecraft:air" } + local index: { [string]: number } = { ["minecraft:air"] = 0 } + local grid = buffer.create(n * 2) + local bes, ents = {}, {} + for _, c in chunks do + local cx, cz = c.x * 16 - lo[1], c.z * 16 - lo[3] + for _, s in c.sections do + local cy = s.y * 16 - lo[2] + if cy + 15 >= 0 and cy < sy and cx + 15 >= 0 and cx < sx and cz + 15 >= 0 and cz < sz then + local lut = table.create(#s.states) :: { number } + for i, st in s.states do + local g = index[st] + if g == nil then + table.insert(states, st) + g = #states - 1 + index[st] = g + end + lut[i] = g + end + if #states > 65536 then + return nil, Err.new(Err.LIMIT, "more than 65536 block states") + end + local cells = s.cells + local y0, y1 = math.max(0, -cy), math.min(15, sy - 1 - cy) + local z0, z1 = math.max(0, -cz), math.min(15, sz - 1 - cz) + local x0, x1 = math.max(0, -cx), math.min(15, sx - 1 - cx) + for y = y0, y1 do + for z = z0, z1 do + local src = ((y * 16 + z) * 16 + x0) * 2 + local dst = ((cx + x0) + sx * ((cy + y) + sy * (cz + z))) * 2 + for _ = x0, x1 do + buffer.writeu16(grid, dst, lut[buffer.readu16(cells, src) + 1] or 0) + src += 2 + dst += 2 + end + end + end + end + end + for _, rec in c.blockEntities do + local be = Mc.blockEntity(rec, "flat") + if be then + local px, py, pz = be.pos[1] - lo[1], be.pos[2] - lo[2], be.pos[3] - lo[3] + if px >= 0 and px < sx and py >= 0 and py < sy and pz >= 0 and pz < sz then + be.pos = { px, py, pz } + table.insert(bes, be) + end + end + end + for _, ent in c.entities do + table.insert(ents, ent) + end + end + local v = Mc.voxels(sx, sy, sz, states, grid) + local b = v.blocks :: Types.VoxelBlocks + b.blockEntities = bes + b.entities = ents + local scene = Types.Scene.new() + scene.voxels = { v } + scene.nodes = { { name = o.name, children = {}, voxels = 1, translation = { lo[1], lo[2], lo[3] } } } + scene.roots = { 1 } + scene.meta.up = "y" + scene.meta.unit = 1 + local rx, rz = regionCoords(o) + scene.meta.source = { format = "mca", region = if rx then { rx, rz } else nil, chunks = infos } + return scene, nil +end + +return Mca diff --git a/src/Formats/model/schematic/Common.luau b/src/Formats/model/schematic/Common.luau index ee1002a..3b3fd7b 100644 --- a/src/Formats/model/schematic/Common.luau +++ b/src/Formats/model/schematic/Common.luau @@ -4,6 +4,7 @@ -- converted from / to MCEdit's and Litematica's flat { x, y, z, id, ... } and Sponge v2's { Pos, Id, ... }). local Types = require("@formats/Types") local Nbt = require("@formats/codecs/text/Nbt") +local Mc = require("@formats/codecs/model/Minecraft") local Common = {} @@ -19,13 +20,7 @@ export type Region = { } -- int(v) -> the integer value of an NBT number (byte / short / int / long tag or plain number) | nil -function Common.int(v: any): number? - local n = Nbt.number(v) - if n == nil or n ~= n or n % 1 ~= 0 then - return nil - end - return n -end +Common.int = Mc.int -- dims(a, b, c, max) -> sx, sy, sz | nil, message: positive sizes whose product stays under max cells function Common.dims(a: any, b: any, c: any, max: number): (number?, any, number?) @@ -43,80 +38,11 @@ function Common.dims(a: any, b: any, c: any, max: number): (number?, any, number end -- ints(v) -> the numbers of an intArray tag or a list of numbers | nil -function Common.ints(v: any): { number }? - if Nbt.isTag(v) and v.type == "intArray" then - return v.value - elseif type(v) == "table" and not Nbt.isTag(v) and (v :: any)[1] ~= nil then - local out: { number } = {} - for i, x in v :: { any } do - out[i] = Nbt.number(x) or 0 - end - return out - end - return nil -end +Common.ints = Mc.ints -local function rest(c: any, skip: { [string]: boolean }): { [string]: any } - local out, keys = {}, {} - for _, k in Types.keys(c) do - if not skip[k] then - out[k] = c[k] - table.insert(keys, k) - end - end - return Types.object(out, keys) -end - -local FLAT_SKIP = { x = true, y = true, z = true, id = true } -local POS_SKIP = { Pos = true, Id = true } - --- blockEntity(c, style) -> the common shape of one record: style "flat" (MCEdit, Litematica), "pos" (Sponge v1 / v2), --- "data" (Sponge v3) -function Common.blockEntity(c: any, style: string): any - if type(c) ~= "table" or Nbt.isTag(c) then - return nil - end - if style == "flat" then - return { pos = { Common.int(c.x) or 0, Common.int(c.y) or 0, Common.int(c.z) or 0 }, id = if type(c.id) == "string" then c.id else nil, data = rest(c, FLAT_SKIP) } - end - local p = Common.ints(c.Pos) or { 0, 0, 0 } - local data = if style == "data" then (if type(c.Data) == "table" then c.Data else Types.object()) else rest(c, POS_SKIP) - return { pos = { p[1] or 0, p[2] or 0, p[3] or 0 }, id = if type(c.Id) == "string" then c.Id else nil, data = data } -end - --- flatBlockEntity(be, style) -> the record in a flavour's shape (the inverse of blockEntity) -function Common.flatBlockEntity(be: any, style: string): any - local o = Types.object() - local data = if type(be.data) == "table" then be.data else Types.object() - if style == "flat" then - Types.set(o, "x", be.pos[1]) - Types.set(o, "y", be.pos[2]) - Types.set(o, "z", be.pos[3]) - if be.id then - Types.set(o, "id", be.id) - end - for _, k in Types.keys(data) do - if not FLAT_SKIP[k] then - Types.set(o, k, data[k]) - end - end - return o - end - Types.set(o, "Pos", Nbt.intArray({ be.pos[1], be.pos[2], be.pos[3] })) - if be.id then - Types.set(o, "Id", be.id) - end - if style == "data" then - Types.set(o, "Data", data) - else - for _, k in Types.keys(data) do - if not POS_SKIP[k] then - Types.set(o, k, data[k]) - end - end - end - return o -end +-- blockEntity(c, style) / flatBlockEntity(be, style): codecs/model/Minecraft's (shared with model/mca) +Common.blockEntity = Mc.blockEntity +Common.flatBlockEntity = Mc.flatBlockEntity -- list(v) -> v when it is an NBT list (array), else an empty list function Common.list(v: any): { any } diff --git a/tests/model/mca.luau b/tests/model/mca.luau new file mode 100644 index 0000000..30ef1c7 --- /dev/null +++ b/tests/model/mca.luau @@ -0,0 +1,148 @@ +-- model/mca tests: region files with 1.18+ chunks (each compression: zlib, gzip, stored, LZ4 block streams), +-- 1.16 / 1.13 / 1.12 chunks (palettes non-spanning and spanning, numeric ids with Add nibbles) and an external .mcc +-- chunk: every cell of the assembled grid against the fixture (a CRC of the cell texts), placement, the chunk list, +-- block entities, opts.chunks / opts.area / maxCells, Mca.list / Mca.chunk, detection, errors and the fuzz pass. +-- Fixtures: tools/fixtures/mca.py. +local T = require("@tests/T") +local F = require("@formats") +local Mca = require("@formats/model/mca") +local Mc = require("@formats/codecs/model/Minecraft") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/mca") + +local t = T.suite("mca") + +t:eq(Mca.name, "mca", "name") +t:check(Mca.caps.decode and not Mca.caps.encode, "caps: read-only") + +local function reader(s: string): Bytes.Reader + return Bytes.reader(buffer.fromstring(s)) +end + +-- the fixture's cell texts: the state, or "legacy::" inside chunks without a DataVersion +local function cellText(scene: Types.Scene): string + local v = (scene.voxels :: { Types.Voxels })[1] + local b = v.blocks :: Types.VoxelBlocks + local o = scene.nodes[1].translation :: { number } + local legacyChunk: { [string]: boolean } = {} + for _, c in scene.meta.source.chunks do + if c.dataVersion == nil then + legacyChunk[c.worldX .. "," .. c.worldZ] = true + end + end + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + local parts = table.create(sx * sy * sz) + local i = 0 + for z = 0, sz - 1 do + for y = 0, sy - 1 do + for x = 0, sx - 1 do + local st = b.palette[buffer.readu16(b.data, i * 2) + 1] + local wx, wz = o[1] + x, o[3] + z + if legacyChunk[(wx // 16) .. "," .. (wz // 16)] then + local id, d = Mc.legacyId(st) + st = "legacy:" .. tostring(id) .. ":" .. tostring(d) + end + i += 1 + parts[i] = st + end + end + end + return table.concat(parts, "\n") +end + +for _, c in Fx.regions do + local opts = { name = c.name, resolve = function(name: string): buffer? + local f = c.files and c.files[name] + return if f then buffer.fromstring(f) else nil + end } + local scene, err = Mca.decode(reader(c.data), opts) + t:check(scene ~= nil, c.name .. ": " .. tostring(err)) + local s = scene :: Types.Scene + local v = (s.voxels :: { Types.Voxels })[1] + t:eq(table.concat(v.size, ","), table.concat(c.size, ","), c.name .. ": size") + t:eq(table.concat(s.nodes[1].translation :: { number }, ","), table.concat(c.min, ","), c.name .. ": minimum corner") + t:eq(Crc32.of(buffer.fromstring(cellText(s))), c.crc, c.name .. ": every cell") + t:eq(#s.meta.source.chunks, #c.chunks, c.name .. ": chunks") + for i, want in c.chunks do + local got = s.meta.source.chunks[i] + t:check(got.x == want.x and got.z == want.z, c.name .. ": chunk " .. i .. " position") + t:eq(got.timestamp, want.timestamp, c.name .. ": chunk " .. i .. " timestamp") + t:eq(got.compression, want.compression, c.name .. ": chunk " .. i .. " compression") + t:eq(got.dataVersion, want.dataVersion, c.name .. ": chunk " .. i .. " DataVersion") + t:check(got.nbt ~= nil, c.name .. ": chunk " .. i .. " NBT kept") + end + t:eq(#((v.blocks :: Types.VoxelBlocks).blockEntities :: { any }), c.blockEntities, c.name .. ": block entities") + -- colours follow the blocks + local air = 0 + for i = 0, buffer.len(v.data) - 1 do + if buffer.readu8(v.data, i) == 0 then + air += 1 + end + end + t:check(air > 0 and air < buffer.len(v.data), c.name .. ": colour grid") +end + +-- details on the 1.18+ region +do + local c = Fx.regions[1] + local list = assert(Mca.list(reader(c.data))) + t:eq(#list, 4, "list") + local nbt, comp = Mca.chunk(reader(c.data), 3, 2) + t:check(nbt and nbt.xPos == 3 and nbt.Status == "minecraft:full", "Mca.chunk") + t:eq(comp, "lz4", "Mca.chunk compression") + t:eq(Mca.chunk(reader(c.data), 9, 9), nil, "absent chunk") + -- only some chunks / an area + local one = assert(Mca.decode(reader(c.data), { chunks = { { 1, 0 } }, keepNbt = false })) + t:eq(table.concat((one.voxels :: { Types.Voxels })[1].size, ","), "16,48,16", "opts.chunks") + t:eq(one.meta.source.chunks[1].nbt, nil, "keepNbt = false") + local part = assert(Mca.decode(reader(c.data), { area = { 4, -64, 4, 19, -60, 9 } })) + local pv = (part.voxels :: { Types.Voxels })[1] + t:eq(table.concat(pv.size, ","), "16,5,6", "opts.area size") + t:eq(table.concat(part.nodes[1].translation :: { number }, ","), "4,-64,4", "opts.area corner") + -- the area's cells equal the same cells of the whole grid + local whole = assert(Mca.decode(reader(c.data))) + local wv = (whole.voxels :: { Types.Voxels })[1] + local wo = whole.nodes[1].translation :: { number } + local bad = 0 + for z = 0, 5 do + for y = 0, 4 do + for x = 0, 15 do + local a = pv.blocks.palette[buffer.readu16(pv.blocks.data, (x + 16 * (y + 5 * z)) * 2) + 1] + local gx, gy, gz = 4 + x - wo[1], -64 + y - wo[2], 4 + z - wo[3] + local w = wv.blocks.palette[buffer.readu16(wv.blocks.data, (gx + wv.size[1] * (gy + wv.size[2] * gz)) * 2) + 1] + if a ~= w then + bad += 1 + end + end + end + end + t:eq(bad, 0, "area cells") + local _, e = Mca.decode(reader(c.data), { maxCells = 1000 }) + t:check(e and e.code == Err.LIMIT, "maxCells") + t:eq(F.detect(c.data), "mca", "F.detect") + local viaApi = F.load(c.data, { name = "r.0.0.mca" }) + t:check(viaApi and viaApi.kind == "scene", "F.load") + t:check(F.save(viaApi, nil, { format = "schem" }) ~= nil, "region -> .schem") +end + +-- errors +do + local ext = Fx.regions[3] + local _, e1 = Mca.decode(reader(ext.data)) + t:check(e1 and e1.code == Err.UNSUPPORTED, "external chunk without resolve") + local _, e2 = Mca.decode(reader(string.sub(Fx.regions[1].data, 1, 9000))) + t:check(e2 and e2.code == Err.TRUNCATED, "truncated region") + local _, e3 = Mca.decode(reader(string.rep("\0", 100))) + t:check(e3 and e3.code == Err.TRUNCATED, "short header") + local _, e4 = Mca.chunk(reader(Fx.regions[1].data), 40, 0) + t:check(e4 and e4.code == Err.ARG, "bad chunk coordinates") +end + +local samples = { Fx.regions[2].data, string.sub(Fx.regions[1].data, 1, 20000) } +t:fuzz("decode", function(b: buffer) + return Mca.decode(Bytes.reader(b)) +end, samples, { keepHeader = 0 }) +t:done() diff --git a/tools/fixtures/mca.py b/tools/fixtures/mca.py new file mode 100644 index 0000000..ff2bbbe --- /dev/null +++ b/tools/fixtures/mca.py @@ -0,0 +1,218 @@ +# model/mca fixtures: Anvil region files assembled here by the Minecraft wiki's "Region file format" / "Chunk format" +# pages (nbtlib writes the chunk NBT; zlib, gzip, python-lz4 + xxhash for lz4-java's LZ4Block stream compress it): +# 1.18+ chunks (sections with palettes, non-spanning packed longs, single-state sections without data, block +# entities), 1.16 and 1.13 chunks (Level.Sections, non-spanning / spanning BlockStates), 1.12 chunks (Blocks / Add / +# Data nibbles), every compression type, and an external .mcc chunk. +# tests/gen/mca.luau { regions = { { name, data, files? = { [name] = bytes }, min = {x,y,z}, size = {x,y,z}, +# crc (CRC-32 of the expected cell texts joined by "\n" in Voxels order: the state, or +# "legacy::" for pre-1.13 cells), chunks = { { x, z, timestamp, compression, +# dataVersion } }, blockEntities } } } +import pickle, subprocess + +BODY = r''' +import nbtlib, pickle, random, struct, sys, io, gzip, zlib +import lz4.block, xxhash +from nbtlib import Byte, Short, Int, Long, String, List, Compound, ByteArray, IntArray, LongArray +import numpy as np +rng = random.Random(9) +MODERN = [("minecraft:stone", {}), ("minecraft:dirt", {}), ("minecraft:grass_block", {"snowy": "false"}), + ("minecraft:oak_log", {"axis": "y"}), ("minecraft:water", {"level": "0"}), ("minecraft:red_wool", {}), + ("minecraft:deepslate", {"axis": "y"}), ("minecraft:oak_stairs", {"facing": "east", "half": "bottom", "shape": "straight", "waterlogged": "false"})] +MODERN += [("minecraft:%s_concrete" % c, {}) for c in ["white", "orange", "magenta", "lime", "pink", "gray", "cyan", "blue", "green", "black"]] +def sname(name, props): + return name + ("[" + ",".join("%s=%s" % kv for kv in props.items()) + "]" if props else "") +def signed(v): + return v - (1 << 64) if v >= (1 << 63) else v +def pack(idx, bits, spanning): + if spanning: + total = (len(idx) * bits + 63) // 64 + acc = 0 + for i, v in enumerate(idx): + acc |= v << (i * bits) + return [signed((acc >> (64 * k)) & ((1 << 64) - 1)) for k in range(total)] + per = 64 // bits + out = [] + for k in range(0, len(idx), per): + acc = 0 + for j, v in enumerate(idx[k:k + per]): + acc |= v << (j * bits) + out.append(signed(acc)) + return out +def bits_for(n, minimum): + b = minimum + while (1 << b) < n: b += 1 + return b +def section_states(fill): + # fill: "air", "solid", "mixed": a palette and 4096 indices (x + 16 z + 256 y) + if fill == "air": + return [("minecraft:air", {})], [0] * 4096 + pool = MODERN[:2] if fill == "solid" else [("minecraft:air", {})] + rng.sample(MODERN, rng.choice([3, 9, 17])) + pal = list(pool) + idx = [rng.randrange(len(pal)) for _ in range(4096)] + used = sorted(set(idx)) + remap = {o: i for i, o in enumerate(used)} + return [pal[u] for u in used], [remap[i] for i in idx] +def pal_nbt(pal): + out = [] + for name, props in pal: + c = Compound({"Name": String(name)}) + if props: + c["Properties"] = Compound({k: String(v) for k, v in props.items()}) + out.append(c) + return List[Compound](out) +cells = {} # world (x, y, z) -> expected text +def record(cx, cz, sy, pal, idx, legacy=None): + for i in range(4096): + x, z, y = i % 16, (i // 16) % 16, i // 256 + key = (cx * 16 + x, sy * 16 + y, cz * 16 + z) + if legacy is not None: + cells[key] = "legacy:%d:%d" % legacy[i] + else: + name, props = pal[idx[i]] + cells[key] = sname(name, props) +def modern_chunk(cx, cz, fills): + secs = [] + for sy in range(-4, 20): + fill = fills.get(sy, "air") + pal, idx = section_states(fill) + s = Compound({"Y": Byte(sy), "block_states": Compound({"palette": pal_nbt(pal)}), + "biomes": Compound({"palette": List[String]([String("minecraft:plains")])})}) + if len(pal) > 1: + s["block_states"]["data"] = LongArray(pack(idx, bits_for(len(pal), 4), False)) + secs.append(s) + if fill != "air": + record(cx, cz, sy, pal, idx) + root = Compound({"DataVersion": Int(3953), "xPos": Int(cx), "yPos": Int(-4), "zPos": Int(cz), + "Status": String("minecraft:full"), "LastUpdate": Long(12345), "sections": List[Compound](secs), + "block_entities": List[Compound]([Compound({"id": String("minecraft:chest"), "x": Int(cx * 16 + 1), + "y": Int(-60), "z": Int(cz * 16 + 2), "keepPacked": Byte(0), "Items": List[Compound]([])})]), + "Heightmaps": Compound({})}) + return root +def old_chunk(cx, cz, dv, spanning, fills): + secs = [] + for sy, fill in fills.items(): + pal, idx = section_states(fill) + bits = bits_for(len(pal), 4) + secs.append(Compound({"Y": Byte(sy), "Palette": pal_nbt(pal), "BlockStates": LongArray(pack(idx, bits, spanning)), + "BlockLight": ByteArray([0] * 2048), "SkyLight": ByteArray([0] * 2048)})) + record(cx, cz, sy, pal, idx) + return Compound({"DataVersion": Int(dv), "Level": Compound({"xPos": Int(cx), "zPos": Int(cz), "Status": String("full"), + "Sections": List[Compound](secs), "TileEntities": List[Compound]([]), "Entities": List[Compound]([])})}) +def legacy_chunk(cx, cz, fills, with_add): + secs = [] + ids = [(1, 0), (2, 0), (3, 0), (35, 14), (5, 2), (17, 5), (53, 3), (0, 0), (9, 0), (251, 4)] + if with_add: + ids += [(300, 1), (1000, 7)] + for sy in fills: + cellsl = [rng.choice(ids) for _ in range(4096)] + blocks = bytes(c[0] & 0xff for c in cellsl) + data = bytearray(2048); add = bytearray(2048) + for i, (bid, d) in enumerate(cellsl): + sh = 0 if i % 2 == 0 else 4 # Minecraft nibble arrays: low nibble first + data[i >> 1] |= d << sh + add[i >> 1] |= (bid >> 8) << sh + s = Compound({"Y": Byte(sy), "Blocks": ByteArray(np.frombuffer(blocks, dtype=np.int8)), + "Data": ByteArray(np.frombuffer(bytes(data), dtype=np.int8)), + "BlockLight": ByteArray([0] * 2048), "SkyLight": ByteArray([0] * 2048)}) + if with_add: + s["Add"] = ByteArray(np.frombuffer(bytes(add), dtype=np.int8)) + secs.append(s) + record(cx, cz, sy, None, None, legacy=cellsl) + return Compound({"Level": Compound({"xPos": Int(cx), "zPos": Int(cz), "Sections": List[Compound](secs), + "TileEntities": List[Compound]([Compound({"id": String("Chest"), "x": Int(cx * 16), "y": Int(fills[0] * 16), "z": Int(cz * 16)})]), + "Entities": List[Compound]([Compound({"id": String("Pig"), "Pos": List[nbtlib.Double]([nbtlib.Double(0.5), nbtlib.Double(1.0), nbtlib.Double(0.5)])})])})}) +def nbt_bytes(root): + f = io.BytesIO() + f.write(b"\x0a"); nbtlib.tag.write_string("", f, "big"); root.write(f, byteorder="big") + return f.getvalue() +def lz4block(raw): + out = bytearray() + for k in range(0, len(raw), 65536): + blk = raw[k:k + 65536] + comp = lz4.block.compress(blk, store_size=False) + chk = xxhash.xxh32(blk, seed=0x9747b28c).intdigest() & 0x0fffffff + out += b"LZ4Block" + bytes([0x26]) + struct.pack(" file bytes, external files + header = bytearray(8192) + body = bytearray() + files = {} + sector = 2 + for lx, lz, root, kind, ext in chunks: + payload = compress(nbt_bytes(root), kind) + ctype = CTYPE[kind] + if ext: + files[ext] = payload + payload = b"" + ctype |= 0x80 + blob = struct.pack(">IB", len(payload) + 1, ctype) + payload + blob += b"\0" * ((-len(blob)) % 4096) + n = len(blob) // 4096 + i = lx + 32 * lz + struct.pack_into(">I", header, i * 4, (sector << 8) | n) + struct.pack_into(">I", header, 4096 + i * 4, 1700000000 + i) + body += blob + sector += n + return bytes(header + body), files +def expected(name, data, files, chunks, nbes, dvs): + xs = [k[0] for k in cells]; ys = [k[1] for k in cells]; zs = [k[2] for k in cells] + lo = (min(xs), min(ys), min(zs)); hi = (max(xs), max(ys), max(zs)) + # x / z cover whole chunks; y the sections holding blocks + lo = (min(c[2]["cx"] for c in chunks) * 16, lo[1], min(c[2]["cz"] for c in chunks) * 16) + hi = (max(c[2]["cx"] for c in chunks) * 16 + 15, hi[1], max(c[2]["cz"] for c in chunks) * 16 + 15) + size = [hi[0] - lo[0] + 1, hi[1] - lo[1] + 1, hi[2] - lo[2] + 1] + out = [] + for z in range(lo[2], hi[2] + 1): + for y in range(lo[1], hi[1] + 1): + for x in range(lo[0], hi[0] + 1): + out.append(cells.get((x, y, z), "minecraft:air")) + text = "\n".join(out).encode() + return {"name": name, "data": data, "files": files, "min": list(lo), "size": size, "crc": zlib.crc32(text), + "chunks": [{"x": c[0], "z": c[1], "timestamp": 1700000000 + c[0] + 32 * c[1], "compression": c[3], + "dataVersion": dvs[k]} for k, c in enumerate(chunks)], "blockEntities": nbes} +regions = [] +# 1. 1.18+ chunks, one per compression type +cells.clear() +spec = [(0, 0, "zlib"), (1, 0, "gzip"), (0, 1, "none"), (3, 2, "lz4")] +chunks = [] +for lx, lz, kind in spec: + root = modern_chunk(lx, lz, {-4: "solid", -3: "mixed", -2: "mixed"}) + chunks.append((lx, lz, {"root": root, "cx": lx, "cz": lz}, kind, None)) +data, files = region([(c[0], c[1], c[2]["root"], c[3], c[4]) for c in chunks]) +regions.append(expected("modern", data, files, chunks, 4, [3953] * 4)) +# 2. older layouts: 1.12 (with Add), 1.13 (spanning), 1.16 (not spanning) +cells.clear() +chunks = [(0, 0, {"root": legacy_chunk(0, 0, [0, 1], True), "cx": 0, "cz": 0}, "zlib", None), + (1, 0, {"root": old_chunk(1, 0, 1631, True, {0: "mixed", 1: "mixed"}), "cx": 1, "cz": 0}, "zlib", None), + (2, 0, {"root": old_chunk(2, 0, 2586, False, {0: "mixed", 1: "solid"}), "cx": 2, "cz": 0}, "gzip", None)] +data, files = region([(c[0], c[1], c[2]["root"], c[3], c[4]) for c in chunks]) +regions.append(expected("old", data, files, chunks, 1, [0, 1631, 2586])) +# 3. an external chunk (c...mcc) in region r.-1.2: local (3, 4) = world chunk (-29, 68) +cells.clear() +chunks = [(3, 4, {"root": modern_chunk(-29, 68, {0: "mixed"}), "cx": -29, "cz": 68}, "zlib", "c.-29.68.mcc")] +data, files = region([(c[0], c[1], c[2]["root"], c[3], c[4]) for c in chunks]) +regions.append(expected("r.-1.2.mca", data, files, chunks, 0, [3953])) # its chest (y -60) is below the grid +sys.stdout.buffer.write(pickle.dumps({"regions": regions}, protocol=4)) +''' + + +def generate(ctx): + try: + out = pickle.loads(ctx.python(["nbtlib", "numpy", "lz4", "xxhash"], BODY)) + except subprocess.CalledProcessError as e: + raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:]) + for r in out["regions"]: + if not r["files"]: + del r["files"] + for c in r["chunks"]: + if not c["dataVersion"]: + del c["dataVersion"] + ctx.emit("mca", out) From f86e12f051c5edb9185126288515c67020daba35 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:52:15 -0500 Subject: [PATCH 6/7] ws-voxel: model/qb (Qubicle Binary read + write: RGBA / BGRA, z orientation, RLE, visibility masks; exact colours in Voxels.colors) --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/model/qb/init.luau | 401 +++++++++++++++++++++++++++++++++ tests/model/qb.luau | 130 +++++++++++ tools/fixtures/_qb_encode.luau | 34 +++ tools/fixtures/qb.py | 156 +++++++++++++ 6 files changed, 734 insertions(+) create mode 100644 src/Formats/model/qb/init.luau create mode 100644 tests/model/qb.luau create mode 100644 tools/fixtures/_qb_encode.luau create mode 100644 tools/fixtures/qb.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 702f9a2..43bbcdf 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -42,6 +42,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | | model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` | +| model | qb | .qb | yes | yes | voxels: true, truecolor: true | `tests/model/qb.luau` | | model | rbxm | .rbxm .rbxl | yes | yes | tree: true, compression: "none", "lz4", "zstd" | `tests/model/rbxm.luau` | | model | rbxmx | .rbxmx .rbxlx | yes | yes | tree: true | `tests/model/rbxmx.luau` | | model | robloxmesh | .mesh | yes | yes | skinning: true, lods: true, versions: "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" | `tests/model/robloxmesh.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index ac05da1..8369b75 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -458,6 +458,18 @@ local list: { Entry } = { return require("@formats/model/ply") end, }, + { + name = "qb", + category = "model", + path = "model/qb", + extensions = { "qb" }, + mime = { "model/x-qubicle" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, truecolor = true }, + load = function() + return require("@formats/model/qb") + end, + }, { name = "rbxm", category = "model", diff --git a/src/Formats/model/qb/init.luau b/src/Formats/model/qb/init.luau new file mode 100644 index 0000000..2c8ce33 --- /dev/null +++ b/src/Formats/model/qb/init.luau @@ -0,0 +1,401 @@ +--!strict +-- model/qb: Qubicle Binary (.qb, Qubicle 1.x "Qubicle Binary" exchange format), read and write. New code, from the +-- format description in the Qubicle documentation (minddesk.com "Qubicle Binary"): version 1.1.0.0, RGBA or BGRA +-- colours, left- or right-handed z axis, uncompressed or run-length compressed matrices (CODEFLAG 2 / NEXTSLICEFLAG 6 +-- per z slice), the visibility mask encoding in the alpha byte, named matrices with a position. +-- decode -> a Scene (meta.up = "y"): one Types.Voxels per matrix with voxels.colors (each cell's exact colour as +-- r, g, b, a bytes; a = the visibility mask when the file encodes one, 0 = empty) and data / palette as an indexed view +-- (up to 255 colours exact, more mapped to the nearest of the 255 most used); a node per matrix with its name and +-- position. Left-handed files are mirrored on z into the scene's right-handed axes (and back on write). +-- encode <- a Scene with voxels or one Types.Voxels: voxels.colors when present (exact), else palette colours; +-- options default to the source file's settings. +-- Not supported: the Qubicle Exchange (.qbt / .qbcl) formats. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") + +-- ------------------------------------------------------------------------------------------------ contract +local Qb = { + name = "qb", + category = "model", + extensions = { "qb" }, + mime = { "model/x-qubicle" }, + deps = { "core/Err", "core/Bytes", "Types" }, + caps = { decode = true, encode = true, voxels = true, truecolor = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + maxCells: number?, -- refuse files whose matrices hold more cells in total (default 2^27) +} +export type EncodeOptions = { + compressed: boolean?, -- run-length compress the matrices (default: the source's, else true) + colorFormat: ("rgba" | "bgra")?, -- default: the source's, else "rgba" + rightHanded: boolean?, -- the z axis orientation (default: the source's, else true) + visibilityMask: boolean?, -- encode the visible sides in the alpha byte (default: the source's, else false) +} + +-- ------------------------------------------------------------------------------------------------ constants +local CODEFLAG, NEXTSLICEFLAG = 2, 6 +-- visibility mask bits (alpha): 1 = filled, then the sides that are not hidden by a neighbour +local LEFT, RIGHT, TOP, BOTTOM, FRONT, BACK = 2, 4, 8, 16, 32, 64 + +-- ------------------------------------------------------------------------------------------------ sniff +function Qb.sniff(r: Bytes.Reader): number + if r:remaining() < 24 or r:peek(4) ~= "\1\1\0\0" then + return 0 + end + local b, p = r.buf, r.pos + local fmt, z, comp, mask = buffer.readu32(b, p + 4), buffer.readu32(b, p + 8), buffer.readu32(b, p + 12), buffer.readu32(b, p + 16) + if fmt > 1 or z > 1 or comp > 1 or mask > 1 then + return 0 + end + return 0.9 +end + +-- ------------------------------------------------------------------------------------------------ decode +-- the indexed view of a true-colour grid: exact for up to 255 colours, else the 255 most used and the nearest of them +local function indexed(v: Types.Voxels, colors: buffer, n: number) + local count: { [number]: number } = {} + for i = 0, n - 1 do + local c = buffer.readu32(colors, i * 4) + if c >= 0x1000000 then -- alpha > 0: filled + local rgb = c % 0x1000000 + local k = count[rgb] + if k == nil then + count[rgb] = 1 + else + count[rgb] = k + 1 + end + end + end + local order = {} + for rgb in count do + table.insert(order, rgb) + end + table.sort(order, function(a: number, b: number): boolean + if count[a] ~= count[b] then + return count[a] > count[b] + end + return a < b + end) + local slot: { [number]: number } = {} + for i = 1, math.min(255, #order) do + local rgb = order[i] + slot[rgb] = i + v.palette[i] = { rgb % 256, (rgb // 256) % 256, rgb // 65536, 255 } + end + for i = 256, #order do + local rgb = order[i] + local r, g, b = rgb % 256, (rgb // 256) % 256, rgb // 65536 + local best, bd = 1, math.huge + for k = 1, 255 do + local p = v.palette[k] + local d = (p[1] - r) ^ 2 + (p[2] - g) ^ 2 + (p[3] - b) ^ 2 + if d < bd then + best, bd = k, d + end + end + slot[rgb] = best + end + for i = 0, n - 1 do + local c = buffer.readu32(colors, i * 4) + buffer.writeu8(v.data, i, if c >= 0x1000000 then slot[c % 0x1000000] else 0) + end +end + +function Qb.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local o: DecodeOptions = opts or {} + local maxCells = o.maxCells or 2 ^ 27 + local ver = r:string(4) + local fmt, zAxis, compressed, mask, count = r:u32le(), r:u32le(), r:u32le(), r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if ver ~= "\1\1\0\0" then + return nil, Err.new(Err.CORRUPT, "not a Qubicle Binary file (version 1.1.0.0)", 0) + end + if fmt > 1 or zAxis > 1 or compressed > 1 or mask > 1 then + return nil, Err.new(Err.CORRUPT, "bad header flags", 4) + end + if count > r:remaining() // 25 then + return nil, Err.new(Err.TRUNCATED, count .. " matrices cannot fit", 20) + end + local scene = Types.Scene.new() + local grids: { Types.Voxels } = {} + scene.voxels = grids + local total = 0 + local bgra = fmt == 1 + for m = 1, count do + local at = r:tell() + local nameLen = r:u8() + local name = r:string(nameLen) + local sx, sy, sz = r:u32le(), r:u32le(), r:u32le() + local px, py, pz = r:i32le(), r:i32le(), r:i32le() + if r.err then + return nil, r.err + end + if sx * sy * sz + total > maxCells then + return nil, Err.new(Err.LIMIT, string.format("matrix %d: %d x %d x %d cells is over maxCells", m, sx, sy, sz), at) + end + local n = sx * sy * sz + total += n + local colors = buffer.create(n * 4) + local b = r.buf + local function put(x: number, y: number, z: number, c: number) + if bgra then -- b, g, r, a -> r, g, b, a + c = (c // 65536) % 256 + (c // 256) % 256 * 256 + c % 256 * 65536 + (c // 16777216) * 16777216 + end + if c < 0x1000000 then + c = 0 -- alpha 0: empty + end + local zz = if zAxis == 0 then sz - 1 - z else z + buffer.writeu32(colors, (x + sx * (y + sy * zz)) * 4, c) + end + if compressed == 0 then + if not r:need(n * 4) then + return nil, r.err + end + local p = r.pos + for z = 0, sz - 1 do + for y = 0, sy - 1 do + for x = 0, sx - 1 do + put(x, y, z, buffer.readu32(b, p)) + p += 4 + end + end + end + r.pos = p + else + local slice = sx * sy + for z = 0, sz - 1 do + local index = 0 + while true do + local d = r:u32le() + if r.err then + return nil, r.err + end + if d == NEXTSLICEFLAG then + break + elseif d == CODEFLAG then + local run, c = r:u32le(), r:u32le() + if r.err then + return nil, r.err + end + if index + run > slice then + return nil, Err.new(Err.CORRUPT, string.format("matrix %d: run past the slice", m), r:tell() - 8) + end + for _ = 1, run do + put(index % sx, index // sx, z, c) + index += 1 + end + else + if index >= slice then + return nil, Err.new(Err.CORRUPT, string.format("matrix %d: slice %d overflows", m, z), r:tell() - 4) + end + put(index % sx, index // sx, z, d) + index += 1 + end + end + end + end + local v = Types.Voxels.new(sx, sy, sz) + v.name = name + v.colors = colors + indexed(v, colors, n) + table.insert(grids, v) + local tz = if zAxis == 0 then 0 - (pz + sz) else pz + table.insert(scene.nodes, { name = name, children = {}, voxels = m, translation = { px, py, tz } }) + table.insert(scene.roots, #scene.nodes) + end + scene.meta.up = "y" + scene.meta.source = { + format = "qb", + colorFormat = if bgra then "bgra" else "rgba", + rightHanded = zAxis == 1, + compressed = compressed == 1, + visibilityMask = mask == 1, + } + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ encode +local function cellColor(v: Types.Voxels, i: number): number + if v.colors then + return buffer.readu32(v.colors, i * 4) + end + local idx = buffer.readu8(v.data, i) + if idx == 0 then + return 0 + end + local p = v.palette[idx] or { 0, 0, 0, 255 } + return p[1] + p[2] * 256 + p[3] * 65536 + 255 * 16777216 +end + +function Qb.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: EncodeOptions = opts or {} + local grids: { { v: Types.Voxels, name: string, pos: { number } } } = {} + local function add(v: any, name: string?, pos: { number }): string? + if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then + return "expected Types.Voxels grids" + end + local n = v.size[1] * v.size[2] * v.size[3] + if buffer.len(v.data) < n or (v.colors and buffer.len(v.colors) < n * 4) then + return "voxel data shorter than its size" + end + local nm = name or v.name or ("matrix" .. (#grids + 1)) + if #nm > 255 then + return "matrix name longer than 255 bytes" + end + table.insert(grids, { v = v, name = nm, pos = pos }) + return nil + end + local src = if type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" and value.meta.source.format == "qb" then value.meta.source else nil + if type(value) == "table" and value.kind == "voxels" then + local e = add(value, nil, { 0, 0, 0 }) + if e then + return nil, Err.new(Err.ARG, e) + end + elseif type(value) == "table" and value.kind == "scene" and type(value.voxels) == "table" then + local used: { [number]: boolean } = {} + local function walk(i: number, base: { number }, depth: number): string? + local node = value.nodes[i] + if type(node) ~= "table" or depth > 64 then + return nil + end + local t = node.translation or { 0, 0, 0 } + local p = { base[1] + (t[1] or 0), base[2] + (t[2] or 0), base[3] + (t[3] or 0) } + if node.voxels and value.voxels[node.voxels] then + used[node.voxels] = true + local e = add(value.voxels[node.voxels], node.name, p) + if e then + return e + end + end + for _, c in node.children or {} do + local e = walk(c, p, depth + 1) + if e then + return e + end + end + return nil + end + for _, root in value.roots or {} do + local e = walk(root, { 0, 0, 0 }, 0) + if e then + return nil, Err.new(Err.ARG, e) + end + end + for i, v in value.voxels do + if not used[i] then + local e = add(v, nil, { 0, 0, 0 }) + if e then + return nil, Err.new(Err.ARG, e) + end + end + end + else + return nil, Err.new(Err.ARG, "expected a Scene with voxels or a Types.Voxels") + end + local function pick(opt: any, key: string, default: any): any + if opt ~= nil then + return opt + elseif src and src[key] ~= nil then + return src[key] + end + return default + end + local compressed = pick(o.compressed, "compressed", true) + local bgra = pick(o.colorFormat, "colorFormat", "rgba") == "bgra" + local right = pick(o.rightHanded, "rightHanded", true) + local mask = pick(o.visibilityMask, "visibilityMask", false) + local keepMask = mask and src ~= nil and src.visibilityMask == true -- the source's alpha bytes already are masks + local w = Bytes.writer(1024) + w:string("\1\1\0\0") + w:u32le(if bgra then 1 else 0) + w:u32le(if right then 1 else 0) + w:u32le(if compressed then 1 else 0) + w:u32le(if mask then 1 else 0) + w:u32le(#grids) + for _, g in grids do + local v = g.v + local sx, sy, sz = v.size[1], v.size[2], v.size[3] + w:u8(#g.name) + w:string(g.name) + w:u32le(sx) + w:u32le(sy) + w:u32le(sz) + local px, py, pz = math.floor(g.pos[1] + 0.5), math.floor(g.pos[2] + 0.5), math.floor(g.pos[3] + 0.5) + w:u32le(px % 4294967296) + w:u32le(py % 4294967296) + w:u32le((if right then pz else -pz - sz) % 4294967296) + local function filled(x: number, y: number, z: number): boolean + if x < 0 or y < 0 or z < 0 or x >= sx or y >= sy or z >= sz then + return false + end + return cellColor(v, x + sx * (y + sy * z)) >= 0x1000000 + end + -- the value of file cell (x, y, z): colour bytes in the file's order, the alpha a mask when asked + local function value(x: number, y: number, z: number): number + local zz = if right then z else sz - 1 - z + local c = cellColor(v, x + sx * (y + sy * zz)) + if c < 0x1000000 then + return 0 + end + local a = c // 16777216 + if mask and not keepMask then + a = 1 + if not filled(x - 1, y, zz) then a += LEFT end + if not filled(x + 1, y, zz) then a += RIGHT end + if not filled(x, y + 1, zz) then a += TOP end + if not filled(x, y - 1, zz) then a += BOTTOM end + if not filled(x, y, zz + 1) then a += FRONT end + if not filled(x, y, zz - 1) then a += BACK end + elseif not mask and src and src.visibilityMask then + a = 255 -- masks are not colours + end + local r, gg, b = c % 256, (c // 256) % 256, (c // 65536) % 256 + if bgra then + r, b = b, r + end + return r + gg * 256 + b * 65536 + a * 16777216 + end + for z = 0, sz - 1 do + if compressed then + local x, y = 0, 0 + local slice = sx * sy + local i = 0 + while i < slice do + x, y = i % sx, i // sx + local c = value(x, y, z) + local run = 1 + while i + run < slice and value((i + run) % sx, (i + run) // sx, z) == c do + run += 1 + end + if run > 2 then + w:u32le(CODEFLAG) + w:u32le(run) + w:u32le(c) + else + for _ = 1, run do + w:u32le(c) + end + end + i += run + end + w:u32le(NEXTSLICEFLAG) + else + for y = 0, sy - 1 do + for x = 0, sx - 1 do + w:u32le(value(x, y, z)) + end + end + end + end + end + return w:finish(), nil +end + +return Qb diff --git a/tests/model/qb.luau b/tests/model/qb.luau new file mode 100644 index 0000000..2aca062 --- /dev/null +++ b/tests/model/qb.luau @@ -0,0 +1,130 @@ +-- model/qb tests: Qubicle Binary files with every option (RGBA / BGRA, left- / right-handed, RLE or not, visibility +-- masks, more than 255 colours) against the reference reader / writer of the fixture (exact colours of every cell, +-- names, positions), the indexed palette view, our encodings read back by the reference (same settings, flipped +-- settings, palette grids with computed masks), the api, error codes and the fuzz pass. Fixtures: tools/fixtures/qb.py. +local T = require("@tests/T") +local F = require("@formats") +local Qb = require("@formats/model/qb") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/qb") + +local t = T.suite("qb") + +t:eq(Qb.name, "qb", "name") +t:check(Qb.caps.decode and Qb.caps.encode, "caps") + +local function dec(data: string | buffer): (Types.Scene?, any) + return Qb.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data)) +end + +local function check(scene: Types.Scene, want: any, label: string) + t:eq(#scene.nodes, #want.matrices, label .. ": matrices") + for i, m in want.matrices do + local node = scene.nodes[i] + local v = (scene.voxels :: { Types.Voxels })[node.voxels :: number] + t:eq(node.name, m.name, label .. " " .. i .. ": name") + t:eq(table.concat(v.size, ","), table.concat(m.size, ","), label .. " " .. i .. ": size") + t:eq(table.concat(node.translation :: { number }, ","), table.concat(m.pos, ","), label .. " " .. i .. ": position") + t:eq(Crc32.of(v.colors :: buffer), m.crc, label .. " " .. i .. ": colours") + local filled = 0 + for k = 0, buffer.len(v.data) - 1 do + if buffer.readu8(v.data, k) ~= 0 then + filled += 1 + end + end + t:eq(filled, m.filled, label .. " " .. i .. ": filled cells") + end +end + +for _, c in Fx.cases do + local s, err = dec(c.data) + t:check(s ~= nil, c.name .. ": " .. tostring(err)) + check(s :: Types.Scene, c, c.name) + local src = (s :: Types.Scene).meta.source + t:check(src.colorFormat == c.colorFormat and src.rightHanded == c.rightHanded and src.compressed == c.compressed and src.visibilityMask == c.visibilityMask, c.name .. ": settings") + t:check(buffer.tostring(Qb.encode(s) :: buffer) == c.data, c.name .. ": same bytes again") + -- the palette view: exact colours when there are up to 255 + local v = ((s :: Types.Scene).voxels :: { Types.Voxels })[1] + local exact = true + for k = 0, buffer.len(v.data) - 1 do + local idx = buffer.readu8(v.data, k) + if idx > 0 then + local p, col = v.palette[idx], buffer.readu32(v.colors :: buffer, k * 4) + if p[1] + p[2] * 256 + p[3] * 65536 ~= col % 16777216 then + exact = false + end + end + end + t:eq(exact, c.name ~= "case5", c.name .. ": palette exact up to 255 colours") + t:eq(F.detect(c.data), "qb", c.name .. ": detect") +end + +-- our encodings, read by the reference +for name, want in Fx.ours do + local base = string.match(name, "^(case%d)_") + if base then + local c + for _, x in Fx.cases do + if x.name == base then + c = x + end + end + t:check(c ~= nil, name .. ": source") + -- the same cells whatever the settings (scene coordinates) + for i, m in want.matrices do + t:eq(m.crc, c.matrices[i].crc, name .. " " .. i .. ": colours read back") + t:eq(table.concat(m.pos, ","), table.concat(c.matrices[i].pos, ","), name .. " " .. i .. ": position read back") + end + if string.find(name, "_flip") then + t:check(want.rightHanded ~= c.rightHanded and want.compressed ~= c.compressed, name .. ": flipped settings") + end + end +end +do + local m = Fx.ours.palette_mask + t:check(m.visibilityMask and m.matrices[1].filled == 15, "palette grid with a mask") + local plain = Fx.ours.palette_plain + t:check(not plain.visibilityMask and plain.rightHanded and plain.compressed, "defaults") + -- our decode of the masked file: the centre cell (hidden on every side) has mask 1 + local v = Types.Voxels.new(3, 3, 3) + v.palette[1] = { 200, 10, 10, 255 } + for i = 0, 26 do + buffer.writeu8(v.data, i, 1) + end + local s = assert(dec(assert(Qb.encode(v, { visibilityMask = true })))) + local colors = ((s.voxels :: { Types.Voxels })[1]).colors :: buffer + t:eq(buffer.readu8(colors, 13 * 4 + 3), 1, "hidden cell mask") + t:eq(buffer.readu8(colors, 0 * 4 + 3), 1 + 2 + 16 + 64, "corner cell mask (left, bottom, back)") +end + +-- api and conversion to .vox +do + local s = assert(F.load(Fx.cases[1].data)) + t:check(s.kind == "scene", "F.load") + t:check(F.save(s, nil, { format = "vox" }) ~= nil, "qb -> vox") + t:check(F.save(s, nil, { format = "schem" }) ~= nil, "qb -> schem") +end + +-- errors +do + local _, e1 = dec("\1\1\0\0") + t:check(e1 and e1.code == Err.TRUNCATED, "truncated header") + local _, e2 = dec("\2\1\0\0" .. string.rep("\0", 20)) + t:check(e2 and e2.code == Err.CORRUPT, "bad version") + local _, e3 = dec(string.sub(Fx.cases[1].data, 1, 60)) + t:check(e3 and e3.code == Err.TRUNCATED, "truncated matrix") + local _, e4 = Qb.encode({} :: any) + t:check(e4 and e4.code == Err.ARG, "encode nothing") +end + +local samples = {} +for _, c in Fx.cases do + table.insert(samples, c.data) +end +t:fuzz("decode", function(b: buffer) + return Qb.decode(Bytes.reader(b)) +end, samples) +t:done() diff --git a/tools/fixtures/_qb_encode.luau b/tools/fixtures/_qb_encode.luau new file mode 100644 index 0000000..2a157dc --- /dev/null +++ b/tools/fixtures/_qb_encode.luau @@ -0,0 +1,34 @@ +-- tools/fixtures/qb.py helper: our model/qb encoder's output for the reference reader there. Prints "\t". +local Qb = require("@formats/model/qb") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Fx = require("@tests/gen/qb") + +local function hex(b: buffer): string + local t = table.create(buffer.len(b)) + for i = 0, buffer.len(b) - 1 do + t[i + 1] = string.format("%02x", buffer.readu8(b, i)) + end + return table.concat(t) +end +local function emit(name: string, b: buffer?, e: any) + if not b then + error(name .. ": " .. tostring(e)) + end + print(name .. "\t" .. hex(b)) +end + +for _, c in Fx.cases do + local s = assert(Qb.decode(Bytes.reader(buffer.fromstring(c.data)))) + emit(c.name .. "_same", Qb.encode(s)) + emit(c.name .. "_flip", Qb.encode(s, { rightHanded = not c.rightHanded, compressed = not c.compressed, colorFormat = if c.colorFormat == "rgba" then "bgra" else "rgba" })) +end +-- a palette grid (no true colours) with a visibility mask computed by the encoder +local v = Types.Voxels.new(3, 3, 3) +v.palette[1] = { 200, 10, 10, 255 } +v.palette[2] = { 10, 200, 10, 255 } +for i = 0, 26 do + buffer.writeu8(v.data, i, if i == 13 then 2 elseif i % 2 == 0 then 1 else 0) +end +emit("palette_mask", Qb.encode(v, { visibilityMask = true })) +emit("palette_plain", Qb.encode(v)) diff --git a/tools/fixtures/qb.py b/tools/fixtures/qb.py new file mode 100644 index 0000000..5539500 --- /dev/null +++ b/tools/fixtures/qb.py @@ -0,0 +1,156 @@ +# model/qb fixtures: Qubicle Binary files from a reader / writer written here from the format description in the +# Qubicle documentation (no Qubicle tool runs under nix), with every option: RGBA / BGRA, left- / right-handed, +# uncompressed / RLE, visibility masks; plus our encoder's output (tools/fixtures/_qb_encode.luau) read back by it. +# tests/gen/qb.luau { cases = { { name, data, colorFormat, rightHanded, compressed, visibilityMask, +# matrices = { { name, size, pos (scene coordinates: left-handed files mirrored on z), crc +# (CRC-32 of the r, g, b, a bytes of every cell in Voxels order), filled } } } }, +# ours = { [name] = { same fields as cases } } } +import importlib.util, os, pickle, struct, subprocess, zlib, random + +INPUTS = ["src/Formats/model/qb", "tools/fixtures/_qb_encode.luau"] + +_spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_model_ref.py")) +R = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(R) + +CODEFLAG, NEXTSLICEFLAG = 2, 6 + + +def write_qb(matrices, bgra, right, compressed, mask): + """matrices: [(name, (sx, sy, sz), (px, py, pz), {(x, y, z): (r, g, b, a)})] in file coordinates""" + out = bytearray(b"\x01\x01\x00\x00") + out += struct.pack(" 2: + out += struct.pack(" settings, [(name, size, pos, {(x, y, z): (r, g, b, a)})] in file coordinates""" + assert data[:4] == b"\x01\x01\x00\x00" + fmt, zaxis, comp, mask, n = struct.unpack_from("> 24 == 0: + return + r, g, b, a = v & 255, v >> 8 & 255, v >> 16 & 255, v >> 24 + if fmt == 1: + r, b = b, r + cells[(x, y, z)] = (r, g, b, a) + for z in range(sz): + if not comp: + for y in range(sy): + for x in range(sx): + put(x, y, z, struct.unpack_from(" Date: Sat, 31 Oct 2026 14:56:33 -0500 Subject: [PATCH 7/7] ws-voxel: docs/guide/voxel.md (NBT / SNBT, schematics, regions, Qubicle; tested snippets) + inputs generator; bench lines for NBT, SNBT, packed arrays, schem, qb --- docs/guide/README.md | 1 + docs/guide/data.md | 3 +- docs/guide/scene.md | 5 ++ docs/guide/voxel.md | 145 +++++++++++++++++++++++++++++++++++ tools/bench.luau | 78 +++++++++++++++++++ tools/fixtures/docs_voxel.py | 84 ++++++++++++++++++++ 6 files changed, 315 insertions(+), 1 deletion(-) create mode 100644 docs/guide/voxel.md create mode 100644 tools/fixtures/docs_voxel.py diff --git a/docs/guide/README.md b/docs/guide/README.md index d1fff6c..b9c2a72 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -18,6 +18,7 @@ and the host notes. Each standard type has its own page: | [Fonts](font.md) | `Font` | TTF / OTF, WOFF, WOFF2, BMFont | | [Archives](archive.md) | `Archive` | zip, tar, gzip, 7z, xz, zstd, Brotli, bzip2 | | [Data](data.md) | plain values, `XmlNode`, `Date` | JSON, XML, YAML, TOML, CSV, INI, MessagePack, CBOR, plist | +| [Minecraft and voxels](voxel.md) | typed values, `Scene` + `Voxels` | NBT, SNBT, `.schem` / `.schematic` / `.litematic`, Anvil `.mca`, Qubicle `.qb` | | [Vector](vector.md) | `Vector` | SVG | | [Layered images](layered.md) | `Layered` | PSD, Aseprite | | [Tile maps](tilemap.md) | `TileMap` | Tiled TMX / TMJ | diff --git a/docs/guide/data.md b/docs/guide/data.md index 3b40019..46a6d52 100644 --- a/docs/guide/data.md +++ b/docs/guide/data.md @@ -3,7 +3,8 @@ The data formats (JSON, XML, YAML, TOML, CSV, INI, MessagePack, CBOR, plist) decode to plain Luau values: tables, strings, numbers, booleans. Three helpers fill the gaps Luau tables leave: `F.data.null` (a null that can sit in a table), ordered objects (`F.Types.object`: key order, and `{}` that stays an object), and `F.Types.Date` (TOML, -YAML, plist, CBOR and MessagePack dates). XML decodes to a tree of `XmlNode`s. +YAML, plist, CBOR and MessagePack dates). XML decodes to a tree of `XmlNode`s. Minecraft's NBT and SNBT (typed +numbers kept) are on the [Minecraft and voxels](voxel.md) page. ```luau local v = assert(F.data.load('{"name": "ada", "tags": ["x", "y"], "boss": null}')) diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 525643e..659ecd4 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -329,6 +329,8 @@ node that shows a model has `node.voxels` (an index into `scene.voxels`) and no | `data` | `buffer` | one byte per cell, `0` = empty, `1..255` = palette index; cell `(x, y, z)` (0-based) at byte `x + sx * (y + sy * z)` | | `palette` | `{ { r, g, b, a } }` | 255 entries, 0..255 **sRGB**, `palette[i]` for index `i`, shared by a file's models | | `materials` | `{ [index]: { type, ... } }?` | MATL: `"diffuse"`, `"metal"`, `"glass"`, `"emit"`, ... with their properties | +| `blocks` | `{ palette, data, blockEntities?, entities? }?` | Minecraft grids: the exact block state of every cell ([voxel.md](voxel.md)) | +| `colors` | `buffer?` | true-colour grids (Qubicle): r, g, b, a bytes per cell | ```luau local V = F.Types.Voxels @@ -392,6 +394,9 @@ assert(F.load(vox).voxels[1].size[1] == 4) | 3MF | yes | yes | | | USDA (+ USDZ read) | yes | yes | | | VOX | yes | yes | voxel grids, scene graph, materials | +| Minecraft `.schem` / `.schematic` / `.litematic` | yes | yes | block grids, see [voxel.md](voxel.md) | +| Minecraft region `.mca` | yes | | block grids of chosen chunks, see [voxel.md](voxel.md) | +| Qubicle `.qb` | yes | yes | true-colour grids, see [voxel.md](voxel.md) | | STEP | via the CAD plug-in | | see [cad.md](cad.md) | Capabilities per format: [FORMATS.md](../FORMATS.md). diff --git a/docs/guide/voxel.md b/docs/guide/voxel.md new file mode 100644 index 0000000..5371656 --- /dev/null +++ b/docs/guide/voxel.md @@ -0,0 +1,145 @@ +# Minecraft and voxel files + +Minecraft's NBT data, its schematics (`.schem`, `.schematic`, `.litematic`) and region files (`.mca`), and Qubicle +`.qb` models. NBT and SNBT load as plain values (the [Data](data.md) category); schematics, regions and Qubicle files +load as a `Scene` whose `scene.voxels` holds `Voxels` grids (see [3D scenes](scene.md#voxels)), so they mesh and save +like a `.vox`. + +| Format | Read | Write | Value | +|---|---|---|---| +| NBT (`.nbt`, `.dat`, `.mcstructure`) | yes | yes | typed plain values; Java big-endian, Bedrock little-endian, gzip / zlib / raw | +| SNBT (`.snbt`) | yes | yes | the same values as text | +| Sponge `.schem` v1 / v2 / v3 | yes | yes | Scene, one grid with block states | +| MCEdit / WorldEdit `.schematic` | yes | yes | Scene; pre-1.13 numeric ids | +| Litematica `.litematic` | yes | yes | Scene, one grid per region | +| Anvil region `.mca` | yes | | Scene, the chosen chunks as one grid, plus each chunk's NBT | +| Qubicle `.qb` | yes | yes | Scene, one grid per matrix, exact colours | + +## NBT and SNBT + +NBT values are plain Luau with their tag type kept, so what you load saves back the same: + +| NBT tag | Luau value | +|---|---| +| int | number | +| string | string | +| byte array | buffer | +| compound | ordered table (`F.Types.object`, keys in file order) | +| list | array (its element type: `Nbt.listType(list)`) | +| byte, short, long, float, double | a tag `{ type = "byte", value = 1 }` (`tostring` gives SNBT: `1b`); longs past 2^53 hold their exact decimal text | +| int array, long array | a tag with `value` = numbers / a buffer of 8-byte little-endian longs | + +```luau +local level = assert(F.load(levelDatBytes, { name = "level.dat" })) -- gzip NBT +local data = level.Data +assert(data.LevelName == "My World" and data.SpawnY == 64) -- ints and strings are plain +assert(data.Difficulty.type == "byte" and data.Difficulty.value == 2) +assert(data.RandomSeed.value == "-4011880356862312345") -- past 2^53: exact text +assert(tostring(data.Player.Health) == "20.0f") + +local Nbt = F.format("nbt").Nbt -- the engine: codecs/text/Nbt +data.Difficulty = Nbt.byte(3) +data.Tags = Nbt.list("string", { "a", "b" }) +local saved = assert(F.save(level, nil, { format = "nbt" })) -- gzip again, like the source +assert(F.load(saved, { format = "nbt" }).Data.Difficulty.value == 3) +local info = F.format("nbt").info(level) -- how it was stored +assert(info.compression == "gzip" and info.endian == "big" and info.name == "") +``` + +Plain inputs work too: a whole number writes as an int, other numbers as a double, `true` / `false` as bytes, a table +with string keys as a compound and an array as a list. Bedrock files (little-endian, with or without the `level.dat` +header) are detected; `endian = "little"`, `varint = true` (network NBT) and `compression` force a layout when saving. + +```luau +local text = assert(F.convert(levelDatBytes, "snbt", { format = "nbt" })) -- NBT -> SNBT text +assert(string.find(buffer.tostring(text), 'LevelName:"My World"', 1, true)) +local v = assert(F.load("{pos:[I;1,2,3],name:'x',scale:1.5f,big:9007199254740993L}", { format = "snbt" })) +assert(v.pos.value[2] == 2 and v.scale.type == "float" and v.big.value == "9007199254740993") +assert(F.saveString(v, { format = "snbt" }) == '{pos:[I;1,2,3],name:"x",scale:1.5f,big:9007199254740993L}') +local pretty = assert(F.saveString(v, { format = "snbt", indent = 2 })) +local bedrock = assert(F.save(v, nil, { format = "nbt", endian = "little", compression = "none" })) +``` + +## Schematics + +A schematic loads as a Scene with `meta.up = "y"` and one unit per block. Each grid has its usual colour view +(`data` / `palette`, from a built-in table of block colours) and `voxels.blocks` with the exact blocks: + +| `voxels.blocks` field | Meaning | +|---|---| +| `palette` | block states (`"minecraft:oak_log[axis=y]"`), entry 1 is index 0 | +| `data` | a buffer, one u16 per cell (same cell order as `voxels.data`): the 0-based palette index | +| `blockEntities` | `{ { pos = { x, y, z }, id, data } }`: chests, signs, ... (`data` is their NBT) | +| `entities` | entity NBT records | + +```luau +local scene = assert(F.load(schemBytes)) -- detected by content: F.detect gives "schem" +local grid = scene.voxels[1] +assert(grid.size[1] == 5 and grid.size[2] == 4) -- x, y (up), z +local blocks = grid.blocks +local function blockAt(x: number, y: number, z: number): string + local i = x + grid.size[1] * (y + grid.size[2] * z) + return blocks.palette[buffer.readu16(blocks.data, i * 2) + 1] +end +assert(blockAt(0, 0, 0) == "minecraft:stone" and blockAt(2, 2, 0) == "minecraft:glass") +assert(F.Types.Voxels.get(grid, 1, 1, 1) == 0) -- air is empty in the colour view + +local lite = assert(F.load(litematicBytes)) +assert(#lite.voxels == 2 and lite.nodes[2].name == "pillar") -- a node per region, placed by translation +local legacy = assert(F.save(lite, nil, { format = "schematic", variant = "schematic" })) -- regions merged +local schem = assert(F.save(lite, nil, { format = "schem" })) -- Sponge v3 +assert(F.detect(schem) == "schem") +``` + +`F.save` picks the flavour from `variant`, the destination's extension (`"out.litematic"`), `format = "schem"` / +`"litematic"`, or the loaded file's. A grid without `blocks` (a `.vox`, a `.qb`) gets the block nearest in colour for +each palette colour, so converting voxel art works: + +```luau +local vox = assert(F.load(voxBytes)) +local schem = assert(F.save(vox, nil, { format = "schem" })) +local back = assert(F.load(schem)) +assert(back.voxels[1].blocks.palette[1] == "minecraft:air") +``` + +## Region files + +An Anvil region holds 32 x 32 chunks. Loading it builds one grid over the chunks you pick (`chunks = { { x, z } }`, +local 0..31), or the blocks inside `area = { minX, minY, minZ, maxX, maxY, maxZ }` (world coordinates), between the +lowest and highest sections holding blocks; `maxCells` (default 2^25) guards against loading a whole world. + +```luau +local Mca = F.format("mca") +local region = assert(F.load(regionBytes, { name = "r.0.0.mca", chunks = { { 0, 0 }, { 1, 0 } } })) +local grid = region.voxels[1] +assert(grid.size[1] == 32 and grid.size[3] == 16) +local corner = region.nodes[1].translation -- the grid's world position +assert(corner[1] == 0 and corner[2] == -64) +local chunk = region.meta.source.chunks[1] +assert(chunk.dataVersion == 3953 and chunk.nbt.Status == "minecraft:full") -- the chunk's whole NBT + +local list = assert(Mca.list(F.Bytes.reader(regionBytes))) -- the chunks present, with timestamps +local nbt = assert(Mca.chunk(F.Bytes.reader(regionBytes), 3, 2)) +assert(nbt.xPos == 3) +``` + +All chunk layouts read: 1.18+ sections, 1.13 - 1.17 palettes and pre-1.13 numeric ids (as state names such as +`minecraft:red_wool`, with `[data=N]` for the rest of a data value). Chunk payloads may be gzip, zlib, LZ4 or stored; +chunks in external `.mcc` files load through `opts.resolve` (filled in when loading by path). Regions are read-only. + +## Qubicle + +Each matrix becomes a grid with `voxels.colors`, the exact colour of every cell (`r, g, b, a` bytes; `a = 0` is +empty), next to the indexed `data` / `palette` view. Left-handed files are mirrored into the scene's right-handed +axes; saving writes the source's settings unless `compressed`, `colorFormat` (`"rgba"` / `"bgra"`), `rightHanded` or +`visibilityMask` say otherwise. + +```luau +local box = assert(F.load(qbBytes)) +local grid = box.voxels[1] +local first = buffer.readu32(grid.colors, 0) -- r + g * 256 + b * 65536 + a * 2^24 +assert(first % 256 == 200 and first // 16777216 == 255) +assert(box.nodes[1].name == "box") +local again = assert(F.save(box, nil, { format = "qb", compressed = false })) +local vox = assert(F.save(box, nil, { format = "vox" })) -- or .schem, .glb after F.ops.mesh.meshVoxels +``` diff --git a/tools/bench.luau b/tools/bench.luau index e7d1364..59a36c4 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -1091,3 +1091,81 @@ do jitTune(false) end end +do + -- NBT / voxels (ws-voxel): a chunk-like NBT tree (24 sections with packed long arrays, 4000 entity-like compounds) + -- through codecs/text/Nbt (binary and SNBT), 1M packed 5-bit indices, a 64^3 Sponge schematic and Qubicle file + local Nbt = require("@formats/codecs/text/Nbt") + local Mc = require("@formats/codecs/model/Minecraft") + local Schematic = require("@formats/model/schematic") + local Qb = require("@formats/model/qb") + local sections = Nbt.list("compound") + for s = 1, 24 do + local pal = Nbt.list("compound") + for p = 1, 16 do + table.insert(pal, Nbt.compound({ Name = "minecraft:block_" .. p, Properties = Nbt.compound({ axis = "y" }, { "axis" }) }, { "Name", "Properties" })) + end + local longs = buffer.create(256 * 8) + for i = 0, 511 do + buffer.writeu32(longs, i * 4, (i * 2654435761) % 4294967296) + end + table.insert(sections, Nbt.compound({ Y = Nbt.byte(s - 5), block_states = Nbt.compound({ palette = pal, data = Nbt.longArray(longs) }, { "palette", "data" }) }, { "Y", "block_states" })) + end + local ents = Nbt.list("compound") + for i = 1, 4000 do + table.insert(ents, Nbt.compound({ + id = "minecraft:thing", + Pos = Nbt.list("double", { Nbt.double(i * 0.5), Nbt.double(64), Nbt.double(-i * 0.25) }), + Health = Nbt.float(20), + UUID = Nbt.intArray({ i, -i, i * 3, 7 }), + Tags = Nbt.list("string", { "a", "b" }), + Age = Nbt.short(i % 1000), + Seed = Nbt.long(i * 1234567), + }, { "id", "Pos", "Health", "UUID", "Tags", "Age", "Seed" })) + end + local root = Nbt.compound({ DataVersion = 3953, sections = sections, entities = ents }, { "DataVersion", "sections", "entities" }) + local raw = assert(Nbt.encode(root, { compression = "none" })) + bench("nbt decode (" .. buffer.len(raw) // 1000 .. " KB)", 5, buffer.len(raw), function() + Nbt.decode(raw) + end) + bench("nbt encode", 5, buffer.len(raw), function() + Nbt.encode(root, { compression = "none" }) + end) + local text = assert(Nbt.print(root)) + bench("snbt parse (" .. #text // 1000 .. " KB)", 3, #text, function() + Nbt.parse(text) + end) + bench("snbt print", 3, #text, function() + Nbt.print(root) + end) + local n = 1048576 + local idx = buffer.create(n * 2) + for i = 0, n - 1 do + buffer.writeu16(idx, i * 2, (i * 7) % 32) + end + local packed = Mc.Packed.pack(idx, n, 5, false) + local out = buffer.create(n * 2) + bench("packed unpack 1M x 5 bits (MB out)", 5, n * 2, function() + Mc.Packed.unpack(packed, 5, n, false, out, 32) + end) + local V = 64 + local states = { "minecraft:air" } + for i = 1, 40 do + table.insert(states, "minecraft:block_" .. i) + end + local cells = buffer.create(V * V * V * 2) + for i = 0, V * V * V - 1 do + buffer.writeu16(cells, i * 2, if (i // V) % 3 == 0 then 0 else 1 + (i // 97) % 40) + end + local grid = Mc.voxels(V, V, V, states, cells) + local schem = assert(Schematic.encode(grid, { compression = "none" })) + bench("schem decode 64^3 (MB of cells)", 3, V * V * V, function() + Schematic.decode(Bytes.reader(schem)) + end) + bench("schem encode 64^3", 3, V * V * V, function() + Schematic.encode(grid, { compression = "none" }) + end) + local qb = assert(Qb.encode(grid)) + bench("qb decode 64^3 rle (MB of cells)", 3, V * V * V, function() + Qb.decode(Bytes.reader(qb)) + end) +end diff --git a/tools/fixtures/docs_voxel.py b/tools/fixtures/docs_voxel.py new file mode 100644 index 0000000..5e3ff9f --- /dev/null +++ b/tools/fixtures/docs_voxel.py @@ -0,0 +1,84 @@ +# Docs inputs for the voxel guide page (docs/guide/voxel.md): a level.dat-like gzip NBT file and a Sponge v3 .schem +# (nbtlib), a two-region .litematic (litemapy), a small Anvil region from tools/fixtures/mca.py and a Qubicle file +# from tools/fixtures/qb.py's writer. +# tests/gen/docs_voxel.luau { files = { [name] = bytes }, vars = { levelDatBytes = ..., ... } } +import importlib.util, os, pickle, subprocess + +INPUTS = ["tools/docs_check.py", "tools/fixtures/mca.py", "tools/fixtures/qb.py"] + +BODY = r''' +import nbtlib, pickle, sys, io, gzip, os, tempfile +from nbtlib import Byte, Short, Int, Long, Float, Double, String, List, Compound, IntArray, ByteArray +import numpy as np +from litemapy import Schematic, Region, BlockState +files = {} +level = Compound({"Data": Compound({"LevelName": String("My World"), "DataVersion": Int(3953), "Difficulty": Byte(2), + "RandomSeed": Long(-4011880356862312345), "SpawnX": Int(16), "SpawnY": Int(64), "SpawnZ": Int(-8), + "GameRules": Compound({"doDaylightCycle": String("true")}), + "Player": Compound({"Pos": List[Double]([Double(16.5), Double(64.0), Double(-7.5)]), "Health": Float(20.0)})})}) +f = nbtlib.File(level, root_name="") +buf = io.BytesIO() +f.write(buf) +files["level.dat"] = gzip.compress(buf.getvalue(), mtime=0) +# a 5 x 4 x 3 Sponge v3 schematic: a stone floor, oak planks walls, one glass block +w, h, l = 5, 4, 3 +states = ["minecraft:air", "minecraft:stone", "minecraft:oak_planks", "minecraft:glass"] +idx = [] +for y in range(h): + for z in range(l): + for x in range(w): + idx.append(1 if y == 0 else (3 if (x, y, z) == (2, 2, 0) else (2 if x in (0, w - 1) else 0))) +s = Compound({"Version": Int(3), "DataVersion": Int(3953), "Width": Short(w), "Height": Short(h), "Length": Short(l), + "Offset": IntArray([0, 0, 0]), "Metadata": Compound({"Name": String("hut")}), + "Blocks": Compound({"Palette": Compound({st: Int(i) for i, st in enumerate(states)}), + "Data": ByteArray(idx), "BlockEntities": List[Compound]([])})}) +buf = io.BytesIO() +nbtlib.File({"Schematic": s}, root_name="").write(buf) +files["hut.schem"] = gzip.compress(buf.getvalue(), mtime=0) +a = Region(0, 0, 0, 3, 2, 3) +for x in range(3): + for z in range(3): + a[x, 0, z] = BlockState("minecraft:cobblestone") +b = Region(5, 0, 0, 2, 3, 1) +for y in range(3): + b[0, y, 0] = BlockState("minecraft:oak_log", axis="y") +tmp = tempfile.mkdtemp() +p = os.path.join(tmp, "build.litematic") +Schematic(name="build", author="docs", regions={"floor": a, "pillar": b}).save(p) +files["build.litematic"] = open(p, "rb").read() +sys.stdout.buffer.write(pickle.dumps(files, protocol=4)) +''' + + +def load(ctx, name): + spec = importlib.util.spec_from_file_location("docs_voxel_" + 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 docs_check(ctx): + spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py")) + m = importlib.util.module_from_spec(spec) + spec.loader.exec_module(m) + return m + + +def generate(ctx): + try: + files = pickle.loads(ctx.python(["nbtlib", "litemapy", "numpy"], BODY)) + except subprocess.CalledProcessError as e: + raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:]) + mca = load(ctx, "mca") + regions = pickle.loads(ctx.python(["nbtlib", "numpy", "lz4", "xxhash"], mca.BODY))["regions"] + files["r.0.0.mca"] = regions[0]["data"] # 1.18+ chunks, every compression type + qb = load(ctx, "qb") + cells = {(x, y, z): ((200, 40, 40, 255) if y == 0 else (240, 240, 240, 255)) for x in range(3) for y in range(2) for z in range(3)} + files["box.qb"] = qb.write_qb([("box", (3, 2, 3), (0, 0, 0), cells)], False, True, True, False) + docs_check(ctx).emit_inputs(ctx, files, { + "levelDatBytes": "level.dat", + "schemBytes": "hut.schem", + "litematicBytes": "build.litematic", + "regionBytes": "r.0.0.mca", + "qbBytes": "box.qb", + })