Add The Reef meditation with parallax coral reef and animated marine lif

- Introduce a new 5-minute "The Reef" scene registered in the menu, drifting along a sunlit coral reef
- Add `pathTrack` (Catmull-Rom 2D path) to Timeline and a reusable `Stamp` buffer for outlined, tinted creature rendering
- Build three parallax reef layers with procedurally generated corals, swaying anemones/fans/kelp, plus water, caustics, god rays, marine snow, bubbles and floor shadows
- Animate clownfish, sunfish, a gliding stingray, jellyfish, fish schools, and a baby turtle meeting two adults before they swim off together
- Bundle the scene's music track (public/audio/the-reef.mp3)
This commit is contained in:
Brian Fertig 2026-10-30 15:53:34 -06:00
parent 401e5310af
commit cfd8c9a7a3
14 changed files with 2050 additions and 1 deletions

View File

@ -36,6 +36,7 @@ so edits on the host reload in the browser; don't run it and `npm run dev` on th
|---|---|---| |---|---|---|
| `northern-cabin` | Northern Cabin — winter sunset by a quiet lake | 5 min | | `northern-cabin` | Northern Cabin — winter sunset by a quiet lake | 5 min |
| `mediterranean-coast` | Mediterranean Coast — clearing skies over a jungle cove | 5 min | | `mediterranean-coast` | Mediterranean Coast — clearing skies over a jungle cove | 5 min |
| `the-reef` | The Reef — drifting along a sunlit coral reef | 5 min |
Each meditation lives in `src/meditations/<id>/` and is registered in `src/meditations/registry.ts`. Each meditation lives in `src/meditations/<id>/` and is registered in `src/meditations/registry.ts`.
A scene is a pure function of time (`render(surface, t)`), drawn pixel by pixel into a 320×180 buffer A scene is a pure function of time (`render(surface, t)`), drawn pixel by pixel into a 320×180 buffer

BIN
public/audio/the-reef.mp3 Normal file

Binary file not shown.

View File

