Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/loop/src/companion.ts

Raw
import type { Theme } from "@earendil-works/pi-coding-agent";
import {
	type Component,
	rgbColor,
	type TUI,
	truncateToWidth,
	visibleWidth,
} from "@earendil-works/pi-tui";
import { ICON } from "./icons.ts";
import type { Budgets, RunStatus } from "./store.ts";

/** A red-haired pin-up who struts below the editor while the loop works. */
export type Pose = "posing" | "peek" | "pout" | "lounge" | "celebrate";
export type RGB = readonly [number, number, number];
export type Pixels = Array<Array<RGB | null>>;

/** Figure raster: half-block cells make square pixels, two per terminal row. */
export const W = 24;
export const H = 30;
const SAMPLES = 3; // Supersampling per axis for soft, anti-aliased shading.
const COVERAGE = 0.45; // Below this a pixel stays transparent over the terminal.

/**
 * A material is a short, hand-picked ramp from deepest shadow to highlight.
 * Shading snaps to these entries, so every pixel is a deliberate palette
 * colour: crisp clusters, no muddy in-between tones.
 */
type Material = { ramp: readonly RGB[] };
// Light skin, hue-shifted: the deepest shadow cools toward violet-brown, the
// first shadow step turns redder and richer, light warms toward peach.
const SKIN: Material = {
	ramp: [
		[156, 96, 102],
		[214, 128, 110],
		[242, 176, 146],
		[255, 210, 182],
		[255, 232, 210],
	],
};
// Copper hair: undercoat, base, mid, highlight band.
const HAIR: Material = {
	ramp: [
		[104, 26, 26],
		[170, 54, 30],
		[220, 96, 46],
		[246, 148, 84],
	],
};
// Pastel orange bikini: soft shadow, base, light; cloth takes no shine.
const BIKINI: Material = {
	ramp: [
		[228, 140, 98],
		[255, 186, 142],
		[255, 218, 188],
	],
};
// Deeper orange for strings and pumps.
const TRIM: Material = {
	ramp: [
		[210, 92, 46],
		[248, 136, 74],
		[255, 190, 142],
	],
};
// Sheer nylons with a warm peach tint.
const NYLON: Material = {
	ramp: [
		[156, 104, 88],
		[222, 166, 140],
		[246, 206, 184],
	],
};
const GOLD: Material = {
	ramp: [
		[150, 104, 40],
		[226, 178, 82],
		[255, 236, 168],
	],
};
// Facial features are single crisp pixels placed after sampling, never blurred.
const EYE: RGB = [28, 92, 56]; // Green, dark enough to read as one pixel.
const LASH: RGB = [150, 84, 70];
const LIPS: RGB = [206, 108, 116];
const LASH_DARK: RGB = [40, 22, 24];
const SCLERA: RGB = [236, 230, 222];
const IRIS: RGB = [62, 132, 84];
const BROW: RGB = [128, 40, 20];
const LOWER_LIP: RGB = [222, 138, 140];
const KISS: RGB = [176, 76, 92];
export const HEART: RGB = [255, 96, 150];

const LIGHT = (() => {
	const [x, y, z] = [-0.45, -0.62, 0.64];
	const n = Math.hypot(x, y, z);
	return [x / n, y / n, z / n] as const;
})();

/** Lambert lighting with soft occlusion at silhouettes, snapped to the ramp. */
function shade(m: Material, nx: number, ny: number, glow = 1): RGB {
	const nz = Math.sqrt(Math.max(0, 1 - nx * nx - ny * ny));
	const diffuse = Math.max(0, nx * LIGHT[0] + ny * LIGHT[1] + nz * LIGHT[2]);
	const i = Math.min(0.999, (0.3 + 0.75 * diffuse) * glow * (0.8 + 0.2 * nz));
	const ramp = m.ramp;
	return ramp[Math.floor(i * ramp.length)] ?? ramp[0] ?? [0, 0, 0];
}

type Point = readonly [number, number];
type Hit = (x: number, y: number) => RGB | null;

/** Tapered limb: rounded segment shaded like a cylinder. */
function limb(
	a: Point,
	b: Point,
	ra: number,
	rb: number,
	m: Material | ((y: number) => Material),
): Hit {
	const dx = b[0] - a[0];
	const dy = b[1] - a[1];
	const len2 = dx * dx + dy * dy || 1;
	return (x, y) => {
		const s = Math.max(
			0,
			Math.min(1, ((x - a[0]) * dx + (y - a[1]) * dy) / len2),
		);
		const r = ra + (rb - ra) * s;
		const ox = x - (a[0] + dx * s);
		const oy = y - (a[1] + dy * s);
		if (ox * ox + oy * oy > r * r) return null;
		return shade(typeof m === "function" ? m(y) : m, ox / r, (oy / r) * 0.6);
	};
}

/** Ellipsoid such as the head or bust, shaded like a sphere. */
function blob(
	cx: number,
	cy: number,
	rx: number,
	ry: number,
	m: Material,
): Hit {
	return (x, y) => {
		const nx = (x - cx) / rx;
		const ny = (y - cy) / ry;
		if (nx * nx + ny * ny > 1) return null;
		return shade(m, nx * 0.9, ny * 0.9);
	};
}

// [y offset from shoulders, half width]; shared by shading and elbow clearance.
const TORSO_PROFILE: ReadonlyArray<Point> = [
	[0, 1.5],
	[0.5, 4.2],
	[1.6, 4.2],
	[2.75, 5.3],
	[3.7, 3.7],
	[4.9, 3.2],
	[6, 4],
	[7.1, 5.6],
	[8.1, 5.6],
	[8.75, 5.4],
	[9.4, 4.7],
];

function torsoWidth(k: number): number {
	for (let i = 1; i < TORSO_PROFILE.length; i++) {
		const [y0, w0] = TORSO_PROFILE[i - 1] ?? [0, 0];
		const [y1, w1] = TORSO_PROFILE[i] ?? [0, 0];
		if (k <= y1) return w0 + (w1 - w0) * smooth((k - y0) / (y1 - y0 || 1));
	}
	return 0;
}

function spine(chest: number, hips: number, k: number): number {
	return (
		chest +
		(hips - chest) * smooth(k / 9.4) +
		(chest - hips) * 0.12 * Math.sin((Math.PI * k) / 9.4)
	);
}

/** Hourglass torso from a half-width profile, curving from shoulders to swaying hips. */
function torso(top: number, chest: number, hips: number, string: number): Hit {
	// The pelvis flows straight into the thighs: no notch at the hip joint.
	const bottom = top + 9.4;
	return (x, y) => {
		if (y < top || y > bottom) return null;
		const k = y - top;
		const nx = (x - spine(chest, hips, k)) / torsoWidth(k);
		if (Math.abs(nx) > 1) return null;
		// Minimal string bikini bottom: a small pastel orange V low on the hips and thin
		// ties around them. Mostly skin, so the curve of the hips reads.
		const side = Math.abs(nx);
		if (Math.abs(k - 7.75) < string && side > 0.38)
			return shade(TRIM, nx, -0.15);
		if (k >= 7.65 && side < 0.42 - (k - 7.65) * 0.22)
			return shade(BIKINI, nx, -0.15);
		return shade(SKIN, nx, -0.15);
	};
}

