ws-roblox: codecs/model/Rbx (RbxTree, typed values, CFrame rotation ids, binary property columns), model/rbxm (binary rbxm / rbxl read + write; LZ4 / Zstd / raw chunks; unknown chunks and property types round trip raw), model/rbxmx (XML rbxmx / rbxlx read + write); tests vs rojo 7.7 + lune 0.11 both ways

init.luau: KIND_CATEGORY gains rbxtree = model (F.save of an RbxTree finds the model category).
This commit is contained in:
4DBug committed 2026-10-31 14:19:46 -05:00
1 parent 1ed25296ba
commit ea9c0b36df
12 files changed
+3563

No files matched your search

+24
View File
@@ -446,6 +446,30 @@ local list: { Entry } = {
return require("@formats/model/ply")
end,
},
{
name = "rbxm",
category = "model",
path = "model/rbxm",
extensions = { "rbxm", "rbxl" },
mime = { "application/x-roblox-rbxm", "application/x-roblox-rbxl" },
deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Lz4", "codecs/compress/Zstd", "codecs/model/Rbx", "codecs/model/Rbx/Binary" },
caps = { decode = true, encode = true, tree = true, compression = { "none", "lz4", "zstd" } },
load = function()
return require("@formats/model/rbxm")
end,
},
{
name = "rbxmx",
category = "model",
path = "model/rbxmx",
extensions = { "rbxmx", "rbxlx" },
mime = { "application/x-roblox-rbxmx", "application/x-roblox-rbxlx" },
deps = { "core/Err", "core/Bytes", "core/Base64", "core/Md5", "codecs/text/Xml", "codecs/model/Rbx" },
caps = { decode = true, encode = true, tree = true },
load = function()
return require("@formats/model/rbxmx")
end,
},
{
name = "stl",
category = "model",
+774
View File
@@ -0,0 +1,774 @@
--!strict
--!native
--!optimize 2
-- codecs/model/Rbx/Binary: the property columns of the Roblox binary format (rbx-dom docs/binary.md): one PROP chunk
-- holds a property's values for every instance of a class, by type id, with the format's array transforms: byte
-- interleaving (all first bytes, then all second bytes, ...), big-endian integers, zigzag signed integers, "rotated"
-- floats (sign bit moved to bit 0), delta-coded referents, and CFrame rotation ids (codecs/model/Rbx). Never throws.
--
-- local values, pEnd = Binary.decode(typeId, buf, p, limit, n, ctx) -- n plain values (codecs/model/Rbx forms)
-- local err = Binary.encode(typeId, values, n, writer, ctx) -- nil, or a message
-- Binary.readRefs(buf, p, limit, n) / Binary.writeRefs(writer, refs) -- referent arrays (INST, PRNT)
--
-- ctx: { ref = function(referent) -> Instance? (decode), refOf = function(Instance?) -> referent (-1 = none),
-- shared = { string } (SSTR entries, 1-based, decode), sharedIndex = function(string) -> 0-based index (encode) }.
-- decode returns nil, message on bad data ("truncated", "corrupt: ...", "unknown" for a type id it does not know /
-- a layout it cannot read, which the format keeps raw).
local Rbx = require("@formats/codecs/model/Rbx")
local Bytes = require("@formats/core/Bytes")
local Binary = {}
local readu8, readu16, readi16, readu32, readf32, readf64 =
buffer.readu8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readf32, buffer.readf64
local writeu32, readstring = buffer.writeu32, buffer.readstring
local writef32 = buffer.writef32
local floor = math.floor
local scratch = buffer.create(8)
local TWO32 = 4294967296
-- ------------------------------------------------------------------------------------------------ transforms
-- the rotated float encoding: bits rotated left by one (sign in bit 0)
local function unrotate(x: number): number
writeu32(scratch, 0, x // 2 + (x % 2) * 2147483648)
return readf32(scratch, 0)
end
local function rotate(v: number): number
writef32(scratch, 0, v)
local bits = readu32(scratch, 0)
return (bits * 2) % TWO32 + bits // 2147483648
end
local function unzigzag(x: number): number
return if x % 2 == 0 then x // 2 else -(x + 1) // 2
end
local function zigzag32(v: number): number
v = floor(v)
return (if v >= 0 then v * 2 else -v * 2 - 1) % TWO32
end
-- n big-endian u32 values interleaved at p (4n bytes)
local function u32s(b: buffer, p: number, n: number): { number }
local out = table.create(n, 0)
local n2, n3 = n * 2, n * 3
for i = 0, n - 1 do
out[i + 1] = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + n2 + i) * 256 + readu8(b, p + n3 + i)
end
return out
end
local function i32s(b: buffer, p: number, n: number): { number }
local out = u32s(b, p, n)
for i = 1, n do
out[i] = unzigzag(out[i])
end
return out
end
local function f32s(b: buffer, p: number, n: number): { number }
local out = u32s(b, p, n)
for i = 1, n do
out[i] = unrotate(out[i])
end
return out
end
-- n zigzag i64 values (8n interleaved bytes), as doubles
local function i64s(b: buffer, p: number, n: number): { number }
local out = table.create(n, 0)
for i = 0, n - 1 do
local hi = readu8(b, p + i) * 16777216 + readu8(b, p + n + i) * 65536 + readu8(b, p + 2 * n + i) * 256 + readu8(b, p + 3 * n + i)
local lo = readu8(b, p + 4 * n + i) * 16777216 + readu8(b, p + 5 * n + i) * 65536 + readu8(b, p + 6 * n + i) * 256 + readu8(b, p + 7 * n + i)
local half = hi * 2147483648 + lo // 2
out[i + 1] = if lo % 2 == 0 then half else -half - 1
end
return out
end
-- writers: n values interleaved as big-endian u32 / zigzag i32 / rotated f32 / zigzag i64
local function putU32s(w: Bytes.Writer, vals: { number })
local n = #vals
local p = w:reserve(4 * n)
local b = w.buf
for i = 0, n - 1 do
local v = vals[i + 1] % TWO32
buffer.writeu8(b, p + i, v // 16777216)
buffer.writeu8(b, p + n + i, (v // 65536) % 256)
buffer.writeu8(b, p + 2 * n + i, (v // 256) % 256)
buffer.writeu8(b, p + 3 * n + i, v % 256)
end
w.pos = p + 4 * n
end
local function putI32s(w: Bytes.Writer, vals: { number })
local t = table.create(#vals, 0)
for i, v in vals do
t[i] = zigzag32(v)
end
putU32s(w, t)
end
local function putF32s(w: Bytes.Writer, vals: { number })
local t = table.create(#vals, 0)
for i, v in vals do
t[i] = rotate(v)
end
putU32s(w, t)
end
local function putI64s(w: Bytes.Writer, vals: { number })
local n = #vals
local p = w:reserve(8 * n)
local b = w.buf
for i = 0, n - 1 do
local v = floor(vals[i + 1])
local z = if v >= 0 then v * 2 else -v * 2 - 1
local hi, lo = (z // TWO32) % TWO32, z % TWO32
buffer.writeu8(b, p + i, hi // 16777216)
buffer.writeu8(b, p + n + i, (hi // 65536) % 256)
buffer.writeu8(b, p + 2 * n + i, (hi // 256) % 256)
buffer.writeu8(b, p + 3 * n + i, hi % 256)
buffer.writeu8(b, p + 4 * n + i, lo // 16777216)
buffer.writeu8(b, p + 5 * n + i, (lo // 65536) % 256)
buffer.writeu8(b, p + 6 * n + i, (lo // 256) % 256)
buffer.writeu8(b, p + 7 * n + i, lo % 256)
end
w.pos = p + 8 * n
end
-- referent arrays: zigzag i32, interleaved, each the difference from the previous one
function Binary.readRefs(b: buffer, p: number, limit: number, n: number): ({ number }?, number)
if n < 0 or p + 4 * n > limit then
return nil, p
end
local out = i32s(b, p, n)
local acc = 0
for i = 1, n do
acc += out[i]
out[i] = acc
end
return out, p + 4 * n
end
function Binary.writeRefs(w: Bytes.Writer, refs: { number })
local d = table.create(#refs, 0)
local prev = 0
for i, r in refs do
d[i] = r - prev
prev = r
end
putI32s(w, d)
end
-- ------------------------------------------------------------------------------------------------ decode
export type Ctx = {
ref: ((number) -> any)?,
refOf: ((any) -> number)?,
shared: { string }?,
sharedIndex: ((string) -> number)?,
}
-- a length-prefixed string at p: string, next p (nil when it runs past limit)
local function str(b: buffer, p: number, limit: number): (string?, number)
if p + 4 > limit then
return nil, p
end
local len = readu32(b, p)
if p + 4 + len > limit then
return nil, p
end
return readstring(b, p + 4, len), p + 4 + len
end
local function cframes(b: buffer, p: number, limit: number, n: number): ({ any }?, number)
local rots: { { number } } = table.create(n) :: any
for i = 1, n do
if p >= limit then
return nil, p
end
local id = readu8(b, p)
p += 1
if id == 0 then
if p + 36 > limit then
return nil, p
end
local m = table.create(9, 0)
for k = 0, 8 do
m[k + 1] = readf32(b, p + 4 * k)
end
rots[i] = m
p += 36
else
local m = Rbx.ROTATIONS[id]
if not m then
return nil, -1
end
rots[i] = m
end
end
if p + 12 * n > limit then
return nil, p
end
local xs, ys, zs = f32s(b, p, n), f32s(b, p + 4 * n, n), f32s(b, p + 8 * n, n)
local out = table.create(n)
for i = 1, n do
local m = rots[i]
out[i] = { xs[i], ys[i], zs[i], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9] }
end
return out, p + 12 * n
end
local FIXED: { [number]: number } = { -- bytes per value of the fixed-size types
[0x02] = 1,
[0x03] = 4,
[0x04] = 4,
[0x05] = 8,
[0x06] = 8,
[0x07] = 16,
[0x08] = 24,
[0x09] = 1,
[0x0A] = 1,
[0x0B] = 4,
[0x0C] = 12,
[0x0D] = 8,
[0x0E] = 12,
[0x0F] = 4,
[0x12] = 4,
[0x13] = 4,
[0x14] = 6,
[0x17] = 8,
[0x18] = 16,
[0x1A] = 3,
[0x1B] = 8,
[0x1C] = 4,
[0x1F] = 16,
[0x21] = 8,
}
-- decode(typeId, b, p, limit, n, ctx) -> n values, the end offset | nil, message
function Binary.decode(t: number, b: buffer, p: number, limit: number, n: number, ctx: Ctx): ({ any }?, any)
if limit > buffer.len(b) or p < 0 or n < 0 then
return nil, "corrupt: bad ranges"
end
local size = FIXED[t]
if size and p + size * n > limit then
return nil, "truncated property values"
end
if t == 0x01 or t == 0x1D then
local out = table.create(n, "")
for i = 1, n do
local s, q = str(b, p, limit)
if not s then
return nil, "truncated string"
end
out[i] = s
p = q
end
return out, p
elseif t == 0x02 then
local out = table.create(n, false)
for i = 1, n do
out[i] = readu8(b, p + i - 1) ~= 0
end
return out, p + n
elseif t == 0x03 then
return i32s(b, p, n), p + 4 * n
elseif t == 0x04 then
return f32s(b, p, n), p + 4 * n
elseif t == 0x05 then
local out = table.create(n, 0)
for i = 1, n do
out[i] = readf64(b, p + 8 * (i - 1))
end
return out, p + 8 * n
elseif t == 0x06 then
local s, o = f32s(b, p, n), i32s(b, p + 4 * n, n)
local out = table.create(n)
for i = 1, n do
out[i] = { s[i], o[i] }
end
return out, p + 8 * n
elseif t == 0x07 then
local xs, ys, xo, yo = f32s(b, p, n), f32s(b, p + 4 * n, n), i32s(b, p + 8 * n, n), i32s(b, p + 12 * n, n)
local out = table.create(n)
for i = 1, n do
out[i] = { xs[i], xo[i], ys[i], yo[i] }
end
return out, p + 16 * n
elseif t == 0x08 then
local out = table.create(n)
for i = 1, n do
local q = p + 24 * (i - 1)
out[i] = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12), readf32(b, q + 16), readf32(b, q + 20) }
end
return out, p + 24 * n
elseif t == 0x09 or t == 0x0A then
local out = table.create(n, 0)
for i = 1, n do
out[i] = readu8(b, p + i - 1)
end
return out, p + n
elseif t == 0x0B or t == 0x12 then
return u32s(b, p, n), p + 4 * n
elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then
local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3
local cols: { { number } } = table.create(k) :: any
for c = 1, k do
cols[c] = f32s(b, p + 4 * n * (c - 1), n)
end
local out = table.create(n)
for i = 1, n do
local v = table.create(k, 0)
for c = 1, k do
v[c] = cols[c][i]
end
out[i] = v
end
return out, p + 4 * k * n
elseif t == 0x0F or t == 0x14 then
local k = if t == 0x0F then 2 else 3
local out = table.create(n)
for i = 1, n do
local q = p + 2 * k * (i - 1)
out[i] = if k == 2 then { readi16(b, q), readi16(b, q + 2) } else { readi16(b, q), readi16(b, q + 2), readi16(b, q + 4) }
end
return out, p + 2 * k * n
elseif t == 0x10 then
local out, q = cframes(b, p, limit, n)
if not out then
return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values"
end
return out, q
elseif t == 0x13 then
local refs, q = Binary.readRefs(b, p, limit, n)
if not refs then
return nil, "truncated referents"
end
local out = table.create(n)
local ref = ctx.ref
for i = 1, n do
out[i] = if ref and refs[i] >= 0 then ref(refs[i]) else nil
end
return out, q
elseif t == 0x15 or t == 0x16 then
local k = if t == 0x15 then 3 else 5
local out = table.create(n)
for i = 1, n do
if p + 4 > limit then
return nil, "truncated sequence"
end
local count = readu32(b, p)
p += 4
if p + count * 4 * k > limit then
return nil, "truncated sequence"
end
local seq = table.create(count)
for j = 1, count do
local key = table.create(k, 0)
for c = 1, k do
key[c] = readf32(b, p + 4 * (c - 1))
end
seq[j] = key
p += 4 * k
end
out[i] = seq
end
return out, p
elseif t == 0x17 then
local out = table.create(n)
for i = 1, n do
out[i] = { readf32(b, p + 8 * (i - 1)), readf32(b, p + 8 * (i - 1) + 4) }
end
return out, p + 8 * n
elseif t == 0x19 then
local out = table.create(n)
for i = 1, n do
if p >= limit then
return nil, "truncated physical properties"
end
local flag = readu8(b, p)
p += 1
if flag % 2 == 1 then
local k = if flag // 2 % 2 == 1 then 6 else 5
if p + 4 * k > limit then
return nil, "truncated physical properties"
end
local v = table.create(6, 1) -- acoustic absorption 1 when the file leaves it out
for c = 1, k do
v[c] = readf32(b, p + 4 * (c - 1))
end
out[i] = v
p += 4 * k
elseif flag ~= 0 then
return nil, "unknown"
end
end
return out, p
elseif t == 0x1A then
local out = table.create(n)
for i = 1, n do
out[i] = { readu8(b, p + i - 1), readu8(b, p + n + i - 1), readu8(b, p + 2 * n + i - 1) }
end
return out, p + 3 * n
elseif t == 0x1B or t == 0x21 then
return i64s(b, p, n), p + 8 * n
elseif t == 0x1C then
local idx = u32s(b, p, n)
local shared: { string } = ctx.shared or {}
local out: { string } = table.create(n, "")
for i = 1, n do
local s = shared[idx[i] + 1]
if s == nil then
return nil, "corrupt: shared string index out of range"
end
out[i] = s
end
return out, p + 4 * n
elseif t == 0x1E then
if p >= limit or readu8(b, p) ~= 0x10 then
return nil, "unknown"
end
local cfs, q = cframes(b, p + 1, limit, n)
if not cfs then
return nil, if q == -1 then "corrupt: bad CFrame rotation id" else "truncated CFrame values"
end
if q + 1 + n > limit or readu8(b, q) ~= 0x02 then
return nil, "truncated optional CFrame flags"
end
local out = table.create(n)
for i = 1, n do
out[i] = if readu8(b, q + i) ~= 0 then cfs[i] else nil
end
return out, q + 1 + n
elseif t == 0x1F then
local out = table.create(n, "")
local hex = table.create(16, "")
for i = 0, n - 1 do
local by = table.create(16, 0)
for k = 0, 15 do
by[k + 1] = readu8(b, p + k * n + i)
end
-- bytes 8..15: the random part rotated left by one bit (as a 64-bit integer); undo it
local carry = by[16] % 2
for k = 9, 16 do
local v = by[k]
by[k] = v // 2 + carry * 128
carry = v % 2
end
for k = 1, 8 do
hex[k] = string.format("%02x", by[8 + k])
end
for k = 1, 8 do
hex[8 + k] = string.format("%02x", by[k + 4 - (if k > 4 then 8 else 0)])
end
out[i + 1] = table.concat(hex)
end
return out, p + 16 * n
elseif t == 0x20 then
local out = table.create(n)
for i = 1, n do
local fam, q = str(b, p, limit)
if not fam or q + 3 > limit then
return nil, "truncated font"
end
local weight, style = readu16(b, q), readu8(b, q + 2)
local face, q2 = str(b, q + 3, limit)
if not face then
return nil, "truncated font"
end
out[i] = { family = fam, weight = weight, style = if style == 1 then "Italic" else "Normal", cachedFaceId = if face ~= "" then face else nil }
p = q2
end
return out, p
elseif t == 0x22 then
if p + 4 * n > limit then
return nil, "truncated content"
end
local kinds = i32s(b, p, n)
p += 4 * n
if p + 4 > limit then
return nil, "truncated content"
end
local nu = readu32(b, p)
p += 4
local uris = table.create(math.min(nu, n))
for j = 1, nu do
local s, q = str(b, p, limit)
if not s then
return nil, "truncated content"
end
uris[j] = s
p = q
end
if p + 4 > limit then
return nil, "truncated content"
end
local no = readu32(b, p)
local objs, q = Binary.readRefs(b, p + 4, limit, no)
if not objs or q + 4 > limit then
return nil, "truncated content"
end
if readu32(b, q) ~= 0 then
return nil, "unknown" -- external objects: kept raw
end
p = q + 4
local out = table.create(n)
local iu, io = 1, 1
for i = 1, n do
local k = kinds[i]
if k == 1 then
if iu > nu then
return nil, "corrupt: content uri count"
end
out[i] = uris[iu]
iu += 1
elseif k == 2 then
if io > no then
return nil, "corrupt: content object count"
end
local r = objs[io]
out[i] = if ctx.ref and r >= 0 then ctx.ref(r) else nil
io += 1
elseif k ~= 0 then
return nil, "unknown"
end
end
return out, p
end
return nil, "unknown"
end
-- ------------------------------------------------------------------------------------------------ encode
local function num(v: any): number
return if type(v) == "number" and v == v then v else 0
end
-- column c of n array values (missing components 0)
local function column(vals: { any }, n: number, c: number): { number }
local out = table.create(n, 0)
for i = 1, n do
local v = vals[i]
out[i] = if type(v) == "table" then num(v[c]) else 0
end
return out
end
local function putString(w: Bytes.Writer, s: string)
w:u32le(#s)
w:string(s)
end
local function putCFrames(w: Bytes.Writer, vals: { any }, n: number)
for i = 1, n do
local v = vals[i]
local cf = if type(v) == "table" then v else { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 }
local id = Rbx.rotationId(cf)
w:u8(id)
if id == 0 then
for k = 4, 12 do
w:f32le(num(cf[k]))
end
end
end
putF32s(w, column(vals, n, 1))
putF32s(w, column(vals, n, 2))
putF32s(w, column(vals, n, 3))
end
local function hexByte(s: string, i: number): number
return tonumber(string.sub(s, 2 * i - 1, 2 * i), 16) or 0
end
-- encode(typeId, values, n, w, ctx) -> nil | message: values[1 .. n] in the codecs/model/Rbx forms (nil entries are
-- the type's none / default)
function Binary.encode(t: number, vals: { any }, n: number, w: Bytes.Writer, ctx: Ctx): string?
if t == 0x01 or t == 0x1D then
for i = 1, n do
local v = vals[i]
putString(w, if type(v) == "string" then v else "")
end
elseif t == 0x02 then
for i = 1, n do
w:u8(if vals[i] then 1 else 0)
end
elseif t == 0x03 then
local c = table.create(n, 0)
for i = 1, n do
c[i] = num(vals[i])
end
putI32s(w, c)
elseif t == 0x04 then
local c = table.create(n, 0)
for i = 1, n do
c[i] = num(vals[i])
end
putF32s(w, c)
elseif t == 0x05 then
for i = 1, n do
w:f64le(num(vals[i]))
end
elseif t == 0x06 then
putF32s(w, column(vals, n, 1))
putI32s(w, column(vals, n, 2))
elseif t == 0x07 then
putF32s(w, column(vals, n, 1))
putF32s(w, column(vals, n, 3))
putI32s(w, column(vals, n, 2))
putI32s(w, column(vals, n, 4))
elseif t == 0x08 then
for i = 1, n do
local v = vals[i]
for c = 1, 6 do
w:f32le(if type(v) == "table" then num(v[c]) else 0)
end
end
elseif t == 0x09 or t == 0x0A then
for i = 1, n do
w:u8(num(vals[i]) % 256)
end
elseif t == 0x0B or t == 0x12 then
local c = table.create(n, 0)
for i = 1, n do
c[i] = floor(num(vals[i]))
end
putU32s(w, c)
elseif t == 0x0C or t == 0x0E or t == 0x0D or t == 0x18 then
local k = if t == 0x0D then 2 elseif t == 0x18 then 4 else 3
for c = 1, k do
putF32s(w, column(vals, n, c))
end
elseif t == 0x0F or t == 0x14 then
local k = if t == 0x0F then 2 else 3
for i = 1, n do
local v = vals[i]
for c = 1, k do
local x = floor(if type(v) == "table" then num(v[c]) else 0) % 65536
w:u16le(x)
end
end
elseif t == 0x10 then
putCFrames(w, vals, n)
elseif t == 0x13 then
local refs = table.create(n, -1)
local refOf = ctx.refOf
for i = 1, n do
refs[i] = if refOf and vals[i] ~= nil then refOf(vals[i]) else -1
end
Binary.writeRefs(w, refs)
elseif t == 0x15 or t == 0x16 then
local k = if t == 0x15 then 3 else 5
for i = 1, n do
local seq = vals[i]
if type(seq) ~= "table" then
seq = {}
end
w:u32le(#seq)
for _, key in seq do
for c = 1, k do
w:f32le(if type(key) == "table" then num(key[c]) else 0)
end
end
end
elseif t == 0x17 then
for i = 1, n do
local v = vals[i]
w:f32le(if type(v) == "table" then num(v[1]) else 0)
w:f32le(if type(v) == "table" then num(v[2]) else 0)
end
elseif t == 0x19 then
for i = 1, n do
local v = vals[i]
if type(v) ~= "table" then
w:u8(0)
else
local acoustic = v[6] ~= nil and v[6] ~= 1 -- (rbx-dom leaves the default out)
w:u8(if acoustic then 3 else 1)
for c = 1, if acoustic then 6 else 5 do
w:f32le(num(v[c]))
end
end
end
elseif t == 0x1A then
for c = 1, 3 do
for i = 1, n do
local v = vals[i]
w:u8(math.clamp(floor(if type(v) == "table" then num(v[c]) else 0), 0, 255))
end
end
elseif t == 0x1B or t == 0x21 then
local c = table.create(n, 0)
for i = 1, n do
c[i] = num(vals[i])
end
putI64s(w, c)
elseif t == 0x1C then
local idx = table.create(n, 0)
local si = ctx.sharedIndex
for i = 1, n do
local v = vals[i]
idx[i] = if si then si(if type(v) == "string" then v else "") else 0
end
putU32s(w, idx)
elseif t == 0x1E then
w:u8(0x10)
putCFrames(w, vals, n)
w:u8(0x02)
for i = 1, n do
w:u8(if type(vals[i]) == "table" then 1 else 0)
end
elseif t == 0x1F then
local p = w:reserve(16 * n)
local b = w.buf
for i = 0, n - 1 do
local s = vals[i + 1]
if type(s) ~= "string" or #s ~= 32 or string.find(s, "[^%x]") then
return "a UniqueId is 32 hex digits"
end
-- index (hex 25..32) and time (17..24) first, then the random part (1..16) rotated left by one bit
local by = table.create(16, 0)
for k = 1, 4 do
by[k] = hexByte(s, 12 + k)
by[4 + k] = hexByte(s, 8 + k)
end
local top = hexByte(s, 1) // 128
for k = 1, 8 do
local v = hexByte(s, k)
local nxt = if k < 8 then hexByte(s, k + 1) // 128 else top
by[8 + k] = (v * 2) % 256 + nxt
end
for k = 0, 15 do
buffer.writeu8(b, p + k * n + i, by[k + 1])
end
end
w.pos = p + 16 * n
elseif t == 0x20 then
for i = 1, n do
local v = vals[i]
if type(v) ~= "table" then
v = Rbx.default("Font")
end
putString(w, if type(v.family) == "string" then v.family else "")
w:u16le(math.clamp(floor(num(v.weight)), 0, 65535))
w:u8(if v.style == "Italic" then 1 else 0)
putString(w, if type(v.cachedFaceId) == "string" then v.cachedFaceId else "")
end
elseif t == 0x22 then
local kinds, uris, objs = table.create(n, 0), {}, {}
local refOf = ctx.refOf
for i = 1, n do
local v = vals[i]
if type(v) == "string" then
kinds[i] = 1
table.insert(uris, v)
elseif type(v) == "table" then
kinds[i] = 2
table.insert(objs, if refOf then refOf(v) else -1)
end
end
putI32s(w, kinds)
w:u32le(#uris)
for _, s in uris do
putString(w, s)
end
w:u32le(#objs)
Binary.writeRefs(w, objs)
w:u32le(0)
else
return "unknown type id " .. t
end
return nil
end
return Binary
+281
View File
@@ -0,0 +1,281 @@
--!strict
-- codecs/model/Rbx: the Roblox instance tree every Roblox file format maps to (model/rbxm binary rbxm / rbxl,
-- model/rbxmx XML rbxmx / rbxlx), the typed property values, the CFrame rotation IDs, and (codecs/model/Rbx/Binary) the
-- binary format's property column codecs. Shared here because a format cannot require another one. Written from the
-- rbx-dom format notes (docs/binary.md, docs/xml.md) and checked against rbx-dom through rojo / lune. A file library,
-- not a Roblox runtime: nothing here creates Instances; a Roblox game reads the tree itself.
--
-- local tree = Rbx.tree() -- { kind = "rbxtree", roots = {}, place = false, ... }
-- local part = Rbx.instance("Part", "Floor") -- { className, name, properties = {}, children = {} }
-- Rbx.set(part, "Size", "Vector3", { 64, 1, 64 }) -- properties.Size = { type = "Vector3", value = {...} }
-- Rbx.add(tree, part) -- a root; Rbx.add(parentInstance, child) nests
-- for inst, depth in Rbx.descendants(tree) do ... end
--
-- Property values are { type = <name>, value = <v> } with these value forms (arrays follow the Roblox constructor
-- argument order, so Vector3.new(table.unpack(v.value)) / CFrame.new(table.unpack(v.value)) rebuild them in Roblox):
-- String, BinaryString, ProtectedString, ContentId, Bytecode string (bytes)
-- SharedString string (the content; writers deduplicate)
-- Bool boolean
-- Int32, Int64, Float32, Float64 number (Int64 exact to 2^53)
-- Enum, BrickColor, SecurityCapabilities number
-- Faces number: bits Right 1, Top 2, Back 4, Left 8, Bottom 16, Front 32
-- Axes number: bits X 1, Y 2, Z 4
-- UDim { scale, offset } UDim2 { xScale, xOffset, yScale, yOffset } NumberRange { min, max }
-- Vector2 / Vector2int16 { x, y } Vector3 / Vector3int16 { x, y, z } Color3 { r, g, b } (0..1)
-- Color3uint8 { r, g, b } (0..255) Rect { minX, minY, maxX, maxY } Ray { ox, oy, oz, dx, dy, dz }
-- CFrame { x, y, z, r00, r01, r02, r10, r11, r12, r20, r21, r22 } OptionalCFrame: the same, or nil (none)
-- NumberSequence { { time, value, envelope } ... } ColorSequence { { time, r, g, b, envelope } ... }
-- PhysicalProperties nil (default) | { density, friction, elasticity, frictionWeight, elasticityWeight,
-- acousticAbsorption } (decoders fill acousticAbsorption = 1 when the file leaves it out)
-- Ref an Instance of the tree, or nil
-- UniqueId 32 hex digits: random (16), time (8), index (8)
-- Font { family, weight (100..900), style ("Normal" | "Italic"), cachedFaceId? }
-- Content nil (none) | string (a URI) | an Instance (object)
-- Raw a binary property of a type this library does not know: { typeId, data (the class's whole column),
-- index, count }; written back verbatim while the class keeps the same instances in the same order
-- XmlRaw an XML property of an unknown type: value = the element (codecs/text/Xml node), written back as it is
-- Name is not a property here: it is inst.name. Never throws.
local Rbx = {}
export type Value = { type: string, value: any }
export type Instance = {
className: string,
name: string,
properties: { [string]: Value },
children: { Instance },
parent: Instance?, -- nil for roots
referent: string?, -- the file's referent (XML "RBX..." id, binary index) when read; writers make their own
service: boolean?, -- a service (binary INST object format 1; rbxl roots)
}
export type Tree = {
kind: "rbxtree",
roots: { Instance },
place: boolean, -- a place (rbxl / rbxlx: the roots are services under the DataModel) or a model
metadata: { [string]: string }, -- binary META / XML <Meta> entries (ExplicitAutoJoints, ...)
extra: { any }, -- unknown binary chunks { name, data } / unknown top-level XML elements, written back
meta: { source: { format: string, [string]: any }?, [string]: any },
}
-- ------------------------------------------------------------------------------------------------ tree
function Rbx.tree(place: boolean?): Tree
return { kind = "rbxtree", roots = {}, place = place == true, metadata = {}, extra = {}, meta = {} }
end
function Rbx.instance(className: string, name: string?): Instance
return { className = className, name = name or className, properties = {}, children = {} }
end
-- add(parent, child) -> child: parent is a Tree (child becomes a root) or an Instance
function Rbx.add(parent: any, child: Instance): Instance
if parent.kind == "rbxtree" then
child.parent = nil
table.insert(parent.roots, child)
else
child.parent = parent
table.insert(parent.children, child)
end
return child
end
-- set(inst, name, type, value): a property (value nil = the type's nil form: Ref none, OptionalCFrame none, ...)
function Rbx.set(inst: Instance, name: string, typ: string, value: any)
inst.properties[name] = { type = typ, value = value }
end
-- get(inst, name) -> the property's value (not the Value table), nil when absent
function Rbx.get(inst: Instance, name: string): any
local v = inst.properties[name]
return if v then v.value else nil
end
-- descendants(treeOrInstance) -> iterator over (instance, depth) in depth-first order (roots / the instance's children
-- at depth 1)
function Rbx.descendants(root: any): () -> (Instance?, number?)
local stack: { any } = {}
local list = if root.kind == "rbxtree" then root.roots else root.children
for i = #list, 1, -1 do
table.insert(stack, { list[i], 1 })
end
return function(): (Instance?, number?)
local top = table.remove(stack)
if not top then
return nil, nil
end
local inst, depth = top[1], top[2]
for i = #inst.children, 1, -1 do
table.insert(stack, { inst.children[i], depth + 1 })
end
return inst, depth
end
end
-- list(tree) -> every instance, depth first
function Rbx.list(tree: any): { Instance }
local out = {}
for inst in Rbx.descendants(tree) do
table.insert(out, inst :: Instance)
end
return out
end
-- find(treeOrInstance, path) -> the instance at a "/"-separated path of names ("Workspace/Baseplate"), or nil
function Rbx.find(root: any, path: string): Instance?
local cur: any = root
for part in string.gmatch(path, "[^/]+") do
local list = if cur.kind == "rbxtree" then cur.roots else cur.children
local found = nil
for _, c in list do
if c.name == part then
found = c
break
end
end
if not found then
return nil
end
cur = found
end
return if cur.kind == "rbxtree" then nil else cur
end
-- fullName(inst) -> "Workspace.Model.Part" (names joined up to the root)
function Rbx.fullName(inst: Instance): string
local parts = {}
local cur: Instance? = inst
while cur do
table.insert(parts, 1, cur.name)
cur = cur.parent
end
return table.concat(parts, ".")
end
-- ------------------------------------------------------------------------------------------------ CFrame rotation ids
-- The binary format stores axis-aligned rotations as one byte: id = 6 * n(RightVector) + n(UpVector) + 1, where n is
-- the NormalId of a unit axis (+X 0, +Y 1, +Z 2, -X 3, -Y 4, -Z 5) and the third column is their cross product.
local AXES = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, { -1, 0, 0 }, { 0, -1, 0 }, { 0, 0, -1 } }
-- the rotation of an id as { r00 .. r22 } (row major), or nil for an id that is not a rotation
local ROTATIONS: { [number]: { number } } = {}
for a = 0, 5 do
for b = 0, 5 do
if a % 3 ~= b % 3 then
local r, u = AXES[a + 1], AXES[b + 1]
local k = { r[2] * u[3] - r[3] * u[2], r[3] * u[1] - r[1] * u[3], r[1] * u[2] - r[2] * u[1] }
-- columns: right, up, back (= right x up)
ROTATIONS[6 * a + b + 1] = { r[1], u[1], k[1] + 0, r[2], u[2], k[2] + 0, r[3], u[3], k[3] + 0 }
end
end
end
Rbx.ROTATIONS = ROTATIONS
local function axisIndex(x: number, y: number, z: number): number?
for i, a in AXES do
if a[1] == x and a[2] == y and a[3] == z then
return i - 1
end
end
return nil
end
-- rotationId(cf) -> the id of the CFrame's rotation (cf = { x, y, z, r00 .. r22 }), or 0 when it is not axis aligned
function Rbx.rotationId(cf: { number }): number
local a = axisIndex(cf[4], cf[7], cf[10])
local b = axisIndex(cf[5], cf[8], cf[11])
if not a or not b then
return 0
end
local id = 6 * a + b + 1
local rot = ROTATIONS[id]
if not rot or rot[3] ~= cf[6] or rot[6] ~= cf[9] or rot[9] ~= cf[12] then
return 0
end
return id
end
-- ------------------------------------------------------------------------------------------------ values
-- binary type ids (rbx-dom docs/binary.md) by type name, and back
Rbx.TYPE_IDS = table.freeze({
String = 0x01,
BinaryString = 0x01,
ProtectedString = 0x01,
ContentId = 0x01,
Bool = 0x02,
Int32 = 0x03,
Float32 = 0x04,
Float64 = 0x05,
UDim = 0x06,
UDim2 = 0x07,
Ray = 0x08,
Faces = 0x09,
Axes = 0x0A,
BrickColor = 0x0B,
Color3 = 0x0C,
Vector2 = 0x0D,
Vector3 = 0x0E,
Vector2int16 = 0x0F,
CFrame = 0x10,
Enum = 0x12,
Ref = 0x13,
Vector3int16 = 0x14,
NumberSequence = 0x15,
ColorSequence = 0x16,
NumberRange = 0x17,
Rect = 0x18,
PhysicalProperties = 0x19,
Color3uint8 = 0x1A,
Int64 = 0x1B,
SharedString = 0x1C,
Bytecode = 0x1D,
OptionalCFrame = 0x1E,
UniqueId = 0x1F,
Font = 0x20,
SecurityCapabilities = 0x21,
Content = 0x22,
} :: { [string]: number })
local NAMES: { [number]: string } = {}
for name, id in Rbx.TYPE_IDS do
if NAMES[id] == nil or name == "String" then
NAMES[id] = name
end
end
Rbx.TYPE_NAMES = table.freeze(NAMES)
-- the value a binary writer uses for an instance without the property (zero / empty / identity; BrickColor 194, the
-- Medium stone grey Roblox defaults to; sequences of two keypoints at times 0 and 1)
local IDENTITY_CF = { 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1 }
function Rbx.default(typ: string): any
if typ == "String" or typ == "BinaryString" or typ == "ProtectedString" or typ == "ContentId" or typ == "Bytecode" or typ == "SharedString" then
return ""
elseif typ == "Bool" then
return false
elseif typ == "BrickColor" then
return 194
elseif typ == "UDim" or typ == "NumberRange" or typ == "Vector2" or typ == "Vector2int16" then
return { 0, 0 }
elseif typ == "UDim2" or typ == "Rect" then
return { 0, 0, 0, 0 }
elseif typ == "Vector3" or typ == "Vector3int16" or typ == "Color3" or typ == "Color3uint8" then
return { 0, 0, 0 }
elseif typ == "Ray" then
return { 0, 0, 0, 0, 0, 0 }
elseif typ == "CFrame" then
return table.clone(IDENTITY_CF)
elseif typ == "NumberSequence" then
return { { 0, 0, 0 }, { 1, 0, 0 } }
elseif typ == "ColorSequence" then
return { { 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 0 } }
elseif typ == "UniqueId" then
return string.rep("0", 32)
elseif typ == "Font" then
return { family = "rbxasset://fonts/families/SourceSansPro.json", weight = 400, style = "Normal" }
elseif typ == "PhysicalProperties" or typ == "Ref" or typ == "OptionalCFrame" or typ == "Content" then
return nil
end
return 0
end
-- STRINGS: the string-valued types (one binary type, several XML tags)
Rbx.STRINGS = table.freeze({ String = true, BinaryString = true, ProtectedString = true, ContentId = true, Bytecode = true } :: { [string]: boolean })
return Rbx
+1
View File
@@ -41,6 +41,7 @@ local KIND_CATEGORY: { [string]: string } = {
audio = "audio",
video = "video",
scene = "model",
rbxtree = "model", -- codecs/model/Rbx trees (model/rbxm, model/rbxmx)
cad = "cad",
font = "font",
archive = "archive",
+575
View File
@@ -0,0 +1,575 @@
--!strict
-- model/rbxm: the Roblox binary model / place format (.rbxm / .rbxl, "<roblox!"), read + write, to and from the instance
-- tree of codecs/model/Rbx (an RbxTree, kind "rbxtree"; not a Scene: Roblox files hold instances, not meshes).
-- Written from the rbx-dom format notes (docs/binary.md); checked against rojo 7.7 and lune 0.11 (rbx-dom) both ways.
-- Decode: the header, META (tree.metadata), SSTR (shared strings), INST (classes, referents, service flags), PROP (every
-- property type of codecs/model/Rbx/Binary), PRNT (the hierarchy), END; chunk bodies raw, LZ4 or Zstandard. Unknown
-- chunks are kept raw in tree.extra and written back; properties of unknown types become "Raw" values that are
-- written back verbatim while the class keeps its instances. tree.place is true when the file marks services (rbxl).
-- Encode: every instance depth first (referents 0..n-1), classes sorted by name, properties sorted by name, chunks
-- LZ4-compressed (opts.compression = "none" writes them raw), SharedStrings deduplicated (MD5 keys). An instance
-- without a property its class's other instances have gets the type's default (the format stores one value per
-- instance). "XmlRaw" values (unknown XML types) are skipped. Not supported: writing Zstandard chunks.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Md5 = require("@formats/core/Md5")
local Lz4 = require("@formats/codecs/compress/Lz4")
local Zstd = require("@formats/codecs/compress/Zstd")
local Rbx = require("@formats/codecs/model/Rbx")
local Binary = require("@formats/codecs/model/Rbx/Binary")
-- ------------------------------------------------------------------------------------------------ contract
local Rbxm = {
name = "rbxm",
category = "model",
extensions = { "rbxm", "rbxl" },
mime = { "application/x-roblox-rbxm", "application/x-roblox-rbxl" },
deps = { "core/Err", "core/Bytes", "core/Md5", "codecs/compress/Lz4", "codecs/compress/Zstd", "codecs/model/Rbx", "codecs/model/Rbx/Binary" },
caps = { decode = true, encode = true, tree = true, compression = { "none", "lz4", "zstd" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxBytes: number?, -- the largest decompressed chunk (default 2^28)
maxInstances: number?, -- default 2^22
}
export type EncodeOptions = {
compression: ("lz4" | "none")?, -- chunk bodies (default "lz4"; END is always raw)
place: boolean?, -- mark the roots as services (an .rbxl; default tree.place, or format = "rbxl")
format: string?, -- "rbxl" writes a place
}
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = "<roblox!\137\255\13\10\26\10"
local readu8, readu32, readi32, readstring = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readstring
-- ------------------------------------------------------------------------------------------------ sniff
function Rbxm.sniff(r: Bytes.Reader): number
return if r:peek(14) == MAGIC then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
type Class = { id: number, name: string, refs: { number }, service: boolean }
-- a length-prefixed string at p of b (limit e): string, next | nil
local function str(b: buffer, p: number, e: number): (string?, number)
if p + 4 > e then
return nil, p
end
local n = readu32(b, p)
if p + 4 + n > e then
return nil, p
end
return readstring(b, p + 4, n), p + 4 + n
end
function Rbxm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 28
local maxInstances = opts and opts.maxInstances or 2 ^ 22
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 32 then
return nil, Err.new(Err.TRUNCATED, "header", base)
end
if readstring(b, base, 14) ~= MAGIC then
return nil, Err.new(Err.CORRUPT, "bad signature", base)
end
local version = buffer.readu16(b, base + 14)
if version ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "format version " .. version, base + 14)
end
local nClasses, nInstances = readi32(b, base + 16), readi32(b, base + 20)
if nClasses < 0 or nInstances < 0 then
return nil, Err.new(Err.CORRUPT, "negative counts", base + 16)
end
if nInstances > maxInstances then
return nil, Err.new(Err.LIMIT, "limit: " .. nInstances .. " instances", base + 20)
end
local tree = Rbx.tree()
tree.meta.source = { format = "rbxm", version = version, classes = nClasses, instances = nInstances, compression = {} }
local classes: { [number]: Class } = {}
local byRef: { [number]: Rbx.Instance } = {}
local shared: { string } = {}
local parented: { [Rbx.Instance]: boolean } = {}
local order: { Rbx.Instance } = {}
local anyService = false
local comp: { [string]: boolean } = {}
local ctx: Binary.Ctx = {
ref = function(n: number): any
return byRef[n]
end,
shared = shared,
}
local p = base + 32
local ended = false
while p < limit do
if p + 16 > limit then
return nil, Err.new(Err.TRUNCATED, "chunk header", p)
end
local name = readstring(b, p, 4)
local clen, ulen = readu32(b, p + 4), readu32(b, p + 8)
local at = p
p += 16
if ulen > maxBytes then
return nil, Err.new(Err.LIMIT, "limit: chunk of " .. ulen .. " bytes", at)
end
local body: buffer, bo: number, be: number
if clen == 0 then
if p + ulen > limit then
return nil, Err.new(Err.TRUNCATED, "chunk " .. name .. " runs past the end", at)
end
body, bo, be = b, p, p + ulen
p += ulen
comp.none = true
else
if p + clen > limit then
return nil, Err.new(Err.TRUNCATED, "chunk " .. name .. " runs past the end", at)
end
local out, err
if Zstd.isFrame(b, p) then
out, err = Zstd.decompress(b, p, clen, { maxBytes = ulen })
comp.zstd = true
else
out, err = Lz4.decompress(b, p, clen, ulen)
comp.lz4 = true
end
if not out then
return nil, err
end
if buffer.len(out) ~= ulen then
return nil, Err.new(Err.CORRUPT, "chunk " .. name .. " decompresses to the wrong size", at)
end
body, bo, be = out, 0, ulen
p += clen
end
if name == "END\0" then
ended = true
break
elseif name == "META" then
if bo + 4 > be then
return nil, Err.new(Err.TRUNCATED, "META", at)
end
local q = bo + 4
for _ = 1, readu32(body, bo) do
local k, q1 = str(body, q, be)
local v, q2 = str(body, q1, be)
if not k or not v then
return nil, Err.new(Err.TRUNCATED, "META entry", at)
end
tree.metadata[k] = v
q = q2
end
elseif name == "SSTR" then
if bo + 8 > be then
return nil, Err.new(Err.TRUNCATED, "SSTR", at)
end
local q = bo + 8
for i = 1, readu32(body, bo + 4) do
local s, q2 = str(body, q + 16, be)
if not s then
return nil, Err.new(Err.TRUNCATED, "shared string", at)
end
shared[i] = s
q = q2
end
elseif name == "INST" then
local id = if bo + 4 <= be then readi32(body, bo) else -1
local cname, q = str(body, bo + 4, be)
if not cname or q + 5 > be then
return nil, Err.new(Err.TRUNCATED, "INST", at)
end
local fmt, count = readu8(body, q), readu32(body, q + 1)
if count > nInstances then
return nil, Err.new(Err.CORRUPT, "more instances than the header says", at)
end
local refs, q2 = Binary.readRefs(body, q + 5, be, count)
if not refs then
return nil, Err.new(Err.TRUNCATED, "INST referents", at)
end
if id < 0 or classes[id] then
return nil, Err.new(Err.CORRUPT, "bad class id " .. id, at)
end
local service = fmt == 1
if service and q2 + count > be then
return nil, Err.new(Err.TRUNCATED, "INST service markers", at)
end
classes[id] = { id = id, name = cname, refs = refs, service = service }
for i, ref in refs do
if byRef[ref] then
return nil, Err.new(Err.CORRUPT, "referent " .. ref .. " used twice", at)
end
local inst = Rbx.instance(cname)
inst.referent = tostring(ref)
if service and readu8(body, q2 + i - 1) ~= 0 then
inst.service = true
anyService = true
end
byRef[ref] = inst
table.insert(order, inst)
end
elseif name == "PROP" then
local id = if bo + 4 <= be then readi32(body, bo) else -1
local pname, q = str(body, bo + 4, be)
if not pname or q + 1 > be then
return nil, Err.new(Err.TRUNCATED, "PROP", at)
end
local cls = classes[id]
if not cls then
return nil, Err.new(Err.CORRUPT, "PROP for an unknown class " .. id, at)
end
local t = readu8(body, q)
local n = #cls.refs
local vals, msg = Binary.decode(t, body, q + 1, be, n, ctx)
if vals then
local tname = Rbx.TYPE_NAMES[t]
for i, ref in cls.refs do
local inst = byRef[ref]
if pname == "Name" and t == 0x01 then
inst.name = vals[i]
else
inst.properties[pname] = { type = tname, value = vals[i] }
end
end
elseif msg == "unknown" then
local data = buffer.create(be - q - 1)
buffer.copy(data, 0, body, q + 1, be - q - 1)
for i, ref in cls.refs do
byRef[ref].properties[pname] = { type = "Raw", value = { typeId = t, data = data, index = i, count = n } }
end
else
return nil, Err.from(msg, at)
end
elseif name == "PRNT" then
if bo + 5 > be then
return nil, Err.new(Err.TRUNCATED, "PRNT", at)
end
if readu8(body, bo) ~= 0 then
return nil, Err.new(Err.UNSUPPORTED, "PRNT version " .. readu8(body, bo), at)
end
local count = readu32(body, bo + 1)
local kids, q = Binary.readRefs(body, bo + 5, be, count)
local parents = if kids then Binary.readRefs(body, q, be, count) else nil
if not kids or not parents then
return nil, Err.new(Err.TRUNCATED, "PRNT referents", at)
end
for i = 1, count do
local child, parent = byRef[kids[i]], parents[i] >= 0 and byRef[parents[i]] or nil
if not child or (parents[i] >= 0 and not parent) then
return nil, Err.new(Err.CORRUPT, "PRNT names an unknown referent", at)
end
if parented[child] then
return nil, Err.new(Err.CORRUPT, "an instance with two parents", at)
end
parented[child] = true
-- refuse cycles: the parent may not be a descendant of the child
local up: Rbx.Instance? = parent
while up do
if up == child then
return nil, Err.new(Err.CORRUPT, "a cycle in the hierarchy", at)
end
up = up.parent
end
Rbx.add(parent or tree, child)
end
else
local data = buffer.create(be - bo)
buffer.copy(data, 0, body, bo, be - bo)
table.insert(tree.extra, { name = name, data = data })
end
end
if not ended then
return nil, Err.new(Err.TRUNCATED, "no END chunk", limit)
end
-- instances PRNT does not mention are roots
for _, inst in order do
if not parented[inst] then
table.insert(tree.roots, inst)
end
end
tree.place = anyService
local list = {}
for k in comp do
table.insert(list, k)
end
table.sort(list)
local src: any = tree.meta.source
src.compression = list
return tree, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- the binary type of a property over a class's instances: type id, type name | nil, message
local function columnType(insts: { Rbx.Instance }, pname: string): (number?, string?)
local id, tname = nil, nil
for _, inst in insts do
local v = inst.properties[pname]
if v then
if type(v) ~= "table" or type(v.type) ~= "string" then
return nil, "property " .. pname .. " of " .. inst.className .. " is not a { type, value } table"
end
local t = if v.type == "Raw" then -1 elseif v.type == "XmlRaw" then -2 else Rbx.TYPE_IDS[v.type]
if not t then
return nil, "property " .. pname .. ": unknown type " .. v.type
end
if id == nil then
id, tname = t, v.type
elseif id ~= t then
return nil, "property " .. pname .. " of " .. inst.className .. " has values of types " .. tostring(tname) .. " and " .. v.type
end
end
end
return id, tname
end
local function chunk(w: Bytes.Writer, name: string, body: buffer, compress: boolean)
w:string(name)
local n = buffer.len(body)
if compress then
local z = Lz4.compress(body) :: buffer
w:u32le(buffer.len(z))
w:u32le(n)
w:u32le(0)
w:bytes(z)
else
w:u32le(0)
w:u32le(n)
w:u32le(0)
w:bytes(body)
end
end
local function putStr(w: Bytes.Writer, s: string)
w:u32le(#s)
w:string(s)
end
function Rbxm.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(tree) ~= "table" or tree.kind ~= "rbxtree" or type(tree.roots) ~= "table" then
return nil, Err.new(Err.ARG, "expected an RbxTree (codecs/model/Rbx)")
end
local o: any = opts or {}
local compress = o.compression ~= "none"
local place = if o.place ~= nil then o.place == true elseif o.format == "rbxl" then true else tree.place == true
-- every instance depth first; referents in that order
local insts: { Rbx.Instance } = {}
local refOf: { [any]: number } = {}
local parentOf: { [Rbx.Instance]: Rbx.Instance? } = {}
local function visit(inst: any, parent: Rbx.Instance?): Err.Err?
if type(inst) ~= "table" or type(inst.className) ~= "string" or type(inst.properties) ~= "table" then
return Err.new(Err.ARG, "an instance needs className and properties")
end
if refOf[inst] then
return Err.new(Err.ARG, "an instance appears twice in the tree")
end
refOf[inst] = #insts
table.insert(insts, inst)
parentOf[inst] = parent
for _, c in inst.children or {} do
local e = visit(c, inst)
if e then
return e
end
end
return nil
end
for _, root in tree.roots do
local e = visit(root, nil)
if e then
return nil, e
end
end
-- classes by name
local byClass: { [string]: { Rbx.Instance } } = {}
local names = {}
for _, inst in insts do
local list = byClass[inst.className]
if not list then
list = {}
byClass[inst.className] = list
table.insert(names, inst.className)
end
table.insert(list, inst)
end
table.sort(names)
-- shared strings, in order of first use
local sharedIdx: { [string]: number } = {}
local sharedList: { string } = {}
local ctx: Binary.Ctx = {
refOf = function(v: any): number
return refOf[v] or -1
end,
sharedIndex = function(s: string): number
local i = sharedIdx[s]
if not i then
table.insert(sharedList, s)
i = #sharedList - 1
sharedIdx[s] = i
end
return i
end,
}
local props: { buffer } = {}
local instChunks: { buffer } = {}
for classId, cname in names do
local list = byClass[cname]
local id = classId - 1
-- INST
local w = Bytes.writer(64 + 5 * #list)
w:u32le(id)
putStr(w, cname)
local service = place and parentOf[list[1]] == nil
for _, inst in list do
if inst.service then
service = true
end
end
w:u8(if service then 1 else 0)
w:u32le(#list)
local refs = table.create(#list, 0)
for i, inst in list do
refs[i] = refOf[inst]
end
Binary.writeRefs(w, refs)
if service then
for _, inst in list do
w:u8(if inst.service or (place and parentOf[inst] == nil) then 1 else 0)
end
end
table.insert(instChunks, w:finish())
-- PROP: Name, then every property any instance of the class has, sorted
local pnames: { string } = {}
local seen: { [string]: boolean } = {}
for _, inst in list do
for pn in inst.properties do
if not seen[pn] and pn ~= "Name" then
seen[pn] = true
table.insert(pnames, pn)
end
end
end
table.sort(pnames)
table.insert(pnames, 1, "Name")
for _, pn in pnames do
local t: number?, tname: string?
if pn == "Name" then
t, tname = 0x01, "String"
else
local e
t, e = columnType(list, pn)
if not t then
return nil, Err.new(Err.ARG, e or "bad property")
end
tname = e
end
local pw = Bytes.writer(64)
pw:u32le(id)
putStr(pw, pn)
local tid = t :: number
if tid == -1 then
-- Raw: the column read from a file, written back only when this class still has exactly its instances
local first = list[1].properties[pn]
local raw = first and first.value
local ok = type(raw) == "table" and raw.count == #list and type(raw.data) == "buffer"
if ok then
for i, inst in list do
local v = inst.properties[pn]
if not v or v.type ~= "Raw" or v.value.data ~= raw.data or v.value.index ~= i then
ok = false
break
end
end
end
if ok then
pw:u8(raw.typeId)
pw:bytes(raw.data)
table.insert(props, pw:finish())
end
elseif tid ~= -2 then
pw:u8(tid)
local vals = table.create(#list)
for i, inst in list do
if pn == "Name" then
vals[i] = if type(inst.name) == "string" then inst.name else inst.className
else
local v = inst.properties[pn]
if v then
vals[i] = v.value
else
vals[i] = Rbx.default(tname :: string)
end
end
end
local e = Binary.encode(tid, vals, #list, pw, ctx)
if e then
return nil, Err.new(Err.ARG, "property " .. pn .. ": " .. e)
end
table.insert(props, pw:finish())
end
end
end
-- PRNT
local pw = Bytes.writer(16 + 8 * #insts)
pw:u8(0)
pw:u32le(#insts)
local kids, parents = table.create(#insts, 0), table.create(#insts, 0)
for i, inst in insts do
kids[i] = i - 1
local par = parentOf[inst]
parents[i] = if par then refOf[par] else -1
end
Binary.writeRefs(pw, kids)
Binary.writeRefs(pw, parents)
local out = Bytes.writer(1024)
out:string(MAGIC)
out:u16le(0)
out:u32le(#names)
out:u32le(#insts)
out:u32le(0)
out:u32le(0)
local metaKeys = {}
for k, v in tree.metadata or {} do
if type(k) == "string" and type(v) == "string" then
table.insert(metaKeys, k)
end
end
if #metaKeys > 0 then
table.sort(metaKeys)
local mw = Bytes.writer(64)
mw:u32le(#metaKeys)
for _, k in metaKeys do
putStr(mw, k)
putStr(mw, (tree.metadata :: any)[k])
end
chunk(out, "META", mw:finish(), compress)
end
if #sharedList > 0 then
local sw = Bytes.writer(64)
sw:u32le(0)
sw:u32le(#sharedList)
for _, s in sharedList do
local h = Md5.new()
h:update(buffer.fromstring(s))
sw:string(h:digest())
putStr(sw, s)
end
chunk(out, "SSTR", sw:finish(), compress)
end
for _, c in instChunks do
chunk(out, "INST", c, compress)
end
for _, c in props do
chunk(out, "PROP", c, compress)
end
chunk(out, "PRNT", pw:finish(), compress)
for _, x in tree.extra or {} do
if type(x) == "table" and type(x.name) == "string" and #x.name == 4 and type(x.data) == "buffer" then
chunk(out, x.name, x.data, compress)
end
end
chunk(out, "END\0", buffer.fromstring("</roblox>"), false)
return out:finish(), nil
end
return Rbxm
+661
View File
@@ -0,0 +1,661 @@
--!strict
-- model/rbxmx: the Roblox XML model / place format (.rbxmx / .rbxlx, `<roblox version="4">`), read + write, to and from
-- the instance tree of codecs/model/Rbx (an RbxTree, as model/rbxm: converting between the two is load + save).
-- Written from the rbx-dom format notes (docs/xml.md); checked against rojo 7.7 and lune 0.11 (rbx-dom) both ways.
-- Decode: <Meta>, <Item class referent> with <Properties> of every type codecs/model/Rbx lists (string, BinaryString
-- (base64), ProtectedString, Content (url / uri / null), ContentId, bool, int, int64, float, double (INF / NAN),
-- token, BrickColor (as rbx-dom: an <int>; read back as BrickColor for the BrickColor properties of a short
-- built-in list), Color3 (components or packed ARGB), Color3uint8, Vector2 / 3 (int16), CoordinateFrame,
-- OptionalCoordinateFrame, UDim / UDim2, Rect2D, Ray, Faces, Axes, NumberSequence, ColorSequence, NumberRange,
-- PhysicalProperties, Ref, SharedString (+ <SharedStrings>), UniqueId, Font, SecurityCapabilities); unknown property
-- tags are kept as "XmlRaw" values and written back as they are; unknown top-level elements go to tree.extra.
-- tree.place is true when a root is a Workspace (rbxlx).
-- Encode: rbx-dom's layout (version 4, referents "RBX" + 32 hex digits, properties sorted by name, two-space indent,
-- floats as the shortest text that reads back to the same f32 / f64). A String holding bytes XML cannot carry (control
-- characters, invalid UTF-8) is written as a BinaryString. "Raw" values (unknown binary types) are skipped.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Base64 = require("@formats/core/Base64")
local Md5 = require("@formats/core/Md5")
local Xml = require("@formats/codecs/text/Xml")
local Rbx = require("@formats/codecs/model/Rbx")
-- ------------------------------------------------------------------------------------------------ contract
local Rbxmx = {
name = "rbxmx",
category = "model",
extensions = { "rbxmx", "rbxlx" },
mime = { "application/x-roblox-rbxmx", "application/x-roblox-rbxlx" },
deps = { "core/Err", "core/Bytes", "core/Base64", "core/Md5", "codecs/text/Xml", "codecs/model/Rbx" },
caps = { decode = true, encode = true, tree = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxDepth: number?, -- XML nesting limit (default 10000)
}
export type EncodeOptions = {
indent: (number | string)?, -- default 2 spaces; 0 for none
}
-- ------------------------------------------------------------------------------------------------ constants
local XmlNode = Xml.element
local find, format, match, gmatch = string.find, string.format, string.match, string.gmatch
-- tag name -> type name for the simple (text) types
local SCALAR_TAGS: { [string]: string } = {
string = "String",
ProtectedString = "ProtectedString",
bool = "Bool",
int = "Int32",
int64 = "Int64",
float = "Float32",
double = "Float64",
token = "Enum",
BrickColor = "BrickColor",
SecurityCapabilities = "SecurityCapabilities",
UniqueId = "UniqueId",
}
-- BrickColor properties: XML writes them as <int> (rbx-dom reads them through its reflection database); these known ones
-- read back as BrickColor (the rest of an <int> stays Int32)
local BRICKCOLOR: { [string]: boolean } = {
["BrickColorValue.Value"] = true,
["SpawnLocation.TeamColor"] = true,
["Team.TeamColor"] = true,
["FlagStand.TeamColor"] = true,
["Skin.SkinColor"] = true,
}
-- the strings rbx-dom writes as BinaryString (the rest decides by content)
local BINARY_NAMES: { [string]: boolean } = { AttributesSerialize = true, Tags = true, MaterialColors = true, SmoothGrid = true, PhysicsGrid = true }
-- ------------------------------------------------------------------------------------------------ sniff
function Rbxmx.sniff(r: Bytes.Reader): number
local head = r:peek(256)
head = string.gsub(head, "^\239\187\191", "")
head = string.gsub(head, "^%s*<%?xml[^>]*%?>", "")
if match(head, "^%s*<roblox[%s>]") then
return if find(head, "version=", 1, true) then 1 else 0.8
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function num(s: string?): number
if s == nil then
return 0
end
local t = string.lower((string.gsub(s, "^%s+", "")))
t = string.gsub(t, "%s+$", "")
if t == "inf" or t == "+inf" or t == "infinity" then
return math.huge
elseif t == "-inf" or t == "-infinity" then
return -math.huge
elseif t == "nan" or t == "-nan" then
return 0 / 0
end
return tonumber(t) or 0
end
local function childText(node: Xml.Node, name: string): string?
local c = Xml.child(node, name)
return if c then Xml.text(c) else nil
end
local function comps(node: Xml.Node?, names: { string }): { number }
local out = table.create(#names, 0)
if node then
for i, n in names do
out[i] = num(childText(node, n))
end
end
return out
end
local function numbers(s: string): { number }
local out = {}
for w in gmatch(s, "%S+") do
table.insert(out, num(w))
end
return out
end
local CF_NAMES = { "X", "Y", "Z", "R00", "R01", "R02", "R10", "R11", "R12", "R20", "R21", "R22" }
local PHYS_NAMES = { "Density", "Friction", "Elasticity", "FrictionWeight", "ElasticityWeight" }
-- a property element -> type name, value | nil (unknown: XmlRaw). refs: referent -> instance (filled later: Refs
-- come back as { pending = referent })
local function readRaw(node: Xml.Node, shared: { [string]: string }, key: string): (string, any)
local tag = node.name
local scalar = SCALAR_TAGS[tag]
if tag == "int" and BRICKCOLOR[key] then
scalar = "BrickColor"
end
if scalar then
local s = Xml.text(node)
if scalar == "String" or scalar == "ProtectedString" then
return scalar, s
elseif scalar == "Bool" then
return scalar, match(s, "^%s*true%s*$") ~= nil
elseif scalar == "UniqueId" then
return scalar, string.lower((string.gsub(s, "%s", "")))
end
return scalar, num(s)
elseif tag == "BinaryString" then
local data = Base64.decode((string.gsub(Xml.text(node), "%s", "")))
return "BinaryString", if data then buffer.tostring(data) else ""
elseif tag == "Content" or tag == "ContentId" then
local url = Xml.child(node, "url")
if url then
return "ContentId", Xml.text(url)
end
local uri = Xml.child(node, "uri")
if uri then
return "Content", Xml.text(uri)
end
local obj = Xml.child(node, "Object") or Xml.child(node, "Ref")
if obj then
return "Content", { pending = Xml.text(obj) }
end
if Xml.child(node, "null") then
return (if tag == "ContentId" then "ContentId" else "Content"), (if tag == "ContentId" then "" else nil)
end
return "ContentId", Xml.text(node)
elseif tag == "Vector2" or tag == "Vector2int16" then
return tag, comps(node, { "X", "Y" })
elseif tag == "Vector3" or tag == "Vector3int16" then
return tag, comps(node, { "X", "Y", "Z" })
elseif tag == "Color3" then
if Xml.child(node, "R") then
return tag, comps(node, { "R", "G", "B" })
end
local v = num(Xml.text(node)) % 4294967296
return tag, { (v // 65536) % 256 / 255, (v // 256) % 256 / 255, v % 256 / 255 }
elseif tag == "Color3uint8" then
local v = num(Xml.text(node)) % 4294967296
return tag, { (v // 65536) % 256, (v // 256) % 256, v % 256 }
elseif tag == "CoordinateFrame" or tag == "CFrame" then
return "CFrame", comps(node, CF_NAMES)
elseif tag == "OptionalCoordinateFrame" then
local cf = Xml.child(node, "CFrame")
return "OptionalCFrame", if cf then comps(cf, CF_NAMES) else nil
elseif tag == "UDim" then
return tag, comps(node, { "S", "O" })
elseif tag == "UDim2" then
return tag, comps(node, { "XS", "XO", "YS", "YO" })
elseif tag == "Rect2D" then
local a, b = comps(Xml.child(node, "min"), { "X", "Y" }), comps(Xml.child(node, "max"), { "X", "Y" })
return "Rect", { a[1], a[2], b[1], b[2] }
elseif tag == "Ray" then
local a, b = comps(Xml.child(node, "origin"), { "X", "Y", "Z" }), comps(Xml.child(node, "direction"), { "X", "Y", "Z" })
return tag, { a[1], a[2], a[3], b[1], b[2], b[3] }
elseif tag == "Faces" or tag == "Axes" then
local t = childText(node, string.lower(tag))
return tag, num(t or Xml.text(node))
elseif tag == "NumberRange" then
local v = numbers(Xml.text(node))
return tag, { v[1] or 0, v[2] or 0 }
elseif tag == "NumberSequence" or tag == "ColorSequence" then
local k = if tag == "NumberSequence" then 3 else 5
local v = numbers(Xml.text(node))
local seq = {}
for i = 1, #v - k + 1, k do
table.insert(seq, table.move(v, i, i + k - 1, 1, table.create(k, 0)))
end
return tag, seq
elseif tag == "PhysicalProperties" then
local custom = childText(node, "CustomPhysics")
if not custom or not match(custom, "^%s*true%s*$") then
return tag, nil
end
local v = comps(node, PHYS_NAMES)
local a = childText(node, "AcousticAbsorption")
v[6] = if a then num(a) else 1
return tag, v
elseif tag == "Ref" then
local s = string.gsub(Xml.text(node), "%s", "")
return tag, if s == "" or s == "null" then nil else { pending = s }
elseif tag == "SharedString" then
local key = string.gsub(Xml.text(node), "%s", "")
return tag, shared[key] or ""
elseif tag == "Font" then
local fam = Xml.child(node, "Family")
local face = Xml.child(node, "CachedFaceId")
local f = {
family = if fam then childText(fam, "url") or Xml.text(fam) else "",
weight = num(childText(node, "Weight") or "400"),
style = if match(childText(node, "Style") or "", "Italic") then "Italic" else "Normal",
cachedFaceId = if face then childText(face, "url") or nil else nil,
}
if f.cachedFaceId == "" then
f.cachedFaceId = nil
end
return tag, f
end
return "XmlRaw", node
end
-- single-precision types: their components rounded to f32 (as a binary file stores them), so XML and binary
-- decodes of the same data are equal. Which components are floats, by type (true = all)
local F32: { [string]: any } = {
Float32 = true,
Vector2 = true,
Vector3 = true,
Color3 = true,
CFrame = true,
OptionalCFrame = true,
Rect = true,
Ray = true,
NumberRange = true,
NumberSequence = true,
ColorSequence = true,
PhysicalProperties = true,
UDim = { true, false },
UDim2 = { true, false, true, false },
}
local f32buf = buffer.create(4)
local function f32(v: number): number
buffer.writef32(f32buf, 0, v)
return buffer.readf32(f32buf, 0)
end
local function round32(v: any, which: any): any
if type(v) == "number" then
return f32(v)
elseif type(v) == "table" then
for i, x in v do
if type(x) == "table" then
round32(x, true)
elseif type(x) == "number" and (which == true or which[i]) then
v[i] = f32(x)
end
end
end
return v
end
local function readValue(node: Xml.Node, shared: { [string]: string }, key: string): (string, any)
local t, v = readRaw(node, shared, key)
local which = F32[t]
if which then
v = round32(v, which)
end
return t, v
end
function Rbxmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Rbx.Tree?, Err.Err?)
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local doc, err = Xml.decode(text, { maxDepth = opts and opts.maxDepth } :: any)
if not doc then
return nil, err
end
local root = (doc :: any).root
if not root or root.name ~= "roblox" then
return nil, Err.new(Err.CORRUPT, "the root element is not <roblox>")
end
local tree = Rbx.tree()
tree.meta.source = { format = "rbxmx", version = root.attrs.version }
-- shared strings first (properties name them by key)
local shared: { [string]: string } = {}
for _, ss in Xml.children(root, "SharedStrings") do
for _, s in Xml.children(ss, "SharedString") do
local key = s.attrs.md5
local data = Base64.decode((string.gsub(Xml.text(s), "%s", "")))
if key and data then
shared[key] = buffer.tostring(data)
end
end
end
local byRef: { [string]: Rbx.Instance } = {}
local pending: { { any } } = {} -- { value table, field, referent }
local function item(node: Xml.Node, parent: any): Err.Err?
local cls = node.attrs.class
if type(cls) ~= "string" then
return Err.new(Err.CORRUPT, "an <Item> without a class")
end
local inst = Rbx.instance(cls)
local ref = node.attrs.referent
if type(ref) == "string" then
inst.referent = ref
byRef[ref] = inst
end
Rbx.add(parent, inst)
for _, c in node.children do
if type(c) == "table" then
if c.name == "Properties" then
for _, pnode in c.children do
if type(pnode) == "table" and string.sub(pnode.name, 1, 1) ~= "#" then
local pname = pnode.attrs.name
if type(pname) == "string" then
local t, v = readValue(pnode, shared, cls .. "." .. pname)
if pname == "Name" and (t == "String" or t == "ProtectedString") then
inst.name = v
else
local val = { type = t, value = v }
inst.properties[pname] = val
if type(v) == "table" and v.pending then
table.insert(pending, { val, v.pending })
end
end
end
end
end
elseif c.name == "Item" then
local e = item(c, inst)
if e then
return e
end
end
end
end
return nil
end
for _, c in root.children do
if type(c) == "table" then
if c.name == "Item" then
local e = item(c, tree)
if e then
return nil, e
end
elseif c.name == "Meta" then
if type(c.attrs.name) == "string" then
tree.metadata[c.attrs.name] = Xml.text(c)
end
elseif c.name ~= "SharedStrings" and string.sub(c.name, 1, 1) ~= "#" then
table.insert(tree.extra, c)
end
end
end
for _, p in pending do
p[1].value = byRef[p[2]]
end
for _, rt in tree.roots do
if rt.className == "Workspace" then
tree.place = true
end
end
return tree, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- the shortest text that reads back as the same float (single: f32 values; else f64)
local function fmt(v: any, single: boolean?): string
if type(v) ~= "number" then
v = 0
end
if v ~= v then
return "NAN"
elseif v == math.huge then
return "INF"
elseif v == -math.huge then
return "-INF"
end
if single then
v = f32(v)
end
if v == math.floor(v) and math.abs(v) < 2 ^ 53 then
return format("%.0f", v)
end
for d = if single then 6 else 15, if single then 9 else 17 do
local s = format("%." .. d .. "g", v)
local back = tonumber(s) or 0
if (if single then f32(back) else back) == v then
return s
end
end
return format("%.17g", v)
end
local function int(v: any): string
return format("%.0f", math.floor(if type(v) == "number" and v == v and math.abs(v) ~= math.huge then v else 0))
end
local function textEl(tag: string, text: string): Xml.Node
return XmlNode(tag, nil, { text })
end
local function compsEl(tag: string, attrs: { [string]: string }?, names: { string }, v: any, single: boolean?, ints: boolean?): Xml.Node
local kids = {}
for i, n in names do
local x = if type(v) == "table" then v[i] else 0
table.insert(kids, textEl(n, if ints then int(x) else fmt(x, single)))
end
return XmlNode(tag, attrs, kids)
end
local function hexDigits(i: number): string
return format("%032X", i)
end
local function xmlSafe(s: string): boolean
if find(s, "[%z\1-\8\11\12\14-\31\127]") then
return false
end
return utf8.len(s) ~= nil
end
-- a property -> its element, or nil to skip
local function writeValue(name: string, v: any, refOf: (any) -> string, sharedKey: (string) -> string): Xml.Node?
local t, x = v.type, v.value
local a = { name = name }
if t == "String" or t == "ProtectedString" or t == "BinaryString" or t == "Bytecode" then
local s = if type(x) == "string" then x else ""
if t == "BinaryString" or t == "Bytecode" or BINARY_NAMES[name] or not xmlSafe(s) then
return XmlNode("BinaryString", a, { Base64.encode(s) })
end
return XmlNode(if t == "ProtectedString" then "ProtectedString" else "string", a, { s })
elseif t == "ContentId" then
local s = if type(x) == "string" then x else ""
return XmlNode("ContentId", a, { if s == "" then XmlNode("null") else textEl("url", s) })
elseif t == "Content" then
if type(x) == "string" then
return XmlNode("Content", a, { textEl("uri", x) })
elseif type(x) == "table" then
return XmlNode("Content", a, { textEl("Object", refOf(x)) })
end
return XmlNode("Content", a, { XmlNode("null") })
elseif t == "Bool" then
return XmlNode("bool", a, { if x then "true" else "false" })
elseif t == "Int32" then
return XmlNode("int", a, { int(x) })
elseif t == "Int64" then
return XmlNode("int64", a, { int(x) })
elseif t == "Float32" then
return XmlNode("float", a, { fmt(x, true) })
elseif t == "Float64" then
return XmlNode("double", a, { fmt(x) })
elseif t == "Enum" then
return XmlNode("token", a, { int(x) })
elseif t == "BrickColor" then
return XmlNode("int", a, { int(x) })
elseif t == "SecurityCapabilities" then
return XmlNode("SecurityCapabilities", a, { int(x) })
elseif t == "UniqueId" then
return XmlNode("UniqueId", a, { if type(x) == "string" then string.lower(x) else string.rep("0", 32) })
elseif t == "Vector2" then
return compsEl(t, a, { "X", "Y" }, x, true)
elseif t == "Vector3" then
return compsEl(t, a, { "X", "Y", "Z" }, x, true)
elseif t == "Vector2int16" then
return compsEl(t, a, { "X", "Y" }, x, false, true)
elseif t == "Vector3int16" then
return compsEl(t, a, { "X", "Y", "Z" }, x, false, true)
elseif t == "Color3" then
return compsEl(t, a, { "R", "G", "B" }, x, true)
elseif t == "Color3uint8" then
local c = if type(x) == "table" then x else { 0, 0, 0 }
local function b(i: number): number
return math.clamp(math.floor(tonumber(c[i]) or 0), 0, 255)
end
return XmlNode(t, a, { int(b(1) * 65536 + b(2) * 256 + b(3)) })
elseif t == "CFrame" then
return compsEl("CoordinateFrame", a, CF_NAMES, x, true)
elseif t == "OptionalCFrame" then
return XmlNode("OptionalCoordinateFrame", a, if type(x) == "table" then { compsEl("CFrame", nil, CF_NAMES, x, true) } else {})
elseif t == "UDim" then
local u = if type(x) == "table" then x else { 0, 0 }
return XmlNode(t, a, { textEl("S", fmt(u[1], true)), textEl("O", int(u[2])) })
elseif t == "UDim2" then
local u = if type(x) == "table" then x else { 0, 0, 0, 0 }
return XmlNode(t, a, { textEl("XS", fmt(u[1], true)), textEl("XO", int(u[2])), textEl("YS", fmt(u[3], true)), textEl("YO", int(u[4])) })
elseif t == "Rect" then
local u = if type(x) == "table" then x else { 0, 0, 0, 0 }
return XmlNode("Rect2D", a, { compsEl("min", nil, { "X", "Y" }, { u[1], u[2] }, true), compsEl("max", nil, { "X", "Y" }, { u[3], u[4] }, true) })
elseif t == "Ray" then
local u = if type(x) == "table" then x else { 0, 0, 0, 0, 0, 0 }
return XmlNode(t, a, { compsEl("origin", nil, { "X", "Y", "Z" }, { u[1], u[2], u[3] }, true), compsEl("direction", nil, { "X", "Y", "Z" }, { u[4], u[5], u[6] }, true) })
elseif t == "Faces" or t == "Axes" then
return XmlNode(t, a, { textEl(string.lower(t), int(x)) })
elseif t == "NumberRange" or t == "NumberSequence" or t == "ColorSequence" then
local parts = {}
local list = if type(x) ~= "table" then {} elseif t == "NumberRange" then { x } else x
for _, key in list do
for _, c in key do
table.insert(parts, fmt(c, true) .. " ")
end
end
return XmlNode(t, a, { table.concat(parts) })
elseif t == "PhysicalProperties" then
if type(x) ~= "table" then
return XmlNode(t, a, { textEl("CustomPhysics", "false") })
end
local kids = { textEl("CustomPhysics", "true") }
for i, n in PHYS_NAMES do
table.insert(kids, textEl(n, fmt(x[i], true)))
end
table.insert(kids, textEl("AcousticAbsorption", fmt(if x[6] ~= nil then x[6] else 1, true)))
return XmlNode(t, a, kids)
elseif t == "Ref" then
return XmlNode("Ref", a, { if x ~= nil then refOf(x) else "null" })
elseif t == "SharedString" then
return XmlNode("SharedString", a, { sharedKey(if type(x) == "string" then x else "") })
elseif t == "Font" then
local f = if type(x) == "table" then x else Rbx.default("Font")
local kids = {
XmlNode("Family", nil, { textEl("url", if type(f.family) == "string" then f.family else "") }),
textEl("Weight", int(f.weight or 400)),
textEl("Style", if f.style == "Italic" then "Italic" else "Normal"),
}
if type(f.cachedFaceId) == "string" and f.cachedFaceId ~= "" then
table.insert(kids, XmlNode("CachedFaceId", nil, { textEl("url", f.cachedFaceId) }))
end
return XmlNode("Font", a, kids)
elseif t == "XmlRaw" then
if type(x) == "table" and type(x.name) == "string" then
local copy = XmlNode(x.name, nil, x.children)
for k, val in x.attrs do
Xml.setAttr(copy, k, val)
end
Xml.setAttr(copy, "name", name)
return copy
end
end
return nil
end
function Rbxmx.encode(tree: Rbx.Tree, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(tree) ~= "table" or tree.kind ~= "rbxtree" or type(tree.roots) ~= "table" then
return nil, Err.new(Err.ARG, "expected an RbxTree (codecs/model/Rbx)")
end
local refs: { [any]: string } = {}
local count = 0
local function assign(inst: any): Err.Err?
if type(inst) ~= "table" or type(inst.className) ~= "string" or type(inst.properties) ~= "table" then
return Err.new(Err.ARG, "an instance needs className and properties")
end
if refs[inst] then
return Err.new(Err.ARG, "an instance appears twice in the tree")
end
refs[inst] = "RBX" .. hexDigits(count)
count += 1
for _, c in inst.children or {} do
local e = assign(c)
if e then
return e
end
end
return nil
end
for _, rt in tree.roots do
local e = assign(rt)
if e then
return nil, e
end
end
local function refOf(x: any): string
return refs[x] or "null"
end
local sharedKeys: { [string]: string } = {}
local sharedList: { string } = {}
local function sharedKey(s: string): string
local k = sharedKeys[s]
if not k then
local h = Md5.new()
h:update(buffer.fromstring(s))
k = Base64.encode(h:digest())
sharedKeys[s] = k
table.insert(sharedList, s)
end
return k
end
local function item(inst: Rbx.Instance): Xml.Node
local props = { textEl("string", inst.name or inst.className) }
props[1].attrs.name = "Name"
local names: { string } = {}
for k in inst.properties do
if k ~= "Name" then
table.insert(names, k)
end
end
table.sort(names)
for _, k in names do
local v = inst.properties[k]
if type(v) == "table" then
local el = writeValue(k, v, refOf, sharedKey)
if el then
table.insert(props, el)
end
end
end
local kids = { XmlNode("Properties", nil, props) }
for _, c in inst.children or {} do
table.insert(kids, item(c))
end
local el = XmlNode("Item", nil, kids)
Xml.setAttr(el, "class", inst.className)
Xml.setAttr(el, "referent", refs[inst])
return el
end
local root = XmlNode("roblox", nil, {})
Xml.setAttr(root, "version", "4")
local metaKeys = {}
for k in tree.metadata or {} do
table.insert(metaKeys, k)
end
table.sort(metaKeys)
for _, k in metaKeys do
local m = textEl("Meta", tostring((tree.metadata :: any)[k]))
m.attrs.name = k
Xml.append(root, m)
end
for _, rt in tree.roots do
Xml.append(root, item(rt))
end
for _, x in tree.extra or {} do
if type(x) == "table" and type(x.name) == "string" and type(x.children) == "table" then
Xml.append(root, x)
end
end
if #sharedList > 0 then
local ss = XmlNode("SharedStrings", nil, {})
for _, s in sharedList do
local el = XmlNode("SharedString", nil, { Base64.encode(s) })
Xml.setAttr(el, "md5", sharedKeys[s])
Xml.append(ss, el)
end
Xml.append(root, ss)
end
local indent = if opts and opts.indent ~= nil then opts.indent else 2
local s, err = Xml.encode(root, { indent = indent, declaration = false, selfClose = false })
if not s then
return nil, err
end
return buffer.fromstring(s), nil
end
return Rbxmx