# Ambience: beds, loops, scenes that change

## Contents
1. Anatomy of an ambience
2. Kernels for beds
3. One-shots for emitters
4. Loops that do not betray themselves
5. Scenes, zones and transitions
6. Realtime mixing in the browser
7. Recipes by place
8. Verifying

## 1. Anatomy

An ambience is three strata, and they are produced and shipped differently:

| Stratum | Examples | Character | Ship as |
|---|---|---|---|
| **Bed** | wind, rain wash, traffic roar, room tone, sea, machine hum | continuous, no identifiable events | kernel (endless) or seamless loop |
| **Texture events** | drips, bird calls, clinks, distant horns, creaks, footsteps | sparse, recognisable, would expose a loop | separate one-shots scattered at random times (emitters) |
| **Space** | reverb of the place, muffling by walls, distance | changes with where the listener is | zone parameters applied at mix time |

Never bake recognisable events into a loop, never bake the room into a bed that must be reused elsewhere,
and never leave digital silence — the quietest room still has `RoomTone`.

## 2. Kernels for beds

All are parametric in realtime and loopable (`opts.period`). Parameters are listed in each class's
`static params` with ranges and meaning; summary:

| Kernel (name) | Parameters | Notes |
|---|---|---|
| `Wind` (wind) | speed, gust, whistle, leaves, rumble | whistle = howling through gaps; leaves = trees; `opts.whistles: [Hz…]` |
| `Rain` (rain) | intensity, near, dropSize | `opts.surface`: any `SURFACES` key — roof, leaves, water, tent (`drumSkin`), window (`glass`) |
| `Fire` (fire) | size, crackle, hiss | candle → campfire → blaze |
| `Stream` (stream) | flow, size | bubble cloud: trickle, brook, torrent, pouring |
| `Sea` (sea) | height, period, distance | three wave trains; loop mode fits whole waves into the period |
| `Birds` (birds) | density, distance | `opts.individuals`, `fmin`, `fmax`; each bird keeps its motif |
| `Insects` (insects) | density, pitch, trill | crickets (chirps) ↔ cicadas (trill) |
| `Traffic` (traffic) | density, distance | roar bed only; add pass-bys as emitters |
| `Engine` (engine) | rpm, load, size, rough | `opts.cylinders`; idle, drive-by source, generator, boat |
| `Machine` (machine) | rate, clank, hiss, whirr, hum | cyclic: press, loom, pump; `opts.material`, `f0`, `pattern` |
| `Hum` (hum) | freq, bright, odd, wobble | mains, transformer, fridge, neon, sci-fi core |
| `Air` (air) | flow, tone, rpm, duct | vents, AC, server room, cabin |
| `Clock` (clock) | period, size, swing | tick ≠ tock; pocket watch → longcase |
| `RoomTone` (roomTone) | level, air, hum | the "silence" of interiors |
| `GrainFlow` (grains) | see `sand.md` | hail, sand, debris beds |

Combine and re-parameterize freely: a cave = `Stream` (low flow) + drips + `Wind` (rumble only); a spaceship =
`Hum` (freq 90, wobble) + `Air` + `Machine` (slow, quiet). Write a new kernel when none fits: extend `Kernel`,
declare `static params`, implement `process(L, R, n)`, call `register(name, Class)` — it immediately works
offline, in the worklet and in scenes.

## 3. One-shots for emitters

`birdCall`, `thunder`, `horn`, `siren`, `strike`/`strikes` (cups, tools, bells, doors), `crunch` (steps),
`shatter`, `speak`/`crowd` (voices), `whoosh` (gusts, passes), `spatialize(engineBuf, { path: passBy(...) })`
(vehicles), recorded samples through `enhance`. An emitter is `{ make(rng, sr) → buf, every: [minS, maxS] }`:
make it return a *different* sound every time (seeded variation of pitch, size, force, call pattern).

## 4. Loops that do not betray themselves

Three methods, by material:

| Material | Method | Why |
|---|---|---|
| Kernel beds | `loopKernel(name, opts, { seconds, xfade })` | makes the slow modulations periodic over the loop, then crossfades the remaining waveform seam: level and tone at the end equal the start |
| Any stationary recording or render | `makeLoop(buf, { seconds, xfade })` | equal-power crossfade of the tail into the head (1–3 s for noise-like beds) |
| Event-based content with tails (drips in a cave, a clock in a hall) | `tailWrap(buf, seconds)` | start events only inside the loop length, let tails overrun, fold the overrun onto the start — no crossfade, every tail completes |
| A short recording | `granulate(buf, { seconds })` | grains wrap around, texture never repeats inside the loop |

Rules of thumb: beds 15–60 s; give layers unequal, non-commensurate lengths (17 s, 23 s, 31 s) so the
combination repeats only after hours; keep loudness within about ±2–3 dB across a loop unless the pulsing *is*
the content (surf, machinery); the more featureless the bed, the shorter it may be (steady hum: 4 s is fine).
Realtime kernels need no loop at all — prefer them when the platform allows.

## 5. Scenes, zones and transitions

A **zone** is a snapshot of "how the world sounds from here": per-layer level and low-pass (how muffled each
bed is from this spot), which emitters are audible, and the room. A **timeline** moves between zones.
`renderScene(scene)` renders it offline; each zone has its own reverb bus, so a temple's tail keeps ringing
while the corridor fades in.

