@floless/app 0.128.2 → 0.130.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.
@@ -190,6 +190,11 @@ function init(canvas, theApi) {
190
190
  // centre far away. ponytail: on-axis depth re-pivot, not a true off-axis orbit-about-cursor (OrbitControls
191
191
  // always keeps the pivot screen-centred — that would need a custom control); add that only if this isn't enough.
192
192
  controls.addEventListener('start', repivotToCursor);
193
+ // The progressive preview auto-frames ONCE, and must not do it to someone who has taken the camera.
194
+ // `start` is the honest signal for "the user did this": it fires on orbit, zoom and pan alike and
195
+ // never on our own `fitCamera`. It matters because the import modal offers "Continue in background"
196
+ // the moment the read starts, so a user can be navigating while the first batch is still arriving.
197
+ controls.addEventListener('start', () => { xrefPreviewCamTouched = true; });
193
198
  // The measure's snap set is FRUSTUM-FILTERED, so unlike every other cached candidate list it goes stale
194
199
  // the moment the camera moves — orbit past a corner and a cached set would keep offering it (projected
195
200
  // to nonsense) while the corners now on screen were absent. Cheap: the rebuild only happens on the next
@@ -230,6 +235,11 @@ function init(canvas, theApi) {
230
235
  // live dimension readout (toast-styled, follows the cursor during a drag — feet + snap type).
231
236
  // Two spans + textContent (never innerHTML) so it's XSS-proof; the type span is muted.
232
237
  readout = document.createElement('div');
238
+ // The ids on this and its sibling hosts below are not hooks for script — nothing looks them up. They
239
+ // exist so the pages' light theme can name them in their dark-island rule (#727): every one of these
240
+ // is glued to the 3D model and paints in colours tuned for the dark canvas, so they must NOT follow
241
+ // the shell into light the way the surrounding chrome does.
242
+ readout.id = 'm3dReadout';
233
243
  readout.style.cssText = 'position:fixed;display:none;pointer-events:none;z-index:60;background:var(--panel,#0f172a);color:var(--text,#f8fafc);border:1px solid var(--line,#1e293b);border-radius:4px;padding:3px 7px;font:12px system-ui;white-space:nowrap;box-shadow:0 2px 8px rgba(0,0,0,.5)';
234
244
  readout._dist = document.createElement('span');
235
245
  readout._type = document.createElement('span'); readout._type.style.color = 'var(--mut,#94a3b8)';
@@ -276,6 +286,7 @@ function init(canvas, theApi) {
276
286
  * `rubber` (a live drag overlay, which must cover everything it is drawn across).
277
287
  */
278
288
  dimLabelHost = document.createElement('div');
289
+ dimLabelHost.id = 'm3dDimLabels';
279
290
  dimLabelHost.style.cssText = 'position:fixed;left:0;top:0;pointer-events:none;z-index:4';
280
291
  document.body.appendChild(dimLabelHost);
281
292
  // …and its label, in the dim host so it is positioned by the same per-frame projection. The cssText is
@@ -284,11 +295,14 @@ function init(canvas, theApi) {
284
295
  refMeasureLabel.style.cssText = 'position:absolute;transform:translate(-50%,-50%);pointer-events:none;background:var(--panel,#0f172a);color:#e2e8f0;border:1px solid #22d3ee;border-radius:4px;padding:1px 6px;font:11px system-ui;white-space:nowrap;box-shadow:0 1px 4px rgba(0,0,0,.4);display:none';
285
296
  dimLabelHost.appendChild(refMeasureLabel);
286
297
  memberLabelHost = document.createElement('div'); // member mark/id labels (Slice 4) — below the dim labels
298
+ memberLabelHost.id = 'm3dMemberLabels';
287
299
  memberLabelHost.style.cssText = 'position:fixed;left:0;top:0;pointer-events:none;z-index:3;display:none';
288
300
  document.body.appendChild(memberLabelHost);
289
301
  propLabelHost = document.createElement('div'); // right-click property labels — own host so they never clobber the mark/id pool
302
+ propLabelHost.id = 'm3dPropLabelHost'; // NOT 'm3dPropLabels' — that id is the ⋯ menu's checkbox
290
303
  propLabelHost.style.cssText = 'position:fixed;left:0;top:0;pointer-events:none;z-index:3;display:none';
291
304
  selLenLabelHost = document.createElement('div'); // ⋯ Display → Show member length: on-select length chips (cyan dimension read)
305
+ selLenLabelHost.id = 'm3dSelLenLabels';
292
306
  selLenLabelHost.style.cssText = 'position:fixed;left:0;top:0;pointer-events:none;z-index:3;display:none';
293
307
  document.body.appendChild(selLenLabelHost);
294
308
  document.body.appendChild(propLabelHost);
@@ -312,11 +326,13 @@ function init(canvas, theApi) {
312
326
  };
313
327
  hoverChipShell.append(hoverChipToggle, hoverChip); statusDock.appendChild(hoverChipShell);
314
328
  } else {
329
+ hoverChip.id = 'm3dHoverChip';
315
330
  hoverChip.style.cssText = 'position:fixed;display:none;pointer-events:none;z-index:55;background:var(--panel,#0f172a);color:var(--mut,#94a3b8);border:1px solid var(--line,#334155);border-radius:6px;padding:5px 12px;font:12px system-ui;white-space:nowrap;max-width:60vw;overflow:hidden;text-overflow:ellipsis;box-shadow:0 2px 8px rgba(0,0,0,.45)';
316
331
  document.body.appendChild(hoverChip);
317
332
  }
318
333
  // rubber-band overlay for LEFT-drag box-select on empty space
319
334
  rubber = document.createElement('div');
335
+ rubber.id = 'm3dRubber';
320
336
  rubber.style.cssText = 'position:fixed;display:none;pointer-events:none;z-index:58;border:1px solid var(--brand,#3b82f6);background:rgba(59,130,246,.12)';
321
337
  document.body.appendChild(rubber);
322
338
  // Pointer gestures: down on a member → grab it (suppress orbit); move → drag with snapping; up →
@@ -838,7 +854,7 @@ function applyCopes(mesh, cuts) {
838
854
 
839
855
  function buildFromScene(sc) {
840
856
  clearRoot();
841
- clipCandidates = null; clipLevels = null; invalidateModelCache(); // the model changed (edit/undo/redo) — drop the clip-draw snap cache so a draw in progress re-snaps against the CURRENT members/grid/levels, never stale ones
857
+ clipCandidates = null; clipLevels = null; invalidateClipFloor(); invalidateModelCache(); // the model changed (edit/undo/redo) — drop the clip-draw snap cache AND the measured floor so a draw in progress re-snaps against the CURRENT members/grid/levels, never stale ones
842
858
  resetConnState(); // a fresh scene rebuilds selection from scratch — drop any stale connection envelope/context
843
859
  for (const mat of baseMat.values()) mat.dispose(); // shared per-profile materials from the prior build
844
860
  groupColor.clear(); baseMat.clear();
@@ -922,7 +938,11 @@ function buildFromScene(sc) {
922
938
  if (hadVisibilityFilter !== hasVisibilityFilter()) notifyVisibilityChange(); // keep the host's recovery control honest when an edit removes the last hidden/isolated mesh
923
939
  applyGroupVisibility(); applyDisplayMode();
924
940
  built = true;
925
- if (fitPending) { fitCamera(box); fitPending = false; } // fit only on entering 3D (rebuild(true)) — NOT on every edit
941
+ // Fit only on entering 3D (rebuild(true)) — NOT on every edit. Frames whatever is on screen, so a
942
+ // project whose references are already cached opens on the borrowed model rather than on nothing.
943
+ // (A reference whose geometry is still streaming in arrives after this and is not re-framed; landing
944
+ // an auto-fit on late-arriving geometry would yank a camera the user may already have moved.)
945
+ if (fitPending) { fitCamera(visibleWorldBox()); fitPending = false; }
926
946
  }
927
947
  let sceneGroups = [];
928
948
 
@@ -1103,6 +1123,136 @@ function xrefMatrix(placement) {
1103
1123
  .multiply(new THREE.Matrix4().makeScale(s, s, s));
1104
1124
  }
1105
1125
 
1126
+ // ── The progressive PREVIEW, and why it is a sibling rather than a reference ──
1127
+ //
1128
+ // A reference import draws as it loads (aware-aeco/aware#405): AWARE announces segments while it is
1129
+ // still tessellating, and these are the meshes for them. The whole design rests on this geometry NOT
1130
+ // being a reference — both server routes refuse AFTER the read (`objectVerdict`, the filter receipt),
1131
+ // so anything drawn early is drawn before FloLess knows it may be kept.
1132
+ //
1133
+ // IT IS A SIBLING OF `xrefGroup`, NEVER A CHILD, and that is what makes "not selectable" structural
1134
+ // instead of a rule someone has to remember. Every reference-interaction entry point reads that group
1135
+ // directly — `pickReferenceAt` raycasts `xrefGroup.children`, while `referenceCandidates` and
1136
+ // `referenceBounds` reach their meshes through `xrefById` — so a preview parented under it would be
1137
+ // pickable, snappable and measurable no matter what any other code said. Keeping it out of BOTH is
1138
+ // what answers all three. It is absent from `xrefById` for that reason, and from
1139
+ // the editor's `refGeom`, whose mere presence gates the measure tool, the move action and the panel's
1140
+ // loaded state.
1141
+ //
1142
+ // It is therefore not in `disposeReferenceMaterials`' sweep either: it owns exactly one material and
1143
+ // disposes it itself.
1144
+
1145
+ let xrefPreviewGroup = null; // the preview's meshes, or null when nothing is previewing
1146
+ let xrefPreviewMat = null; // its ONE material — the preview is uniform, so one is enough
1147
+ let xrefPreviewCount = 0; // objects drawn so far, for the caller's progress copy
1148
+ let xrefPreviewFramed = false; // whether the one-time frame has happened
1149
+ /**
1150
+ * Has the user driven the camera since this preview began?
1151
+ *
1152
+ * Set from OrbitControls' `start`, which fires on every orbit/zoom/pan the USER initiates and never
1153
+ * on a programmatic `fitCamera` — so the auto-frame below cannot mistake its own move for the user's.
1154
+ * `change` would be the wrong event for exactly that reason: `fitCamera` raises it.
1155
+ */
1156
+ let xrefPreviewCamTouched = false;
1157
+
1158
+ /**
1159
+ * Draw one batch of preview objects.
1160
+ *
1161
+ * `objects` is `[{positions, indices}]` and carries nothing else — no ids, no colours, no metadata —
1162
+ * because nothing may ask this layer a question about an object it is showing. Appends to whatever is
1163
+ * already drawn rather than rebuilding: `setReferences` re-uploads every buffer it owns, which is
1164
+ * correct once but would be quadratic per batch and would flicker the whole model on every arrival.
1165
+ *
1166
+ * `placement` is the reference's proposed placement, applied to the group exactly as a real reference's
1167
+ * is, so the preview sits where the finished model will.
1168
+ */
1169
+ function appendReferencePreview(objects, placement) {
1170
+ if (!scene || !Array.isArray(objects) || !objects.length) return 0;
1171
+ if (!xrefPreviewGroup) {
1172
+ xrefPreviewGroup = new THREE.Group();
1173
+ // BEHIND our steel, exactly as a reference is: `renderOrder` -1 with `depthWrite:false`. A preview
1174
+ // that occluded the model it exists to be compared against would be worse than no preview.
1175
+ xrefPreviewGroup.renderOrder = -1;
1176
+ xrefPreviewGroup.applyMatrix4(xrefMatrix(placement));
1177
+ scene.add(xrefPreviewGroup);
1178
+ // UNIFORM GREY, NOT THE FILE'S COLOURS, and that is a statement rather than a shortcut. It is the
1179
+ // same "not your content" slate this app already spends on references, it reads honestly as
1180
+ // provisional — the real colours appear when the import commits — and it lets the server strip
1181
+ // colour runs from the wire entirely. One material, because there is only ever one colour.
1182
+ xrefPreviewMat = newXrefMaterial(XREF_COLOR, 0.5);
1183
+ xrefPreviewMat.opacity = 0.5;
1184
+ xrefPreviewCount = 0;
1185
+ xrefPreviewFramed = false;
1186
+ // Cleared when a preview BEGINS, not on dispose: the question is whether the user has moved the
1187
+ // camera during THIS import, and a flag left standing from an earlier one would silently decline
1188
+ // to frame a reference that needs it.
1189
+ xrefPreviewCamTouched = false;
1190
+ }
1191
+ for (const o of objects) {
1192
+ if (!o || !Array.isArray(o.positions) || !o.positions.length) continue;
1193
+ const g = new THREE.BufferGeometry();
1194
+ g.setAttribute('position', new THREE.Float32BufferAttribute(o.positions, 3));
1195
+ if (Array.isArray(o.indices) && o.indices.length) g.setIndex(o.indices);
1196
+ g.computeVertexNormals();
1197
+ xrefPreviewGroup.add(new THREE.Mesh(g, xrefPreviewMat));
1198
+ xrefPreviewCount++;
1199
+ }
1200
+ // No explicit redraw: this view runs a continuous rAF loop (see `loop`), so adding to the scene is
1201
+ // all a batch has to do to appear.
1202
+ return xrefPreviewCount;
1203
+ }
1204
+
1205
+ /**
1206
+ * Frame the preview ONCE, and only if the user has not taken the camera themselves.
1207
+ *
1208
+ * Without this a model whose origin sits far from ours previews entirely off-screen and the feature
1209
+ * delivers nothing for exactly the coordination files it was built for. With it unconditional, it
1210
+ * would yank the camera away from someone who started navigating while the read ran. So: once, on the
1211
+ * first batch, and never again — the terminal `frameReference` on the committed reference is unchanged.
1212
+ *
1213
+ * It does NOT touch `sceneBox` or any saved view: the preview is not part of the scene's extent, and
1214
+ * a view saved while one was on screen must not remember it.
1215
+ */
1216
+ function frameReferencePreview() {
1217
+ if (!xrefPreviewGroup || xrefPreviewFramed || !xrefPreviewGroup.children.length) return false;
1218
+ // THE GUARD THE PARAGRAPH ABOVE PROMISED. It was documented and not implemented — the function
1219
+ // checked only that it had not already framed — so "and only if the user has not taken the camera
1220
+ // themselves" was a false sentence about the code beneath it. (UX review caught the divergence.)
1221
+ // Marked framed either way: declining once is the decision, not a retry to make on the next batch.
1222
+ xrefPreviewFramed = true;
1223
+ if (xrefPreviewCamTouched) return false;
1224
+ const box = new THREE.Box3().setFromObject(xrefPreviewGroup);
1225
+ if (box.isEmpty()) return false;
1226
+ fitCamera(box);
1227
+ return true;
1228
+ }
1229
+
1230
+ /**
1231
+ * Remove the preview and free everything it holds.
1232
+ *
1233
+ * CALLED BEFORE the authoritative geometry is built, never after, so peak GPU is the larger of the two
1234
+ * and not their sum. Idempotent: every terminal path in the editor calls it, which is the point.
1235
+ */
1236
+ function clearReferencePreview() {
1237
+ if (!xrefPreviewGroup) return;
1238
+ try {
1239
+ xrefPreviewGroup.traverse((o) => { o.geometry?.dispose?.(); });
1240
+ scene?.remove(xrefPreviewGroup);
1241
+ xrefPreviewMat?.dispose?.();
1242
+ } finally {
1243
+ // RESET IN `finally`, because a half-disposed group that stays referenced is worse than a leak.
1244
+ // If a dispose throws and these stay set, the NEXT import's `appendReferencePreview` sees a live
1245
+ // group, skips its whole init block, and appends the new model into the old group — the old
1246
+ // placement matrix, a stale count, and `xrefPreviewFramed` still true so it never frames. On a
1247
+ // refused import that geometry then stays on the canvas for a model FloLess declined, in a group
1248
+ // no selection can reach because it is deliberately outside `xrefById`. (Silent-failure review.)
1249
+ xrefPreviewGroup = null;
1250
+ xrefPreviewMat = null;
1251
+ xrefPreviewCount = 0;
1252
+ xrefPreviewFramed = false;
1253
+ }
1254
+ }
1255
+
1106
1256
  /** Unique world points for snapping, quantised so a tessellated corner is one target and not thirty. */
1107
1257
  function xrefSnapPoints(objects) {
1108
1258
  const seen = new Set(); const out = [];
@@ -1164,6 +1314,8 @@ function disposeReferenceMaterials() {
1164
1314
  */
1165
1315
  function setReferences(list) {
1166
1316
  refMeasureCands = null; // the measure's frustum-filtered snap set is derived from this — see setReferencePlacement
1317
+ invalidateClipFloor(); // the reference layer IS part of the clip-box floor: a reference arriving, being re-read, hidden or removed moves it
1318
+
1167
1319
  if (!scene) return;
1168
1320
  if (!xrefGroup) { xrefGroup = new THREE.Group(); scene.add(xrefGroup); }
1169
1321
  disposeReferenceMaterials();
@@ -1230,9 +1382,10 @@ function setReferences(list) {
1230
1382
  xrefGroup.add(group);
1231
1383
 
1232
1384
  const { points, capped: keptCapped } = xrefSnapPoints(objects);
1233
- // NO CACHED `bounds` HERE. It was stored and never read — `referenceBounds` recomputes — and the
1234
- // stored copy was measured without un-hiding, so it was null for a hidden reference while
1235
- // `frameReference` correctly un-hides first. Two answers to one question, one of them wrong.
1385
+ // NO CACHED `bounds` HERE. It was stored and never read — `referenceBounds` recomputes — so it was
1386
+ // a second answer to a question that already had one, kept up to date by nobody. (An earlier version
1387
+ // of this note also blamed the stored copy for measuring "without un-hiding"; that half was wrong,
1388
+ // and `referenceBounds` now records why: `setFromObject` never looks at `.visible` in the first place.)
1236
1389
  xrefById.set(ref.id, {
1237
1390
  group, display: ref.display || {}, name: ref.name || ref.id,
1238
1391
  points, total: points.length, capped: keptCapped, keptCapped,
@@ -1343,6 +1496,7 @@ function applyReferenceDisplay(id, display) {
1343
1496
  const visible = entry.display.visible !== false;
1344
1497
  const opacity = Number.isFinite(entry.display.opacity) ? Math.max(0, Math.min(1, entry.display.opacity)) : 0.5;
1345
1498
  entry.group.visible = visible;
1499
+ invalidateClipFloor(); // visibility decides whether this reference counts towards the clip-box floor at all — the eye toggle moves it
1346
1500
 
1347
1501
  // HIDING A REFERENCE DROPS ANY OBJECT DRILLED INTO IT — the other door into the state `pickReferenceAt`
1348
1502
  // refuses to create. That function now filters hidden groups so you cannot SELECT what you cannot see;
@@ -1480,6 +1634,7 @@ function setReferencePlacement(id, placement) {
1480
1634
  entry.group.position.set(0, 0, 0); entry.group.quaternion.identity(); entry.group.scale.set(1, 1, 1);
1481
1635
  entry.group.applyMatrix4(xrefMatrix(placement));
1482
1636
  entry.group.updateMatrixWorld(true);
1637
+ invalidateClipFloor(); // this reference just MOVED, so any floor measured from where it used to be is now wrong
1483
1638
  if (refMeasure3d && refMeasure3d.refId === id) {
1484
1639
  // The cache holds points BAKED through the old matrix, so every one of them now points at where
1485
1640
  // the geometry used to be. Camera 'change' is the only other invalidation and no camera moved.
@@ -1732,18 +1887,22 @@ function referenceProbe(id) {
1732
1887
  };
1733
1888
  }
1734
1889
 
1735
- /** World bounds of one reference — what zoom-to frames, and what the off-screen check measures. */
1890
+ /**
1891
+ * World bounds of one reference — what zoom-to frames, and what the off-screen check measures.
1892
+ *
1893
+ * IT MEASURES A HIDDEN REFERENCE, and needs no help to: "where is it and how big is it" is exactly the
1894
+ * question you ask about something you cannot see, and `Box3.setFromObject` answers it regardless of
1895
+ * visibility. It used to un-hide the group first, on the stated grounds that `setFromObject` "skips
1896
+ * invisible children" — it does not. `expandByObject` never reads `.visible`; it recurses over every
1897
+ * child unconditionally (three.core.js). The un-hide/restore pair was therefore inert, and the comment
1898
+ * asserting the opposite sat on the first bounds function a reader reaches, three lines from
1899
+ * `visibleWorldBox`, which has to filter visibility ITSELF precisely because the claim is false.
1900
+ * A hidden reference returns null here only when it has no geometry at all, same as a visible one.
1901
+ */
1736
1902
  function referenceBounds(id) {
1737
1903
  const entry = xrefById.get(id);
1738
1904
  if (!entry || !entry.group.children.length) return null;
1739
- // UN-HIDE FIRST. `Box3.setFromObject` skips invisible children, so a hidden reference measured null —
1740
- // and "where is it and how big is it" is exactly the question you ask about something you cannot see.
1741
- // `frameReference` already did this; this did not, so the panel's size line and the off-screen check
1742
- // both went blank the moment you hid a row.
1743
- const wasVisible = entry.group.visible;
1744
- entry.group.visible = true;
1745
1905
  const box = new THREE.Box3().setFromObject(entry.group);
1746
- entry.group.visible = wasVisible;
1747
1906
  return box.isEmpty() ? null : { min: box.min.toArray(), max: box.max.toArray() };
1748
1907
  }
1749
1908
 
@@ -1758,7 +1917,7 @@ function referenceBounds(id) {
1758
1917
  * ask about something you cannot currently see.
1759
1918
  */
1760
1919
  function frameReference(id) {
1761
- const b = referenceBounds(id); // un-hides to measure, so this frames a hidden reference too
1920
+ const b = referenceBounds(id); // measures regardless of visibility, so this frames a hidden reference too
1762
1921
  if (!b) return false;
1763
1922
  fitCamera(new THREE.Box3(new THREE.Vector3(...b.min), new THREE.Vector3(...b.max)));
1764
1923
  return true;
@@ -2245,8 +2404,16 @@ function fitCamera(box, dir) {
2245
2404
  // far must always clear the WHOLE model, not just the framed box — else a tight detail-zoom (dbl-click) puts the
2246
2405
  // rest of the model behind the far plane and slices it with a view-perpendicular cut that reads as a skewed
2247
2406
  // section. Size far from the scene bounds seen from the final camera position; the fit box only sets distance/zoom.
2248
- const sceneSph = sceneBox.getBoundingSphere(new THREE.Sphere());
2249
- const far = Math.max(dist + r * 4, perspCam.position.distanceTo(sceneSph.center) + sceneSph.radius) * 1.02;
2407
+ // …and the WHOLE scene includes a borrowed reference model, which is routinely the thing furthest from
2408
+ // the steel (site coordinates put one 74 m up and 40 m out) — sized on our own parts alone it is the
2409
+ // reference that falls behind the far plane and gets sliced.
2410
+ const sceneSph = visibleWorldBox().getBoundingSphere(new THREE.Sphere());
2411
+ // An EMPTY box's sphere reports radius -1, which would SUBTRACT from the far distance rather than add
2412
+ // to it. Reachable, and by an ordinary route: `frameReference` deliberately frames a HIDDEN reference,
2413
+ // so the framed box is non-empty while there is nothing VISIBLE to measure. Frame a compact one far
2414
+ // from the origin and the distance term dominates, so the -1 lands straight in `far`.
2415
+ const sceneR = sceneSph.radius > 0 ? sceneSph.radius : 0;
2416
+ const far = Math.max(dist + r * 4, perspCam.position.distanceTo(sceneSph.center) + sceneR) * 1.02;
2250
2417
  perspCam.near = near; perspCam.far = far; perspCam.updateProjectionMatrix();
2251
2418
  orthoCam.near = near; orthoCam.far = far; orthoCam.zoom = 1;
2252
2419
  orthoBaseH = fit.orthoH; // tight, aspect-preserving box fit (no ortho under-frame)
@@ -2277,7 +2444,7 @@ let rebuildSeq = 0;
2277
2444
  async function rebuild(fit = false) {
2278
2445
  if (!api) return;
2279
2446
  invalidatePointEntry('rebuild'); // synchronous, BEFORE the first await — the scene is changing; drop any open typed entry + stale base (never on stale async completion)
2280
- clipCandidates = null; clipLevels = null; invalidateModelCache(); // …and the clip-draw snap cache, synchronously here too (not only in buildFromScene): every edit/undo/redo funnels through rebuild(), so a draw in progress can't snap against pre-edit candidates during the async fetchScene window
2447
+ clipCandidates = null; clipLevels = null; invalidateClipFloor(); invalidateModelCache(); // …and the clip-draw snap cache + measured floor, synchronously here too (not only in buildFromScene): every edit/undo/redo funnels through rebuild(), so a draw in progress can't snap against pre-edit candidates during the async fetchScene window
2281
2448
  if (marker && clipMode === 'box') marker.visible = false; // a model change under an armed box draw invalidates the reticle position — drop it (the next hover re-snaps)
2282
2449
  if (fit) fitPending = true; // entering 3D re-fits; an edit-triggered rebuild keeps the camera put
2283
2450
  const seq = ++rebuildSeq;
@@ -2574,22 +2741,90 @@ function setClipMode(m) { // arm/disarm a clip pick: 'plane' (clic
2574
2741
  if (m && dimMode3d) toggleDimTool();
2575
2742
  if (m) { if (api && api.disarmTransform) api.disarmTransform(); if (api && api.disarmAdd) api.disarmAdd(); cmClear3d(); drClear3d(); disarmFrame3d(); } // clip shares the left-click — disarm Move/Copy + Add + the local frame so their picks don't steal it (onDown routes them first)
2576
2743
  clipMode = (m === 'plane' || m === 'box') ? m : null;
2577
- clipBoxDraft = null; clipCandidates = null; clipLevels = null; setClipPreview(null); setClipPlanePreview(null); if (marker) marker.visible = false; // drop the per-draw snap cache + any live snap marker when arming/disarming
2744
+ clipBoxDraft = null; clipCandidates = null; clipLevels = null; invalidateClipFloor(); setClipPreview(null); setClipPlanePreview(null); if (marker) marker.visible = false; // drop the per-draw snap cache + measured floor + any live snap marker when arming/disarming
2578
2745
  if (canvasEl) canvasEl.style.cursor = clipMode ? 'crosshair' : 'default';
2579
2746
  updateStatusChip();
2580
2747
  if (api && api.onClipModeChange) api.onClipModeChange(clipMode);
2581
2748
  return clipMode;
2582
2749
  }
2583
2750
  function clipModeOn() { return clipMode; }
2751
+ /**
2752
+ * The face a plane may be anchored to under (cx,cy) — the nearest of OUR steel if any of it is hit at
2753
+ * all, and only failing that the nearest reference (IFC) face. Deliberately NOT "the nearest face": see
2754
+ * the precedence paragraph.
2755
+ *
2756
+ * SHARED BY BOTH PLANE TOOLS — the Clip plane pick and the working-plane face pick. They had this same
2757
+ * gap and were fixed in parallel by two branches that could not see each other, each growing its own
2758
+ * copy of this function (`clipFaceHitAt` here, `faceHitAt` beside `wpFacePick`) with the same body and
2759
+ * the same reasoning. The second one to land collapsed them, which is what the first one's comment asked
2760
+ * for. What is left to each caller is the resulting normal: away from the camera for a clip (keep the
2761
+ * far side, reveal the section), toward it for a working plane (you are about to draw on it).
2762
+ *
2763
+ * THEY ALSO DISAGREE ABOUT HOW TO MEASURE THAT, which is NOT a second convention — one of them is
2764
+ * wrong. `clipPlaneAtScreen` tests the normal against `camera.position - hit.point`; `wpFacePick` tests
2765
+ * it against the ray that actually struck the face. In a perspective view the two agree. In this view's
2766
+ * ORTHOGRAPHIC mode they do not: for a hit off to the side, `camera.position - hit.point` is not the
2767
+ * direction you are looking from, so the clip tool can keep the wrong side of a face out at the edge of
2768
+ * a wide model. That is a pre-existing bug on the clip side, left alone here because this branch is not
2769
+ * where it should be fixed — but it is written down rather than smoothed over, because an earlier
2770
+ * version of this paragraph claimed the two callers differ in "exactly one thing" and that sentence is
2771
+ * an invitation to unify them on the wrong one. (Raised by Codex review of the merge.)
2772
+ *
2773
+ * REFERENCE GEOMETRY IS PICKABLE HERE AT ALL, and it was not before. This raycast saw `meshById` alone,
2774
+ * so arming Clip plane and clicking an IFC wall produced no hover ghost and placed no plane — the tool
2775
+ * simply did not react to the reference layer — and a project holding a coordination model but no steel
2776
+ * of its own could not be sectioned at all, since there was nothing in the pick set to click. A borrowed
2777
+ * building is usually the biggest thing on screen and very often the only thing at the cut, so it is
2778
+ * exactly what a user reaches for the clip tool to open up.
2779
+ *
2780
+ * OUR OWN STEEL STILL WINS AN OVERLAP — the same rule `pickReferenceAt` follows, and in Solid the
2781
+ * renderer is why: a reference draws at `renderOrder` -1 with `depthWrite:false`, so wherever the two
2782
+ * overlap the BEAM is the pixel on screen. Taking the nearest hit across both sets instead would anchor
2783
+ * the plane to a surface the user cannot see at the point they clicked.
2784
+ *
2785
+ * IN WIRE AND X-RAY THAT PIXEL ARGUMENT DOES NOT HOLD, and the rule is deliberately kept anyway. Wire
2786
+ * sets the fill `mat.visible = false` (the mesh stays raycastable, carrying only its outline), so a
2787
+ * reference behind a wireframe member IS what you see there. But `meshHitsAt` filters on `m.visible` —
2788
+ * the MESH — so ordinary selection has always resolved that same pixel to the member, and reaching the
2789
+ * reference needs the member to miss. Making the clip pick the exception would produce a display mode
2790
+ * in which pointing at one pixel selects a beam and clips an IFC. Agreeing with selection everywhere is
2791
+ * worth more than agreeing with the framebuffer in two modes. (Raised by Codex review.)
2792
+ *
2793
+ * A HIT ON THE CUT-AWAY SIDE OF AN EXISTING CLIP IS SKIPPED, in both sets. That surface is not on screen
2794
+ * either — the clip already removed it — so a second plane placed on it would appear to float in the
2795
+ * emptiness the first one opened.
2796
+ *
2797
+ * THE NATIVE CAST IS `meshHitsAt` ITSELF, not a copy of it. This function used to spell that raycast out
2798
+ * again — same visibility filter, same `isPointClipped` filter, the same NDC expression character for
2799
+ * character — while its comment claimed selection resolves a pixel the same way. Two implementations of
2800
+ * one rule can only agree until someone edits one of them, so the claim is now structural. (Raised by
2801
+ * review.) The reference cast stays here because nothing else wants it in this shape: `pickReferenceAt`
2802
+ * answers "which object", this wants "which face".
2803
+ *
2804
+ * A hidden reference is not pickable, and the hidden groups are filtered out rather than left to THREE,
2805
+ * which tests only `layers` and would happily return an invisible one.
2806
+ */
2807
+ function faceHitAt(cx, cy) {
2808
+ if (!canvasEl) return null;
2809
+ // BEFORE `meshHitsAt`, which has no such guard: a zero-sized canvas divides through to NaN, and a
2810
+ // raycast down a NaN ray answers nothing while looking like an ordinary miss.
2811
+ const rect = canvasEl.getBoundingClientRect(); if (!rect.width || !rect.height) return null;
2812
+ const own = meshHitsAt(cx, cy).find((h) => !!h.face);
2813
+ if (own) return own;
2814
+ if (!xrefGroup || !xrefGroup.children.length) return null;
2815
+ // RE-AIMED RATHER THAN INHERITED. `meshHitsAt` has just pointed the shared `raycaster` at this very
2816
+ // pixel, so reusing it would work today and break silently the day that function stops being the last
2817
+ // thing to touch it.
2818
+ camera.updateMatrixWorld(); xrefGroup.updateMatrixWorld(true);
2819
+ raycaster.setFromCamera(new THREE.Vector2(((cx - rect.left) / rect.width) * 2 - 1, -((cy - rect.top) / rect.height) * 2 + 1), camera);
2820
+ return raycaster.intersectObjects(xrefGroup.children.filter((g) => g.visible), true)
2821
+ .find((h) => !!h.face && !isPointClipped([h.point.x, h.point.y, h.point.z])) || null;
2822
+ }
2584
2823
  // The plane a face-pick would produce at (cx,cy): { n (keep-side normal, pointing away from the camera), point } or
2585
2824
  // null on a miss. Shared by the actual pick and the hover preview so the ghost always matches what a click places.
2586
2825
  function clipPlaneAtScreen(cx, cy) {
2587
- camera.updateMatrixWorld(); root.updateMatrixWorld(true);
2588
- const rect = canvasEl.getBoundingClientRect(); if (!rect.width || !rect.height) return null;
2589
- const ndc = new THREE.Vector2(((cx - rect.left) / rect.width) * 2 - 1, -((cy - rect.top) / rect.height) * 2 + 1);
2590
- raycaster.setFromCamera(ndc, camera);
2591
- const hit = raycaster.intersectObjects([...meshById.values()].filter((m) => m.visible), false)[0];
2592
- if (!hit || !hit.face) return null; // missed a face → no plane
2826
+ const hit = faceHitAt(cx, cy);
2827
+ if (!hit) return null; // missed a face → no plane
2593
2828
  const n = hit.face.normal.clone().transformDirection(hit.object.matrixWorld).normalize(); // face normal → world
2594
2829
  if (n.dot(camera.position.clone().sub(hit.point)) > 0) n.negate(); // point AWAY from the camera → keep the FAR side, cut away what's between you and the clicked surface (reveal the section)
2595
2830
  return { n, point: hit.point.clone() };
@@ -2634,14 +2869,6 @@ function addClipBoxFromBox(box) { // commit a clip box from an explicit Bo
2634
2869
  applyClips(); selectClip(id); if (api && api.onClipsChange) api.onClipsChange();
2635
2870
  return id;
2636
2871
  }
2637
- function addClipBox(pad = 150) { // convenience: a clip box from the selection's bounds (or the whole model)
2638
- const box = new THREE.Box3();
2639
- if (selIds.size) for (const id of selIds) { const m = meshById.get(id); if (m && m.visible) box.expandByObject(m); }
2640
- if (box.isEmpty()) box.copy(sceneBox);
2641
- if (box.isEmpty()) return null;
2642
- box.expandByScalar(pad);
2643
- return addClipBoxFromBox(box);
2644
- }
2645
2872
  function toggleClip(id, on) { const c = clips.find((x) => x.id === id); if (!c) return; if (api && api.beginClipEdit) api.beginClipEdit(); c.enabled = on === undefined ? !c.enabled : !!on; applyClips(); renderClipGizmo(); if (api && api.onClipsChange) api.onClipsChange(); }
2646
2873
  // Rename a clip. Returns false if the name is empty or already used by ANOTHER clip (case-insensitive) — the
2647
2874
  // caller (legend inline edit) keeps the old name + warns. Undoable.
@@ -2808,14 +3035,40 @@ function onMoveClip(e) {
2808
3035
  }
2809
3036
  // 3-step clip-box draw: click the two FOOTPRINT corners on the floor, then move up/down to PULL the height and
2810
3037
  // click to commit (CAD "rectangle then extrude"). clipBoxDraft: {a} → {a,b} → committed.
2811
- const clipBoxFloorZ = () => (sceneBox.isEmpty() ? 0 : sceneBox.min.z);
3038
+ /**
3039
+ * The elevation the two footprint corners are picked on: the bottom of everything on screen.
3040
+ *
3041
+ * IT READS `visibleWorldBox`, NOT `sceneBox` — the floor of the model you are looking at, which on a
3042
+ * project holding only a borrowed IFC used to be z=0 while the building sat hundreds of feet away. The
3043
+ * rectangle was then drawn in empty space below the model and the box committed around nothing.
3044
+ *
3045
+ * HELD FOR THE SPAN OF ONE DRAW, in `clipFloorZ`, because `clipBoxPreviewAt` asks on every mousemove and
3046
+ * the answer walks every mesh of every visible reference. Same per-draw cache the snap candidates use
3047
+ * two lines down, dropped by the same `setClipMode` on every arm and disarm — so it cannot outlive the
3048
+ * draw it was measured for, and a reference that arrives, moves, or is hidden between draws is picked
3049
+ * up by the next one. `0` only when there is genuinely nothing visible to stand on.
3050
+ */
3051
+ function clipBoxFloorZ() {
3052
+ if (clipFloorZ === null) { const b = visibleWorldBox(); clipFloorZ = b.isEmpty() ? 0 : b.min.z; }
3053
+ return clipFloorZ;
3054
+ }
2812
3055
  function clipBoxFrom(a, b, zlo, ztop) {
2813
3056
  return new THREE.Box3(new THREE.Vector3(Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.min(zlo, ztop)), new THREE.Vector3(Math.max(a[0], b[0]), Math.max(a[1], b[1]), Math.max(zlo, ztop)));
2814
3057
  }
2815
3058
  // The clip-box draw's snap targets, built ONCE per draw (allCandidates does O(n²) beam-intersection work — the
2816
3059
  // dim/Move tools cache it too, tfCandidates/dimCandidates3d). Members can't change mid-draw, so setClipMode drops
2817
3060
  // the cache on every arm/disarm. A malformed member/grid degrades to no snap (raw floor), never a broken tool.
2818
- let clipCandidates = null, clipLevels = null;
3061
+ let clipCandidates = null, clipLevels = null, clipFloorZ = null;
3062
+ /**
3063
+ * Drop the measured clip-box floor — call this wherever the geometry it was measured FROM can change.
3064
+ *
3065
+ * It is separate from the snap-candidate caches beside it because it invalidates on a strictly wider
3066
+ * set of events: the candidates are built from members and the grid, but the floor is built from the
3067
+ * members AND every visible reference model, so a reference arriving, moving or being hidden makes it
3068
+ * stale while leaving the candidates perfectly good. Missing those was the first version of this cache:
3069
+ * `setClipMode` alone looks sufficient, and is, right up until the world moves under an armed tool.
3070
+ */
3071
+ function invalidateClipFloor() { clipFloorZ = null; }
2819
3072
  function clipBoxSnapCands() { if (!clipCandidates) { try { clipCandidates = allCandidates(null); } catch { clipCandidates = []; } } return clipCandidates; }
2820
3073
  function clipBoxLevels() { if (!clipLevels) { try { clipLevels = MODEL().levels(null); } catch { clipLevels = []; } } return clipLevels; } // model-wide: the clip box spans every sheet, so it must be able to snap to an off-sheet endpoint
2821
3074
  // A footprint corner from the cursor: the floor point under it, PULLED to a member/grid/UCS snap when one is
@@ -2873,7 +3126,8 @@ function clipBoxPreviewAt(cx, cy) { // live preview: snap marker + a flat fo
2873
3126
  // ---- working area (Tekla-style) ----
2874
3127
  // One box that bounds the view: shown as a wireframe cuboid AND it sections the model (parts outside it hide),
2875
3128
  // composing with any clip planes/boxes through applyClips (workArea.planes are added when enabled). "Set to all
2876
- // objects" = the model bounds; "define from selection" = a padded box around the selection.
3129
+ // objects" = everything on screen, borrowed reference models included; "define from selection" = a padded box
3130
+ // around the selection (your own parts, since only those are selectable).
2877
3131
  let workAreaHelper = null; // THREE.Box3Helper wireframe for the work area (recreated on each box change)
2878
3132
  function renderWorkArea() {
2879
3133
  if (workAreaHelper) { if (overlayScene) overlayScene.remove(workAreaHelper); workAreaHelper.geometry.dispose(); workAreaHelper.material.dispose(); workAreaHelper = null; }
@@ -2892,7 +3146,7 @@ function setWorkAreaBox(box) {
2892
3146
  if (api && api.onWorkAreaChange) api.onWorkAreaChange(workAreaState());
2893
3147
  return true;
2894
3148
  }
2895
- function workAreaSetAll() { return setWorkAreaBox(sceneBox.clone()); } // "set work area to all objects" = model bounds
3149
+ function workAreaSetAll() { return setWorkAreaBox(visibleWorldBox()); } // "set work area to all objects" — ALL objects, so a visible reference model counts; steel-only made this return false (a dead control) on a project holding only a borrowed IFC
2896
3150
  function workAreaFromSelection(pad = 150) { // define a new work area around the selection
2897
3151
  const box = new THREE.Box3(); for (const id of selIds) { const m = meshById.get(id); if (m && visibleIgnoringWorkArea(m)) box.expandByObject(m); } // include a part hidden ONLY by the current work area — the new box supersedes it (a group/isolate-hidden part is still excluded)
2898
3152
  if (box.isEmpty()) return false; box.expandByScalar(pad); return setWorkAreaBox(box);
@@ -2929,10 +3183,14 @@ function setCameraState(s) {
2929
3183
  if (camera === orthoCam) { if (s.orthoH > 0) orthoBaseH = s.orthoH; orthoCam.zoom = s.zoom > 0 ? s.zoom : 1; reframeOrtho(); }
2930
3184
  // keep near/far clearing the whole scene from the restored spot (mirror fitCamera's sizing so a far-out
2931
3185
  // saved view doesn't clip the model behind the far plane).
2932
- const sph = sceneBox.getBoundingSphere(new THREE.Sphere());
3186
+ const sph = visibleWorldBox().getBoundingSphere(new THREE.Sphere());
2933
3187
  const dist = camera.position.distanceTo(controls.target) || 1;
2934
3188
  const near = Math.max(dist / 2000, 0.5);
2935
- const far = Math.max(dist + (sph.radius || dist) * 4, camera.position.distanceTo(sph.center) + (sph.radius || dist)) * 1.02;
3189
+ // `sph.radius || dist` READ THE EMPTY CASE BACKWARDS: an empty Box3's bounding sphere reports radius
3190
+ // -1, and -1 is truthy, so the fallback never fired and `far` was computed from a NEGATIVE radius —
3191
+ // restoring a saved view of a project with no native steel put the far plane in front of the model.
3192
+ const r = sph.radius > 0 ? sph.radius : dist;
3193
+ const far = Math.max(dist + r * 4, camera.position.distanceTo(sph.center) + r) * 1.02;
2936
3194
  perspCam.near = near; perspCam.far = far; perspCam.updateProjectionMatrix();
2937
3195
  orthoCam.near = near; orthoCam.far = far; orthoCam.updateProjectionMatrix();
2938
3196
  controls.update();
@@ -2972,17 +3230,61 @@ function sectionViewState(boxData, direction, label) {
2972
3230
  };
2973
3231
  }
2974
3232
 
3233
+ /**
3234
+ * WHERE MY STEEL IS — our own parts and nothing else. Deliberately NOT `visibleWorldBox`.
3235
+ *
3236
+ * The editor calls this `nativeModelBounds`, and `refMoveToOrigin` uses it to move a borrowed model
3237
+ * NEXT TO the steel. Fold references in here and that centre would include the very reference being
3238
+ * moved, so "put it beside my steel" would resolve to "put it where it already is". The view-generation
3239
+ * callers want the same steel-only reading.
3240
+ */
2975
3241
  function sceneBounds() {
2976
3242
  if (!sceneBox || sceneBox.isEmpty()) return null;
2977
3243
  return { min: sceneBox.min.toArray(), max: sceneBox.max.toArray() };
2978
3244
  }
2979
3245
 
2980
- function frameAll() { fitCamera(sceneBox); }
3246
+ /**
3247
+ * WHAT IS ON SCREEN — our steel unioned with every VISIBLE reference model.
3248
+ *
3249
+ * `sceneBox` is filled by `expandByObject` over the contract's elements and by nothing else, so every
3250
+ * consumer that meant "everything" quietly meant "everything of ours". On a project whose visible
3251
+ * content is a borrowed IFC that is not a small error, it is the entire answer: Fit and Home were
3252
+ * silent no-ops there (`cameraFitForBox` returns null on an empty box), "set work area to all objects"
3253
+ * returned false, and the clip-box draw picked its two footprint corners on a floor at z=0 while the
3254
+ * building stood hundreds of feet above it. Overlaying somebody's coordination model before modelling
3255
+ * any steel of your own is a normal first move, and it left half the view controls dead.
3256
+ *
3257
+ * THE VISIBILITY FILTER IS OURS, NOT THREE'S — the one thing here that is easy to get wrong by trusting
3258
+ * a comment. `Box3.expandByObject` never reads `.visible`; it walks every child unconditionally. So
3259
+ * hiding a reference has to be honoured HERE or a hidden building still drags the clip floor down,
3260
+ * with nothing on screen to explain why. Filtered per group, the same line `clipFaceHitAt` and
3261
+ * `pickReferenceAt` draw.
3262
+ *
3263
+ * NOT CACHED, on purpose. Reference geometry streams in behind the native steel and a reference can be
3264
+ * moved, hidden, or re-read at any moment, so a stored box would be stale long before it was slow. Every
3265
+ * caller here is bound to a user action — Fit, a view preset, the ViewCube, defining a work area — not to
3266
+ * a frame or a resize. The one caller that could not afford the walk is the clip-box draw, which asks on
3267
+ * every mousemove, and it holds the single number it needs for the span of one draw (see
3268
+ * `invalidateClipFloor` for what releases it).
3269
+ */
3270
+ function visibleWorldBox() {
3271
+ const box = sceneBox.clone();
3272
+ if (xrefGroup) {
3273
+ // The group's OWN place in the world, cheaply (parents only): `setFromObject` already refreshes
3274
+ // every descendant matrix itself, so walking the children again here would double the cost of the
3275
+ // measurement on the largest models in the scene.
3276
+ xrefGroup.updateWorldMatrix(true, false);
3277
+ for (const g of xrefGroup.children) if (g.visible) box.union(new THREE.Box3().setFromObject(g));
3278
+ }
3279
+ return box;
3280
+ }
3281
+
3282
+ function frameAll() { fitCamera(visibleWorldBox()); }
2981
3283
  const VIEWS = { top: [0, 0, 1], bottom: [0, 0, -1], front: [0, -1, 0], back: [0, 1, 0], right: [1, 0, 0], left: [-1, 0, 0], iso: [0.55, -0.8, 0.5] };
2982
- function applyView(name) { const d = VIEWS[name]; if (d) fitCamera(sceneBox, new THREE.Vector3(d[0], d[1], d[2])); }
3284
+ function applyView(name) { const d = VIEWS[name]; if (d) fitCamera(visibleWorldBox(), new THREE.Vector3(d[0], d[1], d[2])); }
2983
3285
  // Fit just the selection (Tekla "Zoom selected" / Shift+Space); falls back to fit-all when nothing's picked.
2984
3286
  function frameSelection() {
2985
- if (!selIds.size) { fitCamera(sceneBox); return; }
3287
+ if (!selIds.size) { fitCamera(visibleWorldBox()); return; }
2986
3288
  const box = new THREE.Box3();
2987
3289
  for (const id of selIds) { const m = meshById.get(id); if (m && m.visible) box.expandByObject(m); }
2988
3290
  if (!box.isEmpty()) fitCamera(box);
@@ -3772,7 +4074,7 @@ function initCube() {
3772
4074
  const p = mesh.worldToLocal(hit.point.clone()), snap = (x) => Math.abs(x) > 0.6 ? Math.sign(x) : 0;
3773
4075
  const dv = new THREE.Vector3(snap(p.x), snap(p.y), snap(p.z));
3774
4076
  if (Math.abs(dv.x) + Math.abs(dv.y) + Math.abs(dv.z) <= 1) { const f = CUBE_FACES[hit.face.materialIndex]; if (f) applyView(f.view); } // a face → ortho view
3775
- else fitCamera(sceneBox, dv); // an edge/corner → iso-style view from that world direction
4077
+ else fitCamera(visibleWorldBox(), dv); // an edge/corner → iso-style view from that world direction (the same bounds the face path frames through applyView — steel-only here would frame a cube FACE onto a reference model but a cube EDGE onto nothing)
3776
4078
  });
3777
4079
  cube = { renderer: cr, scene: cs, cam: cc, mesh };
3778
4080
  }
@@ -4468,15 +4770,39 @@ function setWorkPlanePrincipal(kind, offsetMm) {
4468
4770
  function clearWorkPlane() { workPlane = null; wpMode = null; wpDraft = null; invalidatePointEntry('drift'); renderWorkPlane(); reflectWpBar(); updateStatusChip(); }
4469
4771
  function toggleWorkPlaneVisible(on) { wpVisible = on === undefined ? !wpVisible : !!on; try { localStorage.setItem('steel:wpVisible:v1', wpVisible ? '1' : '0'); } catch { /* storage can be unavailable; keep the session preference */ } renderWorkPlane(); }
4470
4772
  function workPlaneInfo() { return { set: !!workPlane, mode: wpMode, visible: wpVisible, plane: workPlane ? { origin: [...workPlane.origin], normal: [...workPlane.normal], xAxis: [...workPlane.xAxis] } : null }; }
4471
- // face pick: the clip tool's raycast, minus the camera-side flip — the plane lands ON the face.
4773
+ /**
4774
+ * face pick: the same face → plane conversion the clip tool does, over the same `faceHitAt`, with the
4775
+ * opposite normal convention — the plane lands ON the face, facing you.
4776
+ *
4777
+ * THE NORMAL IS TURNED TO FACE THE VIEWER, which is not cosmetic. `planeBasis` derives v as n × u, so
4778
+ * the sign of n decides which way the plane's local +Y and +Z run — and that is Move/Copy's Z lock, the
4779
+ * dimension axes, and the direction Add-member offsets. Reference geometry is drawn `DoubleSide`
4780
+ * precisely because somebody else's IFC winding is not ours to trust, so without this a wall whose
4781
+ * triangles happen to wind inward would hand back a plane whose +Z points into the wall — dimensionally
4782
+ * perfect and backwards.
4783
+ *
4784
+ * IT IS NOT A NO-OP FOR EVERYTHING OF OURS, and an earlier version of this comment claimed it was.
4785
+ * Ordinary members and their cuts are `FrontSide`, so THREE culls back-facing triangles and every hit
4786
+ * it could return for one was already facing the camera — for those the flip provably changes nothing.
4787
+ * But `meshById` also holds two `DoubleSide` kinds: `custom` connection meshes (tessellated with
4788
+ * untrusted winding, same reason as a reference) and placed `image` detail planes, whose normal comes
4789
+ * from an authored `el.n` that may point either way. Clicking one of those from behind used to hand
4790
+ * back a plane pointing away from you and now does not. That is the same correction for the same
4791
+ * reason, not an accident of applying the flip too widely — but it IS a change to existing behaviour,
4792
+ * so it is stated here and pinned by a test rather than left to be discovered. (Raised by Codex review.)
4793
+ *
4794
+ * MEASURED AGAINST THE RAY, not `camera.position - point`: this view has an orthographic mode, where
4795
+ * the camera's position is not the direction you are looking from for an off-axis point. The ray is the
4796
+ * one `faceHitAt` just cast — aimed at this very pixel on both of its paths, by `meshHitsAt` on the
4797
+ * native one and by its own `setFromCamera` on the reference one — and it is what actually struck the
4798
+ * face. (The clip tool answers the same question with `camera.position - point`, which is why the two
4799
+ * disagree in an off-axis ortho view; that is a bug on its side, not a convention.)
4800
+ */
4472
4801
  function wpFacePick(cx, cy) {
4473
- camera.updateMatrixWorld(); root.updateMatrixWorld(true);
4474
- const rect = canvasEl.getBoundingClientRect(); if (!rect.width || !rect.height) return null;
4475
- const ndc = new THREE.Vector2(((cx - rect.left) / rect.width) * 2 - 1, -((cy - rect.top) / rect.height) * 2 + 1);
4476
- raycaster.setFromCamera(ndc, camera);
4477
- const hit = raycaster.intersectObjects([...meshById.values()].filter((m) => m.visible), false)[0];
4478
- if (!hit || !hit.face) return null;
4802
+ const hit = faceHitAt(cx, cy);
4803
+ if (!hit) return null;
4479
4804
  const n = hit.face.normal.clone().transformDirection(hit.object.matrixWorld).normalize();
4805
+ if (n.dot(raycaster.ray.direction) > 0) n.negate(); // wound away from the viewer → turn it around
4480
4806
  const b = planeBasis([n.x, n.y, n.z]);
4481
4807
  return { origin: [hit.point.x, hit.point.y, hit.point.z], normal: [n.x, n.y, n.z], xAxis: b.u, kind: 'face' };
4482
4808
  }
@@ -5685,7 +6011,7 @@ function updateStatusChip() {
5685
6011
  ? `Release to insert ${n} ${noun} into ${HOST_SHORT[teklaDrag.target]} · release here or Esc to cancel`
5686
6012
  : `Release over Tekla, Revit, SketchUp or Rhino to insert ${n} ${noun} · release here or Esc to cancel`;
5687
6013
  }
5688
- else if (wpMode === 'face') txt = 'Click a member face — the working plane lands on it · Esc to cancel';
6014
+ else if (wpMode === 'face') txt = 'Click any face — member or reference — the working plane lands on it · Esc to cancel';
5689
6015
  else if (wpMode === '3pt') txt = ['Click the plane origin (snapped) · Esc to cancel', 'Click the local-X direction point · Esc to cancel', 'Click a point on the plane’s Y side · Esc to cancel'][(wpDraft || []).length] || '';
5690
6016
  else if (addActive()) txt = drDraft ? 'Click the member end · X/Y/Z lock to the local axes, Shift straight · Esc drops the start' + lockChipTxt() : 'Draw a member on the working plane — click the start point · Esc exits';
5691
6017
  else if (cmActive()) { const st = cmActive(), lock = lockChipTxt();
@@ -5760,6 +6086,10 @@ function dispose() {
5760
6086
  refMeasureLabel = null; refMeasure3d = null; refMeasureKept = null; refMeasureCands = null;
5761
6087
  modelReads = null; // the resolved read half belongs to the host that was torn down; a re-init must ask the new one (unit 5, P7d)
5762
6088
  endTeklaDrag(); // release the pointer capture and take the badge with us
6089
+ // The progressive preview is a SIBLING of `xrefGroup`, so the reference teardown below never sees
6090
+ // it — a view disposed mid-import would leak its meshes and their material. It owns its own
6091
+ // disposal for exactly that reason; this is the one caller that has to remember to ask.
6092
+ clearReferencePreview();
5763
6093
  if (rafId) cancelAnimationFrame(rafId);
5764
6094
  if (hoverRAF) cancelAnimationFrame(hoverRAF);
5765
6095
  if (ro) ro.disconnect();
@@ -5952,6 +6282,11 @@ window.Steel3DView = {
5952
6282
  setReferences, setReferenceDisplay: applyReferenceDisplay, setReferencePlacement, selectReference, referenceProbe,
5953
6283
  selectedReference: () => xrefSelected, frameReference, referenceBounds, referenceInfo,
5954
6284
  pickReferenceAt,
6285
+ // The progressive preview (aware-aeco/aware#405) — geometry drawn while AWARE is still tessellating
6286
+ // it. Deliberately a separate trio from the reference verbs above, because it is a separate layer:
6287
+ // nothing here writes `xrefById`, and nothing above can see what these draw. See the section header.
6288
+ appendReferencePreview, clearReferencePreview, frameReferencePreview,
6289
+ referencePreviewCount: () => xrefPreviewCount,
5955
6290
  // Stage A: drilling into ONE object inside a reference. `selectReferenceObject` is what Ctrl+click and
5956
6291
  // (later) an object-tree row both call, so the two routes cannot drift into different selections.
5957
6292
  selectReferenceObject, selectedReferenceObject,
@@ -5990,7 +6325,7 @@ window.Steel3DView = {
5990
6325
  return { group: true, extent: wpExtent, children: wpGroup.children.map((c) => ({ type: c.type, color: c.material && '#' + c.material.color.getHexString(), opacity: c.material && c.material.opacity, w: c.geometry && c.geometry.parameters ? c.geometry.parameters.width : null, h: c.geometry && c.geometry.parameters ? c.geometry.parameters.height : null })) };
5991
6326
  },
5992
6327
  toggleGroup, setGroupsHidden, setIdsHidden, connHiddenIds: () => [...connHidden], selectionHiddenIds: () => [...selectionHidden], soloToggle, setSoloGroups, showAllGroups, groupState, getGroups, visibleMemberIds, visibleObjectIds, visibleGridIds,
5993
- setClipMode, clipMode: clipModeOn, addClipBox, toggleClip, removeClip, clearClips, getClips, renameClip, selectClip, setSelectedClips, selectedClips, deleteSelectedClips, clipState, setClipState,
6328
+ setClipMode, clipMode: clipModeOn, toggleClip, removeClip, clearClips, getClips, renameClip, selectClip, setSelectedClips, selectedClips, deleteSelectedClips, clipState, setClipState,
5994
6329
  isolateSelected, hideSelected, clearIsolation, isIsolated, hasVisibilityFilter,
5995
6330
  cameraState, setCameraState, sectionViewState, sceneBounds, objectsPaneState, applyObjectsPaneState, // saved-view snapshot surface (Views Organizer + F11 generated cuts)
5996
6331
  workAreaSetAll, workAreaFromSelection, workAreaToggle, workAreaSetWhole, clearWorkArea, workAreaState,