/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / README.md
120 lines · 14.0 KBPreviewCodeBlameHistoryRaw
1# double pendulum
3An album of electroacoustic compositions. Each composition's sound and image are computed in the browser, in the background, from a double pendulum simulation. The same seed and settings play the same performance on every device.
5```bash
6npm install
7npm run dev # http://127.0.0.1:8031
8npm run build # static site in dist/ (relative paths, so it works under any subpath)
9```
11## Routes
13- `#/`: the track list
14- `#/<id>`: a composition with its published defaults (what visitors hear)
15- `#/<id>/edit`: author mode. Adds a panel of every parameter, readouts, "start at", and click-to-seek on the progress line.
16- `?slow=N` (before the `#`): testing only. Renders the instruments N× slower, to see how a slow device buffers.
18## Author workflow
201. Open a composition, click **edit**, and tweak while it plays. Levels and drawing settings apply immediately. Any other change recomputes the performance from the current moment (same seed), after a brief buffering pause.
212. Your edits persist in this browser (localStorage), and only in author mode.
223. **copy config** copies the full parameter set as JSON. Paste it over
23 `src/compositions/<dir>/defaults.json` and rebuild to publish it.
244. **seed** = 0 gives a new variation each play. The readouts show the seed that was used, so you can pin a variation you liked.
26## How a performance plays
28Nothing is computed on the audio thread or the page's main thread in real time. A performance is a function of piece time alone, computed ahead in background workers and played from a buffer (`src/stream/`):
30- **Score worker** (`scoreWorker.ts`, one per performance): runs the composition's *score* (`<dir>/score.ts`), which simulates the piece in piece time. It sends drawing data (rows of state, and events such as crossings) to the page, and timed note commands to the synth workers. It holds note commands back 2.5 s of piece time before releasing them, so a score can still lengthen a note it has already played (the final-note hold) once it finds, a little later, that the piece has ended. The ensemble's score renders its audio itself.
31- **Synth workers** (`synthWorker.ts`, one per instrument): render the modal-synth engine from those commands in 128-frame blocks from piece frame 0, at 48 kHz on every device. They render as fast as they can, up to whatever the score has released and the buffer the player asks for.
32- **Player worklet** (`player.ts`): owns the piece's clock. Its playhead advances only while every stem has audio for it. When any stem runs short, everything pauses: the sound fades, and the picture freezes. A spinner shows how full the buffer is. Play resumes once every stem is buffered ahead. The player measures how fast the stems are being rendered. On a device that renders slower than real time, a pause waits long enough to play through to the end; otherwise each pause doubles the wait (1, 2, 4… s), so pauses get rarer.
33- **Page** (`performance.ts`, `piece.ts`): wires the workers to the player with message ports, applies each output's effects (modal-synth's own, or one shared reverb) and live levels, and draws. Each composition's view (`<dir>/view.ts`) draws from the score's data at the player's playhead (less the output latency), so sound and picture share one clock. A seek or an edit starts a new performance at that moment. The score fast-forwards silently and computes sound from 4 s before it, so notes already ringing are heard.
35**Same on every device**: the AudioContext runs at 48 kHz, so it is the same rate the performance is computed at. Nothing depends on device speed; a slow device just buffers more. The physics uses `src/physics/dmath.ts`, ports of the fdlibm algorithms for sin, cos, exp, log and pow built from + − × ÷. Browsers' own `Math.sin` and the like differ in the last bit, and a chaotic pendulum turns that into a different performance within seconds. Scores never call `Math.random`; variations come from the seed.
37## Layout
39- `src/physics/doublePendulum.ts`: Hamiltonian double pendulum, RK4. Energy is steered to a target by a force `λ·p` (`dE/dt = 2λT`), so it rises and falls smoothly.
40- `src/stream/`: the performance system above.
41- `src/instruments/sounds.ts`: the instrument menus: every modal-synth preset from the sibling **modal-synth** project (`../modal-synth`), imported live through the `@modal-synth` alias (see `vite.config.ts` and `tsconfig.json`), as `modal: <name>`. For your own sounds, press **Copy** in modal-synth, choose `modal: custom`, and paste the JSON into **modal custom**. The JSON then becomes part of the composition's config. Building requires `../modal-synth` to be present.
42- `src/instruments/effects.ts`: effects on the page (modal-synth's, or a shared reverb).
43- `src/music/scales.ts`: scales and quantization (including continuous and harmonic series).
44- `src/core/`: params schema (settings marked `live` apply without recomputing), author panel, audio context, and the composition interface.
45- `src/compositions/`: one folder per track: `schema.ts`, `defaults.json`, `layout.ts` (stems and outputs), `score.ts` (worker), `view.ts` (drawing), `index.ts`. They are listed in `index.ts`, and their scores in `scores.ts`.
46- `src/compositions/shared/orbitWorker.ts`: the background orbit portrait (pieces 1 and 2), drawing only, run in short work slices that use about `orbitCpu` of one core.
48## 1. poincaré
50The section is θ1 = 0, crossed with dθ1/dt > 0, and plotted at (θ2, p2). Each crossing plays a note:
52- θ2 sets the pitch (signed or absolute, range, curve, scale, root)
53- |p2| sets the loudness
55After `duration`, once the pendulum has come to rest, no more crossings register: the last note is held for `finalHold` and faded over `finalFade`, the hum fades with it, and the piece ends.
57Behind the live crossings, a pool of energy-conserving orbits at the current energy keeps drawing the section's structure (islands and chaotic sea). They're reseeded as the energy moves.
59The hum is one held note of a sustained modal-synth preset (bowed, blown, self-oscillating or fed back). The energy sets a timbre value, which drives up to two synth settings (A and B), e.g. bow position and bow force. **normalize loudness** measures the hum's output and compensates slowly, so it holds a fixed pitch and loudness while only its timbre follows the energy. The energy follows an envelope: start → peak (exponential or linear rise) → hold → fall to zero at `duration`.
61Units: energy is in units of the potential energy with both arms up, and p2 is in units of √(m2·l2²·E_top).
63## 2. orbits
65Several pendulums at once (8 by default, up to 20). All follow the same energy envelope from random starts. Only the section is shown: each orbit traces its crossings in its own color (**colors**, cycling). Each orbit plays instrument slot n (cycling through 6 slots), with a register shift per slot. Orbits on the same instrument share one polyphonic instance. The note mapping, hum, and rest-based ending match composition 1. The piece ends when every orbit has come to rest and its last note has faded.
67Behind the live dots: the grey portrait of the section at the current energy, and each pendulum's *traced orbit* in its color. Each time the portrait refreshes, every pendulum's current state is followed forward with its energy frozen. That draws the orbit it is on right now: a closed loop on an island, a cloud in the chaotic sea. Traces refresh and crossfade with the portrait as the energy moves.
69Each distinct instrument renders in its own synth worker, in parallel; this is the heaviest piece, so it buffers longest on slow devices. Every device plays all the orbits.
71Shared machinery lives in `src/compositions/shared/`: the energy envelope, crossing → note mapping, hum score, section plot with its "fit energy" zoom, and the portrait/trace layer with its throttled worker.
73## 3. divergence
75Twelve pendulums (1–24) are released together from rest at a wide angle (120° by default, varied by up to 3° each play; the seed pins it). Each outer arm is offset by a tiny amount. For each release, the offset is calibrated by bisection so the outermost pendulums visibly separate (bobs 2% of the length apart) at **separate after** (8 s). The rest fan out after them as chaos takes over. Only the pendulums are drawn, from one pivot, each in its own color, with fading bob trails.
77A note sounds when a bottom bob crosses the vertical through the pivot, in either direction. Loudness follows the bob's speed, and the note is panned toward the side the bob is heading (two copies of the instrument, panned left and right). **pitch** = "chord" gives each pendulum its own note of a chord spread across the range, so the opening is one chord that breaks into arpeggios. With **two chords** (on by default), left-to-right and right-to-left crossings play two interleaved chords (2n notes spread over the range, alternating between them), so the opening swings alternate between neighbouring chords. "motion" takes the pitch from the bob's speed, so the pendulums start in unison and spread out.
79The pendulums swing freely (energy conserved) for **swinging** (40 s). Then each pendulum's energy follows (1 − u)^curve to zero over **damping** (20 s), with viscous friction settling the last of it. Each pendulum's last note rings out, and the piece ends with the fade. No hum.
81## 4. descent
83One pendulum, balanced straight up. It gets a tiny nudge, calibrated so it visibly tips at **tips after** (2.5 s); each play picks the side and shape at random.
85- **Height notes**: short piano notes (Piano-ish) mark the outer bob's height. Think of a ladder of levels: every other note of the scale between C4 (bottom) and C7 (top). Each time the height passes a level, going up or down, that level's note plays, with a small margin so hovering doesn't re-trigger it. You hear the fall as a descending run. The notes ramp in over the opening and quiet with the energy at the end.
86- **Extension notes**: whenever the pendulum is fully extended (the arms pass through a straight line, at any angle), a short violin note plays at a fixed pitch (G3), with its strength from the bob's speed. The first one is accented. The arms must bend about 3° from straight before the next extension can sound.
87- **Clicks**: when the outer bob crosses the vertical close to the pivot (within **near the pivot**, 25% of the length), a click plays (by default a 0.5 s Viola note at C5). With equal arms, a folded pendulum sweeps its bob right through the pivot.
89There's slight friction throughout. Over the damping section it grows smoothly to **final damping**, until the pendulum comes to rest. The last extension note rings out. **overlapping notes** is the most extension notes ringing at once (a new one replaces the quietest), the same on every device.
91## 5. ensemble
93Six double pendulums hung in a row, sounding directly: each one's waveform *is* the sound (the horizontal position of its outer bob, at audio rate). No instruments.
95- **Tuned by their shapes**: a double pendulum swinging gently has two natural frequencies, so each pendulum sounds two pitches. All six share one time scale, so their pitches come from their sizes and proportions. For each pendulum you choose its lower pitch (as a ratio to **base pitch**) and the interval up to its second pitch; `harmony.ts` solves the mass ratio that gives that interval (at the chosen **l2 / l1** shape), and the length that gives that pitch. The default is a D-major chord: D2+D3, A2+A3, D3+A3, F♯3+F♯4, A3+A4, D4+A4. The pendulums are drawn by size (length^**size drawing**, since true scale would make the highest a speck); the lowest is biggest.
96- **The score**: one step per word, each word the pendulums pushed together; `!` after a digit accents that push (**accent** × the energy); `.` is a rest. The default, `36 25 36 25 36 25 1!4`, alternates two chords and ends on the low pendulum, loud. **step length** is in beats at **tempo** (4 beats = a whole note, 2 s at 120 bpm). Each push adds energy along the pendulum's motion, or in a random direction from rest (the seed picks those directions, so each play mixes the two pitches differently). After the last step they ring out for **ring out**, fading over the last **fade**.
97- Pushed hard, a pendulum's pitch sags and the tone roughens: it heads into chaos.
99The six are simulated by the score itself, sample by sample, with RK4 at least 40 steps per cycle of each one's faster mode (usually one per sample). The score sends the audio straight to the player and the pendulums' positions to the page.
101## Lab: the pendulum as instrument (`#/lab/edit`, not on the album)
103An exploration tool. The double pendulum runs at audio rate inside an AudioWorklet, and its motion is the waveform: no instruments. Time is scaled so the lower small-swing mode lands at **pitch** (at low energy you hear two inharmonic partials: 2.414× apart for equal masses and lengths). **left/right signal** choose what is heard: bob positions and velocities, angles, angular velocities, momenta, and so on. A low cut removes constant offsets, and a soft limiter follows the gain. Modes:
105- **strike**: each strike *adds* **strike adds** of energy to the current motion. It's a push along the motion, like pushing a swing in time, or in a random direction from rest. The pendulum then rings down with damping (**ring time**: −60 dB). Repeated strikes (by hand or **restrike every**) build up against the damping. It starts hanging at rest.
106- **sustain**: an energy controller holds the energy, like bowing.
107- **swell**: energy rises from wherever it is to **energy** over **swell time**, then rings down.
109Low energy is nearly periodic; around 0.3–1.5 it's chaotic (broadband); high energy is regular again (rotations). Click the plot or press S to strike. The display shows the bob's path over the last few milliseconds, plus the waveform and spectrum.
111## Deploying
113The site is published from the `site/` directory of `music/double-pendulum` on vault1.magland.org, served at https://double-pendulum--music.vault1-sites.magland.org/. The build needs `../modal-synth`, so it runs locally, not in CI:
115```bash
116npm run site # build, then copy dist/ to site/
117git add -A && git commit -m "Update site" && git push
118```
120Every push to `main` republishes the site.
↑↓ move↵openescclose