merge master into ws/arch2

This commit is contained in:
4DBug committed 2026-10-31 15:22:43 -05:00
commit 0ee0859298
64 files changed
+13113 -30

No files matched your search

+112
View File
@@ -249,6 +249,40 @@ do
Lz4.compress(raw)
end)
end
-- ws-roblox: a model of 20000 parts (built here) through model/rbxm and model/rbxmx, and a .mesh decode
do
local Rbx = require("@formats/codecs/model/Rbx")
local Rbxm = require("@formats/model/rbxm")
local Rbxmx = require("@formats/model/rbxmx")
local RobloxMesh = require("@formats/model/robloxmesh")
local tree = Rbx.tree()
local folder = Rbx.add(tree, Rbx.instance("Folder", "Parts"))
for i = 1, 20000 do
local p = Rbx.add(folder, Rbx.instance("Part", "P" .. i))
Rbx.set(p, "CFrame", "CFrame", { i, i % 7, -i, 1, 0, 0, 0, 1, 0, 0, 0, 1 })
Rbx.set(p, "size", "Vector3", { 4, 1, 2 + i % 3 })
Rbx.set(p, "Color3uint8", "Color3uint8", { i % 256, 128, 255 - i % 256 })
Rbx.set(p, "Anchored", "Bool", i % 2 == 0)
Rbx.set(p, "Transparency", "Float32", (i % 4) / 4)
Rbx.set(p, "Material", "Enum", 256)
end
local bin = Rbxm.encode(tree) :: buffer
local xml = Rbxmx.encode(tree) :: buffer
bench("rbxm decode (20k parts)", 3, buffer.len(bin), function()
Rbxm.decode(Bytes.reader(bin))
end)
bench("rbxm encode (20k parts)", 3, buffer.len(bin), function()
Rbxm.encode(tree)
end)
bench("rbxmx decode (20k parts)", 3, buffer.len(xml), function()
Rbxmx.decode(Bytes.reader(xml))
end)
local M = require("@tests/gen/robloxmesh")
local mesh = buffer.fromstring(M.cases[#M.cases - 1].data)
bench("robloxmesh decode (v7, skinned)", 20, buffer.len(mesh), function()
RobloxMesh.decode(Bytes.reader(mesh))
end)
end
do
local Brotli = require("@formats/codecs/compress/Brotli")
local BB = require("@tests/gen/brotli_bench")
@@ -1143,3 +1177,81 @@ do
end
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
+34
View File
@@ -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))
+27
View File
@@ -0,0 +1,27 @@
-- tools/fixtures/_rbx_encode.luau: run by tools/fixtures/rbxmx.py under the luau CLI: decodes every file of
-- tests/gen/rbx_files (model/rbxm or model/rbxmx) and writes it back with both encoders; prints
-- "<file>/rbxm <hex>" and "<file>/rbxmx <hex>" lines for lune to read.
local Rbxm = require("@formats/model/rbxm")
local Rbxmx = require("@formats/model/rbxmx")
local Bytes = require("@formats/core/Bytes")
local Fx = require("@tests/gen/rbx_files")
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
for _, f in Fx.files do
local fmt: any = if f.xml then Rbxmx else Rbxm
local tree, err = fmt.decode(Bytes.reader(buffer.fromstring(f.data)))
if not tree then
error(f.name .. ": " .. tostring(err))
end
local a = assert(Rbxm.encode(tree))
print(f.name .. "/rbxm " .. hex(a))
local b = assert(Rbxmx.encode(tree))
print(f.name .. "/rbxmx " .. hex(b))
end
+30
View File
@@ -0,0 +1,30 @@
-- tools/fixtures/_robloxmesh_encode.luau: run by tools/fixtures/robloxmesh.py under the luau CLI: decodes every case of
-- tests/gen/robloxmesh and writes it back as versions 2.00 and 4.00; prints "<case>/<version> <hex>" lines for the
-- fixture's own reader.
local RobloxMesh = require("@formats/model/robloxmesh")
local Bytes = require("@formats/core/Bytes")
local Fx = require("@tests/gen/robloxmesh")
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
for _, c in Fx.cases do
if not c.unsupported then
local scene, err = RobloxMesh.decode(Bytes.reader(buffer.fromstring(c.data)))
if not scene then
error(c.name .. ": " .. tostring(err))
end
for _, v in { "2.00", "4.00" } do
local out, e = RobloxMesh.encode(scene, { version = v } :: any)
if not out then
error(c.name .. "/" .. v .. ": " .. tostring(e))
end
print(c.name .. "/" .. v .. " " .. hex(out))
end
end
end
+49
View File
@@ -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" }))
+49
View File
@@ -0,0 +1,49 @@
# Docs inputs for the Roblox guide page (tools/fixtures.py, tools/docs_check.py): a small place built by rojo 7.7 as
# .rbxl (binary) and .rbxlx (XML), and a skinned version 4.00 .mesh written by tools/fixtures/robloxmesh.py's spec
# writer.
# tests/gen/docs_roblox.luau { files = { [name] = bytes }, vars = { placeBytes, placeText, meshBytes } }
import importlib.util, json, os, random, shutil, tempfile
INPUTS = ["tools/docs_check.py", "tools/fixtures/robloxmesh.py"]
PLACE = {"name": "Obby", "tree": {
"$className": "DataModel",
"Workspace": {"$className": "Workspace",
"Spawn": {"$className": "SpawnLocation", "$properties": {"Size": [6, 1, 6], "Anchored": True}},
"Course": {"$className": "Model",
"Step1": {"$className": "Part", "$properties": {"Size": [4, 1, 4], "Position": [0, 4, 10], "Anchored": True, "Color": [1, 0, 0]}},
"Step2": {"$className": "Part", "$properties": {"Size": [4, 1, 4], "Position": [0, 8, 20], "Anchored": True, "Color": [0, 1, 0]}}}},
"Lighting": {"$className": "Lighting", "$properties": {"ClockTime": 14}},
"ServerScriptService": {"$className": "ServerScriptService",
"Main": {"$className": "Script", "$properties": {"Source": "print(\"hello from the obby\")\n"}}},
}}
def load(ctx, name):
spec = importlib.util.spec_from_file_location("docs_roblox_" + name, os.path.join(ctx.root, "tools", *name.split("/")))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def generate(ctx):
dc = load(ctx, "docs_check.py")
mesh = load(ctx, "fixtures/robloxmesh.py")
tmp = tempfile.mkdtemp(prefix="formats-docs-roblox-")
try:
proj = os.path.join(tmp, "place.project.json")
with open(proj, "w") as f:
json.dump(PLACE, f)
files = {}
for out in ("obby.rbxl", "obby.rbxlx"):
ctx.nix("rojo", ["rojo", "build", proj, "-o", os.path.join(tmp, out)])
with open(os.path.join(tmp, out), "rb") as f:
files[out] = f.read()
finally:
shutil.rmtree(tmp, ignore_errors=True)
rng = random.Random(5)
sv, sf = mesh.sphere(rng, 6, 10)
bones = mesh.make_bones(rng, 4)
nv, nf, subs, env, _, _ = mesh.make_skin(rng, sv, sf, bones, segs=10)
files["blob.mesh"], _ = mesh.write_v45("4.00", nv, nf, [0, len(nf)], bones, subs, env)
dc.emit_inputs(ctx, files, {"placeBytes": "obby.rbxl", "placeText": "obby.rbxlx", "meshBytes": "blob.mesh"})
+84
View File
@@ -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",
})
+218
View File
@@ -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)
+152
View File
@@ -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)
+156
View File
@@ -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})
+492
View File
@@ -0,0 +1,492 @@
# Roblox model / place fixtures (tools/fixtures.py) for model/rbxm (binary) and model/rbxmx (XML); one generator for
# both (named rbxmx so that both test filters, "rbxm" and "rbxmx", run it).
# Reference files: rojo 7.7 builds of a model project (a Folder with an explicitly typed property of every type, real
# instances with Refs / SharedStrings / attributes / tags, 120 parts with random and axis-aligned CFrames) and of a
# place project (DataModel services) to .rbxm / .rbxmx / .rbxl / .rbxlx; lune 0.11 (rbx-dom) builds a model of real
# properties of every type lune can set to .rbxm / .rbxmx; variants of the binary model with Zstandard chunks (zstd),
# raw chunks, and an unknown chunk + an unknown property type (python-lz4 / python-zstandard re-pack the chunks).
# Dumps: lune reads every reference file and prints each property the file holds (the names come from the XML twin)
# in a canonical form; the tests compare our decode against it.
# Ours: tools/fixtures/_rbx_encode.luau (luau CLI) decodes every file and writes it back as rbxm and rbxmx; lune
# reads our files and the dumps must equal the reference dumps (verdicts).
# tests/gen/rbx_files.luau { files = { { name, data, xml, place, dump = JSON text of { [path] = { class, props =
# { [name] = canon }, attrs, tags } } } } }
# tests/gen/rbx_ours.luau { { name, ok, detail } }
import json, math, os, random, shutil, struct, subprocess, tempfile
import xml.etree.ElementTree as ET
INPUTS = ["src/Formats/model/rbxm", "src/Formats/model/rbxmx", "src/Formats/codecs/model/Rbx", "tools/fixtures/_rbx_encode.luau"]
# ---------------------------------------------------------------------------------------------------- rojo projects
def cframe(pos, rows):
return {"CFrame": {"position": pos, "orientation": rows}}
def random_rotation(rng):
q = [rng.gauss(0, 1) for _ in range(4)]
n = math.sqrt(sum(c * c for c in q))
x, y, z, w = (c / n for c in q)
return [[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]
AXES = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (-1, 0, 0), (0, -1, 0), (0, 0, -1)]
def axis_rotation(rng):
while True:
r, u = rng.choice(AXES), rng.choice(AXES)
if any(a * b for a, b in zip(r, u)) == 0 and r != u and tuple(-c for c in r) != u:
break
k = (r[1] * u[2] - r[2] * u[1], r[2] * u[0] - r[0] * u[2], r[0] * u[1] - r[1] * u[0])
return [[r[0], u[0], k[0]], [r[1], u[1], k[1]], [r[2], u[2], k[2]]]
TYPES_FOLDER = {
"PString": {"String": "hello <world> & \"quotes\" é日"},
"PBinary": {"BinaryString": "AAECAwT/"},
"PBool": {"Bool": True},
"PInt32": {"Int32": -123},
"PInt64": {"Int64": -1234567890123},
"PFloat32": {"Float32": 1.5},
"PFloat64": {"Float64": 3.141592653589793},
"PUDim": {"UDim": [0.5, 10]},
"PUDim2": {"UDim2": [[0.5, 10], [0.25, -3]]},
"PRay": {"Ray": {"origin": [1, 2, 3], "direction": [4, 5, 6]}},
"PFaces": {"Faces": ["Right", "Top", "Front"]},
"PAxes": {"Axes": ["X", "Z"]},
"PBrickColor": {"BrickColor": 21},
"PColor3": {"Color3": [0.25, 0.5, 1]},
"PVector2": {"Vector2": [1.5, -2]},
"PVector3": {"Vector3": [1, -2, 3.25]},
"PVector3int16": {"Vector3int16": [-1, 2, 300]},
"PCFrame": cframe([1, 2, 3], [[0, 0, 1], [0, 1, 0], [-1, 0, 0]]),
"PCFrame2": cframe([4, 5, 6], [[0.36, 0.48, -0.8], [-0.8, 0.6, 0], [0.48, 0.64, 0.6]]),
"POptCFrame": {"OptionalCFrame": {"position": [1, 2, 3], "orientation": [[1, 0, 0], [0, 1, 0], [0, 0, 1]]}},
"POptNone": {"OptionalCFrame": None},
"PEnum": {"Enum": 3},
"PNumberSequence": {"NumberSequence": {"keypoints": [{"time": 0, "value": 1, "envelope": 0.5}, {"time": 0.5, "value": -3, "envelope": 0}, {"time": 1, "value": 2, "envelope": 0}]}},
"PColorSequence": {"ColorSequence": {"keypoints": [{"time": 0, "color": [1, 0, 0]}, {"time": 1, "color": [0, 0.5, 1]}]}},
"PNumberRange": {"NumberRange": [1, 5]},
"PRect": {"Rect": [[1, 2], [3, 4]]},
"PPhys": {"PhysicalProperties": {"density": 1, "friction": 0.5, "elasticity": 0.25, "frictionWeight": 2, "elasticityWeight": 3, "acousticAbsorption": 0.75}},
"PPhysDefault": {"PhysicalProperties": "Default"},
"PFont": {"Font": {"family": "rbxasset://fonts/families/Arial.json", "weight": "Bold", "style": "Italic"}},
"PUniqueId": {"UniqueId": "44b188dace632b4702e9c68d004815fc"},
"PUniqueId2": {"UniqueId": "7fb188dace632b4702e9c68d004815fd"},
"PSecurity": {"SecurityCapabilities": 12345},
"PContent": {"Content": {"Uri": "rbxassetid://1234"}},
"PContentNone": {"Content": "None"},
"PContentId": {"ContentId": "rbxassetid://99"},
"PShared": {"SharedString": "AAECAw=="},
}
def model_project(rng):
parts = {}
for i in range(120):
rows = axis_rotation(rng) if i % 3 else random_rotation(rng)
pos = [round(rng.uniform(-500, 500), 3) for _ in range(3)]
parts["P%03d" % i] = {"$className": "Part", "$properties": {
"CFrame": cframe(pos, rows),
"Size": [rng.choice([1, 2, 4, 0.5]), rng.uniform(0.2, 20), 2],
"Color": [rng.random(), rng.random(), rng.random()],
"Anchored": rng.random() < 0.5,
"Transparency": rng.choice([0, 0.25, 0.5]),
}}
tree = {
"$className": "Model",
"Types": {"$className": "Folder", "$properties": TYPES_FOLDER, "$attributes": {"Num": 5, "Str": "x", "Flag": True}},
"Types2": {"$className": "Folder", "$properties": {"PString": {"String": ""}, "PShared": {"SharedString": "AAECAw=="}, "PInt32": {"Int32": 2147483647}}},
"Base": {"$className": "Part", "$properties": {
"Size": [4, 1, 2], "CFrame": cframe([1, 2, 3], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]), "Color": [0.2, 0.4, 0.6],
"Anchored": True, "Material": {"Enum": 288},
"CustomPhysicalProperties": {"PhysicalProperties": {"density": 1, "friction": 0.5, "elasticity": 0.25, "frictionWeight": 2, "elasticityWeight": 3, "acousticAbsorption": 1}},
"UniqueId": {"UniqueId": "0123456789abcdef0011223344556677"},
"Capabilities": {"SecurityCapabilities": 12345},
"Tags": ["Enemy", "Boss"],
}, "$attributes": {"Rojo_Id": "base", "Hp": 100}},
"Pointer": {"$className": "ObjectValue", "$attributes": {"Rojo_Target_Value": "base"}},
"Empty": {"$className": "ObjectValue"},
"Code": {"$className": "Script", "$properties": {"Source": "print('hi')\n-- <xml> & \"quotes\" ]]>\n"}},
"Emitter": {"$className": "ParticleEmitter", "$properties": {
"Size": {"NumberSequence": {"keypoints": [{"time": 0, "value": 1, "envelope": 0}, {"time": 1, "value": 3, "envelope": 0}]}},
"Color": {"ColorSequence": {"keypoints": [{"time": 0, "color": [1, 1, 0]}, {"time": 1, "color": [0, 1, 1]}]}},
"Lifetime": {"NumberRange": [1, 2]}}},
"Gui": {"$className": "ScreenGui", "Frame": {"$className": "Frame", "$properties": {"Size": {"UDim2": [[0.5, 10], [0.25, -3]]}, "BackgroundColor3": [1, 0.5, 0]},
"Label": {"$className": "TextLabel", "$properties": {"Text": "label", "FontFace": {"Font": {"family": "rbxasset://fonts/families/Ubuntu.json", "weight": "Light", "style": "Normal"}}}}}},
"Mesh": {"$className": "MeshPart", "$properties": {"MeshContent": {"Content": {"Uri": "rbxassetid://777"}}}},
"Same": {"$className": "Folder"},
"Same2": {"$className": "Folder", "$properties": {"Name": {"String": "Same"}}},
"Parts": dict({"$className": "Folder"}, **parts),
}
return {"name": "Kit", "tree": tree}
def place_project():
return {"name": "Place", "tree": {
"$className": "DataModel",
"Workspace": {"$className": "Workspace", "$properties": {"Gravity": 100},
"Floor": {"$className": "Part", "$properties": {"Size": [64, 1, 64], "Anchored": True, "Color": [0.3, 0.6, 0.3]}}},
"Lighting": {"$className": "Lighting", "$properties": {"Ambient": [0.1, 0.2, 0.3], "ClockTime": 12.5, "Brightness": 2}},
"ReplicatedStorage": {"$className": "ReplicatedStorage", "Lib": {"$className": "ModuleScript", "$properties": {"Source": "return { answer = 42 }\n"}}},
"ServerScriptService": {"$className": "ServerScriptService", "Main": {"$className": "Script", "$properties": {"Source": "print(require(game.ReplicatedStorage.Lib).answer)\n"}}},
"StarterGui": {"$className": "StarterGui"},
}}
# ---------------------------------------------------------------------------------------------------- lune scripts
LUNE_GEN = r"""
local roblox = require("@lune/roblox")
local fs = require("@lune/fs")
local process = require("@lune/process")
local I = roblox.Instance.new
local V3, CF = roblox.Vector3.new, roblox.CFrame.new
local m = I("Model"); m.Name = "Kit"
local p = I("Part"); p.Name = "Base"; p.Parent = m
p.CFrame = CF(1, 2, 3) * roblox.CFrame.Angles(0.3, 0.2, 0.1)
p.Size = V3(4, 1, 2)
p.Color = roblox.Color3.fromRGB(10, 20, 255)
p.Anchored = true
p.Transparency = 0.25
p.Material = roblox.Enum.Material.Neon
p.CustomPhysicalProperties = roblox.PhysicalProperties.new(1, 0.5, 0.25, 2, 3)
p:SetAttribute("Hp", 5); p:SetAttribute("Label", "x"); p:SetAttribute("Pos", V3(1, 2, 3))
p:AddTag("Enemy"); p:AddTag("Boss")
m.PrimaryPart = p
local function add(cls, name, f) local i = I(cls); i.Name = name; i.Parent = m; f(i); return i end
add("StringValue", "Str", function(i) i.Value = "hello\nworld <&>" end)
add("IntValue", "Int", function(i) i.Value = -1234567890123 end)
add("NumberValue", "Num", function(i) i.Value = math.pi end)
add("ObjectValue", "Obj", function(i) i.Value = p end)
add("ObjectValue", "ObjNil", function(i) end)
add("RayValue", "Ray", function(i) i.Value = roblox.Ray.new(V3(1, 2, 3), V3(4, 5, 6)) end)
add("BrickColorValue", "Brick", function(i) i.Value = roblox.BrickColor.new(21) end)
add("Color3Value", "Col", function(i) i.Value = roblox.Color3.new(0.25, 0.5, 1) end)
add("CFrameValue", "Cf", function(i) i.Value = CF(5, 6, 7) * roblox.CFrame.Angles(0, math.pi / 2, 0) end)
add("Vector3Value", "Vec", function(i) i.Value = V3(1, -2, 3.25) end)
add("Sky", "Sky", function(i) i.StarCount = 1234 end)
add("Handles", "Handles", function(i) i.Faces = roblox.Faces.new(roblox.Enum.NormalId.Top, roblox.Enum.NormalId.Front) end)
add("ArcHandles", "Arcs", function(i) i.Axes = roblox.Axes.new(roblox.Enum.Axis.X, roblox.Enum.Axis.Z) end)
add("TerrainRegion", "Region", function(i) i.ExtentsMax = roblox.Vector3int16.new(-1, 2, 300) end)
add("Script", "Code", function(i) i.Source = "print('hi')\n" end)
add("Decal", "Decal", function(i) i.Texture = "rbxassetid://55" end)
local pe = I("ParticleEmitter"); pe.Parent = p
pe.Size = roblox.NumberSequence.new({roblox.NumberSequenceKeypoint.new(0, 1, 0.5), roblox.NumberSequenceKeypoint.new(1, 2)})
pe.Color = roblox.ColorSequence.new(roblox.Color3.new(1, 0, 0), roblox.Color3.new(0, 0, 1))
pe.Lifetime = roblox.NumberRange.new(1, 5)
local sg = I("ScreenGui"); sg.Parent = m
local fr = I("Frame"); fr.Parent = sg; fr.Size = roblox.UDim2.new(0.5, 10, 0.25, -3)
local ul = I("UIListLayout"); ul.Parent = fr; ul.Padding = roblox.UDim.new(0.1, 4)
local il = I("ImageLabel"); il.Parent = fr; il.SliceCenter = roblox.Rect.new(1, 2, 3, 4); il.ImageRectOffset = roblox.Vector2.new(1.5, -2)
local tl = I("TextLabel"); tl.Parent = fr; tl.FontFace = roblox.Font.new("rbxasset://fonts/families/Arial.json", roblox.Enum.FontWeight.Bold, roblox.Enum.FontStyle.Italic)
local sm = I("SpecialMesh"); sm.Parent = p; sm.MeshContent = roblox.Content.fromUri("rbxassetid://1234")
m.ModelMeshData = "\0\1\2\3"
local folder = I("Folder"); folder.Name = "Many"; folder.Parent = m
local seed = 12345
local function rnd() seed = (seed * 1103515245 + 12345) % 2147483648; return seed / 2147483648 end
for k = 1, 150 do
local q = I("Part"); q.Name = "Q" .. k; q.Parent = folder
local rot = if k % 2 == 0 then roblox.CFrame.Angles(0, math.pi / 2 * (k % 4), 0) else roblox.CFrame.Angles(rnd() * 6, rnd() * 6, rnd() * 6)
q.CFrame = CF(rnd() * 1000 - 500, rnd() * 100, rnd() * 1000 - 500) * rot
q.Size = V3(1 + rnd() * 10, 1, 1 + rnd() * 3)
q.Color = roblox.Color3.new(rnd(), rnd(), rnd())
q.Anchored = k % 3 == 0
if k % 5 == 0 then q.Transparency = rnd() end
end
local dir = process.args[1]
fs.writeFile(dir .. "/lune.rbxm", roblox.serializeModel({m}))
fs.writeFile(dir .. "/lune.rbxmx", roblox.serializeModel({m}, true))
"""
LUNE_DUMP = r"""
local roblox = require("@lune/roblox")
local fs = require("@lune/fs")
local serde = require("@lune/serde")
local process = require("@lune/process")
local req = serde.decode("json", fs.readFile(process.args[1]))
local ALIAS = { size = "Size", Color3uint8 = "Color", shape = "Shape", formFactorRaw = "FormFactor", MaxPlayersInternal = "MaxPlayers" }
local function hex(s)
return (string.gsub(s, ".", function(c) return string.format("%02x", string.byte(c)) end))
end
local paths = {}
local function walk(list, prefix)
local seen = {}
for _, inst in list do
local n = inst.Name
seen[n] = (seen[n] or 0) + 1
local p = prefix .. (if prefix == "" then "" else "/") .. n .. (if seen[n] > 1 then "#" .. seen[n] else "")
paths[inst] = p
walk(inst:GetChildren(), p)
end
end
local function bits(v, names)
local b, k = 0, 1
for _, n in names do
if v[n] then b += k end
k *= 2
end
return b
end
local function canon(v)
local t = typeof(v)
if v == nil then return { t = "nil" } end
if t == "string" then return { t = "string", s = hex(v) } end
if t == "boolean" then return { t = "bool", b = v } end
if t == "number" then return { t = "number", n = { v } } end
if t == "Vector3" or t == "Vector3int16" then return { t = t, n = { v.X, v.Y, v.Z } } end
if t == "Vector2" or t == "Vector2int16" then return { t = t, n = { v.X, v.Y } } end
if t == "CFrame" then return { t = t, n = { v:GetComponents() } } end
if t == "Color3" then return { t = t, n = { v.R, v.G, v.B } } end
if t == "UDim" then return { t = t, n = { v.Scale, v.Offset } } end
if t == "UDim2" then return { t = t, n = { v.X.Scale, v.X.Offset, v.Y.Scale, v.Y.Offset } } end
if t == "Rect" then return { t = t, n = { v.Min.X, v.Min.Y, v.Max.X, v.Max.Y } } end
if t == "NumberRange" then return { t = t, n = { v.Min, v.Max } } end
if t == "Ray" then return { t = t, n = { v.Origin.X, v.Origin.Y, v.Origin.Z, v.Direction.X, v.Direction.Y, v.Direction.Z } } end
if t == "NumberSequence" then
local n = {}
for _, k in v.Keypoints do table.insert(n, k.Time); table.insert(n, k.Value); table.insert(n, k.Envelope) end
return { t = t, n = n }
end
if t == "ColorSequence" then
local n = {}
for _, k in v.Keypoints do table.insert(n, k.Time); table.insert(n, k.Value.R); table.insert(n, k.Value.G); table.insert(n, k.Value.B) end
return { t = t, n = n }
end
if t == "PhysicalProperties" then return { t = t, n = { v.Density, v.Friction, v.Elasticity, v.FrictionWeight, v.ElasticityWeight, v.AcousticAbsorption } } end
if t == "BrickColor" then return { t = t, n = { v.Number } } end
if t == "EnumItem" then return { t = t, n = { v.Value } } end
if t == "Faces" then return { t = t, n = { bits(v, { "Right", "Top", "Back", "Left", "Bottom", "Front" }) } } end
if t == "Axes" then return { t = t, n = { bits(v, { "X", "Y", "Z" }) } } end
if t == "Font" then return { t = t, s = v.Family, n = { v.Weight.Value }, style = v.Style.Name } end
if t == "Instance" then return { t = t, s = paths[v] or "?" } end
if t == "Content" then
local st = v.SourceType.Name
return { t = t, kind = st, s = if st == "Uri" then v.Uri elseif st == "Object" then (paths[v.Object] or "?") else "" }
end
if t == "UniqueId" then return { t = t, s = string.lower((string.gsub(tostring(v), "[^%x]", ""))) } end
return { t = t, s = tostring(v) }
end
local out = {}
for _, f in req.files do
local data = fs.readFile(f.path)
paths = {}
local roots
local ok, err = pcall(function()
if f.place then roots = roblox.deserializePlace(data):GetChildren() else roots = roblox.deserializeModel(data) end
end)
if not ok then
out[f.key] = { error = tostring(err) }
else
walk(roots, "")
local d = {}
for inst, p in paths do
local want = f.names[p]
local e = { class = inst.ClassName, props = {} }
if want then
for _, name in want do
local okv, v = pcall(function() return inst[ALIAS[name] or name] end)
if okv then e.props[name] = canon(v) end
end
end
local attrs = {}
for k, v in inst:GetAttributes() do attrs[k] = canon(v) end
e.attrs = attrs
e.tags = inst:GetTags()
d[p] = e
end
out[f.key] = d
end
end
print(serde.encode("json", out))
"""
# ---------------------------------------------------------------------------------------------------- chunk re-packing
REPACK = r"""
import json, struct, sys, lz4.block, zstandard
req = json.load(sys.stdin)
data = bytes.fromhex(req["data"])
mode = req["mode"]
out = bytearray(data[:32])
p = 32
while p < len(data):
name = data[p:p + 4]
cl, ul, res = struct.unpack_from("<III", data, p + 4)
p += 16
if cl == 0:
body = data[p:p + ul]; p += ul
else:
body = lz4.block.decompress(data[p:p + cl], uncompressed_size=ul); p += cl
if mode == "unknown" and name == b"END\0":
# an unknown chunk, and a PROP of an unknown type (0x7f) for class 0 (n instances, 3 bytes each)
extra = b"just some bytes the format does not know"
out += b"ZZZZ" + struct.pack("<III", 0, len(extra), 0) + extra
n = req["class0"]
prop = struct.pack("<i", 0) + struct.pack("<I", 7) + b"Mystery" + bytes([0x7f]) + bytes((i * 7 + k) % 256 for i in range(n) for k in range(3))
out += b"PROP" + struct.pack("<III", 0, len(prop), 0) + prop
if name == b"END\0" or mode in ("raw", "unknown"):
out += name + struct.pack("<III", 0, len(body), 0) + body
else:
z = zstandard.ZstdCompressor(level=3, write_content_size=True).compress(body)
out += name + struct.pack("<III", len(z), len(body), 0) + z
sys.stdout.write(out.hex())
"""
# ---------------------------------------------------------------------------------------------------- names from XML
def xml_names(xml_bytes):
"""{ path: [property names] } from an rbxmx / rbxlx (the same path scheme as the lune dump)"""
root = ET.fromstring(xml_bytes)
names = {}
def walk(items, prefix):
seen = {}
for it in items:
props = it.find("Properties")
nm = None
plist = []
if props is not None:
for pr in props:
pn = pr.get("name")
if pn == "Name":
nm = pr.text or ""
elif pn is not None:
plist.append(pn)
nm = nm if nm is not None else it.get("class")
seen[nm] = seen.get(nm, 0) + 1
path = prefix + ("" if prefix == "" else "/") + nm + ("#%d" % seen[nm] if seen[nm] > 1 else "")
names[path] = ["Name"] + [n for n in plist if n not in ("AttributesSerialize", "Tags")]
walk(it.findall("Item"), path)
walk(root.findall("Item"), "")
return names
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="formats-rbx-")
try:
_generate(ctx, tmp)
finally:
shutil.rmtree(tmp, ignore_errors=True)
def lune(ctx, script, args, tmp):
path = os.path.join(tmp, "script_%d.luau" % abs(hash(script)))
with open(path, "w") as f:
f.write(script)
try:
return subprocess.run(["nix", "shell", "nixpkgs#lune", "-c", "lune", "run", path] + args, capture_output=True, check=True, cwd=tmp).stdout
except subprocess.CalledProcessError as e:
raise RuntimeError("lune: " + e.stderr.decode(errors="replace")[-3000:])
def _generate(ctx, tmp):
rng = random.Random(77)
with open(os.path.join(tmp, "model.project.json"), "w") as f:
json.dump(model_project(rng), f)
with open(os.path.join(tmp, "place.project.json"), "w") as f:
json.dump(place_project(), f)
for proj, outs in (("model", ("model.rbxm", "model.rbxmx")), ("place", ("place.rbxl", "place.rbxlx"))):
for o in outs:
ctx.nix("rojo", ["rojo", "build", os.path.join(tmp, proj + ".project.json"), "-o", os.path.join(tmp, o)])
lune(ctx, LUNE_GEN, [tmp], tmp)
def read(n):
with open(os.path.join(tmp, n), "rb") as f:
return f.read()
files = []
for name, twin, place in (("model.rbxm", "model.rbxmx", False), ("model.rbxmx", "model.rbxmx", False),
("place.rbxl", "place.rbxlx", True), ("place.rbxlx", "place.rbxlx", True),
("lune.rbxm", "lune.rbxmx", False), ("lune.rbxmx", "lune.rbxmx", False)):
files.append({"name": name, "data": read(name), "xml": name.endswith("x"), "place": place, "names": xml_names(read(twin))})
# re-packed variants of the binary model
model = read("model.rbxm")
n0 = None
for mode in ("zstd", "raw", "unknown"):
req = {"data": model.hex(), "mode": mode, "class0": n0 or 0}
if mode == "unknown":
# class 0's instance count: from the raw variant's first INST chunk
raw = bytes.fromhex(ctx.python(["lz4", "zstandard"], REPACK, input=json.dumps({"data": model.hex(), "mode": "raw", "class0": 0}).encode()).decode())
p = 32
while True:
size = struct.unpack_from("<I", raw, p + 8)[0]
if raw[p:p + 4] == b"INST":
body = raw[p + 16:p + 16 + size]
cid, nl = struct.unpack_from("<iI", body, 0)
if cid == 0:
n0 = struct.unpack_from("<I", body, 8 + nl + 1)[0]
break
p += 16 + size
req["class0"] = n0
data = bytes.fromhex(ctx.python(["lz4", "zstandard"], REPACK, input=json.dumps(req).encode()).decode())
fn = "model-%s.rbxm" % mode
with open(os.path.join(tmp, fn), "wb") as f:
f.write(data)
files.append({"name": fn, "data": data, "xml": False, "place": False, "names": files[0]["names"]})
for f in files:
f["path"] = os.path.join(tmp, f["name"])
f["key"] = f["name"]
req = {"files": [{"key": f["key"], "path": f["path"], "place": f["place"], "names": f["names"]} for f in files]}
with open(os.path.join(tmp, "dump.json"), "w") as fh:
json.dump(req, fh)
dumps = json.loads(lune(ctx, LUNE_DUMP, [os.path.join(tmp, "dump.json")], tmp))
for f in files:
d = dumps[f["key"]]
assert "error" not in d, (f["name"], d)
f["dump"] = d
# the dumps as JSON text (a deep Luau table literal is too complex for luau-analyze)
ctx.emit("rbx_files", {"files": [dict({k: f[k] for k in ("name", "data", "xml", "place")}, dump=json.dumps(f["dump"], sort_keys=True)) for f in files]})
# ours: every file decoded and written back as rbxm and rbxmx, read by lune
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_rbx_encode.luau")], capture_output=True, cwd=ctx.root)
if enc.returncode != 0:
raise RuntimeError("_rbx_encode: " + enc.stderr.decode(errors="replace")[-3000:])
ours = []
byname = {f["name"]: f for f in files}
for line in enc.stdout.decode().split("\n"):
if not line.strip():
continue
label, hexdata = line.split(" ", 1)
src, fmt = label.split("/")
fn = "ours-%s.%s" % (src.replace(".", "_"), ("rbxl" if byname[src]["place"] else "rbxm") + ("x" if fmt == "rbxmx" else ""))
with open(os.path.join(tmp, fn), "wb") as fh:
fh.write(bytes.fromhex(hexdata.strip()))
ours.append((label, fn, byname[src]))
req = {"files": [{"key": label, "path": os.path.join(tmp, fn), "place": f["place"], "names": f["names"]} for label, fn, f in ours]}
with open(os.path.join(tmp, "dump2.json"), "w") as fh:
json.dump(req, fh)
got = json.loads(lune(ctx, LUNE_DUMP, [os.path.join(tmp, "dump2.json")], tmp))
verdicts = []
for label, fn, f in ours:
d = got[label]
ok, detail = True, "%d instances" % len(d)
if "error" in d:
ok, detail = False, "lune: " + d["error"][:300]
else:
want = f["dump"]
if set(d) != set(want):
ok, detail = False, "instance paths differ: %s" % sorted(set(d) ^ set(want))[:5]
else:
for path in sorted(want):
a, b = want[path], d[path]
if a["class"] != b["class"]:
ok, detail = False, "%s: class %s, want %s" % (path, b["class"], a["class"])
break
diff = [k for k in a["props"] if a["props"][k] != b["props"].get(k)]
if diff:
k = diff[0]
ok, detail = False, "%s.%s: %s, want %s" % (path, k, json.dumps(b["props"].get(k))[:200], json.dumps(a["props"][k])[:200])
break
if a["attrs"] != b["attrs"] or sorted(a["tags"]) != sorted(b["tags"]):
ok, detail = False, "%s: attributes / tags differ" % path
break
verdicts.append({"name": label, "ok": ok, "detail": detail})
ctx.emit("rbx_ours", verdicts)
+461
View File
@@ -0,0 +1,461 @@
# Roblox FileMesh fixtures (tools/fixtures.py) for model/robloxmesh. No reference tool reads .mesh files, so this
# generator is an independent writer + reader written from the spec (MaximumADHD's "Roblox Mesh Format" notes,
# devforum 326114): it writes meshes of every version (1.00 / 1.01 ASCII, 2.00 with 36- and 40-byte vertices, 3.00 /
# 3.01 with LODs, 4.00 / 4.01 with bones, skinning and several subsets, 5.00 with a FACS blob, 6.00 / 7.00 chunked
# with LODS, SKINNING, FACS and HSRAVIS chunks, a 7.00 Draco COREMESH) with the values they hold, and reads our
# encoder's output (tools/fixtures/_robloxmesh_encode.luau under the luau CLI) back, as verdicts.
# tests/gen/robloxmesh.luau { cases = { { name, data, version, vertices, faces, pos, nrm, uv, tan?, col?, lods =
# { idx crc ... }, joints?, weights?, bones? = { { name, parent, cf } }, facs?, chunks?,
# unsupported? } }, ours = { { name, ok, detail } } }
import json, math, os, random, shutil, struct, subprocess, zlib
INPUTS = ["src/Formats/model/robloxmesh", "tools/fixtures/_robloxmesh_encode.luau"]
def f32(x):
return struct.unpack("<f", struct.pack("<f", x))[0]
def pk(fmt, vals):
return struct.pack("<%d%s" % (len(vals), fmt), *vals)
def crc(b):
return zlib.crc32(b)
def sbyte(v):
return v - 256 if v >= 128 else v
# ---------------------------------------------------------------------------------------------------- geometry
def sphere(rng, rings, segs, radius=2.0):
verts, faces = [], []
for i in range(rings + 1):
th = math.pi * i / rings
for j in range(segs + 1):
ph = 2 * math.pi * j / segs
n = [math.sin(th) * math.cos(ph), math.cos(th), math.sin(th) * math.sin(ph)]
verts.append({
"pos": [f32(c * radius + rng.uniform(-0.01, 0.01)) for c in n],
"nrm": [f32(c) for c in n],
"uv": [f32(j / segs), f32(i / rings)],
"tan": [rng.randrange(-127, 128) for _ in range(3)] + [rng.choice((-127, 127))],
"col": [rng.randrange(256) for _ in range(4)],
})
for i in range(rings):
for j in range(segs):
a = i * (segs + 1) + j
b = a + segs + 1
faces += [(a, b, a + 1), (a + 1, b, b + 1)]
return verts, faces
def vbytes(v, size):
out = pk("f", v["pos"] + v["nrm"] + v["uv"]) + bytes(t & 255 for t in v["tan"])
if size >= 40:
out += bytes(v["col"])
return out
def fbytes(faces):
return b"".join(pk("I", list(f)) for f in faces)
def tangent_f32(t):
return [f32(max(-1.0, min(1.0, c / 127))) for c in t]
def expect_core(verts, faces, lods, colors, tangents=True):
exp = {
"vertices": len(verts), "faces": len(faces),
"pos": crc(b"".join(pk("f", v["pos"]) for v in verts)),
"nrm": crc(b"".join(pk("f", v["nrm"]) for v in verts)),
"uv": crc(b"".join(pk("f", v["uv"]) for v in verts)),
"lods": [crc(fbytes(faces[lods[k]:lods[k + 1]])) for k in range(len(lods) - 1)],
}
if tangents:
exp["tan"] = crc(b"".join(pk("f", tangent_f32(v["tan"])) for v in verts))
if colors:
exp["col"] = crc(b"".join(bytes(v["col"]) for v in verts))
return exp
# ---------------------------------------------------------------------------------------------------- bones / skinning
def rot_y(a):
c, s = math.cos(a), math.sin(a)
return [c, 0, s, 0, 1, 0, -s, 0, c]
def make_bones(rng, n):
bones = []
for i in range(n):
parent = None if i == 0 else rng.randrange(i)
r = rot_y(rng.uniform(-3, 3))
cf = [f32(x) for x in r + [rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(-2, 2)]]
bones.append({"name": "Bone%02d" % i if i else "Root", "parent": parent, "cf": cf, "culling": f32(rng.uniform(0, 5)), "lodParent": 0xFFFF})
return bones
def make_skin(rng, verts, faces, bones, segs=12):
"""influences per vertex (1..4 bones from a window that moves with the sphere ring, so a third of the faces needs
at most ~20 bones), then subsets by face thirds; vertices are duplicated per subset (the format needs contiguous
vertex ranges). Returns new verts, faces, subsets, envelopes, the expected global joints / weights"""
nb = len(bones)
infl = []
for v in range(len(verts)):
ring = v // (segs + 1)
window = [(ring * 4 + k) % nb for k in range(min(8, nb))]
k = rng.randrange(1, 5)
bs = rng.sample(window, min(k, len(window)))
w = [rng.randrange(1, 100) for _ in bs]
tot = sum(w)
wb = [x * 255 // tot for x in w]
wb[0] += 255 - sum(wb)
infl.append(list(zip(bs, wb)))
nverts, nfaces, subsets, env, joints, weights = [], [], [], [], [], []
chunk = max(1, len(faces) // 3)
for s0 in range(0, len(faces), chunk):
sub_faces = faces[s0:s0 + chunk]
used = []
for f in sub_faces:
for v in f:
if v not in used:
used.append(v)
sub_bones = sorted({b for v in used for b, _ in infl[v]})
assert len(sub_bones) <= 26
loc = {b: i for i, b in enumerate(sub_bones)}
remap = {}
vb = len(nverts)
for v in used:
remap[v] = len(nverts)
nverts.append(verts[v])
pairs = infl[v] + [(None, 0)] * (4 - len(infl[v]))
env.append(bytes(loc[b] if b is not None else 0 for b, _ in pairs) + bytes(w for _, w in pairs))
joints.append([b if b is not None else 0 for b, _ in pairs])
weights.append([w for _, w in pairs])
for f in sub_faces:
nfaces.append(tuple(remap[v] for v in f))
subsets.append({"facesBegin": s0, "facesLength": len(sub_faces), "vertsBegin": vb, "vertsLength": len(nverts) - vb, "bones": sub_bones})
return nverts, nfaces, subsets, env, joints, weights
def bone_bytes(bones):
names = b""
out = b""
for b in bones:
idx = len(names)
names += b["name"].encode() + b"\0"
out += struct.pack("<IHHf", idx, 0xFFFF if b["parent"] is None else b["parent"], b["lodParent"], b["culling"]) + pk("f", b["cf"])
return out, names
def subset_bytes(subsets):
out = b""
for s in subsets:
ids = s["bones"] + [0xFFFF] * (26 - len(s["bones"]))
out += struct.pack("<IIIII", s["facesBegin"], s["facesLength"], s["vertsBegin"], s["vertsLength"], len(s["bones"])) + pk("H", ids)
return out
# ---------------------------------------------------------------------------------------------------- writers
def write_v1(version, verts, faces):
scale = 2.0 if version == "1.00" else 1.0
parts = []
exp_verts = []
for f in faces:
for vi in f:
v = verts[vi]
fp = [c * scale for c in v["pos"]]
fv = 1 - v["uv"][1]
parts.append("[%r,%r,%r][%r,%r,%r][%r,%r,0]" % tuple(fp + v["nrm"] + [v["uv"][0], fv]))
exp_verts.append({"pos": [f32(c * (0.5 if version == "1.00" else 1)) for c in fp], "nrm": v["nrm"], "uv": [v["uv"][0], f32(1 - fv)], "tan": [0, 0, 0, 0], "col": [255] * 4})
data = ("version %s\n%d\n" % (version, len(faces)) + "".join(parts)).encode()
exp_faces = [(3 * i, 3 * i + 1, 3 * i + 2) for i in range(len(faces))]
return data, expect_core(exp_verts, exp_faces, [0, len(faces)], False, tangents=False)
def write_v2(verts, faces, colors):
vs = 40 if colors else 36
data = b"version 2.00\n" + struct.pack("<HBBII", 12, vs, 12, len(verts), len(faces)) + b"".join(vbytes(v, vs) for v in verts) + fbytes(faces)
return data, expect_core(verts, faces, [0, len(faces)], colors)
def write_v3(version, verts, faces, lods):
data = (("version %s\n" % version).encode() + struct.pack("<HBBHHII", 16, 40, 12, 4, len(lods), len(verts), len(faces))
+ b"".join(vbytes(v, 40) for v in verts) + fbytes(faces) + pk("I", lods))
return data, expect_core(verts, faces, lods, True)
def write_v45(version, verts, faces, lods, bones, subsets, env, facs=None):
bb, names = bone_bytes(bones)
head = struct.pack("<HHIIHHIHBB", 32 if version == "5.00" else 24, 3, len(verts), len(faces), len(lods), len(bones), len(names), len(subsets), 1, 0)
if version == "5.00":
head += struct.pack("<II", 1 if facs else 0, len(facs or b""))
data = (("version %s\n" % version).encode() + head + b"".join(vbytes(v, 40) for v in verts) + (b"".join(env) if bones else b"")
+ fbytes(faces) + pk("I", lods) + bb + names + subset_bytes(subsets) + (facs or b""))
return data, expect_core(verts, faces, lods, True)
def chunk(name, version, body):
return name.ljust(8, b"\0") + struct.pack("<II", version, len(body)) + body
def write_v67(version, verts, faces, lods, bones, subsets, env, facs, hsr, draco=False):
if draco:
core = chunk(b"COREMESH", 2, struct.pack("<I", 16) + bytes(range(16)))
else:
core = chunk(b"COREMESH", 1, struct.pack("<I", len(verts)) + b"".join(vbytes(v, 40) for v in verts) + struct.pack("<I", len(faces)) + fbytes(faces))
lodc = chunk(b"LODS", 1, struct.pack("<HBI", 3, 1, len(lods)) + pk("I", lods))
bb, names = bone_bytes(bones)
skin = chunk(b"SKINNING", 1, struct.pack("<I", len(verts)) + b"".join(env) + struct.pack("<I", len(bones)) + bb + struct.pack("<I", len(names)) + names
+ struct.pack("<I", len(subsets)) + subset_bytes(subsets))
out = ("version %s\n" % version).encode() + core + lodc + skin
if facs:
out += chunk(b"FACS", 1, struct.pack("<I", len(facs)) + facs)
if hsr:
out += chunk(b"HSRAVIS", 1, struct.pack("<I", 10) + b"\x55\x01")
return out, expect_core(verts, faces, lods, True)
def skin_expect(exp, bones, joints, weights):
exp["joints"] = crc(b"".join(pk("H", j) for j in joints))
exp["weights"] = crc(b"".join(bytes(w) for w in weights))
exp["bones"] = [dict({"name": b["name"], "cf": b["cf"], "culling": b["culling"]}, **({"parent": b["parent"]} if b["parent"] is not None else {})) for b in bones]
return exp
# ---------------------------------------------------------------------------------------------------- reader (for our output)
def read_mesh(data):
line, rest = data.split(b"\n", 1)
version = line.decode().split()[1]
if version == "2.00":
hs, vs, fs, nv, nf = struct.unpack_from("<HBBII", rest, 0)
p = hs
nb = nsub = names_size = 0
lods = [0, nf]
elif version == "4.00":
hs, lod_type, nv, nf, nl, nb, names_size, nsub, hq, _ = struct.unpack_from("<HHIIHHIHBB", rest, 0)
vs, fs, p = 40, 12, hs
else:
raise ValueError("version " + version)
verts = []
for i in range(nv):
q = p + i * vs
v = struct.unpack_from("<8f", rest, q)
t = [sbyte(c) for c in rest[q + 32:q + 36]]
col = list(rest[q + 36:q + 40]) if vs >= 40 else [255] * 4
verts.append({"pos": list(v[:3]), "nrm": list(v[3:6]), "uv": list(v[6:8]), "tan": t, "col": col})
p += nv * vs
env = []
if version == "4.00" and nb > 0:
env = [rest[p + 8 * i:p + 8 * i + 8] for i in range(nv)]
p += 8 * nv
faces = [struct.unpack_from("<3I", rest, p + 12 * i) for i in range(nf)]
p += 12 * nf
if version == "4.00":
lods = list(struct.unpack_from("<%dI" % nl, rest, p))
p += 4 * nl
bones = []
for i in range(nb):
ni, par, lp, cull = struct.unpack_from("<IHHf", rest, p + 60 * i)
bones.append({"ni": ni, "parent": None if par == 0xFFFF else par, "cf": list(struct.unpack_from("<12f", rest, p + 60 * i + 12))})
p += 60 * nb
names = rest[p:p + names_size]
for b in bones:
b["name"] = names[b["ni"]:].split(b"\0", 1)[0].decode()
p += names_size
subsets = []
for i in range(nsub):
fb, fl, vb, vl, n = struct.unpack_from("<5I", rest, p + 72 * i)
ids = list(struct.unpack_from("<26H", rest, p + 72 * i + 20))[:n]
subsets.append({"facesBegin": fb, "facesLength": fl, "vertsBegin": vb, "vertsLength": vl, "bones": ids})
p += 72 * nsub
assert p == len(rest), "trailing bytes: %d of %d" % (p, len(rest))
return {"version": version, "verts": verts, "faces": faces, "lods": lods, "bones": bones, "subsets": subsets, "env": env}
def corners(m, lod=0):
"""the LOD's triangles as tuples of vertex values (position, uv) - comparable across vertex duplication"""
out = []
for f in m["faces"][m["lods"][lod]:m["lods"][lod + 1]]:
out.append(tuple(tuple(m["verts"][v]["pos"] + m["verts"][v]["uv"]) for v in f))
return out
def vertex_influences(m):
"""per vertex: { global bone: weight byte } through the subsets"""
infl = [None] * len(m["verts"])
for s in m["subsets"]:
assert len(s["bones"]) <= 26
for v in range(s["vertsBegin"], s["vertsBegin"] + s["vertsLength"]):
e = m["env"][v]
d = {}
for k in range(4):
if e[4 + k]:
d[s["bones"][e[k]]] = d.get(s["bones"][e[k]], 0) + e[4 + k]
assert sum(e[4:8]) == 255, "weights sum to %d" % sum(e[4:8])
infl[v] = d
return infl
def check_ours(src, out):
"""our re-encoding of a fixture (src: the original read as a v4-style record) -> ok, detail"""
a, b = src, out
if len(b["verts"]) < 1:
return False, "no vertices"
if sorted(corners(a)) != sorted(corners(b)):
return False, "LOD 0 triangles differ"
if b["version"] == "4.00":
if len(a["lods"]) != len(b["lods"]) and not b["bones"]:
return False, "LOD count %d, want %d" % (len(b["lods"]), len(a["lods"]))
if not b["bones"]:
for k in range(len(a["lods"]) - 1):
if sorted(corners(a, k)) != sorted(corners(b, k)):
return False, "LOD %d differs" % k
if a["bones"]:
if [x["name"] for x in a["bones"]] != [x["name"] for x in b["bones"]] or [x["parent"] for x in a["bones"]] != [x["parent"] for x in b["bones"]]:
return False, "bones differ"
for x, y in zip(a["bones"], b["bones"]):
if any(abs(p - q) > 1e-4 for p, q in zip(x["cf"], y["cf"])):
return False, "bone %s transform differs" % x["name"]
ia, ib = vertex_influences(a), vertex_influences(b)
key = lambda m, i: tuple(m["verts"][i]["pos"] + m["verts"][i]["uv"])
want = {key(a, i): ia[i] for i in range(len(a["verts"]))}
for i in range(len(b["verts"])):
w = want.get(key(b, i))
if w is None or ib[i] is None:
return False, "vertex %d has no influences" % i
if set(w) != set(ib[i]) or any(abs(w[j] - ib[i][j]) > 1 for j in w):
return False, "vertex %d influences %r, want %r" % (i, ib[i], w)
return True, "%d vertices, %d faces, %d bones, %d subsets" % (len(b["verts"]), len(b["faces"]), len(b["bones"]), len(b["subsets"]))
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def generate(ctx):
rng = random.Random(1337)
cases = []
sv, sf = sphere(rng, 8, 12)
for version in ("1.00", "1.01"):
data, exp = write_v1(version, sv, sf[:60])
cases.append(dict(exp, name="v" + version, data=data, version=version))
for colors in (False, True):
data, exp = write_v2(sv, sf, colors)
cases.append(dict(exp, name="v2.00-%d" % (40 if colors else 36), data=data, version="2.00"))
lods = [0, len(sf) // 2, len(sf) * 3 // 4, len(sf)]
for version in ("3.00", "3.01"):
data, exp = write_v3(version, sv, sf, lods)
cases.append(dict(exp, name="v" + version, data=data, version=version))
# skinned: 6 bones (one subset of all of them) and 40 bones (several subsets of up to 26)
bones6 = make_bones(rng, 6)
bones40 = make_bones(rng, 40)
for version in ("4.00", "4.01", "5.00"):
for bones in (bones6, bones40):
nv, nf, subs, env, joints, weights = make_skin(rng, sv, sf, bones)
lods2 = [0, len(nf)]
facs = bytes(rng.randrange(256) for _ in range(77)) if version == "5.00" else None
data, exp = write_v45(version, nv, nf, lods2, bones, subs, env, facs)
exp = skin_expect(exp, bones, joints, weights)
if facs:
exp["facs"] = crc(facs)
cases.append(dict(exp, name="v%s-%dbones" % (version, len(bones)), data=data, version=version))
# unskinned 4.00 with LODs
data, exp = write_v45("4.00", sv, sf, lods, [], [], [])
cases.append(dict(exp, name="v4.00-lods", data=data, version="4.00"))
for version in ("6.00", "7.00"):
nv, nf, subs, env, joints, weights = make_skin(rng, sv, sf, bones40)
facs = bytes(rng.randrange(256) for _ in range(40))
data, exp = write_v67(version, nv, nf, [0, len(nf) // 2, len(nf)], bones40, subs, env, facs, hsr=True)
exp = skin_expect(exp, bones40, joints, weights)
exp["facs"] = crc(facs)
exp["chunks"] = ["HSRAVIS"]
cases.append(dict(exp, name="v" + version, data=data, version=version))
data, _ = write_v67("7.00", sv, sf, [0, len(sf)], [], [], [], None, hsr=False, draco=True)
cases.append({"name": "v7.00-draco", "data": data, "version": "7.00", "unsupported": True})
ctx.emit("robloxmesh", {"cases": cases})
# ours: every decodable case re-encoded as 2.00 and 4.00, read back here
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_robloxmesh_encode.luau")], capture_output=True, cwd=ctx.root)
if enc.returncode != 0:
raise RuntimeError("_robloxmesh_encode: " + enc.stderr.decode(errors="replace")[-3000:])
originals = {}
byname = {c["name"]: c for c in cases}
ours = []
for line in enc.stdout.decode().split("\n"):
if not line.strip():
continue
label, hexdata = line.split(" ", 1)
name, version = label.rsplit("/", 1)
try:
out = read_mesh(bytes.fromhex(hexdata.strip()))
if name not in originals:
originals[name] = read_original(byname[name])
ok, detail = check_ours(originals[name], out)
except Exception as e: # a reader failure is a verdict, not a fixture error
ok, detail = False, "read: %r" % e
ours.append({"name": label, "ok": ok, "detail": detail})
ctx.emit("robloxmesh", {"cases": cases, "ours": ours})
def read_original(case):
"""a fixture case as the record read_mesh gives (version 1 / 3 / 5 / 6 / 7 are rewritten through the 4.00 shape)"""
data = case["data"]
line, rest = data.split(b"\n", 1)
version = line.decode().split()[1]
if version in ("1.00", "1.01"):
text = rest.decode().split("\n", 1)[1]
vals = [float(x) for x in text.replace("][", ",").strip("[]").split(",")]
scale = 0.5 if version == "1.00" else 1
verts = []
for i in range(0, len(vals), 9):
verts.append({"pos": [f32(c * scale) for c in vals[i:i + 3]], "nrm": [f32(c) for c in vals[i + 3:i + 6]], "uv": [f32(vals[i + 6]), f32(1 - vals[i + 7])]})
nf = len(verts) // 3
return {"version": version, "verts": verts, "faces": [(3 * i, 3 * i + 1, 3 * i + 2) for i in range(nf)], "lods": [0, nf], "bones": [], "subsets": [], "env": []}
if version == "2.00":
return read_mesh(data)
if version in ("3.00", "3.01"):
hs, vs, fs, ls, nl, nv, nf = struct.unpack_from("<HBBHHII", rest, 0)
head = struct.pack("<HHIIHHIHBB", 24, 0, nv, nf, nl, 0, 0, 0, 0, 0)
return read_mesh(b"version 4.00\n" + head + rest[hs:])
if version in ("4.00", "4.01", "5.00"):
hs = struct.unpack_from("<H", rest, 0)[0]
fields = list(struct.unpack_from("<HHIIHHIHBB", rest, 0))
fields[0] = 24
body = rest[hs:]
if version == "5.00":
body = body[:len(body) - struct.unpack_from("<I", rest, 28)[0]]
return read_mesh(b"version 4.00\n" + struct.pack("<HHIIHHIHBB", *fields) + body)
# 6.00 / 7.00: chunks to the 4.00 layout
p, parts = 0, {}
while p < len(rest):
name = rest[p:p + 8].rstrip(b"\0").decode()
cv, size = struct.unpack_from("<II", rest, p + 8)
parts[name] = rest[p + 16:p + 16 + size]
p += 16 + size
core = parts["COREMESH"]
nv = struct.unpack_from("<I", core, 0)[0]
verts = core[4:4 + 40 * nv]
nf = struct.unpack_from("<I", core, 4 + 40 * nv)[0]
faces = core[8 + 40 * nv:8 + 40 * nv + 12 * nf]
lc = parts["LODS"]
nl = struct.unpack_from("<I", lc, 3)[0]
lods = lc[7:7 + 4 * nl]
sk = parts["SKINNING"]
q = 4
env = sk[q:q + 8 * nv]
q += 8 * nv
nb = struct.unpack_from("<I", sk, q)[0]
q += 4
bones = sk[q:q + 60 * nb]
q += 60 * nb
ns = struct.unpack_from("<I", sk, q)[0]
names = sk[q + 4:q + 4 + ns]
q += 4 + ns
nsub = struct.unpack_from("<I", sk, q)[0]
subs = sk[q + 4:q + 4 + 72 * nsub]
head = struct.pack("<HHIIHHIHBB", 24, 3, nv, nf, nl, nb, ns, nsub, 1, 0)
return read_mesh(b"version 4.00\n" + head + verts + env + faces + lods + bones + names + subs)
+244
View File
@@ -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)