@indispec/fs-compat 0.0.0-stage → 0.1.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.
@@ -0,0 +1,1713 @@
1
+ /**
2
+ * interp.js — the FeatureScript interpreter for this subset.
3
+ *
4
+ * Evaluator for the FeatureScript subset, wired to the SDF/CSG kernel in
5
+ * csg.js. Run a module and call one of its custom features:
6
+ *
7
+ * const { interp, feature, definition } = runFeature(source, 'feature')
8
+ *
9
+ * Semantics are fixed by the engine contract (and the conformance suite):
10
+ * ids are paths and every operation registers its result under its own id;
11
+ * booleans mutate the target body in place and consume the tools;
12
+ * opPattern/opTransform add rigid copies; setProperty NAME/APPEARANCE attach
13
+ * the name and colour used when rendering.
14
+ *
15
+ * FS maps are JS Maps (insertion order matters for defaults), FS arrays are
16
+ * JS arrays, quantities are Q, vectors are Vec, transforms are Xf.
17
+ */
18
+
19
+ import {
20
+ ANG, LEN, ONE, FsError, Q, Vec, Id, Plane, Xf, Color, num,
21
+ rotationMatrix, vec3mm, vec2mm,
22
+ } from './values.js'
23
+ import {
24
+ Circle2, Poly2, Rect2, Prism, Revolve, Union, Diff, Isect, Moved, Fillet, Chamfer, Shell, Loft, Sweep,
25
+ FaceExtrude, Solid, Scene,
26
+ } from './csg.js'
27
+ import { arcPoints, chainContours, nestProfiles, sketchRegions, toCCW } from './regions.js'
28
+ import { parse } from './parse.js'
29
+ import { Tracer, classifyBuiltin, serializeValue, spanOf } from './trace.js'
30
+ import { AssemblyScene, materialFromValue, pipeFromValue, terrainFromValue, transformFromValue } from './assembly.js'
31
+
32
+ /** Thrown to stop evaluation at a rollback point (docs/CAD.md §10: feature rollback). */
33
+ export class RollbackSignal extends Error {
34
+ constructor(seq) {
35
+ super('rollback')
36
+ this.seq = seq
37
+ }
38
+ }
39
+
40
+ // ---------------------------------------------------------------------------
41
+ // runtime helpers
42
+ // ---------------------------------------------------------------------------
43
+
44
+ export class Sel {
45
+ /**
46
+ * A query result: bodies, whole sketches, and/or faces (sketch regions or body faces).
47
+ *
48
+ * `faces` entries are either `{ sketch, region }`, where `region` is one entry of the sketch's
49
+ * `allRegions` (see `regions.js` `sketchRegions`), or a {@link SolidFace} — a planar face of a
50
+ * solid addressed by a geometric anchor (`qPlanarFaceAt`). A face selection is what lets an
51
+ * extrude target "the face between two nested contours" of a sketch, or a face of an existing
52
+ * body, instead of a whole sketch.
53
+ */
54
+ constructor(solids = [], sketches = [], faces = []) {
55
+ this.solids = [...solids]
56
+ this.sketches = [...sketches]
57
+ this.faces = [...faces]
58
+ }
59
+ }
60
+
61
+ /**
62
+ * One planar face of a solid body, addressed by a geometric anchor.
63
+ *
64
+ * The engine records the owning body plus a world point on the face and its outward normal; the
65
+ * exact kernel resolves the B-rep face when the body is translated (the `FaceExtrude` node). Face
66
+ * ids are only valid within one evaluation, so an anchor — not an index — is what a program keeps
67
+ * (docs/CAD.md §7.3).
68
+ */
69
+ export class SolidFace {
70
+ /**
71
+ * @param {object} solid Owning body.
72
+ * @param {number[]} point World point on the face (mm).
73
+ * @param {number[]} normal Outward unit normal of the face at the anchor.
74
+ */
75
+ constructor(solid, point, normal) {
76
+ this.solid = solid
77
+ this.point = [point[0], point[1], point[2]]
78
+ this.normal = [normal[0], normal[1], normal[2]]
79
+ }
80
+ }
81
+
82
+
83
+ export class Sketch {
84
+ constructor(plane) {
85
+ this.plane = plane
86
+ this.entities = []
87
+ /** Legacy flat profile list (what `opRevolve` spins). */
88
+ this.profiles = null
89
+ /** Closed 2D regions with holes (what `opExtrude` builds solids from). */
90
+ this.regions = null
91
+ /**
92
+ * Every face of the sketch's planar subdivision (`sketchRegions`), in the canonical
93
+ * `qNthElement` order: the ring between two nested circles is one face, the inner disc is the
94
+ * next. `regions` above keeps only the material (even-depth) regions for a whole-sketch extrude.
95
+ */
96
+ this.allRegions = null
97
+ }
98
+ }
99
+
100
+ export class Line {
101
+ constructor(o, d) { this.o = o; this.d = d }
102
+ }
103
+
104
+ export class Feature {
105
+ constructor(name, funclit, defaults, meta, line = 0) {
106
+ this.name = name
107
+ this.funclit = funclit
108
+ this.defaults = defaults // Map: name -> value
109
+ this.meta = meta // Map: name -> {"Name":..., "Default":...}
110
+ this.title = name
111
+ this.description = ''
112
+ this.line = line
113
+ }
114
+ }
115
+
116
+ export class Context {
117
+ /** Stands in for the Onshape modelling context. */
118
+ constructor(scene) { this.scene = scene }
119
+ }
120
+
121
+ class _Return {
122
+ constructor(value) { this.value = value }
123
+ }
124
+ class _Break {}
125
+ class _Continue {}
126
+
127
+ export class Env {
128
+ constructor(parent = null) {
129
+ this.vars = new Map()
130
+ this.parent = parent
131
+ }
132
+
133
+ get(name, line = null) {
134
+ let e = this
135
+ while (e !== null) {
136
+ if (e.vars.has(name)) return e.vars.get(name)
137
+ e = e.parent
138
+ }
139
+ throw new FsError(`undefined identifier '${name}'`, line)
140
+ }
141
+
142
+ has(name) {
143
+ let e = this
144
+ while (e !== null) {
145
+ if (e.vars.has(name)) return true
146
+ e = e.parent
147
+ }
148
+ return false
149
+ }
150
+
151
+ declare(name, value) { this.vars.set(name, value) }
152
+
153
+ assign(name, value, line = null) {
154
+ let e = this
155
+ while (e !== null) {
156
+ if (e.vars.has(name)) { e.vars.set(name, value); return }
157
+ e = e.parent
158
+ }
159
+ this.vars.set(name, value)
160
+ }
161
+ }
162
+
163
+ const NAMESPACES = {
164
+ BoundingType: ['BLIND', 'UP_TO_NEXT', 'UP_TO_SURFACE', 'UP_TO_BODY', 'SYMMETRIC'],
165
+ BooleanOperationType: ['UNION', 'SUBTRACTION', 'INTERSECTION'],
166
+ EntityType: ['BODY', 'FACE', 'EDGE', 'VERTEX', 'ANY'],
167
+ PropertyType: ['NAME', 'APPEARANCE', 'MATERIAL', 'PART_NUMBER', 'DESCRIPTION'],
168
+ BodyType: ['SOLID', 'SHEET', 'WIRE', 'POINT'],
169
+ UIHint: ['DROPDOWN', 'DEFAULT', 'COLLAPSIBLE', 'ALWAYS_HIDDEN'],
170
+ GeometryType: ['PLANE', 'CYLINDER', 'SPHERE', 'CONE', 'TORUS'],
171
+ Swatch: [],
172
+ }
173
+
174
+ const nsMember = (ns, name) => `${ns}.${name}`
175
+
176
+ /** Python's %g formatting (6 significant digits). */
177
+ export function fmtG(x) {
178
+ if (Number.isNaN(x)) return 'nan'
179
+ if (x === Infinity) return 'inf'
180
+ if (x === -Infinity) return '-inf'
181
+ if (x === 0) return Object.is(x, -0) ? '-0' : '0'
182
+ const exp = Math.floor(Math.log10(Math.abs(x)))
183
+ if (exp < -4 || exp >= 6) {
184
+ const [m0, e0] = Number(x).toExponential(5).split('e')
185
+ let m = m0
186
+ if (m.includes('.')) m = m.replace(/0+$/, '').replace(/\.$/, '')
187
+ const e = parseInt(e0, 10)
188
+ return `${m}e${e < 0 ? '-' : '+'}${String(Math.abs(e)).padStart(2, '0')}`
189
+ }
190
+ let s = Number(x).toPrecision(6)
191
+ if (s.includes('.')) s = s.replace(/0+$/, '').replace(/\.$/, '')
192
+ return s
193
+ }
194
+
195
+ /** FeatureScript's `~` stringification. */
196
+ export function fsStr(v) {
197
+ if (typeof v === 'string') return v
198
+ if (typeof v === 'boolean') return v ? 'true' : 'false'
199
+ if (v instanceof Q) {
200
+ if (dimEq(v.dim, LEN)) return `${fmtG(v.v)} mm`
201
+ if (dimEq(v.dim, ANG)) return `${fmtG(v.v)} rad`
202
+ return fmtG(v.v)
203
+ }
204
+ if (typeof v === 'number' && Number.isInteger(v)) return String(v)
205
+ if (v === null || v === undefined) return 'undefined'
206
+ return String(v)
207
+ }
208
+
209
+ const dimEq = (a, b) => a[0] === b[0] && a[1] === b[1]
210
+
211
+ /** Python float % (result takes the sign of the divisor). */
212
+ const pyMod = (a, b) => a - b * Math.floor(a / b)
213
+
214
+ const isPlainNumber = (x) => typeof x === 'number'
215
+
216
+ const sizeOf = (x) => {
217
+ if (typeof x === 'string') return x.length
218
+ if (Array.isArray(x)) return x.length
219
+ if (x instanceof Vec) return x.length()
220
+ throw new FsError('size() needs an array or string')
221
+ }
222
+
223
+ // ---------------------------------------------------------------------------
224
+ // interpreter
225
+ // ---------------------------------------------------------------------------
226
+
227
+ export class Interp {
228
+ /**
229
+ * @param {string} [sourceName] Name used in diagnostics and trace spans.
230
+ * @param {boolean} [verbose] Log warnings while running.
231
+ * @param {{ trace?: boolean }} [options] Enable the feature-history trace.
232
+ */
233
+ constructor(sourceName = '<fs>', verbose = false, options = {}) {
234
+ this.source = sourceName
235
+ this.verbose = verbose
236
+ this.scene = new Scene()
237
+ this.context = new Context(this.scene)
238
+ this.globalEnv = new Env()
239
+ this.moduleEnv = null
240
+ this.features = new Map()
241
+ this.notes = []
242
+ /** Feature-history recorder; null unless tracing was requested. */
243
+ this.tracer = options.trace ? new Tracer({ file: sourceName }) : null
244
+ /** Stop after this many recorded features (rollback to that point in history). */
245
+ this.rollbackAt = Number.isInteger(options.rollbackAt) ? options.rollbackAt : null
246
+ /** Assembly declared via `defineAssembly(...)` in an assembly document. */
247
+ this.assemblyFeature = null
248
+ this.#installBuiltins()
249
+ this.#installConstants()
250
+ }
251
+
252
+ /**
253
+ * Install a host operation (an assembly/document op the embedding host provides).
254
+ *
255
+ * Host ops are ordinary builtins from the program's point of view: the same call syntax,
256
+ * the same error path, and — when tracing — the same history entry.
257
+ *
258
+ * @param {string} name Operation name as written in the source.
259
+ * @param {(args: unknown[]) => unknown} fn Implementation.
260
+ */
261
+ defineHostBuiltin(name, fn) {
262
+ this.globalEnv.get('__builtins__').set(name, fn)
263
+ }
264
+
265
+ // -- diagnostics ---------------------------------------------------------
266
+ note(msg) {
267
+ this.notes.push(msg)
268
+ if (this.verbose) console.log(msg)
269
+ }
270
+
271
+ warn(msg) {
272
+ this.notes.push('WARNING: ' + msg)
273
+ console.log('WARNING: ' + msg)
274
+ }
275
+
276
+ // -- environment ----------------------------------------------------------
277
+ #installConstants() {
278
+ const g = this.globalEnv
279
+ g.declare('millimeter', new Q(1.0, LEN))
280
+ g.declare('millimetre', new Q(1.0, LEN))
281
+ g.declare('centimeter', new Q(10.0, LEN))
282
+ g.declare('meter', new Q(1000.0, LEN))
283
+ g.declare('inch', new Q(25.4, LEN))
284
+ g.declare('foot', new Q(304.8, LEN))
285
+ g.declare('degree', new Q(Math.PI / 180.0, ANG))
286
+ g.declare('radian', new Q(1.0, ANG))
287
+ g.declare('unitless', new Q(1.0, ONE))
288
+ g.declare('PI', Math.PI)
289
+ for (const [ns, members] of Object.entries(NAMESPACES)) {
290
+ const m = new Map()
291
+ for (const mem of members) m.set(mem, nsMember(ns, mem))
292
+ g.declare(ns, m)
293
+ }
294
+ }
295
+
296
+ #installBuiltins() {
297
+ const math1 = (fn, keepDim, { angle = false, returnsAngle = false } = {}) =>
298
+ (args) => {
299
+ const x0 = args[0]
300
+ const x = x0 instanceof Q ? x0.v : +x0
301
+ const r = fn(x)
302
+ if (keepDim && x0 instanceof Q) return new Q(r, x0.dim)
303
+ if (returnsAngle) return new Q(r, ANG)
304
+ return new Q(r, ONE)
305
+ }
306
+
307
+ // Python round(): banker's rounding to the nearest integer.
308
+ const pyRound = (x) => {
309
+ const f = Math.floor(x)
310
+ const d = x - f
311
+ if (d < 0.5) return f
312
+ if (d > 0.5) return f + 1
313
+ return f % 2 === 0 ? f : f + 1
314
+ }
315
+
316
+ const minmax = (args, biggest) => {
317
+ const vals = (args.length === 1 && Array.isArray(args[0])) ? [...args[0]] : [...args]
318
+ if (!vals.length) throw new FsError('min()/max() needs at least one value')
319
+ const key = (x) => (x instanceof Q ? x.v : +x)
320
+ return vals.reduce((best, x) => (key(x) > key(best) === biggest ? x : best))
321
+ }
322
+
323
+ const b = new Map()
324
+ // math ----------------------------------------------------------
325
+ b.set('floor', math1(Math.floor, true))
326
+ b.set('ceil', math1(Math.ceil, true))
327
+ b.set('round', math1(pyRound, true))
328
+ b.set('abs', math1(Math.abs, true))
329
+ b.set('sqrt', math1(Math.sqrt, false))
330
+ b.set('sin', math1(Math.sin, false, { angle: true }))
331
+ b.set('cos', math1(Math.cos, false, { angle: true }))
332
+ b.set('tan', math1(Math.tan, false, { angle: true }))
333
+ b.set('asin', math1(Math.asin, false, { returnsAngle: true }))
334
+ b.set('acos', math1(Math.acos, false, { returnsAngle: true }))
335
+ b.set('atan', math1(Math.atan, false, { returnsAngle: true }))
336
+ b.set('min', (a) => minmax(a, false))
337
+ b.set('max', (a) => minmax(a, true))
338
+ b.set('size', (a) => sizeOf(a[0]))
339
+ b.set('range', (a) => {
340
+ const out = []
341
+ for (let i = Math.trunc(num(a[0])); i <= Math.trunc(num(a[1])); i++) out.push(new Q(i, ONE))
342
+ return out
343
+ })
344
+ b.set('append', (a) => [...a[0], a[1]])
345
+ b.set('toString', (a) => fsStr(a[0]))
346
+ // vectors -------------------------------------------------------
347
+ b.set('vector', (a) => new Vec([...a]))
348
+ b.set('cross', (a) => a[0].cross(a[1]))
349
+ b.set('dot', (a) => a[0].dot(a[1]))
350
+ b.set('norm', (a) => new Q(a[0].norm(), ONE))
351
+ b.set('normalize', (a) => a[0].normalized())
352
+ // construction --------------------------------------------------
353
+ b.set('coordSystem', (a) => {
354
+ const origin = vec3mm(a[0], 'coordSystem origin')
355
+ const u = vec3mm(a[1], 'coordSystem xAxis')
356
+ const n = vec3mm(a[2], 'coordSystem zAxis')
357
+ return new Plane(origin, u, n)
358
+ })
359
+ b.set('plane', (a) => a[0])
360
+ b.set('line', (a) => new Line(vec3mm(a[0], 'line origin'), vec3mm(a[1], 'line direction')))
361
+ b.set('transform', (a) => {
362
+ const m = a[0]
363
+ const t = vec3mm(a[1], 'transform translation')
364
+ if (m instanceof Xf) return new Xf(m.m, [m.t[0] + t[0], m.t[1] + t[1], m.t[2] + t[2]])
365
+ return new Xf(m, t)
366
+ })
367
+ b.set('rotationMatrix3d', (a) => {
368
+ const axis = a[0] instanceof Vec ? a[0].comps() : a[0]
369
+ const ang = a[1] instanceof Q ? a[1].rad() : +a[1]
370
+ return rotationMatrix(axis, ang)
371
+ })
372
+ b.set('identityTransform', () => new Xf())
373
+ b.set('color', (a) => {
374
+ const vals = a.map(num)
375
+ while (vals.length < 4) vals.push(1.0)
376
+ return new Color(...vals.slice(0, 4))
377
+ })
378
+ // queries -------------------------------------------------------
379
+ b.set('qCreatedBy', (a) => this.#qCreatedBy(a))
380
+ b.set('qUnion', (a) => {
381
+ const out = new Sel()
382
+ for (const s of a[0]) {
383
+ if (s instanceof Sel) {
384
+ out.solids.push(...s.solids)
385
+ out.sketches.push(...s.sketches)
386
+ out.faces.push(...s.faces)
387
+ }
388
+ }
389
+ return out
390
+ })
391
+ b.set('qNothing', () => new Sel())
392
+ // Host query: every live body in the document. Onshape spells this
393
+ // `qAllModifiableSolidBodies()`; it is what a whole-part transform needs when the
394
+ // program has no single query handle for "the part". Documented as a host extension.
395
+ b.set('qAllModifiableSolidBodies', () => new Sel(this.scene.alive()))
396
+ b.set('qNthElement', (a) => {
397
+ const sel = a[0]
398
+ const i = Math.trunc(num(a[1]))
399
+ if (sel.solids.length) {
400
+ // A feature targeting a body that a later re-evaluation removed (e.g. a fillet on body 2
401
+ // after an earlier extrude switched to Add and merged it away) must be a typed error, not an
402
+ // undefined body that crashes every downstream op with "reading 'alive'".
403
+ if (i < 0 || i >= sel.solids.length) {
404
+ throw new FsError(`qNthElement index ${i} is out of range (${sel.solids.length} bodies)`)
405
+ }
406
+ return new Sel([sel.solids[i]])
407
+ }
408
+ // A sketch query addresses the sketch's **faces** (regions): this is how a specific face
409
+ // between two nested contours is extruded on its own — `qNthElement(qCreatedBy(id + "sk",
410
+ // EntityType.FACE), 0)` is the outer face, `…, 1)` the next one inside it.
411
+ const faces = sel.faces.length ? sel.faces : this.#sketchFaces(sel)
412
+ if (!faces.length) throw new FsError('qNthElement on an empty query')
413
+ if (i < 0 || i >= faces.length) {
414
+ throw new FsError(`qNthElement index ${i} is out of range (${faces.length} sketch regions)`)
415
+ }
416
+ return new Sel([], [], [faces[i]])
417
+ })
418
+ // Host query: the planar face of a body at a geometric anchor. Onshape's stdlib cannot name a
419
+ // face of a body from source without a topological query, so this is a documented dialect
420
+ // extension (like `qAllModifiableSolidBodies`). `point` is a world position on the face
421
+ // (`vector(x, y, z) * millimeter`), `normal` its outward direction (a plain unit vector); the
422
+ // face is resolved against the exact B-rep at evaluation time, and the kernel refuses an anchor
423
+ // that no longer lies on a planar face rather than guessing (docs/CAD.md §7.3).
424
+ b.set('qPlanarFaceAt', (a) => this.#qPlanarFaceAt(a))
425
+ // modelling -----------------------------------------------------
426
+ b.set('defineFeature', (a) => this.#defineFeature(a))
427
+ b.set('newSketchOnPlane', (a) => this.#newSketch(a))
428
+ b.set('skRectangle', (a) => this.#skRect(a))
429
+ b.set('skCircle', (a) => this.#skCircle(a))
430
+ b.set('skLineSegment', (a) => this.#skLine(a))
431
+ b.set('skArc', (a) => this.#skArc(a))
432
+ b.set('skSolve', (a) => this.#skSolve(a))
433
+ b.set('opExtrude', (a) => this.#opExtrude(a))
434
+ b.set('opRevolve', (a) => this.#opRevolve(a))
435
+ b.set('opBoolean', (a) => this.#opBoolean(a))
436
+ b.set('opPattern', (a) => this.#opPattern(a))
437
+ b.set('opTransform', (a) => this.#opTransform(a))
438
+ b.set('opDeleteBodies', (a) => this.#opDelete(a))
439
+ b.set('opFillet', (a) => this.#opEdgeModifier(a, 'fillet'))
440
+ b.set('opChamfer', (a) => this.#opEdgeModifier(a, 'chamfer'))
441
+ b.set('opShell', (a) => this.#opShell(a))
442
+ b.set('opLoft', (a) => this.#opLoft(a))
443
+ b.set('opSweep', (a) => this.#opSweep(a))
444
+ b.set('setProperty', (a) => this.#setProperty(a))
445
+ // reporting -----------------------------------------------------
446
+ const report = (level) => (args) => {
447
+ const last = args.length ? args[args.length - 1] : undefined
448
+ // reportFeatureInfo(context, id, { "message" : … }) is the documented
449
+ // form; a bare map stringifies to "[object Map]" otherwise
450
+ const msg = (last instanceof Map && last.has('message'))
451
+ ? fsStr(last.get('message'))
452
+ : (args.length ? fsStr(last) : '')
453
+ this.note(`[${level}] ${msg}`)
454
+ return null
455
+ }
456
+ b.set('reportFeatureInfo', report('INFO'))
457
+ b.set('reportFeatureWarning', report('WARNING'))
458
+ b.set('reportFeatureError', report('ERROR'))
459
+ b.set('debug', () => null)
460
+ // precondition predicates are handled syntactically; if one is ever
461
+ // evaluated, treat it as a satisfied predicate
462
+ b.set('isLength', () => true)
463
+ b.set('isInteger', () => true)
464
+ b.set('isAngle', () => true)
465
+ b.set('isNumber', () => true)
466
+
467
+ this.globalEnv.declare('__builtins__', b)
468
+ }
469
+
470
+ callBuiltin(name, args, node) {
471
+ const line = node?.line ?? null
472
+ const b = this.globalEnv.get('__builtins__')
473
+ if (!(b instanceof Map) || !b.has(name)) {
474
+ throw new FsError(`unsupported function ${name}()`, line, null, this.source)
475
+ }
476
+ const kind = this.tracer ? classifyBuiltin(name) : null
477
+ // Only an `Id` value is a feature id: `setProperty(context, definition)` has a map in
478
+ // argument 1, and some ops take the definition in a different position.
479
+ const idArg = args[1] instanceof Id ? args[1] : null
480
+ const definitionArg = args[2] instanceof Map ? args[2] : (args[1] instanceof Map ? args[1] : null)
481
+ // Registry size before the call: the delta is the number of bodies this op created.
482
+ const key = kind && idArg ? idArg.toString() : null
483
+ const before = kind && key ? (this.scene.registry[key]?.length ?? 0) : 0
484
+ try {
485
+ const result = b.get(name)(args)
486
+ if (kind) {
487
+ this.tracer.record({
488
+ op: name,
489
+ kind,
490
+ id: key,
491
+ span: spanOf(node, this.source),
492
+ definition: definitionArg ? serializeValue(definitionArg) : null,
493
+ produced: kind && key ? (this.scene.registry[key]?.length ?? 0) - before : 0,
494
+ bodies: this.scene.alive ? this.scene.alive().length : 0,
495
+ })
496
+ }
497
+ if (this.rollbackAt != null && this.tracer && this.tracer.entries.length >= this.rollbackAt) {
498
+ throw new RollbackSignal(this.rollbackAt)
499
+ }
500
+ return result
501
+ } catch (e) {
502
+ if (e instanceof RollbackSignal || e instanceof FsError) throw e
503
+ throw new FsError(`${name}() failed: ${e?.message ?? e}`, line, null, this.source)
504
+ }
505
+ }
506
+
507
+ // -- program execution ----------------------------------------------------
508
+ run(stmts) {
509
+ const env = new Env(this.globalEnv)
510
+ this.moduleEnv = env
511
+ // pass 1: declarations that can be referenced before their definition
512
+ for (const st of stmts) {
513
+ const inner = st.kind === 'Annotation' ? st.stmt : st
514
+ if (inner.kind === 'FuncDecl') {
515
+ env.declare(inner.name, ['func', inner])
516
+ } else if (inner.kind === 'EnumDecl') {
517
+ const m = new Map()
518
+ for (const mem of inner.members) m.set(mem, `${inner.name}.${mem}`)
519
+ env.declare(inner.name, m)
520
+ }
521
+ }
522
+ // pass 2: everything else
523
+ for (const st of stmts) this.execStmt(st, env)
524
+ return env
525
+ }
526
+
527
+ execBlock(block, env) {
528
+ const inner = new Env(env)
529
+ for (const st of block.stmts) this.execStmt(st, inner)
530
+ }
531
+
532
+ execStmt(node, env) {
533
+ try {
534
+ this.#execStmt(node, env)
535
+ } catch (e) {
536
+ if (e instanceof FsError && e.line === null && node.line) {
537
+ throw new FsError(e.message, node.line, null, this.source)
538
+ }
539
+ throw e
540
+ }
541
+ }
542
+
543
+ #execStmt(node, env) {
544
+ switch (node.kind) {
545
+ case 'Skip': return
546
+ case 'Block': this.execBlock(node, env); return
547
+ case 'Annotation': {
548
+ const m = this.eval(node.map, env)
549
+ this.execStmt(node.stmt, env)
550
+ // attach metadata to a feature created by the annotated declaration
551
+ if (node.stmt.kind === 'ConstDecl') {
552
+ const val = env.get(node.stmt.name)
553
+ if (val instanceof Feature) {
554
+ if (!val.name) val.name = node.stmt.name
555
+ val.title = m.get('Feature Type Name') ?? val.title
556
+ val.description = m.get('Feature Type Description') ?? ''
557
+ this.features.set(val.name, val)
558
+ }
559
+ }
560
+ return
561
+ }
562
+ case 'ConstDecl': {
563
+ const val = node.expr !== null && node.expr !== undefined
564
+ ? this.eval(node.expr, env) : null
565
+ if (val instanceof Feature) {
566
+ if (!val.name) val.name = node.name
567
+ if (!val.title) val.title = node.name
568
+ this.features.set(val.name, val)
569
+ }
570
+ env.declare(node.name, val)
571
+ return
572
+ }
573
+ case 'FuncDecl': env.declare(node.name, ['func', node]); return
574
+ case 'EnumDecl': {
575
+ const m = new Map()
576
+ for (const mem of node.members) m.set(mem, `${node.name}.${mem}`)
577
+ env.declare(node.name, m)
578
+ return
579
+ }
580
+ case 'VarDecl': {
581
+ const val = node.expr !== null && node.expr !== undefined
582
+ ? this.eval(node.expr, env) : null
583
+ env.declare(node.name, val)
584
+ return
585
+ }
586
+ case 'Assign': {
587
+ const val = this.eval(node.expr, env)
588
+ if (node.target.kind === 'Ident') {
589
+ env.assign(node.target.name, val, node.line)
590
+ return
591
+ }
592
+ if (node.target.kind === 'Index') {
593
+ const obj = this.eval(node.target.obj, env)
594
+ obj[Math.trunc(num(this.eval(node.target.idx, env)))] = val
595
+ return
596
+ }
597
+ throw new FsError('unsupported assignment target', node.line, null, this.source)
598
+ }
599
+ case 'If': {
600
+ if (this.truth(this.eval(node.cond, env))) this.execBlock(node.then, env)
601
+ else if (node.els !== null && node.els !== undefined) this.execBlock(node.els, env)
602
+ return
603
+ }
604
+ case 'For': {
605
+ const it = this.eval(node.iterable, env)
606
+ let items
607
+ if (Array.isArray(it) || it instanceof Vec) items = it instanceof Vec ? [...it] : it
608
+ else throw new FsError('for-loop needs an array', node.line, null, this.source)
609
+ for (const item of items) {
610
+ const inner = new Env(env)
611
+ inner.declare(node.var, item)
612
+ try {
613
+ for (const st of node.body.stmts) this.execStmt(st, inner)
614
+ } catch (e) {
615
+ if (e instanceof _Continue) continue
616
+ if (e instanceof _Break) break
617
+ throw e
618
+ }
619
+ }
620
+ return
621
+ }
622
+ case 'Return':
623
+ throw new _Return(node.expr !== null && node.expr !== undefined
624
+ ? this.eval(node.expr, env) : null)
625
+ case 'ExprStmt': this.eval(node.expr, env); return
626
+ default:
627
+ throw new FsError(`unsupported statement ${node.kind}`, node.line, null, this.source)
628
+ }
629
+ }
630
+
631
+ // -- expressions -----------------------------------------------------------
632
+ eval(node, env) {
633
+ try {
634
+ return this.#eval(node, env)
635
+ } catch (e) {
636
+ if (e instanceof FsError && e.line === null && node.line) {
637
+ throw new FsError(e.message, node.line, null, this.source)
638
+ }
639
+ throw e
640
+ }
641
+ }
642
+
643
+ #eval(node, env) {
644
+ switch (node.kind) {
645
+ case 'Num': return new Q(node.value, ONE)
646
+ case 'Str': return node.value
647
+ case 'Bool': return node.value
648
+ case 'Undefined': return null
649
+ case 'Ident': return env.get(node.name, node.line)
650
+ case 'Member': {
651
+ const obj = this.eval(node.obj, env)
652
+ if (obj instanceof Map) {
653
+ if (obj.has(node.name)) return obj.get(node.name)
654
+ // a map access on a definition map that has no such key yet
655
+ throw new FsError(`no member '${node.name}'`, node.line, null, this.source)
656
+ }
657
+ throw new FsError(`cannot read member '${node.name}'`, node.line, null, this.source)
658
+ }
659
+ case 'Index': {
660
+ const obj = this.eval(node.obj, env)
661
+ const idx = this.eval(node.idx, env)
662
+ if (obj instanceof Map) {
663
+ // FeatureScript maps are keyed by strings (`REGISTRY["ss316l"]`)
664
+ return obj.get(idx)
665
+ }
666
+ if (obj instanceof Vec) return obj.get(Math.trunc(num(idx)))
667
+ // Python-style negative indexing on arrays
668
+ const i = Math.trunc(num(idx))
669
+ return obj[i < 0 ? obj.length + i : i]
670
+ }
671
+ case 'ArrayLit': return node.items.map((e) => this.eval(e, env))
672
+ case 'MapLit': {
673
+ const out = new Map()
674
+ for (const [k, v] of node.pairs) {
675
+ out.set(this.eval(k, env), this.eval(v, env))
676
+ }
677
+ return out
678
+ }
679
+ case 'Cast': return this.eval(node.expr, env)
680
+ case 'IsType':
681
+ if (node.typename === 'boolean') return typeof this.eval(node.expr, env) === 'boolean'
682
+ return true
683
+ case 'Un': {
684
+ const v = this.eval(node.e, env)
685
+ if (node.op === '-') {
686
+ if (v instanceof Q) return v.neg()
687
+ if (v instanceof Vec) return v.neg()
688
+ if (isPlainNumber(v)) return -v
689
+ throw new FsError(`bad operand for unary -`)
690
+ }
691
+ if (node.op === '!') return !this.truth(v)
692
+ break
693
+ }
694
+ case 'Bin': return this.#evalBin(node, env)
695
+ case 'Call': return this.#evalCall(node, env)
696
+ case 'FuncLit': return ['funclit', node, env]
697
+ default: break
698
+ }
699
+ throw new FsError(`unsupported expression ${node.kind}`, node.line, null, this.source)
700
+ }
701
+
702
+ #evalBin(node, env) {
703
+ const op = node.op
704
+ if (op === '&&') return this.truth(this.eval(node.l, env)) && this.truth(this.eval(node.r, env))
705
+ if (op === '||') return this.truth(this.eval(node.l, env)) || this.truth(this.eval(node.r, env))
706
+ const a = this.eval(node.l, env)
707
+ const b = this.eval(node.r, env)
708
+ try {
709
+ return this.#bin(op, a, b)
710
+ } catch (e) {
711
+ if (e instanceof FsError) throw e
712
+ throw new FsError(`${op} is not defined between ${fsStr(a)} and ${fsStr(b)} (${e?.message ?? e})`,
713
+ node.line, null, this.source)
714
+ }
715
+ }
716
+
717
+ #bin(op, a, b) {
718
+ switch (op) {
719
+ case '~': return fsStr(a) + fsStr(b)
720
+ case '==': return this.equals(a, b)
721
+ case '!=': return !this.equals(a, b)
722
+ case '<': case '>': case '<=': case '>=': {
723
+ if (a instanceof Q && b instanceof Q) {
724
+ if (op === '<') return a.lt(b)
725
+ if (op === '>') return a.gt(b)
726
+ if (op === '<=') return a.le(b)
727
+ return a.ge(b)
728
+ }
729
+ const x = a instanceof Q ? a.v : +a
730
+ const y = b instanceof Q ? b.v : +b
731
+ if (op === '<') return x < y
732
+ if (op === '>') return x > y
733
+ if (op === '<=') return x <= y
734
+ return x >= y
735
+ }
736
+ case '+':
737
+ if (a instanceof Q) return a.add(b)
738
+ if (b instanceof Q) return b.add(a) // number + Q
739
+ if (a instanceof Id) return a.add(b) // Id + "suffix" (Id + Id too)
740
+ if (a instanceof Vec) return a.add(b)
741
+ if (b instanceof Vec) return b.add(a)
742
+ if (typeof a === 'string' || typeof b === 'string') return fsStr(a) + fsStr(b)
743
+ if (Array.isArray(a) && Array.isArray(b)) return [...a, ...b]
744
+ return a + b
745
+ case '-':
746
+ if (a instanceof Q) return a.sub(b)
747
+ if (b instanceof Q && !(a instanceof Q)) return b.neg().add(a)
748
+ if (a instanceof Vec) return a.sub(b)
749
+ if (a instanceof Vec === false && b instanceof Vec) throw new Error('vector size mismatch')
750
+ return a - b
751
+ case '*':
752
+ if (a instanceof Q && b instanceof Vec) return b.mul(a)
753
+ if (a instanceof Q) return a.mul(b)
754
+ if (b instanceof Q) return b.mul(a)
755
+ if (a instanceof Vec) return a.mul(b)
756
+ return a * b
757
+ case '/':
758
+ if (a instanceof Q && b instanceof Q) return a.div(b)
759
+ if (b instanceof Q && !(a instanceof Q)) return new Q(+a / b.v,
760
+ [ONE[0] - b.dim[0], ONE[1] - b.dim[1]])
761
+ if (a instanceof Q) return a.div(b)
762
+ if (a instanceof Vec) return a.div(b)
763
+ return a / b
764
+ case '%': {
765
+ const av = a instanceof Q ? a.v : +a
766
+ const bv = b instanceof Q ? b.v : +b
767
+ return new Q(pyMod(av, bv), a instanceof Q ? a.dim : ONE)
768
+ }
769
+ default:
770
+ throw new FsError(`unsupported operator ${op}`)
771
+ }
772
+ }
773
+
774
+ equals(a, b) {
775
+ if (a instanceof Q && b instanceof Q) return a.eq(b)
776
+ if (isPlainNumber(a) && b instanceof Q) return b.eq(new Q(a, ONE))
777
+ if (a instanceof Q && isPlainNumber(b)) return a.eq(new Q(b, ONE))
778
+ if (typeof a === 'boolean' || typeof b === 'boolean') return a === b
779
+ if (Array.isArray(a) && Array.isArray(b)) {
780
+ return a.length === b.length && a.every((x, i) => this.equals(x, b[i]))
781
+ }
782
+ if (a instanceof Map && b instanceof Map) {
783
+ if (a.size !== b.size) return false
784
+ for (const [k, v] of a) {
785
+ if (!b.has(k) || !this.equals(v, b.get(k))) return false
786
+ }
787
+ return true
788
+ }
789
+ return a === b
790
+ }
791
+
792
+ truth(v) {
793
+ if (typeof v === 'boolean') return v
794
+ if (v instanceof Q) return v.v !== 0
795
+ if (v === null || v === undefined) return false
796
+ if (Array.isArray(v)) return v.length > 0
797
+ if (v instanceof Map) return v.size > 0
798
+ if (v instanceof Vec) return v.length() > 0
799
+ return Boolean(v)
800
+ }
801
+
802
+ #evalCall(node, env) {
803
+ const callee = node.callee
804
+ const args = node.args.map((a) => this.eval(a, env))
805
+ if (callee.kind === 'Ident') {
806
+ const name = callee.name
807
+ if (!env.has(name)) return this.callBuiltin(name, args, node)
808
+ const fn = env.get(name, node.line)
809
+ // A call whose second argument is an Id is a feature-ish invocation (`helper(ctx, id + "x")`):
810
+ // push a frame so every history entry can name the helper call that produced it.
811
+ const frame = this.tracer && args[1] instanceof Id
812
+ ? { callee: name, span: spanOf(node, this.source), id: args[1].toString() }
813
+ : null
814
+ if (frame) this.tracer.pushFrame(frame)
815
+ try {
816
+ if (Array.isArray(fn) && fn.length && fn[0] === 'func') {
817
+ return this.callFunc(fn[1], args, node.line)
818
+ }
819
+ if (Array.isArray(fn) && fn.length && fn[0] === 'funclit') {
820
+ return this.callFunclit(fn[1], args, fn[2], node.line)
821
+ }
822
+ if (typeof fn === 'function') return fn(args)
823
+ throw new FsError(`${name} is not callable`, node.line, null, this.source)
824
+ } finally {
825
+ if (frame) this.tracer.popFrame()
826
+ }
827
+ }
828
+ if (callee.kind === 'Member') {
829
+ const obj = this.eval(callee.obj, env)
830
+ const fname = callee.name
831
+ if (obj instanceof Map && typeof obj.get(fname) === 'function') {
832
+ return obj.get(fname)(args)
833
+ }
834
+ throw new FsError(`unsupported method call .${fname}()`, node.line, null, this.source)
835
+ }
836
+ throw new FsError('unsupported call target', node.line, null, this.source)
837
+ }
838
+
839
+ callFunc(decl, args, line) {
840
+ if (args.length !== decl.params.length) {
841
+ throw new FsError(`${decl.name}() takes ${decl.params.length} arguments, got ${args.length}`,
842
+ line, null, this.source)
843
+ }
844
+ const env = new Env(this.moduleEnv ?? this.globalEnv)
845
+ decl.params.forEach((p, i) => env.declare(p, args[i]))
846
+ try {
847
+ this.execBlock(decl.body, env)
848
+ } catch (e) {
849
+ if (e instanceof _Return) return e.value
850
+ throw e
851
+ }
852
+ return null
853
+ }
854
+
855
+ callFunclit(funclit, args, closure, line) {
856
+ const env = new Env(closure instanceof Env ? closure : this.globalEnv)
857
+ funclit.params.forEach((p, i) => env.declare(p, args[i]))
858
+ try {
859
+ this.execBlock(funclit.body, env)
860
+ } catch (e) {
861
+ if (e instanceof _Return) return e.value
862
+ throw e
863
+ }
864
+ return null
865
+ }
866
+
867
+ // -- precondition scanning --------------------------------------------------
868
+ #scanPrecondition(block) {
869
+ /** Extract parameter defaults from a defineFeature precondition. */
870
+ const defaults = new Map()
871
+ const meta = new Map()
872
+ let pending = new Map()
873
+ if (block === null || block === undefined) return [defaults, meta]
874
+ for (let st of block.stmts) {
875
+ if (st.kind === 'Annotation') {
876
+ pending = this.eval(st.map, new Env(this.globalEnv))
877
+ st = st.stmt
878
+ }
879
+ const expr = st.kind === 'ExprStmt' ? st.expr : null
880
+ if (expr === null || expr === undefined) continue
881
+ let pname = null
882
+ let spec = null
883
+ if (expr.kind === 'Call' && expr.callee.kind === 'Ident'
884
+ && ['isLength', 'isInteger', 'isAngle', 'isNumber'].includes(expr.callee.name)
885
+ && expr.args.length >= 2
886
+ && expr.args[0].kind === 'Member'
887
+ && expr.args[0].obj.kind === 'Ident'
888
+ && expr.args[0].obj.name === 'definition') {
889
+ pname = expr.args[0].name
890
+ spec = this.eval(expr.args[1], new Env(this.globalEnv))
891
+ } else if (expr.kind === 'IsType' && expr.expr.kind === 'Member'
892
+ && expr.expr.obj.kind === 'Ident' && expr.expr.obj.name === 'definition') {
893
+ pname = expr.expr.name
894
+ if (expr.typename === 'boolean') spec = new Map([['__boolean__', true]])
895
+ }
896
+ if (pname === null) {
897
+ pending = new Map()
898
+ continue
899
+ }
900
+ if (spec instanceof Map && spec.has('__boolean__')) {
901
+ defaults.set(pname, !!(pending.get('Default') ?? false))
902
+ } else if (spec instanceof Map && spec.size) {
903
+ const [unit, bounds] = [...spec.entries()][0]
904
+ const vals = [...bounds]
905
+ const dv = vals.length === 3 ? vals[1] : (vals.length >= 2 ? vals[vals.length - 1] : vals[0])
906
+ // FeatureScript reads the bounds in the unit of the spec key:
907
+ // { (millimeter) : [4, 8, 30] } -> default 8 mm
908
+ if (unit instanceof Q && dv instanceof Q && !dimEq(unit.dim, ONE)) {
909
+ defaults.set(pname, new Q(dv.v * unit.v, unit.dim))
910
+ } else {
911
+ defaults.set(pname, dv)
912
+ }
913
+ }
914
+ meta.set(pname, new Map([['Name', pending.get('Name') ?? ''],
915
+ ['Default', pending.get('Default')]]))
916
+ pending = new Map()
917
+ }
918
+ return [defaults, meta]
919
+ }
920
+
921
+ // -- geometry builtins --------------------------------------------------------
922
+ #defineFeature(args) {
923
+ let funclit = args[0]
924
+ if (Array.isArray(funclit) && funclit[0] === 'funclit') funclit = funclit[1]
925
+ if (funclit?.kind !== 'FuncLit') {
926
+ throw new FsError('defineFeature() needs a function literal')
927
+ }
928
+ const [defaults, meta] = this.#scanPrecondition(funclit.precondition)
929
+ return new Feature(null, funclit, defaults, meta, funclit.line)
930
+ }
931
+
932
+ #qCreatedBy(args) {
933
+ const ident = args[0]
934
+ const key = String(ident)
935
+ const et = args.length > 1 ? args[1] : 'EntityType.BODY'
936
+ const scene = this.scene
937
+ if (et === 'EntityType.FACE') {
938
+ if (scene.sketches[key] !== undefined) return new Sel([], [scene.sketches[key]])
939
+ throw new FsError(`no sketch registered under id '${key}'`)
940
+ }
941
+ const solids = scene.registry[key] ?? []
942
+ return new Sel([...solids])
943
+ }
944
+
945
+ /**
946
+ * `qPlanarFaceAt(bodies, point, normal)` — the planar face of `bodies` that contains `point`
947
+ * and faces `normal`.
948
+ *
949
+ * The face is not resolved here: the engine records the body, the anchor point and the outward
950
+ * normal as a {@link SolidFace}, and the exact kernel resolves the B-rep face when the extrude is
951
+ * translated (face ids are only valid within one evaluation, docs/CAD.md §7.3). A body query is
952
+ * required; more than one body is a typed error because an anchor names exactly one face.
953
+ *
954
+ * @param {Array} args Builtin arguments: body query, world point, outward normal.
955
+ * @returns {Sel} A face selection holding the anchored face.
956
+ */
957
+ #qPlanarFaceAt(args) {
958
+ const sel = args[0]
959
+ if (!(sel instanceof Sel)) throw new FsError('qPlanarFaceAt() needs a body query as its first argument')
960
+ const bodies = sel.solids.filter((solid) => solid.alive)
961
+ if (!bodies.length) {
962
+ throw new FsError('qPlanarFaceAt() found no body to take a face from')
963
+ }
964
+ if (bodies.length > 1) {
965
+ throw new FsError(
966
+ `qPlanarFaceAt() needs exactly one body (the query matched ${bodies.length}); address one with qNthElement()`,
967
+ )
968
+ }
969
+ const point = vec3mm(args[1], 'face point')
970
+ const normalValue = args[2]
971
+ if (!(normalValue instanceof Vec) || normalValue.length() !== 3) {
972
+ throw new FsError('qPlanarFaceAt() needs a 3D face normal')
973
+ }
974
+ const raw = normalValue.comps()
975
+ const length = Math.hypot(raw[0], raw[1], raw[2])
976
+ if (!(length > 1e-12)) throw new FsError('qPlanarFaceAt() needs a non-zero face normal')
977
+ const normal = [raw[0] / length, raw[1] / length, raw[2] / length]
978
+ return new Sel([], [], [new SolidFace(bodies[0], point, normal)])
979
+ }
980
+
981
+ #newSketch(args) {
982
+ const ident = args[1]
983
+ const d = args[2]
984
+ const sk = new Sketch(d.get('sketchPlane'))
985
+ this.scene.sketches[String(ident)] = sk
986
+ if (!this.scene.registry[String(ident)]) this.scene.registry[String(ident)] = []
987
+ return sk
988
+ }
989
+
990
+ static #min2(a, b) { return [Math.min(a[0], b[0]), Math.min(a[1], b[1])] }
991
+ static #max2(a, b) { return [Math.max(a[0], b[0]), Math.max(a[1], b[1])] }
992
+
993
+ #skRect(args) {
994
+ const sk = args[0]
995
+ const d = args[2]
996
+ const a = vec2mm(d.get('firstCorner'), 'firstCorner')
997
+ const b = vec2mm(d.get('secondCorner'), 'secondCorner')
998
+ sk.entities.push(['rect', Interp.#min2(a, b), Interp.#max2(a, b)])
999
+ }
1000
+
1001
+ #skCircle(args) {
1002
+ const sk = args[0]
1003
+ const d = args[2]
1004
+ const c = vec2mm(d.get('center'), 'center')
1005
+ const r = d.get('radius')
1006
+ sk.entities.push(['circle', c, r instanceof Q ? r.v : +r])
1007
+ }
1008
+
1009
+ #skLine(args) {
1010
+ const sk = args[0]
1011
+ const d = args[2]
1012
+ const a = vec2mm(d.get('start'), 'start')
1013
+ const b = vec2mm(d.get('end'), 'end')
1014
+ sk.entities.push(['line', a, b])
1015
+ }
1016
+
1017
+ /**
1018
+ * `skArc(sketch, id, { center, start, end, clockwise? })` — a circular arc
1019
+ * from `start` to `end` about `center`. The radius is the centre→start
1020
+ * distance; `end` is projected onto that circle. `clockwise` (default false)
1021
+ * picks the direction, and a zero-sweep arc is taken the long way round, so
1022
+ * the call never silently degenerates. Arcs chain with lines into contours
1023
+ * in `skSolve`, which is what lets a profile carry a real fillet or a
1024
+ * dished end instead of a hand-sampled polyline.
1025
+ */
1026
+ #skArc(args) {
1027
+ const sk = args[0]
1028
+ const d = args[2]
1029
+ const c = vec2mm(d.get('center'), 'center')
1030
+ const start = vec2mm(d.get('start'), 'start')
1031
+ const end = vec2mm(d.get('end'), 'end')
1032
+ const r = Math.hypot(start[0] - c[0], start[1] - c[1])
1033
+ if (!(r > 1e-9)) {
1034
+ throw new FsError('skArc needs a start point away from its center', null, null, this.source)
1035
+ }
1036
+ const a0 = Math.atan2(start[1] - c[1], start[0] - c[0])
1037
+ const a1 = Math.atan2(end[1] - c[1], end[0] - c[0])
1038
+ const clockwise = d.get('clockwise') === true
1039
+ let span = clockwise ? a0 - a1 : a1 - a0
1040
+ const TAU = 2 * Math.PI
1041
+ while (span <= 1e-12) span += TAU
1042
+ while (span > TAU + 1e-12) span -= TAU
1043
+ sk.entities.push(['arc', c, r, a0, clockwise ? -span : span])
1044
+ }
1045
+
1046
+ #skSolve(args) {
1047
+ const sk = args[0]
1048
+ const circles = sk.entities.filter((e) => e[0] === 'circle').map((e) => [e[1], e[2]])
1049
+ const rects = sk.entities.filter((e) => e[0] === 'rect').map((e) => new Rect2(e[1], e[2]))
1050
+ const lines = sk.entities.filter((e) => e[0] === 'line').map((e) => [e[1], e[2]])
1051
+ const arcs = sk.entities.filter((e) => e[0] === 'arc')
1052
+
1053
+ // ---- legacy flat profile list ---------------------------------------
1054
+ // `opRevolve` spins one profile in its sketch plane, where "a hole in the
1055
+ // profile plane" has no meaning; it keeps the pre-region semantics. The
1056
+ // ordering is also what `opExtrude` emitted before regions existed, so a
1057
+ // sketch without nesting renders byte-identically to before.
1058
+ const maximal = []
1059
+ for (let i = 0; i < circles.length; i++) {
1060
+ const [c, r] = circles[i]
1061
+ let inside = false
1062
+ for (let j = 0; j < circles.length; j++) {
1063
+ if (i === j) continue
1064
+ const [c2, r2] = circles[j]
1065
+ if (r2 > r - 1e-9 && Math.hypot(c[0] - c2[0], c[1] - c2[1]) + r <= r2 + 1e-9) {
1066
+ inside = true
1067
+ break
1068
+ }
1069
+ }
1070
+ if (!inside) maximal.push(new Circle2(c, r))
1071
+ }
1072
+ let profiles = [...rects, ...maximal]
1073
+
1074
+ /** The pre-region "chain the line ends in call order" polygon. */
1075
+ const rawPolygon = () => {
1076
+ if (!lines.length) return null
1077
+ const pts = [lines[0][0]]
1078
+ for (const [, b] of lines) pts.push(b)
1079
+ if (pts.length > 2
1080
+ && Math.hypot(pts[0][0] - pts[pts.length - 1][0],
1081
+ pts[0][1] - pts[pts.length - 1][1]) < 1e-9) {
1082
+ pts.pop()
1083
+ }
1084
+ return pts.length >= 3 ? new Poly2(pts) : null
1085
+ }
1086
+
1087
+ // ---- closed 2D regions (the topology opExtrude consumes) -------------
1088
+ // Open entities chain end to end, in any order and either orientation;
1089
+ // arcs are sampled with a chord tolerance. Nesting then becomes holes:
1090
+ // depth 0 is material, depth 1 a hole, depth 2 an island — see regions.js.
1091
+ const segments = []
1092
+ for (const [a, b] of lines) segments.push({ pts: [a, b] })
1093
+ for (const [, c, r, a0, sweep] of arcs) segments.push({ pts: arcPoints(c, r, a0, sweep) })
1094
+ const contourProfiles = chainContours(segments).contours
1095
+ .map((pts) => new Poly2(toCCW(pts)))
1096
+ const regionProfiles = [...rects, ...circles.map(([c, r]) => new Circle2(c, r)),
1097
+ ...contourProfiles]
1098
+ if (!regionProfiles.length) {
1099
+ const p = rawPolygon()
1100
+ if (p) regionProfiles.push(p)
1101
+ }
1102
+ sk.regions = nestProfiles(regionProfiles)
1103
+ // The full face list: every contour is a face (a ring between nested contours, the disc
1104
+ // inside it, islands, …). `qNthElement` over a sketch query addresses these in order.
1105
+ sk.allRegions = sketchRegions(regionProfiles)
1106
+
1107
+ // revolve keeps the legacy list, except that a chained contour (which now
1108
+ // includes any arcs) replaces the old raw line chain.
1109
+ if (!profiles.length) {
1110
+ if (contourProfiles.length) profiles.push(contourProfiles[0])
1111
+ else {
1112
+ const p = rawPolygon()
1113
+ if (p) profiles.push(p)
1114
+ }
1115
+ }
1116
+ sk.profiles = profiles
1117
+ return null
1118
+ }
1119
+
1120
+ #firstSketch(sel, line) {
1121
+ if (!sel.sketches.length) {
1122
+ throw new FsError('operation expected a sketch face query', line, null, this.source)
1123
+ }
1124
+ return sel.sketches[0]
1125
+ }
1126
+
1127
+ /**
1128
+ * Every face of a query's sketches, in the canonical `qNthElement` order.
1129
+ *
1130
+ * A sketch's faces are its regions (`sketchRegions`): one per closed contour, with the contours
1131
+ * directly inside it as holes. For two concentric circles that is the ring (index 0) and the
1132
+ * disc (index 1), so `qNthElement(qCreatedBy(sketchId, EntityType.FACE), 0)` addresses "the face
1133
+ * in between them".
1134
+ *
1135
+ * @param {Sel} sel Query selection holding one or more whole sketches.
1136
+ * @returns {Array<{sketch: Sketch, region: object}>} Face references.
1137
+ */
1138
+ #sketchFaces(sel) {
1139
+ const faces = []
1140
+ for (const sketch of sel.sketches) {
1141
+ for (const region of sketch.allRegions ?? []) faces.push({ sketch, region })
1142
+ }
1143
+ return faces
1144
+ }
1145
+
1146
+ /**
1147
+ * Build the extruded CSG for one sketch face: the outer contour's prism minus a prism of its
1148
+ * holes (a ring for the face between two nested circles).
1149
+ *
1150
+ * @param {Sketch} sketch Sketch the face belongs to.
1151
+ * @param {object} region One entry of `sketch.allRegions`.
1152
+ * @param {number} w0 Start depth along the plane normal.
1153
+ * @param {number} w1 End depth along the plane normal.
1154
+ * @returns {Node} The face's solid node.
1155
+ */
1156
+ #regionNode(sketch, region, w0, w1) {
1157
+ const outer = new Prism(sketch.plane, [region.outer], w0, w1)
1158
+ if (!region.holes.length) return outer
1159
+ return new Diff(outer, new Prism(sketch.plane, region.holes, w0, w1))
1160
+ }
1161
+
1162
+ #opExtrude(args) {
1163
+ const ident = args[1]
1164
+ const d = args[2]
1165
+ const sel = d.get('entities')
1166
+ // Three ways to select what an extrude consumes:
1167
+ // - whole sketches (the historical query) → every *material* region, parity semantics
1168
+ // (two concentric circles extrude to the ring, keeping the hole);
1169
+ // - explicit sketch faces (`qNthElement(qCreatedBy(sketch, EntityType.FACE), i)`, possibly a
1170
+ // `qUnion` of faces from several sketches) → exactly those regions, so "the face in
1171
+ // between" can be extruded on its own and each face keeps its nested contours as holes;
1172
+ // - planar **faces of existing bodies** (`qPlanarFaceAt(...)`) → a `FaceExtrude` node each, so
1173
+ // the exact kernel resolves the face's boundary (holes included) and extrudes it.
1174
+ const selectedFaces = sel.faces ?? []
1175
+ const solidFaces = selectedFaces.filter((face) => face instanceof SolidFace)
1176
+ const sketchFaces = selectedFaces.filter((face) => !(face instanceof SolidFace))
1177
+ const sketches = selectedFaces.length
1178
+ ? []
1179
+ : (sel.sketches?.length ? sel.sketches : [this.#firstSketch(sel, null)])
1180
+ const solidSketches = sketches.filter(Boolean)
1181
+ if (!selectedFaces.length && !solidSketches.length) {
1182
+ throw new FsError('extruding a sketch with no closed profiles')
1183
+ }
1184
+ if (!selectedFaces.length && solidSketches.every((sk) => !sk.regions?.length && !sk.profiles)) {
1185
+ throw new FsError('extruding a sketch with no closed profiles')
1186
+ }
1187
+ const direction = d.get('direction')
1188
+ const dr = direction instanceof Vec ? direction.comps() : direction
1189
+ const nrm = Math.hypot(dr[0], dr[1], dr[2])
1190
+ if (!(nrm > 1e-12)) throw new FsError('opExtrude needs a non-zero direction')
1191
+ const drN = [dr[0] / nrm, dr[1] / nrm, dr[2] / nrm]
1192
+ /**
1193
+ * The signed depth factor for one sketch plane: `+1`/`-1` when the extrude direction is along
1194
+ * that plane's normal, and `+1` (extrude along the face's own normal) for a multi-sketch or
1195
+ * multi-face selection whose planes differ — each face then sweeps normal to its own sketch.
1196
+ *
1197
+ * @param {object} sketch Sketch whose plane the face lies on.
1198
+ * @param {boolean} allowOblique Whether an oblique direction may fall back to the face normal.
1199
+ * @returns {number} Signed factor `s` (`w = depth * s`).
1200
+ */
1201
+ const normalFactor = (sketch, allowOblique) => {
1202
+ const n = sketch.plane.n
1203
+ const dot = drN[0] * n[0] + drN[1] * n[1] + drN[2] * n[2]
1204
+ if (Math.abs(Math.abs(dot) - 1.0) <= 1e-6) return Math.sign(dot) || 1
1205
+ if (allowOblique) return 1
1206
+ throw new FsError('the renderer only supports extrusions normal to their sketch plane')
1207
+ }
1208
+ const depth = d.get('endDepth')
1209
+ const d1 = depth == null ? 0 : (depth instanceof Q ? depth.v : +depth)
1210
+ const start = d.get('startDepth')
1211
+ const d0 = start == null ? 0 : (start instanceof Q ? start.v : +start)
1212
+ /** Depth window on one sketch's plane. */
1213
+ const windowFor = (sketch, allowOblique) => {
1214
+ const s = normalFactor(sketch, allowOblique)
1215
+ // Keep a zero start depth exactly +0: a negative zero would leak into the recorded node.
1216
+ return [d0 === 0 ? 0 : -d0 * s, d1 * s]
1217
+ }
1218
+ /**
1219
+ * Depth window on a body face's outward normal. A face profile is swept along its own normal
1220
+ * (the exact kernel builds the prism there), so the direction only chooses the sign — an
1221
+ * oblique direction would shear the profile, which an extrude profile cannot express.
1222
+ *
1223
+ * @param {SolidFace} face Anchored face.
1224
+ * @returns {[number, number]} Signed window along the face's outward normal.
1225
+ */
1226
+ const faceWindow = (face) => {
1227
+ const n = face.normal
1228
+ const dot = drN[0] * n[0] + drN[1] * n[1] + drN[2] * n[2]
1229
+ if (Math.abs(Math.abs(dot) - 1.0) > 1e-3) {
1230
+ throw new FsError('extruding a body face needs a direction normal to that face')
1231
+ }
1232
+ const s = Math.sign(dot) || 1
1233
+ return [d0 === 0 ? 0 : -d0 * s, d1 * s]
1234
+ }
1235
+ let node
1236
+ if (selectedFaces.length) {
1237
+ // Each selected face becomes its own exact prism (outer − holes); several selected faces
1238
+ // combine into the one body this operation produces.
1239
+ // A mixed selection (sketch faces + body faces) takes its direction from a body face, so a
1240
+ // sketch face whose plane is not parallel to it still sweeps normal to its own sketch plane.
1241
+ const allowOblique = sketchFaces.length > 1 || solidFaces.length > 0
1242
+ const nodes = sketchFaces.map((face) => {
1243
+ const [w0, w1] = windowFor(face.sketch, allowOblique)
1244
+ return this.#regionNode(face.sketch, face.region, w0, w1)
1245
+ })
1246
+ for (const face of solidFaces) {
1247
+ const [w0, w1] = faceWindow(face)
1248
+ nodes.push(new FaceExtrude(face.solid.node, face.point, face.normal, w0, w1))
1249
+ }
1250
+ node = nodes[0]
1251
+ for (let i = 1; i < nodes.length; i++) node = new Union(node, nodes[i])
1252
+ } else {
1253
+ const allowOblique = solidSketches.length > 1
1254
+ const nodes = []
1255
+ for (const sk of solidSketches) {
1256
+ const [w0, w1] = windowFor(sk, allowOblique)
1257
+ const regions = sk.regions
1258
+ if (!regions?.length) {
1259
+ // no region could be solved (an open wire): legacy single-profile solid
1260
+ nodes.push(new Prism(sk.plane, sk.profiles, w0, w1))
1261
+ continue
1262
+ }
1263
+ // Every region without holes is still ONE prism with several profiles —
1264
+ // the same tree as before, so unnested sketches are unchanged. A region
1265
+ // with holes is the exact boolean it means: outer prism minus a prism
1266
+ // unioning its holes. Islands (regions inside a hole) stay separate.
1267
+ const plain = []
1268
+ const holey = []
1269
+ for (const r of regions) (r.holes.length ? holey : plain).push(r)
1270
+ if (plain.length) nodes.push(new Prism(sk.plane, plain.map((r) => r.outer), w0, w1))
1271
+ for (const r of holey) {
1272
+ nodes.push(new Diff(new Prism(sk.plane, [r.outer], w0, w1),
1273
+ new Prism(sk.plane, r.holes, w0, w1)))
1274
+ }
1275
+ }
1276
+ node = nodes[0]
1277
+ for (let i = 1; i < nodes.length; i++) node = new Union(node, nodes[i])
1278
+ }
1279
+ const solid = new Solid(node)
1280
+ this.scene.add(solid)
1281
+ const key = String(ident)
1282
+ if (!this.scene.registry[key]) this.scene.registry[key] = []
1283
+ this.scene.registry[key].push(solid)
1284
+ return null
1285
+ }
1286
+
1287
+ #opRevolve(args) {
1288
+ const ident = args[1]
1289
+ const d = args[2]
1290
+ const sk = this.#firstSketch(d.get('entities'), null)
1291
+ const axis = d.get('axis')
1292
+ if (!(axis instanceof Line)) throw new FsError('opRevolve needs a Line axis')
1293
+ const profiles = [...(sk.profiles ?? [])]
1294
+ if (!profiles.length) throw new FsError('opRevolve needs a closed profile')
1295
+ const angQ = d.get('angle')
1296
+ const ang = angQ instanceof Q ? angQ.rad() : (angQ != null ? +angQ : 2 * Math.PI)
1297
+ const solid = new Solid(new Revolve(sk.plane, profiles[0], axis.o, axis.d, ang))
1298
+ this.scene.add(solid)
1299
+ const key = String(ident)
1300
+ if (!this.scene.registry[key]) this.scene.registry[key] = []
1301
+ this.scene.registry[key].push(solid)
1302
+ return null
1303
+ }
1304
+
1305
+ #opBoolean(args) {
1306
+ const d = args[2]
1307
+ // A boolean operates on live bodies only. Consumed (dead) bodies still sit
1308
+ // in qCreatedBy/qUnion results, but must not be re-tooled or re-targeted:
1309
+ // without this, pipeLib's "union all bores, then subtract" ran the subtract
1310
+ // once per (now-dead) bore as well, nesting redundant Diffs.
1311
+ const tools = d.get('tools').solids.filter((s) => s.alive)
1312
+ const targets = d.get('targets').solids.filter((s) => s.alive)
1313
+ const op = d.get('operationType') ?? 'BooleanOperationType.UNION'
1314
+ if (!targets.length) throw new FsError('boolean with no target bodies')
1315
+ if (op === 'BooleanOperationType.UNION') {
1316
+ // Onshape collapses a union into one resulting body: everything is
1317
+ // merged into the first target (this is also the "tools == targets"
1318
+ // merge-everything idiom). Disjoint lumps stay disjoint geometry.
1319
+ const keep = targets[0]
1320
+ const seen = new Set([keep])
1321
+ let node = keep.node
1322
+ for (const s of [...targets.slice(1), ...tools]) {
1323
+ if (seen.has(s)) continue
1324
+ seen.add(s)
1325
+ node = new Union(node, s.node)
1326
+ s.alive = false
1327
+ }
1328
+ keep.node = node
1329
+ return null
1330
+ }
1331
+ const toolNodes = tools.map((t) => t.node)
1332
+ for (const tgt of targets) {
1333
+ for (const tn of toolNodes) {
1334
+ if (op === 'BooleanOperationType.SUBTRACTION') tgt.node = new Diff(tgt.node, tn)
1335
+ else if (op === 'BooleanOperationType.INTERSECTION') tgt.node = new Isect(tgt.node, tn)
1336
+ }
1337
+ }
1338
+ // a body that is both a target and a tool survives
1339
+ const targetSet = new Set(targets)
1340
+ for (const t of tools) {
1341
+ if (!targetSet.has(t)) t.alive = false
1342
+ }
1343
+ return null
1344
+ }
1345
+
1346
+ #opPattern(args) {
1347
+ const ident = args[1]
1348
+ const d = args[2]
1349
+ const entities = d.get('entities')
1350
+ const xfs = d.get('transforms')
1351
+ const made = []
1352
+ for (const base of entities.solids) {
1353
+ for (const xf of xfs) {
1354
+ const s = new Solid(new Moved(base.node, xf), base.name, base.color)
1355
+ this.scene.add(s)
1356
+ made.push(s)
1357
+ }
1358
+ }
1359
+ const key = String(ident)
1360
+ if (!this.scene.registry[key]) this.scene.registry[key] = []
1361
+ this.scene.registry[key].push(...made)
1362
+ return null
1363
+ }
1364
+
1365
+ #opTransform(args) {
1366
+ const d = args[2]
1367
+ const xf = d.get('transform')
1368
+ for (const s of d.get('bodies').solids) {
1369
+ s.node = new Moved(s.node, xf)
1370
+ }
1371
+ return null
1372
+ }
1373
+
1374
+ #opDelete(args) {
1375
+ const d = args[2]
1376
+ for (const s of d.get('entities').solids) s.alive = false
1377
+ return null
1378
+ }
1379
+
1380
+ /**
1381
+ * `opFillet(context, id, { entities, radius, direction? })` / `opChamfer(…)` — round or cut
1382
+ * the selected bodies' edges.
1383
+ *
1384
+ * The engine records an edge-modifier node around each target body's CSG tree; the exact
1385
+ * kernel translates it, so nothing here touches geometry. A positive radius/distance is
1386
+ * required (a silent no-op fillet is worse than a typed error), and an optional world
1387
+ * `direction` restricts the operation to edges parallel to it — the workbench's "all edges /
1388
+ * vertical / horizontal" option.
1389
+ */
1390
+ #opEdgeModifier(args, kind) {
1391
+ const d = args[2]
1392
+ const size = d.get(kind === 'fillet' ? 'radius' : 'distance')
1393
+ const amount = size instanceof Q ? size.v : +size
1394
+ const label = kind === 'fillet' ? 'fillet radius' : 'chamfer distance'
1395
+ if (!(amount > 0)) throw new FsError(`${kind} needs a positive ${label}`, null, null, this.source)
1396
+ const entities = d.get('entities')
1397
+ const solids = (entities?.solids ?? []).filter((s) => s.alive)
1398
+ if (!solids.length) throw new FsError(`${kind} needs at least one body`, null, null, this.source)
1399
+ const direction = this.#edgeDirection(d.get('direction'))
1400
+ for (const s of solids) {
1401
+ s.node = kind === 'fillet' ? new Fillet(s.node, amount, direction) : new Chamfer(s.node, amount, direction)
1402
+ }
1403
+ return null
1404
+ }
1405
+
1406
+ /**
1407
+ * `opShell(context, id, { entities, thickness, opening })` — hollow the selected bodies.
1408
+ *
1409
+ * The engine records a `Shell` marker around each target body's CSG tree; the exact kernel
1410
+ * performs the OCCT thick-solid offset. A positive wall thickness is required, and `opening`
1411
+ * names the planar face group removed to open the shell (`top`/`bottom`/`x`/`y`).
1412
+ */
1413
+ #opShell(args) {
1414
+ const d = args[2]
1415
+ const size = d.get('thickness')
1416
+ const thickness = size instanceof Q ? size.v : +size
1417
+ if (!(thickness > 0)) throw new FsError('shell needs a positive wall thickness', null, null, this.source)
1418
+ const entities = d.get('entities')
1419
+ const solids = (entities?.solids ?? []).filter((s) => s.alive)
1420
+ if (!solids.length) throw new FsError('shell needs at least one body', null, null, this.source)
1421
+ const rawOpening = d.get('opening')
1422
+ const opening = rawOpening == null ? 'top' : String(rawOpening)
1423
+ if (!['top', 'bottom', 'x', 'y'].includes(opening)) {
1424
+ throw new FsError(`unsupported shell opening '${opening}' (use top, bottom, x or y)`, null, null, this.source)
1425
+ }
1426
+ for (const s of solids) s.node = new Shell(s.node, thickness, opening)
1427
+ return null
1428
+ }
1429
+
1430
+ /**
1431
+ * `opLoft(context, id, { entities })` — loft through two or more sketch profiles.
1432
+ *
1433
+ * `entities` is a union of the sketches' face queries, so the sketches arrive on the query
1434
+ * result in the order the model authored them. Each section takes that sketch's outer profile
1435
+ * (the first closed region, or its legacy flat profile) and keeps its own plane, so profiles on
1436
+ * parallel planes at different offsets loft correctly.
1437
+ */
1438
+ #opLoft(args) {
1439
+ const d = args[2]
1440
+ const sel = d.get('entities')
1441
+ const sketches = sel?.sketches ?? []
1442
+ if (sketches.length < 2) {
1443
+ throw new FsError('loft needs at least two sketch profiles', null, null, this.source)
1444
+ }
1445
+ const sections = []
1446
+ for (const sk of sketches) {
1447
+ const profile = sk.regions?.length ? sk.regions[0].outer : sk.profiles?.[0] ?? null
1448
+ if (!profile) throw new FsError('loft section sketch has no closed profile', null, null, this.source)
1449
+ sections.push({ plane: sk.plane, profiles: [profile] })
1450
+ }
1451
+ const solid = new Solid(new Loft(sections))
1452
+ this.scene.add(solid)
1453
+ const key = String(args[1])
1454
+ if (!this.scene.registry[key]) this.scene.registry[key] = []
1455
+ this.scene.registry[key].push(solid)
1456
+ return null
1457
+ }
1458
+
1459
+ /** Sample one closed profile into a list of 2D points (the sketch plane's coordinates). */
1460
+ #profilePoints(profile) {
1461
+ if (profile instanceof Poly2) return profile.pts.map((p) => [p[0], p[1]])
1462
+ if (profile instanceof Rect2) {
1463
+ const [[x0, y0], [x1, y1]] = profile.bbox()
1464
+ return [[x0, y0], [x1, y0], [x1, y1], [x0, y1]]
1465
+ }
1466
+ if (profile instanceof Circle2) {
1467
+ const points = []
1468
+ for (let i = 0; i < 32; i++) {
1469
+ const angle = (i / 32) * Math.PI * 2
1470
+ points.push([profile.c[0] + Math.cos(angle) * profile.r, profile.c[1] + Math.sin(angle) * profile.r])
1471
+ }
1472
+ return points
1473
+ }
1474
+ return null
1475
+ }
1476
+
1477
+ /**
1478
+ * `opSweep(context, id, { profiles, path })` — sweep a profile sketch along a path sketch.
1479
+ *
1480
+ * The `profiles` query supplies the closed section sketch and the `path` query the sketch whose
1481
+ * chained contour becomes the sweep spine (the sketch model closes a chained contour, so the path
1482
+ * is a loop). Both keep their own sketch planes, so the profile can sit normal to the path start.
1483
+ */
1484
+ #opSweep(args) {
1485
+ const d = args[2]
1486
+ const profilesSel = d.get('profiles')
1487
+ const pathSel = d.get('path')
1488
+ const profileSketch = profilesSel?.sketches?.[0] ?? null
1489
+ const pathSketch = pathSel?.sketches?.[0] ?? null
1490
+ if (!profileSketch) throw new FsError('sweep needs a profile sketch', null, null, this.source)
1491
+ if (!pathSketch) throw new FsError('sweep needs a path sketch', null, null, this.source)
1492
+ const profile = profileSketch.regions?.length ? profileSketch.regions[0].outer : profileSketch.profiles?.[0] ?? null
1493
+ if (!profile) throw new FsError('sweep profile sketch has no closed profile', null, null, this.source)
1494
+ const pathProfile = pathSketch.regions?.length ? pathSketch.regions[0].outer : pathSketch.profiles?.[0] ?? null
1495
+ const path = pathProfile ? this.#profilePoints(pathProfile) : null
1496
+ if (!path || path.length < 3) throw new FsError('sweep path sketch has no path contour', null, null, this.source)
1497
+ const solid = new Solid(new Sweep(profile, profileSketch.plane, path, pathSketch.plane))
1498
+ this.scene.add(solid)
1499
+ const key = String(args[1])
1500
+ if (!this.scene.registry[key]) this.scene.registry[key] = []
1501
+ this.scene.registry[key].push(solid)
1502
+ return null
1503
+ }
1504
+
1505
+ /** Read an optional `direction` value into a unit world vector (or null for "all edges"). */
1506
+ #edgeDirection(value) {
1507
+ if (value == null) return null
1508
+ const v = value instanceof Vec ? value.comps() : value
1509
+ if (!Array.isArray(v) || v.length !== 3) return null
1510
+ const n = Math.hypot(v[0], v[1], v[2])
1511
+ if (!(n > 1e-12)) return null
1512
+ return [v[0] / n, v[1] / n, v[2] / n]
1513
+ }
1514
+
1515
+ #setProperty(args) {
1516
+ const d = args[1]
1517
+ const pt = d.get('propertyType')
1518
+ const val = d.get('value')
1519
+ for (const s of d.get('entities').solids) {
1520
+ if (pt === 'PropertyType.NAME') s.name = val
1521
+ else if (pt === 'PropertyType.APPEARANCE') s.color = val
1522
+ }
1523
+ return null
1524
+ }
1525
+ }
1526
+
1527
+ // ---------------------------------------------------------------------------
1528
+ // driver
1529
+ // ---------------------------------------------------------------------------
1530
+
1531
+ /** --param bedDepth=1000mm / --param includeMedia=false → typed values. */
1532
+ export function parseOverrides(pairs) {
1533
+ const out = new Map()
1534
+ for (const p of pairs ?? []) {
1535
+ if (!p.includes('=')) throw new FsError(`--param needs name=value, got '${p}'`)
1536
+ const eq = p.indexOf('=')
1537
+ const k = p.slice(0, eq).trim()
1538
+ const v = p.slice(eq + 1).trim()
1539
+ out.set(k, parseValue(v))
1540
+ }
1541
+ return out
1542
+ }
1543
+
1544
+ export function parseValue(text) {
1545
+ const low = text.toLowerCase()
1546
+ if (low === 'true' || low === 'false') return low === 'true'
1547
+ for (const [suffix, dim, scale] of [['mm', LEN, 1], ['millimeter', LEN, 1],
1548
+ ['cm', LEN, 10], ['m', LEN, 1000], ['deg', ANG, Math.PI / 180],
1549
+ ['degree', ANG, Math.PI / 180]]) {
1550
+ if (low.endsWith(suffix)) {
1551
+ const head = low.slice(0, -suffix.length).trim()
1552
+ const val = Number(head)
1553
+ if (!Number.isNaN(val) && head !== '' && /^[+-]?[\d.]+([eE][+-]?\d+)?$/.test(head)) {
1554
+ return new Q(val * scale, dim)
1555
+ }
1556
+ break
1557
+ }
1558
+ }
1559
+ const n = Number(text)
1560
+ if (!Number.isNaN(n) && text.trim() !== '') return new Q(n, ONE)
1561
+ return text
1562
+ }
1563
+
1564
+ /**
1565
+ * Paste library sources in front of a module.
1566
+ *
1567
+ * `import()` of another Feature Studio is a no-op in this interpreter, so a
1568
+ * thin module that only consumes a library carries undefined identifiers.
1569
+ * The parser already skips repeated `FeatureScript` / `import(...)` header
1570
+ * lines, so an included library file is used verbatim. Line numbers in
1571
+ * diagnostics refer to the concatenation.
1572
+ *
1573
+ * This takes the library SOURCE text (not file paths),
1574
+ * STRINGS — callers read the files (Node tests) or fetch them (browser).
1575
+ */
1576
+ export function applyIncludes(source, includes) {
1577
+ if (!includes || !includes.length) return source
1578
+ const prelude = []
1579
+ for (const inc of includes) {
1580
+ prelude.push(`// ===== included: ${inc.name ?? 'library'} =====\n${inc.source}`)
1581
+ }
1582
+ return prelude.join('\n') + '\n' + source
1583
+ }
1584
+
1585
+ export function runFeature(source, featureName = null, overrides = null,
1586
+ { verbose = false, includes = null, sourceName = 'module', trace = false, stopAfter = null } = {}) {
1587
+ source = applyIncludes(source, includes)
1588
+ const interp = new Interp(sourceName, verbose, { trace, rollbackAt: stopAfter })
1589
+ const stmts = parse(source, sourceName)
1590
+ interp.run(stmts)
1591
+ if (!interp.features.size) {
1592
+ throw new FsError('no custom feature found (no defineFeature in the module)')
1593
+ }
1594
+ if (featureName === null) featureName = [...interp.features.keys()][0]
1595
+ if (!interp.features.has(featureName)) {
1596
+ throw new FsError(`no feature named '${featureName}'; have ` +
1597
+ `${JSON.stringify([...interp.features.keys()])}`)
1598
+ }
1599
+ const feat = interp.features.get(featureName)
1600
+ const definition = new Map(feat.defaults)
1601
+ for (const [k, v] of overrides ?? []) {
1602
+ if (!definition.has(k)) {
1603
+ throw new FsError(`unknown parameter '${k}'; try one of ` +
1604
+ `${JSON.stringify([...definition.keys()])}`)
1605
+ }
1606
+ definition.set(k, v)
1607
+ }
1608
+ const callArgs = [interp.context, new Id(['feature']), definition]
1609
+ let rolledBack = false
1610
+ try {
1611
+ interp.callFunclit(feat.funclit, callArgs, interp.moduleEnv ?? interp.globalEnv, feat.line)
1612
+ } catch (error) {
1613
+ if (!(error instanceof RollbackSignal)) throw error
1614
+ rolledBack = true
1615
+ }
1616
+ return {
1617
+ /** True when evaluation stopped at \`stopAfter\` (a rollback view). */
1618
+ rolledBack,
1619
+ interp,
1620
+ feature: feat,
1621
+ definition,
1622
+ /** Feature-history entries in execution order (empty unless `trace` was requested). */
1623
+ trace: interp.tracer ? interp.tracer.toJSON() : [],
1624
+ }
1625
+ }
1626
+
1627
+ /**
1628
+ * Run an assembly document.
1629
+ *
1630
+ * The program is ordinary FeatureScript plus two host operations: `instance(context, id, {…})`
1631
+ * records one placed occurrence and `part(name, hash?)` builds a pinned part reference. It may
1632
+ * call `instance` at the top level or declare one assembly with `defineAssembly(function(context
1633
+ * is AssemblyContext, id is Id) { … })`.
1634
+ *
1635
+ * Placement is rigid (translation + rotation about X/Y/Z). Mates are a constraint solve and are
1636
+ * intentionally not part of the program — see docs/CAD.md §2.2 and the assembly section.
1637
+ *
1638
+ * @param {string} source Assembly program text.
1639
+ * @param {{ includes?: Array<{name?: string, source: string}>|null, sourceName?: string, trace?: boolean }} [options]
1640
+ * @returns {{ interp: Interp, scene: AssemblyScene, trace: object[], notes: string[] }}
1641
+ */
1642
+ export function runAssembly(source, { includes = null, sourceName = 'assembly', trace = true } = {}) {
1643
+ source = applyIncludes(source, includes)
1644
+ const interp = new Interp(sourceName, false, { trace })
1645
+ const scene = new AssemblyScene()
1646
+ interp.defineHostBuiltin('instance', (args) => {
1647
+ scene.add({ id: args[1], definition: args[2] })
1648
+ return null
1649
+ })
1650
+ interp.defineHostBuiltin('part', (args) => new Map([
1651
+ ['name', String(args[0])],
1652
+ ['hash', args[1] == null ? null : String(args[1])],
1653
+ ]))
1654
+ // Host op: re-place one already-recorded instance. The CAD workbench's assembly gizmo
1655
+ // compiles a drag to this statement, so placement edits stay diffable source (docs/CAD.md §7).
1656
+ // Accepts the instance runtime id path or its display name, and replaces (not composes) the
1657
+ // placement recorded by the program.
1658
+ interp.defineHostBuiltin('instanceTransform', (args) => {
1659
+ const definition = args[2] instanceof Map ? args[2] : new Map()
1660
+ const key = definition.get('id') ?? definition.get('name')
1661
+ if (key == null) throw new FsError('instanceTransform needs an id or name')
1662
+ const text = String(key)
1663
+ const match = scene.instances.find((instance) => instance.id === text || instance.name === text)
1664
+ if (!match) throw new FsError(`instanceTransform: no instance '${text}'`)
1665
+ match.xf = transformFromValue(definition.get('transform') ?? definition.get('placement'))
1666
+ return null
1667
+ })
1668
+ // Host op: set the surface material of one already-recorded instance. The CAD workbench's
1669
+ // material picker compiles a colour change to this statement, so finishes stay diffable source
1670
+ // (docs/CAD.md §7). Accepts the instance runtime id path or its display name.
1671
+ interp.defineHostBuiltin('instanceMaterial', (args) => {
1672
+ const definition = args[2] instanceof Map ? args[2] : new Map()
1673
+ const key = definition.get('id') ?? definition.get('name')
1674
+ if (key == null) throw new FsError('instanceMaterial needs an id or name')
1675
+ const material = materialFromValue(definition)
1676
+ if (!scene.setMaterial(String(key), material)) {
1677
+ throw new FsError(`instanceMaterial: no instance '${String(key)}'`)
1678
+ }
1679
+ return null
1680
+ })
1681
+ // Host op: record an inline pipe run (a straight tube between two world points). The CAD
1682
+ // workbench compiles a picked port-to-port connection to this statement, so a pipe is diffable
1683
+ // source exactly like an instance (docs/CAD.md §7). Geometry is world-millimetre, not a part ref.
1684
+ interp.defineHostBuiltin('pipe', (args) => {
1685
+ const definition = args[2] instanceof Map ? args[2] : new Map()
1686
+ scene.addPipe({ id: args[1], definition })
1687
+ return null
1688
+ })
1689
+ // Host op: record an inline terrain mesh (a DEM heightfield). The map picker compiles a picked
1690
+ // site to this statement, so terrain is diffable source like a pipe or instance. Heights are in
1691
+ // metres; the kernel's `buildDemMesh` turns the grid into a closed heightfield in millimetres.
1692
+ interp.defineHostBuiltin('terrain', (args) => {
1693
+ const definition = args[2] instanceof Map ? args[2] : new Map()
1694
+ scene.addTerrain({ id: args[1], definition })
1695
+ return null
1696
+ })
1697
+ interp.defineHostBuiltin('defineAssembly', (args) => {
1698
+ let funclit = args[0]
1699
+ if (Array.isArray(funclit) && funclit[0] === 'funclit') funclit = funclit[1]
1700
+ interp.assemblyFeature = funclit
1701
+ return funclit
1702
+ })
1703
+ // The assembly context and root id are host-provided values, exactly like `context`/`id`
1704
+ // parameters inside a part feature.
1705
+ interp.globalEnv.declare('context', scene)
1706
+ interp.globalEnv.declare('id', new Id(['assembly']))
1707
+ interp.run(parse(source, sourceName))
1708
+ if (interp.assemblyFeature) {
1709
+ interp.callFunclit(interp.assemblyFeature, [scene, new Id(['assembly']), new Map()],
1710
+ interp.moduleEnv ?? interp.globalEnv, interp.assemblyFeature.line)
1711
+ }
1712
+ return { interp, scene, trace: interp.tracer ? interp.tracer.toJSON() : [], notes: interp.notes }
1713
+ }