@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/esm/ramp.js ADDED
@@ -0,0 +1,36 @@
1
+ import { fail } from './types.js';
2
+ export function rampStops(value, source) {
3
+ const invalid = () => fail('invalid-ramp', 'Expected distinct ramp stops with finite values and positions in [0, 1]', source);
4
+ if (!Array.isArray(value) || !value.length)
5
+ return invalid();
6
+ const stops = value.map(stop => {
7
+ if (!stop || typeof stop !== 'object' || Array.isArray(stop))
8
+ return invalid();
9
+ const { pos, value, interp = 'linear' } = stop;
10
+ if (!Number.isFinite(pos) || pos < 0 || pos > 1 || !Number.isFinite(value) ||
11
+ (interp !== 'linear' && interp !== 'smooth' && interp !== 'constant'))
12
+ return invalid();
13
+ return { pos, value, interp };
14
+ }).sort((a, b) => a.pos - b.pos);
15
+ if (stops.some((stop, i) => i > 0 && stop.pos === stops[i - 1].pos))
16
+ return invalid();
17
+ return stops;
18
+ }
19
+ export function sampleRamp(stops, u) {
20
+ const x = Math.max(0, Math.min(1, u));
21
+ if (x <= stops[0].pos)
22
+ return stops[0].value;
23
+ for (let i = 1; i < stops.length; i++) {
24
+ const left = stops[i - 1], right = stops[i];
25
+ if (x === right.pos)
26
+ return right.value;
27
+ if (x > right.pos)
28
+ continue;
29
+ if (left.interp === 'constant')
30
+ return left.value;
31
+ const t = (x - left.pos) / (right.pos - left.pos);
32
+ const w = left.interp === 'smooth' ? t * t * (3 - 2 * t) : t;
33
+ return left.value * (1 - w) + right.value * w;
34
+ }
35
+ return stops[stops.length - 1].value;
36
+ }
package/esm/ranges.js ADDED
@@ -0,0 +1,9 @@
1
+ import { fail } from './types.js';
2
+ export function applyRange(ranges, path, value) {
3
+ const range = ranges?.[path];
4
+ if (!range || (value >= range.min && value <= range.max))
5
+ return value;
6
+ if (range.mode === 'error')
7
+ fail('range-violation', `${path} is ${value}, outside [${range.min}, ${range.max}]`, range.source);
8
+ return Math.max(range.min, Math.min(range.max, value));
9
+ }
@@ -0,0 +1,96 @@
1
+ import { channelOperators } from './ch-operators.js';
2
+ import { fail, finite, freeze, } from './types.js';
3
+ const ports = (type, ...names) => names.map(name => ({ name, type }));
4
+ const numeric = (defaults) => Object.entries(defaults)
5
+ .map(([name, value]) => ({ name, type: 'number', default: value }));
6
+ const audioSource = (type) => ({
7
+ type: 'audio:' + type,
8
+ inputs: [],
9
+ outputs: [...ports('object', 'signal'), ...ports('number', 'rms', 'peak')],
10
+ props: type === 'file' ? [{ name: 'asset', type: 'string', required: true }, ...numeric({ gain: 1 })]
11
+ : [{ name: 'device', type: 'string' }, ...numeric({ gain: 1 })],
12
+ evaluate: ({ path, props }, audio) => {
13
+ const gain = Math.abs(props.gain);
14
+ const rms = finite((audio?.rms ?? 0) * gain, path + '/rms');
15
+ const peak = finite((audio?.peak ?? 0) * gain, path + '/peak');
16
+ return { signal: { rms, peak }, rms, peak };
17
+ },
18
+ });
19
+ const audio = [
20
+ audioSource('file'), audioSource('mic'),
21
+ {
22
+ type: 'audio:fft',
23
+ inputs: ports('object', 'signal'),
24
+ outputs: [...ports('number', 'bass', 'mid', 'high', 'centroid', 'flux'), ...ports('object', 'spectrum')],
25
+ props: numeric({ fftSize: 2048, smoothing: 0.8 }),
26
+ evaluate: (_, data) => ({
27
+ bass: data?.bass ?? 0, mid: data?.mid ?? 0, high: data?.high ?? 0, centroid: data?.centroid ?? 0,
28
+ flux: data?.flux ?? 0, spectrum: data?.spectrum ?? [],
29
+ }),
30
+ },
31
+ {
32
+ type: 'audio:envelope',
33
+ inputs: ports('number', 'value'), outputs: ports('number', 'value'),
34
+ props: numeric({ attack: 0.01, release: 0.1 }),
35
+ evaluate: ({ inputs }, data) => ({ value: data?.rms ?? inputs.value ?? 0 }),
36
+ },
37
+ ];
38
+ export const geoTransformDefaults = freeze({ tx: 0, ty: 0, tz: 0, sx: 1, sy: 1, sz: 1 });
39
+ const geo = [
40
+ {
41
+ type: 'geo:box', inputs: [], outputs: ports('object', 'geometry'), props: numeric({ width: 1, height: 1, depth: 1 }),
42
+ evaluate: ({ props }) => ({ geometry: { primitive: 'box', args: [props.width, props.height, props.depth] } }),
43
+ },
44
+ {
45
+ type: 'geo:sphere', inputs: [], outputs: ports('object', 'geometry'), props: numeric({ radius: 1, segments: 32 }),
46
+ evaluate: ({ props }) => ({ geometry: { primitive: 'sphere', args: [props.radius, props.radius, props.segments] } }),
47
+ },
48
+ {
49
+ type: 'geo:transform',
50
+ inputs: [...ports('object', 'geometry'), ...ports('number', ...Object.keys(geoTransformDefaults))],
51
+ outputs: ports('object', 'geometry'), props: [],
52
+ evaluate: ({ inputs }) => ({ geometry: {
53
+ kind: 'transform', geometry: inputs.geometry ?? null,
54
+ translate: [inputs.tx ?? geoTransformDefaults.tx, inputs.ty ?? geoTransformDefaults.ty, inputs.tz ?? geoTransformDefaults.tz],
55
+ scale: [inputs.sx ?? geoTransformDefaults.sx, inputs.sy ?? geoTransformDefaults.sy, inputs.sz ?? geoTransformDefaults.sz],
56
+ } }),
57
+ },
58
+ {
59
+ type: 'geo:merge', inputs: ports('object', 'a', 'b'), outputs: ports('object', 'geometry'), props: [],
60
+ evaluate: ({ inputs }) => ({ geometry: { kind: 'merge', geometries: [inputs.a, inputs.b].filter(value => value !== undefined) } }),
61
+ },
62
+ ];
63
+ export const BUILTIN_CONTEXTS = freeze([
64
+ { name: 'audio', stage: 'audio', nodeTypes: audio },
65
+ { name: 'ch', stage: 'ch', nodeTypes: channelOperators },
66
+ { name: 'geo', stage: 'geo', nodeTypes: geo },
67
+ { name: 'obj', stage: 'obj', nodeTypes: [] },
68
+ { name: 'sim', stage: 'reserved', nodeTypes: [] },
69
+ ]);
70
+ export function createContextRegistry(extensions = []) {
71
+ const contexts = new Map(BUILTIN_CONTEXTS.map(context => [context.name, context]));
72
+ for (const context of extensions) {
73
+ if (typeof context.name !== 'string' || !/^[a-z][a-z0-9_-]*$/.test(context.name) ||
74
+ BUILTIN_CONTEXTS.some(({ name }) => name === context.name)) {
75
+ fail('invalid-extension-context', 'Invalid or reserved extension context: ' + context.name);
76
+ }
77
+ if (contexts.has(context.name))
78
+ fail('duplicate-extension-context', 'Duplicate extension context: ' + context.name);
79
+ if ((context.stage !== 'evaluate' && context.stage !== 'output') || !Array.isArray(context.nodeTypes)) {
80
+ fail('invalid-extension-definition', 'Invalid stage or node types for /' + context.name);
81
+ }
82
+ contexts.set(context.name, Object.freeze({ ...context, nodeTypes: Object.freeze([...context.nodeTypes]) }));
83
+ }
84
+ return Object.freeze({ contexts: Object.freeze([...contexts.values()]), get: (name) => contexts.get(name) });
85
+ }
86
+ export function allowedSource(target, source) {
87
+ switch (target) {
88
+ case 'audio': return source === 'audio';
89
+ case 'ch': return source === 'audio' || source === 'ch';
90
+ case 'geo': return source === 'audio' || source === 'ch' || source === 'geo';
91
+ case 'obj': return source === 'audio' || source === 'ch' || source === 'geo' || source === 'obj';
92
+ case 'evaluate':
93
+ case 'output': return source !== 'output' && source !== 'reserved';
94
+ case 'reserved': return false;
95
+ }
96
+ }
package/evaluate.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { type CompiledScene, type FrameSnapshot, type Result } from './types.js';
2
- export declare function evaluateFrame(scene: CompiledScene, frame: number): Result<FrameSnapshot>;
1
+ import { type CompiledScene, type EvaluateFrameOptions, type FrameSnapshot, type Result } from './types.js';
2
+ export declare function evaluateFrame(scene: CompiledScene, frame: number, options?: EvaluateFrameOptions): Result<FrameSnapshot>;
package/evaluate.js CHANGED
@@ -2,16 +2,21 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.evaluateFrame = evaluateFrame;
4
4
  const channels_js_1 = require("./channels.js");
