ws-3d3-d: model/b3d (Blitz3D read: brushes, textures, node tree, skins, keyframe animation; LH -> RH)

This commit is contained in:
4DBug committed 2026-10-31 14:00:57 -05:00
1 parent de4f14a343
commit 07dc6f7e84
7 files changed
+1106 -1

No files matched your search

+1
View File
@@ -35,6 +35,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` |
| video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.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 | 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` |
| model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` |
+15 -1
View File
@@ -1,6 +1,6 @@
# Scene (3D models) and Voxels
Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX) loads as one `Scene`, a structure
Every model format (glTF / GLB, OBJ, STL, PLY, OFF, FBX, Collada, 3MF, USDA, VOX, B3D, LDraw) loads as one `Scene`, a structure
shaped like glTF 2.0: a node tree, meshes made of primitives, flat attribute buffers (accessors), PBR materials,
textures, cameras, lights, skins and animations. Mesh-only formats (STL, PLY, OFF) give a one-node scene. MagicaVoxel
files also carry voxel grids (`scene.voxels`). Editing goes through `F.ops.mesh`.
@@ -378,6 +378,19 @@ local vox = assert(F.save(grid, nil, { format = "vox" })) -- a grid alone saves
assert(F.load(vox).voxels[1].size[1] == 4)
```
## Blitz3D (B3D)
`.b3d` files (Blitz3D, also written by many old game tools) load read-only. The node tree keeps its names and TRS;
each `MESH` becomes one mesh whose primitives (one per `TRIS` chunk) share the vertex accessors; brushes become
materials (colour, alpha, shininess, the first texture as `baseColorTexture` with its position / scale / rotation as
`transform`, the full brush in `extras.b3d`); `BONE` weights become a skin (the 4 strongest weights per vertex) and
`KEYS` + `ANIM` one animation sampled at `frame / fps`. Texture files come through `files` / `resolve` like any other
model's (by the stored path, then by its base name: B3D files often store absolute Windows paths).
Blitz3D is **left-handed**: the reader mirrors z (and turns the triangle winding and rotations to match), so the scene
is glTF's right-handed Y-up with the model looking as it did in Blitz3D. `meta.source.handedness = "left"` records
the origin, `meta.source.fps` / `frames` the `ANIM` chunk.
## Formats
| Format | Read | Write | Notes |
@@ -392,6 +405,7 @@ assert(F.load(vox).voxels[1].size[1] == 4)
| 3MF | yes | yes | |
| USDA (+ USDZ read) | yes | yes | |
| VOX | yes | yes | voxel grids, scene graph, materials |
| B3D (Blitz3D) | yes | | brushes, textures, skins, keyframe animation; left-handed source mirrored to glTF's frame |
| STEP | via the CAD plug-in | | see [cad.md](cad.md) |
Capabilities per format: [FORMATS.md](../FORMATS.md).
+12
View File
@@ -374,6 +374,18 @@ local list: { Entry } = {
return require("@formats/model/3mf")
end,
},
{
name = "b3d",
category = "model",
path = "model/b3d",
extensions = { "b3d" },
mime = { "model/x-b3d" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/model/Mat4" },
caps = { decode = true, encode = false, materials = true, textures = true, skins = true, animation = true, colors = true },
load = function()
return require("@formats/model/b3d")
end,
},
{
name = "dae",
category = "model",
+576
View File
@@ -0,0 +1,576 @@
--!strict
-- model/b3d/Read: the BB3D chunk tree -> Types.Scene (see model/b3d for what is read and how it is mapped). Chunks are
-- walked with containers/Chunks (4-byte id, u32 little-endian size, no padding); fields are read through core/Bytes
-- readers over each chunk body, so a short body sets the reader's sticky error instead of reading past the end.
-- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from).
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Chunks = require("@formats/containers/Chunks")
local Mat4 = require("@formats/codecs/model/Mat4")
local Read = {}
export type Options = {
resolve: ((uri: string) -> any)?,
files: { [string]: any }?,
maxVertices: number?,
maxDepth: number?,
}
local LAYOUT: Chunks.Layout = { maxChunks = 1000000 }
local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" }
type Brush = { name: string, color: { number }, shininess: number, blend: number, fx: number, textures: { number } }
type TexInfo = { file: string, flags: number, blend: number, offset: { number }, scale: { number }, rotation: number, index: number }
type MeshRec = { mesh: number, node: number, count: number, joints: { { number } }, weights: { { number } } }
type Bone = { node: number, target: MeshRec?, list: { number } }
type Keys = { t: { [number]: { number } }, s: { [number]: { number } }, r: { [number]: { number } } }
-- the file's left-handed Y-up values in glTF's right-handed frame: z mirrored; quaternions as w x y z, conjugated
-- (Blitz3D stores the inverse rotation, as assimp's reader reads them) then mirrored
local function vec(r: Bytes.Reader): { number }
local x, y, z = r:f32le(), r:f32le(), r:f32le()
return { x, y, -z }
end
local function quat(r: Bytes.Reader): { number }
local w, x, y, z = r:f32le(), r:f32le(), r:f32le(), r:f32le()
local l = math.sqrt(w * w + x * x + y * y + z * z)
if l < 1e-12 or l ~= l then
return { 0, 0, 0, 1 }
end
return { x / l, y / l, -z / l, w / l }
end
local function fetcher(opts: Options?): (string) -> buffer?
local files = opts and opts.files
local resolve = opts and opts.resolve
return function(uri: string): buffer?
local v: any = if type(files) == "table" then files[uri] else nil
if v == nil and type(resolve) == "function" then
local ok, res = pcall(resolve, uri)
v = if ok then res else nil
end
return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil
end
end
-- scene(r, opts) -> Scene | nil, message, kind
function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, string?)
local buf = src.buf
local maxVertices = opts and opts.maxVertices or 2 ^ 24
local maxDepth = opts and opts.maxDepth or 256
local fetch = fetcher(opts)
local top = Chunks.walk(buf, src.base, src.limit, LAYOUT)
local head = top[1]
if not head or head.id ~= "BB3D" then
return nil, "not a BB3D file", nil
end
if head.truncated then
return nil, "truncated", "truncated"
end
local hr = Bytes.reader(buf, head.offset, head.size)
local version = hr:i32le()
if hr.err then
return nil, "truncated", "truncated"
end
local scene = Types.Scene.new()
local texs: { TexInfo } = {}
local brushes: { Brush } = {}
local materialOf: { [number]: number } = {} -- brush index (0-based) -> material
local meshes: { MeshRec } = {}
local bones: { Bone } = {}
local nodeKeys: { [number]: Keys } = {}
local anim: { frames: number, fps: number, flags: number }? = nil
local lastMesh: MeshRec? = nil
local totalVertices = 0
local failure: string?, failKind: string? = nil, nil
local function fail(msg: string, kind: string?)
if not failure then
failure, failKind = msg, kind
end
end
local function body(c: Chunks.Chunk): Bytes.Reader
if c.truncated then
fail("truncated " .. c.id .. " chunk", "truncated")
end
return Bytes.reader(buf, c.offset, c.avail)
end
local function readTexs(r: Bytes.Reader)
while r.pos < r.limit and not r.err do
local file = r:cstring()
local t: TexInfo = { file = file, flags = r:i32le(), blend = r:i32le(), offset = { r:f32le(), r:f32le() }, scale = { r:f32le(), r:f32le() }, rotation = r:f32le(), index = 0 }
if r.err then
return fail("truncated TEXS entry", "truncated")
end
local tex: Types.Texture = { name = string.match(file, "([^/\\]+)$") or file, uri = file, mime = MIME[string.lower(string.match(file, "%.(%w+)$") or "")] }
local data = fetch(file)
if not data then
local base = string.match(file, "([^/\\]+)$")
if base and base ~= file then
data = fetch(base)
end
end
tex.data = data
if bit32.band(t.flags, 48) ~= 0 then
tex.sampler = { wrapS = if bit32.band(t.flags, 16) ~= 0 then "clamp" else "repeat", wrapT = if bit32.band(t.flags, 32) ~= 0 then "clamp" else "repeat" }
end
tex.extras = { b3d = { flags = t.flags, blend = t.blend } }
table.insert(scene.textures, tex)
t.index = #scene.textures
table.insert(texs, t)
end
end
local function readBrus(r: Bytes.Reader)
local n = r:i32le()
if r.err or n < 0 or n > 8 then
return fail("bad BRUS texture count")
end
while r.pos < r.limit and not r.err do
local b: Brush = { name = r:cstring(), color = { r:f32le(), r:f32le(), r:f32le(), r:f32le() }, shininess = r:f32le(), blend = r:i32le(), fx = r:i32le(), textures = {} }
for i = 1, n do
b.textures[i] = r:i32le()
end
if r.err then
return fail("truncated BRUS entry", "truncated")
end
table.insert(brushes, b)
end
end
-- the material of brush id (0-based) | nil for -1 / out of range
local function material(id: number): number?
if id < 0 or id >= #brushes then
return nil
end
local have = materialOf[id]
if have then
return have
end
local b = brushes[id + 1]
local m = Types.Scene.material(b.name ~= "" and b.name or nil)
local c = b.color
local function clamp01(v: number): number
return if v ~= v then 1 else math.clamp(v, 0, 1)
end
m.baseColor = { clamp01(c[1]), clamp01(c[2]), clamp01(c[3]), clamp01(c[4]) }
m.metallic = 0
m.roughness = 1 - 0.8 * clamp01(b.shininess)
m.doubleSided = bit32.band(b.fx, 16) ~= 0
if m.baseColor[4] < 1 or bit32.band(b.fx, 32) ~= 0 then
m.alphaMode = "blend"
end
if bit32.band(b.fx, 1) ~= 0 then
m.extensions = { KHR_materials_unlit = {} }
end
local extraTex: { number } = {}
for i, tid in b.textures do
local t = texs[tid + 1]
if tid >= 0 and t then
if not m.baseColorTexture then
local ref: Types.TextureRef = { texture = t.index, texCoord = if bit32.band(t.flags, 65536) ~= 0 then 1 else nil }
local o, s, rot = t.offset, t.scale, t.rotation
if o[1] ~= 0 or o[2] ~= 0 or s[1] ~= 1 or s[2] ~= 1 or rot ~= 0 then
ref.transform = { offset = { o[1], o[2] }, scale = { s[1], s[2] }, rotation = rot }
end
m.baseColorTexture = ref
if bit32.band(t.flags, 4) ~= 0 then
m.alphaMode = "mask"
elseif bit32.band(t.flags, 2) ~= 0 then
m.alphaMode = "blend"
end
else
extraTex[i] = t.index
end
end
end
m.extras = { b3d = { shininess = b.shininess, blend = b.blend, fx = b.fx, textures = if next(extraTex) then extraTex else nil } }
table.insert(scene.materials, m)
materialOf[id] = #scene.materials
return #scene.materials
end
local function readMesh(r: Bytes.Reader, nodeIndex: number): number?
local master = r:i32le()
if r.err then
fail("truncated MESH", "truncated")
return nil
end
local list = Chunks.walk(buf, r.pos, r.limit, LAYOUT)
local attrs: { [string]: Types.Accessor }? = nil
local count = 0
local mesh: Types.Mesh = { primitives = {} }
local rec: MeshRec = { mesh = 0, node = nodeIndex, count = 0, joints = {}, weights = {} }
for _, c in list do
local cr = body(c)
if c.id == "VRTS" and not attrs then
local flags, sets, size = cr:i32le(), cr:i32le(), cr:i32le()
if cr.err or sets < 0 or sets > 8 or size < 0 or size > 4 then
fail("bad VRTS header")
return nil
end
local hasN, hasC = bit32.band(flags, 1) ~= 0, bit32.band(flags, 2) ~= 0
local stride = 12 + (if hasN then 12 else 0) + (if hasC then 16 else 0) + sets * size * 4
local n = (cr.limit - cr.pos) // stride
totalVertices += n
if totalVertices > maxVertices then
fail(string.format("limit: %d vertices is over the %d vertex limit", totalVertices, maxVertices), "limit")
return nil
end
local pos = buffer.create(n * 12)
local nrm = if hasN then buffer.create(n * 12) else nil
local col = if hasC then buffer.create(n * 16) else nil
local uvs: { buffer } = {}
for s = 1, sets do
uvs[s] = buffer.create(n * 8)
end
local readf32, writef32 = buffer.readf32, buffer.writef32
local p = cr.pos
for i = 0, n - 1 do
writef32(pos, i * 12, readf32(buf, p))
writef32(pos, i * 12 + 4, readf32(buf, p + 4))
writef32(pos, i * 12 + 8, -readf32(buf, p + 8))
p += 12
if nrm then
writef32(nrm, i * 12, readf32(buf, p))
writef32(nrm, i * 12 + 4, readf32(buf, p + 4))
writef32(nrm, i * 12 + 8, -readf32(buf, p + 8))
p += 12
end
if col then
for k = 0, 3 do
writef32(col, i * 16 + k * 4, readf32(buf, p + k * 4))
end
p += 16
end
for s = 1, sets do
if size >= 1 then
writef32(uvs[s], i * 8, readf32(buf, p))
end
if size >= 2 then
writef32(uvs[s], i * 8 + 4, readf32(buf, p + 4))
end
p += size * 4
end
end
local a: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, n) }
if nrm then
a.NORMAL = Types.Scene.accessor(nrm, "f32", 3, n)
end
if col then
a.COLOR_0 = Types.Scene.accessor(col, "f32", 4, n)
end
if size > 0 then
for s = 1, sets do
a["TEXCOORD_" .. (s - 1)] = Types.Scene.accessor(uvs[s], "f32", 2, n)
end
end
attrs, count = a, n
mesh.extras = { b3d = { vertexFlags = flags, texCoordSets = sets, texCoordSize = size } }
elseif c.id == "TRIS" then
local brush = cr:i32le()
if cr.err then
fail("truncated TRIS", "truncated")
return nil
end
if not attrs then
fail("TRIS before VRTS")
return nil
end
local nt = (cr.limit - cr.pos) // 12
local idx = buffer.create(nt * 12)
local readu32, writeu32 = buffer.readu32, buffer.writeu32
local p = cr.pos
for i = 0, nt - 1 do
local a, b, cc = readu32(buf, p), readu32(buf, p + 4), readu32(buf, p + 8)
if a >= count or b >= count or cc >= count then
fail(string.format("triangle %d: vertex index out of range", i))
return nil
end
-- mirrored z: reverse the winding to keep the faces front-facing
writeu32(idx, i * 12, a)
writeu32(idx, i * 12 + 4, cc)
writeu32(idx, i * 12 + 8, b)
p += 12
end
local prim: Types.Primitive = { attributes = attrs, indices = Types.Scene.accessor(idx, "u32", 1, nt * 3), mode = "triangles" }
prim.material = material(if brush == -1 then master else brush)
table.insert(mesh.primitives, prim)
end
end
if not attrs then
return nil -- a mesh without vertices: the node stays a pivot
end
if #mesh.primitives == 0 then
table.insert(mesh.primitives, { attributes = attrs, mode = "points" :: "points" })
end
table.insert(scene.meshes, mesh)
rec.mesh, rec.count = #scene.meshes, count
table.insert(meshes, rec)
lastMesh = rec
return #scene.meshes
end
local function readBone(r: Bytes.Reader, nodeIndex: number)
local b: Bone = { node = nodeIndex, target = lastMesh, list = {} }
table.insert(bones, b)
local list = b.list
while r.pos + 8 <= r.limit do
local v, w = r:i32le(), r:f32le()
table.insert(list, v)
table.insert(list, w)
end
end
local function readKeys(r: Bytes.Reader, nodeIndex: number)
local flags = r:i32le()
local per = 4 + (if bit32.band(flags, 1) ~= 0 then 12 else 0) + (if bit32.band(flags, 2) ~= 0 then 12 else 0) + (if bit32.band(flags, 4) ~= 0 then 16 else 0)
local k = nodeKeys[nodeIndex]
if not k then
k = { t = {}, s = {}, r = {} }
nodeKeys[nodeIndex] = k
end
while not r.err and r.pos + per <= r.limit do
local frame = r:i32le()
if bit32.band(flags, 1) ~= 0 then
k.t[frame] = vec(r)
end
if bit32.band(flags, 2) ~= 0 then
local x, y, z = r:f32le(), r:f32le(), r:f32le()
k.s[frame] = { x, y, z }
end
if bit32.band(flags, 4) ~= 0 then
k.r[frame] = quat(r)
end
end
end
local function readNode(c: Chunks.Chunk, depth: number): number?
if depth > maxDepth then
fail("limit: nodes nested deeper than " .. maxDepth, "limit")
return nil
end
local r = body(c)
local name = r:cstring()
local t = vec(r)
local sx, sy, sz = r:f32le(), r:f32le(), r:f32le()
local q = quat(r)
if r.err then
fail("truncated NODE", "truncated")
return nil
end
local node: Types.Node = { name = name, children = {} }
if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then
node.translation = t
end
if q[1] ~= 0 or q[2] ~= 0 or q[3] ~= 0 then
node.rotation = q
end
if sx ~= 1 or sy ~= 1 or sz ~= 1 then
node.scale = { sx, sy, sz }
end
table.insert(scene.nodes, node)
local index = #scene.nodes
for _, sub in Chunks.walk(buf, r.pos, r.limit, LAYOUT) do
if failure then
break
end
local id = sub.id
if id == "NODE" then
local child = readNode(sub, depth + 1)
if child then
table.insert(node.children, child)
end
elseif id == "MESH" and not node.mesh then
node.mesh = readMesh(body(sub), index)
elseif id == "BONE" then
readBone(body(sub), index)
elseif id == "KEYS" then
readKeys(body(sub), index)
elseif id == "ANIM" then
local ar = body(sub)
local flags, frames, fps = ar:i32le(), ar:i32le(), ar:f32le()
if not ar.err and not anim then
anim = { flags = flags, frames = frames, fps = if fps > 0 and fps < 1e6 then fps else 60 }
end
end
end
return index
end
for _, c in Chunks.walk(buf, hr.pos, head.offset + head.size, LAYOUT) do
if failure then
break
end
if c.id == "TEXS" then
readTexs(body(c))
elseif c.id == "BRUS" then
readBrus(body(c))
elseif c.id == "NODE" then
local n = readNode(c, 1)
if n then
table.insert(scene.roots, n)
end
end
end
if failure then
return nil, failure, failKind
end
if #scene.nodes == 0 then
return nil, "no NODE chunk", nil
end
-- ------------------------------------------------------------------------------------------ skins
local parent: { [number]: number } = {}
for i, n in scene.nodes do
for _, ch in n.children do
parent[ch] = i
end
end
local worldCache: { [number]: { number } } = {}
local function world(i: number): { number }
local w = worldCache[i]
if not w then
local n = scene.nodes[i]
local l = Mat4.compose(n.translation, n.rotation, n.scale)
w = if parent[i] then Mat4.mul(world(parent[i]), l) else l
worldCache[i] = w
end
return w
end
local bonesOf: { [MeshRec]: { Bone } } = {}
for _, b in bones do
local m = b.target
if m then
local l = bonesOf[m] or {}
bonesOf[m] = l
table.insert(l, b)
end
end
for _, rec in meshes do
local list = bonesOf[rec]
if list then
local nv = rec.count
local inf: { { number } } = {}
local joints: { number } = {}
for j, b in list do
joints[j] = b.node
local l = b.list
for k = 1, #l, 2 do
local v, w = l[k], l[k + 1]
if v >= 0 and v < nv and w > 0 and w == w then
local e = inf[v + 1]
if not e then
e = {}
inf[v + 1] = e
end
table.insert(e, j - 1)
table.insert(e, w)
end
end
end
local self: number? = nil -- the mesh node as a joint, for vertices no bone moves
local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16)
for v = 0, nv - 1 do
local e = inf[v + 1]
if not e then
if not self then
table.insert(joints, rec.node)
self = #joints - 1
end
buffer.writeu16(jb, v * 8, self :: number)
buffer.writef32(wb, v * 16, 1)
else
-- the 4 strongest, normalised
local order = {}
for k = 1, #e, 2 do
table.insert(order, k)
end
table.sort(order, function(a: number, b: number): boolean
return e[a + 1] > e[b + 1]
end)
local sum = 0
for k = 1, math.min(4, #order) do
sum += e[order[k] + 1]
end
for k = 1, math.min(4, #order) do
buffer.writeu16(jb, v * 8 + (k - 1) * 2, e[order[k]])
buffer.writef32(wb, v * 16 + (k - 1) * 4, e[order[k] + 1] / sum)
end
end
end
local meshWorld = world(rec.node)
local ibm = buffer.create(#joints * 64)
for j, ni in joints do
local inv = Mat4.inverse(world(ni)) or Mat4.identity()
local m = Mat4.mul(inv, meshWorld)
for k = 1, 16 do
buffer.writef32(ibm, (j - 1) * 64 + (k - 1) * 4, m[k])
end
end
local ia = Types.Scene.accessor(ibm, "f32", 16, #joints)
ia.matrix = true
table.insert(scene.skins, { joints = joints, inverseBindMatrices = ia })
scene.nodes[rec.node].skin = #scene.skins
local J, W = Types.Scene.accessor(jb, "u16", 4, nv), Types.Scene.accessor(wb, "f32", 4, nv)
for _, prim in scene.meshes[rec.mesh].primitives do
prim.attributes.JOINTS_0 = J
prim.attributes.WEIGHTS_0 = W
end
end
end
-- ------------------------------------------------------------------------------------------ animation
local fps = if anim then anim.fps else 60
local channels: { Types.Channel } = {}
for ni = 1, #scene.nodes do
local k = nodeKeys[ni]
if k then
for _, path in { "translation", "rotation", "scale" } do
local map = if path == "translation" then k.t elseif path == "rotation" then k.r else k.s
local frames = {}
for f in map do
table.insert(frames, f)
end
if #frames > 0 then
table.sort(frames)
local nc = if path == "rotation" then 4 else 3
local input, output = buffer.create(#frames * 4), buffer.create(#frames * nc * 4)
for i, f in frames do
buffer.writef32(input, (i - 1) * 4, f / fps)
local v = map[f]
for c = 1, nc do
buffer.writef32(output, ((i - 1) * nc + c - 1) * 4, v[c])
end
end
table.insert(channels, {
node = ni,
path = path :: any,
input = Types.Scene.accessor(input, "f32", 1, #frames),
output = Types.Scene.accessor(output, "f32", nc, #frames),
interpolation = "LINEAR" :: "LINEAR",
})
end
end
end
end
if #channels > 0 then
table.insert(scene.animations, { name = "b3d", channels = channels })
end
scene.meta.up = "y"
scene.meta.source = {
format = "b3d",
version = version,
brushes = #brushes,
frames = if anim then anim.frames else nil,
fps = if anim then anim.fps else nil,
handedness = "left", -- converted: z mirrored, winding reversed
}
return scene, nil, nil
end
return Read
+68
View File
@@ -0,0 +1,68 @@
--!strict
-- model/b3d: Blitz3D .b3d (BB3D chunk format, version 1), read. Written from the Blitz3D file format description
-- (blitzbasic.com "b3dfile_specs.txt") and checked against assimp's B3D importer.
-- Reads: TEXS (texture files -> scene.textures, data through opts.files / opts.resolve, clamp flags -> sampler,
-- position / scale / rotation -> the first texture's KHR_texture_transform, flag 65536 = second UV set), BRUS (brushes ->
-- materials: colour + alpha, shininess -> roughness, FX 1 = unlit, 16 = double sided, 32 = blend; the first texture is
-- baseColorTexture, the others are listed in extras.b3d.textures; texture flags 2 / 4 -> blend / mask), the NODE tree
-- (name, position, scale, rotation; MESH -> one Mesh per node: VRTS -> POSITION / NORMAL / COLOR_0 (f32 RGBA) /
-- TEXCOORD_0..7 shared by the mesh's primitives, one "triangles" primitive per TRIS chunk with its brush, else the
-- mesh's master brush), BONE vertex weights -> a skin on the mesh read last before the bone (the 4 strongest weights
-- per vertex, normalised, JOINTS_0 / WEIGHTS_0; vertices no bone moves follow the mesh node, which then joins the
-- joints; inverse bind matrices from the bind pose), KEYS (position / scale / rotation keys) + ANIM (frames, fps,
-- default 60) -> one animation of LINEAR channels at frame / fps seconds.
-- Blitz3D is left-handed and Y up: z is mirrored (positions, normals, translations, keys), the triangle winding
-- reversed and the rotations mirrored, so the scene is glTF's right-handed Y up (meta.up = "y"). UVs keep their
-- top-left origin (= glTF). meta.source = { format, version, brushes, frames?, fps?, handedness = "left" }.
-- Not supported: writing; multiple VRTS chunks in one MESH (the first is used); per-brush blend modes beyond the
-- extras; texture coordinate sets of 3 / 4 components keep their first two.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Read = require("@formats/model/b3d/Read")
-- ------------------------------------------------------------------------------------------------ contract
local B3d = {
name = "b3d",
category = "model",
extensions = { "b3d" },
mime = { "model/x-b3d" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/model/Mat4" },
caps = { decode = true, encode = false, materials = true, textures = true, skins = true, animation = true, colors = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
resolve: ((uri: string) -> any)?, -- texture files (the api sets it for paths)
files: { [string]: any }?, -- or: the files by name
maxVertices: number?, -- default 2^24
maxDepth: number?, -- node nesting (default 256)
}
-- ------------------------------------------------------------------------------------------------ sniff
function B3d.sniff(r: Bytes.Reader): number
if r:peek(4) == "BB3D" then
return if r:peek(4, 8) ~= "" then 1 else 0.8
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function B3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
if r:peek(4) ~= "BB3D" then
return nil, Err.new(Err.CORRUPT, "no BB3D chunk")
end
-- the scene builder is plain (not native) code: a bug there must not escape as an error
local ok, scene, msg, kind = pcall(Read.scene, r, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "bad chunk tree: " .. tostring(scene))
end
if not scene then
return nil, Err.from(msg, nil, kind)
end
return scene, nil
end
return B3d
+230
View File
@@ -0,0 +1,230 @@
-- model/b3d tests: assimp's Blitz3D models (WusonBlitz, dwarf2, turtle1) and generated files (textures, brushes,
-- vertex colours, two UV sets, nested rotated / scaled / mirrored nodes, pivots, master brushes, bones, keys + ANIM)
-- against assimp (meshes, faces, materials, animations, channels, bones; world bounds, triangle area and signed
-- volume from its PreTransformVertices export: the left- to right-handed conversion and the winding) and the counts
-- the generator wrote; the skin's bind pose; error codes; the fuzz no-throw pass. Fixtures: tools/fixtures/b3d.py.
local T = require("@tests/T")
local B3d = require("@formats/model/b3d")
local MeshOps = require("@formats/ops/MeshOps")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Cases = require("@tests/gen/b3d_cases")
local t = T.suite("b3d")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return B3d.decode(Bytes.reader(b), opts)
end
t:eq(B3d.name, "b3d", "name")
t:eq(B3d.category, "model", "category")
t:check(B3d.caps.decode and not B3d.caps.encode, "caps")
t:eq(B3d.sniff(Bytes.reader(buffer.fromstring("BB3D\0\0\0\0\1\0\0\0"))), 1, "sniff")
t:eq(B3d.sniff(Bytes.reader(buffer.fromstring("BX3D\0\0\0\0\1\0\0\0"))), 0, "sniff other")
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
-- world triangles of the merged scene: area and signed volume
local function measure(prim: any): (number, number)
local get = assert(Types.Scene.reader(prim.attributes.POSITION))
local idx = prim.indices and Types.Scene.reader(prim.indices)
local n = if idx then prim.indices.count else prim.attributes.POSITION.count
local area, vol = 0, 0
for k = 0, n // 3 - 1 do
local i0, i1, i2 = 3 * k, 3 * k + 1, 3 * k + 2
if idx then
i0, i1, i2 = idx(i0, 0), idx(i1, 0), idx(i2, 0)
end
local ax, ay, az = get(i0, 0), get(i0, 1), get(i0, 2)
local bx, by, bz = get(i1, 0), get(i1, 1), get(i1, 2)
local cx, cy, cz = get(i2, 0), get(i2, 1), get(i2, 2)
local ux, uy, uz, vx, vy, vz = bx - ax, by - ay, bz - az, cx - ax, cy - ay, cz - az
local x, y, z = uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx
area += math.sqrt(x * x + y * y + z * z) / 2
vol += (ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx) + az * (bx * cy - by * cx)) / 6
end
return area, vol
end
-- assimp's bone count: per primitive, the joints that weight one of its vertices (not the mesh node's own joint)
local function boneCount(scene: any): number
local n = 0
for ni, node in scene.nodes do
if node.mesh and node.skin then
local skin = scene.skins[node.skin]
for _, p in scene.meshes[node.mesh].primitives do
local J, W = Types.Scene.reader(p.attributes.JOINTS_0), Types.Scene.reader(p.attributes.WEIGHTS_0)
local idx = assert(Types.Scene.reader(p.indices))
local seen = {}
for i = 0, p.indices.count - 1 do
local v = idx(i, 0)
for k = 0, 3 do
local j = (J :: any)(v, k)
if (W :: any)(v, k) > 0 and skin.joints[j + 1] ~= ni and not seen[j] then
seen[j] = true
n += 1
end
end
end
end
end
end
return n
end
-- ------------------------------------------------------------------------------------------------ cases
local samples = {}
for _, c in Cases do
local scene, err = decode(c.data, { files = c.files })
local a = c.assimp
t:check(scene, c.name .. ": decode: " .. tostring(err))
if scene and not a.failed then
local prims, faces = 0, 0
for _, pl in Types.Scene.flatten(scene) do
prims += 1
faces += pl.primitive.indices.count // 3
end
t:eq(prims, a.meshes, c.name .. ": meshes (assimp)")
t:eq(faces, a.faces, c.name .. ": faces (assimp)")
t:eq(math.max(1, scene.meta.source.brushes), a.materials, c.name .. ": materials (assimp)")
t:eq(#scene.animations, a.animations, c.name .. ": animations (assimp)")
local animated = {}
local nAnimated = 0
for _, anim in scene.animations do
for _, ch in anim.channels do
if not animated[ch.node] then
animated[ch.node] = true
nAnimated += 1
end
end
end
if a.animations > 0 then
t:eq(nAnimated, a.animation_channels, c.name .. ": animated nodes (assimp)")
end
t:eq(boneCount(scene), a.bones, c.name .. ": bones (assimp)")
local merged = assert(MeshOps.merge(scene))
local lo, hi = MeshOps.bounds(merged)
local ok = lo ~= nil
for k = 1, 3 do
ok = ok and near((lo :: any)[k], a.min[k], 1e-4) and near((hi :: any)[k], a.max[k], 1e-4)
end
t:check(ok, string.format("%s: world bounds (assimp) %s / %s", c.name, table.concat(lo or {}, " "), table.concat(hi or {}, " ")))
local area, vol = measure(merged)
t:check(near(area, a.area, 1e-4), string.format("%s: area %.6g (assimp %.6g)", c.name, area, a.area))
-- (a mirrored node: glTF turns its faces back, assimp's PreTransformVertices does not; skip the volume there)
if not (c.want and c.want.mirrored) then
t:check(near(vol, a.volume, 1e-3), string.format("%s: signed volume %.6g (assimp %.6g)", c.name, vol, a.volume))
end
-- textures resolved through files
for _, tex in scene.textures do
local base = string.match(tex.uri, "([^/\\]+)$")
t:check((tex.data ~= nil) == (c.files[base] ~= nil), c.name .. ": texture data " .. tostring(tex.uri))
end
local w = c.want
if w then
local nv, nt = 0, 0
for _, m in scene.meshes do
nv += m.primitives[1].attributes.POSITION.count
for _, p in m.primitives do
nt += p.indices.count // 3
end
end
t:eq(nv, w.vertices, c.name .. ": vertices")
t:eq(nt, w.triangles, c.name .. ": triangles")
t:eq(#scene.textures, w.textures, c.name .. ": textures")
t:eq(#scene.materials, w.materials, c.name .. ": materials")
t:eq(#scene.nodes, w.nodes, c.name .. ": nodes")
local attrs = scene.meshes[1].primitives[1].attributes
t:eq(attrs.COLOR_0 ~= nil, w.colors, c.name .. ": COLOR_0")
local sets = 0
while attrs["TEXCOORD_" .. sets] do
sets += 1
end
t:eq(sets, w.uvSets, c.name .. ": uv sets")
if w.joints then
t:eq(#scene.skins, 1, c.name .. ": one skin")
t:eq(#scene.skins[1].joints, w.joints, c.name .. ": joints")
t:eq(#scene.animations[1].channels, w.channels, c.name .. ": channels")
t:eq(scene.meta.source.fps, w.fps, c.name .. ": fps")
t:eq(scene.meta.source.frames, w.frames, c.name .. ": frames")
end
end
if c.name == "gen/textured" then
local m1, m2 = scene.materials[1], scene.materials[2]
t:check(m1.name == "red" and m1.baseColorTexture and m1.baseColorTexture.texture == 1, "textured: brush texture")
local tr = m1.baseColorTexture and m1.baseColorTexture.transform
t:check(tr and tr.offset[1] == 0.25 and tr.scale[2] == 3 and tr.rotation == 0.5, "textured: texture transform")
t:check(m1.extras.b3d.textures[2] == 2, "textured: second brush texture in extras")
t:check(m2.name == "glass" and m2.alphaMode == "blend" and m2.doubleSided and m2.extensions.KHR_materials_unlit, "textured: alpha, FX")
t:check(m2.baseColorTexture and m2.baseColorTexture.texCoord == 1, "textured: second UV set flag")
t:check(scene.textures[2].sampler and scene.textures[2].sampler.wrapS == "clamp", "textured: clamp")
end
-- the bind pose: skinning the vertices with the inverse bind matrices gives the static placement
for ni, node in scene.nodes do
if node.skin then
local skin = scene.skins[node.skin]
local worlds = {}
for _, pl in Types.Scene.flatten(scene) do
worlds[pl.node] = pl.matrix
end
local ibm = assert(Types.Scene.reader(skin.inverseBindMatrices))
local function world(i: number): { number }
local parent
for pi, n in scene.nodes do
if table.find(n.children, i) then
parent = pi
end
end
local l = Types.Scene.nodeMatrix(scene.nodes[i])
return if parent then Types.Scene.mul(world(parent), l) else l
end
local maxErr = 0
local meshWorld = world(ni)
for j, jn in skin.joints do
local m = {}
for k = 1, 16 do
m[k] = ibm(j - 1, k - 1)
end
local jm = Types.Scene.mul(world(jn), m)
for k = 1, 16 do
maxErr = math.max(maxErr, math.abs(jm[k] - meshWorld[k]))
end
end
t:check(maxErr < 1e-3, c.name .. ": joint * inverse bind = the mesh's world matrix (" .. maxErr .. ")")
end
end
end
if #c.data < 100000 then
table.insert(samples, c.data)
end
end
-- ------------------------------------------------------------------------------------------------ errors
do
local _, e = decode("BB3D\4\0\0\0\1\0\0\0")
t:check(e and e.code == Err.CORRUPT, "no NODE: CORRUPT")
_, e = decode("BB3D\100\0\0\0\1\0\0\0")
t:check(e and e.code == Err.TRUNCATED, "short BB3D: TRUNCATED")
_, e = decode("RIFF\0\0\0\0")
t:check(e and e.code == Err.CORRUPT, "not B3D: CORRUPT")
local s = Cases[#Cases].data
local _, e2 = decode(string.sub(s, 1, #s - 7))
t:check(e2 and e2.code == Err.TRUNCATED, "truncated file: TRUNCATED (" .. tostring(e2) .. ")")
local _, e3 = decode(s, { maxVertices = 4 })
t:check(e3 and e3.code == Err.LIMIT, "maxVertices: LIMIT")
end
-- ------------------------------------------------------------------------------------------------ fuzz
t:fuzz("decode", function(b: buffer)
local s = B3d.decode(Bytes.reader(b))
if s then
MeshOps.merge(s)
end
return s
end, samples, { mutations = 16, keepHeader = 4 })
t:done()
+204
View File
@@ -0,0 +1,204 @@
# B3D fixtures (tools/fixtures.py): assimp's Blitz3D test models (WusonBlitz, dwarf2, turtle1: read from the nixpkgs
# assimp source, never committed; their textures next to them go into `files`) and B3D files written here (textures
# with transforms and clamp flags, brushes with alpha / FX, vertex colours, two UV sets, nested rotated / scaled nodes,
# pivots, master brushes, bones with weights, KEYS + ANIM), with reference values from assimp: `assimp info -r`
# (meshes, faces, materials, animations, channels, bones) and its PreTransformVertices OBJ export (world bounds,
# triangle area, signed volume: the handedness conversion and winding), plus the counts the generator wrote.
# tests/gen/b3d_cases.luau { name, data, files = { name -> bytes }, assimp = {...}, want? = {...} }
import importlib.util, math, os, re, struct, subprocess
INPUTS = ["tools/fixtures/_model_ref.py"]
def ref_module(ctx):
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def assimp_src():
out = subprocess.run(["nix", "build", "nixpkgs#assimp.src", "--no-link", "--print-out-paths"], capture_output=True, check=True)
return out.stdout.decode().strip().split("\n")[-1]
# ---------------------------------------------------------------------------------------------------- B3D writer
def chunk(tag, *parts):
body = b"".join(parts)
return tag.encode() + struct.pack("<I", len(body)) + body
def cstr(s):
return s.encode() + b"\0"
def f32(*v):
return struct.pack("<%df" % len(v), *v)
def i32(*v):
return struct.pack("<%di" % len(v), *v)
def quat_axis(ax, ay, az, deg):
# Blitz3D order: w, x, y, z
l = math.sqrt(ax * ax + ay * ay + az * az)
h = math.radians(deg) / 2
s = math.sin(h) / l
return (math.cos(h), ax * s, ay * s, az * s)
def node(name, pos=(0, 0, 0), scale=(1, 1, 1), rot=(1, 0, 0, 0), *children):
return chunk("NODE", cstr(name), f32(*pos), f32(*scale), f32(*rot), *children)
def box_mesh(sx, sy, sz, flags=0, sets=1, size=2, brushes=(-1,), master=-1):
# 8 corners, 12 triangles; split between the brushes round-robin by face
verts = []
for i in range(8):
x, y, z = (sx if i & 1 else -sx), (sy if i & 2 else -sy), (sz if i & 4 else -sz)
v = f32(x, y, z)
if flags & 1:
l = math.sqrt(x * x + y * y + z * z)
v += f32(x / l, y / l, z / l)
if flags & 2:
v += f32((i & 1) * 1.0, ((i >> 1) & 1) * 1.0, ((i >> 2) & 1) * 1.0, 1.0)
for s in range(sets):
v += f32(*[(i * 0.1 + s + k * 0.5) for k in range(size)])
verts.append(v)
# Blitz3D front faces are clockwise seen from outside (left-handed, Direct3D culling)
quads = [(0, 2, 3, 1), (4, 5, 7, 6), (0, 1, 5, 4), (2, 6, 7, 3), (0, 4, 6, 2), (1, 3, 7, 5)]
tris = []
for a, b, c, d in quads:
tris += [(a, b, c), (a, c, d)]
tchunks = []
for k, br in enumerate(brushes):
mine = [t for j, t in enumerate(tris) if j % len(brushes) == k]
tchunks.append(chunk("TRIS", i32(br), b"".join(i32(*t) for t in mine)))
return chunk("MESH", i32(master), chunk("VRTS", i32(flags, sets, size), b"".join(verts)), *tchunks), 8, 12
def textured():
texs = chunk("TEXS", cstr("tex/a.png"), i32(1, 2), f32(0.25, 0.5), f32(2, 3), f32(0.5),
cstr("b.png"), i32(1 | 16 | 32 | 65536, 2), f32(0, 0), f32(1, 1), f32(0))
brus = chunk("BRUS", i32(2),
cstr("red"), f32(1, 0, 0, 1), f32(0.5), i32(1, 0), i32(0, 1),
cstr("glass"), f32(0.2, 0.4, 1, 0.5), f32(0), i32(1, 16 | 1), i32(1, -1))
m1, _, _ = box_mesh(1, 2, 3, flags=3, sets=2, size=2, brushes=(0, 1))
m2, _, _ = box_mesh(0.5, 0.5, 0.5, flags=1, sets=1, size=2, brushes=(-1,), master=1)
child = node("child", (3, 1, -2), (1, 2, 1), quat_axis(0, 1, 1, 50), m2)
root = node("root", (1, 2, 3), (2, 1, 0.5), quat_axis(1, 1, 0, 30), m1, child)
data = chunk("BB3D", i32(1), texs, brus, root)
return data, {"vertices": 16, "triangles": 24, "textures": 2, "materials": 2, "colors": True, "uvSets": 2, "nodes": 2}
def pivots():
m1, _, _ = box_mesh(1, 1, 1, brushes=(-1,))
m2, _, _ = box_mesh(2, 0.5, 1, sets=0, brushes=(-1,))
a = node("a", (5, 0, 0), (1, 1, 1), quat_axis(0, 0, 1, 90), m1)
b = node("b", (0, 0, 5), (-1, 1, 1), quat_axis(0, 1, 0, -45), m2)
pivot = node("pivot", (0, 3, 0), (1, 1, 1), quat_axis(1, 0, 0, 20), a, b)
data = chunk("BB3D", i32(1), node("top", (0, 0, 0), (1, 1, 1), (1, 0, 0, 0), pivot))
return data, {"vertices": 16, "triangles": 24, "textures": 0, "materials": 0, "colors": False, "uvSets": 1, "nodes": 4, "mirrored": True}
def skinned():
# a bar along y: 3 rings of 4 vertices; two bones (nested), each weighting rings; keys on both bones
verts, tris = [], []
for ring in range(3):
for k in range(4):
a = math.radians(90 * k)
verts.append(f32(math.cos(a), ring * 2.0, math.sin(a)))
for ring in range(2):
for k in range(4):
a, b = ring * 4 + k, ring * 4 + (k + 1) % 4
tris += [(a, b + 4, b), (a, a + 4, b + 4)]
mesh = chunk("MESH", i32(-1), chunk("VRTS", i32(0, 0, 0), b"".join(verts)), chunk("TRIS", i32(-1), b"".join(i32(*t) for t in tris)))
w1 = b"".join(i32(v) + f32(1.0 if v < 4 else 0.5) for v in range(8))
w2 = b"".join(i32(v) + f32(0.5 if v < 8 else 1.0) for v in range(4, 12))
keys1 = chunk("KEYS", i32(4), *[i32(f) + f32(*quat_axis(0, 0, 1, f * 10)) for f in (1, 5, 10)])
keys2 = chunk("KEYS", i32(1 | 2), *[i32(f) + f32(0, 2 + f * 0.1, 0) + f32(1, 1 + f * 0.05, 1) for f in (1, 10)])
bone2 = node("bone2", (0, 2, 0), (1, 1, 1), (1, 0, 0, 0), chunk("BONE", w2), keys2)
bone1 = node("bone1", (0, 0, 0), (1, 1, 1), (1, 0, 0, 0), chunk("BONE", w1), keys1, bone2)
root = node("body", (0, 1, 0), (1, 1, 1), quat_axis(0, 1, 0, 15), mesh, bone1, chunk("ANIM", i32(0, 10), f32(25)))
data = chunk("BB3D", i32(1), root)
return data, {"vertices": 12, "triangles": 16, "textures": 0, "materials": 0, "colors": False, "uvSets": 0, "nodes": 3,
"joints": 2, "channels": 3, "fps": 25.0, "frames": 10}
# ---------------------------------------------------------------------------------------------------- references
def info(ctx, path):
try:
txt = ctx.nix("assimp", ["assimp", "info", path, "-r"]).decode("utf-8", "replace")
except subprocess.CalledProcessError:
return {"failed": True}
out = {}
for label in ("Meshes", "Materials", "Faces", "Vertices", "Animations", "Bones", "Animation Channels", "Nodes"):
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
out[label.lower().replace(" ", "_")] = int(m.group(1)) if m else -1
return out
def ptv(ctx, path, tmp):
# world-space triangles from assimp's PreTransformVertices OBJ export: bounds, area, signed volume
out = os.path.join(tmp, "ptv.obj")
ctx.nix("assimp", ["assimp", "export", path, out, "-ptv"])
vs, area, vol = [], 0.0, 0.0
lo, hi = [1e30] * 3, [-1e30] * 3
with open(out) as f:
for line in f:
p = line.split()
if not p:
continue
if p[0] == "v":
v = [float(x) for x in p[1:4]]
vs.append(v)
lo = [min(a, b) for a, b in zip(lo, v)]
hi = [max(a, b) for a, b in zip(hi, v)]
elif p[0] == "f":
idx = [int(x.split("/")[0]) for x in p[1:]]
idx = [i - 1 if i > 0 else len(vs) + i for i in idx]
for k in range(1, len(idx) - 1):
a, b, c = vs[idx[0]], vs[idx[k]], vs[idx[k + 1]]
e1 = [b[j] - a[j] for j in range(3)]
e2 = [c[j] - a[j] for j in range(3)]
cr = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]
area += math.sqrt(sum(x * x for x in cr)) / 2
vol += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6
os.remove(out)
return {"min": lo, "max": hi, "area": area, "volume": vol}
def generate(ctx):
M = ref_module(ctx)
tmp = M.tempdir()
cases = []
src = assimp_src()
for rel in ("models/B3D/WusonBlitz.b3d", "models-nonbsd/B3D/dwarf2.b3d", "models-nonbsd/B3D/turtle1.b3d"):
p = os.path.join(src, "test", rel)
if not os.path.exists(p):
continue
d = os.path.dirname(p)
files = {f: open(os.path.join(d, f), "rb").read() for f in sorted(os.listdir(d))
if f.lower().endswith((".png", ".jpg")) and os.path.getsize(os.path.join(d, f)) < 300000}
cases.append({"name": "assimp/" + rel, "path": p, "files": files})
for name, fn in (("textured", textured), ("pivots", pivots), ("skinned", skinned)):
data, want = fn()
p = os.path.join(tmp, name + ".b3d")
with open(p, "wb") as f:
f.write(data)
files = {"a.png": M_PNG, "b.png": M_PNG} if name == "textured" else {}
cases.append({"name": "gen/" + name, "path": p, "files": files, "want": want})
for c in cases:
a = info(ctx, c["path"])
if not a.get("failed"):
a.update(ptv(ctx, c["path"], tmp))
c["assimp"] = a
c["data"] = open(c["path"], "rb").read()
del c["path"]
ctx.emit("b3d_cases", cases)
# a 1x1 PNG (texture data for the generated files)
M_PNG = bytes.fromhex("89504e470d0a1a0a0000000d4948445200000001000000010806000000"
"1f15c4890000000d49444154789c63f8cfc0f01f0005000201a2b3d6bd0000000049454e44ae426082")