# Adaptive Environmental Soundscapes, Surface Footsteps & Lightning-Thunder Delay in Three.js

> Build a living outdoor soundscape on top of GameAudio with stride-driven surface footsteps (dirt, leaves, wood, water), distance-attenuated brook ambience, smooth weather crossfades, speed-of-sound thunder delays, and iOS Safari touchend unlock hygiene.

- **Canonical page:** https://gamecrew.ai/techniques/three/adaptive-environmental-soundscape
- **Techniques hub:** https://gamecrew.ai/techniques
- **Engine:** Three.js
- **Category:** audio
- **Tags:** `audio`, `soundscape`, `footsteps`, `surface`, `ambience`, `weather`, `thunder`, `rain`, `wind`, `brook`, `mobile`, `ios`
- **Verification:** Compile-verified pattern
- **Revision:** 1 (2026-11-24)
- **Demo:** No demo

## When to Use (and When Not To)

Use this architecture whenever a 3D exploration, survival, or open-world browser game needs reactive natural audio that responds to terrain surfaces, water proximity, and drifting weather without frame hitches or repetitive clockwork loops:

- **Stride-distance footsteps instead of fixed timers:** Trigger footsteps every `strideMeters` of actual horizontal travel so slow creeping, normal walking, and sprinting produce natural cadence with zero footsteps while standing still.
- **Surface-zone routing (`dirt`, `leaves`, `wood`, `water`):** Classify the player's ground position against priority-ordered surface zones (for example wooden footbridges and shallow creek crossings overriding forest floor) and add subtle deterministic pitch variation (`0.94..1.06`) so repeated steps stay organic.
- **Smooth exponential ambience crossfades + proximity attenuation:** Hold persistent ambient loops (`forest`, `wind`, `rain`, `brook`) via `GameAudio.loop()` and ease their gains smoothly as weather drifts or the player approaches a creek.
- **Speed-of-sound thunder queue (`distance / 343`):** Schedule thunder cues after each lightning flash using real acoustic propagation delay, attenuating gain and slightly lowering playback pitch for distant rumbles.
- **Mobile Safari unlock hygiene:** On iOS Safari, audio contexts reliably unlock on `touchend` (not `touchstart` alone); attach a one-shot `touchend` unlock hook calling `game.audio.unlock()`.

All audio playback routes strictly through `game.audio` (`GameAudio`) backed by project audio clips in `Assets/Game/Resources/Audio/`. Never bypass `GameAudio` with raw oscillator synthesis.

## Mathematical & Acoustic Core

- **Stride accumulation:** Accumulate horizontal distance $\Delta s = \sqrt{\Delta x^2 + \Delta z^2}$ while grounded; emit a footstep whenever $s \ge L_{\text{stride}}$ and reset $s \leftarrow s - L_{\text{stride}}$.
- **Inverse-square brook attenuation:** Given distance $d$ from player to creek polyline and reference radius $r_0$, gain is $g_{\text{brook}} = \frac{1}{1 + (d / r_0)^2}$, smoothed with exponential decay $\alpha = 1 - e^{-k\,\Delta t}$.
- **Lightning-to-thunder propagation:** For flash distance $D$ (metres), schedule thunder after $t_{\text{delay}} = D / 343\text{ s}$ with volume $v = \mathrm{clamp}\big(\frac{1}{1 + D / 550}, 0.15, 1.0\big)$ and pitch $p = \mathrm{clamp}(1.04 - D / 4500, 0.78, 1.04)$.

## Engine Implementation

### Strict TypeScript Adaptive Soundscape Controller (`Assets/Game/soundscape.ts`)

