@vim3d/core 0.1.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/README.md +36 -1
- package/channels.d.ts +8 -0
- package/channels.js +74 -0
- package/compile.d.ts +2 -0
- package/compile.js +658 -0
- package/contexts.d.ts +55 -0
- package/contexts.js +310 -0
- package/esm/channels.js +68 -0
- package/esm/compile.js +655 -0
- package/esm/contexts.js +304 -0
- package/esm/evaluate.js +213 -0
- package/esm/expression.js +179 -0
- package/esm/graph.js +105 -0
- package/esm/index.js +3 -0
- package/esm/math.js +81 -0
- package/esm/model.js +165 -0
- package/esm/registry.js +93 -0
- package/esm/types.js +23 -0
- package/evaluate.d.ts +2 -0
- package/evaluate.js +216 -0
- package/expression.d.ts +65 -0
- package/expression.js +184 -0
- package/graph.d.ts +14 -0
- package/graph.js +110 -0
- package/index.d.ts +6 -0
- package/index.js +8 -1
- package/math.d.ts +25 -0
- package/math.js +101 -0
- package/model.d.ts +107 -0
- package/model.js +181 -0
- package/package.json +4 -1
- package/registry.d.ts +14 -0
- package/registry.js +98 -0
- package/types.d.ts +192 -0
- package/types.js +30 -0
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { fail, finite } from './types.js';
|
|
2
|
+
const variables = ['$F', '$T', '$FPS', '$NFRAMES', '$PI', '$TAU', '$E'];
|
|
3
|
+
const lerp = (a, b, u) => a + (b - a) * u;
|
|
4
|
+
const unit = (u) => Math.max(0, Math.min(1, u));
|
|
5
|
+
const smooth = (u) => u * u * (3 - 2 * u);
|
|
6
|
+
function noise(x, seed = 0) {
|
|
7
|
+
const i = Math.floor(x);
|
|
8
|
+
if (![i, i + 1, seed].every(Number.isSafeInteger))
|
|
9
|
+
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
|
+
};
|
|
16
|
+
return lerp(hash(i), hash(i + 1), smooth(x - i));
|
|
17
|
+
}
|
|
18
|
+
const functions = {
|
|
19
|
+
sin: [1, 1, Math.sin], cos: [1, 1, Math.cos], tan: [1, 1, Math.tan],
|
|
20
|
+
atan2: [2, 2, (y, x) => x === 0 && y === 0 ? NaN : Math.atan2(y, x)],
|
|
21
|
+
abs: [1, 1, Math.abs], floor: [1, 1, Math.floor], ceil: [1, 1, Math.ceil],
|
|
22
|
+
round: [1, 1, Math.round], min: [1, Infinity, Math.min], max: [1, Infinity, Math.max],
|
|
23
|
+
clamp: [3, 3, (x, lo, hi) => lo <= hi ? Math.max(lo, Math.min(hi, x)) : NaN],
|
|
24
|
+
lerp: [3, 3, lerp],
|
|
25
|
+
fit: [5, 5, (x, a, b, c, d) => a < b ? lerp(c, d, unit((x - a) / (b - a))) : NaN],
|
|
26
|
+
smoothstep: [3, 3, (a, b, x) => a < b ? smooth(unit((x - a) / (b - a))) : NaN],
|
|
27
|
+
pow: [2, 2, Math.pow], sqrt: [1, 1, Math.sqrt], exp: [1, 1, Math.exp],
|
|
28
|
+
log: [1, 1, Math.log], noise: [1, 2, noise],
|
|
29
|
+
};
|
|
30
|
+
export function parseExpression(text, source) {
|
|
31
|
+
let pos = 0;
|
|
32
|
+
const token = /[ \t]*(\d+(?:\.\d*)?(?:[eE][+-]?\d+)?|\.\d+(?:[eE][+-]?\d+)?|\$?[a-zA-Z][a-zA-Z0-9]*|'[^'\x00-\x1f\x7f]*'|"[^"\x00-\x1f\x7f]*"|[()+*/%^-]|,)/y;
|
|
33
|
+
let current = '';
|
|
34
|
+
function next() {
|
|
35
|
+
token.lastIndex = pos;
|
|
36
|
+
const match = token.exec(text);
|
|
37
|
+
if (!match && !/^[ \t]*$/.test(text.slice(pos)))
|
|
38
|
+
invalid('Unexpected token');
|
|
39
|
+
current = match?.[1] ?? '';
|
|
40
|
+
pos = match ? token.lastIndex : text.length;
|
|
41
|
+
}
|
|
42
|
+
function invalid(message) {
|
|
43
|
+
fail('expression-syntax', message + ' at expression column ' + (pos + 1), source);
|
|
44
|
+
}
|
|
45
|
+
function take(expected) {
|
|
46
|
+
if (current !== expected)
|
|
47
|
+
return false;
|
|
48
|
+
next();
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
function expect(expected) {
|
|
52
|
+
if (!take(expected))
|
|
53
|
+
invalid('Expected ' + expected);
|
|
54
|
+
}
|
|
55
|
+
function primary() {
|
|
56
|
+
if (take('(')) {
|
|
57
|
+
const value = sum();
|
|
58
|
+
expect(')');
|
|
59
|
+
return value;
|
|
60
|
+
}
|
|
61
|
+
const word = current;
|
|
62
|
+
next();
|
|
63
|
+
if (/^[\d.]/.test(word))
|
|
64
|
+
return { kind: 'number', value: finite(Number(word), 'Number literal', source) };
|
|
65
|
+
if (variables.includes(word))
|
|
66
|
+
return { kind: 'variable', name: word };
|
|
67
|
+
if (word === 'ch' || word === 'chf' || word === 'cht') {
|
|
68
|
+
expect('(');
|
|
69
|
+
const path = current;
|
|
70
|
+
if (!/^['"]/.test(path))
|
|
71
|
+
invalid('Expected a literal path');
|
|
72
|
+
next();
|
|
73
|
+
let time;
|
|
74
|
+
if (word !== 'ch') {
|
|
75
|
+
expect(',');
|
|
76
|
+
time = sum();
|
|
77
|
+
}
|
|
78
|
+
expect(')');
|
|
79
|
+
return { kind: 'reference', name: word, path: path.slice(1, -1), ...(time && { time }) };
|
|
80
|
+
}
|
|
81
|
+
if (!Object.hasOwn(functions, word))
|
|
82
|
+
invalid('Unknown expression name ' + JSON.stringify(word));
|
|
83
|
+
const name = word;
|
|
84
|
+
expect('(');
|
|
85
|
+
const args = [sum()];
|
|
86
|
+
while (take(','))
|
|
87
|
+
args.push(sum());
|
|
88
|
+
expect(')');
|
|
89
|
+
const [min, max] = functions[name];
|
|
90
|
+
if (args.length < min || args.length > max)
|
|
91
|
+
invalid('Wrong number of arguments to ' + name);
|
|
92
|
+
return { kind: 'call', name, args };
|
|
93
|
+
}
|
|
94
|
+
function unary() {
|
|
95
|
+
if (current === '+' || current === '-') {
|
|
96
|
+
const op = current;
|
|
97
|
+
next();
|
|
98
|
+
return { kind: 'unary', op, operand: unary() };
|
|
99
|
+
}
|
|
100
|
+
const left = primary();
|
|
101
|
+
return take('^') ? { kind: 'binary', op: '^', left, right: unary() } : left;
|
|
102
|
+
}
|
|
103
|
+
function chain(read, ops) {
|
|
104
|
+
let left = read();
|
|
105
|
+
while (ops.includes(current)) {
|
|
106
|
+
const op = current;
|
|
107
|
+
next();
|
|
108
|
+
left = { kind: 'binary', op, left, right: read() };
|
|
109
|
+
}
|
|
110
|
+
return left;
|
|
111
|
+
}
|
|
112
|
+
const sum = () => chain(() => chain(unary, ['*', '/', '%']), ['+', '-']);
|
|
113
|
+
next();
|
|
114
|
+
const ast = sum();
|
|
115
|
+
if (current)
|
|
116
|
+
invalid('Unexpected token ' + current);
|
|
117
|
+
return ast;
|
|
118
|
+
}
|
|
119
|
+
export function bindExpression(ast, resolve) {
|
|
120
|
+
const bind = (expr) => bindExpression(expr, resolve);
|
|
121
|
+
switch (ast.kind) {
|
|
122
|
+
case 'reference': return { ...ast, path: resolve(ast.path, ast.name), ...(ast.time && { time: bind(ast.time) }) };
|
|
123
|
+
case 'unary': return { ...ast, operand: bind(ast.operand) };
|
|
124
|
+
case 'binary': return { ...ast, left: bind(ast.left), right: bind(ast.right) };
|
|
125
|
+
case 'call': return { ...ast, args: ast.args.map(bind) };
|
|
126
|
+
default: return ast;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
export function evaluateExpression(ast, context) {
|
|
130
|
+
const { frame, fps, frameCount, source, read } = context;
|
|
131
|
+
const visit = (node) => {
|
|
132
|
+
let value;
|
|
133
|
+
switch (node.kind) {
|
|
134
|
+
case 'number': return node.value;
|
|
135
|
+
case 'variable':
|
|
136
|
+
if (node.name === '$NFRAMES' && frameCount === undefined) {
|
|
137
|
+
fail('missing-frame-count', '$NFRAMES requires a configured frame count', source);
|
|
138
|
+
}
|
|
139
|
+
value = { $F: frame, $T: frame / fps, $FPS: fps, $NFRAMES: frameCount,
|
|
140
|
+
$PI: Math.PI, $TAU: Math.PI * 2, $E: Math.E }[node.name];
|
|
141
|
+
break;
|
|
142
|
+
case 'reference': {
|
|
143
|
+
const time = node.time ? visit(node.time) : frame;
|
|
144
|
+
return read(node.path, finite(node.name === 'cht' ? time * fps : time, 'Sample frame', source));
|
|
145
|
+
}
|
|
146
|
+
case 'unary': return node.op === '-' ? -visit(node.operand) : visit(node.operand);
|
|
147
|
+
case 'binary': {
|
|
148
|
+
const a = visit(node.left);
|
|
149
|
+
const b = visit(node.right);
|
|
150
|
+
switch (node.op) {
|
|
151
|
+
case '+':
|
|
152
|
+
value = a + b;
|
|
153
|
+
break;
|
|
154
|
+
case '-':
|
|
155
|
+
value = a - b;
|
|
156
|
+
break;
|
|
157
|
+
case '*':
|
|
158
|
+
value = a * b;
|
|
159
|
+
break;
|
|
160
|
+
case '/':
|
|
161
|
+
value = a / b;
|
|
162
|
+
break;
|
|
163
|
+
case '%':
|
|
164
|
+
value = a % b;
|
|
165
|
+
break;
|
|
166
|
+
case '^':
|
|
167
|
+
value = a ** b;
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
170
|
+
break;
|
|
171
|
+
}
|
|
172
|
+
case 'call':
|
|
173
|
+
value = functions[node.name][2](...node.args.map(visit));
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
return finite(value, 'Expression value', source);
|
|
177
|
+
};
|
|
178
|
+
return visit(ast);
|
|
179
|
+
}
|
package/esm/graph.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { fail } from './types.js';
|
|
2
|
+
const encoder = new TextEncoder();
|
|
3
|
+
const graphName = (path) => path.replaceAll('%', '%25').replaceAll('/', '%2F');
|
|
4
|
+
export function comparePaths(a, b) {
|
|
5
|
+
if (a === b)
|
|
6
|
+
return 0;
|
|
7
|
+
const x = encoder.encode(a), y = encoder.encode(b);
|
|
8
|
+
for (let i = 0; i < Math.min(x.length, y.length); i++) {
|
|
9
|
+
if (x[i] !== y[i])
|
|
10
|
+
return x[i] - y[i];
|
|
11
|
+
}
|
|
12
|
+
return x.length - y.length;
|
|
13
|
+
}
|
|
14
|
+
export class GraphBuilder {
|
|
15
|
+
steps = new Map();
|
|
16
|
+
add(path, type, portType, props, source) {
|
|
17
|
+
const context = path.startsWith('/ch/') ? 'ch' : 'obj';
|
|
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 });
|
|
22
|
+
}
|
|
23
|
+
depend(to, on) {
|
|
24
|
+
this.steps.get(to).dependencies.add(on);
|
|
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
|
+
}
|
|
37
|
+
finish() {
|
|
38
|
+
const paths = [...this.steps.keys()].sort(comparePaths);
|
|
39
|
+
const counts = new Map();
|
|
40
|
+
const readers = new Map();
|
|
41
|
+
for (const path of paths) {
|
|
42
|
+
const { dependencies } = this.steps.get(path);
|
|
43
|
+
counts.set(path, dependencies.size);
|
|
44
|
+
for (const dependency of dependencies) {
|
|
45
|
+
const list = readers.get(dependency) ?? [];
|
|
46
|
+
list.push(path);
|
|
47
|
+
readers.set(dependency, list);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const ready = paths.filter(path => !counts.get(path)).reverse();
|
|
51
|
+
const order = [];
|
|
52
|
+
while (ready.length) {
|
|
53
|
+
const path = ready.pop();
|
|
54
|
+
order.push(path);
|
|
55
|
+
for (const reader of readers.get(path) ?? []) {
|
|
56
|
+
const count = counts.get(reader) - 1;
|
|
57
|
+
counts.set(reader, count);
|
|
58
|
+
if (!count) {
|
|
59
|
+
let left = 0, right = ready.length;
|
|
60
|
+
while (left < right) {
|
|
61
|
+
const mid = (left + right) >>> 1;
|
|
62
|
+
if (comparePaths(ready[mid], reader) > 0)
|
|
63
|
+
left = mid + 1;
|
|
64
|
+
else
|
|
65
|
+
right = mid;
|
|
66
|
+
}
|
|
67
|
+
ready.splice(left, 0, reader);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (order.length !== paths.length) {
|
|
72
|
+
const chain = [];
|
|
73
|
+
const indices = new Map();
|
|
74
|
+
let path = paths.find(path => counts.get(path) > 0);
|
|
75
|
+
while (!indices.has(path)) {
|
|
76
|
+
indices.set(path, chain.length);
|
|
77
|
+
chain.push(path);
|
|
78
|
+
path = [...this.steps.get(path).dependencies].filter(dep => counts.get(dep) > 0).sort(comparePaths)[0];
|
|
79
|
+
}
|
|
80
|
+
const cycle = [...chain.slice(indices.get(path)), path];
|
|
81
|
+
fail('dependency-cycle', 'Dependency cycle: ' + cycle.join(' -> '), this.steps.get(path).source, cycle);
|
|
82
|
+
}
|
|
83
|
+
const edges = [];
|
|
84
|
+
const nodes = paths.map(path => {
|
|
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 => {
|
|
96
|
+
const source = this.steps.get(dep).node;
|
|
97
|
+
const output = source.outputs[0];
|
|
98
|
+
edges.push({ src: { node: source.name, port: output.name }, dst: { node: node.name, port: source.name } });
|
|
99
|
+
return { name: source.name, type: output.type };
|
|
100
|
+
});
|
|
101
|
+
return { ...node, inputs: [...inputs, ...typedInputs] };
|
|
102
|
+
});
|
|
103
|
+
return { order, graph: { name: 'scene', nodes, edges } };
|
|
104
|
+
}
|
|
105
|
+
}
|
package/esm/index.js
CHANGED
package/esm/math.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { fail, finite } from './types.js';
|
|
2
|
+
export const identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
|
|
3
|
+
export const worldUp = [0, 1, 0];
|
|
4
|
+
export const add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
|
|
5
|
+
export const sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
|
|
6
|
+
export const scale = (a, s) => [a[0] * s, a[1] * s, a[2] * s];
|
|
7
|
+
export const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
|
8
|
+
export const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
|
|
9
|
+
export const length = (a) => Math.hypot(...a);
|
|
10
|
+
export const normalize = (a) => {
|
|
11
|
+
const n = length(a);
|
|
12
|
+
return n === 0 ? [0, 0, 0] : [a[0] / n, a[1] / n, a[2] / n];
|
|
13
|
+
};
|
|
14
|
+
export const column = (a, i) => [a[i * 4], a[i * 4 + 1], a[i * 4 + 2]];
|
|
15
|
+
const radians = Math.PI / 180;
|
|
16
|
+
export function euler([x, y, z]) {
|
|
17
|
+
const [sx, sy, sz] = [x, y, z].map(a => Math.sin(a * radians));
|
|
18
|
+
const [cx, cy, cz] = [x, y, z].map(a => Math.cos(a * radians));
|
|
19
|
+
return [[cz * cy, sz * cy, -sy],
|
|
20
|
+
[cz * sy * sx - sz * cx, sz * sy * sx + cz * cx, cy * sx],
|
|
21
|
+
[cz * sy * cx + sz * sx, sz * sy * cx - cz * sx, cy * cx]];
|
|
22
|
+
}
|
|
23
|
+
export function decompose(m, source) {
|
|
24
|
+
const cols = [column(m, 0), column(m, 1), column(m, 2)];
|
|
25
|
+
const [sx, sy, sz] = cols.map(length);
|
|
26
|
+
if (![sx, sy, sz].every(n => n > 0 && Number.isFinite(n)))
|
|
27
|
+
return;
|
|
28
|
+
const [x, y, z] = cols.map(normalize);
|
|
29
|
+
if ([dot(x, y), dot(x, z), dot(y, z)].some(n => Math.abs(n) > 1e-8))
|
|
30
|
+
return;
|
|
31
|
+
const sign = Math.sign(dot(cross(x, y), z));
|
|
32
|
+
const ry = Math.asin(Math.max(-1, Math.min(1, -x[2])));
|
|
33
|
+
const singular = Math.abs(Math.cos(ry)) <= 1e-8;
|
|
34
|
+
const rx = singular ? 0 : Math.atan2(y[2], z[2] * sign);
|
|
35
|
+
const rz = singular ? Math.atan2(-y[0], y[1]) : Math.atan2(x[1], x[0]);
|
|
36
|
+
return { rotation: [finite(rx / radians, 'Rotation', source), ry / radians, rz / radians],
|
|
37
|
+
scale: [sx, sy, sz * sign] };
|
|
38
|
+
}
|
|
39
|
+
export function matrix(position, axes, sizes) {
|
|
40
|
+
return [...axes.flatMap((axis, i) => [...scale(axis, sizes[i]), 0]), ...position, 1];
|
|
41
|
+
}
|
|
42
|
+
export function direction(m, p) {
|
|
43
|
+
return add(add(scale(column(m, 0), p[0]), scale(column(m, 1), p[1])), scale(column(m, 2), p[2]));
|
|
44
|
+
}
|
|
45
|
+
export function point(m, p) {
|
|
46
|
+
return add(direction(m, p), column(m, 3));
|
|
47
|
+
}
|
|
48
|
+
export function multiply(a, b) {
|
|
49
|
+
return matrix(point(a, column(b, 3)), [direction(a, column(b, 0)), direction(a, column(b, 1)), direction(a, column(b, 2))], [1, 1, 1]);
|
|
50
|
+
}
|
|
51
|
+
export function inverseDirection(m, p, source) {
|
|
52
|
+
const [a, b, c] = [column(m, 0), column(m, 1), column(m, 2)];
|
|
53
|
+
const u = cross(b, c), v = cross(c, a), w = cross(a, b);
|
|
54
|
+
const det = dot(a, u);
|
|
55
|
+
if (!det || !Number.isFinite(det))
|
|
56
|
+
fail('singular-parent', 'Constraint requires an invertible parent matrix', source);
|
|
57
|
+
return [dot(u, p) / det, dot(v, p) / det, dot(w, p) / det];
|
|
58
|
+
}
|
|
59
|
+
export function aim(parent, origin, target, up, forward, sizes, source) {
|
|
60
|
+
const delta = sub(target, origin);
|
|
61
|
+
if (length(delta) === 0)
|
|
62
|
+
return;
|
|
63
|
+
if (!sizes[1] || !sizes[2])
|
|
64
|
+
fail('zero-lookat-scale', 'Look-at requires nonzero Y and Z scale', source);
|
|
65
|
+
const d = normalize(delta);
|
|
66
|
+
let hint = normalize(up);
|
|
67
|
+
if (length(hint) === 0 || Math.abs(dot(hint, d)) >= 1 - 1e-8) {
|
|
68
|
+
const candidates = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
|
|
69
|
+
hint = candidates.reduce((a, b) => Math.abs(dot(b, d)) < Math.abs(dot(a, d)) ? b : a);
|
|
70
|
+
}
|
|
71
|
+
const z = scale(d, forward);
|
|
72
|
+
const y = cross(z, normalize(cross(hint, z)));
|
|
73
|
+
const localZ = scale(normalize(inverseDirection(parent, z, source)), Math.sign(sizes[2]));
|
|
74
|
+
const projected = inverseDirection(parent, y, source);
|
|
75
|
+
const localY = scale(normalize(sub(projected, scale(localZ, dot(localZ, projected)))), Math.sign(sizes[1]));
|
|
76
|
+
const localX = cross(localY, localZ);
|
|
77
|
+
return [localX, cross(localZ, localX), localZ];
|
|
78
|
+
}
|
|
79
|
+
export function wrap(i, count) {
|
|
80
|
+
return (i % count + count) % count;
|
|
81
|
+
}
|
package/esm/model.js
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { aim, column, cross, decompose, dot, euler, identity, matrix, normalize, worldUp } from './math.js';
|
|
2
|
+
import { fail, finite } from './types.js';
|
|
3
|
+
export const plans = new WeakMap();
|
|
4
|
+
export const objectPath = (object) => '/obj/' + object.name;
|
|
5
|
+
export const channelPath = (channel) => '/ch/' + channel.name;
|
|
6
|
+
export const positionStep = (object) => objectPath(object) + '/@position';
|
|
7
|
+
export const worldStep = (object) => objectPath(object) + '/@world';
|
|
8
|
+
export const translations = ['tx', 'ty', 'tz'];
|
|
9
|
+
export const rotations = ['rx', 'ry', 'rz'];
|
|
10
|
+
export const scales = ['sx', 'sy', 'sz'];
|
|
11
|
+
export const vector = (p, keys) => [p[keys[0]], p[keys[1]], p[keys[2]]];
|
|
12
|
+
export const copyState = (state) => ({ ...state, parameters: { ...state.parameters } });
|
|
13
|
+
export const active = (f, range) => f >= range.start && f <= range.end;
|
|
14
|
+
export const isColor = (param) => /^(diff|amb|spec)[rgba]$/.test(param);
|
|
15
|
+
export function defaults(kind) {
|
|
16
|
+
const parameters = {
|
|
17
|
+
tx: 0, ty: 0, tz: 0, rx: 0, ry: 0, rz: 0, sx: 1, sy: 1, sz: 1,
|
|
18
|
+
};
|
|
19
|
+
if (kind === 'geo' || kind === 'curve' || kind === 'light') {
|
|
20
|
+
Object.assign(parameters, { diffr: 1, diffg: 1, diffb: 1, diffa: 1,
|
|
21
|
+
ambr: 0, ambg: 0, ambb: 0, amba: 1, specr: 0, specg: 0, specb: 0, speca: 1 });
|
|
22
|
+
if (kind !== 'light')
|
|
23
|
+
parameters.shine = 0;
|
|
24
|
+
}
|
|
25
|
+
if (kind === 'camera')
|
|
26
|
+
Object.assign(parameters, { fovy: 45, znear: 0.1, zfar: 1000 });
|
|
27
|
+
return { parameters, up: worldUp, light: 'point', visible: true, enabled: true };
|
|
28
|
+
}
|
|
29
|
+
export function readNumber(text, source) {
|
|
30
|
+
if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(text)) {
|
|
31
|
+
fail('invalid-number', 'Expected a finite number, got ' + JSON.stringify(text), source);
|
|
32
|
+
}
|
|
33
|
+
return finite(Number(text), 'Number', source);
|
|
34
|
+
}
|
|
35
|
+
export function readFrame(text, source) {
|
|
36
|
+
const n = readNumber(text, source);
|
|
37
|
+
if (n < 0 || !Number.isSafeInteger(n) || !/^\+?\d+$/.test(text)) {
|
|
38
|
+
fail('invalid-frame', 'Expected a nonnegative integer frame, got ' + text, source);
|
|
39
|
+
}
|
|
40
|
+
return n;
|
|
41
|
+
}
|
|
42
|
+
export function checkArity(command, args, counts, source) {
|
|
43
|
+
if (!counts.includes(args.length))
|
|
44
|
+
fail('invalid-operands', command + ': invalid argument count', source);
|
|
45
|
+
}
|
|
46
|
+
export function propertyEdit(command, args, object, source) {
|
|
47
|
+
const numbers = (length) => {
|
|
48
|
+
checkArity(command, args, [length], source);
|
|
49
|
+
return args.map(s => readNumber(s, source));
|
|
50
|
+
};
|
|
51
|
+
const setRotation = (state, axes) => {
|
|
52
|
+
if (state.matrix)
|
|
53
|
+
fail('invalid-trs', 'Cannot rotate a matrix without TRS', source);
|
|
54
|
+
const trs = decompose(matrix([0, 0, 0], axes, [1, 1, 1]), source);
|
|
55
|
+
rotations.forEach((key, i) => { state.parameters[key] = trs.rotation[i]; });
|
|
56
|
+
};
|
|
57
|
+
switch (command) {
|
|
58
|
+
case 'position':
|
|
59
|
+
case 'translate':
|
|
60
|
+
case 'scale': {
|
|
61
|
+
const values = numbers(3);
|
|
62
|
+
return state => {
|
|
63
|
+
const keys = command === 'scale' ? scales : translations;
|
|
64
|
+
if (state.matrix && command === 'scale')
|
|
65
|
+
fail('invalid-trs', 'Cannot scale a matrix without TRS', source);
|
|
66
|
+
keys.forEach((key, i) => {
|
|
67
|
+
const original = state.parameters[key];
|
|
68
|
+
state.parameters[key] = finite(command === 'translate' ? original + values[i]
|
|
69
|
+
: command === 'scale' ? original * values[i] : values[i], key, source);
|
|
70
|
+
});
|
|
71
|
+
if (state.matrix)
|
|
72
|
+
state.matrix = [...state.matrix.slice(0, 12), ...vector(state.parameters, translations), 1];
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
case 'rotate': {
|
|
76
|
+
const [degrees, x, y, z] = numbers(4);
|
|
77
|
+
const axis = normalize([x, y, z]);
|
|
78
|
+
if (!axis.some(Boolean))
|
|
79
|
+
fail('invalid-rotation', 'Rotation axis must be nonzero', source);
|
|
80
|
+
const a = degrees * (Math.PI / 180);
|
|
81
|
+
return state => {
|
|
82
|
+
const rot = (v) => {
|
|
83
|
+
const c = Math.cos(a), s = Math.sin(a), p = cross(axis, v), k = dot(axis, v) * (1 - c);
|
|
84
|
+
return [v[0] * c + p[0] * s + k * axis[0], v[1] * c + p[1] * s + k * axis[1], v[2] * c + p[2] * s + k * axis[2]];
|
|
85
|
+
};
|
|
86
|
+
const [a1, a2, a3] = euler(vector(state.parameters, rotations));
|
|
87
|
+
setRotation(state, [rot(a1), rot(a2), rot(a3)]);
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
case 'matrix': {
|
|
91
|
+
const m = numbers(16);
|
|
92
|
+
if (m[3] !== 0 || m[7] !== 0 || m[11] !== 0 || m[15] !== 1)
|
|
93
|
+
fail('invalid-matrix', 'Expected an affine matrix', source);
|
|
94
|
+
const trs = decompose(m, source);
|
|
95
|
+
return state => {
|
|
96
|
+
state.matrix = trs ? undefined : m;
|
|
97
|
+
translations.forEach((key, i) => { state.parameters[key] = m[12 + i]; });
|
|
98
|
+
rotations.forEach((key, i) => { state.parameters[key] = trs?.rotation[i] ?? 0; });
|
|
99
|
+
scales.forEach((key, i) => { state.parameters[key] = trs?.scale[i] ?? Math.hypot(...column(m, i)); });
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
case 'diffuse':
|
|
103
|
+
case 'ambient':
|
|
104
|
+
case 'specular':
|
|
105
|
+
case 'shininess':
|
|
106
|
+
case 'fovy':
|
|
107
|
+
case 'znear':
|
|
108
|
+
case 'zfar': {
|
|
109
|
+
const prefix = command === 'diffuse' ? 'diff' : command === 'ambient' ? 'amb' : command === 'specular' ? 'spec' : undefined;
|
|
110
|
+
const keys = prefix ? [...'rgba'].map(c => prefix + c) : [command === 'shininess' ? 'shine' : command];
|
|
111
|
+
const values = numbers(keys.length);
|
|
112
|
+
if (!Object.hasOwn(object.authored.parameters, keys[0]))
|
|
113
|
+
fail('unsupported-parameter', 'Unsupported property: ' + command, source);
|
|
114
|
+
return state => { keys.forEach((key, i) => { state.parameters[key] = values[i]; }); };
|
|
115
|
+
}
|
|
116
|
+
case 'up':
|
|
117
|
+
case 'camera': {
|
|
118
|
+
if (object.kind !== 'camera')
|
|
119
|
+
fail('invalid-subject', command + ' requires a camera', source);
|
|
120
|
+
if (command === 'camera') {
|
|
121
|
+
if (args[0] !== 'lookat')
|
|
122
|
+
fail('invalid-operands', 'Expected camera lookat X Y Z', source);
|
|
123
|
+
args = args.slice(1);
|
|
124
|
+
}
|
|
125
|
+
const [x, y, z] = numbers(3);
|
|
126
|
+
const value = [x, y, z];
|
|
127
|
+
return state => {
|
|
128
|
+
if (command === 'up')
|
|
129
|
+
state.up = value;
|
|
130
|
+
if (command === 'camera')
|
|
131
|
+
state.focus = value;
|
|
132
|
+
if (state.focus) {
|
|
133
|
+
const axes = aim(identity, vector(state.parameters, translations), state.focus, state.up, -1, [1, 1, 1], source);
|
|
134
|
+
if (axes)
|
|
135
|
+
setRotation(state, axes);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
case 'light': {
|
|
140
|
+
if (object.kind !== 'light')
|
|
141
|
+
fail('invalid-subject', 'light requires a light', source);
|
|
142
|
+
const [mode] = args;
|
|
143
|
+
checkArity(command, args, mode === 'spot' ? [1, 4] : [1], source);
|
|
144
|
+
const direction = args.slice(1).map(s => readNumber(s, source));
|
|
145
|
+
if (!['point', 'dir', 'directional', 'spot', 'on', 'off'].includes(mode)) {
|
|
146
|
+
fail('invalid-operands', 'Unsupported light mode: ' + mode, source);
|
|
147
|
+
}
|
|
148
|
+
return state => {
|
|
149
|
+
if (mode === 'on' || mode === 'off')
|
|
150
|
+
state.enabled = mode === 'on';
|
|
151
|
+
else
|
|
152
|
+
state.light = mode === 'dir' ? 'directional' : mode;
|
|
153
|
+
if (direction.length) {
|
|
154
|
+
const axes = aim(identity, [0, 0, 0], [direction[0], direction[1], direction[2]], worldUp, -1, [1, 1, 1], source);
|
|
155
|
+
if (axes)
|
|
156
|
+
setRotation(state, axes);
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
export const editCommands = new Set([
|
|
163
|
+
'position', 'translate', 'scale', 'rotate', 'matrix', 'diffuse', 'specular', 'ambient',
|
|
164
|
+
'shininess', 'fovy', 'znear', 'zfar', 'up', 'camera', 'light',
|
|
165
|
+
]);
|
package/esm/registry.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { fail, finite, freeze, } from './types.js';
|
|
2
|
+
const ports = (type, ...names) => names.map(name => ({ name, type }));
|
|
3
|
+
const numeric = (defaults) => Object.entries(defaults)
|
|
4
|
+
.map(([name, value]) => ({ name, type: 'number', default: value }));
|
|
5
|
+
const audioSource = (type) => ({
|
|
6
|
+
type: 'audio:' + type,
|
|
7
|
+
inputs: [],
|
|
8
|
+
outputs: [...ports('object', 'signal'), ...ports('number', 'rms', 'peak')],
|
|
9
|
+
props: type === 'file' ? [{ name: 'asset', type: 'string', required: true }, ...numeric({ gain: 1 })]
|
|
10
|
+
: [{ name: 'device', type: 'string' }, ...numeric({ gain: 1 })],
|
|
11
|
+
evaluate: ({ path, props }, audio) => {
|
|
12
|
+
const gain = Math.abs(props.gain);
|
|
13
|
+
const rms = finite((audio?.rms ?? 0) * gain, path + '/rms');
|
|
14
|
+
const peak = finite((audio?.peak ?? 0) * gain, path + '/peak');
|
|
15
|
+
return { signal: { rms, peak }, rms, peak };
|
|
16
|
+
},
|
|
17
|
+
});
|
|
18
|
+
const audio = [
|
|
19
|
+
audioSource('file'), audioSource('mic'),
|
|
20
|
+
{
|
|
21
|
+
type: 'audio:fft',
|
|
22
|
+
inputs: ports('object', 'signal'),
|
|
23
|
+
outputs: [...ports('number', 'bass', 'mid', 'high', 'centroid', 'flux'), ...ports('object', 'spectrum')],
|
|
24
|
+
props: numeric({ fftSize: 2048, smoothing: 0.8 }),
|
|
25
|
+
evaluate: (_, data) => ({
|
|
26
|
+
bass: data?.bass ?? 0, mid: data?.mid ?? 0, high: data?.high ?? 0, centroid: data?.centroid ?? 0,
|
|
27
|
+
flux: data?.flux ?? 0, spectrum: data?.spectrum ?? [],
|
|
28
|
+
}),
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
type: 'audio:envelope',
|
|
32
|
+
inputs: ports('number', 'value'), outputs: ports('number', 'value'),
|
|
33
|
+
props: numeric({ attack: 0.01, release: 0.1 }),
|
|
34
|
+
evaluate: ({ inputs }, data) => ({ value: data?.rms ?? inputs.value ?? 0 }),
|
|
35
|
+
},
|
|
36
|
+
];
|
|
37
|
+
const geo = [
|
|
38
|
+
{
|
|
39
|
+
type: 'geo:box', inputs: [], outputs: ports('object', 'geometry'), props: numeric({ width: 1, height: 1, depth: 1 }),
|
|
40
|
+
evaluate: ({ props }) => ({ geometry: { primitive: 'box', args: [props.width, props.height, props.depth] } }),
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
type: 'geo:sphere', inputs: [], outputs: ports('object', 'geometry'), props: numeric({ radius: 1, segments: 32 }),
|
|
44
|
+
evaluate: ({ props }) => ({ geometry: { primitive: 'sphere', args: [props.radius, props.radius, props.segments] } }),
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
type: 'geo:transform',
|
|
48
|
+
inputs: [...ports('object', 'geometry'), ...ports('number', 'tx', 'ty', 'tz', 'sx', 'sy', 'sz')],
|
|
49
|
+
outputs: ports('object', 'geometry'), props: [],
|
|
50
|
+
evaluate: ({ inputs }) => ({ geometry: {
|
|
51
|
+
kind: 'transform', geometry: inputs.geometry ?? null,
|
|
52
|
+
translate: [inputs.tx ?? 0, inputs.ty ?? 0, inputs.tz ?? 0], scale: [inputs.sx ?? 1, inputs.sy ?? 1, inputs.sz ?? 1],
|
|
53
|
+
} }),
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
type: 'geo:merge', inputs: ports('object', 'a', 'b'), outputs: ports('object', 'geometry'), props: [],
|
|
57
|
+
evaluate: ({ inputs }) => ({ geometry: { kind: 'merge', geometries: [inputs.a, inputs.b].filter(value => value !== undefined) } }),
|
|
58
|
+
},
|
|
59
|
+
];
|
|
60
|
+
export const BUILTIN_CONTEXTS = freeze([
|
|
61
|
+
{ name: 'audio', stage: 'audio', nodeTypes: audio },
|
|
62
|
+
{ name: 'ch', stage: 'ch', nodeTypes: [] },
|
|
63
|
+
{ name: 'geo', stage: 'geo', nodeTypes: geo },
|
|
64
|
+
{ name: 'obj', stage: 'obj', nodeTypes: [] },
|
|
65
|
+
{ name: 'sim', stage: 'reserved', nodeTypes: [] },
|
|
66
|
+
]);
|
|
67
|
+
export function createContextRegistry(extensions = []) {
|
|
68
|
+
const contexts = new Map(BUILTIN_CONTEXTS.map(context => [context.name, context]));
|
|
69
|
+
for (const context of extensions) {
|
|
70
|
+
if (typeof context.name !== 'string' || !/^[a-z][a-z0-9_-]*$/.test(context.name) ||
|
|
71
|
+
BUILTIN_CONTEXTS.some(({ name }) => name === context.name)) {
|
|
72
|
+
fail('invalid-extension-context', 'Invalid or reserved extension context: ' + context.name);
|
|
73
|
+
}
|
|
74
|
+
if (contexts.has(context.name))
|
|
75
|
+
fail('duplicate-extension-context', 'Duplicate extension context: ' + context.name);
|
|
76
|
+
if ((context.stage !== 'evaluate' && context.stage !== 'output') || !Array.isArray(context.nodeTypes)) {
|
|
77
|
+
fail('invalid-extension-definition', 'Invalid stage or node types for /' + context.name);
|
|
78
|
+
}
|
|
79
|
+
contexts.set(context.name, Object.freeze({ ...context, nodeTypes: Object.freeze([...context.nodeTypes]) }));
|
|
80
|
+
}
|
|
81
|
+
return Object.freeze({ contexts: Object.freeze([...contexts.values()]), get: (name) => contexts.get(name) });
|
|
82
|
+
}
|
|
83
|
+
export function allowedSource(target, source) {
|
|
84
|
+
switch (target) {
|
|
85
|
+
case 'audio': return source === 'audio';
|
|
86
|
+
case 'ch': return source === 'audio' || source === 'ch';
|
|
87
|
+
case 'geo': return source === 'audio' || source === 'ch' || source === 'geo';
|
|
88
|
+
case 'obj': return source === 'audio' || source === 'ch' || source === 'geo' || source === 'obj';
|
|
89
|
+
case 'evaluate':
|
|
90
|
+
case 'output': return source !== 'output' && source !== 'reserved';
|
|
91
|
+
case 'reserved': return false;
|
|
92
|
+
}
|
|
93
|
+
}
|
package/esm/types.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export class EvaluationError extends Error {
|
|
2
|
+
diagnostic;
|
|
3
|
+
constructor(diagnostic) {
|
|
4
|
+
super(diagnostic.message);
|
|
5
|
+
this.diagnostic = diagnostic;
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
export function fail(code, message, source, dependencyPath) {
|
|
9
|
+
throw new EvaluationError({ code, message, ...(source && { source }), ...(dependencyPath && { dependencyPath }) });
|
|
10
|
+
}
|
|
11
|
+
export function finite(value, description, source) {
|
|
12
|
+
if (!Number.isFinite(value))
|
|
13
|
+
fail('non-finite', `${description} must be finite`, source);
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
export function freeze(value) {
|
|
17
|
+
if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
18
|
+
for (const child of Object.values(value))
|
|
19
|
+
freeze(child);
|
|
20
|
+
Object.freeze(value);
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
}
|
package/evaluate.d.ts
ADDED