Files
rosetta/src/Formats/model/rbxm/init.luau
T

576 lines
18 KiB
Luau

--!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