const smooth = (t: number) => {
	const c = Math.max(0, Math.min(1, t));
	return c * c * (3 - 2 * c);
};

/** Pose skeleton. Numbers blend between poses so transitions ease in and out. */
export type Rig = {
	/** Pelvis offset; drives the hip sway. */
	sway: number;
	/** Upper body offset, countering the hips for an S-curve. */
	lean: number;
	/** Vertical body offset; negative is up. */
	lift: number;
	/** Shoulder tilt; positive drops her right shoulder. */
	tilt: number;
	/** Head offset beyond the lean. */
	head: number;
	/** Vertical scale about the floor: squash below 1, stretch above. */
	squash: number;
	/** Wrist targets; elbows follow from fixed bone lengths. */
	hands: [Point, Point];
	/** Ankle targets on the floor; knees follow from fixed bone lengths. */
	ankles: [Point, Point];
	/** Finger curl of her right hand, 0 open to 1 curled (beckoning). */
	grip: number;
	eyes: "open" | "wink" | "closed" | "happy";
	kiss: boolean;
	smile: boolean;
	/** Hair swing, supplied by the widget's follow-through spring. */
	hair: number;
	/** Soft-tissue follow-through from the widget's springs: bust and hips lag the body. */
	bust: Point;
	jiggle: number;
};

// Fixed bone lengths keep limbs from stretching or shrinking between poses.
// Landmarks: elbows at the navel, wrists at the crotch, fingertips mid-thigh.
export const UPPER_ARM = 4.5;
export const FOREARM = 4;
export const HAND = 2;
export const THIGH = 6;
export const SHIN = 5.5;
const SHOULDER_Y = 9.4;
const ARM_ANGLE = Math.atan(0.7); // Elbows favour an outward/upward silhouette.
const HIP_Y = 17;

const NEUTRAL: Rig = {
	sway: 0,
	lean: -0.2,
	lift: 0,
	tilt: 0,
	head: 0,
	squash: 1,
	hands: [
		[7.3, 17.6],
		[16.7, 17.6],
	],
	ankles: [
		[10.9, 28.5],
		[13.1, 28.5],
	],
	grip: 0,
	eyes: "open",
	kiss: false,
	smile: true,
	hair: 0,
	bust: [0, 0],
	jiggle: 0,
};

/** Wrist resting on the side of her hip; the hand wraps down over it, elbow out. */
export function onHip(sway: number, side: -1 | 1): Point {
	return [12 + sway + side * 5.2, 15.2];
}

const STRETCH_S = 6; // Seconds of the success stretch before the kisses.
const KISS_S = 5.5; // Unhurried reach, release, then recovery.
const POSE_HOLD = 20; // Seconds per pin-up pose, including the change.
const POSE_CHANGE = 10; // Give the extended arm arcs time to read, without whipping.

/** Calm life inside a held pose: breathing and a slow hip roll. */
function alive(t: number) {
	return {
		lift: 0.12 * Math.sin(t * 1.1),
		roll: 0.3 * Math.sin(t * 0.45),
	};
}

/** Pin-up poses she cycles through while the loop works. */
const PIN_UPS: Array<(t: number) => Rig> = [
	// Contrapposto: weight on one hip, a hand resting on it, knee turned in.
	(t) => {
		const { lift, roll } = alive(t);
		const sway = 1.5 + roll;
		return {
			...NEUTRAL,
			sway,
			lean: -0.55,
			tilt: 0.55,
			head: 0.3,
			lift,
			hands: [onHip(sway, -1), [16.9, 17.4]],
			ankles: [
				[11.2, 28.5],
				[13.4, 28.2],
			],
		};
	},
	// One hand in her hair, hip out the other way.
	(t) => {
		const { lift, roll } = alive(t);
		const sway = -1.4 + roll;
		return {
			...NEUTRAL,
			sway,
			lean: 0.5,
			tilt: -0.5,
			head: -0.4,
			lift,
			hands: [[10.2, 2.7], onHip(sway, 1)],
			ankles: [
				[10.6, 28.2],
				[12.8, 28.5],
			],
		};
	},
	// Both hands behind her head, back arched, chest out.
	(t) => {
		const { lift, roll } = alive(t);
		return {
			...NEUTRAL,
			sway: 0.7 + roll,
			lean: -0.65,
			tilt: 0.2,
			head: -0.25,
			lift,
			hands: [
				[10.4, 2.8],
				[13.6, 2.8],
			],
			ankles: [
				[11.4, 28.5],
				[12.9, 28.2],
			],
		};
	},
	// Hands on both hips, feet apart: owning it.
	(t) => {
		const { lift, roll } = alive(t);
		const sway = -0.9 + roll;
		return {
			...NEUTRAL,
			sway,
			lean: -0.3,
			tilt: -0.35,
			head: 0.25,
			lift,
			hands: [onHip(sway, -1), onHip(sway, 1)],
			ankles: [
				[10.3, 28.5],
				[13.7, 28.5],
			],
		};
	},
];

/**
 * Key poses: confident, unhurried, inviting. `t` is clock time for cycles;
 * `since` is time in this pose, used for anticipation before big actions.
 */
