@vim3d/core 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -2
- package/ch-operators.d.ts +18 -0
- package/ch-operators.js +174 -0
- package/channels.d.ts +2 -0
- package/channels.js +14 -5
- package/compile.js +322 -28
- package/contexts.d.ts +57 -0
- package/contexts.js +330 -0
- package/esm/ch-operators.js +170 -0
- package/esm/channels.js +11 -4
- package/esm/compile.js +323 -29
- package/esm/contexts.js +323 -0
- package/esm/evaluate.js +99 -11
- package/esm/expression.js +34 -8
- package/esm/graph.js +27 -5
- package/esm/index.js +1 -0
- package/esm/ramp.js +36 -0
- package/esm/ranges.js +9 -0
- package/esm/registry.js +96 -0
- package/evaluate.d.ts +2 -2
- package/evaluate.js +98 -10
- package/expression.d.ts +11 -2
- package/expression.js +34 -8
- package/graph.d.ts +3 -0
- package/graph.js +27 -5
- package/index.d.ts +3 -1
- package/index.js +4 -1
- package/model.d.ts +15 -1
- package/package.json +2 -2
- package/ramp.d.ts +8 -0
- package/ramp.js +40 -0
- package/ranges.d.ts +2 -0
- package/ranges.js +12 -0
- package/registry.d.ts +22 -0
- package/registry.js +101 -0
- package/types.d.ts +79 -3
package/contexts.js
ADDED
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Extensions = void 0;
|
|
4
|
+
exports.jsonProp = jsonProp;
|
|
5
|
+
exports.checkAudioFrame = checkAudioFrame;
|
|
6
|
+
exports.createContextEvaluation = createContextEvaluation;
|
|
7
|
+
const channels_js_1 = require("./channels.js");
|
|
8
|
+
const graph_js_1 = require("./graph.js");
|
|
9
|
+
const expression_js_1 = require("./expression.js");
|
|
10
|
+
const registry_js_1 = require("./registry.js");
|
|
11
|
+
const ranges_js_1 = require("./ranges.js");
|
|
12
|
+
const types_js_1 = require("./types.js");
|
|
13
|
+
const nodeType = /^[a-zA-Z][a-zA-Z0-9_-]*:[a-zA-Z][a-zA-Z0-9_-]*$/;
|
|
14
|
+
const propTypes = new Set(['string', 'number', 'boolean', 'object']);
|
|
15
|
+
const portTypes = new Set([...propTypes, 'vector3', 'matrix4']);
|
|
16
|
+
function jsonProp(text, invalid) {
|
|
17
|
+
const raw = text?.trimEnd().match(/^[ \t:]*(?:set|"set")[ \t]+(?:"[^"]*"|[^ \t]+)[ \t]+(.*)$/)?.[1];
|
|
18
|
+
const literal = raw?.match(/^(?:"(?:\\.|[^"\\])*"|[^"#])*/)?.[0];
|
|
19
|
+
try {
|
|
20
|
+
return JSON.parse(literal);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return invalid();
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function isRecord(value) {
|
|
27
|
+
return value !== null && typeof value === 'object' &&
|
|
28
|
+
(Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
|
|
29
|
+
}
|
|
30
|
+
function matches(value, type) {
|
|
31
|
+
if (type === 'object')
|
|
32
|
+
return isRecord(value) || Array.isArray(value);
|
|
33
|
+
if (type === 'number')
|
|
34
|
+
return typeof value === 'number' && Number.isFinite(value);
|
|
35
|
+
if (type === 'vector3' || type === 'matrix4') {
|
|
36
|
+
return Array.isArray(value) && value.length === (type === 'vector3' ? 3 : 16) &&
|
|
37
|
+
Array.from(value).every(item => typeof item === 'number' && Number.isFinite(item));
|
|
38
|
+
}
|
|
39
|
+
return typeof value === type;
|
|
40
|
+
}
|
|
41
|
+
function copyValue(value, invalid, seen = new Set()) {
|
|
42
|
+
if (value === null)
|
|
43
|
+
return null;
|
|
44
|
+
if (typeof value === 'string' || typeof value === 'boolean' ||
|
|
45
|
+
(typeof value === 'number' && Number.isFinite(value)))
|
|
46
|
+
return value;
|
|
47
|
+
if ((!Array.isArray(value) && !isRecord(value)) || seen.has(value))
|
|
48
|
+
return invalid();
|
|
49
|
+
seen.add(value);
|
|
50
|
+
const copy = Array.isArray(value) ? Array.from(value, item => copyValue(item, invalid, seen))
|
|
51
|
+
: Object.fromEntries(Object.entries(value).map(([key, item]) => [key, copyValue(item, invalid, seen)]));
|
|
52
|
+
seen.delete(value);
|
|
53
|
+
return (0, types_js_1.freeze)(copy);
|
|
54
|
+
}
|
|
55
|
+
function definitions(entries, types, kind, owner) {
|
|
56
|
+
if (!Array.isArray(entries))
|
|
57
|
+
(0, types_js_1.fail)('invalid-extension-definition', 'Expected ' + kind + ' definitions for ' + owner);
|
|
58
|
+
const map = new Map();
|
|
59
|
+
for (const entry of entries) {
|
|
60
|
+
if (!entry || typeof entry.name !== 'string' || !(0, channels_js_1.validSegment)(entry.name) || !types.has(entry.type) || map.has(entry.name)) {
|
|
61
|
+
(0, types_js_1.fail)('invalid-extension-definition', 'Invalid or duplicate ' + kind + ' on ' + owner + ': ' + entry?.name);
|
|
62
|
+
}
|
|
63
|
+
map.set(entry.name, { ...entry });
|
|
64
|
+
}
|
|
65
|
+
return map;
|
|
66
|
+
}
|
|
67
|
+
class Extensions {
|
|
68
|
+
registry;
|
|
69
|
+
types = new Map();
|
|
70
|
+
nodes = new Map();
|
|
71
|
+
constructor(registry) {
|
|
72
|
+
this.registry = registry;
|
|
73
|
+
for (const context of registry.contexts) {
|
|
74
|
+
const { name, stage, nodeTypes } = context;
|
|
75
|
+
if (stage === 'obj' || stage === 'ch' || stage === 'reserved')
|
|
76
|
+
continue;
|
|
77
|
+
const types = new Map();
|
|
78
|
+
for (const definition of nodeTypes) {
|
|
79
|
+
const { type, evaluate } = definition;
|
|
80
|
+
if (!nodeType.test(type) || typeof evaluate !== 'function')
|
|
81
|
+
(0, types_js_1.fail)('invalid-extension-definition', 'Invalid node type: ' + type);
|
|
82
|
+
if (types.has(type))
|
|
83
|
+
(0, types_js_1.fail)('duplicate-extension-type', 'Duplicate node type in /' + name + ': ' + type);
|
|
84
|
+
const owner = '/' + name + ' ' + type;
|
|
85
|
+
const inputs = definitions(definition.inputs, portTypes, 'input', owner);
|
|
86
|
+
const outputs = definitions(definition.outputs, portTypes, 'output', owner);
|
|
87
|
+
const props = definitions(definition.props, propTypes, 'prop', owner);
|
|
88
|
+
for (const [key, prop] of props) {
|
|
89
|
+
const invalid = () => (0, types_js_1.fail)('invalid-extension-definition', 'Invalid prop definition on ' + owner + ': ' + key);
|
|
90
|
+
if (prop.required !== undefined && typeof prop.required !== 'boolean')
|
|
91
|
+
invalid();
|
|
92
|
+
if (prop.default !== undefined) {
|
|
93
|
+
if (!matches(prop.default, prop.type))
|
|
94
|
+
invalid();
|
|
95
|
+
props.set(key, { ...prop, default: copyValue(prop.default, invalid) });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
types.set(type, { type, inputs, outputs, props, evaluate });
|
|
99
|
+
}
|
|
100
|
+
this.types.set(name, types);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
add(path, type, source) {
|
|
104
|
+
const [root, context, name, ...extra] = path.split('/');
|
|
105
|
+
if (root || !context || !(0, channels_js_1.validSegment)(name) || extra.length)
|
|
106
|
+
(0, types_js_1.fail)('invalid-path', 'Expected an extension node path: ' + path, source);
|
|
107
|
+
const registered = this.registry.get(context);
|
|
108
|
+
if (!registered)
|
|
109
|
+
(0, types_js_1.fail)('unknown-extension-context', 'Unknown extension context: /' + context, source);
|
|
110
|
+
const definition = this.types.get(context)?.get(type);
|
|
111
|
+
if (!definition)
|
|
112
|
+
(0, types_js_1.fail)('unknown-extension-type', 'Unknown node type in /' + context + ': ' + type, source);
|
|
113
|
+
if (this.nodes.has(path))
|
|
114
|
+
(0, types_js_1.fail)('duplicate-name', 'Name is already used: ' + path, source);
|
|
115
|
+
const props = new Map();
|
|
116
|
+
for (const [key, def] of definition.props)
|
|
117
|
+
if (def.default !== undefined)
|
|
118
|
+
props.set(key, def.default);
|
|
119
|
+
const node = { path, context, stage: registered.stage, definition, source, props, drivers: new Map() };
|
|
120
|
+
this.nodes.set(path, node);
|
|
121
|
+
return node;
|
|
122
|
+
}
|
|
123
|
+
property(address, args, text, source) {
|
|
124
|
+
const { node, key } = this.member(address, source);
|
|
125
|
+
const def = node.definition.props.get(key);
|
|
126
|
+
if (!def)
|
|
127
|
+
(0, types_js_1.fail)('unknown-extension-prop', 'Unknown prop: ' + address, source);
|
|
128
|
+
const invalid = () => (0, types_js_1.fail)('invalid-extension-prop', 'Expected ' + def.type + ' for ' + address, source);
|
|
129
|
+
let value = args[0];
|
|
130
|
+
if (def.type === 'object') {
|
|
131
|
+
value = jsonProp(text, invalid);
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
if (args.length !== 1)
|
|
135
|
+
(0, types_js_1.fail)('invalid-operands', 'Expected one value for ' + address, source);
|
|
136
|
+
if (def.type === 'number')
|
|
137
|
+
value = args[0].trim() === '' ? NaN : Number(args[0]);
|
|
138
|
+
if (def.type === 'boolean')
|
|
139
|
+
value = args[0] === 'true' ? true : args[0] === 'false' ? false : undefined;
|
|
140
|
+
}
|
|
141
|
+
if (!matches(value, def.type))
|
|
142
|
+
invalid();
|
|
143
|
+
node.props.set(key, copyValue(value, invalid));
|
|
144
|
+
}
|
|
145
|
+
input(address, type, driver, source) {
|
|
146
|
+
const { node, key } = this.member(address, source);
|
|
147
|
+
const port = node.definition.inputs.get(key);
|
|
148
|
+
if (!port)
|
|
149
|
+
(0, types_js_1.fail)('unknown-extension-port', 'Unknown input port: ' + address, source);
|
|
150
|
+
if (port.type !== type)
|
|
151
|
+
(0, types_js_1.fail)('extension-port-type', 'Expected ' + port.type + ' at ' + address + ', got ' + type, source);
|
|
152
|
+
for (const from of driver.kind === 'wire' ? [driver.from] : driver.references) {
|
|
153
|
+
if (!(0, registry_js_1.allowedSource)(node.stage, from.stage))
|
|
154
|
+
(0, types_js_1.fail)('extension-stage', address + ' cannot read ' + from.address, source);
|
|
155
|
+
}
|
|
156
|
+
if (node.drivers.has(key))
|
|
157
|
+
(0, types_js_1.fail)('overlapping-drivers', 'Input already has a driver: ' + address, source);
|
|
158
|
+
node.drivers.set(key, driver);
|
|
159
|
+
}
|
|
160
|
+
output(address, source) {
|
|
161
|
+
const { node, key } = this.member(address, source);
|
|
162
|
+
if (node.stage === 'output')
|
|
163
|
+
(0, types_js_1.fail)('extension-stage', 'Cannot read an output-stage node: ' + node.path, source);
|
|
164
|
+
const port = node.definition.outputs.get(key);
|
|
165
|
+
if (!port)
|
|
166
|
+
(0, types_js_1.fail)('unknown-extension-port', 'Unknown output port: ' + address, source);
|
|
167
|
+
return { address, path: node.path, port: key, type: port.type, stage: node.stage };
|
|
168
|
+
}
|
|
169
|
+
numericPort(address, source) {
|
|
170
|
+
const { node, key } = this.member(address, source);
|
|
171
|
+
if (node.definition.inputs.get(key)?.type !== 'number' && node.definition.outputs.get(key)?.type !== 'number') {
|
|
172
|
+
(0, types_js_1.fail)('extension-port-type', 'Expected a numeric port at ' + address, source);
|
|
173
|
+
}
|
|
174
|
+
return address;
|
|
175
|
+
}
|
|
176
|
+
member(address, source) {
|
|
177
|
+
const [root, context, name, key, ...extra] = address.split('/');
|
|
178
|
+
if (root || !context || !name || !key || extra.length)
|
|
179
|
+
(0, types_js_1.fail)('invalid-path', 'Expected an extension member path: ' + address, source);
|
|
180
|
+
if (!this.registry.get(context))
|
|
181
|
+
(0, types_js_1.fail)('unknown-extension-context', 'Unknown extension context: /' + context, source);
|
|
182
|
+
const path = '/' + context + '/' + name;
|
|
183
|
+
const node = this.nodes.get(path);
|
|
184
|
+
if (!node)
|
|
185
|
+
(0, types_js_1.fail)('missing-target', 'Unknown extension node: ' + path, source);
|
|
186
|
+
return { node, key };
|
|
187
|
+
}
|
|
188
|
+
addToGraph(graph) {
|
|
189
|
+
for (const node of this.nodes.values()) {
|
|
190
|
+
const { definition, path, context, source } = node;
|
|
191
|
+
for (const [name, prop] of definition.props) {
|
|
192
|
+
if (prop.required && !node.props.has(name))
|
|
193
|
+
(0, types_js_1.fail)('missing-extension-prop', 'Missing required prop: ' + path + '/' + name, source);
|
|
194
|
+
}
|
|
195
|
+
const props = [...node.props.keys()].sort(graph_js_1.comparePaths).map(name => ({
|
|
196
|
+
name, type: definition.props.get(name).type, value: node.props.get(name),
|
|
197
|
+
}));
|
|
198
|
+
for (const input of [...node.drivers.keys()].sort(graph_js_1.comparePaths)) {
|
|
199
|
+
const driver = node.drivers.get(input);
|
|
200
|
+
if (driver.kind === 'expr') {
|
|
201
|
+
props.push({ name: 'expr/' + input, type: 'object', value: driver.expression });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
graph.addNode(path, { context, type: definition.type, props,
|
|
205
|
+
inputs: [...definition.inputs.values()], outputs: [...definition.outputs.values()] }, source);
|
|
206
|
+
}
|
|
207
|
+
for (const { path, drivers } of this.nodes.values()) {
|
|
208
|
+
for (const [input, driver] of drivers) {
|
|
209
|
+
for (const from of driver.kind === 'wire' ? [driver.from] : driver.references) {
|
|
210
|
+
graph.expose(from.path, { name: from.port, type: from.type });
|
|
211
|
+
graph.wire(path, input, from.path, from.port);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
exports.Extensions = Extensions;
|
|
218
|
+
function checkAudioFrame(path, sampleFrame, frame) {
|
|
219
|
+
if (Math.abs(sampleFrame - frame) > 1e-9) {
|
|
220
|
+
(0, types_js_1.fail)('off-time-audio-reference', 'Audio features are available only at the evaluated frame: ' + path);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
function createContextEvaluation(extensions, order, frame, time, fps, frameCount, options, readBuiltIn, ranges) {
|
|
224
|
+
const used = new Set([...extensions.nodes.values()].map(node => node.context));
|
|
225
|
+
const contextNames = extensions.registry.contexts.filter(({ stage, name }) => stage === 'evaluate' || stage === 'output' || used.has(name)).map(({ name }) => name).sort(graph_js_1.comparePaths);
|
|
226
|
+
let base;
|
|
227
|
+
let objects = new Map();
|
|
228
|
+
const values = new Map();
|
|
229
|
+
const snapshots = new Map();
|
|
230
|
+
const sorted = [...extensions.nodes.keys()].sort(graph_js_1.comparePaths);
|
|
231
|
+
const read = (path, sampleFrame, rampPosition) => {
|
|
232
|
+
if (path.startsWith('/ch/'))
|
|
233
|
+
return readBuiltIn(path, sampleFrame, rampPosition);
|
|
234
|
+
if (path.startsWith('/obj/')) {
|
|
235
|
+
const end = path.lastIndexOf('/');
|
|
236
|
+
const object = objects.get(path.slice(0, end));
|
|
237
|
+
const key = path.slice(end + 1);
|
|
238
|
+
if (key === 'snapshot')
|
|
239
|
+
return copyValue(object, () => (0, types_js_1.fail)('invalid-extension-input', 'Invalid object snapshot: ' + path));
|
|
240
|
+
if (key === 'worldMatrix' || key === 'localMatrix')
|
|
241
|
+
return object[key];
|
|
242
|
+
return object.parameters[key];
|
|
243
|
+
}
|
|
244
|
+
if (path.startsWith('/audio/'))
|
|
245
|
+
checkAudioFrame(path, sampleFrame, frame);
|
|
246
|
+
return values.get(path);
|
|
247
|
+
};
|
|
248
|
+
const snapshot = () => {
|
|
249
|
+
if (!contextNames.length)
|
|
250
|
+
return base;
|
|
251
|
+
const contexts = Object.fromEntries(contextNames.map(name => [name, []]));
|
|
252
|
+
for (const path of sorted) {
|
|
253
|
+
const node = snapshots.get(path);
|
|
254
|
+
if (node)
|
|
255
|
+
contexts[node.context].push(node);
|
|
256
|
+
}
|
|
257
|
+
return (0, types_js_1.freeze)({ ...base, contexts });
|
|
258
|
+
};
|
|
259
|
+
function run(stage) {
|
|
260
|
+
const inputSnapshot = stage === 'output' ? snapshot() : undefined;
|
|
261
|
+
for (const path of order) {
|
|
262
|
+
const node = extensions.nodes.get(path);
|
|
263
|
+
if (!node || node.stage !== stage)
|
|
264
|
+
continue;
|
|
265
|
+
const { definition, source, context } = node;
|
|
266
|
+
const inputs = Object.fromEntries([...node.drivers].map(([key, driver]) => {
|
|
267
|
+
const value = driver.kind === 'wire' ? read(driver.from.address, frame) : (0, expression_js_1.evaluateExpression)(driver.expression, {
|
|
268
|
+
frame, fps, frameCount, source: driver.source, read: (address, sampleFrame, u) => read(address, sampleFrame, u),
|
|
269
|
+
});
|
|
270
|
+
return [key, typeof value === 'number' ? (0, ranges_js_1.applyRange)(ranges, path + '/' + key, value) : value];
|
|
271
|
+
}));
|
|
272
|
+
if (ranges && stage === 'geo' && definition.type === 'geo:transform') {
|
|
273
|
+
for (const [key, fallback] of Object.entries(registry_js_1.geoTransformDefaults)) {
|
|
274
|
+
const address = path + '/' + key;
|
|
275
|
+
if (ranges[address] && !Object.hasOwn(inputs, key))
|
|
276
|
+
inputs[key] = (0, ranges_js_1.applyRange)(ranges, address, fallback);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
const props = (0, types_js_1.freeze)(Object.fromEntries(node.props));
|
|
280
|
+
const evaluate = definition.evaluate;
|
|
281
|
+
const audio = options.audio;
|
|
282
|
+
const name = path.slice('/audio/'.length);
|
|
283
|
+
const data = stage === 'audio' && audio
|
|
284
|
+
? Object.hasOwn(audio, path) ? audio[path] : Object.hasOwn(audio, name) ? audio[name] : undefined
|
|
285
|
+
: undefined;
|
|
286
|
+
const ctx = (0, types_js_1.freeze)({ path, frame, time, fps, inputs, props, ...(inputSnapshot && { snapshot: inputSnapshot }) });
|
|
287
|
+
let result;
|
|
288
|
+
try {
|
|
289
|
+
result = stage === 'audio' ? evaluate(ctx, data) : evaluate(ctx);
|
|
290
|
+
}
|
|
291
|
+
catch (error) {
|
|
292
|
+
if (error instanceof types_js_1.EvaluationError || (stage !== 'evaluate' && stage !== 'output'))
|
|
293
|
+
throw error;
|
|
294
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
295
|
+
(0, types_js_1.fail)('plugin-error', `${path}: ${message}`, source);
|
|
296
|
+
}
|
|
297
|
+
const returned = result === undefined ? {} : result;
|
|
298
|
+
if (!isRecord(returned))
|
|
299
|
+
(0, types_js_1.fail)('invalid-extension-output', 'Expected an output record from ' + path, source);
|
|
300
|
+
for (const name of Object.keys(returned)) {
|
|
301
|
+
if (!definition.outputs.has(name))
|
|
302
|
+
(0, types_js_1.fail)('invalid-extension-output', 'Undeclared output: ' + path + '/' + name, source);
|
|
303
|
+
}
|
|
304
|
+
const outputs = Object.fromEntries([...definition.outputs].map(([name, { type }]) => {
|
|
305
|
+
const address = path + '/' + name;
|
|
306
|
+
const value = Object.hasOwn(returned, name) ? returned[name] : undefined;
|
|
307
|
+
const invalid = () => (0, types_js_1.fail)('invalid-extension-output', 'Expected ' + type + ' output at ' + address, source);
|
|
308
|
+
if (type === 'number' && typeof value === 'number' && !Number.isFinite(value)) {
|
|
309
|
+
(0, types_js_1.fail)('non-finite', address + ' must be finite', source);
|
|
310
|
+
}
|
|
311
|
+
if (!matches(value, type))
|
|
312
|
+
invalid();
|
|
313
|
+
const output = typeof value === 'number' ? (0, ranges_js_1.applyRange)(ranges, address, value) : copyValue(value, invalid);
|
|
314
|
+
values.set(address, output);
|
|
315
|
+
return [name, output];
|
|
316
|
+
}));
|
|
317
|
+
snapshots.set(path, (0, types_js_1.freeze)({ path, context, type: definition.type, stage, props, inputs, outputs }));
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return {
|
|
321
|
+
run, read,
|
|
322
|
+
finish(snapshotBase) {
|
|
323
|
+
base = snapshotBase;
|
|
324
|
+
objects = new Map(base.objects.map(object => [object.path, object]));
|
|
325
|
+
run('evaluate');
|
|
326
|
+
run('output');
|
|
327
|
+
return snapshot();
|
|
328
|
+
},
|
|
329
|
+
};
|
|
330
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { wrap } from './math.js';
|
|
2
|
+
import { fail, finite } from './types.js';
|
|
3
|
+
const numberProp = (name, value) => ({ name, type: 'number', ...(value !== undefined && { default: value }) });
|
|
4
|
+
const stringProp = (name, value) => ({ name, type: 'string', default: value });
|
|
5
|
+
const scalar = [{ name: 'value', type: 'number' }];
|
|
6
|
+
function operator(definition) {
|
|
7
|
+
return {
|
|
8
|
+
...definition, inputs: scalar, outputs: scalar,
|
|
9
|
+
evaluate: ({ inputs, props, frame, fps }) => {
|
|
10
|
+
const value = (inputs.value ?? 0);
|
|
11
|
+
const source = { file: '<channel operator>', line: 1 };
|
|
12
|
+
const invalid = (message) => fail('invalid-channel-operator', message, source);
|
|
13
|
+
const configured = { ...Object.fromEntries(definition.props.map(p => [p.name, p.default])), ...props };
|
|
14
|
+
definition.validate(configured, invalid);
|
|
15
|
+
return { value: definition.sample(configured, frame, fps, source, {
|
|
16
|
+
read: () => value, integrate: () => [value, 0], end: Infinity,
|
|
17
|
+
}) };
|
|
18
|
+
},
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
function interpolateFrames(frame, at) {
|
|
22
|
+
const i = Math.floor(frame);
|
|
23
|
+
const t = frame - i;
|
|
24
|
+
const a = at(i);
|
|
25
|
+
return t ? (1 - t) * a + t * at(i + 1) : a;
|
|
26
|
+
}
|
|
27
|
+
function springStep(stiffness, damping, mass, dt) {
|
|
28
|
+
const k = stiffness / mass, decay = damping / mass / 2;
|
|
29
|
+
const discriminant = k - decay * decay;
|
|
30
|
+
const rate = Math.sqrt(Math.abs(discriminant));
|
|
31
|
+
const E = Math.exp(-decay * dt);
|
|
32
|
+
let c, s;
|
|
33
|
+
if (discriminant > 0) {
|
|
34
|
+
c = E * Math.cos(rate * dt);
|
|
35
|
+
s = E * Math.sin(rate * dt) / rate;
|
|
36
|
+
}
|
|
37
|
+
else if (discriminant < 0 && rate * dt > 1e-4) {
|
|
38
|
+
const slow = Math.exp((-k / (decay + rate)) * dt);
|
|
39
|
+
const fast = Math.exp(-(decay + rate) * dt);
|
|
40
|
+
c = (slow + fast) / 2;
|
|
41
|
+
s = (slow - fast) / (2 * rate);
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
c = E * Math.cosh(rate * dt);
|
|
45
|
+
s = rate === 0 ? E * dt : E * Math.sinh(rate * dt) / rate;
|
|
46
|
+
}
|
|
47
|
+
return ([position, velocity], target) => {
|
|
48
|
+
const offset = position - target;
|
|
49
|
+
return [target + (c + decay * s) * offset + s * velocity, (c - decay * s) * velocity - k * s * offset];
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
const clampFrame = (frame, end) => Math.max(0, Math.min(end, frame));
|
|
53
|
+
const filterRadius = (props, fps) => Math.floor(Number(props.width) * fps / 2);
|
|
54
|
+
export const channelOperators = [
|
|
55
|
+
operator({
|
|
56
|
+
type: 'ch:limit',
|
|
57
|
+
props: [numberProp('min'), numberProp('max'), stringProp('type', 'clamp'), numberProp('quantize')],
|
|
58
|
+
validate(props, invalid) {
|
|
59
|
+
const { min = -Infinity, max = Infinity, type, quantize } = props;
|
|
60
|
+
if (min > max)
|
|
61
|
+
invalid('Expected min <= max');
|
|
62
|
+
if (type !== 'clamp' && type !== 'loop' && type !== 'zigzag')
|
|
63
|
+
invalid('Expected clamp, loop or zigzag');
|
|
64
|
+
if (type !== 'clamp' && (!Number.isFinite(min) || !Number.isFinite(max) || min >= max)) {
|
|
65
|
+
invalid('Loop and zigzag require finite min < max');
|
|
66
|
+
}
|
|
67
|
+
if (quantize !== undefined && Number(quantize) <= 0)
|
|
68
|
+
invalid('Quantize must be positive');
|
|
69
|
+
},
|
|
70
|
+
sample(props, frame, _fps, source, { read }) {
|
|
71
|
+
const { min = -Infinity, max = Infinity, quantize } = props;
|
|
72
|
+
const width = max - min;
|
|
73
|
+
let value = read(frame);
|
|
74
|
+
if (props.type === 'loop')
|
|
75
|
+
value = min + wrap(value - min, width);
|
|
76
|
+
if (props.type === 'zigzag') {
|
|
77
|
+
const offset = wrap(value - min, 2 * width);
|
|
78
|
+
value = min + Math.min(offset, 2 * width - offset);
|
|
79
|
+
}
|
|
80
|
+
if (quantize !== undefined)
|
|
81
|
+
value = Math.round(Math.max(min, Math.min(max, value)) / quantize) * quantize;
|
|
82
|
+
return Math.max(min, Math.min(max, finite(value, 'Limit value', source)));
|
|
83
|
+
},
|
|
84
|
+
}),
|
|
85
|
+
operator({
|
|
86
|
+
type: 'ch:lag',
|
|
87
|
+
props: [numberProp('lagUp', 0.1), numberProp('lagDown', 0.1)],
|
|
88
|
+
usesHistory: props => props.lagUp !== 0 || props.lagDown !== 0,
|
|
89
|
+
validate(props, invalid) {
|
|
90
|
+
if (Number(props.lagUp) < 0 || Number(props.lagDown) < 0)
|
|
91
|
+
invalid('Lag times must be nonnegative');
|
|
92
|
+
},
|
|
93
|
+
sample(props, frame, fps, _source, { end, integrate, read }) {
|
|
94
|
+
const { lagUp, lagDown } = props;
|
|
95
|
+
if (!lagUp && !lagDown)
|
|
96
|
+
return read(frame);
|
|
97
|
+
const alpha = (tau) => tau > 0 ? -Math.expm1(-1 / fps / tau) : 1;
|
|
98
|
+
const up = alpha(lagUp), down = alpha(lagDown);
|
|
99
|
+
return interpolateFrames(clampFrame(frame, end), i => integrate(i, ([previous], input) => {
|
|
100
|
+
const weight = input > previous ? up : down;
|
|
101
|
+
return [(1 - weight) * previous + weight * input, 0];
|
|
102
|
+
})[0]);
|
|
103
|
+
},
|
|
104
|
+
}),
|
|
105
|
+
operator({
|
|
106
|
+
type: 'ch:spring',
|
|
107
|
+
props: [numberProp('stiffness', 120), numberProp('damping', 12), numberProp('mass', 1)],
|
|
108
|
+
usesHistory: () => true,
|
|
109
|
+
validate(props, invalid) {
|
|
110
|
+
if (Number(props.stiffness) <= 0 || Number(props.mass) <= 0 || Number(props.damping) < 0) {
|
|
111
|
+
invalid('Stiffness and mass must be positive; damping must be nonnegative');
|
|
112
|
+
}
|
|
113
|
+
},
|
|
114
|
+
sample(props, frame, fps, _source, { end, integrate }) {
|
|
115
|
+
const { stiffness, damping, mass } = props;
|
|
116
|
+
const step = springStep(stiffness, damping, mass, 1 / fps);
|
|
117
|
+
return interpolateFrames(clampFrame(frame, end), i => integrate(i, step)[0]);
|
|
118
|
+
},
|
|
119
|
+
}),
|
|
120
|
+
operator({
|
|
121
|
+
type: 'ch:filter',
|
|
122
|
+
props: [numberProp('width', 0.2), stringProp('type', 'gaussian')],
|
|
123
|
+
usesHistory: (props, fps) => filterRadius(props, fps) !== 0,
|
|
124
|
+
validate(props, invalid) {
|
|
125
|
+
if (Number(props.width) < 0 || (props.type !== 'box' && props.type !== 'gaussian')) {
|
|
126
|
+
invalid('Expected a nonnegative width and type box or gaussian');
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
sample(props, frame, fps, source, { end, read }) {
|
|
130
|
+
const radius = filterRadius(props, fps);
|
|
131
|
+
if (radius === 0)
|
|
132
|
+
return read(frame);
|
|
133
|
+
if (!Number.isSafeInteger(radius))
|
|
134
|
+
fail('invalid-channel-operator', 'Filter window is too wide', source);
|
|
135
|
+
return interpolateFrames(frame, i => {
|
|
136
|
+
if (!Number.isSafeInteger(i - radius) || !Number.isSafeInteger(i + radius)) {
|
|
137
|
+
fail('invalid-channel-operator', 'Filter sample frame is out of range', source);
|
|
138
|
+
}
|
|
139
|
+
let average = 0, total = 0;
|
|
140
|
+
for (let offset = -radius; offset <= radius; offset++) {
|
|
141
|
+
const weight = props.type === 'box' ? 1 : Math.exp(-2 * (offset / radius) ** 2);
|
|
142
|
+
const nextTotal = total + weight;
|
|
143
|
+
average = average * (total / nextTotal) + read(clampFrame(i + offset, end)) * (weight / nextTotal);
|
|
144
|
+
total = nextTotal;
|
|
145
|
+
}
|
|
146
|
+
return average;
|
|
147
|
+
});
|
|
148
|
+
},
|
|
149
|
+
}),
|
|
150
|
+
];
|
|
151
|
+
export function createChannelSampler(read, frameCount, source, getHistory = () => []) {
|
|
152
|
+
let states;
|
|
153
|
+
return {
|
|
154
|
+
read, end: frameCount === undefined ? Infinity : frameCount - 1,
|
|
155
|
+
integrate(frame, step) {
|
|
156
|
+
if (!Number.isSafeInteger(frame))
|
|
157
|
+
fail('invalid-frame', 'Operator sample frame is out of range', source);
|
|
158
|
+
states ??= getHistory();
|
|
159
|
+
if (!states.length)
|
|
160
|
+
states.push([read(0), 0]);
|
|
161
|
+
for (let i = states.length; i <= frame; i++) {
|
|
162
|
+
const next = step(states[i - 1], read(i));
|
|
163
|
+
finite(next[0], 'Operator position', source);
|
|
164
|
+
finite(next[1], 'Operator velocity', source);
|
|
165
|
+
states.push(next);
|
|
166
|
+
}
|
|
167
|
+
return states[frame];
|
|
168
|
+
},
|
|
169
|
+
};
|
|
170
|
+
}
|
package/esm/channels.js
CHANGED
|
@@ -2,6 +2,8 @@ import { wrap } from './math.js';
|
|
|
2
2
|
import { readNumber } from './model.js';
|
|
3
3
|
import { fail, finite } from './types.js';
|
|
4
4
|
export const validSegment = (text) => !!text && text !== '.' && text !== '..' && !/[\/\x00-\x1f\x7f]/.test(text);
|
|
5
|
+
export const boundaryMode = (value) => value === 'hold' || value === 'cycle' || value === 'clamp' || value === 'wrap';
|
|
6
|
+
export const cyclic = (mode) => mode === 'wrap' || mode === 'cycle';
|
|
5
7
|
export function loadTable(asset, data, source) {
|
|
6
8
|
if (data == null)
|
|
7
9
|
fail('missing-asset', 'Cannot read channel asset: ' + asset, source);
|
|
@@ -32,8 +34,13 @@ export function loadTable(asset, data, source) {
|
|
|
32
34
|
}
|
|
33
35
|
if (!raw || !Number.isFinite(raw.sampleRate) || raw.sampleRate <= 0)
|
|
34
36
|
invalid('expected a positive sampleRate');
|
|
35
|
-
|
|
36
|
-
|
|
37
|
+
for (const mode of [raw.boundary, raw.extend]) {
|
|
38
|
+
if (mode !== undefined && !boundaryMode(mode))
|
|
39
|
+
invalid('invalid boundary mode');
|
|
40
|
+
}
|
|
41
|
+
if (raw.boundary !== undefined && raw.extend !== undefined && cyclic(raw.boundary) !== cyclic(raw.extend)) {
|
|
42
|
+
invalid('conflicting boundary and extend modes');
|
|
43
|
+
}
|
|
37
44
|
if (raw.interpolation !== undefined && raw.interpolation !== 'step' && raw.interpolation !== 'linear')
|
|
38
45
|
invalid('invalid interpolation');
|
|
39
46
|
if (!raw.channels || typeof raw.channels !== 'object' || Array.isArray(raw.channels))
|
|
@@ -51,7 +58,7 @@ export function loadTable(asset, data, source) {
|
|
|
51
58
|
ports.set(name, { samples, source });
|
|
52
59
|
}
|
|
53
60
|
Object.assign(table, { sampleRate: raw.sampleRate,
|
|
54
|
-
interpolation: raw.interpolation ?? 'step', boundary: raw.boundary ?? 'wrap' });
|
|
61
|
+
interpolation: raw.interpolation ?? 'step', boundary: raw.boundary ?? raw.extend ?? 'wrap' });
|
|
55
62
|
}
|
|
56
63
|
else
|
|
57
64
|
invalid('expected a .chan or .json asset');
|
|
@@ -61,7 +68,7 @@ export function sample(table, port, frame, fps) {
|
|
|
61
68
|
const rows = port.samples;
|
|
62
69
|
const r = finite(table.sampleRate === undefined ? frame : frame * table.sampleRate / fps, 'Row coordinate', port.source);
|
|
63
70
|
const i = Math.floor(r);
|
|
64
|
-
const index = (j) => table.boundary
|
|
71
|
+
const index = (j) => cyclic(table.boundary) ? wrap(j, rows.length) : Math.max(0, Math.min(rows.length - 1, j));
|
|
65
72
|
const value = rows[index(i)];
|
|
66
73
|
return table.interpolation === 'step' ? value
|
|
67
74
|
: finite(value + (rows[index(i + 1)] - value) * (r - i), 'Interpolated sample', port.source);
|