merge ws/roblox (codecs/compress/Lz4 for Anvil LZ4 chunks); registry regenerated

This commit is contained in:
4DBug committed 2026-10-31 14:38:23 -05:00
commit 09354cbd12
23 files changed
+5959 -1

No files matched your search

+14 -1
View File
@@ -1,7 +1,7 @@
-- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs.
-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus), tools/fixtures/png.py (1024 x 768 images), tools/fixtures/mp3.py,
-- tools/fixtures/opus.py (3 s stereo files; MB/s of f32 output, 48 kHz stereo f32 is 0.384 MB/s of real time),
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma (*_bench corpora), fonts
-- tools/fixtures/flac.py; wav encodes / decodes a generated tone; zstd / brotli / bzip2 / lzma / lz4 (*_bench corpora), fonts
-- (glyphs per second), json / xml / yaml, jpeg / gif / tiff / qoi / tga / pnm / hdr and ImageOps.
local Deflate = require("@formats/codecs/compress/Deflate")
local Crc32 = require("@formats/core/Crc32")
@@ -236,6 +236,19 @@ do
Zstd.decompress(z19, nil, nil, { verify = false })
end)
end
do
local Lz4 = require("@formats/codecs/compress/Lz4")
local LB = require("@tests/gen/lz4_bench")
local lz = buffer.fromstring(LB.data)
local raw = assert(Lz4.decompress(lz, nil, nil, LB.size))
assert(Crc32.of(raw) == LB.crc, "lz4 bench corpus mismatch")
bench("lz4 block decompress (hc9)", 5, LB.size, function()
Lz4.decompress(lz, nil, nil, LB.size)
end)
bench("lz4 block compress", 3, LB.size, function()
Lz4.compress(raw)
end)
end
do
local Brotli = require("@formats/codecs/compress/Brotli")
local BB = require("@tests/gen/brotli_bench")
+13
View File
@@ -0,0 +1,13 @@
-- tools/fixtures/_lz4_encode.luau: run by tools/fixtures/lz4.py under the luau CLI: compresses every corpus of
-- tests/gen/lz4_corpora with codecs/compress/Lz4 and prints "<name> <hex>" lines for the reference to decompress.
local Lz4 = require("@formats/codecs/compress/Lz4")
local C = require("@tests/gen/lz4_corpora")
for name, data in C do
local b = assert(Lz4.compress(data))
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
print(name .. " " .. table.concat(t))
end
+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
+90
View File
@@ -0,0 +1,90 @@
# LZ4 block fixtures (tools/fixtures.py): deterministic corpora compressed by the reference (python-lz4, the lz4
# library: fast mode at several accelerations, and HC at levels 4 / 9 / 12), plus our own encoder's blocks
# (tools/fixtures/_lz4_encode.luau under the luau CLI) decompressed by the reference, as verdicts.
# tests/gen/lz4.luau { corpora = { [name] = bytes }, cases = { { name, corpus, data } }, ours = { { name, ok } } }
# tests/gen/lz4_bench.luau { size, crc, data (lz4 HC 9 block), raw }
import json, os, random, shutil, subprocess, zlib
INPUTS = ["src/Formats/codecs/compress/Lz4.luau", "tools/fixtures/_lz4_encode.luau"]
REF = r"""
import json, sys, lz4.block
req = json.load(sys.stdin)
out = {}
if req["op"] == "compress":
for name, hexdata in req["corpora"].items():
data = bytes.fromhex(hexdata)
res = {}
for acc in (1, 4, 16):
res["fast%d" % acc] = lz4.block.compress(data, mode="fast", acceleration=acc, store_size=False).hex()
for lv in (4, 9, 12):
res["hc%d" % lv] = lz4.block.compress(data, mode="high_compression", compression=lv, store_size=False).hex()
out[name] = res
else:
for name, item in req["blocks"].items():
try:
got = lz4.block.decompress(bytes.fromhex(item["data"]), uncompressed_size=item["size"])
out[name] = got.hex() == item["want"]
except Exception as e:
out[name] = False
print(json.dumps(out))
"""
def corpora(rng):
base = os.path.dirname(os.__file__)
text = bytearray()
for name in sorted(os.listdir(base)):
if name.endswith(".py"):
with open(os.path.join(base, name), "rb") as f:
text += f.read()
if len(text) >= 300000:
break
text = bytes(text[:300000])
far = rng.randbytes(9000)
return {
"empty": b"",
"one": b"a",
"twelve": b"abcabcabcabc",
"thirteen": b"abcabcabcabca",
"short": b"hello, hello, hello lz4 world\n",
"text": text[:150000],
"random": rng.randbytes(20000),
"runs": b"abc" * 4000 + b"\0" * 70000 + bytes(range(256)) * 40 + b"z" * 300,
"zeros": b"\0" * 100000,
"far": far + rng.randbytes(60000) + far,
"binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(60000)),
"longlit": rng.randbytes(1000) + b"q" * 1000 + rng.randbytes(300),
}
def luau_cmd():
exe = shutil.which("luau")
return [exe] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau"]
def generate(ctx):
rng = random.Random(41)
cs = corpora(rng)
ref = json.loads(ctx.python(["lz4"], REF, input=json.dumps({"op": "compress", "corpora": {k: v.hex() for k, v in cs.items()}}).encode()))
cases = []
for name, res in ref.items():
for mode, hexdata in res.items():
cases.append({"name": "%s/%s" % (name, mode), "corpus": name, "data": bytes.fromhex(hexdata)})
# our encoder's blocks, read back by the reference
ctx.emit("lz4_corpora", cs)
enc = subprocess.run(luau_cmd() + [os.path.join(ctx.root, "tools", "fixtures", "_lz4_encode.luau")], capture_output=True, check=True, cwd=ctx.root).stdout.decode()
blocks = {}
for line in enc.split("\n"):
if line.strip():
name, hexdata = line.split(" ", 1)
blocks[name] = {"data": hexdata.strip(), "size": len(cs[name]), "want": cs[name].hex()}
verdict = json.loads(ctx.python(["lz4"], REF, input=json.dumps({"op": "decompress", "blocks": blocks}).encode()))
ours = [{"name": n, "ok": bool(verdict.get(n)), "size": len(bytes.fromhex(blocks[n]["data"]))} for n in sorted(blocks)]
ctx.emit("lz4", {"cases": cases, "ours": ours})
bench = bytearray()
while len(bench) < 6_000_000:
bench += cs["text"] + bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(100000)) + rng.randbytes(20000)
bench = bytes(bench[:6_000_000])
code = "import sys, lz4.block; sys.stdout.buffer.write(lz4.block.compress(sys.stdin.buffer.read(), mode='high_compression', compression=9, store_size=False))"
ctx.emit("lz4_bench", {"size": len(bench), "crc": zlib.crc32(bench), "data": ctx.python(["lz4"], code, input=bench)})
+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)