diff --git a/README.md b/README.md index 6c6ebc8..5c82116 100644 --- a/README.md +++ b/README.md @@ -57,10 +57,12 @@ Audio lives in `public/audio/` and is configured per meditation in its `index.ts `fx-waves.mp3`; its wave crashes are timed to the peaks listed in `mediterranean-coast/waves.ts` (re-measure them if the file changes). - `ambience: [{ … }, { … }]` — a list layers several loops at once (Cyberpunk City plays `fx-rain.mp3` and `fx-city.mp3` together). -- `cues: [{ t, src, volume, pan }]` — one-shot sound effects starting at scene time `t`, also kept in sync after pause and skip. +- `cues: [{ t, src, volume, pan, gain }]` — one-shot sound effects starting at scene time `t`, also kept in sync after pause and skip. + An optional `gain(t)` rescales the volume every frame while it plays. Cyberpunk City plays a random `fx-flyby-1…5.mp3` whenever a hover car passes close under the drone, timed so the middle of the file (`FLYBY_MID` in its `index.ts`) lands as the car crosses the bottom edge of the frame; the crossings are worked out - from the traffic in `cyberpunk-city/traffic.ts` (`PASSES`). + from the traffic in `cyberpunk-city/traffic.ts` (`PASSES`). Each maglev train plays `fx-train.mp3` as it comes into view, + its `gain` following the drone's distance to the train (`TRAIN_PASSES`). With Docker, rebuild the `web` image (`docker compose up --build -d`) after adding audio so it's included. diff --git a/public/audio/fx-city.mp3 b/public/audio/fx-city.mp3 index 852ba9a..ea35592 100644 Binary files a/public/audio/fx-city.mp3 and b/public/audio/fx-city.mp3 differ diff --git a/public/audio/fx-train.mp3 b/public/audio/fx-train.mp3 new file mode 100644 index 0000000..c2fa14d Binary files /dev/null and b/public/audio/fx-train.mp3 differ diff --git a/src/engine/audio.ts b/src/engine/audio.ts index 5f8ce96..8d97591 100644 --- a/src/engine/audio.ts +++ b/src/engine/audio.ts @@ -178,7 +178,7 @@ export class CueTrack { private readonly cues: readonly Cue[]; private readonly buffers = new Map(); private loading?: Promise; - private readonly live = new Set<{ node: AudioBufferSourceNode; gain: GainNode }>(); + private readonly live = new Set<{ cue: Cue; node: AudioBufferSourceNode; gain: GainNode }>(); /** Index of the first cue not yet scheduled. */ private next = 0; private playing = false; @@ -223,7 +223,15 @@ export class CueTrack { 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.ctx.currentTime, 0.1); - if (this.playing && this.buffers.size) this.schedule(t); + if (!this.playing || !this.buffers.size) return; + this.schedule(t); + for (const { cue, gain } of this.live) { + if (cue.gain && t >= cue.t) gain.gain.setTargetAtTime(this.levelAt(cue, t), this.ctx.currentTime, 0.1); + } + } + + private levelAt(cue: Cue, t: number): number { + return (cue.volume ?? 1) * (cue.gain?.(t) ?? 1); } destroy(): void { @@ -259,16 +267,17 @@ export class CueTrack { while (this.next < this.cues.length && this.cues[this.next].t < t + CUE_LOOKAHEAD) { const cue = this.cues[this.next++]; const buf = this.buffers.get(cue.src); - if (buf && cue.t + buf.duration > t) this.play(cue, buf, cue.t - t); + if (buf && cue.t + buf.duration > t) this.play(cue, buf, t); } } - /** Start a cue `delay` seconds from now, or partway in when the delay is negative. */ - private play(cue: Cue, buf: AudioBuffer, delay: number): void { + /** Start a cue at its time, given the clock now: shortly from now, or partway in if it's under way. */ + private play(cue: Cue, buf: AudioBuffer, t: number): void { const ctx = this.ctx!; const now = ctx.currentTime; + const delay = cue.t - t; const gain = ctx.createGain(); - gain.gain.value = cue.volume ?? 1; + gain.gain.value = this.levelAt(cue, Math.max(t, cue.t)); if (cue.pan) { const pan = ctx.createStereoPanner(); pan.pan.value = cue.pan; @@ -277,7 +286,7 @@ export class CueTrack { const node = ctx.createBufferSource(); node.buffer = buf; node.connect(gain); - const voice = { node, gain }; + const voice = { cue, node, gain }; this.live.add(voice); node.onended = () => this.live.delete(voice); node.start(now + Math.max(0, delay), Math.max(0, -delay)); diff --git a/src/meditations/cyberpunk-city/index.ts b/src/meditations/cyberpunk-city/index.ts index 5282a5d..9fb1444 100644 --- a/src/meditations/cyberpunk-city/index.ts +++ b/src/meditations/cyberpunk-city/index.ts @@ -9,7 +9,7 @@ import { drawRain } from './rain'; import { clearFrame, drawSky } from './sky'; import { drawGround, drawStalls, drawSteam } from './street'; import { DURATION, frameAt } from './timeline'; -import { drawTraffic, PASSES, traceTrafficReflections } from './traffic'; +import { drawTraffic, PASSES, traceTrafficReflections, TRAIN_PASSES } from './traffic'; const scene: Scene = { render(s, t) { @@ -33,28 +33,45 @@ const scene: Scene = { }, }; -/** The fx-flyby-N.mp3 files, and their midpoint (s), which lands as the car crosses the bottom of the frame. */ +/** The fx-flyby-N.mp3 files: how many, their length and midpoint (s), which lands as the car crosses the bottom of the frame. */ const FLYBY_FILES = 5; +const FLYBY_LEN = 5; const FLYBY_MID = 2.5; -/** A whoosh for each hover car that passes close, picked at random but never the same one twice running. */ +/** + * A whoosh for each hover car that passes close, picked at random from the files not still playing + * for an earlier car, so cars passing together never sound alike. + */ const FLYBYS: Cue[] = (() => { const r = new Rng(808); const out: Cue[] = []; + const endsAt = new Array(FLYBY_FILES).fill(-Infinity); let last = -1; - let prevT = -Infinity; for (const p of PASSES) { - // Skip the first seconds, still fading in, and let two cars passing together share one sound. - if (p.t < 3 || p.t - prevT < 2.5) continue; - let n = r.int(0, FLYBY_FILES - 2); - if (n >= last) n++; + // Skip the first seconds, while the scene is still fading in. + if (p.t < 3) continue; + const t = p.t - FLYBY_MID; + let free = endsAt.flatMap((e, n) => (e <= t && n !== last ? [n] : [])); + if (!free.length) free = endsAt.flatMap((_, n) => (n !== last ? [n] : [])); + const n = free[r.int(0, free.length - 1)]; + endsAt[n] = t + FLYBY_LEN; last = n; - prevT = p.t; - out.push({ t: p.t - FLYBY_MID, src: `audio/fx-flyby-${n + 1}.mp3`, volume: 0.55 * Math.min(1, 10 / p.dist), pan: 0.35 * Math.sign(p.x) }); + out.push({ t, src: `audio/fx-flyby-${n + 1}.mp3`, volume: 0.55 * Math.min(1, 10 / p.dist), pan: 0.35 * Math.sign(p.x) }); } return out; })(); +/** + * The maglev's hum, starting as each train slides into view and swelling the nearer it comes to the + * drone: from a soft hum blocks away to full volume as the last one passes right underneath. + */ +const TRAINS: Cue[] = TRAIN_PASSES.map((p) => ({ + t: p.seen - 0.5, + src: 'audio/fx-train.mp3', + volume: 0.7, + gain: (t) => Math.min(1, (40 / p.dist(t)) ** 0.8), +})); + export const cyberpunkCity: Meditation = { id: 'cyberpunk-city', title: 'Cyberpunk City', @@ -66,7 +83,7 @@ export const cyberpunkCity: Meditation = { { src: 'audio/fx-rain.mp3', volume: 0.5 }, { src: 'audio/fx-city.mp3', volume: 0.4 }, ], - cues: FLYBYS, + cues: [...FLYBYS, ...TRAINS], duration: DURATION, previewTime: 282, createScene: () => scene, diff --git a/src/meditations/cyberpunk-city/traffic.ts b/src/meditations/cyberpunk-city/traffic.ts index cdc51fc..f2b2804 100644 --- a/src/meditations/cyberpunk-city/traffic.ts +++ b/src/meditations/cyberpunk-city/traffic.ts @@ -380,10 +380,15 @@ function shadePillar(face: number, _X: number, Y: number, _Z: number, d: number) return haze(c, 1 - glowClarity(d) * 0.9); } +const TRAIN_LEN = TRAIN_CARS * (CAR_LEN + 0.8) - 0.8; + +/** Where a train's nose is along the track at time t. */ +const trainHead = (tr: (typeof TRAINS)[number], t: number): number => tr.dir * TRAIN_SPEED * (t - tr.t); + function trainCars(t: number): Box3[] { const out: Box3[] = []; for (const tr of TRAINS) { - const head = tr.dir * TRAIN_SPEED * (t - tr.t); + const head = trainHead(tr, t); if (Math.abs(head) > 700) continue; for (let n = 0; n < TRAIN_CARS; n++) { const x0 = head - tr.dir * n * (CAR_LEN + 0.8); @@ -394,12 +399,13 @@ function trainCars(t: number): Box3[] { return out; } -function shadeTrain(face: number, X: number, Y: number, _Z: number, d: number): RGB { +function shadeTrain(car: Box3, face: number, X: number, Y: number, d: number): RGB { const lv = (Y - DECK.y1 - 0.3) / 3.4; let c: RGB = TRAIN_BODY; if (face === TOP) c = scale(TRAIN_BODY, 0.75); else if (face === FRONT) { - if (lv > 0.45 && lv < 0.8) c = Math.abs((X % 2.4) - 1.2) < 0.95 ? TRAIN_WIN : scale(TRAIN_BODY, 0.5); + // Windows are spaced from the car's own end, so they ride along with it. + if (lv > 0.45 && lv < 0.8) c = Math.abs(((X - car.x0) % 2.4) - 1.2) < 0.95 ? TRAIN_WIN : scale(TRAIN_BODY, 0.5); else if (lv < 0.18) c = PINK; } else c = scale(TRAIN_BODY, 0.8); return haze(c, 1 - glowClarity(d)); @@ -409,7 +415,7 @@ function drawMaglev(r: Raster, cam: Cam, t: number, mirror: boolean): void { if (MAG_Z < cam.z) return; traceBox(r, cam, DECK, shadeDeck, mirror); for (const p of PILLARS) traceBox(r, cam, p, shadePillar, mirror); - for (const c of trainCars(t)) traceBox(r, cam, c, shadeTrain, mirror); + for (const c of trainCars(t)) traceBox(r, cam, c, (face, X, Y, _Z, d) => shadeTrain(c, face, X, Y, d), mirror); } // --------------------------------------------------------------------------- @@ -464,3 +470,25 @@ function underglow(s: Surface, cam: Cam, v: Placed): void { } } + +/** + * A train's pass across the avenue, for its sound: when its nose comes into view between the front + * rows of buildings, and how far the drone is from the nearest part of it at any time (m). + */ +export interface TrainPass { + seen: number; + dist: (t: number) => number; +} + +/** Half the width of the gap between the avenue's front rows, where the track can be seen. */ +const TRACK_VIEW = LINE + 1; + +export const TRAIN_PASSES: readonly TrainPass[] = TRAINS.map((tr) => ({ + seen: tr.t - TRACK_VIEW / TRAIN_SPEED, + dist: (t) => { + const head = trainHead(tr, t); + const [x0, x1] = tr.dir > 0 ? [head - TRAIN_LEN, head] : [head, head + TRAIN_LEN]; + const dx = Math.max(x0, 0, -x1); + return Math.hypot(dx, MAG_Z - camZAt(t), altitudeAt(t) - DECK.y1 - 2); + }, +})); diff --git a/src/meditations/types.ts b/src/meditations/types.ts index 1e6262b..df41030 100644 --- a/src/meditations/types.ts +++ b/src/meditations/types.ts @@ -31,6 +31,8 @@ export interface Cue { src: string; volume?: number; pan?: number; + /** Scales `volume` as the cue plays, checked every frame: e.g. by how near its source is at time t. */ + gain?: (t: number) => number; } export interface Meditation {