From 4a70ac5a998f5382541c9c999b7f05581b3e8143 Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 20 Aug 2025 00:38:25 -0500 Subject: [PATCH 01/73] Working version of LFOs --- packages/core/controls.mjs | 5 + packages/superdough/superdough.mjs | 146 +++++++++++++++++++++++++---- packages/superdough/synth.mjs | 7 ++ 3 files changed, 141 insertions(+), 17 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index e6181d453..ecb94ea58 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -1430,6 +1430,11 @@ export const { panorient } = registerControl('panorient'); // ['portamento'], // TODO: LFO rate see https://tidalcycles.org/docs/patternlib/tutorials/synthesizers/#supersquare export const { rate } = registerControl('rate'); +export const { lfoTarget } = registerControl('lfoTarget'); +export const { lfoParam } = registerControl('lfoParam'); +export const { lfoNum } = registerControl('lfoNum'); +export const { lfoBipolar } = registerControl('lfoBipolar'); +export const { lfoShape } = registerControl('lfoShape'); // TODO: slide param for certain synths export const { slide } = registerControl('slide'); // TODO: detune? https://tidalcycles.org/docs/patternlib/tutorials/synthesizers/#supersquare diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index eb1466d91..c55cbe0a0 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -510,6 +510,66 @@ export function resetGlobalEffects() { orbits = {}; analysers = {}; analysersData = {}; + lfos = {}; + nodes = {}; +} + +function _getNodeParam(node, name) { + // Worklet case + if (node?.parameters) { + const p = node.parameters.get(name); + if (p instanceof AudioParam) { + return p; + } + } + // Built-in node case + const p = node?.[name]; + if (p instanceof AudioParam) { + return p; + } + return undefined; +} + +function _getNodeParams(node) { + const params = new Set(); + // Worklet case + if (node?.parameters) { + node.parameters.forEach((_v, k) => params.add(k)); + } + // Guesses based on common parameters + ["gain", "frequency", "detune", "Q", "pan", "playbackRate", "delayTime"] + .forEach((k) => { if (node?.[k] instanceof AudioParam) params.add(k); }); + return Array.from(params); +} + +function connectLFO(lfoNum, target, param, frequency, depth, shape, bipolar, start, end) { + debugger; + let lfoNode = lfos[lfoNum]; + const params = { + frequency, + depth, + } + if (lfoNode == null) { + const ac = getAudioContext(); + const dcoffset = bipolar > 0.5 ? -0.5 : 0; + lfoNode = getLfo(ac, start, 1e9, { frequency, depth, shape, dcoffset}); + lfos[lfoNum] = lfoNode; + } + lfoNode.disconnect(); + const targetNodes = nodes[target]; + targetNodes.forEach((targetNode) => { + if (targetNode === undefined) { + const keys = Object.keys(nodes); + errorLogger(new Error(`Could not connect to target ${target} -- it does not exist. Available options are ${keys.join(", ")}`), 'superdough'); + return; + } + const targetParam = _getNodeParam(targetNode, param); + if (targetParam === undefined) { + const parameters = _getNodeParams(targetNode); + errorLogger(new Error(`Could not connect to parameter ${param} on node ${target}. Available parameters are ${parameters.join(", ")}`), 'superdough'); + } + lfoNode.connect(targetParam); + }); } let activeSoundSources = new Map(); @@ -519,6 +579,9 @@ function mapChannelNumbers(channels) { return (Array.isArray(channels) ? channels : [channels]).map((ch) => ch - 1); } +let nodes = {}; +let lfos = {}; + export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) => { // new: t is always expected to be the absolute target onset time const ac = getAudioContext(); @@ -628,6 +691,13 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) compressorKnee, compressorAttack, compressorRelease, + lfo, + lfoNum, + rate, + lfoTarget, + lfoParam, + lfoBipolar, + lfoShape, } = value; delaytime = delaytime ?? cycleToSeconds(delaysync, cps); @@ -681,7 +751,9 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) let sourceNode; if (source) { sourceNode = source(t, value, hapDuration, cps); + nodes['source'] = [sourceNode]; } else if (getSound(s)) { + debugger; const { onTrigger } = getSound(s); const onEnded = () => { audioNodes.forEach((n) => n?.disconnect()); @@ -692,6 +764,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) if (soundHandle) { sourceNode = soundHandle.node; activeSoundSources.set(chainID, soundHandle); + nodes['source'] = [soundHandle.oscillator]; } } else { throw new Error(`sound ${s} not found! Is it loaded?`); @@ -711,12 +784,14 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) stretch !== undefined && chain.push(getWorklet(ac, 'phase-vocoder-processor', { pitchFactor: stretch })); // gain stage - chain.push(gainNode(gain)); + const initialGain = gainNode(gain); + nodes['gain'] = [initialGain]; + chain.push(initialGain); //filter const ftype = getFilterType(value.ftype); if (cutoff !== undefined) { - let lp = () => + const lp = () => createFilter( ac, 'lowpass', @@ -733,14 +808,18 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) ftype, drive, ); - chain.push(lp()); + const lp1 = lp(); + nodes['lpf'] = [lp1]; + chain.push(lp1); if (ftype === '24db') { - chain.push(lp()); + const lp2 = lp(); + nodes['lpf'].push(lp2); + chain.push(lp2); } } if (hcutoff !== undefined) { - let hp = () => + const hp = () => createFilter( ac, 'highpass', @@ -755,31 +834,56 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) end, fanchor, ); - chain.push(hp()); + const hp1 = hp(); + nodes['hpf'] = [hp1]; + chain.push(hp1); if (ftype === '24db') { - chain.push(hp()); + const hp2 = hp(); + nodes['hpf'].push(hp1); + chain.push(hp2); } } if (bandf !== undefined) { let bp = () => createFilter(ac, 'bandpass', bandf, bandq, bpattack, bpdecay, bpsustain, bprelease, bpenv, t, end, fanchor); - chain.push(bp()); + const bp1 = bp(); + nodes['bpf'] = [bp1]; + chain.push(bp1); if (ftype === '24db') { - chain.push(bp()); + const bp2 = bp(); + nodes['bpf'].push(bp2); + chain.push(bp2); } } if (vowel !== undefined) { const vowelFilter = ac.createVowelFilter(vowel); + nodes['vowel'] = vowelFilter; chain.push(vowelFilter); } // effects - coarse !== undefined && chain.push(getWorklet(ac, 'coarse-processor', { coarse })); - crush !== undefined && chain.push(getWorklet(ac, 'crush-processor', { crush })); - shape !== undefined && chain.push(getWorklet(ac, 'shape-processor', { shape, postgain: shapevol })); - distort !== undefined && chain.push(getWorklet(ac, 'distort-processor', { distort, postgain: distortvol })); + if (coarse !== undefined) { + const coarseNode = getWorklet(ac, 'coarse-processor', { coarse }); + nodes['coarse'] = coarseNode; + chain.push(coarseNode); + } + if (crush !== undefined) { + const crushNode = getWorklet(ac, 'crush-processor', { crush }); + nodes['crush'] = crushNode; + chain.push(crushNode); + } + if (shape !== undefined) { + const shapeNode = getWorklet(ac, 'shape-processor', { shape }); + nodes['shape'] = shapeNode; + chain.push(shapeNode); + } + if (distort !== undefined) { + const distortNode = getWorklet(ac, 'distort-processor', { distort }); + nodes['distort'] = distortNode; + chain.push(distortNode); + } if (tremolosync != null) { tremolo = cps * tremolosync; @@ -808,10 +912,11 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) chain.push(amGain); } - compressorThreshold !== undefined && - chain.push( - getCompressor(ac, compressorThreshold, compressorRatio, compressorKnee, compressorAttack, compressorRelease), - ); + if (compressorThreshold !== undefined) { + const compressorNode = getCompressor(ac, compressorThreshold, compressorRatio, compressorKnee, compressorAttack, compressorRelease); + nodes['compressor'] = compressorNode; + chain.push(compressorNode); + } // panning if (pan !== undefined) { @@ -822,17 +927,20 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) // phaser if (phaser !== undefined && phaserdepth > 0) { const phaserFX = getPhaser(t, endWithRelease, phaser, phaserdepth, phasercenter, phasersweep); + nodes['phaser'] = phaserFX; chain.push(phaserFX); } // last gain const post = new GainNode(ac, { gain: postgain }); + nodes['post'] = post; chain.push(post); // delay let delaySend; if (delay > 0 && delaytime > 0 && delayfeedback > 0) { const delayNode = getDelay(orbit, delaytime, delayfeedback, t, orbitChannels); + nodes['delay'] = delayNode; delaySend = effectSend(post, delayNode, delay); audioNodes.push(delaySend); } @@ -851,6 +959,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) roomIR = await loadBuffer(url, ac, ir, 0); } const reverbNode = getReverb(orbit, roomsize, roomfade, roomlp, roomdim, roomIR, orbitChannels); + nodes['room'] = reverbNode; reverbSend = effectSend(post, reverbNode, room); audioNodes.push(reverbSend); } @@ -874,6 +983,9 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) // connect chain elements together chain.slice(1).reduce((last, current) => last.connect(current), chain[0]); audioNodes = audioNodes.concat(chain); + + // finally, now that `nodes` is populated, set up LFOs + connectLFO(lfoNum, lfoTarget, lfoParam, rate, lfo, lfoBipolar, lfoShape, t, endWithRelease); }; export const superdoughTrigger = (t, hap, ct, cps) => { diff --git a/packages/superdough/synth.mjs b/packages/superdough/synth.mjs index 71138ae41..3e1122b56 100644 --- a/packages/superdough/synth.mjs +++ b/packages/superdough/synth.mjs @@ -87,6 +87,7 @@ export function registerSynthSounds() { stop(envEnd); return { node, + oscillator: o, stop: (endTime) => { stop(endTime); }, @@ -156,6 +157,7 @@ export function registerSynthSounds() { return { node, + oscillator: o, stop: (endTime) => { o.stop(endTime); }, @@ -222,6 +224,7 @@ export function registerSynthSounds() { return { node: envGain, + oscillator: o, stop: (time) => { timeoutNode.stop(time); }, @@ -298,6 +301,7 @@ export function registerSynthSounds() { return { node: envGain, + oscillator: o, stop: (time) => { timeoutNode.stop(time); }, @@ -375,6 +379,7 @@ export function registerSynthSounds() { return { node: envGain, + oscillator: o, stop: (time) => { timeoutNode.stop(time); }, @@ -420,6 +425,7 @@ export function registerSynthSounds() { stop(envEnd); return { node, + oscillator: o, stop: (endTime) => { stop(endTime); }, @@ -492,6 +498,7 @@ export function getOscillator(s, t, value) { return { node: noiseMix?.node || o, + oscillator: o, stop: (time) => { fmModulator.stop(time); vibratoOscillator?.stop(time); From efb337677ced73c765f394efe749bb90298a9953 Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 20 Aug 2025 10:08:36 -0500 Subject: [PATCH 02/73] Fully working version with multiple LFOs --- packages/core/controls.mjs | 12 ++- packages/superdough/helpers.mjs | 4 +- packages/superdough/superdough.mjs | 119 ++++++++++++++++++++--------- packages/superdough/synth.mjs | 2 +- packages/superdough/worklets.mjs | 14 ++-- 5 files changed, 103 insertions(+), 48 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index ecb94ea58..83c085d0c 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -1428,13 +1428,17 @@ export const { panorient } = registerControl('panorient'); // ['pitch2'], // ['pitch3'], // ['portamento'], -// TODO: LFO rate see https://tidalcycles.org/docs/patternlib/tutorials/synthesizers/#supersquare -export const { rate } = registerControl('rate'); +export const { lfoNum } = registerControl('lfoNum'); export const { lfoTarget } = registerControl('lfoTarget'); export const { lfoParam } = registerControl('lfoParam'); -export const { lfoNum } = registerControl('lfoNum'); -export const { lfoBipolar } = registerControl('lfoBipolar'); +export const { lfoRate } = registerControl('lfoRate'); +export const { lfoDepth } = registerControl('lfoDepth'); +export const { lfoDCOffset } = registerControl('lfoDCOffset'); export const { lfoShape } = registerControl('lfoShape'); +export const { lfoSkew } = registerControl('lfoSkew'); +export const { lfoCurve } = registerControl('lfoCurve'); +export const { lfoSynced } = registerControl('lfoSynced'); + // TODO: slide param for certain synths export const { slide } = registerControl('slide'); // TODO: detune? https://tidalcycles.org/docs/patternlib/tutorials/synthesizers/#supersquare diff --git a/packages/superdough/helpers.mjs b/packages/superdough/helpers.mjs index c09acf1a5..31a8064c3 100644 --- a/packages/superdough/helpers.mjs +++ b/packages/superdough/helpers.mjs @@ -21,7 +21,9 @@ const getSlope = (y1, y2, x1, x2) => { export function getWorklet(ac, processor, params, config) { const node = new AudioWorkletNode(ac, processor, config); Object.entries(params).forEach(([key, value]) => { - node.parameters.get(key).value = value; + if (value !== undefined) { + node.parameters.get(key).value = value; + } }); return node; } diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index c55cbe0a0..67f86cb87 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -345,31 +345,21 @@ function getDelay(orbit, delaytime, delayfeedback, t, channels) { return orbits[orbit].delayNode; } -export function getLfo(audioContext, begin, end, properties = {}) { - const { shape = 0, ...props } = properties; - const { dcoffset = -0.5, depth = 1 } = properties; +export function getLfo(audioContext, properties = {}) { + // Extract some params we need for deriving other params + const { begin, shape = 0, ...props } = properties; const lfoprops = { - frequency: 1, - depth, - skew: 0.5, - phaseoffset: 0, time: begin, - begin, - end, shape: getModulationShapeInput(shape), - dcoffset, - min: dcoffset * depth, - max: dcoffset * depth + depth, - curve: 1, ...props, }; return getWorklet(audioContext, 'lfo-processor', lfoprops); } -function getPhaser(time, end, frequency = 1, depth = 0.5, centerFrequency = 1000, sweep = 2000) { +function getPhaser(begin, end, frequency = 1, depth = 0.5, centerFrequency = 1000, sweep = 2000) { const ac = getAudioContext(); - const lfoGain = getLfo(ac, time, end, { frequency, depth: sweep * 2 }); + const lfoGain = getLfo(ac, { frequency, depth: sweep * 2, begin, end }); //filters const numStages = 2; //num of filters in series @@ -542,34 +532,69 @@ function _getNodeParams(node) { return Array.from(params); } -function connectLFO(lfoNum, target, param, frequency, depth, shape, bipolar, start, end) { - debugger; +function _connectLFO(params) { + const { + frequency = 1, + synced = 0, + cps = 0.5, + lfoNum = 1, // default to LFO 1 + lfoTarget, + lfoParam, + ...filteredParams + } = params; + filteredParams['frequency'] = synced ? frequency / cps : frequency; let lfoNode = lfos[lfoNum]; - const params = { - frequency, - depth, - } if (lfoNode == null) { const ac = getAudioContext(); - const dcoffset = bipolar > 0.5 ? -0.5 : 0; - lfoNode = getLfo(ac, start, 1e9, { frequency, depth, shape, dcoffset}); + lfoNode = getLfo(ac, filteredParams); lfos[lfoNum] = lfoNode; } lfoNode.disconnect(); - const targetNodes = nodes[target]; + const targetNodes = nodes[lfoTarget]; + if (targetNodes === undefined) { + const keys = Object.keys(nodes); + errorLogger(new Error(`Could not connect to target ${lfoTarget} -- it does not exist. Available options are ${keys.join(", ")}`), 'superdough'); + return; + } targetNodes.forEach((targetNode) => { - if (targetNode === undefined) { - const keys = Object.keys(nodes); - errorLogger(new Error(`Could not connect to target ${target} -- it does not exist. Available options are ${keys.join(", ")}`), 'superdough'); - return; - } - const targetParam = _getNodeParam(targetNode, param); + const targetParam = _getNodeParam(targetNode, lfoParam); if (targetParam === undefined) { const parameters = _getNodeParams(targetNode); - errorLogger(new Error(`Could not connect to parameter ${param} on node ${target}. Available parameters are ${parameters.join(", ")}`), 'superdough'); + errorLogger(new Error(`Could not connect to parameter ${lfoParam} on node ${lfoTarget}. Available parameters are ${parameters.join(", ")}`), 'superdough'); } lfoNode.connect(targetParam); }); + const time = filteredParams.begin; + for (const [name, value] of Object.entries(filteredParams)) { + if (value == null) continue; + const p = lfoNode.parameters?.get(name); + if (p.cancelAndHoldAtTime) p.cancelAndHoldAtTime(time); + else p.cancelScheduledValues(time); + p.setValueAtTime(value, time); + } +} + +function connectLFOs(time, params) { + // We break down params specifying multiple LFOs into a set of parameters for + // a single LFO + const numLFOs = [ + [params.lfoNum].flat().length, + [params.lfoTarget].flat().length, + [params.lfoParam].flat().length, + ].reduce((a, v) => Math.max(a, v)); // Number of LFOs is the max as implied by these values + for (let i = 0; i < numLFOs; i++) { + let singleParams = {}; + for (const k in params) { + const v = params[k]; + const flatV = [v].flat(); + if (flatV.length !== numLFOs && flatV.length !== 1) { + errorLogger(new Error(`Could not setup LFOs. We derived ${numLFOs} as the intended number of LFOs, but ${k}: ${flatV} does not have matching length nor length 1`)); + return; + } + singleParams[k] = flatV[i] ?? flatV[0]; + } + _connectLFO(singleParams); + } } let activeSoundSources = new Map(); @@ -691,13 +716,16 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) compressorKnee, compressorAttack, compressorRelease, - lfo, lfoNum, - rate, lfoTarget, lfoParam, - lfoBipolar, + lfoRate, + lfoDepth, + lfoDCOffset, lfoShape, + lfoSkew, + lfoCurve, + lfoSynced, } = value; delaytime = delaytime ?? cycleToSeconds(delaysync, cps); @@ -753,7 +781,6 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) sourceNode = source(t, value, hapDuration, cps); nodes['source'] = [sourceNode]; } else if (getSound(s)) { - debugger; const { onTrigger } = getSound(s); const onEnded = () => { audioNodes.forEach((n) => n?.disconnect()); @@ -896,7 +923,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) const amGain = new GainNode(ac, { gain }); const time = cycle / cps; - const lfo = getLfo(ac, t, endWithRelease, { + const lfo = getLfo(ac, { skew: tremoloskew ?? (tremoloshape != null ? 0.5 : 1), frequency: tremolo, depth: tremolodepth, @@ -907,6 +934,8 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) min: 0, max: 1, curve: 1.5, + begin: t, + end: endWithRelease, }); lfo.connect(amGain.gain); chain.push(amGain); @@ -985,7 +1014,23 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) audioNodes = audioNodes.concat(chain); // finally, now that `nodes` is populated, set up LFOs - connectLFO(lfoNum, lfoTarget, lfoParam, rate, lfo, lfoBipolar, lfoShape, t, endWithRelease); + if (lfoTarget !== undefined && lfoParam !== undefined) { + connectLFOs(t, { + lfoNum, + lfoTarget, + lfoParam, + frequency: lfoRate, + depth: lfoDepth, + dcoffset: lfoDCOffset ?? 0, // override default value of 0.5 + shape: lfoShape, + skew: lfoSkew, + curve: lfoCurve, + persistent: 1, + begin: t, + synced: lfoSynced, + cps: cps, + }); + } }; export const superdoughTrigger = (t, hap, ct, cps) => { diff --git a/packages/superdough/synth.mjs b/packages/superdough/synth.mjs index 3e1122b56..a242bfdf3 100644 --- a/packages/superdough/synth.mjs +++ b/packages/superdough/synth.mjs @@ -360,7 +360,7 @@ export function registerSynthSounds() { getParamADSR(envGain.gain, attack, decay, sustain, release, 0, 1, begin, holdend, 'linear'); let lfo; if (pwsweep != 0) { - lfo = getLfo(ac, begin, end, { frequency: pwrate, depth: pwsweep }); + lfo = getLfo(ac, { frequency: pwrate, depth: pwsweep, begin, end }); lfo.connect(o.parameters.get('pulsewidth')); } let timeoutNode = webAudioTimeout( diff --git a/packages/superdough/worklets.mjs b/packages/superdough/worklets.mjs index 2406d56dc..f6d7bbec4 100644 --- a/packages/superdough/worklets.mjs +++ b/packages/superdough/worklets.mjs @@ -108,6 +108,7 @@ class LFOProcessor extends AudioWorkletProcessor { { name: 'dcoffset', defaultValue: 0 }, { name: 'min', defaultValue: 0 }, { name: 'max', defaultValue: 1 }, + { name: 'persistent', defaultValue: 0, min: 0, max: 1 }, // whether to ignore end ]; } @@ -123,9 +124,11 @@ class LFOProcessor extends AudioWorkletProcessor { } } - process(inputs, outputs, parameters) { + process(_inputs, outputs, parameters) { const begin = parameters['begin'][0]; - if (currentTime >= parameters.end[0]) { + const end = parameters['end'][0]; + const persistent = parameters['persistent'][0]; + if ((persistent < 0.5) && currentTime >= end) { return false; } if (currentTime <= begin) { @@ -143,8 +146,9 @@ class LFOProcessor extends AudioWorkletProcessor { const curve = parameters['curve'][0]; const dcoffset = parameters['dcoffset'][0]; - const min = parameters['min'][0]; - const max = parameters['max'][0]; + + const min = dcoffset * depth; + const max = dcoffset * depth + depth; const shape = waveShapeNames[parameters['shape'][0]]; const blockSize = output[0].length ?? 0; @@ -161,7 +165,7 @@ class LFOProcessor extends AudioWorkletProcessor { } this.incrementPhase(dt); } - + return true; } } From e25eab11ad63ff15ebd6651e9f6f00bcad596fd1 Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 20 Aug 2025 10:47:57 -0500 Subject: [PATCH 03/73] Working version of envelopes --- packages/core/controls.mjs | 11 ++++ packages/superdough/superdough.mjs | 100 +++++++++++++++++++++++++++-- 2 files changed, 106 insertions(+), 5 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index 83c085d0c..9deede798 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -1439,6 +1439,17 @@ export const { lfoSkew } = registerControl('lfoSkew'); export const { lfoCurve } = registerControl('lfoCurve'); export const { lfoSynced } = registerControl('lfoSynced'); + +export const { envNum } = registerControl('envNum'); +export const { envTarget } = registerControl('envTarget'); +export const { envParam } = registerControl('envParam'); +export const { envAttack } = registerControl('envAttack'); +export const { envDecay } = registerControl('envDecay'); +export const { envSustain } = registerControl('envSustain'); +export const { envRelease } = registerControl('envRelease'); +export const { envCurve } = registerControl('envCurve'); +export const { envDepth } = registerControl('envDepth'); + // TODO: slide param for certain synths export const { slide } = registerControl('slide'); // TODO: detune? https://tidalcycles.org/docs/patternlib/tutorials/synthesizers/#supersquare diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 67f86cb87..e01655cd4 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -9,7 +9,7 @@ import './reverb.mjs'; import './vowel.mjs'; import { clamp, nanFallback, _mod, cycleToSeconds, secondsToCycle } from './util.mjs'; import workletsUrl from './worklets.mjs?audioworklet'; -import { createFilter, gainNode, getCompressor, getWorklet, webAudioTimeout } from './helpers.mjs'; +import { createFilter, gainNode, getCompressor, getWorklet, webAudioTimeout, getADSRValues, getParamADSR } from './helpers.mjs'; import { map } from 'nanostores'; import { logger, errorLogger } from './logger.mjs'; import { loadBuffer } from './sampler.mjs'; @@ -532,6 +532,7 @@ function _getNodeParams(node) { return Array.from(params); } +let lfos = {}; function _connectLFO(params) { const { frequency = 1, @@ -574,7 +575,7 @@ function _connectLFO(params) { } } -function connectLFOs(time, params) { +function connectLFOs(params) { // We break down params specifying multiple LFOs into a set of parameters for // a single LFO const numLFOs = [ @@ -597,6 +598,72 @@ function connectLFOs(time, params) { } } +function _connectEnvelope(params) { + const { + envNum = 1, // default to envelope 1 + envTarget, + envParam, + envDepth, + begin, + end, + attack, + decay, + sustain, + release, + curve, + ...filteredParams + } = params; + const targetNodes = nodes[envTarget]; + if (targetNodes === undefined) { + const keys = Object.keys(nodes); + errorLogger(new Error(`Could not connect to target ${envTarget} -- it does not exist. Available options are ${keys.join(", ")}`), 'superdough'); + return; + } + targetNodes.forEach((targetNode) => { + const targetParam = _getNodeParam(targetNode, envParam); + if (targetParam === undefined) { + const parameters = _getNodeParams(targetNode); + errorLogger(new Error(`Could not connect to parameter ${envParam} on node ${envTarget}. Available parameters are ${parameters.join(", ")}`), 'superdough'); + } + const [att, dec, sus, rel] = getADSRValues( + [ + attack, + decay, + sustain, + release, + ], + curve, + [0.005, 0.14, 0, 0.1] + ); + const min = 0; + const max = envDepth; + getParamADSR(targetParam, att, dec, sus, rel, min, max, begin, end, curve); + }); +} + +function connectEnvelopes(params) { + // We break down params specifying multiple envelopes into a set of parameters for + // a single envelopes + const numEnvelopes = [ + [params.envNum].flat().length, + [params.envTarget].flat().length, + [params.envParam].flat().length, + ].reduce((a, v) => Math.max(a, v)); // Number of envelopes is the max as implied by these values + for (let i = 0; i < numEnvelopes; i++) { + let singleParams = {}; + for (const k in params) { + const v = params[k]; + const flatV = [v].flat(); + if (flatV.length !== numEnvelopes && flatV.length !== 1) { + errorLogger(new Error(`Could not setup envelopes. We derived ${numEnvelopes} as the intended number of envelopes, but ${k}: ${flatV} does not have matching length nor length 1`)); + return; + } + singleParams[k] = flatV[i] ?? flatV[0]; + } + _connectEnvelope(singleParams); + } +} + let activeSoundSources = new Map(); //music programs/audio gear usually increments inputs/outputs from 1, we need to subtract 1 from the input because the webaudio API channels start at 0 @@ -605,7 +672,6 @@ function mapChannelNumbers(channels) { } let nodes = {}; -let lfos = {}; export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) => { // new: t is always expected to be the absolute target onset time @@ -726,6 +792,15 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) lfoSkew, lfoCurve, lfoSynced, + envNum, + envTarget, + envParam, + envAttack, + envDecay, + envSustain, + envRelease, + envCurve, + envDepth, } = value; delaytime = delaytime ?? cycleToSeconds(delaysync, cps); @@ -1013,9 +1088,9 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) chain.slice(1).reduce((last, current) => last.connect(current), chain[0]); audioNodes = audioNodes.concat(chain); - // finally, now that `nodes` is populated, set up LFOs + // finally, now that `nodes` is populated, set up LFOs and envelopes if (lfoTarget !== undefined && lfoParam !== undefined) { - connectLFOs(t, { + connectLFOs({ lfoNum, lfoTarget, lfoParam, @@ -1031,6 +1106,21 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) cps: cps, }); } + if (envTarget !== undefined && envParam !== undefined) { + connectEnvelopes({ + envNum, + envTarget, + envParam, + envDepth, + attack: envAttack, + decay: envDecay, + sustain: envSustain, + release: envRelease, + curve: envCurve, + begin: t, + end: endWithRelease, + }); + } }; export const superdoughTrigger = (t, hap, ct, cps) => { From d8f0d70908705263cb69957a14e6331a79ce3dd8 Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 20 Aug 2025 13:22:37 -0500 Subject: [PATCH 04/73] Big refactor; start envelope at current value --- packages/core/controls.mjs | 2 - packages/superdough/superdough.mjs | 237 ++++++++++++++++------------- 2 files changed, 130 insertions(+), 109 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index 9deede798..ddbfe98eb 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -1439,8 +1439,6 @@ export const { lfoSkew } = registerControl('lfoSkew'); export const { lfoCurve } = registerControl('lfoCurve'); export const { lfoSynced } = registerControl('lfoSynced'); - -export const { envNum } = registerControl('envNum'); export const { envTarget } = registerControl('envTarget'); export const { envParam } = registerControl('envParam'); export const { envAttack } = registerControl('envAttack'); diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index e01655cd4..6145b3981 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -532,15 +532,100 @@ function _getNodeParams(node) { return Array.from(params); } +/** + * Split parameters (which might be arrays -- implying multiple-parameter modulation -- or a single number) into independent + * objects which only account for single-parameter modulation + * + * @param {Object} params - Dictionary of modulation parameters. + * @returns {Object[]} - Array of parameter objects, one per parameter modulation + */ +function _splitParams(params, countKeys) { + const num = ["num", "target", "parameter"] // names used to indicate individual parameter modulations + .map((k) => [params[k] ?? 0].flat().length) + .reduce((a, v) => Math.max(a, v), 1); + + const individualParams = []; + for (let i = 0; i < num; i++) { + const paramsI = {}; + for (const k in params) { + const flatV = [params[k]].flat(); + if (flatV.length !== num && flatV.length !== 1) { + errorLogger( + new Error( + `Could not set up modulations. We derived ${num} items, but ${k}: ${JSON.stringify(flatV)} has length ${flatV.length} (needs 1 or ${num}).` + ), + 'superdough' + ); + return []; + } + paramsI[k] = flatV[i] ?? flatV[0]; + } + individualParams.push(paramsI); + } + return individualParams; +} + +/** + * Given a node name and the name of a parameter on that node, attempt to retrieve + * all nodes corresponding to the name and their associated parameters + * + * Note that we say nodes, plural, because some nodes have multiple sub-nodes, like a + * 24db filter which is two filters in series + * + * @param {string} targetName - Name of the node to modulate parameters on (e.g. `lpf`, `source`, etc.) + * @param {string} paramName - Name of the parameter to modulate on that node + * @returns {AudioParam[]} - Array of audio parameter objects for modulation + * + */ +function _getTargetParams(targetName, paramName) { + const targetNodes = nodes[targetName]; + if (!targetNodes) { + const keys = Object.keys(nodes); + errorLogger( + new Error(`Could not connect to target '${targetName}' — it does not exist. Available targets: ${keys.join(", ")}`), + 'superdough' + ); + return []; + } + + const audioParams = []; + targetNodes.forEach((targetNode) => { + const targetParam = _getNodeParam(targetNode, paramName); + if (!targetParam) { + const available = _getNodeParams(targetNode); + errorLogger( + new Error( + `Could not connect to parameter '${paramName}' on '${targetName}'. Available parameters: ${available.join(", ")}` + ), + 'superdough' + ); + return; + } + audioParams.push(targetParam); + }); + return audioParams; +} + +function _setWorkletParamsAtTime(audioParams, params, time) { + for (const [name, value] of params) { + if (value == null) continue; + const p = audioParams.get(name); + if (p.cancelAndHoldAtTime) p.cancelAndHoldAtTime(time); + else p.cancelScheduledValues(time); + p.setValueAtTime(value, time); + } +} + let lfos = {}; function _connectLFO(params) { const { frequency = 1, synced = 0, cps = 0.5, - lfoNum = 1, // default to LFO 1 - lfoTarget, - lfoParam, + num = 1, // default to LFO 1 + target, + param, + begin, ...filteredParams } = params; filteredParams['frequency'] = synced ? frequency / cps : frequency; @@ -548,61 +633,22 @@ function _connectLFO(params) { if (lfoNode == null) { const ac = getAudioContext(); lfoNode = getLfo(ac, filteredParams); - lfos[lfoNum] = lfoNode; + lfos[num] = lfoNode; } - lfoNode.disconnect(); - const targetNodes = nodes[lfoTarget]; - if (targetNodes === undefined) { - const keys = Object.keys(nodes); - errorLogger(new Error(`Could not connect to target ${lfoTarget} -- it does not exist. Available options are ${keys.join(", ")}`), 'superdough'); - return; - } - targetNodes.forEach((targetNode) => { - const targetParam = _getNodeParam(targetNode, lfoParam); - if (targetParam === undefined) { - const parameters = _getNodeParams(targetNode); - errorLogger(new Error(`Could not connect to parameter ${lfoParam} on node ${lfoTarget}. Available parameters are ${parameters.join(", ")}`), 'superdough'); - } - lfoNode.connect(targetParam); - }); - const time = filteredParams.begin; - for (const [name, value] of Object.entries(filteredParams)) { - if (value == null) continue; - const p = lfoNode.parameters?.get(name); - if (p.cancelAndHoldAtTime) p.cancelAndHoldAtTime(time); - else p.cancelScheduledValues(time); - p.setValueAtTime(value, time); - } -} - -function connectLFOs(params) { - // We break down params specifying multiple LFOs into a set of parameters for - // a single LFO - const numLFOs = [ - [params.lfoNum].flat().length, - [params.lfoTarget].flat().length, - [params.lfoParam].flat().length, - ].reduce((a, v) => Math.max(a, v)); // Number of LFOs is the max as implied by these values - for (let i = 0; i < numLFOs; i++) { - let singleParams = {}; - for (const k in params) { - const v = params[k]; - const flatV = [v].flat(); - if (flatV.length !== numLFOs && flatV.length !== 1) { - errorLogger(new Error(`Could not setup LFOs. We derived ${numLFOs} as the intended number of LFOs, but ${k}: ${flatV} does not have matching length nor length 1`)); - return; - } - singleParams[k] = flatV[i] ?? flatV[0]; - } - _connectLFO(singleParams); + try { + lfoNode.disconnect(); + } catch { + // pass } + const targets = _getTargetParams(target, param); + targets.forEach((target) => lfoNode.connect(target)); + _setWorkletParamsAtTime(lfoNode.parameters, Object.entries(filteredParams), begin); } function _connectEnvelope(params) { const { - envNum = 1, // default to envelope 1 - envTarget, - envParam, + target, + param, envDepth, begin, end, @@ -613,54 +659,33 @@ function _connectEnvelope(params) { curve, ...filteredParams } = params; - const targetNodes = nodes[envTarget]; - if (targetNodes === undefined) { - const keys = Object.keys(nodes); - errorLogger(new Error(`Could not connect to target ${envTarget} -- it does not exist. Available options are ${keys.join(", ")}`), 'superdough'); - return; - } - targetNodes.forEach((targetNode) => { - const targetParam = _getNodeParam(targetNode, envParam); - if (targetParam === undefined) { - const parameters = _getNodeParams(targetNode); - errorLogger(new Error(`Could not connect to parameter ${envParam} on node ${envTarget}. Available parameters are ${parameters.join(", ")}`), 'superdough'); - } - const [att, dec, sus, rel] = getADSRValues( - [ - attack, - decay, - sustain, - release, - ], - curve, - [0.005, 0.14, 0, 0.1] - ); - const min = 0; - const max = envDepth; + const targets = _getTargetParams(target, param); + const [att, dec, sus, rel] = getADSRValues( + [ + attack, + decay, + sustain, + release, + ], + curve, + [0.005, 0.14, 0, 0.1] + ); + targets.forEach((targetParam) => { + const currentValue = targetParam.value; + const min = currentValue; + const max = currentValue + envDepth; getParamADSR(targetParam, att, dec, sus, rel, min, max, begin, end, curve); }); } -function connectEnvelopes(params) { - // We break down params specifying multiple envelopes into a set of parameters for - // a single envelopes - const numEnvelopes = [ - [params.envNum].flat().length, - [params.envTarget].flat().length, - [params.envParam].flat().length, - ].reduce((a, v) => Math.max(a, v)); // Number of envelopes is the max as implied by these values - for (let i = 0; i < numEnvelopes; i++) { - let singleParams = {}; - for (const k in params) { - const v = params[k]; - const flatV = [v].flat(); - if (flatV.length !== numEnvelopes && flatV.length !== 1) { - errorLogger(new Error(`Could not setup envelopes. We derived ${numEnvelopes} as the intended number of envelopes, but ${k}: ${flatV} does not have matching length nor length 1`)); - return; - } - singleParams[k] = flatV[i] ?? flatV[0]; - } - _connectEnvelope(singleParams); +function connectModulators(params, modulatorType) { + // We break down params specifying multiple modulators into a set of parameters for + // a single one + const individualParams = _splitParams(params); + if (modulatorType === "lfo") { + individualParams.forEach(_connectLFO); + } else if (modulatorType === "envelope") { + individualParams.forEach(_connectEnvelope); } } @@ -792,7 +817,6 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) lfoSkew, lfoCurve, lfoSynced, - envNum, envTarget, envParam, envAttack, @@ -1090,10 +1114,10 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) // finally, now that `nodes` is populated, set up LFOs and envelopes if (lfoTarget !== undefined && lfoParam !== undefined) { - connectLFOs({ - lfoNum, - lfoTarget, - lfoParam, + connectModulators({ + num: lfoNum, + target: lfoTarget, + param: lfoParam, frequency: lfoRate, depth: lfoDepth, dcoffset: lfoDCOffset ?? 0, // override default value of 0.5 @@ -1104,13 +1128,12 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) begin: t, synced: lfoSynced, cps: cps, - }); + }, "lfo"); } if (envTarget !== undefined && envParam !== undefined) { - connectEnvelopes({ - envNum, - envTarget, - envParam, + connectModulators({ + target: envTarget, + param: envParam, envDepth, attack: envAttack, decay: envDecay, @@ -1119,7 +1142,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) curve: envCurve, begin: t, end: endWithRelease, - }); + }, "envelope"); } }; From 6a9739bed509839b5e6a4d7b9673f2f6853c63a1 Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 20 Aug 2025 13:39:24 -0500 Subject: [PATCH 05/73] Code format and a typo on lfoNum --- packages/superdough/superdough.mjs | 131 +++++++++++++++-------------- packages/superdough/worklets.mjs | 4 +- 2 files changed, 69 insertions(+), 66 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 6145b3981..97f3900d0 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -9,7 +9,15 @@ import './reverb.mjs'; import './vowel.mjs'; import { clamp, nanFallback, _mod, cycleToSeconds, secondsToCycle } from './util.mjs'; import workletsUrl from './worklets.mjs?audioworklet'; -import { createFilter, gainNode, getCompressor, getWorklet, webAudioTimeout, getADSRValues, getParamADSR } from './helpers.mjs'; +import { + createFilter, + gainNode, + getCompressor, + getWorklet, + webAudioTimeout, + getADSRValues, + getParamADSR, +} from './helpers.mjs'; import { map } from 'nanostores'; import { logger, errorLogger } from './logger.mjs'; import { loadBuffer } from './sampler.mjs'; @@ -527,8 +535,9 @@ function _getNodeParams(node) { node.parameters.forEach((_v, k) => params.add(k)); } // Guesses based on common parameters - ["gain", "frequency", "detune", "Q", "pan", "playbackRate", "delayTime"] - .forEach((k) => { if (node?.[k] instanceof AudioParam) params.add(k); }); + ['gain', 'frequency', 'detune', 'Q', 'pan', 'playbackRate', 'delayTime'].forEach((k) => { + if (node?.[k] instanceof AudioParam) params.add(k); + }); return Array.from(params); } @@ -540,7 +549,7 @@ function _getNodeParams(node) { * @returns {Object[]} - Array of parameter objects, one per parameter modulation */ function _splitParams(params, countKeys) { - const num = ["num", "target", "parameter"] // names used to indicate individual parameter modulations + const num = ['num', 'target', 'parameter'] // names used to indicate individual parameter modulations .map((k) => [params[k] ?? 0].flat().length) .reduce((a, v) => Math.max(a, v), 1); @@ -552,9 +561,9 @@ function _splitParams(params, countKeys) { if (flatV.length !== num && flatV.length !== 1) { errorLogger( new Error( - `Could not set up modulations. We derived ${num} items, but ${k}: ${JSON.stringify(flatV)} has length ${flatV.length} (needs 1 or ${num}).` + `Could not set up modulations. We derived ${num} items, but ${k}: ${JSON.stringify(flatV)} has length ${flatV.length} (needs 1 or ${num}).`, ), - 'superdough' + 'superdough', ); return []; } @@ -582,8 +591,10 @@ function _getTargetParams(targetName, paramName) { if (!targetNodes) { const keys = Object.keys(nodes); errorLogger( - new Error(`Could not connect to target '${targetName}' — it does not exist. Available targets: ${keys.join(", ")}`), - 'superdough' + new Error( + `Could not connect to target '${targetName}' — it does not exist. Available targets: ${keys.join(', ')}`, + ), + 'superdough', ); return []; } @@ -595,9 +606,9 @@ function _getTargetParams(targetName, paramName) { const available = _getNodeParams(targetNode); errorLogger( new Error( - `Could not connect to parameter '${paramName}' on '${targetName}'. Available parameters: ${available.join(", ")}` + `Could not connect to parameter '${paramName}' on '${targetName}'. Available parameters: ${available.join(', ')}`, ), - 'superdough' + 'superdough', ); return; } @@ -629,7 +640,7 @@ function _connectLFO(params) { ...filteredParams } = params; filteredParams['frequency'] = synced ? frequency / cps : frequency; - let lfoNode = lfos[lfoNum]; + let lfoNode = lfos[num]; if (lfoNode == null) { const ac = getAudioContext(); lfoNode = getLfo(ac, filteredParams); @@ -646,30 +657,9 @@ function _connectLFO(params) { } function _connectEnvelope(params) { - const { - target, - param, - envDepth, - begin, - end, - attack, - decay, - sustain, - release, - curve, - ...filteredParams - } = params; + const { target, param, envDepth, begin, end, attack, decay, sustain, release, curve, ...filteredParams } = params; const targets = _getTargetParams(target, param); - const [att, dec, sus, rel] = getADSRValues( - [ - attack, - decay, - sustain, - release, - ], - curve, - [0.005, 0.14, 0, 0.1] - ); + const [att, dec, sus, rel] = getADSRValues([attack, decay, sustain, release], curve, [0.005, 0.14, 0, 0.1]); targets.forEach((targetParam) => { const currentValue = targetParam.value; const min = currentValue; @@ -682,9 +672,9 @@ function connectModulators(params, modulatorType) { // We break down params specifying multiple modulators into a set of parameters for // a single one const individualParams = _splitParams(params); - if (modulatorType === "lfo") { + if (modulatorType === 'lfo') { individualParams.forEach(_connectLFO); - } else if (modulatorType === "envelope") { + } else if (modulatorType === 'envelope') { individualParams.forEach(_connectEnvelope); } } @@ -1041,7 +1031,14 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) } if (compressorThreshold !== undefined) { - const compressorNode = getCompressor(ac, compressorThreshold, compressorRatio, compressorKnee, compressorAttack, compressorRelease); + const compressorNode = getCompressor( + ac, + compressorThreshold, + compressorRatio, + compressorKnee, + compressorAttack, + compressorRelease, + ); nodes['compressor'] = compressorNode; chain.push(compressorNode); } @@ -1114,35 +1111,41 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) // finally, now that `nodes` is populated, set up LFOs and envelopes if (lfoTarget !== undefined && lfoParam !== undefined) { - connectModulators({ - num: lfoNum, - target: lfoTarget, - param: lfoParam, - frequency: lfoRate, - depth: lfoDepth, - dcoffset: lfoDCOffset ?? 0, // override default value of 0.5 - shape: lfoShape, - skew: lfoSkew, - curve: lfoCurve, - persistent: 1, - begin: t, - synced: lfoSynced, - cps: cps, - }, "lfo"); + connectModulators( + { + num: lfoNum, + target: lfoTarget, + param: lfoParam, + frequency: lfoRate, + depth: lfoDepth, + dcoffset: lfoDCOffset ?? 0, // override default value of 0.5 + shape: lfoShape, + skew: lfoSkew, + curve: lfoCurve, + persistent: 1, + begin: t, + synced: lfoSynced, + cps: cps, + }, + 'lfo', + ); } if (envTarget !== undefined && envParam !== undefined) { - connectModulators({ - target: envTarget, - param: envParam, - envDepth, - attack: envAttack, - decay: envDecay, - sustain: envSustain, - release: envRelease, - curve: envCurve, - begin: t, - end: endWithRelease, - }, "envelope"); + connectModulators( + { + target: envTarget, + param: envParam, + envDepth, + attack: envAttack, + decay: envDecay, + sustain: envSustain, + release: envRelease, + curve: envCurve, + begin: t, + end: endWithRelease, + }, + 'envelope', + ); } }; diff --git a/packages/superdough/worklets.mjs b/packages/superdough/worklets.mjs index f6d7bbec4..9ab552d48 100644 --- a/packages/superdough/worklets.mjs +++ b/packages/superdough/worklets.mjs @@ -128,7 +128,7 @@ class LFOProcessor extends AudioWorkletProcessor { const begin = parameters['begin'][0]; const end = parameters['end'][0]; const persistent = parameters['persistent'][0]; - if ((persistent < 0.5) && currentTime >= end) { + if (persistent < 0.5 && currentTime >= end) { return false; } if (currentTime <= begin) { @@ -165,7 +165,7 @@ class LFOProcessor extends AudioWorkletProcessor { } this.incrementPhase(dt); } - + return true; } } From 9c8e39d83d4415cbdaab6960986fa2fe1ec2d569 Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 27 Aug 2025 16:27:36 -0500 Subject: [PATCH 06/73] Add.. a lot of doc strings --- packages/core/controls.mjs | 269 +++++++++++++++++++++++++++++ packages/superdough/superdough.mjs | 2 +- 2 files changed, 270 insertions(+), 1 deletion(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index ddbfe98eb..a078c2b6f 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -1428,24 +1428,293 @@ export const { panorient } = registerControl('panorient'); // ['pitch2'], // ['pitch3'], // ['portamento'], +/** + * Selects which LFO number to use for modulation. Multiple LFOs + * can be applied using the ':' mininotation. There are an arbitrary number + * of LFOs available -- the number is only used to share LFOs across targets + * if desired (and to conserve processing power) + * + * @name lfoNum + * @param {number | Pattern} lfoNum Index of the LFO. + * setup: note("F2").sound("supersaw") + * .lpf(100) + * .lfoDepth(1000) + * .lfoRate(0.25) + * .lfoSynced(1) + * .lfoTarget("lpf") + * .lfoParam("frequency") + * .lfoNum(2) + * + * reuse: note("F3").sound("square").lpf(50) + * .lfoTarget("lpf") + * .lfoParam("frequency") + * .lfoNum(2) // uses the same LFO + */ export const { lfoNum } = registerControl('lfoNum'); + +/** + * Sets the target destination for the LFO modulation. Names are typically related + * to existing controls ("source", "lpf", "vibrato", etc.). You can try a value + * and if it fails, the console will print the available options. + * + * @name lfoTarget + * @param {string | Pattern} lfoTarget Target identifier for modulation. + * note("F2").sound("supersaw") + * .lpf(100) + * .lfoDepth(3000) + * .lfoRate(0.25) + * .lfoSynced(1) + * .lfoTarget("lpf") + * .lfoParam("frequency") + */ export const { lfoTarget } = registerControl('lfoTarget'); + +/** + * Chooses which parameter the LFO will modulate on the target. Parameter values + * are things like "frequency", "Q", "detune", etc. You can try a value + * and if it fails, the console will print the available options. + * + * @name lfoParam + * @param {string | Pattern} lfoParam Parameter name + * note("F2").sound("supersaw") + * .lpf(100) + * .lfoDepth(3000) + * .lfoRate(0.25) + * .lfoSynced(1) + * .lfoTarget("lpf") + * .lfoParam("frequency") + */ export const { lfoParam } = registerControl('lfoParam'); + +/** + * Controls the speed of the LFO. + * + * @name lfoRate + * @param {number | Pattern} lfoRate Frequency or tempo-relative value. + * note("F2").sound("supersaw") + * .lpf(100) + * .lfoTarget("lpf") + * .lfoParam("frequency") + * .lfoDepth(3000) + * .lfoRate(0.25) + */ export const { lfoRate } = registerControl('lfoRate'); + +/** + * Sets the modulation depth of the LFO. + * + * @name lfoDepth + * @param {number | Pattern} lfoDepth Modulation depth amount. + * note("F2").sound("supersaw") + * .lpf(100) + * .lfoTarget("lpf") + * .lfoParam("frequency") + * .lfoSynced(1) + * .lfoDepth(5000) + */ export const { lfoDepth } = registerControl('lfoDepth'); + +/** + * Applies a DC offset to the LFO signal. Normally the LFO varies from + * 0 to 1 (i.e. unipolar). By using an offset of -0.5, one can achieve + * a bipolar LFO. + * + * @name lfoDCOffset + * @param {number | Pattern} lfoDCOffset Offset amount. + * note("F2").sound("supersaw") + * .lpf(2000) + * .lfoTarget("lpf") + * .lfoParam("frequency") + * .lfoDepth(1000) + * .lfoRate(4) + * .lfoSynced(1) + * .lfoDCOffset(-0.5) + */ export const { lfoDCOffset } = registerControl('lfoDCOffset'); + +/** + * Selects the waveform shape of the LFO. Current options are + * triangle, square, sine, saw, ramp (corresponding to 0 through 4, + * respectively). + * + * @name lfoShape + * @param {number | Pattern} lfoShape Waveform type identifier. + * note("F2").sound("supersaw") + * .lpf(100) + * .lfoTarget("lpf") + * .lfoParam("frequency") + * .lfoDepth(1000) + * .lfoRate(4) + * .lfoSynced(1) + * .lfoShape(3) + */ export const { lfoShape } = registerControl('lfoShape'); + +/** + * Skews the LFO waveform. + * + * @name lfoSkew + * @param {number | Pattern} lfoSkew Skew amount (between 0 and 1). + * note("F2").sound("supersaw") + * .lpf(100) + * .lfoTarget("lpf") + * .lfoParam("frequency") + * .lfoDepth(1000) + * .lfoRate(4) + * .lfoSynced(1) + * .lfoSkew(0.75) + */ export const { lfoSkew } = registerControl('lfoSkew'); + +/** + * Adjusts the (exponential) curvature of the LFO waveform. + * + * @name lfoCurve + * @param {number | Pattern} lfoCurve Curve shaping amount. + * note("F2").sound("supersaw") + * .lpf(100) + * .lfoTarget("lpf") + * .lfoParam("frequency") + * .lfoDepth(1000) + * .lfoShape(3).lfoRate(4) + * .lfoSynced(1) + * .lfoCurve(0.95) + */ export const { lfoCurve } = registerControl('lfoCurve'); + +/** + * Determines whether the LFO is tempo-synced. + * + * @name lfoSynced + * @param {number | Pattern} lfoSynced Boolean flag (0 or 1). + * note("F2").sound("supersaw") + * .lpf(100) + * .lfoTarget("lpf") + * .lfoParam("frequency") + * .lfoDepth(1000) + * .lfoShape(3).lfoRate(2) + * .lfoSynced(1) + */ export const { lfoSynced } = registerControl('lfoSynced'); +/** + * Sets the target destination for the envelope modulation. Names are typically related + * to existing controls ("source", "lpf", "vibrato", etc.). You can try a value + * and if it fails, the console will print the available options. + * + * @name envTarget + * @param {number | Pattern} envTarget Target identifier for modulation. + * n(irand(12).seg(8)).scale("F#3:minor").room(1) + * .lpf(100) + * .envDepth("4800:400") + * .envTarget("source:lpf") + * .envParam("detune:frequency") + */ export const { envTarget } = registerControl('envTarget'); + +/** + * Chooses which parameter the LFO will modulate on the target. Parameter values + * are things like "frequency", "Q", "detune", etc. You can try a value + * and if it fails, the console will print the available options. + * + * @name envParam + * @param {number | Pattern} envParam Parameter index or identifier. + * n(irand(12).seg(8)).scale("F#3:minor").room(1) + * .lpf(100) + * .envDepth("4800:400") + * .envTarget("source:lpf") + * .envParam("detune:frequency") + */ export const { envParam } = registerControl('envParam'); + +/** + * Controls the attack time of the envelope. + * + * @name envAttack + * @param {number | Pattern} envAttack Duration of attack phase. + * n(irand(12).seg(8)).scale("F#3:minor").room(1) + * .lpf(500) + * .envDepth("4800:400") + * .envTarget("source:lpf") + * .envParam("detune:frequency") + * .envAttack(0.5) + */ export const { envAttack } = registerControl('envAttack'); + +/** + * Controls the decay time of the envelope. + * + * @name envDecay + * @param {number | Pattern} envDecay Duration of decay phase. + * n(irand(12).seg(8)).scale("F#3:minor").room(1) + * .lpf(100) + * .envDepth("4800:400") + * .envTarget("source:lpf") + * .envParam("detune:frequency") + * .envDecay("0.03:0.15").envCurve("exp:exp") + */ export const { envDecay } = registerControl('envDecay'); + +/** + * Sets the sustain level of the envelope. + * + * @name envSustain + * @param {number | Pattern} envSustain Sustain amplitude level. + * n(irand(12).seg(8)).scale("F#3:minor").room(1) + * .lpf(100) + * .envDepth("4800:400") + * .envTarget("source:lpf") + * .envParam("detune:frequency") + * .envDecay("0.03:0.15").envCurve("exp:exp") + * .envSustain(0.2) + */ export const { envSustain } = registerControl('envSustain'); + +/** + * Controls the release time of the envelope. + * + * @name envRelease + * @param {number | Pattern} envRelease Duration of release phase. + * @example + * n(irand(12).seg(8)).scale("F#3:minor").room(1) + * .lpf(100).release(3) + * .envDepth("4800:400") + * .envTarget("source:lpf") + * .envParam("detune:frequency") + * .envDecay("0.03:0.15").envCurve("exp:exp") + * .envSustain(0.5) + * .envRelease(3) + */ export const { envRelease } = registerControl('envRelease'); + +/** + * Selects the style of envelope: `exp` or `lin` (exponential or linear). + * + * @name envCurve + * @param {string | Pattern} envCurve Envelope curve style. + * @example + * n(irand(12).seg(8)).scale("F#3:minor").room(1) + * .lpf(100).release(2) + * .envTarget("source:lpf") + * .envParam("detune:frequency") + * .envDepth("500:4000") + * .envDecay("0.3:0.15") + * .envCurve("lin:exp") + */ export const { envCurve } = registerControl('envCurve'); + +/** + * Sets the modulation depth of the envelope. + * + * @name envDepth + * @param {number | Pattern} envDepth Modulation depth amount. + * @example + * n(irand(12).seg(8)).scale("F#3:minor").room(1) + * .lpf(100) + * .envTarget("source:lpf") + * .envParam("detune:frequency") + * .envDepth("4800:400") + */ export const { envDepth } = registerControl('envDepth'); // TODO: slide param for certain synths diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 97f3900d0..91a97c17e 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -548,7 +548,7 @@ function _getNodeParams(node) { * @param {Object} params - Dictionary of modulation parameters. * @returns {Object[]} - Array of parameter objects, one per parameter modulation */ -function _splitParams(params, countKeys) { +function _splitParams(params) { const num = ['num', 'target', 'parameter'] // names used to indicate individual parameter modulations .map((k) => [params[k] ?? 0].flat().length) .reduce((a, v) => Math.max(a, v), 1); From 862b88b6c405d95a39500b3915a70bb198179b17 Mon Sep 17 00:00:00 2001 From: Aria Date: Thu, 4 Sep 2025 20:27:05 -0500 Subject: [PATCH 07/73] Some typos and cleanup --- packages/superdough/superdough.mjs | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 91a97c17e..f38382e88 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -549,7 +549,7 @@ function _getNodeParams(node) { * @returns {Object[]} - Array of parameter objects, one per parameter modulation */ function _splitParams(params) { - const num = ['num', 'target', 'parameter'] // names used to indicate individual parameter modulations + const num = ['num', 'target', 'param'] // names used to indicate individual parameter modulations .map((k) => [params[k] ?? 0].flat().length) .reduce((a, v) => Math.max(a, v), 1); @@ -646,11 +646,6 @@ function _connectLFO(params) { lfoNode = getLfo(ac, filteredParams); lfos[num] = lfoNode; } - try { - lfoNode.disconnect(); - } catch { - // pass - } const targets = _getTargetParams(target, param); targets.forEach((target) => lfoNode.connect(target)); _setWorkletParamsAtTime(lfoNode.parameters, Object.entries(filteredParams), begin); @@ -975,29 +970,29 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) if (vowel !== undefined) { const vowelFilter = ac.createVowelFilter(vowel); - nodes['vowel'] = vowelFilter; + nodes['vowel'] = [vowelFilter]; chain.push(vowelFilter); } // effects if (coarse !== undefined) { const coarseNode = getWorklet(ac, 'coarse-processor', { coarse }); - nodes['coarse'] = coarseNode; + nodes['coarse'] = [coarseNode]; chain.push(coarseNode); } if (crush !== undefined) { const crushNode = getWorklet(ac, 'crush-processor', { crush }); - nodes['crush'] = crushNode; + nodes['crush'] = [crushNode]; chain.push(crushNode); } if (shape !== undefined) { const shapeNode = getWorklet(ac, 'shape-processor', { shape }); - nodes['shape'] = shapeNode; + nodes['shape'] = [shapeNode]; chain.push(shapeNode); } if (distort !== undefined) { const distortNode = getWorklet(ac, 'distort-processor', { distort }); - nodes['distort'] = distortNode; + nodes['distort'] = [distortNode]; chain.push(distortNode); } @@ -1039,7 +1034,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) compressorAttack, compressorRelease, ); - nodes['compressor'] = compressorNode; + nodes['compressor'] = [compressorNode]; chain.push(compressorNode); } @@ -1052,20 +1047,20 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) // phaser if (phaser !== undefined && phaserdepth > 0) { const phaserFX = getPhaser(t, endWithRelease, phaser, phaserdepth, phasercenter, phasersweep); - nodes['phaser'] = phaserFX; + nodes['phaser'] = [phaserFX]; chain.push(phaserFX); } // last gain const post = new GainNode(ac, { gain: postgain }); - nodes['post'] = post; + nodes['post'] = [post]; chain.push(post); // delay let delaySend; if (delay > 0 && delaytime > 0 && delayfeedback > 0) { const delayNode = getDelay(orbit, delaytime, delayfeedback, t, orbitChannels); - nodes['delay'] = delayNode; + nodes['delay'] = [delayNode]; delaySend = effectSend(post, delayNode, delay); audioNodes.push(delaySend); } @@ -1084,7 +1079,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) roomIR = await loadBuffer(url, ac, ir, 0); } const reverbNode = getReverb(orbit, roomsize, roomfade, roomlp, roomdim, roomIR, orbitChannels); - nodes['room'] = reverbNode; + nodes['room'] = [reverbNode]; reverbSend = effectSend(post, reverbNode, room); audioNodes.push(reverbSend); } From 2ccbb0596d8c0ab0b226e276fc0c58dee8a3e606 Mon Sep 17 00:00:00 2001 From: Aria Date: Thu, 4 Sep 2025 20:27:32 -0500 Subject: [PATCH 08/73] Codeformat --- packages/core/controls.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index a078c2b6f..d969d7922 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -1444,7 +1444,7 @@ export const { panorient } = registerControl('panorient'); * .lfoTarget("lpf") * .lfoParam("frequency") * .lfoNum(2) - * + * * reuse: note("F3").sound("square").lpf(50) * .lfoTarget("lpf") * .lfoParam("frequency") From 945b32533654e06591af4d4425586690e3759829 Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 13 Sep 2025 14:33:32 -0500 Subject: [PATCH 09/73] Codeformat, example tests --- test/__snapshots__/examples.test.mjs.snap | 111 ++++++++++++++++++++++ website/src/pages/learn/xen.mdx | 11 +-- 2 files changed, 114 insertions(+), 8 deletions(-) diff --git a/test/__snapshots__/examples.test.mjs.snap b/test/__snapshots__/examples.test.mjs.snap index ecbc33eac..b602749d0 100644 --- a/test/__snapshots__/examples.test.mjs.snap +++ b/test/__snapshots__/examples.test.mjs.snap @@ -3395,6 +3395,117 @@ exports[`runs examples > example "end" example index 0 1`] = ` ] `; +exports[`runs examples > example "envCurve" example index 0 1`] = ` +[ + "[ 0/1 → 1/8 | note:F#3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 1/8 → 1/4 | note:G#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 1/4 → 3/8 | note:C#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 3/8 → 1/2 | note:C#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 1/2 → 5/8 | note:B3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 5/8 → 3/4 | note:G#3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 3/4 → 7/8 | note:A3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 7/8 → 1/1 | note:C#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 1/1 → 9/8 | note:E4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 9/8 → 5/4 | note:G#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 5/4 → 11/8 | note:G#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 11/8 → 3/2 | note:A3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 3/2 → 13/8 | note:F#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 13/8 → 7/4 | note:D4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 7/4 → 15/8 | note:A3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 15/8 → 2/1 | note:F#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 2/1 → 17/8 | note:C#5 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 17/8 → 9/4 | note:B4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 9/4 → 19/8 | note:C#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 19/8 → 5/2 | note:B4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 5/2 → 21/8 | note:D4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 21/8 → 11/4 | note:G#3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 11/4 → 23/8 | note:F#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 23/8 → 3/1 | note:F#3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 3/1 → 25/8 | note:A3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 25/8 → 13/4 | note:C#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 13/4 → 27/8 | note:C#5 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 27/8 → 7/2 | note:C#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 7/2 → 29/8 | note:C#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 29/8 → 15/4 | note:C#5 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 15/4 → 31/8 | note:A4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", + "[ 31/8 → 4/1 | note:G#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", +] +`; + +exports[`runs examples > example "envDepth" example index 0 1`] = ` +[ + "[ 0/1 → 1/8 | note:F#3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 1/8 → 1/4 | note:G#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 1/4 → 3/8 | note:C#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 3/8 → 1/2 | note:C#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 1/2 → 5/8 | note:B3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 5/8 → 3/4 | note:G#3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 3/4 → 7/8 | note:A3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 7/8 → 1/1 | note:C#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 1/1 → 9/8 | note:E4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 9/8 → 5/4 | note:G#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 5/4 → 11/8 | note:G#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 11/8 → 3/2 | note:A3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 3/2 → 13/8 | note:F#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 13/8 → 7/4 | note:D4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 7/4 → 15/8 | note:A3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 15/8 → 2/1 | note:F#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 2/1 → 17/8 | note:C#5 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 17/8 → 9/4 | note:B4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 9/4 → 19/8 | note:C#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 19/8 → 5/2 | note:B4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 5/2 → 21/8 | note:D4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 21/8 → 11/4 | note:G#3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 11/4 → 23/8 | note:F#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 23/8 → 3/1 | note:F#3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 3/1 → 25/8 | note:A3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 25/8 → 13/4 | note:C#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 13/4 → 27/8 | note:C#5 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 27/8 → 7/2 | note:C#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 7/2 → 29/8 | note:C#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 29/8 → 15/4 | note:C#5 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 15/4 → 31/8 | note:A4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", + "[ 31/8 → 4/1 | note:G#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", +] +`; + +exports[`runs examples > example "envRelease" example index 0 1`] = ` +[ + "[ 0/1 → 1/8 | note:F#3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 1/8 → 1/4 | note:G#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 1/4 → 3/8 | note:C#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 3/8 → 1/2 | note:C#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 1/2 → 5/8 | note:B3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 5/8 → 3/4 | note:G#3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 3/4 → 7/8 | note:A3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 7/8 → 1/1 | note:C#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 1/1 → 9/8 | note:E4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 9/8 → 5/4 | note:G#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 5/4 → 11/8 | note:G#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 11/8 → 3/2 | note:A3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 3/2 → 13/8 | note:F#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 13/8 → 7/4 | note:D4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 7/4 → 15/8 | note:A3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 15/8 → 2/1 | note:F#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 2/1 → 17/8 | note:C#5 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 17/8 → 9/4 | note:B4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 9/4 → 19/8 | note:C#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 19/8 → 5/2 | note:B4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 5/2 → 21/8 | note:D4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 21/8 → 11/4 | note:G#3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 11/4 → 23/8 | note:F#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 23/8 → 3/1 | note:F#3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 3/1 → 25/8 | note:A3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 25/8 → 13/4 | note:C#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 13/4 → 27/8 | note:C#5 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 27/8 → 7/2 | note:C#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 7/2 → 29/8 | note:C#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 29/8 → 15/4 | note:C#5 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 15/4 → 31/8 | note:A4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", + "[ 31/8 → 4/1 | note:G#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", +] +`; + exports[`runs examples > example "euclid" example index 0 1`] = ` [ "[ 0/1 → 1/8 | note:c3 ]", diff --git a/website/src/pages/learn/xen.mdx b/website/src/pages/learn/xen.mdx index 32e2c0b43..b8b27ac7f 100644 --- a/website/src/pages/learn/xen.mdx +++ b/website/src/pages/learn/xen.mdx @@ -16,10 +16,7 @@ These functions allow the use of scales other than your typical chromatic 12 bas Here's an example of how to configure a basic hexany scale: - + Try other scales like `hexany1`, `iraq`, `gumbeng`, `gunkali`, or `tranh3` @@ -67,6 +64,7 @@ Another helpful trick when exploring new tunings is to strum them. Many have a much more enchanting sound that was chosen over many generations of musicians for being strummed. Take the `sanza` tuning: + + This quality is often due to how the tunings were formed with instruments that were played differently than a piano. As such, some tunings are much better strummed, with the subtle clash of the detuned notes actually making the sound much more magical: From 23aa8ef5090df4b86089333d89df612dc58c4d0f Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 13 Sep 2025 14:49:36 -0500 Subject: [PATCH 10/73] Add ability for LFOs to target.. other lfos :devil emoji: --- packages/superdough/superdough.mjs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 364681c2b..7ef3ee948 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -636,7 +636,7 @@ function _setWorkletParamsAtTime(audioParams, params, time) { } let lfos = {}; -function _connectLFO(params) { +function _connectLFO(params, nodeTracker) { const { frequency = 1, synced = 0, @@ -653,10 +653,12 @@ function _connectLFO(params) { const ac = getAudioContext(); lfoNode = getLfo(ac, filteredParams); lfos[num] = lfoNode; + nodeTracker[`lfo${num}`] = [lfoNode]; } const targets = _getTargetParams(target, param); targets.forEach((target) => lfoNode.connect(target)); _setWorkletParamsAtTime(lfoNode.parameters, Object.entries(filteredParams), begin); + return lfoNode; } function _connectEnvelope(params) { @@ -671,15 +673,16 @@ function _connectEnvelope(params) { }); } -function connectModulators(params, modulatorType) { +function connectModulators(params, modulatorType, nodeTracker) { // We break down params specifying multiple modulators into a set of parameters for // a single one const individualParams = _splitParams(params); if (modulatorType === 'lfo') { - individualParams.forEach(_connectLFO); + individualParams.map((p) => _connectLFO(p, nodeTracker)); } else if (modulatorType === 'envelope') { individualParams.forEach(_connectEnvelope); } + return []; } let activeSoundSources = new Map(); @@ -1118,7 +1121,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) if (lfoTarget !== undefined && lfoParam !== undefined) { connectModulators( { - num: lfoNum, + num: lfoNum ?? 1, target: lfoTarget, param: lfoParam, frequency: lfoRate, @@ -1133,6 +1136,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) cps: cps, }, 'lfo', + nodes, ); } if (envTarget !== undefined && envParam !== undefined) { From 48407c309cca95b87d541e3a420659ff2f04abdd Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Mon, 17 Nov 2025 23:10:10 +0100 Subject: [PATCH 11/73] add basic dough repl --- packages/codemirror/codemirror.mjs | 6 +- website/src/components/Dough/Dough.astro | 17 +++ website/src/components/Dough/dough-mirror.mjs | 139 ++++++++++++++++++ website/src/components/Dough/dough-repl.mjs | 105 +++++++++++++ website/src/pages/dough/index.astro | 15 ++ 5 files changed, 279 insertions(+), 3 deletions(-) create mode 100644 website/src/components/Dough/Dough.astro create mode 100644 website/src/components/Dough/dough-mirror.mjs create mode 100644 website/src/components/Dough/dough-repl.mjs create mode 100644 website/src/pages/dough/index.astro diff --git a/packages/codemirror/codemirror.mjs b/packages/codemirror/codemirror.mjs index 69fce4b50..ad27fd30f 100644 --- a/packages/codemirror/codemirror.mjs +++ b/packages/codemirror/codemirror.mjs @@ -27,7 +27,7 @@ import { updateWidgets, widgetPlugin } from './widget.mjs'; export { toggleBlockComment, toggleBlockCommentByLine, toggleComment, toggleLineComment } from '@codemirror/commands'; -const extensions = { +export const extensions = { isLineWrappingEnabled: (on) => (on ? EditorView.lineWrapping : []), isBracketMatchingEnabled: (on) => (on ? bracketMatching({ brackets: '()[]{}<>' }) : []), isBracketClosingEnabled: (on) => (on ? closeBrackets() : []), @@ -48,7 +48,7 @@ const extensions = { ] : [], }; -const compartments = Object.fromEntries(Object.keys(extensions).map((key) => [key, new Compartment()])); +export const compartments = Object.fromEntries(Object.keys(extensions).map((key) => [key, new Compartment()])); export const defaultSettings = { keybindings: 'codemirror', @@ -411,7 +411,7 @@ export class StrudelMirror { } } -function parseBooleans(value) { +export function parseBooleans(value) { return { true: true, false: false }[value] ?? value; } diff --git a/website/src/components/Dough/Dough.astro b/website/src/components/Dough/Dough.astro new file mode 100644 index 000000000..91b50e07b --- /dev/null +++ b/website/src/components/Dough/Dough.astro @@ -0,0 +1,17 @@ +--- +import '../../repl/Repl.css'; +--- + +
+ + + diff --git a/website/src/components/Dough/dough-mirror.mjs b/website/src/components/Dough/dough-mirror.mjs new file mode 100644 index 000000000..f20fd2b4c --- /dev/null +++ b/website/src/components/Dough/dough-mirror.mjs @@ -0,0 +1,139 @@ +import { + initEditor, + codemirrorSettings, + flash, + compartments, + extensions, + parseBooleans, + activateTheme, + updateMiniLocations, + highlightMiniLocations, +} from '@strudel/codemirror'; +import { evalScope } from '@strudel/core'; +import { Framer } from '@strudel/draw'; +import { persistentAtom } from '@nanostores/persistent'; +import { DoughRepl } from './dough-repl.mjs'; + +const initialCode = '$: note("c a f e")'; +export const code = persistentAtom('vanilla-repl-code', initialCode, { + encode: JSON.stringify, + decode: JSON.parse, +}); + +export class DoughMirror { + constructor(options) { + const { root, initialCode = code.get(), bgFill = true } = options; + this.root = root; + this.code = initialCode; + this.repl = new DoughRepl(); + this.prebaked = this.prebake(); + + // init codemirror + this.editor = initEditor({ + root, + initialCode: this.code, + onChange: (v) => { + if (v.docChanged) { + this.code = v.state.doc.toString(); + code.set(this.code); + } + }, + onEvaluate: this.evaluate.bind(this), + onStop: () => this.stop(), + mondo: false, + }); + const settings = codemirrorSettings.get(); + this.setFontSize(settings.fontSize); + this.setFontFamily(settings.fontFamily); + + // init event highlighting + this.framer = new Framer( + () => { + const frameHaps = this.repl.processHaps(); + highlightMiniLocations(this.editor, time, frameHaps); + }, + (err) => console.log('Framer error', err), + ); + } + prebake() { + const modulesLoading = evalScope(import('@strudel/core'), import('@strudel/tonal'), import('@strudel/mini')); + return Promise.all([modulesLoading, this.repl.prebake()]); + } + async evaluate() { + this.framer.start(); + this.flash(); + await this.prebaked; + const { miniLocations } = await this.repl.evaluate(this.code); + updateMiniLocations(this.editor, miniLocations); + } + stop() { + this.repl.stop(); + this.framer.stop(); + highlightMiniLocations(this.editor, 0, []); + } + // added synonym (compared to StrudelMirror) + settings(settings = {}) { + this.updateSettings(settings); + } + + // the rest is copy pasted from StrudelMirror: + + updateSettings(settings = {}) { + settings.fontSize && this.setFontSize(settings.fontSize); + settings.fontFamily && this.setFontFamily(settings.fontFamily); + for (let key in extensions) { + if (key in settings) { + this.reconfigureExtension(key, settings[key]); + } + } + const updated = { ...codemirrorSettings.get(), ...settings }; + // console.log(updated); + codemirrorSettings.set(updated); + } + reconfigureExtension(key, value) { + if (!extensions[key]) { + console.warn(`extension ${key} is not known`); + return; + } + value = parseBooleans(value); + const newValue = extensions[key](value, this); + this.editor.dispatch({ + effects: compartments[key].reconfigure(newValue), + }); + if (key === 'theme') { + activateTheme(value); + } + } + flash(ms) { + flash(this.editor, ms); + } + setFontSize(size) { + this.root.style.fontSize = size + 'px'; + } + setFontFamily(family) { + this.root.style.fontFamily = family; + const scroller = this.root.querySelector('.cm-scroller'); + if (scroller) { + scroller.style.fontFamily = family; + } + } + setCode(code, offset = 0) { + const changes = { + from: 0, + to: this.editor.state.doc.length + offset, + insert: code, + }; + this.editor.dispatch({ changes }); + } + getCursorLocation() { + return this.editor.state.selection.main.head; + } + setCursorLocation(col) { + return this.editor.dispatch({ selection: { anchor: col } }); + } + appendCode(code) { + const cursor = this.getCursorLocation(); + this.setCode(this.code + code); + this.setCursorLocation(cursor); + } +} diff --git a/website/src/components/Dough/dough-repl.mjs b/website/src/components/Dough/dough-repl.mjs new file mode 100644 index 000000000..643647085 --- /dev/null +++ b/website/src/components/Dough/dough-repl.mjs @@ -0,0 +1,105 @@ +// import { Dough, doughsamples } from 'dough-synth'; +import { Dough, doughsamples } from 'https://unpkg.com/dough-synth@0.1.9/dough.js'; +import { Pattern, noteToMidi, evaluate } from '@strudel/core'; +// import doughUrl from 'dough-synth?url'; +import { transpiler } from '@strudel/transpiler'; +//const doughBaseUrl = doughUrl.split('/').slice(0, -1).join('/') + '/'; +const doughBaseUrl = 'https://unpkg.com/dough-synth@0.1.9/'; + +export class DoughRepl { + pattern; + latency = 0.1; + cps = 0.5; + origin; + t0; + lasttime; + strudel; + q = []; + constructor() { + this.ready = this.init(); + } + async init() { + // init dough immediately, so that it can attach the document click event to initAudio immediately + this.dough = new Dough({ + base: doughBaseUrl, + //base: "../", // local dev + onTick: ({ t0, t1 }) => { + if (!this.pattern) { + return; + } + this.origin ??= t0; + this.t0 = t0; + this.lasttime = performance.now(); + const a = (t0 - this.origin) * this.cps; + const b = (t1 - this.origin) * this.cps; + + const haps = this.pattern.queryArc(a, b).filter((hap) => hap.hasOnset()); + if (!haps.length) { + return; + } + haps.forEach((hap) => { + const time = hap.whole.begin.valueOf() / this.cps + this.origin + this.latency; + const duration = hap.duration.valueOf() / this.cps; + const event = { + dough: 'play', + ...hap.value, + time, + duration, + }; + if (event.note && typeof event.note === 'string') { + event.note = noteToMidi(event.note); + } + //console.log("event", JSON.stringify(Object.entries(event))); + this.dough.evaluate(event); + this.q.push({ event, hap }); + }); + }, + }); + // miniAllStrings(); + const setcps = (cps) => (this.cps = cps); + const setcpm = (cpm) => setcps(cpm / 60); + const replScope = { setcps, setcpm }; + Object.assign(globalThis, replScope); + } + async evaluate(code) { + await this.ready; + let patterns = []; + Pattern.prototype.p = function (id) { + if (!id.startsWith('_')) { + patterns.push(this); + } + }; + + let { meta } = await evaluate(code, transpiler, { addReturn: false, wrapAsync: true, emitWidgets: false }); + const { miniLocations } = meta; + + this.pattern = stack(...patterns); + return { miniLocations, pattern: this.pattern }; + } + stop() { + this.pattern = undefined; + this.origin = undefined; + } + prebake() { + return Promise.all([doughsamples('github:eddyflux/crate')]); + } + // tbd: move this to dough-synth + get time() { + return this.t0 + (performance.now() - this.lasttime) / 1000 + this.latency; + } + processHaps() { + const currentHaps = []; + const time = this.time; + this.q = this.q.filter(({ event, hap }) => { + const end = event.time + event.duration; + const isActive = time >= event.time && time <= end; + if (isActive) { + currentHaps.push(hap); + } + return end > time; // delete old events + // we do NOT return !isActive, because a frame might miss an event, which would cause a leak + }); + // console.log(this.q.length); // to check for leaks + return currentHaps; + } +} diff --git a/website/src/pages/dough/index.astro b/website/src/pages/dough/index.astro new file mode 100644 index 000000000..9909fc6da --- /dev/null +++ b/website/src/pages/dough/index.astro @@ -0,0 +1,15 @@ +--- +import HeadCommon from '../../components/HeadCommon.astro'; +import Dough from '../../components/Dough/Dough.astro'; +--- + + + + + Strudel Dough REPL + + + + + + From 3b1c75d3de236d942f0191d54c237c9ed950547e Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Mon, 17 Nov 2025 23:18:31 +0100 Subject: [PATCH 12/73] fix: linting errors --- website/src/components/Dough/dough-mirror.mjs | 2 +- website/src/components/Dough/dough-repl.mjs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/website/src/components/Dough/dough-mirror.mjs b/website/src/components/Dough/dough-mirror.mjs index f20fd2b4c..5cdfeb3f6 100644 --- a/website/src/components/Dough/dough-mirror.mjs +++ b/website/src/components/Dough/dough-mirror.mjs @@ -48,7 +48,7 @@ export class DoughMirror { // init event highlighting this.framer = new Framer( - () => { + (time) => { const frameHaps = this.repl.processHaps(); highlightMiniLocations(this.editor, time, frameHaps); }, diff --git a/website/src/components/Dough/dough-repl.mjs b/website/src/components/Dough/dough-repl.mjs index 643647085..ef28617e8 100644 --- a/website/src/components/Dough/dough-repl.mjs +++ b/website/src/components/Dough/dough-repl.mjs @@ -1,6 +1,6 @@ // import { Dough, doughsamples } from 'dough-synth'; import { Dough, doughsamples } from 'https://unpkg.com/dough-synth@0.1.9/dough.js'; -import { Pattern, noteToMidi, evaluate } from '@strudel/core'; +import { Pattern, noteToMidi, evaluate, stack } from '@strudel/core'; // import doughUrl from 'dough-synth?url'; import { transpiler } from '@strudel/transpiler'; //const doughBaseUrl = doughUrl.split('/').slice(0, -1).join('/') + '/'; From 29b6729246fa45eab19e8ee0964cb4a50f002eae Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 19 Nov 2025 15:03:11 -0600 Subject: [PATCH 13/73] First pass at improving controls --- packages/core/controls.mjs | 108 +++++++++++++++++++------------------ packages/core/pattern.mjs | 61 +++++++++++++++++++++ 2 files changed, 116 insertions(+), 53 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index 0555bd107..307c15f48 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -1740,29 +1740,6 @@ export const { panorient } = registerControl('panorient'); // ['pitch2'], // ['pitch3'], // ['portamento'], -/** - * Selects which LFO number to use for modulation. Multiple LFOs - * can be applied using the ':' mininotation. There are an arbitrary number - * of LFOs available -- the number is only used to share LFOs across targets - * if desired (and to conserve processing power) - * - * @name lfoNum - * @param {number | Pattern} lfoNum Index of the LFO. - * setup: note("F2").sound("supersaw") - * .lpf(100) - * .lfoDepth(1000) - * .lfoRate(0.25) - * .lfoSynced(1) - * .lfoTarget("lpf") - * .lfoParam("frequency") - * .lfoNum(2) - * - * reuse: note("F3").sound("square").lpf(50) - * .lfoTarget("lpf") - * .lfoParam("frequency") - * .lfoNum(2) // uses the same LFO - */ -export const { lfoNum } = registerControl('lfoNum'); /** * Sets the target destination for the LFO modulation. Names are typically related @@ -1770,7 +1747,8 @@ export const { lfoNum } = registerControl('lfoNum'); * and if it fails, the console will print the available options. * * @name lfoTarget - * @param {string | Pattern} lfoTarget Target identifier for modulation. + * @synonyms lfot, lfotarget + * @param {string | Pattern} target Target identifier for modulation. * note("F2").sound("supersaw") * .lpf(100) * .lfoDepth(3000) @@ -1779,7 +1757,7 @@ export const { lfoNum } = registerControl('lfoNum'); * .lfoTarget("lpf") * .lfoParam("frequency") */ -export const { lfoTarget } = registerControl('lfoTarget'); +export const { lfoTarget, lfot, lfotarget } = registerControl('lfoTarget', 'lfot', 'lfotarget'); /** * Chooses which parameter the LFO will modulate on the target. Parameter values @@ -1787,7 +1765,8 @@ export const { lfoTarget } = registerControl('lfoTarget'); * and if it fails, the console will print the available options. * * @name lfoParam - * @param {string | Pattern} lfoParam Parameter name + * @synonyms lfop, lfoparam + * @param {string | Pattern} param Parameter name * note("F2").sound("supersaw") * .lpf(100) * .lfoDepth(3000) @@ -1796,13 +1775,14 @@ export const { lfoTarget } = registerControl('lfoTarget'); * .lfoTarget("lpf") * .lfoParam("frequency") */ -export const { lfoParam } = registerControl('lfoParam'); +export const { lfoParam, lfop, lfoparam } = registerControl('lfoParam', 'lfop', 'lfoparam'); /** * Controls the speed of the LFO. * * @name lfoRate - * @param {number | Pattern} lfoRate Frequency or tempo-relative value. + * @synonyms lfor, lforate + * @param {number | Pattern} rate Frequency or tempo-relative value. * note("F2").sound("supersaw") * .lpf(100) * .lfoTarget("lpf") @@ -1810,13 +1790,14 @@ export const { lfoParam } = registerControl('lfoParam'); * .lfoDepth(3000) * .lfoRate(0.25) */ -export const { lfoRate } = registerControl('lfoRate'); +export const { lfoRate, lfor, lforate } = registerControl('lfoRate', 'lfor', 'lforate'); /** * Sets the modulation depth of the LFO. * * @name lfoDepth - * @param {number | Pattern} lfoDepth Modulation depth amount. + * @synonyms lfod, lfodepth + * @param {number | Pattern} depth Modulation depth amount. * note("F2").sound("supersaw") * .lpf(100) * .lfoTarget("lpf") @@ -1824,7 +1805,7 @@ export const { lfoRate } = registerControl('lfoRate'); * .lfoSynced(1) * .lfoDepth(5000) */ -export const { lfoDepth } = registerControl('lfoDepth'); +export const { lfoDepth, lfod, lfodepth } = registerControl('lfoDepth', 'lfod', 'lfodepth'); /** * Applies a DC offset to the LFO signal. Normally the LFO varies from @@ -1832,7 +1813,8 @@ export const { lfoDepth } = registerControl('lfoDepth'); * a bipolar LFO. * * @name lfoDCOffset - * @param {number | Pattern} lfoDCOffset Offset amount. + * @synonyms lfodc, lfodcoffset + * @param {number | Pattern} offset Offset amount. * note("F2").sound("supersaw") * .lpf(2000) * .lfoTarget("lpf") @@ -1842,7 +1824,7 @@ export const { lfoDepth } = registerControl('lfoDepth'); * .lfoSynced(1) * .lfoDCOffset(-0.5) */ -export const { lfoDCOffset } = registerControl('lfoDCOffset'); +export const { lfoDCOffset, lfodc, lfodcoffset } = registerControl('lfoDCOffset', 'lfodc', 'lfodcoffset'); /** * Selects the waveform shape of the LFO. Current options are @@ -1850,7 +1832,8 @@ export const { lfoDCOffset } = registerControl('lfoDCOffset'); * respectively). * * @name lfoShape - * @param {number | Pattern} lfoShape Waveform type identifier. + * @synonyms lfosh, lfoshape + * @param {number | Pattern} shape Waveform type identifier. * note("F2").sound("supersaw") * .lpf(100) * .lfoTarget("lpf") @@ -1860,13 +1843,14 @@ export const { lfoDCOffset } = registerControl('lfoDCOffset'); * .lfoSynced(1) * .lfoShape(3) */ -export const { lfoShape } = registerControl('lfoShape'); +export const { lfoShape, lfosh, lfoshape } = registerControl('lfoShape', 'lfosh', 'lfoshape'); /** * Skews the LFO waveform. * * @name lfoSkew - * @param {number | Pattern} lfoSkew Skew amount (between 0 and 1). + * @synonyms lfosk, lfoskew + * @param {number | Pattern} skew Skew amount (between 0 and 1). * note("F2").sound("supersaw") * .lpf(100) * .lfoTarget("lpf") @@ -1876,13 +1860,14 @@ export const { lfoShape } = registerControl('lfoShape'); * .lfoSynced(1) * .lfoSkew(0.75) */ -export const { lfoSkew } = registerControl('lfoSkew'); +export const { lfoSkew, lfosk, lfoskew } = registerControl('lfoSkew', 'lfosk', 'lfoskew'); /** * Adjusts the (exponential) curvature of the LFO waveform. * * @name lfoCurve - * @param {number | Pattern} lfoCurve Curve shaping amount. + * @synonyms lfoc, lfocurve + * @param {number | Pattern} curve Curve shaping amount. * note("F2").sound("supersaw") * .lpf(100) * .lfoTarget("lpf") @@ -1892,22 +1877,22 @@ export const { lfoSkew } = registerControl('lfoSkew'); * .lfoSynced(1) * .lfoCurve(0.95) */ -export const { lfoCurve } = registerControl('lfoCurve'); +export const { lfoCurve, lfoc, lfocurve } = registerControl('lfoCurve', 'lfoc', 'lfocurve'); /** - * Determines whether the LFO is tempo-synced. + * Sets the tempo-synced rate of the LFO * - * @name lfoSynced - * @param {number | Pattern} lfoSynced Boolean flag (0 or 1). + * @name lfoSync + * @synonyms lfos, lfosync + * @param {number | Pattern} rate Rate to be multiplied by cycles per second * note("F2").sound("supersaw") * .lpf(100) * .lfoTarget("lpf") * .lfoParam("frequency") * .lfoDepth(1000) - * .lfoShape(3).lfoRate(2) - * .lfoSynced(1) + * .lfoShape(3).lfoSync(2) */ -export const { lfoSynced } = registerControl('lfoSynced'); +export const { lfoSync, lfos, lfosync } = registerControl('lfoSync', 'lfos', 'lfosync'); /** * Sets the target destination for the envelope modulation. Names are typically related @@ -1915,6 +1900,7 @@ export const { lfoSynced } = registerControl('lfoSynced'); * and if it fails, the console will print the available options. * * @name envTarget + * @synonyms envt, envtarget * @param {number | Pattern} envTarget Target identifier for modulation. * n(irand(12).seg(8)).scale("F#3:minor").room(1) * .lpf(100) @@ -1922,7 +1908,7 @@ export const { lfoSynced } = registerControl('lfoSynced'); * .envTarget("source:lpf") * .envParam("detune:frequency") */ -export const { envTarget } = registerControl('envTarget'); +export const { envTarget, envt, envtarget } = registerControl('envTarget', 'envt', 'envtarget'); /** * Chooses which parameter the LFO will modulate on the target. Parameter values @@ -1930,6 +1916,7 @@ export const { envTarget } = registerControl('envTarget'); * and if it fails, the console will print the available options. * * @name envParam + * @synonyms envp, envparam * @param {number | Pattern} envParam Parameter index or identifier. * n(irand(12).seg(8)).scale("F#3:minor").room(1) * .lpf(100) @@ -1937,12 +1924,13 @@ export const { envTarget } = registerControl('envTarget'); * .envTarget("source:lpf") * .envParam("detune:frequency") */ -export const { envParam } = registerControl('envParam'); +export const { envParam, envp, envparam } = registerControl('envParam', 'envp', 'envparam'); /** * Controls the attack time of the envelope. * * @name envAttack + * @synonyms envatt, envattack * @param {number | Pattern} envAttack Duration of attack phase. * n(irand(12).seg(8)).scale("F#3:minor").room(1) * .lpf(500) @@ -1951,12 +1939,13 @@ export const { envParam } = registerControl('envParam'); * .envParam("detune:frequency") * .envAttack(0.5) */ -export const { envAttack } = registerControl('envAttack'); +export const { envAttack, envatt, envattack } = registerControl('envAttack', 'envatt', 'envattack'); /** * Controls the decay time of the envelope. * * @name envDecay + * @synonyms envdec, envdecay * @param {number | Pattern} envDecay Duration of decay phase. * n(irand(12).seg(8)).scale("F#3:minor").room(1) * .lpf(100) @@ -1965,12 +1954,13 @@ export const { envAttack } = registerControl('envAttack'); * .envParam("detune:frequency") * .envDecay("0.03:0.15").envCurve("exp:exp") */ -export const { envDecay } = registerControl('envDecay'); +export const { envDecay, envdec, envdecay } = registerControl('envDecay', 'envdec', 'envdecay'); /** * Sets the sustain level of the envelope. * * @name envSustain + * @synonyms envs, envsustain * @param {number | Pattern} envSustain Sustain amplitude level. * n(irand(12).seg(8)).scale("F#3:minor").room(1) * .lpf(100) @@ -1980,12 +1970,13 @@ export const { envDecay } = registerControl('envDecay'); * .envDecay("0.03:0.15").envCurve("exp:exp") * .envSustain(0.2) */ -export const { envSustain } = registerControl('envSustain'); +export const { envSustain, envs, envsustain } = registerControl('envSustain', 'envs', 'envsustain'); /** * Controls the release time of the envelope. * * @name envRelease + * @synonyms envr, envrelease * @param {number | Pattern} envRelease Duration of release phase. * @example * n(irand(12).seg(8)).scale("F#3:minor").room(1) @@ -1997,12 +1988,13 @@ export const { envSustain } = registerControl('envSustain'); * .envSustain(0.5) * .envRelease(3) */ -export const { envRelease } = registerControl('envRelease'); +export const { envRelease, envr, envrelease } = registerControl('envRelease', 'envr', 'envrelease'); /** * Selects the style of envelope: `exp` or `lin` (exponential or linear). * * @name envCurve + * @synonyms envc, envcurve * @param {string | Pattern} envCurve Envelope curve style. * @example * n(irand(12).seg(8)).scale("F#3:minor").room(1) @@ -2013,12 +2005,13 @@ export const { envRelease } = registerControl('envRelease'); * .envDecay("0.3:0.15") * .envCurve("lin:exp") */ -export const { envCurve } = registerControl('envCurve'); +export const { envCurve, envc, envcurve } = registerControl('envCurve', 'envc', 'envcurve'); /** * Sets the modulation depth of the envelope. * * @name envDepth + * @synonyms envd, envdepth * @param {number | Pattern} envDepth Modulation depth amount. * @example * n(irand(12).seg(8)).scale("F#3:minor").room(1) @@ -2027,7 +2020,7 @@ export const { envCurve } = registerControl('envCurve'); * .envParam("detune:frequency") * .envDepth("4800:400") */ -export const { envDepth } = registerControl('envDepth'); +export const { envDepth, envd, envdepth } = registerControl('envDepth', 'envd', 'envdepth'); // TODO: slide param for certain synths export const { slide } = registerControl('slide'); @@ -2400,6 +2393,15 @@ export const { clip, legato } = registerControl('clip', 'legato'); */ export const { duration, dur } = registerControl('duration', 'dur'); +/** + * Sets the ID of the pattern for later reference + * + * @name id + * @param {number | Pattern} id ID of the pattern + * + */ +export const { id } = registerControl('id'); + // ZZFX export const { zrand } = registerControl('zrand'); export const { curve } = registerControl('curve'); diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index f5b0c676e..38f9aeb39 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -3624,3 +3624,64 @@ for (const name of distAlgoNames) { return this.distort(argsPat); }; } + +/** + * Selects which LFO number to use for modulation. Multiple LFOs + * can be applied using the ':' mininotation. There are an arbitrary number + * of LFOs available -- the number is only used to share LFOs across targets + * if desired (and to conserve processing power) + * + * @name lfoNum + * @param {number | Pattern} lfoNum Index of the LFO. + * setup: note("F2").sound("supersaw") + * .lpf(100) + * .lfoDepth(1000) + * .lfoRate(0.25) + * .lfoSynced(1) + * .lfoTarget("lpf") + * .lfoParam("frequency") + * .lfoNum(2) + * + * reuse: note("F3").sound("square").lpf(50) + * .lfoTarget("lpf") + * .lfoParam("frequency") + * .lfoNum(2) // uses the same LFO + */ + +/** + * Sets the target destination for the envelope modulation. Names are typically related + * to existing controls ("source", "lpf", "vibrato", etc.). You can try a value + * and if it fails, the console will print the available options. + * + * @name envTarget + * @param {number | Pattern} envTarget Target identifier for modulation. + * n(irand(12).seg(8)).scale("F#3:minor").room(1) + * .lpf(100) + * .envDepth("4800:400") + * .envTarget("source:lpf") + * .envParam("detune:frequency") + */ + + +/** + * Establishes a signal chain. Can be called in sequence like pat.chain(...).chain(...) and so forth + * and/or in a single .chain(..., ..., etc) call. The arguments to `chain` are _patterns_ which each act like + * a self-contained pattern and follow the normal [signal chain](https://strudel.cc/learn/effects/). + * + * If multiple sound generators are present within the chain, they will be mixed in at the location where + * they are declared. + * + * @name chain + * @memberof Pattern + * @param {Pattern | Pattern[]} patterns Patterns to combine into a single chain + * @returns Pattern + */ +Pattern.prototype.chain = function (...pats) { + pats = pats.map(reify); + return this.withValue((v) => (vEff) => { + const currChain = v.chain ?? []; + return { ...v, chain: currChain.concat(vEff) }; + }).appLeft(parray(pats)); +}; + +export const chain = (pats) => pure({}).chain(pats); \ No newline at end of file From b73f62405820993ad0be28291066023279580fad Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 19 Nov 2025 15:41:29 -0600 Subject: [PATCH 14/73] Trying out alias approach --- packages/core/controls.mjs | 54 ++++++++++++++--------- packages/core/pattern.mjs | 90 ++++++++++++++++++++------------------ 2 files changed, 82 insertions(+), 62 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index 6be21414b..732679d64 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -2097,7 +2097,8 @@ export const { envAttack, envatt, envattack } = registerControl('envAttack', 'en * .envDepth("4800:400") * .envTarget("source:lpf") * .envParam("detune:frequency") - * .envDecay("0.03:0.15").envCurve("exp:exp") + * .envDecay("0.03:0.15") + * .envDCurve(-0.4) */ export const { envDecay, envdec, envdecay } = registerControl('envDecay', 'envdec', 'envdecay'); @@ -2112,7 +2113,7 @@ export const { envDecay, envdec, envdecay } = registerControl('envDecay', 'envde * .envDepth("4800:400") * .envTarget("source:lpf") * .envParam("detune:frequency") - * .envDecay("0.03:0.15").envCurve("exp:exp") + * .envACurve(0.6).envDCurve(-0.2) * .envSustain(0.2) */ export const { envSustain, envs, envsustain } = registerControl('envSustain', 'envs', 'envsustain'); @@ -2129,29 +2130,12 @@ export const { envSustain, envs, envsustain } = registerControl('envSustain', 'e * .envDepth("4800:400") * .envTarget("source:lpf") * .envParam("detune:frequency") - * .envDecay("0.03:0.15").envCurve("exp:exp") + * .envDecay("0.03:0.15").envRCurve(0.5) * .envSustain(0.5) * .envRelease(3) */ export const { envRelease, envr, envrelease } = registerControl('envRelease', 'envr', 'envrelease'); -/** - * Selects the style of envelope: `exp` or `lin` (exponential or linear). - * - * @name envCurve - * @synonyms envc, envcurve - * @param {string | Pattern} envCurve Envelope curve style. - * @example - * n(irand(12).seg(8)).scale("F#3:minor").room(1) - * .lpf(100).release(2) - * .envTarget("source:lpf") - * .envParam("detune:frequency") - * .envDepth("500:4000") - * .envDecay("0.3:0.15") - * .envCurve("lin:exp") - */ -export const { envCurve, envc, envcurve } = registerControl('envCurve', 'envc', 'envcurve'); - /** * Sets the modulation depth of the envelope. * @@ -2167,6 +2151,36 @@ export const { envCurve, envc, envcurve } = registerControl('envCurve', 'envc', */ export const { envDepth, envd, envdepth } = registerControl('envDepth', 'envd', 'envdepth'); +/** + * Adjusts the curvature of the attack portion of the envelope. Positive values are snappy, + * negative values are slow + * + * @name envACurve + * @synonyms envac, envacurve + * @param {number | Pattern} envACurve Curvature amount (between -1 and 1). + */ +export const { envACurve, envac, envacurve } = registerControl('envACurve', 'envac', 'envacurve'); + +/** + * Adjusts the curvature of the decay portion of the envelope. Positive values are snappy, + * negative values are slow + * + * @name envDCurve + * @synonyms envdc, envdcurve + * @param {number | Pattern} envDCurve Curvature amount (between -1 and 1). + */ +export const { envDCurve, envdc, envdcurve } = registerControl('envDCurve', 'envdc', 'envdcurve'); + +/** + * Adjusts the curvature of the release portion of the envelope. Positive values are snappy, + * negative values are slow + * + * @name envRCurve + * @synonyms envrc, envrcurve + * @param {number | Pattern} envRCurve Curvature amount (between -1 and 1). + */ +export const { envRCurve, envrc, envrcurve } = registerControl('envRCurve', 'envrc', 'envrcurve'); + // TODO: slide param for certain synths export const { slide } = registerControl('slide'); // TODO: detune? https://tidalcycles.org/docs/patternlib/tutorials/synthesizers/#supersquare diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index ea9d0f34c..4ba24b206 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -3688,42 +3688,43 @@ export const phases = (list) => { return _ensureListPattern(list).as('phases'); }; -/** - * Selects which LFO number to use for modulation. Multiple LFOs - * can be applied using the ':' mininotation. There are an arbitrary number - * of LFOs available -- the number is only used to share LFOs across targets - * if desired (and to conserve processing power) - * - * @name lfoNum - * @param {number | Pattern} lfoNum Index of the LFO. - * setup: note("F2").sound("supersaw") - * .lpf(100) - * .lfoDepth(1000) - * .lfoRate(0.25) - * .lfoSynced(1) - * .lfoTarget("lpf") - * .lfoParam("frequency") - * .lfoNum(2) - * - * reuse: note("F3").sound("square").lpf(50) - * .lfoTarget("lpf") - * .lfoParam("frequency") - * .lfoNum(2) // uses the same LFO - */ +const configAliases = new Map(); +const addConfigAlias = (funcName, canonical, ...aliases) => { + const lowerFunc = String(funcName).toLowerCase(); + const aliasMap = configAliases.get(lowerFunc) ?? new Map(); + const allKeys = new Set([canonical, ...aliases]); + for (const alias of allKeys) { + aliasMap.set(String(alias).toLowerCase(), canonical); + } + configAliases.set(lowerFunc, aliasMap); +}; -/** - * Sets the target destination for the envelope modulation. Names are typically related - * to existing controls ("source", "lpf", "vibrato", etc.). You can try a value - * and if it fails, the console will print the available options. - * - * @name envTarget - * @param {number | Pattern} envTarget Target identifier for modulation. - * n(irand(12).seg(8)).scale("F#3:minor").room(1) - * .lpf(100) - * .envDepth("4800:400") - * .envTarget("source:lpf") - * .envParam("detune:frequency") - */ +const resolveConfigKey = (funcName, key) => { + const aliasMap = configAliases.get(String(funcName).toLowerCase()); + if (!aliasMap) return key; + const normalized = String(key).toLowerCase(); + return aliasMap.get(normalized) ?? key; +}; + +addConfigAlias('lfo', 'lfoTarget', 'lfot', 'lfotarget', 'target', 't'); +addConfigAlias('lfo', 'lfoParam', 'lfop', 'lfoparam', 'param', 'parameter', 'p'); +addConfigAlias('lfo', 'lfoRate', 'lfor', 'lforate', 'rate', 'r'); +addConfigAlias('lfo', 'lfoDepth', 'lfod', 'lfodepth', 'depth', 'd'); +addConfigAlias('lfo', 'lfoDCOffset', 'lfodc', 'lfodcoffset', 'dcoffset', 'offset', 'dc'); +addConfigAlias('lfo', 'lfoShape', 'lfosh', 'lfoshape', 'shape', 'sh'); +addConfigAlias('lfo', 'lfoSkew', 'lfosk', 'lfoskew', 'skew', 'sk'); +addConfigAlias('lfo', 'lfoCurve', 'lfoc', 'lfocurve', 'curve', 'c'); +addConfigAlias('lfo', 'lfoSync', 'lfos', 'lfosync', 'sync', 'synced', 's'); +addConfigAlias('env', 'envTarget', 'envt', 'envtarget'); +addConfigAlias('env', 'envParam', 'envp', 'envparam'); +addConfigAlias('env', 'envAttack', 'envatt', 'envattack'); +addConfigAlias('env', 'envDecay', 'envdec', 'envdecay'); +addConfigAlias('env', 'envSustain', 'envs', 'envsustain'); +addConfigAlias('env', 'envRelease', 'envr', 'envrelease'); +addConfigAlias('env', 'envDepth', 'envd', 'envdepth'); +addConfigAlias('env', 'envACurve', 'envac', 'envacurve'); +addConfigAlias('env', 'envDCurve', 'envdc', 'envdcurve'); +addConfigAlias('env', 'envRCurve', 'envrc', 'envrcurve'); /** * Establishes a signal chain. Can be called in sequence like pat.chain(...).chain(...) and so forth @@ -3738,12 +3739,17 @@ export const phases = (list) => { * @param {Pattern | Pattern[]} patterns Patterns to combine into a single chain * @returns Pattern */ -Pattern.prototype.chain = function (...pats) { - pats = pats.map(reify); - return this.withValue((v) => (vEff) => { - const currChain = v.chain ?? []; - return { ...v, chain: currChain.concat(vEff) }; - }).appLeft(parray(pats)); +Pattern.prototype.lfo = function (config) { + if (config == null || typeof config !== 'object') { + return this; + } + let output = this; + for (const [rawKey, value] of Object.entries(config)) { + const key = resolveConfigKey('lfo', rawKey); + const pat = reify(value); + output = output.set(pat.as(key)); + } + return output; }; -export const chain = (pats) => pure({}).chain(pats); +export const lfo = (config) => pure({}).lfo(config); From 7ccdefe1c69605563ff16768ea06fcb7eaffc8f8 Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 19 Nov 2025 16:33:08 -0600 Subject: [PATCH 15/73] Huge overhaul for config part 1 --- packages/core/controls.mjs | 295 ------------------------------------- packages/core/pattern.mjs | 140 +++++++++++++----- 2 files changed, 105 insertions(+), 330 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index 732679d64..bcab1d1b8 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -1886,301 +1886,6 @@ export const { panorient } = registerControl('panorient'); // ['pitch3'], // ['portamento'], -/** - * Sets the target destination for the LFO modulation. Names are typically related - * to existing controls ("source", "lpf", "vibrato", etc.). You can try a value - * and if it fails, the console will print the available options. - * - * @name lfoTarget - * @synonyms lfot, lfotarget - * @param {string | Pattern} target Target identifier for modulation. - * note("F2").sound("supersaw") - * .lpf(100) - * .lfoDepth(3000) - * .lfoRate(0.25) - * .lfoSynced(1) - * .lfoTarget("lpf") - * .lfoParam("frequency") - */ -export const { lfoTarget, lfot, lfotarget } = registerControl('lfoTarget', 'lfot', 'lfotarget'); - -/** - * Chooses which parameter the LFO will modulate on the target. Parameter values - * are things like "frequency", "Q", "detune", etc. You can try a value - * and if it fails, the console will print the available options. - * - * @name lfoParam - * @synonyms lfop, lfoparam - * @param {string | Pattern} param Parameter name - * note("F2").sound("supersaw") - * .lpf(100) - * .lfoDepth(3000) - * .lfoRate(0.25) - * .lfoSynced(1) - * .lfoTarget("lpf") - * .lfoParam("frequency") - */ -export const { lfoParam, lfop, lfoparam } = registerControl('lfoParam', 'lfop', 'lfoparam'); - -/** - * Controls the speed of the LFO. - * - * @name lfoRate - * @synonyms lfor, lforate - * @param {number | Pattern} rate Frequency or tempo-relative value. - * note("F2").sound("supersaw") - * .lpf(100) - * .lfoTarget("lpf") - * .lfoParam("frequency") - * .lfoDepth(3000) - * .lfoRate(0.25) - */ -export const { lfoRate, lfor, lforate } = registerControl('lfoRate', 'lfor', 'lforate'); - -/** - * Sets the modulation depth of the LFO. - * - * @name lfoDepth - * @synonyms lfod, lfodepth - * @param {number | Pattern} depth Modulation depth amount. - * note("F2").sound("supersaw") - * .lpf(100) - * .lfoTarget("lpf") - * .lfoParam("frequency") - * .lfoSynced(1) - * .lfoDepth(5000) - */ -export const { lfoDepth, lfod, lfodepth } = registerControl('lfoDepth', 'lfod', 'lfodepth'); - -/** - * Applies a DC offset to the LFO signal. Normally the LFO varies from - * 0 to 1 (i.e. unipolar). By using an offset of -0.5, one can achieve - * a bipolar LFO. - * - * @name lfoDCOffset - * @synonyms lfodc, lfodcoffset - * @param {number | Pattern} offset Offset amount. - * note("F2").sound("supersaw") - * .lpf(2000) - * .lfoTarget("lpf") - * .lfoParam("frequency") - * .lfoDepth(1000) - * .lfoRate(4) - * .lfoSynced(1) - * .lfoDCOffset(-0.5) - */ -export const { lfoDCOffset, lfodc, lfodcoffset } = registerControl('lfoDCOffset', 'lfodc', 'lfodcoffset'); - -/** - * Selects the waveform shape of the LFO. Current options are - * triangle, square, sine, saw, ramp (corresponding to 0 through 4, - * respectively). - * - * @name lfoShape - * @synonyms lfosh, lfoshape - * @param {number | Pattern} shape Waveform type identifier. - * note("F2").sound("supersaw") - * .lpf(100) - * .lfoTarget("lpf") - * .lfoParam("frequency") - * .lfoDepth(1000) - * .lfoRate(4) - * .lfoSynced(1) - * .lfoShape(3) - */ -export const { lfoShape, lfosh, lfoshape } = registerControl('lfoShape', 'lfosh', 'lfoshape'); - -/** - * Skews the LFO waveform. - * - * @name lfoSkew - * @synonyms lfosk, lfoskew - * @param {number | Pattern} skew Skew amount (between 0 and 1). - * note("F2").sound("supersaw") - * .lpf(100) - * .lfoTarget("lpf") - * .lfoParam("frequency") - * .lfoDepth(1000) - * .lfoRate(4) - * .lfoSynced(1) - * .lfoSkew(0.75) - */ -export const { lfoSkew, lfosk, lfoskew } = registerControl('lfoSkew', 'lfosk', 'lfoskew'); - -/** - * Adjusts the (exponential) curvature of the LFO waveform. - * - * @name lfoCurve - * @synonyms lfoc, lfocurve - * @param {number | Pattern} curve Curve shaping amount. - * note("F2").sound("supersaw") - * .lpf(100) - * .lfoTarget("lpf") - * .lfoParam("frequency") - * .lfoDepth(1000) - * .lfoShape(3).lfoRate(4) - * .lfoSynced(1) - * .lfoCurve(0.95) - */ -export const { lfoCurve, lfoc, lfocurve } = registerControl('lfoCurve', 'lfoc', 'lfocurve'); - -/** - * Sets the tempo-synced rate of the LFO - * - * @name lfoSync - * @synonyms lfos, lfosync - * @param {number | Pattern} rate Rate to be multiplied by cycles per second - * note("F2").sound("supersaw") - * .lpf(100) - * .lfoTarget("lpf") - * .lfoParam("frequency") - * .lfoDepth(1000) - * .lfoShape(3).lfoSync(2) - */ -export const { lfoSync, lfos, lfosync } = registerControl('lfoSync', 'lfos', 'lfosync'); - -/** - * Sets the target destination for the envelope modulation. Names are typically related - * to existing controls ("source", "lpf", "vibrato", etc.). You can try a value - * and if it fails, the console will print the available options. - * - * @name envTarget - * @synonyms envt, envtarget - * @param {number | Pattern} envTarget Target identifier for modulation. - * n(irand(12).seg(8)).scale("F#3:minor").room(1) - * .lpf(100) - * .envDepth("4800:400") - * .envTarget("source:lpf") - * .envParam("detune:frequency") - */ -export const { envTarget, envt, envtarget } = registerControl('envTarget', 'envt', 'envtarget'); - -/** - * Chooses which parameter the LFO will modulate on the target. Parameter values - * are things like "frequency", "Q", "detune", etc. You can try a value - * and if it fails, the console will print the available options. - * - * @name envParam - * @synonyms envp, envparam - * @param {number | Pattern} envParam Parameter index or identifier. - * n(irand(12).seg(8)).scale("F#3:minor").room(1) - * .lpf(100) - * .envDepth("4800:400") - * .envTarget("source:lpf") - * .envParam("detune:frequency") - */ -export const { envParam, envp, envparam } = registerControl('envParam', 'envp', 'envparam'); - -/** - * Controls the attack time of the envelope. - * - * @name envAttack - * @synonyms envatt, envattack - * @param {number | Pattern} envAttack Duration of attack phase. - * n(irand(12).seg(8)).scale("F#3:minor").room(1) - * .lpf(500) - * .envDepth("4800:400") - * .envTarget("source:lpf") - * .envParam("detune:frequency") - * .envAttack(0.5) - */ -export const { envAttack, envatt, envattack } = registerControl('envAttack', 'envatt', 'envattack'); - -/** - * Controls the decay time of the envelope. - * - * @name envDecay - * @synonyms envdec, envdecay - * @param {number | Pattern} envDecay Duration of decay phase. - * n(irand(12).seg(8)).scale("F#3:minor").room(1) - * .lpf(100) - * .envDepth("4800:400") - * .envTarget("source:lpf") - * .envParam("detune:frequency") - * .envDecay("0.03:0.15") - * .envDCurve(-0.4) - */ -export const { envDecay, envdec, envdecay } = registerControl('envDecay', 'envdec', 'envdecay'); - -/** - * Sets the sustain level of the envelope. - * - * @name envSustain - * @synonyms envs, envsustain - * @param {number | Pattern} envSustain Sustain amplitude level. - * n(irand(12).seg(8)).scale("F#3:minor").room(1) - * .lpf(100) - * .envDepth("4800:400") - * .envTarget("source:lpf") - * .envParam("detune:frequency") - * .envACurve(0.6).envDCurve(-0.2) - * .envSustain(0.2) - */ -export const { envSustain, envs, envsustain } = registerControl('envSustain', 'envs', 'envsustain'); - -/** - * Controls the release time of the envelope. - * - * @name envRelease - * @synonyms envr, envrelease - * @param {number | Pattern} envRelease Duration of release phase. - * @example - * n(irand(12).seg(8)).scale("F#3:minor").room(1) - * .lpf(100).release(3) - * .envDepth("4800:400") - * .envTarget("source:lpf") - * .envParam("detune:frequency") - * .envDecay("0.03:0.15").envRCurve(0.5) - * .envSustain(0.5) - * .envRelease(3) - */ -export const { envRelease, envr, envrelease } = registerControl('envRelease', 'envr', 'envrelease'); - -/** - * Sets the modulation depth of the envelope. - * - * @name envDepth - * @synonyms envd, envdepth - * @param {number | Pattern} envDepth Modulation depth amount. - * @example - * n(irand(12).seg(8)).scale("F#3:minor").room(1) - * .lpf(100) - * .envTarget("source:lpf") - * .envParam("detune:frequency") - * .envDepth("4800:400") - */ -export const { envDepth, envd, envdepth } = registerControl('envDepth', 'envd', 'envdepth'); - -/** - * Adjusts the curvature of the attack portion of the envelope. Positive values are snappy, - * negative values are slow - * - * @name envACurve - * @synonyms envac, envacurve - * @param {number | Pattern} envACurve Curvature amount (between -1 and 1). - */ -export const { envACurve, envac, envacurve } = registerControl('envACurve', 'envac', 'envacurve'); - -/** - * Adjusts the curvature of the decay portion of the envelope. Positive values are snappy, - * negative values are slow - * - * @name envDCurve - * @synonyms envdc, envdcurve - * @param {number | Pattern} envDCurve Curvature amount (between -1 and 1). - */ -export const { envDCurve, envdc, envdcurve } = registerControl('envDCurve', 'envdc', 'envdcurve'); - -/** - * Adjusts the curvature of the release portion of the envelope. Positive values are snappy, - * negative values are slow - * - * @name envRCurve - * @synonyms envrc, envrcurve - * @param {number | Pattern} envRCurve Curvature amount (between -1 and 1). - */ -export const { envRCurve, envrc, envrcurve } = registerControl('envRCurve', 'envrc', 'envrcurve'); - // TODO: slide param for certain synths export const { slide } = registerControl('slide'); // TODO: detune? https://tidalcycles.org/docs/patternlib/tutorials/synthesizers/#supersquare diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index 4ba24b206..1eefa41eb 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -3706,50 +3706,120 @@ const resolveConfigKey = (funcName, key) => { return aliasMap.get(normalized) ?? key; }; -addConfigAlias('lfo', 'lfoTarget', 'lfot', 'lfotarget', 'target', 't'); -addConfigAlias('lfo', 'lfoParam', 'lfop', 'lfoparam', 'param', 'parameter', 'p'); -addConfigAlias('lfo', 'lfoRate', 'lfor', 'lforate', 'rate', 'r'); -addConfigAlias('lfo', 'lfoDepth', 'lfod', 'lfodepth', 'depth', 'd'); -addConfigAlias('lfo', 'lfoDCOffset', 'lfodc', 'lfodcoffset', 'dcoffset', 'offset', 'dc'); -addConfigAlias('lfo', 'lfoShape', 'lfosh', 'lfoshape', 'shape', 'sh'); -addConfigAlias('lfo', 'lfoSkew', 'lfosk', 'lfoskew', 'skew', 'sk'); -addConfigAlias('lfo', 'lfoCurve', 'lfoc', 'lfocurve', 'curve', 'c'); -addConfigAlias('lfo', 'lfoSync', 'lfos', 'lfosync', 'sync', 'synced', 's'); -addConfigAlias('env', 'envTarget', 'envt', 'envtarget'); -addConfigAlias('env', 'envParam', 'envp', 'envparam'); -addConfigAlias('env', 'envAttack', 'envatt', 'envattack'); -addConfigAlias('env', 'envDecay', 'envdec', 'envdecay'); -addConfigAlias('env', 'envSustain', 'envs', 'envsustain'); -addConfigAlias('env', 'envRelease', 'envr', 'envrelease'); -addConfigAlias('env', 'envDepth', 'envd', 'envdepth'); -addConfigAlias('env', 'envACurve', 'envac', 'envacurve'); -addConfigAlias('env', 'envDCurve', 'envdc', 'envdcurve'); -addConfigAlias('env', 'envRCurve', 'envrc', 'envrcurve'); +addConfigAlias('lfo', 'target', 't'); +addConfigAlias('lfo', 'param', 'p'); +addConfigAlias('lfo', 'rate', 'r'); +addConfigAlias('lfo', 'depth', 'dep', 'dp', 'd'); +addConfigAlias('lfo', 'dc'); +addConfigAlias('lfo', 'shape', 'sh'); +addConfigAlias('lfo', 'skew', 'sk'); +addConfigAlias('lfo', 'curve', 'c'); +addConfigAlias('lfo', 'sync', 's'); +addConfigAlias('env', 'target', 't'); +addConfigAlias('env', 'attack', 'att', 'a'); +addConfigAlias('env', 'decay', 'dec', 'd'); +addConfigAlias('env', 'sustain', 'sus', 's'); +addConfigAlias('env', 'release', 'rel', 'r'); +addConfigAlias('env', 'depth', 'dep', 'dp'); +addConfigAlias('env', 'acurve', 'ac'); +addConfigAlias('env', 'dcurve', 'dc'); +addConfigAlias('env', 'rcurve', 'rc'); +addConfigAlias('send', 'id'); +addConfigAlias('send', 'target', 't'); +addConfigAlias('send', 'depth', 'dep', 'dp', 'd'); +addConfigAlias('send', 'dc'); +addConfigAlias('send', 'offset', 'off', 'o'); -/** - * Establishes a signal chain. Can be called in sequence like pat.chain(...).chain(...) and so forth - * and/or in a single .chain(..., ..., etc) call. The arguments to `chain` are _patterns_ which each act like - * a self-contained pattern and follow the normal [signal chain](https://strudel.cc/learn/effects/). - * - * If multiple sound generators are present within the chain, they will be mixed in at the location where - * they are declared. - * - * @name chain - * @memberof Pattern - * @param {Pattern | Pattern[]} patterns Patterns to combine into a single chain - * @returns Pattern - */ -Pattern.prototype.lfo = function (config) { +Pattern.prototype.mod = function (type, config, idx) { if (config == null || typeof config !== 'object') { return this; } + if (!['lfo', 'send', 'env'].includes(type)) { + logger(`[core] Modulation type ${type} not found. Please use one of 'lfo', 'env', 'send'`); + return this; + } let output = this; for (const [rawKey, value] of Object.entries(config)) { - const key = resolveConfigKey('lfo', rawKey); + const key = resolveConfigKey(type, rawKey); const pat = reify(value); - output = output.set(pat.as(key)); + output = output + .fmap((v) => (c) => { + v[type] ??= []; + const t = v[type]; + idx ??= t.length; + t[idx] ??= {}; + t[idx][key] = c; + return v; + }) + .appLeft(pat); } return output; }; +/** + * Configures an LFO. Can be called in sequence like pat.lfo(...).lfo(...) to set up multiple LFOs + * + * + * @name lfo + * @memberof Pattern + * @param {Object} config LFO configuration. + * @param {string | Pattern} [config.target] Node (and parameter if specified like `lpf.frequency`) to modulate. Aliases: target, t + * @param {number | Pattern} [config.rate] Modulation rate. Aliases: rate, r + * @param {number | Pattern} [config.depth] Modulation depth. Aliases: dep, dp, d + * @param {number | Pattern} [config.dc] DC offset / bias for the waveform + * @param {number | Pattern} [config.shape] Waveform shape index. Aliases: sh + * @param {number | Pattern} [config.skew] Waveform skew amount. Aliases: sk + * @param {number | Pattern} [config.curve] Exponential curve amount. Aliases: c + * @param {number | Pattern} [config.sync] Tempo-synced modulation rate. Aliases: s + * @param {number | null} idx Index of the LFO slot to overwrite. Omit to append a new LFO + * @returns Pattern + */ +Pattern.prototype.lfo = function (config, idx) { + return this.mod('lfo', config, idx); +}; export const lfo = (config) => pure({}).lfo(config); + +/** + * Configures an envelope. Can be called in sequence like pat.env(...).env(...) to set up multiple envelopes + * + * + * @name env + * @memberof Pattern + * @param {Object} config Envelope configuration. + * @param {string | Pattern} [config.target] Node (and parameter if specified like `lpf.frequency`) to modulate. Aliases: target, t + * @param {number | Pattern} [config.depth] Modulation depth. Aliases: dep, dp + * @param {number | Pattern} [config.attack] Time to reach depth. Aliases: att, a + * @param {number | Pattern} [config.decay] Time to reach sustain. Aliases: dec, d + * @param {number | Pattern} [config.sustain] Sustain depth. Aliases: sus, s + * @param {number | Pattern} [config.release] Time to return to nominal value. Aliases: rel, r + * @param {number | Pattern} [config.acurve] Snappiness of attack curve (-1 = relaxed, 1 = snappy). Aliases: ac + * @param {number | Pattern} [config.dcurve] Snappiness of decay curve (-1 = relaxed, 1 = snappy). Aliases: dc + * @param {number | Pattern} [config.rcurve] Snappiness of release curve (-1 = relaxed, 1 = snappy). Aliases: rc + * @param {number | null} idx Index of the envelope slot to overwrite. Omit to append a new envelope + * @returns Pattern + */ +Pattern.prototype.env = function (config, idx) { + return this.mod('env', config, idx); +}; +export const env = (config) => pure({}).env(config); + +/** + * Sends the output of this pattern to a parameter on another pattern. + * Can be called in sequence like pat.send(...).send(...) to send to multiple parameters + * + * + * @name send + * @memberof Pattern + * @param {Object} config Send configuration. + * @param {string | Pattern} [config.id] Pattern id to modulate + * @param {string | Pattern} [config.target] Node (and parameter if specified like `lpf.frequency`) to modulate. Aliases: target, t + * @param {number | Pattern} [config.depth] Modulation depth. Aliases:dep, dp, d + * @param {number | Pattern} [config.dc] DC offset prior to application + * @param {number | Pattern} [config.offset] Offset to apply to the parameter. Aliases: off, o + * @param {number | null} idx Index of the send slot to overwrite. Omit to append a new send + * @returns Pattern + */ +Pattern.prototype.send = function (config, idx) { + return this.mod('send', config, idx); +}; +export const send = (config) => pure({}).send(config); From 442f4879738b7f7cb3f3f1baef8a0a5fac7cfb19 Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 19 Nov 2025 17:10:05 -0600 Subject: [PATCH 16/73] Another major cleanup 90% of first pass --- packages/superdough/superdough.mjs | 257 +++++++++++------------------ packages/superdough/worklets.mjs | 4 +- 2 files changed, 100 insertions(+), 161 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 52137c510..4cd713763 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -376,8 +376,7 @@ export function resetGlobalEffects() { controller?.reset(); analysers = {}; analysersData = {}; - lfos = {}; - nodes = {}; + idToNodes = {}; } function _getNodeParam(node, name) { @@ -409,66 +408,21 @@ function _getNodeParams(node) { return Array.from(params); } -/** - * Split parameters (which might be arrays -- implying multiple-parameter modulation -- or a single number) into independent - * objects which only account for single-parameter modulation - * - * @param {Object} params - Dictionary of modulation parameters. - * @returns {Object[]} - Array of parameter objects, one per parameter modulation - */ -function _splitParams(params) { - const num = ['num', 'target', 'param'] // names used to indicate individual parameter modulations - .map((k) => [params[k] ?? 0].flat().length) - .reduce((a, v) => Math.max(a, v), 1); - - const individualParams = []; - for (let i = 0; i < num; i++) { - const paramsI = {}; - for (const k in params) { - const flatV = [params[k]].flat(); - if (flatV.length !== num && flatV.length !== 1) { - errorLogger( - new Error( - `Could not set up modulations. We derived ${num} items, but ${k}: ${JSON.stringify(flatV)} has length ${flatV.length} (needs 1 or ${num}).`, - ), - 'superdough', - ); - return []; - } - paramsI[k] = flatV[i] ?? flatV[0]; - } - individualParams.push(paramsI); - } - return individualParams; -} - -/** - * Given a node name and the name of a parameter on that node, attempt to retrieve - * all nodes corresponding to the name and their associated parameters - * - * Note that we say nodes, plural, because some nodes have multiple sub-nodes, like a - * 24db filter which is two filters in series - * - * @param {string} targetName - Name of the node to modulate parameters on (e.g. `lpf`, `source`, etc.) - * @param {string} paramName - Name of the parameter to modulate on that node - * @returns {AudioParam[]} - Array of audio parameter objects for modulation - * - */ -function _getTargetParams(targetName, paramName) { - const targetNodes = nodes[targetName]; +function _getTargetParams(nodes, target) { + const targetNodes = nodes[target]; if (!targetNodes) { const keys = Object.keys(nodes); errorLogger( new Error( - `Could not connect to target '${targetName}' — it does not exist. Available targets: ${keys.join(', ')}`, + `Could not connect to target '${target}' — it does not exist. Available targets: ${keys.join(', ')}`, ), 'superdough', ); return []; } - const audioParams = []; targetNodes.forEach((targetNode) => { + const paramName = guessParamName(blah); const targetParam = _getNodeParam(targetNode, paramName); if (!targetParam) { const available = _getNodeParams(targetNode); @@ -485,64 +439,57 @@ function _getTargetParams(targetName, paramName) { return audioParams; } -function _setWorkletParamsAtTime(audioParams, params, time) { - for (const [name, value] of params) { - if (value == null) continue; - const p = audioParams.get(name); - if (p.cancelAndHoldAtTime) p.cancelAndHoldAtTime(time); - else p.cancelScheduledValues(time); - p.setValueAtTime(value, time); - } -} - -let lfos = {}; -function _connectLFO(params, nodeTracker) { +function connectLFO(idx, params, nodeTracker) { const { - frequency = 1, - synced = 0, - cps = 0.5, - num = 1, // default to LFO 1 + rate = 1, + sync, + cps, target, - param, - begin, ...filteredParams } = params; - filteredParams['frequency'] = synced ? frequency / cps : frequency; - let lfoNode = lfos[num]; - if (lfoNode == null) { - const ac = getAudioContext(); - lfoNode = getLfo(ac, filteredParams); - lfos[num] = lfoNode; - nodeTracker[`lfo${num}`] = [lfoNode]; - } - const targets = _getTargetParams(target, param); - targets.forEach((target) => lfoNode.connect(target)); - _setWorkletParamsAtTime(lfoNode.parameters, Object.entries(filteredParams), begin); - return lfoNode; + filteredParams['frequency'] = sync !== undefined ? sync / cps : rate; + const ac = getAudioContext(); + lfoNode = getLfo(ac, filteredParams); + nodeTracker[`lfo${idx}`] = [lfoNode]; + _getTargetParams(target).forEach(lfoNode.connect); } -function _connectEnvelope(params) { - const { target, param, envDepth, begin, end, attack, decay, sustain, release, curve, ...filteredParams } = params; - const targets = _getTargetParams(target, param); - const [att, dec, sus, rel] = getADSRValues([attack, decay, sustain, release], curve, [0.005, 0.14, 0, 0.1]); - targets.forEach((targetParam) => { - const currentValue = targetParam.value; - const min = currentValue; - const max = currentValue + envDepth; - getParamADSR(targetParam, att, dec, sus, rel, min, max, begin, end, curve); - }); +function connectEnvelope(idx, params, nodeTracker) { + const { target, ...filteredParams } = params; + const ac = getAudioContext(); + envNode = getEnvelope(ac, filteredParams); + nodeTracker[`env${idx}`] = [envNode]; + _getTargetParams(nodeTracker, target).forEach(envNode.connect); } -function connectModulators(params, modulatorType, nodeTracker) { - // We break down params specifying multiple modulators into a set of parameters for - // a single one - const individualParams = _splitParams(params); - if (modulatorType === 'lfo') { - individualParams.map((p) => _connectLFO(p, nodeTracker)); - } else if (modulatorType === 'envelope') { - individualParams.forEach(_connectEnvelope); - } - return []; +function connectSendModulator(params, signal, nodeTracker, pendingConnections) { + const dc = new ConstantSourceNode(ac, { offset: params.dc ?? 0 }); + dc.start(t); + const offset = new ConstantSourceNode(ac, { offset: params.offset ?? 0 }); + offset.start(t); + const raw = dc.connect(gainNode(1)); + const modulator = post + .connect(raw) + .connect(gainNode((params.depth ?? 1) / 0.3)) + .connect(gainNode(1)); + offset.connect(modulator); + webAudioTimeout( + ac, + () => { + _getTargetParams(nodeTracker, params.target).forEach(signal.connect);; + }, + 0, + params.begin, + ); + webAudioTimeout( + ac, + () => { + signal.disconnect(); + delete pendingConnections[params.id][chainID]; + }, + 0, + params.end + 0.05, + ); } let activeSoundSources = new Map(); @@ -552,9 +499,10 @@ function mapChannelNumbers(channels) { return (Array.isArray(channels) ? channels : [channels]).map((ch) => ch - 1); } -let nodes = {}; - +let idToNodes = {}; +let pendingConnections = {}; export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) => { + const nodes = {}; // new: t is always expected to be the absolute target onset time const ac = getAudioContext(); const audioController = getSuperdoughAudioController(); @@ -644,24 +592,6 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) compressorKnee, compressorAttack, compressorRelease, - lfoNum, - lfoTarget, - lfoParam, - lfoRate, - lfoDepth, - lfoDCOffset, - lfoShape, - lfoSkew, - lfoCurve, - lfoSynced, - envTarget, - envParam, - envAttack, - envDecay, - envSustain, - envRelease, - envCurve, - envDepth, } = value; delaytime = delaytime ?? cycleToSeconds(delaysync, cps); @@ -991,45 +921,56 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) chain.slice(1).reduce((last, current) => last.connect(current), chain[0]); audioNodes = audioNodes.concat(chain); - // finally, now that `nodes` is populated, set up LFOs and envelopes - if (lfoTarget !== undefined && lfoParam !== undefined) { - connectModulators( - { - num: lfoNum ?? 1, - target: lfoTarget, - param: lfoParam, - frequency: lfoRate, - depth: lfoDepth, - dcoffset: lfoDCOffset ?? 0, // override default value of 0.5 - shape: lfoShape, - skew: lfoSkew, - curve: lfoCurve, - persistent: 1, - begin: t, - synced: lfoSynced, - cps: cps, - }, - 'lfo', - nodes, - ); + // finally, now that `nodes` is populated, set up modulators + if (value.lfo) { + for (const [params, idx] of Object.entries(value.lfo)) { + connectLFO( + idx, + { + ...params, + cps, + begin: t, + end: endWithRelease, + }, + 'lfo', + nodes, + ); + } } - if (envTarget !== undefined && envParam !== undefined) { - connectModulators( - { - target: envTarget, - param: envParam, - envDepth, - attack: envAttack, - decay: envDecay, - sustain: envSustain, - release: envRelease, - curve: envCurve, - begin: t, - end: endWithRelease, - }, - 'envelope', - ); + if (value.env) { + for (const [params, idx] of Object.entries(value.env)) { + connectEnvelope( + idx, + { + ...params, + begin: t, + end: endWithRelease, + }, + 'envelope', + nodes, + ); + } } + if (value.id) { + idToNodes[value.id] = new WeakRef(nodes); + } + if (value.send) { + for (const p of value.env) { + const modNodes = idToNodes[p.id]; + if (!modNodes) { + logger( + `[superdough] Could not connect to pattern ${p.id} -- make sure a pattern with this name exists. Available targets: ${Object.keys(idToNodes).join(', ')}`, + ); + } else { + connectSendModulator(params, post); + pendingConnections[p.id] ??= {}; + pendingConnections[p.id][chainID] = [modulator, p.target, p.param, endWithRelease]; + } + }); + } + + if (applySends) { + }; export const superdoughTrigger = (t, hap, ct, cps) => { diff --git a/packages/superdough/worklets.mjs b/packages/superdough/worklets.mjs index 466055563..a098929b2 100644 --- a/packages/superdough/worklets.mjs +++ b/packages/superdough/worklets.mjs @@ -123,7 +123,6 @@ class LFOProcessor extends AudioWorkletProcessor { { name: 'dcoffset', defaultValue: 0 }, { name: 'min', defaultValue: 0 }, { name: 'max', defaultValue: 1 }, - { name: 'persistent', defaultValue: 0, min: 0, max: 1 }, // whether to ignore end ]; } @@ -142,8 +141,7 @@ class LFOProcessor extends AudioWorkletProcessor { process(_inputs, outputs, parameters) { const begin = parameters['begin'][0]; const end = parameters['end'][0]; - const persistent = parameters['persistent'][0]; - if (persistent < 0.5 && currentTime >= end) { + if (currentTime >= end) { return false; } if (currentTime <= begin) { From f8796d039ff90d4408068cff633cc2933617fbf9 Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 19 Nov 2025 17:18:38 -0600 Subject: [PATCH 17/73] Add param guesses --- packages/superdough/superdough.mjs | 36 +++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 4cd713763..df1090a83 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -408,7 +408,38 @@ function _getNodeParams(node) { return Array.from(params); } +const targetToParamGuess = { + source: 'detune', + lpf: 'frequency', + bpf: 'frequency', + hpf: 'frequency', + distort: 'distort', + gain: 'gain', + vowel: 'frequency', + coarse: 'coarse', + crush: 'crush', + shape: 'shape', + compressor: 'threshold', + pan: 'pan', + phaser: 'rate', + post: 'gain', + delay: 'time', + room: 'size', + djf: 'value', + lfo: 'frequency', + env: 'depth', + send: 'depth', +} + function _getTargetParams(nodes, target) { + let param; + if (target.includes('.')) { + const split = target.split('.'); + target = split[0]; + param = split[1]; + } else { + param = targetToParamGuess[target]; + } const targetNodes = nodes[target]; if (!targetNodes) { const keys = Object.keys(nodes); @@ -422,13 +453,12 @@ function _getTargetParams(nodes, target) { } const audioParams = []; targetNodes.forEach((targetNode) => { - const paramName = guessParamName(blah); - const targetParam = _getNodeParam(targetNode, paramName); + const targetParam = _getNodeParam(targetNode, param); if (!targetParam) { const available = _getNodeParams(targetNode); errorLogger( new Error( - `Could not connect to parameter '${paramName}' on '${targetName}'. Available parameters: ${available.join(', ')}`, + `Could not connect to parameter '${param}' on '${targetName}'. Available parameters: ${available.join(', ')}`, ), 'superdough', ); From 0dbca05de09a07a967318f07595829edffc1a74d Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 19 Nov 2025 17:24:33 -0600 Subject: [PATCH 18/73] Ready for testing --- packages/superdough/superdough.mjs | 50 ++++++++++++++++++------------ 1 file changed, 31 insertions(+), 19 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index df1090a83..1262a9261 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -423,13 +423,13 @@ const targetToParamGuess = { pan: 'pan', phaser: 'rate', post: 'gain', - delay: 'time', + delay: 'delayTime', room: 'size', djf: 'value', lfo: 'frequency', env: 'depth', send: 'depth', -} +}; function _getTargetParams(nodes, target) { let param; @@ -438,15 +438,14 @@ function _getTargetParams(nodes, target) { target = split[0]; param = split[1]; } else { - param = targetToParamGuess[target]; + const targetWithoutIndex = target.replace(/(\d+)$/, ''); + param = targetToParamGuess[targetWithoutIndex]; } const targetNodes = nodes[target]; if (!targetNodes) { const keys = Object.keys(nodes); errorLogger( - new Error( - `Could not connect to target '${target}' — it does not exist. Available targets: ${keys.join(', ')}`, - ), + new Error(`Could not connect to target '${target}' — it does not exist. Available targets: ${keys.join(', ')}`), 'superdough', ); return []; @@ -470,13 +469,7 @@ function _getTargetParams(nodes, target) { } function connectLFO(idx, params, nodeTracker) { - const { - rate = 1, - sync, - cps, - target, - ...filteredParams - } = params; + const { rate = 1, sync, cps, target, ...filteredParams } = params; filteredParams['frequency'] = sync !== undefined ? sync / cps : rate; const ac = getAudioContext(); lfoNode = getLfo(ac, filteredParams); @@ -506,7 +499,7 @@ function connectSendModulator(params, signal, nodeTracker, pendingConnections) { webAudioTimeout( ac, () => { - _getTargetParams(nodeTracker, params.target).forEach(signal.connect);; + _getTargetParams(nodeTracker, params.target).forEach(signal.connect); }, 0, params.begin, @@ -994,13 +987,32 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) } else { connectSendModulator(params, post); pendingConnections[p.id] ??= {}; - pendingConnections[p.id][chainID] = [modulator, p.target, p.param, endWithRelease]; + pendingConnections[p.id][chainID] = new WeakRef([modulator, p.target, endWithRelease]); } - }); + } + } + if (value.id in pendingConnections) { + for (const data of Object.values(pendingConnections[id])) { + const [modulator, target, end] = data.deref(); + const targets = _getTargetParams(nodes, target); + webAudioTimeout( + ac, + () => { + targets.forEach((target) => modulator.connect(target)); + }, + 0, + t, + ); + webAudioTimeout( + ac, + () => { + modulator.disconnect(); + }, + 0, + end, + ); + } } - - if (applySends) { - }; export const superdoughTrigger = (t, hap, ct, cps) => { From 19b710c401831f2fd67673bc725061753138ab7a Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 19 Nov 2025 19:44:02 -0600 Subject: [PATCH 19/73] Mostly working version --- packages/core/controls.mjs | 1 - packages/core/pattern.mjs | 12 +++--- packages/soundfonts/fontloader.mjs | 2 +- packages/superdough/helpers.mjs | 20 +++------ packages/superdough/sampler.mjs | 2 +- packages/superdough/superdough.mjs | 68 +++++++++++++----------------- packages/superdough/synth.mjs | 14 +++--- packages/superdough/worklets.mjs | 6 +-- packages/superdough/zzfx.mjs | 1 + 9 files changed, 56 insertions(+), 70 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index bcab1d1b8..eab904429 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -2320,7 +2320,6 @@ export const { curve } = registerControl('curve'); export const { deltaSlide } = registerControl('deltaSlide'); export const { pitchJump } = registerControl('pitchJump'); export const { pitchJumpTime } = registerControl('pitchJumpTime'); -export const { lfo, repeatTime } = registerControl('lfo', 'repeatTime'); // noise on the frequency or as bubo calls it "frequency fog" :) export const { znoise } = registerControl('znoise'); export const { zmod } = registerControl('zmod'); diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index 1eefa41eb..a15ee42e4 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -3710,7 +3710,7 @@ addConfigAlias('lfo', 'target', 't'); addConfigAlias('lfo', 'param', 'p'); addConfigAlias('lfo', 'rate', 'r'); addConfigAlias('lfo', 'depth', 'dep', 'dp', 'd'); -addConfigAlias('lfo', 'dc'); +addConfigAlias('lfo', 'dcoffset', 'dc'); addConfigAlias('lfo', 'shape', 'sh'); addConfigAlias('lfo', 'skew', 'sk'); addConfigAlias('lfo', 'curve', 'c'); @@ -3730,7 +3730,7 @@ addConfigAlias('send', 'depth', 'dep', 'dp', 'd'); addConfigAlias('send', 'dc'); addConfigAlias('send', 'offset', 'off', 'o'); -Pattern.prototype.mod = function (type, config, idx) { +Pattern.prototype.modulate = function (type, config, idx) { if (config == null || typeof config !== 'object') { return this; } @@ -3766,7 +3766,7 @@ Pattern.prototype.mod = function (type, config, idx) { * @param {string | Pattern} [config.target] Node (and parameter if specified like `lpf.frequency`) to modulate. Aliases: target, t * @param {number | Pattern} [config.rate] Modulation rate. Aliases: rate, r * @param {number | Pattern} [config.depth] Modulation depth. Aliases: dep, dp, d - * @param {number | Pattern} [config.dc] DC offset / bias for the waveform + * @param {number | Pattern} [config.dcoffset] DC offset / bias for the waveform. Aliases: dc * @param {number | Pattern} [config.shape] Waveform shape index. Aliases: sh * @param {number | Pattern} [config.skew] Waveform skew amount. Aliases: sk * @param {number | Pattern} [config.curve] Exponential curve amount. Aliases: c @@ -3775,7 +3775,7 @@ Pattern.prototype.mod = function (type, config, idx) { * @returns Pattern */ Pattern.prototype.lfo = function (config, idx) { - return this.mod('lfo', config, idx); + return this.modulate('lfo', config, idx); }; export const lfo = (config) => pure({}).lfo(config); @@ -3799,7 +3799,7 @@ export const lfo = (config) => pure({}).lfo(config); * @returns Pattern */ Pattern.prototype.env = function (config, idx) { - return this.mod('env', config, idx); + return this.modulate('env', config, idx); }; export const env = (config) => pure({}).env(config); @@ -3820,6 +3820,6 @@ export const env = (config) => pure({}).env(config); * @returns Pattern */ Pattern.prototype.send = function (config, idx) { - return this.mod('send', config, idx); + return this.modulate('send', config, idx); }; export const send = (config) => pure({}).send(config); diff --git a/packages/soundfonts/fontloader.mjs b/packages/soundfonts/fontloader.mjs index 427f57e31..9b0525ec7 100644 --- a/packages/soundfonts/fontloader.mjs +++ b/packages/soundfonts/fontloader.mjs @@ -176,7 +176,7 @@ export function registerSoundfonts() { node.disconnect(); onended(); }; - return { node, stop }; + return { node, stop, source: bufferSource }; }, { type: 'soundfont', prebake: true, fonts }, ); diff --git a/packages/superdough/helpers.mjs b/packages/superdough/helpers.mjs index 47161ed61..00ea3883e 100644 --- a/packages/superdough/helpers.mjs +++ b/packages/superdough/helpers.mjs @@ -105,22 +105,16 @@ function getModulationShapeInput(val) { return { tri: 0, triangle: 0, sine: 1, ramp: 2, saw: 3, square: 4 }[val] ?? 0; } -export function getLfo(audioContext, begin, end, properties = {}) { - const { shape = 0, ...props } = properties; - const { dcoffset = -0.5, depth = 1 } = properties; +export function getEnvelope(audioContext, properties = {}) { + return getWorklet(audioContext, 'envelope-processor', properties); +} + +export function getLfo(audioContext, properties = {}) { + // Extract some params we need for deriving other params + const { begin, shape = 0, ...props } = properties; const lfoprops = { - frequency: 1, - depth, - skew: 0.5, - phaseoffset: 0, time: begin, - begin, - end, shape: getModulationShapeInput(shape), - dcoffset, - min: dcoffset * depth, - max: dcoffset * depth + depth, - curve: 1, ...props, }; diff --git a/packages/superdough/sampler.mjs b/packages/superdough/sampler.mjs index 84bac3582..a966252d7 100644 --- a/packages/superdough/sampler.mjs +++ b/packages/superdough/sampler.mjs @@ -331,7 +331,7 @@ export async function onTriggerSample(t, value, onended, bank, resolveUrl) { const stop = (endTime) => { bufferSource.stop(endTime); }; - const handle = { node: out, bufferSource, stop }; + const handle = { node: out, source: bufferSource, stop }; // cut groups if (cut !== undefined) { diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 1262a9261..b2017a9d0 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -16,13 +16,14 @@ import { getADSRValues, getCompressor, getDistortion, + getEnvelope, getLfo, getParamADSR, getWorklet, webAudioTimeout, } from './helpers.mjs'; import { map } from 'nanostores'; -import { logger } from './logger.mjs'; +import { errorLogger, logger } from './logger.mjs'; import { loadBuffer } from './sampler.mjs'; import { getAudioContext } from './audioContext.mjs'; import { SuperdoughAudioController } from './superdoughoutput.mjs'; @@ -292,18 +293,6 @@ function getSuperdoughAudioController() { return controller; } -export function getLfo(audioContext, properties = {}) { - // Extract some params we need for deriving other params - const { begin, shape = 0, ...props } = properties; - const lfoprops = { - time: begin, - shape: getModulationShapeInput(shape), - ...props, - }; - - return getWorklet(audioContext, 'lfo-processor', lfoprops); -} - export function connectToDestination(input, channels) { const controller = getSuperdoughAudioController(); controller.output.connectToDestination(input, channels); @@ -445,7 +434,7 @@ function _getTargetParams(nodes, target) { if (!targetNodes) { const keys = Object.keys(nodes); errorLogger( - new Error(`Could not connect to target '${target}' — it does not exist. Available targets: ${keys.join(', ')}`), + `Could not connect to target '${target}' — it does not exist. Available targets: ${keys.join(', ')}`, 'superdough', ); return []; @@ -456,9 +445,7 @@ function _getTargetParams(nodes, target) { if (!targetParam) { const available = _getNodeParams(targetNode); errorLogger( - new Error( - `Could not connect to parameter '${param}' on '${targetName}'. Available parameters: ${available.join(', ')}`, - ), + `Could not connect to parameter '${param}' on '${target}'. Available parameters: ${available.join(', ')}`, 'superdough', ); return; @@ -472,26 +459,27 @@ function connectLFO(idx, params, nodeTracker) { const { rate = 1, sync, cps, target, ...filteredParams } = params; filteredParams['frequency'] = sync !== undefined ? sync / cps : rate; const ac = getAudioContext(); - lfoNode = getLfo(ac, filteredParams); + const lfoNode = getLfo(ac, filteredParams); nodeTracker[`lfo${idx}`] = [lfoNode]; - _getTargetParams(target).forEach(lfoNode.connect); + _getTargetParams(nodeTracker, target).forEach((t) => lfoNode.connect(t)); } function connectEnvelope(idx, params, nodeTracker) { const { target, ...filteredParams } = params; const ac = getAudioContext(); - envNode = getEnvelope(ac, filteredParams); + const envNode = getEnvelope(ac, filteredParams); nodeTracker[`env${idx}`] = [envNode]; - _getTargetParams(nodeTracker, target).forEach(envNode.connect); + _getTargetParams(nodeTracker, target).forEach((t) => envNode.connect(t)); } -function connectSendModulator(params, signal, nodeTracker, pendingConnections) { +function connectSendModulator(params, signal, nodeTracker, chainID) { + const ac = getAudioContext(); const dc = new ConstantSourceNode(ac, { offset: params.dc ?? 0 }); - dc.start(t); + dc.start(params.begin); const offset = new ConstantSourceNode(ac, { offset: params.offset ?? 0 }); - offset.start(t); + offset.start(params.begin); const raw = dc.connect(gainNode(1)); - const modulator = post + const modulator = signal .connect(raw) .connect(gainNode((params.depth ?? 1) / 0.3)) .connect(gainNode(1)); @@ -499,7 +487,7 @@ function connectSendModulator(params, signal, nodeTracker, pendingConnections) { webAudioTimeout( ac, () => { - _getTargetParams(nodeTracker, params.target).forEach(signal.connect); + _getTargetParams(nodeTracker, params.target).forEach((t) => modulator.connect(t)); }, 0, params.begin, @@ -507,12 +495,13 @@ function connectSendModulator(params, signal, nodeTracker, pendingConnections) { webAudioTimeout( ac, () => { - signal.disconnect(); + modulator.disconnect(); delete pendingConnections[params.id][chainID]; }, 0, params.end + 0.05, ); + return modulator; } let activeSoundSources = new Map(); @@ -679,7 +668,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) if (soundHandle) { sourceNode = soundHandle.node; activeSoundSources.set(chainID, new WeakRef(soundHandle)); // allow GC - nodes['source'] = [soundHandle.oscillator]; + nodes['source'] = [soundHandle.source]; } } else { throw new Error(`sound ${s} not found! Is it loaded?`); @@ -761,7 +750,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) hpParams.type = 'highpass'; const hp1 = filt(hpParams); nodes['hpf'] = [hp1]; - chain.push(hp()); + chain.push(hp1); if (ftype === '24db') { const hp2 = filt(hpParams); nodes['hpf'].push(hp1); @@ -791,7 +780,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) const bpParams = pickAndRename(value, bpMap); bpParams.type = 'bandpass'; const bp1 = filt(bpParams); - chain.push(bp()); + chain.push(bp1); if (ftype === '24db') { const bp2 = filt(bpParams); nodes['bpf'].push(bp2); @@ -946,7 +935,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) // finally, now that `nodes` is populated, set up modulators if (value.lfo) { - for (const [params, idx] of Object.entries(value.lfo)) { + for (const [idx, params] of Object.entries(value.lfo)) { connectLFO( idx, { @@ -955,13 +944,12 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) begin: t, end: endWithRelease, }, - 'lfo', nodes, ); } } if (value.env) { - for (const [params, idx] of Object.entries(value.env)) { + for (const [idx, params] of Object.entries(value.env)) { connectEnvelope( idx, { @@ -969,7 +957,6 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) begin: t, end: endWithRelease, }, - 'envelope', nodes, ); } @@ -978,22 +965,27 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) idToNodes[value.id] = new WeakRef(nodes); } if (value.send) { - for (const p of value.env) { + for (const p of value.send) { const modNodes = idToNodes[p.id]; if (!modNodes) { logger( `[superdough] Could not connect to pattern ${p.id} -- make sure a pattern with this name exists. Available targets: ${Object.keys(idToNodes).join(', ')}`, ); } else { - connectSendModulator(params, post); + const modulator = connectSendModulator({ ...p, begin: t, end: endWithRelease }, post, nodes, chainID); pendingConnections[p.id] ??= {}; pendingConnections[p.id][chainID] = new WeakRef([modulator, p.target, endWithRelease]); } } } if (value.id in pendingConnections) { - for (const data of Object.values(pendingConnections[id])) { - const [modulator, target, end] = data.deref(); + for (const data of Object.values(pendingConnections[value.id])) { + const derefData = data.deref(); + if (!derefData) { + delete pendingConnections[value.id]; + continue; + } + const [modulator, target, end] = derefData; const targets = _getTargetParams(nodes, target); webAudioTimeout( ac, diff --git a/packages/superdough/synth.mjs b/packages/superdough/synth.mjs index ef57ece38..1b88a1e81 100644 --- a/packages/superdough/synth.mjs +++ b/packages/superdough/synth.mjs @@ -71,7 +71,7 @@ export function registerSynthSounds() { stop(envEnd); return { node, - oscillator: o, + source: o, stop: (endTime) => { stop(endTime); }, @@ -141,7 +141,7 @@ export function registerSynthSounds() { return { node, - oscillator: o, + source: o, stop: (endTime) => { o.stop(endTime); }, @@ -208,7 +208,7 @@ export function registerSynthSounds() { return { node: envGain, - oscillator: o, + source: o, stop: (time) => { timeoutNode.stop(time); }, @@ -285,7 +285,7 @@ export function registerSynthSounds() { return { node: envGain, - oscillator: o, + source: o, stop: (time) => { timeoutNode.stop(time); }, @@ -363,7 +363,7 @@ export function registerSynthSounds() { return { node: envGain, - oscillator: o, + source: o, stop: (time) => { timeoutNode.stop(time); }, @@ -409,7 +409,7 @@ export function registerSynthSounds() { stop(envEnd); return { node, - oscillator: o, + source: o, stop: (endTime) => { stop(endTime); }, @@ -503,7 +503,7 @@ export function getOscillator(s, t, value) { return { node: noiseMix?.node || o, - oscillator: o, + source: o, stop: (time) => { fmModulator.stop(time); vibratoOscillator?.stop(time); diff --git a/packages/superdough/worklets.mjs b/packages/superdough/worklets.mjs index a098929b2..cf8d61baf 100644 --- a/packages/superdough/worklets.mjs +++ b/packages/superdough/worklets.mjs @@ -964,7 +964,7 @@ class EnvelopeProcessor extends AudioWorkletProcessor { { name: 'attackCurve', defaultValue: 0, minValue: -1, maxValue: 1 }, { name: 'decayCurve', defaultValue: 0, minValue: -1, maxValue: 1 }, { name: 'releaseCurve', defaultValue: 0, minValue: -1, maxValue: 1 }, - { name: 'peak', defaultValue: 1 }, + { name: 'depth', defaultValue: 1 }, { name: 'retrigger', defaultValue: 1, minValue: 0, maxValue: 1 }, ]; } @@ -1026,7 +1026,7 @@ class EnvelopeProcessor extends AudioWorkletProcessor { const aCurve = pv(params.attackCurve, i); const dCurve = pv(params.decayCurve, i); const rCurve = pv(params.releaseCurve, i); - const peak = pv(params.peak, i); + const depth = pv(params.depth, i); const states = [ { time: Number.POSITIVE_INFINITY, start: 0, target: 0 }, // idle { time: attack, start: this.attackStart, target: 1, curve: aCurve }, @@ -1040,7 +1040,7 @@ class EnvelopeProcessor extends AudioWorkletProcessor { this.state = (this.state + 1) % states.length; time = states[this.state].time; } - out[i] = this.val * peak; + out[i] = this.val * depth; } return true; } diff --git a/packages/superdough/zzfx.mjs b/packages/superdough/zzfx.mjs index 32db0395a..c99b8b9ca 100644 --- a/packages/superdough/zzfx.mjs +++ b/packages/superdough/zzfx.mjs @@ -74,6 +74,7 @@ export const getZZFX = (value, t) => { source.start(t); return { node: source, + source, }; }; From c3ad0d1789d526e006e0d401ad9319ad6f186def Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 19 Nov 2025 20:01:17 -0600 Subject: [PATCH 20/73] Fix for curve params --- packages/superdough/superdough.mjs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index b2017a9d0..2fd74e09a 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -465,9 +465,14 @@ function connectLFO(idx, params, nodeTracker) { } function connectEnvelope(idx, params, nodeTracker) { - const { target, ...filteredParams } = params; + const { target, acurve, dcurve, rcurve, ...filteredParams } = params; const ac = getAudioContext(); - const envNode = getEnvelope(ac, filteredParams); + const envNode = getEnvelope(ac, { + ...filteredParams, + attackCurve: acurve, + decayCurve: dcurve, + releaseCurve: rcurve, + }); nodeTracker[`env${idx}`] = [envNode]; _getTargetParams(nodeTracker, target).forEach((t) => envNode.connect(t)); } From 3e118ce0a88caabce0d8cdacf7cac7e25b1eedfd Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 19 Nov 2025 20:11:02 -0600 Subject: [PATCH 21/73] Fully working version --- packages/superdough/superdough.mjs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 2fd74e09a..c005cae99 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -971,13 +971,14 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) } if (value.send) { for (const p of value.send) { - const modNodes = idToNodes[p.id]; + const modNodes = idToNodes[p.id].deref(); if (!modNodes) { logger( `[superdough] Could not connect to pattern ${p.id} -- make sure a pattern with this name exists. Available targets: ${Object.keys(idToNodes).join(', ')}`, ); + delete idToNodes[p.id]; } else { - const modulator = connectSendModulator({ ...p, begin: t, end: endWithRelease }, post, nodes, chainID); + const modulator = connectSendModulator({ ...p, begin: t, end: endWithRelease }, post, modNodes, chainID); pendingConnections[p.id] ??= {}; pendingConnections[p.id][chainID] = new WeakRef([modulator, p.target, endWithRelease]); } From 2794541dadaccfa828aa0f8c8ce27b29e802c8dd Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 19 Nov 2025 20:52:51 -0600 Subject: [PATCH 22/73] Clean up send nodes and remove offset --- packages/core/pattern.mjs | 2 - packages/superdough/superdough.mjs | 21 ++-- test/__snapshots__/examples.test.mjs.snap | 111 ---------------------- 3 files changed, 11 insertions(+), 123 deletions(-) diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index a15ee42e4..ecca31af8 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -3728,7 +3728,6 @@ addConfigAlias('send', 'id'); addConfigAlias('send', 'target', 't'); addConfigAlias('send', 'depth', 'dep', 'dp', 'd'); addConfigAlias('send', 'dc'); -addConfigAlias('send', 'offset', 'off', 'o'); Pattern.prototype.modulate = function (type, config, idx) { if (config == null || typeof config !== 'object') { @@ -3815,7 +3814,6 @@ export const env = (config) => pure({}).env(config); * @param {string | Pattern} [config.target] Node (and parameter if specified like `lpf.frequency`) to modulate. Aliases: target, t * @param {number | Pattern} [config.depth] Modulation depth. Aliases:dep, dp, d * @param {number | Pattern} [config.dc] DC offset prior to application - * @param {number | Pattern} [config.offset] Offset to apply to the parameter. Aliases: off, o * @param {number | null} idx Index of the send slot to overwrite. Omit to append a new send * @returns Pattern */ diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index c005cae99..0c3e9a719 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -481,14 +481,9 @@ function connectSendModulator(params, signal, nodeTracker, chainID) { const ac = getAudioContext(); const dc = new ConstantSourceNode(ac, { offset: params.dc ?? 0 }); dc.start(params.begin); - const offset = new ConstantSourceNode(ac, { offset: params.offset ?? 0 }); - offset.start(params.begin); - const raw = dc.connect(gainNode(1)); - const modulator = signal - .connect(raw) - .connect(gainNode((params.depth ?? 1) / 0.3)) - .connect(gainNode(1)); - offset.connect(modulator); + const shifted = dc.connect(gainNode(1)); + signal.connect(shifted); + const modulator = shifted.connect(gainNode((params.depth ?? 1) / 0.3)); webAudioTimeout( ac, () => { @@ -506,7 +501,7 @@ function connectSendModulator(params, signal, nodeTracker, chainID) { 0, params.end + 0.05, ); - return modulator; + return { modulator, nodes: [dc, shifted, modulator] }; } let activeSoundSources = new Map(); @@ -978,7 +973,13 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) ); delete idToNodes[p.id]; } else { - const modulator = connectSendModulator({ ...p, begin: t, end: endWithRelease }, post, modNodes, chainID); + const { modulator, nodes: nodesToCleanup } = connectSendModulator( + { ...p, begin: t, end: endWithRelease }, + post, + modNodes, + chainID, + ); + audioNodes = audioNodes.concat(nodesToCleanup); pendingConnections[p.id] ??= {}; pendingConnections[p.id][chainID] = new WeakRef([modulator, p.target, endWithRelease]); } diff --git a/test/__snapshots__/examples.test.mjs.snap b/test/__snapshots__/examples.test.mjs.snap index d0a0153ba..32e61c31d 100644 --- a/test/__snapshots__/examples.test.mjs.snap +++ b/test/__snapshots__/examples.test.mjs.snap @@ -3656,117 +3656,6 @@ exports[`runs examples > example "end" example index 0 1`] = ` ] `; -exports[`runs examples > example "envCurve" example index 0 1`] = ` -[ - "[ 0/1 → 1/8 | note:F#3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 1/8 → 1/4 | note:G#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 1/4 → 3/8 | note:C#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 3/8 → 1/2 | note:C#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 1/2 → 5/8 | note:B3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 5/8 → 3/4 | note:G#3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 3/4 → 7/8 | note:A3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 7/8 → 1/1 | note:C#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 1/1 → 9/8 | note:E4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 9/8 → 5/4 | note:G#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 5/4 → 11/8 | note:G#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 11/8 → 3/2 | note:A3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 3/2 → 13/8 | note:F#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 13/8 → 7/4 | note:D4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 7/4 → 15/8 | note:A3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 15/8 → 2/1 | note:F#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 2/1 → 17/8 | note:C#5 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 17/8 → 9/4 | note:B4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 9/4 → 19/8 | note:C#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 19/8 → 5/2 | note:B4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 5/2 → 21/8 | note:D4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 21/8 → 11/4 | note:G#3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 11/4 → 23/8 | note:F#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 23/8 → 3/1 | note:F#3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 3/1 → 25/8 | note:A3 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 25/8 → 13/4 | note:C#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 13/4 → 27/8 | note:C#5 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 27/8 → 7/2 | note:C#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 7/2 → 29/8 | note:C#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 29/8 → 15/4 | note:C#5 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 15/4 → 31/8 | note:A4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", - "[ 31/8 → 4/1 | note:G#4 room:1 cutoff:100 release:2 envTarget:[source lpf] envParam:[detune frequency] envDepth:[500 4000] envDecay:[0.3 0.15] envCurve:[lin exp] ]", -] -`; - -exports[`runs examples > example "envDepth" example index 0 1`] = ` -[ - "[ 0/1 → 1/8 | note:F#3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 1/8 → 1/4 | note:G#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 1/4 → 3/8 | note:C#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 3/8 → 1/2 | note:C#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 1/2 → 5/8 | note:B3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 5/8 → 3/4 | note:G#3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 3/4 → 7/8 | note:A3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 7/8 → 1/1 | note:C#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 1/1 → 9/8 | note:E4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 9/8 → 5/4 | note:G#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 5/4 → 11/8 | note:G#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 11/8 → 3/2 | note:A3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 3/2 → 13/8 | note:F#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 13/8 → 7/4 | note:D4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 7/4 → 15/8 | note:A3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 15/8 → 2/1 | note:F#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 2/1 → 17/8 | note:C#5 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 17/8 → 9/4 | note:B4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 9/4 → 19/8 | note:C#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 19/8 → 5/2 | note:B4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 5/2 → 21/8 | note:D4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 21/8 → 11/4 | note:G#3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 11/4 → 23/8 | note:F#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 23/8 → 3/1 | note:F#3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 3/1 → 25/8 | note:A3 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 25/8 → 13/4 | note:C#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 13/4 → 27/8 | note:C#5 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 27/8 → 7/2 | note:C#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 7/2 → 29/8 | note:C#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 29/8 → 15/4 | note:C#5 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 15/4 → 31/8 | note:A4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", - "[ 31/8 → 4/1 | note:G#4 room:1 cutoff:100 envTarget:[source lpf] envParam:[detune frequency] envDepth:[4800 400] ]", -] -`; - -exports[`runs examples > example "envRelease" example index 0 1`] = ` -[ - "[ 0/1 → 1/8 | note:F#3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 1/8 → 1/4 | note:G#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 1/4 → 3/8 | note:C#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 3/8 → 1/2 | note:C#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 1/2 → 5/8 | note:B3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 5/8 → 3/4 | note:G#3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 3/4 → 7/8 | note:A3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 7/8 → 1/1 | note:C#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 1/1 → 9/8 | note:E4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 9/8 → 5/4 | note:G#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 5/4 → 11/8 | note:G#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 11/8 → 3/2 | note:A3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 3/2 → 13/8 | note:F#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 13/8 → 7/4 | note:D4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 7/4 → 15/8 | note:A3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 15/8 → 2/1 | note:F#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 2/1 → 17/8 | note:C#5 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 17/8 → 9/4 | note:B4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 9/4 → 19/8 | note:C#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 19/8 → 5/2 | note:B4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 5/2 → 21/8 | note:D4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 21/8 → 11/4 | note:G#3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 11/4 → 23/8 | note:F#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 23/8 → 3/1 | note:F#3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 3/1 → 25/8 | note:A3 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 25/8 → 13/4 | note:C#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 13/4 → 27/8 | note:C#5 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 27/8 → 7/2 | note:C#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 7/2 → 29/8 | note:C#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 29/8 → 15/4 | note:C#5 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 15/4 → 31/8 | note:A4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", - "[ 31/8 → 4/1 | note:G#4 room:1 cutoff:100 release:3 envDepth:[4800 400] envTarget:[source lpf] envParam:[detune frequency] envDecay:[0.03 0.15] envCurve:[exp exp] envSustain:0.5 envRelease:3 ]", -] -`; - exports[`runs examples > example "euclid" example index 0 1`] = ` [ "[ 0/1 → 1/8 | note:c3 ]", From a929b36770ba3bdbcd76fc16f82fc89395b6929a Mon Sep 17 00:00:00 2001 From: Aria Date: Thu, 20 Nov 2025 14:06:45 -0600 Subject: [PATCH 23/73] Remove room --- packages/superdough/superdough.mjs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 0c3e9a719..5ebdd230f 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -413,7 +413,6 @@ const targetToParamGuess = { phaser: 'rate', post: 'gain', delay: 'delayTime', - room: 'size', djf: 'value', lfo: 'frequency', env: 'depth', @@ -904,8 +903,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) } roomIR = await loadBuffer(url, ac, ir, 0); } - const reverbNode = orbitBus.getReverb(roomsize, roomfade, roomlp, roomdim, roomIR, irspeed, irbegin); - nodes['room'] = [reverbNode]; + orbitBus.getReverb(roomsize, roomfade, roomlp, roomdim, roomIR, irspeed, irbegin); const reverbSend = orbitBus.sendReverb(post, room); audioNodes.push(reverbSend); } From 8529516c663ee8c34b8ef108a148c56c1b690fa6 Mon Sep 17 00:00:00 2001 From: Aria Date: Tue, 25 Nov 2025 13:05:27 -0600 Subject: [PATCH 24/73] Add ability to turn mini parsing off with midi-off decorator --- packages/transpiler/test/transpiler.test.mjs | 14 ++++++++ packages/transpiler/transpiler.mjs | 38 ++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/packages/transpiler/test/transpiler.test.mjs b/packages/transpiler/test/transpiler.test.mjs index 02970cf43..68bec9154 100644 --- a/packages/transpiler/test/transpiler.test.mjs +++ b/packages/transpiler/test/transpiler.test.mjs @@ -42,4 +42,18 @@ describe('transpiler', () => { [12, 14], ]); }); + it('allows disabling mini', () => { + const code = `/* mini-off */ + const randPrefix = Math.random() > 0.5 ? "b" : "s"; + const drumPat = \`\${randPrefix}d\`; + // mini-on + s(drumPat).lpf("5000 10000") // make sure mini still runs; + `; + const { output, miniLocations } = transpiler(code, { ...simple, emitMiniLocations: true }); + expect(output).not.toContain("m('b'"); + expect(output).not.toContain("m('s'"); + const cutoffIdx = code.indexOf('5000 10000'); + expect(miniLocations).toHaveLength(2); + expect(miniLocations[0][0]).toEqual(cutoffIdx); + }); }); diff --git a/packages/transpiler/transpiler.mjs b/packages/transpiler/transpiler.mjs index fea6bad4d..b394591c2 100644 --- a/packages/transpiler/transpiler.mjs +++ b/packages/transpiler/transpiler.mjs @@ -21,12 +21,15 @@ export function registerLanguage(type, config) { export function transpiler(input, options = {}) { const { wrapAsync = false, addReturn = true, emitMiniLocations = true, emitWidgets = true } = options; + const comments = []; let ast = parse(input, { ecmaVersion: 2022, allowAwaitOutsideFunction: true, locations: true, + onComment: comments, }); + const miniDisableRanges = findMiniDisableRanges(comments, input.length); let miniLocations = []; const collectMiniLocations = (value, node) => { const minilang = languages.get('minilang'); @@ -66,6 +69,9 @@ export function transpiler(input, options = {}) { return this.replace(tidalWithLocation(raw, offset)); } if (isBackTickString(node, parent)) { + if (isMiniDisabled(node.start, miniDisableRanges)) { + return; + } const { quasis } = node; const { raw } = quasis[0].value; this.skip(); @@ -73,6 +79,9 @@ export function transpiler(input, options = {}) { return this.replace(miniWithLocation(raw, node)); } if (isStringWithDoubleQuotes(node)) { + if (isMiniDisabled(node.start, miniDisableRanges)) { + return; + } const { value } = node; this.skip(); emitMiniLocations && collectMiniLocations(value, node); @@ -327,3 +336,32 @@ function languageWithLocation(name, value, offset) { optional: false, }; } + +function findMiniDisableRanges(comments, codeEnd) { + const ranges = []; + const stack = []; // used to track on/off pairs + for (const comment of comments) { + const value = comment.value.trim(); + if (value.startsWith('mini-off')) { + stack.push(comment.start); + } else if (value.startsWith('mini-on')) { + const start = stack.pop(); + ranges.push([start, comment.end]); + } + } + while (stack.length) { + // If no closing mini-on is found, just turn it off until `codeEnd` + const start = stack.pop(); + ranges.push([start, codeEnd]); + } + return ranges; +} + +function isMiniDisabled(offset, miniDisableRanges) { + for (const [start, end] of miniDisableRanges) { + if (offset >= start && offset < end) { + return true; + } + } + return false; +} From ad43259353a962fb48ec2374a5363715a77e816f Mon Sep 17 00:00:00 2001 From: Aria Date: Fri, 5 Dec 2025 13:39:52 -0600 Subject: [PATCH 25/73] Switch to omod --- packages/core/pattern.mjs | 57 +++++++++---------- packages/soundfonts/fontloader.mjs | 2 +- packages/superdough/helpers.mjs | 4 +- packages/superdough/superdough.mjs | 89 +++++++----------------------- 4 files changed, 52 insertions(+), 100 deletions(-) diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index d1875a964..f1cd06535 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -3726,7 +3726,8 @@ const resolveConfigKey = (funcName, key) => { addConfigAlias('lfo', 'target', 't'); addConfigAlias('lfo', 'param', 'p'); addConfigAlias('lfo', 'rate', 'r'); -addConfigAlias('lfo', 'depth', 'dep', 'dp', 'd'); +addConfigAlias('lfo', 'depth', 'dep', 'dr'); +addConfigAlias('lfo', 'depthabs', 'da'); addConfigAlias('lfo', 'dcoffset', 'dc'); addConfigAlias('lfo', 'shape', 'sh'); addConfigAlias('lfo', 'skew', 'sk'); @@ -3737,21 +3738,23 @@ addConfigAlias('env', 'attack', 'att', 'a'); addConfigAlias('env', 'decay', 'dec', 'd'); addConfigAlias('env', 'sustain', 'sus', 's'); addConfigAlias('env', 'release', 'rel', 'r'); -addConfigAlias('env', 'depth', 'dep', 'dp'); +addConfigAlias('env', 'depth', 'dep', 'dr'); +addConfigAlias('env', 'depthabs', 'da'); addConfigAlias('env', 'acurve', 'ac'); addConfigAlias('env', 'dcurve', 'dc'); addConfigAlias('env', 'rcurve', 'rc'); -addConfigAlias('send', 'id'); -addConfigAlias('send', 'target', 't'); -addConfigAlias('send', 'depth', 'dep', 'dp', 'd'); -addConfigAlias('send', 'dc'); +addConfigAlias('omod', 'orbit', 'o'); +addConfigAlias('omod', 'target', 't'); +addConfigAlias('omod', 'depth', 'dep', 'dr'); +addConfigAlias('omod', 'depthabs', 'da'); +addConfigAlias('omod', 'dc'); Pattern.prototype.modulate = function (type, config, idx) { if (config == null || typeof config !== 'object') { return this; } - if (!['lfo', 'send', 'env'].includes(type)) { - logger(`[core] Modulation type ${type} not found. Please use one of 'lfo', 'env', 'send'`); + if (!['lfo', 'env', 'omod'].includes(type)) { + logger(`[core] Modulation type ${type} not found. Please use one of 'lfo', 'env', 'omod'`); return this; } let output = this; @@ -3775,19 +3778,18 @@ Pattern.prototype.modulate = function (type, config, idx) { /** * Configures an LFO. Can be called in sequence like pat.lfo(...).lfo(...) to set up multiple LFOs * - * * @name lfo * @memberof Pattern * @param {Object} config LFO configuration. - * @param {string | Pattern} [config.target] Node (and parameter if specified like `lpf.frequency`) to modulate. Aliases: target, t + * @param {string | Pattern} [config.target] Node (and parameter if specified like `lpf.frequency`) to modulate. Aliases: t * @param {number | Pattern} [config.rate] Modulation rate. Aliases: rate, r - * @param {number | Pattern} [config.depth] Modulation depth. Aliases: dep, dp, d + * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr + * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da * @param {number | Pattern} [config.dcoffset] DC offset / bias for the waveform. Aliases: dc * @param {number | Pattern} [config.shape] Waveform shape index. Aliases: sh * @param {number | Pattern} [config.skew] Waveform skew amount. Aliases: sk * @param {number | Pattern} [config.curve] Exponential curve amount. Aliases: c * @param {number | Pattern} [config.sync] Tempo-synced modulation rate. Aliases: s - * @param {number | null} idx Index of the LFO slot to overwrite. Omit to append a new LFO * @returns Pattern */ Pattern.prototype.lfo = function (config, idx) { @@ -3798,12 +3800,12 @@ export const lfo = (config) => pure({}).lfo(config); /** * Configures an envelope. Can be called in sequence like pat.env(...).env(...) to set up multiple envelopes * - * * @name env * @memberof Pattern * @param {Object} config Envelope configuration. - * @param {string | Pattern} [config.target] Node (and parameter if specified like `lpf.frequency`) to modulate. Aliases: target, t - * @param {number | Pattern} [config.depth] Modulation depth. Aliases: dep, dp + * @param {string | Pattern} [config.target] Node (and parameter if specified like `lpf.frequency`) to modulate. Aliases: t + * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr + * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da * @param {number | Pattern} [config.attack] Time to reach depth. Aliases: att, a * @param {number | Pattern} [config.decay] Time to reach sustain. Aliases: dec, d * @param {number | Pattern} [config.sustain] Sustain depth. Aliases: sus, s @@ -3811,7 +3813,6 @@ export const lfo = (config) => pure({}).lfo(config); * @param {number | Pattern} [config.acurve] Snappiness of attack curve (-1 = relaxed, 1 = snappy). Aliases: ac * @param {number | Pattern} [config.dcurve] Snappiness of decay curve (-1 = relaxed, 1 = snappy). Aliases: dc * @param {number | Pattern} [config.rcurve] Snappiness of release curve (-1 = relaxed, 1 = snappy). Aliases: rc - * @param {number | null} idx Index of the envelope slot to overwrite. Omit to append a new envelope * @returns Pattern */ Pattern.prototype.env = function (config, idx) { @@ -3820,21 +3821,21 @@ Pattern.prototype.env = function (config, idx) { export const env = (config) => pure({}).env(config); /** - * Sends the output of this pattern to a parameter on another pattern. - * Can be called in sequence like pat.send(...).send(...) to send to multiple parameters + * Modulates with the output from a given `orbit` + * Can be called in sequence like pat.obus(...).obus(...) to set up multiple modulators * - * - * @name send + * @name omod * @memberof Pattern - * @param {Object} config Send configuration. - * @param {string | Pattern} [config.id] Pattern id to modulate - * @param {string | Pattern} [config.target] Node (and parameter if specified like `lpf.frequency`) to modulate. Aliases: target, t - * @param {number | Pattern} [config.depth] Modulation depth. Aliases:dep, dp, d + * @param {Object} config Orbit bus configuration. + * @param {string | Pattern} [config.orbit] Orbit to get modulation signal from + * @param {string | Pattern} [config.target] Node (and parameter if specified like `lpf.frequency`) to modulate. Aliases: t + * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr + * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da + * @param {number | Pattern} [config.ratio] Modulation ratio. Aliases: rat * @param {number | Pattern} [config.dc] DC offset prior to application - * @param {number | null} idx Index of the send slot to overwrite. Omit to append a new send * @returns Pattern */ -Pattern.prototype.send = function (config, idx) { - return this.modulate('send', config, idx); +Pattern.prototype.omod = function (config, idx) { + return this.modulate('omod', config, idx); }; -export const send = (config) => pure({}).send(config); +export const omod = (config) => pure({}).omod(config); diff --git a/packages/soundfonts/fontloader.mjs b/packages/soundfonts/fontloader.mjs index ea5b6818f..62ea5f806 100644 --- a/packages/soundfonts/fontloader.mjs +++ b/packages/soundfonts/fontloader.mjs @@ -176,7 +176,7 @@ export function registerSoundfonts() { vibratoOscillator?.stop(); node.disconnect(); onended(); - }; + }); return { node, stop, source: bufferSource }; }, { type: 'soundfont', prebake: true, fonts }, diff --git a/packages/superdough/helpers.mjs b/packages/superdough/helpers.mjs index 1cd292b9d..33c5a52b4 100644 --- a/packages/superdough/helpers.mjs +++ b/packages/superdough/helpers.mjs @@ -111,13 +111,11 @@ export function getEnvelope(audioContext, properties = {}) { export function getLfo(audioContext, properties = {}) { // Extract some params we need for deriving other params - const { begin, shape = 0, ...props } = properties; + const { shape = 0, ...props } = properties; const lfoprops = { - time: begin, shape: getModulationShapeInput(shape), ...props, }; - return getWorklet(audioContext, 'lfo-processor', lfoprops); } diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 44304e3c3..0a091b156 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -13,12 +13,10 @@ import { createFilter, effectSend, gainNode, - getADSRValues, getCompressor, getDistortion, getEnvelope, getLfo, - getParamADSR, getWorklet, webAudioTimeout, } from './helpers.mjs'; @@ -365,7 +363,6 @@ export function resetGlobalEffects() { controller?.reset(); analysers = {}; analysersData = {}; - idToNodes = {}; } function _getNodeParam(node, name) { @@ -455,12 +452,15 @@ function _getTargetParams(nodes, target) { } function connectLFO(idx, params, nodeTracker) { - const { rate = 1, sync, cps, target, ...filteredParams } = params; + // TODO: figure out min/max values and how to handle depth and depthabs here. + const { rate = 1, sync, cps, cycle, target, ...filteredParams } = params; filteredParams['frequency'] = sync !== undefined ? sync / cps : rate; + filteredParams['time'] = cycle / cps; const ac = getAudioContext(); const lfoNode = getLfo(ac, filteredParams); nodeTracker[`lfo${idx}`] = [lfoNode]; _getTargetParams(nodeTracker, target).forEach((t) => lfoNode.connect(t)); + return lfoNode; } function connectEnvelope(idx, params, nodeTracker) { @@ -474,10 +474,12 @@ function connectEnvelope(idx, params, nodeTracker) { }); nodeTracker[`env${idx}`] = [envNode]; _getTargetParams(nodeTracker, target).forEach((t) => envNode.connect(t)); + return envNode; } -function connectSendModulator(params, signal, nodeTracker, chainID) { +function connectOrbitModulator(params, nodeTracker) { const ac = getAudioContext(); + const signal = controller.getOrbit(params.orbit).output; const dc = new ConstantSourceNode(ac, { offset: params.dc ?? 0 }); dc.start(params.begin); const shifted = dc.connect(gainNode(1)); @@ -491,15 +493,6 @@ function connectSendModulator(params, signal, nodeTracker, chainID) { 0, params.begin, ); - webAudioTimeout( - ac, - () => { - modulator.disconnect(); - delete pendingConnections[params.id][chainID]; - }, - 0, - params.end + 0.05, - ); return { modulator, nodes: [dc, shifted, modulator] }; } @@ -510,8 +503,6 @@ function mapChannelNumbers(channels) { return (Array.isArray(channels) ? channels : [channels]).map((ch) => ch - 1); } -let idToNodes = {}; -let pendingConnections = {}; export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) => { const nodes = {}; // new: t is always expected to be the absolute target onset time @@ -641,7 +632,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) activeSoundSources.delete(chainID); } - let audioNodes = []; + const audioNodes = []; if (['-', '~', '_'].includes(s)) { return; @@ -939,26 +930,28 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) // connect chain elements together chain.slice(1).reduce((last, current) => last.connect(current), chain[0]); - audioNodes = audioNodes.concat(chain); + audioNodes.push(...chain); // finally, now that `nodes` is populated, set up modulators if (value.lfo) { for (const [idx, params] of Object.entries(value.lfo)) { - connectLFO( + const lfo = connectLFO( idx, { ...params, cps, + cycle, begin: t, end: endWithRelease, }, nodes, ); + audioNodes.push(lfo); } } if (value.env) { for (const [idx, params] of Object.entries(value.env)) { - connectEnvelope( + const env = connectEnvelope( idx, { ...params, @@ -967,57 +960,17 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) }, nodes, ); + audioNodes.push(env); } } - if (value.id) { - idToNodes[value.id] = new WeakRef(nodes); - } - if (value.send) { - for (const p of value.send) { - const modNodes = idToNodes[p.id].deref(); - if (!modNodes) { - logger( - `[superdough] Could not connect to pattern ${p.id} -- make sure a pattern with this name exists. Available targets: ${Object.keys(idToNodes).join(', ')}`, - ); - delete idToNodes[p.id]; - } else { - const { modulator, nodes: nodesToCleanup } = connectSendModulator( - { ...p, begin: t, end: endWithRelease }, - post, - modNodes, - chainID, - ); - audioNodes = audioNodes.concat(nodesToCleanup); - pendingConnections[p.id] ??= {}; - pendingConnections[p.id][chainID] = new WeakRef([modulator, p.target, endWithRelease]); - } - } - } - if (value.id in pendingConnections) { - for (const data of Object.values(pendingConnections[value.id])) { - const derefData = data.deref(); - if (!derefData) { - delete pendingConnections[value.id]; - continue; - } - const [modulator, target, end] = derefData; - const targets = _getTargetParams(nodes, target); - webAudioTimeout( - ac, - () => { - targets.forEach((target) => modulator.connect(target)); - }, - 0, - t, - ); - webAudioTimeout( - ac, - () => { - modulator.disconnect(); - }, - 0, - end, + if (value.omod) { + for (const p of value.omod) { + const { nodes: nodesToCleanup } = connectOrbitModulator( + { ...p, begin: t, end: endWithRelease }, + nodes, + chainID, ); + audioNodes.push(...nodesToCleanup); } } }; From 82ca77be9d74c5cae55fb734f3262bbe9f01c1f6 Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 6 Dec 2025 12:02:11 -0600 Subject: [PATCH 26/73] Working version --- packages/core/pattern.mjs | 13 ++- packages/superdough/superdough.mjs | 108 +++++++++++++++++++------ packages/superdough/superdoughdata.mjs | 85 +++++++++++++++++++ packages/superdough/worklets.mjs | 17 ++-- 4 files changed, 191 insertions(+), 32 deletions(-) create mode 100644 packages/superdough/superdoughdata.mjs diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index f1cd06535..986ac9af4 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -3758,19 +3758,26 @@ Pattern.prototype.modulate = function (type, config, idx) { return this; } let output = this; + let target = config.target; for (const [rawKey, value] of Object.entries(config)) { const key = resolveConfigKey(type, rawKey); - const pat = reify(value); + if (key === 'target') continue; // we will set/default it below + const valuePat = reify(value); output = output .fmap((v) => (c) => { + if (target == null) { + // default target to the control set just before this in the chain + // e.g. pat.gain(0.5).lfo({..}) will be a gain-LFO + target = Object.keys(v).at(-1); + } v[type] ??= []; const t = v[type]; idx ??= t.length; - t[idx] ??= {}; + t[idx] ??= { target }; // set target t[idx][key] = c; return v; }) - .appLeft(pat); + .appLeft(valuePat); } return output; }; diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 0a091b156..f32a17168 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -25,6 +25,7 @@ import { errorLogger, logger } from './logger.mjs'; import { loadBuffer } from './sampler.mjs'; import { getAudioContext } from './audioContext.mjs'; import { SuperdoughAudioController } from './superdoughoutput.mjs'; +import { getSuperdoughControlData } from './superdoughdata.mjs'; export const DEFAULT_MAX_POLYPHONY = 128; const DEFAULT_AUDIO_DEVICE_NAME = 'System Standard'; @@ -416,6 +417,28 @@ const targetToParamGuess = { send: 'depth', }; +const controlData = getSuperdoughControlData(); + +// TODO: We would like to use the aliases in `controls` here, but cannot as +// the modules are independent. We may want to inject that method here in situations +// where superdough/core are run in tandem +export let getControlName; +const _getMainName = (control) => getControlName?.(control) ?? control; + +function _getControlData(control) { + return controlData[_getMainName(control)]; +} + +function _getControlValue(control, value, data) { + const main = _getMainName(control); + return Number(value[main] ?? data.default); +} + +function _getControlClamp(data, currentValue) { + const { min, max } = data; + return { min: min - currentValue, max: max - currentValue }; +} + function _getTargetParams(nodes, target) { let param; if (target.includes('.')) { @@ -451,49 +474,77 @@ function _getTargetParams(nodes, target) { return audioParams; } -function connectLFO(idx, params, nodeTracker) { - // TODO: figure out min/max values and how to handle depth and depthabs here. - const { rate = 1, sync, cps, cycle, target, ...filteredParams } = params; - filteredParams['frequency'] = sync !== undefined ? sync / cps : rate; - filteredParams['time'] = cycle / cps; - const ac = getAudioContext(); - const lfoNode = getLfo(ac, filteredParams); +function _getTargetParamsForControl(control, nodes) { + const main = _getMainName(control); + const data = _getControlData(main); + const targetParams = _getTargetParams(nodes, data.param); + return { targetParams, data }; +} + +function connectLFO(idx, params, nodeTracker, value) { + const { rate = 1, sync, cps, cycle, target, depth = 1, depthabs, ...filteredParams } = params; + const { targetParams, data } = _getTargetParamsForControl(target, nodeTracker); + const currentValue = _getControlValue(target, value, data); + const { min, max } = _getControlClamp(data, currentValue); + const depthValue = depthabs != null ? depthabs : depth * currentValue; + const modParams = { + ...filteredParams, + frequency: sync !== undefined ? sync / cps : rate, + time: cycle / cps, + depth: depthValue, + min, + max, + }; + const lfoNode = getLfo(getAudioContext(), modParams); nodeTracker[`lfo${idx}`] = [lfoNode]; - _getTargetParams(nodeTracker, target).forEach((t) => lfoNode.connect(t)); + targetParams.forEach((t) => lfoNode.connect(t)); return lfoNode; } -function connectEnvelope(idx, params, nodeTracker) { - const { target, acurve, dcurve, rcurve, ...filteredParams } = params; - const ac = getAudioContext(); - const envNode = getEnvelope(ac, { +function connectEnvelope(idx, params, nodeTracker, value) { + const { target, acurve, dcurve, rcurve, depth = 1, depthabs, ...filteredParams } = params; + const { targetParams, data } = _getTargetParamsForControl(target, nodeTracker); + const currentValue = _getControlValue(target, value, data); + const { min, max } = _getControlClamp(data, currentValue); + const depthValue = depthabs != null ? depthabs : depth * currentValue; + const envNode = getEnvelope(getAudioContext(), { ...filteredParams, + depth: depthValue, + min, + max, attackCurve: acurve, decayCurve: dcurve, releaseCurve: rcurve, }); nodeTracker[`env${idx}`] = [envNode]; - _getTargetParams(nodeTracker, target).forEach((t) => envNode.connect(t)); + targetParams.forEach((t) => envNode.connect(t)); return envNode; } -function connectOrbitModulator(params, nodeTracker) { +function connectOrbitModulator(params, nodeTracker, value) { const ac = getAudioContext(); + const { target, depth = 1, depthabs } = params; const signal = controller.getOrbit(params.orbit).output; const dc = new ConstantSourceNode(ac, { offset: params.dc ?? 0 }); dc.start(params.begin); const shifted = dc.connect(gainNode(1)); signal.connect(shifted); - const modulator = shifted.connect(gainNode((params.depth ?? 1) / 0.3)); + const { targetParams, data } = _getTargetParamsForControl(target, nodeTracker); + const currentValue = _getControlValue(target, value, data); + const { min, max } = _getControlClamp(data, currentValue); + const depthValue = depthabs != null ? depthabs : depth * currentValue; + const maxAbsDepth = Math.min(Math.abs(min), Math.abs(max)); + const boundedDepth = Math.min(Math.abs(depthValue), maxAbsDepth); + const modulator = shifted.connect(gainNode((Math.sign(depthValue) * boundedDepth) / 0.3)); webAudioTimeout( ac, () => { - _getTargetParams(nodeTracker, params.target).forEach((t) => modulator.connect(t)); + targetParams.forEach((t) => modulator.connect(t)); }, 0, params.begin, ); - return { modulator, nodes: [dc, shifted, modulator] }; + return { modulator, toCleanup: [dc, shifted, modulator] }; } let activeSoundSources = new Map(); @@ -710,11 +761,13 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) lpParams.type = 'lowpass'; const { filter: lpf1, lfo: lfo1 } = filt(lpParams); nodes['lpf'] = [lpf1]; + nodes['lpf_lfo'] = [lfo1]; chain.push(lpf1); lfo1 && audioNodes.push(lfo1); if (ftype === '24db') { const { filter: lpf2, lfo: lfo2 } = filt(lpParams); nodes['lpf'].push(lpf2); + nodes['lpf_lfo'].push(lfo2); chain.push(lpf2); lfo2 && audioNodes.push(lfo2); } @@ -744,11 +797,13 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) hpParams.type = 'highpass'; const { filter: hpf1, lfo: lfo1 } = filt(hpParams); nodes['hpf'] = [hpf1]; + nodes['hpf_lfo'] = [lfo1]; lfo1 && audioNodes.push(lfo1); chain.push(hpf1); if (ftype === '24db') { const { filter: hpf2, lfo: lfo2 } = filt(hpParams); nodes['hpf'].push(hpf2); + nodes['hpf_lfo'].push(lfo2); chain.push(hpf2); lfo2 && audioNodes.push(lfo2); } @@ -777,12 +832,16 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) const bpParams = pickAndRename(value, bpMap); bpParams.type = 'bandpass'; const { filter: bpf1, lfo: lfo1 } = filt(bpParams); + nodes['bpf'] = [bpf1]; + nodes['bpf_lfo'] = [lfo1]; chain.push(bpf1); lfo1 && audioNodes.push(lfo1); if (ftype === '24db') { const { filter: bpf2, lfo: lfo2 } = filt(bpParams); nodes['bpf'].push(bpf2); + nodes['bpf_lfo'].push(lfo2); chain.push(bpf2); + lfo2 && audioNodes.push(lfo2); } } @@ -847,6 +906,8 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) begin: t, end: endWithRelease, }); + nodes['tremolo'] = [lfo]; + nodes['tremolo_gain'] = [amGain]; lfo.connect(amGain.gain); audioNodes.push(lfo); chain.push(amGain); @@ -904,7 +965,8 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) } roomIR = await loadBuffer(url, ac, ir, 0); } - orbitBus.getReverb(roomsize, roomfade, roomlp, roomdim, roomIR, irspeed, irbegin); + const roomNode = orbitBus.getReverb(roomsize, roomfade, roomlp, roomdim, roomIR, irspeed, irbegin); + nodes['room'] = [roomNode]; const reverbSend = orbitBus.sendReverb(post, room); audioNodes.push(reverbSend); } @@ -945,6 +1007,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) end: endWithRelease, }, nodes, + value, ); audioNodes.push(lfo); } @@ -959,18 +1022,15 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) end: endWithRelease, }, nodes, + value, ); audioNodes.push(env); } } if (value.omod) { for (const p of value.omod) { - const { nodes: nodesToCleanup } = connectOrbitModulator( - { ...p, begin: t, end: endWithRelease }, - nodes, - chainID, - ); - audioNodes.push(...nodesToCleanup); + const { toCleanup } = connectOrbitModulator({ ...p, begin: t, end: endWithRelease }, nodes, value); + audioNodes.push(...toCleanup); } } }; diff --git a/packages/superdough/superdoughdata.mjs b/packages/superdough/superdoughdata.mjs new file mode 100644 index 000000000..1f3235e59 --- /dev/null +++ b/packages/superdough/superdoughdata.mjs @@ -0,0 +1,85 @@ +/* +superdoughdata.mjs - Data needed for running superdough (defaults, mappings, etc.) +Copyright (C) 2025 Strudel contributors - see +This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +const CONTROL_DATA = { + stretch: { param: 'stretch.pitchFactor', default: 1, min: -4, max: 100 }, + gain: { param: 'gain.gain', default: 0.8, min: 0, max: 10 }, + postgain: { param: 'post.gain', default: 1, min: 0, max: 10 }, + pan: { param: 'pan.pan', min: 0, max: 1 }, + tremolo: { param: 'tremolo.rate', min: 0, max: 40 }, + tremolosync: { param: 'tremolo.sync', min: 0, max: 8 }, + tremolodepth: { param: 'tremolo_gain.gain', default: 1, min: 0, max: 10 }, + tremoloskew: { param: 'tremolo.skew', min: 0, max: 1 }, + tremolophase: { param: 'tremolo.phase', default: 0, min: 0, max: 1 }, + tremoloshape: { param: 'tremolo.shape', min: 0, max: 4 }, + + // LPF + cutoff: { param: 'lpf.frequency', min: 20, max: 24000 }, + resonance: { param: 'lpf.Q', min: 0.1, max: 30 }, + lprate: { param: 'lpf_lfo.rate', min: 0, max: 40 }, + lpsync: { param: 'lpf_lfo.sync', min: 0, max: 8 }, + lpdepth: { param: 'lpf_lfo.depth', min: 20, max: 24000 }, + lpdepthfrequency: { param: 'lpf_lfo.depth', min: 20, max: 24000 }, + lpshape: { param: 'lpf_lfo.shape', min: 0, max: 4 }, + lpdc: { param: 'lpf_lfo.dcoffset', min: -1, max: 1 }, + lpskew: { param: 'lpf_lfo.skew', min: 0, max: 1 }, + + // HPF + hcutoff: { param: 'hpf.frequency', min: 20, max: 24000 }, + hresonance: { param: 'hpf.Q', min: 0.1, max: 30 }, + + // BPF + bandf: { param: 'bpf.frequency', min: 20, max: 24000 }, + bandq: { param: 'bpf.Q', min: 0.1, max: 30 }, + + // FILTERS + // fanchor: { param: ['lpf.anchor', 'hpf.anchor', 'bpf.anchor'], min: 0, max: 1 }, + // drive: { param: ['lpf.drive', 'hpf.drive', 'bpf.drive'], min: 0, max: 2 }, + // vowel: { param: 'vowel.frequency', min: 200, max: 4000 }, + + // DISTORTION + coarse: { param: 'coarse.coarse', min: 1, max: 64 }, + crush: { param: 'crush.crush', min: 1, max: 16 }, + shape: { param: 'shape.shape', min: -1, max: 0.999 }, + shapevol: { param: 'shape.postgain', default: 1, min: 0, max: 1 }, + distort: { param: 'distort.distort', min: 0, max: 5 }, + distortvol: { param: 'distort.postgain', default: 1, min: 0, max: 1 }, + // distorttype: { param: 'distort.algorithm', default: 0, min: 0, max: 4 }, + + // COMPRESSOR + compressor: { param: 'compressor.threshold', default: -3, min: -100, max: 0 }, + compressorRatio: { param: 'compressor.ratio', default: 10, min: 1, max: 20 }, + compressorKnee: { param: 'compressor.knee', default: 10, min: 0, max: 40 }, + compressorAttack: { param: 'compressor.attack', default: 0.005, min: 0, max: 1 }, + compressorRelease: { param: 'compressor.release', default: 0.05, min: 0, max: 2 }, + + // PHASER + phaserrate: { param: 'phaser.rate', min: 0, max: 40 }, + phaserdepth: { param: 'phaser.depth', default: 0.75, min: 0, max: 1 }, + phasersweep: { param: 'phaser.sweep', min: 0, max: 5000 }, + phasercenter: { param: 'phaser.frequency', min: 20, max: 24000 }, + + // ORBIT EFFECTS + // delay: { param: 'delay.delayTime', default: 0, min: 0, max: 4 }, + delaytime: { param: 'delay.delayTime', min: 0, max: 4 }, + // delayfeedback: { param: 'delay.feedback', default: 0.5, min: 0, max: 0.98 }, + // delaysync: { param: 'delay.sync', default: 3 / 16, min: 0, max: 2 }, + dry: { param: 'dry.gain', min: 0, max: 1 }, + room: { param: 'room.wet', min: 0, max: 1 }, + // roomfade: { param: 'room.fade', min: 0, max: 1 }, + roomlp: { param: 'room.lp', min: 20, max: 24000 }, + djf: { param: 'djf.value', min: 0, max: 1 }, + + // SYNTHS + detune: { param: 'source.detune', min: 0, max: 1 }, + wt: { param: 'source.position', min: 0, max: 1 }, + warp: { param: 'source.warp', min: 0, max: 1 }, + freq: { param: 'source.frequency', min: 20, max: 24000 }, +}; + +export function getSuperdoughControlData() { + return CONTROL_DATA; +} diff --git a/packages/superdough/worklets.mjs b/packages/superdough/worklets.mjs index 65da72bb7..bb33a24ff 100644 --- a/packages/superdough/worklets.mjs +++ b/packages/superdough/worklets.mjs @@ -121,8 +121,8 @@ class LFOProcessor extends AudioWorkletProcessor { { name: 'shape', defaultValue: 0 }, { name: 'curve', defaultValue: 1 }, { name: 'dcoffset', defaultValue: 0 }, - { name: 'min', defaultValue: 0 }, - { name: 'max', defaultValue: 1 }, + { name: 'min', defaultValue: -1e9 }, + { name: 'max', defaultValue: 1e9 }, ]; } @@ -160,8 +160,10 @@ class LFOProcessor extends AudioWorkletProcessor { const dcoffset = parameters['dcoffset'][0]; - const min = dcoffset * depth; - const max = dcoffset * depth + depth; + const userMin = parameters['min'][0]; + const userMax = parameters['max'][0]; + const min = Math.min(userMin, userMax); + const max = Math.max(userMin, userMax); const shape = waveShapeNames[parameters['shape'][0]]; const blockSize = output[0].length ?? 0; @@ -967,6 +969,8 @@ class EnvelopeProcessor extends AudioWorkletProcessor { { name: 'decayCurve', defaultValue: 0, minValue: -1, maxValue: 1 }, { name: 'releaseCurve', defaultValue: 0, minValue: -1, maxValue: 1 }, { name: 'depth', defaultValue: 1 }, + { name: 'min', defaultValue: -1e9 }, + { name: 'max', defaultValue: 1e9 }, { name: 'retrigger', defaultValue: 1, minValue: 0, maxValue: 1 }, ]; } @@ -1029,6 +1033,8 @@ class EnvelopeProcessor extends AudioWorkletProcessor { const dCurve = pv(params.decayCurve, i); const rCurve = pv(params.releaseCurve, i); const depth = pv(params.depth, i); + const clampMin = pv(params.min, i); + const clampMax = pv(params.max, i); const states = [ { time: Number.POSITIVE_INFINITY, start: 0, target: 0 }, // idle { time: attack, start: this.attackStart, target: 1, curve: aCurve }, @@ -1042,7 +1048,8 @@ class EnvelopeProcessor extends AudioWorkletProcessor { this.state = (this.state + 1) % states.length; time = states[this.state].time; } - out[i] = this.val * depth; + const clamped = clamp(this.val * depth, Math.min(clampMin, clampMax), Math.max(clampMin, clampMax)); + out[i] = clamped; } return true; } From a79491dd16fbe10460d5263c77273abe1b305113 Mon Sep 17 00:00:00 2001 From: Aria Date: Mon, 8 Dec 2025 16:32:54 -0600 Subject: [PATCH 27/73] Update loopbegin/end to not be offset --- packages/superdough/sampler.mjs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/packages/superdough/sampler.mjs b/packages/superdough/sampler.mjs index 2deeb4b74..8e46426d3 100644 --- a/packages/superdough/sampler.mjs +++ b/packages/superdough/sampler.mjs @@ -65,21 +65,22 @@ export const getSampleBufferSource = async (hapValue, bank, resolveUrl) => { bufferSource.playbackRate.value = playbackRate; const { loopBegin = 0, loopEnd = 1, begin = 0, end = 1 } = hapValue; + const bufferDuration = bufferSource.buffer.duration; - // "The computation of the offset into the sound is performed using the sound buffer's natural sample rate, - // rather than the current playback rate, so even if the sound is playing at twice its normal speed, - // the midway point through a 10-second audio buffer is still 5." - const offset = begin * bufferSource.buffer.duration; + // The computation of the offset into the sound is performed using the sound buffer's natural duration, + // rather than the playback duration, so that even if the sound is playing at twice its normal speed, + // the midway point through a 10-second audio buffer is still 5. + const offset = begin * bufferDuration; const loop = hapValue.loop; if (loop) { bufferSource.loop = true; - bufferSource.loopStart = loopBegin * bufferSource.buffer.duration - offset; - bufferSource.loopEnd = loopEnd * bufferSource.buffer.duration - offset; + bufferSource.loopStart = loopBegin * bufferDuration; + bufferSource.loopEnd = loopEnd * bufferDuration; } - const bufferDuration = bufferSource.buffer.duration / bufferSource.playbackRate.value; - const sliceDuration = (end - begin) * bufferDuration; - return { bufferSource, offset, bufferDuration, sliceDuration }; + const playbackDuration = bufferDuration / bufferSource.playbackRate.value; + const sliceDuration = (end - begin) * playbackDuration; + return { bufferSource, offset, bufferDuration, playbackDuration, sliceDuration }; }; export const loadBuffer = (url, ac, s, n = 0) => { From 2aeba2e53fa3a72b12b21b97300b5fc0a724a1a0 Mon Sep 17 00:00:00 2001 From: Aria Date: Thu, 11 Dec 2025 11:37:20 -0600 Subject: [PATCH 28/73] Working version of bus --- packages/core/controls.mjs | 22 ++++++++++++++ packages/core/pattern.mjs | 32 ++++++++++---------- packages/superdough/superdough.mjs | 19 ++++++++---- packages/superdough/superdoughdata.mjs | 2 ++ packages/superdough/superdoughoutput.mjs | 24 ++++++++++++--- packages/superdough/synth.mjs | 37 +++++++++++++++++++++++- 6 files changed, 111 insertions(+), 25 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index bcbac6254..6483880b1 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -2046,6 +2046,28 @@ export const { octave, oct } = registerControl('octave', 'oct'); * ) */ export const { orbit } = registerControl('orbit', 'o'); + +/** + * A `bus` is a send which can be used for mixing patterns. It combines with.. + * s("bus") to play that bus through another pattern (for, say, applying non-linear + * effects like distortion to multiple signals) + * + * otherPat.bmod(..) (to modulate another pattern with the bus) + * + * @name bus + * @param {number | Pattern} number + */ +export const { bus } = registerControl('bus'); + +/** + * Postgain multiplier prior to sending the signal to the audio bus. + * + * @name busgain + * @synonyms bgain + * @param {number | Pattern} number + */ +export const { busgain, bgain } = registerControl('busgain', 'bgain'); + // TODO: what is this? not found in tidal doc Answer: gain is limited to maximum of 2. This allows you to go over that export const { overgain } = registerControl('overgain'); // TODO: what is this? not found in tidal doc. Similar to above, but limited to 1 diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index 986ac9af4..b0420a2e6 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -3743,18 +3743,18 @@ addConfigAlias('env', 'depthabs', 'da'); addConfigAlias('env', 'acurve', 'ac'); addConfigAlias('env', 'dcurve', 'dc'); addConfigAlias('env', 'rcurve', 'rc'); -addConfigAlias('omod', 'orbit', 'o'); -addConfigAlias('omod', 'target', 't'); -addConfigAlias('omod', 'depth', 'dep', 'dr'); -addConfigAlias('omod', 'depthabs', 'da'); -addConfigAlias('omod', 'dc'); +addConfigAlias('bmod', 'orbit', 'o'); +addConfigAlias('bmod', 'target', 't'); +addConfigAlias('bmod', 'depth', 'dep', 'dr'); +addConfigAlias('bmod', 'depthabs', 'da'); +addConfigAlias('bmod', 'dc'); Pattern.prototype.modulate = function (type, config, idx) { if (config == null || typeof config !== 'object') { return this; } - if (!['lfo', 'env', 'omod'].includes(type)) { - logger(`[core] Modulation type ${type} not found. Please use one of 'lfo', 'env', 'omod'`); + if (!['lfo', 'env', 'bmod'].includes(type)) { + logger(`[core] Modulation type ${type} not found. Please use one of 'lfo', 'env', 'bmod'`); return this; } let output = this; @@ -3828,13 +3828,15 @@ Pattern.prototype.env = function (config, idx) { export const env = (config) => pure({}).env(config); /** - * Modulates with the output from a given `orbit` - * Can be called in sequence like pat.obus(...).obus(...) to set up multiple modulators + * Modulates with the output from a given `bus`. + * Can be called in sequence like pat.bmod(...).bmod(...) to set up multiple modulators * - * @name omod + * Send to an audio bus with `otherPat.bus(..)`. + * + * @name bmod * @memberof Pattern - * @param {Object} config Orbit bus configuration. - * @param {string | Pattern} [config.orbit] Orbit to get modulation signal from + * @param {Object} config Bus modulation configuration. + * @param {string | Pattern} [config.bus] Bus to get modulation signal from * @param {string | Pattern} [config.target] Node (and parameter if specified like `lpf.frequency`) to modulate. Aliases: t * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da @@ -3842,7 +3844,7 @@ export const env = (config) => pure({}).env(config); * @param {number | Pattern} [config.dc] DC offset prior to application * @returns Pattern */ -Pattern.prototype.omod = function (config, idx) { - return this.modulate('omod', config, idx); +Pattern.prototype.bmod = function (config, idx) { + return this.modulate('bmod', config, idx); }; -export const omod = (config) => pure({}).omod(config); +export const bmod = (config) => pure({}).bmod(config); diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index f32a17168..32d7f0d63 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -163,6 +163,7 @@ let defaultDefaultValues = { distortvol: 1, distorttype: 0, delay: 0, + busgain: 1, byteBeatExpression: '0', delayfeedback: 0.5, delaysync: 3 / 16, @@ -521,10 +522,10 @@ function connectEnvelope(idx, params, nodeTracker, value) { return envNode; } -function connectOrbitModulator(params, nodeTracker, value) { +function connectBusModulator(params, nodeTracker, value) { const ac = getAudioContext(); const { target, depth = 1, depthabs } = params; - const signal = controller.getOrbit(params.orbit).output; + const signal = controller.getBus(params.bus).output; const dc = new ConstantSourceNode(ac, { offset: params.dc ?? 0 }); dc.start(params.begin); const shifted = dc.connect(gainNode(1)); @@ -628,6 +629,8 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) delaysync = getDefaultValue('delaysync'), delaytime, orbit = getDefaultValue('orbit'), + bus, + busgain = getDefaultValue('busgain'), room, roomfade, roomlp, @@ -666,6 +669,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) delay = applyGainCurve(delay); velocity = applyGainCurve(velocity); tremolodepth = applyGainCurve(tremolodepth); + busgain = applyGainCurve(busgain); gain *= velocity; // velocity currently only multiplies with gain. it might do other things in the future const end = t + hapDuration; @@ -970,6 +974,11 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) const reverbSend = orbitBus.sendReverb(post, room); audioNodes.push(reverbSend); } + if (bus != null) { + const busNode = audioController.getBus(bus); + const busSend = effectSend(post, busNode, busgain); + audioNodes.push(busSend); + } if (djf != null) { nodes['djf'] = orbitBus.getDjf(djf, t); @@ -1027,9 +1036,9 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) audioNodes.push(env); } } - if (value.omod) { - for (const p of value.omod) { - const { toCleanup } = connectOrbitModulator({ ...p, begin: t, end: endWithRelease }, nodes, value); + if (value.bmod) { + for (const p of value.bmod) { + const { toCleanup } = connectBusModulator({ ...p, begin: t, end: endWithRelease }, nodes, value); audioNodes.push(...toCleanup); } } diff --git a/packages/superdough/superdoughdata.mjs b/packages/superdough/superdoughdata.mjs index 1f3235e59..8284876e9 100644 --- a/packages/superdough/superdoughdata.mjs +++ b/packages/superdough/superdoughdata.mjs @@ -72,6 +72,8 @@ const CONTROL_DATA = { // roomfade: { param: 'room.fade', min: 0, max: 1 }, roomlp: { param: 'room.lp', min: 20, max: 24000 }, djf: { param: 'djf.value', min: 0, max: 1 }, + busgain: { param: 'bus.gain', default: 1, min: 0, max: 10 }, + bgain: { param: 'bus.gain', default: 1, min: 0, max: 10 }, // SYNTHS detune: { param: 'source.detune', min: 0, max: 1 }, diff --git a/packages/superdough/superdoughoutput.mjs b/packages/superdough/superdoughoutput.mjs index d8ead7d06..204eb62a4 100644 --- a/packages/superdough/superdoughoutput.mjs +++ b/packages/superdough/superdoughoutput.mjs @@ -2,7 +2,10 @@ import { effectSend, getWorklet, webAudioTimeout } from './helpers.mjs'; import { errorLogger } from './logger.mjs'; import { clamp } from './util.mjs'; -let hasChanged = (now, before) => now !== undefined && now !== before; +const hasChanged = (now, before) => now !== undefined && now !== before; +// Node with fixed stereo channel count to prevent clicking when the input signal +// switches from mono to stereo +const getStereoNode = (ac) => new GainNode(ac, { gain: 1, channelCount: 2, channelCountMode: 'explicit' }); export class Orbit { reverbNode; @@ -11,10 +14,11 @@ export class Orbit { summingNode; djfNode; audioContext; + constructor(audioContext) { this.audioContext = audioContext; - this.output = new GainNode(audioContext, { gain: 1, channelCount: 2, channelCountMode: 'explicit' }); - this.summingNode = new GainNode(audioContext, { gain: 1, channelCount: 2, channelCountMode: 'explicit' }); + this.output = getStereoNode(audioContext); + this.summingNode = getStereoNode(audioContext); this.summingNode.connect(this.output); } @@ -164,6 +168,7 @@ export class SuperdoughAudioController { audioContext; output; nodes = {}; + buses = {}; constructor(audioContext) { this.audioContext = audioContext; @@ -171,10 +176,14 @@ export class SuperdoughAudioController { } reset() { - Array.from(this.nodes).forEach((node) => { + Object.values(this.nodes).forEach((node) => { node.disconnect(); }); + Object.values(this.buses).forEach((bus) => { + bus.disconnect(); + }); this.nodes = {}; + this.buses = {}; this.output.reset(); } @@ -206,4 +215,11 @@ export class SuperdoughAudioController { } return this.nodes[orbitNum]; } + + getBus(busNum) { + if (this.buses[busNum] == null) { + this.buses[busNum] = getStereoNode(this.audioContext); + } + return this.buses[busNum]; + } } diff --git a/packages/superdough/synth.mjs b/packages/superdough/synth.mjs index cffbdc0ca..3686e13d1 100644 --- a/packages/superdough/synth.mjs +++ b/packages/superdough/synth.mjs @@ -1,5 +1,5 @@ import { clamp } from './util.mjs'; -import { registerSound, soundMap } from './superdough.mjs'; +import { getSuperdoughAudioController, registerSound, soundMap } from './superdough.mjs'; import { getAudioContext } from './audioContext.mjs'; import { applyFM, @@ -367,6 +367,41 @@ export function registerSynthSounds() { { prebake: true, type: 'synth' }, ); + registerSound( + 'bus', + (begin, value, onended) => { + const ac = getAudioContext(); + const [attack, decay, sustain, release] = getADSRValues( + [value.attack, value.decay, value.sustain, value.release], + 'linear', + [0.001, 0.05, 0.6, 0.01], + ); + const holdend = begin + value.duration; + const end = holdend + release + 0.01; + const bus = getSuperdoughAudioController().getBus(value.n ?? 0); + const envGain = bus.connect(gainNode(1)); + getParamADSR(envGain.gain, attack, decay, sustain, release, 0, 1, begin, holdend, 'linear'); + const timeoutNode = webAudioTimeout( + ac, + () => { + bus.disconnect(envGain); + onended(); + }, + begin, + end, + ); + + return { + node: envGain, + source: bus, + stop: (time) => { + timeoutNode.stop(time); + }, + }; + }, + { prebake: true, type: 'input' }, + ); + [...noises].forEach((s) => { registerSound( s, From 3a17aeabf3227e87d7a9126d7d886043a0ea56c7 Mon Sep 17 00:00:00 2001 From: Aria Date: Thu, 11 Dec 2025 11:41:40 -0600 Subject: [PATCH 29/73] Some cleanup --- packages/core/controls.mjs | 9 --------- packages/superdough/worklets.mjs | 6 ++---- 2 files changed, 2 insertions(+), 13 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index 6483880b1..808babe69 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -2530,15 +2530,6 @@ export const { clip, legato } = registerControl('clip', 'legato'); */ export const { duration, dur } = registerControl('duration', 'dur'); -/** - * Sets the ID of the pattern for later reference - * - * @name id - * @param {number | Pattern} id ID of the pattern - * - */ -export const { id } = registerControl('id'); - // ZZFX export const { zrand } = registerControl('zrand'); export const { curve } = registerControl('curve'); diff --git a/packages/superdough/worklets.mjs b/packages/superdough/worklets.mjs index bb33a24ff..6e850b28d 100644 --- a/packages/superdough/worklets.mjs +++ b/packages/superdough/worklets.mjs @@ -160,10 +160,8 @@ class LFOProcessor extends AudioWorkletProcessor { const dcoffset = parameters['dcoffset'][0]; - const userMin = parameters['min'][0]; - const userMax = parameters['max'][0]; - const min = Math.min(userMin, userMax); - const max = Math.max(userMin, userMax); + const min = parameters['min'][0]; + const max = parameters['max'][0]; const shape = waveShapeNames[parameters['shape'][0]]; const blockSize = output[0].length ?? 0; From 45aa1f5384263fbf52e2be20bbca1a13203de977 Mon Sep 17 00:00:00 2001 From: Aria Date: Thu, 11 Dec 2025 12:52:40 -0600 Subject: [PATCH 30/73] Control cleanup --- packages/superdough/superdoughdata.mjs | 28 +++++++++++++++++--------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/packages/superdough/superdoughdata.mjs b/packages/superdough/superdoughdata.mjs index 8284876e9..fe9bfe46d 100644 --- a/packages/superdough/superdoughdata.mjs +++ b/packages/superdough/superdoughdata.mjs @@ -30,15 +30,26 @@ const CONTROL_DATA = { // HPF hcutoff: { param: 'hpf.frequency', min: 20, max: 24000 }, hresonance: { param: 'hpf.Q', min: 0.1, max: 30 }, + hprate: { param: 'hpf_lfo.rate', min: 0, max: 40 }, + hpsync: { param: 'hpf_lfo.sync', min: 0, max: 8 }, + hpdepth: { param: 'hpf_lfo.depth', min: 20, max: 24000 }, + hpdepthfrequency: { param: 'hpf_lfo.depth', min: 20, max: 24000 }, + hpshape: { param: 'hpf_lfo.shape', min: 0, max: 4 }, + hpdc: { param: 'hpf_lfo.dcoffset', min: -1, max: 1 }, + hpskew: { param: 'hpf_lfo.skew', min: 0, max: 1 }, // BPF bandf: { param: 'bpf.frequency', min: 20, max: 24000 }, bandq: { param: 'bpf.Q', min: 0.1, max: 30 }, + bprate: { param: 'bpf_lfo.rate', min: 0, max: 40 }, + bpsync: { param: 'bpf_lfo.sync', min: 0, max: 8 }, + bpdepth: { param: 'bpf_lfo.depth', min: 20, max: 24000 }, + bpdepthfrequency: { param: 'bpf_lfo.depth', min: 20, max: 24000 }, + bpshape: { param: 'bpf_lfo.shape', min: 0, max: 4 }, + bpdc: { param: 'bpf_lfo.dcoffset', min: -1, max: 1 }, + bpskew: { param: 'bpf_lfo.skew', min: 0, max: 1 }, - // FILTERS - // fanchor: { param: ['lpf.anchor', 'hpf.anchor', 'bpf.anchor'], min: 0, max: 1 }, - // drive: { param: ['lpf.drive', 'hpf.drive', 'bpf.drive'], min: 0, max: 2 }, - // vowel: { param: 'vowel.frequency', min: 200, max: 4000 }, + vowel: { param: 'vowel.frequency', min: 200, max: 4000 }, // DISTORTION coarse: { param: 'coarse.coarse', min: 1, max: 64 }, @@ -47,7 +58,6 @@ const CONTROL_DATA = { shapevol: { param: 'shape.postgain', default: 1, min: 0, max: 1 }, distort: { param: 'distort.distort', min: 0, max: 5 }, distortvol: { param: 'distort.postgain', default: 1, min: 0, max: 1 }, - // distorttype: { param: 'distort.algorithm', default: 0, min: 0, max: 4 }, // COMPRESSOR compressor: { param: 'compressor.threshold', default: -3, min: -100, max: 0 }, @@ -63,17 +73,15 @@ const CONTROL_DATA = { phasercenter: { param: 'phaser.frequency', min: 20, max: 24000 }, // ORBIT EFFECTS - // delay: { param: 'delay.delayTime', default: 0, min: 0, max: 4 }, delaytime: { param: 'delay.delayTime', min: 0, max: 4 }, - // delayfeedback: { param: 'delay.feedback', default: 0.5, min: 0, max: 0.98 }, - // delaysync: { param: 'delay.sync', default: 3 / 16, min: 0, max: 2 }, + delayfeedback: { param: 'delay.feedback', default: 0.5, min: 0, max: 0.98 }, + delaysync: { param: 'delay.sync', default: 3 / 16, min: 0, max: 2 }, dry: { param: 'dry.gain', min: 0, max: 1 }, room: { param: 'room.wet', min: 0, max: 1 }, - // roomfade: { param: 'room.fade', min: 0, max: 1 }, + roomfade: { param: 'room.fade', min: 0, max: 1 }, roomlp: { param: 'room.lp', min: 20, max: 24000 }, djf: { param: 'djf.value', min: 0, max: 1 }, busgain: { param: 'bus.gain', default: 1, min: 0, max: 10 }, - bgain: { param: 'bus.gain', default: 1, min: 0, max: 10 }, // SYNTHS detune: { param: 'source.detune', min: 0, max: 1 }, From e7d1613bfb4978adb498d9ccff87475c584698f5 Mon Sep 17 00:00:00 2001 From: Aria Date: Thu, 11 Dec 2025 14:42:16 -0600 Subject: [PATCH 31/73] Broken tests, but otherwise working --- packages/core/pattern.mjs | 21 ++-- packages/superdough/superdough.mjs | 113 +++++++------------ packages/superdough/superdoughdata.mjs | 144 +++++++++++++------------ packages/superdough/synth.mjs | 2 +- 4 files changed, 128 insertions(+), 152 deletions(-) diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index b0420a2e6..7d0e46138 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -26,6 +26,7 @@ import { } from './util.mjs'; import drawLine from './drawLine.mjs'; import { errorLogger, logger } from './logger.mjs'; +import { getControlName } from './controls.mjs'; let stringParser; @@ -3753,28 +3754,34 @@ Pattern.prototype.modulate = function (type, config, idx) { if (config == null || typeof config !== 'object') { return this; } - if (!['lfo', 'env', 'bmod'].includes(type)) { + const modulatorKeys = ['lfo', 'env', 'bmod']; + if (!modulatorKeys.includes(type)) { logger(`[core] Modulation type ${type} not found. Please use one of 'lfo', 'env', 'bmod'`); return this; } let output = this; - let target = config.target; + let defaultValue = {}; + let defaultSet = 'target' in config; for (const [rawKey, value] of Object.entries(config)) { const key = resolveConfigKey(type, rawKey); - if (key === 'target') continue; // we will set/default it below const valuePat = reify(value); output = output .fmap((v) => (c) => { - if (target == null) { + if (!defaultSet) { // default target to the control set just before this in the chain // e.g. pat.gain(0.5).lfo({..}) will be a gain-LFO - target = Object.keys(v).at(-1); + let control = getControlName(Object.keys(v).at(-1)); + if (modulatorKeys.includes(control)) { + control = `${control}${v[type].length - 1}`; + } + defaultValue = { target: control }; + defaultSet = true; } v[type] ??= []; const t = v[type]; idx ??= t.length; - t[idx] ??= { target }; // set target - t[idx][key] = c; + t[idx] ??= defaultValue; + t[idx][key] = key === 'target' ? getControlName(c) : c; return v; }) .appLeft(valuePat); diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 32d7f0d63..7cbc58b98 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -25,7 +25,7 @@ import { errorLogger, logger } from './logger.mjs'; import { loadBuffer } from './sampler.mjs'; import { getAudioContext } from './audioContext.mjs'; import { SuperdoughAudioController } from './superdoughoutput.mjs'; -import { getSuperdoughControlData } from './superdoughdata.mjs'; +import { getSuperdoughControlTargets } from './superdoughdata.mjs'; export const DEFAULT_MAX_POLYPHONY = 128; const DEFAULT_AUDIO_DEVICE_NAME = 'System Standard'; @@ -396,97 +396,60 @@ function _getNodeParams(node) { return Array.from(params); } -const targetToParamGuess = { - source: 'detune', - lpf: 'frequency', - bpf: 'frequency', - hpf: 'frequency', - distort: 'distort', - gain: 'gain', - vowel: 'frequency', - coarse: 'coarse', - crush: 'crush', - shape: 'shape', - compressor: 'threshold', - pan: 'pan', - phaser: 'rate', - post: 'gain', - delay: 'delayTime', - djf: 'value', - lfo: 'frequency', - env: 'depth', - send: 'depth', -}; - -const controlData = getSuperdoughControlData(); - -// TODO: We would like to use the aliases in `controls` here, but cannot as -// the modules are independent. We may want to inject that method here in situations -// where superdough/core are run in tandem -export let getControlName; -const _getMainName = (control) => getControlName?.(control) ?? control; +const controlTargets = getSuperdoughControlTargets(); +const _stripIndex = (control) => control?.replace(/\d+$/, ''); function _getControlData(control) { - return controlData[_getMainName(control)]; + return controlTargets[_stripIndex(control)]; } -function _getControlValue(control, value, data) { - const main = _getMainName(control); - return Number(value[main] ?? data.default); -} - -function _getControlClamp(data, currentValue) { - const { min, max } = data; - return { min: min - currentValue, max: max - currentValue }; -} - -function _getTargetParams(nodes, target) { - let param; - if (target.includes('.')) { - const split = target.split('.'); - target = split[0]; - param = split[1]; - } else { - const targetWithoutIndex = target.replace(/(\d+)$/, ''); - param = targetToParamGuess[targetWithoutIndex]; +function _getRangeForParam(paramName, targetParams, currentValue) { + if (paramName === 'frequency') { + const liveValue = targetParams?.[0]?.value ?? currentValue ?? 0; + return { min: 20 - liveValue, max: 24000 - liveValue }; } - const targetNodes = nodes[target]; + return { min: undefined, max: undefined }; +} + +function _getTargetParamsForControl(control, nodes, paramOverride) { + const targetInfo = _getControlData(control); + if (!targetInfo) { + errorLogger(`Could not find control data for target '${control}'`, 'superdough'); + return { targetParams: [], paramName: control }; + } + const paramName = paramOverride ?? targetInfo.param; + const nodeKey = nodes[control] ? control : targetInfo.node; + const targetNodes = nodes[nodeKey]; if (!targetNodes) { const keys = Object.keys(nodes); errorLogger( - `Could not connect to target '${target}' — it does not exist. Available targets: ${keys.join(', ')}`, + `Could not connect to target '${nodeKey}' — it does not exist. Available targets: ${keys.join(', ')}`, 'superdough', ); - return []; + return { targetParams: [], paramName }; } const audioParams = []; targetNodes.forEach((targetNode) => { - const targetParam = _getNodeParam(targetNode, param); + const targetParam = _getNodeParam(targetNode, paramName); if (!targetParam) { const available = _getNodeParams(targetNode); errorLogger( - `Could not connect to parameter '${param}' on '${target}'. Available parameters: ${available.join(', ')}`, + `Could not connect to parameter '${paramName}' on '${nodeKey}'. Available parameters: ${available.join(', ')}`, 'superdough', ); return; } audioParams.push(targetParam); }); - return audioParams; -} - -function _getTargetParamsForControl(control, nodes) { - const main = _getMainName(control); - const data = _getControlData(main); - const targetParams = _getTargetParams(nodes, data.param); - return { targetParams, data }; + return { targetParams: audioParams, paramName }; } function connectLFO(idx, params, nodeTracker, value) { - const { rate = 1, sync, cps, cycle, target, depth = 1, depthabs, ...filteredParams } = params; - const { targetParams, data } = _getTargetParamsForControl(target, nodeTracker); - const currentValue = _getControlValue(target, value, data); - const { min, max } = _getControlClamp(data, currentValue); + const { rate = 1, sync, cps, cycle, target = 'lfo', depth = 1, depthabs, param, p, ...filteredParams } = params; + const targetParam = param ?? p; + const { targetParams, paramName } = _getTargetParamsForControl(target, nodeTracker, targetParam); + const currentValue = targetParams[0].value; + const { min, max } = _getRangeForParam(paramName, targetParams, currentValue); const depthValue = depthabs != null ? depthabs : depth * currentValue; const modParams = { ...filteredParams, @@ -504,9 +467,9 @@ function connectLFO(idx, params, nodeTracker, value) { function connectEnvelope(idx, params, nodeTracker, value) { const { target, acurve, dcurve, rcurve, depth = 1, depthabs, ...filteredParams } = params; - const { targetParams, data } = _getTargetParamsForControl(target, nodeTracker); - const currentValue = _getControlValue(target, value, data); - const { min, max } = _getControlClamp(data, currentValue); + const { targetParams, paramName } = _getTargetParamsForControl(target, nodeTracker); + const currentValue = targetParams[0].value; + const { min, max } = _getRangeForParam(paramName, targetParams, currentValue); const depthValue = depthabs != null ? depthabs : depth * currentValue; const envNode = getEnvelope(getAudioContext(), { ...filteredParams, @@ -525,17 +488,17 @@ function connectEnvelope(idx, params, nodeTracker, value) { function connectBusModulator(params, nodeTracker, value) { const ac = getAudioContext(); const { target, depth = 1, depthabs } = params; - const signal = controller.getBus(params.bus).output; + const signal = controller.getBus(params.bus); const dc = new ConstantSourceNode(ac, { offset: params.dc ?? 0 }); dc.start(params.begin); const shifted = dc.connect(gainNode(1)); signal.connect(shifted); - const { targetParams, data } = _getTargetParamsForControl(target, nodeTracker); - const currentValue = _getControlValue(target, value, data); - const { min, max } = _getControlClamp(data, currentValue); + const { targetParams, paramName } = _getTargetParamsForControl(target, nodeTracker); + const currentValue = targetParams[0].value; + const { min, max } = _getRangeForParam(paramName, targetParams, currentValue); const depthValue = depthabs != null ? depthabs : depth * currentValue; const maxAbsDepth = Math.min(Math.abs(min), Math.abs(max)); - const boundedDepth = Math.min(Math.abs(depthValue), maxAbsDepth); + const boundedDepth = Math.min(Math.abs(depthValue), maxAbsDepth) || Math.abs(depthValue); const modulator = shifted.connect(gainNode((Math.sign(depthValue) * boundedDepth) / 0.3)); webAudioTimeout( ac, diff --git a/packages/superdough/superdoughdata.mjs b/packages/superdough/superdoughdata.mjs index fe9bfe46d..cc161b0ee 100644 --- a/packages/superdough/superdoughdata.mjs +++ b/packages/superdough/superdoughdata.mjs @@ -4,92 +4,98 @@ Copyright (C) 2025 Strudel contributors - see . */ -const CONTROL_DATA = { - stretch: { param: 'stretch.pitchFactor', default: 1, min: -4, max: 100 }, - gain: { param: 'gain.gain', default: 0.8, min: 0, max: 10 }, - postgain: { param: 'post.gain', default: 1, min: 0, max: 10 }, - pan: { param: 'pan.pan', min: 0, max: 1 }, - tremolo: { param: 'tremolo.rate', min: 0, max: 40 }, - tremolosync: { param: 'tremolo.sync', min: 0, max: 8 }, - tremolodepth: { param: 'tremolo_gain.gain', default: 1, min: 0, max: 10 }, - tremoloskew: { param: 'tremolo.skew', min: 0, max: 1 }, - tremolophase: { param: 'tremolo.phase', default: 0, min: 0, max: 1 }, - tremoloshape: { param: 'tremolo.shape', min: 0, max: 4 }, +const CONTROL_TARGETS = { + stretch: { node: 'stretch', param: 'pitchFactor' }, + gain: { node: 'gain', param: 'gain' }, + postgain: { node: 'post', param: 'gain' }, + pan: { node: 'pan', param: 'pan' }, + tremolo: { node: 'tremolo', param: 'rate' }, + tremolosync: { node: 'tremolo', param: 'sync' }, + tremolodepth: { node: 'tremolo_gain', param: 'gain' }, + tremoloskew: { node: 'tremolo', param: 'skew' }, + tremolophase: { node: 'tremolo', param: 'phase' }, + tremoloshape: { node: 'tremolo', param: 'shape' }, + + // MODULATORS + lfo: { node: 'lfo', param: 'frequency' }, + env: { node: 'env', param: 'depth' }, + bmod: { node: 'bmod', param: 'depth' }, // LPF - cutoff: { param: 'lpf.frequency', min: 20, max: 24000 }, - resonance: { param: 'lpf.Q', min: 0.1, max: 30 }, - lprate: { param: 'lpf_lfo.rate', min: 0, max: 40 }, - lpsync: { param: 'lpf_lfo.sync', min: 0, max: 8 }, - lpdepth: { param: 'lpf_lfo.depth', min: 20, max: 24000 }, - lpdepthfrequency: { param: 'lpf_lfo.depth', min: 20, max: 24000 }, - lpshape: { param: 'lpf_lfo.shape', min: 0, max: 4 }, - lpdc: { param: 'lpf_lfo.dcoffset', min: -1, max: 1 }, - lpskew: { param: 'lpf_lfo.skew', min: 0, max: 1 }, + cutoff: { node: 'lpf', param: 'frequency' }, + resonance: { node: 'lpf', param: 'Q' }, + lprate: { node: 'lpf_lfo', param: 'rate' }, + lpsync: { node: 'lpf_lfo', param: 'sync' }, + lpdepth: { node: 'lpf_lfo', param: 'depth' }, + lpdepthfrequency: { node: 'lpf_lfo', param: 'depth' }, + lpshape: { node: 'lpf_lfo', param: 'shape' }, + lpdc: { node: 'lpf_lfo', param: 'dcoffset' }, + lpskew: { node: 'lpf_lfo', param: 'skew' }, // HPF - hcutoff: { param: 'hpf.frequency', min: 20, max: 24000 }, - hresonance: { param: 'hpf.Q', min: 0.1, max: 30 }, - hprate: { param: 'hpf_lfo.rate', min: 0, max: 40 }, - hpsync: { param: 'hpf_lfo.sync', min: 0, max: 8 }, - hpdepth: { param: 'hpf_lfo.depth', min: 20, max: 24000 }, - hpdepthfrequency: { param: 'hpf_lfo.depth', min: 20, max: 24000 }, - hpshape: { param: 'hpf_lfo.shape', min: 0, max: 4 }, - hpdc: { param: 'hpf_lfo.dcoffset', min: -1, max: 1 }, - hpskew: { param: 'hpf_lfo.skew', min: 0, max: 1 }, + hcutoff: { node: 'hpf', param: 'frequency' }, + hresonance: { node: 'hpf', param: 'Q' }, + hprate: { node: 'hpf_lfo', param: 'rate' }, + hpsync: { node: 'hpf_lfo', param: 'sync' }, + hpdepth: { node: 'hpf_lfo', param: 'depth' }, + hpdepthfrequency: { node: 'hpf_lfo', param: 'depth' }, + hpshape: { node: 'hpf_lfo', param: 'shape' }, + hpdc: { node: 'hpf_lfo', param: 'dcoffset' }, + hpskew: { node: 'hpf_lfo', param: 'skew' }, // BPF - bandf: { param: 'bpf.frequency', min: 20, max: 24000 }, - bandq: { param: 'bpf.Q', min: 0.1, max: 30 }, - bprate: { param: 'bpf_lfo.rate', min: 0, max: 40 }, - bpsync: { param: 'bpf_lfo.sync', min: 0, max: 8 }, - bpdepth: { param: 'bpf_lfo.depth', min: 20, max: 24000 }, - bpdepthfrequency: { param: 'bpf_lfo.depth', min: 20, max: 24000 }, - bpshape: { param: 'bpf_lfo.shape', min: 0, max: 4 }, - bpdc: { param: 'bpf_lfo.dcoffset', min: -1, max: 1 }, - bpskew: { param: 'bpf_lfo.skew', min: 0, max: 1 }, + bandf: { node: 'bpf', param: 'frequency' }, + bandq: { node: 'bpf', param: 'Q' }, + bprate: { node: 'bpf_lfo', param: 'rate' }, + bpsync: { node: 'bpf_lfo', param: 'sync' }, + bpdepth: { node: 'bpf_lfo', param: 'depth' }, + bpdepthfrequency: { node: 'bpf_lfo', param: 'depth' }, + bpshape: { node: 'bpf_lfo', param: 'shape' }, + bpdc: { node: 'bpf_lfo', param: 'dcoffset' }, + bpskew: { node: 'bpf_lfo', param: 'skew' }, - vowel: { param: 'vowel.frequency', min: 200, max: 4000 }, + vowel: { node: 'vowel', param: 'frequency' }, // DISTORTION - coarse: { param: 'coarse.coarse', min: 1, max: 64 }, - crush: { param: 'crush.crush', min: 1, max: 16 }, - shape: { param: 'shape.shape', min: -1, max: 0.999 }, - shapevol: { param: 'shape.postgain', default: 1, min: 0, max: 1 }, - distort: { param: 'distort.distort', min: 0, max: 5 }, - distortvol: { param: 'distort.postgain', default: 1, min: 0, max: 1 }, + coarse: { node: 'coarse', param: 'coarse' }, + crush: { node: 'crush', param: 'crush' }, + shape: { node: 'shape', param: 'shape' }, + shapevol: { node: 'shape', param: 'postgain' }, + distort: { node: 'distort', param: 'distort' }, + distortvol: { node: 'distort', param: 'postgain' }, // COMPRESSOR - compressor: { param: 'compressor.threshold', default: -3, min: -100, max: 0 }, - compressorRatio: { param: 'compressor.ratio', default: 10, min: 1, max: 20 }, - compressorKnee: { param: 'compressor.knee', default: 10, min: 0, max: 40 }, - compressorAttack: { param: 'compressor.attack', default: 0.005, min: 0, max: 1 }, - compressorRelease: { param: 'compressor.release', default: 0.05, min: 0, max: 2 }, + compressor: { node: 'compressor', param: 'threshold' }, + compressorRatio: { node: 'compressor', param: 'ratio' }, + compressorKnee: { node: 'compressor', param: 'knee' }, + compressorAttack: { node: 'compressor', param: 'attack' }, + compressorRelease: { node: 'compressor', param: 'release' }, // PHASER - phaserrate: { param: 'phaser.rate', min: 0, max: 40 }, - phaserdepth: { param: 'phaser.depth', default: 0.75, min: 0, max: 1 }, - phasersweep: { param: 'phaser.sweep', min: 0, max: 5000 }, - phasercenter: { param: 'phaser.frequency', min: 20, max: 24000 }, + phaserrate: { node: 'phaser', param: 'rate' }, + phaserdepth: { node: 'phaser', param: 'depth' }, + phasersweep: { node: 'phaser', param: 'sweep' }, + phasercenter: { node: 'phaser', param: 'frequency' }, // ORBIT EFFECTS - delaytime: { param: 'delay.delayTime', min: 0, max: 4 }, - delayfeedback: { param: 'delay.feedback', default: 0.5, min: 0, max: 0.98 }, - delaysync: { param: 'delay.sync', default: 3 / 16, min: 0, max: 2 }, - dry: { param: 'dry.gain', min: 0, max: 1 }, - room: { param: 'room.wet', min: 0, max: 1 }, - roomfade: { param: 'room.fade', min: 0, max: 1 }, - roomlp: { param: 'room.lp', min: 20, max: 24000 }, - djf: { param: 'djf.value', min: 0, max: 1 }, - busgain: { param: 'bus.gain', default: 1, min: 0, max: 10 }, + delaytime: { node: 'delay', param: 'delayTime' }, + delayfeedback: { node: 'delay', param: 'feedback' }, + delaysync: { node: 'delay', param: 'sync' }, + dry: { node: 'dry', param: 'gain' }, + room: { node: 'room', param: 'wet' }, + roomfade: { node: 'room', param: 'fade' }, + roomlp: { node: 'room', param: 'lp' }, + djf: { node: 'djf', param: 'value' }, + busgain: { node: 'bus', param: 'gain' }, // SYNTHS - detune: { param: 'source.detune', min: 0, max: 1 }, - wt: { param: 'source.position', min: 0, max: 1 }, - warp: { param: 'source.warp', min: 0, max: 1 }, - freq: { param: 'source.frequency', min: 20, max: 24000 }, + s: { node: 'source', param: 'frequency' }, + detune: { node: 'source', param: 'detune' }, + wt: { node: 'source', param: 'position' }, + warp: { node: 'source', param: 'warp' }, + freq: { node: 'source', param: 'frequency' }, }; -export function getSuperdoughControlData() { - return CONTROL_DATA; +export function getSuperdoughControlTargets() { + return CONTROL_TARGETS; } diff --git a/packages/superdough/synth.mjs b/packages/superdough/synth.mjs index 3686e13d1..35c0bd041 100644 --- a/packages/superdough/synth.mjs +++ b/packages/superdough/synth.mjs @@ -374,7 +374,7 @@ export function registerSynthSounds() { const [attack, decay, sustain, release] = getADSRValues( [value.attack, value.decay, value.sustain, value.release], 'linear', - [0.001, 0.05, 0.6, 0.01], + [0.001, 0.05, 1, 0.01], ); const holdend = begin + value.duration; const end = holdend + release + 0.01; From 4169b764c3ce68fc638d945dc918cd77ae36d6a6 Mon Sep 17 00:00:00 2001 From: Aria Date: Thu, 11 Dec 2025 15:28:48 -0600 Subject: [PATCH 32/73] Simpler control handling --- packages/core/pattern.mjs | 31 +++++++++++++++++++----------- packages/superdough/superdough.mjs | 22 ++++++++++----------- 2 files changed, 31 insertions(+), 22 deletions(-) diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index 7d0e46138..04328ccf7 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -3724,8 +3724,8 @@ const resolveConfigKey = (funcName, key) => { return aliasMap.get(normalized) ?? key; }; -addConfigAlias('lfo', 'target', 't'); -addConfigAlias('lfo', 'param', 'p'); +addConfigAlias('lfo', 'control', 'c'); +addConfigAlias('lfo', 'subControl', 'sc'); addConfigAlias('lfo', 'rate', 'r'); addConfigAlias('lfo', 'depth', 'dep', 'dr'); addConfigAlias('lfo', 'depthabs', 'da'); @@ -3734,7 +3734,8 @@ addConfigAlias('lfo', 'shape', 'sh'); addConfigAlias('lfo', 'skew', 'sk'); addConfigAlias('lfo', 'curve', 'c'); addConfigAlias('lfo', 'sync', 's'); -addConfigAlias('env', 'target', 't'); +addConfigAlias('env', 'control', 'c'); +addConfigAlias('env', 'subControl', 'sc'); addConfigAlias('env', 'attack', 'att', 'a'); addConfigAlias('env', 'decay', 'dec', 'd'); addConfigAlias('env', 'sustain', 'sus', 's'); @@ -3745,7 +3746,8 @@ addConfigAlias('env', 'acurve', 'ac'); addConfigAlias('env', 'dcurve', 'dc'); addConfigAlias('env', 'rcurve', 'rc'); addConfigAlias('bmod', 'orbit', 'o'); -addConfigAlias('bmod', 'target', 't'); +addConfigAlias('bmod', 'control', 'c'); +addConfigAlias('bmod', 'subControl', 'sc'); addConfigAlias('bmod', 'depth', 'dep', 'dr'); addConfigAlias('bmod', 'depthabs', 'da'); addConfigAlias('bmod', 'dc'); @@ -3761,27 +3763,31 @@ Pattern.prototype.modulate = function (type, config, idx) { } let output = this; let defaultValue = {}; - let defaultSet = 'target' in config; + let defaultSet = 'control' in config; for (const [rawKey, value] of Object.entries(config)) { const key = resolveConfigKey(type, rawKey); const valuePat = reify(value); output = output .fmap((v) => (c) => { if (!defaultSet) { - // default target to the control set just before this in the chain + // default control to the control set just before this in the chain // e.g. pat.gain(0.5).lfo({..}) will be a gain-LFO let control = getControlName(Object.keys(v).at(-1)); if (modulatorKeys.includes(control)) { control = `${control}${v[type].length - 1}`; } - defaultValue = { target: control }; + defaultValue = { control }; defaultSet = true; } v[type] ??= []; const t = v[type]; idx ??= t.length; t[idx] ??= defaultValue; - t[idx][key] = key === 'target' ? getControlName(c) : c; + if (key === 'control' || key === 'subControl') { + t[idx][key] = getControlName(c); + } else { + t[idx][key] = c; + } return v; }) .appLeft(valuePat); @@ -3795,7 +3801,8 @@ Pattern.prototype.modulate = function (type, config, idx) { * @name lfo * @memberof Pattern * @param {Object} config LFO configuration. - * @param {string | Pattern} [config.target] Node (and parameter if specified like `lpf.frequency`) to modulate. Aliases: t + * @param {string | Pattern} [config.control] Node to modulate. Aliases: t + * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc, p * @param {number | Pattern} [config.rate] Modulation rate. Aliases: rate, r * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da @@ -3817,7 +3824,8 @@ export const lfo = (config) => pure({}).lfo(config); * @name env * @memberof Pattern * @param {Object} config Envelope configuration. - * @param {string | Pattern} [config.target] Node (and parameter if specified like `lpf.frequency`) to modulate. Aliases: t + * @param {string | Pattern} [config.control] Node to modulate. Aliases: t + * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc, p * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da * @param {number | Pattern} [config.attack] Time to reach depth. Aliases: att, a @@ -3844,7 +3852,8 @@ export const env = (config) => pure({}).env(config); * @memberof Pattern * @param {Object} config Bus modulation configuration. * @param {string | Pattern} [config.bus] Bus to get modulation signal from - * @param {string | Pattern} [config.target] Node (and parameter if specified like `lpf.frequency`) to modulate. Aliases: t + * @param {string | Pattern} [config.control] Node to modulate. Aliases: t + * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc, p * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da * @param {number | Pattern} [config.ratio] Modulation ratio. Aliases: rat diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 7cbc58b98..9efc5b3ef 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -411,14 +411,15 @@ function _getRangeForParam(paramName, targetParams, currentValue) { return { min: undefined, max: undefined }; } -function _getTargetParamsForControl(control, nodes, paramOverride) { - const targetInfo = _getControlData(control); +function _getTargetParamsForControl(control, nodes, subControl) { + const lookupKey = subControl ? `${control}_${subControl}` : control; + const targetInfo = _getControlData(lookupKey) ?? _getControlData(control); if (!targetInfo) { errorLogger(`Could not find control data for target '${control}'`, 'superdough'); return { targetParams: [], paramName: control }; } - const paramName = paramOverride ?? targetInfo.param; - const nodeKey = nodes[control] ? control : targetInfo.node; + const paramName = targetInfo.param; + const nodeKey = nodes[targetInfo.node] ? targetInfo.node : control; const targetNodes = nodes[nodeKey]; if (!targetNodes) { const keys = Object.keys(nodes); @@ -445,9 +446,8 @@ function _getTargetParamsForControl(control, nodes, paramOverride) { } function connectLFO(idx, params, nodeTracker, value) { - const { rate = 1, sync, cps, cycle, target = 'lfo', depth = 1, depthabs, param, p, ...filteredParams } = params; - const targetParam = param ?? p; - const { targetParams, paramName } = _getTargetParamsForControl(target, nodeTracker, targetParam); + const { rate = 1, sync, cps, cycle, control = 'lfo', subControl, depth = 1, depthabs, ...filteredParams } = params; + const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); const currentValue = targetParams[0].value; const { min, max } = _getRangeForParam(paramName, targetParams, currentValue); const depthValue = depthabs != null ? depthabs : depth * currentValue; @@ -466,8 +466,8 @@ function connectLFO(idx, params, nodeTracker, value) { } function connectEnvelope(idx, params, nodeTracker, value) { - const { target, acurve, dcurve, rcurve, depth = 1, depthabs, ...filteredParams } = params; - const { targetParams, paramName } = _getTargetParamsForControl(target, nodeTracker); + const { control, subControl, acurve, dcurve, rcurve, depth = 1, depthabs, ...filteredParams } = params; + const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); const currentValue = targetParams[0].value; const { min, max } = _getRangeForParam(paramName, targetParams, currentValue); const depthValue = depthabs != null ? depthabs : depth * currentValue; @@ -487,13 +487,13 @@ function connectEnvelope(idx, params, nodeTracker, value) { function connectBusModulator(params, nodeTracker, value) { const ac = getAudioContext(); - const { target, depth = 1, depthabs } = params; + const { control, subControl, depth = 1, depthabs } = params; const signal = controller.getBus(params.bus); const dc = new ConstantSourceNode(ac, { offset: params.dc ?? 0 }); dc.start(params.begin); const shifted = dc.connect(gainNode(1)); signal.connect(shifted); - const { targetParams, paramName } = _getTargetParamsForControl(target, nodeTracker); + const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); const currentValue = targetParams[0].value; const { min, max } = _getRangeForParam(paramName, targetParams, currentValue); const depthValue = depthabs != null ? depthabs : depth * currentValue; From 415b6d5f1d41399ca208ded08ce23212662dabc7 Mon Sep 17 00:00:00 2001 From: Aria Date: Thu, 11 Dec 2025 15:48:45 -0600 Subject: [PATCH 33/73] Fix name collision and move modulators into controls to avoid circular import test failure --- packages/core/controls.mjs | 162 ++++++++++++++++++++++++++++++++++++- packages/core/pattern.mjs | 160 ------------------------------------ 2 files changed, 161 insertions(+), 161 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index 808babe69..c4ae8b8de 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -4,7 +4,8 @@ Copyright (C) 2022 Strudel contributors - see . */ -import { Pattern, register, reify } from './pattern.mjs'; +import { logger } from './logger.mjs'; +import { Pattern, pure, register, reify } from './pattern.mjs'; export function createParam(names) { let isMulti = Array.isArray(names); @@ -2808,3 +2809,162 @@ export const scrub = register( }, false, ); + +const configAliases = new Map(); +const addConfigAlias = (funcName, canonical, ...aliases) => { + const lowerFunc = String(funcName).toLowerCase(); + const aliasMap = configAliases.get(lowerFunc) ?? new Map(); + const allKeys = new Set([canonical, ...aliases]); + for (const alias of allKeys) { + aliasMap.set(String(alias).toLowerCase(), canonical); + } + configAliases.set(lowerFunc, aliasMap); +}; + +const resolveConfigKey = (funcName, key) => { + const aliasMap = configAliases.get(String(funcName).toLowerCase()); + if (!aliasMap) return key; + const normalized = String(key).toLowerCase(); + return aliasMap.get(normalized) ?? key; +}; + +addConfigAlias('lfo', 'control', 'c'); +addConfigAlias('lfo', 'subControl', 'sc'); +addConfigAlias('lfo', 'rate', 'r'); +addConfigAlias('lfo', 'depth', 'dep', 'dr'); +addConfigAlias('lfo', 'depthabs', 'da'); +addConfigAlias('lfo', 'dcoffset', 'dc'); +addConfigAlias('lfo', 'shape', 'sh'); +addConfigAlias('lfo', 'skew', 'sk'); +addConfigAlias('lfo', 'curve'); +addConfigAlias('lfo', 'sync', 's'); +addConfigAlias('env', 'control', 'c'); +addConfigAlias('env', 'subControl', 'sc'); +addConfigAlias('env', 'attack', 'att', 'a'); +addConfigAlias('env', 'decay', 'dec', 'd'); +addConfigAlias('env', 'sustain', 'sus', 's'); +addConfigAlias('env', 'release', 'rel', 'r'); +addConfigAlias('env', 'depth', 'dep', 'dr'); +addConfigAlias('env', 'depthabs', 'da'); +addConfigAlias('env', 'acurve', 'ac'); +addConfigAlias('env', 'dcurve', 'dc'); +addConfigAlias('env', 'rcurve', 'rc'); +addConfigAlias('bmod', 'orbit', 'o'); +addConfigAlias('bmod', 'control', 'c'); +addConfigAlias('bmod', 'subControl', 'sc'); +addConfigAlias('bmod', 'depth', 'dep', 'dr'); +addConfigAlias('bmod', 'depthabs', 'da'); +addConfigAlias('bmod', 'dc'); + +Pattern.prototype.modulate = function (type, config, idx) { + if (config == null || typeof config !== 'object') { + return this; + } + const modulatorKeys = ['lfo', 'env', 'bmod']; + if (!modulatorKeys.includes(type)) { + logger(`[core] Modulation type ${type} not found. Please use one of 'lfo', 'env', 'bmod'`); + return this; + } + let output = this; + let defaultValue = {}; + let defaultSet = 'control' in config; + for (const [rawKey, value] of Object.entries(config)) { + const key = resolveConfigKey(type, rawKey); + const valuePat = reify(value); + output = output + .fmap((v) => (c) => { + if (!defaultSet) { + // default control to the control set just before this in the chain + // e.g. pat.gain(0.5).lfo({..}) will be a gain-LFO + let control = getControlName(Object.keys(v).at(-1)); + if (modulatorKeys.includes(control)) { + control = `${control}${v[control].length - 1}`; + } + defaultValue = { control }; + defaultSet = true; + } + v[type] ??= []; + const t = v[type]; + idx ??= t.length; + t[idx] ??= defaultValue; + if (key === 'control' || key === 'subControl') { + t[idx][key] = getControlName(c); + } else { + t[idx][key] = c; + } + return v; + }) + .appLeft(valuePat); + } + return output; +}; + +/** + * Configures an LFO. Can be called in sequence like pat.lfo(...).lfo(...) to set up multiple LFOs + * + * @name lfo + * @memberof Pattern + * @param {Object} config LFO configuration. + * @param {string | Pattern} [config.control] Node to modulate. Aliases: t + * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc, p + * @param {number | Pattern} [config.rate] Modulation rate. Aliases: rate, r + * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr + * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da + * @param {number | Pattern} [config.dcoffset] DC offset / bias for the waveform. Aliases: dc + * @param {number | Pattern} [config.shape] Waveform shape index. Aliases: sh + * @param {number | Pattern} [config.skew] Waveform skew amount. Aliases: sk + * @param {number | Pattern} [config.curve] Exponential curve amount. Aliases: c + * @param {number | Pattern} [config.sync] Tempo-synced modulation rate. Aliases: s + * @returns Pattern + */ +Pattern.prototype.lfo = function (config, idx) { + return this.modulate('lfo', config, idx); +}; +export const lfo = (config) => pure({}).lfo(config); + +/** + * Configures an envelope. Can be called in sequence like pat.env(...).env(...) to set up multiple envelopes + * + * @name env + * @memberof Pattern + * @param {Object} config Envelope configuration. + * @param {string | Pattern} [config.control] Node to modulate. Aliases: t + * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc, p + * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr + * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da + * @param {number | Pattern} [config.attack] Time to reach depth. Aliases: att, a + * @param {number | Pattern} [config.decay] Time to reach sustain. Aliases: dec, d + * @param {number | Pattern} [config.sustain] Sustain depth. Aliases: sus, s + * @param {number | Pattern} [config.release] Time to return to nominal value. Aliases: rel, r + * @param {number | Pattern} [config.acurve] Snappiness of attack curve (-1 = relaxed, 1 = snappy). Aliases: ac + * @param {number | Pattern} [config.dcurve] Snappiness of decay curve (-1 = relaxed, 1 = snappy). Aliases: dc + * @param {number | Pattern} [config.rcurve] Snappiness of release curve (-1 = relaxed, 1 = snappy). Aliases: rc + * @returns Pattern + */ +Pattern.prototype.env = function (config, idx) { + return this.modulate('env', config, idx); +}; +export const env = (config) => pure({}).env(config); + +/** + * Modulates with the output from a given `bus`. + * Can be called in sequence like pat.bmod(...).bmod(...) to set up multiple modulators + * + * Send to an audio bus with `otherPat.bus(..)`. + * + * @name bmod + * @memberof Pattern + * @param {Object} config Bus modulation configuration. + * @param {string | Pattern} [config.bus] Bus to get modulation signal from + * @param {string | Pattern} [config.control] Node to modulate. Aliases: t + * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc, p + * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr + * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da + * @param {number | Pattern} [config.ratio] Modulation ratio. Aliases: rat + * @param {number | Pattern} [config.dc] DC offset prior to application + * @returns Pattern + */ +Pattern.prototype.bmod = function (config, idx) { + return this.modulate('bmod', config, idx); +}; +export const bmod = (config) => pure({}).bmod(config); diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index 04328ccf7..c2e5ca1bc 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -26,7 +26,6 @@ import { } from './util.mjs'; import drawLine from './drawLine.mjs'; import { errorLogger, logger } from './logger.mjs'; -import { getControlName } from './controls.mjs'; let stringParser; @@ -3705,162 +3704,3 @@ Pattern.prototype.phases = function (list) { export const phases = (list) => { return _ensureListPattern(list).as('phases'); }; - -const configAliases = new Map(); -const addConfigAlias = (funcName, canonical, ...aliases) => { - const lowerFunc = String(funcName).toLowerCase(); - const aliasMap = configAliases.get(lowerFunc) ?? new Map(); - const allKeys = new Set([canonical, ...aliases]); - for (const alias of allKeys) { - aliasMap.set(String(alias).toLowerCase(), canonical); - } - configAliases.set(lowerFunc, aliasMap); -}; - -const resolveConfigKey = (funcName, key) => { - const aliasMap = configAliases.get(String(funcName).toLowerCase()); - if (!aliasMap) return key; - const normalized = String(key).toLowerCase(); - return aliasMap.get(normalized) ?? key; -}; - -addConfigAlias('lfo', 'control', 'c'); -addConfigAlias('lfo', 'subControl', 'sc'); -addConfigAlias('lfo', 'rate', 'r'); -addConfigAlias('lfo', 'depth', 'dep', 'dr'); -addConfigAlias('lfo', 'depthabs', 'da'); -addConfigAlias('lfo', 'dcoffset', 'dc'); -addConfigAlias('lfo', 'shape', 'sh'); -addConfigAlias('lfo', 'skew', 'sk'); -addConfigAlias('lfo', 'curve', 'c'); -addConfigAlias('lfo', 'sync', 's'); -addConfigAlias('env', 'control', 'c'); -addConfigAlias('env', 'subControl', 'sc'); -addConfigAlias('env', 'attack', 'att', 'a'); -addConfigAlias('env', 'decay', 'dec', 'd'); -addConfigAlias('env', 'sustain', 'sus', 's'); -addConfigAlias('env', 'release', 'rel', 'r'); -addConfigAlias('env', 'depth', 'dep', 'dr'); -addConfigAlias('env', 'depthabs', 'da'); -addConfigAlias('env', 'acurve', 'ac'); -addConfigAlias('env', 'dcurve', 'dc'); -addConfigAlias('env', 'rcurve', 'rc'); -addConfigAlias('bmod', 'orbit', 'o'); -addConfigAlias('bmod', 'control', 'c'); -addConfigAlias('bmod', 'subControl', 'sc'); -addConfigAlias('bmod', 'depth', 'dep', 'dr'); -addConfigAlias('bmod', 'depthabs', 'da'); -addConfigAlias('bmod', 'dc'); - -Pattern.prototype.modulate = function (type, config, idx) { - if (config == null || typeof config !== 'object') { - return this; - } - const modulatorKeys = ['lfo', 'env', 'bmod']; - if (!modulatorKeys.includes(type)) { - logger(`[core] Modulation type ${type} not found. Please use one of 'lfo', 'env', 'bmod'`); - return this; - } - let output = this; - let defaultValue = {}; - let defaultSet = 'control' in config; - for (const [rawKey, value] of Object.entries(config)) { - const key = resolveConfigKey(type, rawKey); - const valuePat = reify(value); - output = output - .fmap((v) => (c) => { - if (!defaultSet) { - // default control to the control set just before this in the chain - // e.g. pat.gain(0.5).lfo({..}) will be a gain-LFO - let control = getControlName(Object.keys(v).at(-1)); - if (modulatorKeys.includes(control)) { - control = `${control}${v[type].length - 1}`; - } - defaultValue = { control }; - defaultSet = true; - } - v[type] ??= []; - const t = v[type]; - idx ??= t.length; - t[idx] ??= defaultValue; - if (key === 'control' || key === 'subControl') { - t[idx][key] = getControlName(c); - } else { - t[idx][key] = c; - } - return v; - }) - .appLeft(valuePat); - } - return output; -}; - -/** - * Configures an LFO. Can be called in sequence like pat.lfo(...).lfo(...) to set up multiple LFOs - * - * @name lfo - * @memberof Pattern - * @param {Object} config LFO configuration. - * @param {string | Pattern} [config.control] Node to modulate. Aliases: t - * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc, p - * @param {number | Pattern} [config.rate] Modulation rate. Aliases: rate, r - * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr - * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da - * @param {number | Pattern} [config.dcoffset] DC offset / bias for the waveform. Aliases: dc - * @param {number | Pattern} [config.shape] Waveform shape index. Aliases: sh - * @param {number | Pattern} [config.skew] Waveform skew amount. Aliases: sk - * @param {number | Pattern} [config.curve] Exponential curve amount. Aliases: c - * @param {number | Pattern} [config.sync] Tempo-synced modulation rate. Aliases: s - * @returns Pattern - */ -Pattern.prototype.lfo = function (config, idx) { - return this.modulate('lfo', config, idx); -}; -export const lfo = (config) => pure({}).lfo(config); - -/** - * Configures an envelope. Can be called in sequence like pat.env(...).env(...) to set up multiple envelopes - * - * @name env - * @memberof Pattern - * @param {Object} config Envelope configuration. - * @param {string | Pattern} [config.control] Node to modulate. Aliases: t - * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc, p - * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr - * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da - * @param {number | Pattern} [config.attack] Time to reach depth. Aliases: att, a - * @param {number | Pattern} [config.decay] Time to reach sustain. Aliases: dec, d - * @param {number | Pattern} [config.sustain] Sustain depth. Aliases: sus, s - * @param {number | Pattern} [config.release] Time to return to nominal value. Aliases: rel, r - * @param {number | Pattern} [config.acurve] Snappiness of attack curve (-1 = relaxed, 1 = snappy). Aliases: ac - * @param {number | Pattern} [config.dcurve] Snappiness of decay curve (-1 = relaxed, 1 = snappy). Aliases: dc - * @param {number | Pattern} [config.rcurve] Snappiness of release curve (-1 = relaxed, 1 = snappy). Aliases: rc - * @returns Pattern - */ -Pattern.prototype.env = function (config, idx) { - return this.modulate('env', config, idx); -}; -export const env = (config) => pure({}).env(config); - -/** - * Modulates with the output from a given `bus`. - * Can be called in sequence like pat.bmod(...).bmod(...) to set up multiple modulators - * - * Send to an audio bus with `otherPat.bus(..)`. - * - * @name bmod - * @memberof Pattern - * @param {Object} config Bus modulation configuration. - * @param {string | Pattern} [config.bus] Bus to get modulation signal from - * @param {string | Pattern} [config.control] Node to modulate. Aliases: t - * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc, p - * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr - * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da - * @param {number | Pattern} [config.ratio] Modulation ratio. Aliases: rat - * @param {number | Pattern} [config.dc] DC offset prior to application - * @returns Pattern - */ -Pattern.prototype.bmod = function (config, idx) { - return this.modulate('bmod', config, idx); -}; -export const bmod = (config) => pure({}).bmod(config); From 8baecf78b9d62cb7fabee425d1f709fc6b5a5a8b Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 13 Dec 2025 11:37:37 -0600 Subject: [PATCH 34/73] Add note --- packages/superdough/superdoughdata.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/superdough/superdoughdata.mjs b/packages/superdough/superdoughdata.mjs index cc161b0ee..a273021d0 100644 --- a/packages/superdough/superdoughdata.mjs +++ b/packages/superdough/superdoughdata.mjs @@ -94,6 +94,7 @@ const CONTROL_TARGETS = { wt: { node: 'source', param: 'position' }, warp: { node: 'source', param: 'warp' }, freq: { node: 'source', param: 'frequency' }, + note: { node: 'source', param: 'frequency' }, }; export function getSuperdoughControlTargets() { From dc5f6827f9a72f7f760f8e29d4c2b6948c463647 Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 13 Dec 2025 14:50:27 -0600 Subject: [PATCH 35/73] Change names, cleanup --- packages/core/controls.mjs | 80 +++++++++++++++++------------- packages/superdough/superdough.mjs | 2 +- 2 files changed, 47 insertions(+), 35 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index c4ae8b8de..9052d64c5 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -2810,51 +2810,63 @@ export const scrub = register( false, ); -const configAliases = new Map(); -const addConfigAlias = (funcName, canonical, ...aliases) => { +const subControlAliases = new Map(); +const registerSubControl = (funcName, main, ...aliases) => { const lowerFunc = String(funcName).toLowerCase(); - const aliasMap = configAliases.get(lowerFunc) ?? new Map(); - const allKeys = new Set([canonical, ...aliases]); + const aliasMap = subControlAliases.get(lowerFunc) ?? new Map(); + const allKeys = new Set([main, ...aliases]); for (const alias of allKeys) { - aliasMap.set(String(alias).toLowerCase(), canonical); + aliasMap.set(String(alias).toLowerCase(), main); + } + subControlAliases.set(lowerFunc, aliasMap); +}; + +const registerSubControls = (funcName, aliasGroups = []) => { + for (const [main, ...aliases] of aliasGroups) { + registerSubControl(funcName, main, ...aliases); } - configAliases.set(lowerFunc, aliasMap); }; const resolveConfigKey = (funcName, key) => { - const aliasMap = configAliases.get(String(funcName).toLowerCase()); + const aliasMap = subControlAliases.get(String(funcName).toLowerCase()); if (!aliasMap) return key; const normalized = String(key).toLowerCase(); return aliasMap.get(normalized) ?? key; }; -addConfigAlias('lfo', 'control', 'c'); -addConfigAlias('lfo', 'subControl', 'sc'); -addConfigAlias('lfo', 'rate', 'r'); -addConfigAlias('lfo', 'depth', 'dep', 'dr'); -addConfigAlias('lfo', 'depthabs', 'da'); -addConfigAlias('lfo', 'dcoffset', 'dc'); -addConfigAlias('lfo', 'shape', 'sh'); -addConfigAlias('lfo', 'skew', 'sk'); -addConfigAlias('lfo', 'curve'); -addConfigAlias('lfo', 'sync', 's'); -addConfigAlias('env', 'control', 'c'); -addConfigAlias('env', 'subControl', 'sc'); -addConfigAlias('env', 'attack', 'att', 'a'); -addConfigAlias('env', 'decay', 'dec', 'd'); -addConfigAlias('env', 'sustain', 'sus', 's'); -addConfigAlias('env', 'release', 'rel', 'r'); -addConfigAlias('env', 'depth', 'dep', 'dr'); -addConfigAlias('env', 'depthabs', 'da'); -addConfigAlias('env', 'acurve', 'ac'); -addConfigAlias('env', 'dcurve', 'dc'); -addConfigAlias('env', 'rcurve', 'rc'); -addConfigAlias('bmod', 'orbit', 'o'); -addConfigAlias('bmod', 'control', 'c'); -addConfigAlias('bmod', 'subControl', 'sc'); -addConfigAlias('bmod', 'depth', 'dep', 'dr'); -addConfigAlias('bmod', 'depthabs', 'da'); -addConfigAlias('bmod', 'dc'); +registerSubControls('lfo', [ + ['control', 'c'], + ['subControl', 'sc'], + ['rate', 'r'], + ['depth', 'dep', 'dr'], + ['depthabs', 'da'], + ['dcoffset', 'dc'], + ['shape', 'sh'], + ['skew', 'sk'], + ['curve'], + ['sync', 's'], +]); +registerSubControls('env', [ + ['control', 'c'], + ['subControl', 'sc'], + ['attack', 'att', 'a'], + ['decay', 'dec', 'd'], + ['sustain', 'sus', 's'], + ['release', 'rel', 'r'], + ['depth', 'dep', 'dr'], + ['depthabs', 'da'], + ['acurve', 'ac'], + ['dcurve', 'dc'], + ['rcurve', 'rc'], +]); +registerSubControls('bmod', [ + ['bus', 'b'], + ['control', 'c'], + ['subControl', 'sc'], + ['depth', 'dep', 'dr'], + ['depthabs', 'da'], + ['dc'], +]); Pattern.prototype.modulate = function (type, config, idx) { if (config == null || typeof config !== 'object') { diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 9efc5b3ef..86f54f13b 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -485,7 +485,7 @@ function connectEnvelope(idx, params, nodeTracker, value) { return envNode; } -function connectBusModulator(params, nodeTracker, value) { +function connectBusModulator(params, nodeTracker) { const ac = getAudioContext(); const { control, subControl, depth = 1, depthabs } = params; const signal = controller.getBus(params.bus); From ef2ee0969ade3aa331616c1b37e5daf069edcd33 Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 13 Dec 2025 14:59:14 -0600 Subject: [PATCH 36/73] Restore old lfo to avoid unifying right now --- packages/superdough/helpers.mjs | 24 +++++++++++++++++++++++- packages/superdough/superdough.mjs | 10 ++++------ 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/packages/superdough/helpers.mjs b/packages/superdough/helpers.mjs index 19064954b..3b704caea 100644 --- a/packages/superdough/helpers.mjs +++ b/packages/superdough/helpers.mjs @@ -109,7 +109,29 @@ export function getEnvelope(audioContext, properties = {}) { return getWorklet(audioContext, 'envelope-processor', properties); } -export function getLfo(audioContext, properties = {}) { +export function getLfo(audioContext, begin, end, properties = {}) { + const { shape = 0, ...props } = properties; + const { dcoffset = -0.5, depth = 1 } = properties; + const lfoprops = { + frequency: 1, + depth, + skew: 0.5, + phaseoffset: 0, + time: begin, + begin, + end, + shape: getModulationShapeInput(shape), + dcoffset, + min: dcoffset * depth, + max: dcoffset * depth + depth, + curve: 1, + ...props, + }; + + return getWorklet(audioContext, 'lfo-processor', lfoprops); +} + +export function getCustomLfo(audioContext, properties = {}) { // Extract some params we need for deriving other params const { shape = 0, ...props } = properties; const lfoprops = { diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 6fcc9cec7..04e383c4d 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -443,7 +443,7 @@ function _getTargetParamsForControl(control, nodes, subControl) { return { targetParams: audioParams, paramName }; } -function connectLFO(idx, params, nodeTracker, value) { +function connectLFO(idx, params, nodeTracker) { const { rate = 1, sync, cps, cycle, control = 'lfo', subControl, depth = 1, depthabs, ...filteredParams } = params; const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); const currentValue = targetParams[0].value; @@ -457,13 +457,13 @@ function connectLFO(idx, params, nodeTracker, value) { min, max, }; - const lfoNode = getLfo(getAudioContext(), modParams); + const lfoNode = getCustomLfo(getAudioContext(), modParams); nodeTracker[`lfo${idx}`] = [lfoNode]; targetParams.forEach((t) => lfoNode.connect(t)); return lfoNode; } -function connectEnvelope(idx, params, nodeTracker, value) { +function connectEnvelope(idx, params, nodeTracker) { const { control, subControl, acurve, dcurve, rcurve, depth = 1, depthabs, ...filteredParams } = params; const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); const currentValue = targetParams[0].value; @@ -997,7 +997,6 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) end: endWithRelease, }, nodes, - value, ); audioNodes.push(lfo); } @@ -1012,14 +1011,13 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) end: endWithRelease, }, nodes, - value, ); audioNodes.push(env); } } if (value.bmod) { for (const p of value.bmod) { - const { toCleanup } = connectBusModulator({ ...p, begin: t, end: endWithRelease }, nodes, value); + const { toCleanup } = connectBusModulator({ ...p, begin: t, end: endWithRelease }, nodes); audioNodes.push(...toCleanup); } } From 11e3da0552d34c230dcb0682392afe55cf928c84 Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 13 Dec 2025 15:08:48 -0600 Subject: [PATCH 37/73] Parity with other LFO (sync and dcoffset) --- packages/superdough/helpers.mjs | 3 ++- packages/superdough/superdough.mjs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/superdough/helpers.mjs b/packages/superdough/helpers.mjs index 3b704caea..b13f40498 100644 --- a/packages/superdough/helpers.mjs +++ b/packages/superdough/helpers.mjs @@ -132,10 +132,11 @@ export function getLfo(audioContext, begin, end, properties = {}) { } export function getCustomLfo(audioContext, properties = {}) { - // Extract some params we need for deriving other params + // Default / process certain params const { shape = 0, ...props } = properties; const lfoprops = { shape: getModulationShapeInput(shape), + dcoffset: -0.5, ...props, }; return getWorklet(audioContext, 'lfo-processor', lfoprops); diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 04e383c4d..ba84d6910 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -451,7 +451,7 @@ function connectLFO(idx, params, nodeTracker) { const depthValue = depthabs != null ? depthabs : depth * currentValue; const modParams = { ...filteredParams, - frequency: sync !== undefined ? sync / cps : rate, + frequency: sync !== undefined ? sync * cps : rate, time: cycle / cps, depth: depthValue, min, From 4b08dd8447e24216ae1caa4a317362f7f0103867 Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 13 Dec 2025 15:20:51 -0600 Subject: [PATCH 38/73] Unify lfo functions --- packages/superdough/helpers.mjs | 53 ++++++++++++++++-------------- packages/superdough/superdough.mjs | 2 +- 2 files changed, 30 insertions(+), 25 deletions(-) diff --git a/packages/superdough/helpers.mjs b/packages/superdough/helpers.mjs index b13f40498..7b9becdf2 100644 --- a/packages/superdough/helpers.mjs +++ b/packages/superdough/helpers.mjs @@ -109,36 +109,39 @@ export function getEnvelope(audioContext, properties = {}) { return getWorklet(audioContext, 'envelope-processor', properties); } -export function getLfo(audioContext, begin, end, properties = {}) { - const { shape = 0, ...props } = properties; - const { dcoffset = -0.5, depth = 1 } = properties; +export function getLfo(audioContext, properties = {}) { + const { + shape = 0, + begin = 0, + end = 0, + time, + depth = 1, + dcoffset = -0.5, + frequency = 1, + skew = 0.5, + phaseoffset = 0, + curve = 1, + min, + max, + ...props + } = properties; + const lfoprops = { - frequency: 1, - depth, - skew: 0.5, - phaseoffset: 0, - time: begin, begin, end, - shape: getModulationShapeInput(shape), + time: time ?? begin, + depth, dcoffset, - min: dcoffset * depth, - max: dcoffset * depth + depth, - curve: 1, - ...props, - }; - - return getWorklet(audioContext, 'lfo-processor', lfoprops); -} - -export function getCustomLfo(audioContext, properties = {}) { - // Default / process certain params - const { shape = 0, ...props } = properties; - const lfoprops = { + frequency, + skew, + phaseoffset, + curve, shape: getModulationShapeInput(shape), - dcoffset: -0.5, + min: min ?? dcoffset * depth, + max: max ?? dcoffset * depth + depth, ...props, }; + return getWorklet(audioContext, 'lfo-processor', lfoprops); } @@ -177,7 +180,9 @@ export function getParamLfo(audioContext, param, start, end, lfoValues) { } let lfo; if (depth) { - lfo = getLfo(audioContext, start, end, { + lfo = getLfo(audioContext, { + begin: start, + end, depth, dcoffset, ...getLfoInputs, diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index ba84d6910..5ea04f89c 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -457,7 +457,7 @@ function connectLFO(idx, params, nodeTracker) { min, max, }; - const lfoNode = getCustomLfo(getAudioContext(), modParams); + const lfoNode = getLfo(getAudioContext(), modParams); nodeTracker[`lfo${idx}`] = [lfoNode]; targetParams.forEach((t) => lfoNode.connect(t)); return lfoNode; From bae5571df0547d1901a3b035b02d13ff7f86e9b3 Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 13 Dec 2025 15:32:27 -0600 Subject: [PATCH 39/73] Cleanup --- packages/core/controls.mjs | 28 ++++++++++++-------------- packages/superdough/superdoughdata.mjs | 1 + 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index d8fdd51dd..0cb78f05e 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -2814,27 +2814,25 @@ export const scrub = register( ); const subControlAliases = new Map(); -const registerSubControl = (funcName, main, ...aliases) => { - const lowerFunc = String(funcName).toLowerCase(); - const aliasMap = subControlAliases.get(lowerFunc) ?? new Map(); - const allKeys = new Set([main, ...aliases]); +const registerSubControl = (control, subControl, ...aliases) => { + const aliasMap = subControlAliases.get(control) ?? new Map(); + const allKeys = new Set([subControl, ...aliases]); for (const alias of allKeys) { - aliasMap.set(String(alias).toLowerCase(), main); + aliasMap.set(String(alias).toLowerCase(), subControl); } - subControlAliases.set(lowerFunc, aliasMap); + subControlAliases.set(control, aliasMap); }; -const registerSubControls = (funcName, aliasGroups = []) => { - for (const [main, ...aliases] of aliasGroups) { - registerSubControl(funcName, main, ...aliases); +const registerSubControls = (control, subControlAliases = []) => { + for (const [subControl, ...aliases] of subControlAliases) { + registerSubControl(control, subControl, ...aliases); } }; -const resolveConfigKey = (funcName, key) => { - const aliasMap = subControlAliases.get(String(funcName).toLowerCase()); - if (!aliasMap) return key; - const normalized = String(key).toLowerCase(); - return aliasMap.get(normalized) ?? key; +const getMainSubcontrolName = (control, subKey) => { + const aliasMap = subControlAliases.get(control); + if (!aliasMap) return subKey; + return aliasMap.get(String(subKey).toLowerCase()) ?? subKey; }; registerSubControls('lfo', [ @@ -2884,7 +2882,7 @@ Pattern.prototype.modulate = function (type, config, idx) { let defaultValue = {}; let defaultSet = 'control' in config; for (const [rawKey, value] of Object.entries(config)) { - const key = resolveConfigKey(type, rawKey); + const key = getMainSubcontrolName(type, rawKey); const valuePat = reify(value); output = output .fmap((v) => (c) => { diff --git a/packages/superdough/superdoughdata.mjs b/packages/superdough/superdoughdata.mjs index a273021d0..d3b3d40b5 100644 --- a/packages/superdough/superdoughdata.mjs +++ b/packages/superdough/superdoughdata.mjs @@ -4,6 +4,7 @@ Copyright (C) 2025 Strudel contributors - see . */ +// Mapping from control name to webaudio node and parameter const CONTROL_TARGETS = { stretch: { node: 'stretch', param: 'pitchFactor' }, gain: { node: 'gain', param: 'gain' }, From 29f7f5c1f83d00d680fa2916178cc21e3de43b47 Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 13 Dec 2025 16:06:28 -0600 Subject: [PATCH 40/73] Allow lfos to modulate other lfos without clamping --- packages/superdough/superdough.mjs | 15 ++++++++------- packages/superdough/superdoughdata.mjs | 10 ++++++++++ 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 5ea04f89c..977812646 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -401,10 +401,11 @@ function _getControlData(control) { return controlTargets[_stripIndex(control)]; } -function _getRangeForParam(paramName, targetParams, currentValue) { - if (paramName === 'frequency') { - const liveValue = targetParams?.[0]?.value ?? currentValue ?? 0; - return { min: 20 - liveValue, max: 24000 - liveValue }; +function _getRangeForParam(paramName, currentValue, control) { + // For our normal oscillators / filters we want to clamp the frequency to a reasonable range + // For LFOs we allow it to be modulated freely + if (paramName === 'frequency' || control?.startsWith?.('lfo')) { + return { min: 20 - currentValue, max: 24000 - currentValue }; } return { min: undefined, max: undefined }; } @@ -447,7 +448,7 @@ function connectLFO(idx, params, nodeTracker) { const { rate = 1, sync, cps, cycle, control = 'lfo', subControl, depth = 1, depthabs, ...filteredParams } = params; const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); const currentValue = targetParams[0].value; - const { min, max } = _getRangeForParam(paramName, targetParams, currentValue); + const { min, max } = _getRangeForParam(paramName, currentValue, control); const depthValue = depthabs != null ? depthabs : depth * currentValue; const modParams = { ...filteredParams, @@ -467,7 +468,7 @@ function connectEnvelope(idx, params, nodeTracker) { const { control, subControl, acurve, dcurve, rcurve, depth = 1, depthabs, ...filteredParams } = params; const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); const currentValue = targetParams[0].value; - const { min, max } = _getRangeForParam(paramName, targetParams, currentValue); + const { min, max } = _getRangeForParam(paramName, currentValue, control); const depthValue = depthabs != null ? depthabs : depth * currentValue; const envNode = getEnvelope(getAudioContext(), { ...filteredParams, @@ -493,7 +494,7 @@ function connectBusModulator(params, nodeTracker) { signal.connect(shifted); const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); const currentValue = targetParams[0].value; - const { min, max } = _getRangeForParam(paramName, targetParams, currentValue); + const { min, max } = _getRangeForParam(paramName, currentValue, control); const depthValue = depthabs != null ? depthabs : depth * currentValue; const maxAbsDepth = Math.min(Math.abs(min), Math.abs(max)); const boundedDepth = Math.min(Math.abs(depthValue), maxAbsDepth) || Math.abs(depthValue); diff --git a/packages/superdough/superdoughdata.mjs b/packages/superdough/superdoughdata.mjs index d3b3d40b5..6b577889d 100644 --- a/packages/superdough/superdoughdata.mjs +++ b/packages/superdough/superdoughdata.mjs @@ -19,8 +19,18 @@ const CONTROL_TARGETS = { // MODULATORS lfo: { node: 'lfo', param: 'frequency' }, + lfo_rate: { node: 'lfo', param: 'frequency' }, + lfo_sync: { node: 'lfo', param: 'frequency' }, + lfo_depth: { node: 'lfo', param: 'depth' }, + lfo_depthabs: { node: 'lfo', param: 'depth' }, env: { node: 'env', param: 'depth' }, + env_attack: { node: 'env', param: 'attack' }, + env_decay: { node: 'env', param: 'decay' }, + env_sustain: { node: 'env', param: 'sustain' }, + env_release: { node: 'env', param: 'release' }, bmod: { node: 'bmod', param: 'depth' }, + bmod_depth: { node: 'bmod', param: 'depth' }, + bmod_depthabs: { node: 'bmod', param: 'depth' }, // LPF cutoff: { node: 'lpf', param: 'frequency' }, From dec037bed52f8ffa76bc36c57a14276b6981c137 Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 13 Dec 2025 16:23:47 -0600 Subject: [PATCH 41/73] Bus fix --- packages/superdough/superdoughdata.mjs | 1 + packages/superdough/synth.mjs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/superdough/superdoughdata.mjs b/packages/superdough/superdoughdata.mjs index 6b577889d..cab829752 100644 --- a/packages/superdough/superdoughdata.mjs +++ b/packages/superdough/superdoughdata.mjs @@ -74,6 +74,7 @@ const CONTROL_TARGETS = { shapevol: { node: 'shape', param: 'postgain' }, distort: { node: 'distort', param: 'distort' }, distortvol: { node: 'distort', param: 'postgain' }, + distorttype: { node: 'distort', param: 'distort' }, // COMPRESSOR compressor: { node: 'compressor', param: 'threshold' }, diff --git a/packages/superdough/synth.mjs b/packages/superdough/synth.mjs index 39868589e..40e62f86f 100644 --- a/packages/superdough/synth.mjs +++ b/packages/superdough/synth.mjs @@ -380,7 +380,7 @@ export function registerSynthSounds() { const holdend = begin + value.duration; const end = holdend + release + 0.01; const bus = getSuperdoughAudioController().getBus(value.n ?? 0); - const envGain = bus.connect(gainNode(1)); + const envGain = bus.connect(gainNode(0)); getParamADSR(envGain.gain, attack, decay, sustain, release, 0, 1, begin, holdend, 'linear'); const timeoutNode = webAudioTimeout( ac, From c598059dc77ee46eccf334467efc60adac2a3a60 Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 13 Dec 2025 16:26:50 -0600 Subject: [PATCH 42/73] Clean up old code --- packages/superdough/superdough.mjs | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 977812646..9312ccdae 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -381,19 +381,6 @@ function _getNodeParam(node, name) { return undefined; } -function _getNodeParams(node) { - const params = new Set(); - // Worklet case - if (node?.parameters) { - node.parameters.forEach((_v, k) => params.add(k)); - } - // Guesses based on common parameters - ['gain', 'frequency', 'detune', 'Q', 'pan', 'playbackRate', 'delayTime'].forEach((k) => { - if (node?.[k] instanceof AudioParam) params.add(k); - }); - return Array.from(params); -} - const controlTargets = getSuperdoughControlTargets(); const _stripIndex = (control) => control?.replace(/\d+$/, ''); @@ -431,14 +418,6 @@ function _getTargetParamsForControl(control, nodes, subControl) { const audioParams = []; targetNodes.forEach((targetNode) => { const targetParam = _getNodeParam(targetNode, paramName); - if (!targetParam) { - const available = _getNodeParams(targetNode); - errorLogger( - `Could not connect to parameter '${paramName}' on '${nodeKey}'. Available parameters: ${available.join(', ')}`, - 'superdough', - ); - return; - } audioParams.push(targetParam); }); return { targetParams: audioParams, paramName }; From 63de46ae96ecc8069285ad64f77489fb230547f8 Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 13 Dec 2025 16:44:36 -0600 Subject: [PATCH 43/73] Update docstrings --- packages/core/controls.mjs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index 0cb78f05e..826174d8f 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -2924,8 +2924,8 @@ Pattern.prototype.modulate = function (type, config, idx) { * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da * @param {number | Pattern} [config.dcoffset] DC offset / bias for the waveform. Aliases: dc - * @param {number | Pattern} [config.shape] Waveform shape index. Aliases: sh - * @param {number | Pattern} [config.skew] Waveform skew amount. Aliases: sk + * @param {number | Pattern} [config.shape] Shape index. Aliases: sh + * @param {number | Pattern} [config.skew] Skew amount. Aliases: sk * @param {number | Pattern} [config.curve] Exponential curve amount. Aliases: c * @param {number | Pattern} [config.sync] Tempo-synced modulation rate. Aliases: s * @returns Pattern @@ -2973,7 +2973,6 @@ export const env = (config) => pure({}).env(config); * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc, p * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da - * @param {number | Pattern} [config.ratio] Modulation ratio. Aliases: rat * @param {number | Pattern} [config.dc] DC offset prior to application * @returns Pattern */ From 18b3c66eb83948c0f1008ebddba75862b558f6cf Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 13 Dec 2025 17:15:06 -0600 Subject: [PATCH 44/73] Clean up error messages --- packages/superdough/superdough.mjs | 13 ++++++++----- packages/superdough/worklets.mjs | 16 +++++++++++----- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 9312ccdae..8f79e5b24 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -401,7 +401,7 @@ function _getTargetParamsForControl(control, nodes, subControl) { const lookupKey = subControl ? `${control}_${subControl}` : control; const targetInfo = _getControlData(lookupKey) ?? _getControlData(control); if (!targetInfo) { - errorLogger(`Could not find control data for target '${control}'`, 'superdough'); + errorLogger(new Error(`Could not find control data for target '${control}'`), 'superdough'); return { targetParams: [], paramName: control }; } const paramName = targetInfo.param; @@ -410,7 +410,7 @@ function _getTargetParamsForControl(control, nodes, subControl) { if (!targetNodes) { const keys = Object.keys(nodes); errorLogger( - `Could not connect to target '${nodeKey}' — it does not exist. Available targets: ${keys.join(', ')}`, + new Error(`Could not connect to target '${nodeKey}' — it does not exist. Available targets: ${keys.join(', ')}`), 'superdough', ); return { targetParams: [], paramName }; @@ -426,6 +426,7 @@ function _getTargetParamsForControl(control, nodes, subControl) { function connectLFO(idx, params, nodeTracker) { const { rate = 1, sync, cps, cycle, control = 'lfo', subControl, depth = 1, depthabs, ...filteredParams } = params; const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); + if (!targetParams.length) return; const currentValue = targetParams[0].value; const { min, max } = _getRangeForParam(paramName, currentValue, control); const depthValue = depthabs != null ? depthabs : depth * currentValue; @@ -446,6 +447,7 @@ function connectLFO(idx, params, nodeTracker) { function connectEnvelope(idx, params, nodeTracker) { const { control, subControl, acurve, dcurve, rcurve, depth = 1, depthabs, ...filteredParams } = params; const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); + if (!targetParams.length) return; const currentValue = targetParams[0].value; const { min, max } = _getRangeForParam(paramName, currentValue, control); const depthValue = depthabs != null ? depthabs : depth * currentValue; @@ -466,12 +468,13 @@ function connectEnvelope(idx, params, nodeTracker) { function connectBusModulator(params, nodeTracker) { const ac = getAudioContext(); const { control, subControl, depth = 1, depthabs } = params; + const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); + if (!targetParams.length) return { toCleanup: [] }; const signal = controller.getBus(params.bus); const dc = new ConstantSourceNode(ac, { offset: params.dc ?? 0 }); dc.start(params.begin); const shifted = dc.connect(gainNode(1)); signal.connect(shifted); - const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); const currentValue = targetParams[0].value; const { min, max } = _getRangeForParam(paramName, currentValue, control); const depthValue = depthabs != null ? depthabs : depth * currentValue; @@ -978,7 +981,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) }, nodes, ); - audioNodes.push(lfo); + lfo && audioNodes.push(lfo); } } if (value.env) { @@ -992,7 +995,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) }, nodes, ); - audioNodes.push(env); + env && audioNodes.push(env); } } if (value.bmod) { diff --git a/packages/superdough/worklets.mjs b/packages/superdough/worklets.mjs index 321c8b425..4523e9e89 100644 --- a/packages/superdough/worklets.mjs +++ b/packages/superdough/worklets.mjs @@ -1013,9 +1013,15 @@ class EnvelopeProcessor extends AudioWorkletProcessor { } process(_inputs, outputs, params) { + const begin = params['begin'][0]; + const end = params['end'][0]; + if (currentTime >= end) { + return false; + } + if (currentTime <= begin) { + return true; + } const out = outputs[0][0]; - if (!out) return true; - const begin = pv(params.begin, 0); const retrigger = pv(params.retrigger, 0) >= 0.5; // convert to bool if (begin !== this.beginTime && (this.state === 0 || retrigger)) { // triggered @@ -1034,8 +1040,8 @@ class EnvelopeProcessor extends AudioWorkletProcessor { const dCurve = pv(params.decayCurve, i); const rCurve = pv(params.releaseCurve, i); const depth = pv(params.depth, i); - const clampMin = pv(params.min, i); - const clampMax = pv(params.max, i); + const min = pv(params.min, i); + const max = pv(params.max, i); const states = [ { time: Number.POSITIVE_INFINITY, start: 0, target: 0 }, // idle { time: attack, start: this.attackStart, target: 1, curve: aCurve }, @@ -1049,7 +1055,7 @@ class EnvelopeProcessor extends AudioWorkletProcessor { this.state = (this.state + 1) % states.length; time = states[this.state].time; } - const clamped = clamp(this.val * depth, Math.min(clampMin, clampMax), Math.max(clampMin, clampMax)); + const clamped = clamp(this.val * depth, min, max); out[i] = clamped; } return true; From a9752fb2a45104f7101c1b9e3dd653a3dd5fab8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?John=20Bj=C3=B6rk?= Date: Sat, 6 Dec 2025 19:54:33 +0100 Subject: [PATCH 45/73] Exposing Vim from codemirror-vim Docs for adding keybindings Only expose Vim from keybindings --- packages/codemirror/index.mjs | 1 + packages/codemirror/keybindings.mjs | 2 ++ website/src/pages/technical-manual/vim.mdx | 21 +++++++++++++++++++++ 3 files changed, 24 insertions(+) diff --git a/packages/codemirror/index.mjs b/packages/codemirror/index.mjs index 3a5f2a23c..2d5b3de21 100644 --- a/packages/codemirror/index.mjs +++ b/packages/codemirror/index.mjs @@ -4,3 +4,4 @@ export * from './flash.mjs'; export * from './slider.mjs'; export * from './themes.mjs'; export * from './widget.mjs'; +export { Vim } from './keybindings.mjs'; diff --git a/packages/codemirror/keybindings.mjs b/packages/codemirror/keybindings.mjs index d92e9c959..24437b7e1 100644 --- a/packages/codemirror/keybindings.mjs +++ b/packages/codemirror/keybindings.mjs @@ -131,6 +131,8 @@ const keymaps = { vscode: vscodeExtension, }; +export { Vim } from '@replit/codemirror-vim'; + export function keybindings(name) { const active = keymaps[name]; const extensions = active ? [Prec.high(active())] : []; diff --git a/website/src/pages/technical-manual/vim.mdx b/website/src/pages/technical-manual/vim.mdx index fa53aa550..6ec41d4a2 100644 --- a/website/src/pages/technical-manual/vim.mdx +++ b/website/src/pages/technical-manual/vim.mdx @@ -35,3 +35,24 @@ Troubleshooting - If :w logs but evaluation doesn't apply, ensure Vim keybindings are active and try again. You can also use Ctrl+Enter as a fallback. - For :q / gc, ensure focus is inside the editor. If an error occurs, reload the page to reset editor state and try again. + +## Adding custom keybindings + +To add custom keybindings the `Vim` object can be used (either from within a pattern or in a prebake script) + +Example: + +```javascript +// Map 'jk' to Escape in normal mode +Vim.map('jk', '', 'insert'); +// Map 'U' to :w (Evaluate the current code) +Vim.map('U', ':w', 'normal'); +// Map 'Q' to :q — Stop/pause playback +Vim.map('Q', ':q', 'normal'); +// Map 'J' to find next '$' (jump to next label) +Vim.map('J', '/\\$', 'normal'); +// Map 'K' to find previous '$' (jump to previous label) +Vim.map('K', '?\\$', 'normal'); +``` + +For more information on how to use the `Vim` object see [CodeMirror Vim](https://github.com/replit/codemirror-vim) From c7a2c2bb9c37a4a334747330260048742c93d683 Mon Sep 17 00:00:00 2001 From: Wuzzy Date: Sun, 7 Dec 2025 00:02:24 +0100 Subject: [PATCH 46/73] Say that @license should use SPDX identifier --- website/src/pages/learn/metadata.mdx | 34 +++++++++++++++------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/website/src/pages/learn/metadata.mdx b/website/src/pages/learn/metadata.mdx index 61db16f0e..c94257925 100644 --- a/website/src/pages/learn/metadata.mdx +++ b/website/src/pages/learn/metadata.mdx @@ -11,9 +11,9 @@ import { JsDoc } from '../../docs/JsDoc'; You can optionally add some music metadata in your Strudel code, by using tags in code comments: ```js -// @title Hey Hoo -// @by Sam Tagada -// @license CC BY-NC-SA +// @title My Cool Song +// @by John Doe +// @license CC-BY-SA-4.0 ``` Like other comments, those are ignored by Strudel, but it can be used by other tools to retrieve some information about the music. @@ -24,22 +24,22 @@ You can also use comment blocks: ```js /* -@title Hey Hoo -@by Sam Tagada -@license CC BY-NC-SA +@title My Cool Song +@by John Doe +@license CC-BY-SA-4.0 */ ``` Or define multiple tags in one line: ```js -// @title Hey Hoo @by Sam Tagada @license CC BY-NC-SA +// @title My Cool Song @by John Doe @license CC-BY-SA-4.0 ``` The `title` tag has an alternative syntax using quotes (must be defined at the very begining): ```js -// "Hey Hoo" @by Sam Tagada +// "My Cool Song" @by John Doe ``` ## Tags list @@ -48,20 +48,22 @@ Available tags are: - `@title`: music title - `@by`: music author(s), separated by comma, eventually followed with a link in `<>` (ex: `@by John Doe `) -- `@license`: music license(s), e.g. CC BY-NC-SA. Unsure? [Choose a creative commons license here](https://creativecommons.org/choose/) +- `@license`: music license(s), separated by comma. Each license should be specified by using the correct identifier in the [https://spdx.org/licenses/](SPDX License List). Example: CC-BY-SA-4.0. Unsure? [Choose a Creative Commons license here](https://creativecommons.org/choose/). - `@details`: some additional information about the music -- `@url`: web page(s) related to the music (git repo, soundcloud link, etc.) -- `@genre`: music genre(s) (pop, jazz, etc) +- `@url`: web page(s) related to the music (git repository, Soundcloud link, etc.) +- `@genre`: music genre(s) (pop, jazz, etc.) - `@album`: music album name +Note to tool authors: _Never_ trust that a song has filled those fields with syntactically correct values; make sure your software is robust enough it doesn't break if it encounters bad values + ## Multiple values Some of them accepts several values, using the comma or new line separator, or duplicating the tag: ```js /* -@by Sam Tagada - Jimmy +@by John Doe + Jane Doe @genre pop, jazz @url https://example.com @url https://example.org @@ -72,11 +74,11 @@ You can also add optional prefixes and use tags where you want: ```js /* -song @by Sam Tagada -samples @by Jimmy +song @by John Doe +samples @by Jane Doe */ ... -note("a3 c#4 e4 a4") // @by Sandy +note("a3 c#4 e4 a4") // @by Sandy Sue ``` ## Multiline From d349d2a0cd0efcce383e63ed414e3a009f872b06 Mon Sep 17 00:00:00 2001 From: JesCoding Date: Wed, 24 Dec 2025 10:38:21 +0100 Subject: [PATCH 47/73] Fix transpilation example to have same mini-notation This was introduced in https://codeberg.org/uzu/strudel/commit/66f8ca72c1b364f72f25b8cff041cac13b380432 --- website/src/pages/technical-manual/repl.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/pages/technical-manual/repl.mdx b/website/src/pages/technical-manual/repl.mdx index f74a4fb8b..d8a22cf55 100644 --- a/website/src/pages/technical-manual/repl.mdx +++ b/website/src/pages/technical-manual/repl.mdx @@ -41,7 +41,7 @@ note("c3 [e3 g3]*2") is transpiled to: ```strudel -note(m('c3 [e3 g3]', 5)) +note(m('c3 [e3 g3]*2', 5)) ``` Here, the string is wrapped in `m`, which will create a pattern from a mini-notation string. As the second parameter, it gets passed source code location of the string, which enables highlighting active events later. From e286ab2830f5681e1c92ad9f6bfd6913becbf3c5 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Sun, 28 Dec 2025 13:10:37 +0100 Subject: [PATCH 48/73] no default samples for now + add doughsamples to scope --- website/src/components/Dough/dough-repl.mjs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/website/src/components/Dough/dough-repl.mjs b/website/src/components/Dough/dough-repl.mjs index ef28617e8..c8b47a3e8 100644 --- a/website/src/components/Dough/dough-repl.mjs +++ b/website/src/components/Dough/dough-repl.mjs @@ -6,6 +6,8 @@ import { transpiler } from '@strudel/transpiler'; //const doughBaseUrl = doughUrl.split('/').slice(0, -1).join('/') + '/'; const doughBaseUrl = 'https://unpkg.com/dough-synth@0.1.9/'; +Object.assign(globalThis, { doughsamples }); + export class DoughRepl { pattern; latency = 0.1; @@ -81,7 +83,9 @@ export class DoughRepl { this.origin = undefined; } prebake() { - return Promise.all([doughsamples('github:eddyflux/crate')]); + return Promise.all([ + // doughsamples('github:eddyflux/crate') + ]); } // tbd: move this to dough-synth get time() { From 53e49952d8942b7d78393e8626ec32a5808006a2 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Sun, 28 Dec 2025 13:10:57 +0100 Subject: [PATCH 49/73] persist code in hash --- website/src/components/Dough/dough-mirror.mjs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/website/src/components/Dough/dough-mirror.mjs b/website/src/components/Dough/dough-mirror.mjs index 5cdfeb3f6..2626787ed 100644 --- a/website/src/components/Dough/dough-mirror.mjs +++ b/website/src/components/Dough/dough-mirror.mjs @@ -9,12 +9,23 @@ import { updateMiniLocations, highlightMiniLocations, } from '@strudel/codemirror'; -import { evalScope } from '@strudel/core'; +import { evalScope, hash2code } from '@strudel/core'; import { Framer } from '@strudel/draw'; import { persistentAtom } from '@nanostores/persistent'; import { DoughRepl } from './dough-repl.mjs'; -const initialCode = '$: note("c a f e")'; +let initialCode = '$: note("c a f e")'; +if (typeof window !== 'undefined') { + try { + const codeParam = window.location.href.split('#')[1] || ''; + if (codeParam) { + initialCode = hash2code(codeParam); + } + } catch (err) { + console.error('could not init code from url'); + } +} + export const code = persistentAtom('vanilla-repl-code', initialCode, { encode: JSON.stringify, decode: JSON.parse, @@ -64,6 +75,7 @@ export class DoughMirror { this.flash(); await this.prebaked; const { miniLocations } = await this.repl.evaluate(this.code); + window.location.hash = '#' + code2hash(this.code); updateMiniLocations(this.editor, miniLocations); } stop() { From 125eece2237d7fd361f731156a6f47d165ec2486 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Sun, 28 Dec 2025 13:20:22 +0100 Subject: [PATCH 50/73] fix: import --- website/src/components/Dough/dough-mirror.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/components/Dough/dough-mirror.mjs b/website/src/components/Dough/dough-mirror.mjs index 2626787ed..b7794d2db 100644 --- a/website/src/components/Dough/dough-mirror.mjs +++ b/website/src/components/Dough/dough-mirror.mjs @@ -9,7 +9,7 @@ import { updateMiniLocations, highlightMiniLocations, } from '@strudel/codemirror'; -import { evalScope, hash2code } from '@strudel/core'; +import { evalScope, hash2code, code2hash } from '@strudel/core'; import { Framer } from '@strudel/draw'; import { persistentAtom } from '@nanostores/persistent'; import { DoughRepl } from './dough-repl.mjs'; From 300a1bbfd51dc763e0adc20ff0a6755a33fe6ff2 Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Sun, 28 Dec 2025 14:07:27 +0100 Subject: [PATCH 51/73] fix: actually load code from url --- website/src/components/Dough/dough-mirror.mjs | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/website/src/components/Dough/dough-mirror.mjs b/website/src/components/Dough/dough-mirror.mjs index b7794d2db..7784402e9 100644 --- a/website/src/components/Dough/dough-mirror.mjs +++ b/website/src/components/Dough/dough-mirror.mjs @@ -15,22 +15,24 @@ import { persistentAtom } from '@nanostores/persistent'; import { DoughRepl } from './dough-repl.mjs'; let initialCode = '$: note("c a f e")'; -if (typeof window !== 'undefined') { - try { - const codeParam = window.location.href.split('#')[1] || ''; - if (codeParam) { - initialCode = hash2code(codeParam); - } - } catch (err) { - console.error('could not init code from url'); - } -} export const code = persistentAtom('vanilla-repl-code', initialCode, { encode: JSON.stringify, decode: JSON.parse, }); +if (typeof window !== 'undefined') { + try { + const codeParam = window.location.href.split('#')[1] || ''; + if (codeParam) { + const codeFromHash = hash2code(codeParam); + code.set(codeFromHash); + } + } catch (err) { + console.error('could not init code from url'); + } +} + export class DoughMirror { constructor(options) { const { root, initialCode = code.get(), bgFill = true } = options; From 30fe5b47e38ec768c34186cfd348e3b891c83f4b Mon Sep 17 00:00:00 2001 From: Felix Roos Date: Sun, 28 Dec 2025 22:42:42 +0100 Subject: [PATCH 52/73] hotfix: fix scope and friends #1847 --- packages/superdough/superdough.mjs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 4fd6164dc..e98a2aa22 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -359,7 +359,9 @@ export let analysers = {}, analysersData = {}; export function getAnalyserById(id, fftSize = 1024, smoothingTimeConstant = 0.5) { - if (!analysers[id] || analysers[id].audioContext != getAudioContext()) { + // below commented out branch is hotfixing https://codeberg.org/uzu/strudel/issues/1847 + // might cause conflicts with exporting... + if (!analysers[id] /* || analysers[id].audioContext != getAudioContext() */) { // make sure this doesn't happen too often as it piles up garbage const analyserNode = getAudioContext().createAnalyser(); analyserNode.fftSize = fftSize; From 48f6a41683daf95b412ce99979b5ce933286349e Mon Sep 17 00:00:00 2001 From: Aria Date: Sun, 28 Dec 2025 20:13:15 -0500 Subject: [PATCH 53/73] Extend to FM, vibrato, etc --- packages/core/controls.mjs | 15 +++----- packages/soundfonts/fontloader.mjs | 6 +-- packages/superdough/helpers.mjs | 6 ++- packages/superdough/sampler.mjs | 6 +-- packages/superdough/superdough.mjs | 33 ++++++++-------- packages/superdough/superdoughdata.mjs | 37 ++++++++++++++++++ packages/superdough/synth.mjs | 52 +++++++++++++------------- packages/superdough/wavetable.mjs | 19 +++++++--- packages/superdough/zzfx.mjs | 2 +- 9 files changed, 112 insertions(+), 64 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index 826174d8f..5cc53de60 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -2870,36 +2870,33 @@ registerSubControls('bmod', [ ]); Pattern.prototype.modulate = function (type, config, idx) { - if (config == null || typeof config !== 'object') { - return this; - } + config ??= { control: undefined }; const modulatorKeys = ['lfo', 'env', 'bmod']; if (!modulatorKeys.includes(type)) { logger(`[core] Modulation type ${type} not found. Please use one of 'lfo', 'env', 'bmod'`); return this; } let output = this; - let defaultValue = {}; - let defaultSet = 'control' in config; + let defaultValue = undefined; for (const [rawKey, value] of Object.entries(config)) { const key = getMainSubcontrolName(type, rawKey); const valuePat = reify(value); output = output .fmap((v) => (c) => { - if (!defaultSet) { + if (defaultValue === undefined) { // default control to the control set just before this in the chain // e.g. pat.gain(0.5).lfo({..}) will be a gain-LFO let control = getControlName(Object.keys(v).at(-1)); if (modulatorKeys.includes(control)) { control = `${control}${v[control].length - 1}`; } - defaultValue = { control }; - defaultSet = true; + defaultValue = control; } v[type] ??= []; const t = v[type]; idx ??= t.length; - t[idx] ??= defaultValue; + t[idx] ??= { control: defaultValue }; + if (c === undefined) return v; if (key === 'control' || key === 'subControl') { t[idx][key] = getControlName(c); } else { diff --git a/packages/soundfonts/fontloader.mjs b/packages/soundfonts/fontloader.mjs index 81b9eb508..b4ae59828 100644 --- a/packages/soundfonts/fontloader.mjs +++ b/packages/soundfonts/fontloader.mjs @@ -166,7 +166,7 @@ export function registerSoundfonts() { let envEnd = holdEnd + release + 0.01; // vibrato - let vibratoOscillator = getVibratoOscillator(bufferSource.detune, value, time); + const vibratoHandle = getVibratoOscillator(bufferSource.detune, value, time); // pitch envelope getPitchEnvelope(bufferSource.detune, value, time, holdEnd); @@ -174,10 +174,10 @@ export function registerSoundfonts() { const stop = (releaseTime) => {}; onceEnded(bufferSource, () => { releaseAudioNode(bufferSource); - releaseAudioNode(vibratoOscillator); + vibratoHandle?.stop(); onended(); }); - return { node, stop, source: bufferSource }; + return { node, stop, nodes: { source: [bufferSource], ...vibratoHandle?.nodes } }; }, { type: 'soundfont', prebake: true, fonts }, ); diff --git a/packages/superdough/helpers.mjs b/packages/superdough/helpers.mjs index fc7734ea3..8bd8b067b 100644 --- a/packages/superdough/helpers.mjs +++ b/packages/superdough/helpers.mjs @@ -351,7 +351,7 @@ export function getVibratoOscillator(param, value, t) { releaseAudioNode(vibratoOscillator); }); vibratoOscillator.start(t); - return vibratoOscillator; + return { stop: (t) => vibratoOscillator.stop(t), nodes: { vib: [vibratoOscillator], vib_gain: [gain] } }; } } @@ -407,6 +407,7 @@ export function applyFM(param, value, begin) { const ac = getAudioContext(); const toStop = []; // fm oscillators we will expose `stop` for const fms = {}; + const nodes = {}; // Matrix for (let i = 1; i <= 8; i++) { for (let j = 0; j <= 8; j++) { @@ -457,11 +458,13 @@ export function applyFM(param, value, begin) { output = osc.connect(envGain); } fms[idx] = { input: osc.frequency, output, freq, osc, toCleanup }; + nodes[`fm_${idx}`] = [osc]; } const { input, output, freq, osc, toCleanup } = fms[idx]; const g = gainNode(amt * freq); io.push(isMod ? output.connect(g) : input); cleanupOnEnd(osc, [...toCleanup, g]); + nodes[`fm_${idx}_gain`] = [g]; } if (!io[1]) { logger( @@ -474,6 +477,7 @@ export function applyFM(param, value, begin) { } } return { + nodes, stop: (t) => toStop.forEach((m) => m?.stop(t)), }; } diff --git a/packages/superdough/sampler.mjs b/packages/superdough/sampler.mjs index 55f081568..819de3c78 100644 --- a/packages/superdough/sampler.mjs +++ b/packages/superdough/sampler.mjs @@ -301,7 +301,7 @@ export async function onTriggerSample(t, value, onended, bank, resolveUrl) { } // vibrato - let vibratoOscillator = getVibratoOscillator(bufferSource.detune, value, t); + const vibratoHandle = getVibratoOscillator(bufferSource.detune, value, t); const time = t + nudge; bufferSource.start(time, offset); @@ -324,7 +324,7 @@ export async function onTriggerSample(t, value, onended, bank, resolveUrl) { node.connect(out); onceEnded(bufferSource, function () { releaseAudioNode(bufferSource); - releaseAudioNode(vibratoOscillator); + vibratoHandle?.stop(); releaseAudioNode(node); releaseAudioNode(out); onended(); @@ -334,7 +334,7 @@ export async function onTriggerSample(t, value, onended, bank, resolveUrl) { const stop = (endTime) => { bufferSource.stop(endTime); }; - const handle = { node: out, source: bufferSource, stop }; + const handle = { node: out, nodes: { source: [bufferSource], ...vibratoHandle?.nodes }, stop }; // cut groups if (cut !== undefined) { diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index fd198c788..8bca5b30c 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -532,7 +532,7 @@ function mapChannelNumbers(channels) { } export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) => { - const nodes = {}; + let nodes = {}; // new: t is always expected to be the absolute target onset time const ac = getAudioContext(); const audioController = getSuperdoughAudioController(); @@ -690,7 +690,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) if (soundHandle) { sourceNode = soundHandle.node; activeSoundSources.set(chainID, new WeakRef(soundHandle)); // allow GC - nodes['source'] = [soundHandle.source]; + nodes = { ...nodes, ...soundHandle.nodes }; } } else { throw new Error(`sound ${s} not found! Is it loaded?`); @@ -709,22 +709,23 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) chain.push(sourceNode); stretch !== undefined && chain.push(getWorklet(ac, 'phase-vocoder-processor', { pitchFactor: stretch })); - transient !== undefined && - chain.push( - getWorklet( - ac, - 'transient-processor', - {}, - { - processorOptions: { - attack: transient, - sustain: transsustain, - begin: t, - end: endWithRelease, - }, + if (transient !== undefined) { + const transProcessor = getWorklet( + ac, + 'transient-processor', + {}, + { + processorOptions: { + attack: transient, + sustain: transsustain, + begin: t, + end: endWithRelease, }, - ), + }, ); + chain.push(transProcessor); + nodes['transient'] = transProcessor; + } // gain stage const initialGain = gainNode(gain); diff --git a/packages/superdough/superdoughdata.mjs b/packages/superdough/superdoughdata.mjs index cab829752..2ae03101a 100644 --- a/packages/superdough/superdoughdata.mjs +++ b/packages/superdough/superdoughdata.mjs @@ -23,6 +23,9 @@ const CONTROL_TARGETS = { lfo_sync: { node: 'lfo', param: 'frequency' }, lfo_depth: { node: 'lfo', param: 'depth' }, lfo_depthabs: { node: 'lfo', param: 'depth' }, + lfo_skew: { node: 'lfo', param: 'skew' }, + lfo_curve: { node: 'lfo', param: 'curve' }, + lfo_dcoffset: { node: 'lfo', param: 'dcoffset' }, env: { node: 'env', param: 'depth' }, env_attack: { node: 'env', param: 'attack' }, env_decay: { node: 'env', param: 'decay' }, @@ -107,6 +110,40 @@ const CONTROL_TARGETS = { warp: { node: 'source', param: 'warp' }, freq: { node: 'source', param: 'frequency' }, note: { node: 'source', param: 'frequency' }, + wtdc: { node: 'wt_lfo', param: 'dc' }, + wtskew: { node: 'wt_lfo', param: 'skew' }, + wtrate: { node: 'wt_lfo', param: 'frequency' }, + wtsync: { node: 'wt_lfo', param: 'frequency' }, + wtdepth: { node: 'wt_lfo', param: 'depth' }, + warpdc: { node: 'warp_lfo', param: 'dc' }, + warpskew: { node: 'warp_lfo', param: 'skew' }, + warprate: { node: 'warp_lfo', param: 'frequency' }, + warpsync: { node: 'warp_lfo', param: 'frequency' }, + warpdepth: { node: 'warp_lfo', param: 'depth' }, + fmi: { node: 'fm_1_gain', param: 'gain' }, + fmi2: { node: 'fm_2_gain', param: 'gain' }, + fmi3: { node: 'fm_3_gain', param: 'gain' }, + fmi4: { node: 'fm_4_gain', param: 'gain' }, + fmi5: { node: 'fm_5_gain', param: 'gain' }, + fmi6: { node: 'fm_6_gain', param: 'gain' }, + fmi7: { node: 'fm_7_gain', param: 'gain' }, + fmi8: { node: 'fm_8_gain', param: 'gain' }, + fmh: { node: 'fm_1', param: 'frequency' }, + fmh2: { node: 'fm_2', param: 'frequency' }, + fmh3: { node: 'fm_3', param: 'frequency' }, + fmh4: { node: 'fm_4', param: 'frequency' }, + fmh5: { node: 'fm_5', param: 'frequency' }, + fmh6: { node: 'fm_6', param: 'frequency' }, + fmh7: { node: 'fm_7', param: 'frequency' }, + fmh8: { node: 'fm_8', param: 'frequency' }, + pw: { node: 'source', param: 'pulsewidth' }, + pwrate: { node: 'pw_lfo', param: 'frequency' }, + pwsweep: { node: 'pw_lfo', param: 'depth' }, + vib: { node: 'vib_gain', param: 'gain' }, + vibmod: { node: 'vib', param: 'frequency' }, + byteBeatStartTime: { node: 'source', param: 'byteBeatStartTime' }, + spread: { node: 'source', param: 'panspread' }, + transient: { node: 'transient', param: 'attack' }, }; export function getSuperdoughControlTargets() { diff --git a/packages/superdough/synth.mjs b/packages/superdough/synth.mjs index 40e62f86f..d20692729 100644 --- a/packages/superdough/synth.mjs +++ b/packages/superdough/synth.mjs @@ -52,17 +52,17 @@ export function registerSynthSounds() { // turn down const g = gainNode(0.3); - let sound = getOscillator(s, t, value, () => { + const sound = getOscillator(s, t, value, () => { releaseAudioNode(g); onended(); }); - let { node: o, stop, triggerRelease } = sound; + const { node: o, nodes, stop, triggerRelease } = sound; const { duration } = value; const envGain = gainNode(1); - let node = o.connect(g).connect(envGain); + const node = o.connect(g).connect(envGain); const holdEnd = t + duration; getParamADSR(node.gain, attack, decay, sustain, release, 0, 1, t, holdEnd, 'linear'); const envEnd = holdEnd + release + 0.01; @@ -70,7 +70,7 @@ export function registerSynthSounds() { stop(envEnd); return { node, - source: o, + nodes, stop: (endTime) => { stop(endTime); }, @@ -140,7 +140,7 @@ export function registerSynthSounds() { return { node, - source: o, + nodes: { source: [o] }, stop: (endTime) => { o.stop(endTime); }, @@ -185,8 +185,8 @@ export function registerSynthSounds() { const gainAdjustment = 1 / Math.sqrt(voices); getPitchEnvelope(o.parameters.get('detune'), value, begin, holdend); - const vibratoOscillator = getVibratoOscillator(o.parameters.get('detune'), value, begin); - const fm = applyFM(o.parameters.get('frequency'), value, begin); + const vibratoHandle = getVibratoOscillator(o.parameters.get('detune'), value, begin); + const fmHandle = applyFM(o.parameters.get('frequency'), value, begin); let envGain = gainNode(1); envGain = o.connect(envGain); @@ -197,8 +197,8 @@ export function registerSynthSounds() { () => { releaseAudioNode(o); onended(); - fm?.stop(); - vibratoOscillator?.stop(); + fmHandle?.stop(); + vibratoHandle?.stop(); }, begin, end, @@ -206,7 +206,7 @@ export function registerSynthSounds() { return { node: envGain, - source: o, + nodes: { source: [o], ...fmHandle?.nodes, ...vibratoHandle?.nodes }, stop: (time) => { timeoutNode.stop(time); }, @@ -333,25 +333,25 @@ export function registerSynthSounds() { ); getPitchEnvelope(o.parameters.get('detune'), value, begin, holdend); - const vibratoOscillator = getVibratoOscillator(o.parameters.get('detune'), value, begin); - const fm = applyFM(o.parameters.get('frequency'), value, begin); + const vibratoHandle = getVibratoOscillator(o.parameters.get('detune'), value, begin); + const fmHandle = applyFM(o.parameters.get('frequency'), value, begin); let envGain = gainNode(1); envGain = o.connect(envGain); getParamADSR(envGain.gain, attack, decay, sustain, release, 0, 1, begin, holdend, 'linear'); - let lfo; + let pw_lfo; if (pwsweep != 0) { - lfo = getLfo(ac, { frequency: pwrate, depth: pwsweep, begin, end }); - lfo.connect(o.parameters.get('pulsewidth')); + pw_lfo = getLfo(ac, { frequency: pwrate, depth: pwsweep, begin, end }); + pw_lfo.connect(o.parameters.get('pulsewidth')); } let timeoutNode = webAudioTimeout( ac, () => { releaseAudioNode(o); - releaseAudioNode(lfo); + releaseAudioNode(pw_lfo); onended(); - fm?.stop(); - vibratoOscillator?.stop(); + fmHandle?.stop(); + vibratoHandle?.stop(); }, begin, end, @@ -359,7 +359,7 @@ export function registerSynthSounds() { return { node: envGain, - source: o, + nodes: { source: [o], pw_lfo: [pw_lfo], ...fmHandle?.nodes, ...vibratoHandle?.nodes }, stop: (time) => { timeoutNode.stop(time); }, @@ -394,7 +394,7 @@ export function registerSynthSounds() { return { node: envGain, - source: bus, + nodes: { source: [bus] }, stop: (time) => { timeoutNode.stop(time); }, @@ -440,7 +440,7 @@ export function registerSynthSounds() { stop(envEnd); return { node, - source: o, + nodes: { source: [o] }, stop: (endTime) => { stop(endTime); }, @@ -520,11 +520,11 @@ export function getOscillator(s, t, value, onended) { // set frequency o.frequency.value = getFrequencyFromValue(value); - let vibratoOscillator = getVibratoOscillator(o.detune, value, t); + const vibratoHandle = getVibratoOscillator(o.detune, value, t); // pitch envelope getPitchEnvelope(o.detune, value, t, t + duration); - const fmModulator = applyFM(o.frequency, value, t); + const fmHandle = applyFM(o.frequency, value, t); let noiseMix; if (noise) { @@ -541,10 +541,10 @@ export function getOscillator(s, t, value, onended) { return { node: noiseMix?.node || o, - source: o, + nodes: { source: [o], ...vibratoHandle?.nodes, ...fmHandle?.nodes }, stop: (time) => { - fmModulator.stop(time); - vibratoOscillator?.stop(time); + fmHandle.stop(time); + vibratoHandle?.stop(time); noiseMix?.stop(time); o.stop(time); }, diff --git a/packages/superdough/wavetable.mjs b/packages/superdough/wavetable.mjs index ebf951a49..b4fc401f1 100644 --- a/packages/superdough/wavetable.mjs +++ b/packages/superdough/wavetable.mjs @@ -314,19 +314,28 @@ export async function onTriggerSynth(t, value, onended, tables, cps, frameLen) { dcoffset: value.warpdc ?? 0, }, ); - const vibratoOscillator = getVibratoOscillator(source.parameters.get('detune'), value, t); - const fm = applyFM(source.parameters.get('frequency'), value, t); + const vibratoHandle = getVibratoOscillator(source.parameters.get('detune'), value, t); + const fmHandle = applyFM(source.parameters.get('frequency'), value, t); const envGain = ac.createGain(); const node = source.connect(envGain); getParamADSR(node.gain, attack, decay, sustain, release, 0, 0.3, t, holdEnd, 'linear'); getPitchEnvelope(source.parameters.get('detune'), value, t, holdEnd); - const handle = { node, source }; + const handle = { + node, + nodes: { + source: [source], + wt_lfo: [wtPosModulators], + warp_lfo: [wtWarpModulators], + ...fmHandle?.nodes, + ...vibratoHandle?.nodes, + }, + }; const timeoutNode = webAudioTimeout( ac, () => { releaseAudioNode(source); - releaseAudioNode(vibratoOscillator); - fm?.stop(); + vibratoHandle?.stop(); + fmHandle?.stop(); releaseAudioNode(wtPosModulators); releaseAudioNode(wtWarpModulators); onended(); diff --git a/packages/superdough/zzfx.mjs b/packages/superdough/zzfx.mjs index 708f34503..f3dc710b1 100644 --- a/packages/superdough/zzfx.mjs +++ b/packages/superdough/zzfx.mjs @@ -75,7 +75,7 @@ export const getZZFX = (value, t) => { source.start(t); return { node: source, - source, + nodes: { source: [source] }, }; }; From b4496fcc24f8bd9f306fc1c9f0026f9d5f6b1d24 Mon Sep 17 00:00:00 2001 From: Aria Date: Sun, 28 Dec 2025 21:43:08 -0500 Subject: [PATCH 54/73] More control mapping tweaks --- packages/superdough/superdough.mjs | 5 ++++- packages/superdough/superdoughdata.mjs | 15 +++++++-------- packages/superdough/superdoughoutput.mjs | 1 + 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 8bca5b30c..980f18142 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -950,6 +950,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) const delayNode = orbitBus.getDelay(delaytime, delayfeedback, t); nodes['delay'] = [delayNode]; const delaySend = orbitBus.sendDelay(post, delay); + nodes['delay_mix'] = [delaySend]; audioNodes.push(delaySend); } // reverb @@ -968,6 +969,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) const roomNode = orbitBus.getReverb(roomsize, roomfade, roomlp, roomdim, roomIR, irspeed, irbegin); nodes['room'] = [roomNode]; const reverbSend = orbitBus.sendReverb(post, room); + nodes['room_mix'] = [reverbSend]; audioNodes.push(reverbSend); } if (bus != null) { @@ -977,7 +979,8 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) } if (djf != null) { - nodes['djf'] = orbitBus.getDjf(djf, t); + const djfNode = orbitBus.getDjf(djf, t); + nodes['djf'] = [djfNode]; } // analyser diff --git a/packages/superdough/superdoughdata.mjs b/packages/superdough/superdoughdata.mjs index 2ae03101a..f9df6ff83 100644 --- a/packages/superdough/superdoughdata.mjs +++ b/packages/superdough/superdoughdata.mjs @@ -87,25 +87,24 @@ const CONTROL_TARGETS = { compressorRelease: { node: 'compressor', param: 'release' }, // PHASER - phaserrate: { node: 'phaser', param: 'rate' }, - phaserdepth: { node: 'phaser', param: 'depth' }, - phasersweep: { node: 'phaser', param: 'sweep' }, + phaserrate: { node: 'phaser_lfo', param: 'rate' }, + phasersweep: { node: 'phaser_lfo', param: 'depth' }, phasercenter: { node: 'phaser', param: 'frequency' }, + phaserdepth: { node: 'phaser', param: 'Q' }, // ORBIT EFFECTS + delay: { node: 'delay_mix', param: 'gain' }, delaytime: { node: 'delay', param: 'delayTime' }, delayfeedback: { node: 'delay', param: 'feedback' }, - delaysync: { node: 'delay', param: 'sync' }, + delaysync: { node: 'delay', param: 'delayTime' }, dry: { node: 'dry', param: 'gain' }, - room: { node: 'room', param: 'wet' }, - roomfade: { node: 'room', param: 'fade' }, - roomlp: { node: 'room', param: 'lp' }, + room: { node: 'room_mix', param: 'gain' }, djf: { node: 'djf', param: 'value' }, busgain: { node: 'bus', param: 'gain' }, // SYNTHS s: { node: 'source', param: 'frequency' }, - detune: { node: 'source', param: 'detune' }, + detune: { node: 'source', param: 'freqspread' }, wt: { node: 'source', param: 'position' }, warp: { node: 'source', param: 'warp' }, freq: { node: 'source', param: 'frequency' }, diff --git a/packages/superdough/superdoughoutput.mjs b/packages/superdough/superdoughoutput.mjs index 204eb62a4..d3936646a 100644 --- a/packages/superdough/superdoughoutput.mjs +++ b/packages/superdough/superdoughoutput.mjs @@ -38,6 +38,7 @@ export class Orbit { } const val = this.djfNode.parameters.get('value'); val.setValueAtTime(value, t); + return this.djfNode; } getDelay(delaytime = 0, feedback = 0.5, t) { From c0f4f4715026d909cf3339e370a3298027f554a7 Mon Sep 17 00:00:00 2001 From: jeromew Date: Mon, 29 Dec 2025 14:04:40 +0000 Subject: [PATCH 55/73] Fix AudioContext change detection. Use AudioNode.context --- packages/superdough/superdough.mjs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index e98a2aa22..1ce91c835 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -359,9 +359,7 @@ export let analysers = {}, analysersData = {}; export function getAnalyserById(id, fftSize = 1024, smoothingTimeConstant = 0.5) { - // below commented out branch is hotfixing https://codeberg.org/uzu/strudel/issues/1847 - // might cause conflicts with exporting... - if (!analysers[id] /* || analysers[id].audioContext != getAudioContext() */) { + if (!analysers[id] || analysers[id].context != getAudioContext()) { // make sure this doesn't happen too often as it piles up garbage const analyserNode = getAudioContext().createAnalyser(); analyserNode.fftSize = fftSize; From 98367868ac0c7c95e44e48d294467c63c1e85dcb Mon Sep 17 00:00:00 2001 From: Aria Date: Mon, 29 Dec 2025 10:22:48 -0600 Subject: [PATCH 56/73] Handle min/max when target is LFO; fix vib and tremolo --- packages/superdough/superdough.mjs | 23 +++++++++++++---------- packages/superdough/superdoughdata.mjs | 8 ++++---- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 980f18142..13a4ef68c 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -420,10 +420,10 @@ function _getControlData(control) { return controlTargets[_stripIndex(control)]; } -function _getRangeForParam(paramName, currentValue, control) { - // For our normal oscillators / filters we want to clamp the frequency to a reasonable range - // For LFOs we allow it to be modulated freely - if (paramName === 'frequency' || control?.startsWith?.('lfo')) { +function _getRangeForParam(paramName, currentValue) { + // We clamp the frequency to a reasonable range unless the currentValue + // is low, which indicates this may be an LFO + if (paramName === 'frequency' && currentValue >= 30) { return { min: 20 - currentValue, max: 24000 - currentValue }; } return { min: undefined, max: undefined }; @@ -459,8 +459,9 @@ function connectLFO(idx, params, nodeTracker) { const { rate = 1, sync, cps, cycle, control = 'lfo', subControl, depth = 1, depthabs, ...filteredParams } = params; const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); if (!targetParams.length) return; - const currentValue = targetParams[0].value; - const { min, max } = _getRangeForParam(paramName, currentValue, control); + let currentValue = targetParams[0].value; + currentValue = currentValue === 0 ? 1 : currentValue; + const { min, max } = _getRangeForParam(paramName, currentValue); const depthValue = depthabs != null ? depthabs : depth * currentValue; const modParams = { ...filteredParams, @@ -480,8 +481,9 @@ function connectEnvelope(idx, params, nodeTracker) { const { control, subControl, acurve, dcurve, rcurve, depth = 1, depthabs, ...filteredParams } = params; const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); if (!targetParams.length) return; - const currentValue = targetParams[0].value; - const { min, max } = _getRangeForParam(paramName, currentValue, control); + let currentValue = targetParams[0].value; + currentValue = currentValue === 0 ? 1 : currentValue; + const { min, max } = _getRangeForParam(paramName, currentValue); const depthValue = depthabs != null ? depthabs : depth * currentValue; const envNode = getEnvelope(getAudioContext(), { ...filteredParams, @@ -507,8 +509,9 @@ function connectBusModulator(params, nodeTracker) { dc.start(params.begin); const shifted = dc.connect(gainNode(1)); signal.connect(shifted); - const currentValue = targetParams[0].value; - const { min, max } = _getRangeForParam(paramName, currentValue, control); + let currentValue = targetParams[0].value; + currentValue = currentValue === 0 ? 1 : currentValue; + const { min, max } = _getRangeForParam(paramName, currentValue); const depthValue = depthabs != null ? depthabs : depth * currentValue; const maxAbsDepth = Math.min(Math.abs(min), Math.abs(max)); const boundedDepth = Math.min(Math.abs(depthValue), maxAbsDepth) || Math.abs(depthValue); diff --git a/packages/superdough/superdoughdata.mjs b/packages/superdough/superdoughdata.mjs index f9df6ff83..2dac194f1 100644 --- a/packages/superdough/superdoughdata.mjs +++ b/packages/superdough/superdoughdata.mjs @@ -10,8 +10,8 @@ const CONTROL_TARGETS = { gain: { node: 'gain', param: 'gain' }, postgain: { node: 'post', param: 'gain' }, pan: { node: 'pan', param: 'pan' }, - tremolo: { node: 'tremolo', param: 'rate' }, - tremolosync: { node: 'tremolo', param: 'sync' }, + tremolo: { node: 'tremolo', param: 'frequency' }, + tremolosync: { node: 'tremolo', param: 'frequency' }, tremolodepth: { node: 'tremolo_gain', param: 'gain' }, tremoloskew: { node: 'tremolo', param: 'skew' }, tremolophase: { node: 'tremolo', param: 'phase' }, @@ -138,8 +138,8 @@ const CONTROL_TARGETS = { pw: { node: 'source', param: 'pulsewidth' }, pwrate: { node: 'pw_lfo', param: 'frequency' }, pwsweep: { node: 'pw_lfo', param: 'depth' }, - vib: { node: 'vib_gain', param: 'gain' }, - vibmod: { node: 'vib', param: 'frequency' }, + vib: { node: 'vib', param: 'frequency' }, + vibmod: { node: 'vib_gain', param: 'gain' }, byteBeatStartTime: { node: 'source', param: 'byteBeatStartTime' }, spread: { node: 'source', param: 'panspread' }, transient: { node: 'transient', param: 'attack' }, From e79b4b8ccb749b7c1a3cafbeb00e12ee66f220a6 Mon Sep 17 00:00:00 2001 From: Aria Date: Mon, 29 Dec 2025 10:41:20 -0600 Subject: [PATCH 57/73] Refactor modulators --- packages/superdough/index.mjs | 1 + packages/superdough/modulators.mjs | 141 +++++++++++++++++++++++++++++ packages/superdough/superdough.mjs | 140 +--------------------------- packages/superdough/worklets.mjs | 3 +- 4 files changed, 147 insertions(+), 138 deletions(-) create mode 100644 packages/superdough/modulators.mjs diff --git a/packages/superdough/index.mjs b/packages/superdough/index.mjs index a382bd15a..c3d2f6c52 100644 --- a/packages/superdough/index.mjs +++ b/packages/superdough/index.mjs @@ -10,6 +10,7 @@ export * from './helpers.mjs'; export * from './synth.mjs'; export * from './zzfx.mjs'; export * from './logger.mjs'; +export * from './modulators.mjs'; export * from './dspworklet.mjs'; export * from './audioContext.mjs'; export * from './wavetable.mjs'; diff --git a/packages/superdough/modulators.mjs b/packages/superdough/modulators.mjs new file mode 100644 index 000000000..3411aacb7 --- /dev/null +++ b/packages/superdough/modulators.mjs @@ -0,0 +1,141 @@ +/* +modulators.mjs - Helpers for constructing modulators (envelopes, LFOs, etc.) +Copyright (C) 2025 Strudel contributors - see +This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . +*/ + +import { getAudioContext } from './audioContext.mjs'; +import { gainNode, getEnvelope, getLfo, webAudioTimeout } from './helpers.mjs'; +import { errorLogger } from './logger.mjs'; +import { getSuperdoughControlTargets } from './superdoughdata.mjs'; + +const getNodeParam = (node, name) => { + // Worklet case + if (node?.parameters) { + const p = node.parameters.get(name); + if (p instanceof AudioParam) { + return p; + } + } + // Built-in node case + const p = node?.[name]; + if (p instanceof AudioParam) { + return p; + } + return undefined; +}; + +const controlTargets = getSuperdoughControlTargets(); + +const stripIndex = (control) => control?.replace(/\d+$/, ''); +const getControlData = (control) => { + return controlTargets[stripIndex(control)]; +}; + +const getRangeForParam = (paramName, currentValue) => { + // We clamp the frequency to a reasonable range unless the currentValue + // is low, which indicates this may be an LFO + if (paramName === 'frequency' && currentValue >= 30) { + return { min: 20 - currentValue, max: 24000 - currentValue }; + } + return { min: undefined, max: undefined }; +}; + +const getTargetParamsForControl = (control, nodes, subControl) => { + const lookupKey = subControl ? `${control}_${subControl}` : control; + const targetInfo = getControlData(lookupKey) ?? getControlData(control); + if (!targetInfo) { + errorLogger(new Error(`Could not find control data for target '${control}'`), 'superdough'); + return { targetParams: [], paramName: control }; + } + const paramName = targetInfo.param; + const nodeKey = nodes[targetInfo.node] ? targetInfo.node : control; + const targetNodes = nodes[nodeKey]; + if (!targetNodes) { + const keys = Object.keys(nodes); + errorLogger( + new Error(`Could not connect to target '${nodeKey}' — it does not exist. Available targets: ${keys.join(', ')}`), + 'superdough', + ); + return { targetParams: [], paramName }; + } + const audioParams = []; + targetNodes.forEach((targetNode) => { + const targetParam = getNodeParam(targetNode, paramName); + audioParams.push(targetParam); + }); + return { targetParams: audioParams, paramName }; +}; + +export const connectLFO = (idx, params, nodeTracker) => { + const { rate = 1, sync, cps, cycle, control = 'lfo', subControl, depth = 1, depthabs, ...filteredParams } = params; + const { targetParams, paramName } = getTargetParamsForControl(control, nodeTracker, subControl); + if (!targetParams.length) return; + let currentValue = targetParams[0].value; + currentValue = currentValue === 0 ? 1 : currentValue; + const { min, max } = getRangeForParam(paramName, currentValue); + const depthValue = depthabs != null ? depthabs : depth * currentValue; + const modParams = { + ...filteredParams, + frequency: sync !== undefined ? sync * cps : rate, + time: cycle / cps, + depth: depthValue, + min, + max, + }; + const lfoNode = getLfo(getAudioContext(), modParams); + nodeTracker[`lfo${idx}`] = [lfoNode]; + targetParams.forEach((t) => lfoNode.connect(t)); + return lfoNode; +}; + +export const connectEnvelope = (idx, params, nodeTracker) => { + const { control, subControl, acurve, dcurve, rcurve, depth = 1, depthabs, ...filteredParams } = params; + const { targetParams, paramName } = getTargetParamsForControl(control, nodeTracker, subControl); + if (!targetParams.length) return; + let currentValue = targetParams[0].value; + currentValue = currentValue === 0 ? 1 : currentValue; + const { min, max } = getRangeForParam(paramName, currentValue); + const depthValue = depthabs != null ? depthabs : depth * currentValue; + const envNode = getEnvelope(getAudioContext(), { + ...filteredParams, + depth: depthValue, + min, + max, + attackCurve: acurve, + decayCurve: dcurve, + releaseCurve: rcurve, + }); + nodeTracker[`env${idx}`] = [envNode]; + targetParams.forEach((t) => envNode.connect(t)); + return envNode; +}; + +export const connectBusModulator = (params, nodeTracker, controller) => { + const ac = getAudioContext(); + const { control, subControl, depth = 1, depthabs } = params; + const { targetParams, paramName } = getTargetParamsForControl(control, nodeTracker, subControl); + if (!targetParams.length) return { toCleanup: [] }; + const signal = controller.getBus(params.bus); + const dc = new ConstantSourceNode(ac, { offset: params.dc ?? 0 }); + dc.start(params.begin); + const shifted = dc.connect(gainNode(1)); + signal.connect(shifted); + let currentValue = targetParams[0].value; + debugger; + currentValue = currentValue === 0 ? 1 : currentValue; + const { min, max } = getRangeForParam(paramName, currentValue); + const depthValue = depthabs != null ? depthabs : depth * currentValue; + const maxAbsDepth = Math.min(Math.abs(min), Math.abs(max)); + const boundedDepth = Math.min(Math.abs(depthValue), maxAbsDepth) || Math.abs(depthValue); + const modulator = shifted.connect(gainNode((Math.sign(depthValue) * boundedDepth) / 0.3)); + webAudioTimeout( + ac, + () => { + targetParams.forEach((t) => modulator.connect(t)); + }, + 0, + params.begin, + ); + return { modulator, toCleanup: [dc, shifted, modulator] }; +}; diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 13a4ef68c..517b1d3e5 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -15,18 +15,16 @@ import { gainNode, getCompressor, getDistortion, - getEnvelope, getLfo, getWorklet, releaseAudioNode, - webAudioTimeout, } from './helpers.mjs'; import { map } from 'nanostores'; -import { errorLogger, logger } from './logger.mjs'; +import { logger } from './logger.mjs'; +import { connectLFO, connectEnvelope, connectBusModulator } from './modulators.mjs'; import { loadBuffer } from './sampler.mjs'; -import { getAudioContext, setAudioContext } from './audioContext.mjs'; +import { getAudioContext } from './audioContext.mjs'; import { SuperdoughAudioController } from './superdoughoutput.mjs'; -import { getSuperdoughControlTargets } from './superdoughdata.mjs'; import { resetSeenKeys } from './wavetable.mjs'; export const DEFAULT_MAX_POLYPHONY = 128; @@ -397,136 +395,6 @@ export function resetGlobalEffects() { analysersData = {}; } -function _getNodeParam(node, name) { - // Worklet case - if (node?.parameters) { - const p = node.parameters.get(name); - if (p instanceof AudioParam) { - return p; - } - } - // Built-in node case - const p = node?.[name]; - if (p instanceof AudioParam) { - return p; - } - return undefined; -} - -const controlTargets = getSuperdoughControlTargets(); - -const _stripIndex = (control) => control?.replace(/\d+$/, ''); -function _getControlData(control) { - return controlTargets[_stripIndex(control)]; -} - -function _getRangeForParam(paramName, currentValue) { - // We clamp the frequency to a reasonable range unless the currentValue - // is low, which indicates this may be an LFO - if (paramName === 'frequency' && currentValue >= 30) { - return { min: 20 - currentValue, max: 24000 - currentValue }; - } - return { min: undefined, max: undefined }; -} - -function _getTargetParamsForControl(control, nodes, subControl) { - const lookupKey = subControl ? `${control}_${subControl}` : control; - const targetInfo = _getControlData(lookupKey) ?? _getControlData(control); - if (!targetInfo) { - errorLogger(new Error(`Could not find control data for target '${control}'`), 'superdough'); - return { targetParams: [], paramName: control }; - } - const paramName = targetInfo.param; - const nodeKey = nodes[targetInfo.node] ? targetInfo.node : control; - const targetNodes = nodes[nodeKey]; - if (!targetNodes) { - const keys = Object.keys(nodes); - errorLogger( - new Error(`Could not connect to target '${nodeKey}' — it does not exist. Available targets: ${keys.join(', ')}`), - 'superdough', - ); - return { targetParams: [], paramName }; - } - const audioParams = []; - targetNodes.forEach((targetNode) => { - const targetParam = _getNodeParam(targetNode, paramName); - audioParams.push(targetParam); - }); - return { targetParams: audioParams, paramName }; -} - -function connectLFO(idx, params, nodeTracker) { - const { rate = 1, sync, cps, cycle, control = 'lfo', subControl, depth = 1, depthabs, ...filteredParams } = params; - const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); - if (!targetParams.length) return; - let currentValue = targetParams[0].value; - currentValue = currentValue === 0 ? 1 : currentValue; - const { min, max } = _getRangeForParam(paramName, currentValue); - const depthValue = depthabs != null ? depthabs : depth * currentValue; - const modParams = { - ...filteredParams, - frequency: sync !== undefined ? sync * cps : rate, - time: cycle / cps, - depth: depthValue, - min, - max, - }; - const lfoNode = getLfo(getAudioContext(), modParams); - nodeTracker[`lfo${idx}`] = [lfoNode]; - targetParams.forEach((t) => lfoNode.connect(t)); - return lfoNode; -} - -function connectEnvelope(idx, params, nodeTracker) { - const { control, subControl, acurve, dcurve, rcurve, depth = 1, depthabs, ...filteredParams } = params; - const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); - if (!targetParams.length) return; - let currentValue = targetParams[0].value; - currentValue = currentValue === 0 ? 1 : currentValue; - const { min, max } = _getRangeForParam(paramName, currentValue); - const depthValue = depthabs != null ? depthabs : depth * currentValue; - const envNode = getEnvelope(getAudioContext(), { - ...filteredParams, - depth: depthValue, - min, - max, - attackCurve: acurve, - decayCurve: dcurve, - releaseCurve: rcurve, - }); - nodeTracker[`env${idx}`] = [envNode]; - targetParams.forEach((t) => envNode.connect(t)); - return envNode; -} - -function connectBusModulator(params, nodeTracker) { - const ac = getAudioContext(); - const { control, subControl, depth = 1, depthabs } = params; - const { targetParams, paramName } = _getTargetParamsForControl(control, nodeTracker, subControl); - if (!targetParams.length) return { toCleanup: [] }; - const signal = controller.getBus(params.bus); - const dc = new ConstantSourceNode(ac, { offset: params.dc ?? 0 }); - dc.start(params.begin); - const shifted = dc.connect(gainNode(1)); - signal.connect(shifted); - let currentValue = targetParams[0].value; - currentValue = currentValue === 0 ? 1 : currentValue; - const { min, max } = _getRangeForParam(paramName, currentValue); - const depthValue = depthabs != null ? depthabs : depth * currentValue; - const maxAbsDepth = Math.min(Math.abs(min), Math.abs(max)); - const boundedDepth = Math.min(Math.abs(depthValue), maxAbsDepth) || Math.abs(depthValue); - const modulator = shifted.connect(gainNode((Math.sign(depthValue) * boundedDepth) / 0.3)); - webAudioTimeout( - ac, - () => { - targetParams.forEach((t) => modulator.connect(t)); - }, - 0, - params.begin, - ); - return { modulator, toCleanup: [dc, shifted, modulator] }; -} - let activeSoundSources = new Map(); //music programs/audio gear usually increments inputs/outputs from 1, we need to subtract 1 from the input because the webaudio API channels start at 0 @@ -1038,7 +906,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) } if (value.bmod) { for (const p of value.bmod) { - const { toCleanup } = connectBusModulator({ ...p, begin: t, end: endWithRelease }, nodes); + const { toCleanup } = connectBusModulator({ ...p, begin: t, end: endWithRelease }, nodes, controller); audioNodes.push(...toCleanup); } } diff --git a/packages/superdough/worklets.mjs b/packages/superdough/worklets.mjs index 4523e9e89..8001c7da8 100644 --- a/packages/superdough/worklets.mjs +++ b/packages/superdough/worklets.mjs @@ -1055,8 +1055,7 @@ class EnvelopeProcessor extends AudioWorkletProcessor { this.state = (this.state + 1) % states.length; time = states[this.state].time; } - const clamped = clamp(this.val * depth, min, max); - out[i] = clamped; + out[i] = clamp(this.val * depth, min, max); } return true; } From 680b7d78ec3fb5ab89ca27c56a9695519f564cec Mon Sep 17 00:00:00 2001 From: Aria Date: Mon, 29 Dec 2025 12:59:48 -0600 Subject: [PATCH 58/73] Lots of examples; use id instead of index; waveshaper clamping; one mode for synth --- packages/core/controls.mjs | 110 ++++++++++++++++++---- packages/superdough/modulators.mjs | 35 ++++--- packages/superdough/superdough.mjs | 15 +-- packages/superdough/synth.mjs | 15 ++- test/__snapshots__/examples.test.mjs.snap | 90 ++++++++++++++++++ test/examples.test.mjs | 1 + 6 files changed, 228 insertions(+), 38 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index 5cc53de60..1bf3fa85c 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -2869,8 +2869,8 @@ registerSubControls('bmod', [ ['dc'], ]); -Pattern.prototype.modulate = function (type, config, idx) { - config ??= { control: undefined }; +Pattern.prototype.modulate = function (type, config, id) { + config = { control: undefined, ...config }; const modulatorKeys = ['lfo', 'env', 'bmod']; if (!modulatorKeys.includes(type)) { logger(`[core] Modulation type ${type} not found. Please use one of 'lfo', 'env', 'bmod'`); @@ -2888,19 +2888,20 @@ Pattern.prototype.modulate = function (type, config, idx) { // e.g. pat.gain(0.5).lfo({..}) will be a gain-LFO let control = getControlName(Object.keys(v).at(-1)); if (modulatorKeys.includes(control)) { - control = `${control}${v[control].length - 1}`; + control = `${control}_${[...v[control].__ids].at(-1)}`; } defaultValue = control; } - v[type] ??= []; + v[type] ??= { __ids: new Set() }; const t = v[type]; - idx ??= t.length; - t[idx] ??= { control: defaultValue }; + id ??= t.__ids.size; + t[id] ??= { control: defaultValue }; + t.__ids.add(id); // keeps track of insertion order if (c === undefined) return v; if (key === 'control' || key === 'subControl') { - t[idx][key] = getControlName(c); + t[id][key] = getControlName(c); } else { - t[idx][key] = c; + t[id][key] = c; } return v; }) @@ -2910,10 +2911,16 @@ Pattern.prototype.modulate = function (type, config, idx) { }; /** - * Configures an LFO. Can be called in sequence like pat.lfo(...).lfo(...) to set up multiple LFOs + * Configures an LFO. Can be called in sequence like pat.lfo(...).lfo(...) to set up multiple LFOs. + * There are two ways to declare which control will be modulated: + * 1. Explicitly put `control` in the config (e.g. `lfo({ c: "lpf" })`) + * 2. If the control parameter is absent, the control _immediately before_ the `lfo` call will be used + * (e.g. `s("saw").lpf(500).lfo()` to modulate `lpf`) + * + * Modulators can be referred to by `id` so that they can be updated later e.g. inside + * a `sometimes`. See example below. * * @name lfo - * @memberof Pattern * @param {Object} config LFO configuration. * @param {string | Pattern} [config.control] Node to modulate. Aliases: t * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc, p @@ -2925,18 +2932,47 @@ Pattern.prototype.modulate = function (type, config, idx) { * @param {number | Pattern} [config.skew] Skew amount. Aliases: sk * @param {number | Pattern} [config.curve] Exponential curve amount. Aliases: c * @param {number | Pattern} [config.sync] Tempo-synced modulation rate. Aliases: s + * @param {string | Pattern} id ID to use for this modulator * @returns Pattern + * + * @example + * s("saw").note("F1").lpf(500).lfo() + * + * @example + * s("saw").lfo().lpf(500).lfo({ s: 0.3 }) + * + * @example + * s("saw").lpf(500).diode(0.3) + * .lfo({ c: "lpf" }) + * + * @example + * s("pulse").lpf(500).lfo() + * .lfo({ c: "s" }) + * .diode(0.3) + * .sometimes(x => x.lfo({ s: "8" }, 1)) // lfo #1 (0-indexed) + * + * @example + * s("pulse").lpf(500).lfo({ depth: 4 }, 'lpf_mod') + * .lfo({ c: "s" }) + * .diode(0.3) + * .sometimes(x => x.lfo({ s: "8" }, 'lpf_mod')) */ -Pattern.prototype.lfo = function (config, idx) { - return this.modulate('lfo', config, idx); +Pattern.prototype.lfo = function (config, id) { + return this.modulate('lfo', config, id); }; export const lfo = (config) => pure({}).lfo(config); /** * Configures an envelope. Can be called in sequence like pat.env(...).env(...) to set up multiple envelopes + * There are two ways to declare which control will be modulated: + * 1. Explicitly put `control` in the config (e.g. `env({ c: "lpf" })`) + * 2. If the control parameter is absent, the control _immediately before_ the `env` call will be used + * (e.g. `s("saw").lpf(500).env({ a: 1 })` to modulate `lpf`) + * + * Modulators can be referred to by `id` so that they can be updated later e.g. inside + * a `sometimes`. See example below. * * @name env - * @memberof Pattern * @param {Object} config Envelope configuration. * @param {string | Pattern} [config.control] Node to modulate. Aliases: t * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc, p @@ -2949,10 +2985,35 @@ export const lfo = (config) => pure({}).lfo(config); * @param {number | Pattern} [config.acurve] Snappiness of attack curve (-1 = relaxed, 1 = snappy). Aliases: ac * @param {number | Pattern} [config.dcurve] Snappiness of decay curve (-1 = relaxed, 1 = snappy). Aliases: dc * @param {number | Pattern} [config.rcurve] Snappiness of release curve (-1 = relaxed, 1 = snappy). Aliases: rc + * @param {string | Pattern} id ID to use for this modulator * @returns Pattern + * + * @example + * s("saw").note("F1").lpf(500).env({ a: 1 }) + * + * @example + * s("saw").env({ d: 1 }).note("F1") + * .lpq(4).lpf(50) + * .env({ a: 0.1, d: 1, ac: 0.8, dc: 0.3, depth: 50 }) + * + * @example + * s("saw").lpf(500).diode(0.3) + * .env({ c: "lpf", a: 0.5, d: 0.5 }) + * + * @example + * s("pulse").lpf(500).env({ a: 1 }) + * .env({ c: "s", a: 1 }) + * .diode(0.3) + * .sometimes(x => x.env({ a: "0.5" }, 1)) // envelope #1 (0-indexed) + * + * @example + * s("pulse").lpf(500).env({ a: 1 }, 'lpf_mod') + * .env({ c: "s", a: 1 }) + * .diode(0.3) + * .sometimes(x => x.env({ a: "0.5" }, 'lpf_mod')) */ -Pattern.prototype.env = function (config, idx) { - return this.modulate('env', config, idx); +Pattern.prototype.env = function (config, id) { + return this.modulate('env', config, id); }; export const env = (config) => pure({}).env(config); @@ -2962,8 +3023,15 @@ export const env = (config) => pure({}).env(config); * * Send to an audio bus with `otherPat.bus(..)`. * + * There are two ways to declare which control will be modulated: + * 1. Explicitly put `control` in the config (e.g. `bmod({ id: 2, c: "lpf" })`) + * 2. If the control parameter is absent, the control _immediately before_ the `bmod` call will be used + * (e.g. `s("saw").lpf(500).bmod({ id: 2 })` to modulate `lpf`) + * + * Modulators can be referred to by `id` so that they can be updated later e.g. inside + * a `sometimes`. See example below. + * * @name bmod - * @memberof Pattern * @param {Object} config Bus modulation configuration. * @param {string | Pattern} [config.bus] Bus to get modulation signal from * @param {string | Pattern} [config.control] Node to modulate. Aliases: t @@ -2971,10 +3039,16 @@ export const env = (config) => pure({}).env(config); * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da * @param {number | Pattern} [config.dc] DC offset prior to application + * @param {string | Pattern} id ID to use for this modulator * @returns Pattern + * + * @example + * modulator: s("one").seg(64).gain(slider(0, 0, 1)).bus(1).dry(0) + * carrier: s("saw").bmod({ b: 1 }) + * */ -Pattern.prototype.bmod = function (config, idx) { - return this.modulate('bmod', config, idx); +Pattern.prototype.bmod = function (config, id) { + return this.modulate('bmod', config, id); }; export const bmod = (config) => pure({}).bmod(config); diff --git a/packages/superdough/modulators.mjs b/packages/superdough/modulators.mjs index 3411aacb7..32ebae265 100644 --- a/packages/superdough/modulators.mjs +++ b/packages/superdough/modulators.mjs @@ -8,6 +8,7 @@ import { getAudioContext } from './audioContext.mjs'; import { gainNode, getEnvelope, getLfo, webAudioTimeout } from './helpers.mjs'; import { errorLogger } from './logger.mjs'; import { getSuperdoughControlTargets } from './superdoughdata.mjs'; +import { clamp } from './util.mjs'; const getNodeParam = (node, name) => { // Worklet case @@ -27,9 +28,8 @@ const getNodeParam = (node, name) => { const controlTargets = getSuperdoughControlTargets(); -const stripIndex = (control) => control?.replace(/\d+$/, ''); const getControlData = (control) => { - return controlTargets[stripIndex(control)]; + return controlTargets[control.split('_')[0]]; }; const getRangeForParam = (paramName, currentValue) => { @@ -41,6 +41,19 @@ const getRangeForParam = (paramName, currentValue) => { return { min: undefined, max: undefined }; }; +const clampWithWaveShaper = (modulator, min, max) => { + const ac = getAudioContext(); + const curve = new Float32Array(256); + for (let i = 0; i < curve.length; i++) { + const x = (i / (curve.length - 1)) * 2 - 1; + curve[i] = clamp(x * max, min, max); + } + const shaper = new WaveShaperNode(ac, { curve }); + const scaleGain = gainNode(1 / max); + modulator.connect(scaleGain).connect(shaper); + return { modulator, toCleanup: [shaper, scaleGain] }; +}; + const getTargetParamsForControl = (control, nodes, subControl) => { const lookupKey = subControl ? `${control}_${subControl}` : control; const targetInfo = getControlData(lookupKey) ?? getControlData(control); @@ -67,7 +80,7 @@ const getTargetParamsForControl = (control, nodes, subControl) => { return { targetParams: audioParams, paramName }; }; -export const connectLFO = (idx, params, nodeTracker) => { +export const connectLFO = (id, params, nodeTracker) => { const { rate = 1, sync, cps, cycle, control = 'lfo', subControl, depth = 1, depthabs, ...filteredParams } = params; const { targetParams, paramName } = getTargetParamsForControl(control, nodeTracker, subControl); if (!targetParams.length) return; @@ -84,12 +97,12 @@ export const connectLFO = (idx, params, nodeTracker) => { max, }; const lfoNode = getLfo(getAudioContext(), modParams); - nodeTracker[`lfo${idx}`] = [lfoNode]; + nodeTracker[`lfo_${id}`] = [lfoNode]; targetParams.forEach((t) => lfoNode.connect(t)); return lfoNode; }; -export const connectEnvelope = (idx, params, nodeTracker) => { +export const connectEnvelope = (id, params, nodeTracker) => { const { control, subControl, acurve, dcurve, rcurve, depth = 1, depthabs, ...filteredParams } = params; const { targetParams, paramName } = getTargetParamsForControl(control, nodeTracker, subControl); if (!targetParams.length) return; @@ -106,7 +119,7 @@ export const connectEnvelope = (idx, params, nodeTracker) => { decayCurve: dcurve, releaseCurve: rcurve, }); - nodeTracker[`env${idx}`] = [envNode]; + nodeTracker[`env_${id}`] = [envNode]; targetParams.forEach((t) => envNode.connect(t)); return envNode; }; @@ -122,13 +135,12 @@ export const connectBusModulator = (params, nodeTracker, controller) => { const shifted = dc.connect(gainNode(1)); signal.connect(shifted); let currentValue = targetParams[0].value; - debugger; currentValue = currentValue === 0 ? 1 : currentValue; const { min, max } = getRangeForParam(paramName, currentValue); const depthValue = depthabs != null ? depthabs : depth * currentValue; - const maxAbsDepth = Math.min(Math.abs(min), Math.abs(max)); - const boundedDepth = Math.min(Math.abs(depthValue), maxAbsDepth) || Math.abs(depthValue); - const modulator = shifted.connect(gainNode((Math.sign(depthValue) * boundedDepth) / 0.3)); + const depthGain = gainNode((Math.sign(depthValue) * Math.abs(depthValue)) / 0.3); + const unClamped = shifted.connect(depthGain); + let { modulator, toCleanup } = clampWithWaveShaper(unClamped, min, max); webAudioTimeout( ac, () => { @@ -137,5 +149,6 @@ export const connectBusModulator = (params, nodeTracker, controller) => { 0, params.begin, ); - return { modulator, toCleanup: [dc, shifted, modulator] }; + toCleanup.push(dc, shifted, depthGain); + return { modulator, toCleanup }; }; diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 517b1d3e5..ee0cec836 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -875,9 +875,10 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) // finally, now that `nodes` is populated, set up modulators if (value.lfo) { - for (const [idx, params] of Object.entries(value.lfo)) { + for (const id of value.lfo.__ids) { + const params = value.lfo[id]; const lfo = connectLFO( - idx, + id, { ...params, cps, @@ -891,9 +892,10 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) } } if (value.env) { - for (const [idx, params] of Object.entries(value.env)) { + for (const id of value.env.__ids) { + const params = value.env[id]; const env = connectEnvelope( - idx, + id, { ...params, begin: t, @@ -905,8 +907,9 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) } } if (value.bmod) { - for (const p of value.bmod) { - const { toCleanup } = connectBusModulator({ ...p, begin: t, end: endWithRelease }, nodes, controller); + for (const id of value.bmod.__ids) { + const params = value.bmod[id]; + const { toCleanup } = connectBusModulator({ ...params, begin: t, end: endWithRelease }, nodes, controller); audioNodes.push(...toCleanup); } } diff --git a/packages/superdough/synth.mjs b/packages/superdough/synth.mjs index d20692729..6c8d1fea9 100644 --- a/packages/superdough/synth.mjs +++ b/packages/superdough/synth.mjs @@ -19,7 +19,7 @@ import { import { logger } from './logger.mjs'; import { getNoiseMix, getNoiseOscillator } from './noise.mjs'; -const waveforms = ['triangle', 'square', 'sawtooth', 'sine', 'user']; +const waveforms = ['triangle', 'square', 'sawtooth', 'sine', 'user', 'one']; const waveformAliases = [ ['tri', 'triangle'], ['sqr', 'square'], @@ -508,8 +508,17 @@ export function getOscillator(s, t, value, onended) { s = 'triangle'; } s = s === 'user' && !partials ? 'triangle' : s; - // If no partials are given, use stock waveforms - if (!partials || partials?.length === 0 || s === 'sine') { + if (s === 'one') { + // Constant 1 oscillator (used for modulation) + o = new ConstantSourceNode(getAudioContext(), { offset: 1 }); + o.start(t); + return { + node: o, + nodes: { source: o }, + stop: (time) => o?.stop(time), + }; + } else if (!partials || partials?.length === 0 || s === 'sine') { + // If no partials are given, use stock waveforms o = getAudioContext().createOscillator(); o.type = s || 'triangle'; } diff --git a/test/__snapshots__/examples.test.mjs.snap b/test/__snapshots__/examples.test.mjs.snap index 5f8133ec5..61ab11866 100644 --- a/test/__snapshots__/examples.test.mjs.snap +++ b/test/__snapshots__/examples.test.mjs.snap @@ -3803,6 +3803,51 @@ exports[`runs examples > example "end" example index 0 1`] = ` ] `; +exports[`runs examples > example "env" example index 0 1`] = ` +[ + "[ 0/1 → 1/1 | s:saw note:F1 cutoff:500 env:{0:{control:cutoff attack:1} __ids:{}} ]", + "[ 1/1 → 2/1 | s:saw note:F1 cutoff:500 env:{0:{control:cutoff attack:1} __ids:{}} ]", + "[ 2/1 → 3/1 | s:saw note:F1 cutoff:500 env:{0:{control:cutoff attack:1} __ids:{}} ]", + "[ 3/1 → 4/1 | s:saw note:F1 cutoff:500 env:{0:{control:cutoff attack:1} __ids:{}} ]", +] +`; + +exports[`runs examples > example "env" example index 1 1`] = ` +[ + "[ 0/1 → 1/1 | s:saw env:{0:{control:s decay:1} 1:{control:cutoff attack:0.1 decay:1 acurve:0.8 dcurve:0.3 depth:50} __ids:{}} note:F1 resonance:4 cutoff:50 ]", + "[ 1/1 → 2/1 | s:saw env:{0:{control:s decay:1} 1:{control:cutoff attack:0.1 decay:1 acurve:0.8 dcurve:0.3 depth:50} __ids:{}} note:F1 resonance:4 cutoff:50 ]", + "[ 2/1 → 3/1 | s:saw env:{0:{control:s decay:1} 1:{control:cutoff attack:0.1 decay:1 acurve:0.8 dcurve:0.3 depth:50} __ids:{}} note:F1 resonance:4 cutoff:50 ]", + "[ 3/1 → 4/1 | s:saw env:{0:{control:s decay:1} 1:{control:cutoff attack:0.1 decay:1 acurve:0.8 dcurve:0.3 depth:50} __ids:{}} note:F1 resonance:4 cutoff:50 ]", +] +`; + +exports[`runs examples > example "env" example index 2 1`] = ` +[ + "[ 0/1 → 1/1 | s:saw cutoff:500 distort:0.3 distortvol:1 distorttype:diode env:{0:{control:cutoff attack:0.5 decay:0.5} __ids:{}} ]", + "[ 1/1 → 2/1 | s:saw cutoff:500 distort:0.3 distortvol:1 distorttype:diode env:{0:{control:cutoff attack:0.5 decay:0.5} __ids:{}} ]", + "[ 2/1 → 3/1 | s:saw cutoff:500 distort:0.3 distortvol:1 distorttype:diode env:{0:{control:cutoff attack:0.5 decay:0.5} __ids:{}} ]", + "[ 3/1 → 4/1 | s:saw cutoff:500 distort:0.3 distortvol:1 distorttype:diode env:{0:{control:cutoff attack:0.5 decay:0.5} __ids:{}} ]", +] +`; + +exports[`runs examples > example "env" example index 3 1`] = ` +[ + "[ 0/1 → 1/1 | s:pulse cutoff:500 env:{0:{control:cutoff attack:1} 1:{control:s attack:0.5} __ids:{}} distort:0.3 distortvol:1 distorttype:diode ]", + "[ 1/1 → 2/1 | s:pulse cutoff:500 env:{0:{control:cutoff attack:1} 1:{control:s attack:1} __ids:{}} distort:0.3 distortvol:1 distorttype:diode ]", + "[ 2/1 → 3/1 | s:pulse cutoff:500 env:{0:{control:cutoff attack:1} 1:{control:s attack:1} __ids:{}} distort:0.3 distortvol:1 distorttype:diode ]", + "[ 3/1 → 4/1 | s:pulse cutoff:500 env:{0:{control:cutoff attack:1} 1:{control:s attack:0.5} __ids:{}} distort:0.3 distortvol:1 distorttype:diode ]", +] +`; + +exports[`runs examples > example "env" example index 4 1`] = ` +[ + "[ 0/1 → 1/1 | s:pulse cutoff:500 env:{1:{control:s attack:1} __ids:{} lpf_mod:{control:cutoff attack:0.5}} distort:0.3 distortvol:1 distorttype:diode ]", + "[ 1/1 → 2/1 | s:pulse cutoff:500 env:{1:{control:s attack:1} __ids:{} lpf_mod:{control:cutoff attack:1}} distort:0.3 distortvol:1 distorttype:diode ]", + "[ 2/1 → 3/1 | s:pulse cutoff:500 env:{1:{control:s attack:1} __ids:{} lpf_mod:{control:cutoff attack:1}} distort:0.3 distortvol:1 distorttype:diode ]", + "[ 3/1 → 4/1 | s:pulse cutoff:500 env:{1:{control:s attack:1} __ids:{} lpf_mod:{control:cutoff attack:0.5}} distort:0.3 distortvol:1 distorttype:diode ]", +] +`; + exports[`runs examples > example "euclid" example index 0 1`] = ` [ "[ 0/1 → 1/8 | note:c3 ]", @@ -6113,6 +6158,51 @@ exports[`runs examples > example "leslie" example index 0 1`] = ` ] `; +exports[`runs examples > example "lfo" example index 0 1`] = ` +[ + "[ 0/1 → 1/1 | s:saw note:F1 cutoff:500 lfo:{0:{control:cutoff} __ids:{}} ]", + "[ 1/1 → 2/1 | s:saw note:F1 cutoff:500 lfo:{0:{control:cutoff} __ids:{}} ]", + "[ 2/1 → 3/1 | s:saw note:F1 cutoff:500 lfo:{0:{control:cutoff} __ids:{}} ]", + "[ 3/1 → 4/1 | s:saw note:F1 cutoff:500 lfo:{0:{control:cutoff} __ids:{}} ]", +] +`; + +exports[`runs examples > example "lfo" example index 1 1`] = ` +[ + "[ 0/1 → 1/1 | s:saw lfo:{0:{control:s} 1:{control:cutoff sync:0.3} __ids:{}} cutoff:500 ]", + "[ 1/1 → 2/1 | s:saw lfo:{0:{control:s} 1:{control:cutoff sync:0.3} __ids:{}} cutoff:500 ]", + "[ 2/1 → 3/1 | s:saw lfo:{0:{control:s} 1:{control:cutoff sync:0.3} __ids:{}} cutoff:500 ]", + "[ 3/1 → 4/1 | s:saw lfo:{0:{control:s} 1:{control:cutoff sync:0.3} __ids:{}} cutoff:500 ]", +] +`; + +exports[`runs examples > example "lfo" example index 2 1`] = ` +[ + "[ 0/1 → 1/1 | s:saw cutoff:500 distort:0.3 distortvol:1 distorttype:diode lfo:{0:{control:cutoff} __ids:{}} ]", + "[ 1/1 → 2/1 | s:saw cutoff:500 distort:0.3 distortvol:1 distorttype:diode lfo:{0:{control:cutoff} __ids:{}} ]", + "[ 2/1 → 3/1 | s:saw cutoff:500 distort:0.3 distortvol:1 distorttype:diode lfo:{0:{control:cutoff} __ids:{}} ]", + "[ 3/1 → 4/1 | s:saw cutoff:500 distort:0.3 distortvol:1 distorttype:diode lfo:{0:{control:cutoff} __ids:{}} ]", +] +`; + +exports[`runs examples > example "lfo" example index 3 1`] = ` +[ + "[ 0/1 → 1/1 | s:pulse cutoff:500 lfo:{0:{control:cutoff} 1:{control:s sync:8} __ids:{}} distort:0.3 distortvol:1 distorttype:diode ]", + "[ 1/1 → 2/1 | s:pulse cutoff:500 lfo:{0:{control:cutoff} 1:{control:s} __ids:{}} distort:0.3 distortvol:1 distorttype:diode ]", + "[ 2/1 → 3/1 | s:pulse cutoff:500 lfo:{0:{control:cutoff} 1:{control:s} __ids:{}} distort:0.3 distortvol:1 distorttype:diode ]", + "[ 3/1 → 4/1 | s:pulse cutoff:500 lfo:{0:{control:cutoff} 1:{control:s sync:8} __ids:{}} distort:0.3 distortvol:1 distorttype:diode ]", +] +`; + +exports[`runs examples > example "lfo" example index 4 1`] = ` +[ + "[ 0/1 → 1/1 | s:pulse cutoff:500 lfo:{1:{control:s} __ids:{} lpf_mod:{control:cutoff depth:4 sync:8}} distort:0.3 distortvol:1 distorttype:diode ]", + "[ 1/1 → 2/1 | s:pulse cutoff:500 lfo:{1:{control:s} __ids:{} lpf_mod:{control:cutoff depth:4}} distort:0.3 distortvol:1 distorttype:diode ]", + "[ 2/1 → 3/1 | s:pulse cutoff:500 lfo:{1:{control:s} __ids:{} lpf_mod:{control:cutoff depth:4}} distort:0.3 distortvol:1 distorttype:diode ]", + "[ 3/1 → 4/1 | s:pulse cutoff:500 lfo:{1:{control:s} __ids:{} lpf_mod:{control:cutoff depth:4 sync:8}} distort:0.3 distortvol:1 distorttype:diode ]", +] +`; + exports[`runs examples > example "linger" example index 0 1`] = ` [ "[ 0/1 → 1/4 | s:lt ]", diff --git a/test/examples.test.mjs b/test/examples.test.mjs index 896a02f8a..ebec2252e 100644 --- a/test/examples.test.mjs +++ b/test/examples.test.mjs @@ -20,6 +20,7 @@ const skippedExamples = [ 'accelerationX', 'defaultmidimap', 'midimaps', + 'bmod', ]; describe('runs examples', () => { From 0edede106aaf44194c53348658991ccd9391af44 Mon Sep 17 00:00:00 2001 From: Aria Date: Mon, 29 Dec 2025 13:28:26 -0600 Subject: [PATCH 59/73] Fixes for zzfx and soundfonts --- packages/superdough/modulators.mjs | 6 +++++- packages/superdough/zzfx.mjs | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/superdough/modulators.mjs b/packages/superdough/modulators.mjs index 32ebae265..96c68d4bf 100644 --- a/packages/superdough/modulators.mjs +++ b/packages/superdough/modulators.mjs @@ -19,7 +19,11 @@ const getNodeParam = (node, name) => { } } // Built-in node case - const p = node?.[name]; + let p = node?.[name]; + if (p === undefined && name === 'frequency') { + // Fallbacks for source nodes without 'frequency' params (e.g. soundfonts) + p = node?.['detune'] ?? node?.['playbackRate']; + } if (p instanceof AudioParam) { return p; } diff --git a/packages/superdough/zzfx.mjs b/packages/superdough/zzfx.mjs index f3dc710b1..3d6b8e9f5 100644 --- a/packages/superdough/zzfx.mjs +++ b/packages/superdough/zzfx.mjs @@ -75,7 +75,6 @@ export const getZZFX = (value, t) => { source.start(t); return { node: source, - nodes: { source: [source] }, }; }; @@ -91,6 +90,7 @@ export function registerZZFXSounds() { }); return { node: o, + nodes: { source: [o] }, stop: () => {}, }; }, From 6051b922c065175c3c64b5ea34d736ffb16a445c Mon Sep 17 00:00:00 2001 From: Aria Date: Mon, 29 Dec 2025 14:45:49 -0600 Subject: [PATCH 60/73] Fix clamping when min/max not specified --- packages/superdough/modulators.mjs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/superdough/modulators.mjs b/packages/superdough/modulators.mjs index 96c68d4bf..7a1fe252d 100644 --- a/packages/superdough/modulators.mjs +++ b/packages/superdough/modulators.mjs @@ -144,7 +144,13 @@ export const connectBusModulator = (params, nodeTracker, controller) => { const depthValue = depthabs != null ? depthabs : depth * currentValue; const depthGain = gainNode((Math.sign(depthValue) * Math.abs(depthValue)) / 0.3); const unClamped = shifted.connect(depthGain); - let { modulator, toCleanup } = clampWithWaveShaper(unClamped, min, max); + const toCleanup = []; + let modulator = unClamped; + if (min !== undefined && max !== undefined) { + const wsData = clampWithWaveShaper(unClamped, min, max); + modulator = wsData.modulator; + toCleanup.push(...wsData.toCleanup); + } webAudioTimeout( ac, () => { From d41ebf190b6c36d6124cb5af17f78f77e056ab66 Mon Sep 17 00:00:00 2001 From: eddyflux Date: Tue, 30 Dec 2025 00:22:51 +0100 Subject: [PATCH 61/73] fix: missing punctuation --- website/src/pages/workshop/first-sounds.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/pages/workshop/first-sounds.mdx b/website/src/pages/workshop/first-sounds.mdx index 1d659972b..84deb0551 100644 --- a/website/src/pages/workshop/first-sounds.mdx +++ b/website/src/pages/workshop/first-sounds.mdx @@ -377,4 +377,4 @@ insect [crow metal] - -, punchcard /> -Now that we know the basics of how to make beats, let's look at how we can play [notes](/workshop/first-notes) +Now that we know the basics of how to make beats, let's look at how we can play [notes](/workshop/first-notes). From aec33710b751b84c7d65ce22caea24ed34a813c1 Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 31 Dec 2025 14:58:31 -0600 Subject: [PATCH 62/73] Working version --- packages/core/controls.mjs | 8 + packages/core/pattern.mjs | 16 + packages/superdough/feedbackdelay.mjs | 19 +- packages/superdough/modulators.mjs | 27 +- packages/superdough/reverbGen.mjs | 6 +- packages/superdough/superdough.mjs | 746 ++++++++++++++------------ 6 files changed, 472 insertions(+), 350 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index 1bf3fa85c..b18a8dff6 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -2846,6 +2846,7 @@ registerSubControls('lfo', [ ['skew', 'sk'], ['curve'], ['sync', 's'], + ['fxi'], ]); registerSubControls('env', [ ['control', 'c'], @@ -2859,6 +2860,7 @@ registerSubControls('env', [ ['acurve', 'ac'], ['dcurve', 'dc'], ['rcurve', 'rc'], + ['fxi'], ]); registerSubControls('bmod', [ ['bus', 'b'], @@ -2867,6 +2869,7 @@ registerSubControls('bmod', [ ['depth', 'dep', 'dr'], ['depthabs', 'da'], ['dc'], + ['fxi'], ]); Pattern.prototype.modulate = function (type, config, id) { @@ -2932,6 +2935,7 @@ Pattern.prototype.modulate = function (type, config, id) { * @param {number | Pattern} [config.skew] Skew amount. Aliases: sk * @param {number | Pattern} [config.curve] Exponential curve amount. Aliases: c * @param {number | Pattern} [config.sync] Tempo-synced modulation rate. Aliases: s + * @param {number | Pattern} [config.fxi] FX index to target * @param {string | Pattern} id ID to use for this modulator * @returns Pattern * @@ -2985,6 +2989,7 @@ export const lfo = (config) => pure({}).lfo(config); * @param {number | Pattern} [config.acurve] Snappiness of attack curve (-1 = relaxed, 1 = snappy). Aliases: ac * @param {number | Pattern} [config.dcurve] Snappiness of decay curve (-1 = relaxed, 1 = snappy). Aliases: dc * @param {number | Pattern} [config.rcurve] Snappiness of release curve (-1 = relaxed, 1 = snappy). Aliases: rc + * @param {number | Pattern} [config.fxi] FX index to target * @param {string | Pattern} id ID to use for this modulator * @returns Pattern * @@ -3039,6 +3044,7 @@ export const env = (config) => pure({}).env(config); * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da * @param {number | Pattern} [config.dc] DC offset prior to application + * @param {number | Pattern} [config.fxi] FX index to target * @param {string | Pattern} id ID to use for this modulator * @returns Pattern * @@ -3065,3 +3071,5 @@ export const bmod = (config) => pure({}).bmod(config); * s("hh*16").bank("tr909").transient("<-1:1 1:-1>") */ export const { transient } = registerControl(['transient', 'transsustain']); + +export const { FXrelease, FXrel, FXr, fxr } = registerControl('FXrelease', 'FXrel', 'FXr', 'fxr'); diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index 6f214386f..e6169399a 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -3721,3 +3721,19 @@ Pattern.prototype.phases = function (list) { export const phases = (list) => { return _ensureListPattern(list).as('phases'); }; + +/** + * Establishes an FX chain. Can be called by chaining .FX().FX().. + * calls and/or in a single .FX(, , ..) call. The , .. are _patterns_ which + * establish the controls of the given effect. See examples. + * @name FX + * @memberof Pattern + * @returns Pattern + */ +Pattern.prototype.FX = function (...effects) { + effects = effects.map(reify); + return this.withValue((v) => (vEff) => { + const currFX = v.FX ?? []; + return { ...v, FX: currFX.concat(vEff) }; + }).appLeft(parray(effects)); +}; diff --git a/packages/superdough/feedbackdelay.mjs b/packages/superdough/feedbackdelay.mjs index b8269bc02..387176134 100644 --- a/packages/superdough/feedbackdelay.mjs +++ b/packages/superdough/feedbackdelay.mjs @@ -5,19 +5,18 @@ if (typeof DelayNode !== 'undefined') { wet = Math.abs(wet); this.delayTime.value = time; - const feedbackGain = ac.createGain(); - feedbackGain.gain.value = Math.min(Math.abs(feedback), 0.995); - this.feedback = feedbackGain.gain; + this.feedbackGain = ac.createGain(); + this.feedbackGain.gain.value = Math.min(Math.abs(feedback), 0.995); + this.feedback = this.feedbackGain.gain; - const delayGain = ac.createGain(); - delayGain.gain.value = wet; - this.delayGain = delayGain; + this.delayGain = ac.createGain(); + this.delayGain.gain.value = wet; - this.connect(feedbackGain); - this.connect(delayGain); - feedbackGain.connect(this); + this.connect(this.feedbackGain); + this.connect(this.delayGain); + this.feedbackGain.connect(this); - this.connect = (target) => delayGain.connect(target); + this.connect = (target) => this.delayGain.connect(target); return this; } start(t) { diff --git a/packages/superdough/modulators.mjs b/packages/superdough/modulators.mjs index 7a1fe252d..2b6fcf334 100644 --- a/packages/superdough/modulators.mjs +++ b/packages/superdough/modulators.mjs @@ -85,8 +85,19 @@ const getTargetParamsForControl = (control, nodes, subControl) => { }; export const connectLFO = (id, params, nodeTracker) => { - const { rate = 1, sync, cps, cycle, control = 'lfo', subControl, depth = 1, depthabs, ...filteredParams } = params; - const { targetParams, paramName } = getTargetParamsForControl(control, nodeTracker, subControl); + const { + rate = 1, + sync, + cps, + cycle, + control = 'lfo', + subControl, + fxi = 'main', + depth = 1, + depthabs, + ...filteredParams + } = params; + const { targetParams, paramName } = getTargetParamsForControl(control, nodeTracker[fxi], subControl); if (!targetParams.length) return; let currentValue = targetParams[0].value; currentValue = currentValue === 0 ? 1 : currentValue; @@ -101,14 +112,14 @@ export const connectLFO = (id, params, nodeTracker) => { max, }; const lfoNode = getLfo(getAudioContext(), modParams); - nodeTracker[`lfo_${id}`] = [lfoNode]; + nodeTracker[0][`lfo_${id}`] = [lfoNode]; targetParams.forEach((t) => lfoNode.connect(t)); return lfoNode; }; export const connectEnvelope = (id, params, nodeTracker) => { - const { control, subControl, acurve, dcurve, rcurve, depth = 1, depthabs, ...filteredParams } = params; - const { targetParams, paramName } = getTargetParamsForControl(control, nodeTracker, subControl); + const { control, subControl, acurve, dcurve, rcurve, depth = 1, depthabs, fxi = 'main', ...filteredParams } = params; + const { targetParams, paramName } = getTargetParamsForControl(control, nodeTracker[fxi], subControl); if (!targetParams.length) return; let currentValue = targetParams[0].value; currentValue = currentValue === 0 ? 1 : currentValue; @@ -123,15 +134,15 @@ export const connectEnvelope = (id, params, nodeTracker) => { decayCurve: dcurve, releaseCurve: rcurve, }); - nodeTracker[`env_${id}`] = [envNode]; + nodeTracker[0][`env_${id}`] = [envNode]; targetParams.forEach((t) => envNode.connect(t)); return envNode; }; export const connectBusModulator = (params, nodeTracker, controller) => { const ac = getAudioContext(); - const { control, subControl, depth = 1, depthabs } = params; - const { targetParams, paramName } = getTargetParamsForControl(control, nodeTracker, subControl); + const { control, subControl, depth = 1, depthabs, fxi = 'main' } = params; + const { targetParams, paramName } = getTargetParamsForControl(control, nodeTracker[fxi], subControl); if (!targetParams.length) return { toCleanup: [] }; const signal = controller.getBus(params.bus); const dc = new ConstantSourceNode(ac, { offset: params.dc ?? 0 }); diff --git a/packages/superdough/reverbGen.mjs b/packages/superdough/reverbGen.mjs index bb050874c..0949a30d5 100644 --- a/packages/superdough/reverbGen.mjs +++ b/packages/superdough/reverbGen.mjs @@ -12,6 +12,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +import { releaseAudioNode } from './helpers.mjs'; + var reverbGen = {}; /** Generates a reverb impulse response. @@ -104,8 +106,8 @@ var applyGradualLowpass = function (input, lpFreqStart, lpFreqEnd, lpFreqEndAt, player.start(); context.oncomplete = function (event) { callback(event.renderedBuffer); - filter.disconnect(); - player.disconnect(); + releaseAudioNode(filter); + releaseAudioNode(player); }; context.startRendering(); diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 8a3e9f7b3..9e9ffa12d 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -7,7 +7,7 @@ This program is free software: you can redistribute it and/or modify it under th import './feedbackdelay.mjs'; import './reverb.mjs'; import './vowel.mjs'; -import { nanFallback, _mod, cycleToSeconds, pickAndRename } from './util.mjs'; +import { clamp, nanFallback, _mod, cycleToSeconds, pickAndRename } from './util.mjs'; import workletsUrl from './worklets.mjs?audioworklet'; import { createFilter, @@ -18,6 +18,7 @@ import { getLfo, getWorklet, releaseAudioNode, + webAudioTimeout, } from './helpers.mjs'; import { map } from 'nanostores'; import { logger } from './logger.mjs'; @@ -193,6 +194,8 @@ let defaultDefaultValues = { i: 1, velocity: 1, fft: 8, + tremolodepth: 1, + tremolophase: 0, }; const defaultDefaultDefaultValues = Object.freeze({ ...defaultDefaultValues }); @@ -402,8 +405,37 @@ function mapChannelNumbers(channels) { return (Array.isArray(channels) ? channels : [channels]).map((ch) => ch - 1); } +class Chain { + constructor(head) { + this.audioNodes = [head]; + this.tails = [head]; + } + connect(...nodes) { + nodes.forEach((node) => { + this.tails.forEach((tail) => { + tail.connect(node); + }); + }); + this.tails = nodes; + this.audioNodes.push(...nodes); + return this; + } + connectOne(idx, node) { + this.tails[idx].connect(node); + this.tails[idx] = node; + this.audioNodes.push(node); + return this; + } + releaseNodes() { + this.audioNodes.forEach((n) => releaseAudioNode(n)); + this.audioNodes = []; + this.tails = []; + } +} + export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) => { - let nodes = {}; + // mapping from main FX and numbered FX chains to nodes + const nodes = { main: {} }; // new: t is always expected to be the absolute target onset time const ac = getAudioContext(); const audioController = getSuperdoughAudioController(); @@ -432,44 +464,17 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) } // destructure let { - tremolo, - tremolosync, - tremolodepth = 1, - tremoloskew, - tremolophase = 0, - tremoloshape, s = getDefaultValue('s'), bank, source, - gain = getDefaultValue('gain'), postgain = getDefaultValue('postgain'), - density = getDefaultValue('density'), duckorbit, duckonset, duckattack, duckdepth, djf, - // filters - fanchor = getDefaultValue('fanchor'), - release = 0, - - //phaser - phaserrate, - phaserdepth = getDefaultValue('phaserdepth'), - phasersweep, - phasercenter, - // - coarse, - - crush, + release = 0.01, dry, - shape, - shapevol = getDefaultValue('shapevol'), - distort, - distortvol = getDefaultValue('distortvol'), - distorttype = getDefaultValue('distorttype'), - pan, - vowel, delay = getDefaultValue('delay'), delayfeedback = getDefaultValue('delayfeedback'), delaysync = getDefaultValue('delaysync'), @@ -486,16 +491,10 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) irspeed, irbegin, i = getDefaultValue('i'), - velocity = getDefaultValue('velocity'), analyze, // analyser wet fft = getDefaultValue('fft'), // fftSize 0 - 10 - compressor: compressorThreshold, - compressorRatio, - compressorKnee, - compressorAttack, - compressorRelease, - transient, - transsustain, + FX = [], + FXrelease, } = value; delaytime = delaytime ?? cycleToSeconds(delaysync, cps); @@ -510,18 +509,13 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) audioController.duck(duckorbit, t, duckonset, duckattack, duckdepth); } - gain = applyGainCurve(nanFallback(gain, 1)); postgain = applyGainCurve(postgain); - shapevol = applyGainCurve(shapevol); - distortvol = applyGainCurve(distortvol); delay = applyGainCurve(delay); - velocity = applyGainCurve(velocity); - tremolodepth = applyGainCurve(tremolodepth); busgain = applyGainCurve(busgain); - gain *= velocity; // velocity currently only multiplies with gain. it might do other things in the future const end = t + hapDuration; - const endWithRelease = end + release; + const fullRelease = Math.max(release, FXrelease ?? 0); + const endWithRelease = end + fullRelease; const chainID = Math.round(Math.random() * 1000000); // oldest audio nodes will be destroyed if maximum polyphony is exceeded @@ -535,8 +529,6 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) activeSoundSources.delete(chainID); } - const audioNodes = []; - if (['-', '~', '_'].includes(s)) { return; } @@ -549,19 +541,16 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) let sourceNode; if (source) { sourceNode = source(t, value, hapDuration, cps); - nodes['source'] = [sourceNode]; + nodes.main['source'] = [sourceNode]; } else if (getSound(s)) { const { onTrigger } = getSound(s); - const onEnded = () => { - audioNodes.forEach((n) => releaseAudioNode(n)); - activeSoundSources.delete(chainID); - }; + const onEnded = () => {}; const soundHandle = await onTrigger(t, value, onEnded, cps); if (soundHandle) { sourceNode = soundHandle.node; activeSoundSources.set(chainID, new WeakRef(soundHandle)); // allow GC - nodes = { ...nodes, ...soundHandle.nodes }; + nodes.main = { ...nodes.main, ...soundHandle.nodes }; } } else { throw new Error(`sound ${s} not found! Is it loaded?`); @@ -576,253 +565,339 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) logger('[webaudio] skip hap: still loading', ac.currentTime - t); return; } - const chain = []; // audio nodes that will be connected to each other sequentially - chain.push(sourceNode); - stretch !== undefined && chain.push(getWorklet(ac, 'phase-vocoder-processor', { pitchFactor: stretch })); - if (transient !== undefined) { - const transProcessor = getWorklet( - ac, - 'transient-processor', - {}, - { - processorOptions: { - attack: transient, - sustain: transsustain, - begin: t, - end: endWithRelease, + const chain = new Chain(sourceNode); // audio nodes that will be connected to each other sequentially + FX = [...FX, value]; // run through the FX chain and then run through all FX outside of it as well + for (let [idx, fx] of Object.entries(FX)) { + const key = idx == FX.length - 1 ? 'main' : idx; + nodes[key] ??= {}; + const fxNodes = nodes[key]; + let { + gain = getDefaultValue('gain'), + velocity = getDefaultValue('velocity'), + shapevol = getDefaultValue('shapevol'), + distorttype = getDefaultValue('distorttype'), + distortvol = getDefaultValue('distortvol'), + tremolodepth = getDefaultValue('tremolodepth'), + phaserdepth = getDefaultValue('phaserdepth'), + delay = getDefaultValue('delay'), + delayfeedback = getDefaultValue('delayfeedback'), + delaysync = getDefaultValue('delaysync'), + delaytime, + stretch = getDefaultValue('stretch'), + } = fx; + gain = applyGainCurve(nanFallback(gain, 1)); + shapevol = applyGainCurve(shapevol); + distortvol = applyGainCurve(distortvol); + velocity = applyGainCurve(velocity); + tremolodepth = applyGainCurve(tremolodepth); + gain *= velocity; // velocity currently only multiplies with gain. it might do other things in the future + delaytime = delaytime ?? cycleToSeconds(delaysync, cps); + + stretch !== undefined && chain.connect(getWorklet(ac, 'phase-vocoder-processor', { pitchFactor: stretch })); + + if (fx.transient !== undefined) { + const transProcessor = getWorklet( + ac, + 'transient-processor', + {}, + { + processorOptions: { + attack: fx.transient, + sustain: fx.transsustain, + begin: t, + end: endWithRelease, + }, }, - }, - ); - chain.push(transProcessor); - nodes['transient'] = transProcessor; - } + ); + chain.connect(transProcessor); + fxNodes['transient'] = transProcessor; + } - // gain stage - const initialGain = gainNode(gain); - nodes['gain'] = [initialGain]; - chain.push(initialGain); + // gain stage + const initialGain = gainNode(gain); + fxNodes['gain'] = [initialGain]; + chain.connect(initialGain); - // filter - const ftype = getFilterType(value.ftype); + // filter + const ftype = getFilterType(value.ftype); - const filt = (params) => createFilter(ac, t, end, params, cps, cycle); - if (value.cutoff !== undefined) { - const lpMap = { - frequency: 'cutoff', - q: 'resonance', - attack: 'lpattack', - decay: 'lpdecay', - sustain: 'lpsustain', - release: 'lprelease', - env: 'lpenv', - anchor: 'fanchor', - model: 'ftype', - drive: 'drive', - rate: 'lprate', - sync: 'lpsync', - depth: 'lpdepth', - depthfrequency: 'lpdepthfrequency', - shape: 'lpshape', - dcoffset: 'lpdc', - skew: 'lpskew', - }; - const lpParams = pickAndRename(value, lpMap); - lpParams.type = 'lowpass'; - const { filter: lpf1, lfo: lfo1 } = filt(lpParams); - nodes['lpf'] = [lpf1]; - nodes['lpf_lfo'] = [lfo1]; - chain.push(lpf1); - lfo1 && audioNodes.push(lfo1); - if (ftype === '24db') { - const { filter: lpf2, lfo: lfo2 } = filt(lpParams); - nodes['lpf'].push(lpf2); - nodes['lpf_lfo'].push(lfo2); - chain.push(lpf2); - lfo2 && audioNodes.push(lfo2); + const filt = (params) => createFilter(ac, t, end, params, cps, cycle); + if (fx.cutoff !== undefined) { + const lpMap = { + frequency: 'cutoff', + q: 'resonance', + attack: 'lpattack', + decay: 'lpdecay', + sustain: 'lpsustain', + release: 'lprelease', + env: 'lpenv', + anchor: 'fanchor', + model: 'ftype', + drive: 'drive', + rate: 'lprate', + sync: 'lpsync', + depth: 'lpdepth', + depthfrequency: 'lpdepthfrequency', + shape: 'lpshape', + dcoffset: 'lpdc', + skew: 'lpskew', + }; + const lpParams = pickAndRename(fx, lpMap); + lpParams.type = 'lowpass'; + const { filter: lpf1, lfo: lfo1 } = filt(lpParams); + fxNodes['lpf'] = [lpf1]; + fxNodes['lpf_lfo'] = [lfo1]; + chain.connect(lpf1); + lfo1 && chain.audioNodes.push(lfo1); + if (ftype === '24db') { + const { filter: lpf2, lfo: lfo2 } = filt(lpParams); + fxNodes['lpf'].push(lpf2); + fxNodes['lpf_lfo'].push(lfo2); + chain.connect(lpf2); + lfo2 && chain.audioNodes.push(lfo2); + } + } + + if (fx.hcutoff !== undefined) { + const hpMap = { + frequency: 'hcutoff', + q: 'hresonance', + attack: 'hpattack', + decay: 'hpdecay', + sustain: 'hpsustain', + release: 'hprelease', + env: 'hpenv', + anchor: 'fanchor', + model: 'ftype', + drive: 'drive', + rate: 'hprate', + sync: 'hpsync', + depth: 'hpdepth', + depthfrequency: 'hpdepthfrequency', + shape: 'hpshape', + dcoffset: 'hpdc', + skew: 'hpskew', + }; + const hpParams = pickAndRename(fx, hpMap); + hpParams.type = 'highpass'; + const { filter: hpf1, lfo: lfo1 } = filt(hpParams); + fxNodes['hpf'] = [hpf1]; + fxNodes['hpf_lfo'] = [lfo1]; + lfo1 && chain.audioNodes.push(lfo1); + chain.connect(hpf1); + if (ftype === '24db') { + const { filter: hpf2, lfo: lfo2 } = filt(hpParams); + fxNodes['hpf'].push(hpf2); + fxNodes['hpf_lfo'].push(lfo2); + chain.connect(hpf2); + lfo2 && chain.audioNodes.push(lfo2); + } + } + + if (fx.bandf !== undefined) { + const bpMap = { + frequency: 'bandf', + q: 'bandq', + attack: 'bpattack', + decay: 'bpdecay', + sustain: 'bpsustain', + release: 'bprelease', + env: 'bpenv', + anchor: 'fanchor', + model: 'ftype', + drive: 'drive', + rate: 'bprate', + sync: 'bpsync', + depth: 'bpdepth', + depthfrequency: 'bpdepthfrequency', + shape: 'bpshape', + dcoffset: 'bpdc', + skew: 'bpskew', + }; + const bpParams = pickAndRename(fx, bpMap); + bpParams.type = 'bandpass'; + const { filter: bpf1, lfo: lfo1 } = filt(bpParams); + fxNodes['bpf'] = [bpf1]; + fxNodes['bpf_lfo'] = [lfo1]; + chain.connect(bpf1); + lfo1 && chain.audioNodes.push(lfo1); + if (ftype === '24db') { + const { filter: bpf2, lfo: lfo2 } = filt(bpParams); + fxNodes['bpf'].push(bpf2); + fxNodes['bpf_lfo'].push(lfo2); + chain.connect(bpf2); + lfo2 && chain.audioNodes.push(lfo2); + } + } + + if (fx.vowel !== undefined) { + const vowelFilter = ac.createVowelFilter(fx.vowel); + fxNodes['vowel'] = [vowelFilter]; + chain.connect(vowelFilter); + } + + // effects + if (fx.coarse !== undefined) { + const coarseNode = getWorklet(ac, 'coarse-processor', { coarse: fx.coarse }); + fxNodes['coarse'] = [coarseNode]; + chain.connect(coarseNode); + } + if (fx.crush !== undefined) { + const crushNode = getWorklet(ac, 'crush-processor', { crush: fx.crush }); + fxNodes['crush'] = [crushNode]; + chain.connect(crushNode); + } + if (fx.shape !== undefined) { + const shapeNode = getWorklet(ac, 'shape-processor', { shape: fx.shape, postgain: shapevol }); + fxNodes['shape'] = [shapeNode]; + chain.connect(shapeNode); + } + if (fx.distort !== undefined) { + const distortNode = getDistortion(fx.distort, distortvol, distorttype); + fxNodes['distort'] = [distortNode]; + chain.connect(distortNode); + } + + let tremolo = fx.tremolo; + if (fx.tremolosync != null) { + tremolo = cps * fx.tremolosync; + } + + if (tremolo !== undefined) { + // Allow clipping of modulator for more dynamic possiblities, and to prevent speaker overload + // EX: a triangle waveform will clip like this /-\ when the depth is above 1 + const gain = Math.max(1 - tremolodepth, 0); + const amGain = new GainNode(ac, { gain }); + + const time = cycle / cps; + const lfo = getLfo(ac, { + skew: fx.tremoloskew ?? (fx.tremoloshape != null ? 0.5 : 1), + frequency: tremolo, + depth: tremolodepth, + time, + dcoffset: 0, + shape: fx.tremoloshape, + phaseoffset: fx.tremolophase, + min: 0, + max: 1, + curve: 1.5, + begin: t, + end: endWithRelease, + }); + fxNodes['tremolo'] = [lfo]; + fxNodes['tremolo_gain'] = [amGain]; + lfo.connect(amGain.gain); + chain.audioNodes.push(lfo); + chain.connect(amGain); + } + + if (fx.compressor !== undefined) { + const compressorNode = getCompressor( + ac, + fx.compressor, + fx.compressorRatio, + fx.compressorKnee, + fx.compressorAttack, + fx.compressorRelease, + ); + fxNodes['compressor'] = [compressorNode]; + chain.connect(compressorNode); + } + + // panning + if (fx.pan !== undefined) { + const panner = ac.createStereoPanner(); + panner.pan.value = 2 * fx.pan - 1; + chain.connect(panner); + } + // phaser + if (fx.phaserrate !== undefined && phaserdepth > 0) { + const { filterChain, lfo } = getPhaser( + t, + endWithRelease, + fx.phaserrate, + phaserdepth, + fx.phasercenter, + fx.phasersweep, + ); + fxNodes['phaser'] = [...filterChain]; + fxNodes['phaser_lfo'] = [lfo]; + filterChain.forEach((f) => chain.connect(f)); + chain.audioNodes.push(lfo); + } + // delay + if (delay > 0 && delaytime > 0 && delayfeedback > 0) { + const dry = gainNode(1); + delayfeedback = clamp(delayfeedback, 0, 0.98); + const delayNode = ac.createFeedbackDelay(1, delaytime, delayfeedback); + const wetDelay = gainNode(delay); + const dryDelay = gainNode(fx.dry ?? 1); + const sum = new GainNode(ac, { gain: 1, channelCount: 2, channelCountMode: 'explicit' }); + chain + .connect(dry) + .connect(dryDelay, delayNode) + .connectOne(1, wetDelay) // connect delayNode -> wetDelay + .connect(sum); + chain.audioNodes.push(delayNode.feedbackGain, delayNode.delayGain); + fxNodes['delay'] = [delayNode]; + fxNodes['delay_mix'] = [wetDelay]; + } + // reverb + if (fx.room > 0) { + let roomIR; + if (fx.ir !== undefined) { + let url; + let sample = getSound(fx.ir); + if (Array.isArray(sample)) { + url = sample.data.samples[fx.i % sample.data.samples.length]; + } else if (typeof sample === 'object') { + url = Object.values(sample.data.samples).flat()[fx.i % Object.values(sample.data.samples).length]; + } + roomIR = await loadBuffer(url, ac, fx.ir, 0); + } + const dry = gainNode(1); + const reverbNode = ac.createReverb( + fx.roomsize, + fx.roomfade, + fx.roomlp, + fx.roomdim, + roomIR, + fx.irspeed, + fx.irbegin, + ); + const wetReverb = gainNode(fx.room); + const dryReverb = gainNode(fx.dry ?? 1); + const sum = new GainNode(ac, { gain: 1, channelCount: 2, channelCountMode: 'explicit' }); + chain + .connect(dry) + .connect(dryReverb, reverbNode) + .connectOne(1, wetReverb) // connect reverbNode -> wetReverb + .connect(sum); + fxNodes['room'] = [reverbNode]; + fxNodes['room_mix'] = [wetReverb]; } } - if (value.hcutoff !== undefined) { - const hpMap = { - frequency: 'hcutoff', - q: 'hresonance', - attack: 'hpattack', - decay: 'hpdecay', - sustain: 'hpsustain', - release: 'hprelease', - env: 'hpenv', - anchor: 'fanchor', - model: 'ftype', - drive: 'drive', - rate: 'hprate', - sync: 'hpsync', - depth: 'hpdepth', - depthfrequency: 'hpdepthfrequency', - shape: 'hpshape', - dcoffset: 'hpdc', - skew: 'hpskew', - }; - const hpParams = pickAndRename(value, hpMap); - hpParams.type = 'highpass'; - const { filter: hpf1, lfo: lfo1 } = filt(hpParams); - nodes['hpf'] = [hpf1]; - nodes['hpf_lfo'] = [lfo1]; - lfo1 && audioNodes.push(lfo1); - chain.push(hpf1); - if (ftype === '24db') { - const { filter: hpf2, lfo: lfo2 } = filt(hpParams); - nodes['hpf'].push(hpf2); - nodes['hpf_lfo'].push(lfo2); - chain.push(hpf2); - lfo2 && audioNodes.push(lfo2); - } - } - - if (value.bandf !== undefined) { - const bpMap = { - frequency: 'bandf', - q: 'bandq', - attack: 'bpattack', - decay: 'bpdecay', - sustain: 'bpsustain', - release: 'bprelease', - env: 'bpenv', - anchor: 'fanchor', - model: 'ftype', - drive: 'drive', - rate: 'bprate', - sync: 'bpsync', - depth: 'bpdepth', - depthfrequency: 'bpdepthfrequency', - shape: 'bpshape', - dcoffset: 'bpdc', - skew: 'bpskew', - }; - const bpParams = pickAndRename(value, bpMap); - bpParams.type = 'bandpass'; - const { filter: bpf1, lfo: lfo1 } = filt(bpParams); - nodes['bpf'] = [bpf1]; - nodes['bpf_lfo'] = [lfo1]; - chain.push(bpf1); - lfo1 && audioNodes.push(lfo1); - if (ftype === '24db') { - const { filter: bpf2, lfo: lfo2 } = filt(bpParams); - nodes['bpf'].push(bpf2); - nodes['bpf_lfo'].push(lfo2); - chain.push(bpf2); - lfo2 && audioNodes.push(lfo2); - } - } - - if (vowel !== undefined) { - const vowelFilter = ac.createVowelFilter(vowel); - nodes['vowel'] = [vowelFilter]; - chain.push(vowelFilter); - } - - // effects - if (coarse !== undefined) { - const coarseNode = getWorklet(ac, 'coarse-processor', { coarse }); - nodes['coarse'] = [coarseNode]; - chain.push(coarseNode); - } - if (crush !== undefined) { - const crushNode = getWorklet(ac, 'crush-processor', { crush }); - nodes['crush'] = [crushNode]; - chain.push(crushNode); - } - if (shape !== undefined) { - const shapeNode = getWorklet(ac, 'shape-processor', { shape, postgain: shapevol }); - nodes['shape'] = [shapeNode]; - chain.push(shapeNode); - } - if (distort !== undefined) { - const distortNode = getDistortion(distort, distortvol, distorttype); - nodes['distort'] = [distortNode]; - chain.push(distortNode); - } - - if (tremolosync != null) { - tremolo = cps * tremolosync; - } - - if (value.wtPosSynced != null) { - value.wtPosRate /= cps; - } - - if (value.wtWarpSynced != null) { - value.wtWarpRate /= cps; - } - - if (tremolo !== undefined) { - // Allow clipping of modulator for more dynamic possiblities, and to prevent speaker overload - // EX: a triangle waveform will clip like this /-\ when the depth is above 1 - const gain = Math.max(1 - tremolodepth, 0); - const amGain = new GainNode(ac, { gain }); - - const time = cycle / cps; - const lfo = getLfo(ac, { - skew: tremoloskew ?? (tremoloshape != null ? 0.5 : 1), - frequency: tremolo, - depth: tremolodepth, - time, - dcoffset: 0, - shape: tremoloshape, - phaseoffset: tremolophase, - min: 0, - max: 1, - curve: 1.5, - begin: t, - end: endWithRelease, - }); - nodes['tremolo'] = [lfo]; - nodes['tremolo_gain'] = [amGain]; - lfo.connect(amGain.gain); - audioNodes.push(lfo); - chain.push(amGain); - } - - if (compressorThreshold !== undefined) { - const compressorNode = getCompressor( - ac, - compressorThreshold, - compressorRatio, - compressorKnee, - compressorAttack, - compressorRelease, - ); - nodes['compressor'] = [compressorNode]; - chain.push(compressorNode); - } - - // panning - if (pan !== undefined) { - const panner = ac.createStereoPanner(); - panner.pan.value = 2 * pan - 1; - chain.push(panner); - } - // phaser - if (phaserrate !== undefined && phaserdepth > 0) { - const { filterChain, lfo } = getPhaser(t, endWithRelease, phaserrate, phaserdepth, phasercenter, phasersweep); - nodes['phaser'] = [...filterChain]; - nodes['phaser_lfo'] = [lfo]; - chain.push(...filterChain); - audioNodes.push(lfo); + if (FXrelease !== undefined && FXrelease > release) { + const releaseNode = gainNode(1); + releaseNode.gain.setValueAtTime(1, end + release); + releaseNode.gain.linearRampToValueAtTime(0, endWithRelease); + chain.connect(releaseNode); } // last gain const post = new GainNode(ac, { gain: postgain }); - nodes['post'] = [post]; - chain.push(post); + nodes.main['post'] = [post]; + chain.connect(post); // delay if (delay > 0 && delaytime > 0 && delayfeedback > 0) { const delayNode = orbitBus.getDelay(delaytime, delayfeedback, t); - nodes['delay'] = [delayNode]; + nodes.main['delay'] = [delayNode]; const delaySend = orbitBus.sendDelay(post, delay); - nodes['delay_mix'] = [delaySend]; - audioNodes.push(delaySend); + nodes.main['delay_mix'] = [delaySend]; + chain.audioNodes.push(delaySend); } // reverb if (room > 0) { @@ -838,81 +913,92 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) roomIR = await loadBuffer(url, ac, ir, 0); } const roomNode = orbitBus.getReverb(roomsize, roomfade, roomlp, roomdim, roomIR, irspeed, irbegin); - nodes['room'] = [roomNode]; + nodes.main['room'] = [roomNode]; const reverbSend = orbitBus.sendReverb(post, room); - nodes['room_mix'] = [reverbSend]; - audioNodes.push(reverbSend); + nodes.main['room_mix'] = [reverbSend]; + chain.audioNodes.push(reverbSend); } if (bus != null) { const busNode = audioController.getBus(bus); const busSend = effectSend(post, busNode, busgain); - audioNodes.push(busSend); + chain.audioNodes.push(busSend); } if (djf != null) { const djfNode = orbitBus.getDjf(djf, t); - nodes['djf'] = [djfNode]; + nodes.main['djf'] = [djfNode]; } // analyser if (analyze && !(ac instanceof OfflineAudioContext)) { const analyserNode = getAnalyserById(analyze, 2 ** (fft + 5)); const analyserSend = effectSend(post, analyserNode, 1); - audioNodes.push(analyserSend); + chain.audioNodes.push(analyserSend); } if (dry != null) { dry = applyGainCurve(dry); const dryGain = new GainNode(ac, { gain: dry }); - chain.push(dryGain); + chain.connect(dryGain); orbitBus.connectToOutput(dryGain); } else { orbitBus.connectToOutput(post); } - // connect chain elements together - chain.slice(1).reduce((last, current) => last.connect(current), chain[0]); - audioNodes.push(...chain); - // finally, now that `nodes` is populated, set up modulators - if (value.lfo) { - for (const id of value.lfo.__ids) { - const params = value.lfo[id]; - const lfo = connectLFO( - id, - { - ...params, - cps, - cycle, - begin: t, - end: endWithRelease, - }, - nodes, - ); - lfo && audioNodes.push(lfo); + FX.forEach((fx, idx) => { + const key = idx === FX.length - 1 ? 'main' : idx; + if (fx.lfo) { + for (const id of fx.lfo.__ids) { + const params = fx.lfo[id]; + params.fxi ??= key; + const lfo = connectLFO( + id, + { + ...params, + cps, + cycle, + begin: t, + end: endWithRelease, + }, + nodes, + ); + lfo && chain.audioNodes.push(lfo); + } } - } - if (value.env) { - for (const id of value.env.__ids) { - const params = value.env[id]; - const env = connectEnvelope( - id, - { - ...params, - begin: t, - end: endWithRelease, - }, - nodes, - ); - env && audioNodes.push(env); + if (fx.env) { + for (const id of fx.env.__ids) { + const params = fx.env[id]; + params.fxi ??= key; + const env = connectEnvelope( + id, + { + ...params, + begin: t, + end: endWithRelease, + }, + nodes, + ); + env && chain.audioNodes.push(env); + } } - } - if (value.bmod) { - for (const id of value.bmod.__ids) { - const params = value.bmod[id]; - const { toCleanup } = connectBusModulator({ ...params, begin: t, end: endWithRelease }, nodes, controller); - audioNodes.push(...toCleanup); + if (fx.bmod) { + for (const id of fx.bmod.__ids) { + const params = fx.bmod[id]; + params.fxi ??= key; + const { toCleanup } = connectBusModulator({ ...params, begin: t, end: endWithRelease }, nodes, controller); + chain.audioNodes.push(...toCleanup); + } } - } + }); + webAudioTimeout( + ac, + () => { + chain.releaseNodes(); + activeSoundSources.delete(chainID); + }, + 0, + endWithRelease, + ); }; export const superdoughTrigger = (t, hap, ct, cps) => { From 882bcc513f12d62ab477bd336f09294ed528e2f4 Mon Sep 17 00:00:00 2001 From: Aria Date: Wed, 31 Dec 2025 15:17:06 -0600 Subject: [PATCH 63/73] Typos and some examples --- packages/core/pattern.mjs | 16 ++++++++ packages/superdough/modulators.mjs | 4 +- packages/superdough/superdough.mjs | 27 +++++++------ test/__snapshots__/examples.test.mjs.snap | 46 +++++++++++++++++++++++ 4 files changed, 79 insertions(+), 14 deletions(-) diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index e6169399a..f9c1852df 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -3729,6 +3729,22 @@ export const phases = (list) => { * @name FX * @memberof Pattern * @returns Pattern + * @example + * $: s("[sbd ]*4").dec(.4) + * .FX( + * phaser(0.5).gain(2), + * bpf(800), + * distort(1.3), + * room(0.2), + * delay(0.5).gain(1.25), + * distort(0.3), + * ).fxr(1.7) // sets release time of effects (like delay) + * @example + * $: s("saw").fm(0.5) + * .delay(0.3) // outer effects are applied *last* + * .FX(coarse(4)) // first coarse + * .FX(lpf(500).lpe(4).lpa(1).lpd(2)) // then lpf + * .FX(distort(1)) // then distort */ Pattern.prototype.FX = function (...effects) { effects = effects.map(reify); diff --git a/packages/superdough/modulators.mjs b/packages/superdough/modulators.mjs index 2b6fcf334..ea9067102 100644 --- a/packages/superdough/modulators.mjs +++ b/packages/superdough/modulators.mjs @@ -112,7 +112,7 @@ export const connectLFO = (id, params, nodeTracker) => { max, }; const lfoNode = getLfo(getAudioContext(), modParams); - nodeTracker[0][`lfo_${id}`] = [lfoNode]; + nodeTracker.main[`lfo_${id}`] = [lfoNode]; targetParams.forEach((t) => lfoNode.connect(t)); return lfoNode; }; @@ -134,7 +134,7 @@ export const connectEnvelope = (id, params, nodeTracker) => { decayCurve: dcurve, releaseCurve: rcurve, }); - nodeTracker[0][`env_${id}`] = [envNode]; + nodeTracker.main[`env_${id}`] = [envNode]; targetParams.forEach((t) => envNode.connect(t)); return envNode; }; diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 9e9ffa12d..7546bfab4 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -196,6 +196,7 @@ let defaultDefaultValues = { fft: 8, tremolodepth: 1, tremolophase: 0, + release: 0.01, }; const defaultDefaultDefaultValues = Object.freeze({ ...defaultDefaultValues }); @@ -473,7 +474,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) duckattack, duckdepth, djf, - release = 0.01, + release = getDefaultValue('release'), dry, delay = getDefaultValue('delay'), delayfeedback = getDefaultValue('delayfeedback'), @@ -544,7 +545,18 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) nodes.main['source'] = [sourceNode]; } else if (getSound(s)) { const { onTrigger } = getSound(s); - const onEnded = () => {}; + // We have to use onEnded because some sources (e.g. `sampler`) have + // an internal duration which is longer than `value.duration` + const onEnded = () => + webAudioTimeout( + ac, + () => { + chain.releaseNodes(); + activeSoundSources.delete(chainID); + }, + 0, + endWithRelease, + ); const soundHandle = await onTrigger(t, value, onEnded, cps); if (soundHandle) { @@ -566,7 +578,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) return; } - const chain = new Chain(sourceNode); // audio nodes that will be connected to each other sequentially + const chain = new Chain(sourceNode); // connection manager which tracks audio nodes for releasing FX = [...FX, value]; // run through the FX chain and then run through all FX outside of it as well for (let [idx, fx] of Object.entries(FX)) { const key = idx == FX.length - 1 ? 'main' : idx; @@ -990,15 +1002,6 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) } } }); - webAudioTimeout( - ac, - () => { - chain.releaseNodes(); - activeSoundSources.delete(chainID); - }, - 0, - endWithRelease, - ); }; export const superdoughTrigger = (t, hap, ct, cps) => { diff --git a/test/__snapshots__/examples.test.mjs.snap b/test/__snapshots__/examples.test.mjs.snap index 61ab11866..f6547bc61 100644 --- a/test/__snapshots__/examples.test.mjs.snap +++ b/test/__snapshots__/examples.test.mjs.snap @@ -565,6 +565,52 @@ exports[`runs examples > example "_euclidRot" example index 20 1`] = ` ] `; +exports[`runs examples > example "FX" example index 0 1`] = ` +[ + "[ 0/1 → 1/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 1/8 → 1/4 | s:hh decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 1/4 → 3/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 3/8 → 1/2 | s:bd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 1/2 → 5/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 5/8 → 3/4 | s:hh decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 3/4 → 7/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 7/8 → 1/1 | s:lt decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 1/1 → 9/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 9/8 → 5/4 | s:hh decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 5/4 → 11/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 11/8 → 3/2 | s:oh decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 3/2 → 13/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 13/8 → 7/4 | s:hh decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 7/4 → 15/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 15/8 → 2/1 | s:bd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 2/1 → 17/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 17/8 → 9/4 | s:hh decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 9/4 → 19/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 19/8 → 5/2 | s:bd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 5/2 → 21/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 21/8 → 11/4 | s:hh decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 11/4 → 23/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 23/8 → 3/1 | s:bd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 3/1 → 25/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 25/8 → 13/4 | s:hh decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 13/4 → 27/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 27/8 → 7/2 | s:lt decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 7/2 → 29/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 29/8 → 15/4 | s:hh decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 15/4 → 31/8 | s:sbd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", + "[ 31/8 → 4/1 | s:bd decay:0.4 FX:[{phaserrate:0.5 gain:2} {bandf:800} {distort:1.3} {room:0.2} {delay:0.5 gain:1.25} {distort:0.3}] FXrelease:1.7 ]", +] +`; + +exports[`runs examples > example "FX" example index 1 1`] = ` +[ + "[ 0/1 → 1/1 | s:saw fmi:0.5 delay:0.3 FX:[{coarse:4} {cutoff:500 lpenv:4 lpattack:1 lpdecay:2} {distort:1}] ]", + "[ 1/1 → 2/1 | s:saw fmi:0.5 delay:0.3 FX:[{coarse:4} {cutoff:500 lpenv:4 lpattack:1 lpdecay:2} {distort:1}] ]", + "[ 2/1 → 3/1 | s:saw fmi:0.5 delay:0.3 FX:[{coarse:4} {cutoff:500 lpenv:4 lpattack:1 lpdecay:2} {distort:1}] ]", + "[ 3/1 → 4/1 | s:saw fmi:0.5 delay:0.3 FX:[{coarse:4} {cutoff:500 lpenv:4 lpattack:1 lpdecay:2} {distort:1}] ]", +] +`; + exports[`runs examples > example "accelerate" example index 0 1`] = ` [ "[ 0/1 → 2/1 | s:sax accelerate:0 ]", From ebaf7624f98698d65e53f6706a62b8af8ac3e0aa Mon Sep 17 00:00:00 2001 From: Aria Date: Thu, 1 Jan 2026 12:02:54 -0600 Subject: [PATCH 64/73] Fix lfos for vowels, phasers; fix ir index; more informative error message --- packages/superdough/modulators.mjs | 5 ++++- packages/superdough/superdough.mjs | 13 +++++++------ packages/superdough/superdoughdata.mjs | 2 +- packages/superdough/vowel.mjs | 17 +++++++++++------ 4 files changed, 23 insertions(+), 14 deletions(-) diff --git a/packages/superdough/modulators.mjs b/packages/superdough/modulators.mjs index ea9067102..7d119a06b 100644 --- a/packages/superdough/modulators.mjs +++ b/packages/superdough/modulators.mjs @@ -62,7 +62,10 @@ const getTargetParamsForControl = (control, nodes, subControl) => { const lookupKey = subControl ? `${control}_${subControl}` : control; const targetInfo = getControlData(lookupKey) ?? getControlData(control); if (!targetInfo) { - errorLogger(new Error(`Could not find control data for target '${control}'`), 'superdough'); + errorLogger( + new Error(`Could not find control data for target '${control}'. It may not be modulatable.`), + 'superdough', + ); return { targetParams: [], paramName: control }; } const paramName = targetInfo.param; diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 7546bfab4..2e46b2d7e 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -597,6 +597,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) delaysync = getDefaultValue('delaysync'), delaytime, stretch = getDefaultValue('stretch'), + i = getDefaultValue('i'), } = fx; gain = applyGainCurve(nanFallback(gain, 1)); shapevol = applyGainCurve(shapevol); @@ -744,9 +745,9 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) } if (fx.vowel !== undefined) { - const vowelFilter = ac.createVowelFilter(fx.vowel); - fxNodes['vowel'] = [vowelFilter]; - chain.connect(vowelFilter); + const vowelNode = ac.createVowelFilter(fx.vowel); + fxNodes['vowel'] = vowelNode.filters; + chain.connect(vowelNode); } // effects @@ -839,7 +840,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) chain.audioNodes.push(lfo); } // delay - if (delay > 0 && delaytime > 0 && delayfeedback > 0) { + if (key !== 'main' && delay > 0 && delaytime > 0 && delayfeedback > 0) { const dry = gainNode(1); delayfeedback = clamp(delayfeedback, 0, 0.98); const delayNode = ac.createFeedbackDelay(1, delaytime, delayfeedback); @@ -856,7 +857,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) fxNodes['delay_mix'] = [wetDelay]; } // reverb - if (fx.room > 0) { + if (key !== 'main' && fx.room > 0) { let roomIR; if (fx.ir !== undefined) { let url; @@ -864,7 +865,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) if (Array.isArray(sample)) { url = sample.data.samples[fx.i % sample.data.samples.length]; } else if (typeof sample === 'object') { - url = Object.values(sample.data.samples).flat()[fx.i % Object.values(sample.data.samples).length]; + url = Object.values(sample.data.samples).flat()[i % Object.values(sample.data.samples).length]; } roomIR = await loadBuffer(url, ac, fx.ir, 0); } diff --git a/packages/superdough/superdoughdata.mjs b/packages/superdough/superdoughdata.mjs index 2dac194f1..e43df9eef 100644 --- a/packages/superdough/superdoughdata.mjs +++ b/packages/superdough/superdoughdata.mjs @@ -87,7 +87,7 @@ const CONTROL_TARGETS = { compressorRelease: { node: 'compressor', param: 'release' }, // PHASER - phaserrate: { node: 'phaser_lfo', param: 'rate' }, + phaserrate: { node: 'phaser_lfo', param: 'frequency' }, phasersweep: { node: 'phaser_lfo', param: 'depth' }, phasercenter: { node: 'phaser', param: 'frequency' }, phaserdepth: { node: 'phaser', param: 'Q' }, diff --git a/packages/superdough/vowel.mjs b/packages/superdough/vowel.mjs index bfc1c9fcd..8ecbf9d5c 100644 --- a/packages/superdough/vowel.mjs +++ b/packages/superdough/vowel.mjs @@ -1,3 +1,5 @@ +import { releaseAudioNode } from './helpers.mjs'; + // credits to webdirt: https://github.com/dktr0/WebDirt/blob/41342e81d6ad694a2310d491fef7b7e8b0929efe/js-src/Graph.js#L597 export var vowelFormant = { a: { freqs: [660, 1120, 2750, 3000, 3350], gains: [1, 0.5012, 0.0708, 0.0631, 0.0126], qs: [80, 90, 120, 130, 140] }, @@ -46,7 +48,8 @@ if (typeof GainNode !== 'undefined') { } const { gains, qs, freqs } = vowelFormant[letter]; this.makeupGain = ac.createGain(); - this.audioNodes = []; + this.filters = []; + this.gains = []; for (let i = 0; i < 5; i++) { const gain = ac.createGain(); gain.gain.value = gains[i]; @@ -56,9 +59,9 @@ if (typeof GainNode !== 'undefined') { filter.frequency.value = freqs[i]; super.connect(filter); filter.connect(gain); - this.audioNodes.push(filter); + this.filters.push(filter); gain.connect(this.makeupGain); - this.audioNodes.push(gain); + this.gains.push(gain); } this.makeupGain.gain.value = 8; // how much makeup gain to add? return this; @@ -67,11 +70,13 @@ if (typeof GainNode !== 'undefined') { this.makeupGain.connect(target); } disconnect() { - this.makeupGain.disconnect(); - this.audioNodes.forEach((n) => n.disconnect()); + releaseAudioNode(this.makeupGain); + this.filters.forEach(releaseAudioNode); + this.gains.forEach(releaseAudioNode); super.disconnect(); this.makeupGain = null; - this.audioNodes = null; + this.filters = null; + this.gains = null; } } From e54b9c3a32c245cd06392ba908c9974c51e2cd3b Mon Sep 17 00:00:00 2001 From: Aria Date: Thu, 1 Jan 2026 13:07:38 -0600 Subject: [PATCH 65/73] Fix formatting of docstring --- packages/core/pattern.mjs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index f9c1852df..02cf91881 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -3723,8 +3723,8 @@ export const phases = (list) => { }; /** - * Establishes an FX chain. Can be called by chaining .FX().FX().. - * calls and/or in a single .FX(, , ..) call. The , .. are _patterns_ which + * Establishes an FX chain. Can be called by chaining .FX(fx1).FX(fx2).. + * calls and/or in a single .FX(fx1, fx2, ..) call. The fx1, .. are _patterns_ which * establish the controls of the given effect. See examples. * @name FX * @memberof Pattern From 7b1e02e8cfbc71a00777d597bb6ec2089b0cbbc4 Mon Sep 17 00:00:00 2001 From: Aria Date: Fri, 2 Jan 2026 11:43:27 -0600 Subject: [PATCH 66/73] Make pan modulatable --- packages/superdough/superdough.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index 2e46b2d7e..c2515e324 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -821,6 +821,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) // panning if (fx.pan !== undefined) { const panner = ac.createStereoPanner(); + fxNodes['pan'] = [panner]; panner.pan.value = 2 * fx.pan - 1; chain.connect(panner); } From bf243c04b908c2ace4307fabb46396d114f14415 Mon Sep 17 00:00:00 2001 From: Aria Date: Sat, 3 Jan 2026 18:27:11 -0600 Subject: [PATCH 67/73] Make stretch modulatable --- packages/superdough/superdough.mjs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/superdough/superdough.mjs b/packages/superdough/superdough.mjs index c2515e324..33c1e404f 100644 --- a/packages/superdough/superdough.mjs +++ b/packages/superdough/superdough.mjs @@ -607,7 +607,11 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) gain *= velocity; // velocity currently only multiplies with gain. it might do other things in the future delaytime = delaytime ?? cycleToSeconds(delaysync, cps); - stretch !== undefined && chain.connect(getWorklet(ac, 'phase-vocoder-processor', { pitchFactor: stretch })); + if (stretch !== undefined) { + const phaseVocoder = getWorklet(ac, 'phase-vocoder-processor', { pitchFactor: stretch }); + chain.connect(phaseVocoder); + fxNodes['stretch'] = [phaseVocoder]; + } if (fx.transient !== undefined) { const transProcessor = getWorklet( From 58094973b06e3cdce02a91d17b0451b91ee08702 Mon Sep 17 00:00:00 2001 From: Forrest Cahoon Date: Sun, 4 Jan 2026 09:39:17 -0600 Subject: [PATCH 68/73] Fix doc link in @strudel/osc README.md --- packages/osc/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/osc/README.md b/packages/osc/README.md index 0a7bfedcf..c606daa59 100644 --- a/packages/osc/README.md +++ b/packages/osc/README.md @@ -46,4 +46,4 @@ all(osc) [open in repl](https://strudel.cc/#JDogcygiYmQqNCIpCgphbGwob3NjKQ%3D%3D) -You can read more about [how to use Superdirt with Strudel the Tutorial](https://strudel.cc/learn/input-output/#superdirt-api) +You can read more about [how to use Superdirt with Strudel](https://strudel.cc/learn/input-output/#oscsuperdirtstrudeldirt) in the tutorial. From b4b01944550e6f678aaa20b35237a39eb92ca02b Mon Sep 17 00:00:00 2001 From: Aria Date: Mon, 5 Jan 2026 23:17:40 -0600 Subject: [PATCH 69/73] Update docstrings and allow modulator ids to be patterns --- packages/core/controls.mjs | 31 +++++++++++++++++-------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/packages/core/controls.mjs b/packages/core/controls.mjs index b18a8dff6..8fef91294 100644 --- a/packages/core/controls.mjs +++ b/packages/core/controls.mjs @@ -2844,7 +2844,7 @@ registerSubControls('lfo', [ ['dcoffset', 'dc'], ['shape', 'sh'], ['skew', 'sk'], - ['curve'], + ['curve', 'cu'], ['sync', 's'], ['fxi'], ]); @@ -2872,7 +2872,7 @@ registerSubControls('bmod', [ ['fxi'], ]); -Pattern.prototype.modulate = function (type, config, id) { +Pattern.prototype.modulate = function (type, config, idPat) { config = { control: undefined, ...config }; const modulatorKeys = ['lfo', 'env', 'bmod']; if (!modulatorKeys.includes(type)) { @@ -2881,11 +2881,14 @@ Pattern.prototype.modulate = function (type, config, id) { } let output = this; let defaultValue = undefined; + // Copy value into a temporary `v` container and attach a single `id` (to be shared across + // each config entry). At the output we destructure and throw away the id + output = output.fmap((v) => (id) => ({ v, id })).appLeft(reify(idPat)); for (const [rawKey, value] of Object.entries(config)) { const key = getMainSubcontrolName(type, rawKey); const valuePat = reify(value); output = output - .fmap((v) => (c) => { + .fmap(({ v, id }) => (c) => { if (defaultValue === undefined) { // default control to the control set just before this in the chain // e.g. pat.gain(0.5).lfo({..}) will be a gain-LFO @@ -2900,17 +2903,17 @@ Pattern.prototype.modulate = function (type, config, id) { id ??= t.__ids.size; t[id] ??= { control: defaultValue }; t.__ids.add(id); // keeps track of insertion order - if (c === undefined) return v; + if (c === undefined) return { v, id }; if (key === 'control' || key === 'subControl') { t[id][key] = getControlName(c); } else { t[id][key] = c; } - return v; + return { v, id }; }) .appLeft(valuePat); } - return output; + return output.fmap(({ v }) => v); }; /** @@ -2925,15 +2928,15 @@ Pattern.prototype.modulate = function (type, config, id) { * * @name lfo * @param {Object} config LFO configuration. - * @param {string | Pattern} [config.control] Node to modulate. Aliases: t - * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc, p - * @param {number | Pattern} [config.rate] Modulation rate. Aliases: rate, r + * @param {string | Pattern} [config.control] Node to modulate. Aliases: c + * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc + * @param {number | Pattern} [config.rate] Modulation rate. Aliases: r * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da * @param {number | Pattern} [config.dcoffset] DC offset / bias for the waveform. Aliases: dc * @param {number | Pattern} [config.shape] Shape index. Aliases: sh * @param {number | Pattern} [config.skew] Skew amount. Aliases: sk - * @param {number | Pattern} [config.curve] Exponential curve amount. Aliases: c + * @param {number | Pattern} [config.curve] Exponential curve amount. Aliases: cu * @param {number | Pattern} [config.sync] Tempo-synced modulation rate. Aliases: s * @param {number | Pattern} [config.fxi] FX index to target * @param {string | Pattern} id ID to use for this modulator @@ -2978,8 +2981,8 @@ export const lfo = (config) => pure({}).lfo(config); * * @name env * @param {Object} config Envelope configuration. - * @param {string | Pattern} [config.control] Node to modulate. Aliases: t - * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc, p + * @param {string | Pattern} [config.control] Node to modulate. Aliases: c + * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da * @param {number | Pattern} [config.attack] Time to reach depth. Aliases: att, a @@ -3039,8 +3042,8 @@ export const env = (config) => pure({}).env(config); * @name bmod * @param {Object} config Bus modulation configuration. * @param {string | Pattern} [config.bus] Bus to get modulation signal from - * @param {string | Pattern} [config.control] Node to modulate. Aliases: t - * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc, p + * @param {string | Pattern} [config.control] Node to modulate. Aliases: c + * @param {string | Pattern} [config.subControl] Sub-control name to append to the control key. Aliases: sc * @param {number | Pattern} [config.depth] Relative modulation depth. Aliases: dep, dr * @param {number | Pattern} [config.depthabs] Absolute modulation depth. Aliases: da * @param {number | Pattern} [config.dc] DC offset prior to application From 959e8ac7bc43fece46261cf6c8258fbf040bdede Mon Sep 17 00:00:00 2001 From: yaxu Date: Tue, 6 Jan 2026 16:31:51 +0100 Subject: [PATCH 70/73] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 779769d57..59e2483b3 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ Live coding patterns on the web https://strudel.cc/ +https://codeberg.org/uzu/strudel/ *(Along with many other live coding projects, we have moved from Microsoft's Github platform to Codeberg for ethical reasons. Please don't fork the project back to github.)* - Try it here: - Docs: From 37dd8343989d1c75ef682205189f3f01bb25c7f9 Mon Sep 17 00:00:00 2001 From: yaxu Date: Tue, 6 Jan 2026 16:33:06 +0100 Subject: [PATCH 71/73] Update README.md --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 59e2483b3..b1208e7bb 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,17 @@ # strudel Live coding patterns on the web -https://strudel.cc/ -https://codeberg.org/uzu/strudel/ *(Along with many other live coding projects, we have moved from Microsoft's Github platform to Codeberg for ethical reasons. Please don't fork the project back to github.)* + - Try it here: - Docs: +- Source: https://codeberg.org/uzu/strudel/ + * Along with many other live coding projects, we have moved from Microsoft's Github platform to Codeberg for ethical reasons. **Please don't fork the project back to github**. - Technical Blog Post: - 1 Year of Strudel Blog Post: - 2 Years of Strudel Blog Post: + ## Running Locally After cloning the project, you can run the REPL locally: From f7175c05057a75302c9b0bf0dde2357f3a4de333 Mon Sep 17 00:00:00 2001 From: Aria Date: Thu, 8 Jan 2026 19:40:50 -0600 Subject: [PATCH 72/73] Properly handle subcontrols --- packages/superdough/modulators.mjs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/superdough/modulators.mjs b/packages/superdough/modulators.mjs index 7d119a06b..05674baa0 100644 --- a/packages/superdough/modulators.mjs +++ b/packages/superdough/modulators.mjs @@ -32,8 +32,9 @@ const getNodeParam = (node, name) => { const controlTargets = getSuperdoughControlTargets(); -const getControlData = (control) => { - return controlTargets[control.split('_')[0]]; +const getControlData = (control, subControl) => { + const controlNoIdx = control.split('_')[0]; + return controlTargets[`${controlNoIdx}_${subControl}`] ?? controlTargets[controlNoIdx]; }; const getRangeForParam = (paramName, currentValue) => { @@ -59,8 +60,7 @@ const clampWithWaveShaper = (modulator, min, max) => { }; const getTargetParamsForControl = (control, nodes, subControl) => { - const lookupKey = subControl ? `${control}_${subControl}` : control; - const targetInfo = getControlData(lookupKey) ?? getControlData(control); + const targetInfo = getControlData(control, subControl); if (!targetInfo) { errorLogger( new Error(`Could not find control data for target '${control}'. It may not be modulatable.`), From f6a43f1b1019c081c321bc7dc96b73dcb6167466 Mon Sep 17 00:00:00 2001 From: Aria Date: Thu, 8 Jan 2026 20:28:53 -0600 Subject: [PATCH 73/73] Make the scaling by freq in FM a separate node so that modulators behave like the fm control --- packages/superdough/helpers.mjs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/superdough/helpers.mjs b/packages/superdough/helpers.mjs index 8bd8b067b..460dd283c 100644 --- a/packages/superdough/helpers.mjs +++ b/packages/superdough/helpers.mjs @@ -461,10 +461,11 @@ export function applyFM(param, value, begin) { nodes[`fm_${idx}`] = [osc]; } const { input, output, freq, osc, toCleanup } = fms[idx]; - const g = gainNode(amt * freq); - io.push(isMod ? output.connect(g) : input); - cleanupOnEnd(osc, [...toCleanup, g]); - nodes[`fm_${idx}_gain`] = [g]; + const gAmt = gainNode(amt); + const gFreq = gainNode(freq); + io.push(isMod ? output.connect(gAmt).connect(gFreq) : input); + cleanupOnEnd(osc, [...toCleanup, gAmt, gFreq]); + nodes[`fm_${idx}_gain`] = [gAmt]; } if (!io[1]) { logger(