```js
const scene = {
  seconds: 30, seed: 7,
  layers:   { wind: { kernel: 'wind', opts: { speed: 0.55 } }, traffic: { kernel: 'traffic' },
              roomTone: { kernel: 'roomTone' }, clock: { kernel: 'clock', opts: { period: 2, size: 0.8 } } },
  emitters: { horn: { make: (r, sr) => sd.mono(sd.horn(sr, { size: r.range(0.2, 0.8) }), sr), every: [2, 5], gainDb: -14 },
              cups: { make: (r, sr) => sd.mono(sd.strike(cupModes(r), { sr, velocity: r.range(0.3, 0.9), hardness: 0.9 }), sr), every: [0.6, 2.2], gainDb: -10 } },
  zones: {
    sky:      { layers: { wind: 0, traffic: -6 }, emitters: { horn: 0 }, room: 'openField', wetDb: -20 },
    temple:   { layers: { wind: { db: -16, lp: 700 }, traffic: { db: -24, lp: 400 }, roomTone: -6 }, emitters: { horn: -26 }, room: 'temple', wetDb: -5 },
    corridor: { layers: { wind: { db: -30, lp: 300 }, roomTone: -3, clock: { db: -22, lp: 1500 } }, room: 'corridor', wetDb: -8 },
    room:     { layers: { roomTone: 0, clock: 0 }, emitters: { cups: 0 }, room: 'smallRoom', wetDb: -22 } },
  timeline: [{ t: 0, zone: 'sky' }, { t: 10, zone: 'temple', xfade: 1.2 }, { t: 18, zone: 'corridor', xfade: 1.5 }, { t: 23, zone: 'room', xfade: 1 }],
};
const mixdown = sd.master(sd.renderScene(scene), { target: -20, glue: 0 });
```
Design notes:
- **Thresholds are filters, not just fades.** Entering a building = outside beds lose highs first (`lp` 400–900 Hz)
  and 10–25 dB; the room's own tone and reverb come up. A door closing completes it in ~100 ms.
- **The next room is audible before you are in it** (the clock in the corridor at −22 dB, low-passed).
- **Reverb says size; wet level says hardness.** Temple: long `rt60`, high wet. Small furnished room: short,
  nearly dry. Open sky: a few sparse far echoes at most.
- **Crossfade time = travel time** through the threshold: fast camera 0.3–1 s, walking 1.5–3 s.
- **Contrast makes the place**: a small room reads as quiet and intimate only because the preceding space was not.
- Fast montage (camera over a city, sounds changing quickly): many short zones or automate layer params on one
  zone; keep one continuous bed (wind/air) across all cuts as glue.

## 6. Realtime mixing in the browser

`AmbienceMixer.create(ctx, scene)` builds the same scene from Web Audio nodes: kernels in worklets (or loops
from buffers), one gain + low-pass per layer, one `ConvolverNode` per zone, send gains that crossfade.
`mix.goto('temple', 1.5)` from game logic; `mix.play(timeline)` for scripted moves; `mix.layer('wind').set({ speed: 0.9 })`
to change a bed's parameters live (storm arriving). Emitters are scheduled on the audio clock with fresh
variations. Positioned emitters: route through `SpatialSource` instead of the stereo panner.
Budget: each convolver costs CPU — keep zones to those reachable; for many rooms reuse 3–4 IRs and vary wet/pre-delay.

## 7. Recipes by place (starting points — make them particular)

| Place | Bed | Emitters | Space |
|---|---|---|---|
| City street, day | traffic (density 0.6, distance 0.3), air, crowd walla | pass-bys (engine + Doppler), horns, sirens far, door, footsteps, bicycle bell | `streetCanyon`, slap echoes |
| City from above / rooftop | wind (speed 0.5, rumble), traffic (distance 0.8) | far horns, siren, helicopter, flag flap | `openField`, almost dry |
| Forest, day | wind (leaves 0.6), stream far, insects low | birds (several species), twig cracks, woodpecker | `forest` (sparse, soft) |
| Night field | insects (crickets), light wind | owl, dog far, frog | `openField` |
| Seashore | sea, wind (rumble) | gulls (`birdCall` f 1500–2500, harsh), rope/mast clinks | `openField` |
| Storm | rain (intensity 0.8), wind (gust 0.8, whistle) | thunder (distance varies), shutter bang, debris | by shelter: `sheetMetal` roof, `glass` window |
| Factory floor | machine ×2 at unrelated rates, hum, air (duct) | clanks, pneumatic bursts, forklift beeper, shouts (`mumble` + `pa`) | `warehouse` |
| Office / home | roomTone, air (low), hum (fridge) | clock, cups, keyboard ticks, chair creak, fabric | `livingRoom` / `smallRoom` |
| Temple / cathedral | roomTone (level 0.3), outside beds heavily low-passed | footsteps, a bell, cloth, a cough far away | `temple` / `cathedral`, wet −6 dB |
| Cave | stream (flow 0.1), wind (rumble only) | drips (`tailWrap` loop or emitters), stones | `cave` |
| Spaceship / lab | hum (freq 80–120, wobble), air | beeps, relay clicks, door hiss | `corridor`, short and metallic |

## 8. Verifying

- Each loop: `loopcheck.mjs` (and `--preview` for a human).
- Bed character: `--lens texture` — `levelStdDb` 1–3 dB is alive; 0 is a machine; > 5 dB is an event, not a bed.
- Scene: `TIME` map of the mixdown should show each zone as a distinct spectral picture with soft boundaries at
  the transition times; `EVENTS` should show emitters only where their zone is active; the clock's
  `repeats every` must equal its period.
- Mix balance: integrated loudness per zone (analyze slices) — interiors typically 6–15 LU below exteriors.
- Realtime graph: `renderOffline(seconds, (ctx) => AmbienceMixer.create(ctx, scene).then(...))` and compare with
  `renderScene` output: same zones, same balance.