export function rig(pose: Pose, t: number, since = 10): Rig {
	const eyes = t % 5.3 > 5.12 ? "closed" : "open";
	switch (pose) {
		case "posing": {
			// Slow pin-up posing: she holds each pose, breathing, hips rolling
			// gently, then eases into the next over a few seconds.
			const index = Math.floor(t / POSE_HOLD);
			const phase = t % POSE_HOLD;
			const change = POSE_HOLD - POSE_CHANGE;
			const into = (phase - change) / POSE_CHANGE;
			const now = PIN_UPS[index % PIN_UPS.length];
			const next = PIN_UPS[(index + 1) % PIN_UPS.length];
			if (!now || !next) return NEUTRAL;
			const a = now(t);
			const b = next(t);
			// Gather weight opposite the coming move, then release it into the arc.
			const anticipate =
				smooth((phase - change + 0.8) / 0.35) *
				(1 - smooth((phase - change + 0.45) / 0.45));
			const held = blend(a, b, into);
			return {
				...held,
				sway: held.sway - (b.sway - a.sway) * 0.07 * anticipate,
				lean: held.lean + (b.sway - a.sway) * 0.035 * anticipate,
				lift: held.lift + 0.14 * anticipate,
				eyes: t % 9.3 < 0.4 ? "wink" : eyes,
				// A brief tucked-lip beat, then back to the knowing smile.
				smile: !(phase > 9.8 && phase < 10.6),
			};
		}
		case "peek": {
			// Anticipation, softly: hips popped, knees together, one hand on her
			// hip, fingertips slowly tracing her collarbone, chin dipped.
			const { lift, roll } = alive(t);
			const sway = 1.6 + roll;
			const trace = Math.sin(t * 0.5);
			return {
				...NEUTRAL,
				sway,
				lean: -0.3,
				tilt: 0.45,
				head: 0.35,
				lift,
				hands: [onHip(sway, -1), [13.8 + 0.6 * trace, 10 + 0.2 * trace]],
				ankles: [
					[11.4, 28.5],
					[12.7, 28.2],
				],
				eyes: t % 4.7 < 0.5 ? "closed" : eyes,
			};
		}
		case "pout": {
			// Unimpressed: both hands on her hips, slow weight shift, chin up.
			const sway = 0.8 * Math.sin(t * 1.2);
			return {
				...NEUTRAL,
				smile: false,
				sway,
				lean: -0.4,
				head: -0.25,
				hands: [onHip(sway, -1), onHip(sway, 1)],
				ankles: [
					[10.4, 28.5],
					[13.6, 28.5 - Math.max(0, Math.sin(t * 2.4)) * 0.4],
				],
			};
		}
		case "lounge": {
			// Pin-up stance: hand behind her head, the other on her hip, hips
			// rolling in a slow figure-eight, knee in, an occasional hair flip.
			const w = t * 1.1;
			const beat = t % 7;
			const gather =
				smooth((beat - 4.7) / 0.35) * (1 - smooth((beat - 5.05) / 0.35));
			const flip = smooth((beat - 5.35) / 0.55) * (1 - smooth((beat - 6) / 1));
			const sway = 1.5 + 0.45 * Math.sin(w);
			return {
				...NEUTRAL,
				sway,
				lean: -0.5,
				tilt: -0.5 + 0.2 * Math.sin(w),
				lift: 0.2 * Math.sin(2 * w),
				head: -0.4 + 0.18 * gather - 0.65 * flip,
				hands: [
					onHip(sway, -1),
					[13.8 + 2 * flip, 2.6 + 2.5 * flip - 0.5 * Math.sin(Math.PI * flip)],
				],
				ankles: [
					[11.8, 27.9],
					[13.2, 28.5],
				],
				eyes: t % 4 < 1.2 ? "wink" : eyes,
				kiss: t % 4 < 1.2,
			};
		}
		case "celebrate": {
			// Victory, savoured: a small dip of anticipation, then a slow, long
			// stretch with both arms over her head, eyes closed, hips swaying.
			// After that she blows kisses: fingertips rise to her lips with the
			// forearm upright, then the hand opens outward, away from her face.
			const { lift, roll } = alive(t);
			const sway = 1.2 + roll;
			if (since < STRETCH_S) {
				const dip = smooth(since / 0.3) * (1 - smooth((since - 0.3) / 0.3));
				const rise = smooth((since - 0.4) / 1.6);
				const low = onHip(sway, -1);
				const high = onHip(sway, 1);
				return {
					...NEUTRAL,
					sway,
					lean: -0.5,
					lift: 0.4 * dip + lift,
					squash: 1 - 0.04 * dip,
					head: -0.3 * rise,
					hands: [
						gesture(low, [10.6, 1.2], rise, -1, [7.9, SHOULDER_Y]),
						gesture(high, [13.4, 1.2], rise, 1, [15.1, SHOULDER_Y]),
					],
					eyes: rise > 0.5 ? "happy" : "open",
				};
			}
			const k = ((since - STRETCH_S) / KISS_S) % 1;
			// Reach, release, recover: both channels return to rest before wrapping.
			const recover = 1 - smooth((k - 0.8) / 0.2);
			const out = smooth((k - 0.45) / 0.35) * recover;
			const up = smooth(k / 0.45) * recover;
			const kissRig: Rig = {
				...NEUTRAL,
				sway,
				lean: -0.3,
				head: 0.2,
				lift,
				hands: [
					onHip(sway, -1),
					[
						16.6 -
							2.3 * up +
							2.8 * out -
							1.2 * Math.sin(Math.PI * up) * (1 - out),
						16.6 - 8.4 * up + 0.2 * out,
					],
				],
				eyes: k > 0.3 && k < 0.8 ? "wink" : "open",
				kiss: k > 0.3 && k < 0.75,
			};
			// Release the overhead stretch instead of snapping both wrists down.
			return since < STRETCH_S + 0.9
				? blend(
						rig("celebrate", t, STRETCH_S - 1e-3),
						kissRig,
						(since - STRETCH_S) / 0.9,
					)
				: kissRig;
		}
	}
}

/** Sweep a wrist in an arc, extending through the IK bend-side change. */
function gesture(
	a: Point,
	b: Point,
	e: number,
	side: -1 | 1,
	shoulder: Point,
): Point {
	if (
		(a[1] - shoulder[1]) * (b[1] - shoulder[1]) < 0 &&
		Math.min(a[1], b[1]) < shoulder[1] - 3
	) {
		// Changing IK branches with a folded arm pops the elbow. Unfold over
		// the whole gesture, passing outside the shoulder at full extension.
		const ax = (a[0] - shoulder[0]) * side;
		const ay = a[1] - shoulder[1];
		const bx = (b[0] - shoulder[0]) * side;
		const by = b[1] - shoulder[1];
		const start = Math.atan2(ay, ax);
		const end = Math.atan2(by, bx);
		const cross = (start + ARM_ANGLE) / (start - end);
		if (cross <= 0 || cross >= 1)
			return [a[0] + (b[0] - a[0]) * e, a[1] + (b[1] - a[1]) * e];
		const full = UPPER_ARM + FOREARM - 1e-3;
		const radius =
			e < cross
				? Math.hypot(ax, ay) + (full - Math.hypot(ax, ay)) * smooth(e / cross)
				: Math.hypot(bx, by) +
					(full - Math.hypot(bx, by)) * smooth((1 - e) / (1 - cross));
		const angle = start + (end - start) * e;
		return [
			shoulder[0] + side * Math.cos(angle) * radius,
			shoulder[1] + Math.sin(angle) * radius,
		];
	}
	const reach = Math.hypot(b[0] - a[0], b[1] - a[1]);
	const arc = 4 * e * (1 - e);
	return [
		a[0] + (b[0] - a[0]) * e + side * Math.min(1.6, reach * 0.16) * arc,
		a[1] + (b[1] - a[1]) * e - Math.min(0.8, reach * 0.06) * arc,
	];
}

