pixeltation/src/meditations/desert-sunrise/deer.ts

435 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { hex, mix, type RGB } from '../../engine/color';
import { hash } from '../../engine/rng';
import { sampleShape, Stamp } from '../../engine/stamp';
import type { Surface } from '../../engine/Surface';
import { clamp01, ease, pathTrack, track } from '../../engine/Timeline';
import { floorSunAt } from './stream';
import { sunlit, TIMES, type Frame, type Thing } from './timeline';
import { F, project, streamHalf, streamX } from './world';
/**
* A mule deer doe and her family come down the canyon in the blue before dawn. They stop at the
* stream to drink, walk on toward the camera, drink again as the sun breaks through the arch,
* then wade across and wander off to the left.
*/
/** A point on the right bank, `off` meters back from the water's edge. */
const bank = (z: number, off: number): [number, number] => [streamX(z) + streamHalf(z) + off, z];
type Pose = 'look' | 'graze';
interface Move {
t0: number;
t1: number;
pts: [number, number][];
/** Brief stops along the way: [start (s into the move), length (s), what the deer does]. */
pauses: [number, number, Pose][];
}
const T = TIMES.deer;
const MOVES: Move[] = [
{
t0: T,
t1: T + 46,
pts: [bank(74, 1.2), bank(52, 1.0), bank(38, 0.7), bank(29, 0.18)],
pauses: [
[13, 3.5, 'look'],
[29, 4, 'graze'],
],
},
{
t0: T + 71,
t1: T + 108,
pts: [bank(29, 0.18), bank(20, 0.9), bank(12, 0.8), bank(7.2, 0.12)],
pauses: [[13, 3, 'look']],
},
{
t0: T + 134,
t1: T + 156,
pts: [bank(7.2, 0.12), [streamX(6.4), 6.4], [streamX(5.9) - streamHalf(5.9) - 0.5, 5.9], [-3.5, 5.6], [-7.5, 5.4]],
pauses: [],
},
];
/** Head down to drink (1) or raised (0), for the doe; the others follow her lead with a lag. */
const DRINK = track([
[T + 46, 0],
[T + 49, 1],
[T + 57, 1],
[T + 59, 0.15],
[T + 62, 0.15],
[T + 64, 1],
[T + 69, 1],
[T + 71, 0],
[T + 108, 0],
[T + 111, 1],
[T + 117, 1],
// The sun breaks through the arch: she lifts her head and looks up the canyon at it.
[T + 119, 0],
[T + 125, 0],
[T + 127, 1],
[T + 132, 1],
[T + 134, 0],
]);
// ---------------------------------------------------------------------------
// Pacing along each move
// ---------------------------------------------------------------------------
const PACE_DT = 0.05;
/** How much of the way through a pause the deer is, 0 (walking) – 1 (stopped), easing in and out. */
function pauseAmount(m: Move, tm: number): number {
let v = 0;
for (const [p0, len] of m.pauses) {
const ramp = 0.8;
const k = Math.min(clamp01((tm - p0 + ramp) / ramp), clamp01((p0 + len + ramp - tm) / ramp));
v = Math.max(v, ease.sine(k));
}
return v;
}
/**
* Progress 0–1 along each move: speed eases up at the start, down at the end and around each
* pause, and the walking in between runs a touch quicker so every move still arrives on time.
*/
const PACE: Float32Array[] = MOVES.map((m) => {
const d = m.t1 - m.t0;
const n = Math.ceil(d / PACE_DT) + 1;
const out = new Float32Array(n);
for (let i = 1; i < n; i++) {
const tm = (i - 0.5) * PACE_DT;
const ends = Math.min(1, tm / 1.2, (d - tm) / 1.2);
out[i] = out[i - 1] + ease.sine(clamp01(ends)) * (1 - pauseAmount(m, tm)) * PACE_DT;
}
const total = out[n - 1];
for (let i = 0; i < n; i++) out[i] /= total;
return out;
});
function along(t: number, move: number): number {
const m = MOVES[move];
const tab = PACE[move];
const f = (clamp01((t - m.t0) / (m.t1 - m.t0)) * (m.t1 - m.t0)) / PACE_DT;
const i = Math.min(tab.length - 2, Math.floor(f));
return tab[i] + (tab[i + 1] - tab[i]) * (f - i);
}
/** The pose a deer is holding during a pause, with its strength 0–1. */
function pausePose(t: number, move: number): [Pose, number] | undefined {
const m = MOVES[move];
const tm = t - m.t0;
for (const [p0, len, pose] of m.pauses) {
const k = Math.min(clamp01((tm - p0) / 0.9), clamp01((p0 + len - tm) / 0.9));
if (k > 0) return [pose, ease.sine(k)];
}
return undefined;
}
// ---------------------------------------------------------------------------
// The herd
// ---------------------------------------------------------------------------
interface Deer {
lag: number;
size: number;
coat: RGB;
paths: ((u: number) => [number, number])[];
/** Distance walked (m) along each move, sampled evenly in its path parameter. */
lengths: Float32Array[];
seed: number;
}
const LENGTH_STEPS = 256;
function makeDeer(lag: number, dz: number, dOff: number, size: number, coat: string, seed: number): Deer {
const paths = MOVES.map((m, mi) => {
const pts = m.pts.map(([X, z], i): [number, number] => {
// Followers stand a little further up the bank; on the final crossing they spread out.
const zz = z + dz * (mi === 2 && i > 0 ? 0.4 : 1);
return [X + (streamX(zz) - streamX(z)) + dOff * (mi === 2 ? 0.5 : 1), zz];
});
return pathTrack(pts.map(([X, z], i) => [i / (pts.length - 1), X, z] as const));
});
const lengths = paths.map((path) => {
const out = new Float32Array(LENGTH_STEPS + 1);
let [px, pz] = path(0);
for (let i = 1; i <= LENGTH_STEPS; i++) {
const [x, z] = path(i / LENGTH_STEPS);
out[i] = out[i - 1] + Math.hypot(x - px, z - pz);
px = x;
pz = z;
}
return out;
});
return { lag, size, coat: hex(coat), paths, lengths, seed };
}
const HERD: Deer[] = [
makeDeer(0, 0, 0, 1, '#9c7a5c', 1),
makeDeer(3.5, 1.6, 0.55, 0.88, '#94765a', 2),
makeDeer(6.5, 3.1, 0.15, 0.66, '#b08462', 3),
makeDeer(9, 2.3, 1.0, 0.62, '#aa8060', 4),
];
/** Which move a deer is on (or last finished) at its own time tt. */
function moveAt(tt: number): number {
let move = 0;
for (let i = 0; i < MOVES.length; i++) if (tt >= MOVES[i].t0) move = i;
return move;
}
/** Where a deer is (world X, z). */
function place(d: Deer, t: number): { X: number; z: number; move: number } {
const tt = t - d.lag;
const move = moveAt(tt);
const [X, z] = d.paths[move](along(tt, move));
return { X, z, move };
}
/** Total distance a deer has walked by time t (m); the walk cycle is driven by this, so hooves never skate. */
function walked(d: Deer, t: number): number {
const tt = t - d.lag;
let s = 0;
for (let i = 0; i < MOVES.length && tt > MOVES[i].t0; i++) {
const tab = d.lengths[i];
const f = along(tt, i) * LENGTH_STEPS;
const j = Math.min(LENGTH_STEPS - 1, Math.floor(f));
s += tab[j] + (tab[j + 1] - tab[j]) * (f - j);
}
return s;
}
/** Screen-space direction of travel during a move: +1 right, -1 left. */
function moveDir(d: Deer, move: number, u: number): number {
const a = d.paths[move](Math.max(0, u - 0.02));
const b = d.paths[move](Math.min(1, u + 0.02));
return project(b[0], b[1])[0] >= project(a[0], a[1])[0] ? 1 : -1;
}
function facing(d: Deer, t: number): number {
const tt = t - d.lag;
const move = moveAt(tt);
const m = MOVES[move];
const dir = moveDir(d, move, Math.min(along(tt, move), 0.98));
if (move === 0 || tt > m.t0 + 1.6) return dir;
// Turn around at the start of a move if it heads the other way.
const prev = moveDir(d, move - 1, 0.98);
return prev + (dir - prev) * ease.sine(clamp01((tt - m.t0 + 0.2) / 1.6));
}
// ---------------------------------------------------------------------------
// Drawing
// ---------------------------------------------------------------------------
interface DeerPal {
coat: RGB;
dark: RGB;
light: RGB;
muzzle: RGB;
nose: RGB;
ear: RGB;
hoof: RGB;
}
/** Distance from p to a tapering limb running from a to b; <= 0 means inside. */
function limb(lx: number, ly: number, ax: number, ay: number, bx: number, by: number, r0: number, r1: number): number {
const vx = bx - ax;
const vy = by - ay;
const u = Math.max(0, Math.min(1, ((lx - ax) * vx + (ly - ay) * vy) / (vx * vx + vy * vy)));
return Math.hypot(lx - ax - vx * u, ly - ay - vy * u) - (r0 + (r1 - r0) * u);
}
/** Fraction of each leg's cycle spent with the hoof planted on the ground. */
const STANCE = 0.62;
/** Distance covered per full walk cycle, in body lengths of 10 cm × the deer's size. */
const STRIDE = 9.5;
const GROUND = 8.5;
/** Hoof position relative to its hip at cycle point c: planted and sweeping back, then lifted and swung forward. */
function hoof(c: number, reach: number, lift: number): [number, number] {
if (c < STANCE) return [reach * (1 - (2 * c) / STANCE), 0];
const w = (c - STANCE) / (1 - STANCE);
return [reach * (2 * ease.sine(w) - 1), -lift * Math.sin(Math.PI * w)];
}
/**
* Two-bone leg: where the joint sits between hip and hoof. `bend` +1 puts it forward (a foreleg's
* knee), -1 behind (a hind leg's hock).
*/
function joint(hx: number, hy: number, fx: number, fy: number, l1: number, l2: number, bend: number): [number, number] {
const dx = fx - hx;
const dy = fy - hy;
const d = Math.max(1e-3, Math.hypot(dx, dy));
const dd = Math.min(d, (l1 + l2) * 0.999);
const a = (l1 * l1 - l2 * l2 + dd * dd) / (2 * dd);
const h = Math.sqrt(Math.max(0, l1 * l1 - a * a));
const ux = dx / d;
const uy = dy / d;
return [hx + ux * a + uy * h * bend, hy + uy * a - ux * h * bend];
}
interface Gait {
/** Position in the walk cycle (cycles walked). */
phase: number;
/** How much the deer is walking, 0 standing – 1 full stride. */
amp: number;
}
/** The four legs in lateral-sequence walk order: left hind, left fore, right hind, right fore. */
const LEGS = [
{ fore: true, off: 0.25, far: true },
{ fore: false, off: 0, far: true },
{ fore: true, off: 0.75, far: false },
{ fore: false, off: 0.5, far: false },
] as const;
/**
* The deer in local units of 10 cm: x forward, y down, origin mid-body 85 cm above the ground.
* `drink` lowers the head to the water, `alert` raises it high to look around.
*/
function deerSampler(p: DeerPal, g: Gait, drink: number, alert: number, flick: number, earTwitch: number) {
// The body rises and dips a little with each footfall; the hooves stay on the ground.
const bob = 0.3 * g.amp * Math.cos(g.phase * Math.PI * 4);
const nod = 0.07 * g.amp * Math.sin(g.phase * Math.PI * 4 + 1);
// The neck rises forward from the shoulders, carried a little lower while walking; to drink it
// swings down and the shoulders dip.
const baseY = -0.6 + drink * 1.2 + bob;
const neckA = -0.9 + drink * 2.1 + 0.15 * g.amp - 0.3 * alert + nod;
const neckL = 4 + drink * 2.2 + 0.3 * alert;
const nx = 4.4 + Math.cos(neckA) * neckL;
const ny = baseY + Math.sin(neckA) * neckL;
const headA = 0.45 + drink * 1.0 - 0.15 * alert + nod;
const hcx = nx + Math.cos(headA) * 1.1;
const hcy = ny + Math.sin(headA) * 1.1;
const hdx = Math.cos(headA);
const hdy = Math.sin(headA);
// Drinking, the forelegs splay forward a little to let the head reach the water.
const splay = drink * 0.9;
const legs = LEGS.map((l) => {
const hipX = l.fore ? 3.7 : -4;
const hipY = (l.fore ? 0.9 : 0.4) + bob;
const [fx, fy] = hoof((((g.phase + l.off) % 1) + 1) % 1, 2.95 * g.amp, (l.fore ? 1.3 : 1) * g.amp);
const footX = hipX + fx + (l.fore ? splay : -splay * 0.3);
const footY = GROUND + fy;
const [kx, ky] = l.fore ? joint(hipX, hipY, footX, footY, 3.9, 3.9, 1) : joint(hipX, hipY, footX, footY, 4.5, 4.0, -1);
return { ...l, hipX, hipY, footX, footY, kx, ky };
});
const leg = (lx: number, ly: number, far: boolean): RGB | undefined => {
for (const l of legs) {
if (l.far !== far) continue;
// Hind legs carry a heavy ham; forelegs are slimmer.
const upper = l.fore ? limb(lx, ly, l.hipX, l.hipY, l.kx, l.ky, 1.15, 0.6) : limb(lx, ly, l.hipX, l.hipY, l.kx, l.ky, 1.7, 0.65);
const lower = limb(lx, ly, l.kx, l.ky, l.footX, l.footY, 0.52, 0.38);
if (upper > 0 && lower > 0) continue;
let c = Math.hypot(lx - l.footX, ly - l.footY) < 0.75 ? p.hoof : lower <= 0 ? mix(p.coat, p.light, 0.3) : p.coat;
if (upper <= 0 && ly > l.hipY + 1.2 && lx < l.hipX - 0.4 && !l.fore) c = p.light;
return far ? mix(c, p.dark, 0.5) : c;
}
return undefined;
};
return (lx: number, ly: number): RGB | undefined => {
if (lx < -8.4 || lx > 11.5 || ly < -9.5 || ly > 10) return undefined;
// Head, ears and neck in front of the body.
const rx = lx - hcx;
const ry = ly - hcy;
const nearHead = rx * rx + ry * ry < 16;
const al = rx * hdx + ry * hdy;
const across = -rx * hdy + ry * hdx;
const taper = 1.25 - Math.max(0, al) * 0.18;
if (nearHead && al > -1.6 && al < 2.4 && Math.abs(across) < taper) {
if (al > 1.7) return p.nose;
if (al > 0.9) return p.muzzle;
if (al > -0.6 && al < -0.1 && across < -0.2 && across > -0.8) return p.nose;
return across > 0.5 ? p.light : p.coat;
}
for (let side = 0; side < 2 && nearHead; side++) {
const ea = headA - 2.1 - side * 0.45 - earTwitch * (side ? 0.4 : 0) - alert * 0.2;
const ex = hcx - hdx * 0.9 + Math.cos(ea) * 1.4;
const ey = hcy - hdy * 0.9 + Math.sin(ea) * 1.4;
if (limb(lx, ly, hcx - hdx * 0.9, hcy - hdy * 0.9, ex, ey, 0.55, 0.75) <= 0) return side ? mix(p.coat, p.dark, 0.4) : p.ear;
}
if (lx > 2 && limb(lx, ly, 4.0, baseY + 0.4, nx, ny, 2, 1.15) <= 0) return ly > ny + 1.2 && lx > 5.4 && drink < 0.5 ? p.light : p.coat;
const near = ly > 0 ? leg(lx, ly, false) : undefined;
if (near) return near;
// Body parts ride up and down with the bob.
const by = ly - bob;
// Tail: a dark-tipped rope that flicks up to show the white rump.
if (lx < -5.5 && limb(lx, by, -6.3, -1.2, -7.1 - flick * 0.4, 0.8 - flick * 2.6, 0.55, 0.4) <= 0) return by > -1.2 + (1 - flick) * 1.6 ? p.nose : p.light;
const body = (lx / 6.4) ** 2 + ((by + (lx < 0 ? 0.15 : 0)) / 2.8) ** 2;
const chest = Math.hypot(lx - 4.2, by - 0.3) < 2.5;
if (body <= 1 || chest) {
if (lx < -5 && by < 0.6) return p.light;
if (by > 1.7) return p.light;
return by < -1.8 ? mix(p.coat, p.light, 0.25) : p.coat;
}
return ly > 0 ? leg(lx, ly, true) : undefined;
};
}
const stamp = new Stamp();
function drawDeer(s: Surface, f: Frame, d: Deer): void {
const t = f.t;
const p = place(d, t);
const k = F / p.z;
const sc = (k / 10) * d.size;
const [x, y] = project(p.X, p.z, 0.85 * d.size);
if (x < -40 || x > 360) return;
const sun = Math.max(floorSunAt(f, p.X, p.z), 0);
const L = (c: RGB) => sunlit(f, c, sun);
const pal: DeerPal = {
coat: L(d.coat),
dark: L(mix(d.coat, hex('#3c2c22'), 0.55)),
light: L(hex('#e8dece')),
muzzle: L(hex('#5a4a3e')),
nose: L(hex('#1e1814')),
ear: L(hex('#c8a890')),
hoof: L(hex('#2c2420')),
};
// Smaller deer take shorter, quicker steps over the same ground.
const dist = walked(d, t);
const speed = (walked(d, t + 0.1) - walked(d, t - 0.1)) / 0.2;
const gait: Gait = { phase: dist / (STRIDE * 0.1 * d.size) + d.seed * 0.37, amp: clamp01(speed / 0.5) };
const tt = t - d.lag;
const pose = pausePose(tt, moveAt(tt));
let drink = DRINK(t - d.lag * 0.85 - d.seed * 0.6);
let alert = 0;
if (pose?.[0] === 'graze') drink = Math.max(drink, 0.8 * pose[1]);
if (pose?.[0] === 'look') alert = pose[1];
const flick = Math.max(0, Math.sin(t * 0.9 + d.seed * 2) * 6 - 5);
const twitch = hash(Math.floor(t * 0.7 + d.seed), d.seed, 9) > 0.85 ? 1 : 0;
const v = { x, y, scale: sc, facing: facing(d, t) };
sampleShape(stamp, v, 11.5, deerSampler(pal, gait, drink, alert, flick, twitch)).draw(s, 0.72);
drawRipples(s, f, p.X, p.z, sc, gait.amp, d.seed);
}
/** Rings spreading on the water around a deer's legs while it wades or drinks. */
function drawRipples(s: Surface, f: Frame, X: number, z: number, sc: number, stride: number, seed: number): void {
const e = Math.abs(X - streamX(z)) - streamHalf(z);
if (e > 0.45) return;
const [cx, cy] = project(X, z);
for (let i = 0; i < 3; i++) {
const age = (f.t * (0.6 + stride * 0.6) + i / 3 + seed * 0.13) % 1;
const r = (2 + age * 12) * sc;
const a = (1 - age) * 0.35 * (e < 0 ? 1 : 0.5);
for (let j = 0; j < 40; j++) {
const ang = (j / 40) * Math.PI * 2;
const px = cx + Math.cos(ang) * r;
const py = cy + Math.sin(ang) * r * 0.28;
if (Math.abs(cx - px) < 1 && py < cy) continue;
const pxW = ((px - project(0, z)[0]) * z) / F;
if (Math.abs(pxW - streamX(z)) > streamHalf(z)) continue;
s.blend(px, py, [235, 240, 248], a * (0.5 + 0.5 * f.daylight));
}
}
}
export function deerThings(f: Frame): Thing[] {
if (f.t < TIMES.deer - 1) return [];
return HERD.map((d) => {
const p = place(d, f.t);
return { z: p.z - 0.01, draw: (s: Surface, fr: Frame) => drawDeer(s, fr, d) };
});
}