-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgraph.js
537 lines (505 loc) · 12.8 KB
/
graph.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
export class Node {
constructor(type, value) {
this.type = type;
value !== undefined && (this.value = value);
this.ins = [];
}
// connect nodes to input node(s), return this node
withIns(...ins) {
this.ins = ins;
return this;
}
withValue(value) {
this.value = value;
return this;
}
addInput(node) {
this.ins.push(node);
return this;
}
flatten() {
return flatten(this);
}
dagify() {
return dagify(this);
}
apply(fn) {
return fn(this);
}
apply2(fn) {
// clock(10).seq(51,52,0,53).apply2(hold).midinote().sine().out()
return fn(this, this);
}
clone() {
return new Node(this.type, this.value).withIns(...this.ins);
}
map(fn) {
if (this.type !== "poly") {
return fn(this);
}
return poly(...this.ins.map(fn));
}
walk(fn) {
return this.map((node) => dfs(node, fn));
}
log(fn = (x) => x) {
console.log(fn(this));
return this;
}
}
let dfs = (node, fn, visited = []) => {
node = fn(node);
visited.push(node);
node.ins = node.ins.map((input) =>
visited.includes(input) ? input : dfs(input, fn, visited)
);
return node;
};
export let modules = new Map(); // module registry
// user facing function to create modules
export function module(name, fn) {
modules.set(name, fn);
return register(name, (...args) => getNode(name, ...args));
}
export function resolveModules(node) {
return node.walk((node) => {
if (modules.has(node.type)) {
const fn = modules.get(node.type);
node = fn(...node.ins).resolveModules(node);
}
return node;
});
}
Node.prototype.resolveModules = function () {
return resolveModules(this);
};
// converts a registered module into a json string
export function exportModule(name) {
const mod = modules.get(name);
const inputs = Array.from({ length: mod.length }, (_, i) =>
node(`$INPUT${i}`)
);
const exported = mod(...inputs);
return JSON.stringify(exported, null, 2);
}
// returns true if the given node forms a cycle with "me" (or is me)
function loopsToMe(node, me) {
if (node === me) {
return true;
}
if (node.ins.length === 0) {
return false;
}
for (let neighbor of node.ins) {
if (neighbor.ins.includes(me)) {
return true;
}
return loopsToMe(neighbor, me);
}
}
// transforms the graph into a dag, where cycles are broken into feedback_read and feedback_write nodes
function dagify(node) {
let visitedNodes = [];
function dfs(currentNode) {
if (visitedNodes.includes(currentNode)) {
// currentNode has one or more cycles, find them...
const feedbackSources = currentNode.ins.filter((input) =>
loopsToMe(input, currentNode)
);
if (!feedbackSources.length) {
// it might happen that we end up here again after dagification..
return;
}
feedbackSources.forEach((feedbackSource) => {
const feedbackInlet = currentNode.ins.indexOf(feedbackSource);
const feedbackReader = new Node("feedback_read");
currentNode.ins[feedbackInlet] = feedbackReader;
const feedbackWriter = new Node("feedback_write");
feedbackWriter.ins = [feedbackSource];
feedbackWriter.to = feedbackReader;
node.ins.push(feedbackWriter);
});
return;
}
visitedNodes.push(currentNode);
if (!currentNode.ins.length) {
return;
}
for (const neighbor of currentNode.ins) {
dfs(neighbor);
}
}
dfs(node);
return node;
}
function visit(node, visited = []) {
visited.push(node);
node.ins.forEach((child) => {
if (!visited.includes(child)) {
visit(child, visited);
}
});
return visited;
}
function flatten(node) {
const flat = visit(node);
return flat.map((node) => {
let clone = {
type: node.type,
ins: node.ins.map((child) => flat.indexOf(child) + ""),
};
node.value !== undefined && (clone.value = node.value);
node.to !== undefined && (clone.to = flat.indexOf(node.to));
return clone;
});
}
export function evaluate(code) {
// make sure to call Object.assign(globalThis, api);
let nodes = [];
Node.prototype.out = function () {
nodes.push(this);
};
try {
Function(code)();
const node = dac(...nodes).exit();
return node;
} catch (err) {
console.error(err);
return n(0);
}
}
// TODO: find a cool api to register functions (maybe similar to strudel's register)
// so far, node types added here also have to be added to the compiler, as well as NODE_CLASSES (for audio nodes)
// it would be nice if there was a way to define custom functions / nodes / dsp logic in a single place...
// let index = 0;
export const node = (type, value) => new Node(type, value /* , ++index */);
export function n(value) {
if (Array.isArray(value)) {
return poly(...value.map((v) => n(v)));
}
if (typeof value === "object") {
return value;
}
return node("n", value);
//return parseInput(value);
}
const polyType = "poly";
const outputType = "dac";
function parseInput(input, node) {
if (Array.isArray(input)) {
input = new Node(polyType).withIns(...input);
}
if (input.type === polyType) {
// mind bending here we go
return input.withIns(...input.ins.map((arg) => parseInput(arg, input)));
}
if (typeof input === "function") {
return node.apply(input);
}
if (typeof input === "object") {
// is node
return input;
}
if (typeof input === "number" && !isNaN(input)) {
return n(input);
}
console.log(
`invalid input type "${typeof input}" for node of type, falling back to 0. The input was:`,
input
);
return 0;
}
function getNode(type, ...args) {
const next = node(type);
args = args.map((arg) => parseInput(arg, next));
// gets channels per arg
const expansions = args.map((arg) => {
if (arg.type === polyType) {
return arg.ins.length;
}
return 1;
});
// max channels to expand. the 1 is to make sure empty args won't break!
const maxExpansions = Math.max(1, ...expansions);
// no expansion early exit
if (maxExpansions === 1) {
return next.withIns(...args.map(parseInput));
}
// dont expand dac node, but instead input all channels
if (type === outputType) {
const inputs = args
.map((arg) => {
if (arg.type === polyType) {
return arg.ins;
}
return arg;
})
.flat();
return node(outputType).withIns(...inputs);
}
// multichannel expansion:
// node([a,b,c], [x,y]) => expand(node(a,x), node(b,y), node(c,x))
const expanded = Array.from({ length: maxExpansions }, (_, i) => {
const inputs = args.map((arg) => {
if (arg.type === polyType) {
return parseInput(arg.ins[i % arg.ins.length]);
}
return parseInput(arg);
});
return new Node(type).withIns(...inputs);
});
return new Node(polyType).withIns(...expanded);
}
export let makeNode = (type, name = type.toLowerCase()) => {
Node.prototype[name] = function (...args) {
return getNode(type, this, ...args);
};
return (...args) => {
return getNode(type, ...args);
};
};
export let adsr = makeNode("ADSR");
export let clock = makeNode("Clock");
export let clockdiv = makeNode("ClockDiv");
export let distort = makeNode("Distort");
export let noise = makeNode("Noise");
export let pinknoise = makeNode("PinkNoise");
export let pink = makeNode("PinkNoise");
export let brown = makeNode("BrownNoise");
export let dust = makeNode("Dust");
export let pulse = makeNode("Pulse");
export let impulse = makeNode("Impulse");
export let saw = makeNode("Saw");
export let sine = makeNode("Sine");
export let tri = makeNode("Tri");
export let slide = makeNode("Slide");
export let slew = makeNode("Slew");
export let lag = makeNode("Lag");
export let filter = makeNode("Filter");
export let fold = makeNode("Fold");
export let seq = makeNode("Seq");
export let delay = makeNode("Delay");
export let hold = makeNode("Hold");
// export let midin = makeNode("MidiIn");
export let midifreq = makeNode("MidiFreq");
export let midigate = makeNode("MidiGate");
export let midicc = makeNode("MidiCC");
export let audioin = makeNode("AudioIn");
// non-audio nodes
export let sin = makeNode("sin");
export let cos = makeNode("cos");
export let mul = makeNode("mul");
export let add = makeNode("add");
export let div = makeNode("div");
export let sub = makeNode("sub");
export let mod = makeNode("mod"); // untested
export let range = makeNode("range");
export let midinote = makeNode("midinote");
export let dac = makeNode("dac");
export let exit = makeNode("exit");
export let poly = makeNode("poly");
export let register = (name, fn) => {
Node.prototype[name] = function (...args) {
return fn(this, ...args);
};
return fn;
};
export let fork = register("fork", (input, times = 1) =>
poly(...Array.from({ length: times }, () => input.clone()))
);
export let perc = module("perc", (gate, release) =>
gate.adsr(0, 0, 1, release)
);
export let hpf = module("hpf", (input, cutoff, resonance = 0) =>
input.filter(1, resonance).sub(input.filter(cutoff, resonance))
);
export let lpf = module("lpf", filter); // alias
export let lfnoise = module("lfnoise", (freq) => noise().hold(impulse(freq)));
export let mix = register("mix", (input) => {
if (input.type !== "poly") {
return input;
}
return node("mix").withIns(...input.ins);
});
Node.prototype.over = function (fn) {
return this.apply((x) => add(x, fn(x)));
};
// legacy...
Node.prototype.feedback = function (fn) {
return this.add(fn);
};
export let feedback = (fn) => add(fn);
export function getInletName(type, index) {
if (!NODE_SCHEMA[type]?.ins?.[index]) {
return "";
}
return NODE_SCHEMA[type].ins[index].name;
}
// not implemented noisecraft nodes
// TODO:
// Greater, ClockOut, Scope, BitCrush?
// Different Names:
// Add (=add), AudioOut (=out), Const (=n)
// WONT DO:
// GateSeq, MonoSeq, Knob, MonoSeq, Nop, Notes (text note), Module
// this schema is currently only relevant for audio nodes, using, flags dynamic & time, + ins[].default
// TODO: compress format?
export const NODE_SCHEMA = {
ADSR: {
ins: [
{ name: "gate", default: 0 },
{ name: "att", default: 0.02 },
{ name: "dec", default: 0.1 },
{ name: "sus", default: 0.2 },
{ name: "rel", default: 0.1 },
],
args: ["time"], // if set, the update function will get time as first param
},
range: {
audio: false,
ins: [{ name: "in" }, { name: "min" }, { name: "max" }],
},
Clock: {
ins: [{ name: "bpm", default: 120 }],
},
ClockDiv: {
ins: [
{ name: "clock", default: 0 },
{ name: "divisor", default: 2 },
],
},
Delay: {
ins: [
{ name: "in", default: 0 },
{ name: "time", default: 0 },
],
},
Distort: {
ins: [
{ name: "in", default: 0 },
{ name: "amt", default: 0 },
],
},
Filter: {
ins: [
{ name: "in", default: 0 },
{ name: "cutoff", default: 1 },
{ name: "reso", default: 0 },
],
},
Fold: {
ins: [
{ name: "in", default: 0 },
{ name: "rate", default: 0 },
],
},
Seq: {
dynamic: true, // dynamic number of inlets
ins: [
{ name: "clock", default: 0 },
// 1-Infinity of steps
],
},
Hold: {
ins: [
{ name: "in", default: 0 },
{ name: "trig", default: 0 },
],
},
feedback_read: {
ins: [],
},
// feedback_write is a special case in the compiler, so it won't appear here..
AudioIn: {
ins: [],
args: ["input"],
},
MidiIn: {
ins: [],
},
MidiGate: {
ins: [{ name: "channel", default: -1 }],
},
MidiFreq: {
ins: [{ name: "channel", default: -1 }],
},
MidiCC: {
ins: [
{ name: "ccnumber", default: -1 },
{ name: "channel", default: -1 },
],
},
Mod: {
ins: [
{ name: "in0", default: 0 },
{ name: "in1", default: 1 },
],
},
Mul: {
ins: [
{ name: "in0", default: 1 },
{ name: "in1", default: 1 },
],
},
Noise: {
ins: [],
},
PinkNoise: {
ins: [],
},
BrownNoise: {
ins: [],
},
Dust: {
ins: [{ name: "density", default: 0 }],
},
Pulse: {
ins: [
{ name: "freq", default: 0 },
{ name: "pw", default: 0.5 },
],
},
Impulse: {
ins: [
{ name: "freq", default: 0 },
{ name: "phase", default: 0 },
],
},
Saw: {
ins: [{ name: "freq", default: 0 }],
},
/* Scope: {
ins: [{ name: "", default: 0 }],
sendRate: 20,
sendSize: 5,
historyLen: 150,
}, */
Sine: {
ins: [
{ name: "freq", default: 0 },
{ name: "sync", default: 0 },
],
},
Slide: {
ins: [
{ name: "in", default: 0 },
{ name: "rate", default: 1 },
],
},
Lag: {
ins: [
{ name: "in", default: 0 },
{ name: "rate", default: 1 },
],
},
Slew: {
ins: [
{ name: "in", default: 0 },
{ name: "up", default: 1 },
{ name: "dn", default: 1 },
],
},
Tri: {
ins: [{ name: "freq", default: 0 }],
},
};