/** Ease between two rigs; discrete features switch halfway. */
export function blend(from: Rig, to: Rig, k: number): Rig {
	const e = smooth(k);
	const n = (a: number, b: number) => a + (b - a) * e;
	const pt = (a: Point, b: Point): Point => [n(a[0], b[0]), n(a[1], b[1])];
	// Gestures sweep outward rather than cutting straight through the body.
	const hand = (side: 0 | 1): Point =>
		gesture(from.hands[side], to.hands[side], e, side ? 1 : -1, [
			12 + n(from.lean, to.lean) + (side ? 3.6 : -3.6),
			SHOULDER_Y + (side ? -1 : 1) * n(from.tilt, to.tilt),
		]);
	// Transfer one foot at a time; the other retains its contact target.
	const foot = (side: 0 | 1): Point => {
		const a = from.ankles[side];
		const b = to.ankles[side];
		const step = smooth(side ? (k - 0.55) / 0.45 : k / 0.45);
		const lift = Math.min(0.5, Math.hypot(b[0] - a[0], b[1] - a[1]) * 0.35);
		return [
			a[0] + (b[0] - a[0]) * step,
			a[1] + (b[1] - a[1]) * step - lift * 4 * step * (1 - step),
		];
	};
	return {
		sway: n(from.sway, to.sway),
		lean: n(from.lean, to.lean),
		lift: n(from.lift, to.lift),
		tilt: n(from.tilt, to.tilt),
		head: from.head + (to.head - from.head) * smooth((k - 0.08) / 0.92),
		squash: n(from.squash, to.squash),
		hands: [hand(0), hand(1)],
		ankles: [foot(0), foot(1)],
		grip: n(from.grip, to.grip),
		eyes: e < 0.5 ? from.eyes : to.eyes,
		kiss: e < 0.5 ? from.kiss : to.kiss,
		smile: e < 0.5 ? from.smile : to.smile,
		hair: n(from.hair, to.hair),
		bust: pt(from.bust, to.bust),
		jiggle: n(from.jiggle, to.jiggle),
	};
}

/**
 * Two-bone inverse kinematics: where the middle joint (elbow, knee) sits for
 * a root, a target and fixed bone lengths, bending toward `outward` (-1 left,
 * +1 right). Unreachable targets are pulled in to full extension.
 */
export function solve(
	root: Point,
	target: Point,
	a: number,
	b: number,
	outward: -1 | 1,
): { joint: Point; end: Point } {
	const dx = target[0] - root[0];
	const dy = target[1] - root[1];
	const full = Math.hypot(dx, dy);
	const d = Math.min(a + b - 1e-3, Math.max(Math.abs(a - b) + 1e-3, full));
	// A coincident target still needs a direction to preserve both bone lengths.
	const ux = full > 1e-6 ? dx / full : 0;
	const uy = full > 1e-6 ? dy / full : 1;
	const along = (a * a - b * b + d * d) / (2 * d);
	const h = Math.sqrt(Math.max(0, a * a - along * along));
	const mx = root[0] + ux * along;
	const my = root[1] + uy * along;
	const one: Point = [mx - uy * h, my + ux * h];
	const two: Point = [mx + uy * h, my - ux * h];
	const joint =
		(one[0] - root[0]) * outward >= (two[0] - root[0]) * outward ? one : two;
	return { joint, end: [root[0] + ux * d, root[1] + uy * d] };
}

/** The same fixed-length IK, in an arm-specific outward/upward bend plane. */
function solveArm(
	root: Point,
	target: Point,
	outward: -1 | 1,
	folded: boolean,
) {
	const c = Math.cos(ARM_ANGLE);
	const s = Math.sin(ARM_ANGLE) * outward;
	const dx = target[0] - root[0];
	const dy = target[1] - root[1];
	const x = c * dx - s * dy;
	const y = s * dx + c * dy;
	// A folded, inward wrist (collarbone gesture) keeps the elbow below it.
	// Only the extended, outward arc may change bend sides above the shoulder.
	const bend = folded && y < 0 ? (outward === 1 ? -1 : 1) : outward;
	const arm = solve([0, 0], [x, y], UPPER_ARM, FOREARM, bend);
	const world = ([x, y]: Point): Point => [
		root[0] + c * x + s * y,
		root[1] - s * x + c * y,
	];
	return { joint: world(arm.joint), end: world(arm.end) };
}

const FLOOR = 29.5;

/** Where she is drawn: canvas width, her centre column, and facing. */
export type View = {
	width: number;
	center: number;
	facing: 1 | -1;
	/** Body height the camera centres on when close. */
	focus?: number;
};

/** Canvas row of her mouth at this zoom, for effects that start at her lips. */
export function mouthRow(zoom: number, focus?: number): number {
	const sy = 0.93 * zoom;
	return camera(zoom, sy, focus) + (6.8 - FLOOR) * sy;
}

/**
 * Vertical framing; returns the canvas row of the floor line. Far away she
 * stands higher, toward the horizon. Closer, the camera centres on `focus`
 * (a body height: 4 face, 11 bust, 19 hips, 25 legs); without one it tilts
 * up just enough to keep her head in frame.
 */
function camera(zoom: number, sy: number, focus?: number): number {
	const ground = H - 0.5 - Math.max(0, 1 - zoom) * 7;
	if (focus === undefined) return Math.max(ground, 0.8 + (FLOOR - 1) * sy);
	const centred = H / 2 + (FLOOR - focus) * sy;
	return ground + (centred - ground) * smooth((zoom - 1) / 0.5);
}

/**
 * Render one frame. Positions stay fractional until sampling, so camera moves
 * and walking glide instead of snapping by whole cells.
 */
