Files
rosetta/src/Rosetta/containers/Blend.luau
T

738 lines
22 KiB
Luau

--!strict
-- containers/Blend: Blender .blend files (read only). New in rosetta, from the file layout: the 12-byte header
-- ("BLENDER", pointer size '_' 4 / '-' 8, endianness 'v' little / 'V' big, 3-digit version) or the 5.0+ header
-- ("BLENDER", header size "17", '-', format version "01", 'v', 4-digit version: 64-bit little endian, large BHeads);
-- file blocks (BHead: code, length, old address, SDNA index, count); the DNA1 block (SDNA: NAME / TYPE / TLEN / STRC,
-- each section 4-aligned from the block start); gzip (before 3.0) and zstd (3.0+, multi-frame) compressed files.
-- Structs are read by field name through the file's own SDNA; pointers resolve to blocks by old address.
local Err = require("@rosetta/core/Err")
local Deflate = require("@rosetta/codecs/compress/Deflate")
local Zstd = require("@rosetta/codecs/compress/Zstd")
local Blend = {}
local readu8, readu16, readu32, readi8, readi16, readi32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi8, buffer.readi16, buffer.readi32
local readf32, readf64, readstring = buffer.readf32, buffer.readf64, buffer.readstring
export type Field = {
name: string, -- without '*', '(*...)()' and array dimensions
decl: string, -- as declared ("*next", "co[3]", "mat[4][4]")
type: string,
offset: number,
size: number, -- bytes of the whole field (all array elements)
pointer: boolean,
dims: { number },
count: number, -- array elements (1 for scalars)
elem: number, -- bytes of one element
}
export type Struct = { name: string, index: number, size: number, fields: { Field }, byName: { [string]: Field } }
export type Dna = {
names: { string },
types: { string },
lengths: { number },
structs: { Struct }, -- 1-based; a block's sdna is 0-based
byName: { [string]: Struct },
}
export type Block = {
code: string, -- "OB", "ME", "DATA", ... (trailing NULs removed)
sdna: number, -- 0-based struct index
addr: any, -- the old address (a key: a number for 4-byte pointers, an 8-byte string for 8-byte ones)
size: number, -- data bytes
count: number, -- struct elements
offset: number, -- data start in file.buf
index: number,
owner: number, -- the index of the ID block this block follows (DATA blocks belong to the ID before them)
}
export type File = {
buf: buffer, -- the (decompressed) file
version: number, -- 279, 293, 401, 502, ...
subversion: number?, -- from the GLOB block
pointerSize: number,
little: boolean,
format: number, -- 0 (12-byte header) or the 5.0+ file format version
compression: string?, -- "gzip" | "zstd"
blocks: { Block },
byAddr: { [any]: Block },
shared: { [any]: { Block } }, -- addresses used by several blocks (reused between IDs): every block with it
byCode: { [string]: { Block } },
dna: Dna,
-- endian-aware readers (the little-endian ones are buffer's own)
u16: (b: buffer, o: number) -> number,
i16: (b: buffer, o: number) -> number,
u32: (b: buffer, o: number) -> number,
i32: (b: buffer, o: number) -> number,
f32: (b: buffer, o: number) -> number,
f64: (b: buffer, o: number) -> number,
}
export type Options = { maxBytes: number?, maxBlocks: number? }
-- ------------------------------------------------------------------------------------------------ readers
local function swap16(b: buffer, o: number): number
return readu8(b, o) * 256 + readu8(b, o + 1)
end
local function swap32(b: buffer, o: number): number
return ((readu8(b, o) * 256 + readu8(b, o + 1)) * 256 + readu8(b, o + 2)) * 256 + readu8(b, o + 3)
end
local scratch = buffer.create(8)
local function bei16(b: buffer, o: number): number
local v = swap16(b, o)
return if v >= 32768 then v - 65536 else v
end
local function bei32(b: buffer, o: number): number
local v = swap32(b, o)
return if v >= 2147483648 then v - 4294967296 else v
end
local function bef32(b: buffer, o: number): number
for k = 0, 3 do
buffer.writeu8(scratch, k, readu8(b, o + 3 - k))
end
return readf32(scratch, 0)
end
local function bef64(b: buffer, o: number): number
for k = 0, 7 do
buffer.writeu8(scratch, k, readu8(b, o + 7 - k))
end
return readf64(scratch, 0)
end
-- ------------------------------------------------------------------------------------------------ open
function Blend.sniff(buf: buffer, offset: number?, length: number?): number
local o = offset or 0
local n = length or (buffer.len(buf) - o)
if n >= 12 and readstring(buf, o, 7) == "BLENDER" then
return 1
end
if n >= 4 and readu8(buf, o) == 0x1f and readu8(buf, o + 1) == 0x8b then
return 0.05 -- a gzip member: blend only once decompressed
end
return 0
end
local function decompress(buf: buffer, o: number, n: number, opts: Options?): (buffer?, string?, any)
local maxBytes = opts and opts.maxBytes or 2 ^ 31
if n >= 4 and readu8(buf, o) == 0x1f and readu8(buf, o + 1) == 0x8b then
local out, err = Deflate.gunzip(buf, o, n)
if not out then
return nil, nil, err
end
if buffer.len(out) > maxBytes then
return nil, nil, Err.new(Err.LIMIT, "decompressed file over maxBytes")
end
return out, "gzip", nil
end
if n >= 4 and readu32(buf, o) == 0xFD2FB528 then
local out, err = Zstd.decompress(buf, o, n, { maxBytes = maxBytes })
if not out then
return nil, nil, err
end
return out, "zstd", nil
end
return nil, nil, nil
end
local function header(b: buffer, n: number): (number?, number, boolean, number, number, string?)
if n < 12 or readstring(b, 0, 7) ~= "BLENDER" then
return nil, 0, false, 0, 0, "not a .blend file (no BLENDER magic)"
end
local c = readstring(b, 7, 1)
if c == "_" or c == "-" then
local e = readstring(b, 8, 1)
local v = tonumber(readstring(b, 9, 3))
if (e ~= "v" and e ~= "V") or not v then
return nil, 0, false, 0, 0, "bad header"
end
return 12, if c == "_" then 4 else 8, e == "v", v, 0, nil
end
local hs = tonumber(readstring(b, 7, 2))
if not hs or hs < 17 or hs > n then
return nil, 0, false, 0, 0, "bad header size"
end
if readstring(b, 9, 1) ~= "-" or readstring(b, 12, 1) ~= "v" then
return nil, 0, false, 0, 0, "unsupported header: " .. readstring(b, 7, math.min(10, n - 7))
end
local fmt, v = tonumber(readstring(b, 10, 2)), tonumber(readstring(b, 13, 4))
if not fmt or not v then
return nil, 0, false, 0, 0, "bad header"
end
if fmt ~= 1 then
return nil, 0, false, 0, 0, "unsupported: file format version " .. fmt
end
return hs, 8, true, v, fmt, nil
end
local PRIM: { [string]: boolean } = {
char = true, uchar = true, short = true, ushort = true, int = true, uint = true, long = true, ulong = true,
float = true, double = true, int64_t = true, uint64_t = true, int8_t = true, uint8_t = true, int16_t = true,
uint16_t = true, int32_t = true, uint32_t = true, bool = true, void = true,
}
Blend.PRIMITIVE = PRIM
local function parseDna(f: File, at: number, size: number): string?
local b = f.buf
local e = at + size
local i32 = f.i32
local function align(p: number): number
return at + ((p - at + 3) // 4) * 4
end
local function strings(p: number, tag: string): ({ string }?, number)
if p + 8 > e or readstring(b, p, 4) ~= tag then
return nil, p
end
local n = i32(b, p + 4)
p += 8
if n < 0 or n > e - p then
return nil, p
end
local out = table.create(n) :: { string }
for k = 1, n do
local q = p
while q < e and readu8(b, q) ~= 0 do
q += 1
end
if q >= e then
return nil, p
end
out[k] = readstring(b, p, q - p)
p = q + 1
end
return out, p
end
if e > buffer.len(b) or size < 8 or readstring(b, at, 4) ~= "SDNA" then
return "no SDNA in DNA1"
end
local names, p = strings(at + 4, "NAME")
if not names then
return "bad SDNA NAME"
end
local types
types, p = strings(align(p), "TYPE")
if not types then
return "bad SDNA TYPE"
end
p = align(p)
local nt = #types
if p + 4 + nt * 2 > e or readstring(b, p, 4) ~= "TLEN" then
return "bad SDNA TLEN"
end
local lengths = table.create(nt) :: { number }
for k = 1, nt do
lengths[k] = f.u16(b, p + 4 + (k - 1) * 2)
end
p = align(p + 4 + nt * 2)
if p + 8 > e or readstring(b, p, 4) ~= "STRC" then
return "bad SDNA STRC"
end
local ns = i32(b, p + 4)
p += 8
if ns < 0 or ns * 4 > e - p then
return "bad SDNA struct count"
end
local i16 = f.i16
local ps = f.pointerSize
local structs, byName = table.create(ns) :: { Struct }, {} :: { [string]: Struct }
for k = 1, ns do
if p + 4 > e then
return "truncated SDNA structs"
end
local t, nf = i16(b, p), i16(b, p + 2)
p += 4
if t < 0 or t >= nt or nf < 0 or p + nf * 4 > e then
return "bad SDNA struct " .. k
end
local tnames = types :: { string }
local s: Struct = { name = tnames[t + 1], index = k - 1, size = lengths[t + 1], fields = table.create(nf) :: { Field }, byName = {} }
local off = 0
for j = 1, nf do
local ft, fn = i16(b, p), i16(b, p + 2)
p += 4
if ft < 0 or ft >= nt or fn < 0 or fn >= #names then
return "bad SDNA field in " .. s.name
end
local decl: string = (names :: { string })[fn + 1]
local pointer = string.sub(decl, 1, 1) == "*" or string.sub(decl, 1, 2) == "(*"
local dims: { number }, count = {}, 1
for d in string.gmatch(decl, "%[(%d+)%]") do
local v = tonumber(d) or 1
table.insert(dims, v)
count *= v
end
local base = string.gsub(decl, "%[.*$", "")
base = string.gsub(base, "[%*%(%)]", "")
local elem: number = if pointer then ps else lengths[ft + 1]
local fld: Field = {
name = base, decl = decl, type = tnames[ft + 1], offset = off, size = elem * count,
pointer = pointer, dims = dims, count = count, elem = elem,
}
s.fields[j] = fld
if s.byName[base] == nil then
s.byName[base] = fld
end
off += fld.size
end
structs[k] = s
byName[s.name] = s
end
f.dna = { names = names :: { string }, types = types :: { string }, lengths = lengths, structs = structs, byName = byName }
return nil
end
function Blend.open(data: buffer, offset: number?, length: number?, opts: Options?): (File?, Err.Err?)
local o = offset or 0
local n = length or (buffer.len(data) - o)
if o < 0 or n < 0 or o + n > buffer.len(data) then
return nil, Err.new(Err.ARG, "bad range")
end
local b: buffer
local unpacked, compression, derr = decompress(data, o, n, opts)
if derr then
return nil, derr
end
if unpacked then
b = unpacked
n = buffer.len(b)
elseif o == 0 and n == buffer.len(data) then
b = data
else
b = buffer.create(n)
buffer.copy(b, 0, data, o, n)
end
local hs, ps, little, version, fmt, herr = header(b, n)
if not hs then
local code = if n < 12 then Err.TRUNCATED elseif herr and string.sub(herr, 1, 12) == "unsupported:" then Err.UNSUPPORTED else Err.CORRUPT
return nil, Err.new(code, herr or "bad header", 0)
end
local f: File = {
buf = b, version = version, subversion = nil, pointerSize = ps, little = little, format = fmt,
compression = compression, blocks = {}, byAddr = {}, shared = {}, byCode = {}, dna = nil :: any,
u16 = if little then readu16 else swap16,
i16 = if little then readi16 else bei16,
u32 = if little then readu32 else swap32,
i32 = if little then readi32 else bei32,
f32 = if little then readf32 else bef32,
f64 = if little then readf64 else bef64,
}
local u32, i32 = f.u32, f.i32
local maxBlocks = opts and opts.maxBlocks or 2 ^ 22
local bh = if fmt >= 1 then 32 elseif ps == 8 then 24 else 20
local p = hs
local dnaBlock: Block? = nil
local owner = 0
while true do
if p + bh > n then
if p + 4 <= n and readstring(b, p, 4) == "ENDB" then
break -- ENDB written with a short head
end
return nil, Err.new(Err.TRUNCATED, "truncated block header (no ENDB)", p)
end
local code = readstring(b, p, 4)
local size, addr, sdna, count
if fmt >= 1 then
sdna = i32(b, p + 4)
addr = readstring(b, p + 8, 8)
local lo, hi = u32(b, p + 16), i32(b, p + 20)
local clo, chi = u32(b, p + 24), i32(b, p + 28)
if hi ~= 0 or chi ~= 0 then
return nil, Err.new(Err.LIMIT, "block over 4 GiB", p)
end
size, count = lo, clo
else
size = i32(b, p + 4)
addr = if ps == 8 then readstring(b, p + 8, 8) else u32(b, p + 8)
sdna = i32(b, p + 8 + ps)
count = i32(b, p + 12 + ps)
end
p += bh
-- two-letter ID codes are a 16-bit value in a 32-bit field: "\0\0SC" in big-endian files
code = string.gsub(string.gsub(code, "%z+$", ""), "^%z+", "")
if code == "ENDB" then
break
end
if size < 0 or count < 0 or size > n - p then
return nil, Err.new(Err.TRUNCATED, "block " .. code .. " past the end", p - bh)
end
if #f.blocks >= maxBlocks then
return nil, Err.new(Err.LIMIT, "too many blocks")
end
local index = #f.blocks + 1
if code ~= "DATA" then
owner = index
end
local blk: Block = { code = code, sdna = sdna, addr = addr, size = size, count = count, offset = p, index = index, owner = owner }
table.insert(f.blocks, blk)
local prev = f.byAddr[addr]
if prev == nil then
f.byAddr[addr] = blk
else
local list = f.shared[addr]
if not list then
list = { prev }
f.shared[addr] = list
end
table.insert(list, blk)
end
local list = f.byCode[code]
if not list then
list = {}
f.byCode[code] = list
end
table.insert(list, blk)
if code == "DNA1" then
dnaBlock = blk
end
p += size
end
if not dnaBlock then
return nil, Err.new(Err.CORRUPT, "no DNA1 block")
end
local derr2 = parseDna(f, dnaBlock.offset, dnaBlock.size)
if derr2 then
return nil, Err.new(Err.CORRUPT, derr2, dnaBlock.offset)
end
f.byAddr[if ps == 8 then string.rep("\0", 8) else 0] = nil
local glob = f.byCode.GLOB
local fg = f.dna.byName.FileGlobal
local g1: Block? = if glob then glob[1] else nil
local fld = fg and fg.byName.subversion
if g1 and fld then
if fld.offset + 2 <= g1.size then
f.subversion = f.i16(b, g1.offset + fld.offset)
end
end
return f, nil
end
-- ------------------------------------------------------------------------------------------------ structs
local View = {}
View.__index = View
Blend.View = View
export type View = typeof(setmetatable(
{} :: {
file: File,
struct: Struct,
offset: number, -- the struct's first byte in file.buf
block: Block?,
},
View
))
local function view(f: File, s: Struct, offset: number, blk: Block?): View
return setmetatable({ file = f, struct = s, offset = offset, block = blk }, View)
end
function Blend.structOf(f: File, blk: Block): Struct?
return f.dna.structs[blk.sdna + 1]
end
function Blend.struct(f: File, blk: Block, i: number?, as: string?): View?
local s = if as then f.dna.byName[as] else f.dna.structs[blk.sdna + 1]
if not s then
return nil
end
local at = (i or 0) * s.size
if at < 0 or at + s.size > blk.size then
return nil
end
return view(f, s, blk.offset + at, blk)
end
function Blend.view(f: File, structName: string, offset: number): View?
local s = f.dna.byName[structName]
if not s or offset < 0 or offset + s.size > buffer.len(f.buf) then
return nil
end
return view(f, s, offset, nil)
end
function Blend.field(f: File, structName: string, ...: string): Field?
local s = f.dna.byName[structName]
if not s then
return nil
end
for _, name in { ... } do
local fld = s.byName[name]
if fld then
return fld
end
end
return nil
end
function Blend.blocks(f: File, code: string): { Block }
return f.byCode[code] or {}
end
local function pointerKey(f: File, o: number): any
local b = f.buf
if f.pointerSize == 8 then
if readu32(b, o) == 0 and readu32(b, o + 4) == 0 then
return nil
end
return readstring(b, o, 8)
end
local v = f.u32(b, o)
return if v == 0 then nil else v
end
Blend.pointerKey = pointerKey
-- addresses are unique among live allocations only: a DATA block is looked up among the blocks of the ID the
-- pointer comes from first (from = the block holding the pointer), as Blender's reader does
function Blend.resolve(f: File, addr: any, from: Block?): Block?
if addr == nil then
return nil
end
local list = f.shared[addr]
if list and from then
for _, b in list do
if b.owner == from.owner then
return b
end
end
end
return f.byAddr[addr]
end
local function find(self: View, names: { any }): Field?
local by = self.struct.byName
for _, name in names do
local fld = by[name]
if fld then
return fld
end
end
return nil
end
function View.has(self: View, ...: string): boolean
return find(self, { ... }) ~= nil
end
local function scalar(f: File, t: string, size: number, o: number): number
local b = f.buf
if t == "float" then
return f.f32(b, o)
elseif t == "double" then
return f.f64(b, o)
elseif t == "int" or t == "int32_t" or t == "long" then
return if size == 8 then f.u32(b, o + (if f.little then 0 else 4)) else f.i32(b, o)
elseif t == "short" or t == "int16_t" then
return f.i16(b, o)
elseif t == "ushort" or t == "uint16_t" then
return f.u16(b, o)
elseif t == "uint" or t == "uint32_t" or t == "ulong" then
return f.u32(b, o)
elseif t == "int8_t" then
return readi8(b, o)
elseif t == "int64_t" or t == "uint64_t" then
local lo, hi = f.u32(b, o + (if f.little then 0 else 4)), f.u32(b, o + (if f.little then 4 else 0))
if t == "int64_t" and hi >= 2147483648 then
return (hi - 4294967296) * 4294967296 + lo
end
return hi * 4294967296 + lo
end
return readu8(b, o) -- char, uchar, uint8_t, bool
end
function View.get(self: View, ...: string): any
local fld = find(self, { ... })
if not fld then
return nil
end
local f = self.file
local o = self.offset + fld.offset
if o + fld.size > buffer.len(f.buf) then
return nil
end
if fld.pointer then
if fld.count > 1 then
local out = table.create(fld.count)
for k = 0, fld.count - 1 do
out[k + 1] = pointerKey(f, o + k * f.pointerSize) or false
end
return out
end
return pointerKey(f, o)
end
local t = fld.type
if PRIM[t] then
if fld.count == 1 then
return scalar(f, t, fld.elem, o)
end
if t == "char" then
local s = readstring(f.buf, o, fld.size)
local z = string.find(s, "\0", 1, true)
return if z then string.sub(s, 1, z - 1) else s
end
local out = table.create(fld.count)
for k = 0, fld.count - 1 do
out[k + 1] = scalar(f, t, fld.elem, o + k * fld.elem)
end
return out
end
local s = f.dna.byName[t]
if not s then
return nil
end
if fld.count > 1 then
local out = table.create(fld.count)
for k = 0, fld.count - 1 do
out[k + 1] = view(f, s, o + k * s.size, self.block)
end
return out
end
return view(f, s, o, self.block)
end
function View.num(self: View, ...: string): number?
local v = self:get(...)
return if type(v) == "number" then v else nil
end
function View.str(self: View, ...: string): string?
local v = self:get(...)
return if type(v) == "string" then v else nil
end
function View.vec(self: View, ...: string): { number }?
local v = self:get(...)
return if type(v) == "table" and type(v[1]) == "number" then v else nil
end
function View.sub(self: View, ...: string): View?
local v = self:get(...)
return if type(v) == "table" and getmetatable(v) == View then v else nil
end
function View.ptr(self: View, ...: string): any
local fld = find(self, { ... })
if not fld or not fld.pointer or self.offset + fld.offset + self.file.pointerSize > buffer.len(self.file.buf) then
return nil
end
return pointerKey(self.file, self.offset + fld.offset)
end
function View.target(self: View, ...: string): Block?
return Blend.resolve(self.file, self:ptr(...), self.block)
end
function View.deref(self: View, name: string | { string }, i: number?, as: string?): View?
local names: { any } = if type(name) == "table" then name else { name }
local fld = find(self, names)
if not fld or not fld.pointer then
return nil
end
local blk = self:target(fld.name)
if not blk then
return nil
end
local f = self.file
local sname = as or fld.type
if not as and (sname == "void" or not f.dna.byName[sname]) then
local own = f.dna.structs[blk.sdna + 1]
sname = if own then own.name else sname
end
return Blend.struct(f, blk, i, sname)
end
function View.array(self: View, name: string | { string }, as: string?): { View }
local first = self:deref(name, 0, as)
if not first or not first.block then
return {}
end
local blk = first.block :: Block
local s = first.struct
local n = if s.size > 0 then blk.size // s.size else 0
local out = table.create(n) :: { View }
for k = 0, n - 1 do
out[k + 1] = view(self.file, s, blk.offset + k * s.size, blk)
end
return out
end
function View.pointers(self: View, name: string | { string }, n: number?): { any }
local names: { any } = if type(name) == "table" then name else { name }
local fld = find(self, names)
if not fld or not fld.pointer then
return {}
end
local blk = self:target(fld.name)
if not blk then
return {}
end
local f = self.file
local ps = f.pointerSize
local count = blk.size // ps
if n then
count = math.min(count, n)
end
local out = table.create(count)
for k = 0, count - 1 do
out[k + 1] = pointerKey(f, blk.offset + k * ps) or false
end
return out
end
function View.list(self: View, name: string | { string }, as: string?, limit: number?): { View }
local names: { any } = if type(name) == "table" then name else { name }
local lb = self:sub(table.unpack(names))
local out = {}
if not lb then
return out
end
local f = self.file
local addr = lb:ptr("first")
local seen = {}
local max = limit or 2 ^ 20
while addr ~= nil and not seen[addr] and #out < max do
seen[addr] = true
local blk = Blend.resolve(f, addr, self.block)
if not blk then
break
end
local v = Blend.struct(f, blk, 0, as)
if not v then
break
end
table.insert(out, v)
addr = v:ptr("next")
if addr == nil and not v.struct.byName.next then
-- structs that start with an embedded header (ModifierData, ...) keep the link there
local head = v.struct.fields[1]
local sub = head and not head.pointer and f.dna.byName[head.type]
if sub then
addr = view(f, sub, v.offset + head.offset, v.block):ptr("next")
end
end
end
return out
end
function View.data(self: View, ...: string): (number?, number)
local blk = self:target(...)
if not blk then
return nil, 0
end
return blk.offset, blk.size
end
function View.cstring(self: View, ...: string): string?
local blk = self:target(...)
if not blk then
return nil
end
local s = readstring(self.file.buf, blk.offset, blk.size)
local z = string.find(s, "\0", 1, true)
return if z then string.sub(s, 1, z - 1) else s
end
function View.idName(self: View): string?
local id = self:sub("id")
local n = if id then id:str("name") else self:str("name")
if not n then
return nil
end
return string.sub(n, 3)
end
return Blend