Compare commits

...

3 Commits

Author SHA1 Message Date
Tijmen Zwaan 1cb8abd2bb Split pattern.mjs into multiple files 2026-12-04 17:18:47 +01:00
Tijmen Zwaan 152b80ce44 Remove outdated snapshots 2026-12-04 17:18:47 +01:00
Felix Roos 24c3ca0489 hotfix: make @strudel/dough private for now (fails on publish) 2026-12-04 17:02:16 +01:00
28 changed files with 3469 additions and 3468 deletions
+4 -4
View File
@@ -1,22 +1,22 @@
import { queryCode, testCycles } from '../test/runtime.mjs';
import * as tunes from '../website/src/repl/tunes.mjs';
import { describe, bench } from 'vitest';
import { calculateSteps } from '../packages/core/index.mjs';
import { setCalculateSteps } from '../packages/core/index.mjs';
const tuneKeys = Object.keys(tunes);
describe('renders tunes', () => {
tuneKeys.forEach((key) => {
describe(key, () => {
calculateSteps(true);
setCalculateSteps(true);
bench(`+steps`, async () => {
await queryCode(tunes[key], testCycles[key] || 1);
});
calculateSteps(false);
setCalculateSteps(false);
bench(`-steps`, async () => {
await queryCode(tunes[key], testCycles[key] || 1);
});
calculateSteps(true);
setCalculateSteps(true);
});
});
});
+4 -4
View File
@@ -15,7 +15,7 @@ import {
Fraction,
sequence,
lcm,
__steps,
getCalculateSteps,
} from '@strudel/pattern';
export function createParam(names) {
@@ -3756,7 +3756,7 @@ export const { juxBy, juxby } = register(['juxBy', 'juxby'], function (by, func,
const left = pat.withValue((val) => Object.assign({}, val, { pan: elem_or(val, 'pan', 0.5) - by }));
const right = func(pat.withValue((val) => Object.assign({}, val, { pan: elem_or(val, 'pan', 0.5) + by })));
return stack(left, right).setSteps(__steps ? lcm(left._steps, right._steps) : undefined);
return stack(left, right).setSteps(getCalculateSteps() ? lcm(left._steps, right._steps) : undefined);
});
/**
@@ -3888,7 +3888,7 @@ export const chop = register('chop', function (n, pat) {
const func = function (o) {
return sequence(slice_objects.map((slice_o) => merge(o, slice_o)));
};
return pat.squeezeBind(func).setSteps(__steps ? Fraction(n).mulmaybe(pat._steps) : undefined);
return pat.squeezeBind(func).setSteps(getCalculateSteps() ? Fraction(n).mulmaybe(pat._steps) : undefined);
});
/**
@@ -3907,7 +3907,7 @@ export const striate = register('striate', function (n, pat) {
return pat
.set(slicePat)
._fast(n)
.setSteps(__steps ? Fraction(n).mulmaybe(pat._steps) : undefined);
.setSteps(getCalculateSteps() ? Fraction(n).mulmaybe(pat._steps) : undefined);
});
/**
+1
View File
@@ -1,6 +1,7 @@
{
"name": "@strudel/dough",
"version": "1.4.0",
"private": true,
"description": "dough synth integration for strudel",
"main": "dough.mjs",
"type": "module",
+4 -4
View File
@@ -1,10 +1,10 @@
import { describe, bench } from 'vitest';
import { calculateSteps } from '@strudel/pattern';
import { setCalculateSteps } from '@strudel/pattern';
import { mini } from '../index.mjs';
describe('mini', () => {
calculateSteps(true);
setCalculateSteps(true);
bench(
'+tactus',
() => {
@@ -13,7 +13,7 @@ describe('mini', () => {
{ time: 1000 },
);
calculateSteps(false);
setCalculateSteps(false);
bench(
'-tactus',
() => {
@@ -21,5 +21,5 @@ describe('mini', () => {
},
{ time: 1000 },
);
calculateSteps(true);
setCalculateSteps(true);
});
+6 -6
View File
@@ -1,11 +1,11 @@
import { describe, bench } from 'vitest';
import { calculateSteps, sequence, stack } from '../index.mjs';
import { setCalculateSteps, sequence, stack } from '../index.mjs';
const pat64 = sequence(...Array(64).keys());
describe('steps', () => {
calculateSteps(true);
setCalculateSteps(true);
bench(
'+tactus',
() => {
@@ -14,7 +14,7 @@ describe('steps', () => {
{ time: 1000 },
);
calculateSteps(false);
setCalculateSteps(false);
bench(
'-tactus',
() => {
@@ -25,7 +25,7 @@ describe('steps', () => {
});
describe('stack', () => {
calculateSteps(true);
setCalculateSteps(true);
bench(
'+tactus',
() => {
@@ -34,7 +34,7 @@ describe('stack', () => {
{ time: 1000 },
);
calculateSteps(false);
setCalculateSteps(false);
bench(
'-tactus',
() => {
@@ -43,4 +43,4 @@ describe('stack', () => {
{ time: 1000 },
);
});
calculateSteps(true);
setCalculateSteps(true);
+6 -6
View File
@@ -1,13 +1,13 @@
import { describe, bench } from 'vitest';
import { calculateSteps, rand, useRNG } from '../index.mjs';
import { setCalculateSteps, rand, useRNG } from '../index.mjs';
const testingResolution = 128;
const _generateRandomPattern = () => rand.iter(testingResolution).fast(testingResolution).firstCycle();
describe('old random', () => {
calculateSteps(true);
setCalculateSteps(true);
bench(
'+tactus',
() => {
@@ -22,7 +22,7 @@ describe('old random', () => {
},
);
calculateSteps(false);
setCalculateSteps(false);
bench(
'-tactus',
() => {
@@ -39,11 +39,11 @@ describe('old random', () => {
});
describe('random', () => {
calculateSteps(true);
setCalculateSteps(true);
bench('+tactus', _generateRandomPattern, { time: 1000 });
calculateSteps(false);
setCalculateSteps(false);
bench('-tactus', _generateRandomPattern, { time: 1000 });
});
calculateSteps(true);
setCalculateSteps(true);
+5 -2
View File
@@ -10,9 +10,12 @@ https://rohandrape.net/?t=hmt
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 <https://www.gnu.org/licenses/>.
*/
import { timeCat, register, silence, stack, pure, _morph } from './pattern.mjs';
import { silence } from './pattern-atoms.mjs';
import { register } from './register.mjs';
import { timeCat } from './pattern-stepwise.mjs';
import { _morph } from './pattern-structural-temporal.mjs';
import { rotate, flatten, splitAt, zipWith } from './util.mjs';
import Fraction, { lcm } from './fraction.mjs';
import Fraction from './fraction.mjs';
const left = function (n, x) {
const [ons, offs] = n;
+3 -1
View File
@@ -4,7 +4,9 @@ Copyright (C) 2025 Strudel contributors - see <https://codeberg.org/uzu/strudel/
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 <https://www.gnu.org/licenses/>.
*/
import { register, reify, Pattern } from './pattern.mjs';
import { Pattern } from './pattern.mjs';
import { reify } from './pattern-atoms.mjs';
import { register } from './register.mjs';
let timelines = {};
+11
View File
@@ -12,6 +12,17 @@ export * from './hap.mjs';
export * from './impure.mjs';
export * from './logger.mjs';
export * from './pattern.mjs';
export * from './register.mjs';
export * from './pattern-composers.mjs';
export * from './pattern-combiners.mjs';
export * from './pattern-chords.mjs';
export * from './pattern-structural-temporal.mjs';
export * from './pattern-numerical.mjs';
export * from './pattern-atoms.mjs';
export * from './pattern-multi.mjs';
export * from './pattern-misc.mjs';
export * from './pattern-stepwise.mjs';
export * from './pattern-deprecated.mjs';
export * from './pick.mjs';
export * from './signal.mjs';
export * from './state.mjs';
+81
View File
@@ -0,0 +1,81 @@
/*
pattern-atoms.mjs - The most basic pattern construction functions
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-atoms.mjs>
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 <https://www.gnu.org/licenses/>.
*/
import Hap from './hap.mjs';
import Fraction from './fraction.mjs';
import { Pattern, isPattern } from './pattern.mjs';
/**
* Does absolutely nothing, but with a given metrical 'steps'
* @name gap
* @tags generators
* @param {number} steps
* @returns {Pattern}
* @example
* gap(3) // "~@3"
*/
export const gap = (steps) => new Pattern(() => [], steps);
/**
* Does absolutely nothing..
* @name silence
* @tags generators
* @example
* silence // "~"
*/
export const silence = gap(1);
/**
* Like silence, but with a 'steps' (relative duration) of 0
* @name nothing
* @tags generators
* @example
* nothing
*/
export const nothing = gap(0);
/**
* A discrete value that repeats once per cycle.
*
* @global
* @param {number} value
* @tags generators
* @returns {Pattern}
* @example
* pure('e4') // "e4"
* @noAutocomplete
*/
export function pure(value) {
function query(state) {
return state.span.spanCycles.map((subspan) => new Hap(Fraction(subspan.begin).wholeCycle(), subspan, value));
}
const result = new Pattern(query, 1);
result.__pure = value;
return result;
}
let stringParser;
// parser is expected to turn a string into a pattern
// if set, the reify function will parse all strings with it
// intended to use with mini to automatically interpret all strings as mini notation
export const setStringParser = (parser) => (stringParser = parser);
/**
* Turns something into a pattern via pure(), unless it's already a pattern. If a string parser is set via {@link setStringParser}, that is used to reify strings.
* @param {*} thing
* @returns {Pattern}
*/
export function reify(thing) {
// Turns something into a pattern, unless it's already a pattern
if (isPattern(thing)) {
return thing;
}
if (stringParser && typeof thing === 'string') {
return stringParser(thing);
}
return pure(thing);
}
+70
View File
@@ -0,0 +1,70 @@
/*
pattern-chords.mjs - Functions related to chords/patterns of lists/lists of patterns
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-chords.mjs>
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 <https://www.gnu.org/licenses/>.
*/
import Hap from './hap.mjs';
import { Pattern } from './pattern.mjs';
import { reify } from './pattern-atoms.mjs';
import { register } from './register.mjs';
import { _mod } from './util.mjs';
//////////////////////////////////////////////////////////////////////
// functions relating to chords/patterns of lists/lists of patterns
// returns Array<Hap[]> where each list of haps satisfies eq
function groupHapsBy(eq, haps) {
let groups = [];
haps.forEach((hap) => {
const match = groups.findIndex(([other]) => eq(hap, other));
if (match === -1) {
groups.push([hap]);
} else {
groups[match].push(hap);
}
});
return groups;
}
// congruent haps = haps with equal spans
const congruent = (a, b) => a.spanEquals(b);
// Pattern<Hap<T>> -> Pattern<Hap<T[]>>
// returned pattern contains arrays of congruent haps
Pattern.prototype.collect = function () {
return this.withHaps((haps) =>
groupHapsBy(congruent, haps).map((_haps) => new Hap(_haps[0].whole, _haps[0].part, _haps, {})),
);
};
/**
* Selects indices in in stacked notes.
* @tags temporal
* @name arpWith
* @memberof Pattern.prototype
* @example
* note("<[c,eb,g]!2 [c,f,ab] [d,f,ab]>")
* .arpWith(haps => haps[2])
* */
export const arpWith = register('arpWith', (func, pat) => {
return pat
.collect()
.fmap((v) => reify(func(v)))
.innerJoin()
.withHap((h) => new Hap(h.whole, h.part, h.value.value, h.combineContext(h.value)));
});
/**
* Selects indices in in stacked notes.
* @tags temporal
* @name arp
* @memberof Pattern.prototype
* @example
* note("<[c,eb,g]!2 [c,f,ab] [d,f,ab]>")
* .arp("0 [0,2] 1 [0,2]")
* */
export const arp = register(
'arp',
(indices, pat) => pat.arpWith((haps) => reify(indices).fmap((i) => haps[_mod(i, haps.length)])),
false,
);
+263
View File
@@ -0,0 +1,263 @@
/*
pattern-combiners.mjs - Functions that combine multiple patterns into a single pattern
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-combiners.mjs>
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 <https://www.gnu.org/licenses/>.
*/
import Fraction, { lcm } from './fraction.mjs';
import { getCalculateSteps, Pattern } from './pattern.mjs';
import { reify, silence, pure } from './pattern-atoms.mjs';
import { _mod, flatten, curry } from './util.mjs';
import { errorLogger } from './logger.mjs';
/**
* The given items are played at the same time at the same length.
*
* @param {...any} pats
* @tags combiners
* @returns {Pattern}
* @name stack
* @memberof Pattern.prototype
* @synonyms polyrhythm, pr
* @example
* stack("g3", "b3", ["e4", "d4"]).note()
* // "g3,b3,[e4 d4]".note()
*
* @example
* // As a chained function:
* s("hh*4").stack(
* note("c4(5,8)")
* )
*/
export function stack(...pats) {
// Array test here is to avoid infinite recursions..
pats = pats.map((pat) => (Array.isArray(pat) ? sequence(...pat) : reify(pat)));
const query = (state) =>
flatten(
pats.map((pat) => {
if (state.controls.propagateExceptions) {
// In tests, we want exceptions to propagate to actually catch problems
// and to see the proper stack trace in the test result.
return pat.query(state);
} else {
try {
// An error occurring in one part of the stack should not break
// playback of the other parts of the stack.
return pat.query(state);
} catch (e) {
errorLogger(e);
return [];
}
}
}),
);
const result = new Pattern(query);
if (getCalculateSteps()) {
result._steps = lcm(...pats.map((pat) => pat._steps));
}
return result;
}
// aliases
export const polyrhythm = stack;
export const pr = stack;
/**
* Layers the result of the given function(s). Like `superimpose`, but without the original pattern:
* @param {...any} funcs
* @name layer
* @tags combiners
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* "<0 2 4 6 ~ 4 ~ 2 0!3 ~!5>*8"
* .layer(x=>x.add("0,2"))
* .scale('C minor').note()
*/
Pattern.prototype.layer = function (...funcs) {
return stack(...funcs.map((func) => func(this)));
};
/**
* Superimposes the result of the given function(s) on top of the original pattern:
* @param {...any} funcs
* @name superimpose
* @tags combiners
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* "<0 2 4 6 ~ 4 ~ 2 0!3 ~!5>*8"
* .superimpose(x=>x.add(2))
* .scale('C minor').note()
*/
Pattern.prototype.superimpose = function (...funcs) {
return this.stack(...funcs.map((func) => func(this)));
};
/**
* Takes a list of patterns, and returns a pattern of lists.
* @global
* @param {Pattern[]} pats
* @returns {Pattern}
* @tags temporal
*/
export function sequenceP(pats) {
let result = pure([]);
for (const pat of pats) {
result = result.bind((list) => pat.fmap((v) => list.concat([v])));
}
return result;
}
export function sequence(...pats) {
return fastcat(...pats);
}
/** Like **cat**, but the items are crammed into one cycle.
* @tags combiners
* @synonyms fastcat, sequence
* @example
* seq("e5", "b4", ["d5", "c5"]).note()
* // "e5 b4 [d5 c5]".note()
*
* @example
* // As a chained function:
* s("hh*4").seq(
* note("c4(5,8)")
* )
*/
export function seq(...pats) {
return fastcat(...pats);
}
/**
* Concatenation: combines a list of patterns, switching between them successively, one per cycle.
*
* @param {...any} pats
* @tags combiners
* @returns {Pattern}
* @synonyms cat
* @example
* slowcat("e5", "b4", ["d5", "c5"])
*
*/
export function slowcat(...pats) {
// Array test here is to avoid infinite recursions..
pats = pats.map((pat) => (Array.isArray(pat) ? fastcat(...pat) : reify(pat)));
if (!pats.length) {
return silence;
} else if (pats.length == 1) {
return pats[0];
}
const query = function (state) {
const span = state.span;
const pat_n = _mod(span.begin.sam(), pats.length);
const pat = pats[pat_n];
// A bit of maths to make sure that cycles from constituent patterns aren't skipped.
// For example if three patterns are slowcat-ed, the fourth cycle of the result should
// be the second (rather than fourth) cycle from the first pattern.
const offset = span.begin.floor().sub(span.begin.div(pats.length).floor());
return pat.withHapTime((t) => t.add(offset)).query(state.setSpan(span.withTime((t) => t.sub(offset))));
};
const steps = getCalculateSteps() ? lcm(...pats.map((x) => x._steps)) : undefined;
return new Pattern(query).splitQueries().setSteps(steps);
} /** Concatenation: combines a list of patterns, switching between them successively, one per cycle. Unlike slowcat, this version will skip cycles.
* @global
* @tags combiners
* @param {...any} pats The items to concatenate
* @returns {Pattern}
*/
export function slowcatPrime(...pats) {
if (!pats.length) {
return silence;
}
pats = pats.map(reify);
const query = function (state) {
const pat_n = _mod(Math.floor(state.span.begin), pats.length);
const pat = pats[pat_n];
return pat.query(state);
};
return new Pattern(query).splitQueries();
}
/** The given items are con**cat**enated, where each one takes one cycle.
*
* @tags combiners
* @param {...any} pats The items to concatenate
* @synonyms slowcat
* @returns {Pattern}
* @example
* cat("e5", "b4", ["d5", "c5"]).note()
* // "<e5 b4 [d5 c5]>".note()
*
* @example
* // As a chained function:
* s("hh*4").cat(
* note("c4(5,8)")
* )
*/
export function cat(...pats) {
return slowcat(...pats);
}
/**
* Similarly to `arrange`, allows you to arrange multiple patterns together over multiple cycles.
* Unlike `arrange`, you specify a start and stop time for each pattern rather than duration, which
* means that patterns can overlap.
* @param {...any} parts
* @tags combiners
* @returns {Pattern}
* @example
* seqPLoop(
* [0, 2, "bd(3,8)"],
* [1, 3, "cp(3,8)"]
* ).sound()
*/
export function seqPLoop(...parts) {
let total = Fraction(0);
const pats = [];
for (let part of parts) {
if (part.length == 2) {
part.unshift(total);
}
total = part[1];
}
return stack(
...parts.map(([start, stop, pat]) =>
pure(reify(pat)).compress(Fraction(start).div(total), Fraction(stop).div(total)),
),
)
.slow(total)
.innerJoin(); // or resetJoin or restartJoin ??
}
export function fastcat(...pats) {
let result = slowcat(...pats);
if (pats.length > 1) {
result = result._fast(pats.length);
result._steps = pats.length;
}
if (pats.length == 1 && pats[0].__steps_source) {
pats._steps = pats[0]._steps;
}
return result;
}
/**
* Turns a list of patterns into a single pattern which outputs list-values
*
* @param {Pattern[]} pats
* @name parray
* @tags combiners
* @returns {Pattern}
*/
export const parray = (pats) => {
const pack = (...xs) => xs;
let acc = pure(curry(pack, null, pats.length));
for (const p of pats) acc = acc.appBoth(reify(p));
return acc;
};
+518
View File
@@ -0,0 +1,518 @@
/*
pattern-composers.mjs - Pattern composer functions with multiple alignments
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-composers.mjs>
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 <https://www.gnu.org/licenses/>.
*/
import { isFraction } from './fraction.mjs';
import { Pattern } from './pattern.mjs';
import { reify } from './pattern-atoms.mjs';
import { sequence } from './pattern-combiners.mjs';
import { numeralArgs, _mod, curry } from './util.mjs';
import { unionWithObj } from './value.mjs';
//////////////////////////////////////////////////////////////////////
// compose matrix functions
const ALIGNMENTS = {
in(self, other, func) {
return self.fmap(func).appLeft(reify(other));
},
out(self, other, func) {
return self.fmap(func).appRight(reify(other));
},
mix(self, other, func) {
return self.fmap(func).appBoth(reify(other));
},
squeeze(self, other, func) {
const otherPat = reify(other);
return self.fmap((a) => otherPat.fmap((b) => func(a)(b))).squeezeJoin();
},
squeezeOut(self, other, func) {
const otherPat = reify(other);
return otherPat.fmap((a) => self.fmap((b) => func(b)(a))).squeezeJoin();
},
reset(self, other, func) {
const otherPat = reify(other);
return otherPat.fmap((b) => self.fmap((a) => func(a)(b))).resetJoin();
},
restart(self, other, func) {
const otherPat = reify(other);
return otherPat.fmap((b) => self.fmap((a) => func(a)(b))).restartJoin();
},
poly(self, other, func) {
const otherPat = reify(other);
return self.fmap((b) => otherPat.fmap((a) => func(a)(b))).polyJoin();
},
};
let DEFAULT_ALIGNMENT = 'in';
const ALIGNMENT_KEYS = Object.keys(ALIGNMENTS).map((how) => how.toLowerCase());
/**
* Sets the default method of combining events from two patterns (aka [alignment](https://strudel.cc/technical-manual/alignment/)) in Strudel.
* The default method is 'in', meaning that patterns to the left will (typically) dictate the event timings when combined with patterns to the right.
* By changing alignment to 'out', the opposite will happen. With 'mix', they will combine their event timings.
*
* Note that we say the _default_ method, because alignments can also be set explicitly with calls like
* 'add.mix', 'set.squeeze', etc.
*
* @param {string} alignment Default join method to use. Options: 'in', 'out', 'mix', 'squeeze', 'squeezeout', 'reset', 'restart', 'poly'
* @tags combiners
* @example
* setDefaultJoin('mix') // also try 'in', 'out', 'squeeze', etc.
* s("saw").vel("1 0.5").note("F A C E").delay("0 0.2 0.3")
*/
export const setDefaultJoin = (alignment) => {
alignment = alignment?.toLowerCase();
if (DEFAULT_ALIGNMENT !== alignment && ALIGNMENT_KEYS.includes(alignment)) {
DEFAULT_ALIGNMENT = alignment;
setupAlignments();
}
};
// pattern composers
const COMPOSERS = {
/**
* When called on a pattern `a`, with a input pattern `b` (`a.set(b)`),
* combines `a` and `b` such that anything defined in `b`
* and anything defined in `a` that is *not* defined in `b`
* will be in the resulting pattern.
*
* The structure is maintained from `a`,
* because the default pattern alignment is `in`,
* see the section on `Pattern Alignment`
* in the technical manual in the docs
*
* This is the inverse of `keep`
*
* See examples below
* @name set
* @param {Pattern} a
* @param {Pattern} b
* @returns {Pattern}
* @memberof Pattern.prototype
* @tags internals, combiners
* @example
* // because input pattern has `s` set,
* // it overrides the "sine" declared earlier
* note("c a f e").s("sine").set(s("triangle"))
*/
set: [(a, b) => b],
/**
* When called on a pattern `a`, with a input pattern `b` (`a.keep(b)`),
* combines `a` and `b` such that anything defined in `a`,
* and anything defined in `b` that is *not* defined in `a`
* will be in the resulting pattern
*
* The structure is maintained from `a`,
* because the default pattern alignment is `in`,
* see the section on `Pattern Alignment`
* in the technical manual in the docs
*
* This is the inverse of `set`
*
* See examples below
* @name keep
* @param {Pattern} a
* @memberof Pattern.prototype
* @returns {Pattern}
* @tags internals, combiners
* @example
* // notes, already defined, will stay "c a f e",
* // while "s", not defined, will be set to "piano"
* note("c a f e").keep(note("e f a c").s("piano"))
*/
keep: [(a) => a],
keepif: [(a, b) => (b ? a : undefined)],
// numerical functions
/**
*
* Assumes a pattern of numbers. Adds the given number to each item in the pattern.
* @name add
* @memberof Pattern.prototype
* @tags math
* @example
* // Here, the triad 0, 2, 4 is shifted by different amounts
* n("0 2 4".add("<0 3 4 0>")).scale("C:major")
* // Without add, the equivalent would be:
* // n("<[0 2 4] [3 5 7] [4 6 8] [0 2 4]>").scale("C:major")
* @example
* // You can also use add with notes:
* note("c3 e3 g3".add("<0 5 7 0>"))
* // Behind the scenes, the notes are converted to midi numbers:
* // note("48 52 55".add("<0 5 7 0>"))
*/
add: [numeralArgs((a, b) => a + b)], // support string concatenation
/**
*
* Like add, but the given numbers are subtracted.
* @name sub
* @memberof Pattern.prototype
* @tags math
* @example
* n("0 2 4".sub("<0 1 2 3>")).scale("C4:minor")
* // See add for more information.
*/
sub: [numeralArgs((a, b) => a - b)],
/**
*
* Multiplies each number by the given factor.
* @name mul
* @memberof Pattern.prototype
* @tags math
* @example
* "<1 1.5 [1.66, <2 2.33>]>*4".mul(150).freq()
*/
mul: [numeralArgs((a, b) => a * b)],
/**
*
* Divides each number by the given factor.
* @name div
* @memberof Pattern.prototype
* @tags math
*/
div: [numeralArgs((a, b) => a / b)],
/**
*
* Divides each number by the given factor and returns the remainder
* @name mod
* @memberof Pattern.prototype
* @tags math
*/
mod: [numeralArgs(_mod)],
/**
*
* Raises each number to the power of the given factor
* @name pow
* @memberof Pattern.prototype
* @tags math
*/
pow: [numeralArgs(Math.pow)],
/**
*
* Performs a bitwise `and` on each number and the given factor
* @name band
* @memberof Pattern.prototype
* @tags math
*/
band: [numeralArgs((a, b) => a & b)],
/**
*
* Performs a bitwise `or` on each number and the given factor
* @name bor
* @memberof Pattern.prototype
* @tags math
*/
bor: [numeralArgs((a, b) => a | b)],
/**
*
* Performs a bitwise `xor` on each number and the given factor
* @name bxor
* @memberof Pattern.prototype
* @tags math
*/
bxor: [numeralArgs((a, b) => a ^ b)],
/**
*
* Performs a bitwise `left shift` on each number by the given factor
* @name blshift
* @memberof Pattern.prototype
* @tags math
*/
blshift: [numeralArgs((a, b) => a << b)],
/**
*
* Performs a bitwise `right shift` on each number by the given factor
* @name brshift
* @memberof Pattern.prototype
* @tags math
*/
brshift: [numeralArgs((a, b) => a >> b)],
// TODO - force numerical comparison if both look like numbers?
/**
* performs a < b
* @name lt
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
lt: [(a, b) => a < b],
/**
* performs a > b
* @name gt
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
gt: [(a, b) => a > b],
/**
* performs a <= b
* @name lte
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
lte: [(a, b) => a <= b],
/**
* performs a >= b
* @name gte
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
gte: [(a, b) => a >= b],
/**
* performs a == b
* @name eq
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
eq: [(a, b) => a == b],
/**
* performs a === b (strictly equal)
* @name eqt
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
eqt: [(a, b) => a === b],
/**
* performs a != b
* @name ne
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
ne: [(a, b) => a != b],
/**
* performs a !== b (strictly not equal)
* @name net
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
net: [(a, b) => a !== b],
/**
* performs a && b
* @name and
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
and: [(a, b) => a && b],
/**
* performs a || b
* @name or
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
or: [(a, b) => a || b],
// bitwise ops
func: [(a, b) => b(a)],
};
const setupAlignments = () => {
// generate methods to do what and how
for (const [what, [op, preprocess]] of Object.entries(COMPOSERS)) {
// make plain version, e.g. pat._add(value) adds that plain value
// to all the values in pat
Pattern.prototype['_' + what] = function (value) {
return this.fmap((x) => op(x, value));
};
// make patternified monster version
Object.defineProperty(Pattern.prototype, what, {
// Set to configurable so we can update if the default alignment changes
configurable: true,
// a getter that returns a function, so 'pat' can be
// accessed by closures that are methods of that function..
get: function () {
const pat = this;
// wrap the 'in' function as default behaviour
const wrapper = (...other) => pat[what][DEFAULT_ALIGNMENT](...other);
// add methods to that function for each behaviour
for (const [alignment, alignmentFunc] of Object.entries(ALIGNMENTS)) {
wrapper[alignment.toLowerCase()] = function (...other) {
var howpat = pat;
other = sequence(other);
if (preprocess) {
howpat = preprocess(howpat);
other = preprocess(other);
}
var result;
// hack to remove undefs when doing 'keepif'
if (what === 'keepif') {
// avoid union, as we want to throw away the value of 'b' completely
result = alignmentFunc(howpat, other, (a) => (b) => op(a, b));
result = result.removeUndefineds();
} else {
result = alignmentFunc(howpat, other, (a) => (b) => _composeOp(a, b, op));
}
return result;
};
}
wrapper.squeezein = wrapper.squeeze;
return wrapper;
},
});
}
};
function _nonArrayObject(x) {
return !Array.isArray(x) && typeof x === 'object' && !isFraction(x);
}
function _composeOp(a, b, func) {
if (_nonArrayObject(a) || _nonArrayObject(b)) {
if (!_nonArrayObject(a)) {
a = { value: a };
}
if (!_nonArrayObject(b)) {
b = { value: b };
}
return unionWithObj(a, b, func);
}
return func(a, b);
}
// Make composers
setupAlignments();
// Default op to 'set', e.g. pat.squeeze(pat2) = pat.set.squeeze(pat2)
for (const alignment of ALIGNMENT_KEYS) {
Pattern.prototype[alignment] = function (...args) {
return this.set[alignment](args);
};
}
// binary composers
/**
* Applies the given structure to the pattern:
*
* @param {...any} args
* @tags temporal
* @returns {Pattern}
* @example
* note("c,eb,g")
* .struct("x ~ x ~ ~ x ~ x ~ ~ ~ x ~ x ~ ~")
* .slow(2)
*/
Pattern.prototype.struct = function (...args) {
return this.keepif.out(...args);
};
Pattern.prototype.structAll = function (...args) {
return this.keep.out(...args);
};
/**
* Returns silence when mask is 0 or "~"
*
* @param {...any} args
* @tags temporal
* @returns {Pattern}
* @example
* note("c [eb,g] d [eb,g]").mask("<1 [0 1]>")
*/
Pattern.prototype.mask = function (...args) {
return this.keepif.in(...args);
};
Pattern.prototype.maskAll = function (...args) {
return this.keep.in(...args);
};
/**
* Resets the pattern to the start of the cycle for each onset of the reset pattern.
*
* @param {...any} args
* @tags temporal
* @returns {Pattern}
* @example
* s("[<bd lt> sd]*2, hh*8").reset("<x@3 x(5,8)>")
*/
Pattern.prototype.reset = function (...args) {
return this.keepif.reset(...args);
};
Pattern.prototype.resetAll = function (...args) {
return this.keep.reset(...args);
};
/**
* Restarts the pattern for each onset of the restart pattern.
* While reset will only reset the current cycle, restart will start from cycle 0.
*
* @param {...any} args
* @tags temporal
* @returns {Pattern}
* @example
* s("[<bd lt> sd]*2, hh*8").restart("<x@3 x(5,8)>")
*/
Pattern.prototype.restart = function (...args) {
return this.keepif.restart(...args);
};
Pattern.prototype.restartAll = function (...args) {
return this.keep.restart(...args);
};
export const mask = curry((a, b) => reify(b).mask(a));
export const struct = curry((a, b) => reify(b).struct(a));
export const superimpose = curry((a, b) => reify(b).superimpose(...a));
export const withValue = curry((a, b) => reify(b).withValue(a));
export const bind = curry((a, b) => reify(b).bind(a));
export const innerBind = curry((a, b) => reify(b).innerBind(a));
export const outerBind = curry((a, b) => reify(b).outerBind(a));
export const squeezeBind = curry((a, b) => reify(b).squeezeBind(a));
export const stepBind = curry((a, b) => reify(b).stepBind(a));
export const polyBind = curry((a, b) => reify(b).polyBind(a));
// operators
export const set = curry((a, b) => reify(b).set(a));
export const keep = curry((a, b) => reify(b).keep(a));
export const keepif = curry((a, b) => reify(b).keepif(a));
export const add = curry((a, b) => reify(b).add(a));
export const sub = curry((a, b) => reify(b).sub(a));
export const mul = curry((a, b) => reify(b).mul(a));
export const div = curry((a, b) => reify(b).div(a));
export const mod = curry((a, b) => reify(b).mod(a));
export const pow = curry((a, b) => reify(b).pow(a));
export const band = curry((a, b) => reify(b).band(a));
export const bor = curry((a, b) => reify(b).bor(a));
export const bxor = curry((a, b) => reify(b).bxor(a));
export const blshift = curry((a, b) => reify(b).blshift(a));
export const brshift = curry((a, b) => reify(b).brshift(a));
export const lt = curry((a, b) => reify(b).lt(a));
export const gt = curry((a, b) => reify(b).gt(a));
export const lte = curry((a, b) => reify(b).lte(a));
export const gte = curry((a, b) => reify(b).gte(a));
export const eq = curry((a, b) => reify(b).eq(a));
export const eqt = curry((a, b) => reify(b).eqt(a));
export const ne = curry((a, b) => reify(b).ne(a));
export const net = curry((a, b) => reify(b).net(a));
export const and = curry((a, b) => reify(b).and(a));
export const or = curry((a, b) => reify(b).or(a));
export const func = curry((a, b) => reify(b).func(a));
+63
View File
@@ -0,0 +1,63 @@
/*
pattern-deprecated.mjs - Deprecated pattern functions for backwards compatibility
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-deprecated.mjs>
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 <https://www.gnu.org/licenses/>.
*/
import { Pattern } from './pattern.mjs';
import { register } from './register.mjs';
import {
zip,
stepalt,
stepcat,
shrinklist,
shrink,
expand,
extend,
tour,
contract,
drop,
take,
pace,
polymeter,
} from './pattern-stepwise.mjs';
/**
* Plays the pattern at the given cycles per minute.
* @tags temporal
* @deprecated
* @name cpm
* @memberof Pattern.prototype
* @example
* s("<bd sd>,hh*2").cpm(90) // = 90 bpm
*/
// this is redefined in repl.mjs, using the current cps as divisor
export const cpm = register('cpm', function (cpm, pat) {
return pat._fast(cpm / 60 / 1);
});
// Deprecated stepwise aliases
export const s_cat = stepcat;
export const s_alt = stepalt;
export const s_polymeter = polymeter;
Pattern.prototype.s_polymeter = Pattern.prototype.polymeter;
export const s_taper = shrink;
Pattern.prototype.s_taper = Pattern.prototype.shrink;
export const s_taperlist = shrinklist;
Pattern.prototype.s_taperlist = Pattern.prototype.shrinklist;
export const s_add = take;
Pattern.prototype.s_add = Pattern.prototype.take;
export const s_sub = drop;
Pattern.prototype.s_sub = Pattern.prototype.drop;
export const s_expand = expand;
Pattern.prototype.s_expand = Pattern.prototype.expand;
export const s_extend = extend;
Pattern.prototype.s_extend = Pattern.prototype.extend;
export const s_contract = contract;
Pattern.prototype.s_contract = Pattern.prototype.contract;
export const s_tour = tour;
Pattern.prototype.s_tour = Pattern.prototype.tour;
export const s_zip = zip;
Pattern.prototype.s_zip = Pattern.prototype.zip;
export const steps = pace;
Pattern.prototype.steps = Pattern.prototype.pace;
+195
View File
@@ -0,0 +1,195 @@
/*
pattern-misc.mjs - Miscellaneous pattern functions that should probably be moved to a different package
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-misc.mjs>
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 <https://www.gnu.org/licenses/>.
*/
import { Pattern } from './pattern.mjs';
import { pure, reify } from './pattern-atoms.mjs';
import { parray } from './pattern-combiners.mjs';
import { curry } from './util.mjs';
// These functions are related to superdough / kabelsalat / or general IO (e.g. sliders)
// This entire file should probably not live in the Pattern package,
// but move either to core or superdough.
/** exposes a custom value at query time. basically allows mutating state without evaluation
* @param {function():Pattern} accessor
* @returns {Pattern}
* @tags internals
*/
export const ref = (accessor) =>
pure(1)
.withValue(() => reify(accessor()))
.innerJoin();
const _ensureListPattern = (list) => {
if (Array.isArray(list)) {
return parray(list);
}
return reify(list);
};
/**
* Scale the magnitude of the harmonics of one of the core synths ('sine', 'tri', 'saw', ..)
*
* Can also be used to create a new synth via `s('user').partials(...)`
*
* @name partials
* @tags superdough
* @param {number[] | Pattern} list [0, 1] magnitudes for partials. 0th entry is the fundamental harmonic (i.e. DC offset is skipped)
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* s("user").seg(16).n(irand(8)).scale("A:major")
* .partials([1, 0, 1, 0, 0, 1])
* @example
* s("saw").seg(8).n(irand(12)).scale("G#:minor")
* .partials(binaryL(irand(256).add("1")))
*/
Pattern.prototype.partials = function (list) {
return this.withValue((v) => (l) => ({ ...v, partials: l })).appLeft(_ensureListPattern(list));
};
// Also create a top-level function
export const partials = (list) => {
return _ensureListPattern(list).as('partials');
};
/**
* Rotates the harmonics of one of the core synths ('sine', 'tri', 'saw', 'user', ..) by a list of phases
*
* @name phases
* @tags superdough
* @param {number[] | Pattern} list of [0, 1) phases for partials. 0th entry is the fundamental phase (i.e. DC offset is skipped)
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* // Phase cancellation
* s("saw").seg(8).n(irand(12)).scale("G#1:minor")
* .partials(partials([1, 1, 1]))
* .superimpose(x => x.phases([0.5, 0.5, 0.5]))
*/
Pattern.prototype.phases = function (list) {
return this.withValue((v) => (l) => ({ ...v, phases: l })).appLeft(_ensureListPattern(list));
};
// Also create a top-level function
export const phases = (list) => {
return _ensureListPattern(list).as('phases');
};
/**
* 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.
* @param {...any} effects
* @name FX
* @tags superdough
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* $: s("[sbd <hh [bd | lt | oh]>]*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);
return this.withValue((v) => (vEff) => {
const currFX = v.FX ?? [];
return { ...v, FX: currFX.concat(vEff) };
}).appLeft(parray(effects));
};
const _asArrayPattern = (pats) => {
const pack = (...xs) => xs;
let acc = pure(curry(pack, null, pats.length));
for (const p of pats) acc = acc.appLeft(p);
return acc;
};
/**
* Produces a [Kabelsalat](https://kabel.salat.dev/) modular sound engine.
* This can be used as either an effect (by including `audioin()` at the beginning
* of your kabel expression) or as a sound source (via any expression which doesn't
* start with `audioin()`).
*
* Some helpers you have available to you:
* * Strudel mini notation works fine in K(..) via "" or ``
* * More complex Strudel expressions (like "0 1 2".fast(4) or irand(24)) can be
* written by wrapping them in `S(..)` inside your Kabel code
* * We expose Strudel's note frequency under `sFreq` and Strudel's gate
* information under `sGate`
* * You can use more complex multi-line expressions (like `let x = a; let y = b; x.lpf(y);`)
* by wrapping them inside a function in K (see example).
*
* @name K
* @tags generators, superdough
* @param {KabelsalatExpression | Function} expr Kabelsalat graph definition
* @memberof Pattern.prototype
* @returns {Pattern}
*
* @example
* note("A c e".fast(4)).transpose("<0 2 4 6 8>")
* .scale("F:minor").transpose("12")
* .s("saw")
* .K(
* // audioin().mul(sGate.adsr(0.001, 0.3, 0, 0.2)) // as effect
* saw(saw(sFreq / "2!3 16").mul(8).add(sFreq).lag("0!3 0.1")).mul(0.3) // as source
* .mul(sGate.adsr(0, 0.15, 0.5, "0.1!3 1"))
* .lpf(sGate.adsr(0, 0.2, 0.3, 0.2).mul(1).add(0))
* .add(x => x.delay(S("0.3 0.2".fast(2))).mul(0.7))
* .add(x => x.delay("0.03 [0.08 0.01] 0.01 0.013").mul(0.77)).mul(0.7)
* .add(x => x.delay(.13).mul(0.7))
* .out()
* )
*
* @example
* n("<0 1 <2 3 2 4>>*16")
* .scale("G#2:minor").sometimes(x => x.transpose("12 | 24"))
* .K(() => {
* const att = S(rand.range(0, 0.05))
* const dec = S(rand.range(0.05, 0.2))
* let f = n(sFreq);
* const mod = sine(f).mul("0.1 | 0.2 | 0.3")
* .add("[[1.5 1] | 1 | 2 | 4 | [6 4@3]]*2")
* saw(f.mul(mod))
* .mul(sGate.ad(att, dec))
* .add(x => x.delay(0.4).mul(0.3))
* .out()
* }).fxr(1).room(0.3)
*/
/**
* Creates a worklet effect. Typically derived by writing K(...) in the REPL which will parse
* Kabelsalat code.
*
* @name worklet
* @param {string} src Source code of the worklet update function
* @param {...number | ...Pattern} inputs Worklet inputs
* @memberof Pattern.prototype
* @returns {Pattern}
* @noAutocomplete
*/
Pattern.prototype.worklet = function (src, ...inputs) {
inputs = inputs.map(reify);
return this.outerBind((v) => {
return _asArrayPattern(inputs).withValue((vInput) => {
const currInputs = v.workletInputs ?? [];
return { ...v, workletSrc: src, workletInputs: currInputs.concat(vInput) };
});
});
};
export const worklet = (...args) => pure({}).worklet(...args);
+32
View File
@@ -0,0 +1,32 @@
/*
pattern-multi.mjs - Assignment of multi-pattern functions to the pattern prototype
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-multi.mjs>
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 <https://www.gnu.org/licenses/>.
*/
import { Pattern } from './pattern.mjs';
import { slowcat, fastcat, cat, sequence, seq, stack } from './pattern-combiners.mjs';
import { stackLeft, stackRight, stackCenter, stackCentre, stackRepeat } from './pattern-stepwise.mjs';
// These are all top-level functions that combine an arbitrary number of patterns.
// Here we construct the Pattern member versions so they can be chained with other functions.
const multiPatternFunctions = {
stack,
stackLeft,
stackRight,
stackCenter,
stackCentre,
stackRepeat,
sequence,
seq,
cat,
fastcat,
slowcat,
};
for (const [name, func] of Object.entries(multiPatternFunctions)) {
Pattern.prototype[name] = function (...pats) {
return func(this, ...pats);
};
}
+145
View File
@@ -0,0 +1,145 @@
/*
pattern-numerical.mjs - Numerical pattern functions
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-numerical.mjs>
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 <https://www.gnu.org/licenses/>.
*/
import { register } from './register.mjs';
//////////////////////////////////////////////////////////////////////
// Numerical transformations
/**
* Assumes a numerical pattern. Returns a new pattern with all values rounded
* to the nearest integer.
* @name round
* @tags math
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* n("0.5 1.5 2.5".round()).scale("C:major")
*/
export const round = register('round', function (pat) {
return pat.asNumber().fmap((v) => Math.round(v));
});
/**
* Assumes a numerical pattern. Returns a new pattern with all values set to
* their mathematical floor. E.g. `3.7` replaced with to `3`, and `-4.2`
* replaced with `-5`.
* @name floor
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* note("42 42.1 42.5 43".floor())
*/
export const floor = register('floor', function (pat) {
return pat.asNumber().fmap((v) => Math.floor(v));
});
export const log2 = register('log2', (pat) => pat.asNumber().fmap((v) => Math.log2(v)));
/**
* Assumes a numerical pattern. Returns a new pattern with all values set to
* their mathematical ceiling. E.g. `3.2` replaced with `4`, and `-4.2`
* replaced with `-4`.
* @name ceil
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* note("42 42.1 42.5 43".ceil())
*/
export const ceil = register('ceil', function (pat) {
return pat.asNumber().fmap((v) => Math.ceil(v));
});
/**
* Assumes a numerical pattern, containing unipolar values in the range 0 ..
* 1. Returns a new pattern with values scaled to the bipolar range -1 .. 1
* @tags math
* @returns {Pattern}
* @noAutocomplete
* @memberof Pattern.prototype
*/
export const toBipolar = register('toBipolar', function (pat) {
return pat.fmap((x) => x * 2 - 1);
});
/**
* Assumes a numerical pattern, containing bipolar values in the range -1 .. 1
* Returns a new pattern with values scaled to the unipolar range 0 .. 1
* @tags math
* @returns {Pattern}
* @noAutocomplete
* @memberof Pattern.prototype
*/
export const fromBipolar = register('fromBipolar', function (pat) {
return pat.fmap((x) => (x + 1) / 2);
});
/**
* Assumes a numerical pattern, containing unipolar values in the range 0 .. 1.
* Returns a new pattern with values scaled to the given min/max range.
* Most useful in combination with continuous patterns.
* @name range
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* s("[bd sd]*2,hh*8")
* .cutoff(sine.range(500,4000))
*/
export const range = register('range', function (min, max, pat) {
return pat.mul(max - min).add(min);
});
/**
* Assumes a numerical pattern, containing unipolar values in the range 0 .. 1
* Returns a new pattern with values scaled to the given min/max range,
* following an exponential curve.
* @name rangex
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* s("[bd sd]*2,hh*8")
* .cutoff(sine.rangex(500,4000))
*/
export const rangex = register('rangex', function (min, max, pat) {
return pat._range(Math.log(min), Math.log(max)).fmap(Math.exp);
});
/**
* Assumes a numerical pattern, containing bipolar values in the range -1 .. 1
* Returns a new pattern with values scaled to the given min/max range.
* @name range2
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* s("[bd sd]*2,hh*8")
* .cutoff(sine2.range2(500,4000))
*/
export const range2 = register('range2', function (min, max, pat) {
return pat.fromBipolar()._range(min, max);
});
/**
* Allows dividing numbers via list notation using ":".
* Returns a new pattern with just numbers.
* @name ratio
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* ratio("1, 5:4, 3:2").mul(110)
* .freq().s("piano")
*/
export const ratio = register('ratio', (pat) =>
pat.fmap((v) => {
if (!Array.isArray(v)) {
return v;
}
return v.slice(1).reduce((acc, n) => acc / n, v[0]);
}),
);
+729
View File
@@ -0,0 +1,729 @@
/*
pattern-stepwise.mjs - Stepwise pattern functions
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern-stepwise.mjs>
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 <https://www.gnu.org/licenses/>.
*/
import Fraction, { lcm } from './fraction.mjs';
import TimeSpan from './timespan.mjs';
import Hap from './hap.mjs';
import { flatten, uniqsortr, pairs, removeUndefineds } from './util.mjs';
import { Pattern, getCalculateSteps } from './pattern.mjs';
import { reify, gap, silence, nothing } from './pattern-atoms.mjs';
import { register } from './register.mjs';
import { fastcat, slowcat, stack, sequence } from './pattern-combiners.mjs';
// Like register, but defaults to stepJoin
export function stepRegister(name, func, patternify = true, preserveSteps = false, join = (x) => x.stepJoin()) {
return register(name, func, patternify, preserveSteps, join);
}
//////////////////////////////////////////////////////////////////////
// Stepwise functions
Pattern.prototype.stepJoin = function () {
const pp = this;
const first_t = stepcat(..._retime(_slices(pp.queryArc(0, 1))))._steps;
const q = function (state) {
const shifted = pp.early(state.span.begin.sam());
const haps = shifted.query(state.setSpan(new TimeSpan(Fraction(0), Fraction(1))));
const pat = stepcat(..._retime(_slices(haps)));
return pat.query(state);
};
return new Pattern(q, first_t);
};
Pattern.prototype.stepBind = function (func) {
return this.fmap(func).stepJoin();
};
export function _retime(timedHaps) {
const occupied_perc = timedHaps.filter((t, pat) => pat.hasSteps).reduce((a, b) => a.add(b), Fraction(0));
const occupied_steps = removeUndefineds(timedHaps.map((t, pat) => pat._steps)).reduce(
(a, b) => a.add(b),
Fraction(0),
);
const total_steps = occupied_perc.eq(0) ? undefined : occupied_steps.div(occupied_perc);
function adjust(dur, pat) {
if (pat._steps === undefined) {
return [dur.mulmaybe(total_steps), pat];
}
return [pat._steps, pat];
}
return timedHaps.map((x) => adjust(...x));
}
export function _slices(haps) {
// slices evs = map (\s -> ((snd s - fst s), stack $ map value $ fit s evs))
// $ pairs $ sort $ nubOrd $ 0:1:concatMap (\ev -> start (part ev):stop (part ev):[]) evs
const breakpoints = flatten(haps.map((hap) => [hap.part.begin, hap.part.end]));
const unique = uniqsortr([Fraction(0), Fraction(1), ...breakpoints]);
const slicespans = pairs(unique);
return slicespans.map((s) => [
s[1].sub(s[0]),
stack(..._fitslice(new TimeSpan(...s), haps).map((x) => x.value.withHap((h) => h.setContext(h.combineContext(x))))),
]);
}
export function _fitslice(span, haps) {
return removeUndefineds(haps.map((hap) => _match(span, hap)));
}
export function _match(span, hap_p) {
const subspan = span.intersection(hap_p.part);
if (subspan == undefined) {
return undefined;
}
return new Hap(hap_p.whole, subspan, hap_p.value, hap_p.context);
}
function _sequenceCount(x) {
if (Array.isArray(x)) {
if (x.length == 0) {
return [silence, 0];
}
if (x.length == 1) {
return _sequenceCount(x[0]);
}
return [fastcat(...x.map((a) => _sequenceCount(a)[0])), x.length];
}
return [reify(x), 1];
}
export function _polymeterListSteps(steps, ...args) {
const seqs = args.map((a) => _sequenceCount(a));
if (seqs.length == 0) {
return silence;
}
if (steps == 0) {
steps = seqs[0][1];
}
const pats = [];
for (const seq of seqs) {
if (seq[1] == 0) {
continue;
}
if (steps == seq[1]) {
pats.push(seq[0]);
} else {
pats.push(seq[0]._fast(Fraction(steps).div(Fraction(seq[1]))));
}
}
return stack(...pats);
}
/**
* *Experimental*
*
* Aligns the steps of the patterns, creating polymeters. The patterns are repeated until they all fit the cycle. For example, in the below the first pattern is repeated twice, and the second is repeated three times, to fit the lowest common multiple of six steps.
* @param {...any} args
* @tags stepwise
* @synonyms pm
* @returns {Pattern}
* @example
* // The same as note("{c eb g, c2 g2}%6")
* polymeter("c eb g", "c2 g2").note()
*
*/
export function polymeter(...args) {
if (Array.isArray(args[0])) {
// Support old behaviour
return _polymeterListSteps(0, ...args);
}
// TODO currently ignoring arguments without steps...
args = args.filter((arg) => arg.hasSteps);
if (args.length == 0) {
return silence;
}
const steps = lcm(...args.map((x) => x._steps));
if (steps.eq(Fraction(0))) {
return nothing;
}
const result = stack(...args.map((x) => x.pace(steps)));
result._steps = steps;
return result;
}
export const pm = polymeter;
/** 'Concatenates' patterns like `fastcat`, but proportional to a number of steps per cycle.
* The steps can either be inferred from the pattern, or provided as a [length, pattern] pair.
* Has the alias `timecat`.
* @global
* @param {...any} timepats
* @name stepcat
* @tags stepwise
* @synonyms timeCat, timecat
* @returns {Pattern}
* @example
* stepcat([3,"e3"],[1, "g3"]).note()
* // the same as "e3@3 g3".note()
* @example
* stepcat("bd sd cp","hh hh").sound()
* // the same as "bd sd cp hh hh".sound()
*/
export function stepcat(...timepats) {
if (timepats.length === 0) {
return nothing;
}
const findsteps = (x) => (Array.isArray(x) ? x : [x._steps ?? 1, x]);
timepats = timepats.map(findsteps);
if (timepats.find((x) => x[0] === undefined)) {
const times = timepats.map((a) => a[0]).filter((x) => x !== undefined);
if (times.length === 0) {
return fastcat(...timepats.map((x) => x[1]));
}
if (times.length === timepats.length) {
return nothing;
}
const avg = times.reduce((a, b) => a.add(b), Fraction(0)).div(times.length);
for (let timepat of timepats) {
if (timepat[0] === undefined) {
timepat[0] = avg;
}
}
}
if (timepats.length == 1) {
const result = reify(timepats[0][1]);
return result.withSteps((_) => timepats[0][0]);
}
const total = timepats.map((a) => a[0]).reduce((a, b) => a.add(b), Fraction(0));
let begin = Fraction(0);
const pats = [];
for (const [time, pat] of timepats) {
if (Fraction(time).eq(0)) {
continue;
}
const end = begin.add(time);
pats.push(reify(pat)._compress(begin.div(total), end.div(total)));
begin = end;
}
const result = stack(...pats);
result._steps = total;
return result;
}
// Aliases for `stepcat`
export const timecat = stepcat;
export const timeCat = stepcat;
/**
* Allows to arrange multiple patterns together over multiple cycles.
* Takes a variable number of arrays with two elements specifying the number of cycles and the pattern to use.
*
* @global
* @param {...any} sections
* @tags combiners
* @returns {Pattern}
* @example
* arrange(
* [4, "<c a f e>(3,8)"],
* [2, "<g a>(5,8)"]
* ).note()
*/
export function arrange(...sections) {
const total = sections.reduce((sum, [cycles]) => sum + cycles, 0);
sections = sections.map(([cycles, section]) => [cycles, section.fast(cycles)]);
return stepcat(...sections).slow(total);
}
function _stackWith(func, pats) {
pats = pats.map((pat) => (Array.isArray(pat) ? sequence(...pat) : reify(pat)));
if (pats.length === 0) {
return silence;
}
if (pats.length === 1) {
return pats[0];
}
const [left, ...right] = pats.map((pat) => pat._steps);
const steps = getCalculateSteps() ? left.maximum(...right) : undefined;
return stack(...func(steps, pats));
}
/**
* The input patterns are aligned to the left, with silence padded to the shorter pattern(s) in the final steps if there's a stepcount disparity. See also `stackRight` and `stackCenter/stackCentre`
*
* @param {...any} pats
* @name stackLeft
* @tags temporal, stepwise, combiners
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* stackLeft("0 1 2 3", "3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
* @example
* // chainable
* "0 1 2 3".stackLeft("3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
*/
export function stackLeft(...pats) {
return _stackWith(
(steps, pats) => pats.map((pat) => (pat._steps.eq(steps) ? pat : stepcat(pat, gap(steps.sub(pat._steps))))),
pats,
);
}
/**
* The input patterns are aligned to the right, with silence padded to the shorter pattern(s) in the initial steps if there's a stepcount disparity. See also `stackLeft` and `stackCenter/stackCentre`
*
* @param {...any} pats
* @name stackRight
* @tags temporal, stepwise, combiners
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* stackRight("0 1 2 3", "3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
* @example
* // chainable
* "0 1 2 3".stackRight("3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
*/
export function stackRight(...pats) {
return _stackWith(
(steps, pats) => pats.map((pat) => (pat._steps.eq(steps) ? pat : stepcat(gap(steps.sub(pat._steps)), pat))),
pats,
);
}
/**
* The input patterns are aligned to the right, with silence padded to the shorter pattern(s) in the initial steps if there's a stepcount disparity. See also `stackLeft` and `stackRight`
* @param {...any} pats
* @name stackCenter
* @tags temporal, stepwise, combiners
* @synonyms stackCentre
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* stackCenter("0 1 2 3", "3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
* @example
* // chainable
* "0 1 2 3".stackCenter("3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
*/
export function stackCenter(...pats) {
return _stackWith(
(steps, pats) =>
pats.map((pat) => {
if (pat._steps.eq(steps)) {
return pat;
}
const g = gap(steps.sub(pat._steps).div(2));
return stepcat(g, pat, g);
}),
pats,
);
}
export function stackCentre(...pats) {
return stackCenter(...pats);
}
/**
* Shorthand for `pm(patterns).pace(m)` where m is the max step count in the input patterns
* @param {...any} pats
* @name stackRepeat
* @tags temporal, stepwise, combiners
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* stackRepeat("0 1 2 3", "3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
* @example
* // chainable
* "0 1 2 3".stackRepeat("3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
*/
export function stackRepeat(...pats) {
return stackBy(reify('repeat'), ...pats);
}
export function stackBy(by, ...pats) {
const [left, ...right] = pats.map((pat) => pat._steps);
const steps = left.maximum(...right);
const lookup = {
centre: stackCentre,
left: stackLeft,
right: stackRight,
expand: stack,
repeat: (...args) => polymeter(...args).steps(steps),
};
return by
.inhabit(lookup)
.fmap((func) => func(...pats))
.innerJoin()
.setSteps(steps);
}
/**
* *Experimental*
*
* Speeds a pattern up or down, to fit to the given number of steps per cycle.
* @tags stepwise
* @name pace
* @memberof Pattern.prototype
* @example
* sound("bd sd cp").pace(4)
* // The same as sound("{bd sd cp}%4") or sound("<bd sd cp>*4")
*/
export const pace = register('pace', function (targetSteps, pat) {
if (pat._steps === undefined) {
return pat;
}
if (pat._steps.eq(Fraction(0))) {
// avoid divide by zero..
return nothing;
}
return pat._fast(Fraction(targetSteps).div(pat._steps)).setSteps(targetSteps);
});
/**
* *Experimental*
*
* Concatenates patterns stepwise, according to an inferred 'steps per cycle'.
* Similar to `stepcat`, but if an argument is a list, the whole pattern will alternate between the elements in the list.
*
* @global
* @param {...any} groups
* @tags stepwise
* @returns {Pattern}
* @example
* stepalt(["bd cp", "mt"], "bd").sound()
* // The same as "bd cp bd mt bd".sound()
*/
export function stepalt(...groups) {
groups = groups.map((a) => (Array.isArray(a) ? a.map(reify) : [reify(a)]));
const cycles = lcm(...groups.map((x) => Fraction(x.length)));
let result = [];
for (let cycle = 0; cycle < cycles; ++cycle) {
result.push(...groups.map((x) => (x.length == 0 ? silence : x[cycle % x.length])));
}
result = result.filter((x) => x.hasSteps && x._steps > 0);
const steps = result.reduce((a, b) => a.add(b._steps), Fraction(0));
result = stepcat(...result);
result._steps = steps;
return result;
}
/**
* *Experimental*
*
* Takes the given number of steps from a pattern (dropping the rest).
* A positive number will take steps from the start of a pattern, and a negative number from the end.
* @tags stepwise
* @name take
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* "bd cp ht mt".take("2").sound()
* // The same as "bd cp".sound()
* @example
* "bd cp ht mt".take("1 2 3").sound()
* // The same as "bd bd cp bd cp ht".sound()
* @example
* "bd cp ht mt".take("-1 -2 -3").sound()
* // The same as "mt ht mt cp ht mt".sound()
*/
export const take = stepRegister('take', function (i, pat) {
if (!pat.hasSteps) {
return nothing;
}
if (pat._steps.lte(0)) {
return nothing;
}
i = Fraction(i);
if (i.eq(0)) {
return nothing;
}
const flip = i < 0;
if (flip) {
i = i.abs();
}
const frac = i.div(pat._steps);
if (frac.lte(0)) {
return nothing;
}
if (frac.gte(1)) {
return pat;
}
if (flip) {
return pat.zoom(Fraction(1).sub(frac), 1);
}
return pat.zoom(0, frac);
});
/**
* *Experimental*
*
* Drops the given number of steps from a pattern.
* A positive number will drop steps from the start of a pattern, and a negative number from the end.
* @name drop
* @tags stepwise
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* "tha dhi thom nam".drop("1").sound().bank("mridangam")
* @example
* "tha dhi thom nam".drop("-1").sound().bank("mridangam")
* @example
* "tha dhi thom nam".drop("0 1 2 3").sound().bank("mridangam")
* @example
* "tha dhi thom nam".drop("0 -1 -2 -3").sound().bank("mridangam")
*/
export const drop = stepRegister('drop', function (i, pat) {
if (!pat.hasSteps) {
return nothing;
}
i = Fraction(i);
if (i.lt(0)) {
return pat.take(pat._steps.add(i));
}
return pat.take(Fraction(0).sub(pat._steps.sub(i)));
});
/**
* *Experimental*
*
* `extend` is similar to `fast` in that it increases its density, but it also increases the step count
* accordingly. So `stepcat("a b".extend(2), "c d")` would be the same as `"a b a b c d"`, whereas
* `stepcat("a b".fast(2), "c d")` would be the same as `"[a b] [a b] c d"`.
* @name extend
* @tags stepwise
* @memberof Pattern.prototype
* @example
* stepcat(
* sound("bd bd - <cp hh>").extend(2),
* sound("bd - sd -")
* ).pace(8)
*/
export const extend = stepRegister('extend', function (factor, pat) {
return pat.fast(factor).expand(factor);
});
/**
* *Experimental*
*
* `replicate` is similar to `extend`, except that `replicate` will "replicate" the thing being extended. This will only differ from `extend` when the input pattern differs from cycle to cycle.
*
* @tags stepwise
* @memberof Pattern.prototype
* @example
* stepcat(
* sound("bd bd - <cp hh>").replicate(2),
* sound("bd - sd -")
* ).pace(8)
*/
export const replicate = stepRegister('replicate', function (factor, pat) {
return pat.repeatCycles(factor).fast(factor).expand(factor);
});
/**
* *Experimental*
*
* Expands the step size of the pattern by the given factor.
* @name expand
* @tags stepwise
* @memberof Pattern.prototype
* @example
* sound("tha dhi thom nam").bank("mridangam").expand("3 2 1 1 2 3").pace(8)
*/
export const expand = stepRegister('expand', function (factor, pat) {
return pat.withSteps((t) => t.mul(Fraction(factor)));
});
/**
* *Experimental*
*
* Contracts the step size of the pattern by the given factor. See also `expand`.
* @tags stepwise
* @name contract
* @memberof Pattern.prototype
* @example
* sound("tha dhi thom nam").bank("mridangam").contract("3 2 1 1 2 3").pace(8)
*/
export const contract = stepRegister('contract', function (factor, pat) {
return pat.withSteps((t) => t.div(Fraction(factor)));
});
Pattern.prototype.shrinklist = function (amount) {
const pat = this;
if (!pat.hasSteps) {
return [pat];
}
let [amountv, times] = Array.isArray(amount) ? amount : [amount, pat._steps];
amountv = Fraction(amountv);
if (times === 0 || amountv === 0) {
return [pat];
}
const fromstart = amountv > 0;
const ranges = [];
if (fromstart) {
const seg = Fraction(1).div(pat._steps).mul(amountv);
for (let i = 0; i < times; ++i) {
const s = seg.mul(i);
if (s.gt(1)) {
break;
}
ranges.push([s, 1]);
}
} else {
amountv = Fraction(0).sub(amountv);
const seg = Fraction(1).div(pat._steps).mul(amountv);
for (let i = 0; i < times; ++i) {
const e = Fraction(1).sub(seg.mul(i));
if (e.lt(0)) {
break;
}
ranges.push([Fraction(0), e]);
}
}
return ranges.map((x) => pat.zoom(...x));
};
export const shrinklist = (amount, pat) => pat.shrinklist(amount);
Pattern.prototype.growlist = function (amount) {
return this.shrinklist(amount).reverse();
};
export const growlist = (amount, pat) => pat.growlist(amount);
/**
* *Experimental*
*
* Progressively shrinks the pattern by 'n' steps until there's nothing left, or if a second value is given (using mininotation list syntax with `:`),
* that number of times.
* A positive number will progressively drop steps from the start of a pattern, and a negative number from the end.
* @tags stepwise
* @returns {Pattern}
* @name shrink
* @memberof Pattern.prototype
* @example
* "tha dhi thom nam".shrink("1").sound()
* .bank("mridangam")
* @example
* "tha dhi thom nam".shrink("-1").sound()
* .bank("mridangam")
* @example
* "tha dhi thom nam".shrink("1 -1").sound().bank("mridangam").pace(4)
* @example
* note("0 1 2 3 4 5 6 7".scale("C:ritusen")).sound("folkharp")
* .shrink("1 -1").pace(8)
*
*/
export const shrink = register(
'shrink',
function (amount, pat) {
if (!pat.hasSteps) {
return nothing;
}
const list = pat.shrinklist(amount);
const result = stepcat(...list);
// TODO is this calculation needed?
result._steps = list.reduce((a, b) => a.add(b._steps), Fraction(0));
return result;
},
true,
false,
(x) => x.stepJoin(),
);
/**
* *Experimental*
*
* Progressively grows the pattern by 'n' steps until the full pattern is played, or if a second value is given (using mininotation list syntax with `:`),
* that number of times.
* A positive number will progressively grow steps from the start of a pattern, and a negative number from the end.
* @tags stepwise
* @returns {Pattern}
* @name grow
* @memberof Pattern.prototype
* @example
* "tha dhi thom nam".grow("1").sound()
* .bank("mridangam")
* @example
* "tha dhi thom nam".grow("-1").sound()
* .bank("mridangam")
* @example
* "tha dhi thom nam".grow("1 -1").sound().bank("mridangam").pace(4)
* @example
* note("0 1 2 3 4 5 6 7".scale("C:ritusen")).sound("folkharp")
* .grow("1 -1").pace(8)
*/
export const grow = register(
'grow',
function (amount, pat) {
if (!pat.hasSteps) {
return nothing;
}
const list = pat.shrinklist(Fraction(0).sub(amount));
list.reverse();
const result = stepcat(...list);
// TODO is this calculation needed?
result._steps = list.reduce((a, b) => a.add(b._steps), Fraction(0));
return result;
},
true,
false,
(x) => x.stepJoin(),
);
/**
* *Experimental*
*
* Inserts a pattern into a list of patterns. On the first repetition it will be inserted at the end of the list, then moved backwards through the list
* on successive repetitions. The patterns are added together stepwise, with all repetitions taking place over a single cycle. Using `pace` to set the
* number of steps per cycle is therefore usually recommended.
*
* @param {Pattern} pat
* @param {...any} many
* @tags stepwise
* @returns {Pattern}
* @name tour
* @memberof Pattern.prototype
* @example
* "[c g]".tour("e f", "e f g", "g f e c").note()
* .sound("folkharp")
* .pace(8)
*/
export const tour = function (pat, ...many) {
return pat.tour(...many);
};
Pattern.prototype.tour = function (...many) {
return stepcat(
...[].concat(
...many.map((x, i) => [...many.slice(0, many.length - i), this, ...many.slice(many.length - i)]),
this,
...many,
),
);
};
/**
* *Experimental*
*
* 'zips' together the steps of the provided patterns. This can create a long repetition, taking place over a single, dense cycle.
* Using `pace` to set the number of steps per cycle is therefore usually recommended.
*
* @param {...any} pats
* @global
* @tags stepwise
* @returns {Pattern}
* @example
* zip("e f", "e f g", "g [f e] a f4 c").note()
* .sound("folkharp")
* .pace(8)
*/
export const zip = function (...pats) {
pats = pats.filter((pat) => pat.hasSteps);
const zipped = slowcat(...pats.map((pat) => pat._slow(pat._steps)));
const steps = lcm(...pats.map((x) => x._steps));
return zipped._fast(steps).setSteps(steps);
};
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -4,7 +4,9 @@ Copyright (C) 2024 Strudel contributors - see <https://codeberg.org/uzu/strudel/
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 <https://www.gnu.org/licenses/>.
*/
import { Pattern, reify, silence, register } from './pattern.mjs';
import { Pattern } from './pattern.mjs';
import { reify, silence } from './pattern-atoms.mjs';
import { register } from './register.mjs';
import { _mod, clamp, objectMap } from './util.mjs';
+118
View File
@@ -0,0 +1,118 @@
import { isPattern, Pattern } from './pattern.mjs';
import { reify } from './pattern-atoms.mjs';
import { sequence } from './pattern-combiners.mjs';
import { curry } from './util.mjs';
export const strudelScope = {};
/**
* Registers a new pattern method. The method is added to the Pattern class + the standalone function is returned from register.
*
* @tags functional
* @param {string | string[]} name name of the function, or an array of names to be used as synonyms
* @param {Function} func function with 1 or more params, where last is the current pattern
* @param {boolean} [patternify=false] defaults to true; if set to false, you will have more control over the arguments to `func` as they will be
* in their raw form and it will be up to you to patternify them and/or query them for values
* @param {boolean} [preserveSteps=false]
* @param {function(Pattern):Pattern} [join=(x) => x.innerJoin()]
* @returns {object}
* @example
* const vlpf = register('vlpf', (freq, pat) => {
* return pat.fmap((v) => ({...v, cutoff: freq * (v.velocity ?? 1) }));
* })
* s("saw").seg(8).velocity(rand).vlpf(800)
*
*/
export function register(name, func, patternify = true, preserveSteps = false, join = (x) => x.innerJoin()) {
if (isPattern(name)) {
throw new Error(
'Name argument for register is a pattern, try using single quotes (\'name\') instead of double quotes ("name")',
);
}
if (Array.isArray(name)) {
const result = {};
for (const name_item of name) {
result[name_item] = register(name_item, func, patternify, preserveSteps, join);
}
return result;
}
const arity = func.length;
var pfunc; // the patternified function
if (patternify) {
pfunc = function (...args) {
args = args.map(reify);
const pat = args[args.length - 1];
let result;
if (arity === 1) {
result = func(pat);
} else {
const firstArgs = args.slice(0, -1);
if (firstArgs.every((arg) => arg.__pure != undefined)) {
const pureArgs = firstArgs.map((arg) => arg.__pure);
const pureLocs = firstArgs.filter((arg) => arg.__pure_loc).map((arg) => arg.__pure_loc);
result = func(...pureArgs, pat);
result = result.withContext((context) => {
const locations = (context.locations || []).concat(pureLocs);
return { ...context, locations };
});
} else {
const [left, ...right] = firstArgs;
let mapFn = (...args) => {
return func(...args, pat);
};
mapFn = curry(mapFn, null, arity - 1);
result = join(right.reduce((acc, p) => acc.appLeft(p), left.fmap(mapFn)));
}
}
if (preserveSteps) {
result._steps = pat._steps;
}
return result;
};
} else {
pfunc = function (...args) {
args = args.map(reify);
const result = func(...args);
if (preserveSteps) {
result._steps = args[args.length - 1]._steps;
}
return result;
};
}
Pattern.prototype[name] = function (...args) {
// For methods that take a single argument (plus 'this'), allow
// multiple arguments but sequence them
if (arity === 2 && args.length !== 1) {
args = [sequence(...args)];
} else if (arity !== args.length + 1) {
throw new Error(`.${name}() expects ${arity - 1} inputs but got ${args.length}.`);
}
args = args.map(reify);
return pfunc(...args, this);
};
if (arity > 1) {
// There are patternified args, so lets make an unpatternified
// version, prefixed by '_'
Pattern.prototype['_' + name] = function (...args) {
const result = func(...args, this);
if (preserveSteps) {
result.setSteps(this._steps);
}
return result;
};
}
// toplevel functions get curried as well as patternified
// because pfunc uses spread args, we need to state the arity explicitly!
const curried = curry(pfunc, null, arity);
strudelScope[name] = curried;
return curried;
}
+67 -4
View File
@@ -4,13 +4,16 @@ Copyright (C) 2024 Strudel contributors - see <https://codeberg.org/uzu/strudel/
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 <https://www.gnu.org/licenses/>.
*/
import { Hap } from './hap.mjs';
import { Pattern, fastcat, pure, register, reify, silence, stack, sequenceP, isPattern } from './pattern.mjs';
import { _mod, noteToMidi } from './util.mjs';
import Fraction from './fraction.mjs';
import TimeSpan from './timespan.mjs';
import { Hap } from './hap.mjs';
import { Pattern, isPattern } from './pattern.mjs';
import { pure, reify, silence } from './pattern-atoms.mjs';
import { fastcat, stack, sequence, sequenceP } from './pattern-combiners.mjs';
import { register } from './register.mjs';
import { _mod, noteToMidi } from './util.mjs';
import { id, keyAlias, getCurrentKeyboardState } from './util.mjs';
import TimeSpan from './timespan.mjs';
/**
* A `signal` consisting of a constant value. Similar to `pure`, except that function
@@ -1085,6 +1088,9 @@ export function _keyDown(keyname) {
keyname = [keyname];
}
const keyState = getCurrentKeyboardState();
if (keyState === undefined) {
return false;
}
return keyname.every((x) => {
const keyName = keyAlias.get(x) ?? x;
return keyState[keyName];
@@ -1311,3 +1317,60 @@ function __smoothHap(time, hapA, hapB) {
const progress = time.sub(hapA.whole.begin).div(hapA.whole.end.sub(hapA.whole.begin));
return new Hap(hapA.whole, hapA.part, a + (b - a) * (progress.lt(0) ? 0 : progress), context);
}
/**
* Creates a pattern of numbers in base b from a number or pattern of numbers
* limited to d digits long from the right
*
* @name base
* @tags generators
* @param {number | Pattern | number[]} n - number to convert
* @param {number | Pattern} b - base to convert to (defaults to 10)
* @param {number | Pattern} d - max number of digits to produce for each n (defaults to 0 for all)
* @returns {number | Pattern}
* @example
* $: note(base("7175 543", 10, 3)).scale("c:major").s("saw")
* // $: note("1 7 5 5 4 3").scale("c:major").s("saw")
*/
export const base = (n, b = 10, d = 0) => {
if (Array.isArray(n)) {
n = sequence(n);
}
n = reify(n);
b = reify(b);
d = reify(d);
return d
.withValue((e) => {
return b
.withValue((c) => {
return n
.withValue((v) => {
let digits = [];
let value = v;
while (value > 0) {
digits.unshift(value % c);
value = Math.floor(value / c);
}
if (e) {
const l = digits.length;
if (l > e) {
digits = digits.slice(-1 * e);
}
/*
if (l < e){
for (let i = l; i < e; i++) {
digits.unshift("~");//0); //Would like to be padding this but ~- doesn't work
}
console.log("digits", digits);
}
*/
}
return sequence(digits);
})
.squeezeJoin();
})
.squeezeJoin();
})
.squeezeJoin();
};
+2 -1
View File
@@ -4,7 +4,8 @@ Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/
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 <https://www.gnu.org/licenses/>.
*/
import { fastcat, stack, slowcat, silence, pure } from '../pattern.mjs';
import { silence, pure } from '../pattern-atoms.mjs';
import { slowcat, fastcat, stack } from '../pattern-combiners.mjs';
import { describe, it, expect } from 'vitest';
import drawLine from '../drawLine.mjs';
+1 -1
View File
@@ -1,6 +1,6 @@
import { bjorklund } from '../euclid.mjs';
import { describe, expect, it } from 'vitest';
import { fastcat } from '../pattern.mjs';
import { fastcat } from '../pattern-combiners.mjs';
describe('bjorklund', () => {
it('should apply bjorklundlund to ons and steps', () => {
+2 -1
View File
@@ -52,13 +52,14 @@ import {
stackLeft,
stackRight,
stackCentre,
stackCenter,
stepcat,
sometimes,
expand,
arp,
} from '../index.mjs';
import { reify, stackCenter } from '../pattern.mjs';
import { reify } from '../pattern-atoms.mjs';
import { steady } from '../signal.mjs';
+1 -1
View File
@@ -4,7 +4,7 @@ Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/
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 <https://www.gnu.org/licenses/>.
*/
import { pure } from '../pattern.mjs';
import { pure } from '../pattern-atoms.mjs';
import {
_mod,
compose,
+2 -93
View File
@@ -1,98 +1,5 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`runs examples > example "__pick" example index 0 1`] = `
[
"[ 0/1 → 1/2 | note:g ]",
"[ 1/2 → 1/1 | note:a ]",
"[ 1/1 → 3/2 | note:e ]",
"[ 3/2 → 2/1 | note:f ]",
"[ 2/1 → 9/4 | note:f ]",
"[ 9/4 → 5/2 | note:g ]",
"[ 5/2 → 11/4 | note:f ]",
"[ 11/4 → 3/1 | note:g ]",
"[ 3/1 → 13/4 | note:f ]",
"[ 13/4 → 7/2 | note:g ]",
"[ 7/2 → 15/4 | note:f ]",
"[ 15/4 → 4/1 | note:g ]",
]
`;
exports[`runs examples > example "__pick" example index 1 1`] = `
[
"[ 0/1 → 1/2 | s:bd ]",
"[ 1/2 → 1/1 | s:sd ]",
"[ 1/1 → 3/2 | s:cp ]",
"[ 3/2 → 2/1 | s:cp ]",
"[ 2/1 → 5/2 | s:hh ]",
"[ 2/1 → 5/2 | s:bd ]",
"[ 5/2 → 3/1 | s:hh ]",
"[ 5/2 → 3/1 | s:sd ]",
"[ 3/1 → 7/2 | s:bd ]",
"[ 7/2 → 4/1 | s:sd ]",
]
`;
exports[`runs examples > example "__pick" example index 2 1`] = `
[
"[ 0/1 → 1/8 | s:bd ]",
"[ 3/8 → 1/2 | s:bd ]",
"[ 3/4 → 7/8 | s:bd ]",
"[ 1/1 → 9/8 | s:bd ]",
"[ 11/8 → 3/2 | s:bd ]",
"[ 7/4 → 15/8 | s:bd ]",
"[ 2/1 → 17/8 | s:bd ]",
"[ 2/1 → 5/2 | s:sd ]",
"[ 19/8 → 5/2 | s:bd ]",
"[ 5/2 → 3/1 | s:sd ]",
"[ 11/4 → 23/8 | s:bd ]",
"[ 3/1 → 7/2 | s:sd ]",
"[ 7/2 → 4/1 | s:sd ]",
]
`;
exports[`runs examples > example "__pick" example index 3 1`] = `
[
"[ 0/1 → 1/8 | s:bd ]",
"[ 3/8 → 1/2 | s:bd ]",
"[ 3/4 → 7/8 | s:bd ]",
"[ 1/1 → 9/8 | s:bd ]",
"[ 11/8 → 3/2 | s:bd ]",
"[ 7/4 → 15/8 | s:bd ]",
"[ 2/1 → 17/8 | s:bd ]",
"[ 2/1 → 5/2 | s:sd ]",
"[ 19/8 → 5/2 | s:bd ]",
"[ 5/2 → 3/1 | s:sd ]",
"[ 11/4 → 23/8 | s:bd ]",
"[ 3/1 → 7/2 | s:sd ]",
"[ 7/2 → 4/1 | s:sd ]",
]
`;
exports[`runs examples > example "__pick" example index 4 1`] = `
[
"[ 0/1 → 1/4 | s:bd speed:2 ]",
"[ 1/4 → 1/2 | s:cp speed:2 ]",
"[ 1/2 → 3/4 | s:bd speed:3 ]",
"[ 3/4 → 1/1 | s:cp speed:3 ]",
"[ 1/1 → 7/6 | s:bd speed:3 ]",
"[ 7/6 → 4/3 | s:cp speed:3 ]",
"[ 4/3 → 3/2 | s:bd speed:2 ]",
"[ 3/2 → 5/3 | s:cp speed:2 ]",
"[ 5/3 → 11/6 | s:bd speed:3 ]",
"[ 11/6 → 2/1 | s:cp speed:3 ]",
"[ 2/1 → 9/4 | s:bd speed:2 ]",
"[ 9/4 → 5/2 | s:cp speed:2 ]",
"[ 5/2 → 11/4 | s:bd speed:3 ]",
"[ 11/4 → 3/1 | s:cp speed:3 ]",
"[ 3/1 → 19/6 | s:bd speed:3 ]",
"[ 19/6 → 10/3 | s:cp speed:3 ]",
"[ 10/3 → 7/2 | s:bd speed:2 ]",
"[ 7/2 → 11/3 | s:cp speed:2 ]",
"[ 11/3 → 23/6 | s:bd speed:3 ]",
"[ 23/6 → 4/1 | s:cp speed:3 ]",
]
`;
exports[`runs examples > example "_euclidRot" example index 0 1`] = `
[
"[ 0/1 → 1/5 | note:c3 ]",
@@ -8769,6 +8676,8 @@ exports[`runs examples > example "note" example index 3 1`] = `
]
`;
exports[`runs examples > example "nothing" example index 0 1`] = `[]`;
exports[`runs examples > example "nrpnn" example index 0 1`] = `
[
"[ 0/1 → 1/1 | note:c4 nrpnn:[1 8] nrpv:123 midichan:1 ]",