export function figure(r: Rig, t: number, zoom = 1, view?: View): Pixels {
	// Pixels per world unit. Close-ups unlock finer features below.
	const scale = 0.93 * zoom;
	const close = scale >= 1.5;
	// Strings never thinner than half a pixel, so they never flicker away.
	const string = Math.max(0.22, 0.5 / scale);
	const cx = 12;
	const pelvis = r.sway + r.jiggle * 0.65;
	// Pelvis and shoulders counter-rotate around the supporting leg.
	const hipTilt = clampJiggle(r.sway * 0.14, 0.3);
	let dy = r.lift;
	for (const side of [0, 1] as const) {
		const dx = r.ankles[side][0] - (cx + pelvis + (side ? 2.4 : -2.4));
		const reach = Math.sqrt(Math.max(0, (THIGH + SHIN - 1e-3) ** 2 - dx * dx));
		// Lower the pelvis instead of letting IK pull a planted ankle off the floor.
		dy = Math.max(
			dy,
			r.ankles[side][1] - HIP_Y - (side ? hipTilt : -hipTilt) - reach,
		);
	}
	const breath = -0.13 * Math.sin(t * 1.1);
	const at = (p: Point): Point => [p[0], p[1] + dy + breath];
	const chest = cx + r.lean;
	const face = chest + r.head;
	const shoulders = 8.6 + dy + breath;
	const hips: [Point, Point] = [
		[9.6 + pelvis, HIP_Y + dy - hipTilt],
		[14.4 + pelvis, HIP_Y + dy + hipTilt],
	];
	// Roots stay attached; mass and delayed waves gather toward the hair tips.
	const wave = (y: number) =>
		(Math.sin(y * 0.85 - t * 1.4) * 0.08 + r.hair) * Math.max(0, (y - 3) / 10);

	// Painter's order: later layers cover earlier ones.
	const layers: Hit[] = [];
	// Long copper waves falling behind her shoulders.
	layers.push((x, y) => {
		const k = y - dy;
		// Mid-back length, so hair never peeks out beside the pinched waist.
		if (k < 1.6 || k > 12.6) return null;
		const center = face + (chest - face) * smooth(k / 8) + wave(k) * 2;
		const half = k < 4 ? 2.9 : 3.2 + 0.18 * Math.sin(k * 1.4 - t * 0.65);
		const nx = (x - center) / half;
		if (Math.abs(nx) > 1) return null;
		return shade(
			HAIR,
			nx,
			-0.1,
			0.95 + 0.05 * Math.sin((x - center) * 3.1 + k * 0.7),
		);
	});
	// Legs: thighs, sheer stockings from mid-thigh, orange pumps.
	for (const side of [0, 1] as const) {
		const hip = hips[side];
		// Feet stay planted; knees follow from the fixed bone lengths.
		const { joint: knee, end: ankle } = solve(
			hip,
			r.ankles[side],
			THIGH,
			SHIN,
			side ? 1 : -1,
		);
		// Bare thigh, then the stocking's band, then sheer nylon.
		const stocking = 20.6 + dy;
		layers.push(
			limb(hip, knee, 2.9, 1.7, (y) =>
				y < stocking ? SKIN : y < stocking + 0.7 ? BIKINI : NYLON,
			),
		);
		layers.push(limb(knee, ankle, 1.7, 0.95, NYLON));
		// One solid pump per foot.
		const toe: Point = [
			ankle[0] + (side ? 0.4 : -0.4),
			Math.min(29.4, ankle[1] + 1),
		];
		layers.push(limb(ankle, toe, 0.8, 0.65, TRIM));
	}
	// Neck, behind the torso. Only its top sits in the jaw's shadow, so the
	// chin line reads without darkening her chest.
	const jaw = 7.2 + dy;
	const neck = limb([face, jaw], [chest, 9 + dy + breath], 1.05, 1.2, SKIN);
	layers.push((x, y) => {
		const hit = neck(x, y);
		if (!hit) return null;
		// Under the jaw, one ramp step darker.
		return y < jaw + 0.9 ? shade(SKIN, 0, 0, 0.62) : hit;
	});
	const body = torso(shoulders, chest, cx + pelvis, string);
	layers.push(body);
	// Arms first as geometry: the bust reacts to them before anything is drawn.
	const arms = ([0, 1] as const).map((side) => {
		const shoulder: Point = [
			chest + (side ? 3.6 : -3.6),
			SHOULDER_Y + dy + breath + (side ? -r.tilt : r.tilt),
		];
		const outward = side ? 1 : -1;
		const target = at(r.hands[side]);
		const folded = target[1] > shoulder[1] - 3;
		const arm = solveArm(shoulder, target, outward, folded);
		let elbow = arm.joint;
		let wrist = arm.end;
		// Soft elbow/body clearance, easing out of the shoulder insertion.
		// Rotate bones, not wrist targets: repeated IK projection can flip a
		// folded arm. Forearms may still deliberately pass in front of the chest.
		const k = elbow[1] - shoulders;
		if (k > 1 && k < 9.4) {
			const edge =
				spine(chest, cx + pelvis, k) + outward * (torsoWidth(k) + 0.9);
			const contact =
				smooth(((edge - elbow[0]) * outward) / 1.2) *
				smooth((elbow[1] - shoulder[1] - 0.2) / 2.8);
			const start = Math.atan2(
				elbow[1] - shoulder[1],
				(elbow[0] - shoulder[0]) * outward,
			);
			const angle = start + (Math.min(start, Math.PI / 4) - start) * contact;
			elbow = [
				shoulder[0] + outward * Math.cos(angle) * UPPER_ARM,
				shoulder[1] + Math.sin(angle) * UPPER_ARM,
			];
			const length =
				Math.hypot(target[0] - elbow[0], target[1] - elbow[1]) || 1;
			wrist = [
				elbow[0] + ((target[0] - elbow[0]) / length) * FOREARM,
				elbow[1] + ((target[1] - elbow[1]) / length) * FOREARM,
			];
		}
		// A real hand: palm and fingers continuing the forearm, shortening as
		// the fingers curl.
		const reach = Math.hypot(wrist[0] - elbow[0], wrist[1] - elbow[1]) || 1;
		const length = HAND * (1 - (side ? r.grip : 0) * 0.45);
		const tip: Point = [
			wrist[0] + ((wrist[0] - elbow[0]) / reach) * length,
			wrist[1] + ((wrist[1] - elbow[1]) / reach) * length,
		];
		return { shoulder, elbow, wrist, tip };
	});
	const bones = arms.flatMap(({ shoulder, elbow, wrist, tip }) => [
		{ a: shoulder, b: elbow, r: 1.25 },
		{ a: elbow, b: wrist, r: 1 },
		{ a: wrist, b: tip, r: 0.78 },
	]);

	// Bust physics. Gravity hangs each breast below its anchor; raising an arm
	// lifts the breast on that side with the chest muscle; an arm pressing in
	// pushes the soft tissue aside and squashes it; the two never overlap.
	const breasts = ([1, -1] as const).map((side) => {
		const arm = arms[side > 0 ? 0 : 1];
		const raised = arm
			? Math.max(0, Math.min(1, (SHOULDER_Y + dy - arm.wrist[1]) / 8))
			: 0;
		let x = chest - side * 2.25 + r.bust[0];
		let y = 11.5 + dy + breath + side * r.tilt * 0.4 + r.bust[1] - 0.7 * raised;
		let squeeze = 0;
		for (const bone of bones) {
			const dx = bone.b[0] - bone.a[0];
			const dy2 = bone.b[1] - bone.a[1];
			const k = Math.max(
				0,
				Math.min(
					1,
					((x - bone.a[0]) * dx + (y - bone.a[1]) * dy2) /
						(dx * dx + dy2 * dy2 || 1),
				),
			);
			const qx = bone.a[0] + dx * k;
			const qy = bone.a[1] + dy2 * k;
			const d = Math.hypot(x - qx, y - qy) || 1e-6;
			// Contact with the soft core, not the outline: a light touch rests
			// against her, only a real press moves anything.
			const contact = 1.6 + bone.r * 0.8;
			if (d < contact) {
				const depth = contact - d;
				x += ((x - qx) / d) * depth * 0.6;
				y += ((y - qy) / d) * depth * 0.6;
				squeeze = Math.max(squeeze, depth / contact);
			}
		}
		return { side, x, y, squeeze: Math.min(0.3, squeeze) };
	});
	const [left, right] = breasts;
	if (left && right && right.x - left.x < 4.2) {
		// Pressed together: share the overlap, and both flatten a little.
		const push = (4.2 - (right.x - left.x)) / 2;
		left.x -= push;
		right.x += push;
		left.squeeze = Math.max(left.squeeze, push / 3);
		right.squeeze = Math.max(right.squeeze, push / 3);
	}

	// Triangle bikini top: small pastel orange triangles on full bare curves, orange
	// halter strings to the neck and a gold ring between the cups.
	let band = 0;
	for (const { side, x: bx, y: by, squeeze } of breasts) {
		band += by / 2;
		const apex = by - 2.3;
		layers.push(
			// Halter ties at the sides of her neck, below the jaw.
			limb([bx, apex], [chest - side * 1.1, 8.7 + dy], string, string, TRIM),
		);
		// Full pear-shaped breasts: sloping above, round and heavy below;
		// squeezed ones get narrower and fuller in height, keeping volume.
		const width = 2.85 * (1 - squeeze);
		const height = 2.5 * (1 + squeeze * 0.6);
		layers.push((x, y) => {
			const ny = (y - by) / height;
			const taper = ny < 0 ? 0.6 + 0.4 * (1 + ny) : 1;
			const nx = (x - bx) / (width * taper);
			if (nx * nx + ny * ny > 1) return null;
			const triangle = y <= by + 1.5 && Math.abs(x - bx) <= (y - apex) * 0.56;
			return shade(triangle ? BIKINI : SKIN, nx * 0.9, ny * 0.9);
		});
	}
	layers.push(
		blob(
			chest,
			band + 0.4,
			Math.max(0.45, 0.6 / scale),
			Math.max(0.45, 0.6 / scale),
			GOLD,
		),
	);
	// Arms over the bust.
	for (const { shoulder, elbow, wrist, tip } of arms) {
		layers.push(limb(shoulder, elbow, 1.25, 1, SKIN));
		layers.push(limb(elbow, wrist, 1, 0.68, SKIN));
		layers.push(limb(wrist, tip, 0.78, 0.5, SKIN));
	}
	// Neck, face, features.
	// Round cheeks tapering to a soft chin.
	layers.push((x, y) => {
		const ny = (y - 4.6 - dy) / 2.9;
		const rx = 2.75 * (1 - 0.22 * Math.max(0, ny) ** 2);
		const nx = (x - face) / rx;
		if (nx * nx + ny * ny > 1) return null;
		return shade(SKIN, nx * 0.9, ny * 0.6);
	});
	// Fringe and face-framing locks in front.
	layers.push((x, y) => {
		const k = y - dy;
		const capY = 3.3 - 0.35 * Math.max(0, x - face);
		if (k < 1.2) return null;
		if (k < capY && Math.hypot((x - face) / 2.9, (k - 3.2) / 2.1) < 1)
			return shade(HAIR, (x - face) / 2.9, -0.6);
		for (const side of [-1, 1]) {
			const base = face + (chest - face) * smooth((k - 3) / 7);
			const lx = base + side * (2.35 + 0.18 * (k - 3)) + wave(k) * 1.4;
			if (k > 2.5 && k < 10.5 && Math.abs(x - lx) < 0.7 - (k - 2.5) * 0.04)
				return shade(HAIR, side * 0.6, 0);
		}
		return null;
	});

	// Camera: squash and stretch preserve volume; zoom scales everything.
	const sy = scale * r.squash;
	const sx = scale / Math.sqrt(r.squash);
	const cw = view?.width ?? Math.max(8, Math.round(W * zoom));
	const facing = view?.facing ?? 1;
	const wx = cx;
	const ox = view?.center ?? cw / 2;
	const wy = FLOOR;
	const oy = camera(zoom, scale, view?.focus);
	const pixels: Pixels = Array.from({ length: H }, () =>
		Array<RGB | null>(cw).fill(null),
	);
	// Only sample columns she can occupy.
	const reach = W * zoom * 0.6;
	const from = Math.max(0, Math.floor(ox - reach));
	const to = Math.min(cw, Math.ceil(ox + reach));
	const samples = close ? 2 : SAMPLES;
	const step = 1 / samples;
	const total = samples * samples;
	const owner = new Array<number>(total);
	const colors = new Array<RGB>(total);
	for (let py = 0; py < H; py++) {
		const row = pixels[py];
		if (!row) continue;
		for (let px = from; px < to; px++) {
			let hits = 0;
			for (let j = 0; j < samples; j++)
				for (let i = 0; i < samples; i++) {
					const x = wx + (facing * (px + (i + 0.5) * step - ox)) / sx;
					const y = wy + (py + (j + 0.5) * step - oy) / sy;
					for (let l = layers.length - 1; l >= 0; l--) {
						const color = layers[l]?.(x, y);
						if (!color) continue;
						owner[hits] = l;
						colors[hits] = color;
						hits++;
						break;
					}
				}
			if (hits / total < COVERAGE) continue;
			// Each pixel belongs to one surface: the layer covering most samples.
			let best = -1;
			let bestCount = 0;
			for (let n = 0; n < hits; n++) {
				let count = 0;
				for (let m = 0; m < hits; m++) if (owner[m] === owner[n]) count++;
				if (count > bestCount) {
					bestCount = count;
					best = owner[n] ?? -1;
				}
			}
			// Then the ramp colour most of its samples share: pixels stay palette
			// colours instead of blended in-betweens.
			let pick: RGB | undefined;
			let pickCount = 0;
			for (let n = 0; n < hits; n++) {
				if (owner[n] !== best) continue;
				const c = colors[n];
				let count = 0;
				for (let m = 0; m < hits; m++)
					if (owner[m] === best && colors[m] === c) count++;
				if (c && count > pickCount) {
					pickCount = count;
					pick = c;
				}
			}
			if (pick) row[px] = pick;
		}
	}

	// Crisp features on top, sized by how close the camera is.
	const toPixel = (x: number, y: number): Point => [
		ox + facing * (x - wx) * sx,
		oy + (y - wy) * sy,
	];
	const paint = (x: number, y: number, color: RGB) => {
		const row = pixels[Math.floor(y)];
		const col = Math.floor(x);
		if (row?.[col]) row[col] = color;
	};
	/** Paint `n` pixels centred on a point. */
	const span = ([x, y]: Point, n: number, color: RGB, dy = 0) => {
		const start = Math.round(x - n / 2);
		for (let i = 0; i < n; i++) paint(start + i, y + dy, color);
	};
	const shut = (right: boolean) =>
		r.eyes === "closed" || r.eyes === "happy" || (right && r.eyes === "wink");
	for (const [ex, right] of [
		[face - 1.1, false],
		[face + 1.1, true],
	] as const) {
		const eye = toPixel(ex, 4.9 + dy);
		if (scale >= 2) {
			// Lash line over sclera, green iris and pupil.
			span(eye, 3, LASH_DARK, -1);
			if (shut(right)) continue;
			span(eye, 3, SCLERA);
			span(eye, 1, IRIS);
		} else if (close) {
			// Lash line over a light eye with a one-pixel green iris; both irises
			// sit on the same side so the gaze stays consistent, never a blob.
			span(eye, 2, LASH_DARK, -1);
			if (!shut(right)) {
				span(eye, 2, SCLERA);
				span([eye[0] + 0.5, eye[1]], 1, IRIS);
			}
		} else span(eye, 1, shut(right) ? LASH : EYE);
		if (close) {
			// Arched brows lifting toward the outer ends: a confident look.
			const [bx, by] = toPixel(ex, 3.8 + dy);
			const outward = facing * (right ? 1 : -1);
			paint(bx, by, BROW);
			paint(bx + outward, by - 1, BROW);
			if (scale >= 2) paint(bx - outward, by, BROW);
		}
	}
	// Mouth: one clean row of lips, wider up close with a fuller lower lip;
	// puckered and darker for a kiss, shorter in a pout.
	const mouth = toPixel(face, 6.3 + dy);
	const lips = r.kiss
		? 2
		: Math.max(2, Math.round(scale * (r.smile ? 1.5 : 1.1)));
	span(mouth, lips, r.kiss ? KISS : LIPS);
	if (scale >= 2 && !r.kiss)
		span(mouth, Math.max(1, lips - 2), LOWER_LIP, r.smile ? 1 : 0);
	if (close && r.smile && !r.kiss)
		// A knowing half-smile: one corner lifts.
		paint(Math.round(mouth[0] - lips / 2) + lips, mouth[1] - 1, LIPS);
	if (scale >= 1.3)
		span(toPixel(cx + r.sway * 0.4, 14.8 + dy), 1, SKIN.ramp[1] ?? LIPS);
	return pixels;
}

