merge ws/voxel
This commit is contained in:
commit
b7f3a69fcc
44 files changed
+7481
-27
No files matched your search
@@ -1125,3 +1125,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
|
||||
@@ -0,0 +1,34 @@
|
||||
-- tools/fixtures/qb.py helper: our model/qb encoder's output for the reference reader there. Prints "<name>\t<hex>".
|
||||
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))
|
||||
@@ -0,0 +1,49 @@
|
||||
-- tools/fixtures/schematic.py helper: our model/schematic encoder's output for the reference readers (litemapy,
|
||||
-- nbtlib). Prints "<name>\t<hex>" 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" }))
|
||||
@@ -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",
|
||||
})
|
||||
@@ -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)
|
||||
@@ -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<n> s<n> i<n> l<n> f<hex f32 BE> d<hex f64 BE> S<len>:<utf8> B<hex> I[a,b] L[a,b]
|
||||
# [<elemtype>|a,b] {<len>:<key>=<v>;...} (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("<II", 9 + i % 3, len(little)) + little
|
||||
cases.append({
|
||||
"name": "tree%d" % i, "raw": big, "little": little, "gzip": gzip.compress(big, mtime=0),
|
||||
"zlib": zlib.compress(big), "header": header, "version": 9 + i % 3, "root": name, "canon": canon(root),
|
||||
"snbt": nbtlib.serialize_tag(root), "compact": nbtlib.serialize_tag(root, compact=True),
|
||||
})
|
||||
# Bedrock network NBT: an encoder from the wiki.vg description (zigzag varints for int / long / lengths)
|
||||
def uvar(n):
|
||||
out = bytearray()
|
||||
while True:
|
||||
b = n & 0x7f
|
||||
n >>= 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("<b", int(t))
|
||||
if k == "short": return struct.pack("<h", int(t))
|
||||
if k == "int": return zz32(int(t))
|
||||
if k == "long": return zz64(int(t))
|
||||
if k == "float": return struct.pack("<f", float(t))
|
||||
if k == "double": return struct.pack("<d", float(t))
|
||||
if k == "string": return nstr(str(t))
|
||||
if k == "byteArray": return zz32(len(t)) + np.asarray(t, dtype=np.int8).tobytes()
|
||||
if k == "intArray": return zz32(len(t)) + b"".join(zz32(int(x)) for x in t)
|
||||
if k == "longArray": return zz32(len(t)) + b"".join(zz64(int(x)) for x in t)
|
||||
if k == "list": return bytes([IDS[NAMES[t.subtype.__name__]]]) + zz32(len(t)) + b"".join(net(x) for x in t)
|
||||
if k == "compound":
|
||||
return b"".join(bytes([IDS[kind(v)]]) + nstr(key) + net(v) for key, v in t.items()) + b"\x00"
|
||||
nets = []
|
||||
for i in range(20):
|
||||
root = compound(0)
|
||||
nets.append({"data": b"\x0a" + nstr("") + net(root), "canon": canon(root)})
|
||||
sys.stdout.buffer.write(pickle.dumps({"cases": cases, "net": nets}, protocol=4))
|
||||
'''
|
||||
|
||||
|
||||
def run(ctx, packages, body):
|
||||
"""ctx.python with the script's stderr in the error"""
|
||||
import subprocess
|
||||
try:
|
||||
return ctx.python(packages, body)
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise RuntimeError("fixture python failed:\n" + e.stderr.decode(errors="replace")[-3000:])
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
import pickle
|
||||
out = pickle.loads(run(ctx, ["nbtlib", "numpy"], BODY))
|
||||
ctx.emit("nbt", out)
|
||||
@@ -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("<IIIII", 1 if bgra else 0, 1 if right else 0, 1 if compressed else 0, 1 if mask else 0, len(matrices))
|
||||
for name, (sx, sy, sz), (px, py, pz), cells in matrices:
|
||||
nb = name.encode()
|
||||
out += bytes([len(nb)]) + nb + struct.pack("<IIIiii", sx, sy, sz, px, py, pz)
|
||||
|
||||
def val(x, y, z):
|
||||
c = cells.get((x, y, z))
|
||||
if not c:
|
||||
return 0
|
||||
r, g, b, a = c
|
||||
if bgra:
|
||||
r, b = b, r
|
||||
return r | g << 8 | b << 16 | a << 24
|
||||
for z in range(sz):
|
||||
vals = [val(x, y, z) for y in range(sy) for x in range(sx)]
|
||||
if not compressed:
|
||||
out += b"".join(struct.pack("<I", v) for v in vals)
|
||||
continue
|
||||
i = 0
|
||||
while i < len(vals):
|
||||
run = 1
|
||||
while i + run < len(vals) and vals[i + run] == vals[i]:
|
||||
run += 1
|
||||
if run > 2:
|
||||
out += struct.pack("<III", CODEFLAG, run, vals[i])
|
||||
else:
|
||||
out += b"".join(struct.pack("<I", vals[i]) for _ in range(run))
|
||||
i += run
|
||||
out += struct.pack("<I", NEXTSLICEFLAG)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def read_qb(data):
|
||||
"""-> 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("<IIIII", data, 4)
|
||||
p = 24
|
||||
mats = []
|
||||
for _ in range(n):
|
||||
ln = data[p]; p += 1
|
||||
name = data[p:p + ln].decode(); p += ln
|
||||
sx, sy, sz, px, py, pz = struct.unpack_from("<IIIiii", data, p); p += 24
|
||||
cells = {}
|
||||
|
||||
def put(x, y, z, v):
|
||||
if v >> 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("<I", data, p)[0]); p += 4
|
||||
continue
|
||||
i = 0
|
||||
while True:
|
||||
d = struct.unpack_from("<I", data, p)[0]; p += 4
|
||||
if d == NEXTSLICEFLAG:
|
||||
break
|
||||
if d == CODEFLAG:
|
||||
run, v = struct.unpack_from("<II", data, p); p += 8
|
||||
for _ in range(run):
|
||||
put(i % sx, i // sx, z, v); i += 1
|
||||
else:
|
||||
put(i % sx, i // sx, z, d); i += 1
|
||||
mats.append((name, (sx, sy, sz), (px, py, pz), cells))
|
||||
return {"colorFormat": "bgra" if fmt else "rgba", "rightHanded": zaxis == 1, "compressed": comp == 1, "visibilityMask": mask == 1}, mats
|
||||
|
||||
|
||||
def describe(settings, mats):
|
||||
out = []
|
||||
for name, (sx, sy, sz), (px, py, pz), cells in mats:
|
||||
right = settings["rightHanded"]
|
||||
buf = bytearray()
|
||||
for z in range(sz):
|
||||
for y in range(sy):
|
||||
for x in range(sx):
|
||||
fz = z if right else sz - 1 - z
|
||||
buf += bytes(cells.get((x, y, fz), (0, 0, 0, 0)))
|
||||
out.append({"name": name, "size": [sx, sy, sz], "pos": [px, py, pz if right else -(pz + sz)],
|
||||
"crc": zlib.crc32(bytes(buf)), "filled": len(cells)})
|
||||
d = dict(settings)
|
||||
d["matrices"] = out
|
||||
return d
|
||||
|
||||
|
||||
def mask_of(cells, x, y, z):
|
||||
a = 1
|
||||
for (dx, dy, dz), bit in (((-1, 0, 0), 2), ((1, 0, 0), 4), ((0, 1, 0), 8), ((0, -1, 0), 16), ((0, 0, 1), 32), ((0, 0, -1), 64)):
|
||||
if (x + dx, y + dy, z + dz) not in cells:
|
||||
a += bit
|
||||
return a
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = random.Random(4)
|
||||
cases = []
|
||||
for k, (bgra, right, comp, mask) in enumerate([(False, True, True, False), (True, False, False, False), (False, False, True, True),
|
||||
(True, True, False, True), (False, True, False, False), (False, True, True, False)]):
|
||||
mats = []
|
||||
for m in range(1 + k % 3):
|
||||
size = (rng.randrange(1, 9), rng.randrange(1, 7), rng.randrange(1, 6))
|
||||
many = k == 5 # more than 255 colours
|
||||
pal = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(400 if many else 6)]
|
||||
cells = {}
|
||||
for x in range(size[0]):
|
||||
for y in range(size[1]):
|
||||
for z in range(size[2]):
|
||||
if rng.random() < 0.6:
|
||||
cells[(x, y, z)] = pal[rng.randrange(len(pal))] + (255,)
|
||||
if k == 5:
|
||||
size = (20, 20, 3)
|
||||
cells = {(x, y, z): pal[(x + 20 * y + z) % 400] + (255,) for x in range(20) for y in range(20) for z in range(3)}
|
||||
if mask:
|
||||
cells = {p: c[:3] + (mask_of(cells, *p),) for p, c in cells.items()}
|
||||
mats.append(("m%d_%d" % (k, m), size, (rng.randrange(-20, 20), rng.randrange(-5, 5), rng.randrange(-20, 20)), cells))
|
||||
data = write_qb(mats, bgra, right, comp, mask)
|
||||
settings, back = read_qb(data)
|
||||
d = describe(settings, back)
|
||||
d["name"] = "case%d" % k
|
||||
d["data"] = data
|
||||
cases.append(d)
|
||||
ctx.emit("qb", {"cases": cases})
|
||||
try:
|
||||
files = R.luau_encode(ctx, "tools/fixtures/_qb_encode.luau")
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise RuntimeError("our encoder failed:\n" + (e.stderr or b"").decode(errors="replace")[-3000:])
|
||||
ours = {}
|
||||
for name, data in files.items():
|
||||
settings, mats = read_qb(data)
|
||||
ours[name] = describe(settings, mats)
|
||||
ctx.emit("qb", {"cases": cases, "ours": ours})
|
||||
@@ -0,0 +1,244 @@
|
||||
# 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):
|
||||
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))
|
||||
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)
|
||||
Reference in new issue
Block a user