@kruschdev/pascal-plugin-plumbing 0.0.0-stage → 0.2.1

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,2280 @@
1
+ /**
2
+ * Pure 3D Plumbing Routing Engine (`src/ipc/routing.ts`).
3
+ *
4
+ * Trade-Priority Hierarchy:
5
+ * 1. Structural (`structural:beam`, `structural:column`, `beam`, `column`) - inviolable
6
+ * 2. Plumbing (DWV gravity first, then Hot/Cold supply & Fuel Gas) - FIRST MEP right-of-way
7
+ * 3. HVAC (yields to plumbing)
8
+ * 4. Electrical (yields to plumbing & HVAC; Plumbing respects NEC 110.26(E) overhead panel keep-out)
9
+ *
10
+ * Framework-free: zero React, Three.js, or `@pascal-app/*` imports.
11
+ */
12
+
13
+ import {
14
+ type BuildingAnatomy,
15
+ type CanonicalWall,
16
+ type CavityBand,
17
+ type CavityRouteResult,
18
+ type LegalCavityGraph,
19
+ type OccupancyObstacle,
20
+ type RoutingPhysicsMode,
21
+ TradeOccupancyGrid,
22
+ compileBuildingAnatomy,
23
+ compileLegalCavityGraph,
24
+ compileLevelRoofShell,
25
+ countPathElbows as kernelCountPathElbows,
26
+ extractBaseRoomPolygons,
27
+ extractCanonicalWalls,
28
+ extractTradeOccupancyObstacles,
29
+ pointInPolygon2D as kernelPointInPolygon2D,
30
+ polygonAreaAndCentroid as kernelPolygonAreaAndCentroid,
31
+ polylineHorizontalLengthM as kernelPolylineHorizontalLengthM,
32
+ polylineLengthM as kernelPolylineLengthM,
33
+ resolveLevelHeightM as kernelResolveLevelHeightM,
34
+ routeInLegalCavities,
35
+ segmentIntersectsAabb3,
36
+ } from '@kruschdev/pascal-mep-kernel'
37
+ import { type SceneNodeLike, type Vec3, belongsToLevel } from './framing-interop'
38
+ import { IPC_RULE_THRESHOLDS } from './rules'
39
+ import { getMinRequiredDrainSlopeInPerFt } from './sizing'
40
+ import {
41
+ type FoundationType,
42
+ METERS_TO_FEET,
43
+ type OccupancyType,
44
+ type PipeMaterial,
45
+ type PipeNominalSize,
46
+ getPipeOuterDiameterM,
47
+ round2,
48
+ } from './tables'
49
+
50
+ export type Aabb3 = {
51
+ minX: number
52
+ minY: number
53
+ minZ: number
54
+ maxX: number
55
+ maxY: number
56
+ maxZ: number
57
+ }
58
+
59
+ export type PlumbingObstacle = {
60
+ id: string
61
+ /** Underlying scene node ID (shared across subdivided `:segN` boxes on diagonal beams). */
62
+ nodeId?: string
63
+ category: 'structural' | 'electrical-dedicated-space'
64
+ /** Structural member role so vertical columns are never treated as under-floor beams to duck beneath. */
65
+ structuralKind?: 'beam' | 'column'
66
+ /** Optional structural beam role (e.g. 'header', 'floor-girder', 'ridge-beam'). */
67
+ beamRole?: string
68
+ label: string
69
+ box: Aabb3
70
+ }
71
+
72
+ export type WallOpeningSpan = {
73
+ id: string
74
+ wallId: string
75
+ kind: 'door' | 'window'
76
+ name: string
77
+ /** Center distance along host wall from `wall.start` toward `wall.end` (meters). */
78
+ uCenterM: number
79
+ /** Rough opening width (meters). */
80
+ widthM: number
81
+ /** Start distance along host wall (meters). */
82
+ startU: number
83
+ /** End distance along host wall (meters). */
84
+ endU: number
85
+ /** Sill height above wall base (meters, 0 for doors). */
86
+ sillYM: number
87
+ /** Head height above wall base (meters). */
88
+ headYM: number
89
+ /** World-space horizontal center of opening along wall centerline. */
90
+ centerX: number
91
+ centerZ: number
92
+ }
93
+
94
+ export type WallSegment2D = {
95
+ id: string
96
+ start: readonly [number, number]
97
+ end: readonly [number, number]
98
+ lengthM: number
99
+ thicknessM: number
100
+ heightM: number
101
+ ux: number
102
+ uz: number
103
+ nx: number
104
+ nz: number
105
+ }
106
+
107
+ export type RoomPolygon2D = {
108
+ id: string
109
+ name: string
110
+ category:
111
+ | 'bathroom'
112
+ | 'master-bath'
113
+ | 'half-bath'
114
+ | 'kitchen'
115
+ | 'laundry'
116
+ | 'utility'
117
+ | 'garage'
118
+ | 'bedroom'
119
+ | 'living'
120
+ | 'exterior'
121
+ | 'commercial-restroom'
122
+ | 'commercial-kitchen'
123
+ | 'other'
124
+ polygon: ReadonlyArray<readonly [number, number]>
125
+ centroid: readonly [number, number]
126
+ areaSqm: number
127
+ areaSqft: number
128
+ }
129
+
130
+ export function polylineLengthM(path: ReadonlyArray<Vec3>): number {
131
+ return kernelPolylineLengthM(path)
132
+ }
133
+
134
+ export function polylineHorizontalLengthM(path: ReadonlyArray<Vec3>): number {
135
+ return kernelPolylineHorizontalLengthM(path)
136
+ }
137
+
138
+ export function countPathElbows(path: ReadonlyArray<Vec3>): { elbows90: number; elbows45: number } {
139
+ return kernelCountPathElbows(path)
140
+ }
141
+
142
+ /**
143
+ * Inspect a DWV drain path to verify monotonic gravity fall (no uphill segments)
144
+ * and compute effective horizontal slope (in/ft).
145
+ */
146
+ export function measureDrainPathSlope(path: ReadonlyArray<Vec3>): {
147
+ hasUphillSegment: boolean
148
+ minSegmentSlopeInPerFt: number
149
+ overallSlopeInPerFt: number
150
+ horizontalSegments: number
151
+ } {
152
+ let hasUphill = false
153
+ let minSlope = Infinity
154
+ let horizDistM = 0
155
+ let horizDropM = 0
156
+ let horizontalSegments = 0
157
+
158
+ for (let i = 1; i < path.length; i++) {
159
+ const a = path[i - 1]!
160
+ const b = path[i]!
161
+ const dx = b[0] - a[0]
162
+ const dy = b[1] - a[1]
163
+ const dz = b[2] - a[2]
164
+ const horiz = Math.hypot(dx, dz)
165
+ // Skip near-vertical risers / fixture drops (slope > 45°)
166
+ if (horiz < 0.05 || Math.abs(dy) > horiz * 0.85) {
167
+ // A vertical drop is always downward (dy <= 0); upward vertical on a drain is an error
168
+ if (dy > 0.02) hasUphill = true
169
+ continue
170
+ }
171
+ horizontalSegments += 1
172
+ horizDistM += horiz
173
+ horizDropM += -dy
174
+ if (dy > 0.002) {
175
+ hasUphill = true
176
+ minSlope = Math.min(minSlope, -(dy / horiz) * 12)
177
+ } else {
178
+ const slopeInPerFt = (-dy / horiz) * 12
179
+ minSlope = Math.min(minSlope, slopeInPerFt)
180
+ }
181
+ }
182
+
183
+ const overallSlopeInPerFt =
184
+ horizontalSegments > 0
185
+ ? horizDistM > 0.05
186
+ ? round2((horizDropM / horizDistM) * 12)
187
+ : round2(minSlope)
188
+ : 0.25
189
+ return {
190
+ hasUphillSegment: hasUphill,
191
+ minSegmentSlopeInPerFt: horizontalSegments > 0 ? round2(minSlope) : 0.25,
192
+ overallSlopeInPerFt,
193
+ horizontalSegments,
194
+ }
195
+ }
196
+
197
+ const wallSegmentsCache = new WeakMap<
198
+ Readonly<Record<string, SceneNodeLike>>,
199
+ Map<string, WallSegment2D[]>
200
+ >()
201
+
202
+ export function extractWallSegments(
203
+ nodes: Readonly<Record<string, SceneNodeLike>>,
204
+ levelId: string | null = null,
205
+ ): WallSegment2D[] {
206
+ const key = levelId ?? '__all__'
207
+ let byLevel = wallSegmentsCache.get(nodes)
208
+ if (!byLevel) {
209
+ byLevel = new Map()
210
+ wallSegmentsCache.set(nodes, byLevel)
211
+ }
212
+ const cached = byLevel.get(key)
213
+ if (cached) return cached
214
+
215
+ const walls: WallSegment2D[] = []
216
+ for (const n of Object.values(nodes)) {
217
+ if (n.type !== 'wall' || !belongsToLevel(nodes, n, levelId)) continue
218
+ if (!Array.isArray(n.start) || !Array.isArray(n.end)) continue
219
+ const sx = Number(n.start[0])
220
+ const sz = Number(n.start[1])
221
+ const ex = Number(n.end[0])
222
+ const ez = Number(n.end[1])
223
+ const len = Math.hypot(ex - sx, ez - sz)
224
+ if (!Number.isFinite(len) || len < 0.1) continue
225
+ const ux = (ex - sx) / len
226
+ const uz = (ez - sz) / len
227
+ walls.push({
228
+ id: n.id,
229
+ start: [sx, sz],
230
+ end: [ex, ez],
231
+ lengthM: len,
232
+ thicknessM: typeof n.thickness === 'number' && n.thickness > 0 ? n.thickness : 0.14,
233
+ heightM: typeof n.height === 'number' && n.height > 0 ? n.height : 2.6,
234
+ ux,
235
+ uz,
236
+ nx: -uz,
237
+ nz: ux,
238
+ })
239
+ }
240
+ byLevel.set(key, walls)
241
+ return walls
242
+ }
243
+
244
+ /**
245
+ * Map pre-extracted `CanonicalWall` openings (filtering walls with `lengthM >= 0.3`)
246
+ * directly into `WallOpeningSpan[]` without re-scanning scene nodes.
247
+ */
248
+ export function mapCanonicalWallsToOpenings(
249
+ walls: ReadonlyArray<CanonicalWall>,
250
+ ): WallOpeningSpan[] {
251
+ const out: WallOpeningSpan[] = []
252
+ for (const wall of walls) {
253
+ if (wall.lengthM < 0.3) continue
254
+ for (const op of wall.openings) {
255
+ out.push({
256
+ id: op.id,
257
+ wallId: op.wallId,
258
+ kind: op.kind,
259
+ name: op.name ?? op.kind,
260
+ uCenterM: op.uCenterM,
261
+ widthM: op.widthM,
262
+ startU: op.startU,
263
+ endU: op.endU,
264
+ sillYM: op.framedSillYM,
265
+ headYM: op.headYM,
266
+ centerX: op.centerX,
267
+ centerZ: op.centerZ,
268
+ })
269
+ }
270
+ }
271
+ return out
272
+ }
273
+
274
+ /**
275
+ * Extract all Pascal `door` and `window` opening spans along walls on a level
276
+ * (handling both native `door`/`window` nodes and wall-attached opening `item` nodes).
277
+ */
278
+ export function extractWallOpenings(
279
+ nodes: Readonly<Record<string, SceneNodeLike>>,
280
+ levelId: string | null = null,
281
+ ): WallOpeningSpan[] {
282
+ const walls = extractCanonicalWalls(nodes, levelId, { minLengthM: 0.3 })
283
+ if (walls.length === 0) return []
284
+ return mapCanonicalWallsToOpenings(walls)
285
+ }
286
+
287
+ export function classifyRoomName(
288
+ name: string,
289
+ occupancy: OccupancyType = 'residential',
290
+ ): RoomPolygon2D['category'] {
291
+ const s = name
292
+ .toLowerCase()
293
+ .normalize('NFD')
294
+ .replace(/[\u0300-\u036f]/g, '')
295
+ .replace(/[\u2018\u2019`]/g, "'")
296
+ const hasIndoorTerm =
297
+ /bath|shower|restroom|powder|ensuite|en-suite|\bwc\d*\b|toilet|salle\s+de\s+bains?|salle\s+d'eau|salle\s+de\s+douche|\bbad\b|badezimmer|\bbano\b|\bbagno\b|kitchen|cuisine|cocina|cucina|\bkuche\b|\bkueche\b|laundry|buanderie|lavanderia|utility|bedroom|\bchambre\b|living|dining|office/.test(
298
+ s,
299
+ )
300
+ if (
301
+ !hasIndoorTerm &&
302
+ /\bpool\b|swimming|piscine|porch|patio|deck|balcony|yard|lanai|courtyard|garden|driveway|exterior|\bbalcon\b|\bterrasse\b|\bterrace\b|\bterraza\b|\bspawn\b/.test(
303
+ s,
304
+ )
305
+ ) {
306
+ return 'exterior'
307
+ }
308
+ if (/commercial.*restroom|mens|womens|public.*(bath|restroom)/.test(s)) return 'commercial-restroom'
309
+ if (/restroom/.test(s)) return occupancy === 'commercial' ? 'commercial-restroom' : 'bathroom'
310
+ if (/commercial.*kitchen|prep.*kitchen|scullery/.test(s)) return 'commercial-kitchen'
311
+ if (/master.*bath|primary.*bath|ensuite|en-suite/.test(s)) return 'master-bath'
312
+ if (/half.*bath|powder/.test(s)) return 'half-bath'
313
+ if (
314
+ /bath|shower|salle\s+de\s+bains?|salle\s+d'eau|salle\s+de\s+douche|\bbad\b|badezimmer|\bbano\b|cuarto\s+de\s+bano|\bbagno\b/.test(
315
+ s,
316
+ )
317
+ ) {
318
+ return 'bathroom'
319
+ }
320
+ if (/\bwc\d*\b|\btoilettes?\b|\baseo\b/.test(s)) return 'half-bath'
321
+ if (/toilet/.test(s)) return 'bathroom'
322
+ if (/kitchen|pantry|cuisine|cocina|cucina|\bkuche\b|\bkueche\b/.test(s)) return 'kitchen'
323
+ if (/laundry|mudroom|washer|buanderie|waschkuche|waschkueche|lavanderia|hauswirtschaftsraum/.test(s)) {
324
+ return 'laundry'
325
+ }
326
+ if (/utility|mech|boiler|furnace|storage/.test(s)) return 'utility'
327
+ if (/garage|carport/.test(s)) return 'garage'
328
+ if (/bed|nursery|guest|\bchambre\b|schlafzimmer|dormitorio/.test(s)) return 'bedroom'
329
+ if (/living|great|family|dining|office|den|hall|\bsalon\b|\bsejour\b|wohnzimmer|\bbureau\b/.test(s)) return 'living'
330
+ return 'other'
331
+ }
332
+
333
+ export function polygonAreaAndCentroid(
334
+ polygon: ReadonlyArray<readonly [number, number]>,
335
+ ): { areaSqm: number; centroid: readonly [number, number] } {
336
+ if (polygon.length < 3) return { areaSqm: 0, centroid: [0, 0] }
337
+ const { areaSqM, centroid } = kernelPolygonAreaAndCentroid(polygon)
338
+ return { areaSqm: areaSqM, centroid }
339
+ }
340
+
341
+ export function pointInPolygon2D(
342
+ x: number,
343
+ z: number,
344
+ polygon: ReadonlyArray<readonly [number, number]>,
345
+ ): boolean {
346
+ return kernelPointInPolygon2D(x, z, polygon)
347
+ }
348
+
349
+ export function extractRoomPolygons(
350
+ nodes: Readonly<Record<string, SceneNodeLike>>,
351
+ levelId: string | null = null,
352
+ occupancy: OccupancyType = 'residential',
353
+ ): RoomPolygon2D[] {
354
+ return extractBaseRoomPolygons(nodes, levelId).map((base) => {
355
+ const classifyText = `${base.rawCategory} ${base.name}`.trim()
356
+ return {
357
+ id: base.id,
358
+ name: base.name,
359
+ category: classifyRoomName(classifyText, occupancy),
360
+ polygon: base.polygon,
361
+ centroid: base.centroid,
362
+ areaSqm: round2(base.areaSqM),
363
+ areaSqft: round2(base.areaSqFt),
364
+ }
365
+ })
366
+ }
367
+
368
+ export function resolveLevelHeightM(
369
+ nodes: Readonly<Record<string, SceneNodeLike>>,
370
+ levelId: string | null = null,
371
+ ): number {
372
+ return kernelResolveLevelHeightM(nodes, levelId)
373
+ }
374
+
375
+ export type BuildingBounds2D = {
376
+ minX: number
377
+ maxX: number
378
+ minZ: number
379
+ maxZ: number
380
+ }
381
+
382
+ /**
383
+ * Estimate pitched gable roof soffit/ridge elevation at `(x, z)` over the walled building footprint.
384
+ */
385
+ export function estimateGableRoofYAt(
386
+ x: number,
387
+ z: number,
388
+ bounds: BuildingBounds2D,
389
+ wallH: number,
390
+ pitchRiseOver12 = 6,
391
+ ): number {
392
+ const spanX = bounds.maxX - bounds.minX
393
+ const spanZ = bounds.maxZ - bounds.minZ
394
+ if (spanX <= 0.1 || spanZ <= 0.1) return wallH
395
+ const ridgeAlongX = spanX >= spanZ
396
+ const halfSpan = (ridgeAlongX ? spanZ : spanX) / 2
397
+ const center = ridgeAlongX ? (bounds.minZ + bounds.maxZ) / 2 : (bounds.minX + bounds.maxX) / 2
398
+ const distFromRidge = Math.abs((ridgeAlongX ? z : x) - center)
399
+ const riseM = Math.max(0, halfSpan - distFromRidge) * (pitchRiseOver12 / 12)
400
+ return wallH + riseM
401
+ }
402
+
403
+ /**
404
+ * Build a roof-surface evaluator `roofYAt(x, z)` for plumbing clearance checks on `levelId`.
405
+ * Delegates to `@kruschdev/pascal-mep-kernel`'s `compileLevelRoofShell`, supporting all 7 Pascal
406
+ * roof types (`flat`, `shed`, `gable`, `hip`, `dutch`, `mansard`, `conical`), story-ordinal
407
+ * vertical ordering, spatial wall-less roof-level adoption, `pitch === 0` flat behavior, and
408
+ * lower-story flat `wallH` fallback.
409
+ */
410
+ export function buildPlumbingRoofYAt(
411
+ nodes: Readonly<Record<string, SceneNodeLike>>,
412
+ levelId: string | null,
413
+ bounds: BuildingBounds2D,
414
+ wallH: number,
415
+ pitchRiseOver12 = 6,
416
+ ): (x: number, z: number) => number {
417
+ const shell = compileLevelRoofShell(nodes, levelId, wallH, {
418
+ wallBounds: bounds,
419
+ fallbackPitchRiseOver12: pitchRiseOver12,
420
+ clampOverhangToEave: true,
421
+ })
422
+ return shell.roofEnvelopeY
423
+ }
424
+
425
+ /**
426
+ * Map pre-extracted kernel `OccupancyObstacle[]` into `PlumbingObstacle[]`,
427
+ * subdividing diagonal structural beams once into tight AABB segments.
428
+ */
429
+ export function mapOccupancyObstaclesToPlumbing(
430
+ kernelObstacles: ReadonlyArray<OccupancyObstacle>,
431
+ ): PlumbingObstacle[] {
432
+ const obstacles: PlumbingObstacle[] = []
433
+
434
+ for (const occ of kernelObstacles) {
435
+ if (occ.kind === 'structural-beam' && occ.prism) {
436
+ const p = occ.prism
437
+ const sx = p.centerX + p.lxMin * p.cos
438
+ const sz = p.centerZ + p.lxMin * p.sin
439
+ const ex = p.centerX + p.lxMax * p.cos
440
+ const ez = p.centerZ + p.lxMax * p.sin
441
+ if (Math.abs(ex - sx) > 0.2 && Math.abs(ez - sz) > 0.2) {
442
+ const halfW = (p.lzMax - p.lzMin) / 2
443
+ const len = p.lxMax - p.lxMin
444
+ const steps = Math.max(2, Math.min(24, Math.ceil(len / 0.6)))
445
+ for (let i = 0; i < steps; i++) {
446
+ const t0 = i / steps
447
+ const t1 = (i + 1) / steps
448
+ const x0 = sx + (ex - sx) * t0
449
+ const z0 = sz + (ez - sz) * t0
450
+ const x1 = sx + (ex - sx) * t1
451
+ const z1 = sz + (ez - sz) * t1
452
+ obstacles.push({
453
+ id: `${occ.id}:seg${i}`,
454
+ nodeId: occ.nodeId,
455
+ category: 'structural',
456
+ structuralKind: 'beam',
457
+ ...(occ.beamRole ? { beamRole: occ.beamRole } : {}),
458
+ label: occ.label,
459
+ box: {
460
+ minX: Math.min(x0, x1) - halfW,
461
+ maxX: Math.max(x0, x1) + halfW,
462
+ minY: p.yMin,
463
+ maxY: p.yMax,
464
+ minZ: Math.min(z0, z1) - halfW,
465
+ maxZ: Math.max(z0, z1) + halfW,
466
+ },
467
+ })
468
+ }
469
+ continue
470
+ }
471
+ }
472
+
473
+ const category: PlumbingObstacle['category'] =
474
+ occ.kind === 'electrical-dedicated-space' ? 'electrical-dedicated-space' : 'structural'
475
+ obstacles.push({
476
+ id: occ.id,
477
+ nodeId: occ.nodeId,
478
+ category,
479
+ ...(occ.structuralKind ? { structuralKind: occ.structuralKind } : {}),
480
+ ...(occ.beamRole ? { beamRole: occ.beamRole } : {}),
481
+ label: occ.label,
482
+ box: { ...occ.aabb },
483
+ })
484
+ }
485
+
486
+ return obstacles
487
+ }
488
+
489
+ /**
490
+ * Extract Priority #1 Structural obstacles AND NEC 110.26(E) Dedicated Electrical Space columns
491
+ * (footprint of any `electrical:panel` or `electrical:transformer` extending from floor to structural ceiling).
492
+ */
493
+ export function extractPlumbingObstacles(
494
+ nodes: Readonly<Record<string, SceneNodeLike>>,
495
+ levelId: string | null = null,
496
+ ): PlumbingObstacle[] {
497
+ const kernelObstacles = extractTradeOccupancyObstacles(nodes, levelId, {
498
+ forTrade: 'plumbing',
499
+ })
500
+ return mapOccupancyObstaclesToPlumbing(kernelObstacles)
501
+ }
502
+
503
+ export function segmentIntersectsAabb(a: Vec3, b: Vec3, box: Aabb3, margin = 0.02): boolean {
504
+ return segmentIntersectsAabb3(a, b, box, margin)
505
+ }
506
+
507
+ export function detectPlumbingClashes(
508
+ path: ReadonlyArray<Vec3>,
509
+ obstacles: ReadonlyArray<PlumbingObstacle>,
510
+ pipeRadiusM = 0.025,
511
+ ): PlumbingObstacle[] {
512
+ const hits: PlumbingObstacle[] = []
513
+ const seen = new Set<string>()
514
+ for (let i = 1; i < path.length; i++) {
515
+ const a = path[i - 1]!
516
+ const b = path[i]!
517
+ for (const obs of obstacles) {
518
+ const dedupeKey = obs.nodeId ?? obs.id.replace(/:seg\d+$/, '')
519
+ if (seen.has(dedupeKey)) continue
520
+ if (segmentIntersectsAabb(a, b, obs.box, pipeRadiusM + 0.02)) {
521
+ seen.add(dedupeKey)
522
+ hits.push(obs)
523
+ }
524
+ }
525
+ }
526
+ return hits
527
+ }
528
+
529
+ export function nearestWallToPoint(
530
+ x: number,
531
+ z: number,
532
+ walls: ReadonlyArray<WallSegment2D>,
533
+ ): { wall: WallSegment2D; t: number; point: readonly [number, number]; distanceM: number } | null {
534
+ let best: { wall: WallSegment2D; t: number; point: readonly [number, number]; distanceM: number } | null =
535
+ null
536
+ for (const wall of walls) {
537
+ const dx = x - wall.start[0]
538
+ const dz = z - wall.start[1]
539
+ const rawT = (dx * wall.ux + dz * wall.uz) / wall.lengthM
540
+ const t = Math.max(0.08, Math.min(0.92, rawT))
541
+ const px = wall.start[0] + wall.ux * wall.lengthM * t
542
+ const pz = wall.start[1] + wall.uz * wall.lengthM * t
543
+ const dist = Math.hypot(x - px, z - pz)
544
+ if (!best || dist < best.distanceM) {
545
+ best = { wall, t, point: [px, pz], distanceM: dist }
546
+ }
547
+ }
548
+ return best
549
+ }
550
+
551
+ /**
552
+ * Deduplicate consecutive nearly identical waypoints while preserving 0.1 mm (0.0001 m) elevation precision
553
+ * so 1/4"/ft (2.08%) gravity slopes are never quantized below code minimums even on short horizontal legs.
554
+ */
555
+ function cleanPath(pts: Vec3[]): Vec3[] {
556
+ const r4 = (v: number) => Math.round(v * 10000) / 10000
557
+ const out: Vec3[] = []
558
+ for (let i = 0; i < pts.length; i++) {
559
+ const p = pts[i]!
560
+ const prev = out[out.length - 1]
561
+ const dist = prev ? Math.hypot(p[0] - prev[0], p[1] - prev[1], p[2] - prev[2]) : Number.POSITIVE_INFINITY
562
+ if (!prev || dist > 0.008) {
563
+ out.push([r4(p[0]), r4(p[1]), r4(p[2])])
564
+ } else if (i === pts.length - 1 && (dist > 1e-4 || out.length === 1)) {
565
+ // Preserve exact final destination endpoint without tilting the preceding orthogonal segment
566
+ out.push([r4(p[0]), r4(p[1]), r4(p[2])])
567
+ }
568
+ }
569
+ return out
570
+ }
571
+
572
+ function isUnderFloorBeamObstacle(o: PlumbingObstacle): boolean {
573
+ return (
574
+ o.category === 'structural' &&
575
+ (o.structuralKind === 'beam' ||
576
+ (!o.structuralKind && !/column/i.test(o.label) && o.box.maxY <= 0.25)) &&
577
+ o.box.minY < 0
578
+ )
579
+ }
580
+
581
+ function isElevatedBeamObstacle(o: PlumbingObstacle): boolean {
582
+ return (
583
+ o.category === 'structural' &&
584
+ (o.structuralKind === 'beam' || o.beamRole === 'header' || /header|beam|ridge/i.test(o.label)) &&
585
+ o.box.maxY > 0.5
586
+ )
587
+ }
588
+
589
+ /**
590
+ * Given a vertical riser/drop at `(x, z)` that collides with one or more obstacles,
591
+ * generate up to `maxCandidates` (default 8) closest lateral `(x', z')` jog positions just outside the colliding AABBs.
592
+ */
593
+ function buildLateralEscapeCandidates(
594
+ x: number,
595
+ z: number,
596
+ hits: ReadonlyArray<PlumbingObstacle>,
597
+ clearPad: number,
598
+ maxCandidates = 8,
599
+ ): Array<readonly [number, number]> {
600
+ const candidates: Array<readonly [number, number, number]> = []
601
+ const seen = new Set<string>()
602
+ const add = (cx: number, cz: number) => {
603
+ const k = `${Math.round(cx * 100)},${Math.round(cz * 100)}`
604
+ if (seen.has(k)) return
605
+ seen.add(k)
606
+ candidates.push([cx, cz, Math.hypot(cx - x, cz - z)])
607
+ }
608
+ for (const obs of hits) {
609
+ // Try shortest escapes along X and Z past the obstacle's jambs / faces
610
+ const leftX = obs.box.minX - clearPad
611
+ const rightX = obs.box.maxX + clearPad
612
+ const backZ = obs.box.minZ - clearPad
613
+ const frontZ = obs.box.maxZ + clearPad
614
+ add(leftX, z)
615
+ add(rightX, z)
616
+ add(x, backZ)
617
+ add(x, frontZ)
618
+ // Also try diagonal corners in case two beams meet at a corner/post
619
+ add(leftX, backZ)
620
+ add(leftX, frontZ)
621
+ add(rightX, backZ)
622
+ add(rightX, frontZ)
623
+ }
624
+ candidates.sort((a, b) => a[2] - b[2])
625
+ return candidates.slice(0, maxCandidates).map(([cx, cz]) => [cx, cz] as const)
626
+ }
627
+
628
+ function resolveAllowedEnvelope(
629
+ buildingBounds: BuildingBounds2D | undefined,
630
+ from: Vec3,
631
+ toXZ: readonly [number, number],
632
+ margin = 0.08,
633
+ ): BuildingBounds2D | null {
634
+ if (!buildingBounds) return null
635
+ const innerMinX = buildingBounds.minX + margin
636
+ const innerMaxX = buildingBounds.maxX - margin
637
+ const innerMinZ = buildingBounds.minZ + margin
638
+ const innerMaxZ = buildingBounds.maxZ - margin
639
+ return {
640
+ minX: Math.min(innerMinX <= innerMaxX ? innerMinX : buildingBounds.minX, from[0], toXZ[0]),
641
+ maxX: Math.max(innerMinX <= innerMaxX ? innerMaxX : buildingBounds.maxX, from[0], toXZ[0]),
642
+ minZ: Math.min(innerMinZ <= innerMaxZ ? innerMinZ : buildingBounds.minZ, from[2], toXZ[1]),
643
+ maxZ: Math.max(innerMinZ <= innerMaxZ ? innerMaxZ : buildingBounds.maxZ, from[2], toXZ[1]),
644
+ }
645
+ }
646
+
647
+ function exceedsEnvelopeXZ(path: ReadonlyArray<Vec3>, env: BuildingBounds2D | null): boolean {
648
+ if (!env) return false
649
+ for (const p of path) {
650
+ if (p[0] < env.minX - 1e-4 || p[0] > env.maxX + 1e-4 || p[2] < env.minZ - 1e-4 || p[2] > env.maxZ + 1e-4) {
651
+ return true
652
+ }
653
+ }
654
+ return false
655
+ }
656
+
657
+ function minRoofAlongPath(
658
+ path: ReadonlyArray<Vec3>,
659
+ maxRoofYAt?: (x: number, z: number) => number,
660
+ ): number {
661
+ if (!maxRoofYAt) return Infinity
662
+ let minY = Infinity
663
+ for (let i = 1; i < path.length; i++) {
664
+ const a = path[i - 1]!
665
+ const b = path[i]!
666
+ const segLen = Math.hypot(b[0] - a[0], b[2] - a[2])
667
+ const steps = Math.max(4, Math.min(64, Math.ceil(segLen / 0.25)))
668
+ for (let s = 0; s <= steps; s++) {
669
+ const f = s / steps
670
+ const px = a[0] + (b[0] - a[0]) * f
671
+ const pz = a[2] + (b[2] - a[2]) * f
672
+ const ry = maxRoofYAt(px, pz)
673
+ if (ry < minY) minY = ry
674
+ }
675
+ }
676
+ return minY
677
+ }
678
+
679
+ function exceedsRoofPlane(
680
+ path: ReadonlyArray<Vec3>,
681
+ pipeRadiusM: number,
682
+ maxRoofYAt?: (x: number, z: number) => number,
683
+ ): boolean {
684
+ if (!maxRoofYAt) return false
685
+ for (let i = 1; i < path.length; i++) {
686
+ const a = path[i - 1]!
687
+ const b = path[i]!
688
+ const segLen = Math.hypot(b[0] - a[0], b[2] - a[2])
689
+ const steps = Math.max(4, Math.min(64, Math.ceil(segLen / 0.25)))
690
+ for (let s = 0; s <= steps; s++) {
691
+ const f = s / steps
692
+ const px = a[0] + (b[0] - a[0]) * f
693
+ const py = a[1] + (b[1] - a[1]) * f
694
+ const pz = a[2] + (b[2] - a[2]) * f
695
+ if (py + pipeRadiusM > maxRoofYAt(px, pz) - 0.08 + 1e-4) return true
696
+ }
697
+ }
698
+ return false
699
+ }
700
+
701
+ /**
702
+ * Generate obstacle-aware horizontal detour waypoint lists around colliding columns/panels/beams.
703
+ */
704
+ function buildObstacleDetourWaypoints(
705
+ startXZ: readonly [number, number],
706
+ endXZ: readonly [number, number],
707
+ hits: ReadonlyArray<PlumbingObstacle>,
708
+ edgePad: number,
709
+ ): Array<Array<readonly [number, number]>> {
710
+ const out: Array<Array<readonly [number, number]>> = []
711
+ const [sx, sz] = startXZ
712
+ const [ex, ez] = endXZ
713
+ for (const obs of hits) {
714
+ const lx = obs.box.minX - edgePad
715
+ const rx = obs.box.maxX + edgePad
716
+ const bz = obs.box.minZ - edgePad
717
+ const fz = obs.box.maxZ + edgePad
718
+ out.push(
719
+ [[lx, sz], [lx, ez], [ex, ez]],
720
+ [[rx, sz], [rx, ez], [ex, ez]],
721
+ [[sx, bz], [ex, bz], [ex, ez]],
722
+ [[sx, fz], [ex, fz], [ex, ez]],
723
+ [[lx, bz], [ex, bz], [ex, ez]],
724
+ [[rx, fz], [ex, fz], [ex, ez]],
725
+ [[lx, fz], [ex, fz], [ex, ez]],
726
+ [[rx, bz], [ex, bz], [ex, ez]],
727
+ )
728
+ }
729
+ return out
730
+ }
731
+
732
+ export type PlumbingCavityContext = {
733
+ /** Pascal scene nodes (used to compile WeakMap-memoized BuildingAnatomy if `anatomy` is omitted). */
734
+ nodes?: Readonly<Record<string, SceneNodeLike>>
735
+ levelId?: string | null
736
+ /** Pre-compiled BuildingAnatomy (optional). */
737
+ anatomy?: BuildingAnatomy
738
+ /** Pre-compiled LegalCavityGraph (optional — compiled on demand if omitted). */
739
+ graph?: LegalCavityGraph
740
+ /** Pre-populated TradeOccupancyGrid (optional — created on demand if omitted). */
741
+ occupancy?: TradeOccupancyGrid
742
+ }
743
+
744
+ export type RoutePlumbingViaLegalCavityParams = PlumbingCavityContext & {
745
+ from: Vec3
746
+ to: Vec3
747
+ mode: RoutingPhysicsMode
748
+ nominalSize?: PipeNominalSize
749
+ material?: PipeMaterial
750
+ pipeRadiusM?: number
751
+ clearanceM?: number
752
+ allowedBands?: readonly CavityBand[]
753
+ /** Gravity drain minimum slope (in/ft) for `'gravity-slope'` mode. */
754
+ minSlopeInPerFt?: number
755
+ /** Fixture flood-level rim (m) for `'non-descending-vent'` mode (IPC 905.5). */
756
+ floodRimHeightM?: number
757
+ /** Minimum elevation (m) for horizontal legs (overrides `floodRimHeightM + 0.1524 m` when higher). */
758
+ minHorizontalElevationM?: number
759
+ /** Clearance below roof surface (m). Default `0.10`. */
760
+ roofClearanceM?: number
761
+ /** Prefer wall cavities over open plenum corridors when true. */
762
+ preferWallFollowing?: boolean
763
+ /** Foundation hint used for default cavity bands and sub-floor elevation. */
764
+ foundationType?: FoundationType
765
+ /** Sub-floor trench elevation (m) when compiling a cavity graph on demand. */
766
+ subFloorElevationM?: number
767
+ /** Optional extra obstacles (reserved into occupancy grid when `occupancy` is not pre-supplied). */
768
+ obstacles?: ReadonlyArray<PlumbingObstacle>
769
+ /** Reserve the resulting run in `occupancy` (`INV-MEP-07`). */
770
+ reserveOnCommit?: boolean
771
+ runId?: string
772
+ }
773
+
774
+ export type PlumbingCavityRouteResult = CavityRouteResult & {
775
+ readonly path: Vec3[]
776
+ readonly lengthFt: number
777
+ }
778
+
779
+ function hasCavityScene(ctx?: PlumbingCavityContext): boolean {
780
+ if (!ctx) return false
781
+ if (ctx.graph && ctx.graph.vertices.length > 0) return true
782
+ if (ctx.anatomy) return true
783
+ if (ctx.nodes && Object.keys(ctx.nodes).length > 0) return true
784
+ return false
785
+ }
786
+
787
+ function closestPointOnWalls2D(
788
+ x: number,
789
+ z: number,
790
+ walls: ReadonlyArray<WallSegment2D>,
791
+ ): { wall: WallSegment2D; t: number; point: readonly [number, number]; distanceM: number } | null {
792
+ let best: { wall: WallSegment2D; t: number; point: readonly [number, number]; distanceM: number } | null = null
793
+ for (const wall of walls) {
794
+ const dx = x - wall.start[0]
795
+ const dz = z - wall.start[1]
796
+ const rawT = (dx * wall.ux + dz * wall.uz) / wall.lengthM
797
+ const t = Math.max(0, Math.min(1, rawT))
798
+ const px = wall.start[0] + wall.ux * wall.lengthM * t
799
+ const pz = wall.start[1] + wall.uz * wall.lengthM * t
800
+ const dist = Math.hypot(x - px, z - pz)
801
+ if (!best || dist < best.distanceM) {
802
+ best = { wall, t, point: [px, pz], distanceM: dist }
803
+ }
804
+ }
805
+ return best
806
+ }
807
+
808
+ const cachedAnatomyByNodes = new WeakMap<Readonly<Record<string, SceneNodeLike>>, BuildingAnatomy>()
809
+
810
+ function resolveAnatomyForContext(ctx?: PlumbingCavityContext): BuildingAnatomy | undefined {
811
+ if (!ctx) return undefined
812
+ if (ctx.anatomy) return ctx.anatomy
813
+ if (!ctx.nodes) return undefined
814
+ let cached = cachedAnatomyByNodes.get(ctx.nodes)
815
+ if (!cached) {
816
+ cached = compileBuildingAnatomy(ctx.nodes)
817
+ cachedAnatomyByNodes.set(ctx.nodes, cached)
818
+ }
819
+ return cached
820
+ }
821
+
822
+ function toWallSegment2D(w: CanonicalWall): WallSegment2D {
823
+ return {
824
+ id: w.id,
825
+ start: w.start,
826
+ end: w.end,
827
+ lengthM: w.lengthM,
828
+ thicknessM: w.thicknessM,
829
+ heightM: w.heightM,
830
+ ux: w.ux,
831
+ uz: w.uz,
832
+ nx: w.nx,
833
+ nz: w.nz,
834
+ }
835
+ }
836
+
837
+ function isSegmentAlongWalls(
838
+ a: Vec3,
839
+ b: Vec3,
840
+ walls: ReadonlyArray<WallSegment2D>,
841
+ ): boolean {
842
+ const maxY = Math.max(a[1], b[1])
843
+ const horiz = Math.hypot(b[0] - a[0], b[2] - a[2])
844
+ if (horiz < 1e-4) {
845
+ const nw = closestPointOnWalls2D(a[0], a[2], walls)
846
+ return Boolean(
847
+ nw &&
848
+ nw.distanceM <= Math.max(0.14, nw.wall.thicknessM / 2 + 0.06) &&
849
+ maxY <= nw.wall.heightM + 0.05,
850
+ )
851
+ }
852
+ const samples = Math.max(4, Math.ceil(horiz / 0.25) + 1)
853
+ for (let s = 0; s <= samples; s++) {
854
+ const t = s / samples
855
+ const sx = a[0] + (b[0] - a[0]) * t
856
+ const sy = a[1] + (b[1] - a[1]) * t
857
+ const sz = a[2] + (b[2] - a[2]) * t
858
+ const nw = closestPointOnWalls2D(sx, sz, walls)
859
+ if (
860
+ !nw ||
861
+ nw.distanceM > Math.max(0.14, nw.wall.thicknessM / 2 + 0.06) ||
862
+ sy > nw.wall.heightM + 0.05
863
+ ) {
864
+ return false
865
+ }
866
+ }
867
+ return true
868
+ }
869
+
870
+ function exceedsConcaveFootprint(
871
+ path: ReadonlyArray<Vec3>,
872
+ ctx: PlumbingCavityContext | undefined,
873
+ enforce: boolean,
874
+ ): boolean {
875
+ if (!enforce || !ctx || path.length < 2) return false
876
+ const anatomy = resolveAnatomyForContext(ctx)
877
+ if (!anatomy) return false
878
+ const levelId = ctx.levelId ?? null
879
+ const rawWalls = anatomy.getWalls(levelId)
880
+ if (rawWalls.length === 0) return false
881
+ const footprint = anatomy.getFootprint(levelId)
882
+ // Only enforce concave void exclusion when the level actually has enclosed faces or room polygons
883
+ if (!footprint.boundedFacesComplete && footprint.roomPolygons.length === 0) return false
884
+ const wallSegs: WallSegment2D[] = rawWalls.map(toWallSegment2D)
885
+ for (let i = 1; i < path.length; i++) {
886
+ const a = path[i - 1]!
887
+ const b = path[i]!
888
+ // Sub-slab / underground trenches (y <= 0.05 m) do not float in mid-air over outdoor notches
889
+ if (a[1] <= 0.05 && b[1] <= 0.05) continue
890
+ // A segment traveling strictly inside solid building wall cavities is never floating over an outdoor notch
891
+ if (isSegmentAlongWalls(a, b, wallSegs)) continue
892
+ if (
893
+ !footprint.isSegmentInside(a, b, {
894
+ precedence: 'room-first',
895
+ wallToleranceM: 0.45,
896
+ skipExteriorEndpointMarginM: 0.45,
897
+ })
898
+ ) {
899
+ return true
900
+ }
901
+ }
902
+ return false
903
+ }
904
+
905
+ function isVentPathCodeCompliant(path: ReadonlyArray<Vec3>, minHorizontalY: number): boolean {
906
+ if (path.length < 2) return false
907
+ for (let i = 1; i < path.length; i++) {
908
+ const a = path[i - 1]!
909
+ const b = path[i]!
910
+ // IPC 905.2: dry vent must never descend (zero inverted-U condensate traps)
911
+ if (b[1] < a[1] - 0.002) return false
912
+ // IPC 905.5: horizontal dry vent leg must remain >= 6" above flood-level rim
913
+ const horiz = Math.hypot(b[0] - a[0], b[2] - a[2])
914
+ if (horiz > 0.25 && Math.min(a[1], b[1]) < minHorizontalY - 0.02) return false
915
+ }
916
+ return true
917
+ }
918
+
919
+ function getWallsForCavityContext(ctx?: PlumbingCavityContext): WallSegment2D[] {
920
+ if (!ctx) return []
921
+ const anatomy = resolveAnatomyForContext(ctx)
922
+ if (anatomy) {
923
+ const canonical = anatomy.getWalls(ctx.levelId ?? null)
924
+ if (canonical.length > 0) {
925
+ return canonical.map(toWallSegment2D)
926
+ }
927
+ }
928
+ if (ctx.nodes) {
929
+ return extractWallSegments(ctx.nodes, ctx.levelId ?? null)
930
+ }
931
+ return []
932
+ }
933
+
934
+ function segmentsCross2D(
935
+ ax: number,
936
+ az: number,
937
+ bx: number,
938
+ bz: number,
939
+ cx: number,
940
+ cz: number,
941
+ dx: number,
942
+ dz: number,
943
+ ): boolean {
944
+ const rX = bx - ax
945
+ const rZ = bz - az
946
+ const sX = dx - cx
947
+ const sZ = dz - cz
948
+ const denom = rX * sZ - rZ * sX
949
+ if (Math.abs(denom) < 1e-8) return false
950
+ const t = ((cx - ax) * sZ - (cz - az) * sX) / denom
951
+ const u = ((cx - ax) * rZ - (cz - az) * rX) / denom
952
+ return t > 0.02 && t < 0.98 && u > 0.01 && u < 0.99
953
+ }
954
+
955
+ const round4 = (v: number): number => Math.round(v * 10000) / 10000
956
+
957
+ function resolveBackingWallSnap(
958
+ pt: Vec3,
959
+ ctx: PlumbingCavityContext | undefined,
960
+ obstacles: ReadonlyArray<PlumbingObstacle>,
961
+ pipeRadiusM: number,
962
+ buildingBounds: BuildingBounds2D | undefined,
963
+ checkFootprint: boolean,
964
+ maxDistM = 0.85,
965
+ ): Vec3 | null {
966
+ const walls = getWallsForCavityContext(ctx)
967
+ if (walls.length === 0) return null
968
+ const nw = closestPointOnWalls2D(pt[0], pt[2], walls)
969
+ if (!nw || nw.distanceM <= 0.03 || nw.distanceM > maxDistM) return null
970
+ const snap: Vec3 = [round4(nw.point[0]), pt[1], round4(nw.point[1])]
971
+ const stub: Vec3[] = [pt, snap]
972
+ // Allow exterior wall centerlines right on buildingBounds (margin = 0 + 0.05m tolerance)
973
+ if (buildingBounds) {
974
+ const wallEnv = resolveAllowedEnvelope(buildingBounds, pt, [snap[0], snap[2]], -0.05)
975
+ if (exceedsEnvelopeXZ(stub, wallEnv)) return null
976
+ }
977
+ if (exceedsConcaveFootprint(stub, ctx, checkFootprint)) return null
978
+ if (detectPlumbingClashes(stub, obstacles, pipeRadiusM).length > 0) return null
979
+ for (const w of walls) {
980
+ if (w.id === nw.wall.id) continue
981
+ if (segmentsCross2D(pt[0], pt[2], snap[0], snap[2], w.start[0], w.start[1], w.end[0], w.end[1])) {
982
+ return null
983
+ }
984
+ }
985
+ return snap
986
+ }
987
+
988
+ function resolveWallHeightForContext(ctx: PlumbingCavityContext | undefined, fallback = 2.75): number {
989
+ const walls = getWallsForCavityContext(ctx)
990
+ if (walls.length === 0) return fallback
991
+ let minH = Infinity
992
+ for (const w of walls) {
993
+ if (Number.isFinite(w.heightM) && w.heightM > 1.5 && w.heightM < 8) {
994
+ if (w.heightM < minH) minH = w.heightM
995
+ }
996
+ }
997
+ return Number.isFinite(minH) ? minH : fallback
998
+ }
999
+
1000
+ function remapOverheadHorizontalBand(
1001
+ path: ReadonlyArray<Vec3>,
1002
+ targetY: number,
1003
+ minHorizY = 1.9,
1004
+ remapFinalHorizontalEndpoint = false,
1005
+ ): Vec3[] {
1006
+ if (path.length < 2) return [...path]
1007
+ const out: Vec3[] = path.map((p) => [...p] as Vec3)
1008
+ const rTargetY = round4(targetY)
1009
+ for (let i = 1; i < out.length - 1; i++) {
1010
+ const p = out[i]!
1011
+ const prev = path[i - 1]!
1012
+ const next = path[i + 1]!
1013
+ const prevHoriz = Math.hypot(p[0] - prev[0], p[2] - prev[2]) > 0.03
1014
+ const nextHoriz = Math.hypot(next[0] - p[0], next[2] - p[2]) > 0.03
1015
+ if (p[1] >= minHorizY && (prevHoriz || nextHoriz)) {
1016
+ out[i] = [p[0], rTargetY, p[2]]
1017
+ }
1018
+ }
1019
+ // For dry vents terminating horizontally into the main vent stack (IPC 905.2), also lift the final
1020
+ // endpoint so raising the penultimate vertex never introduces a downward terminal drop.
1021
+ if (remapFinalHorizontalEndpoint && out.length >= 2) {
1022
+ const lastIdx = out.length - 1
1023
+ const prev = path[lastIdx - 1]!
1024
+ const last = path[lastIdx]!
1025
+ const finalHoriz = Math.hypot(last[0] - prev[0], last[2] - prev[2]) > 0.03
1026
+ if (finalHoriz && last[1] >= minHorizY) {
1027
+ out[lastIdx] = [last[0], Math.max(last[1], rTargetY), last[2]]
1028
+ }
1029
+ }
1030
+ return cleanPath(out)
1031
+ }
1032
+
1033
+ const defaultCavityGraphCache = new WeakMap<BuildingAnatomy, Map<string, LegalCavityGraph>>()
1034
+
1035
+ function getOrCompileDefaultCavityGraph(
1036
+ anatomy: BuildingAnatomy,
1037
+ levelId: string | null,
1038
+ opts: {
1039
+ roofClearanceM: number
1040
+ pipeRadiusM: number
1041
+ subFloorElevationM: number
1042
+ },
1043
+ ): LegalCavityGraph {
1044
+ let byKey = defaultCavityGraphCache.get(anatomy)
1045
+ if (!byKey) {
1046
+ byKey = new Map()
1047
+ defaultCavityGraphCache.set(anatomy, byKey)
1048
+ }
1049
+ const key = `${levelId === null ? '__all__' : JSON.stringify(levelId)}|${opts.subFloorElevationM}|${opts.roofClearanceM}|${opts.pipeRadiusM}`
1050
+ let graph = byKey.get(key)
1051
+ if (!graph) {
1052
+ graph = compileLegalCavityGraph(anatomy, levelId, {
1053
+ roofClearanceM: opts.roofClearanceM,
1054
+ halfY: opts.pipeRadiusM,
1055
+ halfXZ: opts.pipeRadiusM,
1056
+ subFloorElevationM: opts.subFloorElevationM,
1057
+ })
1058
+ byKey.set(key, graph)
1059
+ }
1060
+ return graph
1061
+ }
1062
+
1063
+ /**
1064
+ * Layer 2 — Legal-Space-First Plumbing Cavity Router (`@kruschdev/pascal-mep-kernel/router`).
1065
+ *
1066
+ * Routes plumbing pipes strictly inside pre-compiled legal building cavities (solid wall stud bays
1067
+ * minus 3D door/window prisms, enclosed overhead plenums clamped below 7-type roof surfaces, and
1068
+ * under-slab/crawlspace trenches) with strict physics enforcement:
1069
+ * - `'gravity-slope'`: DWV drains with strict monotonic `minSlopeInPerFt` fall (IPC 704.1)
1070
+ * - `'non-descending-vent'`: Dry re-vents obeying IPC 905.5 (`floodRim + 0.1524 m`) & IPC 905.2 (zero inverted-U)
1071
+ * - `'orthogonal' | 'euclidean-cavity'`: Pressurized supply, fuel gas, and dryer vent runs avoiding
1072
+ * structural beams/columns, NEC 110.26(E) dedicated spaces, outdoor voids, and roof surfaces.
1073
+ */
1074
+ export function routePlumbingViaLegalCavity(
1075
+ params: RoutePlumbingViaLegalCavityParams,
1076
+ ): PlumbingCavityRouteResult {
1077
+ const {
1078
+ from,
1079
+ to,
1080
+ mode,
1081
+ nominalSize,
1082
+ material = mode === 'gravity-slope' || mode === 'non-descending-vent' ? 'pvc-dwv' : 'pex-a',
1083
+ clearanceM = 0.02,
1084
+ roofClearanceM = 0.1,
1085
+ preferWallFollowing = false,
1086
+ foundationType = 'crawlspace',
1087
+ obstacles,
1088
+ reserveOnCommit,
1089
+ runId,
1090
+ } = params
1091
+
1092
+ const levelId = params.levelId ?? null
1093
+ const anatomy = params.anatomy ?? compileBuildingAnatomy(params.nodes ?? {})
1094
+ const pipeRadiusM =
1095
+ params.pipeRadiusM ?? (nominalSize ? getPipeOuterDiameterM(nominalSize, material) / 2 : 0.025)
1096
+
1097
+ const defaultSubFloorY =
1098
+ params.subFloorElevationM ??
1099
+ (mode === 'gravity-slope'
1100
+ ? Math.min(foundationType === 'slab' ? -0.35 : -0.24, Math.max(-0.45, Math.min(from[1], to[1])))
1101
+ : foundationType === 'slab'
1102
+ ? -0.35
1103
+ : -0.24)
1104
+
1105
+ const graph =
1106
+ params.graph ??
1107
+ getOrCompileDefaultCavityGraph(anatomy, levelId, {
1108
+ roofClearanceM,
1109
+ pipeRadiusM,
1110
+ subFloorElevationM: defaultSubFloorY,
1111
+ })
1112
+
1113
+ let occupancy = params.occupancy
1114
+ if (!occupancy) {
1115
+ occupancy = anatomy.createOccupancyGrid(levelId, { forTrade: 'plumbing' })
1116
+ if (obstacles && obstacles.length > 0) {
1117
+ const existingIds = new Set<string>()
1118
+ for (const o of occupancy.obstacles) {
1119
+ existingIds.add(o.id)
1120
+ existingIds.add(o.nodeId)
1121
+ }
1122
+ for (const obs of obstacles) {
1123
+ const key = obs.nodeId ?? obs.id
1124
+ if (existingIds.has(obs.id) || existingIds.has(key)) continue
1125
+ occupancy.reserveBox({
1126
+ id: obs.id,
1127
+ nodeId: key,
1128
+ trade: obs.category === 'electrical-dedicated-space' ? 'electrical' : 'structural',
1129
+ kind:
1130
+ obs.category === 'electrical-dedicated-space'
1131
+ ? 'electrical-dedicated-space'
1132
+ : obs.structuralKind === 'column'
1133
+ ? 'structural-column'
1134
+ : 'structural-beam',
1135
+ aabb: obs.box,
1136
+ clearanceM: 0.02,
1137
+ label: obs.label,
1138
+ })
1139
+ }
1140
+ }
1141
+ }
1142
+
1143
+ let effectiveTo: Vec3 = to
1144
+ let minSlopeInPerFt: number | undefined
1145
+ let minHorizontalElevationM: number | undefined = params.minHorizontalElevationM
1146
+ let allowedBands: readonly CavityBand[]
1147
+
1148
+ if (mode === 'gravity-slope') {
1149
+ minSlopeInPerFt =
1150
+ params.minSlopeInPerFt ??
1151
+ (nominalSize ? getMinRequiredDrainSlopeInPerFt(nominalSize) : IPC_RULE_THRESHOLDS.drainSlopeSmallInPerFt)
1152
+ allowedBands = params.allowedBands ?? ['under-slab', 'crawlspace', 'under-sill', 'mid-wall']
1153
+ const allowsSubFloor = allowedBands.includes('under-slab') || allowedBands.includes('crawlspace')
1154
+ if (allowsSubFloor && graph.subFloorY !== null && effectiveTo[1] > graph.subFloorY) {
1155
+ effectiveTo = [effectiveTo[0], graph.subFloorY, effectiveTo[2]]
1156
+ }
1157
+ } else if (mode === 'non-descending-vent') {
1158
+ const statutoryFloor =
1159
+ params.floodRimHeightM !== undefined
1160
+ ? params.floodRimHeightM + IPC_RULE_THRESHOLDS.ventMinAboveFloodRimM
1161
+ : undefined
1162
+ const conservativeFloor =
1163
+ statutoryFloor !== undefined
1164
+ ? statutoryFloor + IPC_RULE_THRESHOLDS.ventPlacementMarginM
1165
+ : undefined
1166
+ if (statutoryFloor !== undefined) {
1167
+ if (effectiveTo[1] < statutoryFloor) {
1168
+ effectiveTo = [effectiveTo[0], statutoryFloor, effectiveTo[2]]
1169
+ }
1170
+ const targetFloor = Math.max(statutoryFloor, Math.min(effectiveTo[1], conservativeFloor!))
1171
+ minHorizontalElevationM =
1172
+ minHorizontalElevationM !== undefined ? Math.max(minHorizontalElevationM, targetFloor) : targetFloor
1173
+ }
1174
+ allowedBands = params.allowedBands ?? ['mid-wall', 'top-plate', 'overhead-plenum', 'attic']
1175
+ } else {
1176
+ allowedBands =
1177
+ params.allowedBands ??
1178
+ (foundationType === 'slab'
1179
+ ? ['overhead-plenum', 'attic', 'top-plate', 'mid-wall', 'under-sill']
1180
+ : ['under-slab', 'crawlspace', 'under-sill', 'mid-wall', 'top-plate', 'overhead-plenum', 'attic'])
1181
+ }
1182
+
1183
+ const result = routeInLegalCavities({
1184
+ anatomy,
1185
+ graph,
1186
+ occupancy,
1187
+ request: {
1188
+ trade: 'plumbing',
1189
+ from,
1190
+ to: effectiveTo,
1191
+ halfXZ: pipeRadiusM,
1192
+ halfY: pipeRadiusM,
1193
+ clearanceM,
1194
+ allowedBands,
1195
+ mode,
1196
+ ...(minSlopeInPerFt !== undefined ? { minSlopeInPerFt } : {}),
1197
+ ...(minHorizontalElevationM !== undefined ? { minHorizontalElevationM } : {}),
1198
+ roofClearanceM,
1199
+ preferWallFollowing,
1200
+ ...(reserveOnCommit !== undefined ? { reserveOnCommit } : {}),
1201
+ ...(runId !== undefined ? { runId } : {}),
1202
+ },
1203
+ })
1204
+
1205
+ const cleanedPath = cleanPath([...result.path])
1206
+ return {
1207
+ ...result,
1208
+ path: cleanedPath,
1209
+ lengthFt: round2(polylineLengthM(cleanedPath) * METERS_TO_FEET),
1210
+ }
1211
+ }
1212
+
1213
+ /**
1214
+ * Route a gravity-sloped DWV branch from a fixture rough-in to a stack/collector point.
1215
+ * Guarantees continuous downward fall at >= required IPC slope (1/4"/ft for <= 2.5", 1/8"/ft for >= 3")
1216
+ * and automatically detours horizontally around structural columns, beams, and NEC 110.26(E) electrical spaces.
1217
+ */
1218
+ export function routeDwvDrainRun(params: {
1219
+ from: Vec3
1220
+ to: Vec3
1221
+ nominalSize: PipeNominalSize
1222
+ material?: PipeMaterial
1223
+ pipeRadiusM?: number
1224
+ foundationType?: FoundationType
1225
+ slopeInPerFt?: 0.125 | 0.25
1226
+ obstacles?: ReadonlyArray<PlumbingObstacle>
1227
+ buildingBounds?: BuildingBounds2D
1228
+ cavityContext?: PlumbingCavityContext
1229
+ }): {
1230
+ path: Vec3[]
1231
+ slopeInPerFt: number
1232
+ lengthFt: number
1233
+ detoured: boolean
1234
+ clashes: PlumbingObstacle[]
1235
+ } {
1236
+ const {
1237
+ from,
1238
+ to,
1239
+ nominalSize,
1240
+ material = 'pvc-dwv',
1241
+ foundationType = 'crawlspace',
1242
+ obstacles = [],
1243
+ buildingBounds,
1244
+ cavityContext,
1245
+ } = params
1246
+ const minSlope = getMinRequiredDrainSlopeInPerFt(nominalSize)
1247
+ const slopeInPerFt = Math.max(params.slopeInPerFt ?? 0.25, minSlope)
1248
+ const slopeRatio = slopeInPerFt / 12 // vertical drop per horizontal unit
1249
+
1250
+ const underFloorY = foundationType === 'slab' ? -0.35 : -0.24
1251
+ const startY = Math.min(from[1], underFloorY)
1252
+ const pipeRadiusM = (params.pipeRadiusM ?? getPipeOuterDiameterM(nominalSize, material) / 2) + 0.015
1253
+ const env = resolveAllowedEnvelope(buildingBounds, from, [to[0], to[2]])
1254
+ const checkFootprint = Boolean(buildingBounds) && hasCavityScene(cavityContext)
1255
+
1256
+ const buildSlopedCandidate = (
1257
+ horizWaypoints: ReadonlyArray<readonly [number, number]>,
1258
+ overrideStartY = startY,
1259
+ startJog?: readonly [number, number],
1260
+ ): Vec3[] => {
1261
+ const pts: Vec3[] = [from]
1262
+ let curX = from[0]
1263
+ let curZ = from[2]
1264
+ let curY = overrideStartY
1265
+ if (startJog) {
1266
+ const jogLen = Math.hypot(startJog[0] - from[0], startJog[1] - from[2])
1267
+ const jogY = from[1] - jogLen * slopeRatio
1268
+ if (jogLen >= 0.02 && jogY >= overrideStartY + 0.01) {
1269
+ pts.push([startJog[0], jogY, startJog[1]])
1270
+ curX = startJog[0]
1271
+ curZ = startJog[1]
1272
+ if (jogY > overrideStartY + 0.02) {
1273
+ pts.push([curX, overrideStartY, curZ])
1274
+ curY = overrideStartY
1275
+ } else {
1276
+ curY = jogY
1277
+ }
1278
+ } else if (from[1] > overrideStartY + 0.02) {
1279
+ pts.push([from[0], overrideStartY, from[2]])
1280
+ }
1281
+ } else if (from[1] > overrideStartY + 0.02) {
1282
+ pts.push([from[0], overrideStartY, from[2]])
1283
+ }
1284
+ for (let i = 0; i < horizWaypoints.length; i++) {
1285
+ const [wx, wz] = horizWaypoints[i]!
1286
+ const leg = Math.hypot(wx - curX, wz - curZ)
1287
+ const isLast = i === horizWaypoints.length - 1
1288
+ if (!isLast && leg < 0.15) continue
1289
+ curY -= leg * slopeRatio
1290
+ const y = isLast ? Math.min(to[1], curY) : curY
1291
+ pts.push([wx, y, wz])
1292
+ curX = wx
1293
+ curZ = wz
1294
+ curY = y
1295
+ }
1296
+ return cleanPath(pts)
1297
+ }
1298
+
1299
+ // Wall-drained fixtures (rough-in >= 0.25 m, e.g., lavatories, kitchen sinks, disposals, dishwashers, washers):
1300
+ // stub horizontally back into the backing wet-wall centerline at >= minSlopeInPerFt so the vertical drop
1301
+ // stays concealed inside the wall stud cavity instead of dropping through open room air.
1302
+ const wallDrainSnap =
1303
+ hasCavityScene(cavityContext) && from[1] >= 0.25
1304
+ ? resolveBackingWallSnap(from, cavityContext, obstacles, pipeRadiusM, buildingBounds, checkFootprint, 0.24)
1305
+ : null
1306
+ const wallDrainJog: readonly [number, number] | undefined = wallDrainSnap
1307
+ ? [wallDrainSnap[0], wallDrainSnap[2]]
1308
+ : undefined
1309
+
1310
+ const primary = buildSlopedCandidate(
1311
+ [
1312
+ [to[0], wallDrainJog ? wallDrainJog[1] : from[2]],
1313
+ [to[0], to[2]],
1314
+ ],
1315
+ startY,
1316
+ wallDrainJog,
1317
+ )
1318
+ const drainEnv =
1319
+ wallDrainJog && buildingBounds
1320
+ ? resolveAllowedEnvelope(buildingBounds, from, [to[0], to[2]], -0.05)
1321
+ : env
1322
+ let bestPath = primary
1323
+ let bestClashes = detectPlumbingClashes(primary, obstacles, pipeRadiusM)
1324
+ let bestBoundsViolation =
1325
+ exceedsEnvelopeXZ(primary, drainEnv) || exceedsConcaveFootprint(primary, cavityContext, checkFootprint)
1326
+ let detoured = false
1327
+ let underBeamY: number | null = null
1328
+
1329
+ if (bestClashes.length > 0 || bestBoundsViolation) {
1330
+ const tryCandidate = (cand: Vec3[]): boolean => {
1331
+ const boundsViol =
1332
+ exceedsEnvelopeXZ(cand, drainEnv) || exceedsConcaveFootprint(cand, cavityContext, checkFootprint)
1333
+ if (boundsViol && !bestBoundsViolation) return false
1334
+ const c = detectPlumbingClashes(cand, obstacles, pipeRadiusM)
1335
+ const better =
1336
+ (bestBoundsViolation && !boundsViol) ||
1337
+ (boundsViol === bestBoundsViolation && c.length < bestClashes.length)
1338
+ if (better) {
1339
+ bestPath = cand
1340
+ bestClashes = c
1341
+ bestBoundsViolation = boundsViol
1342
+ detoured = true
1343
+ }
1344
+ return bestClashes.length === 0 && !bestBoundsViolation
1345
+ }
1346
+
1347
+ // Layer 2 — Legal-Space-First Cavity Candidate (gravity-slope) when scene anatomy/graph is present
1348
+ if (hasCavityScene(cavityContext)) {
1349
+ const cav = routePlumbingViaLegalCavity({
1350
+ ...cavityContext,
1351
+ from,
1352
+ to: [to[0], Math.min(to[1], underFloorY), to[2]],
1353
+ mode: 'gravity-slope',
1354
+ nominalSize,
1355
+ material,
1356
+ pipeRadiusM,
1357
+ foundationType,
1358
+ minSlopeInPerFt: slopeInPerFt,
1359
+ subFloorElevationM: underFloorY,
1360
+ obstacles,
1361
+ })
1362
+ if (cav.path.length >= 2) {
1363
+ const cavSlope = measureDrainPathSlope(cav.path)
1364
+ if (
1365
+ !cavSlope.hasUphillSegment &&
1366
+ (cavSlope.horizontalSegments === 0 || cavSlope.minSegmentSlopeInPerFt >= minSlope - 0.02)
1367
+ ) {
1368
+ tryCandidate(cav.path)
1369
+ }
1370
+ }
1371
+ }
1372
+
1373
+ // Compute safe elevation below colliding (and deepest level) under-floor girders
1374
+ const allUnderBeams = obstacles.filter(isUnderFloorBeamObstacle)
1375
+ const structuralHits = bestClashes.filter(isUnderFloorBeamObstacle)
1376
+ const beamPool = structuralHits.length > 0 ? structuralHits : allUnderBeams
1377
+ if (beamPool.length > 0) {
1378
+ const lowestMinY = Math.min(...beamPool.map((o) => o.box.minY))
1379
+ underBeamY = Math.min(startY - 0.18, lowestMinY - pipeRadiusM - 0.06)
1380
+ }
1381
+ const allLowestMinY =
1382
+ allUnderBeams.length > 0 ? Math.min(...allUnderBeams.map((o) => o.box.minY)) : null
1383
+ const allUnderBeamY =
1384
+ allLowestMinY !== null ? Math.min(startY - 0.18, allLowestMinY - pipeRadiusM - 0.06) : null
1385
+
1386
+ if ((bestClashes.length > 0 || bestBoundsViolation) && underBeamY !== null) {
1387
+ for (const sy of allUnderBeamY !== null && allUnderBeamY < underBeamY - 0.01 ? [underBeamY, allUnderBeamY] : [underBeamY]) {
1388
+ for (const wp of [
1389
+ [[to[0], from[2]], [to[0], to[2]]] as const,
1390
+ [[from[0], to[2]], [to[0], to[2]]] as const,
1391
+ ]) {
1392
+ if (tryCandidate(buildSlopedCandidate(wp, sy))) break
1393
+ }
1394
+ if (bestClashes.length === 0 && !bestBoundsViolation) break
1395
+ }
1396
+ }
1397
+
1398
+ if (bestClashes.length > 0 || bestBoundsViolation) {
1399
+ const midX = (from[0] + to[0]) / 2
1400
+ const midZ = (from[2] + to[2]) / 2
1401
+ const edgePad = pipeRadiusM + 0.08
1402
+ const startYs = Array.from(
1403
+ new Set(
1404
+ [underBeamY, allUnderBeamY, startY].filter((v): v is number => v !== null),
1405
+ ),
1406
+ )
1407
+
1408
+ // Check if the vertical drop from `from` directly collides with an under-floor girder or column
1409
+ // Probe to the deepest candidate startY so deeper beams below underBeamY are never missed.
1410
+ const dropProbeY = startYs.length > 0 ? Math.min(...startYs) : startY
1411
+ const dropHits =
1412
+ from[1] > dropProbeY + 0.02
1413
+ ? detectPlumbingClashes([from, [from[0], dropProbeY, from[2]]], obstacles, pipeRadiusM)
1414
+ : []
1415
+ const startJogs: Array<readonly [number, number] | undefined> = [
1416
+ ...(wallDrainJog ? [wallDrainJog] : []),
1417
+ undefined,
1418
+ ...(dropHits.length > 0 ? buildLateralEscapeCandidates(from[0], from[2], dropHits, edgePad) : []),
1419
+ ]
1420
+
1421
+ const baseCandidates: Array<Array<readonly [number, number]>> = [
1422
+ [[to[0], from[2]], [to[0], to[2]]],
1423
+ [[from[0], to[2]], [to[0], to[2]]],
1424
+ [[to[0], from[2] + 0.55], [to[0], to[2]]],
1425
+ [[to[0], from[2] - 0.55], [to[0], to[2]]],
1426
+ [[from[0] + 0.55, to[2]], [to[0], to[2]]],
1427
+ [[from[0] - 0.55, to[2]], [to[0], to[2]]],
1428
+ [[midX + 0.75, from[2] + 0.75], [to[0] + 0.75, to[2]], [to[0], to[2]]],
1429
+ [[midX - 0.75, from[2] - 0.75], [to[0] - 0.75, to[2]], [to[0], to[2]]],
1430
+ [[to[0] + 0.95, from[2]], [to[0] + 0.95, to[2]], [to[0], to[2]]],
1431
+ [[to[0] - 0.95, from[2]], [to[0] - 0.95, to[2]], [to[0], to[2]]],
1432
+ [[from[0], to[2] + 0.95], [to[0], to[2] + 0.95], [to[0], to[2]]],
1433
+ [[from[0], to[2] - 0.95], [to[0], to[2] - 0.95], [to[0], to[2]]],
1434
+ ...buildObstacleDetourWaypoints([from[0], from[2]], [to[0], to[2]], bestClashes, edgePad),
1435
+ ]
1436
+
1437
+ for (const jog of startJogs) {
1438
+ const jx = jog ? jog[0] : from[0]
1439
+ const jz = jog ? jog[1] : from[2]
1440
+ const wpList: Array<Array<readonly [number, number]>> = jog
1441
+ ? [
1442
+ [[to[0], jz], [to[0], to[2]]],
1443
+ [[jx, to[2]], [to[0], to[2]]],
1444
+ ...buildObstacleDetourWaypoints([jx, jz], [to[0], to[2]], bestClashes, edgePad),
1445
+ ...baseCandidates,
1446
+ ]
1447
+ : baseCandidates
1448
+ for (const sy of startYs) {
1449
+ for (const wp of wpList) {
1450
+ if (tryCandidate(buildSlopedCandidate(wp, sy, jog))) break
1451
+ }
1452
+ if (bestClashes.length === 0 && !bestBoundsViolation) break
1453
+ }
1454
+ if (bestClashes.length === 0 && !bestBoundsViolation) break
1455
+ }
1456
+ }
1457
+ }
1458
+
1459
+ return {
1460
+ path: bestPath,
1461
+ slopeInPerFt,
1462
+ lengthFt: round2(polylineLengthM(bestPath) * METERS_TO_FEET),
1463
+ detoured,
1464
+ clashes: bestClashes,
1465
+ }
1466
+ }
1467
+
1468
+ /**
1469
+ * Route a dry re-vent from a fixture wet wall up to >= 6" above flood-level rim (IPC 905.5)
1470
+ * and horizontally over to the main vent stack, detouring around structural headers, beams,
1471
+ * columns, and NEC 110.26(E) obstacles while keeping strictly non-descending elevation (IPC 905.2).
1472
+ */
1473
+ export function routeVentRun(params: {
1474
+ from: Vec3
1475
+ stackPoint: readonly [number, number]
1476
+ floodRimHeightM: number
1477
+ ceilingHeightM?: number
1478
+ nominalSize?: PipeNominalSize
1479
+ material?: PipeMaterial
1480
+ pipeRadiusM?: number
1481
+ obstacles?: ReadonlyArray<PlumbingObstacle>
1482
+ buildingBounds?: BuildingBounds2D
1483
+ maxRoofYAt?: (x: number, z: number) => number
1484
+ cavityContext?: PlumbingCavityContext
1485
+ }): {
1486
+ path: Vec3[]
1487
+ tieInHeightM: number
1488
+ lengthFt: number
1489
+ detoured: boolean
1490
+ clashes: PlumbingObstacle[]
1491
+ } {
1492
+ const {
1493
+ from,
1494
+ stackPoint,
1495
+ floodRimHeightM,
1496
+ ceilingHeightM = 2.6,
1497
+ nominalSize,
1498
+ material = 'pvc-dwv',
1499
+ obstacles = [],
1500
+ buildingBounds,
1501
+ maxRoofYAt,
1502
+ cavityContext,
1503
+ } = params
1504
+ const pipeRadiusM =
1505
+ params.pipeRadiusM ?? (nominalSize ? getPipeOuterDiameterM(nominalSize, material) / 2 : 0.03)
1506
+ const env = resolveAllowedEnvelope(buildingBounds, from, stackPoint)
1507
+ const checkFootprint = Boolean(buildingBounds) && hasCavityScene(cavityContext)
1508
+ // IPC 905.5 (from IPC_DECLARATIVE_RULES): horizontal vent tie-in MUST be >= 6" (0.1524 m) above flood-level rim
1509
+ // IPC 905.2: dry vents must never descend below `from[1]` (zero inverted-U condensate traps)
1510
+ const ipcMinVentY = Math.max(from[1], floodRimHeightM + IPC_RULE_THRESHOLDS.ventMinAboveFloodRimM + 0.01)
1511
+ const minHorizontalVentY = Math.max(from[1], floodRimHeightM + IPC_RULE_THRESHOLDS.ventPlacementMinAboveFloodRimM)
1512
+ const minTieInY = Math.max(from[1], floodRimHeightM + IPC_RULE_THRESHOLDS.ventMinAboveFloodRimM + 0.1)
1513
+ const maxSafeCeilingY = ceilingHeightM - 0.08 - pipeRadiusM
1514
+ const rawTieInHeightM = Math.max(minTieInY, Math.min(ceilingHeightM - 0.15, maxSafeCeilingY))
1515
+ const minEndpointRoofCap = maxRoofYAt
1516
+ ? Math.min(maxRoofYAt(from[0], from[2]), maxRoofYAt(stackPoint[0], stackPoint[1])) - pipeRadiusM - 0.09
1517
+ : Infinity
1518
+ const tieInHeightM = Number.isFinite(minEndpointRoofCap)
1519
+ ? Math.max(ipcMinVentY, Math.min(rawTieInHeightM, minEndpointRoofCap))
1520
+ : rawTieInHeightM
1521
+
1522
+ const buildVentCandidate = (
1523
+ waypoints: ReadonlyArray<readonly [number, number]>,
1524
+ tieY = tieInHeightM,
1525
+ riserJog?: { x: number; z: number; jogY: number },
1526
+ ): Vec3[] => {
1527
+ const safeTieY = Math.max(from[1], tieY)
1528
+ // Clamp jog elevation into [from[1], safeTieY] so dry vents never descend (IPC 905.2)
1529
+ const jy = riserJog ? Math.max(from[1], Math.min(riserJog.jogY, safeTieY)) : safeTieY
1530
+ const pts: Vec3[] = riserJog
1531
+ ? [
1532
+ from,
1533
+ [from[0], jy, from[2]],
1534
+ [riserJog.x, jy, riserJog.z],
1535
+ ...(safeTieY > jy + 0.008 ? [[riserJog.x, safeTieY, riserJog.z] as Vec3] : []),
1536
+ ]
1537
+ : [from, [from[0], safeTieY, from[2]]]
1538
+ for (const [wx, wz] of waypoints) {
1539
+ pts.push([wx, safeTieY, wz])
1540
+ }
1541
+ return cleanPath(pts)
1542
+ }
1543
+
1544
+ const primary = buildVentCandidate([
1545
+ [stackPoint[0], from[2]],
1546
+ [stackPoint[0], stackPoint[1]],
1547
+ ])
1548
+ let bestPath = primary
1549
+ let bestClashes = detectPlumbingClashes(primary, obstacles, pipeRadiusM)
1550
+ let bestBoundsViolation =
1551
+ exceedsEnvelopeXZ(primary, env) || exceedsConcaveFootprint(primary, cavityContext, checkFootprint)
1552
+ let bestRoofViolation = exceedsRoofPlane(primary, pipeRadiusM, maxRoofYAt)
1553
+ let bestTieInY = tieInHeightM
1554
+ let detoured = false
1555
+
1556
+ // Wall-Cavity-First Vent Concealment: when scene walls/cavity graph are present, try routing
1557
+ // along connected top-plate wall cavities first (strictly < wallH so 100% hidden in Full Walls mode
1558
+ // and >= wallH - 0.08 so zero IRC R602.6 horizontal stud-bore errors!) before open-room L-shapes.
1559
+ if (hasCavityScene(cavityContext)) {
1560
+ const wallH = resolveWallHeightForContext(cavityContext, ceilingHeightM)
1561
+ const desiredTopChaseY = round4(
1562
+ Math.max(
1563
+ minHorizontalVentY,
1564
+ Math.min(wallH - 0.055, Number.isFinite(minEndpointRoofCap) ? minEndpointRoofCap : wallH - 0.055),
1565
+ ),
1566
+ )
1567
+ let adoptedWallVent = false
1568
+ for (const bandSet of [['top-plate'] as const, ['top-plate', 'overhead-plenum', 'attic'] as const]) {
1569
+ if (adoptedWallVent) break
1570
+ const cavWall = routePlumbingViaLegalCavity({
1571
+ ...cavityContext,
1572
+ from,
1573
+ to: [stackPoint[0], desiredTopChaseY, stackPoint[1]],
1574
+ mode: 'non-descending-vent',
1575
+ nominalSize,
1576
+ material,
1577
+ pipeRadiusM,
1578
+ floodRimHeightM,
1579
+ minHorizontalElevationM: minHorizontalVentY,
1580
+ preferWallFollowing: true,
1581
+ allowedBands: bandSet,
1582
+ // Allow top-plate topology discovery under low/default eaves before remapping to desiredTopChaseY
1583
+ // and enforcing full roof clearance via `exceedsRoofPlane` below.
1584
+ ...(bandSet.length === 1 && bandSet[0] === 'top-plate'
1585
+ ? { graph: undefined, roofClearanceM: 0.01 }
1586
+ : {}),
1587
+ obstacles,
1588
+ })
1589
+ if (cavWall.path.length >= 2) {
1590
+ const remapped =
1591
+ desiredTopChaseY <= wallH - 0.04 && desiredTopChaseY >= minHorizontalVentY
1592
+ ? remapOverheadHorizontalBand(cavWall.path, desiredTopChaseY, minHorizontalVentY - 0.05, true)
1593
+ : cavWall.path
1594
+ const wallEnv = buildingBounds ? resolveAllowedEnvelope(buildingBounds, from, stackPoint, -0.05) : env
1595
+ for (const cand of [remapped, cavWall.path]) {
1596
+ if (
1597
+ isVentPathCodeCompliant(cand, floodRimHeightM + IPC_RULE_THRESHOLDS.ventMinAboveFloodRimM) &&
1598
+ !exceedsEnvelopeXZ(cand, wallEnv) &&
1599
+ !exceedsConcaveFootprint(cand, cavityContext, checkFootprint) &&
1600
+ !exceedsRoofPlane(cand, pipeRadiusM, maxRoofYAt) &&
1601
+ detectPlumbingClashes(cand, obstacles, pipeRadiusM).length === 0
1602
+ ) {
1603
+ if (bestClashes.length > 0 || bestBoundsViolation || bestRoofViolation) detoured = true
1604
+ bestPath = cand
1605
+ bestClashes = []
1606
+ bestBoundsViolation = false
1607
+ bestRoofViolation = false
1608
+ bestTieInY = cand[cand.length - 1]![1]
1609
+ adoptedWallVent = true
1610
+ break
1611
+ }
1612
+ }
1613
+ }
1614
+ }
1615
+ }
1616
+
1617
+ const ventDetourEnv =
1618
+ buildingBounds && hasCavityScene(cavityContext)
1619
+ ? resolveAllowedEnvelope(buildingBounds, from, stackPoint, -0.05)
1620
+ : env
1621
+ if (bestClashes.length > 0 || bestBoundsViolation || bestRoofViolation) {
1622
+ const tryVent = (cand: Vec3[], tieY: number): boolean => {
1623
+ const boundsViol =
1624
+ exceedsEnvelopeXZ(cand, ventDetourEnv) || exceedsConcaveFootprint(cand, cavityContext, checkFootprint)
1625
+ const roofViol = exceedsRoofPlane(cand, pipeRadiusM, maxRoofYAt)
1626
+ if (boundsViol && !bestBoundsViolation) return false
1627
+ if (roofViol && !bestRoofViolation && boundsViol === bestBoundsViolation) return false
1628
+ const c = detectPlumbingClashes(cand, obstacles, pipeRadiusM)
1629
+ const better =
1630
+ (bestBoundsViolation && !boundsViol) ||
1631
+ (boundsViol === bestBoundsViolation && bestRoofViolation && !roofViol) ||
1632
+ (boundsViol === bestBoundsViolation && roofViol === bestRoofViolation && c.length < bestClashes.length)
1633
+ if (better) {
1634
+ bestPath = cand
1635
+ bestClashes = c
1636
+ bestBoundsViolation = boundsViol
1637
+ bestRoofViolation = roofViol
1638
+ bestTieInY = tieY
1639
+ detoured = true
1640
+ }
1641
+ return bestClashes.length === 0 && !bestBoundsViolation && !bestRoofViolation
1642
+ }
1643
+
1644
+ const edgePad = pipeRadiusM + 0.07
1645
+ const maxAtticTieY = ceilingHeightM + 0.36
1646
+ const elevatedHits = bestClashes.filter(isElevatedBeamObstacle)
1647
+ const allElevatedBeams = obstacles.filter(isElevatedBeamObstacle)
1648
+
1649
+ const primaryMinRoofCap = maxRoofYAt
1650
+ ? minRoofAlongPath(primary, maxRoofYAt) - pipeRadiusM - 0.09
1651
+ : Infinity
1652
+ const altPrimary = buildVentCandidate([
1653
+ [from[0], stackPoint[1]],
1654
+ [stackPoint[0], stackPoint[1]],
1655
+ ])
1656
+ const altMinRoofCap = maxRoofYAt
1657
+ ? minRoofAlongPath(altPrimary, maxRoofYAt) - pipeRadiusM - 0.09
1658
+ : Infinity
1659
+
1660
+ // Candidate attic/upper-wall tie-in elevations:
1661
+ // 1. Default tieInHeightM
1662
+ // 2. Hop cleanly ABOVE wall headers into ceiling/attic space (while remaining strictly under roof envelope)
1663
+ // 3. Duck cleanly BELOW a high ceiling/ridge beam or low/flat explicit roof segment while staying >= 6" above flood rim (IPC 905.5)
1664
+ const tieYs: number[] = [tieInHeightM]
1665
+ const pushTieY = (y: number, minFloorY = ipcMinVentY) => {
1666
+ if (!Number.isFinite(y) || y < minFloorY || y > maxAtticTieY) return
1667
+ if (!tieYs.some((v) => Math.abs(v - y) < 0.02)) tieYs.push(y)
1668
+ }
1669
+ if (elevatedHits.length > 0) {
1670
+ const aboveHit = Math.max(...elevatedHits.map((o) => o.box.maxY)) + pipeRadiusM + 0.05
1671
+ const belowHit = Math.min(...elevatedHits.map((o) => o.box.minY)) - pipeRadiusM - 0.05
1672
+ pushTieY(aboveHit)
1673
+ pushTieY(belowHit)
1674
+ }
1675
+ if (Number.isFinite(minEndpointRoofCap)) pushTieY(minEndpointRoofCap)
1676
+ if (Number.isFinite(primaryMinRoofCap)) pushTieY(primaryMinRoofCap)
1677
+ if (Number.isFinite(altMinRoofCap)) pushTieY(altMinRoofCap)
1678
+ const headerBeams = allElevatedBeams.filter(
1679
+ (o) => o.beamRole === 'header' || /header/i.test(o.label) || o.box.maxY <= ceilingHeightM + 0.08,
1680
+ )
1681
+ if (headerBeams.length > 0) {
1682
+ pushTieY(Math.max(...headerBeams.map((o) => o.box.maxY)) + pipeRadiusM + 0.05)
1683
+ }
1684
+ pushTieY(ceilingHeightM - 0.15)
1685
+ pushTieY(Math.min(ceilingHeightM - 0.15, maxSafeCeilingY))
1686
+ pushTieY(ceilingHeightM - 0.25)
1687
+ pushTieY(ceilingHeightM - 0.45)
1688
+ pushTieY(ceilingHeightM + 0.14)
1689
+ pushTieY(ceilingHeightM + 0.28)
1690
+ pushTieY(minHorizontalVentY)
1691
+ pushTieY(ipcMinVentY)
1692
+
1693
+ // Check if the vertical riser at `from` hits a window/door header or beam directly above the fixture.
1694
+ // If so, offset horizontally past the header jamb at `jogY >= floodRim + 6"` (IPC 905.5) before rising!
1695
+ const riserHits = detectPlumbingClashes(
1696
+ [from, [from[0], Math.max(...tieYs), from[2]]],
1697
+ obstacles,
1698
+ pipeRadiusM,
1699
+ )
1700
+ const riserJogs: Array<{ x: number; z: number; jogY: number } | undefined> = [undefined]
1701
+ if (riserHits.length > 0) {
1702
+ const lowestHitY = Math.min(...riserHits.map((o) => o.box.minY))
1703
+ const safeJogY = Math.max(
1704
+ minHorizontalVentY,
1705
+ Math.min(lowestHitY - pipeRadiusM - 0.06, tieInHeightM - 0.2),
1706
+ )
1707
+ const escapes = buildLateralEscapeCandidates(from[0], from[2], riserHits, edgePad + 0.03)
1708
+ for (const [rx, rz] of escapes) {
1709
+ riserJogs.push({ x: rx, z: rz, jogY: safeJogY })
1710
+ }
1711
+ for (const d of [0.45, -0.45, 0.9, -0.9]) {
1712
+ riserJogs.push({ x: from[0] + d, z: from[2], jogY: safeJogY })
1713
+ riserJogs.push({ x: from[0], z: from[2] + d, jogY: safeJogY })
1714
+ }
1715
+ }
1716
+
1717
+ for (const jog of riserJogs) {
1718
+ const sx = jog ? jog.x : from[0]
1719
+ const sz = jog ? jog.z : from[2]
1720
+ const candidates: Array<Array<readonly [number, number]>> = [
1721
+ [[stackPoint[0], sz], [stackPoint[0], stackPoint[1]]],
1722
+ [[sx, stackPoint[1]], [stackPoint[0], stackPoint[1]]],
1723
+ [[stackPoint[0], sz + 0.55], [stackPoint[0], stackPoint[1]]],
1724
+ [[stackPoint[0], sz - 0.55], [stackPoint[0], stackPoint[1]]],
1725
+ [[sx + 0.55, stackPoint[1]], [stackPoint[0], stackPoint[1]]],
1726
+ [[sx - 0.55, stackPoint[1]], [stackPoint[0], stackPoint[1]]],
1727
+ [[stackPoint[0] + 0.95, sz], [stackPoint[0] + 0.95, stackPoint[1]], [stackPoint[0], stackPoint[1]]],
1728
+ [[stackPoint[0] - 0.95, sz], [stackPoint[0] - 0.95, stackPoint[1]], [stackPoint[0], stackPoint[1]]],
1729
+ ...buildObstacleDetourWaypoints([sx, sz], stackPoint, bestClashes, edgePad),
1730
+ ]
1731
+ for (const tieY of tieYs) {
1732
+ for (const wp of candidates) {
1733
+ if (tryVent(buildVentCandidate(wp, tieY, jog), tieY)) break
1734
+ }
1735
+ if (bestClashes.length === 0 && !bestBoundsViolation && !bestRoofViolation) break
1736
+ }
1737
+ if (bestClashes.length === 0 && !bestBoundsViolation && !bestRoofViolation) break
1738
+ }
1739
+
1740
+ // Layer 2 — Legal-Space-First Cavity Rescue (non-descending-vent, IPC 905.5 & 905.2)
1741
+ if ((bestClashes.length > 0 || bestBoundsViolation || bestRoofViolation) && hasCavityScene(cavityContext)) {
1742
+ const cavityTargetY =
1743
+ cavityContext?.graph &&
1744
+ (!maxRoofYAt ||
1745
+ cavityContext.graph.ceilingPlenumY + pipeRadiusM <=
1746
+ Math.min(maxRoofYAt(from[0], from[2]), maxRoofYAt(stackPoint[0], stackPoint[1])) - 0.08 + 1e-4)
1747
+ ? Math.max(tieInHeightM, cavityContext.graph.ceilingPlenumY)
1748
+ : tieInHeightM
1749
+ const cav = routePlumbingViaLegalCavity({
1750
+ ...cavityContext,
1751
+ from,
1752
+ to: [stackPoint[0], cavityTargetY, stackPoint[1]],
1753
+ mode: 'non-descending-vent',
1754
+ nominalSize,
1755
+ material,
1756
+ pipeRadiusM,
1757
+ floodRimHeightM,
1758
+ minHorizontalElevationM: minHorizontalVentY,
1759
+ obstacles,
1760
+ })
1761
+ if (
1762
+ cav.path.length >= 2 &&
1763
+ isVentPathCodeCompliant(cav.path, floodRimHeightM + IPC_RULE_THRESHOLDS.ventMinAboveFloodRimM)
1764
+ ) {
1765
+ const cavTieY = cav.path[cav.path.length - 1]![1]
1766
+ tryVent(cav.path, cavTieY)
1767
+ }
1768
+ }
1769
+ }
1770
+
1771
+ return {
1772
+ path: bestPath,
1773
+ tieInHeightM: round2(bestTieInY),
1774
+ lengthFt: round2(polylineLengthM(bestPath) * METERS_TO_FEET),
1775
+ detoured,
1776
+ clashes: bestClashes,
1777
+ }
1778
+ }
1779
+
1780
+ /**
1781
+ * Route a pressurized supply (Cold / Hot / Recirc) or Fuel Gas run:
1782
+ * - Drops vertically inside wall cavities to under-floor crawlspace/basement or attic plane
1783
+ * - Automatically detours below floor girders, over door/window headers, and clear of NEC 110.26(E)
1784
+ * electrical-panel keep-out zones & structural columns (including vertical riser/drop jogs).
1785
+ */
1786
+ export function routePressurizedPipeRun(params: {
1787
+ from: Vec3
1788
+ to: Vec3
1789
+ routingPlaneY: number
1790
+ nominalSize?: PipeNominalSize
1791
+ material?: PipeMaterial
1792
+ pipeRadiusM?: number
1793
+ euclideanInCavity?: boolean
1794
+ obstacles?: ReadonlyArray<PlumbingObstacle>
1795
+ buildingBounds?: BuildingBounds2D
1796
+ maxRoofYAt?: (x: number, z: number) => number
1797
+ cavityContext?: PlumbingCavityContext
1798
+ /** Optional explicit cavity band whitelist for Layer 2 cavity rescue. */
1799
+ allowedBands?: readonly CavityBand[]
1800
+ }): {
1801
+ path: Vec3[]
1802
+ lengthFt: number
1803
+ detoured: boolean
1804
+ clashes: PlumbingObstacle[]
1805
+ } {
1806
+ const {
1807
+ from,
1808
+ to,
1809
+ routingPlaneY,
1810
+ nominalSize,
1811
+ material = 'pex-a',
1812
+ euclideanInCavity = true,
1813
+ obstacles = [],
1814
+ buildingBounds,
1815
+ maxRoofYAt,
1816
+ cavityContext,
1817
+ } = params
1818
+ const pipeRadiusM =
1819
+ params.pipeRadiusM ?? (nominalSize ? getPipeOuterDiameterM(nominalSize, material) / 2 : 0.02)
1820
+ const env = resolveAllowedEnvelope(buildingBounds, from, [to[0], to[2]])
1821
+ const checkFootprint = Boolean(buildingBounds) && hasCavityScene(cavityContext)
1822
+
1823
+ const buildCandidate = (
1824
+ elbowFirst: 'x' | 'z' | 'diag',
1825
+ offsetM = 0,
1826
+ planeY = routingPlaneY,
1827
+ fromJog?: readonly [number, number],
1828
+ toJog?: readonly [number, number],
1829
+ customMid?: ReadonlyArray<readonly [number, number]>,
1830
+ ): Vec3[] => {
1831
+ const fx = fromJog ? fromJog[0] : from[0]
1832
+ const fz = fromJog ? fromJog[1] : from[2]
1833
+ const tx = toJog ? toJog[0] : to[0]
1834
+ const tz = toJog ? toJog[1] : to[2]
1835
+
1836
+ const pts: Vec3[] = [from]
1837
+ if (fromJog) pts.push([fx, from[1], fz])
1838
+ pts.push([fx, planeY, fz])
1839
+
1840
+ if (customMid) {
1841
+ for (const [mx, mz] of customMid) {
1842
+ pts.push([mx, planeY, mz])
1843
+ }
1844
+ } else if (elbowFirst === 'diag') {
1845
+ if (Math.abs(offsetM) >= 1e-4) {
1846
+ pts.push([(fx + tx) / 2 + offsetM, planeY, (fz + tz) / 2 - offsetM])
1847
+ }
1848
+ } else if (elbowFirst === 'x') {
1849
+ if (!euclideanInCavity && Math.abs(offsetM) >= 1e-4) {
1850
+ // Strictly orthogonal 3-segment U/Z offset for rigid / orthogonal runs
1851
+ pts.push([fx, planeY, fz + offsetM])
1852
+ pts.push([tx, planeY, fz + offsetM])
1853
+ } else {
1854
+ pts.push([tx + offsetM, planeY, fz + offsetM])
1855
+ }
1856
+ } else {
1857
+ if (!euclideanInCavity && Math.abs(offsetM) >= 1e-4) {
1858
+ pts.push([fx + offsetM, planeY, fz])
1859
+ pts.push([fx + offsetM, planeY, tz])
1860
+ } else {
1861
+ pts.push([fx + offsetM, planeY, tz + offsetM])
1862
+ }
1863
+ }
1864
+
1865
+ pts.push([tx, planeY, tz])
1866
+ if (toJog) pts.push([tx, to[1], tz])
1867
+ pts.push(to)
1868
+ return cleanPath(pts)
1869
+ }
1870
+
1871
+ const fromWallSnap = hasCavityScene(cavityContext)
1872
+ ? resolveBackingWallSnap(from, cavityContext, obstacles, pipeRadiusM, buildingBounds, checkFootprint, 1.05)
1873
+ : null
1874
+ const toWallSnap = hasCavityScene(cavityContext)
1875
+ ? resolveBackingWallSnap(to, cavityContext, obstacles, pipeRadiusM, buildingBounds, checkFootprint, 1.05)
1876
+ : null
1877
+ const wallFromJog: readonly [number, number] | undefined = fromWallSnap
1878
+ ? [fromWallSnap[0], fromWallSnap[2]]
1879
+ : undefined
1880
+ const wallToJog: readonly [number, number] | undefined = toWallSnap
1881
+ ? [toWallSnap[0], toWallSnap[2]]
1882
+ : undefined
1883
+
1884
+ const pressWallEnv =
1885
+ buildingBounds && hasCavityScene(cavityContext)
1886
+ ? resolveAllowedEnvelope(buildingBounds, from, [to[0], to[2]], -0.05)
1887
+ : env
1888
+ const primaryEnv = wallFromJog || wallToJog ? pressWallEnv : env
1889
+ const primary = buildCandidate(
1890
+ euclideanInCavity ? 'diag' : 'x',
1891
+ 0,
1892
+ routingPlaneY,
1893
+ wallFromJog,
1894
+ wallToJog,
1895
+ )
1896
+ let bestPath = primary
1897
+ let bestClashes = detectPlumbingClashes(primary, obstacles, pipeRadiusM)
1898
+ let bestBoundsViolation =
1899
+ exceedsEnvelopeXZ(primary, primaryEnv) || exceedsConcaveFootprint(primary, cavityContext, checkFootprint)
1900
+ let bestRoofViolation = exceedsRoofPlane(primary, pipeRadiusM, maxRoofYAt)
1901
+ let detoured = false
1902
+
1903
+ // Wall-Cavity-First Concealment for overhead pressurized runs (> 1.8 m):
1904
+ // Route between wall-snapped risers strictly inside connected upper wall cavities (top-plate chase)
1905
+ // so pipes stay hidden when Full Walls are enabled, while honoring BUG-PS-05 (>= 2.0 m horizontal travel)
1906
+ // and IRC R602.6 (large mains & fuel gas stay in the top-plate zone >= wallH - 0.08).
1907
+ if (hasCavityScene(cavityContext) && routingPlaneY > 1.8) {
1908
+ const coreFrom: Vec3 = fromWallSnap ?? from
1909
+ const coreTo: Vec3 = toWallSnap ?? to
1910
+ const wallH = resolveWallHeightForContext(cavityContext, Math.max(2.7, routingPlaneY + 0.25))
1911
+ const isLargeOrGas =
1912
+ material === 'black-iron' ||
1913
+ material === 'csst' ||
1914
+ Boolean(nominalSize && getPipeOuterDiameterM(nominalSize, material) > getPipeOuterDiameterM('3/4"', material) + 1e-4)
1915
+ const endpointRoofCap = maxRoofYAt
1916
+ ? Math.min(maxRoofYAt(coreFrom[0], coreFrom[2]), maxRoofYAt(coreTo[0], coreTo[2])) - pipeRadiusM - 0.09
1917
+ : Infinity
1918
+ const roofClampedMaxY = Number.isFinite(endpointRoofCap)
1919
+ ? Math.min(wallH - 0.06, endpointRoofCap)
1920
+ : wallH - 0.06
1921
+ const desiredChaseY = isLargeOrGas
1922
+ ? round4(Math.min(roofClampedMaxY, Math.max(2.05, wallH - 0.075)))
1923
+ : round4(Math.min(roofClampedMaxY, Math.max(2.05, routingPlaneY)))
1924
+ const bandPasses: ReadonlyArray<readonly CavityBand[]> = params.allowedBands
1925
+ ? [params.allowedBands]
1926
+ : [['top-plate'], ['top-plate', 'overhead-plenum', 'attic']]
1927
+ let adoptedWallSupply = false
1928
+ for (const preferredBands of bandPasses) {
1929
+ if (adoptedWallSupply) break
1930
+ const cavWall = routePlumbingViaLegalCavity({
1931
+ ...cavityContext,
1932
+ from: coreFrom,
1933
+ to: coreTo,
1934
+ mode: euclideanInCavity ? 'euclidean-cavity' : 'orthogonal',
1935
+ nominalSize,
1936
+ material,
1937
+ pipeRadiusM,
1938
+ preferWallFollowing: true,
1939
+ allowedBands: preferredBands,
1940
+ ...(preferredBands.length === 1 && preferredBands[0] === 'top-plate'
1941
+ ? { graph: undefined, roofClearanceM: 0.01 }
1942
+ : {}),
1943
+ obstacles,
1944
+ })
1945
+ if (cavWall.path.length >= 2) {
1946
+ const wrapStubs = (corePath: ReadonlyArray<Vec3>): Vec3[] => {
1947
+ const pts: Vec3[] = []
1948
+ const first = corePath[0]!
1949
+ const last = corePath[corePath.length - 1]!
1950
+ if (fromWallSnap) {
1951
+ pts.push(from)
1952
+ // Keep stub strictly horizontal/orthogonal if kernel snapped first vertex in Y or XZ
1953
+ if (Math.abs(first[1] - from[1]) > 1e-3) {
1954
+ if (!euclideanInCavity && Math.abs(first[0] - from[0]) > 0.01 && Math.abs(first[2] - from[2]) > 0.01) {
1955
+ pts.push([first[0], from[1], from[2]])
1956
+ }
1957
+ pts.push([first[0], from[1], first[2]])
1958
+ } else if (!euclideanInCavity && Math.abs(first[0] - from[0]) > 0.01 && Math.abs(first[2] - from[2]) > 0.01) {
1959
+ pts.push([first[0], from[1], from[2]])
1960
+ }
1961
+ }
1962
+ pts.push(...corePath)
1963
+ if (toWallSnap) {
1964
+ if (Math.abs(last[1] - to[1]) > 1e-3) {
1965
+ pts.push([last[0], to[1], last[2]])
1966
+ if (!euclideanInCavity && Math.abs(to[0] - last[0]) > 0.01 && Math.abs(to[2] - last[2]) > 0.01) {
1967
+ pts.push([to[0], to[1], last[2]])
1968
+ }
1969
+ } else if (!euclideanInCavity && Math.abs(to[0] - last[0]) > 0.01 && Math.abs(to[2] - last[2]) > 0.01) {
1970
+ pts.push([to[0], to[1], last[2]])
1971
+ }
1972
+ pts.push(to)
1973
+ }
1974
+ return cleanPath(pts)
1975
+ }
1976
+ const remappedCore = remapOverheadHorizontalBand(cavWall.path, desiredChaseY, 2.0)
1977
+ const coreCandidates = [remappedCore, cavWall.path]
1978
+ const obeysOverheadFloor = (p: ReadonlyArray<Vec3>): boolean => {
1979
+ for (let i = 1; i < p.length; i++) {
1980
+ const a = p[i - 1]!
1981
+ const b = p[i]!
1982
+ if (Math.hypot(b[0] - a[0], b[2] - a[2]) > 0.5 && Math.min(a[1], b[1]) < 2.0 - 1e-3) {
1983
+ return false
1984
+ }
1985
+ }
1986
+ return true
1987
+ }
1988
+ const obeysOrthogonality = (p: ReadonlyArray<Vec3>): boolean => {
1989
+ if (euclideanInCavity) return true
1990
+ for (let i = 1; i < p.length; i++) {
1991
+ const a = p[i - 1]!
1992
+ const b = p[i]!
1993
+ const dx = Math.abs(b[0] - a[0])
1994
+ const dz = Math.abs(b[2] - a[2])
1995
+ if ((dx > 0.02 || dz > 0.02) && Math.min(dx, dz) >= 0.01) {
1996
+ return false
1997
+ }
1998
+ }
1999
+ return true
2000
+ }
2001
+ for (const coreCand of coreCandidates) {
2002
+ if (!obeysOverheadFloor(coreCand)) continue
2003
+ const cand = wrapStubs(coreCand)
2004
+ if (
2005
+ obeysOrthogonality(cand) &&
2006
+ !exceedsEnvelopeXZ(cand, pressWallEnv) &&
2007
+ !exceedsConcaveFootprint(cand, cavityContext, checkFootprint) &&
2008
+ !exceedsRoofPlane(cand, pipeRadiusM, maxRoofYAt) &&
2009
+ detectPlumbingClashes(cand, obstacles, pipeRadiusM).length === 0
2010
+ ) {
2011
+ if (bestClashes.length > 0 || bestBoundsViolation || bestRoofViolation) detoured = true
2012
+ bestPath = cand
2013
+ bestClashes = []
2014
+ bestBoundsViolation = false
2015
+ bestRoofViolation = false
2016
+ adoptedWallSupply = true
2017
+ break
2018
+ }
2019
+ }
2020
+ }
2021
+ }
2022
+ }
2023
+
2024
+ if (bestClashes.length > 0 || bestBoundsViolation || bestRoofViolation) {
2025
+ const maxEval = 300
2026
+ let evalCount = 0
2027
+ const tryPressurized = (cand: Vec3[], bypassBudget = false): boolean => {
2028
+ if (!bypassBudget && evalCount >= maxEval) return true
2029
+ if (!bypassBudget) evalCount += 1
2030
+ const boundsViol =
2031
+ exceedsEnvelopeXZ(cand, pressWallEnv) || exceedsConcaveFootprint(cand, cavityContext, checkFootprint)
2032
+ const roofViol = exceedsRoofPlane(cand, pipeRadiusM, maxRoofYAt)
2033
+ if (boundsViol && !bestBoundsViolation) return !bypassBudget && evalCount >= maxEval
2034
+ if (roofViol && !bestRoofViolation && boundsViol === bestBoundsViolation) return !bypassBudget && evalCount >= maxEval
2035
+ const c = detectPlumbingClashes(cand, obstacles, pipeRadiusM)
2036
+ const better =
2037
+ (bestBoundsViolation && !boundsViol) ||
2038
+ (boundsViol === bestBoundsViolation && bestRoofViolation && !roofViol) ||
2039
+ (boundsViol === bestBoundsViolation && roofViol === bestRoofViolation && c.length < bestClashes.length)
2040
+ if (better) {
2041
+ bestPath = cand
2042
+ bestClashes = c
2043
+ bestBoundsViolation = boundsViol
2044
+ bestRoofViolation = roofViol
2045
+ detoured = true
2046
+ }
2047
+ return (
2048
+ (bestClashes.length === 0 && !bestBoundsViolation && !bestRoofViolation) ||
2049
+ (!bypassBudget && evalCount >= maxEval)
2050
+ )
2051
+ }
2052
+
2053
+ const edgePad = pipeRadiusM + 0.07
2054
+ const allUnderBeams = obstacles.filter(isUnderFloorBeamObstacle)
2055
+ const structuralHits = bestClashes.filter(isUnderFloorBeamObstacle)
2056
+ const elevatedHits = bestClashes.filter(isElevatedBeamObstacle)
2057
+ const allElevatedAreHeaders =
2058
+ elevatedHits.length > 0 &&
2059
+ elevatedHits.every((o) => o.beamRole === 'header' || /header/i.test(o.label))
2060
+
2061
+ const planeYs: number[] = []
2062
+ const pushPlaneY = (y: number) => {
2063
+ if (!planeYs.some((v) => Math.abs(v - y) < 0.015)) planeYs.push(y)
2064
+ }
2065
+
2066
+ if (structuralHits.length > 0) {
2067
+ pushPlaneY(
2068
+ Math.min(routingPlaneY - 0.16, Math.min(...structuralHits.map((o) => o.box.minY)) - pipeRadiusM - 0.06),
2069
+ )
2070
+ }
2071
+ if (allUnderBeams.length > 0 && routingPlaneY <= 0.25) {
2072
+ pushPlaneY(
2073
+ Math.min(routingPlaneY - 0.16, Math.min(...allUnderBeams.map((o) => o.box.minY)) - pipeRadiusM - 0.06),
2074
+ )
2075
+ }
2076
+ if (elevatedHits.length > 0) {
2077
+ const aboveHit = Math.max(...elevatedHits.map((o) => o.box.maxY)) + pipeRadiusM + 0.06
2078
+ const belowHit = Math.min(...elevatedHits.map((o) => o.box.minY)) - pipeRadiusM - 0.06
2079
+ const aboveViolatesRoof =
2080
+ maxRoofYAt !== undefined &&
2081
+ aboveHit + pipeRadiusM >
2082
+ Math.min(maxRoofYAt(from[0], from[2]), maxRoofYAt(to[0], to[2])) - 0.08 + 1e-4
2083
+ // Always try routing OVER door/window headers first; suppress belowHit on overhead runs (> 1.8m)
2084
+ // when routing over fits beneath the roof envelope so supply pipes never drop across open doorways/windows.
2085
+ pushPlaneY(aboveHit)
2086
+ if (!(allElevatedAreHeaders && routingPlaneY > 1.8 && !aboveViolatesRoof)) {
2087
+ pushPlaneY(belowHit)
2088
+ }
2089
+ }
2090
+ pushPlaneY(routingPlaneY)
2091
+ if (!(allElevatedAreHeaders && routingPlaneY > 1.8)) {
2092
+ pushPlaneY(routingPlaneY - 0.28)
2093
+ }
2094
+ if (maxRoofYAt) {
2095
+ const endpointRoofCap =
2096
+ Math.min(maxRoofYAt(from[0], from[2]), maxRoofYAt(to[0], to[2])) - pipeRadiusM - 0.09
2097
+ const primaryRoofCap = minRoofAlongPath(primary, maxRoofYAt) - pipeRadiusM - 0.09
2098
+ const roofSafeY = Math.min(endpointRoofCap, primaryRoofCap)
2099
+ if (bestRoofViolation || roofSafeY < routingPlaneY) {
2100
+ if (Number.isFinite(endpointRoofCap) && endpointRoofCap < routingPlaneY) {
2101
+ pushPlaneY(endpointRoofCap)
2102
+ }
2103
+ if (Number.isFinite(primaryRoofCap) && primaryRoofCap < routingPlaneY) {
2104
+ pushPlaneY(primaryRoofCap)
2105
+ }
2106
+ if (Number.isFinite(roofSafeY) && roofSafeY < routingPlaneY) {
2107
+ pushPlaneY(roofSafeY - 0.12)
2108
+ }
2109
+ }
2110
+ }
2111
+
2112
+ // Probe the FULL vertical riser/drop envelope [minPlaneY, maxPlaneY] so headers/girders
2113
+ // sitting anywhere between endpoint elevation and any candidate routing plane are caught.
2114
+ const minPlaneY = Math.min(...planeYs)
2115
+ const maxPlaneY = Math.max(...planeYs)
2116
+ const fromDropHits = detectPlumbingClashes(
2117
+ [
2118
+ [from[0], Math.min(from[1], minPlaneY), from[2]],
2119
+ [from[0], Math.max(from[1], maxPlaneY), from[2]],
2120
+ ],
2121
+ obstacles,
2122
+ pipeRadiusM,
2123
+ )
2124
+ const toRiseHits = detectPlumbingClashes(
2125
+ [
2126
+ [to[0], Math.min(to[1], minPlaneY), to[2]],
2127
+ [to[0], Math.max(to[1], maxPlaneY), to[2]],
2128
+ ],
2129
+ obstacles,
2130
+ pipeRadiusM,
2131
+ )
2132
+
2133
+ const prefilterJogs = (
2134
+ anchor: Vec3,
2135
+ rawEscapes: ReadonlyArray<readonly [number, number]>,
2136
+ limit = 4,
2137
+ ): Array<readonly [number, number] | undefined> => {
2138
+ if (rawEscapes.length === 0) return [undefined]
2139
+ const yLo = Math.min(anchor[1], minPlaneY)
2140
+ const yHi = Math.max(anchor[1], maxPlaneY)
2141
+ const scored = rawEscapes
2142
+ .filter(([jx, jz]) => {
2143
+ if (
2144
+ pressWallEnv &&
2145
+ (jx < pressWallEnv.minX - 1e-4 ||
2146
+ jx > pressWallEnv.maxX + 1e-4 ||
2147
+ jz < pressWallEnv.minZ - 1e-4 ||
2148
+ jz > pressWallEnv.maxZ + 1e-4)
2149
+ ) {
2150
+ return false
2151
+ }
2152
+ if (
2153
+ checkFootprint &&
2154
+ exceedsConcaveFootprint([anchor, [jx, anchor[1], jz]], cavityContext, true)
2155
+ ) {
2156
+ return false
2157
+ }
2158
+ return true
2159
+ })
2160
+ .map((jog) => {
2161
+ const leg: Vec3[] = [
2162
+ anchor,
2163
+ [jog[0], anchor[1], jog[1]],
2164
+ [jog[0], yLo, jog[1]],
2165
+ [jog[0], yHi, jog[1]],
2166
+ ]
2167
+ const clashCount = detectPlumbingClashes(leg, obstacles, pipeRadiusM).length
2168
+ const dist = Math.hypot(jog[0] - anchor[0], jog[1] - anchor[2])
2169
+ return { jog, clashCount, dist }
2170
+ })
2171
+ scored.sort((a, b) => a.clashCount - b.clashCount || a.dist - b.dist)
2172
+ return [undefined, ...scored.slice(0, limit).map((s) => s.jog)]
2173
+ }
2174
+
2175
+ const fromJogs = prefilterJogs(
2176
+ from,
2177
+ fromDropHits.length > 0 ? buildLateralEscapeCandidates(from[0], from[2], fromDropHits, edgePad) : [],
2178
+ )
2179
+ const toJogs = prefilterJogs(
2180
+ to,
2181
+ toRiseHits.length > 0 ? buildLateralEscapeCandidates(to[0], to[2], toRiseHits, edgePad) : [],
2182
+ )
2183
+
2184
+ const modes: ReadonlyArray<readonly ['x' | 'z' | 'diag', number]> = euclideanInCavity
2185
+ ? [
2186
+ ['diag', 0],
2187
+ ['x', 0],
2188
+ ['z', 0],
2189
+ ['x', 0.55],
2190
+ ['x', -0.55],
2191
+ ['z', 0.55],
2192
+ ['z', -0.55],
2193
+ ['diag', 0.75],
2194
+ ['diag', -0.75],
2195
+ ['x', 1.15],
2196
+ ['x', -1.15],
2197
+ ['z', 1.15],
2198
+ ['z', -1.15],
2199
+ ]
2200
+ : [
2201
+ ['x', 0],
2202
+ ['z', 0],
2203
+ ['x', 0.55],
2204
+ ['x', -0.55],
2205
+ ['z', 0.55],
2206
+ ['z', -0.55],
2207
+ ['x', 1.15],
2208
+ ['x', -1.15],
2209
+ ['z', 1.15],
2210
+ ['z', -1.15],
2211
+ ]
2212
+
2213
+ const isDone = () =>
2214
+ (bestClashes.length === 0 && !bestBoundsViolation && !bestRoofViolation) || evalCount >= maxEval
2215
+
2216
+ for (const fJog of fromJogs) {
2217
+ for (const tJog of toJogs) {
2218
+ const fx = fJog ? fJog[0] : from[0]
2219
+ const fz = fJog ? fJog[1] : from[2]
2220
+ const tx = tJog ? tJog[0] : to[0]
2221
+ const tz = tJog ? tJog[1] : to[2]
2222
+ const dynMids = buildObstacleDetourWaypoints([fx, fz], [tx, tz], bestClashes, edgePad)
2223
+
2224
+ const primaryCount = euclideanInCavity ? 3 : 2
2225
+ for (const py of planeYs) {
2226
+ // Try all zero-offset base modes (['diag',0], ['x',0], ['z',0]) and targeted obstacle detours before blind offsets
2227
+ for (const [m, off] of modes.slice(0, primaryCount)) {
2228
+ if (tryPressurized(buildCandidate(m, off, py, fJog, tJog))) break
2229
+ }
2230
+ if (isDone()) break
2231
+ for (const mid of dynMids) {
2232
+ if (tryPressurized(buildCandidate('x', 0, py, fJog, tJog, mid))) break
2233
+ }
2234
+ if (isDone()) break
2235
+ for (const [m, off] of modes.slice(primaryCount)) {
2236
+ if (tryPressurized(buildCandidate(m, off, py, fJog, tJog))) break
2237
+ }
2238
+ if (isDone()) break
2239
+ }
2240
+ if (isDone()) break
2241
+ }
2242
+ if (isDone()) break
2243
+ }
2244
+
2245
+ // Layer 2 — Legal-Space-First Cavity Rescue:
2246
+ // - Sub-floor planes (<= 0.1 m): strictly under-slab / crawlspace
2247
+ // - Low-elevation appliance runs (0.1 m < y <= 0.6 m, e.g. 4" dryer vent at 0.35 m): allow under-sill / mid-wall / overhead-plenum
2248
+ // - Overhead pressurized water/gas mains (> 0.6 m): strictly overhead-plenum / attic (never intrude on mid-wall/top-plate electrical chases)
2249
+ if ((bestClashes.length > 0 || bestBoundsViolation || bestRoofViolation) && hasCavityScene(cavityContext)) {
2250
+ const allowedBands: readonly CavityBand[] =
2251
+ params.allowedBands ??
2252
+ (routingPlaneY <= 0.1
2253
+ ? ['under-slab', 'crawlspace']
2254
+ : routingPlaneY <= 0.6
2255
+ ? ['under-sill', 'mid-wall', 'overhead-plenum']
2256
+ : ['overhead-plenum', 'attic'])
2257
+ const cav = routePlumbingViaLegalCavity({
2258
+ ...cavityContext,
2259
+ from,
2260
+ to,
2261
+ mode: euclideanInCavity ? 'euclidean-cavity' : 'orthogonal',
2262
+ nominalSize,
2263
+ material,
2264
+ pipeRadiusM,
2265
+ allowedBands,
2266
+ obstacles,
2267
+ })
2268
+ if (cav.path.length >= 2) {
2269
+ tryPressurized(cav.path, true)
2270
+ }
2271
+ }
2272
+ }
2273
+
2274
+ return {
2275
+ path: bestPath,
2276
+ lengthFt: round2(polylineLengthM(bestPath) * METERS_TO_FEET),
2277
+ detoured,
2278
+ clashes: bestClashes,
2279
+ }
2280
+ }