export type CompanionState = {
	status: RunStatus;
	pending: boolean;
	attempts: number;
	turns: number;
	budgets: Budgets;
	/** Label and finish time of the gate that failed the latest attempt. */
	failed: { gate: string; at: number } | null;
	updatedAt: number;
};
export type Companion = Component & { dispose(): void };

const POUT_MS = 7_000;
export const AFTERGLOW_MS = 40_000;
const BLEND_S = 2.5; // Calm ease between poses when the loop state changes.
const SEQUENCE = 96; // Seconds in the posing camera sequence.
const CAPTION_MS = 6_000;

export const MIN_ZOOM = 0.55;
export const MAX_ZOOM = 3.4;

/** A camera setup: how close, and which body height it centres on. */
export type Shot = { zoom: number; focus: number };

/** Where the camera wants to be: slow, intimate close-ups on face, torso and hips. */
export function framing(pose: Pose, t: number, since: number): Shot {
	switch (pose) {
		case "posing": {
			// Establish the silhouette, then deliberately dolly into her expression.
			// Every shot joins continuously, including the end of the sequence.
			const beat = t % SEQUENCE;
			const glide = (from: number, to: number, start: number, length: number) =>
				from + (to - from) * smooth((beat - start) / length);
			if (beat < 6)
				return { zoom: glide(1.7, 3.1, 0, 6), focus: glide(11, 5, 0, 6) };
			if (beat < 24) return { zoom: glide(3.1, 3.2, 6, 18), focus: 5 };
			if (beat < 42)
				return { zoom: glide(3.2, 3, 24, 18), focus: glide(5, 11.5, 24, 18) };
			if (beat < 60) return { zoom: 3, focus: glide(11.5, 17, 42, 18) };
			if (beat < 78) return { zoom: 3, focus: 17 };
			if (beat < 90) return { zoom: 3, focus: glide(17, 5, 78, 12) };
			return { zoom: glide(3, 1.7, 90, 6), focus: glide(5, 11, 90, 6) };
		}
		case "peek":
			// A slow push in on her face and beckoning hand.
			return { zoom: 2.4 + 0.8 * smooth(since / 20), focus: 8.5 };
		case "pout":
			// Close on her unimpressed face.
			return { zoom: 3, focus: 6 };
		case "lounge":
			// A slow pan between her face and her hips.
			return { zoom: 2.8, focus: 11 + 6 * Math.sin(t * 0.08) };
		case "celebrate":
			// Medium for the stretch, her arms over her head in frame, then
			// close on her face for the kisses.
			return {
				zoom: 1.8 + 1.2 * smooth((since - STRETCH_S) / 3),
				focus: 8 - 1.5 * smooth((since - STRETCH_S) / 3),
			};
	}
}

