-- 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 Anim = require("@rosetta/model/blend/Anim") 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"), old = require("@tests/gen/blend_old"), -- Blender 1.66 - 2.04 demo files (big-endian among them) } 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 -- rig values against bpy: numbers within eps, lists element by element, "" in the reference for nil local function same(got: any, want: any, eps: number): boolean if want == "" and got == nil then return true end if type(want) == "number" then return type(got) == "number" and near(got, want, eps) end if type(want) == "table" then if type(got) ~= "table" or #got ~= #want then return false end for i = 1, #want do if not same(got[i], want[i], eps) then return false end end return true end return got == want end -- custom properties: tables key by key (arrays element by element), numbers within 1e-5 local function deepSame(got: any, want: any): boolean if type(want) == "table" then if type(got) ~= "table" then return false end for k, v in want do if not deepSame(got[k], v) then return false end end for k in got do if want[k] == nil then return false end end return true end if type(want) == "number" then return type(got) == "number" and near(got, want, 1e-5) end return got == want end local DRIVEN = {} -- a reference value bpy evaluated through a driver: not compared local function angleNear(a: number?, b: number, eps: number): boolean if not a then return false end local d = (a - b) % (2 * math.pi) return d < eps or 2 * math.pi - d < eps end local REQUIRED: { [string]: { string } } = { IK = { "chain_count", "pole_target", "pole_subtarget", "pole_angle", "use_tail", "use_stretch", "iterations", "weight" }, COPY_ROTATION = { "use_x", "use_y", "use_z", "invert_x", "invert_y", "invert_z", "mix_mode", "euler_order" }, COPY_LOCATION = { "use_x", "use_y", "use_z", "invert_x", "invert_y", "invert_z", "use_offset", "head_tail" }, COPY_SCALE = { "use_x", "use_y", "use_z", "use_offset", "power", "use_add", "use_make_uniform" }, COPY_TRANSFORMS = { "mix_mode", "head_tail" }, DAMPED_TRACK = { "track_axis", "head_tail" }, LIMIT_ROTATION = { "use_limit_x", "use_limit_y", "use_limit_z", "min_x", "max_x", "min_z", "max_z", "use_transform_limit", "use_legacy_behavior" }, LIMIT_LOCATION = { "use_min_x", "use_max_x", "use_min_z", "use_max_z", "min_x", "max_x", "min_z", "max_z", "use_transform_limit" }, CHILD_OF = { "inverse_matrix", "use_location_x", "use_rotation_y", "use_scale_x", "use_scale_z", "set_inverse_pending" }, ACTION = { "action", "transform_channel", "frame_start", "frame_end", "min", "max", "mix_mode", "use_bone_object_action", "use_eval_time", "eval_time" }, TRANSFORM = { "map_from", "map_to", "map_to_x_from", "map_to_y_from", "map_to_z_from", "use_motion_extrapolate", "from_rotation_mode", "to_euler_order", "mix_mode", "mix_mode_rot", "mix_mode_scale", "from_min_x", "from_max_z", "to_min_y", "to_max_x", "from_min_y_rot", "from_max_x_rot", "to_min_z_rot", "to_max_y_rot", "from_min_x_scale", "from_max_y_scale", "to_min_x_scale", "to_max_y_scale" }, STRETCH_TO = { "rest_length", "bulge", "volume", "keep_axis", "use_bulge_min", "use_bulge_max", "bulge_min", "bulge_max", "bulge_smooth" }, ARMATURE = { "use_deform_preserve_volume", "use_bone_envelopes", "use_current_location", "targets" }, FLOOR = { "floor_location", "offset", "use_rotation" }, LIMIT_DISTANCE = { "distance", "limit_mode" }, TRACK_TO = { "track_axis", "up_axis", "use_target_z" }, LOCKED_TRACK = { "track_axis", "lock_axis" }, } local BONE_KEYS = { "inherit_scale", "use_inherit_rotation", "use_local_location", "use_relative_parent", "bbone_segments", "bbone_x", "bbone_z", "bbone_easein", "bbone_easeout", "bbone_rollin", "bbone_rollout", "bbone_curveinx", "bbone_curveinz", "bbone_curveoutx", "bbone_curveoutz", "bbone_scalein", "bbone_scaleout", "bbone_handle_type_start", "bbone_handle_type_end", "bbone_custom_handle_start", "bbone_custom_handle_end", "use_endroll_as_inroll", "bbone_mapping_mode" } local COMMON = { "type", "name", "influence", "mute", "target", "subtarget", "owner_space", "target_space" } local checked = { graphs = 0, drivers = 0, props = 0, actions = 0, rigs = 0, constraints = 0, worlds = 0, meshes = 0, normals = 0, weights = 0, shapes = 0, frames = 0, skinned = 0, curves = 0, materials = 0, cameras = 0, lights = 0 } local samples = {} t:check(#Sets.old >= 4, "the old demo files were fetched (" .. #Sets.old .. ")") for _, tag in { "old", "279", "293", "35", "41", "cur" } do for _, c in Sets[tag] do local ref = c.ref local label = c.name 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 -- with the reference's constraints muted (the reader does not evaluate them: bone-parented objects follow -- the stored pose) local wantW = o.worldMuted or o.world t:check(nearList(W[i], wantW, 1e-4), label .. ": " .. o.name .. " world\n got " .. fmt(W[i]) .. "\n want " .. fmt(wantW)) local e = scene.nodes[i].extras.blend t:check((e.hide_viewport == true) == o.hide_viewport and (e.hide_render == true) == o.hide_render, label .. ": " .. o.name .. " hide flags") -- parenting and the modifier stack as the API names them if o.parent ~= "" and o.parent_type then t:eq(e.parent_type, o.parent_type, label .. ": " .. o.name .. " parent_type") t:eq(e.parent_bone or "", if o.parent_type == "BONE" then o.parent_bone else "", label .. ": " .. o.name .. " parent_bone") if o.parent_info and o.parent_info.matrix_parent_inverse then t:check(nearList(e.matrix_parent_inverse, o.parent_info.matrix_parent_inverse, 1e-5), label .. ": " .. o.name .. " matrix_parent_inverse") if string.sub(o.parent_type, 1, 6) == "VERTEX" then local want = table.move(o.parent_info.parent_vertices, 1, if o.parent_type == "VERTEX" then 1 else 3, 1, {}) t:check(same(e.parent_vertices, want, 0) and not e.parent_vertices_unresolved, label .. ": " .. o.name .. " parent_vertices") end end end -- Blender's versioning adds modifiers to old files (particle systems before 2.5, "Auto Smooth" before 4.1) local modsRef = {} for _, rm in o.modifier_info or {} do if not (src.version < 401 and rm.type == "NODES" and rm.name == "Auto Smooth") then table.insert(modsRef, rm) end end if o.modifier_info and src.version >= 250 then t:eq(#(e.modifiers or {}), #modsRef, label .. ": " .. o.name .. " modifiers") for k, rm in modsRef do local m = (e.modifiers or {})[k] or {} for key, want in rm do local got = m[key] if key == "object" and type(got) == "number" then got = scene.nodes[got].name end t:check(same(got, want, 0), label .. ": " .. o.name .. " modifier " .. rm.name .. " " .. key .. ": got " .. tostring(got) .. ", want " .. tostring(want)) end end end 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 } local facePrims = 0 for _, p in mesh.primitives do if p.mode ~= "lines" then tris += p.indices.count // 3 facePrims += 1 end 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(facePrims, (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 names = mesh.extras.targetNames or {} local keys = mesh.extras.blend.shape_keys or {} t:eq(#keys, #mi.shapes, label .. ": " .. o.name .. " extras.blend.shape_keys") t:eq(mesh.extras.blend.reference_key, mi.reference, label .. ": " .. o.name .. " reference key") local groupWeight = {} for v, list in mi.weights or {} do for _, g in list do groupWeight[g[1] .. "/" .. (v - 1)] = g[2] end end local driven = {} for _, d in o.shape_key_drivers or {} do driven[d.data_path] = true end for k, s in mi.shapes do local e = keys[k] or {} local valueDriven = driven['key_blocks["' .. s.name .. '"].value'] t:check(e.name == s.name and e.relative_key == s.relative and e.mute == s.mute and (e.vertex_group or "") == s.vertex_group and near(e.slider_min, s.slider_min, 1e-6) and near(e.slider_max, s.slider_max, 1e-6) and (o.shapeAction or valueDriven or near(e.value, s.value, 1e-6)), label .. ": " .. o.name .. " shape key " .. s.name .. " fields") end local ti = 0 local worst = 0 for k, s in mi.shapes do if k ~= refIndex then ti += 1 t:eq(names[ti], s.name, label .. ": " .. o.name .. " targetNames[" .. ti .. "]") if not o.shapeAction then -- animated values are checked per frame below t:check(near(mesh.weights[ti], if s.mute then 0 else s.value, 1e-6), label .. ": " .. o.name .. " " .. s.name .. " weight") end -- the delta from the relative key, times the key's vertex group weight local rel = refIndex for q, r in mi.shapes do if r.name == s.relative then rel = q end end for ci, cv in if mi.cornerVerts then cs else {} do local tgt = cv[1].targets and cv[1].targets[ti] local get = tgt and read(tgt.POSITION) local v = mi.cornerVerts[ci] for q = 1, 3 do local want = s.co[v * 3 + q] - mi.shapes[rel].co[v * 3 + q] if s.vertex_group ~= "" then want *= groupWeight[s.vertex_group .. "/" .. v] or 0 end 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 {} -- an input linked to no image: the exporter writes its own guess, the reader a neutral value (checked below) local linked = m.extras.blend.linked or {} t:check(linked.baseColor or nearList(m.baseColor, pbr.baseColorFactor or { 1, 1, 1, 1 }, 1e-5), label .. ": " .. m.name .. " base colour " .. fmt(m.baseColor)) t:check((linked.metallic or near(m.metallic, pbr.metallicFactor or 1, 1e-5)) and (linked.roughness or 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") -- the exporter writes a bump height map as the normal texture; the reader keeps it as extras.blend.bumpTexture t:eq(m.normalTexture ~= nil or m.extras.blend.bumpTexture ~= nil, g.normalTexture ~= nil, label .. ": " .. m.name .. " normal texture") -- images found through pass-through nodes, as the exporter finds them: base colour, and roughness as its -- metallic-roughness texture local function texName(ref: any): string? return ref and scene.textures[ref.texture] and scene.textures[ref.texture].name end local function glName(info: any): string? local tx = info and gl.textures and gl.textures[info.index + 1] local im = tx and tx.source and gl.images and gl.images[tx.source + 1] return im and im.name end if pbr.baseColorTexture and texName(m.baseColorTexture) then t:check(string.find(glName(pbr.baseColorTexture) or "", texName(m.baseColorTexture) :: string, 1, true) == 1, label .. ": " .. m.name .. " base colour image " .. tostring(texName(m.baseColorTexture)) .. " / " .. tostring(glName(pbr.baseColorTexture))) end t:eq(m.metallicRoughnessTexture ~= nil or m.extras.blend.roughnessTexture ~= nil or m.extras.blend.metallicTexture ~= nil, pbr.metallicRoughnessTexture ~= nil, label .. ": " .. m.name .. " metallic / roughness 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 -- the graph against bpy: the image each input reaches, the nodes passed, vertex colours, unresolved links for _, rm in ref.materials do if rm.name ~= m.name then continue end local KEYS = { ["Base Color"] = "baseColor", Roughness = "roughness", Metallic = "metallic", Normal = "normal", Alpha = "alpha", ["Emission Color"] = "emissive", Emission = "emissive" } local e = m.extras.blend for input, rg in rm.graph or {} do local key = KEYS[input] local what = label .. ": " .. m.name .. " " .. input local ref = if key == "baseColor" then m.baseColorTexture elseif key == "normal" then (m.normalTexture or e.bumpTexture) elseif key == "emissive" then m.emissiveTexture else e[key .. "Texture"] if rg.image then local tex = ref and scene.textures[ref.texture] t:check(tex and tex.name == rg.image.name, what .. " image " .. tostring(tex and tex.name) .. " / " .. rg.image.name) local viaKey = if key == "normal" and rg.linked == "ShaderNodeBump" then "bump" else key t:check(same((e.via or {})[viaKey] or {}, rg.via, 0), what .. " via") if key == "roughness" or key == "metallic" then t:eq(ref and ref.channel, if rg.output == "Alpha" then "A" else "R", what .. " channel") end if rg.image.tiles and tex then local tiles = tex.extras.blend.tiles or {} t:eq(#tiles, #rg.image.tiles, what .. " tiles") for q, rt in rg.image.tiles do local tile = tiles[q] or {} t:check(tile.number == rt.number and (tile.label or tostring(tile.number)) == rt.label, what .. " tile " .. rt.number) end t:eq(tex.uri, (string.gsub(rg.image.filepath, "^//", "")), what .. " uri with the token") t:check(tex.data and buffer.tostring(tex.data) == Files["udim.1001.png"], what .. " the first tile's bytes") end if rg.linked == "ShaderNodeBump" then t:check(near(e.bumpStrength, rg.strength, 1e-5) and near(e.bumpDistance, rg.distance, 1e-5), what .. " bump strength / distance") end elseif rg.vertexColor then t:eq(e.vertexColor, rg.vertexColor, what .. " vertex colour") else t:eq((e.linked or {})[key], rg["end"], what .. " flagged as linked") if key == "baseColor" then t:check(nearList({ m.baseColor[1], m.baseColor[2], m.baseColor[3] }, { 0.8, 0.8, 0.8 }, 1e-6), what .. " neutral grey") elseif key == "metallic" then t:eq(m.metallic, 0, what .. " neutral metallic") end end checked.graphs += 1 end end 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 not tex then continue -- not used by a node material (legacy texture slots, face images) elseif im.packed > 0 then t:check(tex.data and buffer.len(tex.data) == im.packed and (tag == "old" or tex.mime == "image/png"), label .. ": packed image " .. im.name) else t:eq(tex.uri, "outside.png", label .. ": external image uri") t:check(tex.data and buffer.len(tex.data) == #Files["outside.png"], label .. ": external image bytes through opts.files") end 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 local curves = false -- the exporter turns curves / text / surfaces / metaballs into meshes; we do not for _, o in ref.objects do curves = curves or o.type == "CURVE" or o.type == "FONT" or o.type == "SURFACE" or o.type == "META" end if gl.meshes and not curves then -- per instance (both sides share meshes differently) local want = 0 for _, n in gl.nodes or {} do if n.mesh then for _, p in gl.meshes[n.mesh + 1].primitives do want += gl.accessors[p.indices + 1].count // 3 end end end local got = 0 for _, n in scene.nodes do if n.mesh then for _, p in scene.meshes[n.mesh].primitives do if p.mode ~= "lines" then got += p.indices.count // 3 end end 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 saved pose (constraints muted in the reference) for key, want in ref.posedBones do local j = bones[string.match(key, "/(.+)$")] t:check(j and nearList(W[j], want, 1e-4), label .. ": bone " .. key) end -- rig data against bpy (Blender 5.x reads the old files through its versioning: layers and bone groups as -- collections, bone group colours as bone colours) local function nameOf(v: any): any return if type(v) == "number" then scene.nodes[v].name else v end local function compareTable(got: { [string]: any }, want: { [string]: any }, keys: { string }, what: string) for _, k in keys do if want[k] == nil and (k == "target" or k == "subtarget") then t:check(got[k] == nil, what .. ": no " .. k) continue end t:check(want[k] ~= nil, what .. ": the reference has " .. k) if want[k] == DRIVEN then continue end local g = got[k] if k == "target" or k == "pole_target" or k == "custom_shape" then g = nameOf(g) elseif k == "targets" and type(g) == "table" then local named = {} for i, x in g do named[i] = { target = nameOf(x.target), subtarget = x.subtarget, weight = x.weight } end local ok = #named == #want[k] for i, x in want[k] do local y = named[i] or {} ok = ok and y.target == x.target and (y.subtarget or "") == x.subtarget and near(y.weight or -1, x.weight, 1e-5) end t:check(ok, what .. " targets") continue end t:check(same(g, want[k], 1e-5), what .. " " .. k .. ": got " .. tostring(g) .. ", want " .. tostring(want[k])) end end local function compareColor(got: any, want: any, what: string) if want.palette == "DEFAULT" then t:check(got == nil, what .. ": default colour") else -- bpy's custom colours are the stored ones (zero for a theme set in 4.x); the reader gives the theme's local custom = want.palette == "CUSTOM" t:check(got and got.palette == want.palette and got.normal and (not custom or nearList(got.normal, want.normal, 1e-5) and nearList(got.select, want.select, 1e-5) and nearList(got.active, want.active, 1e-5)), what .. ": colour " .. want.palette) end end local function compareDrivers(got: { any }?, want: { any }, what: string) local list = got or {} t:eq(#list, #want, what .. " drivers") for k, rd in want do local d = list[k] or { keys = {}, modifiers = {}, driver = { variables = {} } } local w = what .. " driver " .. rd.data_path t:check(d.data_path == rd.data_path and d.array_index == rd.array_index and d.extrapolation == rd.extrapolation, w) t:eq(#d.keys, #rd.keys, w .. " keys") for q, rk in rd.keys do local ck = d.keys[q] or {} t:check(nearList(ck.co, rk.co, 1e-5) and ck.interpolation == rk.interpolation, w .. " key " .. q) end local dr, rr = d.driver or { variables = {} }, rd.driver t:check(dr.type == rr.type and dr.expression == rr.expression and dr.use_self == rr.use_self, w .. " type / expression / use_self: " .. tostring(dr.type) .. " " .. tostring(dr.expression) .. " " .. tostring(dr.use_self)) t:eq(#dr.variables, #rr.variables, w .. " variables") for q, rv in rr.variables do local v = dr.variables[q] or { targets = {} } t:check(v.name == rv.name and v.type == rv.type and #v.targets == #rv.targets, w .. " variable " .. rv.name) for i, rt in rv.targets do local tg = v.targets[i] or {} for _, key in { "id_type", "data_path", "bone_target", "transform_type", "transform_space", "rotation_mode", "context_property" } do t:check(tg[key] == rt[key], w .. " variable " .. rv.name .. " target " .. i .. " " .. key .. ": got " .. tostring(tg[key]) .. ", want " .. tostring(rt[key])) end t:check(same(nameOf(tg.id), rt.id, 0), w .. " variable " .. rv.name .. " target id") end end t:eq(#d.modifiers, #rd.modifiers, w .. " modifiers") for q, rm in rd.modifiers do local m = d.modifiers[q] or {} for key, rv in rm do if m[key] ~= nil or key == "type" then t:check(same(m[key], rv, 1e-5), w .. " modifier " .. rm.type .. " " .. key .. ": got " .. tostring(m[key]) .. ", want " .. tostring(rv)) end end end checked.drivers += 1 end end for _, o in ref.objects do local i = objects[o.name] if i and o.drivers then local e = scene.nodes[i].extras.blend t:check(deepSame(e.props or {}, o.props), label .. ": " .. o.name .. " props") compareDrivers(e.drivers, o.drivers, label .. ": " .. o.name) compareDrivers(e.data_drivers, o.data_drivers, label .. ": " .. o.name .. " data") local m = scene.nodes[i].mesh and scene.meshes[scene.nodes[i].mesh] compareDrivers(m and m.extras.blend.shape_key_drivers, o.shape_key_drivers, label .. ": " .. o.name .. " shape keys") checked.props += 1 end end local POSE_KEYS = { "custom_shape", "custom_shape_transform", "custom_shape_translation", "custom_shape_rotation_euler", "custom_shape_scale_xyz", "use_custom_shape_bone_size", "lock_location", "lock_rotation", "lock_rotation_w", "lock_rotations_4d", "lock_scale", "rotation_mode", "ik_stretch", "location", "rotation_quaternion", "rotation_euler", "rotation_axis_angle", "scale" } for _, a in { "x", "y", "z" } do for _, k in { "lock_ik_", "use_ik_limit_", "ik_min_", "ik_max_", "ik_stiffness_" } do table.insert(POSE_KEYS, k .. a) end end for armName, rig in ref.rigs or {} do local ae = scene.nodes[objects[armName]].extras.blend t:eq(#ae.bone_collections, #rig.collections, label .. ": " .. armName .. " bone collections") for k, c in rig.collections do local g = ae.bone_collections[k] or {} t:check(g.name == c.name and g.visible == c.visible and (g.parent or "") == c.parent, label .. ": collection " .. c.name) end for _, b in rig.bones do local e = scene.nodes[bones[b.name]].extras.blend local what = label .. ": bone " .. b.name t:check(e.deform == b.deform and e.use_connect == b.use_connect and e.show_wire == b.show_wire, what .. " flags") t:check(nearList(e.head_local, b.head_local, 1e-5) and nearList(e.tail_local, b.tail_local, 1e-5), what .. " head / tail") t:check(angleNear(e.roll, b.roll, 1e-4), what .. " roll " .. tostring(e.roll) .. " / " .. b.roll) t:check(same(e.collections, b.collections, 0), what .. " collections " .. table.concat(e.collections, ",") .. " / " .. table.concat(b.collections, ",")) compareColor(e.color, b.color, what) compareColor(e.pose_color, b.pose.color, what .. " pose") compareTable(e, b.pose, POSE_KEYS, what) local bk = {} for _, k in BONE_KEYS do if b.bone[k] ~= nil then table.insert(bk, k) end end compareTable(e, b.bone, bk, what) if b.pose.props then t:check(deepSame(e.props or {}, b.pose.props) and deepSame(e.bone_props or {}, b.pose.bone_props), what .. " props / bone_props") checked.props += 1 end t:eq(#e.constraints, #b.pose.constraints, what .. " constraints") for k, rc in b.pose.constraints do -- bpy reports driven settings as evaluated; the file keeps the last stored value rc = table.clone(rc) for _, o in ref.objects do if o.name == armName then for _, d in o.drivers or {} do local key = string.match(d.data_path, '^pose%.bones%["' .. b.name:gsub("%p", "%%%0") .. '"%]%.constraints%["' .. rc.name:gsub("%p", "%%%0") .. '"%]%.([%w_]+)$') if key then rc[key] = DRIVEN end end end end local c = e.constraints[k] or {} local keys = table.clone(COMMON) for _, x in REQUIRED[rc.type] or {} do table.insert(keys, x) end compareTable(c, rc, keys, what .. " constraint " .. rc.name) for key, v in c do -- everything else the reader gives, where bpy has it if rc[key] ~= nil and rc[key] ~= DRIVEN and type(v) ~= "table" and key ~= "target" and key ~= "pole_target" then t:check(same(v, rc[key], 1e-5), what .. " constraint " .. rc.name .. " " .. key .. ": got " .. tostring(v) .. ", want " .. tostring(rc[key])) end end checked.constraints += 1 end end checked.rigs += 1 end if next(ref.rigs or {}) then local mb = scene.meta.blend for k, cs in ref.themeBoneColors do local g = mb.bone_color_sets[k] t:check(g and nearList(g.normal, cs.normal, 1e-5) and nearList(g.select, cs.select, 1e-5) and nearList(g.active, cs.active, 1e-5), label .. ": theme bone colours " .. k) end -- every custom shape is a widget: a scene node, or a mesh outside the scene; edge-only widgets as lines local shapes = {} for _, rig in ref.rigs do for _, b in rig.bones do if b.pose.custom_shape ~= "" then shapes[b.pose.custom_shape] = true end end end for _, w in mb.widgets do t:check(shapes[w.name], label .. ": widget " .. w.name .. " is a custom shape") shapes[w.name] = nil t:check(w.node == nil or (scene.nodes[w.node].name == w.name and scene.nodes[w.node].extras.blend.widget == true), label .. ": widget node") local m = w.mesh and scene.meshes[w.mesh] local lines = 0 for _, p in m and m.primitives or {} do if p.mode == "lines" then lines += p.indices.count // 2 end end t:check(lines > 0, label .. ": widget " .. w.name .. " edges (" .. lines .. ")") end t:check(next(shapes) == nil, label .. ": every custom shape is listed") end -- every action, raw: frame range, f-curves, keyframe points (bpy's first layer / strip / channel bag) for name, ra in if src.version >= 250 then ref.allActions or {} else {} do -- older files: IPOs Blender converts on load local a = scene.meta.blend and scene.meta.blend.actions and scene.meta.blend.actions[name] t:check(a and nearList(a.frame_range, ra.frame_range, 1e-5), label .. ": action " .. name .. " frame range") if not a then continue end t:eq(#a.curves, #ra.curves, label .. ": action " .. name .. " curves") for k, rc in ra.curves do local c = a.curves[k] or { keys = {} } local what = label .. ": action " .. name .. " " .. rc.data_path .. "[" .. rc.array_index .. "]" t:check(c.data_path == rc.data_path and c.array_index == rc.array_index and c.extrapolation == rc.extrapolation, what) local bone, prop = string.match(rc.data_path, '^pose%.bones%["(.-)"%]%.([%w_]+)$') t:check(c.bone == bone and c.path == (prop or rc.data_path), what .. " bone / path") t:eq(#c.keys, #rc.keys, what .. " keys") for q, rk in rc.keys do local ck = c.keys[q] or {} t:check(nearList(ck.co, rk.co, 1e-5) and nearList(ck.handle_left, rk.handle_left, 1e-4) and nearList(ck.handle_right, rk.handle_right, 1e-4) and ck.interpolation == rk.interpolation and ck.easing == rk.easing, what .. " key " .. q) end checked.actions += 1 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")) if not curves and ob and not ob:has("adt") then curves = B.ipo(file, ob:deref("ipo", 0, "Ipo")) -- before 2.5 end curves = curves or {} for _, rc in refCurves do local p = rc.path if not (p == "location" or p == "scale" or string.find(p, "rotation") or string.find(p, "^delta_")) then continue -- only the transform curves are read end local cur = nil for _, x in curves do if x.path == rc.path and x.index == rc.index then 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 local animated = false -- transform or shape key curves (others, such as an object colour, are not read) for _, list in ref.actions do for _, rc in list do local p = rc.path animated = animated or p == "location" or p == "scale" or string.find(p, "rotation") ~= nil or string.find(p, "key_blocks") ~= nil end end t:check(#scene.animations > 0 or not animated, label .. ": animations") local caches = {} for _, p in ref.poses do local frame = p.frame if frame ~= math.floor(frame) or frame > 20 then continue end local time = (frame - (src.frameZero or src.frameStart)) / 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 = {} for _, o in ref.objects do if o.name == name then for k, s in o.mesh.shapes do if s.name ~= o.mesh.reference then table.insert(want, if s.mute then 0 else values[k]) end end end end -- pre-2.5 IPO bezier keys: Blender recomputes auto handles when converting them; we keep the stored ones local eps = if tag == "old" then 1e-2 else 1e-3 t:check(nearList(w, want, eps), label .. ": frame " .. frame .. " " .. name .. " shape values " .. fmt(w) .. " / " .. fmt(want)) end for name, want in p.skinned or {} do -- morph, then skin: sum of w * jointWorld * inverseBind * position 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 rigs, %d constraints, %d raw action curves, %d drivers, %d property sets, %d material inputs", checked.rigs, checked.constraints, checked.actions, checked.drivers, checked.props, checked.graphs) 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 -- compressed files: by content for model loads, by extension otherwise for _, c in Sets.cur do if string.find(c.name, "_z%.blend$") then local b = buffer.fromstring(c.data) local s = F.model.load(b) t:check(s and s.meta.source.compression == "zstd", "F.model.load of a zstd .blend") t:eq(F.detect(b, { name = "x.blend" }), "blend", "F.detect of a zstd .blend by name") end end for _, c in Sets["293"] do if string.find(c.name, "_z%.blend$") then local s = F.model.load(buffer.fromstring(c.data)) t:check(s and s.meta.source.compression == "gzip", "F.model.load of a gzip .blend") end end -- errors local function code(data: string): string? local s, e = decode(data) 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") for _, c in { { 'pose.bones["FK-RibCage"].constraints["ik_spine"].influence', "pose.bones", "FK-RibCage", 'constraints["ik_spine"].influence' }, { 'pose.bones["Arm.L"].location', "pose.bones", "Arm.L", "location" }, { 'key_blocks["Smile"].value', "key_blocks", "Smile", "value" }, { 'pose.bones["a\\"b"].scale', "pose.bones", 'a"b', "scale" }, { "location", nil, nil, "location" }, } do local kind, who, rest = Anim.split(c[1]) t:check(kind == c[2] and who == c[3] and rest == c[4], "split " .. c[1] .. ": " .. tostring(kind) .. " " .. tostring(who) .. " " .. rest) end t:fuzz("decode", function(b: buffer) return B.decode(Bytes.reader(b)) end, samples, { mutations = 24 }) t:done()