219 lines
11 KiB
Python
219 lines
11 KiB
Python
# 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)
|