const clampJiggle = (value: number, limit: number) =>
	Math.max(-limit, Math.min(limit, value));

function poseOf(state: CompanionState, now: number): Pose {
	if (state.status === "succeeded") return "celebrate";
	if (state.status !== "active") return "lounge";
	if (state.pending) return "peek";
	if (state.failed && now - state.failed.at < POUT_MS) return "pout";
	return "posing";
}

function caption(pose: Pose, state: CompanionState, now: number): string {
	const gate = state.failed?.gate ?? "your gates";
	const lines: Record<Pose, string[]> = {
		posing: [
			"keep going. I'm watching.",
			"show me what you've got",
			"I like it when you take your time",
			"don't stop now, darling",
		],
		peek: [
			`come closer… let's see if ${gate} lets you in`,
			"come here. show me.",
		],
		pout: [
			`${gate} said no. try again. harder.`,
			"is that all you've got?",
			"I expected more from you",
		],
		lounge: ["take your time. I'll wait.", "come back when you're ready"],
		celebrate: ["now that's how it's done ♥", "come here, winner"],
	};
	const options = lines[pose];
	return options[Math.floor(now / CAPTION_MS) % options.length] ?? "";
}

function budget(used: number, limit: number | null): string {
	return limit === null ? `${used}` : `${used}/${limit}`;
}

