Add per-frame gain to cues and maglev train sounds to Cyberpunk City

- Extend `Cue` with an optional `gain(t)` so a cue's volume can be rescaled every frame while it plays (e.g. by source distance), updated live in `CueTrack`.
- Play each maglev train's `fx-train.mp3` as it slides into view, swelling with the drone's proximity via `TRAIN_PASSES` distance data in `traffic.ts`.
- Rework flyby selection to avoid reusing a file still playing for an earlier car instead of just skipping close passes.
- Fix train window shading to be relative to each car's own end so windows ride along with it.
- Update README cue docs and swap the `fx-city.mp3` ambience loop.
This commit is contained in:
Brian Fertig 2026-10-31 20:06:49 -06:00
parent 166dae262c
commit 4d9ccbe3e5
7 changed files with 82 additions and 24 deletions

View File

@ -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` `fx-waves.mp3`; its wave crashes are timed to the peaks listed in `mediterranean-coast/waves.ts`
(re-measure them if the file changes). (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). - `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 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 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. With Docker, rebuild the `web` image (`docker compose up --build -d`) after adding audio so it's included.

Binary file not shown.

BIN
public/audio/fx-train.mp3 Normal file

Binary file not shown.

View File

@ -178,7 +178,7 @@ export class CueTrack {
private readonly cues: readonly Cue[]; private readonly cues: readonly Cue[];
private readonly buffers = new Map<string, AudioBuffer>(); private readonly buffers = new Map<string, AudioBuffer>();
private loading?: Promise<void>; private loading?: Promise<void>;
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. */ /** Index of the first cue not yet scheduled. */
private next = 0; private next = 0;
private playing = false; private playing = false;
@ -223,7 +223,15 @@ export class CueTrack {
if (!this.ctx || !this.master) return; if (!this.ctx || !this.master) return;
const k = Math.max(0, Math.min(1, t / this.fadeIn, (duration - t) / this.fadeOut)); 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); 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 { destroy(): void {
@ -259,16 +267,17 @@ export class CueTrack {
while (this.next < this.cues.length && this.cues[this.next].t < t + CUE_LOOKAHEAD) { while (this.next < this.cues.length && this.cues[this.next].t < t + CUE_LOOKAHEAD) {
const cue = this.cues[this.next++]; const cue = this.cues[this.next++];
const buf = this.buffers.get(cue.src); 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. */ /** 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, delay: number): void { private play(cue: Cue, buf: AudioBuffer, t: number): void {
const ctx = this.ctx!; const ctx = this.ctx!;
const now = ctx.currentTime; const now = ctx.currentTime;
const delay = cue.t - t;
const gain = ctx.createGain(); const gain = ctx.createGain();
gain.gain.value = cue.volume ?? 1; gain.gain.value = this.levelAt(cue, Math.max(t, cue.t));
if (cue.pan) { if (cue.pan) {
const pan = ctx.createStereoPanner(); const pan = ctx.createStereoPanner();
pan.pan.value = cue.pan; pan.pan.value = cue.pan;
@ -277,7 +286,7 @@ export class CueTrack {
const node = ctx.createBufferSource(); const node = ctx.createBufferSource();
node.buffer = buf; node.buffer = buf;
node.connect(gain); node.connect(gain);
const voice = { node, gain }; const voice = { cue, node, gain };
this.live.add(voice); this.live.add(voice);
node.onended = () => this.live.delete(voice); node.onended = () => this.live.delete(voice);
node.start(now + Math.max(0, delay), Math.max(0, -delay)); node.start(now + Math.max(0, delay), Math.max(0, -delay));

View File

@ -9,7 +9,7 @@ import { drawRain } from './rain';
import { clearFrame, drawSky } from './sky'; import { clearFrame, drawSky } from './sky';
import { drawGround, drawStalls, drawSteam } from './street'; import { drawGround, drawStalls, drawSteam } from './street';
import { DURATION, frameAt } from './timeline'; import { DURATION, frameAt } from './timeline';
import { drawTraffic, PASSES, traceTrafficReflections } from './traffic'; import { drawTraffic, PASSES, traceTrafficReflections, TRAIN_PASSES } from './traffic';
const scene: Scene = { const scene: Scene = {
render(s, t) { 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_FILES = 5;
const FLYBY_LEN = 5;
const FLYBY_MID = 2.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 FLYBYS: Cue[] = (() => {
const r = new Rng(808); const r = new Rng(808);
const out: Cue[] = []; const out: Cue[] = [];
const endsAt = new Array<number>(FLYBY_FILES).fill(-Infinity);
let last = -1; let last = -1;
let prevT = -Infinity;
for (const p of PASSES) { for (const p of PASSES) {
// Skip the first seconds, still fading in, and let two cars passing together share one sound. // Skip the first seconds, while the scene is still fading in.
if (p.t < 3 || p.t - prevT < 2.5) continue; if (p.t < 3) continue;
let n = r.int(0, FLYBY_FILES - 2); const t = p.t - FLYBY_MID;
if (n >= last) n++; 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; last = n;
prevT = p.t; 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) });
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) });
} }
return out; 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 = { export const cyberpunkCity: Meditation = {
id: 'cyberpunk-city', id: 'cyberpunk-city',
title: 'Cyberpunk City', title: 'Cyberpunk City',
@ -66,7 +83,7 @@ export const cyberpunkCity: Meditation = {
{ src: 'audio/fx-rain.mp3', volume: 0.5 }, { src: 'audio/fx-rain.mp3', volume: 0.5 },
{ src: 'audio/fx-city.mp3', volume: 0.4 }, { src: 'audio/fx-city.mp3', volume: 0.4 },
], ],
cues: FLYBYS, cues: [...FLYBYS, ...TRAINS],
duration: DURATION, duration: DURATION,
previewTime: 282, previewTime: 282,
createScene: () => scene, createScene: () => scene,

View File

@ -380,10 +380,15 @@ function shadePillar(face: number, _X: number, Y: number, _Z: number, d: number)
return haze(c, 1 - glowClarity(d) * 0.9); 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[] { function trainCars(t: number): Box3[] {
const out: Box3[] = []; const out: Box3[] = [];
for (const tr of TRAINS) { 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; if (Math.abs(head) > 700) continue;
for (let n = 0; n < TRAIN_CARS; n++) { for (let n = 0; n < TRAIN_CARS; n++) {
const x0 = head - tr.dir * n * (CAR_LEN + 0.8); const x0 = head - tr.dir * n * (CAR_LEN + 0.8);
@ -394,12 +399,13 @@ function trainCars(t: number): Box3[] {
return out; 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; const lv = (Y - DECK.y1 - 0.3) / 3.4;
let c: RGB = TRAIN_BODY; let c: RGB = TRAIN_BODY;
if (face === TOP) c = scale(TRAIN_BODY, 0.75); if (face === TOP) c = scale(TRAIN_BODY, 0.75);
else if (face === FRONT) { 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 if (lv < 0.18) c = PINK;
} else c = scale(TRAIN_BODY, 0.8); } else c = scale(TRAIN_BODY, 0.8);
return haze(c, 1 - glowClarity(d)); 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; if (MAG_Z < cam.z) return;
traceBox(r, cam, DECK, shadeDeck, mirror); traceBox(r, cam, DECK, shadeDeck, mirror);
for (const p of PILLARS) traceBox(r, cam, p, shadePillar, 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);
},
}));

View File

@ -31,6 +31,8 @@ export interface Cue {
src: string; src: string;
volume?: number; volume?: number;
pan?: 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 { export interface Meditation {