From 2e82b7d0af96fadcd27622ceb248616e676628ff Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sun, 1 Nov 2026 18:53:41 -0600 Subject: [PATCH] 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)