@indispec/fs-compat 0.0.0-stage → 0.1.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.
@@ -0,0 +1,211 @@
1
+ // Feature execution trace.
2
+ //
3
+ // A FeatureScript program is a general program: helpers, loops and conditionals build
4
+ // features as a side effect. The *feature history* a user sees in a CAD editor is the
5
+ // ordered log of those invocations, which the AST cannot tell you statically (`for` loops
6
+ // and computed ids only exist at runtime). The interpreter therefore records one entry per
7
+ // feature-producing call: its runtime id path, the source span of the call, the call frames
8
+ // that produced it, a serialised snapshot of its definition, and how many bodies it created.
9
+ //
10
+ // This module is pure: no interpreter imports, so it is safe to use from the worker and in
11
+ // unit tests. `docs/CAD.md` §7 lists the derived-vs-authored rule this follows — a trace is
12
+ // derived per evaluation and never persisted.
13
+
14
+ /** A source location range in one file. `end` is exclusive. */
15
+ export class Span {
16
+ /**
17
+ * @param {number} start Absolute character offset of the first token.
18
+ * @param {number} end Absolute character offset after the last token.
19
+ * @param {number} line 1-based line of `start`.
20
+ * @param {string} [file] Source name (module, library or document path).
21
+ */
22
+ constructor(start, end, line, file = 'module') {
23
+ this.start = start;
24
+ this.end = end;
25
+ this.line = line;
26
+ this.file = file;
27
+ }
28
+ }
29
+
30
+ /** A call frame in the program stack that led to a feature invocation. */
31
+ export class TraceFrame {
32
+ /**
33
+ * @param {string} callee Name of the called function (`annZ`, `cylZ`, …).
34
+ * @param {Span} span Span of the call expression itself.
35
+ * @param {string|null} id Runtime `Id` passed to the callee, when it took one.
36
+ */
37
+ constructor(callee, span, id = null) {
38
+ this.callee = callee;
39
+ this.span = span;
40
+ this.id = id;
41
+ }
42
+ }
43
+
44
+ /** One recorded feature invocation. */
45
+ export class TraceEntry {
46
+ /**
47
+ * @param {object} init Entry fields (see the field JSDoc below).
48
+ */
49
+ constructor(init) {
50
+ /** Monotonic sequence number (execution order). */
51
+ this.seq = init.seq;
52
+ /** Builtin/host operation name, e.g. `opExtrude`, `instance`. */
53
+ this.op = init.op;
54
+ /** History class: `sketch | op | modifier | property | report | instance | import | feature`. */
55
+ this.kind = init.kind;
56
+ /** Full runtime id string, e.g. `feature/outer/o/ex` (null when the call had no id). */
57
+ this.id = init.id;
58
+ /** `id` split into path segments; the tree nests by prefix. */
59
+ this.path = init.path;
60
+ /** Span of the call expression in the source. */
61
+ this.span = init.span;
62
+ /** Program stack frames (outermost first) that led here. */
63
+ this.frames = init.frames;
64
+ /** Serialised definition map (JSON-safe), or null for calls without one. */
65
+ this.definition = init.definition;
66
+ /** Bodies created by this invocation (registry delta for its id). */
67
+ this.produced = init.produced;
68
+ /** Live body count after the invocation — enough to reconstruct a rollback bar. */
69
+ this.bodies = init.bodies;
70
+ }
71
+ }
72
+
73
+ /**
74
+ * Classify a builtin call into a feature-history kind.
75
+ *
76
+ * Queries, math and vector helpers are not features and are deliberately excluded: the
77
+ * history is the log of things that change the model, not of every function call.
78
+ *
79
+ * @param {string} name Builtin/host operation name.
80
+ * @returns {string|null} History kind, or null when the call is not a feature.
81
+ */
82
+ export function classifyBuiltin(name) {
83
+ switch (name) {
84
+ case 'opBoolean':
85
+ case 'opTransform':
86
+ case 'opDeleteBodies':
87
+ return 'modifier';
88
+ case 'setProperty':
89
+ return 'property';
90
+ case 'reportFeatureInfo':
91
+ case 'reportFeatureWarning':
92
+ case 'reportFeatureError':
93
+ return 'report';
94
+ case 'newSketchOnPlane':
95
+ case 'newSketch':
96
+ return 'sketch';
97
+ case 'instance':
98
+ return 'instance';
99
+ case 'importStep':
100
+ case 'importAsset':
101
+ return 'import';
102
+ case 'defineFeature':
103
+ case 'defineAssembly':
104
+ return null;
105
+ default:
106
+ return name.startsWith('op') ? 'op' : null;
107
+ }
108
+ }
109
+
110
+ const MAX_SERIALIZE_DEPTH = 4;
111
+
112
+ /**
113
+ * Convert a FeatureScript runtime value into a JSON-safe display value.
114
+ *
115
+ * Quantities become `{ value, dim }`, vectors become arrays, ids become strings and maps
116
+ * become plain objects. The trace is a UI/debug artifact, so unknown values degrade to a
117
+ * constructor name rather than throwing.
118
+ *
119
+ * @param {unknown} value Runtime value.
120
+ * @param {number} [depth] Current recursion depth (internal).
121
+ * @returns {unknown} JSON-serialisable snapshot.
122
+ */
123
+ export function serializeValue(value, depth = 0) {
124
+ if (value === null || value === undefined) return null;
125
+ if (typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean') return value;
126
+ if (depth >= MAX_SERIALIZE_DEPTH) return '…';
127
+ const name = value?.constructor?.name;
128
+ if (name === 'Q') return { value: value.v, dim: value.dim };
129
+ if (name === 'Vec') return Array.from(value.c ?? value, (c) => (c && typeof c === 'object' && 'v' in c ? c.v : c));
130
+ if (name === 'Id') return value.toString();
131
+ if (Array.isArray(value)) return value.map((item) => serializeValue(item, depth + 1));
132
+ if (value instanceof Map) {
133
+ /** @type {Record<string, unknown>} */
134
+ const out = {};
135
+ for (const [key, item] of value.entries()) out[String(key)] = serializeValue(item, depth + 1);
136
+ return out;
137
+ }
138
+ if (name === 'Xf') return { m: value.m, t: value.t };
139
+ if (name === 'Sel') return { solids: value.solids?.length ?? 0 };
140
+ if (typeof value === 'object') return { type: name ?? 'object' };
141
+ return String(value);
142
+ }
143
+
144
+ /**
145
+ * Span of an AST node, falling back to a line-only span for nodes the parser did not stamp.
146
+ *
147
+ * @param {{start?: number, end?: number, line?: number}} node AST node.
148
+ * @param {string} [file] Source name for the span.
149
+ * @returns {Span} Source span.
150
+ */
151
+ export function spanOf(node, file = 'module') {
152
+ return new Span(node?.start ?? 0, node?.end ?? 0, node?.line ?? 0, file);
153
+ }
154
+
155
+ /** Records the feature history of one evaluation. */
156
+ export class Tracer {
157
+ /**
158
+ * @param {{ file?: string }} [options] Tracer options.
159
+ */
160
+ constructor({ file = 'module' } = {}) {
161
+ /** @type {TraceFrame[]} */
162
+ this.frames = [];
163
+ /** @type {TraceEntry[]} */
164
+ this.entries = [];
165
+ this.file = file;
166
+ this.seq = 0;
167
+ }
168
+
169
+ /**
170
+ * Push a call frame (a user function invocation).
171
+ *
172
+ * @param {TraceFrame} frame Frame to push.
173
+ */
174
+ pushFrame(frame) {
175
+ this.frames.push(frame);
176
+ }
177
+
178
+ /** Pop the innermost call frame. */
179
+ popFrame() {
180
+ this.frames.pop();
181
+ }
182
+
183
+ /**
184
+ * Record one feature invocation.
185
+ *
186
+ * @param {object} entry Fields for {@link TraceEntry}; `seq` and `frames` are filled here.
187
+ * @returns {TraceEntry} The recorded entry.
188
+ */
189
+ record(entry) {
190
+ this.seq += 1;
191
+ const id = entry.id ?? null;
192
+ const record = new TraceEntry({
193
+ ...entry,
194
+ seq: this.seq,
195
+ id,
196
+ path: id ? id.split('/') : [],
197
+ frames: this.frames.slice(),
198
+ });
199
+ this.entries.push(record);
200
+ return record;
201
+ }
202
+
203
+ /**
204
+ * The recorded history, as plain JSON.
205
+ *
206
+ * @returns {TraceEntry[]} Entries in execution order.
207
+ */
208
+ toJSON() {
209
+ return this.entries;
210
+ }
211
+ }
@@ -0,0 +1,494 @@
1
+ // FeatureScript value model.
2
+ //
3
+ // Everything geometric is carried in millimetres; angles in radians. A Q
4
+ // (quantity) is a magnitude plus dimension exponents, reproducing
5
+ // FeatureScript's "ValueWithUnits" arithmetic: mm*mm is an area, mm/mm is
6
+ // a plain number, sin() only looks at the magnitude of a radian quantity.
7
+ //
8
+ // Plain ESM, zero dependencies: runs under node and bundles for the browser.
9
+ // numpy is replaced with plain JS arrays (3x3 row-major matrices, [x,y,z]).
10
+
11
+ export const LEN = [1, 0]; // millimetre
12
+ export const ANG = [0, 1]; // radian
13
+ export const ONE = [0, 0];
14
+
15
+ export class FsError extends Error {
16
+ constructor(message, line = null, col = null, source = null) {
17
+ const loc = line ? ` (line ${line})` : '';
18
+ super(`${source ? source + ': ' : ''}${message}${loc}`);
19
+ this.name = 'FsError';
20
+ this.line = line;
21
+ this.col = col;
22
+ this.source = source;
23
+ }
24
+ }
25
+
26
+ // -- small helpers -----------------------------------------------------------
27
+
28
+ function dimEq(a, b) {
29
+ return a[0] === b[0] && a[1] === b[1];
30
+ }
31
+
32
+ // str() of a Python dim tuple, e.g. "(1, 0)" — used inside error messages.
33
+ function dimStr(d) {
34
+ return `(${d[0]}, ${d[1]})`;
35
+ }
36
+
37
+ // Mirror of Python str(float): '1.0', '0.001', '1e-05', '1e+16', 'inf', 'nan'.
38
+ function pyFloatStr(v) {
39
+ if (Number.isNaN(v)) return 'nan';
40
+ if (!Number.isFinite(v)) return v > 0 ? 'inf' : '-inf';
41
+ if (v === 0) return Object.is(v, -0) ? '-0.0' : '0.0';
42
+ const a = Math.abs(v);
43
+ if (a >= 1e16 || a < 1e-4) {
44
+ const m = v.toExponential().match(/^(-?)(\d+(?:\.\d+)?)[eE]([+-])(\d+)$/);
45
+ return m[1] + m[2] + 'e' + m[3] + (m[4].length < 2 ? '0' + m[4] : m[4]);
46
+ }
47
+ let s = String(v);
48
+ if (!s.includes('.')) s += '.0';
49
+ return s;
50
+ }
51
+
52
+ // Mirror of Python round(v, 6) then str(): used by Q.toString().
53
+ function round6str(v) {
54
+ const a = Math.round(Math.abs(v) * 1e6) / 1e6;
55
+ return pyFloatStr(v < 0 ? -a : a);
56
+ }
57
+
58
+ // type(x).__name__-ish for asQ's error message.
59
+ function typeName(x) {
60
+ if (x === null || x === undefined) return 'NoneType';
61
+ if (typeof x === 'string') return 'str';
62
+ if (Array.isArray(x)) return 'list';
63
+ if (typeof x === 'boolean') return 'bool';
64
+ if (typeof x === 'number') return 'float';
65
+ if (typeof x === 'object') {
66
+ if (x.constructor && x.constructor.name !== 'Object') return x.constructor.name;
67
+ return 'dict';
68
+ }
69
+ return typeof x;
70
+ }
71
+
72
+ // -- Q ------------------------------------------------------------------------
73
+
74
+ export class Q {
75
+ // A FeatureScript quantity: value (in base units) + dimension exponents.
76
+ constructor(v, dim = ONE) {
77
+ this.v = Number(v);
78
+ this.dim = dim;
79
+ }
80
+
81
+ // construction helpers
82
+ get isLen() {
83
+ return dimEq(this.dim, LEN);
84
+ }
85
+ get isAng() {
86
+ return dimEq(this.dim, ANG);
87
+ }
88
+ get isPlain() {
89
+ return dimEq(this.dim, ONE);
90
+ }
91
+ mm() {
92
+ // Magnitude as millimetres (only meaningful for lengths/plain).
93
+ return this.v;
94
+ }
95
+ rad() {
96
+ return this.v;
97
+ }
98
+
99
+ // arithmetic
100
+ add(o) {
101
+ o = asQ(o);
102
+ if (!dimEq(this.dim, o.dim)) {
103
+ throw new FsError(`cannot add ${dimStr(this.dim)} to ${dimStr(o.dim)}`);
104
+ }
105
+ return new Q(this.v + o.v, this.dim);
106
+ }
107
+
108
+ sub(o) {
109
+ o = asQ(o);
110
+ if (!dimEq(this.dim, o.dim)) {
111
+ throw new FsError(`cannot subtract ${dimStr(o.dim)} from ${dimStr(this.dim)}`);
112
+ }
113
+ return new Q(this.v - o.v, this.dim);
114
+ }
115
+
116
+ mul(o) {
117
+ if (o instanceof Vec) return o.mul(this);
118
+ o = asQ(o);
119
+ return new Q(this.v * o.v, [this.dim[0] + o.dim[0], this.dim[1] + o.dim[1]]);
120
+ }
121
+
122
+ div(o) {
123
+ o = asQ(o);
124
+ return new Q(this.v / o.v, [this.dim[0] - o.dim[0], this.dim[1] - o.dim[1]]);
125
+ }
126
+
127
+ neg() {
128
+ return new Q(-this.v, this.dim);
129
+ }
130
+
131
+ // comparison
132
+ #cmp(o) {
133
+ o = asQ(o);
134
+ if (!dimEq(this.dim, o.dim)) {
135
+ throw new FsError(`cannot compare ${dimStr(this.dim)} with ${dimStr(o.dim)}`);
136
+ }
137
+ return [this.v, o.v];
138
+ }
139
+
140
+ eq(o) {
141
+ let a, b;
142
+ try {
143
+ [a, b] = this.#cmp(o);
144
+ } catch (e) {
145
+ if (e instanceof FsError) return false;
146
+ throw e;
147
+ }
148
+ return Math.abs(a - b) <= 1e-12 * Math.max(Math.abs(a), Math.abs(b)) + 1e-12;
149
+ }
150
+
151
+ ne(o) {
152
+ return !this.eq(o);
153
+ }
154
+
155
+ lt(o) {
156
+ const [a, b] = this.#cmp(o);
157
+ return a < b;
158
+ }
159
+
160
+ le(o) {
161
+ const [a, b] = this.#cmp(o);
162
+ return a <= b;
163
+ }
164
+
165
+ gt(o) {
166
+ const [a, b] = this.#cmp(o);
167
+ return a > b;
168
+ }
169
+
170
+ ge(o) {
171
+ const [a, b] = this.#cmp(o);
172
+ return a >= b;
173
+ }
174
+
175
+ // Python __hash__ equivalent: rounded key (handy for Map/Set use).
176
+ key() {
177
+ return `${Math.round(this.v * 1e9) / 1e9}|${dimStr(this.dim)}`;
178
+ }
179
+
180
+ // Python __repr__: f"{round(self.v, 6)}{unit}"
181
+ toString() {
182
+ const unit = dimEq(this.dim, LEN) ? 'mm' : dimEq(this.dim, ANG) ? 'rad' : dimEq(this.dim, ONE) ? '' : dimStr(this.dim);
183
+ return `${round6str(this.v)}${unit}`;
184
+ }
185
+ }
186
+
187
+ export function asQ(x) {
188
+ if (x instanceof Q) return x;
189
+ if (typeof x === 'boolean') throw new FsError('boolean is not a number');
190
+ if (typeof x === 'number') return new Q(x);
191
+ throw new FsError(`expected a number, got ${typeName(x)}`);
192
+ }
193
+
194
+ export function num(x) {
195
+ // Plain JS number from a dimensionless quantity or number.
196
+ if (x instanceof Q) {
197
+ if (!dimEq(x.dim, ONE)) {
198
+ throw new FsError(`expected a plain number, got ${x}`);
199
+ }
200
+ return x.v;
201
+ }
202
+ return Number(x);
203
+ }
204
+
205
+ // -- Vec ----------------------------------------------------------------------
206
+
207
+ export class Vec {
208
+ // A 2D or 3D vector of quantities (FeatureScript `vector()`).
209
+ constructor(comps) {
210
+ this.c = Array.from(comps, (c) => asQ(c));
211
+ }
212
+
213
+ length() {
214
+ return this.c.length;
215
+ }
216
+
217
+ get(i) {
218
+ return this.c[i < 0 ? this.c.length + i : i];
219
+ }
220
+
221
+ add(o) {
222
+ if (this.c.length !== o.c.length) throw new FsError('vector size mismatch');
223
+ return new Vec(this.c.map((a, k) => a.add(o.c[k])));
224
+ }
225
+
226
+ sub(o) {
227
+ if (this.c.length !== o.c.length) throw new FsError('vector size mismatch');
228
+ return new Vec(this.c.map((a, k) => a.sub(o.c[k])));
229
+ }
230
+
231
+ neg() {
232
+ return new Vec(this.c.map((a) => a.neg()));
233
+ }
234
+
235
+ mul(s) {
236
+ s = asQ(s);
237
+ return new Vec(this.c.map((a) => a.mul(s)));
238
+ }
239
+
240
+ div(s) {
241
+ s = asQ(s);
242
+ return new Vec(this.c.map((a) => a.div(s)));
243
+ }
244
+
245
+ dot(o) {
246
+ // Mirrors Python sum((a*b ...), Q(0)): raises on dimension mismatch.
247
+ const n = Math.min(this.c.length, o.c.length);
248
+ let acc = new Q(0);
249
+ for (let k = 0; k < n; k++) acc = acc.add(this.c[k].mul(o.c[k]));
250
+ return acc;
251
+ }
252
+
253
+ cross(o) {
254
+ if (this.c.length !== 3) throw new FsError('cross product needs 3D vectors');
255
+ const a = this.c;
256
+ const b = o.c;
257
+ return new Vec([
258
+ a[1].mul(b[2]).sub(a[2].mul(b[1])),
259
+ a[2].mul(b[0]).sub(a[0].mul(b[2])),
260
+ a[0].mul(b[1]).sub(a[1].mul(b[0])),
261
+ ]);
262
+ }
263
+
264
+ norm() {
265
+ let s = 0;
266
+ for (const c of this.c) s += c.v * c.v;
267
+ return Math.sqrt(s);
268
+ }
269
+
270
+ normalized() {
271
+ const n = this.norm();
272
+ if (n === 0) throw new FsError('cannot normalize a zero vector');
273
+ return new Vec(this.c.map((c) => new Q(c.v / n, c.dim)));
274
+ }
275
+
276
+ comps() {
277
+ return this.c.map((c) => c.v);
278
+ }
279
+
280
+ dims() {
281
+ const seen = new Set();
282
+ for (const c of this.c) seen.add(dimStr(c.dim));
283
+ return [...seen];
284
+ }
285
+
286
+ toString() {
287
+ return 'vector(' + this.c.map((c) => c.toString()).join(', ') + ')';
288
+ }
289
+ }
290
+
291
+ export function vec3mm(v, what = 'vector') {
292
+ // Plain [x, y, z] in mm from a Vec of lengths (or plain numbers).
293
+ if (!(v instanceof Vec) || v.length() !== 3) {
294
+ throw new FsError(`${what} must be a 3D vector`);
295
+ }
296
+ return [v.c[0].v, v.c[1].v, v.c[2].v];
297
+ }
298
+
299
+ export function vec2mm(v, what = 'point') {
300
+ if (!(v instanceof Vec) || v.length() !== 2) {
301
+ throw new FsError(`${what} must be a 2D vector`);
302
+ }
303
+ return [v.c[0].v, v.c[1].v];
304
+ }
305
+
306
+ // -- Id -----------------------------------------------------------------------
307
+
308
+ export class Id {
309
+ // FeatureScript `Id`: an ordered path of string components.
310
+ constructor(parts = []) {
311
+ this.parts = Array.from(parts, (p) => String(p));
312
+ }
313
+
314
+ add(other) {
315
+ if (other instanceof Id) return new Id([...this.parts, ...other.parts]);
316
+ return new Id([...this.parts, String(other)]);
317
+ }
318
+
319
+ toString() {
320
+ return this.parts.join('/');
321
+ }
322
+ }
323
+
324
+ // -- Xf -----------------------------------------------------------------------
325
+
326
+ function identity3() {
327
+ return [
328
+ [1, 0, 0],
329
+ [0, 1, 0],
330
+ [0, 0, 1],
331
+ ];
332
+ }
333
+
334
+ function matVec(m, v) {
335
+ // (m @ v)[i] = sum_k m[i][k] * v[k] — m is 3x3 row-major, v length 3.
336
+ const out = new Array(3);
337
+ for (let i = 0; i < 3; i++) out[i] = m[i][0] * v[0] + m[i][1] * v[1] + m[i][2] * v[2];
338
+ return out;
339
+ }
340
+
341
+ function matMul(a, b) {
342
+ const out = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
343
+ for (let i = 0; i < 3; i++) {
344
+ for (let j = 0; j < 3; j++) {
345
+ let s = 0;
346
+ for (let k = 0; k < 3; k++) s += a[i][k] * b[k][j];
347
+ out[i][j] = s;
348
+ }
349
+ }
350
+ return out;
351
+ }
352
+
353
+ function transpose3(m) {
354
+ return [
355
+ [m[0][0], m[1][0], m[2][0]],
356
+ [m[0][1], m[1][1], m[2][1]],
357
+ [m[0][2], m[1][2], m[2][2]],
358
+ ];
359
+ }
360
+
361
+ const isFlatPoint = (P) => !Array.isArray(P[0]);
362
+
363
+ export class Xf {
364
+ // A rigid transform: 3x3 rotation (row-major) + translation (mm).
365
+ constructor(m = identity3(), t = [0, 0, 0]) {
366
+ this.m = m;
367
+ this.t = t;
368
+ }
369
+
370
+ // P: array of points [[x,y,z],...] → transformed points (P @ m^T + t).
371
+ // A single flat point [x,y,z] is also accepted and returns a flat point.
372
+ apply(P) {
373
+ const flat = isFlatPoint(P);
374
+ const rows = flat ? [P] : P;
375
+ const out = rows.map((p) => {
376
+ const r = [
377
+ p[0] * this.m[0][0] + p[1] * this.m[0][1] + p[2] * this.m[0][2] + this.t[0],
378
+ p[0] * this.m[1][0] + p[1] * this.m[1][1] + p[2] * this.m[1][2] + this.t[1],
379
+ p[0] * this.m[2][0] + p[1] * this.m[2][1] + p[2] * this.m[2][2] + this.t[2],
380
+ ];
381
+ return r;
382
+ });
383
+ return flat ? out[0] : out;
384
+ }
385
+
386
+ // Rotation only: V is an array of direction vectors (or one flat vector).
387
+ applyDir(V) {
388
+ const flat = isFlatPoint(V);
389
+ const rows = flat ? [V] : V;
390
+ const out = rows.map((v) => [
391
+ v[0] * this.m[0][0] + v[1] * this.m[0][1] + v[2] * this.m[0][2],
392
+ v[0] * this.m[1][0] + v[1] * this.m[1][1] + v[2] * this.m[1][2],
393
+ v[0] * this.m[2][0] + v[1] * this.m[2][1] + v[2] * this.m[2][2],
394
+ ]);
395
+ return flat ? out[0] : out;
396
+ }
397
+
398
+ inverse() {
399
+ const mi = transpose3(this.m);
400
+ return new Xf(mi, matVec(mi, [-this.t[0], -this.t[1], -this.t[2]]));
401
+ }
402
+
403
+ // Python a @ b: result.apply(P) === a.apply(b.apply(P)).
404
+ compose(o) {
405
+ return new Xf(matMul(this.m, o.m), addV(matVec(this.m, o.t), this.t));
406
+ }
407
+ }
408
+
409
+ function addV(a, b) {
410
+ return [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
411
+ }
412
+
413
+ export function rotationMatrix(axis, angleRad) {
414
+ const ax = axis[0];
415
+ const ay = axis[1];
416
+ const az = axis[2];
417
+ const n = Math.sqrt(ax * ax + ay * ay + az * az);
418
+ if (n === 0) return identity3();
419
+ const x = ax / n;
420
+ const y = ay / n;
421
+ const z = az / n;
422
+ const c = Math.cos(angleRad);
423
+ const s = Math.sin(angleRad);
424
+ const C = 1 - c;
425
+ return [
426
+ [c + x * x * C, x * y * C - z * s, x * z * C + y * s],
427
+ [y * x * C + z * s, c + y * y * C, y * z * C - x * s],
428
+ [z * x * C - y * s, z * y * C + x * s, c + z * z * C],
429
+ ];
430
+ }
431
+
432
+ // -- Plane --------------------------------------------------------------------
433
+
434
+ function norm3(v) {
435
+ return Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
436
+ }
437
+
438
+ function cross3(a, b) {
439
+ return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
440
+ }
441
+
442
+ function dot3(a, b) {
443
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
444
+ }
445
+
446
+ export class Plane {
447
+ // A sketch plane: origin + orthonormal u/v (in-plane) and n (normal).
448
+ constructor(origin, u, n) {
449
+ this.o = [origin[0], origin[1], origin[2]];
450
+ const un = norm3(u);
451
+ const nn = norm3(n);
452
+ this.u = [u[0] / un, u[1] / un, u[2] / un];
453
+ this.n = [n[0] / nn, n[1] / nn, n[2] / nn];
454
+ this.v = cross3(this.n, this.u);
455
+ }
456
+
457
+ // World points (array of [x,y,z], or one flat point) → plane coords (u, v, w).
458
+ toLocal(P) {
459
+ const flat = isFlatPoint(P);
460
+ const rows = flat ? [P] : P;
461
+ const out = rows.map((p) => {
462
+ const d = [p[0] - this.o[0], p[1] - this.o[1], p[2] - this.o[2]];
463
+ return [dot3(d, this.u), dot3(d, this.v), dot3(d, this.n)];
464
+ });
465
+ return flat ? out[0] : out;
466
+ }
467
+
468
+ // Plane coords (array of [u,v,w], or one flat triple) → world points.
469
+ toWorld(L) {
470
+ const flat = isFlatPoint(L);
471
+ const rows = flat ? [L] : L;
472
+ const out = rows.map((l) => [
473
+ this.o[0] + l[0] * this.u[0] + l[1] * this.v[0] + l[2] * this.n[0],
474
+ this.o[1] + l[0] * this.u[1] + l[1] * this.v[1] + l[2] * this.n[1],
475
+ this.o[2] + l[0] * this.u[2] + l[1] * this.v[2] + l[2] * this.n[2],
476
+ ]);
477
+ return flat ? out[0] : out;
478
+ }
479
+ }
480
+
481
+ // -- Color --------------------------------------------------------------------
482
+
483
+ export class Color {
484
+ constructor(r, g, b, a = 1) {
485
+ this.r = r;
486
+ this.g = g;
487
+ this.b = b;
488
+ this.a = a;
489
+ }
490
+
491
+ rgb() {
492
+ return [this.r, this.g, this.b];
493
+ }
494
+ }