@floless/app 0.138.2 → 0.139.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.
Files changed (109) hide show
  1. package/autostart.mjs +6 -2
  2. package/desktop-access-production-manifest.mjs +7 -0
  3. package/dist/floless-server.cjs +157202 -70901
  4. package/dist/schemas/model.continuation.v1.schema.json +19 -0
  5. package/dist/schemas/model.continuation.v2.schema.json +19 -0
  6. package/dist/schemas/model.query-response.v1.schema.json +95 -0
  7. package/dist/schemas/model.query-response.v2.schema.json +80 -0
  8. package/dist/schemas/model.query.v1.schema.json +87 -0
  9. package/dist/schemas/model.query.v2.schema.json +87 -0
  10. package/dist/schemas/model.snap-candidate.v1.schema.json +48 -0
  11. package/dist/schemas/model.snap-constraint.v1.schema.json +18 -0
  12. package/dist/schemas/model.snap-query.v1.schema.json +24 -0
  13. package/dist/schemas/model.snap-result.v1.schema.json +33 -0
  14. package/dist/schemas/model.snapshot.v1.schema.json +136 -0
  15. package/dist/schemas/revit.model.v1.schema.json +24 -0
  16. package/dist/schemas/steel.model.v2.schema.json +45 -6
  17. package/dist/skills/floless-app-approval/SKILL.md +19 -5
  18. package/dist/skills/floless-app-bridge/SKILL.md +19 -6
  19. package/dist/skills/floless-app-knowledge/SKILL.md +22 -1
  20. package/dist/skills/floless-app-new-workflow/SKILL.md +31 -27
  21. package/dist/skills/floless-app-new-workflow/references/build-and-verify.md +13 -12
  22. package/dist/skills/floless-app-onboarding/SKILL.md +3 -3
  23. package/dist/skills/floless-app-onboarding/references/floless-app-tour.md +16 -9
  24. package/dist/skills/floless-app-steel-model/SKILL.md +11 -2
  25. package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +95 -0
  26. package/dist/skills/floless-app-steel-takeoff/SKILL.md +142 -21
  27. package/dist/skills/floless-app-steel-takeoff/references/elevation-registration.md +19 -0
  28. package/dist/skills/floless-app-tweak-contract/SKILL.md +42 -8
  29. package/dist/skills/floless-app-vectorize/SKILL.md +19 -6
  30. package/dist/skills/floless-app-workflows/SKILL.md +30 -3
  31. package/dist/skills/floless-app-workflows/references/workspace-data.md +77 -4
  32. package/dist/templates/floless-workspace-model-report.flo +77 -0
  33. package/dist/templates/revit-model.flo +111 -0
  34. package/dist/web/app.css +415 -177
  35. package/dist/web/app.js +302 -51
  36. package/dist/web/aware.js +1357 -1032
  37. package/dist/web/chat.css +692 -0
  38. package/dist/web/chat.js +2651 -0
  39. package/dist/web/commands-revit.js +42 -0
  40. package/dist/web/commands-shell.js +531 -70
  41. package/dist/web/commands-steel.js +344 -146
  42. package/dist/web/commands.js +1 -1
  43. package/dist/web/index.html +283 -77
  44. package/dist/web/instructor.js +217 -36
  45. package/dist/web/left-pane.js +636 -0
  46. package/dist/web/model-artifact-loader.js +75 -0
  47. package/dist/web/model-authoring-gestures.js +141 -0
  48. package/dist/web/model-cad-tools.js +20 -0
  49. package/dist/web/model-clip-gesture.js +148 -0
  50. package/dist/web/model-clip-list.js +156 -0
  51. package/dist/web/model-clip-session.js +274 -0
  52. package/dist/web/model-clip-three-overlay.js +295 -0
  53. package/dist/web/model-clip-three-preview.js +59 -0
  54. package/dist/web/model-editor-contract.js +519 -0
  55. package/dist/web/model-editor-revit-adapter.js +139 -0
  56. package/dist/web/model-editor-shell.js +271 -0
  57. package/dist/web/model-editor-state-recovery.js +44 -0
  58. package/dist/web/model-editor-steel-adapter.js +410 -0
  59. package/dist/web/model-editor.css +268 -0
  60. package/dist/web/model-frame.js +192 -0
  61. package/dist/web/model-inspector.js +128 -0
  62. package/dist/web/model-measure.js +390 -0
  63. package/dist/web/model-navigation-controls.js +246 -0
  64. package/dist/web/model-orientation-overlay.js +217 -0
  65. package/dist/web/model-panel-bridge.js +230 -0
  66. package/dist/web/model-pointer-dock.js +164 -0
  67. package/dist/web/model-revit-module.js +83 -0
  68. package/dist/web/model-selection-coordinator.js +151 -0
  69. package/dist/web/model-selection-tools.js +290 -0
  70. package/dist/web/model-snap-contract.js +267 -0
  71. package/dist/web/model-snapping.js +497 -0
  72. package/dist/web/model-spatial-panel.js +294 -0
  73. package/dist/web/model-spatial-tools.js +249 -0
  74. package/dist/web/model-tree.js +47 -0
  75. package/dist/web/model-viewport-lighting.js +166 -0
  76. package/dist/web/model-viewport-revit-adapter.js +1224 -0
  77. package/dist/web/model-viewport-state.js +505 -0
  78. package/dist/web/model-viewport-steel-adapter.js +150 -0
  79. package/dist/web/model-viewport-toolbar.js +516 -0
  80. package/dist/web/model-viewport.js +717 -0
  81. package/dist/web/panels.js +8 -15
  82. package/dist/web/renderers.js +3 -0
  83. package/dist/web/revit-editor.css +35 -0
  84. package/dist/web/revit-editor.html +74 -0
  85. package/dist/web/revit-editor.js +845 -0
  86. package/dist/web/steel-3d-core.js +16 -44
  87. package/dist/web/steel-3d-view.js +1384 -633
  88. package/dist/web/steel-canvas-guidance.js +3 -1
  89. package/dist/web/steel-editor.html +2121 -1253
  90. package/dist/web/steel-filter.html +5 -1
  91. package/dist/web/steel-model-v2-commands.js +72 -1
  92. package/dist/web/steel-split-view.js +5 -39
  93. package/dist/web/steel-view-generation.js +107 -17
  94. package/dist/web/vector-3d.html +12 -0
  95. package/dist/web/workspaces.js +2154 -283
  96. package/distribution-profile-active.mjs +2 -0
  97. package/distribution-profile-production.mjs +47 -0
  98. package/distribution-profile-shared.mjs +8 -0
  99. package/distribution-profile.mjs +18 -0
  100. package/distribution-resource-inventory.mjs +81 -0
  101. package/launch.mjs +18 -10
  102. package/log.mjs +2 -1
  103. package/managed-runtime-policy.mjs +104 -0
  104. package/model-reader-policy-active.mjs +7 -0
  105. package/network-policy-active.mjs +6 -0
  106. package/package.json +17 -2
  107. package/post-update-marker.mjs +3 -1
  108. package/rvt-production-uat-authority.mjs +60 -0
  109. package/teardown.mjs +4 -3
