« get me outta code hell

patches.js « data « src - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/data/patches.js
blob: 3ed4fad0c5a5e6577cee8f665f46e915719f9a1e (plain)
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
// --> Patch

export class Patch {
    static INPUT_NONE = 0;
    static INPUT_CONSTANT = 1;
    static INPUT_DIRECT_CONNECTION = 2;
    static INPUT_MANAGED_CONNECTION = 3;

    static INPUT_UNAVAILABLE = 0;
    static INPUT_AVAILABLE = 1;

    static OUTPUT_UNAVAILABLE = 0;
    static OUTPUT_AVAILABLE = 1;

    static inputNames = []; inputNames = null;
    static outputNames = []; outputNames = null;

    manager = null;
    inputs = Object.create(null);

    constructor({
        manager,

        inputNames,
        outputNames,

        inputs,
    } = {}) {
        this.inputNames = inputNames ?? this.constructor.inputNames;
        this.outputNames = outputNames ?? this.constructor.outputNames;

        manager?.addManagedPatch(this);

        if (inputs) {
            Object.assign(this.inputs, inputs);
        }

        this.initializeInputs();
    }

    initializeInputs() {
        for (const inputName of this.inputNames) {
            if (!this.inputs[inputName]) {
                this.inputs[inputName] = [Patch.INPUT_NONE];
            }
        }
    }

    computeInputs() {
        const inputs = Object.create(null);

        for (const inputName of this.inputNames) {
            const input = this.inputs[inputName];
            switch (input[0]) {
                case Patch.INPUT_NONE:
                    inputs[inputName] = [Patch.INPUT_UNAVAILABLE];
                    break;

                case Patch.INPUT_CONSTANT:
                    inputs[inputName] = [Patch.INPUT_AVAILABLE, input[1]];
                    break;

                case Patch.INPUT_DIRECT_CONNECTION: {
                    const patch = input[1];
                    const outputName = input[2];
                    const output = patch.computeOutputs()[outputName];
                    switch (output[0]) {
                        case Patch.OUTPUT_UNAVAILABLE:
                            inputs[inputName] = [Patch.INPUT_UNAVAILABLE];
                            break;
                        case Patch.OUTPUT_AVAILABLE:
                            inputs[inputName] = [Patch.INPUT_AVAILABLE, output[1]];
                            break;
                    }
                    throw new Error('Unreachable');
                }

                case Patch.INPUT_MANAGED_CONNECTION: {
                    if (!this.manager) {
                        inputs[inputName] = [Patch.INPUT_UNAVAILABLE];
                        break;
                    }

                    inputs[inputName] = this.manager.getManagedInput(input[1]);
                    break;
                }
            }
        }

        return inputs;
    }

    computeOutputs() {
        const inputs = this.computeInputs();
        const outputs = Object.create(null);
        console.log(`Compute: ${this.constructor.name}`);
        this.compute(inputs, outputs);
        return outputs;
    }

    compute(inputs, outputs) {
        // No-op. Return all outputs as unavailable. This should be overridden
        // in subclasses.

        for (const outputName of this.constructor.outputNames) {
            outputs[outputName] = [Patch.OUTPUT_UNAVAILABLE];
        }
    }

    attachToManager(manager) {
        manager.addManagedPatch(this);
    }

    detachFromManager() {
        if (this.manager) {
            this.manager.removeManagedPatch(this);
        }
    }
}

// --> PatchManager

export class PatchManager extends Patch {
    managedPatches = [];
    managedInputs = {};

    #externalInputPatch = null;
    #externalOutputPatch = null;

    constructor(...args) {
        super(...args);

        this.#externalInputPatch = new PatchManagerExternalInputPatch({manager: this});
        this.#externalOutputPatch = new PatchManagerExternalOutputPatch({manager: this});
    }

    addManagedPatch(patch) {
        if (patch.manager === this) {
            return false;
        }

        patch.detachFromManager();
        patch.manager = this;

        if (patch.manager === this) {
            this.managedPatches.push(patch);
            return true;
        } else {
            return false;
        }
    }

    removeManagedPatch(patch) {
        if (patch.manager !== this) {
            return false;
        }

        patch.manager = null;

        if (patch.manager === this) {
            return false;
        }

        for (const inputNames of patch.inputNames) {
            const input = patch.inputs[inputName];
            if (input[0] === Patch.INPUT_MANAGED_CONNECTION) {
                this.dropManagedInput(input[1]);
                patch.inputs[inputName] = [Patch.INPUT_NONE];
            }
        }

        this.managedPatches.splice(this.managedPatches.indexOf(patch), 1);

        return true;
    }

    addManagedInput(patchWithInput, inputName, patchWithOutput, outputName) {
        if (patchWithInput.manager !== this || patchWithOutput.manager !== this) {
            throw new Error(`Input and output patches must belong to same manager (this)`);
        }

        const input = patchWithInput.inputs[inputName];
        if (input[0] === Patch.INPUT_MANAGED_CONNECTION) {
            this.managedInputs[input[1]] = [patchWithOutput, outputName, {}];
        } else {
            const key = this.getManagedConnectionIdentifier();
            this.managedInputs[key] = [patchWithOutput, outputName, {}];
            patchWithInput.inputs[inputName] = [Patch.INPUT_MANAGED_CONNECTION, key];
        }

        return true;
    }

    dropManagedInput(identifier) {
        return delete this.managedInputs[key];
    }

