@vim3d/core 0.2.0 → 0.2.1

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/compile.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import { expand } from '@vim3d/parser';
2
2
  import { loadTable, validSegment } from './channels.js';
3
+ import { Extensions } from './contexts.js';
3
4
  import { bindExpression, parseExpression } from './expression.js';
4
5
  import { comparePaths, GraphBuilder } from './graph.js';
6
+ import { allowedSource, createContextRegistry } from './registry.js';
5
7
  import { channelPath, checkArity, copyState, defaults, editCommands, objectPath, plans, positionStep, propertyEdit, readFrame, readNumber, rotations, scales, translations, worldStep } from './model.js';
6
8
  import { EvaluationError, fail, freeze } from './types.js';
7
9
  const aliases = {
@@ -10,8 +12,11 @@ const aliases = {
10
12
  };
11
13
  const primitives = new Set(['cube', 'grid', 'sphere', 'ellipse', 'ellipseFace', 'circle', 'circleFace', 'ring']);
12
14
  const prefixes = { geo: 'geo', curve: 'curve', null: 'null', camera: 'cam', light: 'light', channel: 'ch' };
13
- const deferred = new Set(['parent', 'expr', 'register', 'ref', 'path', 'lookat', 'children']);
15
+ const deferred = new Set(['parent', 'expr', 'register', 'ref', 'path', 'lookat', 'children', 'connect', 'set']);
14
16
  const isChannel = (node) => 'ports' in node;
17
+ const isObject = (node) => 'authored' in node;
18
+ const isExtension = (node) => 'definition' in node;
19
+ const isBuiltInPath = (path) => /^\/(?:obj|ch)\//.test(path);
15
20
  const commandOf = (text) => Object.hasOwn(aliases, text) ? aliases[text] : text;
16
21
  const location = ({ file, line }) => ({ file, line });
17
22
  const prop = (name, value) => ({ name, type: typeof value, value });
@@ -72,6 +77,7 @@ export function compileScene(source, options = {}) {
72
77
  },
73
78
  expandDirectives: true,
74
79
  reservedCommands: ['expr', 'parent'],
80
+ preserveText: true,
75
81
  });
76
82
  if (expanded.problems.length)
