From 2e82b7d0af96fadcd27622ceb248616e676628ff Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 18:53:41 -0600 Subject: [PATCH 1/4] model/blend, containers/Blend: read .blend files (2.4x-5.x headers, SDNA structs by name, gzip/zstd), scenes with meshes of every storage generation, materials, images, cameras, lights, armatures, skins, shape keys, actions --- README.md | 5 +- docs/FORMATS.md | 1 + src/Rosetta/Registry.luau | 12 + src/Rosetta/containers/Blend.luau | 741 ++++++++++++++++++++++ src/Rosetta/model/blend/Anim.luau | 290 +++++++++ src/Rosetta/model/blend/Material.luau | 348 +++++++++++ src/Rosetta/model/blend/Mesh.luau | 604 ++++++++++++++++++ src/Rosetta/model/blend/Normals.luau | 161 +++++ src/Rosetta/model/blend/Prim.luau | 452 ++++++++++++++ src/Rosetta/model/blend/Read.luau | 862 ++++++++++++++++++++++++++ src/Rosetta/model/blend/init.luau | 75 +++ tests/model/blend.luau | 605 ++++++++++++++++++ tools/fixtures/_blend_make.py | 390 ++++++++++++ tools/fixtures/_blend_ref.py | 219 +++++++ tools/fixtures/blend.py | 92 +++ 15 files changed, 4855 insertions(+), 2 deletions(-) create mode 100644 src/Rosetta/containers/Blend.luau create mode 100644 src/Rosetta/model/blend/Anim.luau create mode 100644 src/Rosetta/model/blend/Material.luau create mode 100644 src/Rosetta/model/blend/Mesh.luau create mode 100644 src/Rosetta/model/blend/Normals.luau create mode 100644 src/Rosetta/model/blend/Prim.luau create mode 100644 src/Rosetta/model/blend/Read.luau create mode 100644 src/Rosetta/model/blend/init.luau create mode 100644 tests/model/blend.luau create mode 100644 tools/fixtures/_blend_make.py create mode 100644 tools/fixtures/_blend_ref.py create mode 100644 tools/fixtures/blend.py diff --git a/README.md b/README.md index 7af4b19..c81dfe9 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ print(F.detect(webp), #F.formats()) -- "webp", the format list ## Formats -174 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) +175 formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md) adds each format's capabilities. | Category | Format | Extensions | Read | Write | @@ -109,6 +109,7 @@ adds each format's capabilities. | 3D models | 3ds | .3ds | yes | yes | | 3D models | 3mf | .3mf | yes | yes | | 3D models | b3d | .b3d | yes | - | +| 3D models | blend | .blend | yes | - | | 3D models | bsp | .bsp | yes | - | | 3D models | dae | .dae .zae | yes | yes | | 3D models | fbx | .fbx | yes | yes | @@ -241,7 +242,7 @@ Shared by the formats, not loadable on their own (`src/Rosetta/codecs//` | model | Draco, Mat4, MeshFlatten, Minecraft, Polygon, Rbx, Rig, Sampler, Vrml | | text | Json, Nbt, Text, Url, Xml | | video | Dsp, H263, H264, Legacy, Mpeg1, Mpeg2, Theora, Video | -| containers | Archive, AudioWrap, Avi, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip | +| containers | Archive, AudioWrap, Avi, Blend, Chunks, Cpio, Demux, Ebml, Fat, Iso9660, IsoBmff, MacFile, MpegEs, MpegPs, MpegTs, Ogg, Riff, Tar, Zip | ## Licence diff --git a/docs/FORMATS.md b/docs/FORMATS.md index f2a9a60..f1ff0e7 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -65,6 +65,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | model | 3ds | .3ds | yes | yes | materials: true, textures: true, animation: true, cameras: true, lights: true, instancing: true | `tests/model/3ds.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | b3d | .b3d | yes | - | materials: true, textures: true, skins: true, animation: true, colors: true | `tests/model/b3d.luau` | +| model | blend | .blend | yes | - | materials: true, textures: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true, compressed: true | `tests/model/blend.luau` | | model | bsp | .bsp | yes | - | variants: "quake", "halflife", "quake2", "quake3", lightmaps: "quake3" | `tests/model/bsp.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | | model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` | diff --git a/src/Rosetta/Registry.luau b/src/Rosetta/Registry.luau index 062b60a..162c258 100644 --- a/src/Rosetta/Registry.luau +++ b/src/Rosetta/Registry.luau @@ -734,6 +734,18 @@ local list: { Entry } = { return require("@rosetta/model/b3d") end, }, + { + name = "blend", + category = "model", + path = "model/blend", + extensions = { "blend" }, + mime = { "application/x-blender" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, + load = function() + return require("@rosetta/model/blend") + end, + }, { name = "bsp", category = "model", diff --git a/src/Rosetta/containers/Blend.luau b/src/Rosetta/containers/Blend.luau new file mode 100644 index 0000000..0fd6867 --- /dev/null +++ b/src/Rosetta/containers/Blend.luau @@ -0,0 +1,741 @@ +--!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?) + -- -> header size, pointer size, little, version, format | nil, error + 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) + 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) + 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), {} + 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 s: Struct = { name = types[t + 1], index = k - 1, size = lengths[t + 1], fields = table.create(nf), 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 = names[fn + 1] + local pointer = string.sub(decl, 1, 1) == "*" or string.sub(decl, 1, 2) == "(*" + local dims, 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 = if pointer then ps else lengths[ft + 1] + local fld: Field = { + name = base, decl = decl, type = types[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, types = types, 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 + return nil, Err.new(if n < 12 then Err.TRUNCATED else Err.CORRUPT, 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 + code = string.gsub(code, "%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 + if glob and fg and fg.byName.subversion then + local fld = fg.byName.subversion + if fld.offset + 2 <= glob[1].size then + f.subversion = f.i16(b, glob[1].offset + fld.offset) + end + end + return f, nil +end + +-- ------------------------------------------------------------------------------------------------ structs +export type View = { + file: File, + struct: Struct, + offset: number, -- the struct's first byte in file.buf + block: Block?, +} + +local View = {} +View.__index = View +Blend.View = View + +local function view(f: File, s: Struct, offset: number, blk: Block?): View + return setmetatable({ file = f, struct = s, offset = offset, block = blk }, View) :: any +end + +function Blend.structOf(f: File, blk: Block): Struct? + return f.dna.structs[blk.sdna + 1] +end + +-- element i (0-based) of a block, as its own SDNA struct or as `as` (a struct name) +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 + +-- a number (scalars), a string (char arrays), an array of numbers (other arrays), a View (embedded structs), the +-- pointer key (pointers); nil when no field has any of the names +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 + +-- the struct a pointer field points at (element i, 0-based), typed by the field's type or `as` +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 + +-- all elements of a pointer-to-array field: the block's count (or byte size / struct size when that is larger) +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) + for k = 0, n - 1 do + out[k + 1] = view(self.file, s, blk.offset + k * s.size, blk) + end + return out +end + +-- a pointer to an array of pointers (Material **mat, ActionLayer **layer_array, ...): n keys (default: the block size) +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 + +-- a ListBase field (first / last) walked through each element's `next`, typed as `as` or the first block's struct +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 + +-- the bytes a pointer field points at: (block offset, block size) in file.buf +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 + +-- a NUL-terminated string behind a char pointer +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 + +-- an ID's name without its two-letter code ("OBCube" -> "Cube") +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 diff --git a/src/Rosetta/model/blend/Anim.luau b/src/Rosetta/model/blend/Anim.luau new file mode 100644 index 0000000..e7e1f8b --- /dev/null +++ b/src/Rosetta/model/blend/Anim.luau @@ -0,0 +1,290 @@ +--!strict +-- model/blend/Anim: Blender actions (legacy bAction.curves, and the layered actions of 4.4+: layers -> strips -> +-- keyframe data -> channel bags matched by the AnimData slot handle) and f-curve evaluation: constant, linear, +-- bezier (handles shortened so the segment stays a function of time, as Blender does) and the Penner easing modes; +-- constant or linear extrapolation. F-curve modifiers and NLA strips are not evaluated. +local Blend = require("@rosetta/containers/Blend") + +local Anim = {} + +export type Key = { + x: number, + y: number, + lx: number, -- left handle + ly: number, + rx: number, -- right handle + ry: number, + ipo: number, -- 0 constant, 1 linear, 2 bezier, 3.. easing (back, bounce, circ, cubic, elastic, expo, quad, quart, quint, sine) + easing: number, -- 0 auto, 1 in, 2 out, 3 in-out + back: number, + amplitude: number, + period: number, +} +export type Curve = { path: string, index: number, keys: { Key }, extend: number, modifiers: number } + +local CONST, LIN, BEZ = 0, 1, 2 +local BACK, BOUNCE, CIRC, CUBIC, ELASTIC, EXPO, QUAD, QUART, QUINT, SINE = 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 + +-- ------------------------------------------------------------------------------------------------ reading +local function curve(f: Blend.File, fc: Blend.View): Curve? + local path = fc:cstring("rna_path") + if not path then + return nil + end + local keys: { Key } = {} + for _, b in fc:array("bezt", "BezTriple") do + local v = b:vec("vec") + if v and #v >= 9 then + table.insert(keys, { + lx = v[1], ly = v[2], x = v[4], y = v[5], rx = v[7], ry = v[8], + ipo = b:num("ipo") or BEZ, easing = b:num("easing") or 0, back = b:num("back") or 1.70158, + amplitude = b:num("amplitude") or 0.8, period = b:num("period") or 4.1, + }) + end + end + if #keys == 0 then + for _, p in fc:array("fpt", "FPoint") do + local v = p:vec("vec") + if v and #v >= 2 then + table.insert(keys, { x = v[1], y = v[2], lx = v[1], ly = v[2], rx = v[1], ry = v[2], ipo = LIN, easing = 0, back = 0, amplitude = 0, period = 0 }) + end + end + end + if #keys == 0 then + return nil + end + table.sort(keys, function(a: Key, b: Key): boolean + return a.x < b.x + end) + local mods = fc:list("modifiers") + return { path = path, index = fc:num("array_index") or 0, keys = keys, extend = fc:num("extend") or 0, modifiers = #mods } +end + +-- the f-curves an AnimData plays from its action (nil when it has none) +function Anim.curves(f: Blend.File, adt: Blend.View?): ({ Curve }?, string?) + if not adt then + return nil, nil + end + local act = adt:deref("action", 0, "bAction") + if not act then + return nil, nil + end + local list: { Blend.View } = act:list("curves", "FCurve") + if #list == 0 and act:has("layer_array") then + local handle = adt:num("slot_handle") or 0 + local datas = act:pointers("strip_keyframe_data_array", act:num("strip_keyframe_data_array_num")) + for _, la in act:pointers("layer_array", act:num("layer_array_num")) do + local lblk = la and Blend.resolve(f, la, act.block) + local layer = lblk and Blend.struct(f, lblk, 0, "ActionLayer") + if layer then + for _, sa in layer:pointers("strip_array", layer:num("strip_array_num")) do + local sblk = sa and Blend.resolve(f, sa, act.block) + local strip = sblk and Blend.struct(f, sblk, 0, "ActionStrip") + local di = strip and strip:num("data_index") + local dblk = di and datas[di + 1] and Blend.resolve(f, datas[di + 1], act.block) + local kd = dblk and Blend.struct(f, dblk, 0, "ActionStripKeyframeData") + if kd then + for _, ba in kd:pointers("channelbag_array", kd:num("channelbag_array_num")) do + local bblk = ba and Blend.resolve(f, ba, act.block) + local bag = bblk and (Blend.struct(f, bblk, 0, "ActionChannelBag") or Blend.struct(f, bblk, 0, "ActionChannelbag")) + if bag and (bag:num("slot_handle") or 0) == handle then + for _, ca in bag:pointers("fcurve_array", bag:num("fcurve_array_num")) do + local cblk = ca and Blend.resolve(f, ca, act.block) + local fc = cblk and Blend.struct(f, cblk, 0, "FCurve") + if fc then + table.insert(list, fc) + end + end + end + end + end + end + end + end + end + local out: { Curve } = {} + for _, fc in list do + local c = curve(f, fc) + if c then + table.insert(out, c) + end + end + return out, act:idName() +end + +-- ------------------------------------------------------------------------------------------------ evaluation +local function bezierAt(p0: number, p1: number, p2: number, p3: number, t: number): number + local u = 1 - t + return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3 +end + +local function bezier(a: Key, b: Key, x: number): number + local x0, y0, x3, y3 = a.x, a.y, b.x, b.y + local x1, y1, x2, y2 = a.rx, a.ry, b.lx, b.ly + -- handles longer than the segment are scaled down together so x(t) stays monotonic + local len = x3 - x0 + local h1x, h1y = x1 - x0, y1 - y0 + local h2x, h2y = x2 - x3, y2 - y3 + local l1, l2 = math.abs(h1x), math.abs(h2x) + if l1 + l2 > len and l1 + l2 > 0 then + local fac = len / (l1 + l2) + x1, y1 = x0 + h1x * fac, y0 + h1y * fac + x2, y2 = x3 + h2x * fac, y3 + h2y * fac + end + local lo, hi = 0, 1 + local t = (x - x0) / len + for _ = 1, 60 do + local xt = bezierAt(x0, x1, x2, x3, t) + if math.abs(xt - x) < 1e-9 then + break + end + if xt < x then + lo = t + else + hi = t + end + local d = 3 * (1 - t) * (1 - t) * (x1 - x0) + 6 * (1 - t) * t * (x2 - x1) + 3 * t * t * (x3 - x2) + local nt = if d ~= 0 then t - (xt - x) / d else -1 + t = if nt > lo and nt < hi then nt else (lo + hi) / 2 + end + return bezierAt(y0, y1, y2, y3, t) +end + +-- Penner easing: t in 0..d, from b by c +local function bounceOut(t: number, b: number, c: number, d: number): number + t /= d + if t < 1 / 2.75 then + return c * (7.5625 * t * t) + b + elseif t < 2 / 2.75 then + t -= 1.5 / 2.75 + return c * (7.5625 * t * t + 0.75) + b + elseif t < 2.5 / 2.75 then + t -= 2.25 / 2.75 + return c * (7.5625 * t * t + 0.9375) + b + end + t -= 2.625 / 2.75 + return c * (7.5625 * t * t + 0.984375) + b +end + +local function easeIn(ipo: number, t: number, a: Key): number -- 0..1 -> 0..1 + if ipo == BACK then + local s = a.back + return t * t * ((s + 1) * t - s) + elseif ipo == BOUNCE then + return 1 - bounceOut(1 - t, 0, 1, 1) + elseif ipo == CIRC then + return 1 - math.sqrt(math.max(0, 1 - t * t)) + elseif ipo == CUBIC then + return t * t * t + elseif ipo == ELASTIC then + if t <= 0 or t >= 1 then + return t + end + local p = if a.period > 0 then a.period / 10 else 0.3 + local amp = a.amplitude + local s + if amp < 1 then + amp, s = 1, p / 4 + else + s = p / (2 * math.pi) * math.asin(1 / amp) + end + t -= 1 + return -(amp * 2 ^ (10 * t) * math.sin((t - s) * (2 * math.pi) / p)) + elseif ipo == EXPO then + return if t <= 0 then 0 else 2 ^ (10 * (t - 1)) + elseif ipo == QUAD then + return t * t + elseif ipo == QUART then + return t * t * t * t + elseif ipo == QUINT then + return t * t * t * t * t + elseif ipo == SINE then + return 1 - math.cos(t * math.pi / 2) + end + return t +end + +local function ease(a: Key, b: Key, x: number): number + local t = (x - a.x) / (b.x - a.x) + local mode = a.easing + if mode == 0 then + mode = if a.ipo == BACK or a.ipo == BOUNCE or a.ipo == ELASTIC then 2 else 1 + end + local s + if mode == 1 then + s = easeIn(a.ipo, t, a) + elseif mode == 2 then + s = 1 - easeIn(a.ipo, 1 - t, a) + elseif t < 0.5 then + s = easeIn(a.ipo, t * 2, a) / 2 + else + s = 1 - easeIn(a.ipo, (1 - t) * 2, a) / 2 + end + return a.y + (b.y - a.y) * s +end + +function Anim.evaluate(c: Curve, x: number): number + local keys = c.keys + local n = #keys + local first, last = keys[1], keys[n] + if x <= first.x then + if c.extend == 1 and n > 0 and first.ipo ~= CONST then + if first.ipo == BEZ and first.lx ~= first.x then + return first.y + (x - first.x) * (first.y - first.ly) / (first.x - first.lx) + elseif n > 1 and keys[2].x ~= first.x then + return first.y + (x - first.x) * (keys[2].y - first.y) / (keys[2].x - first.x) + end + end + return first.y + end + if x >= last.x then + local prev = keys[n - 1] + if c.extend == 1 and n > 1 and prev.ipo ~= CONST then + if last.ipo == BEZ and last.rx ~= last.x then + return last.y + (x - last.x) * (last.ry - last.y) / (last.rx - last.x) + elseif last.x ~= prev.x then + return last.y + (x - last.x) * (last.y - prev.y) / (last.x - prev.x) + end + end + return last.y + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if keys[mid].x <= x then + lo = mid + else + hi = mid + end + end + local a, b = keys[lo], keys[hi] + if b.x <= a.x or a.ipo == CONST then + return a.y + elseif a.ipo == LIN then + return a.y + (b.y - a.y) * (x - a.x) / (b.x - a.x) + elseif a.ipo == BEZ then + return bezier(a, b, x) + end + return ease(a, b, x) +end + +function Anim.range(curves: { Curve }): (number, number) + local lo, hi = math.huge, -math.huge + for _, c in curves do + lo = math.min(lo, c.keys[1].x) + hi = math.max(hi, c.keys[#c.keys].x) + end + return lo, hi +end + +-- "pose.bones[\"name\"].location" -> "name", "location" +function Anim.split(path: string): (string?, string?, string) + local kind, name, rest = string.match(path, '^(%w[%w_%.]-)%["(.-)"%]%.([%w_]+)$') + if kind and name and rest then + name = string.gsub(name, '\\(.)', "%1") + return kind, name, rest + end + return nil, nil, path +end + +return Anim diff --git a/src/Rosetta/model/blend/Material.luau b/src/Rosetta/model/blend/Material.luau new file mode 100644 index 0000000..58cce4b --- /dev/null +++ b/src/Rosetta/model/blend/Material.luau @@ -0,0 +1,348 @@ +--!strict +-- model/blend/Material: Blender materials to Scene PBR materials. With nodes: the Principled BSDF (the one feeding the +-- material output, else the first): Base Color, Metallic, Roughness, Alpha, Emission (Color) x Emission Strength +-- (KHR_materials_emissive_strength above 1, as Blender's glTF exporter writes it), images linked directly to Base +-- Color / Emission and through a Normal Map node to Normal (its Strength as the scale), a Separate RGB / Color node to +-- Roughness (G) and Metallic (B), UV Map nodes for the texCoord. Without nodes (or before 2.8 without a +-- Principled node): Material.r / g / b / alpha, metallic, roughness. Images: packed files as encoded bytes, external +-- ones as uris (with the bytes when opts.files / opts.resolve has them). +local Blend = require("@rosetta/containers/Blend") +local Types = require("@rosetta/Types") + +local Material = {} + +type Ctx = { f: Blend.File, scene: Types.Scene, materials: { [any]: number }, textures: { [any]: number }, opts: any, meta: any } + +local readu8, readstring = buffer.readu8, buffer.readstring + +local function sniffMime(b: buffer, o: number, n: number, path: string?): string? + if n >= 8 and readstring(b, o, 8) == "\137PNG\r\n\26\n" then + return "image/png" + elseif n >= 3 and readu8(b, o) == 0xFF and readu8(b, o + 1) == 0xD8 then + return "image/jpeg" + elseif n >= 12 and readstring(b, o, 4) == "RIFF" and readstring(b, o + 8, 4) == "WEBP" then + return "image/webp" + elseif n >= 2 and readstring(b, o, 2) == "BM" then + return "image/bmp" + elseif n >= 4 and readstring(b, o, 4) == "\118\47\49\1" then + return "image/x-exr" + end + local ext = path and string.lower(string.match(path, "%.(%w+)$") or "") + local byExt = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", exr = "image/x-exr", hdr = "image/vnd.radiance", webp = "image/webp", tif = "image/tiff", tiff = "image/tiff" } + return if ext then byExt[ext] else nil +end + +local function fetch(ctx: Ctx, uri: string): buffer? + local opts = ctx.opts + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + if v == nil then + v = opts.files[string.match(uri, "[^/\\]+$") or uri] + end + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil +end + +local function texture(ctx: Ctx, img: Blend.View, sampler: Types.Sampler?): number? + local f = ctx.f + local key = img.block and img.block.addr + if key ~= nil and ctx.textures[key] then + return ctx.textures[key] + end + local name = img:idName() + -- the path field keeps its DNA name "name" (char[1024]) in every version + local pf0 = img.struct.byName.filepath or img.struct.byName.name + local path = if pf0 and pf0.size >= 256 then img:str(pf0.name) else nil + local pf = img:deref("packedfile", 0, "PackedFile") + if not pf then + for _, ipf in img:list("packedfiles", "ImagePackedFile") do + pf = ipf:deref("packedfile", 0, "PackedFile") + if pf then + break + end + end + end + local tex: Types.Texture = { name = name, sampler = sampler } + if pf then + local blk = pf:target("data") + local size = pf:num("size") or 0 + if blk then + local n = math.min(size, blk.size) + local data = buffer.create(n) + buffer.copy(data, 0, f.buf, blk.offset, n) + tex.data = data + tex.mime = sniffMime(data, 0, n, path) + end + end + if path and path ~= "" then + local uri = string.gsub(path, "^//", "") + uri = string.gsub(uri, "\\", "/") + if not tex.data then + tex.uri = uri + local data = fetch(ctx, uri) + if data then + tex.data = data + tex.mime = sniffMime(data, 0, buffer.len(data), uri) + else + tex.mime = sniffMime(buffer.create(0), 0, 0, uri) + end + end + tex.extras = { blend = { filepath = path } } + end + if not tex.data and not tex.uri then + tex.extras = { blend = { generated = true } } + end + table.insert(ctx.scene.textures, tex) + local idx = #ctx.scene.textures + if key ~= nil then + ctx.textures[key] = idx + end + return idx +end + +type Node = { view: Blend.View, idname: string, inputs: { [string]: Blend.View }, outputs: { [any]: string } } +type Graph = { nodes: { [any]: Node }, links: { [any]: { node: Node, socket: string } } } -- links by tosock addr + +local function graph(tree: Blend.View): Graph + local g: Graph = { nodes = {}, links = {} } + for _, n in tree:list("nodes", "bNode") do + local node: Node = { view = n, idname = n:str("idname") or "", inputs = {}, outputs = {} } + for _, s in n:list("inputs", "bNodeSocket") do + local id = s:str("identifier") or s:str("name") or "" + local nm = s:str("name") or id + node.inputs[nm] = s + if node.inputs[id] == nil then + node.inputs[id] = s + end + end + for _, s in n:list("outputs", "bNodeSocket") do + if s.block then + node.outputs[s.block.addr] = s:str("name") or "" + end + end + if n.block then + g.nodes[n.block.addr] = node + end + end + for _, l in tree:list("links", "bNodeLink") do + local from, fs, to = l:ptr("fromnode"), l:ptr("fromsock"), l:ptr("tosock") + local fn = from and g.nodes[from] + if fn and to ~= nil and bit32.band(l:num("flag") or 0, 0x10) == 0 then + g.links[to] = { node = fn, socket = (fs and fn.outputs[fs]) or "" } + end + end + return g +end + +local function input(n: Node, ...: string): Blend.View? + for _, k in { ... } do + local s = n.inputs[k] + if s then + return s + end + end + return nil +end + +local function link(g: Graph, s: Blend.View?): { node: Node, socket: string }? + if not s or not s.block then + return nil + end + return g.links[s.block.addr] +end + +local function value(s: Blend.View?, kind: string): any + if not s then + return nil + end + if kind == "rgba" then + local v = s:deref("default_value", 0, "bNodeSocketValueRGBA") + return v and v:vec("value") + end + local v = s:deref("default_value", 0, "bNodeSocketValueFloat") + return v and v:num("value") +end + +local function imageRef(ctx: Ctx, g: Graph, uvNames: any, s: Blend.View?, through: string?): (Types.TextureRef?, Node?) + local l = link(g, s) + if not l then + return nil, nil + end + local n = l.node + if through and n.idname == through then + local inner = input(n, "Color", "Image") + local ref, tn = imageRef(ctx, g, uvNames, inner, nil) + return ref, if ref then n else tn + end + if n.idname ~= "ShaderNodeTexImage" then + return nil, n + end + local img = n.view:deref("id", 0, "Image") + if not img then + return nil, n + end + local sampler: Types.Sampler = {} + local st = n.view:deref("storage", 0, "NodeTexImage") + if st then + local interp, ext = st:num("interpolation") or 0, st:num("extension") or 0 + if interp == 1 then + sampler.filter = "nearest" + sampler.minFilter = "nearest" + end + if ext == 1 or ext == 2 then + sampler.wrapS, sampler.wrapT = "clamp", "clamp" + elseif ext == 3 then + sampler.wrapS, sampler.wrapT = "mirror", "mirror" + end + end + local t = texture(ctx, img, if next(sampler) then sampler else nil) + if not t then + return nil, n + end + local ref: Types.TextureRef = { texture = t } + local vec = link(g, input(n, "Vector")) + if vec and vec.node.idname == "ShaderNodeUVMap" then + local uvs = vec.node.view:deref("storage", 0, "NodeShaderUVMap") + local name = uvs and uvs:str("uv_map") + if name and uvNames and uvNames[name] then + ref.texCoord = uvNames[name] + end + end + return ref, n +end + +local function principled(g: Graph): Node? + local first: Node? = nil + for _, n in g.nodes do + if n.idname == "ShaderNodeOutputMaterial" then + local l = link(g, n.inputs.Surface) + if l and l.node.idname == "ShaderNodeBsdfPrincipled" then + return l.node + end + elseif n.idname == "ShaderNodeBsdfPrincipled" and (first == nil or (n.view.block and first.view.block and n.view.block.index < first.view.block.index)) then + first = n + end + end + return first +end + +local function emissive(m: Types.Material, color: { number }, strength: number) + local e = { color[1] * strength, color[2] * strength, color[3] * strength } + local mx = math.max(e[1], e[2], e[3]) + if mx > 1 then + m.extensions = m.extensions or {} + ;(m.extensions :: any).KHR_materials_emissive_strength = { emissiveStrength = mx } + e = { e[1] / mx, e[2] / mx, e[3] / mx } + end + m.emissive = e +end + +function Material.get(ctx: Ctx, mv: Blend.View): number + local key = mv.block and mv.block.addr + if key ~= nil and ctx.materials[key] then + return ctx.materials[key] + end + local f = ctx.f + local m = Types.Scene.material(mv:idName()) + local extras: { [string]: any } = {} + m.extras = { blend = extras } + local legacyAlpha = mv:num("a", "alpha") or 1 + m.baseColor = { mv:num("r") or 0.8, mv:num("g") or 0.8, mv:num("b") or 0.8, legacyAlpha } + m.metallic = mv:num("metallic") or 0 + m.roughness = mv:num("roughness") or 0.5 + if f.version < 280 then + m.roughness = 0.5 + end + m.doubleSided = bit32.band(mv:num("blend_flag") or 0, 4) == 0 + local tree = mv:deref("nodetree", 0, "bNodeTree") + local useNodes = (mv:num("use_nodes") or 0) ~= 0 or f.version >= 500 + local bsdf = nil + local g: Graph? = nil + if tree and useNodes then + g = graph(tree) + bsdf = principled(g :: Graph) + end + if bsdf and g then + extras.principled = true + local uvNames = ctx.meta.uvNames + local base = value(input(bsdf, "Base Color"), "rgba") + local alpha = value(input(bsdf, "Alpha"), "float") or 1 + if base then + m.baseColor = { base[1], base[2], base[3], alpha } + end + m.metallic = value(input(bsdf, "Metallic"), "float") or m.metallic + m.roughness = value(input(bsdf, "Roughness"), "float") or m.roughness + local bref = imageRef(ctx, g, uvNames, input(bsdf, "Base Color"), nil) + if bref then + m.baseColorTexture = bref + m.baseColor = { 1, 1, 1, alpha } + end + local aref = imageRef(ctx, g, uvNames, input(bsdf, "Alpha"), nil) + if aref and not m.baseColorTexture then + m.baseColorTexture = aref + end + local nref, nnode = imageRef(ctx, g, uvNames, input(bsdf, "Normal"), "ShaderNodeNormalMap") + if nref then + nref.scale = if nnode then value(nnode.inputs.Strength, "float") or 1 else 1 + m.normalTexture = nref + end + local rl = link(g, input(bsdf, "Roughness")) + local ml = link(g, input(bsdf, "Metallic")) + local sep = (rl and rl.node) or (ml and ml.node) + if sep and (sep.idname == "ShaderNodeSeparateRGB" or sep.idname == "ShaderNodeSeparateColor") then + local mref = imageRef(ctx, g, uvNames, input(sep, "Image", "Color"), nil) + if mref then + m.metallicRoughnessTexture = mref + if rl then + m.roughness = 1 + end + if ml then + m.metallic = 1 + end + end + end + local es = input(bsdf, "Emission Color", "Emission") + local ecol = value(es, "rgba") or { 0, 0, 0, 1 } + local strength = value(input(bsdf, "Emission Strength"), "float") or 1 + local eref = imageRef(ctx, g, uvNames, es, nil) + if eref then + m.emissiveTexture = eref + ecol = { 1, 1, 1, 1 } + end + emissive(m, ecol, strength) + if not eref and m.emissive[1] == 0 and m.emissive[2] == 0 and m.emissive[3] == 0 then + m.emissive = { 0, 0, 0 } + end + local alphaLinked = link(g, input(bsdf, "Alpha")) ~= nil + if alpha < 1 or alphaLinked then + local bm = mv:num("blend_method") or 0 + if bm == 3 then + m.alphaMode = "mask" + m.alphaCutoff = mv:num("alpha_threshold") or 0.5 + else + m.alphaMode = "blend" + end + end + else + extras.legacy = true + if legacyAlpha < 1 then + m.alphaMode = "blend" + end + end + table.insert(ctx.scene.materials, m) + local idx = #ctx.scene.materials + if key ~= nil then + ctx.materials[key] = idx + end + return idx +end + +return Material diff --git a/src/Rosetta/model/blend/Mesh.luau b/src/Rosetta/model/blend/Mesh.luau new file mode 100644 index 0000000..fe5f0a4 --- /dev/null +++ b/src/Rosetta/model/blend/Mesh.luau @@ -0,0 +1,604 @@ +--!strict +-- model/blend/Mesh: a Blender Mesh ID of any storage generation to one polygon form (positions, faces as corner lists, +-- corner / point attributes, deform weights). Generations: MFace tessellated faces (< 2.63, and the 2.7x "legacy mesh +-- format" save); MVert / MEdge / MPoly / MLoop with MLoopUV / MLoopCol layers (2.63 - 3.x); CustomData attribute +-- layers ("position", ".edge_verts", ".corner_vert", poly_offset_indices, 3.x - 4.x); AttributeStorage (5.x). +local Blend = require("@rosetta/containers/Blend") + +local Mesh = {} + +export type Layer = { + name: string, + domain: string, -- "point" | "edge" | "face" | "corner" | "tess" + kind: string, -- a generic kind (float, float2, float3, color, bytecolor, int32, int2, int8, bool, short2, quat, + -- float4x4) or an SDNA struct name (MVert, MEdge, MPoly, MLoop, MFace, MTFace, MCol, MLoopUV, MDeformVert) + offset: number, -- data start in file.buf + bytes: number, -- data bytes available + elem: number, -- bytes per element + single: boolean?, -- one value for every element (AttributeStorage single storage) + activeRender: boolean?, + cdtype: number?, +} + +export type Color = { name: string, domain: string, data: buffer } -- f32 x 4 (linear) per point or corner +export type Poly = { + name: string?, + nv: number, + nf: number, + nc: number, + pos: buffer, -- f32 x 3 per vertex + cornerVert: buffer, -- u32 per corner + faceStart: buffer, -- u32 per face + 1 + faceMat: buffer, -- i32 per face + faceSmooth: buffer, -- u8 per face + uvs: { { name: string, data: buffer } }, -- f32 x 2 per corner + activeUV: number, -- 1-based index into uvs (the active render layer) + colors: { Color }, + customNormals: buffer?, -- f32 x 3 per corner (free custom normals) + encodedNormals: buffer?, -- i16 x 2 per corner (custom normals in Blender's corner-fan space) + sharp: { [number]: boolean }, -- edge keys (min * nv + max) that split smooth fans + autoSmooth: number?, -- radians (Mesh.smoothresh with ME_AUTOSMOOTH, before 4.1) + weights: { { number } }?, -- per vertex: def_nr, weight, def_nr, weight, ... + generation: string, -- "mface" | "mpoly" | "attributes" | "storage" + layers: { Layer }, +} + +local CD_KIND: { [number]: string } = { + [0] = "MVert", [2] = "MDeformVert", [3] = "MEdge", [4] = "MFace", [5] = "MTFace", [6] = "MCol", [10] = "float", + [11] = "int32", [16] = "MLoopUV", [17] = "bytecolor", [25] = "MPoly", [26] = "MLoop", [41] = "short2", [45] = "int8", + [46] = "int2", [47] = "color", [48] = "float3", [49] = "float2", [50] = "bool", [52] = "quat", +} +-- AttributeStorage (5.x) data types and domains +local ATTR_KIND: { [number]: string } = { + [0] = "bool", [1] = "int8", [2] = "short2", [3] = "int32", [4] = "int2", [5] = "float", [6] = "float2", [7] = "float3", + [8] = "float4x4", [9] = "bytecolor", [10] = "color", [11] = "quat", +} +local DOMAIN: { [number]: string } = { [0] = "point", [1] = "edge", [2] = "face", [3] = "corner" } +local SIZE: { [string]: number } = { + bool = 1, int8 = 1, short2 = 4, int32 = 4, int2 = 8, float = 4, float2 = 8, float3 = 12, float4x4 = 64, bytecolor = 4, + color = 16, quat = 16, +} +local ME_SMOOTH = 1 +local ME_SHARP = 0x200 +local ME_AUTOSMOOTH = 0x20 + +local readu8, readi16 = buffer.readu8, buffer.readi16 + +-- sRGB byte -> linear +local SRGB = table.create(256, 0) +for i = 0, 255 do + local c = i / 255 + SRGB[i + 1] = if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4 +end +Mesh.SRGB = SRGB + +local function customData(f: Blend.File, me: Blend.View, names: { string }, domain: string, out: { Layer }) + local cd = me:sub(table.unpack(names)) + if not cd then + return + end + local layers = cd:array("layers", "CustomDataLayer") + local n = cd:num("totlayer") or #layers + for i = 1, math.min(n, #layers) do + local L = layers[i] + local t = L:num("type") or -1 + local kind = CD_KIND[t] + local blk = L:target("data") + if kind and blk then + local st = f.dna.byName[kind] + local elem = if st then st.size else SIZE[kind] or 0 + if elem > 0 then + table.insert(out, { + name = L:str("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, + elem = elem, activeRender = (L:num("active_rnd") or 0) == 0, cdtype = t, + }) + end + end + end +end + +local function storage(f: Blend.File, me: Blend.View, out: { Layer }) + local st = me:sub("attribute_storage") + if not st then + return + end + local attrs = st:array("dna_attributes", "Attribute") + local n = st:num("dna_attributes_num") or #attrs + for i = 1, math.min(n, #attrs) do + local a = attrs[i] + local kind = ATTR_KIND[a:num("data_type") or -1] + local domain = DOMAIN[a:num("domain") or -1] + local single = (a:num("storage_type") or 0) == 1 + local holder = a:deref("data", 0, if single then "AttributeSingle" else "AttributeArray") + local blk = holder and holder:target("data") + if kind and domain and blk then + table.insert(out, { + name = a:cstring("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, + elem = SIZE[kind], single = single, + }) + end + end +end + +local function find(layers: { Layer }, domain: string, kind: string?, name: string?): Layer? + for _, L in layers do + if L.domain == domain and (kind == nil or L.kind == kind) and (name == nil or L.name == name) then + return L + end + end + return nil +end + +-- a raw pointer field (Mesh.mvert, ...) as a layer when no CustomData layer has it +local function legacy(f: Blend.File, me: Blend.View, field: string, kind: string, domain: string): Layer? + local blk = me:target(field) + local st = f.dna.byName[kind] + if not blk or not st or st.size <= 0 then + return nil + end + return { name = "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, elem = st.size } +end + +-- reads element i (0-based) of a layer as number component c (0-based) of a generic kind +local function reader(f: Blend.File, L: Layer): (number, number) -> number + local b = f.buf + local o, elem, k = L.offset, L.elem, L.kind + local max = L.bytes + local single = L.single + local f32, i32, i16 = f.f32, f.i32, f.i16 + local comp = if k == "short2" then 2 elseif k == "int8" or k == "bool" or k == "bytecolor" then 1 else 4 + return function(i: number, c: number): number + local at = (if single then 0 else i * elem) + c * comp + if at < 0 or at + comp > max then + return 0 + end + if k == "float" or k == "float2" or k == "float3" or k == "color" or k == "quat" or k == "float4x4" then + return f32(b, o + at) + elseif k == "int32" or k == "int2" then + return i32(b, o + at) + elseif k == "short2" then + return i16(b, o + at) + elseif k == "int8" then + return buffer.readi8(b, o + at) + end + return readu8(b, o + at) + end +end +Mesh.reader = reader + +-- a field of an SDNA-struct layer: element i -> value (number) of component c +local function fieldReader(f: Blend.File, L: Layer, field: string): ((number, number) -> number)? + local st = f.dna.byName[L.kind] + local fld = st and st.byName[field] + if not fld then + return nil + end + local b, o, elem, max = f.buf, L.offset, L.elem, L.bytes + local t, esz = fld.type, fld.elem + local fo = fld.offset + local f32, i32, i16, u32, u16 = f.f32, f.i32, f.i16, f.u32, f.u16 + return function(i: number, c: number): number + local at = i * elem + fo + c * esz + if at < 0 or at + esz > max then + return 0 + end + at += o + if t == "float" then + return f32(b, at) + elseif t == "int" or t == "int32_t" then + return i32(b, at) + elseif t == "uint" or t == "uint32_t" then + return u32(b, at) + elseif t == "short" or t == "int16_t" then + return i16(b, at) + elseif t == "ushort" or t == "uint16_t" then + return u16(b, at) + end + return readu8(b, at) + end +end + +function Mesh.layers(f: Blend.File, me: Blend.View): { Layer } + local layers: { Layer } = {} + customData(f, me, { "vdata", "vert_data" }, "point", layers) + customData(f, me, { "edata", "edge_data" }, "edge", layers) + customData(f, me, { "pdata", "face_data" }, "face", layers) + customData(f, me, { "ldata", "corner_data" }, "corner", layers) + customData(f, me, { "fdata", "fdata_legacy" }, "tess", layers) + storage(f, me, layers) + return layers +end + +local function count(me: Blend.View, ...: string): number + local v = me:num(...) + return if v and v > 0 then v else 0 +end + +export type Limits = { maxVertices: number? } + +function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, string?) + local layers = Mesh.layers(f, me) + local nv = count(me, "totvert", "verts_num") + local np = count(me, "totpoly", "faces_num") + local nl = count(me, "totloop", "corners_num") + local nt = count(me, "totface", "totface_legacy") + local maxV = limits and limits.maxVertices or 2 ^ 25 + if nv > maxV or nl > maxV or nt > maxV or np > maxV then + return nil, "limit: mesh over maxVertices" + end + -- positions + local pos = buffer.create(nv * 12) + local P = find(layers, "point", "float3", "position") + local mv = find(layers, "point", "MVert") or legacy(f, me, "mvert", "MVert", "point") + local get: ((number, number) -> number)? = nil + if P then + get = reader(f, P) + elseif mv then + get = fieldReader(f, mv, "co") + end + if not get then + if nv > 0 then + return nil, "mesh without positions" + end + get = function(_: number, _: number): number + return 0 + end + end + local g = get :: (number, number) -> number + for i = 0, nv - 1 do + for c = 0, 2 do + buffer.writef32(pos, (i * 3 + c) * 4, g(i, c)) + end + end + local poly: Poly = { + name = me:idName(), nv = nv, nf = 0, nc = 0, pos = pos, cornerVert = buffer.create(0), faceStart = buffer.create(4), + faceMat = buffer.create(0), faceSmooth = buffer.create(0), uvs = {}, activeUV = 1, colors = {}, sharp = {}, + generation = if P and P.cdtype == nil then "storage" elseif P then "attributes" else "mpoly", + layers = layers, + } + local corner: { [string]: any } = {} + if np > 0 then + local offs = me:target("poly_offset_indices", "face_offset_indices") + local mp = find(layers, "face", "MPoly") or legacy(f, me, "mpoly", "MPoly", "face") + local cv = find(layers, "corner", "int32", ".corner_vert") + local ml = find(layers, "corner", "MLoop") or legacy(f, me, "mloop", "MLoop", "corner") + local starts = buffer.create((np + 1) * 4) + if offs and offs.size >= (np + 1) * 4 then + for i = 0, np do + buffer.writeu32(starts, i * 4, math.clamp(f.i32(f.buf, offs.offset + i * 4), 0, nl)) + end + elseif mp then + local ls, tl = fieldReader(f, mp, "loopstart"), fieldReader(f, mp, "totloop") + if not ls or not tl then + return nil, "bad MPoly" + end + -- MPoly faces are usually in loop order; faces that are not get copied corners below + local at = 0 + for i = 0, np - 1 do + buffer.writeu32(starts, i * 4, at) + at += math.max(0, tl(i, 0)) + end + buffer.writeu32(starts, np * 4, at) + if at > maxV * 4 then + return nil, "limit: too many corners" + end + local verts = buffer.create(at * 4) + local vr = if cv then reader(f, cv) else if ml then fieldReader(f, ml, "v") else nil + if not vr then + return nil, "mesh without corners" + end + local remap = buffer.create(at * 4) + local w = 0 + for i = 0, np - 1 do + local s0, n0 = ls(i, 0), tl(i, 0) + for k = 0, n0 - 1 do + local src = s0 + k + buffer.writeu32(verts, w * 4, math.clamp(vr(src, 0), 0, math.max(nv - 1, 0))) + buffer.writeu32(remap, w * 4, math.clamp(src, 0, math.max(nl - 1, 0))) + w += 1 + end + end + corner.remap = remap + corner.verts = verts + nl = at + else + return nil, "mesh without face offsets" + end + poly.faceStart = starts + poly.nf = np + if not corner.verts then + local verts = buffer.create(nl * 4) + local vr = if cv then reader(f, cv) else if ml then fieldReader(f, ml, "v") else nil + if not vr then + return nil, "mesh without corners" + end + for i = 0, nl - 1 do + buffer.writeu32(verts, i * 4, math.clamp(vr(i, 0), 0, math.max(nv - 1, 0))) + end + corner.verts = verts + end + poly.cornerVert = corner.verts + poly.nc = nl + -- material index and smooth flags + local mats = buffer.create(np * 4) + local smooth = buffer.create(np) + local mi = find(layers, "face", "int32", "material_index") + local sf = find(layers, "face", "bool", "sharp_face") + local mr = if mi then reader(f, mi) elseif mp then fieldReader(f, mp, "mat_nr") else nil + local flag = if mp then fieldReader(f, mp, "flag") else nil + local sr = if sf then reader(f, sf) else nil + for i = 0, np - 1 do + buffer.writei32(mats, i * 4, if mr then mr(i, 0) else 0) + local s + if sr then + s = sr(i, 0) == 0 + elseif flag then + s = bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 + else + s = poly.generation ~= "mpoly" + end + buffer.writeu8(smooth, i, if s then 1 else 0) + end + poly.faceMat, poly.faceSmooth = mats, smooth + elseif nt > 0 then + local mf = find(layers, "tess", "MFace") or legacy(f, me, "mface", "MFace", "tess") + if not mf then + return nil, "mesh without faces" + end + poly.generation = "mface" + local v = { fieldReader(f, mf, "v1"), fieldReader(f, mf, "v2"), fieldReader(f, mf, "v3"), fieldReader(f, mf, "v4") } + local mr, flag = fieldReader(f, mf, "mat_nr"), fieldReader(f, mf, "flag") + if not (v[1] and v[2] and v[3] and v[4]) then + return nil, "bad MFace" + end + local starts = buffer.create((nt + 1) * 4) + local verts = buffer.create(nt * 16) + local tessCorner = buffer.create(nt * 16) -- face * 4 + k: where tess layers keep the corner + local mats, smooth = buffer.create(nt * 4), buffer.create(nt) + local at = 0 + for i = 0, nt - 1 do + buffer.writeu32(starts, i * 4, at) + local k = if (v[4] :: any)(i, 0) ~= 0 then 4 else 3 + for c = 1, k do + buffer.writeu32(verts, (at + c - 1) * 4, math.clamp((v[c] :: any)(i, 0), 0, math.max(nv - 1, 0))) + buffer.writeu32(tessCorner, (at + c - 1) * 4, i * 4 + c - 1) + end + at += k + buffer.writei32(mats, i * 4, if mr then mr(i, 0) else 0) + buffer.writeu8(smooth, i, if flag and bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 then 1 else 0) + end + buffer.writeu32(starts, nt * 4, at) + poly.faceStart, poly.cornerVert, poly.nf, poly.nc = starts, verts, nt, at + poly.faceMat, poly.faceSmooth = mats, smooth + corner.tess = tessCorner + end + local nc = poly.nc + -- corner index -> the element index in the source corner layers + local remap: buffer? = corner.remap + local function src(i: number): number + return if remap then buffer.readu32(remap, i * 4) else i + end + -- UV maps + for _, L in layers do + if L.domain == "corner" and (L.kind == "float2" or L.kind == "MLoopUV") and string.sub(L.name, 1, 1) ~= "." then + local r = if L.kind == "float2" then reader(f, L) else fieldReader(f, L, "uv") + if r then + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local s = src(i) + buffer.writef32(d, i * 8, r(s, 0)) + buffer.writef32(d, i * 8 + 4, r(s, 1)) + end + table.insert(poly.uvs, { name = L.name, data = d }) + if L.activeRender and L.kind == "MLoopUV" then + poly.activeUV = #poly.uvs + end + end + elseif L.domain == "tess" and L.kind == "MTFace" and corner.tess then + local r = fieldReader(f, L, "uv") + if r then + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local tc = buffer.readu32(corner.tess, i * 4) + local face, k = tc // 4, tc % 4 + buffer.writef32(d, i * 8, r(face, k * 2)) + buffer.writef32(d, i * 8 + 4, r(face, k * 2 + 1)) + end + table.insert(poly.uvs, { name = L.name, data = d }) + end + end + end + local active = me:cstring("default_uv_map_attribute") or me:cstring("active_uv_map_attribute") + if active then + for k, u in poly.uvs do + if u.name == active then + poly.activeUV = k + end + end + end + -- colour attributes: f32 x 4 linear per element + for _, L in layers do + if (L.domain == "corner" or L.domain == "point") and (L.kind == "color" or L.kind == "bytecolor") and string.sub(L.name, 1, 1) ~= "." then + local n = if L.domain == "corner" then nc else nv + local r = reader(f, L) + local d = buffer.create(n * 16) + for i = 0, n - 1 do + local s = if L.domain == "corner" then src(i) else i + for c = 0, 3 do + local x = r(s, c) + if L.kind == "bytecolor" then + x = if c == 3 then x / 255 else SRGB[math.clamp(x, 0, 255) + 1] + end + buffer.writef32(d, (i * 4 + c) * 4, x) + end + end + table.insert(poly.colors, { name = L.name, domain = L.domain, data = d }) + elseif L.kind == "MCol" and L.domain == "tess" and corner.tess then + -- MCol keeps alpha, blue, green, red in its a, r, g, b fields + local st = f.dna.byName.MCol + local d = buffer.create(nc * 16) + local stride = if st then st.size else 4 + for i = 0, nc - 1 do + local tc = buffer.readu32(corner.tess, i * 4) + local at = (tc // 4) * 4 * stride + (tc % 4) * stride + if at + 4 <= L.bytes then + local o = L.offset + at + local aa, bb, gg, rr = readu8(f.buf, o), readu8(f.buf, o + 1), readu8(f.buf, o + 2), readu8(f.buf, o + 3) + buffer.writef32(d, i * 16, SRGB[rr + 1]) + buffer.writef32(d, i * 16 + 4, SRGB[gg + 1]) + buffer.writef32(d, i * 16 + 8, SRGB[bb + 1]) + buffer.writef32(d, i * 16 + 12, aa / 255) + end + end + table.insert(poly.colors, { name = L.name, domain = "corner", data = d }) + end + end + -- MLoopCol layers carry the CD_PROP_BYTE_COLOR type (17) and are read above as bytecolor (r, g, b, a bytes) + -- custom normals + local cn = find(layers, "corner", "short2", "custom_normal") + for _, L in layers do + if not cn and L.domain == "corner" and L.cdtype == 41 then + cn = L + end + end + if cn then + local r = reader(f, cn) + local d = buffer.create(nc * 4) + for i = 0, nc - 1 do + local s = src(i) + buffer.writei16(d, i * 4, r(s, 0)) + buffer.writei16(d, i * 4 + 2, r(s, 1)) + end + poly.encodedNormals = d + end + local free = find(layers, "corner", "float3", "custom_normal") or find(layers, "point", "float3", "custom_normal") + or find(layers, "face", "float3", "custom_normal") + if free then + local r = reader(f, free) + local d = buffer.create(nc * 12) + local starts = poly.faceStart + for fi = 0, poly.nf - 1 do + local s0, s1 = buffer.readu32(starts, fi * 4), buffer.readu32(starts, fi * 4 + 4) + for i = s0, s1 - 1 do + local e = if free.domain == "corner" then src(i) elseif free.domain == "face" then fi else buffer.readu32(poly.cornerVert, i * 4) + for c = 0, 2 do + buffer.writef32(d, (i * 3 + c) * 4, r(e, c)) + end + end + end + poly.customNormals = d + end + -- sharp edges + local ne = count(me, "totedge", "edges_num") + local ev = find(layers, "edge", "int2", ".edge_verts") + local se = find(layers, "edge", "bool", "sharp_edge") + local medge = find(layers, "edge", "MEdge") or legacy(f, me, "medge", "MEdge", "edge") + local flags = me:num("flag") or 0 + local smoothresh = me:num("smoothresh") + local autoSmooth = f.version < 401 and bit32.band(flags, ME_AUTOSMOOTH) ~= 0 + if autoSmooth then + poly.autoSmooth = smoothresh or math.rad(30) + end + local useSharp = f.version >= 401 or autoSmooth + if useSharp and ne > 0 then + local v1, v2, sharp + if ev and se then + local er, sr = reader(f, ev), reader(f, se) + v1 = function(i: number): number return er(i, 0) end + v2 = function(i: number): number return er(i, 1) end + sharp = function(i: number): boolean return sr(i, 0) ~= 0 end + elseif medge then + local a, b, fl = fieldReader(f, medge, "v1"), fieldReader(f, medge, "v2"), fieldReader(f, medge, "flag") + if a and b and fl then + v1 = function(i: number): number return a(i, 0) end + v2 = function(i: number): number return b(i, 0) end + local ser = if se then reader(f, se) else nil + sharp = function(i: number): boolean + if ser then + return ser(i, 0) ~= 0 + end + return bit32.band(fl(i, 0), ME_SHARP) ~= 0 + end + end + end + if v1 and v2 and sharp then + for i = 0, ne - 1 do + if sharp(i) then + local a, b = v1(i), v2(i) + local lo, hi = math.min(a, b), math.max(a, b) + poly.sharp[lo * nv + hi] = true + end + end + end + end + -- deform weights + local dv = find(layers, "point", "MDeformVert") or legacy(f, me, "dvert", "MDeformVert", "point") + if dv then + local st = f.dna.byName.MDeformVert + local dwf, twf = st and st.byName.dw, st and st.byName.totweight + local mw = f.dna.byName.MDeformWeight + local nrf, wf = mw and mw.byName.def_nr, mw and mw.byName.weight + if dwf and twf and mw and nrf and wf then + local weights = table.create(nv) + for i = 0, nv - 1 do + local list = {} + local at = i * dv.elem + if at + dv.elem <= dv.bytes then + local vw = Blend.view(f, "MDeformVert", dv.offset + at) + local blk = vw and vw:target("dw") + local n = vw and vw:num("totweight") or 0 + if blk then + n = math.min(n, blk.size // mw.size) + for k = 0, n - 1 do + local o = blk.offset + k * mw.size + table.insert(list, f.i32(f.buf, o + nrf.offset)) + table.insert(list, f.f32(f.buf, o + wf.offset)) + end + end + end + weights[i + 1] = list + end + poly.weights = weights + end + end + return poly, nil +end + +-- shape keys: { name, value, relative (0-based), data: f32 x 3 per vertex } in file order, and the reference index +export type Shape = { name: string, value: number, relative: number, data: buffer, mute: boolean } +function Mesh.shapes(f: Blend.File, me: Blend.View, nv: number): ({ Shape }, number?, Blend.View?) + local key = me:deref("key", 0, "Key") + if not key then + return {}, nil, nil + end + local blocks = key:list("block", "KeyBlock") + local refAddr = key:ptr("refkey") + local out: { Shape } = {} + local ref: number? = nil + for i, kb in blocks do + local blk = kb:target("data") + local d = buffer.create(nv * 12) + if blk then + local n = math.min(nv * 12, blk.size) + buffer.copy(d, 0, f.buf, blk.offset, n) + if not f.little then + for k = 0, n // 4 - 1 do + buffer.writef32(d, k * 4, f.f32(f.buf, blk.offset + k * 4)) + end + end + end + if kb.block and kb.block.addr == refAddr then + ref = i + end + table.insert(out, { + name = kb:str("name") or ("Key " .. i), value = kb:num("curval") or 0, relative = kb:num("relative") or 0, data = d, + mute = bit32.band(kb:num("flag") or 0, 2) ~= 0, + }) + end + if ref == nil and #out > 0 then + ref = 1 + end + return out, ref, key +end + +return Mesh diff --git a/src/Rosetta/model/blend/Normals.luau b/src/Rosetta/model/blend/Normals.luau new file mode 100644 index 0000000..980d838 --- /dev/null +++ b/src/Rosetta/model/blend/Normals.luau @@ -0,0 +1,161 @@ +--!strict +-- model/blend/Normals: Blender's encoded custom normals (CD_CUSTOMLOOPNORMAL / the "custom_normal" int16 x 2 corner +-- attribute) decoded in each smooth fan's space: the fan normal N, a reference edge direction R projected +-- perpendicular to N, O = N x R; alpha = the mean angle of the fan's edges to N, beta = the angle from R to the fan's +-- other end edge around N (2 pi for closed fans). A stored (a, b) (units of 1 / 32767) gives the angle a * alpha +-- (a > 0) or a * (2 pi - alpha) from N, turned b * beta (b > 0) or b * (2 pi - beta) from R towards O. +local Normals = {} + +local readu32, readf32, writef32, readi16 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.readi16 +local sqrt, acos, cos, sin = math.sqrt, math.acos, math.cos, math.sin +local TAU = 2 * math.pi +local NEAR = 0.99999 + +type Fans = { next: buffer, prev: buffer, face: buffer, across: { [number]: number } } + +local function dir(pos: buffer, from: number, to: number): (number, number, number) + local x = readf32(pos, to * 12) - readf32(pos, from * 12) + local y = readf32(pos, to * 12 + 4) - readf32(pos, from * 12 + 4) + local z = readf32(pos, to * 12 + 8) - readf32(pos, from * 12 + 8) + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + return x / l, y / l, z / l + end + return 0, 0, 0 +end + +function Normals.decode(poly: any, lnor: buffer, fanId: buffer, fans: Fans, _ang: buffer): buffer + local nc = poly.nc + local cv, pos = poly.cornerVert, poly.pos + local enc = poly.encodedNormals :: buffer + local out = buffer.create(nc * 12) + buffer.copy(out, 0, lnor, 0, nc * 12) + local across = fans.across + local nxt, prv = fans.next, fans.prev + local done: { [number]: boolean } = {} + for c = 0, nc - 1 do + local id = readu32(fanId, c * 4) + if not done[id] then + done[id] = true + -- walk back to the fan's first corner (crossing each corner's previous edge), then forward + local start = c + local cyclic = false + local guard = 0 + while true do + local p = across[readu32(prv, start * 4)] + if p == nil then + break + end + if p == c then + cyclic = true + break + end + start = p + guard += 1 + if guard > nc then + cyclic = true + break + end + end + if cyclic then + local m, q = c, c + repeat + local nq = across[q] + q = if nq then readu32(nxt, nq * 4) else c + if q < m then + m = q + end + guard += 1 + until q == c or guard > 2 * nc + 4 + start = m + end + local v = readu32(cv, start * 4) + local nx, ny, nz = readf32(lnor, start * 12), readf32(lnor, start * 12 + 4), readf32(lnor, start * 12 + 8) + -- the fan's edges in order: the first corner's previous edge, then every corner's next edge + local corners = { start } + local edges = { readu32(cv, readu32(prv, start * 4) * 4) } + local q = start + while true do + table.insert(edges, readu32(cv, readu32(nxt, q * 4) * 4)) + local a = across[q] + if a == nil then + break + end + local nq = readu32(nxt, a * 4) + if nq == start or #corners > nc then + break + end + table.insert(corners, nq) + q = nq + end + local alpha, count = 0, 0 + for k, e in edges do + if not (cyclic and k == #edges) then + local x, y, z = dir(pos, v, e) + alpha += acos(math.clamp(x * nx + y * ny + z * nz, -1, 1)) + count += 1 + end + end + alpha /= math.max(count, 1) + -- Blender walks each fan backwards from the corner whose next edge ends it (in a closed fan: its lowest + -- corner): R is that corner's next edge, the other end the last corner's previous edge + local refEdge = if cyclic then edges[2] else edges[#edges] + local rx, ry, rz = dir(pos, v, refEdge) + local ox, oy, oz = dir(pos, v, if cyclic then refEdge else edges[1]) + local dr, dother = rx * nx + ry * ny + rz * nz, ox * nx + oy * ny + oz * nz + local valid = math.abs(dr) < NEAR and math.abs(dother) < NEAR + local beta = 0 + local tx, ty, tz = 0, 0, 0 + if valid then + rx, ry, rz = rx - nx * dr, ry - ny * dr, rz - nz * dr + local l = sqrt(rx * rx + ry * ry + rz * rz) + rx, ry, rz = rx / l, ry / l, rz / l + tx, ty, tz = ny * rz - nz * ry, nz * rx - nx * rz, nx * ry - ny * rx + l = sqrt(tx * tx + ty * ty + tz * tz) + if l > 0 then + tx, ty, tz = tx / l, ty / l, tz / l + end + ox, oy, oz = ox - nx * dother, oy - ny * dother, oz - nz * dother + l = sqrt(ox * ox + oy * oy + oz * oz) + if l > 0 then + ox, oy, oz = ox / l, oy / l, oz / l + end + local d = rx * ox + ry * oy + rz * oz + if d < NEAR then + beta = acos(math.clamp(d, -1, 1)) + if tx * ox + ty * oy + tz * oz < 0 then + beta = TAU - beta + end + else + beta = TAU + end + end + for _, k in corners do + local a, b = readi16(enc, k * 4) / 32767, readi16(enc, k * 4 + 2) / 32767 + if a ~= 0 and valid and alpha ~= 0 and beta ~= 0 then + local al = (if a > 0 then alpha else TAU - alpha) * a + local sa = sin(al) + local x, y, z = nx * cos(al), ny * cos(al), nz * cos(al) + if b == 0 then + x, y, z = x + rx * sa, y + ry * sa, z + rz * sa + else + local be = (if b > 0 then beta else TAU - beta) * b + x += sa * (rx * cos(be) + tx * sin(be)) + y += sa * (ry * cos(be) + ty * sin(be)) + z += sa * (rz * cos(be) + tz * sin(be)) + end + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + writef32(out, k * 12, x) + writef32(out, k * 12 + 4, y) + writef32(out, k * 12 + 8, z) + end + end + end + end + return out +end + +return Normals diff --git a/src/Rosetta/model/blend/Prim.luau b/src/Rosetta/model/blend/Prim.luau new file mode 100644 index 0000000..364c346 --- /dev/null +++ b/src/Rosetta/model/blend/Prim.luau @@ -0,0 +1,452 @@ +--!strict +-- model/blend/Prim: model/blend/Mesh polygons to Scene primitives (one per material slot): corner normals from smooth +-- fans (angle-weighted face normals; sharp faces, sharp edges, auto smooth before 4.1 and non-manifold or flipped edges +-- split fans, as Blender does), custom normals, vertices shared by corners with equal attributes, n-gons by ear +-- clipping, deform weights (top 4) and shape keys as morph targets. +local Types = require("@rosetta/Types") +local Polygon = require("@rosetta/codecs/model/Polygon") +local Rig = require("@rosetta/codecs/model/Rig") +local Normals = require("@rosetta/model/blend/Normals") +local MeshT = require("@rosetta/model/blend/Mesh") + +local Prim = {} + +local Scene = Types.Scene +local readu32, readf32, writef32, writeu32 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32 +local sqrt, acos = math.sqrt, math.acos + +export type Options = { + triangulate: boolean?, -- default true + flipV: boolean?, -- default true (glTF's top-left UV origin) + normals: boolean?, -- default true +} +export type Skinning = { joints: { [number]: number } } -- def_nr (0-based) -> joint index (0-based) in the skin + +local function face(poly: MeshT.Poly, fi: number): (number, number) + return readu32(poly.faceStart, fi * 4), readu32(poly.faceStart, fi * 4 + 4) +end + +local function vec(pos: buffer, v: number): (number, number, number) + return readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8) +end + +-- face normals (Newell) and corner angles +function Prim.geometry(poly: MeshT.Poly): (buffer, buffer) + local fn = buffer.create(poly.nf * 12) + local ang = buffer.create(poly.nc * 4) + local cv, pos = poly.cornerVert, poly.pos + for fi = 0, poly.nf - 1 do + local s0, s1 = face(poly, fi) + local nx, ny, nz = 0, 0, 0 + local n = s1 - s0 + for c = s0, s1 - 1 do + local d = if c + 1 < s1 then c + 1 else s0 + local x1, y1, z1 = vec(pos, readu32(cv, c * 4)) + local x2, y2, z2 = vec(pos, readu32(cv, d * 4)) + nx += (y1 - y2) * (z1 + z2) + ny += (z1 - z2) * (x1 + x2) + nz += (x1 - x2) * (y1 + y2) + end + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + writef32(fn, fi * 12, nx) + writef32(fn, fi * 12 + 4, ny) + writef32(fn, fi * 12 + 8, nz) + if n >= 3 then + for c = s0, s1 - 1 do + local pc = if c > s0 then c - 1 else s1 - 1 + local nc = if c + 1 < s1 then c + 1 else s0 + local x, y, z = vec(pos, readu32(cv, c * 4)) + local ax, ay, az = vec(pos, readu32(cv, pc * 4)) + local bx, by, bz = vec(pos, readu32(cv, nc * 4)) + ax, ay, az = ax - x, ay - y, az - z + bx, by, bz = bx - x, by - y, bz - z + local la, lb = sqrt(ax * ax + ay * ay + az * az), sqrt(bx * bx + by * by + bz * bz) + local a = 0 + if la > 0 and lb > 0 then + a = acos(math.clamp((ax * bx + ay * by + az * bz) / (la * lb), -1, 1)) + end + writef32(ang, c * 4, a) + end + end + end + return fn, ang +end + +-- smooth fans: for each corner the corner after it in its face, and the fan links across smooth edges +export type Fans = { + next: buffer, -- u32 per corner: the next corner of its face + prev: buffer, -- u32 per corner + face: buffer, -- u32 per corner: its face + -- per corner: the corner of the neighbouring face across the edge from this corner to the next one (the corner + -- at this corner's next vertex), or -1 where the edge splits fans + across: { [number]: number }, +} + +function Prim.fans(poly: MeshT.Poly, fn: buffer): Fans + local nc, nv = poly.nc, poly.nv + local cv = poly.cornerVert + local nxt, prv, fc = buffer.create(nc * 4), buffer.create(nc * 4), buffer.create(nc * 4) + for fi = 0, poly.nf - 1 do + local s0, s1 = face(poly, fi) + for c = s0, s1 - 1 do + writeu32(nxt, c * 4, if c + 1 < s1 then c + 1 else s0) + writeu32(prv, c * 4, if c > s0 then c - 1 else s1 - 1) + writeu32(fc, c * 4, fi) + end + end + local first: { [number]: number } = {} + local second: { [number]: number } = {} + local uses: { [number]: number } = {} + for c = 0, nc - 1 do + local a, b = readu32(cv, c * 4), readu32(cv, readu32(nxt, c * 4) * 4) + local key = math.min(a, b) * nv + math.max(a, b) + local u = (uses[key] or 0) + 1 + uses[key] = u + if u == 1 then + first[key] = c + elseif u == 2 then + second[key] = c + end + end + local across: { [number]: number } = {} + local smooth = poly.faceSmooth + local cosLimit = if poly.autoSmooth then math.cos(poly.autoSmooth) else nil + for key, u in uses do + if u == 2 then + local c1, c2 = first[key], second[key] + local f1, f2 = readu32(fc, c1 * 4), readu32(fc, c2 * 4) + local a1 = readu32(cv, c1 * 4) + local a2 = readu32(cv, c2 * 4) + local ok = a1 ~= a2 and f1 ~= f2 and buffer.readu8(smooth, f1) ~= 0 and buffer.readu8(smooth, f2) ~= 0 + and not poly.sharp[key] + if ok and cosLimit then + local d = readf32(fn, f1 * 12) * readf32(fn, f2 * 12) + readf32(fn, f1 * 12 + 4) * readf32(fn, f2 * 12 + 4) + + readf32(fn, f1 * 12 + 8) * readf32(fn, f2 * 12 + 8) + ok = d >= cosLimit + end + if ok then + -- c1 runs a -> b, c2 runs b -> a: the corner at b in face 2 is c2, at a it is next(c2) + across[c1] = c2 + across[c2] = c1 + end + end + end + return { next = nxt, prev = prv, face = fc, across = across } +end + +-- corner normals: angle-weighted face normals summed over each smooth fan; with fan ids (u32 per corner) +function Prim.cornerNormals(poly: MeshT.Poly, fn: buffer, ang: buffer, fans: Fans): (buffer, buffer) + local nc = poly.nc + local parent = buffer.create(nc * 4) + for c = 0, nc - 1 do + writeu32(parent, c * 4, c) + end + local function root(c: number): number + local r = c + while readu32(parent, r * 4) ~= r do + r = readu32(parent, r * 4) + end + while readu32(parent, c * 4) ~= r do + local nx = readu32(parent, c * 4) + writeu32(parent, c * 4, r) + c = nx + end + return r + end + local function union(a: number, b: number) + local ra, rb = root(a), root(b) + if ra ~= rb then + writeu32(parent, math.max(ra, rb) * 4, math.min(ra, rb)) + end + end + for c1, c2 in fans.across do + if c1 < c2 then + -- edge c1 (a -> b) shared with c2 (b -> a): corners at b are next(c1) and c2, at a c1 and next(c2) + union(readu32(fans.next, c1 * 4), c2) + union(c1, readu32(fans.next, c2 * 4)) + end + end + local acc = buffer.create(nc * 12) + local fanId = buffer.create(nc * 4) + for c = 0, nc - 1 do + local r = root(c) + writeu32(fanId, c * 4, r) + local fi = readu32(fans.face, c * 4) + local w = readf32(ang, c * 4) + for k = 0, 2 do + writef32(acc, (r * 3 + k) * 4, readf32(acc, (r * 3 + k) * 4) + readf32(fn, (fi * 3 + k) * 4) * w) + end + end + local out = buffer.create(nc * 12) + for c = 0, nc - 1 do + local r = readu32(fanId, c * 4) + local x, y, z = readf32(acc, r * 12), readf32(acc, r * 12 + 4), readf32(acc, r * 12 + 8) + local l = sqrt(x * x + y * y + z * z) + if l > 1e-20 then + x, y, z = x / l, y / l, z / l + else + local fi = readu32(fans.face, c * 4) + x, y, z = readf32(fn, fi * 12), readf32(fn, fi * 12 + 4), readf32(fn, fi * 12 + 8) + end + writef32(out, c * 12, x) + writef32(out, c * 12 + 4, y) + writef32(out, c * 12 + 8, z) + end + return out, fanId +end + +function Prim.normals(poly: MeshT.Poly): buffer + local fn, ang = Prim.geometry(poly) + local fans = Prim.fans(poly, fn) + local nrm, fanId = Prim.cornerNormals(poly, fn, ang, fans) + if poly.customNormals then + return poly.customNormals :: buffer + end + if poly.encodedNormals then + return Normals.decode(poly, nrm, fanId, fans, ang) + end + return nrm +end + +-- triangles of face fi as corner indices (appended to out) +local function triangulate(poly: MeshT.Poly, fi: number, fnx: number, fny: number, fnz: number, out: { number }) + local s0, s1 = face(poly, fi) + local n = s1 - s0 + if n < 3 then + return + end + if n == 3 then + table.insert(out, s0) + table.insert(out, s0 + 1) + table.insert(out, s0 + 2) + return + end + local ax, ay, az = math.abs(fnx), math.abs(fny), math.abs(fnz) + local cu, cv, sign = 0, 1, fnz + if ax >= ay and ax >= az then + cu, cv, sign = 1, 2, fnx + elseif ay >= az then + cu, cv, sign = 2, 0, fny + end + local ring = table.create(n * 2) + for c = s0, s1 - 1 do + local v = readu32(poly.cornerVert, c * 4) + local u, w = readf32(poly.pos, (v * 3 + cu) * 4), readf32(poly.pos, (v * 3 + cv) * 4) + table.insert(ring, if sign < 0 then -u else u) + table.insert(ring, w) + end + local tris = Polygon.triangulate({ ring }) + if #tris == (n - 2) * 6 then + for k = 2, #tris, 2 do + table.insert(out, s0 + tris[k] - 1) + end + return + end + for k = 1, n - 2 do -- degenerate: a fan + table.insert(out, s0) + table.insert(out, s0 + k) + table.insert(out, s0 + k + 1) + end +end + +local function accessor(t: { number }, comps: number): Types.Accessor + local n = #t // comps + local b = buffer.create(#t * 4) + for i = 1, #t do + writef32(b, (i - 1) * 4, t[i]) + end + return Scene.accessor(b, "f32", comps, n) +end + +export type Built = { mesh: Types.Mesh, slots: { number }, vertexSource: { { number } } } + +-- slots[k] = the scene material of slot k - 1 (or 0 for none); skin maps deform groups to joints +function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: Skinning?, shapes: { MeshT.Shape }?, ref: number?): Built + local triangulateOn = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local withNormals = not (opts and opts.normals == false) + local nrm = if withNormals and poly.nf > 0 then Prim.normals(poly) else nil + local fn = if poly.nf > 0 then (Prim.geometry(poly)) else buffer.create(0) + local nslots = math.max(#slots, 1) + local groups: { [number]: { number } } = {} + local order: { number } = {} + for fi = 0, poly.nf - 1 do + local m = math.clamp(buffer.readi32(poly.faceMat, fi * 4), 0, nslots - 1) + local g = groups[m] + if not g then + g = {} + groups[m] = g + table.insert(order, m) + end + table.insert(g, fi) + end + table.sort(order) + local cornerColors, pointColors = {}, {} + for _, c in poly.colors do + table.insert(if c.domain == "corner" then cornerColors else pointColors, c) + end + local keyBytes = 4 + (if nrm then 12 else 0) + #poly.uvs * 8 + #cornerColors * 16 + local scratch = buffer.create(keyBytes) + local mesh: Types.Mesh = { name = poly.name, primitives = {} } + local sources: { { number } } = {} + local cv = poly.cornerVert + for _, m in order do + local faces = groups[m] + local map: { [string]: number } = {} + local vsrc: { number } = {} + local corners: { number } = {} -- the first corner of each output vertex + local cornerOut = {} -- corner -> output vertex + for _, fi in faces do + local s0, s1 = face(poly, fi) + for c = s0, s1 - 1 do + local v = readu32(cv, c * 4) + buffer.writeu32(scratch, 0, v) + local o = 4 + if nrm then + buffer.copy(scratch, o, nrm, c * 12, 12) + o += 12 + end + for _, uv in poly.uvs do + buffer.copy(scratch, o, uv.data, c * 8, 8) + o += 8 + end + for _, col in cornerColors do + buffer.copy(scratch, o, col.data, c * 16, 16) + o += 16 + end + local key = buffer.readstring(scratch, 0, keyBytes) + local idx = map[key] + if not idx then + idx = #vsrc + map[key] = idx + table.insert(vsrc, v) + table.insert(corners, c) + end + cornerOut[c] = idx + end + end + local n = #vsrc + local attrs: { [string]: Types.Accessor } = {} + local P = buffer.create(n * 12) + for i = 1, n do + buffer.copy(P, (i - 1) * 12, poly.pos, vsrc[i] * 12, 12) + end + attrs.POSITION = Scene.accessor(P, "f32", 3, n) + if nrm then + local N = buffer.create(n * 12) + for i = 1, n do + buffer.copy(N, (i - 1) * 12, nrm, corners[i] * 12, 12) + end + attrs.NORMAL = Scene.accessor(N, "f32", 3, n) + end + for k, uv in poly.uvs do + local T = buffer.create(n * 8) + for i = 1, n do + local c = corners[i] + writef32(T, (i - 1) * 8, readf32(uv.data, c * 8)) + local v = readf32(uv.data, c * 8 + 4) + writef32(T, (i - 1) * 8 + 4, if flipV then 1 - v else v) + end + local acc = Scene.accessor(T, "f32", 2, n) + acc.name = uv.name + attrs["TEXCOORD_" .. (k - 1)] = acc + end + local ci = 0 + for _, col in poly.colors do + local C = buffer.create(n * 16) + for i = 1, n do + local e = if col.domain == "corner" then corners[i] else vsrc[i] + buffer.copy(C, (i - 1) * 16, col.data, e * 16, 16) + end + local acc = Scene.accessor(C, "f32", 4, n) + acc.name = col.name + attrs["COLOR_" .. ci] = acc + ci += 1 + end + if skin and poly.weights then + local lists = table.create(n) + for i = 1, n do + local src = poly.weights[vsrc[i] + 1] or {} + local l = {} + for k = 1, #src - 1, 2 do + local j = skin.joints[src[k]] + if j then + table.insert(l, j) + table.insert(l, src[k + 1]) + end + end + lists[i] = l + end + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local prim: Types.Primitive = { attributes = attrs, mode = "triangles" } + local idx: { number } = {} + if triangulateOn then + for _, fi in faces do + local tri: { number } = {} + triangulate(poly, fi, readf32(fn, fi * 12), readf32(fn, fi * 12 + 4), readf32(fn, fi * 12 + 8), tri) + for _, c in tri do + table.insert(idx, cornerOut[c]) + end + end + else + local sizes = buffer.create(#faces * 4) + for k, fi in faces do + local s0, s1 = face(poly, fi) + writeu32(sizes, (k - 1) * 4, s1 - s0) + for c = s0, s1 - 1 do + table.insert(idx, cornerOut[c]) + end + end + prim.mode = "polygons" + prim.faces = Scene.accessor(sizes, "u32", 1, #faces) + end + local I = buffer.create(#idx * 4) + for k, v in idx do + writeu32(I, (k - 1) * 4, v) + end + prim.indices = Scene.accessor(I, "u32", 1, #idx) + local mat = slots[m + 1] + if mat and mat > 0 then + prim.material = mat + end + if shapes and ref and #shapes > 1 then + local base = shapes[ref].data + local targets = {} + for k, s in shapes do + if k ~= ref then + local t = table.create(n * 3) + for i = 1, n do + local v = vsrc[i] + for c = 0, 2 do + t[(i - 1) * 3 + c + 1] = readf32(s.data, (v * 3 + c) * 4) - readf32(base, (v * 3 + c) * 4) + end + end + table.insert(targets, { POSITION = accessor(t, 3) }) + end + end + prim.targets = targets + end + table.insert(mesh.primitives, prim) + table.insert(sources, vsrc) + end + if shapes and ref and #shapes > 1 then + local w = {} + for k, s in shapes do + if k ~= ref then + table.insert(w, s.value) + end + end + mesh.weights = w + end + local usedSlots = {} + for _, m in order do + table.insert(usedSlots, m) + end + return { mesh = mesh, slots = usedSlots, vertexSource = sources } +end + +return Prim diff --git a/src/Rosetta/model/blend/Read.luau b/src/Rosetta/model/blend/Read.luau new file mode 100644 index 0000000..40f8a2a --- /dev/null +++ b/src/Rosetta/model/blend/Read.luau @@ -0,0 +1,862 @@ +--!strict +-- model/blend/Read: a parsed .blend (containers/Blend) to a Scene: the current scene's objects (from its collections, +-- or Base list before 2.8) with their transforms (euler orders, quaternion, axis angle, delta transforms, parent +-- inverse; bone parents), meshes (model/blend/Mesh, model/blend/Prim), materials (Principled BSDF node or the legacy +-- colour), images (packed bytes or external uris), cameras, lights (watts to candela / lux as Blender's glTF exporter +-- does: 683 lm/W, / 4 pi for point and spot), armatures (bones to joint nodes with the saved pose), skins, shape keys +-- and actions sampled into channels. +local Blend = require("@rosetta/containers/Blend") +local Types = require("@rosetta/Types") +local Mat4 = require("@rosetta/codecs/model/Mat4") +local Rig = require("@rosetta/codecs/model/Rig") +local Mesh = require("@rosetta/model/blend/Mesh") +local Prim = require("@rosetta/model/blend/Prim") +local Anim = require("@rosetta/model/blend/Anim") +local Material = require("@rosetta/model/blend/Material") + +local Read = {} + +local Scene = Types.Scene +type M4 = { number } + +export type Options = { + triangulate: boolean?, + flipV: boolean?, + collections: boolean?, -- collections as nodes (default true) + scene: string?, -- the scene to read (default: the file's current scene) + sampleStep: number?, -- frames between animation samples (default 1) + animations: boolean?, -- default true + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + maxVertices: number?, +} + +local OB_EMPTY, OB_MESH, OB_LAMP, OB_CAMERA, OB_ARMATURE = 0, 1, 10, 11, 25 +local PARSKEL, PARBONE = 4, 7 +local LA_LOCAL, LA_SUN, LA_SPOT, LA_HEMI, LA_AREA = 0, 1, 2, 3, 4 +local EULER = { [1] = "xyz", [2] = "xzy", [3] = "yxz", [4] = "yzx", [5] = "zxy", [6] = "zyx" } +local TYPE_NAME: { [number]: string } = { + [0] = "empty", [1] = "mesh", [2] = "curve", [3] = "surface", [4] = "text", [5] = "metaball", [10] = "light", + [11] = "camera", [12] = "speaker", [13] = "lightprobe", [22] = "lattice", [25] = "armature", [26] = "gpencil", + [27] = "curves", [28] = "pointcloud", [29] = "volume", [30] = "grease_pencil", +} +local W2LM = 683 + +-- ------------------------------------------------------------------------------------------------ transforms +local function quatWXYZ(q: { number }?): { number } + if not q or #q < 4 then + return { 0, 0, 0, 1 } + end + local w, x, y, z = q[1], q[2], q[3], q[4] + local l = math.sqrt(w * w + x * x + y * y + z * z) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + return { x / l, y / l, z / l, w / l } +end + +local function rotation(mode: number, eul: { number }?, quat: { number }?, axis: { number }?, angle: number?): M4 + if mode == 0 then + return Mat4.fromQuat(quatWXYZ(quat)) + elseif mode == -1 then + local a = axis or { 0, 1, 0 } + return Mat4.fromQuat(Mat4.axisAngle(a[1], a[2], a[3], math.deg(angle or 0))) + end + local e = eul or { 0, 0, 0 } + return Mat4.euler(math.deg(e[1]), math.deg(e[2]), math.deg(e[3]), EULER[mode] or "xyz") +end + +local function scaleM(m: M4, s: { number }): M4 + local r = table.clone(m) + for c = 0, 2 do + for k = 1, 3 do + r[c * 4 + k] *= s[c + 1] + end + end + return r +end + +local function trs(t: { number }, r: M4, s: { number }): M4 + local m = scaleM(r, s) + m[13], m[14], m[15] = t[1], t[2], t[3] + return m +end + +export type Props = { [string]: { number } } -- location / rotation_euler / ... as Blender data paths, rotmode + +-- an object's or pose bone's transform properties, keyed by their RNA names +local function objectProps(ob: Blend.View): Props + local function v(n: number, ...: string): { number } + local x = ob:vec(...) + if x and #x >= n then + return table.clone(x) + end + return table.create(n, 0) + end + return { + location = v(3, "loc"), + rotation_euler = v(3, "rot"), + rotation_quaternion = v(4, "quat"), + rotation_axis_angle = { ob:num("rotAngle") or 0, table.unpack(v(3, "rotAxis")) }, + scale = v(3, "scale", "size"), + delta_location = v(3, "dloc"), + delta_rotation_euler = v(3, "drot"), + delta_rotation_quaternion = v(4, "dquat"), + delta_rotation_axis_angle = { ob:num("drotAngle") or 0, table.unpack(v(3, "drotAxis")) }, + delta_scale = v(3, "dscale", "dsize"), + rotmode = { ob:num("rotmode") or 1 }, + } +end + +local function poseProps(pc: Blend.View?): Props + if not pc then + return { + location = { 0, 0, 0 }, rotation_euler = { 0, 0, 0 }, rotation_quaternion = { 1, 0, 0, 0 }, + rotation_axis_angle = { 0, 0, 1, 0 }, scale = { 1, 1, 1 }, rotmode = { 0 }, + } + end + local function v(n: number, ...: string): { number } + local x = pc:vec(...) + if x and #x >= n then + return table.clone(x) + end + return table.create(n, 0) + end + return { + location = v(3, "loc"), + rotation_euler = v(3, "eul"), + rotation_quaternion = v(4, "quat"), + rotation_axis_angle = { pc:num("rotAngle") or 0, table.unpack(v(3, "rotAxis")) }, + scale = v(3, "scale", "size"), + rotmode = { pc:num("rotmode") or 0 }, + } +end + +-- Blender's object matrix: T(loc + dloc) * Rdelta * R * S(scale * dscale) +local function objectBasis(p: Props): M4 + local mode = p.rotmode[1] + local aa, daa = p.rotation_axis_angle, p.delta_rotation_axis_angle + local r = rotation(mode, p.rotation_euler, p.rotation_quaternion, { aa[2], aa[3], aa[4] }, aa[1]) + if p.delta_location then + local d = rotation(mode, p.delta_rotation_euler, p.delta_rotation_quaternion, { daa[2], daa[3], daa[4] }, daa[1]) + r = Mat4.mul(d, r) + local l, dl, s, ds = p.location, p.delta_location, p.scale, p.delta_scale + return trs({ l[1] + dl[1], l[2] + dl[2], l[3] + dl[3] }, r, { s[1] * ds[1], s[2] * ds[2], s[3] * ds[3] }) + end + return trs(p.location, r, p.scale) +end + +local function nodeTRS(node: Types.Node, m: M4) + local t, r, s = Mat4.decomposeStrict(m) + if t and r and s then + node.translation, node.rotation, node.scale = t, r, s + node.matrix = nil + else + node.matrix = m + node.translation, node.rotation, node.scale = nil, nil, nil + end +end + +local function mat4(v: Blend.View?, ...: string): M4? + local m = v and v:vec(...) + if m and #m == 16 then + return m + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ scene +type Ctx = { + f: Blend.File, + scene: Types.Scene, + opts: Options, + objects: { [any]: number }, -- OB addr -> node + objView: { [number]: Blend.View }, -- node -> its object + parentOf: { [number]: number }, + world: { [number]: M4 }, + meshes: { [string]: number }, + materials: { [any]: number }, + textures: { [any]: number }, + armatures: { [any]: { joints: { number }, names: { [string]: number }, rest: { M4 }, restLocal: { M4 }, bones: { Blend.View }, deform: { boolean }, node: number, poseNames: { [string]: Blend.View } } }, + prefix: { [number]: M4 }, -- node -> the matrix before its basis (parent inverse, bone tail offset) + props: { [number]: Props }, + meta: { [string]: any }, + pending: { { node: number, ob: Blend.View } }, +} + +local function worldOf(ctx: Ctx, node: number): M4 + local cached = ctx.world[node] + if cached then + return cached + end + local m = Scene.nodeMatrix(ctx.scene.nodes[node]) + local p = ctx.parentOf[node] + local w = if p then Mat4.mul(worldOf(ctx, p), m) else m + ctx.world[node] = w + return w +end + +local function addNode(ctx: Ctx, node: Types.Node, parent: number?): number + table.insert(ctx.scene.nodes, node) + local idx = #ctx.scene.nodes + if parent then + table.insert(ctx.scene.nodes[parent].children, idx) + ctx.parentOf[idx] = parent + else + table.insert(ctx.scene.roots, idx) + end + return idx +end + +local function armature(ctx: Ctx, ob: Blend.View, node: number) + local f = ctx.f + local arm = ob:deref("data", 0, "bArmature") + if not arm then + return + end + local pose = ob:deref("pose", 0, "bPose") + local poseNames: { [string]: Blend.View } = {} + if pose then + for _, pc in pose:list("chanbase", "bPoseChannel") do + local n = pc:str("name") + if n then + poseNames[n] = pc + end + end + end + local info = { joints = {}, names = {}, rest = {}, restLocal = {}, bones = {}, deform = {}, node = node, poseNames = poseNames } + local function walk(list: { Blend.View }, parentJoint: number?, parentRest: M4?, depth: number) + if depth > 256 then + return + end + for _, bone in list do + local name = bone:str("name") or "" + local rest = mat4(bone, "arm_mat") or Mat4.identity() + local restLocal = if parentRest then Mat4.mul(Mat4.inverseFull(parentRest) or Mat4.identity(), rest) else rest + local props = poseProps(poseNames[name]) + local basis = objectBasis(props) + local jnode: Types.Node = { name = name, children = {} } + nodeTRS(jnode, Mat4.mul(restLocal, basis)) + local parentNode = if parentJoint then info.joints[parentJoint] else node + local idx = addNode(ctx, jnode, parentNode) + table.insert(info.joints, idx) + table.insert(info.bones, bone) + table.insert(info.rest, rest) + table.insert(info.restLocal, restLocal) + table.insert(info.deform, bit32.band(bone:num("flag") or 0, 0x1000) == 0) + local j = #info.joints + info.names[name] = j + ctx.props[idx] = props + ctx.prefix[idx] = restLocal + jnode.extras = { blend = { bone = true, length = bone:num("length") or 0 } } + walk(bone:list("childbase", "Bone"), j, rest, depth + 1) + end + end + walk(arm:list("bonebase", "Bone"), nil, nil, 0) + ctx.armatures[ob.block and ob.block.addr or node] = info + local _ = f +end + +local function camera(ctx: Ctx, ob: Blend.View, node: number) + local cam = ob:deref("data", 0, "Camera") + if not cam then + return + end + local r = ctx.meta.render + local aspect = r.aspect + local znear, zfar = cam:num("clip_start", "clipsta") or 0.1, cam:num("clip_end", "clipend") or 100 + local c: Types.Camera + if (cam:num("type") or 0) == 1 then + local half = (cam:num("ortho_scale") or 6) / 2 + local xmag, ymag = half, half / aspect + if aspect < 1 then + xmag, ymag = half * aspect, half + end + c = { name = ob:idName(), type = "orthographic", xmag = xmag, ymag = ymag, znear = znear, zfar = zfar } + else + local lens = cam:num("lens") or 50 + local sx, sy = cam:num("sensor_x") or 36, cam:num("sensor_y") or 24 + local fit = cam:num("sensor_fit") or 0 + local yfov + if fit == 2 then + yfov = 2 * math.atan(sy / 2 / lens) + elseif fit == 1 or aspect >= 1 then + yfov = 2 * math.atan(math.tan(math.atan(sx / 2 / lens)) / aspect) + else + yfov = 2 * math.atan(sx / 2 / lens) + end + c = { name = ob:idName(), type = "perspective", yfov = yfov, aspect = aspect, znear = znear, zfar = zfar } + end + table.insert(ctx.scene.cameras, c) + ctx.scene.nodes[node].camera = #ctx.scene.cameras +end + +local function light(ctx: Ctx, ob: Blend.View, node: number) + local la = ob:deref("data", 0, "Light") or ob:deref("data", 0, "Lamp") + if not la then + return + end + local t = la:num("type") or 0 + local color = { la:num("r") or 1, la:num("g") or 1, la:num("b") or 1 } + local energy = la:num("energy") or 1 + if ctx.f.version < 280 then + -- before 2.8 Cycles took the strength from the lamp's Emission node, else 100 (sun: 1); Blender's 2.8 + -- versioning moves that to energy + energy = if t == LA_SUN or t == LA_HEMI then 1 else 100 + local tree = (la:num("use_nodes") or 0) ~= 0 and la:deref("nodetree", 0, "bNodeTree") or nil + for _, n in if tree then tree:list("nodes", "bNode") else {} do + if n:str("idname") == "ShaderNodeEmission" then + for _, s in n:list("inputs", "bNodeSocket") do + local v = s:str("name") == "Strength" and s:deref("default_value", 0, "bNodeSocketValueFloat") + if v then + energy = v:num("value") or energy + end + end + end + end + end + local name = ob:idName() + local l: Types.Light + if t == LA_SUN or t == LA_HEMI then + l = { name = name, type = "directional", color = color, intensity = energy * W2LM } + elseif t == LA_SPOT then + local outer = (la:num("spotsize") or math.rad(45)) / 2 + local blend = la:num("spotblend") or 0 + l = { name = name, type = "spot", color = color, intensity = energy / (4 * math.pi) * W2LM, outerCone = outer, innerCone = outer - outer * blend } + elseif t == LA_LOCAL then + l = { name = name, type = "point", color = color, intensity = energy / (4 * math.pi) * W2LM } + else + local skipped = ctx.meta.skippedLights or {} + ctx.meta.skippedLights = skipped + table.insert(skipped, { name = name, type = if t == LA_AREA then "area" else tostring(t) }) + return + end + table.insert(ctx.scene.lights, l) + ctx.scene.nodes[node].light = #ctx.scene.lights +end + +local function slotMaterials(ctx: Ctx, ob: Blend.View, me: Blend.View): { number } + local obMats = ob:pointers("mat", ob:num("totcol")) + local meMats = me:pointers("mat", me:num("totcol")) + local bits = ob:target("matbits") + local n = math.max(#obMats, #meMats) + local out = {} + for i = 1, n do + local useOb = bits ~= nil and i - 1 < bits.size and buffer.readu8(ctx.f.buf, bits.offset + i - 1) ~= 0 + local addr = if useOb then obMats[i] else meMats[i] + local m = 0 + if addr then + local blk = Blend.resolve(ctx.f, addr) + local mv = blk and Blend.struct(ctx.f, blk, 0, "Material") + if mv then + m = Material.get(ctx :: any, mv) + end + end + out[i] = m + end + return out +end + +local function deformArmature(ctx: Ctx, ob: Blend.View): Blend.View? + for _, md in ob:list("modifiers") do + if md.struct.name == "ArmatureModifierData" then + local a = md:deref("object", 0, "Object") + if a then + return a + end + end + end + local p = ob:deref("parent", 0, "Object") + if p and (ob:num("partype") or 0) == PARSKEL and (p:num("type") or -1) == OB_ARMATURE then + return p + end + return nil +end + +local function groupNames(ob: Blend.View, me: Blend.View): { string } + local list = me:list("vertex_group_names", "bDeformGroup") + if #list == 0 then + list = ob:list("defbase", "bDeformGroup") + end + local out = {} + for i, g in list do + out[i] = g:str("name") or "" + end + return out +end + +local function mesh(ctx: Ctx, ob: Blend.View, node: number) + local f = ctx.f + local me = ob:deref("data", 0, "Mesh") + if not me then + return + end + local slots = slotMaterials(ctx, ob, me) + local armOb = deformArmature(ctx, ob) + local armInfo = armOb and armOb.block and ctx.armatures[armOb.block.addr] + local key = tostring(me.block and me.block.index) .. ":" .. table.concat(slots, ",") .. ":" .. tostring(armOb and armOb.block and armOb.block.index) + local skin: Prim.Skinning? = nil + if armInfo then + local joints = {} + for gi, name in groupNames(ob, me) do + local j = armInfo.names[name] + if j and armInfo.deform[j] then + joints[gi - 1] = j - 1 + end + end + skin = { joints = joints } + end + local idx = ctx.meshes[key] + if not idx then + local poly, err = Mesh.read(f, me, { maxVertices = ctx.opts.maxVertices }) + if not poly then + error(err or "bad mesh", 0) + end + local shapes, ref = Mesh.shapes(f, me, poly.nv) + local built = Prim.build(poly, slots, { triangulate = ctx.opts.triangulate, flipV = ctx.opts.flipV }, skin, shapes, ref) + local m = built.mesh + m.extras = { blend = { vertices = poly.nv, faces = poly.nf, corners = poly.nc, generation = poly.generation, uvs = #poly.uvs, colors = #poly.colors, shapes = #shapes } } + table.insert(ctx.scene.meshes, m) + idx = #ctx.scene.meshes + ctx.meshes[key] = idx + local gens = ctx.meta.generations + gens[poly.generation] = (gens[poly.generation] or 0) + 1 + if #shapes > 1 then + ctx.meta.shapeKeys[idx] = { key = me:deref("key", 0, "Key"), mesh = me, shapes = shapes, ref = ref } + end + end + local n = ctx.scene.nodes[node] + n.mesh = idx + if ctx.scene.meshes[idx].weights then + n.weights = table.clone(ctx.scene.meshes[idx].weights :: { number }) + end + if armInfo then + table.insert(ctx.pending, { node = node, ob = ob }) + end +end + +local function skins(ctx: Ctx) + for _, p in ctx.pending do + local armOb = deformArmature(ctx, p.ob) + local info = armOb and armOb.block and ctx.armatures[armOb.block.addr] + if info then + local armWorld = worldOf(ctx, info.node) + local meshWorld = worldOf(ctx, p.node) + local n = #info.joints + local ibm = buffer.create(n * 64) + for j = 1, n do + local inv = Mat4.inverseFull(Mat4.mul(armWorld, info.rest[j])) or Mat4.identity() + local m = Mat4.mul(inv, meshWorld) + for k = 1, 16 do + buffer.writef32(ibm, ((j - 1) * 16 + k - 1) * 4, m[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, n) + acc.matrix = true + table.insert(ctx.scene.skins, { name = armOb and armOb:idName(), joints = table.clone(info.joints), inverseBindMatrices = acc, skeleton = info.node }) + ctx.scene.nodes[p.node].skin = #ctx.scene.skins + end + end +end + +local function object(ctx: Ctx, ob: Blend.View, under: number?, depth: number): number? + local addr = ob.block and ob.block.addr + if addr ~= nil and ctx.objects[addr] then + return ctx.objects[addr] + end + if depth > 512 then + return nil + end + local parentOb = ob:deref("parent", 0, "Object") + local parentNode: number? = under + local prefix = Mat4.identity() + local partype = ob:num("partype") or 0 + if parentOb then + local pn = object(ctx, parentOb, under, depth + 1) + if pn then + parentNode = pn + prefix = mat4(ob, "parentinv") or Mat4.identity() + if partype == PARBONE then + local info = parentOb.block and ctx.armatures[parentOb.block.addr] + local bone = ob:str("parsubstr") or "" + local j = info and info.names[bone] + if info and j then + parentNode = info.joints[j] + local len = info.bones[j]:num("length") or 0 + prefix = Mat4.mul(Mat4.translation(0, len, 0), prefix) + end + end + end + end + if addr ~= nil and ctx.objects[addr] then + return ctx.objects[addr] + end + local props = objectProps(ob) + local node: Types.Node = { name = ob:idName(), children = {} } + nodeTRS(node, Mat4.mul(prefix, objectBasis(props))) + local idx = addNode(ctx, node, parentNode) + if addr ~= nil then + ctx.objects[addr] = idx + end + ctx.objView[idx] = ob + ctx.props[idx] = props + ctx.prefix[idx] = prefix + local t = ob:num("type") or -1 + local extras: { [string]: any } = { type = TYPE_NAME[t] or tostring(t) } + node.extras = { blend = extras } + local lay = ob:num("lay") + if lay and ctx.f.version < 280 then + extras.layers = lay + end + local mods = {} + for _, md in ob:list("modifiers") do + table.insert(mods, { name = md:sub("modifier") and (md:sub("modifier") :: Blend.View):str("name") or md:str("name") or "", type = (string.gsub(md.struct.name, "ModifierData$", "")) }) + end + if #mods > 0 then + extras.modifiers = mods + ctx.meta.modifiers[node.name or tostring(idx)] = mods + end + if t == OB_ARMATURE then + armature(ctx, ob, idx) + elseif t == OB_CAMERA then + camera(ctx, ob, idx) + elseif t == OB_LAMP then + light(ctx, ob, idx) + elseif t ~= OB_EMPTY and t ~= OB_MESH then + ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] = (ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] or 0) + 1 + end + return idx +end + +-- ------------------------------------------------------------------------------------------------ animation +local function apply(props: Props, curves: { Curve }, frame: number, prefix: string?, name: string?): Props + local p: Props = {} + for k, v in props do + p[k] = table.clone(v) + end + for _, c in curves do + local kind, who, rest = Anim.split(c.path) + if (prefix == nil and kind == nil) or (prefix ~= nil and kind == prefix and who == name) then + local arr = p[rest] + if arr and c.index >= 0 and c.index < #arr then + local v = Anim.evaluate(c, frame) + if rest == "rotation_axis_angle" or rest == "delta_rotation_axis_angle" then + arr[c.index + 1] = v + else + arr[c.index + 1] = v + end + end + end + end + return p +end +type Curve = Anim.Curve + +local function frames(lo: number, hi: number, step: number): { number } + local out = {} + local f = lo + while f < hi - 1e-9 and #out < 2 ^ 20 do + table.insert(out, f) + f += step + end + table.insert(out, hi) + return out +end + +type Job = { kind: string, node: number?, nodes: { number }?, info: any?, curves: { Curve }, action: string, meshIdx: number? } + +local function animations(ctx: Ctx) + local f = ctx.f + local jobs: { Job } = {} + for node = 1, #ctx.scene.nodes do + local ob = ctx.objView[node] + local curves, name + if ob then + curves, name = Anim.curves(f, ob:deref("adt", 0, "AnimData")) + end + if curves and #curves > 0 and name then + table.insert(jobs, { kind = "object", node = node, curves = curves, action = name }) + local info = ob.block and ctx.armatures[ob.block.addr] + if info then + table.insert(jobs, { kind = "pose", info = info, curves = curves, action = name }) + end + end + end + for meshIdx, sk in ctx.meta.shapeKeys do + local curves, name = Anim.curves(f, sk.key and sk.key:deref("adt", 0, "AnimData")) + -- 2.7x could key shape values from the mesh ("shape_keys.key_blocks[...].value") + local mc, mname = Anim.curves(f, sk.mesh:deref("adt", 0, "AnimData")) + for _, c in mc or {} do + if string.sub(c.path, 1, 11) == "shape_keys." then + c.path = string.sub(c.path, 12) + curves = curves or {} + name = name or mname + table.insert(curves :: { Curve }, c) + end + end + if curves and #curves > 0 and name then + local nodes = {} + for i, n in ctx.scene.nodes do + if n.mesh == meshIdx then + table.insert(nodes, i) + end + end + table.insert(jobs, { kind = "shapes", nodes = nodes, curves = curves, action = name, meshIdx = meshIdx }) + end + end + if #jobs == 0 then + return + end + table.sort(jobs, function(a: Job, b: Job): boolean + return a.action < b.action + end) + local zero = ctx.meta.frameStart + for _, j in jobs do + local lo = Anim.range(j.curves) + zero = math.min(zero, math.floor(lo)) + end + ctx.meta.frameZero = zero + local fps = ctx.meta.fps + local step = ctx.opts.sampleStep or 1 + local byAction: { [string]: Types.Animation } = {} + for _, j in jobs do + local anim = byAction[j.action] + if not anim then + anim = { name = j.action, channels = {} } + byAction[j.action] = anim + table.insert(ctx.scene.animations, anim) + end + local lo, hi = Anim.range(j.curves) + local fs = frames(lo, hi, step) + local times = {} + for i, fr in fs do + times[i] = (fr - zero) / fps + end + local tmp = Scene.new() + if j.kind == "object" then + local node = j.node :: number + local track = { translation = {}, rotation = {}, scale = {} } + local last: { number }? = nil + for _, fr in fs do + local p = apply(ctx.props[node], j.curves, fr, nil, nil) + local t, r, s = Mat4.decompose(Mat4.mul(ctx.prefix[node], objectBasis(p))) + if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + last = r + table.move(t, 1, 3, #track.translation + 1, track.translation) + table.move(r, 1, 4, #track.rotation + 1, track.rotation) + table.move(s, 1, 3, #track.scale + 1, track.scale) + end + local nd = ctx.scene.nodes[node] + if nd.matrix then + local t, r, s = Mat4.decompose(nd.matrix) + nd.translation, nd.rotation, nd.scale, nd.matrix = t, r, s, nil + end + Rig.animation(tmp, nil, { node }, times, { [1] = track :: any }, nil) + elseif j.kind == "pose" then + local info = j.info + local tracks = {} + local touched = {} + for _, c in j.curves do + local kind, who = Anim.split(c.path) + if kind == "pose.bones" and who and info.names[who] then + touched[info.names[who]] = true + end + end + for b in touched do + local name = info.bones[b]:str("name") or "" + local node = info.joints[b] + local track = { translation = {}, rotation = {}, scale = {} } + local last: { number }? = nil + for _, fr in fs do + local p = apply(ctx.props[node], j.curves, fr, "pose.bones", name) + local t, r, s = Mat4.decompose(Mat4.mul(info.restLocal[b], objectBasis(p))) + if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + last = r + table.move(t, 1, 3, #track.translation + 1, track.translation) + table.move(r, 1, 4, #track.rotation + 1, track.rotation) + table.move(s, 1, 3, #track.scale + 1, track.scale) + end + tracks[b] = track + end + Rig.animation(tmp, nil, info.joints, times, tracks :: any, nil) + elseif j.kind == "shapes" then + local sk = ctx.meta.shapeKeys[j.meshIdx] + local count = #sk.shapes - 1 + local out = buffer.create(#fs * count * 4) + for i, fr in fs do + local k = 0 + for si, s in sk.shapes do + if si ~= sk.ref then + local v = s.value + for _, c in j.curves do + local kind, who, rest = Anim.split(c.path) + if kind == "key_blocks" and who == s.name and rest == "value" then + v = Anim.evaluate(c, fr) + end + end + buffer.writef32(out, ((i - 1) * count + k) * 4, v) + k += 1 + end + end + end + local tb = buffer.create(#times * 4) + for i, t in times do + buffer.writef32(tb, (i - 1) * 4, t) + end + for _, node in j.nodes :: { number } do + table.insert(tmp.animations, { channels = { + { node = node, path = "weights" :: any, input = Scene.accessor(tb, "f32", 1, #times), output = Scene.accessor(out, "f32", 1, #fs * count), interpolation = "LINEAR" :: any }, + } }) + end + end + for _, a in tmp.animations do + for _, ch in a.channels do + table.insert(anim.channels, ch) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ entry +local function pickScene(f: Blend.File, name: string?): Blend.View? + local scenes = Blend.blocks(f, "SC") + if name then + for _, b in scenes do + local v = Blend.struct(f, b, 0, "Scene") + if v and v:idName() == name then + return v + end + end + return nil + end + local glob = Blend.blocks(f, "GLOB")[1] + local g = glob and Blend.struct(f, glob, 0, "FileGlobal") + local cur = g and g:target("curscene") + if cur and cur.code == "SC" then + return Blend.struct(f, cur, 0, "Scene") + end + return if scenes[1] then Blend.struct(f, scenes[1], 0, "Scene") else nil +end + +function Read.scene(f: Blend.File, opts: Options?): (Types.Scene?, string?) + local o: Options = opts or {} + local scene = Scene.new() + local sc = pickScene(f, o.scene) + if o.scene and not sc then + return nil, "no scene named " .. o.scene + end + local meta: { [string]: any } = { + modifiers = {}, unsupported = {}, generations = {}, shapeKeys = {}, collections = {}, + fps = 24, frameStart = 1, render = { aspect = 16 / 9 }, + } + local ctx: Ctx = { + f = f, scene = scene, opts = o, objects = {}, objView = {}, parentOf = {}, world = {}, meshes = {}, materials = {}, + textures = {}, armatures = {}, prefix = {}, props = {}, meta = meta, pending = {}, + } + local order: { { ob: Blend.View, under: number? } } = {} + if sc then + local r = sc:sub("r") + if r then + local fps = (r:num("frs_sec") or 24) / math.max(r:num("frs_sec_base") or 1, 1e-6) + meta.fps = if fps > 0 then fps else 24 + meta.frameStart = r:num("sfra") or 1 + local xs, ys = r:num("xsch") or 1920, r:num("ysch") or 1080 + local xa, ya = r:num("xasp") or 1, r:num("yasp") or 1 + if xs > 0 and ys > 0 and xa > 0 and ya > 0 then + meta.render = { aspect = (xs * xa) / (ys * ya), width = xs, height = ys } + end + end + local units = sc:sub("unit") + local scale = units and units:num("scale_length") + if scale and scale > 0 then + scene.meta.unit = scale + end + local master = sc:deref("master_collection", 0, "Collection") + if master then + local seen = {} + local function walk(col: Blend.View, under: number?, depth: number) + if depth > 64 or (col.block and seen[col.block.addr]) then + return + end + if col.block then + seen[col.block.addr] = true + end + for _, co in col:list("gobject", "CollectionObject") do + local ob = co:deref("ob", 0, "Object") + if ob then + table.insert(order, { ob = ob, under = under }) + end + end + for _, cc in col:list("children", "CollectionChild") do + local child = cc:deref("collection", 0, "Collection") + if child then + local cn: number? = nil + if o.collections ~= false then + cn = addNode(ctx, { name = child:idName(), children = {}, extras = { blend = { collection = true } } }, under) + end + table.insert(meta.collections, child:idName() or "") + walk(child, cn, depth + 1) + end + end + end + walk(master, nil, 0) + else + for _, base in sc:list("base", "Base") do + local ob = base:deref("object", 0, "Object") + if ob then + table.insert(order, { ob = ob, under = nil }) + end + end + end + end + if #order == 0 then + for _, b in Blend.blocks(f, "OB") do + local ob = Blend.struct(f, b, 0, "Object") + if ob then + table.insert(order, { ob = ob, under = nil }) + end + end + end + -- objects whose parent sits in a collection go under the parent; others under their (first) collection + local firstUnder: { [any]: number? } = {} + for _, e in order do + local a = e.ob.block and e.ob.block.addr + if a ~= nil and firstUnder[a] == nil then + firstUnder[a] = e.under or 0 + end + end + for _, e in order do + local a = e.ob.block and e.ob.block.addr + local u = a ~= nil and firstUnder[a] or nil + object(ctx, e.ob, if u and u > 0 then u else nil, 0) + end + -- meshes after every object exists (armatures first, for skins) + for node = 1, #scene.nodes do + local ob = ctx.objView[node] + if ob and (ob:num("type") or -1) == OB_MESH then + mesh(ctx, ob, node) + end + end + skins(ctx) + if o.animations ~= false then + animations(ctx) + end + meta.shapeKeys = nil + local render = meta.render + meta.render = nil + scene.meta.up = "z" + scene.meta.source = { + format = "blend", version = f.version, subversion = f.subversion, pointerSize = f.pointerSize, + littleEndian = f.little, compression = f.compression, fps = meta.fps, frameStart = meta.frameStart, + frameZero = meta.frameZero, modifiers = meta.modifiers, unsupported = meta.unsupported, + generations = meta.generations, collections = meta.collections, skippedLights = meta.skippedLights, + aspect = render.aspect, scene = sc and sc:idName(), + } + return scene, nil +end + +return Read diff --git a/src/Rosetta/model/blend/init.luau b/src/Rosetta/model/blend/init.luau new file mode 100644 index 0000000..c4cc09b --- /dev/null +++ b/src/Rosetta/model/blend/init.luau @@ -0,0 +1,75 @@ +--!strict +-- model/blend: Blender .blend files (read only), every version from 2.4x to 5.x: plain, gzip or zstd compressed; +-- 32 / 64-bit pointers, either byte order; the 5.0+ header. New in rosetta (from the file layout, read through each +-- file's own SDNA). Supports: the scene's objects and collections, transforms with parent inverse and bone parents, +-- meshes of every storage generation (MFace, MPoly / MLoop, attribute layers, AttributeStorage) with UV maps, colour +-- attributes, custom normals, material slots; Principled BSDF materials; packed and external images; cameras; lights; +-- armatures, skins (vertex groups, top 4 weights), shape keys; actions sampled into channels. +-- Not supported: modifiers (listed in meta.source.modifiers), curves / text / metaballs / grease pencil / volumes, +-- NLA strips, drivers, constraints, f-curve modifiers, linked libraries, collection instances. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@rosetta/core/Err") +local Bytes = require("@rosetta/core/Bytes") +local Types = require("@rosetta/Types") +local Blend = require("@rosetta/containers/Blend") +local Read = require("@rosetta/model/blend/Read") +local Anim = require("@rosetta/model/blend/Anim") + +-- ------------------------------------------------------------------------------------------------ contract +local BlendFormat = { + name = "blend", + category = "model", + extensions = { "blend" }, + mime = { "application/x-blender" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type DecodeOptions = { + triangulate: boolean?, -- default true (false: "polygons" primitives) + flipV: boolean?, -- default true (glTF's top-left UV origin) + collections: boolean?, -- collections as nodes (default true) + scene: string?, -- a scene by name (default: the file's current scene) + sampleStep: number?, -- frames between animation samples (default 1) + animations: boolean?, -- default true + resolve: ((uri: string) -> any)?, -- external images + files: { [string]: any }?, + maxBytes: number?, -- decompressed size limit (default 2^31) + maxVertices: number?, -- per mesh (default 2^25) +} + +-- ------------------------------------------------------------------------------------------------ sniff +function BlendFormat.sniff(r: Bytes.Reader): number + if r:peek(7) == "BLENDER" then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function BlendFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Blend.File?, Err.Err?) + return Blend.open(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes }) +end + +function BlendFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local f, err = BlendFormat.open(r, opts) + if not f then + return nil, err + end + local ok, scene, msg = pcall(Read.scene, f, opts) + if not ok then + return nil, Err.from(tostring(scene)) + end + if not scene then + return nil, Err.from(msg or "bad file") + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +BlendFormat.evaluate = Anim.evaluate +BlendFormat.curves = Anim.curves + +return BlendFormat diff --git a/tests/model/blend.luau b/tests/model/blend.luau new file mode 100644 index 0000000..779435e --- /dev/null +++ b/tests/model/blend.luau @@ -0,0 +1,605 @@ +-- model/blend tests: scenes saved by Blender 2.79, 2.93, 3.5, 4.1 and 5.x (plain, gzip, zstd; the 2.79 legacy mesh +-- format) against the current Blender's own values for the same files (world matrices, mesh counts, bounds, UV / colour +-- sums, corner normals, weights, shape keys, f-curve values, posed matrices per frame, skinned positions) and its +-- glTF exporter (materials, cameras, lights, skins, triangle counts). Fixtures: tools/fixtures/blend.py. +local T = require("@tests/T") +local F = require("@rosetta") +local B = require("@rosetta/model/blend") +local Blend = require("@rosetta/containers/Blend") +local Bytes = require("@rosetta/core/Bytes") +local Err = require("@rosetta/core/Err") +local Types = require("@rosetta/Types") +local Mat4 = require("@rosetta/codecs/model/Mat4") +local Sampler = require("@rosetta/codecs/model/Sampler") +local Versions = require("@tests/gen/blend_versions") +local Files = require("@tests/gen/blend_files") +local Sets = { + ["279"] = require("@tests/gen/blend_279"), + ["293"] = require("@tests/gen/blend_293"), + ["35"] = require("@tests/gen/blend_35"), + ["41"] = require("@tests/gen/blend_41"), + cur = require("@tests/gen/blend_cur"), +} + +local t = T.suite("blend") +local Scene = Types.Scene + +t:eq(B.name, "blend", "name") +t:eq(B.category, "model", "category") +t:check(B.caps.decode and not B.caps.encode, "read only") +t:eq(#Versions, 5, "every Blender version made its files (" .. table.concat(Versions, " ") .. ")") + +local function decode(data: string, opts: any?): (any, any) + return B.decode(Bytes.reader(buffer.fromstring(data)), opts) +end + +local function near(a: number, b: number, eps: number): boolean + return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b)) +end + +local function nearList(a: { number }?, b: { number }?, eps: number): boolean + if not a or not b or #a ~= #b then + return false + end + for i = 1, #a do + if not near(a[i], b[i], eps) then + return false + end + end + return true +end + +local function fmt(m: { number }?): string + if not m then + return "nil" + end + local s = {} + for i, v in m do + s[i] = string.format("%.4f", v) + end + return table.concat(s, " ") +end + +-- world matrices of every node, with an optional pose ({ [node] = { translation, rotation, scale, weights } }) +local function worlds(scene: any, pose: any?): { [number]: { number } } + local out = {} + local function walk(i: number, parent: { number }) + local n = scene.nodes[i] + local p = pose and pose[i] + local m + if p then + local base = if n.matrix then { Mat4.decompose(n.matrix) } else { n.translation, n.rotation, n.scale } + m = Mat4.compose(p.translation or base[1], p.rotation or base[2], p.scale or base[3]) + else + m = Scene.nodeMatrix(n) + end + local w = Scene.mul(parent, m) + out[i] = w + for _, c in n.children do + walk(c, w) + end + end + for _, r in scene.roots do + walk(r, Mat4.identity()) + end + return out +end + +local function byName(scene: any): ({ [string]: number }, { [string]: number }) + local objects, bones = {}, {} + for i, n in scene.nodes do + local e = n.extras and n.extras.blend + if e and e.bone then + bones[n.name] = i + elseif e and e.type then + objects[n.name] = i + end + end + return objects, bones +end + +local function read(acc: any): (number, number) -> number + return assert(Scene.reader(acc)) +end + +-- the corners of the polygons decode in Blender's loop order: { prim, vertex } per corner +local function corners(mesh: any, facemats: { number }, faceSizes: { number }?): { { any } }? + local slots = {} + local cursor = {} + for _, p in mesh.primitives do + table.insert(slots, p) + end + local used = {} + for _, m in facemats do + used[m] = true + end + local order = {} + for m in used do + table.insert(order, m) + end + table.sort(order) + local primOf = {} + for k, m in order do + primOf[m] = slots[k] + end + local out = {} + for fi, m in facemats do + local p = primOf[m] + if not p or not p.faces then + return nil + end + local c = cursor[p] or { face = 0, at = 0 } + cursor[p] = c + local size = buffer.readu32(p.faces.data, c.face * 4) + if faceSizes and faceSizes[fi] ~= size then + return nil + end + for k = 0, size - 1 do + table.insert(out, { p, buffer.readu32(p.indices.data, (c.at + k) * 4) }) + end + c.face += 1 + c.at += size + end + return out +end + +local checked = { worlds = 0, meshes = 0, normals = 0, weights = 0, shapes = 0, frames = 0, skinned = 0, curves = 0, materials = 0, cameras = 0, lights = 0 } +local samples = {} + +for _, tag in { "279", "293", "35", "41", "cur" } do + for _, c in Sets[tag] do + local ref = c.ref + local label = c.name + local scene, err = decode(c.data, { files = Files }) + t:check(scene, label .. ": decode: " .. tostring(err)) + if not scene then + continue + end + if #c.data < 500000 and #samples < 2 then + table.insert(samples, c.data) + end + local src = scene.meta.source + t:eq(src.format, "blend", label .. ": meta.source.format") + t:eq(scene.meta.up, "z", label .. ": z up") + if string.find(label, "_z%.blend$") then + t:eq(src.compression, if src.version < 300 then "gzip" else "zstd", label .. ": compression") + end + local objects, bones = byName(scene) + local W = worlds(scene) + -- objects: world matrices at the saved frame + for _, o in ref.objects do + local i = objects[o.name] + t:check(i, label .. ": object " .. o.name) + if i then + t:check(nearList(W[i], o.world, 1e-4), label .. ": " .. o.name .. " world\n got " .. fmt(W[i]) .. "\n want " .. fmt(o.world)) + checked.worlds += 1 + end + end + -- meshes + local polyScene = decode(c.data, { triangulate = false }) + local polyObjects = polyScene and byName(polyScene) + for _, o in ref.objects do + local mi = o.mesh + local i = objects[o.name] + if not mi or not i then + continue + end + local node = scene.nodes[i] + local mesh = scene.meshes[node.mesh] + t:check(mesh, label .. ": " .. o.name .. " has a mesh") + if not mesh then + continue + end + local e = mesh.extras.blend + t:eq(e.vertices, mi.vertices, label .. ": " .. o.name .. " vertices") + local tris = 0 + local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge } + for _, p in mesh.primitives do + tris += p.indices.count // 3 + local P = read(p.attributes.POSITION) + for v = 0, p.attributes.POSITION.count - 1 do + for k = 1, 3 do + lo[k] = math.min(lo[k], P(v, k - 1)) + hi[k] = math.max(hi[k], P(v, k - 1)) + end + end + end + t:eq(tris, mi.triangles, label .. ": " .. o.name .. " triangles") + if e.generation == "mface" then + -- the 2.7x legacy save drops n-gons, leaving their vertices loose: inside the bounds + local inside = true + for k = 1, 3 do + inside = inside and lo[k] >= mi.min[k] - 1e-5 and hi[k] <= mi.max[k] + 1e-5 + end + t:check(inside, label .. ": " .. o.name .. " bounds") + else + t:check(nearList(lo, mi.min, 1e-5) and nearList(hi, mi.max, 1e-5), label .. ": " .. o.name .. " bounds") + end + t:eq(e.faces, mi.faces, label .. ": " .. o.name .. " faces") + t:eq(e.corners, mi.corners, label .. ": " .. o.name .. " corners") + t:eq(#mesh.primitives, (function() + local u, n = {}, 0 + for _, m in mi.facemats do + if not u[m] then + u[m] = true + n += 1 + end + end + return n + end)(), label .. ": " .. o.name .. " one primitive per used slot") + checked.meshes += 1 + -- corner level (the polygons decode, in Blender's loop order) + local pm = polyScene and polyScene.meshes[polyScene.nodes[polyObjects[o.name]].mesh] + local cs = pm and corners(pm, mi.facemats) + t:check(cs and #cs == mi.corners, label .. ": " .. o.name .. " corners in loop order") + if not cs then + continue + end + for k, uv in mi.uvs do + local su, sv = 0, 0 + for _, cv in cs do + local acc = cv[1].attributes["TEXCOORD_" .. (k - 1)] + if acc then + local get = read(acc) + su += get(cv[2], 0) + sv += 1 - get(cv[2], 1) + end + end + t:check(near(su, uv.sum[1], 1e-4) and near(sv, uv.sum[2], 1e-4), label .. ": " .. o.name .. " uv " .. uv.name .. " sums " .. su .. " " .. sv) + end + for _, col in mi.colors do + local s = { 0, 0, 0, 0 } + local found = false + for _, cv in cs do + for name, acc in cv[1].attributes do + if string.sub(name, 1, 6) == "COLOR_" and acc.name == col.name then + found = true + local get = read(acc) + for k = 1, 4 do + s[k] += get(cv[2], k - 1) + end + end + end + end + t:check(found and nearList(s, col.cornerSum, 1e-3), label .. ": " .. o.name .. " colour " .. col.name .. " " .. fmt(s) .. " / " .. fmt(col.cornerSum)) + end + if mi.normals then + local worst = 0 + for ci, cv in cs do + local get = read(cv[1].attributes.NORMAL) + local want = mi.normals[ci] + for k = 1, 3 do + worst = math.max(worst, math.abs(get(cv[2], k - 1) - want[k])) + end + end + t:check(worst < (if mi.custom then 2e-3 else 1e-4), label .. ": " .. o.name .. " corner normals (worst " .. string.format("%.2g", worst) .. (if mi.custom then ", custom" else "") .. ")") + checked.normals += 1 + end + -- deform weights: the deform bones' groups, top 4 normalized + local arm = nil + for _, a in ref.armatures do + arm = a + end + if mi.weights and arm and node.skin then + local deform = {} + for _, b in arm do + deform[b.name] = b.deform + end + local skin = scene.skins[node.skin] + local jointOf = {} + for j, n in skin.joints do + jointOf[scene.nodes[n].name] = j - 1 + end + local bad = 0 + for ci, cv in cs do + local list = {} + for _, g in mi.weights[mi.cornerVerts[ci] + 1] do + if deform[g[1]] and g[2] > 0 then + table.insert(list, { jointOf[g[1]], g[2] }) + end + end + table.sort(list, function(a, b) + return a[2] > b[2] + end) + local sum = 0 + for k = 1, math.min(4, #list) do + sum += list[k][2] + end + local J, Wt = read(cv[1].attributes.JOINTS_0), read(cv[1].attributes.WEIGHTS_0) + for k = 1, math.min(4, #list) do + local ok = false + for q = 0, 3 do + if J(cv[2], q) == list[k][1] and near(Wt(cv[2], q), list[k][2] / sum, 1e-5) then + ok = true + end + end + if not ok then + bad += 1 + end + end + end + t:eq(bad, 0, label .. ": " .. o.name .. " joints / weights per corner") + checked.weights += 1 + end + if mi.shapes then + local refIndex = 1 + for k, s in mi.shapes do + if s.name == mi.reference then + refIndex = k + end + end + t:eq(#(mesh.weights or {}), #mi.shapes - 1, label .. ": " .. o.name .. " morph weights") + local ti = 0 + local worst = 0 + for k, s in mi.shapes do + if k ~= refIndex then + ti += 1 + t:check(near(mesh.weights[ti], s.value, 1e-6), label .. ": " .. o.name .. " " .. s.name .. " weight") + for ci, cv in cs do + local tgt = cv[1].targets and cv[1].targets[ti] + local get = tgt and read(tgt.POSITION) + local v = mi.cornerVerts[ci] + for q = 1, 3 do + local want = s.co[v * 3 + q] - mi.shapes[refIndex].co[v * 3 + q] + worst = math.max(worst, if get then math.abs(get(cv[2], q - 1) - want) else math.huge) + end + end + end + end + t:check(worst < 1e-5, label .. ": " .. o.name .. " shape key deltas (worst " .. worst .. ")") + checked.shapes += 1 + end + end + -- materials against the glTF exporter (Principled) or the legacy colour + local gl = ref.gltf or {} + local glMats = {} + for _, m in gl.materials or {} do + glMats[m.name] = m + end + for _, m in scene.materials do + local g = glMats[m.name] + if m.extras.blend.principled and g then + local pbr = g.pbrMetallicRoughness or {} + t:check(nearList(m.baseColor, pbr.baseColorFactor or { 1, 1, 1, 1 }, 1e-5), label .. ": " .. m.name .. " base colour " .. fmt(m.baseColor)) + t:check(near(m.metallic, pbr.metallicFactor or 1, 1e-5) and near(m.roughness, pbr.roughnessFactor or 1, 1e-5), label .. ": " .. m.name .. " metallic / roughness") + t:check(nearList(m.emissive, g.emissiveFactor or { 0, 0, 0 }, 1e-5), label .. ": " .. m.name .. " emissive " .. fmt(m.emissive)) + local ges = g.extensions and g.extensions.KHR_materials_emissive_strength + local es = m.extensions and m.extensions.KHR_materials_emissive_strength + t:check(near(es and es.emissiveStrength or 1, ges and ges.emissiveStrength or 1, 1e-5), label .. ": " .. m.name .. " emissive strength") + t:eq(string.upper(m.alphaMode), g.alphaMode or "OPAQUE", label .. ": " .. m.name .. " alpha mode") + t:eq(m.baseColorTexture ~= nil, pbr.baseColorTexture ~= nil, label .. ": " .. m.name .. " base colour texture") + t:eq(m.emissiveTexture ~= nil, g.emissiveTexture ~= nil, label .. ": " .. m.name .. " emissive texture") + t:eq(m.normalTexture ~= nil, g.normalTexture ~= nil, label .. ": " .. m.name .. " normal texture") + if g.normalTexture and m.normalTexture then + t:check(near(m.normalTexture.scale, g.normalTexture.scale or 1, 1e-5), label .. ": " .. m.name .. " normal scale") + end + checked.materials += 1 + elseif not m.extras.blend.principled then + for _, rm in ref.materials do + if rm.name == m.name then + t:check(nearList({ m.baseColor[1], m.baseColor[2], m.baseColor[3] }, { rm.diffuse[1], rm.diffuse[2], rm.diffuse[3] }, 1e-5), label .. ": " .. m.name .. " legacy colour") + checked.materials += 1 + end + end + end + end + -- images: packed bytes, external uris (with the bytes from opts.files) + for _, im in ref.images do + local tex = nil + for _, x in scene.textures do + if x.name == im.name then + tex = x + end + end + if im.packed > 0 then + t:check(tex and tex.data and buffer.len(tex.data) == im.packed and tex.mime == "image/png", label .. ": packed image " .. im.name) + elseif tex then + t:eq(tex.uri, "outside.png", label .. ": external image uri") + t:check(tex.data and buffer.len(tex.data) == #Files["outside.png"], label .. ": external image bytes through opts.files") + end + end + -- cameras and lights against the glTF exporter + for _, gc in gl.cameras or {} do + local cam = nil + for _, x in scene.cameras do + if x.name == gc.name then + cam = x + end + end + t:check(cam, label .. ": camera " .. gc.name) + if cam then + if gc.type == "perspective" then + t:check(cam.type == "perspective" and near(cam.yfov, gc.perspective.yfov, 1e-5) and near(cam.znear, gc.perspective.znear, 1e-5) and near(cam.zfar, gc.perspective.zfar, 1e-5), label .. ": perspective " .. gc.name) + else + t:check(cam.type == "orthographic" and near(cam.xmag, gc.orthographic.xmag, 1e-5) and near(cam.ymag, gc.orthographic.ymag, 1e-5), label .. ": orthographic " .. gc.name) + end + checked.cameras += 1 + end + end + local glLights = gl.extensions and gl.extensions.KHR_lights_punctual and gl.extensions.KHR_lights_punctual.lights or {} + t:eq(#scene.lights, #glLights, label .. ": lights (the area light is skipped)") + for _, gli in glLights do + local l = nil + for _, x in scene.lights do + if x.name == gli.name then + l = x + end + end + t:check(l and l.type == gli.type and near(l.intensity, gli.intensity, 1e-5) and nearList(l.color, gli.color, 1e-5), label .. ": light " .. gli.name .. " " .. (l and l.intensity or -1) .. " " .. gli.intensity) + if l and gli.spot then + t:check(near(l.outerCone, gli.spot.outerConeAngle, 1e-5) and near(l.innerCone, gli.spot.innerConeAngle, 1e-5), label .. ": spot cones") + end + checked.lights += 1 + end + -- triangles: the glTF exporter's meshes + if gl.meshes then + local want = 0 + for _, m in gl.meshes do + for _, p in m.primitives do + want += gl.accessors[p.indices + 1].count // 3 + end + end + local got = 0 + for _, m in scene.meshes do + for _, p in m.primitives do + got += p.indices.count // 3 + end + end + t:eq(got, want, label .. ": triangles (glTF exporter)") + end + t:eq(#scene.skins, #(gl.skins or {}), label .. ": skins (glTF exporter)") + for k, s in scene.skins do + t:eq(#s.joints, #gl.skins[k].joints, label .. ": skin joints") + end + -- bones at the saved frame (the rest pose here) + for armName, list in ref.armatures do + local aw = W[objects[armName]] + for _, b in list do + local j = bones[b.name] + t:check(j and nearList(W[j], Scene.mul(aw, b["local"]), 1e-4), label .. ": bone " .. b.name) + end + end + -- f-curves through the evaluator, at every half frame (bezier, linear, constant, extrapolation) + local file = assert(Blend.open(buffer.fromstring(c.data))) + for _, o in ref.objects do + local refCurves = o.action and ref.actions[o.action] + if refCurves then + local ob = nil + for _, blk in Blend.blocks(file, "OB") do + local v = Blend.struct(file, blk) + if v and v:idName() == o.name then + ob = v + end + end + local curves = B.curves(file, ob and ob:deref("adt", 0, "AnimData")) or {} + t:eq(#curves, #refCurves, label .. ": " .. o.name .. " f-curves") + for _, rc in refCurves do + local cur = nil + for _, x in curves do + if x.path == rc.path and x.index == rc.index then + cur = x + end + end + local worst = 0 + for k, want in rc.values do + local got = if cur then B.evaluate(cur, 1 + 0.5 * (k - 1)) else math.huge + worst = math.max(worst, math.abs(got - want)) + end + t:check(worst < 1e-4, label .. ": " .. o.name .. " " .. rc.path .. "[" .. rc.index .. "] (worst " .. worst .. ")") + checked.curves += 1 + end + end + end + -- the animations sampled at whole frames: posed world matrices, bones, shape key values, skinned positions + if #ref.poses > 0 then + t:check(#scene.animations > 0, label .. ": animations") + local caches = {} + for _, p in ref.poses do + local frame = p.frame + if frame ~= math.floor(frame) or frame > 20 then + continue + end + local time = (frame - src.frameZero) / src.fps + local pose = {} + for ai, a in scene.animations do + caches[ai] = caches[ai] or {} + for node, v in Sampler.pose(scene, a, time, caches[ai]) do + pose[node] = pose[node] or {} + for k, x in v do + pose[node][k] = x + end + end + end + local PW = worlds(scene, pose) + for name, want in p.objects do + local i = objects[name] + t:check(i and nearList(PW[i], want, 1e-3), label .. ": frame " .. frame .. " " .. name .. "\n got " .. fmt(i and PW[i]) .. "\n want " .. fmt(want)) + end + for key, want in p.bones do + local j = bones[string.match(key, "/(.+)$")] + t:check(j and nearList(PW[j], want, 1e-3), label .. ": frame " .. frame .. " bone " .. key) + end + for name, values in p.shapes do + local i = objects[name] + local w = pose[i] and pose[i].weights or scene.nodes[i].weights + local want = table.move(values, 2, #values, 1, {}) + t:check(nearList(w, want, 1e-3), label .. ": frame " .. frame .. " " .. name .. " shape values " .. fmt(w) .. " / " .. fmt(want)) + end + for name, want in p.skinned or {} do + -- morph, then skin: sum of w * jointWorld * inverseBind * position + local i = objects[name] + local node = polyScene.nodes[polyObjects[name]] + local mi = nil + for _, o in ref.objects do + if o.name == name then + mi = o.mesh + end + end + local pm = polyScene.meshes[node.mesh] + local cs = corners(pm, mi.facemats) + local skin = scene.skins[scene.nodes[i].skin] + local IB = read(skin.inverseBindMatrices) + local weights = pose[i] and pose[i].weights or scene.nodes[i].weights or {} + local worst = 0 + for ci, cv in cs do + local P = read(cv[1].attributes.POSITION) + local x, y, z = P(cv[2], 0), P(cv[2], 1), P(cv[2], 2) + for ti, tg in cv[1].targets or {} do + local D = read(tg.POSITION) + x += D(cv[2], 0) * (weights[ti] or 0) + y += D(cv[2], 1) * (weights[ti] or 0) + z += D(cv[2], 2) * (weights[ti] or 0) + end + local J, Wt = read(cv[1].attributes.JOINTS_0), read(cv[1].attributes.WEIGHTS_0) + local ox, oy, oz = 0, 0, 0 + for q = 0, 3 do + local w = Wt(cv[2], q) + if w > 0 then + local j = J(cv[2], q) + local ib = {} + for k = 0, 15 do + ib[k + 1] = IB(j, k) + end + local m = Scene.mul(PW[skin.joints[j + 1]], ib) + local px, py, pz = Mat4.point(m, x, y, z) + ox += w * px + oy += w * py + oz += w * pz + end + end + local v = mi.cornerVerts[ci] + worst = math.max(worst, math.abs(ox - want[v * 3 + 1]), math.abs(oy - want[v * 3 + 2]), math.abs(oz - want[v * 3 + 3])) + end + t:check(worst < 1e-3, label .. ": frame " .. frame .. " " .. name .. " skinned positions (worst " .. worst .. ")") + checked.skinned += 1 + end + checked.frames += 1 + end + end + end +end +t:note("checked: %d world matrices, %d meshes, %d corner normal sets, %d weight sets, %d shape key sets, %d f-curves, %d posed frames, %d skinned frames, %d materials, %d cameras, %d lights", + checked.worlds, checked.meshes, checked.normals, checked.weights, checked.shapes, checked.curves, checked.frames, checked.skinned, checked.materials, checked.cameras, checked.lights) + +-- the api: by extension and magic, compressed files included +local cur = Sets.cur[1] +if cur then + t:eq(F.detect(buffer.fromstring(cur.data)), "blend", "F.detect") + local s = F.load(buffer.fromstring(cur.data)) + t:check(s and s.kind == "scene", "F.load") +end + +-- errors +local function code(data: string): string? + local s, e = decode(data) + return if s then nil else e.code +end +t:eq(code("BLENDER"), Err.TRUNCATED, "a 7-byte file is truncated") +t:eq(code("BLENDER-v279REND"), Err.TRUNCATED, "a truncated block header") +t:eq(code("BLENDERxv279" .. string.rep("\0", 24)), Err.CORRUPT, "bad pointer size") +t:eq(code("BLENDER-v279ENDB" .. string.rep("\0", 20)), Err.CORRUPT, "no DNA1 block") + +t:fuzz("decode", function(b: buffer) + return B.decode(Bytes.reader(b)) +end, samples, { mutations = 24 }) +t:done() diff --git a/tools/fixtures/_blend_make.py b/tools/fixtures/_blend_make.py new file mode 100644 index 0000000..37e5bc2 --- /dev/null +++ b/tools/fixtures/_blend_make.py @@ -0,0 +1,390 @@ +# tools/fixtures/_blend_make: run by tools/fixtures/blend.py inside Blender 2.79 .. 5.x (blender -b --python -- +# ): builds the test scenes with whatever API the running version has and saves them as .blend files: +# scene_.blend collections, transforms (euler / quaternion / delta), parenting with a parent inverse, +# meshes (quads, an n-gon, smooth / flat), two UV maps, colour attributes, materials (Principled +# + packed and external images, a legacy one), cameras, lights, modifiers +# rig_.blend armature with rolls, a skinned mesh (vertex groups, 5 influences on some vertices), shape +# keys, actions on bones / objects / shape keys (bezier, linear, constant), a bone parent +# scene__z.blend scene_ saved compressed (gzip before 3.0, zstd after) +# compat_.blend 2.7x only: the "legacy mesh format" save (MFace tessellated faces) +import bpy, sys, os, math + +out = sys.argv[sys.argv.index("--") + 1] +V = bpy.app.version +TAG = "%d%d" % (V[0], V[1]) +OLD = V < (2, 80) + + +def reset(): + bpy.ops.wm.read_factory_settings(use_empty=True) if not OLD else bpy.ops.wm.read_factory_settings() + if OLD: + for o in list(bpy.data.objects): + bpy.data.objects.remove(o, do_unlink=True) + sc = bpy.context.scene + sc.render.fps = 24 + if OLD: + sc.render.engine = "CYCLES" + sc.frame_start, sc.frame_end = 1, 20 + + +def link(obj, coll=None): + sc = bpy.context.scene + if OLD: + sc.objects.link(obj) + else: + (coll or sc.collection).objects.link(obj) + return obj + + +def mesh(name, verts, faces, smooth=False): + me = bpy.data.meshes.new(name) + me.from_pydata(verts, [], faces) + me.update() + for p in me.polygons: + p.use_smooth = smooth + return me + + +def uv(me, name, f): + if OLD: + me.uv_textures.new(name) + layer = me.uv_layers[name] + else: + layer = me.uv_layers.new(name=name) + for i, d in enumerate(layer.data): + d.uv = f(i) + + +def byte_colors(me, name): + if V >= (3, 2): + a = me.color_attributes.new(name, "BYTE_COLOR", "CORNER") + data = a.data + else: + data = me.vertex_colors.new(name=name).data + for i, d in enumerate(data): + c = ((i % 3) / 2, (i % 5) / 4, (i % 7) / 6) + d.color = c + (1.0,) if len(d.color) == 4 else c + + +def image(name, w, h, f, pack=True, path=None): + img = bpy.data.images.new(name, w, h) + px = [] + for y in range(h): + for x in range(w): + px.extend(f(x, y)) + img.pixels = px + if path: + img.filepath_raw = path + img.file_format = "PNG" + img.save() + img.filepath = "//" + os.path.basename(path) + if pack: + if OLD: + img.pack(as_png=True) + else: + img.pack() + return img + + +def socket(node, *names): + for n in names: + if n in node.inputs: + return node.inputs[n] + return None + + +def principled(mat, base, metallic, rough, emission=None, strength=1.0, alpha=1.0): + mat.use_nodes = True + nt = mat.node_tree + bsdf = None + for n in nt.nodes: + if n.bl_idname == "ShaderNodeBsdfPrincipled": + bsdf = n + if bsdf is None: + for n in list(nt.nodes): + if n.bl_idname != "ShaderNodeOutputMaterial": + nt.nodes.remove(n) + bsdf = nt.nodes.new("ShaderNodeBsdfPrincipled") + outs = [n for n in nt.nodes if n.bl_idname == "ShaderNodeOutputMaterial"] + outn = outs[0] if outs else nt.nodes.new("ShaderNodeOutputMaterial") + nt.links.new(bsdf.outputs[0], outn.inputs["Surface"]) + socket(bsdf, "Base Color").default_value = base + socket(bsdf, "Metallic").default_value = metallic + socket(bsdf, "Roughness").default_value = rough + e = socket(bsdf, "Emission Color", "Emission") + if emission and e: + e.default_value = emission + (1.0,) + s = socket(bsdf, "Emission Strength") + if s: + s.default_value = strength + a = socket(bsdf, "Alpha") + if a: + a.default_value = alpha + return bsdf + + +def tex(mat, img, to, normal=False): + nt = mat.node_tree + t = nt.nodes.new("ShaderNodeTexImage") + t.image = img + if normal: + if not OLD: + img.colorspace_settings.name = "Non-Color" + nm = nt.nodes.new("ShaderNodeNormalMap") + nm.inputs["Strength"].default_value = 0.7 + nt.links.new(t.outputs["Color"], nm.inputs["Color"]) + nt.links.new(nm.outputs["Normal"], to) + else: + nt.links.new(t.outputs["Color"], to) + + +def camera(name, ortho=False): + cam = bpy.data.cameras.new(name) + if ortho: + cam.type = "ORTHO" + cam.ortho_scale = 7.0 + else: + cam.lens = 35.0 + cam.sensor_width = 36.0 + cam.clip_start, cam.clip_end = 0.1, 100.0 + return cam + + +def light(name, kind): + data = (bpy.data.lamps if OLD else bpy.data.lights).new(name, kind) + data.color = (1.0, 0.5, 0.25) + data.energy = {"POINT": 1000.0, "SUN": 3.0, "SPOT": 500.0, "AREA": 200.0}[kind] + if kind == "SPOT": + data.spot_size = 0.8 + data.spot_blend = 0.2 + return data + + +def save(path, compress=False, compat=False): + kw = {"filepath": path, "compress": compress} + if compat: + kw["use_mesh_compat"] = True + bpy.ops.wm.save_as_mainfile(**kw) + + +def update(): + if OLD: + bpy.context.scene.update() + else: + bpy.context.view_layer.update() + + +def scene_file(): + reset() + sc = bpy.context.scene + props = inner = None + if not OLD: + props = bpy.data.collections.new("Props") + sc.collection.children.link(props) + inner = bpy.data.collections.new("Inner") + props.children.link(inner) + cube_v = [(-1, -1, -1), (1, -1, -1), (1, 1, -1), (-1, 1, -1), (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1)] + cube_f = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)] + me = mesh("BoxMesh", cube_v, cube_f) + uv(me, "UVMap", lambda i: ((i % 4) / 4 + 0.1, (i // 4) / 6)) + uv(me, "Second", lambda i: (1 - (i % 3) / 3, (i % 2) * 0.5)) + byte_colors(me, "Col") + if V >= (3, 2): + pc = me.color_attributes.new("PCol", "FLOAT_COLOR", "POINT") + for i, d in enumerate(pc.data): + d.color = (i / 8, 1 - i / 8, 0.5 + i / 16, 1.0) + checker = image("checker", 8, 8, lambda x, y: [float((x + y) % 2), 0.5, 0.25, 1.0]) + bumps = image("bumps", 4, 4, lambda x, y: [0.5 + x / 8, 0.5 + y / 8, 1.0, 1.0]) + outside = image("outside", 2, 2, lambda x, y: [1.0, 0.0, x * 1.0, 1.0], pack=False, + path=os.path.join(out, "outside.png")) + red = bpy.data.materials.new("Red") + bsdf = principled(red, (0.8, 0.1, 0.1, 1.0), 0.3, 0.4, (0.2, 0.3, 0.4), 2.0, 0.9) + tex(red, checker, socket(bsdf, "Base Color")) + tex(red, bumps, socket(bsdf, "Normal"), normal=True) + blue = bpy.data.materials.new("Blue") + blue.diffuse_color = (0.1, 0.2, 0.9) if OLD else (0.1, 0.2, 0.9, 1.0) + if not OLD: + blue.metallic = 0.25 + blue.roughness = 0.6 + if V >= (5, 0): + blue.use_nodes = False + me.materials.append(red) + me.materials.append(blue) + for i, p in enumerate(me.polygons): + p.material_index = i % 2 + box = link(bpy.data.objects.new("Box", me), props) + box.location = (1, 2, 3) + box.rotation_euler = (0.3, 0.2, 0.1) + box.scale = (1, 2, 0.5) + box.modifiers.new("Subdiv", "SUBSURF") + # triangle, quad, convex pentagon, concave hexagon + sv = [(0, 0, 0), (1, 0, 0), (0, 1, 0), (2, 0, 0), (3, 0, 0), (3, 1, 0), (2, 1, 0), + (4, 0, 0), (5, 0, 0), (5.5, 0.8, 0), (4.5, 1.5, 0), (3.6, 0.8, 0), + (6, 0, 0), (8, 0, 0), (8, 2, 0), (7, 0.5, 0), (6, 2, 0), (6.5, 1, 0.2)] + sf = [(0, 1, 2), (3, 4, 5, 6), (7, 8, 9, 10, 11), (12, 13, 14, 15, 16, 17)] + shape_me = mesh("ShapeMesh", sv, sf, smooth=True) + glow = bpy.data.materials.new("Glow") + gb = principled(glow, (0.2, 0.9, 0.2, 1.0), 0.0, 0.8, (1.0, 0.8, 0.1), 5.0) + tex(glow, outside, socket(gb, "Emission Color", "Emission") or socket(gb, "Subsurface Color")) + shape_me.materials.append(glow) + shape = link(bpy.data.objects.new("Shape", shape_me), props) + shape.location = (-4, 0, 1) + shape.modifiers.new("Mirror", "MIRROR") + ball_me = mesh("BallMesh", [(math.cos(a * math.pi / 3) * 0.5, math.sin(a * math.pi / 3) * 0.5, z) + for z in (-0.4, 0.4) for a in range(6)], + [(0, 1, 7, 6), (1, 2, 8, 7), (2, 3, 9, 8), (3, 4, 10, 9), (4, 5, 11, 10), (5, 0, 6, 11), + (5, 4, 3, 2, 1, 0), (6, 7, 8, 9, 10, 11)], smooth=True) + ball = link(bpy.data.objects.new("Ball", ball_me), inner) + ball.location = (-3, 1, 0.5) + ball.rotation_euler = (0, 0, 0.7) + update() + ball.parent = box + ball.matrix_parent_inverse = box.matrix_world.inverted() + pivot = link(bpy.data.objects.new("Pivot", None), props) + pivot.location = (0, -3, 1) + pivot.rotation_mode = "QUATERNION" + q = (0.9, 0.1, 0.3, 0.2) + n = math.sqrt(sum(c * c for c in q)) + pivot.rotation_quaternion = tuple(c / n for c in q) + leaf_me = mesh("LeafMesh", [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)], [(0, 1, 2, 3)]) + leaf_me.materials.append(glow) + leaf = link(bpy.data.objects.new("Leaf", leaf_me), props) + leaf.parent = pivot + leaf.location = (0.5, 0.25, 0) + leaf.rotation_mode = "ZXY" + leaf.rotation_euler = (0.4, -0.3, 1.1) + leaf.scale = (1.5, 1, 1) + leaf.delta_location = (0, 0, 0.5) + leaf.delta_rotation_euler = (0, 0.2, 0) + leaf.delta_scale = (1, 1, 2) + # smooth grid with custom normals + gv = [(x, y, 0.1 * x * y) for y in range(3) for x in range(3)] + gf = [(0, 1, 4, 3), (1, 2, 5, 4), (3, 4, 7, 6), (4, 5, 8, 7)] + grid_me = mesh("BentMesh", gv, gf, smooth=True) + if V < (4, 1): + grid_me.use_auto_smooth = True + grid_me.normals_split_custom_set_from_vertices([(0.3 * (i % 3 - 1), 0.2 * (i // 3 - 1), 1.0) for i in range(9)]) + bent = link(bpy.data.objects.new("Bent", grid_me), props) + bent.location = (0, 4, 0) + cp = link(bpy.data.objects.new("CamP", camera("CamP"))) + cp.location = (7, -7, 5) + cp.rotation_euler = (1.1, 0, 0.8) + co = link(bpy.data.objects.new("CamO", camera("CamO", True))) + co.location = (0, 0, 10) + for kind in ("POINT", "SUN", "SPOT", "AREA"): + lo = link(bpy.data.objects.new("L" + kind.lower(), light("L" + kind.lower(), kind))) + lo.location = ({"POINT": 4, "SUN": 0, "SPOT": -4, "AREA": 2}[kind], 1, 6) + lo.rotation_euler = (0.5, 0.1, 0) + sc.frame_set(1) + update() + save(os.path.join(out, "scene_%s.blend" % TAG)) + save(os.path.join(out, "scene_%s_z.blend" % TAG), compress=True) + + +def rig_file(): + reset() + sc = bpy.context.scene + arm_data = bpy.data.armatures.new("RigData") + rig = link(bpy.data.objects.new("Rig", arm_data)) + rig.location = (0, 0, 0.5) + rig.rotation_euler = (0, 0, 0.2) + if OLD: + sc.objects.active = rig + else: + bpy.context.view_layer.objects.active = rig + bpy.ops.object.mode_set(mode="EDIT") + eb = arm_data.edit_bones + root = eb.new("root") + root.head, root.tail, root.roll = (0, 0, 0), (0, 0, 1), 0.0 + mid = eb.new("mid") + mid.head, mid.tail, mid.roll, mid.parent, mid.use_connect = (0, 0, 1), (0, 0.5, 2), 0.3, root, True + tip = eb.new("tip") + tip.head, tip.tail, tip.roll, tip.parent, tip.use_connect = (0, 0.5, 2), (0.3, 0.5, 2.8), -0.5, mid, True + aux = eb.new("aux") + aux.head, aux.tail, aux.roll, aux.parent = (0.5, 0, 0.5), (1, 0, 0.5), 0.0, root + nodef = eb.new("nodef") + nodef.head, nodef.tail, nodef.parent, nodef.use_deform = (-0.5, 0, 0.5), (-1, 0, 0.7), root, False + bpy.ops.object.mode_set(mode="OBJECT") + ring = [(math.cos(a * math.pi / 4) * 0.3, math.sin(a * math.pi / 4) * 0.3) for a in range(8)] + bv = [(x, y + (0.25 if z == 2 else 0), z) for z in (0, 1, 2) for x, y in ring] + bf = [(r * 8 + a, r * 8 + (a + 1) % 8, (r + 1) * 8 + (a + 1) % 8, (r + 1) * 8 + a) for r in range(2) for a in range(8)] + body_me = mesh("BodyMesh", bv, bf, smooth=True) + body = link(bpy.data.objects.new("Body", body_me)) + body.parent = rig + body.location = (0, 0, 0) + mod = body.modifiers.new("Armature", "ARMATURE") + mod.object = rig + groups = {n: body.vertex_groups.new(name=n) for n in ("root", "mid", "tip", "aux", "nodef", "extra")} + for i in range(24): + z = i // 8 + groups["root"].add([i], max(0.0, 1.0 - z * 0.6), "REPLACE") + groups["mid"].add([i], 0.3 + 0.2 * (z == 1), "REPLACE") + if z == 2: + groups["tip"].add([i], 0.9, "REPLACE") + if i % 3 == 0: + groups["aux"].add([i], 0.05 + 0.01 * i, "REPLACE") + groups["nodef"].add([i], 0.7, "REPLACE") + groups["extra"].add([i], 0.15, "REPLACE") + body.shape_key_add(name="Basis") + fat = body.shape_key_add(name="Fat") + for i, p in enumerate(fat.data): + p.co = (p.co[0] * 1.5, p.co[1] * 1.5, p.co[2]) + thin = body.shape_key_add(name="Thin") + for i, p in enumerate(thin.data): + p.co = (p.co[0] * 0.5, p.co[1] * 0.5, p.co[2] + 0.1) + thin.value = 0.25 + key = body_me.shape_keys + for f, v in ((1, 0.0), (10, 1.0), (20, 0.2)): + fat.value = v + fat.keyframe_insert("value", frame=f) + hat_me = mesh("HatMesh", [(-0.2, -0.2, 0), (0.2, -0.2, 0), (0, 0.2, 0), (0, 0, 0.3)], [(0, 1, 2), (0, 1, 3), (1, 2, 3), (2, 0, 3)]) + hat = link(bpy.data.objects.new("Hat", hat_me)) + hat.parent = rig + hat.parent_type = "BONE" + hat.parent_bone = "tip" + hat.location = (0.1, 0.2, 0.0) + pose = rig.pose.bones + pose["aux"].rotation_mode = "XYZ" + keys = ((1, (0, 0, 0), (1, 0, 0, 0), (1, 1, 1), (0, 0, 0)), + (10, (0.2, 0.1, 0), (0.92, 0.3, 0.2, 0.1), (1.2, 1, 1), (0.4, 0, 0.3)), + (20, (0, 0.3, 0.2), (0.8, -0.2, 0.5, 0.2), (0.8, 1.1, 1), (-0.3, 0.5, 0))) + for f, loc, quat, scl, eul in keys: + pose["root"].location = loc + pose["root"].keyframe_insert("location", frame=f) + n = math.sqrt(sum(c * c for c in quat)) + pose["mid"].rotation_quaternion = tuple(c / n for c in quat) + pose["mid"].keyframe_insert("rotation_quaternion", frame=f) + pose["tip"].scale = scl + pose["tip"].keyframe_insert("scale", frame=f) + pose["aux"].rotation_euler = eul + pose["aux"].keyframe_insert("rotation_euler", frame=f) + mover = link(bpy.data.objects.new("Mover", mesh("MoverMesh", [(0, 0, 0), (1, 0, 0), (0, 1, 0)], [(0, 1, 2)]))) + for f, loc, rot, scl in ((1, (3, 0, 0), (0, 0, 0), (1, 1, 1)), (8, (3, 2, 1), (0.5, 0, 1), (2, 1, 1)), + (20, (5, 2, 0), (0, 1, -1), (1, 1, 3))): + mover.location, mover.rotation_euler, mover.scale = loc, rot, scl + mover.keyframe_insert("location", frame=f) + mover.keyframe_insert("rotation_euler", frame=f) + mover.keyframe_insert("scale", frame=f) + rig_action = rig.animation_data.action + mover_action = mover.animation_data.action + for act, rules in ((rig_action, {"location": "LINEAR", "scale": "CONSTANT"}), + (mover_action, {"rotation_euler": "LINEAR", "scale": "CONSTANT"})): + curves = act.fcurves if hasattr(act, "fcurves") else [c for l in act.layers for s in l.strips for b in s.channelbags for c in b.fcurves] + for fc in curves: + for k, ipo in rules.items(): + if fc.data_path.endswith(k): + for kp in fc.keyframe_points: + kp.interpolation = ipo + if fc.data_path == "location" and fc.array_index == 2: + fc.extrapolation = "LINEAR" + sc.frame_set(1) + update() + save(os.path.join(out, "rig_%s.blend" % TAG)) + + +scene_file() +rig_file() +if OLD: + scene_file() + save(os.path.join(out, "compat_%s.blend" % TAG), compat=True) +print("MADE", TAG) diff --git a/tools/fixtures/_blend_ref.py b/tools/fixtures/_blend_ref.py new file mode 100644 index 0000000..fb37763 --- /dev/null +++ b/tools/fixtures/_blend_ref.py @@ -0,0 +1,219 @@ +# tools/fixtures/_blend_ref: run by tools/fixtures/blend.py inside Blender (blender -b --factory-startup --python +# -- ): opens each file (old ones through Blender's versioning) and writes +# /.json with the reference values (object world matrices, mesh counts / bounds / attribute sums / corner normals, +# vertex groups, shape keys, materials, images, cameras, lights, bones, f-curve values, posed world matrices per frame), +# and exports a .glb of each file (Z up, no modifiers) whose JSON part is returned as "gltf". +import bpy, sys, os, json, struct, math + +args = sys.argv[sys.argv.index("--") + 1:] +paths, outdir = json.loads(args[0]), args[1] +V = bpy.app.version + + +def mat(m): + return [m[r][c] for c in range(4) for r in range(4)] # column-major + + +def r6(x): + return round(float(x), 6) + + +def color_attrs(me): + out = [] + attrs = me.color_attributes if hasattr(me, "color_attributes") else [] + for a in attrs: + s = [0.0, 0.0, 0.0, 0.0] + for l in me.loops: + d = a.data[l.index if a.domain == "CORNER" else l.vertex_index] + for k in range(4): + s[k] += d.color[k] + out.append({"name": a.name, "domain": a.domain, "type": a.data_type, "count": len(a.data), "cornerSum": [r6(x) for x in s]}) + return out + + +def mesh_info(ob): + me = ob.data + me.calc_loop_triangles() + vs = [v.co for v in me.vertices] + lo = [min(v[k] for v in vs) for k in range(3)] if vs else [0, 0, 0] + hi = [max(v[k] for v in vs) for k in range(3)] if vs else [0, 0, 0] + info = { + "name": me.name, "vertices": len(me.vertices), "corners": len(me.loops), "faces": len(me.polygons), + "triangles": len(me.loop_triangles), "min": [r6(x) for x in lo], "max": [r6(x) for x in hi], + "possum": [r6(sum(v[k] for v in vs)) for k in range(3)], + "uvs": [], "colors": color_attrs(me), "slots": [s.material.name if s.material else "" for s in ob.material_slots], + "facemats": [p.material_index for p in me.polygons], + "smooth": [1 if p.use_smooth else 0 for p in me.polygons], + } + for layer in me.uv_layers: + su = sv = 0.0 + for d in layer.data: + su += d.uv[0] + sv += d.uv[1] + info["uvs"].append({"name": layer.name, "sum": [r6(su), r6(sv)], "active_render": bool(layer.active_render)}) + if len(me.loops) <= 400: + if hasattr(me, "corner_normals"): + info["normals"] = [[r6(c) for c in n.vector] for n in me.corner_normals] + info["cornerVerts"] = [l.vertex_index for l in me.loops] + info["custom"] = bool(me.has_custom_normals) + groups = {g.index: g.name for g in ob.vertex_groups} + if groups: + info["weights"] = [[[groups.get(g.group, "?"), r6(g.weight)] for g in v.groups] for v in me.vertices] + if me.shape_keys: + k = me.shape_keys + info["shapes"] = [{"name": b.name, "value": r6(b.value), "relative": b.relative_key.name, + "co": [r6(p.co[c]) for p in b.data for c in range(3)]} for b in k.key_blocks] + info["reference"] = k.reference_key.name + info["modifiers"] = [m.type for m in ob.modifiers] + return info + + +def socket_val(s): + if s is None: + return None + v = s.default_value + try: + return [r6(x) for x in v] + except TypeError: + return r6(v) + + +def linked_image(s): + if s is None or not s.is_linked: + return None + n = s.links[0].from_node + if n.bl_idname == "ShaderNodeNormalMap": + return linked_image(n.inputs["Color"]) + if n.bl_idname == "ShaderNodeTexImage" and n.image: + return n.image.name + return "?" + n.bl_idname + + +def material_info(m): + info = {"name": m.name, "diffuse": [r6(x) for x in m.diffuse_color], "metallic": r6(m.metallic), "roughness": r6(m.roughness), + "use_nodes": bool(m.use_nodes), "cull": bool(m.use_backface_culling)} + if m.node_tree: + for n in m.node_tree.nodes: + if n.bl_idname == "ShaderNodeBsdfPrincipled": + ins = n.inputs + g = lambda *names: next((ins[x] for x in names if x in ins), None) + info["principled"] = { + "base": socket_val(g("Base Color")), "metallic": socket_val(g("Metallic")), "roughness": socket_val(g("Roughness")), + "emission": socket_val(g("Emission Color", "Emission")), "strength": socket_val(g("Emission Strength")), + "alpha": socket_val(g("Alpha")), + "baseTex": linked_image(g("Base Color")), "normalTex": linked_image(g("Normal")), + "emissionTex": linked_image(g("Emission Color", "Emission")), + } + if n.bl_idname == "ShaderNodeNormalMap": + info["normalStrength"] = r6(n.inputs["Strength"].default_value) + return info + + +def fcurves(act): + if act is None: + return [] + if hasattr(act, "fcurves") and V < (5, 0): + return list(act.fcurves) + out = [] + for layer in act.layers: + for strip in layer.strips: + for bag in strip.channelbags: + out.extend(bag.fcurves) + return out + + +FRAMES = [1 + 0.5 * i for i in range(43)] # 1 .. 22 (past the last key: extrapolation) + + +def curve_info(act): + out = [] + for fc in fcurves(act): + out.append({"path": fc.data_path, "index": fc.array_index, "extrapolation": fc.extrapolation, + "keys": len(fc.keyframe_points), "values": [r6(fc.evaluate(f)) for f in FRAMES]}) + return out + + +def dump(path): + bpy.ops.wm.open_mainfile(filepath=path) + sc = bpy.context.scene + sc.frame_set(sc.frame_current) + obs = list(sc.objects) + ref = {"version": list(bpy.data.version), "fps": sc.render.fps / sc.render.fps_base, "frameStart": sc.frame_start, + "frameCurrent": sc.frame_current, "resolution": [sc.render.resolution_x, sc.render.resolution_y], + "objects": [], "materials": [], "images": [], "cameras": {}, "lights": {}, "armatures": {}, "actions": {}} + for ob in obs: + o = {"name": ob.name, "type": ob.type, "parent": ob.parent.name if ob.parent else "", "parent_type": ob.parent_type, + "parent_bone": ob.parent_bone, "world": [r6(x) for x in mat(ob.matrix_world)], + "collections": [c.name for c in ob.users_collection]} + if ob.type == "MESH": + o["mesh"] = mesh_info(ob) + if ob.animation_data and ob.animation_data.action: + a = ob.animation_data.action + ref["actions"][a.name] = curve_info(a) + o["action"] = a.name + if ob.type == "MESH" and ob.data.shape_keys and ob.data.shape_keys.animation_data and ob.data.shape_keys.animation_data.action: + a = ob.data.shape_keys.animation_data.action + ref["actions"][a.name] = curve_info(a) + o["shapeAction"] = a.name + ref["objects"].append(o) + if ob.type == "CAMERA": + c = ob.data + ref["cameras"][ob.name] = {"type": c.type, "lens": r6(c.lens), "sensor": [r6(c.sensor_width), r6(c.sensor_height)], + "fit": c.sensor_fit, "ortho": r6(c.ortho_scale), "clip": [r6(c.clip_start), r6(c.clip_end)], + "angle": [r6(c.angle_x), r6(c.angle_y)]} + if ob.type == "LIGHT": + l = ob.data + ref["lights"][ob.name] = {"type": l.type, "color": [r6(x) for x in l.color], "energy": r6(l.energy), + "spot": [r6(l.spot_size), r6(l.spot_blend)] if l.type == "SPOT" else [0, 0]} + if ob.type == "ARMATURE": + ref["armatures"][ob.name] = [{"name": b.name, "parent": b.parent.name if b.parent else "", "deform": b.use_deform, + "local": [r6(x) for x in mat(b.matrix_local)], "length": r6(b.length)} for b in ob.data.bones] + for m in bpy.data.materials: + ref["materials"].append(material_info(m)) + for im in bpy.data.images: + if im.source in ("FILE", "GENERATED") and im.type == "IMAGE": + ref["images"].append({"name": im.name, "filepath": im.filepath, "packed": im.packed_file.size if im.packed_file else 0, + "source": im.source}) + # posed world matrices: objects, pose bones (world), shape key values + poses = [] + if ref["actions"]: + for f in FRAMES: + sc.frame_set(int(math.floor(f)), subframe=f - math.floor(f)) + p = {"frame": f, "objects": {}, "bones": {}, "shapes": {}} + for ob in obs: + p["objects"][ob.name] = [r6(x) for x in mat(ob.matrix_world)] + if ob.type == "ARMATURE": + for pb in ob.pose.bones: + p["bones"][ob.name + "/" + pb.name] = [r6(x) for x in mat(ob.matrix_world @ pb.matrix)] + if ob.type == "MESH" and ob.data.shape_keys: + p["shapes"][ob.name] = [r6(b.value) for b in ob.data.shape_keys.key_blocks] + if ob.type == "MESH" and any(m.type == "ARMATURE" for m in ob.modifiers) and f == math.floor(f): + ev = ob.evaluated_get(bpy.context.evaluated_depsgraph_get()) + em = ev.to_mesh() + w = ob.matrix_world + p.setdefault("skinned", {})[ob.name] = [r6(c) for v in em.vertices for c in (w @ v.co)] + ev.to_mesh_clear() + poses.append(p) + ref["poses"] = poses + # Blender's glTF exporter on the same file (Z up, modifiers not applied) + glb = os.path.join(outdir, os.path.basename(path) + ".glb") + try: + bpy.ops.export_scene.gltf(filepath=glb, export_format="GLB", export_yup=False, export_apply=False, + export_cameras=True, export_lights=True) + with open(glb, "rb") as fh: + data = fh.read() + n = struct.unpack_from(".luau { { name, data, ref } } +# tests/gen/blend_files.luau sibling files the scenes refer to ({ ["outside.png"] = bytes }) +import json, os, shutil, subprocess, tempfile + +INPUTS = ["tools/fixtures/_blend_make.py", "tools/fixtures/_blend_ref.py"] + +OLD = [ + ("279", ["--impure", "--expr", '(import (builtins.fetchTarball "https://github.com/NixOS/nixpkgs/archive/nixos-19.03.tar.gz") {}).blender']), + ("293", ["github:NixOS/nixpkgs/nixos-21.11#blender"]), + ("35", ["github:NixOS/nixpkgs/nixos-23.05#blender"]), + ("41", ["github:NixOS/nixpkgs/nixos-24.05#blender"]), +] + + +def env(): + e = dict(os.environ) + e.pop("LD_LIBRARY_PATH", None) # the host's alsa / pipewire libraries need a newer glibc than old Blenders have + return e + + +def current(): + exe = shutil.which("blender") + return [exe] if exe else ["nix", "shell", "nixpkgs#blender", "-c", "blender"] + + +def run(cmd, timeout=1800): + try: + res = subprocess.run(cmd, capture_output=True, timeout=timeout, env=env()) + return res.returncode == 0, res.stdout.decode("utf-8", "replace") + res.stderr.decode("utf-8", "replace") + except (subprocess.TimeoutExpired, OSError) as e: + return False, str(e) + + +def clean(v): + if isinstance(v, dict): + return {k: clean(x) for k, x in v.items() if x is not None} + if isinstance(v, list): + return [False if x is None else clean(x) for x in v] + return v + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="blendfx") + make = os.path.join(ctx.root, "tools", "fixtures", "_blend_make.py") + ref = os.path.join(ctx.root, "tools", "fixtures", "_blend_ref.py") + made = {} + for tag, inst in OLD + [("cur", None)]: + out = os.path.join(tmp, tag) + os.makedirs(out) + if inst is None: + cmd = current() + else: + cmd = ["nix", "shell"] + inst + ["-c", "blender"] + ok, log = run(cmd + ["-b", "--factory-startup", "--python", make, "--", out]) + files = sorted(f for f in os.listdir(out) if f.endswith(".blend")) + if not ok or not files: + print("blend: Blender %s did not run (skipped): %s" % (tag, log[-400:])) + continue + made[tag] = (out, files) + paths = [os.path.join(out, f) for out, files in made.values() for f in files] + refdir = os.path.join(tmp, "ref") + os.makedirs(refdir) + ok, log = run(current() + ["-b", "--factory-startup", "--python", ref, "--", json.dumps(paths), refdir], timeout=3600) + if not ok: + raise RuntimeError("blend: the reference Blender failed: " + log[-2000:]) + sibling = None + for tag, (out, files) in made.items(): + cases = [] + for f in files: + p = os.path.join(out, f) + r = json.load(open(os.path.join(refdir, f + ".json"))) + g = r.get("gltf") + if g: + for k in ("bufferViews", "asset", "scene", "scenes", "extensionsUsed", "samplers"): + g.pop(k, None) + cases.append({"name": f, "data": open(p, "rb").read(), "ref": clean(r)}) + name = "cur" if tag == "cur" else tag + ctx.emit("blend_" + name, cases) + if sibling is None and os.path.exists(os.path.join(out, "outside.png")): + sibling = open(os.path.join(out, "outside.png"), "rb").read() + for tag, _ in OLD + [("cur", None)]: + if tag not in made: + ctx.emit("blend_" + tag, []) + ctx.emit("blend_files", {"outside.png": sibling or b""}) + ctx.emit("blend_versions", sorted(made.keys())) + shutil.rmtree(tmp, ignore_errors=True) From 3c8d5e99d708f8f351a2d4c26a8f0a6b9d1961cc Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 19:23:28 -0600 Subject: [PATCH 2/4] model/blend: Blender 1.6x-2.0x files (big-endian, 32-bit, TFace / MCol, IPO curves, additive dsize), easing curves, owner-scoped address lookup; containers/Blend tests; docs section; bench line --- docs/guide/scene.md | 51 ++++- src/Rosetta/containers/Blend.luau | 55 ++--- src/Rosetta/model/blend/Anim.luau | 61 +++++- src/Rosetta/model/blend/Material.luau | 4 +- src/Rosetta/model/blend/Mesh.luau | 77 +++++-- src/Rosetta/model/blend/Prim.luau | 25 +-- src/Rosetta/model/blend/Read.luau | 93 +++++--- src/Rosetta/model/blend/init.luau | 2 + tests/containers/blend.luau | 294 ++++++++++++++++++++++++++ tests/model/blend.luau | 67 ++++-- tools/bench.luau | 9 + tools/fixtures/_blend_make.py | 12 ++ tools/fixtures/blend.py | 53 ++++- tools/fixtures/docs_blend.py | 73 +++++++ 14 files changed, 766 insertions(+), 110 deletions(-) create mode 100644 tests/containers/blend.luau create mode 100644 tools/fixtures/docs_blend.py diff --git a/docs/guide/scene.md b/docs/guide/scene.md index 40c3d7b..1c19ff7 100644 --- a/docs/guide/scene.md +++ b/docs/guide/scene.md @@ -2,7 +2,7 @@ Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, 3DS, MS3D, B3D, LDraw, LightWave LWO, DirectX .x, IQM, PMX / PMD, VRML, X3D, the [game models](#game-models) MD2 / MD3 / MDL / MD5 / BSP / SMD, -[Roblox meshes](roblox.md) and the [Minecraft and Qubicle voxel files](voxel.md)) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes +[Blender .blend](#blender-blend), [Roblox meshes](roblox.md) and the [Minecraft and Qubicle voxel files](voxel.md)) loads as one `Scene`, a structure shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), PBR materials, textures, cameras, lights, skins and animations. Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel files also carry voxel grids (`scene.voxels`). Editing goes through `F.ops.mesh`. @@ -716,6 +716,54 @@ assert(back.meta.source.format == "iqm" and back.meshes[1].name == "tri") assert(back.meshes[1].primitives[1].indices.count == 3) ``` +## Blender (.blend) + +`.blend` files load read only, from every Blender version since 2.4x: plain, gzip (before 3.0) or zstd (3.0+) +compressed, 32 or 64-bit pointers, either byte order, and the 5.0+ header. Each file is read through its own SDNA (the +struct catalogue Blender writes into every file), so fields are found by name whatever version wrote them. The +current scene loads: objects (transforms with euler orders, quaternions, axis angles, delta transforms, the parent +inverse, bone parents), collections as nodes (`collections = false` flattens them), meshes, materials, images, +cameras, lights, armatures, skins, shape keys and actions. Blender is z-up (`meta.up = "z"`). + +| Part | What loads | +|---|---| +| Meshes | every storage generation: MFace (before 2.63 and the 2.7x "legacy mesh format"), MPoly / MLoop (2.63 - 3.x), attribute layers (`position`, `.corner_vert`, ... 3.x - 4.x), AttributeStorage (5.x); a primitive per used material slot, `triangulate = false` keeps the faces (`"polygons"`) | +| Mesh data | UV maps (`TEXCOORD_n`, v flipped to glTF's origin), colour attributes (byte and float, point and corner) as linear `COLOR_n`, corner normals from Blender's smooth fans (sharp edges / faces, auto smooth before 4.1) or the stored custom normals, weights (`JOINTS_0` / `WEIGHTS_0`: the 4 largest deform-bone groups, normalized) | +| Materials | the Principled BSDF (base colour, metallic, roughness, alpha, emission and its strength, image textures on Base Color / Emission, Normal through a Normal Map node, Roughness / Metallic through Separate RGB), else the legacy `r, g, b` colour | +| Images | packed images as encoded bytes (`texture.data`), external ones as `uri` (relative to the `.blend`, bytes through `files` / `resolve`) | +| Cameras, lights | perspective (`yfov` from the lens, sensor fit and render aspect) / orthographic; point, sun, spot (watts to candela / lux as Blender's glTF exporter does); area lights are skipped (`meta.source.skippedLights`) | +| Armatures | a joint node per bone (rest pose times the saved pose), one skin per deformed mesh | +| Animation | the active action of each object, armature (pose bones) and shape key set, f-curves evaluated (constant, linear, bezier, easing; extrapolation) and sampled once per frame (`sampleStep`) into channels; time 0 is `meta.source.frameZero` at `meta.source.fps` | +| Not loaded | modifiers (listed per object in `meta.source.modifiers`, never applied), curves, text, metaballs, grease pencil, volumes, NLA strips, drivers, constraints, linked libraries | + +```luau +local scene = assert(F.model.load(riggedBlendBytes)) +local src = scene.meta.source +assert(src.format == "blend" and src.version >= 500 and src.compression == "zstd") +assert(scene.meta.up == "z" and #scene.skins == 1 and #scene.animations == 1) +local tube = scene.meshes[1].primitives[1] +assert(tube.attributes.JOINTS_0 and tube.attributes.WEIGHTS_0 and #tube.targets == 1) +assert(scene.materials[1].name == "Skin" and scene.materials[1].roughness > 0.69) +print(src.modifiers.Tube[1].type) -- Armature (not applied) +``` + +Anything else in the file is reachable through the container: `F.format("blend").open` parses the blocks and the +SDNA, and every struct reads by field name (`get`, `num`, `str`, `vec`, `sub`, `deref`, `list` for ListBase, `array` +and `pointers` behind pointers). + +```luau +local blend = F.format("blend") +local file = assert(blend.open(F.Bytes.reader(riggedBlendBytes))) +local Blend = blend.container +for _, block in Blend.blocks(file, "OB") do + local ob = assert(Blend.struct(file, block)) + print(ob:idName(), ob:num("type"), ob:vec("loc")[3]) -- Rig 25 0 / Tube 1 0 +end +local arm = assert(Blend.struct(file, Blend.blocks(file, "AR")[1])) +local bones = arm:list("bonebase") +assert(bones[1]:str("name") == "lower" and bones[1]:list("childbase")[1]:str("name") == "upper") +``` + ## Formats | Format | Read | Write | Notes | @@ -746,6 +794,7 @@ assert(back.meshes[1].primitives[1].indices.count == 3) | STEP | via the CAD plug-in | | see [cad.md](cad.md) | | MD2, MD3, MDL, MD5, BSP | yes | - | game models and maps: see "Game models" above | | SMD | yes | yes | Valve studiomdl data | +| Blender `.blend` | yes | | 2.4x - 5.x, compressed; meshes of every generation, materials, skins, shape keys, actions; see "Blender" above | | Roblox `.mesh` (robloxmesh) | yes | yes | see [roblox.md](roblox.md) | | Roblox `.rbxm` / `.rbxl`, `.rbxmx` / `.rbxlx` | as an `RbxTree` | yes | instance trees with typed properties: see [roblox.md](roblox.md) | diff --git a/src/Rosetta/containers/Blend.luau b/src/Rosetta/containers/Blend.luau index 0fd6867..2361230 100644 --- a/src/Rosetta/containers/Blend.luau +++ b/src/Rosetta/containers/Blend.luau @@ -184,7 +184,7 @@ local function parseDna(f: File, at: number, size: number): string? if n < 0 or n > e - p then return nil, p end - local out = table.create(n) + local out = table.create(n) :: { string } for k = 1, n do local q = p while q < e and readu8(b, q) ~= 0 do @@ -215,7 +215,7 @@ local function parseDna(f: File, at: number, size: number): string? if p + 4 + nt * 2 > e or readstring(b, p, 4) ~= "TLEN" then return "bad SDNA TLEN" end - local lengths = table.create(nt) + local lengths = table.create(nt) :: { number } for k = 1, nt do lengths[k] = f.u16(b, p + 4 + (k - 1) * 2) end @@ -230,7 +230,7 @@ local function parseDna(f: File, at: number, size: number): string? end local i16 = f.i16 local ps = f.pointerSize - local structs, byName = table.create(ns), {} + local structs, byName = table.create(ns) :: { Struct }, {} :: { [string]: Struct } for k = 1, ns do if p + 4 > e then return "truncated SDNA structs" @@ -240,7 +240,8 @@ local function parseDna(f: File, at: number, size: number): string? if t < 0 or t >= nt or nf < 0 or p + nf * 4 > e then return "bad SDNA struct " .. k end - local s: Struct = { name = types[t + 1], index = k - 1, size = lengths[t + 1], fields = table.create(nf), byName = {} } + 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) @@ -248,9 +249,9 @@ local function parseDna(f: File, at: number, size: number): string? if ft < 0 or ft >= nt or fn < 0 or fn >= #names then return "bad SDNA field in " .. s.name end - local decl = names[fn + 1] + local decl: string = (names :: { string })[fn + 1] local pointer = string.sub(decl, 1, 1) == "*" or string.sub(decl, 1, 2) == "(*" - local dims, count = {}, 1 + local dims: { number }, count = {}, 1 for d in string.gmatch(decl, "%[(%d+)%]") do local v = tonumber(d) or 1 table.insert(dims, v) @@ -258,9 +259,9 @@ local function parseDna(f: File, at: number, size: number): string? end local base = string.gsub(decl, "%[.*$", "") base = string.gsub(base, "[%*%(%)]", "") - local elem = if pointer then ps else lengths[ft + 1] + local elem: number = if pointer then ps else lengths[ft + 1] local fld: Field = { - name = base, decl = decl, type = types[ft + 1], offset = off, size = elem * count, + 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 @@ -272,7 +273,7 @@ local function parseDna(f: File, at: number, size: number): string? structs[k] = s byName[s.name] = s end - f.dna = { names = names, types = types, lengths = lengths, structs = structs, byName = byName } + f.dna = { names = names :: { string }, types = types :: { string }, lengths = lengths, structs = structs, byName = byName } return nil end @@ -298,7 +299,8 @@ function Blend.open(data: buffer, offset: number?, length: number?, opts: Option end local hs, ps, little, version, fmt, herr = header(b, n) if not hs then - return nil, Err.new(if n < 12 then Err.TRUNCATED else Err.CORRUPT, herr or "bad header", 0) + 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, @@ -341,7 +343,8 @@ function Blend.open(data: buffer, offset: number?, length: number?, opts: Option count = i32(b, p + 12 + ps) end p += bh - code = string.gsub(code, "%z+$", "") + -- 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 @@ -389,29 +392,33 @@ function Blend.open(data: buffer, offset: number?, length: number?, opts: Option f.byAddr[if ps == 8 then string.rep("\0", 8) else 0] = nil local glob = f.byCode.GLOB local fg = f.dna.byName.FileGlobal - if glob and fg and fg.byName.subversion then - local fld = fg.byName.subversion - if fld.offset + 2 <= glob[1].size then - f.subversion = f.i16(b, glob[1].offset + fld.offset) + 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 -export type View = { - file: File, - struct: Struct, - offset: number, -- the struct's first byte in file.buf - block: Block?, -} - 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) :: any + return setmetatable({ file = f, struct = s, offset = offset, block = blk }, View) end function Blend.structOf(f: File, blk: Block): Struct? @@ -641,7 +648,7 @@ function View.array(self: View, name: string | { string }, as: string?): { View 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) + 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 diff --git a/src/Rosetta/model/blend/Anim.luau b/src/Rosetta/model/blend/Anim.luau index e7e1f8b..9ce147d 100644 --- a/src/Rosetta/model/blend/Anim.luau +++ b/src/Rosetta/model/blend/Anim.luau @@ -1,7 +1,8 @@ --!strict -- model/blend/Anim: Blender actions (legacy bAction.curves, and the layered actions of 4.4+: layers -> strips -> -- keyframe data -> channel bags matched by the AnimData slot handle) and f-curve evaluation: constant, linear, --- bezier (handles shortened so the segment stays a function of time, as Blender does) and the Penner easing modes; +-- bezier (handles shortened so the segment stays a function of time, as Blender does) and the Penner easing modes +-- (elastic uses Penner's amplitude / period, which Blender scales differently); -- constant or linear extrapolation. F-curve modifiers and NLA strips are not evaluated. local Blend = require("@rosetta/containers/Blend") @@ -112,6 +113,62 @@ function Anim.curves(f: Blend.File, adt: Blend.View?): ({ Curve }?, string?) return out, act:idName() end +-- pre-2.5 IPO curves (Object.ipo / Key.ipo): the curve's adrcode picks the channel; object rotations are in units of +-- 10 degrees; the interpolation and extrapolation (0 constant, 1 linear; cyclic ones as constant) are per curve +local OB_ADR: { [number]: { any } } = { + [1] = { "location", 0 }, [2] = { "location", 1 }, [3] = { "location", 2 }, + [4] = { "delta_location", 0 }, [5] = { "delta_location", 1 }, [6] = { "delta_location", 2 }, + [7] = { "rotation_euler", 0, math.pi / 18 }, [8] = { "rotation_euler", 1, math.pi / 18 }, [9] = { "rotation_euler", 2, math.pi / 18 }, + [10] = { "delta_rotation_euler", 0, math.pi / 18 }, [11] = { "delta_rotation_euler", 1, math.pi / 18 }, [12] = { "delta_rotation_euler", 2, math.pi / 18 }, + [13] = { "scale", 0 }, [14] = { "scale", 1 }, [15] = { "scale", 2 }, +} + +function Anim.ipo(f: Blend.File, ipo: Blend.View?, keyNames: { string }?): ({ Curve }?, string?) + if not ipo then + return nil, nil + end + local out: { Curve } = {} + for _, icu in ipo:list("curve", "IpoCurve") do + local adr = icu:num("adrcode") or -1 + local path, index, scale + if keyNames then + if adr >= 1 and keyNames[adr + 1] then + path, index, scale = 'key_blocks["' .. keyNames[adr + 1] .. '"].value', 0, 1 + end + else + local m = OB_ADR[adr] + if m then + path, index, scale = m[1], m[2], m[3] or 1 + end + end + if path then + local ipoMode = icu:num("ipo") or BEZ + local keys: { Key } = {} + for _, b in icu:array("bezt", "BezTriple") do + local v = b:vec("vec") + if v and #v >= 9 then + table.insert(keys, { + lx = v[1], ly = v[2] * scale, x = v[4], y = v[5] * scale, rx = v[7], ry = v[8] * scale, + ipo = if ipoMode == CONST or ipoMode == LIN then ipoMode else BEZ, easing = 0, back = 1.70158, amplitude = 0.8, period = 4.1, + }) + end + end + local n = math.min(#keys, icu:num("totvert") or #keys) + while #keys > n do + table.remove(keys) + end + if #keys > 0 then + table.sort(keys, function(a: Key, b: Key): boolean + return a.x < b.x + end) + table.insert(out, { path = path, index = index, keys = keys, extend = if (icu:num("extrap") or 0) == 1 then 1 else 0, modifiers = 0 }) + end + end + end + local _ = f + return out, ipo:idName() +end + -- ------------------------------------------------------------------------------------------------ evaluation local function bezierAt(p0: number, p1: number, p2: number, p3: number, t: number): number local u = 1 - t @@ -191,7 +248,7 @@ local function easeIn(ipo: number, t: number, a: Key): number -- 0..1 -> 0..1 t -= 1 return -(amp * 2 ^ (10 * t) * math.sin((t - s) * (2 * math.pi) / p)) elseif ipo == EXPO then - return if t <= 0 then 0 else 2 ^ (10 * (t - 1)) + return (2 ^ (10 * (t - 1)) - 2 ^ -10) / (1 - 2 ^ -10) -- normalized to run from 0 to 1, as Blender's does elseif ipo == QUAD then return t * t elseif ipo == QUART then diff --git a/src/Rosetta/model/blend/Material.luau b/src/Rosetta/model/blend/Material.luau index 58cce4b..157e2f2 100644 --- a/src/Rosetta/model/blend/Material.luau +++ b/src/Rosetta/model/blend/Material.luau @@ -190,9 +190,11 @@ local function imageRef(ctx: Ctx, g: Graph, uvNames: any, s: Blend.View?, throug return nil, n end local sampler: Types.Sampler = {} + local custom = false local st = n.view:deref("storage", 0, "NodeTexImage") if st then local interp, ext = st:num("interpolation") or 0, st:num("extension") or 0 + custom = interp == 1 or (ext >= 1 and ext <= 3) if interp == 1 then sampler.filter = "nearest" sampler.minFilter = "nearest" @@ -203,7 +205,7 @@ local function imageRef(ctx: Ctx, g: Graph, uvNames: any, s: Blend.View?, throug sampler.wrapS, sampler.wrapT = "mirror", "mirror" end end - local t = texture(ctx, img, if next(sampler) then sampler else nil) + local t = texture(ctx, img, if custom then sampler else nil) if not t then return nil, n end diff --git a/src/Rosetta/model/blend/Mesh.luau b/src/Rosetta/model/blend/Mesh.luau index fe5f0a4..9729197 100644 --- a/src/Rosetta/model/blend/Mesh.luau +++ b/src/Rosetta/model/blend/Mesh.luau @@ -198,6 +198,29 @@ local function fieldReader(f: Blend.File, L: Layer, field: string): ((number, nu end end +-- tessellated face colours: corner k of face i at offset + i * faceStride + first + k * cornerStride, bytes in MCol's +-- memory order (alpha, blue, green, red; reversed when an int held them in a big-endian file), sRGB -> linear; +-- TFace colours load opaque, as Blender's versioning makes them +local function tessColors(f: Blend.File, tess: buffer, nc: number, offset: number, bytes: number, faceStride: number, first: number, cornerStride: number, swap: boolean, opaque: boolean?): buffer + local d = buffer.create(nc * 16) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + local at = (tc // 4) * faceStride + first + (tc % 4) * cornerStride + if at + 4 <= bytes then + local o = offset + at + local aa, bb, gg, rr = readu8(f.buf, o), readu8(f.buf, o + 1), readu8(f.buf, o + 2), readu8(f.buf, o + 3) + if swap then + aa, bb, gg, rr = rr, gg, bb, aa + end + buffer.writef32(d, i * 16, SRGB[rr + 1]) + buffer.writef32(d, i * 16 + 4, SRGB[gg + 1]) + buffer.writef32(d, i * 16 + 8, SRGB[bb + 1]) + buffer.writef32(d, i * 16 + 12, if opaque then 1 else aa / 255) + end + end + return d +end + function Mesh.layers(f: Blend.File, me: Blend.View): { Layer } local layers: { Layer } = {} customData(f, me, { "vdata", "vert_data" }, "point", layers) @@ -396,10 +419,11 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri end elseif L.domain == "tess" and L.kind == "MTFace" and corner.tess then local r = fieldReader(f, L, "uv") + local tess = corner.tess :: buffer if r then local d = buffer.create(nc * 8) for i = 0, nc - 1 do - local tc = buffer.readu32(corner.tess, i * 4) + local tc = buffer.readu32(tess, i * 4) local face, k = tc // 4, tc % 4 buffer.writef32(d, i * 8, r(face, k * 2)) buffer.writef32(d, i * 8 + 4, r(face, k * 2 + 1)) @@ -408,6 +432,21 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri end end end + -- before 2.42 (no CustomData): Mesh.tface (TFace, uv[4][2] per face) and Mesh.mcol (MCol x 4 per face) + if #poly.uvs == 0 and corner.tess then + local tf = legacy(f, me, "tface", "TFace", "tess") + local r = tf and fieldReader(f, tf, "uv") + if r then + local tess = corner.tess :: buffer + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + buffer.writef32(d, i * 8, r(tc // 4, (tc % 4) * 2)) + buffer.writef32(d, i * 8 + 4, r(tc // 4, (tc % 4) * 2 + 1)) + end + table.insert(poly.uvs, { name = "UVMap", data = d }) + end + end local active = me:cstring("default_uv_map_attribute") or me:cstring("active_uv_map_attribute") if active then for k, u in poly.uvs do @@ -434,23 +473,20 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri end table.insert(poly.colors, { name = L.name, domain = L.domain, data = d }) elseif L.kind == "MCol" and L.domain == "tess" and corner.tess then - -- MCol keeps alpha, blue, green, red in its a, r, g, b fields local st = f.dna.byName.MCol - local d = buffer.create(nc * 16) local stride = if st then st.size else 4 - for i = 0, nc - 1 do - local tc = buffer.readu32(corner.tess, i * 4) - local at = (tc // 4) * 4 * stride + (tc % 4) * stride - if at + 4 <= L.bytes then - local o = L.offset + at - local aa, bb, gg, rr = readu8(f.buf, o), readu8(f.buf, o + 1), readu8(f.buf, o + 2), readu8(f.buf, o + 3) - buffer.writef32(d, i * 16, SRGB[rr + 1]) - buffer.writef32(d, i * 16 + 4, SRGB[gg + 1]) - buffer.writef32(d, i * 16 + 8, SRGB[bb + 1]) - buffer.writef32(d, i * 16 + 12, aa / 255) - end - end - table.insert(poly.colors, { name = L.name, domain = "corner", data = d }) + table.insert(poly.colors, { name = L.name, domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, L.offset, L.bytes, stride * 4, 0, stride, false) }) + end + end + -- before 2.42 (no CustomData): Mesh.mcol, or TFace.col (unsigned int col[4], MCol's byte layout in memory) + if #poly.colors == 0 and corner.tess then + local mc = legacy(f, me, "mcol", "MCol", "tess") + local tf = legacy(f, me, "tface", "TFace", "tess") + local col = f.dna.byName.TFace and f.dna.byName.TFace.byName.col + if mc then + table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, mc.offset, mc.bytes, mc.elem * 4, 0, mc.elem, false) }) + elseif tf and col then + table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, tf.offset, tf.bytes, tf.elem, col.offset, 4, not f.little, true) }) end end -- MLoopCol layers carry the CD_PROP_BYTE_COLOR type (17) and are read above as bytecolor (r, g, b, a bytes) @@ -539,7 +575,7 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri local mw = f.dna.byName.MDeformWeight local nrf, wf = mw and mw.byName.def_nr, mw and mw.byName.weight if dwf and twf and mw and nrf and wf then - local weights = table.create(nv) + local weights = table.create(nv) :: { { number } } for i = 0, nv - 1 do local list = {} local at = i * dv.elem @@ -565,7 +601,7 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri end -- shape keys: { name, value, relative (0-based), data: f32 x 3 per vertex } in file order, and the reference index -export type Shape = { name: string, value: number, relative: number, data: buffer, mute: boolean } +export type Shape = { name: string, value: number, relative: number, data: buffer, mute: boolean, min: number, max: number } function Mesh.shapes(f: Blend.File, me: Blend.View, nv: number): ({ Shape }, number?, Blend.View?) local key = me:deref("key", 0, "Key") if not key then @@ -591,8 +627,11 @@ function Mesh.shapes(f: Blend.File, me: Blend.View, nv: number): ({ Shape }, num ref = i end table.insert(out, { - name = kb:str("name") or ("Key " .. i), value = kb:num("curval") or 0, relative = kb:num("relative") or 0, data = d, + -- unnamed in old files: Key 0 (the basis), Key 1, ... + name = kb:str("name") or ("Key " .. (i - 1)), value = kb:num("curval") or 0, relative = kb:num("relative") or 0, data = d, mute = bit32.band(kb:num("flag") or 0, 2) ~= 0, + min = kb:num("slidermin") or 0, + max = kb:num("slidermax") or 1, }) end if ref == nil and #out > 0 then diff --git a/src/Rosetta/model/blend/Prim.luau b/src/Rosetta/model/blend/Prim.luau index 364c346..010b907 100644 --- a/src/Rosetta/model/blend/Prim.luau +++ b/src/Rosetta/model/blend/Prim.luau @@ -185,15 +185,10 @@ function Prim.cornerNormals(poly: MeshT.Poly, fn: buffer, ang: buffer, fans: Fan local r = readu32(fanId, c * 4) local x, y, z = readf32(acc, r * 12), readf32(acc, r * 12 + 4), readf32(acc, r * 12 + 8) local l = sqrt(x * x + y * y + z * z) - if l > 1e-20 then - x, y, z = x / l, y / l, z / l - else - local fi = readu32(fans.face, c * 4) - x, y, z = readf32(fn, fi * 12), readf32(fn, fi * 12 + 4), readf32(fn, fi * 12 + 8) - end - writef32(out, c * 12, x) - writef32(out, c * 12 + 4, y) - writef32(out, c * 12 + 8, z) + local fi = readu32(fans.face, c * 4) + writef32(out, c * 12, if l > 1e-20 then x / l else readf32(fn, fi * 12)) + writef32(out, c * 12 + 4, if l > 1e-20 then y / l else readf32(fn, fi * 12 + 4)) + writef32(out, c * 12 + 8, if l > 1e-20 then z / l else readf32(fn, fi * 12 + 8)) end return out, fanId end @@ -231,7 +226,7 @@ local function triangulate(poly: MeshT.Poly, fi: number, fnx: number, fny: numbe elseif ay >= az then cu, cv, sign = 2, 0, fny end - local ring = table.create(n * 2) + local ring = table.create(n * 2) :: { number } for c = s0, s1 - 1 do local v = readu32(poly.cornerVert, c * 4) local u, w = readf32(poly.pos, (v * 3 + cu) * 4), readf32(poly.pos, (v * 3 + cv) * 4) @@ -284,7 +279,7 @@ function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: S table.insert(g, fi) end table.sort(order) - local cornerColors, pointColors = {}, {} + local cornerColors: { MeshT.Color }, pointColors: { MeshT.Color } = {}, {} for _, c in poly.colors do table.insert(if c.domain == "corner" then cornerColors else pointColors, c) end @@ -367,7 +362,7 @@ function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: S ci += 1 end if skin and poly.weights then - local lists = table.create(n) + local lists = table.create(n) :: { { number } } for i = 1, n do local src = poly.weights[vsrc[i] + 1] or {} local l = {} @@ -415,17 +410,17 @@ function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: S end if shapes and ref and #shapes > 1 then local base = shapes[ref].data - local targets = {} + local targets: { { [string]: Types.Accessor } } = {} for k, s in shapes do if k ~= ref then - local t = table.create(n * 3) + local t = table.create(n * 3) :: { number } for i = 1, n do local v = vsrc[i] for c = 0, 2 do t[(i - 1) * 3 + c + 1] = readf32(s.data, (v * 3 + c) * 4) - readf32(base, (v * 3 + c) * 4) end end - table.insert(targets, { POSITION = accessor(t, 3) }) + table.insert(targets, { POSITION = accessor(t, 3) } :: { [string]: Types.Accessor }) end end prim.targets = targets diff --git a/src/Rosetta/model/blend/Read.luau b/src/Rosetta/model/blend/Read.luau index 40f8a2a..5d6629f 100644 --- a/src/Rosetta/model/blend/Read.luau +++ b/src/Rosetta/model/blend/Read.luau @@ -86,26 +86,33 @@ export type Props = { [string]: { number } } -- location / rotation_euler / ... -- an object's or pose bone's transform properties, keyed by their RNA names local function objectProps(ob: Blend.View): Props - local function v(n: number, ...: string): { number } + -- fields missing from old files take their neutral value + local function v(fallback: { number }, ...: string): { number } local x = ob:vec(...) - if x and #x >= n then + if x and #x >= #fallback then return table.clone(x) end - return table.create(n, 0) + return fallback end - return { - location = v(3, "loc"), - rotation_euler = v(3, "rot"), - rotation_quaternion = v(4, "quat"), - rotation_axis_angle = { ob:num("rotAngle") or 0, table.unpack(v(3, "rotAxis")) }, - scale = v(3, "scale", "size"), - delta_location = v(3, "dloc"), - delta_rotation_euler = v(3, "drot"), - delta_rotation_quaternion = v(4, "dquat"), - delta_rotation_axis_angle = { ob:num("drotAngle") or 0, table.unpack(v(3, "drotAxis")) }, - delta_scale = v(3, "dscale", "dsize"), + local p: Props = { + location = v({ 0, 0, 0 }, "loc"), + rotation_euler = v({ 0, 0, 0 }, "rot"), + rotation_quaternion = v({ 1, 0, 0, 0 }, "quat"), + rotation_axis_angle = { ob:num("rotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "rotAxis")) }, + scale = v({ 1, 1, 1 }, "scale", "size"), + delta_location = v({ 0, 0, 0 }, "dloc"), + delta_rotation_euler = v({ 0, 0, 0 }, "drot"), + delta_rotation_quaternion = v({ 1, 0, 0, 0 }, "dquat"), + delta_rotation_axis_angle = { ob:num("drotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "drotAxis")) }, + delta_scale = v({ 1, 1, 1 }, "dscale"), rotmode = { ob:num("rotmode") or 1 }, } + if not ob:has("dscale") then + -- before 2.5x the delta scale ("dsize") was added to the scale + local d = v({ 0, 0, 0 }, "dsize") + p.scale = { p.scale[1] + d[1], p.scale[2] + d[2], p.scale[3] + d[3] } + end + return p end local function poseProps(pc: Blend.View?): Props @@ -267,12 +274,13 @@ local function camera(ctx: Ctx, ob: Blend.View, node: number) local znear, zfar = cam:num("clip_start", "clipsta") or 0.1, cam:num("clip_end", "clipend") or 100 local c: Types.Camera if (cam:num("type") or 0) == 1 then - local half = (cam:num("ortho_scale") or 6) / 2 + -- files without ortho_scale (before 2.3x) scaled orthographic views by 256 / lens, as Blender's versioning sets it + local half = (cam:num("ortho_scale") or 256 / math.max(cam:num("lens") or 35, 1e-3)) / 2 local xmag, ymag = half, half / aspect if aspect < 1 then xmag, ymag = half * aspect, half end - c = { name = ob:idName(), type = "orthographic", xmag = xmag, ymag = ymag, znear = znear, zfar = zfar } + c = { name = ob:idName(), type = "orthographic", xmag = xmag, ymag = ymag, znear = znear, zfar = zfar } :: Types.Camera else local lens = cam:num("lens") or 50 local sx, sy = cam:num("sensor_x") or 36, cam:num("sensor_y") or 24 @@ -285,7 +293,7 @@ local function camera(ctx: Ctx, ob: Blend.View, node: number) else yfov = 2 * math.atan(sx / 2 / lens) end - c = { name = ob:idName(), type = "perspective", yfov = yfov, aspect = aspect, znear = znear, zfar = zfar } + c = { name = ob:idName(), type = "perspective", yfov = yfov, aspect = aspect, znear = znear, zfar = zfar } :: Types.Camera end table.insert(ctx.scene.cameras, c) ctx.scene.nodes[node].camera = #ctx.scene.cameras @@ -299,9 +307,13 @@ local function light(ctx: Ctx, ob: Blend.View, node: number) local t = la:num("type") or 0 local color = { la:num("r") or 1, la:num("g") or 1, la:num("b") or 1 } local energy = la:num("energy") or 1 - if ctx.f.version < 280 then - -- before 2.8 Cycles took the strength from the lamp's Emission node, else 100 (sun: 1); Blender's 2.8 - -- versioning moves that to energy + if ctx.f.version < 280 and ctx.meta.engine ~= "CYCLES" then + -- Blender's 2.8 versioning: Blender Internal energies times 100 (suns unchanged) + if t ~= LA_SUN and t ~= LA_HEMI then + energy *= 100 + end + elseif ctx.f.version < 280 then + -- Cycles took the strength from the lamp's Emission node, else 100 (sun: 1) energy = if t == LA_SUN or t == LA_HEMI then 1 else 100 local tree = (la:num("use_nodes") or 0) ~= 0 and la:deref("nodetree", 0, "bNodeTree") or nil for _, n in if tree then tree:list("nodes", "bNode") else {} do @@ -318,13 +330,17 @@ local function light(ctx: Ctx, ob: Blend.View, node: number) local name = ob:idName() local l: Types.Light if t == LA_SUN or t == LA_HEMI then - l = { name = name, type = "directional", color = color, intensity = energy * W2LM } + l = { name = name, type = "directional", color = color, intensity = energy * W2LM } :: Types.Light elseif t == LA_SPOT then - local outer = (la:num("spotsize") or math.rad(45)) / 2 + local size = la:num("spotsize") or math.rad(45) + if ctx.f.version < 263 then + size = math.rad(size) -- degrees before 2.63 + end + local outer = size / 2 local blend = la:num("spotblend") or 0 - l = { name = name, type = "spot", color = color, intensity = energy / (4 * math.pi) * W2LM, outerCone = outer, innerCone = outer - outer * blend } + l = { name = name, type = "spot", color = color, intensity = energy / (4 * math.pi) * W2LM, outerCone = outer, innerCone = outer - outer * blend } :: Types.Light elseif t == LA_LOCAL then - l = { name = name, type = "point", color = color, intensity = energy / (4 * math.pi) * W2LM } + l = { name = name, type = "point", color = color, intensity = energy / (4 * math.pi) * W2LM } :: Types.Light else local skipped = ctx.meta.skippedLights or {} ctx.meta.skippedLights = skipped @@ -568,11 +584,23 @@ type Job = { kind: string, node: number?, nodes: { number }?, info: any?, curves local function animations(ctx: Ctx) local f = ctx.f local jobs: { Job } = {} + -- an IPO shared by several objects animates the first by name only, as Blender's 2.5 conversion leaves it + local ipoOwner: { [any]: string } = {} + for _, ob in ctx.objView do + local a, nm = ob:ptr("ipo"), ob:idName() or "" + if a ~= nil and (ipoOwner[a] == nil or nm < ipoOwner[a]) then + ipoOwner[a] = nm + end + end for node = 1, #ctx.scene.nodes do local ob = ctx.objView[node] local curves, name if ob then curves, name = Anim.curves(f, ob:deref("adt", 0, "AnimData")) + local ipoAddr = ob:ptr("ipo") + if not curves and not ob:has("adt") and ipoAddr ~= nil and ipoOwner[ipoAddr] == ob:idName() then + curves, name = Anim.ipo(f, ob:deref("ipo", 0, "Ipo")) + end end if curves and #curves > 0 and name then table.insert(jobs, { kind = "object", node = node, curves = curves, action = name }) @@ -584,6 +612,13 @@ local function animations(ctx: Ctx) end for meshIdx, sk in ctx.meta.shapeKeys do local curves, name = Anim.curves(f, sk.key and sk.key:deref("adt", 0, "AnimData")) + if not curves and sk.key and not sk.key:has("adt") then + local names = {} + for i, s in sk.shapes do + names[i] = s.name + end + curves, name = Anim.ipo(f, sk.key:deref("ipo", 0, "Ipo"), names) + end -- 2.7x could key shape values from the mesh ("shape_keys.key_blocks[...].value") local mc, mname = Anim.curves(f, sk.mesh:deref("adt", 0, "AnimData")) for _, c in mc or {} do @@ -601,7 +636,7 @@ local function animations(ctx: Ctx) table.insert(nodes, i) end end - table.insert(jobs, { kind = "shapes", nodes = nodes, curves = curves, action = name, meshIdx = meshIdx }) + table.insert(jobs, { kind = "shapes", nodes = nodes, curves = curves :: { Curve }, action = name, meshIdx = meshIdx }) end end if #jobs == 0 then @@ -622,12 +657,12 @@ local function animations(ctx: Ctx) for _, j in jobs do local anim = byAction[j.action] if not anim then - anim = { name = j.action, channels = {} } + anim = { name = j.action, channels = {} } :: Types.Animation byAction[j.action] = anim table.insert(ctx.scene.animations, anim) end local lo, hi = Anim.range(j.curves) - local fs = frames(lo, hi, step) + local fs = frames(math.floor(lo), math.ceil(hi), step) -- whole frames, as Blender plays them local times = {} for i, fr in fs do times[i] = (fr - zero) / fps @@ -695,7 +730,7 @@ local function animations(ctx: Ctx) for _, c in j.curves do local kind, who, rest = Anim.split(c.path) if kind == "key_blocks" and who == s.name and rest == "value" then - v = Anim.evaluate(c, fr) + v = math.clamp(Anim.evaluate(c, fr), math.min(s.min, s.max), math.max(s.min, s.max)) -- the slider range end end buffer.writef32(out, ((i - 1) * count + k) * 4, v) @@ -764,6 +799,7 @@ function Read.scene(f: Blend.File, opts: Options?): (Types.Scene?, string?) local fps = (r:num("frs_sec") or 24) / math.max(r:num("frs_sec_base") or 1, 1e-6) meta.fps = if fps > 0 then fps else 24 meta.frameStart = r:num("sfra") or 1 + meta.engine = r:str("engine") local xs, ys = r:num("xsch") or 1920, r:num("ysch") or 1080 local xa, ya = r:num("xasp") or 1, r:num("yasp") or 1 if xs > 0 and ys > 0 and xa > 0 and ya > 0 then @@ -846,6 +882,7 @@ function Read.scene(f: Blend.File, opts: Options?): (Types.Scene?, string?) animations(ctx) end meta.shapeKeys = nil + meta.engine = nil local render = meta.render meta.render = nil scene.meta.up = "z" diff --git a/src/Rosetta/model/blend/init.luau b/src/Rosetta/model/blend/init.luau index c4cc09b..2c341ee 100644 --- a/src/Rosetta/model/blend/init.luau +++ b/src/Rosetta/model/blend/init.luau @@ -69,7 +69,9 @@ function BlendFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene end -- ------------------------------------------------------------------------------------------------ extras +BlendFormat.container = Blend BlendFormat.evaluate = Anim.evaluate BlendFormat.curves = Anim.curves +BlendFormat.ipo = Anim.ipo return BlendFormat diff --git a/tests/containers/blend.luau b/tests/containers/blend.luau new file mode 100644 index 0000000..0ba2458 --- /dev/null +++ b/tests/containers/blend.luau @@ -0,0 +1,294 @@ +-- containers/Blend tests: synthetic files in every header / pointer size / byte order (12-byte header with 4 and 8 +-- byte pointers, little and big endian; the 5.0+ 17-byte header with large block heads), structs by name, arrays, +-- pointers, ListBase walks, addresses reused between IDs, gzip; the real files of tools/fixtures/blend.py (headers, +-- versions, zstd); errors; the fuzz pass. +local T = require("@tests/T") +local Blend = require("@rosetta/containers/Blend") +local Deflate = require("@rosetta/codecs/compress/Deflate") +local Err = require("@rosetta/core/Err") +local Cur = require("@tests/gen/blend_cur") +local Old = require("@tests/gen/blend_293") + +local t = T.suite("containers/Blend") + +-- a writer of either byte order +local function writer(little: boolean) + local parts: { string } = {} + local w = {} + local function bytes(v: number, n: number): string + local s = {} + for k = 0, n - 1 do + s[k + 1] = string.char(math.floor(v / 256 ^ k) % 256) + end + local str = table.concat(s) + return if little then str else string.reverse(str) + end + function w.u8(v: number) + table.insert(parts, string.char(v)) + end + function w.i16(v: number) + table.insert(parts, bytes(v % 65536, 2)) + end + function w.i32(v: number) + table.insert(parts, bytes(v % 4294967296, 4)) + end + function w.u64(v: number) + table.insert(parts, bytes(v, 8)) + end + function w.f32(v: number) + local b = buffer.create(4) + buffer.writef32(b, 0, v) + local s = buffer.tostring(b) + table.insert(parts, if little then s else string.reverse(s)) + end + function w.f64(v: number) + local b = buffer.create(8) + buffer.writef64(b, 0, v) + local s = buffer.tostring(b) + table.insert(parts, if little then s else string.reverse(s)) + end + function w.str(s: string) + table.insert(parts, s) + end + function w.ptr(v: number, ps: number) + if ps == 8 then + w.u64(v) + else + w.i32(v) + end + end + function w.done(): string + return table.concat(parts) + end + return w +end + +-- SDNA: ListBase { void *first, *last }; Thing { Thing *next, *prev; int a; float b[2]; char name[8]; short s; +-- char pad[2]; void *data }; Holder { ListBase things; Thing *one; double d; ID-less } +local NAMES = { "*first", "*last", "*next", "*prev", "a", "b[2]", "name[8]", "s", "pad[2]", "*data", "things", "*one", "d" } +local TYPES = { "char", "short", "int", "float", "double", "void", "ListBase", "Thing", "Holder" } + +local function sdna(little: boolean, ps: number): string + local w = writer(little) + local function pad() + local s = w.done() + return (4 - #s % 4) % 4 + end + w.str("SDNA") + w.str("NAME") + w.i32(#NAMES) + for _, n in NAMES do + w.str(n .. "\0") + end + for _ = 1, pad() do + w.u8(0) + end + w.str("TYPE") + w.i32(#TYPES) + for _, n in TYPES do + w.str(n .. "\0") + end + for _ = 1, pad() do + w.u8(0) + end + w.str("TLEN") + local thing = ps * 2 + 4 + 8 + 8 + 2 + 2 + ps + for _, l in { 1, 2, 4, 4, 8, 0, ps * 2, thing, ps * 2 + ps + 8 } do + w.i16(l) + end + for _ = 1, pad() do + w.u8(0) + end + w.str("STRC") + w.i32(3) + local function struct(ty: number, fields: { { number } }) + w.i16(ty) + w.i16(#fields) + for _, f in fields do + w.i16(f[1]) + w.i16(f[2]) + end + end + -- type / name indices are 0-based + struct(6, { { 5, 0 }, { 5, 1 } }) + struct(7, { { 7, 2 }, { 7, 3 }, { 2, 4 }, { 3, 5 }, { 0, 6 }, { 1, 7 }, { 0, 8 }, { 5, 9 } }) + struct(8, { { 6, 10 }, { 7, 11 }, { 4, 12 } }) + return w.done() +end + +local function file(little: boolean, ps: number, large: boolean, dupe: boolean?): string + local w = writer(little) + if large then + w.str("BLENDER17-01v0502") + else + w.str("BLENDER" .. (if ps == 8 then "-" else "_") .. (if little then "v" else "V") .. "279") + end + local function head(code: string, size: number, addr: number, sdnaIndex: number, count: number) + w.str(code .. string.rep("\0", 4 - #code)) + if large then + w.i32(sdnaIndex) + w.u64(addr) + w.u64(size) + w.u64(count) + else + w.i32(size) + w.ptr(addr, ps) + w.i32(sdnaIndex) + w.i32(count) + end + end + local thingSize = ps * 2 + 24 + ps + head("HO", ps * 3 + 8, 0x1000, 2, 1) + w.ptr(0x2000, ps) -- things.first + w.ptr(0x3000, ps) -- things.last + w.ptr(0x3000, ps) -- one + w.f64(2.5) + local function thing(next: number, prev: number, a: number, b1: number, b2: number, name: string, s: number, data: number) + w.ptr(next, ps) + w.ptr(prev, ps) + w.i32(a) + w.f32(b1) + w.f32(b2) + w.str(name .. string.rep("\0", 8 - #name)) + w.i16(s) + w.str("\0\0") + w.ptr(data, ps) + end + head("DATA", thingSize, 0x2000, 1, 1) + thing(0x3000, 0, -7, 1.5, -2.25, "first", -300, 0x4000) + head("DATA", thingSize, 0x3000, 1, 1) + thing(0, 0x2000, 123456, 0.5, 4, "second!", 1234, 0) + head("DATA", 6, 0x4000, 0, 1) + w.str("hello\0") + if dupe then + -- a second ID whose own data reuses the address 0x4000 + head("H2", ps * 3 + 8, 0x5000, 2, 1) + w.ptr(0, ps) + w.ptr(0, ps) + w.ptr(0x4000, ps) + w.f64(-1) + head("DATA", thingSize, 0x4000, 1, 1) + thing(0, 0, 99, 0, 0, "dup", 0, 0) + end + local dna = sdna(little, ps) + head("DNA1", #dna, 0x9000, 0, 1) + w.str(dna) + head("ENDB", 0, 0, 0, 0) + return w.done() +end + +for _, v in { { true, 8, false }, { true, 4, false }, { false, 8, false }, { false, 4, false }, { true, 8, true } } do + local little, ps, large = v[1], v[2], v[3] + local label = string.format("%s-endian, %d-byte pointers%s", if little then "little" else "big", ps, if large then ", 5.0 header" else "") + local f, err = Blend.open(buffer.fromstring(file(little, ps, large))) + t:check(f, label .. ": open: " .. tostring(err)) + if not f then + continue + end + t:eq(f.pointerSize, ps, label .. ": pointer size") + t:eq(f.little, little, label .. ": byte order") + t:eq(f.version, if large then 502 else 279, label .. ": version") + t:eq(f.format, if large then 1 else 0, label .. ": format") + t:eq(#f.blocks, 5, label .. ": blocks (ENDB not listed)") + t:eq(f.dna.byName.Thing.size, ps * 3 + 24, label .. ": struct size from TLEN") + t:eq(f.dna.byName.Thing.byName.data.offset, ps * 2 + 24, label .. ": field offsets") + local ho = assert(Blend.struct(f, Blend.blocks(f, "HO")[1])) + t:eq(ho:num("d"), 2.5, label .. ": double") + local list = ho:list("things") + t:eq(#list, 2, label .. ": ListBase walk") + t:eq(list[1]:num("a"), -7, label .. ": int") + t:eq(list[2]:num("a"), 123456, label .. ": int 2") + t:eq(list[1]:num("s"), -300, label .. ": short") + t:eq(list[1]:str("name"), "first", label .. ": char array") + t:eq(list[2]:str("name"), "second!", label .. ": char array 2") + local b = list[1]:vec("b") + t:check(b and b[1] == 1.5 and b[2] == -2.25, label .. ": float array") + t:eq(list[1]:cstring("data"), "hello", label .. ": pointer to raw data") + local one = ho:deref("one") + t:check(one and one:num("a") == 123456, label .. ": deref by field type") + t:check(ho:ptr("one") ~= nil and list[2]:ptr("next") == nil, label .. ": null pointers are nil") + t:check(ho:get("missing") == nil and ho:has("d") and not ho:has("missing"), label .. ": unknown fields") + t:eq(ho:num("missing", "d"), 2.5, label .. ": the first existing of several names") + local fld = Blend.field(f, "Thing", "nope", "b") + t:check(fld and fld.count == 2 and fld.type == "float" and #fld.dims == 1, label .. ": Blend.field") +end + +-- an address reused by another ID's data resolves inside the ID that points at it +do + local f = assert(Blend.open(buffer.fromstring(file(true, 8, false, true)))) + local h1 = assert(Blend.struct(f, Blend.blocks(f, "HO")[1])) + local h2 = assert(Blend.struct(f, Blend.blocks(f, "H2")[1])) + t:eq(h1:list("things")[1]:cstring("data"), "hello", "reused address: the first ID's raw data") + local d = h2:deref("one") + t:check(d and d:num("a") == 99 and d:str("name") == "dup", "reused address: the second ID's own block") +end + +-- gzip (Blender before 3.0) +do + local raw = file(true, 8, false) + local gz = assert(Deflate.gzip(raw)) + local f, err = Blend.open(gz) + t:check(f and f.compression == "gzip" and #f.blocks == 5, "gzip: " .. tostring(err)) + t:eq(Blend.sniff(gz), 0.05, "gzip sniffs weakly") + t:eq(Blend.sniff(buffer.fromstring(raw)), 1, "magic") +end + +-- the real files: headers and compression +for _, set in { Cur, Old } do + for _, c in set do + local f, err = Blend.open(buffer.fromstring(c.data)) + t:check(f, c.name .. ": " .. tostring(err)) + if f then + local want = c.ref.version[1] * 100 + c.ref.version[2] + t:eq(f.version, want, c.name .. ": version") + t:eq(f.format, if want >= 500 then 1 else 0, c.name .. ": header format") + if string.find(c.name, "_z%.blend$") then + t:eq(f.compression, if want >= 300 then "zstd" else "gzip", c.name .. ": compression") + end + t:check(f.dna.byName.Object and f.dna.byName.Mesh and #Blend.blocks(f, "OB") > 0, c.name .. ": SDNA and objects") + end + end +end + +-- errors +local function code(s: string): string? + local f, e = Blend.open(buffer.fromstring(s)) + return if f then nil else e.code +end +local good = file(true, 8, false) +t:eq(code("BLEND"), Err.TRUNCATED, "short file") +t:eq(code("NOTBLEND-v279" .. string.rep("\0", 40)), Err.CORRUPT, "bad magic") +t:eq(code(string.sub(good, 1, #good - 30)), Err.TRUNCATED, "no ENDB") +t:eq(code("BLENDER17-02v0502" .. string.rep("\0", 40)), Err.UNSUPPORTED, "unknown header format version") +local noDna = string.gsub(good, "DNA1", "DNA2") +t:eq(code(noDna), Err.CORRUPT, "no DNA1") +local badDna = string.gsub(good, "STRC", "STRX") +t:eq(code(badDna), Err.CORRUPT, "bad SDNA") +local _, e = Blend.open(buffer.fromstring(good), 0, 999999) +t:eq(e and e.code, Err.ARG, "bad range") + +local samples = { good, file(false, 4, false), file(true, 8, true, true) } +t:fuzz("open", function(b: buffer) + local f = Blend.open(b) + if f then + for _, blk in f.blocks do + local v = Blend.struct(f, blk) + if v then + for _, fld in v.struct.fields do + local x = v:get(fld.name) + if fld.pointer then + v:deref(fld.name) + v:array(fld.name) + v:pointers(fld.name) + v:cstring(fld.name) + elseif fld.type == "ListBase" then + v:list(fld.name) + end + local _ = x + end + end + end + end + return f +end, samples, { mutations = 64 }) +t:done() diff --git a/tests/model/blend.luau b/tests/model/blend.luau index 779435e..f3e01cb 100644 --- a/tests/model/blend.luau +++ b/tests/model/blend.luau @@ -19,6 +19,7 @@ local Sets = { ["35"] = require("@tests/gen/blend_35"), ["41"] = require("@tests/gen/blend_41"), cur = require("@tests/gen/blend_cur"), + old = require("@tests/gen/blend_old"), -- Blender 1.66 - 2.04 demo files (big-endian among them) } local t = T.suite("blend") @@ -146,7 +147,8 @@ end local checked = { worlds = 0, meshes = 0, normals = 0, weights = 0, shapes = 0, frames = 0, skinned = 0, curves = 0, materials = 0, cameras = 0, lights = 0 } local samples = {} -for _, tag in { "279", "293", "35", "41", "cur" } do +t:check(#Sets.old >= 4, "the old demo files were fetched (" .. #Sets.old .. ")") +for _, tag in { "old", "279", "293", "35", "41", "cur" } do for _, c in Sets[tag] do local ref = c.ref local label = c.name @@ -334,8 +336,10 @@ for _, tag in { "279", "293", "35", "41", "cur" } do for k, s in mi.shapes do if k ~= refIndex then ti += 1 - t:check(near(mesh.weights[ti], s.value, 1e-6), label .. ": " .. o.name .. " " .. s.name .. " weight") - for ci, cv in cs do + if not o.shapeAction then -- animated values are checked per frame below + t:check(near(mesh.weights[ti], s.value, 1e-6), label .. ": " .. o.name .. " " .. s.name .. " weight") + end + for ci, cv in if mi.cornerVerts then cs else {} do local tgt = cv[1].targets and cv[1].targets[ti] local get = tgt and read(tgt.POSITION) local v = mi.cornerVerts[ci] @@ -391,9 +395,11 @@ for _, tag in { "279", "293", "35", "41", "cur" } do tex = x end end - if im.packed > 0 then - t:check(tex and tex.data and buffer.len(tex.data) == im.packed and tex.mime == "image/png", label .. ": packed image " .. im.name) - elseif tex then + if not tex then + continue -- not used by a node material (legacy texture slots, face images) + elseif im.packed > 0 then + t:check(tex.data and buffer.len(tex.data) == im.packed and (tag == "old" or tex.mime == "image/png"), label .. ": packed image " .. im.name) + else t:eq(tex.uri, "outside.png", label .. ": external image uri") t:check(tex.data and buffer.len(tex.data) == #Files["outside.png"], label .. ": external image bytes through opts.files") end @@ -432,17 +438,26 @@ for _, tag in { "279", "293", "35", "41", "cur" } do checked.lights += 1 end -- triangles: the glTF exporter's meshes - if gl.meshes then + local curves = false -- the exporter turns curves / text / surfaces / metaballs into meshes; we do not + for _, o in ref.objects do + curves = curves or o.type == "CURVE" or o.type == "FONT" or o.type == "SURFACE" or o.type == "META" + end + if gl.meshes and not curves then + -- per instance (both sides share meshes differently) local want = 0 - for _, m in gl.meshes do - for _, p in m.primitives do - want += gl.accessors[p.indices + 1].count // 3 + for _, n in gl.nodes or {} do + if n.mesh then + for _, p in gl.meshes[n.mesh + 1].primitives do + want += gl.accessors[p.indices + 1].count // 3 + end end end local got = 0 - for _, m in scene.meshes do - for _, p in m.primitives do - got += p.indices.count // 3 + for _, n in scene.nodes do + if n.mesh then + for _, p in scene.meshes[n.mesh].primitives do + got += p.indices.count // 3 + end end end t:eq(got, want, label .. ": triangles (glTF exporter)") @@ -471,9 +486,16 @@ for _, tag in { "279", "293", "35", "41", "cur" } do ob = v end end - local curves = B.curves(file, ob and ob:deref("adt", 0, "AnimData")) or {} - t:eq(#curves, #refCurves, label .. ": " .. o.name .. " f-curves") + local curves = B.curves(file, ob and ob:deref("adt", 0, "AnimData")) + if not curves and ob and not ob:has("adt") then + curves = B.ipo(file, ob:deref("ipo", 0, "Ipo")) -- before 2.5 + end + curves = curves or {} for _, rc in refCurves do + local p = rc.path + if not (p == "location" or p == "scale" or string.find(p, "rotation") or string.find(p, "^delta_")) then + continue -- only the transform curves are read + end local cur = nil for _, x in curves do if x.path == rc.path and x.index == rc.index then @@ -492,14 +514,21 @@ for _, tag in { "279", "293", "35", "41", "cur" } do end -- the animations sampled at whole frames: posed world matrices, bones, shape key values, skinned positions if #ref.poses > 0 then - t:check(#scene.animations > 0, label .. ": animations") + local animated = false -- transform or shape key curves (others, such as an object colour, are not read) + for _, list in ref.actions do + for _, rc in list do + local p = rc.path + animated = animated or p == "location" or p == "scale" or string.find(p, "rotation") ~= nil or string.find(p, "key_blocks") ~= nil + end + end + t:check(#scene.animations > 0 or not animated, label .. ": animations") local caches = {} for _, p in ref.poses do local frame = p.frame if frame ~= math.floor(frame) or frame > 20 then continue end - local time = (frame - src.frameZero) / src.fps + local time = (frame - (src.frameZero or src.frameStart)) / src.fps local pose = {} for ai, a in scene.animations do caches[ai] = caches[ai] or {} @@ -523,7 +552,9 @@ for _, tag in { "279", "293", "35", "41", "cur" } do local i = objects[name] local w = pose[i] and pose[i].weights or scene.nodes[i].weights local want = table.move(values, 2, #values, 1, {}) - t:check(nearList(w, want, 1e-3), label .. ": frame " .. frame .. " " .. name .. " shape values " .. fmt(w) .. " / " .. fmt(want)) + -- pre-2.5 IPO bezier keys: Blender recomputes auto handles when converting them; we keep the stored ones + local eps = if tag == "old" then 1e-2 else 1e-3 + t:check(nearList(w, want, eps), label .. ": frame " .. frame .. " " .. name .. " shape values " .. fmt(w) .. " / " .. fmt(want)) end for name, want in p.skinned or {} do -- morph, then skin: sum of w * jointWorld * inverseBind * position diff --git a/tools/bench.luau b/tools/bench.luau index c44889a..2afc7c4 100644 --- a/tools/bench.luau +++ b/tools/bench.luau @@ -941,6 +941,15 @@ do bench("fbx ascii decode (" .. buffer.len(fbxa) // 1000 .. " KB)", 2, buffer.len(fbxa), function() Fbx.decode(Bytes.reader(fbxa)) end) + local BlendFmt = require("@rosetta/model/blend") + for _, c in require("@tests/gen/blend_cur") do + if c.name == "rig_52.blend" or c.name == "scene_52_z.blend" then + local bb = buffer.fromstring(c.data) + bench("blend decode " .. c.name .. " (" .. buffer.len(bb) // 1000 .. " KB)", 5, buffer.len(bb), function() + BlendFmt.decode(Bytes.reader(bb)) + end) + end + end local ThreeMf = require("@rosetta/model/3mf") local tmf = assert(ThreeMf.encode(scene)) bench("3mf decode (" .. buffer.len(tmf) // 1000 .. " KB zipped)", 2, buffer.len(tmf), function() diff --git a/tools/fixtures/_blend_make.py b/tools/fixtures/_blend_make.py index 37e5bc2..0d91b24 100644 --- a/tools/fixtures/_blend_make.py +++ b/tools/fixtures/_blend_make.py @@ -365,6 +365,18 @@ def rig_file(): mover.keyframe_insert("location", frame=f) mover.keyframe_insert("rotation_euler", frame=f) mover.keyframe_insert("scale", frame=f) + # easing interpolations (Penner) with explicit and automatic easing + easer = link(bpy.data.objects.new("Easer", None)) + eases = (("SINE", "EASE_IN_OUT"), ("BOUNCE", "AUTO"), ("SINE", "EASE_OUT"), ("BACK", "EASE_IN"), + ("EXPO", "AUTO"), ("CIRC", "EASE_OUT"), ("QUART", "EASE_IN_OUT"), ("EXPO", "EASE_OUT"), ("EXPO", "EASE_IN_OUT"), ("CUBIC", "EASE_IN")) + for k in range(len(eases) + 1): + easer.location = (k % 2 * 2.0, k * 0.5, 0) + easer.keyframe_insert("location", frame=1 + k * 2.5) + for fc in (easer.animation_data.action.fcurves if hasattr(easer.animation_data.action, "fcurves") else + [c for l in easer.animation_data.action.layers for s in l.strips for b in s.channelbags for c in b.fcurves]): + for kp, (ipo, easing) in zip(fc.keyframe_points, eases): + kp.interpolation = ipo + kp.easing = easing rig_action = rig.animation_data.action mover_action = mover.animation_data.action for act, rules in ((rig_action, {"location": "LINEAR", "scale": "CONSTANT"}), diff --git a/tools/fixtures/blend.py b/tools/fixtures/blend.py index a03dd0e..e539057 100644 --- a/tools/fixtures/blend.py +++ b/tools/fixtures/blend.py @@ -3,8 +3,10 @@ # generation (MFace legacy save, MPoly / MLoop, attribute layers, AttributeStorage), gzip and zstd compression, the # 5.0 header, layered actions. Reference values come from the current Blender opening each file # (tools/fixtures/_blend_ref.py: bpy values plus its glTF exporter's output). An old Blender that does not run is -# skipped (its cases are missing; the test notes it). -# tests/gen/blend_.luau { { name, data, ref } } +# skipped (its cases are missing; the test notes it). Plus a few Blender 1.6x / 2.0x files from download.blender.org's +# old demos (fetched, never committed; 32-bit pointers, big-endian SGI / PowerPC files among them), with references +# from Blender 4.1 (5.0 dropped big-endian files). +# tests/gen/blend_.luau { { name, data, ref } } (: 279, 293, 35, 41, cur, old) # tests/gen/blend_files.luau sibling files the scenes refer to ({ ["outside.png"] = bytes }) import json, os, shutil, subprocess, tempfile @@ -18,6 +20,52 @@ OLD = [ ] +OLD_DEMOS = "https://download.blender.org/demo/old_demos/" +OLD_FILES = ["escher.blend", "hairball.blend", "nmesh.blend", "relative.blend", "demo2.04.blend.gz"] + + +def old_samples(ctx, tmp): + import gzip, urllib.request + out = os.path.join(tmp, "olddemos") + os.makedirs(out) + files = [] + for f in OLD_FILES: + try: + with urllib.request.urlopen(OLD_DEMOS + f, timeout=60) as r: + data = r.read() + except OSError as e: + print("blend: could not fetch %s: %s" % (f, e)) + continue + if f.endswith(".gz"): + data = gzip.decompress(data) + f = f[:-3].replace("2.04", "204") + with open(os.path.join(out, f), "wb") as fh: + fh.write(data) + files.append(os.path.join(out, f)) + if not files: + return [] + refdir = os.path.join(tmp, "oldref") + os.makedirs(refdir) + ref = os.path.join(ctx.root, "tools", "fixtures", "_blend_ref.py") + ok, log = run(["nix", "shell"] + OLD[3][1] + ["-c", "blender", "-b", "--factory-startup", "--python", ref, "--", json.dumps(files), refdir]) + cases = [] + for p in files: + rp = os.path.join(refdir, os.path.basename(p) + ".json") + if not os.path.exists(rp): + continue + r = json.load(open(rp)) + if r.get("error"): + continue + g = r.get("gltf") + if g: + for k in ("bufferViews", "asset", "scene", "scenes", "extensionsUsed", "samplers"): + g.pop(k, None) + cases.append({"name": "old/" + os.path.basename(p), "data": open(p, "rb").read(), "ref": clean(r)}) + if not cases: + print("blend: Blender 4.1 gave no reference for the old demos: " + log[-400:]) + return cases + + def env(): e = dict(os.environ) e.pop("LD_LIBRARY_PATH", None) # the host's alsa / pipewire libraries need a newer glibc than old Blenders have @@ -87,6 +135,7 @@ def generate(ctx): for tag, _ in OLD + [("cur", None)]: if tag not in made: ctx.emit("blend_" + tag, []) + ctx.emit("blend_old", old_samples(ctx, tmp)) ctx.emit("blend_files", {"outside.png": sibling or b""}) ctx.emit("blend_versions", sorted(made.keys())) shutil.rmtree(tmp, ignore_errors=True) diff --git a/tools/fixtures/docs_blend.py b/tools/fixtures/docs_blend.py new file mode 100644 index 0000000..e8f59f1 --- /dev/null +++ b/tools/fixtures/docs_blend.py @@ -0,0 +1,73 @@ +# Docs inputs for the .blend section of docs/guide/scene.md (tools/fixtures.py; tools/docs_check.py explains the +# inputs): a small rig saved zstd-compressed by the nixpkgs Blender (a two-bone armature, a skinned cylinder with a +# shape key, a bone action and a Principled material). +# tests/gen/docs_blend.luau { files = { ["rig.blend"] = bytes }, vars = { riggedBlendBytes = "rig.blend" } } +import importlib.util, os, shutil, subprocess, tempfile + +INPUTS = ["tools/docs_check.py"] + +SCRIPT = r''' +import bpy, sys, math +out = sys.argv[sys.argv.index("--") + 1] +bpy.ops.wm.read_factory_settings(use_empty=True) +arm = bpy.data.armatures.new("RigData") +rig = bpy.data.objects.new("Rig", arm) +bpy.context.scene.collection.objects.link(rig) +bpy.context.view_layer.objects.active = rig +bpy.ops.object.mode_set(mode="EDIT") +a = arm.edit_bones.new("lower") +a.head, a.tail = (0, 0, 0), (0, 0, 1) +b = arm.edit_bones.new("upper") +b.head, b.tail, b.parent, b.use_connect = (0, 0, 1), (0, 0, 2), a, True +bpy.ops.object.mode_set(mode="OBJECT") +ring = [(math.cos(k * math.pi / 3) * 0.3, math.sin(k * math.pi / 3) * 0.3) for k in range(6)] +verts = [(x, y, z) for z in (0, 1, 2) for x, y in ring] +faces = [(r * 6 + k, r * 6 + (k + 1) % 6, (r + 1) * 6 + (k + 1) % 6, (r + 1) * 6 + k) for r in range(2) for k in range(6)] +me = bpy.data.meshes.new("Tube") +me.from_pydata(verts, [], faces) +mat = bpy.data.materials.new("Skin") +mat.use_nodes = True +bsdf = mat.node_tree.nodes["Principled BSDF"] +bsdf.inputs["Base Color"].default_value = (0.9, 0.6, 0.5, 1) +bsdf.inputs["Roughness"].default_value = 0.7 +me.materials.append(mat) +tube = bpy.data.objects.new("Tube", me) +bpy.context.scene.collection.objects.link(tube) +tube.parent = rig +tube.modifiers.new("Armature", "ARMATURE").object = rig +lo, up = tube.vertex_groups.new(name="lower"), tube.vertex_groups.new(name="upper") +for i in range(18): + lo.add([i], 1.0 - (i // 6) * 0.5, "REPLACE") + up.add([i], (i // 6) * 0.5, "REPLACE") +tube.shape_key_add(name="Basis") +bulge = tube.shape_key_add(name="Bulge") +for p in bulge.data: + p.co = (p.co[0] * 1.4, p.co[1] * 1.4, p.co[2]) +pb = rig.pose.bones["upper"] +for f, angle in ((1, 0.0), (12, 0.8), (24, 0.0)): + pb.rotation_quaternion = (math.cos(angle / 2), math.sin(angle / 2), 0, 0) + pb.keyframe_insert("rotation_quaternion", frame=f) +bpy.context.scene.frame_set(1) +bpy.ops.wm.save_as_mainfile(filepath=out, compress=True) +''' + + +def generate(ctx): + spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py")) + check = importlib.util.module_from_spec(spec) + spec.loader.exec_module(check) + tmp = tempfile.mkdtemp(prefix="formats-docs-blend-") + try: + script = os.path.join(tmp, "make.py") + with open(script, "w") as f: + f.write(SCRIPT) + out = os.path.join(tmp, "rig.blend") + exe = shutil.which("blender") + cmd = [exe] if exe else ["nix", "shell", "nixpkgs#blender", "-c", "blender"] + env = dict(os.environ) + env.pop("LD_LIBRARY_PATH", None) + subprocess.run(cmd + ["-b", "--factory-startup", "--python", script, "--", out], capture_output=True, check=True, timeout=900, env=env) + files = {"rig.blend": open(out, "rb").read()} + finally: + shutil.rmtree(tmp, ignore_errors=True) + check.emit_inputs(ctx, files, {"riggedBlendBytes": "rig.blend"}) From 08f3b1c5bd9b4ed02692678e92de8a3d5894e533 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 19:26:34 -0600 Subject: [PATCH 3/4] model/blend: compressed .blend sniffing (gzip peek, zstd up to 4 MB) so F.model.load finds them --- src/Rosetta/Registry.luau | 2 +- src/Rosetta/model/blend/init.luau | 21 +++++++++++++++++++-- tests/model/blend.luau | 16 ++++++++++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/src/Rosetta/Registry.luau b/src/Rosetta/Registry.luau index 162c258..94ca055 100644 --- a/src/Rosetta/Registry.luau +++ b/src/Rosetta/Registry.luau @@ -740,7 +740,7 @@ local list: { Entry } = { path = "model/blend", extensions = { "blend" }, mime = { "application/x-blender" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, load = function() return require("@rosetta/model/blend") diff --git a/src/Rosetta/model/blend/init.luau b/src/Rosetta/model/blend/init.luau index 2c341ee..0f14405 100644 --- a/src/Rosetta/model/blend/init.luau +++ b/src/Rosetta/model/blend/init.luau @@ -13,6 +13,8 @@ local Err = require("@rosetta/core/Err") local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") local Blend = require("@rosetta/containers/Blend") +local Deflate = require("@rosetta/codecs/compress/Deflate") +local Zstd = require("@rosetta/codecs/compress/Zstd") local Read = require("@rosetta/model/blend/Read") local Anim = require("@rosetta/model/blend/Anim") @@ -22,7 +24,7 @@ local BlendFormat = { category = "model", extensions = { "blend" }, mime = { "application/x-blender" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, } @@ -41,10 +43,25 @@ export type DecodeOptions = { } -- ------------------------------------------------------------------------------------------------ sniff +-- compressed files: gzip by peeking the first bytes; zstd by decompressing files up to 4 MB (larger zstd streams +-- score 0.5: picked for model loads, the archive otherwise). Ties with archive/gzip and archive/zst go to the extension. function BlendFormat.sniff(r: Bytes.Reader): number - if r:peek(7) == "BLENDER" then + local head = r:peek(7) + if head == "BLENDER" then return 1 end + local n = r.limit - r.base + if string.sub(head, 1, 3) == "\31\139\8" then + local inner = Deflate.peek(r.buf, r.base, n, 7) + return if inner and buffer.tostring(inner) == "BLENDER" then 1 else 0 + end + if string.sub(head, 1, 4) == Zstd.MAGIC then + if n > 4 * 2 ^ 20 then + return 0.5 + end + local out = Zstd.decompress(r.buf, r.base, n, { verify = false }) + return if out and buffer.len(out) >= 7 and buffer.readstring(out, 0, 7) == "BLENDER" then 1 else 0 + end return 0 end diff --git a/tests/model/blend.luau b/tests/model/blend.luau index f3e01cb..31d4fd9 100644 --- a/tests/model/blend.luau +++ b/tests/model/blend.luau @@ -620,6 +620,22 @@ if cur then t:check(s and s.kind == "scene", "F.load") end +-- compressed files: by content for model loads, by extension otherwise +for _, c in Sets.cur do + if string.find(c.name, "_z%.blend$") then + local b = buffer.fromstring(c.data) + local s = F.model.load(b) + t:check(s and s.meta.source.compression == "zstd", "F.model.load of a zstd .blend") + t:eq(F.detect(b, { name = "x.blend" }), "blend", "F.detect of a zstd .blend by name") + end +end +for _, c in Sets["293"] do + if string.find(c.name, "_z%.blend$") then + local s = F.model.load(buffer.fromstring(c.data)) + t:check(s and s.meta.source.compression == "gzip", "F.model.load of a gzip .blend") + end +end + -- errors local function code(data: string): string? local s, e = decode(data) From be397639eac64208e68447c55d343036c2d2267d Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 19:44:35 -0600 Subject: [PATCH 4/4] model/blend: comments to specs only, a type fix; build: regenerate bundles --- build/Rosetta.luau | 3690 ++++++++++++++++++++++++++ build/Rosetta.luau.linemap.json | 1078 ++++---- build/rosetta.lua | 3690 ++++++++++++++++++++++++++ build/rosetta.lua.linemap.json | 1078 ++++---- src/Rosetta/containers/Blend.luau | 11 - src/Rosetta/model/blend/Anim.luau | 3 - src/Rosetta/model/blend/Mesh.luau | 10 - src/Rosetta/model/blend/Normals.luau | 2 - src/Rosetta/model/blend/Read.luau | 11 +- 9 files changed, 8471 insertions(+), 1102 deletions(-) diff --git a/build/Rosetta.luau b/build/Rosetta.luau index 7d956b2..d99e923 100644 --- a/build/Rosetta.luau +++ b/build/Rosetta.luau @@ -1604,6 +1604,18 @@ local list: { Entry } = { return __include("model/b3d") end, }, + { + name = "blend", + category = "model", + path = "model/blend", + extensions = { "blend" }, + mime = { "application/x-blender" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, + load = function() + return __include("model/blend") + end, + }, { name = "bsp", category = "model", @@ -107589,6 +107601,745 @@ end return Avi end +__FILES["containers/Blend"] = function() + +-- 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 = __include("core/Err") +local Deflate = __include("codecs/compress/Deflate") +local Zstd = __include("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 + +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 +} +type Struct = { name: string, index: number, size: number, fields: { Field }, byName: { [string]: Field } } +type Dna = { + names: { string }, + types: { string }, + lengths: { number }, + structs: { Struct }, -- 1-based; a block's sdna is 0-based + byName: { [string]: Struct }, +} +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) +} +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, +} +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 + +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 +end __FILES["containers/Chunks"] = function() -- containers/Chunks: the generic walker for chunked files (an id and a size per chunk, body, optional trailer and @@ -144442,6 +145193,2945 @@ function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, return scene, nil, nil end +return Read +end +__FILES["model/blend"] = function() + +-- model/blend: Blender .blend files (read only), every version from 2.4x to 5.x: plain, gzip or zstd compressed; +-- 32 / 64-bit pointers, either byte order; the 5.0+ header. New in rosetta (from the file layout, read through each +-- file's own SDNA). Supports: the scene's objects and collections, transforms with parent inverse and bone parents, +-- meshes of every storage generation (MFace, MPoly / MLoop, attribute layers, AttributeStorage) with UV maps, colour +-- attributes, custom normals, material slots; Principled BSDF materials; packed and external images; cameras; lights; +-- armatures, skins (vertex groups, top 4 weights), shape keys; actions sampled into channels. +-- Not supported: modifiers (listed in meta.source.modifiers), curves / text / metaballs / grease pencil / volumes, +-- NLA strips, drivers, constraints, f-curve modifiers, linked libraries, collection instances. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Blend = __include("containers/Blend") +local Deflate = __include("codecs/compress/Deflate") +local Zstd = __include("codecs/compress/Zstd") +local Read = __include("model/blend/Read") +local Anim = __include("model/blend/Anim") + +-- ------------------------------------------------------------------------------------------------ contract +local BlendFormat = { + name = "blend", + category = "model", + extensions = { "blend" }, + mime = { "application/x-blender" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +type DecodeOptions = { + triangulate: boolean?, -- default true (false: "polygons" primitives) + flipV: boolean?, -- default true (glTF's top-left UV origin) + collections: boolean?, -- collections as nodes (default true) + scene: string?, -- a scene by name (default: the file's current scene) + sampleStep: number?, -- frames between animation samples (default 1) + animations: boolean?, -- default true + resolve: ((uri: string) -> any)?, -- external images + files: { [string]: any }?, + maxBytes: number?, -- decompressed size limit (default 2^31) + maxVertices: number?, -- per mesh (default 2^25) +} + +-- ------------------------------------------------------------------------------------------------ sniff +-- compressed files: gzip by peeking the first bytes; zstd by decompressing files up to 4 MB (larger zstd streams +-- score 0.5: picked for model loads, the archive otherwise). Ties with archive/gzip and archive/zst go to the extension. +function BlendFormat.sniff(r: Bytes.Reader): number + local head = r:peek(7) + if head == "BLENDER" then + return 1 + end + local n = r.limit - r.base + if string.sub(head, 1, 3) == "\31\139\8" then + local inner = Deflate.peek(r.buf, r.base, n, 7) + return if inner and buffer.tostring(inner) == "BLENDER" then 1 else 0 + end + if string.sub(head, 1, 4) == Zstd.MAGIC then + if n > 4 * 2 ^ 20 then + return 0.5 + end + local out = Zstd.decompress(r.buf, r.base, n, { verify = false }) + return if out and buffer.len(out) >= 7 and buffer.readstring(out, 0, 7) == "BLENDER" then 1 else 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function BlendFormat.open(r: Bytes.Reader, opts: DecodeOptions?): (Blend.File?, Err.Err?) + return Blend.open(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes }) +end + +function BlendFormat.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?) + local f, err = BlendFormat.open(r, opts) + if not f then + return nil, err + end + local ok, scene, msg = pcall(Read.scene, f, opts) + if not ok then + return nil, Err.from(tostring(scene)) + end + if not scene then + return nil, Err.from(msg or "bad file") + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +BlendFormat.container = Blend +BlendFormat.evaluate = Anim.evaluate +BlendFormat.curves = Anim.curves +BlendFormat.ipo = Anim.ipo + +return BlendFormat +end +__FILES["model/blend/Anim"] = function() + +-- model/blend/Anim: Blender actions (legacy bAction.curves, and the layered actions of 4.4+: layers -> strips -> +-- keyframe data -> channel bags matched by the AnimData slot handle) and f-curve evaluation: constant, linear, +-- bezier (handles shortened so the segment stays a function of time, as Blender does) and the Penner easing modes +-- (elastic uses Penner's amplitude / period, which Blender scales differently); +-- constant or linear extrapolation. F-curve modifiers and NLA strips are not evaluated. +local Blend = __include("containers/Blend") + +local Anim = {} + +type Key = { + x: number, + y: number, + lx: number, -- left handle + ly: number, + rx: number, -- right handle + ry: number, + ipo: number, -- 0 constant, 1 linear, 2 bezier, 3.. easing (back, bounce, circ, cubic, elastic, expo, quad, quart, quint, sine) + easing: number, -- 0 auto, 1 in, 2 out, 3 in-out + back: number, + amplitude: number, + period: number, +} +type Curve = { path: string, index: number, keys: { Key }, extend: number, modifiers: number } + +local CONST, LIN, BEZ = 0, 1, 2 +local BACK, BOUNCE, CIRC, CUBIC, ELASTIC, EXPO, QUAD, QUART, QUINT, SINE = 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 + +-- ------------------------------------------------------------------------------------------------ reading +local function curve(f: Blend.File, fc: Blend.View): Curve? + local path = fc:cstring("rna_path") + if not path then + return nil + end + local keys: { Key } = {} + for _, b in fc:array("bezt", "BezTriple") do + local v = b:vec("vec") + if v and #v >= 9 then + table.insert(keys, { + lx = v[1], ly = v[2], x = v[4], y = v[5], rx = v[7], ry = v[8], + ipo = b:num("ipo") or BEZ, easing = b:num("easing") or 0, back = b:num("back") or 1.70158, + amplitude = b:num("amplitude") or 0.8, period = b:num("period") or 4.1, + }) + end + end + if #keys == 0 then + for _, p in fc:array("fpt", "FPoint") do + local v = p:vec("vec") + if v and #v >= 2 then + table.insert(keys, { x = v[1], y = v[2], lx = v[1], ly = v[2], rx = v[1], ry = v[2], ipo = LIN, easing = 0, back = 0, amplitude = 0, period = 0 }) + end + end + end + if #keys == 0 then + return nil + end + table.sort(keys, function(a: Key, b: Key): boolean + return a.x < b.x + end) + local mods = fc:list("modifiers") + return { path = path, index = fc:num("array_index") or 0, keys = keys, extend = fc:num("extend") or 0, modifiers = #mods } +end + +function Anim.curves(f: Blend.File, adt: Blend.View?): ({ Curve }?, string?) + if not adt then + return nil, nil + end + local act = adt:deref("action", 0, "bAction") + if not act then + return nil, nil + end + local list: { Blend.View } = act:list("curves", "FCurve") + if #list == 0 and act:has("layer_array") then + local handle = adt:num("slot_handle") or 0 + local datas = act:pointers("strip_keyframe_data_array", act:num("strip_keyframe_data_array_num")) + for _, la in act:pointers("layer_array", act:num("layer_array_num")) do + local lblk = la and Blend.resolve(f, la, act.block) + local layer = lblk and Blend.struct(f, lblk, 0, "ActionLayer") + if layer then + for _, sa in layer:pointers("strip_array", layer:num("strip_array_num")) do + local sblk = sa and Blend.resolve(f, sa, act.block) + local strip = sblk and Blend.struct(f, sblk, 0, "ActionStrip") + local di = strip and strip:num("data_index") + local dblk = di and datas[di + 1] and Blend.resolve(f, datas[di + 1], act.block) + local kd = dblk and Blend.struct(f, dblk, 0, "ActionStripKeyframeData") + if kd then + for _, ba in kd:pointers("channelbag_array", kd:num("channelbag_array_num")) do + local bblk = ba and Blend.resolve(f, ba, act.block) + local bag = bblk and (Blend.struct(f, bblk, 0, "ActionChannelBag") or Blend.struct(f, bblk, 0, "ActionChannelbag")) + if bag and (bag:num("slot_handle") or 0) == handle then + for _, ca in bag:pointers("fcurve_array", bag:num("fcurve_array_num")) do + local cblk = ca and Blend.resolve(f, ca, act.block) + local fc = cblk and Blend.struct(f, cblk, 0, "FCurve") + if fc then + table.insert(list, fc) + end + end + end + end + end + end + end + end + end + local out: { Curve } = {} + for _, fc in list do + local c = curve(f, fc) + if c then + table.insert(out, c) + end + end + return out, act:idName() +end + +-- pre-2.5 IPO curves (Object.ipo / Key.ipo): the curve's adrcode picks the channel; object rotations are in units of +-- 10 degrees; the interpolation and extrapolation (0 constant, 1 linear; cyclic ones as constant) are per curve +local OB_ADR: { [number]: { any } } = { + [1] = { "location", 0 }, [2] = { "location", 1 }, [3] = { "location", 2 }, + [4] = { "delta_location", 0 }, [5] = { "delta_location", 1 }, [6] = { "delta_location", 2 }, + [7] = { "rotation_euler", 0, math.pi / 18 }, [8] = { "rotation_euler", 1, math.pi / 18 }, [9] = { "rotation_euler", 2, math.pi / 18 }, + [10] = { "delta_rotation_euler", 0, math.pi / 18 }, [11] = { "delta_rotation_euler", 1, math.pi / 18 }, [12] = { "delta_rotation_euler", 2, math.pi / 18 }, + [13] = { "scale", 0 }, [14] = { "scale", 1 }, [15] = { "scale", 2 }, +} + +function Anim.ipo(f: Blend.File, ipo: Blend.View?, keyNames: { string }?): ({ Curve }?, string?) + if not ipo then + return nil, nil + end + local out: { Curve } = {} + for _, icu in ipo:list("curve", "IpoCurve") do + local adr = icu:num("adrcode") or -1 + local path, index, scale + if keyNames then + if adr >= 1 and keyNames[adr + 1] then + path, index, scale = 'key_blocks["' .. keyNames[adr + 1] .. '"].value', 0, 1 + end + else + local m = OB_ADR[adr] + if m then + path, index, scale = m[1], m[2], m[3] or 1 + end + end + if path then + local ipoMode = icu:num("ipo") or BEZ + local keys: { Key } = {} + for _, b in icu:array("bezt", "BezTriple") do + local v = b:vec("vec") + if v and #v >= 9 then + table.insert(keys, { + lx = v[1], ly = v[2] * scale, x = v[4], y = v[5] * scale, rx = v[7], ry = v[8] * scale, + ipo = if ipoMode == CONST or ipoMode == LIN then ipoMode else BEZ, easing = 0, back = 1.70158, amplitude = 0.8, period = 4.1, + }) + end + end + local n = math.min(#keys, icu:num("totvert") or #keys) + while #keys > n do + table.remove(keys) + end + if #keys > 0 then + table.sort(keys, function(a: Key, b: Key): boolean + return a.x < b.x + end) + table.insert(out, { path = path, index = index, keys = keys, extend = if (icu:num("extrap") or 0) == 1 then 1 else 0, modifiers = 0 }) + end + end + end + local _ = f + return out, ipo:idName() +end + +-- ------------------------------------------------------------------------------------------------ evaluation +local function bezierAt(p0: number, p1: number, p2: number, p3: number, t: number): number + local u = 1 - t + return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3 +end + +local function bezier(a: Key, b: Key, x: number): number + local x0, y0, x3, y3 = a.x, a.y, b.x, b.y + local x1, y1, x2, y2 = a.rx, a.ry, b.lx, b.ly + -- handles longer than the segment are scaled down together so x(t) stays monotonic + local len = x3 - x0 + local h1x, h1y = x1 - x0, y1 - y0 + local h2x, h2y = x2 - x3, y2 - y3 + local l1, l2 = math.abs(h1x), math.abs(h2x) + if l1 + l2 > len and l1 + l2 > 0 then + local fac = len / (l1 + l2) + x1, y1 = x0 + h1x * fac, y0 + h1y * fac + x2, y2 = x3 + h2x * fac, y3 + h2y * fac + end + local lo, hi = 0, 1 + local t = (x - x0) / len + for _ = 1, 60 do + local xt = bezierAt(x0, x1, x2, x3, t) + if math.abs(xt - x) < 1e-9 then + break + end + if xt < x then + lo = t + else + hi = t + end + local d = 3 * (1 - t) * (1 - t) * (x1 - x0) + 6 * (1 - t) * t * (x2 - x1) + 3 * t * t * (x3 - x2) + local nt = if d ~= 0 then t - (xt - x) / d else -1 + t = if nt > lo and nt < hi then nt else (lo + hi) / 2 + end + return bezierAt(y0, y1, y2, y3, t) +end + +local function bounceOut(t: number, b: number, c: number, d: number): number + t /= d + if t < 1 / 2.75 then + return c * (7.5625 * t * t) + b + elseif t < 2 / 2.75 then + t -= 1.5 / 2.75 + return c * (7.5625 * t * t + 0.75) + b + elseif t < 2.5 / 2.75 then + t -= 2.25 / 2.75 + return c * (7.5625 * t * t + 0.9375) + b + end + t -= 2.625 / 2.75 + return c * (7.5625 * t * t + 0.984375) + b +end + +local function easeIn(ipo: number, t: number, a: Key): number -- 0..1 -> 0..1 + if ipo == BACK then + local s = a.back + return t * t * ((s + 1) * t - s) + elseif ipo == BOUNCE then + return 1 - bounceOut(1 - t, 0, 1, 1) + elseif ipo == CIRC then + return 1 - math.sqrt(math.max(0, 1 - t * t)) + elseif ipo == CUBIC then + return t * t * t + elseif ipo == ELASTIC then + if t <= 0 or t >= 1 then + return t + end + local p = if a.period > 0 then a.period / 10 else 0.3 + local amp = a.amplitude + local s + if amp < 1 then + amp, s = 1, p / 4 + else + s = p / (2 * math.pi) * math.asin(1 / amp) + end + t -= 1 + return -(amp * 2 ^ (10 * t) * math.sin((t - s) * (2 * math.pi) / p)) + elseif ipo == EXPO then + return (2 ^ (10 * (t - 1)) - 2 ^ -10) / (1 - 2 ^ -10) -- normalized to run from 0 to 1, as Blender's does + elseif ipo == QUAD then + return t * t + elseif ipo == QUART then + return t * t * t * t + elseif ipo == QUINT then + return t * t * t * t * t + elseif ipo == SINE then + return 1 - math.cos(t * math.pi / 2) + end + return t +end + +local function ease(a: Key, b: Key, x: number): number + local t = (x - a.x) / (b.x - a.x) + local mode = a.easing + if mode == 0 then + mode = if a.ipo == BACK or a.ipo == BOUNCE or a.ipo == ELASTIC then 2 else 1 + end + local s + if mode == 1 then + s = easeIn(a.ipo, t, a) + elseif mode == 2 then + s = 1 - easeIn(a.ipo, 1 - t, a) + elseif t < 0.5 then + s = easeIn(a.ipo, t * 2, a) / 2 + else + s = 1 - easeIn(a.ipo, (1 - t) * 2, a) / 2 + end + return a.y + (b.y - a.y) * s +end + +function Anim.evaluate(c: Curve, x: number): number + local keys = c.keys + local n = #keys + local first, last = keys[1], keys[n] + if x <= first.x then + if c.extend == 1 and n > 0 and first.ipo ~= CONST then + if first.ipo == BEZ and first.lx ~= first.x then + return first.y + (x - first.x) * (first.y - first.ly) / (first.x - first.lx) + elseif n > 1 and keys[2].x ~= first.x then + return first.y + (x - first.x) * (keys[2].y - first.y) / (keys[2].x - first.x) + end + end + return first.y + end + if x >= last.x then + local prev = keys[n - 1] + if c.extend == 1 and n > 1 and prev.ipo ~= CONST then + if last.ipo == BEZ and last.rx ~= last.x then + return last.y + (x - last.x) * (last.ry - last.y) / (last.rx - last.x) + elseif last.x ~= prev.x then + return last.y + (x - last.x) * (last.y - prev.y) / (last.x - prev.x) + end + end + return last.y + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = (lo + hi) // 2 + if keys[mid].x <= x then + lo = mid + else + hi = mid + end + end + local a, b = keys[lo], keys[hi] + if b.x <= a.x or a.ipo == CONST then + return a.y + elseif a.ipo == LIN then + return a.y + (b.y - a.y) * (x - a.x) / (b.x - a.x) + elseif a.ipo == BEZ then + return bezier(a, b, x) + end + return ease(a, b, x) +end + +function Anim.range(curves: { Curve }): (number, number) + local lo, hi = math.huge, -math.huge + for _, c in curves do + lo = math.min(lo, c.keys[1].x) + hi = math.max(hi, c.keys[#c.keys].x) + end + return lo, hi +end + +function Anim.split(path: string): (string?, string?, string) + local kind, name, rest = string.match(path, '^(%w[%w_%.]-)%["(.-)"%]%.([%w_]+)$') + if kind and name and rest then + name = string.gsub(name, '\\(.)', "%1") + return kind, name, rest + end + return nil, nil, path +end + +return Anim +end +__FILES["model/blend/Material"] = function() + +-- model/blend/Material: Blender materials to Scene PBR materials. With nodes: the Principled BSDF (the one feeding the +-- material output, else the first): Base Color, Metallic, Roughness, Alpha, Emission (Color) x Emission Strength +-- (KHR_materials_emissive_strength above 1, as Blender's glTF exporter writes it), images linked directly to Base +-- Color / Emission and through a Normal Map node to Normal (its Strength as the scale), a Separate RGB / Color node to +-- Roughness (G) and Metallic (B), UV Map nodes for the texCoord. Without nodes (or before 2.8 without a +-- Principled node): Material.r / g / b / alpha, metallic, roughness. Images: packed files as encoded bytes, external +-- ones as uris (with the bytes when opts.files / opts.resolve has them). +local Blend = __include("containers/Blend") +local Types = __include("Types") + +local Material = {} + +type Ctx = { f: Blend.File, scene: Types.Scene, materials: { [any]: number }, textures: { [any]: number }, opts: any, meta: any } + +local readu8, readstring = buffer.readu8, buffer.readstring + +local function sniffMime(b: buffer, o: number, n: number, path: string?): string? + if n >= 8 and readstring(b, o, 8) == "\137PNG\r\n\26\n" then + return "image/png" + elseif n >= 3 and readu8(b, o) == 0xFF and readu8(b, o + 1) == 0xD8 then + return "image/jpeg" + elseif n >= 12 and readstring(b, o, 4) == "RIFF" and readstring(b, o + 8, 4) == "WEBP" then + return "image/webp" + elseif n >= 2 and readstring(b, o, 2) == "BM" then + return "image/bmp" + elseif n >= 4 and readstring(b, o, 4) == "\118\47\49\1" then + return "image/x-exr" + end + local ext = path and string.lower(string.match(path, "%.(%w+)$") or "") + local byExt = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", exr = "image/x-exr", hdr = "image/vnd.radiance", webp = "image/webp", tif = "image/tiff", tiff = "image/tiff" } + return if ext then byExt[ext] else nil +end + +local function fetch(ctx: Ctx, uri: string): buffer? + local opts = ctx.opts + local v: any = nil + if type(opts.files) == "table" then + v = opts.files[uri] + if v == nil then + v = opts.files[string.match(uri, "[^/\\]+$") or uri] + end + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = if ok then res else nil + end + if type(v) == "string" then + return buffer.fromstring(v) + end + return if type(v) == "buffer" then v else nil +end + +local function texture(ctx: Ctx, img: Blend.View, sampler: Types.Sampler?): number? + local f = ctx.f + local key = img.block and img.block.addr + if key ~= nil and ctx.textures[key] then + return ctx.textures[key] + end + local name = img:idName() + -- the path field keeps its DNA name "name" (char[1024]) in every version + local pf0 = img.struct.byName.filepath or img.struct.byName.name + local path = if pf0 and pf0.size >= 256 then img:str(pf0.name) else nil + local pf = img:deref("packedfile", 0, "PackedFile") + if not pf then + for _, ipf in img:list("packedfiles", "ImagePackedFile") do + pf = ipf:deref("packedfile", 0, "PackedFile") + if pf then + break + end + end + end + local tex: Types.Texture = { name = name, sampler = sampler } + if pf then + local blk = pf:target("data") + local size = pf:num("size") or 0 + if blk then + local n = math.min(size, blk.size) + local data = buffer.create(n) + buffer.copy(data, 0, f.buf, blk.offset, n) + tex.data = data + tex.mime = sniffMime(data, 0, n, path) + end + end + if path and path ~= "" then + local uri = string.gsub(path, "^//", "") + uri = string.gsub(uri, "\\", "/") + if not tex.data then + tex.uri = uri + local data = fetch(ctx, uri) + if data then + tex.data = data + tex.mime = sniffMime(data, 0, buffer.len(data), uri) + else + tex.mime = sniffMime(buffer.create(0), 0, 0, uri) + end + end + tex.extras = { blend = { filepath = path } } + end + if not tex.data and not tex.uri then + tex.extras = { blend = { generated = true } } + end + table.insert(ctx.scene.textures, tex) + local idx = #ctx.scene.textures + if key ~= nil then + ctx.textures[key] = idx + end + return idx +end + +type Node = { view: Blend.View, idname: string, inputs: { [string]: Blend.View }, outputs: { [any]: string } } +type Graph = { nodes: { [any]: Node }, links: { [any]: { node: Node, socket: string } } } -- links by tosock addr + +local function graph(tree: Blend.View): Graph + local g: Graph = { nodes = {}, links = {} } + for _, n in tree:list("nodes", "bNode") do + local node: Node = { view = n, idname = n:str("idname") or "", inputs = {}, outputs = {} } + for _, s in n:list("inputs", "bNodeSocket") do + local id = s:str("identifier") or s:str("name") or "" + local nm = s:str("name") or id + node.inputs[nm] = s + if node.inputs[id] == nil then + node.inputs[id] = s + end + end + for _, s in n:list("outputs", "bNodeSocket") do + if s.block then + node.outputs[s.block.addr] = s:str("name") or "" + end + end + if n.block then + g.nodes[n.block.addr] = node + end + end + for _, l in tree:list("links", "bNodeLink") do + local from, fs, to = l:ptr("fromnode"), l:ptr("fromsock"), l:ptr("tosock") + local fn = from and g.nodes[from] + if fn and to ~= nil and bit32.band(l:num("flag") or 0, 0x10) == 0 then + g.links[to] = { node = fn, socket = (fs and fn.outputs[fs]) or "" } + end + end + return g +end + +local function input(n: Node, ...: string): Blend.View? + for _, k in { ... } do + local s = n.inputs[k] + if s then + return s + end + end + return nil +end + +local function link(g: Graph, s: Blend.View?): { node: Node, socket: string }? + if not s or not s.block then + return nil + end + return g.links[s.block.addr] +end + +local function value(s: Blend.View?, kind: string): any + if not s then + return nil + end + if kind == "rgba" then + local v = s:deref("default_value", 0, "bNodeSocketValueRGBA") + return v and v:vec("value") + end + local v = s:deref("default_value", 0, "bNodeSocketValueFloat") + return v and v:num("value") +end + +local function imageRef(ctx: Ctx, g: Graph, uvNames: any, s: Blend.View?, through: string?): (Types.TextureRef?, Node?) + local l = link(g, s) + if not l then + return nil, nil + end + local n = l.node + if through and n.idname == through then + local inner = input(n, "Color", "Image") + local ref, tn = imageRef(ctx, g, uvNames, inner, nil) + return ref, if ref then n else tn + end + if n.idname ~= "ShaderNodeTexImage" then + return nil, n + end + local img = n.view:deref("id", 0, "Image") + if not img then + return nil, n + end + local sampler: Types.Sampler = {} + local custom = false + local st = n.view:deref("storage", 0, "NodeTexImage") + if st then + local interp, ext = st:num("interpolation") or 0, st:num("extension") or 0 + custom = interp == 1 or (ext >= 1 and ext <= 3) + if interp == 1 then + sampler.filter = "nearest" + sampler.minFilter = "nearest" + end + if ext == 1 or ext == 2 then + sampler.wrapS, sampler.wrapT = "clamp", "clamp" + elseif ext == 3 then + sampler.wrapS, sampler.wrapT = "mirror", "mirror" + end + end + local t = texture(ctx, img, if custom then sampler else nil) + if not t then + return nil, n + end + local ref: Types.TextureRef = { texture = t } + local vec = link(g, input(n, "Vector")) + if vec and vec.node.idname == "ShaderNodeUVMap" then + local uvs = vec.node.view:deref("storage", 0, "NodeShaderUVMap") + local name = uvs and uvs:str("uv_map") + if name and uvNames and uvNames[name] then + ref.texCoord = uvNames[name] + end + end + return ref, n +end + +local function principled(g: Graph): Node? + local first: Node? = nil + for _, n in g.nodes do + if n.idname == "ShaderNodeOutputMaterial" then + local l = link(g, n.inputs.Surface) + if l and l.node.idname == "ShaderNodeBsdfPrincipled" then + return l.node + end + elseif n.idname == "ShaderNodeBsdfPrincipled" and (first == nil or (n.view.block and first.view.block and n.view.block.index < first.view.block.index)) then + first = n + end + end + return first +end + +local function emissive(m: Types.Material, color: { number }, strength: number) + local e = { color[1] * strength, color[2] * strength, color[3] * strength } + local mx = math.max(e[1], e[2], e[3]) + if mx > 1 then + m.extensions = m.extensions or {} + ;(m.extensions :: any).KHR_materials_emissive_strength = { emissiveStrength = mx } + e = { e[1] / mx, e[2] / mx, e[3] / mx } + end + m.emissive = e +end + +function Material.get(ctx: Ctx, mv: Blend.View): number + local key = mv.block and mv.block.addr + if key ~= nil and ctx.materials[key] then + return ctx.materials[key] + end + local f = ctx.f + local m = Types.Scene.material(mv:idName()) + local extras: { [string]: any } = {} + m.extras = { blend = extras } + local legacyAlpha = mv:num("a", "alpha") or 1 + m.baseColor = { mv:num("r") or 0.8, mv:num("g") or 0.8, mv:num("b") or 0.8, legacyAlpha } + m.metallic = mv:num("metallic") or 0 + m.roughness = mv:num("roughness") or 0.5 + if f.version < 280 then + m.roughness = 0.5 + end + m.doubleSided = bit32.band(mv:num("blend_flag") or 0, 4) == 0 + local tree = mv:deref("nodetree", 0, "bNodeTree") + local useNodes = (mv:num("use_nodes") or 0) ~= 0 or f.version >= 500 + local bsdf = nil + local g: Graph? = nil + if tree and useNodes then + g = graph(tree) + bsdf = principled(g :: Graph) + end + if bsdf and g then + extras.principled = true + local uvNames = ctx.meta.uvNames + local base = value(input(bsdf, "Base Color"), "rgba") + local alpha = value(input(bsdf, "Alpha"), "float") or 1 + if base then + m.baseColor = { base[1], base[2], base[3], alpha } + end + m.metallic = value(input(bsdf, "Metallic"), "float") or m.metallic + m.roughness = value(input(bsdf, "Roughness"), "float") or m.roughness + local bref = imageRef(ctx, g, uvNames, input(bsdf, "Base Color"), nil) + if bref then + m.baseColorTexture = bref + m.baseColor = { 1, 1, 1, alpha } + end + local aref = imageRef(ctx, g, uvNames, input(bsdf, "Alpha"), nil) + if aref and not m.baseColorTexture then + m.baseColorTexture = aref + end + local nref, nnode = imageRef(ctx, g, uvNames, input(bsdf, "Normal"), "ShaderNodeNormalMap") + if nref then + nref.scale = if nnode then value(nnode.inputs.Strength, "float") or 1 else 1 + m.normalTexture = nref + end + local rl = link(g, input(bsdf, "Roughness")) + local ml = link(g, input(bsdf, "Metallic")) + local sep = (rl and rl.node) or (ml and ml.node) + if sep and (sep.idname == "ShaderNodeSeparateRGB" or sep.idname == "ShaderNodeSeparateColor") then + local mref = imageRef(ctx, g, uvNames, input(sep, "Image", "Color"), nil) + if mref then + m.metallicRoughnessTexture = mref + if rl then + m.roughness = 1 + end + if ml then + m.metallic = 1 + end + end + end + local es = input(bsdf, "Emission Color", "Emission") + local ecol = value(es, "rgba") or { 0, 0, 0, 1 } + local strength = value(input(bsdf, "Emission Strength"), "float") or 1 + local eref = imageRef(ctx, g, uvNames, es, nil) + if eref then + m.emissiveTexture = eref + ecol = { 1, 1, 1, 1 } + end + emissive(m, ecol, strength) + if not eref and m.emissive[1] == 0 and m.emissive[2] == 0 and m.emissive[3] == 0 then + m.emissive = { 0, 0, 0 } + end + local alphaLinked = link(g, input(bsdf, "Alpha")) ~= nil + if alpha < 1 or alphaLinked then + local bm = mv:num("blend_method") or 0 + if bm == 3 then + m.alphaMode = "mask" + m.alphaCutoff = mv:num("alpha_threshold") or 0.5 + else + m.alphaMode = "blend" + end + end + else + extras.legacy = true + if legacyAlpha < 1 then + m.alphaMode = "blend" + end + end + table.insert(ctx.scene.materials, m) + local idx = #ctx.scene.materials + if key ~= nil then + ctx.materials[key] = idx + end + return idx +end + +return Material +end +__FILES["model/blend/Mesh"] = function() + +-- model/blend/Mesh: a Blender Mesh ID of any storage generation to one polygon form (positions, faces as corner lists, +-- corner / point attributes, deform weights). Generations: MFace tessellated faces (< 2.63, and the 2.7x "legacy mesh +-- format" save); MVert / MEdge / MPoly / MLoop with MLoopUV / MLoopCol layers (2.63 - 3.x); CustomData attribute +-- layers ("position", ".edge_verts", ".corner_vert", poly_offset_indices, 3.x - 4.x); AttributeStorage (5.x). +local Blend = __include("containers/Blend") + +local Mesh = {} + +type Layer = { + name: string, + domain: string, -- "point" | "edge" | "face" | "corner" | "tess" + kind: string, -- a generic kind (float, float2, float3, color, bytecolor, int32, int2, int8, bool, short2, quat, + -- float4x4) or an SDNA struct name (MVert, MEdge, MPoly, MLoop, MFace, MTFace, MCol, MLoopUV, MDeformVert) + offset: number, -- data start in file.buf + bytes: number, -- data bytes available + elem: number, -- bytes per element + single: boolean?, -- one value for every element (AttributeStorage single storage) + activeRender: boolean?, + cdtype: number?, +} + +type Color = { name: string, domain: string, data: buffer } -- f32 x 4 (linear) per point or corner +type Poly = { + name: string?, + nv: number, + nf: number, + nc: number, + pos: buffer, -- f32 x 3 per vertex + cornerVert: buffer, -- u32 per corner + faceStart: buffer, -- u32 per face + 1 + faceMat: buffer, -- i32 per face + faceSmooth: buffer, -- u8 per face + uvs: { { name: string, data: buffer } }, -- f32 x 2 per corner + activeUV: number, -- 1-based index into uvs (the active render layer) + colors: { Color }, + customNormals: buffer?, -- f32 x 3 per corner (free custom normals) + encodedNormals: buffer?, -- i16 x 2 per corner (custom normals in Blender's corner-fan space) + sharp: { [number]: boolean }, -- edge keys (min * nv + max) that split smooth fans + autoSmooth: number?, -- radians (Mesh.smoothresh with ME_AUTOSMOOTH, before 4.1) + weights: { { number } }?, -- per vertex: def_nr, weight, def_nr, weight, ... + generation: string, -- "mface" | "mpoly" | "attributes" | "storage" + layers: { Layer }, +} + +local CD_KIND: { [number]: string } = { + [0] = "MVert", [2] = "MDeformVert", [3] = "MEdge", [4] = "MFace", [5] = "MTFace", [6] = "MCol", [10] = "float", + [11] = "int32", [16] = "MLoopUV", [17] = "bytecolor", [25] = "MPoly", [26] = "MLoop", [41] = "short2", [45] = "int8", + [46] = "int2", [47] = "color", [48] = "float3", [49] = "float2", [50] = "bool", [52] = "quat", +} +-- AttributeStorage (5.x) data types and domains +local ATTR_KIND: { [number]: string } = { + [0] = "bool", [1] = "int8", [2] = "short2", [3] = "int32", [4] = "int2", [5] = "float", [6] = "float2", [7] = "float3", + [8] = "float4x4", [9] = "bytecolor", [10] = "color", [11] = "quat", +} +local DOMAIN: { [number]: string } = { [0] = "point", [1] = "edge", [2] = "face", [3] = "corner" } +local SIZE: { [string]: number } = { + bool = 1, int8 = 1, short2 = 4, int32 = 4, int2 = 8, float = 4, float2 = 8, float3 = 12, float4x4 = 64, bytecolor = 4, + color = 16, quat = 16, +} +local ME_SMOOTH = 1 +local ME_SHARP = 0x200 +local ME_AUTOSMOOTH = 0x20 + +local readu8, readi16 = buffer.readu8, buffer.readi16 + +-- sRGB byte -> linear +local SRGB = table.create(256, 0) +for i = 0, 255 do + local c = i / 255 + SRGB[i + 1] = if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4 +end +Mesh.SRGB = SRGB + +local function customData(f: Blend.File, me: Blend.View, names: { string }, domain: string, out: { Layer }) + local cd = me:sub(table.unpack(names)) + if not cd then + return + end + local layers = cd:array("layers", "CustomDataLayer") + local n = cd:num("totlayer") or #layers + for i = 1, math.min(n, #layers) do + local L = layers[i] + local t = L:num("type") or -1 + local kind = CD_KIND[t] + local blk = L:target("data") + if kind and blk then + local st = f.dna.byName[kind] + local elem = if st then st.size else SIZE[kind] or 0 + if elem > 0 then + table.insert(out, { + name = L:str("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, + elem = elem, activeRender = (L:num("active_rnd") or 0) == 0, cdtype = t, + }) + end + end + end +end + +local function storage(f: Blend.File, me: Blend.View, out: { Layer }) + local st = me:sub("attribute_storage") + if not st then + return + end + local attrs = st:array("dna_attributes", "Attribute") + local n = st:num("dna_attributes_num") or #attrs + for i = 1, math.min(n, #attrs) do + local a = attrs[i] + local kind = ATTR_KIND[a:num("data_type") or -1] + local domain = DOMAIN[a:num("domain") or -1] + local single = (a:num("storage_type") or 0) == 1 + local holder = a:deref("data", 0, if single then "AttributeSingle" else "AttributeArray") + local blk = holder and holder:target("data") + if kind and domain and blk then + table.insert(out, { + name = a:cstring("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, + elem = SIZE[kind], single = single, + }) + end + end +end + +local function find(layers: { Layer }, domain: string, kind: string?, name: string?): Layer? + for _, L in layers do + if L.domain == domain and (kind == nil or L.kind == kind) and (name == nil or L.name == name) then + return L + end + end + return nil +end + +local function legacy(f: Blend.File, me: Blend.View, field: string, kind: string, domain: string): Layer? + local blk = me:target(field) + local st = f.dna.byName[kind] + if not blk or not st or st.size <= 0 then + return nil + end + return { name = "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, elem = st.size } +end + +local function reader(f: Blend.File, L: Layer): (number, number) -> number + local b = f.buf + local o, elem, k = L.offset, L.elem, L.kind + local max = L.bytes + local single = L.single + local f32, i32, i16 = f.f32, f.i32, f.i16 + local comp = if k == "short2" then 2 elseif k == "int8" or k == "bool" or k == "bytecolor" then 1 else 4 + return function(i: number, c: number): number + local at = (if single then 0 else i * elem) + c * comp + if at < 0 or at + comp > max then + return 0 + end + if k == "float" or k == "float2" or k == "float3" or k == "color" or k == "quat" or k == "float4x4" then + return f32(b, o + at) + elseif k == "int32" or k == "int2" then + return i32(b, o + at) + elseif k == "short2" then + return i16(b, o + at) + elseif k == "int8" then + return buffer.readi8(b, o + at) + end + return readu8(b, o + at) + end +end +Mesh.reader = reader + +local function fieldReader(f: Blend.File, L: Layer, field: string): ((number, number) -> number)? + local st = f.dna.byName[L.kind] + local fld = st and st.byName[field] + if not fld then + return nil + end + local b, o, elem, max = f.buf, L.offset, L.elem, L.bytes + local t, esz = fld.type, fld.elem + local fo = fld.offset + local f32, i32, i16, u32, u16 = f.f32, f.i32, f.i16, f.u32, f.u16 + return function(i: number, c: number): number + local at = i * elem + fo + c * esz + if at < 0 or at + esz > max then + return 0 + end + at += o + if t == "float" then + return f32(b, at) + elseif t == "int" or t == "int32_t" then + return i32(b, at) + elseif t == "uint" or t == "uint32_t" then + return u32(b, at) + elseif t == "short" or t == "int16_t" then + return i16(b, at) + elseif t == "ushort" or t == "uint16_t" then + return u16(b, at) + end + return readu8(b, at) + end +end + +-- tessellated face colours: corner k of face i at offset + i * faceStride + first + k * cornerStride, bytes in MCol's +-- memory order (alpha, blue, green, red; reversed when an int held them in a big-endian file), sRGB -> linear; +-- TFace colours load opaque, as Blender's versioning makes them +local function tessColors(f: Blend.File, tess: buffer, nc: number, offset: number, bytes: number, faceStride: number, first: number, cornerStride: number, swap: boolean, opaque: boolean?): buffer + local d = buffer.create(nc * 16) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + local at = (tc // 4) * faceStride + first + (tc % 4) * cornerStride + if at + 4 <= bytes then + local o = offset + at + local aa, bb, gg, rr = readu8(f.buf, o), readu8(f.buf, o + 1), readu8(f.buf, o + 2), readu8(f.buf, o + 3) + if swap then + aa, bb, gg, rr = rr, gg, bb, aa + end + buffer.writef32(d, i * 16, SRGB[rr + 1]) + buffer.writef32(d, i * 16 + 4, SRGB[gg + 1]) + buffer.writef32(d, i * 16 + 8, SRGB[bb + 1]) + buffer.writef32(d, i * 16 + 12, if opaque then 1 else aa / 255) + end + end + return d +end + +function Mesh.layers(f: Blend.File, me: Blend.View): { Layer } + local layers: { Layer } = {} + customData(f, me, { "vdata", "vert_data" }, "point", layers) + customData(f, me, { "edata", "edge_data" }, "edge", layers) + customData(f, me, { "pdata", "face_data" }, "face", layers) + customData(f, me, { "ldata", "corner_data" }, "corner", layers) + customData(f, me, { "fdata", "fdata_legacy" }, "tess", layers) + storage(f, me, layers) + return layers +end + +local function count(me: Blend.View, ...: string): number + local v = me:num(...) + return if v and v > 0 then v else 0 +end + +type Limits = { maxVertices: number? } + +function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, string?) + local layers = Mesh.layers(f, me) + local nv = count(me, "totvert", "verts_num") + local np = count(me, "totpoly", "faces_num") + local nl = count(me, "totloop", "corners_num") + local nt = count(me, "totface", "totface_legacy") + local maxV = limits and limits.maxVertices or 2 ^ 25 + if nv > maxV or nl > maxV or nt > maxV or np > maxV then + return nil, "limit: mesh over maxVertices" + end + local pos = buffer.create(nv * 12) + local P = find(layers, "point", "float3", "position") + local mv = find(layers, "point", "MVert") or legacy(f, me, "mvert", "MVert", "point") + local get: ((number, number) -> number)? = nil + if P then + get = reader(f, P) + elseif mv then + get = fieldReader(f, mv, "co") + end + if not get then + if nv > 0 then + return nil, "mesh without positions" + end + get = function(_: number, _: number): number + return 0 + end + end + local g = get :: (number, number) -> number + for i = 0, nv - 1 do + for c = 0, 2 do + buffer.writef32(pos, (i * 3 + c) * 4, g(i, c)) + end + end + local poly: Poly = { + name = me:idName(), nv = nv, nf = 0, nc = 0, pos = pos, cornerVert = buffer.create(0), faceStart = buffer.create(4), + faceMat = buffer.create(0), faceSmooth = buffer.create(0), uvs = {}, activeUV = 1, colors = {}, sharp = {}, + generation = if P and P.cdtype == nil then "storage" elseif P then "attributes" else "mpoly", + layers = layers, + } + local corner: { [string]: any } = {} + if np > 0 then + local offs = me:target("poly_offset_indices", "face_offset_indices") + local mp = find(layers, "face", "MPoly") or legacy(f, me, "mpoly", "MPoly", "face") + local cv = find(layers, "corner", "int32", ".corner_vert") + local ml = find(layers, "corner", "MLoop") or legacy(f, me, "mloop", "MLoop", "corner") + local starts = buffer.create((np + 1) * 4) + if offs and offs.size >= (np + 1) * 4 then + for i = 0, np do + buffer.writeu32(starts, i * 4, math.clamp(f.i32(f.buf, offs.offset + i * 4), 0, nl)) + end + elseif mp then + local ls, tl = fieldReader(f, mp, "loopstart"), fieldReader(f, mp, "totloop") + if not ls or not tl then + return nil, "bad MPoly" + end + -- MPoly faces are usually in loop order; faces that are not get copied corners below + local at = 0 + for i = 0, np - 1 do + buffer.writeu32(starts, i * 4, at) + at += math.max(0, tl(i, 0)) + end + buffer.writeu32(starts, np * 4, at) + if at > maxV * 4 then + return nil, "limit: too many corners" + end + local verts = buffer.create(at * 4) + local vr = if cv then reader(f, cv) else if ml then fieldReader(f, ml, "v") else nil + if not vr then + return nil, "mesh without corners" + end + local remap = buffer.create(at * 4) + local w = 0 + for i = 0, np - 1 do + local s0, n0 = ls(i, 0), tl(i, 0) + for k = 0, n0 - 1 do + local src = s0 + k + buffer.writeu32(verts, w * 4, math.clamp(vr(src, 0), 0, math.max(nv - 1, 0))) + buffer.writeu32(remap, w * 4, math.clamp(src, 0, math.max(nl - 1, 0))) + w += 1 + end + end + corner.remap = remap + corner.verts = verts + nl = at + else + return nil, "mesh without face offsets" + end + poly.faceStart = starts + poly.nf = np + if not corner.verts then + local verts = buffer.create(nl * 4) + local vr = if cv then reader(f, cv) else if ml then fieldReader(f, ml, "v") else nil + if not vr then + return nil, "mesh without corners" + end + for i = 0, nl - 1 do + buffer.writeu32(verts, i * 4, math.clamp(vr(i, 0), 0, math.max(nv - 1, 0))) + end + corner.verts = verts + end + poly.cornerVert = corner.verts + poly.nc = nl + local mats = buffer.create(np * 4) + local smooth = buffer.create(np) + local mi = find(layers, "face", "int32", "material_index") + local sf = find(layers, "face", "bool", "sharp_face") + local mr = if mi then reader(f, mi) elseif mp then fieldReader(f, mp, "mat_nr") else nil + local flag = if mp then fieldReader(f, mp, "flag") else nil + local sr = if sf then reader(f, sf) else nil + for i = 0, np - 1 do + buffer.writei32(mats, i * 4, if mr then mr(i, 0) else 0) + local s + if sr then + s = sr(i, 0) == 0 + elseif flag then + s = bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 + else + s = poly.generation ~= "mpoly" + end + buffer.writeu8(smooth, i, if s then 1 else 0) + end + poly.faceMat, poly.faceSmooth = mats, smooth + elseif nt > 0 then + local mf = find(layers, "tess", "MFace") or legacy(f, me, "mface", "MFace", "tess") + if not mf then + return nil, "mesh without faces" + end + poly.generation = "mface" + local v = { fieldReader(f, mf, "v1"), fieldReader(f, mf, "v2"), fieldReader(f, mf, "v3"), fieldReader(f, mf, "v4") } + local mr, flag = fieldReader(f, mf, "mat_nr"), fieldReader(f, mf, "flag") + if not (v[1] and v[2] and v[3] and v[4]) then + return nil, "bad MFace" + end + local starts = buffer.create((nt + 1) * 4) + local verts = buffer.create(nt * 16) + local tessCorner = buffer.create(nt * 16) -- face * 4 + k: where tess layers keep the corner + local mats, smooth = buffer.create(nt * 4), buffer.create(nt) + local at = 0 + for i = 0, nt - 1 do + buffer.writeu32(starts, i * 4, at) + local k = if (v[4] :: any)(i, 0) ~= 0 then 4 else 3 + for c = 1, k do + buffer.writeu32(verts, (at + c - 1) * 4, math.clamp((v[c] :: any)(i, 0), 0, math.max(nv - 1, 0))) + buffer.writeu32(tessCorner, (at + c - 1) * 4, i * 4 + c - 1) + end + at += k + buffer.writei32(mats, i * 4, if mr then mr(i, 0) else 0) + buffer.writeu8(smooth, i, if flag and bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 then 1 else 0) + end + buffer.writeu32(starts, nt * 4, at) + poly.faceStart, poly.cornerVert, poly.nf, poly.nc = starts, verts, nt, at + poly.faceMat, poly.faceSmooth = mats, smooth + corner.tess = tessCorner + end + local nc = poly.nc + local remap: buffer? = corner.remap + local function src(i: number): number + return if remap then buffer.readu32(remap, i * 4) else i + end + for _, L in layers do + if L.domain == "corner" and (L.kind == "float2" or L.kind == "MLoopUV") and string.sub(L.name, 1, 1) ~= "." then + local r = if L.kind == "float2" then reader(f, L) else fieldReader(f, L, "uv") + if r then + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local s = src(i) + buffer.writef32(d, i * 8, r(s, 0)) + buffer.writef32(d, i * 8 + 4, r(s, 1)) + end + table.insert(poly.uvs, { name = L.name, data = d }) + if L.activeRender and L.kind == "MLoopUV" then + poly.activeUV = #poly.uvs + end + end + elseif L.domain == "tess" and L.kind == "MTFace" and corner.tess then + local r = fieldReader(f, L, "uv") + local tess = corner.tess :: buffer + if r then + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + local face, k = tc // 4, tc % 4 + buffer.writef32(d, i * 8, r(face, k * 2)) + buffer.writef32(d, i * 8 + 4, r(face, k * 2 + 1)) + end + table.insert(poly.uvs, { name = L.name, data = d }) + end + end + end + -- before 2.42 (no CustomData): Mesh.tface (TFace, uv[4][2] per face) and Mesh.mcol (MCol x 4 per face) + if #poly.uvs == 0 and corner.tess then + local tf = legacy(f, me, "tface", "TFace", "tess") + local r = tf and fieldReader(f, tf, "uv") + if r then + local tess = corner.tess :: buffer + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + buffer.writef32(d, i * 8, r(tc // 4, (tc % 4) * 2)) + buffer.writef32(d, i * 8 + 4, r(tc // 4, (tc % 4) * 2 + 1)) + end + table.insert(poly.uvs, { name = "UVMap", data = d }) + end + end + local active = me:cstring("default_uv_map_attribute") or me:cstring("active_uv_map_attribute") + if active then + for k, u in poly.uvs do + if u.name == active then + poly.activeUV = k + end + end + end + for _, L in layers do + if (L.domain == "corner" or L.domain == "point") and (L.kind == "color" or L.kind == "bytecolor") and string.sub(L.name, 1, 1) ~= "." then + local n = if L.domain == "corner" then nc else nv + local r = reader(f, L) + local d = buffer.create(n * 16) + for i = 0, n - 1 do + local s = if L.domain == "corner" then src(i) else i + for c = 0, 3 do + local x = r(s, c) + if L.kind == "bytecolor" then + x = if c == 3 then x / 255 else SRGB[math.clamp(x, 0, 255) + 1] + end + buffer.writef32(d, (i * 4 + c) * 4, x) + end + end + table.insert(poly.colors, { name = L.name, domain = L.domain, data = d }) + elseif L.kind == "MCol" and L.domain == "tess" and corner.tess then + local st = f.dna.byName.MCol + local stride = if st then st.size else 4 + table.insert(poly.colors, { name = L.name, domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, L.offset, L.bytes, stride * 4, 0, stride, false) }) + end + end + -- before 2.42 (no CustomData): Mesh.mcol, or TFace.col (unsigned int col[4], MCol's byte layout in memory) + if #poly.colors == 0 and corner.tess then + local mc = legacy(f, me, "mcol", "MCol", "tess") + local tf = legacy(f, me, "tface", "TFace", "tess") + local col = f.dna.byName.TFace and f.dna.byName.TFace.byName.col + if mc then + table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, mc.offset, mc.bytes, mc.elem * 4, 0, mc.elem, false) }) + elseif tf and col then + table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, tf.offset, tf.bytes, tf.elem, col.offset, 4, not f.little, true) }) + end + end + local cn = find(layers, "corner", "short2", "custom_normal") + for _, L in layers do + if not cn and L.domain == "corner" and L.cdtype == 41 then + cn = L + end + end + if cn then + local r = reader(f, cn) + local d = buffer.create(nc * 4) + for i = 0, nc - 1 do + local s = src(i) + buffer.writei16(d, i * 4, r(s, 0)) + buffer.writei16(d, i * 4 + 2, r(s, 1)) + end + poly.encodedNormals = d + end + local free = find(layers, "corner", "float3", "custom_normal") or find(layers, "point", "float3", "custom_normal") + or find(layers, "face", "float3", "custom_normal") + if free then + local r = reader(f, free) + local d = buffer.create(nc * 12) + local starts = poly.faceStart + for fi = 0, poly.nf - 1 do + local s0, s1 = buffer.readu32(starts, fi * 4), buffer.readu32(starts, fi * 4 + 4) + for i = s0, s1 - 1 do + local e = if free.domain == "corner" then src(i) elseif free.domain == "face" then fi else buffer.readu32(poly.cornerVert, i * 4) + for c = 0, 2 do + buffer.writef32(d, (i * 3 + c) * 4, r(e, c)) + end + end + end + poly.customNormals = d + end + -- sharp edges + local ne = count(me, "totedge", "edges_num") + local ev = find(layers, "edge", "int2", ".edge_verts") + local se = find(layers, "edge", "bool", "sharp_edge") + local medge = find(layers, "edge", "MEdge") or legacy(f, me, "medge", "MEdge", "edge") + local flags = me:num("flag") or 0 + local smoothresh = me:num("smoothresh") + local autoSmooth = f.version < 401 and bit32.band(flags, ME_AUTOSMOOTH) ~= 0 + if autoSmooth then + poly.autoSmooth = smoothresh or math.rad(30) + end + local useSharp = f.version >= 401 or autoSmooth + if useSharp and ne > 0 then + local v1, v2, sharp + if ev and se then + local er, sr = reader(f, ev), reader(f, se) + v1 = function(i: number): number return er(i, 0) end + v2 = function(i: number): number return er(i, 1) end + sharp = function(i: number): boolean return sr(i, 0) ~= 0 end + elseif medge then + local a, b, fl = fieldReader(f, medge, "v1"), fieldReader(f, medge, "v2"), fieldReader(f, medge, "flag") + if a and b and fl then + v1 = function(i: number): number return a(i, 0) end + v2 = function(i: number): number return b(i, 0) end + local ser = if se then reader(f, se) else nil + sharp = function(i: number): boolean + if ser then + return ser(i, 0) ~= 0 + end + return bit32.band(fl(i, 0), ME_SHARP) ~= 0 + end + end + end + if v1 and v2 and sharp then + for i = 0, ne - 1 do + if sharp(i) then + local a, b = v1(i), v2(i) + local lo, hi = math.min(a, b), math.max(a, b) + poly.sharp[lo * nv + hi] = true + end + end + end + end + -- deform weights + local dv = find(layers, "point", "MDeformVert") or legacy(f, me, "dvert", "MDeformVert", "point") + if dv then + local st = f.dna.byName.MDeformVert + local dwf, twf = st and st.byName.dw, st and st.byName.totweight + local mw = f.dna.byName.MDeformWeight + local nrf, wf = mw and mw.byName.def_nr, mw and mw.byName.weight + if dwf and twf and mw and nrf and wf then + local weights = table.create(nv) :: { { number } } + for i = 0, nv - 1 do + local list = {} + local at = i * dv.elem + if at + dv.elem <= dv.bytes then + local vw = Blend.view(f, "MDeformVert", dv.offset + at) + local blk = vw and vw:target("dw") + local n = vw and vw:num("totweight") or 0 + if blk then + n = math.min(n, blk.size // mw.size) + for k = 0, n - 1 do + local o = blk.offset + k * mw.size + table.insert(list, f.i32(f.buf, o + nrf.offset)) + table.insert(list, f.f32(f.buf, o + wf.offset)) + end + end + end + weights[i + 1] = list + end + poly.weights = weights + end + end + return poly, nil +end + +-- shape keys: { name, value, relative (0-based), data: f32 x 3 per vertex } in file order, and the reference index +type Shape = { name: string, value: number, relative: number, data: buffer, mute: boolean, min: number, max: number } +function Mesh.shapes(f: Blend.File, me: Blend.View, nv: number): ({ Shape }, number?, Blend.View?) + local key = me:deref("key", 0, "Key") + if not key then + return {}, nil, nil + end + local blocks = key:list("block", "KeyBlock") + local refAddr = key:ptr("refkey") + local out: { Shape } = {} + local ref: number? = nil + for i, kb in blocks do + local blk = kb:target("data") + local d = buffer.create(nv * 12) + if blk then + local n = math.min(nv * 12, blk.size) + buffer.copy(d, 0, f.buf, blk.offset, n) + if not f.little then + for k = 0, n // 4 - 1 do + buffer.writef32(d, k * 4, f.f32(f.buf, blk.offset + k * 4)) + end + end + end + if kb.block and kb.block.addr == refAddr then + ref = i + end + table.insert(out, { + -- unnamed in old files: Key 0 (the basis), Key 1, ... + name = kb:str("name") or ("Key " .. (i - 1)), value = kb:num("curval") or 0, relative = kb:num("relative") or 0, data = d, + mute = bit32.band(kb:num("flag") or 0, 2) ~= 0, + min = kb:num("slidermin") or 0, + max = kb:num("slidermax") or 1, + }) + end + if ref == nil and #out > 0 then + ref = 1 + end + return out, ref, key +end + +return Mesh +end +__FILES["model/blend/Normals"] = function() + +-- model/blend/Normals: Blender's encoded custom normals (CD_CUSTOMLOOPNORMAL / the "custom_normal" int16 x 2 corner +-- attribute) decoded in each smooth fan's space: the fan normal N, a reference edge direction R projected +-- perpendicular to N, O = N x R; alpha = the mean angle of the fan's edges to N, beta = the angle from R to the fan's +-- other end edge around N (2 pi for closed fans). A stored (a, b) (units of 1 / 32767) gives the angle a * alpha +-- (a > 0) or a * (2 pi - alpha) from N, turned b * beta (b > 0) or b * (2 pi - beta) from R towards O. +local Normals = {} + +local readu32, readf32, writef32, readi16 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.readi16 +local sqrt, acos, cos, sin = math.sqrt, math.acos, math.cos, math.sin +local TAU = 2 * math.pi +local NEAR = 0.99999 + +type Fans = { next: buffer, prev: buffer, face: buffer, across: { [number]: number } } + +local function dir(pos: buffer, from: number, to: number): (number, number, number) + local x = readf32(pos, to * 12) - readf32(pos, from * 12) + local y = readf32(pos, to * 12 + 4) - readf32(pos, from * 12 + 4) + local z = readf32(pos, to * 12 + 8) - readf32(pos, from * 12 + 8) + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + return x / l, y / l, z / l + end + return 0, 0, 0 +end + +function Normals.decode(poly: any, lnor: buffer, fanId: buffer, fans: Fans, _ang: buffer): buffer + local nc = poly.nc + local cv, pos = poly.cornerVert, poly.pos + local enc = poly.encodedNormals :: buffer + local out = buffer.create(nc * 12) + buffer.copy(out, 0, lnor, 0, nc * 12) + local across = fans.across + local nxt, prv = fans.next, fans.prev + local done: { [number]: boolean } = {} + for c = 0, nc - 1 do + local id = readu32(fanId, c * 4) + if not done[id] then + done[id] = true + local start = c + local cyclic = false + local guard = 0 + while true do + local p = across[readu32(prv, start * 4)] + if p == nil then + break + end + if p == c then + cyclic = true + break + end + start = p + guard += 1 + if guard > nc then + cyclic = true + break + end + end + if cyclic then + local m, q = c, c + repeat + local nq = across[q] + q = if nq then readu32(nxt, nq * 4) else c + if q < m then + m = q + end + guard += 1 + until q == c or guard > 2 * nc + 4 + start = m + end + local v = readu32(cv, start * 4) + local nx, ny, nz = readf32(lnor, start * 12), readf32(lnor, start * 12 + 4), readf32(lnor, start * 12 + 8) + local corners = { start } + local edges = { readu32(cv, readu32(prv, start * 4) * 4) } + local q = start + while true do + table.insert(edges, readu32(cv, readu32(nxt, q * 4) * 4)) + local a = across[q] + if a == nil then + break + end + local nq = readu32(nxt, a * 4) + if nq == start or #corners > nc then + break + end + table.insert(corners, nq) + q = nq + end + local alpha, count = 0, 0 + for k, e in edges do + if not (cyclic and k == #edges) then + local x, y, z = dir(pos, v, e) + alpha += acos(math.clamp(x * nx + y * ny + z * nz, -1, 1)) + count += 1 + end + end + alpha /= math.max(count, 1) + -- Blender walks each fan backwards from the corner whose next edge ends it (in a closed fan: its lowest + -- corner): R is that corner's next edge, the other end the last corner's previous edge + local refEdge = if cyclic then edges[2] else edges[#edges] + local rx, ry, rz = dir(pos, v, refEdge) + local ox, oy, oz = dir(pos, v, if cyclic then refEdge else edges[1]) + local dr, dother = rx * nx + ry * ny + rz * nz, ox * nx + oy * ny + oz * nz + local valid = math.abs(dr) < NEAR and math.abs(dother) < NEAR + local beta = 0 + local tx, ty, tz = 0, 0, 0 + if valid then + rx, ry, rz = rx - nx * dr, ry - ny * dr, rz - nz * dr + local l = sqrt(rx * rx + ry * ry + rz * rz) + rx, ry, rz = rx / l, ry / l, rz / l + tx, ty, tz = ny * rz - nz * ry, nz * rx - nx * rz, nx * ry - ny * rx + l = sqrt(tx * tx + ty * ty + tz * tz) + if l > 0 then + tx, ty, tz = tx / l, ty / l, tz / l + end + ox, oy, oz = ox - nx * dother, oy - ny * dother, oz - nz * dother + l = sqrt(ox * ox + oy * oy + oz * oz) + if l > 0 then + ox, oy, oz = ox / l, oy / l, oz / l + end + local d = rx * ox + ry * oy + rz * oz + if d < NEAR then + beta = acos(math.clamp(d, -1, 1)) + if tx * ox + ty * oy + tz * oz < 0 then + beta = TAU - beta + end + else + beta = TAU + end + end + for _, k in corners do + local a, b = readi16(enc, k * 4) / 32767, readi16(enc, k * 4 + 2) / 32767 + if a ~= 0 and valid and alpha ~= 0 and beta ~= 0 then + local al = (if a > 0 then alpha else TAU - alpha) * a + local sa = sin(al) + local x, y, z = nx * cos(al), ny * cos(al), nz * cos(al) + if b == 0 then + x, y, z = x + rx * sa, y + ry * sa, z + rz * sa + else + local be = (if b > 0 then beta else TAU - beta) * b + x += sa * (rx * cos(be) + tx * sin(be)) + y += sa * (ry * cos(be) + ty * sin(be)) + z += sa * (rz * cos(be) + tz * sin(be)) + end + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + writef32(out, k * 12, x) + writef32(out, k * 12 + 4, y) + writef32(out, k * 12 + 8, z) + end + end + end + end + return out +end + +return Normals +end +__FILES["model/blend/Prim"] = function() + +-- model/blend/Prim: model/blend/Mesh polygons to Scene primitives (one per material slot): corner normals from smooth +-- fans (angle-weighted face normals; sharp faces, sharp edges, auto smooth before 4.1 and non-manifold or flipped edges +-- split fans, as Blender does), custom normals, vertices shared by corners with equal attributes, n-gons by ear +-- clipping, deform weights (top 4) and shape keys as morph targets. +local Types = __include("Types") +local Polygon = __include("codecs/model/Polygon") +local Rig = __include("codecs/model/Rig") +local Normals = __include("model/blend/Normals") +local MeshT = __include("model/blend/Mesh") + +local Prim = {} + +local Scene = Types.Scene +local readu32, readf32, writef32, writeu32 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32 +local sqrt, acos = math.sqrt, math.acos + +type Options = { + triangulate: boolean?, -- default true + flipV: boolean?, -- default true (glTF's top-left UV origin) + normals: boolean?, -- default true +} +type Skinning = { joints: { [number]: number } } -- def_nr (0-based) -> joint index (0-based) in the skin + +local function face(poly: MeshT.Poly, fi: number): (number, number) + return readu32(poly.faceStart, fi * 4), readu32(poly.faceStart, fi * 4 + 4) +end + +local function vec(pos: buffer, v: number): (number, number, number) + return readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8) +end + +-- face normals (Newell) and corner angles +function Prim.geometry(poly: MeshT.Poly): (buffer, buffer) + local fn = buffer.create(poly.nf * 12) + local ang = buffer.create(poly.nc * 4) + local cv, pos = poly.cornerVert, poly.pos + for fi = 0, poly.nf - 1 do + local s0, s1 = face(poly, fi) + local nx, ny, nz = 0, 0, 0 + local n = s1 - s0 + for c = s0, s1 - 1 do + local d = if c + 1 < s1 then c + 1 else s0 + local x1, y1, z1 = vec(pos, readu32(cv, c * 4)) + local x2, y2, z2 = vec(pos, readu32(cv, d * 4)) + nx += (y1 - y2) * (z1 + z2) + ny += (z1 - z2) * (x1 + x2) + nz += (x1 - x2) * (y1 + y2) + end + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + writef32(fn, fi * 12, nx) + writef32(fn, fi * 12 + 4, ny) + writef32(fn, fi * 12 + 8, nz) + if n >= 3 then + for c = s0, s1 - 1 do + local pc = if c > s0 then c - 1 else s1 - 1 + local nc = if c + 1 < s1 then c + 1 else s0 + local x, y, z = vec(pos, readu32(cv, c * 4)) + local ax, ay, az = vec(pos, readu32(cv, pc * 4)) + local bx, by, bz = vec(pos, readu32(cv, nc * 4)) + ax, ay, az = ax - x, ay - y, az - z + bx, by, bz = bx - x, by - y, bz - z + local la, lb = sqrt(ax * ax + ay * ay + az * az), sqrt(bx * bx + by * by + bz * bz) + local a = 0 + if la > 0 and lb > 0 then + a = acos(math.clamp((ax * bx + ay * by + az * bz) / (la * lb), -1, 1)) + end + writef32(ang, c * 4, a) + end + end + end + return fn, ang +end + +-- smooth fans: for each corner the corner after it in its face, and the fan links across smooth edges +type Fans = { + next: buffer, -- u32 per corner: the next corner of its face + prev: buffer, -- u32 per corner + face: buffer, -- u32 per corner: its face + -- per corner: the corner of the neighbouring face across the edge from this corner to the next one (the corner + -- at this corner's next vertex), or -1 where the edge splits fans + across: { [number]: number }, +} + +function Prim.fans(poly: MeshT.Poly, fn: buffer): Fans + local nc, nv = poly.nc, poly.nv + local cv = poly.cornerVert + local nxt, prv, fc = buffer.create(nc * 4), buffer.create(nc * 4), buffer.create(nc * 4) + for fi = 0, poly.nf - 1 do + local s0, s1 = face(poly, fi) + for c = s0, s1 - 1 do + writeu32(nxt, c * 4, if c + 1 < s1 then c + 1 else s0) + writeu32(prv, c * 4, if c > s0 then c - 1 else s1 - 1) + writeu32(fc, c * 4, fi) + end + end + local first: { [number]: number } = {} + local second: { [number]: number } = {} + local uses: { [number]: number } = {} + for c = 0, nc - 1 do + local a, b = readu32(cv, c * 4), readu32(cv, readu32(nxt, c * 4) * 4) + local key = math.min(a, b) * nv + math.max(a, b) + local u = (uses[key] or 0) + 1 + uses[key] = u + if u == 1 then + first[key] = c + elseif u == 2 then + second[key] = c + end + end + local across: { [number]: number } = {} + local smooth = poly.faceSmooth + local cosLimit = if poly.autoSmooth then math.cos(poly.autoSmooth) else nil + for key, u in uses do + if u == 2 then + local c1, c2 = first[key], second[key] + local f1, f2 = readu32(fc, c1 * 4), readu32(fc, c2 * 4) + local a1 = readu32(cv, c1 * 4) + local a2 = readu32(cv, c2 * 4) + local ok = a1 ~= a2 and f1 ~= f2 and buffer.readu8(smooth, f1) ~= 0 and buffer.readu8(smooth, f2) ~= 0 + and not poly.sharp[key] + if ok and cosLimit then + local d = readf32(fn, f1 * 12) * readf32(fn, f2 * 12) + readf32(fn, f1 * 12 + 4) * readf32(fn, f2 * 12 + 4) + + readf32(fn, f1 * 12 + 8) * readf32(fn, f2 * 12 + 8) + ok = d >= cosLimit + end + if ok then + -- c1 runs a -> b, c2 runs b -> a: the corner at b in face 2 is c2, at a it is next(c2) + across[c1] = c2 + across[c2] = c1 + end + end + end + return { next = nxt, prev = prv, face = fc, across = across } +end + +-- corner normals: angle-weighted face normals summed over each smooth fan; with fan ids (u32 per corner) +function Prim.cornerNormals(poly: MeshT.Poly, fn: buffer, ang: buffer, fans: Fans): (buffer, buffer) + local nc = poly.nc + local parent = buffer.create(nc * 4) + for c = 0, nc - 1 do + writeu32(parent, c * 4, c) + end + local function root(c: number): number + local r = c + while readu32(parent, r * 4) ~= r do + r = readu32(parent, r * 4) + end + while readu32(parent, c * 4) ~= r do + local nx = readu32(parent, c * 4) + writeu32(parent, c * 4, r) + c = nx + end + return r + end + local function union(a: number, b: number) + local ra, rb = root(a), root(b) + if ra ~= rb then + writeu32(parent, math.max(ra, rb) * 4, math.min(ra, rb)) + end + end + for c1, c2 in fans.across do + if c1 < c2 then + -- edge c1 (a -> b) shared with c2 (b -> a): corners at b are next(c1) and c2, at a c1 and next(c2) + union(readu32(fans.next, c1 * 4), c2) + union(c1, readu32(fans.next, c2 * 4)) + end + end + local acc = buffer.create(nc * 12) + local fanId = buffer.create(nc * 4) + for c = 0, nc - 1 do + local r = root(c) + writeu32(fanId, c * 4, r) + local fi = readu32(fans.face, c * 4) + local w = readf32(ang, c * 4) + for k = 0, 2 do + writef32(acc, (r * 3 + k) * 4, readf32(acc, (r * 3 + k) * 4) + readf32(fn, (fi * 3 + k) * 4) * w) + end + end + local out = buffer.create(nc * 12) + for c = 0, nc - 1 do + local r = readu32(fanId, c * 4) + local x, y, z = readf32(acc, r * 12), readf32(acc, r * 12 + 4), readf32(acc, r * 12 + 8) + local l = sqrt(x * x + y * y + z * z) + local fi = readu32(fans.face, c * 4) + writef32(out, c * 12, if l > 1e-20 then x / l else readf32(fn, fi * 12)) + writef32(out, c * 12 + 4, if l > 1e-20 then y / l else readf32(fn, fi * 12 + 4)) + writef32(out, c * 12 + 8, if l > 1e-20 then z / l else readf32(fn, fi * 12 + 8)) + end + return out, fanId +end + +function Prim.normals(poly: MeshT.Poly): buffer + local fn, ang = Prim.geometry(poly) + local fans = Prim.fans(poly, fn) + local nrm, fanId = Prim.cornerNormals(poly, fn, ang, fans) + if poly.customNormals then + return poly.customNormals :: buffer + end + if poly.encodedNormals then + return Normals.decode(poly, nrm, fanId, fans, ang) + end + return nrm +end + +-- triangles of face fi as corner indices (appended to out) +local function triangulate(poly: MeshT.Poly, fi: number, fnx: number, fny: number, fnz: number, out: { number }) + local s0, s1 = face(poly, fi) + local n = s1 - s0 + if n < 3 then + return + end + if n == 3 then + table.insert(out, s0) + table.insert(out, s0 + 1) + table.insert(out, s0 + 2) + return + end + local ax, ay, az = math.abs(fnx), math.abs(fny), math.abs(fnz) + local cu, cv, sign = 0, 1, fnz + if ax >= ay and ax >= az then + cu, cv, sign = 1, 2, fnx + elseif ay >= az then + cu, cv, sign = 2, 0, fny + end + local ring = table.create(n * 2) :: { number } + for c = s0, s1 - 1 do + local v = readu32(poly.cornerVert, c * 4) + local u, w = readf32(poly.pos, (v * 3 + cu) * 4), readf32(poly.pos, (v * 3 + cv) * 4) + table.insert(ring, if sign < 0 then -u else u) + table.insert(ring, w) + end + local tris = Polygon.triangulate({ ring }) + if #tris == (n - 2) * 6 then + for k = 2, #tris, 2 do + table.insert(out, s0 + tris[k] - 1) + end + return + end + for k = 1, n - 2 do -- degenerate: a fan + table.insert(out, s0) + table.insert(out, s0 + k) + table.insert(out, s0 + k + 1) + end +end + +local function accessor(t: { number }, comps: number): Types.Accessor + local n = #t // comps + local b = buffer.create(#t * 4) + for i = 1, #t do + writef32(b, (i - 1) * 4, t[i]) + end + return Scene.accessor(b, "f32", comps, n) +end + +type Built = { mesh: Types.Mesh, slots: { number }, vertexSource: { { number } } } + +-- slots[k] = the scene material of slot k - 1 (or 0 for none); skin maps deform groups to joints +function Prim.build(poly: MeshT.Poly, slots: { number }, opts: Options?, skin: Skinning?, shapes: { MeshT.Shape }?, ref: number?): Built + local triangulateOn = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local withNormals = not (opts and opts.normals == false) + local nrm = if withNormals and poly.nf > 0 then Prim.normals(poly) else nil + local fn = if poly.nf > 0 then (Prim.geometry(poly)) else buffer.create(0) + local nslots = math.max(#slots, 1) + local groups: { [number]: { number } } = {} + local order: { number } = {} + for fi = 0, poly.nf - 1 do + local m = math.clamp(buffer.readi32(poly.faceMat, fi * 4), 0, nslots - 1) + local g = groups[m] + if not g then + g = {} + groups[m] = g + table.insert(order, m) + end + table.insert(g, fi) + end + table.sort(order) + local cornerColors: { MeshT.Color }, pointColors: { MeshT.Color } = {}, {} + for _, c in poly.colors do + table.insert(if c.domain == "corner" then cornerColors else pointColors, c) + end + local keyBytes = 4 + (if nrm then 12 else 0) + #poly.uvs * 8 + #cornerColors * 16 + local scratch = buffer.create(keyBytes) + local mesh: Types.Mesh = { name = poly.name, primitives = {} } + local sources: { { number } } = {} + local cv = poly.cornerVert + for _, m in order do + local faces = groups[m] + local map: { [string]: number } = {} + local vsrc: { number } = {} + local corners: { number } = {} -- the first corner of each output vertex + local cornerOut = {} -- corner -> output vertex + for _, fi in faces do + local s0, s1 = face(poly, fi) + for c = s0, s1 - 1 do + local v = readu32(cv, c * 4) + buffer.writeu32(scratch, 0, v) + local o = 4 + if nrm then + buffer.copy(scratch, o, nrm, c * 12, 12) + o += 12 + end + for _, uv in poly.uvs do + buffer.copy(scratch, o, uv.data, c * 8, 8) + o += 8 + end + for _, col in cornerColors do + buffer.copy(scratch, o, col.data, c * 16, 16) + o += 16 + end + local key = buffer.readstring(scratch, 0, keyBytes) + local idx = map[key] + if not idx then + idx = #vsrc + map[key] = idx + table.insert(vsrc, v) + table.insert(corners, c) + end + cornerOut[c] = idx + end + end + local n = #vsrc + local attrs: { [string]: Types.Accessor } = {} + local P = buffer.create(n * 12) + for i = 1, n do + buffer.copy(P, (i - 1) * 12, poly.pos, vsrc[i] * 12, 12) + end + attrs.POSITION = Scene.accessor(P, "f32", 3, n) + if nrm then + local N = buffer.create(n * 12) + for i = 1, n do + buffer.copy(N, (i - 1) * 12, nrm, corners[i] * 12, 12) + end + attrs.NORMAL = Scene.accessor(N, "f32", 3, n) + end + for k, uv in poly.uvs do + local T = buffer.create(n * 8) + for i = 1, n do + local c = corners[i] + writef32(T, (i - 1) * 8, readf32(uv.data, c * 8)) + local v = readf32(uv.data, c * 8 + 4) + writef32(T, (i - 1) * 8 + 4, if flipV then 1 - v else v) + end + local acc = Scene.accessor(T, "f32", 2, n) + acc.name = uv.name + attrs["TEXCOORD_" .. (k - 1)] = acc + end + local ci = 0 + for _, col in poly.colors do + local C = buffer.create(n * 16) + for i = 1, n do + local e = if col.domain == "corner" then corners[i] else vsrc[i] + buffer.copy(C, (i - 1) * 16, col.data, e * 16, 16) + end + local acc = Scene.accessor(C, "f32", 4, n) + acc.name = col.name + attrs["COLOR_" .. ci] = acc + ci += 1 + end + if skin and poly.weights then + local lists = table.create(n) :: { { number } } + for i = 1, n do + local src = poly.weights[vsrc[i] + 1] or {} + local l = {} + for k = 1, #src - 1, 2 do + local j = skin.joints[src[k]] + if j then + table.insert(l, j) + table.insert(l, src[k + 1]) + end + end + lists[i] = l + end + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local prim: Types.Primitive = { attributes = attrs, mode = "triangles" } + local idx: { number } = {} + if triangulateOn then + for _, fi in faces do + local tri: { number } = {} + triangulate(poly, fi, readf32(fn, fi * 12), readf32(fn, fi * 12 + 4), readf32(fn, fi * 12 + 8), tri) + for _, c in tri do + table.insert(idx, cornerOut[c]) + end + end + else + local sizes = buffer.create(#faces * 4) + for k, fi in faces do + local s0, s1 = face(poly, fi) + writeu32(sizes, (k - 1) * 4, s1 - s0) + for c = s0, s1 - 1 do + table.insert(idx, cornerOut[c]) + end + end + prim.mode = "polygons" + prim.faces = Scene.accessor(sizes, "u32", 1, #faces) + end + local I = buffer.create(#idx * 4) + for k, v in idx do + writeu32(I, (k - 1) * 4, v) + end + prim.indices = Scene.accessor(I, "u32", 1, #idx) + local mat = slots[m + 1] + if mat and mat > 0 then + prim.material = mat + end + if shapes and ref and #shapes > 1 then + local base = shapes[ref].data + local targets: { { [string]: Types.Accessor } } = {} + for k, s in shapes do + if k ~= ref then + local t = table.create(n * 3) :: { number } + for i = 1, n do + local v = vsrc[i] + for c = 0, 2 do + t[(i - 1) * 3 + c + 1] = readf32(s.data, (v * 3 + c) * 4) - readf32(base, (v * 3 + c) * 4) + end + end + table.insert(targets, { POSITION = accessor(t, 3) } :: { [string]: Types.Accessor }) + end + end + prim.targets = targets + end + table.insert(mesh.primitives, prim) + table.insert(sources, vsrc) + end + if shapes and ref and #shapes > 1 then + local w = {} + for k, s in shapes do + if k ~= ref then + table.insert(w, s.value) + end + end + mesh.weights = w + end + local usedSlots = {} + for _, m in order do + table.insert(usedSlots, m) + end + return { mesh = mesh, slots = usedSlots, vertexSource = sources } +end + +return Prim +end +__FILES["model/blend/Read"] = function() + +-- model/blend/Read: a parsed .blend (containers/Blend) to a Scene: the current scene's objects (from its collections, +-- or Base list before 2.8) with their transforms (euler orders, quaternion, axis angle, delta transforms, parent +-- inverse; bone parents), meshes (model/blend/Mesh, model/blend/Prim), materials (Principled BSDF node or the legacy +-- colour), images (packed bytes or external uris), cameras, lights (watts to candela / lux as Blender's glTF exporter +-- does: 683 lm/W, / 4 pi for point and spot), armatures (bones to joint nodes with the saved pose), skins, shape keys +-- and actions sampled into channels. +local Blend = __include("containers/Blend") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Rig = __include("codecs/model/Rig") +local Mesh = __include("model/blend/Mesh") +local Prim = __include("model/blend/Prim") +local Anim = __include("model/blend/Anim") +local Material = __include("model/blend/Material") + +local Read = {} + +local Scene = Types.Scene +type M4 = { number } + +type Options = { + triangulate: boolean?, + flipV: boolean?, + collections: boolean?, -- collections as nodes (default true) + scene: string?, -- the scene to read (default: the file's current scene) + sampleStep: number?, -- frames between animation samples (default 1) + animations: boolean?, -- default true + resolve: ((uri: string) -> any)?, + files: { [string]: any }?, + maxVertices: number?, +} + +local OB_EMPTY, OB_MESH, OB_LAMP, OB_CAMERA, OB_ARMATURE = 0, 1, 10, 11, 25 +local PARSKEL, PARBONE = 4, 7 +local LA_LOCAL, LA_SUN, LA_SPOT, LA_HEMI, LA_AREA = 0, 1, 2, 3, 4 +local EULER = { [1] = "xyz", [2] = "xzy", [3] = "yxz", [4] = "yzx", [5] = "zxy", [6] = "zyx" } +local TYPE_NAME: { [number]: string } = { + [0] = "empty", [1] = "mesh", [2] = "curve", [3] = "surface", [4] = "text", [5] = "metaball", [10] = "light", + [11] = "camera", [12] = "speaker", [13] = "lightprobe", [22] = "lattice", [25] = "armature", [26] = "gpencil", + [27] = "curves", [28] = "pointcloud", [29] = "volume", [30] = "grease_pencil", +} +local W2LM = 683 + +-- ------------------------------------------------------------------------------------------------ transforms +local function quatWXYZ(q: { number }?): { number } + if not q or #q < 4 then + return { 0, 0, 0, 1 } + end + local w, x, y, z = q[1], q[2], q[3], q[4] + local l = math.sqrt(w * w + x * x + y * y + z * z) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + return { x / l, y / l, z / l, w / l } +end + +local function rotation(mode: number, eul: { number }?, quat: { number }?, axis: { number }?, angle: number?): M4 + if mode == 0 then + return Mat4.fromQuat(quatWXYZ(quat)) + elseif mode == -1 then + local a = axis or { 0, 1, 0 } + return Mat4.fromQuat(Mat4.axisAngle(a[1], a[2], a[3], math.deg(angle or 0))) + end + local e = eul or { 0, 0, 0 } + return Mat4.euler(math.deg(e[1]), math.deg(e[2]), math.deg(e[3]), EULER[mode] or "xyz") +end + +local function scaleM(m: M4, s: { number }): M4 + local r = table.clone(m) + for c = 0, 2 do + for k = 1, 3 do + r[c * 4 + k] *= s[c + 1] + end + end + return r +end + +local function trs(t: { number }, r: M4, s: { number }): M4 + local m = scaleM(r, s) + m[13], m[14], m[15] = t[1], t[2], t[3] + return m +end + +type Props = { [string]: { number } } -- location / rotation_euler / ... as Blender data paths, rotmode + +local function objectProps(ob: Blend.View): Props + -- fields missing from old files take their neutral value + local function v(fallback: { number }, ...: string): { number } + local x = ob:vec(...) + if x and #x >= #fallback then + return table.clone(x) + end + return fallback + end + local p: Props = { + location = v({ 0, 0, 0 }, "loc"), + rotation_euler = v({ 0, 0, 0 }, "rot"), + rotation_quaternion = v({ 1, 0, 0, 0 }, "quat"), + rotation_axis_angle = { ob:num("rotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "rotAxis")) }, + scale = v({ 1, 1, 1 }, "scale", "size"), + delta_location = v({ 0, 0, 0 }, "dloc"), + delta_rotation_euler = v({ 0, 0, 0 }, "drot"), + delta_rotation_quaternion = v({ 1, 0, 0, 0 }, "dquat"), + delta_rotation_axis_angle = { ob:num("drotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "drotAxis")) }, + delta_scale = v({ 1, 1, 1 }, "dscale"), + rotmode = { ob:num("rotmode") or 1 }, + } + if not ob:has("dscale") then + -- before 2.5x the delta scale ("dsize") was added to the scale + local d = v({ 0, 0, 0 }, "dsize") + p.scale = { p.scale[1] + d[1], p.scale[2] + d[2], p.scale[3] + d[3] } + end + return p +end + +local function poseProps(pc: Blend.View?): Props + if not pc then + return { + location = { 0, 0, 0 }, rotation_euler = { 0, 0, 0 }, rotation_quaternion = { 1, 0, 0, 0 }, + rotation_axis_angle = { 0, 0, 1, 0 }, scale = { 1, 1, 1 }, rotmode = { 0 }, + } + end + local function v(n: number, ...: string): { number } + local x = pc:vec(...) + if x and #x >= n then + return table.clone(x) + end + return table.create(n, 0) + end + return { + location = v(3, "loc"), + rotation_euler = v(3, "eul"), + rotation_quaternion = v(4, "quat"), + rotation_axis_angle = { pc:num("rotAngle") or 0, table.unpack(v(3, "rotAxis")) }, + scale = v(3, "scale", "size"), + rotmode = { pc:num("rotmode") or 0 }, + } +end + +-- Blender's object matrix: T(loc + dloc) * Rdelta * R * S(scale * dscale) +local function objectBasis(p: Props): M4 + local mode = p.rotmode[1] + local aa, daa = p.rotation_axis_angle, p.delta_rotation_axis_angle + local r = rotation(mode, p.rotation_euler, p.rotation_quaternion, { aa[2], aa[3], aa[4] }, aa[1]) + if p.delta_location then + local d = rotation(mode, p.delta_rotation_euler, p.delta_rotation_quaternion, { daa[2], daa[3], daa[4] }, daa[1]) + r = Mat4.mul(d, r) + local l, dl, s, ds = p.location, p.delta_location, p.scale, p.delta_scale + return trs({ l[1] + dl[1], l[2] + dl[2], l[3] + dl[3] }, r, { s[1] * ds[1], s[2] * ds[2], s[3] * ds[3] }) + end + return trs(p.location, r, p.scale) +end + +local function nodeTRS(node: Types.Node, m: M4) + local t, r, s = Mat4.decomposeStrict(m) + if t and r and s then + node.translation, node.rotation, node.scale = t, r, s + node.matrix = nil + else + node.matrix = m + node.translation, node.rotation, node.scale = nil, nil, nil + end +end + +local function mat4(v: Blend.View?, ...: string): M4? + local m = v and v:vec(...) + if m and #m == 16 then + return m + end + return nil +end + +-- ------------------------------------------------------------------------------------------------ scene +type Ctx = { + f: Blend.File, + scene: Types.Scene, + opts: Options, + objects: { [any]: number }, -- OB addr -> node + objView: { [number]: Blend.View }, -- node -> its object + parentOf: { [number]: number }, + world: { [number]: M4 }, + meshes: { [string]: number }, + materials: { [any]: number }, + textures: { [any]: number }, + armatures: { [any]: { joints: { number }, names: { [string]: number }, rest: { M4 }, restLocal: { M4 }, bones: { Blend.View }, deform: { boolean }, node: number, poseNames: { [string]: Blend.View } } }, + prefix: { [number]: M4 }, -- node -> the matrix before its basis (parent inverse, bone tail offset) + props: { [number]: Props }, + meta: { [string]: any }, + pending: { { node: number, ob: Blend.View } }, +} + +local function worldOf(ctx: Ctx, node: number): M4 + local cached = ctx.world[node] + if cached then + return cached + end + local m = Scene.nodeMatrix(ctx.scene.nodes[node]) + local p = ctx.parentOf[node] + local w = if p then Mat4.mul(worldOf(ctx, p), m) else m + ctx.world[node] = w + return w +end + +local function addNode(ctx: Ctx, node: Types.Node, parent: number?): number + table.insert(ctx.scene.nodes, node) + local idx = #ctx.scene.nodes + if parent then + table.insert(ctx.scene.nodes[parent].children, idx) + ctx.parentOf[idx] = parent + else + table.insert(ctx.scene.roots, idx) + end + return idx +end + +local function armature(ctx: Ctx, ob: Blend.View, node: number) + local f = ctx.f + local arm = ob:deref("data", 0, "bArmature") + if not arm then + return + end + local pose = ob:deref("pose", 0, "bPose") + local poseNames: { [string]: Blend.View } = {} + if pose then + for _, pc in pose:list("chanbase", "bPoseChannel") do + local n = pc:str("name") + if n then + poseNames[n] = pc + end + end + end + local info = { joints = {}, names = {}, rest = {}, restLocal = {}, bones = {}, deform = {}, node = node, poseNames = poseNames } + local function walk(list: { Blend.View }, parentJoint: number?, parentRest: M4?, depth: number) + if depth > 256 then + return + end + for _, bone in list do + local name = bone:str("name") or "" + local rest = mat4(bone, "arm_mat") or Mat4.identity() + local restLocal = if parentRest then Mat4.mul(Mat4.inverseFull(parentRest) or Mat4.identity(), rest) else rest + local props = poseProps(poseNames[name]) + local basis = objectBasis(props) + local jnode: Types.Node = { name = name, children = {} } + nodeTRS(jnode, Mat4.mul(restLocal, basis)) + local parentNode = if parentJoint then info.joints[parentJoint] else node + local idx = addNode(ctx, jnode, parentNode) + table.insert(info.joints, idx) + table.insert(info.bones, bone) + table.insert(info.rest, rest) + table.insert(info.restLocal, restLocal) + table.insert(info.deform, bit32.band(bone:num("flag") or 0, 0x1000) == 0) + local j = #info.joints + info.names[name] = j + ctx.props[idx] = props + ctx.prefix[idx] = restLocal + jnode.extras = { blend = { bone = true, length = bone:num("length") or 0 } } + walk(bone:list("childbase", "Bone"), j, rest, depth + 1) + end + end + walk(arm:list("bonebase", "Bone"), nil, nil, 0) + ctx.armatures[ob.block and ob.block.addr or node] = info + local _ = f +end + +local function camera(ctx: Ctx, ob: Blend.View, node: number) + local cam = ob:deref("data", 0, "Camera") + if not cam then + return + end + local r = ctx.meta.render + local aspect = r.aspect + local znear, zfar = cam:num("clip_start", "clipsta") or 0.1, cam:num("clip_end", "clipend") or 100 + local c: Types.Camera + if (cam:num("type") or 0) == 1 then + -- files without ortho_scale (before 2.3x) scaled orthographic views by 256 / lens, as Blender's versioning sets it + local half = (cam:num("ortho_scale") or 256 / math.max(cam:num("lens") or 35, 1e-3)) / 2 + local xmag, ymag = half, half / aspect + if aspect < 1 then + xmag, ymag = half * aspect, half + end + c = { name = ob:idName(), type = "orthographic", xmag = xmag, ymag = ymag, znear = znear, zfar = zfar } :: Types.Camera + else + local lens = cam:num("lens") or 50 + local sx, sy = cam:num("sensor_x") or 36, cam:num("sensor_y") or 24 + local fit = cam:num("sensor_fit") or 0 + local yfov + if fit == 2 then + yfov = 2 * math.atan(sy / 2 / lens) + elseif fit == 1 or aspect >= 1 then + yfov = 2 * math.atan(math.tan(math.atan(sx / 2 / lens)) / aspect) + else + yfov = 2 * math.atan(sx / 2 / lens) + end + c = { name = ob:idName(), type = "perspective", yfov = yfov, aspect = aspect, znear = znear, zfar = zfar } :: Types.Camera + end + table.insert(ctx.scene.cameras, c) + ctx.scene.nodes[node].camera = #ctx.scene.cameras +end + +local function light(ctx: Ctx, ob: Blend.View, node: number) + local la = ob:deref("data", 0, "Light") or ob:deref("data", 0, "Lamp") + if not la then + return + end + local t = la:num("type") or 0 + local color = { la:num("r") or 1, la:num("g") or 1, la:num("b") or 1 } + local energy = la:num("energy") or 1 + if ctx.f.version < 280 and ctx.meta.engine ~= "CYCLES" then + -- Blender's 2.8 versioning: Blender Internal energies times 100 (suns unchanged) + if t ~= LA_SUN and t ~= LA_HEMI then + energy *= 100 + end + elseif ctx.f.version < 280 then + -- Cycles took the strength from the lamp's Emission node, else 100 (sun: 1) + energy = if t == LA_SUN or t == LA_HEMI then 1 else 100 + local tree = (la:num("use_nodes") or 0) ~= 0 and la:deref("nodetree", 0, "bNodeTree") or nil + for _, n in if tree then tree:list("nodes", "bNode") else {} do + if n:str("idname") == "ShaderNodeEmission" then + for _, s in n:list("inputs", "bNodeSocket") do + local v = s:str("name") == "Strength" and s:deref("default_value", 0, "bNodeSocketValueFloat") + if v then + energy = v:num("value") or energy + end + end + end + end + end + local name = ob:idName() + local l: Types.Light + if t == LA_SUN or t == LA_HEMI then + l = { name = name, type = "directional", color = color, intensity = energy * W2LM } :: Types.Light + elseif t == LA_SPOT then + local size = la:num("spotsize") or math.rad(45) + if ctx.f.version < 263 then + size = math.rad(size) -- degrees before 2.63 + end + local outer = size / 2 + local blend = la:num("spotblend") or 0 + l = { name = name, type = "spot", color = color, intensity = energy / (4 * math.pi) * W2LM, outerCone = outer, innerCone = outer - outer * blend } :: Types.Light + elseif t == LA_LOCAL then + l = { name = name, type = "point", color = color, intensity = energy / (4 * math.pi) * W2LM } :: Types.Light + else + local skipped = ctx.meta.skippedLights or {} + ctx.meta.skippedLights = skipped + table.insert(skipped, { name = name, type = if t == LA_AREA then "area" else tostring(t) }) + return + end + table.insert(ctx.scene.lights, l) + ctx.scene.nodes[node].light = #ctx.scene.lights +end + +local function slotMaterials(ctx: Ctx, ob: Blend.View, me: Blend.View): { number } + local obMats = ob:pointers("mat", ob:num("totcol")) + local meMats = me:pointers("mat", me:num("totcol")) + local bits = ob:target("matbits") + local n = math.max(#obMats, #meMats) + local out = {} + for i = 1, n do + local useOb = bits ~= nil and i - 1 < bits.size and buffer.readu8(ctx.f.buf, bits.offset + i - 1) ~= 0 + local addr = if useOb then obMats[i] else meMats[i] + local m = 0 + if addr then + local blk = Blend.resolve(ctx.f, addr) + local mv = blk and Blend.struct(ctx.f, blk, 0, "Material") + if mv then + m = Material.get(ctx :: any, mv) + end + end + out[i] = m + end + return out +end + +local function deformArmature(ctx: Ctx, ob: Blend.View): Blend.View? + for _, md in ob:list("modifiers") do + if md.struct.name == "ArmatureModifierData" then + local a = md:deref("object", 0, "Object") + if a then + return a + end + end + end + local p = ob:deref("parent", 0, "Object") + if p and (ob:num("partype") or 0) == PARSKEL and (p:num("type") or -1) == OB_ARMATURE then + return p + end + return nil +end + +local function groupNames(ob: Blend.View, me: Blend.View): { string } + local list = me:list("vertex_group_names", "bDeformGroup") + if #list == 0 then + list = ob:list("defbase", "bDeformGroup") + end + local out = {} + for i, g in list do + out[i] = g:str("name") or "" + end + return out +end + +local function mesh(ctx: Ctx, ob: Blend.View, node: number) + local f = ctx.f + local me = ob:deref("data", 0, "Mesh") + if not me then + return + end + local slots = slotMaterials(ctx, ob, me) + local armOb = deformArmature(ctx, ob) + local armInfo = armOb and armOb.block and ctx.armatures[armOb.block.addr] + local key = tostring(me.block and me.block.index) .. ":" .. table.concat(slots, ",") .. ":" .. tostring(armOb and armOb.block and armOb.block.index) + local skin: Prim.Skinning? = nil + if armInfo then + local joints = {} + for gi, name in groupNames(ob, me) do + local j = armInfo.names[name] + if j and armInfo.deform[j] then + joints[gi - 1] = j - 1 + end + end + skin = { joints = joints } + end + local idx = ctx.meshes[key] + if not idx then + local poly, err = Mesh.read(f, me, { maxVertices = ctx.opts.maxVertices }) + if not poly then + error(err or "bad mesh", 0) + end + local shapes, ref = Mesh.shapes(f, me, poly.nv) + local built = Prim.build(poly, slots, { triangulate = ctx.opts.triangulate, flipV = ctx.opts.flipV }, skin, shapes, ref) + local m = built.mesh + m.extras = { blend = { vertices = poly.nv, faces = poly.nf, corners = poly.nc, generation = poly.generation, uvs = #poly.uvs, colors = #poly.colors, shapes = #shapes } } + table.insert(ctx.scene.meshes, m) + idx = #ctx.scene.meshes + ctx.meshes[key] = idx + local gens = ctx.meta.generations + gens[poly.generation] = (gens[poly.generation] or 0) + 1 + if #shapes > 1 then + ctx.meta.shapeKeys[idx] = { key = me:deref("key", 0, "Key"), mesh = me, shapes = shapes, ref = ref } + end + end + local n = ctx.scene.nodes[node] + n.mesh = idx + if ctx.scene.meshes[idx].weights then + n.weights = table.clone(ctx.scene.meshes[idx].weights :: { number }) + end + if armInfo then + table.insert(ctx.pending, { node = node, ob = ob }) + end +end + +local function skins(ctx: Ctx) + for _, p in ctx.pending do + local armOb = deformArmature(ctx, p.ob) + local info = armOb and armOb.block and ctx.armatures[armOb.block.addr] + if info then + local armWorld = worldOf(ctx, info.node) + local meshWorld = worldOf(ctx, p.node) + local n = #info.joints + local ibm = buffer.create(n * 64) + for j = 1, n do + local inv = Mat4.inverseFull(Mat4.mul(armWorld, info.rest[j])) or Mat4.identity() + local m = Mat4.mul(inv, meshWorld) + for k = 1, 16 do + buffer.writef32(ibm, ((j - 1) * 16 + k - 1) * 4, m[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, n) + acc.matrix = true + table.insert(ctx.scene.skins, { name = armOb and armOb:idName(), joints = table.clone(info.joints), inverseBindMatrices = acc, skeleton = info.node }) + ctx.scene.nodes[p.node].skin = #ctx.scene.skins + end + end +end + +local function object(ctx: Ctx, ob: Blend.View, under: number?, depth: number): number? + local addr = ob.block and ob.block.addr + if addr ~= nil and ctx.objects[addr] then + return ctx.objects[addr] + end + if depth > 512 then + return nil + end + local parentOb = ob:deref("parent", 0, "Object") + local parentNode: number? = under + local prefix = Mat4.identity() + local partype = ob:num("partype") or 0 + if parentOb then + local pn = object(ctx, parentOb, under, depth + 1) + if pn then + parentNode = pn + prefix = mat4(ob, "parentinv") or Mat4.identity() + if partype == PARBONE then + local info = parentOb.block and ctx.armatures[parentOb.block.addr] + local bone = ob:str("parsubstr") or "" + local j = info and info.names[bone] + if info and j then + parentNode = info.joints[j] + local len = info.bones[j]:num("length") or 0 + prefix = Mat4.mul(Mat4.translation(0, len, 0), prefix) + end + end + end + end + if addr ~= nil and ctx.objects[addr] then + return ctx.objects[addr] + end + local props = objectProps(ob) + local node: Types.Node = { name = ob:idName(), children = {} } + nodeTRS(node, Mat4.mul(prefix, objectBasis(props))) + local idx = addNode(ctx, node, parentNode) + if addr ~= nil then + ctx.objects[addr] = idx + end + ctx.objView[idx] = ob + ctx.props[idx] = props + ctx.prefix[idx] = prefix + local t = ob:num("type") or -1 + local extras: { [string]: any } = { type = TYPE_NAME[t] or tostring(t) } + node.extras = { blend = extras } + local lay = ob:num("lay") + if lay and ctx.f.version < 280 then + extras.layers = lay + end + local mods = {} + for _, md in ob:list("modifiers") do + table.insert(mods, { name = md:sub("modifier") and (md:sub("modifier") :: Blend.View):str("name") or md:str("name") or "", type = (string.gsub(md.struct.name, "ModifierData$", "")) }) + end + if #mods > 0 then + extras.modifiers = mods + ctx.meta.modifiers[node.name or tostring(idx)] = mods + end + if t == OB_ARMATURE then + armature(ctx, ob, idx) + elseif t == OB_CAMERA then + camera(ctx, ob, idx) + elseif t == OB_LAMP then + light(ctx, ob, idx) + elseif t ~= OB_EMPTY and t ~= OB_MESH then + ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] = (ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] or 0) + 1 + end + return idx +end + +-- ------------------------------------------------------------------------------------------------ animation +local function apply(props: Props, curves: { Curve }, frame: number, prefix: string?, name: string?): Props + local p: Props = {} + for k, v in props do + p[k] = table.clone(v) + end + for _, c in curves do + local kind, who, rest = Anim.split(c.path) + if (prefix == nil and kind == nil) or (prefix ~= nil and kind == prefix and who == name) then + local arr = p[rest] + if arr and c.index >= 0 and c.index < #arr then + local v = Anim.evaluate(c, frame) + if rest == "rotation_axis_angle" or rest == "delta_rotation_axis_angle" then + arr[c.index + 1] = v + else + arr[c.index + 1] = v + end + end + end + end + return p +end +type Curve = Anim.Curve + +local function frames(lo: number, hi: number, step: number): { number } + local out = {} + local f = lo + while f < hi - 1e-9 and #out < 2 ^ 20 do + table.insert(out, f) + f += step + end + table.insert(out, hi) + return out +end + +type Job = { kind: string, node: number?, nodes: { number }?, info: any?, curves: { Curve }, action: string, meshIdx: number? } + +local function animations(ctx: Ctx) + local f = ctx.f + local jobs: { Job } = {} + -- an IPO shared by several objects animates the first by name only, as Blender's 2.5 conversion leaves it + local ipoOwner: { [any]: string } = {} + for _, ob in ctx.objView do + local a, nm = ob:ptr("ipo"), ob:idName() or "" + if a ~= nil and (ipoOwner[a] == nil or nm < ipoOwner[a]) then + ipoOwner[a] = nm + end + end + for node = 1, #ctx.scene.nodes do + local ob = ctx.objView[node] + local curves, name + if ob then + curves, name = Anim.curves(f, ob:deref("adt", 0, "AnimData")) + local ipoAddr = ob:ptr("ipo") + if not curves and not ob:has("adt") and ipoAddr ~= nil and ipoOwner[ipoAddr] == ob:idName() then + curves, name = Anim.ipo(f, ob:deref("ipo", 0, "Ipo")) + end + end + if curves and #curves > 0 and name then + table.insert(jobs, { kind = "object", node = node, curves = curves, action = name }) + local info = ob.block and ctx.armatures[ob.block.addr] + if info then + table.insert(jobs, { kind = "pose", info = info, curves = curves, action = name }) + end + end + end + for meshIdx, sk in ctx.meta.shapeKeys do + local found, name = Anim.curves(f, sk.key and sk.key:deref("adt", 0, "AnimData")) + local curves: { Curve }? = found + if not curves and sk.key and not sk.key:has("adt") then + local names = {} + for i, s in sk.shapes do + names[i] = s.name + end + curves, name = Anim.ipo(f, sk.key:deref("ipo", 0, "Ipo"), names) + end + -- 2.7x could key shape values from the mesh ("shape_keys.key_blocks[...].value") + local mc, mname = Anim.curves(f, sk.mesh:deref("adt", 0, "AnimData")) + for _, c in mc or {} do + if string.sub(c.path, 1, 11) == "shape_keys." then + c.path = string.sub(c.path, 12) + local list: { Curve } = curves or {} + curves = list + name = name or mname + table.insert(list, c) + end + end + if curves and #curves > 0 and name then + local nodes = {} + for i, n in ctx.scene.nodes do + if n.mesh == meshIdx then + table.insert(nodes, i) + end + end + table.insert(jobs, { kind = "shapes", nodes = nodes, curves = curves :: { Curve }, action = name, meshIdx = meshIdx }) + end + end + if #jobs == 0 then + return + end + table.sort(jobs, function(a: Job, b: Job): boolean + return a.action < b.action + end) + local zero = ctx.meta.frameStart + for _, j in jobs do + local lo = Anim.range(j.curves) + zero = math.min(zero, math.floor(lo)) + end + ctx.meta.frameZero = zero + local fps = ctx.meta.fps + local step = ctx.opts.sampleStep or 1 + local byAction: { [string]: Types.Animation } = {} + for _, j in jobs do + local anim = byAction[j.action] + if not anim then + anim = { name = j.action, channels = {} } :: Types.Animation + byAction[j.action] = anim + table.insert(ctx.scene.animations, anim) + end + local lo, hi = Anim.range(j.curves) + local fs = frames(math.floor(lo), math.ceil(hi), step) -- whole frames, as Blender plays them + local times = {} + for i, fr in fs do + times[i] = (fr - zero) / fps + end + local tmp = Scene.new() + if j.kind == "object" then + local node = j.node :: number + local track = { translation = {}, rotation = {}, scale = {} } + local last: { number }? = nil + for _, fr in fs do + local p = apply(ctx.props[node], j.curves, fr, nil, nil) + local t, r, s = Mat4.decompose(Mat4.mul(ctx.prefix[node], objectBasis(p))) + if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + last = r + table.move(t, 1, 3, #track.translation + 1, track.translation) + table.move(r, 1, 4, #track.rotation + 1, track.rotation) + table.move(s, 1, 3, #track.scale + 1, track.scale) + end + local nd = ctx.scene.nodes[node] + if nd.matrix then + local t, r, s = Mat4.decompose(nd.matrix) + nd.translation, nd.rotation, nd.scale, nd.matrix = t, r, s, nil + end + Rig.animation(tmp, nil, { node }, times, { [1] = track :: any }, nil) + elseif j.kind == "pose" then + local info = j.info + local tracks = {} + local touched = {} + for _, c in j.curves do + local kind, who = Anim.split(c.path) + if kind == "pose.bones" and who and info.names[who] then + touched[info.names[who]] = true + end + end + for b in touched do + local name = info.bones[b]:str("name") or "" + local node = info.joints[b] + local track = { translation = {}, rotation = {}, scale = {} } + local last: { number }? = nil + for _, fr in fs do + local p = apply(ctx.props[node], j.curves, fr, "pose.bones", name) + local t, r, s = Mat4.decompose(Mat4.mul(info.restLocal[b], objectBasis(p))) + if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + last = r + table.move(t, 1, 3, #track.translation + 1, track.translation) + table.move(r, 1, 4, #track.rotation + 1, track.rotation) + table.move(s, 1, 3, #track.scale + 1, track.scale) + end + tracks[b] = track + end + Rig.animation(tmp, nil, info.joints, times, tracks :: any, nil) + elseif j.kind == "shapes" then + local sk = ctx.meta.shapeKeys[j.meshIdx] + local count = #sk.shapes - 1 + local out = buffer.create(#fs * count * 4) + for i, fr in fs do + local k = 0 + for si, s in sk.shapes do + if si ~= sk.ref then + local v = s.value + for _, c in j.curves do + local kind, who, rest = Anim.split(c.path) + if kind == "key_blocks" and who == s.name and rest == "value" then + v = math.clamp(Anim.evaluate(c, fr), math.min(s.min, s.max), math.max(s.min, s.max)) -- the slider range + end + end + buffer.writef32(out, ((i - 1) * count + k) * 4, v) + k += 1 + end + end + end + local tb = buffer.create(#times * 4) + for i, t in times do + buffer.writef32(tb, (i - 1) * 4, t) + end + for _, node in j.nodes :: { number } do + table.insert(tmp.animations, { channels = { + { node = node, path = "weights" :: any, input = Scene.accessor(tb, "f32", 1, #times), output = Scene.accessor(out, "f32", 1, #fs * count), interpolation = "LINEAR" :: any }, + } }) + end + end + for _, a in tmp.animations do + for _, ch in a.channels do + table.insert(anim.channels, ch) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ entry +local function pickScene(f: Blend.File, name: string?): Blend.View? + local scenes = Blend.blocks(f, "SC") + if name then + for _, b in scenes do + local v = Blend.struct(f, b, 0, "Scene") + if v and v:idName() == name then + return v + end + end + return nil + end + local glob = Blend.blocks(f, "GLOB")[1] + local g = glob and Blend.struct(f, glob, 0, "FileGlobal") + local cur = g and g:target("curscene") + if cur and cur.code == "SC" then + return Blend.struct(f, cur, 0, "Scene") + end + return if scenes[1] then Blend.struct(f, scenes[1], 0, "Scene") else nil +end + +function Read.scene(f: Blend.File, opts: Options?): (Types.Scene?, string?) + local o: Options = opts or {} + local scene = Scene.new() + local sc = pickScene(f, o.scene) + if o.scene and not sc then + return nil, "no scene named " .. o.scene + end + local meta: { [string]: any } = { + modifiers = {}, unsupported = {}, generations = {}, shapeKeys = {}, collections = {}, + fps = 24, frameStart = 1, render = { aspect = 16 / 9 }, + } + local ctx: Ctx = { + f = f, scene = scene, opts = o, objects = {}, objView = {}, parentOf = {}, world = {}, meshes = {}, materials = {}, + textures = {}, armatures = {}, prefix = {}, props = {}, meta = meta, pending = {}, + } + local order: { { ob: Blend.View, under: number? } } = {} + if sc then + local r = sc:sub("r") + if r then + local fps = (r:num("frs_sec") or 24) / math.max(r:num("frs_sec_base") or 1, 1e-6) + meta.fps = if fps > 0 then fps else 24 + meta.frameStart = r:num("sfra") or 1 + meta.engine = r:str("engine") + local xs, ys = r:num("xsch") or 1920, r:num("ysch") or 1080 + local xa, ya = r:num("xasp") or 1, r:num("yasp") or 1 + if xs > 0 and ys > 0 and xa > 0 and ya > 0 then + meta.render = { aspect = (xs * xa) / (ys * ya), width = xs, height = ys } + end + end + local units = sc:sub("unit") + local scale = units and units:num("scale_length") + if scale and scale > 0 then + scene.meta.unit = scale + end + local master = sc:deref("master_collection", 0, "Collection") + if master then + local seen = {} + local function walk(col: Blend.View, under: number?, depth: number) + if depth > 64 or (col.block and seen[col.block.addr]) then + return + end + if col.block then + seen[col.block.addr] = true + end + for _, co in col:list("gobject", "CollectionObject") do + local ob = co:deref("ob", 0, "Object") + if ob then + table.insert(order, { ob = ob, under = under }) + end + end + for _, cc in col:list("children", "CollectionChild") do + local child = cc:deref("collection", 0, "Collection") + if child then + local cn: number? = nil + if o.collections ~= false then + cn = addNode(ctx, { name = child:idName(), children = {}, extras = { blend = { collection = true } } }, under) + end + table.insert(meta.collections, child:idName() or "") + walk(child, cn, depth + 1) + end + end + end + walk(master, nil, 0) + else + for _, base in sc:list("base", "Base") do + local ob = base:deref("object", 0, "Object") + if ob then + table.insert(order, { ob = ob, under = nil }) + end + end + end + end + if #order == 0 then + for _, b in Blend.blocks(f, "OB") do + local ob = Blend.struct(f, b, 0, "Object") + if ob then + table.insert(order, { ob = ob, under = nil }) + end + end + end + local firstUnder: { [any]: number? } = {} + for _, e in order do + local a = e.ob.block and e.ob.block.addr + if a ~= nil and firstUnder[a] == nil then + firstUnder[a] = e.under or 0 + end + end + for _, e in order do + local a = e.ob.block and e.ob.block.addr + local u = a ~= nil and firstUnder[a] or nil + object(ctx, e.ob, if u and u > 0 then u else nil, 0) + end + for node = 1, #scene.nodes do + local ob = ctx.objView[node] + if ob and (ob:num("type") or -1) == OB_MESH then + mesh(ctx, ob, node) + end + end + skins(ctx) + if o.animations ~= false then + animations(ctx) + end + meta.shapeKeys = nil + meta.engine = nil + local render = meta.render + meta.render = nil + scene.meta.up = "z" + scene.meta.source = { + format = "blend", version = f.version, subversion = f.subversion, pointerSize = f.pointerSize, + littleEndian = f.little, compression = f.compression, fps = meta.fps, frameStart = meta.frameStart, + frameZero = meta.frameZero, modifiers = meta.modifiers, unsupported = meta.unsupported, + generations = meta.generations, collections = meta.collections, skippedLights = meta.skippedLights, + aspect = render.aspect, scene = sc and sc:idName(), + } + return scene, nil +end + return Read end __FILES["model/bsp"] = function() diff --git a/build/Rosetta.luau.linemap.json b/build/Rosetta.luau.linemap.json index f0d926f..cbf2a44 100644 --- a/build/Rosetta.luau.linemap.json +++ b/build/Rosetta.luau.linemap.json @@ -1,539 +1,547 @@ [ [27, "src/Rosetta/init.luau"], [871, "src/Rosetta/Registry.luau"], -[2980, "src/Rosetta/Types.luau"], -[4063, "src/Rosetta/archive/7z/init.luau"], -[4448, "src/Rosetta/archive/7z/Header.luau"], -[4975, "src/Rosetta/archive/adf/init.luau"], -[5257, "src/Rosetta/archive/applesingle/init.luau"], -[5443, "src/Rosetta/archive/ar/init.luau"], -[5846, "src/Rosetta/archive/arj/init.luau"], -[6056, "src/Rosetta/archive/binhex/init.luau"], -[6305, "src/Rosetta/archive/br/init.luau"], -[6380, "src/Rosetta/archive/bz2/init.luau"], -[6444, "src/Rosetta/archive/cab/init.luau"], -[6857, "src/Rosetta/archive/cab/Sum.luau"], -[6898, "src/Rosetta/archive/cpio/init.luau"], -[7066, "src/Rosetta/archive/d64/init.luau"], -[7480, "src/Rosetta/archive/fat/init.luau"], -[7602, "src/Rosetta/archive/grp/init.luau"], -[7716, "src/Rosetta/archive/gzip/init.luau"], -[7901, "src/Rosetta/archive/iso/init.luau"], -[7973, "src/Rosetta/archive/lha/init.luau"], -[8398, "src/Rosetta/archive/lz4/init.luau"], -[8742, "src/Rosetta/archive/macbinary/init.luau"], -[8940, "src/Rosetta/archive/mpq/init.luau"], -[9346, "src/Rosetta/archive/mpq/Crypt.luau"], -[9411, "src/Rosetta/archive/pak/init.luau"], -[9545, "src/Rosetta/archive/rpm/init.luau"], -[9869, "src/Rosetta/archive/tar/init.luau"], -[9987, "src/Rosetta/archive/uu/init.luau"], -[10257, "src/Rosetta/archive/vpk/init.luau"], -[10568, "src/Rosetta/archive/wad/init.luau"], -[11018, "src/Rosetta/archive/wad/Map.luau"], -[11448, "src/Rosetta/archive/wad/Picture.luau"], -[11550, "src/Rosetta/archive/xz/init.luau"], -[11650, "src/Rosetta/archive/yenc/init.luau"], -[11922, "src/Rosetta/archive/z/init.luau"], -[12018, "src/Rosetta/archive/zip/init.luau"], -[12237, "src/Rosetta/archive/zoo/init.luau"], -[12433, "src/Rosetta/archive/zst/init.luau"], -[12497, "src/Rosetta/audio/aac/init.luau"], -[12703, "src/Rosetta/audio/ac3/init.luau"], -[12849, "src/Rosetta/audio/adpcm/init.luau"], -[12994, "src/Rosetta/audio/adx/init.luau"], -[13225, "src/Rosetta/audio/aiff/init.luau"], -[13616, "src/Rosetta/audio/ape/init.luau"], -[13744, "src/Rosetta/audio/au/init.luau"], -[13905, "src/Rosetta/audio/brstm/init.luau"], -[14196, "src/Rosetta/audio/caf/init.luau"], -[14858, "src/Rosetta/audio/flac/init.luau"], -[15006, "src/Rosetta/audio/flac/Meta.luau"], -[15228, "src/Rosetta/audio/flac/Stream.luau"], -[15598, "src/Rosetta/audio/m4a/init.luau"], -[15932, "src/Rosetta/audio/mp3/init.luau"], -[16192, "src/Rosetta/audio/mp3/Index.luau"], -[16383, "src/Rosetta/audio/mp3/Stream.luau"], -[16610, "src/Rosetta/audio/mp3/Tags.luau"], -[16922, "src/Rosetta/audio/mpc/init.luau"], -[17016, "src/Rosetta/audio/opus/init.luau"], -[17394, "src/Rosetta/audio/opus/Encode.luau"], -[17505, "src/Rosetta/audio/qoa/init.luau"], -[17685, "src/Rosetta/audio/tta/init.luau"], -[17803, "src/Rosetta/audio/vag/init.luau"], -[18026, "src/Rosetta/audio/voc/init.luau"], -[18301, "src/Rosetta/audio/vorbis/init.luau"], -[18755, "src/Rosetta/audio/vorbis/Encode.luau"], -[19568, "src/Rosetta/audio/wav/init.luau"], -[20189, "src/Rosetta/audio/wav/Codecs.luau"], -[20355, "src/Rosetta/audio/wavpack/init.luau"], -[20562, "src/Rosetta/cad/step/init.luau"], -[20944, "src/Rosetta/cad/step/Brep.luau"], -[21179, "src/Rosetta/cad/step/Parse.luau"], -[21736, "src/Rosetta/cad/step/Write.luau"], -[21984, "src/Rosetta/codecs/audio/Aac/init.luau"], -[22303, "src/Rosetta/codecs/audio/Aac/Decode.luau"], -[23186, "src/Rosetta/codecs/audio/Aac/Tables.luau"], -[23521, "src/Rosetta/codecs/audio/Ac3/init.luau"], -[23680, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], -[24565, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], -[24666, "src/Rosetta/codecs/audio/Adpcm/init.luau"], -[25420, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], -[25722, "src/Rosetta/codecs/audio/Alac/init.luau"], -[25956, "src/Rosetta/codecs/audio/Alac/Decode.luau"], -[26375, "src/Rosetta/codecs/audio/Alac/Encode.luau"], -[26787, "src/Rosetta/codecs/audio/Ape/init.luau"], -[27002, "src/Rosetta/codecs/audio/Ape/Decode.luau"], -[27763, "src/Rosetta/codecs/audio/ApeTag.luau"], -[27860, "src/Rosetta/codecs/audio/Flac/init.luau"], -[27871, "src/Rosetta/codecs/audio/Flac/Encode.luau"], -[28820, "src/Rosetta/codecs/audio/Flac/Frame.luau"], -[29417, "src/Rosetta/codecs/audio/Hively/init.luau"], -[29613, "src/Rosetta/codecs/audio/Hively/Load.luau"], -[29862, "src/Rosetta/codecs/audio/Hively/Player.luau"], -[30820, "src/Rosetta/codecs/audio/Hively/Tables.luau"], -[31039, "src/Rosetta/codecs/audio/Mdct/init.luau"], -[31223, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], -[31432, "src/Rosetta/codecs/audio/MidiRender.luau"], -[31778, "src/Rosetta/codecs/audio/Mpa/init.luau"], -[31792, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], -[31851, "src/Rosetta/codecs/audio/Mpa/Core.luau"], -[33454, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], -[33746, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], -[34131, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], -[34772, "src/Rosetta/codecs/audio/Mpa/Header.luau"], -[34913, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], -[35139, "src/Rosetta/codecs/audio/Musepack/init.luau"], -[35484, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], -[36365, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], -[36743, "src/Rosetta/codecs/audio/Opus/init.luau"], -[36757, "src/Rosetta/codecs/audio/Opus/Celt.luau"], -[38604, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], -[39669, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], -[39729, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], -[40189, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], -[40526, "src/Rosetta/codecs/audio/Opus/Packet.luau"], -[40759, "src/Rosetta/codecs/audio/Opus/Silk.luau"], -[42795, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], -[43169, "src/Rosetta/codecs/audio/Pcm/init.luau"], -[43432, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], -[43729, "src/Rosetta/codecs/audio/Qoa/init.luau"], -[44011, "src/Rosetta/codecs/audio/Resample/init.luau"], -[44370, "src/Rosetta/codecs/audio/SoundFont/init.luau"], -[44424, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], -[44567, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], -[45080, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], -[45861, "src/Rosetta/codecs/audio/Stream.luau"], -[46022, "src/Rosetta/codecs/audio/Tracker/init.luau"], -[46504, "src/Rosetta/codecs/audio/Tracker/Load.luau"], -[46782, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], -[46951, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], -[47079, "src/Rosetta/codecs/audio/Tracker/Player.luau"], -[49067, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], -[49183, "src/Rosetta/codecs/audio/Tta/init.luau"], -[49300, "src/Rosetta/codecs/audio/Tta/Decode.luau"], -[49552, "src/Rosetta/codecs/audio/Vorbis/init.luau"], -[49565, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], -[49949, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], -[50515, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], -[50936, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], -[50975, "src/Rosetta/codecs/audio/VorbisComment.luau"], -[51027, "src/Rosetta/codecs/audio/WavPack/init.luau"], -[51249, "src/Rosetta/codecs/audio/WavPack/Block.luau"], -[52704, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], -[52767, "src/Rosetta/codecs/compress/Brotli/init.luau"], -[52854, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], -[53823, "src/Rosetta/codecs/compress/Brotli/Static.luau"], -[54691, "src/Rosetta/codecs/compress/Bzip2/init.luau"], -[54739, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], -[55255, "src/Rosetta/codecs/compress/Deflate/init.luau"], -[55581, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], -[56001, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], -[56436, "src/Rosetta/codecs/compress/Explode.luau"], -[56632, "src/Rosetta/codecs/compress/Lz4.luau"], -[56901, "src/Rosetta/codecs/compress/Lzh/init.luau"], -[57505, "src/Rosetta/codecs/compress/Lzma/init.luau"], -[58045, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], -[58083, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], -[58556, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], -[58732, "src/Rosetta/codecs/compress/Lzw/init.luau"], -[59000, "src/Rosetta/codecs/compress/Lzx.luau"], -[59434, "src/Rosetta/codecs/compress/PackBits.luau"], -[59524, "src/Rosetta/codecs/compress/Quantum.luau"], -[59761, "src/Rosetta/codecs/compress/UnixCompress.luau"], -[60065, "src/Rosetta/codecs/compress/Xxh32.luau"], -[60134, "src/Rosetta/codecs/compress/Zstd/init.luau"], -[60191, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], -[61149, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], -[61301, "src/Rosetta/codecs/entropy/Huffman.luau"], -[61583, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], -[61594, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], -[61808, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], -[62052, "src/Rosetta/codecs/font/Bitmap.luau"], -[62253, "src/Rosetta/codecs/font/Cff/init.luau"], -[62894, "src/Rosetta/codecs/font/GlyphNames.luau"], -[63044, "src/Rosetta/codecs/font/TrueType/init.luau"], -[63358, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], -[63750, "src/Rosetta/codecs/font/TrueType/Tables.luau"], -[64252, "src/Rosetta/codecs/image/Bcn/init.luau"], -[64359, "src/Rosetta/codecs/image/Bcn/Decode.luau"], -[64848, "src/Rosetta/codecs/image/Bcn/Encode.luau"], -[65277, "src/Rosetta/codecs/image/Blend.luau"], -[65656, "src/Rosetta/codecs/image/Dct/init.luau"], -[66037, "src/Rosetta/codecs/image/Etc.luau"], -[66335, "src/Rosetta/codecs/image/Half.luau"], -[66404, "src/Rosetta/codecs/image/Jpeg/init.luau"], -[66758, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], -[67166, "src/Rosetta/codecs/image/Jpeg/Color.luau"], -[67403, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], -[68163, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], -[69044, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], -[69490, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], -[69568, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], -[69635, "src/Rosetta/codecs/image/Pixels.luau"], -[69899, "src/Rosetta/codecs/image/Quantize/init.luau"], -[70358, "src/Rosetta/codecs/image/Raster.luau"], -[71055, "src/Rosetta/codecs/image/Texel.luau"], -[71428, "src/Rosetta/codecs/image/Texture.luau"], -[71573, "src/Rosetta/codecs/image/Vp8/init.luau"], -[71703, "src/Rosetta/codecs/image/Vp8/Decode.luau"], -[73659, "src/Rosetta/codecs/image/Vp8/Predict.luau"], -[73918, "src/Rosetta/codecs/image/Vp8/Tables.luau"], -[74167, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], -[74286, "src/Rosetta/codecs/image/Vp8L/init.luau"], -[74390, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], -[75243, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], -[76195, "src/Rosetta/codecs/image/Yuv.luau"], -[76463, "src/Rosetta/codecs/model/Draco/init.luau"], -[76795, "src/Rosetta/codecs/model/Draco/Attributes.luau"], -[77264, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], -[78453, "src/Rosetta/codecs/model/Draco/Int64.luau"], -[78602, "src/Rosetta/codecs/model/Draco/KdTree.luau"], -[78961, "src/Rosetta/codecs/model/Draco/Predict.luau"], -[79923, "src/Rosetta/codecs/model/Draco/Reader.luau"], -[80397, "src/Rosetta/codecs/model/Mat4.luau"], -[80656, "src/Rosetta/codecs/model/MeshFlatten.luau"], -[81184, "src/Rosetta/codecs/model/Minecraft/init.luau"], -[81736, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], -[81815, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], -[81922, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], -[82128, "src/Rosetta/codecs/model/Polygon.luau"], -[82362, "src/Rosetta/codecs/model/Rbx/init.luau"], -[82599, "src/Rosetta/codecs/model/Rbx/Binary.luau"], -[83353, "src/Rosetta/codecs/model/Rig.luau"], -[83596, "src/Rosetta/codecs/model/Sampler.luau"], -[83756, "src/Rosetta/codecs/model/Vrml/init.luau"], -[83904, "src/Rosetta/codecs/model/Vrml/Build.luau"], -[84478, "src/Rosetta/codecs/model/Vrml/Fields.luau"], -[84641, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], -[85390, "src/Rosetta/codecs/model/Vrml/Parse.luau"], -[85912, "src/Rosetta/codecs/model/Vrml/Write.luau"], -[86639, "src/Rosetta/codecs/model/Vrml/Xml.luau"], -[86871, "src/Rosetta/codecs/text/Json/init.luau"], -[87140, "src/Rosetta/codecs/text/Json/Decode.luau"], -[87554, "src/Rosetta/codecs/text/Json/Encode.luau"], -[87856, "src/Rosetta/codecs/text/Nbt/init.luau"], -[88209, "src/Rosetta/codecs/text/Nbt/Binary.luau"], -[88901, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], -[89541, "src/Rosetta/codecs/text/Nbt/Value.luau"], -[89779, "src/Rosetta/codecs/text/Text/init.luau"], -[89870, "src/Rosetta/codecs/text/Url/init.luau"], -[90075, "src/Rosetta/codecs/text/Xml/init.luau"], -[90478, "src/Rosetta/codecs/text/Xml/Parse.luau"], -[91218, "src/Rosetta/codecs/video/Dsp.luau"], -[91941, "src/Rosetta/codecs/video/H263/init.luau"], -[92097, "src/Rosetta/codecs/video/H263/Decoder.luau"], -[92955, "src/Rosetta/codecs/video/H263/Tables.luau"], -[93158, "src/Rosetta/codecs/video/H264/init.luau"], -[93531, "src/Rosetta/codecs/video/H264/Bitstream.luau"], -[93806, "src/Rosetta/codecs/video/H264/Cabac.luau"], -[94937, "src/Rosetta/codecs/video/H264/Cavlc.luau"], -[95705, "src/Rosetta/codecs/video/H264/Deblock.luau"], -[95963, "src/Rosetta/codecs/video/H264/Decoder.luau"], -[96972, "src/Rosetta/codecs/video/H264/Inter.luau"], -[97226, "src/Rosetta/codecs/video/H264/Intra.luau"], -[97633, "src/Rosetta/codecs/video/H264/Mb.luau"], -[98539, "src/Rosetta/codecs/video/H264/Params.luau"], -[98986, "src/Rosetta/codecs/video/H264/Slice.luau"], -[99237, "src/Rosetta/codecs/video/H264/Tables.luau"], -[99278, "src/Rosetta/codecs/video/H264/Transform.luau"], -[99443, "src/Rosetta/codecs/video/Legacy/init.luau"], -[99641, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], -[99938, "src/Rosetta/codecs/video/Legacy/Flic.luau"], -[100305, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], -[100423, "src/Rosetta/codecs/video/Legacy/Picture.luau"], -[100531, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], -[100804, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], -[101199, "src/Rosetta/codecs/video/Legacy/Smc.luau"], -[101376, "src/Rosetta/codecs/video/Mpeg1/init.luau"], -[101388, "src/Rosetta/codecs/video/Mpeg2/init.luau"], -[101755, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], -[103262, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], -[103401, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], -[103539, "src/Rosetta/codecs/video/Theora/init.luau"], -[103802, "src/Rosetta/codecs/video/Theora/Decoder.luau"], -[105066, "src/Rosetta/codecs/video/Theora/Header.luau"], -[105429, "src/Rosetta/codecs/video/Video/init.luau"], -[105986, "src/Rosetta/codecs/video/Video/Source.luau"], -[106271, "src/Rosetta/containers/Archive.luau"], -[106538, "src/Rosetta/containers/AudioWrap.luau"], -[107041, "src/Rosetta/containers/Avi/init.luau"], -[107593, "src/Rosetta/containers/Chunks.luau"], -[107728, "src/Rosetta/containers/Cpio.luau"], -[108156, "src/Rosetta/containers/Demux.luau"], -[108431, "src/Rosetta/containers/Ebml/init.luau"], -[108744, "src/Rosetta/containers/Fat.luau"], -[109432, "src/Rosetta/containers/Iso9660.luau"], -[109937, "src/Rosetta/containers/IsoBmff/init.luau"], -[110107, "src/Rosetta/containers/IsoBmff/Box.luau"], -[110295, "src/Rosetta/containers/IsoBmff/Demux.luau"], -[111140, "src/Rosetta/containers/IsoBmff/Meta.luau"], -[111661, "src/Rosetta/containers/IsoBmff/Mux.luau"], -[112177, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], -[112294, "src/Rosetta/containers/MacFile.luau"], -[112443, "src/Rosetta/containers/MpegEs.luau"], -[112609, "src/Rosetta/containers/MpegPs/init.luau"], -[112829, "src/Rosetta/containers/MpegTs/init.luau"], -[113621, "src/Rosetta/containers/Ogg/init.luau"], -[114046, "src/Rosetta/containers/Ogg/Mux.luau"], -[114241, "src/Rosetta/containers/Ogg/Page.luau"], -[114410, "src/Rosetta/containers/Riff/init.luau"], -[114727, "src/Rosetta/containers/Tar.luau"], -[115141, "src/Rosetta/containers/Zip/init.luau"], -[115773, "src/Rosetta/core/Adler32.luau"], -[115819, "src/Rosetta/core/Base64.luau"], -[115978, "src/Rosetta/core/Bits.luau"], -[116271, "src/Rosetta/core/Bytes.luau"], -[116798, "src/Rosetta/core/Crc16.luau"], -[116850, "src/Rosetta/core/Crc32.luau"], -[116962, "src/Rosetta/core/Err.luau"], -[117044, "src/Rosetta/core/Input.luau"], -[117120, "src/Rosetta/core/Md5.luau"], -[117279, "src/Rosetta/core/Sniff.luau"], -[117308, "src/Rosetta/data/cbor/init.luau"], -[117407, "src/Rosetta/data/cbor/Codec.luau"], -[117976, "src/Rosetta/data/csv/init.luau"], -[118288, "src/Rosetta/data/ini/init.luau"], -[118534, "src/Rosetta/data/json/init.luau"], -[118626, "src/Rosetta/data/msgpack/init.luau"], -[118715, "src/Rosetta/data/msgpack/Codec.luau"], -[119157, "src/Rosetta/data/nbt/init.luau"], -[119216, "src/Rosetta/data/plist/init.luau"], -[119522, "src/Rosetta/data/plist/Binary.luau"], -[119789, "src/Rosetta/data/snbt/init.luau"], -[119852, "src/Rosetta/data/toml/init.luau"], -[119919, "src/Rosetta/data/toml/Decode.luau"], -[120547, "src/Rosetta/data/toml/Encode.luau"], -[120756, "src/Rosetta/data/xml/init.luau"], -[120812, "src/Rosetta/data/yaml/init.luau"], -[120885, "src/Rosetta/data/yaml/Emit.luau"], -[121175, "src/Rosetta/data/yaml/Parse.luau"], -[122468, "src/Rosetta/font/bdf/init.luau"], -[122757, "src/Rosetta/font/bmfont/init.luau"], -[123184, "src/Rosetta/font/bmfont/Parse.luau"], -[123637, "src/Rosetta/font/eot/init.luau"], -[123869, "src/Rosetta/font/fon/init.luau"], -[124152, "src/Rosetta/font/hershey/init.luau"], -[124347, "src/Rosetta/font/pcf/init.luau"], -[124627, "src/Rosetta/font/psf/init.luau"], -[124947, "src/Rosetta/font/ttf/init.luau"], -[124998, "src/Rosetta/font/type1/init.luau"], -[125357, "src/Rosetta/font/type1/Charstring.luau"], -[125635, "src/Rosetta/font/woff/init.luau"], -[125767, "src/Rosetta/font/woff2/init.luau"], -[125824, "src/Rosetta/font/woff2/Rebuild.luau"], -[126364, "src/Rosetta/host/init.luau"], -[126409, "src/Rosetta/host/Love.luau"], -[126552, "src/Rosetta/host/LuaJIT.luau"], -[126602, "src/Rosetta/host/Luau.luau"], -[126625, "src/Rosetta/host/Roblox.luau"], -[126984, "src/Rosetta/image/ani/init.luau"], -[127164, "src/Rosetta/image/blp/init.luau"], -[127422, "src/Rosetta/image/bmp/init.luau"], -[127837, "src/Rosetta/image/dds/init.luau"], -[128320, "src/Rosetta/image/exr/init.luau"], -[129080, "src/Rosetta/image/exr/Codec.luau"], -[129191, "src/Rosetta/image/exr/Piz.luau"], -[129548, "src/Rosetta/image/gif/init.luau"], -[130064, "src/Rosetta/image/gif/Decode.luau"], -[130127, "src/Rosetta/image/hdr/init.luau"], -[130356, "src/Rosetta/image/hdr/Codec.luau"], -[130567, "src/Rosetta/image/icns/init.luau"], -[130898, "src/Rosetta/image/ico/init.luau"], -[131175, "src/Rosetta/image/ico/Dib.luau"], -[131270, "src/Rosetta/image/ilbm/init.luau"], -[131589, "src/Rosetta/image/jpeg/init.luau"], -[131725, "src/Rosetta/image/ktx/init.luau"], -[132385, "src/Rosetta/image/pcx/init.luau"], -[132649, "src/Rosetta/image/png/init.luau"], -[133229, "src/Rosetta/image/png/Apng.luau"], -[133309, "src/Rosetta/image/png/Decode.luau"], -[133549, "src/Rosetta/image/png/Encode.luau"], -[133704, "src/Rosetta/image/pnm/init.luau"], -[134082, "src/Rosetta/image/pnm/Codec.luau"], -[134359, "src/Rosetta/image/qoi/init.luau"], -[134481, "src/Rosetta/image/qoi/Codec.luau"], -[134631, "src/Rosetta/image/sgi/init.luau"], -[134916, "src/Rosetta/image/sunras/init.luau"], -[135162, "src/Rosetta/image/tga/init.luau"], -[135432, "src/Rosetta/image/tga/Codec.luau"], -[135584, "src/Rosetta/image/tiff/init.luau"], -[136411, "src/Rosetta/image/tiff/Pixels.luau"], -[136801, "src/Rosetta/image/tim/init.luau"], -[137043, "src/Rosetta/image/vtf/init.luau"], -[137278, "src/Rosetta/image/webp/init.luau"], -[137888, "src/Rosetta/image/webp/Alpha.luau"], -[137964, "src/Rosetta/image/webp/Anim.luau"], -[138119, "src/Rosetta/image/xbm/init.luau"], -[138280, "src/Rosetta/image/xpm/init.luau"], -[138548, "src/Rosetta/image/xpm/Names.luau"], -[138604, "src/Rosetta/layered/aseprite/init.luau"], -[139342, "src/Rosetta/layered/ora/init.luau"], -[139629, "src/Rosetta/layered/psd/init.luau"], -[140364, "src/Rosetta/layered/psd/Channels.luau"], -[140716, "src/Rosetta/model/3ds/init.luau"], -[140799, "src/Rosetta/model/3ds/Build.luau"], -[141446, "src/Rosetta/model/3ds/Read.luau"], -[141942, "src/Rosetta/model/3ds/Write.luau"], -[142747, "src/Rosetta/model/3mf/init.luau"], -[142829, "src/Rosetta/model/3mf/Read.luau"], -[143417, "src/Rosetta/model/3mf/Write.luau"], -[143822, "src/Rosetta/model/b3d/init.luau"], -[143877, "src/Rosetta/model/b3d/Read.luau"], -[144448, "src/Rosetta/model/bsp/init.luau"], -[144593, "src/Rosetta/model/bsp/Brush.luau"], -[144871, "src/Rosetta/model/bsp/Quake3.luau"], -[145126, "src/Rosetta/model/dae/init.luau"], -[145315, "src/Rosetta/model/dae/Math.luau"], -[145362, "src/Rosetta/model/dae/Read.luau"], -[147212, "src/Rosetta/model/dae/Write.luau"], -[147581, "src/Rosetta/model/fbx/init.luau"], -[147729, "src/Rosetta/model/fbx/Ascii.luau"], -[147999, "src/Rosetta/model/fbx/Binary.luau"], -[148454, "src/Rosetta/model/fbx/Read.luau"], -[149816, "src/Rosetta/model/fbx/Write.luau"], -[150801, "src/Rosetta/model/fbx/Xform.luau"], -[150842, "src/Rosetta/model/gltf/init.luau"], -[151079, "src/Rosetta/model/gltf/Pack.luau"], -[151148, "src/Rosetta/model/gltf/Read.luau"], -[151879, "src/Rosetta/model/gltf/Write.luau"], -[152559, "src/Rosetta/model/iqm/init.luau"], -[152635, "src/Rosetta/model/iqm/Read.luau"], -[152990, "src/Rosetta/model/iqm/Write.luau"], -[153677, "src/Rosetta/model/ldraw/init.luau"], -[153755, "src/Rosetta/model/ldraw/Colors.luau"], -[154073, "src/Rosetta/model/ldraw/Read.luau"], -[154650, "src/Rosetta/model/lwo/init.luau"], -[154726, "src/Rosetta/model/lwo/Build.luau"], -[155188, "src/Rosetta/model/lwo/Parse.luau"], -[155731, "src/Rosetta/model/mca/init.luau"], -[156073, "src/Rosetta/model/mca/Chunk.luau"], -[156206, "src/Rosetta/model/mca/Lz4Block.luau"], -[156276, "src/Rosetta/model/md2/init.luau"], -[156475, "src/Rosetta/model/md3/init.luau"], -[156703, "src/Rosetta/model/md5/init.luau"], -[156784, "src/Rosetta/model/md5/Read.luau"], -[157217, "src/Rosetta/model/mdl/init.luau"], -[157299, "src/Rosetta/model/mdl/HalfLife.luau"], -[157627, "src/Rosetta/model/mdl/Quake.luau"], -[157845, "src/Rosetta/model/ms3d/init.luau"], -[157917, "src/Rosetta/model/ms3d/Read.luau"], -[158363, "src/Rosetta/model/ms3d/Write.luau"], -[158832, "src/Rosetta/model/obj/init.luau"], -[159574, "src/Rosetta/model/obj/Mtl.luau"], -[159861, "src/Rosetta/model/off/init.luau"], -[160323, "src/Rosetta/model/ply/init.luau"], -[161428, "src/Rosetta/model/ply/Binary.luau"], -[161629, "src/Rosetta/model/pmx/init.luau"], -[161698, "src/Rosetta/model/pmx/Build.luau"], -[161994, "src/Rosetta/model/pmx/Pmd.luau"], -[162329, "src/Rosetta/model/pmx/Read.luau"], -[162733, "src/Rosetta/model/qb/init.luau"], -[163126, "src/Rosetta/model/rbxm/init.luau"], -[163718, "src/Rosetta/model/rbxmx/init.luau"], -[164371, "src/Rosetta/model/robloxmesh/init.luau"], -[165030, "src/Rosetta/model/robloxmesh/Parse.luau"], -[165487, "src/Rosetta/model/robloxmesh/Write.luau"], -[165596, "src/Rosetta/model/schematic/init.luau"], -[165917, "src/Rosetta/model/schematic/Common.luau"], -[166037, "src/Rosetta/model/schematic/Litematic.luau"], -[166248, "src/Rosetta/model/schematic/Mcedit.luau"], -[166492, "src/Rosetta/model/schematic/Sponge.luau"], -[166621, "src/Rosetta/model/smd/init.luau"], -[166688, "src/Rosetta/model/smd/Read.luau"], -[166957, "src/Rosetta/model/smd/Write.luau"], -[167200, "src/Rosetta/model/stl/init.luau"], -[167650, "src/Rosetta/model/stl/Decode.luau"], -[167724, "src/Rosetta/model/usda/init.luau"], -[167933, "src/Rosetta/model/usda/Build.luau"], -[169211, "src/Rosetta/model/usda/Parse.luau"], -[170009, "src/Rosetta/model/usda/Write.luau"], -[170826, "src/Rosetta/model/vox/init.luau"], -[171712, "src/Rosetta/model/vox/Grid.luau"], -[171769, "src/Rosetta/model/vrml/init.luau"], -[171835, "src/Rosetta/model/x/init.luau"], -[171965, "src/Rosetta/model/x/Build.luau"], -[172528, "src/Rosetta/model/x/Parse.luau"], -[172825, "src/Rosetta/model/x3d/init.luau"], -[172903, "src/Rosetta/music/669/init.luau"], -[173109, "src/Rosetta/music/ahx/init.luau"], -[173160, "src/Rosetta/music/far/init.luau"], -[173389, "src/Rosetta/music/hmp/init.luau"], -[173653, "src/Rosetta/music/hvl/init.luau"], -[173704, "src/Rosetta/music/it/init.luau"], -[174122, "src/Rosetta/music/it/Itsex.luau"], -[174238, "src/Rosetta/music/med/init.luau"], -[174885, "src/Rosetta/music/midi/init.luau"], -[175028, "src/Rosetta/music/midi/Smf.luau"], -[175439, "src/Rosetta/music/mod/init.luau"], -[175792, "src/Rosetta/music/mtm/init.luau"], -[176014, "src/Rosetta/music/mus/init.luau"], -[176171, "src/Rosetta/music/okt/init.luau"], -[176452, "src/Rosetta/music/ptm/init.luau"], -[176674, "src/Rosetta/music/s3m/init.luau"], -[176910, "src/Rosetta/music/sf2/init.luau"], -[176953, "src/Rosetta/music/stm/init.luau"], -[177184, "src/Rosetta/music/ult/init.luau"], -[177488, "src/Rosetta/music/umx/init.luau"], -[177704, "src/Rosetta/music/xm/init.luau"], -[178265, "src/Rosetta/music/xmi/init.luau"], -[178473, "src/Rosetta/ops/AudioOps.luau"], -[178922, "src/Rosetta/ops/ImageOps/init.luau"], -[179566, "src/Rosetta/ops/ImageOps/Kernels.luau"], -[180076, "src/Rosetta/ops/LayerOps.luau"], -[180169, "src/Rosetta/ops/MeshOps/init.luau"], -[181205, "src/Rosetta/ops/MeshOps/Greedy.luau"], -[181372, "src/Rosetta/ops/MusicOps.luau"], -[181720, "src/Rosetta/playlist/m3u/init.luau"], -[182073, "src/Rosetta/playlist/pls/init.luau"], -[182251, "src/Rosetta/playlist/xspf/init.luau"], -[182454, "src/Rosetta/subtitle/ass/init.luau"], -[182898, "src/Rosetta/subtitle/srt/init.luau"], -[183071, "src/Rosetta/subtitle/vtt/init.luau"], -[183274, "src/Rosetta/vector/svg/init.luau"], -[183360, "src/Rosetta/vector/svg/Parse.luau"], -[184106, "src/Rosetta/vector/svg/PathData.luau"], -[184474, "src/Rosetta/vector/svg/Render.luau"], -[184891, "src/Rosetta/vector/svg/Style.luau"], -[185263, "src/Rosetta/vector/svg/Write.luau"], -[185463, "src/Rosetta/vector/tiled/init.luau"], -[185643, "src/Rosetta/vector/tiled/Data.luau"], -[185794, "src/Rosetta/vector/tiled/Tmj.luau"], -[186425, "src/Rosetta/vector/tiled/Tmx.luau"], -[187037, "src/Rosetta/video/avi/init.luau"], -[187331, "src/Rosetta/video/fli/init.luau"], -[187482, "src/Rosetta/video/flv/init.luau"], -[187866, "src/Rosetta/video/flv/Amf.luau"], -[188024, "src/Rosetta/video/flv/Mux.luau"], -[188305, "src/Rosetta/video/h264/init.luau"], -[188444, "src/Rosetta/video/mkv/init.luau"], -[188600, "src/Rosetta/video/mkv/Mux.luau"], -[188879, "src/Rosetta/video/mkv/Parse.luau"], -[189600, "src/Rosetta/video/mp4/init.luau"], -[189928, "src/Rosetta/video/mpegps/init.luau"], -[190115, "src/Rosetta/video/mpegts/init.luau"], -[190353, "src/Rosetta/video/ogv/init.luau"], -[190748, "src/Rosetta/video/smk/init.luau"], -[191057, "src/Rosetta/video/smk/Audio.luau"], -[191177, "src/Rosetta/video/y4m/init.luau"] +[2992, "src/Rosetta/Types.luau"], +[4075, "src/Rosetta/archive/7z/init.luau"], +[4460, "src/Rosetta/archive/7z/Header.luau"], +[4987, "src/Rosetta/archive/adf/init.luau"], +[5269, "src/Rosetta/archive/applesingle/init.luau"], +[5455, "src/Rosetta/archive/ar/init.luau"], +[5858, "src/Rosetta/archive/arj/init.luau"], +[6068, "src/Rosetta/archive/binhex/init.luau"], +[6317, "src/Rosetta/archive/br/init.luau"], +[6392, "src/Rosetta/archive/bz2/init.luau"], +[6456, "src/Rosetta/archive/cab/init.luau"], +[6869, "src/Rosetta/archive/cab/Sum.luau"], +[6910, "src/Rosetta/archive/cpio/init.luau"], +[7078, "src/Rosetta/archive/d64/init.luau"], +[7492, "src/Rosetta/archive/fat/init.luau"], +[7614, "src/Rosetta/archive/grp/init.luau"], +[7728, "src/Rosetta/archive/gzip/init.luau"], +[7913, "src/Rosetta/archive/iso/init.luau"], +[7985, "src/Rosetta/archive/lha/init.luau"], +[8410, "src/Rosetta/archive/lz4/init.luau"], +[8754, "src/Rosetta/archive/macbinary/init.luau"], +[8952, "src/Rosetta/archive/mpq/init.luau"], +[9358, "src/Rosetta/archive/mpq/Crypt.luau"], +[9423, "src/Rosetta/archive/pak/init.luau"], +[9557, "src/Rosetta/archive/rpm/init.luau"], +[9881, "src/Rosetta/archive/tar/init.luau"], +[9999, "src/Rosetta/archive/uu/init.luau"], +[10269, "src/Rosetta/archive/vpk/init.luau"], +[10580, "src/Rosetta/archive/wad/init.luau"], +[11030, "src/Rosetta/archive/wad/Map.luau"], +[11460, "src/Rosetta/archive/wad/Picture.luau"], +[11562, "src/Rosetta/archive/xz/init.luau"], +[11662, "src/Rosetta/archive/yenc/init.luau"], +[11934, "src/Rosetta/archive/z/init.luau"], +[12030, "src/Rosetta/archive/zip/init.luau"], +[12249, "src/Rosetta/archive/zoo/init.luau"], +[12445, "src/Rosetta/archive/zst/init.luau"], +[12509, "src/Rosetta/audio/aac/init.luau"], +[12715, "src/Rosetta/audio/ac3/init.luau"], +[12861, "src/Rosetta/audio/adpcm/init.luau"], +[13006, "src/Rosetta/audio/adx/init.luau"], +[13237, "src/Rosetta/audio/aiff/init.luau"], +[13628, "src/Rosetta/audio/ape/init.luau"], +[13756, "src/Rosetta/audio/au/init.luau"], +[13917, "src/Rosetta/audio/brstm/init.luau"], +[14208, "src/Rosetta/audio/caf/init.luau"], +[14870, "src/Rosetta/audio/flac/init.luau"], +[15018, "src/Rosetta/audio/flac/Meta.luau"], +[15240, "src/Rosetta/audio/flac/Stream.luau"], +[15610, "src/Rosetta/audio/m4a/init.luau"], +[15944, "src/Rosetta/audio/mp3/init.luau"], +[16204, "src/Rosetta/audio/mp3/Index.luau"], +[16395, "src/Rosetta/audio/mp3/Stream.luau"], +[16622, "src/Rosetta/audio/mp3/Tags.luau"], +[16934, "src/Rosetta/audio/mpc/init.luau"], +[17028, "src/Rosetta/audio/opus/init.luau"], +[17406, "src/Rosetta/audio/opus/Encode.luau"], +[17517, "src/Rosetta/audio/qoa/init.luau"], +[17697, "src/Rosetta/audio/tta/init.luau"], +[17815, "src/Rosetta/audio/vag/init.luau"], +[18038, "src/Rosetta/audio/voc/init.luau"], +[18313, "src/Rosetta/audio/vorbis/init.luau"], +[18767, "src/Rosetta/audio/vorbis/Encode.luau"], +[19580, "src/Rosetta/audio/wav/init.luau"], +[20201, "src/Rosetta/audio/wav/Codecs.luau"], +[20367, "src/Rosetta/audio/wavpack/init.luau"], +[20574, "src/Rosetta/cad/step/init.luau"], +[20956, "src/Rosetta/cad/step/Brep.luau"], +[21191, "src/Rosetta/cad/step/Parse.luau"], +[21748, "src/Rosetta/cad/step/Write.luau"], +[21996, "src/Rosetta/codecs/audio/Aac/init.luau"], +[22315, "src/Rosetta/codecs/audio/Aac/Decode.luau"], +[23198, "src/Rosetta/codecs/audio/Aac/Tables.luau"], +[23533, "src/Rosetta/codecs/audio/Ac3/init.luau"], +[23692, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], +[24577, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], +[24678, "src/Rosetta/codecs/audio/Adpcm/init.luau"], +[25432, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], +[25734, "src/Rosetta/codecs/audio/Alac/init.luau"], +[25968, "src/Rosetta/codecs/audio/Alac/Decode.luau"], +[26387, "src/Rosetta/codecs/audio/Alac/Encode.luau"], +[26799, "src/Rosetta/codecs/audio/Ape/init.luau"], +[27014, "src/Rosetta/codecs/audio/Ape/Decode.luau"], +[27775, "src/Rosetta/codecs/audio/ApeTag.luau"], +[27872, "src/Rosetta/codecs/audio/Flac/init.luau"], +[27883, "src/Rosetta/codecs/audio/Flac/Encode.luau"], +[28832, "src/Rosetta/codecs/audio/Flac/Frame.luau"], +[29429, "src/Rosetta/codecs/audio/Hively/init.luau"], +[29625, "src/Rosetta/codecs/audio/Hively/Load.luau"], +[29874, "src/Rosetta/codecs/audio/Hively/Player.luau"], +[30832, "src/Rosetta/codecs/audio/Hively/Tables.luau"], +[31051, "src/Rosetta/codecs/audio/Mdct/init.luau"], +[31235, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], +[31444, "src/Rosetta/codecs/audio/MidiRender.luau"], +[31790, "src/Rosetta/codecs/audio/Mpa/init.luau"], +[31804, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], +[31863, "src/Rosetta/codecs/audio/Mpa/Core.luau"], +[33466, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], +[33758, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], +[34143, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], +[34784, "src/Rosetta/codecs/audio/Mpa/Header.luau"], +[34925, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], +[35151, "src/Rosetta/codecs/audio/Musepack/init.luau"], +[35496, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], +[36377, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[36755, "src/Rosetta/codecs/audio/Opus/init.luau"], +[36769, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[38616, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[39681, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[39741, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[40201, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[40538, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[40771, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[42807, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[43181, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[43444, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[43741, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[44023, "src/Rosetta/codecs/audio/Resample/init.luau"], +[44382, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[44436, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[44579, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[45092, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[45873, "src/Rosetta/codecs/audio/Stream.luau"], +[46034, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[46516, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[46794, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[46963, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[47091, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[49079, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[49195, "src/Rosetta/codecs/audio/Tta/init.luau"], +[49312, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[49564, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[49577, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[49961, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[50527, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[50948, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[50987, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[51039, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[51261, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[52716, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[52779, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[52866, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[53835, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[54703, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[54751, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[55267, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[55593, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[56013, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[56448, "src/Rosetta/codecs/compress/Explode.luau"], +[56644, "src/Rosetta/codecs/compress/Lz4.luau"], +[56913, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[57517, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[58057, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[58095, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[58568, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[58744, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[59012, "src/Rosetta/codecs/compress/Lzx.luau"], +[59446, "src/Rosetta/codecs/compress/PackBits.luau"], +[59536, "src/Rosetta/codecs/compress/Quantum.luau"], +[59773, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[60077, "src/Rosetta/codecs/compress/Xxh32.luau"], +[60146, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[60203, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[61161, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[61313, "src/Rosetta/codecs/entropy/Huffman.luau"], +[61595, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[61606, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[61820, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[62064, "src/Rosetta/codecs/font/Bitmap.luau"], +[62265, "src/Rosetta/codecs/font/Cff/init.luau"], +[62906, "src/Rosetta/codecs/font/GlyphNames.luau"], +[63056, "src/Rosetta/codecs/font/TrueType/init.luau"], +[63370, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[63762, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[64264, "src/Rosetta/codecs/image/Bcn/init.luau"], +[64371, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[64860, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[65289, "src/Rosetta/codecs/image/Blend.luau"], +[65668, "src/Rosetta/codecs/image/Dct/init.luau"], +[66049, "src/Rosetta/codecs/image/Etc.luau"], +[66347, "src/Rosetta/codecs/image/Half.luau"], +[66416, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[66770, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[67178, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[67415, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[68175, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[69056, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[69502, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[69580, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[69647, "src/Rosetta/codecs/image/Pixels.luau"], +[69911, "src/Rosetta/codecs/image/Quantize/init.luau"], +[70370, "src/Rosetta/codecs/image/Raster.luau"], +[71067, "src/Rosetta/codecs/image/Texel.luau"], +[71440, "src/Rosetta/codecs/image/Texture.luau"], +[71585, "src/Rosetta/codecs/image/Vp8/init.luau"], +[71715, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[73671, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[73930, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[74179, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[74298, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[74402, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[75255, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[76207, "src/Rosetta/codecs/image/Yuv.luau"], +[76475, "src/Rosetta/codecs/model/Draco/init.luau"], +[76807, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[77276, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[78465, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[78614, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[78973, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[79935, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[80409, "src/Rosetta/codecs/model/Mat4.luau"], +[80668, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[81196, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[81748, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[81827, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[81934, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[82140, "src/Rosetta/codecs/model/Polygon.luau"], +[82374, "src/Rosetta/codecs/model/Rbx/init.luau"], +[82611, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[83365, "src/Rosetta/codecs/model/Rig.luau"], +[83608, "src/Rosetta/codecs/model/Sampler.luau"], +[83768, "src/Rosetta/codecs/model/Vrml/init.luau"], +[83916, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[84490, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[84653, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[85402, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[85924, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[86651, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[86883, "src/Rosetta/codecs/text/Json/init.luau"], +[87152, "src/Rosetta/codecs/text/Json/Decode.luau"], +[87566, "src/Rosetta/codecs/text/Json/Encode.luau"], +[87868, "src/Rosetta/codecs/text/Nbt/init.luau"], +[88221, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[88913, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[89553, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[89791, "src/Rosetta/codecs/text/Text/init.luau"], +[89882, "src/Rosetta/codecs/text/Url/init.luau"], +[90087, "src/Rosetta/codecs/text/Xml/init.luau"], +[90490, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[91230, "src/Rosetta/codecs/video/Dsp.luau"], +[91953, "src/Rosetta/codecs/video/H263/init.luau"], +[92109, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[92967, "src/Rosetta/codecs/video/H263/Tables.luau"], +[93170, "src/Rosetta/codecs/video/H264/init.luau"], +[93543, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[93818, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[94949, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[95717, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[95975, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[96984, "src/Rosetta/codecs/video/H264/Inter.luau"], +[97238, "src/Rosetta/codecs/video/H264/Intra.luau"], +[97645, "src/Rosetta/codecs/video/H264/Mb.luau"], +[98551, "src/Rosetta/codecs/video/H264/Params.luau"], +[98998, "src/Rosetta/codecs/video/H264/Slice.luau"], +[99249, "src/Rosetta/codecs/video/H264/Tables.luau"], +[99290, "src/Rosetta/codecs/video/H264/Transform.luau"], +[99455, "src/Rosetta/codecs/video/Legacy/init.luau"], +[99653, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[99950, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[100317, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[100435, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[100543, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[100816, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[101211, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[101388, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[101400, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[101767, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[103274, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[103413, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[103551, "src/Rosetta/codecs/video/Theora/init.luau"], +[103814, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[105078, "src/Rosetta/codecs/video/Theora/Header.luau"], +[105441, "src/Rosetta/codecs/video/Video/init.luau"], +[105998, "src/Rosetta/codecs/video/Video/Source.luau"], +[106283, "src/Rosetta/containers/Archive.luau"], +[106550, "src/Rosetta/containers/AudioWrap.luau"], +[107053, "src/Rosetta/containers/Avi/init.luau"], +[107605, "src/Rosetta/containers/Blend.luau"], +[108344, "src/Rosetta/containers/Chunks.luau"], +[108479, "src/Rosetta/containers/Cpio.luau"], +[108907, "src/Rosetta/containers/Demux.luau"], +[109182, "src/Rosetta/containers/Ebml/init.luau"], +[109495, "src/Rosetta/containers/Fat.luau"], +[110183, "src/Rosetta/containers/Iso9660.luau"], +[110688, "src/Rosetta/containers/IsoBmff/init.luau"], +[110858, "src/Rosetta/containers/IsoBmff/Box.luau"], +[111046, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[111891, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[112412, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[112928, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[113045, "src/Rosetta/containers/MacFile.luau"], +[113194, "src/Rosetta/containers/MpegEs.luau"], +[113360, "src/Rosetta/containers/MpegPs/init.luau"], +[113580, "src/Rosetta/containers/MpegTs/init.luau"], +[114372, "src/Rosetta/containers/Ogg/init.luau"], +[114797, "src/Rosetta/containers/Ogg/Mux.luau"], +[114992, "src/Rosetta/containers/Ogg/Page.luau"], +[115161, "src/Rosetta/containers/Riff/init.luau"], +[115478, "src/Rosetta/containers/Tar.luau"], +[115892, "src/Rosetta/containers/Zip/init.luau"], +[116524, "src/Rosetta/core/Adler32.luau"], +[116570, "src/Rosetta/core/Base64.luau"], +[116729, "src/Rosetta/core/Bits.luau"], +[117022, "src/Rosetta/core/Bytes.luau"], +[117549, "src/Rosetta/core/Crc16.luau"], +[117601, "src/Rosetta/core/Crc32.luau"], +[117713, "src/Rosetta/core/Err.luau"], +[117795, "src/Rosetta/core/Input.luau"], +[117871, "src/Rosetta/core/Md5.luau"], +[118030, "src/Rosetta/core/Sniff.luau"], +[118059, "src/Rosetta/data/cbor/init.luau"], +[118158, "src/Rosetta/data/cbor/Codec.luau"], +[118727, "src/Rosetta/data/csv/init.luau"], +[119039, "src/Rosetta/data/ini/init.luau"], +[119285, "src/Rosetta/data/json/init.luau"], +[119377, "src/Rosetta/data/msgpack/init.luau"], +[119466, "src/Rosetta/data/msgpack/Codec.luau"], +[119908, "src/Rosetta/data/nbt/init.luau"], +[119967, "src/Rosetta/data/plist/init.luau"], +[120273, "src/Rosetta/data/plist/Binary.luau"], +[120540, "src/Rosetta/data/snbt/init.luau"], +[120603, "src/Rosetta/data/toml/init.luau"], +[120670, "src/Rosetta/data/toml/Decode.luau"], +[121298, "src/Rosetta/data/toml/Encode.luau"], +[121507, "src/Rosetta/data/xml/init.luau"], +[121563, "src/Rosetta/data/yaml/init.luau"], +[121636, "src/Rosetta/data/yaml/Emit.luau"], +[121926, "src/Rosetta/data/yaml/Parse.luau"], +[123219, "src/Rosetta/font/bdf/init.luau"], +[123508, "src/Rosetta/font/bmfont/init.luau"], +[123935, "src/Rosetta/font/bmfont/Parse.luau"], +[124388, "src/Rosetta/font/eot/init.luau"], +[124620, "src/Rosetta/font/fon/init.luau"], +[124903, "src/Rosetta/font/hershey/init.luau"], +[125098, "src/Rosetta/font/pcf/init.luau"], +[125378, "src/Rosetta/font/psf/init.luau"], +[125698, "src/Rosetta/font/ttf/init.luau"], +[125749, "src/Rosetta/font/type1/init.luau"], +[126108, "src/Rosetta/font/type1/Charstring.luau"], +[126386, "src/Rosetta/font/woff/init.luau"], +[126518, "src/Rosetta/font/woff2/init.luau"], +[126575, "src/Rosetta/font/woff2/Rebuild.luau"], +[127115, "src/Rosetta/host/init.luau"], +[127160, "src/Rosetta/host/Love.luau"], +[127303, "src/Rosetta/host/LuaJIT.luau"], +[127353, "src/Rosetta/host/Luau.luau"], +[127376, "src/Rosetta/host/Roblox.luau"], +[127735, "src/Rosetta/image/ani/init.luau"], +[127915, "src/Rosetta/image/blp/init.luau"], +[128173, "src/Rosetta/image/bmp/init.luau"], +[128588, "src/Rosetta/image/dds/init.luau"], +[129071, "src/Rosetta/image/exr/init.luau"], +[129831, "src/Rosetta/image/exr/Codec.luau"], +[129942, "src/Rosetta/image/exr/Piz.luau"], +[130299, "src/Rosetta/image/gif/init.luau"], +[130815, "src/Rosetta/image/gif/Decode.luau"], +[130878, "src/Rosetta/image/hdr/init.luau"], +[131107, "src/Rosetta/image/hdr/Codec.luau"], +[131318, "src/Rosetta/image/icns/init.luau"], +[131649, "src/Rosetta/image/ico/init.luau"], +[131926, "src/Rosetta/image/ico/Dib.luau"], +[132021, "src/Rosetta/image/ilbm/init.luau"], +[132340, "src/Rosetta/image/jpeg/init.luau"], +[132476, "src/Rosetta/image/ktx/init.luau"], +[133136, "src/Rosetta/image/pcx/init.luau"], +[133400, "src/Rosetta/image/png/init.luau"], +[133980, "src/Rosetta/image/png/Apng.luau"], +[134060, "src/Rosetta/image/png/Decode.luau"], +[134300, "src/Rosetta/image/png/Encode.luau"], +[134455, "src/Rosetta/image/pnm/init.luau"], +[134833, "src/Rosetta/image/pnm/Codec.luau"], +[135110, "src/Rosetta/image/qoi/init.luau"], +[135232, "src/Rosetta/image/qoi/Codec.luau"], +[135382, "src/Rosetta/image/sgi/init.luau"], +[135667, "src/Rosetta/image/sunras/init.luau"], +[135913, "src/Rosetta/image/tga/init.luau"], +[136183, "src/Rosetta/image/tga/Codec.luau"], +[136335, "src/Rosetta/image/tiff/init.luau"], +[137162, "src/Rosetta/image/tiff/Pixels.luau"], +[137552, "src/Rosetta/image/tim/init.luau"], +[137794, "src/Rosetta/image/vtf/init.luau"], +[138029, "src/Rosetta/image/webp/init.luau"], +[138639, "src/Rosetta/image/webp/Alpha.luau"], +[138715, "src/Rosetta/image/webp/Anim.luau"], +[138870, "src/Rosetta/image/xbm/init.luau"], +[139031, "src/Rosetta/image/xpm/init.luau"], +[139299, "src/Rosetta/image/xpm/Names.luau"], +[139355, "src/Rosetta/layered/aseprite/init.luau"], +[140093, "src/Rosetta/layered/ora/init.luau"], +[140380, "src/Rosetta/layered/psd/init.luau"], +[141115, "src/Rosetta/layered/psd/Channels.luau"], +[141467, "src/Rosetta/model/3ds/init.luau"], +[141550, "src/Rosetta/model/3ds/Build.luau"], +[142197, "src/Rosetta/model/3ds/Read.luau"], +[142693, "src/Rosetta/model/3ds/Write.luau"], +[143498, "src/Rosetta/model/3mf/init.luau"], +[143580, "src/Rosetta/model/3mf/Read.luau"], +[144168, "src/Rosetta/model/3mf/Write.luau"], +[144573, "src/Rosetta/model/b3d/init.luau"], +[144628, "src/Rosetta/model/b3d/Read.luau"], +[145199, "src/Rosetta/model/blend/init.luau"], +[145295, "src/Rosetta/model/blend/Anim.luau"], +[145641, "src/Rosetta/model/blend/Material.luau"], +[145993, "src/Rosetta/model/blend/Mesh.luau"], +[146628, "src/Rosetta/model/blend/Normals.luau"], +[146789, "src/Rosetta/model/blend/Prim.luau"], +[147238, "src/Rosetta/model/blend/Read.luau"], +[148138, "src/Rosetta/model/bsp/init.luau"], +[148283, "src/Rosetta/model/bsp/Brush.luau"], +[148561, "src/Rosetta/model/bsp/Quake3.luau"], +[148816, "src/Rosetta/model/dae/init.luau"], +[149005, "src/Rosetta/model/dae/Math.luau"], +[149052, "src/Rosetta/model/dae/Read.luau"], +[150902, "src/Rosetta/model/dae/Write.luau"], +[151271, "src/Rosetta/model/fbx/init.luau"], +[151419, "src/Rosetta/model/fbx/Ascii.luau"], +[151689, "src/Rosetta/model/fbx/Binary.luau"], +[152144, "src/Rosetta/model/fbx/Read.luau"], +[153506, "src/Rosetta/model/fbx/Write.luau"], +[154491, "src/Rosetta/model/fbx/Xform.luau"], +[154532, "src/Rosetta/model/gltf/init.luau"], +[154769, "src/Rosetta/model/gltf/Pack.luau"], +[154838, "src/Rosetta/model/gltf/Read.luau"], +[155569, "src/Rosetta/model/gltf/Write.luau"], +[156249, "src/Rosetta/model/iqm/init.luau"], +[156325, "src/Rosetta/model/iqm/Read.luau"], +[156680, "src/Rosetta/model/iqm/Write.luau"], +[157367, "src/Rosetta/model/ldraw/init.luau"], +[157445, "src/Rosetta/model/ldraw/Colors.luau"], +[157763, "src/Rosetta/model/ldraw/Read.luau"], +[158340, "src/Rosetta/model/lwo/init.luau"], +[158416, "src/Rosetta/model/lwo/Build.luau"], +[158878, "src/Rosetta/model/lwo/Parse.luau"], +[159421, "src/Rosetta/model/mca/init.luau"], +[159763, "src/Rosetta/model/mca/Chunk.luau"], +[159896, "src/Rosetta/model/mca/Lz4Block.luau"], +[159966, "src/Rosetta/model/md2/init.luau"], +[160165, "src/Rosetta/model/md3/init.luau"], +[160393, "src/Rosetta/model/md5/init.luau"], +[160474, "src/Rosetta/model/md5/Read.luau"], +[160907, "src/Rosetta/model/mdl/init.luau"], +[160989, "src/Rosetta/model/mdl/HalfLife.luau"], +[161317, "src/Rosetta/model/mdl/Quake.luau"], +[161535, "src/Rosetta/model/ms3d/init.luau"], +[161607, "src/Rosetta/model/ms3d/Read.luau"], +[162053, "src/Rosetta/model/ms3d/Write.luau"], +[162522, "src/Rosetta/model/obj/init.luau"], +[163264, "src/Rosetta/model/obj/Mtl.luau"], +[163551, "src/Rosetta/model/off/init.luau"], +[164013, "src/Rosetta/model/ply/init.luau"], +[165118, "src/Rosetta/model/ply/Binary.luau"], +[165319, "src/Rosetta/model/pmx/init.luau"], +[165388, "src/Rosetta/model/pmx/Build.luau"], +[165684, "src/Rosetta/model/pmx/Pmd.luau"], +[166019, "src/Rosetta/model/pmx/Read.luau"], +[166423, "src/Rosetta/model/qb/init.luau"], +[166816, "src/Rosetta/model/rbxm/init.luau"], +[167408, "src/Rosetta/model/rbxmx/init.luau"], +[168061, "src/Rosetta/model/robloxmesh/init.luau"], +[168720, "src/Rosetta/model/robloxmesh/Parse.luau"], +[169177, "src/Rosetta/model/robloxmesh/Write.luau"], +[169286, "src/Rosetta/model/schematic/init.luau"], +[169607, "src/Rosetta/model/schematic/Common.luau"], +[169727, "src/Rosetta/model/schematic/Litematic.luau"], +[169938, "src/Rosetta/model/schematic/Mcedit.luau"], +[170182, "src/Rosetta/model/schematic/Sponge.luau"], +[170311, "src/Rosetta/model/smd/init.luau"], +[170378, "src/Rosetta/model/smd/Read.luau"], +[170647, "src/Rosetta/model/smd/Write.luau"], +[170890, "src/Rosetta/model/stl/init.luau"], +[171340, "src/Rosetta/model/stl/Decode.luau"], +[171414, "src/Rosetta/model/usda/init.luau"], +[171623, "src/Rosetta/model/usda/Build.luau"], +[172901, "src/Rosetta/model/usda/Parse.luau"], +[173699, "src/Rosetta/model/usda/Write.luau"], +[174516, "src/Rosetta/model/vox/init.luau"], +[175402, "src/Rosetta/model/vox/Grid.luau"], +[175459, "src/Rosetta/model/vrml/init.luau"], +[175525, "src/Rosetta/model/x/init.luau"], +[175655, "src/Rosetta/model/x/Build.luau"], +[176218, "src/Rosetta/model/x/Parse.luau"], +[176515, "src/Rosetta/model/x3d/init.luau"], +[176593, "src/Rosetta/music/669/init.luau"], +[176799, "src/Rosetta/music/ahx/init.luau"], +[176850, "src/Rosetta/music/far/init.luau"], +[177079, "src/Rosetta/music/hmp/init.luau"], +[177343, "src/Rosetta/music/hvl/init.luau"], +[177394, "src/Rosetta/music/it/init.luau"], +[177812, "src/Rosetta/music/it/Itsex.luau"], +[177928, "src/Rosetta/music/med/init.luau"], +[178575, "src/Rosetta/music/midi/init.luau"], +[178718, "src/Rosetta/music/midi/Smf.luau"], +[179129, "src/Rosetta/music/mod/init.luau"], +[179482, "src/Rosetta/music/mtm/init.luau"], +[179704, "src/Rosetta/music/mus/init.luau"], +[179861, "src/Rosetta/music/okt/init.luau"], +[180142, "src/Rosetta/music/ptm/init.luau"], +[180364, "src/Rosetta/music/s3m/init.luau"], +[180600, "src/Rosetta/music/sf2/init.luau"], +[180643, "src/Rosetta/music/stm/init.luau"], +[180874, "src/Rosetta/music/ult/init.luau"], +[181178, "src/Rosetta/music/umx/init.luau"], +[181394, "src/Rosetta/music/xm/init.luau"], +[181955, "src/Rosetta/music/xmi/init.luau"], +[182163, "src/Rosetta/ops/AudioOps.luau"], +[182612, "src/Rosetta/ops/ImageOps/init.luau"], +[183256, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[183766, "src/Rosetta/ops/LayerOps.luau"], +[183859, "src/Rosetta/ops/MeshOps/init.luau"], +[184895, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[185062, "src/Rosetta/ops/MusicOps.luau"], +[185410, "src/Rosetta/playlist/m3u/init.luau"], +[185763, "src/Rosetta/playlist/pls/init.luau"], +[185941, "src/Rosetta/playlist/xspf/init.luau"], +[186144, "src/Rosetta/subtitle/ass/init.luau"], +[186588, "src/Rosetta/subtitle/srt/init.luau"], +[186761, "src/Rosetta/subtitle/vtt/init.luau"], +[186964, "src/Rosetta/vector/svg/init.luau"], +[187050, "src/Rosetta/vector/svg/Parse.luau"], +[187796, "src/Rosetta/vector/svg/PathData.luau"], +[188164, "src/Rosetta/vector/svg/Render.luau"], +[188581, "src/Rosetta/vector/svg/Style.luau"], +[188953, "src/Rosetta/vector/svg/Write.luau"], +[189153, "src/Rosetta/vector/tiled/init.luau"], +[189333, "src/Rosetta/vector/tiled/Data.luau"], +[189484, "src/Rosetta/vector/tiled/Tmj.luau"], +[190115, "src/Rosetta/vector/tiled/Tmx.luau"], +[190727, "src/Rosetta/video/avi/init.luau"], +[191021, "src/Rosetta/video/fli/init.luau"], +[191172, "src/Rosetta/video/flv/init.luau"], +[191556, "src/Rosetta/video/flv/Amf.luau"], +[191714, "src/Rosetta/video/flv/Mux.luau"], +[191995, "src/Rosetta/video/h264/init.luau"], +[192134, "src/Rosetta/video/mkv/init.luau"], +[192290, "src/Rosetta/video/mkv/Mux.luau"], +[192569, "src/Rosetta/video/mkv/Parse.luau"], +[193290, "src/Rosetta/video/mp4/init.luau"], +[193618, "src/Rosetta/video/mpegps/init.luau"], +[193805, "src/Rosetta/video/mpegts/init.luau"], +[194043, "src/Rosetta/video/ogv/init.luau"], +[194438, "src/Rosetta/video/smk/init.luau"], +[194747, "src/Rosetta/video/smk/Audio.luau"], +[194867, "src/Rosetta/video/y4m/init.luau"] ] diff --git a/build/rosetta.lua b/build/rosetta.lua index 18bac8a..8dbf841 100644 --- a/build/rosetta.lua +++ b/build/rosetta.lua @@ -2237,6 +2237,18 @@ local list= { return __include("model/b3d") end, }, + { + name = "blend", + category = "model", + path = "model/blend", + extensions = { "blend" }, + mime = { "application/x-blender" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, + load = function() + return __include("model/blend") + end, + }, { name = "bsp", category = "model", @@ -108222,6 +108234,745 @@ end return Avi end +__FILES["containers/Blend"] = function() +local __compat = __compat local buffer, type, __iter = __compat.buffer, __compat.type, __compat.__iter --!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 = __include("core/Err") +local Deflate = __include("codecs/compress/Deflate") +local Zstd = __include("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 + +-- ------------------------------------------------------------------------------------------------ readers + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local function swap16(b, o) +return readu8(b, o) * 256 + readu8(b, o + 1) +end +local function swap32(b, o) +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, o) +local v = swap16(b, o) + return (v >= 32768 and((v - 65536 ))or(v +))end +local function bei32(b, o) +local v = swap32(b, o) + return (v >= 2147483648 and((v - 4294967296 ))or(v +))end +local function bef32(b, o) +for k = 0, 3 do + buffer.writeu8(scratch, k, readu8(b, o + 3 - k)) + end + return readf32(scratch, 0) +end +local function bef64(b, o) +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, offset, length) +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, o, n, opts) +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, n) +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, c == "_" and 4 or 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= { + 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, at, size) +local b = f.buf + local e = at + size + local i32 = f.i32 + local function align(p) +return at + (math.floor((p - at + 3) / 4)) * 4 + end + local function strings(p, tag) +if p + 8 > e or readstring(b, p, 4) ~= tag then + return nil, p + end + local n = i32(b, p + 4) + p =p+ 8 + if n < 0 or n > e - p then + return nil, p + end + local out = (table.create(n) ) +for k = 1, n do + local q = p + while q < e and readu8(b, q) ~= 0 do + q =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) ) +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 =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) ), {} +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 =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 +local s= { name = tnames[t + 1], index = k - 1, size = lengths[t + 1], fields = (table.create(nf) ), byName = {} } + local off = 0 + for j = 1, nf do + local ft, fn = i16(b, p), i16(b, p + 2) + p =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= (names )[fn + 1] + local pointer = string.sub(decl, 1, 1) == "*" or string.sub(decl, 1, 2) == "(*" + local dims, count = {}, 1 + for d in __iter(string.gmatch(decl, "%[(%d+)%]")) do + local v = tonumber(d) or 1 + table.insert(dims, v) + count =count* v + end + local base = string.gsub(decl, "%[.*$", "") + base = string.gsub(base, "[%*%(%)]", "") + local elem= (pointer and{ps }or{lengths[ft + 1] +})[1] local fld= { + 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 =off+ fld.size + end + structs[k] = s + byName[s.name] = s + end + f.dna = { names = names , types = types , lengths = lengths, structs = structs, byName = byName } + return nil +end + +function Blend.open(data, offset, length, opts) +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 +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 = (n < 12 and{Err.TRUNCATED }or{(herr and string.sub(herr, 1, 12) == "unsupported:" and{Err.UNSUPPORTED }or{Err.CORRUPT +})[1]})[1] return nil, Err.new(code, herr or "bad header", 0) + end + local f= { + buf = b, version = version, subversion = nil, pointerSize = ps, little = little, format = fmt, + compression = compression, blocks = {}, byAddr = {}, shared = {}, byCode = {}, dna = nil , + u16 = (little and{readu16 }or{swap16})[1], + i16 = (little and{readi16 }or{bei16})[1], + u32 = (little and{readu32 }or{swap32})[1], + i32 = (little and{readi32 }or{bei32})[1], + f32 = (little and{readf32 }or{bef32})[1], + f64 = (little and{readf64 }or{bef64})[1], + } + local u32, i32 = f.u32, f.i32 + local maxBlocks = opts and opts.maxBlocks or 2 ^ 22 + local bh = fmt >= 1 and 32 or(ps == 8 and 24 or 20 +) local p = hs + local dnaBlock= 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 = (ps == 8 and{(readstring(b, p + 8, 8) )}or{(u32(b, p + 8) +)})[1] sdna = i32(b, p + 8 + ps) + count = i32(b, p + 12 + ps) + end + p =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= { 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 =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[(ps == 8 and{(string.rep("\0", 8) )}or{0})[1] ] = nil + local glob = f.byCode.GLOB + local fg = f.dna.byName.FileGlobal + local g1= (glob and{glob[1] }or{nil +})[1] 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 + + + + + + + + + + + +local function view(f, s, offset, blk) +return setmetatable({ file = f, struct = s, offset = offset, block = blk }, View) +end + +function Blend.structOf(f, blk) +return f.dna.structs[blk.sdna + 1] +end + +function Blend.struct(f, blk, i, as) +local s = (as and{f.dna.byName[as] }or{f.dna.structs[blk.sdna + 1] +})[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, structName, offset) +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, structName, ...) +local s = f.dna.byName[structName] + if not s then + return nil + end + for _, name in __iter({ ... }) do + local fld = s.byName[name] + if fld then + return fld + end + end + return nil +end + +function Blend.blocks(f, code) +return f.byCode[code] or {} +end + +local function pointerKey(f, o) +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 (v == 0 and{nil }or{v +})[1]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, addr, from) +if addr == nil then + return nil + end + local list = f.shared[addr] + if list and from then + for _, b in __iter(list) do + if b.owner == from.owner then + return b + end + end + end + return f.byAddr[addr] +end + +local function find(self, names) +local by = self.struct.byName + for _, name in __iter(names) do + local fld = by[name] + if fld then + return fld + end + end + return nil +end + +function View.has(self, ...) +return find(self, { ... }) ~= nil +end + +local function scalar(f, t, size, o) +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 (size == 8 and{(f.u32(b, o + (f.little and 0 or 4)) )}or{(f.i32(b, o) +)})[1] 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 + (f.little and 0 or 4)), f.u32(b, o + (f.little and 4 or 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, ...) +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 (z and{(string.sub(s, 1, z - 1) )}or{s +})[1] 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, ...) +local v = self:get(...) + return (type(v) == "number" and{v }or{nil +})[1]end + +function View.str(self, ...) +local v = self:get(...) + return (type(v) == "string" and{v }or{nil +})[1]end + +function View.vec(self, ...) +local v = self:get(...) + return (type(v) == "table" and type(v[1]) == "number" and{v }or{nil +})[1]end + +function View.sub(self, ...) +local v = self:get(...) + return (type(v) == "table" and getmetatable(v) == View and{v }or{nil +})[1]end + +function View.ptr(self, ...) +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, ...) +return Blend.resolve(self.file, self:ptr(...), self.block) +end + +function View.deref(self, name, i, as) +local names= (type(name) == "table" and{name }or{{ name } +})[1] 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 = (own and{own.name }or{sname +})[1] end + return Blend.struct(f, blk, i, sname) +end + +function View.array(self, name, as) +local first = self:deref(name, 0, as) + if not first or not first.block then + return {} + end + local blk = first.block +local s = first.struct + local n = (s.size > 0 and{(math.floor(blk.size / s.size ))}or{0 +})[1] local out = (table.create(n) ) +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, name, n) +local names= (type(name) == "table" and{name }or{{ name } +})[1] 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 = math.floor(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, name, as, limit) +local names= (type(name) == "table" and{name }or{{ name } +})[1] 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, ...) +local blk = self:target(...) + if not blk then + return nil, 0 + end + return blk.offset, blk.size +end + +function View.cstring(self, ...) +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 (z and{(string.sub(s, 1, z - 1) )}or{s +})[1]end + +function View.idName(self) +local id = self:sub("id") + local n = (id and{(id:str("name") )}or{(self:str("name") +)})[1] if not n then + return nil + end + return string.sub(n, 3) +end + +return Blend +end __FILES["containers/Chunks"] = function() local __compat = __compat local buffer, bit32 = __compat.buffer, __compat.bit32 --!strict -- containers/Chunks: the generic walker for chunked files (an id and a size per chunk, body, optional trailer and @@ -145075,6 +145826,2945 @@ return e[a + 1] > e[b + 1] return scene, nil, nil end +return Read +end +__FILES["model/blend"] = function() +local __compat = __compat local buffer = __compat.buffer --!strict +-- model/blend: Blender .blend files (read only), every version from 2.4x to 5.x: plain, gzip or zstd compressed; +-- 32 / 64-bit pointers, either byte order; the 5.0+ header. New in rosetta (from the file layout, read through each +-- file's own SDNA). Supports: the scene's objects and collections, transforms with parent inverse and bone parents, +-- meshes of every storage generation (MFace, MPoly / MLoop, attribute layers, AttributeStorage) with UV maps, colour +-- attributes, custom normals, material slots; Principled BSDF materials; packed and external images; cameras; lights; +-- armatures, skins (vertex groups, top 4 weights), shape keys; actions sampled into channels. +-- Not supported: modifiers (listed in meta.source.modifiers), curves / text / metaballs / grease pencil / volumes, +-- NLA strips, drivers, constraints, f-curve modifiers, linked libraries, collection instances. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = __include("core/Err") +local Bytes = __include("core/Bytes") +local Types = __include("Types") +local Blend = __include("containers/Blend") +local Deflate = __include("codecs/compress/Deflate") +local Zstd = __include("codecs/compress/Zstd") +local Read = __include("model/blend/Read") +local Anim = __include("model/blend/Anim") + +-- ------------------------------------------------------------------------------------------------ contract +local BlendFormat = { + name = "blend", + category = "model", + extensions = { "blend" }, + mime = { "application/x-blender" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Blend", "codecs/compress/Deflate", "codecs/compress/Zstd", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Polygon" }, + caps = { decode = true, encode = false, materials = true, textures = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true, compressed = true }, +} +-- ------------------------------------------------------------------------------------------------ types +-- ------------------------------------------------------------------------------------------------ sniff +-- compressed files: gzip by peeking the first bytes; zstd by decompressing files up to 4 MB (larger zstd streams +-- score 0.5: picked for model loads, the archive otherwise). Ties with archive/gzip and archive/zst go to the extension. + + + + + + + + + + + + + + +function BlendFormat.sniff(r) +local head = r:peek(7) + if head == "BLENDER" then + return 1 + end + local n = r.limit - r.base + if string.sub(head, 1, 3) == "\31\139\8" then + local inner = Deflate.peek(r.buf, r.base, n, 7) + return inner and buffer.tostring(inner) == "BLENDER" and 1 or 0 + end + if string.sub(head, 1, 4) == Zstd.MAGIC then + if n > 4 * 2 ^ 20 then + return 0.5 + end + local out = Zstd.decompress(r.buf, r.base, n, { verify = false }) + return out and buffer.len(out) >= 7 and buffer.readstring(out, 0, 7) == "BLENDER" and 1 or 0 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +function BlendFormat.open(r, opts) +return Blend.open(r.buf, r.base, r.limit - r.base, { maxBytes = opts and opts.maxBytes }) +end + +function BlendFormat.decode(r, opts) +local f, err = BlendFormat.open(r, opts) + if not f then + return nil, err + end + local ok, scene, msg = pcall(Read.scene, f, opts) + if not ok then + return nil, Err.from(tostring(scene)) + end + if not scene then + return nil, Err.from(msg or "bad file") + end + return scene, nil +end + +-- ------------------------------------------------------------------------------------------------ extras +BlendFormat.container = Blend +BlendFormat.evaluate = Anim.evaluate +BlendFormat.curves = Anim.curves +BlendFormat.ipo = Anim.ipo + +return BlendFormat +end +__FILES["model/blend/Anim"] = function() +local __compat = __compat local __iter = __compat.__iter --!strict +-- model/blend/Anim: Blender actions (legacy bAction.curves, and the layered actions of 4.4+: layers -> strips -> +-- keyframe data -> channel bags matched by the AnimData slot handle) and f-curve evaluation: constant, linear, +-- bezier (handles shortened so the segment stays a function of time, as Blender does) and the Penner easing modes +-- (elastic uses Penner's amplitude / period, which Blender scales differently); +-- constant or linear extrapolation. F-curve modifiers and NLA strips are not evaluated. +local Blend = __include("containers/Blend") + +local Anim = {} + + + + + + + + + + + + + + + + +local CONST, LIN, BEZ = 0, 1, 2 +local BACK, BOUNCE, CIRC, CUBIC, ELASTIC, EXPO, QUAD, QUART, QUINT, SINE = 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 + +-- ------------------------------------------------------------------------------------------------ reading +local function curve(f, fc) +local path = fc:cstring("rna_path") + if not path then + return nil + end + local keys= {} + for _, b in __iter(fc:array("bezt", "BezTriple")) do + local v = b:vec("vec") + if v and #v >= 9 then + table.insert(keys, { + lx = v[1], ly = v[2], x = v[4], y = v[5], rx = v[7], ry = v[8], + ipo = b:num("ipo") or BEZ, easing = b:num("easing") or 0, back = b:num("back") or 1.70158, + amplitude = b:num("amplitude") or 0.8, period = b:num("period") or 4.1, + }) + end + end + if #keys == 0 then + for _, p in __iter(fc:array("fpt", "FPoint")) do + local v = p:vec("vec") + if v and #v >= 2 then + table.insert(keys, { x = v[1], y = v[2], lx = v[1], ly = v[2], rx = v[1], ry = v[2], ipo = LIN, easing = 0, back = 0, amplitude = 0, period = 0 }) + end + end + end + if #keys == 0 then + return nil + end + table.sort(keys, function(a, b) +return a.x < b.x + end) + local mods = fc:list("modifiers") + return { path = path, index = fc:num("array_index") or 0, keys = keys, extend = fc:num("extend") or 0, modifiers = #mods } +end + +function Anim.curves(f, adt) +if not adt then + return nil, nil + end + local act = adt:deref("action", 0, "bAction") + if not act then + return nil, nil + end + local list= act:list("curves", "FCurve") + if #list == 0 and act:has("layer_array") then + local handle = adt:num("slot_handle") or 0 + local datas = act:pointers("strip_keyframe_data_array", act:num("strip_keyframe_data_array_num")) + for _, la in __iter(act:pointers("layer_array", act:num("layer_array_num"))) do + local lblk = la and Blend.resolve(f, la, act.block) + local layer = lblk and Blend.struct(f, lblk, 0, "ActionLayer") + if layer then + for _, sa in __iter(layer:pointers("strip_array", layer:num("strip_array_num"))) do + local sblk = sa and Blend.resolve(f, sa, act.block) + local strip = sblk and Blend.struct(f, sblk, 0, "ActionStrip") + local di = strip and strip:num("data_index") + local dblk = di and datas[di + 1] and Blend.resolve(f, datas[di + 1], act.block) + local kd = dblk and Blend.struct(f, dblk, 0, "ActionStripKeyframeData") + if kd then + for _, ba in __iter(kd:pointers("channelbag_array", kd:num("channelbag_array_num"))) do + local bblk = ba and Blend.resolve(f, ba, act.block) + local bag = bblk and (Blend.struct(f, bblk, 0, "ActionChannelBag") or Blend.struct(f, bblk, 0, "ActionChannelbag")) + if bag and (bag:num("slot_handle") or 0) == handle then + for _, ca in __iter(bag:pointers("fcurve_array", bag:num("fcurve_array_num"))) do + local cblk = ca and Blend.resolve(f, ca, act.block) + local fc = cblk and Blend.struct(f, cblk, 0, "FCurve") + if fc then + table.insert(list, fc) + end + end + end + end + end + end + end + end + end + local out= {} + for _, fc in __iter(list) do + local c = curve(f, fc) + if c then + table.insert(out, c) + end + end + return out, act:idName() +end + +-- pre-2.5 IPO curves (Object.ipo / Key.ipo): the curve's adrcode picks the channel; object rotations are in units of +-- 10 degrees; the interpolation and extrapolation (0 constant, 1 linear; cyclic ones as constant) are per curve +local OB_ADR= { + [1] = { "location", 0 }, [2] = { "location", 1 }, [3] = { "location", 2 }, + [4] = { "delta_location", 0 }, [5] = { "delta_location", 1 }, [6] = { "delta_location", 2 }, + [7] = { "rotation_euler", 0, math.pi / 18 }, [8] = { "rotation_euler", 1, math.pi / 18 }, [9] = { "rotation_euler", 2, math.pi / 18 }, + [10] = { "delta_rotation_euler", 0, math.pi / 18 }, [11] = { "delta_rotation_euler", 1, math.pi / 18 }, [12] = { "delta_rotation_euler", 2, math.pi / 18 }, + [13] = { "scale", 0 }, [14] = { "scale", 1 }, [15] = { "scale", 2 }, +} + +function Anim.ipo(f, ipo, keyNames) +if not ipo then + return nil, nil + end + local out= {} + for _, icu in __iter(ipo:list("curve", "IpoCurve")) do + local adr = icu:num("adrcode") or -1 + local path, index, scale + if keyNames then + if adr >= 1 and keyNames[adr + 1] then + path, index, scale = 'key_blocks["' .. keyNames[adr + 1] .. '"].value', 0, 1 + end + else + local m = OB_ADR[adr] + if m then + path, index, scale = m[1], m[2], m[3] or 1 + end + end + if path then + local ipoMode = icu:num("ipo") or BEZ + local keys= {} + for _, b in __iter(icu:array("bezt", "BezTriple")) do + local v = b:vec("vec") + if v and #v >= 9 then + table.insert(keys, { + lx = v[1], ly = v[2] * scale, x = v[4], y = v[5] * scale, rx = v[7], ry = v[8] * scale, + ipo = ((ipoMode == CONST or ipoMode == LIN )and{ipoMode }or{BEZ})[1], easing = 0, back = 1.70158, amplitude = 0.8, period = 4.1, + }) + end + end + local n = math.min(#keys, icu:num("totvert") or #keys) + while #keys > n do + table.remove(keys) + end + if #keys > 0 then + table.sort(keys, function(a, b) +return a.x < b.x + end) + table.insert(out, { path = path, index = index, keys = keys, extend = (icu:num("extrap") or 0) == 1 and 1 or 0, modifiers = 0 }) + end + end + end + local _ = f + return out, ipo:idName() +end + +-- ------------------------------------------------------------------------------------------------ evaluation +local function bezierAt(p0, p1, p2, p3, t) +local u = 1 - t + return u * u * u * p0 + 3 * u * u * t * p1 + 3 * u * t * t * p2 + t * t * t * p3 +end + +local function bezier(a, b, x) +local x0, y0, x3, y3 = a.x, a.y, b.x, b.y + local x1, y1, x2, y2 = a.rx, a.ry, b.lx, b.ly + -- handles longer than the segment are scaled down together so x(t) stays monotonic + local len = x3 - x0 + local h1x, h1y = x1 - x0, y1 - y0 + local h2x, h2y = x2 - x3, y2 - y3 + local l1, l2 = math.abs(h1x), math.abs(h2x) + if l1 + l2 > len and l1 + l2 > 0 then + local fac = len / (l1 + l2) + x1, y1 = x0 + h1x * fac, y0 + h1y * fac + x2, y2 = x3 + h2x * fac, y3 + h2y * fac + end + local lo, hi = 0, 1 + local t = (x - x0) / len + for _ = 1, 60 do + local xt = bezierAt(x0, x1, x2, x3, t) + if math.abs(xt - x) < 1e-9 then + break + end + if xt < x then + lo = t + else + hi = t + end + local d = 3 * (1 - t) * (1 - t) * (x1 - x0) + 6 * (1 - t) * t * (x2 - x1) + 3 * t * t * (x3 - x2) + local nt = (d ~= 0 and((t - (xt - x) / d ))or((-1 +))) t = (nt > lo and nt < hi and{nt }or{((lo + hi) / 2 +)})[1] end + return bezierAt(y0, y1, y2, y3, t) +end + +local function bounceOut(t, b, c, d) +t =t/ d + if t < 1 / 2.75 then + return c * (7.5625 * t * t) + b + elseif t < 2 / 2.75 then + t =t- 1.5 / 2.75 + return c * (7.5625 * t * t + 0.75) + b + elseif t < 2.5 / 2.75 then + t =t- 2.25 / 2.75 + return c * (7.5625 * t * t + 0.9375) + b + end + t =t- 2.625 / 2.75 + return c * (7.5625 * t * t + 0.984375) + b +end + +local function easeIn(ipo, t, a) +if ipo == BACK then + local s = a.back + return t * t * ((s + 1) * t - s) + elseif ipo == BOUNCE then + return 1 - bounceOut(1 - t, 0, 1, 1) + elseif ipo == CIRC then + return 1 - math.sqrt(math.max(0, 1 - t * t)) + elseif ipo == CUBIC then + return t * t * t + elseif ipo == ELASTIC then + if t <= 0 or t >= 1 then + return t + end + local p = (a.period > 0 and((a.period / 10 ))or(0.3 +)) local amp = a.amplitude + local s + if amp < 1 then + amp, s = 1, p / 4 + else + s = p / (2 * math.pi) * math.asin(1 / amp) + end + t =t- 1 + return -(amp * 2 ^ (10 * t) * math.sin((t - s) * (2 * math.pi) / p)) + elseif ipo == EXPO then + return (2 ^ (10 * (t - 1)) - 2 ^ -10) / (1 - 2 ^ -10) -- normalized to run from 0 to 1, as Blender's does + elseif ipo == QUAD then + return t * t + elseif ipo == QUART then + return t * t * t * t + elseif ipo == QUINT then + return t * t * t * t * t + elseif ipo == SINE then + return 1 - math.cos(t * math.pi / 2) + end + return t +end + +local function ease(a, b, x) +local t = (x - a.x) / (b.x - a.x) + local mode = a.easing + if mode == 0 then + mode = (a.ipo == BACK or a.ipo == BOUNCE or a.ipo == ELASTIC )and 2 or 1 + end + local s + if mode == 1 then + s = easeIn(a.ipo, t, a) + elseif mode == 2 then + s = 1 - easeIn(a.ipo, 1 - t, a) + elseif t < 0.5 then + s = easeIn(a.ipo, t * 2, a) / 2 + else + s = 1 - easeIn(a.ipo, (1 - t) * 2, a) / 2 + end + return a.y + (b.y - a.y) * s +end + +function Anim.evaluate(c, x) +local keys = c.keys + local n = #keys + local first, last = keys[1], keys[n] + if x <= first.x then + if c.extend == 1 and n > 0 and first.ipo ~= CONST then + if first.ipo == BEZ and first.lx ~= first.x then + return first.y + (x - first.x) * (first.y - first.ly) / (first.x - first.lx) + elseif n > 1 and keys[2].x ~= first.x then + return first.y + (x - first.x) * (keys[2].y - first.y) / (keys[2].x - first.x) + end + end + return first.y + end + if x >= last.x then + local prev = keys[n - 1] + if c.extend == 1 and n > 1 and prev.ipo ~= CONST then + if last.ipo == BEZ and last.rx ~= last.x then + return last.y + (x - last.x) * (last.ry - last.y) / (last.rx - last.x) + elseif last.x ~= prev.x then + return last.y + (x - last.x) * (last.y - prev.y) / (last.x - prev.x) + end + end + return last.y + end + local lo, hi = 1, n + while hi - lo > 1 do + local mid = math.floor((lo + hi) / 2 +) if keys[mid].x <= x then + lo = mid + else + hi = mid + end + end + local a, b = keys[lo], keys[hi] + if b.x <= a.x or a.ipo == CONST then + return a.y + elseif a.ipo == LIN then + return a.y + (b.y - a.y) * (x - a.x) / (b.x - a.x) + elseif a.ipo == BEZ then + return bezier(a, b, x) + end + return ease(a, b, x) +end + +function Anim.range(curves) +local lo, hi = math.huge, -math.huge + for _, c in __iter(curves) do + lo = math.min(lo, c.keys[1].x) + hi = math.max(hi, c.keys[#c.keys].x) + end + return lo, hi +end + +function Anim.split(path) +local kind, name, rest = string.match(path, '^(%w[%w_%.]-)%["(.-)"%]%.([%w_]+)$') + if kind and name and rest then + name = string.gsub(name, '\\(.)', "%1") + return kind, name, rest + end + return nil, nil, path +end + +return Anim +end +__FILES["model/blend/Material"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- model/blend/Material: Blender materials to Scene PBR materials. With nodes: the Principled BSDF (the one feeding the +-- material output, else the first): Base Color, Metallic, Roughness, Alpha, Emission (Color) x Emission Strength +-- (KHR_materials_emissive_strength above 1, as Blender's glTF exporter writes it), images linked directly to Base +-- Color / Emission and through a Normal Map node to Normal (its Strength as the scale), a Separate RGB / Color node to +-- Roughness (G) and Metallic (B), UV Map nodes for the texCoord. Without nodes (or before 2.8 without a +-- Principled node): Material.r / g / b / alpha, metallic, roughness. Images: packed files as encoded bytes, external +-- ones as uris (with the bytes when opts.files / opts.resolve has them). +local Blend = __include("containers/Blend") +local Types = __include("Types") + +local Material = {} + + + +local readu8, readstring = buffer.readu8, buffer.readstring + +local function sniffMime(b, o, n, path) +if n >= 8 and readstring(b, o, 8) == "\137PNG\r\n\26\n" then + return "image/png" + elseif n >= 3 and readu8(b, o) == 0xFF and readu8(b, o + 1) == 0xD8 then + return "image/jpeg" + elseif n >= 12 and readstring(b, o, 4) == "RIFF" and readstring(b, o + 8, 4) == "WEBP" then + return "image/webp" + elseif n >= 2 and readstring(b, o, 2) == "BM" then + return "image/bmp" + elseif n >= 4 and readstring(b, o, 4) == "\118\47\49\1" then + return "image/x-exr" + end + local ext = path and string.lower(string.match(path, "%.(%w+)$") or "") + local byExt = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", exr = "image/x-exr", hdr = "image/vnd.radiance", webp = "image/webp", tif = "image/tiff", tiff = "image/tiff" } + return (ext and{byExt[ext] }or{nil +})[1]end + +local function fetch(ctx, uri) +local opts = ctx.opts + local v= nil + if type(opts.files) == "table" then + v = opts.files[uri] + if v == nil then + v = opts.files[string.match(uri, "[^/\\]+$") or uri] + end + end + if v == nil and type(opts.resolve) == "function" then + local ok, res = pcall(opts.resolve, uri) + v = (ok and{res }or{nil +})[1] end + if type(v) == "string" then + return buffer.fromstring(v) + end + return (type(v) == "buffer" and{v }or{nil +})[1]end + +local function texture(ctx, img, sampler) +local f = ctx.f + local key = img.block and img.block.addr + if key ~= nil and ctx.textures[key] then + return ctx.textures[key] + end + local name = img:idName() + -- the path field keeps its DNA name "name" (char[1024]) in every version + local pf0 = img.struct.byName.filepath or img.struct.byName.name + local path = (pf0 and pf0.size >= 256 and{(img:str(pf0.name) )}or{nil +})[1] local pf = img:deref("packedfile", 0, "PackedFile") + if not pf then + for _, ipf in __iter(img:list("packedfiles", "ImagePackedFile")) do + pf = ipf:deref("packedfile", 0, "PackedFile") + if pf then + break + end + end + end + local tex= { name = name, sampler = sampler } + if pf then + local blk = pf:target("data") + local size = pf:num("size") or 0 + if blk then + local n = math.min(size, blk.size) + local data = buffer.create(n) + buffer.copy(data, 0, f.buf, blk.offset, n) + tex.data = data + tex.mime = sniffMime(data, 0, n, path) + end + end + if path and path ~= "" then + local uri = string.gsub(path, "^//", "") + uri = string.gsub(uri, "\\", "/") + if not tex.data then + tex.uri = uri + local data = fetch(ctx, uri) + if data then + tex.data = data + tex.mime = sniffMime(data, 0, buffer.len(data), uri) + else + tex.mime = sniffMime(buffer.create(0), 0, 0, uri) + end + end + tex.extras = { blend = { filepath = path } } + end + if not tex.data and not tex.uri then + tex.extras = { blend = { generated = true } } + end + table.insert(ctx.scene.textures, tex) + local idx = #ctx.scene.textures + if key ~= nil then + ctx.textures[key] = idx + end + return idx +end + + + + +local function graph(tree) +local g= { nodes = {}, links = {} } + for _, n in __iter(tree:list("nodes", "bNode")) do + local node= { view = n, idname = n:str("idname") or "", inputs = {}, outputs = {} } + for _, s in __iter(n:list("inputs", "bNodeSocket")) do + local id = s:str("identifier") or s:str("name") or "" + local nm = s:str("name") or id + node.inputs[nm] = s + if node.inputs[id] == nil then + node.inputs[id] = s + end + end + for _, s in __iter(n:list("outputs", "bNodeSocket")) do + if s.block then + node.outputs[s.block.addr] = s:str("name") or "" + end + end + if n.block then + g.nodes[n.block.addr] = node + end + end + for _, l in __iter(tree:list("links", "bNodeLink")) do + local from, fs, to = l:ptr("fromnode"), l:ptr("fromsock"), l:ptr("tosock") + local fn = from and g.nodes[from] + if fn and to ~= nil and bit32.band(l:num("flag") or 0, 0x10) == 0 then + g.links[to] = { node = fn, socket = (fs and fn.outputs[fs]) or "" } + end + end + return g +end + +local function input(n, ...) +for _, k in __iter({ ... }) do + local s = n.inputs[k] + if s then + return s + end + end + return nil +end + +local function link(g, s) +if not s or not s.block then + return nil + end + return g.links[s.block.addr] +end + +local function value(s, kind) +if not s then + return nil + end + if kind == "rgba" then + local v = s:deref("default_value", 0, "bNodeSocketValueRGBA") + return v and v:vec("value") + end + local v = s:deref("default_value", 0, "bNodeSocketValueFloat") + return v and v:num("value") +end + +local function imageRef(ctx, g, uvNames, s, through) +local l = link(g, s) + if not l then + return nil, nil + end + local n = l.node + if through and n.idname == through then + local inner = input(n, "Color", "Image") + local ref, tn = imageRef(ctx, g, uvNames, inner, nil) + return ref, (ref and{n }or{tn +})[1] end + if n.idname ~= "ShaderNodeTexImage" then + return nil, n + end + local img = n.view:deref("id", 0, "Image") + if not img then + return nil, n + end + local sampler= {} + local custom = false + local st = n.view:deref("storage", 0, "NodeTexImage") + if st then + local interp, ext = st:num("interpolation") or 0, st:num("extension") or 0 + custom = interp == 1 or (ext >= 1 and ext <= 3) + if interp == 1 then + sampler.filter = "nearest" + sampler.minFilter = "nearest" + end + if ext == 1 or ext == 2 then + sampler.wrapS, sampler.wrapT = "clamp", "clamp" + elseif ext == 3 then + sampler.wrapS, sampler.wrapT = "mirror", "mirror" + end + end + local t = texture(ctx, img, (custom and{sampler }or{nil})[1]) + if not t then + return nil, n + end + local ref= { texture = t } + local vec = link(g, input(n, "Vector")) + if vec and vec.node.idname == "ShaderNodeUVMap" then + local uvs = vec.node.view:deref("storage", 0, "NodeShaderUVMap") + local name = uvs and uvs:str("uv_map") + if name and uvNames and uvNames[name] then + ref.texCoord = uvNames[name] + end + end + return ref, n +end + +local function principled(g) +local first= nil + for _, n in __iter(g.nodes) do + if n.idname == "ShaderNodeOutputMaterial" then + local l = link(g, n.inputs.Surface) + if l and l.node.idname == "ShaderNodeBsdfPrincipled" then + return l.node + end + elseif n.idname == "ShaderNodeBsdfPrincipled" and (first == nil or (n.view.block and first.view.block and n.view.block.index < first.view.block.index)) then + first = n + end + end + return first +end + +local function emissive(m, color, strength) + local e = { color[1] * strength, color[2] * strength, color[3] * strength } + local mx = math.max(e[1], e[2], e[3]) + if mx > 1 then + m.extensions = m.extensions or {} + ;(m.extensions ).KHR_materials_emissive_strength = { emissiveStrength = mx } + e = { e[1] / mx, e[2] / mx, e[3] / mx } + end + m.emissive = e +end + +function Material.get(ctx, mv) +local key = mv.block and mv.block.addr + if key ~= nil and ctx.materials[key] then + return ctx.materials[key] + end + local f = ctx.f + local m = Types.Scene.material(mv:idName()) + local extras= {} + m.extras = { blend = extras } + local legacyAlpha = mv:num("a", "alpha") or 1 + m.baseColor = { mv:num("r") or 0.8, mv:num("g") or 0.8, mv:num("b") or 0.8, legacyAlpha } + m.metallic = mv:num("metallic") or 0 + m.roughness = mv:num("roughness") or 0.5 + if f.version < 280 then + m.roughness = 0.5 + end + m.doubleSided = bit32.band(mv:num("blend_flag") or 0, 4) == 0 + local tree = mv:deref("nodetree", 0, "bNodeTree") + local useNodes = (mv:num("use_nodes") or 0) ~= 0 or f.version >= 500 + local bsdf = nil + local g= nil + if tree and useNodes then + g = graph(tree) + bsdf = principled(g ) + end + if bsdf and g then + extras.principled = true + local uvNames = ctx.meta.uvNames + local base = value(input(bsdf, "Base Color"), "rgba") + local alpha = value(input(bsdf, "Alpha"), "float") or 1 + if base then + m.baseColor = { base[1], base[2], base[3], alpha } + end + m.metallic = value(input(bsdf, "Metallic"), "float") or m.metallic + m.roughness = value(input(bsdf, "Roughness"), "float") or m.roughness + local bref = imageRef(ctx, g, uvNames, input(bsdf, "Base Color"), nil) + if bref then + m.baseColorTexture = bref + m.baseColor = { 1, 1, 1, alpha } + end + local aref = imageRef(ctx, g, uvNames, input(bsdf, "Alpha"), nil) + if aref and not m.baseColorTexture then + m.baseColorTexture = aref + end + local nref, nnode = imageRef(ctx, g, uvNames, input(bsdf, "Normal"), "ShaderNodeNormalMap") + if nref then + nref.scale = (nnode and{value(nnode.inputs.Strength, "float") or 1 }or{1 +})[1] m.normalTexture = nref + end + local rl = link(g, input(bsdf, "Roughness")) + local ml = link(g, input(bsdf, "Metallic")) + local sep = (rl and rl.node) or (ml and ml.node) + if sep and (sep.idname == "ShaderNodeSeparateRGB" or sep.idname == "ShaderNodeSeparateColor") then + local mref = imageRef(ctx, g, uvNames, input(sep, "Image", "Color"), nil) + if mref then + m.metallicRoughnessTexture = mref + if rl then + m.roughness = 1 + end + if ml then + m.metallic = 1 + end + end + end + local es = input(bsdf, "Emission Color", "Emission") + local ecol = value(es, "rgba") or { 0, 0, 0, 1 } + local strength = value(input(bsdf, "Emission Strength"), "float") or 1 + local eref = imageRef(ctx, g, uvNames, es, nil) + if eref then + m.emissiveTexture = eref + ecol = { 1, 1, 1, 1 } + end + emissive(m, ecol, strength) + if not eref and m.emissive[1] == 0 and m.emissive[2] == 0 and m.emissive[3] == 0 then + m.emissive = { 0, 0, 0 } + end + local alphaLinked = link(g, input(bsdf, "Alpha")) ~= nil + if alpha < 1 or alphaLinked then + local bm = mv:num("blend_method") or 0 + if bm == 3 then + m.alphaMode = "mask" + m.alphaCutoff = mv:num("alpha_threshold") or 0.5 + else + m.alphaMode = "blend" + end + end + else + extras.legacy = true + if legacyAlpha < 1 then + m.alphaMode = "blend" + end + end + table.insert(ctx.scene.materials, m) + local idx = #ctx.scene.materials + if key ~= nil then + ctx.materials[key] = idx + end + return idx +end + +return Material +end +__FILES["model/blend/Mesh"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- model/blend/Mesh: a Blender Mesh ID of any storage generation to one polygon form (positions, faces as corner lists, +-- corner / point attributes, deform weights). Generations: MFace tessellated faces (< 2.63, and the 2.7x "legacy mesh +-- format" save); MVert / MEdge / MPoly / MLoop with MLoopUV / MLoopCol layers (2.63 - 3.x); CustomData attribute +-- layers ("position", ".edge_verts", ".corner_vert", poly_offset_indices, 3.x - 4.x); AttributeStorage (5.x). +local Blend = __include("containers/Blend") + +local Mesh = {} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +local CD_KIND= { + [0] = "MVert", [2] = "MDeformVert", [3] = "MEdge", [4] = "MFace", [5] = "MTFace", [6] = "MCol", [10] = "float", + [11] = "int32", [16] = "MLoopUV", [17] = "bytecolor", [25] = "MPoly", [26] = "MLoop", [41] = "short2", [45] = "int8", + [46] = "int2", [47] = "color", [48] = "float3", [49] = "float2", [50] = "bool", [52] = "quat", +} +-- AttributeStorage (5.x) data types and domains +local ATTR_KIND= { + [0] = "bool", [1] = "int8", [2] = "short2", [3] = "int32", [4] = "int2", [5] = "float", [6] = "float2", [7] = "float3", + [8] = "float4x4", [9] = "bytecolor", [10] = "color", [11] = "quat", +} +local DOMAIN= { [0] = "point", [1] = "edge", [2] = "face", [3] = "corner" } +local SIZE= { + bool = 1, int8 = 1, short2 = 4, int32 = 4, int2 = 8, float = 4, float2 = 8, float3 = 12, float4x4 = 64, bytecolor = 4, + color = 16, quat = 16, +} +local ME_SMOOTH = 1 +local ME_SHARP = 0x200 +local ME_AUTOSMOOTH = 0x20 + +local readu8, readi16 = buffer.readu8, buffer.readi16 + +-- sRGB byte -> linear +local SRGB = table.create(256, 0) +for i = 0, 255 do + local c = i / 255 + SRGB[i + 1] = (c <= 0.04045 and((c / 12.92 ))or((((c + 0.055) / 1.055) ^ 2.4 +)))end +Mesh.SRGB = SRGB + +local function customData(f, me, names, domain, out) + local cd = me:sub(table.unpack(names)) + if not cd then + return + end + local layers = cd:array("layers", "CustomDataLayer") + local n = cd:num("totlayer") or #layers + for i = 1, math.min(n, #layers) do + local L = layers[i] + local t = L:num("type") or -1 + local kind = CD_KIND[t] + local blk = L:target("data") + if kind and blk then + local st = f.dna.byName[kind] + local elem = (st and{st.size }or{SIZE[kind] or 0 +})[1] if elem > 0 then + table.insert(out, { + name = L:str("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, + elem = elem, activeRender = (L:num("active_rnd") or 0) == 0, cdtype = t, + }) + end + end + end +end + +local function storage(f, me, out) + local st = me:sub("attribute_storage") + if not st then + return + end + local attrs = st:array("dna_attributes", "Attribute") + local n = st:num("dna_attributes_num") or #attrs + for i = 1, math.min(n, #attrs) do + local a = attrs[i] + local kind = ATTR_KIND[a:num("data_type") or -1] + local domain = DOMAIN[a:num("domain") or -1] + local single = (a:num("storage_type") or 0) == 1 + local holder = a:deref("data", 0, single and"AttributeSingle" or"AttributeArray") + local blk = holder and holder:target("data") + if kind and domain and blk then + table.insert(out, { + name = a:cstring("name") or "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, + elem = SIZE[kind], single = single, + }) + end + end +end + +local function find(layers, domain, kind, name) +for _, L in __iter(layers) do + if L.domain == domain and (kind == nil or L.kind == kind) and (name == nil or L.name == name) then + return L + end + end + return nil +end + +local function legacy(f, me, field, kind, domain) +local blk = me:target(field) + local st = f.dna.byName[kind] + if not blk or not st or st.size <= 0 then + return nil + end + return { name = "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, elem = st.size } +end + +local function reader(f, L) +local b = f.buf + local o, elem, k = L.offset, L.elem, L.kind + local max = L.bytes + local single = L.single + local f32, i32, i16 = f.f32, f.i32, f.i16 + local comp = k == "short2" and 2 or((k == "int8" or k == "bool" or k == "bytecolor" )and 1 or 4 +) return function(i, c) +local at = (single and 0 or i * elem) + c * comp + if at < 0 or at + comp > max then + return 0 + end + if k == "float" or k == "float2" or k == "float3" or k == "color" or k == "quat" or k == "float4x4" then + return f32(b, o + at) + elseif k == "int32" or k == "int2" then + return i32(b, o + at) + elseif k == "short2" then + return i16(b, o + at) + elseif k == "int8" then + return buffer.readi8(b, o + at) + end + return readu8(b, o + at) + end +end +Mesh.reader = reader + +local function fieldReader(f, L, field) +local st = f.dna.byName[L.kind] + local fld = st and st.byName[field] + if not fld then + return nil + end + local b, o, elem, max = f.buf, L.offset, L.elem, L.bytes + local t, esz = fld.type, fld.elem + local fo = fld.offset + local f32, i32, i16, u32, u16 = f.f32, f.i32, f.i16, f.u32, f.u16 + return function(i, c) +local at = i * elem + fo + c * esz + if at < 0 or at + esz > max then + return 0 + end + at =at+ o + if t == "float" then + return f32(b, at) + elseif t == "int" or t == "int32_t" then + return i32(b, at) + elseif t == "uint" or t == "uint32_t" then + return u32(b, at) + elseif t == "short" or t == "int16_t" then + return i16(b, at) + elseif t == "ushort" or t == "uint16_t" then + return u16(b, at) + end + return readu8(b, at) + end +end + +-- tessellated face colours: corner k of face i at offset + i * faceStride + first + k * cornerStride, bytes in MCol's +-- memory order (alpha, blue, green, red; reversed when an int held them in a big-endian file), sRGB -> linear; +-- TFace colours load opaque, as Blender's versioning makes them +local function tessColors(f, tess, nc, offset, bytes, faceStride, first, cornerStride, swap, opaque) +local d = buffer.create(nc * 16) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + local at = (math.floor(tc / 4)) * faceStride + first + (tc % 4) * cornerStride + if at + 4 <= bytes then + local o = offset + at + local aa, bb, gg, rr = readu8(f.buf, o), readu8(f.buf, o + 1), readu8(f.buf, o + 2), readu8(f.buf, o + 3) + if swap then + aa, bb, gg, rr = rr, gg, bb, aa + end + buffer.writef32(d, i * 16, SRGB[rr + 1]) + buffer.writef32(d, i * 16 + 4, SRGB[gg + 1]) + buffer.writef32(d, i * 16 + 8, SRGB[bb + 1]) + buffer.writef32(d, i * 16 + 12, opaque and 1 or aa / 255) + end + end + return d +end + +function Mesh.layers(f, me) +local layers= {} + customData(f, me, { "vdata", "vert_data" }, "point", layers) + customData(f, me, { "edata", "edge_data" }, "edge", layers) + customData(f, me, { "pdata", "face_data" }, "face", layers) + customData(f, me, { "ldata", "corner_data" }, "corner", layers) + customData(f, me, { "fdata", "fdata_legacy" }, "tess", layers) + storage(f, me, layers) + return layers +end + +local function count(me, ...) +local v = me:num(...) + return (v and v > 0 and{v }or{0 +})[1]end + + + +function Mesh.read(f, me, limits) +local layers = Mesh.layers(f, me) + local nv = count(me, "totvert", "verts_num") + local np = count(me, "totpoly", "faces_num") + local nl = count(me, "totloop", "corners_num") + local nt = count(me, "totface", "totface_legacy") + local maxV = limits and limits.maxVertices or 2 ^ 25 + if nv > maxV or nl > maxV or nt > maxV or np > maxV then + return nil, "limit: mesh over maxVertices" + end + local pos = buffer.create(nv * 12) + local P = find(layers, "point", "float3", "position") + local mv = find(layers, "point", "MVert") or legacy(f, me, "mvert", "MVert", "point") + local get= nil + if P then + get = reader(f, P) + elseif mv then + get = fieldReader(f, mv, "co") + end + if not get then + if nv > 0 then + return nil, "mesh without positions" + end + get = function(_, _) +return 0 + end + end + local g = get +for i = 0, nv - 1 do + for c = 0, 2 do + buffer.writef32(pos, (i * 3 + c) * 4, g(i, c)) + end + end + local poly= { + name = me:idName(), nv = nv, nf = 0, nc = 0, pos = pos, cornerVert = buffer.create(0), faceStart = buffer.create(4), + faceMat = buffer.create(0), faceSmooth = buffer.create(0), uvs = {}, activeUV = 1, colors = {}, sharp = {}, + generation = P and P.cdtype == nil and"storage" or(P and"attributes" or"mpoly"), + layers = layers, + } + local corner= {} + if np > 0 then + local offs = me:target("poly_offset_indices", "face_offset_indices") + local mp = find(layers, "face", "MPoly") or legacy(f, me, "mpoly", "MPoly", "face") + local cv = find(layers, "corner", "int32", ".corner_vert") + local ml = find(layers, "corner", "MLoop") or legacy(f, me, "mloop", "MLoop", "corner") + local starts = buffer.create((np + 1) * 4) + if offs and offs.size >= (np + 1) * 4 then + for i = 0, np do + buffer.writeu32(starts, i * 4, math.clamp(f.i32(f.buf, offs.offset + i * 4), 0, nl)) + end + elseif mp then + local ls, tl = fieldReader(f, mp, "loopstart"), fieldReader(f, mp, "totloop") + if not ls or not tl then + return nil, "bad MPoly" + end + -- MPoly faces are usually in loop order; faces that are not get copied corners below + local at = 0 + for i = 0, np - 1 do + buffer.writeu32(starts, i * 4, at) + at =at+ math.max(0, tl(i, 0)) + end + buffer.writeu32(starts, np * 4, at) + if at > maxV * 4 then + return nil, "limit: too many corners" + end + local verts = buffer.create(at * 4) + local vr = (cv and{(reader(f, cv) )}or{(ml and{(fieldReader(f, ml, "v") )}or{nil +})[1]})[1] if not vr then + return nil, "mesh without corners" + end + local remap = buffer.create(at * 4) + local w = 0 + for i = 0, np - 1 do + local s0, n0 = ls(i, 0), tl(i, 0) + for k = 0, n0 - 1 do + local src = s0 + k + buffer.writeu32(verts, w * 4, math.clamp(vr(src, 0), 0, math.max(nv - 1, 0))) + buffer.writeu32(remap, w * 4, math.clamp(src, 0, math.max(nl - 1, 0))) + w =w+ 1 + end + end + corner.remap = remap + corner.verts = verts + nl = at + else + return nil, "mesh without face offsets" + end + poly.faceStart = starts + poly.nf = np + if not corner.verts then + local verts = buffer.create(nl * 4) + local vr = (cv and{(reader(f, cv) )}or{(ml and{(fieldReader(f, ml, "v") )}or{nil +})[1]})[1] if not vr then + return nil, "mesh without corners" + end + for i = 0, nl - 1 do + buffer.writeu32(verts, i * 4, math.clamp(vr(i, 0), 0, math.max(nv - 1, 0))) + end + corner.verts = verts + end + poly.cornerVert = corner.verts + poly.nc = nl + local mats = buffer.create(np * 4) + local smooth = buffer.create(np) + local mi = find(layers, "face", "int32", "material_index") + local sf = find(layers, "face", "bool", "sharp_face") + local mr = (mi and{(reader(f, mi) )}or{(mp and{(fieldReader(f, mp, "mat_nr") )}or{nil +})[1]})[1] local flag = (mp and{(fieldReader(f, mp, "flag") )}or{nil +})[1] local sr = (sf and{(reader(f, sf) )}or{nil +})[1] for i = 0, np - 1 do + buffer.writei32(mats, i * 4, (mr and{(mr(i, 0) )}or{0})[1]) + local s + if sr then + s = sr(i, 0) == 0 + elseif flag then + s = bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 + else + s = poly.generation ~= "mpoly" + end + buffer.writeu8(smooth, i, s and 1 or 0) + end + poly.faceMat, poly.faceSmooth = mats, smooth + elseif nt > 0 then + local mf = find(layers, "tess", "MFace") or legacy(f, me, "mface", "MFace", "tess") + if not mf then + return nil, "mesh without faces" + end + poly.generation = "mface" + local v = { fieldReader(f, mf, "v1"), fieldReader(f, mf, "v2"), fieldReader(f, mf, "v3"), fieldReader(f, mf, "v4") } + local mr, flag = fieldReader(f, mf, "mat_nr"), fieldReader(f, mf, "flag") + if not (v[1] and v[2] and v[3] and v[4]) then + return nil, "bad MFace" + end + local starts = buffer.create((nt + 1) * 4) + local verts = buffer.create(nt * 16) + local tessCorner = buffer.create(nt * 16) -- face * 4 + k: where tess layers keep the corner + local mats, smooth = buffer.create(nt * 4), buffer.create(nt) + local at = 0 + for i = 0, nt - 1 do + buffer.writeu32(starts, i * 4, at) + local k = (v[4] )(i, 0) ~= 0 and 4 or 3 + for c = 1, k do + buffer.writeu32(verts, (at + c - 1) * 4, math.clamp((v[c] )(i, 0), 0, math.max(nv - 1, 0))) + buffer.writeu32(tessCorner, (at + c - 1) * 4, i * 4 + c - 1) + end + at =at+ k + buffer.writei32(mats, i * 4, (mr and{(mr(i, 0) )}or{0})[1]) + buffer.writeu8(smooth, i, flag and bit32.band(flag(i, 0), ME_SMOOTH) ~= 0 and 1 or 0) + end + buffer.writeu32(starts, nt * 4, at) + poly.faceStart, poly.cornerVert, poly.nf, poly.nc = starts, verts, nt, at + poly.faceMat, poly.faceSmooth = mats, smooth + corner.tess = tessCorner + end + local nc = poly.nc + local remap= corner.remap + local function src(i) +return (remap and{(buffer.readu32(remap, i * 4) )}or{i +})[1] end + for _, L in __iter(layers) do + if L.domain == "corner" and (L.kind == "float2" or L.kind == "MLoopUV") and string.sub(L.name, 1, 1) ~= "." then + local r = (L.kind == "float2" and{(reader(f, L) )}or{(fieldReader(f, L, "uv") +)})[1] if r then + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local s = src(i) + buffer.writef32(d, i * 8, r(s, 0)) + buffer.writef32(d, i * 8 + 4, r(s, 1)) + end + table.insert(poly.uvs, { name = L.name, data = d }) + if L.activeRender and L.kind == "MLoopUV" then + poly.activeUV = #poly.uvs + end + end + elseif L.domain == "tess" and L.kind == "MTFace" and corner.tess then + local r = fieldReader(f, L, "uv") + local tess = corner.tess +if r then + local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + local face, k = math.floor(tc / 4), tc % 4 + buffer.writef32(d, i * 8, r(face, k * 2)) + buffer.writef32(d, i * 8 + 4, r(face, k * 2 + 1)) + end + table.insert(poly.uvs, { name = L.name, data = d }) + end + end + end + -- before 2.42 (no CustomData): Mesh.tface (TFace, uv[4][2] per face) and Mesh.mcol (MCol x 4 per face) + if #poly.uvs == 0 and corner.tess then + local tf = legacy(f, me, "tface", "TFace", "tess") + local r = tf and fieldReader(f, tf, "uv") + if r then + local tess = corner.tess +local d = buffer.create(nc * 8) + for i = 0, nc - 1 do + local tc = buffer.readu32(tess, i * 4) + buffer.writef32(d, i * 8, r(math.floor(tc / 4), (tc % 4) * 2)) + buffer.writef32(d, i * 8 + 4, r(math.floor(tc / 4), (tc % 4) * 2 + 1)) + end + table.insert(poly.uvs, { name = "UVMap", data = d }) + end + end + local active = me:cstring("default_uv_map_attribute") or me:cstring("active_uv_map_attribute") + if active then + for k, u in __iter(poly.uvs) do + if u.name == active then + poly.activeUV = k + end + end + end + for _, L in __iter(layers) do + if (L.domain == "corner" or L.domain == "point") and (L.kind == "color" or L.kind == "bytecolor") and string.sub(L.name, 1, 1) ~= "." then + local n = (L.domain == "corner" and{nc }or{nv +})[1] local r = reader(f, L) + local d = buffer.create(n * 16) + for i = 0, n - 1 do + local s = (L.domain == "corner" and{(src(i) )}or{i +})[1] for c = 0, 3 do + local x = r(s, c) + if L.kind == "bytecolor" then + x = (c == 3 and{(x / 255 )}or{SRGB[math.clamp(x, 0, 255) + 1] +})[1] end + buffer.writef32(d, (i * 4 + c) * 4, x) + end + end + table.insert(poly.colors, { name = L.name, domain = L.domain, data = d }) + elseif L.kind == "MCol" and L.domain == "tess" and corner.tess then + local st = f.dna.byName.MCol + local stride = (st and{st.size }or{4 +})[1] table.insert(poly.colors, { name = L.name, domain = "corner", data = tessColors(f, corner.tess , nc, L.offset, L.bytes, stride * 4, 0, stride, false) }) + end + end + -- before 2.42 (no CustomData): Mesh.mcol, or TFace.col (unsigned int col[4], MCol's byte layout in memory) + if #poly.colors == 0 and corner.tess then + local mc = legacy(f, me, "mcol", "MCol", "tess") + local tf = legacy(f, me, "tface", "TFace", "tess") + local col = f.dna.byName.TFace and f.dna.byName.TFace.byName.col + if mc then + table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess , nc, mc.offset, mc.bytes, mc.elem * 4, 0, mc.elem, false) }) + elseif tf and col then + table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess , nc, tf.offset, tf.bytes, tf.elem, col.offset, 4, not f.little, true) }) + end + end + local cn = find(layers, "corner", "short2", "custom_normal") + for _, L in __iter(layers) do + if not cn and L.domain == "corner" and L.cdtype == 41 then + cn = L + end + end + if cn then + local r = reader(f, cn) + local d = buffer.create(nc * 4) + for i = 0, nc - 1 do + local s = src(i) + buffer.writei16(d, i * 4, r(s, 0)) + buffer.writei16(d, i * 4 + 2, r(s, 1)) + end + poly.encodedNormals = d + end + local free = find(layers, "corner", "float3", "custom_normal") or find(layers, "point", "float3", "custom_normal") + or find(layers, "face", "float3", "custom_normal") + if free then + local r = reader(f, free) + local d = buffer.create(nc * 12) + local starts = poly.faceStart + for fi = 0, poly.nf - 1 do + local s0, s1 = buffer.readu32(starts, fi * 4), buffer.readu32(starts, fi * 4 + 4) + for i = s0, s1 - 1 do + local e = (free.domain == "corner" and{(src(i) )}or{(free.domain == "face" and{fi }or{(buffer.readu32(poly.cornerVert, i * 4) +)})[1]})[1] for c = 0, 2 do + buffer.writef32(d, (i * 3 + c) * 4, r(e, c)) + end + end + end + poly.customNormals = d + end + -- sharp edges + local ne = count(me, "totedge", "edges_num") + local ev = find(layers, "edge", "int2", ".edge_verts") + local se = find(layers, "edge", "bool", "sharp_edge") + local medge = find(layers, "edge", "MEdge") or legacy(f, me, "medge", "MEdge", "edge") + local flags = me:num("flag") or 0 + local smoothresh = me:num("smoothresh") + local autoSmooth = f.version < 401 and bit32.band(flags, ME_AUTOSMOOTH) ~= 0 + if autoSmooth then + poly.autoSmooth = smoothresh or math.rad(30) + end + local useSharp = f.version >= 401 or autoSmooth + if useSharp and ne > 0 then + local v1, v2, sharp + if ev and se then + local er, sr = reader(f, ev), reader(f, se) + v1 = function(i)return er(i, 0) end + v2 = function(i)return er(i, 1) end + sharp = function(i)return sr(i, 0) ~= 0 end + elseif medge then + local a, b, fl = fieldReader(f, medge, "v1"), fieldReader(f, medge, "v2"), fieldReader(f, medge, "flag") + if a and b and fl then + v1 = function(i)return a(i, 0) end + v2 = function(i)return b(i, 0) end + local ser = (se and{(reader(f, se) )}or{nil +})[1] sharp = function(i) +if ser then + return ser(i, 0) ~= 0 + end + return bit32.band(fl(i, 0), ME_SHARP) ~= 0 + end + end + end + if v1 and v2 and sharp then + for i = 0, ne - 1 do + if sharp(i) then + local a, b = v1(i), v2(i) + local lo, hi = math.min(a, b), math.max(a, b) + poly.sharp[lo * nv + hi] = true + end + end + end + end + -- deform weights + local dv = find(layers, "point", "MDeformVert") or legacy(f, me, "dvert", "MDeformVert", "point") + if dv then + local st = f.dna.byName.MDeformVert + local dwf, twf = st and st.byName.dw, st and st.byName.totweight + local mw = f.dna.byName.MDeformWeight + local nrf, wf = mw and mw.byName.def_nr, mw and mw.byName.weight + if dwf and twf and mw and nrf and wf then + local weights = (table.create(nv) ) +for i = 0, nv - 1 do + local list = {} + local at = i * dv.elem + if at + dv.elem <= dv.bytes then + local vw = Blend.view(f, "MDeformVert", dv.offset + at) + local blk = vw and vw:target("dw") + local n = vw and vw:num("totweight") or 0 + if blk then + n = math.min(n, math.floor(blk.size / mw.size)) + for k = 0, n - 1 do + local o = blk.offset + k * mw.size + table.insert(list, f.i32(f.buf, o + nrf.offset)) + table.insert(list, f.f32(f.buf, o + wf.offset)) + end + end + end + weights[i + 1] = list + end + poly.weights = weights + end + end + return poly, nil +end +-- shape keys: { name, value, relative (0-based), data: f32 x 3 per vertex } in file order, and the reference index + + +function Mesh.shapes(f, me, nv) +local key = me:deref("key", 0, "Key") + if not key then + return {}, nil, nil + end + local blocks = key:list("block", "KeyBlock") + local refAddr = key:ptr("refkey") + local out= {} + local ref= nil + for i, kb in __iter(blocks) do + local blk = kb:target("data") + local d = buffer.create(nv * 12) + if blk then + local n = math.min(nv * 12, blk.size) + buffer.copy(d, 0, f.buf, blk.offset, n) + if not f.little then + for k = 0, math.floor(n / 4 )- 1 do + buffer.writef32(d, k * 4, f.f32(f.buf, blk.offset + k * 4)) + end + end + end + if kb.block and kb.block.addr == refAddr then + ref = i + end + table.insert(out, { + -- unnamed in old files: Key 0 (the basis), Key 1, ... + name = kb:str("name") or ("Key " .. (i - 1)), value = kb:num("curval") or 0, relative = kb:num("relative") or 0, data = d, + mute = bit32.band(kb:num("flag") or 0, 2) ~= 0, + min = kb:num("slidermin") or 0, + max = kb:num("slidermax") or 1, + }) + end + if ref == nil and #out > 0 then + ref = 1 + end + return out, ref, key +end + +return Mesh +end +__FILES["model/blend/Normals"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- model/blend/Normals: Blender's encoded custom normals (CD_CUSTOMLOOPNORMAL / the "custom_normal" int16 x 2 corner +-- attribute) decoded in each smooth fan's space: the fan normal N, a reference edge direction R projected +-- perpendicular to N, O = N x R; alpha = the mean angle of the fan's edges to N, beta = the angle from R to the fan's +-- other end edge around N (2 pi for closed fans). A stored (a, b) (units of 1 / 32767) gives the angle a * alpha +-- (a > 0) or a * (2 pi - alpha) from N, turned b * beta (b > 0) or b * (2 pi - beta) from R towards O. +local Normals = {} + +local readu32, readf32, writef32, readi16 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.readi16 +local sqrt, acos, cos, sin = math.sqrt, math.acos, math.cos, math.sin +local TAU = 2 * math.pi +local NEAR = 0.99999 + + + +local function dir(pos, from, to) +local x = readf32(pos, to * 12) - readf32(pos, from * 12) + local y = readf32(pos, to * 12 + 4) - readf32(pos, from * 12 + 4) + local z = readf32(pos, to * 12 + 8) - readf32(pos, from * 12 + 8) + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + return x / l, y / l, z / l + end + return 0, 0, 0 +end + +function Normals.decode(poly, lnor, fanId, fans, _ang) +local nc = poly.nc + local cv, pos = poly.cornerVert, poly.pos + local enc = poly.encodedNormals +local out = buffer.create(nc * 12) + buffer.copy(out, 0, lnor, 0, nc * 12) + local across = fans.across + local nxt, prv = fans.next, fans.prev + local done= {} + for c = 0, nc - 1 do + local id = readu32(fanId, c * 4) + if not done[id] then + done[id] = true + local start = c + local cyclic = false + local guard = 0 + while true do + local p = across[readu32(prv, start * 4)] + if p == nil then + break + end + if p == c then + cyclic = true + break + end + start = p + guard =guard+ 1 + if guard > nc then + cyclic = true + break + end + end + if cyclic then + local m, q = c, c + repeat + local nq = across[q] + q = (nq and{(readu32(nxt, nq * 4) )}or{c +})[1] if q < m then + m = q + end + guard =guard+ 1 + until q == c or guard > 2 * nc + 4 + start = m + end + local v = readu32(cv, start * 4) + local nx, ny, nz = readf32(lnor, start * 12), readf32(lnor, start * 12 + 4), readf32(lnor, start * 12 + 8) + local corners = { start } + local edges = { readu32(cv, readu32(prv, start * 4) * 4) } + local q = start + while true do + table.insert(edges, readu32(cv, readu32(nxt, q * 4) * 4)) + local a = across[q] + if a == nil then + break + end + local nq = readu32(nxt, a * 4) + if nq == start or #corners > nc then + break + end + table.insert(corners, nq) + q = nq + end + local alpha, count = 0, 0 + for k, e in __iter(edges) do + if not (cyclic and k == #edges) then + local x, y, z = dir(pos, v, e) + alpha =alpha+ acos(math.clamp(x * nx + y * ny + z * nz, -1, 1)) + count =count+ 1 + end + end + alpha =alpha/ math.max(count, 1) + -- Blender walks each fan backwards from the corner whose next edge ends it (in a closed fan: its lowest + -- corner): R is that corner's next edge, the other end the last corner's previous edge + local refEdge = (cyclic and{edges[2] }or{edges[#edges] +})[1] local rx, ry, rz = dir(pos, v, refEdge) + local ox, oy, oz = dir(pos, v, (cyclic and{refEdge }or{edges[1]})[1]) + local dr, dother = rx * nx + ry * ny + rz * nz, ox * nx + oy * ny + oz * nz + local valid = math.abs(dr) < NEAR and math.abs(dother) < NEAR + local beta = 0 + local tx, ty, tz = 0, 0, 0 + if valid then + rx, ry, rz = rx - nx * dr, ry - ny * dr, rz - nz * dr + local l = sqrt(rx * rx + ry * ry + rz * rz) + rx, ry, rz = rx / l, ry / l, rz / l + tx, ty, tz = ny * rz - nz * ry, nz * rx - nx * rz, nx * ry - ny * rx + l = sqrt(tx * tx + ty * ty + tz * tz) + if l > 0 then + tx, ty, tz = tx / l, ty / l, tz / l + end + ox, oy, oz = ox - nx * dother, oy - ny * dother, oz - nz * dother + l = sqrt(ox * ox + oy * oy + oz * oz) + if l > 0 then + ox, oy, oz = ox / l, oy / l, oz / l + end + local d = rx * ox + ry * oy + rz * oz + if d < NEAR then + beta = acos(math.clamp(d, -1, 1)) + if tx * ox + ty * oy + tz * oz < 0 then + beta = TAU - beta + end + else + beta = TAU + end + end + for _, k in __iter(corners) do + local a, b = readi16(enc, k * 4) / 32767, readi16(enc, k * 4 + 2) / 32767 + if a ~= 0 and valid and alpha ~= 0 and beta ~= 0 then + local al = ((a > 0 and{alpha }or{(TAU - alpha)})[1]) * a + local sa = sin(al) + local x, y, z = nx * cos(al), ny * cos(al), nz * cos(al) + if b == 0 then + x, y, z = x + rx * sa, y + ry * sa, z + rz * sa + else + local be = ((b > 0 and{beta }or{(TAU - beta)})[1]) * b + x =x+ sa * (rx * cos(be) + tx * sin(be)) + y =y+ sa * (ry * cos(be) + ty * sin(be)) + z =z+ sa * (rz * cos(be) + tz * sin(be)) + end + local l = sqrt(x * x + y * y + z * z) + if l > 0 then + x, y, z = x / l, y / l, z / l + end + writef32(out, k * 12, x) + writef32(out, k * 12 + 4, y) + writef32(out, k * 12 + 8, z) + end + end + end + end + return out +end + +return Normals +end +__FILES["model/blend/Prim"] = function() +local __compat = __compat local buffer, __iter = __compat.buffer, __compat.__iter --!strict +-- model/blend/Prim: model/blend/Mesh polygons to Scene primitives (one per material slot): corner normals from smooth +-- fans (angle-weighted face normals; sharp faces, sharp edges, auto smooth before 4.1 and non-manifold or flipped edges +-- split fans, as Blender does), custom normals, vertices shared by corners with equal attributes, n-gons by ear +-- clipping, deform weights (top 4) and shape keys as morph targets. +local Types = __include("Types") +local Polygon = __include("codecs/model/Polygon") +local Rig = __include("codecs/model/Rig") +local Normals = __include("model/blend/Normals") +local MeshT = __include("model/blend/Mesh") + +local Prim = {} + +local Scene = Types.Scene +local readu32, readf32, writef32, writeu32 = buffer.readu32, buffer.readf32, buffer.writef32, buffer.writeu32 +local sqrt, acos = math.sqrt, math.acos + + + + + + + + +local function face(poly, fi) +return readu32(poly.faceStart, fi * 4), readu32(poly.faceStart, fi * 4 + 4) +end + +local function vec(pos, v) +return readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8) +end + +-- face normals (Newell) and corner angles +function Prim.geometry(poly) +local fn = buffer.create(poly.nf * 12) + local ang = buffer.create(poly.nc * 4) + local cv, pos = poly.cornerVert, poly.pos + for fi = 0, poly.nf - 1 do + local s0, s1 = face(poly, fi) + local nx, ny, nz = 0, 0, 0 + local n = s1 - s0 + for c = s0, s1 - 1 do + local d = (c + 1 < s1 and((c + 1 ))or(s0 +)) local x1, y1, z1 = vec(pos, readu32(cv, c * 4)) + local x2, y2, z2 = vec(pos, readu32(cv, d * 4)) + nx =nx+ (y1 - y2) * (z1 + z2) + ny =ny+ (z1 - z2) * (x1 + x2) + nz =nz+ (x1 - x2) * (y1 + y2) + end + local l = sqrt(nx * nx + ny * ny + nz * nz) + if l > 0 then + nx, ny, nz = nx / l, ny / l, nz / l + end + writef32(fn, fi * 12, nx) + writef32(fn, fi * 12 + 4, ny) + writef32(fn, fi * 12 + 8, nz) + if n >= 3 then + for c = s0, s1 - 1 do + local pc = (c > s0 and((c - 1 ))or((s1 - 1 +))) local nc = (c + 1 < s1 and((c + 1 ))or(s0 +)) local x, y, z = vec(pos, readu32(cv, c * 4)) + local ax, ay, az = vec(pos, readu32(cv, pc * 4)) + local bx, by, bz = vec(pos, readu32(cv, nc * 4)) + ax, ay, az = ax - x, ay - y, az - z + bx, by, bz = bx - x, by - y, bz - z + local la, lb = sqrt(ax * ax + ay * ay + az * az), sqrt(bx * bx + by * by + bz * bz) + local a = 0 + if la > 0 and lb > 0 then + a = acos(math.clamp((ax * bx + ay * by + az * bz) / (la * lb), -1, 1)) + end + writef32(ang, c * 4, a) + end + end + end + return fn, ang +end +-- smooth fans: for each corner the corner after it in its face, and the fan links across smooth edges + + + + + + + + + + +function Prim.fans(poly, fn) +local nc, nv = poly.nc, poly.nv + local cv = poly.cornerVert + local nxt, prv, fc = buffer.create(nc * 4), buffer.create(nc * 4), buffer.create(nc * 4) + for fi = 0, poly.nf - 1 do + local s0, s1 = face(poly, fi) + for c = s0, s1 - 1 do + writeu32(nxt, c * 4, (c + 1 < s1 and((c + 1 ))or(s0))) + writeu32(prv, c * 4, (c > s0 and((c - 1 ))or((s1 - 1)))) + writeu32(fc, c * 4, fi) + end + end + local first= {} + local second= {} + local uses= {} + for c = 0, nc - 1 do + local a, b = readu32(cv, c * 4), readu32(cv, readu32(nxt, c * 4) * 4) + local key = math.min(a, b) * nv + math.max(a, b) + local u = (uses[key] or 0) + 1 + uses[key] = u + if u == 1 then + first[key] = c + elseif u == 2 then + second[key] = c + end + end + local across= {} + local smooth = poly.faceSmooth + local cosLimit = (poly.autoSmooth and{(math.cos(poly.autoSmooth) )}or{nil +})[1] for key, u in __iter(uses) do + if u == 2 then + local c1, c2 = first[key], second[key] + local f1, f2 = readu32(fc, c1 * 4), readu32(fc, c2 * 4) + local a1 = readu32(cv, c1 * 4) + local a2 = readu32(cv, c2 * 4) + local ok = a1 ~= a2 and f1 ~= f2 and buffer.readu8(smooth, f1) ~= 0 and buffer.readu8(smooth, f2) ~= 0 + and not poly.sharp[key] + if ok and cosLimit then + local d = readf32(fn, f1 * 12) * readf32(fn, f2 * 12) + readf32(fn, f1 * 12 + 4) * readf32(fn, f2 * 12 + 4) + + readf32(fn, f1 * 12 + 8) * readf32(fn, f2 * 12 + 8) + ok = d >= cosLimit + end + if ok then + -- c1 runs a -> b, c2 runs b -> a: the corner at b in face 2 is c2, at a it is next(c2) + across[c1] = c2 + across[c2] = c1 + end + end + end + return { next = nxt, prev = prv, face = fc, across = across } +end + +-- corner normals: angle-weighted face normals summed over each smooth fan; with fan ids (u32 per corner) +function Prim.cornerNormals(poly, fn, ang, fans) +local nc = poly.nc + local parent = buffer.create(nc * 4) + for c = 0, nc - 1 do + writeu32(parent, c * 4, c) + end + local function root(c) +local r = c + while readu32(parent, r * 4) ~= r do + r = readu32(parent, r * 4) + end + while readu32(parent, c * 4) ~= r do + local nx = readu32(parent, c * 4) + writeu32(parent, c * 4, r) + c = nx + end + return r + end + local function union(a, b) + local ra, rb = root(a), root(b) + if ra ~= rb then + writeu32(parent, math.max(ra, rb) * 4, math.min(ra, rb)) + end + end + for c1, c2 in __iter(fans.across) do + if c1 < c2 then + -- edge c1 (a -> b) shared with c2 (b -> a): corners at b are next(c1) and c2, at a c1 and next(c2) + union(readu32(fans.next, c1 * 4), c2) + union(c1, readu32(fans.next, c2 * 4)) + end + end + local acc = buffer.create(nc * 12) + local fanId = buffer.create(nc * 4) + for c = 0, nc - 1 do + local r = root(c) + writeu32(fanId, c * 4, r) + local fi = readu32(fans.face, c * 4) + local w = readf32(ang, c * 4) + for k = 0, 2 do + writef32(acc, (r * 3 + k) * 4, readf32(acc, (r * 3 + k) * 4) + readf32(fn, (fi * 3 + k) * 4) * w) + end + end + local out = buffer.create(nc * 12) + for c = 0, nc - 1 do + local r = readu32(fanId, c * 4) + local x, y, z = readf32(acc, r * 12), readf32(acc, r * 12 + 4), readf32(acc, r * 12 + 8) + local l = sqrt(x * x + y * y + z * z) + local fi = readu32(fans.face, c * 4) + writef32(out, c * 12, (l > 1e-20 and{(x / l )}or{(readf32(fn, fi * 12))})[1]) + writef32(out, c * 12 + 4, (l > 1e-20 and{(y / l )}or{(readf32(fn, fi * 12 + 4))})[1]) + writef32(out, c * 12 + 8, (l > 1e-20 and{(z / l )}or{(readf32(fn, fi * 12 + 8))})[1]) + end + return out, fanId +end + +function Prim.normals(poly) +local fn, ang = Prim.geometry(poly) + local fans = Prim.fans(poly, fn) + local nrm, fanId = Prim.cornerNormals(poly, fn, ang, fans) + if poly.customNormals then + return poly.customNormals +end + if poly.encodedNormals then + return Normals.decode(poly, nrm, fanId, fans, ang) + end + return nrm +end + +-- triangles of face fi as corner indices (appended to out) +local function triangulate(poly, fi, fnx, fny, fnz, out) + local s0, s1 = face(poly, fi) + local n = s1 - s0 + if n < 3 then + return + end + if n == 3 then + table.insert(out, s0) + table.insert(out, s0 + 1) + table.insert(out, s0 + 2) + return + end + local ax, ay, az = math.abs(fnx), math.abs(fny), math.abs(fnz) + local cu, cv, sign = 0, 1, fnz + if ax >= ay and ax >= az then + cu, cv, sign = 1, 2, fnx + elseif ay >= az then + cu, cv, sign = 2, 0, fny + end + local ring = (table.create(n * 2) ) +for c = s0, s1 - 1 do + local v = readu32(poly.cornerVert, c * 4) + local u, w = readf32(poly.pos, (v * 3 + cu) * 4), readf32(poly.pos, (v * 3 + cv) * 4) + table.insert(ring, (sign < 0 and{(-u )}or{u})[1]) + table.insert(ring, w) + end + local tris = Polygon.triangulate({ ring }) + if #tris == (n - 2) * 6 then + for k = 2, #tris, 2 do + table.insert(out, s0 + tris[k] - 1) + end + return + end + for k = 1, n - 2 do -- degenerate: a fan + table.insert(out, s0) + table.insert(out, s0 + k) + table.insert(out, s0 + k + 1) + end +end + +local function accessor(t, comps) +local n = math.floor(#t / comps +) local b = buffer.create(#t * 4) + for i = 1, #t do + writef32(b, (i - 1) * 4, t[i]) + end + return Scene.accessor(b, "f32", comps, n) +end + +-- slots[k] = the scene material of slot k - 1 (or 0 for none); skin maps deform groups to joints + + +function Prim.build(poly, slots, opts, skin, shapes, ref) +local triangulateOn = not (opts and opts.triangulate == false) + local flipV = not (opts and opts.flipV == false) + local withNormals = not (opts and opts.normals == false) + local nrm = (withNormals and poly.nf > 0 and{(Prim.normals(poly) )}or{nil +})[1] local fn = (poly.nf > 0 and{(Prim.geometry(poly)) }or{(buffer.create(0) +)})[1] local nslots = math.max(#slots, 1) + local groups= {} + local order= {} + for fi = 0, poly.nf - 1 do + local m = math.clamp(buffer.readi32(poly.faceMat, fi * 4), 0, nslots - 1) + local g = groups[m] + if not g then + g = {} + groups[m] = g + table.insert(order, m) + end + table.insert(g, fi) + end + table.sort(order) + local cornerColors, pointColors= {}, {} + for _, c in __iter(poly.colors) do + table.insert((c.domain == "corner" and{cornerColors }or{pointColors})[1], c) + end + local keyBytes = 4 + (nrm and 12 or 0) + #poly.uvs * 8 + #cornerColors * 16 + local scratch = buffer.create(keyBytes) + local mesh= { name = poly.name, primitives = {} } + local sources= {} + local cv = poly.cornerVert + for _, m in __iter(order) do + local faces = groups[m] + local map= {} + local vsrc= {} + local corners= {} -- the first corner of each output vertex + local cornerOut = {} -- corner -> output vertex + for _, fi in __iter(faces) do + local s0, s1 = face(poly, fi) + for c = s0, s1 - 1 do + local v = readu32(cv, c * 4) + buffer.writeu32(scratch, 0, v) + local o = 4 + if nrm then + buffer.copy(scratch, o, nrm, c * 12, 12) + o =o+ 12 + end + for _, uv in __iter(poly.uvs) do + buffer.copy(scratch, o, uv.data, c * 8, 8) + o =o+ 8 + end + for _, col in __iter(cornerColors) do + buffer.copy(scratch, o, col.data, c * 16, 16) + o =o+ 16 + end + local key = buffer.readstring(scratch, 0, keyBytes) + local idx = map[key] + if not idx then + idx = #vsrc + map[key] = idx + table.insert(vsrc, v) + table.insert(corners, c) + end + cornerOut[c] = idx + end + end + local n = #vsrc + local attrs= {} + local P = buffer.create(n * 12) + for i = 1, n do + buffer.copy(P, (i - 1) * 12, poly.pos, vsrc[i] * 12, 12) + end + attrs.POSITION = Scene.accessor(P, "f32", 3, n) + if nrm then + local N = buffer.create(n * 12) + for i = 1, n do + buffer.copy(N, (i - 1) * 12, nrm, corners[i] * 12, 12) + end + attrs.NORMAL = Scene.accessor(N, "f32", 3, n) + end + for k, uv in __iter(poly.uvs) do + local T = buffer.create(n * 8) + for i = 1, n do + local c = corners[i] + writef32(T, (i - 1) * 8, readf32(uv.data, c * 8)) + local v = readf32(uv.data, c * 8 + 4) + writef32(T, (i - 1) * 8 + 4, (flipV and((1 - v ))or(v))) + end + local acc = Scene.accessor(T, "f32", 2, n) + acc.name = uv.name + attrs["TEXCOORD_" .. (k - 1)] = acc + end + local ci = 0 + for _, col in __iter(poly.colors) do + local C = buffer.create(n * 16) + for i = 1, n do + local e = (col.domain == "corner" and{corners[i] }or{vsrc[i] +})[1] buffer.copy(C, (i - 1) * 16, col.data, e * 16, 16) + end + local acc = Scene.accessor(C, "f32", 4, n) + acc.name = col.name + attrs["COLOR_" .. ci] = acc + ci =ci+ 1 + end + if skin and poly.weights then + local lists = (table.create(n) ) +for i = 1, n do + local src = poly.weights[vsrc[i] + 1] or {} + local l = {} + for k = 1, #src - 1, 2 do + local j = skin.joints[src[k] ] + if j then + table.insert(l, j) + table.insert(l, src[k + 1]) + end + end + lists[i] = l + end + attrs.JOINTS_0, attrs.WEIGHTS_0 = Rig.influences(lists) + end + local prim= { attributes = attrs, mode = "triangles" } + local idx= {} + if triangulateOn then + for _, fi in __iter(faces) do + local tri= {} + triangulate(poly, fi, readf32(fn, fi * 12), readf32(fn, fi * 12 + 4), readf32(fn, fi * 12 + 8), tri) + for _, c in __iter(tri) do + table.insert(idx, cornerOut[c]) + end + end + else + local sizes = buffer.create(#faces * 4) + for k, fi in __iter(faces) do + local s0, s1 = face(poly, fi) + writeu32(sizes, (k - 1) * 4, s1 - s0) + for c = s0, s1 - 1 do + table.insert(idx, cornerOut[c]) + end + end + prim.mode = "polygons" + prim.faces = Scene.accessor(sizes, "u32", 1, #faces) + end + local I = buffer.create(#idx * 4) + for k, v in __iter(idx) do + writeu32(I, (k - 1) * 4, v) + end + prim.indices = Scene.accessor(I, "u32", 1, #idx) + local mat = slots[m + 1] + if mat and mat > 0 then + prim.material = mat + end + if shapes and ref and #shapes > 1 then + local base = shapes[ref].data + local targets= {} + for k, s in __iter(shapes) do + if k ~= ref then + local t = (table.create(n * 3) ) +for i = 1, n do + local v = vsrc[i] + for c = 0, 2 do + t[(i - 1) * 3 + c + 1] = readf32(s.data, (v * 3 + c) * 4) - readf32(base, (v * 3 + c) * 4) + end + end + table.insert(targets, { POSITION = accessor(t, 3) } ) + end + end + prim.targets = targets + end + table.insert(mesh.primitives, prim) + table.insert(sources, vsrc) + end + if shapes and ref and #shapes > 1 then + local w = {} + for k, s in __iter(shapes) do + if k ~= ref then + table.insert(w, s.value) + end + end + mesh.weights = w + end + local usedSlots = {} + for _, m in __iter(order) do + table.insert(usedSlots, m) + end + return { mesh = mesh, slots = usedSlots, vertexSource = sources } +end + +return Prim +end +__FILES["model/blend/Read"] = function() +local __compat = __compat local buffer, bit32, type, __iter = __compat.buffer, __compat.bit32, __compat.type, __compat.__iter --!strict +-- model/blend/Read: a parsed .blend (containers/Blend) to a Scene: the current scene's objects (from its collections, +-- or Base list before 2.8) with their transforms (euler orders, quaternion, axis angle, delta transforms, parent +-- inverse; bone parents), meshes (model/blend/Mesh, model/blend/Prim), materials (Principled BSDF node or the legacy +-- colour), images (packed bytes or external uris), cameras, lights (watts to candela / lux as Blender's glTF exporter +-- does: 683 lm/W, / 4 pi for point and spot), armatures (bones to joint nodes with the saved pose), skins, shape keys +-- and actions sampled into channels. +local Blend = __include("containers/Blend") +local Types = __include("Types") +local Mat4 = __include("codecs/model/Mat4") +local Rig = __include("codecs/model/Rig") +local Mesh = __include("model/blend/Mesh") +local Prim = __include("model/blend/Prim") +local Anim = __include("model/blend/Anim") +local Material = __include("model/blend/Material") + +local Read = {} + +local Scene = Types.Scene + + + + + + + + + + + + + + +local OB_EMPTY, OB_MESH, OB_LAMP, OB_CAMERA, OB_ARMATURE = 0, 1, 10, 11, 25 +local PARSKEL, PARBONE = 4, 7 +local LA_LOCAL, LA_SUN, LA_SPOT, LA_HEMI, LA_AREA = 0, 1, 2, 3, 4 +local EULER = { [1] = "xyz", [2] = "xzy", [3] = "yxz", [4] = "yzx", [5] = "zxy", [6] = "zyx" } +local TYPE_NAME= { + [0] = "empty", [1] = "mesh", [2] = "curve", [3] = "surface", [4] = "text", [5] = "metaball", [10] = "light", + [11] = "camera", [12] = "speaker", [13] = "lightprobe", [22] = "lattice", [25] = "armature", [26] = "gpencil", + [27] = "curves", [28] = "pointcloud", [29] = "volume", [30] = "grease_pencil", +} +local W2LM = 683 + +-- ------------------------------------------------------------------------------------------------ transforms +local function quatWXYZ(q) +if not q or #q < 4 then + return { 0, 0, 0, 1 } + end + local w, x, y, z = q[1], q[2], q[3], q[4] + local l = math.sqrt(w * w + x * x + y * y + z * z) + if l < 1e-12 then + return { 0, 0, 0, 1 } + end + return { x / l, y / l, z / l, w / l } +end + +local function rotation(mode, eul, quat, axis, angle) +if mode == 0 then + return Mat4.fromQuat(quatWXYZ(quat)) + elseif mode == -1 then + local a = axis or { 0, 1, 0 } + return Mat4.fromQuat(Mat4.axisAngle(a[1], a[2], a[3], math.deg(angle or 0))) + end + local e = eul or { 0, 0, 0 } + return Mat4.euler(math.deg(e[1]), math.deg(e[2]), math.deg(e[3]), EULER[mode] or "xyz") +end + +local function scaleM(m, s) +local r = table.clone(m) + for c = 0, 2 do + for k = 1, 3 do +do local __DARKLUA_VAR=c * 4 + k r[__DARKLUA_VAR]=r[__DARKLUA_VAR]* s[c + 1] +end end + end + return r +end + +local function trs(t, r, s) +local m = scaleM(r, s) + m[13], m[14], m[15] = t[1], t[2], t[3] + return m +end + + + +local function objectProps(ob) -- fields missing from old files take their neutral value + +local function v(fallback, ...) +local x = ob:vec(...) + if x and #x >= #fallback then + return table.clone(x) + end + return fallback + end + local p= { + location = v({ 0, 0, 0 }, "loc"), + rotation_euler = v({ 0, 0, 0 }, "rot"), + rotation_quaternion = v({ 1, 0, 0, 0 }, "quat"), + rotation_axis_angle = { ob:num("rotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "rotAxis")) }, + scale = v({ 1, 1, 1 }, "scale", "size"), + delta_location = v({ 0, 0, 0 }, "dloc"), + delta_rotation_euler = v({ 0, 0, 0 }, "drot"), + delta_rotation_quaternion = v({ 1, 0, 0, 0 }, "dquat"), + delta_rotation_axis_angle = { ob:num("drotAngle") or 0, table.unpack(v({ 0, 1, 0 }, "drotAxis")) }, + delta_scale = v({ 1, 1, 1 }, "dscale"), + rotmode = { ob:num("rotmode") or 1 }, + } + if not ob:has("dscale") then + -- before 2.5x the delta scale ("dsize") was added to the scale + local d = v({ 0, 0, 0 }, "dsize") + p.scale = { p.scale[1] + d[1], p.scale[2] + d[2], p.scale[3] + d[3] } + end + return p +end + +local function poseProps(pc) +if not pc then + return { + location = { 0, 0, 0 }, rotation_euler = { 0, 0, 0 }, rotation_quaternion = { 1, 0, 0, 0 }, + rotation_axis_angle = { 0, 0, 1, 0 }, scale = { 1, 1, 1 }, rotmode = { 0 }, + } + end + local function v(n, ...) +local x = pc:vec(...) + if x and #x >= n then + return table.clone(x) + end + return table.create(n, 0) + end + return { + location = v(3, "loc"), + rotation_euler = v(3, "eul"), + rotation_quaternion = v(4, "quat"), + rotation_axis_angle = { pc:num("rotAngle") or 0, table.unpack(v(3, "rotAxis")) }, + scale = v(3, "scale", "size"), + rotmode = { pc:num("rotmode") or 0 }, + } +end + +-- Blender's object matrix: T(loc + dloc) * Rdelta * R * S(scale * dscale) +local function objectBasis(p) +local mode = p.rotmode[1] + local aa, daa = p.rotation_axis_angle, p.delta_rotation_axis_angle + local r = rotation(mode, p.rotation_euler, p.rotation_quaternion, { aa[2], aa[3], aa[4] }, aa[1]) + if p.delta_location then + local d = rotation(mode, p.delta_rotation_euler, p.delta_rotation_quaternion, { daa[2], daa[3], daa[4] }, daa[1]) + r = Mat4.mul(d, r) + local l, dl, s, ds = p.location, p.delta_location, p.scale, p.delta_scale + return trs({ l[1] + dl[1], l[2] + dl[2], l[3] + dl[3] }, r, { s[1] * ds[1], s[2] * ds[2], s[3] * ds[3] }) + end + return trs(p.location, r, p.scale) +end + +local function nodeTRS(node, m) + local t, r, s = Mat4.decomposeStrict(m) + if t and r and s then + node.translation, node.rotation, node.scale = t, r, s + node.matrix = nil + else + node.matrix = m + node.translation, node.rotation, node.scale = nil, nil, nil + end +end + +local function mat4(v, ...) +local m = v and v:vec(...) + if m and #m == 16 then + return m + end + return nil +end +-- ------------------------------------------------------------------------------------------------ scene + + + + + + + + + + + + + + + + + + + +local function worldOf(ctx, node) +local cached = ctx.world[node] + if cached then + return cached + end + local m = Scene.nodeMatrix(ctx.scene.nodes[node]) + local p = ctx.parentOf[node] + local w = (p and{(Mat4.mul(worldOf(ctx, p), m) )}or{m +})[1] ctx.world[node] = w + return w +end + +local function addNode(ctx, node, parent) +table.insert(ctx.scene.nodes, node) + local idx = #ctx.scene.nodes + if parent then + table.insert(ctx.scene.nodes[parent].children, idx) + ctx.parentOf[idx] = parent + else + table.insert(ctx.scene.roots, idx) + end + return idx +end + +local function armature(ctx, ob, node) + local f = ctx.f + local arm = ob:deref("data", 0, "bArmature") + if not arm then + return + end + local pose = ob:deref("pose", 0, "bPose") + local poseNames= {} + if pose then + for _, pc in __iter(pose:list("chanbase", "bPoseChannel")) do + local n = pc:str("name") + if n then + poseNames[n] = pc + end + end + end + local info = { joints = {}, names = {}, rest = {}, restLocal = {}, bones = {}, deform = {}, node = node, poseNames = poseNames } + local function walk(list, parentJoint, parentRest, depth) + if depth > 256 then + return + end + for _, bone in __iter(list) do + local name = bone:str("name") or "" + local rest = mat4(bone, "arm_mat") or Mat4.identity() + local restLocal = (parentRest and{(Mat4.mul(Mat4.inverseFull(parentRest) or Mat4.identity(), rest) )}or{rest +})[1] local props = poseProps(poseNames[name]) + local basis = objectBasis(props) + local jnode= { name = name, children = {} } + nodeTRS(jnode, Mat4.mul(restLocal, basis)) + local parentNode = (parentJoint and{info.joints[parentJoint] }or{node +})[1] local idx = addNode(ctx, jnode, parentNode) + table.insert(info.joints, idx) + table.insert(info.bones, bone) + table.insert(info.rest, rest) + table.insert(info.restLocal, restLocal) + table.insert(info.deform, bit32.band(bone:num("flag") or 0, 0x1000) == 0) + local j = #info.joints + info.names[name] = j + ctx.props[idx] = props + ctx.prefix[idx] = restLocal + jnode.extras = { blend = { bone = true, length = bone:num("length") or 0 } } + walk(bone:list("childbase", "Bone"), j, rest, depth + 1) + end + end + walk(arm:list("bonebase", "Bone"), nil, nil, 0) + ctx.armatures[ob.block and ob.block.addr or node] = info + local _ = f +end + +local function camera(ctx, ob, node) + local cam = ob:deref("data", 0, "Camera") + if not cam then + return + end + local r = ctx.meta.render + local aspect = r.aspect + local znear, zfar = cam:num("clip_start", "clipsta") or 0.1, cam:num("clip_end", "clipend") or 100 + local c +if (cam:num("type") or 0) == 1 then + -- files without ortho_scale (before 2.3x) scaled orthographic views by 256 / lens, as Blender's versioning sets it + local half = (cam:num("ortho_scale") or 256 / math.max(cam:num("lens") or 35, 1e-3)) / 2 + local xmag, ymag = half, half / aspect + if aspect < 1 then + xmag, ymag = half * aspect, half + end + c = { name = ob:idName(), type = "orthographic", xmag = xmag, ymag = ymag, znear = znear, zfar = zfar } +else + local lens = cam:num("lens") or 50 + local sx, sy = cam:num("sensor_x") or 36, cam:num("sensor_y") or 24 + local fit = cam:num("sensor_fit") or 0 + local yfov + if fit == 2 then + yfov = 2 * math.atan(sy / 2 / lens) + elseif fit == 1 or aspect >= 1 then + yfov = 2 * math.atan(math.tan(math.atan(sx / 2 / lens)) / aspect) + else + yfov = 2 * math.atan(sx / 2 / lens) + end + c = { name = ob:idName(), type = "perspective", yfov = yfov, aspect = aspect, znear = znear, zfar = zfar } +end + table.insert(ctx.scene.cameras, c) + ctx.scene.nodes[node].camera = #ctx.scene.cameras +end + +local function light(ctx, ob, node) + local la = ob:deref("data", 0, "Light") or ob:deref("data", 0, "Lamp") + if not la then + return + end + local t = la:num("type") or 0 + local color = { la:num("r") or 1, la:num("g") or 1, la:num("b") or 1 } + local energy = la:num("energy") or 1 + if ctx.f.version < 280 and ctx.meta.engine ~= "CYCLES" then + -- Blender's 2.8 versioning: Blender Internal energies times 100 (suns unchanged) + if t ~= LA_SUN and t ~= LA_HEMI then + energy =energy* 100 + end + elseif ctx.f.version < 280 then + -- Cycles took the strength from the lamp's Emission node, else 100 (sun: 1) + energy = (t == LA_SUN or t == LA_HEMI )and 1 or 100 + local tree = (la:num("use_nodes") or 0) ~= 0 and la:deref("nodetree", 0, "bNodeTree") or nil + for _, n in __iter((tree and{(tree:list("nodes", "bNode") )}or{{} })[1])do + if n:str("idname") == "ShaderNodeEmission" then + for _, s in __iter(n:list("inputs", "bNodeSocket")) do + local v = s:str("name") == "Strength" and s:deref("default_value", 0, "bNodeSocketValueFloat") + if v then + energy = v:num("value") or energy + end + end + end + end + end + local name = ob:idName() + local l +if t == LA_SUN or t == LA_HEMI then + l = { name = name, type = "directional", color = color, intensity = energy * W2LM } +elseif t == LA_SPOT then + local size = la:num("spotsize") or math.rad(45) + if ctx.f.version < 263 then + size = math.rad(size) -- degrees before 2.63 + end + local outer = size / 2 + local blend = la:num("spotblend") or 0 + l = { name = name, type = "spot", color = color, intensity = energy / (4 * math.pi) * W2LM, outerCone = outer, innerCone = outer - outer * blend } +elseif t == LA_LOCAL then + l = { name = name, type = "point", color = color, intensity = energy / (4 * math.pi) * W2LM } +else + local skipped = ctx.meta.skippedLights or {} + ctx.meta.skippedLights = skipped + table.insert(skipped, { name = name, type = t == LA_AREA and"area" or tostring(t) }) + return + end + table.insert(ctx.scene.lights, l) + ctx.scene.nodes[node].light = #ctx.scene.lights +end + +local function slotMaterials(ctx, ob, me) +local obMats = ob:pointers("mat", ob:num("totcol")) + local meMats = me:pointers("mat", me:num("totcol")) + local bits = ob:target("matbits") + local n = math.max(#obMats, #meMats) + local out = {} + for i = 1, n do + local useOb = bits ~= nil and i - 1 < bits.size and buffer.readu8(ctx.f.buf, bits.offset + i - 1) ~= 0 + local addr = (useOb and{obMats[i] }or{meMats[i] +})[1] local m = 0 + if addr then + local blk = Blend.resolve(ctx.f, addr) + local mv = blk and Blend.struct(ctx.f, blk, 0, "Material") + if mv then + m = Material.get(ctx , mv) + end + end + out[i] = m + end + return out +end + +local function deformArmature(ctx, ob) +for _, md in __iter(ob:list("modifiers")) do + if md.struct.name == "ArmatureModifierData" then + local a = md:deref("object", 0, "Object") + if a then + return a + end + end + end + local p = ob:deref("parent", 0, "Object") + if p and (ob:num("partype") or 0) == PARSKEL and (p:num("type") or -1) == OB_ARMATURE then + return p + end + return nil +end + +local function groupNames(ob, me) +local list = me:list("vertex_group_names", "bDeformGroup") + if #list == 0 then + list = ob:list("defbase", "bDeformGroup") + end + local out = {} + for i, g in __iter(list) do + out[i] = g:str("name") or "" + end + return out +end + +local function mesh(ctx, ob, node) + local f = ctx.f + local me = ob:deref("data", 0, "Mesh") + if not me then + return + end + local slots = slotMaterials(ctx, ob, me) + local armOb = deformArmature(ctx, ob) + local armInfo = armOb and armOb.block and ctx.armatures[armOb.block.addr] + local key = tostring(me.block and me.block.index) .. ":" .. table.concat(slots, ",") .. ":" .. tostring(armOb and armOb.block and armOb.block.index) + local skin= nil + if armInfo then + local joints = {} + for gi, name in __iter(groupNames(ob, me)) do + local j = armInfo.names[name] + if j and armInfo.deform[j] then + joints[gi - 1] = j - 1 + end + end + skin = { joints = joints } + end + local idx = ctx.meshes[key] + if not idx then + local poly, err = Mesh.read(f, me, { maxVertices = ctx.opts.maxVertices }) + if not poly then + error(err or "bad mesh", 0) + end + local shapes, ref = Mesh.shapes(f, me, poly.nv) + local built = Prim.build(poly, slots, { triangulate = ctx.opts.triangulate, flipV = ctx.opts.flipV }, skin, shapes, ref) + local m = built.mesh + m.extras = { blend = { vertices = poly.nv, faces = poly.nf, corners = poly.nc, generation = poly.generation, uvs = #poly.uvs, colors = #poly.colors, shapes = #shapes } } + table.insert(ctx.scene.meshes, m) + idx = #ctx.scene.meshes + ctx.meshes[key] = idx + local gens = ctx.meta.generations + gens[poly.generation] = (gens[poly.generation] or 0) + 1 + if #shapes > 1 then + ctx.meta.shapeKeys[idx] = { key = me:deref("key", 0, "Key"), mesh = me, shapes = shapes, ref = ref } + end + end + local n = ctx.scene.nodes[node] + n.mesh = idx + if ctx.scene.meshes[idx].weights then + n.weights = table.clone(ctx.scene.meshes[idx].weights ) + end + if armInfo then + table.insert(ctx.pending, { node = node, ob = ob }) + end +end + +local function skins(ctx) + for _, p in __iter(ctx.pending) do + local armOb = deformArmature(ctx, p.ob) + local info = armOb and armOb.block and ctx.armatures[armOb.block.addr] + if info then + local armWorld = worldOf(ctx, info.node) + local meshWorld = worldOf(ctx, p.node) + local n = #info.joints + local ibm = buffer.create(n * 64) + for j = 1, n do + local inv = Mat4.inverseFull(Mat4.mul(armWorld, info.rest[j])) or Mat4.identity() + local m = Mat4.mul(inv, meshWorld) + for k = 1, 16 do + buffer.writef32(ibm, ((j - 1) * 16 + k - 1) * 4, m[k]) + end + end + local acc = Scene.accessor(ibm, "f32", 16, n) + acc.matrix = true + table.insert(ctx.scene.skins, { name = armOb and armOb:idName(), joints = table.clone(info.joints), inverseBindMatrices = acc, skeleton = info.node }) + ctx.scene.nodes[p.node].skin = #ctx.scene.skins + end + end +end + +local function object(ctx, ob, under, depth) +local addr = ob.block and ob.block.addr + if addr ~= nil and ctx.objects[addr] then + return ctx.objects[addr] + end + if depth > 512 then + return nil + end + local parentOb = ob:deref("parent", 0, "Object") + local parentNode= under + local prefix = Mat4.identity() + local partype = ob:num("partype") or 0 + if parentOb then + local pn = object(ctx, parentOb, under, depth + 1) + if pn then + parentNode = pn + prefix = mat4(ob, "parentinv") or Mat4.identity() + if partype == PARBONE then + local info = parentOb.block and ctx.armatures[parentOb.block.addr] + local bone = ob:str("parsubstr") or "" + local j = info and info.names[bone] + if info and j then + parentNode = info.joints[j] + local len = info.bones[j]:num("length") or 0 + prefix = Mat4.mul(Mat4.translation(0, len, 0), prefix) + end + end + end + end + if addr ~= nil and ctx.objects[addr] then + return ctx.objects[addr] + end + local props = objectProps(ob) + local node= { name = ob:idName(), children = {} } + nodeTRS(node, Mat4.mul(prefix, objectBasis(props))) + local idx = addNode(ctx, node, parentNode) + if addr ~= nil then + ctx.objects[addr] = idx + end + ctx.objView[idx] = ob + ctx.props[idx] = props + ctx.prefix[idx] = prefix + local t = ob:num("type") or -1 + local extras= { type = TYPE_NAME[t] or tostring(t) } + node.extras = { blend = extras } + local lay = ob:num("lay") + if lay and ctx.f.version < 280 then + extras.layers = lay + end + local mods = {} + for _, md in __iter(ob:list("modifiers")) do + table.insert(mods, { name = md:sub("modifier") and ((md:sub("modifier") )):str("name") or md:str("name") or "", type = (string.gsub(md.struct.name, "ModifierData$", "")) }) + end + if #mods > 0 then + extras.modifiers = mods + ctx.meta.modifiers[node.name or tostring(idx)] = mods + end + if t == OB_ARMATURE then + armature(ctx, ob, idx) + elseif t == OB_CAMERA then + camera(ctx, ob, idx) + elseif t == OB_LAMP then + light(ctx, ob, idx) + elseif t ~= OB_EMPTY and t ~= OB_MESH then + ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] = (ctx.meta.unsupported[TYPE_NAME[t] or tostring(t)] or 0) + 1 + end + return idx +end + +-- ------------------------------------------------------------------------------------------------ animation +local function apply(props, curves, frame, prefix, name) +local p= {} + for k, v in __iter(props) do + p[k] = table.clone(v) + end + for _, c in __iter(curves) do + local kind, who, rest = Anim.split(c.path) + if (prefix == nil and kind == nil) or (prefix ~= nil and kind == prefix and who == name) then + local arr = p[rest] + if arr and c.index >= 0 and c.index < #arr then + local v = Anim.evaluate(c, frame) + if rest == "rotation_axis_angle" or rest == "delta_rotation_axis_angle" then + arr[c.index + 1] = v + else + arr[c.index + 1] = v + end + end + end + end + return p +end + + +local function frames(lo, hi, step) +local out = {} + local f = lo + while f < hi - 1e-9 and #out < 2 ^ 20 do + table.insert(out, f) + f =f+ step + end + table.insert(out, hi) + return out +end + + + +local function animations(ctx) + local f = ctx.f + local jobs= {} + -- an IPO shared by several objects animates the first by name only, as Blender's 2.5 conversion leaves it + local ipoOwner= {} + for _, ob in __iter(ctx.objView) do + local a, nm = ob:ptr("ipo"), ob:idName() or "" + if a ~= nil and (ipoOwner[a] == nil or nm < ipoOwner[a]) then + ipoOwner[a] = nm + end + end + for node = 1, #ctx.scene.nodes do + local ob = ctx.objView[node] + local curves, name + if ob then + curves, name = Anim.curves(f, ob:deref("adt", 0, "AnimData")) + local ipoAddr = ob:ptr("ipo") + if not curves and not ob:has("adt") and ipoAddr ~= nil and ipoOwner[ipoAddr] == ob:idName() then + curves, name = Anim.ipo(f, ob:deref("ipo", 0, "Ipo")) + end + end + if curves and #curves > 0 and name then + table.insert(jobs, { kind = "object", node = node, curves = curves, action = name }) + local info = ob.block and ctx.armatures[ob.block.addr] + if info then + table.insert(jobs, { kind = "pose", info = info, curves = curves, action = name }) + end + end + end + for meshIdx, sk in __iter(ctx.meta.shapeKeys) do + local found, name = Anim.curves(f, sk.key and sk.key:deref("adt", 0, "AnimData")) + local curves= found + if not curves and sk.key and not sk.key:has("adt") then + local names = {} + for i, s in __iter(sk.shapes) do + names[i] = s.name + end + curves, name = Anim.ipo(f, sk.key:deref("ipo", 0, "Ipo"), names) + end + -- 2.7x could key shape values from the mesh ("shape_keys.key_blocks[...].value") + local mc, mname = Anim.curves(f, sk.mesh:deref("adt", 0, "AnimData")) + for _, c in __iter(mc or {}) do + if string.sub(c.path, 1, 11) == "shape_keys." then + c.path = string.sub(c.path, 12) + local list= curves or {} + curves = list + name = name or mname + table.insert(list, c) + end + end + if curves and #curves > 0 and name then + local nodes = {} + for i, n in __iter(ctx.scene.nodes) do + if n.mesh == meshIdx then + table.insert(nodes, i) + end + end + table.insert(jobs, { kind = "shapes", nodes = nodes, curves = curves , action = name, meshIdx = meshIdx }) + end + end + if #jobs == 0 then + return + end + table.sort(jobs, function(a, b) +return a.action < b.action + end) + local zero = ctx.meta.frameStart + for _, j in __iter(jobs) do + local lo = Anim.range(j.curves) + zero = math.min(zero, math.floor(lo)) + end + ctx.meta.frameZero = zero + local fps = ctx.meta.fps + local step = ctx.opts.sampleStep or 1 + local byAction= {} + for _, j in __iter(jobs) do + local anim = byAction[j.action] + if not anim then + anim = { name = j.action, channels = {} } +byAction[j.action] = anim + table.insert(ctx.scene.animations, anim) + end + local lo, hi = Anim.range(j.curves) + local fs = frames(math.floor(lo), math.ceil(hi), step) -- whole frames, as Blender plays them + local times = {} + for i, fr in __iter(fs) do + times[i] = (fr - zero) / fps + end + local tmp = Scene.new() + if j.kind == "object" then + local node = j.node +local track = { translation = {}, rotation = {}, scale = {} } + local last= nil + for _, fr in __iter(fs) do + local p = apply(ctx.props[node], j.curves, fr, nil, nil) + local t, r, s = Mat4.decompose(Mat4.mul(ctx.prefix[node], objectBasis(p))) + if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + last = r + table.move(t, 1, 3, #track.translation + 1, track.translation) + table.move(r, 1, 4, #track.rotation + 1, track.rotation) + table.move(s, 1, 3, #track.scale + 1, track.scale) + end + local nd = ctx.scene.nodes[node] + if nd.matrix then + local t, r, s = Mat4.decompose(nd.matrix) + nd.translation, nd.rotation, nd.scale, nd.matrix = t, r, s, nil + end + Rig.animation(tmp, nil, { node }, times, { [1] = track }, nil) + elseif j.kind == "pose" then + local info = j.info + local tracks = {} + local touched = {} + for _, c in __iter(j.curves) do + local kind, who = Anim.split(c.path) + if kind == "pose.bones" and who and info.names[who] then + touched[info.names[who] ] = true + end + end + for b in __iter(touched) do + local name = info.bones[b]:str("name") or "" + local node = info.joints[b] + local track = { translation = {}, rotation = {}, scale = {} } + local last= nil + for _, fr in __iter(fs) do + local p = apply(ctx.props[node], j.curves, fr, "pose.bones", name) + local t, r, s = Mat4.decompose(Mat4.mul(info.restLocal[b], objectBasis(p))) + if last and last[1] * r[1] + last[2] * r[2] + last[3] * r[3] + last[4] * r[4] < 0 then + r = { -r[1], -r[2], -r[3], -r[4] } + end + last = r + table.move(t, 1, 3, #track.translation + 1, track.translation) + table.move(r, 1, 4, #track.rotation + 1, track.rotation) + table.move(s, 1, 3, #track.scale + 1, track.scale) + end + tracks[b] = track + end + Rig.animation(tmp, nil, info.joints, times, tracks , nil) + elseif j.kind == "shapes" then + local sk = ctx.meta.shapeKeys[j.meshIdx] + local count = #sk.shapes - 1 + local out = buffer.create(#fs * count * 4) + for i, fr in __iter(fs) do + local k = 0 + for si, s in __iter(sk.shapes) do + if si ~= sk.ref then + local v = s.value + for _, c in __iter(j.curves) do + local kind, who, rest = Anim.split(c.path) + if kind == "key_blocks" and who == s.name and rest == "value" then + v = math.clamp(Anim.evaluate(c, fr), math.min(s.min, s.max), math.max(s.min, s.max)) -- the slider range + end + end + buffer.writef32(out, ((i - 1) * count + k) * 4, v) + k =k+ 1 + end + end + end + local tb = buffer.create(#times * 4) + for i, t in __iter(times) do + buffer.writef32(tb, (i - 1) * 4, t) + end + for _, node in __iter(j.nodes) do + table.insert(tmp.animations, { channels = { + { node = node, path = "weights" , input = Scene.accessor(tb, "f32", 1, #times), output = Scene.accessor(out, "f32", 1, #fs * count), interpolation = "LINEAR" }, + } }) + end + end + for _, a in __iter(tmp.animations) do + for _, ch in __iter(a.channels) do + table.insert(anim.channels, ch) + end + end + end +end + +-- ------------------------------------------------------------------------------------------------ entry +local function pickScene(f, name) +local scenes = Blend.blocks(f, "SC") + if name then + for _, b in __iter(scenes) do + local v = Blend.struct(f, b, 0, "Scene") + if v and v:idName() == name then + return v + end + end + return nil + end + local glob = Blend.blocks(f, "GLOB")[1] + local g = glob and Blend.struct(f, glob, 0, "FileGlobal") + local cur = g and g:target("curscene") + if cur and cur.code == "SC" then + return Blend.struct(f, cur, 0, "Scene") + end + return (scenes[1] and{(Blend.struct(f, scenes[1], 0, "Scene") )}or{nil +})[1]end + +function Read.scene(f, opts) +local o= opts or {} + local scene = Scene.new() + local sc = pickScene(f, o.scene) + if o.scene and not sc then + return nil, "no scene named " .. o.scene + end + local meta= { + modifiers = {}, unsupported = {}, generations = {}, shapeKeys = {}, collections = {}, + fps = 24, frameStart = 1, render = { aspect = 16 / 9 }, + } + local ctx= { + f = f, scene = scene, opts = o, objects = {}, objView = {}, parentOf = {}, world = {}, meshes = {}, materials = {}, + textures = {}, armatures = {}, prefix = {}, props = {}, meta = meta, pending = {}, + } + local order= {} + if sc then + local r = sc:sub("r") + if r then + local fps = (r:num("frs_sec") or 24) / math.max(r:num("frs_sec_base") or 1, 1e-6) + meta.fps = (fps > 0 and{fps }or{24 +})[1] meta.frameStart = r:num("sfra") or 1 + meta.engine = r:str("engine") + local xs, ys = r:num("xsch") or 1920, r:num("ysch") or 1080 + local xa, ya = r:num("xasp") or 1, r:num("yasp") or 1 + if xs > 0 and ys > 0 and xa > 0 and ya > 0 then + meta.render = { aspect = (xs * xa) / (ys * ya), width = xs, height = ys } + end + end + local units = sc:sub("unit") + local scale = units and units:num("scale_length") + if scale and scale > 0 then + scene.meta.unit = scale + end + local master = sc:deref("master_collection", 0, "Collection") + if master then + local seen = {} + local function walk(col, under, depth) + if depth > 64 or (col.block and seen[col.block.addr]) then + return + end + if col.block then + seen[col.block.addr] = true + end + for _, co in __iter(col:list("gobject", "CollectionObject")) do + local ob = co:deref("ob", 0, "Object") + if ob then + table.insert(order, { ob = ob, under = under }) + end + end + for _, cc in __iter(col:list("children", "CollectionChild")) do + local child = cc:deref("collection", 0, "Collection") + if child then + local cn= nil + if o.collections ~= false then + cn = addNode(ctx, { name = child:idName(), children = {}, extras = { blend = { collection = true } } }, under) + end + table.insert(meta.collections, child:idName() or "") + walk(child, cn, depth + 1) + end + end + end + walk(master, nil, 0) + else + for _, base in __iter(sc:list("base", "Base")) do + local ob = base:deref("object", 0, "Object") + if ob then + table.insert(order, { ob = ob, under = nil }) + end + end + end + end + if #order == 0 then + for _, b in __iter(Blend.blocks(f, "OB")) do + local ob = Blend.struct(f, b, 0, "Object") + if ob then + table.insert(order, { ob = ob, under = nil }) + end + end + end + local firstUnder= {} + for _, e in __iter(order) do + local a = e.ob.block and e.ob.block.addr + if a ~= nil and firstUnder[a] == nil then + firstUnder[a] = e.under or 0 + end + end + for _, e in __iter(order) do + local a = e.ob.block and e.ob.block.addr + local u = a ~= nil and firstUnder[a] or nil + object(ctx, e.ob, (u and u > 0 and{u }or{nil})[1], 0) + end + for node = 1, #scene.nodes do + local ob = ctx.objView[node] + if ob and (ob:num("type") or -1) == OB_MESH then + mesh(ctx, ob, node) + end + end + skins(ctx) + if o.animations ~= false then + animations(ctx) + end + meta.shapeKeys = nil + meta.engine = nil + local render = meta.render + meta.render = nil + scene.meta.up = "z" + scene.meta.source = { + format = "blend", version = f.version, subversion = f.subversion, pointerSize = f.pointerSize, + littleEndian = f.little, compression = f.compression, fps = meta.fps, frameStart = meta.frameStart, + frameZero = meta.frameZero, modifiers = meta.modifiers, unsupported = meta.unsupported, + generations = meta.generations, collections = meta.collections, skippedLights = meta.skippedLights, + aspect = render.aspect, scene = sc and sc:idName(), + } + return scene, nil +end + return Read end __FILES["model/bsp"] = function() diff --git a/build/rosetta.lua.linemap.json b/build/rosetta.lua.linemap.json index 45c4801..89abe06 100644 --- a/build/rosetta.lua.linemap.json +++ b/build/rosetta.lua.linemap.json @@ -1,539 +1,547 @@ [ [660, "src/Rosetta/init.luau"], [1504, "src/Rosetta/Registry.luau"], -[3613, "src/Rosetta/Types.luau"], -[4696, "src/Rosetta/archive/7z/init.luau"], -[5081, "src/Rosetta/archive/7z/Header.luau"], -[5608, "src/Rosetta/archive/adf/init.luau"], -[5890, "src/Rosetta/archive/applesingle/init.luau"], -[6076, "src/Rosetta/archive/ar/init.luau"], -[6479, "src/Rosetta/archive/arj/init.luau"], -[6689, "src/Rosetta/archive/binhex/init.luau"], -[6938, "src/Rosetta/archive/br/init.luau"], -[7013, "src/Rosetta/archive/bz2/init.luau"], -[7077, "src/Rosetta/archive/cab/init.luau"], -[7490, "src/Rosetta/archive/cab/Sum.luau"], -[7531, "src/Rosetta/archive/cpio/init.luau"], -[7699, "src/Rosetta/archive/d64/init.luau"], -[8113, "src/Rosetta/archive/fat/init.luau"], -[8235, "src/Rosetta/archive/grp/init.luau"], -[8349, "src/Rosetta/archive/gzip/init.luau"], -[8534, "src/Rosetta/archive/iso/init.luau"], -[8606, "src/Rosetta/archive/lha/init.luau"], -[9031, "src/Rosetta/archive/lz4/init.luau"], -[9375, "src/Rosetta/archive/macbinary/init.luau"], -[9573, "src/Rosetta/archive/mpq/init.luau"], -[9979, "src/Rosetta/archive/mpq/Crypt.luau"], -[10044, "src/Rosetta/archive/pak/init.luau"], -[10178, "src/Rosetta/archive/rpm/init.luau"], -[10502, "src/Rosetta/archive/tar/init.luau"], -[10620, "src/Rosetta/archive/uu/init.luau"], -[10890, "src/Rosetta/archive/vpk/init.luau"], -[11201, "src/Rosetta/archive/wad/init.luau"], -[11651, "src/Rosetta/archive/wad/Map.luau"], -[12081, "src/Rosetta/archive/wad/Picture.luau"], -[12183, "src/Rosetta/archive/xz/init.luau"], -[12283, "src/Rosetta/archive/yenc/init.luau"], -[12555, "src/Rosetta/archive/z/init.luau"], -[12651, "src/Rosetta/archive/zip/init.luau"], -[12870, "src/Rosetta/archive/zoo/init.luau"], -[13066, "src/Rosetta/archive/zst/init.luau"], -[13130, "src/Rosetta/audio/aac/init.luau"], -[13336, "src/Rosetta/audio/ac3/init.luau"], -[13482, "src/Rosetta/audio/adpcm/init.luau"], -[13627, "src/Rosetta/audio/adx/init.luau"], -[13858, "src/Rosetta/audio/aiff/init.luau"], -[14249, "src/Rosetta/audio/ape/init.luau"], -[14377, "src/Rosetta/audio/au/init.luau"], -[14538, "src/Rosetta/audio/brstm/init.luau"], -[14829, "src/Rosetta/audio/caf/init.luau"], -[15491, "src/Rosetta/audio/flac/init.luau"], -[15639, "src/Rosetta/audio/flac/Meta.luau"], -[15861, "src/Rosetta/audio/flac/Stream.luau"], -[16231, "src/Rosetta/audio/m4a/init.luau"], -[16565, "src/Rosetta/audio/mp3/init.luau"], -[16825, "src/Rosetta/audio/mp3/Index.luau"], -[17016, "src/Rosetta/audio/mp3/Stream.luau"], -[17243, "src/Rosetta/audio/mp3/Tags.luau"], -[17555, "src/Rosetta/audio/mpc/init.luau"], -[17649, "src/Rosetta/audio/opus/init.luau"], -[18027, "src/Rosetta/audio/opus/Encode.luau"], -[18138, "src/Rosetta/audio/qoa/init.luau"], -[18318, "src/Rosetta/audio/tta/init.luau"], -[18436, "src/Rosetta/audio/vag/init.luau"], -[18659, "src/Rosetta/audio/voc/init.luau"], -[18934, "src/Rosetta/audio/vorbis/init.luau"], -[19388, "src/Rosetta/audio/vorbis/Encode.luau"], -[20201, "src/Rosetta/audio/wav/init.luau"], -[20822, "src/Rosetta/audio/wav/Codecs.luau"], -[20988, "src/Rosetta/audio/wavpack/init.luau"], -[21195, "src/Rosetta/cad/step/init.luau"], -[21577, "src/Rosetta/cad/step/Brep.luau"], -[21812, "src/Rosetta/cad/step/Parse.luau"], -[22369, "src/Rosetta/cad/step/Write.luau"], -[22617, "src/Rosetta/codecs/audio/Aac/init.luau"], -[22936, "src/Rosetta/codecs/audio/Aac/Decode.luau"], -[23819, "src/Rosetta/codecs/audio/Aac/Tables.luau"], -[24154, "src/Rosetta/codecs/audio/Ac3/init.luau"], -[24313, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], -[25198, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], -[25299, "src/Rosetta/codecs/audio/Adpcm/init.luau"], -[26053, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], -[26355, "src/Rosetta/codecs/audio/Alac/init.luau"], -[26589, "src/Rosetta/codecs/audio/Alac/Decode.luau"], -[27008, "src/Rosetta/codecs/audio/Alac/Encode.luau"], -[27420, "src/Rosetta/codecs/audio/Ape/init.luau"], -[27635, "src/Rosetta/codecs/audio/Ape/Decode.luau"], -[28396, "src/Rosetta/codecs/audio/ApeTag.luau"], -[28493, "src/Rosetta/codecs/audio/Flac/init.luau"], -[28504, "src/Rosetta/codecs/audio/Flac/Encode.luau"], -[29453, "src/Rosetta/codecs/audio/Flac/Frame.luau"], -[30050, "src/Rosetta/codecs/audio/Hively/init.luau"], -[30246, "src/Rosetta/codecs/audio/Hively/Load.luau"], -[30495, "src/Rosetta/codecs/audio/Hively/Player.luau"], -[31453, "src/Rosetta/codecs/audio/Hively/Tables.luau"], -[31672, "src/Rosetta/codecs/audio/Mdct/init.luau"], -[31856, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], -[32065, "src/Rosetta/codecs/audio/MidiRender.luau"], -[32411, "src/Rosetta/codecs/audio/Mpa/init.luau"], -[32425, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], -[32484, "src/Rosetta/codecs/audio/Mpa/Core.luau"], -[34087, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], -[34379, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], -[34764, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], -[35405, "src/Rosetta/codecs/audio/Mpa/Header.luau"], -[35546, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], -[35772, "src/Rosetta/codecs/audio/Musepack/init.luau"], -[36117, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], -[36998, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], -[37376, "src/Rosetta/codecs/audio/Opus/init.luau"], -[37390, "src/Rosetta/codecs/audio/Opus/Celt.luau"], -[39237, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], -[40302, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], -[40362, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], -[40822, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], -[41159, "src/Rosetta/codecs/audio/Opus/Packet.luau"], -[41392, "src/Rosetta/codecs/audio/Opus/Silk.luau"], -[43428, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], -[43802, "src/Rosetta/codecs/audio/Pcm/init.luau"], -[44065, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], -[44362, "src/Rosetta/codecs/audio/Qoa/init.luau"], -[44644, "src/Rosetta/codecs/audio/Resample/init.luau"], -[45003, "src/Rosetta/codecs/audio/SoundFont/init.luau"], -[45057, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], -[45200, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], -[45713, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], -[46494, "src/Rosetta/codecs/audio/Stream.luau"], -[46655, "src/Rosetta/codecs/audio/Tracker/init.luau"], -[47137, "src/Rosetta/codecs/audio/Tracker/Load.luau"], -[47415, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], -[47584, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], -[47712, "src/Rosetta/codecs/audio/Tracker/Player.luau"], -[49700, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], -[49816, "src/Rosetta/codecs/audio/Tta/init.luau"], -[49933, "src/Rosetta/codecs/audio/Tta/Decode.luau"], -[50185, "src/Rosetta/codecs/audio/Vorbis/init.luau"], -[50198, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], -[50582, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], -[51148, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], -[51569, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], -[51608, "src/Rosetta/codecs/audio/VorbisComment.luau"], -[51660, "src/Rosetta/codecs/audio/WavPack/init.luau"], -[51882, "src/Rosetta/codecs/audio/WavPack/Block.luau"], -[53337, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], -[53400, "src/Rosetta/codecs/compress/Brotli/init.luau"], -[53487, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], -[54456, "src/Rosetta/codecs/compress/Brotli/Static.luau"], -[55324, "src/Rosetta/codecs/compress/Bzip2/init.luau"], -[55372, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], -[55888, "src/Rosetta/codecs/compress/Deflate/init.luau"], -[56214, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], -[56634, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], -[57069, "src/Rosetta/codecs/compress/Explode.luau"], -[57265, "src/Rosetta/codecs/compress/Lz4.luau"], -[57534, "src/Rosetta/codecs/compress/Lzh/init.luau"], -[58138, "src/Rosetta/codecs/compress/Lzma/init.luau"], -[58678, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], -[58716, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], -[59189, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], -[59365, "src/Rosetta/codecs/compress/Lzw/init.luau"], -[59633, "src/Rosetta/codecs/compress/Lzx.luau"], -[60067, "src/Rosetta/codecs/compress/PackBits.luau"], -[60157, "src/Rosetta/codecs/compress/Quantum.luau"], -[60394, "src/Rosetta/codecs/compress/UnixCompress.luau"], -[60698, "src/Rosetta/codecs/compress/Xxh32.luau"], -[60767, "src/Rosetta/codecs/compress/Zstd/init.luau"], -[60824, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], -[61782, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], -[61934, "src/Rosetta/codecs/entropy/Huffman.luau"], -[62216, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], -[62227, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], -[62441, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], -[62685, "src/Rosetta/codecs/font/Bitmap.luau"], -[62886, "src/Rosetta/codecs/font/Cff/init.luau"], -[63527, "src/Rosetta/codecs/font/GlyphNames.luau"], -[63677, "src/Rosetta/codecs/font/TrueType/init.luau"], -[63991, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], -[64383, "src/Rosetta/codecs/font/TrueType/Tables.luau"], -[64885, "src/Rosetta/codecs/image/Bcn/init.luau"], -[64992, "src/Rosetta/codecs/image/Bcn/Decode.luau"], -[65481, "src/Rosetta/codecs/image/Bcn/Encode.luau"], -[65910, "src/Rosetta/codecs/image/Blend.luau"], -[66289, "src/Rosetta/codecs/image/Dct/init.luau"], -[66670, "src/Rosetta/codecs/image/Etc.luau"], -[66968, "src/Rosetta/codecs/image/Half.luau"], -[67037, "src/Rosetta/codecs/image/Jpeg/init.luau"], -[67391, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], -[67799, "src/Rosetta/codecs/image/Jpeg/Color.luau"], -[68036, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], -[68796, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], -[69677, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], -[70123, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], -[70201, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], -[70268, "src/Rosetta/codecs/image/Pixels.luau"], -[70532, "src/Rosetta/codecs/image/Quantize/init.luau"], -[70991, "src/Rosetta/codecs/image/Raster.luau"], -[71688, "src/Rosetta/codecs/image/Texel.luau"], -[72061, "src/Rosetta/codecs/image/Texture.luau"], -[72206, "src/Rosetta/codecs/image/Vp8/init.luau"], -[72336, "src/Rosetta/codecs/image/Vp8/Decode.luau"], -[74292, "src/Rosetta/codecs/image/Vp8/Predict.luau"], -[74551, "src/Rosetta/codecs/image/Vp8/Tables.luau"], -[74800, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], -[74919, "src/Rosetta/codecs/image/Vp8L/init.luau"], -[75023, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], -[75876, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], -[76828, "src/Rosetta/codecs/image/Yuv.luau"], -[77096, "src/Rosetta/codecs/model/Draco/init.luau"], -[77428, "src/Rosetta/codecs/model/Draco/Attributes.luau"], -[77897, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], -[79086, "src/Rosetta/codecs/model/Draco/Int64.luau"], -[79235, "src/Rosetta/codecs/model/Draco/KdTree.luau"], -[79594, "src/Rosetta/codecs/model/Draco/Predict.luau"], -[80556, "src/Rosetta/codecs/model/Draco/Reader.luau"], -[81030, "src/Rosetta/codecs/model/Mat4.luau"], -[81289, "src/Rosetta/codecs/model/MeshFlatten.luau"], -[81817, "src/Rosetta/codecs/model/Minecraft/init.luau"], -[82369, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], -[82448, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], -[82555, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], -[82761, "src/Rosetta/codecs/model/Polygon.luau"], -[82995, "src/Rosetta/codecs/model/Rbx/init.luau"], -[83232, "src/Rosetta/codecs/model/Rbx/Binary.luau"], -[83986, "src/Rosetta/codecs/model/Rig.luau"], -[84229, "src/Rosetta/codecs/model/Sampler.luau"], -[84389, "src/Rosetta/codecs/model/Vrml/init.luau"], -[84537, "src/Rosetta/codecs/model/Vrml/Build.luau"], -[85111, "src/Rosetta/codecs/model/Vrml/Fields.luau"], -[85274, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], -[86023, "src/Rosetta/codecs/model/Vrml/Parse.luau"], -[86545, "src/Rosetta/codecs/model/Vrml/Write.luau"], -[87272, "src/Rosetta/codecs/model/Vrml/Xml.luau"], -[87504, "src/Rosetta/codecs/text/Json/init.luau"], -[87773, "src/Rosetta/codecs/text/Json/Decode.luau"], -[88187, "src/Rosetta/codecs/text/Json/Encode.luau"], -[88489, "src/Rosetta/codecs/text/Nbt/init.luau"], -[88842, "src/Rosetta/codecs/text/Nbt/Binary.luau"], -[89534, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], -[90174, "src/Rosetta/codecs/text/Nbt/Value.luau"], -[90412, "src/Rosetta/codecs/text/Text/init.luau"], -[90503, "src/Rosetta/codecs/text/Url/init.luau"], -[90708, "src/Rosetta/codecs/text/Xml/init.luau"], -[91111, "src/Rosetta/codecs/text/Xml/Parse.luau"], -[91851, "src/Rosetta/codecs/video/Dsp.luau"], -[92574, "src/Rosetta/codecs/video/H263/init.luau"], -[92730, "src/Rosetta/codecs/video/H263/Decoder.luau"], -[93588, "src/Rosetta/codecs/video/H263/Tables.luau"], -[93791, "src/Rosetta/codecs/video/H264/init.luau"], -[94164, "src/Rosetta/codecs/video/H264/Bitstream.luau"], -[94439, "src/Rosetta/codecs/video/H264/Cabac.luau"], -[95570, "src/Rosetta/codecs/video/H264/Cavlc.luau"], -[96338, "src/Rosetta/codecs/video/H264/Deblock.luau"], -[96596, "src/Rosetta/codecs/video/H264/Decoder.luau"], -[97605, "src/Rosetta/codecs/video/H264/Inter.luau"], -[97859, "src/Rosetta/codecs/video/H264/Intra.luau"], -[98266, "src/Rosetta/codecs/video/H264/Mb.luau"], -[99172, "src/Rosetta/codecs/video/H264/Params.luau"], -[99619, "src/Rosetta/codecs/video/H264/Slice.luau"], -[99870, "src/Rosetta/codecs/video/H264/Tables.luau"], -[99911, "src/Rosetta/codecs/video/H264/Transform.luau"], -[100076, "src/Rosetta/codecs/video/Legacy/init.luau"], -[100274, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], -[100571, "src/Rosetta/codecs/video/Legacy/Flic.luau"], -[100938, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], -[101056, "src/Rosetta/codecs/video/Legacy/Picture.luau"], -[101164, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], -[101437, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], -[101832, "src/Rosetta/codecs/video/Legacy/Smc.luau"], -[102009, "src/Rosetta/codecs/video/Mpeg1/init.luau"], -[102021, "src/Rosetta/codecs/video/Mpeg2/init.luau"], -[102388, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], -[103895, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], -[104034, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], -[104172, "src/Rosetta/codecs/video/Theora/init.luau"], -[104435, "src/Rosetta/codecs/video/Theora/Decoder.luau"], -[105699, "src/Rosetta/codecs/video/Theora/Header.luau"], -[106062, "src/Rosetta/codecs/video/Video/init.luau"], -[106619, "src/Rosetta/codecs/video/Video/Source.luau"], -[106904, "src/Rosetta/containers/Archive.luau"], -[107171, "src/Rosetta/containers/AudioWrap.luau"], -[107674, "src/Rosetta/containers/Avi/init.luau"], -[108226, "src/Rosetta/containers/Chunks.luau"], -[108361, "src/Rosetta/containers/Cpio.luau"], -[108789, "src/Rosetta/containers/Demux.luau"], -[109064, "src/Rosetta/containers/Ebml/init.luau"], -[109377, "src/Rosetta/containers/Fat.luau"], -[110065, "src/Rosetta/containers/Iso9660.luau"], -[110570, "src/Rosetta/containers/IsoBmff/init.luau"], -[110740, "src/Rosetta/containers/IsoBmff/Box.luau"], -[110928, "src/Rosetta/containers/IsoBmff/Demux.luau"], -[111773, "src/Rosetta/containers/IsoBmff/Meta.luau"], -[112294, "src/Rosetta/containers/IsoBmff/Mux.luau"], -[112810, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], -[112927, "src/Rosetta/containers/MacFile.luau"], -[113076, "src/Rosetta/containers/MpegEs.luau"], -[113242, "src/Rosetta/containers/MpegPs/init.luau"], -[113462, "src/Rosetta/containers/MpegTs/init.luau"], -[114254, "src/Rosetta/containers/Ogg/init.luau"], -[114679, "src/Rosetta/containers/Ogg/Mux.luau"], -[114874, "src/Rosetta/containers/Ogg/Page.luau"], -[115043, "src/Rosetta/containers/Riff/init.luau"], -[115360, "src/Rosetta/containers/Tar.luau"], -[115774, "src/Rosetta/containers/Zip/init.luau"], -[116406, "src/Rosetta/core/Adler32.luau"], -[116452, "src/Rosetta/core/Base64.luau"], -[116611, "src/Rosetta/core/Bits.luau"], -[116904, "src/Rosetta/core/Bytes.luau"], -[117431, "src/Rosetta/core/Crc16.luau"], -[117483, "src/Rosetta/core/Crc32.luau"], -[117595, "src/Rosetta/core/Err.luau"], -[117677, "src/Rosetta/core/Input.luau"], -[117753, "src/Rosetta/core/Md5.luau"], -[117912, "src/Rosetta/core/Sniff.luau"], -[117941, "src/Rosetta/data/cbor/init.luau"], -[118040, "src/Rosetta/data/cbor/Codec.luau"], -[118609, "src/Rosetta/data/csv/init.luau"], -[118921, "src/Rosetta/data/ini/init.luau"], -[119167, "src/Rosetta/data/json/init.luau"], -[119259, "src/Rosetta/data/msgpack/init.luau"], -[119348, "src/Rosetta/data/msgpack/Codec.luau"], -[119790, "src/Rosetta/data/nbt/init.luau"], -[119849, "src/Rosetta/data/plist/init.luau"], -[120155, "src/Rosetta/data/plist/Binary.luau"], -[120422, "src/Rosetta/data/snbt/init.luau"], -[120485, "src/Rosetta/data/toml/init.luau"], -[120552, "src/Rosetta/data/toml/Decode.luau"], -[121180, "src/Rosetta/data/toml/Encode.luau"], -[121389, "src/Rosetta/data/xml/init.luau"], -[121445, "src/Rosetta/data/yaml/init.luau"], -[121518, "src/Rosetta/data/yaml/Emit.luau"], -[121808, "src/Rosetta/data/yaml/Parse.luau"], -[123101, "src/Rosetta/font/bdf/init.luau"], -[123390, "src/Rosetta/font/bmfont/init.luau"], -[123817, "src/Rosetta/font/bmfont/Parse.luau"], -[124270, "src/Rosetta/font/eot/init.luau"], -[124502, "src/Rosetta/font/fon/init.luau"], -[124785, "src/Rosetta/font/hershey/init.luau"], -[124980, "src/Rosetta/font/pcf/init.luau"], -[125260, "src/Rosetta/font/psf/init.luau"], -[125580, "src/Rosetta/font/ttf/init.luau"], -[125631, "src/Rosetta/font/type1/init.luau"], -[125990, "src/Rosetta/font/type1/Charstring.luau"], -[126268, "src/Rosetta/font/woff/init.luau"], -[126400, "src/Rosetta/font/woff2/init.luau"], -[126457, "src/Rosetta/font/woff2/Rebuild.luau"], -[126997, "src/Rosetta/host/init.luau"], -[127042, "src/Rosetta/host/Love.luau"], -[127185, "src/Rosetta/host/LuaJIT.luau"], -[127235, "src/Rosetta/host/Luau.luau"], -[127258, "src/Rosetta/host/Roblox.luau"], -[127617, "src/Rosetta/image/ani/init.luau"], -[127797, "src/Rosetta/image/blp/init.luau"], -[128055, "src/Rosetta/image/bmp/init.luau"], -[128470, "src/Rosetta/image/dds/init.luau"], -[128953, "src/Rosetta/image/exr/init.luau"], -[129713, "src/Rosetta/image/exr/Codec.luau"], -[129824, "src/Rosetta/image/exr/Piz.luau"], -[130181, "src/Rosetta/image/gif/init.luau"], -[130697, "src/Rosetta/image/gif/Decode.luau"], -[130760, "src/Rosetta/image/hdr/init.luau"], -[130989, "src/Rosetta/image/hdr/Codec.luau"], -[131200, "src/Rosetta/image/icns/init.luau"], -[131531, "src/Rosetta/image/ico/init.luau"], -[131808, "src/Rosetta/image/ico/Dib.luau"], -[131903, "src/Rosetta/image/ilbm/init.luau"], -[132222, "src/Rosetta/image/jpeg/init.luau"], -[132358, "src/Rosetta/image/ktx/init.luau"], -[133018, "src/Rosetta/image/pcx/init.luau"], -[133282, "src/Rosetta/image/png/init.luau"], -[133862, "src/Rosetta/image/png/Apng.luau"], -[133942, "src/Rosetta/image/png/Decode.luau"], -[134182, "src/Rosetta/image/png/Encode.luau"], -[134337, "src/Rosetta/image/pnm/init.luau"], -[134715, "src/Rosetta/image/pnm/Codec.luau"], -[134992, "src/Rosetta/image/qoi/init.luau"], -[135114, "src/Rosetta/image/qoi/Codec.luau"], -[135264, "src/Rosetta/image/sgi/init.luau"], -[135549, "src/Rosetta/image/sunras/init.luau"], -[135795, "src/Rosetta/image/tga/init.luau"], -[136065, "src/Rosetta/image/tga/Codec.luau"], -[136217, "src/Rosetta/image/tiff/init.luau"], -[137044, "src/Rosetta/image/tiff/Pixels.luau"], -[137434, "src/Rosetta/image/tim/init.luau"], -[137676, "src/Rosetta/image/vtf/init.luau"], -[137911, "src/Rosetta/image/webp/init.luau"], -[138521, "src/Rosetta/image/webp/Alpha.luau"], -[138597, "src/Rosetta/image/webp/Anim.luau"], -[138752, "src/Rosetta/image/xbm/init.luau"], -[138913, "src/Rosetta/image/xpm/init.luau"], -[139181, "src/Rosetta/image/xpm/Names.luau"], -[139237, "src/Rosetta/layered/aseprite/init.luau"], -[139975, "src/Rosetta/layered/ora/init.luau"], -[140262, "src/Rosetta/layered/psd/init.luau"], -[140997, "src/Rosetta/layered/psd/Channels.luau"], -[141349, "src/Rosetta/model/3ds/init.luau"], -[141432, "src/Rosetta/model/3ds/Build.luau"], -[142079, "src/Rosetta/model/3ds/Read.luau"], -[142575, "src/Rosetta/model/3ds/Write.luau"], -[143380, "src/Rosetta/model/3mf/init.luau"], -[143462, "src/Rosetta/model/3mf/Read.luau"], -[144050, "src/Rosetta/model/3mf/Write.luau"], -[144455, "src/Rosetta/model/b3d/init.luau"], -[144510, "src/Rosetta/model/b3d/Read.luau"], -[145081, "src/Rosetta/model/bsp/init.luau"], -[145226, "src/Rosetta/model/bsp/Brush.luau"], -[145504, "src/Rosetta/model/bsp/Quake3.luau"], -[145759, "src/Rosetta/model/dae/init.luau"], -[145948, "src/Rosetta/model/dae/Math.luau"], -[145995, "src/Rosetta/model/dae/Read.luau"], -[147845, "src/Rosetta/model/dae/Write.luau"], -[148214, "src/Rosetta/model/fbx/init.luau"], -[148362, "src/Rosetta/model/fbx/Ascii.luau"], -[148632, "src/Rosetta/model/fbx/Binary.luau"], -[149087, "src/Rosetta/model/fbx/Read.luau"], -[150449, "src/Rosetta/model/fbx/Write.luau"], -[151434, "src/Rosetta/model/fbx/Xform.luau"], -[151475, "src/Rosetta/model/gltf/init.luau"], -[151712, "src/Rosetta/model/gltf/Pack.luau"], -[151781, "src/Rosetta/model/gltf/Read.luau"], -[152512, "src/Rosetta/model/gltf/Write.luau"], -[153192, "src/Rosetta/model/iqm/init.luau"], -[153268, "src/Rosetta/model/iqm/Read.luau"], -[153623, "src/Rosetta/model/iqm/Write.luau"], -[154310, "src/Rosetta/model/ldraw/init.luau"], -[154388, "src/Rosetta/model/ldraw/Colors.luau"], -[154706, "src/Rosetta/model/ldraw/Read.luau"], -[155283, "src/Rosetta/model/lwo/init.luau"], -[155359, "src/Rosetta/model/lwo/Build.luau"], -[155821, "src/Rosetta/model/lwo/Parse.luau"], -[156364, "src/Rosetta/model/mca/init.luau"], -[156706, "src/Rosetta/model/mca/Chunk.luau"], -[156839, "src/Rosetta/model/mca/Lz4Block.luau"], -[156909, "src/Rosetta/model/md2/init.luau"], -[157108, "src/Rosetta/model/md3/init.luau"], -[157336, "src/Rosetta/model/md5/init.luau"], -[157417, "src/Rosetta/model/md5/Read.luau"], -[157850, "src/Rosetta/model/mdl/init.luau"], -[157932, "src/Rosetta/model/mdl/HalfLife.luau"], -[158260, "src/Rosetta/model/mdl/Quake.luau"], -[158478, "src/Rosetta/model/ms3d/init.luau"], -[158550, "src/Rosetta/model/ms3d/Read.luau"], -[158996, "src/Rosetta/model/ms3d/Write.luau"], -[159465, "src/Rosetta/model/obj/init.luau"], -[160207, "src/Rosetta/model/obj/Mtl.luau"], -[160494, "src/Rosetta/model/off/init.luau"], -[160956, "src/Rosetta/model/ply/init.luau"], -[162061, "src/Rosetta/model/ply/Binary.luau"], -[162262, "src/Rosetta/model/pmx/init.luau"], -[162331, "src/Rosetta/model/pmx/Build.luau"], -[162627, "src/Rosetta/model/pmx/Pmd.luau"], -[162962, "src/Rosetta/model/pmx/Read.luau"], -[163366, "src/Rosetta/model/qb/init.luau"], -[163759, "src/Rosetta/model/rbxm/init.luau"], -[164351, "src/Rosetta/model/rbxmx/init.luau"], -[165004, "src/Rosetta/model/robloxmesh/init.luau"], -[165663, "src/Rosetta/model/robloxmesh/Parse.luau"], -[166120, "src/Rosetta/model/robloxmesh/Write.luau"], -[166229, "src/Rosetta/model/schematic/init.luau"], -[166550, "src/Rosetta/model/schematic/Common.luau"], -[166670, "src/Rosetta/model/schematic/Litematic.luau"], -[166881, "src/Rosetta/model/schematic/Mcedit.luau"], -[167125, "src/Rosetta/model/schematic/Sponge.luau"], -[167254, "src/Rosetta/model/smd/init.luau"], -[167321, "src/Rosetta/model/smd/Read.luau"], -[167590, "src/Rosetta/model/smd/Write.luau"], -[167833, "src/Rosetta/model/stl/init.luau"], -[168283, "src/Rosetta/model/stl/Decode.luau"], -[168357, "src/Rosetta/model/usda/init.luau"], -[168566, "src/Rosetta/model/usda/Build.luau"], -[169844, "src/Rosetta/model/usda/Parse.luau"], -[170642, "src/Rosetta/model/usda/Write.luau"], -[171459, "src/Rosetta/model/vox/init.luau"], -[172345, "src/Rosetta/model/vox/Grid.luau"], -[172402, "src/Rosetta/model/vrml/init.luau"], -[172468, "src/Rosetta/model/x/init.luau"], -[172598, "src/Rosetta/model/x/Build.luau"], -[173161, "src/Rosetta/model/x/Parse.luau"], -[173458, "src/Rosetta/model/x3d/init.luau"], -[173536, "src/Rosetta/music/669/init.luau"], -[173742, "src/Rosetta/music/ahx/init.luau"], -[173793, "src/Rosetta/music/far/init.luau"], -[174022, "src/Rosetta/music/hmp/init.luau"], -[174286, "src/Rosetta/music/hvl/init.luau"], -[174337, "src/Rosetta/music/it/init.luau"], -[174755, "src/Rosetta/music/it/Itsex.luau"], -[174871, "src/Rosetta/music/med/init.luau"], -[175518, "src/Rosetta/music/midi/init.luau"], -[175661, "src/Rosetta/music/midi/Smf.luau"], -[176072, "src/Rosetta/music/mod/init.luau"], -[176425, "src/Rosetta/music/mtm/init.luau"], -[176647, "src/Rosetta/music/mus/init.luau"], -[176804, "src/Rosetta/music/okt/init.luau"], -[177085, "src/Rosetta/music/ptm/init.luau"], -[177307, "src/Rosetta/music/s3m/init.luau"], -[177543, "src/Rosetta/music/sf2/init.luau"], -[177586, "src/Rosetta/music/stm/init.luau"], -[177817, "src/Rosetta/music/ult/init.luau"], -[178121, "src/Rosetta/music/umx/init.luau"], -[178337, "src/Rosetta/music/xm/init.luau"], -[178898, "src/Rosetta/music/xmi/init.luau"], -[179106, "src/Rosetta/ops/AudioOps.luau"], -[179555, "src/Rosetta/ops/ImageOps/init.luau"], -[180199, "src/Rosetta/ops/ImageOps/Kernels.luau"], -[180709, "src/Rosetta/ops/LayerOps.luau"], -[180802, "src/Rosetta/ops/MeshOps/init.luau"], -[181838, "src/Rosetta/ops/MeshOps/Greedy.luau"], -[182005, "src/Rosetta/ops/MusicOps.luau"], -[182353, "src/Rosetta/playlist/m3u/init.luau"], -[182706, "src/Rosetta/playlist/pls/init.luau"], -[182884, "src/Rosetta/playlist/xspf/init.luau"], -[183087, "src/Rosetta/subtitle/ass/init.luau"], -[183531, "src/Rosetta/subtitle/srt/init.luau"], -[183704, "src/Rosetta/subtitle/vtt/init.luau"], -[183907, "src/Rosetta/vector/svg/init.luau"], -[183993, "src/Rosetta/vector/svg/Parse.luau"], -[184739, "src/Rosetta/vector/svg/PathData.luau"], -[185107, "src/Rosetta/vector/svg/Render.luau"], -[185524, "src/Rosetta/vector/svg/Style.luau"], -[185896, "src/Rosetta/vector/svg/Write.luau"], -[186096, "src/Rosetta/vector/tiled/init.luau"], -[186276, "src/Rosetta/vector/tiled/Data.luau"], -[186427, "src/Rosetta/vector/tiled/Tmj.luau"], -[187058, "src/Rosetta/vector/tiled/Tmx.luau"], -[187670, "src/Rosetta/video/avi/init.luau"], -[187964, "src/Rosetta/video/fli/init.luau"], -[188115, "src/Rosetta/video/flv/init.luau"], -[188499, "src/Rosetta/video/flv/Amf.luau"], -[188657, "src/Rosetta/video/flv/Mux.luau"], -[188938, "src/Rosetta/video/h264/init.luau"], -[189077, "src/Rosetta/video/mkv/init.luau"], -[189233, "src/Rosetta/video/mkv/Mux.luau"], -[189512, "src/Rosetta/video/mkv/Parse.luau"], -[190233, "src/Rosetta/video/mp4/init.luau"], -[190561, "src/Rosetta/video/mpegps/init.luau"], -[190748, "src/Rosetta/video/mpegts/init.luau"], -[190986, "src/Rosetta/video/ogv/init.luau"], -[191381, "src/Rosetta/video/smk/init.luau"], -[191690, "src/Rosetta/video/smk/Audio.luau"], -[191810, "src/Rosetta/video/y4m/init.luau"] +[3625, "src/Rosetta/Types.luau"], +[4708, "src/Rosetta/archive/7z/init.luau"], +[5093, "src/Rosetta/archive/7z/Header.luau"], +[5620, "src/Rosetta/archive/adf/init.luau"], +[5902, "src/Rosetta/archive/applesingle/init.luau"], +[6088, "src/Rosetta/archive/ar/init.luau"], +[6491, "src/Rosetta/archive/arj/init.luau"], +[6701, "src/Rosetta/archive/binhex/init.luau"], +[6950, "src/Rosetta/archive/br/init.luau"], +[7025, "src/Rosetta/archive/bz2/init.luau"], +[7089, "src/Rosetta/archive/cab/init.luau"], +[7502, "src/Rosetta/archive/cab/Sum.luau"], +[7543, "src/Rosetta/archive/cpio/init.luau"], +[7711, "src/Rosetta/archive/d64/init.luau"], +[8125, "src/Rosetta/archive/fat/init.luau"], +[8247, "src/Rosetta/archive/grp/init.luau"], +[8361, "src/Rosetta/archive/gzip/init.luau"], +[8546, "src/Rosetta/archive/iso/init.luau"], +[8618, "src/Rosetta/archive/lha/init.luau"], +[9043, "src/Rosetta/archive/lz4/init.luau"], +[9387, "src/Rosetta/archive/macbinary/init.luau"], +[9585, "src/Rosetta/archive/mpq/init.luau"], +[9991, "src/Rosetta/archive/mpq/Crypt.luau"], +[10056, "src/Rosetta/archive/pak/init.luau"], +[10190, "src/Rosetta/archive/rpm/init.luau"], +[10514, "src/Rosetta/archive/tar/init.luau"], +[10632, "src/Rosetta/archive/uu/init.luau"], +[10902, "src/Rosetta/archive/vpk/init.luau"], +[11213, "src/Rosetta/archive/wad/init.luau"], +[11663, "src/Rosetta/archive/wad/Map.luau"], +[12093, "src/Rosetta/archive/wad/Picture.luau"], +[12195, "src/Rosetta/archive/xz/init.luau"], +[12295, "src/Rosetta/archive/yenc/init.luau"], +[12567, "src/Rosetta/archive/z/init.luau"], +[12663, "src/Rosetta/archive/zip/init.luau"], +[12882, "src/Rosetta/archive/zoo/init.luau"], +[13078, "src/Rosetta/archive/zst/init.luau"], +[13142, "src/Rosetta/audio/aac/init.luau"], +[13348, "src/Rosetta/audio/ac3/init.luau"], +[13494, "src/Rosetta/audio/adpcm/init.luau"], +[13639, "src/Rosetta/audio/adx/init.luau"], +[13870, "src/Rosetta/audio/aiff/init.luau"], +[14261, "src/Rosetta/audio/ape/init.luau"], +[14389, "src/Rosetta/audio/au/init.luau"], +[14550, "src/Rosetta/audio/brstm/init.luau"], +[14841, "src/Rosetta/audio/caf/init.luau"], +[15503, "src/Rosetta/audio/flac/init.luau"], +[15651, "src/Rosetta/audio/flac/Meta.luau"], +[15873, "src/Rosetta/audio/flac/Stream.luau"], +[16243, "src/Rosetta/audio/m4a/init.luau"], +[16577, "src/Rosetta/audio/mp3/init.luau"], +[16837, "src/Rosetta/audio/mp3/Index.luau"], +[17028, "src/Rosetta/audio/mp3/Stream.luau"], +[17255, "src/Rosetta/audio/mp3/Tags.luau"], +[17567, "src/Rosetta/audio/mpc/init.luau"], +[17661, "src/Rosetta/audio/opus/init.luau"], +[18039, "src/Rosetta/audio/opus/Encode.luau"], +[18150, "src/Rosetta/audio/qoa/init.luau"], +[18330, "src/Rosetta/audio/tta/init.luau"], +[18448, "src/Rosetta/audio/vag/init.luau"], +[18671, "src/Rosetta/audio/voc/init.luau"], +[18946, "src/Rosetta/audio/vorbis/init.luau"], +[19400, "src/Rosetta/audio/vorbis/Encode.luau"], +[20213, "src/Rosetta/audio/wav/init.luau"], +[20834, "src/Rosetta/audio/wav/Codecs.luau"], +[21000, "src/Rosetta/audio/wavpack/init.luau"], +[21207, "src/Rosetta/cad/step/init.luau"], +[21589, "src/Rosetta/cad/step/Brep.luau"], +[21824, "src/Rosetta/cad/step/Parse.luau"], +[22381, "src/Rosetta/cad/step/Write.luau"], +[22629, "src/Rosetta/codecs/audio/Aac/init.luau"], +[22948, "src/Rosetta/codecs/audio/Aac/Decode.luau"], +[23831, "src/Rosetta/codecs/audio/Aac/Tables.luau"], +[24166, "src/Rosetta/codecs/audio/Ac3/init.luau"], +[24325, "src/Rosetta/codecs/audio/Ac3/Decode.luau"], +[25210, "src/Rosetta/codecs/audio/Ac3/Tables.luau"], +[25311, "src/Rosetta/codecs/audio/Adpcm/init.luau"], +[26065, "src/Rosetta/codecs/audio/Adpcm/Decoder.luau"], +[26367, "src/Rosetta/codecs/audio/Alac/init.luau"], +[26601, "src/Rosetta/codecs/audio/Alac/Decode.luau"], +[27020, "src/Rosetta/codecs/audio/Alac/Encode.luau"], +[27432, "src/Rosetta/codecs/audio/Ape/init.luau"], +[27647, "src/Rosetta/codecs/audio/Ape/Decode.luau"], +[28408, "src/Rosetta/codecs/audio/ApeTag.luau"], +[28505, "src/Rosetta/codecs/audio/Flac/init.luau"], +[28516, "src/Rosetta/codecs/audio/Flac/Encode.luau"], +[29465, "src/Rosetta/codecs/audio/Flac/Frame.luau"], +[30062, "src/Rosetta/codecs/audio/Hively/init.luau"], +[30258, "src/Rosetta/codecs/audio/Hively/Load.luau"], +[30507, "src/Rosetta/codecs/audio/Hively/Player.luau"], +[31465, "src/Rosetta/codecs/audio/Hively/Tables.luau"], +[31684, "src/Rosetta/codecs/audio/Mdct/init.luau"], +[31868, "src/Rosetta/codecs/audio/Mdct/Fft.luau"], +[32077, "src/Rosetta/codecs/audio/MidiRender.luau"], +[32423, "src/Rosetta/codecs/audio/Mpa/init.luau"], +[32437, "src/Rosetta/codecs/audio/Mpa/Analysis.luau"], +[32496, "src/Rosetta/codecs/audio/Mpa/Core.luau"], +[34099, "src/Rosetta/codecs/audio/Mpa/EncTables.luau"], +[34391, "src/Rosetta/codecs/audio/Mpa/Encode2.luau"], +[34776, "src/Rosetta/codecs/audio/Mpa/Encode3.luau"], +[35417, "src/Rosetta/codecs/audio/Mpa/Header.luau"], +[35558, "src/Rosetta/codecs/audio/Mpa/Tables.luau"], +[35784, "src/Rosetta/codecs/audio/Musepack/init.luau"], +[36129, "src/Rosetta/codecs/audio/Musepack/Decode.luau"], +[37010, "src/Rosetta/codecs/audio/Musepack/Tables.luau"], +[37388, "src/Rosetta/codecs/audio/Opus/init.luau"], +[37402, "src/Rosetta/codecs/audio/Opus/Celt.luau"], +[39249, "src/Rosetta/codecs/audio/Opus/CeltEncoder.luau"], +[40314, "src/Rosetta/codecs/audio/Opus/CeltTables.luau"], +[40374, "src/Rosetta/codecs/audio/Opus/Decoder.luau"], +[40834, "src/Rosetta/codecs/audio/Opus/Mdct.luau"], +[41171, "src/Rosetta/codecs/audio/Opus/Packet.luau"], +[41404, "src/Rosetta/codecs/audio/Opus/Silk.luau"], +[43440, "src/Rosetta/codecs/audio/Opus/SilkTables.luau"], +[43814, "src/Rosetta/codecs/audio/Pcm/init.luau"], +[44077, "src/Rosetta/codecs/audio/Pcm/Convert.luau"], +[44374, "src/Rosetta/codecs/audio/Qoa/init.luau"], +[44656, "src/Rosetta/codecs/audio/Resample/init.luau"], +[45015, "src/Rosetta/codecs/audio/SoundFont/init.luau"], +[45069, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], +[45212, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], +[45725, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"], +[46506, "src/Rosetta/codecs/audio/Stream.luau"], +[46667, "src/Rosetta/codecs/audio/Tracker/init.luau"], +[47149, "src/Rosetta/codecs/audio/Tracker/Load.luau"], +[47427, "src/Rosetta/codecs/audio/Tracker/Mixer.luau"], +[47596, "src/Rosetta/codecs/audio/Tracker/Pcm.luau"], +[47724, "src/Rosetta/codecs/audio/Tracker/Player.luau"], +[49712, "src/Rosetta/codecs/audio/Tracker/Tables.luau"], +[49828, "src/Rosetta/codecs/audio/Tta/init.luau"], +[49945, "src/Rosetta/codecs/audio/Tta/Decode.luau"], +[50197, "src/Rosetta/codecs/audio/Vorbis/init.luau"], +[50210, "src/Rosetta/codecs/audio/Vorbis/Codebook.luau"], +[50594, "src/Rosetta/codecs/audio/Vorbis/Packet.luau"], +[51160, "src/Rosetta/codecs/audio/Vorbis/Setup.luau"], +[51581, "src/Rosetta/codecs/audio/Vorbis/Tables.luau"], +[51620, "src/Rosetta/codecs/audio/VorbisComment.luau"], +[51672, "src/Rosetta/codecs/audio/WavPack/init.luau"], +[51894, "src/Rosetta/codecs/audio/WavPack/Block.luau"], +[53349, "src/Rosetta/codecs/audio/WavPack/Tables.luau"], +[53412, "src/Rosetta/codecs/compress/Brotli/init.luau"], +[53499, "src/Rosetta/codecs/compress/Brotli/Decode.luau"], +[54468, "src/Rosetta/codecs/compress/Brotli/Static.luau"], +[55336, "src/Rosetta/codecs/compress/Bzip2/init.luau"], +[55384, "src/Rosetta/codecs/compress/Bzip2/Decode.luau"], +[55900, "src/Rosetta/codecs/compress/Deflate/init.luau"], +[56226, "src/Rosetta/codecs/compress/Deflate/Compress.luau"], +[56646, "src/Rosetta/codecs/compress/Deflate/Inflate.luau"], +[57081, "src/Rosetta/codecs/compress/Explode.luau"], +[57277, "src/Rosetta/codecs/compress/Lz4.luau"], +[57546, "src/Rosetta/codecs/compress/Lzh/init.luau"], +[58150, "src/Rosetta/codecs/compress/Lzma/init.luau"], +[58690, "src/Rosetta/codecs/compress/Lzma/Crc64.luau"], +[58728, "src/Rosetta/codecs/compress/Lzma/Decode.luau"], +[59201, "src/Rosetta/codecs/compress/Lzma/Filters.luau"], +[59377, "src/Rosetta/codecs/compress/Lzw/init.luau"], +[59645, "src/Rosetta/codecs/compress/Lzx.luau"], +[60079, "src/Rosetta/codecs/compress/PackBits.luau"], +[60169, "src/Rosetta/codecs/compress/Quantum.luau"], +[60406, "src/Rosetta/codecs/compress/UnixCompress.luau"], +[60710, "src/Rosetta/codecs/compress/Xxh32.luau"], +[60779, "src/Rosetta/codecs/compress/Zstd/init.luau"], +[60836, "src/Rosetta/codecs/compress/Zstd/Decode.luau"], +[61794, "src/Rosetta/codecs/compress/Zstd/Xxh64.luau"], +[61946, "src/Rosetta/codecs/entropy/Huffman.luau"], +[62228, "src/Rosetta/codecs/entropy/RangeCoder/init.luau"], +[62239, "src/Rosetta/codecs/entropy/RangeCoder/Decoder.luau"], +[62453, "src/Rosetta/codecs/entropy/RangeCoder/Encoder.luau"], +[62697, "src/Rosetta/codecs/font/Bitmap.luau"], +[62898, "src/Rosetta/codecs/font/Cff/init.luau"], +[63539, "src/Rosetta/codecs/font/GlyphNames.luau"], +[63689, "src/Rosetta/codecs/font/TrueType/init.luau"], +[64003, "src/Rosetta/codecs/font/TrueType/Glyf.luau"], +[64395, "src/Rosetta/codecs/font/TrueType/Tables.luau"], +[64897, "src/Rosetta/codecs/image/Bcn/init.luau"], +[65004, "src/Rosetta/codecs/image/Bcn/Decode.luau"], +[65493, "src/Rosetta/codecs/image/Bcn/Encode.luau"], +[65922, "src/Rosetta/codecs/image/Blend.luau"], +[66301, "src/Rosetta/codecs/image/Dct/init.luau"], +[66682, "src/Rosetta/codecs/image/Etc.luau"], +[66980, "src/Rosetta/codecs/image/Half.luau"], +[67049, "src/Rosetta/codecs/image/Jpeg/init.luau"], +[67403, "src/Rosetta/codecs/image/Jpeg/Arith.luau"], +[67811, "src/Rosetta/codecs/image/Jpeg/Color.luau"], +[68048, "src/Rosetta/codecs/image/Jpeg/Decode.luau"], +[68808, "src/Rosetta/codecs/image/Jpeg/Encode.luau"], +[69689, "src/Rosetta/codecs/image/Jpeg/Scan.luau"], +[70135, "src/Rosetta/codecs/image/Jpeg/Tables.luau"], +[70213, "src/Rosetta/codecs/image/Jpeg/Yuv.luau"], +[70280, "src/Rosetta/codecs/image/Pixels.luau"], +[70544, "src/Rosetta/codecs/image/Quantize/init.luau"], +[71003, "src/Rosetta/codecs/image/Raster.luau"], +[71700, "src/Rosetta/codecs/image/Texel.luau"], +[72073, "src/Rosetta/codecs/image/Texture.luau"], +[72218, "src/Rosetta/codecs/image/Vp8/init.luau"], +[72348, "src/Rosetta/codecs/image/Vp8/Decode.luau"], +[74304, "src/Rosetta/codecs/image/Vp8/Predict.luau"], +[74563, "src/Rosetta/codecs/image/Vp8/Tables.luau"], +[74812, "src/Rosetta/codecs/image/Vp8/Yuv.luau"], +[74931, "src/Rosetta/codecs/image/Vp8L/init.luau"], +[75035, "src/Rosetta/codecs/image/Vp8L/Decode.luau"], +[75888, "src/Rosetta/codecs/image/Vp8L/Encode.luau"], +[76840, "src/Rosetta/codecs/image/Yuv.luau"], +[77108, "src/Rosetta/codecs/model/Draco/init.luau"], +[77440, "src/Rosetta/codecs/model/Draco/Attributes.luau"], +[77909, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], +[79098, "src/Rosetta/codecs/model/Draco/Int64.luau"], +[79247, "src/Rosetta/codecs/model/Draco/KdTree.luau"], +[79606, "src/Rosetta/codecs/model/Draco/Predict.luau"], +[80568, "src/Rosetta/codecs/model/Draco/Reader.luau"], +[81042, "src/Rosetta/codecs/model/Mat4.luau"], +[81301, "src/Rosetta/codecs/model/MeshFlatten.luau"], +[81829, "src/Rosetta/codecs/model/Minecraft/init.luau"], +[82381, "src/Rosetta/codecs/model/Minecraft/Colors.luau"], +[82460, "src/Rosetta/codecs/model/Minecraft/Legacy.luau"], +[82567, "src/Rosetta/codecs/model/Minecraft/Packed.luau"], +[82773, "src/Rosetta/codecs/model/Polygon.luau"], +[83007, "src/Rosetta/codecs/model/Rbx/init.luau"], +[83244, "src/Rosetta/codecs/model/Rbx/Binary.luau"], +[83998, "src/Rosetta/codecs/model/Rig.luau"], +[84241, "src/Rosetta/codecs/model/Sampler.luau"], +[84401, "src/Rosetta/codecs/model/Vrml/init.luau"], +[84549, "src/Rosetta/codecs/model/Vrml/Build.luau"], +[85123, "src/Rosetta/codecs/model/Vrml/Fields.luau"], +[85286, "src/Rosetta/codecs/model/Vrml/Geometry.luau"], +[86035, "src/Rosetta/codecs/model/Vrml/Parse.luau"], +[86557, "src/Rosetta/codecs/model/Vrml/Write.luau"], +[87284, "src/Rosetta/codecs/model/Vrml/Xml.luau"], +[87516, "src/Rosetta/codecs/text/Json/init.luau"], +[87785, "src/Rosetta/codecs/text/Json/Decode.luau"], +[88199, "src/Rosetta/codecs/text/Json/Encode.luau"], +[88501, "src/Rosetta/codecs/text/Nbt/init.luau"], +[88854, "src/Rosetta/codecs/text/Nbt/Binary.luau"], +[89546, "src/Rosetta/codecs/text/Nbt/Snbt.luau"], +[90186, "src/Rosetta/codecs/text/Nbt/Value.luau"], +[90424, "src/Rosetta/codecs/text/Text/init.luau"], +[90515, "src/Rosetta/codecs/text/Url/init.luau"], +[90720, "src/Rosetta/codecs/text/Xml/init.luau"], +[91123, "src/Rosetta/codecs/text/Xml/Parse.luau"], +[91863, "src/Rosetta/codecs/video/Dsp.luau"], +[92586, "src/Rosetta/codecs/video/H263/init.luau"], +[92742, "src/Rosetta/codecs/video/H263/Decoder.luau"], +[93600, "src/Rosetta/codecs/video/H263/Tables.luau"], +[93803, "src/Rosetta/codecs/video/H264/init.luau"], +[94176, "src/Rosetta/codecs/video/H264/Bitstream.luau"], +[94451, "src/Rosetta/codecs/video/H264/Cabac.luau"], +[95582, "src/Rosetta/codecs/video/H264/Cavlc.luau"], +[96350, "src/Rosetta/codecs/video/H264/Deblock.luau"], +[96608, "src/Rosetta/codecs/video/H264/Decoder.luau"], +[97617, "src/Rosetta/codecs/video/H264/Inter.luau"], +[97871, "src/Rosetta/codecs/video/H264/Intra.luau"], +[98278, "src/Rosetta/codecs/video/H264/Mb.luau"], +[99184, "src/Rosetta/codecs/video/H264/Params.luau"], +[99631, "src/Rosetta/codecs/video/H264/Slice.luau"], +[99882, "src/Rosetta/codecs/video/H264/Tables.luau"], +[99923, "src/Rosetta/codecs/video/H264/Transform.luau"], +[100088, "src/Rosetta/codecs/video/Legacy/init.luau"], +[100286, "src/Rosetta/codecs/video/Legacy/Cinepak.luau"], +[100583, "src/Rosetta/codecs/video/Legacy/Flic.luau"], +[100950, "src/Rosetta/codecs/video/Legacy/Msvideo1.luau"], +[101068, "src/Rosetta/codecs/video/Legacy/Picture.luau"], +[101176, "src/Rosetta/codecs/video/Legacy/QtRle.luau"], +[101449, "src/Rosetta/codecs/video/Legacy/Smacker.luau"], +[101844, "src/Rosetta/codecs/video/Legacy/Smc.luau"], +[102021, "src/Rosetta/codecs/video/Mpeg1/init.luau"], +[102033, "src/Rosetta/codecs/video/Mpeg2/init.luau"], +[102400, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], +[103907, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], +[104046, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"], +[104184, "src/Rosetta/codecs/video/Theora/init.luau"], +[104447, "src/Rosetta/codecs/video/Theora/Decoder.luau"], +[105711, "src/Rosetta/codecs/video/Theora/Header.luau"], +[106074, "src/Rosetta/codecs/video/Video/init.luau"], +[106631, "src/Rosetta/codecs/video/Video/Source.luau"], +[106916, "src/Rosetta/containers/Archive.luau"], +[107183, "src/Rosetta/containers/AudioWrap.luau"], +[107686, "src/Rosetta/containers/Avi/init.luau"], +[108238, "src/Rosetta/containers/Blend.luau"], +[108977, "src/Rosetta/containers/Chunks.luau"], +[109112, "src/Rosetta/containers/Cpio.luau"], +[109540, "src/Rosetta/containers/Demux.luau"], +[109815, "src/Rosetta/containers/Ebml/init.luau"], +[110128, "src/Rosetta/containers/Fat.luau"], +[110816, "src/Rosetta/containers/Iso9660.luau"], +[111321, "src/Rosetta/containers/IsoBmff/init.luau"], +[111491, "src/Rosetta/containers/IsoBmff/Box.luau"], +[111679, "src/Rosetta/containers/IsoBmff/Demux.luau"], +[112524, "src/Rosetta/containers/IsoBmff/Meta.luau"], +[113045, "src/Rosetta/containers/IsoBmff/Mux.luau"], +[113561, "src/Rosetta/containers/IsoBmff/QtPalette.luau"], +[113678, "src/Rosetta/containers/MacFile.luau"], +[113827, "src/Rosetta/containers/MpegEs.luau"], +[113993, "src/Rosetta/containers/MpegPs/init.luau"], +[114213, "src/Rosetta/containers/MpegTs/init.luau"], +[115005, "src/Rosetta/containers/Ogg/init.luau"], +[115430, "src/Rosetta/containers/Ogg/Mux.luau"], +[115625, "src/Rosetta/containers/Ogg/Page.luau"], +[115794, "src/Rosetta/containers/Riff/init.luau"], +[116111, "src/Rosetta/containers/Tar.luau"], +[116525, "src/Rosetta/containers/Zip/init.luau"], +[117157, "src/Rosetta/core/Adler32.luau"], +[117203, "src/Rosetta/core/Base64.luau"], +[117362, "src/Rosetta/core/Bits.luau"], +[117655, "src/Rosetta/core/Bytes.luau"], +[118182, "src/Rosetta/core/Crc16.luau"], +[118234, "src/Rosetta/core/Crc32.luau"], +[118346, "src/Rosetta/core/Err.luau"], +[118428, "src/Rosetta/core/Input.luau"], +[118504, "src/Rosetta/core/Md5.luau"], +[118663, "src/Rosetta/core/Sniff.luau"], +[118692, "src/Rosetta/data/cbor/init.luau"], +[118791, "src/Rosetta/data/cbor/Codec.luau"], +[119360, "src/Rosetta/data/csv/init.luau"], +[119672, "src/Rosetta/data/ini/init.luau"], +[119918, "src/Rosetta/data/json/init.luau"], +[120010, "src/Rosetta/data/msgpack/init.luau"], +[120099, "src/Rosetta/data/msgpack/Codec.luau"], +[120541, "src/Rosetta/data/nbt/init.luau"], +[120600, "src/Rosetta/data/plist/init.luau"], +[120906, "src/Rosetta/data/plist/Binary.luau"], +[121173, "src/Rosetta/data/snbt/init.luau"], +[121236, "src/Rosetta/data/toml/init.luau"], +[121303, "src/Rosetta/data/toml/Decode.luau"], +[121931, "src/Rosetta/data/toml/Encode.luau"], +[122140, "src/Rosetta/data/xml/init.luau"], +[122196, "src/Rosetta/data/yaml/init.luau"], +[122269, "src/Rosetta/data/yaml/Emit.luau"], +[122559, "src/Rosetta/data/yaml/Parse.luau"], +[123852, "src/Rosetta/font/bdf/init.luau"], +[124141, "src/Rosetta/font/bmfont/init.luau"], +[124568, "src/Rosetta/font/bmfont/Parse.luau"], +[125021, "src/Rosetta/font/eot/init.luau"], +[125253, "src/Rosetta/font/fon/init.luau"], +[125536, "src/Rosetta/font/hershey/init.luau"], +[125731, "src/Rosetta/font/pcf/init.luau"], +[126011, "src/Rosetta/font/psf/init.luau"], +[126331, "src/Rosetta/font/ttf/init.luau"], +[126382, "src/Rosetta/font/type1/init.luau"], +[126741, "src/Rosetta/font/type1/Charstring.luau"], +[127019, "src/Rosetta/font/woff/init.luau"], +[127151, "src/Rosetta/font/woff2/init.luau"], +[127208, "src/Rosetta/font/woff2/Rebuild.luau"], +[127748, "src/Rosetta/host/init.luau"], +[127793, "src/Rosetta/host/Love.luau"], +[127936, "src/Rosetta/host/LuaJIT.luau"], +[127986, "src/Rosetta/host/Luau.luau"], +[128009, "src/Rosetta/host/Roblox.luau"], +[128368, "src/Rosetta/image/ani/init.luau"], +[128548, "src/Rosetta/image/blp/init.luau"], +[128806, "src/Rosetta/image/bmp/init.luau"], +[129221, "src/Rosetta/image/dds/init.luau"], +[129704, "src/Rosetta/image/exr/init.luau"], +[130464, "src/Rosetta/image/exr/Codec.luau"], +[130575, "src/Rosetta/image/exr/Piz.luau"], +[130932, "src/Rosetta/image/gif/init.luau"], +[131448, "src/Rosetta/image/gif/Decode.luau"], +[131511, "src/Rosetta/image/hdr/init.luau"], +[131740, "src/Rosetta/image/hdr/Codec.luau"], +[131951, "src/Rosetta/image/icns/init.luau"], +[132282, "src/Rosetta/image/ico/init.luau"], +[132559, "src/Rosetta/image/ico/Dib.luau"], +[132654, "src/Rosetta/image/ilbm/init.luau"], +[132973, "src/Rosetta/image/jpeg/init.luau"], +[133109, "src/Rosetta/image/ktx/init.luau"], +[133769, "src/Rosetta/image/pcx/init.luau"], +[134033, "src/Rosetta/image/png/init.luau"], +[134613, "src/Rosetta/image/png/Apng.luau"], +[134693, "src/Rosetta/image/png/Decode.luau"], +[134933, "src/Rosetta/image/png/Encode.luau"], +[135088, "src/Rosetta/image/pnm/init.luau"], +[135466, "src/Rosetta/image/pnm/Codec.luau"], +[135743, "src/Rosetta/image/qoi/init.luau"], +[135865, "src/Rosetta/image/qoi/Codec.luau"], +[136015, "src/Rosetta/image/sgi/init.luau"], +[136300, "src/Rosetta/image/sunras/init.luau"], +[136546, "src/Rosetta/image/tga/init.luau"], +[136816, "src/Rosetta/image/tga/Codec.luau"], +[136968, "src/Rosetta/image/tiff/init.luau"], +[137795, "src/Rosetta/image/tiff/Pixels.luau"], +[138185, "src/Rosetta/image/tim/init.luau"], +[138427, "src/Rosetta/image/vtf/init.luau"], +[138662, "src/Rosetta/image/webp/init.luau"], +[139272, "src/Rosetta/image/webp/Alpha.luau"], +[139348, "src/Rosetta/image/webp/Anim.luau"], +[139503, "src/Rosetta/image/xbm/init.luau"], +[139664, "src/Rosetta/image/xpm/init.luau"], +[139932, "src/Rosetta/image/xpm/Names.luau"], +[139988, "src/Rosetta/layered/aseprite/init.luau"], +[140726, "src/Rosetta/layered/ora/init.luau"], +[141013, "src/Rosetta/layered/psd/init.luau"], +[141748, "src/Rosetta/layered/psd/Channels.luau"], +[142100, "src/Rosetta/model/3ds/init.luau"], +[142183, "src/Rosetta/model/3ds/Build.luau"], +[142830, "src/Rosetta/model/3ds/Read.luau"], +[143326, "src/Rosetta/model/3ds/Write.luau"], +[144131, "src/Rosetta/model/3mf/init.luau"], +[144213, "src/Rosetta/model/3mf/Read.luau"], +[144801, "src/Rosetta/model/3mf/Write.luau"], +[145206, "src/Rosetta/model/b3d/init.luau"], +[145261, "src/Rosetta/model/b3d/Read.luau"], +[145832, "src/Rosetta/model/blend/init.luau"], +[145928, "src/Rosetta/model/blend/Anim.luau"], +[146274, "src/Rosetta/model/blend/Material.luau"], +[146626, "src/Rosetta/model/blend/Mesh.luau"], +[147261, "src/Rosetta/model/blend/Normals.luau"], +[147422, "src/Rosetta/model/blend/Prim.luau"], +[147871, "src/Rosetta/model/blend/Read.luau"], +[148771, "src/Rosetta/model/bsp/init.luau"], +[148916, "src/Rosetta/model/bsp/Brush.luau"], +[149194, "src/Rosetta/model/bsp/Quake3.luau"], +[149449, "src/Rosetta/model/dae/init.luau"], +[149638, "src/Rosetta/model/dae/Math.luau"], +[149685, "src/Rosetta/model/dae/Read.luau"], +[151535, "src/Rosetta/model/dae/Write.luau"], +[151904, "src/Rosetta/model/fbx/init.luau"], +[152052, "src/Rosetta/model/fbx/Ascii.luau"], +[152322, "src/Rosetta/model/fbx/Binary.luau"], +[152777, "src/Rosetta/model/fbx/Read.luau"], +[154139, "src/Rosetta/model/fbx/Write.luau"], +[155124, "src/Rosetta/model/fbx/Xform.luau"], +[155165, "src/Rosetta/model/gltf/init.luau"], +[155402, "src/Rosetta/model/gltf/Pack.luau"], +[155471, "src/Rosetta/model/gltf/Read.luau"], +[156202, "src/Rosetta/model/gltf/Write.luau"], +[156882, "src/Rosetta/model/iqm/init.luau"], +[156958, "src/Rosetta/model/iqm/Read.luau"], +[157313, "src/Rosetta/model/iqm/Write.luau"], +[158000, "src/Rosetta/model/ldraw/init.luau"], +[158078, "src/Rosetta/model/ldraw/Colors.luau"], +[158396, "src/Rosetta/model/ldraw/Read.luau"], +[158973, "src/Rosetta/model/lwo/init.luau"], +[159049, "src/Rosetta/model/lwo/Build.luau"], +[159511, "src/Rosetta/model/lwo/Parse.luau"], +[160054, "src/Rosetta/model/mca/init.luau"], +[160396, "src/Rosetta/model/mca/Chunk.luau"], +[160529, "src/Rosetta/model/mca/Lz4Block.luau"], +[160599, "src/Rosetta/model/md2/init.luau"], +[160798, "src/Rosetta/model/md3/init.luau"], +[161026, "src/Rosetta/model/md5/init.luau"], +[161107, "src/Rosetta/model/md5/Read.luau"], +[161540, "src/Rosetta/model/mdl/init.luau"], +[161622, "src/Rosetta/model/mdl/HalfLife.luau"], +[161950, "src/Rosetta/model/mdl/Quake.luau"], +[162168, "src/Rosetta/model/ms3d/init.luau"], +[162240, "src/Rosetta/model/ms3d/Read.luau"], +[162686, "src/Rosetta/model/ms3d/Write.luau"], +[163155, "src/Rosetta/model/obj/init.luau"], +[163897, "src/Rosetta/model/obj/Mtl.luau"], +[164184, "src/Rosetta/model/off/init.luau"], +[164646, "src/Rosetta/model/ply/init.luau"], +[165751, "src/Rosetta/model/ply/Binary.luau"], +[165952, "src/Rosetta/model/pmx/init.luau"], +[166021, "src/Rosetta/model/pmx/Build.luau"], +[166317, "src/Rosetta/model/pmx/Pmd.luau"], +[166652, "src/Rosetta/model/pmx/Read.luau"], +[167056, "src/Rosetta/model/qb/init.luau"], +[167449, "src/Rosetta/model/rbxm/init.luau"], +[168041, "src/Rosetta/model/rbxmx/init.luau"], +[168694, "src/Rosetta/model/robloxmesh/init.luau"], +[169353, "src/Rosetta/model/robloxmesh/Parse.luau"], +[169810, "src/Rosetta/model/robloxmesh/Write.luau"], +[169919, "src/Rosetta/model/schematic/init.luau"], +[170240, "src/Rosetta/model/schematic/Common.luau"], +[170360, "src/Rosetta/model/schematic/Litematic.luau"], +[170571, "src/Rosetta/model/schematic/Mcedit.luau"], +[170815, "src/Rosetta/model/schematic/Sponge.luau"], +[170944, "src/Rosetta/model/smd/init.luau"], +[171011, "src/Rosetta/model/smd/Read.luau"], +[171280, "src/Rosetta/model/smd/Write.luau"], +[171523, "src/Rosetta/model/stl/init.luau"], +[171973, "src/Rosetta/model/stl/Decode.luau"], +[172047, "src/Rosetta/model/usda/init.luau"], +[172256, "src/Rosetta/model/usda/Build.luau"], +[173534, "src/Rosetta/model/usda/Parse.luau"], +[174332, "src/Rosetta/model/usda/Write.luau"], +[175149, "src/Rosetta/model/vox/init.luau"], +[176035, "src/Rosetta/model/vox/Grid.luau"], +[176092, "src/Rosetta/model/vrml/init.luau"], +[176158, "src/Rosetta/model/x/init.luau"], +[176288, "src/Rosetta/model/x/Build.luau"], +[176851, "src/Rosetta/model/x/Parse.luau"], +[177148, "src/Rosetta/model/x3d/init.luau"], +[177226, "src/Rosetta/music/669/init.luau"], +[177432, "src/Rosetta/music/ahx/init.luau"], +[177483, "src/Rosetta/music/far/init.luau"], +[177712, "src/Rosetta/music/hmp/init.luau"], +[177976, "src/Rosetta/music/hvl/init.luau"], +[178027, "src/Rosetta/music/it/init.luau"], +[178445, "src/Rosetta/music/it/Itsex.luau"], +[178561, "src/Rosetta/music/med/init.luau"], +[179208, "src/Rosetta/music/midi/init.luau"], +[179351, "src/Rosetta/music/midi/Smf.luau"], +[179762, "src/Rosetta/music/mod/init.luau"], +[180115, "src/Rosetta/music/mtm/init.luau"], +[180337, "src/Rosetta/music/mus/init.luau"], +[180494, "src/Rosetta/music/okt/init.luau"], +[180775, "src/Rosetta/music/ptm/init.luau"], +[180997, "src/Rosetta/music/s3m/init.luau"], +[181233, "src/Rosetta/music/sf2/init.luau"], +[181276, "src/Rosetta/music/stm/init.luau"], +[181507, "src/Rosetta/music/ult/init.luau"], +[181811, "src/Rosetta/music/umx/init.luau"], +[182027, "src/Rosetta/music/xm/init.luau"], +[182588, "src/Rosetta/music/xmi/init.luau"], +[182796, "src/Rosetta/ops/AudioOps.luau"], +[183245, "src/Rosetta/ops/ImageOps/init.luau"], +[183889, "src/Rosetta/ops/ImageOps/Kernels.luau"], +[184399, "src/Rosetta/ops/LayerOps.luau"], +[184492, "src/Rosetta/ops/MeshOps/init.luau"], +[185528, "src/Rosetta/ops/MeshOps/Greedy.luau"], +[185695, "src/Rosetta/ops/MusicOps.luau"], +[186043, "src/Rosetta/playlist/m3u/init.luau"], +[186396, "src/Rosetta/playlist/pls/init.luau"], +[186574, "src/Rosetta/playlist/xspf/init.luau"], +[186777, "src/Rosetta/subtitle/ass/init.luau"], +[187221, "src/Rosetta/subtitle/srt/init.luau"], +[187394, "src/Rosetta/subtitle/vtt/init.luau"], +[187597, "src/Rosetta/vector/svg/init.luau"], +[187683, "src/Rosetta/vector/svg/Parse.luau"], +[188429, "src/Rosetta/vector/svg/PathData.luau"], +[188797, "src/Rosetta/vector/svg/Render.luau"], +[189214, "src/Rosetta/vector/svg/Style.luau"], +[189586, "src/Rosetta/vector/svg/Write.luau"], +[189786, "src/Rosetta/vector/tiled/init.luau"], +[189966, "src/Rosetta/vector/tiled/Data.luau"], +[190117, "src/Rosetta/vector/tiled/Tmj.luau"], +[190748, "src/Rosetta/vector/tiled/Tmx.luau"], +[191360, "src/Rosetta/video/avi/init.luau"], +[191654, "src/Rosetta/video/fli/init.luau"], +[191805, "src/Rosetta/video/flv/init.luau"], +[192189, "src/Rosetta/video/flv/Amf.luau"], +[192347, "src/Rosetta/video/flv/Mux.luau"], +[192628, "src/Rosetta/video/h264/init.luau"], +[192767, "src/Rosetta/video/mkv/init.luau"], +[192923, "src/Rosetta/video/mkv/Mux.luau"], +[193202, "src/Rosetta/video/mkv/Parse.luau"], +[193923, "src/Rosetta/video/mp4/init.luau"], +[194251, "src/Rosetta/video/mpegps/init.luau"], +[194438, "src/Rosetta/video/mpegts/init.luau"], +[194676, "src/Rosetta/video/ogv/init.luau"], +[195071, "src/Rosetta/video/smk/init.luau"], +[195380, "src/Rosetta/video/smk/Audio.luau"], +[195500, "src/Rosetta/video/y4m/init.luau"] ] diff --git a/src/Rosetta/containers/Blend.luau b/src/Rosetta/containers/Blend.luau index 2361230..72561dd 100644 --- a/src/Rosetta/containers/Blend.luau +++ b/src/Rosetta/containers/Blend.luau @@ -131,7 +131,6 @@ local function decompress(buf: buffer, o: number, n: number, opts: Options?): (b end local function header(b: buffer, n: number): (number?, number, boolean, number, number, string?) - -- -> header size, pointer size, little, version, format | nil, error if n < 12 or readstring(b, 0, 7) ~= "BLENDER" then return nil, 0, false, 0, 0, "not a .blend file (no BLENDER magic)" end @@ -425,7 +424,6 @@ function Blend.structOf(f: File, blk: Block): Struct? return f.dna.structs[blk.sdna + 1] end --- element i (0-based) of a block, as its own SDNA struct or as `as` (a struct name) 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 @@ -535,8 +533,6 @@ local function scalar(f: File, t: string, size: number, o: number): number return readu8(b, o) -- char, uchar, uint8_t, bool end --- a number (scalars), a string (char arrays), an array of numbers (other arrays), a View (embedded structs), the --- pointer key (pointers); nil when no field has any of the names function View.get(self: View, ...: string): any local fld = find(self, { ... }) if not fld then @@ -619,7 +615,6 @@ function View.target(self: View, ...: string): Block? return Blend.resolve(self.file, self:ptr(...), self.block) end --- the struct a pointer field points at (element i, 0-based), typed by the field's type or `as` 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) @@ -639,7 +634,6 @@ function View.deref(self: View, name: string | { string }, i: number?, as: strin return Blend.struct(f, blk, i, sname) end --- all elements of a pointer-to-array field: the block's count (or byte size / struct size when that is larger) 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 @@ -655,7 +649,6 @@ function View.array(self: View, name: string | { string }, as: string?): { View return out end --- a pointer to an array of pointers (Material **mat, ActionLayer **layer_array, ...): n keys (default: the block size) 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) @@ -679,7 +672,6 @@ function View.pointers(self: View, name: string | { string }, n: number?): { any return out end --- a ListBase field (first / last) walked through each element's `next`, typed as `as` or the first block's struct 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)) @@ -715,7 +707,6 @@ function View.list(self: View, name: string | { string }, as: string?, limit: nu return out end --- the bytes a pointer field points at: (block offset, block size) in file.buf function View.data(self: View, ...: string): (number?, number) local blk = self:target(...) if not blk then @@ -724,7 +715,6 @@ function View.data(self: View, ...: string): (number?, number) return blk.offset, blk.size end --- a NUL-terminated string behind a char pointer function View.cstring(self: View, ...: string): string? local blk = self:target(...) if not blk then @@ -735,7 +725,6 @@ function View.cstring(self: View, ...: string): string? return if z then string.sub(s, 1, z - 1) else s end --- an ID's name without its two-letter code ("OBCube" -> "Cube") function View.idName(self: View): string? local id = self:sub("id") local n = if id then id:str("name") else self:str("name") diff --git a/src/Rosetta/model/blend/Anim.luau b/src/Rosetta/model/blend/Anim.luau index 9ce147d..7d1eebf 100644 --- a/src/Rosetta/model/blend/Anim.luau +++ b/src/Rosetta/model/blend/Anim.luau @@ -61,7 +61,6 @@ local function curve(f: Blend.File, fc: Blend.View): Curve? return { path = path, index = fc:num("array_index") or 0, keys = keys, extend = fc:num("extend") or 0, modifiers = #mods } end --- the f-curves an AnimData plays from its action (nil when it has none) function Anim.curves(f: Blend.File, adt: Blend.View?): ({ Curve }?, string?) if not adt then return nil, nil @@ -207,7 +206,6 @@ local function bezier(a: Key, b: Key, x: number): number return bezierAt(y0, y1, y2, y3, t) end --- Penner easing: t in 0..d, from b by c local function bounceOut(t: number, b: number, c: number, d: number): number t /= d if t < 1 / 2.75 then @@ -334,7 +332,6 @@ function Anim.range(curves: { Curve }): (number, number) return lo, hi end --- "pose.bones[\"name\"].location" -> "name", "location" function Anim.split(path: string): (string?, string?, string) local kind, name, rest = string.match(path, '^(%w[%w_%.]-)%["(.-)"%]%.([%w_]+)$') if kind and name and rest then diff --git a/src/Rosetta/model/blend/Mesh.luau b/src/Rosetta/model/blend/Mesh.luau index 9729197..25155b5 100644 --- a/src/Rosetta/model/blend/Mesh.luau +++ b/src/Rosetta/model/blend/Mesh.luau @@ -129,7 +129,6 @@ local function find(layers: { Layer }, domain: string, kind: string?, name: stri return nil end --- a raw pointer field (Mesh.mvert, ...) as a layer when no CustomData layer has it local function legacy(f: Blend.File, me: Blend.View, field: string, kind: string, domain: string): Layer? local blk = me:target(field) local st = f.dna.byName[kind] @@ -139,7 +138,6 @@ local function legacy(f: Blend.File, me: Blend.View, field: string, kind: string return { name = "", domain = domain, kind = kind, offset = blk.offset, bytes = blk.size, elem = st.size } end --- reads element i (0-based) of a layer as number component c (0-based) of a generic kind local function reader(f: Blend.File, L: Layer): (number, number) -> number local b = f.buf local o, elem, k = L.offset, L.elem, L.kind @@ -166,7 +164,6 @@ local function reader(f: Blend.File, L: Layer): (number, number) -> number end Mesh.reader = reader --- a field of an SDNA-struct layer: element i -> value (number) of component c local function fieldReader(f: Blend.File, L: Layer, field: string): ((number, number) -> number)? local st = f.dna.byName[L.kind] local fld = st and st.byName[field] @@ -249,7 +246,6 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri if nv > maxV or nl > maxV or nt > maxV or np > maxV then return nil, "limit: mesh over maxVertices" end - -- positions local pos = buffer.create(nv * 12) local P = find(layers, "point", "float3", "position") local mv = find(layers, "point", "MVert") or legacy(f, me, "mvert", "MVert", "point") @@ -342,7 +338,6 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri end poly.cornerVert = corner.verts poly.nc = nl - -- material index and smooth flags local mats = buffer.create(np * 4) local smooth = buffer.create(np) local mi = find(layers, "face", "int32", "material_index") @@ -396,12 +391,10 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri corner.tess = tessCorner end local nc = poly.nc - -- corner index -> the element index in the source corner layers local remap: buffer? = corner.remap local function src(i: number): number return if remap then buffer.readu32(remap, i * 4) else i end - -- UV maps for _, L in layers do if L.domain == "corner" and (L.kind == "float2" or L.kind == "MLoopUV") and string.sub(L.name, 1, 1) ~= "." then local r = if L.kind == "float2" then reader(f, L) else fieldReader(f, L, "uv") @@ -455,7 +448,6 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri end end end - -- colour attributes: f32 x 4 linear per element for _, L in layers do if (L.domain == "corner" or L.domain == "point") and (L.kind == "color" or L.kind == "bytecolor") and string.sub(L.name, 1, 1) ~= "." then local n = if L.domain == "corner" then nc else nv @@ -489,8 +481,6 @@ function Mesh.read(f: Blend.File, me: Blend.View, limits: Limits?): (Poly?, stri table.insert(poly.colors, { name = "Col", domain = "corner", data = tessColors(f, corner.tess :: buffer, nc, tf.offset, tf.bytes, tf.elem, col.offset, 4, not f.little, true) }) end end - -- MLoopCol layers carry the CD_PROP_BYTE_COLOR type (17) and are read above as bytecolor (r, g, b, a bytes) - -- custom normals local cn = find(layers, "corner", "short2", "custom_normal") for _, L in layers do if not cn and L.domain == "corner" and L.cdtype == 41 then diff --git a/src/Rosetta/model/blend/Normals.luau b/src/Rosetta/model/blend/Normals.luau index 980d838..52f372d 100644 --- a/src/Rosetta/model/blend/Normals.luau +++ b/src/Rosetta/model/blend/Normals.luau @@ -37,7 +37,6 @@ function Normals.decode(poly: any, lnor: buffer, fanId: buffer, fans: Fans, _ang local id = readu32(fanId, c * 4) if not done[id] then done[id] = true - -- walk back to the fan's first corner (crossing each corner's previous edge), then forward local start = c local cyclic = false local guard = 0 @@ -71,7 +70,6 @@ function Normals.decode(poly: any, lnor: buffer, fanId: buffer, fans: Fans, _ang end local v = readu32(cv, start * 4) local nx, ny, nz = readf32(lnor, start * 12), readf32(lnor, start * 12 + 4), readf32(lnor, start * 12 + 8) - -- the fan's edges in order: the first corner's previous edge, then every corner's next edge local corners = { start } local edges = { readu32(cv, readu32(prv, start * 4) * 4) } local q = start diff --git a/src/Rosetta/model/blend/Read.luau b/src/Rosetta/model/blend/Read.luau index 5d6629f..494c5e0 100644 --- a/src/Rosetta/model/blend/Read.luau +++ b/src/Rosetta/model/blend/Read.luau @@ -84,7 +84,6 @@ end export type Props = { [string]: { number } } -- location / rotation_euler / ... as Blender data paths, rotmode --- an object's or pose bone's transform properties, keyed by their RNA names local function objectProps(ob: Blend.View): Props -- fields missing from old files take their neutral value local function v(fallback: { number }, ...: string): { number } @@ -611,7 +610,8 @@ local function animations(ctx: Ctx) end end for meshIdx, sk in ctx.meta.shapeKeys do - local curves, name = Anim.curves(f, sk.key and sk.key:deref("adt", 0, "AnimData")) + local found, name = Anim.curves(f, sk.key and sk.key:deref("adt", 0, "AnimData")) + local curves: { Curve }? = found if not curves and sk.key and not sk.key:has("adt") then local names = {} for i, s in sk.shapes do @@ -624,9 +624,10 @@ local function animations(ctx: Ctx) for _, c in mc or {} do if string.sub(c.path, 1, 11) == "shape_keys." then c.path = string.sub(c.path, 12) - curves = curves or {} + local list: { Curve } = curves or {} + curves = list name = name or mname - table.insert(curves :: { Curve }, c) + table.insert(list, c) end end if curves and #curves > 0 and name then @@ -857,7 +858,6 @@ function Read.scene(f: Blend.File, opts: Options?): (Types.Scene?, string?) end end end - -- objects whose parent sits in a collection go under the parent; others under their (first) collection local firstUnder: { [any]: number? } = {} for _, e in order do local a = e.ob.block and e.ob.block.addr @@ -870,7 +870,6 @@ function Read.scene(f: Blend.File, opts: Options?): (Types.Scene?, string?) local u = a ~= nil and firstUnder[a] or nil object(ctx, e.ob, if u and u > 0 then u else nil, 0) end - -- meshes after every object exists (armatures first, for skins) for node = 1, #scene.nodes do local ob = ctx.objView[node] if ob and (ob:num("type") or -1) == OB_MESH then