    getManagedInput(identifier) {
        const connection = this.managedInputs[identifier];
        const patch = connection[0];
        const outputName = connection[1];
        const memory = connection[2];
        return this.computeManagedInput(patch, outputName, memory);
    }

    computeManagedInput(patch, outputName, memory) {
        // Override this function in subclasses to alter behavior of the "wire"
        // used for connecting patches.

        const output = patch.computeOutputs()[outputName];
        switch (output[0]) {
            case Patch.OUTPUT_UNAVAILABLE:
                return [Patch.INPUT_UNAVAILABLE];
            case Patch.OUTPUT_AVAILABLE:
                return [Patch.INPUT_AVAILABLE, output[1]];
        }
    }

    #managedConnectionIdentifier = 0;
    getManagedConnectionIdentifier() {
        return this.#managedConnectionIdentifier++;
    }

    addExternalInput(patchWithInput, patchInputName, managerInputName) {
        return this.addManagedInput(patchWithInput, patchInputName, this.#externalInputPatch, managerInputName);
    }

    setExternalOutput(managerOutputName, patchWithOutput, patchOutputName) {
        return this.addManagedInput(this.#externalOutputPatch, managerOutputName, patchWithOutput, patchOutputName);
    }

    compute(inputs, outputs) {
        Object.assign(outputs, this.#externalOutputPatch.computeOutputs());
    }
}

class PatchManagerExternalInputPatch extends Patch {
    constructor({manager, ...rest}) {
        super({
            manager,
            inputNames: manager.inputNames,
            outputNames: manager.inputNames,
            ...rest
        });
    }

    computeInputs() {
        return this.manager.computeInputs();
    }

    compute(inputs, outputs) {
        for (const name of this.inputNames) {
            const input = inputs[name];
            switch (input[0]) {
                case Patch.INPUT_UNAVAILABLE:
                    outputs[name] = [Patch.OUTPUT_UNAVAILABLE];
                    break;
                case Patch.INPUT_AVAILABLE:
                    outputs[name] = [Patch.INPUT_AVAILABLE, input[1]];
                    break;
            }
        }
    }
}

class PatchManagerExternalOutputPatch extends Patch {
    constructor({manager, ...rest}) {
        super({
            manager,
            inputNames: manager.outputNames,
            outputNames: manager.outputNames,
            ...rest
        });
    }

    compute(inputs, outputs) {
        for (const name of this.inputNames) {
            const input = inputs[name];
            switch (input[0]) {
                case Patch.INPUT_UNAVAILABLE:
                    outputs[name] = [Patch.OUTPUT_UNAVAILABLE];
                    break;
                case Patch.INPUT_AVAILABLE:
                    outputs[name] = [Patch.INPUT_AVAILABLE, input[1]];
                    break;
            }
        }
    }
}

// --> demo

const caches = Symbol();
const common = Symbol();
const hsmusic = Symbol();

Patch[caches] = {
    WireCachedPatchManager: class extends PatchManager {
        // "Wire" caching for PatchManager: Remembers the last outputs to come
        // from each patch. As long as the inputs for a patch do not change, its
        // cached outputs are reused.

        // TODO: This has a unique cache for each managed input. It should
        // re-use a cache for the same patch and output name. How can we ensure
        // the cache is dropped when the patch is removed, though? (Spoilers:
        // probably just override removeManagedPatch)
        computeManagedInput(patch, outputName, memory) {
            let cache = true;

            const { previousInputs } = memory;
            const { inputs } = patch;
            if (memory.previousInputs) {
                for (const inputName of patch.inputNames) {
                    // TODO: This doesn't account for connections whose values
                    // have changed (analogous to bubbling cache invalidation).
                    if (inputs[inputName] !== previousInputs[inputName]) {
                        cache = false;
                        break;
                    }
                }
            } else {
                cache = false;
            }

            if (cache) {
                return memory.previousOutputs[outputName];
            }

            const outputs = patch.computeOutputs();
            memory.previousOutputs = outputs;
            memory.previousInputs = {...inputs};
            return outputs[outputName];
        }
    },
};

Patch[common] = {
    Stringify: class extends Patch {
        static inputNames = ['value'];
        static outputNames = ['value'];

        compute(inputs, outputs) {
            if (inputs.value[0] === Patch.INPUT_AVAILABLE) {
                outputs.value = [Patch.OUTPUT_AVAILABLE, inputs.value[1].toString()];
            } else {
                outputs.value = [Patch.OUTPUT_UNAVAILABLE];
            }
        }
    },

    Echo: class extends Patch {
        static inputNames = ['value'];
        static outputNames = ['value'];

        compute(inputs, outputs) {
            if (inputs.value[0] === Patch.INPUT_AVAILABLE) {
                outputs.value = [Patch.OUTPUT_AVAILABLE, inputs.value[1]];
            } else {
                outputs.value = [Patch.OUTPUT_UNAVAILABLE];
            }
        }
    },
};

const PM = new Patch[caches].WireCachedPatchManager({
    inputNames: ['externalInput'],
    outputNames: ['externalOutput'],
});

const P1 = new Patch[common].Stringify({manager: PM});
const P2 = new Patch[common].Echo({manager: PM});

PM.addExternalInput(P1, 'value', 'externalInput');
PM.addManagedInput(P2, 'value', P1, 'value');
PM.setExternalOutput('externalOutput', P2, 'value');

PM.inputs.externalInput = [Patch.INPUT_CONSTANT, 123];
console.log(PM.computeOutputs());
console.log(PM.computeOutputs());