@@ -0,0 +1,1224 @@
1
+ import * as THREE from 'three';
2
+ import { OrbitControls } from 'three/addons/OrbitControls.js';
3
+ import { RoomEnvironment } from 'three/addons/RoomEnvironment.js';
4
+ import {
5
+ MODEL_NAMED_VIEWS, createCadOrbitEventProxy, mountCadInputArbiter,
6
+ } from './model-navigation-controls.js';
7
+ import { buildModelSnapIndex } from './model-snapping.js';
8
+ import { modelOrientationPose } from './model-orientation-overlay.js';
9
+ import { createModelFrame } from './model-frame.js';
10
+ import { createModelViewportController } from './model-viewport.js';
11
+ import { createEntityKeyRegistry } from './model-viewport-state.js';
12
+ import { createModelSelectionCoordinator } from './model-selection-coordinator.js';
13
+ import { createModelClipGesture, orientClipNormalAwayFromCamera } from './model-clip-gesture.js';
14
+ import { createModelClipThreeOverlay } from './model-clip-three-overlay.js';
15
+ import { createModelClipThreePreview } from './model-clip-three-preview.js';
16
+ import { MODEL_LIGHTING_DEFAULTS, modelSunDirection, normalizeModelLighting } from './model-viewport-lighting.js';
17
+
18
+ const COMPONENT = { 5121: { bytes: 1, read: 'getUint8', array: Uint8Array }, 5123: { bytes: 2, read: 'getUint16', array: Uint16Array }, 5125: { bytes: 4, read: 'getUint32', array: Uint32Array }, 5126: { bytes: 4, read: 'getFloat32', array: Float32Array } };
19
+ const WIDTH = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4 };
20
+ const PROVIDER_WATERMARK_NODE = 'EVALUATION_WATERMARK';
21
+ const IDENTITY_RENDER_MATRIX = Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);
22
+ const LEGACY_RENDER_MATRIX = Object.freeze([0.001, 0, 0, 0, 0, 0, -0.001, 0, 0, 0.001, 0, 0, 0, 0, 0, 1]);
23
+
24
+ const sameMatrix = (actual, expected) => Array.isArray(actual) && actual.length === 16 && actual.every((value, index) => value === expected[index]);
25
+
26
+ /** Exact versioned render boundary. Unknown combinations fail instead of silently rotating/scaling twice. */
27
+ export function revitGeometryFrame(receipt = { schema: 'floless.model-cas-manifest/v1', geometryToRenderMatrix: LEGACY_RENDER_MATRIX }) {
28
+ if (receipt?.schema === 'floless.model-cas-manifest/v1' && sameMatrix(receipt.geometryToRenderMatrix, LEGACY_RENDER_MATRIX)) {
29
+ return Object.freeze({ ...createModelFrame({ matrix: LEGACY_RENDER_MATRIX, millimetresPerRenderUnit: 1000 }), receiptSchema: receipt.schema });
30
+ }
31
+ if (receipt?.schema === 'floless.model-cas-manifest/v2' && sameMatrix(receipt.geometryToRenderMatrix, IDENTITY_RENDER_MATRIX)) {
32
+ return Object.freeze({ ...createModelFrame({ matrix: IDENTITY_RENDER_MATRIX, millimetresPerRenderUnit: 1 }), receiptSchema: receipt.schema });
33
+ }
34
+ throw new Error('The verified model uses an unsupported geometry-to-render frame.');
35
+ }
36
+
37
+ export function revitDistanceMm(frame, a, b) {
38
+ const renderDistance = Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]);
39
+ return typeof frame?.renderToCanonicalDistance === 'function'
40
+ ? frame.renderToCanonicalDistance(renderDistance)
41
+ : renderDistance * frame.millimetresPerWorldUnit;
42
+ }
43
+
44
+ // Wireframe draws the model's OWN edges, not its triangulation. `material.wireframe` draws all three
45
+ // edges of every triangle, so a converted Revit model reads as a dense mesh rather than a wireframe
46
+ // of the building (#1409). EdgesGeometry keeps only edges where the adjacent faces diverge past a
47
+ // threshold, which is what a CAD wireframe is. 20° matches the Steel viewer: it keeps corners and
48
+ // drops the flat-face triangulation diagonals.
49
+ // Realistic rebalances the rig so the image-based environment contributes real form. Calibrated
50
+ // against the Residential production model: enough to reveal shape, not so much that the Revit
51
+ // element colours darken out of recognition.
52
+ const REALISTIC_AMBIENT_SCALE = 0.25;
53
+ const REALISTIC_KEY_SCALE = 0.9;
54
+ // RoomEnvironment is a bright white box, and on a matte dielectric its whole contribution is
55
+ // indirect DIFFUSE — i.e. more flat fill light, which is the opposite of the form Realistic is for.
56
+ // Left at three's default of 1 it simply floods the model and washes the Revit colours out.
57
+ const REALISTIC_ENV_INTENSITY = 0.35;
58
+ // How long to wait for a real frame before building the next outline batch on a timer instead.
59
+ // Long enough that rAF wins whenever the page is actually being drawn; short enough that a page
60
+ // which never composites still finishes the build promptly.
61
+ const OUTLINE_FALLBACK_MS = 100;
62
+ // Above this many meshes the conversion takes long enough to need saying out loud. Below it the
63
+ // progressive reveal is its own explanation and a message would be noise.
64
+ const OUTLINE_ANNOUNCE_THRESHOLD = 1500;
65
+ const REVIT_EDGE_THRESHOLD_DEGREES = 20;
66
+ const REVIT_EDGE_COLOUR = 0x94a3b8; // slate, reads against the dark viewport
67
+ const REVIT_EDGE_SELECTED = 0x2563eb; // the same blue the Solid selection cue uses
68
+ const REVIT_EDGE_HOVERED = 0x0ea5e9;
69
+
70
+ // EdgesGeometry classifies the 20° in the geometry's LOCAL space, and derives face normals from
71
+ // positions rather than the authored NORMAL. The adapter deliberately preserves affine node matrices
72
+ // (see sceneFromGlb), and a shear or non-uniform scale changes the dihedral angle the viewer actually
73
+ // sees — so a true crease can be dropped and a flat seam kept. Angle-preserving transforms (rigid,
74
+ // or uniform scale) cannot do that, so only the non-conformal case pays for the bake below.
75
+ function preservesAngles(matrix) {
76
+ const e = matrix.elements;
77
+ const x = new THREE.Vector3(e[0], e[1], e[2]);
78
+ const y = new THREE.Vector3(e[4], e[5], e[6]);
79
+ const z = new THREE.Vector3(e[8], e[9], e[10]);
80
+ const lx = x.length(), ly = y.length(), lz = z.length();
81
+ if (!(lx > 0 && ly > 0 && lz > 0)) return false;
82
+ const scale = (Math.abs(lx - ly) <= 1e-6 * lx) && (Math.abs(lx - lz) <= 1e-6 * lx);
83
+ const square = Math.abs(x.dot(y)) <= 1e-6 * lx * ly
84
+ && Math.abs(x.dot(z)) <= 1e-6 * lx * lz
85
+ && Math.abs(y.dot(z)) <= 1e-6 * ly * lz;
86
+ return scale && square;
87
+ }
88
+
89
+ /** The edge geometry a mesh's outline is drawn from, classified in the space the viewer sees. */
90
+ export function revitEdgeGeometry(mesh) {
91
+ mesh.updateWorldMatrix(true, false);
92
+ const world = mesh.matrixWorld;
93
+ if (preservesAngles(world)) return new THREE.EdgesGeometry(mesh.geometry, REVIT_EDGE_THRESHOLD_DEGREES);
94
+ // Classify in world space, then bring the result back into the mesh's local space — the outline is
95
+ // a CHILD of the mesh, so it is transformed by that same matrix again when it is drawn.
96
+ const baked = mesh.geometry.clone().applyMatrix4(world);
97
+ const edges = new THREE.EdgesGeometry(baked, REVIT_EDGE_THRESHOLD_DEGREES);
98
+ baked.dispose();
99
+ edges.applyMatrix4(new THREE.Matrix4().copy(world).invert());
100
+ return edges;
101
+ }
102
+
103
+ /**
104
+ * Outline line materials are SHARED, keyed by colour and opacity, so selected, hovered, ghosted and
105
+ * ordinary outlines are distinct cached entries. A shared material must never be mutated in place —
106
+ * that would repaint every other outline using it — so the paint below REASSIGNS from this cache.
107
+ * The cache owns its materials and disposes them exactly once, at scene disposal; disposing them per
108
+ * mesh would double-dispose. Each mesh owns only its own line GEOMETRY.
109
+ */
110
+ export function createRevitEdgeMaterials() {
111
+ const cache = new Map();
112
+ let planes = [];
113
+ return {
114
+ get(hex, opacity) {
115
+ const key = `${hex}:${opacity.toFixed(4)}`;
116
+ let material = cache.get(key);
117
+ if (!material) {
118
+ material = new THREE.LineBasicMaterial({
119
+ color: hex, transparent: opacity < 1, opacity, depthWrite: opacity >= 1,
120
+ });
121
+ // A new outline material inherits NO clipping planes, so without this an outline runs straight
122
+ // through a section cut while the fill it replaces respects it.
123
+ material.clippingPlanes = planes;
124
+ cache.set(key, material);
125
+ }
126
+ return material;
127
+ },
128
+ // paintSpatialState REPLACES the plane array rather than mutating it, so every cached material
129
+ // must be re-pointed at the new one — a kept reference silently clips against the previous set.
130
+ setClippingPlanes(next) {
131
+ planes = next;
132
+ for (const material of cache.values()) material.clippingPlanes = next;
133
+ },
134
+ dispose() {
135
+ for (const material of cache.values()) material.dispose();
136
+ cache.clear();
137
+ },
138
+ };
139
+ }
140
+
141
+ /** Build (or return) a mesh's edge outline. One outline is atomic — never split part-built. */
142
+ export function revitOutlineFor(mesh, materials) {
143
+ if (mesh.userData.revitOutline) return mesh.userData.revitOutline;
144
+ const outline = new THREE.LineSegments(revitEdgeGeometry(mesh), materials.get(REVIT_EDGE_COLOUR, 1));
145
+ outline.userData.revitOutline = true;
146
+ outline.visible = false;
147
+ mesh.add(outline);
148
+ mesh.userData.revitOutline = outline;
149
+ return outline;
150
+ }
151
+
152
+ /**
153
+ * Outlines are built INCREMENTALLY across frames under a time budget. EdgesGeometry is synchronous
154
+ * CPU work plus a GPU allocation per primitive, so building a whole large model in one pass blocks
155
+ * the main thread and reads as a hang. One outline is atomic, so a single very large primitive can
156
+ * still overrun the budget — the budget bounds the batch, not one primitive.
157
+ *
158
+ * The job is tagged with the scene GENERATION it belongs to. `rebuild` applies the display mode to a
159
+ * staged generation that is activated only later, so an untagged job could attach outlines to a scene
160
+ * that has already been retired, or leave the live one empty.
161
+ */
162
+ export function createRevitOutlineBuilder({ meshes, materials, generation, budgetMs = 8, onBatch = () => {}, schedule }) {
163
+ const queue = [...meshes];
164
+ let cursor = 0;
165
+ let cancelled = false;
166
+ let stopped = false;
167
+ let runToken = 0;
168
+ let worstOutlineMs = 0;
169
+ const built = [];
170
+ const now = () => (typeof performance === 'object' && performance ? performance.now() : Date.now());
171
+ const step = () => {
172
+ if (cancelled || stopped) return;
173
+ const started = now();
174
+ let any = false;
175
+ while (cursor < queue.length) {
176
+ const one = now();
177
+ revitOutlineFor(queue[cursor], materials);
178
+ worstOutlineMs = Math.max(worstOutlineMs, now() - one);
179
+ built.push(queue[cursor]);
180
+ cursor += 1; any = true;
181
+ if (now() - started >= budgetMs) break;
182
+ }
183
+ if (any) onBatch();
184
+ if (cursor < queue.length) pump();
185
+ };
186
+ // Exactly one live chain. Toggling out of Wireframe and back during a build leaves the previous
187
+ // callback pending, and without this it would resume ALONGSIDE the restarted one — two chains over
188
+ // one queue, each repainting every mesh on every batch. A token rather than a busy flag, because a
189
+ // flag left set by a callback that never ran would instead deadlock the build.
190
+ const pump = () => { const token = ++runToken; schedule(() => { if (token === runToken) step(); }); };
191
+ return {
192
+ start() { stopped = false; if (!cancelled && cursor < queue.length) pump(); },
193
+ // Leaving Wireframe STOPS the build but keeps what it made. Measured on the Residential
194
+ // production model, the finished outlines are about 9 MB against a 90 MB model, and rebuilding
195
+ // them costs ~3 s of CPU -- so throwing them away to save 9 MB would make every toggle back into
196
+ // Wireframe pay that again. A half-finished build resumes where it left off, because
197
+ // revitOutlineFor returns the existing outline for a mesh that already has one.
198
+ stop() { stopped = true; },
199
+ // Cancelling also DISPOSES, for a generation being retired: its outlines must not outlive it.
200
+ cancel() {
201
+ if (cancelled) return;
202
+ cancelled = true;
203
+ for (const mesh of built) disposeOutline(mesh);
204
+ built.length = 0;
205
+ },
206
+ get generation() { return generation; },
207
+ get done() { return cursor >= queue.length; },
208
+ get cancelled() { return cancelled; },
209
+ get stopped() { return stopped; },
210
+ get pending() { return Math.max(0, queue.length - cursor); },
211
+ get worstOutlineMs() { return worstOutlineMs; },
212
+ };
213
+ }
214
+
215
+ /** A mesh owns its line geometry; the shared material belongs to the cache and is NOT disposed here. */
216
+ function disposeOutline(mesh) {
217
+ const outline = mesh.userData?.revitOutline;
218
+ if (!outline) return;
219
+ mesh.remove(outline);
220
+ outline.geometry?.dispose();
221
+ mesh.userData.revitOutline = null;
222
+ }
223
+
224
+ function disposeMeshes(items) {
225
+ items.forEach((mesh) => {
226
+ disposeOutline(mesh);
227
+ mesh.geometry?.dispose();
228
+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
229
+ materials.forEach((material) => material?.dispose());
230
+ });
231
+ }
232
+
233
+ function parseGlb(bytes) {
234
+ const data = bytes instanceof ArrayBuffer ? bytes : bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
235
+ const view = new DataView(data);
236
+ if (view.byteLength < 20 || view.getUint32(0, true) !== 0x46546c67 || view.getUint32(4, true) !== 2 || view.getUint32(8, true) !== view.byteLength) throw new Error('The verified geometry tile is not a bounded GLB 2.0 file.');
237
+ let at = 12; let json = null; let binary = null;
238
+ while (at + 8 <= view.byteLength) {
239
+ const length = view.getUint32(at, true); const kind = view.getUint32(at + 4, true); at += 8;
240
+ if (at + length > view.byteLength) throw new Error('The geometry tile has a truncated GLB chunk.');
241
+ if (kind === 0x4e4f534a && json === null) json = JSON.parse(new TextDecoder().decode(new Uint8Array(data, at, length)).trim());
242
+ else if (kind === 0x004e4942 && binary === null) binary = new Uint8Array(data, at, length);
243
+ at += length;
244
+ }
245
+ if (!json || !binary || json.asset?.version !== '2.0' || json.buffers?.length !== 1 || json.buffers[0].uri) throw new Error('The geometry tile uses an unsupported external GLB resource.');
246
+ return { json, binary };
247
+ }
248
+
249
+ function accessor(doc, binary, index) {
250
+ const a = doc.accessors?.[index]; const component = COMPONENT[a?.componentType]; const width = WIDTH[a?.type]; const b = doc.bufferViews?.[a?.bufferView];
251
+ if (!a || !b || !component || !width || b.buffer !== 0 || a.sparse || b.byteStride) throw new Error('The geometry tile uses an unsupported accessor.');
252
+ const count = a.count * width; const offset = (b.byteOffset || 0) + (a.byteOffset || 0); const needed = count * component.bytes;
253
+ if (!Number.isSafeInteger(count) || count < 0 || offset < 0 || offset + needed > binary.byteLength) throw new Error('The geometry tile accessor exceeds its verified bytes.');
254
+ const out = new component.array(count); const view = new DataView(binary.buffer, binary.byteOffset + offset, needed);
255
+ for (let i = 0; i < count; i++) out[i] = view[component.read](i * component.bytes, true);
256
+ return { array: out, width, normalized: a.normalized === true, componentType: a.componentType };
257
+ }
258
+
259
+ function colorAccessor(doc, binary, index, vertexCount) {
260
+ const color = accessor(doc, binary, index);
261
+ if (![3, 4].includes(color.width) || ![5121, 5123, 5126].includes(color.componentType)) {
262
+ throw new Error('The geometry tile COLOR_0 accessor is not a canonical glTF vertex color.');
263
+ }
264
+ if ((color.componentType === 5121 || color.componentType === 5123) && !color.normalized) {
265
+ throw new Error('The geometry tile COLOR_0 integer accessor must be normalized.');
266
+ }
267
+ if (color.componentType === 5126 && color.normalized) {
268
+ throw new Error('The geometry tile COLOR_0 float accessor cannot be normalized.');
269
+ }
270
+ if (color.array.length / color.width !== vertexCount) {
271
+ throw new Error('The geometry tile COLOR_0 count does not match POSITION.');
272
+ }
273
+ return color;
274
+ }
275
+
276
+ const NORMAL_UNIT_TOLERANCE = 1e-4;
277
+
278
+ function normalAccessor(doc, binary, index, vertexCount) {
279
+ const normal = accessor(doc, binary, index);
280
+ if (normal.componentType !== 5126 || normal.width !== 3 || normal.normalized) {
281
+ throw new Error('The geometry tile NORMAL accessor must be an unnormalized FLOAT VEC3.');
282
+ }
283
+ if (normal.array.length / normal.width !== vertexCount) {
284
+ throw new Error('The geometry tile NORMAL count does not match POSITION.');
285
+ }
286
+ for (let at = 0; at < normal.array.length; at += 3) {
287
+ const length = Math.hypot(normal.array[at], normal.array[at + 1], normal.array[at + 2]);
288
+ if (!Number.isFinite(length) || Math.abs(length - 1) > NORMAL_UNIT_TOLERANCE) {
289
+ throw new Error('The geometry tile NORMAL accessor contains a non-unit vector.');
290
+ }
291
+ }
292
+ return normal;
293
+ }
294
+
295
+ function materialFor(source, vertexColors, flatShading) {
296
+ if (source !== undefined && (!source || typeof source !== 'object' || Array.isArray(source))) {
297
+ throw new Error('The geometry tile material must be an object.');
298
+ }
299
+ for (const key of Object.keys(source ?? {})) {
300
+ if (!['alphaMode', 'alphaCutoff', 'doubleSided', 'pbrMetallicRoughness'].includes(key)) {
301
+ throw new Error(`The geometry tile material property '${key}' is unsupported.`);
302
+ }
303
+ }
304
+ const pbr = source?.pbrMetallicRoughness ?? {};
305
+ if (!pbr || typeof pbr !== 'object' || Array.isArray(pbr)) {
306
+ throw new Error('The geometry tile PBR material must be an object.');
307
+ }
308
+ for (const key of Object.keys(pbr)) {
309
+ if (!['baseColorFactor', 'metallicFactor', 'roughnessFactor'].includes(key)) {
310
+ throw new Error(`The geometry tile PBR material property '${key}' is unsupported.`);
311
+ }
312
+ }
313
+ const rgba = pbr.baseColorFactor ?? [1, 1, 1, 1];
314
+ if (!Array.isArray(rgba) || rgba.length !== 4 || rgba.some((value) => !Number.isFinite(value) || value < 0 || value > 1)) {
315
+ throw new Error('The geometry tile baseColorFactor must contain four values in [0,1].');
316
+ }
317
+ const metalness = pbr.metallicFactor ?? 1;
318
+ const roughness = pbr.roughnessFactor ?? 1;
319
+ if (![metalness, roughness].every((value) => Number.isFinite(value) && value >= 0 && value <= 1)) {
320
+ throw new Error('The geometry tile metallic and roughness factors must be in [0,1].');
321
+ }
322
+ const doubleSided = source?.doubleSided ?? false;
323
+ if (typeof doubleSided !== 'boolean') throw new Error('The geometry tile doubleSided value must be Boolean.');
324
+ const alphaMode = source?.alphaMode ?? 'OPAQUE';
325
+ if (!['OPAQUE', 'MASK', 'BLEND'].includes(alphaMode)) throw new Error('The geometry tile material has an unsupported alpha mode.');
326
+ const alphaCutoff = source?.alphaCutoff;
327
+ if (alphaCutoff !== undefined && (alphaMode !== 'MASK' || !Number.isFinite(alphaCutoff) || alphaCutoff < 0)) {
328
+ throw new Error('The geometry tile alphaCutoff is valid only for MASK and must be non-negative.');
329
+ }
330
+ const factorAlpha = rgba[3];
331
+ // glTF ignores base/vertex alpha in OPAQUE mode. MASK keeps the authored alpha in the shader but
332
+ // writes depth; BLEND enters Three's transparent pass even when the factor is 1 because COLOR_0
333
+ // may still supply per-vertex alpha.
334
+ const opacity = alphaMode === 'OPAQUE' ? 1 : factorAlpha;
335
+ const transparent = alphaMode === 'BLEND';
336
+ const material = new THREE.MeshStandardMaterial({
337
+ color: new THREE.Color(rgba[0], rgba[1], rgba[2]),
338
+ opacity,
339
+ transparent,
340
+ depthWrite: !transparent,
341
+ alphaTest: alphaMode === 'MASK' ? (alphaCutoff ?? 0.5) : 0,
342
+ vertexColors,
343
+ roughness,
344
+ metalness,
345
+ side: doubleSided ? THREE.DoubleSide : THREE.FrontSide,
346
+ flatShading,
347
+ });
348
+ material.userData.revitAuthoredAlpha = Object.freeze({ opacity, transparent, depthWrite: !transparent });
349
+ return material;
350
+ }
351
+
352
+ export function sceneFromGlb(bytes, ownerByNode = new Map(), frameReceipt) {
353
+ const frame = revitGeometryFrame(frameReceipt);
354
+ const { json, binary } = parseGlb(bytes); const root = new THREE.Group(); const meshes = []; const ownedMeshes = []; const decorationMeshes = [];
355
+ const nodes = json.nodes ?? []; const scenes = json.scenes ?? [];
356
+ const sceneIndex = Number.isInteger(json.scene) ? json.scene : 0; const selectedScene = scenes[sceneIndex];
357
+ if (!selectedScene || !Array.isArray(selectedScene.nodes)) throw new Error('The geometry tile has no selected GLB scene.');
358
+ const active = new Set(); const attached = new Set();
359
+
360
+ const nodeObject = (nodeIndex, inheritedOwner = null) => {
361
+ if (!Number.isInteger(nodeIndex) || nodeIndex < 0 || nodeIndex >= nodes.length) throw new Error('The geometry tile scene references an invalid node.');
362
+ if (active.has(nodeIndex)) throw new Error('The geometry tile scene graph contains a cycle.');
363
+ if (attached.has(nodeIndex)) throw new Error('The geometry tile scene graph attaches one node more than once.');
364
+ active.add(nodeIndex); attached.add(nodeIndex);
365
+ const node = nodes[nodeIndex]; const object = new THREE.Group(); object.name = String(node.name || `Object ${nodeIndex + 1}`);
366
+ // Pick-map ownership may be recorded on a transform-only ancestor. Propagate only a real receipt;
367
+ // provider decoration and any other unowned drawable must never acquire a display-name identity.
368
+ const explicitOwner = ownerByNode.has(object.name) ? ownerByNode.get(object.name) : null;
369
+ if (explicitOwner != null && (typeof explicitOwner !== 'string' || explicitOwner.length === 0)) throw new Error('The geometry tile contains an invalid entity ownership receipt.');
370
+ const mappedOwner = explicitOwner ?? inheritedOwner;
371
+ object.userData.entityId = mappedOwner;
372
+ if (Array.isArray(node.matrix)) {
373
+ if (node.matrix.length !== 16 || node.matrix.some((value) => !Number.isFinite(value))) throw new Error('The geometry tile node matrix is invalid.');
374
+ // Do not decompose: glTF matrices may contain affine transforms that TRS cannot reproduce.
375
+ object.matrix.fromArray(node.matrix); object.matrixAutoUpdate = false;
376
+ } else {
377
+ if (node.translation) object.position.fromArray(node.translation);
378
+ if (node.rotation) object.quaternion.fromArray(node.rotation);
379
+ if (node.scale) object.scale.fromArray(node.scale);
380
+ }
381
+ if (Number.isInteger(node.mesh)) {
382
+ const meshDef = json.meshes?.[node.mesh];
383
+ for (const primitive of meshDef?.primitives ?? []) {
384
+ if (primitive.mode !== undefined && primitive.mode !== 4) continue;
385
+ let geometry = null;
386
+ try {
387
+ const pos = accessor(json, binary, primitive.attributes?.POSITION); geometry = new THREE.BufferGeometry();
388
+ geometry.setAttribute('position', new THREE.BufferAttribute(pos.array, pos.width, pos.normalized));
389
+ const hasNormals = Number.isInteger(primitive.attributes?.NORMAL);
390
+ if (hasNormals) { const normal = normalAccessor(json, binary, primitive.attributes.NORMAL, pos.array.length / pos.width); geometry.setAttribute('normal', new THREE.BufferAttribute(normal.array, normal.width, normal.normalized)); }
391
+ let hasVertexColors = false;
392
+ if (Number.isInteger(primitive.attributes?.COLOR_0)) {
393
+ const color = colorAccessor(json, binary, primitive.attributes.COLOR_0, pos.array.length / pos.width);
394
+ geometry.setAttribute('color', new THREE.BufferAttribute(color.array, color.width, color.normalized));
395
+ hasVertexColors = true;
396
+ }
397
+ if (Number.isInteger(primitive.indices)) { const indices = accessor(json, binary, primitive.indices); geometry.setIndex(new THREE.BufferAttribute(indices.array, 1)); }
398
+ let sourceMaterial;
399
+ if (primitive.material !== undefined) {
400
+ if (!Number.isInteger(primitive.material) || primitive.material < 0 || primitive.material >= (json.materials?.length ?? 0)) {
401
+ throw new Error('The geometry tile primitive references an invalid material.');
402
+ }
403
+ sourceMaterial = json.materials[primitive.material];
404
+ }
405
+ const mesh = new THREE.Mesh(geometry, materialFor(sourceMaterial, hasVertexColors, !hasNormals));
406
+ mesh.userData.entityId = mappedOwner; object.add(mesh); meshes.push(mesh);
407
+ if (object.name === PROVIDER_WATERMARK_NODE) {
408
+ if (mappedOwner != null) throw new Error('The provider watermark cannot own a model entity.');
409
+ mesh.userData.revitDecoration = true; decorationMeshes.push(mesh);
410
+ } else if (mappedOwner != null) {
411
+ ownedMeshes.push(mesh);
412
+ } else {
413
+ throw new Error('The geometry tile contains an unowned drawable node.');
414
+ }
415
+ } catch (error) {
416
+ if (geometry && !meshes.some((mesh) => mesh.geometry === geometry)) geometry.dispose();
417
+ throw error;
418
+ }
419
+ }
420
+ }
421
+ for (const childIndex of node.children ?? []) object.add(nodeObject(childIndex, mappedOwner));
422
+ active.delete(nodeIndex);
423
+ return object;
424
+ };
425
+
426
+ try {
427
+ for (const nodeIndex of selectedScene.nodes) root.add(nodeObject(nodeIndex));
428
+ } catch (error) {
429
+ disposeMeshes(meshes);
430
+ throw error;
431
+ }
432
+ root.matrix.fromArray(frame.matrix); root.matrixAutoUpdate = false;
433
+ let disposed = false;
434
+ const dispose = () => {
435
+ if (disposed) return;
436
+ disposed = true;
437
+ disposeMeshes(meshes);
438
+ };
439
+ return { root, meshes, ownedMeshes, decorationMeshes, dispose };
440
+ }
441
+
442
+ /** One executable owner for attach, replacement, and terminal release of a parsed Revit scene. */
443
+ function createRevitSceneGeneration(next, lifecycle) {
444
+ if (!next?.root || typeof next.dispose !== 'function') throw new TypeError('A parsed Revit scene is required.');
445
+ if (!lifecycle || typeof lifecycle.attach !== 'function' || typeof lifecycle.activate !== 'function'
446
+ || typeof lifecycle.detach !== 'function' || typeof lifecycle.release !== 'function') {
447
+ throw new TypeError('A complete Revit scene lifecycle is required.');
448
+ }
449
+ let activated = false; let released = false;
450
+ return Object.freeze({
451
+ activate() {
452
+ if (released) throw new Error('The staged Revit generation was already released.');
453
+ lifecycle.attach(next.root); activated = true; lifecycle.activate(next);
454
+ },
455
+ dispose() {
456
+ if (released) return;
457
+ released = true;
458
+ const errors = [];
459
+ try { lifecycle.detach(next.root); } catch (error) { errors.push(error); }
460
+ try { next.dispose(); } catch (error) { errors.push(error); }
461
+ if (activated) { try { lifecycle.release(next); } catch (error) { errors.push(error); } }
462
+ if (errors.length) throw new AggregateError(errors, 'Revit scene generation disposal failed.');
463
+ },
464
+ });
465
+ }
466
+
467
+ /** The exact generation factory used by the real adapter and controller lifecycle tests. */
468
+ export function createRevitViewportGeneration({ next, records, scene, onActivate, onRelease }) {
469
+ if (!scene || typeof scene.add !== 'function' || typeof scene.remove !== 'function') {
470
+ throw new TypeError('A Revit generation scene is required.');
471
+ }
472
+ if (typeof onActivate !== 'function' || typeof onRelease !== 'function') {
473
+ throw new TypeError('Revit generation state callbacks are required.');
474
+ }
475
+ const lifecycle = createRevitSceneGeneration(next, {
476
+ attach: (root) => scene.add(root), activate: onActivate,
477
+ detach: (root) => scene.remove(root), release: onRelease,
478
+ });
479
+ return Object.freeze({ records, ...lifecycle });
480
+ }
481
+
482
+ export function applyRevitDisplayMode(meshes, next, presentation = {}) {
483
+ const selectedIds = new Set(presentation.selectedIds ?? []);
484
+ const ghostActive = presentation.ghostUnselected === true && selectedIds.size > 0;
485
+ const wire = next === 'wire';
486
+ const hoveredId = typeof presentation.hoveredId === 'string' ? presentation.hoveredId : null;
487
+ const materials = presentation.edgeMaterials ?? null;
488
+ for (const mesh of meshes) {
489
+ const material = mesh.material;
490
+ const wasTransparent = material.transparent;
491
+ const authored = material.userData.revitAuthoredAlpha ?? { opacity: 1, transparent: false, depthWrite: true };
492
+ const ghosted = ghostActive && !selectedIds.has(mesh.userData.entityId);
493
+ const outline = mesh.userData.revitOutline ?? null;
494
+ // Never `material.wireframe` — that is the triangulation this change exists to stop drawing.
495
+ material.wireframe = false;
496
+ if (next === 'xray') {
497
+ material.transparent = true;
498
+ material.opacity = authored.opacity * (ghosted ? 0.08 : 0.28);
499
+ material.depthWrite = false;
500
+ } else if (ghosted) {
501
+ material.transparent = true;
502
+ material.opacity = Math.min(authored.opacity, 0.18);
503
+ material.depthWrite = false;
504
+ } else {
505
+ // `realistic` is an opaque mode exactly as `solid` is: it changes the LIGHTING, not the alpha.
506
+ material.transparent = authored.transparent;
507
+ material.opacity = authored.opacity;
508
+ material.depthWrite = authored.depthWrite;
509
+ }
510
+ // Hide the FILL's material, never the mesh: `mesh.visible = false` would also hide the outline
511
+ // that is its child, and Three still raycasts a mesh whose material is invisible — which is what
512
+ // keeps picking working in Wireframe.
513
+ // The fill is only surrendered once this mesh's outline actually exists. Outlines are built
514
+ // progressively on a large model, and hiding every fill up front would show an empty viewport
515
+ // until the build caught up.
516
+ material.visible = !(wire && outline);
517
+ if (outline) {
518
+ outline.visible = wire;
519
+ if (wire && materials) {
520
+ const chosen = selectedIds.has(mesh.userData.entityId);
521
+ const hovered = hoveredId === mesh.userData.entityId;
522
+ // Selected outranks hovered, and this ternary is the ONLY place that says so — guarding
523
+ // `hovered` with `!chosen` as well would state the precedence twice, which leaves each copy
524
+ // free to rot without a test noticing.
525
+ const hex = chosen ? REVIT_EDGE_SELECTED : hovered ? REVIT_EDGE_HOVERED : REVIT_EDGE_COLOUR;
526
+ // Ghosting fades the OUTLINE — the fill it would otherwise fade is not the drawn thing here.
527
+ // Reassigned from the cache rather than mutated: the material is shared with every other
528
+ // outline of the same colour and opacity.
529
+ outline.material = materials.get(hex, ghosted ? 0.18 : 1);
530
+ }
531
+ }
532
+ if (material.transparent !== wasTransparent) material.needsUpdate = true;
533
+ }
534
+ }
535
+
536
+ /** Base visibility and spatial eligibility are independent filters; neither may resurrect the other. */
537
+ export function composeRevitVisibility(baseVisible, spatialEligible) {
538
+ return baseVisible === true && spatialEligible === true;
539
+ }
540
+
541
+ /** Translate the shared clip-state shape (`origin`) into the model-frame plane shape (`point`). */
542
+ export function revitClipPlaneForRenderer(frame, value) {
543
+ const transformed = frame.canonicalToRenderPlane({ point: value?.origin, normal: value?.normal });
544
+ const normal = new THREE.Vector3().fromArray(transformed.normal).normalize();
545
+ const point = new THREE.Vector3().fromArray(transformed.point);
546
+ return new THREE.Plane(normal, -normal.dot(point));
547
+ }
548
+
549
+ // Isolate keeps each mesh's visibility from before it, so lifting the isolation (Ghost unselected taking over) brings
550
+ // back only what Isolate hid. A hide made while isolated is folded in; anything else that sets visibility (Show all,
551
+ // a restored view, a new revision) forgets it.
552
+ export function createRevitIsolation() {
553
+ let before = null;
554
+ return {
555
+ isolate(visibility, meshes, keep) {
556
+ before = before ?? new Map(meshes.map((mesh) => [mesh, visibility.get(mesh)]));
557
+ meshes.forEach((mesh) => visibility.set(mesh, keep(mesh)));
558
+ },
559
+ hid(meshes) { if (before) meshes.forEach((mesh) => before.set(mesh, false)); },
560
+ active: () => before !== null,
561
+ clear(visibility) { if (!before) return false; before.forEach((visible, mesh) => visibility.set(mesh, visible)); before = null; return true; },
562
+ forget() { before = null; },
563
+ };
564
+ }
565
+
566
+ export function createRevitViewport({ canvas, onSelect = () => {}, onOutlineBuild = () => {} }) {
567
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false }); renderer.setPixelRatio(Math.min(devicePixelRatio || 1, 2)); renderer.setClearColor(0x020817, 1); renderer.localClippingEnabled = true;
568
+ const scene = new THREE.Scene(); const overlayScene = new THREE.Scene();
569
+ const ambient = new THREE.AmbientLight(0xffffff, 1.6); scene.add(ambient);
570
+ const key = new THREE.DirectionalLight(0xffffff, 1.4); scene.add(key); scene.add(key.target);
571
+ let lighting = MODEL_LIGHTING_DEFAULTS;
572
+ const perspective = new THREE.PerspectiveCamera(45, 1, 0.01, 100000); const orthographic = new THREE.OrthographicCamera(-10, 10, 10, -10, 0.01, 100000);
573
+ perspective.up.set(0, 0, 1); orthographic.up.set(0, 0, 1);
574
+ perspective.position.set(1, -1, 1); orthographic.position.copy(perspective.position);
575
+ perspective.lookAt(0, 0, 0); orthographic.lookAt(0, 0, 0);
576
+ let camera = perspective; let model = null; let modelDisposer = null; let meshes = []; let ownedMeshes = []; let mode = 'solid'; let selected = []; let hoveredId = null; let ghostUnselected = false; let disposed = false; let mounted = false; let shown = false; let paintAllowed = false; let orthoSpan = 10; let geometryFrame = revitGeometryFrame();
577
+ let mountContext = null; let inputArbiter = null; let releaseClipInput = null; let releaseClipOverlayInput = null; let pendingLoad = null; let loadSequence = 0; let controller = null;
578
+ let spatialTools = null; let releaseSpatial = null; let spatialState = null; let workPlaneHelper = null;
579
+ // Outline materials are shared across generations (they are keyed by colour and opacity, not by
580
+ // model), so the cache lives with the VIEWPORT and is disposed exactly once, at viewport disposal.
581
+ const edgeMaterials = createRevitEdgeMaterials();
582
+ let outlineJob = null; let sceneGeneration = 0;
583
+ // Realistic's global state lives HERE, with the renderer and the lights, not in the mesh-level
584
+ // display-mode helper — that helper is handed meshes and cannot reach any of this.
585
+ let environmentTarget = null; let environmentFailed = false; let environmentLive = false;
586
+ let environmentUp = null; // the up direction the last bake ATTEMPT was for, success or failure
587
+ function applyRealistic() {
588
+ const want = mode === 'realistic';
589
+ // RoomEnvironment is authored Y-up. Revit's render frame is not always Y-up, so the bake is
590
+ // oriented to whichever direction canonical up maps to.
591
+ const up = new THREE.Vector3().fromArray(geometryFrame.canonicalToRenderDirection([0, 0, 1])).normalize();
592
+ // geometryFrame is REASSIGNED on every generation activation, and a v1 manifest's render matrix
593
+ // is not a v2's — so a bake cached from the previous model would light this one from its side,
594
+ // with no way back short of reloading the page. Re-bake when the up direction actually changed.
595
+ //
596
+ // Keyed on the last ATTEMPT, not on a surviving target: a bake that threw leaves no target, so a
597
+ // check guarded on one could never clear environmentFailed, and a single failure would latch
598
+ // Realistic off for the rest of the session — including on a later model where it would have
599
+ // worked. Retrying is still bounded to once per changed frame, not once per render.
600
+ if (environmentUp && environmentUp.angleTo(up) > 1e-6) {
601
+ environmentTarget?.dispose(); environmentTarget = null; environmentUp = null; environmentFailed = false;
602
+ }
603
+ if (want && !environmentTarget && !environmentFailed) {
604
+ let pmrem = null; let room = null;
605
+ try {
606
+ pmrem = new THREE.PMREMGenerator(renderer);
607
+ room = new RoomEnvironment();
608
+ room.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), up);
609
+ environmentTarget = pmrem.fromScene(room, 0.04);
610
+ } catch (error) {
611
+ // Half-applying is the one outcome to avoid: it would ship an unlit scene. Fall back to
612
+ // Solid's treatment whole, and let the UI say so rather than failing silently.
613
+ environmentFailed = true; console.warn('Revit Realistic is unavailable:', error);
614
+ } finally {
615
+ // Both are scaffolding for the bake and are dead the moment it returns -- and the generator
616
+ // holds GPU allocations, so skipping this on the throwing path would leak them for the life
617
+ // of the renderer, which is exactly the path least likely to be exercised.
618
+ pmrem?.dispose();
619
+ room?.dispose?.();
620
+ // Recorded on BOTH paths, because it is what bounds a retry: a failure remembers the frame
621
+ // it failed for, so it is not retried every render, and IS retried when the frame changes.
622
+ environmentUp = up.clone();
623
+ }
624
+ }
625
+ environmentLive = want && !!environmentTarget;
626
+ scene.environment = environmentLive ? environmentTarget.texture : null;
627
+ // Per material, because three r160 has no scene.environmentIntensity.
628
+ for (const mesh of ownedMeshes) mesh.material.envMapIntensity = environmentLive ? REALISTIC_ENV_INTENSITY : 1;
629
+ // The watermark shares the model scene, so the environment would relight it too. It is provider
630
+ // chrome, not model geometry, and must read identically in every display mode.
631
+ for (const mesh of meshes) if (mesh.userData.revitDecoration) mesh.material.envMapIntensity = 0;
632
+ // Deliberately NOT filmic, which is where Revit parts company with the Steel viewer. Steel needs
633
+ // ACES because metal is all reflection and needs the filmic curve to read at all. A converted
634
+ // Revit model is matte, untextured dielectrics whose colour IS the content, and measured on the
635
+ // Residential production model ACES simply washed those colours out: the lawn went pale mint and
636
+ // the building lost the contrast it has in Solid. Tested with it off and the colours come back
637
+ // while the environment still adds the softer shading this mode is for.
638
+ renderer.toneMapping = THREE.NoToneMapping;
639
+ // Derived from the live mode every time, never replayed from a snapshot — which is what makes a
640
+ // rebuild and a mid-mode Lighting change safe.
641
+ applyLighting(lighting);
642
+ }
643
+ /** Whether Realistic is actually shading the model, so the UI can say when it could not. */
644
+ function realisticState() {
645
+ return { requested: mode === 'realistic', live: environmentLive, unavailable: environmentFailed };
646
+ }
647
+ // rAF paces the build against real frames, which is what keeps it off the main thread's back. But
648
+ // rAF is STARVED whenever the page is not being composited — an occluded window, a background tab,
649
+ // a remote or virtual display — and `document.visibilityState` still reports "visible" in those
650
+ // cases, so there is no flag to branch on. Without a fallback the build simply never resumes and
651
+ // Wireframe shows solid fills forever, silently. Whichever timer arrives first wins; the other
652
+ // becomes a no-op.
653
+ const scheduleOutlineStep = (step) => {
654
+ let ran = false;
655
+ const once = () => { if (ran) return; ran = true; step(); };
656
+ if (typeof requestAnimationFrame === 'function') requestAnimationFrame(once);
657
+ setTimeout(once, OUTLINE_FALLBACK_MS);
658
+ };
659
+ // Cancelled whenever the mode leaves Wireframe, a new generation activates, or the viewport is
660
+ // disposed — so a job can never attach outlines to a scene that has been retired.
661
+ function cancelOutlineJob() { outlineJob?.cancel(); outlineJob = null; }
662
+ function ensureOutlines() {
663
+ if (mode !== 'wire' || !ownedMeshes.length) return;
664
+ if (outlineJob && outlineJob.generation === sceneGeneration && !outlineJob.cancelled) {
665
+ outlineJob.start(); // resumes a stopped job at its cursor; a finished one is a no-op
666
+ return;
667
+ }
668
+ cancelOutlineJob();
669
+ if (ownedMeshes.length >= OUTLINE_ANNOUNCE_THRESHOLD) { try { onOutlineBuild(ownedMeshes.length); } catch { /* an announcement must never break the build */ } }
670
+ outlineJob = createRevitOutlineBuilder({
671
+ meshes: ownedMeshes, materials: edgeMaterials, generation: sceneGeneration,
672
+ schedule: scheduleOutlineStep,
673
+ // Each batch repaints, so the finished outlines appear and their fills stand down together.
674
+ // Guarded on the generation: a batch that lands after a rebuild must not paint the new scene.
675
+ onBatch: () => { if (outlineJob?.generation === sceneGeneration) paintSelection(ownedMeshes, selected); },
676
+ });
677
+ outlineJob.start();
678
+ }
679
+ let clipSession = null; let releaseClipSession = null; let clipEdit = null;
680
+ let baseVisibility = new Map(); const isolation = createRevitIsolation(); let spatialVisibilityBox = null; let activeRenderPlanes = []; let clipSeq = 0;
681
+ const identityRegistry = createEntityKeyRegistry();
682
+ const selectionCoordinator = createModelSelectionCoordinator({
683
+ registry: identityRegistry,
684
+ onCommit(commit, entries) {
685
+ controller?.commitSelection(commit);
686
+ onSelect(entries.map((entry) => entry.sourceId));
687
+ },
688
+ });
689
+ const orbitInput = createCadOrbitEventProxy(canvas);
690
+ const controls = new OrbitControls(camera, orbitInput.element);
691
+ const ray = new THREE.Raycaster(); const pointer = new THREE.Vector2();
692
+ const cameraListeners = new Set();
693
+ const orientationListeners = new Set();
694
+ const pointerWorldListeners = new Set();
695
+ let snapIndex = buildModelSnapIndex([]);
696
+ const setRayAt = (clientX, clientY) => {
697
+ const rect = canvas.getBoundingClientRect(); if (!rect.width || !rect.height) return null;
698
+ pointer.set(((clientX - rect.left) / rect.width) * 2 - 1, -((clientY - rect.top) / rect.height) * 2 + 1);
699
+ ray.setFromCamera(pointer, camera); return ray.ray;
700
+ };
701
+ const ownerHitsAt = (clientX, clientY) => {
702
+ if (!setRayAt(clientX, clientY)) return [];
703
+ const hits = ray.intersectObjects(ownedMeshes.filter((mesh) => mesh.visible), false)
704
+ .filter((hit) => activeRenderPlanes.every((plane) => plane.distanceToPoint(hit.point) >= -1e-7));
705
+ if (ghostUnselected && selected.length) hits.sort((a, b) => (Number(selected.includes(b.object.userData.entityId)) - Number(selected.includes(a.object.userData.entityId))) || (a.distance - b.distance));
706
+ return hits;
707
+ };
708
+ const qualifiedHitAt = (clientX, clientY) => {
709
+ const hit = ownerHitsAt(clientX, clientY)[0]; const receipt = hit?.object?.userData?.entityReceipt;
710
+ if (!hit || !receipt) return null;
711
+ return { ...receipt, providerToken: hit.object.userData.entityId, point: hit.point?.toArray() ?? null,
712
+ normal: hit.face?.normal?.toArray() ?? null, distance: hit.distance };
713
+ };
714
+ const pickSurface = (clientX, clientY) => ownerHitsAt(clientX, clientY)[0]?.point?.toArray() ?? null;
715
+ const orientationPose = () => modelOrientationPose({ v: 1, camera: {
716
+ position: camera.position.toArray(), target: controls.target.toArray(), up: camera.up.toArray(),
717
+ } });
718
+ const notifyCamera = () => {
719
+ const inverse = camera.quaternion.clone().invert();
720
+ const basis = {
721
+ x: new THREE.Vector3(1, 0, 0).applyQuaternion(inverse).toArray(),
722
+ y: new THREE.Vector3(0, 1, 0).applyQuaternion(inverse).toArray(),
723
+ z: new THREE.Vector3(0, 0, 1).applyQuaternion(inverse).toArray(),
724
+ };
725
+ for (const listener of cameraListeners) listener(basis);
726
+ const pose = orientationPose(); for (const listener of orientationListeners) listener(pose);
727
+ mountContext?.reportCameraState?.();
728
+ };
729
+ function resize(size = {}) { const w = Math.max(1, size.width ?? canvas.clientWidth), h = Math.max(1, size.height ?? canvas.clientHeight); renderer.setPixelRatio(Math.min(size.pixelRatio ?? devicePixelRatio ?? 1, 2)); renderer.setSize(w, h, false); perspective.aspect = w / h; perspective.updateProjectionMatrix(); orthographic.left = -orthoSpan * w / h; orthographic.right = orthoSpan * w / h; orthographic.top = orthoSpan; orthographic.bottom = -orthoSpan; orthographic.updateProjectionMatrix(); }
730
+ function bounds(objects = ownedMeshes) { const box = new THREE.Box3(); objects.forEach((mesh) => { if (mesh.visible) box.expandByObject(mesh); }); return box; }
731
+ function applyLighting(value = lighting) {
732
+ lighting = normalizeModelLighting(value);
733
+ // Realistic REBALANCES this rig rather than adding to it. Ambient 1.6 and key 1.4 are bright
734
+ // enough to flatten the environment's contribution to nothing, so an unrebalanced Realistic looks
735
+ // like Solid with shifted colours — a mode that changes the picture without improving it.
736
+ //
737
+ // This is the ONLY writer of the light intensities, and it derives them from the user's current
738
+ // lighting every time. Scaling the lights somewhere else instead would be silently undone by the
739
+ // Lighting dialog or by a rebuild (which re-runs this function on activation), and leaving the
740
+ // mode would restore whatever was captured on entry rather than what the user has now.
741
+ const realistic = mode === 'realistic' && environmentLive;
742
+ const ambientScale = realistic ? REALISTIC_AMBIENT_SCALE : 1;
743
+ const keyScale = realistic ? REALISTIC_KEY_SCALE : 1;
744
+ ambient.intensity = 1.6 * lighting.ambientBrightness * ambientScale;
745
+ key.intensity = lighting.sunlight ? 1.4 * lighting.sunBrightness * keyScale : 0;
746
+ const box = bounds(ownedMeshes); const centre = box.isEmpty() ? new THREE.Vector3() : box.getCenter(new THREE.Vector3());
747
+ const radius = box.isEmpty() ? 5 : box.getBoundingSphere(new THREE.Sphere()).radius;
748
+ const canonicalDirection = modelSunDirection(lighting);
749
+ const direction = new THREE.Vector3().fromArray(geometryFrame.canonicalToRenderDirection(canonicalDirection)).normalize();
750
+ key.position.copy(centre).addScaledVector(direction, Math.max(radius * 2, 10));
751
+ key.target.position.copy(centre); key.target.updateMatrixWorld();
752
+ return lighting;
753
+ }
754
+ applyLighting();
755
+ const canonicalBounds = (objects = ownedMeshes) => {
756
+ const box = bounds(objects); if (box.isEmpty()) return null;
757
+ return geometryFrame.renderToCanonicalBounds({ min: box.min.toArray(), max: box.max.toArray() });
758
+ };
759
+ const visibleCanonicalBounds = () => canonicalBounds(ownedMeshes.filter((mesh) => hasVisibleFragment(mesh)));
760
+ const clippingPlanesForBox = ({ min, max }) => [
761
+ { origin: [min[0], 0, 0], normal: [1, 0, 0] }, { origin: [max[0], 0, 0], normal: [-1, 0, 0] },
762
+ { origin: [0, min[1], 0], normal: [0, 1, 0] }, { origin: [0, max[1], 0], normal: [0, -1, 0] },
763
+ { origin: [0, 0, min[2]], normal: [0, 0, 1] }, { origin: [0, 0, max[2]], normal: [0, 0, -1] },
764
+ ];
765
+ const toThreePlane = (value) => revitClipPlaneForRenderer(geometryFrame, value);
766
+ const recomputeVisibility = () => {
767
+ for (const mesh of ownedMeshes) {
768
+ const inArea = !spatialVisibilityBox || spatialVisibilityBox.intersectsBox(new THREE.Box3().setFromObject(mesh));
769
+ mesh.visible = composeRevitVisibility(baseVisibility.get(mesh) !== false, inArea);
770
+ }
771
+ };
772
+ const paintSpatialState = (state) => {
773
+ spatialState = state;
774
+ const planes = [];
775
+ for (const clip of state?.clips ?? []) {
776
+ if (clip.enabled === false) continue;
777
+ if (clip.kind === 'plane') planes.push(toThreePlane(clip));
778
+ else if (clip.kind === 'box') planes.push(...clippingPlanesForBox(clip).map(toThreePlane));
779
+ }
780
+ const area = state?.workArea?.visible ? state.workArea : null;
781
+ if (area?.wholeParts) {
782
+ const renderArea = geometryFrame.canonicalToRenderBounds(area);
783
+ spatialVisibilityBox = new THREE.Box3(new THREE.Vector3().fromArray(renderArea.min), new THREE.Vector3().fromArray(renderArea.max));
784
+ } else {
785
+ spatialVisibilityBox = null;
786
+ if (area) planes.push(...clippingPlanesForBox(area).map(toThreePlane));
787
+ }
788
+ activeRenderPlanes = planes;
789
+ recomputeVisibility();
790
+ for (const mesh of ownedMeshes) mesh.material.clippingPlanes = planes;
791
+ edgeMaterials.setClippingPlanes(planes);
792
+ if (workPlaneHelper) { scene.remove(workPlaneHelper); workPlaneHelper.geometry.dispose(); workPlaneHelper.material.dispose(); workPlaneHelper = null; }
793
+ const workPlane = state?.workPlane?.visible ? state.frames?.find((frame) => frame.id === state.workPlane.frameId) : null;
794
+ if (workPlane) {
795
+ const model = canonicalBounds(); const span = model ? Math.max(...model.max.map((value, axis) => value - model.min[axis]), 1000) : 10000;
796
+ workPlaneHelper = new THREE.GridHelper(geometryFrame.canonicalToRenderDistance(span), 20, 0x3b82f6, 0x334155);
797
+ workPlaneHelper.geometry.rotateX(Math.PI / 2);
798
+ const x = new THREE.Vector3().fromArray(geometryFrame.canonicalToRenderDirection(workPlane.xAxis));
799
+ const y = new THREE.Vector3().fromArray(geometryFrame.canonicalToRenderDirection(workPlane.yAxis));
800
+ const z = new THREE.Vector3().fromArray(geometryFrame.canonicalToRenderDirection(workPlane.zAxis));
801
+ const matrix = new THREE.Matrix4().makeBasis(x, y, z); workPlaneHelper.quaternion.setFromRotationMatrix(matrix);
802
+ workPlaneHelper.position.fromArray(geometryFrame.canonicalToRenderPoint(workPlane.origin)); scene.add(workPlaneHelper);
803
+ }
804
+ paintSelection(ownedMeshes, selected);
805
+ mountContext?.reportSectionState?.();
806
+ };
807
+ function fit(objects = ownedMeshes, direction = MODEL_NAMED_VIEWS.iso) { const box = bounds(objects); if (box.isEmpty()) return; const sphere = box.getBoundingSphere(new THREE.Sphere()); orthoSpan = Math.max(sphere.radius * 1.35, .1); const view = new THREE.Vector3().fromArray(direction).normalize(); camera.position.copy(sphere.center).addScaledVector(view, Math.max(sphere.radius * 2.8, 1)); camera.near = Math.max(sphere.radius / 10000, .001); camera.far = Math.max(sphere.radius * 100, 100); camera.updateProjectionMatrix(); controls.object = camera; controls.target.copy(sphere.center); camera.lookAt(sphere.center); controls.update(); resize(); notifyCamera(); }
808
+ function applyView(name) { const direction = MODEL_NAMED_VIEWS[name]; if (direction) fit(ownedMeshes, direction); }
809
+ function applyDirection(direction) {
810
+ if (!Array.isArray(direction) || direction.length !== 3 || !direction.every(Number.isFinite)) throw new TypeError('View direction must be a finite vector.');
811
+ if (new THREE.Vector3().fromArray(direction).lengthSq() <= Number.EPSILON) throw new TypeError('View direction must be non-zero.');
812
+ fit(ownedMeshes, direction);
813
+ }
814
+ const hasVisibleFragment = (mesh) => {
815
+ if (!mesh.visible) return false;
816
+ const planes = mesh.material.clippingPlanes ?? []; if (!planes.length) return true;
817
+ const box = new THREE.Box3().setFromObject(mesh);
818
+ const corners = [];
819
+ for (const x of [box.min.x, box.max.x]) for (const y of [box.min.y, box.max.y]) for (const z of [box.min.z, box.max.z]) corners.push(new THREE.Vector3(x, y, z));
820
+ return planes.every((plane) => corners.some((point) => plane.distanceToPoint(point) >= 0));
821
+ };
822
+ const clipCreationPreview = createModelClipThreePreview({
823
+ THREE, overlayScene, canvas, getCamera: () => camera,
824
+ canonicalToRenderPoint: (point) => geometryFrame.canonicalToRenderPoint(point),
825
+ });
826
+ const resolveClipPlane = ({ clientX, clientY }) => {
827
+ const hit = ownerHitsAt(clientX, clientY).find((item) => item.face?.normal && item.point); if (!hit) return null;
828
+ hit.object.updateMatrixWorld(true);
829
+ const renderNormal = hit.face.normal.clone().applyMatrix3(new THREE.Matrix3().getNormalMatrix(hit.object.matrixWorld)).normalize();
830
+ const canonicalRay = geometryFrame.renderToCanonicalRay({ origin: ray.ray.origin.toArray(), direction: ray.ray.direction.toArray() });
831
+ const canonicalNormal = geometryFrame.renderToCanonicalNormal(renderNormal.toArray());
832
+ return { point: geometryFrame.renderToCanonicalPoint(hit.point.toArray()), normal: orientClipNormalAwayFromCamera(canonicalNormal, canonicalRay.direction) };
833
+ };
834
+ const resolveClipFloor = ({ clientX, clientY }, floorZ) => {
835
+ if (!setRayAt(clientX, clientY)) return null;
836
+ const transformed = geometryFrame.canonicalToRenderPlane({ point: [0, 0, floorZ], normal: [0, 0, 1] });
837
+ const normal = new THREE.Vector3().fromArray(transformed.normal).normalize(); const point = new THREE.Vector3().fromArray(transformed.point);
838
+ const hit = ray.ray.intersectPlane(new THREE.Plane(normal, -normal.dot(point)), new THREE.Vector3());
839
+ return hit ? { point: geometryFrame.renderToCanonicalPoint(hit.toArray()), snap: null } : null;
840
+ };
841
+ const resolveClipHeight = ({ clientX, clientY }, draft) => {
842
+ if (!setRayAt(clientX, clientY)) return null;
843
+ const current = geometryFrame.renderToCanonicalRay({ origin: ray.ray.origin.toArray(), direction: ray.ray.direction.toArray() });
844
+ const origin = current.origin; const direction = current.direction;
845
+ const centre = [(draft.a[0] + draft.b[0]) / 2, (draft.a[1] + draft.b[1]) / 2, draft.floorZ];
846
+ const w = centre.map((value, axis) => value - origin[axis]); const b = direction[2];
847
+ const d = w[2]; const e = direction.reduce((sum, value, axis) => sum + value * w[axis], 0); const denominator = 1 - b * b;
848
+ const along = Math.abs(denominator) < 1e-6 ? d : (b * e - d) / denominator;
849
+ const z = draft.floorZ + Math.max(along, 1); return { z, point: [centre[0], centre[1], z], snap: null };
850
+ };
851
+ const nextClipIdentity = (kind) => {
852
+ const existing = new Set((spatialState?.clips ?? []).map((clip) => clip.id)); let id;
853
+ do { clipSeq += 1; id = `clip-${clipSeq}`; } while (existing.has(id));
854
+ const sameKind = (spatialState?.clips ?? []).filter((clip) => clip.kind === kind).length + 1;
855
+ return { id, label: `${kind === 'plane' ? 'Plane' : 'Box'} ${sameKind}` };
856
+ };
857
+ const clipGesture = createModelClipGesture({
858
+ visibleBounds: visibleCanonicalBounds,
859
+ resolvePlane: resolveClipPlane,
860
+ resolveFloor: resolveClipFloor,
861
+ resolveHeight: resolveClipHeight,
862
+ preview: (value) => clipCreationPreview.show(value),
863
+ commitPlane(value) { if (clipSession) clipSession.addPlane({ origin: value.point, normal: value.normal }); else { const tools = spatialTools; if (!tools) throw new Error('Shared spatial tools are not mounted.'); tools.addClipPlane({ ...nextClipIdentity('plane'), origin: value.point, normal: value.normal }); } },
864
+ commitBox(value) { if (clipSession) clipSession.addBox(value); else { const tools = spatialTools; if (!tools) throw new Error('Shared spatial tools are not mounted.'); tools.addClipBox({ ...nextClipIdentity('box'), ...value }); } },
865
+ onState(value) { if (!value.active) releaseClipInput?.deactivate?.(); mountContext?.reportSectionState?.(); },
866
+ onCursor(value) { canvas.style.cursor = value; },
867
+ });
868
+ const clipReadout = document.createElement('div'); clipReadout.className = 'model-clip-drag-readout'; clipReadout.hidden = true; canvas.parentElement?.append(clipReadout);
869
+ const clipGeometryPatch = (clip) => clip.kind === 'plane'
870
+ ? { origin: [...(clip.origin ?? clip.point)], normal: [...(clip.normal ?? clip.n)] }
871
+ : { min: [...(clip.box?.min ?? clip.min)], max: [...(clip.box?.max ?? clip.max)] };
872
+ const clipOverlay = createModelClipThreeOverlay({
873
+ THREE, overlayScene, canvas, getCamera: () => camera,
874
+ rayAt(clientX, clientY) { const value = setRayAt(clientX, clientY); return value ? { origin: value.origin, direction: value.direction } : { origin: camera.position, direction: new THREE.Vector3(0, 0, -1) }; },
875
+ canonicalToRenderPoint: (point) => geometryFrame.canonicalToRenderPoint(point),
876
+ canonicalToRenderDirection: (direction) => geometryFrame.canonicalToRenderDirection(direction),
877
+ renderToCanonicalPoint: (point) => geometryFrame.renderToCanonicalPoint(point),
878
+ getClips: () => clipSession?.clips?.() ?? spatialState?.clips ?? [],
879
+ getSelectedClipIds: () => clipSession?.selected?.() ?? [],
880
+ isPlacementArmed: () => clipGesture.state().active !== null,
881
+ formatDistance: (valueMm) => `${Math.round(valueMm)} mm`,
882
+ update({ clipId, clip }) {
883
+ if (!clipSession) return;
884
+ clipEdit ||= clipSession.beginLogicalEdit('clip-handle-drag');
885
+ clipEdit.update(clipId, clipGeometryPatch(clip));
886
+ },
887
+ commit() { clipEdit?.finish(); clipEdit = null; clipReadout.hidden = true; },
888
+ cancel() { clipEdit?.finish(); clipEdit = null; clipReadout.hidden = true; },
889
+ readout(value) {
890
+ if (value?.hidden || !value?.readout?.text) { clipReadout.hidden = true; return; }
891
+ clipReadout.textContent = `${value.readout.text}${value.readout.type ? ` · ${value.readout.type}` : ''}`;
892
+ clipReadout.style.left = `${value.event.clientX + 14}px`; clipReadout.style.top = `${value.event.clientY + 14}px`; clipReadout.hidden = false;
893
+ },
894
+ });
895
+ function paintSelection(items, ids) {
896
+ const eligible = ids.filter((id) => items.some((mesh) => mesh.userData.entityId === id && hasVisibleFragment(mesh)));
897
+ const set = new Set(eligible);
898
+ applyRevitDisplayMode(items, mode, { selectedIds: eligible, ghostUnselected, hoveredId, edgeMaterials });
899
+ items.forEach((mesh) => {
900
+ const chosen = set.has(mesh.userData.entityId); const hovered = !chosen && hoveredId === mesh.userData.entityId;
901
+ mesh.material.emissive?.set(chosen ? 0x2563eb : hovered ? 0x0ea5e9 : 0x000000);
902
+ mesh.material.emissiveIntensity = chosen ? .65 : hovered ? .34 : 0;
903
+ });
904
+ }
905
+ function reflectSelection(ids) { selected = [...ids]; paintSelection(ownedMeshes, ids); }
906
+ function reflectHover(id) { hoveredId = typeof id === 'string' ? id : null; paintSelection(ownedMeshes, selected); }
907
+ function display(next) {
908
+ mode = next;
909
+ if (mode === 'wire') ensureOutlines(); else outlineJob?.stop();
910
+ applyRealistic();
911
+ paintSelection(ownedMeshes, selected); mountContext?.reportDisplayMode?.(mode);
912
+ }
913
+ function projection(next) { const old = camera; camera = next === 'ortho' ? orthographic : perspective; camera.position.copy(old.position); camera.quaternion.copy(old.quaternion); controls.object = camera; controls.update(); notifyCamera(); }
914
+ const selectAt = (event) => {
915
+ const hit = qualifiedHitAt(event.clientX, event.clientY);
916
+ if (hit) selectionCoordinator.replaceAll([{ kind: 'native', sourceId: hit.providerToken }], 'mesh');
917
+ };
918
+ const legacySelectionInterceptor = Object.freeze({ click: selectAt });
919
+ let selectionInterceptor = legacySelectionInterceptor;
920
+ const selectionInputProxy = Object.freeze({
921
+ pointerDown: (event) => selectionInterceptor?.pointerDown?.(event),
922
+ pointerMove: (event) => { const point = pickSurface(event.clientX, event.clientY); for (const listener of pointerWorldListeners) listener(point); return selectionInterceptor?.pointerMove?.(event); },
923
+ pointerEnter: (event) => selectionInterceptor?.pointerEnter?.(event),
924
+ pointerLeave: (event) => selectionInterceptor?.pointerLeave?.(event),
925
+ pointerCancel: (event) => selectionInterceptor?.pointerCancel?.(event),
926
+ click: (event) => selectionInterceptor?.click?.(event),
927
+ doubleClick: (event) => selectionInterceptor?.doubleClick?.(event),
928
+ wheel: (event) => selectionInterceptor?.wheel?.(event),
929
+ contextMenu: (event) => selectionInterceptor?.contextMenu?.(event),
930
+ windowPointerMove: (event) => selectionInterceptor?.windowPointerMove?.(event),
931
+ windowPointerUp: (event) => selectionInterceptor?.windowPointerUp?.(event),
932
+ windowBlur: (event) => selectionInterceptor?.windowBlur?.(event),
933
+ keyDown: (event) => selectionInterceptor?.keyDown?.(event),
934
+ keyUp: (event) => selectionInterceptor?.keyUp?.(event),
935
+ orbitStart() { selectionInterceptor?.orbitStart?.(); },
936
+ orbitChange() { selectionInterceptor?.orbitChange?.(); notifyCamera(); },
937
+ });
938
+ const orientation = Object.freeze({
939
+ getPose: orientationPose,
940
+ subscribe(listener) {
941
+ if (typeof listener !== 'function') throw new TypeError('Orientation subscriber must be a function.');
942
+ orientationListeners.add(listener); listener(orientationPose());
943
+ let active = true; return () => { if (active) { active = false; orientationListeners.delete(listener); } };
944
+ },
945
+ applyView,
946
+ applyDirection,
947
+ });
948
+
949
+ const idsForKeys = (keys = []) => keys.map((key) => identityRegistry.lookup(key)).filter((item) => item?.kind === 'native').map((item) => item.sourceId);
950
+ const visibleSnapshot = () => ownedMeshes.map((mesh) => ({ id: mesh.userData.entityId, visible: baseVisibility.get(mesh) !== false }));
951
+ const adapter = Object.freeze({
952
+ mount(context) {
953
+ if (disposed) throw new Error('Revit viewport adapter is disposed.');
954
+ mountContext = context;
955
+ inputArbiter = mountCadInputArbiter({
956
+ surface: canvas, controls, orbitInput, getCamera: () => camera, pickPoint: pickSurface, applyView,
957
+ fitSelection: () => fit(ownedMeshes.filter((mesh) => selected.includes(mesh.userData.entityId))),
958
+ isActive: () => mounted && shown && paintAllowed && canvas.offsetParent !== null,
959
+ plugin: selectionInputProxy,
960
+ });
961
+ releaseClipInput = inputArbiter.registerTool(clipGesture.inputPlugin(), { id: 'model-clip', priority: 100, exclusiveGroup: 'model-command' });
962
+ const overlayInput = clipOverlay.inputPlugin();
963
+ releaseClipOverlayInput = inputArbiter.registerTool({ ...overlayInput,
964
+ keyDown(event) { return overlayInput.keyDown?.(event) === true || clipSession?.handleKeydown?.(event) === true; },
965
+ }, { id: 'model-clip-overlay', priority: 200 });
966
+ mounted = true;
967
+ },
968
+ unmount() { clipGesture.cancel('unmount'); releaseClipInput = null; releaseClipOverlayInput = null; inputArbiter?.destroy(); inputArbiter = null; mounted = false; mountContext = null; },
969
+ async rebuild(context) {
970
+ const request = pendingLoad; pendingLoad = null;
971
+ if (!request) throw new Error('No verified Revit generation was staged for loading.');
972
+ const nextFrame = revitGeometryFrame(request.frameReceipt);
973
+ const next = sceneFromGlb(request.bytes, request.ownerByNode, request.frameReceipt);
974
+ try {
975
+ applyRevitDisplayMode(next.ownedMeshes, mode);
976
+ const receipts = new Map();
977
+ for (const mesh of next.ownedMeshes) {
978
+ const id = mesh.userData.entityId;
979
+ if (!receipts.has(id)) receipts.set(id, await context.generation.register('native', id));
980
+ }
981
+ for (const mesh of next.ownedMeshes) mesh.userData.entityReceipt = receipts.get(mesh.userData.entityId);
982
+ const records = [...receipts.entries()].map(([providerToken, identity]) => ({ identity, providerToken, layer: 'model', selectable: true }));
983
+ const nextSnapIndex = buildModelSnapIndex(next.ownedMeshes); paintSelection(next.ownedMeshes, []);
984
+ const generation = createRevitViewportGeneration({ next, records, scene,
985
+ onActivate() {
986
+ model = next.root; meshes = next.meshes; ownedMeshes = next.ownedMeshes; geometryFrame = nextFrame;
987
+ baseVisibility = new Map(ownedMeshes.map((mesh) => [mesh, true])); isolation.forget(); spatialVisibilityBox = null;
988
+ modelDisposer = next.dispose;
989
+ snapIndex = nextSnapIndex; selected = []; hoveredId = null; applyRealistic(); if (spatialState) paintSpatialState(spatialState); clipOverlay.render();
990
+ // The staged generation is only live from here, so the outline build starts now —
991
+ // not at the applyRevitDisplayMode above, which still ran against a staged scene.
992
+ cancelOutlineJob(); sceneGeneration += 1; ensureOutlines();
993
+ },
994
+ onRelease() {
995
+ if (model === next.root) { cancelOutlineJob(); model = null; modelDisposer = null; meshes = []; ownedMeshes = []; hoveredId = null; baseVisibility.clear(); isolation.forget(); spatialVisibilityBox = null; snapIndex = buildModelSnapIndex([]); }
996
+ },
997
+ });
998
+ return { empty: next.ownedMeshes.length === 0, generation };
999
+ } catch (error) {
1000
+ next.dispose(); throw error;
1001
+ }
1002
+ },
1003
+ bounds(purpose, keys = []) {
1004
+ const ids = purpose === 'camera-selection' ? new Set(idsForKeys(keys)) : null;
1005
+ const box = bounds(ids ? ownedMeshes.filter((mesh) => ids.has(mesh.userData.entityId)) : ownedMeshes);
1006
+ return box.isEmpty() ? null : { min: box.min.toArray(), max: box.max.toArray() };
1007
+ },
1008
+ fit({ purpose }) { fit(purpose === 'camera-selection' ? ownedMeshes.filter((mesh) => selected.includes(mesh.userData.entityId)) : ownedMeshes); },
1009
+ pick(payload) { return qualifiedHitAt(payload.clientX, payload.clientY); },
1010
+ raycastRecords(event) { const hit = qualifiedHitAt(event.clientX, event.clientY); return hit ? [hit] : []; },
1011
+ applyCamera(value) {
1012
+ if (value?.projection && value.projection !== (camera === orthographic ? 'ortho' : 'persp')) projection(value.projection);
1013
+ if (Array.isArray(value?.position)) camera.position.fromArray(value.position);
1014
+ if (Array.isArray(value?.target)) controls.target.fromArray(value.target);
1015
+ if (Array.isArray(value?.up)) camera.up.fromArray(value.up);
1016
+ if (Number.isFinite(value?.orthoHeight) && value.orthoHeight > 0) orthoSpan = value.orthoHeight / 2;
1017
+ if (Number.isFinite(value?.zoom) && value.zoom > 0) camera.zoom = value.zoom;
1018
+ if (Number.isFinite(value?.near) && value.near > 0) camera.near = value.near;
1019
+ if (Number.isFinite(value?.far) && value.far > camera.near) camera.far = value.far;
1020
+ camera.updateProjectionMatrix(); controls.update(); resize(); notifyCamera();
1021
+ },
1022
+ applyOrientation(value) { if (typeof value === 'string') applyView(value); else applyDirection(value); },
1023
+ applyDisplayMode: display,
1024
+ applyClipState(value) {
1025
+ if (!spatialTools) throw new Error('Shared spatial tools are not mounted.');
1026
+ spatialTools.replaceSections({ clips: value?.clipping ?? value?.clips ?? [], workArea: value?.workArea ?? null });
1027
+ },
1028
+ applyPresentation({ selectedKeys = [], hoverKey = null, ghostUnselected: ghost = false }) {
1029
+ ghostUnselected = ghost === true; hoveredId = idsForKeys(hoverKey ? [hoverKey] : [])[0] ?? null;
1030
+ reflectSelection(idsForKeys(selectedKeys));
1031
+ },
1032
+ beforeRender() { controls.update(); clipOverlay.resize(); clipCreationPreview.resize(); }, render() { if (paintAllowed) { renderer.render(scene, camera); const previousAutoClear = renderer.autoClear; renderer.autoClear = false; renderer.clearDepth(); renderer.render(overlayScene, camera); renderer.autoClear = previousAutoClear; } }, afterRender() {},
1033
+ setPaintAllowed(on) { paintAllowed = on === true; },
1034
+ snapshotVisibility: visibleSnapshot,
1035
+ applyVisibilitySnapshot(value) { isolation.forget(); const visible = new Map((value ?? []).map((item) => [item.id, item.visible === true])); ownedMeshes.forEach((mesh) => { if (visible.has(mesh.userData.entityId)) baseVisibility.set(mesh, visible.get(mesh.userData.entityId)); }); recomputeVisibility(); paintSelection(ownedMeshes, selected); },
1036
+ hideSelection(keys) {
1037
+ const ids = new Set(idsForKeys(keys)); const hiddenIds = new Set();
1038
+ ownedMeshes.forEach((mesh) => { if (ids.has(mesh.userData.entityId) && baseVisibility.get(mesh) !== false) { baseVisibility.set(mesh, false); hiddenIds.add(mesh.userData.entityId); } });
1039
+ isolation.hid(ownedMeshes.filter((mesh) => ids.has(mesh.userData.entityId))); // even one the isolation had already hidden
1040
+ recomputeVisibility(); paintSelection(ownedMeshes, selected);
1041
+ const hiddenKeys = keys.filter((key) => { const item = identityRegistry.lookup(key); return item?.kind === 'native' && hiddenIds.has(item.sourceId); });
1042
+ return Object.freeze({ count: hiddenIds.size, hiddenKeys: Object.freeze(hiddenKeys) });
1043
+ },
1044
+ isolateSelection(keys) { const ids = new Set(idsForKeys(keys)); isolation.isolate(baseVisibility, ownedMeshes, (mesh) => ids.has(mesh.userData.entityId)); recomputeVisibility(); paintSelection(ownedMeshes, selected); },
1045
+ isIsolated: () => isolation.active(),
1046
+ clearIsolation() { if (isolation.clear(baseVisibility)) { recomputeVisibility(); paintSelection(ownedMeshes, selected); } },
1047
+ clearVisibility() { isolation.forget(); ownedMeshes.forEach((mesh) => baseVisibility.set(mesh, true)); recomputeVisibility(); paintSelection(ownedMeshes, selected); },
1048
+ hasVisibilityFilter() { return ownedMeshes.some((mesh) => baseVisibility.get(mesh) === false); },
1049
+ isVisibilityActionable(key) { return identityRegistry.lookup(key)?.kind === 'native'; },
1050
+ cameraState() { return { projection: camera === orthographic ? 'ortho' : 'persp', position: camera.position.toArray(), target: controls.target.toArray(), up: camera.up.toArray(), orthoHeight: orthoSpan * 2, zoom: camera.zoom, near: camera.near, far: camera.far }; },
1051
+ displayMode: () => mode,
1052
+ sectionState: () => ({ clipping: spatialState?.clips ?? [], workPlane: spatialState?.workPlane ?? null, workArea: spatialState?.workArea ?? null, activeClipGesture: clipGesture.state().active }),
1053
+ resize, blockOrbit() { const was = controls.enabled; controls.enabled = false; return () => { if (!disposed) controls.enabled = was; }; },
1054
+ show() { shown = true; controls.enabled = true; }, hide() { shown = false; controls.enabled = false; },
1055
+ queueLoad(bytes, ownerByNode, frameReceipt) { pendingLoad = { id: ++loadSequence, bytes, ownerByNode, frameReceipt }; return pendingLoad.id; },
1056
+ registerInputTool(plugin, options) { if (!inputArbiter) throw new Error('Revit viewport input is not mounted.'); return inputArbiter.registerTool(plugin, options); },
1057
+ registerSelectionInterceptor(interceptor) {
1058
+ if (!interceptor || typeof interceptor !== 'object') throw new TypeError('Revit selection interceptor must be an object.');
1059
+ if (selectionInterceptor !== legacySelectionInterceptor) throw new Error('Revit selection interceptor is already mounted.');
1060
+ selectionInterceptor = interceptor; let live = true;
1061
+ return () => { if (live) { live = false; if (selectionInterceptor === interceptor) selectionInterceptor = legacySelectionInterceptor; } };
1062
+ },
1063
+ dispose() {
1064
+ if (disposed) return; disposed = true; shown = false; pendingLoad = null;
1065
+ selectionInterceptor = legacySelectionInterceptor; clipGesture.dispose(); clipOverlay.dispose(); clipCreationPreview.dispose(); releaseClipInput = null; releaseClipOverlayInput = null; inputArbiter?.destroy(); inputArbiter = null; controls.dispose(); releaseClipSession?.(); releaseClipSession = null; clipSession = null; releaseSpatial?.(); releaseSpatial = null; spatialTools = null;
1066
+ if (workPlaneHelper) { scene.remove(workPlaneHelper); workPlaneHelper.geometry.dispose(); workPlaneHelper.material.dispose(); workPlaneHelper = null; }
1067
+ clipReadout.remove();
1068
+ cancelOutlineJob(); edgeMaterials.dispose();
1069
+ scene.environment = null; environmentTarget?.dispose(); environmentTarget = null; environmentUp = null; environmentLive = false;
1070
+ modelDisposer?.(); modelDisposer = null; meshes = []; ownedMeshes = []; model = null;
1071
+ renderer.dispose(); renderer.forceContextLoss?.(); cameraListeners.clear(); orientationListeners.clear(); pointerWorldListeners.clear(); mountContext = null;
1072
+ },
1073
+ });
1074
+
1075
+ const platform = {
1076
+ requestFrame: (callback) => requestAnimationFrame(callback), cancelFrame: (id) => cancelAnimationFrame(id),
1077
+ // #1419: the controller races a timer against every animation frame so a viewport in a window that
1078
+ // is not being composited keeps redrawing. A tab the browser reports as hidden is not that case —
1079
+ // nobody is looking — so it opts out of the fallback and idles as it always has.
1080
+ pageHidden: () => document.visibilityState === 'hidden',
1081
+ observeResize: (surface, callback) => { const observer = new ResizeObserver(callback); observer.observe(surface); return () => observer.disconnect(); },
1082
+ measureSurface: (surface) => ({ width: surface.clientWidth || 1, height: surface.clientHeight || 1, pixelRatio: Math.min(devicePixelRatio || 1, 2) }),
1083
+ // The adapter's shared CAD arbiter owns the browser listener set. The controller owns the loop,
1084
+ // lifecycle and generation transactions without mounting a second pointer/keyboard owner.
1085
+ win: null,
1086
+ };
1087
+ controller = createModelViewportController({ adapter, platform, identityRegistry, selectionCoordinator, initialSelectionCommit: selectionCoordinator.current() });
1088
+ try { controller.init(canvas); controller.show(); } catch (error) { controller.dispose(); selectionCoordinator.dispose(); throw error; }
1089
+ let suspended = false; let terminal = false;
1090
+ const setSelection = ({ ids = [] }) => {
1091
+ const normalized = [...new Set(ids)];
1092
+ if (normalized.length === selectionCoordinator.entries().length && normalized.every((id, index) => selectionCoordinator.entries()[index]?.sourceId === id)) return selectionCoordinator.current();
1093
+ return selectionCoordinator.replaceAll(normalized.map((sourceId) => ({ kind: 'native', sourceId })));
1094
+ };
1095
+ const screenBoundsFor = (mesh) => {
1096
+ const box = new THREE.Box3().setFromObject(mesh); if (box.isEmpty()) return null;
1097
+ const points = [];
1098
+ for (const x of [box.min.x, box.max.x]) for (const y of [box.min.y, box.max.y]) for (const z of [box.min.z, box.max.z]) points.push(new THREE.Vector3(x, y, z).project(camera));
1099
+ if (points.some((point) => !Number.isFinite(point.x) || !Number.isFinite(point.y))) return null;
1100
+ const rect = canvas.getBoundingClientRect(); const xs = points.map((point) => rect.left + (point.x * .5 + .5) * rect.width); const ys = points.map((point) => rect.top + (-point.y * .5 + .5) * rect.height);
1101
+ return { left: Math.min(...xs), right: Math.max(...xs), top: Math.min(...ys), bottom: Math.max(...ys) };
1102
+ };
1103
+ const selectionHit = (mesh, extra = {}) => {
1104
+ const receipt = mesh?.userData?.entityReceipt; const sourceId = mesh?.userData?.entityId;
1105
+ if (!receipt || typeof sourceId !== 'string') return null;
1106
+ return { entity: { kind: 'native', sourceId }, key: receipt.key, namespace: receipt.namespace, generation: receipt.generation,
1107
+ generationToken: receipt.namespace, providerToken: sourceId, screenBounds: screenBoundsFor(mesh), rawVisible: mesh.visible, visible: mesh.visible,
1108
+ selectable: true, facets: { provider: 'revit' }, ...extra };
1109
+ };
1110
+ const hitsAt = (value) => {
1111
+ const seen = new Set(); const out = [];
1112
+ for (const hit of ownerHitsAt(value?.x, value?.y)) {
1113
+ const item = selectionHit(hit.object, { point: hit.point?.toArray() ?? null, normal: hit.face?.normal?.toArray() ?? null, distance: hit.distance });
1114
+ if (item && !seen.has(item.key)) { seen.add(item.key); out.push(item); }
1115
+ }
1116
+ return out;
1117
+ };
1118
+ const allHits = () => {
1119
+ const byKey = new Map();
1120
+ for (const mesh of ownedMeshes) {
1121
+ const item = selectionHit(mesh); if (!item || item.rawVisible === false) continue;
1122
+ const prior = byKey.get(item.key);
1123
+ if (!prior) { byKey.set(item.key, item); continue; }
1124
+ if (prior.screenBounds && item.screenBounds) prior.screenBounds = {
1125
+ left: Math.min(prior.screenBounds.left, item.screenBounds.left), right: Math.max(prior.screenBounds.right, item.screenBounds.right),
1126
+ top: Math.min(prior.screenBounds.top, item.screenBounds.top), bottom: Math.max(prior.screenBounds.bottom, item.screenBounds.bottom),
1127
+ };
1128
+ }
1129
+ return [...byKey.values()];
1130
+ };
1131
+ const selectionTools = Object.freeze({
1132
+ coordinator: selectionCoordinator, hitsAt, allHits, marqueeHits: () => allHits(),
1133
+ generationToken: () => identityRegistry.currentNamespace(),
1134
+ registerInterceptor: (interceptor) => adapter.registerSelectionInterceptor(interceptor),
1135
+ });
1136
+ const selectedMeshes = () => ownedMeshes.filter((mesh) => selected.includes(mesh.userData.entityId));
1137
+ const needSpatial = () => { if (!spatialTools) throw new Error('Shared spatial tools are not mounted.'); return spatialTools; };
1138
+ return Object.freeze({
1139
+ isReady: () => !!model,
1140
+ async load(bytes, ownerByNode, frameReceipt) { adapter.queueLoad(bytes, ownerByNode, frameReceipt); return controller.rebuild({ fit: true }); },
1141
+ setProjection: (value) => controller.setProjection(value), setDisplayMode: (value) => controller.setDisplayMode(value),
1142
+ fitAll: () => controller.fitAll(), fitSelection: () => controller.fitSelection(),
1143
+ applyView, applyDirection, orientation,
1144
+ cameraState: () => adapter.cameraState(), applyCamera: (value) => adapter.applyCamera(value),
1145
+ isolateSelected: () => controller.isolateSelection(), hideSelected: () => controller.hideSelection(), showAll: () => controller.showAll(), setSelection,
1146
+ setGhostUnselected: (value) => controller.setGhostUnselected(value), toggleGhostUnselected: () => controller.toggleGhostUnselected(), ghostUnselected: () => controller.ghostUnselected(),
1147
+ getState: () => controller.getState(), subscribe: (listener) => controller.subscribe(listener),
1148
+ setHover: reflectHover,
1149
+ bindSpatialTools(tools) {
1150
+ if (!tools || typeof tools.subscribe !== 'function' || typeof tools.activeFrame !== 'function') throw new TypeError('Revit viewport needs shared model spatial tools.');
1151
+ releaseSpatial?.(); spatialTools = tools; releaseSpatial = tools.subscribe(paintSpatialState); return () => { releaseSpatial?.(); releaseSpatial = null; if (spatialTools === tools) spatialTools = null; };
1152
+ },
1153
+ bindClipSession(session) {
1154
+ if (!session?.subscribe || !session?.clips || !session?.selected) throw new TypeError('Revit viewport needs a shared model clip session.');
1155
+ releaseClipSession?.(); clipSession = session; releaseClipSession = session.subscribe(() => clipOverlay.render());
1156
+ clipOverlay.render();
1157
+ let live = true; return () => { if (!live) return; live = false; releaseClipSession?.(); releaseClipSession = null; if (clipSession === session) clipSession = null; clipOverlay.render(); };
1158
+ },
1159
+ activeFrame() {
1160
+ const value = spatialTools?.activeFrame?.(); if (!value) return null;
1161
+ return { ...value, origin: geometryFrame.canonicalToRenderPoint(value.origin), xAxis: geometryFrame.canonicalToRenderDirection(value.xAxis), yAxis: geometryFrame.canonicalToRenderDirection(value.yAxis), zAxis: geometryFrame.canonicalToRenderDirection(value.zAxis) };
1162
+ },
1163
+ renderToCanonicalPoint: (point) => geometryFrame.renderToCanonicalPoint(point),
1164
+ canonicalToRenderPoint: (point) => geometryFrame.canonicalToRenderPoint(point),
1165
+ modelBoundsCanonical: (selectionOnly = false) => canonicalBounds(selectionOnly ? selectedMeshes() : ownedMeshes),
1166
+ armClip(kind) { needSpatial(); releaseClipInput?.activate?.(); return clipGesture.arm(kind); },
1167
+ cancelClip() { return clipGesture.cancel(); }, clearClips: () => clipSession?.clear?.() ?? needSpatial().clearClips(), clipMode: () => clipGesture.state().active?.mode ?? null,
1168
+ clipDragActive: () => clipEdit !== null,
1169
+ armWorkPlanePick() { throw new Error('Face and three-point working planes require authenticated pick anchors.'); },
1170
+ setWorkPlane: (value) => needSpatial().setPrincipalWorkPlane(value),
1171
+ setWorkPlaneVisible: (value) => needSpatial().setWorkPlaneVisible(value),
1172
+ clearWorkPlane() { const tools = needSpatial(); const state = tools.state(); if (state.workPlane?.visible) tools.setWorkPlaneVisible(false); return tools.resetGlobal(); },
1173
+ workPlaneInfo: () => spatialState?.workPlane ?? null,
1174
+ setWorkArea(from) { const box = canonicalBounds(from === 'selection' ? selectedMeshes() : ownedMeshes); if (!box) throw new Error(from === 'selection' ? 'Select model objects first.' : 'No visible model bounds are available.'); return needSpatial().setWorkArea({ ...box, wholeParts: true }); },
1175
+ toggleWorkArea() { const tools = needSpatial(); const area = tools.state().workArea; if (!area) throw new Error('Set a work area first.'); return tools.setWorkAreaVisible(!area.visible); },
1176
+ toggleWorkAreaWhole() { const tools = needSpatial(); const area = tools.state().workArea; if (!area) throw new Error('Set a work area first.'); return tools.setWorkAreaWhole(!area.wholeParts); },
1177
+ workAreaState: () => spatialState?.workArea ?? null,
1178
+ projection: () => controller.cameraState().projection, displayMode: () => controller.displayMode(),
1179
+ lightingState: () => ({ ...lighting }), setLighting: (value) => ({ ...applyLighting(value) }),
1180
+ realisticState,
1181
+ outlineState: () => ({
1182
+ mode, meshes: ownedMeshes.length,
1183
+ built: ownedMeshes.filter((mesh) => mesh.userData.revitOutline).length,
1184
+ drawn: ownedMeshes.filter((mesh) => mesh.userData.revitOutline?.visible).length,
1185
+ fillsHidden: ownedMeshes.filter((mesh) => mesh.material.visible === false).length,
1186
+ pending: outlineJob ? outlineJob.pending : 0,
1187
+ done: outlineJob ? outlineJob.done : false,
1188
+ worstOutlineMs: outlineJob ? +outlineJob.worstOutlineMs.toFixed(2) : 0,
1189
+ // The colour of the line actually DRAWN, per entity. Reading the fill's emissive instead would
1190
+ // report a selection cue the user cannot see, because the fill is hidden in this mode.
1191
+ outlineColours: [...new Set(ownedMeshes
1192
+ .filter((mesh) => mesh.userData.revitOutline?.visible)
1193
+ .map((mesh) => '#' + mesh.userData.revitOutline.material.color.getHexString()))],
1194
+ selectedOutlineColours: [...new Set(ownedMeshes
1195
+ .filter((mesh) => mesh.userData.revitOutline?.visible && selected.includes(mesh.userData.entityId))
1196
+ .map((mesh) => '#' + mesh.userData.revitOutline.material.color.getHexString()))],
1197
+ segments: ownedMeshes.reduce((sum, mesh) => sum
1198
+ + (mesh.userData.revitOutline?.geometry.getAttribute('position').count ?? 0) / 2, 0),
1199
+ triangles: ownedMeshes.reduce((sum, mesh) => {
1200
+ const index = mesh.geometry.getIndex();
1201
+ return sum + (index ? index.count : mesh.geometry.getAttribute('position').count) / 3;
1202
+ }, 0),
1203
+ }),
1204
+ presentationProbe: () => ownedMeshes.map((mesh) => ({
1205
+ id: mesh.userData.entityId, visible: mesh.visible, selected: selected.includes(mesh.userData.entityId),
1206
+ opacity: mesh.material.opacity, transparent: mesh.material.transparent, depthWrite: mesh.material.depthWrite,
1207
+ wireframe: mesh.material.wireframe, renderOrder: mesh.renderOrder,
1208
+ hasNormals: !!mesh.geometry.getAttribute('normal'), flatShading: mesh.material.flatShading,
1209
+ side: mesh.material.side, metalness: mesh.material.metalness, roughness: mesh.material.roughness,
1210
+ })),
1211
+ pickSurface,
1212
+ projectPoint(point) { const value = new THREE.Vector3().fromArray(point).project(camera); const rect = canvas.getBoundingClientRect(); return { x: rect.left + (value.x * .5 + .5) * rect.width, y: rect.top + (-value.y * .5 + .5) * rect.height, visible: value.z >= -1 && value.z <= 1 }; },
1213
+ // xeoRVT GLB millimetres cross the render boundary as metres (root scale 0.001). Convert only
1214
+ // the measured display value back here; persisted provider coordinates remain untouched.
1215
+ distanceMm(a, b) { return revitDistanceMm(geometryFrame, a, b); },
1216
+ snapIndex: () => snapIndex, registerInputTool: (plugin, options) => adapter.registerInputTool(plugin, options),
1217
+ selectionTools,
1218
+ onCameraChange(listener) { cameraListeners.add(listener); notifyCamera(); return () => cameraListeners.delete(listener); },
1219
+ onPointerWorld(listener) { if (typeof listener !== 'function') throw new TypeError('Pointer-world subscriber must be a function.'); pointerWorldListeners.add(listener); return () => pointerWorldListeners.delete(listener); },
1220
+ suspend() { if (terminal || suspended) return; suspended = true; controller.hide(); },
1221
+ resume() { if (terminal || !suspended) return; suspended = false; controller.show(); },
1222
+ dispose() { if (terminal) return; terminal = true; suspended = false; controller.dispose(); selectionCoordinator.dispose(); },
1223
+ });
1224
+ }