@ -30,6 +30,36 @@ export function track(keys: readonly (readonly [number, number])[], e: Ease = ea
}; };
} }
/**
* Smooth keyframed 2D path through [time, x, y] keys (Catmull-Rom style), so creatures glide
* through their waypoints instead of turning sharp corners. Holds the end points outside the keyed range.
*/
export function pathTrack(keys: readonly (readonly [number, number, number])[]): (t: number) => [number, number] {
const n = keys.length;
return (t) => {
if (t <= keys[0][0]) return [keys[0][1], keys[0][2]];
if (t >= keys[n - 1][0]) return [keys[n - 1][1], keys[n - 1][2]];
let i = 0;
while (t >= keys[i + 1][0]) i++;
const k0 = keys[Math.max(0, i - 1)];
const k1 = keys[i];
const k2 = keys[i + 1];
const k3 = keys[Math.min(n - 1, i + 2)];
const d = k2[0] - k1[0];
const u = (t - k1[0]) / d;
const u2 = u * u;
const u3 = u2 * u;
const out: [number, number] = [0, 0];
for (let j = 1; j <= 2; j++) {
// Tangents are scaled to this segment's duration so uneven key spacing doesn't overshoot.
const m1 = ((k2[j] - k0[j]) / (k2[0] - k0[0])) * d;
const m2 = ((k3[j] - k1[j]) / (k3[0] - k1[0])) * d;
out[j - 1] = (2 * u3 - 3 * u2 + 1) * k1[j] + (u3 - 2 * u2 + u) * m1 + (-2 * u3 + 3 * u2) * k2[j] + (u3 - u2) * m2;
}
return out;
};
}
/** Keyframed color, same semantics as `track`. */ /** Keyframed color, same semantics as `track`. */
export function colorTrack(keys: readonly (readonly [number, RGB])[], e: Ease = ease.sine): (t: number) => RGB { export function colorTrack(keys: readonly (readonly [number, RGB])[], e: Ease = ease.sine): (t: number) => RGB {
return (t) => { return (t) => {

94
src/engine/stamp.ts Normal file
View File

@ -0,0 +1,94 @@
import { scale, type RGB } from './color';
import type { Surface } from './Surface';
/**
* A scratch buffer for building one creature out of colored pixels before it is drawn, so the
* whole shape can get a clean dark outline and be tinted (e.g. by water depth) as one piece.
*/
export class Stamp {
private x0 = 0;
private y0 = 0;
private w = 0;
private h = 0;
private cols: (RGB | undefined)[] = [];
/** Start a new shape covering the screen rectangle [x0, x0 + w) × [y0, y0 + h). */
begin(x0: number, y0: number, w: number, h: number): this {
this.x0 = Math.floor(x0);
this.y0 = Math.floor(y0);
this.w = Math.ceil(w);
this.h = Math.ceil(h);
const n = this.w * this.h;
if (this.cols.length < n) this.cols.length = n;
this.cols.fill(undefined, 0, n);
return this;
}
put(x: number, y: number, c: RGB): void {
const lx = Math.floor(x) - this.x0;
const ly = Math.floor(y) - this.y0;
if (lx < 0 || ly < 0 || lx >= this.w || ly >= this.h) return;
this.cols[ly * this.w + lx] = c;
}
private at(lx: number, ly: number): RGB | undefined {
if (lx < 0 || ly < 0 || lx >= this.w || ly >= this.h) return undefined;
return this.cols[ly * this.w + lx];
}
/**
* Draw onto the surface. Pixels on the shape's edge are darkened by `outline` (1 = no outline),
* `tint` can recolor every pixel (e.g. depth fog), and `alpha` blends the whole shape.
*/
draw(s: Surface, outline = 0.62, alpha = 1, tint?: (c: RGB, x: number, y: number) => RGB): void {
for (let ly = 0; ly < this.h; ly++) {
for (let lx = 0; lx < this.w; lx++) {
let c = this.cols[ly * this.w + lx];
if (!c) continue;
const edge = !this.at(lx - 1, ly) || !this.at(lx + 1, ly) || !this.at(lx, ly - 1) || !this.at(lx, ly + 1);
if (edge) c = scale(c, outline);
const x = lx + this.x0;
const y = ly + this.y0;
if (tint) c = tint(c, x, y);
s.blend(x, y, c, alpha);
}
}
}
}
export interface ShapeView {
x: number;
y: number;
/** Screen pixels per local unit. */
scale: number;
/** 1 faces right, -1 faces left; values in between squash the shape as it turns. */
facing: number;
/** Nose-up angle in radians. */
pitch?: number;
}
/**
* Fill a stamp from a shape described in local coordinates (x forward, y down, origin at the
* shape's center), so one drawing can be scaled, flipped, turned and tilted freely.
*/
export function sampleShape(
st: Stamp,
v: ShapeView,
radius: number,
sample: (lx: number, ly: number) => RGB | undefined,
): Stamp {
const R = Math.ceil(radius * v.scale) + 1;
st.begin(v.x - R, v.y - R, R * 2 + 1, R * 2 + 1);
const c = Math.cos(v.pitch ?? 0);
const sn = Math.sin(v.pitch ?? 0);
const fx = Math.abs(v.facing) < 0.35 ? 0.35 * Math.sign(v.facing || 1) : v.facing;
for (let y = Math.floor(v.y - R); y <= v.y + R; y++) {
for (let x = Math.floor(v.x - R); x <= v.x + R; x++) {
const dx = (x + 0.5 - v.x) / v.scale / fx;
const dy = (y + 0.5 - v.y) / v.scale;
const col = sample(c * dx - sn * dy, sn * dx + c * dy);
if (col) st.put(x, y, col);
}
}
return st;
}

View File

@ -1,9 +1,10 @@
import type { Meditation } from './types'; import type { Meditation } from './types';
import { mediterraneanCoast } from './mediterranean-coast'; import { mediterraneanCoast } from './mediterranean-coast';
import { northernCabin } from './northern-cabin'; import { northernCabin } from './northern-cabin';
import { theReef } from './the-reef';
/** Every meditation listed on the main menu, in display order. Add new ones here. */ /** Every meditation listed on the main menu, in display order. Add new ones here. */
export const meditations: readonly Meditation[] = [northernCabin, mediterraneanCoast]; export const meditations: readonly Meditation[] = [northernCabin, mediterraneanCoast, theReef];
export function findMeditation(id: string): Meditation | undefined { export function findMeditation(id: string): Meditation | undefined {
return meditations.find((m) => m.id === id); return meditations.find((m) => m.id === id);

View File

@ -0,0 +1,333 @@
import { hex, type RGB } from '../../engine/color';
import { noise1, noise2, Rng } from '../../engine/rng';
import { drawSprite, type SpriteArt } from '../../engine/sprite';
import { sampleShape, Stamp } from '../../engine/stamp';
import type { Surface } from '../../engine/Surface';
import { pathTrack } from '../../engine/Timeline';
import { getReef } from './reef';
import type { Frame } from './timeline';
import { fog, W } from './world';
// ---------------------------------------------------------------------------
// Small fish sprites (all facing right; tail flick in the second frame)
// ---------------------------------------------------------------------------
const CLOWN: [SpriteArt, SpriteArt] = [
['.....kok...', 'k.woowoowo.', 'oowoowoowEo', 'k.woowoowo.', '....k..k...'],
['.....kok...', '.kwoowoowo.', '.owoowoowEo', '.kwoowoowo.', '....k..k...'],
];
const CLOWN_PAL: Record<string, RGB> = { o: hex('#f47a24'), w: hex('#f8f6f0'), k: hex('#1c1418'), E: hex('#0c0c10') };
const SCHOOL_FISH: [SpriteArt, SpriteArt] = [
['t.bbbb.', '.tmmmem', 't.llll.'],
['.tbbbb.', 'ttmmmem', '.tllll.'],
];
const SMALL_FISH: [SpriteArt, SpriteArt] = [
['t.bb.', '.tmme', 't.ll.'],
['.tbb.', 'ttmme', '.tll.'],
];
const BUTTERFLY: [SpriteArt, SpriteArt] = [
['...yyy...', '..yyyyy..', 't.yyyykw.', 'tyyyyykwk', 't.yyyykw.', '..yyyyy..', '...yyy...'],
['...yyy...', '..yyyyy..', '.tyyyykw.', 'tyyyyykwk', '.tyyyykw.', '..yyyyy..', '...yyy...'],
];
const BUTTERFLY_PAL: Record<string, RGB> = { y: hex('#f8d444'), t: hex('#e8ecd8'), k: hex('#1a1a1a'), w: hex('#f8f8f0') };
const fishPal = (t: string, b: string, m: string, l: string): Record<string, RGB> => ({
t: hex(t),
b: hex(b),
m: hex(m),
l: hex(l),
e: hex('#101018'),
});
const CHROMIS = fishPal('#3a9ab8', '#2a7ab0', '#58c8e0', '#a8eef0');
function drawFish(s: Surface, frames: [SpriteArt, SpriteArt], x: number, y: number, pal: Record<string, RGB>, left: boolean, flick: number): void {
const art = frames[Math.floor(flick) % 2 ? 1 : 0];
drawSprite(s, art, Math.round(x - art[0].length / 2), Math.round(y - art.length / 2), pal, left);
}
/** Fog a sprite palette for fish swimming further away. */
function fogPal(p: Record<string, RGB>, y: number, k: number): Record<string, RGB> {
return Object.fromEntries(Object.entries(p).map(([key, c]) => [key, fog(c, y, k)]));
}
// ---------------------------------------------------------------------------
// Clownfish, darting in and out of their anemones
// ---------------------------------------------------------------------------
function clownAt(t: number, phase: number): [number, number] {
const R = 5 + 5 * noise1(t * 0.1 + phase, 40);
return [
Math.sin(t * 0.45 + phase) * R + Math.sin(t * 1.1 + phase * 2) * 2,
Math.cos(t * 0.37 + phase) * R * 0.45 + Math.sin(t * 0.9 + phase) * 1.5,
];
}
export function drawClownfish(s: Surface, f: Frame): void {
for (const a of getReef().anemones) {
const ox = a.x - f.cam;
if (a.clowns === 0 || ox < -40 || ox > W + 40) continue;
for (let j = 0; j < a.clowns; j++) {
const phase = a.seed * 0.37 + j * 2.4;
const [dx, dy] = clownAt(f.t, phase);
const [nx] = clownAt(f.t + 0.1, phase);
drawFish(s, CLOWN, ox + dx, a.y - a.size * 0.95 + dy, CLOWN_PAL, nx < dx, f.t * 7 + j);
}
}
}
// ---------------------------------------------------------------------------
// Resident reef fish: chromis hovering over the coral and pairs of butterflyfish
// ---------------------------------------------------------------------------
export function drawResidentFish(s: Surface, f: Frame): void {
const t = f.t;
for (const c of getReef().clusters) {
const ox = c.cx - f.cam;
if (ox < -c.hw - 30 || ox > W + c.hw + 30) continue;
if (c.index % 3 === 1) {
const top = c.topAt(c.cx);
for (let j = 0; j < 6; j++) {
const ph = j * 1.7 + c.index;
const x = ox + Math.sin(t * 0.3 + ph) * c.hw * 0.5 + (noise1(t * 0.4 + ph, 41) - 0.5) * 6;
const y = top - 9 - (j % 3) * 4 + Math.sin(t * 0.5 + ph) * 3;
drawFish(s, SMALL_FISH, x, y, CHROMIS, Math.cos(t * 0.3 + ph) < 0, t * 8 + j);
}
}
if (c.index % 4 === 2) {
for (let j = 0; j < 2; j++) {
const tt = t - j * 1.3;
const x = ox + Math.sin(tt * 0.11 + c.index) * c.hw * 0.75;
const y = c.topAt(c.cx + (x - ox)) - 7 - j * 3 + Math.sin(tt * 0.4 + j) * 2;
drawFish(s, BUTTERFLY, x, y, BUTTERFLY_PAL, Math.cos(tt * 0.11 + c.index) < 0, t * 5 + j);
}
}
}
}
// ---------------------------------------------------------------------------
// Ocean sunfish, sculling slowly through the open water
// ---------------------------------------------------------------------------
const MOLA = {
back: hex('#7e8ea4'),
mid: hex('#abb8c8'),
belly: hex('#dfe6ec'),
blotch: hex('#c8d4de'),
fin: hex('#8a98ac'),
finEdge: hex('#6c7a8e'),
clavus: hex('#9eacbc'),
eye: hex('#1a1e28'),
shine: hex('#f4fbff'),
};
/** A tapering fin from a base on the body out to a blunt tip. */
function inFin(lx: number, ly: number, by: number, tipx: number, tipy: number): boolean {
const v = (ly - by) / (tipy - by);
if (v < 0 || v > 1) return false;
const left = -8 + (tipx - 1.3 + 8) * v;
const right = -1 + (tipx + 1.3 + 1) * v;
return lx >= left && lx <= right;
}
function molaSampler(t: number, seed: number) {
const flap = Math.sin(t * 2.1 + seed);
const tipx = -5 + flap * 3;
const reach = 20 + Math.cos(t * 2.1 + seed) * 1.5;
return (lx: number, ly: number): RGB | undefined => {
const body = ((lx - 1) / 11) ** 2 + (ly / 10.5) ** 2 <= 1 && lx > -7.5;
if (body) {
if (Math.hypot(lx - 6.5, ly + 2.5) < 1.6) return lx > 6.6 && ly < -2.8 ? MOLA.shine : MOLA.eye;
if (Math.hypot(lx - 11.2, ly - 1) < 0.9) return MOLA.finEdge;
// Pectoral fin, fluttering.
const pf = (lx - 2 + Math.sin(t * 4 + seed) * 0.6) ** 2 / 4 + (ly - 1.5) ** 2 / 1.4;
if (pf < 1) return pf > 0.55 ? MOLA.finEdge : MOLA.fin;
if (noise2(lx / 3 + seed, ly / 3, 42) > 0.66) return MOLA.blotch;
return ly < -5 ? MOLA.back : ly > 5 ? MOLA.belly : MOLA.mid;
}
// The clavus: the frilly rudder that stands in for a tail.
if (lx <= -7.5 && lx > -10.8 + 0.8 * Math.sin(ly * 1.3 + t * 2) && Math.abs(ly) < 7.5) {
return Math.abs(ly) % 3 < 1 ? MOLA.finEdge : MOLA.clavus;
}
if (inFin(lx, ly, -8, tipx, -reach) || inFin(lx, -ly, -8, tipx, -reach)) {
return Math.abs(ly) > reach - 3 ? MOLA.finEdge : MOLA.fin;
}
return undefined;
};
}
interface Mola {
path: (t: number) => [number, number];
scale: number;
facing: 1 | -1;
fog: number;
seed: number;
}
const MOLAS: Mola[] = [
{
path: pathTrack([
[0, 60, 66],
[30, 140, 58],
[60, 250, 70],
[80, 370, 62],
]),
scale: 0.8,
facing: 1,
fog: 0.08,
seed: 0,
},
{
path: pathTrack([
[0, 290, 46],
[35, 196, 40],
[72, -50, 52],
]),
scale: 0.5,
facing: -1,
fog: 0.38,
seed: 2,
},
];
const stamp = new Stamp();
function drawMola(s: Surface, f: Frame, m: Mola): void {
if (f.t > 80) return;
const [x, y] = m.path(f.t);
sampleShape(stamp, { x, y, scale: m.scale, facing: m.facing, pitch: Math.sin(f.t * 0.5 + m.seed) * 0.06 }, 24, molaSampler(f.t, m.seed));
stamp.draw(s, 0.7, 1, m.fog > 0 ? (c, _x, yy) => fog(c, yy, m.fog) : undefined);
}
/** The distant sunfish swims behind the near reef. */
export function drawFarSunfish(s: Surface, f: Frame): void {
drawMola(s, f, MOLAS[1]);
}
export function drawNearSunfish(s: Surface, f: Frame): void {
drawMola(s, f, MOLAS[0]);
}
// ---------------------------------------------------------------------------
// Schools of colorful fish
// ---------------------------------------------------------------------------
interface School {
center: (t: number) => [number, number];
frames: [SpriteArt, SpriteArt];
pal: Record<string, RGB>;
fish: { lag: number; side: number; phase: number }[];
spread: number;
fog: number;
}
function school(
keys: [number, number, number][],
n: number,
seed: number,
frames: [SpriteArt, SpriteArt],
pal: Record<string, RGB>,
spread: number,
lagMax: number,
fogK = 0,
): School {
const r = new Rng(seed);
return {
center: pathTrack(keys),
frames,
pal,
fish: Array.from({ length: n }, () => ({ lag: r.range(0, lagMax), side: r.range(-1, 1), phase: r.range(0, 100) })),
spread,
fog: fogK,
};
}
/** Blue chromis sweeping in from the left, out over the reef and back. */
const BLUE = school(
[
[178, -70, 64],
[190, 70, 52],
[200, 190, 66],
[208, 250, 88],
[216, 210, 104],
[226, 100, 92],
[236, 30, 70],
[246, -90, 60],
],
40,
11,
SCHOOL_FISH,
fishPal('#3a6ad0', '#2a4ab8', '#5aa8f4', '#b4e4fc'),
14,
4,
);
/** Yellow, blue-striped snappers cruising past further away. */
const GOLD = school(
[
[182, 390, 84],
[196, 250, 76],
[210, 140, 88],
[222, 70, 78],
[232, 150, 66],
[242, 260, 74],
[252, 410, 78],
],
32,
12,
SCHOOL_FISH,
fishPal('#e0a020', '#e8b830', '#58aef0', '#f8e078'),
12,
3.5,
0.22,
);
/** A swirl of tiny pink-orange anthias around the coral. */
const PINK = school(
[
[188, 350, 104],
[198, 262, 108],
[204, 222, 94],
[210, 190, 108],
[216, 222, 120],
[222, 252, 108],
[228, 222, 92],
[234, 182, 102],
[246, -70, 98],
],
44,
13,
SMALL_FISH,
fishPal('#e05878', '#f07890', '#ffa08c', '#ffd0a8'),
11,
4,
);
function drawSchool(s: Surface, f: Frame, sc: School): void {
const pal = sc.fog > 0 ? fogPal(sc.pal, 100, sc.fog) : sc.pal;
for (const fish of sc.fish) {
const tt = f.t - fish.lag;
const [cx, cy] = sc.center(tt);
const [nx, ny] = sc.center(tt + 0.15);
const vx = nx - cx;
const vy = ny - cy;
const sp = Math.hypot(vx, vy) || 1;
// Fish spread out to the sides of the school's heading, each weaving a little.
const x = cx - (vy / sp) * fish.side * sc.spread + (noise1(f.t * 0.6 + fish.phase, 43) - 0.5) * 6;
const y = cy + (vx / sp) * fish.side * sc.spread + (noise1(f.t * 0.5 + fish.phase, 44) - 0.5) * 5;
if (x < -10 || x > W + 10) continue;
drawFish(s, sc.frames, x, y, pal, vx < 0, f.t * 9 + fish.phase);
}
}
export function drawFarSchools(s: Surface, f: Frame): void {
if (f.t < 178 || f.t > 256) return;
drawSchool(s, f, GOLD);
}
export function drawNearSchools(s: Surface, f: Frame): void {
if (f.t < 176 || f.t > 256) return;
drawSchool(s, f, PINK);
drawSchool(s, f, BLUE);
}

View File

@ -0,0 +1,49 @@
import type { Meditation, Scene } from '../types';
import { drawClownfish, drawFarSchools, drawFarSunfish, drawNearSchools, drawNearSunfish, drawResidentFish } from './fish';
import { drawFarJellies, drawNearJellies } from './jellyfish';
import { drawBubbles, drawFarReef, drawForeground, drawMidReef, drawNearBack, drawNearFront, drawNearReef } from './reef';
import { drawStingray, drawStingrayShadow } from './stingray';
import { DURATION, frameAt } from './timeline';
import { drawTurtles } from './turtles';
import { drawFloor, drawGodRays, drawMarineSnow, drawWater } from './water';
const scene: Scene = {
render(s, t) {
const f = frameAt(t);
drawWater(s, f);
drawFarReef(s, f);
drawFloor(s, f);
drawStingrayShadow(s, f);
drawMidReef(s, f);
drawFarSunfish(s, f);
drawFarJellies(s, f);
drawFarSchools(s, f);
drawNearBack(s, f);
drawNearReef(s, f);
drawNearFront(s, f);
drawClownfish(s, f);
drawResidentFish(s, f);
drawBubbles(s, f);
drawNearSunfish(s, f);
drawStingray(s, f);
drawNearJellies(s, f);
drawNearSchools(s, f);
drawTurtles(s, f);
drawMarineSnow(s, f);
drawGodRays(s, f);
drawForeground(s, f);
s.darken(f.fade);
},
};
export const theReef: Meditation = {
id: 'the-reef',
title: 'The Reef',
subtitle: 'Drifting along a sunlit coral reef',
description:
'Glide slowly along a coral reef beneath shimmering light. Clownfish tend their anemones, a ray sails past, jellyfish pulse by and schools of fish swirl, until a young sea turtle finds its family and they swim off into the blue together.',
duration: DURATION,
previewTime: 276,
music: 'audio/the-reef.mp3',
createScene: () => scene,
};

View File

@ -0,0 +1,135 @@
import { ditherStep, hex, mix, type RGB } from '../../engine/color';
import type { Surface } from '../../engine/Surface';
import { pathTrack } from '../../engine/Timeline';
import type { Frame } from './timeline';
import { TIMES } from './timeline';
import { fog } from './world';
/** Jellyfish drift in around the two-minute mark, pulse about for a minute, then rise away toward the light. */
interface JellyPal {
bell: RGB;
rim: RGB;
inner: RGB;
arms: RGB;
}
const PINK: JellyPal = { bell: hex('#f88ac0'), rim: hex('#ffd0ea'), inner: hex('#d04898'), arms: hex('#f070b0') };
const LAVENDER: JellyPal = { bell: hex('#b490f4'), rim: hex('#e8dcff'), inner: hex('#7a54d8'), arms: hex('#a07cf0') };
const PEACH: JellyPal = { bell: hex('#ffaa60'), rim: hex('#ffe0b0'), inner: hex('#e07030'), arms: hex('#ff9048') };
const MOON: JellyPal = { bell: hex('#b8e4fc'), rim: hex('#f4fdff'), inner: hex('#e080d0'), arms: hex('#a8d4f4') };
interface Jelly {
path: (t: number) => [number, number];
size: number;
pal: JellyPal;
/** Far jellies are smaller, hazier and swim behind the near reef. */
far: boolean;
/** Pulses per second. */
rate: number;
seed: number;
}
const jelly = (keys: [number, number, number][], size: number, pal: JellyPal, far: boolean, rate: number, seed: number): Jelly => ({
path: pathTrack(keys),
size,
pal,
far,
rate,
seed,
});
const JELLIES: Jelly[] = [
jelly([[118, 250, -34], [135, 228, 72], [150, 200, 92], [165, 168, 80], [180, 140, 46], [192, 118, -50]], 1.4, PINK, false, 0.55, 1),
jelly([[120, 345, 64], [140, 272, 84], [160, 220, 70], [178, 182, 54], [190, 150, -34]], 0.7, LAVENDER, true, 0.7, 2),
jelly([[124, -24, 86], [140, 58, 100], [158, 96, 86], [172, 110, 66], [188, 120, -46]], 1.25, MOON, false, 0.5, 3),
jelly([[126, 150, -28], [145, 140, 54], [165, 118, 74], [180, 100, 54], [194, 90, -32]], 0.6, PEACH, true, 0.75, 4),
jelly([[132, 348, 116], [150, 282, 120], [168, 252, 96], [182, 236, 56], [195, 224, -50]], 1.1, PEACH, false, 0.6, 5),
jelly([[128, 60, -24], [148, 40, 64], [168, 52, 80], [184, 70, 46], [195, 80, -34]], 0.55, PINK, true, 0.8, 6),
jelly([[136, 300, -30], [156, 300, 54], [172, 286, 74], [186, 268, 44], [196, 258, -40]], 0.75, LAVENDER, false, 0.65, 7),
];
/** 0 = relaxed, 1 = fully contracted, over one pulse. */
function contraction(phase: number): number {
return phase < 0.3 ? Math.sin((phase / 0.3) * Math.PI * 0.5) : Math.cos(((phase - 0.3) / 0.7) * Math.PI * 0.5);
}
/** Each pulse lifts the jelly a little; between pulses it sinks back, so it bobs as it travels. */
function bob(t: number, rate: number): number {
const c = t * rate;
const n = Math.floor(c);
const fr = c - n;
const lift = n + Math.min(1, fr / 0.4) ** 0.6;
return -(lift - c) * 4;
}
function drawJelly(s: Surface, f: Frame, j: Jelly): void {
const t = f.t;
const [px, py0] = j.path(t);
const py = py0 + bob(t + j.seed, j.rate);
const phase = (t * j.rate + j.seed * 0.17) % 1;
const c = contraction(phase);
const rx = 7 * j.size * (1 - 0.2 * c);
const ry = 6 * j.size * (1 + 0.15 * c);
const haze = j.far ? 0.38 : 0;
const tint = (col: RGB, y: number) => (haze ? fog(col, y, haze) : col);
const alpha = j.far ? 0.6 : 0.85;
// Long fine tentacles from the rim, trailing and swaying.
const nT = Math.round(6 * j.size) + 2;
for (let i = 0; i < nT; i++) {
const u = nT > 1 ? i / (nT - 1) : 0.5;
const x0 = px + (u - 0.5) * rx * 1.8;
const len = (16 + 10 * Math.sin(i * 2.3 + j.seed)) * j.size;
for (let k = 0; k < len; k++) {
const x = x0 + Math.sin(t * 1.3 + k * 0.22 + i * 1.7) * k * 0.09 + f.surge * k * 0.05;
const y = py + 1 + k;
s.blend(Math.round(x), Math.round(y), tint(j.pal.rim, y), (1 - k / len) * 0.5 * alpha);
}
}
// Frilly oral arms from the middle.
for (let i = 0; i < 3; i++) {
const len = (10 + i * 3) * j.size;
for (let k = 0; k < len; k++) {
const x = px + (i - 1) * 1.5 + Math.sin(t * 1.1 + k * 0.3 + i * 2) * (1 + k * 0.08);
const y = py + 1 + k;
const col = tint(k % 3 === 0 ? j.pal.rim : j.pal.arms, y);
s.blend(Math.round(x), Math.round(y), col, 0.8 * alpha);
if (k < len * 0.6) s.blend(Math.round(x) + 1, Math.round(y), col, 0.5 * alpha);
}
}
// The bell: a translucent dome, brighter at the rim, with a soft glow around it.
for (let y = Math.floor(py - ry - 2); y <= py + 2; y++) {
for (let x = Math.floor(px - rx - 2); x <= px + rx + 2; x++) {
const dx = (x + 0.5 - px) / rx;
const dy = (y + 0.5 - py) / ry;
const e = dx * dx + (dy < 0 ? dy * dy : (dy * 3) ** 2);
if (e > 1) {
const g = Math.max(0, 1 - (e - 1) * 1.5);
s.light(x, y, j.pal.rim, ditherStep(g * 0.12 * alpha, x, y, 4));
continue;
}
let col = j.pal.bell;
if (e > 0.72) col = j.pal.rim;
else if (Math.hypot(dx * 1.6, dy + 0.35) < 0.45 && Math.abs(dx) > 0.08) col = j.pal.inner;
if (dy < -0.55 && dx < -0.1 && dx > -0.45) col = mix(col, [255, 255, 279], 0.5);
s.blend(x, y, tint(col, y), (e > 0.72 ? 0.9 : 0.62) * alpha);
}
}
}
function inWindow(t: number): boolean {
return t >= TIMES.jellyfish[0] && t <= TIMES.jellyfish[1] + 2;
}
export function drawFarJellies(s: Surface, f: Frame): void {
if (!inWindow(f.t)) return;
for (const j of JELLIES) if (j.far) drawJelly(s, f, j);
}
export function drawNearJellies(s: Surface, f: Frame): void {
if (!inWindow(f.t)) return;
for (const j of JELLIES) if (!j.far) drawJelly(s, f, j);
}

View File

@ -0,0 +1,741 @@
import { bayer, ditherStep, hex, scale, type RGB } from '../../engine/color';
import { hash, noise1, noise2, Rng } from '../../engine/rng';
import { Surface } from '../../engine/Surface';
import { CAM_MAX, type Frame } from './timeline';
import { caustic, drawBubbleStream } from './water';
import { FAR, floorRow, fog, H, MID, NEAR, W } from './world';
/**
* The reef is three layers of rock and coral at different depths. Their static parts are painted
* once into wide images that scroll at each layer's parallax; anything that sways (anemones,
* sea fans, algae, sea grass) is drawn fresh every frame on top.
*/
/** Spare columns either side of each layer image. */
const PAD = 24;
interface Layer {
img: Surface;
p: number;
/** First row with anything in it, so blits can skip open water. */
top: number;
}
function newLayer(p: number): Layer {
return { img: new Surface(Math.ceil(CAM_MAX * p) + W + PAD * 2, H), p, top: H };
}
/** Paint a pixel into a layer at world x. */
function put(L: Layer, x: number, y: number, c: RGB): void {
x = Math.round(x);
y = Math.round(y);
if (y < 0 || y >= H) return;
L.img.set(x + PAD, y, c);
if (y < L.top) L.top = y;
}
/** Fade every painted pixel of a layer toward the water behind it. */
function fogLayer(L: Layer, k: (y: number) => number): void {
const d = L.img.data;
for (let y = 0; y < H; y++) {
const kk = k(y);
for (let x = 0; x < L.img.w; x++) {
const i = (y * L.img.w + x) * 4;
if (d[i + 3] === 0) continue;
const c = fog([d[i], d[i + 1], d[i + 2]], y, kk);
d[i] = c[0];
d[i + 1] = c[1];
d[i + 2] = c[2];
}
}
}
// ---------------------------------------------------------------------------
// Palettes
// ---------------------------------------------------------------------------
const pal = <K extends string>(o: Record<K, string>): Record<K, RGB> =>
Object.fromEntries(Object.entries(o).map(([k, v]) => [k, hex(v as string)])) as Record<K, RGB>;
type RockPal = Record<'hi' | 'light' | 'mid' | 'dark' | 'hole' | 'pink' | 'pink2', RGB>;
const ROCK: RockPal = pal({
hi: '#b0a2aa',
light: '#8c7c90',
mid: '#6a5c76',
dark: '#4a3e5a',
hole: '#2a2236',
pink: '#c46a90',
pink2: '#ea96b0',
});
const BRAIN = [
pal({ light: '#ece08e', mid: '#c8b060', dark: '#8a7440', groove: '#6a5a30' }),
pal({ light: '#bee696', mid: '#88b860', dark: '#5a8040', groove: '#40602e' }),
pal({ light: '#f4b884', mid: '#d08858', dark: '#985c3c', groove: '#704030' }),
];
const BRANCH = [
pal({ base: '#d8b888', tip: '#fff0d0', shade: '#a88860' }),
pal({ base: '#9a62c0', tip: '#e6b8ff', shade: '#6a3a8a' }),
pal({ base: '#4a8ad8', tip: '#b0e6ff', shade: '#30609a' }),
pal({ base: '#e8a040', tip: '#ffe488', shade: '#b07020' }),
];
const TABLE = [
pal({ top: '#b0e8d8', mid: '#70b0a0', under: '#3a6a66' }),
pal({ top: '#e6c8f4', mid: '#b08ac8', under: '#6a4a80' }),
pal({ top: '#f4dca4', mid: '#c8a870', under: '#7a6040' }),
];
const TUBE = [
pal({ light: '#ffac6c', mid: '#e87838', dark: '#a84a20', inner: '#4a1a10' }),
pal({ light: '#d894ec', mid: '#a058c0', dark: '#6a3088', inner: '#2a1038' }),
pal({ light: '#fff484', mid: '#e8c840', dark: '#a88a20', inner: '#4a3a10' }),
pal({ light: '#ff98c4', mid: '#e05898', dark: '#a03068', inner: '#401028' }),
];
const BARREL = pal({ light: '#dc8c74', mid: '#a8584a', dark: '#703830', inner: '#301818' });
const FINGERS = [
pal({ light: '#ffc4dc', mid: '#e888a8', dark: '#b05878' }),
pal({ light: '#e4f494', mid: '#b8d060', dark: '#80963a' }),
pal({ light: '#a8f4f4', mid: '#60c8d0', dark: '#3a8a98' }),
];
const CLAM = pal({ shell: '#b8b4a8', shade: '#6a6660', m1: '#3a8ad8', m2: '#8a4ac8', spot: '#a8f0ff' });
const STARS = [pal({ c: '#f07838', d: '#b04a20' }), pal({ c: '#4a7ae8', d: '#2a4aa0' }), pal({ c: '#f0c040', d: '#b08820' })];
const pick = <T>(r: Rng, list: readonly T[]): T => list[Math.floor(r.next() * list.length)];
// ---------------------------------------------------------------------------
// Static coral and rock
// ---------------------------------------------------------------------------
function rockColor(x: number, y: number, depth: number, fromBottom: number, seed: number, p: RockPal): RGB {
const n = noise2(x / 4, y / 4, seed + 3) + (bayer(x, y) - 0.5) * 0.2;
if (depth > 3 && noise2(x / 3, y / 2.2, seed + 4) > 0.8) return p.hole;
if (depth > 1 && noise2(x / 4, y / 4, seed + 5) > 0.76) return n > 0.5 ? p.pink2 : p.pink;
if (depth < 1) return p.hi;
if (fromBottom < 3) return p.dark;
if (depth < 3) return p.light;
return n > 0.62 ? p.light : n < 0.32 ? p.dark : p.mid;
}
/** A lumpy mound of old reef rock; returns its top row for any x across it. */
function mound(L: Layer, cx: number, hw: number, ht: number, base: number, seed: number, p: RockPal): (x: number) => number {
const x0 = Math.floor(cx - hw);
const tops: number[] = [];
for (let x = x0; x <= cx + hw; x++) {
const u = (x - cx) / hw;
const h =
Math.abs(u) >= 1
? 0
: ht * Math.pow(1 - u * u, 0.55) * (0.7 + 0.6 * noise1(x / 13, seed)) + (noise1(x / 3.5, seed + 1) - 0.5) * 4;
const top = Math.round(base - Math.max(1, h));
tops.push(top);
if (h <= 0) continue;
const bottom = base + 1 + Math.round(noise1(x / 4, seed + 2) * 3);
for (let y = top; y <= bottom; y++) put(L, x, y, rockColor(x, y, y - top, bottom - y, seed, p));
}
return (x) => tops[Math.round(x) - x0] ?? base;
}
function brain(L: Layer, x: number, y: number, rx: number, p: (typeof BRAIN)[number], seed: number): void {
const ry = Math.max(2, Math.round(rx * 0.72));
for (let dy = -ry; dy <= 1; dy++) {
for (let dx = -rx; dx <= rx; dx++) {
const e = (dx / rx) ** 2 + (Math.min(0, dy) / ry) ** 2;
if (e > 1) continue;
const groove = Math.sin((dx * 0.95 + noise2((x + dx) / 3, dy / 3, seed) * 5) * 1.5 + dy * 0.7) > 0.62;
const k = -dy / ry;
let c = k > 0.55 ? p.light : k > 0.1 ? p.mid : p.dark;
if (e > 0.8 && k < 0.5) c = p.dark;
if (groove && e < 0.88 && rx > 3) c = p.groove;
put(L, x + dx, y + dy, c);
}
}
}
function branchCoral(L: Layer, x: number, y: number, h: number, p: (typeof BRANCH)[number], r: Rng): void {
const grow = (px: number, py: number, a: number, len: number, w: number, depth: number) => {
const steps = Math.ceil(len * 2);
for (let i = 0; i <= steps; i++) {
const s = (i / steps) * len;
const qx = px + Math.sin(a) * s;
const qy = py - Math.cos(a) * s;
put(L, qx, qy, depth === 0 && s > len - 2 ? p.tip : p.base);
if (w > 1) put(L, qx + 1, qy, p.shade);
}
if (depth === 0) return;
const ex = px + Math.sin(a) * len;
const ey = py - Math.cos(a) * len;
const kids = r.next() < 0.3 ? 3 : 2;
for (let k = 0; k < kids; k++) {
grow(ex, ey, a + r.range(-0.75, 0.75), len * r.range(0.6, 0.85), Math.max(1, w - 1), depth - 1);
}
};
const trunks = r.int(1, 3);
for (let i = 0; i < trunks; i++) grow(x + (i - (trunks - 1) / 2) * 3, y, r.range(-0.35, 0.35), h * 0.38, 2, 2);
}
function tableCoral(L: Layer, x: number, y: number, w: number, p: (typeof TABLE)[number], r: Rng): void {
const stalk = r.int(3, 7);
for (let i = 0; i < stalk; i++) {
put(L, x, y - i, p.under);
put(L, x + 1, y - i, p.under);
}
const tiers = w > 18 && r.next() < 0.5 ? 2 : 1;
for (let tier = 0; tier < tiers; tier++) {
const py = y - stalk - tier * 4;
const rx = (w / 2) * (tier ? 0.6 : 1);
const tilt = r.range(-0.1, 0.1);
for (let dx = -Math.round(rx); dx <= rx; dx++) {
const e = Math.abs(dx) / rx;
const yy = py + Math.round(dx * tilt) + (e > 0.8 ? 1 : 0);
const polyp = hash(x + dx, tier, 7) > 0.7;
put(L, x + dx, yy - 1, polyp ? scale(p.top, 1.08) : p.top);
put(L, x + dx, yy, p.mid);
if (e < 0.85) put(L, x + dx, yy + 1, p.under);
}
}
}
function tubes(L: Layer, x: number, y: number, k: number, p: (typeof TUBE)[number], r: Rng): void {
const n = r.int(2, 4);
for (let i = 0; i < n; i++) {
const w = k < 0.8 ? 2 : r.int(3, 4);
const h = Math.round(r.range(8, 22) * k);
const lean = r.range(-0.15, 0.15);
const bx = x + (i - (n - 1) / 2) * (w + 1) + r.int(-1, 1);
for (let j = 0; j < h; j++) {
const cx = Math.round(bx + lean * j);
for (let q = 0; q < w; q++) put(L, cx + q, y - j, q === 0 ? p.light : q === w - 1 ? p.dark : p.mid);
}
const tx = Math.round(bx + lean * h);
for (let q = 0; q < w; q++) put(L, tx + q, y - h, q === 0 || q === w - 1 ? p.light : p.inner);
for (let q = 1; q < w - 1; q++) put(L, tx + q, y - h - 1, p.light);
}
}
function barrel(L: Layer, x: number, y: number, w: number, h: number, p: typeof BARREL): void {
for (let j = 0; j < h; j++) {
const v = j / h;
const half = Math.round((w / 2) * (0.6 + 0.4 * Math.sin(v * Math.PI * 0.6 + 0.4)));
for (let dx = -half; dx <= half; dx++) {
const side = dx / Math.max(1, half);
let c = side < -0.45 ? p.light : side > 0.5 ? p.dark : p.mid;
if (j % 3 === 1 && Math.abs(side) < 0.9) c = p.dark;
put(L, x + dx, y - j, c);
}
}
const half = Math.round((w / 2) * (0.6 + 0.4 * Math.sin(Math.PI * 0.6 + 0.4)));
for (let dx = -half + 1; dx < half; dx++) put(L, x + dx, y - h, p.inner);
for (let dx = -half; dx <= half; dx++) put(L, x + dx, y - h - 1, dx === -half || dx === half ? p.mid : p.light);
}
function fingers(L: Layer, x: number, y: number, k: number, p: (typeof FINGERS)[number], r: Rng): void {
const n = r.int(3, 6);
for (let i = 0; i < n; i++) {
const fx = x + i * 2 - n;
const h = Math.round(r.range(4, 10) * k);
for (let j = 0; j < h; j++) {
put(L, fx, y - j, p.mid);
put(L, fx + 1, y - j, p.dark);
}
put(L, fx, y - h, p.light);
put(L, fx + 1, y - h, p.mid);
}
}
function clam(L: Layer, x: number, y: number, r: Rng): void {
for (let dx = 0; dx < 8; dx++) {
if (dx % 2 === 0) put(L, x + dx, y - 2, CLAM.shell);
put(L, x + dx, y - 1, r.next() < 0.2 ? CLAM.spot : dx % 3 === 0 ? CLAM.m2 : CLAM.m1);
put(L, x + dx, y, CLAM.shade);
}
}
const STAR_ART = ['..o..', 'ooooo', '.ooo.', '.o.o.', 'o...o'];
function seaStar(L: Layer, x: number, y: number, p: (typeof STARS)[number]): void {
STAR_ART.forEach((row, j) => {
for (let i = 0; i < row.length; i++) if (row[i] === 'o') put(L, x + i - 2, y + j - 4, j > 2 ? p.d : p.c);
});
}
/** One random coral or sponge growing at (x, y), k scaling its size. */
function coral(L: Layer, x: number, y: number, k: number, r: Rng): void {
const roll = r.next();
if (roll < 0.2) brain(L, x, y, Math.max(2, Math.round(r.range(4, 10) * k)), pick(r, BRAIN), r.int(0, 999));
else if (roll < 0.4) branchCoral(L, x, y, r.range(16, 32) * k, pick(r, BRANCH), r);
else if (roll < 0.5) tableCoral(L, x, y, r.range(14, 30) * k, pick(r, TABLE), r);
else if (roll < 0.66) tubes(L, x, y, r.range(0.9, 1.3) * k, pick(r, TUBE), r);
else if (roll < 0.73) barrel(L, x, y, Math.round(r.range(8, 14) * k), Math.round(r.range(10, 16) * k), BARREL);
else fingers(L, x, y, k, pick(r, FINGERS), r);
}
// ---------------------------------------------------------------------------
// Swaying life, drawn every frame
// ---------------------------------------------------------------------------
export interface Anemone {
x: number;
y: number;
size: number;
pal: Record<'stalk' | 'back' | 'body' | 'tip', RGB>;
seed: number;
/** How many clownfish call it home. */
clowns: number;
}
const ANEMONE = [
pal({ stalk: '#8a3a5a', back: '#a8487a', body: '#dc64a0', tip: '#ffb4de' }),
pal({ stalk: '#6a4a7a', back: '#5a9a5a', body: '#86c872', tip: '#eca4f4' }),
pal({ stalk: '#9a6a4a', back: '#c8784a', body: '#f2a464', tip: '#fff2c4' }),
];
interface Fan {
x: number;
y: number;
h: number;
/** Packed [dx, dy, tone] triples. */
pts: number[];
tones: RGB[];
seed: number;
}
const FAN = [
[hex('#5a2468'), hex('#9a4ab0'), hex('#c878d8')],
[hex('#6a2028'), hex('#c04a4a'), hex('#ec7a68')],
[hex('#7a4018'), hex('#e08a3a'), hex('#f8b464')],
];
function makeFan(h: number, seed: number): number[] {
const pts: number[] = [];
const hw = h * 0.42;
const cy = h * 0.55;
for (let dy = -h; dy <= 0; dy++) {
for (let dx = -Math.ceil(hw); dx <= hw; dx++) {
if (dy > -4) {
if (dx === 0) pts.push(dx, dy, 0);
continue;
}
const e = (dx / hw) ** 2 + ((dy + cy) / cy) ** 2;
if (e > 1) continue;
const a = Math.atan2(dx, -dy);
const rib = Math.abs((((a / 0.2 + noise2(dx / 5, dy / 5, seed) * 1.4) % 1) + 1) % 1 - 0.5) < 0.13;
const mesh = Math.abs(Math.sin((dx + dy * 0.6) * 1.1)) < 0.3 || Math.abs(Math.sin((dx - dy * 0.6) * 1.1)) < 0.3;
if (rib || e > 0.86) pts.push(dx, dy, 1);
else if (mesh && noise2(dx / 4, dy / 4, seed + 1) > 0.25) pts.push(dx, dy, 2);
}
}
return pts;
}
interface Strand {
x: number;
y: number;
len: number;
phase: number;
leafy: boolean;
dark: RGB;
light: RGB;
}
const ALGAE = [
[hex('#2e7a3e'), hex('#6cc062')],
[hex('#8a3048'), hex('#d8708a')],
[hex('#6a6420'), hex('#c4b048')],
[hex('#2a6a5a'), hex('#5ac0a0')],
];
interface Tuft {
x: number;
y: number;
blades: { dx: number; len: number; lean: number }[];
}
const GRASS_DARK = hex('#3a7a42');
const GRASS_LIGHT = hex('#8ccc6a');
// ---------------------------------------------------------------------------
// Building the reef
// ---------------------------------------------------------------------------
export interface Cluster {
cx: number;
hw: number;
topAt: (x: number) => number;
index: number;
}
interface Reef {
far: Layer;
mid: Layer;
near: Layer;
fans: Fan[];
backStrands: Strand[];
frontStrands: Strand[];
tufts: Tuft[];
anemones: Anemone[];
clusters: Cluster[];
foreground: { x: number; blades: { dx: number; len: number; phase: number; w: number }[] }[];
}
export const NEAR_BASE = floorRow(NEAR);
const MID_BASE = floorRow(MID);
const FAR_BASE = floorRow(FAR);
/** World x range where the clownfish anemones go, so they are on screen through the first minute. */
const CLOWN_HOMES = [60, 380] as const;
function buildNear(L: Layer, reef: Reef): void {
const r = new Rng(2024);
let x = -6;
let i = 0;
while (x < L.img.w - PAD) {
const hw = r.range(18, 46);
const cx = x + hw;
const ht = r.next() < 0.25 ? r.range(46, 66) : r.range(16, 38);
const topAt = mound(L, cx, hw, ht, NEAR_BASE, 100 + i * 7, ROCK);
const cluster = { cx, hw, topAt, index: i };
reef.clusters.push(cluster);
// Sea fans and tall kelp stand behind the rock, rooted out of sight.
if (r.next() < 0.6) {
const fx = cx + r.range(-hw * 0.5, hw * 0.5);
const h = r.int(16, 30);
const seed = r.int(0, 999);
reef.fans.push({ x: fx, y: topAt(fx) + 3, h, pts: makeFan(h, seed), tones: pick(r, FAN), seed });
}
if (r.next() < 0.4) {
const sx = cx + r.range(-hw * 0.6, hw * 0.6);
const [dark, light] = pick(r, ALGAE);
for (let k = 0; k < r.int(2, 4); k++) {
reef.backStrands.push({ x: sx + k * 3, y: topAt(sx) + 4, len: r.int(22, 44), phase: r.range(0, 6), leafy: true, dark, light });
}
}
// Coral crowding the top of the rock, and smaller growths down its face.
for (let fx = cx - hw * 0.85; fx < cx + hw * 0.85; fx += r.range(4, 9)) {
const ty = topAt(fx) + 1;
if (ty < NEAR_BASE - 3) coral(L, fx, ty, 1, r);
}
for (let k = 0; k < hw / 5; k++) {
const fx = cx + r.range(-hw * 0.8, hw * 0.8);
const top = topAt(fx);
if (NEAR_BASE - top < 10) continue;
coral(L, fx, Math.round(r.range(top + 5, NEAR_BASE - 1)), 0.6, r);
}
// Small things tucked into the rock face.
for (let k = 0; k < r.int(1, 3); k++) {
const fx = cx + r.range(-hw * 0.6, hw * 0.6);
const top = topAt(fx);
if (NEAR_BASE - top < 14) continue;
const fy = Math.round(r.range(top + 6, NEAR_BASE - 2));
const roll = r.next();
if (roll < 0.4) clam(L, fx - 4, fy, r);
else if (roll < 0.7) seaStar(L, fx, fy, pick(r, STARS));
else fingers(L, fx, fy, 0.6, pick(r, FINGERS), r);
}
// Anemones: the first few within reach of the opening minute are home to clownfish.
const homes = reef.anemones.filter((a) => a.clowns > 0).length;
const clownHome = cx > CLOWN_HOMES[0] && cx < CLOWN_HOMES[1] && homes < 3;
if (clownHome || r.next() < 0.4) {
const ax = cx + r.range(-hw * 0.3, hw * 0.3);
reef.anemones.push({
x: ax,
y: topAt(ax) + 2,
size: clownHome ? r.int(12, 14) : r.int(8, 12),
pal: clownHome ? ANEMONE[homes === 1 ? 2 : 0] : pick(r, ANEMONE),
seed: r.int(0, 999),
clowns: clownHome ? (homes === 2 ? 1 : 2) : 0,
});
}
// Algae at the foot of the rock.
for (const side of [-1, 1]) {
if (r.next() < 0.45) continue;
const sx = cx + side * hw * r.range(0.55, 0.85);
const [dark, light] = pick(r, ALGAE);
for (let k = 0; k < r.int(2, 4); k++) {
reef.frontStrands.push({ x: sx + k * 2, y: NEAR_BASE + r.int(1, 4), len: r.int(9, 22), phase: r.range(0, 6), leafy: r.next() < 0.6, dark, light });
}
}
const gap = r.range(16, 64);
// Sea grass, shells and the odd sea star on the sand between outcrops.
for (let gx = cx + hw + 4; gx < cx + hw + gap - 4; gx += r.range(8, 20)) {
if (r.next() < 0.6) {
reef.tufts.push({
x: gx,
y: NEAR_BASE + r.int(2, 8),
blades: Array.from({ length: r.int(4, 8) }, () => ({ dx: r.int(-3, 3), len: r.range(5, 14), lean: r.range(-0.4, 0.4) })),
});
} else if (r.next() < 0.5) {
seaStar(L, gx, NEAR_BASE + r.int(4, 8), pick(r, STARS));
} else {
brain(L, gx, NEAR_BASE + r.int(2, 5), r.int(2, 3), pick(r, BRAIN), 0);
}
}
x = cx + hw + gap;
i++;
}
// Water between here and the viewer softens the shadows near the sand.
fogLayer(L, (y) => 0.05 + Math.max(0, (y - 120) / 45) * 0.12);
}
function buildMid(L: Layer): void {
const r = new Rng(77);
const rock: RockPal = { ...ROCK, pink: hex('#b0708e'), pink2: hex('#c890a8') };
let x = -10;
let i = 0;
while (x < L.img.w - PAD) {
const hw = r.range(12, 32);
const cx = x + hw;
const ht = r.next() < 0.2 ? r.range(32, 46) : r.range(8, 26);
const topAt = mound(L, cx, hw, ht, MID_BASE, 300 + i * 5, rock);
for (let fx = cx - hw * 0.8; fx < cx + hw * 0.8; fx += r.range(3, 7)) {
const ty = topAt(fx) + 1;
if (ty > MID_BASE - 2) continue;
if (r.next() < 0.15) {
const h = r.int(10, 18);
const tones = pick(r, FAN);
const pts = makeFan(h, r.int(0, 999));
for (let k = 0; k < pts.length; k += 3) put(L, fx + pts[k], ty + 2 + pts[k + 1], tones[pts[k + 2]]);
} else coral(L, fx, ty, 0.6, r);
}
for (let k = 0; k < hw / 6; k++) {
const fx = cx + r.range(-hw * 0.7, hw * 0.7);
const top = topAt(fx);
if (MID_BASE - top > 8) coral(L, fx, Math.round(r.range(top + 4, MID_BASE - 1)), 0.4, r);
}
x = cx + hw + r.range(10, 50);
i++;
}
fogLayer(L, () => 0.34);
}
function buildFar(L: Layer): void {
const r = new Rng(31);
const rock: RockPal = { ...ROCK, pink: ROCK.mid, pink2: ROCK.light };
let x = -10;
let i = 0;
while (x < L.img.w - PAD) {
const hw = r.range(16, 44);
const cx = x + hw;
const ht = r.next() < 0.2 ? r.range(50, 84) : r.range(10, 34);
const topAt = mound(L, cx, hw, ht, FAR_BASE, 500 + i * 3, rock);
for (let fx = cx - hw * 0.8; fx < cx + hw * 0.8; fx += r.range(4, 9)) {
const ty = topAt(fx) + 1;
if (ty > FAR_BASE - 2) continue;
if (r.next() < 0.5) brain(L, fx, ty, r.int(2, 4), pick(r, BRAIN), 0);
else branchCoral(L, fx, ty, r.range(5, 10), pick(r, BRANCH), r);
}
x = cx + hw + r.range(0, 30);
i++;
}
fogLayer(L, (y) => 0.6 + Math.max(0, (FAR_BASE - y) / FAR_BASE) * 0.15);
}
function buildForeground(reef: Reef): void {
const r = new Rng(404);
for (let x = 120; x < CAM_MAX * 1.5 + W; x += r.range(170, 300)) {
reef.foreground.push({
x,
blades: Array.from({ length: r.int(3, 6) }, () => ({ dx: r.range(-10, 10), len: r.range(22, 48), phase: r.range(0, 6), w: r.int(2, 3) })),
});
}
}
let reef: Reef | undefined;
/** The reef is built the first time it is needed (it takes a moment), then reused. */
export function getReef(): Reef {
if (reef) return reef;
const built: Reef = {
far: newLayer(FAR),
mid: newLayer(MID),
near: newLayer(NEAR),
fans: [],
backStrands: [],
frontStrands: [],
tufts: [],
anemones: [],
clusters: [],
foreground: [],
};
buildFar(built.far);
buildMid(built.mid);
buildNear(built.near, built);
buildForeground(built);
reef = built;
return built;
}
// ---------------------------------------------------------------------------
// Drawing
// ---------------------------------------------------------------------------
const CAUSTIC = hex('#fffbe8');
function blit(s: Surface, L: Layer, cam: number, t?: number): void {
const off = Math.round(cam * L.p) + PAD;
const src = L.img.data;
const lw = L.img.w;
const dst = s.data;
for (let y = L.top; y < H; y++) {
// Sunlight dances most on the shallow, upper parts of the reef.
const ck = 0.34 * (1 - (y / H) * 0.6);
for (let x = 0; x < W; x++) {
const lx = x + off;
if (lx < 0 || lx >= lw) continue;
const i = (y * lw + lx) * 4;
if (src[i + 3] === 0) continue;
const o = (y * W + x) * 4;
dst[o] = src[i];
dst[o + 1] = src[i + 1];
dst[o + 2] = src[i + 2];
// Caustics are worked out on every other pixel and shared with the next one.
if (t === undefined || (x + y) & 1) continue;
const k = caustic(lx, y, t);
if (k <= 0) continue;
s.light(x, y, CAUSTIC, ditherStep(k * ck, x, y, 5));
if (src[i + 7] !== 0) s.light(x + 1, y, CAUSTIC, ditherStep(k * ck, x + 1, y, 5));
}
}
}
export function drawFarReef(s: Surface, f: Frame): void {
blit(s, getReef().far, f.cam);
}
export function drawMidReef(s: Surface, f: Frame): void {
blit(s, getReef().mid, f.cam);
}
export function drawNearReef(s: Surface, f: Frame): void {
blit(s, getReef().near, f.cam, f.t);
}
const onScreen = (x: number, margin: number) => x > -margin && x < W + margin;
function drawStrand(s: Surface, f: Frame, st: Strand): void {
let px = st.x - f.cam;
if (!onScreen(px, 30)) return;
let py = st.y;
for (let k = 0; k < st.len; k++) {
const u = k / st.len;
const ang = (f.surge * 0.4 + Math.sin(f.t * 0.9 + k * 0.18 + st.phase) * 0.22) * u;
px += Math.sin(ang);
py -= Math.cos(ang);
const x = Math.round(px);
const y = Math.round(py);
s.set(x, y, st.light);
s.set(x + 1, y, st.dark);
if (st.leafy && k % 3 === 0 && k > 1) {
const side = (k / 3) % 2 ? 1 : -1;
s.set(x + (side > 0 ? 2 : -1), y - 1, st.light);
if (k < st.len - 4) s.set(x + (side > 0 ? 3 : -2), y - 2, st.dark);
}
}
}
function drawFan(s: Surface, f: Frame, fan: Fan): void {
const ox = fan.x - f.cam;
if (!onScreen(ox, 30)) return;
const sway = 0.75 * f.surge + 0.25 * Math.sin(f.t * 1.1 + fan.seed);
const p = fan.pts;
for (let k = 0; k < p.length; k += 3) {
const up = -p[k + 1] / fan.h;
s.set(Math.round(ox + p[k] + sway * up * up * 3), fan.y + p[k + 1], fan.tones[p[k + 2]]);
}
}
function drawAnemone(s: Surface, f: Frame, a: Anemone): void {
const ox = a.x - f.cam;
if (!onScreen(ox, 30)) return;
const cw = Math.round(a.size * 0.3);
const ch = Math.round(a.size * 0.35);
const oy = a.y - ch;
for (let dy = 0; dy <= ch; dy++) {
for (let dx = -cw; dx <= cw; dx++) s.set(Math.round(ox) + dx, oy + dy, dx > cw / 2 ? scale(a.pal.stalk, 0.8) : a.pal.stalk);
}
const n = Math.round(a.size * 1.1);
for (let pass = 0; pass < 2; pass++) {
for (let i = 0; i < n; i++) {
const u = n > 1 ? i / (n - 1) : 0.5;
const a0 = (u - 0.5) * 2.6 + (pass === 0 ? 0.12 : -0.05);
const len = a.size * (0.7 + 0.35 * hash(i, pass, a.seed)) * (pass === 0 ? 0.85 : 1);
let px = ox + (u - 0.5) * cw * 1.8;
let py = oy + (pass === 0 ? 0 : 1);
let ang = a0;
for (let k = 0; k < len; k += 0.6) {
ang += f.surge * 0.035 + Math.sin(f.t * 1.4 + i * 0.9 + k * 0.25 + a.seed) * 0.03 + Math.sign(a0) * Math.abs(a0) * 0.012;
px += Math.sin(ang) * 0.6;
py -= Math.cos(ang) * 0.6;
const c = k > len - 1.6 ? a.pal.tip : pass === 0 ? a.pal.back : a.pal.body;
s.set(Math.round(px), Math.round(py), c);
}
}
}
}
function drawTuft(s: Surface, f: Frame, tf: Tuft): void {
const ox = tf.x - f.cam;
if (!onScreen(ox, 20)) return;
for (const b of tf.blades) {
let px = ox + b.dx;
let py = tf.y;
for (let k = 0; k < b.len; k++) {
const u = k / b.len;
const ang = b.lean * u + (f.surge * 0.5 + Math.sin(f.t * 1.2 + b.dx) * 0.15) * u * u;
px += Math.sin(ang);
py -= Math.cos(ang);
s.set(Math.round(px), Math.round(py), u > 0.5 ? GRASS_LIGHT : GRASS_DARK);
}
}
}
/** Sea fans and kelp standing behind the near reef. */
export function drawNearBack(s: Surface, f: Frame): void {
const reef = getReef();
for (const fan of reef.fans) drawFan(s, f, fan);
for (const st of reef.backStrands) drawStrand(s, f, st);
}
/** Anemones, algae and sea grass in front of the near reef. */
export function drawNearFront(s: Surface, f: Frame): void {
const reef = getReef();
for (const a of reef.anemones) drawAnemone(s, f, a);
for (const st of reef.frontStrands) drawStrand(s, f, st);
for (const tf of reef.tufts) drawTuft(s, f, tf);
}
const FG_DARK = hex('#0c3038');
const FG_EDGE = hex('#1a5258');
/** Tall dark seaweed close to the viewer, sliding past faster than everything else. */
export function drawForeground(s: Surface, f: Frame): void {
for (const clump of getReef().foreground) {
const ox = clump.x - f.cam * 1.5;
if (!onScreen(ox, 40)) continue;
for (const b of clump.blades) {
let px = ox + b.dx;
let py = H + 2;
for (let k = 0; k < b.len; k++) {
const u = k / b.len;
const ang = (f.surge * 0.45 + Math.sin(f.t * 0.7 + b.phase + k * 0.1) * 0.2) * u;
px += Math.sin(ang);
py -= Math.cos(ang);
const w = u > 0.8 ? 1 : b.w;
for (let q = 0; q < w; q++) s.set(Math.round(px) + q, Math.round(py), q === 0 ? FG_EDGE : FG_DARK);
}
}
}
}
/** Now and then a few bubbles escape from the coral and wobble up toward the light. */
export function drawBubbles(s: Surface, f: Frame): void {
for (const c of getReef().clusters) {
if (c.index % 4 !== 3) continue;
const x = c.cx + c.hw * 0.2;
if (onScreen(x - f.cam, 20)) drawBubbleStream(s, f, x, c.topAt(x) - 2, c.index);
}
}

View File

@ -0,0 +1,96 @@
import { hex, mix, scale, type RGB } from '../../engine/color';
import { hash } from '../../engine/rng';
import { Stamp } from '../../engine/stamp';
import type { Surface } from '../../engine/Surface';
import { pathTrack } from '../../engine/Timeline';
import type { Frame } from './timeline';
import { TIMES } from './timeline';
import { drawFloorShadow } from './water';
import { W } from './world';
/**
* A spotted ray gliding right to left across the screen over a minute, seen slightly from above
* so its wide wings ripple as it flies.
*/
const TOP = hex('#3c4c6c');
const EDGE = hex('#2a3450');
const HIGH = hex('#5a6e92');
const SPOT = hex('#e8f4ff');
const TAIL = hex('#283048');
const SIZE = 1.35;
/** How flattened the wings look from this viewing angle. */
const TILT = 0.8;
const path = pathTrack([
[TIMES.stingray[0], W + 60, 112],
[45, 236, 120],
[60, 160, 114],
[75, 80, 124],
[TIMES.stingray[1], -70, 118],
]);
/** Half the wingspan at a point along the body (local x from -14 at the back to 14 at the nose). */
function halfSpan(lx: number): number {
const u = (lx + 14) / 28;
if (u <= 0 || u >= 1) return 0;
return 22 * Math.pow(Math.sin(Math.PI * Math.pow(u, 0.8)), 0.9);
}
const stamp = new Stamp();
export function stingrayPos(t: number): [number, number] | undefined {
if (t < TIMES.stingray[0] || t > TIMES.stingray[1]) return undefined;
const [x, y] = path(t);
return [x, y + Math.sin(t * 0.7) * 2];
}
/** Its shadow on the sand, drawn with the floor. */
export function drawStingrayShadow(s: Surface, f: Frame): void {
const p = stingrayPos(f.t);
if (p) drawFloorShadow(s, p[0] + 4, 171, 20, 3.5, 0.35);
}
export function drawStingray(s: Surface, f: Frame): void {
const p = stingrayPos(f.t);
if (!p) return;
const [cx, cy] = p;
const t = f.t;
// Swimming left, so local "forward" points to screen left.
const dir = -1;
stamp.begin(cx - 80, cy - 30, 160, 60);
// The tail trails behind, swaying.
for (let k = 0; k < 36; k += 0.5) {
const sway = Math.sin(t * 1.3 - k * 0.15) * 2 * (k / 36);
stamp.put(cx - dir * (14 + k) * SIZE * 0.95, cy + sway + k * 0.08, TAIL);
}
// Wings are filled from the far side to the near side so the near wing covers the far one.
const beat = t * 2 * Math.PI * 0.32;
for (let z = 22; z >= -22; z -= 0.4) {
for (let lx = -14; lx <= 15; lx += 0.4) {
const span = halfSpan(lx);
const head = lx > 12 && Math.abs(z) < 3.2 - (lx - 12) * 0.8;
if (Math.abs(z) > span && !head) continue;
const reach = Math.abs(z) / 22;
// A ripple runs from the front of each wing to the back.
const lift = 3.2 * Math.pow(reach, 1.5) * Math.sin(beat - lx * 0.28);
const slope = 3.2 * Math.pow(reach, 1.5) * Math.cos(beat - lx * 0.28);
const x = cx + dir * lx * SIZE;
const y = cy + (-z * TILT - lift) * SIZE * 0.7;
// Wings tilted up toward the light read brighter; the far side sits a little in shade.
let c: RGB = slope > 1.2 ? HIGH : TOP;
if (z > 8) c = mix(c, EDGE, 0.25);
if (Math.abs(z) > span - 1.2 && !head) c = EDGE;
// White spots scattered over the back.
const gx = Math.round(lx / 2.6);
const gz = Math.round(z / 2.6);
if (hash(gx, gz, 61) > 0.72 && Math.abs(z) < span - 2 && Math.hypot(lx - gx * 2.6, z - gz * 2.6) < 0.8) c = SPOT;
if (lx > 9 && lx < 11 && Math.abs(Math.abs(z) - 3) < 0.6) c = scale(EDGE, 0.6);
stamp.put(x, y, c);
}
}
stamp.draw(s, 0.7);
}

View File

@ -0,0 +1,68 @@
import { progress, track } from '../../engine/Timeline';
/** All timings for The Reef, in seconds. */
export const DURATION = 300;
export const TIMES = {
fadeIn: [0, 6],
fadeOut: [291, 300],
/** Sunfish and clownfish open the scene. */
sunfish: [0, 75],
stingray: [30, 90],
jellyfish: [118, 195],
schools: [178, 250],
babyTurtle: 238,
turtlesMeet: 270,
} as const;
/**
* The camera drifts right along the reef. It eases off while the stingray glides past so the ray
* clearly crosses the reef, and again for the turtles' meeting so it can be watched at rest.
*/
const camSpeed = track([
[0, 3.5],
[24, 3.5],
[36, 2.4],
[86, 2.4],
[100, 3.5],
[250, 3.5],
[266, 1.2],
[284, 1.2],
[298, 2.4],
]);
/** Camera position integrated once into a table, so it stays a pure function of t. */
const CAM_STEP = 0.05;
const CAM: Float64Array = (() => {
const n = Math.ceil(DURATION / CAM_STEP) + 2;
const a = new Float64Array(n);
for (let i = 1; i < n; i++) a[i] = a[i - 1] + camSpeed((i - 0.5) * CAM_STEP) * CAM_STEP;
return a;
})();
export function camAt(t: number): number {
const f = Math.max(0, Math.min(DURATION, t)) / CAM_STEP;
const i = Math.floor(f);
return CAM[i] + (CAM[i + 1] - CAM[i]) * (f - i);
}
/** How far the camera travels over the whole meditation. */
export const CAM_MAX = camAt(DURATION);
export interface Frame {
t: number;
/** Camera position: something at parallax p and world x is drawn at x - cam * p. */
cam: number;
/** Gentle back-and-forth surge of the water that everything rooted sways with, -1..1. */
surge: number;
fade: number;
}
export function frameAt(t: number): Frame {
return {
t,
cam: camAt(t),
surge: 0.65 * Math.sin(t * 0.52) + 0.35 * Math.sin(t * 0.23 + 1.3),
fade: progress(t, TIMES.fadeIn[0], TIMES.fadeIn[1]) * (1 - progress(t, TIMES.fadeOut[0], TIMES.fadeOut[1])),
};
}

View File

@ -0,0 +1,223 @@
import { hex, scale, type RGB } from '../../engine/color';
import { hash } from '../../engine/rng';
import { sampleShape, Stamp } from '../../engine/stamp';
import type { Surface } from '../../engine/Surface';
import { pathTrack, progress, track } from '../../engine/Timeline';
import type { Frame } from './timeline';
import { TIMES } from './timeline';
import { fog } from './world';
/**
* A baby sea turtle arrives at four minutes and explores the reef. Two adults come to meet it;
* they greet nose to nose, then all three swim off together into the blue.
*/
interface TurtlePal {
shell: RGB;
scute: RGB;
scuteLight: RGB;
seam: RGB;
rim: RGB;
skin: RGB;
skinLight: RGB;
plastron: RGB;
eye: RGB;
}
const ADULT: TurtlePal = {
shell: hex('#6a5430'),
scute: hex('#8c7040'),
scuteLight: hex('#b89654'),
seam: hex('#3e301c'),
rim: hex('#5a4626'),
skin: hex('#7a8c5c'),
skinLight: hex('#b4c48e'),
plastron: hex('#e6d6a2'),
eye: hex('#141410'),
};
const BABY: TurtlePal = {
shell: hex('#4a3c2c'),
scute: hex('#5e4c36'),
scuteLight: hex('#80684a'),
seam: hex('#2a2018'),
rim: hex('#3c3024'),
skin: hex('#4c5a50'),
skinLight: hex('#d4dace'),
plastron: hex('#ecead8'),
eye: hex('#0c0c0c'),
};
/** Distance from p to a tapering limb running from (ax, ay) to (bx, by); <= 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)));
const d = Math.hypot(lx - ax - vx * u, ly - ay - vy * u);
return d - (r0 + (r1 - r0) * u);
}
function turtleSampler(p: TurtlePal, stroke: number, nod: number, rearKick: number) {
// Front flippers sweep from raised-back (stroke -1) to swept-down (stroke 1).
const a = Math.PI - 0.15 - 0.85 * stroke;
const L = 11;
const sx = 5;
const sy = 1.5;
const tx = sx + Math.cos(a) * L;
const ty = sy + Math.sin(a) * L;
const flipper = (lx: number, ly: number, far: boolean): RGB | undefined => {
const d = limb(lx, ly, sx, sy, tx, ty, 2.3, 0.7);
if (d > 0) return undefined;
const c = d > -0.7 ? p.skinLight : hash(Math.round(lx * 1.3), Math.round(ly * 1.3), 9) > 0.75 ? p.skinLight : p.skin;
return far ? scale(c, 0.68) : c;
};
return (lx: number, ly: number): RGB | undefined => {
const near = flipper(lx, ly, false);
if (near) return near;
// Head and neck.
const hy = -0.6 + nod;
if (Math.hypot(lx - 14.2, ly - hy + 0.6) < 0.75) return p.eye;
const head = ((lx - 13) / 3.6) ** 2 + ((ly - hy) / 2.6) ** 2;
const neck = ((lx - 9.5) / 3) ** 2 + ((ly - 0.2) / 2.2) ** 2;
if (head <= 1 || neck <= 1) {
if (head <= 1 && lx > 15.6 && ly > hy) return p.seam;
if (ly > hy + 0.8) return p.skinLight;
return hash(Math.round(lx * 1.2), Math.round(ly * 1.2), 8) > 0.7 ? p.skinLight : p.skin;
}
// Back flipper and tail.
if (limb(lx, ly, -8, 1.8, -12.5, 2.8 + rearKick, 1.4, 0.8) <= 0) return p.skin;
if (limb(lx, ly, -9, 0.8, -12, 1.2, 0.7, 0.3) <= 0) return p.skin;
// Shell: a dome over a flatter belly.
const sy0 = -0.5;
const e = (lx / 10.5) ** 2 + ((ly - sy0) / (ly < sy0 ? 6 : 3)) ** 2;
if (e <= 1) {
if (ly > sy0 + 1.4) return p.plastron;
if (ly > sy0) return p.rim;
if (e > 0.8) return ((lx + 20) * 0.55) % 1 < 0.22 ? p.seam : p.rim;
if (Math.abs(ly + 3.6) < 0.45) return p.seam;
const cell = (((lx + 1.5) % 5) + 5) % 5;
if (Math.abs(cell - 2.5) > 2.05) return p.seam;
const centre = Math.abs(cell - 2.5) < 1.1 && Math.abs(ly - (ly < -3.6 ? -4.9 : -1.9)) < 0.9;
return centre ? p.scuteLight : p.scute;
}
return flipper(lx + 1, ly + 1.4, true);
};
}
interface Turtle {
path: (t: number) => [number, number];
facing: (t: number) => number;
scale: number;
pal: TurtlePal;
/** Seconds per flipper stroke. */
period: number;
start: number;
seed: number;
}
const BABY_TURTLE: Turtle = {
path: pathTrack([
[TIMES.babyTurtle, -34, 96],
[246, 40, 90],
[252, 90, 98],
[257, 125, 92],
[262, 148, 82],
[267, 160, 88],
[271, 168, 90],
[275, 172, 89],
[279, 174, 90],
[283, 182, 88],
[288, 212, 78],
[294, 252, 68],
[300, 300, 58],
]),
facing: () => 1,
scale: 0.65,
pal: BABY,
period: 1.7,
start: TIMES.babyTurtle,
seed: 0,
};
const ADULT_A: Turtle = {
path: pathTrack([
[260, 372, 72],
[266, 280, 78],
[271, 222, 86],
[275, 202, 88],
[278, 198, 89],
[281, 204, 86],
[285, 222, 72],
[290, 252, 60],
[295, 286, 50],
[300, 330, 42],
]),
facing: track([
[0, -1],
[279, -1],
[282.5, 1],
]),
scale: 1.25,
pal: ADULT,
period: 3.2,
start: 260,
seed: 1,
};
const ADULT_B: Turtle = {
path: pathTrack([
[262, 404, 112],
[270, 290, 114],
[276, 226, 108],
[280, 206, 110],
[283, 198, 108],
[286, 210, 100],
[290, 232, 88],
[295, 268, 80],
[300, 316, 72],
]),
facing: track([
[0, -1],
[282, -1],
[285.5, 1],
]),
scale: 1.4,
pal: ADULT,
period: 3.6,
start: 262,
seed: 2,
};
const stamp = new Stamp();
function drawTurtle(s: Surface, f: Frame, tu: Turtle): void {
const t = f.t;
if (t < tu.start) return;
const [x, y0] = tu.path(t);
const [nx, ny] = tu.path(t + 0.2);
// Nuzzling: small bobs while the three are together.
const greet = progress(t, TIMES.turtlesMeet + 2, TIMES.turtlesMeet + 4) * (1 - progress(t, 281, 284));
const y = y0 + Math.sin(t * 2.4 + tu.seed) * 1.2 * greet;
const vx = nx - x;
const vy = ny - y0;
const facing = tu.facing(t);
// Level out while turning around, when the side view is squeezed narrow.
const pitch = Math.max(-0.45, Math.min(0.45, Math.atan2(-vy, Math.abs(vx) + 0.4) * 0.8)) * Math.abs(facing);
const phase = ((t - tu.start) / tu.period + tu.seed * 0.3) % 1;
// Strong down-stroke, slower recovery, then a short glide.
const sw = Math.sin(phase * Math.PI * 2);
const stroke = Math.sign(sw) * Math.abs(sw) ** 0.7;
const nod = Math.sin(t * 1.3 + tu.seed) * 0.4 + greet * Math.sin(t * 3) * 0.5;
// As they leave they shrink into the distance and fade into the blue.
const away = progress(t, 286, 300);
const sc = tu.scale * (1 - 0.3 * away);
sampleShape(stamp, { x, y, scale: sc, facing, pitch }, 24, turtleSampler(tu.pal, stroke, nod, Math.sin(phase * Math.PI * 2 + 1) * 0.8));
const haze = 0.4 * away + (tu === ADULT_B ? 0.08 : 0);
stamp.draw(s, 0.6, 1, haze > 0 ? (c, _x, yy) => fog(c, yy, haze) : undefined);
}
export function drawTurtles(s: Surface, f: Frame): void {
drawTurtle(s, f, ADULT_B);
drawTurtle(s, f, BABY_TURTLE);
drawTurtle(s, f, ADULT_A);
}

View File

@ -0,0 +1,240 @@
import { bayer, ditherStep, hex, mix, type RGB } from '../../engine/color';
import { hash, noise1, noise2, Rng } from '../../engine/rng';
import { Surface } from '../../engine/Surface';
import { CAM_MAX, type Frame } from './timeline';
import { FLOOR_TOP, floorParallax, H, SUN_X, W, WATER } from './world';
const LIGHT = hex('#e4fbff');
const SUNLIGHT = hex('#fff8e0');
const SURFACE_DEEP = hex('#6ccfe4');
const SURFACE_MID = hex('#a6ecf4');
const SURFACE_LIT = hex('#dcfaff');
// ---------------------------------------------------------------------------
// Open water
// ---------------------------------------------------------------------------
/** The water gradient (in dithered bands) with the sun's glow under the surface, worked out once. */
const BASE: Uint8ClampedArray = (() => {
const s = new Surface(W, H);
const BANDS = 18;
for (let y = 0; y < H; y++) {
for (let x = 0; x < W; x++) {
const v = (y / (H - 1)) * (BANDS - 1) + (bayer(x, y) - 0.5) * 0.9;
const band = Math.max(0, Math.min(BANDS - 1, Math.round(v)));
s.set(x, y, WATER[Math.round((band / (BANDS - 1)) * (H - 1))]);
// Brighter water around where the sun stands overhead.
const glow = Math.exp(-(((x - SUN_X) / 80) ** 2)) * Math.max(0, 1 - y / 90) ** 2 * 0.32;
s.light(x, y, SUNLIGHT, ditherStep(glow, x, y, 5));
}
}
return s.data;
})();
/** Rows hidden behind the rippling underside of the surface at column x. */
function surfaceLine(xw: number, t: number): number {
return 8 + 1.4 * Math.sin(xw * 0.07 - t * 0.8) + 1.1 * Math.sin(xw * 0.13 + t * 0.55) + (noise1(xw / 9 + t * 0.3, 5) - 0.5) * 2.4;
}
export function drawWater(s: Surface, f: Frame): void {
s.data.set(BASE);
const t = f.t;
for (let x = 0; x < W; x++) {
const xw = x + f.cam * 0.8;
const line = surfaceLine(xw, t);
const sun = Math.exp(-(((x - SUN_X) / 46) ** 2));
for (let y = 0; y < line + 3; y++) {
if (y < line - 0.5) {
// The underside of the surface, mirroring light in shifting ripples.
const r = noise2(xw / 7 + t * 0.25, y * 0.8 - t * 0.5, 7) + sun * 0.45;
const c = r > 0.82 ? SURFACE_LIT : r > 0.5 ? SURFACE_MID : SURFACE_DEEP;
s.set(x, y, c);
} else if (y < line + 0.5) {
s.set(x, y, mix(SURFACE_LIT, LIGHT, sun));
} else {
s.blend(x, y, LIGHT, ditherStep((line + 3 - y) * 0.16, x, y, 4));
}
}
}
}
/** Shafts of sunlight fanning down from the surface, slowly shifting with the waves above. */
const RAY_SX = SUN_X;
const RAY_SY = -80;
const RAY_BINS = 720;
const RAY_A0 = -1.3;
const RAY_A1 = 1.3;
/** Which angular bin each 2x2 block falls in as seen from the sun (fixed by the layout). */
const RAY_BLOCKS: Uint16Array = (() => {
const out = new Uint16Array((W / 2) * (H / 2));
for (let by = 0; by < H; by += 2) {
for (let bx = 0; bx < W; bx += 2) {
const a = Math.atan2(bx + 1 - RAY_SX, by + 1 - RAY_SY);
out[(by / 2) * (W / 2) + bx / 2] = Math.max(0, Math.min(RAY_BINS - 1, Math.round(((a - RAY_A0) / (RAY_A1 - RAY_A0)) * (RAY_BINS - 1))));
}
}
return out;
})();
const rayStrength = new Float32Array(RAY_BINS);
export function drawGodRays(s: Surface, f: Frame): void {
const sway = Math.sin(f.t * 0.05) * 0.05;
for (let i = 0; i < RAY_BINS; i++) {
const a = RAY_A0 + (i / (RAY_BINS - 1)) * (RAY_A1 - RAY_A0) + sway;
const n = noise1(a * 22 + f.t * 0.04, 31) * 0.7 + noise1(a * 55 - f.t * 0.09, 32) * 0.3;
rayStrength[i] = Math.max(0, Math.min(1, (n - 0.5) * 3.2));
}
for (let by = 6; by < H; by += 2) {
const fall = Math.pow(1 - by / H, 1.3) * 0.18;
for (let bx = 0; bx < W; bx += 2) {
const k = rayStrength[RAY_BLOCKS[(by / 2) * (W / 2) + bx / 2]] * fall;
if (k <= 0) continue;
for (let y = by; y < by + 2; y++) {
for (let x = bx; x < bx + 2; x++) s.light(x, y, LIGHT, ditherStep(k, x, y, 6));
}
}
}
}
// ---------------------------------------------------------------------------
// Caustics and the sandy floor
// ---------------------------------------------------------------------------
/** Rippling net of focused sunlight, 0–1, at a point on a lit surface. */
export function caustic(x: number, y: number, t: number): number {
const a = noise2(x * 0.11 + t * 0.21, y * 0.2 - t * 0.13, 71);
const b = noise2(x * 0.09 - t * 0.17, y * 0.17 + t * 0.19, 72);
const d = Math.abs(a - b);
return d < 0.085 ? 1 - d / 0.085 : 0;
}
const SAND_LIGHT = hex('#f0dcae');
const SAND_MID = hex('#d8c08e');
const SAND_DARK = hex('#b49c72');
const SAND_SHELL = hex('#fff4e0');
const SAND_PEBBLE = hex('#8a7a6a');
const SAND_TINT = hex('#78bcd0');
const CAUSTIC = hex('#fffbe8');
/**
* Each floor row scrolls at its own fixed rate, so its sand is painted once into a strip
* (pixel i of row y sits at sand position (i - W/2) / p) and only shifted per frame.
*/
const FLOOR: { strip: Uint8ClampedArray; p: number; v: number; haze: number }[] = [];
function floorRows(): typeof FLOOR {
if (FLOOR.length) return FLOOR;
for (let y = FLOOR_TOP; y < H; y++) {
const p = floorParallax(y + 0.5);
const v = 60 / p;
const far = 1 - (y - FLOOR_TOP) / (H - FLOOR_TOP);
const haze = 0.18 + 0.78 * far * far;
const n = W + Math.ceil(CAM_MAX * p) + 2;
const strip = new Uint8ClampedArray(n * 3);
for (let i = 0; i < n; i++) {
const u = (i - W / 2) / p;
const rip = Math.sin(v * 1.2 + noise2(u * 0.07, v * 0.1, 81) * 5) + (bayer(i, y) - 0.5) * 0.5;
let c: RGB = rip > 0.6 ? SAND_LIGHT : rip < -0.55 ? SAND_DARK : SAND_MID;
if (noise2(u / 34, v / 8, 82) > 0.68) c = mix(c, SAND_DARK, 0.45);
const speck = hash(Math.floor(u * 0.8), Math.floor(v * 1.6), 83);
if (speck > 0.993) c = SAND_SHELL;
else if (speck < 0.004) c = SAND_PEBBLE;
strip.set(mix(mix(c, SAND_TINT, 0.22), WATER[y], haze), i * 3);
}
FLOOR.push({ strip, p, v, haze });
}
return FLOOR;
}
export function drawFloor(s: Surface, f: Frame): void {
const d = s.data;
const rows = floorRows();
for (let y = FLOOR_TOP; y < H; y++) {
const { strip, p, v, haze } = rows[y - FLOOR_TOP];
const off = Math.round(f.cam * p);
const ck = 0.42 * (1 - haze);
for (let x = 0; x < W; x++) {
const i = (x + off) * 3;
const o = (y * W + x) * 4;
d[o] = strip[i];
d[o + 1] = strip[i + 1];
d[o + 2] = strip[i + 2];
d[o + 3] = 255;
// Caustics are worked out on every other pixel; they are soft enough not to need more.
if ((x + y) & 1 || ck < 0.03) continue;
const k = caustic(((x + off - W / 2) / p) * 0.9, v, f.t);
if (k > 0) {
s.light(x, y, CAUSTIC, ditherStep(k * ck, x, y, 5));
s.light(x + 1, y, CAUSTIC, ditherStep(k * ck, x + 1, y, 5));
}
}
}
}
/** A soft dark patch on the sand under something swimming low (screen x, size in pixels). */
export function drawFloorShadow(s: Surface, x: number, y: number, rx: number, ry: number, k: number): void {
for (let yy = Math.floor(y - ry); yy <= y + ry; yy++) {
if (yy < FLOOR_TOP) continue;
for (let xx = Math.floor(x - rx); xx <= x + rx; xx++) {
const d = ((xx - x) / rx) ** 2 + ((yy - y) / ry) ** 2;
if (d < 1) s.blend(xx, yy, [10, 40, 70], ditherStep((1 - d) * k, xx, yy, 4));
}
}
}
// ---------------------------------------------------------------------------
// Drifting particles and bubbles
// ---------------------------------------------------------------------------
const SNOW_COLOR = hex('#e6f6f2');
const SNOW = (() => {
const r = new Rng(5);
return Array.from({ length: 80 }, () => ({
x: r.range(0, W + 20),
y: r.range(0, H),
p: r.range(0.25, 1.3),
fall: r.range(0.6, 2.2),
phase: r.range(0, Math.PI * 2),
}));
})();
const wrap = (v: number, m: number) => ((v % m) + m) % m;
/** Specks of marine snow drifting slowly through the water at every depth. */
export function drawMarineSnow(s: Surface, f: Frame): void {
for (const p of SNOW) {
const x = wrap(p.x - f.cam * p.p + f.surge * 4 * p.p + Math.sin(f.t * 0.4 + p.phase) * 2, W + 20) - 10;
const y = wrap(p.y + f.t * p.fall, H);
s.blend(Math.round(x), Math.round(y), SNOW_COLOR, 0.2 + 0.35 * Math.min(1, p.p));
}
}
const BUBBLE = hex('#e8ffff');
const BUBBLE_RIM = hex('#9ae0f0');
/** A small stream of bubbles from a spot on the reef: world x, start row, seed. */
export function drawBubbleStream(s: Surface, f: Frame, wx: number, y0: number, seed: number): void {
const PERIOD = 7 + hash(seed, 1, 90) * 6;
const RISE = 12;
const now = f.t + hash(seed, 2, 90) * PERIOD;
const burst = Math.floor(now / PERIOD);
for (let b = burst - 2; b <= burst; b++) {
for (let i = 0; i < 5; i++) {
const age = now - b * PERIOD - i * 0.45;
const y = y0 - age * RISE * (0.8 + 0.2 * i);
if (age < 0 || y < 10) continue;
const x = wx - f.cam + Math.sin(age * 2.6 + i) * 1.4 + age * 0.4 * f.surge;
const big = age > 3 ? 1 : 0;
const px = Math.round(x);
const py = Math.round(y);
if (big) {
s.blend(px - 1, py, BUBBLE_RIM, 0.6);
s.blend(px + 1, py, BUBBLE_RIM, 0.6);
s.blend(px, py + 1, BUBBLE_RIM, 0.6);
}
s.blend(px, py, BUBBLE, 0.85);
}
}
}

View File

@ -0,0 +1,38 @@
import { gradient, hex, mix, type RGB } from '../../engine/color';
/** Fixed layout of the scene on the 320x180 canvas. */
export const W = 320;
export const H = 180;
/**
* The sea floor is seen in perspective: the row where it fades into the blue scrolls slowest and
* the bottom row fastest. Each reef layer rests on the floor row that matches its parallax.
*/
export const FLOOR_TOP = 124;
export const FAR = 0.3;
export const MID = 0.6;
export const NEAR = 1;
export function floorParallax(y: number): number {
return FAR + (y - FLOOR_TOP) / (H - FLOOR_TOP);
}
export function floorRow(p: number): number {
return Math.round(FLOOR_TOP + (p - FAR) * (H - FLOOR_TOP));
}
/** The sun sits above the surface here (screen x); light and rays fan out from it. */
export const SUN_X = 214;
/** Open water from just under the surface down to the deep blue behind the reef. */
const WATER_STOPS = ['#a4e8f0', '#5cc6de', '#3aa4d0', '#2888bd', '#1e72aa', '#18629b'].map(hex);
export const WATER: readonly RGB[] = Array.from({ length: H }, (_, y) => gradient(WATER_STOPS, y / (H - 1)));
export function waterAt(y: number): RGB {
return WATER[Math.max(0, Math.min(H - 1, Math.round(y)))];
}
/** Fade a color into the surrounding water, k = 0 (right here) to 1 (lost in the blue). */
export function fog(c: RGB, y: number, k: number): RGB {
return k <= 0 ? c : mix(c, waterAt(y), k);
}