Remove the hum; reliable stop; deeper render-ahead buffer
- Poincaré and orbits no longer have the hum (and its settings).
- The play button is "stop" from the tap on play onward; a stop while the
audio system is still starting cancels the start.
- Instruments keep up to 12 s rendered ahead (was 4 s), so dense passages
are paid for out of the average load rather than the peak.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
24 changed files+48−215
README.mdmodified+6−6View file
@@ -29,7 +29,7 @@ Nothing is computed on the audio thread or the page's main thread in real time.
2929
3030 - **Score worker** (`scoreWorker.ts`, one per performance): runs the composition's *score* (`<dir>/score.ts`), which simulates the piece in piece time. It sends drawing data (rows of state, and events such as crossings) to the page, and timed note commands to the synth workers. It holds note commands back 2.5 s of piece time before releasing them, so a score can still lengthen a note it has already played (the final-note hold) once it finds, a little later, that the piece has ended. The ensemble's score renders its audio itself.
3131 - **Synth workers** (`synthWorker.ts`, one per instrument): render the modal-synth engine from those commands in 128-frame blocks from piece frame 0, at 48 kHz on every device. They render as fast as they can, up to whatever the score has released and the buffer the player asks for.
32-- **Player worklet** (`player.ts`): owns the piece's clock. Its playhead advances only while every stem has audio for it. When any stem runs short, everything pauses: the sound fades, and the picture freezes. A spinner shows how full the buffer is. Play resumes once every stem is buffered ahead. The player measures how fast the stems are being rendered. On a device that renders slower than real time, a pause waits long enough to play through to the end; otherwise each pause doubles the wait (1, 2, 4… s), so pauses get rarer.
32+- **Player worklet** (`player.ts`): owns the piece's clock. Its playhead advances only while every stem has audio for it. When any stem runs short, everything pauses: the sound fades, and the picture freezes. A spinner shows how full the buffer is. Play resumes once every stem is buffered ahead; while playing, the workers keep up to 12 s rendered ahead, so dense passages are paid for out of the average load, not the peak. The player measures how fast the stems are being rendered. On a device that renders slower than real time, a pause waits long enough to play through to the end; otherwise each pause doubles the wait (1, 2, 4… s), so pauses get rarer.
3333 - **Page** (`performance.ts`, `piece.ts`): wires the workers to the player with message ports, applies each output's effects (modal-synth's own, or one shared reverb) and live levels, and draws. Each composition's view (`<dir>/view.ts`) draws from the score's data at the player's playhead (less the output latency), so sound and picture share one clock. A seek or an edit starts a new performance at that moment. The score fast-forwards silently and computes sound from 4 s before it, so notes already ringing are heard.
3434
3535 **Same on every device**: the AudioContext runs at 48 kHz, so it is the same rate the performance is computed at. Nothing depends on device speed; a slow device just buffers more. The physics uses `src/physics/dmath.ts`, ports of the fdlibm algorithms for sin, cos, exp, log and pow built from + − × ÷. Browsers' own `Math.sin` and the like differ in the last bit, and a chaotic pendulum turns that into a different performance within seconds. Scores never call `Math.random`; variations come from the seed.
@@ -52,23 +52,23 @@ The section is θ1 = 0, crossed with dθ1/dt > 0, and plotted at (θ2, p2). Each
5252 - θ2 sets the pitch (signed or absolute, range, curve, scale, root)
5353 - |p2| sets the loudness
5454
55-After `duration`, once the pendulum has come to rest, no more crossings register: the last note is held for `finalHold` and faded over `finalFade`, the hum fades with it, and the piece ends.
55+After `duration`, once the pendulum has come to rest, no more crossings register: the last note is held for `finalHold` and faded over `finalFade`, and the piece ends.
5656
5757 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.
5858
59-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`.
59+The energy follows an envelope: start → peak (exponential or linear rise) → hold → fall to zero at `duration`.
6060
6161 Units: energy is in units of the potential energy with both arms up, and p2 is in units of √(m2·l2²·E_top).
6262
6363 ## 2. orbits
6464
65-Several pendulums at once (8 by default, up to 20). All follow the same energy envelope from random starts. Only the section is shown: each orbit traces its crossings in its own color (**colors**, cycling). Each orbit plays instrument slot n (cycling through 6 slots), with a register shift per slot. Orbits on the same instrument share one polyphonic instance. The note mapping, hum, and rest-based ending match composition 1. The piece ends when every orbit has come to rest and its last note has faded.
65+Several pendulums at once (8 by default, up to 20). All follow the same energy envelope from random starts. Only the section is shown: each orbit traces its crossings in its own color (**colors**, cycling). Each orbit plays instrument slot n (cycling through 6 slots), with a register shift per slot. Orbits on the same instrument share one polyphonic instance. The note mapping and rest-based ending match composition 1. The piece ends when every orbit has come to rest and its last note has faded.
6666
6767 Behind the live dots: the grey portrait of the section at the current energy, and each pendulum's *traced orbit* in its color. Each time the portrait refreshes, every pendulum's current state is followed forward with its energy frozen. That draws the orbit it is on right now: a closed loop on an island, a cloud in the chaotic sea. Traces refresh and crossfade with the portrait as the energy moves.
6868
6969 Each distinct instrument renders in its own synth worker, in parallel; this is the heaviest piece, so it buffers longest on slow devices. Every device plays all the orbits.
7070
71-Shared machinery lives in `src/compositions/shared/`: the energy envelope, crossing → note mapping, hum score, section plot with its "fit energy" zoom, and the portrait/trace layer with its throttled worker.
71+Shared machinery lives in `src/compositions/shared/`: the energy envelope, crossing → note mapping, section plot with its "fit energy" zoom, and the portrait/trace layer with its throttled worker.
7272
7373 ## 3. divergence
7474
@@ -76,7 +76,7 @@ Twelve pendulums (1–24) are released together from rest at a wide angle (120°
7676
7777 A note sounds when a bottom bob crosses the vertical through the pivot, in either direction. Loudness follows the bob's speed, and the note is panned toward the side the bob is heading (two copies of the instrument, panned left and right). **pitch** = "chord" gives each pendulum its own note of a chord spread across the range, so the opening is one chord that breaks into arpeggios. With **two chords** (on by default), left-to-right and right-to-left crossings play two interleaved chords (2n notes spread over the range, alternating between them), so the opening swings alternate between neighbouring chords. "motion" takes the pitch from the bob's speed, so the pendulums start in unison and spread out.
7878
79-The pendulums swing freely (energy conserved) for **swinging** (40 s). Then each pendulum's energy follows (1 − u)^curve to zero over **damping** (20 s), with viscous friction settling the last of it. Each pendulum's last note rings out, and the piece ends with the fade. No hum.
79+The pendulums swing freely (energy conserved) for **swinging** (40 s). Then each pendulum's energy follows (1 − u)^curve to zero over **damping** (20 s), with viscous friction settling the last of it. Each pendulum's last note rings out, and the piece ends with the fade.
8080
8181 ## 4. descent
8282
site/assets/index-CTL9vx7o.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=48e3,t=null;async function n(){if(!t){let n;try{n=new AudioContext({latencyHint:`playback`,sampleRate:e})}catch{n=new AudioContext({latencyHint:`playback`})}let r=n.createGain(),i=n.createDynamicsCompressor();i.threshold.value=-6,i.knee.value=6,i.ratio.value=12,i.attack.value=.003,i.release.value=.25,r.connect(i).connect(n.destination),t={ctx:n,input:r}}return t.ctx.state!==`running`&&await t.ctx.resume(),t}function r(e){return 10**(e/20)}function i(e){let t={};for(let n of e)t[n.key]=n.default;return t}function a(e,...t){let n=i(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 o(e,t){let n={};for(let r of e)n[r.key]=t[r.key];return JSON.stringify(n,null,2)+`
2+`}var s=1e3;function c(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))*s)}function l(e,t){let n=t/s,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 u(e){return String(Number(e.toPrecision(4)))}function d(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n),r}function f(e){let t=d(`aside`,{className:`author`}),n=[],r=(t,n)=>{e.set({...e.get(),[t]:n})},i=d(`span`,{className:`status`}),f=e=>{i.textContent=e,window.setTimeout(()=>{i.textContent===e&&(i.textContent=``)},2e3)},p=d(`button`,{textContent:`copy config`});p.onclick=async()=>{let t=o(e.schema,e.get());try{await navigator.clipboard.writeText(t),f(`copied`)}catch{window.prompt(`copy:`,t)}};let m=d(`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(a(e.schema,JSON.parse(t))),y(),f(`pasted`)}catch{f(`not valid JSON`)}};let h=d(`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(d(`div`,{className:`actions`},p,m,h,i));let g=d(`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(d(`label`,{className:`row`},d(`span`,{textContent:`start at (s)`}),g));let _=d(`dl`,{className:`readouts`});t.append(_);let v=new Map;for(let i of e.schema){let a=v.get(i.group);a||(a=d(`fieldset`,{},d(`legend`,{textContent:i.group})),v.set(i.group,a),t.append(a));let o=d(`label`,{className:`row`},d(`span`,{textContent:i.label,title:i.hint??``}));if(i.kind===`number`){let t=d(`input`,{type:`range`,min:`0`,max:String(s),step:`1`}),a=d(`input`,{type:`number`,step:`any`}),f=d(`span`,{className:`unit`,textContent:i.unit??``});t.oninput=()=>{let e=l(i,Number(t.value));a.value=u(e),r(i.key,e)},a.onchange=()=>{let e=Number(a.value);Number.isFinite(e)&&(t.value=String(c(i,e)),r(i.key,e))},n.push(()=>{let n=e.get()[i.key];t.value=String(c(i,n)),a.value=u(n)}),o.append(t,a,f)}else if(i.kind===`select`){let t=d(`select`);for(let e of i.options)t.append(d(`option`,{value:e,textContent:e}));t.onchange=()=>r(i.key,t.value),n.push(()=>t.value=e.get()[i.key]),o.append(t)}else if(i.kind===`text`){let t=d(`textarea`,{rows:3,spellcheck:!1,placeholder:i.hint??``});t.onchange=()=>r(i.key,t.value),n.push(()=>t.value=e.get()[i.key]),o.classList.add(`text`),o.append(t)}else{let t=d(`input`,{type:`checkbox`});t.onchange=()=>r(i.key,t.checked),n.push(()=>t.checked=e.get()[i.key]),o.append(t)}a.append(o)}function y(){for(let e of n)e()}function b(){let t=e.readouts();_.replaceChildren(...Object.entries(t).flatMap(([e,t])=>[d(`dt`,{textContent:e}),d(`dd`,{textContent:t})]))}return y(),b(),{el:t,sync:y,updateReadouts:b}}function p(){return 1+Math.floor(Math.random()*999999)}var m=(e,t)=>e[t],h=e=>e.geometry===`membrane`||e.geometry===`plate`||e.geometry===`disc`,g=(...e)=>t=>e.includes(t.geometry),_=(...e)=>t=>e.includes(t.exciter),v=[`bow`,`reed`,`selfosc`,`noise`],y=[[`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`]],b=[[`sine`,`Sine`],[`tri`,`Triangle`],[`saw`,`Saw`],[`square`,`Square`],[`sh`,`Sample & hold`],[`smooth`,`Smooth random`]];function x(e){let t=t=>t[`lfo${e}Target`]!==`off`;return[{kind:`enum`,id:`lfo${e}Target`,label:`LFO ${e} →`,group:`Modulation`,options:y,def:`off`},{kind:`enum`,id:`lfo${e}Shape`,label:`Shape`,group:`Modulation`,options:b,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 S=[{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:g(`plate`)},{kind:`num`,id:`powerExp`,label:`Exponent p`,group:`Body`,min:.3,max:3,def:1.5,model:!0,show:g(`free`)},{kind:`num`,id:`discExp`,label:`Chladni exponent`,group:`Body`,min:1,max:2.5,def:2,model:!0,show:g(`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&&h(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:h},{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:_(`strike`)},{kind:`num`,id:`hardness`,label:`Contact time`,group:`Exciter`,min:.05,max:20,def:1,scale:`log`,unit:`ms`,show:_(`strike`,`impulse`)},{kind:`num`,id:`feltExp`,label:`Felt exponent`,group:`Exciter`,min:1,max:4,def:2.5,show:_(`strike`)},{kind:`num`,id:`bowForce`,label:`Bow force`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:_(`bow`)},{kind:`num`,id:`bowSpeed`,label:`Bow speed`,group:`Exciter`,min:0,max:2,def:.4,scale:`pow2`,show:_(`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:_(`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:_(`reed`)},{kind:`num`,id:`reedGain`,label:`Reed opening`,group:`Exciter`,min:0,max:2,def:.5,show:_(`reed`)},{kind:`num`,id:`breath`,label:`Breath noise`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`,show:_(`reed`)},{kind:`num`,id:`selfGain`,label:`Negative damping`,group:`Exciter`,min:0,max:4,def:.5,scale:`pow2`,show:_(`selfosc`)},{kind:`num`,id:`selfSat`,label:`Saturation level`,group:`Exciter`,min:.02,max:4,def:.5,scale:`log`,show:_(`selfosc`)},{kind:`num`,id:`noiseLevel`,label:`Noise level`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:_(`noise`)},{kind:`num`,id:`noiseColor`,label:`Noise cutoff`,group:`Exciter`,min:50,max:16e3,def:3e3,scale:`log`,unit:`Hz`,show:_(`noise`,`reed`,`bow`)},{kind:`num`,id:`attack`,label:`Attack`,group:`Exciter`,min:1,max:3e3,def:40,scale:`log`,unit:`ms`,show:_(...v)},{kind:`num`,id:`release`,label:`Release`,group:`Exciter`,min:5,max:5e3,def:150,scale:`log`,unit:`ms`,show:_(...v)},{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},...x(1),...x(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:h},{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(S.map(e=>[e.id,e]));var C=Object.fromEntries(S.map(e=>[e.id,e.def]));S.filter(e=>e.model).map(e=>e.id);var w=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=m(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=m(e,`delayMix`);n(this.delaySend.gain,i);let a=m(e,`delayTime`)/1e3;n(this.dL.delayTime,a),n(this.dR.delayTime,a),n(this.fbL.gain,m(e,`delayFb`)),n(this.fbR.gain,m(e,`delayFb`));let o=m(e,`reverbMix`);n(this.revSend.gain,o),n(this.dry.gain,r>0?1/(1+2*r):1),n(this.master.gain,10**(m(e,`volume`)/20));let s=m(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}};function T(e,t,n,r,i){if(!r){t.connect(n);return}if(i===`own`){let i=new w(e,n);t.connect(i.input),i.set(r);return}let a=e.createGain();if(a.gain.value=10**(r.volume/20),t.connect(a).connect(n),i!==`none`){let n=e.createGain();n.gain.value=r.reverbMix*a.gain.value,t.connect(n).connect(i.send)}}var ee=class{input;conv;constructor(e,t,n){this.input=e.createGain(),this.conv=e.createConvolver(),this.conv.buffer=E(e,n),this.input.connect(this.conv).connect(t)}dispose(){this.input.disconnect(),this.conv.disconnect()}};function E(e,t){let n=e.sampleRate,r=Math.round(n*Math.min(t*1.1,12)),i=e.createBuffer(2,r,n);for(let e=0;e<2;e++){let a=i.getChannelData(e),o=0;for(let e=0;e<r;e++){let r=e/n,i=9e3*Math.exp(-r/(.6*t))+400,s=1-Math.exp(-2*Math.PI*i/n);o+=s*(Math.random()*2-1-o),a[e]=o*Math.exp(-6.9*r/t)*Math.min(1,r/.004)*.5}}return i}var D=class{tracks=new Map;events=[];infos=[];add(e,t,n){if(!n.length)return;let r=this.tracks.get(e);r||this.tracks.set(e,r=[]),r.push({t0:n[0],t1:n[n.length-t],stride:t,data:n})}addEvents(e){for(let t of e)this.events.push(t)}addInfo(e,t){this.infos.push({t:e,info:t})}info(e){let t={};for(let n of this.infos)n.t<=e&&(t=n.info);return t}trim(e){for(let t of this.tracks.values())for(;t.length>1&&t[1].t0<=e&&t[0].t1<e;)t.shift();let t=0;for(;t<this.events.length&&this.events[t].t<e;)t++;for(t>0&&this.events.splice(0,t);this.infos.length>1&&this.infos[1].t<=e;)this.infos.shift()}last(e){let t=this.tracks.get(e);return t?.length?t[t.length-1].t1:-1/0}at(e,t,n){let r=this.tracks.get(e);if(!r?.length)return null;let i=r.length-1;for(;i>0&&r[i].t0>t;)i--;let a=r[i],o=a.stride,s=a.data.length/o,c=a.data,l=0,u=s-1;if(t<=c[0])u=0;else if(t>=c[(s-1)*o])l=u=s-1;else for(;u-l>1;){let e=l+u>>1;c[e*o]<=t?l=e:u=e}let d=l*o,f=u*o,p=c,m=c;l===u&&l===s-1&&i+1<r.length&&t>c[d]&&(m=r[i+1].data,f=0);let h=p[d],g=m[f],_=g>h?Math.min(1,Math.max(0,(t-h)/(g-h))):0;for(let e=1;e<o;e++)n[e-1]=p[d+e]+_*(m[f+e]-p[d+e]);return n}rows(e,t,n,r){let i=this.tracks.get(e);if(i)for(let e of i){if(e.t1<t)continue;if(e.t0>n)break;let i=e.stride,a=e.data;for(let e=0;e<a.length;e+=i){let i=a[e];if(!(i<t)){if(i>n)break;r(a,e)}}}}},O=new URL(`player-xzpyjnp9.js`,import.meta.url).href,k=4,A=new WeakMap,j=class{store=new D;start;seed;state=`loading`;endT=null;error=null;fill=0;rebuffers=0;ahead=0;ready;ctx;layout;workers=[];node=null;master;levels=[];pans=[];reverb=null;status=null;disposed=!1;estimatedEnd;constructor(e,t,n,r,i,a,o,s){this.ctx=e,this.start=a,this.seed=i,this.layout=o,this.estimatedEnd=s,this.master=e.createGain(),this.master.connect(t),this.ready=this.open(n,r)}async open(t,n){let r=this.ctx,i=A.get(r);if(i||A.set(r,i=r.audioWorklet.addModule(O)),await i,this.disposed)return;let{stems:a,outputs:o}=this.layout,s={stems:a.length,outputs:o.length,route:a.map(e=>e.output),startFrame:Math.round(this.start*e),estimatedEnd:Math.round(this.estimatedEnd*e)},c=new AudioWorkletNode(r,`stream-player`,{numberOfInputs:0,numberOfOutputs:o.length,outputChannelCount:o.map(()=>2),processorOptions:s});this.node=c,o.some(e=>e.effects===`shared`)&&(this.reverb=new ee(r,this.master,this.layout.reverbTime??3)),o.forEach((e,t)=>{let i=r.createGain();i.gain.value=10**(e.level(n)/20),c.connect(i,t);let a=i,o=null;e.pan&&(o=r.createStereoPanner(),o.pan.value=e.pan(n),i.connect(o),a=o),T(r,a,this.master,e.sound,e.effects===`shared`?{send:this.reverb.input}:e.effects),this.levels.push(i),this.pans.push(o)}),c.port.onmessage=e=>this.onStatus(e.data);let l=Math.max(0,this.start-k),u=[],d=[];a.forEach((t,n)=>{if(t.kind!==`synth`){d.push(null);return}let r=new Worker(new URL(new URL(`synthWorker-DKkixN-4.js`,import.meta.url).href,``+import.meta.url),{type:`module`});this.workers.push(r);let i=new MessageChannel,a=new MessageChannel;d.push(i.port1),u.push(a.port2);let o={type:`init`,sound:t.sound??{},fromFrame:Math.floor(l*e/128)*128,sendFrame:Math.round(this.start*e),stem:n,scorePort:i.port2,playerPort:a.port1,slow:Number(new URLSearchParams(location.search).get(`slow`))||void 0};r.postMessage(o,[i.port2,a.port1]),r.onerror=e=>this.fail(`instrument: ${e.message}`)});let f=new Worker(new URL(new URL(`scoreWorker-DiSIToaP.js`,import.meta.url).href,``+import.meta.url),{type:`module`});this.workers.push(f);let p=new MessageChannel;u.push(p.port2),f.onmessage=e=>this.onScore(e.data),f.onerror=e=>this.fail(`score: ${e.message}`);let m={type:`init`,comp:t,P:n,seed:this.seed,start:this.start,from:l,synthPorts:d,playerPort:p.port1};f.postMessage(m,[...d.filter(e=>!!e),p.port1]),c.port.postMessage({type:`ports`,ports:u},u),this.state=`buffering`}onScore(e){e.type===`frames`?this.store.add(e.track,e.stride,e.data):e.type===`events`?this.store.addEvents(e.events):e.type===`info`?this.store.addInfo(e.t,e.info):e.type===`end`?this.endT=e.t:e.type===`error`&&this.fail(e.message)}onStatus(e){this.status=e,this.state!==`error`&&(this.state=e.state,this.fill=e.fill,this.rebuffers=e.rebuffers,this.ahead=e.ahead)}fail(e){this.state=`error`,this.error=e,console.error(e)}time(){let t=this.status;if(!t)return this.start;let n=t.playhead;t.state===`playing`&&(n+=Math.min(4096,Math.max(0,this.ctx.currentTime*e-t.at)));let r=(this.ctx.outputLatency||0)+(this.ctx.baseLatency||0);return Math.max(this.start,n/e-r)}update(e){let t=this.ctx.currentTime;this.layout.outputs.forEach((n,r)=>{this.levels[r]?.gain.setTargetAtTime(10**(n.level(e)/20),t,.05),n.pan&&this.pans[r]?.pan.setTargetAtTime(n.pan(e),t,.05)})}dispose(){if(this.disposed)return;this.disposed=!0;for(let e of this.workers)e.terminate();let e=this.ctx.currentTime,t=this.master,n=this.node,r=this.reverb;t.gain.setTargetAtTime(0,e,.02),window.setTimeout(()=>{n?.disconnect(),n?.port.close(),r?.dispose(),t.disconnect()},200)}},te=400;function M(e,t,n){let r=e.view(t,n),i=e.schema.filter(e=>!e.live).map(e=>e.key),a=e=>JSON.stringify(i.map(t=>e[t])),o=null,s=null,c=``,l=null,u=0,d=null,f=0,m=0,h=null,g=window.setInterval(()=>l?.trim(y.now()-r.keep(n())),1e3);function _(t,r,i){let u=n();s?.dispose(),o=t,i&&f||(f=u.seed>0?Math.round(u.seed):p()),s=new j(t.ctx,t.input,e.id,u,f,Math.max(0,r),e.layout(u),e.estimateLength(u)),c=a(u),l=s.store,d=null,h=null,m=0}function v(){s&&=(u=s.time(),s.endT!==null&&(d=s.endT),s.dispose(),null)}let y={get playing(){return s!==null},async start(e,t){_(e,t,!1),await s.ready},stop:v,seek(e){o&&_(o,e,!0)},draw(){let e=n();if(s){if(s.state===`error`)h=`something went wrong computing this piece; try play again`,v();else if(s.state===`ended`){let e=s.endT??s.time();v(),u=e,y.onEnded?.()}else if(s.update(e),a(e)!==c){let e=performance.now();m?e>=m&&o&&_(o,s.time(),!0):m=e+te}else m=0}let t=y.now();l?.trim(t-r.keep(e)),r.draw(t,l,s?.state===`playing`)},now:()=>s?s.time():u,length:()=>s?.endT??d??e.estimateLength(n()),status:()=>({buffering:s!==null&&(s.state===`loading`||s.state===`buffering`),fill:s?.fill??0}),notice:()=>h,readouts(){let e=y.now();return{time:`${e.toFixed(1)} / ${y.length().toFixed(1)} s`,buffer:s?`${s.state}, ${s.ahead.toFixed(1)} s ahead, ${s.rebuffers} pause${s.rebuffers===1?``:`s`}`:`–`,"seed used":f?String(f):`–`,...l?.info(e)??{},...r.readouts?.(e,l)??{}}},dispose(){v(),window.clearInterval(g),r.dispose?.(),t.replaceChildren()}};return y}var ne={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,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},N={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},re=[{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:{...N,modes:128,inharm:4e-5,exPos:.09,vibDepth:16,vibRate:5.2,soundbox:`cello`}},{name:`Violin`,category:`Instrument`,note:67,p:{...N,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:{...N,modes:96,inharm:3e-5,exPos:.1,vibDepth:15,vibRate:5.5,soundbox:`viola`}},{name:`Double bass`,category:`Instrument`,note:36,p:{...N,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:{...N,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 ie(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 P=[...re.map(e=>`modal: ${e.name}`),`modal: custom`];function F(e,t,n={}){let r=e===`modal: custom`?ie(t):re.find(t=>`modal: ${t.name}`===e)?.p;return{...C,...r??{},...n}}function ae(e){let t=F(e.noteInstrument,e.modalCustom);return{stems:[{kind:`synth`,sound:t,output:0}],outputs:[{effects:`own`,sound:t,level:e=>e.notesLevel}]}}function oe(e){return e.duration+.5+e.finalHold+e.finalFade+.3}var I=[{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:`modal: Nylon harp`,options:P,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:Object.keys({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})},{group:`notes`,key:`root`,label:`root`,kind:`select`,default:`D`,options:[`C`,`C#`,`D`,`D#`,`E`,`F`,`F#`,`G`,`G#`,`A`,`A#`,`B`]},{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`,live:!0},{group:`notes`,key:`noteLength`,label:`length`,kind:`number`,default:1.5,min:.05,max:10,log:!0,unit:`s`},{group:`visual`,key:`pendulumAlpha`,label:`pendulum opacity`,kind:`number`,default:1,min:0,max:1,step:.01,hint:`0 = hide the pendulum`,live:!0},{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)`,live:!0},{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`,live:!0},{group:`visual`,key:`fade`,label:`point fade`,kind:`number`,default:10,min:.2,max:120,log:!0,unit:`s`,live:!0},{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`,live:!0},{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`,live:!0},{group:`visual`,key:`plotP`,label:`fixed p2 range`,kind:`number`,default:1.5,min:.05,max:5,log:!0,live:!0},{group:`visual`,key:`pointSize`,label:`point size`,kind:`number`,default:2,min:.5,max:8,step:.1,unit:`px`,live:!0},{group:`orbits`,key:`orbits`,label:`show orbits`,kind:`bool`,default:!0,live:!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`,live:!0},{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`,live:!0},{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`,live:!0},{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`,live:!0},{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`,live:!0},{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`,live:!0},{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`,live:!0},{group:`orbits`,key:`orbitAlpha`,label:`brightness`,kind:`number`,default:.3,min:.02,max:1,step:.01,live:!0},{group:`orbits`,key:`orbitSize`,label:`point size`,kind:`number`,default:1,min:.5,max:4,step:.1,unit:`px`,live:!0}],se=100,ce=class{worker=null;portraits=[];resetPending=!1;latestGen=0;ignoreBelow=0;rate=0;newPts=0;rateT=0;now;live;constructor(e,t){this.now=e,this.live=t}reset(){this.dirty=!0,this.portraits=[],this.ignoreBelow=this.latestGen+1,this.resetPending=!0}ensureWorker(){return this.worker||(this.worker=new Worker(new URL(new URL(`orbitWorker-CV_Zv_V1.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),this.worker.onmessage=e=>this.receive(e.data)),this.worker}receive({gen:e,energy:t,pts:n,tracks:r}){if(!this.live()||(this.latestGen=Math.max(this.latestGen,e),e<this.ignoreBelow))return;let i=this.portraits[this.portraits.length-1];if(!i||e>i.gen){let n=this.now();for(let e of this.portraits)e.retiredAt??=n;i={gen:e,energy:t,pts:[],tracks:new Map,retiredAt:null},this.portraits.push(i)}else if(e<i.gen)return;for(let e=0;e<n.length;e++)i.pts.push(n[e]);for(let e of r){let t=i.tracks.get(e.id);t||i.tracks.set(e.id,t=[]);for(let n=0;n<e.pts.length;n++)t.push(e.pts[n])}this.newPts+=n.length/2+r.reduce((e,t)=>e+t.pts.length/2,0),this.dirty=!0}post(e,t,n,r,i,a){if(!t.show&&!t.tracks&&!this.worker)return;let o={running:e&&(t.show||t.tracks),reset:this.resetPending,energy:n,m2:r,l2:i,count:t.show?Math.round(t.count):0,life:t.life,band:t.band,minHold:t.minHold,maxPoints:t.show?t.maxPoints:0,cpu:t.cpu,tracks:t.tracks?a:[],trackMax:t.trackMax};this.resetPending=!1,this.ensureWorker().postMessage(o)}layer=null;layerAt=0;layerKey=``;dirty=!0;lm={cx:0,kx:1,cy:0,ky:1};draw(e,t,n,r,i){let{g:a,w:o,h:s,sx:c,sy:l}=e,u=this.portraits.length;this.portraits=this.portraits.filter(e=>e.retiredAt===null||t-e.retiredAt<n.xfade),this.portraits.length!==u&&(this.dirty=!0);let d=this.portraits.some(e=>e.retiredAt!==null),f=window.devicePixelRatio||1,p=[o,s,f,n.show,n.tracks,n.alpha,n.size,n.trackAlpha,n.trackSize,r].join(`|`),m={cx:c(0),kx:c(1)-c(0),cy:l(0),ky:l(1)-l(0)},h=m.kx/this.lm.kx,g=m.ky/this.lm.ky,_=Math.abs(Math.log(h))>.05||Math.abs(Math.log(g))>.05,v=performance.now();this.layer||=document.createElement(`canvas`);let y=this.layer;if((this.dirty||d||_||p!==this.layerKey)&&v-this.layerAt>=se){let e=Math.round(o*f),a=Math.round(s*f);(y.width!==e||y.height!==a)&&(y.width=e,y.height=a);let u=y.getContext(`2d`);u.setTransform(f,0,0,f,0,0),u.clearRect(0,0,o,s);for(let e of this.portraits){let a=e.retiredAt===null?1:Math.max(0,1-(t-e.retiredAt)/n.xfade);if(n.show&&e.pts.length){let t=n.size;u.fillStyle=r,u.globalAlpha=n.alpha*a,u.beginPath();let i=e.pts;for(let e=0;e<i.length;e+=2)u.rect(c(i[e])-t/2,l(i[e+1])-t/2,t,t);u.fill()}if(n.tracks){let t=n.trackSize;for(let[r,o]of e.tracks){u.fillStyle=i(r),u.globalAlpha=n.trackAlpha*a,u.beginPath();for(let e=0;e<o.length;e+=2)u.rect(c(o[e])-t/2,l(o[e+1])-t/2,t,t);u.fill()}}}u.globalAlpha=1,this.layerAt=v,this.layerKey=p,this.lm=m,this.dirty=!1}if(y.width){let e=m.kx/this.lm.kx,t=m.ky/this.lm.ky;a.save(),a.setTransform(f*e,0,0,f*t,f*(m.cx-e*this.lm.cx),f*(m.cy-t*this.lm.cy)),a.drawImage(y,0,0,o,s),a.restore()}}describe(){let e=performance.now()/1e3;e-this.rateT>1&&(this.rate=this.newPts/(e-this.rateT||1),this.newPts=0,this.rateT=e);let t=this.portraits.find(e=>e.retiredAt===null);if(!t)return`–`;let n=[...t.tracks.values()].reduce((e,t)=>e+t.length/2,0);return`E ${t.energy.toFixed(4)}, ${t.pts.length/2} pts${t.tracks.size?` + ${n} traced`:``}, ${Math.round(this.rate)}/s`}dispose(){this.worker?.terminate(),this.worker=null}};function L(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 R(e,t,n=`#ccc`){return getComputedStyle(e).getPropertyValue(t).trim()||n}var le=class{thR=Math.PI;pR=1;lastWall=0;canvas;constructor(e){this.canvas=e}begin(e,t,n,r,i){let a=performance.now()/1e3,o=a-this.lastWall;this.lastWall=a;let s=this.canvas,c=L(s),l=s.clientWidth,u=s.clientHeight;c.clearRect(0,0,l,u);let d=Math.PI,f=e.plotP;if(e.plotZoom===`fit energy`&&t!==null&&n){let e=Math.max(1e-6,t),i=e*r,a=i>=2*n.m2*n.g*n.l2?Math.PI:Math.acos(1-i/(n.m2*n.g*n.l2));d=Math.min(Math.PI,1.08*a),f=1.08*Math.sqrt(2*e)}let p=o>0&&o<.5?1-Math.exp(-o/Math.max(.01,e.zoomSmooth)):1;this.thR*=Math.exp(p*Math.log(d/this.thR)),this.pR*=Math.exp(p*Math.log(f/this.pR));let m=(l/2-8)/this.thR,h=(u/2-8)/this.pR;return c.strokeStyle=i,c.lineWidth=1,c.beginPath(),c.moveTo(8,u/2),c.lineTo(l-8,u/2),c.moveTo(l/2,8),c.lineTo(l/2,u-8),c.stroke(),{g:c,w:l,h:u,sx:e=>l/2+m*e,sy:e=>u/2-h*e}}};function ue(e,t,n,r,i,a,o){let{g:s,sx:c,sy:l}=e;s.fillStyle=o,s.globalAlpha=Math.exp(-r/i),s.beginPath(),s.arc(c(t),l(n),a/2,0,2*Math.PI),s.fill(),r<.4&&(s.globalAlpha=1-r/.4,s.strokeStyle=o,s.beginPath(),s.arc(c(t),l(n),a/2+3+12*r,0,2*Math.PI),s.stroke()),s.globalAlpha=1}var de=64,fe=2,pe=50;function z(e,t){return 2*(1+e)+2*e*t}function me(e,t){e.classList.add(`c01`);let n=document.createElement(`canvas`);e.append(n);let r=new le(n),i=0,a=!1,o=new ce(()=>i,()=>a),s=e=>({show:e.orbits,count:e.orbitCount,cpu:e.orbitCpu,life:e.orbitLife,band:e.orbitBand,minHold:e.orbitMinHold,maxPoints:e.orbitMaxPoints,xfade:e.orbitXfade,alpha:e.orbitAlpha,size:e.orbitSize,tracks:!1,trackMax:0,trackAlpha:0,trackSize:1}),c=new Float64Array(3),l=null,u=0,d=0,f=1/60;function p(t,n,r,i,o,s){let l=i.pendulumAlpha;if(l<=0)return;let u=e=>{let t=s?.at(0,e,c);return t?[t[0],t[1]]:[0,0]},d=a?i.motionBlur*f:0,p=i.lengthRatio,m=i.pendulumSize*Math.min(n,r)/2,h=.9*m/(1+p),g=8+m,_=8+m,v=1;if(d>0){let e=0,t=u(o);for(let n=1;n<=8;n++){let r=u(o-d*n/8);e+=h*(+Math.abs(r[0]-t[0])+p*Math.abs(r[1]-t[1])),t=r}v=Math.max(2,Math.min(de,Math.ceil(e/fe)))}let y=l*(v===1?1:1-.03**(1/v)),b=3*Math.cbrt(i.massRatio),x=R(e,`--fg`);t.strokeStyle=x,t.fillStyle=x,t.lineWidth=1.5,t.lineCap=`round`,t.globalAlpha=y;for(let e=0;e<v;e++){let[n,r]=u(o-d*e/Math.max(1,v-1)),i=g+h*1*Math.sin(n),a=_+h*1*Math.cos(n),s=i+h*p*Math.sin(r),c=a+h*p*Math.cos(r);t.beginPath(),t.moveTo(g,_),t.lineTo(i,a),t.lineTo(s,c),t.stroke(),t.beginPath(),t.arc(i,a,3,0,2*Math.PI),t.moveTo(s+b,c),t.arc(s,c,b,0,2*Math.PI),t.fill()}t.globalAlpha=l,t.beginPath(),t.arc(g,_,1.5,0,2*Math.PI),t.fill(),t.globalAlpha=1}return{keep:e=>4.6*e.fade+.5,draw(n,m,h){let g=t();i=n,a=h;let _=performance.now(),v=(_-d)/1e3;d=_,v>0&&v<.1&&(f+=(v-f)*.1),m!==l&&(l=m,o.reset());let y=m?.at(0,n,c),b=y?y[2]:null,x=g.massRatio,S=g.lengthRatio,C=R(e,`--fg`);_-u>pe&&(u=_,o.post(h,s(g),b??0,x,S,[]));let w=r.begin(g,b,{m1:1,l1:1,g:1,m2:x,l2:S},z(x,S),R(e,`--dim`));if(o.draw(w,n,s(g),C,()=>C),m){let e=g.fade,t=g.pointSize;for(let r of m.events){let i=n-r.t;if(i<0)break;ue(w,r.th2,r.p2,i,e,t,C)}}p(w.g,w.w,w.h,g,n,m)},readouts:()=>({"orbit portrait":o.describe()}),dispose(){o.dispose(),e.classList.remove(`c01`)}}}var B={id:`01-poincare`,schema:I,layout:ae,estimateLength:oe,view:me},he={id:B.id,title:`poincaré`,schema:I,defaults:ne,create:(e,t)=>M(B,e,t)},ge={duration:60,peakTime:25,holdTime:10,energyStart:.005,energyPeak:.4,riseShape:`exponential`,riseCurve:1,fallCurve:1,restEnergy:.001,finalHold:2,finalFade:5,speed:40,massRatio:1,lengthRatio:1,tau:2,seed:0,orbitCount:8,colors:`#d6b37a, #7fa8cf, #c48bb8, #93bf8a, #d48f7f, #a9a6e0`,slot1Instrument:`modal: Nylon harp`,slot1Octave:0,slot2Instrument:`modal: Marimba`,slot2Octave:-1,slot3Instrument:`modal: Vibraphone`,slot3Octave:0,slot4Instrument:`modal: Church bell`,slot4Octave:-1,slot5Instrument:`modal: Steel-string pluck`,slot5Octave:0,slot6Instrument:`modal: Glass harmonics`,slot6Octave:1,modalCustom:``,reverbTime:3.5,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,fade:20,plotZoom:`fit energy`,zoomSmooth:1.5,plotP:1.5,pointSize:2.5,portrait:!0,portraitCount:24,portraitCpu:.4,portraitLife:300,portraitBand:.25,portraitMinHold:3,portraitMaxPoints:8e3,portraitXfade:1.5,portraitAlpha:.15,portraitSize:1,traces:!0,traceMax:1500,traceAlpha:.75,traceSize:1.5};function _e(e){return Math.max(1,Math.min(20,Math.round(e.orbitCount)))}function ve(e){let t=[],n=[];for(let r=0;r<_e(e);r++){let i=e[`slot${r%6+1}Instrument`],a=t.indexOf(i);a<0&&(a=t.push(i)-1),n.push(a)}return{names:t,stemOf:n}}function ye(e){let{names:t}=ve(e),n=t.map(t=>F(t,e.modalCustom));return{stems:n.map((e,t)=>({kind:`synth`,sound:e,output:t})),outputs:n.map(e=>({effects:`shared`,sound:e,level:e=>e.notesLevel})),reverbTime:e.reverbTime}}function be(e){return e.duration+.5+e.finalHold+e.finalFade+.3}var V=(e,t={})=>{let n=I.find(t=>t.key===e);if(!n)throw Error(`no setting ${e} in composition 1`);return{...n,...t}},xe=[[`modal: Nylon harp`,0],[`modal: Marimba`,-1],[`modal: Vibraphone`,0],[`modal: Church bell`,-1],[`modal: Steel-string pluck`,0],[`modal: Glass harmonics`,1]],Se=[...[`duration`,`peakTime`,`holdTime`,`energyStart`].map(e=>V(e)),V(`energyPeak`,{default:.4}),...[`riseShape`,`riseCurve`,`fallCurve`,`restEnergy`,`finalHold`,`finalFade`].map(e=>V(e)),V(`speed`,{default:40}),...[`massRatio`,`lengthRatio`,`tau`,`seed`].map(e=>V(e)),{group:`orbits`,key:`orbitCount`,label:`orbits`,kind:`number`,default:8,min:1,max:20,step:1,hint:`pendulums, all following the same energy; each starts at a random place`},{group:`orbits`,key:`colors`,label:`colors`,kind:`text`,default:`#d6b37a, #7fa8cf, #c48bb8, #93bf8a, #d48f7f, #a9a6e0`,hint:`comma-separated CSS colors; orbit n uses color n (cycling)`,live:!0},...Array.from({length:6},(e,t)=>[{group:`orbits`,key:`slot${t+1}Instrument`,label:`instrument ${t+1}`,kind:`select`,default:xe[t][0],options:P,hint:`orbits ${t+1}, ${t+1+6}, ${t+1+12}, … play this instrument`},{group:`orbits`,key:`slot${t+1}Octave`,label:`octave ${t+1}`,kind:`number`,default:xe[t][1],min:-3,max:3,step:1,hint:`register shift for this instrument`}]).flat(),V(`modalCustom`,{group:`orbits`,hint:`for “modal: custom” in any slot: paste JSON from modal-synth’s Copy button`}),{group:`orbits`,key:`reverbTime`,label:`reverb time`,kind:`number`,default:3.5,min:.3,max:12,log:!0,unit:`s`,hint:`one reverb shared by all the orbit instruments (each sends its preset's reverb amount)`},V(`scale`,{default:`dorian`}),...[`root`,`pitchSource`,`thetaRange`,`pitchLow`,`pitchHigh`,`pitchCurve`,`invertPitch`,`p2Ref`,`loudCurve`,`loudFloor`,`notesLevel`,`noteLength`].map(e=>V(e)),V(`fade`,{default:20,hint:`how long each live crossing dot stays visible`}),...[`plotZoom`,`zoomSmooth`,`plotP`].map(e=>V(e)),V(`pointSize`,{default:2.5}),V(`orbits`,{key:`portrait`,group:`portrait`,label:`show portrait`,hint:`grey background: the section's structure at the current energy`}),V(`orbitCount`,{key:`portraitCount`,group:`portrait`}),V(`orbitCpu`,{key:`portraitCpu`,group:`portrait`}),V(`orbitLife`,{key:`portraitLife`,group:`portrait`}),V(`orbitBand`,{key:`portraitBand`,group:`portrait`}),V(`orbitMinHold`,{key:`portraitMinHold`,group:`portrait`}),V(`orbitMaxPoints`,{key:`portraitMaxPoints`,group:`portrait`}),V(`orbitXfade`,{key:`portraitXfade`,group:`portrait`}),V(`orbitAlpha`,{key:`portraitAlpha`,group:`portrait`,default:.15}),V(`orbitSize`,{key:`portraitSize`,group:`portrait`}),{group:`portrait`,key:`traces`,label:`trace orbits`,kind:`bool`,default:!0,hint:`with each portrait, follow every pendulum from its current state (energy frozen) and draw the orbit it's on, in its color`,live:!0},{group:`portrait`,key:`traceMax`,label:`trace length`,kind:`number`,default:1500,min:50,max:1e4,log:!0,hint:`crossings computed per orbit trace`,live:!0},{group:`portrait`,key:`traceAlpha`,label:`trace brightness`,kind:`number`,default:.75,min:.02,max:1,step:.01,live:!0},{group:`portrait`,key:`traceSize`,label:`trace point size`,kind:`number`,default:1.5,min:.5,max:4,step:.1,unit:`px`,live:!0}],Ce=50;function we(e,t){e.classList.add(`c02`);let n=document.createElement(`canvas`);e.append(n);let r=new le(n),i=0,a=!1,o=new ce(()=>i,()=>a),s=e=>({show:e.portrait,count:e.portraitCount,cpu:e.portraitCpu,life:e.portraitLife,band:e.portraitBand,minHold:e.portraitMinHold,maxPoints:e.portraitMaxPoints,xfade:e.portraitXfade,alpha:e.portraitAlpha,size:e.portraitSize,tracks:e.traces,trackMax:e.traceMax,trackAlpha:e.traceAlpha,trackSize:e.traceSize}),c=t=>{let n=String(t.colors).split(`,`).map(e=>e.trim()).filter(Boolean);return n.length?n:[R(e,`--fg`)]},l=new Float64Array(2),u=null,d=0;return{keep:e=>4.6*e.fade+.5,draw(n,f,p){let m=t();i=n,a=p,f!==u&&(u=f,o.reset());let h=_e(m);l.length!==2+5*h&&(l=new Float64Array(2+5*h));let g=f?.at(0,n,l)??null,_=m.massRatio,v=m.lengthRatio,y=performance.now();if(y-d>Ce){d=y;let e=[];if(g)for(let t=0;t<h;t++)g[2+5*t+4]>.5&&e.push({id:t,y:[g[2+5*t],g[3+5*t],g[4+5*t],g[5+5*t]]});o.post(p,s(m),g?g[0]:0,_,v,e)}let b=r.begin(m,g?g[1]:null,{m1:1,l1:1,g:1,m2:_,l2:v},z(_,v),R(e,`--dim`)),x=c(m);if(o.draw(b,n,s(m),R(e,`--fg`),e=>x[e%x.length]),f){let e=m.fade,t=m.pointSize;for(let r of f.events){let i=n-r.t;if(i<0)break;ue(b,r.th2,r.p2,i,e,t,x[r.o%x.length])}}},readouts:()=>({portrait:o.describe()}),dispose(){o.dispose(),e.classList.remove(`c02`)}}}var Te={id:`02-orbits`,schema:Se,layout:ye,estimateLength:be,view:we},Ee={id:Te.id,title:`orbits`,schema:Se,defaults:ge,create:(e,t)=>M(Te,e,t)},De={freeTime:40,dampTime:20,dampCurve:1.5,tau:2,restEnergy:.001,finalHold:2,finalFade:5,count:12,releaseAngle:120,jitter:3,separateAt:8,sepThreshold:.02,speed:2.5,massRatio:1,lengthRatio:1,seed:0,instrument:`modal: Vibraphone`,modalCustom:``,pitchMode:`chord`,directionChords:!0,scale:`dorian`,root:`D`,pitchLow:50,pitchHigh:86,loudRef:.6,loudCurve:1,loudFloor:.08,notesLevel:-8,noteLength:2,directionPan:.35,reverbTime:3.5,trails:!0,trailLength:3,trailWidth:1.2,armAlpha:.75,bobSize:3,saturation:35};function Oe(e){let t=F(e.instrument,e.modalCustom);return{stems:[{kind:`synth`,sound:t,output:0},{kind:`synth`,sound:t,output:1}],outputs:[{effects:`shared`,sound:t,level:e=>e.notesLevel,pan:e=>-e.directionPan},{effects:`shared`,sound:t,level:e=>e.notesLevel,pan:e=>e.directionPan}],reverbTime:e.reverbTime}}function ke(e){return e.freeTime+e.dampTime+1+e.finalHold+e.finalFade+.3}var H=(e,t={})=>{let n=I.find(t=>t.key===e);if(!n)throw Error(`no setting ${e} in composition 1`);return{...n,...t}},Ae=[{group:`form`,key:`freeTime`,label:`swinging`,kind:`number`,default:40,min:5,max:600,step:1,unit:`s`,hint:`free (undamped) swinging before the damping begins`},{group:`form`,key:`dampTime`,label:`damping`,kind:`number`,default:20,min:2,max:300,step:.5,unit:`s`,hint:`time for the damping to bring every pendulum to rest`},{group:`form`,key:`dampCurve`,label:`damping curve`,kind:`number`,default:1.5,min:.3,max:5,log:!0,hint:`energy follows (1 − u)^curve during the damping; >1 settles fast then lingers`},{group:`form`,key:`tau`,label:`damping follow`,kind:`number`,default:2,min:.1,max:50,log:!0,unit:`sim s`,hint:`how closely each pendulum's energy follows the damping curve`},H(`restEnergy`,{hint:`after the damping, a pendulum counts as at rest below this energy: its last note rings out`}),H(`finalHold`),H(`finalFade`),{group:`pendulums`,key:`count`,label:`pendulums`,kind:`number`,default:12,min:1,max:24,step:1},{group:`pendulums`,key:`releaseAngle`,label:`release angle`,kind:`number`,default:120,min:10,max:179,step:1,unit:`°`,hint:`both arms released from rest at this angle from straight down`},{group:`pendulums`,key:`jitter`,label:`angle variation`,kind:`number`,default:3,min:0,max:30,step:.1,unit:`°`,hint:`each play varies the release angles by up to this much (seed fixes it)`},{group:`pendulums`,key:`separateAt`,label:`separate after`,kind:`number`,default:8,min:1,max:60,step:.5,unit:`s`,hint:`the tiny offsets between pendulums are calibrated so the outermost visibly separate at about this time`},{group:`pendulums`,key:`sepThreshold`,label:`“visibly”`,kind:`number`,default:.02,min:.001,max:.5,log:!0,hint:`bob separation (fraction of the pendulum's length) that counts as separated`},{group:`pendulums`,key:`speed`,label:`speed`,kind:`number`,default:2.5,min:.25,max:20,log:!0,unit:`×`,hint:`simulated seconds per real second`},H(`massRatio`,{group:`pendulums`}),H(`lengthRatio`,{group:`pendulums`}),H(`seed`,{group:`pendulums`,hint:`0 = a different release every play`}),{group:`notes`,key:`instrument`,label:`instrument`,kind:`select`,default:`modal: Vibraphone`,options:P},H(`modalCustom`),{group:`notes`,key:`pitchMode`,label:`pitch`,kind:`select`,default:`chord`,options:[`chord`,`motion`],hint:`chord: each pendulum has its own note of a chord spread over the range. motion: pitch from the bob's speed at the crossing`},{group:`notes`,key:`directionChords`,label:`two chords`,kind:`bool`,default:!0,hint:`chord mode: left-to-right and right-to-left crossings play two interleaved chords, so the swings alternate between them`},H(`scale`,{default:`dorian`}),H(`root`),H(`pitchLow`,{default:50}),H(`pitchHigh`,{default:86}),{group:`notes`,key:`loudRef`,label:`speed for full`,kind:`number`,default:.6,min:.05,max:1,step:.01,hint:`bob speed (fraction of the fastest possible at release energy) that gives full loudness (and top pitch in motion mode)`},H(`loudCurve`),H(`loudFloor`),H(`notesLevel`,{default:-8,live:!0}),H(`noteLength`,{default:2}),{group:`notes`,key:`directionPan`,label:`pan with direction`,kind:`number`,default:.35,min:0,max:1,step:.01,hint:`a crossing is panned toward the side the bob is heading`,live:!0},{group:`notes`,key:`reverbTime`,label:`reverb time`,kind:`number`,default:3.5,min:.3,max:12,log:!0,unit:`s`},{group:`visual`,key:`trails`,label:`trails`,kind:`bool`,default:!0,live:!0},{group:`visual`,key:`trailLength`,label:`trail length`,kind:`number`,default:3,min:.2,max:20,log:!0,unit:`s`,live:!0},{group:`visual`,key:`trailWidth`,label:`trail width`,kind:`number`,default:1.2,min:.3,max:5,step:.1,unit:`px`,live:!0},{group:`visual`,key:`armAlpha`,label:`arm opacity`,kind:`number`,default:.75,min:.05,max:1,step:.01,live:!0},{group:`visual`,key:`bobSize`,label:`bob size`,kind:`number`,default:3,min:.5,max:10,step:.1,unit:`px`,live:!0},{group:`visual`,key:`saturation`,label:`color saturation`,kind:`number`,default:35,min:0,max:100,step:1,unit:`%`,live:!0}];function je(e,t){let n=Math.PI/180,r=e.releaseAngle*n,i=e.jitter*n;return t?[r+(2*t()-1)*i,r+(2*t()-1)*i]:[r,r]}var Me=1/120;function Ne(e,t){e.classList.add(`c03`);let n=document.createElement(`canvas`);e.append(n);let r=new Float64Array,i=(e,t,n)=>`hsl(${((30+360*t/Math.max(1,n))%360).toFixed(0)} ${e.saturation}% 70%)`;return{keep:e=>e.trailLength+.5,draw(a,o){let s=t(),c=L(n),l=n.clientWidth,u=n.clientHeight;c.clearRect(0,0,l,u);let d=Math.max(1,Math.round(s.count)),f=s.lengthRatio,p=.46*Math.min(l,u)/(1+f),m=l/2,h=u/2,g=(e,t)=>{let n=m+p*1*Math.sin(e),r=h+p*1*Math.cos(e);return[n,r,n+p*f*Math.sin(t),r+p*f*Math.cos(t)]};if(s.trails&&o){let e=s.trailLength;c.lineWidth=s.trailWidth,c.lineJoin=c.lineCap=`round`;for(let t=0;t<d;t++){c.strokeStyle=i(s,t,d);for(let n=0;n<6;n++){let r=a-n*e/6,i=a-(n+1)*e/6;c.globalAlpha=.7*(1-(n+.5)/6),c.beginPath();let s=!1;o.rows(0,i-Me,Math.min(a,r+Me),(e,n)=>{let[,,r,i]=g(e[n+1+2*t],e[n+2+2*t]);s?c.lineTo(r,i):(c.moveTo(r,i),s=!0)}),c.stroke()}}c.globalAlpha=1}r.length!==2*d&&(r=new Float64Array(2*d));let _=o?.at(0,a,r)??null,[v,y]=je(s,null);c.lineWidth=1.5,c.lineCap=`round`;let b=s.bobSize;for(let e=d-1;e>=0;e--){let[t,n,r,a]=_?g(_[2*e],_[2*e+1]):g(v,y),o=i(s,e,d);c.strokeStyle=o,c.fillStyle=o,c.globalAlpha=s.armAlpha,c.beginPath(),c.moveTo(m,h),c.lineTo(t,n),c.lineTo(r,a),c.stroke(),c.globalAlpha=1,c.beginPath(),c.arc(t,n,b*.8,0,2*Math.PI),c.moveTo(r+b,a),c.arc(r,a,b,0,2*Math.PI),c.fill()}c.fillStyle=R(e,`--fg`),c.beginPath(),c.arc(m,h,1.5,0,2*Math.PI),c.fill()},dispose(){e.classList.remove(`c03`)}}}var Pe={id:`03-divergence`,schema:Ae,layout:Oe,estimateLength:ke,view:Ne},Fe={id:Pe.id,title:`divergence`,schema:Ae,defaults:De,create:(e,t)=>M(Pe,e,t)},Ie={fallAfter:2.5,freeTime:60,dampTime:20,dampBase:.004,dampEnd:.2,restEnergy:.001,finalHold:2,finalFade:5,speed:1.5,tipThreshold:.02,massRatio:1,lengthRatio:1,seed:0,extInstrument:`modal: Violin`,modalCustom:``,extPitch:55,minDepth:.25,extLength:.4,firstVel:1,maxVel:.6,loudRef:.8,loudCurve:1,loudFloor:.15,notesLevel:2,maxOverlap:4,click:!0,clickInstrument:`modal: Viola`,clickPitch:72,clickLength:.5,clickMaxVel:.7,clickLevel:-8,heightNotes:!0,heightInstrument:`modal: Piano-ish`,heightLow:60,heightHigh:96,scale:`dorian`,root:`D`,heightStep:2,heightLength:.3,heightVel:.7,heightLevel:14,heightRamp:6,heightRampFrom:.5,heightFollow:.3,trails:!0,trailLength:2.5,rings:!0,motionBlur:1};function Le(e){let t=e.modalCustom,n=F(e.extInstrument,t,{voices:Math.round(e.maxOverlap)}),r=F(e.clickInstrument,t),i=F(e.heightInstrument,t);return{stems:[{kind:`synth`,sound:n,output:0},{kind:`synth`,sound:r,output:1},{kind:`synth`,sound:i,output:2}],outputs:[{effects:`own`,sound:n,level:e=>e.notesLevel},{effects:`own`,sound:r,level:e=>e.clickLevel},{effects:`own`,sound:i,level:e=>e.heightLevel}]}}function Re(e){return e.freeTime+e.dampTime+3+e.finalHold+e.finalFade+.3}var U=(e,t={})=>{let n=I.find(t=>t.key===e);if(!n)throw Error(`no setting ${e} in composition 1`);return{...n,...t}},ze=[{group:`form`,key:`fallAfter`,label:`tips after`,kind:`number`,default:2.5,min:1,max:30,step:.5,unit:`s`,hint:`the nudge from straight up is calibrated so the pendulum visibly tips at about this time`},{group:`form`,key:`freeTime`,label:`swinging`,kind:`number`,default:60,min:5,max:600,step:1,unit:`s`,hint:`time before the stronger damping begins`},{group:`form`,key:`dampTime`,label:`damping`,kind:`number`,default:20,min:2,max:300,step:.5,unit:`s`,hint:`time over which the damping grows to its final strength`},{group:`form`,key:`dampBase`,label:`slight damping`,kind:`number`,default:.004,min:0,max:.1,step:5e-4,unit:`/sim s`,hint:`friction throughout (energy loses roughly this fraction per simulated second)`},{group:`form`,key:`dampEnd`,label:`final damping`,kind:`number`,default:.2,min:.01,max:2,log:!0,unit:`/sim s`,hint:`friction reached by the end of the damping`},U(`restEnergy`,{hint:`after the damping, the pendulum counts as at rest below this energy: the last extension note rings out`}),U(`finalHold`),U(`finalFade`),{group:`pendulum`,key:`speed`,label:`speed`,kind:`number`,default:1.5,min:.25,max:20,log:!0,unit:`×`,hint:`simulated seconds per real second`},{group:`pendulum`,key:`tipThreshold`,label:`“visibly”`,kind:`number`,default:.02,min:.001,max:.5,log:!0,hint:`sideways bob movement (fraction of the length) that counts as tipping`},U(`massRatio`,{group:`pendulum`}),U(`lengthRatio`,{group:`pendulum`}),U(`seed`,{group:`pendulum`,hint:`0 = a different nudge (side and shape) every play`}),{group:`extension`,key:`extInstrument`,label:`instrument`,kind:`select`,default:`modal: Violin`,options:P},U(`modalCustom`,{group:`extension`}),{group:`extension`,key:`extPitch`,label:`pitch`,kind:`number`,default:55,min:12,max:108,step:.5,unit:`midi`},{group:`extension`,key:`extLength`,label:`length`,kind:`number`,default:.4,min:.05,max:5,log:!0,unit:`s`},{group:`extension`,key:`firstVel`,label:`first note`,kind:`number`,default:1,min:.05,max:1,step:.01,hint:`strength of the first extension note (accent)`},{group:`extension`,key:`maxVel`,label:`strongest`,kind:`number`,default:.6,min:.05,max:1,step:.01,hint:`strength of later extension notes at full speed`},{group:`extension`,key:`loudRef`,label:`speed for full`,kind:`number`,default:.8,min:.05,max:1,step:.01,hint:`bob speed (fraction of the fastest possible) that gives the strongest note`},U(`loudCurve`,{group:`extension`}),U(`loudFloor`,{group:`extension`,default:.15}),U(`notesLevel`,{group:`extension`,default:2,max:18,live:!0}),{group:`extension`,key:`maxOverlap`,label:`overlapping notes`,kind:`number`,default:4,min:1,max:16,step:1,hint:`most extension notes ringing at once (a new one replaces the quietest)`},{group:`click`,key:`minDepth`,label:`near the pivot`,kind:`number`,default:.25,min:0,max:.95,step:.01,hint:`a click when the outer bob crosses the vertical within this distance of the pivot (fraction of the length)`},{group:`click`,key:`click`,label:`click`,kind:`bool`,default:!0,hint:`a click when the outer bob passes the pivot (closer than the minimum depth)`},{group:`click`,key:`clickInstrument`,label:`instrument`,kind:`select`,default:`modal: Viola`,options:P},{group:`click`,key:`clickPitch`,label:`pitch`,kind:`number`,default:72,min:24,max:120,step:.5,unit:`midi`},{group:`click`,key:`clickLength`,label:`length`,kind:`number`,default:.5,min:.01,max:2,log:!0,unit:`s`},{group:`click`,key:`clickMaxVel`,label:`strongest`,kind:`number`,default:.7,min:.05,max:1,step:.01,hint:`strength at full bob speed (follows the speed like the extension notes)`},{group:`click`,key:`clickLevel`,label:`level`,kind:`number`,default:-8,min:-48,max:6,step:.5,unit:`dB`,live:!0},{group:`height`,key:`heightNotes`,label:`height notes`,kind:`bool`,default:!0,hint:"levels are the scale's notes between the low and high pitch (every `step`-th); passing one, up or down, plays it"},{group:`height`,key:`heightInstrument`,label:`instrument`,kind:`select`,default:`modal: Piano-ish`,options:P},{group:`height`,key:`heightLow`,label:`pitch at bottom`,kind:`number`,default:60,min:24,max:108,step:.5,unit:`midi`,hint:`bob straight down`},{group:`height`,key:`heightHigh`,label:`pitch at top`,kind:`number`,default:96,min:24,max:120,step:.5,unit:`midi`,hint:`bob straight up`},U(`scale`,{group:`height`,default:`dorian`}),U(`root`,{group:`height`}),{group:`height`,key:`heightStep`,label:`step`,kind:`number`,default:2,min:1,max:7,step:1,hint:`levels every this many scale notes (2 = arpeggio-like)`},{group:`height`,key:`heightLength`,label:`length`,kind:`number`,default:.3,min:.05,max:3,log:!0,unit:`s`},{group:`height`,key:`heightVel`,label:`strength`,kind:`number`,default:.7,min:.05,max:1,step:.01},{group:`height`,key:`heightLevel`,label:`level`,kind:`number`,default:14,min:-48,max:18,step:.5,unit:`dB`,live:!0},{group:`height`,key:`heightRamp`,label:`ramp in`,kind:`number`,default:6,min:0,max:60,step:.5,unit:`s`,hint:`the notes grow to full strength over the opening`},{group:`height`,key:`heightRampFrom`,label:`ramp from`,kind:`number`,default:.5,min:0,max:1,step:.01,hint:`starting strength, as a fraction of full`},{group:`height`,key:`heightFollow`,label:`fades with energy`,kind:`number`,default:.3,min:0,max:2,step:.05,hint:`strength × (energy / start energy)^this`},{group:`visual`,key:`trails`,label:`trail`,kind:`bool`,default:!0,live:!0},{group:`visual`,key:`trailLength`,label:`trail length`,kind:`number`,default:2.5,min:.2,max:20,log:!0,unit:`s`,live:!0},{group:`visual`,key:`rings`,label:`rings`,kind:`bool`,default:!0,hint:`a brief ring where each extension note (and, smaller, each click) happens`,live:!0},U(`motionBlur`)],Be=48,Ve=2,He=.9,Ue=.35;function We(e,t){e.classList.add(`c04`);let n=document.createElement(`canvas`);e.append(n);let r=new Float64Array(2),i=0,a=1/60;return{keep:e=>Math.max(e.trailLength,He)+.5,draw(o,s,c){let l=t(),u=performance.now()/1e3,d=u-i;i=u,d>0&&d<.1&&(a+=(d-a)*.1);let f=L(n),p=n.clientWidth,m=n.clientHeight;f.clearRect(0,0,p,m);let h=R(e,`--fg`),g=l.lengthRatio,_=.46*Math.min(p,m)/(1+g),v=p/2,y=m/2,b=(e,t)=>{let n=v+_*1*Math.sin(e),r=y+_*1*Math.cos(e);return[n,r,n+_*g*Math.sin(t),r+_*g*Math.cos(t)]},x=e=>{let t=s?.at(0,e,r);return t?[t[0],t[1]]:[Math.PI,Math.PI]};if(l.trails&&s){let e=l.trailLength;f.strokeStyle=h,f.lineWidth=1,f.lineJoin=f.lineCap=`round`;for(let t=0;t<6;t++){let n=o-t*e/6,r=o-(t+1)*e/6;f.globalAlpha=.45*(1-(t+.5)/6),f.beginPath();let i=!1,a=0;s.rows(0,r-.01,Math.min(o,n+.01),(e,t)=>{if(a++%2)return;let[,,n,r]=b(e[t+1],e[t+2]);i?f.lineTo(n,r):(f.moveTo(n,r),i=!0)}),f.stroke()}f.globalAlpha=1}if(l.rings&&s){for(let e of s.events){if(e.kind!==`ring`)continue;let t=o-e.t,n=e.click===1,r=n?Ue:He;if(t<0||t>r)continue;let i=e.strength,a=v+_*e.x,s=y+_*e.y;f.strokeStyle=h,f.globalAlpha=(1-t/r)*(.4+.6*i),f.lineWidth=n?1:1.2,f.beginPath();let c=n?14:60*(.5+i);f.arc(a,s,(n?3:6)+c*Math.sqrt(t/r),0,2*Math.PI),f.stroke()}f.globalAlpha=1}let S=c?l.motionBlur*a:0,C=1;if(S>0){let e=0,t=x(o);for(let n=1;n<=8;n++){let r=x(o-S*n/8);e+=_*(+Math.abs(r[0]-t[0])+g*Math.abs(r[1]-t[1])),t=r}C=Math.max(2,Math.min(Be,Math.ceil(e/Ve)))}let w=C===1?1:1-.03**(1/C),T=4*Math.cbrt(l.massRatio);f.strokeStyle=h,f.fillStyle=h,f.lineWidth=1.5,f.lineCap=`round`,f.globalAlpha=w;for(let e=0;e<C;e++){let[t,n]=x(o-S*e/Math.max(1,C-1)),[r,i,a,s]=b(t,n);f.beginPath(),f.moveTo(v,y),f.lineTo(r,i),f.lineTo(a,s),f.stroke(),f.beginPath(),f.arc(r,i,4,0,2*Math.PI),f.moveTo(a+T,s),f.arc(a,s,T,0,2*Math.PI),f.fill()}f.globalAlpha=1,f.beginPath(),f.arc(v,y,1.5,0,2*Math.PI),f.fill()},dispose(){e.classList.remove(`c04`)}}}var Ge={id:`04-descent`,schema:ze,layout:Le,estimateLength:Re,view:We},Ke={id:Ge.id,title:`descent`,schema:ze,defaults:Ie,create:(e,t)=>M(Ge,e,t)},qe={basePitch:73.42,sizeExp:.5,trail:.35,score:`36 25 36 25 36 25 1!4`,tempo:120,stepBeats:4,pulseAdds:.08,accent:4,tail:16,seed:0,fade:6,signal:`x2`,gain:0,spread:.7,dcCut:20,level:0,ratio1:`1`,partial1:`2`,shape1:1,ring1:20,level1:0,ratio2:`3/2`,partial2:`2`,shape2:1.3,ring2:18,level2:-6,ratio3:`2`,partial3:`3/2`,shape3:.8,ring3:16,level3:-6,ratio4:`5/2`,partial4:`2`,shape4:1.6,ring4:14,level4:-6,ratio5:`3`,partial5:`2`,shape5:.7,ring5:12,level5:-6,ratio6:`4`,partial6:`3/2`,shape6:1.2,ring6:10,level6:-6};function Je(){return{stems:[{kind:`score`,output:0}],outputs:[{effects:`none`,level:e=>e.level}]}}var Ye=.4;function Xe(e,t,n){return e.trim().split(/\s+/).filter(Boolean).map(e=>{let r=[];for(let i=0;i<e.length;i++)/[1-6]/.test(e[i])&&r.push({i:Number(e[i])-1,add:t*(e[i+1]===`!`?n:1)});return r})}var Ze=e=>e.stepBeats*60/Math.max(1,e.tempo),Qe=e=>Ye+Xe(e.score,0,1).length*Ze(e),$e=e=>Qe(e)+e.tail,W=[`x2`,`y2`,`vx2`,`vy2`,`x1`,`vx1`,`θ1`,`θ2`,`θ2−θ1`,`ω1`,`ω2`,`p1`,`p2`,`speed2`];function G(e,t){let n=1+e,r=e*t,i=e*t*t,a=1+e,o=e*t,s=n*i-r*r,c=(a*i+o*n)/s,l=a*o/s,u=Math.sqrt(Math.max(0,c*c-4*l));return[Math.sqrt((c-u)/2),Math.sqrt((c+u)/2)]}function et(e,t){let n=1e-4,r=1e4,i=e=>{let[n,r]=G(e,t);return r/n};if(i(n)>=e)return n;if(i(r)<=e)return r;for(let t=0;t<80;t++){let t=Math.sqrt(n*r);i(t)<e?n=t:r=t}return Math.sqrt(n*r)}function tt(e){let[t,n]=e.split(`/`).map(Number);return n?t/n:t}function nt(e,t,n,r,i){let a=et(n,r),[o,s]=G(a,r),c=2*Math.PI*e*t,l=o*i/c,u=l*l;return{l1:u,l2:r*u,m2:a,lower:e*t,upper:e*t*(s/o)}}function rt(e,t,n,r){let[i]=G(et(n,r),r);return 2*Math.PI*e*t/i}var it=`1.16/15.9/8.6/5.5/4.4/3.45/32.3/2.8/5.5/3.9/5.15/8.2.9/4.12/5.5/2.8/3.3.16/5.10/3.15/4.4.9/2.5.6.8`.split(`.`),at=[`5/4`,`4/3`,`3/2`,`5/3`,`2`,`5/2`,`3`,`4`,`5`,`6`,`8`],ot=[[`1`,`2`,1,20],[`3/2`,`2`,1.3,18],[`2`,`3/2`,.8,16],[`5/2`,`2`,1.6,14],[`3`,`2`,.7,12],[`4`,`3/2`,1.2,10]],st=[{group:`harmony`,key:`basePitch`,label:`base pitch`,kind:`number`,default:73.42,min:20,max:1e3,log:!0,unit:`Hz`,hint:`pitch ratio 1 sounds here (D2 by default); all pendulums share one time scale, so each pitch comes from its size`},{group:`visual`,key:`sizeExp`,label:`size drawing`,kind:`number`,default:.5,min:0,max:1,step:.05,hint:`drawn size ∝ length^this (1 = true scale: two octaves = 16× the length)`,live:!0},{group:`visual`,key:`trail`,label:`trail`,kind:`number`,default:.35,min:0,max:1,step:.01,hint:`opacity of the bobs' recent paths`,live:!0},{group:`score`,key:`score`,label:`score`,kind:`text`,default:`36 25 36 25 36 25 1!4`,hint:`one step per word: the pendulums pushed together (1–6); ! after a digit = accented; . = a rest`},{group:`score`,key:`tempo`,label:`tempo`,kind:`number`,default:120,min:10,max:400,log:!0,unit:`bpm`},{group:`score`,key:`stepBeats`,label:`step length`,kind:`number`,default:4,min:.25,max:16,step:.25,unit:`beats`,hint:`4 = a whole note per step`},{group:`score`,key:`pulseAdds`,label:`push adds`,kind:`number`,default:.08,min:5e-4,max:2,log:!0,hint:`energy each push adds, in units of E_top`},{group:`score`,key:`accent`,label:`accent`,kind:`number`,default:4,min:1,max:20,log:!0,unit:`×`,hint:`an accented push (!) adds this many times the energy`},{group:`score`,key:`tail`,label:`ring out`,kind:`number`,default:16,min:1,max:120,log:!0,unit:`s`,hint:`after the last step, before the end`},{group:`score`,key:`seed`,label:`seed`,kind:`number`,default:0,min:0,max:999999,step:1,hint:`pushes from rest go in random directions (the mix of each pendulum's two pitches); 0 = a new variation every play`},{group:`score`,key:`fade`,label:`fade`,kind:`number`,default:6,min:.1,max:60,log:!0,unit:`s`,hint:`the last part of the ring-out fades to silence`},{group:`sound`,key:`signal`,label:`signal`,kind:`select`,default:`x2`,options:[...W],hint:`what each pendulum contributes (bob position, velocity, angles…)`},{group:`sound`,key:`gain`,label:`gain`,kind:`number`,default:0,min:-40,max:30,step:.5,unit:`dB`,hint:`per pendulum, before its soft limiter`},{group:`sound`,key:`spread`,label:`stereo spread`,kind:`number`,default:.7,min:0,max:1,step:.01},{group:`sound`,key:`dcCut`,label:`low cut`,kind:`number`,default:20,min:1,max:500,log:!0,unit:`Hz`},{group:`sound`,key:`level`,label:`level`,kind:`number`,default:0,min:-48,max:12,step:.5,unit:`dB`,live:!0},...ot.flatMap(([e,t,n,r],i)=>{let a=`pendulum ${i+1}`;return[{group:a,key:`ratio${i+1}`,label:`pitch ratio`,kind:`select`,default:e,options:it,hint:`lower partial = base pitch × this (sets the size)`},{group:a,key:`partial${i+1}`,label:`partials`,kind:`select`,default:t,options:at,hint:`upper/lower partial interval (sets the mass ratio)`},{group:a,key:`shape${i+1}`,label:`l2 / l1`,kind:`number`,default:n,min:.2,max:5,log:!0,hint:`the pendulum's shape`},{group:a,key:`ring${i+1}`,label:`ring time`,kind:`number`,default:r,min:.05,max:60,log:!0,unit:`s`},{group:a,key:`level${i+1}`,label:`level`,kind:`number`,default:-6,min:-48,max:12,step:.5,unit:`dB`}]})];function K(e){let t=e.basePitch,n=Array.from({length:6},(t,n)=>({ratio:tt(e[`ratio${n+1}`]),partial:tt(e[`partial${n+1}`]),shape:e[`shape${n+1}`]})),r=n.reduce((e,t)=>t.ratio<e.ratio?t:e),i=rt(t,r.ratio,r.partial,r.shape);return{k:i,built:n.map(e=>nt(t,e.ratio,e.partial,e.shape,i))}}var ct=.012;function lt(e,t,n){let r=1.5,i=.2,a=e.reduce((e,t)=>e+r*t,0)+i*(e.length-1),o=Math.min(.92*t/a,.5*n/Math.max(...e)),s=n/2-Math.max(...e)*o/2,c=(t-a*o)/2;return{unit:o,at:e.map(e=>{let t={x:c+r/2*e*o,y:s};return c+=(r*e+i)*o,t})}}function ut(e,t){e.classList.add(`c05`);let n=document.createElement(`canvas`);e.append(n);let r=new Float64Array(24),i=``,a=K(t()).built;return{keep:()=>1.5,draw(o,s){let c=t(),l=JSON.stringify([c.basePitch,...Array.from({length:6},(e,t)=>[c[`ratio${t+1}`],c[`partial${t+1}`],c[`shape${t+1}`]])]);l!==i&&(i=l,a=K(c).built);let u=L(n),d=n.clientWidth,f=n.clientHeight;u.clearRect(0,0,d,f);let p=R(e,`--fg`),m=R(e,`--muted`),h=c.sizeExp,g=a.map(e=>e.l1+e.l2),_=g.map(e=>e**+h),{unit:v,at:y}=lt(_,d,f),b=s?.at(0,o,r)??null,x=c.trail,S=[,,,,,,].fill(-1/0);if(s)for(let e of s.events)e.kind===`push`&&e.t<=o&&(S[e.i]=e.t);u.lineCap=`round`,u.lineJoin=`round`;for(let e=0;e<6;e++){let{x:t,y:n}=y[e],r=v*_[e]/g[e];if(s&&x>0){u.strokeStyle=m,u.globalAlpha=x,u.lineWidth=1,u.beginPath();let i=!1;s.rows(1,o-ct,o,(a,o)=>{let s=t+r*a[o+1+2*e],c=n+r*a[o+2+2*e];i?u.lineTo(s,c):(u.moveTo(s,c),i=!0)}),u.stroke()}let i=a[e],c=b?b.subarray(4*e,4*e+4):[0,i.l1,0,g[e]],l=t+r*c[0],d=n+r*c[1],f=t+r*c[2],h=n+r*c[3];u.globalAlpha=.6+.4*Math.max(0,1-(o-S[e])),u.strokeStyle=p,u.fillStyle=p,u.lineWidth=1.5,u.beginPath(),u.moveTo(t,n),u.lineTo(l,d),u.lineTo(f,h),u.stroke();let C=2.2*Math.cbrt(i.m2)+1;u.beginPath(),u.arc(l,d,2,0,2*Math.PI),u.moveTo(f+C,h),u.arc(f,h,C,0,2*Math.PI),u.moveTo(t+1.5,n),u.arc(t,n,1.5,0,2*Math.PI),u.fill()}u.globalAlpha=1},readouts(){let{k:e}=K(t()),n={"time scale":`${e.toFixed(0)} sim s per s`};return a.forEach((e,t)=>{n[`pendulum ${t+1}`]=`${e.lower.toFixed(1)} + ${e.upper.toFixed(1)} Hz; l1 ${e.l1.toFixed(3)}, l2 ${e.l2.toFixed(3)}, m2/m1 ${e.m2.toFixed(2)}`}),n},dispose(){e.classList.remove(`c05`)}}}var q={id:`05-ensemble`,schema:st,layout:Je,estimateLength:$e,view:ut},dt={id:q.id,title:`ensemble`,schema:st,defaults:qe,create:(e,t)=>M(q,e,t)},ft={mode:`strike`,strikeEnergy:.3,energy:1,pitch:110,ringTime:4,restrike:5,swellTime:2,follow:3,left:`x2`,right:`x1`,gain:-6,dcCut:15,level:-12,massRatio:1,lengthRatio:1,trailMs:12},pt=new URL(`pendulumWorklet-BpTttuTz.js`,import.meta.url).href,mt=new WeakMap;function ht(e,t){let n=document.createElement(`canvas`);n.title=`click (or press S) to strike`,n.style.cursor=`pointer`,e.append(n);let i=null,a=null,o=null,s=null,c,l=!1,u=0,d=null,f=``,p=0,m=e=>({mode:e.mode,pitch:e.pitch,energy:e.energy,strikeEnergy:e.strikeEnergy,ringTime:e.ringTime,restrike:e.restrike,swellTime:e.swellTime,massRatio:e.massRatio,lengthRatio:e.lengthRatio,left:e.left,right:e.right,gain:r(e.gain),dcCut:e.dcCut,follow:e.follow}),h=e=>a?.port.postMessage(e),g=()=>h({type:`strike`});n.onclick=g;let _=e=>{let t=e.target;e.key!==`s`&&e.key!==`S`||t instanceof Element&&t.closest(`input, select, textarea`)||g()};window.addEventListener(`keydown`,_);function v(){if(!a||!i||!o)return;let e=t(),n=m(e),s=JSON.stringify(n);s!==f&&(f=s,h({type:`settings`,s:n})),o.gain.setTargetAtTime(r(e.level),i.ctx.currentTime,.05)}async function y(e){b();let t=++p;i=e;let n=e.ctx,r=mt.get(n);r||mt.set(n,r=n.audioWorklet.addModule(pt)),await r,t===p&&(o=n.createGain(),o.gain.value=0,s=n.createAnalyser(),s.fftSize=4096,s.smoothingTimeConstant=.6,a=new AudioWorkletNode(n,`pendulum-voice`,{numberOfInputs:0,outputChannelCount:[2]}),a.port.onmessage=e=>d=e.data,a.connect(o),o.connect(e.input),o.connect(s),f=``,v(),l=!0,u=n.currentTime,c=window.setInterval(v,50))}function b(){if(p++,c!==void 0&&window.clearInterval(c),c=void 0,l=!1,!i)return;let e=o,t=a,n=s;e&&e.gain.setTargetAtTime(0,i.ctx.currentTime,.03),window.setTimeout(()=>{t?.disconnect(),e?.disconnect(),n?.disconnect()},300),a=o=s=null}let x=new Float32Array(2048),S=null;function C(){let r=t(),a=L(n),o=n.clientWidth,c=n.clientHeight;a.clearRect(0,0,o,c);let u=R(e,`--fg`),f=R(e,`--dim`),p=R(e,`--muted`),m=c*.62;if(d){let e=d.trail,t=e.length/4,n=Math.min(t,Math.round(r.trailMs/(2/48e3*1e3))),i=1+r.lengthRatio,s=.46*Math.min(o,m)/i,c=o/2,l=m/2;a.lineWidth=1,a.strokeStyle=u,a.beginPath();for(let r=t-n;r<t;r++){let i=c+s*e[4*r+2],o=l+s*e[4*r+3];r===t-n?a.moveTo(i,o):a.lineTo(i,o)}a.globalAlpha=.8,a.stroke();let f=t-1;a.globalAlpha=1,a.strokeStyle=p,a.beginPath(),a.moveTo(c,l),a.lineTo(c+s*e[4*f],l+s*e[4*f+1]),a.lineTo(c+s*e[4*f+2],l+s*e[4*f+3]),a.stroke()}if(s){let e=(c-m)*.45,t=m+8;s.getFloatTimeDomainData(x),a.strokeStyle=u,a.lineWidth=1,a.beginPath();for(let n=0;n<1024;n++){let r=n/1023*o,i=t+e/2-x[n]*e/2;n?a.lineTo(r,i):a.moveTo(r,i)}a.stroke(),S&&S.length===s.frequencyBinCount||(S=new Float32Array(s.frequencyBinCount)),s.getFloatFrequencyData(S);let n=(c-m)*.45,r=c-4,l=i.ctx.sampleRate,d=e=>Math.log(e/20)/Math.log(1e3)*o;a.strokeStyle=f,a.beginPath();for(let e of[100,1e3,1e4])a.moveTo(d(e),r-n),a.lineTo(d(e),r);a.stroke(),a.strokeStyle=u,a.beginPath();let p=!1;for(let e=1;e<S.length;e++){let t=e*l/(2*S.length);if(t<20||t>2e4)continue;let i=Math.max(0,Math.min(1,(S[e]+110)/100)),o=d(t),s=r-i*n;p?a.lineTo(o,s):(a.moveTo(o,s),p=!0)}a.stroke()}l||(a.fillStyle=p,a.font=`12px ui-monospace, monospace`,a.fillText(`play, then click here (or press S) to strike`,8,16))}function w(){return{mode:l&&d?d.phase:`–`,energy:d?d.energy.toFixed(4):`–`,"time scale":d?`${d.k.toFixed(0)} sim s per s`:`–`,strike:`click the plot or press S`}}return{get playing(){return l},start:e=>y(e),stop:b,draw:C,now:()=>l&&i?i.ctx.currentTime-u:0,length:()=>1/0,readouts:w,dispose(){b(),window.removeEventListener(`keydown`,_),e.replaceChildren()}}}var gt={id:`lab`,title:`lab: the pendulum as instrument`,hidden:!0,schema:[{group:`play`,key:`mode`,label:`mode`,kind:`select`,default:`strike`,options:[`strike`,`sustain`,`swell`],hint:`strike: start at the energy and ring down; sustain: energy held (like bowing); swell: energy rises, then rings down`},{group:`play`,key:`strikeEnergy`,label:`strike adds`,kind:`number`,default:.3,min:5e-4,max:5,log:!0,hint:`energy each strike adds to the current motion (units of E_top, both arms up)`},{group:`play`,key:`energy`,label:`energy`,kind:`number`,default:1,min:.001,max:5,log:!0,hint:`sustain level and swell target (units of E_top). Low: nearly periodic, two inharmonic modes. ~0.3–1.5: chaos. High: regular again (rotations)`},{group:`play`,key:`pitch`,label:`pitch`,kind:`number`,default:110,min:5,max:2e3,log:!0,unit:`Hz`,hint:`the lower small-swing mode lands here (time scaling)`},{group:`play`,key:`ringTime`,label:`ring time`,kind:`number`,default:4,min:.05,max:60,log:!0,unit:`s`,hint:`damping: amplitude falls 60 dB in this time (strike and swell)`},{group:`play`,key:`restrike`,label:`restrike every`,kind:`number`,default:5,min:0,max:60,step:.1,unit:`s`,hint:`0 = strike once`},{group:`play`,key:`swellTime`,label:`swell time`,kind:`number`,default:2,min:.05,max:30,log:!0,unit:`s`},{group:`play`,key:`follow`,label:`energy follow`,kind:`number`,default:3,min:.2,max:200,log:!0,unit:`periods`,hint:`sustain/swell: how quickly the energy controller corrects`},{group:`sound`,key:`left`,label:`left signal`,kind:`select`,default:`x2`,options:[...W],hint:`x/y: bob position, v: velocity, θ: angles, ω: angular velocities, p: momenta`},{group:`sound`,key:`right`,label:`right signal`,kind:`select`,default:`x1`,options:[...W]},{group:`sound`,key:`gain`,label:`gain`,kind:`number`,default:-6,min:-40,max:30,step:.5,unit:`dB`,hint:`before a soft limiter (high gain = saturated)`},{group:`sound`,key:`dcCut`,label:`low cut`,kind:`number`,default:15,min:1,max:500,log:!0,unit:`Hz`,hint:`removes constant offsets and very slow drift`},{group:`sound`,key:`level`,label:`level`,kind:`number`,default:-12,min:-48,max:6,step:.5,unit:`dB`},{group:`pendulum`,key:`massRatio`,label:`m2 / m1`,kind:`number`,default:1,min:.05,max:20,log:!0},{group:`pendulum`,key:`lengthRatio`,label:`l2 / l1`,kind:`number`,default:1,min:.05,max:20,log:!0},{group:`visual`,key:`trailMs`,label:`path length`,kind:`number`,default:12,min:1,max:16,step:.5,unit:`ms`,hint:`how much of the bob's recent path to draw`}],defaults:ft,create:ht},J=`double pendulum`,Y=[he,Ee,Fe,Ke,dt,gt],X=document.getElementById(`app`),Z=null;function Q(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n),r}var $={"04-crash":`04-descent`,ensemble:`05-ensemble`};for(let[e,t]of Object.entries($))try{let n=localStorage.getItem(`double-pendulum:author:${e}`);n!==null&&localStorage.getItem(`double-pendulum:author:${t}`)===null&&localStorage.setItem(`double-pendulum:author:${t}`,n),localStorage.removeItem(`double-pendulum:author:${e}`)}catch{}function _t(){Z?.(),Z=null,X.replaceChildren();let e=location.hash.replace(/^#\/?/,``).split(`/`).filter(Boolean);if(e[0]&&$[e[0]]){location.replace(`#/${[$[e[0]],...e.slice(1)].join(`/`)}`);return}let t=Y.find(t=>t.id===e[0]);if(!t)return vt();Z=St(t,e[1]===`edit`)}function vt(){document.title=J;let e=Q(`ol`,{className:`tracks`});for(let t of Y)t.hidden||e.append(Q(`li`,{},Q(`a`,{href:`#/${t.id}`,textContent:t.title})));X.append(Q(`main`,{className:`album`},Q(`h1`,{textContent:J}),e))}var yt=e=>`double-pendulum:author:${e.id}`;function bt(e){try{let t=localStorage.getItem(yt(e));return t?JSON.parse(t):null}catch{return null}}function xt(e,t){try{localStorage.setItem(yt(e),JSON.stringify(t))}catch{}}function St(e,t){let r=Y.filter(e=>!e.hidden).indexOf(e)+1;document.title=`${e.title} · ${J}`;let i=()=>a(e.schema,e.defaults),o=t?a(e.schema,e.defaults,bt(e)):i(),s=Q(`div`,{className:`view`}),c=Q(`button`,{className:`big-play`,textContent:`▶`,title:`play`});c.setAttribute(`aria-label`,`play`);let l=Q(`button`,{className:`play`,textContent:`play`}),u=Q(`div`,{className:`bar`}),d=Q(`div`,{className:`progress`},u),p=Q(`a`,{className:`edit`,href:t?`#/${e.id}`:`#/${e.id}/edit`,textContent:t?`done`:`edit`}),m=Q(`header`,{},Q(`a`,{href:`#/`,textContent:J}),Q(`span`,{className:`sep`,textContent:` / `}),Q(`span`,{textContent:e.hidden?e.title:`${r}. ${e.title}`})),h=Q(`div`,{className:`notice`}),g=Q(`div`,{className:`buffering`,hidden:!0},Q(`div`,{className:`spinner`}),Q(`div`,{className:`fill`})),_=Q(`main`,{className:`stage`},m,h,s,Q(`div`,{className:`transport`},l,d,p)),v=Q(`div`,{className:t?`page with-author`:`page`},_);X.append(v);let y=e.create(s,()=>o);s.append(c,g);let b=()=>{let e=Math.floor(Math.min(s.clientWidth,s.clientHeight));for(let t of s.querySelectorAll(`canvas`))t.style.width=`${e}px`,t.style.height=`${e}px`},x=new ResizeObserver(b);x.observe(s),b();let S={value:0},C=!1,w=0,T=async e=>{let t=++w;C=!0;try{let r=await n();if(t!==w)return;await y.start(r,e),t!==w&&y.stop()}finally{t===w&&(C=!1)}},ee=()=>{w++,C=!1,y.stop()},E=()=>y.playing||C;l.onclick=()=>E()?ee():T(t?S.value:0),c.onclick=()=>l.click(),t&&(d.classList.add(`seekable`),d.onclick=e=>{let t=d.getBoundingClientRect(),n=Math.max(0,(e.clientX-t.left)/t.width*y.length());y.playing&&y.seek?y.seek(n):T(n)});let D=null;t&&(D=f({schema:e.schema,get:()=>o,set:t=>{o=t,xt(e,t)},defaults:i,readouts:()=>y.readouts(),startAt:S}),v.append(D.el));let O=e=>{let t=e.target.tagName;e.code===`Space`&&t!==`INPUT`&&t!==`SELECT`&&t!==`BUTTON`&&(e.preventDefault(),l.click())};window.addEventListener(`keydown`,O);let k=0,A=0,j=e=>{y.draw(),l.textContent=E()?`stop`:`play`,c.hidden=E();let t=y.playing?y.status?.():void 0,n=!!t?.buffering||C;g.hidden=!n,n&&(g.lastChild.textContent=`${Math.round(100*(t?.fill??0))}%`);let r=y.notice?.()??``;h.textContent!==r&&(h.textContent=r),u.style.width=`${Math.min(100,100*y.now()/y.length())}%`,D&&e-A>200&&(D.updateReadouts(),A=e),k=requestAnimationFrame(j)};return k=requestAnimationFrame(j),()=>{cancelAnimationFrame(k),window.removeEventListener(`keydown`,O),x.disconnect(),y.dispose()}}window.addEventListener(`hashchange`,_t),_t();
site/assets/index-D9r0IF3O.jsdeleted+0−2View file
@@ -1,2 +0,0 @@
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=48e3,t=null;async function n(){if(!t){let n;try{n=new AudioContext({latencyHint:`playback`,sampleRate:e})}catch{n=new AudioContext({latencyHint:`playback`})}let r=n.createGain(),i=n.createDynamicsCompressor();i.threshold.value=-6,i.knee.value=6,i.ratio.value=12,i.attack.value=.003,i.release.value=.25,r.connect(i).connect(n.destination),t={ctx:n,input:r}}return t.ctx.state!==`running`&&await t.ctx.resume(),t}function r(e){return 10**(e/20)}function i(e){let t={};for(let n of e)t[n.key]=n.default;return t}function a(e,...t){let n=i(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 o(e,t){let n={};for(let r of e)n[r.key]=t[r.key];return JSON.stringify(n,null,2)+`
2-`}var s=1e3;function c(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))*s)}function l(e,t){let n=t/s,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 u(e){return String(Number(e.toPrecision(4)))}function d(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n),r}function f(e){let t=d(`aside`,{className:`author`}),n=[],r=(t,n)=>{e.set({...e.get(),[t]:n})},i=d(`span`,{className:`status`}),f=e=>{i.textContent=e,window.setTimeout(()=>{i.textContent===e&&(i.textContent=``)},2e3)},p=d(`button`,{textContent:`copy config`});p.onclick=async()=>{let t=o(e.schema,e.get());try{await navigator.clipboard.writeText(t),f(`copied`)}catch{window.prompt(`copy:`,t)}};let m=d(`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(a(e.schema,JSON.parse(t))),y(),f(`pasted`)}catch{f(`not valid JSON`)}};let h=d(`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(d(`div`,{className:`actions`},p,m,h,i));let g=d(`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(d(`label`,{className:`row`},d(`span`,{textContent:`start at (s)`}),g));let _=d(`dl`,{className:`readouts`});t.append(_);let v=new Map;for(let i of e.schema){let a=v.get(i.group);a||(a=d(`fieldset`,{},d(`legend`,{textContent:i.group})),v.set(i.group,a),t.append(a));let o=d(`label`,{className:`row`},d(`span`,{textContent:i.label,title:i.hint??``}));if(i.kind===`number`){let t=d(`input`,{type:`range`,min:`0`,max:String(s),step:`1`}),a=d(`input`,{type:`number`,step:`any`}),f=d(`span`,{className:`unit`,textContent:i.unit??``});t.oninput=()=>{let e=l(i,Number(t.value));a.value=u(e),r(i.key,e)},a.onchange=()=>{let e=Number(a.value);Number.isFinite(e)&&(t.value=String(c(i,e)),r(i.key,e))},n.push(()=>{let n=e.get()[i.key];t.value=String(c(i,n)),a.value=u(n)}),o.append(t,a,f)}else if(i.kind===`select`){let t=d(`select`);for(let e of i.options)t.append(d(`option`,{value:e,textContent:e}));t.onchange=()=>r(i.key,t.value),n.push(()=>t.value=e.get()[i.key]),o.append(t)}else if(i.kind===`text`){let t=d(`textarea`,{rows:3,spellcheck:!1,placeholder:i.hint??``});t.onchange=()=>r(i.key,t.value),n.push(()=>t.value=e.get()[i.key]),o.classList.add(`text`),o.append(t)}else{let t=d(`input`,{type:`checkbox`});t.onchange=()=>r(i.key,t.checked),n.push(()=>t.checked=e.get()[i.key]),o.append(t)}a.append(o)}function y(){for(let e of n)e()}function b(){let t=e.readouts();_.replaceChildren(...Object.entries(t).flatMap(([e,t])=>[d(`dt`,{textContent:e}),d(`dd`,{textContent:t})]))}return y(),b(),{el:t,sync:y,updateReadouts:b}}function p(){return 1+Math.floor(Math.random()*999999)}var m=(e,t)=>e[t],h=e=>e.geometry===`membrane`||e.geometry===`plate`||e.geometry===`disc`,g=(...e)=>t=>e.includes(t.geometry),_=(...e)=>t=>e.includes(t.exciter),v=[`bow`,`reed`,`selfosc`,`noise`],y=[[`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`]],b=[[`sine`,`Sine`],[`tri`,`Triangle`],[`saw`,`Saw`],[`square`,`Square`],[`sh`,`Sample & hold`],[`smooth`,`Smooth random`]];function x(e){let t=t=>t[`lfo${e}Target`]!==`off`;return[{kind:`enum`,id:`lfo${e}Target`,label:`LFO ${e} →`,group:`Modulation`,options:y,def:`off`},{kind:`enum`,id:`lfo${e}Shape`,label:`Shape`,group:`Modulation`,options:b,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 S=[{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:g(`plate`)},{kind:`num`,id:`powerExp`,label:`Exponent p`,group:`Body`,min:.3,max:3,def:1.5,model:!0,show:g(`free`)},{kind:`num`,id:`discExp`,label:`Chladni exponent`,group:`Body`,min:1,max:2.5,def:2,model:!0,show:g(`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&&h(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:h},{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:_(`strike`)},{kind:`num`,id:`hardness`,label:`Contact time`,group:`Exciter`,min:.05,max:20,def:1,scale:`log`,unit:`ms`,show:_(`strike`,`impulse`)},{kind:`num`,id:`feltExp`,label:`Felt exponent`,group:`Exciter`,min:1,max:4,def:2.5,show:_(`strike`)},{kind:`num`,id:`bowForce`,label:`Bow force`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:_(`bow`)},{kind:`num`,id:`bowSpeed`,label:`Bow speed`,group:`Exciter`,min:0,max:2,def:.4,scale:`pow2`,show:_(`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:_(`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:_(`reed`)},{kind:`num`,id:`reedGain`,label:`Reed opening`,group:`Exciter`,min:0,max:2,def:.5,show:_(`reed`)},{kind:`num`,id:`breath`,label:`Breath noise`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`,show:_(`reed`)},{kind:`num`,id:`selfGain`,label:`Negative damping`,group:`Exciter`,min:0,max:4,def:.5,scale:`pow2`,show:_(`selfosc`)},{kind:`num`,id:`selfSat`,label:`Saturation level`,group:`Exciter`,min:.02,max:4,def:.5,scale:`log`,show:_(`selfosc`)},{kind:`num`,id:`noiseLevel`,label:`Noise level`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:_(`noise`)},{kind:`num`,id:`noiseColor`,label:`Noise cutoff`,group:`Exciter`,min:50,max:16e3,def:3e3,scale:`log`,unit:`Hz`,show:_(`noise`,`reed`,`bow`)},{kind:`num`,id:`attack`,label:`Attack`,group:`Exciter`,min:1,max:3e3,def:40,scale:`log`,unit:`ms`,show:_(...v)},{kind:`num`,id:`release`,label:`Release`,group:`Exciter`,min:5,max:5e3,def:150,scale:`log`,unit:`ms`,show:_(...v)},{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},...x(1),...x(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:h},{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(S.map(e=>[e.id,e]));var C=Object.fromEntries(S.map(e=>[e.id,e.def]));S.filter(e=>e.model).map(e=>e.id);var w=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=m(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=m(e,`delayMix`);n(this.delaySend.gain,i);let a=m(e,`delayTime`)/1e3;n(this.dL.delayTime,a),n(this.dR.delayTime,a),n(this.fbL.gain,m(e,`delayFb`)),n(this.fbR.gain,m(e,`delayFb`));let o=m(e,`reverbMix`);n(this.revSend.gain,o),n(this.dry.gain,r>0?1/(1+2*r):1),n(this.master.gain,10**(m(e,`volume`)/20));let s=m(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}};function T(e,t,n,r,i){if(!r){t.connect(n);return}if(i===`own`){let i=new w(e,n);t.connect(i.input),i.set(r);return}let a=e.createGain();if(a.gain.value=10**(r.volume/20),t.connect(a).connect(n),i!==`none`){let n=e.createGain();n.gain.value=r.reverbMix*a.gain.value,t.connect(n).connect(i.send)}}var E=class{input;conv;constructor(e,t,n){this.input=e.createGain(),this.conv=e.createConvolver(),this.conv.buffer=D(e,n),this.input.connect(this.conv).connect(t)}dispose(){this.input.disconnect(),this.conv.disconnect()}};function D(e,t){let n=e.sampleRate,r=Math.round(n*Math.min(t*1.1,12)),i=e.createBuffer(2,r,n);for(let e=0;e<2;e++){let a=i.getChannelData(e),o=0;for(let e=0;e<r;e++){let r=e/n,i=9e3*Math.exp(-r/(.6*t))+400,s=1-Math.exp(-2*Math.PI*i/n);o+=s*(Math.random()*2-1-o),a[e]=o*Math.exp(-6.9*r/t)*Math.min(1,r/.004)*.5}}return i}var O=class{tracks=new Map;events=[];infos=[];add(e,t,n){if(!n.length)return;let r=this.tracks.get(e);r||this.tracks.set(e,r=[]),r.push({t0:n[0],t1:n[n.length-t],stride:t,data:n})}addEvents(e){for(let t of e)this.events.push(t)}addInfo(e,t){this.infos.push({t:e,info:t})}info(e){let t={};for(let n of this.infos)n.t<=e&&(t=n.info);return t}trim(e){for(let t of this.tracks.values())for(;t.length>1&&t[1].t0<=e&&t[0].t1<e;)t.shift();let t=0;for(;t<this.events.length&&this.events[t].t<e;)t++;for(t>0&&this.events.splice(0,t);this.infos.length>1&&this.infos[1].t<=e;)this.infos.shift()}last(e){let t=this.tracks.get(e);return t?.length?t[t.length-1].t1:-1/0}at(e,t,n){let r=this.tracks.get(e);if(!r?.length)return null;let i=r.length-1;for(;i>0&&r[i].t0>t;)i--;let a=r[i],o=a.stride,s=a.data.length/o,c=a.data,l=0,u=s-1;if(t<=c[0])u=0;else if(t>=c[(s-1)*o])l=u=s-1;else for(;u-l>1;){let e=l+u>>1;c[e*o]<=t?l=e:u=e}let d=l*o,f=u*o,p=c,m=c;l===u&&l===s-1&&i+1<r.length&&t>c[d]&&(m=r[i+1].data,f=0);let h=p[d],g=m[f],_=g>h?Math.min(1,Math.max(0,(t-h)/(g-h))):0;for(let e=1;e<o;e++)n[e-1]=p[d+e]+_*(m[f+e]-p[d+e]);return n}rows(e,t,n,r){let i=this.tracks.get(e);if(i)for(let e of i){if(e.t1<t)continue;if(e.t0>n)break;let i=e.stride,a=e.data;for(let e=0;e<a.length;e+=i){let i=a[e];if(!(i<t)){if(i>n)break;r(a,e)}}}}},k=new URL(`player-CFiFcj0f.js`,import.meta.url).href,ee=4,te=new WeakMap,ne=class{store=new O;start;seed;state=`loading`;endT=null;error=null;fill=0;rebuffers=0;ahead=0;ready;ctx;layout;workers=[];node=null;master;levels=[];pans=[];reverb=null;status=null;disposed=!1;estimatedEnd;constructor(e,t,n,r,i,a,o,s){this.ctx=e,this.start=a,this.seed=i,this.layout=o,this.estimatedEnd=s,this.master=e.createGain(),this.master.connect(t),this.ready=this.open(n,r)}async open(t,n){let r=this.ctx,i=te.get(r);if(i||te.set(r,i=r.audioWorklet.addModule(k)),await i,this.disposed)return;let{stems:a,outputs:o}=this.layout,s={stems:a.length,outputs:o.length,route:a.map(e=>e.output),startFrame:Math.round(this.start*e),estimatedEnd:Math.round(this.estimatedEnd*e)},c=new AudioWorkletNode(r,`stream-player`,{numberOfInputs:0,numberOfOutputs:o.length,outputChannelCount:o.map(()=>2),processorOptions:s});this.node=c,o.some(e=>e.effects===`shared`)&&(this.reverb=new E(r,this.master,this.layout.reverbTime??3)),o.forEach((e,t)=>{let i=r.createGain();i.gain.value=10**(e.level(n)/20),c.connect(i,t);let a=i,o=null;e.pan&&(o=r.createStereoPanner(),o.pan.value=e.pan(n),i.connect(o),a=o),T(r,a,this.master,e.sound,e.effects===`shared`?{send:this.reverb.input}:e.effects),this.levels.push(i),this.pans.push(o)}),c.port.onmessage=e=>this.onStatus(e.data);let l=Math.max(0,this.start-ee),u=[],d=[];a.forEach((t,n)=>{if(t.kind!==`synth`){d.push(null);return}let r=new Worker(new URL(new URL(`synthWorker-ByLtHWda.js`,import.meta.url).href,``+import.meta.url),{type:`module`});this.workers.push(r);let i=new MessageChannel,a=new MessageChannel;d.push(i.port1),u.push(a.port2);let o={type:`init`,sound:t.sound??{},fromFrame:Math.floor(l*e/128)*128,sendFrame:Math.round(this.start*e),stem:n,scorePort:i.port2,playerPort:a.port1,slow:Number(new URLSearchParams(location.search).get(`slow`))||void 0};r.postMessage(o,[i.port2,a.port1]),r.onerror=e=>this.fail(`instrument: ${e.message}`)});let f=new Worker(new URL(new URL(`scoreWorker-B3-6tjqi.js`,import.meta.url).href,``+import.meta.url),{type:`module`});this.workers.push(f);let p=new MessageChannel;u.push(p.port2),f.onmessage=e=>this.onScore(e.data),f.onerror=e=>this.fail(`score: ${e.message}`);let m={type:`init`,comp:t,P:n,seed:this.seed,start:this.start,from:l,synthPorts:d,playerPort:p.port1};f.postMessage(m,[...d.filter(e=>!!e),p.port1]),c.port.postMessage({type:`ports`,ports:u},u),this.state=`buffering`}onScore(e){e.type===`frames`?this.store.add(e.track,e.stride,e.data):e.type===`events`?this.store.addEvents(e.events):e.type===`info`?this.store.addInfo(e.t,e.info):e.type===`end`?this.endT=e.t:e.type===`error`&&this.fail(e.message)}onStatus(e){this.status=e,this.state!==`error`&&(this.state=e.state,this.fill=e.fill,this.rebuffers=e.rebuffers,this.ahead=e.ahead)}fail(e){this.state=`error`,this.error=e,console.error(e)}time(){let t=this.status;if(!t)return this.start;let n=t.playhead;t.state===`playing`&&(n+=Math.min(4096,Math.max(0,this.ctx.currentTime*e-t.at)));let r=(this.ctx.outputLatency||0)+(this.ctx.baseLatency||0);return Math.max(this.start,n/e-r)}update(e){let t=this.ctx.currentTime;this.layout.outputs.forEach((n,r)=>{this.levels[r]?.gain.setTargetAtTime(10**(n.level(e)/20),t,.05),n.pan&&this.pans[r]?.pan.setTargetAtTime(n.pan(e),t,.05)})}dispose(){if(this.disposed)return;this.disposed=!0;for(let e of this.workers)e.terminate();let e=this.ctx.currentTime,t=this.master,n=this.node,r=this.reverb;t.gain.setTargetAtTime(0,e,.02),window.setTimeout(()=>{n?.disconnect(),n?.port.close(),r?.dispose(),t.disconnect()},200)}},re=400;function A(e,t,n){let r=e.view(t,n),i=e.schema.filter(e=>!e.live).map(e=>e.key),a=e=>JSON.stringify(i.map(t=>e[t])),o=null,s=null,c=``,l=null,u=0,d=null,f=0,m=0,h=null,g=window.setInterval(()=>l?.trim(y.now()-r.keep(n())),1e3);function _(t,r,i){let u=n();s?.dispose(),o=t,i&&f||(f=u.seed>0?Math.round(u.seed):p()),s=new ne(t.ctx,t.input,e.id,u,f,Math.max(0,r),e.layout(u),e.estimateLength(u)),c=a(u),l=s.store,d=null,h=null,m=0}function v(){s&&=(u=s.time(),s.endT!==null&&(d=s.endT),s.dispose(),null)}let y={get playing(){return s!==null},async start(e,t){_(e,t,!1),await s.ready},stop:v,seek(e){o&&_(o,e,!0)},draw(){let e=n();if(s){if(s.state===`error`)h=`something went wrong computing this piece; try play again`,v();else if(s.state===`ended`){let e=s.endT??s.time();v(),u=e,y.onEnded?.()}else if(s.update(e),a(e)!==c){let e=performance.now();m?e>=m&&o&&_(o,s.time(),!0):m=e+re}else m=0}let t=y.now();l?.trim(t-r.keep(e)),r.draw(t,l,s?.state===`playing`)},now:()=>s?s.time():u,length:()=>s?.endT??d??e.estimateLength(n()),status:()=>({buffering:s!==null&&(s.state===`loading`||s.state===`buffering`),fill:s?.fill??0}),notice:()=>h,readouts(){let e=y.now();return{time:`${e.toFixed(1)} / ${y.length().toFixed(1)} s`,buffer:s?`${s.state}, ${s.ahead.toFixed(1)} s ahead, ${s.rebuffers} pause${s.rebuffers===1?``:`s`}`:`–`,"seed used":f?String(f):`–`,...l?.info(e)??{},...r.readouts?.(e,l)??{}}},dispose(){v(),window.clearInterval(g),r.dispose?.(),t.replaceChildren()}};return y}var ie={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,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},j={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},M=[{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:{...j,modes:128,inharm:4e-5,exPos:.09,vibDepth:16,vibRate:5.2,soundbox:`cello`}},{name:`Violin`,category:`Instrument`,note:67,p:{...j,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:{...j,modes:96,inharm:3e-5,exPos:.1,vibDepth:15,vibRate:5.5,soundbox:`viola`}},{name:`Double bass`,category:`Instrument`,note:36,p:{...j,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:{...j,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 ae(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 oe=[`bow`,`reed`,`selfosc`,`noise`],N=[...M.map(e=>`modal: ${e.name}`),`modal: custom`],se=[...M.filter(e=>{let t={...C,...e.p};return oe.includes(t.exciter)||t.fbGain>0}).map(e=>`modal: ${e.name}`),`modal: custom`];function P(e,t,n={}){let r=e===`modal: custom`?ae(t):M.find(t=>`modal: ${t.name}`===e)?.p;return{...C,...r??{},...n}}var F=[`bowForce`,`bowSpeed`,`bowNoise`,`exPos`,`reedPressure`,`reedGain`,`breath`,`selfGain`,`selfSat`,`noiseLevel`,`noiseColor`,`tension`,`cascade`,`curvature`,`fbGain`,`fbFreq`,`fbQ`,`fbSat`,`hfDamp`,`t60`,`pickup`,`tilt`,`vibDepth`];function ce(e){let t=P(e.noteInstrument,e.modalCustom),n=P(e.humInstrument,e.humCustom,{voices:1});return{stems:[{kind:`synth`,sound:t,output:0},{kind:`synth`,sound:n,output:1}],outputs:[{effects:`own`,sound:t,level:e=>e.notesLevel},{effects:`own`,sound:n,level:e=>e.humLevel}]}}function le(e){return e.duration+.5+e.finalHold+e.finalFade+.3}var I=[{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:`modal: Nylon harp`,options:N,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:Object.keys({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})},{group:`notes`,key:`root`,label:`root`,kind:`select`,default:`D`,options:[`C`,`C#`,`D`,`D#`,`E`,`F`,`F#`,`G`,`G#`,`A`,`A#`,`B`]},{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`,live:!0},{group:`notes`,key:`noteLength`,label:`length`,kind:`number`,default:1.5,min:.05,max:10,log:!0,unit:`s`},{group:`hum`,key:`humInstrument`,label:`instrument`,kind:`select`,default:`modal: Clarinet-ish`,options: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`,live:!0},{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`,...F],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`,...F]},{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`,live:!0},{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)`,live:!0},{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`,live:!0},{group:`visual`,key:`fade`,label:`point fade`,kind:`number`,default:10,min:.2,max:120,log:!0,unit:`s`,live:!0},{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`,live:!0},{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`,live:!0},{group:`visual`,key:`plotP`,label:`fixed p2 range`,kind:`number`,default:1.5,min:.05,max:5,log:!0,live:!0},{group:`visual`,key:`pointSize`,label:`point size`,kind:`number`,default:2,min:.5,max:8,step:.1,unit:`px`,live:!0},{group:`orbits`,key:`orbits`,label:`show orbits`,kind:`bool`,default:!0,live:!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`,live:!0},{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`,live:!0},{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`,live:!0},{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`,live:!0},{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`,live:!0},{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`,live:!0},{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`,live:!0},{group:`orbits`,key:`orbitAlpha`,label:`brightness`,kind:`number`,default:.3,min:.02,max:1,step:.01,live:!0},{group:`orbits`,key:`orbitSize`,label:`point size`,kind:`number`,default:1,min:.5,max:4,step:.1,unit:`px`,live:!0}],ue=100,de=class{worker=null;portraits=[];resetPending=!1;latestGen=0;ignoreBelow=0;rate=0;newPts=0;rateT=0;now;live;constructor(e,t){this.now=e,this.live=t}reset(){this.dirty=!0,this.portraits=[],this.ignoreBelow=this.latestGen+1,this.resetPending=!0}ensureWorker(){return this.worker||(this.worker=new Worker(new URL(new URL(`orbitWorker-CV_Zv_V1.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),this.worker.onmessage=e=>this.receive(e.data)),this.worker}receive({gen:e,energy:t,pts:n,tracks:r}){if(!this.live()||(this.latestGen=Math.max(this.latestGen,e),e<this.ignoreBelow))return;let i=this.portraits[this.portraits.length-1];if(!i||e>i.gen){let n=this.now();for(let e of this.portraits)e.retiredAt??=n;i={gen:e,energy:t,pts:[],tracks:new Map,retiredAt:null},this.portraits.push(i)}else if(e<i.gen)return;for(let e=0;e<n.length;e++)i.pts.push(n[e]);for(let e of r){let t=i.tracks.get(e.id);t||i.tracks.set(e.id,t=[]);for(let n=0;n<e.pts.length;n++)t.push(e.pts[n])}this.newPts+=n.length/2+r.reduce((e,t)=>e+t.pts.length/2,0),this.dirty=!0}post(e,t,n,r,i,a){if(!t.show&&!t.tracks&&!this.worker)return;let o={running:e&&(t.show||t.tracks),reset:this.resetPending,energy:n,m2:r,l2:i,count:t.show?Math.round(t.count):0,life:t.life,band:t.band,minHold:t.minHold,maxPoints:t.show?t.maxPoints:0,cpu:t.cpu,tracks:t.tracks?a:[],trackMax:t.trackMax};this.resetPending=!1,this.ensureWorker().postMessage(o)}layer=null;layerAt=0;layerKey=``;dirty=!0;lm={cx:0,kx:1,cy:0,ky:1};draw(e,t,n,r,i){let{g:a,w:o,h:s,sx:c,sy:l}=e,u=this.portraits.length;this.portraits=this.portraits.filter(e=>e.retiredAt===null||t-e.retiredAt<n.xfade),this.portraits.length!==u&&(this.dirty=!0);let d=this.portraits.some(e=>e.retiredAt!==null),f=window.devicePixelRatio||1,p=[o,s,f,n.show,n.tracks,n.alpha,n.size,n.trackAlpha,n.trackSize,r].join(`|`),m={cx:c(0),kx:c(1)-c(0),cy:l(0),ky:l(1)-l(0)},h=m.kx/this.lm.kx,g=m.ky/this.lm.ky,_=Math.abs(Math.log(h))>.05||Math.abs(Math.log(g))>.05,v=performance.now();this.layer||=document.createElement(`canvas`);let y=this.layer;if((this.dirty||d||_||p!==this.layerKey)&&v-this.layerAt>=ue){let e=Math.round(o*f),a=Math.round(s*f);(y.width!==e||y.height!==a)&&(y.width=e,y.height=a);let u=y.getContext(`2d`);u.setTransform(f,0,0,f,0,0),u.clearRect(0,0,o,s);for(let e of this.portraits){let a=e.retiredAt===null?1:Math.max(0,1-(t-e.retiredAt)/n.xfade);if(n.show&&e.pts.length){let t=n.size;u.fillStyle=r,u.globalAlpha=n.alpha*a,u.beginPath();let i=e.pts;for(let e=0;e<i.length;e+=2)u.rect(c(i[e])-t/2,l(i[e+1])-t/2,t,t);u.fill()}if(n.tracks){let t=n.trackSize;for(let[r,o]of e.tracks){u.fillStyle=i(r),u.globalAlpha=n.trackAlpha*a,u.beginPath();for(let e=0;e<o.length;e+=2)u.rect(c(o[e])-t/2,l(o[e+1])-t/2,t,t);u.fill()}}}u.globalAlpha=1,this.layerAt=v,this.layerKey=p,this.lm=m,this.dirty=!1}if(y.width){let e=m.kx/this.lm.kx,t=m.ky/this.lm.ky;a.save(),a.setTransform(f*e,0,0,f*t,f*(m.cx-e*this.lm.cx),f*(m.cy-t*this.lm.cy)),a.drawImage(y,0,0,o,s),a.restore()}}describe(){let e=performance.now()/1e3;e-this.rateT>1&&(this.rate=this.newPts/(e-this.rateT||1),this.newPts=0,this.rateT=e);let t=this.portraits.find(e=>e.retiredAt===null);if(!t)return`–`;let n=[...t.tracks.values()].reduce((e,t)=>e+t.length/2,0);return`E ${t.energy.toFixed(4)}, ${t.pts.length/2} pts${t.tracks.size?` + ${n} traced`:``}, ${Math.round(this.rate)}/s`}dispose(){this.worker?.terminate(),this.worker=null}};function L(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 R(e,t,n=`#ccc`){return getComputedStyle(e).getPropertyValue(t).trim()||n}var fe=class{thR=Math.PI;pR=1;lastWall=0;canvas;constructor(e){this.canvas=e}begin(e,t,n,r,i){let a=performance.now()/1e3,o=a-this.lastWall;this.lastWall=a;let s=this.canvas,c=L(s),l=s.clientWidth,u=s.clientHeight;c.clearRect(0,0,l,u);let d=Math.PI,f=e.plotP;if(e.plotZoom===`fit energy`&&t!==null&&n){let e=Math.max(1e-6,t),i=e*r,a=i>=2*n.m2*n.g*n.l2?Math.PI:Math.acos(1-i/(n.m2*n.g*n.l2));d=Math.min(Math.PI,1.08*a),f=1.08*Math.sqrt(2*e)}let p=o>0&&o<.5?1-Math.exp(-o/Math.max(.01,e.zoomSmooth)):1;this.thR*=Math.exp(p*Math.log(d/this.thR)),this.pR*=Math.exp(p*Math.log(f/this.pR));let m=(l/2-8)/this.thR,h=(u/2-8)/this.pR;return c.strokeStyle=i,c.lineWidth=1,c.beginPath(),c.moveTo(8,u/2),c.lineTo(l-8,u/2),c.moveTo(l/2,8),c.lineTo(l/2,u-8),c.stroke(),{g:c,w:l,h:u,sx:e=>l/2+m*e,sy:e=>u/2-h*e}}};function z(e,t,n,r,i,a,o){let{g:s,sx:c,sy:l}=e;s.fillStyle=o,s.globalAlpha=Math.exp(-r/i),s.beginPath(),s.arc(c(t),l(n),a/2,0,2*Math.PI),s.fill(),r<.4&&(s.globalAlpha=1-r/.4,s.strokeStyle=o,s.beginPath(),s.arc(c(t),l(n),a/2+3+12*r,0,2*Math.PI),s.stroke()),s.globalAlpha=1}var pe=64,me=2,he=50;function ge(e,t){return 2*(1+e)+2*e*t}function _e(e,t){e.classList.add(`c01`);let n=document.createElement(`canvas`);e.append(n);let r=new fe(n),i=0,a=!1,o=new de(()=>i,()=>a),s=e=>({show:e.orbits,count:e.orbitCount,cpu:e.orbitCpu,life:e.orbitLife,band:e.orbitBand,minHold:e.orbitMinHold,maxPoints:e.orbitMaxPoints,xfade:e.orbitXfade,alpha:e.orbitAlpha,size:e.orbitSize,tracks:!1,trackMax:0,trackAlpha:0,trackSize:1}),c=new Float64Array(3),l=null,u=0,d=0,f=1/60;function p(t,n,r,i,o,s){let l=i.pendulumAlpha;if(l<=0)return;let u=e=>{let t=s?.at(0,e,c);return t?[t[0],t[1]]:[0,0]},d=a?i.motionBlur*f:0,p=i.lengthRatio,m=i.pendulumSize*Math.min(n,r)/2,h=.9*m/(1+p),g=8+m,_=8+m,v=1;if(d>0){let e=0,t=u(o);for(let n=1;n<=8;n++){let r=u(o-d*n/8);e+=h*(+Math.abs(r[0]-t[0])+p*Math.abs(r[1]-t[1])),t=r}v=Math.max(2,Math.min(pe,Math.ceil(e/me)))}let y=l*(v===1?1:1-.03**(1/v)),b=3*Math.cbrt(i.massRatio),x=R(e,`--fg`);t.strokeStyle=x,t.fillStyle=x,t.lineWidth=1.5,t.lineCap=`round`,t.globalAlpha=y;for(let e=0;e<v;e++){let[n,r]=u(o-d*e/Math.max(1,v-1)),i=g+h*1*Math.sin(n),a=_+h*1*Math.cos(n),s=i+h*p*Math.sin(r),c=a+h*p*Math.cos(r);t.beginPath(),t.moveTo(g,_),t.lineTo(i,a),t.lineTo(s,c),t.stroke(),t.beginPath(),t.arc(i,a,3,0,2*Math.PI),t.moveTo(s+b,c),t.arc(s,c,b,0,2*Math.PI),t.fill()}t.globalAlpha=l,t.beginPath(),t.arc(g,_,1.5,0,2*Math.PI),t.fill(),t.globalAlpha=1}return{keep:e=>4.6*e.fade+.5,draw(n,m,h){let g=t();i=n,a=h;let _=performance.now(),v=(_-d)/1e3;d=_,v>0&&v<.1&&(f+=(v-f)*.1),m!==l&&(l=m,o.reset());let y=m?.at(0,n,c),b=y?y[2]:null,x=g.massRatio,S=g.lengthRatio,C=R(e,`--fg`);_-u>he&&(u=_,o.post(h,s(g),b??0,x,S,[]));let w=r.begin(g,b,{m1:1,l1:1,g:1,m2:x,l2:S},ge(x,S),R(e,`--dim`));if(o.draw(w,n,s(g),C,()=>C),m){let e=g.fade,t=g.pointSize;for(let r of m.events){let i=n-r.t;if(i<0)break;z(w,r.th2,r.p2,i,e,t,C)}}p(w.g,w.w,w.h,g,n,m)},readouts:()=>({"orbit portrait":o.describe()}),dispose(){o.dispose(),e.classList.remove(`c01`)}}}var ve={id:`01-poincare`,schema:I,layout:ce,estimateLength:le,view:_e},ye={id:ve.id,title:`poincaré`,schema:I,defaults:ie,create:(e,t)=>A(ve,e,t)},be={duration:60,peakTime:25,holdTime:10,energyStart:.005,energyPeak:.4,riseShape:`exponential`,riseCurve:1,fallCurve:1,restEnergy:.001,finalHold:2,finalFade:5,speed:40,massRatio:1,lengthRatio:1,tau:2,seed:0,orbitCount:8,colors:`#d6b37a, #7fa8cf, #c48bb8, #93bf8a, #d48f7f, #a9a6e0`,slot1Instrument:`modal: Nylon harp`,slot1Octave:0,slot2Instrument:`modal: Marimba`,slot2Octave:-1,slot3Instrument:`modal: Vibraphone`,slot3Octave:0,slot4Instrument:`modal: Church bell`,slot4Octave:-1,slot5Instrument:`modal: Steel-string pluck`,slot5Octave:0,slot6Instrument:`modal: Glass harmonics`,slot6Octave:1,modalCustom:``,reverbTime:3.5,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,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,fade:20,plotZoom:`fit energy`,zoomSmooth:1.5,plotP:1.5,pointSize:2.5,portrait:!0,portraitCount:24,portraitCpu:.4,portraitLife:300,portraitBand:.25,portraitMinHold:3,portraitMaxPoints:8e3,portraitXfade:1.5,portraitAlpha:.15,portraitSize:1,traces:!0,traceMax:1500,traceAlpha:.75,traceSize:1.5};function xe(e){return Math.max(1,Math.min(20,Math.round(e.orbitCount)))}function Se(e){let t=[],n=[];for(let r=0;r<xe(e);r++){let i=e[`slot${r%6+1}Instrument`],a=t.indexOf(i);a<0&&(a=t.push(i)-1),n.push(a)}return{names:t,stemOf:n}}function Ce(e){let{names:t}=Se(e),n=t.map(t=>P(t,e.modalCustom)),r=P(e.humInstrument,e.humCustom,{voices:1});return{stems:[...n.map((e,t)=>({kind:`synth`,sound:e,output:t})),{kind:`synth`,sound:r,output:t.length}],outputs:[...n.map(e=>({effects:`shared`,sound:e,level:e=>e.notesLevel})),{effects:`own`,sound:r,level:e=>e.humLevel}],reverbTime:e.reverbTime}}function we(e){return e.duration+.5+e.finalHold+e.finalFade+.3}var B=(e,t={})=>{let n=I.find(t=>t.key===e);if(!n)throw Error(`no setting ${e} in composition 1`);return{...n,...t}},Te=[[`modal: Nylon harp`,0],[`modal: Marimba`,-1],[`modal: Vibraphone`,0],[`modal: Church bell`,-1],[`modal: Steel-string pluck`,0],[`modal: Glass harmonics`,1]],Ee=[...[`duration`,`peakTime`,`holdTime`,`energyStart`].map(e=>B(e)),B(`energyPeak`,{default:.4}),...[`riseShape`,`riseCurve`,`fallCurve`,`restEnergy`,`finalHold`,`finalFade`].map(e=>B(e)),B(`speed`,{default:40}),...[`massRatio`,`lengthRatio`,`tau`,`seed`].map(e=>B(e)),{group:`orbits`,key:`orbitCount`,label:`orbits`,kind:`number`,default:8,min:1,max:20,step:1,hint:`pendulums, all following the same energy; each starts at a random place`},{group:`orbits`,key:`colors`,label:`colors`,kind:`text`,default:`#d6b37a, #7fa8cf, #c48bb8, #93bf8a, #d48f7f, #a9a6e0`,hint:`comma-separated CSS colors; orbit n uses color n (cycling)`,live:!0},...Array.from({length:6},(e,t)=>[{group:`orbits`,key:`slot${t+1}Instrument`,label:`instrument ${t+1}`,kind:`select`,default:Te[t][0],options:N,hint:`orbits ${t+1}, ${t+1+6}, ${t+1+12}, … play this instrument`},{group:`orbits`,key:`slot${t+1}Octave`,label:`octave ${t+1}`,kind:`number`,default:Te[t][1],min:-3,max:3,step:1,hint:`register shift for this instrument`}]).flat(),B(`modalCustom`,{group:`orbits`,hint:`for “modal: custom” in any slot: paste JSON from modal-synth’s Copy button`}),{group:`orbits`,key:`reverbTime`,label:`reverb time`,kind:`number`,default:3.5,min:.3,max:12,log:!0,unit:`s`,hint:`one reverb shared by all the orbit instruments (each sends its preset's reverb amount)`},B(`scale`,{default:`dorian`}),...[`root`,`pitchSource`,`thetaRange`,`pitchLow`,`pitchHigh`,`pitchCurve`,`invertPitch`,`p2Ref`,`loudCurve`,`loudFloor`,`notesLevel`,`noteLength`].map(e=>B(e)),...I.filter(e=>e.group===`hum`),B(`fade`,{default:20,hint:`how long each live crossing dot stays visible`}),...[`plotZoom`,`zoomSmooth`,`plotP`].map(e=>B(e)),B(`pointSize`,{default:2.5}),B(`orbits`,{key:`portrait`,group:`portrait`,label:`show portrait`,hint:`grey background: the section's structure at the current energy`}),B(`orbitCount`,{key:`portraitCount`,group:`portrait`}),B(`orbitCpu`,{key:`portraitCpu`,group:`portrait`}),B(`orbitLife`,{key:`portraitLife`,group:`portrait`}),B(`orbitBand`,{key:`portraitBand`,group:`portrait`}),B(`orbitMinHold`,{key:`portraitMinHold`,group:`portrait`}),B(`orbitMaxPoints`,{key:`portraitMaxPoints`,group:`portrait`}),B(`orbitXfade`,{key:`portraitXfade`,group:`portrait`}),B(`orbitAlpha`,{key:`portraitAlpha`,group:`portrait`,default:.15}),B(`orbitSize`,{key:`portraitSize`,group:`portrait`}),{group:`portrait`,key:`traces`,label:`trace orbits`,kind:`bool`,default:!0,hint:`with each portrait, follow every pendulum from its current state (energy frozen) and draw the orbit it's on, in its color`,live:!0},{group:`portrait`,key:`traceMax`,label:`trace length`,kind:`number`,default:1500,min:50,max:1e4,log:!0,hint:`crossings computed per orbit trace`,live:!0},{group:`portrait`,key:`traceAlpha`,label:`trace brightness`,kind:`number`,default:.75,min:.02,max:1,step:.01,live:!0},{group:`portrait`,key:`traceSize`,label:`trace point size`,kind:`number`,default:1.5,min:.5,max:4,step:.1,unit:`px`,live:!0}],De=50;function Oe(e,t){e.classList.add(`c02`);let n=document.createElement(`canvas`);e.append(n);let r=new fe(n),i=0,a=!1,o=new de(()=>i,()=>a),s=e=>({show:e.portrait,count:e.portraitCount,cpu:e.portraitCpu,life:e.portraitLife,band:e.portraitBand,minHold:e.portraitMinHold,maxPoints:e.portraitMaxPoints,xfade:e.portraitXfade,alpha:e.portraitAlpha,size:e.portraitSize,tracks:e.traces,trackMax:e.traceMax,trackAlpha:e.traceAlpha,trackSize:e.traceSize}),c=t=>{let n=String(t.colors).split(`,`).map(e=>e.trim()).filter(Boolean);return n.length?n:[R(e,`--fg`)]},l=new Float64Array(2),u=null,d=0;return{keep:e=>4.6*e.fade+.5,draw(n,f,p){let m=t();i=n,a=p,f!==u&&(u=f,o.reset());let h=xe(m);l.length!==2+5*h&&(l=new Float64Array(2+5*h));let g=f?.at(0,n,l)??null,_=m.massRatio,v=m.lengthRatio,y=performance.now();if(y-d>De){d=y;let e=[];if(g)for(let t=0;t<h;t++)g[2+5*t+4]>.5&&e.push({id:t,y:[g[2+5*t],g[3+5*t],g[4+5*t],g[5+5*t]]});o.post(p,s(m),g?g[0]:0,_,v,e)}let b=r.begin(m,g?g[1]:null,{m1:1,l1:1,g:1,m2:_,l2:v},ge(_,v),R(e,`--dim`)),x=c(m);if(o.draw(b,n,s(m),R(e,`--fg`),e=>x[e%x.length]),f){let e=m.fade,t=m.pointSize;for(let r of f.events){let i=n-r.t;if(i<0)break;z(b,r.th2,r.p2,i,e,t,x[r.o%x.length])}}},readouts:()=>({portrait:o.describe()}),dispose(){o.dispose(),e.classList.remove(`c02`)}}}var ke={id:`02-orbits`,schema:Ee,layout:Ce,estimateLength:we,view:Oe},Ae={id:ke.id,title:`orbits`,schema:Ee,defaults:be,create:(e,t)=>A(ke,e,t)},je={freeTime:40,dampTime:20,dampCurve:1.5,tau:2,restEnergy:.001,finalHold:2,finalFade:5,count:12,releaseAngle:120,jitter:3,separateAt:8,sepThreshold:.02,speed:2.5,massRatio:1,lengthRatio:1,seed:0,instrument:`modal: Vibraphone`,modalCustom:``,pitchMode:`chord`,directionChords:!0,scale:`dorian`,root:`D`,pitchLow:50,pitchHigh:86,loudRef:.6,loudCurve:1,loudFloor:.08,notesLevel:-8,noteLength:2,directionPan:.35,reverbTime:3.5,trails:!0,trailLength:3,trailWidth:1.2,armAlpha:.75,bobSize:3,saturation:35};function Me(e){let t=P(e.instrument,e.modalCustom);return{stems:[{kind:`synth`,sound:t,output:0},{kind:`synth`,sound:t,output:1}],outputs:[{effects:`shared`,sound:t,level:e=>e.notesLevel,pan:e=>-e.directionPan},{effects:`shared`,sound:t,level:e=>e.notesLevel,pan:e=>e.directionPan}],reverbTime:e.reverbTime}}function Ne(e){return e.freeTime+e.dampTime+1+e.finalHold+e.finalFade+.3}var V=(e,t={})=>{let n=I.find(t=>t.key===e);if(!n)throw Error(`no setting ${e} in composition 1`);return{...n,...t}},Pe=[{group:`form`,key:`freeTime`,label:`swinging`,kind:`number`,default:40,min:5,max:600,step:1,unit:`s`,hint:`free (undamped) swinging before the damping begins`},{group:`form`,key:`dampTime`,label:`damping`,kind:`number`,default:20,min:2,max:300,step:.5,unit:`s`,hint:`time for the damping to bring every pendulum to rest`},{group:`form`,key:`dampCurve`,label:`damping curve`,kind:`number`,default:1.5,min:.3,max:5,log:!0,hint:`energy follows (1 − u)^curve during the damping; >1 settles fast then lingers`},{group:`form`,key:`tau`,label:`damping follow`,kind:`number`,default:2,min:.1,max:50,log:!0,unit:`sim s`,hint:`how closely each pendulum's energy follows the damping curve`},V(`restEnergy`,{hint:`after the damping, a pendulum counts as at rest below this energy: its last note rings out`}),V(`finalHold`),V(`finalFade`),{group:`pendulums`,key:`count`,label:`pendulums`,kind:`number`,default:12,min:1,max:24,step:1},{group:`pendulums`,key:`releaseAngle`,label:`release angle`,kind:`number`,default:120,min:10,max:179,step:1,unit:`°`,hint:`both arms released from rest at this angle from straight down`},{group:`pendulums`,key:`jitter`,label:`angle variation`,kind:`number`,default:3,min:0,max:30,step:.1,unit:`°`,hint:`each play varies the release angles by up to this much (seed fixes it)`},{group:`pendulums`,key:`separateAt`,label:`separate after`,kind:`number`,default:8,min:1,max:60,step:.5,unit:`s`,hint:`the tiny offsets between pendulums are calibrated so the outermost visibly separate at about this time`},{group:`pendulums`,key:`sepThreshold`,label:`“visibly”`,kind:`number`,default:.02,min:.001,max:.5,log:!0,hint:`bob separation (fraction of the pendulum's length) that counts as separated`},{group:`pendulums`,key:`speed`,label:`speed`,kind:`number`,default:2.5,min:.25,max:20,log:!0,unit:`×`,hint:`simulated seconds per real second`},V(`massRatio`,{group:`pendulums`}),V(`lengthRatio`,{group:`pendulums`}),V(`seed`,{group:`pendulums`,hint:`0 = a different release every play`}),{group:`notes`,key:`instrument`,label:`instrument`,kind:`select`,default:`modal: Vibraphone`,options:N},V(`modalCustom`),{group:`notes`,key:`pitchMode`,label:`pitch`,kind:`select`,default:`chord`,options:[`chord`,`motion`],hint:`chord: each pendulum has its own note of a chord spread over the range. motion: pitch from the bob's speed at the crossing`},{group:`notes`,key:`directionChords`,label:`two chords`,kind:`bool`,default:!0,hint:`chord mode: left-to-right and right-to-left crossings play two interleaved chords, so the swings alternate between them`},V(`scale`,{default:`dorian`}),V(`root`),V(`pitchLow`,{default:50}),V(`pitchHigh`,{default:86}),{group:`notes`,key:`loudRef`,label:`speed for full`,kind:`number`,default:.6,min:.05,max:1,step:.01,hint:`bob speed (fraction of the fastest possible at release energy) that gives full loudness (and top pitch in motion mode)`},V(`loudCurve`),V(`loudFloor`),V(`notesLevel`,{default:-8,live:!0}),V(`noteLength`,{default:2}),{group:`notes`,key:`directionPan`,label:`pan with direction`,kind:`number`,default:.35,min:0,max:1,step:.01,hint:`a crossing is panned toward the side the bob is heading`,live:!0},{group:`notes`,key:`reverbTime`,label:`reverb time`,kind:`number`,default:3.5,min:.3,max:12,log:!0,unit:`s`},{group:`visual`,key:`trails`,label:`trails`,kind:`bool`,default:!0,live:!0},{group:`visual`,key:`trailLength`,label:`trail length`,kind:`number`,default:3,min:.2,max:20,log:!0,unit:`s`,live:!0},{group:`visual`,key:`trailWidth`,label:`trail width`,kind:`number`,default:1.2,min:.3,max:5,step:.1,unit:`px`,live:!0},{group:`visual`,key:`armAlpha`,label:`arm opacity`,kind:`number`,default:.75,min:.05,max:1,step:.01,live:!0},{group:`visual`,key:`bobSize`,label:`bob size`,kind:`number`,default:3,min:.5,max:10,step:.1,unit:`px`,live:!0},{group:`visual`,key:`saturation`,label:`color saturation`,kind:`number`,default:35,min:0,max:100,step:1,unit:`%`,live:!0}];function Fe(e,t){let n=Math.PI/180,r=e.releaseAngle*n,i=e.jitter*n;return t?[r+(2*t()-1)*i,r+(2*t()-1)*i]:[r,r]}var Ie=1/120;function Le(e,t){e.classList.add(`c03`);let n=document.createElement(`canvas`);e.append(n);let r=new Float64Array,i=(e,t,n)=>`hsl(${((30+360*t/Math.max(1,n))%360).toFixed(0)} ${e.saturation}% 70%)`;return{keep:e=>e.trailLength+.5,draw(a,o){let s=t(),c=L(n),l=n.clientWidth,u=n.clientHeight;c.clearRect(0,0,l,u);let d=Math.max(1,Math.round(s.count)),f=s.lengthRatio,p=.46*Math.min(l,u)/(1+f),m=l/2,h=u/2,g=(e,t)=>{let n=m+p*1*Math.sin(e),r=h+p*1*Math.cos(e);return[n,r,n+p*f*Math.sin(t),r+p*f*Math.cos(t)]};if(s.trails&&o){let e=s.trailLength;c.lineWidth=s.trailWidth,c.lineJoin=c.lineCap=`round`;for(let t=0;t<d;t++){c.strokeStyle=i(s,t,d);for(let n=0;n<6;n++){let r=a-n*e/6,i=a-(n+1)*e/6;c.globalAlpha=.7*(1-(n+.5)/6),c.beginPath();let s=!1;o.rows(0,i-Ie,Math.min(a,r+Ie),(e,n)=>{let[,,r,i]=g(e[n+1+2*t],e[n+2+2*t]);s?c.lineTo(r,i):(c.moveTo(r,i),s=!0)}),c.stroke()}}c.globalAlpha=1}r.length!==2*d&&(r=new Float64Array(2*d));let _=o?.at(0,a,r)??null,[v,y]=Fe(s,null);c.lineWidth=1.5,c.lineCap=`round`;let b=s.bobSize;for(let e=d-1;e>=0;e--){let[t,n,r,a]=_?g(_[2*e],_[2*e+1]):g(v,y),o=i(s,e,d);c.strokeStyle=o,c.fillStyle=o,c.globalAlpha=s.armAlpha,c.beginPath(),c.moveTo(m,h),c.lineTo(t,n),c.lineTo(r,a),c.stroke(),c.globalAlpha=1,c.beginPath(),c.arc(t,n,b*.8,0,2*Math.PI),c.moveTo(r+b,a),c.arc(r,a,b,0,2*Math.PI),c.fill()}c.fillStyle=R(e,`--fg`),c.beginPath(),c.arc(m,h,1.5,0,2*Math.PI),c.fill()},dispose(){e.classList.remove(`c03`)}}}var H={id:`03-divergence`,schema:Pe,layout:Me,estimateLength:Ne,view:Le},Re={id:H.id,title:`divergence`,schema:Pe,defaults:je,create:(e,t)=>A(H,e,t)},ze={fallAfter:2.5,freeTime:60,dampTime:20,dampBase:.004,dampEnd:.2,restEnergy:.001,finalHold:2,finalFade:5,speed:1.5,tipThreshold:.02,massRatio:1,lengthRatio:1,seed:0,extInstrument:`modal: Violin`,modalCustom:``,extPitch:55,minDepth:.25,extLength:.4,firstVel:1,maxVel:.6,loudRef:.8,loudCurve:1,loudFloor:.15,notesLevel:2,maxOverlap:4,click:!0,clickInstrument:`modal: Viola`,clickPitch:72,clickLength:.5,clickMaxVel:.7,clickLevel:-8,heightNotes:!0,heightInstrument:`modal: Piano-ish`,heightLow:60,heightHigh:96,scale:`dorian`,root:`D`,heightStep:2,heightLength:.3,heightVel:.7,heightLevel:14,heightRamp:6,heightRampFrom:.5,heightFollow:.3,trails:!0,trailLength:2.5,rings:!0,motionBlur:1};function Be(e){let t=e.modalCustom,n=P(e.extInstrument,t,{voices:Math.round(e.maxOverlap)}),r=P(e.clickInstrument,t),i=P(e.heightInstrument,t);return{stems:[{kind:`synth`,sound:n,output:0},{kind:`synth`,sound:r,output:1},{kind:`synth`,sound:i,output:2}],outputs:[{effects:`own`,sound:n,level:e=>e.notesLevel},{effects:`own`,sound:r,level:e=>e.clickLevel},{effects:`own`,sound:i,level:e=>e.heightLevel}]}}function Ve(e){return e.freeTime+e.dampTime+3+e.finalHold+e.finalFade+.3}var U=(e,t={})=>{let n=I.find(t=>t.key===e);if(!n)throw Error(`no setting ${e} in composition 1`);return{...n,...t}},He=[{group:`form`,key:`fallAfter`,label:`tips after`,kind:`number`,default:2.5,min:1,max:30,step:.5,unit:`s`,hint:`the nudge from straight up is calibrated so the pendulum visibly tips at about this time`},{group:`form`,key:`freeTime`,label:`swinging`,kind:`number`,default:60,min:5,max:600,step:1,unit:`s`,hint:`time before the stronger damping begins`},{group:`form`,key:`dampTime`,label:`damping`,kind:`number`,default:20,min:2,max:300,step:.5,unit:`s`,hint:`time over which the damping grows to its final strength`},{group:`form`,key:`dampBase`,label:`slight damping`,kind:`number`,default:.004,min:0,max:.1,step:5e-4,unit:`/sim s`,hint:`friction throughout (energy loses roughly this fraction per simulated second)`},{group:`form`,key:`dampEnd`,label:`final damping`,kind:`number`,default:.2,min:.01,max:2,log:!0,unit:`/sim s`,hint:`friction reached by the end of the damping`},U(`restEnergy`,{hint:`after the damping, the pendulum counts as at rest below this energy: the last extension note rings out`}),U(`finalHold`),U(`finalFade`),{group:`pendulum`,key:`speed`,label:`speed`,kind:`number`,default:1.5,min:.25,max:20,log:!0,unit:`×`,hint:`simulated seconds per real second`},{group:`pendulum`,key:`tipThreshold`,label:`“visibly”`,kind:`number`,default:.02,min:.001,max:.5,log:!0,hint:`sideways bob movement (fraction of the length) that counts as tipping`},U(`massRatio`,{group:`pendulum`}),U(`lengthRatio`,{group:`pendulum`}),U(`seed`,{group:`pendulum`,hint:`0 = a different nudge (side and shape) every play`}),{group:`extension`,key:`extInstrument`,label:`instrument`,kind:`select`,default:`modal: Violin`,options:N},U(`modalCustom`,{group:`extension`}),{group:`extension`,key:`extPitch`,label:`pitch`,kind:`number`,default:55,min:12,max:108,step:.5,unit:`midi`},{group:`extension`,key:`extLength`,label:`length`,kind:`number`,default:.4,min:.05,max:5,log:!0,unit:`s`},{group:`extension`,key:`firstVel`,label:`first note`,kind:`number`,default:1,min:.05,max:1,step:.01,hint:`strength of the first extension note (accent)`},{group:`extension`,key:`maxVel`,label:`strongest`,kind:`number`,default:.6,min:.05,max:1,step:.01,hint:`strength of later extension notes at full speed`},{group:`extension`,key:`loudRef`,label:`speed for full`,kind:`number`,default:.8,min:.05,max:1,step:.01,hint:`bob speed (fraction of the fastest possible) that gives the strongest note`},U(`loudCurve`,{group:`extension`}),U(`loudFloor`,{group:`extension`,default:.15}),U(`notesLevel`,{group:`extension`,default:2,max:18,live:!0}),{group:`extension`,key:`maxOverlap`,label:`overlapping notes`,kind:`number`,default:4,min:1,max:16,step:1,hint:`most extension notes ringing at once (a new one replaces the quietest)`},{group:`click`,key:`minDepth`,label:`near the pivot`,kind:`number`,default:.25,min:0,max:.95,step:.01,hint:`a click when the outer bob crosses the vertical within this distance of the pivot (fraction of the length)`},{group:`click`,key:`click`,label:`click`,kind:`bool`,default:!0,hint:`a click when the outer bob passes the pivot (closer than the minimum depth)`},{group:`click`,key:`clickInstrument`,label:`instrument`,kind:`select`,default:`modal: Viola`,options:N},{group:`click`,key:`clickPitch`,label:`pitch`,kind:`number`,default:72,min:24,max:120,step:.5,unit:`midi`},{group:`click`,key:`clickLength`,label:`length`,kind:`number`,default:.5,min:.01,max:2,log:!0,unit:`s`},{group:`click`,key:`clickMaxVel`,label:`strongest`,kind:`number`,default:.7,min:.05,max:1,step:.01,hint:`strength at full bob speed (follows the speed like the extension notes)`},{group:`click`,key:`clickLevel`,label:`level`,kind:`number`,default:-8,min:-48,max:6,step:.5,unit:`dB`,live:!0},{group:`height`,key:`heightNotes`,label:`height notes`,kind:`bool`,default:!0,hint:"levels are the scale's notes between the low and high pitch (every `step`-th); passing one, up or down, plays it"},{group:`height`,key:`heightInstrument`,label:`instrument`,kind:`select`,default:`modal: Piano-ish`,options:N},{group:`height`,key:`heightLow`,label:`pitch at bottom`,kind:`number`,default:60,min:24,max:108,step:.5,unit:`midi`,hint:`bob straight down`},{group:`height`,key:`heightHigh`,label:`pitch at top`,kind:`number`,default:96,min:24,max:120,step:.5,unit:`midi`,hint:`bob straight up`},U(`scale`,{group:`height`,default:`dorian`}),U(`root`,{group:`height`}),{group:`height`,key:`heightStep`,label:`step`,kind:`number`,default:2,min:1,max:7,step:1,hint:`levels every this many scale notes (2 = arpeggio-like)`},{group:`height`,key:`heightLength`,label:`length`,kind:`number`,default:.3,min:.05,max:3,log:!0,unit:`s`},{group:`height`,key:`heightVel`,label:`strength`,kind:`number`,default:.7,min:.05,max:1,step:.01},{group:`height`,key:`heightLevel`,label:`level`,kind:`number`,default:14,min:-48,max:18,step:.5,unit:`dB`,live:!0},{group:`height`,key:`heightRamp`,label:`ramp in`,kind:`number`,default:6,min:0,max:60,step:.5,unit:`s`,hint:`the notes grow to full strength over the opening`},{group:`height`,key:`heightRampFrom`,label:`ramp from`,kind:`number`,default:.5,min:0,max:1,step:.01,hint:`starting strength, as a fraction of full`},{group:`height`,key:`heightFollow`,label:`fades with energy`,kind:`number`,default:.3,min:0,max:2,step:.05,hint:`strength × (energy / start energy)^this`},{group:`visual`,key:`trails`,label:`trail`,kind:`bool`,default:!0,live:!0},{group:`visual`,key:`trailLength`,label:`trail length`,kind:`number`,default:2.5,min:.2,max:20,log:!0,unit:`s`,live:!0},{group:`visual`,key:`rings`,label:`rings`,kind:`bool`,default:!0,hint:`a brief ring where each extension note (and, smaller, each click) happens`,live:!0},U(`motionBlur`)],Ue=48,We=2,Ge=.9,Ke=.35;function qe(e,t){e.classList.add(`c04`);let n=document.createElement(`canvas`);e.append(n);let r=new Float64Array(2),i=0,a=1/60;return{keep:e=>Math.max(e.trailLength,Ge)+.5,draw(o,s,c){let l=t(),u=performance.now()/1e3,d=u-i;i=u,d>0&&d<.1&&(a+=(d-a)*.1);let f=L(n),p=n.clientWidth,m=n.clientHeight;f.clearRect(0,0,p,m);let h=R(e,`--fg`),g=l.lengthRatio,_=.46*Math.min(p,m)/(1+g),v=p/2,y=m/2,b=(e,t)=>{let n=v+_*1*Math.sin(e),r=y+_*1*Math.cos(e);return[n,r,n+_*g*Math.sin(t),r+_*g*Math.cos(t)]},x=e=>{let t=s?.at(0,e,r);return t?[t[0],t[1]]:[Math.PI,Math.PI]};if(l.trails&&s){let e=l.trailLength;f.strokeStyle=h,f.lineWidth=1,f.lineJoin=f.lineCap=`round`;for(let t=0;t<6;t++){let n=o-t*e/6,r=o-(t+1)*e/6;f.globalAlpha=.45*(1-(t+.5)/6),f.beginPath();let i=!1,a=0;s.rows(0,r-.01,Math.min(o,n+.01),(e,t)=>{if(a++%2)return;let[,,n,r]=b(e[t+1],e[t+2]);i?f.lineTo(n,r):(f.moveTo(n,r),i=!0)}),f.stroke()}f.globalAlpha=1}if(l.rings&&s){for(let e of s.events){if(e.kind!==`ring`)continue;let t=o-e.t,n=e.click===1,r=n?Ke:Ge;if(t<0||t>r)continue;let i=e.strength,a=v+_*e.x,s=y+_*e.y;f.strokeStyle=h,f.globalAlpha=(1-t/r)*(.4+.6*i),f.lineWidth=n?1:1.2,f.beginPath();let c=n?14:60*(.5+i);f.arc(a,s,(n?3:6)+c*Math.sqrt(t/r),0,2*Math.PI),f.stroke()}f.globalAlpha=1}let S=c?l.motionBlur*a:0,C=1;if(S>0){let e=0,t=x(o);for(let n=1;n<=8;n++){let r=x(o-S*n/8);e+=_*(+Math.abs(r[0]-t[0])+g*Math.abs(r[1]-t[1])),t=r}C=Math.max(2,Math.min(Ue,Math.ceil(e/We)))}let w=C===1?1:1-.03**(1/C),T=4*Math.cbrt(l.massRatio);f.strokeStyle=h,f.fillStyle=h,f.lineWidth=1.5,f.lineCap=`round`,f.globalAlpha=w;for(let e=0;e<C;e++){let[t,n]=x(o-S*e/Math.max(1,C-1)),[r,i,a,s]=b(t,n);f.beginPath(),f.moveTo(v,y),f.lineTo(r,i),f.lineTo(a,s),f.stroke(),f.beginPath(),f.arc(r,i,4,0,2*Math.PI),f.moveTo(a+T,s),f.arc(a,s,T,0,2*Math.PI),f.fill()}f.globalAlpha=1,f.beginPath(),f.arc(v,y,1.5,0,2*Math.PI),f.fill()},dispose(){e.classList.remove(`c04`)}}}var W={id:`04-descent`,schema:He,layout:Be,estimateLength:Ve,view:qe},Je={id:W.id,title:`descent`,schema:He,defaults:ze,create:(e,t)=>A(W,e,t)},Ye={basePitch:73.42,sizeExp:.5,trail:.35,score:`36 25 36 25 36 25 1!4`,tempo:120,stepBeats:4,pulseAdds:.08,accent:4,tail:16,seed:0,fade:6,signal:`x2`,gain:0,spread:.7,dcCut:20,level:0,ratio1:`1`,partial1:`2`,shape1:1,ring1:20,level1:0,ratio2:`3/2`,partial2:`2`,shape2:1.3,ring2:18,level2:-6,ratio3:`2`,partial3:`3/2`,shape3:.8,ring3:16,level3:-6,ratio4:`5/2`,partial4:`2`,shape4:1.6,ring4:14,level4:-6,ratio5:`3`,partial5:`2`,shape5:.7,ring5:12,level5:-6,ratio6:`4`,partial6:`3/2`,shape6:1.2,ring6:10,level6:-6};function Xe(){return{stems:[{kind:`score`,output:0}],outputs:[{effects:`none`,level:e=>e.level}]}}var Ze=.4;function Qe(e,t,n){return e.trim().split(/\s+/).filter(Boolean).map(e=>{let r=[];for(let i=0;i<e.length;i++)/[1-6]/.test(e[i])&&r.push({i:Number(e[i])-1,add:t*(e[i+1]===`!`?n:1)});return r})}var $e=e=>e.stepBeats*60/Math.max(1,e.tempo),et=e=>Ze+Qe(e.score,0,1).length*$e(e),tt=e=>et(e)+e.tail,G=[`x2`,`y2`,`vx2`,`vy2`,`x1`,`vx1`,`θ1`,`θ2`,`θ2−θ1`,`ω1`,`ω2`,`p1`,`p2`,`speed2`];function K(e,t){let n=1+e,r=e*t,i=e*t*t,a=1+e,o=e*t,s=n*i-r*r,c=(a*i+o*n)/s,l=a*o/s,u=Math.sqrt(Math.max(0,c*c-4*l));return[Math.sqrt((c-u)/2),Math.sqrt((c+u)/2)]}function nt(e,t){let n=1e-4,r=1e4,i=e=>{let[n,r]=K(e,t);return r/n};if(i(n)>=e)return n;if(i(r)<=e)return r;for(let t=0;t<80;t++){let t=Math.sqrt(n*r);i(t)<e?n=t:r=t}return Math.sqrt(n*r)}function rt(e){let[t,n]=e.split(`/`).map(Number);return n?t/n:t}function it(e,t,n,r,i){let a=nt(n,r),[o,s]=K(a,r),c=2*Math.PI*e*t,l=o*i/c,u=l*l;return{l1:u,l2:r*u,m2:a,lower:e*t,upper:e*t*(s/o)}}function at(e,t,n,r){let[i]=K(nt(n,r),r);return 2*Math.PI*e*t/i}var ot=`1.16/15.9/8.6/5.5/4.4/3.45/32.3/2.8/5.5/3.9/5.15/8.2.9/4.12/5.5/2.8/3.3.16/5.10/3.15/4.4.9/2.5.6.8`.split(`.`),st=[`5/4`,`4/3`,`3/2`,`5/3`,`2`,`5/2`,`3`,`4`,`5`,`6`,`8`],ct=[[`1`,`2`,1,20],[`3/2`,`2`,1.3,18],[`2`,`3/2`,.8,16],[`5/2`,`2`,1.6,14],[`3`,`2`,.7,12],[`4`,`3/2`,1.2,10]],lt=[{group:`harmony`,key:`basePitch`,label:`base pitch`,kind:`number`,default:73.42,min:20,max:1e3,log:!0,unit:`Hz`,hint:`pitch ratio 1 sounds here (D2 by default); all pendulums share one time scale, so each pitch comes from its size`},{group:`visual`,key:`sizeExp`,label:`size drawing`,kind:`number`,default:.5,min:0,max:1,step:.05,hint:`drawn size ∝ length^this (1 = true scale: two octaves = 16× the length)`,live:!0},{group:`visual`,key:`trail`,label:`trail`,kind:`number`,default:.35,min:0,max:1,step:.01,hint:`opacity of the bobs' recent paths`,live:!0},{group:`score`,key:`score`,label:`score`,kind:`text`,default:`36 25 36 25 36 25 1!4`,hint:`one step per word: the pendulums pushed together (1–6); ! after a digit = accented; . = a rest`},{group:`score`,key:`tempo`,label:`tempo`,kind:`number`,default:120,min:10,max:400,log:!0,unit:`bpm`},{group:`score`,key:`stepBeats`,label:`step length`,kind:`number`,default:4,min:.25,max:16,step:.25,unit:`beats`,hint:`4 = a whole note per step`},{group:`score`,key:`pulseAdds`,label:`push adds`,kind:`number`,default:.08,min:5e-4,max:2,log:!0,hint:`energy each push adds, in units of E_top`},{group:`score`,key:`accent`,label:`accent`,kind:`number`,default:4,min:1,max:20,log:!0,unit:`×`,hint:`an accented push (!) adds this many times the energy`},{group:`score`,key:`tail`,label:`ring out`,kind:`number`,default:16,min:1,max:120,log:!0,unit:`s`,hint:`after the last step, before the end`},{group:`score`,key:`seed`,label:`seed`,kind:`number`,default:0,min:0,max:999999,step:1,hint:`pushes from rest go in random directions (the mix of each pendulum's two pitches); 0 = a new variation every play`},{group:`score`,key:`fade`,label:`fade`,kind:`number`,default:6,min:.1,max:60,log:!0,unit:`s`,hint:`the last part of the ring-out fades to silence`},{group:`sound`,key:`signal`,label:`signal`,kind:`select`,default:`x2`,options:[...G],hint:`what each pendulum contributes (bob position, velocity, angles…)`},{group:`sound`,key:`gain`,label:`gain`,kind:`number`,default:0,min:-40,max:30,step:.5,unit:`dB`,hint:`per pendulum, before its soft limiter`},{group:`sound`,key:`spread`,label:`stereo spread`,kind:`number`,default:.7,min:0,max:1,step:.01},{group:`sound`,key:`dcCut`,label:`low cut`,kind:`number`,default:20,min:1,max:500,log:!0,unit:`Hz`},{group:`sound`,key:`level`,label:`level`,kind:`number`,default:0,min:-48,max:12,step:.5,unit:`dB`,live:!0},...ct.flatMap(([e,t,n,r],i)=>{let a=`pendulum ${i+1}`;return[{group:a,key:`ratio${i+1}`,label:`pitch ratio`,kind:`select`,default:e,options:ot,hint:`lower partial = base pitch × this (sets the size)`},{group:a,key:`partial${i+1}`,label:`partials`,kind:`select`,default:t,options:st,hint:`upper/lower partial interval (sets the mass ratio)`},{group:a,key:`shape${i+1}`,label:`l2 / l1`,kind:`number`,default:n,min:.2,max:5,log:!0,hint:`the pendulum's shape`},{group:a,key:`ring${i+1}`,label:`ring time`,kind:`number`,default:r,min:.05,max:60,log:!0,unit:`s`},{group:a,key:`level${i+1}`,label:`level`,kind:`number`,default:-6,min:-48,max:12,step:.5,unit:`dB`}]})];function q(e){let t=e.basePitch,n=Array.from({length:6},(t,n)=>({ratio:rt(e[`ratio${n+1}`]),partial:rt(e[`partial${n+1}`]),shape:e[`shape${n+1}`]})),r=n.reduce((e,t)=>t.ratio<e.ratio?t:e),i=at(t,r.ratio,r.partial,r.shape);return{k:i,built:n.map(e=>it(t,e.ratio,e.partial,e.shape,i))}}var ut=.012;function dt(e,t,n){let r=1.5,i=.2,a=e.reduce((e,t)=>e+r*t,0)+i*(e.length-1),o=Math.min(.92*t/a,.5*n/Math.max(...e)),s=n/2-Math.max(...e)*o/2,c=(t-a*o)/2;return{unit:o,at:e.map(e=>{let t={x:c+r/2*e*o,y:s};return c+=(r*e+i)*o,t})}}function ft(e,t){e.classList.add(`c05`);let n=document.createElement(`canvas`);e.append(n);let r=new Float64Array(24),i=``,a=q(t()).built;return{keep:()=>1.5,draw(o,s){let c=t(),l=JSON.stringify([c.basePitch,...Array.from({length:6},(e,t)=>[c[`ratio${t+1}`],c[`partial${t+1}`],c[`shape${t+1}`]])]);l!==i&&(i=l,a=q(c).built);let u=L(n),d=n.clientWidth,f=n.clientHeight;u.clearRect(0,0,d,f);let p=R(e,`--fg`),m=R(e,`--muted`),h=c.sizeExp,g=a.map(e=>e.l1+e.l2),_=g.map(e=>e**+h),{unit:v,at:y}=dt(_,d,f),b=s?.at(0,o,r)??null,x=c.trail,S=[,,,,,,].fill(-1/0);if(s)for(let e of s.events)e.kind===`push`&&e.t<=o&&(S[e.i]=e.t);u.lineCap=`round`,u.lineJoin=`round`;for(let e=0;e<6;e++){let{x:t,y:n}=y[e],r=v*_[e]/g[e];if(s&&x>0){u.strokeStyle=m,u.globalAlpha=x,u.lineWidth=1,u.beginPath();let i=!1;s.rows(1,o-ut,o,(a,o)=>{let s=t+r*a[o+1+2*e],c=n+r*a[o+2+2*e];i?u.lineTo(s,c):(u.moveTo(s,c),i=!0)}),u.stroke()}let i=a[e],c=b?b.subarray(4*e,4*e+4):[0,i.l1,0,g[e]],l=t+r*c[0],d=n+r*c[1],f=t+r*c[2],h=n+r*c[3];u.globalAlpha=.6+.4*Math.max(0,1-(o-S[e])),u.strokeStyle=p,u.fillStyle=p,u.lineWidth=1.5,u.beginPath(),u.moveTo(t,n),u.lineTo(l,d),u.lineTo(f,h),u.stroke();let C=2.2*Math.cbrt(i.m2)+1;u.beginPath(),u.arc(l,d,2,0,2*Math.PI),u.moveTo(f+C,h),u.arc(f,h,C,0,2*Math.PI),u.moveTo(t+1.5,n),u.arc(t,n,1.5,0,2*Math.PI),u.fill()}u.globalAlpha=1},readouts(){let{k:e}=q(t()),n={"time scale":`${e.toFixed(0)} sim s per s`};return a.forEach((e,t)=>{n[`pendulum ${t+1}`]=`${e.lower.toFixed(1)} + ${e.upper.toFixed(1)} Hz; l1 ${e.l1.toFixed(3)}, l2 ${e.l2.toFixed(3)}, m2/m1 ${e.m2.toFixed(2)}`}),n},dispose(){e.classList.remove(`c05`)}}}var pt={id:`05-ensemble`,schema:lt,layout:Xe,estimateLength:tt,view:ft},mt={id:pt.id,title:`ensemble`,schema:lt,defaults:Ye,create:(e,t)=>A(pt,e,t)},ht={mode:`strike`,strikeEnergy:.3,energy:1,pitch:110,ringTime:4,restrike:5,swellTime:2,follow:3,left:`x2`,right:`x1`,gain:-6,dcCut:15,level:-12,massRatio:1,lengthRatio:1,trailMs:12},gt=new URL(`pendulumWorklet-BpTttuTz.js`,import.meta.url).href,_t=new WeakMap;function vt(e,t){let n=document.createElement(`canvas`);n.title=`click (or press S) to strike`,n.style.cursor=`pointer`,e.append(n);let i=null,a=null,o=null,s=null,c,l=!1,u=0,d=null,f=``,p=0,m=e=>({mode:e.mode,pitch:e.pitch,energy:e.energy,strikeEnergy:e.strikeEnergy,ringTime:e.ringTime,restrike:e.restrike,swellTime:e.swellTime,massRatio:e.massRatio,lengthRatio:e.lengthRatio,left:e.left,right:e.right,gain:r(e.gain),dcCut:e.dcCut,follow:e.follow}),h=e=>a?.port.postMessage(e),g=()=>h({type:`strike`});n.onclick=g;let _=e=>{let t=e.target;e.key!==`s`&&e.key!==`S`||t instanceof Element&&t.closest(`input, select, textarea`)||g()};window.addEventListener(`keydown`,_);function v(){if(!a||!i||!o)return;let e=t(),n=m(e),s=JSON.stringify(n);s!==f&&(f=s,h({type:`settings`,s:n})),o.gain.setTargetAtTime(r(e.level),i.ctx.currentTime,.05)}async function y(e){b();let t=++p;i=e;let n=e.ctx,r=_t.get(n);r||_t.set(n,r=n.audioWorklet.addModule(gt)),await r,t===p&&(o=n.createGain(),o.gain.value=0,s=n.createAnalyser(),s.fftSize=4096,s.smoothingTimeConstant=.6,a=new AudioWorkletNode(n,`pendulum-voice`,{numberOfInputs:0,outputChannelCount:[2]}),a.port.onmessage=e=>d=e.data,a.connect(o),o.connect(e.input),o.connect(s),f=``,v(),l=!0,u=n.currentTime,c=window.setInterval(v,50))}function b(){if(p++,c!==void 0&&window.clearInterval(c),c=void 0,l=!1,!i)return;let e=o,t=a,n=s;e&&e.gain.setTargetAtTime(0,i.ctx.currentTime,.03),window.setTimeout(()=>{t?.disconnect(),e?.disconnect(),n?.disconnect()},300),a=o=s=null}let x=new Float32Array(2048),S=null;function C(){let r=t(),a=L(n),o=n.clientWidth,c=n.clientHeight;a.clearRect(0,0,o,c);let u=R(e,`--fg`),f=R(e,`--dim`),p=R(e,`--muted`),m=c*.62;if(d){let e=d.trail,t=e.length/4,n=Math.min(t,Math.round(r.trailMs/(2/48e3*1e3))),i=1+r.lengthRatio,s=.46*Math.min(o,m)/i,c=o/2,l=m/2;a.lineWidth=1,a.strokeStyle=u,a.beginPath();for(let r=t-n;r<t;r++){let i=c+s*e[4*r+2],o=l+s*e[4*r+3];r===t-n?a.moveTo(i,o):a.lineTo(i,o)}a.globalAlpha=.8,a.stroke();let f=t-1;a.globalAlpha=1,a.strokeStyle=p,a.beginPath(),a.moveTo(c,l),a.lineTo(c+s*e[4*f],l+s*e[4*f+1]),a.lineTo(c+s*e[4*f+2],l+s*e[4*f+3]),a.stroke()}if(s){let e=(c-m)*.45,t=m+8;s.getFloatTimeDomainData(x),a.strokeStyle=u,a.lineWidth=1,a.beginPath();for(let n=0;n<1024;n++){let r=n/1023*o,i=t+e/2-x[n]*e/2;n?a.lineTo(r,i):a.moveTo(r,i)}a.stroke(),S&&S.length===s.frequencyBinCount||(S=new Float32Array(s.frequencyBinCount)),s.getFloatFrequencyData(S);let n=(c-m)*.45,r=c-4,l=i.ctx.sampleRate,d=e=>Math.log(e/20)/Math.log(1e3)*o;a.strokeStyle=f,a.beginPath();for(let e of[100,1e3,1e4])a.moveTo(d(e),r-n),a.lineTo(d(e),r);a.stroke(),a.strokeStyle=u,a.beginPath();let p=!1;for(let e=1;e<S.length;e++){let t=e*l/(2*S.length);if(t<20||t>2e4)continue;let i=Math.max(0,Math.min(1,(S[e]+110)/100)),o=d(t),s=r-i*n;p?a.lineTo(o,s):(a.moveTo(o,s),p=!0)}a.stroke()}l||(a.fillStyle=p,a.font=`12px ui-monospace, monospace`,a.fillText(`play, then click here (or press S) to strike`,8,16))}function w(){return{mode:l&&d?d.phase:`–`,energy:d?d.energy.toFixed(4):`–`,"time scale":d?`${d.k.toFixed(0)} sim s per s`:`–`,strike:`click the plot or press S`}}return{get playing(){return l},start:e=>y(e),stop:b,draw:C,now:()=>l&&i?i.ctx.currentTime-u:0,length:()=>1/0,readouts:w,dispose(){b(),window.removeEventListener(`keydown`,_),e.replaceChildren()}}}var yt={id:`lab`,title:`lab: the pendulum as instrument`,hidden:!0,schema:[{group:`play`,key:`mode`,label:`mode`,kind:`select`,default:`strike`,options:[`strike`,`sustain`,`swell`],hint:`strike: start at the energy and ring down; sustain: energy held (like bowing); swell: energy rises, then rings down`},{group:`play`,key:`strikeEnergy`,label:`strike adds`,kind:`number`,default:.3,min:5e-4,max:5,log:!0,hint:`energy each strike adds to the current motion (units of E_top, both arms up)`},{group:`play`,key:`energy`,label:`energy`,kind:`number`,default:1,min:.001,max:5,log:!0,hint:`sustain level and swell target (units of E_top). Low: nearly periodic, two inharmonic modes. ~0.3–1.5: chaos. High: regular again (rotations)`},{group:`play`,key:`pitch`,label:`pitch`,kind:`number`,default:110,min:5,max:2e3,log:!0,unit:`Hz`,hint:`the lower small-swing mode lands here (time scaling)`},{group:`play`,key:`ringTime`,label:`ring time`,kind:`number`,default:4,min:.05,max:60,log:!0,unit:`s`,hint:`damping: amplitude falls 60 dB in this time (strike and swell)`},{group:`play`,key:`restrike`,label:`restrike every`,kind:`number`,default:5,min:0,max:60,step:.1,unit:`s`,hint:`0 = strike once`},{group:`play`,key:`swellTime`,label:`swell time`,kind:`number`,default:2,min:.05,max:30,log:!0,unit:`s`},{group:`play`,key:`follow`,label:`energy follow`,kind:`number`,default:3,min:.2,max:200,log:!0,unit:`periods`,hint:`sustain/swell: how quickly the energy controller corrects`},{group:`sound`,key:`left`,label:`left signal`,kind:`select`,default:`x2`,options:[...G],hint:`x/y: bob position, v: velocity, θ: angles, ω: angular velocities, p: momenta`},{group:`sound`,key:`right`,label:`right signal`,kind:`select`,default:`x1`,options:[...G]},{group:`sound`,key:`gain`,label:`gain`,kind:`number`,default:-6,min:-40,max:30,step:.5,unit:`dB`,hint:`before a soft limiter (high gain = saturated)`},{group:`sound`,key:`dcCut`,label:`low cut`,kind:`number`,default:15,min:1,max:500,log:!0,unit:`Hz`,hint:`removes constant offsets and very slow drift`},{group:`sound`,key:`level`,label:`level`,kind:`number`,default:-12,min:-48,max:6,step:.5,unit:`dB`},{group:`pendulum`,key:`massRatio`,label:`m2 / m1`,kind:`number`,default:1,min:.05,max:20,log:!0},{group:`pendulum`,key:`lengthRatio`,label:`l2 / l1`,kind:`number`,default:1,min:.05,max:20,log:!0},{group:`visual`,key:`trailMs`,label:`path length`,kind:`number`,default:12,min:1,max:16,step:.5,unit:`ms`,hint:`how much of the bob's recent path to draw`}],defaults:ht,create:vt},J=`double pendulum`,Y=[ye,Ae,Re,Je,mt,yt],X=document.getElementById(`app`),Z=null;function Q(e,t={},...n){let r=Object.assign(document.createElement(e),t);return r.append(...n),r}var $={"04-crash":`04-descent`,ensemble:`05-ensemble`};for(let[e,t]of Object.entries($))try{let n=localStorage.getItem(`double-pendulum:author:${e}`);n!==null&&localStorage.getItem(`double-pendulum:author:${t}`)===null&&localStorage.setItem(`double-pendulum:author:${t}`,n),localStorage.removeItem(`double-pendulum:author:${e}`)}catch{}function bt(){Z?.(),Z=null,X.replaceChildren();let e=location.hash.replace(/^#\/?/,``).split(`/`).filter(Boolean);if(e[0]&&$[e[0]]){location.replace(`#/${[$[e[0]],...e.slice(1)].join(`/`)}`);return}let t=Y.find(t=>t.id===e[0]);if(!t)return xt();Z=Tt(t,e[1]===`edit`)}function xt(){document.title=J;let e=Q(`ol`,{className:`tracks`});for(let t of Y)t.hidden||e.append(Q(`li`,{},Q(`a`,{href:`#/${t.id}`,textContent:t.title})));X.append(Q(`main`,{className:`album`},Q(`h1`,{textContent:J}),e))}var St=e=>`double-pendulum:author:${e.id}`;function Ct(e){try{let t=localStorage.getItem(St(e));return t?JSON.parse(t):null}catch{return null}}function wt(e,t){try{localStorage.setItem(St(e),JSON.stringify(t))}catch{}}function Tt(e,t){let r=Y.filter(e=>!e.hidden).indexOf(e)+1;document.title=`${e.title} · ${J}`;let i=()=>a(e.schema,e.defaults),o=t?a(e.schema,e.defaults,Ct(e)):i(),s=Q(`div`,{className:`view`}),c=Q(`button`,{className:`big-play`,textContent:`▶`,title:`play`});c.setAttribute(`aria-label`,`play`);let l=Q(`button`,{className:`play`,textContent:`play`}),u=Q(`div`,{className:`bar`}),d=Q(`div`,{className:`progress`},u),p=Q(`a`,{className:`edit`,href:t?`#/${e.id}`:`#/${e.id}/edit`,textContent:t?`done`:`edit`}),m=Q(`header`,{},Q(`a`,{href:`#/`,textContent:J}),Q(`span`,{className:`sep`,textContent:` / `}),Q(`span`,{textContent:e.hidden?e.title:`${r}. ${e.title}`})),h=Q(`div`,{className:`notice`}),g=Q(`div`,{className:`buffering`,hidden:!0},Q(`div`,{className:`spinner`}),Q(`div`,{className:`fill`})),_=Q(`main`,{className:`stage`},m,h,s,Q(`div`,{className:`transport`},l,d,p)),v=Q(`div`,{className:t?`page with-author`:`page`},_);X.append(v);let y=e.create(s,()=>o);s.append(c,g);let b=()=>{let e=Math.floor(Math.min(s.clientWidth,s.clientHeight));for(let t of s.querySelectorAll(`canvas`))t.style.width=`${e}px`,t.style.height=`${e}px`},x=new ResizeObserver(b);x.observe(s),b();let S={value:0},C=!1,w=async e=>{C=!0;try{let t=await n();await y.start(t,e)}finally{C=!1}};l.onclick=()=>y.playing?y.stop():w(t?S.value:0),c.onclick=()=>l.click(),t&&(d.classList.add(`seekable`),d.onclick=e=>{let t=d.getBoundingClientRect(),n=Math.max(0,(e.clientX-t.left)/t.width*y.length());y.playing&&y.seek?y.seek(n):w(n)});let T=null;t&&(T=f({schema:e.schema,get:()=>o,set:t=>{o=t,wt(e,t)},defaults:i,readouts:()=>y.readouts(),startAt:S}),v.append(T.el));let E=e=>{let t=e.target.tagName;e.code===`Space`&&t!==`INPUT`&&t!==`SELECT`&&t!==`BUTTON`&&(e.preventDefault(),l.click())};window.addEventListener(`keydown`,E);let D=0,O=0,k=e=>{y.draw(),l.textContent=y.playing?`stop`:`play`,c.hidden=y.playing||C;let t=y.playing?y.status?.():void 0,n=!!t?.buffering||C;g.hidden=!n,n&&(g.lastChild.textContent=`${Math.round(100*(t?.fill??0))}%`);let r=y.notice?.()??``;h.textContent!==r&&(h.textContent=r),u.style.width=`${Math.min(100,100*y.now()/y.length())}%`,T&&e-O>200&&(T.updateReadouts(),O=e),D=requestAnimationFrame(k)};return D=requestAnimationFrame(k),()=>{cancelAnimationFrame(D),window.removeEventListener(`keydown`,E),x.disconnect(),y.dispose()}}window.addEventListener(`hashchange`,bt),bt();
site/assets/player-CFiFcj0f.jsdeleted+0−1View file
@@ -1 +0,0 @@
1-const e=.985;var t=class extends AudioWorkletProcessor{o;queues;avail;doneAt;ports=[];playhead;endFrame=1/0;state=`buffering`;resume=1;rebuffers=0;fadeIn=0;tail;blocks=0;rateLog=[];constructor(e){super(e),this.o=e.processorOptions,this.queues=Array.from({length:this.o.stems},()=>[]),this.avail=Array(this.o.stems).fill(this.o.startFrame),this.doneAt=Array(this.o.stems).fill(1/0),this.playhead=this.o.startFrame,this.tail=Array.from({length:this.o.outputs},()=>[0,0]),this.port.onmessage=e=>{if(e.data?.type===`ports`){for(let t of e.data.ports)this.ports.push(t),t.onmessage=e=>this.receive(e.data);this.clock()}}}receive(e){if(e.type===`chunk`){let t=this.queues[e.stem];if(!t)return;t.push({frame:e.frame,L:e.L,R:e.R}),this.avail[e.stem]=Math.max(this.avail[e.stem],e.frame+e.L.length)}else e.type===`done`?this.doneAt[e.stem]=Math.min(this.doneAt[e.stem],e.frame):e.type===`end`&&(this.endFrame=e.frame)}readyTo(e){for(let t=0;t<this.o.stems;t++){let n=Math.min(e,this.doneAt[t],this.endFrame);if(this.avail[t]<n)return!1}return!0}least(){let e=1/0;for(let t=0;t<this.o.stems;t++)this.doneAt[t]>this.playhead&&(e=Math.min(e,this.avail[t]));return e}rate(){let e=this.rateLog;if(e.length<2)return null;let[t,n]=e[0],[r,i]=e[e.length-1];return r-t<+sampleRate?null:(i-n)/(r-t)}aheadFrames(){return Math.round(Math.max(4,2*this.resume,this.target()+2)*sampleRate)}measure(){let e=this.least(),t=this.aheadFrames();if(!Number.isFinite(e)||e-this.playhead>.8*t)this.rateLog=[];else for(this.rateLog.push([currentFrame,e]);this.rateLog.length>2&¤tFrame-this.rateLog[0][0]>2*sampleRate;)this.rateLog.shift()}target(){let e=this.rate();if(e===null||e>=1)return this.resume;let t=((Number.isFinite(this.endFrame)?this.endFrame:this.o.estimatedEnd)-this.playhead)/sampleRate*(1-e)*1.15+.5;return Math.min(32,Math.max(this.resume,t))}fill(){let e=Math.min(this.playhead+this.target()*sampleRate,this.endFrame);if(e<=this.playhead)return 1;let t=1;for(let n=0;n<this.o.stems;n++){let r=Math.min(e,this.doneAt[n]);r<=this.playhead||(t=Math.min(t,Math.max(0,(this.avail[n]-this.playhead)/(r-this.playhead))))}return t}ahead(){let e=1/0;for(let t=0;t<this.o.stems;t++)this.doneAt[t]>this.playhead&&(e=Math.min(e,this.avail[t]-this.playhead));return e===1/0?0:e/sampleRate}clock(){let e=this.aheadFrames(),t={type:`clock`,playhead:this.playhead,ahead:e};for(let e of this.ports)e.postMessage(t)}report(){let e={type:`status`,state:this.state,playhead:this.playhead,at:currentFrame,fill:this.state===`buffering`?this.fill():1,rebuffers:this.rebuffers,ahead:this.ahead()};this.port.postMessage(e)}process(t,n){if(this.state===`playing`&&this.playhead>=this.endFrame&&(this.state=`ended`),this.blocks%12==0&&this.measure(),this.state===`buffering`){let e=Math.min(this.playhead+Math.round(this.target()*sampleRate),this.endFrame);this.readyTo(e)&&(this.state=`playing`,this.fadeIn=0)}if(this.state===`playing`&&!this.readyTo(this.playhead+128)&&(this.state=`buffering`,this.rebuffers++,this.resume=Math.min(32,this.resume*2)),this.state!==`playing`)for(let t=0;t<n.length;t++){let r=n[t][0],i=n[t][1]??r,a=this.tail[t];for(let t=0;t<128;t++)a[0]*=e,a[1]*=e,r[t]=a[0],i!==r&&(i[t]=a[1])}else{let e=this.playhead;for(let t=0;t<this.o.stems;t++){let r=this.queues[t];for(;r.length&&r[0].frame+r[0].L.length<=e;)r.shift();if(e>=this.doneAt[t])continue;let i=n[this.o.route[t]];if(!i)continue;let a=i[0],o=i[1]??a,s=0;for(let t of r){if(s>=128)break;let n=e+s;if(t.frame+t.L.length<=n)continue;if(t.frame>n)break;let r=n-t.frame,i=Math.min(128-s,t.L.length-r);for(let e=0;e<i;e++)a[s+e]+=t.L[r+e],o!==a&&(o[s+e]+=t.R[r+e]);s+=i}}for(let e=0;e<n.length;e++){let t=n[e][0],r=n[e][1]??t;if(this.fadeIn<512)for(let e=0;e<128;e++){let n=Math.min(1,(this.fadeIn+e)/512);t[e]*=n,r!==t&&(r[e]*=n)}this.tail[e][0]=t[127],this.tail[e][1]=r[127]}this.fadeIn+=128,this.playhead+=128}return++this.blocks%6==0&&(this.report(),this.clock()),!0}};registerProcessor(`stream-player`,t);
site/assets/player-xzpyjnp9.jsadded+1−0View file
@@ -0,0 +1 @@
1+const e=.985;var t=class extends AudioWorkletProcessor{o;queues;avail;doneAt;ports=[];playhead;endFrame=1/0;state=`buffering`;resume=1;rebuffers=0;fadeIn=0;tail;blocks=0;rateLog=[];constructor(e){super(e),this.o=e.processorOptions,this.queues=Array.from({length:this.o.stems},()=>[]),this.avail=Array(this.o.stems).fill(this.o.startFrame),this.doneAt=Array(this.o.stems).fill(1/0),this.playhead=this.o.startFrame,this.tail=Array.from({length:this.o.outputs},()=>[0,0]),this.port.onmessage=e=>{if(e.data?.type===`ports`){for(let t of e.data.ports)this.ports.push(t),t.onmessage=e=>this.receive(e.data);this.clock()}}}receive(e){if(e.type===`chunk`){let t=this.queues[e.stem];if(!t)return;t.push({frame:e.frame,L:e.L,R:e.R}),this.avail[e.stem]=Math.max(this.avail[e.stem],e.frame+e.L.length)}else e.type===`done`?this.doneAt[e.stem]=Math.min(this.doneAt[e.stem],e.frame):e.type===`end`&&(this.endFrame=e.frame)}readyTo(e){for(let t=0;t<this.o.stems;t++){let n=Math.min(e,this.doneAt[t],this.endFrame);if(this.avail[t]<n)return!1}return!0}least(){let e=1/0;for(let t=0;t<this.o.stems;t++)this.doneAt[t]>this.playhead&&(e=Math.min(e,this.avail[t]));return e}rate(){let e=this.rateLog;if(e.length<2)return null;let[t,n]=e[0],[r,i]=e[e.length-1];return r-t<+sampleRate?null:(i-n)/(r-t)}aheadFrames(){return Math.round(Math.max(12,2*this.resume,this.target()+2)*sampleRate)}measure(){let e=this.least(),t=this.aheadFrames();if(!Number.isFinite(e)||e-this.playhead>.8*t)this.rateLog=[];else for(this.rateLog.push([currentFrame,e]);this.rateLog.length>2&¤tFrame-this.rateLog[0][0]>2*sampleRate;)this.rateLog.shift()}target(){let e=this.rate();if(e===null||e>=1)return this.resume;let t=((Number.isFinite(this.endFrame)?this.endFrame:this.o.estimatedEnd)-this.playhead)/sampleRate*(1-e)*1.15+.5;return Math.min(32,Math.max(this.resume,t))}fill(){let e=Math.min(this.playhead+this.target()*sampleRate,this.endFrame);if(e<=this.playhead)return 1;let t=1;for(let n=0;n<this.o.stems;n++){let r=Math.min(e,this.doneAt[n]);r<=this.playhead||(t=Math.min(t,Math.max(0,(this.avail[n]-this.playhead)/(r-this.playhead))))}return t}ahead(){let e=1/0;for(let t=0;t<this.o.stems;t++)this.doneAt[t]>this.playhead&&(e=Math.min(e,this.avail[t]-this.playhead));return e===1/0?0:e/sampleRate}clock(){let e=this.aheadFrames(),t={type:`clock`,playhead:this.playhead,ahead:e};for(let e of this.ports)e.postMessage(t)}report(){let e={type:`status`,state:this.state,playhead:this.playhead,at:currentFrame,fill:this.state===`buffering`?this.fill():1,rebuffers:this.rebuffers,ahead:this.ahead()};this.port.postMessage(e)}process(t,n){if(this.state===`playing`&&this.playhead>=this.endFrame&&(this.state=`ended`),this.blocks%12==0&&this.measure(),this.state===`buffering`){let e=Math.min(this.playhead+Math.round(this.target()*sampleRate),this.endFrame);this.readyTo(e)&&(this.state=`playing`,this.fadeIn=0)}if(this.state===`playing`&&!this.readyTo(this.playhead+128)&&(this.state=`buffering`,this.rebuffers++,this.resume=Math.min(32,this.resume*2)),this.state!==`playing`)for(let t=0;t<n.length;t++){let r=n[t][0],i=n[t][1]??r,a=this.tail[t];for(let t=0;t<128;t++)a[0]*=e,a[1]*=e,r[t]=a[0],i!==r&&(i[t]=a[1])}else{let e=this.playhead;for(let t=0;t<this.o.stems;t++){let r=this.queues[t];for(;r.length&&r[0].frame+r[0].L.length<=e;)r.shift();if(e>=this.doneAt[t])continue;let i=n[this.o.route[t]];if(!i)continue;let a=i[0],o=i[1]??a,s=0;for(let t of r){if(s>=128)break;let n=e+s;if(t.frame+t.L.length<=n)continue;if(t.frame>n)break;let r=n-t.frame,i=Math.min(128-s,t.L.length-r);for(let e=0;e<i;e++)a[s+e]+=t.L[r+e],o!==a&&(o[s+e]+=t.R[r+e]);s+=i}}for(let e=0;e<n.length;e++){let t=n[e][0],r=n[e][1]??t;if(this.fadeIn<512)for(let e=0;e<128;e++){let n=Math.min(1,(this.fadeIn+e)/512);t[e]*=n,r!==t&&(r[e]*=n)}this.tail[e][0]=t[127],this.tail[e][1]=r[127]}this.fadeIn+=128,this.playhead+=128}return++this.blocks%6==0&&(this.report(),this.clock()),!0}};registerProcessor(`stream-player`,t);
site/assets/scoreWorker-B3-6tjqi.jsdeleted+0−1View file
@@ -1 +0,0 @@
1-function e(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}}const t=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8)),n=e=>(t.setFloat64(0,e),t.getInt32(0)),r=(e,n)=>(t.setInt32(0,e),t.setInt32(4,n),t.getFloat64(0)),i=e=>(t.setFloat64(0,e),t.getInt32(4));function a(e,t){let n=e*e,r=n*e,i=.00833333333332249+n*(-.0001984126982985795+n*(27557313707070068e-22+n*(-2.5050760253406863e-8+n*158969099521155e-24)));return e-(n*(.5*t-r*i)-t-r*-.16666666666666632)}function o(e,t){let n=e*e,r=n*(.0416666666666666+n*(-.001388888888887411+n*(2480158728947673e-20+n*(-2.7557314351390663e-7+n*(2.087572321298175e-9+n*-11359647557788195e-27))))),i=.5*n,a=1-i;return a+(1-a-i+(n*r-e*t))}let s=0,c=0;function l(e){let t=Math.round(e*.6366197723675814),n=e-t*1.5707963267341256,r=t*6077100506303966e-26,i;return i=n-r,r=t*20222662487959506e-37-(n-i-r),s=i-r,c=i-s-r,t}function u(e){if(!Number.isFinite(e))return NaN;if(Math.abs(e)<.7853981633974483)return a(e,0);let t=l(e)&3;return t===0?a(s,c):t===1?o(s,c):t===2?-a(s,c):-o(s,c)}function d(e){if(!Number.isFinite(e))return NaN;if(Math.abs(e)<.7853981633974483)return o(e,0);let t=l(e)&3;return t===0?o(s,c):t===1?-a(s,c):t===2?-o(s,c):a(s,c)}const f=.6931471803691238,p=19082149292705877e-26;function m(e,t){for(;t>1023;)e*=r(0x7fe00000,0),t-=1023;for(;t<-1022;)e*=r(1048576,0),t+=1022;return e*r(t+1023<<20,0)}function h(e){if(Number.isNaN(e))return NaN;if(e>709.782712893384)return 1/0;if(e<-745.1332191019411)return 0;let t,n,r,i=Math.abs(e);if(i>.34657359027997264)r=Math.trunc(1.4426950408889634*e+(e<0?-.5:.5)),t=e-r*f,n=r*p,e=t-n;else if(i>3.7252902984e-9)r=0,t=e,n=0;else return 1+e;let a=e*e,o=e-a*(.16666666666666602+a*(-.0027777777777015593+a*(6613756321437934e-20+a*(-16533902205465252e-22+a*4.1381367970572385e-8)))),s=1+(e*o/(2-o)-n+t);return r===0?s:m(s,r)}function g(e){if(Number.isNaN(e)||e<0)return NaN;if(e===0)return-1/0;if(e===1/0)return 1/0;let t=0;e<22250738585072014e-324&&(e*=0x40000000000000,t-=54);let a=n(e),o=i(e);a+=614242,t+=(a>>20)-1023,a=(a&0xfffff)+0x3fe6a09e,e=r(a,o);let s=e-1,c=.5*s*s,l=s/(2+s),u=l*l,d=u*u,m=d*(.3999999999940942+d*(.22222198432149784+d*.15313837699209373));return l*(c+(u*(.6666666666666735+d*(.2857142874366239+d*(.1818357216161805+d*.14798198605116586)))+m))+t*p-c+s+t*f}function _(e,t){if(t===0||e===1)return 1;if(Number.isNaN(e)||Number.isNaN(t))return NaN;if(e===0)return t>0?0:1/0;if(e<0){if(!Number.isInteger(t))return NaN;let n=h(t*g(-e));return t%2==0?n:-n}return t===1?e:t===2?e*e:t===.5?Math.sqrt(e):h(t*g(e))}function v(e,t){return Math.sqrt(e*e+t*t)}function y(e){if(e>20)return 1;if(e<-20)return-1;let t=h(2*e);return(t-1)/(t+1)}const b=6.283185307179586;function x(e){return e-b*Math.floor((e+Math.PI)/b)}var S=class{cfg;y=/* @__PURE__ */ new Float64Array(4);t=0;eTarget=0;tau=2;controlled=!0;damping=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]],f=o-s,p=d(f),m=u(f),h=t+n*m*m,g=(i*c-r*l*p)/(r*r*i*h),_=(r*(t+n)*l-i*n*c*p)/(r*i*i*n*h);return{w1:g,w2:_,T:.5*(c*g+l*_),V:(t+n)*a*r*(1-d(o))+n*a*i*(1-d(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],f=e[3],p=s-c,m=d(p),h=u(p),g=n+r*h*h,_=(a*l-i*f*m)/(i*i*a*g),v=(i*(n+r)*f-a*r*l*m)/(i*a*a*r*g),y=l*f*h/(i*a*g),b=(a*a*r*l*l+i*i*(n+r)*f*f-2*i*a*r*l*f*m)*u(2*p)/(2*i*i*a*a*g*g),x=.5*(l*_+f*v),S=(n+r)*o*i*(1-d(s))+r*o*a*(1-d(c)),C=0;if(this.controlled){let e=.02*this.vTop,t=4/this.tau;C=(this.eTarget-(x+S))/(this.tau*(2*x+e)),C>t?C=t:C<-t&&(C=-t)}C-=this.damping,t[0]=_,t[1]=v,t[2]=-(n+r)*o*i*u(s)-y+b+C*l,t[3]=-r*o*a*u(c)+y-b+C*f}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,f=0;for(let e=0;e<1e3&&(c=(2*t()-1)*s,l=(2*t()-1)*s,f=this.derived([c,l,0,0]).V,!(f<.9*o));e++)c=l=0,f=0;let p=o-f,m=t()*2*Math.PI,h=d(m),g=u(m),_=d(c-l),v=(n+r)*i*i,y=r*i*a*_,b=r*a*a,x=.5*(v*h*h+2*y*h*g+b*g*g),S=Math.sqrt(p/x),C=S*h,w=S*g;this.y[0]=c,this.y[1]=l,this.y[2]=v*C+y*w,this.y[3]=y*C+b*w,this.t=0}};function C(e){return x(e)}function w(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}const T=e=>e.geometry===`membrane`||e.geometry===`plate`||e.geometry===`disc`,E=(...e)=>t=>e.includes(t.geometry),D=(...e)=>t=>e.includes(t.exciter),O=[`bow`,`reed`,`selfosc`,`noise`],k=[[`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`]],A=[[`sine`,`Sine`],[`tri`,`Triangle`],[`saw`,`Saw`],[`square`,`Square`],[`sh`,`Sample & hold`],[`smooth`,`Smooth random`]];function j(e){let t=t=>t[`lfo${e}Target`]!==`off`;return[{kind:`enum`,id:`lfo${e}Target`,label:`LFO ${e} →`,group:`Modulation`,options:k,def:`off`},{kind:`enum`,id:`lfo${e}Shape`,label:`Shape`,group:`Modulation`,options:A,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 M=[{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:E(`plate`)},{kind:`num`,id:`powerExp`,label:`Exponent p`,group:`Body`,min:.3,max:3,def:1.5,model:!0,show:E(`free`)},{kind:`num`,id:`discExp`,label:`Chladni exponent`,group:`Body`,min:1,max:2.5,def:2,model:!0,show:E(`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&&T(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:T},{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:D(`strike`)},{kind:`num`,id:`hardness`,label:`Contact time`,group:`Exciter`,min:.05,max:20,def:1,scale:`log`,unit:`ms`,show:D(`strike`,`impulse`)},{kind:`num`,id:`feltExp`,label:`Felt exponent`,group:`Exciter`,min:1,max:4,def:2.5,show:D(`strike`)},{kind:`num`,id:`bowForce`,label:`Bow force`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:D(`bow`)},{kind:`num`,id:`bowSpeed`,label:`Bow speed`,group:`Exciter`,min:0,max:2,def:.4,scale:`pow2`,show:D(`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:D(`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:D(`reed`)},{kind:`num`,id:`reedGain`,label:`Reed opening`,group:`Exciter`,min:0,max:2,def:.5,show:D(`reed`)},{kind:`num`,id:`breath`,label:`Breath noise`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`,show:D(`reed`)},{kind:`num`,id:`selfGain`,label:`Negative damping`,group:`Exciter`,min:0,max:4,def:.5,scale:`pow2`,show:D(`selfosc`)},{kind:`num`,id:`selfSat`,label:`Saturation level`,group:`Exciter`,min:.02,max:4,def:.5,scale:`log`,show:D(`selfosc`)},{kind:`num`,id:`noiseLevel`,label:`Noise level`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:D(`noise`)},{kind:`num`,id:`noiseColor`,label:`Noise cutoff`,group:`Exciter`,min:50,max:16e3,def:3e3,scale:`log`,unit:`Hz`,show:D(`noise`,`reed`,`bow`)},{kind:`num`,id:`attack`,label:`Attack`,group:`Exciter`,min:1,max:3e3,def:40,scale:`log`,unit:`ms`,show:D(...O)},{kind:`num`,id:`release`,label:`Release`,group:`Exciter`,min:5,max:5e3,def:150,scale:`log`,unit:`ms`,show:D(...O)},{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},...j(1),...j(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:T},{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`}],N=Object.fromEntries(M.map(e=>[e.id,e])),P=Object.fromEntries(M.map(e=>[e.id,e.def]));M.filter(e=>e.model).map(e=>e.id);const F={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},I=[{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:{...F,modes:128,inharm:4e-5,exPos:.09,vibDepth:16,vibRate:5.2,soundbox:`cello`}},{name:`Violin`,category:`Instrument`,note:67,p:{...F,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:{...F,modes:96,inharm:3e-5,exPos:.1,vibDepth:15,vibRate:5.5,soundbox:`viola`}},{name:`Double bass`,category:`Instrument`,note:36,p:{...F,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:{...F,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}}],ee=[`bow`,`reed`,`selfosc`,`noise`];[...I.map(e=>`modal: ${e.name}`)],[...I.filter(e=>{let t={...P,...e.p};return ee.includes(t.exciter)||t.fbGain>0}).map(e=>`modal: ${e.name}`)];const te=[`bowForce`,`bowSpeed`,`bowNoise`,`exPos`,`reedPressure`,`reedGain`,`breath`,`selfGain`,`selfSat`,`noiseLevel`,`noiseColor`,`tension`,`cascade`,`curvature`,`fbGain`,`fbFreq`,`fbQ`,`fbSat`,`hfDamp`,`t60`,`pickup`,`tilt`,`vibDepth`];function ne(e,t,n){let r=N[e];if(!r||r.kind!==`num`)return NaN;let i=Math.max(0,Math.min(1,t));return r.scale===`log`?r.min*n(r.max/r.min,i):r.scale===`pow2`?r.min+(r.max-r.min)*i*i:r.min+(r.max-r.min)*i}function re(e){let t=N[e];return t&&t.min!==void 0&&t.max!==void 0?t.max-t.min:1}var L=class{started=!1;next=0;sent={};P;stem;sink;constructor(e,t,n){this.P=e,this.stem=t,this.sink=n}update(e,t,n){let{P:r,sink:i,stem:a}=this;if(!i.emitting||e<this.next)return;this.next=e+.05,this.started||(this.started=!0,i.cmd(a,{t:e,type:`gain`,value:0,tau:0}),i.cmd(a,{t:e,type:`noteOn`,note:r.humPitch,vel:1}));let o=r.energyPeak,s=Math.max(0,Math.min(1,t/o)),c=Math.min(r.energyStart,.999*o),l=r.humColorMode===`log`?Math.max(0,Math.min(1,g(Math.max(t,1e-12)/c)/g(o/c))):s,u=r.humFadeIn,d=r.humFadeOut,f=Math.max(0,Math.min(1,u>0?e/u:1,n!==null&&d>0?(n-e)/d:1)),p=r.humFollow;i.cmd(a,{t:e,type:`gain`,value:f*(1-p+p*s),tau:.08,normalize:r.humNormalize});let m=_(l,r.humColorCurve),h={},v=!1;for(let e of[1,2]){let t=r[`humTarget${e}`];if(t===`none`||!te.includes(t))continue;let n=r[`humFrom${e}`],i=ne(t,n+(r[`humTo${e}`]-n)*m,_);Number.isFinite(i)&&(h[t]=i,(this.sent[t]===void 0||Math.abs(i-this.sent[t])>.002*re(t))&&(v=!0))}v&&(this.sent=h,i.cmd(a,{t:e,type:`params`,params:h}))}};const ie={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};Object.keys(ie);const R=[`C`,`C#`,`D`,`D#`,`E`,`F`,`F#`,`G`,`G#`,`A`,`A#`,`B`];function ae(e){return 440*_(2,(e-69)/12)}function z(e,t,n){if(t===`harmonic series`){let t=ae(n+12*Math.floor((24-n)/12));return 69+12*g(Math.max(1,Math.round(ae(e)/t))*t/440)/g(2)}let r=ie[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}function oe(e,t,n,r=0){let i=e.thetaRange,a=e.pitchSource===`absolute`?Math.min(1,Math.abs(t)/i):Math.max(0,Math.min(1,.5+.5*t/i));e.invertPitch&&(a=1-a),a=_(a,e.pitchCurve);let o=e.pitchLow,s=e.pitchHigh,c=R.indexOf(e.root),l=z(o+(s-o)*a+12*r,e.scale,c),u=Math.min(1,Math.abs(n)/e.p2Ref),d=e.loudFloor;return{midi:l,velocity:d+(1-d)*_(u,e.loudCurve)}}const se=.002,ce=(t,n,r)=>{let i=new S({m1:1,l1:1,g:1,m2:t.massRatio,l2:t.lengthRatio});i.randomize(w(t,0),e(n)),i.tau=t.tau;let a=t.speed,o=t.duration,s=t.restEnergy,c=t.finalHold+t.finalFade+.3,l=new L(t,1,r),u=i.y,d=0,f=C(u[0]),p=u[1],m=u[3],h=null,g=null,_=0,v=0,y=0;function b(){i.eTarget=w(t,d)*i.vTop;let e=d;i.step(se),d+=se/a;let n=C(u[0]);if(h===null&&f<0&&n>=0&&n-f<Math.PI){let a=-f/(n-f),o=e+a*(d-e),s=C(p+a*(u[1]-p)),c=(m+a*(u[3]-m))/i.p2Scale;r.event({t:o,kind:`x`,th2:s,p2:c});let{midi:l,velocity:h}=oe(t,s,c);g=r.note(0,o,l,h,t.noteLength)??g,_++}h===null&&d>=o&&(i.energyNorm()<s||d>=o+10)&&(h=d,g&&r.hold(g,g.t,t.finalHold,t.finalFade),r.end(d+c)),f=n,p=u[1],m=u[3];let b=i.energyNorm();l.update(d,b,h===null?null:h+c),d>=v&&(r.frame(0,d,[u[0],u[1],b]),v=d+.0010416666666666667),d>=y&&(y=d+.1,r.info(d,{"energy target":w(t,d).toFixed(4),energy:b.toFixed(4),notes:String(_)}))}return{get time(){return d},advance(e){for(;d<e;)b()}}};function le(e){return Math.max(1,Math.min(20,Math.round(e.orbitCount)))}function ue(e){let t=[],n=[];for(let r=0;r<le(e);r++){let i=e[`slot${r%6+1}Instrument`],a=t.indexOf(i);a<0&&(a=t.push(i)-1),n.push(a)}return{names:t,stemOf:n}}function de(e){return ue(e).names.length}const fe=.003,pe=(t,n,r)=>{let i=t.speed,a=t.duration,o=t.restEnergy,s=t.finalHold+t.finalFade+.3,{stemOf:c}=ue(t),l=new L(t,de(t),r),u=Math.max(1e-4,w(t,0)),d=Array.from({length:le(t)},(r,i)=>{let a=new S({m1:1,l1:1,g:1,m2:t.massRatio,l2:t.lengthRatio});return a.randomize(u,e(n*1009+i*7919+1)),a.tau=t.tau,{pend:a,prev:C(a.y[0]),prevTh2:a.y[1],prevP2:a.y[3],lastNote:null,restAt:null,stem:c[i],octave:t[`slot${i%6+1}Octave`]}}),f=0,p=null,m=0,h=0,g=0,_=[];function v(){let e=w(t,f),n=f;f+=fe/i,d.forEach((i,s)=>{let c=i.pend,l=c.y;c.eTarget=e*c.vTop,c.step(fe);let u=C(l[0]);if(i.restAt===null&&i.prev<0&&u>=0&&u-i.prev<Math.PI){let e=-i.prev/(u-i.prev),a=n+e*(f-n),o=C(i.prevTh2+e*(l[1]-i.prevTh2)),d=(i.prevP2+e*(l[3]-i.prevP2))/c.p2Scale;r.event({t:a,kind:`x`,o:s,th2:o,p2:d});let{midi:p,velocity:h}=oe(t,o,d,i.octave);i.lastNote=r.note(i.stem,a,p,h,t.noteLength)??i.lastNote,m++}i.restAt===null&&f>=a&&(c.energyNorm()<o||f>=a+10)&&(i.restAt=f,i.lastNote&&r.hold(i.lastNote,i.lastNote.t,t.finalHold,t.finalFade)),i.prev=u,i.prevTh2=l[1],i.prevP2=l[3]}),p===null&&d.every(e=>e.restAt!==null)&&(p=f,r.end(f+s));let c=0,u=0;for(let e of d){let t=e.pend.energyNorm();c+=t,u=Math.max(u,t)}let v=c/d.length;if(l.update(f,v,p===null?null:p+s),f>=h){h=f+.03333333333333333,_.length=0,_.push(v,u);for(let e of d)_.push(e.pend.y[0],e.pend.y[1],e.pend.y[2],e.pend.y[3],+(e.restAt===null));r.frame(0,f,_)}f>=g&&(g=f+.1,r.info(f,{"energy target":e.toFixed(4),"energy (mean)":v.toFixed(4),notes:String(m),"at rest":`${d.filter(e=>e.restAt!==null).length} / ${d.length}`}))}return{get time(){return f},advance(e){for(;f<e;)v()}}},B=.002;function me(e,t,n,r){let i=new S(e);return i.controlled=!1,i.y[0]=t,i.y[1]=n+r,i.y[2]=0,i.y[3]=0,i}function V(e,t){return[e.l1*u(t[0])+e.l2*u(t[1]),e.l1*d(t[0])+e.l2*d(t[1])]}function H(e,t,n,r,i,a){let o=me(e,t,n,-r/2),s=me(e,t,n,r/2);for(let t=0;t<a;t+=B){o.step(B),s.step(B);let[n,r]=V(e,o.y),[a,c]=V(e,s.y);if(v(n-a,r-c)>i)return t+B}return 1/0}function he(e,t,n,r,i){let a=3*r+10,o=1e-15,s=.01;if(H(e,t,n,o,i,a)<=r)return{offset:o,separatesAt:H(e,t,n,o,i,a)};if(H(e,t,n,s,i,a)>=r)return{offset:s,separatesAt:H(e,t,n,s,i,a)};for(let c=0;c<16;c++){let c=Math.sqrt(o*s);H(e,t,n,c,i,a)>r?o=c:s=c}let c=Math.sqrt(o*s);return{offset:c,separatesAt:H(e,t,n,c,i,a)}}function ge(e,t){let n=Math.PI/180,r=e.releaseAngle*n,i=e.jitter*n;return t?[r+(2*t()-1)*i,r+(2*t()-1)*i]:[r,r]}function _e(e,t){let n=e.pitchLow,r=e.pitchHigh,i=R.indexOf(e.root),a=!!e.directionChords,o=a?2*t:t,s=[];if(e.scale===`continuous`)s=Array.from({length:Math.max(o,2)},(e,t)=>n+(r-n)*t/Math.max(1,Math.max(o,2)-1));else for(let t=Math.ceil(n);t<=r;t++)Math.abs(z(t,e.scale,i)-t)<1e-6&&s.push(t);s.length||(s=[z((n+r)/2,e.scale,i)]);let c=Array.from({length:o},(e,t)=>s[o>1?Math.round(t*(s.length-1)/(o-1)):Math.floor(s.length/2)]);return a?{right:c.filter((e,t)=>t%2==0),left:c.filter((e,t)=>t%2==1)}:{right:c,left:c}}const ve=(t,n,r)=>{let i={m1:1,l1:1,g:1,m2:t.massRatio,l2:t.lengthRatio},a=t.speed,[o,s]=ge(t,e(n)),c=he(i,o,s,t.separateAt*a,t.sepThreshold*(i.l1+i.l2)),l=Math.max(1,Math.round(t.count)),f=Array.from({length:l},(e,t)=>{let n=me(i,o,s,l>1?(t/(l-1)-.5)*c.offset:0);return{p:n,prevX:V(i,n.y)[0],E0:0,lastNote:null,restAt:null}}),p=Math.sqrt(2*f[0].p.energy()/i.m2),m=t.freeTime,h=t.dampTime,g=t.dampCurve,y=t.tau,b=t.restEnergy,x=t.finalHold+t.finalFade+.3,S=_e(t,l),C=180/Math.PI,w=`${(o*C).toFixed(2)}°, ${(s*C).toFixed(2)}°`,T=`${c.offset.toExponential(2)} rad → separate at ${(c.separatesAt/a).toFixed(1)} s`,E=0,D=null,O=0,k=0,A=0,j=new Float64Array(2*l);function M(e,n,a){let o=f[e],s=o.p.y,c=o.p.derived(),l=i.l1*d(s[0])*c.w1+i.l2*d(s[1])*c.w2,m=i.l1*u(s[0])*c.w1+i.l2*u(s[1])*c.w2,h=Math.min(1,v(l,m)/(t.loudRef*p)),g=t.loudFloor,y=g+(1-g)*_(h,t.loudCurve),b=t.pitchMode===`motion`?z(t.pitchLow+(t.pitchHigh-t.pitchLow)*h,t.scale,R.indexOf(t.root)):S[a>0?`right`:`left`][e];o.lastNote=r.note(+(a>0),n,b,y,t.noteLength)??o.lastNote,O++}function N(){let e=E;E+=B/a;let n=(e-m)/h;if(f.forEach((a,o)=>{let s=a.p;n>=0&&(s.controlled||(s.controlled=!0,a.E0=s.energy()),s.tau=y,s.eTarget=n<1?a.E0*_(1-n,g):0,s.damping=n>=1?1/y:0),s.step(B);let c=V(i,s.y)[0];a.restAt===null&&(a.prevX<0&&c>=0||a.prevX>0&&c<=0)&&M(o,e+a.prevX/(a.prevX-c)*(E-e),c>a.prevX?1:-1),a.prevX=c,a.restAt===null&&n>=1&&(s.energyNorm()<b||E>=m+h+10)&&(a.restAt=E,a.lastNote&&r.hold(a.lastNote,a.lastNote.t,t.finalHold,t.finalFade))}),D===null&&f.every(e=>e.restAt!==null)&&(D=E,r.end(E+x)),E>=k&&(k=E+.008333333333333333,f.forEach((e,t)=>{j[2*t]=e.p.y[0],j[2*t+1]=e.p.y[1]}),r.frame(0,E,j)),E>=A){A=E+.1;let e=D===null?E<m?`swinging`:E<m+h?`damping`:`settling`:`at rest`;r.info(E,{phase:e,"energy (mean)":(f.reduce((e,t)=>e+t.p.energyNorm(),0)/l).toFixed(4),notes:String(O),release:w,"offset (outermost)":T,"at rest":`${f.filter(e=>e.restAt!==null).length} / ${l}`})}}return{get time(){return E},advance(e){for(;E<e;)N()}}},U=.002;function ye(e,t,n,r){let i=new S(e);return i.controlled=!1,i.y[0]=Math.PI+r*t,i.y[1]=Math.PI+r*t*n,i}function W(e,t){return[e.l1*u(t[0])+e.l2*u(t[1]),e.l1*d(t[0])+e.l2*d(t[1])]}function be(e,t,n,r,i){let a=ye(e,t,n,1);for(let t=0;t<i;t+=U)if(a.step(U),Math.abs(W(e,a.y)[0])>r)return t+U;return 1/0}function xe(e,t,n,r){let i=3*n+10,a=n=>be(e,n,t,r,i),o=[];for(let e=0;e<=58;e++){let t=_(10,-15+.25*e);o.push({d:t,t:a(t)})}let s=[...o];for(let e=0;e+1<o.length;e++){let t=o[e],r=o[e+1];if(t.t>n&&r.t<=n){for(let e=0;e<14;e++){let e=Math.sqrt(t.d*r.d),i=a(e);i>n?t={d:e,t:i}:r={d:e,t:i}}s.push(t,r)}}let c=e=>Math.abs(e.t-n),l=Math.min(...s.map(c)),u=s.filter(e=>c(e)<=l+.01*n).reduce((e,t)=>t.d<e.d?t:e);return{nudge:u.d,tipsAt:u.t}}const Se=(t,n,r)=>{let i={m1:1,l1:1,g:1,m2:t.massRatio,l2:t.lengthRatio},a=t.speed,o=e(n),s=o()<.5?-1:1,c=.6+.8*o(),l=xe(i,c,t.fallAfter*a,t.tipThreshold*(i.l1+i.l2)),f=ye(i,l.nudge,c,s),p=i.l1+i.l2,m=f.energy(),h=Math.sqrt(2*m/i.m2),g=t.freeTime+t.dampTime,y=t.restEnergy,b=t.minDepth*p,S=`${l.nudge.toExponential(2)} rad ${s>0?`→`:`←`} (shape ${c.toFixed(2)}), tips at ${(l.tipsAt/a).toFixed(1)} s`,C=(()=>{if(!t.heightNotes)return[];let e=t.heightLow,n=t.heightHigh,r=R.indexOf(t.root),i=[];for(let a=Math.ceil(e);a<=n;a++)(t.scale===`continuous`||Math.abs(z(a,t.scale,r)-a)<1e-6)&&i.push(a);let a=Math.max(1,Math.round(t.heightStep));return i.filter((e,t)=>t%a===0)})(),w=e=>t.heightLow+(t.heightHigh-t.heightLow)*((p-e)/(2*p)),T=e=>{let t=0;for(;t<C.length&&C[t]<e;)t++;return t},E=.3*(C.length>1?(C[C.length-1]-C[0])/(C.length-1):1),D=0,O=W(i,f.y)[0],k=x(f.y[1]-f.y[0]),A=!1,j=T(w(W(i,f.y)[1])),M=null,N=null,P=0,F=0,I=0,ee=0,te=0,ne=e=>{let n=Math.max(0,Math.min(1,(e-t.freeTime)/t.dampTime)),r=n*n*(3-2*n);return t.dampBase+(t.dampEnd-t.dampBase)*r},re=()=>{let e=f.derived(),n=f.y,r=i.l1*d(n[0])*e.w1+i.l2*d(n[1])*e.w2,a=i.l1*u(n[0])*e.w1+i.l2*u(n[1])*e.w2,o=Math.min(1,v(r,a)/(t.loudRef*h)),s=t.loudFloor;return s+(1-s)*_(o,t.loudCurve)},L=(e,n)=>{let i=t.heightRamp>0?Math.max(0,Math.min(1,e/t.heightRamp)):1,a=t.heightRampFrom,o=a+(1-a)*i*i*(3-2*i),s=Math.min(1,Math.max(0,f.energy())/m);r.note(2,e,n,t.heightVel*o*_(s,t.heightFollow),t.heightLength),I++};function ie(){let e=D;D+=U/a,f.damping=ne(e),f.step(U);let[n,o]=W(i,f.y);if(M===null&&C.length){let e=w(o);for(;j<C.length&&e>C[j]+E;)L(D,C[j++]);for(;j>0&&e<C[j-1]-E;)L(D,C[--j])}if(M===null&&Math.abs(o)<=b&&(O<0&&n>=0||O>0&&n<=0)){let i=e+O/(O-n)*(D-e);if(F++,t.click){let e=t.clickMaxVel*re();r.note(1,i,t.clickPitch,e,t.clickLength),r.event({t:i,kind:`ring`,x:0,y:o,strength:e,click:1})}}O=n;let s=x(f.y[1]-f.y[0]);if(Math.abs(s)>.05&&(A=!0),M===null&&A&&(k<0&&s>=0||k>0&&s<=0)&&Math.abs(s-k)<Math.PI){let i=e+k/(k-s)*(D-e);A=!1,P++;let a=P===1?t.firstVel:t.maxVel*re();N=r.note(0,i,t.extPitch,a,t.extLength)??N,r.event({t:i,kind:`ring`,x:n,y:o,strength:a,click:0})}if(k=s,M===null&&D>=g&&(f.energyNorm()<y||D>=g+15)&&(M=D,N&&r.hold(N,N.t,t.finalHold,t.finalFade),r.end(D+t.finalHold+t.finalFade+.3)),D>=ee&&(r.frame(0,D,[f.y[0],f.y[1]]),ee=D+.0020833333333333333),D>=te){te=D+.1;let e=t.freeTime,n=M===null?P===0?`falling`:D<e?`swinging`:D<g?`damping`:`settling`:`at rest`;r.info(D,{phase:n,energy:`${(f.energy()/m).toFixed(3)} of start`,"extension notes":String(P),clicks:String(F),"height notes":String(I),nudge:S,friction:`${ne(D).toFixed(4)} /sim s`})}}return r.emitting&&r.frame(0,0,[f.y[0],f.y[1]]),{get time(){return D},advance(e){for(;D<e;)ie()}}};function Ce(e,t,n){let r=e.y;if(!(t>0))return;let i=r[2],a=r[3],o=v(i,a);if(o>1e-9)i/=o,a/=o;else{let e=n()*2*Math.PI;i=d(e),a=u(e)}let s=e.derived(),c=i*s.w1+a*s.w2,l=e.derived([r[0],r[1],i,a]),f=i*l.w1+a*l.w2,p=(-c+Math.sqrt(Math.max(0,c*c+2*f*t)))/f;r[2]+=p*i,r[3]+=p*a}function we(e,t,n,r){let{l1:i,l2:a,m2:o}=e.cfg,s=e.y,c=i+a,l=Math.sqrt(2*e.vTop/o)+1e-9,f=u(s[0]),p=d(s[0]),m=u(s[1]),h=d(s[1]);switch(t){case`x2`:return(i*f+a*m)/c;case`y2`:return-(i*p+a*h)/c;case`vx2`:return(i*p*n+a*h*r)/l;case`vy2`:return(i*f*n+a*m*r)/l;case`x1`:return f;case`vx1`:return i*p*n/l;case`θ1`:return x(s[0])/Math.PI;case`θ2`:return x(s[1])/Math.PI;case`θ2−θ1`:return x(s[1]-s[0])/Math.PI;case`ω1`:return n*i/l;case`ω2`:return r*a/l;case`p1`:return s[2]/(l*(1+o)*i*i+1e-9);case`p2`:return s[3]/(l*o*a*a+1e-9);case`speed2`:return v(i*p*n+a*h*r,i*f*n+a*m*r)/l}}var Te=class{x=0;y=0;run(e,t){let n=e-this.x+t*this.y;return this.x=e,this.y=n,n}};const G=48e3;function Ee(e,t){let n=1+e,r=e*t,i=e*t*t,a=1+e,o=e*t,s=n*i-r*r,c=(a*i+o*n)/s,l=a*o/s,u=Math.sqrt(Math.max(0,c*c-4*l));return[Math.sqrt((c-u)/2),Math.sqrt((c+u)/2)]}function De(e,t){let n=1e-4,r=1e4,i=e=>{let[n,r]=Ee(e,t);return r/n};if(i(n)>=e)return n;if(i(r)<=e)return r;for(let t=0;t<80;t++){let t=Math.sqrt(n*r);i(t)<e?n=t:r=t}return Math.sqrt(n*r)}function Oe(e){let[t,n]=e.split(`/`).map(Number);return n?t/n:t}function ke(e,t,n,r,i){let a=De(n,r),[o,s]=Ee(a,r),c=2*Math.PI*e*t,l=o*i/c,u=l*l;return{l1:u,l2:r*u,m2:a,lower:e*t,upper:e*t*(s/o)}}function Ae(e,t,n,r){let[i]=Ee(De(n,r),r);return 2*Math.PI*e*t/i}function je(e,t,n){return e.trim().split(/\s+/).filter(Boolean).map(e=>{let r=[];for(let i=0;i<e.length;i++)/[1-6]/.test(e[i])&&r.push({i:Number(e[i])-1,add:t*(e[i+1]===`!`?n:1)});return r})}const Me=e=>e.stepBeats*60/Math.max(1,e.tempo),Ne=e=>.4+je(e.score,0,1).length*Me(e);function Pe(e){let t=e.basePitch,n=Array.from({length:6},(t,n)=>({ratio:Oe(e[`ratio${n+1}`]),partial:Oe(e[`partial${n+1}`]),shape:e[`shape${n+1}`]})),r=n.reduce((e,t)=>t.ratio<e.ratio?t:e),i=Ae(t,r.ratio,r.partial,r.shape);return{k:i,built:n.map(e=>ke(t,e.ratio,e.partial,e.shape,i))}}const Fe={"01-poincare":ce,"02-orbits":pe,"03-divergence":ve,"04-descent":Se,"05-ensemble":(t,n,r)=>{let{k:i,built:a}=Pe(t),o=e(n),s=t.signal,c=h(t.gain*.11512925464970229),l=1-2*Math.PI*t.dcCut/G,f=je(t.score,t.pulseAdds,t.accent),p=Me(t),m=Ne(t)+t.tail,g=Math.min(t.fade,t.tail),_=i/G,v=a.map((e,n)=>{let r=new S({m1:1,m2:e.m2,l1:e.l1,l2:e.l2,g:1});r.controlled=!1;let a=t[`ring${n+1}`];r.damping=a>0?13.8156/(a*i):0;let o=Math.max(1,Math.ceil(40*e.upper/G)),s=(t.spread*(2*n/5-1)+1)*Math.PI/4,c=h(t[`level${n+1}`]*.11512925464970229);return{p:r,dc:new Te,sub:o,h:_/o,gl:d(s)*c,gr:u(s)*c}}),b=0,x=0,C=!1,w=/* @__PURE__ */ new Float64Array(24),T=/* @__PURE__ */ new Float64Array(12);function E(e){C||(C=!0,r.end(m));let t=Math.round(e*G)-b;if(t<=0)return;let n=new Float32Array(t),i=new Float32Array(t);for(let e=0;e<t;e++,b++){let t=b/G;if(x<f.length&&t>=.4+x*p){for(let e of f[x]){let n=v[e.i];n&&(Ce(n.p,e.add*n.p.vTop,o),r.event({t,kind:`push`,i:e.i}))}x++}let a=0,h=0;for(let e of v){for(let t=0;t<e.sub;t++)e.p.step(e.h);Number.isFinite(e.p.y[0])||e.p.y.fill(0);let t=e.p.derived(),n=y(c*e.dc.run(we(e.p,s,t.w1,t.w2),l));a+=e.gl*n,h+=e.gr*n}let _=Math.max(0,Math.min(1,(m-t)/g));n[e]=a*_*_,i[e]=h*_*_,b%6==0&&(v.forEach((e,t)=>{let n=e.p.y,r=e.p.cfg;T[2*t]=r.l1*u(n[0])+r.l2*u(n[1]),T[2*t+1]=r.l1*d(n[0])+r.l2*d(n[1])}),r.frame(1,t,T)),b%400==0&&(v.forEach((e,t)=>{let n=e.p.y,r=e.p.cfg,i=r.l1*u(n[0]),a=r.l1*d(n[0]);w.set([i,a,i+r.l2*u(n[1]),a+r.l2*d(n[1])],4*t)}),r.frame(0,t,w),r.info(t,{score:`step ${x} of ${f.length}`,energies:v.map(e=>e.p.energyNorm().toFixed(2)).join(` `)}))}r.audio(0,n,i)}return{get time(){return b/G},advance:E}}},Ie=2.5;let K,q,J=!1,Le=0,Re=4*G,Y=1/0,X=!1,ze=!1,Z=[],Be=-1/0;const Ve=/* @__PURE__ */ new Map;let He=[],Q=null,Ue=-1/0;const We=/* @__PURE__ */ new Map,$=(e,t=[])=>self.postMessage(e,t),Ge=(e,t=[])=>q.playerPort.postMessage(e,t),Ke={get emitting(){return J},frame(e,t,n){if(!J)return;let r=Ve.get(e);r||Ve.set(e,r={stride:n.length+1,rows:[]}),r.rows.push(t);for(let e=0;e<n.length;e++)r.rows.push(n[e])},event(e){J&&He.push(e)},info(e,t){J&&(Q={t:e,info:t})},note(e,t,n,r,i){if(!J||!Z[e]||r<=0)return null;let a={t,type:`noteOn`,note:n,vel:Math.max(.01,Math.min(1,r))},o={t:t+i,type:`noteOff`,note:n,on:t};return Z[e].push(a,o),{stem:e,t,off:o}},hold(e,t,n,r){if(!J||!Z[e.stem])return;let i=Math.max(t,Be),a=i+n+r;Z[e.stem].includes(e.off)&&e.off.t<a&&(e.off.t=a),Z[e.stem].push({t:i,type:`hold`,hold:n,fade:r})},cmd(e,t){J&&Z[e]&&Z[e].push(t)},audio(e,t,n){if(!J)return;let r=We.get(e)??Math.round(q.from*48e3);We.set(e,r+t.length);let i=Math.round(q.start*G);if(r+t.length<=i)return;let a=Math.max(0,i-r),o=a?t.slice(a):t,s=a?n.slice(a):n;Ge({type:`chunk`,stem:e,frame:r+a,L:o,R:s},[o.buffer,s.buffer])},end(e){Y===1/0&&(Y=e,$({type:`end`,t:e}),Ge({type:`end`,frame:Math.round(e*G)}))}};function qe(e,t=!1){if(e>Be&&(q.synthPorts.forEach((t,n)=>{if(!t)return;let r=Z[n];r.sort((e,t)=>e.t-t.t);let i=0;for(;i<r.length&&r[i].t<e;)i++;let a={type:`cmds`,cmds:r.splice(0,i),horizon:e};t.postMessage(a)}),Be=e),!(!t&&K.time-Ue<.1)){Ue=K.time;for(let[e,t]of Ve){if(!t.rows.length)continue;let n=Float64Array.from(t.rows);t.rows=[],$({type:`frames`,track:e,stride:t.stride,data:n},[n.buffer])}He.length&&($({type:`events`,events:He}),He=[]),Q&&=($({type:`info`,t:Q.t,info:Q.info}),null)}}function Je(){ze||X||(ze=!0,setTimeout(Ye,0))}function Ye(){ze=!1;try{if(K.time>=Y){qe(Y+1,!0),q.synthPorts.forEach(e=>e?.postMessage({type:`end`,t:Y})),X=!0;return}let e=Math.min(Y,(Le+Re)/G+Ie+.5);if(K.time>=e)return;K.advance(Math.min(K.time+.05,e,Y)),qe(K.time-Ie)}catch(e){X=!0,$({type:`error`,message:String(e?.stack??e)});return}Je()}self.onmessage=e=>{let t=e.data;if(t.type===`init`){q=t,Z=t.synthPorts.map(()=>[]),Le=Math.round(t.start*G),t.playerPort.onmessage=e=>{Le=e.data.playhead,Re=e.data.ahead,Je()};try{let e=Fe[t.comp];if(!e)throw Error(`no score for ${t.comp}`);K=e(t.P,t.seed,Ke),t.from>0&&K.advance(t.from),J=!0,Be=t.from}catch(e){X=!0,$({type:`error`,message:String(e?.stack??e)});return}Je()}};
site/assets/scoreWorker-DiSIToaP.jsadded+1−0View file
@@ -0,0 +1 @@
1+function e(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}}const t=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8)),n=e=>(t.setFloat64(0,e),t.getInt32(0)),r=(e,n)=>(t.setInt32(0,e),t.setInt32(4,n),t.getFloat64(0)),i=e=>(t.setFloat64(0,e),t.getInt32(4));function a(e,t){let n=e*e,r=n*e,i=.00833333333332249+n*(-.0001984126982985795+n*(27557313707070068e-22+n*(-2.5050760253406863e-8+n*158969099521155e-24)));return e-(n*(.5*t-r*i)-t-r*-.16666666666666632)}function o(e,t){let n=e*e,r=n*(.0416666666666666+n*(-.001388888888887411+n*(2480158728947673e-20+n*(-2.7557314351390663e-7+n*(2.087572321298175e-9+n*-11359647557788195e-27))))),i=.5*n,a=1-i;return a+(1-a-i+(n*r-e*t))}let s=0,c=0;function l(e){let t=Math.round(e*.6366197723675814),n=e-t*1.5707963267341256,r=t*6077100506303966e-26,i;return i=n-r,r=t*20222662487959506e-37-(n-i-r),s=i-r,c=i-s-r,t}function u(e){if(!Number.isFinite(e))return NaN;if(Math.abs(e)<.7853981633974483)return a(e,0);let t=l(e)&3;return t===0?a(s,c):t===1?o(s,c):t===2?-a(s,c):-o(s,c)}function d(e){if(!Number.isFinite(e))return NaN;if(Math.abs(e)<.7853981633974483)return o(e,0);let t=l(e)&3;return t===0?o(s,c):t===1?-a(s,c):t===2?-o(s,c):a(s,c)}const f=.6931471803691238,p=19082149292705877e-26;function m(e,t){for(;t>1023;)e*=r(0x7fe00000,0),t-=1023;for(;t<-1022;)e*=r(1048576,0),t+=1022;return e*r(t+1023<<20,0)}function h(e){if(Number.isNaN(e))return NaN;if(e>709.782712893384)return 1/0;if(e<-745.1332191019411)return 0;let t,n,r,i=Math.abs(e);if(i>.34657359027997264)r=Math.trunc(1.4426950408889634*e+(e<0?-.5:.5)),t=e-r*f,n=r*p,e=t-n;else if(i>3.7252902984e-9)r=0,t=e,n=0;else return 1+e;let a=e*e,o=e-a*(.16666666666666602+a*(-.0027777777777015593+a*(6613756321437934e-20+a*(-16533902205465252e-22+a*4.1381367970572385e-8)))),s=1+(e*o/(2-o)-n+t);return r===0?s:m(s,r)}function g(e){if(Number.isNaN(e)||e<0)return NaN;if(e===0)return-1/0;if(e===1/0)return 1/0;let t=0;e<22250738585072014e-324&&(e*=0x40000000000000,t-=54);let a=n(e),o=i(e);a+=614242,t+=(a>>20)-1023,a=(a&0xfffff)+0x3fe6a09e,e=r(a,o);let s=e-1,c=.5*s*s,l=s/(2+s),u=l*l,d=u*u,m=d*(.3999999999940942+d*(.22222198432149784+d*.15313837699209373));return l*(c+(u*(.6666666666666735+d*(.2857142874366239+d*(.1818357216161805+d*.14798198605116586)))+m))+t*p-c+s+t*f}function _(e,t){if(t===0||e===1)return 1;if(Number.isNaN(e)||Number.isNaN(t))return NaN;if(e===0)return t>0?0:1/0;if(e<0){if(!Number.isInteger(t))return NaN;let n=h(t*g(-e));return t%2==0?n:-n}return t===1?e:t===2?e*e:t===.5?Math.sqrt(e):h(t*g(e))}function v(e,t){return Math.sqrt(e*e+t*t)}function y(e){if(e>20)return 1;if(e<-20)return-1;let t=h(2*e);return(t-1)/(t+1)}const b=6.283185307179586;function x(e){return e-b*Math.floor((e+Math.PI)/b)}var S=class{cfg;y=/* @__PURE__ */ new Float64Array(4);t=0;eTarget=0;tau=2;controlled=!0;damping=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]],f=o-s,p=d(f),m=u(f),h=t+n*m*m,g=(i*c-r*l*p)/(r*r*i*h),_=(r*(t+n)*l-i*n*c*p)/(r*i*i*n*h);return{w1:g,w2:_,T:.5*(c*g+l*_),V:(t+n)*a*r*(1-d(o))+n*a*i*(1-d(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],f=e[3],p=s-c,m=d(p),h=u(p),g=n+r*h*h,_=(a*l-i*f*m)/(i*i*a*g),v=(i*(n+r)*f-a*r*l*m)/(i*a*a*r*g),y=l*f*h/(i*a*g),b=(a*a*r*l*l+i*i*(n+r)*f*f-2*i*a*r*l*f*m)*u(2*p)/(2*i*i*a*a*g*g),x=.5*(l*_+f*v),S=(n+r)*o*i*(1-d(s))+r*o*a*(1-d(c)),C=0;if(this.controlled){let e=.02*this.vTop,t=4/this.tau;C=(this.eTarget-(x+S))/(this.tau*(2*x+e)),C>t?C=t:C<-t&&(C=-t)}C-=this.damping,t[0]=_,t[1]=v,t[2]=-(n+r)*o*i*u(s)-y+b+C*l,t[3]=-r*o*a*u(c)+y-b+C*f}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,f=0;for(let e=0;e<1e3&&(c=(2*t()-1)*s,l=(2*t()-1)*s,f=this.derived([c,l,0,0]).V,!(f<.9*o));e++)c=l=0,f=0;let p=o-f,m=t()*2*Math.PI,h=d(m),g=u(m),_=d(c-l),v=(n+r)*i*i,y=r*i*a*_,b=r*a*a,x=.5*(v*h*h+2*y*h*g+b*g*g),S=Math.sqrt(p/x),C=S*h,w=S*g;this.y[0]=c,this.y[1]=l,this.y[2]=v*C+y*w,this.y[3]=y*C+b*w,this.t=0}};function C(e){return x(e)}function w(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}const T={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};Object.keys(T);const E=[`C`,`C#`,`D`,`D#`,`E`,`F`,`F#`,`G`,`G#`,`A`,`A#`,`B`];function D(e){return 440*_(2,(e-69)/12)}function O(e,t,n){if(t===`harmonic series`){let t=D(n+12*Math.floor((24-n)/12));return 69+12*g(Math.max(1,Math.round(D(e)/t))*t/440)/g(2)}let r=T[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}function k(e,t,n,r=0){let i=e.thetaRange,a=e.pitchSource===`absolute`?Math.min(1,Math.abs(t)/i):Math.max(0,Math.min(1,.5+.5*t/i));e.invertPitch&&(a=1-a),a=_(a,e.pitchCurve);let o=e.pitchLow,s=e.pitchHigh,c=E.indexOf(e.root),l=O(o+(s-o)*a+12*r,e.scale,c),u=Math.min(1,Math.abs(n)/e.p2Ref),d=e.loudFloor;return{midi:l,velocity:d+(1-d)*_(u,e.loudCurve)}}const A=e=>e.geometry===`membrane`||e.geometry===`plate`||e.geometry===`disc`,j=(...e)=>t=>e.includes(t.geometry),M=(...e)=>t=>e.includes(t.exciter),N=[`bow`,`reed`,`selfosc`,`noise`],P=[[`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`]],F=[[`sine`,`Sine`],[`tri`,`Triangle`],[`saw`,`Saw`],[`square`,`Square`],[`sh`,`Sample & hold`],[`smooth`,`Smooth random`]];function I(e){let t=t=>t[`lfo${e}Target`]!==`off`;return[{kind:`enum`,id:`lfo${e}Target`,label:`LFO ${e} →`,group:`Modulation`,options:P,def:`off`},{kind:`enum`,id:`lfo${e}Shape`,label:`Shape`,group:`Modulation`,options:F,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 L=[{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:j(`plate`)},{kind:`num`,id:`powerExp`,label:`Exponent p`,group:`Body`,min:.3,max:3,def:1.5,model:!0,show:j(`free`)},{kind:`num`,id:`discExp`,label:`Chladni exponent`,group:`Body`,min:1,max:2.5,def:2,model:!0,show:j(`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&&A(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:A},{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:M(`strike`)},{kind:`num`,id:`hardness`,label:`Contact time`,group:`Exciter`,min:.05,max:20,def:1,scale:`log`,unit:`ms`,show:M(`strike`,`impulse`)},{kind:`num`,id:`feltExp`,label:`Felt exponent`,group:`Exciter`,min:1,max:4,def:2.5,show:M(`strike`)},{kind:`num`,id:`bowForce`,label:`Bow force`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:M(`bow`)},{kind:`num`,id:`bowSpeed`,label:`Bow speed`,group:`Exciter`,min:0,max:2,def:.4,scale:`pow2`,show:M(`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:M(`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:M(`reed`)},{kind:`num`,id:`reedGain`,label:`Reed opening`,group:`Exciter`,min:0,max:2,def:.5,show:M(`reed`)},{kind:`num`,id:`breath`,label:`Breath noise`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`,show:M(`reed`)},{kind:`num`,id:`selfGain`,label:`Negative damping`,group:`Exciter`,min:0,max:4,def:.5,scale:`pow2`,show:M(`selfosc`)},{kind:`num`,id:`selfSat`,label:`Saturation level`,group:`Exciter`,min:.02,max:4,def:.5,scale:`log`,show:M(`selfosc`)},{kind:`num`,id:`noiseLevel`,label:`Noise level`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:M(`noise`)},{kind:`num`,id:`noiseColor`,label:`Noise cutoff`,group:`Exciter`,min:50,max:16e3,def:3e3,scale:`log`,unit:`Hz`,show:M(`noise`,`reed`,`bow`)},{kind:`num`,id:`attack`,label:`Attack`,group:`Exciter`,min:1,max:3e3,def:40,scale:`log`,unit:`ms`,show:M(...N)},{kind:`num`,id:`release`,label:`Release`,group:`Exciter`,min:5,max:5e3,def:150,scale:`log`,unit:`ms`,show:M(...N)},{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},...I(1),...I(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:A},{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(L.map(e=>[e.id,e])),Object.fromEntries(L.map(e=>[e.id,e.def])),L.filter(e=>e.model).map(e=>e.id);const R={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};[...[{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:{...R,modes:128,inharm:4e-5,exPos:.09,vibDepth:16,vibRate:5.2,soundbox:`cello`}},{name:`Violin`,category:`Instrument`,note:67,p:{...R,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:{...R,modes:96,inharm:3e-5,exPos:.1,vibDepth:15,vibRate:5.5,soundbox:`viola`}},{name:`Double bass`,category:`Instrument`,note:36,p:{...R,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:{...R,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}}].map(e=>`modal: ${e.name}`)];const z=.002,ee=(t,n,r)=>{let i=new S({m1:1,l1:1,g:1,m2:t.massRatio,l2:t.lengthRatio});i.randomize(w(t,0),e(n)),i.tau=t.tau;let a=t.speed,o=t.duration,s=t.restEnergy,c=t.finalHold+t.finalFade+.3,l=i.y,u=0,d=C(l[0]),f=l[1],p=l[3],m=null,h=null,g=0,_=0,v=0;function y(){i.eTarget=w(t,u)*i.vTop;let e=u;i.step(z),u+=z/a;let n=C(l[0]);if(m===null&&d<0&&n>=0&&n-d<Math.PI){let a=-d/(n-d),o=e+a*(u-e),s=C(f+a*(l[1]-f)),c=(p+a*(l[3]-p))/i.p2Scale;r.event({t:o,kind:`x`,th2:s,p2:c});let{midi:m,velocity:_}=k(t,s,c);h=r.note(0,o,m,_,t.noteLength)??h,g++}m===null&&u>=o&&(i.energyNorm()<s||u>=o+10)&&(m=u,h&&r.hold(h,h.t,t.finalHold,t.finalFade),r.end(u+c)),d=n,f=l[1],p=l[3];let y=i.energyNorm();u>=_&&(r.frame(0,u,[l[0],l[1],y]),_=u+.0010416666666666667),u>=v&&(v=u+.1,r.info(u,{"energy target":w(t,u).toFixed(4),energy:y.toFixed(4),notes:String(g)}))}return{get time(){return u},advance(e){for(;u<e;)y()}}};function B(e){return Math.max(1,Math.min(20,Math.round(e.orbitCount)))}function te(e){let t=[],n=[];for(let r=0;r<B(e);r++){let i=e[`slot${r%6+1}Instrument`],a=t.indexOf(i);a<0&&(a=t.push(i)-1),n.push(a)}return{names:t,stemOf:n}}const V=.003,ne=(t,n,r)=>{let i=t.speed,a=t.duration,o=t.restEnergy,s=t.finalHold+t.finalFade+.3,{stemOf:c}=te(t),l=Math.max(1e-4,w(t,0)),u=Array.from({length:B(t)},(r,i)=>{let a=new S({m1:1,l1:1,g:1,m2:t.massRatio,l2:t.lengthRatio});return a.randomize(l,e(n*1009+i*7919+1)),a.tau=t.tau,{pend:a,prev:C(a.y[0]),prevTh2:a.y[1],prevP2:a.y[3],lastNote:null,restAt:null,stem:c[i],octave:t[`slot${i%6+1}Octave`]}}),d=0,f=null,p=0,m=0,h=0,g=[];function _(){let e=w(t,d),n=d;d+=V/i,u.forEach((i,s)=>{let c=i.pend,l=c.y;c.eTarget=e*c.vTop,c.step(V);let u=C(l[0]);if(i.restAt===null&&i.prev<0&&u>=0&&u-i.prev<Math.PI){let e=-i.prev/(u-i.prev),a=n+e*(d-n),o=C(i.prevTh2+e*(l[1]-i.prevTh2)),f=(i.prevP2+e*(l[3]-i.prevP2))/c.p2Scale;r.event({t:a,kind:`x`,o:s,th2:o,p2:f});let{midi:m,velocity:h}=k(t,o,f,i.octave);i.lastNote=r.note(i.stem,a,m,h,t.noteLength)??i.lastNote,p++}i.restAt===null&&d>=a&&(c.energyNorm()<o||d>=a+10)&&(i.restAt=d,i.lastNote&&r.hold(i.lastNote,i.lastNote.t,t.finalHold,t.finalFade)),i.prev=u,i.prevTh2=l[1],i.prevP2=l[3]}),f===null&&u.every(e=>e.restAt!==null)&&(f=d,r.end(d+s));let c=0,l=0;for(let e of u){let t=e.pend.energyNorm();c+=t,l=Math.max(l,t)}let _=c/u.length;if(d>=m){m=d+.03333333333333333,g.length=0,g.push(_,l);for(let e of u)g.push(e.pend.y[0],e.pend.y[1],e.pend.y[2],e.pend.y[3],+(e.restAt===null));r.frame(0,d,g)}d>=h&&(h=d+.1,r.info(d,{"energy target":e.toFixed(4),"energy (mean)":_.toFixed(4),notes:String(p),"at rest":`${u.filter(e=>e.restAt!==null).length} / ${u.length}`}))}return{get time(){return d},advance(e){for(;d<e;)_()}}},H=.002;function re(e,t,n,r){let i=new S(e);return i.controlled=!1,i.y[0]=t,i.y[1]=n+r,i.y[2]=0,i.y[3]=0,i}function U(e,t){return[e.l1*u(t[0])+e.l2*u(t[1]),e.l1*d(t[0])+e.l2*d(t[1])]}function W(e,t,n,r,i,a){let o=re(e,t,n,-r/2),s=re(e,t,n,r/2);for(let t=0;t<a;t+=H){o.step(H),s.step(H);let[n,r]=U(e,o.y),[a,c]=U(e,s.y);if(v(n-a,r-c)>i)return t+H}return 1/0}function ie(e,t,n,r,i){let a=3*r+10,o=1e-15,s=.01;if(W(e,t,n,o,i,a)<=r)return{offset:o,separatesAt:W(e,t,n,o,i,a)};if(W(e,t,n,s,i,a)>=r)return{offset:s,separatesAt:W(e,t,n,s,i,a)};for(let c=0;c<16;c++){let c=Math.sqrt(o*s);W(e,t,n,c,i,a)>r?o=c:s=c}let c=Math.sqrt(o*s);return{offset:c,separatesAt:W(e,t,n,c,i,a)}}function ae(e,t){let n=Math.PI/180,r=e.releaseAngle*n,i=e.jitter*n;return t?[r+(2*t()-1)*i,r+(2*t()-1)*i]:[r,r]}function oe(e,t){let n=e.pitchLow,r=e.pitchHigh,i=E.indexOf(e.root),a=!!e.directionChords,o=a?2*t:t,s=[];if(e.scale===`continuous`)s=Array.from({length:Math.max(o,2)},(e,t)=>n+(r-n)*t/Math.max(1,Math.max(o,2)-1));else for(let t=Math.ceil(n);t<=r;t++)Math.abs(O(t,e.scale,i)-t)<1e-6&&s.push(t);s.length||(s=[O((n+r)/2,e.scale,i)]);let c=Array.from({length:o},(e,t)=>s[o>1?Math.round(t*(s.length-1)/(o-1)):Math.floor(s.length/2)]);return a?{right:c.filter((e,t)=>t%2==0),left:c.filter((e,t)=>t%2==1)}:{right:c,left:c}}const se=(t,n,r)=>{let i={m1:1,l1:1,g:1,m2:t.massRatio,l2:t.lengthRatio},a=t.speed,[o,s]=ae(t,e(n)),c=ie(i,o,s,t.separateAt*a,t.sepThreshold*(i.l1+i.l2)),l=Math.max(1,Math.round(t.count)),f=Array.from({length:l},(e,t)=>{let n=re(i,o,s,l>1?(t/(l-1)-.5)*c.offset:0);return{p:n,prevX:U(i,n.y)[0],E0:0,lastNote:null,restAt:null}}),p=Math.sqrt(2*f[0].p.energy()/i.m2),m=t.freeTime,h=t.dampTime,g=t.dampCurve,y=t.tau,b=t.restEnergy,x=t.finalHold+t.finalFade+.3,S=oe(t,l),C=180/Math.PI,w=`${(o*C).toFixed(2)}°, ${(s*C).toFixed(2)}°`,T=`${c.offset.toExponential(2)} rad → separate at ${(c.separatesAt/a).toFixed(1)} s`,D=0,k=null,A=0,j=0,M=0,N=new Float64Array(2*l);function P(e,n,a){let o=f[e],s=o.p.y,c=o.p.derived(),l=i.l1*d(s[0])*c.w1+i.l2*d(s[1])*c.w2,m=i.l1*u(s[0])*c.w1+i.l2*u(s[1])*c.w2,h=Math.min(1,v(l,m)/(t.loudRef*p)),g=t.loudFloor,y=g+(1-g)*_(h,t.loudCurve),b=t.pitchMode===`motion`?O(t.pitchLow+(t.pitchHigh-t.pitchLow)*h,t.scale,E.indexOf(t.root)):S[a>0?`right`:`left`][e];o.lastNote=r.note(+(a>0),n,b,y,t.noteLength)??o.lastNote,A++}function F(){let e=D;D+=H/a;let n=(e-m)/h;if(f.forEach((a,o)=>{let s=a.p;n>=0&&(s.controlled||(s.controlled=!0,a.E0=s.energy()),s.tau=y,s.eTarget=n<1?a.E0*_(1-n,g):0,s.damping=n>=1?1/y:0),s.step(H);let c=U(i,s.y)[0];a.restAt===null&&(a.prevX<0&&c>=0||a.prevX>0&&c<=0)&&P(o,e+a.prevX/(a.prevX-c)*(D-e),c>a.prevX?1:-1),a.prevX=c,a.restAt===null&&n>=1&&(s.energyNorm()<b||D>=m+h+10)&&(a.restAt=D,a.lastNote&&r.hold(a.lastNote,a.lastNote.t,t.finalHold,t.finalFade))}),k===null&&f.every(e=>e.restAt!==null)&&(k=D,r.end(D+x)),D>=j&&(j=D+.008333333333333333,f.forEach((e,t)=>{N[2*t]=e.p.y[0],N[2*t+1]=e.p.y[1]}),r.frame(0,D,N)),D>=M){M=D+.1;let e=k===null?D<m?`swinging`:D<m+h?`damping`:`settling`:`at rest`;r.info(D,{phase:e,"energy (mean)":(f.reduce((e,t)=>e+t.p.energyNorm(),0)/l).toFixed(4),notes:String(A),release:w,"offset (outermost)":T,"at rest":`${f.filter(e=>e.restAt!==null).length} / ${l}`})}}return{get time(){return D},advance(e){for(;D<e;)F()}}},G=.002;function ce(e,t,n,r){let i=new S(e);return i.controlled=!1,i.y[0]=Math.PI+r*t,i.y[1]=Math.PI+r*t*n,i}function K(e,t){return[e.l1*u(t[0])+e.l2*u(t[1]),e.l1*d(t[0])+e.l2*d(t[1])]}function le(e,t,n,r,i){let a=ce(e,t,n,1);for(let t=0;t<i;t+=G)if(a.step(G),Math.abs(K(e,a.y)[0])>r)return t+G;return 1/0}function ue(e,t,n,r){let i=3*n+10,a=n=>le(e,n,t,r,i),o=[];for(let e=0;e<=58;e++){let t=_(10,-15+.25*e);o.push({d:t,t:a(t)})}let s=[...o];for(let e=0;e+1<o.length;e++){let t=o[e],r=o[e+1];if(t.t>n&&r.t<=n){for(let e=0;e<14;e++){let e=Math.sqrt(t.d*r.d),i=a(e);i>n?t={d:e,t:i}:r={d:e,t:i}}s.push(t,r)}}let c=e=>Math.abs(e.t-n),l=Math.min(...s.map(c)),u=s.filter(e=>c(e)<=l+.01*n).reduce((e,t)=>t.d<e.d?t:e);return{nudge:u.d,tipsAt:u.t}}const de=(t,n,r)=>{let i={m1:1,l1:1,g:1,m2:t.massRatio,l2:t.lengthRatio},a=t.speed,o=e(n),s=o()<.5?-1:1,c=.6+.8*o(),l=ue(i,c,t.fallAfter*a,t.tipThreshold*(i.l1+i.l2)),f=ce(i,l.nudge,c,s),p=i.l1+i.l2,m=f.energy(),h=Math.sqrt(2*m/i.m2),g=t.freeTime+t.dampTime,y=t.restEnergy,b=t.minDepth*p,S=`${l.nudge.toExponential(2)} rad ${s>0?`→`:`←`} (shape ${c.toFixed(2)}), tips at ${(l.tipsAt/a).toFixed(1)} s`,C=(()=>{if(!t.heightNotes)return[];let e=t.heightLow,n=t.heightHigh,r=E.indexOf(t.root),i=[];for(let a=Math.ceil(e);a<=n;a++)(t.scale===`continuous`||Math.abs(O(a,t.scale,r)-a)<1e-6)&&i.push(a);let a=Math.max(1,Math.round(t.heightStep));return i.filter((e,t)=>t%a===0)})(),w=e=>t.heightLow+(t.heightHigh-t.heightLow)*((p-e)/(2*p)),T=e=>{let t=0;for(;t<C.length&&C[t]<e;)t++;return t},D=.3*(C.length>1?(C[C.length-1]-C[0])/(C.length-1):1),k=0,A=K(i,f.y)[0],j=x(f.y[1]-f.y[0]),M=!1,N=T(w(K(i,f.y)[1])),P=null,F=null,I=0,L=0,R=0,z=0,ee=0,B=e=>{let n=Math.max(0,Math.min(1,(e-t.freeTime)/t.dampTime)),r=n*n*(3-2*n);return t.dampBase+(t.dampEnd-t.dampBase)*r},te=()=>{let e=f.derived(),n=f.y,r=i.l1*d(n[0])*e.w1+i.l2*d(n[1])*e.w2,a=i.l1*u(n[0])*e.w1+i.l2*u(n[1])*e.w2,o=Math.min(1,v(r,a)/(t.loudRef*h)),s=t.loudFloor;return s+(1-s)*_(o,t.loudCurve)},V=(e,n)=>{let i=t.heightRamp>0?Math.max(0,Math.min(1,e/t.heightRamp)):1,a=t.heightRampFrom,o=a+(1-a)*i*i*(3-2*i),s=Math.min(1,Math.max(0,f.energy())/m);r.note(2,e,n,t.heightVel*o*_(s,t.heightFollow),t.heightLength),R++};function ne(){let e=k;k+=G/a,f.damping=B(e),f.step(G);let[n,o]=K(i,f.y);if(P===null&&C.length){let e=w(o);for(;N<C.length&&e>C[N]+D;)V(k,C[N++]);for(;N>0&&e<C[N-1]-D;)V(k,C[--N])}if(P===null&&Math.abs(o)<=b&&(A<0&&n>=0||A>0&&n<=0)){let i=e+A/(A-n)*(k-e);if(L++,t.click){let e=t.clickMaxVel*te();r.note(1,i,t.clickPitch,e,t.clickLength),r.event({t:i,kind:`ring`,x:0,y:o,strength:e,click:1})}}A=n;let s=x(f.y[1]-f.y[0]);if(Math.abs(s)>.05&&(M=!0),P===null&&M&&(j<0&&s>=0||j>0&&s<=0)&&Math.abs(s-j)<Math.PI){let i=e+j/(j-s)*(k-e);M=!1,I++;let a=I===1?t.firstVel:t.maxVel*te();F=r.note(0,i,t.extPitch,a,t.extLength)??F,r.event({t:i,kind:`ring`,x:n,y:o,strength:a,click:0})}if(j=s,P===null&&k>=g&&(f.energyNorm()<y||k>=g+15)&&(P=k,F&&r.hold(F,F.t,t.finalHold,t.finalFade),r.end(k+t.finalHold+t.finalFade+.3)),k>=z&&(r.frame(0,k,[f.y[0],f.y[1]]),z=k+.0020833333333333333),k>=ee){ee=k+.1;let e=t.freeTime,n=P===null?I===0?`falling`:k<e?`swinging`:k<g?`damping`:`settling`:`at rest`;r.info(k,{phase:n,energy:`${(f.energy()/m).toFixed(3)} of start`,"extension notes":String(I),clicks:String(L),"height notes":String(R),nudge:S,friction:`${B(k).toFixed(4)} /sim s`})}}return r.emitting&&r.frame(0,0,[f.y[0],f.y[1]]),{get time(){return k},advance(e){for(;k<e;)ne()}}};function fe(e,t,n){let r=e.y;if(!(t>0))return;let i=r[2],a=r[3],o=v(i,a);if(o>1e-9)i/=o,a/=o;else{let e=n()*2*Math.PI;i=d(e),a=u(e)}let s=e.derived(),c=i*s.w1+a*s.w2,l=e.derived([r[0],r[1],i,a]),f=i*l.w1+a*l.w2,p=(-c+Math.sqrt(Math.max(0,c*c+2*f*t)))/f;r[2]+=p*i,r[3]+=p*a}function pe(e,t,n,r){let{l1:i,l2:a,m2:o}=e.cfg,s=e.y,c=i+a,l=Math.sqrt(2*e.vTop/o)+1e-9,f=u(s[0]),p=d(s[0]),m=u(s[1]),h=d(s[1]);switch(t){case`x2`:return(i*f+a*m)/c;case`y2`:return-(i*p+a*h)/c;case`vx2`:return(i*p*n+a*h*r)/l;case`vy2`:return(i*f*n+a*m*r)/l;case`x1`:return f;case`vx1`:return i*p*n/l;case`θ1`:return x(s[0])/Math.PI;case`θ2`:return x(s[1])/Math.PI;case`θ2−θ1`:return x(s[1]-s[0])/Math.PI;case`ω1`:return n*i/l;case`ω2`:return r*a/l;case`p1`:return s[2]/(l*(1+o)*i*i+1e-9);case`p2`:return s[3]/(l*o*a*a+1e-9);case`speed2`:return v(i*p*n+a*h*r,i*f*n+a*m*r)/l}}var me=class{x=0;y=0;run(e,t){let n=e-this.x+t*this.y;return this.x=e,this.y=n,n}};const q=48e3;function he(e,t){let n=1+e,r=e*t,i=e*t*t,a=1+e,o=e*t,s=n*i-r*r,c=(a*i+o*n)/s,l=a*o/s,u=Math.sqrt(Math.max(0,c*c-4*l));return[Math.sqrt((c-u)/2),Math.sqrt((c+u)/2)]}function ge(e,t){let n=1e-4,r=1e4,i=e=>{let[n,r]=he(e,t);return r/n};if(i(n)>=e)return n;if(i(r)<=e)return r;for(let t=0;t<80;t++){let t=Math.sqrt(n*r);i(t)<e?n=t:r=t}return Math.sqrt(n*r)}function _e(e){let[t,n]=e.split(`/`).map(Number);return n?t/n:t}function ve(e,t,n,r,i){let a=ge(n,r),[o,s]=he(a,r),c=2*Math.PI*e*t,l=o*i/c,u=l*l;return{l1:u,l2:r*u,m2:a,lower:e*t,upper:e*t*(s/o)}}function ye(e,t,n,r){let[i]=he(ge(n,r),r);return 2*Math.PI*e*t/i}function be(e,t,n){return e.trim().split(/\s+/).filter(Boolean).map(e=>{let r=[];for(let i=0;i<e.length;i++)/[1-6]/.test(e[i])&&r.push({i:Number(e[i])-1,add:t*(e[i+1]===`!`?n:1)});return r})}const xe=e=>e.stepBeats*60/Math.max(1,e.tempo),Se=e=>.4+be(e.score,0,1).length*xe(e);function Ce(e){let t=e.basePitch,n=Array.from({length:6},(t,n)=>({ratio:_e(e[`ratio${n+1}`]),partial:_e(e[`partial${n+1}`]),shape:e[`shape${n+1}`]})),r=n.reduce((e,t)=>t.ratio<e.ratio?t:e),i=ye(t,r.ratio,r.partial,r.shape);return{k:i,built:n.map(e=>ve(t,e.ratio,e.partial,e.shape,i))}}const we={"01-poincare":ee,"02-orbits":ne,"03-divergence":se,"04-descent":de,"05-ensemble":(t,n,r)=>{let{k:i,built:a}=Ce(t),o=e(n),s=t.signal,c=h(t.gain*.11512925464970229),l=1-2*Math.PI*t.dcCut/q,f=be(t.score,t.pulseAdds,t.accent),p=xe(t),m=Se(t)+t.tail,g=Math.min(t.fade,t.tail),_=i/q,v=a.map((e,n)=>{let r=new S({m1:1,m2:e.m2,l1:e.l1,l2:e.l2,g:1});r.controlled=!1;let a=t[`ring${n+1}`];r.damping=a>0?13.8156/(a*i):0;let o=Math.max(1,Math.ceil(40*e.upper/q)),s=(t.spread*(2*n/5-1)+1)*Math.PI/4,c=h(t[`level${n+1}`]*.11512925464970229);return{p:r,dc:new me,sub:o,h:_/o,gl:d(s)*c,gr:u(s)*c}}),b=0,x=0,C=!1,w=/* @__PURE__ */ new Float64Array(24),T=/* @__PURE__ */ new Float64Array(12);function E(e){C||(C=!0,r.end(m));let t=Math.round(e*q)-b;if(t<=0)return;let n=new Float32Array(t),i=new Float32Array(t);for(let e=0;e<t;e++,b++){let t=b/q;if(x<f.length&&t>=.4+x*p){for(let e of f[x]){let n=v[e.i];n&&(fe(n.p,e.add*n.p.vTop,o),r.event({t,kind:`push`,i:e.i}))}x++}let a=0,h=0;for(let e of v){for(let t=0;t<e.sub;t++)e.p.step(e.h);Number.isFinite(e.p.y[0])||e.p.y.fill(0);let t=e.p.derived(),n=y(c*e.dc.run(pe(e.p,s,t.w1,t.w2),l));a+=e.gl*n,h+=e.gr*n}let _=Math.max(0,Math.min(1,(m-t)/g));n[e]=a*_*_,i[e]=h*_*_,b%6==0&&(v.forEach((e,t)=>{let n=e.p.y,r=e.p.cfg;T[2*t]=r.l1*u(n[0])+r.l2*u(n[1]),T[2*t+1]=r.l1*d(n[0])+r.l2*d(n[1])}),r.frame(1,t,T)),b%400==0&&(v.forEach((e,t)=>{let n=e.p.y,r=e.p.cfg,i=r.l1*u(n[0]),a=r.l1*d(n[0]);w.set([i,a,i+r.l2*u(n[1]),a+r.l2*d(n[1])],4*t)}),r.frame(0,t,w),r.info(t,{score:`step ${x} of ${f.length}`,energies:v.map(e=>e.p.energyNorm().toFixed(2)).join(` `)}))}r.audio(0,n,i)}return{get time(){return b/q},advance:E}}},Te=2.5;let J,Y,X=!1,Ee=0,De=4*q,Z=1/0,Oe=!1,ke=!1,Q=[],Ae=-1/0;const je=/* @__PURE__ */ new Map;let Me=[],Ne=null,Pe=-1/0;const Fe=/* @__PURE__ */ new Map,$=(e,t=[])=>self.postMessage(e,t),Ie=(e,t=[])=>Y.playerPort.postMessage(e,t),Le={get emitting(){return X},frame(e,t,n){if(!X)return;let r=je.get(e);r||je.set(e,r={stride:n.length+1,rows:[]}),r.rows.push(t);for(let e=0;e<n.length;e++)r.rows.push(n[e])},event(e){X&&Me.push(e)},info(e,t){X&&(Ne={t:e,info:t})},note(e,t,n,r,i){if(!X||!Q[e]||r<=0)return null;let a={t,type:`noteOn`,note:n,vel:Math.max(.01,Math.min(1,r))},o={t:t+i,type:`noteOff`,note:n,on:t};return Q[e].push(a,o),{stem:e,t,off:o}},hold(e,t,n,r){if(!X||!Q[e.stem])return;let i=Math.max(t,Ae),a=i+n+r;Q[e.stem].includes(e.off)&&e.off.t<a&&(e.off.t=a),Q[e.stem].push({t:i,type:`hold`,hold:n,fade:r})},cmd(e,t){X&&Q[e]&&Q[e].push(t)},audio(e,t,n){if(!X)return;let r=Fe.get(e)??Math.round(Y.from*48e3);Fe.set(e,r+t.length);let i=Math.round(Y.start*q);if(r+t.length<=i)return;let a=Math.max(0,i-r),o=a?t.slice(a):t,s=a?n.slice(a):n;Ie({type:`chunk`,stem:e,frame:r+a,L:o,R:s},[o.buffer,s.buffer])},end(e){Z===1/0&&(Z=e,$({type:`end`,t:e}),Ie({type:`end`,frame:Math.round(e*q)}))}};function Re(e,t=!1){if(e>Ae&&(Y.synthPorts.forEach((t,n)=>{if(!t)return;let r=Q[n];r.sort((e,t)=>e.t-t.t);let i=0;for(;i<r.length&&r[i].t<e;)i++;let a={type:`cmds`,cmds:r.splice(0,i),horizon:e};t.postMessage(a)}),Ae=e),!(!t&&J.time-Pe<.1)){Pe=J.time;for(let[e,t]of je){if(!t.rows.length)continue;let n=Float64Array.from(t.rows);t.rows=[],$({type:`frames`,track:e,stride:t.stride,data:n},[n.buffer])}Me.length&&($({type:`events`,events:Me}),Me=[]),Ne&&=($({type:`info`,t:Ne.t,info:Ne.info}),null)}}function ze(){ke||Oe||(ke=!0,setTimeout(Be,0))}function Be(){ke=!1;try{if(J.time>=Z){Re(Z+1,!0),Y.synthPorts.forEach(e=>e?.postMessage({type:`end`,t:Z})),Oe=!0;return}let e=Math.min(Z,(Ee+De)/q+Te+.5);if(J.time>=e)return;J.advance(Math.min(J.time+.05,e,Z)),Re(J.time-Te)}catch(e){Oe=!0,$({type:`error`,message:String(e?.stack??e)});return}ze()}self.onmessage=e=>{let t=e.data;if(t.type===`init`){Y=t,Q=t.synthPorts.map(()=>[]),Ee=Math.round(t.start*q),t.playerPort.onmessage=e=>{Ee=e.data.playhead,De=e.data.ahead,ze()};try{let e=we[t.comp];if(!e)throw Error(`no score for ${t.comp}`);J=e(t.P,t.seed,Le),t.from>0&&J.advance(t.from),X=!0,Ae=t.from}catch(e){Oe=!0,$({type:`error`,message:String(e?.stack??e)});return}ze()}};
site/assets/synthWorker-ByLtHWda.jsdeleted+0−1View file
@@ -1 +0,0 @@
1-const e=(e,t)=>e[t],t=(e,t)=>e[t],n=e=>e.geometry===`membrane`||e.geometry===`plate`||e.geometry===`disc`,r=(...e)=>t=>e.includes(t.geometry),i=(...e)=>t=>e.includes(t.exciter),a=[`bow`,`reed`,`selfosc`,`noise`],o=[[`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`]],s=[[`sine`,`Sine`],[`tri`,`Triangle`],[`saw`,`Saw`],[`square`,`Square`],[`sh`,`Sample & hold`],[`smooth`,`Smooth random`]];function c(e){let t=t=>t[`lfo${e}Target`]!==`off`;return[{kind:`enum`,id:`lfo${e}Target`,label:`LFO ${e} →`,group:`Modulation`,options:o,def:`off`},{kind:`enum`,id:`lfo${e}Shape`,label:`Shape`,group:`Modulation`,options:s,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 l=[{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:r(`plate`)},{kind:`num`,id:`powerExp`,label:`Exponent p`,group:`Body`,min:.3,max:3,def:1.5,model:!0,show:r(`free`)},{kind:`num`,id:`discExp`,label:`Chladni exponent`,group:`Body`,min:1,max:2.5,def:2,model:!0,show:r(`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&&n(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:n},{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:i(`strike`)},{kind:`num`,id:`hardness`,label:`Contact time`,group:`Exciter`,min:.05,max:20,def:1,scale:`log`,unit:`ms`,show:i(`strike`,`impulse`)},{kind:`num`,id:`feltExp`,label:`Felt exponent`,group:`Exciter`,min:1,max:4,def:2.5,show:i(`strike`)},{kind:`num`,id:`bowForce`,label:`Bow force`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:i(`bow`)},{kind:`num`,id:`bowSpeed`,label:`Bow speed`,group:`Exciter`,min:0,max:2,def:.4,scale:`pow2`,show:i(`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:i(`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:i(`reed`)},{kind:`num`,id:`reedGain`,label:`Reed opening`,group:`Exciter`,min:0,max:2,def:.5,show:i(`reed`)},{kind:`num`,id:`breath`,label:`Breath noise`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`,show:i(`reed`)},{kind:`num`,id:`selfGain`,label:`Negative damping`,group:`Exciter`,min:0,max:4,def:.5,scale:`pow2`,show:i(`selfosc`)},{kind:`num`,id:`selfSat`,label:`Saturation level`,group:`Exciter`,min:.02,max:4,def:.5,scale:`log`,show:i(`selfosc`)},{kind:`num`,id:`noiseLevel`,label:`Noise level`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:i(`noise`)},{kind:`num`,id:`noiseColor`,label:`Noise cutoff`,group:`Exciter`,min:50,max:16e3,def:3e3,scale:`log`,unit:`Hz`,show:i(`noise`,`reed`,`bow`)},{kind:`num`,id:`attack`,label:`Attack`,group:`Exciter`,min:1,max:3e3,def:40,scale:`log`,unit:`ms`,show:i(...a)},{kind:`num`,id:`release`,label:`Release`,group:`Exciter`,min:5,max:5e3,def:150,scale:`log`,unit:`ms`,show:i(...a)},{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},...c(1),...c(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:n},{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(l.map(e=>[e.id,e]));const u=Object.fromEntries(l.map(e=>[e.id,e.def])),d=l.filter(e=>e.model).map(e=>e.id),f=Math.SQRT2,p=Math.PI;function m(e,t){let n=Math.ceil(Math.abs(t)+e)+24,r=0;for(let i=0;i<=n;i++){let a=p*i/n;r+=(i===0||i===n?.5:1)*Math.cos(e*a-t*Math.sin(a))}return r/n}function h(e,t){let n=[],r=e===0?.5:e,i=m(e,r);for(let a=r+.05;a<=t;a+=.05){let t=m(e,a);if(i*t<0){let t=r,o=a,s=i;for(let n=0;n<50;n++){let n=.5*(t+o),r=m(e,n);s*r<=0?o=n:(t=n,s=r)}n.push(.5*(t+o))}r=a,i=t}return n}const g=[4.730040745,7.853204624,10.99560784,14.13716549,17.27875966],_=e=>e<g.length?g[e]:(2*e+3)*p/2;function v(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 y=[[.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 b(e,t,n,r,i=2){let a=new Float64Array(t),o=new Float64Array(t),s={kind:e,N:t,ratios:a,wavenum:o,aspect:n};switch(e){case`string`:case`free`:for(let n=0;n<t;n++){let t=n+1;a[n]=e===`string`?t:t**+r,o[n]=t}return{...s,view:`line`,dim:1,shape:(e,t)=>f*Math.sin((e+1)*p*t)};case`tube_co`:for(let e=0;e<t;e++)a[e]=2*e+1,o[e]=(2*e+1)/2;return{...s,view:`line`,dim:1,shape:(e,t)=>f*Math.cos((2*e+1)*p*t/2)};case`tube_oo`:for(let e=0;e<t;e++)a[e]=e+1,o[e]=e+1;return{...s,view:`line`,dim:1,shape:(e,t)=>f*Math.cos((e+1)*p*t)};case`bar`:{let e=_(0),n=new Float64Array(t),r=2048;for(let i=0;i<t;i++){let t=_(i);a[i]=(t/e)**2,o[i]=t/p;let s=0;for(let e=0;e<r;e++)s+=v(i,t,(e+.5)/r)**2;n[i]=1/Math.sqrt(s/r)}return{...s,view:`line`,dim:1,shape:(e,t)=>n[e]*v(e,_(e),t)}}case`ring`:{let e=[],n=[],r=0,i=0,c=2;for(;e.length<t;){r<y.length?[i,c]=y[r]:(i*=1.09,c+=+(r%2==0));for(let s=0;s<2&&e.length<t;s++)a[e.length]=i*(s===0?1:1+6e-4*(1+r%3)),o[e.length]=2*c,e.push(c),n.push(s);r++}return{...s,view:`ring`,dim:1,shape:(t,r)=>{let i=2*p*r*e[t];return f*(n[t]===0?Math.cos(i):Math.sin(i))}}}case`plate`:{let e=Math.ceil(3*Math.sqrt(t))+3,r=[];for(let t=1;t<=e;t++)for(let i=1;i<=e;i++)r.push([t*t+(i/n)**2,t,i]);r.sort((e,t)=>e[0]-t[0]);let i=new Int32Array(t),c=new Int32Array(t),l=r[0][0];for(let e=0;e<t;e++){let[t,s,u]=r[e];a[e]=t/l,o[e]=Math.sqrt(s*s+(u/n)**2),i[e]=s,c[e]=u}return{...s,view:`rect`,dim:2,shape:(e,t,n)=>2*Math.sin(i[e]*p*t)*Math.sin(c[e]*p*n)}}case`membrane`:{let e=2*Math.sqrt(t)+6,n=[];for(;;){n=[];for(let t=0;t<=Math.ceil(e);t++)for(let r of h(t,e))n.push([r,t,0]),t>0&&n.push([r,t,1]);if(n.length>=t)break;e*=1.3}n.sort((e,t)=>e[0]-t[0]||e[2]-t[2]);let r=n[0][0],i=new Int32Array(t),c=new Int32Array(t),l=new Float64Array(t),u=new Float64Array(t);for(let e=0;e<t;e++){let[t,s,d]=n[e];a[e]=t/r,o[e]=t/p,i[e]=s,c[e]=d,l[e]=t,u[e]=s===0?1/Math.abs(m(1,t)):f/Math.abs(m(s+1,t))}return S(s,i,c,l,u)}case`disc`:{let e=i,n=Math.ceil(Math.sqrt(2*t))+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 c=r.slice(0,t),l=c.reduce((e,t)=>Math.max(e,t[1]),0),u=c.reduce((e,t)=>Math.max(e,t[2]),0),d=[];for(let e=0;e<=l;e++)d.push(x(e,u+1));let f=new Int32Array(t),m=new Int32Array(t),h=new Float64Array(t),g=c[0][0];for(let e=0;e<t;e++){let[t,n,r,i]=c[e];a[e]=t/g,f[e]=n,m[e]=i,h[e]=d[n][n===0?r-1:r],o[e]=h[e]/p}return S(s,f,m,h,null)}}}function x(e,t){let n=t=>e===0?-m(1,t):.5*(m(e-1,t)-m(e+1,t)),r=[],i=e===0?.5:Math.max(.3,e*.8),a=n(i);for(let e=i+.05;r.length<t;e+=.05){let t=n(e);if(a*t<0){let t=i,o=e,s=a;for(let e=0;e<50;e++){let e=.5*(t+o),r=n(e);s*r<=0?o=e:(t=e,s=r)}r.push(.5*(t+o))}i=e,a=t}return r}function S(e,t,n,r,i){let a=e.N,o=Array(a).fill(null),s=i??new Float64Array(a),c=(e,n)=>{let a=o[e];if(!a){a=/* @__PURE__ */ new Float64Array(258);for(let n=0;n<=256;n++)a[n]=m(t[e],r[e]*n/256);if(a[257]=a[256],o[e]=a,!i){let n=0;for(let e=0;e<=256;e++)n+=(e===0||e===256?.5:1)*a[e]*a[e]*e/256/256;s[e]=1/Math.sqrt(Math.max(1e-12,(t[e]===0?2:1)*n))}}let c=n*256,l=Math.floor(c),u=c-l;return a[l]*(1-u)+a[l+1]*u};return{...e,view:`disk`,dim:2,shape:(e,r,i)=>{let a=2*r-1,o=2*i-1,l=Math.hypot(a,o);if(l>=1)return 0;let u=c(e,l),d=t[e],f=d===0?1:n[e]===0?Math.cos(d*Math.atan2(o,a)):Math.sin(d*Math.atan2(o,a));return s[e]*u*f}}}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 ee=e=>d.map(t=>String(e[t])).join(`|`);function T(n){let r=Math.round(e(n,`modes`)),i=b(t(n,`geometry`),r,e(n,`aspect`),e(n,`powerExp`),e(n,`discExp`)),a=Math.round(e(n,`seed`)),o=C(a*7919+13),s=e(n,`stretch`),c=e(n,`inharm`),l=e(n,`harmonize`),u=e(n,`jitter`),d=0;for(let e=0;e<r;e++)if(Math.abs(i.ratios[e]-1)<1e-9){d=e;break}let f=new Float64Array(r);for(let e=0;e<r;e++){let t=i.ratios[e]**+s;if(t*=Math.sqrt(1+c*t*t)/Math.sqrt(1+c),l>0){let e=t<.75?.5:Math.max(1,Math.round(t));t=t**(1-l)*e**+l}let n=w(o);e!==d&&u>0&&(t*=2**(u*n/1200)),f[e]=t}let p=Int32Array.from({length:r},(e,t)=>t).sort((e,t)=>f[e]-f[t]),m=new Float64Array(r),h=new Float64Array(r),g=0;for(let e=0;e<r;e++)m[e]=f[p[e]],h[e]=i.wavenum[p[e]],p[e]===d&&(g=e);let _=Math.min(r,Math.round(e(n,`nlModes`))),v=Math.round(e(n,`terms`)),y=C(a*104729+7),x=[],S=new Float64Array(v*_);for(let e=0;e<v;e++){let t=[],n=Math.max(2,Math.round(_*.75)),r=0;for(let e=0;e<n;e++){let e=Math.floor(y()*_),n=y()<.25?e:Math.floor(y()*_),i=w(y);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<_;t++){let n=w(y);S[e*_+t]=n,o+=n*n}o=1/Math.sqrt(o);for(let t=0;t<_;t++)S[e*_+t]*=o}let T=x.reduce((e,t)=>e+t.length,0),E=new Int32Array(v+1),D=new Int32Array(T),O=new Int32Array(T),te=new Float64Array(T),k=0;for(let e=0;e<v;e++){E[e]=k;for(let[t,n,r]of x[e])D[k]=t,O[k]=n,te[k]=r,k++}E[v]=k;let A=C(a*31337+1),j=new Float64Array(_),M=0;for(let e=0;e<_;e++)j[e]=w(A),M+=j[e]**2;for(let e=0;e<_;e++)j[e]/=Math.sqrt(M);let N=new Float64Array(r);for(let e=0;e<r;e++)N[e]=(A()<.5?-1:1)*(.5+.5*A());return{key:ee(n),geom:i,N:r,ratios:m,wavenum:h,pitchK:g,perm:p,Nnl:_,M:v,tStart:E,ti:D,tj:O,tv:te,tb:S,bx:j,rad:N,shape:(e,t,n)=>i.shape(p[e],t,n)}}const E={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 D(e,t,n,r=1){let i=E[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 O(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 te=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=D(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+=O(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 k=.5,A=1e-14,j=.002,M=.05,N=e=>{let t=Math.abs(e);return t+Math.log1p(Math.exp(-2*t))-Math.LN2},ne=6.907755,re=10**-9,ie=.1;var ae=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;nTune=0;cull=1/0;nNL=0;nNLTune=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;sw2=/* @__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;fast=!1;tc=0;tq=0;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`,`sw2`,`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,this.uncull()}uncull(){this.cull=1/0,this.nAct=this.nTune,this.nNL=this.nNLTune}};const oe=e=>440*2**((e-69)/12),se=e=>e<0?0:e>1?1:e,P=e=>e-Math.floor(e);var ce=class{sr;h;p={...u};model;voices=[];act=[];eps=A;vMax=0;vHold=0;psi=Math.sqrt(A);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 te;boxOut=/* @__PURE__ */ new Float64Array(2);constructor(e){this.sr=e,this.h=1/e,this.model=T(this.p);for(let e=0;e<16;e++){let t=new ae(e);t.alloc(this.model.N),this.voices.push(t)}}message(e){e.type===`params`?this.setParams(e.params):this.pending.push(e)}setParams(n){if(this.p={...u,...n},this.paramVersion++,ee(this.p)!==this.model.key){this.model=T(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 r=t(this.p,`soundbox`);r===`off`?(this.box.configure(``,1,1,this.sr),this.box.reset()):this.box.configure(r,e(this.p,`boxSize`),e(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(t){let n=this.voices.find(e=>e.active&&e.note===t);if(n)return n;let r=Math.round(e(this.p,`voices`)),i=this.voices.filter(e=>e.active);return i.length>=r?(i.sort((e,t)=>Number(e.gate)-Number(t.gate)||e.energy-t.energy||e.order-t.order),n=i[0]):n=this.voices.find(e=>!e.active),n.reset(),n.active=!0,n.glideMul=1,n.vibMul=1,n.vibPh=this.rand(),n.vibRateJ=1+.1*(this.rand()*2-1),n.note=t,n.baseHz=oe(t),n.held=n.sustained=n.touching=!1,n.gate=!1,n.dirtyTune=n.dirtyVec=!0,n.tunedPitch=-1,this.psiReset=!0,n}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.uncull(),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(n,r){n.uncull();let i=t(this.p,`exciter`),a=k*(e(this.p,`strength`)*r)**2;if(a<=0)return;let o=n.nAct,s=n.phiE,c=n.om,l=this.h;if(i===`strike`){let t=e(this.p,`hammerMass`),r=e(this.p,`hardness`)/1e3,i=e(this.p,`feltExp`),c=Math.sqrt(2*a/t),u=Math.sqrt(2*k/t)*r/Math.PI,d=0,f=0;for(let e=0;e<o;e++)d+=s[e]*n.q[e],f+=s[e]*(n.q[e]-n.qp[e])/l;let p=Math.sqrt(t);n.ham=!0,n.hamTimer=0,n.hamISM=1/p,n.hamK=t*(Math.PI/r)**2/u**(i-1),n.hamA=i,n.hz=d*p,n.hzp=(d-(f+c)*l)*p}else if(i===`pluck`){let e=0;for(let t=0;t<o;t++)e+=s[t]*s[t]/(c[t]*c[t]);if(e<=0)return;let t=Math.sqrt(2*a/e);for(let e=0;e<o;e++){let r=t*s[e]/(c[e]*c[e]);n.q[e]+=r,n.qp[e]+=r}this.psiReset=!0}else if(i===`impulse`){let t=e(this.p,`hardness`)/1e3,r=0,i=n.qn;for(let e=0;e<o;e++){let n=c[e]*t/2,a=1-(n/Math.PI)**2,o=n<1e-9?1:Math.abs(a)<1e-6?.5:Math.abs(Math.sin(n)/n/a);i[e]=s[e]*o,r+=i[e]*i[e]}if(r<=0)return;let u=Math.sqrt(2*a/r);for(let e=0;e<o;e++)n.qp[e]-=l*u*i[e];i.fill(0)}}tuneVoice(t){let n=this.model,r=n.N,i=this.h,a=this.p,o=t.baseHz*this.pitchMul*t.glideMul*t.vibMul,s=ne/e(a,`t60`),c=e(a,`hfDamp`),l=e(a,`damper`),u=!t.gate&&t.damped&&l<19.9?ne/l:0,d=.45*this.sr,f=0,p=0;for(let e=0;e<r;e++){let r=o*n.ratios[e],a=2*Math.PI*r;if(t.om[e]=a,r>=d){t.A[e]=t.B[e]=t.C[e]=t.sw[e]=t.sw2[e]=0;continue}f=e+1;let l=(s+c*(r/1e3)**2)*this.dampMul+u,m=Math.exp(-l*i);if(l<a)t.A[e]=2*m*Math.cos(Math.sqrt(a*a-l*l)*i);else{let n=Math.sqrt(l*l-a*a)*i;t.A[e]=m*(Math.exp(n)+Math.exp(-n))}t.B[e]=m*m,t.C[e]=i*i/(1+Math.tanh(l*i));let h=2-2*Math.cos(a*i),g=Math.max(0,Math.min(1,(3.6/h-1)/12));t.sw[e]=a*Math.sqrt(g),t.sw2[e]=a*a*g,g>0&&(p=e+1)}for(let e=f;e<r;e++)t.q[e]=t.qp[e]=0;t.nTune=f,t.nNLTune=Math.min(p,f),t.nAct=Math.min(f,t.cull),t.nNL=Math.min(t.nNLTune,t.nAct),t.omega1=2*Math.PI*o,t.Z0=2*o;let m=0;for(let e=0;e<f;e++)m+=t.phiE[e]*t.phiE[e]*t.C[e];t.wsum=m;let h=+Math.max(t.buzzPhi1,.05)/t.omega1,g=e(a,`buzz`);t.buzzGap=e(a,`buzzGap`)*h,t.buzzK=g>0?g*(2*Math.PI*4e3)**2*.1*h**(1-this.buzzA):0,t.tunedPitch=this.pitchMul,t.tunedDamp=this.dampMul,t.tunedGate=t.gate,t.tunedGlide=t.glideMul,t.tunedVib=t.vibMul,t.dirtyTune=!1}vecVoice(t){let n=this.model,r=n.N,i=this.p,a=t.posX>=0?t.posX:se(e(i,`exPos`)+this.posOff),o=t.posY>=0?t.posY:se(e(i,`exPosY`)+this.posOff),s=e(i,`exWidth`)*.15,c=e(i,`buzzPos`),l=e(i,`buzzPosY`),u=P(e(i,`pickup`)+this.pickOff),d=e(i,`pickupY`),f=e(i,`width`),p=P(u+.5*f),m=P(d+.37*f),h=e(i,`spread`),g=e(i,`tilt`)/6.0206;for(let e=0;e<r;e++){let i=Math.exp(-.5*(Math.PI*n.wavenum[e]*s)**2);t.phiE[e]=n.shape(e,a,o)*i,t.phiB[e]=n.shape(e,c,l);let f=n.ratios[e]**+g;t.wL[e]=((1-h)*n.shape(e,u,d)+h*n.rad[e])*f,t.wR[e]=((1-h)*n.shape(e,p,m)+h*n.rad[(e+1)%r]*(e%2?1:-1))*f}t.buzzPhi1=Math.abs(n.shape(n.pitchK,c,l)),t.beta=Math.max(.02,Math.min(a,1-a)),t.dirtyVec=!1,t.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(n,r){let i=this.p,a=e(i,`lfo${n+1}Rate`),o=this.lfoPh[n]+a*r;switch(o>=1&&(o-=Math.floor(o),this.lfoA[n]=this.lfoB[n],this.lfoB[n]=this.rand()*2-1),this.lfoPh[n]=o,t(i,`lfo${n+1}Shape`)){case`tri`:return 1-4*Math.abs(o-.5);case`saw`:return 2*o-1;case`square`:return o<.5?1:-1;case`sh`:return this.lfoB[n];case`smooth`:return this.lfoA[n]+(this.lfoB[n]-this.lfoA[n])*(.5-.5*Math.cos(Math.PI*o));default:return Math.sin(2*Math.PI*o)}}blockUpdate(n){let r=this.p,i=this.sr,a=n/i,o=this.bend*e(r,`bendRange`),s=1,c=0,l=0,u=e(r,`tension`),d=e(r,`cascade`),f=1,p=1,m=1;for(let n=0;n<2;n++){let i=t(r,`lfo${n+1}Target`);if(i===`off`)continue;let h=e(r,`lfo${n+1}Depth`),g=this.lfo(n,a)*h;switch(i){case`pitch`:o+=4*g;break;case`amp`:s*=Math.max(0,1+g);break;case`position`:c+=.5*g;break;case`pickup`:l+=.5*g;break;case`tension`:u*=Math.max(0,1+g);break;case`cascade`:d*=Math.max(0,1+g);break;case`damping`:f*=2**(3*g);break;case`feedback`:p*=Math.max(0,1+g);break;case`exciter`:m*=Math.max(0,1+g)}}this.pitchMul=2**(o/12),this.dampMul=f,this.ampMul=s,this.fbMul=p,this.excMul=m,this.kt=u,this.kc=this.model.M>0?d:0,this.cc=+e(r,`curvature`),this.ct=e(r,`crossTension`),this.cl=e(r,`crossLink`),this.crossOn=this.ct>0||this.cl>0,this.buzzTwo=t(r,`buzzSides`)===`two`;let h=t(r,`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]=e(r,`bowSpeed`)*.5,g[1]=+e(r,`bowForce`),g[2]=e(r,`bowNoise`)):this.law===2?(g[0]=e(r,`reedGain`)*2,g[1]=e(r,`reedPressure`),g[2]=e(r,`breath`)):this.law===3&&(g[0]=+e(r,`selfGain`),g[1]=e(r,`selfSat`)),this.envAtt=1-Math.exp(-1/(e(r,`attack`)/1e3*i)),this.envRel=1-Math.exp(-1/(e(r,`release`)/1e3*i));let _=Math.min(e(r,`noiseColor`),.45*i);this.noiseC=1-Math.exp(-2*Math.PI*_/i),this.noiseNorm=Math.sqrt(3*(2-this.noiseC)/this.noiseC),this.fbD=Math.max(1,Math.min(32767,Math.round(e(r,`fbDelay`)/1e3*i)));let v=2*Math.PI*Math.min(e(r,`fbFreq`),.45*i)/i,y=Math.sin(v)/(2*e(r,`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=c!==this.lastPosOff||l!==this.lastPickOff||this.vecVersion!==this.paramVersion;this.posOff=c,this.pickOff=l,this.lastPosOff=c,this.lastPickOff=l,this.vecVersion=this.paramVersion;let S=e(r,`vibDepth`),C=e(r,`vibRate`),w=e(r,`vibDelay`)/1e3;this.act.length=0;for(let e of this.voices)if(e.active){if(S>0){e.vibAge+=a;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))*a,e.vibPh-=Math.floor(e.vibPh);let r=2**(S*n*Math.sin(2*Math.PI*e.vibPh)/1200);(Math.abs(r/e.vibMul-1)>1e-5||n===0&&e.vibMul!==1)&&(e.vibMul=r)}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/k;o+=this.kt*k*.5*e*e*N(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)/k;o+=u*k*m*m*N(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}nlTension(e){let t=e.nNL,n=e.q,r=e.qp,i=e.sw2,a=0,o=0;for(let e=0;e<t;e++){let t=i[e]*n[e];a+=t*n[e],o+=t*r[e]}if(e.S=a,e.X=0,e.gz=0,e.fast=!0,a>0){let t=3/this.kt,n=a/k;e.Vv=this.kt*k*.5*t*t*N(n/t),e.tc=this.kt*t*Math.tanh(n/t),e.tq=e.tc===0?0:o,e.useG=!0}else e.Vv=0,e.tc=0,e.tq=0,e.useG=!1}lawEval(e){let t=0,n=0;if(this.law===1){let r=e-this.lwVb,i=Math.tanh(r/j),a=1+Math.abs(r)/M,o=.35+.65/a,s=-.65/(M*a*a)*(r>=0?1:-1);t=-this.lwF*i*o,n=-this.lwF*((1-i*i)/j*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(t,n,r,i=0){let a=Date.now(),o=r/this.sr;if(this.pending.length){let e=[];for(let t of this.pending)(`time`in t&&t.time!==void 0?t.time:0)<=i+o?this.handle(t):e.push(t);this.pending=e}this.blockUpdate(r);let s=this.act,c=this.h,l=c*c,u=1/c,d=this.p,f=e(d,`fbGain`)*this.fbMul,p=e(d,`fbSat`),m=e(d,`noiseLevel`),h=this.law,g=h===4||h===3||h===2&&e(d,`breath`)>0||h===1&&e(d,`bowNoise`)>0,_=this.box,v=_.n>0,y=v?e(d,`boxMix`):0,b=1-y,x=this.boxOut,S=.25*this.ampMul*u*10**(e(d,`level`)/20),C=32767,w=this.kt>0&&this.kt<=ie&&this.kc<=0&&!this.crossOn;for(let e=0;e<r;e++){let r=0,i=0,a=!1;for(let e=0;e<s.length;e++){let t=s[e];t.env+=((t.gate?t.vel:0)-t.env)*(t.gate?this.envAtt:this.envRel);let n=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],r=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=r,n+=p*t.Z0*Math.tanh(f*r/p)*t.env}h===3&&(n+=.001*t.Z0*t.env*e),h===4?n+=m*t.Z0*t.env*this.excMul*e*.5:h!==0&&(n+=this.solveLaw(t,n,e))}else t.fLaw=0;t.f=n,w&&!t.ham&&t.buzzK<=0?this.nlTension(t):(t.fast=!1,this.nl(t)),r+=t.Vv,i+=t.X,t.useG&&(a=!0)}if(this.crossOn&&s.length){let e=i/k;r+=k*3*3*N(e/3);let t=3*Math.tanh(e/3),n=this.ct,a=+this.cl,o=this.model.bx,c=this.model.Nnl;for(let e of s){let r=e.nNL,i=e.grad,s=e.q,l=e.sw;for(let e=0;e<r;e++)i[e]+=t*(n*l[e]*l[e]*s[e]+(e<c?a*o[e]*l[e]:0))}}let o=0;if(!a)this.psi=Math.sqrt(this.eps);else{r>this.vMax&&(this.vMax=r),this.psiReset&&(this.eps=.01);let e=Math.sqrt(2*r+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 n=0;for(let e of s){if(!e.useG)continue;if(e.fast){n+=e.tc*e.tq;continue}let t=e.nAct,r=e.grad,i=e.qp;for(let e=0;e<t;e++)n+=r[e]*i[e];e.ham&&(n+=e.gz*e.hzp)}n*=t;let i=this.psi,a=n/4-i,c=0,u=0;for(let e of s){if(!e.useG)continue;e.pred=!1;let n=e.nAct,r=e.q,i=e.qp,o=e.qn,s=e.A,d=e.B,f=e.C,p=e.phiE,m=e.f;if(e.fast){let l=e.nNL,h=e.sw2,g=e.tc*t;for(let e=0;e<l;e++){let t=g*h[e]*r[e],n=f[e],l=s[e]*r[e]-d[e]*i[e]+n*(p[e]*m+t*a);o[e]=l,c+=t*l,u+=n*t*t}for(let e=l;e<n;e++)o[e]=s[e]*r[e]-d[e]*i[e]+f[e]*p[e]*m;continue}let h=e.grad;for(let e=0;e<n;e++){let n=h[e]*t,l=s[e]*r[e]-d[e]*i[e]+f[e]*(p[e]*m+n*a);o[e]=l,c+=n*l,u+=f[e]*n*n}if(e.ham){let n=e.gz*t,r=2*e.hz-e.hzp+l*n*a;e.hzn=r,c+=n*r,u+=l*n*n}}let d=c/(1+u/4);o=d*t/4;for(let e of s){if(!e.useG||e.fast)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]*o;e.ham&&(e.hzn-=l*e.gz*o)}this.psi=i+(d-n)/2}let c=0,d=0;for(let e of s){let t=e.nAct,n=e.q,r=e.qp,i=e.qn,a=e.wL,s=e.wR,l=0,f=0;if(!e.useG){let o=e.A,c=e.B,u=e.C,d=e.phiE,p=e.f;if(e.pred){e.pred=!1;for(let e=0;e<t;e++){let t=i[e]+u[e]*d[e]*p;i[e]=t;let r=t-n[e];l+=a[e]*r,f+=s[e]*r}}else if(p!==0)for(let e=0;e<t;e++){let t=o[e]*n[e]-c[e]*r[e]+u[e]*d[e]*p;i[e]=t;let m=t-n[e];l+=a[e]*m,f+=s[e]*m}else for(let e=0;e<t;e++){let t=o[e]*n[e]-c[e]*r[e];i[e]=t;let u=t-n[e];l+=a[e]*u,f+=s[e]*u}e.ham&&(e.hzn=2*e.hz-e.hzp)}else if(e.fast){let r=e.nNL,c=e.sw2,u=e.C,d=e.tc*o;for(let e=0;e<r;e++){let t=i[e]-u[e]*c[e]*n[e]*d;i[e]=t;let r=t-n[e];l+=a[e]*r,f+=s[e]*r}for(let e=r;e<t;e++){let t=i[e]-n[e];l+=a[e]*t,f+=s[e]*t}}else for(let e=0;e<t;e++){let t=i[e]-n[e];l+=a[e]*t,f+=s[e]*t}c+=l,d+=f,e.fb[e.fbW]=.5*(l+f)*u,e.fbW=e.fbW+1&C;let p=e.qp;e.qp=e.q,e.q=e.qn,e.qn=p,e.ham&&(e.hzp=e.hz,e.hz=e.hzn)}v?(_.tick(.5*(c+d)*S,x),t[e]=b*c*S+y*x[0],n[e]=b*d*S+y*x[1]):(t[e]=c*S,n[e]=d*S)}this.blockEnd(r),this.cpuMs+=Date.now()-a,this.cpuWall+=o*1e3}blockEnd(t){let n=1/this.h,r=this.kc<=0&&this.kt<=ie&&!this.crossOn&&!(e(this.p,`fbGain`)>0);for(let t of this.act){let i=t.nAct,a=t.q,o=t.qp,s=t.om,c=0,l=0;for(let e=0;e<i;e++){let t=(a[e]-o[e])*n,r=.5*(t*t+s[e]*s[e]*a[e]*a[e]);c+=r,r>l&&(l=r)}if(r&&!t.ham&&t.buzzK<=0&&(this.law===0||t.env<=1e-6)){let e=l*re,r=i;for(;r>1;){let t=r-1,i=(a[t]-o[t])*n;if(.5*(i*i+s[t]*s[t]*a[t]*a[t])>e)break;r--}if(r<i){for(let e=r;e<i;e++)a[e]=o[e]=0;t.cull=r,t.nAct=r,t.nNL=Math.min(t.nNLTune,r)}}else t.cull!==1/0&&t.uncull();if(!Number.isFinite(c)||c>1e8){t.reset(),t.active=!1,this.psiReset=!0;continue}t.energy=c;let u=e(this.p,`glide`),d=1;if(u!==0){let e=4*c/k;d=2**(u*e/(1+e)/12)}(Math.abs(d/t.glideMul-1)>2e-5||d===1&&t.glideMul!==1)&&(t.glideMul=d),!t.gate&&!t.ham&&c<1e-10&&t.env<1e-4&&(t.active=!1)}let i=0;for(let e of this.act)e.active&&(i+=e.energy);this.vHold=Math.max(this.vMax,this.vHold*.95),this.vMax=0;let a=Math.max(A,.02*i+2*this.vHold);if(a<this.eps){let e=Math.max(a,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+=t,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])}};const F=48e3,I=.3;let L,R,z,B=0,le,V=0,ue=0,H=0,U=1/0,W=0,de=4*F,fe=!1;const G=[],pe=/* @__PURE__ */ new Map;let K=!1,q=1,J=1,me=1,Y=0,X=!1,Z=I*I,he=!1,ge=1/0,_e=1;self.onmessage=e=>{let t=e.data;t.type===`init`&&(R={...u,...t.sound},z=R,L=new ce(F),L.message({type:`params`,params:R}),B=t.stem,q=Math.max(1,t.slow??1),V=t.fromFrame,H=t.fromFrame,ue=t.sendFrame,W=t.sendFrame,le=t.playerPort,le.onmessage=e=>{W=e.data.playhead,de=e.data.ahead,ve()},t.scorePort.onmessage=e=>{let t=e.data;if(t.type===`cmds`){for(let e of t.cmds)G.push(e);H=Math.max(H,Math.floor(t.horizon*F))}else t.type===`end`&&(U=Math.round(t.t*F),H=Math.max(H,U));ve()})};function ve(){K||(K=!0,setTimeout(xe,0))}function ye(e){switch(e.type){case`noteOn`:L.message({type:`noteOn`,note:e.note,vel:e.vel}),pe.set(e.note,e.t);break;case`noteOff`:if(e.on!==void 0&&(pe.get(e.note)??-1/0)>e.on)break;L.message({type:`noteOff`,note:e.note});break;case`params`:z={...z,...e.params},L.message({type:`params`,params:z});break;case`bend`:L.message({type:`bend`,value:e.value});break;case`gain`:me=e.value,Y=e.tau,X=!!e.normalize;break;case`hold`:{if(he)break;he=!0;let t=e.hold+e.fade,n=Math.min(60,Math.max(R.t60,6*t)),r=n/R.t60;z={...z,t60:n,hfDamp:R.hfDamp/r},L.message({type:`params`,params:z}),ge=e.t+Math.max(e.hold,.005),_e=Math.max(.01,e.fade);break}}}const Q=/* @__PURE__ */ new Float32Array(128),$=/* @__PURE__ */ new Float32Array(128);function be(e,t,n){let r=V/F,i=(V+128)/F;for(;G.length&&G[0].t<i;)ye(G.shift());if(Q.fill(0),$.fill(0),L.process(Q,$,128,r),X){let e=0;for(let t=0;t<128;t++)e+=Q[t]*Q[t]+$[t]*$[t];e/=256,e>1e-10&&(Z+=(e-Z)*(1-Math.exp(-128/F/1.5)))}let a=X?Math.max(.05,Math.min(20,I/Math.sqrt(Z))):1,o=me*a,s=J;J=Y>0?J+(o-J)*(1-Math.exp(-128/F/Y)):o;for(let r=0;r<128;r++){let i=s+(J-s)*(r+1)/128,a=(V+r)/F;if(a>=ge){let e=Math.min(1,(a-ge)/_e),t=Math.cos(Math.PI/2*e);i*=t*t}e[n+r]=Q[r]*i,t[n+r]=$[r]*i}V+=128}function xe(){if(K=!1,!L)return;if(V>=U){fe||(fe=!0,Se({type:`done`,stem:B,frame:U}));return}let e=Math.min(H,W+de,U+128-1),t=Math.min(2048,Math.floor((e-V)/128)*128);if(t<=0)return;let n=V,r=new Float32Array(t),i=new Float32Array(t),a=performance.now();for(let e=0;e<t;e+=128)be(r,i,e);if(q>1){let e=performance.now()+(q-1)*(performance.now()-a);for(;performance.now()<e;);}if(n+t>ue){let e=Math.max(0,ue-n),t=e?r.slice(e):r,a=e?i.slice(e):i;Se({type:`chunk`,stem:B,frame:n+e,L:t,R:a},[t.buffer,a.buffer])}ve()}function Se(e,t=[]){le.postMessage(e,t)}
site/assets/synthWorker-DKkixN-4.jsadded+1−0View file
@@ -0,0 +1 @@
1+const e=(e,t)=>e[t],t=(e,t)=>e[t],n=e=>e.geometry===`membrane`||e.geometry===`plate`||e.geometry===`disc`,r=(...e)=>t=>e.includes(t.geometry),i=(...e)=>t=>e.includes(t.exciter),a=[`bow`,`reed`,`selfosc`,`noise`],o=[[`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`]],s=[[`sine`,`Sine`],[`tri`,`Triangle`],[`saw`,`Saw`],[`square`,`Square`],[`sh`,`Sample & hold`],[`smooth`,`Smooth random`]];function c(e){let t=t=>t[`lfo${e}Target`]!==`off`;return[{kind:`enum`,id:`lfo${e}Target`,label:`LFO ${e} →`,group:`Modulation`,options:o,def:`off`},{kind:`enum`,id:`lfo${e}Shape`,label:`Shape`,group:`Modulation`,options:s,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 l=[{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:r(`plate`)},{kind:`num`,id:`powerExp`,label:`Exponent p`,group:`Body`,min:.3,max:3,def:1.5,model:!0,show:r(`free`)},{kind:`num`,id:`discExp`,label:`Chladni exponent`,group:`Body`,min:1,max:2.5,def:2,model:!0,show:r(`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&&n(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:n},{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:i(`strike`)},{kind:`num`,id:`hardness`,label:`Contact time`,group:`Exciter`,min:.05,max:20,def:1,scale:`log`,unit:`ms`,show:i(`strike`,`impulse`)},{kind:`num`,id:`feltExp`,label:`Felt exponent`,group:`Exciter`,min:1,max:4,def:2.5,show:i(`strike`)},{kind:`num`,id:`bowForce`,label:`Bow force`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:i(`bow`)},{kind:`num`,id:`bowSpeed`,label:`Bow speed`,group:`Exciter`,min:0,max:2,def:.4,scale:`pow2`,show:i(`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:i(`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:i(`reed`)},{kind:`num`,id:`reedGain`,label:`Reed opening`,group:`Exciter`,min:0,max:2,def:.5,show:i(`reed`)},{kind:`num`,id:`breath`,label:`Breath noise`,group:`Exciter`,min:0,max:1,def:.05,scale:`pow2`,show:i(`reed`)},{kind:`num`,id:`selfGain`,label:`Negative damping`,group:`Exciter`,min:0,max:4,def:.5,scale:`pow2`,show:i(`selfosc`)},{kind:`num`,id:`selfSat`,label:`Saturation level`,group:`Exciter`,min:.02,max:4,def:.5,scale:`log`,show:i(`selfosc`)},{kind:`num`,id:`noiseLevel`,label:`Noise level`,group:`Exciter`,min:0,max:4,def:1,scale:`pow2`,show:i(`noise`)},{kind:`num`,id:`noiseColor`,label:`Noise cutoff`,group:`Exciter`,min:50,max:16e3,def:3e3,scale:`log`,unit:`Hz`,show:i(`noise`,`reed`,`bow`)},{kind:`num`,id:`attack`,label:`Attack`,group:`Exciter`,min:1,max:3e3,def:40,scale:`log`,unit:`ms`,show:i(...a)},{kind:`num`,id:`release`,label:`Release`,group:`Exciter`,min:5,max:5e3,def:150,scale:`log`,unit:`ms`,show:i(...a)},{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},...c(1),...c(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:n},{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(l.map(e=>[e.id,e]));const u=Object.fromEntries(l.map(e=>[e.id,e.def])),d=l.filter(e=>e.model).map(e=>e.id),f=Math.SQRT2,p=Math.PI;function m(e,t){let n=Math.ceil(Math.abs(t)+e)+24,r=0;for(let i=0;i<=n;i++){let a=p*i/n;r+=(i===0||i===n?.5:1)*Math.cos(e*a-t*Math.sin(a))}return r/n}function h(e,t){let n=[],r=e===0?.5:e,i=m(e,r);for(let a=r+.05;a<=t;a+=.05){let t=m(e,a);if(i*t<0){let t=r,o=a,s=i;for(let n=0;n<50;n++){let n=.5*(t+o),r=m(e,n);s*r<=0?o=n:(t=n,s=r)}n.push(.5*(t+o))}r=a,i=t}return n}const g=[4.730040745,7.853204624,10.99560784,14.13716549,17.27875966],_=e=>e<g.length?g[e]:(2*e+3)*p/2;function v(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 y=[[.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 b(e,t,n,r,i=2){let a=new Float64Array(t),o=new Float64Array(t),s={kind:e,N:t,ratios:a,wavenum:o,aspect:n};switch(e){case`string`:case`free`:for(let n=0;n<t;n++){let t=n+1;a[n]=e===`string`?t:t**+r,o[n]=t}return{...s,view:`line`,dim:1,shape:(e,t)=>f*Math.sin((e+1)*p*t)};case`tube_co`:for(let e=0;e<t;e++)a[e]=2*e+1,o[e]=(2*e+1)/2;return{...s,view:`line`,dim:1,shape:(e,t)=>f*Math.cos((2*e+1)*p*t/2)};case`tube_oo`:for(let e=0;e<t;e++)a[e]=e+1,o[e]=e+1;return{...s,view:`line`,dim:1,shape:(e,t)=>f*Math.cos((e+1)*p*t)};case`bar`:{let e=_(0),n=new Float64Array(t),r=2048;for(let i=0;i<t;i++){let t=_(i);a[i]=(t/e)**2,o[i]=t/p;let s=0;for(let e=0;e<r;e++)s+=v(i,t,(e+.5)/r)**2;n[i]=1/Math.sqrt(s/r)}return{...s,view:`line`,dim:1,shape:(e,t)=>n[e]*v(e,_(e),t)}}case`ring`:{let e=[],n=[],r=0,i=0,c=2;for(;e.length<t;){r<y.length?[i,c]=y[r]:(i*=1.09,c+=+(r%2==0));for(let s=0;s<2&&e.length<t;s++)a[e.length]=i*(s===0?1:1+6e-4*(1+r%3)),o[e.length]=2*c,e.push(c),n.push(s);r++}return{...s,view:`ring`,dim:1,shape:(t,r)=>{let i=2*p*r*e[t];return f*(n[t]===0?Math.cos(i):Math.sin(i))}}}case`plate`:{let e=Math.ceil(3*Math.sqrt(t))+3,r=[];for(let t=1;t<=e;t++)for(let i=1;i<=e;i++)r.push([t*t+(i/n)**2,t,i]);r.sort((e,t)=>e[0]-t[0]);let i=new Int32Array(t),c=new Int32Array(t),l=r[0][0];for(let e=0;e<t;e++){let[t,s,u]=r[e];a[e]=t/l,o[e]=Math.sqrt(s*s+(u/n)**2),i[e]=s,c[e]=u}return{...s,view:`rect`,dim:2,shape:(e,t,n)=>2*Math.sin(i[e]*p*t)*Math.sin(c[e]*p*n)}}case`membrane`:{let e=2*Math.sqrt(t)+6,n=[];for(;;){n=[];for(let t=0;t<=Math.ceil(e);t++)for(let r of h(t,e))n.push([r,t,0]),t>0&&n.push([r,t,1]);if(n.length>=t)break;e*=1.3}n.sort((e,t)=>e[0]-t[0]||e[2]-t[2]);let r=n[0][0],i=new Int32Array(t),c=new Int32Array(t),l=new Float64Array(t),u=new Float64Array(t);for(let e=0;e<t;e++){let[t,s,d]=n[e];a[e]=t/r,o[e]=t/p,i[e]=s,c[e]=d,l[e]=t,u[e]=s===0?1/Math.abs(m(1,t)):f/Math.abs(m(s+1,t))}return S(s,i,c,l,u)}case`disc`:{let e=i,n=Math.ceil(Math.sqrt(2*t))+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 c=r.slice(0,t),l=c.reduce((e,t)=>Math.max(e,t[1]),0),u=c.reduce((e,t)=>Math.max(e,t[2]),0),d=[];for(let e=0;e<=l;e++)d.push(x(e,u+1));let f=new Int32Array(t),m=new Int32Array(t),h=new Float64Array(t),g=c[0][0];for(let e=0;e<t;e++){let[t,n,r,i]=c[e];a[e]=t/g,f[e]=n,m[e]=i,h[e]=d[n][n===0?r-1:r],o[e]=h[e]/p}return S(s,f,m,h,null)}}}function x(e,t){let n=t=>e===0?-m(1,t):.5*(m(e-1,t)-m(e+1,t)),r=[],i=e===0?.5:Math.max(.3,e*.8),a=n(i);for(let e=i+.05;r.length<t;e+=.05){let t=n(e);if(a*t<0){let t=i,o=e,s=a;for(let e=0;e<50;e++){let e=.5*(t+o),r=n(e);s*r<=0?o=e:(t=e,s=r)}r.push(.5*(t+o))}i=e,a=t}return r}function S(e,t,n,r,i){let a=e.N,o=Array(a).fill(null),s=i??new Float64Array(a),c=(e,n)=>{let a=o[e];if(!a){a=/* @__PURE__ */ new Float64Array(258);for(let n=0;n<=256;n++)a[n]=m(t[e],r[e]*n/256);if(a[257]=a[256],o[e]=a,!i){let n=0;for(let e=0;e<=256;e++)n+=(e===0||e===256?.5:1)*a[e]*a[e]*e/256/256;s[e]=1/Math.sqrt(Math.max(1e-12,(t[e]===0?2:1)*n))}}let c=n*256,l=Math.floor(c),u=c-l;return a[l]*(1-u)+a[l+1]*u};return{...e,view:`disk`,dim:2,shape:(e,r,i)=>{let a=2*r-1,o=2*i-1,l=Math.hypot(a,o);if(l>=1)return 0;let u=c(e,l),d=t[e],f=d===0?1:n[e]===0?Math.cos(d*Math.atan2(o,a)):Math.sin(d*Math.atan2(o,a));return s[e]*u*f}}}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 ee=e=>d.map(t=>String(e[t])).join(`|`);function T(n){let r=Math.round(e(n,`modes`)),i=b(t(n,`geometry`),r,e(n,`aspect`),e(n,`powerExp`),e(n,`discExp`)),a=Math.round(e(n,`seed`)),o=C(a*7919+13),s=e(n,`stretch`),c=e(n,`inharm`),l=e(n,`harmonize`),u=e(n,`jitter`),d=0;for(let e=0;e<r;e++)if(Math.abs(i.ratios[e]-1)<1e-9){d=e;break}let f=new Float64Array(r);for(let e=0;e<r;e++){let t=i.ratios[e]**+s;if(t*=Math.sqrt(1+c*t*t)/Math.sqrt(1+c),l>0){let e=t<.75?.5:Math.max(1,Math.round(t));t=t**(1-l)*e**+l}let n=w(o);e!==d&&u>0&&(t*=2**(u*n/1200)),f[e]=t}let p=Int32Array.from({length:r},(e,t)=>t).sort((e,t)=>f[e]-f[t]),m=new Float64Array(r),h=new Float64Array(r),g=0;for(let e=0;e<r;e++)m[e]=f[p[e]],h[e]=i.wavenum[p[e]],p[e]===d&&(g=e);let _=Math.min(r,Math.round(e(n,`nlModes`))),v=Math.round(e(n,`terms`)),y=C(a*104729+7),x=[],S=new Float64Array(v*_);for(let e=0;e<v;e++){let t=[],n=Math.max(2,Math.round(_*.75)),r=0;for(let e=0;e<n;e++){let e=Math.floor(y()*_),n=y()<.25?e:Math.floor(y()*_),i=w(y);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<_;t++){let n=w(y);S[e*_+t]=n,o+=n*n}o=1/Math.sqrt(o);for(let t=0;t<_;t++)S[e*_+t]*=o}let T=x.reduce((e,t)=>e+t.length,0),E=new Int32Array(v+1),D=new Int32Array(T),O=new Int32Array(T),k=new Float64Array(T),A=0;for(let e=0;e<v;e++){E[e]=A;for(let[t,n,r]of x[e])D[A]=t,O[A]=n,k[A]=r,A++}E[v]=A;let j=C(a*31337+1),M=new Float64Array(_),N=0;for(let e=0;e<_;e++)M[e]=w(j),N+=M[e]**2;for(let e=0;e<_;e++)M[e]/=Math.sqrt(N);let P=new Float64Array(r);for(let e=0;e<r;e++)P[e]=(j()<.5?-1:1)*(.5+.5*j());return{key:ee(n),geom:i,N:r,ratios:m,wavenum:h,pitchK:g,perm:p,Nnl:_,M:v,tStart:E,ti:D,tj:O,tv:k,tb:S,bx:M,rad:P,shape:(e,t,n)=>i.shape(p[e],t,n)}}const E={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 D(e,t,n,r=1){let i=E[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 O(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 k=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=D(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+=O(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 A=.5,j=1e-14,M=.002,N=.05,P=e=>{let t=Math.abs(e);return t+Math.log1p(Math.exp(-2*t))-Math.LN2},te=6.907755,ne=10**-9,re=.1;var ie=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;nTune=0;cull=1/0;nNL=0;nNLTune=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;sw2=/* @__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;fast=!1;tc=0;tq=0;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`,`sw2`,`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,this.uncull()}uncull(){this.cull=1/0,this.nAct=this.nTune,this.nNL=this.nNLTune}};const ae=e=>440*2**((e-69)/12),oe=e=>e<0?0:e>1?1:e,F=e=>e-Math.floor(e);var se=class{sr;h;p={...u};model;voices=[];act=[];eps=j;vMax=0;vHold=0;psi=Math.sqrt(j);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 k;boxOut=/* @__PURE__ */ new Float64Array(2);constructor(e){this.sr=e,this.h=1/e,this.model=T(this.p);for(let e=0;e<16;e++){let t=new ie(e);t.alloc(this.model.N),this.voices.push(t)}}message(e){e.type===`params`?this.setParams(e.params):this.pending.push(e)}setParams(n){if(this.p={...u,...n},this.paramVersion++,ee(this.p)!==this.model.key){this.model=T(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 r=t(this.p,`soundbox`);r===`off`?(this.box.configure(``,1,1,this.sr),this.box.reset()):this.box.configure(r,e(this.p,`boxSize`),e(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(t){let n=this.voices.find(e=>e.active&&e.note===t);if(n)return n;let r=Math.round(e(this.p,`voices`)),i=this.voices.filter(e=>e.active);return i.length>=r?(i.sort((e,t)=>Number(e.gate)-Number(t.gate)||e.energy-t.energy||e.order-t.order),n=i[0]):n=this.voices.find(e=>!e.active),n.reset(),n.active=!0,n.glideMul=1,n.vibMul=1,n.vibPh=this.rand(),n.vibRateJ=1+.1*(this.rand()*2-1),n.note=t,n.baseHz=ae(t),n.held=n.sustained=n.touching=!1,n.gate=!1,n.dirtyTune=n.dirtyVec=!0,n.tunedPitch=-1,this.psiReset=!0,n}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.uncull(),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(n,r){n.uncull();let i=t(this.p,`exciter`),a=A*(e(this.p,`strength`)*r)**2;if(a<=0)return;let o=n.nAct,s=n.phiE,c=n.om,l=this.h;if(i===`strike`){let t=e(this.p,`hammerMass`),r=e(this.p,`hardness`)/1e3,i=e(this.p,`feltExp`),c=Math.sqrt(2*a/t),u=Math.sqrt(2*A/t)*r/Math.PI,d=0,f=0;for(let e=0;e<o;e++)d+=s[e]*n.q[e],f+=s[e]*(n.q[e]-n.qp[e])/l;let p=Math.sqrt(t);n.ham=!0,n.hamTimer=0,n.hamISM=1/p,n.hamK=t*(Math.PI/r)**2/u**(i-1),n.hamA=i,n.hz=d*p,n.hzp=(d-(f+c)*l)*p}else if(i===`pluck`){let e=0;for(let t=0;t<o;t++)e+=s[t]*s[t]/(c[t]*c[t]);if(e<=0)return;let t=Math.sqrt(2*a/e);for(let e=0;e<o;e++){let r=t*s[e]/(c[e]*c[e]);n.q[e]+=r,n.qp[e]+=r}this.psiReset=!0}else if(i===`impulse`){let t=e(this.p,`hardness`)/1e3,r=0,i=n.qn;for(let e=0;e<o;e++){let n=c[e]*t/2,a=1-(n/Math.PI)**2,o=n<1e-9?1:Math.abs(a)<1e-6?.5:Math.abs(Math.sin(n)/n/a);i[e]=s[e]*o,r+=i[e]*i[e]}if(r<=0)return;let u=Math.sqrt(2*a/r);for(let e=0;e<o;e++)n.qp[e]-=l*u*i[e];i.fill(0)}}tuneVoice(t){let n=this.model,r=n.N,i=this.h,a=this.p,o=t.baseHz*this.pitchMul*t.glideMul*t.vibMul,s=te/e(a,`t60`),c=e(a,`hfDamp`),l=e(a,`damper`),u=!t.gate&&t.damped&&l<19.9?te/l:0,d=.45*this.sr,f=0,p=0;for(let e=0;e<r;e++){let r=o*n.ratios[e],a=2*Math.PI*r;if(t.om[e]=a,r>=d){t.A[e]=t.B[e]=t.C[e]=t.sw[e]=t.sw2[e]=0;continue}f=e+1;let l=(s+c*(r/1e3)**2)*this.dampMul+u,m=Math.exp(-l*i);if(l<a)t.A[e]=2*m*Math.cos(Math.sqrt(a*a-l*l)*i);else{let n=Math.sqrt(l*l-a*a)*i;t.A[e]=m*(Math.exp(n)+Math.exp(-n))}t.B[e]=m*m,t.C[e]=i*i/(1+Math.tanh(l*i));let h=2-2*Math.cos(a*i),g=Math.max(0,Math.min(1,(3.6/h-1)/12));t.sw[e]=a*Math.sqrt(g),t.sw2[e]=a*a*g,g>0&&(p=e+1)}for(let e=f;e<r;e++)t.q[e]=t.qp[e]=0;t.nTune=f,t.nNLTune=Math.min(p,f),t.nAct=Math.min(f,t.cull),t.nNL=Math.min(t.nNLTune,t.nAct),t.omega1=2*Math.PI*o,t.Z0=2*o;let m=0;for(let e=0;e<f;e++)m+=t.phiE[e]*t.phiE[e]*t.C[e];t.wsum=m;let h=+Math.max(t.buzzPhi1,.05)/t.omega1,g=e(a,`buzz`);t.buzzGap=e(a,`buzzGap`)*h,t.buzzK=g>0?g*(2*Math.PI*4e3)**2*.1*h**(1-this.buzzA):0,t.tunedPitch=this.pitchMul,t.tunedDamp=this.dampMul,t.tunedGate=t.gate,t.tunedGlide=t.glideMul,t.tunedVib=t.vibMul,t.dirtyTune=!1}vecVoice(t){let n=this.model,r=n.N,i=this.p,a=t.posX>=0?t.posX:oe(e(i,`exPos`)+this.posOff),o=t.posY>=0?t.posY:oe(e(i,`exPosY`)+this.posOff),s=e(i,`exWidth`)*.15,c=e(i,`buzzPos`),l=e(i,`buzzPosY`),u=F(e(i,`pickup`)+this.pickOff),d=e(i,`pickupY`),f=e(i,`width`),p=F(u+.5*f),m=F(d+.37*f),h=e(i,`spread`),g=e(i,`tilt`)/6.0206;for(let e=0;e<r;e++){let i=Math.exp(-.5*(Math.PI*n.wavenum[e]*s)**2);t.phiE[e]=n.shape(e,a,o)*i,t.phiB[e]=n.shape(e,c,l);let f=n.ratios[e]**+g;t.wL[e]=((1-h)*n.shape(e,u,d)+h*n.rad[e])*f,t.wR[e]=((1-h)*n.shape(e,p,m)+h*n.rad[(e+1)%r]*(e%2?1:-1))*f}t.buzzPhi1=Math.abs(n.shape(n.pitchK,c,l)),t.beta=Math.max(.02,Math.min(a,1-a)),t.dirtyVec=!1,t.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(n,r){let i=this.p,a=e(i,`lfo${n+1}Rate`),o=this.lfoPh[n]+a*r;switch(o>=1&&(o-=Math.floor(o),this.lfoA[n]=this.lfoB[n],this.lfoB[n]=this.rand()*2-1),this.lfoPh[n]=o,t(i,`lfo${n+1}Shape`)){case`tri`:return 1-4*Math.abs(o-.5);case`saw`:return 2*o-1;case`square`:return o<.5?1:-1;case`sh`:return this.lfoB[n];case`smooth`:return this.lfoA[n]+(this.lfoB[n]-this.lfoA[n])*(.5-.5*Math.cos(Math.PI*o));default:return Math.sin(2*Math.PI*o)}}blockUpdate(n){let r=this.p,i=this.sr,a=n/i,o=this.bend*e(r,`bendRange`),s=1,c=0,l=0,u=e(r,`tension`),d=e(r,`cascade`),f=1,p=1,m=1;for(let n=0;n<2;n++){let i=t(r,`lfo${n+1}Target`);if(i===`off`)continue;let h=e(r,`lfo${n+1}Depth`),g=this.lfo(n,a)*h;switch(i){case`pitch`:o+=4*g;break;case`amp`:s*=Math.max(0,1+g);break;case`position`:c+=.5*g;break;case`pickup`:l+=.5*g;break;case`tension`:u*=Math.max(0,1+g);break;case`cascade`:d*=Math.max(0,1+g);break;case`damping`:f*=2**(3*g);break;case`feedback`:p*=Math.max(0,1+g);break;case`exciter`:m*=Math.max(0,1+g)}}this.pitchMul=2**(o/12),this.dampMul=f,this.ampMul=s,this.fbMul=p,this.excMul=m,this.kt=u,this.kc=this.model.M>0?d:0,this.cc=+e(r,`curvature`),this.ct=e(r,`crossTension`),this.cl=e(r,`crossLink`),this.crossOn=this.ct>0||this.cl>0,this.buzzTwo=t(r,`buzzSides`)===`two`;let h=t(r,`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]=e(r,`bowSpeed`)*.5,g[1]=+e(r,`bowForce`),g[2]=e(r,`bowNoise`)):this.law===2?(g[0]=e(r,`reedGain`)*2,g[1]=e(r,`reedPressure`),g[2]=e(r,`breath`)):this.law===3&&(g[0]=+e(r,`selfGain`),g[1]=e(r,`selfSat`)),this.envAtt=1-Math.exp(-1/(e(r,`attack`)/1e3*i)),this.envRel=1-Math.exp(-1/(e(r,`release`)/1e3*i));let _=Math.min(e(r,`noiseColor`),.45*i);this.noiseC=1-Math.exp(-2*Math.PI*_/i),this.noiseNorm=Math.sqrt(3*(2-this.noiseC)/this.noiseC),this.fbD=Math.max(1,Math.min(32767,Math.round(e(r,`fbDelay`)/1e3*i)));let v=2*Math.PI*Math.min(e(r,`fbFreq`),.45*i)/i,y=Math.sin(v)/(2*e(r,`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=c!==this.lastPosOff||l!==this.lastPickOff||this.vecVersion!==this.paramVersion;this.posOff=c,this.pickOff=l,this.lastPosOff=c,this.lastPickOff=l,this.vecVersion=this.paramVersion;let S=e(r,`vibDepth`),C=e(r,`vibRate`),w=e(r,`vibDelay`)/1e3;this.act.length=0;for(let e of this.voices)if(e.active){if(S>0){e.vibAge+=a;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))*a,e.vibPh-=Math.floor(e.vibPh);let r=2**(S*n*Math.sin(2*Math.PI*e.vibPh)/1200);(Math.abs(r/e.vibMul-1)>1e-5||n===0&&e.vibMul!==1)&&(e.vibMul=r)}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/A;o+=this.kt*A*.5*e*e*P(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)/A;o+=u*A*m*m*P(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}nlTension(e){let t=e.nNL,n=e.q,r=e.qp,i=e.sw2,a=0,o=0;for(let e=0;e<t;e++){let t=i[e]*n[e];a+=t*n[e],o+=t*r[e]}if(e.S=a,e.X=0,e.gz=0,e.fast=!0,a>0){let t=3/this.kt,n=a/A;e.Vv=this.kt*A*.5*t*t*P(n/t),e.tc=this.kt*t*Math.tanh(n/t),e.tq=e.tc===0?0:o,e.useG=!0}else e.Vv=0,e.tc=0,e.tq=0,e.useG=!1}lawEval(e){let t=0,n=0;if(this.law===1){let r=e-this.lwVb,i=Math.tanh(r/M),a=1+Math.abs(r)/N,o=.35+.65/a,s=-.65/(N*a*a)*(r>=0?1:-1);t=-this.lwF*i*o,n=-this.lwF*((1-i*i)/M*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(t,n,r,i=0){let a=Date.now(),o=r/this.sr;if(this.pending.length){let e=[];for(let t of this.pending)(`time`in t&&t.time!==void 0?t.time:0)<=i+o?this.handle(t):e.push(t);this.pending=e}this.blockUpdate(r);let s=this.act,c=this.h,l=c*c,u=1/c,d=this.p,f=e(d,`fbGain`)*this.fbMul,p=e(d,`fbSat`),m=e(d,`noiseLevel`),h=this.law,g=h===4||h===3||h===2&&e(d,`breath`)>0||h===1&&e(d,`bowNoise`)>0,_=this.box,v=_.n>0,y=v?e(d,`boxMix`):0,b=1-y,x=this.boxOut,S=.25*this.ampMul*u*10**(e(d,`level`)/20),C=32767,w=this.kt>0&&this.kt<=re&&this.kc<=0&&!this.crossOn;for(let e=0;e<r;e++){let r=0,i=0,a=!1;for(let e=0;e<s.length;e++){let t=s[e];t.env+=((t.gate?t.vel:0)-t.env)*(t.gate?this.envAtt:this.envRel);let n=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],r=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=r,n+=p*t.Z0*Math.tanh(f*r/p)*t.env}h===3&&(n+=.001*t.Z0*t.env*e),h===4?n+=m*t.Z0*t.env*this.excMul*e*.5:h!==0&&(n+=this.solveLaw(t,n,e))}else t.fLaw=0;t.f=n,w&&!t.ham&&t.buzzK<=0?this.nlTension(t):(t.fast=!1,this.nl(t)),r+=t.Vv,i+=t.X,t.useG&&(a=!0)}if(this.crossOn&&s.length){let e=i/A;r+=A*3*3*P(e/3);let t=3*Math.tanh(e/3),n=this.ct,a=+this.cl,o=this.model.bx,c=this.model.Nnl;for(let e of s){let r=e.nNL,i=e.grad,s=e.q,l=e.sw;for(let e=0;e<r;e++)i[e]+=t*(n*l[e]*l[e]*s[e]+(e<c?a*o[e]*l[e]:0))}}let o=0;if(!a)this.psi=Math.sqrt(this.eps);else{r>this.vMax&&(this.vMax=r),this.psiReset&&(this.eps=.01);let e=Math.sqrt(2*r+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 n=0;for(let e of s){if(!e.useG)continue;if(e.fast){n+=e.tc*e.tq;continue}let t=e.nAct,r=e.grad,i=e.qp;for(let e=0;e<t;e++)n+=r[e]*i[e];e.ham&&(n+=e.gz*e.hzp)}n*=t;let i=this.psi,a=n/4-i,c=0,u=0;for(let e of s){if(!e.useG)continue;e.pred=!1;let n=e.nAct,r=e.q,i=e.qp,o=e.qn,s=e.A,d=e.B,f=e.C,p=e.phiE,m=e.f;if(e.fast){let l=e.nNL,h=e.sw2,g=e.tc*t;for(let e=0;e<l;e++){let t=g*h[e]*r[e],n=f[e],l=s[e]*r[e]-d[e]*i[e]+n*(p[e]*m+t*a);o[e]=l,c+=t*l,u+=n*t*t}for(let e=l;e<n;e++)o[e]=s[e]*r[e]-d[e]*i[e]+f[e]*p[e]*m;continue}let h=e.grad;for(let e=0;e<n;e++){let n=h[e]*t,l=s[e]*r[e]-d[e]*i[e]+f[e]*(p[e]*m+n*a);o[e]=l,c+=n*l,u+=f[e]*n*n}if(e.ham){let n=e.gz*t,r=2*e.hz-e.hzp+l*n*a;e.hzn=r,c+=n*r,u+=l*n*n}}let d=c/(1+u/4);o=d*t/4;for(let e of s){if(!e.useG||e.fast)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]*o;e.ham&&(e.hzn-=l*e.gz*o)}this.psi=i+(d-n)/2}let c=0,d=0;for(let e of s){let t=e.nAct,n=e.q,r=e.qp,i=e.qn,a=e.wL,s=e.wR,l=0,f=0;if(!e.useG){let o=e.A,c=e.B,u=e.C,d=e.phiE,p=e.f;if(e.pred){e.pred=!1;for(let e=0;e<t;e++){let t=i[e]+u[e]*d[e]*p;i[e]=t;let r=t-n[e];l+=a[e]*r,f+=s[e]*r}}else if(p!==0)for(let e=0;e<t;e++){let t=o[e]*n[e]-c[e]*r[e]+u[e]*d[e]*p;i[e]=t;let m=t-n[e];l+=a[e]*m,f+=s[e]*m}else for(let e=0;e<t;e++){let t=o[e]*n[e]-c[e]*r[e];i[e]=t;let u=t-n[e];l+=a[e]*u,f+=s[e]*u}e.ham&&(e.hzn=2*e.hz-e.hzp)}else if(e.fast){let r=e.nNL,c=e.sw2,u=e.C,d=e.tc*o;for(let e=0;e<r;e++){let t=i[e]-u[e]*c[e]*n[e]*d;i[e]=t;let r=t-n[e];l+=a[e]*r,f+=s[e]*r}for(let e=r;e<t;e++){let t=i[e]-n[e];l+=a[e]*t,f+=s[e]*t}}else for(let e=0;e<t;e++){let t=i[e]-n[e];l+=a[e]*t,f+=s[e]*t}c+=l,d+=f,e.fb[e.fbW]=.5*(l+f)*u,e.fbW=e.fbW+1&C;let p=e.qp;e.qp=e.q,e.q=e.qn,e.qn=p,e.ham&&(e.hzp=e.hz,e.hz=e.hzn)}v?(_.tick(.5*(c+d)*S,x),t[e]=b*c*S+y*x[0],n[e]=b*d*S+y*x[1]):(t[e]=c*S,n[e]=d*S)}this.blockEnd(r),this.cpuMs+=Date.now()-a,this.cpuWall+=o*1e3}blockEnd(t){let n=1/this.h,r=this.kc<=0&&this.kt<=re&&!this.crossOn&&!(e(this.p,`fbGain`)>0);for(let t of this.act){let i=t.nAct,a=t.q,o=t.qp,s=t.om,c=0,l=0;for(let e=0;e<i;e++){let t=(a[e]-o[e])*n,r=.5*(t*t+s[e]*s[e]*a[e]*a[e]);c+=r,r>l&&(l=r)}if(r&&!t.ham&&t.buzzK<=0&&(this.law===0||t.env<=1e-6)){let e=l*ne,r=i;for(;r>1;){let t=r-1,i=(a[t]-o[t])*n;if(.5*(i*i+s[t]*s[t]*a[t]*a[t])>e)break;r--}if(r<i){for(let e=r;e<i;e++)a[e]=o[e]=0;t.cull=r,t.nAct=r,t.nNL=Math.min(t.nNLTune,r)}}else t.cull!==1/0&&t.uncull();if(!Number.isFinite(c)||c>1e8){t.reset(),t.active=!1,this.psiReset=!0;continue}t.energy=c;let u=e(this.p,`glide`),d=1;if(u!==0){let e=4*c/A;d=2**(u*e/(1+e)/12)}(Math.abs(d/t.glideMul-1)>2e-5||d===1&&t.glideMul!==1)&&(t.glideMul=d),!t.gate&&!t.ham&&c<1e-10&&t.env<1e-4&&(t.active=!1)}let i=0;for(let e of this.act)e.active&&(i+=e.energy);this.vHold=Math.max(this.vMax,this.vHold*.95),this.vMax=0;let a=Math.max(j,.02*i+2*this.vHold);if(a<this.eps){let e=Math.max(a,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+=t,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])}};const I=48e3;let L,R,z,B=0,V,H=0,U=0,W=0,G=1/0,K=0,ce=4*I,le=!1;const q=[],ue=/* @__PURE__ */ new Map;let J=!1,Y=1,X=1,de=1,Z=0,fe=!1,Q=1/0,pe=1;self.onmessage=e=>{let t=e.data;t.type===`init`&&(R={...u,...t.sound},z=R,L=new se(I),L.message({type:`params`,params:R}),B=t.stem,Y=Math.max(1,t.slow??1),H=t.fromFrame,W=t.fromFrame,U=t.sendFrame,K=t.sendFrame,V=t.playerPort,V.onmessage=e=>{K=e.data.playhead,ce=e.data.ahead,$()},t.scorePort.onmessage=e=>{let t=e.data;if(t.type===`cmds`){for(let e of t.cmds)q.push(e);W=Math.max(W,Math.floor(t.horizon*I))}else t.type===`end`&&(G=Math.round(t.t*I),W=Math.max(W,G));$()})};function $(){J||(J=!0,setTimeout(ve,0))}function me(e){switch(e.type){case`noteOn`:L.message({type:`noteOn`,note:e.note,vel:e.vel}),ue.set(e.note,e.t);break;case`noteOff`:if(e.on!==void 0&&(ue.get(e.note)??-1/0)>e.on)break;L.message({type:`noteOff`,note:e.note});break;case`params`:z={...z,...e.params},L.message({type:`params`,params:z});break;case`bend`:L.message({type:`bend`,value:e.value});break;case`gain`:de=e.value,Z=e.tau;break;case`hold`:{if(fe)break;fe=!0;let t=e.hold+e.fade,n=Math.min(60,Math.max(R.t60,6*t)),r=n/R.t60;z={...z,t60:n,hfDamp:R.hfDamp/r},L.message({type:`params`,params:z}),Q=e.t+Math.max(e.hold,.005),pe=Math.max(.01,e.fade);break}}}const he=/* @__PURE__ */ new Float32Array(128),ge=/* @__PURE__ */ new Float32Array(128);function _e(e,t,n){let r=H/I,i=(H+128)/I;for(;q.length&&q[0].t<i;)me(q.shift());he.fill(0),ge.fill(0),L.process(he,ge,128,r);let a=de,o=X;X=Z>0?X+(a-X)*(1-Math.exp(-128/I/Z)):a;for(let r=0;r<128;r++){let i=o+(X-o)*(r+1)/128,a=(H+r)/I;if(a>=Q){let e=Math.min(1,(a-Q)/pe),t=Math.cos(Math.PI/2*e);i*=t*t}e[n+r]=he[r]*i,t[n+r]=ge[r]*i}H+=128}function ve(){if(J=!1,!L)return;if(H>=G){le||(le=!0,ye({type:`done`,stem:B,frame:G}));return}let e=Math.min(W,K+ce,G+128-1),t=Math.min(2048,Math.floor((e-H)/128)*128);if(t<=0)return;let n=H,r=new Float32Array(t),i=new Float32Array(t),a=performance.now();for(let e=0;e<t;e+=128)_e(r,i,e);if(Y>1){let e=performance.now()+(Y-1)*(performance.now()-a);for(;performance.now()<e;);}if(n+t>U){let e=Math.max(0,U-n),t=e?r.slice(e):r,a=e?i.slice(e):i;ye({type:`chunk`,stem:B,frame:n+e,L:t,R:a},[t.buffer,a.buffer])}$()}function ye(e,t=[]){V.postMessage(e,t)}
site/index.htmlmodified+1−1View file
@@ -5,7 +5,7 @@
55 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
66 <title>double pendulum</title>
77 <link rel="icon" href="data:," />
8- <script type="module" crossorigin src="./assets/index-D9r0IF3O.js"></script>
8+ <script type="module" crossorigin src="./assets/index-CTL9vx7o.js"></script>
99 <link rel="stylesheet" crossorigin href="./assets/index-BFl0mzg8.css">
1010 </head>
1111 <body>
src/compositions/c01-poincare/defaults.jsonmodified+0−16View file
@@ -30,22 +30,6 @@
3030 "loudFloor": 0.08,
3131 "notesLevel": -6,
3232 "noteLength": 1.5,
33- "humInstrument": "modal: Clarinet-ish",
34- "humCustom": "",
35- "humPitch": 38,
36- "humLevel": -24,
37- "humFollow": 0,
38- "humNormalize": true,
39- "humColorMode": "log",
40- "humColorCurve": 1,
41- "humTarget1": "pickup",
42- "humFrom1": 0.15,
43- "humTo1": 0.75,
44- "humTarget2": "tilt",
45- "humFrom2": 0.3333,
46- "humTo2": 0.5833,
47- "humFadeIn": 3,
48- "humFadeOut": 6,
4933 "pendulumAlpha": 1,
5034 "pendulumSize": 0.32,
5135 "motionBlur": 1,
src/compositions/c01-poincare/layout.tsmodified+2−5View file
@@ -2,20 +2,17 @@ import type { Params } from "../../core/params.ts";
22 import { soundOf } from "../../instruments/sounds.ts";
33 import type { Layout } from "../../stream/layout.ts";
44
5-/** Stems: 0 the crossing notes, 1 the hum. */
6-export const NOTES = 0, HUM = 1;
5+/** One stem: the crossing notes. */
6+export const NOTES = 0;
77
88 export function layout(P: Params): Layout {
99 const notes = soundOf(P.noteInstrument as string, P.modalCustom as string);
10- const hum = soundOf(P.humInstrument as string, P.humCustom as string, { voices: 1 });
1110 return {
1211 stems: [
1312 { kind: "synth", sound: notes, output: NOTES },
14- { kind: "synth", sound: hum, output: HUM },
1513 ],
1614 outputs: [
1715 { effects: "own", sound: notes, level: (Q) => Q.notesLevel as number },
18- { effects: "own", sound: hum, level: (Q) => Q.humLevel as number },
1916 ],
2017 };
2118 }
src/compositions/c01-poincare/schema.tsmodified+1−18View file
@@ -1,5 +1,5 @@
11 import type { ParamSpec } from "../../core/params.ts";
2-import { DRONE_SOUNDS, LIVE_TARGETS, NOTE_SOUNDS } from "../../instruments/sounds.ts";
2+import { NOTE_SOUNDS } from "../../instruments/sounds.ts";
33 import { NOTE_NAMES, SCALE_NAMES } from "../../music/scales.ts";
44
55 // Energies are in units of the potential energy with both arms straight up.
@@ -43,23 +43,6 @@ export const schema: ParamSpec[] = [
4343 { group: "notes", key: "notesLevel", label: "level", kind: "number", default: -6, min: -48, max: 6, step: 0.5, unit: "dB", live: true },
4444 { group: "notes", key: "noteLength", label: "length", kind: "number", default: 1.5, min: 0.05, max: 10, log: true, unit: "s" },
4545
46- // ── hum (energy) ──
47- { group: "hum", key: "humInstrument", label: "instrument", kind: "select", default: "modal: Clarinet-ish", options: DRONE_SOUNDS, hint: "modal: … = one held note of a sustained modal-synth preset" },
48- { group: "hum", key: "humCustom", label: "modal custom", kind: "text", default: "", hint: "for “modal: custom”: paste JSON from modal-synth’s Copy button" },
49- { group: "hum", key: "humPitch", label: "pitch", kind: "number", default: 38, min: 12, max: 72, step: 0.5, unit: "midi" },
50- { group: "hum", key: "humLevel", label: "level", kind: "number", default: -24, min: -60, max: 0, step: 0.5, unit: "dB", live: true },
51- { group: "hum", key: "humFollow", label: "loudness follows energy", kind: "number", default: 0, min: 0, max: 1, step: 0.01, hint: "0 = constant loudness" },
52- { 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" },
53- { 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" },
54- { 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" },
55- { 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, …)" },
56- { 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" },
57- { group: "hum", key: "humTo1", label: "A at peak", kind: "number", default: 0.75, min: 0, max: 1, step: 0.005 },
58- { group: "hum", key: "humTarget2", label: "timbre → B", kind: "select", default: "tilt", options: ["none", ...LIVE_TARGETS] },
59- { group: "hum", key: "humFrom2", label: "B at low energy", kind: "number", default: 0.3333, min: 0, max: 1, step: 0.005 },
60- { group: "hum", key: "humTo2", label: "B at peak", kind: "number", default: 0.5833, min: 0, max: 1, step: 0.005 },
61- { group: "hum", key: "humFadeIn", label: "fade in", kind: "number", default: 3, min: 0, max: 60, step: 0.5, unit: "s" },
62- { 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" },
6346
6447 // ── visual ──
6548 { group: "visual", key: "pendulumAlpha", label: "pendulum opacity", kind: "number", default: 1, min: 0, max: 1, step: 0.01, hint: "0 = hide the pendulum", live: true },
src/compositions/c01-poincare/score.tsmodified+4−7View file
@@ -1,9 +1,9 @@
11 // Composition 1: a double pendulum and its Poincaré section — the score (score worker).
22 //
33 // Section: θ1 = 0 crossed upward (dθ1/dt > 0); plotted at (θ2, p2). Each crossing plays a note:
4-// θ2 → pitch, |p2| → loudness. A hum runs throughout; its timbre follows the energy. Energy is
5-// steered along an envelope: small → peak → hold → zero. Once the pendulum is at rest, no more
6-// crossings register; the last note is held and faded, the hum fades with it, and the piece ends.
4+// θ2 → pitch, |p2| → loudness. Energy is steered along an envelope: small → peak → hold → zero.
5+// Once the pendulum is at rest, no more crossings register; the last note is held and faded, and
6+// the piece ends.
77 //
88 // Drawing data: track 0 = [θ1, θ2, energy] (960 per piece second); events "x" = crossings.
99
@@ -12,9 +12,8 @@ import { mulberry32 } from "../../core/rng.ts";
1212 import { DoublePendulum, wrapAngle } from "../../physics/doublePendulum.ts";
1313 import type { NoteRef, ScoreFactory } from "../../stream/score.ts";
1414 import { energyTarget } from "../shared/form.ts";
15-import { HumScore } from "../shared/humScore.ts";
1615 import { noteFor } from "../shared/noteMap.ts";
17-import { HUM, NOTES } from "./layout.ts";
16+import { NOTES } from "./layout.ts";
1817
1918 const DT = 0.002; // simulation step (sim seconds)
2019 const MAX_SETTLE = 10; // s after duration: count the pendulum as at rest regardless
@@ -27,7 +26,6 @@ export const poincareScore: ScoreFactory = (P: Params, seed: number, sink) => {
2726 pend.tau = P.tau as number;
2827 const speed = P.speed as number, duration = P.duration as number, restE = P.restEnergy as number;
2928 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
30- const hum = new HumScore(P, HUM, sink);
3129 const y = pend.y;
3230
3331 let time = 0;
@@ -63,7 +61,6 @@ export const poincareScore: ScoreFactory = (P: Params, seed: number, sink) => {
6361 prevTh2 = y[1];
6462 prevP2 = y[3];
6563 const e = pend.energyNorm();
66- hum.update(time, e, restAt !== null ? restAt + ring : null);
6764 if (time >= nextFrame) {
6865 sink.frame(0, time, [y[0], y[1], e]);
6966 nextFrame = time + FRAME_DT;
src/compositions/c02-orbits/defaults.jsonmodified+0−16View file
@@ -44,22 +44,6 @@
4444 "loudFloor": 0.08,
4545 "notesLevel": -6,
4646 "noteLength": 1.5,
47- "humInstrument": "modal: Clarinet-ish",
48- "humCustom": "",
49- "humPitch": 38,
50- "humLevel": -24,
51- "humFollow": 0,
52- "humNormalize": true,
53- "humColorMode": "log",
54- "humColorCurve": 1,
55- "humTarget1": "pickup",
56- "humFrom1": 0.15,
57- "humTo1": 0.75,
58- "humTarget2": "tilt",
59- "humFrom2": 0.3333,
60- "humTo2": 0.5833,
61- "humFadeIn": 3,
62- "humFadeOut": 6,
6347 "fade": 20,
6448 "plotZoom": "fit energy",
6549 "zoomSmooth": 1.5,
src/compositions/c02-orbits/layout.tsmodified+2−11View file
@@ -24,21 +24,12 @@ export function orbitStems(P: Params): { names: string[]; stemOf: number[] } {
2424 return { names, stemOf };
2525 }
2626
27-/** The hum's stem comes after the instruments'. */
28-export function humStem(P: Params): number {
29- return orbitStems(P).names.length;
30-}
31-
3227 export function layout(P: Params): Layout {
3328 const { names } = orbitStems(P);
3429 const sounds = names.map((n) => soundOf(n, P.modalCustom as string));
35- const hum = soundOf(P.humInstrument as string, P.humCustom as string, { voices: 1 });
3630 return {
37- stems: [...sounds.map((sound, i) => ({ kind: "synth" as const, sound, output: i })), { kind: "synth", sound: hum, output: names.length }],
38- outputs: [
39- ...sounds.map((sound) => ({ effects: "shared" as const, sound, level: (Q: Params) => Q.notesLevel as number })),
40- { effects: "own", sound: hum, level: (Q) => Q.humLevel as number },
41- ],
31+ stems: sounds.map((sound, i) => ({ kind: "synth" as const, sound, output: i })),
32+ outputs: sounds.map((sound) => ({ effects: "shared" as const, sound, level: (Q: Params) => Q.notesLevel as number })),
4233 reverbTime: P.reverbTime as number,
4334 };
4435 }
src/compositions/c02-orbits/schema.tsmodified+0−3View file
@@ -51,9 +51,6 @@ export const schema: ParamSpec[] = [
5151 pick("scale", { default: "dorian" }),
5252 ...["root", "pitchSource", "thetaRange", "pitchLow", "pitchHigh", "pitchCurve", "invertPitch", "p2Ref", "loudCurve", "loudFloor", "notesLevel", "noteLength"].map((k) => pick(k)),
5353
54- // ── hum ──
55- ...c01.filter((s) => s.group === "hum"),
56-
5754 // ── visual ──
5855 pick("fade", { default: 20, hint: "how long each live crossing dot stays visible" }),
5956 ...["plotZoom", "zoomSmooth", "plotP"].map((k) => pick(k)),
src/compositions/c02-orbits/score.tsmodified+2−5View file
@@ -2,7 +2,7 @@
22 //
33 // Several double pendulums at once, all steered along the same energy envelope from random
44 // starting states. Each orbit's crossings play its own instrument (orbit n uses slot n, cycling)
5-// in its own register. A hum follows the energy. Each orbit plays until it comes to rest; its last
5+// in its own register. Each orbit plays until it comes to rest; its last
66 // note rings out, and the piece ends when every orbit has rested and faded.
77 //
88 // Drawing data: track 0 = [mean energy, max energy, then per orbit θ1, θ2, p1, p2, active]
@@ -13,9 +13,8 @@ import { mulberry32 } from "../../core/rng.ts";
1313 import { DoublePendulum, wrapAngle } from "../../physics/doublePendulum.ts";
1414 import type { NoteRef, ScoreFactory } from "../../stream/score.ts";
1515 import { energyTarget } from "../shared/form.ts";
16-import { HumScore } from "../shared/humScore.ts";
1716 import { noteFor } from "../shared/noteMap.ts";
18-import { SLOTS, humStem, orbitCount, orbitStems } from "./layout.ts";
17+import { SLOTS, orbitCount, orbitStems } from "./layout.ts";
1918
2019 const DT = 0.003; // simulation step (sim seconds)
2120 const MAX_SETTLE = 10; // s after duration: count every orbit as at rest regardless
@@ -37,7 +36,6 @@ export const orbitsScore: ScoreFactory = (P: Params, seed: number, sink) => {
3736 const speed = P.speed as number, duration = P.duration as number, restE = P.restEnergy as number;
3837 const ring = (P.finalHold as number) + (P.finalFade as number) + 0.3;
3938 const { stemOf } = orbitStems(P);
40- const hum = new HumScore(P, humStem(P), sink);
4139 const e0 = Math.max(1e-4, energyTarget(P, 0));
4240 const orbits: Orbit[] = Array.from({ length: orbitCount(P) }, (_, i) => {
4341 const pend = new DoublePendulum({ m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number });
@@ -91,7 +89,6 @@ export const orbitsScore: ScoreFactory = (P: Params, seed: number, sink) => {
9189 max = Math.max(max, e);
9290 }
9391 const mean = sum / orbits.length;
94- hum.update(time, mean, restAll !== null ? restAll + ring : null);
9592 if (time >= nextFrame) {
9693 nextFrame = time + FRAME_DT;
9794 row.length = 0;
src/compositions/shared/humScore.tsdeleted+0−63View file
@@ -1,63 +0,0 @@
1-// The energy hum, in the score: one held note of a sustained sound whose timbre follows the energy,
2-// with a fade-in at the start and a fade-out that ends with the piece. Its overall level is the
3-// output's live level (humLevel); the score sends the fades, the loudness-follow and the timbre.
4-
5-import type { Params } from "../../core/params.ts";
6-import { LIVE_TARGETS, targetRange, targetValue } from "../../instruments/sounds.ts";
7-import { log, pow } from "../../physics/dmath.ts";
8-import type { ScoreSink } from "../../stream/score.ts";
9-
10-const CONTROL_DT = 0.05; // s of piece time between control updates
11-
12-export class HumScore {
13- private started = false;
14- private next = 0;
15- private sent: Record<string, number> = {};
16-
17- private P: Params;
18- private stem: number;
19- private sink: ScoreSink;
20-
21- constructor(P: Params, stem: number, sink: ScoreSink) {
22- this.P = P;
23- this.stem = stem;
24- this.sink = sink;
25- }
26-
27- /** e: normalized energy at piece time t; end: piece time everything has faded (null until known). */
28- update(t: number, e: number, end: number | null) {
29- const { P, sink, stem } = this;
30- if (!sink.emitting || t < this.next) return;
31- this.next = t + CONTROL_DT;
32- if (!this.started) {
33- this.started = true;
34- sink.cmd(stem, { t, type: "gain", value: 0, tau: 0 });
35- sink.cmd(stem, { t, type: "noteOn", note: P.humPitch as number, vel: 1 });
36- }
37- const peak = P.energyPeak as number;
38- const rel = Math.max(0, Math.min(1, e / peak));
39- const e0 = Math.min(P.energyStart as number, 0.999 * peak);
40- const colorBase = P.humColorMode === "log" ? Math.max(0, Math.min(1, log(Math.max(e, 1e-12) / e0) / log(peak / e0))) : rel;
41- const fadeIn = P.humFadeIn as number, fadeOut = P.humFadeOut as number;
42- const fade = Math.max(0, Math.min(1, fadeIn > 0 ? t / fadeIn : 1, end !== null && fadeOut > 0 ? (end - t) / fadeOut : 1));
43- const follow = P.humFollow as number;
44- sink.cmd(stem, { t, type: "gain", value: fade * (1 - follow + follow * rel), tau: 0.08, normalize: P.humNormalize as boolean });
45- // timbre: the mapped settings, sent when they move noticeably
46- const color = pow(colorBase, P.humColorCurve as number);
47- const params: Record<string, number> = {};
48- let changed = false;
49- for (const i of [1, 2]) {
50- const target = P[`humTarget${i}`] as string;
51- if (target === "none" || !LIVE_TARGETS.includes(target)) continue;
52- const from = P[`humFrom${i}`] as number, to = P[`humTo${i}`] as number;
53- const v = targetValue(target, from + (to - from) * color, pow);
54- if (!Number.isFinite(v)) continue;
55- params[target] = v;
56- if (this.sent[target] === undefined || Math.abs(v - this.sent[target]) > 0.002 * targetRange(target)) changed = true;
57- }
58- if (changed) {
59- this.sent = params;
60- sink.cmd(stem, { t, type: "params", params });
61- }
62- }
63-}
src/instruments/sounds.tsmodified+1−35View file
@@ -2,7 +2,7 @@
22 // sibling project through the @modal-synth alias) and pasted custom presets. Worker-safe: the
33 // sounds are just parameter sets; the synth workers render them.
44
5-import { DEFAULTS, PARAM_BY_ID, type Params } from "@modal-synth/engine/params.ts";
5+import { DEFAULTS, type Params } from "@modal-synth/engine/params.ts";
66 import { PRESETS } from "@modal-synth/presets.ts";
77
88 /** Parse a pasted preset (the JSON from modal-synth's Copy button). */
@@ -16,45 +16,11 @@ export function parseModalPreset(text: string | undefined): Params | null {
1616 }
1717 }
1818
19-const SUSTAINED_EXCITERS = ["bow", "reed", "selfosc", "noise"];
20-
2119 /** Menu names for note instruments: every preset, plus "modal: custom". */
2220 export const NOTE_SOUNDS: string[] = [...PRESETS.map((p) => `modal: ${p.name}`), "modal: custom"];
2321
24-/** Menu names for drones: sustained presets (bowed, blown, self-oscillating, fed back), plus custom. */
25-export const DRONE_SOUNDS: string[] = [
26- ...PRESETS.filter((p) => {
27- const q = { ...DEFAULTS, ...p.p };
28- return SUSTAINED_EXCITERS.includes(q.exciter as string) || (q.fbGain as number) > 0;
29- }).map((p) => `modal: ${p.name}`),
30- "modal: custom",
31-];
32-
3322 /** The full synth parameters for a menu name (custom: the pasted JSON). */
3423 export function soundOf(name: string, custom: string, overrides: Params = {}): Params {
3524 const preset = name === "modal: custom" ? parseModalPreset(custom) : PRESETS.find((p) => `modal: ${p.name}` === name)?.p;
3625 return { ...DEFAULTS, ...(preset ?? {}), ...overrides };
3726 }
38-
39-/** Settings the synth reads every block, so they can follow the energy while a drone is held. */
40-export const LIVE_TARGETS = [
41- "bowForce", "bowSpeed", "bowNoise", "exPos", "reedPressure", "reedGain", "breath",
42- "selfGain", "selfSat", "noiseLevel", "noiseColor", "tension", "cascade", "curvature",
43- "fbGain", "fbFreq", "fbQ", "fbSat", "hfDamp", "t60", "pickup", "tilt", "vibDepth",
44-];
45-
46-/** 0..1 → a modal-synth setting's value, following that setting's own slider scale. */
47-export function targetValue(id: string, u: number, pow: (x: number, y: number) => number): number {
48- const d = PARAM_BY_ID[id];
49- if (!d || d.kind !== "num") return NaN;
50- const x = Math.max(0, Math.min(1, u));
51- if (d.scale === "log") return d.min * pow(d.max / d.min, x);
52- if (d.scale === "pow2") return d.min + (d.max - d.min) * x * x;
53- return d.min + (d.max - d.min) * x;
54-}
55-
56-/** A setting's range, for deciding whether a change is worth sending. */
57-export function targetRange(id: string): number {
58- const d = PARAM_BY_ID[id] as { min?: number; max?: number } | undefined;
59- return d && d.min !== undefined && d.max !== undefined ? d.max - d.min : 1;
60-}
src/main.tsmodified+18−5View file
@@ -115,17 +115,30 @@ function showComposition(comp: Composition, author: boolean): () => void {
115115 fit();
116116 const startAt = { value: 0 };
117117
118- let starting = false; // instruments can take a moment to load; don't offer play twice
118+ // From the tap on play until the piece ends or is stopped, the button is "stop" — including
119+ // while the audio system is still starting (a phone can take a moment): a stop then cancels the
120+ // start, even if it completes afterwards.
121+ let starting = false;
122+ let session = 0;
119123 const play = async (offset: number) => {
124+ const my = ++session;
120125 starting = true;
121126 try {
122127 const audio = await getAudio();
128+ if (my !== session) return; // stopped while starting
123129 await piece.start(audio, offset);
130+ if (my !== session) piece.stop();
124131 } finally {
125- starting = false;
132+ if (my === session) starting = false;
126133 }
127134 };
128- playBtn.onclick = () => (piece.playing ? piece.stop() : play(author ? startAt.value : 0));
135+ const stop = () => {
136+ session++;
137+ starting = false;
138+ piece.stop();
139+ };
140+ const active = () => piece.playing || starting;
141+ playBtn.onclick = () => (active() ? stop() : play(author ? startAt.value : 0));
129142 bigPlay.onclick = () => playBtn.click();
130143 if (author) {
131144 // author can click the progress line to jump
@@ -167,8 +180,8 @@ function showComposition(comp: Composition, author: boolean): () => void {
167180 let lastReadout = 0;
168181 const frame = (ts: number) => {
169182 piece.draw();
170- playBtn.textContent = piece.playing ? "stop" : "play";
171- bigPlay.hidden = piece.playing || starting;
183+ playBtn.textContent = active() ? "stop" : "play";
184+ bigPlay.hidden = active();
172185 const st = piece.playing ? piece.status?.() : undefined;
173186 const buffering = !!st?.buffering || starting;
174187 bufferingEl.hidden = !buffering;
src/stream/player.tsmodified+1−1View file
@@ -18,7 +18,7 @@ declare function registerProcessor(name: string, ctor: new (options: { processor
1818
1919 const RESUME_START = 1.0; // s buffered before playing at first
2020 const RESUME_MAX = 32; // s
21-const AHEAD_MIN = 4; // s producers keep rendered ahead, at least
21+const AHEAD_MIN = 12; // s producers keep rendered ahead, at least (a deep buffer absorbs dense passages)
2222 const FADE_IN = 512; // samples
2323 const TAIL = 0.985; // per-sample decay of the last sample when sound stops for buffering
2424 const REPORT_EVERY = 6; // blocks between status reports (~16 ms)
src/stream/protocol.tsmodified+2−2View file
@@ -72,8 +72,8 @@ export type SynthCmd =
7272 | { t: number; type: "noteOff"; note: number; on?: number }
7373 | { t: number; type: "params"; params: Record<string, number | string | boolean> } // merged over the sound
7474 | { t: number; type: "bend"; value: number }
75- /** output gain: move toward `value` with time constant `tau`; `normalize` holds the loudness steady */
76- | { t: number; type: "gain"; value: number; tau: number; normalize?: boolean }
75+ /** output gain: move toward `value` with time constant `tau` */
76+ | { t: number; type: "gain"; value: number; tau: number }
7777 /** the final note: from t, slow the decay so it rings `hold + fade` s, and fade out over the last `fade` s */
7878 | { t: number; type: "hold"; hold: number; fade: number };
7979
src/stream/synthWorker.tsmodified+3−16View file
@@ -8,10 +8,6 @@ import { DEFAULTS, type Params } from "@modal-synth/engine/params.ts";
88 import { Synth } from "@modal-synth/engine/synth.ts";
99 import { BLOCK, CHUNK, SAMPLE_RATE, type Clock, type ScoreToSynth, type SynthCmd, type SynthInit, type ToPlayer } from "./protocol.ts";
1010
11-const NORM_REF = 0.3; // normalized loudness: level 1 ≈ this RMS
12-const NORM_TAU = 1.5; // s
13-const NORM_RANGE = 20; // compensation limited to ×1/20 … ×20
14-
1511 let synth: Synth;
1612 let sound: Params;
1713 let cur: Params; // sound with the latest timed changes
@@ -29,9 +25,8 @@ const lastOn = new Map<number, number>(); // pitch → when it was last struck
2925 let scheduled = false;
3026 let slow = 1;
3127
32-// output gain (hum levels), loudness normalization, and the final-note fade
33-let gain = 1, gainTarget = 1, gainTau = 0, normalize = false;
34-let msq = NORM_REF * NORM_REF;
28+// output gain, and the final-note fade
29+let gain = 1, gainTarget = 1, gainTau = 0;
3530 let holding = false;
3631 let fadeFrom = Infinity, fadeLen = 1; // s
3732
@@ -94,7 +89,6 @@ function apply(c: SynthCmd) {
9489 case "gain":
9590 gainTarget = c.value;
9691 gainTau = c.tau;
97- normalize = !!c.normalize;
9892 break;
9993 case "hold": {
10094 if (holding) break; // instrument-wide: the first hold sets it up
@@ -123,14 +117,7 @@ function renderBlock(L: Float32Array, R: Float32Array, at: number) {
123117 bl.fill(0);
124118 br.fill(0);
125119 synth.process(bl, br, BLOCK, now);
126- if (normalize) {
127- let s = 0;
128- for (let i = 0; i < BLOCK; i++) s += bl[i] * bl[i] + br[i] * br[i];
129- s /= 2 * BLOCK;
130- if (s > 1e-10) msq += (s - msq) * (1 - Math.exp(-BLOCK / SAMPLE_RATE / NORM_TAU));
131- }
132- const comp = normalize ? Math.max(1 / NORM_RANGE, Math.min(NORM_RANGE, NORM_REF / Math.sqrt(msq))) : 1;
133- const target = gainTarget * comp;
120+ const target = gainTarget;
134121 const g0 = gain;
135122 gain = gainTau > 0 ? gain + (target - gain) * (1 - Math.exp(-BLOCK / SAMPLE_RATE / gainTau)) : target;
136123 for (let i = 0; i < BLOCK; i++) {