/** Animated widget: she struts across the editor while the loop runs. */
export function createCompanion(
	tui: TUI,
	theme: Theme,
	state: () => CompanionState,
	now: () => number = Date.now,
	displayScale = 1,
): Companion {
	let disposed = false;
	let timer: ReturnType<typeof setTimeout> | undefined;
	const started = now();
	let last = started;
	const hearts: Array<{ x: number; y: number; born: number; drift: number }> =
		[];
	let nextHeart = started;
	// Pose-to-pose easing and a damped spring for hair follow-through.
	let pose: Pose | undefined;
	let changedAt = started;
	let from: Rig | undefined;
	let shown: Rig | undefined;
	let hair = 0;
	let hairSpeed = 0;
	// Camera dolly: zoom eases toward a per-pose framing on a damped spring.
	let zoom = 1;
	let zoomSpeed = 0;
	let focus = 15;
	let focusSpeed = 0;
	// Soft tissue: underdamped springs anchored to the body, so bust and hips
	// lag, overshoot and settle after each step and turn.
	let bustX = 0;
	let bustY = 0;
	let bustVX = 0;
	let bustVY = 0;
	let hips = 0;
	let hipsV = 0;

	const schedule = () => {
		if (disposed || timer) return;
		timer = setTimeout(() => {
			timer = undefined;
			if (!disposed) tui.requestRender();
		}, 80);
		timer.unref?.();
	};

	return {
		render(width) {
			if (disposed) return [];
			const time = now();
			const current = state();
			const hidden =
				current.status === "stopped" ||
				(current.status === "succeeded" &&
					time - current.updatedAt > AFTERGLOW_MS);
			if (hidden || width < 1) {
				clearTimeout(timer);
				timer = undefined;
				return [];
			}
			const outputWidth = width;
			width = Math.max(1, Math.floor(outputWidth / displayScale));
			schedule();
			const target = poseOf(current, time);
			if (target !== pose) {
				from = shown;
				pose = target;
				changedAt = time;
			}
			const t = (time - started) / 1000;
			const dt = Math.max(0, Math.min(0.5, (time - last) / 1000));
			last = time;
			const since = (time - changedAt) / 1000;
			let body = rig(pose, t, since);
			if (from && since < BLEND_S) body = blend(from, body, since / BLEND_S);
			// Counterbalance couples the chest to the pelvis, not an independent jiggle.
			const chestAnchor = body.lean - body.sway * 0.2 + body.tilt * 0.18;
			const riseAnchor = body.lift - 0.13 * Math.sin(t * 1.1);
			const hairAnchor = body.lean + body.head - body.sway * 0.18;
			if (!shown) {
				// Start at rest: no artificial impulse on the first rendered frame.
				hair = hairAnchor;
				bustX = chestAnchor;
				bustY = riseAnchor;
				hips = body.sway;
			}
			// Fixed small sub-steps keep the stiff springs stable even when a
			// frame arrives late.
			const substeps = Math.max(1, Math.ceil(dt / 0.02));
			const h = dt / substeps;
			for (let n = 0; n < substeps; n++) {
				// Hair is heaviest and slowest; supported tissue settles sooner.
				hairSpeed += ((hairAnchor - hair) * 20 - hairSpeed * 5.8) * h;
				hair += hairSpeed * h;
				bustVX += ((chestAnchor - bustX) * 36 - bustVX * 6.2) * h;
				bustX += bustVX * h;
				bustVY += ((riseAnchor - bustY) * 32 - bustVY * 5.8) * h;
				bustY += bustVY * h;
				hipsV += ((body.sway - hips) * 24 - hipsV * 6.4) * h;
				hips += hipsV * h;
			}
			// Soft tissue reads only up close: far away it would just be noise, so
			// the follow-through fades in with the zoom and grows in close-ups.
			const soft = smooth((zoom - 1.2) / 1.4);
			const gain = 1.3 + 1.8 * soft;
			shown = {
				...body,
				hair: body.hair + clampJiggle((hair - hairAnchor) * 2, 1.1),
				bust: [
					clampJiggle((bustX - chestAnchor) * gain, 0.65 * soft),
					clampJiggle((bustY - riseAnchor) * gain, 0.7 * soft),
				],
				jiggle: clampJiggle((hips - body.sway) * gain, 0.9 * soft),
			};
			// Critically damped springs, slow on purpose: the camera glides.
			const shot = framing(pose, t, since);
			zoomSpeed += ((shot.zoom - zoom) * 0.5 - zoomSpeed * 1.42) * dt;
			zoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, zoom + zoomSpeed * dt));
			focusSpeed += ((shot.focus - focus) * 0.5 - focusSpeed * 1.42) * dt;
			focus += focusSpeed * dt;
			// She stays put; a slow lateral drift keeps the frame alive.
			const x = width / 2 + Math.sin(t * 0.06) * Math.min(4, width / 10);

			// Hearts float up from her lips, more of them when she is pleased.
			// A heart only travels with a blown kiss.
			if (shown.kiss && time >= nextHeart) {
				hearts.push({
					x,
					y: mouthRow(zoom, focus),
					born: time,
					drift: Math.random() * 2 - 1,
				});
				nextHeart = time + 700;
			}
			while (hearts.length && time - (hearts[0]?.born ?? 0) > 2_500)
				hearts.shift();

			const canvas = figure(shown, t, zoom, {
				width,
				center: x,
				facing: 1,
				focus,
			});
			for (const heart of hearts) {
				const age = (time - heart.born) / 1000;
				const hx = Math.round(heart.x + heart.drift * age * 2);
				const hy = Math.round(heart.y - age * 4);
				for (const [dx, dy] of [
					[-1, 0],
					[1, 0],
					[-1, 1],
					[0, 1],
					[1, 1],
					[0, 2],
				] as const) {
					const row = canvas[hy + dy];
					if (row && hx + dx >= 0 && hx + dx < width && !row[hx + dx])
						row[hx + dx] = HEART;
				}
			}

			const lines: string[] = [];
			const pixelHeight = Math.ceil(H * displayScale);
			const pixel = (x: number, y: number) =>
				y < pixelHeight
					? canvas[Math.floor(y / displayScale)]?.[Math.floor(x / displayScale)]
					: undefined;
			for (let y = 0; y < pixelHeight; y += 2) {
				let end = outputWidth;
				while (end > 0 && !pixel(end - 1, y) && !pixel(end - 1, y + 1)) end--;
				let line = "";
				for (let i = 0; i < end; i++) {
					const top = pixel(i, y);
					const bottom = pixel(i, y + 1);
					if (top && bottom)
						line += theme.style("▀", {
							fg: rgbColor(...top),
							bg: rgbColor(...bottom),
						});
					else if (top) line += theme.style("▀", { fg: rgbColor(...top) });
					else if (bottom)
						line += theme.style("▄", { fg: rgbColor(...bottom) });
					else line += " ";
				}
				lines.push(line);
			}

			// One subtle line: her remark on the left, run facts on the right.
			const facts = [
				`${ICON.gate} ${budget(current.attempts, current.budgets.attempts)}`,
				`${ICON.turn} ${budget(current.turns, current.budgets.turns)}`,
				...(current.failed && current.status !== "succeeded"
					? [`${ICON.failed} ${current.failed.gate}`]
					: []),
			].join("  ");
			const remark = caption(pose, current, time);
			const gap = outputWidth - visibleWidth(remark) - visibleWidth(facts);
			lines.push(
				truncateToWidth(
					gap >= 2
						? `${theme.fg("accent", remark)}${" ".repeat(gap)}${theme.fg("dim", facts)}`
						: theme.fg("accent", remark),
					outputWidth,
				),
			);
			return lines;
		},
		invalidate() {
			if (disposed) return;
			clearTimeout(timer);
			timer = undefined;
			tui.requestRender();
		},
		dispose() {
			disposed = true;
			clearTimeout(timer);
			timer = undefined;
		},
	};
}