Add Mediterranean Coast meditation and clock-synced ambience loop
- New 5-minute scene: clearing skies over a jungle cove with waves, sailboat, gulls, crabs, palms, god rays, and an afternoon-to-evening light arc - Add AmbientLoop (Web Audio) so a looping ambient track stays locked to the meditation clock through pause/seek, keeping visuals like wave crashes in sync with sound; Mediterranean Coast uses fx-waves.mp3 timed to measured crash peaks - Extract ditherStep into engine/color and add Surface.setScaled for allocation-free scaled pixel writes - Introduce ambience option on Meditation type and a Soundtrack wrapper in the Player that drives music and ambience together; disable audio under dev fast-forward - Register mediterranean-coast in the registry and document the new ambience config in the README
This commit is contained in:
parent
15817f7c35
commit
7977dbdd61
15
README.md
15
README.md
|
|
@ -35,16 +35,23 @@ so edits on the host reload in the browser; don't run it and `npm run dev` on th
|
|||
| id | Title | Length |
|
||||
|---|---|---|
|
||||
| `northern-cabin` | Northern Cabin — winter sunset by a quiet lake | 5 min |
|
||||
| `mediterranean-coast` | Mediterranean Coast — clearing skies over a jungle cove | 5 min |
|
||||
|
||||
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
|
||||
that is scaled up crisply, so all art is generated in code.
|
||||
|
||||
## Music
|
||||
## Music and ambience
|
||||
|
||||
Drop an audio file in `public/audio/` and set `music: 'audio/<file>.mp3'` on the meditation
|
||||
(e.g. in `src/meditations/northern-cabin/index.ts`). It fades in at the start and out over the last 10 seconds.
|
||||
With Docker, rebuild the `web` image (`docker compose up --build -d`) so the file is included.
|
||||
Audio lives in `public/audio/` and is configured per meditation in its `index.ts`:
|
||||
|
||||
- `music: 'audio/<file>.mp3'` — background track; fades in at the start and out over the last 10 seconds.
|
||||
- `ambience: { src: 'audio/<file>.mp3', volume }` — a seamless loop (Web Audio) locked to the scene clock,
|
||||
so visuals keyed to it stay in sync, including after pause and skip. Mediterranean Coast uses
|
||||
`fx-waves.mp3`; its wave crashes are timed to the peaks listed in `mediterranean-coast/waves.ts`
|
||||
(re-measure them if the file changes).
|
||||
|
||||
With Docker, rebuild the `web` image (`docker compose up --build -d`) after adding audio so it's included.
|
||||
|
||||
## Dev tools
|
||||
|
||||
|
|
|
|||
|
|
@ -36,6 +36,19 @@ export class Surface {
|
|||
d[i + 3] = 255;
|
||||
}
|
||||
|
||||
/** Set a color multiplied by a brightness factor, without allocating a new color. */
|
||||
setScaled(x: number, y: number, c: RGB, k: number): void {
|
||||
x |= 0;
|
||||
y |= 0;
|
||||
if (x < 0 || y < 0 || x >= this.w || y >= this.h) return;
|
||||
const i = (y * this.w + x) * 4;
|
||||
const d = this.data;
|
||||
d[i] = c[0] * k;
|
||||
d[i + 1] = c[1] * k;
|
||||
d[i + 2] = c[2] * k;
|
||||
d[i + 3] = 255;
|
||||
}
|
||||
|
||||
/** Alpha-blend a color over the existing pixel. */
|
||||
blend(x: number, y: number, c: RGB, a: number): void {
|
||||
if (!(a > 0)) return; // also rejects NaN
|
||||
|
|
|
|||
|
|
@ -45,3 +45,111 @@ export class Music {
|
|||
this.el.load();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A gapless looping ambient sound (Web Audio), locked to the meditation clock: at time t it plays
|
||||
* from t mod loopLength, so visuals keyed to the loop (e.g. waves) stay in sync with what is heard.
|
||||
*/
|
||||
export class AmbientLoop {
|
||||
private ctx?: AudioContext;
|
||||
private master?: GainNode;
|
||||
private buffer?: AudioBuffer;
|
||||
private loading?: Promise<void>;
|
||||
private source?: { node: AudioBufferSourceNode; gain: GainNode; offset: number; startedAt: number };
|
||||
private playing = false;
|
||||
private lastT = 0;
|
||||
|
||||
constructor(
|
||||
private readonly src?: string,
|
||||
private readonly volume = 0.55,
|
||||
private readonly fadeIn = 4,
|
||||
private readonly fadeOut = 10,
|
||||
) {}
|
||||
|
||||
/** Must first be called from a user gesture so the AudioContext may start. */
|
||||
start(t: number): void {
|
||||
if (!this.src) return;
|
||||
this.lastT = t;
|
||||
this.playing = true;
|
||||
if (!this.ctx) {
|
||||
this.ctx = new AudioContext();
|
||||
this.master = this.ctx.createGain();
|
||||
this.master.gain.value = 0;
|
||||
this.master.connect(this.ctx.destination);
|
||||
}
|
||||
void this.ctx.resume();
|
||||
if (this.buffer) this.restart(t);
|
||||
else void this.load().then(() => this.playing && this.restart(this.lastT));
|
||||
}
|
||||
|
||||
pause(): void {
|
||||
this.playing = false;
|
||||
this.stopSource();
|
||||
}
|
||||
|
||||
seek(t: number): void {
|
||||
this.lastT = t;
|
||||
if (this.playing && this.buffer) this.restart(t);
|
||||
}
|
||||
|
||||
/** Call every frame with the meditation clock: applies fades and corrects any drift. */
|
||||
update(t: number, duration: number): void {
|
||||
this.lastT = t;
|
||||
if (!this.ctx || !this.master) return;
|
||||
const k = Math.max(0, Math.min(1, t / this.fadeIn, (duration - t) / this.fadeOut));
|
||||
this.master.gain.setTargetAtTime(k * this.volume, this.ctx.currentTime, 0.1);
|
||||
if (!this.playing || !this.source || !this.buffer) return;
|
||||
const len = this.buffer.duration;
|
||||
const heard = (this.source.offset + this.ctx.currentTime - this.source.startedAt) % len;
|
||||
let drift = Math.abs(heard - (t % len));
|
||||
drift = Math.min(drift, len - drift);
|
||||
if (drift > 0.08) this.restart(t);
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
this.pause();
|
||||
void this.ctx?.close();
|
||||
this.ctx = undefined;
|
||||
}
|
||||
|
||||
private load(): Promise<void> {
|
||||
this.loading ??= fetch(this.src!)
|
||||
.then((r) => r.arrayBuffer())
|
||||
.then((data) => this.ctx!.decodeAudioData(data))
|
||||
.then((buf) => {
|
||||
this.buffer = buf;
|
||||
})
|
||||
.catch(() => {
|
||||
/* missing or undecodable file — the meditation still works silently */
|
||||
});
|
||||
return this.loading;
|
||||
}
|
||||
|
||||
/** Start the loop at the offset matching t, with a short crossfade from any previous source. */
|
||||
private restart(t: number): void {
|
||||
if (!this.ctx || !this.master || !this.buffer) return;
|
||||
this.stopSource(0.04);
|
||||
const now = this.ctx.currentTime;
|
||||
const gain = this.ctx.createGain();
|
||||
gain.gain.setValueAtTime(0, now);
|
||||
gain.gain.linearRampToValueAtTime(1, now + 0.04);
|
||||
gain.connect(this.master);
|
||||
const node = this.ctx.createBufferSource();
|
||||
node.buffer = this.buffer;
|
||||
node.loop = true;
|
||||
node.connect(gain);
|
||||
const offset = t % this.buffer.duration;
|
||||
node.start(now, offset);
|
||||
this.source = { node, gain, offset, startedAt: now };
|
||||
}
|
||||
|
||||
private stopSource(fade = 0.02): void {
|
||||
const src = this.source;
|
||||
if (!src || !this.ctx) return;
|
||||
this.source = undefined;
|
||||
const now = this.ctx.currentTime;
|
||||
src.gain.gain.setValueAtTime(src.gain.gain.value, now);
|
||||
src.gain.gain.linearRampToValueAtTime(0, now + fade);
|
||||
src.node.stop(now + fade + 0.01);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,3 +45,8 @@ const BAYER4 = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];
|
|||
export function bayer(x: number, y: number): number {
|
||||
return (BAYER4[(y & 3) * 4 + (x & 3)] + 0.5) / 16;
|
||||
}
|
||||
|
||||
/** Quantize an alpha to a few dithered steps so soft light still looks like pixel art. */
|
||||
export function ditherStep(a: number, x: number, y: number, n = 6): number {
|
||||
return Math.floor(a * n + bayer(x, y)) / n;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,139 @@
|
|||
import { bayer, ditherStep, hex, mix, type RGB } from '../../engine/color';
|
||||
import { clamp01, progress } from '../../engine/Timeline';
|
||||
import { hash, noise1, noise2 } from '../../engine/rng';
|
||||
import type { Surface } from '../../engine/Surface';
|
||||
import { cloudLight, seaEnd } from './sea';
|
||||
import { lit, sunlit, type Frame } from './timeline';
|
||||
import { breakTime, waterEdge, waveFront, waveReach, wetReach, wetness } from './waves';
|
||||
import { H, SHORE, W } from './world';
|
||||
|
||||
const SAND = hex('#ead4a8');
|
||||
const SAND_SHADE = hex('#d6bb8c');
|
||||
const SAND_LIGHT = hex('#f6e6c4');
|
||||
const WET = hex('#b49a72');
|
||||
const SHALLOW = hex('#a6e2e0');
|
||||
const FOAM = hex('#f4f8f6');
|
||||
const WEED = hex('#6a5a32');
|
||||
const SHELL = hex('#f8e8e0');
|
||||
const PEBBLE = hex('#a89a8a');
|
||||
const DRIFTWOOD = hex('#9a8a74');
|
||||
const DRIFTWOOD_DARK = hex('#6a5a4a');
|
||||
|
||||
/** The high-tide line of dried seaweed, a little up the beach from the waterline. */
|
||||
const tideLine = (x: number) => SHORE[x] + 27 + Math.round(noise1(x / 13, 41) * 4);
|
||||
|
||||
/** Sand texture never changes, so it is worked out once: 0–2 sand tones, 3 shell, 4 pebble, 5 seaweed. */
|
||||
const SAND_MAP: Uint8Array = (() => {
|
||||
const map = new Uint8Array(W * H);
|
||||
for (let x = 0; x < W; x++) {
|
||||
const tl = tideLine(x);
|
||||
for (let y = 0; y < H; y++) {
|
||||
const v = noise2(x * 0.05, y * 0.22, 42) + Math.sin(x * 0.18 + y * 0.9 + noise1(y / 5, 43) * 3) * 0.06;
|
||||
let k = Math.max(0, Math.min(2, Math.floor(v * 2.6 + (bayer(x, y) - 0.5) * 0.5 - 0.3)));
|
||||
const h = hash(x, y, 44);
|
||||
if (h > 0.996) k = 3;
|
||||
else if (h < 0.003) k = 4;
|
||||
if (y >= tl && y <= tl + 1 && noise1(x / 5, 48) > 0.55 && hash(x, y, 45) > 0.55) k = 5;
|
||||
map[y * W + x] = k;
|
||||
}
|
||||
}
|
||||
return map;
|
||||
})();
|
||||
|
||||
export function drawBeach(s: Surface, f: Frame): void {
|
||||
const t = f.t;
|
||||
const palette: RGB[] = [
|
||||
sunlit(f, SAND_LIGHT, 0.2),
|
||||
sunlit(f, SAND, 0.18),
|
||||
sunlit(f, SAND_SHADE, 0.12),
|
||||
sunlit(f, SHELL, 0.2),
|
||||
lit(f, PEBBLE),
|
||||
lit(f, WEED),
|
||||
];
|
||||
const wet = mix(lit(f, WET), f.horizonColor, 0.12);
|
||||
const shallow = sunlit(f, SHALLOW, 0.15);
|
||||
const foam = sunlit(f, FOAM, 0.15);
|
||||
const shaded = f.cover > 0.3;
|
||||
const glintSeed = 46 + Math.floor(t * 2);
|
||||
const reach: number[] = [];
|
||||
const dampness: number[] = [];
|
||||
|
||||
for (let x = 0; x < W; x++) {
|
||||
const edge = waterEdge(f.waves, x, t);
|
||||
// How far up each recent wave wetted this column, and how damp it still is.
|
||||
reach.length = 0;
|
||||
dampness.length = 0;
|
||||
for (const w of f.waves) {
|
||||
const d = wetness(w, x, t);
|
||||
if (d <= 0) continue;
|
||||
reach.push(wetReach(w, x, t));
|
||||
dampness.push(d);
|
||||
}
|
||||
for (let y = seaEnd(x); y < H; y++) {
|
||||
let c = palette[SAND_MAP[y * W + x]];
|
||||
// Darker, slightly reflective sand where the water has just been.
|
||||
let damp = y < SHORE[x] + 2 ? 1 : 0;
|
||||
for (let i = 0; i < reach.length; i++) if (y <= reach[i] && dampness[i] > damp) damp = dampness[i];
|
||||
if (damp > 0) c = mix(c, wet, damp * 0.85);
|
||||
s.setScaled(x, y, c, shaded ? cloudLight(f, x, y) : 1);
|
||||
if (damp > 0.5 && hash(x, y, glintSeed) > 0.994) s.blend(x, y, f.sunColor, 0.8 * f.direct);
|
||||
|
||||
// A thin sheet of water over the sand, up to the current edge.
|
||||
if (y < edge) {
|
||||
const depth = clamp01((edge - y) / 8);
|
||||
s.blend(x, y, shallow, 0.28 + 0.32 * depth);
|
||||
}
|
||||
}
|
||||
drawEdgeFoam(s, f, x, edge, foam);
|
||||
}
|
||||
drawDriftwood(s, f);
|
||||
}
|
||||
|
||||
/** Foam on the leading edge of the wash, and the lacy line it leaves as it slides back. */
|
||||
function drawEdgeFoam(s: Surface, f: Frame, x: number, edge: number, foam: RGB): void {
|
||||
const t = f.t;
|
||||
const top = seaEnd(x);
|
||||
for (const w of f.waves) {
|
||||
const tb = breakTime(w, x);
|
||||
const since = t - tb;
|
||||
if (since < 0 || since > 9) continue;
|
||||
const front = waveFront(w, x, t);
|
||||
if (front >= top && since < 5.7) {
|
||||
// Leading foam is thick while the wave runs up, thinner on the way back.
|
||||
const thick = since < 2.3 ? 2 + w.strength * 1.5 : 1.2;
|
||||
const a = since < 2.3 ? 0.95 : 0.6 * (1 - progress(since, 2.3, 5.7));
|
||||
for (let y = Math.floor(front - thick); y <= front; y++) {
|
||||
if (y < top) continue;
|
||||
if (Math.abs(front - edge) > 3 && y > edge) continue;
|
||||
s.blend(x, y, foam, ditherStep(a * (y >= front - 1 ? 1 : 0.7), x, y, 4));
|
||||
}
|
||||
}
|
||||
// Lace left at the high point, slowly breaking up and soaking away.
|
||||
if (since > 2.0) {
|
||||
const maxY = SHORE[x] + waveReach(w, x);
|
||||
const k = (1 - progress(since, 2.3, 9)) * 0.85;
|
||||
for (let y = Math.floor(maxY - 2); y <= maxY; y++) {
|
||||
const lace = noise2(x * 0.6 + w.id, y * 1.4 + since * 0.15, 47);
|
||||
if (lace > 0.55 && y < H) s.blend(x, y, foam, ditherStep(k * (lace - 0.4) * 2, x, y, 4));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawDriftwood(s: Surface, f: Frame): void {
|
||||
const wood = sunlit(f, DRIFTWOOD, 0.2);
|
||||
const dark = lit(f, DRIFTWOOD_DARK);
|
||||
const shadow = lit(f, hex('#b89a6c'));
|
||||
const x0 = 214;
|
||||
const y0 = 158;
|
||||
for (let i = 0; i < 20; i++) {
|
||||
const y = y0 + Math.round(i * 0.15);
|
||||
s.blend(x0 + i, y + 2, shadow, 0.6);
|
||||
s.set(x0 + i, y, wood);
|
||||
s.set(x0 + i, y + 1, dark);
|
||||
}
|
||||
// A forked branch stub.
|
||||
s.set(x0 + 5, y0 - 1, wood);
|
||||
s.set(x0 + 4, y0 - 2, wood);
|
||||
s.set(x0 + 20, y0 + 3, dark);
|
||||
}
|
||||
|
|
@ -0,0 +1,129 @@
|
|||
import { bayer } from '../../engine/color';
|
||||
import { noise1, noise2 } from '../../engine/rng';
|
||||
import { H, HORIZON, W } from './world';
|
||||
|
||||
/** Cloud density sampled once per frame over the sky, shared by the sky, god rays and sea. */
|
||||
export interface CloudField {
|
||||
/** Density per sky pixel (row-major, W x HORIZON). */
|
||||
d: Float32Array;
|
||||
/** Density above which a pixel is cloud. */
|
||||
th: number;
|
||||
}
|
||||
|
||||
export function computeClouds(t: number, cover: number, sunX: number, sunY: number, out?: CloudField): CloudField {
|
||||
const d = out?.d ?? new Float32Array(W * HORIZON);
|
||||
const drift = t * 1.1;
|
||||
for (let y = 0; y < HORIZON; y++) {
|
||||
// Clouds flatten and shrink toward the horizon, and drift more slowly there.
|
||||
const p = y / HORIZON;
|
||||
const sx = 46 * (1 - 0.55 * p);
|
||||
const sy = 14 * (1 - 0.7 * p);
|
||||
const xd = drift * (1 - 0.5 * p);
|
||||
for (let x = 0; x < W; x++) {
|
||||
const xs = x + xd;
|
||||
let v =
|
||||
0.58 * noise2(xs / sx, y / sy, 1) +
|
||||
0.3 * noise2((xs * 1.3 + 40) / (sx * 0.45), y / (sy * 0.5), 2) +
|
||||
0.12 * noise2(x / 6 + drift * 0.3, y / 4, 3);
|
||||
// A ragged opening around the sun lets the light break through.
|
||||
const dx = x - sunX;
|
||||
const dy = (y - sunY) * 1.4;
|
||||
v -= 0.13 * Math.exp(-(dx * dx + dy * dy) / (2 * 26 * 26));
|
||||
d[y * W + x] = v;
|
||||
}
|
||||
}
|
||||
return { d, th: 0.32 + (1 - cover) * 0.5 };
|
||||
}
|
||||
|
||||
export function cloudAt(c: CloudField, x: number, y: number): number {
|
||||
const xi = Math.max(0, Math.min(W - 1, Math.round(x)));
|
||||
const yi = Math.max(0, Math.min(HORIZON - 1, Math.round(y)));
|
||||
return c.d[yi * W + xi];
|
||||
}
|
||||
|
||||
/** 0 = solid cloud, 1 = clear sky at a point (soft edge). */
|
||||
export function openness(c: CloudField, x: number, y: number): number {
|
||||
if (y >= HORIZON) return 1;
|
||||
return Math.max(0, Math.min(1, (c.th - cloudAt(c, x, y)) * 9 + 0.5));
|
||||
}
|
||||
|
||||
/** Angles (y down, so 0..π fans downward) covered by the god-ray table. */
|
||||
export const RAY_A0 = -0.4;
|
||||
export const RAY_A1 = Math.PI + 0.4;
|
||||
const RAY_BINS = 720;
|
||||
|
||||
/**
|
||||
* Brightness of the god ray leaving the sun at each angle: lit where the clouds just
|
||||
* around the sun are open, broken into streaks.
|
||||
*/
|
||||
export function computeRayTable(c: CloudField, sunX: number, sunY: number, t: number, out?: Float32Array): Float32Array {
|
||||
const table = out ?? new Float32Array(RAY_BINS);
|
||||
for (let i = 0; i < RAY_BINS; i++) {
|
||||
const a = RAY_A0 + ((RAY_A1 - RAY_A0) * i) / (RAY_BINS - 1);
|
||||
const ca = Math.cos(a);
|
||||
const sa = Math.sin(a);
|
||||
const gap = Math.min(openness(c, sunX + ca * 18, sunY + sa * 18), openness(c, sunX + ca * 30, sunY + sa * 30));
|
||||
table[i] = gap * (0.5 + 0.5 * noise1(a * 40 + t * 0.05, 7));
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
export function rayAt(table: Float32Array, a: number): number {
|
||||
if (a < RAY_A0 || a > RAY_A1) return 0;
|
||||
return table[Math.round(((a - RAY_A0) / (RAY_A1 - RAY_A0)) * (RAY_BINS - 1))];
|
||||
}
|
||||
|
||||
/** Per-pixel cloud tone: 0 clear, 1 lit, 2 mid, 3 shadowed; +4 marks a thin, translucent edge. */
|
||||
export function shadeClouds(c: CloudField, sunX: number, cover: number, out?: Uint8Array): Uint8Array {
|
||||
const tone = out ?? new Uint8Array(W * HORIZON);
|
||||
for (let y = 0; y < HORIZON; y++) {
|
||||
for (let x = 0; x < W; x++) {
|
||||
const e = c.d[y * W + x] - c.th;
|
||||
if (e <= 0) {
|
||||
tone[y * W + x] = 0;
|
||||
continue;
|
||||
}
|
||||
// Tops and sun-facing sides are lit; undersides and thick middles fall into shade.
|
||||
const toward = Math.sign(sunX - x) || 1;
|
||||
const vertical = cloudAt(c, x, y + 3) - cloudAt(c, x, y - 3);
|
||||
const facing = cloudAt(c, x - toward * 3, y) - cloudAt(c, x + toward * 3, y);
|
||||
const score = 0.5 + vertical * 2.6 + facing * 1.6 - e * 1.4 - cover * 0.12 + (bayer(x, y) - 0.5) * 0.35;
|
||||
tone[y * W + x] = (score > 0.62 ? 1 : score > 0.36 ? 2 : 3) + (e < 0.03 ? 4 : 0);
|
||||
}
|
||||
}
|
||||
return tone;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cloud light and shadow on the water and sand below the horizon: sampled coarsely (every 4 px)
|
||||
* and smoothed to full resolution, once per cached cloud step.
|
||||
*/
|
||||
const STEP = 4;
|
||||
const CW = W / STEP + 1;
|
||||
const CH = Math.ceil((H - HORIZON) / STEP) + 1;
|
||||
const coarse = new Float32Array(CW * CH);
|
||||
|
||||
export function computeGroundLight(c: CloudField, out?: Float32Array): Float32Array {
|
||||
const rows = H - HORIZON;
|
||||
const light = out ?? new Float32Array(W * rows);
|
||||
for (let gy = 0; gy < CH; gy++) {
|
||||
for (let gx = 0; gx < CW; gx++) {
|
||||
const x = gx * STEP;
|
||||
const y = HORIZON + gy * STEP;
|
||||
coarse[gy * CW + gx] = 0.86 + 0.2 * openness(c, x * 0.8 + 30, 18 + ((y - HORIZON) / rows) * 46);
|
||||
}
|
||||
}
|
||||
for (let y = 0; y < rows; y++) {
|
||||
const gy = Math.floor(y / STEP);
|
||||
const fy = (y % STEP) / STEP;
|
||||
for (let x = 0; x < W; x++) {
|
||||
const gx = Math.floor(x / STEP);
|
||||
const fx = (x % STEP) / STEP;
|
||||
const i = gy * CW + gx;
|
||||
const top = coarse[i] + (coarse[i + 1] - coarse[i]) * fx;
|
||||
const bottom = coarse[i + CW] + (coarse[i + CW + 1] - coarse[i + CW]) * fx;
|
||||
light[y * W + x] = top + (bottom - top) * fy;
|
||||
}
|
||||
}
|
||||
return light;
|
||||
}
|
||||
|
|
@ -0,0 +1,224 @@
|
|||
import { hex, type RGB } from '../../engine/color';
|
||||
import { drawSprite, type SpriteArt } from '../../engine/sprite';
|
||||
import { ease, progress } from '../../engine/Timeline';
|
||||
import { Rng } from '../../engine/rng';
|
||||
import type { Surface } from '../../engine/Surface';
|
||||
import { lit, sunlit, type Frame } from './timeline';
|
||||
import { waterEdge } from './waves';
|
||||
import { SHORE, W } from './world';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Seagulls
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const GULL_UP: SpriteArt = ['k.......k', '.w.....w.', '..ww.ww..', '...www...'];
|
||||
const GULL_MID: SpriteArt = ['.........', '.........', 'kwwwwwwwk', '...ggg...'];
|
||||
const GULL_DOWN: SpriteArt = ['.........', '...www...', '.wwgwgww.', 'k.......k'];
|
||||
const GULL_GLIDE: SpriteArt = ['.........', '.ww...ww.', 'k..www..k', '...ggg...'];
|
||||
const FAR_UP: SpriteArt = ['w...w', '.www.'];
|
||||
const FAR_MID: SpriteArt = ['.....', 'wwwww'];
|
||||
const FAR_DOWN: SpriteArt = ['.www.', 'w...w'];
|
||||
|
||||
/** Standing gull, facing right. */
|
||||
const GULL_STAND: SpriteArt = ['....ww.', '....wey', '...www.', '.gggww.', 'kgggww.', '..o.o..'];
|
||||
const GULL_STEP: SpriteArt = ['....ww.', '....wey', '...www.', '.gggww.', 'kgggww.', '...oo..'];
|
||||
const GULL_PECK: SpriteArt = ['.......', '.......', '.gggww.', 'kgggwww', '....wwy', '..o.o..'];
|
||||
|
||||
function gullPalette(f: Frame): Record<string, RGB> {
|
||||
return {
|
||||
w: sunlit(f, hex('#f6f4f0'), 0.25),
|
||||
g: lit(f, hex('#a4acb8')),
|
||||
k: lit(f, hex('#2e323c')),
|
||||
e: hex('#1a1a1a'),
|
||||
y: sunlit(f, hex('#f0c040'), 0.2),
|
||||
o: sunlit(f, hex('#e89060'), 0.2),
|
||||
};
|
||||
}
|
||||
|
||||
function flapFrame(dt: number, far: boolean): SpriteArt {
|
||||
// Bursts of flapping between long, easy glides.
|
||||
const cyc = dt % 4.2;
|
||||
if (cyc > 1.7) return far ? FAR_MID : GULL_GLIDE;
|
||||
const frames = far ? [FAR_UP, FAR_MID, FAR_DOWN, FAR_MID] : [GULL_UP, GULL_MID, GULL_DOWN, GULL_MID];
|
||||
return frames[Math.floor(cyc / 0.13) % 4];
|
||||
}
|
||||
|
||||
interface Flock {
|
||||
start: number;
|
||||
dir: 1 | -1;
|
||||
y: number;
|
||||
speed: number;
|
||||
far: boolean;
|
||||
count: number;
|
||||
}
|
||||
|
||||
const FLOCKS: Flock[] = (() => {
|
||||
const r = new Rng(77);
|
||||
const out: Flock[] = [];
|
||||
for (let t = 12; t < 280; t += r.range(26, 44)) {
|
||||
const far = r.next() < 0.55;
|
||||
out.push({
|
||||
start: t,
|
||||
dir: r.next() < 0.5 ? 1 : -1,
|
||||
y: far ? r.range(30, 62) : r.range(14, 40),
|
||||
speed: far ? r.range(11, 16) : r.range(18, 26),
|
||||
far,
|
||||
count: r.int(1, 3),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
})();
|
||||
|
||||
export function drawFlyingGulls(s: Surface, f: Frame): void {
|
||||
const pal = gullPalette(f);
|
||||
for (const fl of FLOCKS) {
|
||||
const dt = f.t - fl.start;
|
||||
if (dt < 0 || dt > (W + 60) / fl.speed) continue;
|
||||
for (let i = 0; i < fl.count; i++) {
|
||||
const lag = i * (fl.far ? 6 : 10);
|
||||
const along = fl.speed * dt - lag;
|
||||
const x = fl.dir > 0 ? -10 + along : W + 10 - along;
|
||||
const y = fl.y + i * (fl.far ? 3 : 5) + Math.sin(dt * 0.45 + i * 1.3) * 5;
|
||||
drawSprite(s, flapFrame(dt + i * 0.6, fl.far), Math.round(x), Math.round(y), pal);
|
||||
}
|
||||
}
|
||||
drawVisitingGull(s, f, pal, true);
|
||||
}
|
||||
|
||||
/** One gull drops in, wanders on the sand and pecks around, then takes off again. */
|
||||
const VISIT = { arrive: 132, land: 137, leave: 171, gone: 178, landX: 206, groundY: 151 };
|
||||
const VISIT_PATH: [number, number, 'walk' | 'peck' | 'idle'][] = [
|
||||
[137, 206, 'idle'],
|
||||
[141, 206, 'walk'],
|
||||
[145, 196, 'peck'],
|
||||
[149, 196, 'idle'],
|
||||
[151, 196, 'walk'],
|
||||
[155, 186, 'peck'],
|
||||
[159, 186, 'walk'],
|
||||
[165, 200, 'idle'],
|
||||
[171, 200, 'idle'],
|
||||
];
|
||||
|
||||
function drawVisitingGull(s: Surface, f: Frame, pal: Record<string, RGB>, air: boolean): void {
|
||||
const t = f.t;
|
||||
if (t < VISIT.arrive || t > VISIT.gone) return;
|
||||
if (t < VISIT.land) {
|
||||
if (!air) return;
|
||||
const u = progress(t, VISIT.arrive, VISIT.land, ease.out);
|
||||
const x = W + 10 + (VISIT.landX - W - 10) * u;
|
||||
const y = 36 + (VISIT.groundY - 6 - 36) * ease.in(u);
|
||||
drawSprite(s, flapFrame((t - VISIT.arrive) * 0.4 + 0.5, false), Math.round(x) - 4, Math.round(y), pal);
|
||||
return;
|
||||
}
|
||||
if (t > VISIT.leave) {
|
||||
if (!air) return;
|
||||
const u = progress(t, VISIT.leave, VISIT.gone, ease.in);
|
||||
const x = 200 - 220 * u;
|
||||
const y = VISIT.groundY - 6 - 120 * ease.out(u);
|
||||
drawSprite(s, flapFrame((t - VISIT.leave) * 0.6, false), Math.round(x) - 4, Math.round(y), pal);
|
||||
return;
|
||||
}
|
||||
if (air) return;
|
||||
let i = 0;
|
||||
while (i < VISIT_PATH.length - 2 && t >= VISIT_PATH[i + 1][0]) i++;
|
||||
const [ta, xa, mode] = VISIT_PATH[i];
|
||||
const [tb, xb] = VISIT_PATH[i + 1];
|
||||
const u = (t - ta) / (tb - ta);
|
||||
let x = xa;
|
||||
let art = GULL_STAND;
|
||||
let facingLeft = xb < xa;
|
||||
if (mode === 'walk') {
|
||||
x = xa + (xb - xa) * u;
|
||||
art = Math.floor(t * 6) % 2 ? GULL_STEP : GULL_STAND;
|
||||
} else if (mode === 'peck') {
|
||||
x = xa + (xb - xa) * u;
|
||||
facingLeft = true;
|
||||
art = (t * 1.4) % 1 < 0.35 ? GULL_PECK : Math.floor(t * 6) % 2 && xb !== xa ? GULL_STEP : GULL_STAND;
|
||||
} else {
|
||||
// Idle: turn its head now and then.
|
||||
facingLeft = Math.floor(t / 2.3) % 2 === 0;
|
||||
}
|
||||
s.blend(Math.round(x) - 2, VISIT.groundY + 1, lit(f, hex('#b89a6c')), 0.5);
|
||||
s.blend(Math.round(x) - 1, VISIT.groundY + 1, lit(f, hex('#b89a6c')), 0.5);
|
||||
drawSprite(s, art, Math.round(x) - 3, VISIT.groundY - 5, pal, facingLeft);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Crabs
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const CRAB_A: SpriteArt = ['.k...k.', 'C.ccc.C', '.ccccc.', 'c.c.c.c'];
|
||||
const CRAB_B: SpriteArt = ['.k...k.', 'C.ccc.C', '.ccccc.', '.c.c.c.'];
|
||||
|
||||
interface CrabVisit {
|
||||
start: number;
|
||||
holeX: number;
|
||||
holeY: number;
|
||||
/** Keyframes [time offset, dx from the hole]. */
|
||||
path: [number, number][];
|
||||
end: number;
|
||||
}
|
||||
|
||||
const EMERGE = 1.2;
|
||||
|
||||
const CRABS: CrabVisit[] = [26, 92, 196, 250].map((start, n) => {
|
||||
const r = new Rng(300 + n);
|
||||
const holeX = Math.round(r.range(112, 232));
|
||||
const holeY = SHORE[holeX] + Math.round(r.range(15, 21));
|
||||
const path: [number, number][] = [[EMERGE + 0.6, 0]];
|
||||
let time = EMERGE + 0.6;
|
||||
let dx = 0;
|
||||
for (let k = 0; k < 4; k++) {
|
||||
const next = Math.max(-18, Math.min(18, dx + (r.next() < 0.5 ? -1 : 1) * r.range(5, 13)));
|
||||
time += Math.abs(next - dx) / 10;
|
||||
path.push([time, next]);
|
||||
dx = next;
|
||||
time += r.range(1.5, 3.5);
|
||||
path.push([time, dx]);
|
||||
}
|
||||
time += Math.abs(dx) / 10;
|
||||
path.push([time, 0]);
|
||||
return { start, holeX, holeY, path, end: time + 0.4 + EMERGE };
|
||||
});
|
||||
|
||||
function crabOffset(c: CrabVisit, u: number): { dx: number; moving: boolean } {
|
||||
const p = c.path;
|
||||
if (u <= p[0][0]) return { dx: 0, moving: false };
|
||||
for (let i = 0; i < p.length - 1; i++) {
|
||||
const [ta, a] = p[i];
|
||||
const [tb, b] = p[i + 1];
|
||||
if (u < tb) return { dx: a + (b - a) * ((u - ta) / (tb - ta)), moving: a !== b };
|
||||
}
|
||||
return { dx: 0, moving: false };
|
||||
}
|
||||
|
||||
export function drawCrabs(s: Surface, f: Frame): void {
|
||||
const pal: Record<string, RGB> = {
|
||||
c: sunlit(f, hex('#d8643c'), 0.2),
|
||||
C: lit(f, hex('#9a3a22')),
|
||||
k: hex('#1a1414'),
|
||||
};
|
||||
const hole = lit(f, hex('#6a5434'));
|
||||
for (const c of CRABS) {
|
||||
const u = f.t - c.start;
|
||||
if (u < -3 || u > c.end + 3) continue;
|
||||
s.set(c.holeX, c.holeY + 1, hole);
|
||||
s.set(c.holeX + 1, c.holeY + 1, hole);
|
||||
if (u < 0 || u > c.end) continue;
|
||||
const { dx, moving } = crabOffset(c, u);
|
||||
const x = c.holeX + dx;
|
||||
// Sidles away from the water whenever a wash comes up to it.
|
||||
const edge = waterEdge(f.waves, Math.round(x), f.t);
|
||||
const y = Math.max(c.holeY, edge + 4);
|
||||
const out = Math.min(1, u / EMERGE, (c.end - u) / EMERGE);
|
||||
const rows = Math.round(out * 4);
|
||||
const art = moving && Math.floor(f.t * 9) % 2 ? CRAB_B : CRAB_A;
|
||||
const visible = art.slice(0, rows);
|
||||
if (rows > 0) drawSprite(s, visible, Math.round(x) - 3, Math.round(y) - rows + 1, pal);
|
||||
}
|
||||
}
|
||||
|
||||
/** The landed gull is drawn with the ground creatures so the jungle can overlap it correctly. */
|
||||
export function drawGroundGull(s: Surface, f: Frame): void {
|
||||
drawVisitingGull(s, f, gullPalette(f), false);
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
import type { Meditation, Scene } from '../types';
|
||||
import { drawBeach } from './beach';
|
||||
import { drawCrabs, drawFlyingGulls, drawGroundGull } from './creatures';
|
||||
import { drawJungleBack, drawJungleFront } from './jungle';
|
||||
import { drawSailboat } from './sailboat';
|
||||
import { drawSea } from './sea';
|
||||
import { drawGodRays, drawSky } from './sky';
|
||||
import { DURATION, frameAt } from './timeline';
|
||||
|
||||
const scene: Scene = {
|
||||
render(s, t) {
|
||||
const f = frameAt(t);
|
||||
drawSky(s, f);
|
||||
drawSea(s, f);
|
||||
drawSailboat(s, f);
|
||||
drawBeach(s, f);
|
||||
drawCrabs(s, f);
|
||||
drawGroundGull(s, f);
|
||||
drawGodRays(s, f);
|
||||
drawJungleBack(s, f);
|
||||
drawJungleFront(s, f);
|
||||
drawFlyingGulls(s, f);
|
||||
s.darken(f.fade);
|
||||
},
|
||||
};
|
||||
|
||||
export const mediterraneanCoast: Meditation = {
|
||||
id: 'mediterranean-coast',
|
||||
title: 'Mediterranean Coast',
|
||||
subtitle: 'Clearing skies over a jungle cove',
|
||||
description:
|
||||
'Waves roll onto a quiet cove framed by swaying palms. Watch the clouds part and the light break through as a distant sailboat drifts by and the afternoon slips into a golden evening.',
|
||||
duration: DURATION,
|
||||
previewTime: 70,
|
||||
music: 'audio/coastline.mp3',
|
||||
ambience: { src: 'audio/fx-waves.mp3', volume: 0.55 },
|
||||
createScene: () => scene,
|
||||
};
|
||||
|
|
@ -0,0 +1,259 @@
|
|||
import { bayer, hex, mix, scale, type RGB } from '../../engine/color';
|
||||
import { hash, noise1, noise2 } from '../../engine/rng';
|
||||
import type { Surface } from '../../engine/Surface';
|
||||
import { lit, sunlit, type Frame } from './timeline';
|
||||
import { H, W } from './world';
|
||||
|
||||
const LEAF_DARK = hex('#1f4426');
|
||||
const LEAF_MID = hex('#33683a');
|
||||
const LEAF_LIGHT = hex('#5e9a48');
|
||||
const LEAF_SUN = hex('#9cc85a');
|
||||
const RIB = hex('#3e5a2a');
|
||||
const TRUNK = hex('#8a7056');
|
||||
const TRUNK_DARK = hex('#5e4a3a');
|
||||
const TRUNK_LIGHT = hex('#b4987a');
|
||||
const COCONUT = hex('#6a4a2a');
|
||||
|
||||
/** Gentle, gusty breeze shared by everything that sways. */
|
||||
function breeze(t: number): number {
|
||||
return 0.55 + 0.45 * noise1(t * 0.12, 61);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Dense foliage masses on each side
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface Mass {
|
||||
/** How far the foliage reaches in from its side at row y. */
|
||||
reach: (y: number) => number;
|
||||
side: -1 | 1;
|
||||
top: number;
|
||||
tone: number;
|
||||
seed: number;
|
||||
}
|
||||
|
||||
const MASSES: Mass[] = [
|
||||
{ side: -1, top: 30, tone: 0.55, seed: 1, reach: (y) => 26 + (y - 30) * 0.3 },
|
||||
{ side: 1, top: 36, tone: 0.55, seed: 2, reach: (y) => 22 + (y - 36) * 0.28 },
|
||||
{ side: -1, top: 96, tone: 0.8, seed: 3, reach: (y) => 30 + (y - 96) * 0.45 },
|
||||
{ side: 1, top: 104, tone: 0.8, seed: 4, reach: (y) => 30 + (y - 104) * 0.4 },
|
||||
];
|
||||
|
||||
const MASS_WIDTH = 90;
|
||||
const EMPTY = 255;
|
||||
|
||||
/** Foliage shape and leaf tones at rest, worked out once per mass (EMPTY where there is no foliage). */
|
||||
const MASS_MAPS: Uint8Array[] = MASSES.map((m) => {
|
||||
const map = new Uint8Array(MASS_WIDTH * H).fill(EMPTY);
|
||||
for (let y = Math.max(0, m.top - 12); y < H; y++) {
|
||||
for (let inward = 0; inward < MASS_WIDTH; inward++) {
|
||||
const x = m.side < 0 ? inward : W - 1 - inward;
|
||||
// Leafy, lumpy edge: clumps of foliage poke out past the base line.
|
||||
const clump = noise2(y / 9, inward / 9 + m.seed * 10, 62 + m.seed);
|
||||
const edge = m.reach(y) + (clump - 0.5) * 22 - Math.max(0, m.top - y) * 2.4;
|
||||
if (inward > edge) continue;
|
||||
const leaf = noise2(x / 3.5, y / 3, 63 + m.seed);
|
||||
let k = leaf * 2.2 + Math.max(0, 1 - (edge - inward) / 10) * 1.1 - 0.6 + (bayer(x, y) - 0.5) * 0.4;
|
||||
if (y < m.top + 10) k += 0.3;
|
||||
map[y * MASS_WIDTH + inward] = Math.max(0, Math.min(3, Math.floor(k)));
|
||||
}
|
||||
}
|
||||
return map;
|
||||
});
|
||||
|
||||
function drawMass(s: Surface, f: Frame, index: number): void {
|
||||
const m = MASSES[index];
|
||||
const map = MASS_MAPS[index];
|
||||
const sway = breeze(f.t);
|
||||
const tones: RGB[] = [lit(f, LEAF_DARK), sunlit(f, LEAF_MID, 0.15), sunlit(f, LEAF_LIGHT, 0.3), sunlit(f, LEAF_SUN, 0.45)].map(
|
||||
(c) => scale(c, m.tone),
|
||||
);
|
||||
for (let y = Math.max(0, m.top - 12); y < H; y++) {
|
||||
// Each row of leaves drifts a pixel or two with the breeze.
|
||||
const shift = Math.round(Math.sin(f.t * 0.8 + y * 0.07 + m.seed) * 1.6 * sway);
|
||||
for (let inward = 0; inward < MASS_WIDTH; inward++) {
|
||||
const src = inward - shift * -m.side;
|
||||
if (src < 0 || src >= MASS_WIDTH) continue;
|
||||
const k = map[y * MASS_WIDTH + src];
|
||||
if (k === EMPTY) continue;
|
||||
s.set(m.side < 0 ? inward : W - 1 - inward, y, tones[k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Palm fronds (also used for undergrowth)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function drawFrond(
|
||||
s: Surface,
|
||||
f: Frame,
|
||||
ox: number,
|
||||
oy: number,
|
||||
angle: number,
|
||||
len: number,
|
||||
droop: number,
|
||||
seed: number,
|
||||
dim = 1,
|
||||
): void {
|
||||
const dark = scale(lit(f, LEAF_DARK), dim);
|
||||
const mid = scale(sunlit(f, LEAF_MID, 0.2), dim);
|
||||
const light = scale(sunlit(f, LEAF_LIGHT, 0.35), dim);
|
||||
const sun = scale(sunlit(f, LEAF_SUN, 0.5), dim);
|
||||
const rib = scale(sunlit(f, RIB, 0.2), dim);
|
||||
const dx = Math.cos(angle);
|
||||
const dy = Math.sin(angle);
|
||||
const steps = Math.ceil(len * 2);
|
||||
for (let i = 0; i <= steps; i++) {
|
||||
const u = i / steps;
|
||||
const px = ox + dx * len * u;
|
||||
const py = oy + dy * len * u + droop * len * u * u;
|
||||
// Tangent of the arching rib.
|
||||
let tx = dx;
|
||||
let ty = dy + 2 * droop * u;
|
||||
const tl = Math.hypot(tx, ty);
|
||||
tx /= tl;
|
||||
ty /= tl;
|
||||
if (i % 2 === 0 && u > 0.06) {
|
||||
const leaflet = 1 + 8 * Math.pow(1 - u, 0.8) * Math.min(1, u * 4);
|
||||
for (const side of [-1, 1]) {
|
||||
// Leaflets hang down and back from the rib.
|
||||
let lx = -ty * side + tx * 0.25;
|
||||
let ly = tx * side + ty * 0.25 + 0.9;
|
||||
const ll = Math.hypot(lx, ly);
|
||||
lx /= ll;
|
||||
ly /= ll;
|
||||
const flutter = Math.sin(f.t * 3 + i * 0.7 + seed) * 0.15;
|
||||
for (let k = 1; k <= leaflet; k++) {
|
||||
const qx = px + (lx + flutter) * k;
|
||||
const qy = py + ly * k;
|
||||
const tip = k / leaflet;
|
||||
// Leaflets on the upper side of the arch catch the light; the rest sit in their own shade.
|
||||
const upper = side * tx * Math.sign(ty + 0.001) > 0 || ty < -0.2;
|
||||
let c = upper ? (tip > 0.5 ? sun : light) : tip > 0.55 ? mid : dark;
|
||||
if (!upper && hash(Math.round(qx), Math.round(qy), seed) > 0.85) c = light;
|
||||
if (k === 1) c = dark;
|
||||
s.set(Math.round(qx), Math.round(qy), c);
|
||||
}
|
||||
}
|
||||
}
|
||||
s.set(Math.round(px), Math.round(py), rib);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Palms
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface Palm {
|
||||
base: [number, number];
|
||||
ctrl: [number, number];
|
||||
crown: [number, number];
|
||||
fronds: number;
|
||||
len: number;
|
||||
seed: number;
|
||||
dim: number;
|
||||
}
|
||||
|
||||
const PALMS: Palm[] = [
|
||||
{ base: [-6, 150], ctrl: [0, 96], crown: [22, 54], fronds: 10, len: 30, seed: 11, dim: 0.8 },
|
||||
{ base: [290, 184], ctrl: [284, 132], crown: [244, 72], fronds: 10, len: 28, seed: 12, dim: 0.85 },
|
||||
{ base: [10, 184], ctrl: [16, 96], crown: [60, 32], fronds: 12, len: 42, seed: 13, dim: 1 },
|
||||
{ base: [42, 184], ctrl: [50, 124], crown: [90, 66], fronds: 11, len: 32, seed: 14, dim: 1 },
|
||||
{ base: [320, 184], ctrl: [306, 92], crown: [264, 30], fronds: 12, len: 42, seed: 15, dim: 1 },
|
||||
];
|
||||
|
||||
function bezier(p: Palm, crown: [number, number], u: number): [number, number] {
|
||||
const a = (1 - u) * (1 - u);
|
||||
const b = 2 * (1 - u) * u;
|
||||
const c = u * u;
|
||||
return [a * p.base[0] + b * p.ctrl[0] + c * crown[0], a * p.base[1] + b * p.ctrl[1] + c * crown[1]];
|
||||
}
|
||||
|
||||
function drawPalm(s: Surface, f: Frame, p: Palm): void {
|
||||
const t = f.t;
|
||||
const gust = breeze(t);
|
||||
const swayX = Math.sin((2 * Math.PI * t) / 6.5 + p.seed) * 1.6 * gust;
|
||||
const swayY = Math.abs(swayX) * 0.2;
|
||||
const crown: [number, number] = [p.crown[0] + swayX, p.crown[1] + swayY];
|
||||
const toSun = Math.sign(f.sunX - crown[0]) || 1;
|
||||
const bark = scale(sunlit(f, TRUNK, 0.15), p.dim);
|
||||
const barkDark = scale(lit(f, TRUNK_DARK), p.dim);
|
||||
const barkLight = scale(sunlit(f, TRUNK_LIGHT, 0.35), p.dim);
|
||||
|
||||
// Trunk: tapering, ringed, lit on the sun side.
|
||||
const length = Math.hypot(p.base[0] - crown[0], p.base[1] - crown[1]) * 1.1;
|
||||
const n = Math.ceil(length * 1.5);
|
||||
for (let i = 0; i <= n; i++) {
|
||||
const u = i / n;
|
||||
const [cx, cy] = bezier(p, crown, u);
|
||||
const r = 2.4 - 1.3 * u;
|
||||
const ring = Math.floor(u * length / 2.6) % 2 === 0;
|
||||
for (let ox = -Math.ceil(r); ox <= Math.ceil(r); ox++) {
|
||||
if (Math.abs(ox) > r) continue;
|
||||
const lit = ox * toSun;
|
||||
let c = lit > r * 0.3 ? barkLight : lit < -r * 0.4 ? barkDark : bark;
|
||||
if (ring && Math.abs(ox) < r) c = mix(c, barkDark, 0.45);
|
||||
s.set(Math.round(cx + ox), Math.round(cy), c);
|
||||
}
|
||||
}
|
||||
|
||||
// Fronds fanned around the crown, swaying in the breeze.
|
||||
const back: number[] = [];
|
||||
const front: number[] = [];
|
||||
for (let i = 0; i < p.fronds; i++) (i % 2 ? back : front).push(i);
|
||||
for (const i of [...back, ...front]) {
|
||||
const spread = i / (p.fronds - 1) - 0.5;
|
||||
const base = -Math.PI / 2 + spread * 3.6;
|
||||
const sway = Math.sin((2 * Math.PI * t) / 5.2 + p.seed + i * 0.55) * 0.09 * gust + swayX * 0.015;
|
||||
const len = p.len * (0.8 + 0.3 * hash(i, p.seed, 64));
|
||||
const droop = 0.62 + 0.3 * Math.abs(spread) + Math.sin(t * 0.9 + i) * 0.03 * gust;
|
||||
drawFrond(s, f, crown[0], crown[1], base + sway, len, droop, p.seed * 10 + i, p.dim);
|
||||
}
|
||||
const nut = scale(sunlit(f, COCONUT, 0.15), p.dim);
|
||||
for (const [ox, oy] of [
|
||||
[-1, 2],
|
||||
[2, 2],
|
||||
[0, 4],
|
||||
]) {
|
||||
s.set(Math.round(crown[0] + ox), Math.round(crown[1] + oy), nut);
|
||||
s.set(Math.round(crown[0] + ox + 1), Math.round(crown[1] + oy), nut);
|
||||
s.set(Math.round(crown[0] + ox), Math.round(crown[1] + oy + 1), scale(nut, 0.8));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Foreground undergrowth in the bottom corners
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const UNDERGROWTH: [number, number, number, number, number][] = [
|
||||
// x, y, angle, length, seed
|
||||
[6, 182, -1.1, 34, 21],
|
||||
[18, 184, -0.7, 40, 22],
|
||||
[30, 186, -0.35, 36, 23],
|
||||
[52, 186, -0.6, 28, 24],
|
||||
[70, 188, -0.25, 22, 25],
|
||||
[314, 182, -2.05, 34, 26],
|
||||
[300, 184, -2.45, 40, 27],
|
||||
[286, 186, -2.8, 34, 28],
|
||||
[264, 186, -2.5, 28, 29],
|
||||
[248, 188, -2.9, 22, 30],
|
||||
];
|
||||
|
||||
export function drawJungleBack(s: Surface, f: Frame): void {
|
||||
drawMass(s, f, 0);
|
||||
drawMass(s, f, 1);
|
||||
drawPalm(s, f, PALMS[0]);
|
||||
drawPalm(s, f, PALMS[1]);
|
||||
drawMass(s, f, 2);
|
||||
drawMass(s, f, 3);
|
||||
}
|
||||
|
||||
export function drawJungleFront(s: Surface, f: Frame): void {
|
||||
for (const p of PALMS.slice(2)) drawPalm(s, f, p);
|
||||
const gust = breeze(f.t);
|
||||
for (const [x, y, a, len, seed] of UNDERGROWTH) {
|
||||
const sway = Math.sin(f.t * 1.1 + seed) * 0.06 * gust;
|
||||
drawFrond(s, f, x, y, a + sway, len, 0.35, seed, 0.75);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
import { hex, mix, type RGB } from '../../engine/color';
|
||||
import { hash } from '../../engine/rng';
|
||||
import type { Surface } from '../../engine/Surface';
|
||||
import { lit, sunlit, TIMES, type Frame } from './timeline';
|
||||
import { HORIZON } from './world';
|
||||
|
||||
type Part = 'hull' | 'keel' | 'mast' | 'main' | 'jib';
|
||||
|
||||
/** The sloop, bow to the right, as [dx, dy, part] around a pivot at the waterline (dy < 0 is up). */
|
||||
const PIXELS: [number, number, Part][] = (() => {
|
||||
const out: [number, number, Part][] = [];
|
||||
for (let dx = -5; dx <= 4; dx++) out.push([dx, 0, 'keel']);
|
||||
for (let dx = -6; dx <= 6; dx++) out.push([dx, -1, 'hull']);
|
||||
for (let dy = -13; dy <= -2; dy++) out.push([-1, dy, 'mast']);
|
||||
// Mainsail behind the mast, widening toward the boom.
|
||||
for (let dy = -12; dy <= -3; dy++) {
|
||||
const w = Math.round(((dy + 13) / 10) * 5);
|
||||
for (let dx = -2; dx >= -1 - w; dx--) out.push([dx, dy, 'main']);
|
||||
}
|
||||
// Jib ahead of the mast, down to the bow.
|
||||
for (let dy = -11; dy <= -3; dy++) {
|
||||
const w = Math.round(((dy + 12) / 9) * 5);
|
||||
for (let dx = 0; dx < w; dx++) out.push([dx, dy, 'jib']);
|
||||
}
|
||||
return out;
|
||||
})();
|
||||
|
||||
const ROCK_PERIOD = 4.3;
|
||||
|
||||
export function drawSailboat(s: Surface, f: Frame): void {
|
||||
const t = f.t;
|
||||
const [t0, t1] = TIMES.boat;
|
||||
if (t < t0 || t > t1) return;
|
||||
const x0 = -16 + ((t - t0) / (t1 - t0)) * 352;
|
||||
const y0 = HORIZON + 7;
|
||||
// Rocking on the swell: lean the mast and sails side to side about the waterline.
|
||||
const angle = 0.12 * Math.sin((2 * Math.PI * t) / ROCK_PERIOD) + 0.035 * Math.sin((2 * Math.PI * t) / 2.1 + 1);
|
||||
const lean = Math.tan(angle);
|
||||
const bob = Math.sin((2 * Math.PI * t) / ROCK_PERIOD + 1.2) > 0.75 ? 1 : 0;
|
||||
|
||||
const haze = 0.22;
|
||||
const colors: Record<Part, RGB> = {
|
||||
hull: mix(sunlit(f, hex('#eeeae0'), 0.3), f.horizonColor, haze),
|
||||
keel: mix(lit(f, hex('#2e3a4c')), f.horizonColor, haze),
|
||||
mast: mix(lit(f, hex('#4a4a50')), f.horizonColor, haze),
|
||||
main: mix(sunlit(f, hex('#f8f4ea'), 0.35), f.horizonColor, haze * 0.6),
|
||||
jib: mix(sunlit(f, hex('#e2ded4'), 0.2), f.horizonColor, haze * 0.6),
|
||||
};
|
||||
|
||||
for (const [dx, dy, part] of PIXELS) {
|
||||
const x = Math.round(x0 + dx - dy * lean);
|
||||
const y = y0 + dy + bob;
|
||||
s.set(x, y, colors[part]);
|
||||
// A faint, wavering reflection.
|
||||
const ry = y0 - dy + 1 + bob;
|
||||
if (dy > -9) {
|
||||
const wob = Math.round(Math.sin(ry * 1.3 + t * 3) * 0.6);
|
||||
s.blend(x + wob, ry, colors[part], part === 'main' || part === 'jib' ? 0.22 : 0.3);
|
||||
}
|
||||
}
|
||||
// A little wake trailing behind.
|
||||
const foam = mix(lit(f, hex('#f4f8f6')), f.horizonColor, haze);
|
||||
for (let k = 7; k < 14; k++) {
|
||||
if (hash(k, Math.floor(t * 3), 51) < 0.55 - k * 0.03) s.blend(Math.round(x0) - k, y0 + bob, foam, 0.7 - k * 0.04);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,110 @@
|
|||
import { ditherStep, gradient, hex, mix, type RGB } from '../../engine/color';
|
||||
import { clamp01, ease } from '../../engine/Timeline';
|
||||
import { hash, noise2 } from '../../engine/rng';
|
||||
import type { Surface } from '../../engine/Surface';
|
||||
import { sunlit, type Frame } from './timeline';
|
||||
import { APPROACH, breakTime, waveFront } from './waves';
|
||||
import { BREAK, H, HORIZON, SHORE, W } from './world';
|
||||
|
||||
const DEEP = [hex('#2a5578'), hex('#2a6f8e'), hex('#33909e'), hex('#5ab6ac')];
|
||||
const CREST = hex('#86d4c8');
|
||||
const TROUGH = hex('#1f4e66');
|
||||
const FOAM = hex('#f4f8f6');
|
||||
|
||||
/** Last sea row in a column; the beach (with its sheet of wash water) takes over below. */
|
||||
export const seaEnd = (x: number) => SHORE[x] - 4;
|
||||
|
||||
/** Light and shadow patches thrown on the water and sand by the drifting clouds. */
|
||||
export function cloudLight(f: Frame, x: number, y: number): number {
|
||||
return f.groundLight[(y - HORIZON) * W + x];
|
||||
}
|
||||
|
||||
const LEVELS = 32;
|
||||
|
||||
/** Depth level (0 = horizon … LEVELS-1 = the shallows) of every sea pixel, fixed by the layout. */
|
||||
const DEPTH_MAP: Uint8Array = (() => {
|
||||
const map = new Uint8Array(W * H);
|
||||
for (let x = 0; x < W; x++) {
|
||||
for (let y = HORIZON; y < H; y++) {
|
||||
const depth = Math.min(1, (y - HORIZON) / (SHORE[x] - HORIZON));
|
||||
map[y * W + x] = Math.round(depth * (LEVELS - 1));
|
||||
}
|
||||
}
|
||||
return map;
|
||||
})();
|
||||
|
||||
export function drawSea(s: Surface, f: Frame): void {
|
||||
const t = f.t;
|
||||
const deep = DEEP.map((c) => sunlit(f, c, 0.12));
|
||||
const sparkle = mix(f.sunColor, [255, 255, 255], 0.5);
|
||||
const skyGlint = f.skyBands[Math.floor(f.skyBands.length * 0.6)];
|
||||
// Water colors per depth level, plus the lighter and darker ripple variants.
|
||||
const base: RGB[] = [];
|
||||
const light: RGB[] = [];
|
||||
for (let i = 0; i < LEVELS; i++) {
|
||||
const depth = i / (LEVELS - 1);
|
||||
const c = mix(gradient(deep, Math.pow(depth, 0.8)), f.horizonColor, Math.pow(1 - depth, 3) * 0.55);
|
||||
base.push(c);
|
||||
light.push(mix(c, skyGlint, 0.3));
|
||||
}
|
||||
const shaded = f.cover > 0.3;
|
||||
for (let x = 0; x < W; x++) {
|
||||
const end = seaEnd(x);
|
||||
for (let y = HORIZON; y < end; y++) {
|
||||
const level = DEPTH_MAP[y * W + x];
|
||||
const depth = level / (LEVELS - 1);
|
||||
const n = noise2(x * (0.06 / (0.3 + depth)) + t * 0.05, y * 0.85 - t * 0.25, 21);
|
||||
const k = (n < 0.22 ? 0.9 : 1) * (shaded ? cloudLight(f, x, y) : 1);
|
||||
s.setScaled(x, y, n > 0.72 ? light[level] : base[level], k);
|
||||
|
||||
// Glitter path under the sun.
|
||||
const width = 3 + (y - HORIZON) * 0.32;
|
||||
const off = Math.abs(x - f.sunX) / width;
|
||||
if (off < 1 && noise2(x * 0.35, y * 1.6 + t * 1.3, 22) > 0.55 + off * 0.2) {
|
||||
s.blend(x, y, sparkle, 0.85 * f.direct * (1 - off * 0.6));
|
||||
}
|
||||
}
|
||||
}
|
||||
drawSwellsAndSurf(s, f);
|
||||
}
|
||||
|
||||
function drawSwellsAndSurf(s: Surface, f: Frame): void {
|
||||
const t = f.t;
|
||||
const crest = sunlit(f, CREST, 0.2);
|
||||
const trough = sunlit(f, TROUGH, 0.05);
|
||||
const foam = sunlit(f, FOAM, 0.15);
|
||||
for (const w of f.waves) {
|
||||
for (let x = 0; x < W; x++) {
|
||||
const tb = breakTime(w, x);
|
||||
const end = seaEnd(x);
|
||||
const a = (t - (tb - APPROACH)) / APPROACH;
|
||||
if (a >= 0 && a < 1) {
|
||||
// Incoming swell: rises and steepens as it nears the break line.
|
||||
const start = HORIZON + 8;
|
||||
const cy = Math.round(start + (BREAK[x] - start) * ease.in(a));
|
||||
const face = 1 + Math.round(2.5 * a * w.strength);
|
||||
for (let k = 1; k <= face; k++) s.blend(x, cy + k, trough, 0.35 + 0.3 * a);
|
||||
s.blend(x, cy, crest, 0.5 + 0.5 * a);
|
||||
if (a > 0.8 && hash(x, w.id, 31) < (a - 0.8) * 4 * w.strength) s.set(x, cy - 1, foam);
|
||||
}
|
||||
const since = t - tb;
|
||||
if (since >= -0.15 && since < 5) {
|
||||
// Spray thrown up as it breaks.
|
||||
if (since < 0.9 && hash(x, w.id, 32) < 0.55 * w.strength) {
|
||||
const h = Math.sin((Math.max(0, since) / 0.9) * Math.PI) * (1 + 3 * w.strength) * hash(x, w.id, 33);
|
||||
for (let k = 0; k < h; k++) s.blend(x, BREAK[x] - 1 - k, foam, 0.9 - k * 0.15);
|
||||
}
|
||||
// White water rolling toward the sand, and the foam it leaves behind.
|
||||
const front = Math.min(end, waveFront(w, x, t));
|
||||
const fade = clamp01(1 - since / 4.5) * (0.5 + 0.5 * w.strength);
|
||||
for (let y = BREAK[x] - 1; y < end; y++) {
|
||||
if (y > front) break;
|
||||
const edge = front - y < 2.5 && since < 2.4;
|
||||
const lace = noise2(x * 0.45 + w.id, y * 0.9 - since * 0.6, 34);
|
||||
const k = edge ? 0.95 : lace > 0.5 ? fade * (lace - 0.3) * 1.6 : 0;
|
||||
if (k > 0) s.blend(x, y, foam, ditherStep(Math.min(1, k), x, y, 4));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,128 @@
|
|||
import { bayer, ditherStep, hex, mix, type RGB } from '../../engine/color';
|
||||
import type { Surface } from '../../engine/Surface';
|
||||
import { rayAt } from './clouds';
|
||||
import { CLOUD_LIT, CLOUD_MID, CLOUD_SHADE, lit, SKY_BANDS, SUN_R, sunlit, type Frame } from './timeline';
|
||||
import { H, HEADLAND, HORIZON, ISLAND, W } from './world';
|
||||
|
||||
const HEADLAND_ROCK = hex('#6a7660');
|
||||
const HEADLAND_SHADE = hex('#4a5850');
|
||||
const ISLAND_COLOR = hex('#6c84a0');
|
||||
const HALO = hex('#fff0c8');
|
||||
|
||||
/** Which gradient band each sky pixel uses, with dithered seams; fixed by the layout. */
|
||||
const BAND_MAP: Uint8Array = (() => {
|
||||
const map = new Uint8Array(W * HORIZON);
|
||||
for (let y = 0; y < HORIZON; y++) {
|
||||
for (let x = 0; x < W; x++) {
|
||||
const v = (y / (HORIZON - 1)) * (SKY_BANDS - 1) + (bayer(x, y) - 0.5) * 0.95;
|
||||
map[y * W + x] = Math.max(0, Math.min(SKY_BANDS - 1, Math.round(v)));
|
||||
}
|
||||
}
|
||||
return map;
|
||||
})();
|
||||
|
||||
export function drawSky(s: Surface, f: Frame): void {
|
||||
for (let y = 0; y < HORIZON; y++) {
|
||||
for (let x = 0; x < W; x++) {
|
||||
if (f.cloudTone[y * W + x] & 3 && !(f.cloudTone[y * W + x] & 4)) continue; // solid cloud covers it
|
||||
s.set(x, y, f.skyBands[BAND_MAP[y * W + x]]);
|
||||
}
|
||||
}
|
||||
drawSun(s, f);
|
||||
drawClouds(s, f);
|
||||
drawBloom(s, f);
|
||||
drawDistantLand(s, f);
|
||||
}
|
||||
|
||||
function drawSun(s: Surface, f: Frame): void {
|
||||
const cx = Math.round(f.sunX);
|
||||
const cy = Math.round(f.sunY);
|
||||
const glowR = 40;
|
||||
for (let y = Math.max(0, cy - glowR); y < Math.min(HORIZON, cy + glowR); y++) {
|
||||
for (let x = cx - glowR; x <= cx + glowR; x++) {
|
||||
const d = Math.hypot(x - cx, y - cy);
|
||||
if (d > glowR) continue;
|
||||
s.blend(x, y, mix(f.sunColor, HALO, 0.3), ditherStep(Math.pow(1 - d / glowR, 2.2) * 0.6, x, y));
|
||||
}
|
||||
}
|
||||
for (let y = -SUN_R; y <= SUN_R; y++) {
|
||||
for (let x = -SUN_R; x <= SUN_R; x++) {
|
||||
if (x * x + y * y <= SUN_R * SUN_R + SUN_R * 0.8) s.set(cx + x, cy + y, mix(f.sunColor, [255, 255, 255], 0.35));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawClouds(s: Surface, f: Frame): void {
|
||||
const lining = mix(f.sunColor, [255, 255, 255], 0.4);
|
||||
const base = [CLOUD_LIT(f.t), CLOUD_MID(f.t), CLOUD_SHADE(f.t)];
|
||||
for (let y = 0; y < HORIZON; y++) {
|
||||
const haze = (y / HORIZON) * 0.35;
|
||||
const row = base.map((c) => mix(c, f.horizonColor, haze));
|
||||
for (let x = 0; x < W; x++) {
|
||||
const tone = f.cloudTone[y * W + x];
|
||||
if (tone === 0) continue;
|
||||
let col: RGB = row[(tone & 3) - 1];
|
||||
if (tone & 4) {
|
||||
// Thin edges: bright silver lining close to the sun, translucent elsewhere.
|
||||
const near = Math.max(0, 1 - Math.hypot(x - f.sunX, y - f.sunY) / 55);
|
||||
if (near > 0) col = mix(col, lining, 0.75 * near);
|
||||
s.blend(x, y, col, near > 0.2 ? 1 : 0.65);
|
||||
continue;
|
||||
}
|
||||
s.set(x, y, col);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Light bleeding through and around the clouds near the sun. */
|
||||
function drawBloom(s: Surface, f: Frame): void {
|
||||
const R = 26;
|
||||
const k = 0.12 + 0.3 * f.sunOpen;
|
||||
for (let y = Math.max(0, Math.floor(f.sunY - R)); y < Math.min(HORIZON, f.sunY + R); y++) {
|
||||
for (let x = Math.floor(f.sunX - R); x <= f.sunX + R; x++) {
|
||||
const d = Math.hypot(x - f.sunX, y - f.sunY);
|
||||
if (d > R) continue;
|
||||
s.light(x, y, f.sunColor, ditherStep(k * Math.pow(1 - d / R, 2), x, y, 5));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function drawDistantLand(s: Surface, f: Frame): void {
|
||||
const island = mix(lit(f, ISLAND_COLOR), f.horizonColor, 0.55);
|
||||
const rock = mix(sunlit(f, HEADLAND_ROCK), f.horizonColor, 0.42);
|
||||
const shade = mix(lit(f, HEADLAND_SHADE), f.horizonColor, 0.35);
|
||||
for (let x = 0; x < W; x++) {
|
||||
for (let y = ISLAND[x]; y < HORIZON; y++) s.set(x, y, island);
|
||||
const top = HEADLAND[x];
|
||||
// Faces turned toward the sun are lighter.
|
||||
const facesSun = x < f.sunX ? (HEADLAND[Math.min(W - 1, x + 1)] ?? top) >= top : (HEADLAND[Math.max(0, x - 1)] ?? top) >= top;
|
||||
for (let y = top; y < HORIZON; y++) s.set(x, y, facesSun && y - top < 6 ? rock : shade);
|
||||
}
|
||||
}
|
||||
|
||||
/** Crepuscular rays fanning down from the sun wherever the clouds near it open up. */
|
||||
export function drawGodRays(s: Surface, f: Frame): void {
|
||||
if (f.rays <= 0) return;
|
||||
const sx = f.sunX;
|
||||
const sy = f.sunY;
|
||||
const { d, th } = f.clouds;
|
||||
// Rays are soft, so their strength is worked out per 2x2 block and dithered per pixel.
|
||||
for (let by = Math.max(0, Math.floor(sy - 4)) & ~1; by < H; by += 2) {
|
||||
const dy = by + 0.5 - sy;
|
||||
for (let bx = 0; bx < W; bx += 2) {
|
||||
const dx = bx + 0.5 - sx;
|
||||
const r = Math.hypot(dx, dy);
|
||||
if (r < 16) continue;
|
||||
const ray = rayAt(f.rayTable, Math.atan2(dy, dx));
|
||||
if (ray <= 0) continue;
|
||||
const k = f.rays * ray * Math.exp(-r / 150) * Math.min(1, (r - 16) / 24) * 0.2;
|
||||
for (let y = by; y < by + 2; y++) {
|
||||
for (let x = bx; x < bx + 2; x++) {
|
||||
// Rays read as light in the air, so they show less over solid cloud.
|
||||
const kk = y < HORIZON && d[y * W + x] > th ? k * 0.35 : k;
|
||||
s.light(x, y, f.sunColor, ditherStep(kk, x, y, 6));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,147 @@
|
|||
import { add, gradient, hex, mul, scale, type RGB } from '../../engine/color';
|
||||
import { colorTrack, ease, progress, track } from '../../engine/Timeline';
|
||||
import { computeClouds, computeGroundLight, computeRayTable, openness, shadeClouds, type CloudField } from './clouds';
|
||||
import { wavesNear, type Wave } from './waves';
|
||||
|
||||
/** All timings for the Mediterranean Coast meditation, in seconds. */
|
||||
export const DURATION = 300;
|
||||
|
||||
export const TIMES = {
|
||||
fadeIn: [0, 6],
|
||||
fadeOut: [291, 300],
|
||||
boat: [6, 294],
|
||||
} as const;
|
||||
|
||||
/** Light phases: overcast afternoon → clouds breaking → mostly clear → golden evening. */
|
||||
const P = [0, 90, 200, 300] as const;
|
||||
const phase = (a: string, b: string, c: string, d: string) =>
|
||||
colorTrack([
|
||||
[P[0], hex(a)],
|
||||
[P[1], hex(b)],
|
||||
[P[2], hex(c)],
|
||||
[P[3], hex(d)],
|
||||
]);
|
||||
|
||||
/** Sky gradient stops from zenith to horizon. */
|
||||
const SKY = [
|
||||
phase('#5b7ba2', '#4f7cb4', '#3f6aa8', '#34508e'),
|
||||
phase('#7b98bc', '#77a0cc', '#6b90c4', '#6a78b0'),
|
||||
phase('#a0b8d0', '#a8c4dc', '#a8b8d0', '#c0909e'),
|
||||
phase('#c6d2dc', '#d6dcd8', '#e8c8a8', '#f2a878'),
|
||||
phase('#dedfd8', '#f0e2c4', '#ffd49a', '#ffc070'),
|
||||
];
|
||||
|
||||
/** Overall light on the scene as a per-channel multiplier. */
|
||||
const AMBIENT = phase('#c4c8d2', '#e2dace', '#fff2dc', '#f4c896');
|
||||
|
||||
export const CLOUD_LIT = phase('#eceef2', '#f6f2ea', '#fff0dc', '#ffdcb4');
|
||||
export const CLOUD_MID = phase('#b8bec8', '#c8cad0', '#e4ccc0', '#e8a89a');
|
||||
export const CLOUD_SHADE = phase('#7e8698', '#8a90a4', '#a092a8', '#8e6e8c');
|
||||
|
||||
const sunX = track([[0, 204], [300, 188]], ease.linear);
|
||||
const sunY = track([[0, 24], [300, 58]], ease.linear);
|
||||
const sunColor = phase('#fffbea', '#fff4d4', '#ffe0a0', '#ffbe68');
|
||||
const cover = track([[0, 0.84], [50, 0.8], [150, 0.52], [230, 0.24], [300, 0.14]]);
|
||||
const rays = track([[0, 0.6], [25, 1], [150, 0.85], [235, 0]]);
|
||||
const golden = track([[150, 0], [300, 1]]);
|
||||
|
||||
export const SUN_R = 7;
|
||||
export const SKY_BANDS = 22;
|
||||
|
||||
export interface Frame {
|
||||
t: number;
|
||||
amb: RGB;
|
||||
skyBands: RGB[];
|
||||
horizonColor: RGB;
|
||||
sunX: number;
|
||||
sunY: number;
|
||||
sunColor: RGB;
|
||||
/** How much of the sun is unobstructed by cloud, 0–1. */
|
||||
sunOpen: number;
|
||||
/** Strength of direct sunlight on lit surfaces, 0–1. */
|
||||
direct: number;
|
||||
cover: number;
|
||||
rays: number;
|
||||
golden: number;
|
||||
clouds: CloudField;
|
||||
/** Brightness of cloud light and shadow below the horizon, per pixel (see computeGroundLight). */
|
||||
groundLight: Float32Array;
|
||||
/** Cached per-pixel cloud tones (see shadeClouds). */
|
||||
cloudTone: Uint8Array;
|
||||
/** God-ray brightness by angle from the sun (see clouds.ts). */
|
||||
rayTable: Float32Array;
|
||||
waves: Wave[];
|
||||
fade: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clouds drift about a pixel a second, so the field is recomputed only every 1/12 s of scene time.
|
||||
* Keying the cache on quantized time keeps the scene a pure function of t.
|
||||
*/
|
||||
const CLOUD_STEP = 1 / 12;
|
||||
let cache:
|
||||
| { key: number; clouds: CloudField; tone: Uint8Array; light: Float32Array; rays: Float32Array; sunOpen: number }
|
||||
| undefined;
|
||||
|
||||
function cloudsAt(t: number) {
|
||||
const key = Math.round(t / CLOUD_STEP);
|
||||
if (cache?.key === key) return cache;
|
||||
const tq = key * CLOUD_STEP;
|
||||
const sx = sunX(tq);
|
||||
const sy = sunY(tq);
|
||||
const cv = cover(tq);
|
||||
const clouds = computeClouds(tq, cv, sx, sy, cache?.clouds);
|
||||
let open = 0;
|
||||
for (let i = 0; i < 9; i++) {
|
||||
const a = (i / 9) * Math.PI * 2;
|
||||
open += openness(clouds, sx + Math.cos(a) * (i ? 4 : 0), sy + Math.sin(a) * (i ? 4 : 0));
|
||||
}
|
||||
cache = {
|
||||
key,
|
||||
clouds,
|
||||
tone: shadeClouds(clouds, sx, cv, cache?.tone),
|
||||
light: computeGroundLight(clouds, cache?.light),
|
||||
rays: computeRayTable(clouds, sx, sy, tq, cache?.rays),
|
||||
sunOpen: open / 9,
|
||||
};
|
||||
return cache;
|
||||
}
|
||||
|
||||
export function frameAt(t: number): Frame {
|
||||
const sky = SKY.map((c) => c(t));
|
||||
const sx = sunX(t);
|
||||
const sy = sunY(t);
|
||||
const cv = cover(t);
|
||||
const { clouds, tone: cloudTone, light: groundLight, rays: rayTable, sunOpen } = cloudsAt(t);
|
||||
return {
|
||||
t,
|
||||
amb: scale(AMBIENT(t), 1 / 255),
|
||||
skyBands: Array.from({ length: SKY_BANDS }, (_, i) => gradient(sky, i / (SKY_BANDS - 1))),
|
||||
horizonColor: sky[4],
|
||||
sunX: sx,
|
||||
sunY: sy,
|
||||
sunColor: sunColor(t),
|
||||
sunOpen,
|
||||
// Even behind thin cloud some direct light gets through; it strengthens as the sky clears.
|
||||
direct: 0.25 + 0.75 * Math.max(sunOpen, 1 - cv),
|
||||
cover: cv,
|
||||
rays: rays(t),
|
||||
golden: golden(t),
|
||||
clouds,
|
||||
cloudTone,
|
||||
groundLight,
|
||||
rayTable,
|
||||
waves: wavesNear(t),
|
||||
fade: progress(t, TIMES.fadeIn[0], TIMES.fadeIn[1]) * (1 - progress(t, TIMES.fadeOut[0], TIMES.fadeOut[1])),
|
||||
};
|
||||
}
|
||||
|
||||
/** Apply ambient light to a base (daylight) color. */
|
||||
export function lit(f: Frame, base: RGB): RGB {
|
||||
return mul(base, f.amb);
|
||||
}
|
||||
|
||||
/** Ambient light plus a share of warm direct sun, for surfaces facing the sun. */
|
||||
export function sunlit(f: Frame, base: RGB, k = 0.22): RGB {
|
||||
return add(mul(base, f.amb), mul(base, scale(f.sunColor, 1 / 255)), k * f.direct);
|
||||
}
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
import { ease, progress } from '../../engine/Timeline';
|
||||
import { noise1 } from '../../engine/rng';
|
||||
import { BREAK, SHORE } from './world';
|
||||
|
||||
/** Length of the looping wave sound, public/audio/fx-waves.mp3. */
|
||||
export const WAVE_LOOP = 30;
|
||||
|
||||
/**
|
||||
* Crash peaks measured from the loudness envelope of fx-waves.mp3, as [seconds into the loop, strength].
|
||||
* Every visual wave is keyed to one of these so the picture and the sound break together.
|
||||
*/
|
||||
const PEAKS: readonly (readonly [number, number])[] = [
|
||||
[1.5, 0.35],
|
||||
[5.7, 0.8],
|
||||
[8.6, 0.9],
|
||||
[11.6, 0.4],
|
||||
[13.2, 1.0],
|
||||
[15.8, 0.45],
|
||||
[17.7, 0.85],
|
||||
[20.9, 0.95],
|
||||
[25.9, 0.85],
|
||||
[28.7, 0.35],
|
||||
];
|
||||
|
||||
/** Seconds a swell is visible before it breaks. */
|
||||
export const APPROACH = 3.2;
|
||||
const RUN_UP = 2.3;
|
||||
const BACKWASH = 3.4;
|
||||
const WET_FADE = 10;
|
||||
|
||||
export interface Wave {
|
||||
/** Absolute time of the crash. */
|
||||
peak: number;
|
||||
strength: number;
|
||||
/** Seed so each wave's edge has its own shape. */
|
||||
id: number;
|
||||
}
|
||||
|
||||
/** Waves relevant around time t (approaching, breaking, washing or still drying). */
|
||||
export function wavesNear(t: number): Wave[] {
|
||||
const loop = Math.floor(t / WAVE_LOOP);
|
||||
const out: Wave[] = [];
|
||||
for (let k = loop - 1; k <= loop + 1; k++) {
|
||||
PEAKS.forEach(([p, strength], i) => {
|
||||
const peak = k * WAVE_LOOP + p;
|
||||
if (t > peak - APPROACH - 0.5 && t < peak + RUN_UP + BACKWASH + WET_FADE) {
|
||||
out.push({ peak, strength, id: (k + 10) * 16 + i });
|
||||
}
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** How far up the sand (in rows past the resting waterline) this wave's water reaches at column x. */
|
||||
export function waveReach(w: Wave, x: number): number {
|
||||
return (5 + 14 * w.strength) * (0.75 + 0.5 * noise1(x / 11 + w.id * 3.7, 9));
|
||||
}
|
||||
|
||||
/** The wave's local break time at column x: it peels a little along the beach. */
|
||||
export function breakTime(w: Wave, x: number): number {
|
||||
const dir = w.id % 2 === 0 ? 1 : -1;
|
||||
return w.peak + ((x - 160) / 320) * 0.7 * dir;
|
||||
}
|
||||
|
||||
/** Row of the water's leading edge for one wave at column x, or -Infinity before it reaches the sand. */
|
||||
export function waveFront(w: Wave, x: number, t: number): number {
|
||||
const tb = breakTime(w, x);
|
||||
if (t < tb) return -Infinity;
|
||||
const rest = SHORE[x];
|
||||
const max = rest + waveReach(w, x);
|
||||
if (t < tb + RUN_UP) {
|
||||
const u = ease.out((t - tb) / RUN_UP);
|
||||
return BREAK[x] + (max - BREAK[x]) * u;
|
||||
}
|
||||
const u = progress(t, tb + RUN_UP, tb + RUN_UP + BACKWASH, ease.sine);
|
||||
return max + (rest - 3 - max) * u;
|
||||
}
|
||||
|
||||
/** The furthest the water has run up at column x right now. */
|
||||
export function waterEdge(waves: Wave[], x: number, t: number): number {
|
||||
// A slow breathing of the waterline between waves.
|
||||
let edge = SHORE[x] + Math.sin(t * 0.9 + x * 0.03) * 0.8;
|
||||
for (const w of waves) edge = Math.max(edge, waveFront(w, x, t));
|
||||
return edge;
|
||||
}
|
||||
|
||||
/** Lowest row (furthest up the beach) one wave has wetted in column x so far. */
|
||||
export function wetReach(w: Wave, x: number, t: number): number {
|
||||
const tb = breakTime(w, x);
|
||||
return SHORE[x] + waveReach(w, x) * Math.min(1, ease.out(Math.max(0, t - tb) / RUN_UP));
|
||||
}
|
||||
|
||||
/** 0–1 dampness one wave leaves in column x (above its wetReach), fading as the sand dries. */
|
||||
export function wetness(w: Wave, x: number, t: number): number {
|
||||
const tb = breakTime(w, x);
|
||||
if (t < tb + 0.4) return 0;
|
||||
return Math.min(1, 1 - Math.max(0, (t - (tb + RUN_UP)) / WET_FADE));
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import { noise1 } from '../../engine/rng';
|
||||
|
||||
/** Fixed layout of the scene on the 320x180 canvas. */
|
||||
export const W = 320;
|
||||
export const H = 180;
|
||||
|
||||
/** Where the sea meets the sky. */
|
||||
export const HORIZON = 78;
|
||||
|
||||
/**
|
||||
* Resting waterline for each column. The cove curves away at the sides, so the water
|
||||
* comes closest to the viewer in the middle.
|
||||
*/
|
||||
export const SHORE: readonly number[] = Array.from({ length: W }, (_, x) => {
|
||||
const u = (x - 165) / 175;
|
||||
return Math.round(114 + 9 * (1 - u * u) + 1.5 * Math.sin(x * 0.045) + (noise1(x / 14, 3) - 0.5) * 2);
|
||||
});
|
||||
|
||||
/** Where incoming swells break, a little out from the waterline. */
|
||||
export const BREAK: readonly number[] = SHORE.map((y, x) => y - 6 - Math.round(noise1(x / 20, 4) * 2));
|
||||
|
||||
/** Distant island silhouette (top row per column, or H when absent). */
|
||||
export const ISLAND: readonly number[] = Array.from({ length: W }, (_, x) => {
|
||||
const u = (x - 118) / 30;
|
||||
if (Math.abs(u) > 1) return H;
|
||||
const h = (1 - u * u) * 5 + noise1(x / 4, 5) * 2;
|
||||
return Math.round(HORIZON - h);
|
||||
});
|
||||
|
||||
/** Rocky headlands at the far edges of the bay, mostly hidden behind the jungle. */
|
||||
export const HEADLAND: readonly number[] = Array.from({ length: W }, (_, x) => {
|
||||
const left = 58 + Math.max(0, x - 40) * 0.42 + noise1(x / 6, 6) * 3;
|
||||
const right = 60 + Math.max(0, 268 - x) * 0.38 + noise1(x / 6, 7) * 3;
|
||||
return Math.round(Math.min(HORIZON, left, right));
|
||||
});
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { bayer, hex, mix, type RGB } from '../../engine/color';
|
||||
import { bayer, ditherStep, hex, mix, type RGB } from '../../engine/color';
|
||||
import { progress } from '../../engine/Timeline';
|
||||
import { Rng } from '../../engine/rng';
|
||||
import type { Surface } from '../../engine/Surface';
|
||||
|
|
@ -40,8 +40,7 @@ const AURORA_HIGH = hex('#9a6cff');
|
|||
const MOON = hex('#f2f0e0');
|
||||
const MOON_SHADE = hex('#c9c6b4');
|
||||
|
||||
/** Quantize an alpha to a few dithered steps so soft light still looks like pixel art. */
|
||||
const steps = (a: number, x: number, y: number, n = 6) => Math.floor(a * n + bayer(x, y)) / n;
|
||||
const steps = ditherStep;
|
||||
|
||||
export function drawSky(s: Surface, f: Frame): void {
|
||||
// Banded gradient with dithered seams.
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
import type { Meditation } from './types';
|
||||
import { mediterraneanCoast } from './mediterranean-coast';
|
||||
import { northernCabin } from './northern-cabin';
|
||||
|
||||
/** Every meditation listed on the main menu, in display order. Add new ones here. */
|
||||
export const meditations: readonly Meditation[] = [northernCabin];
|
||||
export const meditations: readonly Meditation[] = [northernCabin, mediterraneanCoast];
|
||||
|
||||
export function findMeditation(id: string): Meditation | undefined {
|
||||
return meditations.find((m) => m.id === id);
|
||||
|
|
|
|||
|
|
@ -19,5 +19,7 @@ export interface Meditation {
|
|||
previewTime: number;
|
||||
/** Optional music file, e.g. 'audio/northern-cabin.mp3' (placed in /public). */
|
||||
music?: string;
|
||||
/** Optional ambient sound that loops seamlessly for the whole meditation, kept in step with the scene clock. */
|
||||
ambience?: { src: string; volume?: number };
|
||||
createScene(): Scene;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { Music } from '../engine/audio';
|
||||
import { AmbientLoop, Music } from '../engine/audio';
|
||||
import { Loop } from '../engine/Loop';
|
||||
import { PixelCanvas } from '../engine/PixelCanvas';
|
||||
import type { Meditation, Scene } from '../meditations/types';
|
||||
|
|
@ -22,6 +22,43 @@ const ICONS = {
|
|||
'<svg viewBox="0 0 10 10" fill="currentColor"><path d="M1 1h3v1H2v2H1zM6 1h3v3H8V2H6zM1 6h1v2h2v1H1zM8 6h1v3H6V8h2z"/></svg>',
|
||||
};
|
||||
|
||||
/** Music plus an optional looping ambience, driven together from the meditation clock. */
|
||||
class Soundtrack {
|
||||
private readonly music: Music;
|
||||
private readonly ambience: AmbientLoop;
|
||||
|
||||
constructor(m: Meditation, enabled: boolean) {
|
||||
this.music = new Music(enabled ? m.music : undefined, 0.75);
|
||||
this.ambience = new AmbientLoop(enabled ? m.ambience?.src : undefined, m.ambience?.volume);
|
||||
}
|
||||
|
||||
play(t: number): void {
|
||||
this.music.seek(t);
|
||||
this.music.play();
|
||||
this.ambience.start(t);
|
||||
}
|
||||
|
||||
pause(): void {
|
||||
this.music.pause();
|
||||
this.ambience.pause();
|
||||
}
|
||||
|
||||
seek(t: number): void {
|
||||
this.music.seek(t);
|
||||
this.ambience.seek(t);
|
||||
}
|
||||
|
||||
update(t: number, duration: number): void {
|
||||
this.music.update(t, duration);
|
||||
this.ambience.update(t, duration);
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
this.music.destroy();
|
||||
this.ambience.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(s: number): string {
|
||||
const v = Math.max(0, Math.ceil(s));
|
||||
return `${Math.floor(v / 60)}:${String(v % 60).padStart(2, '0')}`;
|
||||
|
|
@ -34,7 +71,7 @@ export class Player implements View {
|
|||
private readonly root: HTMLElement;
|
||||
private readonly view: PixelCanvas;
|
||||
private readonly loop: Loop;
|
||||
private readonly music: Music;
|
||||
private readonly sound: Soundtrack;
|
||||
private readonly scene: Scene;
|
||||
private t: number;
|
||||
private state: State = 'ready';
|
||||
|
|
@ -59,7 +96,8 @@ export class Player implements View {
|
|||
parent.appendChild(this.root);
|
||||
this.view = new PixelCanvas(this.root);
|
||||
this.scene = m.createScene();
|
||||
this.music = new Music(m.music);
|
||||
// Sound can't follow a dev fast-forward, so it stays off then.
|
||||
this.sound = new Soundtrack(m, (opts.speed ?? 1) === 1);
|
||||
this.t = opts.startAt ?? 0;
|
||||
|
||||
this.begin = this.overlay(`
|
||||
|
|
@ -130,7 +168,7 @@ export class Player implements View {
|
|||
this.finish();
|
||||
}
|
||||
}
|
||||
this.music.update(this.t, this.m.duration);
|
||||
this.sound.update(this.t, this.m.duration);
|
||||
this.render();
|
||||
};
|
||||
|
||||
|
|
@ -147,14 +185,13 @@ export class Player implements View {
|
|||
this.begin.classList.add('hidden');
|
||||
this.end.classList.add('hidden');
|
||||
this.controls.classList.remove('hidden');
|
||||
this.music.seek(this.t);
|
||||
this.music.play();
|
||||
this.sound.play(this.t);
|
||||
this.wake();
|
||||
}
|
||||
|
||||
private finish(): void {
|
||||
this.state = 'ended';
|
||||
this.music.pause();
|
||||
this.sound.pause();
|
||||
this.controls.classList.add('hidden');
|
||||
this.root.classList.remove('idle');
|
||||
this.end.classList.remove('hidden');
|
||||
|
|
@ -164,8 +201,8 @@ export class Player implements View {
|
|||
private setPaused(paused: boolean): void {
|
||||
if (this.state !== 'playing' && this.state !== 'paused') return;
|
||||
this.state = paused ? 'paused' : 'playing';
|
||||
if (paused) this.music.pause();
|
||||
else this.music.play();
|
||||
if (paused) this.sound.pause();
|
||||
else this.sound.play(this.t);
|
||||
this.playBtn.innerHTML = paused ? ICONS.play : ICONS.pause;
|
||||
this.playBtn.setAttribute('aria-label', paused ? 'Play' : 'Pause');
|
||||
this.pausedLabel.style.opacity = paused ? '1' : '0';
|
||||
|
|
@ -213,7 +250,7 @@ export class Player implements View {
|
|||
}
|
||||
if (import.meta.env.DEV && (e.key === '[' || e.key === ']')) {
|
||||
this.t = Math.max(0, Math.min(this.m.duration - 0.01, this.t + (e.key === ']' ? 10 : -10)));
|
||||
this.music.seek(this.t);
|
||||
this.sound.seek(this.t);
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -223,7 +260,7 @@ export class Player implements View {
|
|||
|
||||
destroy(): void {
|
||||
this.loop.stop();
|
||||
this.music.destroy();
|
||||
this.sound.destroy();
|
||||
clearTimeout(this.idleTimer);
|
||||
window.removeEventListener('keydown', this.onKey);
|
||||
document.removeEventListener('visibilitychange', this.onVisibility);
|
||||
|
|
|
|||
Loading…
Reference in New Issue