import test from 'node:test'; import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { compilePoses, expandPoses } from '../src/authoring.js'; import { renderProject, parseColor } from '../src/core.js'; import { inspectMotion } from '../src/motion.js'; import { cleanupIds, rasterizeBone, rasterizeMass } from '../src/craft.js'; import { heroRig, bossRig, plainRig } from '../scripts/figure-rigs.mjs'; const cached = new Map(); function fixture(make) { if (!cached.has(make)) { const source = make(), expanded = expandPoses(source), compiled = compilePoses(source), project = renderProject(compiled.recipe, { stats: true }); cached.set(make, { source, expanded, ...compiled, project, rasters: new Map() }); } return cached.get(make); } for (const [make, count, instances] of [[heroRig, 39, 18], [bossRig, 95, 32]]) { test(`${make.name}: editable expansion round-trips, deduplicates drawings and preserves named layers`, () => { const f = fixture(make), before = JSON.stringify(f.source); assert.equal(f.recipe.frames.length, count); assert.ok(f.recipe.frames.every(frame => frame.layers.length === instances)); assert.deepEqual(compilePoses(f.expanded), { recipe: f.recipe, metadata: f.metadata }); assert.equal(JSON.stringify(f.source), before); const rows = Object.values(f.recipe.symbols).map(rows => JSON.stringify(rows)); assert.equal(new Set(rows).size, rows.length); assert.equal(f.metadata.warnings, undefined); assert.equal(f.project.clipping, undefined); // The suite holds the work, which a slower algorithm moves on every machine: the recipe's size and the renderer's // own drawing count (the hero draws 67,269 pixels, the boss 929,888). How long expansion, compilation and rendering // take is measured by `npm run bench -- --budgets` (poses/hero-expand, poses/hero, render/hero, poses/boss, // render/boss), which reports a case over its budget without failing CI: a busy runner is not a broken build. if (make === heroRig) assert.ok(JSON.stringify(f.recipe).length < 150000); assert.ok(f.project.work.pixels <= (make === heroRig ? 135000 : 6700000), `drawing work: ${f.project.work.pixels} pixels`); const colors = new Set(Object.values(f.source.palette).map(c => new Uint32Array(Uint8Array.from(parseColor(c)).buffer)[0])); for (const frame of f.project.frames) { const pixels = new Uint32Array(frame.data.buffer); for (let i = 0; i < pixels.length; i++) if (frame.data[i * 4 + 3]) assert.ok(colors.has(pixels[i]), `palette ${frame.name}`); } }); const motions = make === heroRig ? ['idle', 'walk', 'run', 'jump', 'attack'] : ['idle', 'walk', 'run', 'jump', 'attack', 'hurt', 'prowl', 'charge']; for (const animation of motions) test(`${make.name}: ${animation} has clean parts, joined bones and passing motion measurements`, () => { const f = fixture(make), view = inspectMotion(f.project, { animation, metadata: f.metadata, scale: 1 }); // The review's images are its work, about half these bounds at most (the hero's walk is 286 × 420, the boss's // charge 718 × 1060). Its time is the bench's motion/hero-run. assert.ok(view.sheet.width * view.sheet.height <= (make === heroRig ? 250000 : 1600000), `review sheet ${view.sheet.width} × ${view.sheet.height}`); for (const [name, pass] of Object.entries(view.motion.checks)) assert.notEqual(pass, false, `${name}: ${JSON.stringify(view.motion)}`); const names = new Set(f.project.animations[animation].frames.map(i => f.project.frames[i].name)); for (const pose of f.expanded.poses.filter(p => names.has(p.name))) { const placed = f.metadata.poses[pose.name].parts; for (const [i, instance] of pose.parts.entries()) { const part = placed[instance.name], definition = f.source.parts[instance.part], shape = definition.bone ?? definition.mass; if (!shape) continue; const key = JSON.stringify([instance.part, part.rotate ?? 0, instance.flipX ?? false, instance.squash ?? 1]); if (!f.rasters.has(key)) { const raster = (definition.bone ? rasterizeBone : rasterizeMass)(shape, { angle: part.rotate ?? 0, flipX: instance.flipX === true, squash: instance.squash ?? 1, ramp: f.source.ramps[shape.ramp], light: f.source.light }); const ids = Uint32Array.from([...raster.rows.join('')].map(c => c === '.' ? 0 : c.charCodeAt(0))), spine = new Set((raster.spine ?? []).map(([x, y]) => y * raster.width + x)); assert.equal(cleanupIds(ids, raster.width, raster.height, { corners: true, allowed: j => Boolean(raster.outlineMask[j] || spine.has(j)) }).length, 0, `${pose.name}/${instance.name} corners`); assert.equal(cleanupIds(ids, raster.width, raster.height, { strays: true, allowed: j => Boolean(raster.fill[j] && !spine.has(j)) }).length, 0, `${pose.name}/${instance.name} orphans`); if (definition.mass) { const normal = rasterizeMass(shape, { angle: part.rotate ?? 0, flipX: instance.flipX === true, ramp: f.source.ramps[shape.ramp], light: f.source.light }); const area = r => r.rows.join('').replaceAll('.', '').length; assert.ok(Math.abs(area(raster) / area(normal) - 1) <= .1, `${pose.name}/${instance.name} mass area`); } f.rasters.set(key, raster); } if (part.reach) assert.equal(part.reach.error, 0, `${pose.name}/${instance.name} reach`); const parent = placed[instance.attach?.part]; if (!parent?.joints || !part.joints) continue; assert.deepEqual(part.joints.start, parent.joints.end, `${pose.name}/${instance.name} joint`); const child = f.rasters.get(key), parentInstance = pose.parts.find(p => p.name === instance.attach.part), parentShape = f.source.parts[parentInstance.part].bone; const parentRaster = rasterizeBone(parentShape, { angle: parent.rotate ?? 0, flipX: parentInstance.flipX === true, ramp: f.source.ramps[parentShape.ramp], light: f.source.light }); const joint = part.joints.start; const local = new Uint8Array(9); for (const p of [parent, part]) { const rows = f.recipe.symbols[p.symbol ?? p.definition]; for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) { const x = joint[0] + dx - p.topLeft[0], y = joint[1] + dy - p.topLeft[1], c = rows[y]?.[x]; if (c && c !== '.' && c !== ' ') local[(dy + 1) * 3 + dx + 1] = 1; } } const reached = new Set([4]), queue = [4]; while (queue.length) { const at = queue.pop(), x = at % 3, y = Math.floor(at / 3); for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { const nx = x + dx, ny = y + dy, next = ny * 3 + nx; if (nx >= 0 && nx < 3 && ny >= 0 && ny < 3 && local[next] && !reached.has(next)) { reached.add(next); queue.push(next); } } } for (const [p, r] of [[parent, parentRaster], [part, child]]) { const x = joint[0] - p.topLeft[0], y = joint[1] - p.topLeft[1]; assert.ok(r.fill[y * r.width + x], `${pose.name}/${instance.name} shared filled joint`); assert.ok([...reached].some(at => { const nx = x + at % 3 - 1, ny = y + Math.floor(at / 3) - 1; return at !== 4 && nx >= 0 && ny >= 0 && nx < r.width && ny < r.height && r.fill[ny * r.width + nx]; }), `${pose.name}/${instance.name} edge-connected joint into ${p.definition}`); } if (pose.parts.indexOf(parentInstance) < i) { const rows = f.recipe.symbols[part.symbol ?? part.definition]; for (let y = 0; y < child.height; y++) for (let x = 0; x < child.width; x++) { const px = part.topLeft[0] + x - parent.topLeft[0], py = part.topLeft[1] + y - parent.topLeft[1]; if (child.outlineMask[y * child.width + x] && px >= 0 && py >= 0 && px < parentRaster.width && py < parentRaster.height && parentRaster.fill[py * parentRaster.width + px]) assert.equal(rows[y][x], '.', `${pose.name}/${instance.name} internal seam`); } } } } }); } test('templates expose authored overrides, depth swaps, strike holds, metadata speed and two-pose breathing', () => { const source = heroRig(), expanded = expandPoses(source), a = expanded.poses.find(p => p.name === 'run-contact-a'), b = expanded.poses.find(p => p.name === 'run-contact-b'); const ahead = (pose, first, second) => pose.parts.findIndex(p => p.name === first) < pose.parts.findIndex(p => p.name === second); // A side view keeps its near limbs and held weapon in front in both halves of the cycle. for (const pose of [a, b]) assert.ok(ahead(pose, 'farThigh', 'body') && ahead(pose, 'body', 'nearThigh') && ahead(pose, 'body', 'sword'), pose.name); // swapDepth (front or back views) exchanges the paired subtrees in the second half, held items included. const swapped = structuredClone(source); swapped.motions.run.swapDepth = true; const [sa, sb] = ['run-contact-a', 'run-contact-b'].map(name => expandPoses(swapped).poses.find(p => p.name === name)); assert.ok(ahead(sa, 'farThigh', 'body') && ahead(sb, 'nearThigh', 'body')); assert.ok(ahead(sa, 'body', 'sword') && ahead(sb, 'sword', 'body'), 'weapon stays in its arm subtree across unequal-depth swaps'); swapped.motions.run.swapDepth = 'yes'; assert.throws(() => expandPoses(swapped), /poses\.motions\.run\.swapDepth/); const changed = structuredClone(a); changed.duration = 123; source.poses.push(changed); assert.equal(expandPoses(source).poses.find(p => p.name === changed.name).duration, 123); assert.equal(expanded.animations.attack.frames.filter(name => name === 'attack-strike').length, 2); assert.ok(expanded.poses.find(p => p.name === 'attack-strike').markers.some(m => m.name === 'strike')); assert.equal(expanded.motionInfo.run.speed, 48); source.motions.idle.frames = 2; const idle = expandPoses(source).poses.filter(p => p.name.startsWith('idle-')); assert.deepEqual(idle.map(p => p.name), ['idle-inhale', 'idle-exhale']); assert.notEqual(idle[0].parts.find(p => p.name === 'body').squash, idle[1].parts.find(p => p.name === 'body').squash); source.motions.run.lift = 0; source.poses = [source.poses[0]]; for (const pose of expandPoses(source).poses.filter(p => p.name.startsWith('run-'))) { for (const chain of source.rig.legs) assert.equal(pose.parts.find(p => p.name === chain.at(-1)).reach[1], source.rig.ground); } }); test('cache order cannot change a rig drawing, symbol table or pose metadata', () => { const { expanded, recipe, metadata } = fixture(heroRig), reordered = structuredClone(expanded); reordered.poses.reverse(); const again = compilePoses(reordered); assert.deepEqual(again.recipe.symbols, recipe.symbols); for (const frame of recipe.frames) assert.deepEqual(again.recipe.frames.find(f => f.name === frame.name), frame); for (const [name, pose] of Object.entries(metadata.poses)) assert.deepEqual(again.metadata.poses[name], pose); }); test('templates reject bad roles, ranges, chains, annotations and conflicting names with paths', () => { const checks = [ s => { s.rig.body = 'absent'; }, s => { s.rig.rest = 'absent'; }, s => { s.rig.legs[0][1] = 'head'; }, s => { s.rig.legs[1][0] = s.rig.legs[0][0]; }, s => { s.motions.run.frames = 5; }, s => { s.motions.run.speed = null; }, s => { s.motions.idle.breath = 2; }, s => { s.motions.idle.stride = 5; }, s => { s.motions.attack.arm = 4; }, s => { s.motions.attack.hold = 0; }, s => { s.motions.jump.apex = 40; }, s => { s.motions.run.template = 'fly'; }, s => { s.motionInfo = {}; }, s => { s.animations = { run: { frames: ['stand'] } }; } ]; for (const mutate of checks) { const s = heroRig(); mutate(s); assert.throws(() => expandPoses(s), /poses\.(rig|motions|motionInfo)/); } const s = expandPoses(heroRig()); s.motionInfo.run.keyPoses = ['missing']; assert.throws(() => compilePoses(s), /motionInfo.run.keyPoses/); }); test('motion code uses deterministic polynomial mathematics', async () => { for (const file of ['motions.js', 'motion.js']) assert.doesNotMatch(await readFile(new URL(`../src/${file}`, import.meta.url), 'utf8'), /Math\.(sin|cos|tan|atan|atan2|acos|asin|hypot|pow|random)\s*\(/); }); test('malformed pose sources fail with a path, not a TypeError', () => { // A marker naming an Object.prototype key ("toString") once reached Object.hasOwn(undefined, ...). const marker = { format: 'pixelforge-poses', version: 1, name: 'm', width: 8, height: 8, palette: { r: '#ff0000' }, parts: { dot: { rows: ['r'] } }, poses: [{ name: 'p', parts: [{ name: 'dot', part: 'dot' }], markers: [{ name: 'm', part: 'toString', point: 'x' }] }] }; for (const name of ['toString', 'constructor', 'hasOwnProperty']) { marker.poses[0].markers[0].part = name; assert.throws(() => compilePoses(marker), error => error.name === 'PixelError' && /poses\.poses\[0\]\.markers\[0\]/.test(error.message)); } // A null pose beside motions once crashed the rest-pose lookup. const source = heroRig(); source.poses.push(null); for (const run of [() => expandPoses(source), () => compilePoses(source)]) assert.throws(run, error => error.name === 'PixelError' && /poses\.poses\[1\]/.test(error.message)); }); test('every template at its defaults passes its own motion checks on a plain side-view humanoid', () => { const source = plainRig(), { recipe, metadata } = compilePoses(source), project = renderProject(recipe); assert.deepEqual(metadata.warnings ?? [], []); for (const animation of Object.keys(source.motions)) { const { motion } = inspectMotion(project, { animation, metadata }); for (const [check, pass] of Object.entries(motion.checks)) assert.notEqual(pass, false, `${animation}.${check}`); } for (const animation of ['walk', 'run']) { const { motion } = inspectMotion(project, { animation, metadata }); // Measured, not skipped: feet stay planted on the ground, and the contact poses trade legs. assert.deepEqual(motion.checks, { slide: true, ground: true, poseSpread: true, loopSeam: true, armSwing: true, ...(animation === 'walk' ? { contactLegs: true, kneeLift: true } : { contactLegs: null, kneeLift: null }) }, animation); const pair = motion.poseSpread.find(p => p.from === `${animation}-contact-a` && p.to === `${animation}-contact-b`); assert.ok(pair.jointDegrees >= 20, `${animation} contact poses differ by ${pair.jointDegrees}°`); // Near limbs stay in front of the body in both halves of a side-view cycle. for (const name of [`${animation}-contact-a`, `${animation}-contact-b`]) { const layers = recipe.frames.find(f => f.name === name).layers.map(l => l.name); assert.ok(layers.indexOf('farThigh') < layers.indexOf(source.rig.body) && layers.indexOf(source.rig.body) < layers.indexOf('nearThigh'), name); } } }); test('the rigged hero example compiles without warnings and draws the plain humanoid from an origin at its feet', async () => { // The example places its hips with `at` from an origin where the feet meet the ground, so every frame's atlas // anchor is a ground point; the pixels are exactly those of the plain fixture above, whose origin is its hips. const hero = JSON.parse(await readFile(new URL('../examples/hero.poses.json', import.meta.url), 'utf8')); const compiled = compilePoses(hero), plain = renderProject(compilePoses(plainRig()).recipe); assert.equal(compiled.warnings, undefined); const frames = renderProject(compiled.recipe).frames; assert.deepEqual(frames.map(frame => frame.name), plain.frames.map(frame => frame.name)); frames.forEach((frame, i) => assert.ok(Buffer.from(frame.data).equals(Buffer.from(plain.frames[i].data)), frame.name)); // The rest pose is measured but, played by no animation, is not a frame; every frame shares its ground point. assert.deepEqual(compiled.metadata.poses.stand.origin, [15, 35]); assert.ok(!compiled.recipe.frames.some(frame => frame.name === 'stand')); assert.deepEqual(compiled.recipe.anchor ?? compiled.recipe.frames[0].anchor, [15, 35]); }); test('structural drawing has a deterministic work budget, and cached masses are copies', () => { // Many distinct large masses (each squash and angle is a new drawing) fail fast with a path instead of drawing // for seconds and blocking the MCP server or the studio thread. const poses = Array.from({ length: 4 }, (_, i) => ({ name: `p${i}`, origin: [64, 64], parts: Array.from({ length: 64 }, (_, j) => ({ name: `m${j}`, part: 'blob', rotate: (i * 64 + j) % 360, squash: [.5, .75, 1.25, 1.5, 2][(i + j) % 5], flipX: (i + j) % 2 === 1 })) })); const source = { format: 'pixelforge-poses', version: 1, name: 'heavy', width: 128, height: 128, palette: { k: '#000000', a: '#333333', b: '#666666' }, ramps: [['a', 'b']], parts: { blob: { mass: { size: [64, 64], ramp: 0, base: 1, outline: 'k' } } }, poses }; const failure = (() => { try { compilePoses(source); } catch (error) { return error; } })(); assert.equal(failure?.name, 'PixelError'); assert.match(failure.message, /^poses\.poses\[\d+\]\.parts\[\d+\]: drawing bone and mass parts exceeds the 8,388,608-pixel budget/); // Work is nominal, so a cached drawing charges what drawing it would: the verdict never depends on the caches. const mass = { size: [12, 7], base: 1, outline: 'k' }, options = { angle: 30, squash: 1.2, ramp: ['a', 'b', 'c'] }; const first = rasterizeMass(mass, options), second = rasterizeMass(mass, options); assert.ok(first.work > 0 && first.work === second.work); first.fill.fill(9); first.rows[0] = 'changed'; first.pivot[0] = 99; const third = rasterizeMass(mass, options); assert.deepEqual([third.rows, third.fill, third.pivot], [second.rows, second.fill, second.pivot]); assert.deepEqual(third.map([3, -2]), second.map([3, -2])); }); test('an expanded source cut down to one motion compiles: the other motions\' notes are skipped with a warning', async () => { // compile --expand, then delete every animation but attack and the poses only they use: the motionInfo entries of // the deleted animations used to stop the compile with "poses.motionInfo.idle: unknown or null field". const hero = JSON.parse(await readFile(new URL('../examples/hero.poses.json', import.meta.url), 'utf8')); const expanded = expandPoses(hero), keep = new Set([hero.rig.rest, ...expanded.animations.attack.frames]); const cut = { ...expanded, poses: expanded.poses.filter(pose => keep.has(pose.name)), animations: { attack: expanded.animations.attack } }; const others = Object.keys(expanded.motionInfo).filter(name => name !== 'attack'), compiled = compilePoses(cut); assert.ok(others.length > 1); assert.equal(compiled.warnings.length, 1); assert.match(compiled.warnings[0], /^poses\.motionInfo: There are no animations "[^.]*, so their entries were skipped: delete them, or rename them to match renamed animations\.$/); for (const name of others.slice(0, 6)) assert.ok(compiled.warnings[0].includes(`"${name}"`), name); // It compiles exactly as the source with those entries deleted by hand, and attack keeps its notes. const trimmed = compilePoses({ ...cut, motionInfo: { attack: expanded.motionInfo.attack } }), { warnings, ...metadata } = compiled.metadata; assert.equal(trimmed.warnings, undefined); assert.deepEqual(compiled.recipe, trimmed.recipe); assert.deepEqual(metadata, trimmed.metadata); assert.deepEqual(warnings, [{ path: 'poses.motionInfo', message: compiled.warnings[0].slice('poses.motionInfo: '.length) }]); assert.equal(metadata.animations.attack.template, 'attack'); // One left over is named at its own path; a key pose no longer in its animation is an error that names it. assert.deepEqual(compilePoses({ ...cut, motionInfo: { attack: expanded.motionInfo.attack, idle: expanded.motionInfo.idle } }).warnings, ['poses.motionInfo.idle: There is no animation "idle", so this entry was skipped: delete it, or rename it to match a renamed animation.']); const stray = { ...cut, motionInfo: { attack: { ...expanded.motionInfo.attack, keyPoses: [...expanded.motionInfo.attack.keyPoses, 'walk-gone'] } } }; assert.throws(() => compilePoses(stray), { name: 'PixelError', message: 'poses.motionInfo.attack.keyPoses: "walk-gone" is not in animation attack; remove it from keyPoses, or delete motionInfo.attack' }); assert.throws(() => compilePoses({ ...cut, motionInfo: [] }), { message: 'poses.motionInfo: expected an object' }); assert.throws(() => compilePoses({ ...cut, motionInfo: { attack: null } }), { message: 'poses.motionInfo.attack: expected an object' }); }); test('a sword held with a relative angle turns with the forearm through the attack, and the docs say so where agents look', async () => { const source = JSON.parse(await readFile(new URL('../examples/hero-sword.poses.json', import.meta.url), 'utf8')); const turn = degrees => ((degrees % 360) + 360) % 360, compiled = compilePoses(source); assert.equal(compiled.warnings, undefined, 'the blade stays on the canvas'); const attack = metadata => metadata.animations.attack.entries.map(({ frame }) => metadata.poses[frame].parts); const held = attack(compiled.metadata); // In every attack pose the blade points 45 degrees anticlockwise of the forearm, so it swings with the arm: back // over the shoulder at the wind-up, level at the strike. for (const parts of held) assert.equal(turn((parts.sword.rotate ?? 0) - parts.nearFore.worldAngle), turn(-45)); const swords = held.map(parts => turn(parts.sword.rotate ?? 0)); assert.ok(new Set(swords).size >= 3 && Math.max(...swords) - Math.min(...swords) >= 90, `sword angles ${swords}`); // An absolute rotate on the same instance keeps one angle through the whole attack: the mistake the docs warn about. const fixed = structuredClone(source), sword = fixed.poses[0].parts.find(part => part.name === 'sword'); delete sword.angle; sword.rotate = -45; assert.deepEqual([...new Set(attack(compilePoses(fixed).metadata).map(parts => turn(parts.sword.rotate ?? 0)))], [turn(-45)]); // The pointer is where an agent adding a held item reads: the rotate paragraph, the skill's Characters section and // the quick start's character line. const text = async file => (await readFile(new URL(`../${file}`, import.meta.url), 'utf8')).replace(/\r\n/g, '\n'); const rotate = (await text('docs/art-workflow.md')).split('\n').find(line => line.startsWith('An instance with `"rotate": 30`')); assert.match(rotate, /`rotate` is an absolute angle/); assert.match(rotate, /relative `angle`/); assert.match(rotate, /examples\/hero-sword\.poses\.json/); assert.doesNotMatch(rotate, /so a held item stays in the hand/); const characters = (await text('docs/agent-craft.md')).split('\n## ').find(section => section.startsWith('Characters')); assert.match(characters, /relative `angle`.*hero-sword\.poses\.json/s); assert.match((await text('docs/agent-quick-start.md')).split('\n').find(line => line.includes('examples/hero.poses.json')), /hero-sword\.poses\.json`: the prop's relative `angle` turns it with the arm/); }); test('a tail follows through: it trails in a run, further than in a walk, lifts as a jump falls, whips past rest after a strike and settles round a loop', async () => { // The plain humanoid's scarf hangs down and back from the nape (facing right): a larger relative angle trails it // further back, or lifts it. const swings = source => { const expanded = expandPoses(source), rest = Object.fromEntries(source.poses[0].parts.map(part => [part.name, part.angle])); return name => expanded.poses.find(pose => pose.name === name).parts.filter(part => source.rig.tail.includes(part.name)).map(part => ((part.angle - rest[part.name]) % 360 + 540) % 360 - 180); }; const swing = swings(plainRig()), root = name => swing(name)[0], mean = names => names.reduce((sum, name) => sum + root(name), 0) / names.length; const motion = (prefix, count) => expandPoses(plainRig()).poses.filter(pose => pose.name.startsWith(`${prefix}-`)).map(pose => pose.name).slice(0, count); const walk = mean(motion('walk')), run = mean(motion('run')); assert.ok(walk > 8 && run > walk + 3, `the scarf trails ${walk}° in the walk and ${run}° in the run`); assert.ok(root('jump-fall') >= root('jump-apex') + 30 && root('jump-fall') >= 30, `it lifts as the body falls: apex ${root('jump-apex')}°, fall ${root('jump-fall')}°`); assert.ok(root('jump-rise') < 0 && root('jump-land') < root('jump-fall'), 'it is pulled down as the body rises and drops on landing'); assert.ok(root('attack-strike') > 0 && root('attack-follow-through') <= root('attack-strike') - 15 && root('attack-recover') < 0, `a strike flings it back and it whips through past rest: ${['strike', 'follow-through', 'recover'].map(name => root(`attack-${name}`))}`); assert.ok(motion('idle').every(name => Math.abs(root(name)) <= 15), 'an idle sways it gently'); // A loop is run round until it repeats, so its first frame follows its last as any frame follows the one before. for (const prefix of ['idle', 'walk', 'run']) { const angles = motion(prefix).map(root), steps = angles.map((angle, i) => Math.abs(angles[(i + 1) % angles.length] - angle)); assert.ok(steps.at(-1) <= Math.max(...steps.slice(0, -1)), `${prefix} seam ${steps.at(-1)}° against ${steps.slice(0, -1)}`); } // A link lags the one it hangs from: at the strike the root has swung back and the tip still bends forward. assert.ok(swing('attack-strike')[1] < swing('attack-strike')[0], `tip ${swing('attack-strike')[1]}° against root ${swing('attack-strike')[0]}°`); // follow scales the swing: 0 holds the tail as drawn, 2 trails it further. const held = plainRig(), loose = plainRig(); for (const motion of Object.values(held.motions)) motion.follow = 0; for (const motion of Object.values(loose.motions)) motion.follow = 2; const still = swings(held), wide = swings(loose); assert.ok(expandPoses(held).poses.slice(1).every(pose => still(pose.name).every(degrees => degrees === 0))); assert.ok(motion('run').reduce((sum, name) => sum + wide(name)[0], 0) / motion('run').length > run * 1.5); // A chain bends as one curved piece and a link on the figure stops short of flipping over, even on the fox, whose // level tail every fall and landing catches broadside: the cracked-whip tips and upright tails of a loose chain. const fox = JSON.parse(await readFile(new URL('../examples/fox.poses.json', import.meta.url), 'utf8')), foxSwing = swings(fox); for (const pose of expandPoses(fox).poses.slice(1)) { const [root, ...bends] = foxSwing(pose.name); assert.ok(Math.abs(root) <= 75 && bends.every(bend => Math.abs(bend) <= 30), `${pose.name}: ${[root, ...bends]}`); } const bare = plainRig(); delete bare.rig.tail; bare.motions.run.follow = 1; assert.throws(() => expandPoses(bare), /^PixelError: poses\.motions\.run\.follow: follow swings the tail; name its instances in rig\.tail$/); loose.motions.run.follow = 3; assert.throws(() => expandPoses(loose), /poses\.motions\.run\.follow: expected a number from 0 to 2/); }); test('a rig rest pose is a frame only when an animation plays it', async () => { const hero = JSON.parse(await readFile(new URL('../examples/hero.poses.json', import.meta.url), 'utf8')); const { recipe, metadata } = compilePoses(hero), played = new Set(Object.values(recipe.animations).flatMap(animation => animation.frames)); // Every cell of the sheet is a frame some animation plays: a four-frame idle exports four cells, not five. assert.deepEqual(recipe.frames.map(frame => frame.name).filter(name => !played.has(name)), []); assert.ok(!recipe.frames.some(frame => frame.name === 'stand')); // It is still measured, since the motions and the review tools read it. assert.deepEqual(metadata.poses.stand.origin, [15, 35]); // An animation that names it keeps it, where the source wrote it. const kept = compilePoses({ ...hero, animations: { ...hero.animations, stand: { frames: ['stand'] } } }).recipe; assert.equal(kept.frames.length, recipe.frames.length + 1); assert.equal(kept.frames[0].name, 'stand'); assert.deepEqual(kept.frames.slice(1), recipe.frames); // A source without a rig keeps every pose it wrote, played or not. const { rig, motions, ...plain } = expandPoses(hero); assert.equal(compilePoses(plain).recipe.frames.length, recipe.frames.length + 1); }); test('an arm left out of rig.arms holds what it carries: the shield of the knight stays put while the sword arm swings', async () => { const source = JSON.parse(await readFile(new URL('../examples/knight.poses.json', import.meta.url), 'utf8')), expanded = expandPoses(source); const angle = (pose, name) => pose.parts.find(part => part.name === name).angle, rest = expanded.poses.find(pose => pose.name === source.rig.rest); const generated = expanded.poses.filter(pose => pose !== rest); assert.ok(generated.length >= 16); for (const pose of generated) for (const name of ['shieldUpper', 'shieldFore']) assert.equal(angle(pose, name), angle(rest, name), `${pose.name} ${name}`); for (const motion of ['walk', 'attack']) assert.ok(generated.filter(pose => pose.name.startsWith(motion)).some(pose => angle(pose, 'farUpper') !== angle(rest, 'farUpper')), `${motion} swings the sword arm`); // The shield hangs from the arm, so in the drawing it moves only as the body does: never more than the walk's bob and sway. const { recipe } = compilePoses(source), project = renderProject(recipe), gold = [217, 162, 58]; const boxes = project.animations.walk.frames.map(index => { const { data } = project.frames[index]; let left = Infinity, right = -Infinity; for (let p = 0; p < data.length; p += 4) if (data[p] === gold[0] && data[p + 1] === gold[1] && data[p + 2] === gold[2]) { const x = p / 4 % project.width; left = Math.min(left, x); right = Math.max(right, x); } return [left, right]; }); // The sword's guard is gold too and passes the shield's right rim, so the left rim is the one that tells. assert.ok(boxes.every(([left]) => Math.abs(left - boxes[0][0]) <= 1), JSON.stringify(boxes)); }); test('a motion palette recolours every pose the motion makes: the knight flashes when hurt, and other motions keep the rest pose palette', async () => { const source = JSON.parse(await readFile(new URL('../examples/knight.poses.json', import.meta.url), 'utf8')); const white = Object.fromEntries(['A', 'B', 'C', 'r', 's', 't', 'g', 'G', 'c', 'w'].map(key => [key, '#fff'])); source.motions.hurt.palette = white; const { recipe } = compilePoses(source), project = renderProject(recipe), named = name => recipe.frames.find(frame => frame.name === name); assert.deepEqual([named('hurt-recoil').palette, named('hurt-recover').palette, named('walk-contact-a').palette], [white, white, undefined]); // Drawn: every pixel of the flash is the outline, white or the lightest steel and gold the map leaves alone. const kept = new Set(['#1b1724', '#ffffff', '#e6ebf5', '#f6dc7a']), hex = (d, p) => '#' + [0, 1, 2].map(c => d[p + c].toString(16).padStart(2, '0')).join(''); const { data } = project.frames[recipe.frames.indexOf(named('hurt-recoil'))], seen = new Set(); for (let p = 0; p < data.length; p += 4) if (data[p + 3]) seen.add(hex(data, p)); assert.ok([...seen].every(colour => kept.has(colour)) && seen.has('#ffffff'), [...seen].join(' ')); // A rest pose's palette is carried into the poses the templates make from it, unless the motion gives its own. const tinted = structuredClone(source); tinted.poses[0].palette = { s: '#3050a0' }; const again = compilePoses(tinted).recipe, of = name => again.frames.find(frame => frame.name === name).palette; assert.deepEqual([of('walk-contact-a'), of('hurt-recoil')], [{ s: '#3050a0' }, white]); // An empty motion palette is none, as an empty pose palette is: it clears the rest pose's. tinted.motions.hurt.palette = {}; const cleared = compilePoses(tinted).recipe, clearedOf = name => cleared.frames.find(frame => frame.name === name).palette; assert.deepEqual([clearedOf('walk-contact-a'), clearedOf('hurt-recoil'), clearedOf('hurt-recover')], [{ s: '#3050a0' }, undefined, undefined]); // A one-frame flash: an authored pose with the generated name hurt-recoil replaces that pose, and only it flashes. const once = structuredClone(source); delete once.motions.hurt.palette; once.poses.push({ ...structuredClone(once.poses[0]), name: 'hurt-recoil', palette: white }); const flashed = compilePoses(once).recipe, flashedOf = name => flashed.frames.find(frame => frame.name === name).palette; assert.deepEqual([flashedOf('hurt-recoil'), flashedOf('hurt-recover')], [white, undefined]); assert.deepEqual(flashed.animations.hurt.frames, ['hurt-recoil', 'hurt-recover']); source.motions.hurt.palette = { Q: '#fff' }; assert.throws(() => compilePoses(source), { message: /^poses\.motions\.hurt\.palette\.Q: a motion palette recolours keys declared in poses\.palette/ }); }); test('an attachment to a missing point or instance says what the pose has and how to add the point', async () => { // The hero with a bow hung from `attach`: the mistake a first character makes. const text = await readFile(new URL('../examples/hero.poses.json', import.meta.url), 'utf8'); const withBow = attach => { const source = JSON.parse(text); source.parts.bow = { rows: ['k', 'k'] }; source.poses[0].parts.push({ name: 'bow', part: 'bow', attach }); return source; }; const cases = [ [{ part: 'nearHand', point: 'grip' }, /"nearHand" has no point "grip" \(it has none\)\. Name one of its points, or add this one under parts\.hand\.points: "grip": \[column, row\] in its rows$/], [{ part: 'chest', point: 'grip' }, /"chest" has no point "grip" \(its points: end, shoulder, neck, nape\)\..*parts\.chest\.points: "grip": "end", or \[along, across\] from the start of the bone$/], [{ part: 'hips', point: 'grip' }, /its points: hip, waist\).*\[x, y\] from the centre of the mass$/], [{ part: 'hand', point: 'grip' }, /no part instance named "hand" in this pose \("hand" is a part definition, placed here as "nearHand"; attach\.part takes an instance's name\); its instances: tail, tip, .* and 3 more$/], [{ part: 'nope', point: 'grip' }, /no part instance named "nope" in this pose; its instances: tail, tip, /] ]; for (const [attach, pattern] of cases) assert.throws(() => compilePoses(withBow(attach)), error => { assert.equal(error.path, 'poses.poses[0].parts[18].attach'); assert.match(error.message, pattern); return true; }); });