@floless/app 0.101.0 → 0.101.2

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.
@@ -3,13 +3,14 @@
3
3
  * node (server/grid-core.test.ts) AND loaded by the steel editor's 2D plan mode + 3D view.
4
4
  *
5
5
  * The grid is Tekla-style but friendlier: X/Y spacings are RELATIVE coordinate strings
6
- * ("0 3*25' 20'-6\"" — each entry is the distance from the previous line, n*d repeats a bay),
6
+ * ("0'-0\", 3*25'-0\", 20'-6 1/2\"" — commas separate entries; n*d repeats a bay),
7
7
  * Z levels are ABSOLUTE elevations. Tokens accept ft-in (25'-6"), bare inches (6"), metres (7.5m)
8
8
  * and bare numbers as mm — mixed freely. Everything parses to canonical mm.
9
9
  *
10
10
  * Contract shape (PER-PLAN, plan.grid — origin/spacings live in that sheet's display space, like
11
11
  * member wp / frame / dims, so it rides the per-plan undo stack safely):
12
- * { on, origin:[x,y] px, x:"0 3*25'", y:"0 4*20'", z:"0", labels_x:"", labels_y:"", ext: mm,
12
+ * { on, origin:[x,y] px, x:"0'-0\", 3*25'-0\"", y:"0'-0\", 4*20'-0\"", z:"0'-0\"",
13
+ * labels_x:"", labels_y:"", labels_z:[], ext: mm,
13
14
  * lines:[{ id, label, a:[x,y], b:[x,y] }] }
14
15
  * X entries position lines ALONG +X (the lines run vertically on the plan), labelled 1,2,3… ;
15
16
  * Y entries march UP the sheet (display -Y == scene +Y), lines horizontal, labelled A,B,C… .
@@ -19,10 +20,29 @@
19
20
  export const IN_MM = 25.4;
20
21
  export const FT_MM = 304.8;
21
22
 
23
+ const gcd = (a, b) => { while (b) { const t = a % b; a = b; b = t; } return a; };
24
+ export const truncateText = (value, maxLength = 40) => Array.from(String(value == null ? '' : value)).slice(0, maxLength).join('');
25
+
26
+ const parseInches = (raw) => {
27
+ const s = String(raw || '').trim();
28
+ let m;
29
+ if ((m = /^(\d+(?:\.\d+)?)(?:\s+(\d+)\/(\d+))?$/.exec(s))) {
30
+ const whole = +m[1];
31
+ if (!m[2]) return whole;
32
+ const num = +m[2], den = +m[3];
33
+ return den > 0 && num < den ? whole + num / den : NaN;
34
+ }
35
+ if ((m = /^(\d+)\/(\d+)$/.exec(s))) {
36
+ const num = +m[1], den = +m[2];
37
+ return den > 0 && num < den ? num / den : NaN;
38
+ }
39
+ return NaN;
40
+ };
41
+
22
42
  /** mm per display px for a plan scale (matches steel-3d-core kOf). */
23
43
  export const mmPerPx = (ptPerFt) => FT_MM / (ptPerFt > 0 ? ptPerFt : 1);
24
44
 
25
- /** One length token → mm, or NaN. Accepts 25' | 25'-6" | 25'6" | 6" | 7.5m | 6096 (mm) | 6096mm; leading '-' negates. */
45
+ /** One length token → mm, or NaN. Accepts 25' | 25'-6 1/2" | 6 1/2" | 1/2" | 7.5m | 6096 (mm) | 6096mm; leading '-' negates. */
26
46
  export function parseLen(tok) {
27
47
  let s = String(tok == null ? '' : tok).trim();
28
48
  if (!s) return NaN;
@@ -30,37 +50,61 @@ export function parseLen(tok) {
30
50
  if (s[0] === '-') { sign = -1; s = s.slice(1); }
31
51
  else if (s[0] === '+') s = s.slice(1);
32
52
  let m;
33
- if ((m = /^(\d+(?:\.\d+)?)'(?:-?(\d+(?:\.\d+)?)")?$/.exec(s))) return sign * (+m[1] * FT_MM + (m[2] ? +m[2] * IN_MM : 0));
34
- if ((m = /^(\d+(?:\.\d+)?)"$/.exec(s))) return sign * +m[1] * IN_MM;
53
+ if ((m = /^(\d+(?:\.\d+)?)'(?:-?(.+)")?$/.exec(s))) {
54
+ const inches = m[2] == null ? 0 : parseInches(m[2]);
55
+ return isFinite(inches) ? sign * (+m[1] * FT_MM + inches * IN_MM) : NaN;
56
+ }
57
+ if ((m = /^(.+)"$/.exec(s))) {
58
+ const inches = parseInches(m[1]);
59
+ return isFinite(inches) ? sign * inches * IN_MM : NaN;
60
+ }
35
61
  if ((m = /^(\d+(?:\.\d+)?)m$/.exec(s))) return sign * +m[1] * 1000;
36
62
  if ((m = /^(\d+(?:\.\d+)?)(?:mm)?$/.exec(s))) return sign * +m[1];
37
63
  return NaN;
38
64
  }
39
65
 
40
- /** mm → a clean display token: ft-in when it lands on a 1/16", else integer mm. Round-trips through parseLen. */
66
+ /** mm → canonical architectural ft-in rounded to the nearest 1/16". Round-trips through parseLen. */
41
67
  export function fmtLen(mm) {
42
- if (Math.abs(mm) < 0.05) return '0';
43
- const neg = mm < 0, a = Math.abs(mm);
44
- const sixteenths = Math.round(a / (IN_MM / 16));
45
- if (sixteenths > 0 && Math.abs(a - sixteenths * (IN_MM / 16)) < 0.05) { // lands on a 1/16" → ft-in reads native for US drawings
46
- const inches = sixteenths / 16;
47
- const ft = Math.floor(inches / 12);
48
- const rest = inches - ft * 12; // may be fractional — decimal inches, since tokens can't contain spaces
49
- const restStr = String(Math.round(rest * 16) / 16) + '"';
50
- const body = ft > 0 ? (ft + "'" + (rest > 0 ? '-' + restStr : '')) : restStr;
51
- return (neg ? '-' : '') + body;
68
+ const total16 = Math.round(Math.abs(Number(mm) || 0) / (IN_MM / 16));
69
+ const feet16 = Math.floor(total16 / (12 * 16));
70
+ const rem16 = total16 % (12 * 16);
71
+ const inches16 = Math.floor(rem16 / 16);
72
+ const numerator16 = rem16 % 16;
73
+ let inchText16 = String(inches16);
74
+ if (numerator16) {
75
+ const divisor16 = gcd(numerator16, 16);
76
+ inchText16 += ' ' + (numerator16 / divisor16) + '/' + (16 / divisor16);
77
+ }
78
+ return (mm < 0 && total16 ? '-' : '') + feet16 + "'-" + inchText16 + '"';
79
+ }
80
+
81
+ export function lengthTokens(str, allowRepeat = false) {
82
+ const raw = String(str == null ? '' : str).trim();
83
+ if (!raw) return { tokens: [], err: null };
84
+ const validSingle = (s) => {
85
+ const rep = allowRepeat ? /^(\d+)[*xX](.+)$/.exec(s) : null;
86
+ return isFinite(parseLen(rep ? rep[2] : s));
87
+ };
88
+ if (raw.includes(',')) {
89
+ const tokens = raw.split(',').map((s) => s.trim());
90
+ if (tokens.some((s) => !s)) return { tokens: [], err: 'empty value — separate values with a single comma' };
91
+ return { tokens, err: null };
52
92
  }
53
- return (neg ? '-' : '') + Math.round(a);
93
+ if (validSingle(raw)) return { tokens: [raw], err: null };
94
+ if (raw.includes('/')) return { tokens: [], err: 'Separate values with commas.' };
95
+ return { tokens: raw.split(/\s+/).filter(Boolean), err: null };
54
96
  }
55
97
 
56
98
  /**
57
99
  * A relative spacing string → cumulative offsets (mm, from the grid origin).
58
- * "0 3*25' 20'" → [0, 7620, 15240, 22860, 28956]. Separators: whitespace / commas; repeat: n*d or nxd.
100
+ * "0'-0\", 3*25'-0\", 20'-0\"" → [0, 7620, 15240, 22860, 28956]. Repeat: n*d or nxd.
59
101
  * The first entry is the first line's offset (any sign); later entries must be > 0.
60
102
  * Returns { offsets, err } — err is a human-readable reason (offsets = [] then).
61
103
  */
62
104
  export function parseSpacings(str) {
63
- const toks = String(str == null ? '' : str).trim().split(/[\s,]+/).filter(Boolean);
105
+ const split = lengthTokens(str, true);
106
+ if (split.err) return { offsets: [], err: split.err };
107
+ const toks = split.tokens;
64
108
  if (!toks.length) return { offsets: [], err: null }; // empty = a valid axis-less grid (X-only / Y-only)
65
109
  const offsets = [];
66
110
  let at = 0;
@@ -71,24 +115,103 @@ export function parseSpacings(str) {
71
115
  if (!isFinite(d) || (rep && n < 1)) return { offsets: [], err: 'can’t read “' + toks[i] + '”' };
72
116
  const isFirstOffset = (i === 0 && !rep); // only the first plain entry may be ≤ 0 (the origin offset)
73
117
  if (!isFirstOffset && d <= 0) return { offsets: [], err: 'spacing “' + toks[i] + '” must be > 0' };
118
+ if (!isFirstOffset && Math.round(d / (IN_MM / 16)) <= 0) return { offsets: [], err: 'spacing "' + toks[i] + '" must be > 0' };
74
119
  for (let r = 0; r < n; r++) { at += d; offsets.push(at); }
75
120
  }
76
121
  return { offsets, err: null };
77
122
  }
78
123
 
79
- /** Cumulative offsets (mm) → a compact relative string ("0 3*25' 20'"): equal runs compress to n*d. */
124
+ /** Cumulative offsets (mm) → a canonical comma-separated string; equal runs compress to n*d. */
80
125
  export function formatSpacings(offsets) {
81
126
  if (!offsets || !offsets.length) return '';
82
127
  const diffs = offsets.map((v, i) => v - (i ? offsets[i - 1] : 0));
128
+ const tokens = diffs.map(fmtLen);
83
129
  const out = [];
84
- for (let i = 0; i < diffs.length;) {
130
+ for (let i = 0; i < tokens.length;) {
85
131
  let j = i + 1;
86
- while (j < diffs.length && Math.abs(diffs[j] - diffs[i]) < 0.5) j++;
87
- const n = j - i, tok = fmtLen(diffs[i]);
132
+ while (j < tokens.length && tokens[j] === tokens[i]) j++;
133
+ const n = j - i, tok = tokens[i];
88
134
  out.push(n > 1 ? n + '*' + tok : tok);
89
135
  i = j;
90
136
  }
91
- return out.join(' ');
137
+ return out.join(', ');
138
+ }
139
+
140
+ export function parseLevels(str, labelsZ = []) {
141
+ const split = lengthTokens(str, false);
142
+ if (split.err) return { levels: [], err: split.err, warnings: [], tokens: [] };
143
+ const labels = Array.isArray(labelsZ) ? labelsZ : [];
144
+ const warnings = [];
145
+ const levels = [];
146
+ for (let sourceIndex = 0; sourceIndex < split.tokens.length; sourceIndex++) {
147
+ const token = split.tokens[sourceIndex];
148
+ const rawMm = parseLen(token);
149
+ if (!isFinite(rawMm)) return { levels: [], err: 'can’t read “' + token + '”', warnings, tokens: split.tokens };
150
+ const mm = parseLen(fmtLen(rawMm)); // persist the same 1/16" value the panel displays, so two authored values can never serialize identically and collapse on the next read
151
+ const authored = truncateText(String(labels[sourceIndex] == null ? '' : labels[sourceIndex]).trim());
152
+ const duplicate = levels.find((z) => Math.abs(z.mm - mm) < 0.5);
153
+ if (duplicate) {
154
+ warnings.push({ kind: authored && authored !== duplicate.label ? 'duplicate-label' : 'duplicate-level', sourceIndex, keptSourceIndex: duplicate.sourceIndex });
155
+ continue;
156
+ }
157
+ levels.push({ mm, label: authored || fmtLen(mm), sourceIndex });
158
+ }
159
+ for (let i = split.tokens.length; i < labels.length; i++) {
160
+ if (String(labels[i] == null ? '' : labels[i]).trim()) warnings.push({ kind: 'orphan-label', sourceIndex: i });
161
+ }
162
+ levels.sort((a, b) => a.mm - b.mm);
163
+ return { levels, err: null, warnings, tokens: split.tokens };
164
+ }
165
+
166
+ /**
167
+ * Re-key source-indexed labels to the sorted/deduplicated level order while retaining every
168
+ * non-empty label whose source elevation was dropped. Extras remain appended until the user
169
+ * explicitly removes them, so editing a matched label never becomes implicit data loss.
170
+ */
171
+ export function normalizeLevelLabels(parsed, labelsZ = []) {
172
+ const labels = Array.isArray(labelsZ) ? labelsZ : [];
173
+ const levels = parsed && Array.isArray(parsed.levels) ? parsed.levels : [];
174
+ const used = new Set(levels.map((level) => level.sourceIndex));
175
+ const normalized = levels.map((level) => truncateText(String(labels[level.sourceIndex] == null ? '' : labels[level.sourceIndex]).trim()));
176
+ const extras = [];
177
+ for (let i = 0; i < labels.length; i++) {
178
+ const label = truncateText(String(labels[i] == null ? '' : labels[i]).trim());
179
+ if (label && !used.has(i)) extras.push(label);
180
+ }
181
+ return { labels: [...normalized, ...extras], extraCount: extras.length };
182
+ }
183
+
184
+ /**
185
+ * Carry labels from one canonical level list to another by elevation, never by display position.
186
+ * The editor sorts Z values before showing them, so using array indexes here would silently swap
187
+ * labels loaded from an unsorted legacy contract. Labels for removed elevations join the retained
188
+ * extras and remain available until the user explicitly removes them.
189
+ */
190
+ export function reconcileLevelLabels(previousParsed, normalizedLabels = [], nextParsed) {
191
+ const previous = previousParsed && Array.isArray(previousParsed.levels) ? previousParsed.levels : [];
192
+ const next = nextParsed && Array.isArray(nextParsed.levels) ? nextParsed.levels : [];
193
+ const labels = Array.isArray(normalizedLabels)
194
+ ? normalizedLabels.map((label) => truncateText(String(label == null ? '' : label).trim()))
195
+ : [];
196
+ const byElevation = new Map();
197
+ previous.forEach((level, index) => byElevation.set(fmtLen(level.mm), { index, label: labels[index] || '' }));
198
+ const used = new Set();
199
+ const matched = next.map((level) => {
200
+ const prior = byElevation.get(fmtLen(level.mm));
201
+ if (!prior) return '';
202
+ used.add(prior.index);
203
+ return prior.label;
204
+ });
205
+ const extras = labels.slice(previous.length).filter(Boolean);
206
+ previous.forEach((_, index) => {
207
+ const label = labels[index] || '';
208
+ if (label && !used.has(index)) extras.push(label);
209
+ });
210
+ return { labels: [...matched, ...extras], extraCount: extras.length };
211
+ }
212
+
213
+ export function formatLevels(levels) {
214
+ return (levels || []).map(fmtLen).join(', ');
92
215
  }
93
216
 
94
217
  /** Auto labels: style 'num' → 1,2,3… ; 'alpha' → A…Z, AA, AB… */
@@ -112,7 +235,7 @@ export function labelsFor(override, style, n) {
112
235
 
113
236
  /** A fresh default grid (display-space origin px). 4×4 30' bays, ground level only. */
114
237
  export function defaultGrid(origin) {
115
- return { on: true, origin: (origin || [0, 0]).slice(0, 2), x: "0 3*30'", y: "0 3*30'", z: '0', labels_x: '', labels_y: '', ext: 5 * FT_MM };
238
+ return { on: true, origin: (origin || [0, 0]).slice(0, 2), x: "0'-0\", 3*30'-0\"", y: "0'-0\", 3*30'-0\"", z: "0'-0\"", labels_x: '', labels_y: '', labels_z: [], ext: 5 * FT_MM };
116
239
  }
117
240
 
118
241
  /** True when g is structurally usable (parseable origin — the spacing strings report their own errors). */
@@ -124,12 +247,15 @@ const pt2 = (p) => Array.isArray(p) && p.length >= 2 && isFinite(p[0]) && isFini
124
247
 
125
248
  /** Sanitized standalone/free-angle grid lines. Invalid or zero-length lines are ignored. */
126
249
  export function gridLines(g) {
127
- const out = [];
250
+ const out = [], used = new Set();
128
251
  if (!g || !Array.isArray(g.lines)) return out;
129
252
  for (let i = 0; i < g.lines.length; i++) {
130
253
  const l = g.lines[i] || {}, a = pt2(l.a), b = pt2(l.b);
131
254
  if (!a || !b || Math.hypot(b[0] - a[0], b[1] - a[1]) < 1e-6) continue;
132
- out.push({ id: String(l.id || ('line-' + (i + 1))), label: String(l.label || (i + 1)), a, b });
255
+ const root = String(l.id || ('line-' + (i + 1))); let id = root, suffix = 2;
256
+ while (used.has(id)) id = root + '-' + suffix++;
257
+ used.add(id);
258
+ out.push({ id, label: String(l.label || (i + 1)), a, b });
133
259
  }
134
260
  return out;
135
261
  }
@@ -139,8 +265,9 @@ export function gridLines(g) {
139
265
  * v = vertical lines (spaced along +X, labels 1,2,3…): { x, label }
140
266
  * h = horizontal lines (spaced UP the sheet = -Y, labels A,B,C…): { y, label }
141
267
  * lines = standalone free-angle lines: { id, label, a, b }
142
- * zs = levels: { mm, label } (sorted, deduped). ext/extents are display px.
143
- * errX/errY/errZ carry per-axis parse errors; lines of a failed axis are [].
268
+ * zs = levels: { mm, label, sourceIndex } (sorted, deduped). ext/extents are display px.
269
+ * errX/errY/errZ carry per-axis parse errors; warningsZ reports duplicate/orphan level labels;
270
+ * lines of a failed axis are [].
144
271
  */
145
272
  export function gridGeometry(g, ptPerFt) {
146
273
  const k = mmPerPx(ptPerFt);
@@ -152,17 +279,9 @@ export function gridGeometry(g, ptPerFt) {
152
279
  const ly = labelsFor(g && g.labels_y, 'alpha', Y.offsets.length);
153
280
  const v = X.offsets.map((off, i) => ({ x: ox + px(off), label: lx[i] }));
154
281
  const h = Y.offsets.map((off, i) => ({ y: oy - px(off), label: ly[i] })); // up the sheet = -Y (scene +Y)
155
- // Z levels: absolute tokens, sorted + deduped, labelled by elevation (or overridden order-preserving)
156
- const ztoks = String((g && g.z) == null ? '' : g.z).trim().split(/[\s,]+/).filter(Boolean);
157
- let errZ = null;
158
- const zmm = [];
159
- for (const t of ztoks) {
160
- const val = parseLen(t);
161
- if (!isFinite(val)) { errZ = 'can’t read “' + t + '”'; break; }
162
- if (!zmm.some((z) => Math.abs(z - val) < 0.5)) zmm.push(val);
163
- }
164
- zmm.sort((a, b) => a - b);
165
- const zs = errZ ? [] : zmm.map((mm) => ({ mm, label: fmtLen(mm) }));
282
+ // Z levels are absolute, sorted/deduped, and retain their authored label source index.
283
+ const resolvedZ = parseLevels(g && g.z, g && g.labels_z);
284
+ const levelsZ = resolvedZ.err ? [] : resolvedZ.levels;
166
285
  const ext = px((g && isFinite(g.ext)) ? g.ext : 5 * FT_MM);
167
286
  const xs = v.map((l) => l.x), ys = h.map((l) => l.y);
168
287
  const lines = gridLines(g);
@@ -171,8 +290,8 @@ export function gridGeometry(g, ptPerFt) {
171
290
  const ly0 = lines.length ? Math.min(...lines.flatMap((l) => [l.a[1], l.b[1]])) : oy;
172
291
  const ly1 = lines.length ? Math.max(...lines.flatMap((l) => [l.a[1], l.b[1]])) : oy;
173
292
  const geo = {
174
- v, h, lines, zs,
175
- errX: X.err, errY: Y.err, errZ,
293
+ v, h, lines, zs: levelsZ,
294
+ errX: X.err, errY: Y.err, errZ: resolvedZ.err, warningsZ: resolvedZ.warnings,
176
295
  ext,
177
296
  x0: Math.min((xs.length ? Math.min(...xs) : ox), lx0) - ext,
178
297
  x1: Math.max((xs.length ? Math.max(...xs) : ox), lx1) + ext,
@@ -427,9 +546,10 @@ export function gridFromDrawing(elements, ptPerFt) {
427
546
  const labeled = [...v, ...h].length > 0 && [...v, ...h].every((l) => l.label);
428
547
  const grid = {
429
548
  on: true, origin,
430
- x: formatSpacings(xOff), y: formatSpacings(yOff), z: '0',
549
+ x: formatSpacings(xOff), y: formatSpacings(yOff), z: "0'-0\"",
431
550
  labels_x: labeled ? v.map((l) => l.label).join(' ') : '',
432
551
  labels_y: labeled ? h.map((l) => l.label).reverse().join(' ') : '',
552
+ labels_z: [],
433
553
  ext: 5 * FT_MM,
434
554
  };
435
555
  // extension: how far lines overhang the perpendicular family (to reach their bubbles)
@@ -471,5 +591,5 @@ export function inferGrid(members, ptPerFt) {
471
591
  const origin = [cx[0], cy[cy.length - 1]]; // left-most line × bottom-most (display y-down) line
472
592
  const xOff = cx.map((x) => snapHalfIn((x - origin[0]) * k));
473
593
  const yOff = cy.map((y) => snapHalfIn((origin[1] - y) * k)).reverse(); // up the sheet, ascending
474
- return { on: true, origin, x: formatSpacings(xOff), y: formatSpacings(yOff), z: '0', labels_x: '', labels_y: '', ext: 5 * FT_MM };
594
+ return { on: true, origin, x: formatSpacings(xOff), y: formatSpacings(yOff), z: "0'-0\"", labels_x: '', labels_y: '', labels_z: [], ext: 5 * FT_MM };
475
595
  }
@@ -14,6 +14,116 @@
14
14
  export const FT_TO_MM = 304.8;
15
15
  export const IN_TO_MM = 25.4;
16
16
 
17
+ /**
18
+ * Clip a 3D segment against convex half-spaces. Each plane is
19
+ * `{ normal:[x,y,z], constant }`, with points on the non-negative side kept.
20
+ * The representation intentionally mirrors THREE.Plane without importing Three,
21
+ * so camera/section clipping stays deterministic and unit-testable.
22
+ */
23
+ export function clipSegmentToPlanes(a, b, planes = []) {
24
+ let lo = 0, hi = 1;
25
+ for (const plane of planes) {
26
+ const n = plane && plane.normal;
27
+ if (!n) continue;
28
+ const c = Number(plane.constant) || 0;
29
+ const da = n[0] * a[0] + n[1] * a[1] + n[2] * a[2] + c;
30
+ const db = n[0] * b[0] + n[1] * b[1] + n[2] * b[2] + c;
31
+ if (da < 0 && db < 0) return null;
32
+ if (da < 0 || db < 0) {
33
+ const t = da / (da - db);
34
+ if (da < 0) lo = Math.max(lo, t);
35
+ else hi = Math.min(hi, t);
36
+ if (lo > hi) return null;
37
+ }
38
+ }
39
+ const mix = (t) => [
40
+ a[0] + (b[0] - a[0]) * t,
41
+ a[1] + (b[1] - a[1]) * t,
42
+ a[2] + (b[2] - a[2]) * t,
43
+ ];
44
+ return [mix(lo), mix(hi)];
45
+ }
46
+
47
+ /** Closest screen-pixel distance from `point` to segment a-b, including its clamped parameter. */
48
+ export function pointSegmentDistance2d(point, a, b) {
49
+ const dx = b[0] - a[0], dy = b[1] - a[1], d2 = dx * dx + dy * dy;
50
+ const t = d2 ? Math.max(0, Math.min(1, ((point[0] - a[0]) * dx + (point[1] - a[1]) * dy) / d2)) : 0;
51
+ const closest = [a[0] + dx * t, a[1] + dy * t];
52
+ return { distance: Math.hypot(point[0] - closest[0], point[1] - closest[1]), t, closest };
53
+ }
54
+
55
+ /**
56
+ * Convert a parameter measured along the projected screen segment back to the
57
+ * linear parameter on its world segment. Perspective projection divides each
58
+ * endpoint by clip-space W, so direct world lerp with the screen parameter is
59
+ * only correct for orthographic/equal-W endpoints.
60
+ */
61
+ export function perspectiveSegmentParameter(screenT, clipW0, clipW1) {
62
+ const rawS = Number(screenT);
63
+ const s = Number.isFinite(rawS) ? Math.max(0, Math.min(1, rawS)) : 0;
64
+ const w0 = Number(clipW0), w1 = Number(clipW1);
65
+ if (!Number.isFinite(w0) || !Number.isFinite(w1) || Math.abs(w0) < 1e-12 || Math.abs(w1) < 1e-12) return s;
66
+ const denominator = (1 - s) * w1 + s * w0;
67
+ if (!Number.isFinite(denominator) || Math.abs(denominator) < 1e-12) return s;
68
+ return Math.max(0, Math.min(1, (s * w0) / denominator));
69
+ }
70
+
71
+ /** True when a projected grid hit is at least as near as the closest solid hit at the pointer. */
72
+ export function gridDepthWins(gridDepth, meshDepth, epsilon = 1e-6) {
73
+ if (!Number.isFinite(gridDepth)) return false;
74
+ return !Number.isFinite(meshDepth) || gridDepth <= meshDepth + epsilon;
75
+ }
76
+
77
+ /** Tekla-style area hit: window mode encloses both ends; crossing mode accepts any touch. */
78
+ export function segmentHitsRect2d(a, b, rect, windowMode) {
79
+ const inside = (p) => p[0] >= rect[0] && p[0] <= rect[2] && p[1] >= rect[1] && p[1] <= rect[3];
80
+ if (windowMode) return inside(a) && inside(b);
81
+ if (inside(a) || inside(b)) return true;
82
+ const EPS = 1e-9;
83
+ const orient = (p, q, r) => (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]);
84
+ const onSegment = (p, q, r) => q[0] >= Math.min(p[0], r[0]) - EPS && q[0] <= Math.max(p[0], r[0]) + EPS
85
+ && q[1] >= Math.min(p[1], r[1]) - EPS && q[1] <= Math.max(p[1], r[1]) + EPS;
86
+ const crosses = (p, q, r, s) => {
87
+ const o1 = orient(p, q, r), o2 = orient(p, q, s), o3 = orient(r, s, p), o4 = orient(r, s, q);
88
+ if (Math.abs(o1) <= EPS && onSegment(p, r, q)) return true;
89
+ if (Math.abs(o2) <= EPS && onSegment(p, s, q)) return true;
90
+ if (Math.abs(o3) <= EPS && onSegment(r, p, s)) return true;
91
+ if (Math.abs(o4) <= EPS && onSegment(r, q, s)) return true;
92
+ return (o1 > 0) !== (o2 > 0) && (o3 > 0) !== (o4 > 0);
93
+ };
94
+ const corners = [[rect[0], rect[1]], [rect[2], rect[1]], [rect[2], rect[3]], [rect[0], rect[3]]];
95
+ for (let i = 0; i < 4; i++) if (crosses(a, b, corners[i], corners[(i + 1) % 4])) return true;
96
+ return false;
97
+ }
98
+
99
+ /** Tekla-style hit for a projected solid footprint: window encloses it; crossing touches its convex hull. */
100
+ export function projectedFootprintHitsRect2d(points, rect, windowMode) {
101
+ if (!Array.isArray(points) || !points.length) return false;
102
+ const inside = (p) => p[0] >= rect[0] && p[0] <= rect[2] && p[1] >= rect[1] && p[1] <= rect[3];
103
+ if (windowMode) return points.every(inside);
104
+ const unique = [...new Map(points.filter((p) => Array.isArray(p) && Number.isFinite(p[0]) && Number.isFinite(p[1]))
105
+ .map((p) => [`${p[0]},${p[1]}`, [p[0], p[1]]])).values()].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
106
+ if (!unique.length) return false;
107
+ if (unique.some(inside)) return true;
108
+ const cross = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
109
+ const half = (pts) => { const out = []; for (const p of pts) { while (out.length >= 2 && cross(out[out.length - 2], out[out.length - 1], p) <= 0) out.pop(); out.push(p); } return out; };
110
+ const hull = unique.length <= 2 ? unique : [...half(unique).slice(0, -1), ...half([...unique].reverse()).slice(0, -1)];
111
+ if (hull.length === 1) return false;
112
+ if (hull.length === 2) return segmentHitsRect2d(hull[0], hull[1], rect, false);
113
+ for (let i = 0; i < hull.length; i++) if (segmentHitsRect2d(hull[i], hull[(i + 1) % hull.length], rect, false)) return true;
114
+ // No hull edge crossed the rectangle, so the only remaining overlap is the rectangle lying wholly inside the hull.
115
+ const corner = [rect[0], rect[1]];
116
+ let sign = 0;
117
+ for (let i = 0; i < hull.length; i++) {
118
+ const side = cross(hull[i], hull[(i + 1) % hull.length], corner);
119
+ if (Math.abs(side) <= 1e-9) continue;
120
+ const next = side > 0 ? 1 : -1;
121
+ if (sign && next !== sign) return false;
122
+ sign = next;
123
+ }
124
+ return true;
125
+ }
126
+
17
127
  const kOf = (ptPerFt) => FT_TO_MM / (ptPerFt > 0 ? ptPerFt : 1);
18
128
 
19
129
  const nz = (n) => n + 0; // normalize -0 → 0 (negating 0 yields -0, which surprises equality checks)