@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,4555 @@
1
+ /**
2
+ * One-Click IPC/UPC Auto-Populate & Bones Schematic Ingestion (`src/ipc/autopopulate.ts`).
3
+ *
4
+ * Scans Pascal scene rooms, walls, slabs, placed Pascal `item`/`cabinet` fixtures,
5
+ * and optional `@pascal-app/plugin-bones` (`bones:framing`, `bones:service`) anchors to generate
6
+ * a complete, code-compliant 3D plumbing network:
7
+ * - Main water entry (shutoff + PRV + backflow)
8
+ * - Water heater (tank / tankless / HPWH) + thermal expansion tank
9
+ * - PEX Home-Run Manifold (or Copper/PEX Trunk-and-Branch)
10
+ * - Wet-wall fixture rough-ins + minimum 2 exterior frost-proof hose bibbs
11
+ * - Gravity-sloped DWV drains (1/4"/ft / 1/8"/ft), 3" main vent stack, dry re-vents (>= 6" above flood rim), & cleanouts
12
+ * - Optional Fuel Gas (IFGC) & Rigid 4" Dryer Vent (IRC M1502.4)
13
+ * - Full `electricalDemand` payloads on every powered unit for automatic Electrical Panel coordination!
14
+ *
15
+ * Framework-free: zero React, Three.js, or `@pascal-app/*` imports.
16
+ */
17
+
18
+ import {
19
+ type LegalCavityGraph,
20
+ compileBuildingAnatomy,
21
+ compileLegalCavityGraph,
22
+ evaluatePlacementCandidate,
23
+ } from '@kruschdev/pascal-mep-kernel'
24
+ import {
25
+ type ElectricalPowerDemand,
26
+ type SceneNodeLike,
27
+ type Vec3,
28
+ belongsToLevel,
29
+ checkWetWallPipeFit,
30
+ extractBonesPlumbingContext,
31
+ getEquipmentElectricalDemand,
32
+ getFixtureElectricalDemand,
33
+ getLowerWalledLevelIds,
34
+ isGroundOrLowestWalledLevel,
35
+ resolveBonesAnchorPosition,
36
+ resolveEffectiveWallThicknessM,
37
+ } from './framing-interop'
38
+
39
+ export { isGroundOrLowestWalledLevel } from './framing-interop'
40
+ import {
41
+ type PlumbingCavityContext,
42
+ type RoomPolygon2D,
43
+ type WallOpeningSpan,
44
+ type WallSegment2D,
45
+ countPathElbows,
46
+ extractRoomPolygons,
47
+ extractWallSegments,
48
+ mapCanonicalWallsToOpenings,
49
+ mapOccupancyObstaclesToPlumbing,
50
+ nearestWallToPoint,
51
+ pointInPolygon2D,
52
+ resolveLevelHeightM,
53
+ routeDwvDrainRun,
54
+ routePressurizedPipeRun,
55
+ routeVentRun,
56
+ } from './routing'
57
+ import { IPC_RULE_THRESHOLDS, getIpcRuleById } from './rules'
58
+ import {
59
+ checkDryerVentRun,
60
+ sizeBuildingDrain,
61
+ sizeDrainBranch,
62
+ sizeFuelGasPipe,
63
+ sizeSupplyPipe,
64
+ sizeVentStack,
65
+ sizeWaterHeater,
66
+ } from './sizing'
67
+ import {
68
+ type CodeEdition,
69
+ type EquipmentKind,
70
+ FIXTURE_SPECS,
71
+ type FixtureKind,
72
+ type FoundationType,
73
+ type ManifoldKind,
74
+ type OccupancyType,
75
+ PIPE_NOMINAL_INCHES,
76
+ type PipeMaterial,
77
+ type PipeNominalSize,
78
+ type PlumbingSystem,
79
+ type SupplyTopology,
80
+ getFixtureDfu,
81
+ getFixtureWsfu,
82
+ getPipeOuterDiameterM,
83
+ round2,
84
+ } from './tables'
85
+
86
+ export type BonesIngestionMode = 'auto' | 'import-only' | 'ignore'
87
+
88
+ export type PlumbingAutoPopulateOptions = {
89
+ levelId?: string | null
90
+ occupancy?: OccupancyType
91
+ codeEdition?: CodeEdition
92
+ supplyTopology?: SupplyTopology
93
+ supplyMaterial?: 'pex-a' | 'pex-b' | 'copper-l' | 'cpvc'
94
+ dwvMaterial?: 'pvc-dwv' | 'abs-dwv' | 'cast-iron'
95
+ foundationType?: FoundationType
96
+ waterHeaterKind?:
97
+ | 'water-heater-tank-electric'
98
+ | 'water-heater-tank-gas'
99
+ | 'water-heater-tankless-gas'
100
+ | 'water-heater-hpwh'
101
+ includeFuelGas?: boolean
102
+ includeDryerVent?: boolean
103
+ includeHotRecirc?: boolean
104
+ bonesMode?: BonesIngestionMode
105
+ }
106
+
107
+ export type PlannedEquipmentSpec = {
108
+ id: string
109
+ name: string
110
+ equipmentKind: EquipmentKind
111
+ position: Vec3
112
+ rotation: number
113
+ roomName: string
114
+ capacityGal?: number
115
+ gasBtuh?: number
116
+ watts?: number
117
+ hasDrainPan?: boolean
118
+ hasTpDischarge?: boolean
119
+ hasExpansionTank?: boolean
120
+ electricalDemand?: ElectricalPowerDemand | null
121
+ furnishingSourceId?: string
122
+ catalogSku?: string
123
+ roughInOnly?: boolean
124
+ }
125
+
126
+ export type PlannedManifoldSpec = {
127
+ id: string
128
+ name: string
129
+ manifoldKind: ManifoldKind
130
+ position: Vec3
131
+ rotation: number
132
+ portCount: number
133
+ supplyMaterial: PipeMaterial
134
+ coverRemoved: boolean
135
+ furnishingSourceId?: string
136
+ catalogSku?: string
137
+ roughInOnly?: boolean
138
+ }
139
+
140
+ export type PlannedFixtureSpec = {
141
+ id: string
142
+ name: string
143
+ fixtureKind: FixtureKind
144
+ position: Vec3
145
+ rotation: number
146
+ roomName: string
147
+ wallId?: string
148
+ dfu: number
149
+ wsfuCold: number
150
+ wsfuHot: number
151
+ wsfuTotal: number
152
+ trapSize: PipeNominalSize | null
153
+ drainSize: PipeNominalSize | null
154
+ ventSize: PipeNominalSize | null
155
+ supplySize: PipeNominalSize | null
156
+ hasVacuumBreaker: boolean
157
+ hasPTrap: boolean
158
+ electricalDemand?: ElectricalPowerDemand | null
159
+ furnishingSourceId?: string
160
+ catalogSku?: string
161
+ roughInOnly?: boolean
162
+ }
163
+
164
+ export type PlannedPipeRunSpec = {
165
+ id: string
166
+ name: string
167
+ system: PlumbingSystem
168
+ material: PipeMaterial
169
+ nominalSize: PipeNominalSize
170
+ path: Vec3[]
171
+ slopeInPerFt: number
172
+ dfuLoad: number
173
+ wsfuLoad: number
174
+ gasBtuh: number
175
+ sourceNodeId?: string
176
+ targetNodeId?: string
177
+ hasCleanout: boolean
178
+ hasSedimentTrap: boolean
179
+ hasShutoffWithin6Ft: boolean
180
+ isHorizontalSanTee: boolean
181
+ isMainVentStack: boolean
182
+ trapArmLengthFt?: number
183
+ wallId?: string
184
+ }
185
+
186
+ export type PlumbingAutoPopulatePlan = {
187
+ levelId: string | null
188
+ codeEdition: CodeEdition
189
+ supplyTopology: SupplyTopology
190
+ foundationType: FoundationType
191
+ equipment: PlannedEquipmentSpec[]
192
+ manifolds: PlannedManifoldSpec[]
193
+ fixtures: PlannedFixtureSpec[]
194
+ pipeRuns: PlannedPipeRunSpec[]
195
+ bonesAnchorsUsed: string[]
196
+ summary: string
197
+ }
198
+
199
+ export type FurnishingPlumbingRole =
200
+ | {
201
+ role: 'fixture'
202
+ fixtureKind: FixtureKind
203
+ basins: 1 | 2
204
+ priority: 1 | 2
205
+ widthM: number
206
+ sku?: string
207
+ label: string
208
+ }
209
+ | {
210
+ role: 'water-heater'
211
+ equipmentKind:
212
+ | 'water-heater-tank-electric'
213
+ | 'water-heater-tank-gas'
214
+ | 'water-heater-tankless-gas'
215
+ | 'water-heater-hpwh'
216
+ capacityGal: number
217
+ sku?: string
218
+ label: string
219
+ }
220
+ | {
221
+ role: 'manifold'
222
+ portCount: number
223
+ sku?: string
224
+ label: string
225
+ }
226
+ | {
227
+ role: 'gas-appliance'
228
+ btuh: number
229
+ sku?: string
230
+ label: string
231
+ }
232
+ | {
233
+ role: 'ice-maker'
234
+ wsfuCold: number
235
+ sku?: string
236
+ label: string
237
+ }
238
+ | {
239
+ role: 'dryer'
240
+ isGas: boolean
241
+ sku?: string
242
+ label: string
243
+ }
244
+
245
+ const FURNISHING_DISCOVERY_NODE_TYPES = new Set([
246
+ 'item',
247
+ 'cabinet',
248
+ 'procedural-item',
249
+ 'catalog:sku-item',
250
+ 'furnishings:item',
251
+ 'furnishings:electronics',
252
+ ])
253
+
254
+ function rotateLocal2D(cx: number, cz: number, lx: number, lz: number, rot: number): [number, number] {
255
+ const cos = Math.cos(rot)
256
+ const sin = Math.sin(rot)
257
+ return [round2(cx + lx * cos + lz * sin), round2(cz - lx * sin + lz * cos)]
258
+ }
259
+
260
+ /**
261
+ * Compute rotation-aware cold or hot supply stub-out world coordinates for a fixture so
262
+ * N/S/E/W-facing fixtures always receive properly aligned side-by-side angle-stop connections.
263
+ */
264
+ export function getFixtureSupplyPoint(
265
+ fix: Pick<PlannedFixtureSpec, 'fixtureKind' | 'position' | 'rotation'>,
266
+ side: 'cold' | 'hot',
267
+ ): Vec3 {
268
+ const rot = typeof fix.rotation === 'number' && Number.isFinite(fix.rotation) ? fix.rotation : 0
269
+ if (fix.fixtureKind === 'hose-bibb') {
270
+ const [px, pz] = rotateLocal2D(fix.position[0], fix.position[2], 0, -0.14, rot)
271
+ return [px, fix.position[1], pz]
272
+ }
273
+ if (fix.fixtureKind === 'water-closet') {
274
+ // Standard US rear-left toilet cold angle stop (-0.12m local X, -0.16m local Z)
275
+ const [px, pz] = rotateLocal2D(fix.position[0], fix.position[2], -0.12, -0.16, rot)
276
+ return [px, fix.position[1], pz]
277
+ }
278
+ const lx = side === 'cold' ? 0.08 : -0.08
279
+ const [px, pz] = rotateLocal2D(fix.position[0], fix.position[2], lx, 0, rot)
280
+ return [px, fix.position[1], pz]
281
+ }
282
+
283
+ function resolveNodeWidthMeters(node: SceneNodeLike, fallbackM: number): number {
284
+ if (typeof node.widthM === 'number' && Number.isFinite(node.widthM) && node.widthM > 0.2 && node.widthM <= 5) {
285
+ return node.widthM
286
+ }
287
+ const dimsMm = node.dimensionsMm as ReadonlyArray<number> | undefined
288
+ if (
289
+ Array.isArray(dimsMm) &&
290
+ typeof dimsMm[0] === 'number' &&
291
+ Number.isFinite(dimsMm[0]) &&
292
+ dimsMm[0] > 200 &&
293
+ dimsMm[0] <= 5000
294
+ ) {
295
+ return dimsMm[0] / 1000
296
+ }
297
+ const name = String(node.name ?? '')
298
+ const inMatch = name.match(/\b(\d{2})\s*(?:"|in\b|-?inch)/i)
299
+ if (inMatch) {
300
+ const inches = Number(inMatch[1])
301
+ if (inches >= 18 && inches <= 96) return round2(inches * 0.0254)
302
+ }
303
+ return fallbackM
304
+ }
305
+
306
+ /**
307
+ * Inspect any native Pascal `item`/`cabinet`/`procedural-item`, `@kruschdev/pascal-plugin-catalog`
308
+ * `catalog:sku-item`, or `@kruschdev/pascal-plugin-furnishings` node and classify its plumbing role
309
+ * (fixture, water heater, PEX manifold, fuel-gas range/dryer, refrigerator ice-maker, or dryer vent).
310
+ */
311
+ export function inferCatalogOrFurnishingPlumbingRole(node: SceneNodeLike): FurnishingPlumbingRole | null {
312
+ if (node.visible === false || !FURNISHING_DISCOVERY_NODE_TYPES.has(node.type)) return null
313
+
314
+ const meta = (node.metadata as Record<string, unknown> | undefined) ?? undefined
315
+ const sku = typeof node.sku === 'string' && node.sku.trim() ? node.sku.trim() : undefined
316
+ const recipeId = String(node.customRecipeId ?? meta?.recipeId ?? '').trim().toLowerCase()
317
+ const trade = String(node.customTrade ?? meta?.trade ?? '').trim().toLowerCase()
318
+ const rawName = String(node.name ?? (node.asset as { name?: string } | undefined)?.name ?? '').trim()
319
+ const hay = `${rawName} ${sku ?? ''} ${recipeId} ${String(node.assetId ?? '')} ${String(node.category ?? '')} ${String(node.kind ?? '')} ${String(node.itemKind ?? '')}`.toLowerCase()
320
+
321
+ // Strict negative guards: never misclassify lighting bars ("Vanity Bar"), non-sink cabinets,
322
+ // structural/fenestration/surface SKUs, furniture, electronics, or bath decor as plumbing fixtures.
323
+ if (
324
+ trade === 'lighting' ||
325
+ trade === 'surfaces' ||
326
+ trade === 'structural' ||
327
+ trade === 'fenestration' ||
328
+ trade === 'outdoor' ||
329
+ trade === 'electrical' ||
330
+ trade === 'hvac' ||
331
+ recipeId.startsWith('lighting-') ||
332
+ recipeId.startsWith('surfaces-') ||
333
+ recipeId.startsWith('structural-') ||
334
+ recipeId.startsWith('door-') ||
335
+ recipeId.startsWith('window-') ||
336
+ recipeId.startsWith('outdoor-') ||
337
+ recipeId === 'cabinet-base-shaker' ||
338
+ recipeId === 'cabinet-drawer-base' ||
339
+ recipeId === 'cabinet-wall-shaker' ||
340
+ recipeId === 'cabinet-tall-pantry' ||
341
+ recipeId === 'millwork-stair-flight' ||
342
+ (recipeId === 'cabinet-kitchen-island' && !/\bsink\b|wet.?bar|prep.?sink/.test(hay))
343
+ ) {
344
+ return null
345
+ }
346
+ if (
347
+ /\b(sconce|chandelier|pendant|vanity\s*(?:bar|light)|ceiling\s*fan|lantern|lamp|recessed\s*(?:light|can|downlight|troffer)|under[- ]?cabinet)\b/.test(
348
+ hay,
349
+ )
350
+ ) {
351
+ return null
352
+ }
353
+ if (
354
+ /\brug\b|\bmat\b|towel|curtain|\bpaper\b|\broll\b|brush|holder|caddy|soap|dispenser|sculpture|statue|ornate|mirror|\bshelf\b|hamper|basket|\bplant(?:er|s)?\b|artwork|pillow|\bsofa\b|\bchair\b|\bdesk\b|nightstand|dresser|bookcase|\btv\b|television|speaker|monitor|laptop|projector/.test(
355
+ hay,
356
+ )
357
+ ) {
358
+ return null
359
+ }
360
+
361
+ // 1. Real-world Water Heater SKU (`fixture-water-heater`, Rheem/AO Smith, etc.)
362
+ if (
363
+ recipeId === 'fixture-water-heater' ||
364
+ (sku && /^(AOS-GCR|RHM-PROPH|RHM-XE|RHM-XG)/i.test(sku)) ||
365
+ /\bwater.?heater\b/.test(hay)
366
+ ) {
367
+ const equipmentKind:
368
+ | 'water-heater-tank-electric'
369
+ | 'water-heater-tank-gas'
370
+ | 'water-heater-tankless-gas'
371
+ | 'water-heater-hpwh' = /hpwh|heat.?pump|proph/.test(hay)
372
+ ? 'water-heater-hpwh'
373
+ : /tankless/.test(hay)
374
+ ? 'water-heater-tankless-gas'
375
+ : /\bgas\b|gcr|xg\d/.test(hay)
376
+ ? 'water-heater-tank-gas'
377
+ : 'water-heater-tank-electric'
378
+ const galMatch = hay.match(/\b(\d{2,3})\s*-?\s*gal/) ?? (sku ? sku.match(/(?:gcr|proph|xe|xg)(\d{2})/i) : null)
379
+ const capacityGal = galMatch ? Math.max(20, Math.min(200, Number(galMatch[1]))) : 50
380
+ return {
381
+ role: 'water-heater',
382
+ equipmentKind,
383
+ capacityGal,
384
+ ...(sku ? { sku } : {}),
385
+ label: rawName || 'Water Heater',
386
+ }
387
+ }
388
+
389
+ // 2. Real-world PEX Manifold SKU (`plumbing-pex-manifold`, Sioux Chief)
390
+ if (recipeId === 'plumbing-pex-manifold' || (sku && /^SC-PEX-MAN/i.test(sku))) {
391
+ const portMatch = hay.match(/\b(\d{1,2})\s*-?\s*port/) ?? (sku ? sku.match(/MAN-?(\d{1,2})/i) : null)
392
+ const portCount = portMatch ? Math.max(4, Math.min(36, Number(portMatch[1]))) : 12
393
+ return {
394
+ role: 'manifold',
395
+ portCount,
396
+ ...(sku ? { sku } : {}),
397
+ label: rawName || 'PEX Distribution Manifold',
398
+ }
399
+ }
400
+
401
+ // 3. Gas Range / Cooktop -> IFGC Fuel-Gas Target (65 kBTU/hr)
402
+ if (
403
+ (recipeId === 'appliance-range-30in' || /\b(?:gas\s*(?:range|stove|cooktop|oven)|slide-in\s*gas\s*range)\b/.test(hay)) &&
404
+ /\bgas\b/.test(hay) &&
405
+ !/\b(electric|induction|microwave)\b/.test(hay)
406
+ ) {
407
+ return {
408
+ role: 'gas-appliance',
409
+ btuh: 65000,
410
+ ...(sku ? { sku } : {}),
411
+ label: rawName || 'Gas Range',
412
+ }
413
+ }
414
+
415
+ // 4. French-Door Refrigerator -> 1/2" Cold-Water Ice-Maker Supply Line (no hot, no drain)
416
+ if (
417
+ (recipeId === 'appliance-french-fridge' || /\b(?:refrigerator|fridge|ice.?maker)\b/.test(hay)) &&
418
+ !/\b(?:mini[- ]?fridge|wine[- ]?(?:fridge|cooler)|beverage)\b/.test(hay)
419
+ ) {
420
+ return {
421
+ role: 'ice-maker',
422
+ wsfuCold: 0.5,
423
+ ...(sku ? { sku } : {}),
424
+ label: rawName || 'Refrigerator Ice Maker',
425
+ }
426
+ }
427
+
428
+ // 5. Dedicated Clothes Dryer (NOT a washer or washer-dryer combo) -> 4" Rigid Dryer Vent (+ gas if gas dryer)
429
+ // Check name/SKU directly so shared recipeId `appliance-washer-dryer` never masks dedicated dryer SKUs like LG-DLEX4000B.
430
+ const nameAndSku = `${rawName} ${sku ?? ''}`.toLowerCase()
431
+ if (
432
+ !(/\b(?:hair|blow|hand)\s*dryer\b/.test(hay)) &&
433
+ ((/\bdryer\b/.test(nameAndSku) && !/\bwasher\b|washing/.test(nameAndSku)) ||
434
+ Boolean(sku && /^(LG-DLEX|LG-DLGX|SAM-DVE|SAM-DVG|WHP-WED|WHP-WGD)/i.test(sku)))
435
+ ) {
436
+ return {
437
+ role: 'dryer',
438
+ isGas: /\bgas\b|dlgx|dvg|wgd/.test(nameAndSku),
439
+ ...(sku ? { sku } : {}),
440
+ label: rawName || 'Clothes Dryer',
441
+ }
442
+ }
443
+
444
+ // 6. Authoritative Catalog Recipe Fixture Mapping (before generic keyword fallback)
445
+ if (recipeId === 'fixture-toilet-two-piece') {
446
+ return { role: 'fixture', fixtureKind: 'water-closet', basins: 1, priority: 2, widthM: resolveNodeWidthMeters(node, 0.45), ...(sku ? { sku } : {}), label: rawName || 'Toilet' }
447
+ }
448
+ if (recipeId === 'cabinet-vanity-sink') {
449
+ const isDouble = /double.?basin|double.?sink|dual.?basin|dual.?vanity/.test(hay) || Boolean(sku && /-\d{2}D$/i.test(sku))
450
+ return {
451
+ role: 'fixture',
452
+ fixtureKind: 'lavatory',
453
+ basins: isDouble ? 2 : 1,
454
+ priority: 2,
455
+ widthM: resolveNodeWidthMeters(node, isDouble ? 1.22 : 0.76),
456
+ ...(sku ? { sku } : {}),
457
+ label: rawName || 'Bathroom Vanity',
458
+ }
459
+ }
460
+ if (recipeId === 'fixture-kitchen-sink') {
461
+ return { role: 'fixture', fixtureKind: 'kitchen-sink', basins: 1, priority: 2, widthM: resolveNodeWidthMeters(node, 0.84), ...(sku ? { sku } : {}), label: rawName || 'Kitchen Sink' }
462
+ }
463
+ if (recipeId === 'cabinet-sink-base-farmhouse') {
464
+ return { role: 'fixture', fixtureKind: 'kitchen-sink', basins: 1, priority: 1, widthM: resolveNodeWidthMeters(node, 0.91), ...(sku ? { sku } : {}), label: rawName || 'Sink Base Cabinet' }
465
+ }
466
+ if (recipeId === 'fixture-alcove-bathtub') {
467
+ const kind: FixtureKind = /combo|shower/.test(hay) ? 'tub-shower-combo' : 'bathtub'
468
+ return { role: 'fixture', fixtureKind: kind, basins: 1, priority: 2, widthM: resolveNodeWidthMeters(node, 1.52), ...(sku ? { sku } : {}), label: rawName || 'Alcove Bathtub' }
469
+ }
470
+ if (recipeId === 'fixture-walkin-shower') {
471
+ return { role: 'fixture', fixtureKind: 'shower', basins: 1, priority: 2, widthM: resolveNodeWidthMeters(node, 1.22), ...(sku ? { sku } : {}), label: rawName || 'Walk-In Shower' }
472
+ }
473
+ if (recipeId === 'appliance-washer-dryer') {
474
+ return { role: 'fixture', fixtureKind: 'clothes-washer', basins: 1, priority: 2, widthM: resolveNodeWidthMeters(node, 0.69), ...(sku ? { sku } : {}), label: rawName || 'Front-Load Washer' }
475
+ }
476
+
477
+ // 7. Generic keyword fallback (native Pascal items/cabinets + custom SKUs)
478
+ let kind: FixtureKind | null = null
479
+ if (/toilet|water.?closet|\bwc\b/.test(hay)) kind = 'water-closet'
480
+ else if (/urinal/.test(hay)) kind = 'urinal'
481
+ else if (/bidet/.test(hay)) kind = 'bidet'
482
+ else if (/tub.*shower|shower.*tub|(?:bath|tub|shower).{0,16}combo|combo.{0,16}(?:bath|tub|shower)/.test(hay)) {
483
+ kind = 'tub-shower-combo'
484
+ } else if (/bathtub|soaking.?tub|\btub\b/.test(hay)) kind = 'bathtub'
485
+ else if (/shower/.test(hay)) kind = 'shower'
486
+ else if (/kitchen.?sink|sink.?base/.test(hay)) kind = 'kitchen-sink'
487
+ else if (/laundry.?sink|utility.?sink|mop.?sink/.test(hay)) kind = /mop/.test(hay) ? 'mop-sink' : 'laundry-sink'
488
+ else if (/bar.?sink/.test(hay)) kind = 'bar-sink'
489
+ else if (/vanity|lavatory|basin|bathroom.?sink|\bsink\b/.test(hay)) kind = 'lavatory'
490
+ else if (/dishwasher/.test(hay)) kind = 'dishwasher'
491
+ else if (!/\b(?:pressure|bottle|glass)\s*washer\b/.test(hay) && /washing.?machine|clothes.?washer|\bwasher\b/.test(hay)) {
492
+ kind = 'clothes-washer'
493
+ }
494
+ else if (/disposal|disposer/.test(hay)) kind = 'garbage-disposal'
495
+ else if (/floor.?drain/.test(hay)) kind = 'floor-drain'
496
+ else if (/grease.?(?:trap|interceptor)/.test(hay)) kind = 'grease-interceptor'
497
+ else if (/hose.?bib|spigot|sillcock/.test(hay)) kind = 'hose-bibb'
498
+
499
+ if (!kind) return null
500
+ const isDoubleLav = kind === 'lavatory' && /double.?basin|double.?sink|dual.?basin|dual.?vanity/.test(hay)
501
+ return {
502
+ role: 'fixture',
503
+ fixtureKind: kind,
504
+ basins: isDoubleLav ? 2 : 1,
505
+ priority: /sink.?base/.test(hay) ? 1 : 2,
506
+ widthM: resolveNodeWidthMeters(node, FIXTURE_SPECS[kind].dimensionsM[0]),
507
+ ...(sku ? { sku } : {}),
508
+ label: rawName || FIXTURE_SPECS[kind].label,
509
+ }
510
+ }
511
+
512
+ /**
513
+ * Count real-world catalog/furnishing plumbing fixtures & appliances on a level and how many
514
+ * are still waiting to be connected to the plumbing network.
515
+ */
516
+ export function countDetectedFurnishingFixtures(
517
+ nodes: Readonly<Record<string, SceneNodeLike>>,
518
+ levelId: string | null = null,
519
+ ): { total: number; unlinked: number } {
520
+ const linkedSourceIds = new Set<string>()
521
+ const existingFixtures: Array<{ kind: FixtureKind; x: number; z: number }> = []
522
+ for (const n of Object.values(nodes)) {
523
+ if (!belongsToLevel(nodes, n, levelId)) continue
524
+ if (typeof n.furnishingSourceId === 'string' && n.furnishingSourceId) {
525
+ linkedSourceIds.add(n.furnishingSourceId)
526
+ }
527
+ if (n.type === 'plumbing:pipe-run' && typeof n.targetNodeId === 'string' && n.targetNodeId) {
528
+ linkedSourceIds.add(n.targetNodeId)
529
+ }
530
+ if (n.type === 'plumbing:pipe-run' && typeof n.sourceNodeId === 'string' && n.sourceNodeId) {
531
+ linkedSourceIds.add(n.sourceNodeId)
532
+ }
533
+ if (
534
+ n.type === 'plumbing:fixture' &&
535
+ typeof n.fixtureKind === 'string' &&
536
+ Array.isArray(n.position) &&
537
+ n.position.length >= 3
538
+ ) {
539
+ existingFixtures.push({
540
+ kind: n.fixtureKind as FixtureKind,
541
+ x: Number(n.position[0]),
542
+ z: Number(n.position[2]),
543
+ })
544
+ }
545
+ }
546
+ let total = 0
547
+ let unlinked = 0
548
+ for (const n of Object.values(nodes)) {
549
+ if (!belongsToLevel(nodes, n, levelId)) continue
550
+ const role = inferCatalogOrFurnishingPlumbingRole(n)
551
+ if (!role) continue
552
+ total += 1
553
+ if (linkedSourceIds.has(n.id)) continue
554
+ // Co-located same-kind fixture (e.g. sink-base cabinet directly under an apron kitchen sink) is already covered
555
+ if (
556
+ role.role === 'fixture' &&
557
+ Array.isArray(n.position) &&
558
+ n.position.length >= 3 &&
559
+ existingFixtures.some(
560
+ (ef) =>
561
+ ef.kind === role.fixtureKind &&
562
+ Math.hypot(ef.x - Number(n.position![0]), ef.z - Number(n.position![2])) < 0.65,
563
+ )
564
+ ) {
565
+ continue
566
+ }
567
+ unlinked += 1
568
+ }
569
+ return { total, unlinked }
570
+ }
571
+
572
+ function defaultFixturesForRoom(room: RoomPolygon2D): FixtureKind[] {
573
+ switch (room.category) {
574
+ case 'master-bath':
575
+ return ['water-closet', 'lavatory', 'lavatory', 'shower', 'bathtub']
576
+ case 'bathroom':
577
+ return ['water-closet', 'lavatory', 'tub-shower-combo']
578
+ case 'half-bath':
579
+ return ['water-closet', 'lavatory']
580
+ case 'commercial-restroom':
581
+ return ['water-closet', 'water-closet', 'urinal', 'lavatory', 'lavatory', 'floor-drain']
582
+ case 'kitchen':
583
+ return ['kitchen-sink', 'dishwasher', 'garbage-disposal']
584
+ case 'commercial-kitchen':
585
+ return ['kitchen-sink', 'dishwasher', 'mop-sink', 'grease-interceptor', 'floor-drain']
586
+ case 'laundry':
587
+ return ['clothes-washer', 'laundry-sink']
588
+ case 'utility':
589
+ return ['floor-drain']
590
+ default:
591
+ return []
592
+ }
593
+ }
594
+
595
+ function yawFacingRoom(wall: WallSegment2D, roomCentroid: readonly [number, number]): number {
596
+ const mx = (wall.start[0] + wall.end[0]) / 2
597
+ const mz = (wall.start[1] + wall.end[1]) / 2
598
+ const toCx = roomCentroid[0] - mx
599
+ const toCz = roomCentroid[1] - mz
600
+ const dot = toCx * wall.nx + toCz * wall.nz
601
+ const nx = dot >= 0 ? wall.nx : -wall.nx
602
+ const nz = dot >= 0 ? wall.nz : -wall.nz
603
+ return round2(Math.atan2(nx, nz))
604
+ }
605
+
606
+ function sceneBounds(walls: ReadonlyArray<WallSegment2D>, rooms: ReadonlyArray<RoomPolygon2D>): {
607
+ minX: number
608
+ maxX: number
609
+ minZ: number
610
+ maxZ: number
611
+ cx: number
612
+ cz: number
613
+ } {
614
+ let minX = Infinity
615
+ let maxX = -Infinity
616
+ let minZ = Infinity
617
+ let maxZ = -Infinity
618
+ // Always derive building envelope from actual walled footprint when walls exist,
619
+ // so outer yard / terrace / pool / balcony / spawn zones never inflate indoor bounds.
620
+ if (walls.length > 0) {
621
+ for (const w of walls) {
622
+ minX = Math.min(minX, w.start[0], w.end[0])
623
+ maxX = Math.max(maxX, w.start[0], w.end[0])
624
+ minZ = Math.min(minZ, w.start[1], w.end[1])
625
+ maxZ = Math.max(maxZ, w.start[1], w.end[1])
626
+ }
627
+ } else {
628
+ const nonExterior = rooms.filter((r) => r.category !== 'exterior')
629
+ const roomPool = nonExterior.length > 0 ? nonExterior : rooms
630
+ for (const r of roomPool) {
631
+ for (const [x, z] of r.polygon) {
632
+ minX = Math.min(minX, x)
633
+ maxX = Math.max(maxX, x)
634
+ minZ = Math.min(minZ, z)
635
+ maxZ = Math.max(maxZ, z)
636
+ }
637
+ }
638
+ }
639
+ if (!Number.isFinite(minX)) {
640
+ return { minX: -4, maxX: 4, minZ: -3, maxZ: 3, cx: 0, cz: 0 }
641
+ }
642
+ return {
643
+ minX,
644
+ maxX,
645
+ minZ,
646
+ maxZ,
647
+ cx: (minX + maxX) / 2,
648
+ cz: (minZ + maxZ) / 2,
649
+ }
650
+ }
651
+
652
+ function isFiniteVec3(pos: unknown): pos is Vec3 {
653
+ return (
654
+ Array.isArray(pos) &&
655
+ pos.length >= 3 &&
656
+ Number.isFinite(Number(pos[0])) &&
657
+ Number.isFinite(Number(pos[1])) &&
658
+ Number.isFinite(Number(pos[2]))
659
+ )
660
+ }
661
+
662
+ function distancePointToPolygon2D(px: number, pz: number, poly: ReadonlyArray<readonly [number, number]>): number {
663
+ if (poly.length < 3) return Infinity
664
+ if (pointInPolygon2D(px, pz, poly)) return 0
665
+ let best = Infinity
666
+ for (let i = 0; i < poly.length; i++) {
667
+ const a = poly[i]!
668
+ const b = poly[(i + 1) % poly.length]!
669
+ const dx = b[0] - a[0]
670
+ const dz = b[1] - a[1]
671
+ const lenSq = dx * dx + dz * dz
672
+ const t = lenSq > 1e-8 ? Math.max(0, Math.min(1, ((px - a[0]) * dx + (pz - a[1]) * dz) / lenSq)) : 0
673
+ const cx = a[0] + dx * t
674
+ const cz = a[1] + dz * t
675
+ const d = Math.hypot(px - cx, pz - cz)
676
+ if (d < best) best = d
677
+ }
678
+ return best
679
+ }
680
+
681
+ function resolveIndoorRoomForPoint(
682
+ px: number,
683
+ pz: number,
684
+ indoorRooms: ReadonlyArray<RoomPolygon2D>,
685
+ nearWall: { wall: WallSegment2D } | null | undefined,
686
+ ): RoomPolygon2D | undefined {
687
+ const direct = indoorRooms.find((r) => pointInPolygon2D(px, pz, r.polygon))
688
+ if (direct) return direct
689
+ // Wall-hosted or wall-flush furnishings can land right on a zone boundary; probe ±0.25 m along wall normal.
690
+ if (nearWall) {
691
+ const { nx, nz } = nearWall.wall
692
+ for (const sign of [1, -1] as const) {
693
+ const probeX = px + nx * sign * 0.25
694
+ const probeZ = pz + nz * sign * 0.25
695
+ const hit = indoorRooms.find((r) => pointInPolygon2D(probeX, probeZ, r.polygon))
696
+ if (hit) return hit
697
+ }
698
+ }
699
+ let bestRoom: RoomPolygon2D | undefined
700
+ let bestDist = 0.30
701
+ for (const r of indoorRooms) {
702
+ const d = distancePointToPolygon2D(px, pz, r.polygon)
703
+ if (d <= bestDist) {
704
+ bestDist = d
705
+ bestRoom = r
706
+ }
707
+ }
708
+ return bestRoom
709
+ }
710
+
711
+ function resolveVentOriginForFixture(
712
+ pos: Vec3,
713
+ wallId: string | undefined,
714
+ wallById: ReadonlyMap<string, WallSegment2D>,
715
+ walls: ReadonlyArray<WallSegment2D>,
716
+ hitsOpening?: (x: number, z: number) => boolean,
717
+ ): Vec3 {
718
+ const hostWall = wallId ? wallById.get(wallId) : undefined
719
+ if (hostWall) {
720
+ const hostSnap = nearestWallToPoint(pos[0], pos[2], [hostWall])
721
+ if (
722
+ hostSnap &&
723
+ hostSnap.distanceM > 0.03 &&
724
+ hostSnap.distanceM <= 1.05 &&
725
+ (!hitsOpening || !hitsOpening(hostSnap.point[0], hostSnap.point[1]))
726
+ ) {
727
+ return [round2(hostSnap.point[0]), pos[1], round2(hostSnap.point[1])]
728
+ }
729
+ }
730
+ const ventWallSnap = nearestWallToPoint(pos[0], pos[2], walls)
731
+ if (
732
+ ventWallSnap &&
733
+ ventWallSnap.distanceM > 0.03 &&
734
+ ventWallSnap.distanceM <= 1.05 &&
735
+ (!hitsOpening || !hitsOpening(ventWallSnap.point[0], ventWallSnap.point[1]))
736
+ ) {
737
+ return [round2(ventWallSnap.point[0]), pos[1], round2(ventWallSnap.point[1])]
738
+ }
739
+ return pos
740
+ }
741
+
742
+ function inferFoundationFromSupplyPipes(levelPipes: ReadonlyArray<SceneNodeLike>): FoundationType {
743
+ let sawSubFloorHoriz = false
744
+ for (const p of levelPipes) {
745
+ if (p.system !== 'cold-water' && p.system !== 'hot-water') continue
746
+ if (!Array.isArray(p.path) || p.path.length < 2) continue
747
+ const pts = p.path as ReadonlyArray<Vec3>
748
+ for (let i = 1; i < pts.length; i++) {
749
+ const a = pts[i - 1]!
750
+ const b = pts[i]!
751
+ if (!isFiniteVec3(a) || !isFiniteVec3(b)) continue
752
+ const horiz = Math.hypot(Number(b[0]) - Number(a[0]), Number(b[2]) - Number(a[2]))
753
+ const dy = Math.abs(Number(b[1]) - Number(a[1]))
754
+ if (horiz > 0.25 && dy < 0.05) {
755
+ const y = (Number(a[1]) + Number(b[1])) / 2
756
+ if (y > 1.2) return 'slab'
757
+ if (y < 0.0) sawSubFloorHoriz = true
758
+ }
759
+ }
760
+ }
761
+ if (sawSubFloorHoriz) return 'crawlspace'
762
+ const sampleSupply = levelPipes.find((p) => p.system === 'cold-water' || p.system === 'hot-water')
763
+ const sampleSupplyY =
764
+ Array.isArray(sampleSupply?.path) && sampleSupply.path.length >= 2
765
+ ? Number((sampleSupply.path[Math.floor(sampleSupply.path.length / 2)] as Vec3 | undefined)?.[1] ?? -0.16)
766
+ : null
767
+ return sampleSupplyY !== null && sampleSupplyY > 1.2 ? 'slab' : 'crawlspace'
768
+ }
769
+
770
+ /**
771
+ * Plan a complete IPC/UPC/IFGC plumbing layout for a Pascal level.
772
+ */
773
+ export function planPlumbingAutoPopulate(
774
+ nodes: Readonly<Record<string, SceneNodeLike>>,
775
+ options: PlumbingAutoPopulateOptions = {},
776
+ ): PlumbingAutoPopulatePlan {
777
+ const {
778
+ levelId = null,
779
+ occupancy = 'residential',
780
+ codeEdition = 'IPC-2021',
781
+ supplyTopology = 'manifold',
782
+ supplyMaterial = 'pex-a',
783
+ dwvMaterial = 'pvc-dwv',
784
+ foundationType = 'crawlspace',
785
+ waterHeaterKind = 'water-heater-tank-electric',
786
+ includeDryerVent = true,
787
+ includeHotRecirc = false,
788
+ bonesMode = 'auto',
789
+ } = options
790
+
791
+ const sceneGasAppliances: Array<{ id: string; name: string; pos: Vec3; btuh: number }> = []
792
+ const sceneGasIds = new Set<string>()
793
+ const pushGasAppliance = (entry: { id: string; name: string; pos: Vec3; btuh: number }) => {
794
+ if (sceneGasIds.has(entry.id)) return
795
+ sceneGasIds.add(entry.id)
796
+ sceneGasAppliances.push(entry)
797
+ }
798
+ for (const n of Object.values(nodes)) {
799
+ if (!belongsToLevel(nodes, n, levelId)) continue
800
+ if (
801
+ (n.type === 'hvac:equipment' || (n.type === 'plumbing:equipment' && n.equipmentKind !== 'gas-meter')) &&
802
+ typeof n.gasBtuh === 'number' &&
803
+ n.gasBtuh > 0 &&
804
+ isFiniteVec3(n.position)
805
+ ) {
806
+ pushGasAppliance({
807
+ id: n.id,
808
+ name: typeof n.name === 'string' && n.name ? n.name : n.id,
809
+ pos: [Number(n.position[0]), Math.max(0.45, Number(n.position[1]) + 0.45), Number(n.position[2])],
810
+ btuh: n.gasBtuh,
811
+ })
812
+ }
813
+ }
814
+
815
+ const walls = extractWallSegments(nodes, levelId)
816
+ const wallById = new Map<string, WallSegment2D>(walls.map((w) => [w.id, w]))
817
+ const rooms = extractRoomPolygons(nodes, levelId, occupancy)
818
+ const levelH = resolveLevelHeightM(nodes, levelId)
819
+ const wetWallFitRule = getIpcRuleById('irc-r602-6-wet-wall-fit')
820
+ const dryerVentRule = getIpcRuleById('irc-m1502-4-dryer-vent')
821
+ const dryerVentMaterialRule = getIpcRuleById('irc-m1502-4-1-dryer-vent-material')
822
+
823
+ // Layer 2 — Shared WeakMap-cached BuildingAnatomy, LegalCavityGraph & TradeOccupancyGrid
824
+ const anatomy = compileBuildingAnatomy(nodes)
825
+ const subFloorElevationM = foundationType === 'slab' ? -0.35 : -0.24
826
+ const legalCavityGraph: LegalCavityGraph | undefined =
827
+ walls.length > 0
828
+ ? compileLegalCavityGraph(anatomy, levelId, {
829
+ roofClearanceM: 0.1,
830
+ subFloorElevationM,
831
+ })
832
+ : undefined
833
+ const occupancyGrid = anatomy.createOccupancyGrid(levelId, { forTrade: 'plumbing' })
834
+ const obstacles = mapOccupancyObstaclesToPlumbing(occupancyGrid.obstacles)
835
+ const cavityContext: PlumbingCavityContext = {
836
+ nodes,
837
+ levelId,
838
+ anatomy,
839
+ ...(legalCavityGraph ? { graph: legalCavityGraph } : {}),
840
+ occupancy: occupancyGrid,
841
+ }
842
+ const wallOpenings = mapCanonicalWallsToOpenings(anatomy.getWalls(levelId))
843
+ const openingsByWall = new Map<string, WallOpeningSpan[]>()
844
+ for (const op of wallOpenings) {
845
+ let list = openingsByWall.get(op.wallId)
846
+ if (!list) {
847
+ list = []
848
+ openingsByWall.set(op.wallId, list)
849
+ }
850
+ list.push(op)
851
+ }
852
+ const bones =
853
+ bonesMode === 'ignore'
854
+ ? null
855
+ : extractBonesPlumbingContext(nodes, levelId)
856
+ const bounds = sceneBounds(walls, rooms)
857
+ const lowerWalledLevelIds = getLowerWalledLevelIds(nodes, levelId)
858
+ const isGroundStory = isGroundOrLowestWalledLevel(nodes, levelId)
859
+ const lowerWaterHeater = !isGroundStory
860
+ ? (Object.values(nodes).find(
861
+ (n) =>
862
+ n.type === 'plumbing:equipment' &&
863
+ typeof n.equipmentKind === 'string' &&
864
+ n.equipmentKind.startsWith('water-heater-') &&
865
+ lowerWalledLevelIds.some((lid) => belongsToLevel(nodes, n, lid)),
866
+ ) ?? null)
867
+ : null
868
+ const emitMainShutoff = isGroundStory
869
+ const emitWaterHeater = isGroundStory || !lowerWaterHeater
870
+ const clampToBoundsXZ = (x: number, z: number, margin = 0.15): readonly [number, number] => {
871
+ const minX = bounds.minX + margin
872
+ const maxX = bounds.maxX - margin
873
+ const minZ = bounds.minZ + margin
874
+ const maxZ = bounds.maxZ - margin
875
+ return [
876
+ round2(minX <= maxX ? Math.max(minX, Math.min(maxX, x)) : bounds.cx),
877
+ round2(minZ <= maxZ ? Math.max(minZ, Math.min(maxZ, z)) : bounds.cz),
878
+ ]
879
+ }
880
+
881
+ // Filter out exterior zones (pools, patios, terraces, balconies, yards, outdoor spawns) and
882
+ // any zone whose centroid sits outside the walled building envelope.
883
+ const indoorRooms = rooms.filter((r) => {
884
+ if (r.category === 'exterior') return false
885
+ if (walls.length > 0) {
886
+ const [cx, cz] = r.centroid
887
+ if (
888
+ cx < bounds.minX - 0.15 ||
889
+ cx > bounds.maxX + 0.15 ||
890
+ cz < bounds.minZ - 0.15 ||
891
+ cz > bounds.maxZ + 0.15
892
+ ) {
893
+ return false
894
+ }
895
+ }
896
+ return true
897
+ })
898
+
899
+ // Determine roof clearance envelope (explicit roof-segment + pitched/flat fallback) for the active level
900
+ // so indoor supply & re-vent pipes stay strictly below the roof plane (only Main DWV Stack penetrates).
901
+ const levelAssembly = Object.values(nodes).find(
902
+ (n) => n.type === 'structural:assembly' && belongsToLevel(nodes, n, levelId),
903
+ )
904
+ const roofPitchRise =
905
+ typeof levelAssembly?.roofPitchRise === 'number' &&
906
+ Number.isFinite(levelAssembly.roofPitchRise) &&
907
+ levelAssembly.roofPitchRise >= 0
908
+ ? levelAssembly.roofPitchRise
909
+ : 6
910
+ const maxRoofYAt = anatomy.getRoofShell(levelId, {
911
+ wallBounds: bounds,
912
+ fallbackPitchRiseOver12: roofPitchRise,
913
+ clampOverhangToEave: true,
914
+ }).roofEnvelopeY
915
+
916
+ // Spatial clearance predicates covering ALL structural obstacles (floor girders, door/window headers,
917
+ // ceiling/ridge beams, structural columns) + NEC 110.26(E) dedicated electrical spaces + Pascal wall openings.
918
+ const floorBeamsForNudge = obstacles.filter((o) => o.category === 'structural' && o.box.minY < 0.15)
919
+ const hitsFloorBeamXZ = (cx: number, cz: number, pad = 0.28): boolean =>
920
+ floorBeamsForNudge.some(
921
+ (b) =>
922
+ cx >= b.box.minX - pad &&
923
+ cx <= b.box.maxX + pad &&
924
+ cz >= b.box.minZ - pad &&
925
+ cz <= b.box.maxZ + pad,
926
+ )
927
+ const hitsAnyObstacleXZ = (cx: number, cz: number, pad = 0.28): boolean =>
928
+ obstacles.some(
929
+ (o) =>
930
+ cx >= o.box.minX - pad &&
931
+ cx <= o.box.maxX + pad &&
932
+ cz >= o.box.minZ - pad &&
933
+ cz <= o.box.maxZ + pad,
934
+ )
935
+ const hitsWallOpening = (
936
+ wallId: string,
937
+ alongM: number,
938
+ pad = 0.28,
939
+ allowWindows = false,
940
+ ): boolean => {
941
+ const ops = openingsByWall.get(wallId)
942
+ if (!ops || ops.length === 0) return false
943
+ return ops.some((op) => {
944
+ if (allowWindows && op.kind === 'window') return false
945
+ return alongM >= op.startU - pad && alongM <= op.endU + pad
946
+ })
947
+ }
948
+ const hitsAnyWallOpeningXZ = (
949
+ cx: number,
950
+ cz: number,
951
+ pad = 0.28,
952
+ allowWindows = false,
953
+ ): boolean => {
954
+ for (const w of walls) {
955
+ const ops = openingsByWall.get(w.id)
956
+ if (!ops || ops.length === 0) continue
957
+ const dx = cx - w.start[0]
958
+ const dz = cz - w.start[1]
959
+ const along = dx * w.ux + dz * w.uz
960
+ const perp = Math.abs(dx * w.nx + dz * w.nz)
961
+ if (perp > w.thicknessM / 2 + pad) continue
962
+ if (
963
+ ops.some(
964
+ (op) =>
965
+ !(allowWindows && op.kind === 'window') &&
966
+ along >= op.startU - pad &&
967
+ along <= op.endU + pad,
968
+ )
969
+ ) {
970
+ return true
971
+ }
972
+ }
973
+ return false
974
+ }
975
+ const nudgeOffFloorGirder = (
976
+ x: number,
977
+ z: number,
978
+ pad = 0.16,
979
+ maxShifts: ReadonlyArray<number> = [0.22, -0.22, 0.36, -0.36, 0.52, -0.52],
980
+ roomPoly?: ReadonlyArray<readonly [number, number]>,
981
+ ): readonly [number, number] => {
982
+ if (floorBeamsForNudge.length === 0 || !hitsFloorBeamXZ(x, z, pad)) return [round2(x), round2(z)]
983
+ const isValidNudge = (nx: number, nz: number): boolean => {
984
+ if (
985
+ nx < bounds.minX + 0.12 ||
986
+ nx > bounds.maxX - 0.12 ||
987
+ nz < bounds.minZ + 0.12 ||
988
+ nz > bounds.maxZ - 0.12
989
+ ) {
990
+ return false
991
+ }
992
+ if (roomPoly && roomPoly.length >= 3 && !pointInPolygon2D(nx, nz, roomPoly)) {
993
+ return false
994
+ }
995
+ return true
996
+ }
997
+ for (const d of maxShifts) {
998
+ if (isValidNudge(x + d, z) && !hitsFloorBeamXZ(x + d, z, pad)) return [round2(x + d), round2(z)]
999
+ if (isValidNudge(x, z + d) && !hitsFloorBeamXZ(x, z + d, pad)) return [round2(x), round2(z + d)]
1000
+ }
1001
+ for (const d of maxShifts) {
1002
+ if (isValidNudge(x + d, z + d) && !hitsFloorBeamXZ(x + d, z + d, pad)) return [round2(x + d), round2(z + d)]
1003
+ if (isValidNudge(x + d, z - d) && !hitsFloorBeamXZ(x + d, z - d, pad)) return [round2(x + d), round2(z - d)]
1004
+ }
1005
+ return [round2(x), round2(z)]
1006
+ }
1007
+
1008
+ const equipment: PlannedEquipmentSpec[] = []
1009
+ const manifolds: PlannedManifoldSpec[] = []
1010
+ const fixtures: PlannedFixtureSpec[] = []
1011
+ const pipeRuns: PlannedPipeRunSpec[] = []
1012
+ const bonesAnchorsUsed: string[] = []
1013
+
1014
+ const seq = { eq: 1, man: 1, fix: 1, pipe: 1 }
1015
+ const allocId = (prefix: string, key: keyof typeof seq) => {
1016
+ while (nodes[`${prefix}_${seq[key]}`]) seq[key] += 1
1017
+ return `${prefix}_${seq[key]++}`
1018
+ }
1019
+ const nextEqId = () => allocId('plumbeq_auto', 'eq')
1020
+ const nextManId = () => allocId('plumbman_auto', 'man')
1021
+ const nextFixId = () => allocId('plumbfix_auto', 'fix')
1022
+ const nextPipeId = () => allocId('plumbpipe_auto', 'pipe')
1023
+
1024
+ // 1. Discover placed real-world catalog SKUs (`catalog:sku-item`), furnishings (`furnishings:*`),
1025
+ // and native Pascal `item` / `cabinet` / `procedural-item` fixtures, appliances & mechanical units first.
1026
+ type PlacedFixtureCandidate = {
1027
+ kind: FixtureKind
1028
+ pos: Vec3
1029
+ roomName: string
1030
+ roomId?: string
1031
+ rot: number
1032
+ wallId?: string
1033
+ priority: 1 | 2
1034
+ furnishingSourceId: string
1035
+ catalogSku?: string
1036
+ labelSuffix?: string
1037
+ }
1038
+ const rawPlacedFixtures: PlacedFixtureCandidate[] = []
1039
+ let placedWaterHeaterSku: {
1040
+ sourceId: string
1041
+ equipmentKind:
1042
+ | 'water-heater-tank-electric'
1043
+ | 'water-heater-tank-gas'
1044
+ | 'water-heater-tankless-gas'
1045
+ | 'water-heater-hpwh'
1046
+ capacityGal: number
1047
+ pos: Vec3
1048
+ rot: number
1049
+ roomName: string
1050
+ sku?: string
1051
+ label: string
1052
+ } | null = null
1053
+ let placedManifoldSku: {
1054
+ sourceId: string
1055
+ portCount: number
1056
+ pos: Vec3
1057
+ rot: number
1058
+ roomPolygon?: ReadonlyArray<readonly [number, number]>
1059
+ sku?: string
1060
+ label: string
1061
+ } | null = null
1062
+ const discoveredIceMakers: Array<{
1063
+ sourceId: string
1064
+ name: string
1065
+ pos: Vec3
1066
+ rot: number
1067
+ wsfuCold: number
1068
+ roomName: string
1069
+ sku?: string
1070
+ }> = []
1071
+ const discoveredDryers: Array<{
1072
+ sourceId: string
1073
+ name: string
1074
+ pos: Vec3
1075
+ rot: number
1076
+ isGas: boolean
1077
+ roomName: string
1078
+ sku?: string
1079
+ }> = []
1080
+
1081
+ for (const n of Object.values(nodes)) {
1082
+ if (!belongsToLevel(nodes, n, levelId)) continue
1083
+ const role = inferCatalogOrFurnishingPlumbingRole(n)
1084
+ if (!role) continue
1085
+ if (!isFiniteVec3(n.position)) continue
1086
+ let rawPx = Number(n.position[0])
1087
+ let rawPz = Number(n.position[2])
1088
+ const hostWall = typeof n.parentId === 'string' ? wallById.get(n.parentId) : undefined
1089
+ if (hostWall) {
1090
+ // Wall-parented Pascal items (e.g. wall-mounted showerheads / sinks) store wall-local [u, y, localZ].
1091
+ const uClamped = Math.max(0.05, Math.min(hostWall.lengthM - 0.05, rawPx))
1092
+ const localZ = Math.max(-0.5, Math.min(0.5, rawPz))
1093
+ rawPx = hostWall.start[0] + hostWall.ux * uClamped + hostWall.nx * localZ
1094
+ rawPz = hostWall.start[1] + hostWall.uz * uClamped + hostWall.nz * localZ
1095
+ if (walls.length > 0) {
1096
+ const [clampedX, clampedZ] = clampToBoundsXZ(rawPx, rawPz, 0.15)
1097
+ rawPx = clampedX
1098
+ rawPz = clampedZ
1099
+ }
1100
+ } else if (
1101
+ walls.length > 0 &&
1102
+ (rawPx < bounds.minX - 0.15 ||
1103
+ rawPx > bounds.maxX + 0.15 ||
1104
+ rawPz < bounds.minZ - 0.15 ||
1105
+ rawPz > bounds.maxZ + 0.15)
1106
+ ) {
1107
+ // Skip outdoor items located outside the walled building envelope
1108
+ continue
1109
+ }
1110
+ const nearWall = hostWall
1111
+ ? { wall: hostWall, t: 0.5, point: [rawPx, rawPz] as const, distanceM: 0 }
1112
+ : nearestWallToPoint(rawPx, rawPz, walls)
1113
+ const room = resolveIndoorRoomForPoint(rawPx, rawPz, indoorRooms, nearWall)
1114
+ const rot =
1115
+ typeof n.rotation === 'number' && Number.isFinite(n.rotation)
1116
+ ? n.rotation
1117
+ : Array.isArray(n.rotation) && n.rotation.length >= 2 && Number.isFinite(Number(n.rotation[1]))
1118
+ ? Number(n.rotation[1])
1119
+ : nearWall && room
1120
+ ? yawFacingRoom(nearWall.wall, room.centroid)
1121
+ : 0
1122
+ const roomLabel = room?.name ?? (typeof n.roomName === 'string' && n.roomName.trim() ? n.roomName.trim() : 'Main')
1123
+
1124
+ if (role.role === 'water-heater') {
1125
+ if (!placedWaterHeaterSku) {
1126
+ const [whX, whZ] = nudgeOffFloorGirder(rawPx, rawPz, 0.25, undefined, room?.polygon)
1127
+ placedWaterHeaterSku = {
1128
+ sourceId: n.id,
1129
+ equipmentKind: role.equipmentKind,
1130
+ capacityGal: role.capacityGal,
1131
+ pos: [round2(whX), 0, round2(whZ)],
1132
+ rot,
1133
+ roomName: roomLabel,
1134
+ ...(role.sku ? { sku: role.sku } : {}),
1135
+ label: role.label,
1136
+ }
1137
+ }
1138
+ continue
1139
+ }
1140
+
1141
+ if (role.role === 'manifold') {
1142
+ if (!placedManifoldSku) {
1143
+ placedManifoldSku = {
1144
+ sourceId: n.id,
1145
+ portCount: role.portCount,
1146
+ pos: [round2(rawPx), 1.35, round2(rawPz)],
1147
+ rot,
1148
+ ...(room?.polygon ? { roomPolygon: room.polygon } : {}),
1149
+ ...(role.sku ? { sku: role.sku } : {}),
1150
+ label: role.label,
1151
+ }
1152
+ }
1153
+ continue
1154
+ }
1155
+
1156
+ if (role.role === 'gas-appliance') {
1157
+ const [gx, gz] = rotateLocal2D(rawPx, rawPz, 0, -0.22, rot)
1158
+ const [cx, cz] = walls.length > 0 ? clampToBoundsXZ(gx, gz, 0.12) : [gx, gz]
1159
+ pushGasAppliance({
1160
+ id: n.id,
1161
+ name: role.sku ? `${roomLabel} ${role.label} [${role.sku}]` : `${roomLabel} ${role.label}`,
1162
+ pos: [cx, 0.45, cz],
1163
+ btuh: role.btuh,
1164
+ })
1165
+ continue
1166
+ }
1167
+
1168
+ if (role.role === 'ice-maker') {
1169
+ const [ix, iz] = rotateLocal2D(rawPx, rawPz, 0, -0.24, rot)
1170
+ const [cx, cz] = walls.length > 0 ? clampToBoundsXZ(ix, iz, 0.12) : [ix, iz]
1171
+ discoveredIceMakers.push({
1172
+ sourceId: n.id,
1173
+ name: role.sku ? `${roomLabel} Refrigerator Ice Maker [${role.sku}]` : `${roomLabel} Refrigerator Ice Maker`,
1174
+ pos: [cx, 0.45, cz],
1175
+ rot,
1176
+ wsfuCold: role.wsfuCold,
1177
+ roomName: roomLabel,
1178
+ ...(role.sku ? { sku: role.sku } : {}),
1179
+ })
1180
+ continue
1181
+ }
1182
+
1183
+ if (role.role === 'dryer') {
1184
+ discoveredDryers.push({
1185
+ sourceId: n.id,
1186
+ name: role.label,
1187
+ pos: [round2(rawPx), 0.35, round2(rawPz)],
1188
+ rot,
1189
+ isGas: role.isGas,
1190
+ roomName: roomLabel,
1191
+ ...(role.sku ? { sku: role.sku } : {}),
1192
+ })
1193
+ if (role.isGas) {
1194
+ const [gx, gz] = rotateLocal2D(rawPx, rawPz, 0, -0.22, rot)
1195
+ const [cx, cz] = walls.length > 0 ? clampToBoundsXZ(gx, gz, 0.12) : [gx, gz]
1196
+ pushGasAppliance({
1197
+ id: n.id,
1198
+ name: role.sku ? `${roomLabel} Gas Dryer [${role.sku}]` : `${roomLabel} Gas Dryer`,
1199
+ pos: [cx, 0.45, cz],
1200
+ btuh: 22000,
1201
+ })
1202
+ }
1203
+ continue
1204
+ }
1205
+
1206
+ // Fixture role (single basin or double-basin vanity)
1207
+ const spec = FIXTURE_SPECS[role.fixtureKind]
1208
+ if (role.basins === 2) {
1209
+ const halfSpan = Math.min(0.42, Math.max(0.24, role.widthM * 0.25))
1210
+ // Nudge the vanity center once and apply the same delta to both basins so symmetric spacing is preserved.
1211
+ const [centerX, centerZ] = nudgeOffFloorGirder(rawPx, rawPz, 0.12, undefined, room?.polygon)
1212
+ const sides: ReadonlyArray<{ sign: -1 | 1; suffix: string }> = [
1213
+ { sign: -1, suffix: 'Left Basin' },
1214
+ { sign: 1, suffix: 'Right Basin' },
1215
+ ]
1216
+ for (const s of sides) {
1217
+ const [bx, bz] = rotateLocal2D(centerX, centerZ, s.sign * halfSpan, 0, rot)
1218
+ rawPlacedFixtures.push({
1219
+ kind: role.fixtureKind,
1220
+ pos: [round2(bx), spec.roughInHeightM, round2(bz)],
1221
+ roomName: roomLabel,
1222
+ roomId: room?.id,
1223
+ rot,
1224
+ wallId: nearWall?.wall.id,
1225
+ priority: role.priority,
1226
+ furnishingSourceId: n.id,
1227
+ ...(role.sku ? { catalogSku: role.sku } : {}),
1228
+ labelSuffix: s.suffix,
1229
+ })
1230
+ }
1231
+ } else {
1232
+ const [px, pz] = nudgeOffFloorGirder(rawPx, rawPz, 0.14, undefined, room?.polygon)
1233
+ rawPlacedFixtures.push({
1234
+ kind: role.fixtureKind,
1235
+ pos: [round2(px), spec.roughInHeightM, round2(pz)],
1236
+ roomName: roomLabel,
1237
+ roomId: room?.id,
1238
+ rot,
1239
+ wallId: nearWall?.wall.id,
1240
+ priority: role.priority,
1241
+ furnishingSourceId: n.id,
1242
+ ...(role.sku ? { catalogSku: role.sku } : {}),
1243
+ })
1244
+ }
1245
+ }
1246
+
1247
+ // De-duplicate co-located same-kind placed fixtures (e.g. apron `fixture-kitchen-sink` resting on
1248
+ // `cabinet-sink-base-farmhouse` within 0.65m -> keep higher-priority sink SKU, never double-plumb!).
1249
+ rawPlacedFixtures.sort((a, b) => b.priority - a.priority)
1250
+ const placedFixtures: PlacedFixtureCandidate[] = []
1251
+ for (const cand of rawPlacedFixtures) {
1252
+ const dup = placedFixtures.some(
1253
+ (existing) =>
1254
+ existing.kind === cand.kind &&
1255
+ existing.furnishingSourceId !== cand.furnishingSourceId &&
1256
+ Math.hypot(existing.pos[0] - cand.pos[0], existing.pos[2] - cand.pos[2]) < 0.65,
1257
+ )
1258
+ if (!dup) placedFixtures.push(cand)
1259
+ }
1260
+
1261
+ const resolvedWaterHeaterKind =
1262
+ options.waterHeaterKind ?? placedWaterHeaterSku?.equipmentKind ?? waterHeaterKind
1263
+ const hasGasWaterHeater =
1264
+ resolvedWaterHeaterKind === 'water-heater-tank-gas' || resolvedWaterHeaterKind === 'water-heater-tankless-gas'
1265
+ const includeFuelGas = options.includeFuelGas ?? (hasGasWaterHeater || sceneGasAppliances.length > 0)
1266
+
1267
+ // 2. Supplement wet rooms that lack placed Pascal items (or fallback residential core if empty scene)
1268
+ const existingKindsByRoomKey = new Map<string, FixtureKind[]>()
1269
+ for (const pf of placedFixtures) {
1270
+ const rk = pf.roomId ?? pf.roomName
1271
+ let list = existingKindsByRoomKey.get(rk)
1272
+ if (!list) {
1273
+ list = []
1274
+ existingKindsByRoomKey.set(rk, list)
1275
+ }
1276
+ list.push(pf.kind)
1277
+ }
1278
+ const wetRooms = indoorRooms.filter((r) => defaultFixturesForRoom(r).length > 0)
1279
+
1280
+ const targetWetRooms: RoomPolygon2D[] =
1281
+ wetRooms.length > 0
1282
+ ? wetRooms
1283
+ : placedFixtures.length === 0
1284
+ ? [
1285
+ {
1286
+ id: 'synth_bath',
1287
+ name: 'Bathroom',
1288
+ category: 'bathroom',
1289
+ polygon: [
1290
+ [bounds.minX + 0.5, bounds.minZ + 0.5],
1291
+ [bounds.cx, bounds.minZ + 0.5],
1292
+ [bounds.cx, bounds.cz],
1293
+ [bounds.minX + 0.5, bounds.cz],
1294
+ ],
1295
+ centroid: [(bounds.minX + bounds.cx) / 2, (bounds.minZ + bounds.cz) / 2],
1296
+ areaSqm: 5.5,
1297
+ areaSqft: 60,
1298
+ },
1299
+ {
1300
+ id: 'synth_kitchen',
1301
+ name: 'Kitchen',
1302
+ category: 'kitchen',
1303
+ polygon: [
1304
+ [bounds.cx, bounds.minZ + 0.5],
1305
+ [bounds.maxX - 0.5, bounds.minZ + 0.5],
1306
+ [bounds.maxX - 0.5, bounds.cz],
1307
+ [bounds.cx, bounds.cz],
1308
+ ],
1309
+ centroid: [(bounds.cx + bounds.maxX) / 2, (bounds.minZ + bounds.cz) / 2],
1310
+ areaSqm: 12,
1311
+ areaSqft: 130,
1312
+ },
1313
+ ]
1314
+ : []
1315
+
1316
+ const flushType: 'flush-tank' | 'flushometer' = occupancy === 'commercial' ? 'flushometer' : 'flush-tank'
1317
+
1318
+ const placedKitchenSinkByRoomId = new Map<string, PlannedFixtureSpec>()
1319
+ for (const pf of placedFixtures) {
1320
+ const spec = FIXTURE_SPECS[pf.kind]
1321
+ const wsfu = getFixtureWsfu(pf.kind, occupancy)
1322
+ const suffixPart = pf.labelSuffix ? ` (${pf.labelSuffix})` : ''
1323
+ const skuPart = pf.catalogSku ? ` [${pf.catalogSku}]` : ''
1324
+ const plannedFix: PlannedFixtureSpec = {
1325
+ id: nextFixId(),
1326
+ name: `${pf.roomName} ${spec.label}${suffixPart}${skuPart}`,
1327
+ fixtureKind: pf.kind,
1328
+ position: pf.pos,
1329
+ rotation: pf.rot,
1330
+ roomName: pf.roomName,
1331
+ wallId: pf.wallId,
1332
+ dfu: getFixtureDfu(pf.kind, codeEdition),
1333
+ wsfuCold: wsfu.cold,
1334
+ wsfuHot: wsfu.hot,
1335
+ wsfuTotal: wsfu.total,
1336
+ trapSize: spec.minTrapIn,
1337
+ drainSize: spec.minDrainIn,
1338
+ ventSize: spec.minVentIn,
1339
+ supplySize: spec.supplySizeIn,
1340
+ hasVacuumBreaker: pf.kind === 'hose-bibb',
1341
+ hasPTrap: spec.needsPTrap,
1342
+ electricalDemand: getFixtureElectricalDemand(pf.kind),
1343
+ furnishingSourceId: pf.furnishingSourceId,
1344
+ ...(pf.catalogSku ? { catalogSku: pf.catalogSku } : {}),
1345
+ roughInOnly: true,
1346
+ }
1347
+ fixtures.push(plannedFix)
1348
+ if (pf.kind === 'kitchen-sink' && pf.roomId && !placedKitchenSinkByRoomId.has(pf.roomId)) {
1349
+ placedKitchenSinkByRoomId.set(pf.roomId, plannedFix)
1350
+ }
1351
+ }
1352
+
1353
+ if (bonesMode !== 'import-only') {
1354
+ for (const room of targetWetRooms) {
1355
+ const existingInRoom = [
1356
+ ...(existingKindsByRoomKey.get(room.id) ?? existingKindsByRoomKey.get(room.name) ?? []),
1357
+ ]
1358
+ const defaults = defaultFixturesForRoom(room)
1359
+ const missing = defaults.filter((k) => {
1360
+ const idx = existingInRoom.indexOf(k)
1361
+ if (idx >= 0) {
1362
+ existingInRoom.splice(idx, 1)
1363
+ return false
1364
+ }
1365
+ // Smart bath dedup: a placed alcove bathtub or walk-in shower satisfies a generic tub-shower-combo default,
1366
+ // and a placed tub-shower-combo satisfies a standalone bathtub/shower default.
1367
+ if (k === 'tub-shower-combo') {
1368
+ const altIdx = existingInRoom.findIndex((e) => e === 'bathtub' || e === 'shower')
1369
+ if (altIdx >= 0) {
1370
+ existingInRoom.splice(altIdx, 1)
1371
+ return false
1372
+ }
1373
+ }
1374
+ if ((k === 'bathtub' || k === 'shower') && existingInRoom.includes('tub-shower-combo')) {
1375
+ return false
1376
+ }
1377
+ return true
1378
+ })
1379
+ if (missing.length === 0) continue
1380
+
1381
+ const nearWall = nearestWallToPoint(room.centroid[0], room.centroid[1], walls)
1382
+ const count = missing.length
1383
+ const placedKitchenSinkInRoom =
1384
+ placedKitchenSinkByRoomId.get(room.id) ??
1385
+ fixtures.find((f) => f.fixtureKind === 'kitchen-sink' && f.roomName === room.name && f.furnishingSourceId)
1386
+
1387
+ for (let i = 0; i < count; i++) {
1388
+ const kind = missing[i]!
1389
+ const spec = FIXTURE_SPECS[kind]
1390
+ const wsfu = getFixtureWsfu(kind, occupancy)
1391
+ const allowUnderWindow = kind === 'kitchen-sink'
1392
+ const minFixSepM = kind === 'garbage-disposal' ? 0.18 : 0.48
1393
+ let px = room.centroid[0]
1394
+ let pz = room.centroid[1]
1395
+ let chosenWall = nearWall?.wall
1396
+ let rot = chosenWall ? yawFacingRoom(chosenWall, room.centroid) : 0
1397
+
1398
+ // Tuck garbage disposal directly beneath a placed real-world kitchen sink and place dishwasher neatly beside it
1399
+ if (kind === 'garbage-disposal' && placedKitchenSinkInRoom) {
1400
+ fixtures.push({
1401
+ id: nextFixId(),
1402
+ name: `${room.name} ${spec.label}`,
1403
+ fixtureKind: kind,
1404
+ position: [placedKitchenSinkInRoom.position[0], spec.roughInHeightM, placedKitchenSinkInRoom.position[2]],
1405
+ rotation: placedKitchenSinkInRoom.rotation,
1406
+ roomName: room.name,
1407
+ wallId: placedKitchenSinkInRoom.wallId,
1408
+ dfu: getFixtureDfu(kind, codeEdition),
1409
+ wsfuCold: wsfu.cold,
1410
+ wsfuHot: wsfu.hot,
1411
+ wsfuTotal: wsfu.total,
1412
+ trapSize: spec.minTrapIn,
1413
+ drainSize: spec.minDrainIn,
1414
+ ventSize: spec.minVentIn,
1415
+ supplySize: spec.supplySizeIn,
1416
+ hasVacuumBreaker: false,
1417
+ hasPTrap: spec.needsPTrap,
1418
+ electricalDemand: getFixtureElectricalDemand(kind),
1419
+ })
1420
+ continue
1421
+ }
1422
+ if (kind === 'dishwasher' && placedKitchenSinkInRoom) {
1423
+ const [dwLeftX, dwLeftZ] = rotateLocal2D(
1424
+ placedKitchenSinkInRoom.position[0],
1425
+ placedKitchenSinkInRoom.position[2],
1426
+ -0.68,
1427
+ 0,
1428
+ placedKitchenSinkInRoom.rotation,
1429
+ )
1430
+ const [dwRightX, dwRightZ] = rotateLocal2D(
1431
+ placedKitchenSinkInRoom.position[0],
1432
+ placedKitchenSinkInRoom.position[2],
1433
+ 0.68,
1434
+ 0,
1435
+ placedKitchenSinkInRoom.rotation,
1436
+ )
1437
+ const dwCand = [
1438
+ [dwRightX, dwRightZ] as const,
1439
+ [dwLeftX, dwLeftZ] as const,
1440
+ ].find(
1441
+ ([cx, cz]) =>
1442
+ (room.polygon.length < 3 || pointInPolygon2D(cx, cz, room.polygon)) &&
1443
+ !hitsAnyObstacleXZ(cx, cz, 0.24) &&
1444
+ !hitsAnyWallOpeningXZ(cx, cz, 0.2, false) &&
1445
+ !fixtures.some((f) => Math.hypot(cx - f.position[0], cz - f.position[2]) < 0.45),
1446
+ )
1447
+ if (dwCand) {
1448
+ const [dwX, dwZ] = nudgeOffFloorGirder(dwCand[0], dwCand[1], 0.14, undefined, room.polygon)
1449
+ fixtures.push({
1450
+ id: nextFixId(),
1451
+ name: `${room.name} ${spec.label}`,
1452
+ fixtureKind: kind,
1453
+ position: [dwX, spec.roughInHeightM, dwZ],
1454
+ rotation: placedKitchenSinkInRoom.rotation,
1455
+ roomName: room.name,
1456
+ wallId: placedKitchenSinkInRoom.wallId,
1457
+ dfu: getFixtureDfu(kind, codeEdition),
1458
+ wsfuCold: wsfu.cold,
1459
+ wsfuHot: wsfu.hot,
1460
+ wsfuTotal: wsfu.total,
1461
+ trapSize: spec.minTrapIn,
1462
+ drainSize: spec.minDrainIn,
1463
+ ventSize: spec.minVentIn,
1464
+ supplySize: spec.supplySizeIn,
1465
+ hasVacuumBreaker: false,
1466
+ hasPTrap: spec.needsPTrap,
1467
+ electricalDemand: getFixtureElectricalDemand(kind),
1468
+ })
1469
+ continue
1470
+ }
1471
+ }
1472
+
1473
+ if (nearWall) {
1474
+ const wall = nearWall.wall
1475
+ const span = Math.min(wall.lengthM * 0.72, Math.max(0.8, count * 0.65))
1476
+ const frac = count === 1 ? 0.5 : i / (count - 1)
1477
+ const offsetAlong = (frac - 0.5) * span
1478
+ const baseT = Math.max(0.15, Math.min(0.85, nearWall.t))
1479
+ let alongM = Math.max(0.28, Math.min(wall.lengthM - 0.28, wall.lengthM * baseT + offsetAlong))
1480
+ const toCx = room.centroid[0] - (wall.start[0] + wall.ux * alongM)
1481
+ const toCz = room.centroid[1] - (wall.start[1] + wall.uz * alongM)
1482
+ const dot = toCx * wall.nx + toCz * wall.nz
1483
+ const sign = dot >= 0 ? 1 : -1
1484
+ const inward = wall.thicknessM / 2 + Math.min(0.28, spec.dimensionsM[2] / 2)
1485
+ px = wall.start[0] + wall.ux * alongM + wall.nx * sign * inward
1486
+ pz = wall.start[1] + wall.uz * alongM + wall.nz * sign * inward
1487
+
1488
+ const hitsExistingFixture = (cx: number, cz: number): boolean =>
1489
+ fixtures.some((f) => {
1490
+ if (kind === 'garbage-disposal' && f.fixtureKind === 'kitchen-sink') return false
1491
+ if (f.fixtureKind === 'garbage-disposal' && kind === 'kitchen-sink') return false
1492
+ return Math.hypot(cx - f.position[0], cz - f.position[2]) < minFixSepM
1493
+ })
1494
+
1495
+ const isFixtureSpotBlocked = (
1496
+ w: WallSegment2D,
1497
+ candAlong: number,
1498
+ cx: number,
1499
+ cz: number,
1500
+ pad: number,
1501
+ allowWin: boolean,
1502
+ ): boolean =>
1503
+ hitsExistingFixture(cx, cz) ||
1504
+ hitsAnyObstacleXZ(cx, cz, pad) ||
1505
+ hitsWallOpening(w.id, candAlong, pad, allowWin) ||
1506
+ hitsAnyWallOpeningXZ(cx, cz, Math.min(0.2, pad), allowWin)
1507
+
1508
+ // Keep vertical fixture risers & rough-ins strictly inside `room.polygon` and clear of ALL
1509
+ // structural beams (floor girders AND door/window headers), columns, existing fixtures, and wall openings.
1510
+ const initialOutsideRoom = room.polygon.length >= 3 && !pointInPolygon2D(px, pz, room.polygon)
1511
+ if (initialOutsideRoom || isFixtureSpotBlocked(wall, alongM, px, pz, 0.26, allowUnderWindow)) {
1512
+ let foundClear = false
1513
+ const maxStep = Math.ceil(wall.lengthM / 0.25)
1514
+ // Pass 1: stay strictly inside room.polygon and clear of ALL obstacles + doors/windows on primary wall
1515
+ for (let step = 1; step <= maxStep && !foundClear; step++) {
1516
+ for (const dir of [1, -1] as const) {
1517
+ const candAlong = alongM + dir * step * 0.25
1518
+ if (candAlong < 0.28 || candAlong > wall.lengthM - 0.28) continue
1519
+ const cx = wall.start[0] + wall.ux * candAlong + wall.nx * sign * inward
1520
+ const cz = wall.start[1] + wall.uz * candAlong + wall.nz * sign * inward
1521
+ if (room.polygon.length >= 3 && !pointInPolygon2D(cx, cz, room.polygon)) continue
1522
+ if (!isFixtureSpotBlocked(wall, candAlong, cx, cz, 0.26, allowUnderWindow)) {
1523
+ alongM = candAlong
1524
+ px = cx
1525
+ pz = cz
1526
+ foundClear = true
1527
+ break
1528
+ }
1529
+ }
1530
+ }
1531
+ // Pass 2: if primary wall sits directly over a floor girder or is full of openings, try other nearby walls
1532
+ if (!foundClear && walls.length > 1) {
1533
+ const altWalls = walls
1534
+ .filter((w) => w.id !== wall.id && w.lengthM >= 0.7)
1535
+ .map((w) => {
1536
+ const proj = nearestWallToPoint(room.centroid[0], room.centroid[1], [w])!
1537
+ return { wall: w, t: proj.t, dist: proj.distanceM }
1538
+ })
1539
+ .filter((c) => c.dist <= Math.max(4.5, nearWall.distanceM + 2.5))
1540
+ .sort((a, b) => a.dist - b.dist)
1541
+
1542
+ for (const alt of altWalls) {
1543
+ const w = alt.wall
1544
+ const baseA = Math.max(0.28, Math.min(w.lengthM - 0.28, w.lengthM * alt.t + offsetAlong * 0.5))
1545
+ const aToCx = room.centroid[0] - (w.start[0] + w.ux * baseA)
1546
+ const aToCz = room.centroid[1] - (w.start[1] + w.uz * baseA)
1547
+ const aSign = aToCx * w.nx + aToCz * w.nz >= 0 ? 1 : -1
1548
+ const aInward = w.thicknessM / 2 + Math.min(0.28, spec.dimensionsM[2] / 2)
1549
+ const steps = Math.ceil(w.lengthM / 0.25)
1550
+ for (let step = 0; step <= steps && !foundClear; step++) {
1551
+ const dirs = step === 0 ? ([0] as const) : ([1, -1] as const)
1552
+ for (const dir of dirs) {
1553
+ const candAlong = baseA + dir * step * 0.25
1554
+ if (candAlong < 0.28 || candAlong > w.lengthM - 0.28) continue
1555
+ const cx = w.start[0] + w.ux * candAlong + w.nx * aSign * aInward
1556
+ const cz = w.start[1] + w.uz * candAlong + w.nz * aSign * aInward
1557
+ if (room.polygon.length >= 3 && !pointInPolygon2D(cx, cz, room.polygon)) {
1558
+ continue
1559
+ }
1560
+ if (!isFixtureSpotBlocked(w, candAlong, cx, cz, 0.24, allowUnderWindow)) {
1561
+ chosenWall = w
1562
+ rot = yawFacingRoom(w, room.centroid)
1563
+ px = cx
1564
+ pz = cz
1565
+ foundClear = true
1566
+ break
1567
+ }
1568
+ }
1569
+ }
1570
+ if (foundClear) break
1571
+ }
1572
+ }
1573
+ // Pass 3: keep fixture inside room.polygon & off doorways, staggered by fixture index, then nudge off girders
1574
+ if (!foundClear) {
1575
+ if (
1576
+ (room.polygon.length >= 3 && !pointInPolygon2D(px, pz, room.polygon)) ||
1577
+ hitsWallOpening(wall.id, alongM, 0.24, allowUnderWindow) ||
1578
+ hitsExistingFixture(px, pz)
1579
+ ) {
1580
+ const angle = (i * Math.PI * 2) / Math.max(1, count)
1581
+ const candX = room.centroid[0] + Math.cos(angle) * 0.45
1582
+ const candZ = room.centroid[1] + Math.sin(angle) * 0.45
1583
+ if (room.polygon.length < 3 || pointInPolygon2D(candX, candZ, room.polygon)) {
1584
+ px = candX
1585
+ pz = candZ
1586
+ } else {
1587
+ px = room.centroid[0]
1588
+ pz = room.centroid[1]
1589
+ }
1590
+ }
1591
+ const [nx, nz] = nudgeOffFloorGirder(px, pz, 0.22, undefined, room.polygon)
1592
+ px = nx
1593
+ pz = nz
1594
+ }
1595
+ }
1596
+ } else {
1597
+ px = room.centroid[0] + (i - (count - 1) / 2) * 0.75
1598
+ if (room.polygon.length >= 3 && !pointInPolygon2D(px, pz, room.polygon)) {
1599
+ px = room.centroid[0]
1600
+ pz = room.centroid[1]
1601
+ }
1602
+ const [nx, nz] = nudgeOffFloorGirder(px, pz, 0.22, undefined, room.polygon)
1603
+ px = nx
1604
+ pz = nz
1605
+ }
1606
+ fixtures.push({
1607
+ id: nextFixId(),
1608
+ name: `${room.name} ${spec.label}`,
1609
+ fixtureKind: kind,
1610
+ position: [round2(px), spec.roughInHeightM, round2(pz)],
1611
+ rotation: rot,
1612
+ roomName: room.name,
1613
+ wallId: chosenWall?.id,
1614
+ dfu: getFixtureDfu(kind, codeEdition),
1615
+ wsfuCold: wsfu.cold,
1616
+ wsfuHot: wsfu.hot,
1617
+ wsfuTotal: wsfu.total,
1618
+ trapSize: spec.minTrapIn,
1619
+ drainSize: spec.minDrainIn,
1620
+ ventSize: spec.minVentIn,
1621
+ supplySize: spec.supplySizeIn,
1622
+ hasVacuumBreaker: kind === 'hose-bibb',
1623
+ hasPTrap: spec.needsPTrap,
1624
+ electricalDemand: getFixtureElectricalDemand(kind),
1625
+ })
1626
+ }
1627
+ }
1628
+
1629
+ // 3. Minimum 2 Frost-Proof Exterior Hose Bibbs (Front & Rear per IPC / best practice)
1630
+ // Ground / lowest walled story only: never place exterior frost-proof hose bibbs on upper stories!
1631
+ // Always snap flush onto an actual exterior wall segment (never floating in concave L-cutouts or U-courtyards),
1632
+ // and keep the hose bibb + cold supply tap (+0.06m X) clear of floor girders, headers, and openings.
1633
+ if (isGroundStory) {
1634
+ const hoseBibbSpec = FIXTURE_SPECS['hose-bibb']
1635
+ const hoseWsfu = getFixtureWsfu('hose-bibb', occupancy)
1636
+ const pickClearHoseBibbOnSide = (
1637
+ side: 'front' | 'rear',
1638
+ ): { position: Vec3; rotation: number; wallId?: string } => {
1639
+ const targetZ = side === 'front' ? bounds.maxZ : bounds.minZ
1640
+ const defaultZOffset = side === 'front' ? 0.08 : -0.08
1641
+ const defaultRot = side === 'front' ? 0 : Math.PI
1642
+
1643
+ const horizCandidates = walls
1644
+ .filter((w) => w.lengthM >= 0.6 && Math.abs(w.uz) < 0.35)
1645
+ .map((w) => {
1646
+ const midZ = (w.start[1] + w.end[1]) / 2
1647
+ const onSide = side === 'front' ? midZ >= bounds.cz - 0.1 : midZ <= bounds.cz + 0.1
1648
+ return { wall: w, distToTarget: Math.abs(midZ - targetZ), onSide }
1649
+ })
1650
+ .filter((c) => c.onSide)
1651
+ .sort((a, b) => a.distToTarget - b.distToTarget || b.wall.lengthM - a.wall.lengthM)
1652
+
1653
+ const angledFallback = walls
1654
+ .filter((w) => w.lengthM >= 0.6)
1655
+ .map((w) => {
1656
+ const extZ = side === 'front' ? Math.max(w.start[1], w.end[1]) : Math.min(w.start[1], w.end[1])
1657
+ return { wall: w, distToTarget: Math.abs(extZ - targetZ) }
1658
+ })
1659
+ .sort((a, b) => a.distToTarget - b.distToTarget || b.wall.lengthM - a.wall.lengthM)
1660
+
1661
+ const rankedWalls: Array<{ wall: WallSegment2D; distToTarget: number }> = []
1662
+ const seenWallIds = new Set<string>()
1663
+ for (const c of horizCandidates) {
1664
+ if (!seenWallIds.has(c.wall.id)) {
1665
+ seenWallIds.add(c.wall.id)
1666
+ rankedWalls.push({ wall: c.wall, distToTarget: c.distToTarget })
1667
+ }
1668
+ }
1669
+ for (const c of angledFallback) {
1670
+ if (!seenWallIds.has(c.wall.id)) {
1671
+ seenWallIds.add(c.wall.id)
1672
+ rankedWalls.push({ wall: c.wall, distToTarget: c.distToTarget })
1673
+ }
1674
+ }
1675
+
1676
+ const resolveOutwardNormal = (w: WallSegment2D): { outNx: number; outNz: number; rot: number } => {
1677
+ if (Math.abs(w.uz) < 0.35 && Math.abs(w.nz) > 0.25) {
1678
+ const desiredZ = side === 'front' ? 1 : -1
1679
+ const sign = w.nz * desiredZ >= 0 ? 1 : -1
1680
+ const outNx = w.nx * sign
1681
+ const outNz = w.nz * sign
1682
+ const rot = Math.abs(outNx) < 1e-3 ? (outNz >= 0 ? 0 : Math.PI) : round2(Math.atan2(outNx, outNz))
1683
+ return { outNx, outNz, rot }
1684
+ }
1685
+ const mx = (w.start[0] + w.end[0]) / 2
1686
+ const mz = (w.start[1] + w.end[1]) / 2
1687
+ const sign = (mx - bounds.cx) * w.nx + (mz - bounds.cz) * w.nz >= 0 ? 1 : -1
1688
+ const outNx = w.nx * sign
1689
+ const outNz = w.nz * sign
1690
+ return { outNx, outNz, rot: round2(Math.atan2(outNx, outNz)) }
1691
+ }
1692
+
1693
+ const isClearAt = (
1694
+ x: number,
1695
+ z: number,
1696
+ w: WallSegment2D | null,
1697
+ alongM: number,
1698
+ pad: number,
1699
+ ): boolean =>
1700
+ !indoorRooms.some((r) => r.polygon.length >= 3 && pointInPolygon2D(x, z, r.polygon)) &&
1701
+ !hitsFloorBeamXZ(x, z, pad) &&
1702
+ !hitsFloorBeamXZ(x + 0.06, z, pad) &&
1703
+ !hitsAnyObstacleXZ(x, z, pad * 0.7) &&
1704
+ !hitsAnyObstacleXZ(x + 0.06, z, pad * 0.7) &&
1705
+ (!w || !hitsWallOpening(w.id, alongM, 0.22, false)) &&
1706
+ !hitsAnyWallOpeningXZ(x, z, 0.22, false)
1707
+
1708
+ if (rankedWalls.length > 0) {
1709
+ const minDist = rankedWalls[0]!.distToTarget
1710
+ const outerBand = rankedWalls.filter((c) => c.distToTarget <= minDist + 0.5).map((c) => c.wall)
1711
+ const innerFallback = rankedWalls.filter((c) => c.distToTarget > minDist + 0.5).map((c) => c.wall)
1712
+
1713
+ const sampleWall = (
1714
+ w: WallSegment2D,
1715
+ pad: number,
1716
+ ): { position: Vec3; rotation: number; wallId: string } | null => {
1717
+ const { outNx, outNz, rot } = resolveOutwardNormal(w)
1718
+ const outOffset = Math.max(0.08, Math.min(0.14, w.thicknessM / 2))
1719
+ const margin = Math.min(0.35, w.lengthM * 0.25)
1720
+ const projAlong = (bounds.cx - w.start[0]) * w.ux + (targetZ - w.start[1]) * w.uz
1721
+ const baseAlong = Math.max(margin, Math.min(w.lengthM - margin, projAlong))
1722
+ for (const shift of [0, 0.55, -0.55, 0.95, -0.95, 1.4, -1.4, 2.0, -2.0, 2.6, -2.6]) {
1723
+ const candAlong = Math.max(margin, Math.min(w.lengthM - margin, baseAlong + shift))
1724
+ const bx = round2(w.start[0] + w.ux * candAlong + outNx * outOffset)
1725
+ const bz = round2(w.start[1] + w.uz * candAlong + outNz * outOffset)
1726
+ if (isClearAt(bx, bz, w, candAlong, pad)) {
1727
+ return {
1728
+ position: [bx, hoseBibbSpec.roughInHeightM, bz],
1729
+ rotation: rot,
1730
+ wallId: w.id,
1731
+ }
1732
+ }
1733
+ }
1734
+ return null
1735
+ }
1736
+
1737
+ // Prefer outer exterior facade walls before any recessed wall segments
1738
+ for (const wallGroup of [outerBand, innerFallback]) {
1739
+ for (const pad of [0.30, 0.16]) {
1740
+ for (const w of wallGroup) {
1741
+ const hit = sampleWall(w, pad)
1742
+ if (hit) return hit
1743
+ }
1744
+ }
1745
+ }
1746
+
1747
+ // Guaranteed wall-snapped fallback on the closest exterior wall segment (avoiding openings when possible)
1748
+ const firstWall = outerBand[0] ?? rankedWalls[0]!.wall
1749
+ const { outNx, outNz, rot } = resolveOutwardNormal(firstWall)
1750
+ const outOffset = Math.max(0.08, Math.min(0.14, firstWall.thicknessM / 2))
1751
+ const margin = Math.min(0.35, firstWall.lengthM * 0.25)
1752
+ const projAlong = (bounds.cx - firstWall.start[0]) * firstWall.ux + (targetZ - firstWall.start[1]) * firstWall.uz
1753
+ let fallbackAlong = Math.max(margin, Math.min(firstWall.lengthM - margin, projAlong))
1754
+ if (hitsWallOpening(firstWall.id, fallbackAlong, 0.22, false)) {
1755
+ for (const shift of [0.55, -0.55, 1.0, -1.0, 1.5, -1.5, 2.2, -2.2]) {
1756
+ const cand = Math.max(margin, Math.min(firstWall.lengthM - margin, fallbackAlong + shift))
1757
+ if (!hitsWallOpening(firstWall.id, cand, 0.22, false)) {
1758
+ fallbackAlong = cand
1759
+ break
1760
+ }
1761
+ }
1762
+ }
1763
+ return {
1764
+ position: [
1765
+ round2(firstWall.start[0] + firstWall.ux * fallbackAlong + outNx * outOffset),
1766
+ hoseBibbSpec.roughInHeightM,
1767
+ round2(firstWall.start[1] + firstWall.uz * fallbackAlong + outNz * outOffset),
1768
+ ],
1769
+ rotation: rot,
1770
+ wallId: firstWall.id,
1771
+ }
1772
+ }
1773
+
1774
+ // Wall-less scene fallback
1775
+ const wallZ = round2(targetZ + defaultZOffset)
1776
+ const minX = bounds.minX + 0.35
1777
+ const maxX = bounds.maxX - 0.35
1778
+ const baseX = bounds.cx
1779
+ for (const pad of [0.30, 0.16]) {
1780
+ for (const shift of [0, 0.55, -0.55, 0.95, -0.95, 1.4, -1.4, 2.0, -2.0, 2.6, -2.6]) {
1781
+ const cx = round2(Math.max(minX, Math.min(maxX, baseX + shift)))
1782
+ if (isClearAt(cx, wallZ, null, 0, pad)) {
1783
+ return { position: [cx, hoseBibbSpec.roughInHeightM, wallZ], rotation: defaultRot }
1784
+ }
1785
+ }
1786
+ }
1787
+ return { position: [round2(baseX), hoseBibbSpec.roughInHeightM, wallZ], rotation: defaultRot }
1788
+ }
1789
+ const frontBibb = pickClearHoseBibbOnSide('front')
1790
+ const rearBibb = pickClearHoseBibbOnSide('rear')
1791
+ fixtures.push(
1792
+ {
1793
+ id: nextFixId(),
1794
+ name: 'Exterior Front Hose Bibb (Frost-Proof)',
1795
+ fixtureKind: 'hose-bibb',
1796
+ position: frontBibb.position,
1797
+ rotation: frontBibb.rotation,
1798
+ roomName: 'Exterior Front',
1799
+ wallId: frontBibb.wallId,
1800
+ dfu: 0,
1801
+ wsfuCold: hoseWsfu.cold,
1802
+ wsfuHot: 0,
1803
+ wsfuTotal: hoseWsfu.total,
1804
+ trapSize: null,
1805
+ drainSize: null,
1806
+ ventSize: null,
1807
+ supplySize: '1/2"',
1808
+ hasVacuumBreaker: true,
1809
+ hasPTrap: false,
1810
+ electricalDemand: null,
1811
+ },
1812
+ {
1813
+ id: nextFixId(),
1814
+ name: 'Exterior Rear Hose Bibb (Frost-Proof)',
1815
+ fixtureKind: 'hose-bibb',
1816
+ position: rearBibb.position,
1817
+ rotation: rearBibb.rotation,
1818
+ roomName: 'Exterior Rear',
1819
+ wallId: rearBibb.wallId,
1820
+ dfu: 0,
1821
+ wsfuCold: hoseWsfu.cold,
1822
+ wsfuHot: 0,
1823
+ wsfuTotal: hoseWsfu.total,
1824
+ trapSize: null,
1825
+ drainSize: null,
1826
+ ventSize: null,
1827
+ supplySize: '1/2"',
1828
+ hasVacuumBreaker: true,
1829
+ hasPTrap: false,
1830
+ electricalDemand: null,
1831
+ },
1832
+ )
1833
+ }
1834
+ }
1835
+
1836
+ // 4. Place Mechanical Core: Water Entry (PRV + Shutoff), Water Heater, Expansion Tank, PEX Manifold, optional Gas Meter
1837
+ // Prefer a dedicated Utility/Garage/Laundry room; when none exists, tuck the mechanical core cleanly into
1838
+ // a corner alcove of the wet core (Kitchen/Bath) instead of dropping a water heater in the middle of a Living Room,
1839
+ // and stay strictly inside the walled building bounds and clear of floor HVAC / NEC 110.26 panels.
1840
+ const dedicatedMechRoom =
1841
+ indoorRooms.find((r) => r.category === 'utility' || r.category === 'garage' || r.category === 'laundry') ?? null
1842
+ const mechRoom =
1843
+ dedicatedMechRoom ??
1844
+ indoorRooms.find((r) => r.category === 'kitchen' || r.category === 'commercial-kitchen') ??
1845
+ indoorRooms.find((r) => r.category === 'bathroom' || r.category === 'master-bath' || r.category === 'commercial-restroom') ??
1846
+ indoorRooms[0] ??
1847
+ null
1848
+
1849
+ const crossTradeFloorEquip: Array<{ x: number; z: number; minClearM: number }> = []
1850
+ for (const n of Object.values(nodes)) {
1851
+ if (!belongsToLevel(nodes, n, levelId)) continue
1852
+ if (!Array.isArray(n.position) || n.position.length < 3) continue
1853
+ const ny = Number(n.position[1] ?? 0)
1854
+ // Ignore attic/roof-mounted HVAC equipment (y >= levelH - 0.1) so floor plumbing can stack neatly below an attic core
1855
+ if (n.type === 'hvac:equipment' && ny < levelH - 0.1) {
1856
+ crossTradeFloorEquip.push({ x: Number(n.position[0]), z: Number(n.position[2]), minClearM: 1.05 })
1857
+ } else if (n.type === 'electrical:panel') {
1858
+ crossTradeFloorEquip.push({ x: Number(n.position[0]), z: Number(n.position[2]), minClearM: 1.0 })
1859
+ }
1860
+ }
1861
+
1862
+ const minClearCrossTrade = (cx: number, cz: number): number => {
1863
+ let best = Infinity
1864
+ for (const eq of crossTradeFloorEquip) {
1865
+ const d = Math.hypot(cx - eq.x, cz - eq.z) - eq.minClearM
1866
+ if (d < best) best = d
1867
+ }
1868
+ for (const f of fixtures) {
1869
+ const d = Math.hypot(cx - f.position[0], cz - f.position[2]) - 0.65
1870
+ if (d < best) best = d
1871
+ }
1872
+ return best
1873
+ }
1874
+
1875
+ const pickWallTuckedMechCorner = (room: RoomPolygon2D | null): [number, number] => {
1876
+ if (!room || room.polygon.length < 3) {
1877
+ // When no indoor zone polygons exist, anchor near the first indoor fixture (tucked inward)
1878
+ // or cleanly inside the walled building bounds.
1879
+ const indoorFix = fixtures.find((f) => f.fixtureKind !== 'hose-bibb')
1880
+ if (indoorFix) {
1881
+ const nw = nearestWallToPoint(indoorFix.position[0], indoorFix.position[2], walls)
1882
+ if (nw) {
1883
+ const w = nw.wall
1884
+ const toCx = bounds.cx - nw.point[0]
1885
+ const toCz = bounds.cz - nw.point[1]
1886
+ const sign = toCx * w.nx + toCz * w.nz >= 0 ? 1 : -1
1887
+ const [cx, cz] = clampToBoundsXZ(
1888
+ nw.point[0] + w.nx * sign * 0.45,
1889
+ nw.point[1] + w.nz * sign * 0.45,
1890
+ 0.25,
1891
+ )
1892
+ return [cx, cz]
1893
+ }
1894
+ const [cx, cz] = clampToBoundsXZ(indoorFix.position[0], indoorFix.position[2], 0.25)
1895
+ return [cx, cz]
1896
+ }
1897
+ const [cx, cz] = clampToBoundsXZ(bounds.minX + 0.55, bounds.minZ + 0.55, 0.25)
1898
+ return [cx, cz]
1899
+ }
1900
+ const inset = 0.42
1901
+ const candidates: Array<readonly [number, number]> = []
1902
+ for (let i = 0; i < room.polygon.length; i++) {
1903
+ const a = room.polygon[i]!
1904
+ const b = room.polygon[(i + 1) % room.polygon.length]!
1905
+ const dxC = room.centroid[0] - a[0]
1906
+ const dzC = room.centroid[1] - a[1]
1907
+ const lenC = Math.hypot(dxC, dzC)
1908
+ if (lenC > inset * 1.1) {
1909
+ candidates.push([round2(a[0] + (dxC / lenC) * inset), round2(a[1] + (dzC / lenC) * inset)])
1910
+ }
1911
+ const mx = (a[0] + b[0]) / 2
1912
+ const mz = (a[1] + b[1]) / 2
1913
+ const dxM = room.centroid[0] - mx
1914
+ const dzM = room.centroid[1] - mz
1915
+ const lenM = Math.hypot(dxM, dzM)
1916
+ if (lenM > inset * 1.1) {
1917
+ candidates.push([round2(mx + (dxM / lenM) * inset), round2(mz + (dzM / lenM) * inset)])
1918
+ }
1919
+ }
1920
+ let best: [number, number] | null = null
1921
+ let bestScore = -Infinity
1922
+ for (const [cx, cz] of candidates) {
1923
+ if (!pointInPolygon2D(cx, cz, room.polygon)) continue
1924
+ if (cx < bounds.minX + 0.2 || cx > bounds.maxX - 0.2 || cz < bounds.minZ + 0.2 || cz > bounds.maxZ - 0.2) continue
1925
+ const beamPenalty = hitsFloorBeamXZ(cx, cz, 0.35) ? -80 : 40
1926
+ const obstaclePenalty = hitsAnyObstacleXZ(cx, cz, 0.32) ? -100 : 0
1927
+ const openingPenalty = hitsAnyWallOpeningXZ(cx, cz, 0.42, false) ? -120 : 0
1928
+ const clear = minClearCrossTrade(cx, cz)
1929
+ const clearScore = clear >= 0 ? 60 + Math.min(1.5, clear) * 10 : clear * 60
1930
+ // Prefer exterior wall corners for short water-entry / condensate / flue runs
1931
+ const extDist = Math.min(
1932
+ Math.abs(cx - bounds.minX),
1933
+ Math.abs(bounds.maxX - cx),
1934
+ Math.abs(cz - bounds.minZ),
1935
+ Math.abs(bounds.maxZ - cz),
1936
+ )
1937
+ const score = beamPenalty + obstaclePenalty + openingPenalty + clearScore - extDist * 2.5
1938
+ if (score > bestScore) {
1939
+ bestScore = score
1940
+ best = [cx, cz]
1941
+ }
1942
+ }
1943
+ if (best) return best
1944
+ const [fx, fz] = clampToBoundsXZ(room.centroid[0], room.centroid[1], 0.2)
1945
+ return [fx, fz]
1946
+ }
1947
+
1948
+ const mechNudgeShifts: ReadonlyArray<number> = [0.55, -0.55, 0.95, -0.95]
1949
+
1950
+ const [cornerWhX, cornerWhZ] = pickWallTuckedMechCorner(mechRoom)
1951
+ let whPos: Vec3 = [cornerWhX, 0, cornerWhZ]
1952
+ if (placedWaterHeaterSku) {
1953
+ whPos = placedWaterHeaterSku.pos
1954
+ } else if (bones?.waterHeaterAnchor) {
1955
+ const resolved = resolveBonesAnchorPosition(nodes, bones.waterHeaterAnchor, 0)
1956
+ if (resolved) {
1957
+ whPos = [round2(resolved[0]), 0, round2(resolved[2])]
1958
+ bonesAnchorsUsed.push(`water-heater (${bones.waterHeaterAnchor.nodeId})`)
1959
+ }
1960
+ } else {
1961
+ const [nx, nz] = nudgeOffFloorGirder(whPos[0], whPos[2], 0.35, mechNudgeShifts, mechRoom?.polygon)
1962
+ const [cx, cz] = clampToBoundsXZ(nx, nz, 0.15)
1963
+ whPos = [cx, 0, cz]
1964
+ }
1965
+
1966
+ // Snap West-side service entries (Main Water Shutoff / Gas Meter) onto the West exterior wall segment
1967
+ // closest to whPos[2] so concave L/U footprints and collinear split walls stay on a real West wall span.
1968
+ const westBandWalls = walls
1969
+ .filter((w) => Math.abs(w.start[0] - w.end[0]) < 0.25 && Math.abs(w.end[1] - w.start[1]) >= 0.8)
1970
+ .map((w) => ({
1971
+ x: (w.start[0] + w.end[0]) / 2,
1972
+ minZ: Math.min(w.start[1], w.end[1]),
1973
+ maxZ: Math.max(w.start[1], w.end[1]),
1974
+ }))
1975
+ .filter((w) => Math.abs(w.x - bounds.minX) < 0.5)
1976
+ const distToWestSpan = (z: number, w: { minZ: number; maxZ: number }) =>
1977
+ z < w.minZ ? w.minZ - z : z > w.maxZ ? z - w.maxZ : 0
1978
+ const westOuterWall =
1979
+ westBandWalls.sort(
1980
+ (a, b) =>
1981
+ distToWestSpan(whPos[2], a) - distToWestSpan(whPos[2], b) ||
1982
+ Math.abs(a.x - bounds.minX) - Math.abs(b.x - bounds.minX),
1983
+ )[0] ?? null
1984
+ const westMinZ = westOuterWall ? westOuterWall.minZ + 0.25 : bounds.minZ + 0.15
1985
+ const westMaxZ = westOuterWall ? westOuterWall.maxZ - 0.25 : bounds.maxZ - 0.15
1986
+ const clampWestZ = (z: number): number =>
1987
+ round2(westMinZ <= westMaxZ ? Math.max(westMinZ, Math.min(westMaxZ, z)) : (westMinZ + westMaxZ) / 2)
1988
+
1989
+ let waterEntryPos: Vec3 = [round2((westOuterWall ? westOuterWall.x : bounds.minX) + 0.15), 0.75, clampWestZ(whPos[2])]
1990
+ if (emitMainShutoff) {
1991
+ if (bones?.waterEntryAnchor) {
1992
+ const resolved = resolveBonesAnchorPosition(nodes, bones.waterEntryAnchor, 0.75)
1993
+ if (resolved) {
1994
+ waterEntryPos = [
1995
+ round2(resolved[0]),
1996
+ round2(Number.isFinite(resolved[1]) ? resolved[1] : 0.75),
1997
+ round2(resolved[2]),
1998
+ ]
1999
+ bonesAnchorsUsed.push(`water-entry (${bones.waterEntryAnchor.nodeId})`)
2000
+ }
2001
+ } else {
2002
+ const [nx, nz] = nudgeOffFloorGirder(waterEntryPos[0], waterEntryPos[2], 0.35, mechNudgeShifts)
2003
+ const [ex, ez] = clampToBoundsXZ(nx, westOuterWall ? clampWestZ(nz) : nz, 0.15)
2004
+ waterEntryPos = [ex, 0.75, ez]
2005
+ }
2006
+ }
2007
+
2008
+ // Ground-story building sewer exit: snap onto actual East exterior wall span on concave L/U footprints
2009
+ // so the horizontal sewer exit never crosses an empty L-cutout, and keep strictly below slab (y <= -0.45m).
2010
+ const eastWalls = walls
2011
+ .filter((w) => Math.abs(w.start[0] - w.end[0]) < 0.25 && Math.abs(w.end[1] - w.start[1]) >= 0.8)
2012
+ .map((w) => ({
2013
+ x: (w.start[0] + w.end[0]) / 2,
2014
+ minZ: Math.min(w.start[1], w.end[1]),
2015
+ maxZ: Math.max(w.start[1], w.end[1]),
2016
+ }))
2017
+ .sort((a, b) => Math.abs(a.x - bounds.maxX) - Math.abs(b.x - bounds.maxX))
2018
+ const eastOuterWall = eastWalls[0] && Math.abs(eastWalls[0].x - bounds.maxX) < 0.5 ? eastWalls[0] : null
2019
+ const sewerMinZ = eastOuterWall ? eastOuterWall.minZ + 0.35 : bounds.minZ + 0.35
2020
+ const sewerMaxZ = eastOuterWall ? eastOuterWall.maxZ - 0.35 : bounds.maxZ - 0.35
2021
+ const sewerBaseZ = sewerMinZ <= sewerMaxZ ? Math.max(sewerMinZ, Math.min(sewerMaxZ, bounds.cz)) : bounds.cz
2022
+ let sewerExitZ = round2(sewerBaseZ)
2023
+ if (isGroundStory && !bones?.sewerExitAnchor && sewerMinZ <= sewerMaxZ && hitsFloorBeamXZ(bounds.maxX, sewerExitZ, 0.35)) {
2024
+ for (const shift of [0.65, -0.65, 1.15, -1.15, 1.75, -1.75]) {
2025
+ const cz = round2(Math.max(sewerMinZ, Math.min(sewerMaxZ, sewerBaseZ + shift)))
2026
+ if (!hitsFloorBeamXZ(bounds.maxX, cz, 0.35)) {
2027
+ sewerExitZ = cz
2028
+ break
2029
+ }
2030
+ }
2031
+ }
2032
+ let sewerExitPos: Vec3 = [round2(bounds.maxX + 1.2), foundationType === 'slab' ? -0.55 : -0.45, sewerExitZ]
2033
+ if (isGroundStory && bones?.sewerExitAnchor) {
2034
+ const resolved = resolveBonesAnchorPosition(nodes, bones.sewerExitAnchor, -0.45)
2035
+ if (resolved) {
2036
+ sewerExitPos = [round2(resolved[0]), foundationType === 'slab' ? -0.55 : -0.45, round2(resolved[2])]
2037
+ bonesAnchorsUsed.push(`sewer-exit (${bones.sewerExitAnchor.nodeId})`)
2038
+ }
2039
+ }
2040
+
2041
+ const wcCount = fixtures.filter((f) => f.fixtureKind === 'water-closet').length
2042
+ const totalDfu = fixtures.reduce((s, f) => s + f.dfu, 0)
2043
+ const iceMakerWsfu = discoveredIceMakers.reduce((s, im) => s + im.wsfuCold, 0)
2044
+ const totalWsfu = round2(fixtures.reduce((s, f) => s + f.wsfuTotal, 0) + iceMakerWsfu)
2045
+ const whFuel =
2046
+ resolvedWaterHeaterKind === 'water-heater-tank-gas'
2047
+ ? 'gas'
2048
+ : resolvedWaterHeaterKind === 'water-heater-tankless-gas'
2049
+ ? 'tankless-gas'
2050
+ : resolvedWaterHeaterKind === 'water-heater-hpwh'
2051
+ ? 'hpwh'
2052
+ : 'electric'
2053
+ const whSizing = sizeWaterHeater({
2054
+ bathrooms: Math.max(1, wcCount),
2055
+ bedrooms: Math.max(2, wcCount + 1),
2056
+ occupancy,
2057
+ fuelType: whFuel,
2058
+ })
2059
+ const resolvedWhCapGal =
2060
+ resolvedWaterHeaterKind === 'water-heater-tankless-gas'
2061
+ ? 0
2062
+ : Math.max(whSizing.recommendedTankGal, placedWaterHeaterSku?.capacityGal ?? 0)
2063
+
2064
+ let waterEntryId: string | undefined
2065
+ if (emitMainShutoff) {
2066
+ waterEntryId = nextEqId()
2067
+ equipment.push({
2068
+ id: waterEntryId,
2069
+ name: 'Main Water Shutoff, PRV & Check Valve',
2070
+ equipmentKind: 'main-shutoff-prv',
2071
+ position: waterEntryPos,
2072
+ rotation: 0,
2073
+ roomName: mechRoom?.name ?? placedWaterHeaterSku?.roomName ?? 'Utility',
2074
+ electricalDemand: null,
2075
+ })
2076
+ }
2077
+
2078
+ let whId: string | undefined
2079
+ if (emitWaterHeater) {
2080
+ whId = nextEqId()
2081
+ const skuTag = placedWaterHeaterSku?.sku ? ` [${placedWaterHeaterSku.sku}]` : ''
2082
+ equipment.push({
2083
+ id: whId,
2084
+ name:
2085
+ resolvedWaterHeaterKind === 'water-heater-tankless-gas'
2086
+ ? `Tankless Gas Water Heater (${whSizing.recommendedTanklessGpm} GPM)${skuTag}`
2087
+ : resolvedWaterHeaterKind === 'water-heater-hpwh'
2088
+ ? `Hybrid Heat Pump Water Heater (${resolvedWhCapGal} gal)${skuTag}`
2089
+ : `${whFuel === 'gas' ? 'Gas' : 'Electric'} Water Heater (${resolvedWhCapGal} gal)${skuTag}`,
2090
+ equipmentKind: resolvedWaterHeaterKind,
2091
+ position: whPos,
2092
+ rotation: placedWaterHeaterSku?.rot ?? 0,
2093
+ roomName: placedWaterHeaterSku?.roomName ?? mechRoom?.name ?? 'Utility',
2094
+ capacityGal: resolvedWhCapGal,
2095
+ gasBtuh: whSizing.gasBtuh,
2096
+ watts: whSizing.electricalLoadWatts,
2097
+ hasDrainPan: true,
2098
+ hasTpDischarge: true,
2099
+ hasExpansionTank: true,
2100
+ electricalDemand: getEquipmentElectricalDemand(resolvedWaterHeaterKind, whSizing.electricalLoadWatts),
2101
+ ...(placedWaterHeaterSku
2102
+ ? {
2103
+ furnishingSourceId: placedWaterHeaterSku.sourceId,
2104
+ ...(placedWaterHeaterSku.sku ? { catalogSku: placedWaterHeaterSku.sku } : {}),
2105
+ roughInOnly: true,
2106
+ }
2107
+ : {}),
2108
+ })
2109
+ }
2110
+
2111
+ const pickInwardDir = (distM: number): readonly [number, number] => {
2112
+ const dirs: ReadonlyArray<readonly [number, number]> = [
2113
+ [1, 0],
2114
+ [-1, 0],
2115
+ [0, 1],
2116
+ [0, -1],
2117
+ ]
2118
+ for (const [dx, dz] of dirs) {
2119
+ const tx = round2(whPos[0] + dx * distM)
2120
+ const tz = round2(whPos[2] + dz * distM)
2121
+ const inBounds =
2122
+ tx >= bounds.minX + 0.15 &&
2123
+ tx <= bounds.maxX - 0.15 &&
2124
+ tz >= bounds.minZ + 0.15 &&
2125
+ tz <= bounds.maxZ - 0.15
2126
+ if (!inBounds) continue
2127
+ if (!mechRoom || pointInPolygon2D(tx, tz, mechRoom.polygon)) {
2128
+ return [dx, dz]
2129
+ }
2130
+ }
2131
+ for (const [dx, dz] of dirs) {
2132
+ const tx = round2(whPos[0] + dx * distM)
2133
+ const tz = round2(whPos[2] + dz * distM)
2134
+ if (
2135
+ tx >= bounds.minX + 0.15 &&
2136
+ tx <= bounds.maxX - 0.15 &&
2137
+ tz >= bounds.minZ + 0.15 &&
2138
+ tz <= bounds.maxZ - 0.15
2139
+ ) {
2140
+ return [dx, dz]
2141
+ }
2142
+ }
2143
+ return [0, 0]
2144
+ }
2145
+ const [mechDirX, mechDirZ] = pickInwardDir(0.68)
2146
+
2147
+ if (emitWaterHeater) {
2148
+ const [expX, expZ] = clampToBoundsXZ(whPos[0] + mechDirX * 0.35, whPos[2] + mechDirZ * 0.35, 0.15)
2149
+ const expTankY = round2(Math.min(1.65, Math.max(1.1, levelH - 0.7)))
2150
+ const expTankId = nextEqId()
2151
+ equipment.push({
2152
+ id: expTankId,
2153
+ name: `Thermal Expansion Tank (${whSizing.expansionTankGal} gal, IPC 607.3)`,
2154
+ equipmentKind: 'expansion-tank',
2155
+ position: [expX, expTankY, expZ],
2156
+ rotation: 0,
2157
+ roomName: mechRoom?.name ?? 'Utility',
2158
+ capacityGal: whSizing.expansionTankGal,
2159
+ electricalDemand: null,
2160
+ })
2161
+ }
2162
+
2163
+ let manifoldId: string | undefined
2164
+ let manifoldRotation = placedManifoldSku?.rot ?? 0
2165
+ let [rawManifoldX, rawManifoldZ] = placedManifoldSku
2166
+ ? [placedManifoldSku.pos[0], placedManifoldSku.pos[2]]
2167
+ : emitWaterHeater
2168
+ ? clampToBoundsXZ(whPos[0] + mechDirX * 0.65, whPos[2] + mechDirZ * 0.65, 0.15)
2169
+ : [whPos[0], whPos[2]]
2170
+
2171
+ // Recess an auto-placed PEX Home-Run Manifold flush inside its backing mechanical-room wall stud bay
2172
+ // (instead of floating 0.75 m out in the garage) so all home-run risers enter directly into the wall cavity.
2173
+ if (!placedManifoldSku && walls.length > 0) {
2174
+ const manWall = nearestWallToPoint(rawManifoldX, rawManifoldZ, walls)
2175
+ if (manWall && manWall.distanceM <= 1.25 && manWall.wall.lengthM >= 0.8) {
2176
+ const w = manWall.wall
2177
+ let along = Math.max(0.35, Math.min(w.lengthM - 0.35, w.lengthM * manWall.t))
2178
+ let sx = round2(w.start[0] + w.ux * along)
2179
+ let sz = round2(w.start[1] + w.uz * along)
2180
+ // Ensure manifold doesn't sit directly on top of the water heater or inside a door/window opening
2181
+ if (Math.hypot(sx - whPos[0], sz - whPos[2]) < 0.45 || hitsWallOpening(w.id, along, 0.3, false)) {
2182
+ for (const shift of [-0.65, 0.65, -1.1, 1.1]) {
2183
+ const candAlong = along + shift
2184
+ if (candAlong < 0.35 || candAlong > w.lengthM - 0.35) continue
2185
+ const cx = round2(w.start[0] + w.ux * candAlong)
2186
+ const cz = round2(w.start[1] + w.uz * candAlong)
2187
+ if (Math.hypot(cx - whPos[0], cz - whPos[2]) >= 0.45 && !hitsWallOpening(w.id, candAlong, 0.3, false)) {
2188
+ along = candAlong
2189
+ sx = cx
2190
+ sz = cz
2191
+ break
2192
+ }
2193
+ }
2194
+ }
2195
+ if (!hitsWallOpening(w.id, along, 0.25, false) && !hitsAnyObstacleXZ(sx, sz, 0.2)) {
2196
+ rawManifoldX = sx
2197
+ rawManifoldZ = sz
2198
+ manifoldRotation = round2(Math.atan2(-w.uz, w.ux))
2199
+ }
2200
+ }
2201
+ }
2202
+
2203
+ const [nudgedManX, nudgedManZ] = nudgeOffFloorGirder(
2204
+ rawManifoldX,
2205
+ rawManifoldZ,
2206
+ 0.25,
2207
+ mechNudgeShifts,
2208
+ placedManifoldSku?.roomPolygon ?? mechRoom?.polygon,
2209
+ )
2210
+ // Keep recessed manifold flush inside the wall thickness while staying >= 0.10 m inside outer bounds
2211
+ // so side inlet/outlet nipples (+0.085 m) never protrude past building exterior bounds.
2212
+ const [manX, manZ] = clampToBoundsXZ(nudgedManX, nudgedManZ, 0.12)
2213
+ const manifoldPos: Vec3 = [manX, 1.35, manZ]
2214
+ if (supplyTopology === 'manifold') {
2215
+ manifoldId = nextManId()
2216
+ const demandPorts = Math.ceil(((fixtures.length + discoveredIceMakers.length) * 1.6) / 6) * 6
2217
+ const portCount = placedManifoldSku
2218
+ ? Math.min(36, Math.max(4, placedManifoldSku.portCount))
2219
+ : Math.min(36, Math.max(12, demandPorts))
2220
+ const manSkuTag = placedManifoldSku?.sku ? ` [${placedManifoldSku.sku}]` : ''
2221
+ manifolds.push({
2222
+ id: manifoldId,
2223
+ name: `PEX Home-Run Manifold (${portCount}-Port)${manSkuTag}`,
2224
+ manifoldKind: 'pex-homerun',
2225
+ position: manifoldPos,
2226
+ rotation: manifoldRotation,
2227
+ portCount,
2228
+ supplyMaterial,
2229
+ coverRemoved: false,
2230
+ ...(placedManifoldSku
2231
+ ? {
2232
+ furnishingSourceId: placedManifoldSku.sourceId,
2233
+ ...(placedManifoldSku.sku ? { catalogSku: placedManifoldSku.sku } : {}),
2234
+ roughInOnly: true,
2235
+ }
2236
+ : {}),
2237
+ })
2238
+ }
2239
+
2240
+ // 5. Route Main Cold Supply Service (ground story) or Interior Supply Risers (upper stories)
2241
+ const supplyPlaneY = foundationType === 'slab' ? levelH - 0.25 : -0.16
2242
+ const mainColdSized = sizeSupplyPipe({
2243
+ wsfu: Math.max(1, totalWsfu),
2244
+ material: supplyMaterial,
2245
+ isHot: false,
2246
+ minSize: '3/4"',
2247
+ flushType,
2248
+ })
2249
+ const totalHotWsfu = round2(fixtures.reduce((s, f) => s + f.wsfuHot, 0))
2250
+ const hotMainSized = sizeSupplyPipe({
2251
+ wsfu: Math.max(1, totalHotWsfu),
2252
+ material: supplyMaterial,
2253
+ isHot: true,
2254
+ minSize: '3/4"',
2255
+ flushType,
2256
+ })
2257
+
2258
+ let coldRiserId: string | undefined
2259
+ let hotRiserId: string | undefined
2260
+ let coldTrunkOrigin: Vec3 = [whPos[0] + 0.08, 1.45, whPos[2]]
2261
+ let hotTrunkOrigin: Vec3 = [whPos[0] - 0.08, 1.45, whPos[2]]
2262
+
2263
+ if (emitWaterHeater && whId) {
2264
+ const coldSourcePos: Vec3 = emitMainShutoff ? waterEntryPos : [whPos[0] + 0.1, supplyPlaneY, whPos[2]]
2265
+ const mainColdRoute = routePressurizedPipeRun({
2266
+ from: coldSourcePos,
2267
+ to: [whPos[0] + 0.1, 1.55, whPos[2]],
2268
+ routingPlaneY: supplyPlaneY,
2269
+ nominalSize: mainColdSized.size,
2270
+ material: supplyMaterial,
2271
+ euclideanInCavity: false,
2272
+ obstacles,
2273
+ buildingBounds: bounds,
2274
+ maxRoofYAt,
2275
+ cavityContext,
2276
+ })
2277
+ pipeRuns.push({
2278
+ id: nextPipeId(),
2279
+ name: emitMainShutoff
2280
+ ? `${mainColdSized.size} Main Cold Water Service`
2281
+ : `${mainColdSized.size} Upper-Story Cold Supply Riser`,
2282
+ system: 'cold-water',
2283
+ material: supplyMaterial,
2284
+ nominalSize: mainColdSized.size,
2285
+ path: mainColdRoute.path,
2286
+ slopeInPerFt: 0,
2287
+ dfuLoad: 0,
2288
+ wsfuLoad: round2(totalWsfu),
2289
+ gasBtuh: 0,
2290
+ sourceNodeId: waterEntryId,
2291
+ targetNodeId: whId,
2292
+ hasCleanout: false,
2293
+ hasSedimentTrap: false,
2294
+ hasShutoffWithin6Ft: true,
2295
+ isHorizontalSanTee: false,
2296
+ isMainVentStack: false,
2297
+ })
2298
+
2299
+ if (manifoldId) {
2300
+ // Cold Supply Header: Main Service Tee (WH cold side +0.1) -> PEX Manifold Cold Inlet (+0.085)
2301
+ const mainToManifoldCold = routePressurizedPipeRun({
2302
+ from: [whPos[0] + 0.1, 1.55, whPos[2]],
2303
+ to: [manifoldPos[0] + 0.085, manifoldPos[1], manifoldPos[2]],
2304
+ routingPlaneY: 1.69,
2305
+ nominalSize: mainColdSized.size,
2306
+ material: supplyMaterial,
2307
+ euclideanInCavity: false,
2308
+ obstacles,
2309
+ buildingBounds: bounds,
2310
+ maxRoofYAt,
2311
+ cavityContext,
2312
+ })
2313
+ pipeRuns.push({
2314
+ id: nextPipeId(),
2315
+ name: `${mainColdSized.size} Cold Header (Main -> PEX Manifold)`,
2316
+ system: 'cold-water',
2317
+ material: supplyMaterial,
2318
+ nominalSize: mainColdSized.size,
2319
+ path: mainToManifoldCold.path,
2320
+ slopeInPerFt: 0,
2321
+ dfuLoad: 0,
2322
+ wsfuLoad: round2(totalWsfu),
2323
+ gasBtuh: 0,
2324
+ sourceNodeId: waterEntryId ?? whId,
2325
+ targetNodeId: manifoldId,
2326
+ hasCleanout: false,
2327
+ hasSedimentTrap: false,
2328
+ hasShutoffWithin6Ft: true,
2329
+ isHorizontalSanTee: false,
2330
+ isMainVentStack: false,
2331
+ })
2332
+
2333
+ // Hot Supply Header: WH Hot Outlet Nipple (-0.1) -> PEX Manifold Hot Inlet (-0.085)
2334
+ const whToManifoldHot = routePressurizedPipeRun({
2335
+ from: [whPos[0] - 0.1, 1.55, whPos[2]],
2336
+ to: [manifoldPos[0] - 0.085, manifoldPos[1], manifoldPos[2]],
2337
+ routingPlaneY: 1.65,
2338
+ nominalSize: hotMainSized.size,
2339
+ material: supplyMaterial,
2340
+ euclideanInCavity: false,
2341
+ obstacles,
2342
+ buildingBounds: bounds,
2343
+ maxRoofYAt,
2344
+ cavityContext,
2345
+ })
2346
+ pipeRuns.push({
2347
+ id: nextPipeId(),
2348
+ name: `${hotMainSized.size} Hot Header (WH -> PEX Manifold)`,
2349
+ system: 'hot-water',
2350
+ material: supplyMaterial,
2351
+ nominalSize: hotMainSized.size,
2352
+ path: whToManifoldHot.path,
2353
+ slopeInPerFt: 0,
2354
+ dfuLoad: 0,
2355
+ wsfuLoad: totalHotWsfu,
2356
+ gasBtuh: 0,
2357
+ sourceNodeId: whId,
2358
+ targetNodeId: manifoldId,
2359
+ hasCleanout: false,
2360
+ hasSedimentTrap: false,
2361
+ hasShutoffWithin6Ft: true,
2362
+ isHorizontalSanTee: false,
2363
+ isMainVentStack: false,
2364
+ })
2365
+ }
2366
+ } else {
2367
+ // Upper story served by lower-level water heater: tie into vertical interior Cold & Hot supply risers
2368
+ // strictly inside the building footprint at the upper-story manifold / wet core.
2369
+ const riserAnchorX = manifoldId ? manifoldPos[0] : whPos[0]
2370
+ const riserAnchorZ = manifoldId ? manifoldPos[2] : whPos[2]
2371
+ const riserTopY = manifoldId ? manifoldPos[1] : 1.45
2372
+ const [coldRiserX, coldRiserZ] = clampToBoundsXZ(riserAnchorX + 0.08, riserAnchorZ, 0.15)
2373
+ coldTrunkOrigin = [coldRiserX, riserTopY, coldRiserZ]
2374
+ const coldRiserRoute = routePressurizedPipeRun({
2375
+ from: [coldRiserX, supplyPlaneY, coldRiserZ],
2376
+ to: [coldRiserX, riserTopY, coldRiserZ],
2377
+ routingPlaneY: supplyPlaneY,
2378
+ nominalSize: mainColdSized.size,
2379
+ material: supplyMaterial,
2380
+ euclideanInCavity: false,
2381
+ obstacles,
2382
+ buildingBounds: bounds,
2383
+ maxRoofYAt,
2384
+ cavityContext,
2385
+ })
2386
+ coldRiserId = nextPipeId()
2387
+ pipeRuns.push({
2388
+ id: coldRiserId,
2389
+ name: `${mainColdSized.size} Upper-Story Cold Supply Riser`,
2390
+ system: 'cold-water',
2391
+ material: supplyMaterial,
2392
+ nominalSize: mainColdSized.size,
2393
+ path: coldRiserRoute.path,
2394
+ slopeInPerFt: 0,
2395
+ dfuLoad: 0,
2396
+ wsfuLoad: round2(totalWsfu),
2397
+ gasBtuh: 0,
2398
+ targetNodeId: manifoldId,
2399
+ hasCleanout: false,
2400
+ hasSedimentTrap: false,
2401
+ hasShutoffWithin6Ft: true,
2402
+ isHorizontalSanTee: false,
2403
+ isMainVentStack: false,
2404
+ })
2405
+
2406
+ if (totalHotWsfu > 0) {
2407
+ const [hotRiserX, hotRiserZ] = clampToBoundsXZ(riserAnchorX - 0.08, riserAnchorZ, 0.15)
2408
+ hotTrunkOrigin = [hotRiserX, riserTopY, hotRiserZ]
2409
+ const hotRiserRoute = routePressurizedPipeRun({
2410
+ from: [hotRiserX, supplyPlaneY + 0.04, hotRiserZ],
2411
+ to: [hotRiserX, riserTopY, hotRiserZ],
2412
+ routingPlaneY: supplyPlaneY + 0.04,
2413
+ nominalSize: hotMainSized.size,
2414
+ material: supplyMaterial,
2415
+ euclideanInCavity: false,
2416
+ obstacles,
2417
+ buildingBounds: bounds,
2418
+ maxRoofYAt,
2419
+ cavityContext,
2420
+ })
2421
+ hotRiserId = nextPipeId()
2422
+ pipeRuns.push({
2423
+ id: hotRiserId,
2424
+ name: `${hotMainSized.size} Upper-Story Hot Supply Riser`,
2425
+ system: 'hot-water',
2426
+ material: supplyMaterial,
2427
+ nominalSize: hotMainSized.size,
2428
+ path: hotRiserRoute.path,
2429
+ slopeInPerFt: 0,
2430
+ dfuLoad: 0,
2431
+ wsfuLoad: totalHotWsfu,
2432
+ gasBtuh: 0,
2433
+ targetNodeId: manifoldId,
2434
+ hasCleanout: false,
2435
+ hasSedimentTrap: false,
2436
+ hasShutoffWithin6Ft: true,
2437
+ isHorizontalSanTee: false,
2438
+ isMainVentStack: false,
2439
+ })
2440
+ }
2441
+ }
2442
+
2443
+ // Trunk-and-branch spine routing: build a sized 3/4"/1" main Cold Trunk and Hot Trunk along the wet-room corridor,
2444
+ // then tap short 1/2" branches from the nearest trunk point to each fixture!
2445
+ let coldTrunkId: string | undefined
2446
+ let hotTrunkId: string | undefined
2447
+ let coldTrunkSpine: Vec3[] = []
2448
+ let hotTrunkSpine: Vec3[] = []
2449
+
2450
+ const nearestPointOnSpine = (spine: ReadonlyArray<Vec3>, x: number, z: number, fallbackY: number): Vec3 => {
2451
+ let bestPt: Vec3 = spine[0] ?? [x, fallbackY, z]
2452
+ let bestDist = Infinity
2453
+ for (let i = 1; i < spine.length; i++) {
2454
+ const a = spine[i - 1]!
2455
+ const b = spine[i]!
2456
+ const dx = b[0] - a[0]
2457
+ const dz = b[2] - a[2]
2458
+ const lenSq = dx * dx + dz * dz
2459
+ if (lenSq < 1e-4) continue
2460
+ const t = Math.max(0, Math.min(1, ((x - a[0]) * dx + (z - a[2]) * dz) / lenSq))
2461
+ const px = a[0] + dx * t
2462
+ const py = a[1] + (b[1] - a[1]) * t
2463
+ const pz = a[2] + dz * t
2464
+ const d = Math.hypot(x - px, z - pz)
2465
+ if (d < bestDist) {
2466
+ bestDist = d
2467
+ bestPt = [round2(px), round2(py), round2(pz)]
2468
+ }
2469
+ }
2470
+ return bestPt
2471
+ }
2472
+
2473
+ if (supplyTopology === 'trunk-and-branch' && fixtures.length > 0) {
2474
+ const supplyFixtures = fixtures.filter((f) => f.supplySize !== null)
2475
+ if (supplyFixtures.length > 0) {
2476
+ const furthestFix = supplyFixtures.reduce((far, f) => {
2477
+ const dFar = Math.hypot(far.position[0] - whPos[0], far.position[2] - whPos[2])
2478
+ const dCur = Math.hypot(f.position[0] - whPos[0], f.position[2] - whPos[2])
2479
+ return dCur > dFar ? f : far
2480
+ }, supplyFixtures[0]!)
2481
+ const spineEndX = round2(furthestFix.position[0])
2482
+ const spineEndZ = round2(furthestFix.position[2])
2483
+
2484
+ const coldTrunkRoute = routePressurizedPipeRun({
2485
+ from: coldTrunkOrigin,
2486
+ to: [spineEndX, supplyPlaneY, spineEndZ],
2487
+ routingPlaneY: supplyPlaneY,
2488
+ nominalSize: mainColdSized.size,
2489
+ material: supplyMaterial,
2490
+ euclideanInCavity: false,
2491
+ obstacles,
2492
+ buildingBounds: bounds,
2493
+ maxRoofYAt,
2494
+ cavityContext,
2495
+ })
2496
+ coldTrunkId = nextPipeId()
2497
+ coldTrunkSpine = coldTrunkRoute.path
2498
+ pipeRuns.push({
2499
+ id: coldTrunkId,
2500
+ name: `${mainColdSized.size} Main Cold Distribution Trunk`,
2501
+ system: 'cold-water',
2502
+ material: supplyMaterial,
2503
+ nominalSize: mainColdSized.size,
2504
+ path: coldTrunkRoute.path,
2505
+ slopeInPerFt: 0,
2506
+ dfuLoad: 0,
2507
+ wsfuLoad: round2(totalWsfu),
2508
+ gasBtuh: 0,
2509
+ sourceNodeId: waterEntryId ?? coldRiserId ?? whId,
2510
+ hasCleanout: false,
2511
+ hasSedimentTrap: false,
2512
+ hasShutoffWithin6Ft: true,
2513
+ isHorizontalSanTee: false,
2514
+ isMainVentStack: false,
2515
+ })
2516
+
2517
+ if (totalHotWsfu > 0) {
2518
+ const hotTrunkRoute = routePressurizedPipeRun({
2519
+ from: hotTrunkOrigin,
2520
+ to: [spineEndX, supplyPlaneY + 0.04, spineEndZ],
2521
+ routingPlaneY: supplyPlaneY + 0.04,
2522
+ nominalSize: hotMainSized.size,
2523
+ material: supplyMaterial,
2524
+ euclideanInCavity: false,
2525
+ obstacles,
2526
+ buildingBounds: bounds,
2527
+ maxRoofYAt,
2528
+ cavityContext,
2529
+ })
2530
+ hotTrunkId = nextPipeId()
2531
+ hotTrunkSpine = hotTrunkRoute.path
2532
+ pipeRuns.push({
2533
+ id: hotTrunkId,
2534
+ name: `${hotMainSized.size} Main Hot Distribution Trunk`,
2535
+ system: 'hot-water',
2536
+ material: supplyMaterial,
2537
+ nominalSize: hotMainSized.size,
2538
+ path: hotTrunkRoute.path,
2539
+ slopeInPerFt: 0,
2540
+ dfuLoad: 0,
2541
+ wsfuLoad: totalHotWsfu,
2542
+ gasBtuh: 0,
2543
+ sourceNodeId: whId ?? hotRiserId,
2544
+ hasCleanout: false,
2545
+ hasSedimentTrap: false,
2546
+ hasShutoffWithin6Ft: true,
2547
+ isHorizontalSanTee: false,
2548
+ isMainVentStack: false,
2549
+ })
2550
+ }
2551
+ }
2552
+ }
2553
+
2554
+ // 6. Place Main 3"/4" Vent Stack near Wet-Fixture Centroid & Route Gravity DWV + Re-Vents + Supply
2555
+ const drainFixtures = fixtures.filter((f) => f.drainSize !== null)
2556
+ const stackX =
2557
+ drainFixtures.length > 0
2558
+ ? round2(drainFixtures.reduce((s, f) => s + f.position[0], 0) / drainFixtures.length)
2559
+ : round2(bounds.cx)
2560
+ const stackZ =
2561
+ drainFixtures.length > 0
2562
+ ? round2(drainFixtures.reduce((s, f) => s + f.position[2], 0) / drainFixtures.length)
2563
+ : round2(bounds.cz)
2564
+
2565
+ const buildingDrainSizing = sizeBuildingDrain({
2566
+ totalDfu,
2567
+ slopeInPerFt: 0.25,
2568
+ hasWaterCloset: wcCount > 0,
2569
+ waterClosetCount: wcCount,
2570
+ codeEdition,
2571
+ })
2572
+ const mainVentSizing = sizeVentStack({ totalDfu, isMainStack: true })
2573
+ const stackPipeRadiusM = getPipeOuterDiameterM(mainVentSizing.recommendedSize, dwvMaterial) / 2
2574
+
2575
+ const canWallFitPipe = (wall: WallSegment2D, pipeSize: PipeNominalSize, pos: Vec3): boolean => {
2576
+ const nominalIn = PIPE_NOMINAL_INCHES[pipeSize] ?? 2
2577
+ const wallRule = bones?.wallRules.get(wall.id)
2578
+ const effectiveThicknessM = resolveEffectiveWallThicknessM(wall.thicknessM, bones, wallRule)
2579
+ const decl = evaluatePlacementCandidate(
2580
+ [wetWallFitRule],
2581
+ {
2582
+ kind: 'plumbing:pipe-run',
2583
+ system: 'dwv-drain',
2584
+ pos,
2585
+ nominalSizeIn: nominalIn,
2586
+ wallThicknessM: effectiveThicknessM,
2587
+ },
2588
+ 'placement',
2589
+ )
2590
+ if (!decl.legal) return false
2591
+ return checkWetWallPipeFit({
2592
+ wallThicknessM: effectiveThicknessM,
2593
+ pipeSize,
2594
+ material: dwvMaterial,
2595
+ isLoadBearing: wallRule?.isLoadBearing ?? false,
2596
+ }).fits
2597
+ }
2598
+
2599
+ // Prefer a 2x6 wet wall satisfying `irc-r602-6-wet-wall-fit` for the 3"/4" Main DWV Soil & Vent Stack,
2600
+ // and guard the vertical stack centerline strictly against ALL NEC 110.26(E) electrical panel dedicated
2601
+ // spaces, structural beams/headers/columns, and Pascal door/window openings (IRC R502.8 / R602).
2602
+ const wetCapableWalls = walls.filter((w) =>
2603
+ canWallFitPipe(w, mainVentSizing.recommendedSize, [stackX, 1.0, stackZ]),
2604
+ )
2605
+ const stackWallPool = wetCapableWalls.length > 0 ? wetCapableWalls : walls
2606
+ const stackNearWall = nearestWallToPoint(stackX, stackZ, stackWallPool)
2607
+ let stackPt: readonly [number, number] = stackNearWall
2608
+ ? [round2(stackNearWall.point[0]), round2(stackNearWall.point[1])]
2609
+ : [stackX, stackZ]
2610
+ let stackWallId: string | undefined = stackNearWall?.wall.id
2611
+
2612
+ const electricalDedicatedSpaces = obstacles.filter((o) => o.category === 'electrical-dedicated-space')
2613
+ const hitsElectricalDedicatedSpace = (cx: number, cz: number): boolean => {
2614
+ if (electricalDedicatedSpaces.length === 0) return false
2615
+ const necPad = stackPipeRadiusM + 0.06
2616
+ for (const panelSpace of electricalDedicatedSpaces) {
2617
+ if (
2618
+ cx >= panelSpace.box.minX - necPad &&
2619
+ cx <= panelSpace.box.maxX + necPad &&
2620
+ cz >= panelSpace.box.minZ - necPad &&
2621
+ cz <= panelSpace.box.maxZ + necPad
2622
+ ) {
2623
+ return true
2624
+ }
2625
+ }
2626
+ return false
2627
+ }
2628
+
2629
+ const isStackPointClear = (cx: number, cz: number, wall: WallSegment2D | null, alongM: number, pad: number): boolean => {
2630
+ if (hitsElectricalDedicatedSpace(cx, cz)) return false
2631
+ if (hitsAnyObstacleXZ(cx, cz, pad)) return false
2632
+ if (wall && hitsWallOpening(wall.id, alongM, pad, false)) return false
2633
+ if (hitsAnyWallOpeningXZ(cx, cz, Math.min(0.24, pad), false)) return false
2634
+ return true
2635
+ }
2636
+
2637
+ const initialAlong = stackNearWall ? stackNearWall.wall.lengthM * stackNearWall.t : 0
2638
+ if (!isStackPointClear(stackPt[0], stackPt[1], stackNearWall?.wall ?? null, initialAlong, 0.28)) {
2639
+ let cleared = false
2640
+ const fallbackWalls =
2641
+ wetCapableWalls.length > 0 && wetCapableWalls.length < walls.length
2642
+ ? [...wetCapableWalls, ...walls.filter((w) => !wetCapableWalls.includes(w))]
2643
+ : stackWallPool
2644
+ const orderedWalls = fallbackWalls
2645
+ .map((w) => {
2646
+ const proj = nearestWallToPoint(stackX, stackZ, [w])!
2647
+ const isWetCapable = wetCapableWalls.includes(w) ? 0 : 1
2648
+ return { wall: w, t: proj.t, dist: proj.distanceM, isWetCapable }
2649
+ })
2650
+ .sort((a, b) => a.isWetCapable - b.isWetCapable || a.dist - b.dist)
2651
+
2652
+ // Pass 0 (Layer 2 Legal Cavity Piers): prefer a solid king-stud riser pier on a wet wall clear of
2653
+ // openings, structural beams, and NEC 110.26(E) electrical panel dedicated spaces.
2654
+ if (legalCavityGraph) {
2655
+ const pierCandidates: Array<{
2656
+ wall: WallSegment2D
2657
+ x: number
2658
+ z: number
2659
+ t: number
2660
+ dist: number
2661
+ isWetCapable: number
2662
+ }> = []
2663
+ for (const entry of orderedWalls) {
2664
+ const piers = legalCavityGraph.wallRiserPiers.get(entry.wall.id)
2665
+ if (!piers || piers.length === 0) continue
2666
+ for (const pier of piers) {
2667
+ pierCandidates.push({
2668
+ wall: entry.wall,
2669
+ x: round2(pier.x),
2670
+ z: round2(pier.z),
2671
+ t: pier.t,
2672
+ dist: Math.hypot(pier.x - stackX, pier.z - stackZ),
2673
+ isWetCapable: entry.isWetCapable,
2674
+ })
2675
+ }
2676
+ }
2677
+ pierCandidates.sort((a, b) => a.isWetCapable - b.isWetCapable || a.dist - b.dist)
2678
+ for (const pier of pierCandidates) {
2679
+ if (isStackPointClear(pier.x, pier.z, pier.wall, pier.t, 0.24)) {
2680
+ stackPt = [pier.x, pier.z]
2681
+ stackWallId = pier.wall.id
2682
+ cleared = true
2683
+ break
2684
+ }
2685
+ }
2686
+ }
2687
+
2688
+ // Pass 1: >= 0.28 m stud-bay clearance from headers/beams/openings/panels; Pass 2: tighter >= 0.15 m clearance
2689
+ for (const pad of [0.28, 0.15]) {
2690
+ if (cleared) break
2691
+ for (const cand of orderedWalls) {
2692
+ const w = cand.wall
2693
+ if (w.lengthM < 0.45) continue
2694
+ const edgeMargin = Math.min(0.24, w.lengthM * 0.2)
2695
+ const baseAlong = Math.max(edgeMargin, Math.min(w.lengthM - edgeMargin, w.lengthM * cand.t))
2696
+ const maxSteps = Math.ceil(w.lengthM / 0.2)
2697
+ for (let step = 0; step <= maxSteps; step++) {
2698
+ const dirs = step === 0 ? ([0] as const) : ([1, -1] as const)
2699
+ for (const dir of dirs) {
2700
+ const along = baseAlong + dir * step * 0.2
2701
+ if (along < edgeMargin || along > w.lengthM - edgeMargin) continue
2702
+ const cx = round2(w.start[0] + w.ux * along)
2703
+ const cz = round2(w.start[1] + w.uz * along)
2704
+ if (isStackPointClear(cx, cz, w, along, pad)) {
2705
+ stackPt = [cx, cz]
2706
+ stackWallId = w.id
2707
+ cleared = true
2708
+ break
2709
+ }
2710
+ }
2711
+ if (cleared) break
2712
+ }
2713
+ if (cleared) break
2714
+ }
2715
+ }
2716
+
2717
+ // Fallback: if every wall on the level is blocked by openings/beams/panels, place an interior pipe chase
2718
+ // clear of ALL structural beams, headers, columns, openings, and NEC 110.26(E) dedicated spaces.
2719
+ if (!cleared) {
2720
+ const [bx, bz] = stackPt
2721
+ for (const pad of [0.28, 0.14]) {
2722
+ for (const r of [0.35, 0.65, 0.95, 1.35, 1.8, 2.4, 3.2]) {
2723
+ const offsets: ReadonlyArray<readonly [number, number]> = [
2724
+ [r, 0],
2725
+ [-r, 0],
2726
+ [0, r],
2727
+ [0, -r],
2728
+ [r, r],
2729
+ [r, -r],
2730
+ [-r, r],
2731
+ [-r, -r],
2732
+ ]
2733
+ for (const [dx, dz] of offsets) {
2734
+ const cx = round2(bx + dx)
2735
+ const cz = round2(bz + dz)
2736
+ if (cx < bounds.minX + 0.15 || cx > bounds.maxX - 0.15 || cz < bounds.minZ + 0.15 || cz > bounds.maxZ - 0.15) {
2737
+ continue
2738
+ }
2739
+ if (isStackPointClear(cx, cz, null, 0, pad)) {
2740
+ stackPt = [cx, cz]
2741
+ stackWallId = undefined
2742
+ cleared = true
2743
+ break
2744
+ }
2745
+ }
2746
+ if (cleared) break
2747
+ }
2748
+ if (cleared) break
2749
+ }
2750
+ if (!cleared) {
2751
+ const nudged = nudgeOffFloorGirder(stackPt[0], stackPt[1], 0.35, mechNudgeShifts)
2752
+ stackPt = clampToBoundsXZ(nudged[0], nudged[1], 0.15)
2753
+ stackWallId = undefined
2754
+ }
2755
+ }
2756
+ }
2757
+
2758
+ // Enforce `irc-r602-6-wet-wall-fit` on stack wall tag: never falsely tag a 3"/4" stack inside a 2x4 wall cavity
2759
+ if (stackWallId) {
2760
+ const chosenStackWall = wallById.get(stackWallId)
2761
+ if (
2762
+ chosenStackWall &&
2763
+ !canWallFitPipe(chosenStackWall, mainVentSizing.recommendedSize, [stackPt[0], 1.0, stackPt[1]])
2764
+ ) {
2765
+ stackWallId = undefined
2766
+ }
2767
+ }
2768
+
2769
+ // Allocate stack ID first, route fixture branches to find lowest arrival invert
2770
+ // so the Main Building Drain ALWAYS starts at or below every arriving branch drain invert!
2771
+ const defaultStackBaseY = foundationType === 'slab' ? -0.45 : -0.34
2772
+ const stackId = nextPipeId()
2773
+ const mainDrainId = isGroundStory ? nextPipeId() : undefined
2774
+
2775
+ // Route every fixture's DWV branch, Re-Vent, Cold Supply, and Hot Supply
2776
+ const supplySourcePos: Vec3 = manifoldId ? manifoldPos : [whPos[0], 1.45, whPos[2]]
2777
+ const coldSupplySourceId = manifoldId ?? whId ?? coldRiserId
2778
+ const hotSupplySourceId = manifoldId ?? whId ?? hotRiserId
2779
+ let furthestHotFixture: PlannedFixtureSpec | null = null
2780
+ let maxHotDist = 0
2781
+ let minBranchArrivalY = defaultStackBaseY
2782
+ const branchPipeRuns: PlannedPipeRunSpec[] = []
2783
+
2784
+ for (const fix of fixtures) {
2785
+ const spec = FIXTURE_SPECS[fix.fixtureKind]
2786
+
2787
+ // DWV Drain & Re-Vent
2788
+ if (fix.drainSize) {
2789
+ const branchSizing = sizeDrainBranch({
2790
+ dfu: fix.dfu,
2791
+ hasWaterCloset: fix.fixtureKind === 'water-closet',
2792
+ minUpstreamSize: fix.drainSize,
2793
+ codeEdition,
2794
+ })
2795
+ const branchStartY = foundationType === 'slab' ? -0.35 : -0.24
2796
+ const dwvRoute = routeDwvDrainRun({
2797
+ from: fix.position,
2798
+ to: [stackPt[0], branchStartY, stackPt[1]],
2799
+ nominalSize: branchSizing.recommendedSize,
2800
+ material: dwvMaterial,
2801
+ foundationType,
2802
+ slopeInPerFt: 0.25,
2803
+ obstacles,
2804
+ buildingBounds: bounds,
2805
+ cavityContext,
2806
+ })
2807
+ const arrivalY = dwvRoute.path[dwvRoute.path.length - 1]?.[1]
2808
+ if (typeof arrivalY === 'number' && arrivalY < minBranchArrivalY) {
2809
+ minBranchArrivalY = arrivalY
2810
+ }
2811
+ const trapArmFt = fix.ventSize ? 1.5 : dwvRoute.lengthFt
2812
+ // Single-source `irc-r602-6-wet-wall-fit` check: if host wall is <= 0.125 m 2x4 (or too thin for 3" WC branch),
2813
+ // omit `wallId` so the 3" drain routes cleanly as an under-slab/chased vertical drop rather than falsely
2814
+ // tagging inside a 2x4 stud cavity (preventing IRC R602.6 wet-wall audit errors by construction).
2815
+ const hostWallForBranch = fix.wallId ? wallById.get(fix.wallId) : undefined
2816
+ const safeDrainWallId =
2817
+ hostWallForBranch && canWallFitPipe(hostWallForBranch, branchSizing.recommendedSize, fix.position)
2818
+ ? fix.wallId
2819
+ : undefined
2820
+ branchPipeRuns.push({
2821
+ id: nextPipeId(),
2822
+ name: `${branchSizing.recommendedSize} DWV Drain (${fix.name})`,
2823
+ system: 'dwv-drain',
2824
+ material: dwvMaterial,
2825
+ nominalSize: branchSizing.recommendedSize,
2826
+ path: dwvRoute.path,
2827
+ slopeInPerFt: dwvRoute.slopeInPerFt,
2828
+ dfuLoad: fix.dfu,
2829
+ wsfuLoad: 0,
2830
+ gasBtuh: 0,
2831
+ sourceNodeId: fix.id,
2832
+ targetNodeId: stackId,
2833
+ hasCleanout: false,
2834
+ hasSedimentTrap: false,
2835
+ hasShutoffWithin6Ft: false,
2836
+ isHorizontalSanTee: false,
2837
+ isMainVentStack: false,
2838
+ trapArmLengthFt: trapArmFt,
2839
+ ...(safeDrainWallId !== undefined ? { wallId: safeDrainWallId } : {}),
2840
+ })
2841
+
2842
+ if (fix.ventSize) {
2843
+ // Dry re-vent starts at the sanitary tee inside the backing wet-wall cavity (IPC 905.5)
2844
+ // so the vertical vent rises cleanly inside the stud bay instead of out in front of the fixture.
2845
+ const ventOrigin = resolveVentOriginForFixture(fix.position, fix.wallId, wallById, walls, (x, z) =>
2846
+ hitsAnyWallOpeningXZ(x, z, 0.12, false),
2847
+ )
2848
+ const ventRoute = routeVentRun({
2849
+ from: ventOrigin,
2850
+ stackPoint: stackPt,
2851
+ floodRimHeightM: spec.floodRimHeightM,
2852
+ ceilingHeightM: levelH,
2853
+ nominalSize: fix.ventSize,
2854
+ material: dwvMaterial,
2855
+ obstacles,
2856
+ buildingBounds: bounds,
2857
+ maxRoofYAt,
2858
+ cavityContext,
2859
+ })
2860
+ const safeVentWallId =
2861
+ hostWallForBranch && canWallFitPipe(hostWallForBranch, fix.ventSize, fix.position)
2862
+ ? fix.wallId
2863
+ : undefined
2864
+ branchPipeRuns.push({
2865
+ id: nextPipeId(),
2866
+ name: `${fix.ventSize} Re-Vent (${fix.name})`,
2867
+ system: 'dwv-vent',
2868
+ material: dwvMaterial,
2869
+ nominalSize: fix.ventSize,
2870
+ path: ventRoute.path,
2871
+ slopeInPerFt: 0,
2872
+ dfuLoad: fix.dfu,
2873
+ wsfuLoad: 0,
2874
+ gasBtuh: 0,
2875
+ sourceNodeId: fix.id,
2876
+ targetNodeId: stackId,
2877
+ hasCleanout: false,
2878
+ hasSedimentTrap: false,
2879
+ hasShutoffWithin6Ft: false,
2880
+ isHorizontalSanTee: false,
2881
+ isMainVentStack: false,
2882
+ ...(safeVentWallId !== undefined ? { wallId: safeVentWallId } : {}),
2883
+ })
2884
+ }
2885
+ }
2886
+
2887
+ // Cold Water Supply (velocity-checked, rotation-aware stub-out; taps nearest trunk spine point in trunk-and-branch mode)
2888
+ if (fix.supplySize && fix.wsfuCold > 0) {
2889
+ const coldSized = sizeSupplyPipe({
2890
+ wsfu: fix.wsfuCold,
2891
+ material: supplyMaterial,
2892
+ isHot: false,
2893
+ minSize: fix.supplySize,
2894
+ flushType,
2895
+ })
2896
+ const rawColdTarget = getFixtureSupplyPoint(fix, 'cold')
2897
+ const [coldTx, coldTz] =
2898
+ fix.fixtureKind === 'hose-bibb' || walls.length === 0
2899
+ ? [rawColdTarget[0], rawColdTarget[2]]
2900
+ : clampToBoundsXZ(rawColdTarget[0], rawColdTarget[2], 0.08)
2901
+ const coldTarget: Vec3 = [coldTx, rawColdTarget[1], coldTz]
2902
+ const coldOrigin: Vec3 =
2903
+ supplyTopology === 'trunk-and-branch' && coldTrunkSpine.length >= 2
2904
+ ? nearestPointOnSpine(coldTrunkSpine, coldTarget[0], coldTarget[2], supplyPlaneY)
2905
+ : [supplySourcePos[0] + 0.08, supplySourcePos[1], supplySourcePos[2]]
2906
+ const coldRoute = routePressurizedPipeRun({
2907
+ from: coldOrigin,
2908
+ to: coldTarget,
2909
+ routingPlaneY: supplyPlaneY,
2910
+ nominalSize: coldSized.size,
2911
+ material: supplyMaterial,
2912
+ euclideanInCavity: false,
2913
+ obstacles,
2914
+ buildingBounds: bounds,
2915
+ maxRoofYAt,
2916
+ cavityContext,
2917
+ })
2918
+ branchPipeRuns.push({
2919
+ id: nextPipeId(),
2920
+ name: `${coldSized.size} Cold ${supplyTopology === 'trunk-and-branch' ? 'Branch' : 'Supply'} (${fix.name})`,
2921
+ system: 'cold-water',
2922
+ material: supplyMaterial,
2923
+ nominalSize: coldSized.size,
2924
+ path: coldRoute.path,
2925
+ slopeInPerFt: 0,
2926
+ dfuLoad: 0,
2927
+ wsfuLoad: fix.wsfuCold,
2928
+ gasBtuh: 0,
2929
+ sourceNodeId: coldTrunkId ?? coldSupplySourceId,
2930
+ targetNodeId: fix.id,
2931
+ hasCleanout: false,
2932
+ hasSedimentTrap: false,
2933
+ hasShutoffWithin6Ft: true,
2934
+ isHorizontalSanTee: false,
2935
+ isMainVentStack: false,
2936
+ })
2937
+ }
2938
+
2939
+ // Hot Water Supply (velocity-checked, rotation-aware stub-out; taps nearest trunk spine point in trunk-and-branch mode)
2940
+ if (fix.supplySize && fix.wsfuHot > 0) {
2941
+ const hotSized = sizeSupplyPipe({
2942
+ wsfu: fix.wsfuHot,
2943
+ material: supplyMaterial,
2944
+ isHot: true,
2945
+ minSize: fix.supplySize,
2946
+ flushType,
2947
+ })
2948
+ const rawHotTarget = getFixtureSupplyPoint(fix, 'hot')
2949
+ const [hotTx, hotTz] =
2950
+ fix.fixtureKind === 'hose-bibb' || walls.length === 0
2951
+ ? [rawHotTarget[0], rawHotTarget[2]]
2952
+ : clampToBoundsXZ(rawHotTarget[0], rawHotTarget[2], 0.08)
2953
+ const hotTarget: Vec3 = [hotTx, rawHotTarget[1], hotTz]
2954
+ const hotOrigin: Vec3 =
2955
+ supplyTopology === 'trunk-and-branch' && hotTrunkSpine.length >= 2
2956
+ ? nearestPointOnSpine(hotTrunkSpine, hotTarget[0], hotTarget[2], supplyPlaneY + 0.04)
2957
+ : [supplySourcePos[0] - 0.08, supplySourcePos[1], supplySourcePos[2]]
2958
+ const hotRoute = routePressurizedPipeRun({
2959
+ from: hotOrigin,
2960
+ to: hotTarget,
2961
+ routingPlaneY: supplyPlaneY + 0.04,
2962
+ nominalSize: hotSized.size,
2963
+ material: supplyMaterial,
2964
+ euclideanInCavity: false,
2965
+ obstacles,
2966
+ buildingBounds: bounds,
2967
+ maxRoofYAt,
2968
+ cavityContext,
2969
+ })
2970
+ const distFromWh = Math.hypot(fix.position[0] - whPos[0], fix.position[2] - whPos[2])
2971
+ if (distFromWh > maxHotDist) {
2972
+ maxHotDist = distFromWh
2973
+ furthestHotFixture = fix
2974
+ }
2975
+ branchPipeRuns.push({
2976
+ id: nextPipeId(),
2977
+ name: `${hotSized.size} Hot ${supplyTopology === 'trunk-and-branch' ? 'Branch' : 'Supply'} (${fix.name})`,
2978
+ system: 'hot-water',
2979
+ material: supplyMaterial,
2980
+ nominalSize: hotSized.size,
2981
+ path: hotRoute.path,
2982
+ slopeInPerFt: 0,
2983
+ dfuLoad: 0,
2984
+ wsfuLoad: fix.wsfuHot,
2985
+ gasBtuh: 0,
2986
+ sourceNodeId: hotTrunkId ?? hotSupplySourceId,
2987
+ targetNodeId: fix.id,
2988
+ hasCleanout: false,
2989
+ hasSedimentTrap: false,
2990
+ hasShutoffWithin6Ft: true,
2991
+ isHorizontalSanTee: false,
2992
+ isMainVentStack: false,
2993
+ })
2994
+ }
2995
+ }
2996
+
2997
+ // Dedicated 1/2" Cold-Water Ice-Maker Supply Lines for placed French-Door Refrigerators (cold only, no drain)
2998
+ for (const fridge of discoveredIceMakers) {
2999
+ const coldOrigin: Vec3 =
3000
+ supplyTopology === 'trunk-and-branch' && coldTrunkSpine.length >= 2
3001
+ ? nearestPointOnSpine(coldTrunkSpine, fridge.pos[0], fridge.pos[2], supplyPlaneY)
3002
+ : [supplySourcePos[0] + 0.08, supplySourcePos[1], supplySourcePos[2]]
3003
+ const iceRoute = routePressurizedPipeRun({
3004
+ from: coldOrigin,
3005
+ to: fridge.pos,
3006
+ routingPlaneY: supplyPlaneY,
3007
+ nominalSize: '1/2"',
3008
+ material: supplyMaterial,
3009
+ euclideanInCavity: false,
3010
+ obstacles,
3011
+ buildingBounds: bounds,
3012
+ maxRoofYAt,
3013
+ cavityContext,
3014
+ })
3015
+ branchPipeRuns.push({
3016
+ id: nextPipeId(),
3017
+ name: `1/2" Cold Ice-Maker Line (${fridge.name})`,
3018
+ system: 'cold-water',
3019
+ material: supplyMaterial,
3020
+ nominalSize: '1/2"',
3021
+ path: iceRoute.path,
3022
+ slopeInPerFt: 0,
3023
+ dfuLoad: 0,
3024
+ wsfuLoad: fridge.wsfuCold,
3025
+ gasBtuh: 0,
3026
+ sourceNodeId: coldTrunkId ?? coldSupplySourceId,
3027
+ targetNodeId: fridge.sourceId,
3028
+ hasCleanout: false,
3029
+ hasSedimentTrap: false,
3030
+ hasShutoffWithin6Ft: true,
3031
+ isHorizontalSanTee: false,
3032
+ isMainVentStack: false,
3033
+ })
3034
+ }
3035
+
3036
+ // Main 3"/4" Soil/Vent Stack (anchored at or below the lowest branch arrival invert -> through roof)
3037
+ const stackBaseY = Math.floor(Math.min(defaultStackBaseY, minBranchArrivalY) * 10000) / 10000
3038
+ pipeRuns.push({
3039
+ id: stackId,
3040
+ name: isGroundStory
3041
+ ? `${mainVentSizing.recommendedSize} Main DWV Soil & Vent Stack (Through Roof)`
3042
+ : `${mainVentSizing.recommendedSize} DWV Soil & Vent Stack Riser`,
3043
+ system: 'dwv-vent',
3044
+ material: dwvMaterial,
3045
+ nominalSize: mainVentSizing.recommendedSize,
3046
+ path: [
3047
+ [stackPt[0], stackBaseY, stackPt[1]],
3048
+ [stackPt[0], round2(levelH + 0.45), stackPt[1]],
3049
+ ],
3050
+ slopeInPerFt: 0,
3051
+ dfuLoad: round2(totalDfu),
3052
+ wsfuLoad: 0,
3053
+ gasBtuh: 0,
3054
+ hasCleanout: true, // Stack-base cleanout per IPC 708.1
3055
+ hasSedimentTrap: false,
3056
+ hasShutoffWithin6Ft: false,
3057
+ isHorizontalSanTee: false,
3058
+ isMainVentStack: true,
3059
+ wallId: stackWallId,
3060
+ })
3061
+
3062
+ // Main Building Drain (Stack Base -> Sewer Exit, 1/4"/ft slope, with cleanout)
3063
+ // Ground / lowest walled story only: upper stories discharge strictly into the interior vertical soil stack
3064
+ // so no exterior sewer lateral ever juts into mid-air outside upper floors.
3065
+ if (isGroundStory && mainDrainId) {
3066
+ const mainDrainRoute = routeDwvDrainRun({
3067
+ from: [stackPt[0], stackBaseY, stackPt[1]],
3068
+ to: sewerExitPos,
3069
+ nominalSize: buildingDrainSizing.recommendedSize,
3070
+ material: dwvMaterial,
3071
+ foundationType,
3072
+ slopeInPerFt: 0.25,
3073
+ obstacles,
3074
+ })
3075
+ pipeRuns.push({
3076
+ id: mainDrainId,
3077
+ name: `${buildingDrainSizing.recommendedSize} Main Building Drain (${totalDfu} DFU -> Sewer Exit)`,
3078
+ system: 'dwv-drain',
3079
+ material: dwvMaterial,
3080
+ nominalSize: buildingDrainSizing.recommendedSize,
3081
+ path: mainDrainRoute.path,
3082
+ slopeInPerFt: mainDrainRoute.slopeInPerFt,
3083
+ dfuLoad: round2(totalDfu),
3084
+ wsfuLoad: 0,
3085
+ gasBtuh: 0,
3086
+ sourceNodeId: stackId,
3087
+ hasCleanout: true,
3088
+ hasSedimentTrap: false,
3089
+ hasShutoffWithin6Ft: false,
3090
+ isHorizontalSanTee: false,
3091
+ isMainVentStack: false,
3092
+ })
3093
+ }
3094
+ pipeRuns.push(...branchPipeRuns)
3095
+
3096
+ // 7. Optional Hot Water Recirculation Return Loop (for long hot runs > 40 ft or when requested)
3097
+ if (includeHotRecirc && emitWaterHeater && furthestHotFixture) {
3098
+ const recircId = nextEqId()
3099
+ const canPlaceLeft = whPos[0] - 0.35 >= bounds.minX + 0.15
3100
+ // Offset orthogonally from expansion tank (mechDir * 0.35) when left side is blocked
3101
+ const orthoX = mechDirZ !== 0 ? -mechDirZ : 0
3102
+ const orthoZ = mechDirX !== 0 ? mechDirX : 1
3103
+ const rawRecircX = canPlaceLeft ? whPos[0] - 0.35 : whPos[0] + orthoX * 0.35
3104
+ const rawRecircZ = canPlaceLeft ? whPos[2] : whPos[2] + orthoZ * 0.35
3105
+ const [recX, recZ] = clampToBoundsXZ(rawRecircX, rawRecircZ, 0.15)
3106
+ const recircPos: Vec3 = [recX, 1.25, recZ]
3107
+ equipment.push({
3108
+ id: recircId,
3109
+ name: 'Hot Water Recirculation Pump',
3110
+ equipmentKind: 'recirc-pump',
3111
+ position: recircPos,
3112
+ rotation: 0,
3113
+ roomName: mechRoom?.name ?? 'Utility',
3114
+ electricalDemand: getEquipmentElectricalDemand('recirc-pump'),
3115
+ })
3116
+ const recircRoute = routePressurizedPipeRun({
3117
+ from: furthestHotFixture.position,
3118
+ to: recircPos,
3119
+ routingPlaneY: supplyPlaneY + 0.08,
3120
+ nominalSize: '1/2"',
3121
+ material: supplyMaterial,
3122
+ euclideanInCavity: false,
3123
+ obstacles,
3124
+ buildingBounds: bounds,
3125
+ maxRoofYAt,
3126
+ cavityContext,
3127
+ })
3128
+ pipeRuns.push({
3129
+ id: nextPipeId(),
3130
+ name: `1/2" Hot Recirculation Return (${furthestHotFixture.name})`,
3131
+ system: 'hot-recirc',
3132
+ material: supplyMaterial,
3133
+ nominalSize: '1/2"',
3134
+ path: recircRoute.path,
3135
+ slopeInPerFt: 0,
3136
+ dfuLoad: 0,
3137
+ wsfuLoad: 0,
3138
+ gasBtuh: 0,
3139
+ sourceNodeId: furthestHotFixture.id,
3140
+ targetNodeId: recircId,
3141
+ hasCleanout: false,
3142
+ hasSedimentTrap: false,
3143
+ hasShutoffWithin6Ft: true,
3144
+ isHorizontalSanTee: false,
3145
+ isMainVentStack: false,
3146
+ })
3147
+ }
3148
+
3149
+ // 8. Optional IFGC Fuel Gas Distribution (only route to actual gas appliances/furnaces; never into electric/HPWH WH!)
3150
+ const gasTargets: Array<{ id: string; name: string; pos: Vec3; btuh: number }> = [
3151
+ ...(emitWaterHeater && whId && hasGasWaterHeater && whSizing.gasBtuh > 0
3152
+ ? [{ id: whId, name: 'Gas Water Heater', pos: [whPos[0], 0.65, whPos[2]] as Vec3, btuh: whSizing.gasBtuh }]
3153
+ : []),
3154
+ ...sceneGasAppliances,
3155
+ ]
3156
+ if (includeFuelGas && gasTargets.length > 0) {
3157
+ let gasSourcePos: Vec3 = [whPos[0], supplyPlaneY - 0.06, whPos[2]]
3158
+ let gasSourceId: string | undefined
3159
+ if (isGroundStory) {
3160
+ const rawGasMeterZ = whPos[2] + 0.8 <= westMaxZ ? whPos[2] + 0.8 : whPos[2] - 0.8
3161
+ const gasMeterZ = clampWestZ(rawGasMeterZ)
3162
+ gasSourcePos = [round2((westOuterWall ? westOuterWall.x : bounds.minX) - 0.15), 0.9, gasMeterZ]
3163
+ gasSourceId = nextEqId()
3164
+ const totalGasBtuh = gasTargets.reduce((sum, t) => sum + t.btuh, 0)
3165
+ equipment.push({
3166
+ id: gasSourceId,
3167
+ name: `Natural Gas Meter (${Math.round(totalGasBtuh / 1000)} kBTU/hr)`,
3168
+ equipmentKind: 'gas-meter',
3169
+ position: gasSourcePos,
3170
+ rotation: 0,
3171
+ roomName: 'Exterior',
3172
+ gasBtuh: 0, // Supply meter, not an appliance load (prevents double-counting appliance BTU/hr)
3173
+ electricalDemand: null,
3174
+ })
3175
+ }
3176
+ for (const target of gasTargets) {
3177
+ const prelimGasSizing = sizeFuelGasPipe({
3178
+ totalBtuh: target.btuh,
3179
+ longestRunFt: 40,
3180
+ material: 'black-iron',
3181
+ })
3182
+ let gasRoute = routePressurizedPipeRun({
3183
+ from: gasSourcePos,
3184
+ to: target.pos,
3185
+ routingPlaneY: supplyPlaneY - 0.06,
3186
+ nominalSize: prelimGasSizing.recommendedSize,
3187
+ material: 'black-iron',
3188
+ euclideanInCavity: false,
3189
+ obstacles,
3190
+ buildingBounds: bounds,
3191
+ maxRoofYAt,
3192
+ cavityContext,
3193
+ })
3194
+ const gasSizing = sizeFuelGasPipe({
3195
+ totalBtuh: target.btuh,
3196
+ longestRunFt: Math.max(IPC_RULE_THRESHOLDS.fuelGasMinSizingLengthPlacementFt, gasRoute.lengthFt),
3197
+ material: 'black-iron',
3198
+ })
3199
+ if (gasSizing.recommendedSize !== prelimGasSizing.recommendedSize) {
3200
+ gasRoute = routePressurizedPipeRun({
3201
+ from: gasSourcePos,
3202
+ to: target.pos,
3203
+ routingPlaneY: supplyPlaneY - 0.06,
3204
+ nominalSize: gasSizing.recommendedSize,
3205
+ material: 'black-iron',
3206
+ euclideanInCavity: false,
3207
+ obstacles,
3208
+ buildingBounds: bounds,
3209
+ maxRoofYAt,
3210
+ cavityContext,
3211
+ })
3212
+ }
3213
+ pipeRuns.push({
3214
+ id: nextPipeId(),
3215
+ name: `${gasSizing.recommendedSize} Fuel Gas Line (${target.name}, ${Math.round(target.btuh / 1000)} kBTU/hr, IFGC 402.4)`,
3216
+ system: 'fuel-gas',
3217
+ material: 'black-iron',
3218
+ nominalSize: gasSizing.recommendedSize,
3219
+ path: gasRoute.path,
3220
+ slopeInPerFt: 0,
3221
+ dfuLoad: 0,
3222
+ wsfuLoad: 0,
3223
+ gasBtuh: target.btuh,
3224
+ sourceNodeId: gasSourceId,
3225
+ targetNodeId: target.id,
3226
+ hasCleanout: false,
3227
+ hasSedimentTrap: true,
3228
+ hasShutoffWithin6Ft: true,
3229
+ isHorizontalSanTee: false,
3230
+ isMainVentStack: false,
3231
+ })
3232
+ }
3233
+ }
3234
+
3235
+ // 9. Optional IRC M1502.4 Rigid 4" Dryer Vent for placed Clothes Dryer (preferred) or Clothes Washer / Laundry
3236
+ // Evaluates candidate exterior wall exits against `irc-m1502-4-dryer-vent` (<= 35 ft effective length,
3237
+ // smooth rigid-aluminum), preferring a clash-free exterior wall exit that satisfies the declarative rule.
3238
+ if (includeDryerVent) {
3239
+ const dryerAnchor = discoveredDryers[0]
3240
+ const washer = fixtures.find((f) => f.fixtureKind === 'clothes-washer')
3241
+ const dryerSourceId = dryerAnchor?.sourceId ?? washer?.id
3242
+ const dryerPos = dryerAnchor?.pos ?? (washer ? ([washer.position[0], 0.35, washer.position[2]] as Vec3) : null)
3243
+ if (dryerSourceId && dryerPos) {
3244
+ const dryerOrigin: Vec3 = [dryerPos[0], 0.35, dryerPos[2]]
3245
+ const dryerMaterial: PipeMaterial =
3246
+ (IPC_RULE_THRESHOLDS.dryerVentRequiredMaterials[0] as PipeMaterial | undefined) ?? 'rigid-aluminum'
3247
+ const exitCandidates: Array<{ distM: number; exitPt: Vec3 }> = (
3248
+ [
3249
+ { distM: Math.abs(dryerOrigin[0] - bounds.minX), exitPt: [round2(bounds.minX - 0.08), 0.35, dryerOrigin[2]] as Vec3 },
3250
+ { distM: Math.abs(bounds.maxX - dryerOrigin[0]), exitPt: [round2(bounds.maxX + 0.08), 0.35, dryerOrigin[2]] as Vec3 },
3251
+ { distM: Math.abs(bounds.maxZ - dryerOrigin[2]), exitPt: [dryerOrigin[0], 0.35, round2(bounds.maxZ + 0.08)] as Vec3 },
3252
+ { distM: Math.abs(dryerOrigin[2] - bounds.minZ), exitPt: [dryerOrigin[0], 0.35, round2(bounds.minZ - 0.08)] as Vec3 },
3253
+ ] satisfies Array<{ distM: number; exitPt: Vec3 }>
3254
+ ).sort((a, b) => a.distM - b.distM)
3255
+
3256
+ let bestDryerRoute: {
3257
+ path: Vec3[]
3258
+ clashes: number
3259
+ legal: boolean
3260
+ effectiveLengthFt: number
3261
+ } | null = null
3262
+
3263
+ for (const cand of exitCandidates) {
3264
+ const route = routePressurizedPipeRun({
3265
+ from: dryerOrigin,
3266
+ to: cand.exitPt,
3267
+ routingPlaneY: 0.35,
3268
+ nominalSize: '4"',
3269
+ material: dryerMaterial,
3270
+ euclideanInCavity: false,
3271
+ obstacles,
3272
+ buildingBounds: bounds,
3273
+ maxRoofYAt,
3274
+ cavityContext,
3275
+ allowedBands: ['under-sill', 'mid-wall', 'overhead-plenum'],
3276
+ })
3277
+ const { elbows90, elbows45 } = countPathElbows(route.path)
3278
+ const check = checkDryerVentRun({ lengthFt: route.lengthFt, elbows90, elbows45 })
3279
+ const declEval = evaluatePlacementCandidate(
3280
+ [dryerVentRule, dryerVentMaterialRule],
3281
+ {
3282
+ id: dryerSourceId,
3283
+ kind: 'plumbing:pipe-run',
3284
+ system: 'dryer-vent',
3285
+ material: dryerMaterial,
3286
+ pos: cand.exitPt,
3287
+ effectiveLengthFt: check.effectiveLengthFt,
3288
+ },
3289
+ 'placement',
3290
+ )
3291
+ const scored = {
3292
+ path: route.path,
3293
+ clashes: route.clashes.length,
3294
+ legal: declEval.legal,
3295
+ effectiveLengthFt: check.effectiveLengthFt,
3296
+ }
3297
+ if (
3298
+ !bestDryerRoute ||
3299
+ (scored.legal && !bestDryerRoute.legal) ||
3300
+ (scored.legal === bestDryerRoute.legal && scored.clashes < bestDryerRoute.clashes) ||
3301
+ (scored.legal === bestDryerRoute.legal &&
3302
+ scored.clashes === bestDryerRoute.clashes &&
3303
+ scored.effectiveLengthFt < bestDryerRoute.effectiveLengthFt)
3304
+ ) {
3305
+ bestDryerRoute = scored
3306
+ }
3307
+ if (scored.legal && scored.clashes === 0 && cand.distM === exitCandidates[0]!.distM) {
3308
+ break
3309
+ }
3310
+ }
3311
+
3312
+ if (bestDryerRoute) {
3313
+ const dryerLabel = dryerAnchor
3314
+ ? dryerAnchor.sku
3315
+ ? `${dryerAnchor.name} [${dryerAnchor.sku}]`
3316
+ : dryerAnchor.name
3317
+ : ''
3318
+ pipeRuns.push({
3319
+ id: nextPipeId(),
3320
+ name: dryerLabel
3321
+ ? `4" Rigid Aluminum Dryer Vent (${dryerLabel}, IRC M1502.4)`
3322
+ : '4" Rigid Aluminum Dryer Vent (IRC M1502.4)',
3323
+ system: 'dryer-vent',
3324
+ material: dryerMaterial,
3325
+ nominalSize: '4"',
3326
+ path: bestDryerRoute.path,
3327
+ slopeInPerFt: 0,
3328
+ dfuLoad: 0,
3329
+ wsfuLoad: 0,
3330
+ gasBtuh: 0,
3331
+ sourceNodeId: dryerSourceId,
3332
+ hasCleanout: false,
3333
+ hasSedimentTrap: false,
3334
+ hasShutoffWithin6Ft: false,
3335
+ isHorizontalSanTee: false,
3336
+ isMainVentStack: false,
3337
+ })
3338
+ }
3339
+ }
3340
+ }
3341
+
3342
+ const poweredCount =
3343
+ equipment.filter((e) => e.electricalDemand?.required).length +
3344
+ fixtures.filter((f) => f.electricalDemand?.required).length
3345
+
3346
+ return {
3347
+ levelId,
3348
+ codeEdition,
3349
+ supplyTopology,
3350
+ foundationType,
3351
+ equipment,
3352
+ manifolds,
3353
+ fixtures,
3354
+ pipeRuns,
3355
+ bonesAnchorsUsed,
3356
+ summary: `Auto-populated ${fixtures.length} plumbing fixtures (${round2(totalDfu)} DFU / ${round2(totalWsfu)} WSFU), ${equipment.length} equipment unit(s), ${manifolds.length} manifold(s), and ${pipeRuns.length} 3D pipe runs (${poweredCount} powered load(s) tagged for Electrical coordination).`,
3357
+ }
3358
+ }
3359
+
3360
+ export type SingleFixtureConnectResult = {
3361
+ pipeRuns: PlannedPipeRunSpec[]
3362
+ connectedSystems: PlumbingSystem[]
3363
+ hasSupplySource: boolean
3364
+ hasDwvStack: boolean
3365
+ }
3366
+
3367
+ type ResolvedSupplySource = {
3368
+ id: string
3369
+ pos: Vec3
3370
+ isManifold: boolean
3371
+ spine?: ReadonlyArray<Vec3>
3372
+ }
3373
+
3374
+ type PrecompiledLevelRoutingContext = {
3375
+ levelId: string | null
3376
+ occupancy: OccupancyType
3377
+ supplyMaterial: 'pex-a' | 'pex-b' | 'copper-l' | 'cpvc'
3378
+ dwvMaterial: 'pvc-dwv' | 'abs-dwv' | 'cast-iron'
3379
+ foundationType: FoundationType
3380
+ supplyPlaneY: number
3381
+ subFloorElevationM: number
3382
+ levelPipes: SceneNodeLike[]
3383
+ walls: WallSegment2D[]
3384
+ wallById: Map<string, WallSegment2D>
3385
+ rooms: RoomPolygon2D[]
3386
+ indoorRooms: RoomPolygon2D[]
3387
+ bounds: ReturnType<typeof sceneBounds>
3388
+ levelH: number
3389
+ obstacles: ReturnType<typeof mapOccupancyObstaclesToPlumbing>
3390
+ cavityContext: PlumbingCavityContext
3391
+ maxRoofYAt: (x: number, z: number) => number
3392
+ bones: ReturnType<typeof extractBonesPlumbingContext>
3393
+ wetWallFitRule: ReturnType<typeof getIpcRuleById>
3394
+ dryerVentRule: ReturnType<typeof getIpcRuleById>
3395
+ dryerVentMaterialRule: ReturnType<typeof getIpcRuleById>
3396
+ hitsOpeningXZ: (x: number, z: number) => boolean
3397
+ clampXZ: (x: number, z: number, margin?: number) => [number, number]
3398
+ coldSupplySource: ResolvedSupplySource | null
3399
+ hotSupplySource: ResolvedSupplySource | null
3400
+ mainStack: SceneNodeLike | null
3401
+ stackPt: readonly [number, number] | null
3402
+ }
3403
+
3404
+ function nearestPointOnPipeSpine(spine: ReadonlyArray<Vec3>, x: number, z: number, fallbackY: number): Vec3 {
3405
+ let bestPt: Vec3 = spine[0] ?? [x, fallbackY, z]
3406
+ let bestDist = Infinity
3407
+ for (let i = 1; i < spine.length; i++) {
3408
+ const a = spine[i - 1]!
3409
+ const b = spine[i]!
3410
+ const dx = b[0] - a[0]
3411
+ const dz = b[2] - a[2]
3412
+ const lenSq = dx * dx + dz * dz
3413
+ if (lenSq < 1e-4) continue
3414
+ const t = Math.max(0, Math.min(1, ((x - a[0]) * dx + (z - a[2]) * dz) / lenSq))
3415
+ const px = a[0] + dx * t
3416
+ const py = a[1] + (b[1] - a[1]) * t
3417
+ const pz = a[2] + dz * t
3418
+ const d = Math.hypot(x - px, z - pz)
3419
+ if (d < bestDist) {
3420
+ bestDist = d
3421
+ bestPt = [round2(px), round2(py), round2(pz)]
3422
+ }
3423
+ }
3424
+ return bestPt
3425
+ }
3426
+
3427
+ function buildLevelRoutingContext(
3428
+ nodes: Readonly<Record<string, SceneNodeLike>>,
3429
+ levelId: string | null,
3430
+ occupancy: OccupancyType,
3431
+ options: {
3432
+ supplyMaterial?: 'pex-a' | 'pex-b' | 'copper-l' | 'cpvc'
3433
+ dwvMaterial?: 'pvc-dwv' | 'abs-dwv' | 'cast-iron'
3434
+ foundationType?: FoundationType
3435
+ } = {},
3436
+ ): PrecompiledLevelRoutingContext {
3437
+ const levelPipes = Object.values(nodes).filter(
3438
+ (n) => n.type === 'plumbing:pipe-run' && belongsToLevel(nodes, n, levelId),
3439
+ )
3440
+ const sampleSupply = levelPipes.find((p) => p.system === 'cold-water' || p.system === 'hot-water')
3441
+ const sampleDwv = levelPipes.find((p) => p.system === 'dwv-drain' || p.system === 'dwv-vent')
3442
+ const supplyMaterial: 'pex-a' | 'pex-b' | 'copper-l' | 'cpvc' =
3443
+ options.supplyMaterial ??
3444
+ (sampleSupply &&
3445
+ (sampleSupply.material === 'pex-a' ||
3446
+ sampleSupply.material === 'pex-b' ||
3447
+ sampleSupply.material === 'copper-l' ||
3448
+ sampleSupply.material === 'cpvc')
3449
+ ? sampleSupply.material
3450
+ : 'pex-a')
3451
+ const dwvMaterial: 'pvc-dwv' | 'abs-dwv' | 'cast-iron' =
3452
+ options.dwvMaterial ??
3453
+ (sampleDwv &&
3454
+ (sampleDwv.material === 'pvc-dwv' || sampleDwv.material === 'abs-dwv' || sampleDwv.material === 'cast-iron')
3455
+ ? sampleDwv.material
3456
+ : 'pvc-dwv')
3457
+
3458
+ const walls = extractWallSegments(nodes, levelId)
3459
+ const wallById = new Map<string, WallSegment2D>(walls.map((w) => [w.id, w]))
3460
+ const rooms = extractRoomPolygons(nodes, levelId, occupancy)
3461
+ const bounds = sceneBounds(walls, rooms)
3462
+ const indoorRooms = rooms.filter((r) => {
3463
+ if (r.category === 'exterior') return false
3464
+ if (walls.length > 0) {
3465
+ const [cx, cz] = r.centroid
3466
+ if (
3467
+ cx < bounds.minX - 0.15 ||
3468
+ cx > bounds.maxX + 0.15 ||
3469
+ cz < bounds.minZ - 0.15 ||
3470
+ cz > bounds.maxZ + 0.15
3471
+ ) {
3472
+ return false
3473
+ }
3474
+ }
3475
+ return true
3476
+ })
3477
+ const levelH = resolveLevelHeightM(nodes, levelId)
3478
+ const anatomy = compileBuildingAnatomy(nodes)
3479
+
3480
+ const foundationType: FoundationType = options.foundationType ?? inferFoundationFromSupplyPipes(levelPipes)
3481
+ const supplyPlaneY = foundationType === 'slab' ? levelH - 0.25 : -0.16
3482
+ const subFloorElevationM = foundationType === 'slab' ? -0.35 : -0.24
3483
+
3484
+ const legalCavityGraph =
3485
+ walls.length > 0
3486
+ ? compileLegalCavityGraph(anatomy, levelId, { roofClearanceM: 0.1, subFloorElevationM })
3487
+ : undefined
3488
+ const occupancyGrid = anatomy.createOccupancyGrid(levelId, { forTrade: 'plumbing' })
3489
+ const obstacles = mapOccupancyObstaclesToPlumbing(occupancyGrid.obstacles)
3490
+ const cavityContext: PlumbingCavityContext = {
3491
+ nodes,
3492
+ levelId,
3493
+ anatomy,
3494
+ ...(legalCavityGraph ? { graph: legalCavityGraph } : {}),
3495
+ occupancy: occupancyGrid,
3496
+ }
3497
+ const maxRoofYAt = anatomy.getRoofShell(levelId, {
3498
+ wallBounds: bounds,
3499
+ fallbackPitchRiseOver12: 6,
3500
+ clampOverhangToEave: true,
3501
+ }).roofEnvelopeY
3502
+
3503
+ const wallOpenings = mapCanonicalWallsToOpenings(anatomy.getWalls(levelId))
3504
+ const openingsByWall = new Map<string, WallOpeningSpan[]>()
3505
+ for (const op of wallOpenings) {
3506
+ let list = openingsByWall.get(op.wallId)
3507
+ if (!list) {
3508
+ list = []
3509
+ openingsByWall.set(op.wallId, list)
3510
+ }
3511
+ list.push(op)
3512
+ }
3513
+ const hitsOpeningXZ = (cx: number, cz: number): boolean => {
3514
+ for (const w of walls) {
3515
+ const ops = openingsByWall.get(w.id)
3516
+ if (!ops || ops.length === 0) continue
3517
+ const dx = cx - w.start[0]
3518
+ const dz = cz - w.start[1]
3519
+ const along = dx * w.ux + dz * w.uz
3520
+ const perp = Math.abs(dx * w.nx + dz * w.nz)
3521
+ if (perp > w.thicknessM / 2 + 0.12) continue
3522
+ if (ops.some((op) => along >= op.startU - 0.12 && along <= op.endU + 0.12)) {
3523
+ return true
3524
+ }
3525
+ }
3526
+ return false
3527
+ }
3528
+
3529
+ const clampXZ = (x: number, z: number, margin = 0.08): [number, number] => {
3530
+ if (walls.length === 0) return [round2(x), round2(z)]
3531
+ const minX = bounds.minX + margin
3532
+ const maxX = bounds.maxX - margin
3533
+ const minZ = bounds.minZ + margin
3534
+ const maxZ = bounds.maxZ - margin
3535
+ return [
3536
+ round2(minX <= maxX ? Math.max(minX, Math.min(maxX, x)) : bounds.cx),
3537
+ round2(minZ <= maxZ ? Math.max(minZ, Math.min(maxZ, z)) : bounds.cz),
3538
+ ]
3539
+ }
3540
+
3541
+ // Find active water supply sources: PEX/Copper manifold -> existing cold/hot trunk or riser -> on-level WH -> lower-level WH riser
3542
+ const manifold = Object.values(nodes).find(
3543
+ (n) =>
3544
+ n.type === 'plumbing:manifold' &&
3545
+ n.manifoldKind !== 'gas-csst' &&
3546
+ belongsToLevel(nodes, n, levelId) &&
3547
+ isFiniteVec3(n.position),
3548
+ )
3549
+ const waterHeater = Object.values(nodes).find(
3550
+ (n) =>
3551
+ n.type === 'plumbing:equipment' &&
3552
+ typeof n.equipmentKind === 'string' &&
3553
+ n.equipmentKind.startsWith('water-heater-') &&
3554
+ belongsToLevel(nodes, n, levelId) &&
3555
+ isFiniteVec3(n.position),
3556
+ )
3557
+ const isGroundStory = isGroundOrLowestWalledLevel(nodes, levelId)
3558
+ const lowerWalledLevelIds = !isGroundStory ? getLowerWalledLevelIds(nodes, levelId) : []
3559
+ const lowerWaterHeater = !isGroundStory
3560
+ ? (Object.values(nodes).find(
3561
+ (n) =>
3562
+ n.type === 'plumbing:equipment' &&
3563
+ typeof n.equipmentKind === 'string' &&
3564
+ n.equipmentKind.startsWith('water-heater-') &&
3565
+ isFiniteVec3(n.position) &&
3566
+ lowerWalledLevelIds.some((lid) => belongsToLevel(nodes, n, lid)),
3567
+ ) ?? null)
3568
+ : null
3569
+
3570
+ const findTrunkOrRiser = (sys: 'cold-water' | 'hot-water'): ResolvedSupplySource | null => {
3571
+ const trunk = levelPipes.find(
3572
+ (p) =>
3573
+ p.system === sys &&
3574
+ typeof p.name === 'string' &&
3575
+ /\btrunk\b/i.test(p.name) &&
3576
+ Array.isArray(p.path) &&
3577
+ p.path.length >= 2,
3578
+ )
3579
+ if (trunk) {
3580
+ const spine = (trunk.path as Vec3[]).filter(isFiniteVec3)
3581
+ if (spine.length >= 2) {
3582
+ return { id: trunk.id, pos: spine[0]!, isManifold: false, spine }
3583
+ }
3584
+ }
3585
+ const riser = levelPipes.find(
3586
+ (p) =>
3587
+ p.system === sys &&
3588
+ typeof p.name === 'string' &&
3589
+ /\briser\b/i.test(p.name) &&
3590
+ Array.isArray(p.path) &&
3591
+ p.path.length >= 2,
3592
+ )
3593
+ if (riser) {
3594
+ const pts = (riser.path as Vec3[]).filter(isFiniteVec3)
3595
+ if (pts.length >= 2) {
3596
+ const topPt = pts[pts.length - 1]!
3597
+ return { id: riser.id, pos: [Number(topPt[0]), Number(topPt[1]), Number(topPt[2])], isManifold: false }
3598
+ }
3599
+ }
3600
+ return null
3601
+ }
3602
+
3603
+ const resolveSupplyForSystem = (sys: 'cold-water' | 'hot-water'): ResolvedSupplySource | null => {
3604
+ if (manifold && isFiniteVec3(manifold.position)) {
3605
+ return {
3606
+ id: manifold.id,
3607
+ pos: [Number(manifold.position[0]), Number(manifold.position[1]), Number(manifold.position[2])],
3608
+ isManifold: true,
3609
+ }
3610
+ }
3611
+ const trunkOrRiser = findTrunkOrRiser(sys)
3612
+ if (trunkOrRiser) return trunkOrRiser
3613
+ if (waterHeater && isFiniteVec3(waterHeater.position)) {
3614
+ return {
3615
+ id: waterHeater.id,
3616
+ pos: [Number(waterHeater.position[0]), 1.45, Number(waterHeater.position[2])],
3617
+ isManifold: false,
3618
+ }
3619
+ }
3620
+ if (lowerWaterHeater && isFiniteVec3(lowerWaterHeater.position)) {
3621
+ const [rx, rz] = clampXZ(Number(lowerWaterHeater.position[0]), Number(lowerWaterHeater.position[2]), 0.15)
3622
+ return {
3623
+ id: lowerWaterHeater.id,
3624
+ pos: [rx, supplyPlaneY, rz],
3625
+ isManifold: false,
3626
+ }
3627
+ }
3628
+ return null
3629
+ }
3630
+
3631
+ const coldSupplySource = resolveSupplyForSystem('cold-water')
3632
+ const hotSupplySource = resolveSupplyForSystem('hot-water')
3633
+
3634
+ // Find active Main DWV Soil/Vent Stack on level: prefer explicit `isMainVentStack`, then vertical >= 3" vent stack, then any `dwv-vent`
3635
+ const isVerticalLargeStack = (p: SceneNodeLike): boolean => {
3636
+ if (p.system !== 'dwv-vent' || !Array.isArray(p.path) || p.path.length < 2) return false
3637
+ const nomIn = PIPE_NOMINAL_INCHES[p.nominalSize as PipeNominalSize] ?? 0
3638
+ if (nomIn < 3) return false
3639
+ const first = p.path[0]
3640
+ const last = p.path[p.path.length - 1]
3641
+ if (!isFiniteVec3(first) || !isFiniteVec3(last)) return false
3642
+ const horiz = Math.hypot(Number(last[0]) - Number(first[0]), Number(last[2]) - Number(first[2]))
3643
+ const vert = Math.abs(Number(last[1]) - Number(first[1]))
3644
+ return horiz < 0.25 && vert > 1.0
3645
+ }
3646
+ const mainStack =
3647
+ levelPipes.find((p) => p.isMainVentStack === true && Array.isArray(p.path) && p.path.length >= 2) ??
3648
+ levelPipes.find(isVerticalLargeStack) ??
3649
+ levelPipes.find((p) => p.system === 'dwv-vent' && Array.isArray(p.path) && p.path.length >= 2) ??
3650
+ null
3651
+ const stackPt: readonly [number, number] | null =
3652
+ mainStack && Array.isArray(mainStack.path) && isFiniteVec3(mainStack.path[0])
3653
+ ? [Number((mainStack.path as Vec3[])[0]![0]), Number((mainStack.path as Vec3[])[0]![2])]
3654
+ : null
3655
+
3656
+ return {
3657
+ levelId,
3658
+ occupancy,
3659
+ supplyMaterial,
3660
+ dwvMaterial,
3661
+ foundationType,
3662
+ supplyPlaneY,
3663
+ subFloorElevationM,
3664
+ levelPipes,
3665
+ walls,
3666
+ wallById,
3667
+ rooms,
3668
+ indoorRooms,
3669
+ bounds,
3670
+ levelH,
3671
+ obstacles,
3672
+ cavityContext,
3673
+ maxRoofYAt,
3674
+ bones: extractBonesPlumbingContext(nodes, levelId),
3675
+ wetWallFitRule: getIpcRuleById('irc-r602-6-wet-wall-fit'),
3676
+ dryerVentRule: getIpcRuleById('irc-m1502-4-dryer-vent'),
3677
+ dryerVentMaterialRule: getIpcRuleById('irc-m1502-4-1-dryer-vent-material'),
3678
+ hitsOpeningXZ,
3679
+ clampXZ,
3680
+ coldSupplySource,
3681
+ hotSupplySource,
3682
+ mainStack,
3683
+ stackPt,
3684
+ }
3685
+ }
3686
+
3687
+ /**
3688
+ * Deterministically connect a single newly placed or unconnected `plumbing:fixture` into the
3689
+ * active level's existing mechanical core (manifold / trunk / water heater) and main DWV stack:
3690
+ * - Water Closet -> 1/2" Cold Supply + 3" sloped DWV drain + 2" re-vent (never hot water)
3691
+ * - Lavatory / Kitchen Sink / Tub / Shower / Washer / Bidet -> Cold + Hot + DWV drain + re-vent
3692
+ * - Dishwasher -> Hot-only supply + indirect DWV drain + re-vent
3693
+ * - Hose Bibb -> Cold-only supply (no drain)
3694
+ * - Floor Drain / Garbage Disposal -> DWV drain + re-vent (no water supply)
3695
+ */
3696
+ export function planConnectSingleFixture(
3697
+ nodes: Readonly<Record<string, SceneNodeLike>>,
3698
+ fixture: Pick<
3699
+ PlannedFixtureSpec,
3700
+ | 'id'
3701
+ | 'name'
3702
+ | 'fixtureKind'
3703
+ | 'position'
3704
+ | 'rotation'
3705
+ | 'wallId'
3706
+ | 'dfu'
3707
+ | 'wsfuCold'
3708
+ | 'wsfuHot'
3709
+ | 'drainSize'
3710
+ | 'ventSize'
3711
+ | 'supplySize'
3712
+ >,
3713
+ options: {
3714
+ levelId?: string | null
3715
+ codeEdition?: CodeEdition
3716
+ occupancy?: OccupancyType
3717
+ supplyMaterial?: 'pex-a' | 'pex-b' | 'copper-l' | 'cpvc'
3718
+ dwvMaterial?: 'pvc-dwv' | 'abs-dwv' | 'cast-iron'
3719
+ foundationType?: FoundationType
3720
+ existingPipeIds?: ReadonlySet<string>
3721
+ _precompiled?: PrecompiledLevelRoutingContext
3722
+ } = {},
3723
+ ): SingleFixtureConnectResult {
3724
+ const levelId = options.levelId ?? null
3725
+ const codeEdition = options.codeEdition ?? 'IPC-2021'
3726
+ const occupancy = options.occupancy ?? 'residential'
3727
+ const flushType: 'flush-tank' | 'flushometer' = occupancy === 'commercial' ? 'flushometer' : 'flush-tank'
3728
+
3729
+ const ctx =
3730
+ options._precompiled ??
3731
+ buildLevelRoutingContext(nodes, levelId, occupancy, {
3732
+ ...(options.supplyMaterial ? { supplyMaterial: options.supplyMaterial } : {}),
3733
+ ...(options.dwvMaterial ? { dwvMaterial: options.dwvMaterial } : {}),
3734
+ ...(options.foundationType ? { foundationType: options.foundationType } : {}),
3735
+ })
3736
+
3737
+ const {
3738
+ supplyMaterial,
3739
+ dwvMaterial,
3740
+ foundationType,
3741
+ supplyPlaneY,
3742
+ subFloorElevationM,
3743
+ levelPipes,
3744
+ walls,
3745
+ wallById,
3746
+ bounds,
3747
+ levelH,
3748
+ obstacles,
3749
+ cavityContext,
3750
+ maxRoofYAt,
3751
+ bones,
3752
+ wetWallFitRule,
3753
+ hitsOpeningXZ,
3754
+ clampXZ,
3755
+ coldSupplySource,
3756
+ hotSupplySource,
3757
+ mainStack,
3758
+ stackPt,
3759
+ } = ctx
3760
+
3761
+ const alreadyHasSystem = (sys: PlumbingSystem): boolean =>
3762
+ levelPipes.some(
3763
+ (p) => p.system === sys && (p.targetNodeId === fixture.id || p.sourceNodeId === fixture.id),
3764
+ )
3765
+
3766
+ const usedIds = new Set<string>([...Object.keys(nodes), ...(options.existingPipeIds ?? [])])
3767
+ let pipeSeq = 1
3768
+ const nextPipeId = () => {
3769
+ while (usedIds.has(`plumbpipe_conn_${pipeSeq}`)) pipeSeq += 1
3770
+ const id = `plumbpipe_conn_${pipeSeq++}`
3771
+ usedIds.add(id)
3772
+ return id
3773
+ }
3774
+
3775
+ const pipeRuns: PlannedPipeRunSpec[] = []
3776
+ const connectedSystems: PlumbingSystem[] = []
3777
+ const spec = FIXTURE_SPECS[fixture.fixtureKind]
3778
+ const hostWall = fixture.wallId ? wallById.get(fixture.wallId) : nearestWallToPoint(fixture.position[0], fixture.position[2], walls)?.wall
3779
+ const canFitWall = (pipeSize: PipeNominalSize): boolean => {
3780
+ if (!hostWall) return false
3781
+ const nominalIn = PIPE_NOMINAL_INCHES[pipeSize] ?? 2
3782
+ const wallRule = bones.wallRules.get(hostWall.id)
3783
+ const effThick = resolveEffectiveWallThicknessM(hostWall.thicknessM, bones, wallRule)
3784
+ const decl = evaluatePlacementCandidate(
3785
+ [wetWallFitRule],
3786
+ { kind: 'plumbing:pipe-run', system: 'dwv-drain', pos: fixture.position, nominalSizeIn: nominalIn, wallThicknessM: effThick },
3787
+ 'placement',
3788
+ )
3789
+ return decl.legal && checkWetWallPipeFit({ wallThicknessM: effThick, pipeSize, material: dwvMaterial, isLoadBearing: wallRule?.isLoadBearing ?? false }).fits
3790
+ }
3791
+
3792
+ // 1. Cold Water Supply
3793
+ if (coldSupplySource && fixture.supplySize && fixture.wsfuCold > 0 && !alreadyHasSystem('cold-water')) {
3794
+ const coldSized = sizeSupplyPipe({
3795
+ wsfu: fixture.wsfuCold,
3796
+ material: supplyMaterial,
3797
+ isHot: false,
3798
+ minSize: fixture.supplySize,
3799
+ flushType,
3800
+ })
3801
+ const rawTarget = getFixtureSupplyPoint(fixture, 'cold')
3802
+ const [tx, tz] = fixture.fixtureKind === 'hose-bibb' ? [rawTarget[0], rawTarget[2]] : clampXZ(rawTarget[0], rawTarget[2])
3803
+ const fromPt: Vec3 =
3804
+ coldSupplySource.spine && coldSupplySource.spine.length >= 2
3805
+ ? nearestPointOnPipeSpine(coldSupplySource.spine, tx, tz, supplyPlaneY)
3806
+ : [coldSupplySource.pos[0] + 0.08, coldSupplySource.pos[1], coldSupplySource.pos[2]]
3807
+ const route = routePressurizedPipeRun({
3808
+ from: fromPt,
3809
+ to: [tx, rawTarget[1], tz],
3810
+ routingPlaneY: supplyPlaneY,
3811
+ nominalSize: coldSized.size,
3812
+ material: supplyMaterial,
3813
+ euclideanInCavity: false,
3814
+ obstacles,
3815
+ buildingBounds: bounds,
3816
+ maxRoofYAt,
3817
+ cavityContext,
3818
+ })
3819
+ pipeRuns.push({
3820
+ id: nextPipeId(),
3821
+ name: `${coldSized.size} Cold ${coldSupplySource.spine ? 'Branch' : 'Supply'} (${fixture.name})`,
3822
+ system: 'cold-water',
3823
+ material: supplyMaterial,
3824
+ nominalSize: coldSized.size,
3825
+ path: route.path,
3826
+ slopeInPerFt: 0,
3827
+ dfuLoad: 0,
3828
+ wsfuLoad: fixture.wsfuCold,
3829
+ gasBtuh: 0,
3830
+ sourceNodeId: coldSupplySource.id,
3831
+ targetNodeId: fixture.id,
3832
+ hasCleanout: false,
3833
+ hasSedimentTrap: false,
3834
+ hasShutoffWithin6Ft: true,
3835
+ isHorizontalSanTee: false,
3836
+ isMainVentStack: false,
3837
+ })
3838
+ connectedSystems.push('cold-water')
3839
+ }
3840
+
3841
+ // 2. Hot Water Supply
3842
+ if (hotSupplySource && fixture.supplySize && fixture.wsfuHot > 0 && !alreadyHasSystem('hot-water')) {
3843
+ const hotSized = sizeSupplyPipe({
3844
+ wsfu: fixture.wsfuHot,
3845
+ material: supplyMaterial,
3846
+ isHot: true,
3847
+ minSize: fixture.supplySize,
3848
+ flushType,
3849
+ })
3850
+ const rawTarget = getFixtureSupplyPoint(fixture, 'hot')
3851
+ const [tx, tz] = fixture.fixtureKind === 'hose-bibb' ? [rawTarget[0], rawTarget[2]] : clampXZ(rawTarget[0], rawTarget[2])
3852
+ const fromPt: Vec3 =
3853
+ hotSupplySource.spine && hotSupplySource.spine.length >= 2
3854
+ ? nearestPointOnPipeSpine(hotSupplySource.spine, tx, tz, supplyPlaneY + 0.04)
3855
+ : [hotSupplySource.pos[0] - 0.08, hotSupplySource.pos[1], hotSupplySource.pos[2]]
3856
+ const route = routePressurizedPipeRun({
3857
+ from: fromPt,
3858
+ to: [tx, rawTarget[1], tz],
3859
+ routingPlaneY: supplyPlaneY + 0.04,
3860
+ nominalSize: hotSized.size,
3861
+ material: supplyMaterial,
3862
+ euclideanInCavity: false,
3863
+ obstacles,
3864
+ buildingBounds: bounds,
3865
+ maxRoofYAt,
3866
+ cavityContext,
3867
+ })
3868
+ pipeRuns.push({
3869
+ id: nextPipeId(),
3870
+ name: `${hotSized.size} Hot ${hotSupplySource.spine ? 'Branch' : 'Supply'} (${fixture.name})`,
3871
+ system: 'hot-water',
3872
+ material: supplyMaterial,
3873
+ nominalSize: hotSized.size,
3874
+ path: route.path,
3875
+ slopeInPerFt: 0,
3876
+ dfuLoad: 0,
3877
+ wsfuLoad: fixture.wsfuHot,
3878
+ gasBtuh: 0,
3879
+ sourceNodeId: hotSupplySource.id,
3880
+ targetNodeId: fixture.id,
3881
+ hasCleanout: false,
3882
+ hasSedimentTrap: false,
3883
+ hasShutoffWithin6Ft: true,
3884
+ isHorizontalSanTee: false,
3885
+ isMainVentStack: false,
3886
+ })
3887
+ connectedSystems.push('hot-water')
3888
+ }
3889
+
3890
+ // 3. Gravity DWV Drain & Re-Vent
3891
+ if (stackPt && mainStack && fixture.drainSize && !alreadyHasSystem('dwv-drain')) {
3892
+ const branchSizing = sizeDrainBranch({
3893
+ dfu: fixture.dfu,
3894
+ hasWaterCloset: fixture.fixtureKind === 'water-closet',
3895
+ minUpstreamSize: fixture.drainSize,
3896
+ codeEdition,
3897
+ })
3898
+ const dwvRoute = routeDwvDrainRun({
3899
+ from: fixture.position,
3900
+ to: [stackPt[0], subFloorElevationM, stackPt[1]],
3901
+ nominalSize: branchSizing.recommendedSize,
3902
+ material: dwvMaterial,
3903
+ foundationType,
3904
+ slopeInPerFt: 0.25,
3905
+ obstacles,
3906
+ buildingBounds: bounds,
3907
+ cavityContext,
3908
+ })
3909
+ const safeDrainWallId = hostWall && canFitWall(branchSizing.recommendedSize) ? hostWall.id : undefined
3910
+ pipeRuns.push({
3911
+ id: nextPipeId(),
3912
+ name: `${branchSizing.recommendedSize} DWV Drain (${fixture.name})`,
3913
+ system: 'dwv-drain',
3914
+ material: dwvMaterial,
3915
+ nominalSize: branchSizing.recommendedSize,
3916
+ path: dwvRoute.path,
3917
+ slopeInPerFt: dwvRoute.slopeInPerFt,
3918
+ dfuLoad: fixture.dfu,
3919
+ wsfuLoad: 0,
3920
+ gasBtuh: 0,
3921
+ sourceNodeId: fixture.id,
3922
+ targetNodeId: mainStack.id,
3923
+ hasCleanout: false,
3924
+ hasSedimentTrap: false,
3925
+ hasShutoffWithin6Ft: false,
3926
+ isHorizontalSanTee: false,
3927
+ isMainVentStack: false,
3928
+ trapArmLengthFt: fixture.ventSize ? 1.5 : dwvRoute.lengthFt,
3929
+ ...(safeDrainWallId !== undefined ? { wallId: safeDrainWallId } : {}),
3930
+ })
3931
+ connectedSystems.push('dwv-drain')
3932
+ }
3933
+
3934
+ if (stackPt && mainStack && fixture.ventSize && !alreadyHasSystem('dwv-vent')) {
3935
+ const ventOrigin = resolveVentOriginForFixture(
3936
+ fixture.position,
3937
+ fixture.wallId,
3938
+ wallById,
3939
+ walls,
3940
+ hitsOpeningXZ,
3941
+ )
3942
+ const ventRoute = routeVentRun({
3943
+ from: ventOrigin,
3944
+ stackPoint: stackPt,
3945
+ floodRimHeightM: spec.floodRimHeightM,
3946
+ ceilingHeightM: levelH,
3947
+ nominalSize: fixture.ventSize,
3948
+ material: dwvMaterial,
3949
+ obstacles,
3950
+ buildingBounds: bounds,
3951
+ maxRoofYAt,
3952
+ cavityContext,
3953
+ })
3954
+ const safeVentWallId = hostWall && canFitWall(fixture.ventSize) ? hostWall.id : undefined
3955
+ pipeRuns.push({
3956
+ id: nextPipeId(),
3957
+ name: `${fixture.ventSize} Re-Vent (${fixture.name})`,
3958
+ system: 'dwv-vent',
3959
+ material: dwvMaterial,
3960
+ nominalSize: fixture.ventSize,
3961
+ path: ventRoute.path,
3962
+ slopeInPerFt: 0,
3963
+ dfuLoad: fixture.dfu,
3964
+ wsfuLoad: 0,
3965
+ gasBtuh: 0,
3966
+ sourceNodeId: fixture.id,
3967
+ targetNodeId: mainStack.id,
3968
+ hasCleanout: false,
3969
+ hasSedimentTrap: false,
3970
+ hasShutoffWithin6Ft: false,
3971
+ isHorizontalSanTee: false,
3972
+ isMainVentStack: false,
3973
+ ...(safeVentWallId !== undefined ? { wallId: safeVentWallId } : {}),
3974
+ })
3975
+ connectedSystems.push('dwv-vent')
3976
+ }
3977
+
3978
+ return {
3979
+ pipeRuns,
3980
+ connectedSystems,
3981
+ hasSupplySource: Boolean(coldSupplySource || hotSupplySource),
3982
+ hasDwvStack: Boolean(mainStack),
3983
+ }
3984
+ }
3985
+
3986
+ export type PlumbingSyncResult = {
3987
+ fellBackToFullAutoPopulate: boolean
3988
+ fullPlan?: PlumbingAutoPopulatePlan
3989
+ fixtures: PlannedFixtureSpec[]
3990
+ pipeRuns: PlannedPipeRunSpec[]
3991
+ newlyLinkedFurnishings: number
3992
+ connectedFixtures: number
3993
+ summary: string
3994
+ }
3995
+
3996
+ /**
3997
+ * Incrementally sync newly placed real-world catalog/furnishing fixtures (toilets, vanities,
3998
+ * kitchen sinks, tubs, showers, washers, refrigerators) and unconnected `plumbing:fixture` nodes
3999
+ * into the level's existing plumbing core without disturbing existing equipment or pipe runs.
4000
+ * Falls back to full `planPlumbingAutoPopulate` if no plumbing core exists on the level yet.
4001
+ */
4002
+ export function planSyncPlumbingFixtures(
4003
+ nodes: Readonly<Record<string, SceneNodeLike>>,
4004
+ options: PlumbingAutoPopulateOptions = {},
4005
+ ): PlumbingSyncResult {
4006
+ const levelId = options.levelId ?? null
4007
+ const codeEdition = options.codeEdition ?? 'IPC-2021'
4008
+ const occupancy = options.occupancy ?? 'residential'
4009
+
4010
+ const isGroundStory = isGroundOrLowestWalledLevel(nodes, levelId)
4011
+ const lowerWalledLevelIds = !isGroundStory ? getLowerWalledLevelIds(nodes, levelId) : []
4012
+ const hasSupplyCore = Object.values(nodes).some(
4013
+ (n) =>
4014
+ (belongsToLevel(nodes, n, levelId) &&
4015
+ ((n.type === 'plumbing:manifold' && n.manifoldKind !== 'gas-csst') ||
4016
+ (n.type === 'plumbing:equipment' &&
4017
+ typeof n.equipmentKind === 'string' &&
4018
+ n.equipmentKind.startsWith('water-heater-')) ||
4019
+ (n.type === 'plumbing:pipe-run' &&
4020
+ (n.system === 'cold-water' || n.system === 'hot-water') &&
4021
+ typeof n.name === 'string' &&
4022
+ /\b(?:trunk|riser)\b/i.test(n.name)))) ||
4023
+ (!isGroundStory &&
4024
+ n.type === 'plumbing:equipment' &&
4025
+ typeof n.equipmentKind === 'string' &&
4026
+ n.equipmentKind.startsWith('water-heater-') &&
4027
+ lowerWalledLevelIds.some((lid) => belongsToLevel(nodes, n, lid))),
4028
+ )
4029
+ const hasStack = Object.values(nodes).some(
4030
+ (n) =>
4031
+ belongsToLevel(nodes, n, levelId) &&
4032
+ n.type === 'plumbing:pipe-run' &&
4033
+ (n.isMainVentStack === true || n.system === 'dwv-vent'),
4034
+ )
4035
+ if (!hasSupplyCore && !hasStack) {
4036
+ const fullPlan = planPlumbingAutoPopulate(nodes, options)
4037
+ return {
4038
+ fellBackToFullAutoPopulate: true,
4039
+ fullPlan,
4040
+ fixtures: fullPlan.fixtures,
4041
+ pipeRuns: fullPlan.pipeRuns,
4042
+ newlyLinkedFurnishings: fullPlan.fixtures.filter((f) => Boolean(f.furnishingSourceId)).length,
4043
+ connectedFixtures: fullPlan.fixtures.length,
4044
+ summary: fullPlan.summary,
4045
+ }
4046
+ }
4047
+
4048
+ // Compile building anatomy, cavity graph, occupancy grid, materials, and supply/stack anchors ONCE for the entire sync pass
4049
+ const ctx = buildLevelRoutingContext(nodes, levelId, occupancy, {
4050
+ ...(options.supplyMaterial ? { supplyMaterial: options.supplyMaterial } : {}),
4051
+ ...(options.dwvMaterial ? { dwvMaterial: options.dwvMaterial } : {}),
4052
+ ...(options.foundationType ? { foundationType: options.foundationType } : {}),
4053
+ })
4054
+ const {
4055
+ supplyMaterial,
4056
+ dwvMaterial,
4057
+ foundationType,
4058
+ supplyPlaneY,
4059
+ levelPipes,
4060
+ walls,
4061
+ wallById,
4062
+ indoorRooms,
4063
+ bounds,
4064
+ obstacles,
4065
+ cavityContext,
4066
+ maxRoofYAt,
4067
+ dryerVentRule,
4068
+ dryerVentMaterialRule,
4069
+ clampXZ,
4070
+ coldSupplySource,
4071
+ } = ctx
4072
+
4073
+ const existingPlumbingFixtures = Object.values(nodes).filter(
4074
+ (n) => n.type === 'plumbing:fixture' && belongsToLevel(nodes, n, levelId),
4075
+ )
4076
+ const linkedSourceIds = new Set<string>()
4077
+ const existingDryerVentSourceIds = new Set<string>()
4078
+ for (const n of Object.values(nodes)) {
4079
+ if (!belongsToLevel(nodes, n, levelId)) continue
4080
+ if (typeof n.furnishingSourceId === 'string' && n.furnishingSourceId) {
4081
+ linkedSourceIds.add(n.furnishingSourceId)
4082
+ }
4083
+ if (n.type === 'plumbing:pipe-run') {
4084
+ if (typeof n.targetNodeId === 'string' && n.targetNodeId) {
4085
+ linkedSourceIds.add(n.targetNodeId)
4086
+ }
4087
+ if (typeof n.sourceNodeId === 'string' && n.sourceNodeId) {
4088
+ linkedSourceIds.add(n.sourceNodeId)
4089
+ if (n.system === 'dryer-vent') {
4090
+ existingDryerVentSourceIds.add(n.sourceNodeId)
4091
+ }
4092
+ }
4093
+ }
4094
+ }
4095
+
4096
+ const usedIds = new Set<string>(Object.keys(nodes))
4097
+ let fixSeq = 1
4098
+ const nextFixId = () => {
4099
+ while (usedIds.has(`plumbfix_sync_${fixSeq}`)) fixSeq += 1
4100
+ const id = `plumbfix_sync_${fixSeq++}`
4101
+ usedIds.add(id)
4102
+ return id
4103
+ }
4104
+
4105
+ const newFixtures: PlannedFixtureSpec[] = []
4106
+ const newIceMakers: Array<{ sourceId: string; name: string; pos: Vec3; wsfuCold: number }> = []
4107
+ const newGasTargets: Array<{ sourceId: string; name: string; pos: Vec3; btuh: number }> = []
4108
+ const newDryers: Array<{ sourceId: string; name: string; pos: Vec3 }> = []
4109
+ const linkedInThisSync = new Set<string>()
4110
+
4111
+ for (const n of Object.values(nodes)) {
4112
+ if (!belongsToLevel(nodes, n, levelId) || linkedSourceIds.has(n.id)) continue
4113
+ const role = inferCatalogOrFurnishingPlumbingRole(n)
4114
+ if (!role) continue
4115
+ if (!isFiniteVec3(n.position)) continue
4116
+ let rawPx = Number(n.position[0])
4117
+ let rawPz = Number(n.position[2])
4118
+ const hostWall = typeof n.parentId === 'string' ? wallById.get(n.parentId) : undefined
4119
+ if (hostWall) {
4120
+ const uClamped = Math.max(0.05, Math.min(hostWall.lengthM - 0.05, rawPx))
4121
+ const localZ = Math.max(-0.5, Math.min(0.5, rawPz))
4122
+ rawPx = hostWall.start[0] + hostWall.ux * uClamped + hostWall.nx * localZ
4123
+ rawPz = hostWall.start[1] + hostWall.uz * uClamped + hostWall.nz * localZ
4124
+ if (walls.length > 0) {
4125
+ const [clampedX, clampedZ] = clampXZ(rawPx, rawPz, 0.15)
4126
+ rawPx = clampedX
4127
+ rawPz = clampedZ
4128
+ }
4129
+ } else if (
4130
+ walls.length > 0 &&
4131
+ (rawPx < bounds.minX - 0.15 ||
4132
+ rawPx > bounds.maxX + 0.15 ||
4133
+ rawPz < bounds.minZ - 0.15 ||
4134
+ rawPz > bounds.maxZ + 0.15)
4135
+ ) {
4136
+ continue
4137
+ }
4138
+
4139
+ const nearWall = hostWall
4140
+ ? { wall: hostWall, t: 0.5, point: [rawPx, rawPz] as const, distanceM: 0 }
4141
+ : nearestWallToPoint(rawPx, rawPz, walls)
4142
+ const room = resolveIndoorRoomForPoint(rawPx, rawPz, indoorRooms, nearWall)
4143
+ const rot =
4144
+ typeof n.rotation === 'number' && Number.isFinite(n.rotation)
4145
+ ? n.rotation
4146
+ : Array.isArray(n.rotation) && n.rotation.length >= 2 && Number.isFinite(Number(n.rotation[1]))
4147
+ ? Number(n.rotation[1])
4148
+ : nearWall && room
4149
+ ? yawFacingRoom(nearWall.wall, room.centroid)
4150
+ : 0
4151
+ const roomName = room?.name ?? (typeof n.roomName === 'string' && n.roomName.trim() ? n.roomName.trim() : 'Main')
4152
+
4153
+ if (role.role === 'ice-maker') {
4154
+ const [ix, iz] = rotateLocal2D(rawPx, rawPz, 0, -0.24, rot)
4155
+ const [cx, cz] = walls.length > 0 ? clampXZ(ix, iz, 0.08) : [ix, iz]
4156
+ newIceMakers.push({
4157
+ sourceId: n.id,
4158
+ name: role.sku ? `${roomName} Refrigerator Ice Maker [${role.sku}]` : `${roomName} Refrigerator Ice Maker`,
4159
+ pos: [cx, 0.45, cz],
4160
+ wsfuCold: role.wsfuCold,
4161
+ })
4162
+ continue
4163
+ }
4164
+
4165
+ if (role.role === 'gas-appliance') {
4166
+ if (options.includeFuelGas !== false) {
4167
+ const [gx, gz] = rotateLocal2D(rawPx, rawPz, 0, -0.22, rot)
4168
+ const [cx, cz] = walls.length > 0 ? clampXZ(gx, gz, 0.08) : [gx, gz]
4169
+ newGasTargets.push({
4170
+ sourceId: n.id,
4171
+ name: role.sku ? `${roomName} ${role.label} [${role.sku}]` : `${roomName} ${role.label}`,
4172
+ pos: [cx, 0.45, cz],
4173
+ btuh: role.btuh,
4174
+ })
4175
+ }
4176
+ continue
4177
+ }
4178
+
4179
+ if (role.role === 'dryer') {
4180
+ if (options.includeDryerVent !== false && !existingDryerVentSourceIds.has(n.id)) {
4181
+ const [dx, dz] = walls.length > 0 ? clampXZ(rawPx, rawPz, 0.08) : [round2(rawPx), round2(rawPz)]
4182
+ newDryers.push({
4183
+ sourceId: n.id,
4184
+ name: role.sku ? `${role.label} [${role.sku}]` : role.label,
4185
+ pos: [dx, 0.35, dz],
4186
+ })
4187
+ }
4188
+ if (role.isGas && options.includeFuelGas !== false) {
4189
+ const [gx, gz] = rotateLocal2D(rawPx, rawPz, 0, -0.22, rot)
4190
+ const [cx, cz] = walls.length > 0 ? clampXZ(gx, gz, 0.08) : [gx, gz]
4191
+ newGasTargets.push({
4192
+ sourceId: n.id,
4193
+ name: role.sku ? `${roomName} Gas Dryer [${role.sku}]` : `${roomName} Gas Dryer`,
4194
+ pos: [cx, 0.45, cz],
4195
+ btuh: 22000,
4196
+ })
4197
+ }
4198
+ continue
4199
+ }
4200
+
4201
+ if (role.role !== 'fixture') continue
4202
+
4203
+ const spec = FIXTURE_SPECS[role.fixtureKind]
4204
+ const wsfu = getFixtureWsfu(role.fixtureKind, occupancy)
4205
+ const skuTag = role.sku ? ` [${role.sku}]` : ''
4206
+ const offsets: ReadonlyArray<{ lx: number; suffix: string }> =
4207
+ role.basins === 2
4208
+ ? [
4209
+ { lx: -Math.min(0.42, Math.max(0.24, role.widthM * 0.25)), suffix: ' (Left Basin)' },
4210
+ { lx: Math.min(0.42, Math.max(0.24, role.widthM * 0.25)), suffix: ' (Right Basin)' },
4211
+ ]
4212
+ : [{ lx: 0, suffix: '' }]
4213
+
4214
+ // Deduplicate double-basin vanities per basin (< 0.22 m) so a single existing basin doesn't mask the second basin.
4215
+ const dedupRadiusM = role.basins === 2 ? 0.22 : 0.6
4216
+ let addedForNode = false
4217
+ for (const off of offsets) {
4218
+ const [fx, fz] = off.lx === 0 ? [round2(rawPx), round2(rawPz)] : rotateLocal2D(rawPx, rawPz, off.lx, 0, rot)
4219
+ const checkX = role.basins === 2 ? fx : rawPx
4220
+ const checkZ = role.basins === 2 ? fz : rawPz
4221
+ const basinCovered = [...existingPlumbingFixtures, ...newFixtures].some((ef) => {
4222
+ const ePos = ef.position as Vec3 | undefined
4223
+ return (
4224
+ ef.fixtureKind === role.fixtureKind &&
4225
+ isFiniteVec3(ePos) &&
4226
+ Math.hypot(Number(ePos[0]) - checkX, Number(ePos[2]) - checkZ) < dedupRadiusM
4227
+ )
4228
+ })
4229
+ if (basinCovered) continue
4230
+ newFixtures.push({
4231
+ id: nextFixId(),
4232
+ name: `${roomName} ${spec.label}${off.suffix}${skuTag}`,
4233
+ fixtureKind: role.fixtureKind,
4234
+ position: [fx, spec.roughInHeightM, fz],
4235
+ rotation: rot,
4236
+ roomName,
4237
+ wallId: nearWall?.wall.id,
4238
+ dfu: getFixtureDfu(role.fixtureKind, codeEdition),
4239
+ wsfuCold: wsfu.cold,
4240
+ wsfuHot: wsfu.hot,
4241
+ wsfuTotal: wsfu.total,
4242
+ trapSize: spec.minTrapIn,
4243
+ drainSize: spec.minDrainIn,
4244
+ ventSize: spec.minVentIn,
4245
+ supplySize: spec.supplySizeIn,
4246
+ hasVacuumBreaker: role.fixtureKind === 'hose-bibb',
4247
+ hasPTrap: spec.needsPTrap,
4248
+ electricalDemand: getFixtureElectricalDemand(role.fixtureKind),
4249
+ furnishingSourceId: n.id,
4250
+ ...(role.sku ? { catalogSku: role.sku } : {}),
4251
+ roughInOnly: true,
4252
+ })
4253
+ addedForNode = true
4254
+ }
4255
+ if (addedForNode) {
4256
+ linkedInThisSync.add(n.id)
4257
+ }
4258
+ }
4259
+
4260
+ // Connect all newly linked fixtures AND any existing unconnected manual plumbing:fixture nodes
4261
+ const allPipeRuns: PlannedPipeRunSpec[] = []
4262
+ let connectedFixtures = 0
4263
+ const targetsToConnect: Array<
4264
+ Pick<
4265
+ PlannedFixtureSpec,
4266
+ | 'id'
4267
+ | 'name'
4268
+ | 'fixtureKind'
4269
+ | 'position'
4270
+ | 'rotation'
4271
+ | 'wallId'
4272
+ | 'dfu'
4273
+ | 'wsfuCold'
4274
+ | 'wsfuHot'
4275
+ | 'drainSize'
4276
+ | 'ventSize'
4277
+ | 'supplySize'
4278
+ >
4279
+ > = [
4280
+ ...newFixtures,
4281
+ ...existingPlumbingFixtures.map((ef) => {
4282
+ const rawKind = typeof ef.fixtureKind === 'string' ? ef.fixtureKind : ''
4283
+ const kind: FixtureKind = rawKind in FIXTURE_SPECS ? (rawKind as FixtureKind) : 'lavatory'
4284
+ const spec = FIXTURE_SPECS[kind]
4285
+ const wsfu = getFixtureWsfu(kind, occupancy)
4286
+ const pos = isFiniteVec3(ef.position)
4287
+ ? ([Number(ef.position[0]), Number(ef.position[1]), Number(ef.position[2])] as Vec3)
4288
+ : ([bounds.cx, spec.roughInHeightM, bounds.cz] as Vec3)
4289
+ return {
4290
+ id: ef.id,
4291
+ name: typeof ef.name === 'string' && ef.name ? ef.name : spec.label,
4292
+ fixtureKind: kind,
4293
+ position: pos,
4294
+ rotation: typeof ef.rotation === 'number' && Number.isFinite(ef.rotation) ? ef.rotation : 0,
4295
+ wallId: typeof ef.wallId === 'string' ? ef.wallId : undefined,
4296
+ dfu: typeof ef.dfu === 'number' ? ef.dfu : getFixtureDfu(kind, codeEdition),
4297
+ wsfuCold: typeof ef.wsfuCold === 'number' ? ef.wsfuCold : wsfu.cold,
4298
+ wsfuHot: typeof ef.wsfuHot === 'number' ? ef.wsfuHot : wsfu.hot,
4299
+ drainSize: (ef.drainSize as PipeNominalSize | null | undefined) ?? spec.minDrainIn,
4300
+ ventSize: (ef.ventSize as PipeNominalSize | null | undefined) ?? spec.minVentIn,
4301
+ supplySize: (ef.supplySize as PipeNominalSize | null | undefined) ?? spec.supplySizeIn,
4302
+ }
4303
+ }),
4304
+ ]
4305
+
4306
+ for (const fix of targetsToConnect) {
4307
+ const conn = planConnectSingleFixture(nodes, fix, {
4308
+ levelId,
4309
+ codeEdition,
4310
+ occupancy,
4311
+ supplyMaterial,
4312
+ dwvMaterial,
4313
+ foundationType,
4314
+ existingPipeIds: usedIds,
4315
+ _precompiled: ctx,
4316
+ })
4317
+ if (conn.pipeRuns.length > 0) {
4318
+ connectedFixtures += 1
4319
+ for (const r of conn.pipeRuns) {
4320
+ usedIds.add(r.id)
4321
+ allPipeRuns.push(r)
4322
+ }
4323
+ }
4324
+ }
4325
+
4326
+ // Also route cold-water ice-maker lines, fuel-gas lines, and 4" rigid aluminum dryer vents using the precompiled context
4327
+ if (newIceMakers.length > 0 || newGasTargets.length > 0 || newDryers.length > 0) {
4328
+ let auxSeq = 1
4329
+ const nextAuxPipeId = () => {
4330
+ while (usedIds.has(`plumbpipe_sync_${auxSeq}`)) auxSeq += 1
4331
+ const id = `plumbpipe_sync_${auxSeq++}`
4332
+ usedIds.add(id)
4333
+ return id
4334
+ }
4335
+
4336
+ if (coldSupplySource) {
4337
+ for (const fridge of newIceMakers) {
4338
+ const origin: Vec3 =
4339
+ coldSupplySource.spine && coldSupplySource.spine.length >= 2
4340
+ ? nearestPointOnPipeSpine(coldSupplySource.spine, fridge.pos[0], fridge.pos[2], supplyPlaneY)
4341
+ : [coldSupplySource.pos[0] + 0.08, coldSupplySource.pos[1], coldSupplySource.pos[2]]
4342
+ const route = routePressurizedPipeRun({
4343
+ from: origin,
4344
+ to: fridge.pos,
4345
+ routingPlaneY: supplyPlaneY,
4346
+ nominalSize: '1/2"',
4347
+ material: supplyMaterial,
4348
+ euclideanInCavity: false,
4349
+ obstacles,
4350
+ buildingBounds: bounds,
4351
+ maxRoofYAt,
4352
+ cavityContext,
4353
+ })
4354
+ allPipeRuns.push({
4355
+ id: nextAuxPipeId(),
4356
+ name: `1/2" Cold Ice-Maker Line (${fridge.name})`,
4357
+ system: 'cold-water',
4358
+ material: supplyMaterial,
4359
+ nominalSize: '1/2"',
4360
+ path: route.path,
4361
+ slopeInPerFt: 0,
4362
+ dfuLoad: 0,
4363
+ wsfuLoad: fridge.wsfuCold,
4364
+ gasBtuh: 0,
4365
+ sourceNodeId: coldSupplySource.id,
4366
+ targetNodeId: fridge.sourceId,
4367
+ hasCleanout: false,
4368
+ hasSedimentTrap: false,
4369
+ hasShutoffWithin6Ft: true,
4370
+ isHorizontalSanTee: false,
4371
+ isMainVentStack: false,
4372
+ })
4373
+ linkedInThisSync.add(fridge.sourceId)
4374
+ connectedFixtures += 1
4375
+ }
4376
+ }
4377
+
4378
+ const gasMeter = Object.values(nodes).find(
4379
+ (n) =>
4380
+ n.type === 'plumbing:equipment' &&
4381
+ n.equipmentKind === 'gas-meter' &&
4382
+ belongsToLevel(nodes, n, levelId) &&
4383
+ isFiniteVec3(n.position),
4384
+ )
4385
+ if (gasMeter && isFiniteVec3(gasMeter.position)) {
4386
+ const gPos = gasMeter.position as Vec3
4387
+ for (const target of newGasTargets) {
4388
+ const prelim = sizeFuelGasPipe({ totalBtuh: target.btuh, longestRunFt: 40, material: 'black-iron' })
4389
+ let gasRoute = routePressurizedPipeRun({
4390
+ from: [Number(gPos[0]), Number(gPos[1]), Number(gPos[2])],
4391
+ to: target.pos,
4392
+ routingPlaneY: supplyPlaneY - 0.06,
4393
+ nominalSize: prelim.recommendedSize,
4394
+ material: 'black-iron',
4395
+ euclideanInCavity: false,
4396
+ obstacles,
4397
+ buildingBounds: bounds,
4398
+ maxRoofYAt,
4399
+ cavityContext,
4400
+ })
4401
+ const sized = sizeFuelGasPipe({
4402
+ totalBtuh: target.btuh,
4403
+ longestRunFt: Math.max(IPC_RULE_THRESHOLDS.fuelGasMinSizingLengthPlacementFt, gasRoute.lengthFt),
4404
+ material: 'black-iron',
4405
+ })
4406
+ if (sized.recommendedSize !== prelim.recommendedSize) {
4407
+ gasRoute = routePressurizedPipeRun({
4408
+ from: [Number(gPos[0]), Number(gPos[1]), Number(gPos[2])],
4409
+ to: target.pos,
4410
+ routingPlaneY: supplyPlaneY - 0.06,
4411
+ nominalSize: sized.recommendedSize,
4412
+ material: 'black-iron',
4413
+ euclideanInCavity: false,
4414
+ obstacles,
4415
+ buildingBounds: bounds,
4416
+ maxRoofYAt,
4417
+ cavityContext,
4418
+ })
4419
+ }
4420
+ allPipeRuns.push({
4421
+ id: nextAuxPipeId(),
4422
+ name: `${sized.recommendedSize} Fuel Gas Line (${target.name}, ${Math.round(target.btuh / 1000)} kBTU/hr, IFGC 402.4)`,
4423
+ system: 'fuel-gas',
4424
+ material: 'black-iron',
4425
+ nominalSize: sized.recommendedSize,
4426
+ path: gasRoute.path,
4427
+ slopeInPerFt: 0,
4428
+ dfuLoad: 0,
4429
+ wsfuLoad: 0,
4430
+ gasBtuh: target.btuh,
4431
+ sourceNodeId: gasMeter.id,
4432
+ targetNodeId: target.sourceId,
4433
+ hasCleanout: false,
4434
+ hasSedimentTrap: true,
4435
+ hasShutoffWithin6Ft: true,
4436
+ isHorizontalSanTee: false,
4437
+ isMainVentStack: false,
4438
+ })
4439
+ linkedInThisSync.add(target.sourceId)
4440
+ connectedFixtures += 1
4441
+ }
4442
+ }
4443
+
4444
+ if (newDryers.length > 0) {
4445
+ const dryerMaterial: PipeMaterial =
4446
+ (IPC_RULE_THRESHOLDS.dryerVentRequiredMaterials[0] as PipeMaterial | undefined) ?? 'rigid-aluminum'
4447
+ for (const dryer of newDryers) {
4448
+ const dryerOrigin: Vec3 = [dryer.pos[0], 0.35, dryer.pos[2]]
4449
+ const exitCandidates: Array<{ distM: number; exitPt: Vec3 }> = (
4450
+ [
4451
+ { distM: Math.abs(dryerOrigin[0] - bounds.minX), exitPt: [round2(bounds.minX - 0.08), 0.35, dryerOrigin[2]] as Vec3 },
4452
+ { distM: Math.abs(bounds.maxX - dryerOrigin[0]), exitPt: [round2(bounds.maxX + 0.08), 0.35, dryerOrigin[2]] as Vec3 },
4453
+ { distM: Math.abs(bounds.maxZ - dryerOrigin[2]), exitPt: [dryerOrigin[0], 0.35, round2(bounds.maxZ + 0.08)] as Vec3 },
4454
+ { distM: Math.abs(dryerOrigin[2] - bounds.minZ), exitPt: [dryerOrigin[0], 0.35, round2(bounds.minZ - 0.08)] as Vec3 },
4455
+ ] satisfies Array<{ distM: number; exitPt: Vec3 }>
4456
+ ).sort((a, b) => a.distM - b.distM)
4457
+
4458
+ let bestDryerRoute: {
4459
+ path: Vec3[]
4460
+ clashes: number
4461
+ legal: boolean
4462
+ effectiveLengthFt: number
4463
+ } | null = null
4464
+
4465
+ for (const cand of exitCandidates) {
4466
+ const route = routePressurizedPipeRun({
4467
+ from: dryerOrigin,
4468
+ to: cand.exitPt,
4469
+ routingPlaneY: 0.35,
4470
+ nominalSize: '4"',
4471
+ material: dryerMaterial,
4472
+ euclideanInCavity: false,
4473
+ obstacles,
4474
+ buildingBounds: bounds,
4475
+ maxRoofYAt,
4476
+ cavityContext,
4477
+ allowedBands: ['under-sill', 'mid-wall', 'overhead-plenum'],
4478
+ })
4479
+ const { elbows90, elbows45 } = countPathElbows(route.path)
4480
+ const check = checkDryerVentRun({ lengthFt: route.lengthFt, elbows90, elbows45 })
4481
+ const declEval = evaluatePlacementCandidate(
4482
+ [dryerVentRule, dryerVentMaterialRule],
4483
+ {
4484
+ id: dryer.sourceId,
4485
+ kind: 'plumbing:pipe-run',
4486
+ system: 'dryer-vent',
4487
+ material: dryerMaterial,
4488
+ pos: cand.exitPt,
4489
+ effectiveLengthFt: check.effectiveLengthFt,
4490
+ },
4491
+ 'placement',
4492
+ )
4493
+ const scored = {
4494
+ path: route.path,
4495
+ clashes: route.clashes.length,
4496
+ legal: declEval.legal,
4497
+ effectiveLengthFt: check.effectiveLengthFt,
4498
+ }
4499
+ if (
4500
+ !bestDryerRoute ||
4501
+ (scored.legal && !bestDryerRoute.legal) ||
4502
+ (scored.legal === bestDryerRoute.legal && scored.clashes < bestDryerRoute.clashes) ||
4503
+ (scored.legal === bestDryerRoute.legal &&
4504
+ scored.clashes === bestDryerRoute.clashes &&
4505
+ scored.effectiveLengthFt < bestDryerRoute.effectiveLengthFt)
4506
+ ) {
4507
+ bestDryerRoute = scored
4508
+ }
4509
+ if (scored.legal && scored.clashes === 0 && cand.distM === exitCandidates[0]!.distM) {
4510
+ break
4511
+ }
4512
+ }
4513
+
4514
+ if (bestDryerRoute) {
4515
+ allPipeRuns.push({
4516
+ id: nextAuxPipeId(),
4517
+ name: `4" Rigid Aluminum Dryer Vent (${dryer.name}, IRC M1502.4)`,
4518
+ system: 'dryer-vent',
4519
+ material: dryerMaterial,
4520
+ nominalSize: '4"',
4521
+ path: bestDryerRoute.path,
4522
+ slopeInPerFt: 0,
4523
+ dfuLoad: 0,
4524
+ wsfuLoad: 0,
4525
+ gasBtuh: 0,
4526
+ sourceNodeId: dryer.sourceId,
4527
+ hasCleanout: false,
4528
+ hasSedimentTrap: false,
4529
+ hasShutoffWithin6Ft: false,
4530
+ isHorizontalSanTee: false,
4531
+ isMainVentStack: false,
4532
+ })
4533
+ linkedInThisSync.add(dryer.sourceId)
4534
+ connectedFixtures += 1
4535
+ }
4536
+ }
4537
+ }
4538
+ }
4539
+
4540
+ // Silence unused variable lint if levelPipes isn't directly read after ctx destructuring
4541
+ void levelPipes
4542
+
4543
+ const newlyLinkedFurnishings = linkedInThisSync.size
4544
+ return {
4545
+ fellBackToFullAutoPopulate: false,
4546
+ fixtures: newFixtures,
4547
+ pipeRuns: allPipeRuns,
4548
+ newlyLinkedFurnishings,
4549
+ connectedFixtures,
4550
+ summary:
4551
+ newFixtures.length === 0 && allPipeRuns.length === 0
4552
+ ? 'All placed furnishings and plumbing fixtures on this level are already connected.'
4553
+ : `Synced ${newlyLinkedFurnishings} real-world fixture(s) (${newFixtures.length} rough-in(s)) and routed ${allPipeRuns.length} supply/DWV/vent pipe run(s) across ${connectedFixtures} fixture(s).`,
4554
+ }
4555
+ }