@kruschdev/pascal-mep-kernel 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2486 @@
1
+ import {
2
+ segmentIntersectsOrientedPrismY2,
3
+ polylineLengthM2,
4
+ polylineHorizontalLengthM2,
5
+ countPathBendDegrees2,
6
+ countPathElbows2,
7
+ round22,
8
+ round32,
9
+ round42
10
+ } from "./chunk-jfzqztgh.js";
11
+ import {
12
+ countPathOpeningPrismHits2,
13
+ findNearestWallToPoint2
14
+ } from "./chunk-2e23cyn0.js";
15
+
16
+ // src/router/cavity-graph.ts
17
+ var DEFAULT_ROOF_CLEARANCE_M = 0.14;
18
+ var DEFAULT_HALF_Y = 0.02;
19
+ var DEFAULT_HALF_XZ = 0.02;
20
+ var DEFAULT_PLENUM_GRID_STEP_M = 1.5;
21
+ var DEFAULT_SUB_FLOOR_ELEVATION_M = -0.35;
22
+ var WALL_JUNCTION_SNAP_M = 0.25;
23
+ var WALL_VERTEX_SHARE_EPS_M = 0.1;
24
+ var WALL_STATION_DEDUPE_M = 0.04;
25
+ var JAMB_OFFSET_M = 0.08;
26
+ var JAMB_EDGE_CLAMP_M = 0.03;
27
+ var UNDER_SILL_Y = 0.25;
28
+ var MID_WALL_Y = 1.15;
29
+ var TOP_PLATE_MARGIN_M = 0.06;
30
+ var RISER_MIN_Y = 0.02;
31
+ var RISER_TOP_MARGIN_M = 0.04;
32
+ var WALL_BANDS = ["under-sill", "mid-wall", "top-plate"];
33
+ var COST_WALL_HORIZONTAL = 1;
34
+ var COST_WALL_VERTICAL = 1.1;
35
+ var COST_OVERHEAD_PLENUM = 1.05;
36
+ var COST_ATTIC = 1;
37
+ var COST_SUB_FLOOR = 1.15;
38
+ var COST_LAYER_TRANSITION = 1.2;
39
+ var FOOTPRINT_STRICT_WALL_TOL_M = 0.02;
40
+ var MAX_TOTAL_VERTICES_TARGET = 580;
41
+ var MAX_STATIONS_PER_WALL = 24;
42
+ var floor3 = (n) => Math.floor((n + 0.000000001) * 1000) / 1000;
43
+ function clamp(v, lo, hi) {
44
+ return v < lo ? lo : v > hi ? hi : v;
45
+ }
46
+ function dist3(a, b) {
47
+ return Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]);
48
+ }
49
+ function distXZ(a, b) {
50
+ return Math.hypot(b[0] - a[0], b[2] - a[2]);
51
+ }
52
+ function segmentIntersectsAnyOpening(a, b, prisms, pad) {
53
+ for (let i = 0;i < prisms.length; i++) {
54
+ if (segmentIntersectsOrientedPrismY2(a, b, prisms[i], pad)) {
55
+ return true;
56
+ }
57
+ }
58
+ return false;
59
+ }
60
+ function pointIntersectsAnyOpening(x, y, z, prisms, pad) {
61
+ const pt = [x, y, z];
62
+ return segmentIntersectsAnyOpening(pt, pt, prisms, pad);
63
+ }
64
+ function deduplicateSortedNumbers(values, eps, minVal, maxVal) {
65
+ if (values.length === 0)
66
+ return [];
67
+ values.sort((a, b) => a - b);
68
+ const out = [];
69
+ for (let i = 0;i < values.length; i++) {
70
+ const v = clamp(values[i], minVal, maxVal);
71
+ if (out.length === 0) {
72
+ out.push(v);
73
+ } else if (v - out[out.length - 1] > eps) {
74
+ out.push(v);
75
+ } else if (Math.abs(v - maxVal) <= 0.000001) {
76
+ out[out.length - 1] = maxVal;
77
+ }
78
+ }
79
+ if (out.length > 0 && Math.abs(out[0] - minVal) <= eps) {
80
+ out[0] = minVal;
81
+ }
82
+ if (out.length > 0 && Math.abs(out[out.length - 1] - maxVal) <= eps) {
83
+ out[out.length - 1] = maxVal;
84
+ }
85
+ return out;
86
+ }
87
+ function computeWallSplitParameters(walls, halfXZ, subdivStepM) {
88
+ const splits = walls.map((w) => [0, w.lengthM]);
89
+ for (let i = 0;i < walls.length; i++) {
90
+ const a = walls[i];
91
+ for (let j = i + 1;j < walls.length; j++) {
92
+ const b = walls[j];
93
+ const denom = a.ux * b.uz - a.uz * b.ux;
94
+ if (Math.abs(denom) > 0.0001) {
95
+ const rx = b.start[0] - a.start[0];
96
+ const rz = b.start[1] - a.start[1];
97
+ const ta = (rx * b.uz - rz * b.ux) / denom;
98
+ const tb = (rx * a.uz - rz * a.ux) / denom;
99
+ if (ta >= -WALL_JUNCTION_SNAP_M && ta <= a.lengthM + WALL_JUNCTION_SNAP_M && tb >= -WALL_JUNCTION_SNAP_M && tb <= b.lengthM + WALL_JUNCTION_SNAP_M) {
100
+ splits[i].push(clamp(ta, 0, a.lengthM));
101
+ splits[j].push(clamp(tb, 0, b.lengthM));
102
+ }
103
+ }
104
+ for (const ep of [a.start, a.end]) {
105
+ const tb = (ep[0] - b.start[0]) * b.ux + (ep[1] - b.start[1]) * b.uz;
106
+ if (tb >= -WALL_JUNCTION_SNAP_M && tb <= b.lengthM + WALL_JUNCTION_SNAP_M) {
107
+ const clampedTb = clamp(tb, 0, b.lengthM);
108
+ const px = b.start[0] + b.ux * clampedTb;
109
+ const pz = b.start[1] + b.uz * clampedTb;
110
+ if (Math.hypot(ep[0] - px, ep[1] - pz) <= WALL_JUNCTION_SNAP_M) {
111
+ splits[j].push(clampedTb);
112
+ }
113
+ }
114
+ }
115
+ for (const ep of [b.start, b.end]) {
116
+ const ta = (ep[0] - a.start[0]) * a.ux + (ep[1] - a.start[1]) * a.uz;
117
+ if (ta >= -WALL_JUNCTION_SNAP_M && ta <= a.lengthM + WALL_JUNCTION_SNAP_M) {
118
+ const clampedTa = clamp(ta, 0, a.lengthM);
119
+ const px = a.start[0] + a.ux * clampedTa;
120
+ const pz = a.start[1] + a.uz * clampedTa;
121
+ if (Math.hypot(ep[0] - px, ep[1] - pz) <= WALL_JUNCTION_SNAP_M) {
122
+ splits[i].push(clampedTa);
123
+ }
124
+ }
125
+ }
126
+ }
127
+ }
128
+ const result = [];
129
+ for (let i = 0;i < walls.length; i++) {
130
+ const w = walls[i];
131
+ const ts = splits[i];
132
+ const minClamp = Math.min(JAMB_EDGE_CLAMP_M, w.lengthM * 0.5);
133
+ const maxClamp = Math.max(w.lengthM - JAMB_EDGE_CLAMP_M, w.lengthM * 0.5);
134
+ for (const op of w.openings) {
135
+ ts.push(clamp(op.startU - JAMB_OFFSET_M, minClamp, maxClamp));
136
+ ts.push(clamp(op.endU + JAMB_OFFSET_M, minClamp, maxClamp));
137
+ if (halfXZ > JAMB_OFFSET_M) {
138
+ const wideOff = halfXZ + 0.02;
139
+ ts.push(clamp(op.startU - wideOff, minClamp, maxClamp));
140
+ ts.push(clamp(op.endU + wideOff, minClamp, maxClamp));
141
+ }
142
+ }
143
+ const baseSorted = deduplicateSortedNumbers(ts, WALL_STATION_DEDUPE_M, 0, w.lengthM);
144
+ const withSubdiv = [...baseSorted];
145
+ const maxStep = Math.max(2, subdivStepM);
146
+ for (let k = 0;k < baseSorted.length - 1; k++) {
147
+ const t0 = baseSorted[k];
148
+ const t1 = baseSorted[k + 1];
149
+ const span = t1 - t0;
150
+ if (span <= maxStep * 1.15)
151
+ continue;
152
+ const mid = (t0 + t1) * 0.5;
153
+ const insideOpening = w.openings.some((op) => mid > op.startU - 0.02 && mid < op.endU + 0.02);
154
+ if (insideOpening)
155
+ continue;
156
+ const pieces = Math.min(8, Math.ceil(span / maxStep));
157
+ for (let p = 1;p < pieces; p++) {
158
+ withSubdiv.push(t0 + span * p / pieces);
159
+ }
160
+ }
161
+ let finalTs = deduplicateSortedNumbers(withSubdiv, WALL_STATION_DEDUPE_M, 0, w.lengthM);
162
+ if (finalTs.length > MAX_STATIONS_PER_WALL) {
163
+ finalTs = baseSorted.length <= MAX_STATIONS_PER_WALL ? baseSorted : baseSorted.slice(0, MAX_STATIONS_PER_WALL);
164
+ if (finalTs[finalTs.length - 1] !== w.lengthM) {
165
+ finalTs[finalTs.length - 1] = w.lengthM;
166
+ }
167
+ }
168
+ result.push(finalTs);
169
+ }
170
+ return result;
171
+ }
172
+ function adaptGridStep(spanX, spanZ, baseStep, maxGridCells) {
173
+ let step = Math.max(0.25, baseStep);
174
+ const safeSpanX = Math.max(0.25, spanX);
175
+ const safeSpanZ = Math.max(0.25, spanZ);
176
+ const countCells = (s) => Math.max(1, Math.floor(safeSpanX / s)) * Math.max(1, Math.floor(safeSpanZ / s));
177
+ if (countCells(step) <= maxGridCells)
178
+ return step;
179
+ const area = safeSpanX * safeSpanZ;
180
+ step = Math.max(step, Math.sqrt(area / Math.max(1, maxGridCells)));
181
+ while (countCells(step) > maxGridCells) {
182
+ step *= 1.1;
183
+ }
184
+ return round32(step);
185
+ }
186
+ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
187
+ const roofClearanceM = typeof opts.roofClearanceM === "number" && Number.isFinite(opts.roofClearanceM) && opts.roofClearanceM >= 0 ? opts.roofClearanceM : DEFAULT_ROOF_CLEARANCE_M;
188
+ const halfY = typeof opts.halfY === "number" && Number.isFinite(opts.halfY) && opts.halfY >= 0 ? opts.halfY : DEFAULT_HALF_Y;
189
+ const halfXZ = typeof opts.halfXZ === "number" && Number.isFinite(opts.halfXZ) && opts.halfXZ >= 0 ? opts.halfXZ : DEFAULT_HALF_XZ;
190
+ const requestedGridStepM = typeof opts.plenumGridStepM === "number" && Number.isFinite(opts.plenumGridStepM) && opts.plenumGridStepM > 0.1 ? opts.plenumGridStepM : DEFAULT_PLENUM_GRID_STEP_M;
191
+ const includeSubFloorLayer = opts.includeSubFloorLayer !== false;
192
+ const subFloorBand = opts.subFloorBand === "crawlspace" ? "crawlspace" : "under-slab";
193
+ const subFloorY = includeSubFloorLayer ? round32(typeof opts.subFloorElevationM === "number" && Number.isFinite(opts.subFloorElevationM) ? opts.subFloorElevationM : DEFAULT_SUB_FLOOR_ELEVATION_M) : null;
194
+ const levelH = anatomy.getLevelHeightM(levelId);
195
+ const walls = [...anatomy.getWalls(levelId)].sort((a, b) => a.id.localeCompare(b.id));
196
+ const openingPrisms = anatomy.getOpeningPrisms(levelId);
197
+ const roofShell = anatomy.getRoofShell(levelId);
198
+ const footprint = anatomy.getFootprint(levelId);
199
+ const flatSoffitMarginM = typeof opts.flatSoffitMarginM === "number" && Number.isFinite(opts.flatSoffitMarginM) && opts.flatSoffitMarginM >= 0 ? opts.flatSoffitMarginM : levelH >= 2.6 ? 0.16 : 0.08;
200
+ let ceilingPlenumY = floor3(levelH - flatSoffitMarginM);
201
+ if (roofShell.hasRoofAbove && (roofShell.isFlatRoof || ceilingPlenumY + halfY + roofClearanceM > roofShell.maxRidgeY + 0.000001)) {
202
+ ceilingPlenumY = floor3(Math.min(ceilingPlenumY, roofShell.maxRidgeY - roofClearanceM - halfY));
203
+ }
204
+ let atticY = null;
205
+ if (roofShell.hasRoofAbove && !roofShell.isFlatRoof) {
206
+ const desiredAtticY = typeof opts.atticElevationM === "number" && Number.isFinite(opts.atticElevationM) ? opts.atticElevationM : levelH + 0.35;
207
+ const maxAllowedAtticY = roofShell.maxRidgeY - roofClearanceM - halfY;
208
+ const candidateAtticY = Math.min(desiredAtticY, maxAllowedAtticY);
209
+ if (candidateAtticY > levelH + 0.05) {
210
+ atticY = floor3(candidateAtticY);
211
+ }
212
+ }
213
+ const openingPad = [halfXZ, halfY, halfXZ];
214
+ const fpPointOpts = {
215
+ precedence: "room-first",
216
+ wallToleranceM: FOOTPRINT_STRICT_WALL_TOL_M,
217
+ outdoorPolygons: opts.outdoorPolygons,
218
+ interiorPolygons: opts.interiorPolygons
219
+ };
220
+ const fpStrictPointOpts = {
221
+ precedence: "room-first",
222
+ wallToleranceM: 0,
223
+ outdoorPolygons: opts.outdoorPolygons,
224
+ interiorPolygons: opts.interiorPolygons
225
+ };
226
+ const baseSegmentStepM = 0.35;
227
+ const fpSegmentOpts = {
228
+ precedence: "room-first",
229
+ wallToleranceM: FOOTPRINT_STRICT_WALL_TOL_M,
230
+ outdoorPolygons: opts.outdoorPolygons,
231
+ interiorPolygons: opts.interiorPolygons,
232
+ stepM: baseSegmentStepM
233
+ };
234
+ const singleSegmentRoof = roofShell.hasRoofAbove && roofShell.segments.length === 1;
235
+ const roofTopOffset = halfY + roofClearanceM;
236
+ const isRoofPointClear = (x, y, z) => {
237
+ if (!roofShell.hasRoofAbove)
238
+ return true;
239
+ return y + roofTopOffset <= roofShell.roofEnvelopeY(x, z) + 0.000001;
240
+ };
241
+ const isRoofSegmentClear = (a, b) => {
242
+ if (!roofShell.hasRoofAbove)
243
+ return true;
244
+ if (roofShell.isFlatRoof && roofShell.segments.length === 0) {
245
+ return a[1] + roofTopOffset <= roofShell.roofEnvelopeY(a[0], a[2]) + 0.000001 && b[1] + roofTopOffset <= roofShell.roofEnvelopeY(b[0], b[2]) + 0.000001;
246
+ }
247
+ if (singleSegmentRoof) {
248
+ const syA = roofShell.roofSurfaceY(a[0], a[2]);
249
+ const syB = roofShell.roofSurfaceY(b[0], b[2]);
250
+ if (syA !== null && syB !== null) {
251
+ return a[1] + roofTopOffset <= syA + 0.000001 && b[1] + roofTopOffset <= syB + 0.000001;
252
+ }
253
+ }
254
+ return roofShell.isPathClearOfRoof([a, b], halfY, roofClearanceM);
255
+ };
256
+ const vertices = [];
257
+ const adjacency = [];
258
+ const edgeKeys = new Set;
259
+ const bandsPresent = new Set;
260
+ const wallRiserPiers = new Map;
261
+ let minBaseWeight = 1;
262
+ const wallBandVertexIds = {
263
+ "under-sill": [],
264
+ "mid-wall": [],
265
+ "top-plate": [],
266
+ "overhead-plenum": [],
267
+ attic: [],
268
+ "under-slab": [],
269
+ crawlspace: []
270
+ };
271
+ const addVertex = (v) => {
272
+ const id = vertices.length;
273
+ vertices.push({ id, ...v });
274
+ adjacency.push([]);
275
+ bandsPresent.add(v.band);
276
+ return id;
277
+ };
278
+ const addUndirectedEdge = (u, v, params) => {
279
+ if (u === v)
280
+ return false;
281
+ const key = u < v ? `${u}:${v}` : `${v}:${u}`;
282
+ if (edgeKeys.has(key))
283
+ return false;
284
+ const va = vertices[u];
285
+ const vb = vertices[v];
286
+ const lengthM = round32(dist3(va.pos, vb.pos));
287
+ const horizontalLengthM = round32(distXZ(va.pos, vb.pos));
288
+ if (lengthM < 0.00001)
289
+ return false;
290
+ edgeKeys.add(key);
291
+ if (Number.isFinite(params.baseCostWeight) && params.baseCostWeight > 0 && params.baseCostWeight < minBaseWeight) {
292
+ minBaseWeight = params.baseCostWeight;
293
+ }
294
+ const edgeUV = {
295
+ to: v,
296
+ lengthM,
297
+ horizontalLengthM,
298
+ band: params.bandOverride ?? vb.band,
299
+ isWallEdge: params.isWallEdge,
300
+ isVerticalTransition: params.isVerticalTransition,
301
+ ...params.wallId !== undefined ? { wallId: params.wallId } : {},
302
+ baseCostWeight: params.baseCostWeight
303
+ };
304
+ const edgeVU = {
305
+ to: u,
306
+ lengthM,
307
+ horizontalLengthM,
308
+ band: params.bandOverride ?? va.band,
309
+ isWallEdge: params.isWallEdge,
310
+ isVerticalTransition: params.isVerticalTransition,
311
+ ...params.wallId !== undefined ? { wallId: params.wallId } : {},
312
+ baseCostWeight: params.baseCostWeight
313
+ };
314
+ adjacency[u].push(edgeUV);
315
+ adjacency[v].push(edgeVU);
316
+ return true;
317
+ };
318
+ const boundsSpanX = footprint.bounds ? footprint.bounds.maxX - footprint.bounds.minX : 0;
319
+ const boundsSpanZ = footprint.bounds ? footprint.bounds.maxZ - footprint.bounds.minZ : 0;
320
+ const initialWallSubdivStep = Math.max(2, requestedGridStepM, Math.max(boundsSpanX, boundsSpanZ) / 10);
321
+ const wallSplitParams = computeWallSplitParameters(walls, halfXZ, initialWallSubdivStep);
322
+ const wallStations = [];
323
+ const findOrCreateWallVertex = (x, y, z, band, wallId, wallT, isRiserPier, maxClearY) => {
324
+ const existingIds = wallBandVertexIds[band];
325
+ let bestId = -1;
326
+ let bestDist = WALL_VERTEX_SHARE_EPS_M + 0.000001;
327
+ for (let i = 0;i < existingIds.length; i++) {
328
+ const id = existingIds[i];
329
+ const ev = vertices[id];
330
+ if (Math.abs(ev.pos[1] - y) > 0.08)
331
+ continue;
332
+ const d = Math.hypot(ev.pos[0] - x, ev.pos[2] - z);
333
+ if (d < bestDist) {
334
+ bestDist = d;
335
+ bestId = id;
336
+ }
337
+ }
338
+ if (bestId !== -1) {
339
+ return bestId;
340
+ }
341
+ const id = addVertex({
342
+ pos: [x, y, z],
343
+ band,
344
+ wallId,
345
+ wallT: round32(wallT),
346
+ isRiserPier,
347
+ maxClearY: floor3(maxClearY)
348
+ });
349
+ existingIds.push(id);
350
+ return id;
351
+ };
352
+ for (let wi = 0;wi < walls.length; wi++) {
353
+ const wall = walls[wi];
354
+ const ts = wallSplitParams[wi];
355
+ const piers = [];
356
+ const stations = [];
357
+ for (let si = 0;si < ts.length; si++) {
358
+ const t = ts[si];
359
+ const x = round32(wall.start[0] + wall.ux * t);
360
+ const z = round32(wall.start[1] + wall.uz * t);
361
+ const wallTopY = Math.min(levelH, wall.heightM);
362
+ const roofY = roofShell.hasRoofAbove ? roofShell.roofEnvelopeY(x, z) : Number.POSITIVE_INFINITY;
363
+ const roofClearY = roofShell.hasRoofAbove ? roofY - roofClearanceM - halfY : Number.POSITIVE_INFINITY;
364
+ const topPlateY = floor3(Math.min(wallTopY - TOP_PLATE_MARGIN_M, roofClearY));
365
+ const pierMaxY = floor3(Math.min(wallTopY - RISER_TOP_MARGIN_M, roofShell.hasRoofAbove ? roofY - Math.max(RISER_TOP_MARGIN_M, roofClearanceM + halfY) : Number.POSITIVE_INFINITY));
366
+ const isRiserPier = pierMaxY > RISER_MIN_Y + 0.05 && !segmentIntersectsAnyOpening([x, RISER_MIN_Y, z], [x, pierMaxY, z], openingPrisms, openingPad);
367
+ if (isRiserPier) {
368
+ piers.push({
369
+ wallId: wall.id,
370
+ t: round32(t),
371
+ x,
372
+ z,
373
+ minSafeY: RISER_MIN_Y,
374
+ maxSafeY: pierMaxY
375
+ });
376
+ }
377
+ const bandVertexIds = {};
378
+ const maxClearY = Number.isFinite(roofClearY) ? roofClearY : wallTopY;
379
+ if (UNDER_SILL_Y < topPlateY - 0.05 && !pointIntersectsAnyOpening(x, UNDER_SILL_Y, z, openingPrisms, openingPad) && isRoofPointClear(x, UNDER_SILL_Y, z)) {
380
+ bandVertexIds["under-sill"] = findOrCreateWallVertex(x, UNDER_SILL_Y, z, "under-sill", wall.id, t, isRiserPier, maxClearY);
381
+ }
382
+ if (MID_WALL_Y < topPlateY - 0.05 && !pointIntersectsAnyOpening(x, MID_WALL_Y, z, openingPrisms, openingPad) && isRoofPointClear(x, MID_WALL_Y, z)) {
383
+ bandVertexIds["mid-wall"] = findOrCreateWallVertex(x, MID_WALL_Y, z, "mid-wall", wall.id, t, isRiserPier, maxClearY);
384
+ }
385
+ if (topPlateY > 0.1 && !pointIntersectsAnyOpening(x, topPlateY, z, openingPrisms, openingPad) && isRoofPointClear(x, topPlateY, z)) {
386
+ bandVertexIds["top-plate"] = findOrCreateWallVertex(x, topPlateY, z, "top-plate", wall.id, t, isRiserPier, maxClearY);
387
+ }
388
+ if (isRiserPier) {
389
+ const verticalIds = [];
390
+ for (const b of WALL_BANDS) {
391
+ const vid = bandVertexIds[b];
392
+ if (vid !== undefined)
393
+ verticalIds.push(vid);
394
+ }
395
+ verticalIds.sort((a, b) => vertices[a].pos[1] - vertices[b].pos[1]);
396
+ for (let k = 0;k < verticalIds.length - 1; k++) {
397
+ const vLow = verticalIds[k];
398
+ const vHigh = verticalIds[k + 1];
399
+ const pLow = vertices[vLow].pos;
400
+ const pHigh = vertices[vHigh].pos;
401
+ if (!segmentIntersectsAnyOpening(pLow, pHigh, openingPrisms, openingPad) && isRoofSegmentClear(pLow, pHigh)) {
402
+ addUndirectedEdge(vLow, vHigh, {
403
+ isWallEdge: true,
404
+ isVerticalTransition: true,
405
+ wallId: wall.id,
406
+ baseCostWeight: COST_WALL_VERTICAL
407
+ });
408
+ }
409
+ }
410
+ }
411
+ stations.push({
412
+ t,
413
+ x,
414
+ z,
415
+ topPlateY,
416
+ pierMaxY,
417
+ isRiserPier,
418
+ bandVertexIds
419
+ });
420
+ }
421
+ wallRiserPiers.set(wall.id, piers);
422
+ wallStations.push(stations);
423
+ for (const band of WALL_BANDS) {
424
+ let prevVid = null;
425
+ for (let si = 0;si < stations.length; si++) {
426
+ const curVid = stations[si].bandVertexIds[band] ?? null;
427
+ if (curVid === null) {
428
+ prevVid = null;
429
+ continue;
430
+ }
431
+ if (prevVid !== null && prevVid !== curVid) {
432
+ const pa = vertices[prevVid].pos;
433
+ const pb = vertices[curVid].pos;
434
+ if (!segmentIntersectsAnyOpening(pa, pb, openingPrisms, openingPad) && isRoofSegmentClear(pa, pb)) {
435
+ addUndirectedEdge(prevVid, curVid, {
436
+ isWallEdge: true,
437
+ isVerticalTransition: false,
438
+ wallId: wall.id,
439
+ baseCostWeight: COST_WALL_HORIZONTAL,
440
+ bandOverride: band
441
+ });
442
+ }
443
+ }
444
+ prevVid = curVid;
445
+ }
446
+ }
447
+ }
448
+ for (const band of WALL_BANDS) {
449
+ const ids = wallBandVertexIds[band];
450
+ for (let i = 0;i < ids.length; i++) {
451
+ const uid = ids[i];
452
+ const vu = vertices[uid];
453
+ for (let j = i + 1;j < ids.length; j++) {
454
+ const vid = ids[j];
455
+ const vv = vertices[vid];
456
+ if (vu.wallId === vv.wallId)
457
+ continue;
458
+ if (Math.abs(vu.pos[1] - vv.pos[1]) > 0.08)
459
+ continue;
460
+ const d = Math.hypot(vu.pos[0] - vv.pos[0], vu.pos[2] - vv.pos[2]);
461
+ if (d > WALL_VERTEX_SHARE_EPS_M && d <= WALL_JUNCTION_SNAP_M) {
462
+ if (!segmentIntersectsAnyOpening(vu.pos, vv.pos, openingPrisms, openingPad) && isRoofSegmentClear(vu.pos, vv.pos)) {
463
+ addUndirectedEdge(uid, vid, {
464
+ isWallEdge: true,
465
+ isVerticalTransition: false,
466
+ baseCostWeight: COST_WALL_HORIZONTAL,
467
+ bandOverride: band
468
+ });
469
+ }
470
+ }
471
+ }
472
+ }
473
+ }
474
+ const bounds = footprint.bounds;
475
+ const num2DLayers = 1 + (atticY !== null ? 1 : 0) + (subFloorY !== null ? 1 : 0);
476
+ const remainingVertexBudget = Math.max(90, MAX_TOTAL_VERTICES_TARGET - vertices.length);
477
+ const maxVertsPerLayer = Math.max(30, Math.floor(remainingVertexBudget / num2DLayers));
478
+ const maxGridCellsPerLayer = Math.max(20, Math.floor(maxVertsPerLayer * 0.78));
479
+ const effectiveGridStepM = bounds ? adaptGridStep(bounds.maxX - bounds.minX, bounds.maxZ - bounds.minZ, requestedGridStepM, maxGridCellsPerLayer) : requestedGridStepM;
480
+ const layerSegmentOpts = {
481
+ ...fpSegmentOpts,
482
+ stepM: Math.max(0.35, Math.min(0.65, effectiveGridStepM * 0.25))
483
+ };
484
+ const fpCoordKey = (x, z) => `${Math.round(x * 1000)}:${Math.round(z * 1000)}`;
485
+ const fpStrictPointCache = new Map;
486
+ const isFootprintStrictPointInside = (x, z) => {
487
+ const k = fpCoordKey(x, z);
488
+ const cached = fpStrictPointCache.get(k);
489
+ if (cached !== undefined)
490
+ return cached;
491
+ const res = footprint.isPointInside(x, z, fpStrictPointOpts);
492
+ fpStrictPointCache.set(k, res);
493
+ return res;
494
+ };
495
+ const fpLayerSegCache = new Map;
496
+ const isFootprintLayerSegInside = (a, b) => {
497
+ const ka = fpCoordKey(a[0], a[2]);
498
+ const kb = fpCoordKey(b[0], b[2]);
499
+ const k = ka < kb ? `${ka}|${kb}` : `${kb}|${ka}`;
500
+ const cached = fpLayerSegCache.get(k);
501
+ if (cached !== undefined)
502
+ return cached;
503
+ const res = footprint.isSegmentInside(a, b, layerSegmentOpts);
504
+ fpLayerSegCache.set(k, res);
505
+ return res;
506
+ };
507
+ const sortedRooms = [...footprint.roomPolygons].sort((a, b) => a.id.localeCompare(b.id));
508
+ const seedDedupeRadius = Math.max(0.6, effectiveGridStepM * 0.65);
509
+ const pierInteriorSeeds = [];
510
+ const pushPierSeed = (x, z) => {
511
+ for (let i = 0;i < pierInteriorSeeds.length; i++) {
512
+ const prev = pierInteriorSeeds[i];
513
+ if (Math.hypot(prev.x - x, prev.z - z) <= seedDedupeRadius)
514
+ return;
515
+ }
516
+ pierInteriorSeeds.push({ x, z });
517
+ };
518
+ for (let wi = 0;wi < walls.length; wi++) {
519
+ const wall = walls[wi];
520
+ const piers = wallRiserPiers.get(wall.id) ?? [];
521
+ const inset = Math.max(0.12, wall.thicknessM / 2 + 0.1);
522
+ for (let pi = 0;pi < piers.length; pi++) {
523
+ const pier = piers[pi];
524
+ const posX = round32(pier.x + wall.nx * inset);
525
+ const posZ = round32(pier.z + wall.nz * inset);
526
+ const negX = round32(pier.x - wall.nx * inset);
527
+ const negZ = round32(pier.z - wall.nz * inset);
528
+ const posIn = isFootprintStrictPointInside(posX, posZ);
529
+ const negIn = isFootprintStrictPointInside(negX, negZ);
530
+ if (posIn && negIn) {
531
+ if (isFootprintStrictPointInside(pier.x, pier.z)) {
532
+ pushPierSeed(pier.x, pier.z);
533
+ } else {
534
+ pushPierSeed(posX, posZ);
535
+ }
536
+ } else if (posIn) {
537
+ pushPierSeed(posX, posZ);
538
+ } else if (negIn) {
539
+ pushPierSeed(negX, negZ);
540
+ } else if (footprint.isPointInside(pier.x, pier.z, fpPointOpts)) {
541
+ pushPierSeed(pier.x, pier.z);
542
+ }
543
+ }
544
+ }
545
+ const gridSpanX = bounds ? bounds.maxX - bounds.minX : 0;
546
+ const gridSpanZ = bounds ? bounds.maxZ - bounds.minZ : 0;
547
+ const gridCols = bounds ? Math.max(1, Math.floor(gridSpanX / effectiveGridStepM)) : 0;
548
+ const gridRows = bounds ? Math.max(1, Math.floor(gridSpanZ / effectiveGridStepM)) : 0;
549
+ const gridStepX = gridCols > 0 ? gridSpanX / gridCols : 0;
550
+ const gridStepZ = gridRows > 0 ? gridSpanZ / gridRows : 0;
551
+ const gridX = [];
552
+ const gridZ = [];
553
+ const gridInside = [];
554
+ const gridRoofEnvY = [];
555
+ const gridRoofOnSingleSeg = [];
556
+ const gridEdgeEastInside = [];
557
+ const gridEdgeSouthInside = [];
558
+ if (bounds && gridCols > 0 && gridRows > 0) {
559
+ for (let ix = 0;ix < gridCols; ix++) {
560
+ gridX.push(round32(bounds.minX + (ix + 0.5) * gridStepX));
561
+ }
562
+ for (let iz = 0;iz < gridRows; iz++) {
563
+ gridZ.push(round32(bounds.minZ + (iz + 0.5) * gridStepZ));
564
+ }
565
+ for (let ix = 0;ix < gridCols; ix++) {
566
+ const x = gridX[ix];
567
+ const insideCol = new Uint8Array(gridRows);
568
+ const roofCol = new Float64Array(gridRows);
569
+ const singleSegCol = new Uint8Array(gridRows);
570
+ for (let iz = 0;iz < gridRows; iz++) {
571
+ const z = gridZ[iz];
572
+ const isIn = isFootprintStrictPointInside(x, z);
573
+ insideCol[iz] = isIn ? 1 : 0;
574
+ if (isIn && roofShell.hasRoofAbove) {
575
+ if (singleSegmentRoof) {
576
+ const sy = roofShell.roofSurfaceY(x, z);
577
+ if (sy !== null) {
578
+ roofCol[iz] = sy;
579
+ singleSegCol[iz] = 1;
580
+ } else {
581
+ roofCol[iz] = roofShell.roofEnvelopeY(x, z);
582
+ }
583
+ } else {
584
+ roofCol[iz] = roofShell.roofEnvelopeY(x, z);
585
+ if (roofShell.isFlatRoof && roofShell.segments.length <= 1)
586
+ singleSegCol[iz] = 1;
587
+ }
588
+ } else {
589
+ roofCol[iz] = Number.POSITIVE_INFINITY;
590
+ }
591
+ }
592
+ gridInside.push(insideCol);
593
+ gridRoofEnvY.push(roofCol);
594
+ gridRoofOnSingleSeg.push(singleSegCol);
595
+ gridEdgeEastInside.push(new Uint8Array(gridRows));
596
+ gridEdgeSouthInside.push(new Uint8Array(gridRows));
597
+ }
598
+ for (let ix = 0;ix < gridCols; ix++) {
599
+ const x = gridX[ix];
600
+ for (let iz = 0;iz < gridRows; iz++) {
601
+ if (!gridInside[ix][iz])
602
+ continue;
603
+ const z = gridZ[iz];
604
+ if (ix + 1 < gridCols && gridInside[ix + 1][iz]) {
605
+ if (isFootprintLayerSegInside([x, 0, z], [gridX[ix + 1], 0, z])) {
606
+ gridEdgeEastInside[ix][iz] = 1;
607
+ }
608
+ }
609
+ if (iz + 1 < gridRows && gridInside[ix][iz + 1]) {
610
+ if (isFootprintLayerSegInside([x, 0, z], [x, 0, gridZ[iz + 1]])) {
611
+ gridEdgeSouthInside[ix][iz] = 1;
612
+ }
613
+ }
614
+ }
615
+ }
616
+ }
617
+ const buildHorizontalLayer = (band, layerY, checkRoof, allowDiagonals, baseCostWeight) => {
618
+ const layerIds = [];
619
+ if (!bounds || gridCols === 0 || gridRows === 0)
620
+ return { vertexIds: layerIds };
621
+ const isPointLegal = (x, z) => {
622
+ if (!isFootprintStrictPointInside(x, z))
623
+ return false;
624
+ if (checkRoof && !isRoofPointClear(x, layerY, z))
625
+ return false;
626
+ return true;
627
+ };
628
+ const isEdgeLegal = (a, b) => {
629
+ if (!isFootprintLayerSegInside(a, b))
630
+ return false;
631
+ if (checkRoof && !isRoofSegmentClear(a, b))
632
+ return false;
633
+ return true;
634
+ };
635
+ const gridIds = Array.from({ length: gridCols }, () => new Array(gridRows).fill(-1));
636
+ for (let ix = 0;ix < gridCols; ix++) {
637
+ const x = gridX[ix];
638
+ const insideCol = gridInside[ix];
639
+ const roofCol = gridRoofEnvY[ix];
640
+ for (let iz = 0;iz < gridRows; iz++) {
641
+ if (!insideCol[iz])
642
+ continue;
643
+ const roofY = roofCol[iz];
644
+ if (checkRoof && roofShell.hasRoofAbove && layerY + roofTopOffset > roofY + 0.000001)
645
+ continue;
646
+ const z = gridZ[iz];
647
+ const maxClearY = checkRoof && roofShell.hasRoofAbove ? floor3(roofY - roofTopOffset) : round32(levelH);
648
+ const id = addVertex({
649
+ pos: [x, layerY, z],
650
+ band,
651
+ maxClearY
652
+ });
653
+ gridIds[ix][iz] = id;
654
+ layerIds.push(id);
655
+ }
656
+ }
657
+ for (let ix = 0;ix < gridCols; ix++) {
658
+ for (let iz = 0;iz < gridRows; iz++) {
659
+ const uid = gridIds[ix][iz];
660
+ if (uid === -1)
661
+ continue;
662
+ const pa = vertices[uid].pos;
663
+ const uRoofFast = !checkRoof || !roofShell.hasRoofAbove || gridRoofOnSingleSeg[ix][iz] === 1;
664
+ if (ix + 1 < gridCols && gridEdgeEastInside[ix][iz]) {
665
+ const vid = gridIds[ix + 1][iz];
666
+ if (vid !== -1 && (uRoofFast && gridRoofOnSingleSeg[ix + 1][iz] === 1 || !checkRoof || isRoofSegmentClear(pa, vertices[vid].pos))) {
667
+ addUndirectedEdge(uid, vid, {
668
+ isWallEdge: false,
669
+ isVerticalTransition: false,
670
+ baseCostWeight,
671
+ bandOverride: band
672
+ });
673
+ }
674
+ }
675
+ if (iz + 1 < gridRows && gridEdgeSouthInside[ix][iz]) {
676
+ const vid = gridIds[ix][iz + 1];
677
+ if (vid !== -1 && (uRoofFast && gridRoofOnSingleSeg[ix][iz + 1] === 1 || !checkRoof || isRoofSegmentClear(pa, vertices[vid].pos))) {
678
+ addUndirectedEdge(uid, vid, {
679
+ isWallEdge: false,
680
+ isVerticalTransition: false,
681
+ baseCostWeight,
682
+ bandOverride: band
683
+ });
684
+ }
685
+ }
686
+ if (allowDiagonals && ix + 1 < gridCols) {
687
+ for (const dz of [1, -1]) {
688
+ const nz = iz + dz;
689
+ if (nz < 0 || nz >= gridRows)
690
+ continue;
691
+ const vid = gridIds[ix + 1][nz];
692
+ if (vid === -1)
693
+ continue;
694
+ const pb = vertices[vid].pos;
695
+ if (!isFootprintLayerSegInside(pa, pb))
696
+ continue;
697
+ if (uRoofFast && gridRoofOnSingleSeg[ix + 1][nz] === 1 || !checkRoof || isRoofSegmentClear(pa, pb)) {
698
+ addUndirectedEdge(uid, vid, {
699
+ isWallEdge: false,
700
+ isVerticalTransition: false,
701
+ baseCostWeight,
702
+ bandOverride: band
703
+ });
704
+ }
705
+ }
706
+ }
707
+ }
708
+ }
709
+ const extraSeeds = [];
710
+ if (band === "attic") {
711
+ for (let si = 0;si < roofShell.segments.length; si++) {
712
+ const seg = roofShell.segments[si];
713
+ extraSeeds.push({ x: round32(seg.cx), z: round32(seg.cz) });
714
+ const halfRidge = seg.effWidth * 0.25;
715
+ if (halfRidge >= 0.4) {
716
+ extraSeeds.push({
717
+ x: round32(seg.cx + halfRidge * seg.effCos),
718
+ z: round32(seg.cz - halfRidge * seg.effSin)
719
+ });
720
+ extraSeeds.push({
721
+ x: round32(seg.cx - halfRidge * seg.effCos),
722
+ z: round32(seg.cz + halfRidge * seg.effSin)
723
+ });
724
+ }
725
+ }
726
+ }
727
+ for (let ri = 0;ri < sortedRooms.length; ri++) {
728
+ const room = sortedRooms[ri];
729
+ extraSeeds.push({ x: round32(room.centroid[0]), z: round32(room.centroid[1]) });
730
+ }
731
+ for (let pi = 0;pi < pierInteriorSeeds.length; pi++) {
732
+ extraSeeds.push(pierInteriorSeeds[pi]);
733
+ }
734
+ const dedupeRadiusSq = seedDedupeRadius * seedDedupeRadius;
735
+ const primaryConnectRadius = Math.max(2.6, effectiveGridStepM * 1.85);
736
+ const fallbackConnectRadius = Math.max(4.5, effectiveGridStepM * 2.8);
737
+ const fallbackConnectRadiusSq = fallbackConnectRadius * fallbackConnectRadius;
738
+ const coordKey = (x, z) => `${Math.round(x * 1000)}:${Math.round(z * 1000)}`;
739
+ const layerCoordMap = new Map;
740
+ for (let li = 0;li < layerIds.length; li++) {
741
+ const lid = layerIds[li];
742
+ const lv = vertices[lid];
743
+ layerCoordMap.set(coordKey(lv.pos[0], lv.pos[2]), lid);
744
+ }
745
+ const findOrCreateCornerVertex = (cx, cz, allowCreate) => {
746
+ const key = coordKey(cx, cz);
747
+ const existing = layerCoordMap.get(key);
748
+ if (existing !== undefined)
749
+ return existing;
750
+ if (!allowCreate)
751
+ return -1;
752
+ const cornerMaxClearY = checkRoof && roofShell.hasRoofAbove ? floor3(roofShell.roofEnvelopeY(cx, cz) - roofTopOffset) : round32(levelH);
753
+ const cid = addVertex({
754
+ pos: [cx, layerY, cz],
755
+ band,
756
+ maxClearY: cornerMaxClearY
757
+ });
758
+ layerIds.push(cid);
759
+ layerCoordMap.set(key, cid);
760
+ return cid;
761
+ };
762
+ const maxSeedConnections = allowDiagonals ? 3 : 2;
763
+ for (let si = 0;si < extraSeeds.length; si++) {
764
+ if (layerIds.length >= maxVertsPerLayer)
765
+ break;
766
+ const seed = extraSeeds[si];
767
+ if (!isPointLegal(seed.x, seed.z))
768
+ continue;
769
+ const seedPos = [seed.x, layerY, seed.z];
770
+ let tooClose = false;
771
+ for (let li = 0;li < layerIds.length; li++) {
772
+ const ev = vertices[layerIds[li]];
773
+ const dx = ev.pos[0] - seed.x;
774
+ const dz = ev.pos[2] - seed.z;
775
+ if (dx * dx + dz * dz <= dedupeRadiusSq) {
776
+ if (isEdgeLegal(seedPos, ev.pos)) {
777
+ tooClose = true;
778
+ break;
779
+ }
780
+ }
781
+ }
782
+ if (tooClose)
783
+ continue;
784
+ const maxClearY = checkRoof && roofShell.hasRoofAbove ? floor3(roofShell.roofEnvelopeY(seed.x, seed.z) - roofTopOffset) : round32(levelH);
785
+ const newId = addVertex({
786
+ pos: seedPos,
787
+ band,
788
+ maxClearY
789
+ });
790
+ layerCoordMap.set(coordKey(seed.x, seed.z), newId);
791
+ const candidates = [];
792
+ for (let li = 0;li < layerIds.length; li++) {
793
+ const otherId = layerIds[li];
794
+ const ov = vertices[otherId];
795
+ const dx = ov.pos[0] - seed.x;
796
+ const dz = ov.pos[2] - seed.z;
797
+ const dSq = dx * dx + dz * dz;
798
+ if (dSq <= fallbackConnectRadiusSq && dSq > 0.00000001) {
799
+ candidates.push({ id: otherId, distSq: dSq });
800
+ }
801
+ }
802
+ candidates.sort((a, b) => a.distSq - b.distSq || a.id - b.id);
803
+ const primaryConnectRadiusSq = primaryConnectRadius * primaryConnectRadius;
804
+ let connected = 0;
805
+ for (let ci = 0;ci < candidates.length && connected < maxSeedConnections; ci++) {
806
+ const cand = candidates[ci];
807
+ if (cand.distSq > primaryConnectRadiusSq && connected > 0)
808
+ break;
809
+ const targetPos = vertices[cand.id].pos;
810
+ const isAxisAligned = Math.abs(seed.x - targetPos[0]) < 0.001 || Math.abs(seed.z - targetPos[2]) < 0.001;
811
+ if (allowDiagonals || isAxisAligned) {
812
+ if (isEdgeLegal(seedPos, targetPos)) {
813
+ addUndirectedEdge(newId, cand.id, {
814
+ isWallEdge: false,
815
+ isVerticalTransition: false,
816
+ baseCostWeight,
817
+ bandOverride: band
818
+ });
819
+ connected += 1;
820
+ }
821
+ } else {
822
+ const corners = [
823
+ [seed.x, layerY, targetPos[2]],
824
+ [targetPos[0], layerY, seed.z]
825
+ ];
826
+ for (let ki = 0;ki < corners.length; ki++) {
827
+ const cornerPos = corners[ki];
828
+ if (!isPointLegal(cornerPos[0], cornerPos[2]))
829
+ continue;
830
+ if (!isEdgeLegal(seedPos, cornerPos) || !isEdgeLegal(cornerPos, targetPos))
831
+ continue;
832
+ const cornerId = findOrCreateCornerVertex(cornerPos[0], cornerPos[2], layerIds.length < maxVertsPerLayer || connected === 0);
833
+ if (cornerId === -1)
834
+ continue;
835
+ const e1 = addUndirectedEdge(newId, cornerId, {
836
+ isWallEdge: false,
837
+ isVerticalTransition: false,
838
+ baseCostWeight,
839
+ bandOverride: band
840
+ });
841
+ const e2 = addUndirectedEdge(cornerId, cand.id, {
842
+ isWallEdge: false,
843
+ isVerticalTransition: false,
844
+ baseCostWeight,
845
+ bandOverride: band
846
+ });
847
+ if (e1 || e2) {
848
+ connected += 1;
849
+ break;
850
+ }
851
+ }
852
+ }
853
+ }
854
+ layerIds.push(newId);
855
+ }
856
+ return { vertexIds: layerIds };
857
+ };
858
+ const plenumLayer = buildHorizontalLayer("overhead-plenum", ceilingPlenumY, true, false, COST_OVERHEAD_PLENUM);
859
+ const atticLayer = atticY !== null ? buildHorizontalLayer("attic", atticY, true, true, COST_ATTIC) : { vertexIds: [] };
860
+ const subFloorLayer = subFloorY !== null ? buildHorizontalLayer(subFloorBand, subFloorY, false, false, COST_SUB_FLOOR) : { vertexIds: [] };
861
+ const connectToNearestInLayer = (srcId, targetLayerIds, maxRadiusM, checkRoof, checkOpenings) => {
862
+ if (targetLayerIds.length === 0)
863
+ return false;
864
+ const srcPos = vertices[srcId].pos;
865
+ const maxRadiusSq = maxRadiusM * maxRadiusM;
866
+ const candidates = [];
867
+ for (let i = 0;i < targetLayerIds.length; i++) {
868
+ const tid = targetLayerIds[i];
869
+ const tp = vertices[tid].pos;
870
+ const dx = tp[0] - srcPos[0];
871
+ const dz = tp[2] - srcPos[2];
872
+ const dSq = dx * dx + dz * dz;
873
+ if (dSq <= maxRadiusSq) {
874
+ candidates.push({ id: tid, distSq: dSq });
875
+ }
876
+ }
877
+ candidates.sort((a, b) => a.distSq - b.distSq || a.id - b.id);
878
+ for (let i = 0;i < candidates.length; i++) {
879
+ const cand = candidates[i];
880
+ const tid = cand.id;
881
+ const targetPos = vertices[tid].pos;
882
+ if (cand.distSq > 0.00000001 && !isFootprintLayerSegInside(srcPos, targetPos))
883
+ continue;
884
+ if (checkRoof && !isRoofSegmentClear(srcPos, targetPos))
885
+ continue;
886
+ if (checkOpenings && segmentIntersectsAnyOpening(srcPos, targetPos, openingPrisms, openingPad)) {
887
+ continue;
888
+ }
889
+ addUndirectedEdge(srcId, tid, {
890
+ isWallEdge: false,
891
+ isVerticalTransition: true,
892
+ baseCostWeight: COST_LAYER_TRANSITION
893
+ });
894
+ return true;
895
+ }
896
+ return false;
897
+ };
898
+ const wallToPlenumRadius = Math.max(3, effectiveGridStepM * 2.2);
899
+ const wallToAtticRadius = Math.max(3.6, effectiveGridStepM * 2.5);
900
+ const plenumToAtticRadius = Math.max(2.2, effectiveGridStepM * 1.45);
901
+ const topPlateIds = wallBandVertexIds["top-plate"];
902
+ for (let i = 0;i < topPlateIds.length; i++) {
903
+ const tpId = topPlateIds[i];
904
+ connectToNearestInLayer(tpId, plenumLayer.vertexIds, wallToPlenumRadius, true, true);
905
+ if (atticLayer.vertexIds.length > 0) {
906
+ connectToNearestInLayer(tpId, atticLayer.vertexIds, wallToAtticRadius, true, true);
907
+ }
908
+ }
909
+ for (let i = 0;i < atticLayer.vertexIds.length; i++) {
910
+ const avId = atticLayer.vertexIds[i];
911
+ connectToNearestInLayer(avId, plenumLayer.vertexIds, plenumToAtticRadius, true, false);
912
+ }
913
+ if (subFloorLayer.vertexIds.length > 0) {
914
+ const connectedPierRoots = new Set;
915
+ for (let wi = 0;wi < wallStations.length; wi++) {
916
+ const stations = wallStations[wi];
917
+ for (let si = 0;si < stations.length; si++) {
918
+ const st = stations[si];
919
+ if (!st.isRiserPier)
920
+ continue;
921
+ const rootId = st.bandVertexIds["under-sill"] ?? st.bandVertexIds["mid-wall"] ?? st.bandVertexIds["top-plate"];
922
+ if (rootId === undefined || connectedPierRoots.has(rootId))
923
+ continue;
924
+ connectedPierRoots.add(rootId);
925
+ connectToNearestInLayer(rootId, subFloorLayer.vertexIds, wallToPlenumRadius, false, true);
926
+ }
927
+ }
928
+ }
929
+ return {
930
+ levelId,
931
+ levelHeightM: levelH,
932
+ vertices,
933
+ adjacency,
934
+ wallRiserPiers,
935
+ bandsPresent,
936
+ ceilingPlenumY,
937
+ atticY,
938
+ subFloorY,
939
+ compiledHalfXZ: halfXZ,
940
+ compiledHalfY: halfY,
941
+ compiledRoofClearanceM: roofClearanceM,
942
+ minBaseWeight
943
+ };
944
+ }
945
+ function findLegalWallRiserPier2(graph, wallId, desiredT, fromY, toY) {
946
+ const piers = graph.wallRiserPiers.get(wallId);
947
+ if (!piers || piers.length === 0)
948
+ return null;
949
+ const loY = Math.min(fromY, toY);
950
+ const hiY = Math.max(fromY, toY);
951
+ const effectiveLoY = loY < RISER_MIN_Y ? RISER_MIN_Y : loY;
952
+ let best = null;
953
+ let bestDelta = Number.POSITIVE_INFINITY;
954
+ for (let i = 0;i < piers.length; i++) {
955
+ const pier = piers[i];
956
+ if (pier.minSafeY > effectiveLoY + 0.0001)
957
+ continue;
958
+ if (pier.maxSafeY < hiY - 0.0001)
959
+ continue;
960
+ const delta = Math.abs(pier.t - desiredT);
961
+ if (delta < bestDelta - 0.000001 || Math.abs(delta - bestDelta) <= 0.000001 && best && pier.t < best.t) {
962
+ bestDelta = delta;
963
+ best = pier;
964
+ }
965
+ }
966
+ return best;
967
+ }
968
+ // src/router/shortest-path.ts
969
+ var DEFAULT_ROOF_CLEARANCE_M2 = 0.14;
970
+ var DEFAULT_MIN_SLOPE_IN_PER_FT = 0.25;
971
+ var UPHILL_TOL_M = 0.002;
972
+ var DIR_BUCKETS = 13;
973
+ var CLASH_PENALTY = 5000;
974
+ var OPENING_PENALTY = 2000;
975
+ var ROOF_PENALTY = 2000;
976
+ var OUTDOOR_PENALTY = 2000;
977
+ var PHYSICS_PENALTY = 1000;
978
+ var BEND_COST_PER_DEG = 0.0025;
979
+ var WALL_BANDS2 = new Set([
980
+ "under-sill",
981
+ "mid-wall",
982
+ "top-plate"
983
+ ]);
984
+ var OPEN_CAVITY_BANDS = new Set([
985
+ "attic",
986
+ "crawlspace",
987
+ "overhead-plenum",
988
+ "under-slab"
989
+ ]);
990
+ var autoRunCounter = 1;
991
+
992
+ class BinaryMinHeap {
993
+ items = [];
994
+ get size() {
995
+ return this.items.length;
996
+ }
997
+ push(entry) {
998
+ const items = this.items;
999
+ items.push(entry);
1000
+ let idx = items.length - 1;
1001
+ while (idx > 0) {
1002
+ const parentIdx = idx - 1 >> 1;
1003
+ const parent = items[parentIdx];
1004
+ if (this.compare(entry, parent) >= 0)
1005
+ break;
1006
+ items[idx] = parent;
1007
+ idx = parentIdx;
1008
+ }
1009
+ items[idx] = entry;
1010
+ }
1011
+ pop() {
1012
+ const items = this.items;
1013
+ const n = items.length;
1014
+ if (n === 0)
1015
+ return;
1016
+ const top = items[0];
1017
+ const last = items.pop();
1018
+ if (n > 1) {
1019
+ let idx = 0;
1020
+ const half = n - 1 >> 1;
1021
+ while (idx < half) {
1022
+ let leftIdx = (idx << 1) + 1;
1023
+ const rightIdx = leftIdx + 1;
1024
+ let smallest = items[leftIdx];
1025
+ if (rightIdx < n - 1) {
1026
+ const right = items[rightIdx];
1027
+ if (this.compare(right, smallest) < 0) {
1028
+ leftIdx = rightIdx;
1029
+ smallest = right;
1030
+ }
1031
+ }
1032
+ if (this.compare(last, smallest) <= 0)
1033
+ break;
1034
+ items[idx] = smallest;
1035
+ idx = leftIdx;
1036
+ }
1037
+ items[idx] = last;
1038
+ }
1039
+ return top;
1040
+ }
1041
+ compare(a, b) {
1042
+ if (a.f !== b.f)
1043
+ return a.f - b.f;
1044
+ if (a.g !== b.g)
1045
+ return a.g - b.g;
1046
+ return a.seq - b.seq;
1047
+ }
1048
+ }
1049
+ function sanitizeVec3(v) {
1050
+ const x = typeof v[0] === "number" && Number.isFinite(v[0]) ? v[0] : 0;
1051
+ const y = typeof v[1] === "number" && Number.isFinite(v[1]) ? v[1] : 0;
1052
+ const z = typeof v[2] === "number" && Number.isFinite(v[2]) ? v[2] : 0;
1053
+ return [x, y, z];
1054
+ }
1055
+ function roundVec3(v) {
1056
+ return [round42(v[0]), round42(v[1]), round42(v[2])];
1057
+ }
1058
+ function dist32(a, b) {
1059
+ return Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]);
1060
+ }
1061
+ function distXZ2(a, b) {
1062
+ return Math.hypot(b[0] - a[0], b[2] - a[2]);
1063
+ }
1064
+ function unitDir(a, b) {
1065
+ const dx = b[0] - a[0];
1066
+ const dy = b[1] - a[1];
1067
+ const dz = b[2] - a[2];
1068
+ const len = Math.hypot(dx, dy, dz);
1069
+ if (len < 0.00001)
1070
+ return null;
1071
+ return [dx / len, dy / len, dz / len];
1072
+ }
1073
+ function turnAngleDeg(d1, d2) {
1074
+ if (!d1 || !d2)
1075
+ return 0;
1076
+ const dot = Math.max(-1, Math.min(1, d1[0] * d2[0] + d1[1] * d2[1] + d1[2] * d2[2]));
1077
+ const deg = Math.acos(dot) * 180 / Math.PI;
1078
+ return deg > 2 ? deg : 0;
1079
+ }
1080
+ function dirToBucket(d) {
1081
+ if (!d)
1082
+ return 0;
1083
+ const [x, y, z] = d;
1084
+ const ax = Math.abs(x);
1085
+ const ay = Math.abs(y);
1086
+ const az = Math.abs(z);
1087
+ if (ay >= 0.85)
1088
+ return y >= 0 ? 5 : 6;
1089
+ if (ay > 0.25)
1090
+ return y >= 0 ? 11 : 12;
1091
+ if (ax >= 0.85)
1092
+ return x >= 0 ? 1 : 2;
1093
+ if (az >= 0.85)
1094
+ return z >= 0 ? 3 : 4;
1095
+ if (x >= 0 && z >= 0)
1096
+ return 7;
1097
+ if (x >= 0 && z < 0)
1098
+ return 8;
1099
+ if (x < 0 && z >= 0)
1100
+ return 9;
1101
+ return 10;
1102
+ }
1103
+ function segmentHitsAnyOpening(a, b, prisms) {
1104
+ for (let i = 0;i < prisms.length; i++) {
1105
+ if (segmentIntersectsOrientedPrismY2(a, b, prisms[i], 0))
1106
+ return true;
1107
+ }
1108
+ return false;
1109
+ }
1110
+ function compactPolyline(points, eps = 0.0001) {
1111
+ const deduped = [];
1112
+ for (const pt of points) {
1113
+ const clean = sanitizeVec3(pt);
1114
+ if (deduped.length === 0 || dist32(deduped[deduped.length - 1], clean) > eps) {
1115
+ deduped.push(clean);
1116
+ }
1117
+ }
1118
+ if (deduped.length <= 2)
1119
+ return deduped;
1120
+ const out = [deduped[0]];
1121
+ for (let i = 1;i < deduped.length - 1; i++) {
1122
+ const prev = out[out.length - 1];
1123
+ const cur = deduped[i];
1124
+ const next = deduped[i + 1];
1125
+ const d1 = unitDir(prev, cur);
1126
+ const d2 = unitDir(cur, next);
1127
+ if (d1 && d2) {
1128
+ const dot = d1[0] * d2[0] + d1[1] * d2[1] + d1[2] * d2[2];
1129
+ if (dot > 0.9998)
1130
+ continue;
1131
+ }
1132
+ out.push(cur);
1133
+ }
1134
+ out.push(deduped[deduped.length - 1]);
1135
+ return out;
1136
+ }
1137
+ function checkSegmentPhysicsOk(a, b, ctx) {
1138
+ const hDist = distXZ2(a, b);
1139
+ const dy = b[1] - a[1];
1140
+ if (ctx.mode === "gravity-slope") {
1141
+ if (dy > UPHILL_TOL_M)
1142
+ return false;
1143
+ return true;
1144
+ }
1145
+ if (ctx.mode === "non-descending-vent") {
1146
+ if (dy < -UPHILL_TOL_M)
1147
+ return false;
1148
+ const floorY = ctx.minHorizY;
1149
+ if (floorY !== undefined && hDist > 0.01) {
1150
+ if (a[1] < floorY - 0.0001 || b[1] < floorY - 0.0001)
1151
+ return false;
1152
+ }
1153
+ const ceilingEnforced = floorY === undefined || ctx.tieInY >= floorY - 0.0001;
1154
+ if (ceilingEnforced) {
1155
+ if (a[1] > ctx.tieInY + 0.0001 || b[1] > ctx.tieInY + 0.0001)
1156
+ return false;
1157
+ }
1158
+ return true;
1159
+ }
1160
+ if (ctx.minHorizY !== undefined && hDist > 0.01) {
1161
+ if (a[1] < ctx.minHorizY - 0.0001 || b[1] < ctx.minHorizY - 0.0001)
1162
+ return false;
1163
+ }
1164
+ return true;
1165
+ }
1166
+ function evaluatePolyline(rawPoints, ctx, allowExteriorEndpointMargin) {
1167
+ const points = compactPolyline(rawPoints);
1168
+ const clashSet = new Set;
1169
+ let openingHits = 0;
1170
+ let footprintOk = true;
1171
+ let physicsHardOk = true;
1172
+ let lengthM = 0;
1173
+ let internalBendDeg = 0;
1174
+ let firstDir = null;
1175
+ let lastDir = null;
1176
+ const fpOpts = allowExteriorEndpointMargin ? { skipExteriorEndpointMarginM: 0.35 } : undefined;
1177
+ for (let i = 1;i < points.length; i++) {
1178
+ const a = points[i - 1];
1179
+ const b = points[i];
1180
+ const segLen = dist32(a, b);
1181
+ lengthM += segLen;
1182
+ const d = unitDir(a, b);
1183
+ if (d) {
1184
+ if (!firstDir)
1185
+ firstDir = d;
1186
+ if (lastDir)
1187
+ internalBendDeg += turnAngleDeg(lastDir, d);
1188
+ lastDir = d;
1189
+ }
1190
+ const hits = ctx.occupancy.segmentClashes(a, b, ctx.clashParams);
1191
+ for (const obs of hits) {
1192
+ clashSet.add(obs.nodeId);
1193
+ ctx.encounteredObstacleIds.add(obs.nodeId);
1194
+ }
1195
+ if (segmentHitsAnyOpening(a, b, ctx.openingPrisms)) {
1196
+ openingHits += 1;
1197
+ }
1198
+ if (footprintOk && !ctx.footprint.isSegmentInside(a, b, fpOpts)) {
1199
+ footprintOk = false;
1200
+ }
1201
+ if (physicsHardOk && !checkSegmentPhysicsOk(a, b, ctx)) {
1202
+ physicsHardOk = false;
1203
+ }
1204
+ }
1205
+ const roofOk = ctx.roofShell.isPathClearOfRoof(points, ctx.halfY, ctx.roofClearanceM);
1206
+ return {
1207
+ points,
1208
+ lengthM,
1209
+ internalBendDeg,
1210
+ firstDir,
1211
+ lastDir,
1212
+ clashNodeIds: [...clashSet],
1213
+ openingHits,
1214
+ roofOk,
1215
+ footprintOk,
1216
+ physicsHardOk
1217
+ };
1218
+ }
1219
+ function evalPenalty(ev) {
1220
+ let pen = 0;
1221
+ pen += ev.clashNodeIds.length * CLASH_PENALTY;
1222
+ pen += ev.openingHits * OPENING_PENALTY;
1223
+ if (!ev.roofOk)
1224
+ pen += ROOF_PENALTY;
1225
+ if (!ev.footprintOk)
1226
+ pen += OUTDOOR_PENALTY;
1227
+ if (!ev.physicsHardOk)
1228
+ pen += PHYSICS_PENALTY;
1229
+ return pen;
1230
+ }
1231
+ function isHardClean(ev) {
1232
+ return ev.clashNodeIds.length === 0 && ev.openingHits === 0 && ev.roofOk && ev.footprintOk && ev.physicsHardOk;
1233
+ }
1234
+ function selectCandidateSpliceVertices(pt, graph, allowedBandSet, expanded = false) {
1235
+ const scored = [];
1236
+ for (let i = 0;i < graph.vertices.length; i++) {
1237
+ const v = graph.vertices[i];
1238
+ if (!allowedBandSet.has(v.band))
1239
+ continue;
1240
+ const dx = v.pos[0] - pt[0];
1241
+ const dy = v.pos[1] - pt[1];
1242
+ const dz = v.pos[2] - pt[2];
1243
+ const dXZSq = dx * dx + dz * dz;
1244
+ scored.push({ v, dXZSq, d3Sq: dXZSq + dy * dy });
1245
+ }
1246
+ if (scored.length === 0)
1247
+ return [];
1248
+ const byXZ = [...scored].sort((a, b) => a.dXZSq - b.dXZSq || a.d3Sq - b.d3Sq || a.v.id - b.v.id);
1249
+ const by3D = [...scored].sort((a, b) => a.d3Sq - b.d3Sq || a.v.id - b.v.id);
1250
+ const minDistXZ = Math.sqrt(byXZ[0].dXZSq);
1251
+ const localRadiusXZ = expanded ? Number.POSITIVE_INFINITY : Math.max(2, minDistXZ + 1.5);
1252
+ const localRadiusXZSq = Number.isFinite(localRadiusXZ) ? localRadiusXZ * localRadiusXZ : Number.POSITIVE_INFINITY;
1253
+ const maxXZCount = expanded ? 16 : 8;
1254
+ const max3DCount = expanded ? 12 : 6;
1255
+ const selectedIds = new Set;
1256
+ const picked = [];
1257
+ const addVertex = (v) => {
1258
+ if (!selectedIds.has(v.id)) {
1259
+ selectedIds.add(v.id);
1260
+ picked.push(v);
1261
+ }
1262
+ };
1263
+ for (let i = 0;i < byXZ.length; i++) {
1264
+ if (picked.length >= maxXZCount)
1265
+ break;
1266
+ const s = byXZ[i];
1267
+ if (s.dXZSq <= localRadiusXZSq || picked.length < 2)
1268
+ addVertex(s.v);
1269
+ }
1270
+ let added3D = 0;
1271
+ for (let i = 0;i < by3D.length; i++) {
1272
+ if (added3D >= max3DCount)
1273
+ break;
1274
+ const s = by3D[i];
1275
+ if (s.dXZSq <= localRadiusXZSq || picked.length < 2) {
1276
+ addVertex(s.v);
1277
+ added3D++;
1278
+ }
1279
+ }
1280
+ let addedPiers = 0;
1281
+ for (let i = 0;i < byXZ.length && addedPiers < 4; i++) {
1282
+ const s = byXZ[i];
1283
+ if (s.v.isRiserPier && s.dXZSq <= localRadiusXZSq) {
1284
+ addVertex(s.v);
1285
+ addedPiers++;
1286
+ }
1287
+ }
1288
+ const perBandCounts = new Map;
1289
+ for (let i = 0;i < byXZ.length; i++) {
1290
+ const v = byXZ[i].v;
1291
+ const c = perBandCounts.get(v.band) ?? 0;
1292
+ if (c < 1) {
1293
+ perBandCounts.set(v.band, 1);
1294
+ addVertex(v);
1295
+ }
1296
+ }
1297
+ return picked;
1298
+ }
1299
+ function buildHorizontalCandidates(a, b, mode, wall) {
1300
+ const dx = Math.abs(b[0] - a[0]);
1301
+ const dz = Math.abs(b[2] - a[2]);
1302
+ const y = a[1];
1303
+ if (dx < 0.03 || dz < 0.03) {
1304
+ return [[a, [b[0], y, b[2]]]];
1305
+ }
1306
+ if (mode === "euclidean-cavity") {
1307
+ return [
1308
+ [a, [b[0], y, b[2]]],
1309
+ [a, [b[0], y, a[2]], [b[0], y, b[2]]],
1310
+ [a, [a[0], y, b[2]], [b[0], y, b[2]]]
1311
+ ];
1312
+ }
1313
+ const cands = [];
1314
+ if (wall && Math.abs(wall.ux) > 0.05 && Math.abs(wall.uz) > 0.05) {
1315
+ const t = (a[0] - wall.start[0]) * wall.ux + (a[2] - wall.start[1]) * wall.uz;
1316
+ const clampedT = Math.max(0, Math.min(wall.lengthM, t));
1317
+ const px = wall.start[0] + wall.ux * clampedT;
1318
+ const pz = wall.start[1] + wall.uz * clampedT;
1319
+ cands.push([a, [px, y, pz], [b[0], y, b[2]]]);
1320
+ }
1321
+ cands.push([a, [b[0], y, a[2]], [b[0], y, b[2]]]);
1322
+ cands.push([a, [a[0], y, b[2]], [b[0], y, b[2]]]);
1323
+ return cands;
1324
+ }
1325
+ function buildSpliceCandidatePolylines(a, b, role, mode, wall) {
1326
+ const hDist = distXZ2(a, b);
1327
+ const dy = Math.abs(b[1] - a[1]);
1328
+ if (dist32(a, b) < 0.0001)
1329
+ return [[a, b]];
1330
+ if (hDist < 0.03)
1331
+ return [[a, b]];
1332
+ if (dy < 0.03) {
1333
+ return buildHorizontalCandidates(a, b, mode, wall).map((pts) => {
1334
+ const copy = [...pts];
1335
+ copy[copy.length - 1] = b;
1336
+ return copy;
1337
+ });
1338
+ }
1339
+ const candidates = [];
1340
+ const verticalFirst = () => {
1341
+ const mid = [a[0], b[1], a[2]];
1342
+ for (const hLeg of buildHorizontalCandidates(mid, b, mode, wall)) {
1343
+ candidates.push([a, ...hLeg]);
1344
+ }
1345
+ };
1346
+ const horizontalFirst = () => {
1347
+ const endAtAY = [b[0], a[1], b[2]];
1348
+ for (const hLeg of buildHorizontalCandidates(a, endAtAY, mode, wall)) {
1349
+ candidates.push([...hLeg, b]);
1350
+ }
1351
+ };
1352
+ if (role === "enter") {
1353
+ verticalFirst();
1354
+ horizontalFirst();
1355
+ } else {
1356
+ horizontalFirst();
1357
+ verticalFirst();
1358
+ }
1359
+ if (mode === "euclidean-cavity" && (dy < 0.35 || hDist < 0.35)) {
1360
+ candidates.push([a, b]);
1361
+ }
1362
+ return candidates;
1363
+ }
1364
+ function evaluateSpliceBatch(endpoint, role, candidates, wallMap, ctx, endpointExterior) {
1365
+ const results = [];
1366
+ for (const v of candidates) {
1367
+ const a = role === "enter" ? endpoint : v.pos;
1368
+ const b = role === "enter" ? v.pos : endpoint;
1369
+ const wall = v.wallId ? wallMap.get(v.wallId) : undefined;
1370
+ const polylines = buildSpliceCandidatePolylines(a, b, role, ctx.mode, wall);
1371
+ const seenKeys = new Set;
1372
+ const ranked = [];
1373
+ for (let pi = 0;pi < polylines.length; pi++) {
1374
+ const compacted = compactPolyline(polylines[pi]);
1375
+ let key = "";
1376
+ for (let qi = 0;qi < compacted.length; qi++) {
1377
+ const p = compacted[qi];
1378
+ if (qi > 0)
1379
+ key += "|";
1380
+ key += `${Math.round(p[0] * 1e4)},${Math.round(p[1] * 1e4)},${Math.round(p[2] * 1e4)}`;
1381
+ }
1382
+ if (seenKeys.has(key))
1383
+ continue;
1384
+ seenKeys.add(key);
1385
+ ranked.push({ pts: compacted, rawLen: polylineLengthM2(compacted) });
1386
+ }
1387
+ ranked.sort((x, y) => x.rawLen - y.rawLen);
1388
+ let bestClean = null;
1389
+ let bestCleanScore = Number.POSITIVE_INFINITY;
1390
+ let bestAny = null;
1391
+ let bestAnyScore = Number.POSITIVE_INFINITY;
1392
+ for (let ri = 0;ri < ranked.length; ri++) {
1393
+ const cand = ranked[ri];
1394
+ if (bestClean !== null && cand.rawLen >= bestCleanScore - 0.000000001) {
1395
+ break;
1396
+ }
1397
+ const ev = evaluatePolyline(cand.pts, ctx, endpointExterior);
1398
+ const baseScore = ev.lengthM + ev.internalBendDeg * BEND_COST_PER_DEG;
1399
+ const totalScore = baseScore + evalPenalty(ev);
1400
+ if (isHardClean(ev) && baseScore < bestCleanScore) {
1401
+ bestClean = ev;
1402
+ bestCleanScore = baseScore;
1403
+ }
1404
+ if (totalScore < bestAnyScore) {
1405
+ bestAny = ev;
1406
+ bestAnyScore = totalScore;
1407
+ }
1408
+ }
1409
+ if (bestAny) {
1410
+ results.push({
1411
+ vertexId: v.id,
1412
+ band: v.band,
1413
+ isWallEdge: WALL_BANDS2.has(v.band),
1414
+ hardClean: bestClean,
1415
+ bestFallback: bestAny
1416
+ });
1417
+ }
1418
+ }
1419
+ return results;
1420
+ }
1421
+ function buildSpliceConnections(endpoint, role, graph, allowedBandSet, wallMap, ctx) {
1422
+ const endpointExterior = !ctx.footprint.isPointInside(endpoint[0], endpoint[2]);
1423
+ const localCandidates = selectCandidateSpliceVertices(endpoint, graph, allowedBandSet, false);
1424
+ const localResults = evaluateSpliceBatch(endpoint, role, localCandidates, wallMap, ctx, endpointExterior);
1425
+ if (localResults.some((s) => s.hardClean !== null)) {
1426
+ return localResults;
1427
+ }
1428
+ const seenIds = new Set(localCandidates.map((v) => v.id));
1429
+ const expandedCandidates = selectCandidateSpliceVertices(endpoint, graph, allowedBandSet, true).filter((v) => !seenIds.has(v.id));
1430
+ if (expandedCandidates.length === 0)
1431
+ return localResults;
1432
+ return [
1433
+ ...localResults,
1434
+ ...evaluateSpliceBatch(endpoint, role, expandedCandidates, wallMap, ctx, endpointExterior)
1435
+ ];
1436
+ }
1437
+ function resolveSharedDirectBand(from, to, graph, walls, allowedBandSet, mode) {
1438
+ const hDist = distXZ2(from, to);
1439
+ const dy = Math.abs(to[1] - from[1]);
1440
+ const isOrthogonalCompatible = mode !== "orthogonal" || hDist < 0.03 || dy < 0.03 && (Math.abs(to[0] - from[0]) < 0.03 || Math.abs(to[2] - from[2]) < 0.03);
1441
+ if (allowedBandSet.has("attic") && graph.atticY !== null && Math.abs(from[1] - graph.atticY) <= 0.45 && Math.abs(to[1] - graph.atticY) <= 0.45 && isOrthogonalCompatible) {
1442
+ return { band: "attic", isWall: false };
1443
+ }
1444
+ if (allowedBandSet.has("crawlspace") && graph.subFloorY !== null && Math.abs(from[1] - graph.subFloorY) <= 0.5 && Math.abs(to[1] - graph.subFloorY) <= 0.5 && isOrthogonalCompatible) {
1445
+ return { band: "crawlspace", isWall: false };
1446
+ }
1447
+ if (allowedBandSet.has("under-slab") && graph.subFloorY !== null && Math.abs(from[1] - graph.subFloorY) <= 0.5 && Math.abs(to[1] - graph.subFloorY) <= 0.5 && isOrthogonalCompatible) {
1448
+ return { band: "under-slab", isWall: false };
1449
+ }
1450
+ if (allowedBandSet.has("overhead-plenum") && Math.abs(from[1] - graph.ceilingPlenumY) <= 0.35 && Math.abs(to[1] - graph.ceilingPlenumY) <= 0.35 && isOrthogonalCompatible) {
1451
+ return { band: "overhead-plenum", isWall: false };
1452
+ }
1453
+ if (walls.length > 0) {
1454
+ const pFrom = findNearestWallToPoint2(from[0], from[2], walls);
1455
+ const pTo = findNearestWallToPoint2(to[0], to[2], walls);
1456
+ if (pFrom && pTo && pFrom.wall.id === pTo.wall.id && pFrom.distM <= pFrom.wall.thicknessM / 2 + 0.2 && pTo.distM <= pTo.wall.thicknessM / 2 + 0.2) {
1457
+ const dy = Math.abs(to[1] - from[1]);
1458
+ if (mode !== "orthogonal" || hDist < 0.03 || dy < 0.03) {
1459
+ const avgY = (from[1] + to[1]) * 0.5;
1460
+ const wallH = pFrom.wall.heightM;
1461
+ const inferredBand = avgY >= wallH - 0.35 ? "top-plate" : avgY <= 0.65 ? "under-sill" : "mid-wall";
1462
+ if (allowedBandSet.has(inferredBand)) {
1463
+ return { band: inferredBand, isWall: true };
1464
+ }
1465
+ for (const wb of ["mid-wall", "under-sill", "top-plate"]) {
1466
+ if (allowedBandSet.has(wb))
1467
+ return { band: wb, isWall: true };
1468
+ }
1469
+ }
1470
+ }
1471
+ }
1472
+ return null;
1473
+ }
1474
+ var MAX_PARETO_LABELS_PER_STATE = 16;
1475
+ function runConstrainedAStar(params) {
1476
+ const {
1477
+ graph,
1478
+ from,
1479
+ to,
1480
+ allowedBandSet,
1481
+ request,
1482
+ startSplices,
1483
+ goalSplicesByVertex,
1484
+ directShortcut,
1485
+ edgeCache,
1486
+ ctx,
1487
+ minWeightScale,
1488
+ allowDegraded
1489
+ } = params;
1490
+ const nVerts = graph.vertices.length;
1491
+ const START_ID = nVerts;
1492
+ const GOAL_ID = nVerts + 1;
1493
+ const preferWall = request.preferWallFollowing === true;
1494
+ const maxBendDeg = typeof request.maxBendDegrees === "number" && Number.isFinite(request.maxBendDegrees) ? request.maxBendDegrees : undefined;
1495
+ const usePareto = maxBendDeg !== undefined;
1496
+ const compiledWithinOpeningEnvelope = typeof graph.compiledHalfXZ === "number" && typeof graph.compiledHalfY === "number" && ctx.clashParams.halfXZ <= graph.compiledHalfXZ + 0.000000001 && ctx.halfY <= graph.compiledHalfY + 0.000000001;
1497
+ const compiledWithinRoofEnvelope = typeof graph.compiledHalfY === "number" && typeof graph.compiledRoofClearanceM === "number" && ctx.halfY <= graph.compiledHalfY + 0.000000001 && ctx.roofClearanceM <= graph.compiledRoofClearanceM + 0.000000001;
1498
+ const wallFactorFor = (isWall) => preferWall ? isWall ? 0.85 : 1.15 : 1;
1499
+ const getEdgeEval = (uId, vId, uPos, vPos, isWallEdge, uBand, vBand) => {
1500
+ const physicsHardOk = checkSegmentPhysicsOk(uPos, vPos, ctx);
1501
+ if (!allowDegraded && !physicsHardOk) {
1502
+ return { dir: null, penalty: PHYSICS_PENALTY, hardClean: false };
1503
+ }
1504
+ const cacheKey = uId < vId ? uId * nVerts + vId : vId * nVerts + uId;
1505
+ let uEval = edgeCache.get(cacheKey);
1506
+ if (!uEval || allowDegraded && !uEval.fullEvaluated) {
1507
+ const hits = ctx.occupancy.segmentClashes(uPos, vPos, ctx.clashParams);
1508
+ const clashSet = new Set;
1509
+ for (let i = 0;i < hits.length; i++) {
1510
+ const obs = hits[i];
1511
+ clashSet.add(obs.nodeId);
1512
+ ctx.encounteredObstacleIds.add(obs.nodeId);
1513
+ }
1514
+ if (!allowDegraded && clashSet.size > 0) {
1515
+ uEval = {
1516
+ clashNodeIds: [...clashSet],
1517
+ openingHit: false,
1518
+ roofOk: true,
1519
+ footprintOk: true,
1520
+ undirectedPenalty: clashSet.size * CLASH_PENALTY,
1521
+ undirectedHardClean: false,
1522
+ fullEvaluated: false
1523
+ };
1524
+ edgeCache.set(cacheKey, uEval);
1525
+ } else {
1526
+ const isSubFloorEdge = uBand === "under-slab" || uBand === "crawlspace" || vBand === "under-slab" || vBand === "crawlspace";
1527
+ const skipOpeningCheck = compiledWithinOpeningEnvelope && isWallEdge;
1528
+ const skipRoofCheck = compiledWithinRoofEnvelope && !isSubFloorEdge;
1529
+ let openingHit = false;
1530
+ let roofOk = true;
1531
+ let footprintOk = true;
1532
+ let fullEvaluated = true;
1533
+ if (!skipOpeningCheck) {
1534
+ openingHit = segmentHitsAnyOpening(uPos, vPos, ctx.openingPrisms);
1535
+ }
1536
+ if (!allowDegraded && openingHit) {
1537
+ fullEvaluated = false;
1538
+ } else {
1539
+ if (!skipRoofCheck) {
1540
+ roofOk = ctx.roofShell.isPathClearOfRoof([uPos, vPos], ctx.halfY, ctx.roofClearanceM);
1541
+ }
1542
+ if (!allowDegraded && !roofOk) {
1543
+ fullEvaluated = false;
1544
+ } else {
1545
+ footprintOk = ctx.footprint.isSegmentInside(uPos, vPos);
1546
+ }
1547
+ }
1548
+ let undirectedPenalty = clashSet.size * CLASH_PENALTY;
1549
+ if (openingHit)
1550
+ undirectedPenalty += OPENING_PENALTY;
1551
+ if (!roofOk)
1552
+ undirectedPenalty += ROOF_PENALTY;
1553
+ if (!footprintOk)
1554
+ undirectedPenalty += OUTDOOR_PENALTY;
1555
+ uEval = {
1556
+ clashNodeIds: [...clashSet],
1557
+ openingHit,
1558
+ roofOk,
1559
+ footprintOk,
1560
+ undirectedPenalty,
1561
+ undirectedHardClean: clashSet.size === 0 && !openingHit && roofOk && footprintOk,
1562
+ fullEvaluated
1563
+ };
1564
+ edgeCache.set(cacheKey, uEval);
1565
+ }
1566
+ }
1567
+ const hardClean = uEval.undirectedHardClean && physicsHardOk;
1568
+ if (!allowDegraded && !hardClean) {
1569
+ return { dir: null, penalty: uEval.undirectedPenalty, hardClean: false };
1570
+ }
1571
+ return {
1572
+ dir: unitDir(uPos, vPos),
1573
+ penalty: uEval.undirectedPenalty + (physicsHardOk ? 0 : PHYSICS_PENALTY),
1574
+ hardClean
1575
+ };
1576
+ };
1577
+ const heap = new BinaryMinHeap;
1578
+ const bestG = new Map;
1579
+ const paretoLabels = new Map;
1580
+ const parentState = new Map;
1581
+ const tryAcceptLabel = (stateKey, gNext, nextBend, entrySeq) => {
1582
+ if (!usePareto) {
1583
+ const prevBest = bestG.get(stateKey);
1584
+ if (prevBest !== undefined && gNext >= prevBest - 0.000000001)
1585
+ return false;
1586
+ bestG.set(stateKey, gNext);
1587
+ return true;
1588
+ }
1589
+ let labels = paretoLabels.get(stateKey);
1590
+ if (!labels) {
1591
+ paretoLabels.set(stateKey, [{ g: gNext, bendDeg: nextBend, seq: entrySeq }]);
1592
+ return true;
1593
+ }
1594
+ for (let i = 0;i < labels.length; i++) {
1595
+ const L = labels[i];
1596
+ if (L.g <= gNext + 0.000000001 && L.bendDeg <= nextBend + 0.001) {
1597
+ return false;
1598
+ }
1599
+ }
1600
+ const filtered = [];
1601
+ for (let i = 0;i < labels.length; i++) {
1602
+ const L = labels[i];
1603
+ if (gNext <= L.g + 0.000000001 && nextBend <= L.bendDeg + 0.001)
1604
+ continue;
1605
+ filtered.push(L);
1606
+ }
1607
+ let insertIdx = filtered.length;
1608
+ for (let i = 0;i < filtered.length; i++) {
1609
+ if (gNext < filtered[i].g) {
1610
+ insertIdx = i;
1611
+ break;
1612
+ }
1613
+ }
1614
+ const candidate = { g: gNext, bendDeg: nextBend, seq: entrySeq };
1615
+ filtered.splice(insertIdx, 0, candidate);
1616
+ if (filtered.length > MAX_PARETO_LABELS_PER_STATE) {
1617
+ const isExtreme = insertIdx === 0 || insertIdx === filtered.length - 1;
1618
+ if (!isExtreme) {
1619
+ filtered.splice(insertIdx, 1);
1620
+ paretoLabels.set(stateKey, filtered);
1621
+ return false;
1622
+ }
1623
+ filtered.splice(filtered.length - 2, 1);
1624
+ }
1625
+ paretoLabels.set(stateKey, filtered);
1626
+ return true;
1627
+ };
1628
+ let nextSeq = 1;
1629
+ const startSeq = 0;
1630
+ const startKey = START_ID * DIR_BUCKETS;
1631
+ tryAcceptLabel(startKey, 0, 0, startSeq);
1632
+ heap.push({
1633
+ f: dist32(from, to) * minWeightScale,
1634
+ g: 0,
1635
+ seq: startSeq,
1636
+ nodeId: START_ID,
1637
+ dirBucket: 0,
1638
+ dir: null,
1639
+ bendDeg: 0,
1640
+ stateKey: startKey
1641
+ });
1642
+ let winningGoalSeq = null;
1643
+ while (heap.size > 0) {
1644
+ const cur = heap.pop();
1645
+ if (!usePareto) {
1646
+ const recordedBest = bestG.get(cur.stateKey);
1647
+ if (recordedBest !== undefined && cur.g > recordedBest + 0.000000001)
1648
+ continue;
1649
+ } else {
1650
+ const labels = paretoLabels.get(cur.stateKey);
1651
+ let active = false;
1652
+ if (labels) {
1653
+ for (let i = 0;i < labels.length; i++) {
1654
+ if (labels[i].seq === cur.seq) {
1655
+ active = true;
1656
+ break;
1657
+ }
1658
+ }
1659
+ }
1660
+ if (!active)
1661
+ continue;
1662
+ }
1663
+ if (cur.nodeId === GOAL_ID) {
1664
+ winningGoalSeq = cur.seq;
1665
+ break;
1666
+ }
1667
+ if (cur.nodeId === START_ID) {
1668
+ if (directShortcut && isHardClean(directShortcut.eval)) {
1669
+ const ev = directShortcut.eval;
1670
+ const bend = ev.internalBendDeg;
1671
+ if (maxBendDeg === undefined || bend <= maxBendDeg + 0.001 || allowDegraded) {
1672
+ const bendExcessPen = maxBendDeg !== undefined && bend > maxBendDeg + 0.001 ? 200 * (bend - maxBendDeg) / 90 : 0;
1673
+ const gNext = ev.lengthM * wallFactorFor(directShortcut.isWall) + bend * BEND_COST_PER_DEG + bendExcessPen;
1674
+ const bucket = dirToBucket(ev.lastDir);
1675
+ const nextKey = GOAL_ID * DIR_BUCKETS + bucket;
1676
+ const entrySeq = nextSeq++;
1677
+ if (tryAcceptLabel(nextKey, gNext, bend, entrySeq)) {
1678
+ parentState.set(entrySeq, {
1679
+ prevSeq: cur.seq,
1680
+ prevNode: START_ID,
1681
+ points: ev.points,
1682
+ band: directShortcut.band
1683
+ });
1684
+ heap.push({
1685
+ f: gNext,
1686
+ g: gNext,
1687
+ seq: entrySeq,
1688
+ nodeId: GOAL_ID,
1689
+ dirBucket: bucket,
1690
+ dir: ev.lastDir,
1691
+ bendDeg: bend,
1692
+ stateKey: nextKey
1693
+ });
1694
+ }
1695
+ }
1696
+ }
1697
+ for (const splice of startSplices) {
1698
+ const ev = allowDegraded ? splice.hardClean ?? splice.bestFallback : splice.hardClean;
1699
+ if (!ev)
1700
+ continue;
1701
+ const bend = ev.internalBendDeg;
1702
+ if (!allowDegraded && maxBendDeg !== undefined && bend > maxBendDeg + 0.001)
1703
+ continue;
1704
+ const bendExcessPen = maxBendDeg !== undefined && bend > maxBendDeg + 0.001 ? 200 * (bend - maxBendDeg) / 90 : 0;
1705
+ const penalty = allowDegraded ? evalPenalty(ev) : 0;
1706
+ const gNext = ev.lengthM * wallFactorFor(splice.isWallEdge) + bend * BEND_COST_PER_DEG + bendExcessPen + penalty;
1707
+ const bucket = dirToBucket(ev.lastDir);
1708
+ const nextKey = splice.vertexId * DIR_BUCKETS + bucket;
1709
+ const entrySeq = nextSeq++;
1710
+ if (tryAcceptLabel(nextKey, gNext, bend, entrySeq)) {
1711
+ const v = graph.vertices[splice.vertexId];
1712
+ parentState.set(entrySeq, {
1713
+ prevSeq: cur.seq,
1714
+ prevNode: START_ID,
1715
+ points: ev.points,
1716
+ band: splice.band,
1717
+ wallId: v.wallId
1718
+ });
1719
+ const h = dist32(v.pos, to) * minWeightScale;
1720
+ heap.push({
1721
+ f: gNext + h,
1722
+ g: gNext,
1723
+ seq: entrySeq,
1724
+ nodeId: splice.vertexId,
1725
+ dirBucket: bucket,
1726
+ dir: ev.lastDir,
1727
+ bendDeg: bend,
1728
+ stateKey: nextKey
1729
+ });
1730
+ }
1731
+ }
1732
+ continue;
1733
+ }
1734
+ const uVertex = graph.vertices[cur.nodeId];
1735
+ const goalSplice = goalSplicesByVertex.get(cur.nodeId);
1736
+ if (goalSplice) {
1737
+ const ev = allowDegraded ? goalSplice.hardClean ?? goalSplice.bestFallback : goalSplice.hardClean;
1738
+ if (ev) {
1739
+ const joinTurn = turnAngleDeg(cur.dir, ev.firstDir);
1740
+ const nextBend = cur.bendDeg + joinTurn + ev.internalBendDeg;
1741
+ if (allowDegraded || maxBendDeg === undefined || nextBend <= maxBendDeg + 0.001) {
1742
+ const bendExcessPen = maxBendDeg !== undefined && nextBend > maxBendDeg + 0.001 ? 200 * (nextBend - maxBendDeg) / 90 : 0;
1743
+ const penalty = allowDegraded ? evalPenalty(ev) : 0;
1744
+ const gNext = cur.g + ev.lengthM * wallFactorFor(goalSplice.isWallEdge) + (joinTurn + ev.internalBendDeg) * BEND_COST_PER_DEG + bendExcessPen + penalty;
1745
+ const bucket = dirToBucket(ev.lastDir ?? cur.dir);
1746
+ const nextKey = GOAL_ID * DIR_BUCKETS + bucket;
1747
+ const entrySeq = nextSeq++;
1748
+ if (tryAcceptLabel(nextKey, gNext, nextBend, entrySeq)) {
1749
+ parentState.set(entrySeq, {
1750
+ prevSeq: cur.seq,
1751
+ prevNode: cur.nodeId,
1752
+ points: ev.points,
1753
+ band: goalSplice.band,
1754
+ wallId: uVertex.wallId
1755
+ });
1756
+ heap.push({
1757
+ f: gNext,
1758
+ g: gNext,
1759
+ seq: entrySeq,
1760
+ nodeId: GOAL_ID,
1761
+ dirBucket: bucket,
1762
+ dir: ev.lastDir ?? cur.dir,
1763
+ bendDeg: nextBend,
1764
+ stateKey: nextKey
1765
+ });
1766
+ }
1767
+ }
1768
+ }
1769
+ }
1770
+ const edges = graph.adjacency[cur.nodeId] ?? [];
1771
+ for (let ei = 0;ei < edges.length; ei++) {
1772
+ const edge = edges[ei];
1773
+ if (!allowedBandSet.has(edge.band))
1774
+ continue;
1775
+ const vVertex = graph.vertices[edge.to];
1776
+ if (!vVertex || !allowedBandSet.has(vVertex.band))
1777
+ continue;
1778
+ const ev = getEdgeEval(cur.nodeId, edge.to, uVertex.pos, vVertex.pos, edge.isWallEdge, uVertex.band, vVertex.band);
1779
+ if (!allowDegraded && !ev.hardClean)
1780
+ continue;
1781
+ const turn = turnAngleDeg(cur.dir, ev.dir);
1782
+ const nextBend = cur.bendDeg + turn;
1783
+ if (!allowDegraded && maxBendDeg !== undefined && nextBend > maxBendDeg + 0.001)
1784
+ continue;
1785
+ const bendExcessPen = maxBendDeg !== undefined && nextBend > maxBendDeg + 0.001 ? 200 * (nextBend - maxBendDeg) / 90 : 0;
1786
+ const baseW = Number.isFinite(edge.baseCostWeight) && edge.baseCostWeight > 0 ? edge.baseCostWeight : 1;
1787
+ const stepLen = Number.isFinite(edge.lengthM) && edge.lengthM >= 0 ? edge.lengthM : dist32(uVertex.pos, vVertex.pos);
1788
+ const gNext = cur.g + stepLen * baseW * wallFactorFor(edge.isWallEdge) + turn * BEND_COST_PER_DEG + bendExcessPen + (allowDegraded ? ev.penalty : 0);
1789
+ const nextDir = ev.dir ?? cur.dir;
1790
+ const bucket = dirToBucket(nextDir);
1791
+ const nextKey = edge.to * DIR_BUCKETS + bucket;
1792
+ const entrySeq = nextSeq++;
1793
+ if (tryAcceptLabel(nextKey, gNext, nextBend, entrySeq)) {
1794
+ parentState.set(entrySeq, {
1795
+ prevSeq: cur.seq,
1796
+ prevNode: cur.nodeId,
1797
+ points: [uVertex.pos, vVertex.pos],
1798
+ band: edge.band,
1799
+ wallId: edge.wallId ?? vVertex.wallId
1800
+ });
1801
+ const h = dist32(vVertex.pos, to) * minWeightScale;
1802
+ heap.push({
1803
+ f: gNext + h,
1804
+ g: gNext,
1805
+ seq: entrySeq,
1806
+ nodeId: edge.to,
1807
+ dirBucket: bucket,
1808
+ dir: nextDir,
1809
+ bendDeg: nextBend,
1810
+ stateKey: nextKey
1811
+ });
1812
+ }
1813
+ }
1814
+ }
1815
+ if (winningGoalSeq === null)
1816
+ return null;
1817
+ const segments = [];
1818
+ let cursorSeq = winningGoalSeq;
1819
+ while (cursorSeq !== startSeq) {
1820
+ const step = parentState.get(cursorSeq);
1821
+ if (!step)
1822
+ break;
1823
+ segments.push({ points: step.points, band: step.band, wallId: step.wallId });
1824
+ cursorSeq = step.prevSeq;
1825
+ }
1826
+ segments.reverse();
1827
+ const waypoints = [];
1828
+ const vertexBands = [];
1829
+ const wallIdsByPoint = [];
1830
+ const bandsUsedSet = new Set;
1831
+ for (const seg of segments) {
1832
+ if (seg.band && polylineLengthM2(seg.points) > 0.0001)
1833
+ bandsUsedSet.add(seg.band);
1834
+ for (let i = 0;i < seg.points.length; i++) {
1835
+ const pt = seg.points[i];
1836
+ if (waypoints.length === 0 || dist32(waypoints[waypoints.length - 1], pt) > 0.0001) {
1837
+ waypoints.push(pt);
1838
+ vertexBands.push(seg.band);
1839
+ wallIdsByPoint.push(seg.wallId);
1840
+ } else if (seg.band && vertexBands[vertexBands.length - 1] === null) {
1841
+ vertexBands[vertexBands.length - 1] = seg.band;
1842
+ }
1843
+ }
1844
+ }
1845
+ if (waypoints.length < 2) {
1846
+ return {
1847
+ waypoints: [from, to],
1848
+ vertexBands: [segments[0]?.band ?? null, segments[0]?.band ?? null],
1849
+ bandsUsed: [...bandsUsedSet],
1850
+ wallIdsByPoint: [undefined, undefined]
1851
+ };
1852
+ }
1853
+ return {
1854
+ waypoints,
1855
+ vertexBands,
1856
+ bandsUsed: [...bandsUsedSet],
1857
+ wallIdsByPoint
1858
+ };
1859
+ }
1860
+ function applyLateralStagger(rawPoints, wallIdsByPoint, staggerM, wallMap, ctx, maxBendDegrees) {
1861
+ if (!Number.isFinite(staggerM) || Math.abs(staggerM) < 0.0001 || rawPoints.length < 2) {
1862
+ return rawPoints;
1863
+ }
1864
+ const firstPt = rawPoints[0];
1865
+ const lastPt = rawPoints[rawPoints.length - 1];
1866
+ const allowExteriorEndpointMargin = !ctx.footprint.isPointInside(firstPt[0], firstPt[2]) || !ctx.footprint.isPointInside(lastPt[0], lastPt[2]);
1867
+ const segCount = rawPoints.length - 1;
1868
+ const segWalls = new Array(segCount).fill(undefined);
1869
+ let hasWallSeg = false;
1870
+ for (let k = 0;k < segCount; k++) {
1871
+ const a = rawPoints[k];
1872
+ const b = rawPoints[k + 1];
1873
+ if (Math.abs(b[1] - a[1]) > 0.001)
1874
+ continue;
1875
+ const hDist = distXZ2(a, b);
1876
+ if (hDist <= 0.001)
1877
+ continue;
1878
+ const ux = (b[0] - a[0]) / hDist;
1879
+ const uz = (b[2] - a[2]) / hDist;
1880
+ const mx = (a[0] + b[0]) * 0.5;
1881
+ const mz = (a[2] + b[2]) * 0.5;
1882
+ const candIds = [wallIdsByPoint[k], wallIdsByPoint[k + 1]];
1883
+ for (let ci = 0;ci < candIds.length; ci++) {
1884
+ const wid = candIds[ci];
1885
+ if (!wid)
1886
+ continue;
1887
+ const w = wallMap.get(wid);
1888
+ if (!w)
1889
+ continue;
1890
+ const parallelDot = Math.abs(ux * w.ux + uz * w.uz);
1891
+ if (parallelDot < 0.98)
1892
+ continue;
1893
+ const projT = (mx - w.start[0]) * w.ux + (mz - w.start[1]) * w.uz;
1894
+ const clampedT = Math.max(0, Math.min(w.lengthM, projT));
1895
+ const px = w.start[0] + w.ux * clampedT;
1896
+ const pz = w.start[1] + w.uz * clampedT;
1897
+ if (Math.hypot(mx - px, mz - pz) <= w.thicknessM / 2 + 0.25) {
1898
+ segWalls[k] = w;
1899
+ hasWallSeg = true;
1900
+ break;
1901
+ }
1902
+ }
1903
+ }
1904
+ if (!hasWallSeg)
1905
+ return rawPoints;
1906
+ const wallNormalSign = new Map;
1907
+ const strictInteriorOpts = { precedence: "room-first", wallToleranceM: 0 };
1908
+ for (let k = 0;k < segCount; k++) {
1909
+ const w = segWalls[k];
1910
+ if (!w || wallNormalSign.has(w.id))
1911
+ continue;
1912
+ const midX = (w.start[0] + w.end[0]) * 0.5;
1913
+ const midZ = (w.start[1] + w.end[1]) * 0.5;
1914
+ const probeD = Math.max(0.15, w.thicknessM / 2 + 0.1);
1915
+ const posIn = ctx.footprint.isPointInside(midX + w.nx * probeD, midZ + w.nz * probeD, strictInteriorOpts);
1916
+ const negIn = ctx.footprint.isPointInside(midX - w.nx * probeD, midZ - w.nz * probeD, strictInteriorOpts);
1917
+ wallNormalSign.set(w.id, negIn && !posIn ? -1 : 1);
1918
+ }
1919
+ const shiftedPt = (pt, w, sign) => {
1920
+ const off = staggerM * sign * (wallNormalSign.get(w.id) ?? 1);
1921
+ return [pt[0] + w.nx * off, pt[1], pt[2] + w.nz * off];
1922
+ };
1923
+ const baseEval = evaluatePolyline(rawPoints, ctx, allowExteriorEndpointMargin);
1924
+ for (const sign of [1, -1]) {
1925
+ const out = [firstPt];
1926
+ const firstWall = segWalls[0];
1927
+ if (firstWall) {
1928
+ out.push(shiftedPt(firstPt, firstWall, sign));
1929
+ }
1930
+ for (let k = 1;k < segCount; k++) {
1931
+ const pt = rawPoints[k];
1932
+ const wPrev = segWalls[k - 1];
1933
+ const wCur = segWalls[k];
1934
+ if (!wPrev && !wCur) {
1935
+ out.push(pt);
1936
+ } else if (!wPrev && wCur) {
1937
+ out.push(pt);
1938
+ out.push(shiftedPt(pt, wCur, sign));
1939
+ } else if (wPrev && !wCur) {
1940
+ out.push(shiftedPt(pt, wPrev, sign));
1941
+ out.push(pt);
1942
+ } else if (wPrev && wCur) {
1943
+ if (wPrev.id === wCur.id) {
1944
+ out.push(shiftedPt(pt, wCur, sign));
1945
+ } else {
1946
+ const sPrev = shiftedPt(pt, wPrev, sign);
1947
+ const sCur = shiftedPt(pt, wCur, sign);
1948
+ const denom = wPrev.ux * wCur.uz - wPrev.uz * wCur.ux;
1949
+ let mitered = false;
1950
+ if (Math.abs(denom) > 0.001) {
1951
+ const t = ((sCur[0] - sPrev[0]) * wCur.uz - (sCur[2] - sPrev[2]) * wCur.ux) / denom;
1952
+ const ix = sPrev[0] + wPrev.ux * t;
1953
+ const iz = sPrev[2] + wPrev.uz * t;
1954
+ if (Math.hypot(ix - pt[0], iz - pt[2]) <= Math.abs(staggerM) * 4 + 0.05) {
1955
+ out.push([ix, pt[1], iz]);
1956
+ mitered = true;
1957
+ }
1958
+ }
1959
+ if (!mitered) {
1960
+ if (distXZ2(sPrev, sCur) < 0.0001) {
1961
+ out.push(sCur);
1962
+ } else {
1963
+ out.push(sPrev);
1964
+ out.push(pt);
1965
+ out.push(sCur);
1966
+ }
1967
+ }
1968
+ }
1969
+ }
1970
+ }
1971
+ const lastWall = segWalls[segCount - 1];
1972
+ if (lastWall) {
1973
+ out.push(shiftedPt(lastPt, lastWall, sign));
1974
+ }
1975
+ out.push(lastPt);
1976
+ const compacted = compactPolyline(out);
1977
+ if (maxBendDegrees !== undefined && Number.isFinite(maxBendDegrees) && countPathBendDegrees2(compacted) > maxBendDegrees + 0.01) {
1978
+ continue;
1979
+ }
1980
+ const testEval = evaluatePolyline(compacted, ctx, allowExteriorEndpointMargin);
1981
+ if (testEval.clashNodeIds.length <= baseEval.clashNodeIds.length && testEval.openingHits <= baseEval.openingHits && (!baseEval.roofOk || testEval.roofOk) && (!baseEval.footprintOk || testEval.footprintOk)) {
1982
+ return compacted;
1983
+ }
1984
+ }
1985
+ return rawPoints;
1986
+ }
1987
+ function shapeEuclideanCavity(waypoints, vertexBands, ctx) {
1988
+ if (waypoints.length <= 2)
1989
+ return compactPolyline(waypoints);
1990
+ const canShortcut = (a, b) => {
1991
+ if (ctx.occupancy.segmentClashes(a, b, ctx.clashParams).length > 0)
1992
+ return false;
1993
+ if (segmentHitsAnyOpening(a, b, ctx.openingPrisms))
1994
+ return false;
1995
+ if (!ctx.roofShell.isPathClearOfRoof([a, b], ctx.halfY, ctx.roofClearanceM))
1996
+ return false;
1997
+ if (!ctx.footprint.isSegmentInside(a, b))
1998
+ return false;
1999
+ if (ctx.minHorizY !== undefined && distXZ2(a, b) > 0.01) {
2000
+ if (a[1] < ctx.minHorizY - 0.0001 || b[1] < ctx.minHorizY - 0.0001)
2001
+ return false;
2002
+ }
2003
+ return true;
2004
+ };
2005
+ const isOpenPoint = (idx) => {
2006
+ const b = vertexBands[idx];
2007
+ return b !== null && b !== undefined && OPEN_CAVITY_BANDS.has(b);
2008
+ };
2009
+ const result = [waypoints[0]];
2010
+ let i = 0;
2011
+ while (i < waypoints.length - 1) {
2012
+ let bestJ = i + 1;
2013
+ if (isOpenPoint(i)) {
2014
+ for (let j = waypoints.length - 1;j > i + 1; j--) {
2015
+ if (!isOpenPoint(j))
2016
+ continue;
2017
+ let spanValid = true;
2018
+ for (let k = i;k <= j; k++) {
2019
+ if (!isOpenPoint(k) || Math.abs(waypoints[k][1] - waypoints[i][1]) > 0.5) {
2020
+ spanValid = false;
2021
+ break;
2022
+ }
2023
+ }
2024
+ if (!spanValid)
2025
+ continue;
2026
+ if (canShortcut(waypoints[i], waypoints[j])) {
2027
+ bestJ = j;
2028
+ break;
2029
+ }
2030
+ }
2031
+ }
2032
+ result.push(waypoints[bestJ]);
2033
+ i = bestJ;
2034
+ }
2035
+ return compactPolyline(result);
2036
+ }
2037
+ function buildGravitySlopedCandidate(pts, slopeRatio, remHorizM, toY, anchorToTargetStart, hasHeadForTarget) {
2038
+ const out = [pts[0]];
2039
+ let curY = pts[0][1];
2040
+ let startedHorizontal = false;
2041
+ for (let i = 1;i < pts.length; i++) {
2042
+ const prev = out[out.length - 1];
2043
+ const raw = pts[i];
2044
+ const hDist = distXZ2(prev, raw);
2045
+ const minTargetY = hasHeadForTarget ? toY + remHorizM[i] * slopeRatio : Number.NEGATIVE_INFINITY;
2046
+ if (hDist < 0.0001) {
2047
+ let desiredY = raw[1];
2048
+ if (hasHeadForTarget) {
2049
+ if (anchorToTargetStart && !startedHorizontal && remHorizM[i] > 0.0001) {
2050
+ desiredY = Math.min(pts[0][1], minTargetY);
2051
+ } else {
2052
+ desiredY = Math.max(desiredY, minTargetY);
2053
+ }
2054
+ }
2055
+ const nextY = Math.min(curY, desiredY);
2056
+ if (curY - nextY > 0.0001) {
2057
+ out.push([raw[0], nextY, raw[2]]);
2058
+ curY = nextY;
2059
+ }
2060
+ continue;
2061
+ }
2062
+ if (anchorToTargetStart && hasHeadForTarget && !startedHorizontal) {
2063
+ const horizStartY = Math.min(curY, toY + remHorizM[i - 1] * slopeRatio);
2064
+ if (curY - horizStartY > 0.0001) {
2065
+ out.push([prev[0], horizStartY, prev[2]]);
2066
+ curY = horizStartY;
2067
+ }
2068
+ }
2069
+ startedHorizontal = true;
2070
+ const slopedY = curY - hDist * slopeRatio;
2071
+ const dropFloorY = hasHeadForTarget ? Math.max(raw[1], minTargetY) : raw[1];
2072
+ if (dropFloorY < slopedY - 0.0001) {
2073
+ out.push([raw[0], slopedY, raw[2]]);
2074
+ out.push([raw[0], dropFloorY, raw[2]]);
2075
+ curY = dropFloorY;
2076
+ } else {
2077
+ out.push([raw[0], slopedY, raw[2]]);
2078
+ curY = slopedY;
2079
+ }
2080
+ }
2081
+ return out.length >= 2 ? compactPolyline(out) : [pts[0], [pts[pts.length - 1][0], curY, pts[pts.length - 1][2]]];
2082
+ }
2083
+ function shapeGravitySlope(rawPoints, minSlopeInPerFt, ctx, allowExteriorEndpointMargin) {
2084
+ const pts = compactPolyline(rawPoints);
2085
+ if (pts.length < 2) {
2086
+ return { path: pts, slopeInPerFt: undefined };
2087
+ }
2088
+ const slopeRatio = Math.max(0, minSlopeInPerFt) / 12;
2089
+ const remHorizM = new Float64Array(pts.length);
2090
+ for (let i = pts.length - 2;i >= 0; i--) {
2091
+ remHorizM[i] = remHorizM[i + 1] + distXZ2(pts[i], pts[i + 1]);
2092
+ }
2093
+ const totalInputHorizM = remHorizM[0];
2094
+ const fromY = pts[0][1];
2095
+ const toY = pts[pts.length - 1][1];
2096
+ const hasHeadForTarget = totalInputHorizM > 0.0001 && fromY >= toY + totalInputHorizM * slopeRatio - 0.000001;
2097
+ let finalPts;
2098
+ if (hasHeadForTarget) {
2099
+ const targetAnchored = buildGravitySlopedCandidate(pts, slopeRatio, remHorizM, toY, true, true);
2100
+ const trenchAnchored = buildGravitySlopedCandidate(pts, slopeRatio, remHorizM, toY, false, true);
2101
+ const evalTarget = evaluatePolyline(targetAnchored, ctx, allowExteriorEndpointMargin);
2102
+ const penTarget = evalPenalty(evalTarget);
2103
+ const evalTrench = evaluatePolyline(trenchAnchored, ctx, allowExteriorEndpointMargin);
2104
+ const penTrench = evalPenalty(evalTrench);
2105
+ if (penTrench < penTarget) {
2106
+ finalPts = trenchAnchored;
2107
+ } else if (penTarget < penTrench) {
2108
+ finalPts = targetAnchored;
2109
+ } else {
2110
+ finalPts = evalTarget.lengthM <= evalTrench.lengthM + 0.0001 ? targetAnchored : trenchAnchored;
2111
+ }
2112
+ } else {
2113
+ finalPts = buildGravitySlopedCandidate(pts, slopeRatio, remHorizM, toY, false, false);
2114
+ evaluatePolyline(finalPts, ctx, allowExteriorEndpointMargin);
2115
+ }
2116
+ let totalHorizM = 0;
2117
+ let totalHorizDropM = 0;
2118
+ for (let i = 1;i < finalPts.length; i++) {
2119
+ const a = finalPts[i - 1];
2120
+ const b = finalPts[i];
2121
+ const h = distXZ2(a, b);
2122
+ if (h > 0.0001) {
2123
+ totalHorizM += h;
2124
+ totalHorizDropM += a[1] - b[1];
2125
+ }
2126
+ }
2127
+ const slopeInPerFt = totalHorizM > 0.0001 ? round42(totalHorizDropM / totalHorizM * 12) : undefined;
2128
+ return { path: finalPts, slopeInPerFt };
2129
+ }
2130
+ function shapeNonDescendingVent(rawPoints, from, to, minHorizontalElevationM, ctx, allowExteriorEndpointMargin) {
2131
+ const pts = compactPolyline(rawPoints);
2132
+ if (pts.length < 2)
2133
+ return pts;
2134
+ const floorY = minHorizontalElevationM ?? from[1];
2135
+ const tieInY = to[1];
2136
+ const ceilingY = Math.max(floorY, tieInY);
2137
+ const out = [pts[0]];
2138
+ let curY = pts[0][1];
2139
+ for (let i = 1;i < pts.length; i++) {
2140
+ const prev = out[out.length - 1];
2141
+ const raw = pts[i];
2142
+ const hDist = distXZ2(prev, raw);
2143
+ const isLast = i === pts.length - 1;
2144
+ if (hDist < 0.0001) {
2145
+ const targetY = Math.max(curY, Math.min(raw[1], ceilingY));
2146
+ if (targetY > curY + 0.0001) {
2147
+ out.push([raw[0], targetY, raw[2]]);
2148
+ curY = targetY;
2149
+ }
2150
+ continue;
2151
+ }
2152
+ const clampedRawY = Math.min(raw[1], ceilingY);
2153
+ const horizY = Math.min(ceilingY, Math.max(curY, floorY, clampedRawY));
2154
+ if (horizY > curY + 0.0001) {
2155
+ out.push([prev[0], horizY, prev[2]]);
2156
+ curY = horizY;
2157
+ }
2158
+ out.push([raw[0], curY, raw[2]]);
2159
+ if (isLast && tieInY > curY + 0.0001) {
2160
+ out.push([raw[0], tieInY, raw[2]]);
2161
+ curY = tieInY;
2162
+ }
2163
+ }
2164
+ const shaped = compactPolyline(out);
2165
+ evaluatePolyline(shaped, ctx, allowExteriorEndpointMargin);
2166
+ return shaped;
2167
+ }
2168
+ function buildDisconnectedFallbackPath(from, to, mode, graph, allowedBands) {
2169
+ if (mode === "euclidean-cavity") {
2170
+ return compactPolyline([from, to]);
2171
+ }
2172
+ const primaryBand = allowedBands[0];
2173
+ const cruiseY = primaryBand === "attic" && graph.atticY !== null ? graph.atticY : (primaryBand === "under-slab" || primaryBand === "crawlspace") && graph.subFloorY !== null ? graph.subFloorY : primaryBand === "overhead-plenum" ? graph.ceilingPlenumY : mode === "gravity-slope" ? Math.min(from[1], to[1]) : Math.max(from[1], to[1]);
2174
+ const pts = [from];
2175
+ if (Math.abs(cruiseY - from[1]) > 0.03) {
2176
+ pts.push([from[0], cruiseY, from[2]]);
2177
+ }
2178
+ if (Math.abs(to[0] - from[0]) > 0.03 && Math.abs(to[2] - from[2]) > 0.03) {
2179
+ pts.push([to[0], cruiseY, from[2]]);
2180
+ }
2181
+ pts.push([to[0], cruiseY, to[2]]);
2182
+ if (Math.abs(to[1] - cruiseY) > 0.03) {
2183
+ pts.push(to);
2184
+ }
2185
+ return compactPolyline(pts);
2186
+ }
2187
+ function routeInLegalCavities2(params) {
2188
+ const { anatomy, graph, occupancy, request } = params;
2189
+ const from = sanitizeVec3(request.from);
2190
+ const to = sanitizeVec3(request.to);
2191
+ const halfXZ = Number.isFinite(request.halfXZ) ? Math.max(0, request.halfXZ) : 0;
2192
+ const halfY = Number.isFinite(request.halfY) ? Math.max(0, request.halfY) : 0;
2193
+ const clearanceM = Number.isFinite(request.clearanceM) ? Math.max(0, request.clearanceM) : 0;
2194
+ const roofClearanceM = typeof request.roofClearanceM === "number" && Number.isFinite(request.roofClearanceM) ? Math.max(0, request.roofClearanceM) : DEFAULT_ROOF_CLEARANCE_M2;
2195
+ const minSlopeInPerFt = typeof request.minSlopeInPerFt === "number" && Number.isFinite(request.minSlopeInPerFt) && request.minSlopeInPerFt >= 0 ? request.minSlopeInPerFt : DEFAULT_MIN_SLOPE_IN_PER_FT;
2196
+ const minHorizY = typeof request.minHorizontalElevationM === "number" && Number.isFinite(request.minHorizontalElevationM) ? request.minHorizontalElevationM : undefined;
2197
+ const openingPrisms = anatomy.getOpeningPrisms(graph.levelId);
2198
+ const roofShell = anatomy.getRoofShell(graph.levelId);
2199
+ const footprint = anatomy.getFootprint(graph.levelId);
2200
+ const walls = anatomy.getWalls(graph.levelId);
2201
+ const wallMap = new Map;
2202
+ for (const w of walls)
2203
+ wallMap.set(w.id, w);
2204
+ const allowedBandSet = new Set(request.allowedBands);
2205
+ const clashParams = {
2206
+ halfXZ,
2207
+ halfY,
2208
+ extraClearanceM: clearanceM,
2209
+ ignoreNodeIds: request.ignoreObstacleNodeIds
2210
+ };
2211
+ const encounteredObstacleIds = new Set;
2212
+ const ctx = {
2213
+ occupancy,
2214
+ clashParams,
2215
+ openingPrisms,
2216
+ roofShell,
2217
+ footprint,
2218
+ halfY,
2219
+ roofClearanceM,
2220
+ mode: request.mode,
2221
+ minHorizY,
2222
+ tieInY: to[1],
2223
+ encounteredObstacleIds
2224
+ };
2225
+ for (const obs of occupancy.segmentClashes(from, to, clashParams)) {
2226
+ encounteredObstacleIds.add(obs.nodeId);
2227
+ }
2228
+ if (dist32(from, to) < 0.0001) {
2229
+ const trivialPath = [roundVec3(from), roundVec3(to)];
2230
+ return finalizeRouteResult({
2231
+ path: trivialPath,
2232
+ bandsUsed: [],
2233
+ slopeInPerFt: undefined,
2234
+ encounteredObstacleIds,
2235
+ occupancy,
2236
+ clashParams,
2237
+ openingPrisms,
2238
+ roofShell,
2239
+ footprint,
2240
+ halfXZ,
2241
+ halfY,
2242
+ clearanceM,
2243
+ roofClearanceM,
2244
+ request
2245
+ });
2246
+ }
2247
+ let minBaseWeight = 1;
2248
+ if (typeof graph.minBaseWeight === "number" && Number.isFinite(graph.minBaseWeight) && graph.minBaseWeight > 0) {
2249
+ minBaseWeight = graph.minBaseWeight;
2250
+ } else {
2251
+ for (let u = 0;u < graph.adjacency.length; u++) {
2252
+ const edges = graph.adjacency[u];
2253
+ if (!edges)
2254
+ continue;
2255
+ for (let e = 0;e < edges.length; e++) {
2256
+ const w = edges[e].baseCostWeight;
2257
+ if (Number.isFinite(w) && w > 0 && w < minBaseWeight) {
2258
+ minBaseWeight = w;
2259
+ }
2260
+ }
2261
+ }
2262
+ }
2263
+ const minWeightScale = Math.max(0.1, minBaseWeight * (request.preferWallFollowing ? 0.85 : 1));
2264
+ const sharedDirect = resolveSharedDirectBand(from, to, graph, walls, allowedBandSet, request.mode);
2265
+ const skipWallDirectForStagger = sharedDirect?.isWall === true && request.mode === "orthogonal" && typeof request.lateralStaggerM === "number" && Math.abs(request.lateralStaggerM) > 0.0001;
2266
+ const directShortcut = sharedDirect && !skipWallDirectForStagger ? {
2267
+ eval: evaluatePolyline([from, to], ctx, false),
2268
+ band: sharedDirect.band,
2269
+ isWall: sharedDirect.isWall
2270
+ } : null;
2271
+ const startSplices = buildSpliceConnections(from, "enter", graph, allowedBandSet, wallMap, ctx);
2272
+ const goalSplices = buildSpliceConnections(to, "exit", graph, allowedBandSet, wallMap, ctx);
2273
+ const goalSplicesByVertex = new Map;
2274
+ for (const gs of goalSplices)
2275
+ goalSplicesByVertex.set(gs.vertexId, gs);
2276
+ const edgeCache = new Map;
2277
+ let searchResult = runConstrainedAStar({
2278
+ graph,
2279
+ from,
2280
+ to,
2281
+ allowedBandSet,
2282
+ request,
2283
+ startSplices,
2284
+ goalSplicesByVertex,
2285
+ directShortcut,
2286
+ edgeCache,
2287
+ ctx,
2288
+ minWeightScale,
2289
+ allowDegraded: false
2290
+ });
2291
+ if (!searchResult) {
2292
+ searchResult = runConstrainedAStar({
2293
+ graph,
2294
+ from,
2295
+ to,
2296
+ allowedBandSet,
2297
+ request,
2298
+ startSplices,
2299
+ goalSplicesByVertex,
2300
+ directShortcut,
2301
+ edgeCache,
2302
+ ctx,
2303
+ minWeightScale,
2304
+ allowDegraded: true
2305
+ });
2306
+ }
2307
+ let rawPath;
2308
+ let vertexBands;
2309
+ let bandsUsed;
2310
+ let wallIdsByPoint;
2311
+ if (searchResult) {
2312
+ rawPath = searchResult.waypoints;
2313
+ vertexBands = searchResult.vertexBands;
2314
+ bandsUsed = searchResult.bandsUsed;
2315
+ wallIdsByPoint = searchResult.wallIdsByPoint;
2316
+ } else {
2317
+ const fallbackPts = buildDisconnectedFallbackPath(from, to, request.mode, graph, request.allowedBands);
2318
+ const fallbackBand = request.allowedBands[0] ?? null;
2319
+ rawPath = fallbackPts;
2320
+ vertexBands = fallbackPts.map(() => fallbackBand);
2321
+ bandsUsed = fallbackBand ? [fallbackBand] : [];
2322
+ wallIdsByPoint = fallbackPts.map(() => {
2323
+ return;
2324
+ });
2325
+ }
2326
+ const hasExteriorEndpoint = !footprint.isPointInside(from[0], from[2]) || !footprint.isPointInside(to[0], to[2]);
2327
+ let shapedPath = compactPolyline(rawPath);
2328
+ let slopeInPerFt;
2329
+ if (request.mode === "orthogonal") {
2330
+ if (typeof request.lateralStaggerM === "number" && Math.abs(request.lateralStaggerM) > 0.0001) {
2331
+ shapedPath = applyLateralStagger(rawPath, wallIdsByPoint, request.lateralStaggerM, wallMap, ctx, request.maxBendDegrees);
2332
+ }
2333
+ shapedPath = compactPolyline(shapedPath);
2334
+ } else if (request.mode === "euclidean-cavity") {
2335
+ shapedPath = shapeEuclideanCavity(rawPath, vertexBands, ctx);
2336
+ } else if (request.mode === "gravity-slope") {
2337
+ const sloped = shapeGravitySlope(shapedPath, minSlopeInPerFt, ctx, hasExteriorEndpoint);
2338
+ shapedPath = sloped.path;
2339
+ slopeInPerFt = sloped.slopeInPerFt;
2340
+ } else if (request.mode === "non-descending-vent") {
2341
+ shapedPath = shapeNonDescendingVent(shapedPath, from, to, minHorizY, ctx, hasExteriorEndpoint);
2342
+ }
2343
+ const roundedPath = shapedPath.map(roundVec3);
2344
+ if (roundedPath.length === 0) {
2345
+ roundedPath.push(roundVec3(from), roundVec3(to));
2346
+ } else if (roundedPath.length === 1) {
2347
+ roundedPath.push(roundVec3(to));
2348
+ }
2349
+ return finalizeRouteResult({
2350
+ path: roundedPath,
2351
+ bandsUsed,
2352
+ slopeInPerFt,
2353
+ encounteredObstacleIds,
2354
+ occupancy,
2355
+ clashParams,
2356
+ openingPrisms,
2357
+ roofShell,
2358
+ footprint,
2359
+ halfXZ,
2360
+ halfY,
2361
+ clearanceM,
2362
+ roofClearanceM,
2363
+ request
2364
+ });
2365
+ }
2366
+ function finalizeRouteResult(params) {
2367
+ const {
2368
+ path,
2369
+ bandsUsed,
2370
+ slopeInPerFt,
2371
+ encounteredObstacleIds,
2372
+ occupancy,
2373
+ clashParams,
2374
+ openingPrisms,
2375
+ roofShell,
2376
+ footprint,
2377
+ halfXZ,
2378
+ halfY,
2379
+ clearanceM,
2380
+ roofClearanceM,
2381
+ request
2382
+ } = params;
2383
+ const pathClashes = occupancy.detectPathClashes(path, {
2384
+ ...clashParams,
2385
+ deduplicateByNode: true
2386
+ });
2387
+ const clashSet = new Set;
2388
+ for (const c of pathClashes)
2389
+ clashSet.add(c.obstacle.nodeId);
2390
+ const clashObstacleIds = [...clashSet];
2391
+ const avoidedObstacleIds = [];
2392
+ for (const id of encounteredObstacleIds) {
2393
+ if (!clashSet.has(id))
2394
+ avoidedObstacleIds.push(id);
2395
+ }
2396
+ const openingHits = countPathOpeningPrismHits2(path, openingPrisms, 0);
2397
+ const roofViolation = !roofShell.isPathClearOfRoof(path, halfY, roofClearanceM);
2398
+ const sanitizedFrom = sanitizeVec3(request.from);
2399
+ const sanitizedTo = sanitizeVec3(request.to);
2400
+ const hasExteriorEndpoint = !footprint.isPointInside(sanitizedFrom[0], sanitizedFrom[2]) || !footprint.isPointInside(sanitizedTo[0], sanitizedTo[2]);
2401
+ const outdoorVoidViolation = hasExteriorEndpoint ? footprint.pathCrossesOutdoorVoid(path, { skipExteriorEndpointMarginM: 0.35 }) : footprint.pathCrossesOutdoorVoid(path);
2402
+ const lengthM = round42(polylineLengthM2(path));
2403
+ const horizontalLengthM = round42(polylineHorizontalLengthM2(path));
2404
+ const bendDegrees = round22(countPathBendDegrees2(path));
2405
+ const { elbows90, elbows45 } = countPathElbows2(path);
2406
+ const elbowCount = elbows90 + elbows45;
2407
+ const bendViolation = typeof request.maxBendDegrees === "number" && Number.isFinite(request.maxBendDegrees) && bendDegrees > request.maxBendDegrees + 0.01;
2408
+ let physicsViolation = false;
2409
+ if (request.mode === "gravity-slope" && path.length >= 2) {
2410
+ const fromY = sanitizedFrom[1];
2411
+ const toY = sanitizedTo[1];
2412
+ const slopeRatio = (typeof request.minSlopeInPerFt === "number" && Number.isFinite(request.minSlopeInPerFt) && request.minSlopeInPerFt >= 0 ? request.minSlopeInPerFt : DEFAULT_MIN_SLOPE_IN_PER_FT) / 12;
2413
+ if (toY > fromY + UPHILL_TOL_M) {
2414
+ physicsViolation = true;
2415
+ }
2416
+ let pathHorizM = 0;
2417
+ for (let i = 1;i < path.length; i++) {
2418
+ const a = path[i - 1];
2419
+ const b = path[i];
2420
+ if (b[1] - a[1] > UPHILL_TOL_M) {
2421
+ physicsViolation = true;
2422
+ break;
2423
+ }
2424
+ pathHorizM += distXZ2(a, b);
2425
+ }
2426
+ if (!physicsViolation && fromY >= toY + pathHorizM * slopeRatio - 0.0001) {
2427
+ const lastPt = path[path.length - 1];
2428
+ if (Math.abs(lastPt[1] - toY) > 0.02) {
2429
+ physicsViolation = true;
2430
+ }
2431
+ }
2432
+ } else if (request.mode === "non-descending-vent" && path.length >= 2) {
2433
+ const toY = sanitizedTo[1];
2434
+ const minHorizY = typeof request.minHorizontalElevationM === "number" && Number.isFinite(request.minHorizontalElevationM) ? request.minHorizontalElevationM : undefined;
2435
+ for (let i = 1;i < path.length; i++) {
2436
+ const a = path[i - 1];
2437
+ const b = path[i];
2438
+ if (b[1] - a[1] < -UPHILL_TOL_M) {
2439
+ physicsViolation = true;
2440
+ break;
2441
+ }
2442
+ if (minHorizY !== undefined && distXZ2(a, b) > 0.01) {
2443
+ if (a[1] < minHorizY - 0.001 || b[1] < minHorizY - 0.001) {
2444
+ physicsViolation = true;
2445
+ break;
2446
+ }
2447
+ }
2448
+ }
2449
+ if (!physicsViolation) {
2450
+ const lastPt = path[path.length - 1];
2451
+ if (Math.abs(lastPt[1] - toY) > 0.02) {
2452
+ physicsViolation = true;
2453
+ }
2454
+ }
2455
+ }
2456
+ const ok = clashObstacleIds.length === 0 && openingHits === 0 && !roofViolation && !outdoorVoidViolation && !bendViolation && !physicsViolation;
2457
+ let reservationId;
2458
+ if (request.reserveOnCommit === true && path.length >= 2) {
2459
+ const runId = request.runId ?? `${request.trade}-run-${autoRunCounter++}`;
2460
+ reservationId = occupancy.reserveRun({
2461
+ runId,
2462
+ trade: request.trade,
2463
+ path,
2464
+ halfXZ,
2465
+ halfY,
2466
+ clearanceM
2467
+ });
2468
+ }
2469
+ return {
2470
+ ok,
2471
+ path,
2472
+ lengthM,
2473
+ horizontalLengthM,
2474
+ bendDegrees,
2475
+ elbowCount,
2476
+ bandsUsed,
2477
+ avoidedObstacleIds,
2478
+ clashObstacleIds,
2479
+ openingHits,
2480
+ roofViolation,
2481
+ outdoorVoidViolation,
2482
+ ...slopeInPerFt !== undefined ? { slopeInPerFt } : {},
2483
+ ...reservationId !== undefined ? { reservationId } : {}
2484
+ };
2485
+ }
2486
+ export { compileLegalCavityGraph2, findLegalWallRiserPier2, routeInLegalCavities2 };