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
This commit is contained in:
1 parent
09354cbd12
commit
286d193f14
9 files changed
+1032
-80
No files matched your search
@@ -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` |
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,355 @@
|
||||
--!strict
|
||||
-- model/mca: Minecraft Anvil region files (r.<x>.<z>.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.<x>.<z>.mca"), for .mcc files
|
||||
name: string?, -- the file name (the api fills it in)
|
||||
resolve: ((string) -> buffer?)?, -- reads a sibling file: external chunks c.<x>.<z>.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.<x>.<z>.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
|
||||
@@ -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 }
|
||||
|
||||
@@ -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:<id>:<data>" 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()
|
||||
@@ -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:<id>:<data>" 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("<iii", len(comp), len(blk), chk) + comp
|
||||
out += b"LZ4Block" + bytes([0x16]) + struct.pack("<iii", 0, 0, 0)
|
||||
return bytes(out)
|
||||
CTYPE = {"gzip": 1, "zlib": 2, "none": 3, "lz4": 4}
|
||||
def compress(raw, kind):
|
||||
if kind == "gzip": return gzip.compress(raw, mtime=0)
|
||||
if kind == "zlib": return zlib.compress(raw)
|
||||
if kind == "none": return raw
|
||||
return lz4block(raw)
|
||||
def region(chunks):
|
||||
# chunks: [(lx, lz, root, kind, external)] -> 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.<x>.<z>.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)
|
||||
Reference in new issue
Block a user