Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
test(motion): cover the rig solver and the software renderer
nirholas3361e24a531c
diff --git a/packages/motion/test/rig.test.js b/packages/motion/test/rig.test.jsnew file mode 100644index 000000000..8609eb827--- /dev/null+++ b/packages/motion/test/rig.test.js@@ -0,0 +1,325 @@+// The kinematics core, checked against the reference skeleton it is measured+// from. Every assertion here is an invariant a motion depends on: get any of+// them wrong and every clip the package emits is subtly broken in a way that+// only shows up as "the animation looks off" three layers downstream.++import { describe, it } from 'node:test';+import assert from 'node:assert/strict';++import {+ ANKLE_REST_HEIGHT,+ ARM_REACH,+ BODY_FORWARD,+ BODY_LEFT,+ BODY_UP,+ CANONICAL_BONES,+ LEG_LENGTH,+ SHOULDER_SPAN,+ STANDING_HIP_HEIGHT,+ boneLength,+ hasBone,+ parentOf,+ restPos,+} from '../src/rig/skeleton.js';+import { qAxisAngle, qMul, qRotate, vDot, vLen, vNorm, vSub } from '../src/rig/math.js';+import { restPose, blendPose } from '../src/rig/pose.js';+import {+ balanceError,+ centreOfMass,+ gazeDirection,+ shapeHand,+ solveArm,+ solveGaze,+ solveLeg,+ solveSpine,+ solveTurn,+} from '../src/rig/ik.js';+import { ANCHOR_NAMES, anchorPoint, bodyDirection } from '../src/rig/anchors.js';++const near = (a, b, tol, message) => assert.ok(Math.abs(a - b) <= tol, `${message ?? ''} expected ${a} within ${tol} of ${b}`);+const dist = (a, b) => vLen(vSub(a, b));++describe('the reference skeleton', () => {+ it('is a single connected tree rooted at the hips', () => {+ const roots = CANONICAL_BONES.filter((b) => parentOf(b) === null);+ assert.deepEqual(roots, ['Hips']);+ for (const bone of CANONICAL_BONES) {+ let node = bone;+ let hops = 0;+ while (parentOf(node)) {+ node = parentOf(node);+ assert.ok(++hops < 32, `${bone} does not reach the root`);+ }+ assert.equal(node, 'Hips');+ }+ });++ it('carries a full humanoid: spine, both arms, both legs, both hands', () => {+ for (const bone of ['Hips', 'Spine', 'Spine1', 'Spine2', 'Neck', 'Head']) assert.ok(hasBone(bone), bone);+ for (const side of ['Left', 'Right']) {+ for (const part of ['Shoulder', 'Arm', 'ForeArm', 'Hand', 'UpLeg', 'Leg', 'Foot', 'ToeBase']) {+ assert.ok(hasBone(`${side}${part}`), `${side}${part}`);+ }+ for (const finger of ['Index', 'Middle', 'Ring', 'Pinky', 'Thumb']) {+ for (const joint of [1, 2, 3]) assert.ok(hasBone(`${side}Hand${finger}${joint}`));+ }+ }+ });++ it('is mirror-symmetric across the body midline', () => {+ for (const bone of CANONICAL_BONES) {+ if (!bone.startsWith('Left')) continue;+ const mirror = `Right${bone.slice(4)}`;+ assert.ok(hasBone(mirror), `${bone} has no mirror`);+ const left = restPos(bone);+ const right = restPos(mirror);+ near(vDot(left, BODY_LEFT), -vDot(right, BODY_LEFT), 0.002, `${bone} lateral`);+ near(left[1], right[1], 0.002, `${bone} height`);+ }+ });++ it('reads its own body frame off the rig rather than assuming an axis', () => {+ near(vLen(BODY_FORWARD), 1, 1e-9);+ near(vLen(BODY_LEFT), 1, 1e-9);+ near(vDot(BODY_FORWARD, BODY_LEFT), 0, 1e-6, 'forward and left are perpendicular');+ // The rig's LeftArm must be on the side the frame calls left, or every+ // motion the package emits is mirrored.+ assert.ok(vDot(restPos('LeftArm'), BODY_LEFT) > 0, 'LeftArm is on the left');+ assert.ok(vDot(restPos('RightArm'), BODY_LEFT) < 0, 'RightArm is on the right');+ // The toes must point the way the body faces.+ const toe = vSub(restPos('LeftToeBase'), restPos('LeftFoot'));+ assert.ok(vDot(toe, BODY_FORWARD) > 0, 'toes point forward');+ });++ it('has plausible human proportions', () => {+ near(STANDING_HIP_HEIGHT, 0.98, 0.15, 'hip height');+ near(SHOULDER_SPAN, 0.41, 0.1, 'shoulder span');+ assert.ok(ARM_REACH > 0.4 && ARM_REACH < 0.75, `arm reach ${ARM_REACH}`);+ assert.ok(LEG_LENGTH > 0.7 && LEG_LENGTH < 1.0, `leg length ${LEG_LENGTH}`);+ assert.ok(ANKLE_REST_HEIGHT > 0.02 && ANKLE_REST_HEIGHT < 0.2, `ankle height ${ANKLE_REST_HEIGHT}`);+ // The upper and lower segments of a limb are close to the same length,+ // which is what makes two-bone IK well-conditioned.+ near(boneLength('LeftArm') / boneLength('LeftForeArm'), 1, 0.35, 'arm segment ratio');+ near(boneLength('LeftUpLeg') / boneLength('LeftLeg'), 1, 0.35, 'leg segment ratio');+ });+});++describe('forward kinematics', () => {+ it('reproduces the bind pose exactly when nothing is posed', () => {+ const pose = restPose();+ for (const bone of CANONICAL_BONES) {+ near(dist(pose.worldPos(bone), restPos(bone)), 0, 1e-9, bone);+ }+ });++ it('carries every descendant when the root moves', () => {+ const pose = restPose();+ pose.setRootOffset([0.1, -0.25, 0.4]);+ for (const bone of CANONICAL_BONES) {+ const moved = vSub(pose.worldPos(bone), restPos(bone));+ near(moved[0], 0.1, 1e-9, bone);+ near(moved[1], -0.25, 1e-9, bone);+ near(moved[2], 0.4, 1e-9, bone);+ }+ });++ it('keeps bone lengths fixed under any rotation', () => {+ const pose = restPose();+ pose.setLocal('Spine1', qMul(pose.getLocal('Spine1'), qAxisAngle([1, 0, 0], 35)));+ pose.setLocal('LeftArm', qMul(pose.getLocal('LeftArm'), qAxisAngle([0, 0, 1], -55)));+ for (const bone of CANONICAL_BONES) {+ const parent = parentOf(bone);+ if (!parent) continue;+ near(+ dist(pose.worldPos(bone), pose.worldPos(parent)),+ dist(restPos(bone), restPos(parent)),+ 1e-9,+ `${parent} to ${bone}`,+ );+ }+ });++ it('blends two poses without leaving the unit quaternion', () => {+ const a = restPose();+ const b = restPose();+ b.setLocal('Head', qAxisAngle([0, 1, 0], 60));+ b.setRootOffset([0, -0.2, 0]);+ for (const t of [0, 0.25, 0.5, 0.75, 1]) {+ const mid = blendPose(a, b, t);+ near(vLen([...mid.getLocal('Head')].slice(0, 3).concat(0)) ** 2 + mid.getLocal('Head')[3] ** 2, 1, 1e-9);+ near(mid.rootOffset[1], -0.2 * t, 1e-9);+ }+ });+});++describe('limb IK', () => {+ it('puts a wrist exactly on a reachable target', () => {+ const pose = restPose();+ for (const target of [[-0.15, 1.35, 0.3], [-0.3, 1.7, 0.1], [-0.2, 1.1, -0.15]]) {+ solveArm(pose, 'Right', { wrist: target });+ near(dist(pose.worldPos('RightHand'), target), 0, 1e-6, `target ${target}`);+ }+ });++ it('reproduces the rest leg when asked for the rest ankle', () => {+ const pose = restPose();+ for (const side of ['Left', 'Right']) {+ solveLeg(pose, side, { ankle: restPos(`${side}Foot`) });+ near(dist(pose.worldPos(`${side}Foot`), restPos(`${side}Foot`)), 0, 2e-3, `${side} ankle`);+ near(dist(pose.worldPos(`${side}ToeBase`), restPos(`${side}ToeBase`)), 0, 2e-3, `${side} toe`);+ }+ });++ it('keeps the feet planted while the hips drop, which is what a crouch is', () => {+ const pose = restPose();+ const ankles = { Left: restPos('LeftFoot'), Right: restPos('RightFoot') };+ pose.setRootOffset([0, -0.32, 0]);+ for (const side of ['Left', 'Right']) solveLeg(pose, side, { ankle: ankles[side] });+ for (const side of ['Left', 'Right']) {+ near(dist(pose.worldPos(`${side}Foot`), ankles[side]), 0, 1e-6, `${side} stayed planted`);+ }+ // The knee has to travel forward, or the leg folded the wrong way.+ const kneeTravel = vDot(vSub(pose.worldPos('LeftLeg'), restPos('LeftLeg')), BODY_FORWARD);+ assert.ok(kneeTravel > 0.05, `knee went forward by ${kneeTravel}`);+ });++ it('bends the elbow toward the pole it is given', () => {+ const target = [-0.2, 1.3, 0.28];+ const out = restPose();+ solveArm(out, 'Right', { wrist: target, pole: [-1, -0.2, -0.2] });+ const back = restPose();+ solveArm(back, 'Right', { wrist: target, pole: [0.2, -0.4, -1] });+ const elbowOut = vDot(out.worldPos('RightForeArm'), BODY_LEFT);+ const elbowBack = vDot(back.worldPos('RightForeArm'), BODY_LEFT);+ assert.ok(elbowOut < elbowBack, 'the outward pole puts the elbow further right');+ });++ it('clamps an unreachable target instead of stretching the arm', () => {+ const pose = restPose();+ solveArm(pose, 'Right', { wrist: [-3, 1.5, 3] });+ const reach = dist(pose.worldPos('RightHand'), pose.worldPos('RightArm'));+ assert.ok(reach <= ARM_REACH + 1e-6, `wrist stayed inside reach: ${reach}`);+ });++ it('lets the clavicle extend a long reach', () => {+ const far = [0.1, 0.55, 0.35];+ const assisted = restPose();+ solveArm(assisted, 'Left', { wrist: far });+ const bolted = restPose();+ solveArm(bolted, 'Left', { wrist: far, clavicle: false });+ assert.ok(+ dist(assisted.worldPos('LeftHand'), far) < dist(bolted.worldPos('LeftHand'), far),+ 'the shoulder girdle got the hand closer',+ );+ });+});++describe('spine, gaze, and hands', () => {+ it('shares a lean along the chain instead of hinging at one joint', () => {+ const pose = restPose();+ solveSpine(pose, { lean: 40 });+ const moved = ['Hips', 'Spine', 'Spine1', 'Spine2']+ .filter((b) => pose.local.has(b))+ .map((b) => vDot(vSub(pose.worldPos(b === 'Hips' ? 'Spine' : b), restPos(b === 'Hips' ? 'Spine' : b)), BODY_FORWARD));+ assert.equal(moved.length, 4);+ // The chest travels further than the waist: a spine, not a hinge.+ assert.ok(vDot(vSub(pose.worldPos('Head'), restPos('Head')), BODY_FORWARD) > 0.2, 'the head went forward');+ });++ it('turns the whole body from the root, feet included', () => {+ const pose = restPose();+ solveTurn(pose, 90);+ const left = vSub(pose.worldPos('LeftFoot'), pose.worldPos('Hips'));+ // A quarter turn to the body's left swings the left foot toward where the+ // body was facing.+ assert.ok(vDot(vNorm(left), BODY_FORWARD) > 0.8, 'the stance turned with the body');+ });++ it('looks where it is told, and cannot look further than a neck allows', () => {+ const pose = restPose();+ solveGaze(pose, { yaw: 40 });+ assert.ok(vDot(gazeDirection(pose), BODY_LEFT) > 0.5, 'looked left');+ const level = restPose();+ solveGaze(level, { pitch: 30 });+ assert.ok(vDot(gazeDirection(level), BODY_UP) > 0.3, 'looked up');+ });++ it('curls a fist and leaves a pointing finger straight', () => {+ const fist = restPose();+ shapeHand(fist, 'Right', { curl: 1, thumb: 0.85 });+ const open = restPose();+ const tip = (pose) => dist(pose.worldPos('RightHandIndex3'), pose.worldPos('RightHand'));+ assert.ok(tip(fist) < tip(open) * 0.8, 'a fist brings the fingertip in');++ const pointing = restPose();+ shapeHand(pointing, 'Right', { curl: 0.9, thumb: 0.6 });+ shapeHand(pointing, 'Right', { curl: 0, thumb: 0.6, only: ['Index'] });+ assert.ok(tip(pointing) > tip(fist), 'the index came back out');+ assert.ok(+ dist(pointing.worldPos('RightHandPinky3'), pointing.worldPos('RightHand'))+ < dist(open.worldPos('RightHandPinky3'), open.worldPos('RightHand')) * 0.9,+ 'the other fingers stayed curled',+ );+ });+});++describe('balance and anchors', () => {+ it('finds a centre of mass inside the body', () => {+ const com = centreOfMass(restPose());+ assert.ok(com[1] > 0.7 && com[1] < 1.3, `centre of mass at ${com[1]}m`);+ near(com[0], 0, 0.02, 'centred laterally');+ });++ it('calls a standing body balanced and a leaning one not', () => {+ assert.ok(balanceError(restPose()) < 0.02, 'standing is balanced');+ const leaning = restPose();+ solveSpine(leaning, { lean: 55 });+ assert.ok(balanceError(leaning) > 0.08, 'a deep unsupported lean is not');+ });++ it('places every anchor somewhere on the body', () => {+ const pose = restPose();+ for (const name of ANCHOR_NAMES) {+ for (const side of ['Left', 'Right']) {+ const point = anchorPoint(pose, name, { side });+ assert.ok(point.every(Number.isFinite), `${name} ${side} is finite`);+ assert.ok(point[1] >= -0.05 && point[1] <= 2.1, `${name} ${side} is at a plausible height`);+ assert.ok(Math.abs(vDot(point, BODY_LEFT)) < 0.8, `${name} ${side} is not off the side of the body`);+ }+ }+ });++ it('keeps every hand anchor inside the arm that has to reach it', () => {+ // The three exceptions are reach-down targets, used with a crouch or a+ // seat: a standing wrist genuinely cannot get to the floor.+ const groundLevel = new Set(['floor', 'knee', 'hips']);+ const pose = restPose();+ for (const name of ANCHOR_NAMES) {+ if (groundLevel.has(name)) continue;+ for (const side of ['Left', 'Right']) {+ const reach = dist(anchorPoint(pose, name, { side }), pose.worldPos(`${side}Arm`));+ assert.ok(reach <= ARM_REACH * 0.99, `${name} ${side} is ${reach.toFixed(3)}m away, reach is ${ARM_REACH.toFixed(3)}m`);+ }+ }+ });++ it('carries an anchor with the bone that owns it', () => {+ const still = restPose();+ const turned = restPose();+ solveGaze(turned, { yaw: 55 });+ const stillChin = anchorPoint(still, 'chin');+ const turnedChin = anchorPoint(turned, 'chin');+ assert.ok(dist(stillChin, turnedChin) > 0.03, 'the chin followed the head');+ // The hips did not move, so a hip anchor must not either.+ near(dist(anchorPoint(still, 'hip'), anchorPoint(turned, 'hip')), 0, 1e-9, 'the hip stayed put');+ });++ it('mirrors a body-relative direction per acting hand', () => {+ const pose = restPose();+ const leftOut = bodyDirection(pose, 'out', 'Left');+ const rightOut = bodyDirection(pose, 'out', 'Right');+ assert.ok(vDot(leftOut, rightOut) < -0.9, '"out" points opposite ways for the two hands');+ // An absolute direction does not mirror.+ near(vDot(bodyDirection(pose, 'up', 'Left'), bodyDirection(pose, 'up', 'Right')), 1, 1e-9);+ });+});diff --git a/packages/render/tests/glb.test.js b/packages/render/tests/glb.test.jsnew file mode 100644index 000000000..269fe6309--- /dev/null+++ b/packages/render/tests/glb.test.js@@ -0,0 +1,129 @@+// GLB container surgery: the step that lets three.js parse an avatar in Node.+//+// The renderer strips every image out of a glTF before GLTFLoader sees it,+// because the loader's texture path needs a DOM. These tests hold the contract+// that makes the re-attach step possible: images come out intact, materials+// keep an index marker, and the repacked container is still a valid GLB.++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { parseGlb, packGlb, extractImages, stripImages } from '../src/glb.js';++const AVATAR = 'public/avatars/default.glb';++function readAvatar() {+ const buf = readFileSync(AVATAR);+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);+}++describe('parseGlb', () => {+ it('splits a real avatar into JSON and BIN chunks', () => {+ const { json, bin } = parseGlb(readAvatar());+ expect(json.asset.version).toBe('2.0');+ expect(json.meshes.length).toBeGreaterThan(0);+ expect(bin.byteLength).toBeGreaterThan(0);+ });++ it('refuses anything that is not a GLB', () => {+ const notGlb = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]).buffer;+ expect(() => parseGlb(notGlb)).toThrow(/not a GLB/);+ });+});++describe('packGlb', () => {+ it('round-trips a parsed container', () => {+ const original = parseGlb(readAvatar());+ const repacked = parseGlb(packGlb(original.json, original.bin));+ expect(repacked.json.meshes.length).toBe(original.json.meshes.length);+ expect(repacked.bin.byteLength).toBe(original.bin.byteLength);+ });++ it('pads the JSON chunk with spaces, as the spec requires', () => {+ const packed = packGlb({ asset: { version: '2.0' }, x: 'pad' }, null);+ const bytes = new Uint8Array(packed);+ const length = new DataView(packed).getUint32(12, true);+ // Every byte of a chunk beyond the JSON text must be 0x20, never 0x00.+ const text = new TextDecoder().decode(bytes.subarray(20, 20 + length));+ expect(text.trimEnd()).toBe(JSON.stringify({ asset: { version: '2.0' }, x: 'pad' }));+ expect(text.slice(text.trimEnd().length)).toMatch(/^ *$/);+ });++ it('keeps a bin-less container valid', () => {+ const { json } = parseGlb(packGlb({ asset: { version: '2.0' } }, null));+ expect(json.asset.version).toBe('2.0');+ });+});++describe('extractImages', () => {+ it('lifts every embedded texture out of the binary chunk', () => {+ const { json, bin } = parseGlb(readAvatar());+ const images = extractImages(json, bin);+ expect(images.size).toBe(json.images.length);+ for (const [, image] of images) {+ expect(image.bytes.byteLength).toBeGreaterThan(0);+ expect(image.mimeType).toMatch(/^image\//);+ }+ });++ it('decodes data-URI images', () => {+ const png = Buffer.from('89504e470d0a1a0a', 'hex').toString('base64');+ const images = extractImages({ images: [{ uri: `data:image/png;base64,${png}` }] }, null);+ expect(images.get(0).mimeType).toBe('image/png');+ expect(images.get(0).bytes.length).toBe(8);+ });++ it('skips images that live behind an external URI', () => {+ const images = extractImages({ images: [{ uri: 'skin.png' }] }, null);+ expect(images.size).toBe(0);+ });+});++describe('stripImages', () => {+ it('removes every image, texture and sampler', () => {+ const { json } = parseGlb(readAvatar());+ const { json: stripped } = stripImages(json);+ expect(stripped.images).toBeUndefined();+ expect(stripped.textures).toBeUndefined();+ expect(stripped.samplers).toBeUndefined();+ for (const material of stripped.materials) {+ expect(material.pbrMetallicRoughness?.baseColorTexture).toBeUndefined();+ expect(material.normalTexture).toBeUndefined();+ }+ });++ it('marks each material with its index so textures can be re-attached', () => {+ const { json } = parseGlb(readAvatar());+ const { json: stripped } = stripImages(json);+ stripped.materials.forEach((material, index) => {+ expect(material.extras.__twsMaterial).toBe(index);+ });+ });++ it('records what each material was using', () => {+ const { json } = parseGlb(readAvatar());+ const { bindings } = stripImages(json);+ expect(bindings.size).toBe(json.materials.length);+ const textured = [...bindings.values()].filter((b) => b.baseColor);+ expect(textured.length).toBeGreaterThan(0);+ for (const binding of textured) {+ expect(typeof binding.baseColor.image).toBe('number');+ expect(['repeat', 'clamp', 'mirror']).toContain(binding.baseColor.wrapS);+ }+ });++ it('does not mutate the source JSON', () => {+ const { json } = parseGlb(readAvatar());+ const before = json.images.length;+ stripImages(json);+ expect(json.images.length).toBe(before);+ expect(json.materials[0].extras?.__twsMaterial).toBeUndefined();+ });++ it('drops extensions whose decoders this renderer does not ship', () => {+ const { json: stripped } = stripImages({+ extensionsUsed: ['KHR_texture_basisu', 'EXT_meshopt_compression'],+ materials: [],+ });+ expect(stripped.extensionsUsed).toEqual(['EXT_meshopt_compression']);+ });+});diff --git a/packages/render/tests/render.test.js b/packages/render/tests/render.test.jsnew file mode 100644index 000000000..c0c23c8b7--- /dev/null+++ b/packages/render/tests/render.test.js@@ -0,0 +1,182 @@+// End-to-end renders of a real avatar, with no GPU and no browser.+//+// These run the whole path: meshopt-compressed GLB in, CPU-skinned triangles,+// mip-mapped texture sampling, tonemapped RGBA out. They use the default avatar+// that ships with the site, so a regression in loading, skinning, framing or+// rasterization fails here rather than in production OG cards.++import { describe, it, expect, beforeAll } from 'vitest';+import { readFileSync } from 'node:fs';+import { AvatarModel } from '../src/model.js';+import { renderFrame, renderFrames, frameCamera, PRESETS } from '../src/render.js';+import { parseClipJson } from '../src/clips.js';+import { encodePng, encodeApng } from '../src/encode.js';+import { decodePng } from '../src/image.js';++const AVATAR = 'public/avatars/default.glb';+const CLIP = 'public/animations/clips/idle.json';++let model;++beforeAll(async () => {+ model = await AvatarModel.load(AVATAR);+}, 60_000);++/** Fraction of pixels that carry any alpha. */+function coverage(frame) {+ let filled = 0;+ for (let i = 3; i < frame.data.length; i += 4) if (frame.data[i] > 8) filled++;+ return filled / (frame.width * frame.height);+}++/** Mean channel value over covered pixels, as a cheap "is it lit" probe. */+function meanLuma(frame) {+ let sum = 0;+ let n = 0;+ for (let i = 0; i < frame.data.length; i += 4) {+ if (frame.data[i + 3] <= 8) continue;+ sum += 0.2126 * frame.data[i] + 0.7152 * frame.data[i + 1] + 0.0722 * frame.data[i + 2];+ n++;+ }+ return n ? sum / n : 0;+}++describe('AvatarModel', () => {+ it('loads a meshopt-compressed, quantized avatar', () => {+ expect(model.meshes.length).toBeGreaterThan(0);+ expect(model.meshes.some((m) => m.skeleton)).toBe(true);+ });++ it('decodes its textures into mip pyramids', () => {+ expect(model.textures.size).toBeGreaterThan(0);+ for (const mips of model.textures.values()) {+ expect(mips.length).toBeGreaterThan(1);+ // A pyramid always bottoms out at a single texel.+ const last = mips[mips.length - 1];+ expect(last.width).toBe(1);+ expect(last.height).toBe(1);+ }+ });++ it('measures a plausible humanoid bounding box', () => {+ const height = model.bounds.max[1] - model.bounds.min[1];+ expect(height).toBeGreaterThan(1);+ expect(height).toBeLessThan(3);+ });+});++describe('renderFrame', () => {+ it('renders the avatar, textured and lit', () => {+ const frame = renderFrame(model, { width: 96, height: 96, supersample: 1, background: 'transparent' });+ expect(frame.width).toBe(96);+ expect(coverage(frame)).toBeGreaterThan(0.05);+ // A washed-out render (inverted winding, dead normals) pins the mean+ // near the rim colour. A correct one lands in the midtones.+ const luma = meanLuma(frame);+ expect(luma).toBeGreaterThan(20);+ expect(luma).toBeLessThan(215);+ });++ it('is deterministic', () => {+ const options = { width: 64, height: 64, supersample: 1 };+ const a = renderFrame(model, options);+ const b = renderFrame(model, options);+ expect(Buffer.from(a.data)).toEqual(Buffer.from(b.data));+ });++ it('fills the frame with an opaque background and keeps alpha without one', () => {+ const opaque = renderFrame(model, { width: 48, height: 48, supersample: 1, background: '#101820' });+ expect(coverage(opaque)).toBe(1);+ const clear = renderFrame(model, { width: 48, height: 48, supersample: 1, background: 'transparent' });+ expect(coverage(clear)).toBeLessThan(1);+ });++ it('frames a head closer than a full body', () => {+ const full = frameCamera(model.bounds, { focus: 'full' });+ const head = frameCamera(model.bounds, { focus: 'head' });+ expect(head.distance).toBeLessThan(full.distance);+ // The head shot looks at the top of the model, not its middle.+ expect(head.target[1]).toBeGreaterThan(full.target[1]);+ });++ it('covers more of the frame when focused on the head', () => {+ const full = renderFrame(model, { width: 64, height: 64, supersample: 1, background: 'transparent' });+ const head = renderFrame(model, { width: 64, height: 64, supersample: 1, background: 'transparent', focus: 'head' });+ expect(coverage(head)).toBeGreaterThan(coverage(full));+ });++ it('honours a radial backdrop', () => {+ const frame = renderFrame(model, {+ width: 64,+ height: 64,+ supersample: 1,+ background: { inner: '#ffffff', outer: '#000000' },+ });+ const centre = (32 * 64 + 32) * 4;+ const corner = 0;+ expect(frame.data[corner]).toBeLessThan(frame.data[centre]);+ });++ it('exposes named lighting presets', () => {+ expect(Object.keys(PRESETS)).toContain('studio');+ for (const preset of Object.values(PRESETS)) {+ expect(preset.lights.length).toBeGreaterThan(0);+ expect(preset.ambient).toHaveLength(3);+ }+ });+});++describe('animation', () => {+ it('retargets a library clip onto the avatar rig and moves it', async () => {+ const posed = await AvatarModel.load(AVATAR);+ const clip = parseClipJson(JSON.parse(readFileSync(CLIP, 'utf8')));+ expect(posed.addClips([clip])).toBe(1);+ expect(posed.play(clip.name)).toBeTruthy();++ posed.setTime(0);+ const first = renderFrame(posed, { width: 64, height: 64, supersample: 1, background: 'transparent' });+ posed.setTime(1.5);+ const later = renderFrame(posed, { width: 64, height: 64, supersample: 1, background: 'transparent' });+ expect(Buffer.from(first.data)).not.toEqual(Buffer.from(later.data));+ }, 60_000);++ it('renders a turntable where every frame differs', async () => {+ const frames = await renderFrames(model, {+ width: 48,+ height: 48,+ supersample: 1,+ background: 'transparent',+ frames: 4,+ spin: 360,+ });+ expect(frames).toHaveLength(4);+ const hashes = new Set(frames.map((f) => Buffer.from(f.data).toString('base64').slice(0, 64)));+ expect(hashes.size).toBe(4);+ }, 60_000);+});++describe('encoders', () => {+ it('writes a PNG that decodes back to the same pixels', () => {+ const frame = renderFrame(model, { width: 32, height: 32, supersample: 1, background: '#123456' });+ const decoded = decodePng(new Uint8Array(encodePng(frame)));+ expect(decoded.width).toBe(32);+ expect(Buffer.from(decoded.data)).toEqual(Buffer.from(frame.data));+ });++ it('writes an APNG with one control chunk per frame', async () => {+ const frames = await renderFrames(model, { width: 24, height: 24, supersample: 1, frames: 3, spin: 90 });+ const png = encodeApng(frames, { fps: 12 });+ const text = png.toString('latin1');+ expect(text.slice(1, 4)).toBe('PNG');+ expect(text.split('acTL').length - 1).toBe(1);+ expect(text.split('fcTL').length - 1).toBe(3);+ // Frame 0 rides in IDAT; the rest are fdAT.+ expect(text.split('fdAT').length - 1).toBe(2);+ }, 60_000);++ it('refuses frames of mismatched size', () => {+ const a = { width: 4, height: 4, data: new Uint8ClampedArray(64) };+ const b = { width: 8, height: 4, data: new Uint8ClampedArray(128) };+ expect(() => encodeApng([a, b])).toThrow(/share the first frame size/);+ });+});