```ts
import type { Game, Sound } from 'ccgd';

export type SurfaceKind = 'dirt' | 'leaves' | 'wood' | 'water';

export interface SurfaceZone {
  readonly id: string;
  readonly surface: SurfaceKind;
  readonly minX: number;
  readonly maxX: number;
  readonly minZ: number;
  readonly maxZ: number;
  /** Higher priority wins when zones overlap (e.g. a wooden footbridge over a creek). */
  readonly priority: number;
}

export interface WeatherMix {
  readonly wind: number;
  readonly rain: number;
  readonly forest: number;
}

export interface ScheduledThunder {
  readonly triggerAt: number;
  readonly distanceMeters: number;
  readonly volume: number;
  readonly pitch: number;
}

const SURFACE_CUES: Record<SurfaceKind, string> = {
  dirt: 'step_dirt',
  leaves: 'step_leaves',
  wood: 'step_wood',
  water: 'step_water',
};

const AMBIENCE_CUES = {
  forest: 'amb_forest',
  wind: 'amb_wind',
  rain: 'amb_rain',
  brook: 'amb_brook',
} as const;

export const SPEED_OF_SOUND_MPS = 343;

/** Deterministic surface classifier: picks the highest-priority zone containing (x, z), else 'dirt'. */
export function classifySurface(x: number, z: number, zones: readonly SurfaceZone[]): SurfaceKind {
  let best: SurfaceZone | undefined;
  for (let i = 0; i < zones.length; i++) {
    const z0 = zones[i];
    if (x >= z0.minX && x <= z0.maxX && z >= z0.minZ && z <= z0.maxZ) {
      if (!best || z0.priority > best.priority) best = z0;
    }
  }
  return best ? best.surface : 'dirt';
}

/** Smooth inverse-square distance attenuation for localized creeks, waterfalls, or campfires. */
export function brookAttenuation(distMeters: number, refRadius = 5.5): number {
  const r = Math.max(0.25, refRadius);
  const ratio = Math.max(0, distMeters) / r;
  return 1 / (1 + ratio * ratio);
}

/** Computes propagation delay, gain, and subtle low-frequency pitch shift for a lightning strike. */
export function planThunderEvent(nowSeconds: number, distanceMeters: number): ScheduledThunder {
  const d = Math.max(35, distanceMeters);
  const delay = d / SPEED_OF_SOUND_MPS;
  const volume = Math.min(1, Math.max(0.15, 1 / (1 + d / 550)));
  const pitch = Math.min(1.04, Math.max(0.78, 1.04 - d / 4500));
  return { triggerAt: nowSeconds + delay, distanceMeters: d, volume, pitch };
}

/**
 * Coordinates surface-aware footsteps, smooth weather/brook ambience layers, lightning-delayed thunder,
 * and mobile Safari touchend audio unlock through GameAudio.
 */
export class EnvironmentalSoundscape {
  readonly zones: SurfaceZone[];
  readonly brookCenter: { x: number; z: number };
  readonly strideMeters: number;

  activeSurface: SurfaceKind = 'dirt';
  footstepsPlayed = 0;
  thundersPlayed = 0;
  readonly levels = { forest: 0.45, wind: 0.15, rain: 0, brook: 0 };

  private readonly game: Game;
  private readonly loops: Partial<Record<keyof typeof AMBIENCE_CUES, Sound>> = {};
  private readonly pendingThunder: ScheduledThunder[] = [];
  private readonly pendingStartQueue: (keyof typeof AMBIENCE_CUES)[] = ['forest', 'wind', 'rain', 'brook'];
  private strideAccum = 0;
  private lastX = 0;
  private lastZ = 0;
  private hasLast = false;
  private stepSeed = 1337;
  private unlockBound = false;

  constructor(
    game: Game,
    opts: { zones: SurfaceZone[]; brookCenter?: { x: number; z: number }; strideMeters?: number }
  ) {
    this.game = game;
    this.zones = opts.zones;
    this.brookCenter = opts.brookCenter ?? { x: 0, z: 4 };
    this.strideMeters = opts.strideMeters ?? 1.45;
  }

  /** Attaches a one-shot mobile Safari touchend gesture unlock to GameAudio. */
  bindMobileUnlock(target?: Pick<EventTarget, 'addEventListener' | 'removeEventListener'>): void {
    if (this.unlockBound || !target) return;
    this.unlockBound = true;
    const onUnlock = () => {
      this.game.audio.unlock();
      target.removeEventListener('touchend', onUnlock);
      target.removeEventListener('pointerup', onUnlock);
    };
    target.addEventListener('touchend', onUnlock, { passive: true });
    target.addEventListener('pointerup', onUnlock, { passive: true });
  }

  /** Starts one ambience bed per frame slice after load to avoid audio decode spikes on mobile. */
  stepStartupSlice(): boolean {
    const next = this.pendingStartQueue.shift();
    if (!next) return true;
    const cue = AMBIENCE_CUES[next];
    this.loops[next] = this.game.audio.loop(cue, { volume: this.levels[next] });
    return this.pendingStartQueue.length === 0;
  }

  /** Schedules a delayed thunder rumble after a lightning bolt at `distanceMeters`. */
  triggerLightning(distanceMeters: number): ScheduledThunder {
    const ev = planThunderEvent(this.game.time, distanceMeters);
    this.pendingThunder.push(ev);
    return ev;
  }

  /** Advances stride detection, ambient crossfading, brook attenuation, and scheduled thunder. */
  update(
    dt: number,
    playerX: number,
    playerZ: number,
    grounded: boolean,
    weather: WeatherMix,
    onStep?: (surface: SurfaceKind, x: number, z: number) => void
  ): void {
    this.stepStartupSlice();

    const surface = classifySurface(playerX, playerZ, this.zones);
    this.activeSurface = surface;

    if (this.hasLast && grounded) {
      const moved = Math.hypot(playerX - this.lastX, playerZ - this.lastZ);
      this.strideAccum += moved;
      if (this.strideAccum >= this.strideMeters) {
        this.strideAccum -= this.strideMeters;
        this.playFootstep(surface);
        onStep?.(surface, playerX, playerZ);
      }
    }
    this.lastX = playerX;
    this.lastZ = playerZ;
    this.hasLast = true;

    // Smooth exponential ambient mix (dt-invariant)
    const smooth = 1 - Math.exp(-Math.max(0, dt) * 2.8);
    const brookDist = Math.hypot(playerX - this.brookCenter.x, playerZ - this.brookCenter.z);
    const targetBrook = brookAttenuation(brookDist, 6.0) * 0.72;

    this.levels.forest += (weather.forest - this.levels.forest) * smooth;
    this.levels.wind += (weather.wind - this.levels.wind) * smooth;
    this.levels.rain += (weather.rain - this.levels.rain) * smooth;
    this.levels.brook += (targetBrook - this.levels.brook) * smooth;

    this.loops.forest?.setVolume(this.levels.forest);
    this.loops.wind?.setVolume(this.levels.wind);
    this.loops.rain?.setVolume(this.levels.rain);
    this.loops.brook?.setVolume(this.levels.brook);

    // Fire any thunder whose acoustic delay has elapsed
    for (let i = this.pendingThunder.length - 1; i >= 0; i--) {
      const ev = this.pendingThunder[i];
      if (this.game.time >= ev.triggerAt) {
        this.pendingThunder.splice(i, 1);
        const thunderCue = 'thunder_rumble';
        this.game.audio.play(thunderCue, { volume: ev.volume, pitch: ev.pitch });
        this.thundersPlayed++;
      }
    }
  }

  dispose(): void {
    this.loops.forest?.stop();
    this.loops.wind?.stop();
    this.loops.rain?.stop();
    this.loops.brook?.stop();
  }

  private playFootstep(surface: SurfaceKind): void {
    this.stepSeed = (this.stepSeed * 16807) % 2147483647;
    const jitter = (this.stepSeed / 2147483647) * 2 - 1; // [-1, 1]
    const cue = SURFACE_CUES[surface];
    const volume = surface === 'water' ? 0.82 : surface === 'wood' ? 0.75 : 0.62;
    this.game.audio.play(cue, { volume: volume + jitter * 0.06, pitch: 1 + jitter * 0.06 });
    this.footstepsPlayed++;
  }
}
```

