Merge branch 'main' into fix-import
This commit is contained in:
commit
9774e9627b
80 changed files with 4017 additions and 723 deletions
|
|
@ -126,3 +126,10 @@ registerWidget('_scope', (id, options = {}, pat) => {
|
|||
const ctx = getCanvasWidget(id, options).getContext('2d');
|
||||
return pat.tag(id).scope({ ...options, ctx, id });
|
||||
});
|
||||
|
||||
registerWidget('_pitchwheel', (id, options = {}, pat) => {
|
||||
let _size = options.size || 200;
|
||||
options = { width: _size, height: _size, ...options, size: _size / 5 };
|
||||
const ctx = getCanvasWidget(id, options).getContext('2d');
|
||||
return pat.pitchwheel({ ...options, ctx, id });
|
||||
});
|
||||
|
|
|
|||
46
packages/core/bench/pattern.bench.mjs
Normal file
46
packages/core/bench/pattern.bench.mjs
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import { describe, bench } from 'vitest';
|
||||
|
||||
import { calculateTactus, sequence, stack } from '../index.mjs';
|
||||
|
||||
const pat64 = sequence(...Array(64).keys());
|
||||
|
||||
describe('tactus', () => {
|
||||
calculateTactus(true);
|
||||
bench(
|
||||
'+tactus',
|
||||
() => {
|
||||
pat64.iter(64).fast(64).firstCycle();
|
||||
},
|
||||
{ time: 1000 },
|
||||
);
|
||||
|
||||
calculateTactus(false);
|
||||
bench(
|
||||
'-tactus',
|
||||
() => {
|
||||
pat64.iter(64).fast(64).firstCycle();
|
||||
},
|
||||
{ time: 1000 },
|
||||
);
|
||||
});
|
||||
|
||||
describe('stack', () => {
|
||||
calculateTactus(true);
|
||||
bench(
|
||||
'+tactus',
|
||||
() => {
|
||||
stack(pat64, pat64, pat64, pat64, pat64, pat64, pat64, pat64).fast(64).firstCycle();
|
||||
},
|
||||
{ time: 1000 },
|
||||
);
|
||||
|
||||
calculateTactus(false);
|
||||
bench(
|
||||
'-tactus',
|
||||
() => {
|
||||
stack(pat64, pat64, pat64, pat64, pat64, pat64, pat64, pat64).fast(64).firstCycle();
|
||||
},
|
||||
{ time: 1000 },
|
||||
);
|
||||
});
|
||||
calculateTactus(true);
|
||||
|
|
@ -47,7 +47,7 @@ export function createParam(names) {
|
|||
return func;
|
||||
}
|
||||
|
||||
function registerControl(names, ...aliases) {
|
||||
export function registerControl(names, ...aliases) {
|
||||
const name = Array.isArray(names) ? names[0] : names;
|
||||
let bag = {};
|
||||
bag[name] = createParam(names);
|
||||
|
|
|
|||
|
|
@ -37,12 +37,17 @@ export class Cyclist {
|
|||
this.lastBegin = begin;
|
||||
const end = this.num_cycles_at_cps_change + num_cycles_since_cps_change;
|
||||
this.lastEnd = end;
|
||||
this.lastTick = phase;
|
||||
|
||||
if (phase < t) {
|
||||
// avoid querying haps that are in the past anyway
|
||||
console.log(`skip query: too late`);
|
||||
return;
|
||||
}
|
||||
|
||||
// query the pattern for events
|
||||
const haps = this.pattern.queryArc(begin, end, { _cps: this.cps });
|
||||
|
||||
this.lastTick = phase;
|
||||
|
||||
haps.forEach((hap) => {
|
||||
if (hap.hasOnset()) {
|
||||
const targetTime =
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ This program is free software: you can redistribute it and/or modify it under th
|
|||
|
||||
import Fraction from 'fraction.js';
|
||||
import { TimeSpan } from './timespan.mjs';
|
||||
import { removeUndefineds } from './util.mjs';
|
||||
|
||||
// Returns the start of the cycle.
|
||||
Fraction.prototype.sam = function () {
|
||||
|
|
@ -47,6 +48,10 @@ Fraction.prototype.eq = function (other) {
|
|||
return this.compare(other) == 0;
|
||||
};
|
||||
|
||||
Fraction.prototype.ne = function (other) {
|
||||
return this.compare(other) != 0;
|
||||
};
|
||||
|
||||
Fraction.prototype.max = function (other) {
|
||||
return this.gt(other) ? this : other;
|
||||
};
|
||||
|
|
@ -60,6 +65,22 @@ Fraction.prototype.min = function (other) {
|
|||
return this.lt(other) ? this : other;
|
||||
};
|
||||
|
||||
Fraction.prototype.mulmaybe = function (other) {
|
||||
return other !== undefined ? this.mul(other) : undefined;
|
||||
};
|
||||
|
||||
Fraction.prototype.divmaybe = function (other) {
|
||||
return other !== undefined ? this.div(other) : undefined;
|
||||
};
|
||||
|
||||
Fraction.prototype.addmaybe = function (other) {
|
||||
return other !== undefined ? this.add(other) : undefined;
|
||||
};
|
||||
|
||||
Fraction.prototype.submaybe = function (other) {
|
||||
return other !== undefined ? this.sub(other) : undefined;
|
||||
};
|
||||
|
||||
Fraction.prototype.show = function (/* excludeWhole = false */) {
|
||||
// return this.toFraction(excludeWhole);
|
||||
return this.s * this.n + '/' + this.d;
|
||||
|
|
@ -85,11 +106,24 @@ const fraction = (n) => {
|
|||
};
|
||||
|
||||
export const gcd = (...fractions) => {
|
||||
fractions = removeUndefineds(fractions);
|
||||
if (fractions.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return fractions.reduce((gcd, fraction) => gcd.gcd(fraction), fraction(1));
|
||||
};
|
||||
|
||||
export const lcm = (...fractions) => {
|
||||
return fractions.reduce((lcm, fraction) => lcm.lcm(fraction), fraction(1));
|
||||
fractions = removeUndefineds(fractions);
|
||||
if (fractions.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return fractions.reduce(
|
||||
(lcm, fraction) => (lcm === undefined || fraction === undefined ? undefined : lcm.lcm(fraction)),
|
||||
fraction(1),
|
||||
);
|
||||
};
|
||||
|
||||
fraction._original = Fraction;
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@
|
|||
},
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"bench": "vitest bench",
|
||||
"build": "vite build",
|
||||
"prepublishOnly": "pnpm build"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -10,12 +10,29 @@ import Hap from './hap.mjs';
|
|||
import State from './state.mjs';
|
||||
import { unionWithObj } from './value.mjs';
|
||||
|
||||
import { compose, removeUndefineds, flatten, id, listRange, curry, _mod, numeralArgs, parseNumeral } from './util.mjs';
|
||||
import {
|
||||
uniqsortr,
|
||||
removeUndefineds,
|
||||
flatten,
|
||||
id,
|
||||
listRange,
|
||||
curry,
|
||||
_mod,
|
||||
numeralArgs,
|
||||
parseNumeral,
|
||||
pairs,
|
||||
} from './util.mjs';
|
||||
import drawLine from './drawLine.mjs';
|
||||
import { logger } from './logger.mjs';
|
||||
|
||||
let stringParser;
|
||||
|
||||
let __tactus = true;
|
||||
|
||||
export const calculateTactus = function (x) {
|
||||
__tactus = x ? true : false;
|
||||
};
|
||||
|
||||
// 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
|
||||
|
|
@ -31,16 +48,16 @@ export class Pattern {
|
|||
*/
|
||||
constructor(query, tactus = undefined) {
|
||||
this.query = query;
|
||||
this._Pattern = true; // this property is used to detect if a pattern that fails instanceof Pattern is an instance of another Pattern
|
||||
this.__tactus = tactus; // in terms of number of beats per cycle
|
||||
this._Pattern = true; // this property is used to detectinstance of another Pattern
|
||||
this.tactus = tactus; // in terms of number of steps per cycle
|
||||
}
|
||||
|
||||
get tactus() {
|
||||
return this.__tactus ?? Fraction(1);
|
||||
return this.__tactus;
|
||||
}
|
||||
|
||||
set tactus(tactus) {
|
||||
this.__tactus = Fraction(tactus);
|
||||
this.__tactus = tactus === undefined ? undefined : Fraction(tactus);
|
||||
}
|
||||
|
||||
setTactus(tactus) {
|
||||
|
|
@ -48,6 +65,17 @@ export class Pattern {
|
|||
return this;
|
||||
}
|
||||
|
||||
withTactus(f) {
|
||||
if (!__tactus) {
|
||||
return this;
|
||||
}
|
||||
return new Pattern(this.query, this.tactus === undefined ? undefined : f(this.tactus));
|
||||
}
|
||||
|
||||
get hasTactus() {
|
||||
return this.tactus !== undefined;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Haskell-style functor, applicative and monadic operations
|
||||
|
||||
|
|
@ -130,7 +158,9 @@ export class Pattern {
|
|||
return span_a.intersection_e(span_b);
|
||||
};
|
||||
const result = pat_func.appWhole(whole_func, pat_val);
|
||||
result.tactus = lcm(pat_val.tactus, pat_func.tactus);
|
||||
if (__tactus) {
|
||||
result.tactus = lcm(pat_val.tactus, pat_func.tactus);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
|
@ -242,12 +272,12 @@ export class Pattern {
|
|||
}
|
||||
|
||||
outerBind(func) {
|
||||
return this.bindWhole((a) => a, func);
|
||||
return this.bindWhole((a) => a, func).setTactus(this.tactus);
|
||||
}
|
||||
|
||||
outerJoin() {
|
||||
// Flattens a pattern of patterns into a pattern, where wholes are
|
||||
// taken from inner haps.
|
||||
// taken from outer haps.
|
||||
return this.outerBind(id);
|
||||
}
|
||||
|
||||
|
|
@ -1137,24 +1167,24 @@ function _composeOp(a, b, func) {
|
|||
export const polyrhythm = stack;
|
||||
export const pr = stack;
|
||||
|
||||
export const pm = polymeter;
|
||||
export const pm = s_polymeter;
|
||||
|
||||
// methods that create patterns, which are added to patternified Pattern methods
|
||||
// TODO: remove? this is only used in old transpiler (shapeshifter)
|
||||
Pattern.prototype.factories = {
|
||||
pure,
|
||||
stack,
|
||||
slowcat,
|
||||
fastcat,
|
||||
cat,
|
||||
timecat,
|
||||
sequence,
|
||||
seq,
|
||||
polymeter,
|
||||
pm,
|
||||
polyrhythm,
|
||||
pr,
|
||||
};
|
||||
// Pattern.prototype.factories = {
|
||||
// pure,
|
||||
// stack,
|
||||
// slowcat,
|
||||
// fastcat,
|
||||
// cat,
|
||||
// timecat,
|
||||
// sequence,
|
||||
// seq,
|
||||
// polymeter,
|
||||
// pm,
|
||||
// polyrhythm,
|
||||
// pr,
|
||||
// };
|
||||
// the magic happens in Pattern constructor. Keeping this in prototype enables adding methods from the outside (e.g. see tonal.ts)
|
||||
|
||||
// Elemental patterns
|
||||
|
|
@ -1166,7 +1196,7 @@ Pattern.prototype.factories = {
|
|||
* @example
|
||||
* gap(3) // "~@3"
|
||||
*/
|
||||
export const gap = (tactus) => new Pattern(() => [], Fraction(tactus));
|
||||
export const gap = (tactus) => new Pattern(() => [], tactus);
|
||||
|
||||
/**
|
||||
* Does absolutely nothing..
|
||||
|
|
@ -1235,7 +1265,9 @@ export function stack(...pats) {
|
|||
pats = pats.map((pat) => (Array.isArray(pat) ? sequence(...pat) : reify(pat)));
|
||||
const query = (state) => flatten(pats.map((pat) => pat.query(state)));
|
||||
const result = new Pattern(query);
|
||||
result.tactus = lcm(...pats.map((pat) => pat.tactus));
|
||||
if (__tactus) {
|
||||
result.tactus = lcm(...pats.map((pat) => pat.tactus));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
|
@ -1248,20 +1280,20 @@ function _stackWith(func, pats) {
|
|||
return pats[0];
|
||||
}
|
||||
const [left, ...right] = pats.map((pat) => pat.tactus);
|
||||
const tactus = left.maximum(...right);
|
||||
const tactus = __tactus ? left.maximum(...right) : undefined;
|
||||
return stack(...func(tactus, pats));
|
||||
}
|
||||
|
||||
export function stackLeft(...pats) {
|
||||
return _stackWith(
|
||||
(tactus, pats) => pats.map((pat) => (pat.tactus.eq(tactus) ? pat : timecat(pat, gap(tactus.sub(pat.tactus))))),
|
||||
(tactus, pats) => pats.map((pat) => (pat.tactus.eq(tactus) ? pat : s_cat(pat, gap(tactus.sub(pat.tactus))))),
|
||||
pats,
|
||||
);
|
||||
}
|
||||
|
||||
export function stackRight(...pats) {
|
||||
return _stackWith(
|
||||
(tactus, pats) => pats.map((pat) => (pat.tactus.eq(tactus) ? pat : timecat(gap(tactus.sub(pat.tactus)), pat))),
|
||||
(tactus, pats) => pats.map((pat) => (pat.tactus.eq(tactus) ? pat : s_cat(gap(tactus.sub(pat.tactus)), pat))),
|
||||
pats,
|
||||
);
|
||||
}
|
||||
|
|
@ -1274,7 +1306,7 @@ export function stackCentre(...pats) {
|
|||
return pat;
|
||||
}
|
||||
const g = gap(tactus.sub(pat.tactus).div(2));
|
||||
return timecat(g, pat, g);
|
||||
return s_cat(g, pat, g);
|
||||
}),
|
||||
pats,
|
||||
);
|
||||
|
|
@ -1288,7 +1320,7 @@ export function stackBy(by, ...pats) {
|
|||
left: stackLeft,
|
||||
right: stackRight,
|
||||
expand: stack,
|
||||
repeat: (...args) => polymeterSteps(tactus, ...args),
|
||||
repeat: (...args) => s_polymeterSteps(tactus, ...args),
|
||||
};
|
||||
return by
|
||||
.inhabit(lookup)
|
||||
|
|
@ -1328,7 +1360,8 @@ export function slowcat(...pats) {
|
|||
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))));
|
||||
};
|
||||
return new Pattern(query).splitQueries();
|
||||
const tactus = __tactus ? lcm(...pats.map((x) => x.tactus)) : undefined;
|
||||
return new Pattern(query).splitQueries().setTactus(tactus);
|
||||
}
|
||||
|
||||
/** Concatenation: combines a list of patterns, switching between them successively, one per cycle. Unlike slowcat, this version will skip cycles.
|
||||
|
|
@ -1359,42 +1392,6 @@ export function cat(...pats) {
|
|||
return slowcat(...pats);
|
||||
}
|
||||
|
||||
/** Sequences patterns like `seq`, but each pattern has a length, relative to the whole.
|
||||
* This length can either be provided as a [length, pattern] pair, or inferred from
|
||||
* the pattern's 'tactus', generally inferred by the mininotation.
|
||||
* @return {Pattern}
|
||||
* @example
|
||||
* timecat([3,"e3"],[1, "g3"]).note()
|
||||
* // the same as "e3@3 g3".note()
|
||||
* @example
|
||||
* timecat("bd sd cp","hh hh").sound()
|
||||
* // the same as "bd sd cp hh hh".sound()
|
||||
*/
|
||||
export function timecat(...timepats) {
|
||||
const findtactus = (x) => (Array.isArray(x) ? x : [x.tactus, x]);
|
||||
timepats = timepats.map(findtactus);
|
||||
if (timepats.length == 1) {
|
||||
const result = reify(timepats[0][1]);
|
||||
result.tactus = timepats[0][0];
|
||||
return result;
|
||||
}
|
||||
|
||||
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) {
|
||||
const end = begin.add(time);
|
||||
pats.push(reify(pat)._compress(begin.div(total), end.div(total)));
|
||||
begin = end;
|
||||
}
|
||||
const result = stack(...pats);
|
||||
result.tactus = total;
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Deprecated alias for `timecat` */
|
||||
export const timeCat = timecat;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
|
|
@ -1409,7 +1406,7 @@ export const timeCat = timecat;
|
|||
export function arrange(...sections) {
|
||||
const total = sections.reduce((sum, [cycles]) => sum + cycles, 0);
|
||||
sections = sections.map(([cycles, section]) => [cycles, section.fast(cycles)]);
|
||||
return timecat(...sections).slow(total);
|
||||
return s_cat(...sections).slow(total);
|
||||
}
|
||||
|
||||
export function fastcat(...pats) {
|
||||
|
|
@ -1426,30 +1423,6 @@ export function sequence(...pats) {
|
|||
return fastcat(...pats);
|
||||
}
|
||||
|
||||
/**
|
||||
* Concatenates patterns stepwise, according to their 'tactus'.
|
||||
* Similar to `timecat`, but if an argument is a list, the whole pattern will be repeated for each element in the list.
|
||||
*
|
||||
* @return {Pattern}
|
||||
* @example
|
||||
* stepcat(["bd cp", "mt"], "bd").sound()
|
||||
*/
|
||||
export function stepcat(...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.tactus > 0);
|
||||
const tactus = result.reduce((a, b) => a.add(b.tactus), Fraction(0));
|
||||
result = timecat(...result);
|
||||
result.tactus = tactus;
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Like **cat**, but the items are crammed into one cycle.
|
||||
* @synonyms fastcat, sequence
|
||||
* @example
|
||||
|
|
@ -1474,86 +1447,6 @@ function _sequenceCount(x) {
|
|||
return [reify(x), 1];
|
||||
}
|
||||
|
||||
/**
|
||||
* Speeds a pattern up or down, to fit to the given metrical 'tactus'.
|
||||
* @example
|
||||
* s("bd sd cp").toTactus(4)
|
||||
* // The same as s("{bd sd cp}%4")
|
||||
*/
|
||||
export const toTactus = register('toTactus', function (targetTactus, pat) {
|
||||
return pat.fast(Fraction(targetTactus).div(pat.tactus));
|
||||
});
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Aligns one or more given patterns to the given number of steps per cycle.
|
||||
* This relies on patterns having coherent number of steps per cycle,
|
||||
*
|
||||
* @name polymeterSteps
|
||||
* @param {number} steps how many items are placed in one cycle
|
||||
* @param {any[]} patterns one or more patterns
|
||||
* @example
|
||||
* // the same as "{c d, e f g}%4"
|
||||
* polymeterSteps(4, "c d", "e f g")
|
||||
*/
|
||||
export function polymeterSteps(steps, ...args) {
|
||||
if (args.length == 0) {
|
||||
return silence;
|
||||
}
|
||||
if (Array.isArray(args[0])) {
|
||||
// Support old behaviour
|
||||
return _polymeterListSteps(steps, ...args);
|
||||
}
|
||||
|
||||
return polymeter(...args).toTactus(steps);
|
||||
}
|
||||
|
||||
/**
|
||||
* Combines the given lists of patterns with the same pulse, creating polymeters when different sized sequences are used.
|
||||
* @synonyms pm
|
||||
* @example
|
||||
* // The same as "{c eb g, c2 g2}"
|
||||
* polymeter("c eb g", "c2 g2")
|
||||
*
|
||||
*/
|
||||
export function polymeter(...args) {
|
||||
if (Array.isArray(args[0])) {
|
||||
// Support old behaviour
|
||||
return _polymeterListSteps(0, ...args);
|
||||
}
|
||||
|
||||
if (args.length == 0) {
|
||||
return silence;
|
||||
}
|
||||
const tactus = args[0].tactus;
|
||||
const [head, ...tail] = args;
|
||||
|
||||
const result = stack(head, ...tail.map((pat) => pat._slow(pat.tactus.div(tactus))));
|
||||
result.tactus = tactus;
|
||||
return result;
|
||||
}
|
||||
|
||||
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));
|
||||
|
|
@ -1593,7 +1486,7 @@ export const func = curry((a, b) => reify(b).func(a));
|
|||
* @noAutocomplete
|
||||
*
|
||||
*/
|
||||
export function register(name, func, patternify = true, preserveTactus = false) {
|
||||
export function register(name, func, patternify = true, preserveTactus = false, join = (x) => x.innerJoin()) {
|
||||
if (Array.isArray(name)) {
|
||||
const result = {};
|
||||
for (const name_item of name) {
|
||||
|
|
@ -1630,7 +1523,7 @@ export function register(name, func, patternify = true, preserveTactus = false)
|
|||
return func(...args, pat);
|
||||
};
|
||||
mapFn = curry(mapFn, null, arity - 1);
|
||||
result = right.reduce((acc, p) => acc.appLeft(p), left.fmap(mapFn)).innerJoin();
|
||||
result = join(right.reduce((acc, p) => acc.appLeft(p), left.fmap(mapFn)));
|
||||
}
|
||||
}
|
||||
if (preserveTactus) {
|
||||
|
|
@ -1674,6 +1567,11 @@ export function register(name, func, patternify = true, preserveTactus = false)
|
|||
return curry(pfunc, null, arity);
|
||||
}
|
||||
|
||||
// Like register, but defaults to stepJoin
|
||||
function stepRegister(name, func, patternify = true, preserveTactus = false, join = (x) => x.stepJoin()) {
|
||||
return register(name, func, patternify, preserveTactus, join);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Numerical transformations
|
||||
|
||||
|
|
@ -1881,7 +1779,9 @@ export const { focusSpan, focusspan } = register(['focusSpan', 'focusspan'], fun
|
|||
*/
|
||||
export const ply = register('ply', function (factor, pat) {
|
||||
const result = pat.fmap((x) => pure(x)._fast(factor)).squeezeJoin();
|
||||
result.tactus = pat.tactus.mul(factor);
|
||||
if (__tactus) {
|
||||
result.tactus = Fraction(factor).mulmaybe(pat.tactus);
|
||||
}
|
||||
return result;
|
||||
});
|
||||
|
||||
|
|
@ -1896,16 +1796,19 @@ export const ply = register('ply', function (factor, pat) {
|
|||
* @example
|
||||
* s("bd hh sd hh").fast(2) // s("[bd hh sd hh]*2")
|
||||
*/
|
||||
export const { fast, density } = register(['fast', 'density'], function (factor, pat) {
|
||||
if (factor === 0) {
|
||||
return silence;
|
||||
}
|
||||
factor = Fraction(factor);
|
||||
const fastQuery = pat.withQueryTime((t) => t.mul(factor));
|
||||
const result = fastQuery.withHapTime((t) => t.div(factor));
|
||||
result.tactus = factor.mul(pat.tactus);
|
||||
return result;
|
||||
});
|
||||
export const { fast, density } = register(
|
||||
['fast', 'density'],
|
||||
function (factor, pat) {
|
||||
if (factor === 0) {
|
||||
return silence;
|
||||
}
|
||||
factor = Fraction(factor);
|
||||
const fastQuery = pat.withQueryTime((t) => t.mul(factor));
|
||||
return fastQuery.withHapTime((t) => t.div(factor)).setTactus(pat.tactus);
|
||||
},
|
||||
true,
|
||||
true,
|
||||
);
|
||||
|
||||
/**
|
||||
* Both speeds up the pattern (like 'fast') and the sample playback (like 'speed').
|
||||
|
|
@ -2069,11 +1972,16 @@ export const late = register(
|
|||
export const zoom = register('zoom', function (s, e, pat) {
|
||||
e = Fraction(e);
|
||||
s = Fraction(s);
|
||||
if (s.gte(e)) {
|
||||
return nothing;
|
||||
}
|
||||
const d = e.sub(s);
|
||||
const tactus = __tactus ? pat.tactus.mulmaybe(d) : undefined;
|
||||
return pat
|
||||
.withQuerySpan((span) => span.withCycle((t) => t.mul(d).add(s)))
|
||||
.withHapSpan((span) => span.withCycle((t) => t.sub(s).div(d)))
|
||||
.splitQueries();
|
||||
.splitQueries()
|
||||
.setTactus(tactus);
|
||||
});
|
||||
|
||||
export const { zoomArc, zoomarc } = register(['zoomArc', 'zoomarc'], function (a, pat) {
|
||||
|
|
@ -2110,6 +2018,24 @@ export const segment = register('segment', function (rate, pat) {
|
|||
return pat.struct(pure(true)._fast(rate)).setTactus(rate);
|
||||
});
|
||||
|
||||
/**
|
||||
* The function `swingBy x n` breaks each cycle into `n` slices, and then delays events in the second half of each slice by the amount `x`, which is relative to the size of the (half) slice. So if `x` is 0 it does nothing, `0.5` delays for half the note duration, and 1 will wrap around to doing nothing again. The end result is a shuffle or swing-like rhythm
|
||||
* @param {number} subdivision
|
||||
* @param {number} offset
|
||||
* @example
|
||||
* s("hh*8").swingBy(1/3, 4)
|
||||
*/
|
||||
export const swingBy = register('swingBy', (swing, n, pat) => pat.inside(n, late(seq(0, swing / 2))));
|
||||
|
||||
/**
|
||||
* Shorthand for swingBy with 1/3:
|
||||
* @param {number} subdivision
|
||||
* @example
|
||||
* s("hh*8").swing(4)
|
||||
* // s("hh*8").swingBy(1/3, 4)
|
||||
*/
|
||||
export const swing = register('swing', (n, pat) => pat.swingBy(1 / 3, n));
|
||||
|
||||
/**
|
||||
* Swaps 1s and 0s in a binary pattern.
|
||||
* @name invert
|
||||
|
|
@ -2265,7 +2191,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).setTactus(lcm(left.tactus, right.tactus));
|
||||
return stack(left, right).setTactus(__tactus ? lcm(left.tactus, right.tactus) : undefined);
|
||||
});
|
||||
|
||||
/**
|
||||
|
|
@ -2384,7 +2310,13 @@ export const { iterBack, iterback } = register(
|
|||
export const { repeatCycles } = register(
|
||||
'repeatCycles',
|
||||
function (n, pat) {
|
||||
return slowcat(...Array(n).fill(pat));
|
||||
return new Pattern(function (state) {
|
||||
const cycle = state.span.begin.sam();
|
||||
const source_cycle = cycle.div(n).sam();
|
||||
const delta = cycle.sub(source_cycle);
|
||||
state = state.withSpan((span) => span.withTime((spant) => spant.sub(delta)));
|
||||
return pat.query(state).map((hap) => hap.withSpan((span) => span.withTime((spant) => spant.add(delta))));
|
||||
}).splitQueries();
|
||||
},
|
||||
true,
|
||||
true,
|
||||
|
|
@ -2487,6 +2419,360 @@ Pattern.prototype.tag = function (tag) {
|
|||
return this.withContext((ctx) => ({ ...ctx, tags: (ctx.tags || []).concat([tag]) }));
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Tactus-related functions, i.e. ones that do stepwise
|
||||
// transformations
|
||||
|
||||
Pattern.prototype.stepJoin = function () {
|
||||
const pp = this;
|
||||
const first_t = s_cat(..._retime(_slices(pp.queryArc(0, 1)))).tactus;
|
||||
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 = s_cat(..._retime(_slices(haps)));
|
||||
return pat.query(state);
|
||||
};
|
||||
return new Pattern(q, first_t);
|
||||
};
|
||||
|
||||
export function _retime(timedHaps) {
|
||||
const occupied_perc = timedHaps.filter((t, pat) => pat.hasTactus).reduce((a, b) => a.add(b), Fraction(0));
|
||||
const occupied_tactus = removeUndefineds(timedHaps.map((t, pat) => pat.tactus)).reduce(
|
||||
(a, b) => a.add(b),
|
||||
Fraction(0),
|
||||
);
|
||||
const total_tactus = occupied_perc.eq(0) ? undefined : occupied_tactus.div(occupied_perc);
|
||||
function adjust(dur, pat) {
|
||||
if (pat.tactus === undefined) {
|
||||
return [dur.mulmaybe(total_tactus), pat];
|
||||
}
|
||||
return [pat.tactus, 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* *EXPERIMENTAL* - Speeds a pattern up or down, to fit to the given number of steps per cycle (aka tactus).
|
||||
* @example
|
||||
* s("bd sd cp").steps(4)
|
||||
* // The same as s("{bd sd cp}%4")
|
||||
*/
|
||||
export const steps = register('steps', function (targetTactus, pat) {
|
||||
if (pat.tactus === undefined) {
|
||||
return pat;
|
||||
}
|
||||
if (pat.tactus.eq(Fraction(0))) {
|
||||
// avoid divide by zero..
|
||||
return nothing;
|
||||
}
|
||||
return pat.fast(Fraction(targetTactus).div(pat.tactus));
|
||||
});
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Aligns one or more given patterns to the given number of steps per cycle.
|
||||
* This relies on patterns having coherent number of steps per cycle,
|
||||
*
|
||||
* @name s_polymeterSteps
|
||||
* @param {number} steps how many items are placed in one cycle
|
||||
* @param {any[]} patterns one or more patterns
|
||||
* @example
|
||||
* // the same as "{c d, e f g}%4"
|
||||
* s_polymeterSteps(4, "c d", "e f g")
|
||||
*/
|
||||
export function s_polymeterSteps(steps, ...args) {
|
||||
if (args.length == 0) {
|
||||
return silence;
|
||||
}
|
||||
if (Array.isArray(args[0])) {
|
||||
// Support old behaviour
|
||||
return _polymeterListSteps(steps, ...args);
|
||||
}
|
||||
|
||||
return s_polymeter(...args).steps(steps);
|
||||
}
|
||||
|
||||
/**
|
||||
* *EXPERIMENTAL* - Combines the given lists of patterns with the same pulse, creating polymeters when different sized sequences are used.
|
||||
* @synonyms pm
|
||||
* @example
|
||||
* // The same as "{c eb g, c2 g2}"
|
||||
* s_polymeter("c eb g", "c2 g2")
|
||||
*
|
||||
*/
|
||||
export function s_polymeter(...args) {
|
||||
if (Array.isArray(args[0])) {
|
||||
// Support old behaviour
|
||||
return _polymeterListSteps(0, ...args);
|
||||
}
|
||||
|
||||
// TODO currently ignoring arguments without tactus...
|
||||
args = args.filter((arg) => arg.hasTactus);
|
||||
|
||||
if (args.length == 0) {
|
||||
return silence;
|
||||
}
|
||||
const tactus = args[0].tactus;
|
||||
if (tactus.eq(Fraction(0))) {
|
||||
return nothing;
|
||||
}
|
||||
const [head, ...tail] = args;
|
||||
|
||||
const result = stack(head, ...tail.map((pat) => pat._slow(pat.tactus.div(tactus))));
|
||||
result.tactus = tactus;
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Sequences patterns like `seq`, but each pattern has a length, relative to the whole.
|
||||
* This length can either be provided as a [length, pattern] pair, or inferred from
|
||||
* the pattern's 'tactus', generally inferred by the mininotation. Has the alias `timecat`.
|
||||
* @return {Pattern}
|
||||
* @example
|
||||
* s_cat([3,"e3"],[1, "g3"]).note()
|
||||
* // the same as "e3@3 g3".note()
|
||||
* @example
|
||||
* s_cat("bd sd cp","hh hh").sound()
|
||||
* // the same as "bd sd cp hh hh".sound()
|
||||
*/
|
||||
export function s_cat(...timepats) {
|
||||
if (timepats.length === 0) {
|
||||
return nothing;
|
||||
}
|
||||
const findtactus = (x) => (Array.isArray(x) ? x : [x.tactus, x]);
|
||||
timepats = timepats.map(findtactus);
|
||||
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]);
|
||||
result.tactus = timepats[0][0];
|
||||
return result;
|
||||
}
|
||||
|
||||
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.tactus = total;
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Aliases for `s_cat` */
|
||||
export const timecat = s_cat;
|
||||
export const timeCat = s_cat;
|
||||
|
||||
/**
|
||||
* *EXPERIMENTAL* - Concatenates patterns stepwise, according to their 'tactus'.
|
||||
* Similar to `s_cat`, but if an argument is a list, the whole pattern will alternate between the elements in the list.
|
||||
*
|
||||
* @return {Pattern}
|
||||
* @example
|
||||
* s_alt(["bd cp", "mt"], "bd").sound()
|
||||
*/
|
||||
export function s_alt(...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.hasTactus && x.tactus > 0);
|
||||
const tactus = result.reduce((a, b) => a.add(b.tactus), Fraction(0));
|
||||
result = s_cat(...result);
|
||||
result.tactus = tactus;
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* *EXPERIMENTAL* - Retains the given number of steps in a pattern (and dropping the rest), according to its 'tactus'.
|
||||
*/
|
||||
export const s_add = stepRegister('s_add', function (i, pat) {
|
||||
if (!pat.hasTactus) {
|
||||
return nothing;
|
||||
}
|
||||
if (pat.tactus.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.tactus);
|
||||
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* - Removes the given number of steps from a pattern, according to its 'tactus'.
|
||||
*/
|
||||
export const s_sub = stepRegister('s_sub', function (i, pat) {
|
||||
if (!pat.hasTactus) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
i = Fraction(i);
|
||||
if (i.lt(0)) {
|
||||
return pat.s_add(Fraction(0).sub(pat.tactus.add(i)));
|
||||
}
|
||||
return pat.s_add(pat.tactus.sub(i));
|
||||
});
|
||||
|
||||
export const s_expand = stepRegister('s_expand', function (factor, pat) {
|
||||
return pat.withTactus((t) => t.mul(Fraction(factor)));
|
||||
});
|
||||
|
||||
export const s_contract = stepRegister('s_contract', function (factor, pat) {
|
||||
return pat.withTactus((t) => t.div(Fraction(factor)));
|
||||
});
|
||||
|
||||
/**
|
||||
* *EXPERIMENTAL*
|
||||
*/
|
||||
Pattern.prototype.s_taperlist = function (amount, times) {
|
||||
const pat = this;
|
||||
|
||||
if (!pat.hasTactus) {
|
||||
return [pat];
|
||||
}
|
||||
|
||||
times = times - 1;
|
||||
|
||||
if (times === 0) {
|
||||
return [pat];
|
||||
}
|
||||
|
||||
const list = [];
|
||||
const reverse = amount > 0;
|
||||
amount = Fraction(Math.abs(amount));
|
||||
const start = pat.tactus.sub(amount.mul(Fraction(times))).max(Fraction(0));
|
||||
|
||||
for (let i = 0; i < times; ++i) {
|
||||
list.push(pat.zoom(0, start.add(amount.mul(Fraction(i))).div(pat.tactus)));
|
||||
}
|
||||
list.push(pat);
|
||||
if (reverse) {
|
||||
list.reverse();
|
||||
}
|
||||
return list;
|
||||
};
|
||||
export const s_taperlist = (amount, times, pat) => pat.s_taperlist(amount, times);
|
||||
|
||||
/**
|
||||
* *EXPERIMENTAL*
|
||||
*/
|
||||
export const s_taper = register(
|
||||
's_taper',
|
||||
function (amount, times, pat) {
|
||||
if (!pat.hasTactus) {
|
||||
return nothing;
|
||||
}
|
||||
|
||||
const list = pat.s_taperlist(amount, times);
|
||||
const result = s_cat(...list);
|
||||
result.tactus = list.reduce((a, b) => a.add(b.tactus), Fraction(0));
|
||||
return result;
|
||||
},
|
||||
true,
|
||||
false,
|
||||
(x) => x.stepJoin(),
|
||||
);
|
||||
|
||||
/**
|
||||
* *EXPERIMENTAL*
|
||||
*/
|
||||
Pattern.prototype.s_tour = function (...many) {
|
||||
return s_cat(
|
||||
...[].concat(
|
||||
...many.map((x, i) => [...many.slice(0, many.length - i), this, ...many.slice(many.length - i)]),
|
||||
this,
|
||||
...many,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
export const s_tour = function (pat, ...many) {
|
||||
return pat.s_tour(...many);
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Control-related functions, i.e. ones that manipulate patterns of
|
||||
// objects
|
||||
|
|
@ -2511,7 +2797,7 @@ export const chop = register('chop', function (n, pat) {
|
|||
const func = function (o) {
|
||||
return sequence(slice_objects.map((slice_o) => Object.assign({}, o, slice_o)));
|
||||
};
|
||||
return pat.squeezeBind(func).setTactus(pat.tactus.mul(n));
|
||||
return pat.squeezeBind(func).setTactus(__tactus ? Fraction(n).mulmaybe(pat.tactus) : undefined);
|
||||
});
|
||||
|
||||
/**
|
||||
|
|
@ -2526,7 +2812,10 @@ export const striate = register('striate', function (n, pat) {
|
|||
const slices = Array.from({ length: n }, (x, i) => i);
|
||||
const slice_objects = slices.map((i) => ({ begin: i / n, end: (i + 1) / n }));
|
||||
const slicePat = slowcat(...slice_objects);
|
||||
return pat.set(slicePat)._fast(n);
|
||||
return pat
|
||||
.set(slicePat)
|
||||
._fast(n)
|
||||
.setTactus(__tactus ? Fraction(n).mulmaybe(pat.tactus) : undefined);
|
||||
});
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -54,10 +54,12 @@ export function repl({
|
|||
const scheduler =
|
||||
sync && typeof SharedWorker != 'undefined' ? new NeoCyclist(schedulerOptions) : new Cyclist(schedulerOptions);
|
||||
let pPatterns = {};
|
||||
let anonymousIndex = 0;
|
||||
let allTransform;
|
||||
|
||||
const hush = function () {
|
||||
pPatterns = {};
|
||||
anonymousIndex = 0;
|
||||
allTransform = undefined;
|
||||
return silence;
|
||||
};
|
||||
|
|
@ -82,6 +84,15 @@ export function repl({
|
|||
// set pattern methods that use this repl via closure
|
||||
const injectPatternMethods = () => {
|
||||
Pattern.prototype.p = function (id) {
|
||||
if (id.startsWith('_') || id.endsWith('_')) {
|
||||
// allows muting a pattern x with x_ or _x
|
||||
return silence;
|
||||
}
|
||||
if (id === '$') {
|
||||
// allows adding anonymous patterns with $:
|
||||
id = `$${anonymousIndex}`;
|
||||
anonymousIndex++;
|
||||
}
|
||||
pPatterns[id] = this;
|
||||
return this;
|
||||
};
|
||||
|
|
@ -156,6 +167,7 @@ export function repl({
|
|||
return pattern;
|
||||
} catch (err) {
|
||||
logger(`[eval] error: ${err.message}`, 'error');
|
||||
console.error(err);
|
||||
updateState({ evalError: err, pending: false });
|
||||
onEvalError?.(err);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -486,8 +486,10 @@ export const wchoose = (...pairs) => wchooseWith(rand, ...pairs);
|
|||
* @returns {Pattern}
|
||||
* @example
|
||||
* wchooseCycles(["bd",10], ["hh",1], ["sd",1]).s().fast(8)
|
||||
* @example
|
||||
* wchooseCycles(["bd bd bd",5], ["hh hh hh",3], ["sd sd sd",1]).fast(4).s()
|
||||
*/
|
||||
export const wchooseCycles = (...pairs) => _wchooseWith(rand, ...pairs).innerJoin();
|
||||
export const wchooseCycles = (...pairs) => _wchooseWith(rand.segment(1), ...pairs).innerJoin();
|
||||
|
||||
export const wrandcat = wchooseCycles;
|
||||
|
||||
|
|
|
|||
|
|
@ -21,8 +21,8 @@ import {
|
|||
cat,
|
||||
sequence,
|
||||
palindrome,
|
||||
polymeter,
|
||||
polymeterSteps,
|
||||
s_polymeter,
|
||||
s_polymeterSteps,
|
||||
polyrhythm,
|
||||
silence,
|
||||
fast,
|
||||
|
|
@ -47,6 +47,11 @@ import {
|
|||
time,
|
||||
run,
|
||||
pick,
|
||||
stackLeft,
|
||||
stackRight,
|
||||
stackCentre,
|
||||
s_cat,
|
||||
calculateTactus,
|
||||
} from '../index.mjs';
|
||||
|
||||
import { steady } from '../signal.mjs';
|
||||
|
|
@ -603,18 +608,18 @@ describe('Pattern', () => {
|
|||
);
|
||||
});
|
||||
});
|
||||
describe('polymeter()', () => {
|
||||
describe('s_polymeter()', () => {
|
||||
it('Can layer up cycles, stepwise, with lists', () => {
|
||||
expect(polymeterSteps(3, ['d', 'e']).firstCycle()).toStrictEqual(
|
||||
expect(s_polymeterSteps(3, ['d', 'e']).firstCycle()).toStrictEqual(
|
||||
fastcat(pure('d'), pure('e'), pure('d')).firstCycle(),
|
||||
);
|
||||
|
||||
expect(polymeter(['a', 'b', 'c'], ['d', 'e']).fast(2).firstCycle()).toStrictEqual(
|
||||
expect(s_polymeter(['a', 'b', 'c'], ['d', 'e']).fast(2).firstCycle()).toStrictEqual(
|
||||
stack(sequence('a', 'b', 'c', 'a', 'b', 'c'), sequence('d', 'e', 'd', 'e', 'd', 'e')).firstCycle(),
|
||||
);
|
||||
});
|
||||
it('Can layer up cycles, stepwise, with weighted patterns', () => {
|
||||
sameFirst(polymeterSteps(3, sequence('a', 'b')).fast(2), sequence('a', 'b', 'a', 'b', 'a', 'b'));
|
||||
sameFirst(s_polymeterSteps(3, sequence('a', 'b')).fast(2), sequence('a', 'b', 'a', 'b', 'a', 'b'));
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -1123,8 +1128,8 @@ describe('Pattern', () => {
|
|||
it('Is correctly preserved/calculated through transformations', () => {
|
||||
expect(sequence(0, 1, 2, 3).linger(4).tactus).toStrictEqual(Fraction(4));
|
||||
expect(sequence(0, 1, 2, 3).iter(4).tactus).toStrictEqual(Fraction(4));
|
||||
expect(sequence(0, 1, 2, 3).fast(4).tactus).toStrictEqual(Fraction(16));
|
||||
expect(sequence(0, 1, 2, 3).hurry(4).tactus).toStrictEqual(Fraction(16));
|
||||
expect(sequence(0, 1, 2, 3).fast(4).tactus).toStrictEqual(Fraction(4));
|
||||
expect(sequence(0, 1, 2, 3).hurry(4).tactus).toStrictEqual(Fraction(4));
|
||||
expect(sequence(0, 1, 2, 3).rev().tactus).toStrictEqual(Fraction(4));
|
||||
expect(sequence(1).segment(10).tactus).toStrictEqual(Fraction(10));
|
||||
expect(sequence(1, 0, 1).invert().tactus).toStrictEqual(Fraction(3));
|
||||
|
|
@ -1136,6 +1141,72 @@ describe('Pattern', () => {
|
|||
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).splice(4, sequence(0, 1, 2, 3)).tactus).toStrictEqual(
|
||||
Fraction(4),
|
||||
);
|
||||
expect(sequence({ n: 0 }, { n: 1 }, { n: 2 }).chop(4).tactus).toStrictEqual(Fraction(12));
|
||||
expect(
|
||||
pure((x) => x + 1)
|
||||
.setTactus(3)
|
||||
.appBoth(pure(1).setTactus(2)).tactus,
|
||||
).toStrictEqual(Fraction(6));
|
||||
expect(
|
||||
pure((x) => x + 1)
|
||||
.setTactus(undefined)
|
||||
.appBoth(pure(1).setTactus(2)).tactus,
|
||||
).toStrictEqual(Fraction(2));
|
||||
expect(
|
||||
pure((x) => x + 1)
|
||||
.setTactus(3)
|
||||
.appBoth(pure(1).setTactus(undefined)).tactus,
|
||||
).toStrictEqual(Fraction(3));
|
||||
expect(stack(fastcat(0, 1, 2), fastcat(3, 4)).tactus).toStrictEqual(Fraction(6));
|
||||
expect(stack(fastcat(0, 1, 2), fastcat(3, 4).setTactus(undefined)).tactus).toStrictEqual(Fraction(3));
|
||||
expect(stackLeft(fastcat(0, 1, 2, 3), fastcat(3, 4)).tactus).toStrictEqual(Fraction(4));
|
||||
expect(stackRight(fastcat(0, 1, 2), fastcat(3, 4)).tactus).toStrictEqual(Fraction(3));
|
||||
// maybe this should double when they are either all even or all odd
|
||||
expect(stackCentre(fastcat(0, 1, 2), fastcat(3, 4)).tactus).toStrictEqual(Fraction(3));
|
||||
expect(fastcat(0, 1).ply(3).tactus).toStrictEqual(Fraction(6));
|
||||
expect(fastcat(0, 1).setTactus(undefined).ply(3).tactus).toStrictEqual(undefined);
|
||||
expect(fastcat(0, 1).fast(3).tactus).toStrictEqual(Fraction(2));
|
||||
expect(fastcat(0, 1).setTactus(undefined).fast(3).tactus).toStrictEqual(undefined);
|
||||
});
|
||||
});
|
||||
describe('s_cat', () => {
|
||||
it('can cat', () => {
|
||||
expect(sameFirst(s_cat(fastcat(0, 1, 2, 3), fastcat(4, 5)), fastcat(0, 1, 2, 3, 4, 5)));
|
||||
expect(sameFirst(s_cat(pure(1), pure(2), pure(3)), fastcat(1, 2, 3)));
|
||||
});
|
||||
it('calculates undefined tactuses as the average', () => {
|
||||
expect(sameFirst(s_cat(pure(1), pure(2), pure(3).setTactus(undefined)), fastcat(1, 2, 3)));
|
||||
});
|
||||
});
|
||||
describe('s_taper', () => {
|
||||
it('can taper', () => {
|
||||
expect(sameFirst(sequence(0, 1, 2, 3, 4).s_taper(1, 5), sequence(0, 1, 2, 3, 4, 0, 1, 2, 3, 0, 1, 2, 0, 1, 0)));
|
||||
});
|
||||
it('can taper backwards', () => {
|
||||
expect(sameFirst(sequence(0, 1, 2, 3, 4).s_taper(-1, 5), sequence(0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4)));
|
||||
});
|
||||
});
|
||||
describe('s_add and s_sub', () => {
|
||||
it('can add from the left', () => {
|
||||
expect(sameFirst(sequence(0, 1, 2, 3, 4).s_add(2), sequence(0, 1)));
|
||||
});
|
||||
it('can sub to the left', () => {
|
||||
expect(sameFirst(sequence(0, 1, 2, 3, 4).s_sub(2), sequence(0, 1, 2)));
|
||||
});
|
||||
it('can add from the right', () => {
|
||||
expect(sameFirst(sequence(0, 1, 2, 3, 4).s_add(-2), sequence(3, 4)));
|
||||
});
|
||||
it('can sub to the right', () => {
|
||||
expect(sameFirst(sequence(0, 1, 2, 3, 4).s_sub(-2), sequence(2, 3, 4)));
|
||||
});
|
||||
it('can subtract nothing', () => {
|
||||
expect(sameFirst(pure('a').s_sub(0), pure('a')));
|
||||
});
|
||||
it('can subtract nothing, repeatedly', () => {
|
||||
expect(sameFirst(pure('a').s_sub(0, 0), fastcat('a', 'a')));
|
||||
for (var i = 0; i < 100; ++i) {
|
||||
expect(sameFirst(pure('a').s_sub(...Array(i).fill(0)), fastcat(...Array(i).fill('a'))));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -61,6 +61,11 @@ export const valueToMidi = (value, fallbackValue) => {
|
|||
return fallbackValue;
|
||||
};
|
||||
|
||||
// used to schedule external event like midi and osc out
|
||||
export const getEventOffsetMs = (targetTimeSeconds, currentTimeSeconds) => {
|
||||
return (targetTimeSeconds - currentTimeSeconds) * 1000;
|
||||
};
|
||||
|
||||
/**
|
||||
* @deprecated does not appear to be referenced or invoked anywhere in the codebase
|
||||
* @noAutocomplete
|
||||
|
|
@ -231,6 +236,14 @@ export const splitAt = function (index, value) {
|
|||
|
||||
export const zipWith = (f, xs, ys) => xs.map((n, i) => f(n, ys[i]));
|
||||
|
||||
export const pairs = function (xs) {
|
||||
const result = [];
|
||||
for (let i = 0; i < xs.length - 1; ++i) {
|
||||
result.push([xs[i], xs[i + 1]]);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
export const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
|
||||
|
||||
/* solmization, not used yet */
|
||||
|
|
@ -289,6 +302,30 @@ export const sol2note = (n, notation = 'letters') => {
|
|||
return note + oct;
|
||||
};
|
||||
|
||||
// Remove duplicates from list
|
||||
export function uniq(a) {
|
||||
var seen = {};
|
||||
return a.filter(function (item) {
|
||||
return seen.hasOwn(item) ? false : (seen[item] = true);
|
||||
});
|
||||
}
|
||||
|
||||
// Remove duplicates from list, sorting in the process. Mutates argument!
|
||||
export function uniqsort(a) {
|
||||
return a.sort().filter(function (item, pos, ary) {
|
||||
return !pos || item != ary[pos - 1];
|
||||
});
|
||||
}
|
||||
|
||||
// rational version
|
||||
export function uniqsortr(a) {
|
||||
return a
|
||||
.sort((x, y) => x.compare(y))
|
||||
.filter(function (item, pos, ary) {
|
||||
return !pos || item.ne(ary[pos - 1]);
|
||||
});
|
||||
}
|
||||
|
||||
// code hashing helpers
|
||||
|
||||
export function unicodeToBase64(text) {
|
||||
|
|
|
|||
|
|
@ -26,8 +26,7 @@ function createClock(
|
|||
// callback as long as we're inside the lookahead
|
||||
while (phase < lookahead) {
|
||||
phase = round ? Math.round(phase * precision) / precision : phase;
|
||||
phase >= t && callback(phase, duration, tick, t);
|
||||
phase < t && console.log('TOO LATE', phase); // what if latency is added from outside?
|
||||
callback(phase, duration, tick, t); // callback has to skip / handle phase < t!
|
||||
phase += duration; // increment phase by duration
|
||||
tick++;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ export const csound = register('csound', (instrument, pat) => {
|
|||
instrument = instrument || 'triangle';
|
||||
init(); // not async to support csound inside other patterns + to be able to call pattern methods after it
|
||||
// TODO: find a alternative way to wait for csound to load (to wait with first time playback)
|
||||
return pat.onTrigger((time, hap) => {
|
||||
return pat.onTrigger((time_deprecate, hap, currentTime, _cps, targetTime) => {
|
||||
if (!_csound) {
|
||||
logger('[csound] not loaded yet', 'warning');
|
||||
return;
|
||||
|
|
@ -38,9 +38,11 @@ export const csound = register('csound', (instrument, pat) => {
|
|||
.join('/');
|
||||
// TODO: find out how to send a precise ctx based time
|
||||
// http://www.csounds.com/manual/html/i.html
|
||||
const timeOffset = targetTime - currentTime; // latency ?
|
||||
//const timeOffset = time_deprecate - getAudioContext().currentTime
|
||||
const params = [
|
||||
`"${instrument}"`, // p1: instrument name
|
||||
time - getAudioContext().currentTime, //.toFixed(precision), // p2: starting time in arbitrary unit called beats
|
||||
timeOffset, // p2: starting time in arbitrary unit called beats
|
||||
hap.duration + 0, // p3: duration in beats
|
||||
// instrument specific params:
|
||||
freq, //.toFixed(precision), // p4: frequency
|
||||
|
|
|
|||
|
|
@ -1,14 +1,16 @@
|
|||
import { Invoke } from './utils.mjs';
|
||||
import { Pattern, noteToMidi } from '@strudel/core';
|
||||
import { Pattern, getEventOffsetMs, noteToMidi } from '@strudel/core';
|
||||
|
||||
const ON_MESSAGE = 0x90;
|
||||
const OFF_MESSAGE = 0x80;
|
||||
const CC_MESSAGE = 0xb0;
|
||||
|
||||
Pattern.prototype.midi = function (output) {
|
||||
return this.onTrigger((time, hap, currentTime, cps) => {
|
||||
return this.onTrigger((time_deprecate, hap, currentTime, cps, targetTime) => {
|
||||
let { note, nrpnn, nrpv, ccn, ccv, velocity = 0.9, gain = 1 } = hap.value;
|
||||
const offset = (time - currentTime) * 1000;
|
||||
//magic number to get audio engine to line up, can probably be calculated somehow
|
||||
const latencyMs = 34;
|
||||
const offset = getEventOffsetMs(targetTime, currentTime) + latencyMs;
|
||||
velocity = Math.floor(gain * velocity * 100);
|
||||
const duration = Math.floor((hap.duration.valueOf() / cps) * 1000 - 10);
|
||||
const roundedOffset = Math.round(offset);
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
import { parseNumeral, Pattern } from '@strudel/core';
|
||||
import { parseNumeral, Pattern, getEventOffsetMs } from '@strudel/core';
|
||||
import { Invoke } from './utils.mjs';
|
||||
|
||||
Pattern.prototype.osc = function () {
|
||||
return this.onTrigger(async (time, hap, currentTime, cps = 1) => {
|
||||
return this.onTrigger(async (time, hap, currentTime, cps = 1, targetTime) => {
|
||||
hap.ensureObjectValue();
|
||||
const cycle = hap.wholeOrPart().begin.valueOf();
|
||||
const delta = hap.duration.valueOf();
|
||||
|
|
@ -13,7 +13,7 @@ Pattern.prototype.osc = function () {
|
|||
|
||||
const params = [];
|
||||
|
||||
const timestamp = Math.round(Date.now() + (time - currentTime) * 1000);
|
||||
const timestamp = Math.round(Date.now() + getEventOffsetMs(targetTime, currentTime));
|
||||
|
||||
Object.keys(controls).forEach((key) => {
|
||||
const val = controls[key];
|
||||
|
|
|
|||
|
|
@ -3,3 +3,4 @@ export * from './color.mjs';
|
|||
export * from './draw.mjs';
|
||||
export * from './pianoroll.mjs';
|
||||
export * from './spiral.mjs';
|
||||
export * from './pitchwheel.mjs';
|
||||
|
|
|
|||
127
packages/draw/pitchwheel.mjs
Normal file
127
packages/draw/pitchwheel.mjs
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
import { Pattern, midiToFreq, getFrequency } from '@strudel/core';
|
||||
import { getTheme, getDrawContext } from './draw.mjs';
|
||||
|
||||
const c = midiToFreq(36);
|
||||
|
||||
const circlePos = (cx, cy, radius, angle) => {
|
||||
angle = angle * Math.PI * 2;
|
||||
const x = Math.sin(angle) * radius + cx;
|
||||
const y = Math.cos(angle) * radius + cy;
|
||||
return [x, y];
|
||||
};
|
||||
|
||||
const freq2angle = (freq, root) => {
|
||||
return 0.5 - (Math.log2(freq / root) % 1);
|
||||
};
|
||||
|
||||
export function pitchwheel({
|
||||
haps,
|
||||
ctx,
|
||||
id,
|
||||
hapcircles = 1,
|
||||
circle = 0,
|
||||
edo = 12,
|
||||
root = c,
|
||||
thickness = 3,
|
||||
hapRadius = 6,
|
||||
mode = 'flake',
|
||||
margin = 10,
|
||||
} = {}) {
|
||||
const connectdots = mode === 'polygon';
|
||||
const centerlines = mode === 'flake';
|
||||
const w = ctx.canvas.width;
|
||||
const h = ctx.canvas.height;
|
||||
ctx.clearRect(0, 0, w, h);
|
||||
const color = getTheme().foreground;
|
||||
|
||||
const size = Math.min(w, h);
|
||||
const radius = size / 2 - thickness / 2 - hapRadius - margin;
|
||||
const centerX = w / 2;
|
||||
const centerY = h / 2;
|
||||
|
||||
if (id) {
|
||||
haps = haps.filter((hap) => hap.hasTag(id));
|
||||
}
|
||||
ctx.strokeStyle = color;
|
||||
ctx.fillStyle = color;
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.lineWidth = thickness;
|
||||
|
||||
if (circle) {
|
||||
ctx.beginPath();
|
||||
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
if (edo) {
|
||||
Array.from({ length: edo }, (_, i) => {
|
||||
const angle = freq2angle(root * Math.pow(2, i / edo), root);
|
||||
const [x, y] = circlePos(centerX, centerY, radius, angle);
|
||||
ctx.beginPath();
|
||||
ctx.arc(x, y, hapRadius, 0, 2 * Math.PI);
|
||||
ctx.fill();
|
||||
});
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
let shape = [];
|
||||
ctx.lineWidth = hapRadius;
|
||||
haps.forEach((hap) => {
|
||||
let freq;
|
||||
try {
|
||||
freq = getFrequency(hap);
|
||||
} catch (err) {
|
||||
return;
|
||||
}
|
||||
const angle = freq2angle(freq, root);
|
||||
const [x, y] = circlePos(centerX, centerY, radius, angle);
|
||||
const hapColor = hap.value.color || color;
|
||||
ctx.strokeStyle = hapColor;
|
||||
ctx.fillStyle = hapColor;
|
||||
const { velocity = 1, gain = 1 } = hap.value || {};
|
||||
const alpha = velocity * gain;
|
||||
ctx.globalAlpha = alpha;
|
||||
shape.push([x, y, angle, hapColor, alpha]);
|
||||
ctx.beginPath();
|
||||
if (hapcircles) {
|
||||
ctx.moveTo(x + hapRadius, y);
|
||||
ctx.arc(x, y, hapRadius, 0, 2 * Math.PI);
|
||||
ctx.fill();
|
||||
}
|
||||
if (centerlines) {
|
||||
ctx.moveTo(centerX, centerY);
|
||||
ctx.lineTo(x, y);
|
||||
}
|
||||
ctx.stroke();
|
||||
});
|
||||
|
||||
ctx.strokeStyle = color;
|
||||
ctx.globalAlpha = 1;
|
||||
if (connectdots && shape.length) {
|
||||
shape = shape.sort((a, b) => a[2] - b[2]);
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(shape[0][0], shape[0][1]);
|
||||
shape.forEach(([x, y, _, color, alpha]) => {
|
||||
ctx.strokeStyle = color;
|
||||
ctx.globalAlpha = alpha;
|
||||
ctx.lineTo(x, y);
|
||||
});
|
||||
ctx.lineTo(shape[0][0], shape[0][1]);
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
Pattern.prototype.pitchwheel = function (options = {}) {
|
||||
let { ctx = getDrawContext(), id = 1 } = options;
|
||||
return this.tag(id).onPaint((_, time, haps) =>
|
||||
pitchwheel({
|
||||
...options,
|
||||
time,
|
||||
ctx,
|
||||
haps: haps.filter((hap) => hap.isActive(time)),
|
||||
id,
|
||||
}),
|
||||
);
|
||||
};
|
||||
2
packages/hs2js/.npmignore
Normal file
2
packages/hs2js/.npmignore
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
pnpm-lock.yaml
|
||||
vite.config.js
|
||||
661
packages/hs2js/LICENSE
Normal file
661
packages/hs2js/LICENSE
Normal file
|
|
@ -0,0 +1,661 @@
|
|||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
127
packages/hs2js/README.md
Normal file
127
packages/hs2js/README.md
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
# hs2js
|
||||
|
||||
Experimental haskell in javascript interpreter. Many haskell features are not implemented.
|
||||
This projects mainly exists to be able to write and interpret [Tidal Cycles](https://tidalcycles.org/) code in the browser,
|
||||
as part of [Strudel](https://github.com/tidalcycles/strudel). This project could only exist thanks to [tree-sitter-haskell](https://github.com/tree-sitter/tree-sitter-haskell).
|
||||
|
||||
## Installation
|
||||
|
||||
### Via Script Tag
|
||||
|
||||
You can load the library directly from a script tag via unpkg:
|
||||
|
||||
```html
|
||||
<script src="https://unpkg.com/hs2js@0.0.3"></script>
|
||||
<button id="hello">hello</button>
|
||||
<script>
|
||||
hs2js.setBase('https://unpkg.com/hs2js@0.0.3/dist/');
|
||||
hs2js.loadParser().then(()=>{
|
||||
document.getElementById('hello').addEventListener('click', () => {
|
||||
hs2js.evaluate('alert "hello from haskell!"');
|
||||
});
|
||||
})
|
||||
</script>
|
||||
```
|
||||
|
||||
### Via npm
|
||||
|
||||
You need to add `postinstall` to your `package.json` script to copy the parser to your `public` folder:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"postinstall": "cp node_modules/hs2js/dist/tree-sitter.wasm public && cp node_modules/hs2js/dist/tree-sitter-haskell.wasm public"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Depending on your setup, replace `public` with the folder that will serve your assets to `/`. Then install the package:
|
||||
|
||||
```sh
|
||||
npm i hs2js
|
||||
```
|
||||
|
||||
and use it:
|
||||
|
||||
```js
|
||||
import * as hs2js from 'hs2js';
|
||||
hs2js.loadParser();
|
||||
document.getElementById('hello').addEventListener('click', () => {
|
||||
hs2js.evaluate('alert "hello from haskell!"');
|
||||
});
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
These are all functions exported by the package:
|
||||
|
||||
### evaluate
|
||||
|
||||
Evaluates a piece of haskell code
|
||||
|
||||
- `code`: [valid](https://github.com/tree-sitter/tree-sitter-haskell?tab=readme-ov-file#supported-language-extensions) haskell code
|
||||
- `scope`: global scope, defaults to globalThis. Allows you to pass an object of your own functions / variables from JS to Haskell.
|
||||
- `ops`: mapping for custom infix operator
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
// simple
|
||||
hs2js.evaluate(`2 + 2`) // = 4
|
||||
// passing variables via scope:
|
||||
hs2js.evaluate(`a + b`, { a: 1, b: 2 }) // = 3
|
||||
// custom operator
|
||||
hs2js.evaluate(`2 |* 3`, {}, { '|*': (l, r) => l * r }) // = 6
|
||||
```
|
||||
|
||||
### parse
|
||||
|
||||
[Parses](https://github.com/tree-sitter/tree-sitter-haskell) a piece of haskell code, returning its AST representation.
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
const ast = hs2js.parse(`2 + 2`)
|
||||
console.log(ast.toString())
|
||||
// (haskell declarations: (declarations (top_splice (apply function: (variable) argument: (literal (integer))))))
|
||||
```
|
||||
|
||||
### run
|
||||
|
||||
Evaluates `rootNode` of haskell AST (used by evaluate internally).
|
||||
|
||||
- `rootNode`: haskell AST root node, as returned by `parse`
|
||||
- `scope`: see evaluate
|
||||
- `ops`: see evaluate
|
||||
|
||||
Example:
|
||||
|
||||
```js
|
||||
const ast = hs2js.parse(`2 + 3`);
|
||||
const res = hs2js.run(ast.rootNode);
|
||||
console.log(res); // = 5
|
||||
```
|
||||
|
||||
### loadParser
|
||||
|
||||
Loads and caches the parser by fetching `tree-sitter.wasm` and `tree-sitter-haskell.wasm`.
|
||||
Make sure to call and await this function before calling `parse` or `evaluate`.
|
||||
|
||||
```js
|
||||
hs2js.loadParser().then(() => hs2js.evaluate('alert "ready"'))
|
||||
```
|
||||
|
||||
### setBase
|
||||
|
||||
Sets the base path where the WASM files are expected by `loadParser`. Defaults to `/`.
|
||||
Expects `tree-sitter.wasm` and `tree-sitter-haskell.wasm` to be present.
|
||||
Can either be a relative path or a URL.
|
||||
|
||||
```js
|
||||
hs2js.setBase('https://unpkg.com/hs2js@0.0.4/dist/');
|
||||
hs2js.loadParser();
|
||||
/* loads
|
||||
- https://unpkg.com/hs2js@0.0.4/dist/tree-sitter.wasm
|
||||
- https://unpkg.com/hs2js@0.0.4/dist/tree-sitter-haskell.wasm
|
||||
*/
|
||||
```
|
||||
37
packages/hs2js/package.json
Normal file
37
packages/hs2js/package.json
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
{
|
||||
"name": "hs2js",
|
||||
"version": "0.0.9",
|
||||
"description": "Experimental Haskell in JavaScript interpreter",
|
||||
"main": "src/index.mjs",
|
||||
"type": "module",
|
||||
"publishConfig": {
|
||||
"main": "dist/index.js",
|
||||
"module": "dist/index.mjs"
|
||||
},
|
||||
"scripts": {
|
||||
"build-wasm": "tree-sitter build-wasm node_modules/tree-sitter-haskell && mv tree-sitter-haskell.wasm ./dist/ && cp node_modules/web-tree-sitter/tree-sitter.wasm ./dist/",
|
||||
"build": "vite build && npm run build-wasm",
|
||||
"prepublishOnly": "npm run build"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/tidalcycles/strudel.git"
|
||||
},
|
||||
"keywords": [
|
||||
"haskell",
|
||||
"javascript"
|
||||
],
|
||||
"author": "Felix Roos <flix91@gmail.com>",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"bugs": {
|
||||
"url": "https://github.com/tidalcycles/strudel/issues"
|
||||
},
|
||||
"homepage": "https://github.com/tidalcycles/strudel",
|
||||
"dependencies": {
|
||||
"web-tree-sitter": "^0.20.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vite": "^5.0.10",
|
||||
"tree-sitter-haskell": "^0.21.0"
|
||||
}
|
||||
}
|
||||
520
packages/hs2js/pnpm-lock.yaml
generated
Normal file
520
packages/hs2js/pnpm-lock.yaml
generated
Normal file
|
|
@ -0,0 +1,520 @@
|
|||
lockfileVersion: '6.0'
|
||||
|
||||
settings:
|
||||
autoInstallPeers: true
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
dependencies:
|
||||
web-tree-sitter:
|
||||
specifier: ^0.20.8
|
||||
version: 0.20.8
|
||||
|
||||
devDependencies:
|
||||
tree-sitter-haskell:
|
||||
specifier: ^0.21.0
|
||||
version: 0.21.0(tree-sitter@0.21.1)
|
||||
vite:
|
||||
specifier: ^5.0.10
|
||||
version: 5.2.11
|
||||
|
||||
packages:
|
||||
|
||||
/@esbuild/aix-ppc64@0.20.2:
|
||||
resolution: {integrity: sha512-D+EBOJHXdNZcLJRBkhENNG8Wji2kgc9AZ9KiPr1JuZjsNtyHzrsfLRrY0tk2H2aoFu6RANO1y1iPPUCDYWkb5g==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [ppc64]
|
||||
os: [aix]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/android-arm64@0.20.2:
|
||||
resolution: {integrity: sha512-mRzjLacRtl/tWU0SvD8lUEwb61yP9cqQo6noDZP/O8VkwafSYwZ4yWy24kan8jE/IMERpYncRt2dw438LP3Xmg==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [arm64]
|
||||
os: [android]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/android-arm@0.20.2:
|
||||
resolution: {integrity: sha512-t98Ra6pw2VaDhqNWO2Oph2LXbz/EJcnLmKLGBJwEwXX/JAN83Fym1rU8l0JUWK6HkIbWONCSSatf4sf2NBRx/w==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [arm]
|
||||
os: [android]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/android-x64@0.20.2:
|
||||
resolution: {integrity: sha512-btzExgV+/lMGDDa194CcUQm53ncxzeBrWJcncOBxuC6ndBkKxnHdFJn86mCIgTELsooUmwUm9FkhSp5HYu00Rg==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [x64]
|
||||
os: [android]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/darwin-arm64@0.20.2:
|
||||
resolution: {integrity: sha512-4J6IRT+10J3aJH3l1yzEg9y3wkTDgDk7TSDFX+wKFiWjqWp/iCfLIYzGyasx9l0SAFPT1HwSCR+0w/h1ES/MjA==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/darwin-x64@0.20.2:
|
||||
resolution: {integrity: sha512-tBcXp9KNphnNH0dfhv8KYkZhjc+H3XBkF5DKtswJblV7KlT9EI2+jeA8DgBjp908WEuYll6pF+UStUCfEpdysA==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/freebsd-arm64@0.20.2:
|
||||
resolution: {integrity: sha512-d3qI41G4SuLiCGCFGUrKsSeTXyWG6yem1KcGZVS+3FYlYhtNoNgYrWcvkOoaqMhwXSMrZRl69ArHsGJ9mYdbbw==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [arm64]
|
||||
os: [freebsd]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/freebsd-x64@0.20.2:
|
||||
resolution: {integrity: sha512-d+DipyvHRuqEeM5zDivKV1KuXn9WeRX6vqSqIDgwIfPQtwMP4jaDsQsDncjTDDsExT4lR/91OLjRo8bmC1e+Cw==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [x64]
|
||||
os: [freebsd]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/linux-arm64@0.20.2:
|
||||
resolution: {integrity: sha512-9pb6rBjGvTFNira2FLIWqDk/uaf42sSyLE8j1rnUpuzsODBq7FvpwHYZxQ/It/8b+QOS1RYfqgGFNLRI+qlq2A==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/linux-arm@0.20.2:
|
||||
resolution: {integrity: sha512-VhLPeR8HTMPccbuWWcEUD1Az68TqaTYyj6nfE4QByZIQEQVWBB8vup8PpR7y1QHL3CpcF6xd5WVBU/+SBEvGTg==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/linux-ia32@0.20.2:
|
||||
resolution: {integrity: sha512-o10utieEkNPFDZFQm9CoP7Tvb33UutoJqg3qKf1PWVeeJhJw0Q347PxMvBgVVFgouYLGIhFYG0UGdBumROyiig==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [ia32]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/linux-loong64@0.20.2:
|
||||
resolution: {integrity: sha512-PR7sp6R/UC4CFVomVINKJ80pMFlfDfMQMYynX7t1tNTeivQ6XdX5r2XovMmha/VjR1YN/HgHWsVcTRIMkymrgQ==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [loong64]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/linux-mips64el@0.20.2:
|
||||
resolution: {integrity: sha512-4BlTqeutE/KnOiTG5Y6Sb/Hw6hsBOZapOVF6njAESHInhlQAghVVZL1ZpIctBOoTFbQyGW+LsVYZ8lSSB3wkjA==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [mips64el]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/linux-ppc64@0.20.2:
|
||||
resolution: {integrity: sha512-rD3KsaDprDcfajSKdn25ooz5J5/fWBylaaXkuotBDGnMnDP1Uv5DLAN/45qfnf3JDYyJv/ytGHQaziHUdyzaAg==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/linux-riscv64@0.20.2:
|
||||
resolution: {integrity: sha512-snwmBKacKmwTMmhLlz/3aH1Q9T8v45bKYGE3j26TsaOVtjIag4wLfWSiZykXzXuE1kbCE+zJRmwp+ZbIHinnVg==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/linux-s390x@0.20.2:
|
||||
resolution: {integrity: sha512-wcWISOobRWNm3cezm5HOZcYz1sKoHLd8VL1dl309DiixxVFoFe/o8HnwuIwn6sXre88Nwj+VwZUvJf4AFxkyrQ==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/linux-x64@0.20.2:
|
||||
resolution: {integrity: sha512-1MdwI6OOTsfQfek8sLwgyjOXAu+wKhLEoaOLTjbijk6E2WONYpH9ZU2mNtR+lZ2B4uwr+usqGuVfFT9tMtGvGw==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/netbsd-x64@0.20.2:
|
||||
resolution: {integrity: sha512-K8/DhBxcVQkzYc43yJXDSyjlFeHQJBiowJ0uVL6Tor3jGQfSGHNNJcWxNbOI8v5k82prYqzPuwkzHt3J1T1iZQ==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [x64]
|
||||
os: [netbsd]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/openbsd-x64@0.20.2:
|
||||
resolution: {integrity: sha512-eMpKlV0SThJmmJgiVyN9jTPJ2VBPquf6Kt/nAoo6DgHAoN57K15ZghiHaMvqjCye/uU4X5u3YSMgVBI1h3vKrQ==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [x64]
|
||||
os: [openbsd]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/sunos-x64@0.20.2:
|
||||
resolution: {integrity: sha512-2UyFtRC6cXLyejf/YEld4Hajo7UHILetzE1vsRcGL3earZEW77JxrFjH4Ez2qaTiEfMgAXxfAZCm1fvM/G/o8w==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [x64]
|
||||
os: [sunos]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/win32-arm64@0.20.2:
|
||||
resolution: {integrity: sha512-GRibxoawM9ZCnDxnP3usoUDO9vUkpAxIIZ6GQI+IlVmr5kP3zUq+l17xELTHMWTWzjxa2guPNyrpq1GWmPvcGQ==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/win32-ia32@0.20.2:
|
||||
resolution: {integrity: sha512-HfLOfn9YWmkSKRQqovpnITazdtquEW8/SoHW7pWpuEeguaZI4QnCRW6b+oZTztdBnZOS2hqJ6im/D5cPzBTTlQ==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [ia32]
|
||||
os: [win32]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@esbuild/win32-x64@0.20.2:
|
||||
resolution: {integrity: sha512-N49X4lJX27+l9jbLKSqZ6bKNjzQvHaT8IIFUy+YIqmXQdjYCToGWwOItDrfby14c78aDd5NHQl29xingXfCdLQ==}
|
||||
engines: {node: '>=12'}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-android-arm-eabi@4.17.2:
|
||||
resolution: {integrity: sha512-NM0jFxY8bB8QLkoKxIQeObCaDlJKewVlIEkuyYKm5An1tdVZ966w2+MPQ2l8LBZLjR+SgyV+nRkTIunzOYBMLQ==}
|
||||
cpu: [arm]
|
||||
os: [android]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-android-arm64@4.17.2:
|
||||
resolution: {integrity: sha512-yeX/Usk7daNIVwkq2uGoq2BYJKZY1JfyLTaHO/jaiSwi/lsf8fTFoQW/n6IdAsx5tx+iotu2zCJwz8MxI6D/Bw==}
|
||||
cpu: [arm64]
|
||||
os: [android]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-darwin-arm64@4.17.2:
|
||||
resolution: {integrity: sha512-kcMLpE6uCwls023+kknm71ug7MZOrtXo+y5p/tsg6jltpDtgQY1Eq5sGfHcQfb+lfuKwhBmEURDga9N0ol4YPw==}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-darwin-x64@4.17.2:
|
||||
resolution: {integrity: sha512-AtKwD0VEx0zWkL0ZjixEkp5tbNLzX+FCqGG1SvOu993HnSz4qDI6S4kGzubrEJAljpVkhRSlg5bzpV//E6ysTQ==}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-linux-arm-gnueabihf@4.17.2:
|
||||
resolution: {integrity: sha512-3reX2fUHqN7sffBNqmEyMQVj/CKhIHZd4y631duy0hZqI8Qoqf6lTtmAKvJFYa6bhU95B1D0WgzHkmTg33In0A==}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-linux-arm-musleabihf@4.17.2:
|
||||
resolution: {integrity: sha512-uSqpsp91mheRgw96xtyAGP9FW5ChctTFEoXP0r5FAzj/3ZRv3Uxjtc7taRQSaQM/q85KEKjKsZuiZM3GyUivRg==}
|
||||
cpu: [arm]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-linux-arm64-gnu@4.17.2:
|
||||
resolution: {integrity: sha512-EMMPHkiCRtE8Wdk3Qhtciq6BndLtstqZIroHiiGzB3C5LDJmIZcSzVtLRbwuXuUft1Cnv+9fxuDtDxz3k3EW2A==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-linux-arm64-musl@4.17.2:
|
||||
resolution: {integrity: sha512-NMPylUUZ1i0z/xJUIx6VUhISZDRT+uTWpBcjdv0/zkp7b/bQDF+NfnfdzuTiB1G6HTodgoFa93hp0O1xl+/UbA==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-linux-powerpc64le-gnu@4.17.2:
|
||||
resolution: {integrity: sha512-T19My13y8uYXPw/L/k0JYaX1fJKFT/PWdXiHr8mTbXWxjVF1t+8Xl31DgBBvEKclw+1b00Chg0hxE2O7bTG7GQ==}
|
||||
cpu: [ppc64]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-linux-riscv64-gnu@4.17.2:
|
||||
resolution: {integrity: sha512-BOaNfthf3X3fOWAB+IJ9kxTgPmMqPPH5f5k2DcCsRrBIbWnaJCgX2ll77dV1TdSy9SaXTR5iDXRL8n7AnoP5cg==}
|
||||
cpu: [riscv64]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-linux-s390x-gnu@4.17.2:
|
||||
resolution: {integrity: sha512-W0UP/x7bnn3xN2eYMql2T/+wpASLE5SjObXILTMPUBDB/Fg/FxC+gX4nvCfPBCbNhz51C+HcqQp2qQ4u25ok6g==}
|
||||
cpu: [s390x]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-linux-x64-gnu@4.17.2:
|
||||
resolution: {integrity: sha512-Hy7pLwByUOuyaFC6mAr7m+oMC+V7qyifzs/nW2OJfC8H4hbCzOX07Ov0VFk/zP3kBsELWNFi7rJtgbKYsav9QQ==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-linux-x64-musl@4.17.2:
|
||||
resolution: {integrity: sha512-h1+yTWeYbRdAyJ/jMiVw0l6fOOm/0D1vNLui9iPuqgRGnXA0u21gAqOyB5iHjlM9MMfNOm9RHCQ7zLIzT0x11Q==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-win32-arm64-msvc@4.17.2:
|
||||
resolution: {integrity: sha512-tmdtXMfKAjy5+IQsVtDiCfqbynAQE/TQRpWdVataHmhMb9DCoJxp9vLcCBjEQWMiUYxO1QprH/HbY9ragCEFLA==}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-win32-ia32-msvc@4.17.2:
|
||||
resolution: {integrity: sha512-7II/QCSTAHuE5vdZaQEwJq2ZACkBpQDOmQsE6D6XUbnBHW8IAhm4eTufL6msLJorzrHDFv3CF8oCA/hSIRuZeQ==}
|
||||
cpu: [ia32]
|
||||
os: [win32]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@rollup/rollup-win32-x64-msvc@4.17.2:
|
||||
resolution: {integrity: sha512-TGGO7v7qOq4CYmSBVEYpI1Y5xDuCEnbVC5Vth8mOsW0gDSzxNrVERPc790IGHsrT2dQSimgMr9Ub3Y1Jci5/8w==}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/@types/estree@1.0.5:
|
||||
resolution: {integrity: sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==}
|
||||
dev: true
|
||||
|
||||
/esbuild@0.20.2:
|
||||
resolution: {integrity: sha512-WdOOppmUNU+IbZ0PaDiTst80zjnrOkyJNHoKupIcVyU8Lvla3Ugx94VzkQ32Ijqd7UhHJy75gNWDMUekcrSJ6g==}
|
||||
engines: {node: '>=12'}
|
||||
hasBin: true
|
||||
requiresBuild: true
|
||||
optionalDependencies:
|
||||
'@esbuild/aix-ppc64': 0.20.2
|
||||
'@esbuild/android-arm': 0.20.2
|
||||
'@esbuild/android-arm64': 0.20.2
|
||||
'@esbuild/android-x64': 0.20.2
|
||||
'@esbuild/darwin-arm64': 0.20.2
|
||||
'@esbuild/darwin-x64': 0.20.2
|
||||
'@esbuild/freebsd-arm64': 0.20.2
|
||||
'@esbuild/freebsd-x64': 0.20.2
|
||||
'@esbuild/linux-arm': 0.20.2
|
||||
'@esbuild/linux-arm64': 0.20.2
|
||||
'@esbuild/linux-ia32': 0.20.2
|
||||
'@esbuild/linux-loong64': 0.20.2
|
||||
'@esbuild/linux-mips64el': 0.20.2
|
||||
'@esbuild/linux-ppc64': 0.20.2
|
||||
'@esbuild/linux-riscv64': 0.20.2
|
||||
'@esbuild/linux-s390x': 0.20.2
|
||||
'@esbuild/linux-x64': 0.20.2
|
||||
'@esbuild/netbsd-x64': 0.20.2
|
||||
'@esbuild/openbsd-x64': 0.20.2
|
||||
'@esbuild/sunos-x64': 0.20.2
|
||||
'@esbuild/win32-arm64': 0.20.2
|
||||
'@esbuild/win32-ia32': 0.20.2
|
||||
'@esbuild/win32-x64': 0.20.2
|
||||
dev: true
|
||||
|
||||
/fsevents@2.3.3:
|
||||
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
|
||||
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
|
||||
os: [darwin]
|
||||
requiresBuild: true
|
||||
dev: true
|
||||
optional: true
|
||||
|
||||
/nanoid@3.3.7:
|
||||
resolution: {integrity: sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==}
|
||||
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
|
||||
hasBin: true
|
||||
dev: true
|
||||
|
||||
/node-addon-api@8.0.0:
|
||||
resolution: {integrity: sha512-ipO7rsHEBqa9STO5C5T10fj732ml+5kLN1cAG8/jdHd56ldQeGj3Q7+scUS+VHK/qy1zLEwC4wMK5+yM0btPvw==}
|
||||
engines: {node: ^18 || ^20 || >= 21}
|
||||
dev: true
|
||||
|
||||
/node-gyp-build@4.8.1:
|
||||
resolution: {integrity: sha512-OSs33Z9yWr148JZcbZd5WiAXhh/n9z8TxQcdMhIOlpN9AhWpLfvVFO73+m77bBABQMaY9XSvIa+qk0jlI7Gcaw==}
|
||||
hasBin: true
|
||||
dev: true
|
||||
|
||||
/picocolors@1.0.1:
|
||||
resolution: {integrity: sha512-anP1Z8qwhkbmu7MFP5iTt+wQKXgwzf7zTyGlcdzabySa9vd0Xt392U0rVmz9poOaBj0uHJKyyo9/upk0HrEQew==}
|
||||
dev: true
|
||||
|
||||
/postcss@8.4.38:
|
||||
resolution: {integrity: sha512-Wglpdk03BSfXkHoQa3b/oulrotAkwrlLDRSOb9D0bN86FdRyE9lppSp33aHNPgBa0JKCoB+drFLZkQoRRYae5A==}
|
||||
engines: {node: ^10 || ^12 || >=14}
|
||||
dependencies:
|
||||
nanoid: 3.3.7
|
||||
picocolors: 1.0.1
|
||||
source-map-js: 1.2.0
|
||||
dev: true
|
||||
|
||||
/rollup@4.17.2:
|
||||
resolution: {integrity: sha512-/9ClTJPByC0U4zNLowV1tMBe8yMEAxewtR3cUNX5BoEpGH3dQEWpJLr6CLp0fPdYRF/fzVOgvDb1zXuakwF5kQ==}
|
||||
engines: {node: '>=18.0.0', npm: '>=8.0.0'}
|
||||
hasBin: true
|
||||
dependencies:
|
||||
'@types/estree': 1.0.5
|
||||
optionalDependencies:
|
||||
'@rollup/rollup-android-arm-eabi': 4.17.2
|
||||
'@rollup/rollup-android-arm64': 4.17.2
|
||||
'@rollup/rollup-darwin-arm64': 4.17.2
|
||||
'@rollup/rollup-darwin-x64': 4.17.2
|
||||
'@rollup/rollup-linux-arm-gnueabihf': 4.17.2
|
||||
'@rollup/rollup-linux-arm-musleabihf': 4.17.2
|
||||
'@rollup/rollup-linux-arm64-gnu': 4.17.2
|
||||
'@rollup/rollup-linux-arm64-musl': 4.17.2
|
||||
'@rollup/rollup-linux-powerpc64le-gnu': 4.17.2
|
||||
'@rollup/rollup-linux-riscv64-gnu': 4.17.2
|
||||
'@rollup/rollup-linux-s390x-gnu': 4.17.2
|
||||
'@rollup/rollup-linux-x64-gnu': 4.17.2
|
||||
'@rollup/rollup-linux-x64-musl': 4.17.2
|
||||
'@rollup/rollup-win32-arm64-msvc': 4.17.2
|
||||
'@rollup/rollup-win32-ia32-msvc': 4.17.2
|
||||
'@rollup/rollup-win32-x64-msvc': 4.17.2
|
||||
fsevents: 2.3.3
|
||||
dev: true
|
||||
|
||||
/source-map-js@1.2.0:
|
||||
resolution: {integrity: sha512-itJW8lvSA0TXEphiRoawsCksnlf8SyvmFzIhltqAHluXd88pkCd+cXJVHTDwdCr0IzwptSm035IHQktUu1QUMg==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
dev: true
|
||||
|
||||
/tree-sitter-haskell@0.21.0(tree-sitter@0.21.1):
|
||||
resolution: {integrity: sha512-b2RLegPHuYPh7nJ3YKWgkWnFYxmYlQDE8TDJuNH+iuNuBcCMYyaA9JlJlMHfCvf7DmJNPtqqbO9Kh9NXEmbatQ==}
|
||||
requiresBuild: true
|
||||
peerDependencies:
|
||||
tree-sitter: ^0.21.0
|
||||
tree_sitter: '*'
|
||||
peerDependenciesMeta:
|
||||
tree_sitter:
|
||||
optional: true
|
||||
dependencies:
|
||||
node-addon-api: 8.0.0
|
||||
node-gyp-build: 4.8.1
|
||||
tree-sitter: 0.21.1
|
||||
dev: true
|
||||
|
||||
/tree-sitter@0.21.1:
|
||||
resolution: {integrity: sha512-7dxoA6kYvtgWw80265MyqJlkRl4yawIjO7S5MigytjELkX43fV2WsAXzsNfO7sBpPPCF5Gp0+XzHk0DwLCq3xQ==}
|
||||
requiresBuild: true
|
||||
dependencies:
|
||||
node-addon-api: 8.0.0
|
||||
node-gyp-build: 4.8.1
|
||||
dev: true
|
||||
|
||||
/vite@5.2.11:
|
||||
resolution: {integrity: sha512-HndV31LWW05i1BLPMUCE1B9E9GFbOu1MbenhS58FuK6owSO5qHm7GiCotrNY1YE5rMeQSFBGmT5ZaLEjFizgiQ==}
|
||||
engines: {node: ^18.0.0 || >=20.0.0}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
'@types/node': ^18.0.0 || >=20.0.0
|
||||
less: '*'
|
||||
lightningcss: ^1.21.0
|
||||
sass: '*'
|
||||
stylus: '*'
|
||||
sugarss: '*'
|
||||
terser: ^5.4.0
|
||||
peerDependenciesMeta:
|
||||
'@types/node':
|
||||
optional: true
|
||||
less:
|
||||
optional: true
|
||||
lightningcss:
|
||||
optional: true
|
||||
sass:
|
||||
optional: true
|
||||
stylus:
|
||||
optional: true
|
||||
sugarss:
|
||||
optional: true
|
||||
terser:
|
||||
optional: true
|
||||
dependencies:
|
||||
esbuild: 0.20.2
|
||||
postcss: 8.4.38
|
||||
rollup: 4.17.2
|
||||
optionalDependencies:
|
||||
fsevents: 2.3.3
|
||||
dev: true
|
||||
|
||||
/web-tree-sitter@0.20.8:
|
||||
resolution: {integrity: sha512-weOVgZ3aAARgdnb220GqYuh7+rZU0Ka9k9yfKtGAzEYMa6GgiCzW9JjQRJyCJakvibQW+dfjJdihjInKuuCAUQ==}
|
||||
dev: false
|
||||
136
packages/hs2js/src/hs2js.mjs
Normal file
136
packages/hs2js/src/hs2js.mjs
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
import { parse } from './parser.mjs';
|
||||
|
||||
function runApply(node, scope, ops) {
|
||||
if (node.children.length !== 2)
|
||||
throw new Error(`expected 2 children for node type apply, got ${node.children.length}`);
|
||||
const [fn, arg] = node.children.map((child) => run(child, scope, ops));
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`${node.children[0].text} is not a function`);
|
||||
}
|
||||
// only works if fn is curried!
|
||||
return fn(arg);
|
||||
}
|
||||
|
||||
function runInfix(left, symbol, right, ops) {
|
||||
const customOp = ops[symbol];
|
||||
if (customOp) {
|
||||
return customOp(left, right);
|
||||
}
|
||||
switch (symbol) {
|
||||
case '+':
|
||||
return left + right;
|
||||
case '-':
|
||||
return left - right;
|
||||
case '*':
|
||||
return left * right;
|
||||
case '/':
|
||||
return left / right;
|
||||
case '$':
|
||||
return left(right);
|
||||
case '&':
|
||||
console.log('right', right);
|
||||
return right(left);
|
||||
case '.':
|
||||
return (x) => left(right(x));
|
||||
default:
|
||||
throw new Error('unexpected infix operator ' + symbol);
|
||||
}
|
||||
}
|
||||
|
||||
function curry(patterns, body, scope, ops) {
|
||||
const [variable, ...rest] = patterns;
|
||||
return (arg) => {
|
||||
let _scope = { ...scope, [variable.text]: arg };
|
||||
if (patterns.length === 1) {
|
||||
const result = run(body, _scope, ops);
|
||||
return result;
|
||||
}
|
||||
return curry(rest, body, _scope, ops);
|
||||
};
|
||||
}
|
||||
|
||||
export function run(node, scope, ops = {}) {
|
||||
let runInScope = (node, scp = scope) => run(node, scp, ops);
|
||||
//console.log("node", node.type, node.text);
|
||||
if (ops[node.type]) {
|
||||
return ops[node.type](node);
|
||||
}
|
||||
switch (node.type) {
|
||||
case 'ERROR':
|
||||
throw new Error(`invalid syntax: "${node.text}"`);
|
||||
case 'declarations':
|
||||
let result;
|
||||
node.children.forEach((declaration) => {
|
||||
result = runInScope(declaration);
|
||||
});
|
||||
return result;
|
||||
case 'integer':
|
||||
return Number(node.text);
|
||||
case 'float':
|
||||
return Number(node.text);
|
||||
case 'string':
|
||||
const str = node.text.slice(1, -1);
|
||||
return String(str);
|
||||
case 'lambda':
|
||||
const [_, lpatterns, __, lbody] = node.children;
|
||||
return curry(lpatterns.children, lbody, scope, ops);
|
||||
case 'function':
|
||||
const [fvariable, fpatterns, fbody] = node.children;
|
||||
scope[fvariable.text] = curry(fpatterns.children, fbody, scope, ops);
|
||||
return scope[fvariable.text];
|
||||
case 'list': {
|
||||
return node.children
|
||||
.filter((_, i) => i % 2 === 1) // elements are at odd indices
|
||||
.map((node) => runInScope(node));
|
||||
}
|
||||
case 'match':
|
||||
if (node.children[0].text !== '=' || node.children.length !== 2) {
|
||||
throw new Error('match node so far only support simple assignments');
|
||||
}
|
||||
return runInScope(node.children[1]);
|
||||
case 'bind':
|
||||
if (node.children.length !== 2) throw new Error('expected 2 children for node type bind');
|
||||
if (node.children[0].type !== 'variable') throw new Error('expected variable as first child of bind node');
|
||||
if (node.children[1].type !== 'match') throw new Error('expected match as first child of bind node');
|
||||
const [bvariable, bmatch] = node.children;
|
||||
const value = runInScope(bmatch);
|
||||
scope[bvariable.text] = value;
|
||||
return value;
|
||||
case 'variable':
|
||||
return scope[node.text];
|
||||
case 'infix': {
|
||||
const [a, op, b] = node.children;
|
||||
const symbol = op.text;
|
||||
const [left, right] = [runInScope(a), runInScope(b)];
|
||||
return runInfix(left, symbol, right, ops);
|
||||
}
|
||||
case 'apply':
|
||||
return runApply(node, scope, ops);
|
||||
case 'left_section': {
|
||||
const [_, b, op] = node.children;
|
||||
const right = runInScope(b);
|
||||
return (left) => runInfix(left, op.text, right, ops);
|
||||
}
|
||||
case 'right_section': {
|
||||
const [_, op, b] = node.children;
|
||||
const right = runInScope(b);
|
||||
return (left) => runInfix(left, op.text, right, ops);
|
||||
}
|
||||
case 'parens':
|
||||
if (node.children.length !== 3) throw new Error('expected 3 children for node type parens');
|
||||
return runInScope(node.children[1]);
|
||||
default:
|
||||
if (node.children.length === 0) {
|
||||
throw new Error('unhandled leaf type ' + node.type);
|
||||
}
|
||||
if (node.children.length > 1) {
|
||||
throw new Error('unhandled branch type ' + node.type);
|
||||
}
|
||||
return runInScope(node.children[0]);
|
||||
}
|
||||
}
|
||||
|
||||
export function evaluate(haskellCode, scope = globalThis, ops) {
|
||||
const ast = parse(haskellCode);
|
||||
return run(ast.rootNode, scope, ops);
|
||||
}
|
||||
2
packages/hs2js/src/index.mjs
Normal file
2
packages/hs2js/src/index.mjs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export * from './hs2js.mjs';
|
||||
export * from './parser.mjs';
|
||||
37
packages/hs2js/src/parser.mjs
Normal file
37
packages/hs2js/src/parser.mjs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
import Parser from 'web-tree-sitter';
|
||||
|
||||
let base = '/';
|
||||
export function setBase(path) {
|
||||
base = path;
|
||||
}
|
||||
|
||||
let isReady = false,
|
||||
parser;
|
||||
async function _loadParser() {
|
||||
await Parser.init({
|
||||
locateFile(scriptName, scriptDirectory) {
|
||||
return `${base}${scriptName}`;
|
||||
},
|
||||
});
|
||||
parser = new Parser();
|
||||
const Lang = await Parser.Language.load(`${base}tree-sitter-haskell.wasm`);
|
||||
parser.setLanguage(Lang);
|
||||
isReady = true;
|
||||
return parser;
|
||||
}
|
||||
|
||||
let parserLoaded;
|
||||
export function loadParser() {
|
||||
if (!parserLoaded) {
|
||||
parserLoaded = _loadParser();
|
||||
}
|
||||
return parserLoaded;
|
||||
}
|
||||
|
||||
export function parse(code) {
|
||||
if (!isReady) {
|
||||
throw new Error('hs2js not ready. await loadParser before calling evaluate or parse functions');
|
||||
}
|
||||
// for some reason, the parser doesn't like new lines..
|
||||
return parser.parse(code.replaceAll('\n\n', '~~~~').replaceAll('\n', ' ').replaceAll('~~~~', ' \n'));
|
||||
}
|
||||
20
packages/hs2js/vite.config.js
Normal file
20
packages/hs2js/vite.config.js
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import { defineConfig } from 'vite';
|
||||
import { resolve } from 'path';
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [],
|
||||
build: {
|
||||
lib: {
|
||||
entry: resolve(__dirname, 'src', 'index.mjs'),
|
||||
name: 'hs2js',
|
||||
formats: ['es', 'iife'],
|
||||
fileName: (ext) => ({ es: 'index.mjs', iife: 'index.js' })[ext],
|
||||
},
|
||||
rollupOptions: {
|
||||
// external: [...Object.keys(dependencies)],
|
||||
plugins: [],
|
||||
},
|
||||
target: 'esnext',
|
||||
},
|
||||
});
|
||||
|
|
@ -5,7 +5,7 @@ This program is free software: you can redistribute it and/or modify it under th
|
|||
*/
|
||||
|
||||
import * as _WebMidi from 'webmidi';
|
||||
import { Pattern, isPattern, logger, ref } from '@strudel/core';
|
||||
import { Pattern, getEventOffsetMs, isPattern, logger, ref } from '@strudel/core';
|
||||
import { noteToMidi } from '@strudel/core';
|
||||
import { Note } from 'webmidi';
|
||||
// if you use WebMidi from outside of this package, make sure to import that instance:
|
||||
|
|
@ -112,25 +112,24 @@ Pattern.prototype.midi = function (output) {
|
|||
logger(`Midi device disconnected! Available: ${getMidiDeviceNamesString(outputs)}`),
|
||||
});
|
||||
|
||||
return this.onTrigger((time, hap, currentTime, cps) => {
|
||||
return this.onTrigger((time_deprecate, hap, currentTime, cps, targetTime) => {
|
||||
if (!WebMidi.enabled) {
|
||||
console.log('not enabled');
|
||||
return;
|
||||
}
|
||||
const device = getDevice(output, WebMidi.outputs);
|
||||
hap.ensureObjectValue();
|
||||
|
||||
const offset = (time - currentTime) * 1000;
|
||||
//magic number to get audio engine to line up, can probably be calculated somehow
|
||||
const latencyMs = 34;
|
||||
// passing a string with a +num into the webmidi api adds an offset to the current time https://webmidijs.org/api/classes/Output
|
||||
const timeOffsetString = `+${offset}`;
|
||||
|
||||
const timeOffsetString = `+${getEventOffsetMs(targetTime, currentTime) + latencyMs}`;
|
||||
// destructure value
|
||||
let { note, nrpnn, nrpv, ccn, ccv, midichan = 1, midicmd, gain = 1, velocity = 0.9 } = hap.value;
|
||||
|
||||
velocity = gain * velocity;
|
||||
|
||||
// note off messages will often a few ms arrive late, try to prevent glitching by subtracting from the duration length
|
||||
const duration = Math.floor((hap.duration.valueOf() / cps) * 1000 - 10);
|
||||
const duration = (hap.duration.valueOf() / cps) * 1000 - 10;
|
||||
if (note != null) {
|
||||
const midiNumber = typeof note === 'number' ? note : noteToMidi(note);
|
||||
const midiNote = new Note(midiNumber, { attack: velocity, duration });
|
||||
|
|
@ -177,7 +176,7 @@ export async function midin(input) {
|
|||
}
|
||||
const initial = await enableWebMidi(); // only returns on first init
|
||||
const device = getDevice(input, WebMidi.inputs);
|
||||
if (initial || WebMidi.enabled) {
|
||||
if (initial) {
|
||||
const otherInputs = WebMidi.inputs.filter((o) => o.name !== device.name);
|
||||
logger(
|
||||
`Midi enabled! Using "${device.name}". ${
|
||||
|
|
|
|||
25
packages/mini/bench/mini.bench.mjs
Normal file
25
packages/mini/bench/mini.bench.mjs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { describe, bench } from 'vitest';
|
||||
|
||||
import { calculateTactus } from '../../core/index.mjs';
|
||||
import { mini } from '../index.mjs';
|
||||
|
||||
describe('mini', () => {
|
||||
calculateTactus(true);
|
||||
bench(
|
||||
'+tactus',
|
||||
() => {
|
||||
mini('a b c*3 [c d e, f g] <a b [c d?]>').fast(64).firstCycle();
|
||||
},
|
||||
{ time: 1000 },
|
||||
);
|
||||
|
||||
calculateTactus(false);
|
||||
bench(
|
||||
'-tactus',
|
||||
() => {
|
||||
mini('a b c*3 [c d e, f g] <a b [c d?]>').fast(64).firstCycle();
|
||||
},
|
||||
{ time: 1000 },
|
||||
);
|
||||
calculateTactus(true);
|
||||
});
|
||||
|
|
@ -295,7 +295,14 @@ function peg$parse(input, options) {
|
|||
var peg$f6 = function(a) { return a };
|
||||
var peg$f7 = function(s) { s.arguments_.alignment = 'polymeter_slowcat'; return s; };
|
||||
var peg$f8 = function(a) { return x => x.options_['weight'] = (x.options_['weight'] ?? 1) + (a ?? 2) - 1 };
|
||||
var peg$f9 = function(a) { return x => x.options_['reps'] = (x.options_['reps'] ?? 1) + (a ?? 2) - 1 };
|
||||
var peg$f9 = function(a) { return x => {// A bit fiddly, to support both x!4 and x!!! as equivalent..
|
||||
const reps = (x.options_['reps'] ?? 1) + (a ?? 2) - 1;
|
||||
x.options_['reps'] = reps;
|
||||
x.options_['ops'] = x.options_['ops'].filter(x => x.type_ !== "replicate");
|
||||
x.options_['ops'].push({ type_: "replicate", arguments_ :{ amount:reps }});
|
||||
x.options_['weight'] = reps;
|
||||
}
|
||||
};
|
||||
var peg$f10 = function(p, s, r) { return x => x.options_['ops'].push({ type_: "bjorklund", arguments_ :{ pulse: p, step:s, rotation:r }}) };
|
||||
var peg$f11 = function(a) { return x => x.options_['ops'].push({ type_: "stretch", arguments_ :{ amount:a, type: 'slow' }}) };
|
||||
var peg$f12 = function(a) { return x => x.options_['ops'].push({ type_: "stretch", arguments_ :{ amount:a, type: 'fast' }}) };
|
||||
|
|
|
|||
|
|
@ -135,7 +135,14 @@ op_weight = ws ("@" / "_") a:number?
|
|||
{ return x => x.options_['weight'] = (x.options_['weight'] ?? 1) + (a ?? 2) - 1 }
|
||||
|
||||
op_replicate = ws "!" a:number?
|
||||
{ return x => x.options_['reps'] = (x.options_['reps'] ?? 1) + (a ?? 2) - 1 }
|
||||
{ return x => {// A bit fiddly, to support both x!4 and x!!! as equivalent..
|
||||
const reps = (x.options_['reps'] ?? 1) + (a ?? 2) - 1;
|
||||
x.options_['reps'] = reps;
|
||||
x.options_['ops'] = x.options_['ops'].filter(x => x.type_ !== "replicate");
|
||||
x.options_['ops'].push({ type_: "replicate", arguments_ :{ amount:reps }});
|
||||
x.options_['weight'] = reps;
|
||||
}
|
||||
}
|
||||
|
||||
op_bjorklund = "(" ws p:slice_with_ops ws comma ws s:slice_with_ops ws comma? ws r:slice_with_ops? ws ")"
|
||||
{ return x => x.options_['ops'].push({ type_: "bjorklund", arguments_ :{ pulse: p, step:s, rotation:r }}) }
|
||||
|
|
|
|||
|
|
@ -27,6 +27,12 @@ const applyOptions = (parent, enter) => (pat, i) => {
|
|||
pat = strudel.reify(pat)[type](enter(amount));
|
||||
break;
|
||||
}
|
||||
case 'replicate': {
|
||||
const { amount } = op.arguments_;
|
||||
pat = strudel.reify(pat);
|
||||
pat = pat._repeatCycles(amount)._fast(amount);
|
||||
break;
|
||||
}
|
||||
case 'bjorklund': {
|
||||
if (op.arguments_.rotation) {
|
||||
pat = pat.euclidRot(enter(op.arguments_.pulse), enter(op.arguments_.step), enter(op.arguments_.rotation));
|
||||
|
|
@ -67,26 +73,13 @@ const applyOptions = (parent, enter) => (pat, i) => {
|
|||
return pat;
|
||||
};
|
||||
|
||||
function resolveReplications(ast) {
|
||||
ast.source_ = strudel.flatten(
|
||||
ast.source_.map((child) => {
|
||||
const { reps } = child.options_ || {};
|
||||
if (!reps) {
|
||||
return [child];
|
||||
}
|
||||
delete child.options_.reps;
|
||||
return Array(reps).fill(child);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// expects ast from mini2ast + quoted mini string + optional callback when a node is entered
|
||||
export function patternifyAST(ast, code, onEnter, offset = 0) {
|
||||
onEnter?.(ast);
|
||||
const enter = (node) => patternifyAST(node, code, onEnter, offset);
|
||||
switch (ast.type_) {
|
||||
case 'pattern': {
|
||||
resolveReplications(ast);
|
||||
// resolveReplications(ast);
|
||||
const children = ast.source_.map((child) => enter(child)).map(applyOptions(ast, enter));
|
||||
const alignment = ast.arguments_.alignment;
|
||||
const with_tactus = children.filter((child) => child.__tactus_source);
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@
|
|||
},
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"bench": "vitest bench",
|
||||
"build:parser": "peggy -o krill-parser.js --format es ./krill.pegjs",
|
||||
"build": "vite build",
|
||||
"prepublishOnly": "npm run build"
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ This program is free software: you can redistribute it and/or modify it under th
|
|||
|
||||
import OSC from 'osc-js';
|
||||
|
||||
import { logger, parseNumeral, Pattern } from '@strudel/core';
|
||||
import { logger, parseNumeral, Pattern, getEventOffsetMs, isNote, noteToMidi } from '@strudel/core';
|
||||
|
||||
let connection; // Promise<OSC>
|
||||
function connect() {
|
||||
|
|
@ -44,7 +44,7 @@ function connect() {
|
|||
* @returns Pattern
|
||||
*/
|
||||
Pattern.prototype.osc = function () {
|
||||
return this.onTrigger(async (time, hap, currentTime, cps = 1) => {
|
||||
return this.onTrigger(async (time, hap, currentTime, cps = 1, targetTime) => {
|
||||
hap.ensureObjectValue();
|
||||
const osc = await connect();
|
||||
const cycle = hap.wholeOrPart().begin.valueOf();
|
||||
|
|
@ -52,11 +52,20 @@ Pattern.prototype.osc = function () {
|
|||
const controls = Object.assign({}, { cps, cycle, delta }, hap.value);
|
||||
// make sure n and note are numbers
|
||||
controls.n && (controls.n = parseNumeral(controls.n));
|
||||
controls.note && (controls.note = parseNumeral(controls.note));
|
||||
if (typeof controls.note !== 'undefined') {
|
||||
if (isNote(controls.note)) {
|
||||
controls.midinote = noteToMidi(controls.note, controls.octave || 3);
|
||||
} else {
|
||||
controls.note = parseNumeral(controls.note);
|
||||
}
|
||||
}
|
||||
controls.bank && (controls.s = controls.bank + controls.s);
|
||||
controls.roomsize && (controls.size = parseNumeral(controls.roomsize));
|
||||
const keyvals = Object.entries(controls).flat();
|
||||
// time should be audio time of onset
|
||||
// currentTime should be current time of audio context (slightly before time)
|
||||
const offset = (time - currentTime) * 1000;
|
||||
const offset = getEventOffsetMs(targetTime, currentTime);
|
||||
|
||||
// timestamp in milliseconds used to trigger the osc bundle at a precise moment
|
||||
const ts = Math.floor(Date.now() + offset);
|
||||
const message = new OSC.Message('/dirt/play', ...keyvals);
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/st
|
|||
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/>.
|
||||
*/
|
||||
|
||||
const OSC = require('osc-js');
|
||||
import OSC from 'osc-js';
|
||||
|
||||
const config = {
|
||||
receiver: 'ws', // @param {string} Where messages sent via 'send' method will be delivered to, 'ws' for Websocket clients, 'udp' for udp client
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/st
|
|||
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/>.
|
||||
*/
|
||||
|
||||
const OSC = require('osc-js');
|
||||
import OSC from 'osc-js';
|
||||
|
||||
const config = {
|
||||
receiver: 'ws', // @param {string} Where messages sent via 'send' method will be delivered to, 'ws' for Websocket clients, 'udp' for udp client
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@strudel/sampler",
|
||||
"version": "0.0.8",
|
||||
"version": "0.0.12",
|
||||
"description": "",
|
||||
"keywords": [
|
||||
"tidalcycles",
|
||||
|
|
|
|||
|
|
@ -48,8 +48,9 @@ async function getBanks(directory) {
|
|||
// const directory = resolve(__dirname, '.');
|
||||
let files = await getFilesInDirectory(directory);
|
||||
let banks = {};
|
||||
let separator = process.platform === 'win32' ? '\\' : '/';
|
||||
files = files.map((url) => {
|
||||
const [bank] = url.split('/').slice(-2);
|
||||
const [bank] = url.split(separator).slice(-2);
|
||||
banks[bank] = banks[bank] || [];
|
||||
url = url.replace(directory, '');
|
||||
banks[bank].push(url);
|
||||
|
|
|
|||
|
|
@ -74,6 +74,6 @@ export const dough = async (code) => {
|
|||
worklet.node.connect(ac.destination);
|
||||
};
|
||||
|
||||
export function doughTrigger(t, hap, currentTime, duration, cps) {
|
||||
window.postMessage({ time: t, dough: hap.value, currentTime, duration, cps });
|
||||
export function doughTrigger(time_deprecate, hap, currentTime, cps, targetTime) {
|
||||
window.postMessage({ time: targetTime, dough: hap.value, currentTime, duration: hap.duration, cps });
|
||||
}
|
||||
|
|
|
|||
|
|
@ -273,6 +273,12 @@ export const superdough = async (value, t, hapDuration) => {
|
|||
value.duration = hapDuration;
|
||||
// calculate absolute time
|
||||
t = typeof t === 'string' && t.startsWith('=') ? Number(t.slice(1)) : ac.currentTime + t;
|
||||
if (t < ac.currentTime) {
|
||||
console.warn(
|
||||
`[superdough]: cannot schedule sounds in the past (target: ${t.toFixed(2)}, now: ${ac.currentTime.toFixed(2)})`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
// destructure
|
||||
let {
|
||||
s = 'triangle',
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
// coarse, crush, and shape processors adapted from dktr0's webdirt: https://github.com/dktr0/WebDirt/blob/5ce3d698362c54d6e1b68acc47eb2955ac62c793/dist/AudioWorklets.js
|
||||
// LICENSE GNU General Public License v3.0 see https://github.com/dktr0/WebDirt/blob/main/LICENSE
|
||||
|
||||
const blockSize = 128;
|
||||
class CoarseProcessor extends AudioWorkletProcessor {
|
||||
static get parameterDescriptors() {
|
||||
return [{ name: 'coarse', defaultValue: 1 }];
|
||||
|
|
@ -8,19 +9,21 @@ class CoarseProcessor extends AudioWorkletProcessor {
|
|||
|
||||
constructor() {
|
||||
super();
|
||||
this.started = false;
|
||||
}
|
||||
|
||||
process(inputs, outputs, parameters) {
|
||||
const input = inputs[0];
|
||||
const output = outputs[0];
|
||||
const blockSize = 128;
|
||||
|
||||
const hasInput = !(input[0] === undefined);
|
||||
if (this.started && !hasInput) {
|
||||
return false;
|
||||
}
|
||||
this.started = hasInput;
|
||||
|
||||
let coarse = parameters.coarse[0] ?? 0;
|
||||
coarse = Math.max(1, coarse);
|
||||
|
||||
if (input[0] == null || output[0] == null) {
|
||||
return false;
|
||||
}
|
||||
for (let n = 0; n < blockSize; n++) {
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
output[i][n] = n % coarse === 0 ? input[i][n] : output[i][n - 1];
|
||||
|
|
@ -38,19 +41,22 @@ class CrushProcessor extends AudioWorkletProcessor {
|
|||
|
||||
constructor() {
|
||||
super();
|
||||
this.started = false;
|
||||
}
|
||||
|
||||
process(inputs, outputs, parameters) {
|
||||
const input = inputs[0];
|
||||
const output = outputs[0];
|
||||
const blockSize = 128;
|
||||
|
||||
const hasInput = !(input[0] === undefined);
|
||||
if (this.started && !hasInput) {
|
||||
return false;
|
||||
}
|
||||
this.started = hasInput;
|
||||
|
||||
let crush = parameters.crush[0] ?? 8;
|
||||
crush = Math.max(1, crush);
|
||||
|
||||
if (input[0] == null || output[0] == null) {
|
||||
return false;
|
||||
}
|
||||
for (let n = 0; n < blockSize; n++) {
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const x = Math.pow(2, crush - 1);
|
||||
|
|
@ -72,21 +78,24 @@ class ShapeProcessor extends AudioWorkletProcessor {
|
|||
|
||||
constructor() {
|
||||
super();
|
||||
this.started = false;
|
||||
}
|
||||
|
||||
process(inputs, outputs, parameters) {
|
||||
const input = inputs[0];
|
||||
const output = outputs[0];
|
||||
const blockSize = 128;
|
||||
|
||||
const hasInput = !(input[0] === undefined);
|
||||
if (this.started && !hasInput) {
|
||||
return false;
|
||||
}
|
||||
this.started = hasInput;
|
||||
|
||||
let shape = parameters.shape[0];
|
||||
shape = shape < 1 ? shape : 1.0 - 4e-10;
|
||||
shape = (2.0 * shape) / (1.0 - shape);
|
||||
const postgain = Math.max(0.001, Math.min(1, parameters.postgain[0]));
|
||||
|
||||
if (input[0] == null || output[0] == null) {
|
||||
return false;
|
||||
}
|
||||
for (let n = 0; n < blockSize; n++) {
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
output[i][n] = (((1 + shape) * input[i][n]) / (1 + shape * Math.abs(input[i][n]))) * postgain;
|
||||
|
|
@ -107,19 +116,22 @@ class DistortProcessor extends AudioWorkletProcessor {
|
|||
|
||||
constructor() {
|
||||
super();
|
||||
this.started = false;
|
||||
}
|
||||
|
||||
process(inputs, outputs, parameters) {
|
||||
const input = inputs[0];
|
||||
const output = outputs[0];
|
||||
const blockSize = 128;
|
||||
|
||||
const hasInput = !(input[0] === undefined);
|
||||
if (this.started && !hasInput) {
|
||||
return false;
|
||||
}
|
||||
this.started = hasInput;
|
||||
|
||||
const shape = Math.expm1(parameters.distort[0]);
|
||||
const postgain = Math.max(0.001, Math.min(1, parameters.postgain[0]));
|
||||
|
||||
if (input[0] == null || output[0] == null) {
|
||||
return false;
|
||||
}
|
||||
for (let n = 0; n < blockSize; n++) {
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
output[i][n] = (((1 + shape) * input[i][n]) / (1 + shape * Math.abs(input[i][n]))) * postgain;
|
||||
|
|
|
|||
28
packages/tidal/package.json
Normal file
28
packages/tidal/package.json
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
{
|
||||
"name": "@strudel/tidal",
|
||||
"version": "0.0.7",
|
||||
"description": "Experimental Tidal Code interpreter",
|
||||
"module": "tidal.mjs",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/felixroos/hs2js.git"
|
||||
},
|
||||
"keywords": [
|
||||
"haskell",
|
||||
"javascript"
|
||||
],
|
||||
"author": "Felix Roos <flix91@gmail.com>",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"bugs": {
|
||||
"url": "https://github.com/tidalcycles/strudel/issues"
|
||||
},
|
||||
"homepage": "https://github.com/tidalcycles/strudel/tree/main/packages/hs2js",
|
||||
"dependencies": {
|
||||
"hs2js": "workspace:*",
|
||||
"@strudel/core": "workspace:*",
|
||||
"@strudel/mini": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vite": "^5.0.10"
|
||||
}
|
||||
}
|
||||
73
packages/tidal/tidal.mjs
Normal file
73
packages/tidal/tidal.mjs
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import { reify } from '@strudel/core';
|
||||
import { m } from '@strudel/mini';
|
||||
import { loadParser, evaluate } from 'hs2js';
|
||||
|
||||
function getInfixOperators() {
|
||||
let operators = {
|
||||
'>': 'set',
|
||||
'#': 'set',
|
||||
'+': 'add',
|
||||
'-': 'sub',
|
||||
'*': 'mul',
|
||||
'/': 'div',
|
||||
};
|
||||
let alignments = {
|
||||
in: (s) => '|' + s,
|
||||
out: (s) => s + '|',
|
||||
mix: (s) => '|' + s + '|',
|
||||
};
|
||||
let ops = {};
|
||||
Object.entries(operators).forEach(([o, name]) => {
|
||||
// operator without alignment
|
||||
ops[o] = (l, r) => reify(l)[name](reify(r));
|
||||
Object.entries(alignments).forEach(([a, getSymbol]) => {
|
||||
// get symbol with alignment
|
||||
let symbol = getSymbol(o);
|
||||
ops[symbol] = (l, r) => reify(l)[name][a](reify(r));
|
||||
});
|
||||
});
|
||||
ops['~>'] = (l, r) => reify(l).late(reify(r));
|
||||
ops['<~'] = (l, r) => reify(l).early(reify(r));
|
||||
ops['<$>'] = (l, r) => reify(r).fmap(l).outerJoin(); // is this right?
|
||||
return ops;
|
||||
}
|
||||
const ops = getInfixOperators();
|
||||
|
||||
export async function initTidal() {
|
||||
// TODO: implement this in regular land
|
||||
window.d1 = (pat) => pat.p('d1');
|
||||
window.d2 = (pat) => pat.p('d2');
|
||||
window.d3 = (pat) => pat.p('d3');
|
||||
window.d4 = (pat) => pat.p('d4');
|
||||
window.d5 = (pat) => pat.p('d5');
|
||||
window.d6 = (pat) => pat.p('d6');
|
||||
window.d7 = (pat) => pat.p('d7');
|
||||
window.d8 = (pat) => pat.p('d8');
|
||||
window.d9 = (pat) => pat.p('d9');
|
||||
return loadParser();
|
||||
}
|
||||
|
||||
// offset is expected to be passed in from transpiler
|
||||
/*
|
||||
1. acorn parses JS to find location of tidal call
|
||||
2. haskell-tree-sitter calls "string" function with node (including location)
|
||||
3. m function sets locations for individual mini notation atom
|
||||
|
||||
so the location for a mini notation atom is:
|
||||
|
||||
js offset + hs offset + atom offset
|
||||
*/
|
||||
export function tidal(code, offset = 0) {
|
||||
if (Array.isArray(code)) {
|
||||
code = code.join('');
|
||||
}
|
||||
return evaluate(code, window, {
|
||||
...ops,
|
||||
string: (node) => {
|
||||
// parses strings as mini notation and passes location
|
||||
const str = node.text.slice(1, -1);
|
||||
const col = node.startIndex + offset;
|
||||
return m(str, col);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
@ -7,7 +7,7 @@ This program is free software: you can redistribute it and/or modify it under th
|
|||
// import { strict as assert } from 'assert';
|
||||
|
||||
import '../tonal.mjs'; // need to import this to add prototypes
|
||||
import { pure, n, seq } from '@strudel/core';
|
||||
import { pure, n, seq, note } from '@strudel/core';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { mini } from '../../mini/mini.mjs';
|
||||
|
||||
|
|
@ -44,4 +44,36 @@ describe('tonal', () => {
|
|||
.firstCycleValues.map((h) => h.note),
|
||||
).toEqual(['C3', 'D3', 'E3']);
|
||||
});
|
||||
it('transposes note numbers with interval numbers', () => {
|
||||
expect(
|
||||
note(40, 40, 40)
|
||||
.transpose(0, 1, 2)
|
||||
.firstCycleValues.map((h) => h.note),
|
||||
).toEqual([40, 41, 42]);
|
||||
expect(seq(40, 40, 40).transpose(0, 1, 2).firstCycleValues).toEqual([40, 41, 42]);
|
||||
});
|
||||
it('transposes note numbers with interval strings', () => {
|
||||
expect(
|
||||
note(40, 40, 40)
|
||||
.transpose('1P', '2M', '3m')
|
||||
.firstCycleValues.map((h) => h.note),
|
||||
).toEqual([40, 42, 43]);
|
||||
expect(seq(40, 40, 40).transpose('1P', '2M', '3m').firstCycleValues).toEqual([40, 42, 43]);
|
||||
});
|
||||
it('transposes note strings with interval numbers', () => {
|
||||
expect(
|
||||
note('c', 'c', 'c')
|
||||
.transpose(0, 1, 2)
|
||||
.firstCycleValues.map((h) => h.note),
|
||||
).toEqual(['C', 'Db', 'D']);
|
||||
expect(seq('c', 'c', 'c').transpose(0, 1, 2).firstCycleValues).toEqual(['C', 'Db', 'D']);
|
||||
});
|
||||
it('transposes note strings with interval strings', () => {
|
||||
expect(
|
||||
note('c', 'c', 'c')
|
||||
.transpose('1P', '2M', '3m')
|
||||
.firstCycleValues.map((h) => h.note),
|
||||
).toEqual(['C', 'D', 'Eb']);
|
||||
expect(seq('c', 'c', 'c').transpose('1P', '2M', '3m').firstCycleValues).toEqual(['C', 'D', 'Eb']);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -96,18 +96,37 @@ function scaleOffset(scale, offset, note) {
|
|||
|
||||
export const transpose = register('transpose', function (intervalOrSemitones, pat) {
|
||||
return pat.withHap((hap) => {
|
||||
const interval = !isNaN(Number(intervalOrSemitones))
|
||||
? Interval.fromSemitones(intervalOrSemitones /* as number */)
|
||||
: String(intervalOrSemitones);
|
||||
if (typeof hap.value === 'number') {
|
||||
const semitones = typeof interval === 'string' ? Interval.semitones(interval) || 0 : interval;
|
||||
return hap.withValue(() => hap.value + semitones);
|
||||
const note = hap.value.note ?? hap.value;
|
||||
if (typeof note === 'number') {
|
||||
// note is a number, so just add the number semitones of the interval
|
||||
let semitones;
|
||||
if (typeof intervalOrSemitones === 'number') {
|
||||
semitones = intervalOrSemitones;
|
||||
} else if (typeof intervalOrSemitones === 'string') {
|
||||
semitones = Interval.semitones(intervalOrSemitones) || 0;
|
||||
}
|
||||
const targetNote = note + semitones;
|
||||
if (typeof hap.value === 'object') {
|
||||
return hap.withValue(() => ({ ...hap.value, note: targetNote }));
|
||||
}
|
||||
return hap.withValue(() => targetNote);
|
||||
}
|
||||
if (typeof hap.value === 'object')
|
||||
return hap.withValue(() => ({ ...hap.value, note: Note.simplify(Note.transpose(hap.value.note, interval)) }));
|
||||
if (typeof note !== 'string' || !isNote(note)) {
|
||||
logger(`[tonal] transpose: not a note "${note}"`, 'warning');
|
||||
return hap;
|
||||
}
|
||||
// note is a string, so we might be able to preserve harmonics if interval is a string as well
|
||||
const interval = !isNaN(Number(intervalOrSemitones))
|
||||
? Interval.fromSemitones(intervalOrSemitones)
|
||||
: String(intervalOrSemitones);
|
||||
// TODO: move simplify to player to preserve enharmonics
|
||||
// tone.js doesn't understand multiple sharps flats e.g. F##3 has to be turned into G3
|
||||
return hap.withValue(() => Note.simplify(Note.transpose(hap.value, interval)));
|
||||
// TODO: check if this is still relevant..
|
||||
const targetNote = Note.simplify(Note.transpose(note, interval));
|
||||
if (typeof hap.value === 'object') {
|
||||
return hap.withValue(() => ({ ...hap.value, note: targetNote }));
|
||||
}
|
||||
return hap.withValue(() => targetNote);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -169,61 +188,66 @@ export const scaleTranspose = register('scaleTranspose', function (offset /* : n
|
|||
* .s("piano")
|
||||
*/
|
||||
|
||||
export const scale = register('scale', function (scale, pat) {
|
||||
// Supports ':' list syntax in mininotation
|
||||
if (Array.isArray(scale)) {
|
||||
scale = scale.flat().join(' ');
|
||||
}
|
||||
return (
|
||||
pat
|
||||
.fmap((value) => {
|
||||
const isObject = typeof value === 'object';
|
||||
let step = isObject ? value.n : value;
|
||||
if (isObject) {
|
||||
delete value.n; // remove n so it won't cause trouble
|
||||
}
|
||||
if (isNote(step)) {
|
||||
// legacy..
|
||||
return pure(step);
|
||||
}
|
||||
let asNumber = Number(step);
|
||||
let semitones = 0;
|
||||
if (isNaN(asNumber)) {
|
||||
step = String(step);
|
||||
if (!/^[-+]?\d+(#*|b*){1}$/.test(step)) {
|
||||
logger(
|
||||
`[tonal] invalid scale step "${step}", expected number or integer with optional # b suffixes`,
|
||||
'error',
|
||||
);
|
||||
return silence;
|
||||
export const scale = register(
|
||||
'scale',
|
||||
function (scale, pat) {
|
||||
// Supports ':' list syntax in mininotation
|
||||
if (Array.isArray(scale)) {
|
||||
scale = scale.flat().join(' ');
|
||||
}
|
||||
return (
|
||||
pat
|
||||
.fmap((value) => {
|
||||
const isObject = typeof value === 'object';
|
||||
let step = isObject ? value.n : value;
|
||||
if (isObject) {
|
||||
delete value.n; // remove n so it won't cause trouble
|
||||
}
|
||||
const isharp = step.indexOf('#');
|
||||
if (isharp >= 0) {
|
||||
asNumber = Number(step.substring(0, isharp));
|
||||
semitones = step.length - isharp;
|
||||
} else {
|
||||
const iflat = step.indexOf('b');
|
||||
asNumber = Number(step.substring(0, iflat));
|
||||
semitones = iflat - step.length;
|
||||
if (isNote(step)) {
|
||||
// legacy..
|
||||
return pure(step);
|
||||
}
|
||||
}
|
||||
try {
|
||||
let note;
|
||||
if (isObject && value.anchor) {
|
||||
note = stepInNamedScale(asNumber, scale, value.anchor);
|
||||
} else {
|
||||
note = scaleStep(asNumber, scale);
|
||||
let asNumber = Number(step);
|
||||
let semitones = 0;
|
||||
if (isNaN(asNumber)) {
|
||||
step = String(step);
|
||||
if (!/^[-+]?\d+(#*|b*){1}$/.test(step)) {
|
||||
logger(
|
||||
`[tonal] invalid scale step "${step}", expected number or integer with optional # b suffixes`,
|
||||
'error',
|
||||
);
|
||||
return silence;
|
||||
}
|
||||
const isharp = step.indexOf('#');
|
||||
if (isharp >= 0) {
|
||||
asNumber = Number(step.substring(0, isharp));
|
||||
semitones = step.length - isharp;
|
||||
} else {
|
||||
const iflat = step.indexOf('b');
|
||||
asNumber = Number(step.substring(0, iflat));
|
||||
semitones = iflat - step.length;
|
||||
}
|
||||
}
|
||||
if (semitones != 0) note = Note.transpose(note, Interval.fromSemitones(semitones));
|
||||
value = pure(isObject ? { ...value, note } : note);
|
||||
} catch (err) {
|
||||
logger(`[tonal] ${err.message}`, 'error');
|
||||
value = silence;
|
||||
}
|
||||
return value;
|
||||
})
|
||||
.outerJoin()
|
||||
// legacy:
|
||||
.withHap((hap) => hap.setContext({ ...hap.context, scale }))
|
||||
);
|
||||
});
|
||||
try {
|
||||
let note;
|
||||
if (isObject && value.anchor) {
|
||||
note = stepInNamedScale(asNumber, scale, value.anchor);
|
||||
} else {
|
||||
note = scaleStep(asNumber, scale);
|
||||
}
|
||||
if (semitones != 0) note = Note.transpose(note, Interval.fromSemitones(semitones));
|
||||
value = pure(isObject ? { ...value, note } : note);
|
||||
} catch (err) {
|
||||
logger(`[tonal] ${err.message}`, 'error');
|
||||
value = silence;
|
||||
}
|
||||
return value;
|
||||
})
|
||||
.outerJoin()
|
||||
// legacy:
|
||||
.withHap((hap) => hap.setContext({ ...hap.context, scale }))
|
||||
);
|
||||
},
|
||||
true,
|
||||
true, // preserve tactus
|
||||
);
|
||||
|
|
|
|||
|
|
@ -235,6 +235,11 @@ Object.keys(simple).forEach((symbol) => {
|
|||
let alias = symbol.replace('^', 'M');
|
||||
voicingAlias(symbol, alias, [complex, simple]);
|
||||
}
|
||||
// add aliases for "+" === "aug"
|
||||
if (symbol.includes('+')) {
|
||||
let alias = symbol.replace('+', 'aug');
|
||||
voicingAlias(symbol, alias, [complex, simple]);
|
||||
}
|
||||
});
|
||||
|
||||
registerVoicings('ireal', simple);
|
||||
|
|
|
|||
|
|
@ -26,6 +26,16 @@ export function transpiler(input, options = {}) {
|
|||
|
||||
walk(ast, {
|
||||
enter(node, parent /* , prop, index */) {
|
||||
if (isTidalTeplateLiteral(node)) {
|
||||
const raw = node.quasi.quasis[0].value.raw;
|
||||
const offset = node.quasi.start + 1;
|
||||
if (emitMiniLocations) {
|
||||
const stringLocs = collectHaskellMiniLocations(raw, offset);
|
||||
miniLocations = miniLocations.concat(stringLocs);
|
||||
}
|
||||
this.skip();
|
||||
return this.replace(tidalWithLocation(raw, offset));
|
||||
}
|
||||
if (isBackTickString(node, parent)) {
|
||||
const { quasis } = node;
|
||||
const { raw } = quasis[0].value;
|
||||
|
|
@ -207,3 +217,47 @@ function labelToP(node) {
|
|||
},
|
||||
};
|
||||
}
|
||||
|
||||
// tidal highlighting
|
||||
// this feels kind of stupid, when we also know the location inside the string op (tidal.mjs)
|
||||
// but maybe it's the only way
|
||||
|
||||
function isTidalTeplateLiteral(node) {
|
||||
return node.type === 'TaggedTemplateExpression' && node.tag.name === 'tidal';
|
||||
}
|
||||
|
||||
function collectHaskellMiniLocations(haskellCode, offset) {
|
||||
return haskellCode
|
||||
.split('')
|
||||
.reduce((acc, char, i) => {
|
||||
if (char !== '"') {
|
||||
return acc;
|
||||
}
|
||||
if (!acc.length || acc[acc.length - 1].length > 1) {
|
||||
acc.push([i + 1]);
|
||||
} else {
|
||||
acc[acc.length - 1].push(i);
|
||||
}
|
||||
return acc;
|
||||
}, [])
|
||||
.map(([start, end]) => {
|
||||
const miniString = haskellCode.slice(start, end);
|
||||
return getLeafLocations(`"${miniString}"`, offset + start - 1);
|
||||
})
|
||||
.flat();
|
||||
}
|
||||
|
||||
function tidalWithLocation(value, offset) {
|
||||
return {
|
||||
type: 'CallExpression',
|
||||
callee: {
|
||||
type: 'Identifier',
|
||||
name: 'tidal',
|
||||
},
|
||||
arguments: [
|
||||
{ type: 'Literal', value },
|
||||
{ type: 'Literal', value: offset },
|
||||
],
|
||||
optional: false,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue