@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TheTechCompany
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,135 @@
1
- # Temporary Holding Version
1
+ # `@indispec/fs-compat`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **FeatureScript-compatible for a documented subset.** A dependency-free lexer, parser, value model
4
+ and interpreter for the FeatureScript language, in plain ESM. No native modules, no build step, no
5
+ dependencies — it runs unchanged in Node (≥ 20) and in a browser worker.
6
+
7
+ The interpreter evaluates a `.fs` module and **records** the geometry it builds as a typed node tree
8
+ (`Box`, `Prism`, `Revolve`, `Union`, `Diff`, `Isect`, `Moved`, `Fillet`, `Loft`, `Sweep`, …). It is
9
+ not a geometry kernel: translating that tree into exact B-rep is a separate concern.
10
+
11
+ > **Status: experimental (0.x).** This is not yet a compatibility promise. The supported subset is
12
+ > real and tested, but the gaps are listed below rather than papered over — and the highest tier,
13
+ > *geometric identity* (same sketch and features producing the same faces as Onshape), is **not
14
+ > claimed**.
15
+
16
+ ## Install
17
+
18
+ ```bash
19
+ npm install @indispec/fs-compat
20
+ ```
21
+
22
+ ## Quickstart
23
+
24
+ ```js
25
+ import { runFeature } from '@indispec/fs-compat'
26
+
27
+ const source = `
28
+ annotation { "Feature Type Name" : "Bound plate" }
29
+ export const boundPlate = defineFeature(function(context is Context, id is Id, definition is map)
30
+ precondition
31
+ {
32
+ annotation { "Name" : "Plate length" }
33
+ isLength(definition.plateLen, { (millimeter) : [60, 120, 240] });
34
+ }
35
+ {
36
+ var plateLen = definition.plateLen / millimeter;
37
+ var sk = newSketchOnPlane(context, id + "sk", {
38
+ "sketchPlane" : plane(coordSystem(vector(0, 0, 0) * millimeter, vector(1, 0, 0), vector(0, 0, 1)))
39
+ });
40
+ skCircle(sk, "c", { "center" : vector(0, 0), "radius" : 10 * millimeter });
41
+ skSolve(sk);
42
+ opExtrude(context, id + "ex", {
43
+ "entities" : qCreatedBy(id + "sk", EntityType.FACE),
44
+ "direction" : vector(0, 0, 1),
45
+ "endBound" : BoundingType.BLIND,
46
+ "endDepth" : plateLen * millimeter
47
+ });
48
+ }
49
+ );
50
+ `
51
+
52
+ const { interp, trace } = runFeature(source, null, null, { trace: true, sourceName: 'plate.fs' })
53
+
54
+ interp.scene.solids.length // 1 recorded solid
55
+ trace.find((entry) => entry.op === 'opExtrude').definition // the invocation's definition
56
+ .endDepth.value // 120 (mm, the authored default)
57
+ ```
58
+
59
+ ### Bind parameters without rewriting the source
60
+
61
+ The committed program keeps its authored defaults — so it stays portable and valid FeatureScript
62
+ elsewhere — while evaluation runs with values bound from outside:
63
+
64
+ ```js
65
+ import { runFeature, parseOverrides } from '@indispec/fs-compat'
66
+
67
+ runFeature(source, null, parseOverrides(['plateLen=240mm'])) // endDepth is now 240
68
+ runFeature(source, null, parseOverrides(['plateLen=12cm'])) // 120 — units are carried
69
+ ```
70
+
71
+ Values use the engine's own value grammar. An unknown parameter name is an error, never a silent
72
+ ignore.
73
+
74
+ ## What you get
75
+
76
+ | Export | Purpose |
77
+ |---|---|
78
+ | `parse(source, sourceName?)` | AST; every node carries an absolute source span |
79
+ | `runFeature(source, featureName?, overrides?, options?)` | Evaluate one custom feature; returns `{ interp, feature, definition, trace, rolledBack }` |
80
+ | `runAssembly(source, ...)` | Record an assembly (instances + placements) instead of solids |
81
+ | `parseOverrides(pairs)` | `name=value` texts → typed values |
82
+ | `scene`, `Solid`, `Node`, geometry classes | The recorded node tree a kernel translates |
83
+ | `sketchRegions`, `regionPolygon`, `regionArea`, … | Sketch topology: contours chained into closed regions with holes |
84
+ | `projectFeatureList`, `projectAssemblyList`, `assemblyBom` | The authored feature tree / BOM derived from the execution trace |
85
+ | `Q`, `Xf`, `Plane`, `Id`, `Color`, `Vec` | The value model (millimetres, radians) |
86
+
87
+ `options.trace` records one entry per feature-producing call with its runtime id path, its source
88
+ span, the call frames that produced it and a snapshot of its definition — which is what an editor's
89
+ feature tree is derived from. `options.stopAfter` stops after N recorded features, for a rollback
90
+ view.
91
+
92
+ Implemented host operations include sketch creation (`newSketchOnPlane`/`skSolve`, lines, arcs,
93
+ circles), `opExtrude` (new/add/remove/intersect, including planar-face profiles), `opBoolean`,
94
+ `opPattern`, `opTransform`, `opDeleteBodies`, `opFillet`, `opChamfer`, `opShell`, `opLoft`,
95
+ `opSweep`, `setProperty`, `reportFeature*`, and assembly composition (`instance`, `part`).
96
+
97
+ ## Known gaps
98
+
99
+ These are the **silent** divergences from the reference semantics — the cases where the interpreter
100
+ does something rather than refusing. They are the reason the compatibility claim is not made yet.
101
+
102
+ - **`endBound` is ignored.** Only `BLIND` is honoured; `UP_TO_*` extrudes are treated as blind.
103
+ - **`opRevolve` uses only the first profile** in a sketch; the rest are dropped.
104
+ - **`is` is permissive and `as` is an identity cast.** `is` returns true for any non-boolean value.
105
+ - **`precondition` predicates are not evaluated.** `isLength`, `isNumber`, … all report satisfied; only
106
+ parameter defaults are read from the precondition block.
107
+ - **`setProperty` honours `NAME` and `APPEARANCE` only**, and silently drops other property types.
108
+ - **`import()` is a no-op.** Libraries are prepended textually by `applyIncludes`, so line numbers in
109
+ diagnostics shift relative to the original file.
110
+ - **No FeatureScript standard library is bundled.** Calls into it must be supplied through
111
+ `options.includes`, or they raise an unsupported-function error.
112
+ - There is no B-rep, no tessellation and no geometric-identity guarantee.
113
+
114
+ Syntax and runtime errors do carry a line, column, an absolute span and the source name.
115
+
116
+ ## Development
117
+
118
+ ```bash
119
+ node --test test/*.test.mjs # 46 tests, no dependencies
120
+ ```
121
+
122
+ ## Provenance and license
123
+
124
+ MIT — see [LICENSE](LICENSE).
125
+
126
+ The engine originated in the `featurescript-studio` project (itself split out of `nitrate-producer`)
127
+ and was extracted into the IndiSpec monorepo. Two deliberate departures from that origin: the
128
+ geometry kernel is not included (only the recorded node tree), and the GLSL emitter, clip algebra and
129
+ tessellation code are not carried over.
130
+
131
+ No third-party code is bundled. The FeatureScript standard library is *not* included; when it is
132
+ vendored it is MIT-licensed (© PTC Inc.) and its notice will ship with it.
133
+
134
+ FeatureScript and Onshape are trademarks of PTC Inc. This project is not affiliated with or endorsed
135
+ by PTC.
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@indispec/fs-compat",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "FeatureScript-compatible lexer, parser, value model and interpreter for a documented language subset.",
5
+ "license": "MIT",
6
+ "author": "TheTechCompany",
7
+ "type": "module",
8
+ "main": "src/index.js",
9
+ "types": "src/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./src/index.d.ts",
13
+ "default": "./src/index.js"
14
+ }
15
+ },
16
+ "files": [
17
+ "src/"
18
+ ],
19
+ "sideEffects": false,
20
+ "engines": {
21
+ "node": ">=20"
22
+ },
23
+ "keywords": [
24
+ "featurescript",
25
+ "cad",
26
+ "parametric",
27
+ "interpreter",
28
+ "parser",
29
+ "lexer",
30
+ "b-rep",
31
+ "language"
32
+ ],
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "git+https://github.com/TheTechCompany/IndiSpec.git",
36
+ "directory": "packages/cad/featurescript"
37
+ },
38
+ "homepage": "https://github.com/TheTechCompany/IndiSpec/tree/main/packages/cad/featurescript",
39
+ "bugs": {
40
+ "url": "https://github.com/TheTechCompany/IndiSpec/issues"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "scripts": {
46
+ "test": "node --test test/*.test.mjs",
47
+ "prepublishOnly": "node --test test/*.test.mjs"
48
+ }
49
+ }
@@ -0,0 +1,481 @@
1
+ // Assembly document recording.
2
+ //
3
+ // An assembly is a *composition*, not a parametric part: instances of other documents plus
4
+ // their placement. It is still authored as code — the same parser and interpreter run the
5
+ // assembly program, with a different host operation set (`instance`, `part`) and a recorder
6
+ // that collects placements instead of solids (docs/CAD.md §2.2, "one document = one part";
7
+ // assemblies are the second document kind).
8
+ //
9
+ // References are never paths or "latest": an instance names a part through a {@link PartRef}
10
+ // that the document layer resolves from its pinned payload. Source text may *name* a
11
+ // reference; it may not *contain* one.
12
+ //
13
+ // This module is pure (values only, no interpreter import), so the worker and unit tests can
14
+ // use it directly. Placement is restricted to rigid transforms: translation plus rotation
15
+ // about X/Y/Z. Mates are a constraint solve and deliberately do not live in the program.
16
+
17
+ import { Xf } from './values.js';
18
+
19
+ /** A reference to a part document, pinned by content hash when available. */
20
+ export class PartRef {
21
+ /**
22
+ * @param {string} name Logical part name (the document title or a label in the source).
23
+ * @param {{ page?: string|null, hash?: string|null }} [options] Document/page id and content hash.
24
+ */
25
+ constructor(name, { page = null, hash = null } = {}) {
26
+ /** Logical name used as the BOM line and tree label. */
27
+ this.name = name;
28
+ /** Page/document id the shell resolves to a source, when pinned. */
29
+ this.page = page;
30
+ /** Content hash of the part source at authoring time (pinning / staleness check). */
31
+ this.hash = hash;
32
+ }
33
+ }
34
+
35
+ /** One placed instance in an assembly. */
36
+ export class AssemblyInstance {
37
+ /**
38
+ * @param {object} init Instance fields.
39
+ */
40
+ constructor(init) {
41
+ /** Execution order (0-based). */
42
+ this.seq = init.seq;
43
+ /** Runtime id path, e.g. `assembly/ring1`. */
44
+ this.id = init.id;
45
+ /** `id` split into segments. */
46
+ this.path = init.path;
47
+ /** Display label. */
48
+ this.name = init.name;
49
+ /** The referenced part. */
50
+ this.part = init.part;
51
+ /** Rigid placement: 3x3 rotation matrix (row-major) plus translation in mm. */
52
+ this.xf = init.xf;
53
+ /** Serialised definition map, for the inspector. */
54
+ this.definition = init.definition;
55
+ /**
56
+ * Optional authored surface material (`{ color: [r,g,b], metallic, roughness }`), or null.
57
+ * Set by the `instanceMaterial` host op and composed by the kernel.
58
+ */
59
+ this.material = init.material ?? null;
60
+ }
61
+ }
62
+
63
+ /** The recorded composition for one assembly evaluation. */
64
+ export class AssemblyScene {
65
+ constructor() {
66
+ /** @type {AssemblyInstance[]} */
67
+ this.instances = [];
68
+ /** @type {Array<object>} Inline pipe runs (`pipe(...)` host op), placed in world millimetres. */
69
+ this.pipes = [];
70
+ /** @type {Array<object>} Inline terrain meshes (`terrain(...)` host op), heights in metres. */
71
+ this.terrains = [];
72
+ /** Non-fatal notes raised by the program (`reportFeatureInfo` etc.). */
73
+ this.notes = [];
74
+ }
75
+
76
+ /**
77
+ * Add one instance.
78
+ *
79
+ * @param {{ id: unknown, definition: unknown }} init Runtime `Id` and definition map.
80
+ * @returns {AssemblyInstance} The recorded instance.
81
+ */
82
+ add({ id, definition }) {
83
+ const path = id && typeof id.toString === 'function' ? id.toString().split('/') : [];
84
+ const def = definition instanceof Map ? definition : new Map();
85
+ const part = partRefFromValue(def.get('part')) ?? new PartRef('(unspecified part)');
86
+ const xf = transformFromValue(def.get('transform') ?? def.get('placement'));
87
+ const name = def.get('name') != null ? String(def.get('name')) : part.name;
88
+ const instance = new AssemblyInstance({
89
+ seq: this.instances.length,
90
+ id: path.join('/') || null,
91
+ path,
92
+ name,
93
+ part,
94
+ xf,
95
+ definition: serializeDefinition(def),
96
+ });
97
+ this.instances.push(instance);
98
+ return instance;
99
+ }
100
+
101
+ /**
102
+ * Add one inline pipe run.
103
+ *
104
+ * @param {{ id: unknown, definition: unknown }} init Runtime `Id` and definition map.
105
+ * @returns {object} The recorded pipe run.
106
+ */
107
+ addPipe({ id, definition }) {
108
+ const path = id && typeof id.toString === 'function' ? id.toString().split('/') : [];
109
+ const def = definition instanceof Map ? definition : new Map();
110
+ const pipe = pipeFromValue(def);
111
+ const record = {
112
+ seq: this.pipes.length,
113
+ id: path.join('/') || null,
114
+ path,
115
+ name: pipe.name,
116
+ start: pipe.start,
117
+ end: pipe.end,
118
+ outerRadiusMm: pipe.outerRadiusMm,
119
+ innerRadiusMm: pipe.innerRadiusMm,
120
+ definition: serializeDefinition(def),
121
+ };
122
+ this.pipes.push(record);
123
+ return record;
124
+ }
125
+
126
+ /** Live instance count. */
127
+ count() {
128
+ return this.instances.length;
129
+ }
130
+
131
+ /** Live inline-pipe count. */
132
+ pipeCount() {
133
+ return this.pipes.length;
134
+ }
135
+
136
+ /**
137
+ * Add one inline terrain mesh.
138
+ *
139
+ * @param {{ id: unknown, definition: unknown }} init Runtime `Id` and definition map.
140
+ * @returns {object} The recorded terrain.
141
+ */
142
+ addTerrain({ id, definition }) {
143
+ const path = id && typeof id.toString === 'function' ? id.toString().split('/') : [];
144
+ const def = definition instanceof Map ? definition : new Map();
145
+ const terrain = terrainFromValue(def);
146
+ const record = {
147
+ seq: this.terrains.length,
148
+ id: path.join('/') || null,
149
+ path,
150
+ name: terrain.name,
151
+ heights: terrain.heights,
152
+ columns: terrain.columns,
153
+ rows: terrain.rows,
154
+ extentXmm: terrain.extentXmm,
155
+ extentYmm: terrain.extentYmm,
156
+ originXmm: terrain.originXmm,
157
+ originYmm: terrain.originYmm,
158
+ originZmm: terrain.originZmm,
159
+ site: terrain.site,
160
+ definition: serializeDefinition(def),
161
+ };
162
+ this.terrains.push(record);
163
+ return record;
164
+ }
165
+
166
+ /** Live inline-terrain count. */
167
+ terrainCount() {
168
+ return this.terrains.length;
169
+ }
170
+
171
+ /**
172
+ * Set the surface material of one recorded instance, addressed by runtime id path or display
173
+ * name. Returns false when no instance matches (the caller turns that into an error).
174
+ *
175
+ * @param {string} key Instance id path or display name.
176
+ * @param {{ color: number[], metallic: number, roughness: number }} material Authored material.
177
+ * @returns {boolean} True when an instance was updated.
178
+ */
179
+ setMaterial(key, material) {
180
+ const text = String(key);
181
+ const match = this.instances.find((instance) => instance.id === text || instance.name === text);
182
+ if (!match) return false;
183
+ match.material = material;
184
+ return true;
185
+ }
186
+
187
+ /**
188
+ * Plain-JSON view for transport to the kernel worker and the UI.
189
+ *
190
+ * @returns {Array<object>} Instances as JSON-safe objects.
191
+ */
192
+ toJSON() {
193
+ return this.instances.map((instance) => ({
194
+ seq: instance.seq,
195
+ id: instance.id,
196
+ path: instance.path,
197
+ name: instance.name,
198
+ part: { name: instance.part.name, page: instance.part.page, hash: instance.part.hash },
199
+ xf: instance.xf,
200
+ material: instance.material,
201
+ definition: instance.definition,
202
+ }));
203
+ }
204
+
205
+ /**
206
+ * Plain-JSON view of the inline pipe runs (world millimetres).
207
+ *
208
+ * @returns {Array<object>} Pipe runs as JSON-safe objects.
209
+ */
210
+ pipesToJSON() {
211
+ return this.pipes.map((pipe) => ({
212
+ seq: pipe.seq,
213
+ id: pipe.id,
214
+ name: pipe.name,
215
+ start: pipe.start,
216
+ end: pipe.end,
217
+ outerRadiusMm: pipe.outerRadiusMm,
218
+ innerRadiusMm: pipe.innerRadiusMm,
219
+ }));
220
+ }
221
+
222
+ /**
223
+ * Plain-JSON view of the inline terrain meshes (heights in metres, extents in millimetres).
224
+ *
225
+ * @returns {Array<object>} Terrain meshes as JSON-safe objects.
226
+ */
227
+ terrainsToJSON() {
228
+ return this.terrains.map((terrain) => ({
229
+ seq: terrain.seq,
230
+ id: terrain.id,
231
+ name: terrain.name,
232
+ heights: terrain.heights,
233
+ columns: terrain.columns,
234
+ rows: terrain.rows,
235
+ extentXmm: terrain.extentXmm,
236
+ extentYmm: terrain.extentYmm,
237
+ originXmm: terrain.originXmm,
238
+ originYmm: terrain.originYmm,
239
+ originZmm: terrain.originZmm,
240
+ site: terrain.site,
241
+ }));
242
+ }
243
+ }
244
+
245
+ /** Identity rotation. */
246
+ const IDENTITY3 = [
247
+ [1, 0, 0],
248
+ [0, 1, 0],
249
+ [0, 0, 1],
250
+ ];
251
+
252
+ const ORIGIN3 = [0, 0, 0];
253
+
254
+ /**
255
+ * Row-major 3x3 product.
256
+ *
257
+ * @param {number[][]} a Left matrix.
258
+ * @param {number[][]} b Right matrix.
259
+ * @returns {number[][]} `a · b`.
260
+ */
261
+ export function multiply3(a, b) {
262
+ const out = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
263
+ for (let i = 0; i < 3; i += 1) {
264
+ for (let j = 0; j < 3; j += 1) {
265
+ out[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j];
266
+ }
267
+ }
268
+ return out;
269
+ }
270
+
271
+ /**
272
+ * Rotation matrix about one axis.
273
+ *
274
+ * @param {'x'|'y'|'z'} axis Rotation axis.
275
+ * @param {number} radians Rotation angle.
276
+ * @returns {number[][]} Row-major 3x3 matrix.
277
+ */
278
+ export function rotation3(axis, radians) {
279
+ const c = Math.cos(radians);
280
+ const s = Math.sin(radians);
281
+ if (axis === 'x') return [[1, 0, 0], [0, c, -s], [0, s, c]];
282
+ if (axis === 'y') return [[c, 0, s], [0, 1, 0], [-s, 0, c]];
283
+ return [[c, -s, 0], [s, c, 0], [0, 0, 1]];
284
+ }
285
+
286
+ /**
287
+ * Read a number-ish FeatureScript value (quantity, plain number, or numeric string).
288
+ *
289
+ * @param {unknown} value Runtime value.
290
+ * @returns {number} Numeric magnitude, or 0 when unreadable.
291
+ */
292
+ function numberOf(value) {
293
+ if (value == null) return 0;
294
+ if (typeof value === 'number') return value;
295
+ if (typeof value === 'string') return Number(value) || 0;
296
+ if (typeof value === 'object' && 'v' in value) return Number(value.v) || 0;
297
+ return 0;
298
+ }
299
+
300
+ /**
301
+ * Read a 3D vector (metres of translation: millimetres, as the engine's length unit).
302
+ *
303
+ * @param {unknown} value Vector or `[x, y, z]`.
304
+ * @returns {number[]} Three components.
305
+ */
306
+ function vec3Of(value) {
307
+ if (Array.isArray(value)) return [numberOf(value[0]), numberOf(value[1]), numberOf(value[2])];
308
+ if (value && Array.isArray(value.c)) return value.c.map(numberOf);
309
+ return ORIGIN3;
310
+ }
311
+
312
+ /**
313
+ * Turn an `instance` `part` value into a reference.
314
+ *
315
+ * Accepts a plain string/Id name, or a map `{ "name": …, "page": …, "hash": … }` produced by
316
+ * the `part(...)` host helper.
317
+ *
318
+ * @param {unknown} value Runtime value.
319
+ * @returns {PartRef|null} The reference, or null when absent.
320
+ */
321
+ export function partRefFromValue(value) {
322
+ if (value == null) return null;
323
+ if (typeof value === 'string') return new PartRef(value);
324
+ const name = value?.constructor?.name;
325
+ if (name === 'Id') return new PartRef(value.toString());
326
+ if (value instanceof Map) {
327
+ const rawName = value.get('name') ?? value.get('part') ?? value.get('page');
328
+ if (rawName == null) return null;
329
+ return new PartRef(String(rawName), {
330
+ page: value.get('page') == null ? null : String(value.get('page')),
331
+ hash: value.get('hash') == null ? null : String(value.get('hash')),
332
+ });
333
+ }
334
+ return null;
335
+ }
336
+
337
+ /**
338
+ * Turn an `instance` `transform` value into a rigid placement.
339
+ *
340
+ * Supported forms: an `Xf`; a translation vector; or a map with `translate` +
341
+ * `rotateX`/`rotateY`/`rotateZ` (degrees or angle quantities). Rotations compose X→Y→Z.
342
+ * Anything else falls back to identity, which the projection reports as unplaced.
343
+ *
344
+ * @param {unknown} value Runtime value.
345
+ * @returns {{ m: number[][], t: number[] }} Rotation matrix plus translation in mm.
346
+ */
347
+ export function transformFromValue(value) {
348
+ if (value == null) return { m: IDENTITY3.map((row) => [...row]), t: [...ORIGIN3] };
349
+ if (value instanceof Xf) return { m: value.m.map((row) => [...row]), t: [...value.t] };
350
+ if (Array.isArray(value) || (value && Array.isArray(value.c))) {
351
+ return { m: IDENTITY3.map((row) => [...row]), t: vec3Of(value) };
352
+ }
353
+ if (value instanceof Map) {
354
+ const t = vec3Of(value.get('translate') ?? value.get('offset'));
355
+ const rotX = numberOf(value.get('rotateX'));
356
+ const rotY = numberOf(value.get('rotateY'));
357
+ const rotZ = numberOf(value.get('rotateZ'));
358
+ let m = IDENTITY3.map((row) => [...row]);
359
+ if (rotX) m = multiply3(rotation3('x', rotX), m);
360
+ if (rotY) m = multiply3(rotation3('y', rotY), m);
361
+ if (rotZ) m = multiply3(rotation3('z', rotZ), m);
362
+ return { m, t };
363
+ }
364
+ if (value instanceof Xf) return { m: value.m, t: value.t };
365
+ return { m: IDENTITY3.map((row) => [...row]), t: [...ORIGIN3] };
366
+ }
367
+
368
+ /**
369
+ * Turn an `instanceMaterial` definition map into a surface material.
370
+ *
371
+ * Accepts `{ "color": vector(r,g,b) | [r,g,b], "metallic": number, "roughness": number }`. Colour
372
+ * components are 0..1; metallic/roughness are 0..1 and default to 0 / 1 (a matte finish).
373
+ *
374
+ * @param {unknown} value Runtime definition map.
375
+ * @returns {{ color: number[], metallic: number, roughness: number }} The material.
376
+ */
377
+ export function materialFromValue(value) {
378
+ const def = value instanceof Map ? value : new Map();
379
+ const color = vec3Of(def.get('color'));
380
+ const clamp = (v) => Math.max(0, Math.min(1, numberOf(v)));
381
+ return {
382
+ color: [clamp(color[0]), clamp(color[1]), clamp(color[2])],
383
+ metallic: clamp(def.get('metallic')),
384
+ roughness: clamp(def.get('roughness') ?? 1),
385
+ };
386
+ }
387
+
388
+ /**
389
+ * Turn a `pipe` definition map into an inline pipe run.
390
+ *
391
+ * Accepts `{ "start": vector(…), "end": vector(…), "outerRadius": length, "innerRadius"?:
392
+ * length, "name"? }`. Points are in millimetres; radii are length quantities in millimetres.
393
+ *
394
+ * @param {unknown} value Runtime definition map.
395
+ * @returns {{ start: number[], end: number[], outerRadiusMm: number, innerRadiusMm: number, name: string | null }} The pipe run.
396
+ */
397
+ export function pipeFromValue(value) {
398
+ const def = value instanceof Map ? value : new Map();
399
+ const radius = (key, fallback) => {
400
+ const v = numberOf(def.get(key));
401
+ return v > 0 ? v : fallback;
402
+ };
403
+ return {
404
+ start: vec3Of(def.get('start')),
405
+ end: vec3Of(def.get('end')),
406
+ outerRadiusMm: radius('outerRadius', 0),
407
+ innerRadiusMm: radius('innerRadius', 0),
408
+ name: def.get('name') != null ? String(def.get('name')) : null,
409
+ };
410
+ }
411
+
412
+ /**
413
+ * Turn a `terrain` definition map into an inline terrain mesh.
414
+ *
415
+ * Accepts `{ "heights": number[], "columns": int, "rows": int, "extentXmm": length,
416
+ * "extentYmm": length, "originXmm"?: length, "originYmm"?: length, "originZmm"?: length, "site"?:
417
+ * { "west", "south", "east", "north" }, "name"? }`. Heights are in metres (the Terrarium
418
+ * convention); extents are length quantities in millimetres. The kernel's `buildDemMesh` turns the
419
+ * grid into a closed heightfield.
420
+ *
421
+ * `site` is the grid's geographic footprint (WGS-84 degrees) — the map picker records it so the
422
+ * viewport can drape satellite imagery over the mesh (`terrain-imagery.ts` in the CAD editor). It
423
+ * is optional: an un-georeferenced terrain renders as a plain solid. A half-specified footprint
424
+ * is treated as absent rather than guessed.
425
+ *
426
+ * @param {unknown} value Runtime definition map.
427
+ * @returns {{ heights: number[], columns: number, rows: number, extentXmm: number, extentYmm: number, originXmm: number, originYmm: number, originZmm: number, site: { west: number, south: number, east: number, north: number } | null, name: string | null }} The terrain.
428
+ */
429
+ export function terrainFromValue(value) {
430
+ const def = value instanceof Map ? value : new Map();
431
+ const raw = def.get('heights');
432
+ const heights = Array.isArray(raw) ? raw.map(numberOf) : [];
433
+ return {
434
+ heights,
435
+ columns: Math.max(2, Math.round(numberOf(def.get('columns')))),
436
+ rows: Math.max(2, Math.round(numberOf(def.get('rows')))),
437
+ extentXmm: numberOf(def.get('extentXmm')),
438
+ extentYmm: numberOf(def.get('extentYmm')),
439
+ originXmm: numberOf(def.get('originXmm') ?? 0),
440
+ originYmm: numberOf(def.get('originYmm') ?? 0),
441
+ originZmm: numberOf(def.get('originZmm') ?? 0),
442
+ site: siteFromValue(def.get('site')),
443
+ name: def.get('name') != null ? String(def.get('name')) : null,
444
+ };
445
+ }
446
+
447
+ /**
448
+ * Read a terrain's geographic footprint from its `site` map.
449
+ *
450
+ * @param {unknown} value The `site` entry of a terrain definition (a FeatureScript map).
451
+ * @returns {{ west: number, south: number, east: number, north: number } | null} Degrees, or null
452
+ * when the map is absent/incomplete or the box is degenerate.
453
+ */
454
+ function siteFromValue(value) {
455
+ if (!(value instanceof Map)) return null;
456
+ const keys = ['west', 'south', 'east', 'north'];
457
+ const raw = keys.map((key) => value.get(key));
458
+ if (raw.some((entry) => entry == null)) return null;
459
+ const [west, south, east, north] = raw.map(numberOf);
460
+ if (![west, south, east, north].every(Number.isFinite)) return null;
461
+ if (!(east > west) || !(north > south)) return null;
462
+ return { west, south, east, north };
463
+ }
464
+
465
+ /** Serialise a definition map for display (depth-limited, JSON-safe). */
466
+ function serializeDefinition(definition) {
467
+ /** @type {Record<string, unknown>} */
468
+ const out = {};
469
+ for (const [key, value] of definition.entries()) {
470
+ const name = value?.constructor?.name;
471
+ if (value instanceof PartRef) out[String(key)] = { name: value.name, page: value.page, hash: value.hash };
472
+ else if (name === 'Vec') out[String(key)] = vec3Of(value);
473
+ else if (name === 'Q') out[String(key)] = numberOf(value);
474
+ else if (name === 'Id') out[String(key)] = value.toString();
475
+ else if (value instanceof Map) out[String(key)] = serializeDefinition(value);
476
+ else if (typeof value === 'number' || typeof value === 'string' || typeof value === 'boolean') {
477
+ out[String(key)] = value;
478
+ } else out[String(key)] = value === null || value === undefined ? null : (name ?? typeof value);
479
+ }
480
+ return out;
481
+ }