## Performance & Platform Traps

- **iOS Safari Gesture Unlock (`touchend`):** Calling `AudioContext.resume()` only inside `touchstart` silently fails on several iOS WebKit builds; always wire `touchend` / `pointerup` to `game.audio.unlock()`.
- **Never Start All Looping Ambience Tracks in Frame 0:** Decoding four ambient loops simultaneously spikes main-thread memory and stalls mobile launch; call `stepStartupSlice()` across consecutive frames after the first render.
- **Avoid Clockwork Footsteps:** Fixed `0.45 s` timers feel robotic and keep firing during micro-slides. Accumulating horizontal stride distance (`strideMeters`) with `±6%` pitch jitter keeps steps synced to motion automatically.
- **Use Priority Overlaps for Bridges:** A footbridge crossing a creek overlaps the creek's XZ footprint; giving the `wood` zone higher `priority` than `water` guarantees planks sound like wood instead of splashing water.

## Verification Checklist

1. Assert `classifySurface` resolves `wood` over overlapping `water` zones and falls back to `dirt` outside defined patches.
2. Walk across `dirt`, `leaves`, `wood`, and `water` zones in PlayMode and assert `game.audio.plays('step_wood')` / `step_leaves` / `step_dirt` increment strictly with distance traveled.
3. Confirm brook ambience gain increases smoothly as the player approaches the creek crossing and attenuates away from it.
4. Trigger `triggerLightning(343)` and assert `thunder_rumble` fires after `~1.0 s` rather than immediately on the flash frame.

## Official references

- Web Audio API Specification (W3C)
- Andy Farnell — Designing Sound (Environmental & Weather Acoustics)
- iOS Safari Web Audio Gesture Unlock Guidelines
