@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.
@@ -0,0 +1,323 @@
1
+ import { validSegment } from './channels.js';
2
+ import { comparePaths } from './graph.js';
3
+ import { evaluateExpression } from './expression.js';
4
+ import { allowedSource, geoTransformDefaults } from './registry.js';
5
+ import { applyRange } from './ranges.js';
6
+ import { EvaluationError, fail, freeze, } from './types.js';
7
+ const nodeType = /^[a-zA-Z][a-zA-Z0-9_-]*:[a-zA-Z][a-zA-Z0-9_-]*$/;
8
+ const propTypes = new Set(['string', 'number', 'boolean', 'object']);
9
+ const portTypes = new Set([...propTypes, 'vector3', 'matrix4']);
10
+ export function jsonProp(text, invalid) {
11
+ const raw = text?.trimEnd().match(/^[ \t:]*(?:set|"set")[ \t]+(?:"[^"]*"|[^ \t]+)[ \t]+(.*)$/)?.[1];
12
+ const literal = raw?.match(/^(?:"(?:\\.|[^"\\])*"|[^"#])*/)?.[0];
13
+ try {
14
+ return JSON.parse(literal);
15
+ }
16
+ catch {
17
+ return invalid();
18
+ }
19
+ }
20
+ function isRecord(value) {
21
+ return value !== null && typeof value === 'object' &&
22
+ (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
23
+ }
24
+ function matches(value, type) {
25
+ if (type === 'object')
26
+ return isRecord(value) || Array.isArray(value);
27
+ if (type === 'number')
28
+ return typeof value === 'number' && Number.isFinite(value);
29
+ if (type === 'vector3' || type === 'matrix4') {
30
+ return Array.isArray(value) && value.length === (type === 'vector3' ? 3 : 16) &&
31
+ Array.from(value).every(item => typeof item === 'number' && Number.isFinite(item));
32
+ }
33
+ return typeof value === type;
34
+ }
35
+ function copyValue(value, invalid, seen = new Set()) {
36
+ if (value === null)
37
+ return null;
38
+ if (typeof value === 'string' || typeof value === 'boolean' ||
39
+ (typeof value === 'number' && Number.isFinite(value)))
40
+ return value;
41
+ if ((!Array.isArray(value) && !isRecord(value)) || seen.has(value))
42
+ return invalid();
43
+ seen.add(value);
44
+ const copy = Array.isArray(value) ? Array.from(value, item => copyValue(item, invalid, seen))
45
+ : Object.fromEntries(Object.entries(value).map(([key, item]) => [key, copyValue(item, invalid, seen)]));
46
+ seen.delete(value);
47
+ return freeze(copy);
48
+ }
49
+ function definitions(entries, types, kind, owner) {
50
+ if (!Array.isArray(entries))
51
+ fail('invalid-extension-definition', 'Expected ' + kind + ' definitions for ' + owner);
52
+ const map = new Map();
53
+ for (const entry of entries) {
54
+ if (!entry || typeof entry.name !== 'string' || !validSegment(entry.name) || !types.has(entry.type) || map.has(entry.name)) {
55
+ fail('invalid-extension-definition', 'Invalid or duplicate ' + kind + ' on ' + owner + ': ' + entry?.name);
56
+ }
57
+ map.set(entry.name, { ...entry });
58
+ }
59
+ return map;
60
+ }
61
+ export class Extensions {
62
+ registry;
63
+ types = new Map();
64
+ nodes = new Map();
65
+ constructor(registry) {
66
+ this.registry = registry;
67
+ for (const context of registry.contexts) {
68
+ const { name, stage, nodeTypes } = context;
69
+ if (stage === 'obj' || stage === 'ch' || stage === 'reserved')
70
+ continue;
71
+ const types = new Map();
72
+ for (const definition of nodeTypes) {
73
+ const { type, evaluate } = definition;
74
+ if (!nodeType.test(type) || typeof evaluate !== 'function')
75
+ fail('invalid-extension-definition', 'Invalid node type: ' + type);
76
+ if (types.has(type))
77
+ fail('duplicate-extension-type', 'Duplicate node type in /' + name + ': ' + type);
78
+ const owner = '/' + name + ' ' + type;
79
+ const inputs = definitions(definition.inputs, portTypes, 'input', owner);
80
+ const outputs = definitions(definition.outputs, portTypes, 'output', owner);
81
+ const props = definitions(definition.props, propTypes, 'prop', owner);
82
+ for (const [key, prop] of props) {
83
+ const invalid = () => fail('invalid-extension-definition', 'Invalid prop definition on ' + owner + ': ' + key);
84
+ if (prop.required !== undefined && typeof prop.required !== 'boolean')
85
+ invalid();
86
+ if (prop.default !== undefined) {
87
+ if (!matches(prop.default, prop.type))
88
+ invalid();
89
+ props.set(key, { ...prop, default: copyValue(prop.default, invalid) });
90
+ }
91
+ }
92
+ types.set(type, { type, inputs, outputs, props, evaluate });
93
+ }
94
+ this.types.set(name, types);
95
+ }
96
+ }
97
+ add(path, type, source) {
98
+ const [root, context, name, ...extra] = path.split('/');
99
+ if (root || !context || !validSegment(name) || extra.length)
100
+ fail('invalid-path', 'Expected an extension node path: ' + path, source);
101
+ const registered = this.registry.get(context);
102
+ if (!registered)
103
+ fail('unknown-extension-context', 'Unknown extension context: /' + context, source);
104
+ const definition = this.types.get(context)?.get(type);
105
+ if (!definition)
106
+ fail('unknown-extension-type', 'Unknown node type in /' + context + ': ' + type, source);
107
+ if (this.nodes.has(path))
108
+ fail('duplicate-name', 'Name is already used: ' + path, source);
109
+ const props = new Map();
110
+ for (const [key, def] of definition.props)
111
+ if (def.default !== undefined)
112
+ props.set(key, def.default);
113
+ const node = { path, context, stage: registered.stage, definition, source, props, drivers: new Map() };
114
+ this.nodes.set(path, node);
115
+ return node;
116
+ }
117
+ property(address, args, text, source) {
118
+ const { node, key } = this.member(address, source);
119
+ const def = node.definition.props.get(key);
120
+ if (!def)
121
+ fail('unknown-extension-prop', 'Unknown prop: ' + address, source);
122
+ const invalid = () => fail('invalid-extension-prop', 'Expected ' + def.type + ' for ' + address, source);
123
+ let value = args[0];
124
+ if (def.type === 'object') {
125
+ value = jsonProp(text, invalid);
126
+ }
127
+ else {
128
+ if (args.length !== 1)
129
+ fail('invalid-operands', 'Expected one value for ' + address, source);
130
+ if (def.type === 'number')
131
+ value = args[0].trim() === '' ? NaN : Number(args[0]);
132
+ if (def.type === 'boolean')
133
+ value = args[0] === 'true' ? true : args[0] === 'false' ? false : undefined;
134
+ }
135
+ if (!matches(value, def.type))
136
+ invalid();
137
+ node.props.set(key, copyValue(value, invalid));
138
+ }
139
+ input(address, type, driver, source) {
140
+ const { node, key } = this.member(address, source);
141
+ const port = node.definition.inputs.get(key);
142
+ if (!port)
143
+ fail('unknown-extension-port', 'Unknown input port: ' + address, source);
144
+ if (port.type !== type)
145
+ fail('extension-port-type', 'Expected ' + port.type + ' at ' + address + ', got ' + type, source);
146
+ for (const from of driver.kind === 'wire' ? [driver.from] : driver.references) {
147
+ if (!allowedSource(node.stage, from.stage))
148
+ fail('extension-stage', address + ' cannot read ' + from.address, source);
149
+ }
150
+ if (node.drivers.has(key))
151
+ fail('overlapping-drivers', 'Input already has a driver: ' + address, source);
152
+ node.drivers.set(key, driver);
153
+ }
154
+ output(address, source) {
155
+ const { node, key } = this.member(address, source);
156
+ if (node.stage === 'output')
157
+ fail('extension-stage', 'Cannot read an output-stage node: ' + node.path, source);
158
+ const port = node.definition.outputs.get(key);
159
+ if (!port)
160
+ fail('unknown-extension-port', 'Unknown output port: ' + address, source);
161
+ return { address, path: node.path, port: key, type: port.type, stage: node.stage };
162
+ }
163
+ numericPort(address, source) {
164
+ const { node, key } = this.member(address, source);
165
+ if (node.definition.inputs.get(key)?.type !== 'number' && node.definition.outputs.get(key)?.type !== 'number') {
166
+ fail('extension-port-type', 'Expected a numeric port at ' + address, source);
167
+ }
168
+ return address;
169
+ }
170
+ member(address, source) {
171
+ const [root, context, name, key, ...extra] = address.split('/');
172
+ if (root || !context || !name || !key || extra.length)
173
+ fail('invalid-path', 'Expected an extension member path: ' + address, source);
174
+ if (!this.registry.get(context))
175
+ fail('unknown-extension-context', 'Unknown extension context: /' + context, source);
176
+ const path = '/' + context + '/' + name;
177
+ const node = this.nodes.get(path);
178
+ if (!node)
179
+ fail('missing-target', 'Unknown extension node: ' + path, source);
180
+ return { node, key };
181
+ }
182
+ addToGraph(graph) {
183
+ for (const node of this.nodes.values()) {
184
+ const { definition, path, context, source } = node;
185
+ for (const [name, prop] of definition.props) {
186
+ if (prop.required && !node.props.has(name))
187
+ fail('missing-extension-prop', 'Missing required prop: ' + path + '/' + name, source);
188
+ }
189
+ const props = [...node.props.keys()].sort(comparePaths).map(name => ({
190
+ name, type: definition.props.get(name).type, value: node.props.get(name),
191
+ }));
192
+ for (const input of [...node.drivers.keys()].sort(comparePaths)) {
193
+ const driver = node.drivers.get(input);
194
+ if (driver.kind === 'expr') {
195
+ props.push({ name: 'expr/' + input, type: 'object', value: driver.expression });
196
+ }
197
+ }
198
+ graph.addNode(path, { context, type: definition.type, props,
199
+ inputs: [...definition.inputs.values()], outputs: [...definition.outputs.values()] }, source);
200
+ }
201
+ for (const { path, drivers } of this.nodes.values()) {
202
+ for (const [input, driver] of drivers) {
203
+ for (const from of driver.kind === 'wire' ? [driver.from] : driver.references) {
204
+ graph.expose(from.path, { name: from.port, type: from.type });
205
+ graph.wire(path, input, from.path, from.port);
206
+ }
207
+ }
208
+ }
209
+ }
210
+ }
211
+ export function checkAudioFrame(path, sampleFrame, frame) {
212
+ if (Math.abs(sampleFrame - frame) > 1e-9) {
213
+ fail('off-time-audio-reference', 'Audio features are available only at the evaluated frame: ' + path);
214
+ }
215
+ }
216
+ export function createContextEvaluation(extensions, order, frame, time, fps, frameCount, options, readBuiltIn, ranges) {
217
+ const used = new Set([...extensions.nodes.values()].map(node => node.context));
218
+ const contextNames = extensions.registry.contexts.filter(({ stage, name }) => stage === 'evaluate' || stage === 'output' || used.has(name)).map(({ name }) => name).sort(comparePaths);
219
+ let base;
220
+ let objects = new Map();
221
+ const values = new Map();
222
+ const snapshots = new Map();
223
+ const sorted = [...extensions.nodes.keys()].sort(comparePaths);
224
+ const read = (path, sampleFrame, rampPosition) => {
225
+ if (path.startsWith('/ch/'))
226
+ return readBuiltIn(path, sampleFrame, rampPosition);
227
+ if (path.startsWith('/obj/')) {
228
+ const end = path.lastIndexOf('/');
229
+ const object = objects.get(path.slice(0, end));
230
+ const key = path.slice(end + 1);
231
+ if (key === 'snapshot')
232
+ return copyValue(object, () => fail('invalid-extension-input', 'Invalid object snapshot: ' + path));
233
+ if (key === 'worldMatrix' || key === 'localMatrix')
234
+ return object[key];
235
+ return object.parameters[key];
236
+ }
237
+ if (path.startsWith('/audio/'))
238
+ checkAudioFrame(path, sampleFrame, frame);
239
+ return values.get(path);
240
+ };
241
+ const snapshot = () => {
242
+ if (!contextNames.length)
243
+ return base;
244
+ const contexts = Object.fromEntries(contextNames.map(name => [name, []]));
245
+ for (const path of sorted) {
246
+ const node = snapshots.get(path);
247
+ if (node)
248
+ contexts[node.context].push(node);
249
+ }
250
+ return freeze({ ...base, contexts });
251
+ };
252
+ function run(stage) {
253
+ const inputSnapshot = stage === 'output' ? snapshot() : undefined;
254
+ for (const path of order) {
255
+ const node = extensions.nodes.get(path);
256
+ if (!node || node.stage !== stage)
257
+ continue;
258
+ const { definition, source, context } = node;
259
+ const inputs = Object.fromEntries([...node.drivers].map(([key, driver]) => {
260
+ const value = driver.kind === 'wire' ? read(driver.from.address, frame) : evaluateExpression(driver.expression, {
261
+ frame, fps, frameCount, source: driver.source, read: (address, sampleFrame, u) => read(address, sampleFrame, u),
262
+ });
263
+ return [key, typeof value === 'number' ? applyRange(ranges, path + '/' + key, value) : value];
264
+ }));
265
+ if (ranges && stage === 'geo' && definition.type === 'geo:transform') {
266
+ for (const [key, fallback] of Object.entries(geoTransformDefaults)) {
267
+ const address = path + '/' + key;
268
+ if (ranges[address] && !Object.hasOwn(inputs, key))
269
+ inputs[key] = applyRange(ranges, address, fallback);
270
+ }
271
+ }
272
+ const props = freeze(Object.fromEntries(node.props));
273
+ const evaluate = definition.evaluate;
274
+ const audio = options.audio;
275
+ const name = path.slice('/audio/'.length);
276
+ const data = stage === 'audio' && audio
277
+ ? Object.hasOwn(audio, path) ? audio[path] : Object.hasOwn(audio, name) ? audio[name] : undefined
278
+ : undefined;
279
+ const ctx = freeze({ path, frame, time, fps, inputs, props, ...(inputSnapshot && { snapshot: inputSnapshot }) });
280
+ let result;
281
+ try {
282
+ result = stage === 'audio' ? evaluate(ctx, data) : evaluate(ctx);
283
+ }
284
+ catch (error) {
285
+ if (error instanceof EvaluationError || (stage !== 'evaluate' && stage !== 'output'))
286
+ throw error;
287
+ const message = error instanceof Error ? error.message : String(error);
288
+ fail('plugin-error', `${path}: ${message}`, source);
289
+ }
290
+ const returned = result === undefined ? {} : result;
291
+ if (!isRecord(returned))
292
+ fail('invalid-extension-output', 'Expected an output record from ' + path, source);
293
+ for (const name of Object.keys(returned)) {
294
+ if (!definition.outputs.has(name))
295
+ fail('invalid-extension-output', 'Undeclared output: ' + path + '/' + name, source);
296
+ }
297
+ const outputs = Object.fromEntries([...definition.outputs].map(([name, { type }]) => {
298
+ const address = path + '/' + name;
299
+ const value = Object.hasOwn(returned, name) ? returned[name] : undefined;
300
+ const invalid = () => fail('invalid-extension-output', 'Expected ' + type + ' output at ' + address, source);
301
+ if (type === 'number' && typeof value === 'number' && !Number.isFinite(value)) {
302
+ fail('non-finite', address + ' must be finite', source);
303
+ }
304
+ if (!matches(value, type))
305
+ invalid();
306
+ const output = typeof value === 'number' ? applyRange(ranges, address, value) : copyValue(value, invalid);
307
+ values.set(address, output);
308
+ return [name, output];
309
+ }));
310
+ snapshots.set(path, freeze({ path, context, type: definition.type, stage, props, inputs, outputs }));
311
+ }
312
+ }
313
+ return {
314
+ run, read,
315
+ finish(snapshotBase) {
316
+ base = snapshotBase;
317
+ objects = new Map(base.objects.map(object => [object.path, object]));
318
+ run('evaluate');
319
+ run('output');
320
+ return snapshot();
321
+ },
322
+ };
323
+ }
package/esm/evaluate.js CHANGED
@@ -1,14 +1,19 @@
1
- import { sample } from './channels.js';
1
+ import { cyclic, sample } from './channels.js';
2
+ import { createChannelSampler } from './ch-operators.js';
3
+ import { checkAudioFrame, createContextEvaluation } from './contexts.js';
4
+ import { applyRange } from './ranges.js';
5
+ import { sampleRamp } from './ramp.js';
2
6
  import { evaluateExpression } from './expression.js';
3
7
  import { add, aim, column, euler, identity, inverseDirection, matrix, multiply, normalize, point, scale, sub, worldUp, wrap } from './math.js';
4
8
  import { active, channelPath, copyState, isColor, objectPath, plans, positionStep, rotations, scales, translations, vector, worldStep } from './model.js';
5
9
  import { EvaluationError, fail, finite, freeze } from './types.js';
6
- export function evaluateFrame(scene, frame) {
10
+ const channelHistories = new WeakMap();
11
+ export function evaluateFrame(scene, frame, options = {}) {
7
12
  try {
8
13
  if (!Number.isSafeInteger(frame) || frame < 0 || (scene.frameCount !== undefined && frame >= scene.frameCount)) {
9
14
  fail('invalid-frame', 'Frame is outside the scene: ' + frame);
10
15
  }
11
- return { value: evaluate(scene, frame) };
16
+ return { value: evaluate(scene, frame, options) };
12
17
  }
13
18
  catch (error) {
14
19
  if (error instanceof EvaluationError)
@@ -16,10 +21,39 @@ export function evaluateFrame(scene, frame) {
16
21
  throw error;
17
22
  }
18
23
  }
19
- function evaluate(scene, frame) {
24
+ function isLiveSample(input) {
25
+ return typeof input === 'object' && input !== null && 'values' in input
26
+ && typeof input.values === 'object' && input.values !== null;
27
+ }
28
+ function readLivePort(options, channel, portName, path, source) {
29
+ const input = options?.liveChannels?.[channel.name] ?? options?.liveChannels?.[channelPath(channel)];
30
+ if (!input || typeof input !== 'object') {
31
+ fail('missing-live-channel', 'Missing live channel input for ' + path, source);
32
+ }
33
+ let values;
34
+ if (isLiveSample(input)) {
35
+ if (input.timestamp !== undefined) {
36
+ finite(input.timestamp, 'Live channel timestamp for ' + channelPath(channel), source);
37
+ }
38
+ values = input.values;
39
+ }
40
+ else {
41
+ values = input;
42
+ }
43
+ const value = values[portName];
44
+ if (value === undefined)
45
+ fail('missing-live-channel', 'Missing live channel value for ' + path, source);
46
+ if (typeof value !== 'number')
47
+ fail('non-finite', path + ' must be finite', source);
48
+ return finite(value, path, source);
49
+ }
50
+ function evaluate(scene, frame, options) {
20
51
  const plan = plans.get(scene);
21
52
  if (!plan)
22
53
  fail('invalid-scene', 'Scene was not created by compileScene');
54
+ if (options?.deterministic && scene.liveChannels.length) {
55
+ fail('non-deterministic-live-channel', 'Deterministic evaluation cannot run a scene with live channels');
56
+ }
23
57
  const { fps, frameCount } = scene;
24
58
  const time = finite(frame / fps, 'Scene time');
25
59
  const state = new Map(plan.objects.map(object => [object, copyState(object.authored)]));
@@ -39,30 +73,79 @@ function evaluate(scene, frame) {
39
73
  worlds.set(worldStep(object), object);
40
74
  }
41
75
  const outputs = new Map();
76
+ const operators = new Map();
77
+ let histories;
78
+ if (!scene.liveChannels.length && !options?.liveChannels && !options?.audio) {
79
+ histories = channelHistories.get(scene);
80
+ if (!histories) {
81
+ histories = new Map();
82
+ channelHistories.set(scene, histories);
83
+ }
84
+ }
42
85
  for (const channel of plan.channels) {
43
86
  for (const [name, port] of channel.ports) {
44
- outputs.set(channelPath(channel) + '/' + name, { channel, port, cache: new Map() });
87
+ const path = channelPath(channel) + '/' + name;
88
+ outputs.set(path, { channel, name, port, cache: new Map() });
89
+ if (channel.operator)
90
+ operators.set(path, createChannelSampler(q => applyRange(scene.ranges, channelPath(channel) + '/input/value', expr(port.expression, q, port.source)), frameCount, port.source, histories && (() => {
91
+ const history = histories.get(path) ?? [];
92
+ histories.set(path, history);
93
+ return history;
94
+ })));
45
95
  }
46
96
  }
97
+ const contexts = createContextEvaluation(plan.extensions, plan.order, frame, time, fps, frameCount, options, read, scene.ranges);
47
98
  const expr = (ast, q, source) => evaluateExpression(ast, { frame: q, fps, frameCount, source, read });
48
- function read(path, q) {
99
+ function read(path, q, rampPosition) {
100
+ if (path.startsWith('/audio/'))
101
+ return contexts.read(path, q);
49
102
  if (path.startsWith('/obj/')) {
50
103
  const { object, name } = parameters.get(path);
51
104
  return state.get(object).parameters[name];
52
105
  }
53
- const { channel, port, cache } = outputs.get(path);
106
+ if (plan.audioChannels.has(path)) {
107
+ checkAudioFrame(path, q, frame);
108
+ q = frame;
109
+ }
110
+ const { channel, name, port, cache } = outputs.get(path);
111
+ if (channel.extend)
112
+ q = cyclic(channel.extend) ? wrap(q, frameCount) : Math.max(0, Math.min(frameCount === undefined ? Infinity : frameCount - 1, q));
113
+ if (channel.ramp)
114
+ return applyRange(scene.ranges, path, sampleRamp(channel.ramp, rampPosition ?? 0));
54
115
  const value = cache.get(q);
55
116
  if (value !== undefined)
56
117
  return value;
57
- const result = channel.table ? sample(channel.table, port, q, fps) : expr(port.expression, q, port.source);
118
+ let result;
119
+ if (port.live) {
120
+ if (q !== frame)
121
+ fail('off-time-live-channel', 'Live channel does not support off-time reads: ' + path, port.source);
122
+ result = readLivePort(options, channel, name, path, port.source);
123
+ }
124
+ else if (channel.operator) {
125
+ const { definition, props } = channel.operator;
126
+ const sampler = operators.get(path);
127
+ const sampleOperator = (at) => finite(definition.sample(props, at, fps, port.source, sampler), path, port.source);
128
+ if (channel.extend && cyclic(channel.extend) && !Number.isInteger(q) && definition.usesHistory?.(props, fps)) {
129
+ const left = Math.floor(q), t = q - left;
130
+ result = finite((1 - t) * sampleOperator(left) + t * sampleOperator(wrap(left + 1, frameCount)), path, port.source);
131
+ }
132
+ else
133
+ result = sampleOperator(q);
134
+ }
135
+ else {
136
+ result = channel.table ? sample(channel.table, port, q, fps) : expr(port.expression, q, port.source);
137
+ }
138
+ result = applyRange(scene.ranges, path, result);
58
139
  cache.set(q, result);
59
140
  return result;
60
141
  }
61
142
  const channels = Object.create(null);
143
+ contexts.run('audio');
62
144
  for (const path of plan.order) {
63
145
  if (outputs.has(path))
64
146
  channels[path] = read(path, frame);
65
147
  }
148
+ contexts.run('geo');
66
149
  for (const path of plan.order) {
67
150
  const target = parameters.get(path);
68
151
  if (!target)
@@ -85,7 +168,8 @@ function evaluate(scene, frame) {
85
168
  value = binding.scale * at(frame) + binding.offset;
86
169
  }
87
170
  finite(value, path, binding?.source ?? object.source);
88
- values[name] = isColor(name) ? Math.min(1, Math.max(0, value)) : value;
171
+ values[name] = isColor(name) && !scene.ranges?.[path]
172
+ ? Math.min(1, Math.max(0, value)) : applyRange(scene.ranges, path, value);
89
173
  }
90
174
  const worldPositions = new Map();
91
175
  const localMatrices = new Map();
@@ -129,7 +213,9 @@ function evaluate(scene, frame) {
129
213
  const localPosition = pathBinding
130
214
  ? inverseDirection(parent, sub(worldPositions.get(object), column(parent, 3)), pathBinding.source)
131
215
  : vector(authored.parameters, translations);
132
- const local = authored.matrix ?? matrix(localPosition, axes, sizes);
216
+ const local = authored.matrix
217
+ ? [...authored.matrix.slice(0, 12), ...localPosition, 1]
218
+ : matrix(localPosition, axes, sizes);
133
219
  const world = multiply(parent, local);
134
220
  for (const component of [...local, ...world])
135
221
  finite(component, 'Final matrix component', binding?.source ?? object.source);
@@ -144,6 +230,7 @@ function evaluate(scene, frame) {
144
230
  path: objectPath(object), kind: object.kind, ...(object.parent && { parent: objectPath(object.parent) }),
145
231
  localMatrix, worldMatrix, parameters: p, visible: authored.visible,
146
232
  ...(object.geometry && { geometry: object.geometry }),
233
+ ...(object.geometrySource && { proceduralGeometry: contexts.read(object.geometrySource, frame) }),
147
234
  ...(Object.hasOwn(p, 'diffr') && { material: {
148
235
  diffuse: [p.diffr, p.diffg, p.diffb, p.diffa], ambient: [p.ambr, p.ambg, p.ambb, p.amba],
149
236
  specular: [p.specr, p.specg, p.specb, p.speca], ...(p.shine !== undefined && { shininess: p.shine }),
@@ -159,6 +246,7 @@ function evaluate(scene, frame) {
159
246
  };
160
247
  return snapshot;
161
248
  });
162
- return freeze({ frame, time, fps, objects, channels, cameras: objects.filter(o => o.kind === 'camera'),
249
+ const snapshot = freeze({ frame, time, fps, objects, channels, cameras: objects.filter(o => o.kind === 'camera'),
163
250
  lights: objects.filter(o => o.kind === 'light') });
251
+ return contexts.finish(snapshot);
164
252
  }
package/esm/expression.js CHANGED
@@ -3,18 +3,25 @@ const variables = ['$F', '$T', '$FPS', '$NFRAMES', '$PI', '$TAU', '$E'];
3
3
  const lerp = (a, b, u) => a + (b - a) * u;
4
4
  const unit = (u) => Math.max(0, Math.min(1, u));
5
5
  const smooth = (u) => u * u * (3 - 2 * u);
6
+ function boundedLerp(a, b, u) {
7
+ if (u <= 0)
8
+ return a;
9
+ if (u >= 1)
10
+ return b;
11
+ return Math.max(Math.min(a, b), Math.min(Math.max(a, b), lerp(a, b, u)));
12
+ }
6
13
  function noise(x, seed = 0) {
7
14
  const i = Math.floor(x);
8
15
  if (![i, i + 1, seed].every(Number.isSafeInteger))
9
16
  return NaN;
10
- const hash = (j) => {
11
- let n = j ^ seed;
12
- n = Math.imul(n ^ (n >>> 16), 0x7feb352d);
13
- n = Math.imul(n ^ (n >>> 15), 0x846ca68b);
14
- return 2 * ((n ^ (n >>> 16)) >>> 0) / 4294967295 - 1;
15
- };
17
+ const hash = (j) => 2 * mix32(j ^ seed) / 4294967295 - 1;
16
18
  return lerp(hash(i), hash(i + 1), smooth(x - i));
17
19
  }
20
+ function mix32(n) {
21
+ n = Math.imul(n ^ (n >>> 16), 0x7feb352d);
22
+ n = Math.imul(n ^ (n >>> 15), 0x846ca68b);
23
+ return (n ^ (n >>> 16)) >>> 0;
24
+ }
18
25
  const functions = {
19
26
  sin: [1, 1, Math.sin], cos: [1, 1, Math.cos], tan: [1, 1, Math.tan],
20
27
  atan2: [2, 2, (y, x) => x === 0 && y === 0 ? NaN : Math.atan2(y, x)],
@@ -22,7 +29,24 @@ const functions = {
22
29
  round: [1, 1, Math.round], min: [1, Infinity, Math.min], max: [1, Infinity, Math.max],
23
30
  clamp: [3, 3, (x, lo, hi) => lo <= hi ? Math.max(lo, Math.min(hi, x)) : NaN],
24
31
  lerp: [3, 3, lerp],
25
- fit: [5, 5, (x, a, b, c, d) => a < b ? lerp(c, d, unit((x - a) / (b - a))) : NaN],
32
+ fit: [5, 5, (x, a, b, c, d) => {
33
+ if (a >= b)
34
+ return NaN;
35
+ if (x <= a)
36
+ return c;
37
+ if (x >= b)
38
+ return d;
39
+ return boundedLerp(c, d, (x - a) / (b - a));
40
+ }],
41
+ fit01: [3, 3, (x, c, d) => boundedLerp(c, d, x)],
42
+ fit10: [3, 3, (x, c, d) => boundedLerp(d, c, x)],
43
+ fit11: [3, 3, (x, c, d) => boundedLerp(c, d, (x + 1) / 2)],
44
+ efit: [5, 5, (x, a, b, c, d) => a !== b ? lerp(c, d, (x - a) / (b - a)) : NaN],
45
+ rand: [1, 1, seed => mix32(seed) / 4294967296],
46
+ sign: [1, 1, x => x === 0 ? 0 : Math.sign(x)],
47
+ deg: [1, 1, x => x * (180 / Math.PI)],
48
+ rad: [1, 1, x => x * (Math.PI / 180)],
49
+ modulo: [2, 2, (a, b) => a - b * Math.floor(a / b)],
26
50
  smoothstep: [3, 3, (a, b, x) => a < b ? smooth(unit((x - a) / (b - a))) : NaN],
27
51
  pow: [2, 2, Math.pow], sqrt: [1, 1, Math.sqrt], exp: [1, 1, Math.exp],
28
52
  log: [1, 1, Math.log], noise: [1, 2, noise],
@@ -64,7 +88,7 @@ export function parseExpression(text, source) {
64
88
  return { kind: 'number', value: finite(Number(word), 'Number literal', source) };
65
89
  if (variables.includes(word))
66
90
  return { kind: 'variable', name: word };
67
- if (word === 'ch' || word === 'chf' || word === 'cht') {
91
+ if (word === 'ch' || word === 'chf' || word === 'cht' || word === 'chramp') {
68
92
  expect('(');
69
93
  const path = current;
70
94
  if (!/^['"]/.test(path))
@@ -141,6 +165,8 @@ export function evaluateExpression(ast, context) {
141
165
  break;
142
166
  case 'reference': {
143
167
  const time = node.time ? visit(node.time) : frame;
168
+ if (node.name === 'chramp')
169
+ return read(node.path, frame, time);
144
170
  return read(node.path, finite(node.name === 'cht' ? time * fps : time, 'Sample frame', source));
145
171
  }
146
172
  case 'unary': return node.op === '-' ? -visit(node.operand) : visit(node.operand);
package/esm/graph.js CHANGED
@@ -15,12 +15,25 @@ export class GraphBuilder {
15
15
  steps = new Map();
16
16
  add(path, type, portType, props, source) {
17
17
  const context = path.startsWith('/ch/') ? 'ch' : 'obj';
18
- this.steps.set(path, { node: { name: graphName(path), context, type, props, inputs: [],
19
- outputs: [{ name: 'value', type: portType }] }, dependencies: new Set(), source });
18
+ this.addNode(path, { context, type, props, inputs: [], outputs: [{ name: 'value', type: portType }] }, source);
19
+ }
20
+ addNode(path, node, source) {
21
+ this.steps.set(path, { node: { ...node, name: graphName(path) }, dependencies: new Set(), wires: [], source });
20
22
  }
21
23
  depend(to, on) {
22
24
  this.steps.get(to).dependencies.add(on);
23
25
  }
26
+ wire(to, input, from, output) {
27
+ const step = this.steps.get(to);
28
+ step.dependencies.add(from);
29
+ step.wires.push({ path: from, output, input });
30
+ }
31
+ expose(path, port) {
32
+ const step = this.steps.get(path);
33
+ if (!step.node.outputs.some(output => output.name === port.name)) {
34
+ step.node = { ...step.node, outputs: [...step.node.outputs, port] };
35
+ }
36
+ }
24
37
  finish() {
25
38
  const paths = [...this.steps.keys()].sort(comparePaths);
26
39
  const counts = new Map();
@@ -69,14 +82,23 @@ export class GraphBuilder {
69
82
  }
70
83
  const edges = [];
71
84
  const nodes = paths.map(path => {
72
- const { node, dependencies } = this.steps.get(path);
73
- const inputs = [...dependencies].sort(comparePaths).map(dep => {
85
+ const { node, dependencies, wires } = this.steps.get(path);
86
+ const typedInputs = wires.sort((a, b) => comparePaths(a.input, b.input) || comparePaths(a.path, b.path) || comparePaths(a.output, b.output)).map(({ path: from, output, input }) => {
87
+ const source = this.steps.get(from).node;
88
+ edges.push({ src: { node: source.name, port: output }, dst: { node: node.name, port: input } });
89
+ return { name: input, type: source.outputs.find(port => port.name === output).type };
90
+ });
91
+ if (node.context !== 'obj' && node.context !== 'ch') {
92
+ return node;
93
+ }
94
+ const wired = new Set(wires.map(wire => wire.path));
95
+ const inputs = [...dependencies].filter(dep => !wired.has(dep)).sort(comparePaths).map(dep => {
74
96
  const source = this.steps.get(dep).node;
75
97
  const output = source.outputs[0];
76
98
  edges.push({ src: { node: source.name, port: output.name }, dst: { node: node.name, port: source.name } });
77
99
  return { name: source.name, type: output.type };
78
100
  });
79
- return { ...node, inputs };
101
+ return { ...node, inputs: [...new Map([...node.inputs, ...inputs, ...typedInputs].map(port => [port.name, port])).values()] };
80
102
  });
81
103
  return { order, graph: { name: 'scene', nodes, edges } };
82
104
  }
package/esm/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export const name = '@vim3d/core';
2
2
  export { compileScene } from './compile.js';
3
3
  export { evaluateFrame } from './evaluate.js';
4
+ export { BUILTIN_CONTEXTS, createContextRegistry } from './registry.js';