repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/loop/src/companion.ts
RawFile outline
- Pose line 13
- RGB line 14
- Pixels line 15
- W line 18
- H line 19
- SAMPLES line 20
- COVERAGE line 21
- Material line 28
- SKIN line 31
- HAIR line 41
- BIKINI line 50
- TRIM line 58
- NYLON line 66
- GOLD line 73
- EYE line 81
- LASH line 82
- LIPS line 83
- LASH_DARK line 84
- SCLERA line 85
- IRIS line 86
- BROW line 87
- LOWER_LIP line 88
- KISS line 89
- HEART line 90
- LIGHT line 92
- shade line 99
- Point line 107
- Hit line 108
- limb line 111
- blob line 135
- torso line 151
- smooth line 197
- Rig line 204
- UPPER_ARM line 235
- FOREARM line 236
- HAND line 237
- THIGH line 238
- SHIN line 239
- SHOULDER_Y line 240
- HIP_Y line 241
- NEUTRAL line 243
- onHip line 268
- STRETCH_S line 272
- KISS_S line 273
- POSE_HOLD line 274
- POSE_CHANGE line 275
- alive line 278
- PIN_UPS line 286
- rig line 365
- blend line 492
- n line 494
- pt line 495
- pair line 496
- solve line 524
- FLOOR line 548
- View line 551
- mouthRow line 560
- camera line 571
- figure line 582
- at line 589
- wave line 599
- toPixel line 863
- paint line 867
- span line 873
- shut line 877
- CompanionState line 924
- Companion line 934
- POUT_MS line 936
- AFTERGLOW_MS line 937
- BLEND_S line 938
- SEQUENCE line 939
- CAPTION_MS line 940
- MIN_ZOOM line 942
- MAX_ZOOM line 943
- Shot line 946
- framing line 949
- glide line 956
- clampJiggle line 983
- poseOf line 986
- caption line 994
- budget line 1019
- createCompanion line 1024
- born line 1034
- drift line 1034
- x line 1034
- y line 1034
- schedule line 1058
- render line 1071
- invalidate line 1211
- dispose line 1217
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);
};
}
/** Hourglass torso from a half-width profile, curving from shoulders to swaying hips. */
function torso(top: number, chest: number, hips: number, string: number): Hit {
// [y offset from shoulders, half width]
const profile: Array<[number, number]> = [
// Full, healthy curves: soft shoulders, generous bust and hips, a
// defined but natural waist.
[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],
];
// 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;
let w = 0;
for (let i = 1; i < profile.length; i++) {
const [y0, w0] = profile[i - 1] ?? [0, 0];
const [y1, w1] = profile[i] ?? [0, 0];
if (k <= y1) {
w = w0 + (w1 - w0) * smooth((k - y0) / (y1 - y0 || 1));
break;
}
}
// The spine bends in an S: shoulders over the lean, pelvis over the sway.
const center = chest + (hips - chest) * smooth(k / 9.4);
const nx = (x - center) / w;
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. */
/** 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 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 = 3.5; // Seconds per blown kiss.
const POSE_HOLD = 18; // Seconds per pin-up pose, including the change.
const POSE_CHANGE = 3.5; // Seconds to ease from one pose into the next.
/** 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.4,
tilt: 0.4,
head: 0.2,
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.4,
tilt: -0.4,
head: -0.3,
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.5,
head: -0.2,
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,
head: 0.15,
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 into = smooth(
((t % POSE_HOLD) - (POSE_HOLD - POSE_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 held = blend(now(t), next(t), into);
return { ...held, eyes: t % 9.3 < 0.4 ? "wink" : eyes };
}
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 flip =
smooth(((t % 7) - 5.4) / 0.6) * (1 - smooth(((t % 7) - 6.3) / 0.6));
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.5 * flip,
hands: [onHip(sway, -1), [13.8 + 2 * flip, 2.6 + 2.5 * 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: [
[low[0] + (10.6 - low[0]) * rise, low[1] + (1.2 - low[1]) * rise],
[
high[0] + (13.4 - high[0]) * rise,
high[1] + (1.2 - high[1]) * rise,
],
],
eyes: rise > 0.5 ? "happy" : "open",
};
}
const k = ((since - STRETCH_S) / KISS_S) % 1;
// 0 → 0.45 fingertips to lips, 0.45 → 0.8 the kiss travels out, then rest.
const out = smooth((k - 0.45) / 0.35);
const up = smooth(k / 0.45) * (1 - smooth((k - 0.8) / 0.2));
return {
...NEUTRAL,
sway,
lean: -0.3,
head: 0.2,
lift,
hands: [
onHip(sway, -1),
[16.6 - 2.3 * up + 1.6 * 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,
};
}
}
}
/** 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])];
const pair = (a: [Point, Point], b: [Point, Point]): [Point, Point] => [
pt(a[0], b[0]),
pt(a[1], b[1]),
];
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: n(from.head, to.head),
squash: n(from.squash, to.squash),
hands: pair(from.hands, to.hands),
ankles: pair(from.ankles, to.ankles),
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) || 1e-6;
const d = Math.min(a + b - 1e-3, Math.max(Math.abs(a - b) + 1e-3, full));
const ux = dx / full;
const uy = dy / full;
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] };
}
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 dy = r.lift;
const at = (p: Point): Point => [p[0], p[1] + dy];
const cx = 12;
const chest = cx + r.lean;
const face = chest + r.head;
const shoulders = 8.6 + dy;
const hips: [Point, Point] = [
[9.6 + r.sway, HIP_Y + dy],
[14.4 + r.sway, HIP_Y + dy],
];
// Hair trails the body: the swing grows toward the tips.
const wave = (y: number) =>
(Math.sin(y * 1.1 + t * 3) * 0.3 + r.hair) * Math.max(0, (y - 5) / 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.4 * Math.sin(k * 1.4 + t * 2.4);
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 * 3.1 + k * 0.7 + t));
});
// 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], 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;
});
layers.push(torso(shoulders, chest, cx + r.sway + r.jiggle, string));
// 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 + (side ? -r.tilt : r.tilt),
];
// Elbows point outward; bone lengths never change.
const { joint: elbow, end: wrist } = solve(
shoulder,
at(r.hands[side]),
UPPER_ARM,
FOREARM,
side ? 1 : -1,
);
// 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 + 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, 1);
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;
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": {
// A calm 96 s sequence of long, slow close-ups: her face, her bust,
// a glide down to her hips, her hips, then a glide back up to her
// face. Only a brief medium shot; never the whole figure.
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: 1.7, focus: 11 };
if (beat < 24) return { zoom: 3.2, focus: 5 };
if (beat < 42) return { zoom: 3, focus: 11.5 };
if (beat < 60) return { zoom: 3, focus: glide(11.5, 17, 42, 18) };
if (beat < 78) return { zoom: 3.2, focus: 17 };
return { zoom: 3, focus: glide(17, 5, 78, 18) };
}
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 since < STRETCH_S
? { zoom: 1.8, focus: 8 }
: { zoom: 3, focus: 6.5 };
}
}
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,
): 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 = (fast: boolean) => {
if (disposed || timer) return;
timer = setTimeout(
() => {
timer = undefined;
if (!disposed) tui.requestRender();
},
fast ? 80 : 1_000,
);
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);
schedule(!hidden);
if (hidden || width < 1) return [];
const target = poseOf(current, time);
if (target !== pose) {
from = shown;
pose = target;
changedAt = time;
}
const t = (time - started) / 1000;
const dt = 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);
const pull = -body.sway * 0.3;
// 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++) {
hairSpeed += ((pull - hair) * 38 - hairSpeed * 6) * h;
hair += hairSpeed * h;
bustVX += ((body.lean - bustX) * 55 - bustVX * 3.2) * h;
bustX += bustVX * h;
bustVY += ((body.lift - bustY) * 45 - bustVY * 2.6) * h;
bustY += bustVY * h;
hipsV += ((body.sway - hips) * 50 - hipsV * 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 + 1.6 * soft;
shown = {
...body,
hair,
bust: [
clampJiggle((bustX - body.lean) * gain, 0.8 * soft),
clampJiggle((bustY - body.lift) * gain, 1 * 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[] = [];
for (let y = 0; y < H; y += 2) {
const upper = canvas[y] ?? [];
const lower = canvas[y + 1] ?? [];
let end = width;
while (end > 0 && !upper[end - 1] && !lower[end - 1]) end--;
let line = "";
for (let i = 0; i < end; i++) {
const top = upper[i];
const bottom = lower[i];
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 = width - visibleWidth(remark) - visibleWidth(facts);
lines.push(
truncateToWidth(
gap >= 2
? `${theme.fg("accent", remark)}${" ".repeat(gap)}${theme.fg("dim", facts)}`
: theme.fg("accent", remark),
width,
),
);
return lines;
},
invalidate() {
if (disposed) return;
clearTimeout(timer);
timer = undefined;
tui.requestRender();
},
dispose() {
disposed = true;
clearTimeout(timer);
timer = undefined;
},
};
}