/ music / double-pendulum
Sign in
music / double-pendulum
double pendulum: album app with composition 1 (poincaré)
Live double-pendulum simulation with a Poincaré section; crossings play notes (modal-synth instruments), a modal-synth hum follows the energy. Author mode at #/<id>/edit; built site in site/. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Jeremy Magland <jmagland@flatironinstitute.org> committed commit 73fe08aed057 Browse files
37 changed files+3862−0
.gitignoreadded+5−0View file
@@ -0,0 +1,5 @@
1+node_modules
2+dist
3+.DS_Store
4+renders
5+.claude
README.mdadded+60−0View file
@@ -0,0 +1,60 @@
1+# double pendulum
2+
3+An album of electroacoustic compositions. Each composition's sound and image are computed live in the browser from a double pendulum simulation.
4+
5+```bash
6+npm install
7+npm run dev # http://127.0.0.1:8031
8+npm run build # static site in dist/ (relative paths, so it works under any subpath)
9+```
10+
11+## Routes
12+
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+
17+## Author workflow
18+
19+1. Open a composition, click **edit**, and tweak while it plays. Most changes are heard immediately. Instrument choice and the seed apply on the next play.
20+2. Your edits persist in this browser (localStorage), and only in author mode.
21+3. **copy config** copies the full parameter set as JSON. Paste it over
22+ `src/compositions/<dir>/defaults.json` and rebuild to publish it.
23+4. **seed** = 0 gives a new variation each play. The readouts show the seed that was used, so you can pin a variation you liked.
24+
25+## Layout
26+
27+- `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.
28+- `src/instruments/`: instrument interfaces (`NoteInstrument`, `DroneInstrument`), placeholders, and the registry. Add real instruments here and they appear in the composition's instrument menus.
29+- `src/instruments/modal.ts`: instruments from the sibling **modal-synth** project (`../modal-synth`), imported live through the `@modal-synth` alias (see `vite.config.ts` and `tsconfig.json`). Every built-in modal-synth preset appears 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.
30+- `src/music/scales.ts`: scales and quantization (including continuous and harmonic series).
31+- `src/core/`: params schema, author panel, audio context, and the composition interface.
32+- `src/compositions/`: one folder per track (`schema.ts`, `defaults.json`, `piece.ts`), listed in `index.ts`.
33+- `src/compositions/c01-poincare/orbitWorker.ts`: background orbit portrait, run in short work slices that use about `orbitCpu` of one core.
34+
35+## 1. poincaré
36+
37+The section is θ1 = 0, crossed with dθ1/dt > 0, and plotted at (θ2, p2). Each crossing plays a note:
38+
39+- θ2 sets the pitch (signed or absolute, range, curve, scale, root)
40+- |p2| sets the loudness
41+- θ2 sets the pan
42+
43+Notes stop at `duration − finalAt`. The last note is then held for `finalHold` and faded over `finalFade`, all within `tail`.
44+
45+Behind 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.
46+
47+The 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`.
48+
49+Units: energy is in units of the potential energy with both arms up, and p2 is in units of √(m2·l2²·E_top).
50+
51+## Deploying
52+
53+The 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:
54+
55+```bash
56+npm run site # build, then copy dist/ to site/
57+git add -A && git commit -m "Update site" && git push
58+```
59+
60+Every push to `main` republishes the site.
index.htmladded+12−0View file
@@ -0,0 +1,12 @@
1+<!doctype html>
2+<html lang="en">
3+ <head>
4+ <meta charset="UTF-8" />
5+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+ <title>double pendulum</title>
7+ </head>
8+ <body>
9+ <div id="app"></div>
10+ <script type="module" src="/src/main.ts"></script>
11+ </body>
12+</html>
package-lock.jsonadded+1257−0View file
@@ -0,0 +1,1257 @@
1+{
2+ "name": "double-pendulum",
3+ "lockfileVersion": 3,
4+ "requires": true,
5+ "packages": {
6+ "": {
7+ "name": "double-pendulum",
8+ "devDependencies": {
9+ "@types/node": "^26.6.11",
10+ "typescript": "^7.0.2",
11+ "vite": "^8.4.1"
12+ }
13+ },
14+ "node_modules/@oxc-project/types": {
15+ "version": "0.160.0",
16+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.160.0.tgz",
17+ "integrity": "sha512-gw4k9syEmnckbOgw2A2FU1TBDdX9hfwV9jEn/uio65pguPzwWiXQS3OIJDMEhv9m06tj9XiEe6RoD0YA+LgreA==",
18+ "dev": true,
19+ "license": "MIT",
20+ "funding": {
21+ "url": "https://github.com/sponsors/oxc-project"
22+ }
23+ },
24+ "node_modules/@rolldown/binding-android-arm-eabi": {
25+ "version": "1.3.4",
26+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.3.4.tgz",
27+ "integrity": "sha512-xCW8CkL/ualx/SbYqeG9iK87lJCZGDQ0soE+kaORJ0Bd+pHALyE4qK7BStmEAyYWLEzZ3/biSIpA6/7GDFvzIg==",
28+ "cpu": [
29+ "arm"
30+ ],
31+ "dev": true,
32+ "license": "MIT",
33+ "optional": true,
34+ "os": [
35+ "android"
36+ ],
37+ "engines": {
38+ "node": "^20.19.0 || >=22.12.0"
39+ }
40+ },
41+ "node_modules/@rolldown/binding-android-arm64": {
42+ "version": "1.3.4",
43+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.3.4.tgz",
44+ "integrity": "sha512-5lifIO+b/prcM9sx/bkPN4w6UEToEfQ3gjhx0+0neuL+dkYskI792CfAq03T51jc8JFcaYXs2hi3l8RjiH/VWQ==",
45+ "cpu": [
46+ "arm64"
47+ ],
48+ "dev": true,
49+ "license": "MIT",
50+ "optional": true,
51+ "os": [
52+ "android"
53+ ],
54+ "engines": {
55+ "node": "^20.19.0 || >=22.12.0"
56+ }
57+ },
58+ "node_modules/@rolldown/binding-darwin-arm64": {
59+ "version": "1.3.4",
60+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.3.4.tgz",
61+ "integrity": "sha512-RCgxTI4AJQxhVF//BI3ImQOsXTHrF4Eg+f99jBy8WoETA2kSEGFxpnrVmW0leQq/2aBR4R5AC6csmy3rc66e3Q==",
62+ "cpu": [
63+ "arm64"
64+ ],
65+ "dev": true,
66+ "license": "MIT",
67+ "optional": true,
68+ "os": [
69+ "darwin"
70+ ],
71+ "engines": {
72+ "node": "^20.19.0 || >=22.12.0"
73+ }
74+ },
75+ "node_modules/@rolldown/binding-darwin-x64": {
76+ "version": "1.3.4",
77+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.3.4.tgz",
78+ "integrity": "sha512-zNPJVVPUaDEj+L0lImoK3rFv2b+Z5gNijI6DWu/fcD3/1TfmRXKb9ZyxbSN+2AhlctqjbNzUvCsMa+EBhnEM4Q==",
79+ "cpu": [
80+ "x64"
81+ ],
82+ "dev": true,
83+ "license": "MIT",
84+ "optional": true,
85+ "os": [
86+ "darwin"
87+ ],
88+ "engines": {
89+ "node": "^20.19.0 || >=22.12.0"
90+ }
91+ },
92+ "node_modules/@rolldown/binding-freebsd-x64": {
93+ "version": "1.3.4",
94+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.3.4.tgz",
95+ "integrity": "sha512-upP6g7ZIRy5by1RDQ/EphHIdJ5xK0eUD7sUgfZFWJ49s4XdbYsIvIlAPtrFpayR70Hhf9J22lb4Pm8/9FhrZmg==",
96+ "cpu": [
97+ "x64"
98+ ],
99+ "dev": true,
100+ "license": "MIT",
101+ "optional": true,
102+ "os": [
103+ "freebsd"
104+ ],
105+ "engines": {
106+ "node": "^20.19.0 || >=22.12.0"
107+ }
108+ },
109+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
110+ "version": "1.3.4",
111+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.3.4.tgz",
112+ "integrity": "sha512-SAX5C5+poMLCxu8dkPF6h5yst40rkzs+9Y3cbPn2OFSydmHjAEprrGi64zGgnYyPIVZfdGUFqJ2fJbfbnHI+mA==",
113+ "cpu": [
114+ "arm"
115+ ],
116+ "dev": true,
117+ "license": "MIT",
118+ "optional": true,
119+ "os": [
120+ "linux"
121+ ],
122+ "engines": {
123+ "node": "^20.19.0 || >=22.12.0"
124+ }
125+ },
126+ "node_modules/@rolldown/binding-linux-arm64-gnu": {
127+ "version": "1.3.4",
128+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.3.4.tgz",
129+ "integrity": "sha512-nwHqdlRZS6GWBef3dG5/pMY6RNTBBUjj7s0Da+m6xsFpe7jx6IC46SLZcCu8f46JOfCovZmwnrz51EzGE+7Fyw==",
130+ "cpu": [
131+ "arm64"
132+ ],
133+ "dev": true,
134+ "libc": [
135+ "glibc"
136+ ],
137+ "license": "MIT",
138+ "optional": true,
139+ "os": [
140+ "linux"
141+ ],
142+ "engines": {
143+ "node": "^20.19.0 || >=22.12.0"
144+ }
145+ },
146+ "node_modules/@rolldown/binding-linux-arm64-musl": {
147+ "version": "1.3.4",
148+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.3.4.tgz",
149+ "integrity": "sha512-Gr78X2ur/AgLCkmZgHffk/FerIX8S5zb/eII4bCcvJo0ANzeXhTShahdNbpnY6bpiszIAgIfiuKS9ziziWsamw==",
150+ "cpu": [
151+ "arm64"
152+ ],
153+ "dev": true,
154+ "libc": [
155+ "musl"
156+ ],
157+ "license": "MIT",
158+ "optional": true,
159+ "os": [
160+ "linux"
161+ ],
162+ "engines": {
163+ "node": "^20.19.0 || >=22.12.0"
164+ }
165+ },
166+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {
167+ "version": "1.3.4",
168+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.3.4.tgz",
169+ "integrity": "sha512-o9Wcn8nWrsQasaBRYM4d//FwhlBsTJYWkPVlhlt6FwzpwEoovY4IopRZjk5Fq3+ntRuSDORJjF/nA8sFeF2q6w==",
170+ "cpu": [
171+ "ppc64"
172+ ],
173+ "dev": true,
174+ "libc": [
175+ "glibc"
176+ ],
177+ "license": "MIT",
178+ "optional": true,
179+ "os": [
180+ "linux"
181+ ],
182+ "engines": {
183+ "node": "^20.19.0 || >=22.12.0"
184+ }
185+ },
186+ "node_modules/@rolldown/binding-linux-s390x-gnu": {
187+ "version": "1.3.4",
188+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.3.4.tgz",
189+ "integrity": "sha512-UDWu4jkVcx2kiBKm3Ec//4lVCbeTWj8gmJ9SyLWCdLWtTlyq7fQVeVV/14nXvRtSLErvJ2+yA/Ux5taS31Y17Q==",
190+ "cpu": [
191+ "s390x"
192+ ],
193+ "dev": true,
194+ "libc": [
195+ "glibc"
196+ ],
197+ "license": "MIT",
198+ "optional": true,
199+ "os": [
200+ "linux"
201+ ],
202+ "engines": {
203+ "node": "^20.19.0 || >=22.12.0"
204+ }
205+ },
206+ "node_modules/@rolldown/binding-linux-x64-gnu": {
207+ "version": "1.3.4",
208+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.3.4.tgz",
209+ "integrity": "sha512-W9mGtTa0w4fWh8RLMNPyaEhhcuqUfO07Q4I1bBc4PDMNg7gQSw0yPQNQ3D0qwbkXwxbyL4YrIzc8n6k1vuFExQ==",
210+ "cpu": [
211+ "x64"
212+ ],
213+ "dev": true,
214+ "libc": [
215+ "glibc"
216+ ],
217+ "license": "MIT",
218+ "optional": true,
219+ "os": [
220+ "linux"
221+ ],
222+ "engines": {
223+ "node": "^20.19.0 || >=22.12.0"
224+ }
225+ },
226+ "node_modules/@rolldown/binding-linux-x64-musl": {
227+ "version": "1.3.4",
228+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.3.4.tgz",
229+ "integrity": "sha512-8B+ofyQZ7/aCmkqnyMonPr5zKLqMVNczhRGFNtdIuItiwNn8iQWJawMq2E58r7bxD1XEbtRRsULY/eCWwZQ01Q==",
230+ "cpu": [
231+ "x64"
232+ ],
233+ "dev": true,
234+ "libc": [
235+ "musl"
236+ ],
237+ "license": "MIT",
238+ "optional": true,
239+ "os": [
240+ "linux"
241+ ],
242+ "engines": {
243+ "node": "^20.19.0 || >=22.12.0"
244+ }
245+ },
246+ "node_modules/@rolldown/binding-openharmony-arm64": {
247+ "version": "1.3.4",
248+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.3.4.tgz",
249+ "integrity": "sha512-TlD0FSZaC7o2B4NCe9V5N11ugTnhzTM9ksj4sgRLvrKosDzjEkvlsTX3ehkw4ZlPv8AADimZZTvJGEa16pfXug==",
250+ "cpu": [
251+ "arm64"
252+ ],
253+ "dev": true,
254+ "license": "MIT",
255+ "optional": true,
256+ "os": [
257+ "openharmony"
258+ ],
259+ "engines": {
260+ "node": "^20.19.0 || >=22.12.0"
261+ }
262+ },
263+ "node_modules/@rolldown/binding-wasm32-wasi": {
264+ "version": "1.3.4",
265+ "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.3.4.tgz",
266+ "integrity": "sha512-jwO8P3o53ygo7b5061B7BeaJ1BGv3BKZ6jroFdw/01qWry7Z+qNBlDvulzbTle5s/A0Fc1FRgsTxrke9DvsSbA==",
267+ "cpu": [
268+ "wasm32"
269+ ],
270+ "dev": true,
271+ "license": "MIT",
272+ "optional": true,
273+ "dependencies": {
274+ "@oxc-project/types": "0.160.0"
275+ },
276+ "engines": {
277+ "node": "^20.19.0 || ^22.13.0 || >=23.5.0"
278+ }
279+ },
280+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
281+ "version": "1.3.4",
282+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.3.4.tgz",
283+ "integrity": "sha512-8adGMrNtrdzi2WD1ozhYapER59gD8Q/DV6SCKJlyG2HqULPdeQUBvMa33lTsiEYwIqTZUaIU2MmvPp5f1wbtXA==",
284+ "cpu": [
285+ "arm64"
286+ ],
287+ "dev": true,
288+ "license": "MIT",
289+ "optional": true,
290+ "os": [
291+ "win32"
292+ ],
293+ "engines": {
294+ "node": "^20.19.0 || >=22.12.0"
295+ }
296+ },
297+ "node_modules/@rolldown/binding-win32-x64-msvc": {
298+ "version": "1.3.4",
299+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.3.4.tgz",
300+ "integrity": "sha512-rIMjtESdXJCIoOiUTroQ1Y1rjVDZkuUVRUxs3APX2vNv175D7TDWvzdELiIhzGq9cUNUFat+co+PTmPHPqSREg==",
301+ "cpu": [
302+ "x64"
303+ ],
304+ "dev": true,
305+ "license": "MIT",
306+ "optional": true,
307+ "os": [
308+ "win32"
309+ ],
310+ "engines": {
311+ "node": "^20.19.0 || >=22.12.0"
312+ }
313+ },
314+ "node_modules/@rolldown/pluginutils": {
315+ "version": "1.1.1",
316+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz",
317+ "integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==",
318+ "dev": true,
319+ "license": "MIT"
320+ },
321+ "node_modules/@types/node": {
322+ "version": "26.6.11",
323+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.11.tgz",
324+ "integrity": "sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==",
325+ "dev": true,
326+ "license": "MIT",
327+ "dependencies": {
328+ "undici-types": "~8.9.0"
329+ }
330+ },
331+ "node_modules/@typescript/typescript-aix-ppc64": {
332+ "version": "7.0.2",
333+ "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
334+ "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
335+ "cpu": [
336+ "ppc64"
337+ ],
338+ "dev": true,
339+ "license": "Apache-2.0",
340+ "optional": true,
341+ "os": [
342+ "aix"
343+ ],
344+ "engines": {
345+ "node": ">=16.20.0"
346+ }
347+ },
348+ "node_modules/@typescript/typescript-darwin-arm64": {
349+ "version": "7.0.2",
350+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
351+ "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
352+ "cpu": [
353+ "arm64"
354+ ],
355+ "dev": true,
356+ "license": "Apache-2.0",
357+ "optional": true,
358+ "os": [
359+ "darwin"
360+ ],
361+ "engines": {
362+ "node": ">=16.20.0"
363+ }
364+ },
365+ "node_modules/@typescript/typescript-darwin-x64": {
366+ "version": "7.0.2",
367+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
368+ "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
369+ "cpu": [
370+ "x64"
371+ ],
372+ "dev": true,
373+ "license": "Apache-2.0",
374+ "optional": true,
375+ "os": [
376+ "darwin"
377+ ],
378+ "engines": {
379+ "node": ">=16.20.0"
380+ }
381+ },
382+ "node_modules/@typescript/typescript-freebsd-arm64": {
383+ "version": "7.0.2",
384+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
385+ "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
386+ "cpu": [
387+ "arm64"
388+ ],
389+ "dev": true,
390+ "license": "Apache-2.0",
391+ "optional": true,
392+ "os": [
393+ "freebsd"
394+ ],
395+ "engines": {
396+ "node": ">=16.20.0"
397+ }
398+ },
399+ "node_modules/@typescript/typescript-freebsd-x64": {
400+ "version": "7.0.2",
401+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
402+ "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
403+ "cpu": [
404+ "x64"
405+ ],
406+ "dev": true,
407+ "license": "Apache-2.0",
408+ "optional": true,
409+ "os": [
410+ "freebsd"
411+ ],
412+ "engines": {
413+ "node": ">=16.20.0"
414+ }
415+ },
416+ "node_modules/@typescript/typescript-linux-arm": {
417+ "version": "7.0.2",
418+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
419+ "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
420+ "cpu": [
421+ "arm"
422+ ],
423+ "dev": true,
424+ "license": "Apache-2.0",
425+ "optional": true,
426+ "os": [
427+ "linux"
428+ ],
429+ "engines": {
430+ "node": ">=16.20.0"
431+ }
432+ },
433+ "node_modules/@typescript/typescript-linux-arm64": {
434+ "version": "7.0.2",
435+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
436+ "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
437+ "cpu": [
438+ "arm64"
439+ ],
440+ "dev": true,
441+ "license": "Apache-2.0",
442+ "optional": true,
443+ "os": [
444+ "linux"
445+ ],
446+ "engines": {
447+ "node": ">=16.20.0"
448+ }
449+ },
450+ "node_modules/@typescript/typescript-linux-loong64": {
451+ "version": "7.0.2",
452+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
453+ "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
454+ "cpu": [
455+ "loong64"
456+ ],
457+ "dev": true,
458+ "license": "Apache-2.0",
459+ "optional": true,
460+ "os": [
461+ "linux"
462+ ],
463+ "engines": {
464+ "node": ">=16.20.0"
465+ }
466+ },
467+ "node_modules/@typescript/typescript-linux-mips64el": {
468+ "version": "7.0.2",
469+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
470+ "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
471+ "cpu": [
472+ "mips64el"
473+ ],
474+ "dev": true,
475+ "license": "Apache-2.0",
476+ "optional": true,
477+ "os": [
478+ "linux"
479+ ],
480+ "engines": {
481+ "node": ">=16.20.0"
482+ }
483+ },
484+ "node_modules/@typescript/typescript-linux-ppc64": {
485+ "version": "7.0.2",
486+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
487+ "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
488+ "cpu": [
489+ "ppc64"
490+ ],
491+ "dev": true,
492+ "license": "Apache-2.0",
493+ "optional": true,
494+ "os": [
495+ "linux"
496+ ],
497+ "engines": {
498+ "node": ">=16.20.0"
499+ }
500+ },
501+ "node_modules/@typescript/typescript-linux-riscv64": {
502+ "version": "7.0.2",
503+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
504+ "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
505+ "cpu": [
506+ "riscv64"
507+ ],
508+ "dev": true,
509+ "license": "Apache-2.0",
510+ "optional": true,
511+ "os": [
512+ "linux"
513+ ],
514+ "engines": {
515+ "node": ">=16.20.0"
516+ }
517+ },
518+ "node_modules/@typescript/typescript-linux-s390x": {
519+ "version": "7.0.2",
520+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
521+ "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
522+ "cpu": [
523+ "s390x"
524+ ],
525+ "dev": true,
526+ "license": "Apache-2.0",
527+ "optional": true,
528+ "os": [
529+ "linux"
530+ ],
531+ "engines": {
532+ "node": ">=16.20.0"
533+ }
534+ },
535+ "node_modules/@typescript/typescript-linux-x64": {
536+ "version": "7.0.2",
537+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
538+ "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
539+ "cpu": [
540+ "x64"
541+ ],
542+ "dev": true,
543+ "license": "Apache-2.0",
544+ "optional": true,
545+ "os": [
546+ "linux"
547+ ],
548+ "engines": {
549+ "node": ">=16.20.0"
550+ }
551+ },
552+ "node_modules/@typescript/typescript-netbsd-arm64": {
553+ "version": "7.0.2",
554+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
555+ "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
556+ "cpu": [
557+ "arm64"
558+ ],
559+ "dev": true,
560+ "license": "Apache-2.0",
561+ "optional": true,
562+ "os": [
563+ "netbsd"
564+ ],
565+ "engines": {
566+ "node": ">=16.20.0"
567+ }
568+ },
569+ "node_modules/@typescript/typescript-netbsd-x64": {
570+ "version": "7.0.2",
571+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
572+ "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
573+ "cpu": [
574+ "x64"
575+ ],
576+ "dev": true,
577+ "license": "Apache-2.0",
578+ "optional": true,
579+ "os": [
580+ "netbsd"
581+ ],
582+ "engines": {
583+ "node": ">=16.20.0"
584+ }
585+ },
586+ "node_modules/@typescript/typescript-openbsd-arm64": {
587+ "version": "7.0.2",
588+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
589+ "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
590+ "cpu": [
591+ "arm64"
592+ ],
593+ "dev": true,
594+ "license": "Apache-2.0",
595+ "optional": true,
596+ "os": [
597+ "openbsd"
598+ ],
599+ "engines": {
600+ "node": ">=16.20.0"
601+ }
602+ },
603+ "node_modules/@typescript/typescript-openbsd-x64": {
604+ "version": "7.0.2",
605+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
606+ "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
607+ "cpu": [
608+ "x64"
609+ ],
610+ "dev": true,
611+ "license": "Apache-2.0",
612+ "optional": true,
613+ "os": [
614+ "openbsd"
615+ ],
616+ "engines": {
617+ "node": ">=16.20.0"
618+ }
619+ },
620+ "node_modules/@typescript/typescript-sunos-x64": {
621+ "version": "7.0.2",
622+ "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
623+ "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
624+ "cpu": [
625+ "x64"
626+ ],
627+ "dev": true,
628+ "license": "Apache-2.0",
629+ "optional": true,
630+ "os": [
631+ "sunos"
632+ ],
633+ "engines": {
634+ "node": ">=16.20.0"
635+ }
636+ },
637+ "node_modules/@typescript/typescript-win32-arm64": {
638+ "version": "7.0.2",
639+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
640+ "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
641+ "cpu": [
642+ "arm64"
643+ ],
644+ "dev": true,
645+ "license": "Apache-2.0",
646+ "optional": true,
647+ "os": [
648+ "win32"
649+ ],
650+ "engines": {
651+ "node": ">=16.20.0"
652+ }
653+ },
654+ "node_modules/@typescript/typescript-win32-x64": {
655+ "version": "7.0.2",
656+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
657+ "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
658+ "cpu": [
659+ "x64"
660+ ],
661+ "dev": true,
662+ "license": "Apache-2.0",
663+ "optional": true,
664+ "os": [
665+ "win32"
666+ ],
667+ "engines": {
668+ "node": ">=16.20.0"
669+ }
670+ },
671+ "node_modules/detect-libc": {
672+ "version": "2.1.2",
673+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
674+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
675+ "dev": true,
676+ "license": "Apache-2.0",
677+ "engines": {
678+ "node": ">=8"
679+ }
680+ },
681+ "node_modules/fdir": {
682+ "version": "6.5.0",
683+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
684+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
685+ "dev": true,
686+ "license": "MIT",
687+ "engines": {
688+ "node": ">=12.0.0"
689+ },
690+ "peerDependencies": {
691+ "picomatch": "^3 || ^4"
692+ },
693+ "peerDependenciesMeta": {
694+ "picomatch": {
695+ "optional": true
696+ }
697+ }
698+ },
699+ "node_modules/fsevents": {
700+ "version": "2.3.3",
701+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
702+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
703+ "dev": true,
704+ "hasInstallScript": true,
705+ "license": "MIT",
706+ "optional": true,
707+ "os": [
708+ "darwin"
709+ ],
710+ "engines": {
711+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
712+ }
713+ },
714+ "node_modules/lightningcss": {
715+ "version": "1.33.0",
716+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
717+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
718+ "dev": true,
719+ "license": "MPL-2.0",
720+ "dependencies": {
721+ "detect-libc": "^2.0.3"
722+ },
723+ "engines": {
724+ "node": ">= 12.0.0"
725+ },
726+ "funding": {
727+ "type": "opencollective",
728+ "url": "https://opencollective.com/parcel"
729+ },
730+ "optionalDependencies": {
731+ "lightningcss-android-arm64": "1.33.0",
732+ "lightningcss-darwin-arm64": "1.33.0",
733+ "lightningcss-darwin-x64": "1.33.0",
734+ "lightningcss-freebsd-x64": "1.33.0",
735+ "lightningcss-linux-arm-gnueabihf": "1.33.0",
736+ "lightningcss-linux-arm64-gnu": "1.33.0",
737+ "lightningcss-linux-arm64-musl": "1.33.0",
738+ "lightningcss-linux-x64-gnu": "1.33.0",
739+ "lightningcss-linux-x64-musl": "1.33.0",
740+ "lightningcss-win32-arm64-msvc": "1.33.0",
741+ "lightningcss-win32-x64-msvc": "1.33.0"
742+ }
743+ },
744+ "node_modules/lightningcss-android-arm64": {
745+ "version": "1.33.0",
746+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",
747+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",
748+ "cpu": [
749+ "arm64"
750+ ],
751+ "dev": true,
752+ "license": "MPL-2.0",
753+ "optional": true,
754+ "os": [
755+ "android"
756+ ],
757+ "engines": {
758+ "node": ">= 12.0.0"
759+ },
760+ "funding": {
761+ "type": "opencollective",
762+ "url": "https://opencollective.com/parcel"
763+ }
764+ },
765+ "node_modules/lightningcss-darwin-arm64": {
766+ "version": "1.33.0",
767+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",
768+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",
769+ "cpu": [
770+ "arm64"
771+ ],
772+ "dev": true,
773+ "license": "MPL-2.0",
774+ "optional": true,
775+ "os": [
776+ "darwin"
777+ ],
778+ "engines": {
779+ "node": ">= 12.0.0"
780+ },
781+ "funding": {
782+ "type": "opencollective",
783+ "url": "https://opencollective.com/parcel"
784+ }
785+ },
786+ "node_modules/lightningcss-darwin-x64": {
787+ "version": "1.33.0",
788+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",
789+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",
790+ "cpu": [
791+ "x64"
792+ ],
793+ "dev": true,
794+ "license": "MPL-2.0",
795+ "optional": true,
796+ "os": [
797+ "darwin"
798+ ],
799+ "engines": {
800+ "node": ">= 12.0.0"
801+ },
802+ "funding": {
803+ "type": "opencollective",
804+ "url": "https://opencollective.com/parcel"
805+ }
806+ },
807+ "node_modules/lightningcss-freebsd-x64": {
808+ "version": "1.33.0",
809+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",
810+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",
811+ "cpu": [
812+ "x64"
813+ ],
814+ "dev": true,
815+ "license": "MPL-2.0",
816+ "optional": true,
817+ "os": [
818+ "freebsd"
819+ ],
820+ "engines": {
821+ "node": ">= 12.0.0"
822+ },
823+ "funding": {
824+ "type": "opencollective",
825+ "url": "https://opencollective.com/parcel"
826+ }
827+ },
828+ "node_modules/lightningcss-linux-arm-gnueabihf": {
829+ "version": "1.33.0",
830+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",
831+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",
832+ "cpu": [
833+ "arm"
834+ ],
835+ "dev": true,
836+ "license": "MPL-2.0",
837+ "optional": true,
838+ "os": [
839+ "linux"
840+ ],
841+ "engines": {
842+ "node": ">= 12.0.0"
843+ },
844+ "funding": {
845+ "type": "opencollective",
846+ "url": "https://opencollective.com/parcel"
847+ }
848+ },
849+ "node_modules/lightningcss-linux-arm64-gnu": {
850+ "version": "1.33.0",
851+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",
852+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",
853+ "cpu": [
854+ "arm64"
855+ ],
856+ "dev": true,
857+ "libc": [
858+ "glibc"
859+ ],
860+ "license": "MPL-2.0",
861+ "optional": true,
862+ "os": [
863+ "linux"
864+ ],
865+ "engines": {
866+ "node": ">= 12.0.0"
867+ },
868+ "funding": {
869+ "type": "opencollective",
870+ "url": "https://opencollective.com/parcel"
871+ }
872+ },
873+ "node_modules/lightningcss-linux-arm64-musl": {
874+ "version": "1.33.0",
875+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",
876+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",
877+ "cpu": [
878+ "arm64"
879+ ],
880+ "dev": true,
881+ "libc": [
882+ "musl"
883+ ],
884+ "license": "MPL-2.0",
885+ "optional": true,
886+ "os": [
887+ "linux"
888+ ],
889+ "engines": {
890+ "node": ">= 12.0.0"
891+ },
892+ "funding": {
893+ "type": "opencollective",
894+ "url": "https://opencollective.com/parcel"
895+ }
896+ },
897+ "node_modules/lightningcss-linux-x64-gnu": {
898+ "version": "1.33.0",
899+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
900+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
901+ "cpu": [
902+ "x64"
903+ ],
904+ "dev": true,
905+ "libc": [
906+ "glibc"
907+ ],
908+ "license": "MPL-2.0",
909+ "optional": true,
910+ "os": [
911+ "linux"
912+ ],
913+ "engines": {
914+ "node": ">= 12.0.0"
915+ },
916+ "funding": {
917+ "type": "opencollective",
918+ "url": "https://opencollective.com/parcel"
919+ }
920+ },
921+ "node_modules/lightningcss-linux-x64-musl": {
922+ "version": "1.33.0",
923+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",
924+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",
925+ "cpu": [
926+ "x64"
927+ ],
928+ "dev": true,
929+ "libc": [
930+ "musl"
931+ ],
932+ "license": "MPL-2.0",
933+ "optional": true,
934+ "os": [
935+ "linux"
936+ ],
937+ "engines": {
938+ "node": ">= 12.0.0"
939+ },
940+ "funding": {
941+ "type": "opencollective",
942+ "url": "https://opencollective.com/parcel"
943+ }
944+ },
945+ "node_modules/lightningcss-win32-arm64-msvc": {
946+ "version": "1.33.0",
947+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",
948+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",
949+ "cpu": [
950+ "arm64"
951+ ],
952+ "dev": true,
953+ "license": "MPL-2.0",
954+ "optional": true,
955+ "os": [
956+ "win32"
957+ ],
958+ "engines": {
959+ "node": ">= 12.0.0"
960+ },
961+ "funding": {
962+ "type": "opencollective",
963+ "url": "https://opencollective.com/parcel"
964+ }
965+ },
966+ "node_modules/lightningcss-win32-x64-msvc": {
967+ "version": "1.33.0",
968+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",
969+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",
970+ "cpu": [
971+ "x64"
972+ ],
973+ "dev": true,
974+ "license": "MPL-2.0",
975+ "optional": true,
976+ "os": [
977+ "win32"
978+ ],
979+ "engines": {
980+ "node": ">= 12.0.0"
981+ },
982+ "funding": {
983+ "type": "opencollective",
984+ "url": "https://opencollective.com/parcel"
985+ }
986+ },
987+ "node_modules/nanoid": {
988+ "version": "3.3.20",
989+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
990+ "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
991+ "dev": true,
992+ "funding": [
993+ {
994+ "type": "github",
995+ "url": "https://github.com/sponsors/ai"
996+ }
997+ ],
998+ "license": "MIT",
999+ "bin": {
1000+ "nanoid": "bin/nanoid.cjs"
1001+ },
1002+ "engines": {
1003+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
1004+ }
1005+ },
1006+ "node_modules/napi-windows-process-start-time": {
1007+ "version": "0.1.0",
1008+ "resolved": "https://registry.npmjs.org/napi-windows-process-start-time/-/napi-windows-process-start-time-0.1.0.tgz",
1009+ "integrity": "sha512-zHxhzKsIFu3elch3eFw69WEUGc79DFhbc3nD/WEOzWL/pFFLZRW13EHnuO0c+0YjncE5uCaS9ICHxOBXkb6vPw==",
1010+ "cpu": [
1011+ "x64",
1012+ "arm64"
1013+ ],
1014+ "dev": true,
1015+ "license": "MIT",
1016+ "optional": true,
1017+ "os": [
1018+ "win32"
1019+ ],
1020+ "engines": {
1021+ "node": ">=20"
1022+ }
1023+ },
1024+ "node_modules/picocolors": {
1025+ "version": "1.1.1",
1026+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
1027+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
1028+ "dev": true,
1029+ "license": "ISC"
1030+ },
1031+ "node_modules/picomatch": {
1032+ "version": "4.0.7",
1033+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
1034+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
1035+ "dev": true,
1036+ "license": "MIT",
1037+ "engines": {
1038+ "node": ">=12"
1039+ },
1040+ "funding": {
1041+ "url": "https://github.com/sponsors/jonschlinkert"
1042+ }
1043+ },
1044+ "node_modules/postcss": {
1045+ "version": "8.5.34",
1046+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.34.tgz",
1047+ "integrity": "sha512-P1Qzj0XXZjMda74C7qiVnBG90UKNbyNUAOeQRBW8X63RsIMV57gevRqjnkELdwtZ/S2/uQFksJhmwuN8xShLPw==",
1048+ "dev": true,
1049+ "funding": [
1050+ {
1051+ "type": "opencollective",
1052+ "url": "https://opencollective.com/postcss/"
1053+ },
1054+ {
1055+ "type": "tidelift",
1056+ "url": "https://tidelift.com/funding/github/npm/postcss"
1057+ },
1058+ {
1059+ "type": "github",
1060+ "url": "https://github.com/sponsors/ai"
1061+ }
1062+ ],
1063+ "license": "MIT",
1064+ "dependencies": {
1065+ "nanoid": "^3.3.20",
1066+ "picocolors": "^1.1.1",
1067+ "source-map-js": "^1.2.4"
1068+ },
1069+ "engines": {
1070+ "node": "^10 || ^12 || >=14"
1071+ }
1072+ },
1073+ "node_modules/rolldown": {
1074+ "version": "1.3.4",
1075+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.3.4.tgz",
1076+ "integrity": "sha512-p2rq4bfBmF0M6yaR8+A89fbkBQynZI2fxUW4G07eq9kpctAkpo7q5BZ4X4Mo4XZ7HHROu33cX9PeopUFN6u+2Q==",
1077+ "dev": true,
1078+ "license": "MIT",
1079+ "dependencies": {
1080+ "@oxc-project/types": "=0.160.0",
1081+ "@rolldown/pluginutils": "^1.0.0"
1082+ },
1083+ "bin": {
1084+ "rolldown": "bin/cli.mjs"
1085+ },
1086+ "engines": {
1087+ "node": "^20.19.0 || >=22.12.0"
1088+ },
1089+ "optionalDependencies": {
1090+ "@rolldown/binding-android-arm-eabi": "1.3.4",
1091+ "@rolldown/binding-android-arm64": "1.3.4",
1092+ "@rolldown/binding-darwin-arm64": "1.3.4",
1093+ "@rolldown/binding-darwin-x64": "1.3.4",
1094+ "@rolldown/binding-freebsd-x64": "1.3.4",
1095+ "@rolldown/binding-linux-arm-gnueabihf": "1.3.4",
1096+ "@rolldown/binding-linux-arm64-gnu": "1.3.4",
1097+ "@rolldown/binding-linux-arm64-musl": "1.3.4",
1098+ "@rolldown/binding-linux-ppc64-gnu": "1.3.4",
1099+ "@rolldown/binding-linux-s390x-gnu": "1.3.4",
1100+ "@rolldown/binding-linux-x64-gnu": "1.3.4",
1101+ "@rolldown/binding-linux-x64-musl": "1.3.4",
1102+ "@rolldown/binding-openharmony-arm64": "1.3.4",
1103+ "@rolldown/binding-wasm32-wasi": "1.3.4",
1104+ "@rolldown/binding-win32-arm64-msvc": "1.3.4",
1105+ "@rolldown/binding-win32-x64-msvc": "1.3.4"
1106+ }
1107+ },
1108+ "node_modules/source-map-js": {
1109+ "version": "1.3.0",
1110+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.3.0.tgz",
1111+ "integrity": "sha512-pdUVfIWcK0kCgK831ibqkZDcL7I9zljjOu0TQFnA+fiQ6y1CYqYB7RkTOHHO45FGMg5P/Mvk/+4ToQ7gAYAL5Q==",
1112+ "dev": true,
1113+ "license": "BSD-3-Clause",
1114+ "engines": {
1115+ "node": ">=6.0.0"
1116+ }
1117+ },
1118+ "node_modules/tinyglobby": {
1119+ "version": "0.2.17",
1120+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
1121+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
1122+ "dev": true,
1123+ "license": "MIT",
1124+ "dependencies": {
1125+ "fdir": "^6.5.0",
1126+ "picomatch": "^4.0.4"
1127+ },
1128+ "engines": {
1129+ "node": ">=12.0.0"
1130+ },
1131+ "funding": {
1132+ "url": "https://github.com/sponsors/SuperchupuDev"
1133+ }
1134+ },
1135+ "node_modules/typescript": {
1136+ "version": "7.0.2",
1137+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
1138+ "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
1139+ "dev": true,
1140+ "license": "Apache-2.0",
1141+ "bin": {
1142+ "tsc": "bin/tsc"
1143+ },
1144+ "engines": {
1145+ "node": ">=16.20.0"
1146+ },
1147+ "optionalDependencies": {
1148+ "@typescript/typescript-aix-ppc64": "7.0.2",
1149+ "@typescript/typescript-darwin-arm64": "7.0.2",
1150+ "@typescript/typescript-darwin-x64": "7.0.2",
1151+ "@typescript/typescript-freebsd-arm64": "7.0.2",
1152+ "@typescript/typescript-freebsd-x64": "7.0.2",
1153+ "@typescript/typescript-linux-arm": "7.0.2",
1154+ "@typescript/typescript-linux-arm64": "7.0.2",
1155+ "@typescript/typescript-linux-loong64": "7.0.2",
1156+ "@typescript/typescript-linux-mips64el": "7.0.2",
1157+ "@typescript/typescript-linux-ppc64": "7.0.2",
1158+ "@typescript/typescript-linux-riscv64": "7.0.2",
1159+ "@typescript/typescript-linux-s390x": "7.0.2",
1160+ "@typescript/typescript-linux-x64": "7.0.2",
1161+ "@typescript/typescript-netbsd-arm64": "7.0.2",
1162+ "@typescript/typescript-netbsd-x64": "7.0.2",
1163+ "@typescript/typescript-openbsd-arm64": "7.0.2",
1164+ "@typescript/typescript-openbsd-x64": "7.0.2",
1165+ "@typescript/typescript-sunos-x64": "7.0.2",
1166+ "@typescript/typescript-win32-arm64": "7.0.2",
1167+ "@typescript/typescript-win32-x64": "7.0.2"
1168+ }
1169+ },
1170+ "node_modules/undici-types": {
1171+ "version": "8.9.0",
1172+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
1173+ "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
1174+ "dev": true,
1175+ "license": "MIT"
1176+ },
1177+ "node_modules/vite": {
1178+ "version": "8.4.1",
1179+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.4.1.tgz",
1180+ "integrity": "sha512-2bl8n3+GkKBKQQR8CZC+t+3NvjWCBNh9S0Dbfu7hr7+Jjeg71jcZk7uKF6mo8GZXjIws+Nl6jhvAfHUO320VuQ==",
1181+ "dev": true,
1182+ "license": "MIT",
1183+ "dependencies": {
1184+ "lightningcss": "^1.33.0",
1185+ "picomatch": "^4.0.7",
1186+ "postcss": "^8.5.34",
1187+ "rolldown": "~1.3.4",
1188+ "tinyglobby": "^0.2.17"
1189+ },
1190+ "bin": {
1191+ "vite": "bin/vite.js"
1192+ },
1193+ "engines": {
1194+ "node": "^20.19.0 || >=22.12.0"
1195+ },
1196+ "funding": {
1197+ "url": "https://github.com/vitejs/vite?sponsor=1"
1198+ },
1199+ "optionalDependencies": {
1200+ "fsevents": "~2.3.3",
1201+ "napi-windows-process-start-time": "^0.1.0"
1202+ },
1203+ "peerDependencies": {
1204+ "@types/node": "^20.19.0 || >=22.12.0",
1205+ "@vitejs/devtools": "^0.7.1 || ^0.8.0",
1206+ "esbuild": "^0.27.0 || ^0.28.0",
1207+ "jiti": ">=1.21.0",
1208+ "less": "^4.0.0",
1209+ "sass": "^1.70.0",
1210+ "sass-embedded": "^1.70.0",
1211+ "stylus": ">=0.54.8",
1212+ "sugarss": "^5.0.0",
1213+ "terser": "^5.16.0",
1214+ "tsx": "^4.8.1",
1215+ "yaml": "^2.4.2"
1216+ },
1217+ "peerDependenciesMeta": {
1218+ "@types/node": {
1219+ "optional": true
1220+ },
1221+ "@vitejs/devtools": {
1222+ "optional": true
1223+ },
1224+ "esbuild": {
1225+ "optional": true
1226+ },
1227+ "jiti": {
1228+ "optional": true
1229+ },
1230+ "less": {
1231+ "optional": true
1232+ },
1233+ "sass": {
1234+ "optional": true
1235+ },
1236+ "sass-embedded": {
1237+ "optional": true
1238+ },
1239+ "stylus": {
1240+ "optional": true
1241+ },
1242+ "sugarss": {
1243+ "optional": true
1244+ },
1245+ "terser": {
1246+ "optional": true
1247+ },
1248+ "tsx": {
1249+ "optional": true
1250+ },
1251+ "yaml": {
1252+ "optional": true
1253+ }
1254+ }
1255+ }
1256+ }
1257+}
package.jsonadded+18−0View file
@@ -0,0 +1,18 @@
1+{
2+ "name": "double-pendulum",
3+ "private": true,
4+ "type": "module",
5+ "description": "double pendulum: an album of electroacoustic compositions computed live from a double pendulum simulation",
6+ "scripts": {
7+ "dev": "vite --port 8031 --host 127.0.0.1",
8+ "build": "tsc --noEmit && vite build",
9+ "preview": "vite preview --port 8032 --host 127.0.0.1",
10+ "typecheck": "tsc --noEmit",
11+ "site": "npm run build && rm -rf site && cp -R dist site"
12+ },
13+ "devDependencies": {
14+ "@types/node": "^26.6.11",
15+ "typescript": "^7.0.2",
16+ "vite": "^8.4.1"
17+ }
18+}
scripts/check-physics.tsadded+54−0View file
@@ -0,0 +1,54 @@
1+// Sanity checks for the pendulum model: energy conservation, controller tracking,
2+// and typical Poincaré crossing rates / p2 ranges at several energies.
3+import { DoublePendulum, wrapAngle } from "../src/physics/doublePendulum.ts";
4+
5+const cfg = { m1: 1, m2: 1, l1: 1, l2: 1, g: 1 };
6+const dt = 0.002;
7+
8+for (const e of [0.005, 0.05, 0.2, 0.5, 1, 2]) {
9+ const P = new DoublePendulum(cfg);
10+ let s = 1;
11+ P.randomize(e, () => ((s = (s * 16807) % 2147483647) / 2147483647));
12+ P.tau = 1e9;
13+ P.eTarget = P.energy();
14+ const E0 = P.energy();
15+ let prev = wrapAngle(P.y[0]);
16+ let n = 0, pmax = 0, sumAbs = 0;
17+ const Tsim = 400;
18+ for (let i = 0; i < Tsim / dt; i++) {
19+ P.step(dt);
20+ const cur = wrapAngle(P.y[0]);
21+ if (prev < 0 && cur >= 0 && cur - prev < Math.PI) {
22+ n++;
23+ const p2n = Math.abs(P.y[3]) / P.p2Scale;
24+ pmax = Math.max(pmax, p2n);
25+ sumAbs += p2n;
26+ }
27+ prev = cur;
28+ }
29+ console.log(`e=${e}: drift ${((P.energy() - E0) / E0).toExponential(1)}, crossings/simsec ${(n / Tsim).toFixed(3)}, |p2n| mean ${(sumAbs / Math.max(n, 1)).toFixed(3)} max ${pmax.toFixed(3)}`);
30+}
31+
32+// controller tracking
33+const P = new DoublePendulum(cfg);
34+P.randomize(0.005, Math.random);
35+P.tau = 2;
36+for (const target of [0.5, 1.2, 0.1, 0]) {
37+ P.eTarget = target * P.vTop;
38+ for (let i = 0; i < 40 / dt; i++) P.step(dt);
39+ console.log(`target ${target} -> after 40 sim s: ${P.energyNorm().toFixed(4)}`);
40+}
41+
42+// on-section seeding lands at the requested energy, moving upward through θ1 = 0
43+import { seedOnSection } from "../src/physics/doublePendulum.ts";
44+for (const e of [0.01, 0.3, 1.2]) {
45+ const Q = new DoublePendulum({ m1: 1, m2: 2, l1: 1, l2: 0.7, g: 1 });
46+ let ok = 0, maxErr = 0;
47+ for (let i = 0; i < 200; i++) {
48+ if (!seedOnSection(Q, e, Math.random)) continue;
49+ ok++;
50+ maxErr = Math.max(maxErr, Math.abs(Q.energyNorm() - e) / e);
51+ if (Q.derived().w1 <= 0) throw new Error("w1 <= 0");
52+ }
53+ console.log(`seedOnSection e=${e}: ${ok}/200 seeded, max rel energy err ${maxErr.toExponential(1)}`);
54+}
scripts/note-activity.tsadded+49−0View file
@@ -0,0 +1,49 @@
1+// Simulates composition 1 with its defaults (no audio) and prints note activity per window:
2+// how many crossings, their loudness (velocity before level) and pitch spread.
3+// node scripts/note-activity.ts [seed]
4+import { readFileSync } from "node:fs";
5+import { DoublePendulum, wrapAngle } from "../src/physics/doublePendulum.ts";
6+import { energyTarget } from "../src/compositions/c01-poincare/form.ts";
7+import { NOTE_NAMES, quantize } from "../src/music/scales.ts";
8+import { mulberry32 } from "../src/core/rng.ts";
9+
10+const P = JSON.parse(readFileSync(new URL("../src/compositions/c01-poincare/defaults.json", import.meta.url), "utf8"));
11+const seed = Number(process.argv[2] ?? 1);
12+const DT = 0.002, WIN = 4;
13+const pend = new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio, l2: P.lengthRatio });
14+pend.randomize(energyTarget(P, 0), mulberry32(seed));
15+pend.tau = P.tau;
16+let t = 0, prev = wrapAngle(pend.y[0]);
17+let restAt: number | null = null, lastNote = -1, lastVel = 0;
18+const wins: { n: number; vel: number[]; pitch: Set<number>; e: number }[] = [];
19+while (restAt === null) {
20+ const y0 = [...pend.y];
21+ pend.eTarget = energyTarget(P, t) * pend.vTop;
22+ pend.step(DT);
23+ t += DT / P.speed;
24+ const cur = wrapAngle(pend.y[0]);
25+ const w = (wins[Math.floor(t / WIN)] ??= { n: 0, vel: [], pitch: new Set(), e: 0 });
26+ w.e = pend.energyNorm();
27+ if (prev < 0 && cur >= 0 && cur - prev < Math.PI) {
28+ const f = -prev / (cur - prev);
29+ const th2 = wrapAngle(y0[1] + f * (pend.y[1] - y0[1]));
30+ const p2 = (y0[3] + f * (pend.y[3] - y0[3])) / pend.p2Scale;
31+ let u = Math.max(0, Math.min(1, 0.5 + (0.5 * th2) / P.thetaRange));
32+ const midi = quantize(P.pitchLow + (P.pitchHigh - P.pitchLow) * Math.pow(u, P.pitchCurve), P.scale, NOTE_NAMES.indexOf(P.root));
33+ const x = Math.min(1, Math.abs(p2) / P.p2Ref);
34+ w.n++;
35+ w.vel.push(P.loudFloor + (1 - P.loudFloor) * Math.pow(x, P.loudCurve));
36+ w.pitch.add(midi);
37+ lastNote = t;
38+ lastVel = w.vel[w.vel.length - 1];
39+ }
40+ if (t >= P.duration && (pend.energyNorm() < P.restEnergy || t >= P.duration + 10)) restAt = t;
41+ prev = cur;
42+}
43+console.log(`at rest ${restAt!.toFixed(2)} s; last note ${lastNote.toFixed(2)} s (velocity ${lastVel.toFixed(3)}); fades out by ${(restAt! + P.finalHold + P.finalFade + 0.3).toFixed(1)} s`);
44+console.log(`seed ${seed} speed ${P.speed} p2Ref ${P.p2Ref} loudFloor ${P.loudFloor}`);
45+wins.forEach((w, i) => {
46+ const v = w.vel.length ? w.vel.reduce((a, b) => a + b) / w.vel.length : 0;
47+ const db = v > 0 ? (20 * Math.log10(v)).toFixed(0) : "-inf";
48+ console.log(`${String(i * WIN).padStart(3)}–${String((i + 1) * WIN).padEnd(3)}s energy ${w.e.toFixed(4)} notes ${String(w.n).padStart(3)} mean vel ${v.toFixed(3)} (${db} dB) distinct pitches ${w.pitch.size}`);
49+});
scripts/render-hum.tsadded+159−0View file
@@ -0,0 +1,159 @@
1+// Offline audition of hum candidates (modal-synth engine in Node, no browser).
2+// Each candidate holds one note while its timbre sweeps 0 → 1 (as the energy would),
3+// with the same slow loudness normalization the app uses. Prints brightness/stability
4+// per stage and, with --wav, writes renders/hum-<name>.wav.
5+// node scripts/render-hum.ts [--wav] [--pitch 38] [--only name]
6+import fs from "node:fs";
7+import { Synth } from "../../modal-synth/src/engine/synth.ts";
8+import { DEFAULTS, PARAM_BY_ID, type Params } from "../../modal-synth/src/engine/params.ts";
9+import { PRESETS } from "../../modal-synth/src/presets.ts";
10+
11+const args = process.argv.slice(2);
12+const opt = (k: string, d: string) => (args.includes(`--${k}`) ? args[args.indexOf(`--${k}`) + 1] : d);
13+const WAV = args.includes("--wav");
14+const PITCH = Number(opt("pitch", "38"));
15+const ONLY = opt("only", "");
16+const SR = 48000, BLOCK = 128;
17+const preset = (n: string) => PRESETS.find((p) => p.name === n)!.p;
18+
19+interface Map { target: string; from: number; to: number } // actual values, not fractions
20+interface Cand { name: string; p: Params; map: Map[] }
21+
22+export const CANDIDATES: Cand[] = [
23+ { name: "clarinet", p: preset("Clarinet-ish"), map: [{ target: "pickup", from: 0.25, to: 0.75 }, { target: "tilt", from: 0, to: 4 }] },
24+ { name: "bass-bowed", p: { ...preset("Double bass"), vibDepth: 0 }, map: [{ target: "exPos", from: 0.2, to: 0.07 }, { target: "bowForce", from: 0.5, to: 1.4 }] },
25+ { name: "cello-bowed", p: { ...preset("Cello"), vibDepth: 0 }, map: [{ target: "exPos", from: 0.2, to: 0.07 }, { target: "bowForce", from: 0.5, to: 1.4 }] },
26+ { name: "bowl", p: preset("Singing bowl"), map: [{ target: "selfGain", from: 0.1, to: 0.6 }, { target: "pickup", from: 0.15, to: 0.4 }] },
27+ // van der Pol on a string: weak self-excitation is nearly sinusoidal, strong becomes a rich relaxation oscillation
28+ {
29+ name: "string-vdp",
30+ p: { geometry: "string", modes: 32, t60: 6, hfDamp: 2, damper: 6, exciter: "selfosc", selfGain: 0.3, selfSat: 0.5, exPos: 0.12, exWidth: 0.05, attack: 400, release: 1500, pickup: 0.3, spread: 0.3, width: 0.4, tilt: -3, reverbMix: 0.3, reverbSize: 4 },
31+ map: [{ target: "selfGain", from: 0.1, to: 1.2 }, { target: "tilt", from: -4, to: 0 }],
32+ },
33+ {
34+ name: "tube-vdp",
35+ p: { geometry: "tube_oo", modes: 24, t60: 4, hfDamp: 3, damper: 6, exciter: "selfosc", selfGain: 0.3, selfSat: 0.5, exPos: 0.02, exWidth: 0.02, attack: 400, release: 1500, pickup: 0.5, spread: 0.3, width: 0.4, tilt: -3, reverbMix: 0.3, reverbSize: 4 },
36+ map: [{ target: "selfGain", from: 0.1, to: 1.2 }, { target: "tilt", from: -4, to: 0 }],
37+ },
38+ {
39+ name: "dark-reed",
40+ p: { ...preset("Clarinet-ish"), breath: 0.01, pickup: 0.15 },
41+ map: [{ target: "pickup", from: 0.15, to: 0.5 }, { target: "tilt", from: -4, to: 1 }],
42+ },
43+ {
44+ name: "warm-reed",
45+ p: { ...preset("Clarinet-ish"), breath: 0.01, pickup: 0.15, reverbMix: 0.3, reverbSize: 4 },
46+ map: [{ target: "pickup", from: 0.15, to: 0.6 }, { target: "tilt", from: -4, to: -1 }],
47+ },
48+ {
49+ name: "mellow-reed",
50+ p: { ...preset("Clarinet-ish"), breath: 0.01, pickup: 0.15, reverbMix: 0.3, reverbSize: 4 },
51+ map: [{ target: "pickup", from: 0.15, to: 0.75 }, { target: "tilt", from: -4, to: 2 }],
52+ },
53+ {
54+ name: "tube-co-vdp",
55+ p: { geometry: "tube_co", modes: 24, t60: 4, hfDamp: 3, damper: 6, exciter: "selfosc", selfGain: 0.3, selfSat: 0.5, exPos: 0, exWidth: 0.01, attack: 400, release: 1500, pickup: 0.2, spread: 0.3, width: 0.4, tilt: -4, reverbMix: 0.3, reverbSize: 4 },
56+ map: [{ target: "selfGain", from: 0.15, to: 1.5 }, { target: "pickup", from: 0.15, to: 0.5 }],
57+ },
58+ {
59+ name: "bass-tasto",
60+ p: { ...preset("Double bass"), vibDepth: 0, tilt: -6 },
61+ map: [{ target: "exPos", from: 0.3, to: 0.12 }, { target: "tilt", from: -7, to: -3 }],
62+ },
63+];
64+
65+const STAGES = 5, STAGE_S = 3, LEAD_S = 2.5;
66+
67+function fftMag(x: Float64Array): Float64Array {
68+ const n = x.length, re = Float64Array.from(x), im = new Float64Array(n);
69+ for (let i = 1, j = 0; i < n; i++) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) [re[i], re[j]] = [re[j], re[i]]; }
70+ for (let len = 2; len <= n; len <<= 1) {
71+ const a = (-2 * Math.PI) / len;
72+ for (let i = 0; i < n; i += len) for (let k = 0; k < len / 2; k++) {
73+ const c = Math.cos(a * k), s = Math.sin(a * k), h = len / 2;
74+ const vr = re[i + k + h] * c - im[i + k + h] * s, vi = re[i + k + h] * s + im[i + k + h] * c;
75+ re[i + k + h] = re[i + k] - vr; im[i + k + h] = im[i + k] - vi; re[i + k] += vr; im[i + k] += vi;
76+ }
77+ }
78+ const m = new Float64Array(n / 2);
79+ for (let i = 0; i < n / 2; i++) m[i] = Math.hypot(re[i], im[i]);
80+ return m;
81+}
82+
83+/** brightness (centroid, × f0), share of energy within ±3% of harmonics, and fundamental's share */
84+function analyze(sig: Float32Array, start: number, f0: number) {
85+ const n = 32768, x = new Float64Array(n);
86+ for (let i = 0; i < n; i++) x[i] = (sig[start + i] ?? 0) * (0.5 - 0.5 * Math.cos((2 * Math.PI * i) / n));
87+ const m = fftMag(x), df = SR / n;
88+ let num = 0, den = 0, harm = 0, fund = 0;
89+ for (let i = 1; i < m.length && i * df < 8000; i++) {
90+ const f = i * df, p = m[i] * m[i];
91+ num += p * f; den += p;
92+ const k = Math.round(f / f0);
93+ if (k >= 1 && Math.abs(f - k * f0) < 0.03 * k * f0 + 2 * df) { harm += p; if (k === 1) fund += p; }
94+ }
95+ return { cent: num / den / f0, harm: harm / den, fund: fund / den };
96+}
97+
98+function render(c: Cand) {
99+ const synth = new Synth(SR);
100+ const base: Params = { ...DEFAULTS, ...c.p, voices: 1 };
101+ synth.message({ type: "params", params: base });
102+ const f0 = 440 * Math.pow(2, (PITCH - 69) / 12);
103+ synth.message({ type: "noteOn", note: PITCH, vel: 1 });
104+ const total = Math.round((LEAD_S + STAGES * STAGE_S) * SR);
105+ const L = new Float32Array(total), R = new Float32Array(total);
106+ let msq = 0.09, lastParam = -1;
107+ const outL = new Float32Array(BLOCK), outR = new Float32Array(BLOCK);
108+ const rawL = new Float32Array(total);
109+ let comp = 1;
110+ for (let i = 0; i < total; i += BLOCK) {
111+ const t = i / SR;
112+ // color: 0 during lead-in, then stepped stages 0, .25, .5, .75, 1
113+ const stage = t < LEAD_S ? 0 : Math.min(STAGES - 1, Math.floor((t - LEAD_S) / STAGE_S));
114+ const color = stage / (STAGES - 1);
115+ if (stage !== lastParam) {
116+ lastParam = stage;
117+ const next: Params = { ...base };
118+ for (const m of c.map) next[m.target] = m.from + (m.to - m.from) * color;
119+ synth.message({ type: "params", params: next });
120+ }
121+ outL.fill(0); outR.fill(0);
122+ synth.process(outL, outR, BLOCK, t);
123+ let s = 0;
124+ for (let j = 0; j < BLOCK; j++) s += outL[j] * outL[j];
125+ s /= BLOCK;
126+ if (s > 1e-12) msq += (s - msq) * (1 - Math.exp(-BLOCK / SR / 1.5));
127+ comp = Math.max(1 / 20, Math.min(20, 0.3 / Math.sqrt(msq)));
128+ for (let j = 0; j < BLOCK && i + j < total; j++) { rawL[i + j] = outL[j]; L[i + j] = outL[j] * comp; R[i + j] = outR[j] * comp; }
129+ }
130+ const rows: string[] = [];
131+ for (let s = 0; s < STAGES; s++) {
132+ const start = Math.round((LEAD_S + s * STAGE_S + STAGE_S - 0.75) * SR);
133+ const a = analyze(rawL, start, f0);
134+ let e = 0; for (let j = 0; j < 9600; j++) e += rawL[start + j] ** 2;
135+ rows.push(`${(s / (STAGES - 1)).toFixed(2)}: ${(10 * Math.log10(e / 9600 + 1e-20)).toFixed(0)}dB bright ${a.cent.toFixed(2)}× harmonic ${(a.harm * 100).toFixed(0)}% fund ${(a.fund * 100).toFixed(0)}%`);
136+ }
137+ console.log(`\n${c.name} @ midi ${PITCH} (${f0.toFixed(1)} Hz) ${c.map.map((m) => `${m.target} ${m.from}→${m.to}`).join(", ")}`);
138+ for (const r of rows) console.log(" " + r);
139+ if (WAV) {
140+ fs.mkdirSync("renders", { recursive: true });
141+ const n = L.length, buf = Buffer.alloc(44 + n * 4);
142+ buf.write("RIFF", 0); buf.writeUInt32LE(36 + n * 4, 4); buf.write("WAVE", 8); buf.write("fmt ", 12);
143+ buf.writeUInt32LE(16, 16); buf.writeUInt16LE(1, 20); buf.writeUInt16LE(2, 22); buf.writeUInt32LE(SR, 24);
144+ buf.writeUInt32LE(SR * 4, 28); buf.writeUInt16LE(4, 32); buf.writeUInt16LE(16, 34); buf.write("data", 36); buf.writeUInt32LE(n * 4, 40);
145+ let peak = 1e-9; for (let i = 0; i < n; i++) peak = Math.max(peak, Math.abs(L[i]), Math.abs(R[i]));
146+ const g = 0.5 / peak;
147+ for (let i = 0; i < n; i++) {
148+ const fade = Math.min(1, i / (0.3 * SR), (n - i) / (0.5 * SR));
149+ buf.writeInt16LE(Math.round(Math.max(-1, Math.min(1, L[i] * g * fade)) * 32767), 44 + i * 4);
150+ buf.writeInt16LE(Math.round(Math.max(-1, Math.min(1, R[i] * g * fade)) * 32767), 46 + i * 4);
151+ }
152+ fs.writeFileSync(`renders/hum-${c.name}-${PITCH}.wav`, buf);
153+ }
154+}
155+
156+for (const c of CANDIDATES) if (!ONLY || c.name === ONLY) {
157+ for (const m of c.map) if (!PARAM_BY_ID[m.target]) throw new Error(`unknown target ${m.target}`);
158+ render(c);
159+}
scripts/write-defaults.tsadded+9−0View file
@@ -0,0 +1,9 @@
1+// Writes a composition's defaults.json from its schema defaults (only for bootstrapping a new composition).
2+// usage: node scripts/write-defaults.ts c01-poincare
3+import { writeFileSync } from "node:fs";
4+const dir = process.argv[2];
5+const { schema } = await import(`../src/compositions/${dir}/schema.ts`);
6+const { schemaDefaults, serializeParams } = await import("../src/core/params.ts");
7+const path = new URL(`../src/compositions/${dir}/defaults.json`, import.meta.url);
8+writeFileSync(path, serializeParams(schema, schemaDefaults(schema)));
9+console.log("wrote", path.pathname);
site/assets/index-DFpYSV6v.jsadded+2−0View file
@@ -0,0 +1,2 @@
1+(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e=null;async function t(){if(!e){let t=new AudioContext({latencyHint:`playback`}),n=t.createGain(),r=t.createDynamicsCompressor();r.threshold.value=-6,r.knee.value=6,r.ratio.value=12,r.attack.value=.003,r.release.value=.25,n.connect(r).connect(t.destination),e={ctx:t,input:n}}return e.ctx.state!==`running`&&await e.ctx.resume(),e}function n(e){return 10**(e/20)}function r(e){let t={};for(let n of e)t[n.key]=n.default;return t}function i(e,...t){let n=r(e);for(let r of t)if(r)for(let t of e){let e=r[t.key];e!==void 0&&(t.kind===`number`&&typeof e==`number`&&Number.isFinite(e)||t.kind===`select`&&typeof e==`string`&&t.options.includes(e)||t.kind===`bool`&&typeof e==`boolean`||t.kind===`text`&&typeof e==`string`)&&(n[t.key]=e)}return n}function a(e,t){let n={};for(let r of e)n[r.key]=t[r.key];return JSON.stringify(n,null,2)+`
2+`}var o=1e3;function s(e,t){let n=e.log?Math.log(t/e.min)/Math.log(e.max/e.min):(t-e.min)/(e.max-e.min);return Math.round(Math.max(0,Math.min(1,n))*o)}function c(e,t){let n=t/o,r=e.log?e.min*(e.max/e.min)**+n:e.min+n*(e.max-e.min);return e.step&&(r=Math.round(r/e.step)*e.step),Number(r.toPrecision(4))}function l(e){return String(Number(e.toPrecision(4)))}function u(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n),r}function d(e){let t=u(`aside`,{className:`author`}),n=[],r=(t,n)=>{e.set({...e.get(),[t]:n})},d=u(`span`,{className:`status`}),f=e=>{d.textContent=e,window.setTimeout(()=>{d.textContent===e&&(d.textContent=``)},2e3)},p=u(`button`,{textContent:`copy config`});p.onclick=async()=>{let t=a(e.schema,e.get());try{await navigator.clipboard.writeText(t),f(`copied`)}catch{window.prompt(`copy:`,t)}};let m=u(`button`,{textContent:`paste config`});m.onclick=async()=>{let t=null;try{t=await navigator.clipboard.readText()}catch{t=window.prompt(`paste config JSON:`)}if(t)try{e.set(i(e.schema,JSON.parse(t))),y(),f(`pasted`)}catch{f(`not valid JSON`)}};let h=u(`button`,{textContent:`reset to defaults`});h.onclick=()=>{window.confirm(`Discard your edits and return to the published defaults?`)&&(e.set(e.defaults()),y())},t.append(u(`div`,{className:`actions`},p,m,h,d));let g=u(`input`,{type:`number`,min:`0`,step:`1`,value:String(e.startAt.value)});g.oninput=()=>{e.startAt.value=Math.max(0,Number(g.value)||0)},t.append(u(`label`,{className:`row`},u(`span`,{textContent:`start at (s)`}),g));let _=u(`dl`,{className:`readouts`});t.append(_);let v=new Map;for(let i of e.schema){let a=v.get(i.group);a||(a=u(`fieldset`,{},u(`legend`,{textContent:i.group})),v.set(i.group,a),t.append(a));let d=u(`label`,{className:`row`},u(`span`,{textContent:i.label,title:i.hint??``}));if(i.kind===`number`){let t=u(`input`,{type:`range`,min:`0`,max:String(o),step:`1`}),a=u(`input`,{type:`number`,step:`any`}),f=u(`span`,{className:`unit`,textContent:i.unit??``});t.oninput=()=>{let e=c(i,Number(t.value));a.value=l(e),r(i.key,e)},a.onchange=()=>{let e=Number(a.value);Number.isFinite(e)&&(t.value=String(s(i,e)),r(i.key,e))},n.push(()=>{let n=e.get()[i.key];t.value=String(s(i,n)),a.value=l(n)}),d.append(t,a,f)}else if(i.kind===`select`){let t=u(`select`);for(let e of i.options)t.append(u(`option`,{value:e,textContent:e}));t.onchange=()=>r(i.key,t.value),n.push(()=>t.value=e.get()[i.key]),d.append(t)}else if(i.kind===`text`){let t=u(`textarea`,{rows:3,spellcheck:!1,placeholder:i.hint??``});t.onchange=()=>r(i.key,t.value),n.push(()=>t.value=e.get()[i.key]),d.classList.add(`text`),d.append(t)}else{let t=u(`input`,{type:`checkbox`});t.onchange=()=>r(i.key,t.checked),n.push(()=>t.checked=e.get()[i.key]),d.append(t)}a.append(d)}function y(){for(let e of n)e()}function b(){let t=e.readouts();_.replaceChildren(...Object.entries(t).flatMap(([e,t])=>[u(`dt`,{textContent:e}),u(`dd`,{textContent:t})]))}return y(),b(),{el:t,sync:y,updateReadouts:b}}var f={duration:60,peakTime:25,holdTime:10,energyStart:.005,energyPeak:.4,riseShape:`exponential`,riseCurve:1,fallCurve:1,restEnergy:.001,finalHold:2,finalFade:5,speed:50,massRatio:1,lengthRatio:1,tau:2,seed:0,noteInstrument:`modal: Nylon harp`,modalCustom:``,scale:`dorian`,root:`D`,pitchSource:`signed`,thetaRange:3.1416,pitchLow:50,pitchHigh:86,pitchCurve:1,invertPitch:!1,p2Ref:1,loudCurve:1,loudFloor:.08,notesLevel:-6,noteLength:1.5,panAmount:.6,humInstrument:`modal: Clarinet-ish`,humCustom:``,humPitch:38,humLevel:-24,humFollow:0,humNormalize:!0,humColorMode:`log`,humColorCurve:1,humTarget1:`pickup`,humFrom1:.15,humTo1:.75,humTarget2:`tilt`,humFrom2:.3333,humTo2:.5833,humFadeIn:3,humFadeOut:6,pendulumAlpha:1,pendulumSize:.32,motionBlur:1,fade:10,plotZoom:`fit energy`,zoomSmooth:1.5,plotP:1.5,pointSize:2,orbits:!0,orbitCount:24,orbitCpu:.4,orbitLife:300,orbitBand:.25,orbitMinHold:3,orbitMaxPoints:8e3,orbitXfade:1.5,orbitAlpha:.3,orbitSize:1};function p(e){let t=e>>>0;return()=>{t=t+0x6d2b79f5>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function m(){return 1+Math.floor(Math.random()*999999)}var h=(e,t)=>e[t],g=e=>e.geometry===`membrane`||e.geometry===`plate`||e.geometry===`disc`,_=(...e)=>t=>e.includes(t.geometry),v=(...e)=>t=>e.includes(t.exciter),y=[`bow`,`reed`,`selfosc`,`noise`],b=[[`off`,`Off`],[`pitch`,`Pitch`],[`amp`,`Amplitude`],[`position`,`Excite position`],[`pickup`,`Pickup position`],[`tension`,`Tension coupling`],[`cascade`,`Cascade coupling`],[`damping`,`Damping`],[`feedback`,`Feedback gain`],[`exciter`,`Exciter intensity`]],x=[[`sine`,`Sine`],[`tri`,`Triangle`],[`saw`,`Saw`],[`square`,`Square`],[`sh`,`Sample & hold`],[`smooth`,`Smooth random`]];function S(e){let t=t=>t[`lfo${e}Target`]!==`off`;return[{kind:`enum`,id:`lfo${e}Target`,label:`LFO ${e} →`,group:`Modulation`,options:b,def:`off`},{kind:`enum`,id:`lfo${e}Shape`,label:`Shape`,group:`Modulation`,options:x,def:`sine`,show:t},{kind:`num`,id:`lfo${e}Rate`,label:`Rate`,group:`Modulation`,min:.01,max:40,def:1,scale:`log`,unit:`Hz`,show:t},{kind:`num`,id:`lfo${e}Depth`,label:`Depth`,group:`Modulation`,min:0,max:1,def:.3,scale:`pow2`,show:t}]}var C=[{kind:`enum`,id:`geometry`,label:`Geometry`,group:`Body`,model:!0,def:`string`,options:[[`string`,`String`],[`bar`,`Bar (free–free)`],[`tube_co`,`Tube (closed–open)`],[`tube_oo`,`Tube (open–open)`],[`membrane`,`Membrane (circular)`],[`plate`,`Plate (rectangular)`],[`disc`,`Disc (cymbal / gong)`],[`ring`,`Bell / ring`],[`free`,`Free spectrum (kᵖ)`]],hint:`Sets the mode frequency ratios and mode shapes`},{kind:`num`,id:`modes`,label:`Modes`,group:`Body`,min:4,max:256,def:64,int:!0,model:!0,scale:`log`},{kind:`num`,id:`aspect`,label:`Aspect ratio`,group:`Body`,min:.2,max:1,def:.71,model:!0,show:_(`plate`)},{kind:`num`,id:`powerExp`,label:`Exponent p`,group:`Body`,min:.3,max:3,def:1.5,model:!0,show:_(`free`)},{kind:`num`,id:`discExp`,label:`Chladni exponent`,group:`Body`,min:1,max:2.5,def:2,model:!0,show:_(`disc`),hint:`f ∝ (m + 2n)^p: 2 = flat plate; lower for domed cymbals and gongs`},{kind:`num`,id:`stretch`,label:`Stretch`,group:`Body`,min:.5,max:2,def:1,model:!0,digits:3,hint:`ratio → ratio^s (bar with s≈1.368 gives the 1:4:10 marimba tuning)`},{kind:`num`,id:`inharm`,label:`Stiffness B`,group:`Body`,min:0,max:.05,def:0,scale:`pow2`,model:!0,digits:5,hint:`ratio·√(1+B·ratio²): piano-like stretched partials`},{kind:`num`,id:`harmonize`,label:`Harmonize`,group:`Body`,min:0,max:1,def:0,model:!0,hint:`pull partials toward integer multiples`},{kind:`num`,id:`jitter`,label:`Detune jitter`,group:`Body`,min:0,max:200,def:0,scale:`pow2`,unit:`¢`,model:!0},{kind:`num`,id:`seed`,label:`Seed`,group:`Body`,min:1,max:999,def:1,int:!0,model:!0,hint:`random detune, coupling topology and radiation`},{kind:`num`,id:`t60`,label:`Decay T60`,group:`Damping`,min:.05,max:60,def:4,scale:`log`,unit:`s`},{kind:`num`,id:`hfDamp`,label:`HF damping`,group:`Damping`,min:0,max:100,def:2,scale:`pow2`,unit:`/s@1k`,hint:`extra decay rate σ = c·(f/1kHz)²`},{kind:`num`,id:`damper`,label:`Damper T60`,group:`Damping`,min:.02,max:20,def:.3,scale:`log`,unit:`s`,hint:`applied on key release; max = no damper`},{kind:`num`,id:`tension`,label:`Tension modulation`,group:`Nonlinear`,min:0,max:2,def:0,scale:`pow2`,digits:3,hint:`amplitude-dependent pitch (glides)`},{kind:`num`,id:`cascade`,label:`Cascade coupling`,group:`Nonlinear`,min:0,max:20,def:0,scale:`pow2`,digits:3,hint:`random quartic coupling: energy spreads across modes (gong/cymbal shimmer)`},{kind:`num`,id:`curvature`,label:`Curvature (3-wave)`,group:`Nonlinear`,min:0,max:3,def:0,scale:`pow2`,digits:3,hint:`quadratic forces: sum/difference tones, crashes`},{kind:`num`,id:`terms`,label:`Coupling terms`,group:`Nonlinear`,min:1,max:16,def:6,int:!0,model:!0},{kind:`num`,id:`nlModes`,label:`Coupled modes`,group:`Nonlinear`,min:4,max:128,def:48,int:!0,model:!0,scale:`log`},{kind:`num`,id:`glide`,label:`Pitch glide`,group:`Nonlinear`,min:-12,max:12,def:0,unit:`st`,hint:`pitch offset while loud, relaxing as the note decays: + falls (like tension), − rises (Chinese opera gong)`},{kind:`num`,id:`crossTension`,label:`Cross-note tension`,group:`Nonlinear`,min:0,max:2,def:0,scale:`pow2`,digits:3,hint:`notes share one tension: they bend each other`},{kind:`num`,id:`crossLink`,label:`Cross-note link`,group:`Nonlinear`,min:0,max:2,def:0,scale:`pow2`,digits:3,hint:`sympathetic coupling + intermodulation between notes`},{kind:`num`,id:`buzz`,label:`Barrier stiffness`,group:`Collision`,min:0,max:1,def:0,scale:`pow2`,digits:3,hint:`sitar bridge, snare wires, rattles`},{kind:`num`,id:`buzzGap`,label:`Gap`,group:`Collision`,min:0,max:2,def:.2,digits:3,show:e=>e.buzz>0},{kind:`num`,id:`buzzPos`,label:`Position`,group:`Collision`,min:0,max:1,def:.02,digits:3,show:e=>e.buzz>0},{kind:`num`,id:`buzzPosY`,label:`Position Y`,group:`Collision`,min:0,max:1,def:.5,show:e=>e.buzz>0&&g(e)},{kind:`enum`,id:`buzzSides`,label:`Barrier`,group:`Collision`,options:[[`one`,`One-sided (bridge)`],[`two`,`Two-sided (rattle)`]],def:`one`,show:e=>e.buzz>0},{kind:`enum`,id:`exciter`,label:`Key exciter`,group:`Exciter`,def:`strike`,options:[[`strike`,`Strike (hammer / mallet)`],[`pluck`,`Pluck`],[`impulse`,`Impulse`],[`bow`,`Bow`],[`reed`,`Reed / blow`],[`selfosc`,`Self-oscillator`],[`noise`,`Noise`]]},{kind:`num`,id:`strength`,label:`Strength`,group:`Exciter`,min:0,max:6,def:1,scale:`pow2`,hint:`>1 pushes the body into its nonlinear regime`},{kind:`num`,id:`exPos`,label:`Position`,group:`Exciter`,min:0,max:1,def:.13,digits:3},{kind:`num`,id:`exPosY`,label:`Position Y`,group:`Exciter`,min:0,max:1,def:.37,show:g},{kind:`num`,id:`exWidth`,label:`Contact width`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`},{kind:`num`,id:`hammerMass`,label:`Hammer mass`,group:`Exciter`,min:.005,max:5,def:.1,scale:`log`,digits:3,show:v(`strike`)},{kind:`num`,id:`hardness`,label:`Contact time`,group:`Exciter`,min:.05,max:20,def:1,scale:`log`,unit:`ms`,show:v(`strike`,`impulse`)},{kind:`num`,id:`feltExp`,label:`Felt exponent`,group:`Exciter`,min:1,max:4,def:2.5,show:v(`strike`)},{kind:`num`,id:`bowForce`,label:`Bow force`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:v(`bow`)},{kind:`num`,id:`bowSpeed`,label:`Bow speed`,group:`Exciter`,min:0,max:2,def:.4,scale:`pow2`,show:v(`bow`),hint:`scaled by key velocity: sets the loudness`},{kind:`num`,id:`bowNoise`,label:`Bow noise`,group:`Exciter`,min:0,max:1,def:0,scale:`pow2`,show:v(`bow`),hint:`random bow-force fluctuation: rosin and hair noise`},{kind:`num`,id:`reedPressure`,label:`Mouth pressure`,group:`Exciter`,min:0,max:1.5,def:.6,show:v(`reed`)},{kind:`num`,id:`reedGain`,label:`Reed opening`,group:`Exciter`,min:0,max:2,def:.5,show:v(`reed`)},{kind:`num`,id:`breath`,label:`Breath noise`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`,show:v(`reed`)},{kind:`num`,id:`selfGain`,label:`Negative damping`,group:`Exciter`,min:0,max:4,def:.5,scale:`pow2`,show:v(`selfosc`)},{kind:`num`,id:`selfSat`,label:`Saturation level`,group:`Exciter`,min:.02,max:4,def:.5,scale:`log`,show:v(`selfosc`)},{kind:`num`,id:`noiseLevel`,label:`Noise level`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:v(`noise`)},{kind:`num`,id:`noiseColor`,label:`Noise cutoff`,group:`Exciter`,min:50,max:16e3,def:3e3,scale:`log`,unit:`Hz`,show:v(`noise`,`reed`,`bow`)},{kind:`num`,id:`attack`,label:`Attack`,group:`Exciter`,min:1,max:3e3,def:40,scale:`log`,unit:`ms`,show:v(...y)},{kind:`num`,id:`release`,label:`Release`,group:`Exciter`,min:5,max:5e3,def:150,scale:`log`,unit:`ms`,show:v(...y)},{kind:`num`,id:`fbGain`,label:`Feedback gain`,group:`Feedback`,min:0,max:8,def:0,scale:`pow2`,hint:`output → delay → band-pass → saturate → back into the body (while a key is held)`},{kind:`num`,id:`fbDelay`,label:`Delay`,group:`Feedback`,min:.05,max:600,def:5,scale:`log`,unit:`ms`,show:e=>e.fbGain>0},{kind:`num`,id:`fbFreq`,label:`Band centre`,group:`Feedback`,min:30,max:12e3,def:800,scale:`log`,unit:`Hz`,show:e=>e.fbGain>0},{kind:`num`,id:`fbQ`,label:`Band Q`,group:`Feedback`,min:.3,max:30,def:1.5,scale:`log`,show:e=>e.fbGain>0},{kind:`num`,id:`fbSat`,label:`Saturation`,group:`Feedback`,min:.01,max:4,def:.4,scale:`log`,show:e=>e.fbGain>0},...S(1),...S(2),{kind:`num`,id:`vibDepth`,label:`Vibrato depth`,group:`Modulation`,min:0,max:100,def:0,scale:`pow2`,unit:`¢`,hint:`per-note vibrato, each note with its own phase and rate`},{kind:`num`,id:`vibRate`,label:`Vibrato rate`,group:`Modulation`,min:1,max:12,def:5.5,unit:`Hz`,show:e=>e.vibDepth>0},{kind:`num`,id:`vibDelay`,label:`Vibrato onset`,group:`Modulation`,min:0,max:2e3,def:300,unit:`ms`,show:e=>e.vibDepth>0,hint:`vibrato fades in after the note starts`},{kind:`num`,id:`bendRange`,label:`Pitch-bend range`,group:`Modulation`,min:0,max:24,def:2,int:!0,unit:`st`},{kind:`enum`,id:`soundbox`,label:`Soundbox`,group:`Soundbox`,def:`off`,options:[[`off`,`Off`],[`violin`,`Violin`],[`viola`,`Viola`],[`cello`,`Cello`],[`bass`,`Double bass`],[`guitar`,`Guitar`]],hint:`fixed resonances that every note passes through (they don't transpose)`},{kind:`num`,id:`boxSize`,label:`Size`,group:`Soundbox`,min:.4,max:3,def:1,scale:`log`,digits:3,show:e=>e.soundbox!==`off`,hint:`>1 lowers every resonance`},{kind:`num`,id:`boxDamp`,label:`Damping`,group:`Soundbox`,min:.3,max:4,def:1,scale:`log`,show:e=>e.soundbox!==`off`,hint:`scales every resonance's bandwidth`},{kind:`num`,id:`boxMix`,label:`Mix`,group:`Soundbox`,min:0,max:1,def:1,show:e=>e.soundbox!==`off`},{kind:`num`,id:`pickup`,label:`Pickup position`,group:`Output`,min:0,max:1,def:.77,digits:3},{kind:`num`,id:`pickupY`,label:`Pickup Y`,group:`Output`,min:0,max:1,def:.61,show:g},{kind:`num`,id:`width`,label:`Stereo width`,group:`Output`,min:0,max:1,def:.3,hint:`right pickup is offset from the left one`},{kind:`num`,id:`spread`,label:`Whole-body radiation`,group:`Output`,min:0,max:1,def:.2,hint:`0 = point pickup, 1 = every mode radiates equally`},{kind:`num`,id:`tilt`,label:`Spectral tilt`,group:`Output`,min:-12,max:12,def:0,unit:`dB/oct`},{kind:`num`,id:`level`,label:`Level`,group:`Output`,min:-24,max:36,def:0,unit:`dB`,hint:`instrument level (saved with presets; Volume is not)`},{kind:`num`,id:`voices`,label:`Max notes`,group:`Output`,min:1,max:16,def:8,int:!0},{kind:`num`,id:`drive`,label:`Saturation`,group:`Output`,min:0,max:1,def:0},{kind:`num`,id:`delayMix`,label:`Delay mix`,group:`Output`,min:0,max:1,def:0},{kind:`num`,id:`delayTime`,label:`Delay time`,group:`Output`,min:10,max:1500,def:350,scale:`log`,unit:`ms`,show:e=>e.delayMix>0},{kind:`num`,id:`delayFb`,label:`Delay feedback`,group:`Output`,min:0,max:.95,def:.35,show:e=>e.delayMix>0},{kind:`num`,id:`reverbMix`,label:`Reverb mix`,group:`Output`,min:0,max:1,def:.15},{kind:`num`,id:`reverbSize`,label:`Reverb time`,group:`Output`,min:.2,max:12,def:2.5,scale:`log`,unit:`s`,show:e=>e.reverbMix>0},{kind:`num`,id:`volume`,label:`Volume`,group:`Output`,min:-40,max:12,def:-6,unit:`dB`},{kind:`bool`,id:`seqOn`,label:`Auto-play`,group:`Auto`,def:!1},{kind:`enum`,id:`seqMode`,label:`Pattern`,group:`Auto`,def:`mixed`,options:[[`mixed`,`Mixed (changes every 4 bars)`],[`melody`,`Melody`],[`arpeggio`,`Arpeggio`],[`chords`,`Chords`],[`rhythm`,`Rhythm (one pitch)`],[`drone`,`Drone + sparse melody`]]},{kind:`num`,id:`seqTempo`,label:`Tempo`,group:`Auto`,min:20,max:400,def:110,int:!0,unit:`bpm`},{kind:`num`,id:`seqDensity`,label:`Density`,group:`Auto`,min:0,max:1,def:.5},{kind:`enum`,id:`seqScale`,label:`Scale`,group:`Auto`,def:`pentatonic`,options:[[`chromatic`,`Chromatic`],[`major`,`Major`],[`minor`,`Natural minor`],[`dorian`,`Dorian`],[`pentatonic`,`Pentatonic`],[`wholetone`,`Whole tone`],[`harmonic`,`Harmonic series`]]},{kind:`num`,id:`seqRoot`,label:`Root`,group:`Auto`,min:24,max:84,def:48,int:!0},{kind:`num`,id:`seqRange`,label:`Range`,group:`Auto`,min:1,max:4,def:2,int:!0,unit:`oct`},{kind:`num`,id:`seqGate`,label:`Note length`,group:`Auto`,min:.05,max:8,def:.5,scale:`log`,unit:`beats`},{kind:`num`,id:`seqPoly`,label:`Notes per step`,group:`Auto`,min:1,max:4,def:1,int:!0,show:e=>e.seqMode===`melody`||e.seqMode===`mixed`},{kind:`num`,id:`seqVelRand`,label:`Velocity spread`,group:`Auto`,min:0,max:1,def:.3},{kind:`num`,id:`seqPosRand`,label:`Position spread`,group:`Auto`,min:0,max:1,def:0,hint:`randomize where each note is excited`}],w=Object.fromEntries(C.map(e=>[e.id,e])),T=Object.fromEntries(C.map(e=>[e.id,e.def]));C.filter(e=>e.model).map(e=>e.id);var E=class{ctx;input;analyser;scope;shaper;dry;delaySend;dL;dR;fbL;fbR;revSend;conv;master;lastDrive=-1;lastSize=-1;sizeTimer;constructor(e,t=e.destination){this.ctx=e,this.input=e.createGain(),this.analyser=e.createAnalyser(),this.analyser.fftSize=8192,this.analyser.smoothingTimeConstant=0,this.analyser.minDecibels=-120,this.analyser.maxDecibels=-10,this.scope=e.createAnalyser(),this.scope.fftSize=4096,this.input.connect(this.analyser),this.input.connect(this.scope),this.shaper=e.createWaveShaper(),this.shaper.oversample=`4x`,this.dry=e.createGain(),this.master=e.createGain(),this.input.connect(this.shaper),this.shaper.connect(this.dry),this.dry.connect(this.master),this.delaySend=e.createGain();let n=e.createChannelSplitter(2),r=e.createChannelMerger(2);this.dL=e.createDelay(2),this.dR=e.createDelay(2),this.fbL=e.createGain(),this.fbR=e.createGain(),this.shaper.connect(this.delaySend),this.delaySend.connect(n),n.connect(this.dL,0),n.connect(this.dR,1),this.dL.connect(this.fbL),this.fbL.connect(this.dR),this.dR.connect(this.fbR),this.fbR.connect(this.dL),this.dL.connect(r,0,0),this.dR.connect(r,0,1),r.connect(this.master),this.revSend=e.createGain(),this.conv=e.createConvolver(),this.shaper.connect(this.revSend),this.revSend.connect(this.conv),this.conv.connect(this.master);let i=e.createDynamicsCompressor();i.threshold.value=-3,i.knee.value=3,i.ratio.value=20,i.attack.value=.002,i.release.value=.15,this.master.connect(i),i.connect(t)}set(e){let t=this.ctx.currentTime,n=(e,n)=>e.setTargetAtTime(n,t,.02),r=h(e,`drive`);if(r!==this.lastDrive){if(this.lastDrive=r,r<=0)this.shaper.curve=null;else{let e=1+40*r*r,t=2048,n=new Float32Array(t);for(let r=0;r<t;r++){let t=r/2047*2-1;n[r]=Math.tanh(e*t)/Math.tanh(e)}this.shaper.curve=n}}let i=h(e,`delayMix`);n(this.delaySend.gain,i);let a=h(e,`delayTime`)/1e3;n(this.dL.delayTime,a),n(this.dR.delayTime,a),n(this.fbL.gain,h(e,`delayFb`)),n(this.fbR.gain,h(e,`delayFb`));let o=h(e,`reverbMix`);n(this.revSend.gain,o),n(this.dry.gain,r>0?1/(1+2*r):1),n(this.master.gain,10**(h(e,`volume`)/20));let s=h(e,`reverbSize`);s!==this.lastSize&&(this.lastSize=s,clearTimeout(this.sizeTimer),this.sizeTimer=window.setTimeout(()=>this.conv.buffer=this.makeIR(s),150))}makeIR(e){let t=this.ctx.sampleRate,n=Math.round(t*Math.min(e*1.1,12)),r=this.ctx.createBuffer(2,n,t);for(let i=0;i<2;i++){let a=r.getChannelData(i),o=0;for(let r=0;r<n;r++){let n=r/t,i=9e3*Math.exp(-n/(.6*e))+400,s=1-Math.exp(-2*Math.PI*i/t);o+=s*(Math.random()*2-1-o);let c=Math.exp(-6.9*n/e)*Math.min(1,n/.004);a[r]=o*c*.5}}return r}},D=new URL(`worklet-PIV7En5i.js`,import.meta.url).href,O={geometry:`string`,t60:3,hfDamp:2,damper:.6,exciter:`bow`,bowForce:1,bowSpeed:.4,bowNoise:.06,noiseColor:4e3,exWidth:.1,attack:80,release:150,pickup:.99,width:0,spread:0,tilt:-6,vibDelay:350,boxMix:.9,level:23,voices:4,reverbMix:.25,reverbSize:2.2},k=[{name:`Piano-ish`,category:`Instrument`,note:48,p:{geometry:`string`,modes:80,inharm:4e-4,t60:9,hfDamp:1.2,damper:.15,exciter:`strike`,strength:1,exPos:.12,exWidth:.04,hammerMass:.04,hardness:1.4,feltExp:2.6,tension:.01,crossLink:.15,pickup:.77,spread:.35,width:.4,reverbMix:.18}},{name:`Steel-string pluck`,category:`Instrument`,note:52,p:{geometry:`string`,modes:64,inharm:8e-5,t60:5,hfDamp:3,damper:.4,exciter:`pluck`,strength:1,exPos:.18,exWidth:.03,tension:.02,pickup:.92,spread:.25,reverbMix:.15}},{name:`Nylon harp`,category:`Instrument`,note:60,p:{geometry:`string`,modes:48,t60:3.5,hfDamp:8,damper:20,exciter:`pluck`,exPos:.35,exWidth:.2,pickup:.5,spread:.5,reverbMix:.25}},{name:`Marimba`,category:`Instrument`,note:60,p:{geometry:`bar`,modes:24,stretch:1.368,t60:1.3,hfDamp:6,damper:20,exciter:`strike`,exPos:.42,exWidth:.05,hammerMass:.25,hardness:1,feltExp:2,pickup:.22,spread:.3,reverbMix:.2}},{name:`Vibraphone`,category:`Instrument`,note:65,p:{geometry:`bar`,modes:24,stretch:1.368,t60:7,hfDamp:1.5,damper:.2,exciter:`strike`,exPos:.45,exWidth:.05,hammerMass:.15,hardness:.8,feltExp:2.2,pickup:.22,spread:.3,lfo1Target:`amp`,lfo1Rate:5,lfo1Depth:.45,reverbMix:.25}},{name:`Church bell`,category:`Instrument`,note:55,p:{geometry:`ring`,modes:40,t60:14,hfDamp:.4,damper:20,jitter:4,exciter:`strike`,exPos:.1,exWidth:.02,hammerMass:.6,hardness:.5,feltExp:1.5,tension:.01,pickup:.3,spread:.5,reverbMix:.35,reverbSize:5}},{name:`Tom drum`,category:`Instrument`,note:43,p:{geometry:`membrane`,modes:40,t60:.7,hfDamp:6,damper:20,tension:.25,exciter:`strike`,strength:1.6,exPos:.35,exPosY:.45,exWidth:.05,hammerMass:.3,hardness:2.5,feltExp:2,pickup:.5,pickupY:.5,spread:.5,reverbMix:.15}},{name:`Snare-ish`,category:`Instrument`,note:50,p:{geometry:`membrane`,modes:64,t60:.5,hfDamp:2,damper:20,tension:.1,buzz:.5,buzzGap:.05,buzzPos:.5,buzzPosY:.55,buzzSides:`two`,exciter:`strike`,strength:1.5,exPos:.4,exPosY:.4,exWidth:.02,hammerMass:.05,hardness:.6,feltExp:1.5,pickup:.5,pickupY:.5,spread:.6,reverbMix:.15}},{name:`Sitar / tanpura`,category:`Instrument`,note:50,p:{geometry:`string`,modes:96,t60:8,hfDamp:.3,damper:20,buzz:.6,buzzGap:.15,buzzPos:.015,buzzSides:`one`,exciter:`pluck`,strength:1.2,exPos:.2,exWidth:.02,pickup:.12,spread:.3,reverbMix:.25}},{name:`Cello`,category:`Instrument`,note:48,p:{...O,modes:128,inharm:4e-5,exPos:.09,vibDepth:16,vibRate:5.2,soundbox:`cello`}},{name:`Violin`,category:`Instrument`,note:67,p:{...O,modes:80,inharm:2e-5,exPos:.1,exWidth:.15,vibDepth:14,vibRate:5.8,vibDelay:250,soundbox:`violin`}},{name:`Viola`,category:`Instrument`,note:60,p:{...O,modes:96,inharm:3e-5,exPos:.1,vibDepth:15,vibRate:5.5,soundbox:`viola`}},{name:`Double bass`,category:`Instrument`,note:36,p:{...O,modes:160,inharm:6e-5,exPos:.08,t60:4,attack:120,vibDepth:12,vibRate:4.8,vibDelay:450,soundbox:`bass`,voices:3,level:20}},{name:`Cello pizzicato`,category:`Instrument`,note:48,p:{...O,modes:96,inharm:4e-5,exciter:`pluck`,strength:1.2,exPos:.3,exWidth:.25,t60:2.2,hfDamp:8,damper:.4,vibDepth:0,soundbox:`cello`,voices:8,level:24}},{name:`Clarinet-ish`,category:`Instrument`,note:50,p:{geometry:`tube_co`,modes:24,t60:.25,hfDamp:6,damper:.05,exciter:`reed`,reedPressure:.7,reedGain:.4,breath:.03,noiseColor:3e3,exPos:0,exWidth:0,attack:30,release:60,pickup:.25,spread:.2,reverbMix:.2}},{name:`Singing bowl`,category:`Instrument`,note:62,p:{geometry:`ring`,modes:24,t60:20,hfDamp:.5,damper:20,jitter:2,exciter:`selfosc`,selfGain:.15,selfSat:.3,exPos:0,exWidth:.01,attack:1500,release:3e3,pickup:.15,spread:.4,width:.6,reverbMix:.35,reverbSize:6}},{name:`Rubber band`,category:`Experimental`,note:40,p:{geometry:`string`,modes:40,t60:1.5,hfDamp:4,damper:.3,tension:1.2,exciter:`pluck`,strength:2.5,exPos:.3,exWidth:.05,pickup:.8,reverbMix:.1}},{name:`Chaos gong`,category:`Experimental`,note:40,p:{geometry:`plate`,modes:128,aspect:.8,nlModes:64,terms:8,cascade:12,curvature:2.2,t60:10,hfDamp:.2,damper:20,crossTension:.4,crossLink:.8,exciter:`strike`,strength:3.5,exPos:.3,exPosY:.3,hammerMass:.4,hardness:2,feltExp:2,pickup:.6,pickupY:.7,spread:.5,width:.6,reverbMix:.3,reverbSize:6,voices:4}},{name:`Ring-mod chords`,category:`Experimental`,note:57,p:{geometry:`free`,powerExp:1.7,modes:32,jitter:15,t60:6,hfDamp:1,damper:1,crossTension:.3,crossLink:1.4,curvature:.5,exciter:`strike`,strength:1.8,exPos:.2,hammerMass:.1,hardness:.8,pickup:.7,spread:.6,width:.6,delayMix:.25,delayTime:375,delayFb:.4,reverbMix:.3}},{name:`Feedback drone plate`,category:`Experimental`,note:45,p:{geometry:`plate`,modes:96,aspect:.62,nlModes:64,cascade:.8,curvature:.3,t60:6,hfDamp:.5,damper:3,exciter:`noise`,noiseLevel:.2,noiseColor:800,attack:800,release:3e3,fbGain:2.5,fbDelay:12,fbFreq:600,fbQ:2,fbSat:.4,lfo1Target:`position`,lfo1Rate:.07,lfo1Depth:.5,lfo1Shape:`smooth`,lfo2Target:`pickup`,lfo2Rate:.11,lfo2Depth:.4,lfo2Shape:`smooth`,pickup:.3,pickupY:.7,spread:.3,width:.7,reverbMix:.35,reverbSize:5,voices:4}},{name:`Buzzing bar organ`,category:`Experimental`,note:48,p:{geometry:`bar`,modes:32,t60:3,hfDamp:1,damper:.3,buzz:.4,buzzGap:.3,buzzPos:.5,buzzSides:`two`,exciter:`selfosc`,selfGain:.6,selfSat:.4,exPos:.02,attack:60,release:300,pickup:.3,spread:.3,reverbMix:.25}},{name:`Glass harmonics`,category:`Experimental`,note:72,p:{geometry:`free`,powerExp:1.25,modes:24,harmonize:.3,t60:12,hfDamp:.3,damper:2,exciter:`impulse`,strength:.8,hardness:.3,exPos:.21,pickup:.6,spread:.6,width:.8,tension:.05,lfo1Target:`pickup`,lfo1Rate:.3,lfo1Depth:.6,delayMix:.3,delayTime:450,delayFb:.5,reverbMix:.45,reverbSize:7}}];function A(e,t=128){let n=new Float32Array(t);for(let r=0;r<t;r++)n[r]=e*Math.cos(Math.PI/2*(r/(t-1)))**2;return n}var j=new WeakMap;function M(e){let t=j.get(e);return t||(t=e.audioWorklet.addModule(D),j.set(e,t)),t}function N(e){if(!e||!e.trim())return null;try{let t=JSON.parse(e);return t&&typeof t==`object`&&!Array.isArray(t)?t:null}catch{return null}}var ee=.2,P=25;function F(e){return(t,n,r)=>{let i={...T,...e??N(r.custom)??{}},a=t.createGain(),o=new E(t,n);a.connect(o.input),o.set(i);let s=null,c=[],l=e=>s?s.port.postMessage(e):c.push(e),u=M(t).then(()=>{s=new AudioWorkletNode(t,`modal-synth`,{numberOfInputs:0,outputChannelCount:[2]}),s.port.onmessage=()=>{},s.port.postMessage({type:`params`,params:i});for(let e of c.splice(0))s.port.postMessage(e);s.connect(a)}),d=[],f=new Map,p=window.setInterval(()=>{let e=t.currentTime+ee,n=[];for(let t of d)t.time>e?n.push(t):(f.get(t.note)??-1/0)<=t.on&&l({type:`noteOff`,note:t.note,time:t.time});d=n},P);return{ready:u,play({when:e,freq:n,velocity:r,duration:o}){if(r<=0)return null;let s=69+12*Math.log2(n/440);l({type:`noteOn`,note:s,vel:Math.max(.01,Math.min(1,r)),time:e}),f.set(s,e);let c={note:s,on:e,time:e+o};return d.push(c),{hold(e,n,r){let o=Math.max(e,t.currentTime),s=n+r;c.time=o+s;let u=Math.min(60,Math.max(i.t60,6*s)),d=u/i.t60,f={...i,t60:u,hfDamp:i.hfDamp/d};window.setTimeout(()=>l({type:`params`,params:f}),Math.max(0,(o-t.currentTime)*1e3)),a.gain.setValueCurveAtTime(A(1),o+Math.max(n,.005),r)}}},dispose(){window.clearInterval(p),l({type:`panic`}),window.setTimeout(()=>{s?.disconnect(),s?.port.close(),a.disconnect()},1e3)}}}}function I(){let e={};for(let t of k)e[`modal: ${t.name}`]=F(t.p);return e[`modal: custom`]=F(null),e}var L=[`bowForce`,`bowSpeed`,`bowNoise`,`exPos`,`reedPressure`,`reedGain`,`breath`,`selfGain`,`selfSat`,`noiseLevel`,`noiseColor`,`tension`,`cascade`,`curvature`,`fbGain`,`fbFreq`,`fbQ`,`fbSat`,`hfDamp`,`t60`,`pickup`,`tilt`,`vibDepth`];function te(e,t){let n=w[e];if(!n||n.kind!==`num`)return NaN;let r=Math.max(0,Math.min(1,t));return n.scale===`log`?n.min*(n.max/n.min)**+r:n.scale===`pow2`?n.min+(n.max-n.min)*r*r:n.min+(n.max-n.min)*r}var ne=[`bow`,`reed`,`selfosc`,`noise`],re=50,R=.3,z=1.5,B=20;function V(e){return(t,n,r)=>{let i={...T,...e??N(r.custom)??{},voices:1},a=t.createGain();a.gain.value=0;let o=new E(t,n);a.connect(o.input),o.set(i);let s=t.createAnalyser();s.fftSize=2048;let c=new Float32Array(s.fftSize),l=R*R,u=0,d=1,f=null,p=[],m=e=>f?f.port.postMessage(e):p.push(e),h=M(t).then(()=>{f=new AudioWorkletNode(t,`modal-synth`,{numberOfInputs:0,outputChannelCount:[2]}),f.port.onmessage=()=>{},f.port.postMessage({type:`params`,params:i});for(let e of p.splice(0))f.port.postMessage(e);f.connect(a),f.connect(s)}),g=null,_=i,v=0,y=``,b=e=>69+12*Math.log2(e/440);return{ready:h,start(e,t){g=b(t),m({type:`noteOn`,note:g,vel:1,time:e})},stop(e,n){let r=Math.max(t.currentTime,e-n);a.gain.cancelScheduledValues(r),a.gain.setTargetAtTime(0,r,n/4),g!==null&&m({type:`noteOff`,note:g,time:r}),g=null},set(e,{level:t,color:n,freq:r,timbre:o,normalize:p}){let h=performance.now()/1e3,x=u?Math.min(.5,h-u):0;if(u=h,p&&f){s.getFloatTimeDomainData(c);let e=0;for(let t of c)e+=t*t;e/=c.length,e>1e-10&&(l+=(e-l)*(1-Math.exp(-x/z))),d=Math.max(1/B,Math.min(B,R/Math.sqrt(l)))}else d=1;a.gain.setTargetAtTime(t*d,e,.08);let S=b(r);g!==null&&Math.abs(S-g)>.01&&(m({type:`noteOff`,note:g,time:e}),g=S,m({type:`noteOn`,note:g,vel:1,time:e}));let C=performance.now();if(!o?.length||C-v<re)return;let T={...i},E=[],D=!1;for(let e of o){if(!L.includes(e.target))continue;let t=te(e.target,e.from+(e.to-e.from)*n);if(!Number.isFinite(t))continue;T[e.target]=t,E.push(`${e.target} ${Number(t.toPrecision(3))}`);let r=w[e.target];Math.abs(t-_[e.target])>.002*(r.max-r.min)&&(D=!0)}y=E.join(`, `),D&&(_=T,v=C,m({type:`params`,params:T}))},describe:()=>d===1?y:`${y}${y?`, `:``}gain ${(20*Math.log10(d)).toFixed(1)} dB`,dispose(){m({type:`panic`}),window.setTimeout(()=>{f?.disconnect(),f?.port.close(),a.disconnect()},1e3)}}}}function ie(){let e={};for(let t of k){let n={...T,...t.p};(ne.includes(n.exciter)||n.fbGain>0)&&(e[`modal: ${t.name}`]=V(t.p))}return e[`modal: custom`]=V(null),e}function ae(e,t){return{play({when:n,freq:r,velocity:i,pan:a,duration:o}){if(i<=0)return null;let s=Math.max(n,e.currentTime),c=s+o,l=.3*i,u=s+.004,d=e.createGain();d.gain.setValueAtTime(0,s),d.gain.linearRampToValueAtTime(l,u),d.gain.exponentialRampToValueAtTime(1e-4,c);let f=e.createStereoPanner();f.pan.value=Math.max(-1,Math.min(1,a)),d.connect(f).connect(t);let p=e.createOscillator();p.frequency.value=r,p.connect(d);let m=e.createOscillator();m.type=`triangle`,m.frequency.value=r*2;let h=e.createGain();h.gain.value=.08+.15*i,m.connect(h).connect(d);for(let e of[p,m])e.start(s),e.stop(c+.05);return m.onended=()=>f.disconnect(),{hold(t,n,r){let i=Math.max(t,u,e.currentTime);if(i>=c)return;let a=l*(1e-4/l)**((i-u)/(c-u)),o=d.gain;typeof o.cancelAndHoldAtTime==`function`?o.cancelAndHoldAtTime(i):o.cancelScheduledValues(i),o.setValueAtTime(a,i),o.setValueCurveAtTime(A(a),i+Math.max(n,.005),r);let s=i+n+r+.05;p.stop(s),m.stop(s)}}},dispose(){}}}function H(e,t){let n=e.createGain();n.gain.value=0;let r=e.createBiquadFilter();r.type=`lowpass`,r.frequency.value=120,r.Q.value=.7,r.connect(n).connect(t);let i=e.createOscillator(),a=e.createGain();a.gain.value=.5,i.connect(a).connect(n);let o=[-6,6].map(t=>{let n=e.createOscillator();n.type=`sawtooth`,n.detune.value=t;let i=e.createGain();return i.gain.value=.25,n.connect(i).connect(r),n}),s=[i,...o];return{start(e,t){i.frequency.value=t;for(let e of o)e.frequency.value=t*2;for(let t of s)t.start(e)},stop(e,t){n.gain.cancelScheduledValues(e-t),n.gain.setTargetAtTime(0,e-t,t/4);for(let t of s)t.stop(e+.1)},set(e,{level:t,color:a,freq:s}){let c=.08;n.gain.setTargetAtTime(t,e,c),i.frequency.setTargetAtTime(s,e,c);for(let t of o)t.frequency.setTargetAtTime(s*2,e,c);let l=Math.max(0,Math.min(1,a));r.frequency.setTargetAtTime(s*2*2**(6*l),e,c),r.Q.setTargetAtTime(.7+5*l*l,e,c)},dispose(){n.disconnect()}}}var oe={"placeholder tone":ae,...I()},se={"placeholder hum":H,...ie()},U={continuous:null,chromatic:[0,1,2,3,4,5,6,7,8,9,10,11],major:[0,2,4,5,7,9,11],"natural minor":[0,2,3,5,7,8,10],dorian:[0,2,3,5,7,9,10],lydian:[0,2,4,6,7,9,11],"pentatonic major":[0,2,4,7,9],"pentatonic minor":[0,3,5,7,10],"whole tone":[0,2,4,6,8,10],"harmonic series":null},ce=Object.keys(U),le=[`C`,`C#`,`D`,`D#`,`E`,`F`,`F#`,`G`,`G#`,`A`,`A#`,`B`];function W(e){return 440*2**((e-69)/12)}function ue(e,t,n){if(t===`harmonic series`){let t=W(n+12*Math.floor((24-n)/12)),r=Math.max(1,Math.round(W(e)/t));return 69+12*Math.log2(r*t/440)}let r=U[t];if(!r)return e;let i=e-n,a=Math.floor(i/12),o=i-12*a,s=r[0],c=1/0;for(let e of[...r,12]){let t=Math.abs(o-e);t<c&&(c=t,s=e)}return n+12*a+s}var de=class{cfg;y=new Float64Array(4);t=0;eTarget=0;tau=2;controlled=!0;k1=new Float64Array(4);k2=new Float64Array(4);k3=new Float64Array(4);k4=new Float64Array(4);tmp=new Float64Array(4);constructor(e){this.cfg={...e}}get vTop(){let{m1:e,m2:t,l1:n,l2:r,g:i}=this.cfg;return 2*(e+t)*i*n+2*t*i*r}get p2Scale(){let{m2:e,l2:t}=this.cfg;return Math.sqrt(e*t*t*this.vTop)}derived(e=this.y){let{m1:t,m2:n,l1:r,l2:i,g:a}=this.cfg,[o,s,c,l]=[e[0],e[1],e[2],e[3]],u=o-s,d=Math.cos(u),f=Math.sin(u),p=t+n*f*f,m=(i*c-r*l*d)/(r*r*i*p),h=(r*(t+n)*l-i*n*c*d)/(r*i*i*n*p);return{w1:m,w2:h,T:.5*(c*m+l*h),V:(t+n)*a*r*(1-Math.cos(o))+n*a*i*(1-Math.cos(s))}}energy(e=this.y){let t=this.derived(e);return t.T+t.V}energyNorm(){return this.energy()/this.vTop}deriv(e,t){let{m1:n,m2:r,l1:i,l2:a,g:o}=this.cfg,s=e[0],c=e[1],l=e[2],u=e[3],d=s-c,f=Math.cos(d),p=Math.sin(d),m=n+r*p*p,h=(a*l-i*u*f)/(i*i*a*m),g=(i*(n+r)*u-a*r*l*f)/(i*a*a*r*m),_=l*u*p/(i*a*m),v=(a*a*r*l*l+i*i*(n+r)*u*u-2*i*a*r*l*u*f)*Math.sin(2*d)/(2*i*i*a*a*m*m),y=.5*(l*h+u*g),b=(n+r)*o*i*(1-Math.cos(s))+r*o*a*(1-Math.cos(c)),x=0;if(this.controlled){let e=.02*this.vTop,t=4/this.tau;x=(this.eTarget-(y+b))/(this.tau*(2*y+e)),x>t?x=t:x<-t&&(x=-t)}t[0]=h,t[1]=g,t[2]=-(n+r)*o*i*Math.sin(s)-_+v+x*l,t[3]=-r*o*a*Math.sin(c)+_-v+x*u}step(e){let{y:t,k1:n,k2:r,k3:i,k4:a,tmp:o}=this;this.deriv(t,n);for(let r=0;r<4;r++)o[r]=t[r]+.5*e*n[r];this.deriv(o,r);for(let n=0;n<4;n++)o[n]=t[n]+.5*e*r[n];this.deriv(o,i);for(let n=0;n<4;n++)o[n]=t[n]+e*i[n];this.deriv(o,a);for(let o=0;o<4;o++)t[o]+=e/6*(n[o]+2*r[o]+2*i[o]+a[o]);this.t+=e}randomize(e,t){let{m1:n,m2:r,l1:i,l2:a}=this.cfg,o=Math.max(e,1e-6)*this.vTop,s=Math.min(Math.PI,3*Math.sqrt(o/(r*this.cfg.g*Math.min(i,a)))),c=0,l=0,u=0;for(let e=0;e<1e3&&(c=(2*t()-1)*s,l=(2*t()-1)*s,u=this.derived([c,l,0,0]).V,!(u<.9*o));e++)c=l=0,u=0;let d=o-u,f=t()*2*Math.PI,p=Math.cos(f),m=Math.sin(f),h=Math.cos(c-l),g=(n+r)*i*i,_=r*i*a*h,v=r*a*a,y=.5*(g*p*p+2*_*p*m+v*m*m),b=Math.sqrt(d/y),x=b*p,S=b*m;this.y[0]=c,this.y[1]=l,this.y[2]=g*x+_*S,this.y[3]=_*x+v*S,this.t=0}};function G(e){return Math.atan2(Math.sin(e),Math.cos(e))}function K(e,t){let n=e.duration,r=Math.min(e.peakTime,n),i=Math.min(r+e.holdTime,n),a=e.energyStart,o=e.energyPeak;if(t<0)return a;if(t<r){let n=(t/r)**+e.riseCurve;return e.riseShape===`exponential`?a*(o/a)**+n:a+(o-a)*n}return t<i?o:t<n?o*(1-(t-i)/(n-i))**e.fallCurve:0}var fe=.002,pe=.15,me=25,he=10,ge=1/960,_e=64,ve=2;function q(e,t){e.classList.add(`c01`);let r=document.createElement(`canvas`);e.append(r);let i=null,a=null,o=null,s=``,c=null,l=``,u=0,d=null,f=null,h,g=!1,_=0,v=0,y=0,b=0,x=0,S=[],C=-1/0,w=[],T=Math.PI,E=1,D=null,O=null,k=null,A=[],j=!1,M=0,N=0,ee=0,P=0,F=0,I={get playing(){return g},start:R,stop:B,draw:Q,now:L,length:()=>H(t()),readouts:$,dispose(){B(),k?.terminate(),k=null,e.classList.remove(`c01`),e.replaceChildren()}};function L(){return!a||!g?x:a.ctx.currentTime-_}function te(){return k||(k=new Worker(new URL(new URL(`orbitWorker-Da4eRcGA.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),k.onmessage=e=>{if(!g)return;let{gen:t,energy:n,pts:r}=e.data;if(M=Math.max(M,t),t<N)return;let i=A[A.length-1];if(!i||t>i.gen){let e=L();for(let t of A)t.retiredAt??=e;i={gen:t,energy:n,pts:[],retiredAt:null},A.push(i)}else if(t<i.gen)return;for(let e=0;e<r.length;e++)i.pts.push(r[e]);P+=r.length/2}),k}function ne(e){let n=t();if(!n.orbits&&!k)return;let r={running:e&&n.orbits,reset:j,energy:i?i.energyNorm():0,m2:n.massRatio,l2:n.lengthRatio,count:Math.round(n.orbitCount),life:n.orbitLife,band:n.orbitBand,minHold:n.orbitMinHold,maxPoints:n.orbitMaxPoints,cpu:n.orbitCpu};j=!1,te().postMessage(r)}function re(e){return new de({m1:1,l1:1,g:1,m2:e.massRatio,l2:e.lengthRatio})}async function R(e,n){B();let r=++u;a=e;let s=t(),c=e.ctx;y=s.seed>0?Math.round(s.seed):m(),i=re(s),i.randomize(K(s,0),p(y)),i.tau=s.tau,v=0,S=[],C=-1/0,w=[],A=[],N=M+1,j=!0,b=0,D=null,O=null,n>0&&V(n,!1),f=c.createGain(),f.connect(e.input),z(),await Promise.all([o?.ready,d?.ready]),r===u&&(_=c.currentTime+.1-n,d.start(c.currentTime+.05,W(s.humPitch)),g=!0,U(),h=window.setInterval(U,me))}function z(){if(!a||!f)return;let e=t();c||(c=a.ctx.createGain(),c.connect(f)),c.gain.setTargetAtTime(n(e.notesLevel),a.ctx.currentTime,.05);let r=e.noteInstrument,i=r===`modal: custom`?`${r}\n${e.modalCustom}`:r;o&&s===i||(o?.dispose(),s=i,o=oe[r](a.ctx,c,{custom:e.modalCustom}));let u=e.humInstrument,p=u===`modal: custom`?`${u}\n${e.humCustom}`:u;if(!d||l!==p){let t=d;if(l=p,d=se[u](a.ctx,f,{custom:e.humCustom}),t&&g){let n=a.ctx.currentTime;t.stop(n+.5,.5),window.setTimeout(()=>t.dispose(),1500);let r=d;(r.ready??Promise.resolve()).then(()=>r===d&&r.start(a.ctx.currentTime+.05,W(e.humPitch)))}}}function B(){u++,h!==void 0&&window.clearInterval(h),h=void 0;let e=g;if(g&&(x=L(),g=!1,ne(!1)),!a)return;let t=a.ctx.currentTime;e&&d?.stop(t+.3,.3);let n=f;n&&(n.gain.setTargetAtTime(0,t,.05),window.setTimeout(()=>n.disconnect(),600));let r=d;window.setTimeout(()=>r?.dispose(),600),d=null,l=``,o?.dispose(),o=null,s=``,c=null,f=null}function V(e,n){if(!i)return;let r=t();i.cfg.m2=r.massRatio,i.cfg.l2=r.lengthRatio,i.tau=r.tau;let a=r.speed,o=r.duration,s=r.restEnergy,c=i.y,l=G(c[0]),u=c[1],d=c[3],f=v;for(;v<e;){i.eTarget=K(r,v)*i.vTop,i.step(fe),v+=fe/a;let e=G(c[0]);if(O===null&&l<0&&e>=0&&e-l<Math.PI){let t=-l/(e-l),a={t:f+t*(v-f),th2:G(u+t*(c[1]-u)),p2:(d+t*(c[3]-d))/i.p2Scale};w.push(a),n&&ie(a,r)}O===null&&v>=o&&(i.energyNorm()<s||v>=o+he)&&(O=v,n&&ae(r)),l=e,u=c[1],d=c[3],f=v,v-C>=ge&&(S.push({t:v,th1:c[0],th2:c[1]}),C=v)}}function ie(e,t){if(!a||!o)return;let n=_+e.t;if(n<a.ctx.currentTime-.02)return;let r=t.thetaRange,i=t.pitchSource===`absolute`?Math.min(1,Math.abs(e.th2)/r):Math.max(0,Math.min(1,.5+.5*e.th2/r));t.invertPitch&&(i=1-i),i**=+t.pitchCurve;let s=t.pitchLow,c=t.pitchHigh,l=le.indexOf(t.root),u=ue(s+(c-s)*i,t.scale,l),d=Math.min(1,Math.abs(e.p2)/t.p2Ref),f=t.loudFloor,p=f+(1-f)*d**+t.loudCurve,m=W(u),h=t.panAmount*Math.max(-1,Math.min(1,e.th2/Math.PI)),g=o.play({when:n,freq:m,velocity:p,pan:h,duration:t.noteLength});g&&(D={handle:g,when:n}),b++}function ae(e){D&&D.handle.hold(D.when,e.finalHold,e.finalFade)}function H(e){let t=e.finalHold+e.finalFade+.3;return(O??e.duration+.5)+t}function U(){if(!a||!i||!g)return;let e=t();z();let r=a.ctx,o=r.currentTime-_,s=H(e);if(O!==null&&o>=s){B(),x=s,I.onEnded?.();return}V(o+pe,!0),ne(!0);let c=i.energyNorm(),l=e.energyPeak,u=Math.max(0,Math.min(1,c/l)),f=Math.min(e.energyStart,.999*l),p=e.humColorMode===`log`?Math.max(0,Math.min(1,Math.log(Math.max(c,1e-12)/f)/Math.log(l/f))):u,m=e.humFadeIn,h=e.humFadeOut,v=Math.min(1,m>0?o/m:1,O!==null&&h>0?(s-o)/h:1),y=e.humFollow,b=n(e.humLevel)*Math.max(0,v)*(1-y+y*u);d?.set(r.currentTime,{level:b,color:p**+e.humColorCurve,freq:W(e.humPitch),normalize:e.humNormalize,timbre:[1,2].filter(t=>e[`humTarget${t}`]!==`none`).map(t=>({target:e[`humTarget${t}`],from:e[`humFrom${t}`],to:e[`humTo${t}`]}))});let C=0;for(;C<S.length-1&&S[C+1].t<=o-.1;)C++;C>0&&S.splice(0,C)}function ce(e){let t=window.devicePixelRatio||1,n=Math.round(e.clientWidth*t),r=Math.round(e.clientHeight*t);(e.width!==n||e.height!==r)&&(e.width=n,e.height=r);let i=e.getContext(`2d`);return i.setTransform(t,0,0,t,0,0),i}function q(t){return getComputedStyle(e).getPropertyValue(t).trim()||`#ccc`}function J(e){let t=S.length;if(!t)return i?{th1:i.y[0],th2:i.y[1]}:{th1:0,th2:0};if(e<=S[0].t)return S[0];if(e>=S[t-1].t)return S[t-1];let n=0,r=t-1;for(;r-n>1;){let t=n+r>>1;S[t].t<=e?n=t:r=t}let a=S[n],o=S[r],s=(e-a.t)/(o.t-a.t);return{th1:a.th1+s*(o.th1-a.th1),th2:a.th2+s*(o.th2-a.th2)}}let Y=0,X=1/60;function Z(e,t,n,r,i){let a=r.pendulumAlpha;if(a<=0)return;let o=g?r.motionBlur*X:0,s=r.lengthRatio,c=r.pendulumSize*Math.min(t,n)/2,l=.9*c/(1+s),u=8+c,d=8+c,f=1;if(o>0){let e=0,t=J(i);for(let n=1;n<=8;n++){let r=J(i-o*n/8);e+=l*(+Math.abs(r.th1-t.th1)+s*Math.abs(r.th2-t.th2)),t=r}f=Math.max(2,Math.min(_e,Math.ceil(e/ve)))}let p=a*(f===1?1:1-.03**(1/f)),m=3*Math.cbrt(r.massRatio),h=q(`--fg`);e.strokeStyle=h,e.fillStyle=h,e.lineWidth=1.5,e.lineCap=`round`,e.globalAlpha=p;for(let t=0;t<f;t++){let{th1:n,th2:r}=J(i-o*t/Math.max(1,f-1)),a=u+l*1*Math.sin(n),c=d+l*1*Math.cos(n),p=a+l*s*Math.sin(r),h=c+l*s*Math.cos(r);e.beginPath(),e.moveTo(u,d),e.lineTo(a,c),e.lineTo(p,h),e.stroke(),e.beginPath(),e.arc(a,c,3,0,2*Math.PI),e.moveTo(p+m,h),e.arc(p,h,m,0,2*Math.PI),e.fill()}e.globalAlpha=a,e.beginPath(),e.arc(u,d,1.5,0,2*Math.PI),e.fill(),e.globalAlpha=1}function Q(){let e=t(),n=L(),a=performance.now()/1e3,o=a-Y;Y=a,o>0&&o<.1&&(X+=(o-X)*.1);let s=q(`--fg`),c=q(`--dim`);{let t=ce(r),a=r.clientWidth,l=r.clientHeight;t.clearRect(0,0,a,l);let u=Math.PI,d=e.plotP;if(e.plotZoom===`fit energy`&&i){let e=Math.max(1e-6,i.energyNorm()),t=e*i.vTop,n=i.cfg.m2,r=i.cfg.l2,a=i.cfg.g,o=t>=2*n*a*r?Math.PI:Math.acos(1-t/(n*a*r));u=Math.min(Math.PI,1.08*o),d=1.08*Math.sqrt(2*e)}let f=o>0&&o<.5?1-Math.exp(-o/Math.max(.01,e.zoomSmooth)):1;T*=Math.exp(f*Math.log(u/T)),E*=Math.exp(f*Math.log(d/E));let p=(a/2-8)/T,m=(l/2-8)/E,h=e=>a/2+p*e,g=e=>l/2-m*e;if(t.strokeStyle=c,t.lineWidth=1,t.beginPath(),t.moveTo(8,l/2),t.lineTo(a-8,l/2),t.moveTo(a/2,8),t.lineTo(a/2,l-8),t.stroke(),e.orbits){let r=e.orbitXfade,i=e.orbitAlpha,a=e.orbitSize;A=A.filter(e=>e.retiredAt===null||n-e.retiredAt<r),t.fillStyle=s;for(let e of A){t.globalAlpha=i*(e.retiredAt===null?1:Math.max(0,1-(n-e.retiredAt)/r)),t.beginPath();let o=e.pts;for(let e=0;e<o.length;e+=2)t.rect(h(o[e])-a/2,g(o[e+1])-a/2,a,a);t.fill()}t.globalAlpha=1}let _=e.fade,v=e.pointSize,y=0;for(;y<w.length&&n-w[y].t>4.6*_;)y++;y>0&&w.splice(0,y),t.fillStyle=s;for(let e of w){let r=n-e.t;if(r<0)break;t.globalAlpha=Math.exp(-r/_),t.beginPath(),t.arc(h(e.th2),g(e.p2),v/2,0,2*Math.PI),t.fill(),r<.4&&(t.globalAlpha=1-r/.4,t.strokeStyle=s,t.beginPath(),t.arc(h(e.th2),g(e.p2),v/2+3+12*r,0,2*Math.PI),t.stroke())}t.globalAlpha=1,Z(t,a,l,e,n)}}function $(){let e=t(),n=L(),r=performance.now()/1e3;return r-F>1&&(ee=P/(r-F||1),P=0,F=r),{time:`${n.toFixed(1)} / ${I.length().toFixed(0)} s`,"energy target":K(e,n).toFixed(4),energy:i?i.energyNorm().toFixed(4):`–`,notes:String(b),"seed used":y?String(y):`–`,hum:d?.describe?.()||`–`,"orbit portrait":(()=>{let e=A.find(e=>e.retiredAt===null);return e?`E ${e.energy.toFixed(4)}, ${e.pts.length/2} pts, ${Math.round(ee)}/s`:`–`})()}}return I}var J={id:`01-poincare`,title:`poincaré`,schema:[{group:`form`,key:`duration`,label:`duration`,kind:`number`,default:60,min:10,max:600,step:1,unit:`s`,hint:`energy returns to zero at this time`},{group:`form`,key:`peakTime`,label:`peak at`,kind:`number`,default:25,min:1,max:600,step:.5,unit:`s`},{group:`form`,key:`holdTime`,label:`hold`,kind:`number`,default:10,min:0,max:600,step:.5,unit:`s`},{group:`form`,key:`energyStart`,label:`start energy`,kind:`number`,default:.005,min:1e-4,max:1,log:!0},{group:`form`,key:`energyPeak`,label:`peak energy`,kind:`number`,default:1.2,min:.01,max:5,log:!0},{group:`form`,key:`riseShape`,label:`rise shape`,kind:`select`,default:`exponential`,options:[`exponential`,`linear`]},{group:`form`,key:`riseCurve`,label:`rise curve`,kind:`number`,default:1,min:.2,max:5,log:!0,hint:`exponent on the rise; >1 starts slow`},{group:`form`,key:`fallCurve`,label:`fall curve`,kind:`number`,default:1,min:.2,max:5,log:!0,hint:`exponent on the fall; >1 drops fast then lingers`},{group:`form`,key:`restEnergy`,label:`rest energy`,kind:`number`,default:.001,min:1e-5,max:.05,log:!0,hint:`after duration, the pendulum counts as at rest below this energy: no more crossings; the last note rings out`},{group:`form`,key:`finalHold`,label:`final hold`,kind:`number`,default:2,min:0,max:20,step:.1,unit:`s`,hint:`the last note sustains this long…`},{group:`form`,key:`finalFade`,label:`final fade`,kind:`number`,default:5,min:.1,max:30,step:.1,unit:`s`,hint:`…then fades out over this long; the piece ends with it`},{group:`physics`,key:`speed`,label:`speed`,kind:`number`,default:12,min:.5,max:100,log:!0,unit:`×`,hint:`simulated seconds per real second`},{group:`physics`,key:`massRatio`,label:`m2 / m1`,kind:`number`,default:1,min:.1,max:10,log:!0},{group:`physics`,key:`lengthRatio`,label:`l2 / l1`,kind:`number`,default:1,min:.1,max:10,log:!0},{group:`physics`,key:`tau`,label:`energy follow`,kind:`number`,default:2,min:.1,max:50,log:!0,unit:`sim s`,hint:`how quickly the energy tracks its target`},{group:`physics`,key:`seed`,label:`seed`,kind:`number`,default:0,min:0,max:999999,step:1,hint:`0 = a new variation every play`},{group:`notes`,key:`noteInstrument`,label:`instrument`,kind:`select`,default:`placeholder tone`,options:Object.keys(oe),hint:`modal: … instruments come from the modal-synth project`},{group:`notes`,key:`modalCustom`,label:`modal custom`,kind:`text`,default:``,hint:`for “modal: custom”: paste JSON from modal-synth’s Copy button`},{group:`notes`,key:`scale`,label:`scale`,kind:`select`,default:`pentatonic minor`,options:ce},{group:`notes`,key:`root`,label:`root`,kind:`select`,default:`D`,options:le},{group:`notes`,key:`pitchSource`,label:`pitch from θ2`,kind:`select`,default:`signed`,options:[`signed`,`absolute`],hint:`signed: −range→low, +range→high. absolute: 0→low, ±range→high`},{group:`notes`,key:`thetaRange`,label:`θ2 range`,kind:`number`,default:3.1416,min:.02,max:3.1416,log:!0,unit:`rad`},{group:`notes`,key:`pitchLow`,label:`low pitch`,kind:`number`,default:50,min:12,max:120,step:.5,unit:`midi`},{group:`notes`,key:`pitchHigh`,label:`high pitch`,kind:`number`,default:86,min:12,max:120,step:.5,unit:`midi`},{group:`notes`,key:`pitchCurve`,label:`pitch curve`,kind:`number`,default:1,min:.2,max:5,log:!0},{group:`notes`,key:`invertPitch`,label:`invert pitch`,kind:`bool`,default:!1},{group:`notes`,key:`p2Ref`,label:`|p2| for full`,kind:`number`,default:1,min:.01,max:4,log:!0,hint:`|p2| that gives full loudness`},{group:`notes`,key:`loudCurve`,label:`loudness curve`,kind:`number`,default:1,min:.2,max:5,log:!0},{group:`notes`,key:`loudFloor`,label:`loudness floor`,kind:`number`,default:.08,min:0,max:1,step:.01,hint:`loudness of a crossing with p2 = 0`},{group:`notes`,key:`notesLevel`,label:`level`,kind:`number`,default:-6,min:-48,max:6,step:.5,unit:`dB`},{group:`notes`,key:`noteLength`,label:`length`,kind:`number`,default:1.5,min:.05,max:10,log:!0,unit:`s`},{group:`notes`,key:`panAmount`,label:`pan from θ2`,kind:`number`,default:.6,min:0,max:1,step:.01,hint:`placeholder tone only; modal instruments have their own stereo image`},{group:`hum`,key:`humInstrument`,label:`instrument`,kind:`select`,default:`modal: Clarinet-ish`,options:Object.keys(se),hint:`modal: … = one held note of a sustained modal-synth preset`},{group:`hum`,key:`humCustom`,label:`modal custom`,kind:`text`,default:``,hint:`for “modal: custom”: paste JSON from modal-synth’s Copy button`},{group:`hum`,key:`humPitch`,label:`pitch`,kind:`number`,default:38,min:12,max:72,step:.5,unit:`midi`},{group:`hum`,key:`humLevel`,label:`level`,kind:`number`,default:-24,min:-60,max:0,step:.5,unit:`dB`},{group:`hum`,key:`humFollow`,label:`loudness follows energy`,kind:`number`,default:0,min:0,max:1,step:.01,hint:`0 = constant loudness`},{group:`hum`,key:`humNormalize`,label:`normalize loudness`,kind:`bool`,default:!0,hint:`modal hum: measure the output and compensate slowly, so timbre changes don't change loudness`},{group:`hum`,key:`humColorMode`,label:`timbre from energy`,kind:`select`,default:`log`,options:[`log`,`power`],hint:`log: even steps per energy doubling, from start energy (0) to peak (1). power: (energy / peak)^curve`},{group:`hum`,key:`humColorCurve`,label:`timbre curve`,kind:`number`,default:1,min:.1,max:5,log:!0,hint:`exponent applied to the timbre value`},{group:`hum`,key:`humTarget1`,label:`timbre → A`,kind:`select`,default:`pickup`,options:[`none`,...L],hint:`modal hum: synth setting driven by timbre (bow position, force, pressure, feedback, …)`},{group:`hum`,key:`humFrom1`,label:`A at low energy`,kind:`number`,default:.15,min:0,max:1,step:.005,hint:`fraction of the setting's range in modal-synth`},{group:`hum`,key:`humTo1`,label:`A at peak`,kind:`number`,default:.75,min:0,max:1,step:.005},{group:`hum`,key:`humTarget2`,label:`timbre → B`,kind:`select`,default:`tilt`,options:[`none`,...L]},{group:`hum`,key:`humFrom2`,label:`B at low energy`,kind:`number`,default:.3333,min:0,max:1,step:.005},{group:`hum`,key:`humTo2`,label:`B at peak`,kind:`number`,default:.5833,min:0,max:1,step:.005},{group:`hum`,key:`humFadeIn`,label:`fade in`,kind:`number`,default:3,min:0,max:60,step:.5,unit:`s`},{group:`hum`,key:`humFadeOut`,label:`fade out`,kind:`number`,default:6,min:0,max:60,step:.5,unit:`s`,hint:`ends together with the last note's fade`},{group:`visual`,key:`pendulumAlpha`,label:`pendulum opacity`,kind:`number`,default:1,min:0,max:1,step:.01,hint:`0 = hide the pendulum`},{group:`visual`,key:`pendulumSize`,label:`pendulum size`,kind:`number`,default:.32,min:.1,max:1,step:.01,hint:`inset diameter, as a fraction of the plot (upper-left corner)`},{group:`visual`,key:`motionBlur`,label:`motion blur`,kind:`number`,default:1,min:0,max:4,step:.05,hint:`pendulum shutter, in display frames; 0 = off`},{group:`visual`,key:`fade`,label:`point fade`,kind:`number`,default:10,min:.2,max:120,log:!0,unit:`s`},{group:`visual`,key:`plotZoom`,label:`plot zoom`,kind:`select`,default:`fit energy`,options:[`fit energy`,`fixed`],hint:`fit energy: frame the region the pendulum can reach at its current energy`},{group:`visual`,key:`zoomSmooth`,label:`zoom smoothing`,kind:`number`,default:1.5,min:.05,max:20,log:!0,unit:`s`,hint:`time constant of zoom changes`},{group:`visual`,key:`plotP`,label:`fixed p2 range`,kind:`number`,default:1.5,min:.05,max:5,log:!0},{group:`visual`,key:`pointSize`,label:`point size`,kind:`number`,default:2,min:.5,max:8,step:.1,unit:`px`},{group:`orbits`,key:`orbits`,label:`show orbits`,kind:`bool`,default:!0},{group:`orbits`,key:`orbitCount`,label:`orbits`,kind:`number`,default:24,min:1,max:64,step:1,hint:`trajectories integrated in parallel, all at the portrait's energy`},{group:`orbits`,key:`orbitCpu`,label:`cpu`,kind:`number`,default:.4,min:.02,max:.9,step:.01,hint:`fraction of one core the background computation may use`},{group:`orbits`,key:`orbitLife`,label:`life`,kind:`number`,default:300,min:10,max:5e3,log:!0,hint:`crossings before an orbit is reseeded elsewhere on the section`},{group:`orbits`,key:`orbitBand`,label:`refresh at`,kind:`number`,default:.25,min:.01,max:2,log:!0,hint:`start a new portrait when the energy has changed by this fraction`},{group:`orbits`,key:`orbitMinHold`,label:`min hold`,kind:`number`,default:3,min:0,max:30,step:.1,unit:`s`,hint:`a portrait is kept at least this long`},{group:`orbits`,key:`orbitMaxPoints`,label:`max points`,kind:`number`,default:8e3,min:500,max:4e4,log:!0,hint:`a portrait stops computing (and using CPU) once it has this many points`},{group:`orbits`,key:`orbitXfade`,label:`crossfade`,kind:`number`,default:1.5,min:.05,max:10,log:!0,unit:`s`,hint:`time for the old portrait to fade out once a new one starts`},{group:`orbits`,key:`orbitAlpha`,label:`brightness`,kind:`number`,default:.3,min:.02,max:1,step:.01},{group:`orbits`,key:`orbitSize`,label:`point size`,kind:`number`,default:1,min:.5,max:4,step:.1,unit:`px`}],defaults:f,create:q},Y=`double pendulum`,X=[J],Z=document.getElementById(`app`),Q=null;function $(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n),r}function ye(){Q?.(),Q=null,Z.replaceChildren();let e=location.hash.replace(/^#\/?/,``).split(`/`).filter(Boolean),t=X.find(t=>t.id===e[0]);if(!t)return be();Q=we(t,e[1]===`edit`)}function be(){document.title=Y;let e=$(`ol`,{className:`tracks`});for(let t of X)e.append($(`li`,{},$(`a`,{href:`#/${t.id}`,textContent:t.title})));Z.append($(`main`,{className:`album`},$(`h1`,{textContent:Y}),e))}var xe=e=>`double-pendulum:author:${e.id}`;function Se(e){try{let t=localStorage.getItem(xe(e));return t?JSON.parse(t):null}catch{return null}}function Ce(e,t){try{localStorage.setItem(xe(e),JSON.stringify(t))}catch{}}function we(e,n){let r=X.indexOf(e)+1;document.title=`${e.title} · ${Y}`;let a=()=>i(e.schema,e.defaults),o=n?i(e.schema,e.defaults,Se(e)):a(),s=$(`div`,{className:`view`}),c=$(`button`,{className:`play`,textContent:`play`}),l=$(`div`,{className:`bar`}),u=$(`div`,{className:`progress`},l),f=$(`a`,{className:`edit`,href:n?`#/${e.id}`:`#/${e.id}/edit`,textContent:n?`done`:`edit`}),p=$(`main`,{className:`stage`},$(`header`,{},$(`a`,{href:`#/`,textContent:Y}),$(`span`,{className:`sep`,textContent:` / `}),$(`span`,{textContent:`${r}. ${e.title}`})),s,$(`div`,{className:`transport`},c,u,f)),m=$(`div`,{className:n?`page with-author`:`page`},p);Z.append(m);let h=e.create(s,()=>o),g={value:0},_=async e=>{let n=await t();await h.start(n,e)};c.onclick=()=>h.playing?h.stop():_(n?g.value:0),n&&(u.classList.add(`seekable`),u.onclick=e=>{let t=u.getBoundingClientRect(),n=Math.max(0,(e.clientX-t.left)/t.width*h.length());_(n)});let v=null;n&&(v=d({schema:e.schema,get:()=>o,set:t=>{o=t,Ce(e,t)},defaults:a,readouts:()=>h.readouts(),startAt:g}),m.append(v.el));let y=e=>{let t=e.target.tagName;e.code===`Space`&&t!==`INPUT`&&t!==`SELECT`&&t!==`BUTTON`&&(e.preventDefault(),c.click())};window.addEventListener(`keydown`,y);let b=0,x=0,S=e=>{h.draw(),c.textContent=h.playing?`stop`:`play`,l.style.width=`${Math.min(100,100*h.now()/h.length())}%`,v&&e-x>200&&(v.updateReadouts(),x=e),b=requestAnimationFrame(S)};return b=requestAnimationFrame(S),()=>{cancelAnimationFrame(b),window.removeEventListener(`keydown`,y),h.dispose()}}window.addEventListener(`hashchange`,ye),ye();
\ No newline at end of file
site/assets/index-EgyvN0Ym.cssadded+1−0View file
@@ -0,0 +1 @@
1+:root{--bg:#0b0b0b;--fg:#d8d8d8;--dim:#2e2e2e;--muted:#777;--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark}*{box-sizing:border-box}html,body{background:var(--bg);color:var(--fg);margin:0}body{font:14px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}a{color:var(--fg);text-decoration:none}a:hover{text-decoration:underline}button{font:inherit;color:var(--fg);border:1px solid var(--dim);cursor:pointer;background:0 0;padding:2px 10px}button:hover{border-color:var(--muted)}.album{max-width:640px;margin:15vh auto;padding:0 16px}.album h1{margin:0 0 24px;font-size:18px;font-weight:400}.tracks{padding-left:1.5em}.page{min-height:100vh;display:flex}.stage{flex-direction:column;flex:1;gap:12px;min-width:0;padding:16px;display:flex}header,header a{color:var(--muted)}.sep{color:var(--dim)}.view{flex:1;justify-content:center;align-items:center;min-height:0;display:flex}.view canvas{aspect-ratio:1;width:min(90vw,80vh);display:block}.page.with-author .view canvas{width:min(100vw - 420px,80vh)}@media (max-width:720px){.page{flex-direction:column}.view canvas,.page.with-author .view canvas{width:min(100vw - 32px,70vh)}}.transport{align-items:center;gap:12px;display:flex}.transport .play{min-width:64px}.progress{background:var(--dim);flex:1;height:1px;position:relative}.progress.seekable{cursor:pointer;background:linear-gradient(var(--dim), var(--dim)) center / 100% 1px no-repeat;height:9px}.progress .bar{background:var(--fg);width:0;height:1px;margin-top:-.5px;position:absolute;top:50%;left:0}.edit{color:var(--muted)}.author{border-left:1px solid var(--dim);flex:none;width:360px;height:100vh;padding:12px;font-size:12px;position:sticky;top:0;overflow-y:auto}@media (max-width:720px){.author{border-left:none;border-top:1px solid var(--dim);width:auto;height:auto;position:static}}.author .actions{flex-wrap:wrap;align-items:center;gap:6px;margin-bottom:10px;display:flex}.author .status{color:var(--muted)}.author fieldset{border:none;border-top:1px solid var(--dim);margin:10px 0 0;padding:6px 0 0}.author legend{color:var(--muted);padding:0 6px 0 0}.author .row{grid-template-columns:110px 1fr 64px 36px;align-items:center;gap:6px;margin:3px 0;display:grid}.author .row>span:first-child{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}:is(.author .row:has(select),.author .row:has(input[type=checkbox])){grid-template-columns:110px 1fr}.author .row:has(select) select{justify-self:start}.author .row:has(input[type=checkbox]) input{justify-self:start}.author>.row{grid-template-columns:110px 80px}.author input[type=number],.author select{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--dim);width:100%;padding:1px 3px}.author input[type=range]{width:100%;accent-color:var(--muted)}.author .unit{color:var(--muted)}.readouts{color:var(--muted);grid-template-columns:110px 1fr;gap:2px 6px;margin:8px 0;display:grid}.readouts dt,.readouts dd{margin:0}.readouts dd{color:var(--fg)}.author .row.text{grid-template-columns:110px 1fr;align-items:start}.author textarea{font:inherit;color:var(--fg);background:var(--bg);border:1px solid var(--dim);resize:vertical;width:100%;font-size:11px}
site/assets/orbitWorker-Da4eRcGA.jsadded+1−0View file
@@ -0,0 +1 @@
1+var e=class{cfg;y=/* @__PURE__ */ new Float64Array(4);t=0;eTarget=0;tau=2;controlled=!0;k1=/* @__PURE__ */ new Float64Array(4);k2=/* @__PURE__ */ new Float64Array(4);k3=/* @__PURE__ */ new Float64Array(4);k4=/* @__PURE__ */ new Float64Array(4);tmp=/* @__PURE__ */ new Float64Array(4);constructor(e){this.cfg={...e}}get vTop(){let{m1:e,m2:t,l1:n,l2:r,g:i}=this.cfg;return 2*(e+t)*i*n+2*t*i*r}get p2Scale(){let{m2:e,l2:t}=this.cfg;return Math.sqrt(e*t*t*this.vTop)}derived(e=this.y){let{m1:t,m2:n,l1:r,l2:i,g:a}=this.cfg,[o,s,c,l]=[e[0],e[1],e[2],e[3]],u=o-s,d=Math.cos(u),f=Math.sin(u),p=t+n*f*f,m=(i*c-r*l*d)/(r*r*i*p),h=(r*(t+n)*l-i*n*c*d)/(r*i*i*n*p);return{w1:m,w2:h,T:.5*(c*m+l*h),V:(t+n)*a*r*(1-Math.cos(o))+n*a*i*(1-Math.cos(s))}}energy(e=this.y){let t=this.derived(e);return t.T+t.V}energyNorm(){return this.energy()/this.vTop}deriv(e,t){let{m1:n,m2:r,l1:i,l2:a,g:o}=this.cfg,s=e[0],c=e[1],l=e[2],u=e[3],d=s-c,f=Math.cos(d),p=Math.sin(d),m=n+r*p*p,h=(a*l-i*u*f)/(i*i*a*m),g=(i*(n+r)*u-a*r*l*f)/(i*a*a*r*m),_=l*u*p/(i*a*m),v=(a*a*r*l*l+i*i*(n+r)*u*u-2*i*a*r*l*u*f)*Math.sin(2*d)/(2*i*i*a*a*m*m),y=.5*(l*h+u*g),b=(n+r)*o*i*(1-Math.cos(s))+r*o*a*(1-Math.cos(c)),x=0;if(this.controlled){let e=.02*this.vTop,t=4/this.tau;x=(this.eTarget-(y+b))/(this.tau*(2*y+e)),x>t?x=t:x<-t&&(x=-t)}t[0]=h,t[1]=g,t[2]=-(n+r)*o*i*Math.sin(s)-_+v+x*l,t[3]=-r*o*a*Math.sin(c)+_-v+x*u}step(e){let{y:t,k1:n,k2:r,k3:i,k4:a,tmp:o}=this;this.deriv(t,n);for(let r=0;r<4;r++)o[r]=t[r]+.5*e*n[r];this.deriv(o,r);for(let n=0;n<4;n++)o[n]=t[n]+.5*e*r[n];this.deriv(o,i);for(let n=0;n<4;n++)o[n]=t[n]+e*i[n];this.deriv(o,a);for(let o=0;o<4;o++)t[o]+=e/6*(n[o]+2*r[o]+2*i[o]+a[o]);this.t+=e}randomize(e,t){let{m1:n,m2:r,l1:i,l2:a}=this.cfg,o=Math.max(e,1e-6)*this.vTop,s=Math.min(Math.PI,3*Math.sqrt(o/(r*this.cfg.g*Math.min(i,a)))),c=0,l=0,u=0;for(let e=0;e<1e3&&(c=(2*t()-1)*s,l=(2*t()-1)*s,u=this.derived([c,l,0,0]).V,!(u<.9*o));e++)c=l=0,u=0;let d=o-u,f=t()*2*Math.PI,p=Math.cos(f),m=Math.sin(f),h=Math.cos(c-l),g=(n+r)*i*i,_=r*i*a*h,v=r*a*a,y=.5*(g*p*p+2*_*p*m+v*m*m),b=Math.sqrt(d/y),x=b*p,S=b*m;this.y[0]=c,this.y[1]=l,this.y[2]=g*x+_*S,this.y[3]=_*x+v*S,this.t=0}};function t(e,t,n){let{m1:r,m2:i,l1:a,l2:o,g:s}=e.cfg,c=t*e.vTop,l=Math.sqrt(2*c*i*o*o*(1+i/r))+1e-12;for(let t=0;t<400;t++){let t=(2*n()-1)*Math.PI,u=(2*n()-1)*l,d=i*s*o*(1-Math.cos(t));if(d>=c)continue;let f=Math.cos(-t),p=Math.sin(-t),m=r+i*p*p,h=i*o*o,g=-2*i*a*o*u*f,_=(r+i)*a*a*u*u-2*i*a*a*o*o*m*(c-d),v=g*g-4*h*_;if(v<0)continue;let y=(-g+Math.sqrt(v))/(2*h);return e.y[0]=0,e.y[1]=t,e.y[2]=y,e.y[3]=u,e.t=0,!0}return!1}function n(e){return Math.atan2(Math.sin(e),Math.cos(e))}function r(e){let t=e>>>0;return()=>{t=t+0x6d2b79f5>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}let i=null,a=null;const o=r(Math.random()*2**31|0);let s=0,c=0,l=0,u=0,d=0,f=0,p=[];self.onmessage=e=>{let t=i?.reset??!1;i=e.data,i.reset||=t,i.running&&a===null&&(a=setTimeout(g,0))};function m(e){s++,c=e.energy,l=performance.now(),u=0,d=e.m2,f=e.l2,p=[]}function h(e){e.crossings=0,e.prev=0,e.ok=t(e.pend,c,o)}function g(){a=null;let t=i;if(!t||!t.running)return;let r=e=>a=setTimeout(g,e);if(t.energy<1e-5)return void r(100);let o=(performance.now()-l)/1e3,_=c>0?Math.abs(Math.log(t.energy/c)):1/0;if((s===0||t.reset||t.m2!==d||t.l2!==f||_>Math.log(1+t.band)&&o>=t.minHold)&&(t.reset=!1,m(t)),u>=t.maxPoints)return void r(50);let v=Math.max(1,Math.round(t.count));for(;p.length<v;){let t=new e({m1:1,l1:1,g:1,m2:d,l2:f});t.controlled=!1;let n={pend:t,crossings:0,prev:0,ok:!1};h(n),p.push(n)}p.length>v&&(p.length=v);let y=[],b=performance.now();for(;performance.now()-b<8;)for(let e of p){if((!e.ok||e.crossings>=t.life)&&(h(e),!e.ok))continue;let r=e.pend,i=r.y;for(let t=0;t<100;t++){let t=i[1],a=i[3];r.step(.005);let o=n(i[0]);if(e.prev<0&&o>=0&&o-e.prev<Math.PI){let s=-e.prev/(o-e.prev);y.push(n(t+s*(i[1]-t)),(a+s*(i[3]-a))/r.p2Scale),e.crossings++}e.prev=o}}if(u+=y.length/2,y.length){let e=new Float32Array(y),t={gen:s,energy:c,pts:e};self.postMessage(t,[e.buffer])}let x=Math.max(.02,Math.min(1,t.cpu));r(8*(1-x)/x)}
\ No newline at end of file
site/assets/worklet-PIV7En5i.jsadded+1−0View file
@@ -0,0 +1 @@
1+const e=Math.SQRT2,t=Math.PI;function n(e,n){let r=Math.ceil(Math.abs(n)+e)+24,i=0;for(let a=0;a<=r;a++){let o=t*a/r;i+=(a===0||a===r?.5:1)*Math.cos(e*o-n*Math.sin(o))}return i/r}function r(e,t){let r=[],i=e===0?.5:e,a=n(e,i);for(let o=i+.05;o<=t;o+=.05){let t=n(e,o);if(a*t<0){let t=i,s=o,c=a;for(let r=0;r<50;r++){let r=.5*(t+s),i=n(e,r);c*i<=0?s=r:(t=r,c=i)}r.push(.5*(t+s))}i=o,a=t}return r}const i=[4.730040745,7.853204624,10.99560784,14.13716549,17.27875966],a=e=>e<i.length?i[e]:(2*e+3)*t/2;function o(e,t,n){if(t<12){let e=(Math.cosh(t)-Math.cos(t))/(Math.sinh(t)-Math.sin(t));return Math.cosh(t*n)+Math.cos(t*n)-e*(Math.sinh(t*n)+Math.sin(t*n))}let r=e%2==0?1:-1;return Math.cos(t*n)-Math.sin(t*n)+Math.exp(-t*n)+r*Math.exp(-t*(1-n))}const s=[[.5,2],[1,2],[1.2,3],[1.5,3],[2,4],[2.5,4],[2.67,3],[3,5],[4,6],[4.24,5],[5.33,7],[5.7,6],[6.67,8],[7.2,7],[8,9],[9,8],[10,10],[11.1,9],[12.1,11],[13.5,10]];function c(i,c,d,f,p=2){let m=new Float64Array(c),h=new Float64Array(c),g={kind:i,N:c,ratios:m,wavenum:h,aspect:d};switch(i){case`string`:case`free`:for(let e=0;e<c;e++){let t=e+1;m[e]=i===`string`?t:t**+f,h[e]=t}return{...g,view:`line`,dim:1,shape:(n,r)=>e*Math.sin((n+1)*t*r)};case`tube_co`:for(let e=0;e<c;e++)m[e]=2*e+1,h[e]=(2*e+1)/2;return{...g,view:`line`,dim:1,shape:(n,r)=>e*Math.cos((2*n+1)*t*r/2)};case`tube_oo`:for(let e=0;e<c;e++)m[e]=e+1,h[e]=e+1;return{...g,view:`line`,dim:1,shape:(n,r)=>e*Math.cos((n+1)*t*r)};case`bar`:{let e=a(0),n=new Float64Array(c),r=2048;for(let i=0;i<c;i++){let s=a(i);m[i]=(s/e)**2,h[i]=s/t;let c=0;for(let e=0;e<r;e++)c+=o(i,s,(e+.5)/r)**2;n[i]=1/Math.sqrt(c/r)}return{...g,view:`line`,dim:1,shape:(e,t)=>n[e]*o(e,a(e),t)}}case`ring`:{let n=[],r=[],i=0,a=0,o=2;for(;n.length<c;){i<s.length?[a,o]=s[i]:(a*=1.09,o+=+(i%2==0));for(let e=0;e<2&&n.length<c;e++)m[n.length]=a*(e===0?1:1+6e-4*(1+i%3)),h[n.length]=2*o,n.push(o),r.push(e);i++}return{...g,view:`ring`,dim:1,shape:(i,a)=>{let o=2*t*a*n[i];return e*(r[i]===0?Math.cos(o):Math.sin(o))}}}case`plate`:{let e=Math.ceil(3*Math.sqrt(c))+3,n=[];for(let t=1;t<=e;t++)for(let r=1;r<=e;r++)n.push([t*t+(r/d)**2,t,r]);n.sort((e,t)=>e[0]-t[0]);let r=new Int32Array(c),i=new Int32Array(c),a=n[0][0];for(let e=0;e<c;e++){let[t,o,s]=n[e];m[e]=t/a,h[e]=Math.sqrt(o*o+(s/d)**2),r[e]=o,i[e]=s}return{...g,view:`rect`,dim:2,shape:(e,n,a)=>2*Math.sin(r[e]*t*n)*Math.sin(i[e]*t*a)}}case`membrane`:{let i=2*Math.sqrt(c)+6,a=[];for(;;){a=[];for(let e=0;e<=Math.ceil(i);e++)for(let t of r(e,i))a.push([t,e,0]),e>0&&a.push([t,e,1]);if(a.length>=c)break;i*=1.3}a.sort((e,t)=>e[0]-t[0]||e[2]-t[2]);let o=a[0][0],s=new Int32Array(c),l=new Int32Array(c),d=new Float64Array(c),f=new Float64Array(c);for(let r=0;r<c;r++){let[i,c,u]=a[r];m[r]=i/o,h[r]=i/t,s[r]=c,l[r]=u,d[r]=i,f[r]=c===0?1/Math.abs(n(1,i)):e/Math.abs(n(c+1,i))}return u(g,s,l,d,f)}case`disc`:{let e=p,n=Math.ceil(Math.sqrt(2*c))+4,r=[];for(let t=0;t<=n;t++)for(let i=0;t+2*i<=n;i++){if(i===0&&t<2)continue;let n=(t+2.1*i)**+e;r.push([n,t,i,0]),t>0&&r.push([n*1.0004,t,i,1])}r.sort((e,t)=>e[0]-t[0]);let i=r.slice(0,c),a=i.reduce((e,t)=>Math.max(e,t[1]),0),o=i.reduce((e,t)=>Math.max(e,t[2]),0),s=[];for(let e=0;e<=a;e++)s.push(l(e,o+1));let d=new Int32Array(c),f=new Int32Array(c),_=new Float64Array(c),v=i[0][0];for(let e=0;e<c;e++){let[n,r,a,o]=i[e];m[e]=n/v,d[e]=r,f[e]=o,_[e]=s[r][r===0?a-1:a],h[e]=_[e]/t}return u(g,d,f,_,null)}}}function l(e,t){let r=t=>e===0?-n(1,t):.5*(n(e-1,t)-n(e+1,t)),i=[],a=e===0?.5:Math.max(.3,e*.8),o=r(a);for(let e=a+.05;i.length<t;e+=.05){let t=r(e);if(o*t<0){let t=a,n=e,s=o;for(let e=0;e<50;e++){let e=.5*(t+n),i=r(e);s*i<=0?n=e:(t=e,s=i)}i.push(.5*(t+n))}a=e,o=t}return i}function u(e,t,r,i,a){let o=e.N,s=Array(o).fill(null),c=a??new Float64Array(o),l=(e,r)=>{let o=s[e];if(!o){o=/* @__PURE__ */ new Float64Array(258);for(let r=0;r<=256;r++)o[r]=n(t[e],i[e]*r/256);if(o[257]=o[256],s[e]=o,!a){let n=0;for(let e=0;e<=256;e++)n+=(e===0||e===256?.5:1)*o[e]*o[e]*e/256/256;c[e]=1/Math.sqrt(Math.max(1e-12,(t[e]===0?2:1)*n))}}let l=r*256,u=Math.floor(l),d=l-u;return o[u]*(1-d)+o[u+1]*d};return{...e,view:`disk`,dim:2,shape:(e,n,i)=>{let a=2*n-1,o=2*i-1,s=Math.hypot(a,o);if(s>=1)return 0;let u=l(e,s),d=t[e],f=d===0?1:r[e]===0?Math.cos(d*Math.atan2(o,a)):Math.sin(d*Math.atan2(o,a));return c[e]*u*f}}}const d=(e,t)=>e[t],f=(e,t)=>e[t],p=e=>e.geometry===`membrane`||e.geometry===`plate`||e.geometry===`disc`,m=(...e)=>t=>e.includes(t.geometry),h=(...e)=>t=>e.includes(t.exciter),g=[`bow`,`reed`,`selfosc`,`noise`],_=[[`off`,`Off`],[`pitch`,`Pitch`],[`amp`,`Amplitude`],[`position`,`Excite position`],[`pickup`,`Pickup position`],[`tension`,`Tension coupling`],[`cascade`,`Cascade coupling`],[`damping`,`Damping`],[`feedback`,`Feedback gain`],[`exciter`,`Exciter intensity`]],v=[[`sine`,`Sine`],[`tri`,`Triangle`],[`saw`,`Saw`],[`square`,`Square`],[`sh`,`Sample & hold`],[`smooth`,`Smooth random`]];function y(e){let t=t=>t[`lfo${e}Target`]!==`off`;return[{kind:`enum`,id:`lfo${e}Target`,label:`LFO ${e} →`,group:`Modulation`,options:_,def:`off`},{kind:`enum`,id:`lfo${e}Shape`,label:`Shape`,group:`Modulation`,options:v,def:`sine`,show:t},{kind:`num`,id:`lfo${e}Rate`,label:`Rate`,group:`Modulation`,min:.01,max:40,def:1,scale:`log`,unit:`Hz`,show:t},{kind:`num`,id:`lfo${e}Depth`,label:`Depth`,group:`Modulation`,min:0,max:1,def:.3,scale:`pow2`,show:t}]}const b=[{kind:`enum`,id:`geometry`,label:`Geometry`,group:`Body`,model:!0,def:`string`,options:[[`string`,`String`],[`bar`,`Bar (free–free)`],[`tube_co`,`Tube (closed–open)`],[`tube_oo`,`Tube (open–open)`],[`membrane`,`Membrane (circular)`],[`plate`,`Plate (rectangular)`],[`disc`,`Disc (cymbal / gong)`],[`ring`,`Bell / ring`],[`free`,`Free spectrum (kᵖ)`]],hint:`Sets the mode frequency ratios and mode shapes`},{kind:`num`,id:`modes`,label:`Modes`,group:`Body`,min:4,max:256,def:64,int:!0,model:!0,scale:`log`},{kind:`num`,id:`aspect`,label:`Aspect ratio`,group:`Body`,min:.2,max:1,def:.71,model:!0,show:m(`plate`)},{kind:`num`,id:`powerExp`,label:`Exponent p`,group:`Body`,min:.3,max:3,def:1.5,model:!0,show:m(`free`)},{kind:`num`,id:`discExp`,label:`Chladni exponent`,group:`Body`,min:1,max:2.5,def:2,model:!0,show:m(`disc`),hint:`f ∝ (m + 2n)^p: 2 = flat plate; lower for domed cymbals and gongs`},{kind:`num`,id:`stretch`,label:`Stretch`,group:`Body`,min:.5,max:2,def:1,model:!0,digits:3,hint:`ratio → ratio^s (bar with s≈1.368 gives the 1:4:10 marimba tuning)`},{kind:`num`,id:`inharm`,label:`Stiffness B`,group:`Body`,min:0,max:.05,def:0,scale:`pow2`,model:!0,digits:5,hint:`ratio·√(1+B·ratio²): piano-like stretched partials`},{kind:`num`,id:`harmonize`,label:`Harmonize`,group:`Body`,min:0,max:1,def:0,model:!0,hint:`pull partials toward integer multiples`},{kind:`num`,id:`jitter`,label:`Detune jitter`,group:`Body`,min:0,max:200,def:0,scale:`pow2`,unit:`¢`,model:!0},{kind:`num`,id:`seed`,label:`Seed`,group:`Body`,min:1,max:999,def:1,int:!0,model:!0,hint:`random detune, coupling topology and radiation`},{kind:`num`,id:`t60`,label:`Decay T60`,group:`Damping`,min:.05,max:60,def:4,scale:`log`,unit:`s`},{kind:`num`,id:`hfDamp`,label:`HF damping`,group:`Damping`,min:0,max:100,def:2,scale:`pow2`,unit:`/s@1k`,hint:`extra decay rate σ = c·(f/1kHz)²`},{kind:`num`,id:`damper`,label:`Damper T60`,group:`Damping`,min:.02,max:20,def:.3,scale:`log`,unit:`s`,hint:`applied on key release; max = no damper`},{kind:`num`,id:`tension`,label:`Tension modulation`,group:`Nonlinear`,min:0,max:2,def:0,scale:`pow2`,digits:3,hint:`amplitude-dependent pitch (glides)`},{kind:`num`,id:`cascade`,label:`Cascade coupling`,group:`Nonlinear`,min:0,max:20,def:0,scale:`pow2`,digits:3,hint:`random quartic coupling: energy spreads across modes (gong/cymbal shimmer)`},{kind:`num`,id:`curvature`,label:`Curvature (3-wave)`,group:`Nonlinear`,min:0,max:3,def:0,scale:`pow2`,digits:3,hint:`quadratic forces: sum/difference tones, crashes`},{kind:`num`,id:`terms`,label:`Coupling terms`,group:`Nonlinear`,min:1,max:16,def:6,int:!0,model:!0},{kind:`num`,id:`nlModes`,label:`Coupled modes`,group:`Nonlinear`,min:4,max:128,def:48,int:!0,model:!0,scale:`log`},{kind:`num`,id:`glide`,label:`Pitch glide`,group:`Nonlinear`,min:-12,max:12,def:0,unit:`st`,hint:`pitch offset while loud, relaxing as the note decays: + falls (like tension), − rises (Chinese opera gong)`},{kind:`num`,id:`crossTension`,label:`Cross-note tension`,group:`Nonlinear`,min:0,max:2,def:0,scale:`pow2`,digits:3,hint:`notes share one tension: they bend each other`},{kind:`num`,id:`crossLink`,label:`Cross-note link`,group:`Nonlinear`,min:0,max:2,def:0,scale:`pow2`,digits:3,hint:`sympathetic coupling + intermodulation between notes`},{kind:`num`,id:`buzz`,label:`Barrier stiffness`,group:`Collision`,min:0,max:1,def:0,scale:`pow2`,digits:3,hint:`sitar bridge, snare wires, rattles`},{kind:`num`,id:`buzzGap`,label:`Gap`,group:`Collision`,min:0,max:2,def:.2,digits:3,show:e=>e.buzz>0},{kind:`num`,id:`buzzPos`,label:`Position`,group:`Collision`,min:0,max:1,def:.02,digits:3,show:e=>e.buzz>0},{kind:`num`,id:`buzzPosY`,label:`Position Y`,group:`Collision`,min:0,max:1,def:.5,show:e=>e.buzz>0&&p(e)},{kind:`enum`,id:`buzzSides`,label:`Barrier`,group:`Collision`,options:[[`one`,`One-sided (bridge)`],[`two`,`Two-sided (rattle)`]],def:`one`,show:e=>e.buzz>0},{kind:`enum`,id:`exciter`,label:`Key exciter`,group:`Exciter`,def:`strike`,options:[[`strike`,`Strike (hammer / mallet)`],[`pluck`,`Pluck`],[`impulse`,`Impulse`],[`bow`,`Bow`],[`reed`,`Reed / blow`],[`selfosc`,`Self-oscillator`],[`noise`,`Noise`]]},{kind:`num`,id:`strength`,label:`Strength`,group:`Exciter`,min:0,max:6,def:1,scale:`pow2`,hint:`>1 pushes the body into its nonlinear regime`},{kind:`num`,id:`exPos`,label:`Position`,group:`Exciter`,min:0,max:1,def:.13,digits:3},{kind:`num`,id:`exPosY`,label:`Position Y`,group:`Exciter`,min:0,max:1,def:.37,show:p},{kind:`num`,id:`exWidth`,label:`Contact width`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`},{kind:`num`,id:`hammerMass`,label:`Hammer mass`,group:`Exciter`,min:.005,max:5,def:.1,scale:`log`,digits:3,show:h(`strike`)},{kind:`num`,id:`hardness`,label:`Contact time`,group:`Exciter`,min:.05,max:20,def:1,scale:`log`,unit:`ms`,show:h(`strike`,`impulse`)},{kind:`num`,id:`feltExp`,label:`Felt exponent`,group:`Exciter`,min:1,max:4,def:2.5,show:h(`strike`)},{kind:`num`,id:`bowForce`,label:`Bow force`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:h(`bow`)},{kind:`num`,id:`bowSpeed`,label:`Bow speed`,group:`Exciter`,min:0,max:2,def:.4,scale:`pow2`,show:h(`bow`),hint:`scaled by key velocity: sets the loudness`},{kind:`num`,id:`bowNoise`,label:`Bow noise`,group:`Exciter`,min:0,max:1,def:0,scale:`pow2`,show:h(`bow`),hint:`random bow-force fluctuation: rosin and hair noise`},{kind:`num`,id:`reedPressure`,label:`Mouth pressure`,group:`Exciter`,min:0,max:1.5,def:.6,show:h(`reed`)},{kind:`num`,id:`reedGain`,label:`Reed opening`,group:`Exciter`,min:0,max:2,def:.5,show:h(`reed`)},{kind:`num`,id:`breath`,label:`Breath noise`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`,show:h(`reed`)},{kind:`num`,id:`selfGain`,label:`Negative damping`,group:`Exciter`,min:0,max:4,def:.5,scale:`pow2`,show:h(`selfosc`)},{kind:`num`,id:`selfSat`,label:`Saturation level`,group:`Exciter`,min:.02,max:4,def:.5,scale:`log`,show:h(`selfosc`)},{kind:`num`,id:`noiseLevel`,label:`Noise level`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:h(`noise`)},{kind:`num`,id:`noiseColor`,label:`Noise cutoff`,group:`Exciter`,min:50,max:16e3,def:3e3,scale:`log`,unit:`Hz`,show:h(`noise`,`reed`,`bow`)},{kind:`num`,id:`attack`,label:`Attack`,group:`Exciter`,min:1,max:3e3,def:40,scale:`log`,unit:`ms`,show:h(...g)},{kind:`num`,id:`release`,label:`Release`,group:`Exciter`,min:5,max:5e3,def:150,scale:`log`,unit:`ms`,show:h(...g)},{kind:`num`,id:`fbGain`,label:`Feedback gain`,group:`Feedback`,min:0,max:8,def:0,scale:`pow2`,hint:`output → delay → band-pass → saturate → back into the body (while a key is held)`},{kind:`num`,id:`fbDelay`,label:`Delay`,group:`Feedback`,min:.05,max:600,def:5,scale:`log`,unit:`ms`,show:e=>e.fbGain>0},{kind:`num`,id:`fbFreq`,label:`Band centre`,group:`Feedback`,min:30,max:12e3,def:800,scale:`log`,unit:`Hz`,show:e=>e.fbGain>0},{kind:`num`,id:`fbQ`,label:`Band Q`,group:`Feedback`,min:.3,max:30,def:1.5,scale:`log`,show:e=>e.fbGain>0},{kind:`num`,id:`fbSat`,label:`Saturation`,group:`Feedback`,min:.01,max:4,def:.4,scale:`log`,show:e=>e.fbGain>0},...y(1),...y(2),{kind:`num`,id:`vibDepth`,label:`Vibrato depth`,group:`Modulation`,min:0,max:100,def:0,scale:`pow2`,unit:`¢`,hint:`per-note vibrato, each note with its own phase and rate`},{kind:`num`,id:`vibRate`,label:`Vibrato rate`,group:`Modulation`,min:1,max:12,def:5.5,unit:`Hz`,show:e=>e.vibDepth>0},{kind:`num`,id:`vibDelay`,label:`Vibrato onset`,group:`Modulation`,min:0,max:2e3,def:300,unit:`ms`,show:e=>e.vibDepth>0,hint:`vibrato fades in after the note starts`},{kind:`num`,id:`bendRange`,label:`Pitch-bend range`,group:`Modulation`,min:0,max:24,def:2,int:!0,unit:`st`},{kind:`enum`,id:`soundbox`,label:`Soundbox`,group:`Soundbox`,def:`off`,options:[[`off`,`Off`],[`violin`,`Violin`],[`viola`,`Viola`],[`cello`,`Cello`],[`bass`,`Double bass`],[`guitar`,`Guitar`]],hint:`fixed resonances that every note passes through (they don't transpose)`},{kind:`num`,id:`boxSize`,label:`Size`,group:`Soundbox`,min:.4,max:3,def:1,scale:`log`,digits:3,show:e=>e.soundbox!==`off`,hint:`>1 lowers every resonance`},{kind:`num`,id:`boxDamp`,label:`Damping`,group:`Soundbox`,min:.3,max:4,def:1,scale:`log`,show:e=>e.soundbox!==`off`,hint:`scales every resonance's bandwidth`},{kind:`num`,id:`boxMix`,label:`Mix`,group:`Soundbox`,min:0,max:1,def:1,show:e=>e.soundbox!==`off`},{kind:`num`,id:`pickup`,label:`Pickup position`,group:`Output`,min:0,max:1,def:.77,digits:3},{kind:`num`,id:`pickupY`,label:`Pickup Y`,group:`Output`,min:0,max:1,def:.61,show:p},{kind:`num`,id:`width`,label:`Stereo width`,group:`Output`,min:0,max:1,def:.3,hint:`right pickup is offset from the left one`},{kind:`num`,id:`spread`,label:`Whole-body radiation`,group:`Output`,min:0,max:1,def:.2,hint:`0 = point pickup, 1 = every mode radiates equally`},{kind:`num`,id:`tilt`,label:`Spectral tilt`,group:`Output`,min:-12,max:12,def:0,unit:`dB/oct`},{kind:`num`,id:`level`,label:`Level`,group:`Output`,min:-24,max:36,def:0,unit:`dB`,hint:`instrument level (saved with presets; Volume is not)`},{kind:`num`,id:`voices`,label:`Max notes`,group:`Output`,min:1,max:16,def:8,int:!0},{kind:`num`,id:`drive`,label:`Saturation`,group:`Output`,min:0,max:1,def:0},{kind:`num`,id:`delayMix`,label:`Delay mix`,group:`Output`,min:0,max:1,def:0},{kind:`num`,id:`delayTime`,label:`Delay time`,group:`Output`,min:10,max:1500,def:350,scale:`log`,unit:`ms`,show:e=>e.delayMix>0},{kind:`num`,id:`delayFb`,label:`Delay feedback`,group:`Output`,min:0,max:.95,def:.35,show:e=>e.delayMix>0},{kind:`num`,id:`reverbMix`,label:`Reverb mix`,group:`Output`,min:0,max:1,def:.15},{kind:`num`,id:`reverbSize`,label:`Reverb time`,group:`Output`,min:.2,max:12,def:2.5,scale:`log`,unit:`s`,show:e=>e.reverbMix>0},{kind:`num`,id:`volume`,label:`Volume`,group:`Output`,min:-40,max:12,def:-6,unit:`dB`},{kind:`bool`,id:`seqOn`,label:`Auto-play`,group:`Auto`,def:!1},{kind:`enum`,id:`seqMode`,label:`Pattern`,group:`Auto`,def:`mixed`,options:[[`mixed`,`Mixed (changes every 4 bars)`],[`melody`,`Melody`],[`arpeggio`,`Arpeggio`],[`chords`,`Chords`],[`rhythm`,`Rhythm (one pitch)`],[`drone`,`Drone + sparse melody`]]},{kind:`num`,id:`seqTempo`,label:`Tempo`,group:`Auto`,min:20,max:400,def:110,int:!0,unit:`bpm`},{kind:`num`,id:`seqDensity`,label:`Density`,group:`Auto`,min:0,max:1,def:.5},{kind:`enum`,id:`seqScale`,label:`Scale`,group:`Auto`,def:`pentatonic`,options:[[`chromatic`,`Chromatic`],[`major`,`Major`],[`minor`,`Natural minor`],[`dorian`,`Dorian`],[`pentatonic`,`Pentatonic`],[`wholetone`,`Whole tone`],[`harmonic`,`Harmonic series`]]},{kind:`num`,id:`seqRoot`,label:`Root`,group:`Auto`,min:24,max:84,def:48,int:!0},{kind:`num`,id:`seqRange`,label:`Range`,group:`Auto`,min:1,max:4,def:2,int:!0,unit:`oct`},{kind:`num`,id:`seqGate`,label:`Note length`,group:`Auto`,min:.05,max:8,def:.5,scale:`log`,unit:`beats`},{kind:`num`,id:`seqPoly`,label:`Notes per step`,group:`Auto`,min:1,max:4,def:1,int:!0,show:e=>e.seqMode===`melody`||e.seqMode===`mixed`},{kind:`num`,id:`seqVelRand`,label:`Velocity spread`,group:`Auto`,min:0,max:1,def:.3},{kind:`num`,id:`seqPosRand`,label:`Position spread`,group:`Auto`,min:0,max:1,def:0,hint:`randomize where each note is excited`}];Object.fromEntries(b.map(e=>[e.id,e]));const x=Object.fromEntries(b.map(e=>[e.id,e.def])),S=b.filter(e=>e.model).map(e=>e.id);function C(e){let t=e>>>0;return()=>{t=t+0x6d2b79f5>>>0;let e=t;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}}function w(e){let t=Math.max(e(),1e-12);return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*e())}const T=e=>S.map(t=>String(e[t])).join(`|`);function E(e){let t=Math.round(d(e,`modes`)),n=c(f(e,`geometry`),t,d(e,`aspect`),d(e,`powerExp`),d(e,`discExp`)),r=Math.round(d(e,`seed`)),i=C(r*7919+13),a=d(e,`stretch`),o=d(e,`inharm`),s=d(e,`harmonize`),l=d(e,`jitter`),u=0;for(let e=0;e<t;e++)if(Math.abs(n.ratios[e]-1)<1e-9){u=e;break}let p=new Float64Array(t);for(let e=0;e<t;e++){let t=n.ratios[e]**+a;if(t*=Math.sqrt(1+o*t*t)/Math.sqrt(1+o),s>0){let e=t<.75?.5:Math.max(1,Math.round(t));t=t**(1-s)*e**+s}let r=w(i);e!==u&&l>0&&(t*=2**(l*r/1200)),p[e]=t}let m=Int32Array.from({length:t},(e,t)=>t).sort((e,t)=>p[e]-p[t]),h=new Float64Array(t),g=new Float64Array(t),_=0;for(let e=0;e<t;e++)h[e]=p[m[e]],g[e]=n.wavenum[m[e]],m[e]===u&&(_=e);let v=Math.min(t,Math.round(d(e,`nlModes`))),y=Math.round(d(e,`terms`)),b=C(r*104729+7),x=[],S=new Float64Array(y*v);for(let e=0;e<y;e++){let t=[],n=Math.max(2,Math.round(v*.75)),r=0;for(let e=0;e<n;e++){let e=Math.floor(b()*v),n=b()<.25?e:Math.floor(b()*v),i=w(b);t.push([e,n,i]),r+=(e===n?1:2)*i*i}let i=1/Math.sqrt(r),a=[];for(let[e,n,r]of t)a.push([e,n,r*i]),e!==n&&a.push([n,e,r*i]);x.push(a);let o=0;for(let t=0;t<v;t++){let n=w(b);S[e*v+t]=n,o+=n*n}o=1/Math.sqrt(o);for(let t=0;t<v;t++)S[e*v+t]*=o}let E=x.reduce((e,t)=>e+t.length,0),D=new Int32Array(y+1),O=new Int32Array(E),k=new Int32Array(E),A=new Float64Array(E),j=0;for(let e=0;e<y;e++){D[e]=j;for(let[t,n,r]of x[e])O[j]=t,k[j]=n,A[j]=r,j++}D[y]=j;let M=C(r*31337+1),N=new Float64Array(v),P=0;for(let e=0;e<v;e++)N[e]=w(M),P+=N[e]**2;for(let e=0;e<v;e++)N[e]/=Math.sqrt(P);let F=new Float64Array(t);for(let e=0;e<t;e++)F[e]=(M()<.5?-1:1)*(.5+.5*M());return{key:T(e),geom:n,N:t,ratios:h,wavenum:g,pitchK:_,perm:m,Nnl:v,M:y,tStart:D,ti:O,tj:k,tv:A,tb:S,bx:N,rad:F,shape:(e,t,r)=>n.shape(m[e],t,r)}}const D={violin:{name:`Violin`,low:[[275,22,0],[405,30,-12],[470,40,-8],[460,32,0],[540,32,2]],hill:2600,hillDb:6,top:5500},viola:{name:`Viola`,low:[[230,22,0],[340,30,-12],[390,40,-8],[380,32,0],[445,32,2]],hill:2100,hillDb:5,top:4800},cello:{name:`Cello`,low:[[102,20,0],[145,30,-10],[170,40,-8],[178,30,1],[210,30,2]],hill:1500,hillDb:4,top:3500},bass:{name:`Double bass`,low:[[62,18,0],[92,28,-10],[104,38,-8],[112,30,1],[138,30,2]],hill:900,hillDb:3,top:2400},guitar:{name:`Guitar`,low:[[98,18,0],[204,28,3],[230,35,-6],[390,30,-3],[440,35,-2]],hill:2500,hillDb:2,top:5e3}};function O(e,t,n,r=1){let i=D[e];if(!i)return[];let a=C(r*6151+17),o=[];for(let[e,r,s]of i.low){let i=10**(s/20);o.push({f:e/t,q:r/n,gL:i,gR:i*(.8+.4*a())})}let s=1.2*Math.max(...i.low.map(e=>e[0]));for(;s<4.5*i.top;){let e=Math.log2(s/i.hill),r=-6+i.hillDb*Math.exp(-(e*e)/.72);r-=12*Math.max(0,Math.log2(s/i.top));let c=10**((r+3*w(a))/20),l=10**((r+3*w(a))/20);o.push({f:s/t,q:(20+25*a())/n,gL:c*(a()<.5?-1:1),gR:l*(a()<.5?-1:1)}),s*=1+.07*(.5+a())}return o}function k(e,t){let n=0,r=0,i=0,a=0;for(let o of e){let e=t/o.f,s=1-e*e,c=e/o.q,l=s*s+c*c,u=c*c/l,d=c*s/l;n+=o.gL*u,r+=o.gL*d,i+=o.gR*u,a+=o.gR*d}return .5*(n*n+r*r+i*i+a*a)}var A=class{n=0;b0=/* @__PURE__ */ new Float64Array;a1=/* @__PURE__ */ new Float64Array;a2=/* @__PURE__ */ new Float64Array;gL=/* @__PURE__ */ new Float64Array;gR=/* @__PURE__ */ new Float64Array;x1=0;x2=0;y1=/* @__PURE__ */ new Float64Array;y2=/* @__PURE__ */ new Float64Array;key=``;configure(e,t,n,r){let i=`${e}|${t}|${n}|${r}`;if(i===this.key)return;this.key=i;let a=O(e,t,n).filter(e=>e.f<.45*r),o=0,s=0;if(a.length){let e=.8*a[0].f,t=Math.min(1e4,.45*r);for(let n=0;n<=200;n++)o+=k(a,e*(t/e)**(n/200)),s++}let c=s?1/Math.sqrt(o/s):0,l=a.length,u=this.n!==l;if(this.n=l,u)for(let e of[`b0`,`a1`,`a2`,`gL`,`gR`,`y1`,`y2`])this[e]=new Float64Array(l);a.forEach((e,t)=>{let n=2*Math.PI*e.f/r,i=Math.sin(n)/(2*e.q),a=1+i;this.b0[t]=i/a,this.a1[t]=-2*Math.cos(n)/a,this.a2[t]=(1-i)/a,this.gL[t]=e.gL*c,this.gR[t]=e.gR*c})}reset(){this.x1=this.x2=0,this.y1.fill(0),this.y2.fill(0)}tick(e,t){let n=this.n,r=this.b0,i=this.a1,a=this.a2,o=this.y1,s=this.y2,c=this.gL,l=this.gR,u=e-this.x2;this.x2=this.x1,this.x1=e;let d=0,f=0;for(let e=0;e<n;e++){let t=r[e]*u-i[e]*o[e]-a[e]*s[e];s[e]=o[e],o[e]=t,d+=c[e]*t,f+=l[e]*t}t[0]=d,t[1]=f}};const j=.5,M=1e-14,N=.002,P=.05,F=e=>{let t=Math.abs(e);return t+Math.log1p(Math.exp(-2*t))-Math.LN2},I=6.907755;var L=class{idx;active=!1;note=60;baseHz=261.6;vel=1;gate=!1;held=!1;sustained=!1;touching=!1;damped=!0;order=0;N=0;nAct=0;nNL=0;q=/* @__PURE__ */ new Float64Array;qp=/* @__PURE__ */ new Float64Array;qn=/* @__PURE__ */ new Float64Array;A=/* @__PURE__ */ new Float64Array;B=/* @__PURE__ */ new Float64Array;C=/* @__PURE__ */ new Float64Array;om=/* @__PURE__ */ new Float64Array;sw=/* @__PURE__ */ new Float64Array;grad=/* @__PURE__ */ new Float64Array;pv=/* @__PURE__ */ new Float64Array;gp=/* @__PURE__ */ new Float64Array;phiE=/* @__PURE__ */ new Float64Array;phiB=/* @__PURE__ */ new Float64Array;wL=/* @__PURE__ */ new Float64Array;wR=/* @__PURE__ */ new Float64Array;wsum=0;omega1=1;Z0=1;tunedPitch=-1;tunedDamp=-1;tunedGate=!1;glideMul=1;tunedGlide=1;vibMul=1;tunedVib=1;vibPh=0;vibAge=0;vibRateJ=1;dirtyTune=!0;dirtyVec=!0;posX=-1;posY=-1;ham=!1;hz=0;hzp=0;hzn=0;hamISM=1;hamK=0;hamA=2.5;hamTimer=0;gz=0;buzzK=0;buzzGap=0;buzzPhi1=1;beta=.11;env=0;fLaw=0;nz=0;f=0;fb=/* @__PURE__ */ new Float32Array(32768);fbW=0;bx1=0;bx2=0;by1=0;by2=0;S=0;X=0;Vv=0;useG=!1;pred=!1;energy=0;outMono=0;constructor(e){this.idx=e}alloc(e){let t=t=>{let n=new Float64Array(e);return n.set(t.subarray(0,Math.min(e,t.length))),n};this.q=t(this.q),this.qp=t(this.qp),this.qn=new Float64Array(e);for(let t of[`A`,`B`,`C`,`om`,`sw`,`grad`,`pv`,`gp`,`phiE`,`phiB`,`wL`,`wR`])this[t]=new Float64Array(e);this.N=e,this.dirtyTune=this.dirtyVec=!0}reset(){this.q.fill(0),this.qp.fill(0),this.qn.fill(0),this.ham=!1,this.env=0,this.fLaw=0,this.fb.fill(0),this.bx1=this.bx2=this.by1=this.by2=0,this.energy=0}};const R=e=>440*2**((e-69)/12),z=e=>e<0?0:e>1?1:e,B=e=>e-Math.floor(e);var V=class{sr;h;p={...x};model;voices=[];act=[];eps=M;vMax=0;vHold=0;psi=Math.sqrt(M);psiReset=!1;order=0;bend=0;sustain=!1;lastNote=60;focus=null;touchVoice=null;pending=[];post=()=>{};paramVersion=0;rngS=0x9e3779b9;lfoPh=[0,0];lfoA=[0,0];lfoB=[0,0];kt=0;kc=0;cc=0;ct=0;cl=0;crossOn=!1;buzzA=1.5;buzzTwo=!1;ampMul=1;fbMul=1;excMul=1;pitchMul=1;dampMul=1;posOff=0;pickOff=0;vecVersion=-1;lastPosOff=0;lastPickOff=0;law=0;lwF=0;lwVb=0;lwGam=0;lwD=0;lawK=/* @__PURE__ */ new Float64Array(3);envAtt=0;envRel=0;noiseC=0;noiseNorm=1;fbD=1;fb0=0;fb2=0;fa1=0;fa2=0;snapCount=0;cpuMs=0;cpuWall=0;cpu=0;lastTouch=null;box=new A;boxOut=/* @__PURE__ */ new Float64Array(2);constructor(e){this.sr=e,this.h=1/e,this.model=E(this.p);for(let e=0;e<16;e++){let t=new L(e);t.alloc(this.model.N),this.voices.push(t)}}message(e){e.type===`params`?this.setParams(e.params):this.pending.push(e)}setParams(e){if(this.p={...x,...e},this.paramVersion++,T(this.p)!==this.model.key){this.model=E(this.p);for(let e of this.voices)e.alloc(this.model.N);this.psiReset=!0}for(let e of this.voices)e.dirtyTune=e.dirtyVec=!0;let t=f(this.p,`soundbox`);t===`off`?(this.box.configure(``,1,1,this.sr),this.box.reset()):this.box.configure(t,d(this.p,`boxSize`),d(this.p,`boxDamp`),this.sr)}handle(e){switch(e.type){case`noteOn`:this.noteOn(e.note,e.vel,e.x,e.y);break;case`noteOff`:this.noteOff(e.note);break;case`sustain`:if(this.sustain=e.on,!e.on)for(let e of this.voices)e.sustained&&(e.sustained=!1,this.updateGate(e));break;case`bend`:this.bend=e.value;break;case`touchStart`:this.touchStart(e.x,e.y,e.vel);break;case`touchMove`:this.lastTouch={x:e.x,y:e.y},this.touchVoice&&(this.touchVoice.posX=e.x,this.touchVoice.posY=e.y,this.touchVoice.dirtyVec=!0);break;case`touchEnd`:this.lastTouch=null,this.touchVoice&&=(this.touchVoice.touching=!1,this.updateGate(this.touchVoice),null);break;case`panic`:for(let e of this.voices)e.reset(),e.active=!1;this.box.reset(),this.psi=Math.sqrt(this.eps)}}allocVoice(e){let t=this.voices.find(t=>t.active&&t.note===e);if(t)return t;let n=Math.round(d(this.p,`voices`)),r=this.voices.filter(e=>e.active);return r.length>=n?(r.sort((e,t)=>Number(e.gate)-Number(t.gate)||e.energy-t.energy||e.order-t.order),t=r[0]):t=this.voices.find(e=>!e.active),t.reset(),t.active=!0,t.glideMul=1,t.vibMul=1,t.vibPh=this.rand(),t.vibRateJ=1+.1*(this.rand()*2-1),t.note=e,t.baseHz=R(e),t.held=t.sustained=t.touching=!1,t.gate=!1,t.dirtyTune=t.dirtyVec=!0,t.tunedPitch=-1,this.psiReset=!0,t}updateGate(e){let t=e.held||e.sustained||e.touching;t!==e.gate&&(e.gate=t,e.dirtyTune=!0)}noteOn(e,t,n,r){let i=this.allocVoice(e);i.order=++this.order,i.vel=Math.max(.01,Math.min(1,t)),i.held=!0,i.damped=!0,i.vibAge=0,i.posX=n??-1,i.posY=r??-1,i.dirtyVec=!0,this.updateGate(i),this.lastNote=e,this.focus=i,this.prepare(i),this.excite(i,i.vel)}noteOff(e){for(let t of this.voices)t.active&&t.note===e&&t.held&&(t.held=!1,this.sustain&&(t.sustained=!0),this.updateGate(t))}touchStart(e,t,n){this.lastTouch={x:e,y:t};let r=this.focus&&this.focus.active?this.focus:null;r||(r=this.allocVoice(this.lastNote),r.order=++this.order,r.damped=!1,this.focus=r),r.posX=e,r.posY=t,r.vel=n,r.dirtyVec=!0;let i=this.law!==0;i&&(r.touching=!0,this.touchVoice=r,this.updateGate(r)),this.prepare(r),i||this.excite(r,n)}prepare(e){e.dirtyVec&&this.vecVoice(e),(e.dirtyTune||e.tunedPitch!==this.pitchMul||e.tunedDamp!==this.dampMul||e.tunedGate!==e.gate||e.tunedGlide!==e.glideMul||e.tunedVib!==e.vibMul)&&this.tuneVoice(e)}excite(e,t){let n=f(this.p,`exciter`),r=j*(d(this.p,`strength`)*t)**2;if(r<=0)return;let i=e.nAct,a=e.phiE,o=e.om,s=this.h;if(n===`strike`){let t=d(this.p,`hammerMass`),n=d(this.p,`hardness`)/1e3,o=d(this.p,`feltExp`),c=Math.sqrt(2*r/t),l=Math.sqrt(2*j/t)*n/Math.PI,u=0,f=0;for(let t=0;t<i;t++)u+=a[t]*e.q[t],f+=a[t]*(e.q[t]-e.qp[t])/s;let p=Math.sqrt(t);e.ham=!0,e.hamTimer=0,e.hamISM=1/p,e.hamK=t*(Math.PI/n)**2/l**(o-1),e.hamA=o,e.hz=u*p,e.hzp=(u-(f+c)*s)*p}else if(n===`pluck`){let t=0;for(let e=0;e<i;e++)t+=a[e]*a[e]/(o[e]*o[e]);if(t<=0)return;let n=Math.sqrt(2*r/t);for(let t=0;t<i;t++){let r=n*a[t]/(o[t]*o[t]);e.q[t]+=r,e.qp[t]+=r}this.psiReset=!0}else if(n===`impulse`){let t=d(this.p,`hardness`)/1e3,n=0,c=e.qn;for(let e=0;e<i;e++){let r=o[e]*t/2,i=1-(r/Math.PI)**2,s=r<1e-9?1:Math.abs(i)<1e-6?.5:Math.abs(Math.sin(r)/r/i);c[e]=a[e]*s,n+=c[e]*c[e]}if(n<=0)return;let l=Math.sqrt(2*r/n);for(let t=0;t<i;t++)e.qp[t]-=s*l*c[t];c.fill(0)}}tuneVoice(e){let t=this.model,n=t.N,r=this.h,i=this.p,a=e.baseHz*this.pitchMul*e.glideMul*e.vibMul,o=I/d(i,`t60`),s=d(i,`hfDamp`),c=d(i,`damper`),l=!e.gate&&e.damped&&c<19.9?I/c:0,u=.45*this.sr,f=0,p=0;for(let i=0;i<n;i++){let n=a*t.ratios[i],c=2*Math.PI*n;if(e.om[i]=c,n>=u){e.A[i]=e.B[i]=e.C[i]=e.sw[i]=0;continue}f=i+1;let d=(o+s*(n/1e3)**2)*this.dampMul+l,m=Math.exp(-d*r);if(d<c)e.A[i]=2*m*Math.cos(Math.sqrt(c*c-d*d)*r);else{let t=Math.sqrt(d*d-c*c)*r;e.A[i]=m*(Math.exp(t)+Math.exp(-t))}e.B[i]=m*m,e.C[i]=r*r/(1+Math.tanh(d*r));let h=2-2*Math.cos(c*r),g=Math.max(0,Math.min(1,(3.6/h-1)/12));e.sw[i]=c*Math.sqrt(g),g>0&&(p=i+1)}for(let t=f;t<n;t++)e.q[t]=e.qp[t]=0;e.nAct=f,e.nNL=Math.min(p,f),e.omega1=2*Math.PI*a,e.Z0=2*a;let m=0;for(let t=0;t<f;t++)m+=e.phiE[t]*e.phiE[t]*e.C[t];e.wsum=m;let h=+Math.max(e.buzzPhi1,.05)/e.omega1,g=d(i,`buzz`);e.buzzGap=d(i,`buzzGap`)*h,e.buzzK=g>0?g*(2*Math.PI*4e3)**2*.1*h**(1-this.buzzA):0,e.tunedPitch=this.pitchMul,e.tunedDamp=this.dampMul,e.tunedGate=e.gate,e.tunedGlide=e.glideMul,e.tunedVib=e.vibMul,e.dirtyTune=!1}vecVoice(e){let t=this.model,n=t.N,r=this.p,i=e.posX>=0?e.posX:z(d(r,`exPos`)+this.posOff),a=e.posY>=0?e.posY:z(d(r,`exPosY`)+this.posOff),o=d(r,`exWidth`)*.15,s=d(r,`buzzPos`),c=d(r,`buzzPosY`),l=B(d(r,`pickup`)+this.pickOff),u=d(r,`pickupY`),f=d(r,`width`),p=B(l+.5*f),m=B(u+.37*f),h=d(r,`spread`),g=d(r,`tilt`)/6.0206;for(let r=0;r<n;r++){let d=Math.exp(-.5*(Math.PI*t.wavenum[r]*o)**2);e.phiE[r]=t.shape(r,i,a)*d,e.phiB[r]=t.shape(r,s,c);let f=t.ratios[r]**+g;e.wL[r]=((1-h)*t.shape(r,l,u)+h*t.rad[r])*f,e.wR[r]=((1-h)*t.shape(r,p,m)+h*t.rad[(r+1)%n]*(r%2?1:-1))*f}e.buzzPhi1=Math.abs(t.shape(t.pitchK,s,c)),e.beta=Math.max(.02,Math.min(i,1-i)),e.dirtyVec=!1,e.dirtyTune=!0}rand(){let e=this.rngS;return e^=e<<13,e^=e>>>17,e^=e<<5,this.rngS=e>>>0,this.rngS/4294967296}lfo(e,t){let n=this.p,r=d(n,`lfo${e+1}Rate`),i=this.lfoPh[e]+r*t;switch(i>=1&&(i-=Math.floor(i),this.lfoA[e]=this.lfoB[e],this.lfoB[e]=this.rand()*2-1),this.lfoPh[e]=i,f(n,`lfo${e+1}Shape`)){case`tri`:return 1-4*Math.abs(i-.5);case`saw`:return 2*i-1;case`square`:return i<.5?1:-1;case`sh`:return this.lfoB[e];case`smooth`:return this.lfoA[e]+(this.lfoB[e]-this.lfoA[e])*(.5-.5*Math.cos(Math.PI*i));default:return Math.sin(2*Math.PI*i)}}blockUpdate(e){let t=this.p,n=this.sr,r=e/n,i=this.bend*d(t,`bendRange`),a=1,o=0,s=0,c=d(t,`tension`),l=d(t,`cascade`),u=1,p=1,m=1;for(let e=0;e<2;e++){let n=f(t,`lfo${e+1}Target`);if(n===`off`)continue;let h=d(t,`lfo${e+1}Depth`),g=this.lfo(e,r)*h;switch(n){case`pitch`:i+=4*g;break;case`amp`:a*=Math.max(0,1+g);break;case`position`:o+=.5*g;break;case`pickup`:s+=.5*g;break;case`tension`:c*=Math.max(0,1+g);break;case`cascade`:l*=Math.max(0,1+g);break;case`damping`:u*=2**(3*g);break;case`feedback`:p*=Math.max(0,1+g);break;case`exciter`:m*=Math.max(0,1+g)}}this.pitchMul=2**(i/12),this.dampMul=u,this.ampMul=a,this.fbMul=p,this.excMul=m,this.kt=c,this.kc=this.model.M>0?l:0,this.cc=+d(t,`curvature`),this.ct=d(t,`crossTension`),this.cl=d(t,`crossLink`),this.crossOn=this.ct>0||this.cl>0,this.buzzTwo=f(t,`buzzSides`)===`two`;let h=f(t,`exciter`);this.law=h===`bow`?1:h===`reed`?2:h===`selfosc`?3:h===`noise`?4:0;let g=this.lawK;this.law===1?(g[0]=d(t,`bowSpeed`)*.5,g[1]=+d(t,`bowForce`),g[2]=d(t,`bowNoise`)):this.law===2?(g[0]=d(t,`reedGain`)*2,g[1]=d(t,`reedPressure`),g[2]=d(t,`breath`)):this.law===3&&(g[0]=+d(t,`selfGain`),g[1]=d(t,`selfSat`)),this.envAtt=1-Math.exp(-1/(d(t,`attack`)/1e3*n)),this.envRel=1-Math.exp(-1/(d(t,`release`)/1e3*n));let _=Math.min(d(t,`noiseColor`),.45*n);this.noiseC=1-Math.exp(-2*Math.PI*_/n),this.noiseNorm=Math.sqrt(3*(2-this.noiseC)/this.noiseC),this.fbD=Math.max(1,Math.min(32767,Math.round(d(t,`fbDelay`)/1e3*n)));let v=2*Math.PI*Math.min(d(t,`fbFreq`),.45*n)/n,y=Math.sin(v)/(2*d(t,`fbQ`)),b=1+y;this.fb0=y/b,this.fb2=-y/b,this.fa1=-2*Math.cos(v)/b,this.fa2=(1-y)/b;let x=o!==this.lastPosOff||s!==this.lastPickOff||this.vecVersion!==this.paramVersion;this.posOff=o,this.pickOff=s,this.lastPosOff=o,this.lastPickOff=s,this.vecVersion=this.paramVersion;let S=d(t,`vibDepth`),C=d(t,`vibRate`),w=d(t,`vibDelay`)/1e3;this.act.length=0;for(let e of this.voices)if(e.active){if(S>0){e.vibAge+=r;let t=e.vibAge,n=w>0?(t-.3*w)/(.7*w):1;n=n<0?0:n>1?1:n*n*(3-2*n),e.vibPh+=C*e.vibRateJ*(1+.06*Math.sin(2.3*t+7*e.vibRateJ))*r,e.vibPh-=Math.floor(e.vibPh);let i=2**(S*n*Math.sin(2*Math.PI*e.vibPh)/1200);(Math.abs(i/e.vibMul-1)>1e-5||n===0&&e.vibMul!==1)&&(e.vibMul=i)}else e.vibMul=1;x&&(e.dirtyVec=!0),this.prepare(e),this.act.push(e)}}nl(e){if(this.kt<=0&&this.ct<=0&&this.kc<=0&&!this.crossOn&&!e.ham&&e.buzzK<=0){e.S=e.X=e.Vv=e.gz=0,e.useG=!1;return}let t=e.nAct,n=e.q,r=e.sw,i=e.grad,a=this.model,o=0,s=!1,c=e.nNL,l=0;if(this.kt>0||this.ct>0||this.kc>0)for(let e=0;e<c;e++){let t=r[e]*n[e];l+=t*t}if(e.S=l,i.fill(0,0,t),e.gz=0,this.kt>0&&l>0){let e=3/this.kt,t=l/j;o+=this.kt*j*.5*e*e*F(t/e);let a=this.kt*e*Math.tanh(t/e);for(let e=0;e<c;e++)i[e]+=a*r[e]*r[e]*n[e];s=!0}let u=this.kc;if(u>0){let t=a.Nnl,l=Math.min(c,t),d=e.pv,f=e.gp,p=this.cc,m=3/(u*a.M);for(let e=0;e<t;e++)d[e]=e<l?r[e]*n[e]:0,f[e]=0;let h=a.ti,g=a.tj,_=a.tv,v=a.tb;for(let e=0;e<a.M;e++){let n=a.tStart[e],r=a.tStart[e+1],i=0;for(let e=n;e<r;e++)i+=_[e]*d[h[e]]*d[g[e]];let s=0,c=e*t;if(p!==0)for(let e=0;e<l;e++)s+=v[c+e]*d[e];let y=(i+p*s)/j;o+=u*j*m*m*F(y/m);let b=u*m*Math.tanh(y/m),x=2*b;for(let e=n;e<r;e++)f[h[e]]+=x*_[e]*d[g[e]];let S=b*p;if(S!==0)for(let e=0;e<l;e++)f[e]+=S*v[c+e]}for(let e=0;e<l;e++)i[e]+=r[e]*f[e];s=!0}if(e.ham){let r=e.phiE,a=0;for(let e=0;e<t;e++)a+=r[e]*n[e];let c=e.hz*e.hamISM-a;if(c>0){let n=e.hamA,a=e.hamK*c**+n;o+=a*c/(n+1);for(let e=0;e<t;e++)i[e]-=a*r[e];e.gz=a*e.hamISM,e.hamTimer=0,s=!0}else++e.hamTimer>.05*this.sr&&(e.ham=!1)}if(e.buzzK>0){let r=e.phiB,a=0;for(let e=0;e<t;e++)a+=r[e]*n[e];let c=this.buzzA,l=0,u=a-e.buzzGap;if(u>0){let t=e.buzzK*u**+c;o+=t*u/(c+1),l+=t}if(this.buzzTwo){let t=-a-e.buzzGap;if(t>0){let n=e.buzzK*t**+c;o+=n*t/(c+1),l-=n}}if(l!==0){for(let e=0;e<t;e++)i[e]+=l*r[e];s=!0}}if(this.crossOn){let t=0,r=Math.min(c,a.Nnl),i=a.bx;if(this.cl>0)for(let a=0;a<r;a++)t+=i[a]*e.sw[a]*n[a];e.X=.5*this.ct*l+this.cl*1*t}else e.X=0;e.Vv=o,e.useG=s||this.crossOn}lawEval(e){let t=0,n=0;if(this.law===1){let r=e-this.lwVb,i=Math.tanh(r/N),a=1+Math.abs(r)/P,o=.35+.65/a,s=-.65/(P*a*a)*(r>=0?1:-1);t=-this.lwF*i*o,n=-this.lwF*((1-i*i)/N*o+i*s)}else if(this.law===2){let r=this.lwGam-e;if(r<1){let e=Math.sqrt(Math.abs(r)+1e-9),i=this.lwF;r>=0?(t=i*(1-r)*e,n=-i*(-e+(1-r)/(2*e))):(t=-i*(1-r)*e,n=-i*(e+(1-r)/(2*e)))}}else{let r=this.lwF,i=this.lwVb;t=r*(e-e*e*e/(3*i*i)),n=r*(1-e*e/(i*i))}return this.lwD=n,t}solveLaw(e,t,n){let r=e.nAct,i=e.phiE,a=e.A,o=e.B,s=e.q,c=e.qp,l=e.qn,u=0;for(let e=0;e<r;e++){let t=a[e]*s[e]-o[e]*c[e];l[e]=t,u+=i[e]*(t-c[e])}e.pred=!0;let d=.5/this.h,f=(u+t*e.wsum)*d,p=e.wsum*d,m=e.env*this.excMul,h=e.Z0,g=this.lawK;if(this.law===1){this.lwVb=g[0]*m;let t=g[2];this.lwF=g[1]*h*(this.lwVb/.05)*(.11/e.beta)*(t>0?Math.max(0,1+t*n):1)}else this.law===2?(this.lwF=g[0]*h,this.lwGam=g[1]*m*(1+g[2]*n)):(this.lwF=g[0]*h*m,this.lwVb=g[1]);let _=this.lwF+1e-9,v=1e-9*_,y=e.fLaw,b=!1;for(let e=0;e<8;e++){let e=y-this.lawEval(f+p*y);if(Math.abs(e)<v){b=!0;break}let t=1-p*this.lwD;if(t<.05)break;y-=e/t}if(!b||!Number.isFinite(y)){let t=Number.isFinite(e.fLaw)?e.fLaw:0,n=.01*_,r=t,i=t,a=0,o=0;for(let e=0;e<60&&(r=t-n,i=t+n,a=r-this.lawEval(f+p*r),o=i-this.lawEval(f+p*i),!(a<=0&&o>=0));e++)n*=2;for(let e=0;e<50;e++){let e=.5*(r+i);e-this.lawEval(f+p*e)<0?r=e:i=e}y=.5*(r+i),Number.isFinite(y)||(y=0)}return e.fLaw=y,y}process(e,t,n,r=0){let i=Date.now(),a=n/this.sr;if(this.pending.length){let e=[];for(let t of this.pending)(`time`in t&&t.time!==void 0?t.time:0)<=r+a?this.handle(t):e.push(t);this.pending=e}this.blockUpdate(n);let o=this.act,s=this.h,c=s*s,l=1/s,u=this.p,f=d(u,`fbGain`)*this.fbMul,p=d(u,`fbSat`),m=d(u,`noiseLevel`),h=this.law,g=h===4||h===3||h===2&&d(u,`breath`)>0||h===1&&d(u,`bowNoise`)>0,_=this.box,v=_.n>0,y=v?d(u,`boxMix`):0,b=1-y,x=this.boxOut,S=.25*this.ampMul*l*10**(d(u,`level`)/20),C=32767;for(let r=0;r<n;r++){let n=0,i=0,a=!1;for(let e=0;e<o.length;e++){let t=o[e];t.env+=((t.gate?t.vel:0)-t.env)*(t.gate?this.envAtt:this.envRel);let r=0;if(t.env>1e-6){let e=0;if(g&&(t.nz+=this.noiseC*(this.rand()*2-1-t.nz),e=t.nz*this.noiseNorm),f>0){let e=t.fb[t.fbW-this.fbD&C],n=this.fb0*e+this.fb2*t.bx2-this.fa1*t.by1-this.fa2*t.by2;t.bx2=t.bx1,t.bx1=e,t.by2=t.by1,t.by1=n,r+=p*t.Z0*Math.tanh(f*n/p)*t.env}h===3&&(r+=.001*t.Z0*t.env*e),h===4?r+=m*t.Z0*t.env*this.excMul*e*.5:h!==0&&(r+=this.solveLaw(t,r,e))}else t.fLaw=0;t.f=r,this.nl(t),n+=t.Vv,i+=t.X,t.useG&&(a=!0)}if(this.crossOn&&o.length){let e=i/j;n+=j*3*3*F(e/3);let t=3*Math.tanh(e/3),r=this.ct,a=+this.cl,s=this.model.bx,c=this.model.Nnl;for(let e of o){let n=e.nNL,i=e.grad,o=e.q,l=e.sw;for(let e=0;e<n;e++)i[e]+=t*(r*l[e]*l[e]*o[e]+(e<c?a*s[e]*l[e]:0))}}if(a){n>this.vMax&&(this.vMax=n),this.psiReset&&(this.eps=.01);let e=Math.sqrt(2*n+this.eps),t=1/e;if(this.psiReset)this.psi=e,this.psiReset=!1;else{let t=this.psi+.01*(e-this.psi);Math.abs(t)<Math.abs(this.psi)&&(this.psi=t)}let r=0;for(let e of o){if(!e.useG)continue;let t=e.nAct,n=e.grad,i=e.qp;for(let e=0;e<t;e++)r+=n[e]*i[e];e.ham&&(r+=e.gz*e.hzp)}r*=t;let i=this.psi,a=r/4,s=0,l=0;for(let e of o){if(!e.useG){this.linearStep(e);continue}e.pred=!1;let n=e.nAct,r=e.grad,o=e.q,u=e.qp,d=e.qn,f=e.A,p=e.B,m=e.C,h=e.phiE,g=e.f;for(let e=0;e<n;e++){let n=r[e]*t,c=f[e]*o[e]-p[e]*u[e]+m[e]*(h[e]*g+n*(a-i));d[e]=c,s+=n*c,l+=m[e]*n*n}if(e.ham){let n=e.gz*t,r=2*e.hz-e.hzp+c*n*(a-i);e.hzn=r,s+=n*r,l+=c*n*n}}let u=s/(1+l/4),d=u*t/4;for(let e of o){if(!e.useG)continue;let t=e.nAct,n=e.grad,r=e.qn,i=e.C;for(let e=0;e<t;e++)r[e]-=i[e]*n[e]*d;e.ham&&(e.hzn-=c*e.gz*d)}this.psi=i+(u-r)/2}else{for(let e of o)this.linearStep(e);this.psi=Math.sqrt(this.eps)}let s=0,u=0;for(let e of o){let t=e.nAct,n=e.q,r=e.qn,i=e.wL,a=e.wR,o=0,c=0;for(let e=0;e<t;e++){let t=r[e]-n[e];o+=i[e]*t,c+=a[e]*t}s+=o,u+=c,e.fb[e.fbW]=.5*(o+c)*l,e.fbW=e.fbW+1&C;let d=e.qp;e.qp=e.q,e.q=e.qn,e.qn=d,e.ham&&(e.hzp=e.hz,e.hz=e.hzn)}v?(_.tick(.5*(s+u)*S,x),e[r]=b*s*S+y*x[0],t[r]=b*u*S+y*x[1]):(e[r]=s*S,t[r]=u*S)}this.blockEnd(n),this.cpuMs+=Date.now()-i,this.cpuWall+=a*1e3}linearStep(e){let t=e.nAct,n=e.q,r=e.qp,i=e.qn,a=e.A,o=e.B,s=e.C,c=e.phiE,l=e.f;if(e.pred){if(e.pred=!1,l!==0)for(let e=0;e<t;e++)i[e]+=s[e]*c[e]*l}else if(l!==0)for(let e=0;e<t;e++)i[e]=a[e]*n[e]-o[e]*r[e]+s[e]*c[e]*l;else for(let e=0;e<t;e++)i[e]=a[e]*n[e]-o[e]*r[e];e.ham&&(e.hzn=2*e.hz-e.hzp)}blockEnd(e){let t=1/this.h;for(let e of this.act){let n=e.nAct,r=e.q,i=e.qp,a=e.om,o=0;for(let e=0;e<n;e++){let n=(r[e]-i[e])*t;o+=.5*(n*n+a[e]*a[e]*r[e]*r[e])}if(!Number.isFinite(o)||o>1e8){e.reset(),e.active=!1,this.psiReset=!0;continue}e.energy=o;let s=d(this.p,`glide`),c=1;if(s!==0){let e=4*o/j;c=2**(s*e/(1+e)/12)}(Math.abs(c/e.glideMul-1)>2e-5||c===1&&e.glideMul!==1)&&(e.glideMul=c),!e.gate&&!e.ham&&o<1e-10&&e.env<1e-4&&(e.active=!1)}let n=0;for(let e of this.act)e.active&&(n+=e.energy);this.vHold=Math.max(this.vMax,this.vHold*.95),this.vMax=0;let r=Math.max(M,.02*n+2*this.vHold);if(r<this.eps){let e=Math.max(r,this.eps*.95),t=this.psi*this.psi-(this.eps-e);this.psi=(this.psi<0?-1:1)*Math.sqrt(Math.max(0,t)),this.eps=e}this.snapCount+=e,this.snapCount>=this.sr/30&&(this.snapCount=0,this.cpuWall>0&&(this.cpu=this.cpuMs/this.cpuWall),this.cpuMs=this.cpuWall=0,this.snapshot())}snapshot(){let e=this.focus&&this.focus.active?this.focus:null;if(!e)for(let t of this.voices)t.active&&(!e||t.order>e.order)&&(e=t);let t=this.model.N,n=new Float32Array(t),r=new Float32Array(t),i=new Float32Array(t),a=new Float32Array(t);if(e){let o=1/this.h;for(let s=0;s<t;s++){n[s]=e.q[s];let t=(e.q[s]-e.qp[s])*o;r[s]=t,i[s]=.5*(t*t+e.om[s]*e.om[s]*e.q[s]*e.q[s]),a[s]=e.om[s]/(2*Math.PI)}}let o=[];for(let e of this.voices)e.active&&o.push(e.note);let s={type:`snap`,cpu:this.cpu,nVoices:o.length,notes:o,focusNote:e?e.note:-1,focusHz:e?e.baseHz*this.pitchMul:0,nAct:e?e.nAct:0,q:n,qd:r,energy:i,freqs:a,touch:this.lastTouch};this.post(s,[n.buffer,r.buffer,i.buffer,a.buffer])}},H=class extends AudioWorkletProcessor{synth=new V(sampleRate);constructor(){super(),this.port.onmessage=e=>this.synth.message(e.data),this.synth.post=(e,t)=>this.port.postMessage(e,t)}process(e,t){let n=t[0],r=n[0],i=n[1]??n[0];return this.synth.process(r,i,r.length,currentTime),!0}};registerProcessor(`modal-synth`,H);
\ No newline at end of file
site/index.htmladded+13−0View file
@@ -0,0 +1,13 @@
1+<!doctype html>
2+<html lang="en">
3+ <head>
4+ <meta charset="UTF-8" />
5+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+ <title>double pendulum</title>
7+ <script type="module" crossorigin src="./assets/index-DFpYSV6v.js"></script>
8+ <link rel="stylesheet" crossorigin href="./assets/index-EgyvN0Ym.css">
9+ </head>
10+ <body>
11+ <div id="app"></div>
12+ </body>
13+</html>
src/compositions/c01-poincare/defaults.jsonadded+68−0View file
@@ -0,0 +1,68 @@
1+{
2+ "duration": 60,
3+ "peakTime": 25,
4+ "holdTime": 10,
5+ "energyStart": 0.005,
6+ "energyPeak": 0.4,
7+ "riseShape": "exponential",
8+ "riseCurve": 1,
9+ "fallCurve": 1,
10+ "restEnergy": 0.001,
11+ "finalHold": 2,
12+ "finalFade": 5,
13+ "speed": 50,
14+ "massRatio": 1,
15+ "lengthRatio": 1,
16+ "tau": 2,
17+ "seed": 0,
18+ "noteInstrument": "modal: Nylon harp",
19+ "modalCustom": "",
20+ "scale": "dorian",
21+ "root": "D",
22+ "pitchSource": "signed",
23+ "thetaRange": 3.1416,
24+ "pitchLow": 50,
25+ "pitchHigh": 86,
26+ "pitchCurve": 1,
27+ "invertPitch": false,
28+ "p2Ref": 1,
29+ "loudCurve": 1,
30+ "loudFloor": 0.08,
31+ "notesLevel": -6,
32+ "noteLength": 1.5,
33+ "panAmount": 0.6,
34+ "humInstrument": "modal: Clarinet-ish",
35+ "humCustom": "",
36+ "humPitch": 38,
37+ "humLevel": -24,
38+ "humFollow": 0,
39+ "humNormalize": true,
40+ "humColorMode": "log",
41+ "humColorCurve": 1,
42+ "humTarget1": "pickup",
43+ "humFrom1": 0.15,
44+ "humTo1": 0.75,
45+ "humTarget2": "tilt",
46+ "humFrom2": 0.3333,
47+ "humTo2": 0.5833,
48+ "humFadeIn": 3,
49+ "humFadeOut": 6,
50+ "pendulumAlpha": 1,
51+ "pendulumSize": 0.32,
52+ "motionBlur": 1,
53+ "fade": 10,
54+ "plotZoom": "fit energy",
55+ "zoomSmooth": 1.5,
56+ "plotP": 1.5,
57+ "pointSize": 2,
58+ "orbits": true,
59+ "orbitCount": 24,
60+ "orbitCpu": 0.4,
61+ "orbitLife": 300,
62+ "orbitBand": 0.25,
63+ "orbitMinHold": 3,
64+ "orbitMaxPoints": 8000,
65+ "orbitXfade": 1.5,
66+ "orbitAlpha": 0.3,
67+ "orbitSize": 1
68+}
src/compositions/c01-poincare/form.tsadded+21−0View file
@@ -0,0 +1,21 @@
1+import type { Params } from "../../core/params.ts";
2+
3+/** Target energy (units of E_top) at piece time t: start → peak → hold → zero at duration. */
4+export function energyTarget(P: Params, t: number): number {
5+ const dur = P.duration as number;
6+ const peakT = Math.min(P.peakTime as number, dur);
7+ const holdEnd = Math.min(peakT + (P.holdTime as number), dur);
8+ const e0 = P.energyStart as number;
9+ const e1 = P.energyPeak as number;
10+ if (t < 0) return e0;
11+ if (t < peakT) {
12+ const u = Math.pow(t / peakT, P.riseCurve as number);
13+ return P.riseShape === "exponential" ? e0 * Math.pow(e1 / e0, u) : e0 + (e1 - e0) * u;
14+ }
15+ if (t < holdEnd) return e1;
16+ if (t < dur) {
17+ const u = (t - holdEnd) / (dur - holdEnd);
18+ return e1 * Math.pow(1 - u, P.fallCurve as number);
19+ }
20+ return 0;
21+}
src/compositions/c01-poincare/index.tsadded+12−0View file
@@ -0,0 +1,12 @@
1+import type { Composition } from "../../core/composition.ts";
2+import defaults from "./defaults.json";
3+import { createPoincarePiece } from "./piece.ts";
4+import { schema } from "./schema.ts";
5+
6+export const poincare: Composition = {
7+ id: "01-poincare",
8+ title: "poincaré",
9+ schema,
10+ defaults,
11+ create: createPoincarePiece,
12+};
src/compositions/c01-poincare/orbitWorker.tsadded+144−0View file
@@ -0,0 +1,144 @@
1+// Background Poincaré portrait, computed in "portraits" at a single fixed energy.
2+//
3+// A portrait is a pool of energy-conserving orbits, all at exactly the same energy, seeded
4+// uniformly over the section. Orbits are long-lived so invariant curves (islands) fill in;
5+// after `life` crossings an orbit is reseeded elsewhere to explore more of the section.
6+// A new portrait starts only when the pendulum's energy has moved by more than `band`
7+// (relative) AND the current portrait is at least `minHold` seconds old. A portrait stops
8+// computing once it has `maxPoints`, so a settled energy costs no CPU.
9+// Work runs in short slices separated by sleeps, using about `cpu` of one core.
10+
11+import { DoublePendulum, seedOnSection, wrapAngle } from "../../physics/doublePendulum.ts";
12+import { mulberry32 } from "../../core/rng.ts";
13+
14+export interface OrbitConfig {
15+ running: boolean;
16+ /** start a new portrait right away (new play / seek) */
17+ reset: boolean;
18+ /** current normalized energy of the pendulum */
19+ energy: number;
20+ m2: number;
21+ l2: number;
22+ count: number;
23+ /** crossings per orbit before it is reseeded elsewhere */
24+ life: number;
25+ /** relative energy change that triggers a new portrait */
26+ band: number;
27+ /** minimum portrait lifetime (s) */
28+ minHold: number;
29+ /** points per portrait, after which computing pauses */
30+ maxPoints: number;
31+ /** fraction of one core, 0..1 */
32+ cpu: number;
33+}
34+
35+export interface OrbitBatch {
36+ gen: number;
37+ energy: number;
38+ pts: Float32Array; // [θ2, p2, θ2, p2, …]
39+}
40+
41+interface Orbit {
42+ pend: DoublePendulum;
43+ crossings: number;
44+ prev: number;
45+ ok: boolean;
46+}
47+
48+const DT = 0.005;
49+const SLICE_MS = 8;
50+const STEPS_PER_CHECK = 100;
51+
52+let cfg: OrbitConfig | null = null;
53+let timer: ReturnType<typeof setTimeout> | null = null;
54+const rand = mulberry32((Math.random() * 2 ** 31) | 0);
55+
56+let gen = 0;
57+let genE = 0;
58+let genStart = 0;
59+let genPoints = 0;
60+let genM2 = 0;
61+let genL2 = 0;
62+let orbits: Orbit[] = [];
63+
64+self.onmessage = (ev: MessageEvent<OrbitConfig>) => {
65+ const reset = cfg?.reset ?? false;
66+ cfg = ev.data;
67+ cfg.reset ||= reset; // keep a pending reset until work() has seen it
68+ if (cfg.running && timer === null) timer = setTimeout(work, 0);
69+};
70+
71+function newPortrait(c: OrbitConfig) {
72+ gen++;
73+ genE = c.energy;
74+ genStart = performance.now();
75+ genPoints = 0;
76+ genM2 = c.m2;
77+ genL2 = c.l2;
78+ orbits = [];
79+}
80+
81+function seed(o: Orbit) {
82+ o.crossings = 0;
83+ o.prev = 0;
84+ o.ok = seedOnSection(o.pend, genE, rand);
85+}
86+
87+function work() {
88+ timer = null;
89+ const c = cfg;
90+ if (!c || !c.running) return;
91+ const sleep = (ms: number) => (timer = setTimeout(work, ms));
92+ if (c.energy < 1e-5) return void sleep(100);
93+
94+ const age = (performance.now() - genStart) / 1000;
95+ const drift = genE > 0 ? Math.abs(Math.log(c.energy / genE)) : Infinity;
96+ if (gen === 0 || c.reset || c.m2 !== genM2 || c.l2 !== genL2 || (drift > Math.log(1 + c.band) && age >= c.minHold)) {
97+ c.reset = false;
98+ newPortrait(c);
99+ }
100+ if (genPoints >= c.maxPoints) return void sleep(50); // portrait complete: idle
101+
102+ const count = Math.max(1, Math.round(c.count));
103+ while (orbits.length < count) {
104+ const pend = new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: genM2, l2: genL2 });
105+ pend.controlled = false;
106+ const o: Orbit = { pend, crossings: 0, prev: 0, ok: false };
107+ seed(o);
108+ orbits.push(o);
109+ }
110+ if (orbits.length > count) orbits.length = count;
111+
112+ const out: number[] = [];
113+ const t0 = performance.now();
114+ while (performance.now() - t0 < SLICE_MS) {
115+ for (const o of orbits) {
116+ if (!o.ok || o.crossings >= c.life) {
117+ seed(o);
118+ if (!o.ok) continue;
119+ }
120+ const P = o.pend;
121+ const y = P.y;
122+ for (let i = 0; i < STEPS_PER_CHECK; i++) {
123+ const pTh2 = y[1], pP2 = y[3];
124+ P.step(DT);
125+ const cur = wrapAngle(y[0]);
126+ if (o.prev < 0 && cur >= 0 && cur - o.prev < Math.PI) {
127+ const f = -o.prev / (cur - o.prev);
128+ out.push(wrapAngle(pTh2 + f * (y[1] - pTh2)), (pP2 + f * (y[3] - pP2)) / P.p2Scale);
129+ o.crossings++;
130+ }
131+ o.prev = cur;
132+ }
133+ }
134+ }
135+ genPoints += out.length / 2;
136+
137+ if (out.length) {
138+ const pts = new Float32Array(out);
139+ const msg: OrbitBatch = { gen, energy: genE, pts };
140+ (self as unknown as Worker).postMessage(msg, [pts.buffer]);
141+ }
142+ const cpu = Math.max(0.02, Math.min(1, c.cpu));
143+ sleep((SLICE_MS * (1 - cpu)) / cpu);
144+}
src/compositions/c01-poincare/piece.tsadded+605−0View file
@@ -0,0 +1,605 @@
1+// Composition 1: a double pendulum and its Poincaré section.
2+//
3+// Section: θ1 = 0 crossed upward (dθ1/dt > 0); plotted at (θ2, p2).
4+// Each crossing plays a note: θ2 → pitch, |p2| → loudness, θ2 → pan.
5+// A hum runs throughout; its timbre follows the energy.
6+// Energy is steered along an envelope: small → peak → hold → zero.
7+// Notes stop at the end and the last one is held and faded.
8+// Behind the live crossings, a worker draws the section's orbits at the current energy.
9+
10+import type { AudioEngine } from "../../core/audio.ts";
11+import { dbToGain } from "../../core/audio.ts";
12+import type { Piece } from "../../core/composition.ts";
13+import type { Params } from "../../core/params.ts";
14+import { mulberry32, randomSeed } from "../../core/rng.ts";
15+import { DRONE_INSTRUMENTS, NOTE_INSTRUMENTS } from "../../instruments/index.ts";
16+import type { DroneInstrument, NoteHandle, NoteInstrument } from "../../instruments/types.ts";
17+import { NOTE_NAMES, midiToFreq, quantize } from "../../music/scales.ts";
18+import { DoublePendulum, wrapAngle } from "../../physics/doublePendulum.ts";
19+import { energyTarget } from "./form.ts";
20+import type { OrbitBatch, OrbitConfig } from "./orbitWorker.ts";
21+
22+const DT = 0.002; // simulation step (sim seconds)
23+const LOOKAHEAD = 0.15; // audio scheduled this far ahead (s)
24+const TICK_MS = 25;
25+const MAX_SETTLE = 10; // s after duration: count the pendulum as at rest regardless
26+const HISTORY_DT = 1 / 960; // piece-time spacing of stored pendulum snapshots
27+const BLUR_MAX_SAMPLES = 64; // cap on sub-frame positions drawn for motion blur
28+const BLUR_SPACING_PX = 2; // target distance the tip moves between blur samples
29+
30+interface Snapshot {
31+ t: number;
32+ th1: number;
33+ th2: number;
34+}
35+
36+interface Crossing {
37+ t: number; // piece time
38+ th2: number; // wrapped
39+ p2: number; // normalized
40+}
41+
42+export function createPoincarePiece(view: HTMLElement, params: () => Params): Piece {
43+ view.classList.add("c01");
44+ // one canvas: the Poincaré section, with the pendulum as an inset in its upper-left corner
45+ const plotCanvas = document.createElement("canvas");
46+ view.append(plotCanvas);
47+
48+ let pend: DoublePendulum | null = null;
49+ let audio: AudioEngine | null = null;
50+ let notes: NoteInstrument | null = null;
51+ let noteKey = ""; // instrument name (+ custom settings) the current instance was built from
52+ let noteBus: GainNode | null = null; // notes level
53+ let humKey = "";
54+ let startToken = 0;
55+ let hum: DroneInstrument | null = null;
56+ let out: GainNode | null = null;
57+ let timer: number | undefined;
58+ let playing = false;
59+ let pieceStart = 0; // AudioContext time of piece time 0
60+ let simPieceT = 0; // piece time of the simulation state
61+ let seedUsed = 0;
62+ let noteCount = 0;
63+ let stoppedAt = 0;
64+ let history: Snapshot[] = [];
65+ let lastHistT = -Infinity;
66+ let points: Crossing[] = [];
67+ let thR = Math.PI; // plot half-ranges (smoothed)
68+ let pR = 1;
69+ // final note
70+ let lastNote: { handle: NoteHandle; when: number } | null = null;
71+ // The ending comes from the simulation: once the energy target is zero and the pendulum's
72+ // energy falls below restEnergy it is at rest. No crossings register after that; the last
73+ // real note is held and faded, the hum fades with it, and the piece ends with the fade.
74+ let restAt: number | null = null; // piece time the pendulum came to rest
75+
76+ // background orbit portraits (worker). Each portrait is at one fixed energy; when a new one
77+ // arrives, the older ones are retired and crossfade out.
78+ interface Portrait {
79+ gen: number;
80+ energy: number;
81+ pts: number[]; // [θ2, p2, …]
82+ retiredAt: number | null;
83+ }
84+ let worker: Worker | null = null;
85+ let portraits: Portrait[] = [];
86+ let resetOrbits = false;
87+ let latestGen = 0;
88+ let ignoreBelow = 0; // batches from portraits started before the last reset
89+ let orbitRate = 0; // points per second, smoothed, for the readout
90+ let orbitNew = 0;
91+ let orbitRateT = 0;
92+
93+ const piece: Piece = {
94+ get playing() {
95+ return playing;
96+ },
97+ start,
98+ stop,
99+ draw,
100+ now,
101+ length: () => endTime(params()),
102+ readouts,
103+ dispose() {
104+ stop();
105+ worker?.terminate();
106+ worker = null;
107+ view.classList.remove("c01");
108+ view.replaceChildren();
109+ },
110+ };
111+
112+ function now(): number {
113+ if (!audio || !playing) return stoppedAt;
114+ return audio.ctx.currentTime - pieceStart;
115+ }
116+
117+ // ── orbits ──
118+
119+ function ensureWorker(): Worker {
120+ if (!worker) {
121+ worker = new Worker(new URL("./orbitWorker.ts", import.meta.url), { type: "module" });
122+ worker.onmessage = (ev: MessageEvent<OrbitBatch>) => {
123+ if (!playing) return;
124+ const { gen, energy, pts } = ev.data;
125+ latestGen = Math.max(latestGen, gen);
126+ if (gen < ignoreBelow) return;
127+ let cur = portraits[portraits.length - 1];
128+ if (!cur || gen > cur.gen) {
129+ const t = now();
130+ for (const p of portraits) p.retiredAt ??= t;
131+ cur = { gen, energy, pts: [], retiredAt: null };
132+ portraits.push(cur);
133+ } else if (gen < cur.gen) return; // stale batch from before a reset
134+ for (let i = 0; i < pts.length; i++) cur.pts.push(pts[i]);
135+ orbitNew += pts.length / 2;
136+ };
137+ }
138+ return worker;
139+ }
140+
141+ function postOrbitConfig(running: boolean) {
142+ const P = params();
143+ if (!P.orbits && !worker) return;
144+ const msg: OrbitConfig = {
145+ running: running && (P.orbits as boolean),
146+ reset: resetOrbits,
147+ energy: pend ? pend.energyNorm() : 0,
148+ m2: P.massRatio as number,
149+ l2: P.lengthRatio as number,
150+ count: Math.round(P.orbitCount as number),
151+ life: P.orbitLife as number,
152+ band: P.orbitBand as number,
153+ minHold: P.orbitMinHold as number,
154+ maxPoints: P.orbitMaxPoints as number,
155+ cpu: P.orbitCpu as number,
156+ };
157+ resetOrbits = false;
158+ ensureWorker().postMessage(msg);
159+ }
160+
161+ // ── transport ──
162+
163+ function makePendulum(P: Params): DoublePendulum {
164+ return new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number });
165+ }
166+
167+ async function start(a: AudioEngine, offset: number) {
168+ stop();
169+ const token = ++startToken;
170+ audio = a;
171+ const P = params();
172+ const ctx = a.ctx;
173+ seedUsed = (P.seed as number) > 0 ? Math.round(P.seed as number) : randomSeed();
174+ pend = makePendulum(P);
175+ pend.randomize(energyTarget(P, 0), mulberry32(seedUsed));
176+ pend.tau = P.tau as number;
177+ simPieceT = 0;
178+ history = [];
179+ lastHistT = -Infinity;
180+ points = [];
181+ // the worker starts a fresh portrait
182+ portraits = [];
183+ ignoreBelow = latestGen + 1;
184+ resetOrbits = true;
185+ noteCount = 0;
186+ lastNote = null;
187+ restAt = null;
188+ // fast-forward silently to the start offset (author "start at")
189+ if (offset > 0) advanceTo(offset, false);
190+
191+ out = ctx.createGain();
192+ out.connect(a.input);
193+ ensureInstruments();
194+ await Promise.all([notes?.ready, hum?.ready]); // e.g. the modal-synth worklet loading
195+ if (token !== startToken) return; // stopped or restarted meanwhile
196+ pieceStart = ctx.currentTime + 0.1 - offset;
197+ hum!.start(ctx.currentTime + 0.05, midiToFreq(P.humPitch as number));
198+ playing = true;
199+ tick();
200+ timer = window.setInterval(tick, TICK_MS);
201+ }
202+
203+ function ensureInstruments() {
204+ if (!audio || !out) return;
205+ const P = params();
206+ if (!noteBus) {
207+ noteBus = audio.ctx.createGain();
208+ noteBus.connect(out);
209+ }
210+ noteBus.gain.setTargetAtTime(dbToGain(P.notesLevel as number), audio.ctx.currentTime, 0.05);
211+ const name = P.noteInstrument as string;
212+ const key = name === "modal: custom" ? `${name}\n${P.modalCustom}` : name;
213+ if (!notes || noteKey !== key) {
214+ notes?.dispose();
215+ noteKey = key;
216+ notes = NOTE_INSTRUMENTS[name](audio.ctx, noteBus, { custom: P.modalCustom as string });
217+ }
218+ const hName = P.humInstrument as string;
219+ const hKey = hName === "modal: custom" ? `${hName}\n${P.humCustom}` : hName;
220+ if (!hum || humKey !== hKey) {
221+ const old = hum;
222+ humKey = hKey;
223+ hum = DRONE_INSTRUMENTS[hName](audio.ctx, out, { custom: P.humCustom as string });
224+ if (old && playing) {
225+ // switched while playing: crossfade to the new hum
226+ const t = audio.ctx.currentTime;
227+ old.stop(t + 0.5, 0.5);
228+ window.setTimeout(() => old.dispose(), 1500);
229+ const h = hum;
230+ void (h.ready ?? Promise.resolve()).then(() => h === hum && h.start(audio!.ctx.currentTime + 0.05, midiToFreq(P.humPitch as number)));
231+ }
232+ }
233+ }
234+
235+ function stop() {
236+ startToken++;
237+ if (timer !== undefined) window.clearInterval(timer);
238+ timer = undefined;
239+ const wasPlaying = playing;
240+ if (playing) {
241+ stoppedAt = now();
242+ playing = false;
243+ postOrbitConfig(false);
244+ }
245+ // release the audio graph (also when a start is still waiting for its instrument to load)
246+ if (!audio) return;
247+ const t = audio.ctx.currentTime;
248+ if (wasPlaying) hum?.stop(t + 0.3, 0.3); // a hum is only started once playing
249+ const o = out;
250+ if (o) {
251+ o.gain.setTargetAtTime(0, t, 0.05);
252+ window.setTimeout(() => o.disconnect(), 600);
253+ }
254+ const h = hum;
255+ window.setTimeout(() => h?.dispose(), 600);
256+ hum = null;
257+ humKey = "";
258+ notes?.dispose();
259+ notes = null;
260+ noteKey = "";
261+ noteBus = null;
262+ out = null;
263+ }
264+
265+ // ── simulation ──
266+
267+ /** Simulate up to piece time `target`; schedule notes if `sound`. */
268+ function advanceTo(target: number, sound: boolean) {
269+ if (!pend) return;
270+ const P = params();
271+ pend.cfg.m2 = P.massRatio as number;
272+ pend.cfg.l2 = P.lengthRatio as number;
273+ pend.tau = P.tau as number;
274+ const speed = P.speed as number;
275+ const duration = P.duration as number;
276+ const restE = P.restEnergy as number;
277+ const y = pend.y;
278+ let prev = wrapAngle(y[0]);
279+ let prevTh2 = y[1];
280+ let prevP2 = y[3];
281+ let prevT = simPieceT;
282+ while (simPieceT < target) {
283+ pend.eTarget = energyTarget(P, simPieceT) * pend.vTop;
284+ pend.step(DT);
285+ simPieceT += DT / speed;
286+ const cur = wrapAngle(y[0]);
287+ if (restAt === null && prev < 0 && cur >= 0 && cur - prev < Math.PI) {
288+ const f = -prev / (cur - prev);
289+ const c: Crossing = {
290+ t: prevT + f * (simPieceT - prevT),
291+ th2: wrapAngle(prevTh2 + f * (y[1] - prevTh2)),
292+ p2: (prevP2 + f * (y[3] - prevP2)) / pend.p2Scale,
293+ };
294+ points.push(c);
295+ if (sound) playNote(c, P);
296+ }
297+ if (restAt === null && simPieceT >= duration && (pend.energyNorm() < restE || simPieceT >= duration + MAX_SETTLE)) {
298+ restAt = simPieceT;
299+ if (sound) holdFinalNote(P);
300+ }
301+ prev = cur;
302+ prevTh2 = y[1];
303+ prevP2 = y[3];
304+ prevT = simPieceT;
305+ if (simPieceT - lastHistT >= HISTORY_DT) {
306+ history.push({ t: simPieceT, th1: y[0], th2: y[1] });
307+ lastHistT = simPieceT;
308+ }
309+ }
310+ }
311+
312+ function playNote(c: Crossing, P: Params) {
313+ if (!audio || !notes) return;
314+ const when = pieceStart + c.t;
315+ if (when < audio.ctx.currentTime - 0.02) return; // too late (e.g. tab was in background)
316+
317+ const range = P.thetaRange as number;
318+ let u =
319+ P.pitchSource === "absolute"
320+ ? Math.min(1, Math.abs(c.th2) / range)
321+ : Math.max(0, Math.min(1, 0.5 + (0.5 * c.th2) / range));
322+ if (P.invertPitch) u = 1 - u;
323+ u = Math.pow(u, P.pitchCurve as number);
324+ const low = P.pitchLow as number, high = P.pitchHigh as number;
325+ const root = NOTE_NAMES.indexOf(P.root as string);
326+ const midi = quantize(low + (high - low) * u, P.scale as string, root);
327+
328+ const x = Math.min(1, Math.abs(c.p2) / (P.p2Ref as number));
329+ const floor = P.loudFloor as number;
330+ const vel = floor + (1 - floor) * Math.pow(x, P.loudCurve as number);
331+
332+ const freq = midiToFreq(midi);
333+ const pan = (P.panAmount as number) * Math.max(-1, Math.min(1, c.th2 / Math.PI));
334+ const handle = notes.play({ when, freq, velocity: vel, pan, duration: P.noteLength as number });
335+ if (handle) lastNote = { handle, when };
336+ noteCount++;
337+ }
338+
339+ /** Let the last real note ring: sustain it for finalHold, then fade over finalFade. */
340+ function holdFinalNote(P: Params) {
341+ if (!lastNote) return;
342+ lastNote.handle.hold(lastNote.when, P.finalHold as number, P.finalFade as number);
343+ }
344+
345+ /** Piece time at which everything has faded: known once the pendulum is at rest, estimated before. */
346+ function endTime(P: Params): number {
347+ const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
348+ return (restAt ?? (P.duration as number) + 0.5) + ring;
349+ }
350+
351+ function tick() {
352+ if (!audio || !pend || !playing) return;
353+ const P = params();
354+ ensureInstruments();
355+ const ctx = audio.ctx;
356+ const t = ctx.currentTime - pieceStart;
357+ const total = endTime(P);
358+ if (restAt !== null && t >= total) {
359+ stop();
360+ stoppedAt = total;
361+ piece.onEnded?.();
362+ return;
363+ }
364+ advanceTo(t + LOOKAHEAD, true);
365+ postOrbitConfig(true);
366+
367+ // hum
368+ const e = pend.energyNorm();
369+ const peak = P.energyPeak as number;
370+ const rel = Math.max(0, Math.min(1, e / peak));
371+ const e0 = Math.min(P.energyStart as number, 0.999 * peak);
372+ const colorBase =
373+ P.humColorMode === "log" ? Math.max(0, Math.min(1, Math.log(Math.max(e, 1e-12) / e0) / Math.log(peak / e0))) : rel;
374+ const fadeIn = P.humFadeIn as number;
375+ const fadeOut = P.humFadeOut as number;
376+ // the hum's fade-out ends with the last note's fade (only once the pendulum is at rest)
377+ const fade = Math.min(1, fadeIn > 0 ? t / fadeIn : 1, restAt !== null && fadeOut > 0 ? (total - t) / fadeOut : 1);
378+ const follow = P.humFollow as number;
379+ const level = dbToGain(P.humLevel as number) * Math.max(0, fade) * (1 - follow + follow * rel);
380+ hum?.set(ctx.currentTime, {
381+ level,
382+ color: Math.pow(colorBase, P.humColorCurve as number),
383+ freq: midiToFreq(P.humPitch as number),
384+ normalize: P.humNormalize as boolean,
385+ timbre: [1, 2]
386+ .filter((i) => P[`humTarget${i}`] !== "none")
387+ .map((i) => ({ target: P[`humTarget${i}`] as string, from: P[`humFrom${i}`] as number, to: P[`humTo${i}`] as number })),
388+ });
389+
390+ // trim history to what drawing still needs
391+ let i = 0;
392+ while (i < history.length - 1 && history[i + 1].t <= t - 0.1) i++;
393+ if (i > 0) history.splice(0, i);
394+ }
395+
396+ // ── drawing ──
397+
398+ function fit(c: HTMLCanvasElement): CanvasRenderingContext2D {
399+ const dpr = window.devicePixelRatio || 1;
400+ const w = Math.round(c.clientWidth * dpr);
401+ const h = Math.round(c.clientHeight * dpr);
402+ if (c.width !== w || c.height !== h) {
403+ c.width = w;
404+ c.height = h;
405+ }
406+ const g = c.getContext("2d")!;
407+ g.setTransform(dpr, 0, 0, dpr, 0, 0);
408+ return g;
409+ }
410+
411+ function color(name: string): string {
412+ return getComputedStyle(view).getPropertyValue(name).trim() || "#ccc";
413+ }
414+
415+ /** Pendulum angles at piece time t, interpolated between stored snapshots. */
416+ function stateAt(t: number): { th1: number; th2: number } {
417+ const n = history.length;
418+ if (!n) return pend ? { th1: pend.y[0], th2: pend.y[1] } : { th1: 0, th2: 0 };
419+ if (t <= history[0].t) return history[0];
420+ if (t >= history[n - 1].t) return history[n - 1];
421+ let lo = 0, hi = n - 1; // history[lo].t <= t < history[hi].t
422+ while (hi - lo > 1) {
423+ const mid = (lo + hi) >> 1;
424+ if (history[mid].t <= t) lo = mid;
425+ else hi = mid;
426+ }
427+ const a = history[lo], b = history[hi];
428+ const f = (t - a.t) / (b.t - a.t);
429+ return { th1: a.th1 + f * (b.th1 - a.th1), th2: a.th2 + f * (b.th2 - a.th2) };
430+ }
431+
432+ let lastDrawWall = 0;
433+ let frameDt = 1 / 60; // smoothed display frame interval (s)
434+
435+ /**
436+ * The pendulum as an inset in the plot's upper-left corner (outside the energetically allowed
437+ * region of the section most of the time), drawn as before: solid arms and filled bobs.
438+ * Motion blur: several faint positions spread over the last frame interval.
439+ */
440+ function drawPendulum(g: CanvasRenderingContext2D, w: number, h: number, P: Params, t: number) {
441+ const opacity = P.pendulumAlpha as number;
442+ if (opacity <= 0) return;
443+ const shutter = playing ? (P.motionBlur as number) * frameDt : 0;
444+ const l1 = 1, l2 = P.lengthRatio as number;
445+ const R = ((P.pendulumSize as number) * Math.min(w, h)) / 2; // inset radius
446+ const scale = (0.9 * R) / (l1 + l2);
447+ const x0 = 8 + R, y0 = 8 + R; // pivot
448+
449+ // enough samples that the tip moves ~BLUR_SPACING_PX between them
450+ let k = 1;
451+ if (shutter > 0) {
452+ let path = 0;
453+ let a = stateAt(t);
454+ for (let j = 1; j <= 8; j++) {
455+ const b = stateAt(t - (shutter * j) / 8);
456+ path += scale * (l1 * Math.abs(b.th1 - a.th1) + l2 * Math.abs(b.th2 - a.th2));
457+ a = b;
458+ }
459+ k = Math.max(2, Math.min(BLUR_MAX_SAMPLES, Math.ceil(path / BLUR_SPACING_PX)));
460+ }
461+ // per-sample alpha so a still pendulum still draws (nearly) fully opaque
462+ const alpha = opacity * (k === 1 ? 1 : 1 - Math.pow(0.03, 1 / k));
463+ const r1 = 3, r2 = 3 * Math.cbrt(P.massRatio as number);
464+ const fg = color("--fg");
465+ g.strokeStyle = fg;
466+ g.fillStyle = fg;
467+ g.lineWidth = 1.5;
468+ g.lineCap = "round";
469+ g.globalAlpha = alpha;
470+ for (let i = 0; i < k; i++) {
471+ const { th1, th2 } = stateAt(t - (shutter * i) / Math.max(1, k - 1));
472+ const x1 = x0 + scale * l1 * Math.sin(th1), y1 = y0 + scale * l1 * Math.cos(th1);
473+ const x2 = x1 + scale * l2 * Math.sin(th2), y2 = y1 + scale * l2 * Math.cos(th2);
474+ g.beginPath();
475+ g.moveTo(x0, y0);
476+ g.lineTo(x1, y1);
477+ g.lineTo(x2, y2);
478+ g.stroke();
479+ g.beginPath();
480+ g.arc(x1, y1, r1, 0, 2 * Math.PI);
481+ g.moveTo(x2 + r2, y2);
482+ g.arc(x2, y2, r2, 0, 2 * Math.PI);
483+ g.fill();
484+ }
485+ g.globalAlpha = opacity;
486+ g.beginPath();
487+ g.arc(x0, y0, 1.5, 0, 2 * Math.PI);
488+ g.fill();
489+ g.globalAlpha = 1;
490+ }
491+
492+ function draw() {
493+ const P = params();
494+ const t = now();
495+ const wall = performance.now() / 1000;
496+ const dtw = wall - lastDrawWall;
497+ lastDrawWall = wall;
498+ if (dtw > 0 && dtw < 0.1) frameDt += (dtw - frameDt) * 0.1;
499+ const fg = color("--fg");
500+ const dim = color("--dim");
501+
502+ // Poincaré section
503+ {
504+ const g = fit(plotCanvas);
505+ const w = plotCanvas.clientWidth, h = plotCanvas.clientHeight;
506+ g.clearRect(0, 0, w, h);
507+ let thT = Math.PI, pT = P.plotP as number;
508+ if (P.plotZoom === "fit energy" && pend) {
509+ // exact extent of the energetically allowed region of the section (θ1 = 0):
510+ // p2² ≤ 2·m2·l2²·(E − V(θ2)), so |p2|max = √(2e) in normalized units,
511+ // and |θ2| ≤ acos(1 − E/(m2·g·l2)).
512+ const e = Math.max(1e-6, pend.energyNorm());
513+ const E = e * pend.vTop;
514+ const m2 = pend.cfg.m2, l2 = pend.cfg.l2, gr = pend.cfg.g;
515+ const th = E >= 2 * m2 * gr * l2 ? Math.PI : Math.acos(1 - E / (m2 * gr * l2));
516+ thT = Math.min(Math.PI, 1.08 * th);
517+ pT = 1.08 * Math.sqrt(2 * e);
518+ }
519+ // ease toward the target range with a time constant, in log space so zooming in and out feel alike
520+ const ease = dtw > 0 && dtw < 0.5 ? 1 - Math.exp(-dtw / Math.max(0.01, P.zoomSmooth as number)) : 1;
521+ thR *= Math.exp(ease * Math.log(thT / thR));
522+ pR *= Math.exp(ease * Math.log(pT / pR));
523+ const pad = 8;
524+ const kx = (w / 2 - pad) / thR, ky = (h / 2 - pad) / pR;
525+ const sx = (th: number) => w / 2 + kx * th;
526+ const sy = (p: number) => h / 2 - ky * p;
527+ g.strokeStyle = dim;
528+ g.lineWidth = 1;
529+ g.beginPath();
530+ g.moveTo(pad, h / 2);
531+ g.lineTo(w - pad, h / 2);
532+ g.moveTo(w / 2, pad);
533+ g.lineTo(w / 2, h - pad);
534+ g.stroke();
535+
536+ // background orbit portraits
537+ if (P.orbits) {
538+ const xfade = P.orbitXfade as number;
539+ const alpha = P.orbitAlpha as number;
540+ const sz = P.orbitSize as number;
541+ portraits = portraits.filter((p) => p.retiredAt === null || t - p.retiredAt < xfade);
542+ g.fillStyle = fg;
543+ for (const p of portraits) {
544+ g.globalAlpha = alpha * (p.retiredAt === null ? 1 : Math.max(0, 1 - (t - p.retiredAt) / xfade));
545+ g.beginPath();
546+ const d = p.pts;
547+ for (let i = 0; i < d.length; i += 2) g.rect(sx(d[i]) - sz / 2, sy(d[i + 1]) - sz / 2, sz, sz);
548+ g.fill();
549+ }
550+ g.globalAlpha = 1;
551+ }
552+
553+ // the pendulum's own crossings
554+ const fade = P.fade as number;
555+ const size = P.pointSize as number;
556+ let drop = 0;
557+ while (drop < points.length && t - points[drop].t > 4.6 * fade) drop++;
558+ if (drop > 0) points.splice(0, drop);
559+ g.fillStyle = fg;
560+ for (const c of points) {
561+ const age = t - c.t;
562+ if (age < 0) break; // not sounded yet
563+ g.globalAlpha = Math.exp(-age / fade);
564+ g.beginPath();
565+ g.arc(sx(c.th2), sy(c.p2), size / 2, 0, 2 * Math.PI);
566+ g.fill();
567+ if (age < 0.4) {
568+ // brief ring on the newest crossings
569+ g.globalAlpha = 1 - age / 0.4;
570+ g.strokeStyle = fg;
571+ g.beginPath();
572+ g.arc(sx(c.th2), sy(c.p2), size / 2 + 3 + 12 * age, 0, 2 * Math.PI);
573+ g.stroke();
574+ }
575+ }
576+ g.globalAlpha = 1;
577+ drawPendulum(g, w, h, P, t);
578+ }
579+ }
580+
581+ function readouts(): Record<string, string> {
582+ const P = params();
583+ const t = now();
584+ const wall = performance.now() / 1000;
585+ if (wall - orbitRateT > 1) {
586+ orbitRate = orbitNew / (wall - orbitRateT || 1);
587+ orbitNew = 0;
588+ orbitRateT = wall;
589+ }
590+ return {
591+ time: `${t.toFixed(1)} / ${piece.length().toFixed(0)} s`,
592+ "energy target": energyTarget(P, t).toFixed(4),
593+ energy: pend ? pend.energyNorm().toFixed(4) : "–",
594+ notes: String(noteCount),
595+ "seed used": seedUsed ? String(seedUsed) : "–",
596+ hum: hum?.describe?.() || "–",
597+ "orbit portrait": (() => {
598+ const p = portraits.find((q) => q.retiredAt === null);
599+ return p ? `E ${p.energy.toFixed(4)}, ${p.pts.length / 2} pts, ${Math.round(orbitRate)}/s` : "–";
600+ })(),
601+ };
602+ }
603+
604+ return piece;
605+}
src/compositions/c01-poincare/schema.tsadded+87−0View file
@@ -0,0 +1,87 @@
1+import type { ParamSpec } from "../../core/params.ts";
2+import { DRONE_INSTRUMENTS, NOTE_INSTRUMENTS } from "../../instruments/index.ts";
3+import { LIVE_TARGETS } from "../../instruments/modal.ts";
4+import { NOTE_NAMES, SCALE_NAMES } from "../../music/scales.ts";
5+
6+// Energies are in units of the potential energy with both arms straight up.
7+// Momentum p2 is in units of √(m2·l2²·E_top).
8+
9+export const schema: ParamSpec[] = [
10+ // ── form ──
11+ { group: "form", key: "duration", label: "duration", kind: "number", default: 60, min: 10, max: 600, step: 1, unit: "s", hint: "energy returns to zero at this time" },
12+ { group: "form", key: "peakTime", label: "peak at", kind: "number", default: 25, min: 1, max: 600, step: 0.5, unit: "s" },
13+ { group: "form", key: "holdTime", label: "hold", kind: "number", default: 10, min: 0, max: 600, step: 0.5, unit: "s" },
14+ { group: "form", key: "energyStart", label: "start energy", kind: "number", default: 0.005, min: 0.0001, max: 1, log: true },
15+ { group: "form", key: "energyPeak", label: "peak energy", kind: "number", default: 1.2, min: 0.01, max: 5, log: true },
16+ { group: "form", key: "riseShape", label: "rise shape", kind: "select", default: "exponential", options: ["exponential", "linear"] },
17+ { group: "form", key: "riseCurve", label: "rise curve", kind: "number", default: 1, min: 0.2, max: 5, log: true, hint: "exponent on the rise; >1 starts slow" },
18+ { group: "form", key: "fallCurve", label: "fall curve", kind: "number", default: 1, min: 0.2, max: 5, log: true, hint: "exponent on the fall; >1 drops fast then lingers" },
19+ { group: "form", key: "restEnergy", label: "rest energy", kind: "number", default: 0.001, min: 0.00001, max: 0.05, log: true, hint: "after duration, the pendulum counts as at rest below this energy: no more crossings; the last note rings out" },
20+ { group: "form", key: "finalHold", label: "final hold", kind: "number", default: 2, min: 0, max: 20, step: 0.1, unit: "s", hint: "the last note sustains this long…" },
21+ { group: "form", key: "finalFade", label: "final fade", kind: "number", default: 5, min: 0.1, max: 30, step: 0.1, unit: "s", hint: "…then fades out over this long; the piece ends with it" },
22+
23+ // ── physics ──
24+ { group: "physics", key: "speed", label: "speed", kind: "number", default: 12, min: 0.5, max: 100, log: true, unit: "×", hint: "simulated seconds per real second" },
25+ { group: "physics", key: "massRatio", label: "m2 / m1", kind: "number", default: 1, min: 0.1, max: 10, log: true },
26+ { group: "physics", key: "lengthRatio", label: "l2 / l1", kind: "number", default: 1, min: 0.1, max: 10, log: true },
27+ { group: "physics", key: "tau", label: "energy follow", kind: "number", default: 2, min: 0.1, max: 50, log: true, unit: "sim s", hint: "how quickly the energy tracks its target" },
28+ { group: "physics", key: "seed", label: "seed", kind: "number", default: 0, min: 0, max: 999999, step: 1, hint: "0 = a new variation every play" },
29+
30+ // ── notes (one per Poincaré crossing) ──
31+ { group: "notes", key: "noteInstrument", label: "instrument", kind: "select", default: "placeholder tone", options: Object.keys(NOTE_INSTRUMENTS), hint: "modal: … instruments come from the modal-synth project" },
32+ { group: "notes", key: "modalCustom", label: "modal custom", kind: "text", default: "", hint: "for “modal: custom”: paste JSON from modal-synth’s Copy button" },
33+ { group: "notes", key: "scale", label: "scale", kind: "select", default: "pentatonic minor", options: SCALE_NAMES },
34+ { group: "notes", key: "root", label: "root", kind: "select", default: "D", options: NOTE_NAMES },
35+ { group: "notes", key: "pitchSource", label: "pitch from θ2", kind: "select", default: "signed", options: ["signed", "absolute"], hint: "signed: −range→low, +range→high. absolute: 0→low, ±range→high" },
36+ { group: "notes", key: "thetaRange", label: "θ2 range", kind: "number", default: 3.1416, min: 0.02, max: 3.1416, log: true, unit: "rad" },
37+ { group: "notes", key: "pitchLow", label: "low pitch", kind: "number", default: 50, min: 12, max: 120, step: 0.5, unit: "midi" },
38+ { group: "notes", key: "pitchHigh", label: "high pitch", kind: "number", default: 86, min: 12, max: 120, step: 0.5, unit: "midi" },
39+ { group: "notes", key: "pitchCurve", label: "pitch curve", kind: "number", default: 1, min: 0.2, max: 5, log: true },
40+ { group: "notes", key: "invertPitch", label: "invert pitch", kind: "bool", default: false },
41+ { group: "notes", key: "p2Ref", label: "|p2| for full", kind: "number", default: 1, min: 0.01, max: 4, log: true, hint: "|p2| that gives full loudness" },
42+ { group: "notes", key: "loudCurve", label: "loudness curve", kind: "number", default: 1, min: 0.2, max: 5, log: true },
43+ { group: "notes", key: "loudFloor", label: "loudness floor", kind: "number", default: 0.08, min: 0, max: 1, step: 0.01, hint: "loudness of a crossing with p2 = 0" },
44+ { group: "notes", key: "notesLevel", label: "level", kind: "number", default: -6, min: -48, max: 6, step: 0.5, unit: "dB" },
45+ { group: "notes", key: "noteLength", label: "length", kind: "number", default: 1.5, min: 0.05, max: 10, log: true, unit: "s" },
46+ { group: "notes", key: "panAmount", label: "pan from θ2", kind: "number", default: 0.6, min: 0, max: 1, step: 0.01, hint: "placeholder tone only; modal instruments have their own stereo image" },
47+
48+ // ── hum (energy) ──
49+ { group: "hum", key: "humInstrument", label: "instrument", kind: "select", default: "modal: Clarinet-ish", options: Object.keys(DRONE_INSTRUMENTS), hint: "modal: … = one held note of a sustained modal-synth preset" },
50+ { group: "hum", key: "humCustom", label: "modal custom", kind: "text", default: "", hint: "for “modal: custom”: paste JSON from modal-synth’s Copy button" },
51+ { group: "hum", key: "humPitch", label: "pitch", kind: "number", default: 38, min: 12, max: 72, step: 0.5, unit: "midi" },
52+ { group: "hum", key: "humLevel", label: "level", kind: "number", default: -24, min: -60, max: 0, step: 0.5, unit: "dB" },
53+ { group: "hum", key: "humFollow", label: "loudness follows energy", kind: "number", default: 0, min: 0, max: 1, step: 0.01, hint: "0 = constant loudness" },
54+ { group: "hum", key: "humNormalize", label: "normalize loudness", kind: "bool", default: true, hint: "modal hum: measure the output and compensate slowly, so timbre changes don't change loudness" },
55+ { group: "hum", key: "humColorMode", label: "timbre from energy", kind: "select", default: "log", options: ["log", "power"], hint: "log: even steps per energy doubling, from start energy (0) to peak (1). power: (energy / peak)^curve" },
56+ { group: "hum", key: "humColorCurve", label: "timbre curve", kind: "number", default: 1, min: 0.1, max: 5, log: true, hint: "exponent applied to the timbre value" },
57+ { group: "hum", key: "humTarget1", label: "timbre → A", kind: "select", default: "pickup", options: ["none", ...LIVE_TARGETS], hint: "modal hum: synth setting driven by timbre (bow position, force, pressure, feedback, …)" },
58+ { group: "hum", key: "humFrom1", label: "A at low energy", kind: "number", default: 0.15, min: 0, max: 1, step: 0.005, hint: "fraction of the setting's range in modal-synth" },
59+ { group: "hum", key: "humTo1", label: "A at peak", kind: "number", default: 0.75, min: 0, max: 1, step: 0.005 },
60+ { group: "hum", key: "humTarget2", label: "timbre → B", kind: "select", default: "tilt", options: ["none", ...LIVE_TARGETS] },
61+ { group: "hum", key: "humFrom2", label: "B at low energy", kind: "number", default: 0.3333, min: 0, max: 1, step: 0.005 },
62+ { group: "hum", key: "humTo2", label: "B at peak", kind: "number", default: 0.5833, min: 0, max: 1, step: 0.005 },
63+ { group: "hum", key: "humFadeIn", label: "fade in", kind: "number", default: 3, min: 0, max: 60, step: 0.5, unit: "s" },
64+ { group: "hum", key: "humFadeOut", label: "fade out", kind: "number", default: 6, min: 0, max: 60, step: 0.5, unit: "s", hint: "ends together with the last note's fade" },
65+
66+ // ── visual ──
67+ { group: "visual", key: "pendulumAlpha", label: "pendulum opacity", kind: "number", default: 1, min: 0, max: 1, step: 0.01, hint: "0 = hide the pendulum" },
68+ { group: "visual", key: "pendulumSize", label: "pendulum size", kind: "number", default: 0.32, min: 0.1, max: 1, step: 0.01, hint: "inset diameter, as a fraction of the plot (upper-left corner)" },
69+ { group: "visual", key: "motionBlur", label: "motion blur", kind: "number", default: 1, min: 0, max: 4, step: 0.05, hint: "pendulum shutter, in display frames; 0 = off" },
70+ { group: "visual", key: "fade", label: "point fade", kind: "number", default: 10, min: 0.2, max: 120, log: true, unit: "s" },
71+ { group: "visual", key: "plotZoom", label: "plot zoom", kind: "select", default: "fit energy", options: ["fit energy", "fixed"], hint: "fit energy: frame the region the pendulum can reach at its current energy" },
72+ { group: "visual", key: "zoomSmooth", label: "zoom smoothing", kind: "number", default: 1.5, min: 0.05, max: 20, log: true, unit: "s", hint: "time constant of zoom changes" },
73+ { group: "visual", key: "plotP", label: "fixed p2 range", kind: "number", default: 1.5, min: 0.05, max: 5, log: true },
74+ { group: "visual", key: "pointSize", label: "point size", kind: "number", default: 2, min: 0.5, max: 8, step: 0.1, unit: "px" },
75+
76+ // ── orbits: live background portrait of the section at the current energy ──
77+ { group: "orbits", key: "orbits", label: "show orbits", kind: "bool", default: true },
78+ { group: "orbits", key: "orbitCount", label: "orbits", kind: "number", default: 24, min: 1, max: 64, step: 1, hint: "trajectories integrated in parallel, all at the portrait's energy" },
79+ { group: "orbits", key: "orbitCpu", label: "cpu", kind: "number", default: 0.4, min: 0.02, max: 0.9, step: 0.01, hint: "fraction of one core the background computation may use" },
80+ { group: "orbits", key: "orbitLife", label: "life", kind: "number", default: 300, min: 10, max: 5000, log: true, hint: "crossings before an orbit is reseeded elsewhere on the section" },
81+ { group: "orbits", key: "orbitBand", label: "refresh at", kind: "number", default: 0.25, min: 0.01, max: 2, log: true, hint: "start a new portrait when the energy has changed by this fraction" },
82+ { group: "orbits", key: "orbitMinHold", label: "min hold", kind: "number", default: 3, min: 0, max: 30, step: 0.1, unit: "s", hint: "a portrait is kept at least this long" },
83+ { group: "orbits", key: "orbitMaxPoints", label: "max points", kind: "number", default: 8000, min: 500, max: 40000, log: true, hint: "a portrait stops computing (and using CPU) once it has this many points" },
84+ { group: "orbits", key: "orbitXfade", label: "crossfade", kind: "number", default: 1.5, min: 0.05, max: 10, log: true, unit: "s", hint: "time for the old portrait to fade out once a new one starts" },
85+ { group: "orbits", key: "orbitAlpha", label: "brightness", kind: "number", default: 0.3, min: 0.02, max: 1, step: 0.01 },
86+ { group: "orbits", key: "orbitSize", label: "point size", kind: "number", default: 1, min: 0.5, max: 4, step: 0.1, unit: "px" },
87+];
src/compositions/index.tsadded+6−0View file
@@ -0,0 +1,6 @@
1+import type { Composition } from "../core/composition.ts";
2+import { poincare } from "./c01-poincare/index.ts";
3+
4+/** Track list, in album order. */
5+export const ALBUM_TITLE = "double pendulum";
6+export const COMPOSITIONS: Composition[] = [poincare];
src/core/audio.tsadded+31−0View file
@@ -0,0 +1,31 @@
1+// One shared AudioContext for the whole album, created on the first user gesture.
2+
3+export interface AudioEngine {
4+ ctx: AudioContext;
5+ /** Compositions connect here. */
6+ input: AudioNode;
7+}
8+
9+let engine: AudioEngine | null = null;
10+
11+export async function getAudio(): Promise<AudioEngine> {
12+ if (!engine) {
13+ const ctx = new AudioContext({ latencyHint: "playback" });
14+ const input = ctx.createGain();
15+ // gentle safety limiter on the master bus
16+ const limiter = ctx.createDynamicsCompressor();
17+ limiter.threshold.value = -6;
18+ limiter.knee.value = 6;
19+ limiter.ratio.value = 12;
20+ limiter.attack.value = 0.003;
21+ limiter.release.value = 0.25;
22+ input.connect(limiter).connect(ctx.destination);
23+ engine = { ctx, input };
24+ }
25+ if (engine.ctx.state !== "running") await engine.ctx.resume();
26+ return engine;
27+}
28+
29+export function dbToGain(db: number): number {
30+ return Math.pow(10, db / 20);
31+}
src/core/authorPanel.tsadded+173−0View file
@@ -0,0 +1,173 @@
1+// Author panel: controls generated from a composition's schema, plus copy/paste of the whole config.
2+import type { NumberSpec, ParamSpec, ParamValue, Params } from "./params.ts";
3+import { resolveParams, serializeParams } from "./params.ts";
4+
5+export interface AuthorPanelOptions {
6+ schema: ParamSpec[];
7+ get: () => Params;
8+ set: (p: Params) => void;
9+ defaults: () => Params;
10+ readouts: () => Record<string, string>;
11+ /** author-only start offset (s); not part of the config */
12+ startAt: { value: number };
13+}
14+
15+export interface AuthorPanel {
16+ el: HTMLElement;
17+ /** refresh all controls from the current params */
18+ sync(): void;
19+ updateReadouts(): void;
20+}
21+
22+const SLIDER_STEPS = 1000;
23+
24+function toSlider(s: NumberSpec, v: number): number {
25+ const u = s.log ? Math.log(v / s.min) / Math.log(s.max / s.min) : (v - s.min) / (s.max - s.min);
26+ return Math.round(Math.max(0, Math.min(1, u)) * SLIDER_STEPS);
27+}
28+
29+function fromSlider(s: NumberSpec, pos: number): number {
30+ const u = pos / SLIDER_STEPS;
31+ let v = s.log ? s.min * Math.pow(s.max / s.min, u) : s.min + u * (s.max - s.min);
32+ if (s.step) v = Math.round(v / s.step) * s.step;
33+ return Number(v.toPrecision(4));
34+}
35+
36+function fmt(v: number): string {
37+ return String(Number(v.toPrecision(4)));
38+}
39+
40+function el<K extends keyof HTMLElementTagNameMap>(tag: K, props: Record<string, unknown> = {}, ...kids: (Node | string)[]): HTMLElementTagNameMap[K] {
41+ const e = Object.assign(document.createElement(tag), props) as HTMLElementTagNameMap[K];
42+ e.append(...kids);
43+ return e;
44+}
45+
46+export function createAuthorPanel(o: AuthorPanelOptions): AuthorPanel {
47+ const root = el("aside", { className: "author" });
48+ const syncers: (() => void)[] = [];
49+
50+ const update = (key: string, v: ParamValue) => {
51+ o.set({ ...o.get(), [key]: v });
52+ };
53+
54+ // ── actions ──
55+ const status = el("span", { className: "status" });
56+ const flash = (msg: string) => {
57+ status.textContent = msg;
58+ window.setTimeout(() => {
59+ if (status.textContent === msg) status.textContent = "";
60+ }, 2000);
61+ };
62+ const copyBtn = el("button", { textContent: "copy config" });
63+ copyBtn.onclick = async () => {
64+ const text = serializeParams(o.schema, o.get());
65+ try {
66+ await navigator.clipboard.writeText(text);
67+ flash("copied");
68+ } catch {
69+ window.prompt("copy:", text);
70+ }
71+ };
72+ const pasteBtn = el("button", { textContent: "paste config" });
73+ pasteBtn.onclick = async () => {
74+ let text: string | null = null;
75+ try {
76+ text = await navigator.clipboard.readText();
77+ } catch {
78+ text = window.prompt("paste config JSON:");
79+ }
80+ if (!text) return;
81+ try {
82+ o.set(resolveParams(o.schema, JSON.parse(text)));
83+ sync();
84+ flash("pasted");
85+ } catch {
86+ flash("not valid JSON");
87+ }
88+ };
89+ const resetBtn = el("button", { textContent: "reset to defaults" });
90+ resetBtn.onclick = () => {
91+ if (!window.confirm("Discard your edits and return to the published defaults?")) return;
92+ o.set(o.defaults());
93+ sync();
94+ };
95+ root.append(el("div", { className: "actions" }, copyBtn, pasteBtn, resetBtn, status));
96+
97+ // ── author-only transport option ──
98+ const startInput = el("input", { type: "number", min: "0", step: "1", value: String(o.startAt.value) });
99+ startInput.oninput = () => {
100+ o.startAt.value = Math.max(0, Number(startInput.value) || 0);
101+ };
102+ root.append(el("label", { className: "row" }, el("span", { textContent: "start at (s)" }), startInput));
103+
104+ const readoutBox = el("dl", { className: "readouts" });
105+ root.append(readoutBox);
106+
107+ // ── params grouped ──
108+ const groups = new Map<string, HTMLElement>();
109+ for (const s of o.schema) {
110+ let fs = groups.get(s.group);
111+ if (!fs) {
112+ fs = el("fieldset", {}, el("legend", { textContent: s.group }));
113+ groups.set(s.group, fs);
114+ root.append(fs);
115+ }
116+ const label = el("span", { textContent: s.label, title: s.hint ?? "" });
117+ const row = el("label", { className: "row" }, label);
118+
119+ if (s.kind === "number") {
120+ const slider = el("input", { type: "range", min: "0", max: String(SLIDER_STEPS), step: "1" });
121+ const num = el("input", { type: "number", step: "any" });
122+ const unit = el("span", { className: "unit", textContent: s.unit ?? "" });
123+ slider.oninput = () => {
124+ const v = fromSlider(s, Number(slider.value));
125+ num.value = fmt(v);
126+ update(s.key, v);
127+ };
128+ num.onchange = () => {
129+ const v = Number(num.value);
130+ if (!Number.isFinite(v)) return;
131+ slider.value = String(toSlider(s, v));
132+ update(s.key, v);
133+ };
134+ syncers.push(() => {
135+ const v = o.get()[s.key] as number;
136+ slider.value = String(toSlider(s, v));
137+ num.value = fmt(v);
138+ });
139+ row.append(slider, num, unit);
140+ } else if (s.kind === "select") {
141+ const sel = el("select");
142+ for (const opt of s.options) sel.append(el("option", { value: opt, textContent: opt }));
143+ sel.onchange = () => update(s.key, sel.value);
144+ syncers.push(() => (sel.value = o.get()[s.key] as string));
145+ row.append(sel);
146+ } else if (s.kind === "text") {
147+ const ta = el("textarea", { rows: 3, spellcheck: false, placeholder: s.hint ?? "" });
148+ ta.onchange = () => update(s.key, ta.value);
149+ syncers.push(() => (ta.value = o.get()[s.key] as string));
150+ row.classList.add("text");
151+ row.append(ta);
152+ } else {
153+ const cb = el("input", { type: "checkbox" });
154+ cb.onchange = () => update(s.key, cb.checked);
155+ syncers.push(() => (cb.checked = o.get()[s.key] as boolean));
156+ row.append(cb);
157+ }
158+ fs.append(row);
159+ }
160+
161+ function sync() {
162+ for (const f of syncers) f();
163+ }
164+
165+ function updateReadouts() {
166+ const r = o.readouts();
167+ readoutBox.replaceChildren(...Object.entries(r).flatMap(([k, v]) => [el("dt", { textContent: k }), el("dd", { textContent: v })]));
168+ }
169+
170+ sync();
171+ updateReadouts();
172+ return { el: root, sync, updateReadouts };
173+}
src/core/composition.tsadded+32−0View file
@@ -0,0 +1,32 @@
1+import type { AudioEngine } from "./audio.ts";
2+import type { ParamSpec, Params } from "./params.ts";
3+
4+/** A running (or ready-to-run) performance of a composition, bound to a view element. */
5+export interface Piece {
6+ /** Start (or restart) from piece time `offset` seconds. Resolves once sound has begun. */
7+ start(audio: AudioEngine, offset: number): Promise<void>;
8+ stop(): void;
9+ /** Called every animation frame, playing or not. */
10+ draw(): void;
11+ readonly playing: boolean;
12+ /** Current piece time in seconds. */
13+ now(): number;
14+ /** Total length in seconds, including any tail. */
15+ length(): number;
16+ /** Diagnostic values shown in author mode. */
17+ readouts(): Record<string, string>;
18+ /** Called when the piece reaches its end on its own. */
19+ onEnded?: () => void;
20+ dispose(): void;
21+}
22+
23+export interface Composition {
24+ /** used in the URL, e.g. "01-poincare" */
25+ id: string;
26+ title: string;
27+ schema: ParamSpec[];
28+ /** The published settings: the contents of the composition's defaults.json */
29+ defaults: Partial<Params>;
30+ /** `params` is live: read it whenever needed so author edits take effect immediately. */
31+ create(view: HTMLElement, params: () => Params): Piece;
32+}
src/core/params.tsadded+71−0View file
@@ -0,0 +1,71 @@
1+// Parameter schema shared by all compositions. The author panel is generated from it,
2+// and a composition's config is just a flat { key: value } object.
3+
4+export type ParamValue = number | string | boolean;
5+export type Params = Record<string, ParamValue>;
6+
7+interface Base {
8+ key: string;
9+ label: string;
10+ group: string;
11+ hint?: string;
12+}
13+
14+export interface NumberSpec extends Base {
15+ kind: "number";
16+ default: number;
17+ min: number;
18+ max: number;
19+ step?: number;
20+ /** slider moves logarithmically (min must be > 0) */
21+ log?: boolean;
22+ unit?: string;
23+}
24+
25+export interface SelectSpec extends Base {
26+ kind: "select";
27+ default: string;
28+ options: string[];
29+}
30+
31+export interface BoolSpec extends Base {
32+ kind: "bool";
33+ default: boolean;
34+}
35+
36+export interface TextSpec extends Base {
37+ kind: "text";
38+ default: string;
39+}
40+
41+export type ParamSpec = NumberSpec | SelectSpec | BoolSpec | TextSpec;
42+
43+export function schemaDefaults(schema: ParamSpec[]): Params {
44+ const out: Params = {};
45+ for (const s of schema) out[s.key] = s.default;
46+ return out;
47+}
48+
49+/** Merge layers onto the schema, keeping only known keys with the right type. */
50+export function resolveParams(schema: ParamSpec[], ...layers: (Partial<Params> | null | undefined)[]): Params {
51+ const out = schemaDefaults(schema);
52+ for (const layer of layers) {
53+ if (!layer) continue;
54+ for (const s of schema) {
55+ const v = layer[s.key];
56+ if (v === undefined) continue;
57+ if (s.kind === "number" && typeof v === "number" && Number.isFinite(v)) out[s.key] = v;
58+ else if (s.kind === "select" && typeof v === "string" && s.options.includes(v)) out[s.key] = v;
59+ else if (s.kind === "bool" && typeof v === "boolean") out[s.key] = v;
60+ else if (s.kind === "text" && typeof v === "string") out[s.key] = v;
61+ }
62+ }
63+ return out;
64+}
65+
66+/** JSON in schema order, ready to paste over a composition's defaults.json. */
67+export function serializeParams(schema: ParamSpec[], params: Params): string {
68+ const ordered: Params = {};
69+ for (const s of schema) ordered[s.key] = params[s.key];
70+ return JSON.stringify(ordered, null, 2) + "\n";
71+}
src/core/rng.tsadded+15−0View file
@@ -0,0 +1,15 @@
1+/** mulberry32: small seeded PRNG so a good variation can be reproduced from its seed. */
2+export function mulberry32(seed: number): () => number {
3+ let a = seed >>> 0;
4+ return () => {
5+ a = (a + 0x6d2b79f5) >>> 0;
6+ let t = a;
7+ t = Math.imul(t ^ (t >>> 15), t | 1);
8+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
9+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
10+ };
11+}
12+
13+export function randomSeed(): number {
14+ return 1 + Math.floor(Math.random() * 999999);
15+}
src/instruments/fade.tsadded+6−0View file
@@ -0,0 +1,6 @@
1+/** Gain curve for a musical fade-out: cos², so -6 dB at the midpoint and the drop concentrated at the end. */
2+export function fadeCurve(from: number, n = 128): Float32Array {
3+ const c = new Float32Array(n);
4+ for (let i = 0; i < n; i++) c[i] = from * Math.cos((Math.PI / 2) * (i / (n - 1))) ** 2;
5+ return c;
6+}
src/instruments/index.tsadded+13−0View file
@@ -0,0 +1,13 @@
1+import { modalDrones, modalInstruments } from "./modal.ts";
2+import { placeholderHum, placeholderTone } from "./placeholders.ts";
3+import type { DroneInstrumentFactory, NoteInstrumentFactory } from "./types.ts";
4+
5+export const NOTE_INSTRUMENTS: Record<string, NoteInstrumentFactory> = {
6+ "placeholder tone": placeholderTone,
7+ ...modalInstruments(),
8+};
9+
10+export const DRONE_INSTRUMENTS: Record<string, DroneInstrumentFactory> = {
11+ "placeholder hum": placeholderHum,
12+ ...modalDrones(),
13+};
src/instruments/modal.tsadded+262−0View file
@@ -0,0 +1,262 @@
1+// Instruments from the sibling modal-synth project (coupled nonlinear modal oscillators),
2+// imported live via the @modal-synth alias. Each instrument instance is one AudioWorklet synth
3+// (up to 16 voices) followed by modal-synth's own effects (saturation, delay, reverb).
4+
5+import { FX } from "@modal-synth/audio/fx.ts";
6+import workletUrl from "@modal-synth/audio/worklet.ts?worker&url";
7+import { DEFAULTS, PARAM_BY_ID, type Params } from "@modal-synth/engine/params.ts";
8+import type { Msg } from "@modal-synth/engine/synth.ts";
9+import { PRESETS } from "@modal-synth/presets.ts";
10+import { fadeCurve } from "./fade.ts";
11+import type { DroneInstrumentFactory, NoteHandle, NoteInstrument, NoteInstrumentFactory } from "./types.ts";
12+
13+const loaded = new WeakMap<BaseAudioContext, Promise<void>>();
14+function loadWorklet(ctx: AudioContext): Promise<void> {
15+ let p = loaded.get(ctx);
16+ if (!p) {
17+ p = ctx.audioWorklet.addModule(workletUrl);
18+ loaded.set(ctx, p);
19+ }
20+ return p;
21+}
22+
23+/** Parse a pasted preset (the JSON from modal-synth's Copy button). */
24+export function parseModalPreset(text: string | undefined): Params | null {
25+ if (!text || !text.trim()) return null;
26+ try {
27+ const v = JSON.parse(text);
28+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Params) : null;
29+ } catch {
30+ return null;
31+ }
32+}
33+
34+const NOTE_OFF_LEAD = 0.2; // post noteOffs to the worklet this far ahead of their time
35+const FLUSH_MS = 25;
36+
37+export function makeModalFactory(preset: Params | null): NoteInstrumentFactory {
38+ return (ctx, out, opts) => {
39+ const sound: Params = { ...DEFAULTS, ...(preset ?? parseModalPreset(opts.custom) ?? {}) };
40+
41+ // synth → fade (used by the final-note hold) → modal-synth FX → our output
42+ const fade = ctx.createGain();
43+ const fx = new FX(ctx, out);
44+ fade.connect(fx.input);
45+ fx.set(sound);
46+
47+ let node: AudioWorkletNode | null = null;
48+ const early: Msg[] = [];
49+ const post = (m: Msg) => (node ? node.port.postMessage(m) : early.push(m));
50+
51+ const ready = loadWorklet(ctx).then(() => {
52+ node = new AudioWorkletNode(ctx, "modal-synth", { numberOfInputs: 0, outputChannelCount: [2] });
53+ node.port.onmessage = () => {}; // snapshots for modal-synth's views; not needed here
54+ node.port.postMessage({ type: "params", params: sound } satisfies Msg);
55+ for (const m of early.splice(0)) node.port.postMessage(m);
56+ node.connect(fade);
57+ });
58+
59+ // noteOffs are held here until shortly before they're due, so the final note can be extended.
60+ // Notes are identified by pitch in the synth; a noteOff is skipped if the same pitch was
61+ // re-struck after its noteOn (the newer note has its own noteOff).
62+ interface Off { note: number; on: number; time: number }
63+ let offs: Off[] = [];
64+ const lastOn = new Map<number, number>();
65+ const flush = () => {
66+ const horizon = ctx.currentTime + NOTE_OFF_LEAD;
67+ const keep: Off[] = [];
68+ for (const o of offs) {
69+ if (o.time > horizon) keep.push(o);
70+ else if ((lastOn.get(o.note) ?? -Infinity) <= o.on) post({ type: "noteOff", note: o.note, time: o.time });
71+ }
72+ offs = keep;
73+ };
74+ const timer = window.setInterval(flush, FLUSH_MS);
75+
76+ const inst: NoteInstrument = {
77+ ready,
78+ play({ when, freq, velocity, duration }) {
79+ if (velocity <= 0) return null;
80+ const note = 69 + 12 * Math.log2(freq / 440);
81+ post({ type: "noteOn", note, vel: Math.max(0.01, Math.min(1, velocity)), time: when });
82+ lastOn.set(note, when);
83+ const off: Off = { note, on: when, time: when + duration };
84+ offs.push(off);
85+ const handle: NoteHandle = {
86+ hold(from, holdLen, fadeLen) {
87+ const t = Math.max(from, ctx.currentTime);
88+ const ring = holdLen + fadeLen;
89+ // keep the damper off through the whole hold and fade (if still queued, the release moves later)
90+ off.time = t + ring;
91+ // a plucked or struck body decays by itself: lengthen its decay so it really rings through
92+ // the hold. Only the final note is sounding by then, so the instrument-wide change is safe.
93+ // Both the base decay (t60) and the frequency-dependent loss (hfDamp) are slowed by the same
94+ // factor, so the note keeps its tone color while it rings.
95+ const t60 = Math.min(60, Math.max(sound.t60 as number, 6 * ring));
96+ const slow = t60 / (sound.t60 as number);
97+ const ringing: Params = { ...sound, t60, hfDamp: (sound.hfDamp as number) / slow };
98+ window.setTimeout(() => post({ type: "params", params: ringing }), Math.max(0, (t - ctx.currentTime) * 1000));
99+ fade.gain.setValueCurveAtTime(fadeCurve(1), t + Math.max(holdLen, 0.005), fadeLen);
100+ },
101+ };
102+ return handle;
103+ },
104+ dispose() {
105+ window.clearInterval(timer);
106+ post({ type: "panic" });
107+ window.setTimeout(() => {
108+ node?.disconnect();
109+ node?.port.close();
110+ fade.disconnect();
111+ }, 1000);
112+ },
113+ };
114+ return inst;
115+ };
116+}
117+
118+/** Menu name → factory, for every built-in modal-synth preset plus "modal: custom". */
119+export function modalInstruments(): Record<string, NoteInstrumentFactory> {
120+ const out: Record<string, NoteInstrumentFactory> = {};
121+ for (const p of PRESETS) out[`modal: ${p.name}`] = makeModalFactory(p.p);
122+ out["modal: custom"] = makeModalFactory(null);
123+ return out;
124+}
125+
126+// ── drones: one held note of a sustained preset, with color mapped onto synth settings ──
127+
128+/** Settings the synth reads every block, so they can follow the energy while a note is held. */
129+export const LIVE_TARGETS = [
130+ "bowForce", "bowSpeed", "bowNoise", "exPos", "reedPressure", "reedGain", "breath",
131+ "selfGain", "selfSat", "noiseLevel", "noiseColor", "tension", "cascade", "curvature",
132+ "fbGain", "fbFreq", "fbQ", "fbSat", "hfDamp", "t60", "pickup", "tilt", "vibDepth",
133+];
134+
135+/** 0..1 → a modal-synth setting's value, following that setting's own slider scale. */
136+export function targetValue(id: string, u: number): number {
137+ const d = PARAM_BY_ID[id];
138+ if (!d || d.kind !== "num") return NaN;
139+ const x = Math.max(0, Math.min(1, u));
140+ if (d.scale === "log") return d.min * Math.pow(d.max / d.min, x);
141+ if (d.scale === "pow2") return d.min + (d.max - d.min) * x * x;
142+ return d.min + (d.max - d.min) * x;
143+}
144+
145+const SUSTAINED_EXCITERS = ["bow", "reed", "selfosc", "noise"];
146+const DRONE_UPDATE_MS = 50; // at most this often, a "params" message to the worklet
147+const NORM_REF = 0.3; // with normalize on, level 1 ≈ this RMS (about the placeholder hum's)
148+const NORM_TAU = 1.5; // seconds: how slowly the loudness compensation follows
149+const NORM_RANGE = 20; // compensation limited to ×1/20 … ×20
150+
151+export function makeModalDroneFactory(preset: Params | null): DroneInstrumentFactory {
152+ return (ctx, out, opts) => {
153+ const base: Params = { ...DEFAULTS, ...(preset ?? parseModalPreset(opts.custom) ?? {}), voices: 1 };
154+ const gain = ctx.createGain();
155+ gain.gain.value = 0;
156+ const fx = new FX(ctx, out);
157+ gain.connect(fx.input);
158+ fx.set(base);
159+ // loudness meter on the raw synth output, for normalization
160+ const meter = ctx.createAnalyser();
161+ meter.fftSize = 2048;
162+ const buf = new Float32Array(meter.fftSize);
163+ let msq = NORM_REF * NORM_REF; // smoothed mean square
164+ let lastMeter = 0;
165+ let comp = 1;
166+
167+ let node: AudioWorkletNode | null = null;
168+ const early: Msg[] = [];
169+ const post = (m: Msg) => (node ? node.port.postMessage(m) : early.push(m));
170+ const ready = loadWorklet(ctx).then(() => {
171+ node = new AudioWorkletNode(ctx, "modal-synth", { numberOfInputs: 0, outputChannelCount: [2] });
172+ node.port.onmessage = () => {};
173+ node.port.postMessage({ type: "params", params: base } satisfies Msg);
174+ for (const m of early.splice(0)) node.port.postMessage(m);
175+ node.connect(gain);
176+ node.connect(meter);
177+ });
178+
179+ let note: number | null = null;
180+ let sent: Params = base;
181+ let lastPost = 0;
182+ let desc = "";
183+ const midi = (f: number) => 69 + 12 * Math.log2(f / 440);
184+
185+ return {
186+ ready,
187+ start(when, freq) {
188+ note = midi(freq);
189+ post({ type: "noteOn", note, vel: 1, time: when });
190+ },
191+ stop(when, release) {
192+ const t = Math.max(ctx.currentTime, when - release);
193+ gain.gain.cancelScheduledValues(t);
194+ gain.gain.setTargetAtTime(0, t, release / 4);
195+ if (note !== null) post({ type: "noteOff", note, time: t });
196+ note = null;
197+ },
198+ set(when, { level, color, freq, timbre, normalize }) {
199+ // loudness normalization: follow the measured level slowly, compensate toward NORM_REF
200+ const now = performance.now() / 1000;
201+ const dt = lastMeter ? Math.min(0.5, now - lastMeter) : 0;
202+ lastMeter = now;
203+ if (normalize && node) {
204+ meter.getFloatTimeDomainData(buf);
205+ let s = 0;
206+ for (const x of buf) s += x * x;
207+ s /= buf.length;
208+ if (s > 1e-10) msq += (s - msq) * (1 - Math.exp(-dt / NORM_TAU));
209+ comp = Math.max(1 / NORM_RANGE, Math.min(NORM_RANGE, NORM_REF / Math.sqrt(msq)));
210+ } else comp = 1;
211+ gain.gain.setTargetAtTime(level * comp, when, 0.08);
212+ // retune by restarting the note if the pitch setting moved
213+ const m = midi(freq);
214+ if (note !== null && Math.abs(m - note) > 0.01) {
215+ post({ type: "noteOff", note, time: when });
216+ note = m;
217+ post({ type: "noteOn", note, vel: 1, time: when });
218+ }
219+ // color → mapped settings, throttled
220+ const wall = performance.now();
221+ if (!timbre?.length || wall - lastPost < DRONE_UPDATE_MS) return;
222+ const next: Params = { ...base };
223+ const parts: string[] = [];
224+ let changed = false;
225+ for (const tm of timbre) {
226+ if (!LIVE_TARGETS.includes(tm.target)) continue;
227+ const v = targetValue(tm.target, tm.from + (tm.to - tm.from) * color);
228+ if (!Number.isFinite(v)) continue;
229+ next[tm.target] = v;
230+ parts.push(`${tm.target} ${Number(v.toPrecision(3))}`);
231+ const d = PARAM_BY_ID[tm.target] as { min: number; max: number };
232+ if (Math.abs(v - (sent[tm.target] as number)) > 0.002 * (d.max - d.min)) changed = true;
233+ }
234+ desc = parts.join(", ");
235+ if (!changed) return;
236+ sent = next;
237+ lastPost = wall;
238+ post({ type: "params", params: next });
239+ },
240+ describe: () => (comp !== 1 ? `${desc}${desc ? ", " : ""}gain ${(20 * Math.log10(comp)).toFixed(1)} dB` : desc),
241+ dispose() {
242+ post({ type: "panic" });
243+ window.setTimeout(() => {
244+ node?.disconnect();
245+ node?.port.close();
246+ gain.disconnect();
247+ }, 1000);
248+ },
249+ };
250+ };
251+}
252+
253+/** Sustained presets (bowed, blown, self-oscillating, fed back) as "modal: <name>", plus "modal: custom". */
254+export function modalDrones(): Record<string, DroneInstrumentFactory> {
255+ const out: Record<string, DroneInstrumentFactory> = {};
256+ for (const p of PRESETS) {
257+ const q = { ...DEFAULTS, ...p.p };
258+ if (SUSTAINED_EXCITERS.includes(q.exciter as string) || (q.fbGain as number) > 0) out[`modal: ${p.name}`] = makeModalDroneFactory(p.p);
259+ }
260+ out["modal: custom"] = makeModalDroneFactory(null);
261+ return out;
262+}
src/instruments/placeholders.tsadded+112−0View file
@@ -0,0 +1,112 @@
1+// Placeholder instruments: deliberately plain, to be replaced later.
2+import { fadeCurve } from "./fade.ts";
3+import type { DroneInstrument, NoteEvent, NoteHandle, NoteInstrument } from "./types.ts";
4+
5+/** Sine + soft octave triangle with a percussive exponential decay. */
6+export function placeholderTone(ctx: AudioContext, out: AudioNode): NoteInstrument {
7+ return {
8+ play({ when, freq, velocity, pan, duration }: NoteEvent): NoteHandle | null {
9+ if (velocity <= 0) return null;
10+ const t0 = Math.max(when, ctx.currentTime);
11+ const end = t0 + duration;
12+ const peak = 0.3 * velocity;
13+ const ta = t0 + 0.004;
14+ const env = ctx.createGain();
15+ env.gain.setValueAtTime(0, t0);
16+ env.gain.linearRampToValueAtTime(peak, ta);
17+ env.gain.exponentialRampToValueAtTime(0.0001, end);
18+ const panner = ctx.createStereoPanner();
19+ panner.pan.value = Math.max(-1, Math.min(1, pan));
20+ env.connect(panner).connect(out);
21+
22+ const a = ctx.createOscillator();
23+ a.frequency.value = freq;
24+ a.connect(env);
25+ const b = ctx.createOscillator();
26+ b.type = "triangle";
27+ b.frequency.value = freq * 2;
28+ const bg = ctx.createGain();
29+ bg.gain.value = 0.08 + 0.15 * velocity; // a touch brighter when louder
30+ b.connect(bg).connect(env);
31+
32+ for (const o of [a, b]) {
33+ o.start(t0);
34+ o.stop(end + 0.05);
35+ }
36+ b.onended = () => panner.disconnect();
37+
38+ return {
39+ hold(from, holdLen, fadeLen) {
40+ const t = Math.max(from, ta, ctx.currentTime);
41+ if (t >= end) return;
42+ // level of the exponential decay at t
43+ const v = peak * Math.pow(0.0001 / peak, (t - ta) / (end - ta));
44+ const g = env.gain;
45+ if (typeof g.cancelAndHoldAtTime === "function") g.cancelAndHoldAtTime(t);
46+ else g.cancelScheduledValues(t);
47+ g.setValueAtTime(v, t);
48+ g.setValueCurveAtTime(fadeCurve(v), t + Math.max(holdLen, 0.005), fadeLen);
49+ const stopAt = t + holdLen + fadeLen + 0.05;
50+ a.stop(stopAt);
51+ b.stop(stopAt);
52+ },
53+ };
54+ },
55+ dispose() {},
56+ };
57+}
58+
59+/**
60+ * Hum: sub sine + two detuned saws through a low-pass. `color` (0..1) opens the
61+ * filter and adds resonance, so the timbre brightens with energy at fixed pitch.
62+ */
63+export function placeholderHum(ctx: AudioContext, out: AudioNode): DroneInstrument {
64+ const gain = ctx.createGain();
65+ gain.gain.value = 0;
66+ const filter = ctx.createBiquadFilter();
67+ filter.type = "lowpass";
68+ filter.frequency.value = 120;
69+ filter.Q.value = 0.7;
70+ filter.connect(gain).connect(out);
71+
72+ const sub = ctx.createOscillator();
73+ const subGain = ctx.createGain();
74+ subGain.gain.value = 0.5;
75+ sub.connect(subGain).connect(gain); // sub bypasses the filter: the stable core of the hum
76+
77+ const saws = [-6, 6].map((cents) => {
78+ const o = ctx.createOscillator();
79+ o.type = "sawtooth";
80+ o.detune.value = cents;
81+ const g = ctx.createGain();
82+ g.gain.value = 0.25;
83+ o.connect(g).connect(filter);
84+ return o;
85+ });
86+ const oscs = [sub, ...saws];
87+
88+ return {
89+ start(when, freq) {
90+ sub.frequency.value = freq;
91+ for (const o of saws) o.frequency.value = freq * 2;
92+ for (const o of oscs) o.start(when);
93+ },
94+ stop(when, release) {
95+ gain.gain.cancelScheduledValues(when - release);
96+ gain.gain.setTargetAtTime(0, when - release, release / 4);
97+ for (const o of oscs) o.stop(when + 0.1);
98+ },
99+ set(when, { level, color, freq }) {
100+ const tc = 0.08;
101+ gain.gain.setTargetAtTime(level, when, tc);
102+ sub.frequency.setTargetAtTime(freq, when, tc);
103+ for (const o of saws) o.frequency.setTargetAtTime(freq * 2, when, tc);
104+ const c = Math.max(0, Math.min(1, color));
105+ filter.frequency.setTargetAtTime(freq * 2 * Math.pow(2, 6 * c), when, tc);
106+ filter.Q.setTargetAtTime(0.7 + 5 * c * c, when, tc);
107+ },
108+ dispose() {
109+ gain.disconnect();
110+ },
111+ };
112+}
src/instruments/types.tsadded+71−0View file
@@ -0,0 +1,71 @@
1+// Instrument interfaces. Real instruments drop in by implementing these and
2+// registering in ./index.ts; compositions pick them by name.
3+
4+export interface NoteEvent {
5+ /** AudioContext time */
6+ when: number;
7+ freq: number;
8+ /** dynamics, 0..1 (overall level is set by the composition's mixer, not here) */
9+ velocity: number;
10+ /** -1..1 */
11+ pan: number;
12+ /** seconds; how long the note rings (instrument may interpret freely) */
13+ duration: number;
14+}
15+
16+/** Control over a note after it has been scheduled. */
17+export interface NoteHandle {
18+ /**
19+ * Stop the note's natural decay at `from` (AudioContext time), sustain its level for
20+ * `holdLen` seconds, then fade out over `fadeLen` seconds. Used for the final note of a piece.
21+ */
22+ hold(from: number, holdLen: number, fadeLen: number): void;
23+}
24+
25+export interface NoteInstrument {
26+ /** resolves when the instrument can play (e.g. an AudioWorklet has loaded) */
27+ ready?: Promise<void>;
28+ play(ev: NoteEvent): NoteHandle | null;
29+ dispose(): void;
30+}
31+
32+/** Map the drone's color (0..1) onto one instrument setting. from/to are 0..1 of that setting's range. */
33+export interface TimbreMap {
34+ target: string;
35+ from: number;
36+ to: number;
37+}
38+
39+export interface DroneInstrument {
40+ /** resolves when the instrument can play */
41+ ready?: Promise<void>;
42+ start(when: number, freq: number): void;
43+ /** Stop with a release ending at `when`. */
44+ stop(when: number, release: number): void;
45+ /**
46+ * Continuous controls, called often.
47+ * level: linear gain 0..1; color: 0..1 timbre control (driven by energy).
48+ */
49+ set(
50+ when: number,
51+ controls: {
52+ level: number;
53+ color: number;
54+ freq: number;
55+ timbre?: TimbreMap[];
56+ /** hold the output loudness steady while the timbre changes (instruments that support it) */
57+ normalize?: boolean;
58+ },
59+ ): void;
60+ /** current values of mapped settings, for the author readouts */
61+ describe?(): string;
62+ dispose(): void;
63+}
64+
65+export interface InstrumentOptions {
66+ /** instrument-specific settings, e.g. a pasted modal-synth preset (JSON) */
67+ custom?: string;
68+}
69+
70+export type NoteInstrumentFactory = (ctx: AudioContext, out: AudioNode, opts: InstrumentOptions) => NoteInstrument;
71+export type DroneInstrumentFactory = (ctx: AudioContext, out: AudioNode, opts: InstrumentOptions) => DroneInstrument;
src/main.tsadded+145−0View file
@@ -0,0 +1,145 @@
1+// Album shell: hash routes
2+// #/ track list
3+// #/<id> a composition (visitor: published defaults only)
4+// #/<id>/edit the same composition with the author panel
5+import "./style.css";
6+import { getAudio } from "./core/audio.ts";
7+import { createAuthorPanel } from "./core/authorPanel.ts";
8+import type { Composition, Piece } from "./core/composition.ts";
9+import { resolveParams } from "./core/params.ts";
10+import type { Params } from "./core/params.ts";
11+import { ALBUM_TITLE, COMPOSITIONS } from "./compositions/index.ts";
12+
13+const app = document.getElementById("app")!;
14+let teardown: (() => void) | null = null;
15+
16+function h<K extends keyof HTMLElementTagNameMap>(tag: K, props: Record<string, unknown> = {}, ...kids: (Node | string)[]): HTMLElementTagNameMap[K] {
17+ const e = Object.assign(document.createElement(tag), props) as HTMLElementTagNameMap[K];
18+ e.append(...kids);
19+ return e;
20+}
21+
22+function route() {
23+ teardown?.();
24+ teardown = null;
25+ app.replaceChildren();
26+ const parts = location.hash.replace(/^#\/?/, "").split("/").filter(Boolean);
27+ const comp = COMPOSITIONS.find((c) => c.id === parts[0]);
28+ if (!comp) return showAlbum();
29+ teardown = showComposition(comp, parts[1] === "edit");
30+}
31+
32+function showAlbum() {
33+ document.title = ALBUM_TITLE;
34+ const list = h("ol", { className: "tracks" });
35+ for (const c of COMPOSITIONS) list.append(h("li", {}, h("a", { href: `#/${c.id}`, textContent: c.title })));
36+ app.append(h("main", { className: "album" }, h("h1", { textContent: ALBUM_TITLE }), list));
37+}
38+
39+const storageKey = (c: Composition) => `double-pendulum:author:${c.id}`;
40+
41+function loadEdits(c: Composition): Partial<Params> | null {
42+ try {
43+ const s = localStorage.getItem(storageKey(c));
44+ return s ? JSON.parse(s) : null;
45+ } catch {
46+ return null;
47+ }
48+}
49+
50+function saveEdits(c: Composition, p: Params) {
51+ try {
52+ localStorage.setItem(storageKey(c), JSON.stringify(p));
53+ } catch {
54+ /* storage unavailable: edits last for this page view only */
55+ }
56+}
57+
58+function showComposition(comp: Composition, author: boolean): () => void {
59+ const index = COMPOSITIONS.indexOf(comp) + 1;
60+ document.title = `${comp.title} · ${ALBUM_TITLE}`;
61+ const published = () => resolveParams(comp.schema, comp.defaults);
62+ let params = author ? resolveParams(comp.schema, comp.defaults, loadEdits(comp)) : published();
63+
64+ const view = h("div", { className: "view" });
65+ const playBtn = h("button", { className: "play", textContent: "play" });
66+ const bar = h("div", { className: "bar" });
67+ const progress = h("div", { className: "progress" }, bar);
68+ const editLink = h("a", { className: "edit", href: author ? `#/${comp.id}` : `#/${comp.id}/edit`, textContent: author ? "done" : "edit" });
69+ const header = h(
70+ "header",
71+ {},
72+ h("a", { href: "#/", textContent: ALBUM_TITLE }),
73+ h("span", { className: "sep", textContent: " / " }),
74+ h("span", { textContent: `${index}. ${comp.title}` }),
75+ );
76+ const stage = h("main", { className: "stage" }, header, view, h("div", { className: "transport" }, playBtn, progress, editLink));
77+ const page = h("div", { className: author ? "page with-author" : "page" }, stage);
78+ app.append(page);
79+
80+ const piece: Piece = comp.create(view, () => params);
81+ const startAt = { value: 0 };
82+
83+ const play = async (offset: number) => {
84+ const audio = await getAudio();
85+ await piece.start(audio, offset);
86+ };
87+ playBtn.onclick = () => (piece.playing ? piece.stop() : play(author ? startAt.value : 0));
88+ if (author) {
89+ // author can click the progress line to jump
90+ progress.classList.add("seekable");
91+ progress.onclick = (ev) => {
92+ const r = progress.getBoundingClientRect();
93+ const t = Math.max(0, ((ev.clientX - r.left) / r.width) * piece.length());
94+ void play(t);
95+ };
96+ }
97+
98+ let panel: ReturnType<typeof createAuthorPanel> | null = null;
99+ if (author) {
100+ panel = createAuthorPanel({
101+ schema: comp.schema,
102+ get: () => params,
103+ set: (p) => {
104+ params = p;
105+ saveEdits(comp, p);
106+ },
107+ defaults: published,
108+ readouts: () => piece.readouts(),
109+ startAt,
110+ });
111+ page.append(panel.el);
112+ }
113+
114+ const onKey = (e: KeyboardEvent) => {
115+ const tag = (e.target as HTMLElement).tagName;
116+ if (e.code === "Space" && tag !== "INPUT" && tag !== "SELECT" && tag !== "BUTTON") {
117+ e.preventDefault();
118+ playBtn.click();
119+ }
120+ };
121+ window.addEventListener("keydown", onKey);
122+
123+ let raf = 0;
124+ let lastReadout = 0;
125+ const frame = (ts: number) => {
126+ piece.draw();
127+ playBtn.textContent = piece.playing ? "stop" : "play";
128+ bar.style.width = `${Math.min(100, (100 * piece.now()) / piece.length())}%`;
129+ if (panel && ts - lastReadout > 200) {
130+ panel.updateReadouts();
131+ lastReadout = ts;
132+ }
133+ raf = requestAnimationFrame(frame);
134+ };
135+ raf = requestAnimationFrame(frame);
136+
137+ return () => {
138+ cancelAnimationFrame(raf);
139+ window.removeEventListener("keydown", onKey);
140+ piece.dispose();
141+ };
142+}
143+
144+window.addEventListener("hashchange", route);
145+route();
src/music/scales.tsadded+45−0View file
@@ -0,0 +1,45 @@
1+// Scales as semitone offsets within an octave. "continuous" means no quantization.
2+
3+export const SCALES: Record<string, number[] | null> = {
4+ continuous: null,
5+ chromatic: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
6+ major: [0, 2, 4, 5, 7, 9, 11],
7+ "natural minor": [0, 2, 3, 5, 7, 8, 10],
8+ dorian: [0, 2, 3, 5, 7, 9, 10],
9+ lydian: [0, 2, 4, 6, 7, 9, 11],
10+ "pentatonic major": [0, 2, 4, 7, 9],
11+ "pentatonic minor": [0, 3, 5, 7, 10],
12+ "whole tone": [0, 2, 4, 6, 8, 10],
13+ "harmonic series": null, // handled specially: partials of the root
14+};
15+
16+export const SCALE_NAMES = Object.keys(SCALES);
17+export const NOTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
18+
19+export function midiToFreq(m: number): number {
20+ return 440 * Math.pow(2, (m - 69) / 12);
21+}
22+
23+/** Snap a (fractional) MIDI pitch to the nearest pitch of the scale. */
24+export function quantize(midi: number, scale: string, root: number): number {
25+ if (scale === "harmonic series") {
26+ // partials of the root an octave or more below the pitch range
27+ const f0 = midiToFreq(root + 12 * Math.floor((24 - root) / 12)); // root in octave 1 (≈ 32–62 Hz)
28+ const n = Math.max(1, Math.round(midiToFreq(midi) / f0));
29+ return 69 + 12 * Math.log2((n * f0) / 440);
30+ }
31+ const steps = SCALES[scale];
32+ if (!steps) return midi;
33+ const rel = midi - root;
34+ const oct = Math.floor(rel / 12);
35+ const within = rel - 12 * oct;
36+ let best = steps[0], bestD = Infinity;
37+ for (const s of [...steps, 12]) {
38+ const d = Math.abs(within - s);
39+ if (d < bestD) {
40+ bestD = d;
41+ best = s;
42+ }
43+ }
44+ return root + 12 * oct + best;
45+}
src/physics/doublePendulum.tsadded+201−0View file
@@ -0,0 +1,201 @@
1+// Frictionless double pendulum in canonical (Hamiltonian) coordinates.
2+// State y = [θ1, θ2, p1, p2]; angles measured from straight down.
3+//
4+// Energy is steered toward a target with a generalized force Q = λ·p.
5+// Because p = M·ω, that gives dE/dt = λ·pᵀω = 2λT, so choosing
6+// λ = (E* − E) / (τ (2T + ε))
7+// makes E relax toward E* with time constant ≈ τ while the motion stays smooth.
8+
9+export interface PendulumConfig {
10+ m1: number;
11+ m2: number;
12+ l1: number;
13+ l2: number;
14+ g: number;
15+}
16+
17+export interface Derived {
18+ w1: number;
19+ w2: number;
20+ T: number;
21+ V: number;
22+}
23+
24+export class DoublePendulum {
25+ cfg: PendulumConfig;
26+ y = new Float64Array(4);
27+ t = 0;
28+ /** Target energy (absolute units) and relaxation time used by the controller. */
29+ eTarget = 0;
30+ tau = 2;
31+ /** When false the energy controller is off and energy is conserved. */
32+ controlled = true;
33+
34+ private k1 = new Float64Array(4);
35+ private k2 = new Float64Array(4);
36+ private k3 = new Float64Array(4);
37+ private k4 = new Float64Array(4);
38+ private tmp = new Float64Array(4);
39+
40+ constructor(cfg: PendulumConfig) {
41+ this.cfg = { ...cfg };
42+ }
43+
44+ /** Potential energy of both arms straight up (with V = 0 hanging down). Used as the energy unit. */
45+ get vTop(): number {
46+ const { m1, m2, l1, l2, g } = this.cfg;
47+ return 2 * (m1 + m2) * g * l1 + 2 * m2 * g * l2;
48+ }
49+
50+ /** Natural momentum scale for p2 (so plots and mappings don't depend on masses/lengths). */
51+ get p2Scale(): number {
52+ const { m2, l2 } = this.cfg;
53+ return Math.sqrt(m2 * l2 * l2 * this.vTop);
54+ }
55+
56+ derived(y: ArrayLike<number> = this.y): Derived {
57+ const { m1, m2, l1, l2, g } = this.cfg;
58+ const [th1, th2, p1, p2] = [y[0], y[1], y[2], y[3]];
59+ const d = th1 - th2;
60+ const cd = Math.cos(d);
61+ const sd = Math.sin(d);
62+ const den = m1 + m2 * sd * sd;
63+ const w1 = (l2 * p1 - l1 * p2 * cd) / (l1 * l1 * l2 * den);
64+ const w2 = (l1 * (m1 + m2) * p2 - l2 * m2 * p1 * cd) / (l1 * l2 * l2 * m2 * den);
65+ const T = 0.5 * (p1 * w1 + p2 * w2);
66+ const V = (m1 + m2) * g * l1 * (1 - Math.cos(th1)) + m2 * g * l2 * (1 - Math.cos(th2));
67+ return { w1, w2, T, V };
68+ }
69+
70+ energy(y: ArrayLike<number> = this.y): number {
71+ const d = this.derived(y);
72+ return d.T + d.V;
73+ }
74+
75+ /** Energy in units of vTop. */
76+ energyNorm(): number {
77+ return this.energy() / this.vTop;
78+ }
79+
80+ private deriv(y: Float64Array, out: Float64Array) {
81+ const { m1, m2, l1, l2, g } = this.cfg;
82+ const th1 = y[0], th2 = y[1], p1 = y[2], p2 = y[3];
83+ const d = th1 - th2;
84+ const cd = Math.cos(d);
85+ const sd = Math.sin(d);
86+ const den = m1 + m2 * sd * sd;
87+ const w1 = (l2 * p1 - l1 * p2 * cd) / (l1 * l1 * l2 * den);
88+ const w2 = (l1 * (m1 + m2) * p2 - l2 * m2 * p1 * cd) / (l1 * l2 * l2 * m2 * den);
89+ const C1 = (p1 * p2 * sd) / (l1 * l2 * den);
90+ const C2 =
91+ ((l2 * l2 * m2 * p1 * p1 + l1 * l1 * (m1 + m2) * p2 * p2 - 2 * l1 * l2 * m2 * p1 * p2 * cd) *
92+ Math.sin(2 * d)) /
93+ (2 * l1 * l1 * l2 * l2 * den * den);
94+
95+ // energy controller
96+ const T = 0.5 * (p1 * w1 + p2 * w2);
97+ const V = (m1 + m2) * g * l1 * (1 - Math.cos(th1)) + m2 * g * l2 * (1 - Math.cos(th2));
98+ let lam = 0;
99+ if (this.controlled) {
100+ const eps = 0.02 * this.vTop;
101+ const lamMax = 4 / this.tau;
102+ lam = (this.eTarget - (T + V)) / (this.tau * (2 * T + eps));
103+ if (lam > lamMax) lam = lamMax;
104+ else if (lam < -lamMax) lam = -lamMax;
105+ }
106+
107+ out[0] = w1;
108+ out[1] = w2;
109+ out[2] = -(m1 + m2) * g * l1 * Math.sin(th1) - C1 + C2 + lam * p1;
110+ out[3] = -m2 * g * l2 * Math.sin(th2) + C1 - C2 + lam * p2;
111+ }
112+
113+ /** One RK4 step. */
114+ step(dt: number) {
115+ const { y, k1, k2, k3, k4, tmp } = this;
116+ this.deriv(y, k1);
117+ for (let i = 0; i < 4; i++) tmp[i] = y[i] + 0.5 * dt * k1[i];
118+ this.deriv(tmp, k2);
119+ for (let i = 0; i < 4; i++) tmp[i] = y[i] + 0.5 * dt * k2[i];
120+ this.deriv(tmp, k3);
121+ for (let i = 0; i < 4; i++) tmp[i] = y[i] + dt * k3[i];
122+ this.deriv(tmp, k4);
123+ for (let i = 0; i < 4; i++) y[i] += (dt / 6) * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]);
124+ this.t += dt;
125+ }
126+
127+ /**
128+ * Random state with normalized energy e (in units of vTop).
129+ * Angles are drawn so that V < E, the remaining energy goes into a random velocity direction.
130+ */
131+ randomize(e: number, rand: () => number) {
132+ const { m1, m2, l1, l2 } = this.cfg;
133+ const E = Math.max(e, 1e-6) * this.vTop;
134+ const a = Math.min(Math.PI, 3 * Math.sqrt(E / (m2 * this.cfg.g * Math.min(l1, l2))));
135+ let th1 = 0, th2 = 0, V = 0;
136+ for (let tries = 0; tries < 1000; tries++) {
137+ th1 = (2 * rand() - 1) * a;
138+ th2 = (2 * rand() - 1) * a;
139+ V = this.derived([th1, th2, 0, 0]).V;
140+ if (V < 0.9 * E) break;
141+ th1 = th2 = 0;
142+ V = 0;
143+ }
144+ const K = E - V;
145+ const phi = rand() * 2 * Math.PI;
146+ const u1 = Math.cos(phi), u2 = Math.sin(phi);
147+ const cd = Math.cos(th1 - th2);
148+ // mass matrix M
149+ const M11 = (m1 + m2) * l1 * l1;
150+ const M12 = m2 * l1 * l2 * cd;
151+ const M22 = m2 * l2 * l2;
152+ const T1 = 0.5 * (M11 * u1 * u1 + 2 * M12 * u1 * u2 + M22 * u2 * u2);
153+ const s = Math.sqrt(K / T1);
154+ const w1 = s * u1, w2 = s * u2;
155+ this.y[0] = th1;
156+ this.y[1] = th2;
157+ this.y[2] = M11 * w1 + M12 * w2;
158+ this.y[3] = M12 * w1 + M22 * w2;
159+ this.t = 0;
160+ }
161+}
162+
163+/**
164+ * Place the pendulum on the Poincaré section (θ1 = 0, dθ1/dt > 0) at normalized energy e,
165+ * with (θ2, p2) drawn uniformly over the energetically allowed region. Returns false if
166+ * no allowed point was found.
167+ */
168+export function seedOnSection(P: DoublePendulum, e: number, rand: () => number): boolean {
169+ const { m1, m2, l1, l2, g } = P.cfg;
170+ const E = e * P.vTop;
171+ // p2 range: bound from the kinetic energy available with θ1 = 0
172+ const pMax = Math.sqrt(2 * E * m2 * l2 * l2 * (1 + m2 / m1)) + 1e-12;
173+ for (let tries = 0; tries < 400; tries++) {
174+ const th2 = (2 * rand() - 1) * Math.PI;
175+ const p2 = (2 * rand() - 1) * pMax;
176+ const V = m2 * g * l2 * (1 - Math.cos(th2));
177+ if (V >= E) continue;
178+ const cd = Math.cos(-th2);
179+ const sd = Math.sin(-th2);
180+ const den = m1 + m2 * sd * sd;
181+ // T(p1) = E − V is a quadratic in p1
182+ const a = m2 * l2 * l2;
183+ const b = -2 * m2 * l1 * l2 * p2 * cd;
184+ const c = (m1 + m2) * l1 * l1 * p2 * p2 - 2 * m2 * l1 * l1 * l2 * l2 * den * (E - V);
185+ const disc = b * b - 4 * a * c;
186+ if (disc < 0) continue;
187+ // the larger root is the one with dθ1/dt > 0
188+ const p1 = (-b + Math.sqrt(disc)) / (2 * a);
189+ P.y[0] = 0;
190+ P.y[1] = th2;
191+ P.y[2] = p1;
192+ P.y[3] = p2;
193+ P.t = 0;
194+ return true;
195+ }
196+ return false;
197+}
198+
199+export function wrapAngle(a: number): number {
200+ return Math.atan2(Math.sin(a), Math.cos(a));
201+}
src/style.cssadded+69−0View file
@@ -0,0 +1,69 @@
1+/* Deliberately bare; real styling comes later. */
2+:root {
3+ --bg: #0b0b0b;
4+ --fg: #d8d8d8;
5+ --dim: #2e2e2e;
6+ --muted: #777;
7+ color-scheme: dark;
8+}
9+* { box-sizing: border-box; }
10+html, body { margin: 0; background: var(--bg); color: var(--fg); }
11+body { font: 14px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; }
12+a { color: var(--fg); text-decoration: none; }
13+a:hover { text-decoration: underline; }
14+button {
15+ font: inherit; color: var(--fg); background: none; border: 1px solid var(--dim);
16+ padding: 2px 10px; cursor: pointer;
17+}
18+button:hover { border-color: var(--muted); }
19+
20+.album { max-width: 640px; margin: 15vh auto; padding: 0 16px; }
21+.album h1 { font-weight: normal; font-size: 18px; margin: 0 0 24px; }
22+.tracks { padding-left: 1.5em; }
23+
24+.page { display: flex; min-height: 100vh; }
25+.stage { flex: 1; min-width: 0; display: flex; flex-direction: column; padding: 16px; gap: 12px; }
26+header { color: var(--muted); }
27+header a { color: var(--muted); }
28+.sep { color: var(--dim); }
29+
30+.view { flex: 1; display: flex; min-height: 0; align-items: center; justify-content: center; }
31+.view canvas { width: min(90vw, 80vh); aspect-ratio: 1; display: block; }
32+.page.with-author .view canvas { width: min(calc(100vw - 420px), 80vh); }
33+@media (max-width: 720px) {
34+ .page { flex-direction: column; }
35+ .view canvas, .page.with-author .view canvas { width: min(calc(100vw - 32px), 70vh); }
36+}
37+
38+.transport { display: flex; align-items: center; gap: 12px; }
39+.transport .play { min-width: 64px; }
40+.progress { flex: 1; height: 1px; background: var(--dim); position: relative; }
41+.progress.seekable { cursor: pointer; height: 9px; background: linear-gradient(var(--dim), var(--dim)) center / 100% 1px no-repeat; }
42+.progress .bar { position: absolute; left: 0; top: 50%; height: 1px; margin-top: -0.5px; background: var(--fg); width: 0; }
43+.edit { color: var(--muted); }
44+
45+.author {
46+ width: 360px; flex: none; height: 100vh; overflow-y: auto; position: sticky; top: 0;
47+ border-left: 1px solid var(--dim); padding: 12px; font-size: 12px;
48+}
49+@media (max-width: 720px) { .author { width: auto; height: auto; position: static; border-left: none; border-top: 1px solid var(--dim); } }
50+.author .actions { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-bottom: 10px; }
51+.author .status { color: var(--muted); }
52+.author fieldset { border: none; border-top: 1px solid var(--dim); margin: 10px 0 0; padding: 6px 0 0; }
53+.author legend { color: var(--muted); padding: 0 6px 0 0; }
54+.author .row { display: grid; grid-template-columns: 110px 1fr 64px 36px; gap: 6px; align-items: center; margin: 3px 0; }
55+.author .row > span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
56+.author .row:has(select) , .author .row:has(input[type=checkbox]) { grid-template-columns: 110px 1fr; }
57+.author .row:has(select) select { justify-self: start; }
58+.author .row:has(input[type=checkbox]) input { justify-self: start; }
59+.author > .row { grid-template-columns: 110px 80px; }
60+.author input[type=number], .author select {
61+ font: inherit; color: var(--fg); background: var(--bg); border: 1px solid var(--dim); padding: 1px 3px; width: 100%;
62+}
63+.author input[type=range] { width: 100%; accent-color: var(--muted); }
64+.author .unit { color: var(--muted); }
65+.readouts { display: grid; grid-template-columns: 110px 1fr; gap: 2px 6px; margin: 8px 0; color: var(--muted); }
66+.readouts dt, .readouts dd { margin: 0; }
67+.readouts dd { color: var(--fg); }
68+.author .row.text { grid-template-columns: 110px 1fr; align-items: start; }
69+.author textarea { font: inherit; font-size: 11px; color: var(--fg); background: var(--bg); border: 1px solid var(--dim); width: 100%; resize: vertical; }
tsconfig.jsonadded+19−0View file
@@ -0,0 +1,19 @@
1+{
2+ "compilerOptions": {
3+ "target": "ES2023",
4+ "module": "ESNext",
5+ "moduleResolution": "Bundler",
6+ "lib": ["ES2023", "DOM", "DOM.Iterable"],
7+ "types": ["node", "vite/client"],
8+ "strict": true,
9+ "noEmit": true,
10+ "allowImportingTsExtensions": true,
11+ "verbatimModuleSyntax": true,
12+ "erasableSyntaxOnly": true,
13+ "skipLibCheck": true,
14+ "isolatedModules": true,
15+ "noUnusedLocals": true,
16+ "paths": { "@modal-synth/*": ["../modal-synth/src/*"] }
17+ },
18+ "include": ["src", "scripts", "vite.config.ts"]
19+}
vite.config.tsadded+13−0View file
@@ -0,0 +1,13 @@
1+import { fileURLToPath } from "node:url";
2+import { defineConfig } from "vite";
3+
4+// Instruments are imported live from the sibling modal-synth project.
5+const modalSynth = fileURLToPath(new URL("../modal-synth/src", import.meta.url));
6+
7+export default defineConfig({
8+ base: "./",
9+ resolve: { alias: { "@modal-synth": modalSynth } },
10+ server: { fs: { allow: [".", modalSynth] } },
11+ worker: { format: "es" },
12+ build: { target: "es2022" },
13+});
↑↓ move↵openescclose