ws-voxel: model/qb (Qubicle Binary read + write: RGBA / BGRA, z orientation, RLE, visibility masks; exact colours in Voxels.colors)

This commit is contained in:
4DBug committed 2026-10-31 14:52:15 -05:00
1 parent 286d193f14
commit f86e12f051
6 files changed
+734

No files matched your search

+1
View File
@@ -42,6 +42,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` |
| model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` |
| model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` |
| model | qb | .qb | yes | yes | voxels: true, truecolor: true | `tests/model/qb.luau` |
| model | rbxm | .rbxm .rbxl | yes | yes | tree: true, compression: "none", "lz4", "zstd" | `tests/model/rbxm.luau` |
| model | rbxmx | .rbxmx .rbxlx | yes | yes | tree: true | `tests/model/rbxmx.luau` |
| model | robloxmesh | .mesh | yes | yes | skinning: true, lods: true, versions: "1.00", "1.01", "2.00", "3.00", "3.01", "4.00", "4.01", "5.00", "6.00", "7.00" | `tests/model/robloxmesh.luau` |
+12
View File
@@ -458,6 +458,18 @@ local list: { Entry } = {
return require("@formats/model/ply")
end,
},
{
name = "qb",
category = "model",
path = "model/qb",
extensions = { "qb" },
mime = { "model/x-qubicle" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, voxels = true, truecolor = true },
load = function()
return require("@formats/model/qb")
end,
},
{
name = "rbxm",
category = "model",
+401
View File
@@ -0,0 +1,401 @@
--!strict
-- model/qb: Qubicle Binary (.qb, Qubicle 1.x "Qubicle Binary" exchange format), read and write. New code, from the
-- format description in the Qubicle documentation (minddesk.com "Qubicle Binary"): version 1.1.0.0, RGBA or BGRA
-- colours, left- or right-handed z axis, uncompressed or run-length compressed matrices (CODEFLAG 2 / NEXTSLICEFLAG 6
-- per z slice), the visibility mask encoding in the alpha byte, named matrices with a position.
-- decode -> a Scene (meta.up = "y"): one Types.Voxels per matrix with voxels.colors (each cell's exact colour as
-- r, g, b, a bytes; a = the visibility mask when the file encodes one, 0 = empty) and data / palette as an indexed view
-- (up to 255 colours exact, more mapped to the nearest of the 255 most used); a node per matrix with its name and
-- position. Left-handed files are mirrored on z into the scene's right-handed axes (and back on write).
-- encode <- a Scene with voxels or one Types.Voxels: voxels.colors when present (exact), else palette colours;
-- options default to the source file's settings.
-- Not supported: the Qubicle Exchange (.qbt / .qbcl) formats.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
-- ------------------------------------------------------------------------------------------------ contract
local Qb = {
name = "qb",
category = "model",
extensions = { "qb" },
mime = { "model/x-qubicle" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, voxels = true, truecolor = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxCells: number?, -- refuse files whose matrices hold more cells in total (default 2^27)
}
export type EncodeOptions = {
compressed: boolean?, -- run-length compress the matrices (default: the source's, else true)
colorFormat: ("rgba" | "bgra")?, -- default: the source's, else "rgba"
rightHanded: boolean?, -- the z axis orientation (default: the source's, else true)
visibilityMask: boolean?, -- encode the visible sides in the alpha byte (default: the source's, else false)
}
-- ------------------------------------------------------------------------------------------------ constants
local CODEFLAG, NEXTSLICEFLAG = 2, 6
-- visibility mask bits (alpha): 1 = filled, then the sides that are not hidden by a neighbour
local LEFT, RIGHT, TOP, BOTTOM, FRONT, BACK = 2, 4, 8, 16, 32, 64
-- ------------------------------------------------------------------------------------------------ sniff
function Qb.sniff(r: Bytes.Reader): number
if r:remaining() < 24 or r:peek(4) ~= "\1\1\0\0" then
return 0
end
local b, p = r.buf, r.pos
local fmt, z, comp, mask = buffer.readu32(b, p + 4), buffer.readu32(b, p + 8), buffer.readu32(b, p + 12), buffer.readu32(b, p + 16)
if fmt > 1 or z > 1 or comp > 1 or mask > 1 then
return 0
end
return 0.9
end
-- ------------------------------------------------------------------------------------------------ decode
-- the indexed view of a true-colour grid: exact for up to 255 colours, else the 255 most used and the nearest of them
local function indexed(v: Types.Voxels, colors: buffer, n: number)
local count: { [number]: number } = {}
for i = 0, n - 1 do
local c = buffer.readu32(colors, i * 4)
if c >= 0x1000000 then -- alpha > 0: filled
local rgb = c % 0x1000000
local k = count[rgb]
if k == nil then
count[rgb] = 1
else
count[rgb] = k + 1
end
end
end
local order = {}
for rgb in count do
table.insert(order, rgb)
end
table.sort(order, function(a: number, b: number): boolean
if count[a] ~= count[b] then
return count[a] > count[b]
end
return a < b
end)
local slot: { [number]: number } = {}
for i = 1, math.min(255, #order) do
local rgb = order[i]
slot[rgb] = i
v.palette[i] = { rgb % 256, (rgb // 256) % 256, rgb // 65536, 255 }
end
for i = 256, #order do
local rgb = order[i]
local r, g, b = rgb % 256, (rgb // 256) % 256, rgb // 65536
local best, bd = 1, math.huge
for k = 1, 255 do
local p = v.palette[k]
local d = (p[1] - r) ^ 2 + (p[2] - g) ^ 2 + (p[3] - b) ^ 2
if d < bd then
best, bd = k, d
end
end
slot[rgb] = best
end
for i = 0, n - 1 do
local c = buffer.readu32(colors, i * 4)
buffer.writeu8(v.data, i, if c >= 0x1000000 then slot[c % 0x1000000] else 0)
end
end
function Qb.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local o: DecodeOptions = opts or {}
local maxCells = o.maxCells or 2 ^ 27
local ver = r:string(4)
local fmt, zAxis, compressed, mask, count = r:u32le(), r:u32le(), r:u32le(), r:u32le(), r:u32le()
if r.err then
return nil, r.err
end
if ver ~= "\1\1\0\0" then
return nil, Err.new(Err.CORRUPT, "not a Qubicle Binary file (version 1.1.0.0)", 0)
end
if fmt > 1 or zAxis > 1 or compressed > 1 or mask > 1 then
return nil, Err.new(Err.CORRUPT, "bad header flags", 4)
end
if count > r:remaining() // 25 then
return nil, Err.new(Err.TRUNCATED, count .. " matrices cannot fit", 20)
end
local scene = Types.Scene.new()
local grids: { Types.Voxels } = {}
scene.voxels = grids
local total = 0
local bgra = fmt == 1
for m = 1, count do
local at = r:tell()
local nameLen = r:u8()
local name = r:string(nameLen)
local sx, sy, sz = r:u32le(), r:u32le(), r:u32le()
local px, py, pz = r:i32le(), r:i32le(), r:i32le()
if r.err then
return nil, r.err
end
if sx * sy * sz + total > maxCells then
return nil, Err.new(Err.LIMIT, string.format("matrix %d: %d x %d x %d cells is over maxCells", m, sx, sy, sz), at)
end
local n = sx * sy * sz
total += n
local colors = buffer.create(n * 4)
local b = r.buf
local function put(x: number, y: number, z: number, c: number)
if bgra then -- b, g, r, a -> r, g, b, a
c = (c // 65536) % 256 + (c // 256) % 256 * 256 + c % 256 * 65536 + (c // 16777216) * 16777216
end
if c < 0x1000000 then
c = 0 -- alpha 0: empty
end
local zz = if zAxis == 0 then sz - 1 - z else z
buffer.writeu32(colors, (x + sx * (y + sy * zz)) * 4, c)
end
if compressed == 0 then
if not r:need(n * 4) then
return nil, r.err
end
local p = r.pos
for z = 0, sz - 1 do
for y = 0, sy - 1 do
for x = 0, sx - 1 do
put(x, y, z, buffer.readu32(b, p))
p += 4
end
end
end
r.pos = p
else
local slice = sx * sy
for z = 0, sz - 1 do
local index = 0
while true do
local d = r:u32le()
if r.err then
return nil, r.err
end
if d == NEXTSLICEFLAG then
break
elseif d == CODEFLAG then
local run, c = r:u32le(), r:u32le()
if r.err then
return nil, r.err
end
if index + run > slice then
return nil, Err.new(Err.CORRUPT, string.format("matrix %d: run past the slice", m), r:tell() - 8)
end
for _ = 1, run do
put(index % sx, index // sx, z, c)
index += 1
end
else
if index >= slice then
return nil, Err.new(Err.CORRUPT, string.format("matrix %d: slice %d overflows", m, z), r:tell() - 4)
end
put(index % sx, index // sx, z, d)
index += 1
end
end
end
end
local v = Types.Voxels.new(sx, sy, sz)
v.name = name
v.colors = colors
indexed(v, colors, n)
table.insert(grids, v)
local tz = if zAxis == 0 then 0 - (pz + sz) else pz
table.insert(scene.nodes, { name = name, children = {}, voxels = m, translation = { px, py, tz } })
table.insert(scene.roots, #scene.nodes)
end
scene.meta.up = "y"
scene.meta.source = {
format = "qb",
colorFormat = if bgra then "bgra" else "rgba",
rightHanded = zAxis == 1,
compressed = compressed == 1,
visibilityMask = mask == 1,
}
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function cellColor(v: Types.Voxels, i: number): number
if v.colors then
return buffer.readu32(v.colors, i * 4)
end
local idx = buffer.readu8(v.data, i)
if idx == 0 then
return 0
end
local p = v.palette[idx] or { 0, 0, 0, 255 }
return p[1] + p[2] * 256 + p[3] * 65536 + 255 * 16777216
end
function Qb.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: EncodeOptions = opts or {}
local grids: { { v: Types.Voxels, name: string, pos: { number } } } = {}
local function add(v: any, name: string?, pos: { number }): string?
if type(v) ~= "table" or type(v.size) ~= "table" or type(v.data) ~= "buffer" then
return "expected Types.Voxels grids"
end
local n = v.size[1] * v.size[2] * v.size[3]
if buffer.len(v.data) < n or (v.colors and buffer.len(v.colors) < n * 4) then
return "voxel data shorter than its size"
end
local nm = name or v.name or ("matrix" .. (#grids + 1))
if #nm > 255 then
return "matrix name longer than 255 bytes"
end
table.insert(grids, { v = v, name = nm, pos = pos })
return nil
end
local src = if type(value) == "table" and type(value.meta) == "table" and type(value.meta.source) == "table" and value.meta.source.format == "qb" then value.meta.source else nil
if type(value) == "table" and value.kind == "voxels" then
local e = add(value, nil, { 0, 0, 0 })
if e then
return nil, Err.new(Err.ARG, e)
end
elseif type(value) == "table" and value.kind == "scene" and type(value.voxels) == "table" then
local used: { [number]: boolean } = {}
local function walk(i: number, base: { number }, depth: number): string?
local node = value.nodes[i]
if type(node) ~= "table" or depth > 64 then
return nil
end
local t = node.translation or { 0, 0, 0 }
local p = { base[1] + (t[1] or 0), base[2] + (t[2] or 0), base[3] + (t[3] or 0) }
if node.voxels and value.voxels[node.voxels] then
used[node.voxels] = true
local e = add(value.voxels[node.voxels], node.name, p)
if e then
return e
end
end
for _, c in node.children or {} do
local e = walk(c, p, depth + 1)
if e then
return e
end
end
return nil
end
for _, root in value.roots or {} do
local e = walk(root, { 0, 0, 0 }, 0)
if e then
return nil, Err.new(Err.ARG, e)
end
end
for i, v in value.voxels do
if not used[i] then
local e = add(v, nil, { 0, 0, 0 })
if e then
return nil, Err.new(Err.ARG, e)
end
end
end
else
return nil, Err.new(Err.ARG, "expected a Scene with voxels or a Types.Voxels")
end
local function pick(opt: any, key: string, default: any): any
if opt ~= nil then
return opt
elseif src and src[key] ~= nil then
return src[key]
end
return default
end
local compressed = pick(o.compressed, "compressed", true)
local bgra = pick(o.colorFormat, "colorFormat", "rgba") == "bgra"
local right = pick(o.rightHanded, "rightHanded", true)
local mask = pick(o.visibilityMask, "visibilityMask", false)
local keepMask = mask and src ~= nil and src.visibilityMask == true -- the source's alpha bytes already are masks
local w = Bytes.writer(1024)
w:string("\1\1\0\0")
w:u32le(if bgra then 1 else 0)
w:u32le(if right then 1 else 0)
w:u32le(if compressed then 1 else 0)
w:u32le(if mask then 1 else 0)
w:u32le(#grids)
for _, g in grids do
local v = g.v
local sx, sy, sz = v.size[1], v.size[2], v.size[3]
w:u8(#g.name)
w:string(g.name)
w:u32le(sx)
w:u32le(sy)
w:u32le(sz)
local px, py, pz = math.floor(g.pos[1] + 0.5), math.floor(g.pos[2] + 0.5), math.floor(g.pos[3] + 0.5)
w:u32le(px % 4294967296)
w:u32le(py % 4294967296)
w:u32le((if right then pz else -pz - sz) % 4294967296)
local function filled(x: number, y: number, z: number): boolean
if x < 0 or y < 0 or z < 0 or x >= sx or y >= sy or z >= sz then
return false
end
return cellColor(v, x + sx * (y + sy * z)) >= 0x1000000
end
-- the value of file cell (x, y, z): colour bytes in the file's order, the alpha a mask when asked
local function value(x: number, y: number, z: number): number
local zz = if right then z else sz - 1 - z
local c = cellColor(v, x + sx * (y + sy * zz))
if c < 0x1000000 then
return 0
end
local a = c // 16777216
if mask and not keepMask then
a = 1
if not filled(x - 1, y, zz) then a += LEFT end
if not filled(x + 1, y, zz) then a += RIGHT end
if not filled(x, y + 1, zz) then a += TOP end
if not filled(x, y - 1, zz) then a += BOTTOM end
if not filled(x, y, zz + 1) then a += FRONT end
if not filled(x, y, zz - 1) then a += BACK end
elseif not mask and src and src.visibilityMask then
a = 255 -- masks are not colours
end
local r, gg, b = c % 256, (c // 256) % 256, (c // 65536) % 256
if bgra then
r, b = b, r
end
return r + gg * 256 + b * 65536 + a * 16777216
end
for z = 0, sz - 1 do
if compressed then
local x, y = 0, 0
local slice = sx * sy
local i = 0
while i < slice do
x, y = i % sx, i // sx
local c = value(x, y, z)
local run = 1
while i + run < slice and value((i + run) % sx, (i + run) // sx, z) == c do
run += 1
end
if run > 2 then
w:u32le(CODEFLAG)
w:u32le(run)
w:u32le(c)
else
for _ = 1, run do
w:u32le(c)
end
end
i += run
end
w:u32le(NEXTSLICEFLAG)
else
for y = 0, sy - 1 do
for x = 0, sx - 1 do
w:u32le(value(x, y, z))
end
end
end
end
end
return w:finish(), nil
end
return Qb
+130
View File
@@ -0,0 +1,130 @@
-- model/qb tests: Qubicle Binary files with every option (RGBA / BGRA, left- / right-handed, RLE or not, visibility
-- masks, more than 255 colours) against the reference reader / writer of the fixture (exact colours of every cell,
-- names, positions), the indexed palette view, our encodings read back by the reference (same settings, flipped
-- settings, palette grids with computed masks), the api, error codes and the fuzz pass. Fixtures: tools/fixtures/qb.py.
local T = require("@tests/T")
local F = require("@formats")
local Qb = require("@formats/model/qb")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Fx = require("@tests/gen/qb")
local t = T.suite("qb")
t:eq(Qb.name, "qb", "name")
t:check(Qb.caps.decode and Qb.caps.encode, "caps")
local function dec(data: string | buffer): (Types.Scene?, any)
return Qb.decode(Bytes.reader(if type(data) == "string" then buffer.fromstring(data) else data))
end
local function check(scene: Types.Scene, want: any, label: string)
t:eq(#scene.nodes, #want.matrices, label .. ": matrices")
for i, m in want.matrices do
local node = scene.nodes[i]
local v = (scene.voxels :: { Types.Voxels })[node.voxels :: number]
t:eq(node.name, m.name, label .. " " .. i .. ": name")
t:eq(table.concat(v.size, ","), table.concat(m.size, ","), label .. " " .. i .. ": size")
t:eq(table.concat(node.translation :: { number }, ","), table.concat(m.pos, ","), label .. " " .. i .. ": position")
t:eq(Crc32.of(v.colors :: buffer), m.crc, label .. " " .. i .. ": colours")
local filled = 0
for k = 0, buffer.len(v.data) - 1 do
if buffer.readu8(v.data, k) ~= 0 then
filled += 1
end
end
t:eq(filled, m.filled, label .. " " .. i .. ": filled cells")
end
end
for _, c in Fx.cases do
local s, err = dec(c.data)
t:check(s ~= nil, c.name .. ": " .. tostring(err))
check(s :: Types.Scene, c, c.name)
local src = (s :: Types.Scene).meta.source
t:check(src.colorFormat == c.colorFormat and src.rightHanded == c.rightHanded and src.compressed == c.compressed and src.visibilityMask == c.visibilityMask, c.name .. ": settings")
t:check(buffer.tostring(Qb.encode(s) :: buffer) == c.data, c.name .. ": same bytes again")
-- the palette view: exact colours when there are up to 255
local v = ((s :: Types.Scene).voxels :: { Types.Voxels })[1]
local exact = true
for k = 0, buffer.len(v.data) - 1 do
local idx = buffer.readu8(v.data, k)
if idx > 0 then
local p, col = v.palette[idx], buffer.readu32(v.colors :: buffer, k * 4)
if p[1] + p[2] * 256 + p[3] * 65536 ~= col % 16777216 then
exact = false
end
end
end
t:eq(exact, c.name ~= "case5", c.name .. ": palette exact up to 255 colours")
t:eq(F.detect(c.data), "qb", c.name .. ": detect")
end
-- our encodings, read by the reference
for name, want in Fx.ours do
local base = string.match(name, "^(case%d)_")
if base then
local c
for _, x in Fx.cases do
if x.name == base then
c = x
end
end
t:check(c ~= nil, name .. ": source")
-- the same cells whatever the settings (scene coordinates)
for i, m in want.matrices do
t:eq(m.crc, c.matrices[i].crc, name .. " " .. i .. ": colours read back")
t:eq(table.concat(m.pos, ","), table.concat(c.matrices[i].pos, ","), name .. " " .. i .. ": position read back")
end
if string.find(name, "_flip") then
t:check(want.rightHanded ~= c.rightHanded and want.compressed ~= c.compressed, name .. ": flipped settings")
end
end
end
do
local m = Fx.ours.palette_mask
t:check(m.visibilityMask and m.matrices[1].filled == 15, "palette grid with a mask")
local plain = Fx.ours.palette_plain
t:check(not plain.visibilityMask and plain.rightHanded and plain.compressed, "defaults")
-- our decode of the masked file: the centre cell (hidden on every side) has mask 1
local v = Types.Voxels.new(3, 3, 3)
v.palette[1] = { 200, 10, 10, 255 }
for i = 0, 26 do
buffer.writeu8(v.data, i, 1)
end
local s = assert(dec(assert(Qb.encode(v, { visibilityMask = true }))))
local colors = ((s.voxels :: { Types.Voxels })[1]).colors :: buffer
t:eq(buffer.readu8(colors, 13 * 4 + 3), 1, "hidden cell mask")
t:eq(buffer.readu8(colors, 0 * 4 + 3), 1 + 2 + 16 + 64, "corner cell mask (left, bottom, back)")
end
-- api and conversion to .vox
do
local s = assert(F.load(Fx.cases[1].data))
t:check(s.kind == "scene", "F.load")
t:check(F.save(s, nil, { format = "vox" }) ~= nil, "qb -> vox")
t:check(F.save(s, nil, { format = "schem" }) ~= nil, "qb -> schem")
end
-- errors
do
local _, e1 = dec("\1\1\0\0")
t:check(e1 and e1.code == Err.TRUNCATED, "truncated header")
local _, e2 = dec("\2\1\0\0" .. string.rep("\0", 20))
t:check(e2 and e2.code == Err.CORRUPT, "bad version")
local _, e3 = dec(string.sub(Fx.cases[1].data, 1, 60))
t:check(e3 and e3.code == Err.TRUNCATED, "truncated matrix")
local _, e4 = Qb.encode({} :: any)
t:check(e4 and e4.code == Err.ARG, "encode nothing")
end
local samples = {}
for _, c in Fx.cases do
table.insert(samples, c.data)
end
t:fuzz("decode", function(b: buffer)
return Qb.decode(Bytes.reader(b))
end, samples)
t:done()
+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))
+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})