@floless/app 0.111.2 → 0.112.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.
@@ -19,8 +19,10 @@ import { OrbitControls } from 'three/addons/OrbitControls.js';
19
19
  import { RoomEnvironment } from 'three/addons/RoomEnvironment.js';
20
20
  import { surfaceTextures, applyTriplanar, TILE_MM, DIRECTIONAL } from './steel-materials.js';
21
21
  import { Brush, Evaluator, SUBTRACTION } from 'three-bvh-csg';
22
- import { snapCandidates, snapPoint, planPointToWp, memberGeometry, planScaleOf, planScaleIndex, memberGeometryInOwnPlan, elevationLevels, elevationLevelsByPlan, snapElevation, dim3dGeom, dominantAxis3d, planeBasis, planeFrom3Points, vecToPlane, frameFrom3Points, frameFromAngle, worldToLocal, identityFrame, resolvePointEntry, offsetsFor, candidateOnPlane, snapGridPoint, clipSegmentToPlanes, pointSegmentDistance2d, perspectiveSegmentParameter, gridDepthWins, segmentHitsRect2d, projectedFootprintHitsRect2d, pickGridLevel } from './steel-3d-core.js';
23
- import { gridGeometry, gridCandidates3d, mmPerPx, visibleGridLevels } from './grid-core.js';
22
+ import { snapPoint, planPointToWp, memberGeometry, snapElevation, dim3dGeom, dominantAxis3d, planeBasis, planeFrom3Points, vecToPlane, frameFrom3Points, frameFromAngle, worldToLocal, identityFrame, resolvePointEntry, offsetsFor, candidateOnPlane, snapGridPoint, clipSegmentToPlanes, pointSegmentDistance2d, perspectiveSegmentParameter, gridDepthWins, segmentHitsRect2d, projectedFootprintHitsRect2d, pickGridLevel } from './steel-3d-core.js';
23
+ // `gridGeometry`, `gridCandidates3d` and `mmPerPx` moved behind the host's model read half (unit 5, P7d):
24
+ // each takes a `ptPerFt`, which is a v1 PLAN default and meaningless on a world-mm model grid.
25
+ import { visibleGridLevels } from './grid-core.js';
24
26
 
25
27
  let renderer, scene, perspCam, orthoCam, camera, controls, root, api, canvasEl, ro, rafId, grid, raycaster, downXY, lastPick = '(none)';
26
28
  let lightAmb, lightKey, lightFill; // dimmed in Realistic, where the environment lights the scene
@@ -122,7 +124,7 @@ function candOnActiveWP(c, dragged, wp) {
122
124
  return candidateOnPlane(c, dragged, wp.origin, wp.normal, WP_SNAP_TOL_MM);
123
125
  }
124
126
  let rightDownXY = null, rightMoved = false; // right button: dragged (= orbit/pan, no menu) vs clicked (= snap menu)
125
- let teklaDrag = null; // Ctrl+Shift drag-out to Tekla: { ids } from the moment the gesture is armed until dragend
127
+ let teklaDrag = null; // Ctrl+Shift drag-out to a CAD host: { ids, stack, target } from the moment the gesture is armed until release
126
128
  const dimLock = new Set(); // locked MEASURE axes (subset of x|y|z); empty = Free/aligned. Toggle+combine like Move/Copy's tfLock (measures along the resolved/dominant axis; the 2nd point still free-snaps).
127
129
  let dims3dVisibleFlag = true; // show/hide placed dims
128
130
  let dimDraft3d = null; // { a:[x,y,z] } once the first point is placed (awaiting the 2nd)
