@vim3d/core 0.0.1 → 0.2.0
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 +32 -1
- package/channels.d.ts +8 -0
- package/channels.js +74 -0
- package/compile.d.ts +2 -0
- package/compile.js +486 -0
- package/esm/channels.js +68 -0
- package/esm/compile.js +483 -0
- package/esm/evaluate.js +164 -0
- package/esm/expression.js +179 -0
- package/esm/graph.js +83 -0
- package/esm/index.js +2 -0
- package/esm/math.js +81 -0
- package/esm/model.js +165 -0
- package/esm/types.js +23 -0
- package/evaluate.d.ts +2 -0
- package/evaluate.js +167 -0
- package/expression.d.ts +65 -0
- package/expression.js +184 -0
- package/graph.d.ts +11 -0
- package/graph.js +88 -0
- package/index.d.ts +4 -0
- package/index.js +5 -1
- package/math.d.ts +25 -0
- package/math.js +101 -0
- package/model.d.ts +101 -0
- package/model.js +181 -0
- package/package.json +13 -9
- package/types.d.ts +123 -0
- package/types.js +30 -0
- package/esm/index.d.ts +0 -1
package/esm/evaluate.js
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { sample } from './channels.js';
|
|
2
|
+
import { evaluateExpression } from './expression.js';
|
|
3
|
+
import { add, aim, column, euler, identity, inverseDirection, matrix, multiply, normalize, point, scale, sub, worldUp, wrap } from './math.js';
|
|
4
|
+
import { active, channelPath, copyState, isColor, objectPath, plans, positionStep, rotations, scales, translations, vector, worldStep } from './model.js';
|
|
5
|
+
import { EvaluationError, fail, finite, freeze } from './types.js';
|
|
6
|
+
export function evaluateFrame(scene, frame) {
|
|
7
|
+
try {
|
|
8
|
+
if (!Number.isSafeInteger(frame) || frame < 0 || (scene.frameCount !== undefined && frame >= scene.frameCount)) {
|
|
9
|
+
fail('invalid-frame', 'Frame is outside the scene: ' + frame);
|
|
10
|
+
}
|
|
11
|
+
return { value: evaluate(scene, frame) };
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
if (error instanceof EvaluationError)
|
|
15
|
+
return { diagnostics: [error.diagnostic] };
|
|
16
|
+
throw error;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function evaluate(scene, frame) {
|
|
20
|
+
const plan = plans.get(scene);
|
|
21
|
+
if (!plan)
|
|
22
|
+
fail('invalid-scene', 'Scene was not created by compileScene');
|
|
23
|
+
const { fps, frameCount } = scene;
|
|
24
|
+
const time = finite(frame / fps, 'Scene time');
|
|
25
|
+
const state = new Map(plan.objects.map(object => [object, copyState(object.authored)]));
|
|
26
|
+
for (const event of plan.events) {
|
|
27
|
+
if (event.frame > frame)
|
|
28
|
+
break;
|
|
29
|
+
event.edit(state.get(event.object));
|
|
30
|
+
}
|
|
31
|
+
const parameters = new Map();
|
|
32
|
+
const positions = new Map();
|
|
33
|
+
const worlds = new Map();
|
|
34
|
+
for (const object of plan.objects) {
|
|
35
|
+
const path = objectPath(object);
|
|
36
|
+
for (const name of Object.keys(object.authored.parameters))
|
|
37
|
+
parameters.set(path + '/' + name, { object, name });
|
|
38
|
+
positions.set(positionStep(object), object);
|
|
39
|
+
worlds.set(worldStep(object), object);
|
|
40
|
+
}
|
|
41
|
+
const outputs = new Map();
|
|
42
|
+
for (const channel of plan.channels) {
|
|
43
|
+
for (const [name, port] of channel.ports) {
|
|
44
|
+
outputs.set(channelPath(channel) + '/' + name, { channel, port, cache: new Map() });
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
const expr = (ast, q, source) => evaluateExpression(ast, { frame: q, fps, frameCount, source, read });
|
|
48
|
+
function read(path, q) {
|
|
49
|
+
if (path.startsWith('/obj/')) {
|
|
50
|
+
const { object, name } = parameters.get(path);
|
|
51
|
+
return state.get(object).parameters[name];
|
|
52
|
+
}
|
|
53
|
+
const { channel, port, cache } = outputs.get(path);
|
|
54
|
+
const value = cache.get(q);
|
|
55
|
+
if (value !== undefined)
|
|
56
|
+
return value;
|
|
57
|
+
const result = channel.table ? sample(channel.table, port, q, fps) : expr(port.expression, q, port.source);
|
|
58
|
+
cache.set(q, result);
|
|
59
|
+
return result;
|
|
60
|
+
}
|
|
61
|
+
const channels = Object.create(null);
|
|
62
|
+
for (const path of plan.order) {
|
|
63
|
+
if (outputs.has(path))
|
|
64
|
+
channels[path] = read(path, frame);
|
|
65
|
+
}
|
|
66
|
+
for (const path of plan.order) {
|
|
67
|
+
const target = parameters.get(path);
|
|
68
|
+
if (!target)
|
|
69
|
+
continue;
|
|
70
|
+
const { object, name } = target;
|
|
71
|
+
const values = state.get(object).parameters;
|
|
72
|
+
const binding = plan.drivers.get(path)?.find(range => active(frame, range));
|
|
73
|
+
let value = values[name];
|
|
74
|
+
if (binding?.kind === 'expr')
|
|
75
|
+
value = expr(binding.expression, frame, binding.source);
|
|
76
|
+
else if (binding?.kind === 'ref')
|
|
77
|
+
value = binding.scale * read(binding.input, frame) + binding.offset;
|
|
78
|
+
else if (binding?.kind === 'register') {
|
|
79
|
+
const at = (f) => read(binding.input, finite(binding.freq * f + binding.shift, 'Registration sample frame', binding.source));
|
|
80
|
+
if (name === 'rx' || name === 'ry' || name === 'rz') {
|
|
81
|
+
if (frame !== binding.start)
|
|
82
|
+
value += binding.scale * (at(binding.start) - at(frame));
|
|
83
|
+
}
|
|
84
|
+
else
|
|
85
|
+
value = binding.scale * at(frame) + binding.offset;
|
|
86
|
+
}
|
|
87
|
+
finite(value, path, binding?.source ?? object.source);
|
|
88
|
+
values[name] = isColor(name) ? Math.min(1, Math.max(0, value)) : value;
|
|
89
|
+
}
|
|
90
|
+
const worldPositions = new Map();
|
|
91
|
+
const localMatrices = new Map();
|
|
92
|
+
const worldMatrices = new Map();
|
|
93
|
+
for (const path of plan.order) {
|
|
94
|
+
const positioned = positions.get(path);
|
|
95
|
+
if (positioned) {
|
|
96
|
+
const authored = state.get(positioned);
|
|
97
|
+
const binding = positioned.pathBindings.find(range => active(frame, range));
|
|
98
|
+
let worldPosition;
|
|
99
|
+
if (binding) {
|
|
100
|
+
const vertices = binding.curve.geometry.vertices;
|
|
101
|
+
const index = wrap(Math.floor(finite(binding.freq * frame + binding.shift, 'Path vertex index', binding.source)), vertices.length);
|
|
102
|
+
worldPosition = add(point(worldMatrices.get(binding.curve), vertices[index]), binding.offset);
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
const parent = positioned.parent ? worldMatrices.get(positioned.parent) : identity;
|
|
106
|
+
worldPosition = point(parent, vector(authored.parameters, translations));
|
|
107
|
+
}
|
|
108
|
+
for (const coordinate of worldPosition)
|
|
109
|
+
finite(coordinate, 'Final position', binding?.source ?? positioned.source);
|
|
110
|
+
worldPositions.set(positioned, worldPosition);
|
|
111
|
+
}
|
|
112
|
+
const object = worlds.get(path);
|
|
113
|
+
if (!object)
|
|
114
|
+
continue;
|
|
115
|
+
const authored = state.get(object);
|
|
116
|
+
const parent = object.parent ? worldMatrices.get(object.parent) : identity;
|
|
117
|
+
const sizes = vector(authored.parameters, scales);
|
|
118
|
+
const binding = object.aimBindings.find(range => active(frame, range));
|
|
119
|
+
let axes = euler(vector(authored.parameters, rotations));
|
|
120
|
+
if (binding) {
|
|
121
|
+
if (object.kind === 'light' && authored.light !== 'spot') {
|
|
122
|
+
fail('invalid-lookat-subject', 'Only spotlights may use lookat', binding.source);
|
|
123
|
+
}
|
|
124
|
+
const up = object.kind === 'camera' ? authored.up : worldUp;
|
|
125
|
+
const forward = object.kind === 'camera' || object.kind === 'light' ? -1 : 1;
|
|
126
|
+
axes = aim(parent, worldPositions.get(object), worldPositions.get(binding.target), up, forward, sizes, binding.source) ?? axes;
|
|
127
|
+
}
|
|
128
|
+
const pathBinding = object.pathBindings.find(range => active(frame, range));
|
|
129
|
+
const localPosition = pathBinding
|
|
130
|
+
? inverseDirection(parent, sub(worldPositions.get(object), column(parent, 3)), pathBinding.source)
|
|
131
|
+
: vector(authored.parameters, translations);
|
|
132
|
+
const local = authored.matrix ?? matrix(localPosition, axes, sizes);
|
|
133
|
+
const world = multiply(parent, local);
|
|
134
|
+
for (const component of [...local, ...world])
|
|
135
|
+
finite(component, 'Final matrix component', binding?.source ?? object.source);
|
|
136
|
+
localMatrices.set(object, local);
|
|
137
|
+
worldMatrices.set(object, world);
|
|
138
|
+
}
|
|
139
|
+
const objects = plan.objects.map(object => {
|
|
140
|
+
const authored = state.get(object);
|
|
141
|
+
const p = authored.parameters;
|
|
142
|
+
const localMatrix = localMatrices.get(object), worldMatrix = worldMatrices.get(object);
|
|
143
|
+
const snapshot = {
|
|
144
|
+
path: objectPath(object), kind: object.kind, ...(object.parent && { parent: objectPath(object.parent) }),
|
|
145
|
+
localMatrix, worldMatrix, parameters: p, visible: authored.visible,
|
|
146
|
+
...(object.geometry && { geometry: object.geometry }),
|
|
147
|
+
...(Object.hasOwn(p, 'diffr') && { material: {
|
|
148
|
+
diffuse: [p.diffr, p.diffg, p.diffb, p.diffa], ambient: [p.ambr, p.ambg, p.ambb, p.amba],
|
|
149
|
+
specular: [p.specr, p.specg, p.specb, p.speca], ...(p.shine !== undefined && { shininess: p.shine }),
|
|
150
|
+
} }),
|
|
151
|
+
...(object.kind === 'camera' && { camera: {
|
|
152
|
+
position: column(worldMatrix, 3), direction: normalize(scale(column(worldMatrix, 2), -1)),
|
|
153
|
+
up: normalize(column(worldMatrix, 1)), fovy: p.fovy, znear: p.znear, zfar: p.zfar,
|
|
154
|
+
} }),
|
|
155
|
+
...(object.kind === 'light' && { light: {
|
|
156
|
+
kind: authored.light, enabled: authored.enabled, position: column(worldMatrix, 3),
|
|
157
|
+
direction: normalize(scale(column(worldMatrix, 2), -1)),
|
|
158
|
+
} }),
|
|
159
|
+
};
|
|
160
|
+
return snapshot;
|
|
161
|
+
});
|
|
162
|
+
return freeze({ frame, time, fps, objects, channels, cameras: objects.filter(o => o.kind === 'camera'),
|
|
163
|
+
lights: objects.filter(o => o.kind === 'light') });
|
|
164
|
+
}
|
|
@@ -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,83 @@
|
|
|
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.steps.set(path, { node: { name: graphName(path), context, type, props, inputs: [],
|
|
19
|
+
outputs: [{ name: 'value', type: portType }] }, dependencies: new Set(), source });
|
|
20
|
+
}
|
|
21
|
+
depend(to, on) {
|
|
22
|
+
this.steps.get(to).dependencies.add(on);
|
|
23
|
+
}
|
|
24
|
+
finish() {
|
|
25
|
+
const paths = [...this.steps.keys()].sort(comparePaths);
|
|
26
|
+
const counts = new Map();
|
|
27
|
+
const readers = new Map();
|
|
28
|
+
for (const path of paths) {
|
|
29
|
+
const { dependencies } = this.steps.get(path);
|
|
30
|
+
counts.set(path, dependencies.size);
|
|
31
|
+
for (const dependency of dependencies) {
|
|
32
|
+
const list = readers.get(dependency) ?? [];
|
|
33
|
+
list.push(path);
|
|
34
|
+
readers.set(dependency, list);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
const ready = paths.filter(path => !counts.get(path)).reverse();
|
|
38
|
+
const order = [];
|
|
39
|
+
while (ready.length) {
|
|
40
|
+
const path = ready.pop();
|
|
41
|
+
order.push(path);
|
|
42
|
+
for (const reader of readers.get(path) ?? []) {
|
|
43
|
+
const count = counts.get(reader) - 1;
|
|
44
|
+
counts.set(reader, count);
|
|
45
|
+
if (!count) {
|
|
46
|
+
let left = 0, right = ready.length;
|
|
47
|
+
while (left < right) {
|
|
48
|
+
const mid = (left + right) >>> 1;
|
|
49
|
+
if (comparePaths(ready[mid], reader) > 0)
|
|
50
|
+
left = mid + 1;
|
|
51
|
+
else
|
|
52
|
+
right = mid;
|
|
53
|
+
}
|
|
54
|
+
ready.splice(left, 0, reader);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (order.length !== paths.length) {
|
|
59
|
+
const chain = [];
|
|
60
|
+
const indices = new Map();
|
|
61
|
+
let path = paths.find(path => counts.get(path) > 0);
|
|
62
|
+
while (!indices.has(path)) {
|
|
63
|
+
indices.set(path, chain.length);
|
|
64
|
+
chain.push(path);
|
|
65
|
+
path = [...this.steps.get(path).dependencies].filter(dep => counts.get(dep) > 0).sort(comparePaths)[0];
|
|
66
|
+
}
|
|
67
|
+
const cycle = [...chain.slice(indices.get(path)), path];
|
|
68
|
+
fail('dependency-cycle', 'Dependency cycle: ' + cycle.join(' -> '), this.steps.get(path).source, cycle);
|
|
69
|
+
}
|
|
70
|
+
const edges = [];
|
|
71
|
+
const nodes = paths.map(path => {
|
|
72
|
+
const { node, dependencies } = this.steps.get(path);
|
|
73
|
+
const inputs = [...dependencies].sort(comparePaths).map(dep => {
|
|
74
|
+
const source = this.steps.get(dep).node;
|
|
75
|
+
const output = source.outputs[0];
|
|
76
|
+
edges.push({ src: { node: source.name, port: output.name }, dst: { node: node.name, port: source.name } });
|
|
77
|
+
return { name: source.name, type: output.type };
|
|
78
|
+
});
|
|
79
|
+
return { ...node, inputs };
|
|
80
|
+
});
|
|
81
|
+
return { order, graph: { name: 'scene', nodes, edges } };
|
|
82
|
+
}
|
|
83
|
+
}
|
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
|
+
]);
|