5
+ const ch_operators_js_1 = require("./ch-operators.js");
6
+ const contexts_js_1 = require("./contexts.js");
7
+ const ranges_js_1 = require("./ranges.js");
8
+ const ramp_js_1 = require("./ramp.js");
5
9
  const expression_js_1 = require("./expression.js");
6
10
  const math_js_1 = require("./math.js");
7
11
  const model_js_1 = require("./model.js");
8
12
  const types_js_1 = require("./types.js");
9
- function evaluateFrame(scene, frame) {
13
+ const channelHistories = new WeakMap();
14
+ function evaluateFrame(scene, frame, options = {}) {
10
15
  try {
11
16
  if (!Number.isSafeInteger(frame) || frame < 0 || (scene.frameCount !== undefined && frame >= scene.frameCount)) {
12
17
  (0, types_js_1.fail)('invalid-frame', 'Frame is outside the scene: ' + frame);
13
18
  }
14
- return { value: evaluate(scene, frame) };
19
+ return { value: evaluate(scene, frame, options) };
15
20
  }
16
21
  catch (error) {
17
22
  if (error instanceof types_js_1.EvaluationError)
@@ -19,10 +24,39 @@ function evaluateFrame(scene, frame) {
19
24
  throw error;
20
25
  }
21
26
  }
22
- function evaluate(scene, frame) {
27
+ function isLiveSample(input) {
28
+ return typeof input === 'object' && input !== null && 'values' in input
29
+ && typeof input.values === 'object' && input.values !== null;
30
+ }
31
+ function readLivePort(options, channel, portName, path, source) {
32
+ const input = options?.liveChannels?.[channel.name] ?? options?.liveChannels?.[(0, model_js_1.channelPath)(channel)];
33
+ if (!input || typeof input !== 'object') {
34
+ (0, types_js_1.fail)('missing-live-channel', 'Missing live channel input for ' + path, source);
35
+ }
36
+ let values;
37
+ if (isLiveSample(input)) {
38
+ if (input.timestamp !== undefined) {
39
+ (0, types_js_1.finite)(input.timestamp, 'Live channel timestamp for ' + (0, model_js_1.channelPath)(channel), source);
40
+ }
41
+ values = input.values;
42
+ }
43
+ else {
44
+ values = input;
45
+ }
46
+ const value = values[portName];
47
+ if (value === undefined)
48
+ (0, types_js_1.fail)('missing-live-channel', 'Missing live channel value for ' + path, source);
49
+ if (typeof value !== 'number')
50
+ (0, types_js_1.fail)('non-finite', path + ' must be finite', source);
51
+ return (0, types_js_1.finite)(value, path, source);
52
+ }
53
+ function evaluate(scene, frame, options) {
23
54
  const plan = model_js_1.plans.get(scene);
24
55
  if (!plan)
25
56
  (0, types_js_1.fail)('invalid-scene', 'Scene was not created by compileScene');
57
+ if (options?.deterministic && scene.liveChannels.length) {
58
+ (0, types_js_1.fail)('non-deterministic-live-channel', 'Deterministic evaluation cannot run a scene with live channels');
59
+ }
26
60
  const { fps, frameCount } = scene;
27
61
  const time = (0, types_js_1.finite)(frame / fps, 'Scene time');
28
62
  const state = new Map(plan.objects.map(object => [object, (0, model_js_1.copyState)(object.authored)]));
@@ -42,30 +76,79 @@ function evaluate(scene, frame) {
42
76
  worlds.set((0, model_js_1.worldStep)(object), object);
43
77
  }
44
78
  const outputs = new Map();
79
+ const operators = new Map();
80
+ let histories;
81
+ if (!scene.liveChannels.length && !options?.liveChannels && !options?.audio) {
82
+ histories = channelHistories.get(scene);
83
+ if (!histories) {
84
+ histories = new Map();
85
+ channelHistories.set(scene, histories);
86
+ }
87
+ }
45
88
  for (const channel of plan.channels) {
46
89
  for (const [name, port] of channel.ports) {
47
- outputs.set((0, model_js_1.channelPath)(channel) + '/' + name, { channel, port, cache: new Map() });
90
+ const path = (0, model_js_1.channelPath)(channel) + '/' + name;
91
+ outputs.set(path, { channel, name, port, cache: new Map() });
92
+ if (channel.operator)
93
+ operators.set(path, (0, ch_operators_js_1.createChannelSampler)(q => (0, ranges_js_1.applyRange)(scene.ranges, (0, model_js_1.channelPath)(channel) + '/input/value', expr(port.expression, q, port.source)), frameCount, port.source, histories && (() => {
94
+ const history = histories.get(path) ?? [];
95
+ histories.set(path, history);
96
+ return history;
97
+ })));
48
98
  }
49
99
  }
100
+ const contexts = (0, contexts_js_1.createContextEvaluation)(plan.extensions, plan.order, frame, time, fps, frameCount, options, read, scene.ranges);
50
101
  const expr = (ast, q, source) => (0, expression_js_1.evaluateExpression)(ast, { frame: q, fps, frameCount, source, read });
51
- function read(path, q) {
102
+ function read(path, q, rampPosition) {
103
+ if (path.startsWith('/audio/'))
104
+ return contexts.read(path, q);
52
105
  if (path.startsWith('/obj/')) {
53
106
  const { object, name } = parameters.get(path);
54
107
  return state.get(object).parameters[name];
55
108
  }
56
- const { channel, port, cache } = outputs.get(path);
109
+ if (plan.audioChannels.has(path)) {
110
+ (0, contexts_js_1.checkAudioFrame)(path, q, frame);
111
+ q = frame;
112
+ }
113
+ const { channel, name, port, cache } = outputs.get(path);
114
+ if (channel.extend)
115
+ q = (0, channels_js_1.cyclic)(channel.extend) ? (0, math_js_1.wrap)(q, frameCount) : Math.max(0, Math.min(frameCount === undefined ? Infinity : frameCount - 1, q));
116
+ if (channel.ramp)
117
+ return (0, ranges_js_1.applyRange)(scene.ranges, path, (0, ramp_js_1.sampleRamp)(channel.ramp, rampPosition ?? 0));
57
118
  const value = cache.get(q);
58
119
  if (value !== undefined)
59
120
  return value;
60
- const result = channel.table ? (0, channels_js_1.sample)(channel.table, port, q, fps) : expr(port.expression, q, port.source);
121
+ let result;
122
+ if (port.live) {
123
+ if (q !== frame)
124
+ (0, types_js_1.fail)('off-time-live-channel', 'Live channel does not support off-time reads: ' + path, port.source);
125
+ result = readLivePort(options, channel, name, path, port.source);
126
+ }
127
+ else if (channel.operator) {
128
+ const { definition, props } = channel.operator;
129
+ const sampler = operators.get(path);
130
+ const sampleOperator = (at) => (0, types_js_1.finite)(definition.sample(props, at, fps, port.source, sampler), path, port.source);
131
+ if (channel.extend && (0, channels_js_1.cyclic)(channel.extend) && !Number.isInteger(q) && definition.usesHistory?.(props, fps)) {
132
+ const left = Math.floor(q), t = q - left;
133
+ result = (0, types_js_1.finite)((1 - t) * sampleOperator(left) + t * sampleOperator((0, math_js_1.wrap)(left + 1, frameCount)), path, port.source);
134
+ }
135
+ else
136
+ result = sampleOperator(q);
137
+ }
138
+ else {
139
+ result = channel.table ? (0, channels_js_1.sample)(channel.table, port, q, fps) : expr(port.expression, q, port.source);
140
+ }
141
+ result = (0, ranges_js_1.applyRange)(scene.ranges, path, result);
61
142
  cache.set(q, result);
62
143
  return result;
63
144
  }
64
145
  const channels = Object.create(null);
146
+ contexts.run('audio');
65
147
  for (const path of plan.order) {
66
148
  if (outputs.has(path))
67
149
  channels[path] = read(path, frame);
68
150
  }
151
+ contexts.run('geo');
69
152
  for (const path of plan.order) {
70
153
  const target = parameters.get(path);
71
154
  if (!target)
@@ -88,7 +171,8 @@ function evaluate(scene, frame) {
88
171
  value = binding.scale * at(frame) + binding.offset;
89
172
  }
90
173
  (0, types_js_1.finite)(value, path, binding?.source ?? object.source);
91
- values[name] = (0, model_js_1.isColor)(name) ? Math.min(1, Math.max(0, value)) : value;
174
+ values[name] = (0, model_js_1.isColor)(name) && !scene.ranges?.[path]
175
+ ? Math.min(1, Math.max(0, value)) : (0, ranges_js_1.applyRange)(scene.ranges, path, value);
92
176
  }
93
177
  const worldPositions = new Map();
94
178
  const localMatrices = new Map();
@@ -132,7 +216,9 @@ function evaluate(scene, frame) {
132
216
  const localPosition = pathBinding
133
217
  ? (0, math_js_1.inverseDirection)(parent, (0, math_js_1.sub)(worldPositions.get(object), (0, math_js_1.column)(parent, 3)), pathBinding.source)
134
218
  : (0, model_js_1.vector)(authored.parameters, model_js_1.translations);
135
- const local = authored.matrix ?? (0, math_js_1.matrix)(localPosition, axes, sizes);
219
+ const local = authored.matrix
220
+ ? [...authored.matrix.slice(0, 12), ...localPosition, 1]
221
+ : (0, math_js_1.matrix)(localPosition, axes, sizes);
136
222
  const world = (0, math_js_1.multiply)(parent, local);
137
223
  for (const component of [...local, ...world])
138
224
  (0, types_js_1.finite)(component, 'Final matrix component', binding?.source ?? object.source);
@@ -147,6 +233,7 @@ function evaluate(scene, frame) {
147
233
  path: (0, model_js_1.objectPath)(object), kind: object.kind, ...(object.parent && { parent: (0, model_js_1.objectPath)(object.parent) }),
148
234
  localMatrix, worldMatrix, parameters: p, visible: authored.visible,
149
235
  ...(object.geometry && { geometry: object.geometry }),
236
+ ...(object.geometrySource && { proceduralGeometry: contexts.read(object.geometrySource, frame) }),
150
237
  ...(Object.hasOwn(p, 'diffr') && { material: {
151
238
  diffuse: [p.diffr, p.diffg, p.diffb, p.diffa], ambient: [p.ambr, p.ambg, p.ambb, p.amba],
152
239
  specular: [p.specr, p.specg, p.specb, p.speca], ...(p.shine !== undefined && { shininess: p.shine }),
@@ -162,6 +249,7 @@ function evaluate(scene, frame) {
162
249
  };
163
250
  return snapshot;
164
251
  });
165
- return (0, types_js_1.freeze)({ frame, time, fps, objects, channels, cameras: objects.filter(o => o.kind === 'camera'),
252
+ const snapshot = (0, types_js_1.freeze)({ frame, time, fps, objects, channels, cameras: objects.filter(o => o.kind === 'camera'),
166
253
  lights: objects.filter(o => o.kind === 'light') });
254
+ return contexts.finish(snapshot);
167
255
  }
package/expression.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type SourceLocation } from './types.js';
2
2
  declare const variables: readonly ["$F", "$T", "$FPS", "$NFRAMES", "$PI", "$TAU", "$E"];
3
3
  export type Variable = typeof variables[number];
4
- export type ReferenceFunction = 'ch' | 'chf' | 'cht';
4
+ export type ReferenceFunction = 'ch' | 'chf' | 'cht' | 'chramp';
5
5
  export type UnaryOperator = '+' | '-';
6
6
  export type BinaryOperator = '+' | '-' | '*' | '/' | '%' | '^';
7
7
  export type Expression = {
@@ -44,6 +44,15 @@ declare const functions: {
44
44
  clamp: [number, number, (x: number, lo: number, hi: number) => number];
45
45
  lerp: [number, number, (a: number, b: number, u: number) => number];
46
46
  fit: [number, number, (x: number, a: number, b: number, c: number, d: number) => number];
47
+ fit01: [number, number, (x: number, c: number, d: number) => number];
48
+ fit10: [number, number, (x: number, c: number, d: number) => number];
49
+ fit11: [number, number, (x: number, c: number, d: number) => number];
50
+ efit: [number, number, (x: number, a: number, b: number, c: number, d: number) => number];
51
+ rand: [number, number, (seed: number) => number];
52
+ sign: [number, number, (x: number) => number];
53
+ deg: [number, number, (x: number) => number];
54
+ rad: [number, number, (x: number) => number];
55
+ modulo: [number, number, (a: number, b: number) => number];
47
56
  smoothstep: [number, number, (a: number, b: number, x: number) => number];
48
57
  pow: [number, number, (x: number, y: number) => number];
49
58
  sqrt: [number, number, (x: number) => number];
@@ -59,7 +68,7 @@ interface ExpressionContext {
59
68
  fps: number;
60
69
  frameCount?: number;
61
70
  source: SourceLocation;
62
- read: (path: string, frame: number) => number;
71
+ read: (path: string, frame: number, rampPosition?: number) => number;
63
72
  }
64
73
  export declare function evaluateExpression(ast: Expression, context: ExpressionContext): number;
65
74
  export {};
package/expression.js CHANGED
@@ -8,18 +8,25 @@ const variables = ['$F', '$T', '$FPS', '$NFRAMES', '$PI', '$TAU', '$E'];
8
8
  const lerp = (a, b, u) => a + (b - a) * u;
9
9
  const unit = (u) => Math.max(0, Math.min(1, u));
10
10
  const smooth = (u) => u * u * (3 - 2 * u);
11
+ function boundedLerp(a, b, u) {
12
+ if (u <= 0)
13
+ return a;
14
+ if (u >= 1)
15
+ return b;
16
+ return Math.max(Math.min(a, b), Math.min(Math.max(a, b), lerp(a, b, u)));
17
+ }
11
18
  function noise(x, seed = 0) {
12
19
  const i = Math.floor(x);
13
20
  if (![i, i + 1, seed].every(Number.isSafeInteger))
14
21
  return NaN;
15
- const hash = (j) => {
16
- let n = j ^ seed;
17
- n = Math.imul(n ^ (n >>> 16), 0x7feb352d);
18
- n = Math.imul(n ^ (n >>> 15), 0x846ca68b);
19
- return 2 * ((n ^ (n >>> 16)) >>> 0) / 4294967295 - 1;
20
- };
22
+ const hash = (j) => 2 * mix32(j ^ seed) / 4294967295 - 1;
21
23
  return lerp(hash(i), hash(i + 1), smooth(x - i));
22
24
  }
25
+ function mix32(n) {
26
+ n = Math.imul(n ^ (n >>> 16), 0x7feb352d);
27
+ n = Math.imul(n ^ (n >>> 15), 0x846ca68b);
28
+ return (n ^ (n >>> 16)) >>> 0;
29
+ }
23
30
  const functions = {
24
31
  sin: [1, 1, Math.sin], cos: [1, 1, Math.cos], tan: [1, 1, Math.tan],
25
32
  atan2: [2, 2, (y, x) => x === 0 && y === 0 ? NaN : Math.atan2(y, x)],
@@ -27,7 +34,24 @@ const functions = {
27
34
  round: [1, 1, Math.round], min: [1, Infinity, Math.min], max: [1, Infinity, Math.max],
28
35
  clamp: [3, 3, (x, lo, hi) => lo <= hi ? Math.max(lo, Math.min(hi, x)) : NaN],
29
36
  lerp: [3, 3, lerp],
30
- fit: [5, 5, (x, a, b, c, d) => a < b ? lerp(c, d, unit((x - a) / (b - a))) : NaN],
37
+ fit: [5, 5, (x, a, b, c, d) => {
38
+ if (a >= b)
39
+ return NaN;
40
+ if (x <= a)
41
+ return c;
42
+ if (x >= b)
43
+ return d;
44
+ return boundedLerp(c, d, (x - a) / (b - a));
45
+ }],
46
+ fit01: [3, 3, (x, c, d) => boundedLerp(c, d, x)],
47
+ fit10: [3, 3, (x, c, d) => boundedLerp(d, c, x)],
48
+ fit11: [3, 3, (x, c, d) => boundedLerp(c, d, (x + 1) / 2)],
49
+ efit: [5, 5, (x, a, b, c, d) => a !== b ? lerp(c, d, (x - a) / (b - a)) : NaN],
50
+ rand: [1, 1, seed => mix32(seed) / 4294967296],
51
+ sign: [1, 1, x => x === 0 ? 0 : Math.sign(x)],
52
+ deg: [1, 1, x => x * (180 / Math.PI)],
53
+ rad: [1, 1, x => x * (Math.PI / 180)],
54
+ modulo: [2, 2, (a, b) => a - b * Math.floor(a / b)],
31
55
  smoothstep: [3, 3, (a, b, x) => a < b ? smooth(unit((x - a) / (b - a))) : NaN],
32
56
  pow: [2, 2, Math.pow], sqrt: [1, 1, Math.sqrt], exp: [1, 1, Math.exp],
33
57
  log: [1, 1, Math.log], noise: [1, 2, noise],
@@ -69,7 +93,7 @@ function parseExpression(text, source) {
69
93
  return { kind: 'number', value: (0, types_js_1.finite)(Number(word), 'Number literal', source) };
70
94
  if (variables.includes(word))
71
95
  return { kind: 'variable', name: word };
72
- if (word === 'ch' || word === 'chf' || word === 'cht') {
96
+ if (word === 'ch' || word === 'chf' || word === 'cht' || word === 'chramp') {
73
97
  expect('(');
74
98
  const path = current;
75
99
  if (!/^['"]/.test(path))
@@ -146,6 +170,8 @@ function evaluateExpression(ast, context) {
146
170
  break;
147
171
  case 'reference': {
148
172
  const time = node.time ? visit(node.time) : frame;
173
+ if (node.name === 'chramp')
174
+ return read(node.path, frame, time);
149
175
  return read(node.path, (0, types_js_1.finite)(node.name === 'cht' ? time * fps : time, 'Sample frame', source));
150
176
  }
151
177
  case 'unary': return node.op === '-' ? -visit(node.operand) : visit(node.operand);
package/graph.d.ts CHANGED
@@ -3,7 +3,10 @@ export declare function comparePaths(a: string, b: string): number;
3
3
  export declare class GraphBuilder {
4
4
  private steps;
5
5
  add(path: string, type: string, portType: GraphPort['type'], props: GraphNode['props'], source?: SourceLocation): void;
6
+ addNode(path: string, node: Omit<GraphNode, 'name'>, source?: SourceLocation): void;
6
7
  depend(to: string, on: string): void;
8
+ wire(to: string, input: string, from: string, output: string): void;
9
+ expose(path: string, port: GraphPort): void;
7
10
  finish(): {
8
11
  order: string[];
9
12
  graph: EvaluationGraph;
package/graph.js CHANGED
@@ -19,12 +19,25 @@ class GraphBuilder {
19
19
  steps = new Map();
20
20
  add(path, type, portType, props, source) {
21
21
  const context = path.startsWith('/ch/') ? 'ch' : 'obj';
22
- this.steps.set(path, { node: { name: graphName(path), context, type, props, inputs: [],
23
- outputs: [{ name: 'value', type: portType }] }, dependencies: new Set(), source });
22
+ this.addNode(path, { context, type, props, inputs: [], outputs: [{ name: 'value', type: portType }] }, source);
23
+ }
24
+ addNode(path, node, source) {
25
+ this.steps.set(path, { node: { ...node, name: graphName(path) }, dependencies: new Set(), wires: [], source });
24
26
  }
25
27
  depend(to, on) {
26
28
  this.steps.get(to).dependencies.add(on);
27
29
  }
30
+ wire(to, input, from, output) {
31
+ const step = this.steps.get(to);
32
+ step.dependencies.add(from);
33
+ step.wires.push({ path: from, output, input });
34
+ }
35
+ expose(path, port) {
36
+ const step = this.steps.get(path);
37
+ if (!step.node.outputs.some(output => output.name === port.name)) {
38
+ step.node = { ...step.node, outputs: [...step.node.outputs, port] };
39
+ }
40
+ }
28
41
  finish() {
29
42
  const paths = [...this.steps.keys()].sort(comparePaths);
30
43
  const counts = new Map();
@@ -73,14 +86,23 @@ class GraphBuilder {
73
86
  }
74
87
  const edges = [];
75
88
  const nodes = paths.map(path => {
76
- const { node, dependencies } = this.steps.get(path);
77
- const inputs = [...dependencies].sort(comparePaths).map(dep => {
89
+ const { node, dependencies, wires } = this.steps.get(path);
90
+ 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 }) => {
91
+ const source = this.steps.get(from).node;
92
+ edges.push({ src: { node: source.name, port: output }, dst: { node: node.name, port: input } });
93
+ return { name: input, type: source.outputs.find(port => port.name === output).type };
94
+ });
95
+ if (node.context !== 'obj' && node.context !== 'ch') {
96
+ return node;
97
+ }
98
+ const wired = new Set(wires.map(wire => wire.path));
99
+ const inputs = [...dependencies].filter(dep => !wired.has(dep)).sort(comparePaths).map(dep => {
78
100
  const source = this.steps.get(dep).node;
79
101
  const output = source.outputs[0];
80
102
  edges.push({ src: { node: source.name, port: output.name }, dst: { node: node.name, port: source.name } });
81
103
  return { name: source.name, type: output.type };
82
104
  });
83
- return { ...node, inputs };
105
+ return { ...node, inputs: [...new Map([...node.inputs, ...inputs, ...typedInputs].map(port => [port.name, port])).values()] };
84
106
  });
85
107
  return { order, graph: { name: 'scene', nodes, edges } };
86
108
  }
package/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export declare 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';
5
+ export type { ContextDefinition, ContextRegistry, ContextStage } from './registry.js';
4
6
  export type { BinaryOperator, Expression, MathFunction, ReferenceFunction, UnaryOperator, Variable } from './expression.js';
5
- export type { CameraSnapshot, ChannelSnapshot, CompiledScene, CompileOptions, Diagnostic, EvaluationGraph, FrameSnapshot, GeometrySnapshot, GraphEdge, GraphEndpoint, GraphNode, GraphPort, GraphProp, LightKind, LightSnapshot, MaterialSnapshot, Matrix4, ObjectKind, ObjectSnapshot, Result, SceneSource, SourceLocation, Vec3, } from './types.js';
7
+ export type { AudioFrameData, CameraSnapshot, ChannelSnapshot, CompiledScene, CompileOptions, ContextNodeSnapshot, ContextValue, ContextValues, Diagnostic, EvaluateFrameOptions, EvaluateOptions, EvaluationGraph, ExtensionContextDefinition, ExtensionContextStage, ExtensionNodeEvalContext, ExtensionNodeType, ExtensionPropDefinition, FrameSnapshot, GeometrySnapshot, GraphEdge, GraphEndpoint, GraphNode, GraphPort, GraphPortType, GraphProp, LightKind, LightSnapshot, LiveChannelInput, LiveChannelSample, MaterialSnapshot, Matrix4, ObjectKind, ObjectSnapshot, ParameterRange, Result, SceneSource, SourceLocation, Vec3, } from './types.js';
package/index.js CHANGED
@@ -1,8 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.evaluateFrame = exports.compileScene = exports.name = void 0;
3
+ exports.createContextRegistry = exports.BUILTIN_CONTEXTS = exports.evaluateFrame = exports.compileScene = exports.name = void 0;
4
4
  exports.name = '@vim3d/core';
5
5
  var compile_js_1 = require("./compile.js");
6
6
  Object.defineProperty(exports, "compileScene", { enumerable: true, get: function () { return compile_js_1.compileScene; } });
7
7
  var evaluate_js_1 = require("./evaluate.js");
8
8
  Object.defineProperty(exports, "evaluateFrame", { enumerable: true, get: function () { return evaluate_js_1.evaluateFrame; } });
9
+ var registry_js_1 = require("./registry.js");
10
+ Object.defineProperty(exports, "BUILTIN_CONTEXTS", { enumerable: true, get: function () { return registry_js_1.BUILTIN_CONTEXTS; } });
11
+ Object.defineProperty(exports, "createContextRegistry", { enumerable: true, get: function () { return registry_js_1.createContextRegistry; } });
package/model.d.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import type { Expression } from './expression.js';
2
+ import type { Extensions } from './contexts.js';
3
+ import type { ChannelOperatorDefinition } from './ch-operators.js';
4
+ import type { RampStop } from './ramp.js';
2
5
  import { type CompiledScene, type GeometrySnapshot, type LightKind, type Matrix4, type ObjectKind, type SourceLocation, type Vec3 } from './types.js';
3
6
  export interface Authored {
4
7
  parameters: Record<string, number>;
@@ -16,6 +19,7 @@ export interface SceneObject {
16
19
  source: SourceLocation;
17
20
  parent?: SceneObject;
18
21
  geometry?: GeometrySnapshot;
22
+ geometrySource?: string;
19
23
  authored: Authored;
20
24
  pathBindings: PathBinding[];
21
25
  aimBindings: AimBinding[];
@@ -24,18 +28,26 @@ export interface Table {
24
28
  asset: string;
25
29
  sampleRate?: number;
26
30
  interpolation: 'step' | 'linear';
27
- boundary: 'wrap' | 'clamp';
31
+ boundary: 'wrap' | 'clamp' | 'cycle' | 'hold';
28
32
  }
29
33
  export interface Channel {
30
34
  id: number;
31
35
  name: string;
32
36
  source: SourceLocation;
33
37
  table?: Table;
38
+ extend?: Table['boundary'];
39
+ ramp?: readonly RampStop[];
40
+ operator?: {
41
+ definition: ChannelOperatorDefinition;
42
+ props: Record<string, string | number>;
43
+ };
44
+ live?: boolean;
34
45
  ports: Map<string, ChannelPort>;
35
46
  }
36
47
  export interface ChannelPort {
37
48
  samples?: number[];
38
49
  expression?: Expression;
50
+ live?: boolean;
39
51
  source: SourceLocation;
40
52
  }
41
53
  export interface ActiveRange {
@@ -75,6 +87,8 @@ export interface Event {
75
87
  edit: PropertyEdit;
76
88
  }
77
89
  export interface Plan {
90
+ extensions: Extensions;
91
+ audioChannels: ReadonlySet<string>;
78
92
  objects: SceneObject[];
79
93
  channels: Channel[];
80
94
  drivers: Map<string, Driver[]>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vim3d/core",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "A shared scene model for Vim3D.",
5
5
  "author": "Dan Lynch <pyramation@gmail.com>",
6
6
  "homepage": "https://github.com/pyramation/vim3d/tree/master/js/packages/core",
@@ -21,7 +21,7 @@
21
21
  "url": "https://github.com/pyramation/vim3d/issues"
22
22
  },
23
23
  "dependencies": {
24
- "@vim3d/parser": "^0.2.0"
24
+ "@vim3d/parser": "^0.2.2"
25
25
  },
26
26
  "devDependencies": {
27
27
  "makage": "^0.8.0"
package/ramp.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { type SourceLocation } from './types.js';
2
+ export interface RampStop {
3
+ readonly pos: number;
4
+ readonly value: number;
5
+ readonly interp: 'linear' | 'smooth' | 'constant';
6
+ }
7
+ export declare function rampStops(value: unknown, source: SourceLocation): RampStop[];
8
+ export declare function sampleRamp(stops: readonly RampStop[], u: number): number;