@@ -749,7 +751,7 @@ function applyCopes(mesh, cuts) {
749
751
 
750
752
  function buildFromScene(sc) {
751
753
  clearRoot();
752
- clipCandidates = null; clipLevels = null; scaleIdx = null; // 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
754
+ 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
753
755
  resetConnState(); // a fresh scene rebuilds selection from scratch — drop any stale connection envelope/context
754
756
  for (const mat of baseMat.values()) mat.dispose(); // shared per-profile materials from the prior build
755
757
  groupColor.clear(); baseMat.clear();
@@ -846,8 +848,11 @@ function buildRefLines() {
846
848
  if (!refLineOn || !api) return;
847
849
  const pts = [];
848
850
  for (const m of members()) {
849
- if (!m || !Array.isArray(m.wp) || m.wp.length < 2) continue;
850
- const g = geoOf(m);
851
+ // Ask the READ HALF whether this member has a work line, rather than testing for `m.wp` — that is a
852
+ // v1 STORAGE shape, and a v2 member has none, so the old guard skipped every member of a canonical
853
+ // model and drew no reference lines at all. Silently: an empty `pts` just returns. (unit 5, P7d)
854
+ const g = m && geoOf(m);
855
+ if (!g || !g.line) continue;
851
856
  pts.push(new THREE.Vector3(g.line[0][0], g.line[0][1], g.line[0][2]), new THREE.Vector3(g.line[1][0], g.line[1][1], g.line[1][2]));
852
857
  }
853
858
  if (!pts.length) return;
@@ -1084,11 +1089,11 @@ const gridTexCache = new Map(); // 'b:LABEL' bubble / 't:LABEL' tag -> CanvasTex
1084
1089
  // scale-independent. Intersections stay within a sheet (pairwise across the whole model is O(n²) noise).
1085
1090
  // Grid is the active sheet's (the plan-locked reference the user is drawing against).
1086
1091
  function allCandidates(excludeId) {
1087
- const dtos = api.defaultTosMm();
1088
- const byPlan = (api.membersByPlan && api.membersByPlan()) || [{ members: members(), ptPerFt: api.ptPerFt(), defaultTosMm: dtos }];
1089
- const base = byPlan.flatMap((pl) => snapCandidates(pl.members, pl.ptPerFt, pl.defaultTosMm != null ? pl.defaultTosMm : dtos, excludeId)); // each sheet's OWN default T.O.S — a default-elevation member on a non-active sheet must snap at the level it RENDERS at (the bake uses the same per-plan default), not the active sheet's
1092
+ // The member and grid halves come from the read half; the UCS origin does NOT — it is VIEW state, not
1093
+ // model data, and it keeps its position between them so the candidate ORDER is unchanged.
1094
+ const base = MODEL().memberCandidates(excludeId);
1090
1095
  if (frame3d && !(pending && pending.frameDrag)) base.push({ type: 'origin', p: [...frame3d.origin], fromId: 'ucs-origin' }); // the local UCS origin is a snap target for every tool (Move/Copy, Add, Dimension); excluded while dragging the origin itself → no self-snap
1091
- try { return base.concat(gridCandidates3d(api.getGrid ? api.getGrid() : null, api.ptPerFt())); }
1096
+ try { return base.concat(MODEL().gridCandidates()); }
1092
1097
  catch { return base; } // a malformed hand-edited grid must never break member dragging
1093
1098
  }
1094
1099
 
@@ -1132,14 +1137,20 @@ function clearStructGrid() {
1132
1137
  }
1133
1138
  function buildStructGrid() {
1134
1139
  clearStructGrid();
1135
- dimCandidates3d = null; tfCandidates = null; clipCandidates = null; clipLevels = null; scaleIdx = null; // the grid just changed → EVERY cached snap set built from the OLD one is stale (dim, Move/Copy + Add, clip-box draw). rebuild() already nulls these, but refresh3DGrid() (grid panel edits, and the plan switch setPlan now fires) reaches us without it, which would pair one sheet's grid X/Y with another's elevations.
1136
- if (!api || !api.getGrid || !scene) return;
1137
- let g = null, geo = null;
1138
- try { g = api.getGrid(); if (!g || g.on === false) return; geo = gridGeometry(g, api.ptPerFt()); }
1140
+ dimCandidates3d = null; tfCandidates = null; clipCandidates = null; clipLevels = null; invalidateModelCache(); // the grid just changed → EVERY cached snap set built from the OLD one is stale (dim, Move/Copy + Add, clip-box draw). rebuild() already nulls these, but refresh3DGrid() (grid panel edits, and the plan switch setPlan now fires) reaches us without it, which would pair one sheet's grid X/Y with another's elevations.
1141
+ if (!api || !scene) return;
1142
+ // THE GRID NEEDS ITS OWN v2 PATH, and this is the one place it shows (§8.3). v1's grid is stored in the
1143
+ // active sheet's DISPLAY space — px, with Y growing DOWN the page — so the two conversions below are a
1144
+ // scale AND a reflection. v2's grid is already world mm with Y up. Handing a world-mm grid to the v1
1145
+ // conversion would not throw; it would draw the whole grid mirrored about Y, plausibly, at 1/12 scale.
1146
+ // So the read half answers with the drawable geometry AND the two facts needed to place it.
1147
+ let d = null;
1148
+ try { d = MODEL().gridDraw(); }
1139
1149
  catch (e) { console.warn('[steel-3d] grid skipped (bad grid data)', e); return; }
1150
+ if (!d) return; // no grid, or the grid is switched off
1151
+ const { g, geo, k, flipY } = d;
1140
1152
  if (!geo.v.length && !geo.h.length && !(geo.lines && geo.lines.length)) return;
1141
- const k = mmPerPx(api.ptPerFt());
1142
- const mmX = (px) => px * k, mmY = (px) => -px * k; // display → scene (Y flips)
1153
+ const mmX = (u) => u * k, mmY = (u) => (flipY ? -u : u) * k; // stored space → scene
1143
1154
  const levels = geo.zs.length ? visibleGridLevels(geo.zs, g.hidden_z) : [{ mm: 0, label: '0' }];
1144
1155
  if (!levels.length) return; // every authored Z datum is hidden
1145
1156
  gridLevelsMm = levels.map((lv) => lv.mm); // the planes grid snapping evaluates on — same list, same order as what gets drawn below
@@ -1257,7 +1268,7 @@ let rebuildSeq = 0;
1257
1268
  async function rebuild(fit = false) {
1258
1269
  if (!api) return;
1259
1270
  invalidatePointEntry('rebuild'); // synchronous, BEFORE the first await — the scene is changing; drop any open typed entry + stale base (never on stale async completion)
1260
- clipCandidates = null; clipLevels = null; scaleIdx = null; // …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
1271
+ 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
1261
1272
  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)
1262
1273
  if (fit) fitPending = true; // entering 3D re-fits; an edit-triggered rebuild keeps the camera put
1263
1274
  const seq = ++rebuildSeq;
@@ -1773,7 +1784,7 @@ function clipBoxFrom(a, b, zlo, ztop) {
1773
1784
  // the cache on every arm/disarm. A malformed member/grid degrades to no snap (raw floor), never a broken tool.
1774
1785
  let clipCandidates = null, clipLevels = null;
1775
1786
  function clipBoxSnapCands() { if (!clipCandidates) { try { clipCandidates = allCandidates(null); } catch { clipCandidates = []; } } return clipCandidates; }
1776
- function clipBoxLevels() { if (!clipLevels) { try { clipLevels = elevationLevelsByPlan(planList(), activeScale(), 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
1787
+ 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
1777
1788
  // A footprint corner from the cursor: the floor point under it, PULLED to a member/grid/UCS snap when one is
1778
1789
  // screen-near — same candidates + running-snaps filter as the Dimension / Move tools. Returns { xy:[x,y], snap,
1779
1790
  // world } or null (ray parallel to the floor). We keep only the snap's X/Y (the corner rides the floor plane).
@@ -2022,6 +2033,15 @@ function onKey(e) {
2022
2033
  }
2023
2034
  // ---- 3D dimension tool controls (driven from the toolbar + the keyboard) ----
2024
2035
  function toggleDimTool() {
2036
+ // ARMING is refused when the host says the model is read-only (unit 5, P7d). Disabling the #m3dDim
2037
+ // BUTTON is not enough and that was measured, not assumed: the tool also arms from a bare `d` keydown
2038
+ // on this view, and a DOM `disabled` only suppresses that button's own click — it says nothing about an
2039
+ // independent keyboard listener. Without this the user gets a live tool on a document that will refuse
2040
+ // its writes, which is the silent no-op the whole mode exists to avoid.
2041
+ if (!dimMode3d && api && typeof api.canEditModel === 'function' && !api.canEditModel()) {
2042
+ if (api.toast) api.toast('This model is read-only here — dimensions are coming. Ask your terminal AI to change it.');
2043
+ return dimMode3d;
2044
+ }
2025
2045
  if (!dimMode3d) dropGridLinePick3d(); // arming the dim tool takes the left-click — cancel an armed grid-line pick through the editor first
2026
2046
  dimMode3d = !dimMode3d;
2027
2047
  if (!dimMode3d) { dimDraft3d = null; dimCandidates3d = null; dimPreviewLine.visible = false; marker.visible = false; readout.style.display = 'none'; canvasEl.style.cursor = 'default'; setSnapOnly3d(null); } // disarming ends the operation → the snap override reverts to all snaps
@@ -2806,21 +2826,43 @@ const memberById = (id) => { const all = (api && api.allMembers && api.allMember
2806
2826
  // the ACTIVE plane's ppf/dtos, so editing an off-active-sheet member whose sheet has a different
2807
2827
  // pt_per_ft inverted the commit through the wrong scale and wrote a mis-scaled wp — while the target it
2808
2828
  // snapped to had been computed in the target sheet's own scale. One source ⇒ they cannot disagree.
2809
- const activeScale = () => ({ ptPerFt: api.ptPerFt(), defaultTosMm: api.defaultTosMm() });
2810
- const planList = () => { try { return (api.membersByPlan && api.membersByPlan()) || []; } catch { return []; } };
2811
- // id → owning plan's scale, built ONCE per scene rebuild. Resolving per call scanned every plan's
2812
- // members (and re-allocated the membersByPlan wrapper array), turning the model-wide per-member loops
2813
- // — labels, endpoints, reference lines, membersInRect — quadratic. Invalidated in buildFromScene
2814
- // alongside the other scene caches; a member added since the last rebuild misses the index and falls
2815
- // back to the active scale, which is where a newly-added member lives anyway.
2816
- let scaleIdx = null;
2817
- const scaleIndex = () => { if (!scaleIdx) { try { scaleIdx = planScaleIndex(planList(), activeScale()); } catch { return new Map(); } } return scaleIdx; }; // a transient failure returns an empty index WITHOUT caching it — caching one would silently downgrade every member to the active scale until the next rebuild
2818
- const scaleFor = (m) => planScaleOf(scaleIndex(), m, activeScale()); // keyed by the member OBJECT — ids are only sheet-unique
2819
- // A member's geometry in ITS OWN sheet's scale + default T.O.S — matching the server bake, which
2820
- // resolves per-plan (contract-to-scene: per-plan pt_per_ft + `default_tos ?? 0`). Using the ACTIVE
2821
- // sheet's default T.O.S here put every overlay (handles, labels, reference lines) for an off-sheet
2829
+ /*
2830
+ * ---- THE MODEL READ HALF (unit 5, P7d) -----------------------------------------------------------
2831
+ *
2832
+ * Every geometry read this view makes goes through ONE object the host injects, so the contract VERSION
2833
+ * stops at that boundary instead of branching through 4,400 lines. Epic §15 answer 4: "the gate at the
2834
+ * ADAPTER boundary, not scattered `if (v2)` branches through the editor closure" — a branch per geometry
2835
+ * site is the shape this epic has rejected three times.
2836
+ *
2837
+ * The host supplies BOTH arms. steel.takeoff/v1's is today's computation, moved verbatim — the per-plan
2838
+ * scale index, `planScaleOf`, `memberGeometryInOwnPlan` — so v1 stays byte-identical by construction
2839
+ * rather than by test. steel.model/v2's answers from world-mm members and needs none of it.
2840
+ *
2841
+ * WHAT LIVED HERE AND MOVED: `activeScale`, `planList`, `scaleIndex`, `scaleFor` and the scale cache.
2842
+ * P5's review round 4 corrected the understatement that geoOf was a delegation — it is a seam, and those
2843
+ * four came with it. The cache came too, which is why `invalidateModelCache()` exists: this view still
2844
+ * owns WHEN the model changed (buildFromScene, rebuild, buildStructGrid), it just no longer owns HOW the
2845
+ * geometry is derived.
2846
+ */
2847
+ let modelReads = null;
2848
+ function MODEL() {
2849
+ if (!modelReads) {
2850
+ // NAMED rather than a fallback. A host without this seam cannot be served by quietly reverting to v1's
2851
+ // computation: for a v2 document that would read `m.wp`/`m.col` off members that have neither and yield
2852
+ // NaN geometry — a scene that draws, silently, in nowhere.
2853
+ if (!api || typeof api.model !== 'function') throw new Error('steel-3d-view: the host supplied no api.model() — the model read half is required');
2854
+ modelReads = api.model();
2855
+ }
2856
+ return modelReads;
2857
+ }
2858
+ /** The model changed, or the grid did — drop whatever the read half cached off the old one. */
2859
+ function invalidateModelCache() { if (modelReads && typeof modelReads.invalidate === 'function') modelReads.invalidate(); }
2860
+ const scaleFor = (m) => MODEL().scaleOf(m); // keyed by the member OBJECT — ids are only sheet-unique
2861
+ // A member's WORK LINE in world mm. For v1 that is its OWN sheet's scale + default T.O.S — matching the
2862
+ // server bake, which resolves per-plan (contract-to-scene: per-plan pt_per_ft + `default_tos ?? 0`). Using
2863
+ // the ACTIVE sheet's default T.O.S put every overlay (handles, labels, reference lines) for an off-sheet
2822
2864
  // member whose T.O.S is unset at the WRONG elevation, while its server-built mesh sat at the right one.
2823
- const geoOf = (m) => memberGeometryInOwnPlan(m, scaleIndex(), activeScale());
2865
+ const geoOf = (m) => MODEL().geometryOf(m);
2824
2866
  const geoMode = () => (api && api.geoMode && api.geoMode()) || null;
2825
2867
 
2826
2868
  // ---- working plane (spec §6): session view-state grounding ALL 3D picks. null = the active plan's
@@ -2844,11 +2886,11 @@ let framePreview = null; // THREE.Group: the live X/Y rubber-band + Z-fli
2844
2886
  const cloneFrame = (f) => ({ origin: [...f.origin], xAxis: [...f.xAxis], yAxis: [...f.yAxis], normal: [...f.normal] });
2845
2887
  const _dot3 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
2846
2888
  const _unit3 = (a) => { const L = Math.hypot(a[0], a[1], a[2]) || 1; return [a[0] / L, a[1] / L, a[2] / L]; };
2847
- function frameZ() { return frame3d ? frame3d.origin[2] : (api ? api.defaultTosMm() : 0); }
2889
+ function frameZ() { return frame3d ? frame3d.origin[2] : (api ? MODEL().defaultPlaneZ() : 0); }
2848
2890
  function effectiveWP() {
2849
2891
  if (workPlane) return workPlane; // explicit ◇ Plane wins (unchanged)
2850
2892
  if (frame3d) return { origin: [...frame3d.origin], normal: [...frame3d.normal], xAxis: [...frame3d.xAxis], kind: 'frame' };
2851
- return { origin: [0, 0, api ? api.defaultTosMm() : 0], normal: [0, 0, 1], xAxis: [1, 0, 0] };
2893
+ return { origin: [0, 0, api ? MODEL().defaultPlaneZ() : 0], normal: [0, 0, 1], xAxis: [1, 0, 0] };
2852
2894
  }
2853
2895
  // ---- Typed coordinate entry (UCS Stage 3) — the ONE authoritative point-entry frame + a generation-stamped
2854
2896
  // lifecycle. `pointEntryFrame()` is what the tools actually follow: a ◇ Plane shadows the local frame, and
@@ -2919,7 +2961,7 @@ function setFrame3d(originMm, angleDeg) {
2919
2961
  // Set a full (possibly tilted) UCS from a computed basis — the 3-click pick's output.
2920
2962
  function setFrameBasis(basis) { frame3d = cloneFrame(basis); fireFrameChange(); }
2921
2963
  // Numeric "Angle°" sets a HORIZONTAL frame at that in-plane angle (keeps origin) — the horizontal refine case.
2922
- function setFrameAngle(angleDeg) { setFrame3d(frame3d ? frame3d.origin : [0, 0, api ? api.defaultTosMm() : 0], angleDeg); }
2964
+ function setFrameAngle(angleDeg) { setFrame3d(frame3d ? frame3d.origin : [0, 0, api ? MODEL().defaultPlaneZ() : 0], angleDeg); }
2923
2965
  function setFrameOrigin(originMm) { // translate origin, keep the basis orientation
2924
2966
  if (!frame3d) { setFrame3d(originMm, 0); return; }
2925
2967
  frame3d.origin = [originMm[0], originMm[1], originMm.length > 2 ? originMm[2] : frame3d.origin[2]];
@@ -3283,7 +3325,7 @@ function cmAxisLock(e, axisVec, base, opts) {
3283
3325
  if (Math.abs(n[2]) > 0.999 && !(opts && opts.noSnap)) { // ~vertical axis → snap the elevation to a framing level (WORLD-space: in Top view all levels share one screen point); Add+Alt passes noSnap so "no snap" holds even under a lock
3284
3326
  const tol = pxToWorldAt(SNAP_TOL_PX, base);
3285
3327
  let best = null, bestD = tol;
3286
- for (const z of elevationLevels(members(), api.ptPerFt(), api.defaultTosMm(), null)) { const d = Math.abs(p[2] - z); if (d <= bestD) { bestD = d; best = z; } }
3328
+ for (const z of MODEL().levelsHere()) { const d = Math.abs(p[2] - z); if (d <= bestD) { bestD = d; best = z; } }
3287
3329
  if (best != null) { t = (best - base[2]) / n[2]; p = [base[0] + n[0] * t, base[1] + n[1] * t, best]; snap = true; type = 'level'; } // re-solve t so the point stays exactly on base + t·axis
3288
3330
  }
3289
3331
  return { p, snap, type };
@@ -3701,12 +3743,25 @@ function onDown(e) {
3701
3743
  // to the Ctrl-copy this modifier combination would otherwise mean, quietly duplicating members
3702
3744
  // in the draft), it simply never becomes a drag-out.
3703
3745
  if (ids.length) {
3704
- teklaDrag = { ids, active: false, blocked: !!(api.teklaSendBusy && api.teklaSendBusy()) };
3705
- // Capture the pointer so move/up keep arriving once the cursor is over Tekla — that stream is
3706
- // the whole gesture. (A native HTML5 drag would carry an image over other windows, but the OS
3707
- // then paints its own "no drop here" cursor the entire way, because Tekla never accepts the
3708
- // data — it looks like a refusal while the send actually works.)
3746
+ teklaDrag = { ids, active: false, blocked: !!(api.teklaSendBusy && api.teklaSendBusy()), stack: null, running: [], target: null };
3747
+ // Capture the pointer so move/up keep arriving once the cursor is over the other app — that
3748
+ // stream is the whole gesture. (A native HTML5 drag would carry an image over other windows,
3749
+ // but the OS then paints its own "no drop here" cursor the entire way, because a CAD host
3750
+ // never accepts the data — it looks like a refusal while the send actually works.)
3709
3751
  try { canvasEl.setPointerCapture(e.pointerId); teklaDrag.pointerId = e.pointerId; } catch { /* capture is an optimisation; window-level listeners still fire */ }
3752
+ // Snapshot where the CAD windows are, ONCE, so the badge can name what the cursor is over
3753
+ // without a round-trip per pointer-move (a live probe costs ~350ms). Advisory only: the
3754
+ // release re-resolves authoritatively, so a stale snapshot can mislabel the badge for an
3755
+ // instant but can never send members to the wrong application. Fire-and-forget — if it never
3756
+ // arrives the badge simply stays unnamed and the drop still works.
3757
+ const claimed = teklaDrag;
3758
+ if (api.hostWindows) {
3759
+ api.hostWindows().then((snap) => {
3760
+ if (teklaDrag !== claimed) return; // the gesture ended before the answer came back
3761
+ claimed.stack = Array.isArray(snap && snap.stack) ? snap.stack : [];
3762
+ claimed.running = Array.isArray(snap && snap.running) ? snap.running : [];
3763
+ }).catch(() => { /* no snapshot: the badge stays unnamed, the drop is unaffected */ });
3764
+ }
3710
3765
  }
3711
3766
  }
3712
3767
  pending = {
@@ -3715,7 +3770,7 @@ function onDown(e) {
3715
3770
  grab: geo ? rayToPlane(e.clientX, e.clientY, planeZ) : null,
3716
3771
  origMm: geo ? geo.line.map((p) => [p[0], p[1], p[2]]) : null,
3717
3772
  candidates: allCandidates(ctrl ? undefined : id).filter((c) => candAllowed3d(c.type)), // member + grid snap targets (a ctrl-copy snaps to the ORIGINAL too; a move excludes itself), filtered by the running-snaps (⋯ menu → Snapping)
3718
- levels: elevationLevelsByPlan(planList(), activeScale(), m), // Alt-drag snaps to T.O.S levels across EVERY sheet, each in its own default elevation (pairing the active sheet's members with the grabbed sheet's default reported unset-T.O.S members at an elevation they are not drawn at)
3773
+ levels: MODEL().levels(m), // Alt-drag snaps to T.O.S levels across EVERY sheet, each in its own default elevation (pairing the active sheet's members with the grabbed sheet's default reported unset-T.O.S members at an elevation they are not drawn at)
3719
3774
  mesh, meshPos0: mesh ? mesh.position.clone() : null, delta: null, mode: null,
3720
3775
  };
3721
3776
  } catch (err) { controls.enabled = true; pending = null; endTeklaDrag(); } // a failure must never strand orbit disabled — nor an armed drag-out holding the pointer capture, which the next movement would fire
@@ -3733,6 +3788,46 @@ function onDown(e) {
3733
3788
  // keeps move/up flowing while the cursor is over Tekla, leaves the cursor alone, and makes Esc a real
3734
3789
  // cancel (during a native drag the page never sees the key).
3735
3790
 
3791
+ /** Short display names for the drop targets. The badge has no room for "Tekla Structures". */
3792
+ const HOST_SHORT = { tekla: 'Tekla', revit: 'Revit', sketchup: 'SketchUp' };
3793
+
3794
+ /**
3795
+ * Which host is under this screen point, per the snapshot taken at dragstart?
3796
+ *
3797
+ * The topmost window containing the point decides, host or not — non-host windows are in the stack
3798
+ * precisely so an app sitting over Revit reads as "not Revit" rather than being ignored. Browser
3799
+ * screen coordinates are CSS pixels; the snapshot is in physical pixels, so they are scaled by the
3800
+ * device pixel ratio before comparison or the hit lands off by the display scale factor.
3801
+ */
3802
+ function hostUnderPointer(drag, e) {
3803
+ if (!drag || !Array.isArray(drag.stack) || !drag.stack.length) return null;
3804
+ const dpr = window.devicePixelRatio || 1;
3805
+ const x = e.screenX * dpr, y = e.screenY * dpr;
3806
+ for (const w of drag.stack) {
3807
+ if (x >= w.left && x < w.right && y >= w.top && y < w.bottom) return w.host || null;
3808
+ }
3809
+ return null;
3810
+ }
3811
+
3812
+ /**
3813
+ * Keep the badge's words in step with what the cursor is actually over.
3814
+ *
3815
+ * A named target reads "3 members → Revit", so the promise is specific before the user commits.
3816
+ * Over something we do not recognise the badge must NOT name a host it is not going to reach — it
3817
+ * says where to go instead. Only the text node is rewritten, so the brand glyph is never rebuilt.
3818
+ */
3819
+ function paintDragBadge(drag) {
3820
+ if (!drag || !drag.badge) return;
3821
+ const n = drag.ids.length, noun = n === 1 ? 'member' : 'members';
3822
+ const label = drag.target ? HOST_SHORT[drag.target] : null;
3823
+ // With no recognised target the arrow is DROPPED rather than pointed at a guess: the badge is
3824
+ // decorative (it clips at the window edge anyway), and the status chip below carries the sentence
3825
+ // that actually teaches where to go. A badge promising a destination it cannot reach is worse
3826
+ // than a badge that just counts.
3827
+ const node = drag.badge.lastChild;
3828
+ if (node && node.nodeType === 3) node.nodeValue = label ? `${n} ${noun} → ${label}` : `${n} ${noun}`;
3829
+ }
3830
+
3736
3831
  /** The badge that follows the cursor while a drag-out is live (same recipe as the legend's drag ghost). */
3737
3832
  function teklaBadge(n) {
3738
3833
  const el = document.createElement('div');
@@ -3740,7 +3835,7 @@ function teklaBadge(n) {
3740
3835
  el.innerHTML = '<svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false">'
3741
3836
  + '<path d="M9.5 2.5H13.5V6.5M13.5 2.5 8 8M11 9.5V12a1.5 1.5 0 0 1-1.5 1.5h-6A1.5 1.5 0 0 1 2 12V6a1.5 1.5 0 0 1 1.5-1.5H6"'
3742
3837
  + ' fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>';
3743
- el.append(document.createTextNode(`${n} ${n === 1 ? 'member' : 'members'} → Tekla`));
3838
+ el.append(document.createTextNode(`${n} ${n === 1 ? 'member' : 'members'}`)); // paintDragBadge names the target
3744
3839
  document.body.appendChild(el);
3745
3840
  return el;
3746
3841
  }
@@ -3795,7 +3890,14 @@ function onTeklaDragMove(e) {
3795
3890
  // the message from there.
3796
3891
  teklaDrag.badge.style.left = (e.clientX + 16) + 'px';
3797
3892
  teklaDrag.badge.style.top = (e.clientY + 14) + 'px';
3798
- if (canvasEl) canvasEl.style.cursor = pointerOutsideWindow(e) ? 'default' : 'alias';
3893
+ // Only name a target once the pointer has actually left FloLess. Inside our own window the answer
3894
+ // is always "release here to cancel", and naming a host underneath us would invite the user to
3895
+ // let go somewhere that abandons the gesture.
3896
+ const outside = pointerOutsideWindow(e);
3897
+ const nextTarget = outside ? hostUnderPointer(teklaDrag, e) : null;
3898
+ if (nextTarget !== teklaDrag.target) { teklaDrag.target = nextTarget; updateStatusChip(); }
3899
+ paintDragBadge(teklaDrag);
3900
+ if (canvasEl) canvasEl.style.cursor = outside ? 'default' : 'alias';
3799
3901
  }
3800
3902
 
3801
3903
  // Vertical (Alt) drag: raise/lower the member's elevation, snapping to other members' T.O.S levels.
@@ -4013,11 +4115,21 @@ function onUp(e) {
4013
4115
  // or readout left over from before the gesture would otherwise sit on the canvas until the next
4014
4116
  // hover. The send is deferred to just past that line for the same reason.
4015
4117
  pending = dragging = null; downXY = null; if (controls) controls.enabled = true;
4016
- if (pointerOutsideWindow(e) && api && api.onSendToTekla) teklaSend = drag.ids;
4118
+ // Carry the RELEASE POINT, not the badge's guess. The badge reads a snapshot taken at
4119
+ // dragstart, which is advisory; the send re-resolves the window under this exact point so a
4120
+ // window that moved, or an app that came to the front mid-drag, cannot misdirect the members.
4121
+ // `hinted` is only what the badge promised, so the caller can tell a real change of target
4122
+ // from an unresolvable drop.
4123
+ if (pointerOutsideWindow(e) && api && api.onSendToHost) {
4124
+ // CSS screen pixels, plus OUR ratio. The physical conversion belongs to the server, which
4125
+ // knows about monitors; a mixed-DPI desktop makes this window's ratio a poor guide once the
4126
+ // cursor is over a differently-scaled screen.
4127
+ teklaSend = { ids: drag.ids, screenX: e.screenX, screenY: e.screenY, dpr: window.devicePixelRatio || 1, hinted: drag.target, running: drag.running };
4128
+ }
4017
4129
  }
4018
4130
  }
4019
4131
  if (marker) marker.visible = false; if (readout) readout.style.display = 'none'; if (rubber) rubber.style.display = 'none'; if (epPreview) epPreview.visible = false; if (epMovedLine) epMovedLine.visible = false; clearCopyGhost(); dragEp = null; // always clear overlays
4020
- if (teklaSend) { api.onSendToTekla(teklaSend); return; }
4132
+ if (teklaSend) { api.onSendToHost(teklaSend); return; }
4021
4133
  if (!renderer || !canvasEl || canvasEl.style.display === 'none') { downXY = null; boxSel = pending = dragging = null; if (controls) controls.enabled = true; return; } // 3D hidden mid-gesture → drop stale gesture state (no resume on re-show)
4022
4134
  const bs = boxSel; boxSel = null;
4023
4135
  if (bs) { // empty-space gesture: drag = box-select, click = clear selection
@@ -4242,7 +4354,13 @@ function updateStatusChip() {
4242
4354
  const showId = hoverId || (selIds.size === 1 ? [...selIds][0] : null);
4243
4355
  // The badge follows the cursor and so clips away at the window edge — from there this chip is the
4244
4356
  // only thing still telling the user what releasing will do.
4245
- if (teklaDrag && teklaDrag.active) txt = `Release over the Tekla window to insert ${teklaDrag.ids.length} member${teklaDrag.ids.length === 1 ? '' : 's'} · release here or Esc to cancel`;
4357
+ if (teklaDrag && teklaDrag.active) {
4358
+ const n = teklaDrag.ids.length, noun = n === 1 ? 'member' : 'members';
4359
+ // Name the app the pointer is actually over, so the chip and the badge never disagree.
4360
+ txt = teklaDrag.target
4361
+ ? `Release to insert ${n} ${noun} into ${HOST_SHORT[teklaDrag.target]} · release here or Esc to cancel`
4362
+ : `Release over Tekla, Revit or SketchUp to insert ${n} ${noun} · release here or Esc to cancel`;
4363
+ }
4246
4364
  else if (wpMode === 'face') txt = 'Click a member face — the working plane lands on it · Esc to cancel';
4247
4365
  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] || '';
4248
4366
  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';
@@ -4286,6 +4404,7 @@ function hide() {
4286
4404
  function isReady() { return built; }
4287
4405
 
4288
4406
  function dispose() {
4407
+ 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)
4289
4408
  endTeklaDrag(); // release the pointer capture and take the badge with us
4290
4409
  if (rafId) cancelAnimationFrame(rafId);
4291
4410
  if (hoverRAF) cancelAnimationFrame(hoverRAF);