77
83
  return { diagnostics: expanded.problems.map(problem => ({
@@ -86,6 +92,8 @@ export function compileScene(source, options = {}) {
86
92
  }
87
93
  }
88
94
  function compile(lines, root, fps, options) {
95
+ const registry = createContextRegistry(options.contexts);
96
+ const extensions = new Extensions(registry);
89
97
  const objects = [];
90
98
  const channels = [];
91
99
  const objNames = new Map();
@@ -96,6 +104,26 @@ function compile(lines, root, fps, options) {
96
104
  const pending = [];
97
105
  const timed = [];
98
106
  let nextId = 0;
107
+ for (const [name, portNames] of Object.entries(options.liveChannels ?? {})) {
108
+ if (!validSegment(name))
109
+ fail('invalid-live-channel', 'Invalid live channel name: ' + name, root);
110
+ if (!Array.isArray(portNames) || !portNames.length) {
111
+ fail('invalid-live-channel', 'Live channel must declare at least one port: ' + name, root);
112
+ }
113
+ const ports = new Map();
114
+ for (const portName of portNames) {
115
+ if (typeof portName !== 'string' || !validSegment(portName)) {
116
+ fail('invalid-live-channel', 'Invalid live channel port name: ' + String(portName), root);
117
+ }
118
+ if (ports.has(portName)) {
119
+ fail('invalid-live-channel', 'Duplicate live channel port: /ch/' + name + '/' + portName, root);
120
+ }
121
+ ports.set(portName, { live: true, source: root });
122
+ }
123
+ const channel = { id: nextId++, name, source: root, live: true, ports };
124
+ channels.push(channel);
125
+ chNames.set(name, channel);
126
+ }
99
127
  function nextName(type, names) {
100
128
  let n = counters.get(type) ?? 0;
101
129
  let name;
@@ -149,6 +177,30 @@ function compile(lines, root, fps, options) {
149
177
  fail('invalid-path', 'Expected an object parameter path: ' + path, source);
150
178
  return scalar(getObject(name, source), param, source);
151
179
  };
180
+ const extensionAddress = (path, source) => {
181
+ if (!path?.startsWith('/'))
182
+ fail('invalid-path', 'Expected an absolute path: ' + path, source);
183
+ return normalizePath(path, '/', source);
184
+ };
185
+ const extensionSource = (address, source) => {
186
+ if (address.startsWith('/ch/')) {
187
+ const path = channelOutput(address, source);
188
+ return { address: path, path, type: 'number', port: 'value', stage: 'ch' };
189
+ }
190
+ if (address.startsWith('/obj/')) {
191
+ const [, , name, member, ...extra] = address.split('/');
192
+ if (!member || extra.length)
193
+ fail('invalid-path', 'Expected an object output path: ' + address, source);
194
+ const object = getObject(name, source);
195
+ if (member === 'worldMatrix' || member === 'localMatrix' || member === 'snapshot') {
196
+ return { address, path: worldStep(object), port: member === 'worldMatrix' ? 'value' : member,
197
+ type: member === 'snapshot' ? 'object' : 'matrix4', stage: 'obj' };
198
+ }
199
+ const path = scalar(object, member, source);
200
+ return { address: path, path, type: 'number', port: 'value', stage: 'obj' };
201
+ }
202
+ return extensions.output(address, source);
203
+ };
152
204
  let current = addObject('camera', root, 'Cam0');
153
205
  let viewCamera;
154
206
  let backgroundColor;
@@ -168,6 +220,10 @@ function compile(lines, root, fps, options) {
168
220
  else if (curve && command !== 'end') {
169
221
  fail('invalid-curve', 'Expected a curve vertex or end', source);
170
222
  }
223
+ else if (command === 'node') {
224
+ checkArity(command, args, [2], source);
225
+ current = extensions.add(extensionAddress(args[0], source), args[1], source);
226
+ }
171
227
  else if (command === 'begin') {
172
228
  checkArity(command, args, [0, 1], source);
173
229
  if (args.length && args[0] !== 'draw')
@@ -211,13 +267,16 @@ function compile(lines, root, fps, options) {
211
267
  }
212
268
  else if (command === 'select') {
213
269
  checkArity(command, args, [1], source);
214
- current = lookup(args[0], 'either', source);
270
+ const address = args[0].startsWith('/') && !isBuiltInPath(args[0]) ? extensionAddress(args[0], source) : args[0];
271
+ current = extensions.nodes.get(address) ?? lookup(args[0], 'either', source);
215
272
  }
216
273
  else if (command === 'name') {
217
274
  checkArity(command, args, [1], source);
218
275
  const [name] = args;
219
276
  if (!validSegment(name))
220
277
  fail('invalid-name', 'Invalid name: ' + name, source);
278
+ if (isExtension(current))
279
+ fail('invalid-subject', 'name requires an object or channel', source);
221
280
  if (isChannel(current))
222
281
  rename(chNames, current, name, source);
223
282
  else
@@ -262,10 +321,10 @@ function compile(lines, root, fps, options) {
262
321
  timed.push({ frame, source, command: eventCommand, args: values, objectCount: nextId });
263
322
  }
264
323
  else if (deferred.has(command)) {
265
- pending.push({ command, args, source, current });
324
+ pending.push({ command, args, source, current, text: line.text });
266
325
  }
267
326
  else if (editCommands.has(command)) {
268
- if (isChannel(current))
327
+ if (!isObject(current))
269
328
  fail('invalid-subject', command + ' requires an object', source);
270
329
  propertyEdit(command, args, current, source)(current.authored);
271
330
  }
@@ -288,6 +347,8 @@ function compile(lines, root, fps, options) {
288
347
  expressionPorts.set(channelPath(channel) + '/' + name, { node: channel, name, port });
289
348
  }
290
349
  const inputs = new Map();
350
+ const offTimeRefs = [];
351
+ const contextWires = [];
291
352
  const depend = (path, on) => {
292
353
  if (!inputs.has(path))
293
354
  inputs.set(path, new Set());
@@ -295,6 +356,22 @@ function compile(lines, root, fps, options) {
295
356
  };
296
357
  const bind = (text, path, source) => bindExpression(parseExpression(text, source), (ref, name) => {
297
358
  const address = normalizePath(ref, path.slice(0, path.lastIndexOf('/')), source);
359
+ const targetStage = path.startsWith('/ch/') ? 'ch' : 'obj';
360
+ if (!isBuiltInPath(address) && registry.get(address.split('/')[1])) {
361
+ const from = extensionSource(address, source);
362
+ if (!allowedSource(targetStage, from.stage)) {
363
+ fail('extension-stage', 'Built-in nodes cannot read ' + address, source);
364
+ }
365
+ if (from.stage !== 'audio' || name !== 'ch') {
366
+ fail('off-time-extension-reference', 'Only ch() can read built-in audio scalars: ' + address, source);
367
+ }
368
+ if (from.type !== 'number')
369
+ fail('extension-port-type', 'Expected a number at ' + from.address, source);
370
+ if (!contextWires.some(wire => wire.to === path && wire.from.address === from.address)) {
371
+ contextWires.push({ to: path, input: from.address, from });
372
+ }
373
+ return from.address;
374
+ }
298
375
  if (address.startsWith('/obj/')) {
299
376
  if (path.startsWith('/ch/'))
300
377
  fail('channel-object-reference', 'Channel expressions cannot read object parameters: ' + address, source);
@@ -302,30 +379,92 @@ function compile(lines, root, fps, options) {
302
379
  fail('off-time-object-reference', name + ' requires a channel: ' + address, source);
303
380
  }
304
381
  const input = address.startsWith('/ch/') ? channelOutput(address, source) : objectScalar(address, source);
382
+ if (name !== 'ch' && input.startsWith('/ch/'))
383
+ offTimeRefs.push({ path: input, source });
305
384
  depend(path, input);
306
385
  return input;
307
386
  });
308
- for (const { command, args, source, current } of pending) {
387
+ const driveScalar = (path, expression, source) => {
388
+ if (path.startsWith('/ch/')) {
389
+ const { port } = expressionPorts.get(path);
390
+ if (port.samples || port.expression || port.live)
391
+ fail('overlapping-drivers', 'Channel already has a driver: ' + path, source);
392
+ port.expression = expression;
393
+ port.source = source;
394
+ }
395
+ else
396
+ addDriver(path, { kind: 'expr', expression, ...range([], 0, source) });
397
+ };
398
+ for (const { command, args, source, current, text: lineText } of pending) {
309
399
  if (command === 'parent')
310
400
  continue;
311
401
  const numberAt = (i, fallback) => args[i] === undefined ? fallback : readNumber(args[i], source);
312
- if (command === 'expr') {
402
+ if (command === 'set') {
403
+ const [target] = args;
404
+ if (!target)
405
+ fail('invalid-operands', 'Expected set KEY VALUE', source);
406
+ if (!target.startsWith('/') && !isExtension(current))
407
+ fail('invalid-subject', 'set requires an extension node', source);
408
+ const address = target.startsWith('/') ? extensionAddress(target, source)
409
+ : current.path + '/' + target;
410
+ extensions.property(address, args.slice(1), lineText, source);
411
+ }
412
+ else if (command === 'connect') {
413
+ checkArity(command, args, [2], source);
414
+ const to = extensionAddress(args[1], source);
415
+ const from = extensionSource(extensionAddress(args[0], source), source);
416
+ if (isBuiltInPath(to)) {
417
+ if (from.stage === 'audio') {
418
+ if (from.type !== 'number')
419
+ fail('extension-port-type', 'Expected an audio scalar at ' + from.address, source);
420
+ const path = to.startsWith('/ch/') ? channelOutput(to, source) : objectScalar(to, source);
421
+ driveScalar(path, { kind: 'reference', name: 'ch', path: from.address }, source);
422
+ contextWires.push({ to: path, input: from.address, from });
423
+ continue;
424
+ }
425
+ const [, context, name, input, extra] = to.split('/');
426
+ if (context !== 'obj' || input !== 'geometry' || extra !== undefined || from.stage !== 'geo') {
427
+ fail('extension-stage', 'connect cannot drive this built-in input: ' + to, source);
428
+ }
429
+ const object = getObject(name, source);
430
+ if (object.kind !== 'geo')
431
+ fail('invalid-subject', 'A geometry connection requires a geometry object', source);
432
+ if (from.type !== 'object')
433
+ fail('extension-port-type', 'Expected object geometry at ' + to, source);
434
+ if (object.geometry || object.geometrySource)
435
+ fail('overlapping-drivers', 'Geometry already assigned: ' + to, source);
436
+ object.geometrySource = from.address;
437
+ contextWires.push({ to: worldStep(object), input, from });
438
+ }
439
+ else
440
+ extensions.input(to, from.type, { kind: 'wire', from }, source);
441
+ }
442
+ else if (command === 'expr') {
313
443
  checkArity(command, args, [2], source);
314
444
  const [target, text] = args;
315
445
  if (!target.startsWith('/'))
316
446
  fail('invalid-path', 'Expression targets must be absolute', source);
317
447
  const address = normalizePath(target, '/', source);
318
- const path = address.startsWith('/ch/') ? channelOutput(address, source) : objectScalar(address, source);
319
- const expression = bind(text, path, source);
320
- if (path.startsWith('/ch/')) {
321
- const { port } = expressionPorts.get(path);
322
- if (port.samples || port.expression)
323
- fail('overlapping-drivers', 'Channel already has a driver: ' + path, source);
324
- port.expression = expression;
325
- port.source = source;
448
+ if (!isBuiltInPath(address) && (registry.get(address.split('/')[1]) || options.contexts?.length)) {
449
+ const references = new Map();
450
+ const owner = address.slice(0, address.lastIndexOf('/'));
451
+ const expression = bindExpression(parseExpression(text, source), (ref, name) => {
452
+ const from = extensionSource(normalizePath(ref, owner, source), source);
453
+ if (name !== 'ch' && !from.address.startsWith('/ch/')) {
454
+ fail('off-time-extension-reference', name + ' requires a channel: ' + from.address, source);
455
+ }
456
+ if (from.type !== 'number')
457
+ fail('extension-port-type', 'Expected a number at ' + from.address, source);
458
+ if (name !== 'ch' && from.address.startsWith('/ch/'))
459
+ offTimeRefs.push({ path: from.address, source });
460
+ references.set(from.address, from);
461
+ return from.address;
462
+ });
463
+ extensions.input(address, 'number', { kind: 'expr', expression, references: [...references.values()], source }, source);
464
+ continue;
326
465
  }
327
- else
328
- addDriver(path, { kind: 'expr', expression, ...range([], 0, source) });
466
+ const path = address.startsWith('/ch/') ? channelOutput(address, source) : objectScalar(address, source);
467
+ driveScalar(path, bind(text, path, source), source);
329
468
  }
330
469
  else if (command === 'register' || command === 'ref') {
331
470
  const register = command === 'register';
@@ -341,6 +480,9 @@ function compile(lines, root, fps, options) {
341
480
  const common = { input, scale: numberAt(end + 1, 1), offset: numberAt(end + 2, 0), ...range(args, end + 4, source) };
342
481
  const freq = numberAt(end, 1);
343
482
  const shift = numberAt(end + 3, 0);
483
+ if (register && (freq !== 1 || shift !== 0 || args[1] === 'rx' || args[1] === 'ry' || args[1] === 'rz')) {
484
+ offTimeRefs.push({ path: input, source });
485
+ }
344
486
  addDriver(path, register ? { kind: 'register', freq, shift, ...common } : { kind: 'ref', ...common });
345
487
  depend(path, input);
346
488
  }
@@ -358,7 +500,7 @@ function compile(lines, root, fps, options) {
358
500
  else {
359
501
  checkArity(command, args, [2, 4], source);
360
502
  const target = getObject(args[1], source);
361
- if (command === 'children' && (args[0] !== 'lookat' || isChannel(current))) {
503
+ if (command === 'children' && (args[0] !== 'lookat' || !isObject(current))) {
362
504
  fail('invalid-subject', 'Expected children lookat TARGET with an object current', source);
363
505
  }
364
506
  const activeRange = range(args, 2, source);
@@ -392,7 +534,7 @@ function compile(lines, root, fps, options) {
392
534
  const command = commandOf(event.command);
393
535
  if (!editCommands.has(command))
394
536
  fail('forbidden-event-command', 'at cannot execute ' + event.command, source);
395
- if (isChannel(selected) || selected.id >= objectCount)
537
+ if (!isObject(selected) || selected.id >= objectCount)
396
538
  fail('event-missing-target', 'No current object is available at the event source', source);
397
539
  const edit = propertyEdit(command, args, selected, source);
398
540
  edit(state.get(selected));
@@ -421,10 +563,13 @@ function compile(lines, root, fps, options) {
421
563
  }
422
564
  }
423
565
  for (const [path, { node, name, port }] of expressionPorts) {
424
- if (!port.samples && !port.expression)
566
+ if (!port.samples && !port.expression && !port.live)
425
567
  fail('missing-channel-driver', 'Missing driver for ' + path, port.source);
426
- graph.add(path, node.table ? 'source:table' : 'source:expression', 'number', [prop('target', path), prop('port', name), ...(node.table ? [prop('asset', node.table.asset),
427
- prop('sampling', node.table)] : [prop('ast', port.expression)])], port.source);
568
+ const nodeType = node.table ? 'source:table' : port.live ? 'source:live' : 'source:expression';
569
+ const nodeProps = node.table
570
+ ? [prop('asset', node.table.asset), prop('sampling', node.table)]
571
+ : port.live ? [] : [prop('ast', port.expression)];
572
+ graph.add(path, nodeType, 'number', [prop('target', path), prop('port', name), ...nodeProps], port.source);
428
573
  }
429
574
  for (const object of objects) {
430
575
  const path = objectPath(object);
@@ -460,9 +605,36 @@ function compile(lines, root, fps, options) {
460
605
  for (const [path, dependencies] of inputs)
461
606
  for (const input of dependencies)
462
607
  graph.depend(path, input);
608
+ extensions.addToGraph(graph);
609
+ for (const { to, input, from } of contextWires)
610
+ graph.wire(to, input, from.path, from.port);
463
611
  const finished = graph.finish();
464
- const scene = freeze({ fps, ...(options.frameCount !== undefined && { frameCount: options.frameCount }),
612
+ const livePorts = new Set();
613
+ for (const path of finished.order) {
614
+ const entry = expressionPorts.get(path);
615
+ if (!entry)
616
+ continue;
617
+ if (entry.port.live || [...(inputs.get(path) ?? [])].some(dep => livePorts.has(dep))) {
618
+ livePorts.add(path);
619
+ }
620
+ }
621
+ for (const ref of offTimeRefs) {
622
+ if (livePorts.has(ref.path)) {
623
+ fail('off-time-live-channel', 'Live channel does not support off-time reads: ' + ref.path, ref.source);
624
+ }
625
+ }
626
+ const liveChannels = channels.filter(channel => channel.live).map(channelPath).sort(comparePaths);
627
+ const audioChannels = new Set(contextWires.filter(({ to, from }) => to.startsWith('/ch/') && from.stage === 'audio').map(({ to }) => to));
628
+ for (const path of finished.order) {
629
+ if (path.startsWith('/ch/') && [...(inputs.get(path) ?? [])].some(input => audioChannels.has(input))) {
630
+ audioChannels.add(path);
631
+ }
632
+ }
633
+ const scene = freeze({
634
+ fps,
635
+ ...(options.frameCount !== undefined && { frameCount: options.frameCount }),
465
636
  graph: finished.graph,
637
+ liveChannels,
466
638
  ...((viewCamera || backgroundColor || display) && { view: {
467
639
  ...(viewCamera && { camera: objectPath(viewCamera) }),
468
640
  ...(backgroundColor && { backgroundColor }),
@@ -471,7 +643,7 @@ function compile(lines, root, fps, options) {
471
643
  });
472
644
  objects.sort((a, b) => comparePaths(objectPath(a), objectPath(b)));
473
645
  channels.sort((a, b) => comparePaths(channelPath(a), channelPath(b)));
474
- plans.set(scene, { objects, channels, drivers, events, order: finished.order });
646
+ plans.set(scene, { objects, channels, drivers, events, order: finished.order, extensions, audioChannels });
475
647
  return scene;
476
648
  }
477
649
  function rename(names, node, name, source) {