@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,842 @@
1
+ /**
2
+ * Pure TypeScript interoperability helpers for:
3
+ * 1. Pascal's `@pascal-app/plugin-bones` (`bones:framing` and `bones:service` nodes)
4
+ * 2. Cross-trade electrical power coordination (`electricalDemand` contract shared with
5
+ * `@kruschdev/pascal-plugin-electrical` and future `@kruschdev/pascal-plugin-hvac`)
6
+ *
7
+ * Framework-free: zero React, Three.js, or `@pascal-app/*` imports.
8
+ */
9
+
10
+ import {
11
+ belongsToLevel as kernelBelongsToLevel,
12
+ getLowerWalledLevelIds as kernelGetLowerWalledLevelIds,
13
+ isGroundOrLowestWalledLevel as kernelIsGroundOrLowestWalledLevel,
14
+ resolveNodeLevelId as kernelResolveNodeLevelId,
15
+ } from '@kruschdev/pascal-mep-kernel'
16
+ import { IPC_RULE_THRESHOLDS } from './rules'
17
+ import {
18
+ type EquipmentKind,
19
+ type FixtureKind,
20
+ INCHES_TO_METERS,
21
+ METERS_TO_INCHES,
22
+ type PipeMaterial,
23
+ type PipeNominalSize,
24
+ getPipeOuterDiameterM,
25
+ } from './tables'
26
+
27
+ export type Vec3 = readonly [number, number, number]
28
+
29
+ export type SceneNodeLike = {
30
+ id: string
31
+ type: string
32
+ name?: string
33
+ parentId?: string | null
34
+ position?: readonly [number, number, number]
35
+ rotation?: number | readonly [number, number, number]
36
+ start?: readonly [number, number]
37
+ end?: readonly [number, number]
38
+ height?: number
39
+ thickness?: number
40
+ width?: number
41
+ depth?: number
42
+ polygon?: ReadonlyArray<readonly [number, number]>
43
+ path?: ReadonlyArray<readonly [number, number, number]>
44
+ children?: readonly string[]
45
+ [key: string]: unknown
46
+ }
47
+
48
+ /**
49
+ * Standardized cross-trade electrical power demand payload published by powered
50
+ * plumbing (and future HVAC) equipment/fixture nodes so `@kruschdev/pascal-plugin-electrical`
51
+ * can automatically allocate breakers, panel schedules, NEC 220 loads, and 3D power runs
52
+ * with zero hard package dependency.
53
+ */
54
+ export type ElectricalPowerDemand = {
55
+ required: boolean
56
+ voltage: 120 | 208 | 240 | 480
57
+ poles: 1 | 2 | 3
58
+ breakerAmps: number
59
+ loadVa: number
60
+ continuous: boolean
61
+ dedicatedCircuit: boolean
62
+ gfciRequired: boolean
63
+ afciRequired: boolean
64
+ loadCategory: 'fixed' | 'appliance' | 'motor' | 'hvac-heating' | 'hvac-cooling' | 'heat-pump'
65
+ label: string
66
+ }
67
+
68
+ const NEC_STANDARD_BREAKERS = [
69
+ 15, 20, 25, 30, 35, 40, 45, 50, 60, 70, 80, 90, 100, 125, 150, 175, 200, 225, 250, 300, 350, 400,
70
+ ] as const
71
+
72
+ /**
73
+ * Compute minimum NEC 240.6(A) standard breaker rating for a continuous water-heating/equipment load
74
+ * per NEC 422.11(E) / 422.13 (125% of nameplate current).
75
+ */
76
+ export function standardNec240BreakerAmps(watts: number, voltage = 240): number {
77
+ const minAmps = (Math.max(100, watts) / voltage) * 1.25
78
+ for (const std of NEC_STANDARD_BREAKERS) {
79
+ if (std >= minAmps) return std
80
+ }
81
+ return Math.ceil(minAmps / 50) * 50
82
+ }
83
+
84
+ /**
85
+ * Default NEC-compliant electrical power demands for powered plumbing equipment.
86
+ */
87
+ export function getEquipmentElectricalDemand(
88
+ kind: EquipmentKind,
89
+ customWatts?: number,
90
+ ): ElectricalPowerDemand | null {
91
+ switch (kind) {
92
+ case 'water-heater-tank-electric': {
93
+ const watts = customWatts && customWatts > 0 ? customWatts : 4500
94
+ const amps = Math.max(30, standardNec240BreakerAmps(watts, 240))
95
+ return {
96
+ required: true,
97
+ voltage: 240,
98
+ poles: 2,
99
+ breakerAmps: amps,
100
+ loadVa: watts,
101
+ continuous: true,
102
+ dedicatedCircuit: true,
103
+ gfciRequired: false,
104
+ afciRequired: false,
105
+ loadCategory: 'fixed',
106
+ label: `Electric Water Heater (${(watts / 1000).toFixed(1)} kW)`,
107
+ }
108
+ }
109
+ case 'water-heater-hpwh': {
110
+ const watts = customWatts && customWatts > 0 ? customWatts : 4500
111
+ const amps = Math.max(30, standardNec240BreakerAmps(watts, 240))
112
+ return {
113
+ required: true,
114
+ voltage: 240,
115
+ poles: 2,
116
+ breakerAmps: amps,
117
+ loadVa: watts,
118
+ continuous: true,
119
+ dedicatedCircuit: true,
120
+ gfciRequired: false,
121
+ afciRequired: false,
122
+ loadCategory: 'fixed',
123
+ label: 'Heat Pump Water Heater (Hybrid)',
124
+ }
125
+ }
126
+ case 'water-heater-tankless-gas': {
127
+ const watts = customWatts && customWatts > 0 ? customWatts : 300
128
+ const amps = Math.max(15, standardNec240BreakerAmps(watts, 120))
129
+ return {
130
+ required: true,
131
+ voltage: 120,
132
+ poles: 1,
133
+ breakerAmps: amps,
134
+ loadVa: watts,
135
+ continuous: false,
136
+ dedicatedCircuit: false,
137
+ gfciRequired: true,
138
+ afciRequired: false,
139
+ loadCategory: 'appliance',
140
+ label: 'Tankless Gas WH Ignition / Blower',
141
+ }
142
+ }
143
+ case 'sump-pump': {
144
+ const watts = customWatts && customWatts > 0 ? customWatts : 1200
145
+ const amps = Math.max(20, standardNec240BreakerAmps(watts, 120))
146
+ return {
147
+ required: true,
148
+ voltage: 120,
149
+ poles: 1,
150
+ breakerAmps: amps,
151
+ loadVa: watts,
152
+ continuous: false,
153
+ dedicatedCircuit: true,
154
+ gfciRequired: true,
155
+ afciRequired: false,
156
+ loadCategory: 'motor',
157
+ label: 'Sump Pump (Dedicated GFCI)',
158
+ }
159
+ }
160
+ case 'sewage-ejector': {
161
+ const watts = customWatts && customWatts > 0 ? customWatts : 1440
162
+ const amps = Math.max(20, standardNec240BreakerAmps(watts, 120))
163
+ return {
164
+ required: true,
165
+ voltage: 120,
166
+ poles: 1,
167
+ breakerAmps: amps,
168
+ loadVa: watts,
169
+ continuous: false,
170
+ dedicatedCircuit: true,
171
+ gfciRequired: true,
172
+ afciRequired: false,
173
+ loadCategory: 'motor',
174
+ label: 'Sewage Ejector Pump (Dedicated GFCI)',
175
+ }
176
+ }
177
+ case 'recirc-pump': {
178
+ const watts = customWatts && customWatts > 0 ? customWatts : 180
179
+ const amps = Math.max(15, standardNec240BreakerAmps(watts, 120))
180
+ return {
181
+ required: true,
182
+ voltage: 120,
183
+ poles: 1,
184
+ breakerAmps: amps,
185
+ loadVa: watts,
186
+ continuous: true,
187
+ dedicatedCircuit: false,
188
+ gfciRequired: true,
189
+ afciRequired: false,
190
+ loadCategory: 'motor',
191
+ label: 'Hot Water Recirculation Pump',
192
+ }
193
+ }
194
+ case 'water-softener': {
195
+ const watts = customWatts && customWatts > 0 ? customWatts : 150
196
+ const amps = Math.max(15, standardNec240BreakerAmps(watts, 120))
197
+ return {
198
+ required: true,
199
+ voltage: 120,
200
+ poles: 1,
201
+ breakerAmps: amps,
202
+ loadVa: watts,
203
+ continuous: false,
204
+ dedicatedCircuit: false,
205
+ gfciRequired: true,
206
+ afciRequired: false,
207
+ loadCategory: 'appliance',
208
+ label: 'Water Softener Control Head',
209
+ }
210
+ }
211
+ default:
212
+ return null
213
+ }
214
+ }
215
+
216
+ /**
217
+ * Default NEC-compliant electrical power demands for powered plumbing fixtures.
218
+ */
219
+ export function getFixtureElectricalDemand(kind: FixtureKind): ElectricalPowerDemand | null {
220
+ switch (kind) {
221
+ case 'dishwasher':
222
+ return {
223
+ required: true,
224
+ voltage: 120,
225
+ poles: 1,
226
+ breakerAmps: 20,
227
+ loadVa: 1500,
228
+ continuous: false,
229
+ dedicatedCircuit: true,
230
+ gfciRequired: true,
231
+ afciRequired: true,
232
+ loadCategory: 'appliance',
233
+ label: 'Dishwasher (NEC 210.8(D) GFCI)',
234
+ }
235
+ case 'garbage-disposal':
236
+ return {
237
+ required: true,
238
+ voltage: 120,
239
+ poles: 1,
240
+ breakerAmps: 20,
241
+ loadVa: 1000,
242
+ continuous: false,
243
+ dedicatedCircuit: true,
244
+ gfciRequired: true,
245
+ afciRequired: true,
246
+ loadCategory: 'appliance',
247
+ label: 'Garbage Disposal (3/4 HP)',
248
+ }
249
+ case 'clothes-washer':
250
+ return {
251
+ required: true,
252
+ voltage: 120,
253
+ poles: 1,
254
+ breakerAmps: 20,
255
+ loadVa: 1500,
256
+ continuous: false,
257
+ dedicatedCircuit: true,
258
+ gfciRequired: true,
259
+ afciRequired: true,
260
+ loadCategory: 'appliance',
261
+ label: 'Laundry Washer Branch (NEC 210.11(C)(2))',
262
+ }
263
+ case 'bidet':
264
+ return {
265
+ required: true,
266
+ voltage: 120,
267
+ poles: 1,
268
+ breakerAmps: 15,
269
+ loadVa: 1200,
270
+ continuous: false,
271
+ dedicatedCircuit: true, // NEC 210.23(B)(2): 1200 VA > 50% of 15A branch rating
272
+ gfciRequired: true,
273
+ afciRequired: false,
274
+ loadCategory: 'appliance',
275
+ label: 'Heated Bidet Seat (Dedicated GFCI)',
276
+ }
277
+ default:
278
+ return null
279
+ }
280
+ }
281
+
282
+ export type BonesWallConstruction = 'framed' | 'lgs' | 'cmu' | 'skip'
283
+
284
+ export type BonesWallRule = {
285
+ construction: BonesWallConstruction
286
+ spacingIn: 12 | 16 | 24
287
+ studThicknessM: number
288
+ /** Per-wall stud cavity depth in inches from `structural:assembly.wallOverrides[id].studSize` (`5.5` for 2x6, `3.5` for 2x4). */
289
+ studDepthIn?: number
290
+ isLoadBearing?: boolean
291
+ isWetWall?: boolean
292
+ }
293
+
294
+ export type BonesPlumbingServiceType = 'water-heater' | 'water-entry' | 'sewer-exit'
295
+
296
+ export type BonesPlumbingServiceAnchor = {
297
+ nodeId: string
298
+ serviceType: BonesPlumbingServiceType
299
+ wallId?: string
300
+ wallT?: number
301
+ heightAff?: number
302
+ position?: Vec3
303
+ }
304
+
305
+ export type BonesPlumbingContext = {
306
+ framingPresent: boolean
307
+ /** Authoritative source of framing rules (`structural` takes Priority #1 over `bones`). */
308
+ source?: 'structural' | 'bones' | 'default'
309
+ defaultSpacingIn: 12 | 16 | 24
310
+ /** Authoritative stud cavity depth in inches from Priority #1 `structural:assembly` (`5.5` for 2x6, `3.5` for 2x4). */
311
+ defaultStudDepthIn?: number
312
+ framingSystem: 'lumber' | 'lgs'
313
+ floorSystem?: 'dimensional' | 'tji-ijoist' | 'open-web-truss'
314
+ wallRules: ReadonlyMap<string, BonesWallRule>
315
+ waterHeaterAnchor: BonesPlumbingServiceAnchor | null
316
+ waterEntryAnchor: BonesPlumbingServiceAnchor | null
317
+ sewerExitAnchor: BonesPlumbingServiceAnchor | null
318
+ hasPlumbingSchematic: boolean
319
+ }
320
+
321
+ export const DRESSED_STUD_THICKNESS_M = 1.5 * INCHES_TO_METERS
322
+ /** Standard 2x4 cavity depth = 3.5" (0.0889 m); finished 2x4 wall = ~4.5" (0.114 m). */
323
+ export const WALL_2X4_MAX_THICKNESS_M = IPC_RULE_THRESHOLDS.wetWallMax2x4ThicknessM
324
+ /** Standard 2x6 cavity depth = 5.5" (0.1397 m); finished 2x6 wall = ~6.5" (0.165 m). */
325
+ export const WALL_2X6_MIN_THICKNESS_M = IPC_RULE_THRESHOLDS.wetWallMinThicknessM
326
+
327
+ export function belongsToLevel(
328
+ nodes: Readonly<Record<string, SceneNodeLike>>,
329
+ node: SceneNodeLike,
330
+ levelId: string | null,
331
+ ): boolean {
332
+ return kernelBelongsToLevel(nodes, node, levelId)
333
+ }
334
+
335
+ export function resolveNodeLevelId(
336
+ nodes: Readonly<Record<string, SceneNodeLike>>,
337
+ node: SceneNodeLike,
338
+ ): string | null {
339
+ return kernelResolveNodeLevelId(nodes, node)
340
+ }
341
+
342
+ /**
343
+ * Return the IDs of all lower walled sibling levels in the same building as `levelId`,
344
+ * sorted from lowest to highest story. Returns an empty array when `levelId` is null/missing
345
+ * or is already the lowest walled level in its building.
346
+ */
347
+ export function getLowerWalledLevelIds(
348
+ nodes: Readonly<Record<string, SceneNodeLike>>,
349
+ levelId: string | null | undefined,
350
+ ): string[] {
351
+ return kernelGetLowerWalledLevelIds(nodes, levelId)
352
+ }
353
+
354
+ /**
355
+ * Returns `true` if `levelId` is null/missing, has no lower walled sibling levels in the same
356
+ * building, or is the lowest walled level in its building. Returns `false` for upper stories
357
+ * (e.g. Floor 1 / Floor 2) when a lower walled ground story exists in the same building.
358
+ */
359
+ export function isGroundOrLowestWalledLevel(
360
+ nodes: Readonly<Record<string, SceneNodeLike>>,
361
+ levelId: string | null | undefined,
362
+ ): boolean {
363
+ return kernelIsGroundOrLowestWalledLevel(nodes, levelId)
364
+ }
365
+
366
+ const bonesContextCache = new WeakMap<
367
+ Readonly<Record<string, SceneNodeLike>>,
368
+ Map<string, BonesPlumbingContext>
369
+ >()
370
+
371
+ /**
372
+ * Extract `@pascal-app/plugin-bones` framing rules and authoritative `bones:service` plumbing anchors
373
+ * (`water-heater`, `water-entry`, `sewer-exit`) for a level. WeakMap-memoized per scene nodes object.
374
+ */
375
+ export function extractBonesPlumbingContext(
376
+ nodes: Readonly<Record<string, SceneNodeLike>>,
377
+ levelId: string | null = null,
378
+ ): BonesPlumbingContext {
379
+ const key = levelId ?? '__all__'
380
+ let byLevel = bonesContextCache.get(nodes)
381
+ if (!byLevel) {
382
+ byLevel = new Map()
383
+ bonesContextCache.set(nodes, byLevel)
384
+ }
385
+ const cached = byLevel.get(key)
386
+ if (cached) return cached
387
+
388
+ const all = Object.values(nodes)
389
+ // Priority #1: Dedicated `@kruschdev/pascal-plugin-structural` (`structural:assembly`) takes precedence over `bones:framing`.
390
+ const structuralNode = all.find(
391
+ (n) => n.type === 'structural:assembly' && belongsToLevel(nodes, n, levelId),
392
+ )
393
+ const bonesNode = all.find(
394
+ (n) => n.type === 'bones:framing' && belongsToLevel(nodes, n, levelId),
395
+ )
396
+ const framingNode = structuralNode ?? bonesNode
397
+ const source: 'structural' | 'bones' | 'default' = structuralNode
398
+ ? 'structural'
399
+ : bonesNode
400
+ ? 'bones'
401
+ : 'default'
402
+
403
+ const defaultSpacingIn: 12 | 16 | 24 =
404
+ framingNode?.studSpacingIn === 12
405
+ ? 12
406
+ : framingNode?.studSpacingIn === 24
407
+ ? 24
408
+ : 16
409
+ const defaultStudDepthIn: number | undefined =
410
+ structuralNode?.studSize === '2x6'
411
+ ? 5.5
412
+ : structuralNode?.studSize === '2x4'
413
+ ? 3.5
414
+ : undefined
415
+ const framingSystem: 'lumber' | 'lgs' = framingNode?.framingSystem === 'lgs' ? 'lgs' : 'lumber'
416
+ const floorSystem =
417
+ structuralNode?.floorSystem === 'tji-ijoist' ||
418
+ structuralNode?.floorSystem === 'open-web-truss' ||
419
+ structuralNode?.floorSystem === 'dimensional'
420
+ ? structuralNode.floorSystem
421
+ : undefined
422
+ const wallRules = new Map<string, BonesWallRule>()
423
+
424
+ const defaultConstruction: BonesWallConstruction = framingSystem === 'lgs' ? 'lgs' : 'framed'
425
+ const applyOverrides = (rawOverrides: unknown) => {
426
+ if (!rawOverrides || typeof rawOverrides !== 'object') return
427
+ for (const [wallId, rawRule] of Object.entries(rawOverrides as Record<string, unknown>)) {
428
+ if (typeof rawRule === 'string') {
429
+ const construction: BonesWallConstruction =
430
+ rawRule === 'lgs' || rawRule === 'cmu' || rawRule === 'skip'
431
+ ? rawRule
432
+ : rawRule === 'framed'
433
+ ? 'framed'
434
+ : defaultConstruction
435
+ wallRules.set(wallId, {
436
+ construction,
437
+ spacingIn: defaultSpacingIn,
438
+ studThicknessM: DRESSED_STUD_THICKNESS_M,
439
+ isLoadBearing: rawRule === 'shear-wall',
440
+ isWetWall: false,
441
+ })
442
+ continue
443
+ }
444
+ if (!rawRule || typeof rawRule !== 'object') continue
445
+ const r = rawRule as Record<string, unknown>
446
+ const prev = wallRules.get(wallId)
447
+ const construction: BonesWallConstruction =
448
+ r.construction === 'lgs' || r.construction === 'cmu' || r.construction === 'skip'
449
+ ? r.construction
450
+ : r.construction === 'framed'
451
+ ? 'framed'
452
+ : (prev?.construction ?? defaultConstruction)
453
+ const rawSpacing = r.studSpacingIn ?? r.spacingIn
454
+ const spacingIn: 12 | 16 | 24 =
455
+ rawSpacing === 12
456
+ ? 12
457
+ : rawSpacing === 16
458
+ ? 16
459
+ : rawSpacing === 24
460
+ ? 24
461
+ : (prev?.spacingIn ?? defaultSpacingIn)
462
+ const studDepthIn: number | undefined =
463
+ r.studSize === '2x6' ? 5.5 : r.studSize === '2x4' ? 3.5 : prev?.studDepthIn
464
+ wallRules.set(wallId, {
465
+ construction,
466
+ spacingIn,
467
+ studThicknessM: DRESSED_STUD_THICKNESS_M,
468
+ ...(typeof studDepthIn === 'number' ? { studDepthIn } : {}),
469
+ isLoadBearing:
470
+ r.isLoadBearing !== undefined || r.isShearWall !== undefined || r.construction === 'shear-wall'
471
+ ? Boolean(r.isLoadBearing || r.isShearWall || r.construction === 'shear-wall')
472
+ : Boolean(prev?.isLoadBearing),
473
+ isWetWall: r.isWetWall !== undefined ? Boolean(r.isWetWall) : Boolean(prev?.isWetWall),
474
+ })
475
+ }
476
+ }
477
+ // Seed per-wall Bones overrides first, then layer Priority #1 Structural overrides on top
478
+ applyOverrides(bonesNode?.wallOverrides)
479
+ applyOverrides(structuralNode?.wallOverrides)
480
+
481
+ let waterHeaterAnchor: BonesPlumbingServiceAnchor | null = null
482
+ let waterEntryAnchor: BonesPlumbingServiceAnchor | null = null
483
+ let sewerExitAnchor: BonesPlumbingServiceAnchor | null = null
484
+
485
+ for (const n of all) {
486
+ if (n.type !== 'bones:service' || !belongsToLevel(nodes, n, levelId)) continue
487
+ const st = n.serviceType
488
+ if (st !== 'water-heater' && st !== 'water-entry' && st !== 'sewer-exit') continue
489
+ const rawPos = Array.isArray(n.position) && n.position.length >= 3
490
+ ? ([Number(n.position[0]), Number(n.position[1]), Number(n.position[2])] as Vec3)
491
+ : undefined
492
+ const pos =
493
+ rawPos &&
494
+ Number.isFinite(rawPos[0]) &&
495
+ Number.isFinite(rawPos[1]) &&
496
+ Number.isFinite(rawPos[2])
497
+ ? rawPos
498
+ : undefined
499
+ const anchor: BonesPlumbingServiceAnchor = {
500
+ nodeId: n.id,
501
+ serviceType: st,
502
+ wallId: typeof n.wallId === 'string' ? n.wallId : undefined,
503
+ wallT: typeof n.wallT === 'number' ? n.wallT : undefined,
504
+ heightAff: typeof n.heightAff === 'number' ? n.heightAff : undefined,
505
+ position: pos,
506
+ }
507
+ if (st === 'water-heater' && !waterHeaterAnchor) waterHeaterAnchor = anchor
508
+ if (st === 'water-entry' && !waterEntryAnchor) waterEntryAnchor = anchor
509
+ if (st === 'sewer-exit' && !sewerExitAnchor) sewerExitAnchor = anchor
510
+ }
511
+
512
+ const ctx: BonesPlumbingContext = {
513
+ framingPresent: Boolean(framingNode),
514
+ source,
515
+ defaultSpacingIn,
516
+ defaultStudDepthIn,
517
+ framingSystem,
518
+ floorSystem,
519
+ wallRules,
520
+ waterHeaterAnchor,
521
+ waterEntryAnchor,
522
+ sewerExitAnchor,
523
+ hasPlumbingSchematic: Boolean(waterHeaterAnchor || waterEntryAnchor || sewerExitAnchor),
524
+ }
525
+ byLevel.set(key, ctx)
526
+ return ctx
527
+ }
528
+
529
+ /**
530
+ * Resolve effective wall thickness (m) honoring per-wall `structural:assembly` `wallOverrides[id].studSize`
531
+ * first (without inflating a `2x4` interior partition to a global `2x6` default), falling back to global
532
+ * `defaultStudDepthIn` when no per-wall override is present.
533
+ */
534
+ export function resolveEffectiveWallThicknessM(
535
+ wallThicknessM: number,
536
+ bonesContext?: BonesPlumbingContext | null,
537
+ wallRule?: BonesWallRule,
538
+ ): number {
539
+ if (typeof wallRule?.studDepthIn === 'number') {
540
+ return wallRule.studDepthIn * INCHES_TO_METERS + INCHES_TO_METERS
541
+ }
542
+ if (bonesContext?.source === 'structural' && typeof bonesContext.defaultStudDepthIn === 'number') {
543
+ return Math.max(wallThicknessM, bonesContext.defaultStudDepthIn * INCHES_TO_METERS + INCHES_TO_METERS)
544
+ }
545
+ return wallThicknessM
546
+ }
547
+
548
+ /**
549
+ * IRC R602.6 / IPC wet-wall cavity check:
550
+ * - A 3" or 4" PVC/ABS DWV pipe (3.5" / 4.5" OD + hub) cannot fit inside a 2x4 stud wall (3.5" cavity).
551
+ * - Boring through load-bearing studs is limited to 40% of stud depth (60% non-load-bearing), measured on drilled hole diameter.
552
+ * - Steel nail shield plates are required when the edge of the bored hole is < 1-1/4" (1.25") from the stud face (IRC R602.6 / IPC 305.6).
553
+ */
554
+ export function checkWetWallPipeFit(params: {
555
+ wallThicknessM: number
556
+ pipeSize: PipeNominalSize
557
+ material: PipeMaterial
558
+ isLoadBearing?: boolean
559
+ isHorizontalBore?: boolean
560
+ }): {
561
+ fits: boolean
562
+ needs2x6WetWall: boolean
563
+ needsNailPlate: boolean
564
+ borePctOfStud: number
565
+ codeRef: string
566
+ reason?: string
567
+ } {
568
+ const {
569
+ wallThicknessM,
570
+ pipeSize,
571
+ material,
572
+ isLoadBearing = false,
573
+ isHorizontalBore = false,
574
+ } = params
575
+ // Approximate stud cavity depth = wallThickness - 1" total drywall (0.0254 m)
576
+ const cavityDepthM = Math.max(0.0889, wallThicknessM - 0.0254)
577
+ const pipeOdM = getPipeOuterDiameterM(pipeSize, material)
578
+ const boreM = recommendHoleSawIn(pipeSize, material) * INCHES_TO_METERS
579
+ const hubAllowanceM = material === 'pvc-dwv' || material === 'abs-dwv' || material === 'cast-iron' ? 0.014 : 0
580
+ const requiredCavityM = pipeOdM + hubAllowanceM
581
+ const borePct = Math.round(((isHorizontalBore ? boreM : pipeOdM) / cavityDepthM) * 100)
582
+ const maxBorePct = isLoadBearing ? 40 : 60
583
+ const needsNailPlate = (cavityDepthM - boreM) / 2 < 1.25 * INCHES_TO_METERS
584
+
585
+ if (requiredCavityM > cavityDepthM + 0.002) {
586
+ return {
587
+ fits: false,
588
+ needs2x6WetWall: true,
589
+ needsNailPlate: true,
590
+ borePctOfStud: borePct,
591
+ codeRef: 'IRC R602.6 / Wet Wall',
592
+ reason: `${pipeSize} ${material.toUpperCase()} (${(requiredCavityM * METERS_TO_INCHES).toFixed(2)}" w/ hub) exceeds ${(cavityDepthM * METERS_TO_INCHES).toFixed(1)}" stud cavity; upgrade to 2x6 wet wall (5.5" cavity) or pipe chase.`,
593
+ }
594
+ }
595
+
596
+ if (isHorizontalBore && borePct > maxBorePct) {
597
+ return {
598
+ fits: false,
599
+ needs2x6WetWall: cavityDepthM < 0.13,
600
+ needsNailPlate,
601
+ borePctOfStud: borePct,
602
+ codeRef: 'IRC R602.6',
603
+ reason: `Horizontal bore (${(boreM / INCHES_TO_METERS).toFixed(2)}" hole = ${borePct}% of stud depth) exceeds ${maxBorePct}% ${isLoadBearing ? 'load-bearing' : 'non-load-bearing'} limit.`,
604
+ }
605
+ }
606
+
607
+ return {
608
+ fits: true,
609
+ needs2x6WetWall: false,
610
+ needsNailPlate,
611
+ borePctOfStud: borePct,
612
+ codeRef: 'IRC R602.6',
613
+ }
614
+ }
615
+
616
+ /**
617
+ * Resolve a `bones:service` anchor into level-local 3D coordinates using wall geometry when wall-anchored.
618
+ */
619
+ export function resolveBonesAnchorPosition(
620
+ nodes: Readonly<Record<string, SceneNodeLike>>,
621
+ anchor: BonesPlumbingServiceAnchor,
622
+ fallbackY = 0,
623
+ ): Vec3 | null {
624
+ const pos = anchor.position
625
+ const hasExplicitPos =
626
+ pos && (Math.abs(pos[0]) > 1e-4 || Math.abs(pos[1]) > 1e-4 || Math.abs(pos[2]) > 1e-4)
627
+ if (hasExplicitPos) {
628
+ return pos
629
+ }
630
+ if (anchor.wallId && nodes[anchor.wallId]) {
631
+ const w = nodes[anchor.wallId]!
632
+ if (Array.isArray(w.start) && Array.isArray(w.end)) {
633
+ const t = typeof anchor.wallT === 'number' ? Math.max(0.05, Math.min(0.95, anchor.wallT)) : 0.5
634
+ const x = w.start[0] + (w.end[0] - w.start[0]) * t
635
+ const z = w.start[1] + (w.end[1] - w.start[1]) * t
636
+ const y = typeof anchor.heightAff === 'number' ? anchor.heightAff : fallbackY
637
+ return [x, y, z]
638
+ }
639
+ }
640
+ return pos ?? null
641
+ }
642
+
643
+ export type FramingMemberKind = 'stud' | 'sole-plate' | 'top-plate' | 'floor-joist'
644
+
645
+ export type FramingPenetration = {
646
+ id: string
647
+ pipeRunId: string
648
+ wallId?: string
649
+ memberKind: FramingMemberKind
650
+ memberLabel: string
651
+ position: Vec3
652
+ /** Direction vector along the pipe at penetration (unit vector). */
653
+ pipeDirection: Vec3
654
+ /** Unit normal `[nx, nz]` perpendicular to the penetrated wall plane for nail-plate orientation. */
655
+ wallNormal: readonly [number, number]
656
+ /** Nominal stud cavity depth (m) for accurate front/back nail-plate surface offset. */
657
+ studDepthM: number
658
+ pipeSize: PipeNominalSize
659
+ material: PipeMaterial
660
+ /** Recommended drill bit / hole-saw diameter in inches (OD + 1/4" clearance, rounded to 1/8"). */
661
+ holeSawIn: number
662
+ borePctOfStud: number
663
+ needsNailPlate: boolean
664
+ codeCompliant: boolean
665
+ codeRef: string
666
+ note?: string
667
+ }
668
+
669
+ /**
670
+ * Compute recommended hole-saw / auger-bit diameter (inches) for a nominal pipe & material.
671
+ */
672
+ export function recommendHoleSawIn(pipeSize: PipeNominalSize, material: PipeMaterial): number {
673
+ const odIn = getPipeOuterDiameterM(pipeSize, material) / INCHES_TO_METERS
674
+ const clearance = odIn >= 1.5 ? 0.25 : 0.1875
675
+ return Math.ceil((odIn + clearance) * 8) / 8
676
+ }
677
+
678
+ /**
679
+ * Compute exact 3D stud, sole-plate, and top-plate penetrations where a pipe run
680
+ * crosses `@pascal-app/plugin-bones` framing members (16" or 24" OC studs + plates).
681
+ */
682
+ export function computePipeFramingPenetrations(params: {
683
+ pipeRunId: string
684
+ path: ReadonlyArray<Vec3>
685
+ pipeSize: PipeNominalSize
686
+ material: PipeMaterial
687
+ walls: ReadonlyArray<{
688
+ id: string
689
+ start: readonly [number, number]
690
+ end: readonly [number, number]
691
+ lengthM: number
692
+ thicknessM: number
693
+ heightM: number
694
+ ux: number
695
+ uz: number
696
+ nx: number
697
+ nz: number
698
+ }>
699
+ bonesContext?: BonesPlumbingContext | null
700
+ }): FramingPenetration[] {
701
+ const { pipeRunId, path, pipeSize, material, walls, bonesContext } = params
702
+ if (path.length < 2) return []
703
+
704
+ const penetrations: FramingPenetration[] = []
705
+ const holeSawIn = recommendHoleSawIn(pipeSize, material)
706
+ const defaultSpacingIn = bonesContext?.defaultSpacingIn ?? 16
707
+ let seq = 1
708
+
709
+ for (let i = 1; i < path.length; i++) {
710
+ const a = path[i - 1]!
711
+ const b = path[i]!
712
+ const dx = b[0] - a[0]
713
+ const dy = b[1] - a[1]
714
+ const dz = b[2] - a[2]
715
+ const segLen = Math.hypot(dx, dy, dz)
716
+ if (segLen < 0.02) continue
717
+ const dir: Vec3 = [dx / segLen, dy / segLen, dz / segLen]
718
+
719
+ for (const wall of walls) {
720
+ const rule = bonesContext?.wallRules.get(wall.id)
721
+ if (rule?.construction === 'skip' || rule?.construction === 'cmu') continue
722
+ const spacingM = (rule?.spacingIn ?? defaultSpacingIn) * INCHES_TO_METERS
723
+ const effectiveWallThicknessM = resolveEffectiveWallThicknessM(wall.thicknessM, bonesContext, rule)
724
+ const studDepthM = Math.max(0.0889, effectiveWallThicknessM - INCHES_TO_METERS)
725
+ const halfThick = effectiveWallThicknessM / 2 + 0.04
726
+
727
+ // Project endpoints into wall-local coordinates (u along wall, n perpendicular to wall)
728
+ const ua = (a[0] - wall.start[0]) * wall.ux + (a[2] - wall.start[1]) * wall.uz
729
+ const na = (a[0] - wall.start[0]) * wall.nx + (a[2] - wall.start[1]) * wall.nz
730
+ const ub = (b[0] - wall.start[0]) * wall.ux + (b[2] - wall.start[1]) * wall.uz
731
+ const nb = (b[0] - wall.start[0]) * wall.nx + (b[2] - wall.start[1]) * wall.nz
732
+
733
+ // Check if segment travels inside or right along this wall cavity
734
+ const minAbsN = Math.min(Math.abs(na), Math.abs(nb))
735
+ const crossesWallPlane = na * nb <= 0
736
+ if (minAbsN > halfThick && !crossesWallPlane) continue
737
+
738
+ const uMin = Math.min(ua, ub)
739
+ const uMax = Math.max(ua, ub)
740
+ if (uMax < 0 || uMin > wall.lengthM) continue
741
+
742
+ // 1. Vertical crossings of Sole Plate (y = 0.02 m) and Double Top Plate (y = wall.heightM - 0.04 m)
743
+ const yMin = Math.min(a[1], b[1])
744
+ const yMax = Math.max(a[1], b[1])
745
+ if (Math.abs(dy) > 0.05) {
746
+ const plateHeights: Array<{ kind: FramingMemberKind; label: string; y: number }> = [
747
+ { kind: 'sole-plate', label: `Sole Plate (${wall.id})`, y: 0.02 },
748
+ { kind: 'top-plate', label: `Double Top Plate (${wall.id})`, y: wall.heightM - 0.04 },
749
+ ]
750
+ for (const plate of plateHeights) {
751
+ if (yMin <= plate.y && yMax >= plate.y) {
752
+ const t = (plate.y - a[1]) / dy
753
+ if ((i === 1 ? t < 0 : t <= 1e-6) || t > 1) continue
754
+ const px = a[0] + dx * t
755
+ const pz = a[2] + dz * t
756
+ const pu = (px - wall.start[0]) * wall.ux + (pz - wall.start[1]) * wall.uz
757
+ const pn = Math.abs((px - wall.start[0]) * wall.nx + (pz - wall.start[1]) * wall.nz)
758
+ if (pu >= 0 && pu <= wall.lengthM && pn <= halfThick) {
759
+ const fit = checkWetWallPipeFit({
760
+ wallThicknessM: effectiveWallThicknessM,
761
+ pipeSize,
762
+ material,
763
+ isLoadBearing: rule?.isLoadBearing ?? false,
764
+ isHorizontalBore: false,
765
+ })
766
+ const firestopNote =
767
+ bonesContext?.source === 'structural'
768
+ ? 'IRC R302.11(5) firestop collar / intumescent caulk required at plate penetration.'
769
+ : undefined
770
+ penetrations.push({
771
+ id: `${pipeRunId}_pen_${seq++}`,
772
+ pipeRunId,
773
+ wallId: wall.id,
774
+ memberKind: plate.kind,
775
+ memberLabel: plate.label,
776
+ position: [px, plate.y, pz],
777
+ pipeDirection: dir,
778
+ wallNormal: [wall.nx, wall.nz],
779
+ studDepthM,
780
+ pipeSize,
781
+ material,
782
+ holeSawIn,
783
+ borePctOfStud: fit.borePctOfStud,
784
+ needsNailPlate: fit.needsNailPlate,
785
+ codeCompliant: fit.fits,
786
+ codeRef: bonesContext?.source === 'structural' ? 'IRC R602.6 / R302.11(5)' : fit.codeRef,
787
+ note: [fit.reason, firestopNote].filter(Boolean).join(' ') || undefined,
788
+ })
789
+ }
790
+ }
791
+ }
792
+ }
793
+
794
+ // 2. Horizontal crossings of individual 16"/24" OC wall studs
795
+ const du = ub - ua
796
+ if (Math.abs(du) > 0.05 && yMax > 0.05 && yMin < wall.heightM - 0.08) {
797
+ const firstIdx = Math.max(1, Math.ceil(uMin / spacingM))
798
+ const lastIdx = Math.min(Math.floor((wall.lengthM - 0.05) / spacingM), Math.floor(uMax / spacingM))
799
+ for (let studIdx = firstIdx; studIdx <= lastIdx; studIdx++) {
800
+ const studU = studIdx * spacingM
801
+ const t = (studU - ua) / du
802
+ if ((i === 1 ? t < 0 : t <= 1e-6) || t > 1) continue
803
+ const py = a[1] + dy * t
804
+ if (py <= 0.05 || py >= wall.heightM - 0.08) continue
805
+ const px = a[0] + dx * t
806
+ const pz = a[2] + dz * t
807
+ const pn = Math.abs((px - wall.start[0]) * wall.nx + (pz - wall.start[1]) * wall.nz)
808
+ if (pn > halfThick) continue
809
+
810
+ const fit = checkWetWallPipeFit({
811
+ wallThicknessM: effectiveWallThicknessM,
812
+ pipeSize,
813
+ material,
814
+ isLoadBearing: rule?.isLoadBearing ?? false,
815
+ isHorizontalBore: true,
816
+ })
817
+ penetrations.push({
818
+ id: `${pipeRunId}_pen_${seq++}`,
819
+ pipeRunId,
820
+ wallId: wall.id,
821
+ memberKind: 'stud',
822
+ memberLabel: `Stud #${studIdx} @ ${Math.round(studU / INCHES_TO_METERS)}" OC`,
823
+ position: [px, py, pz],
824
+ pipeDirection: dir,
825
+ wallNormal: [wall.nx, wall.nz],
826
+ studDepthM,
827
+ pipeSize,
828
+ material,
829
+ holeSawIn,
830
+ borePctOfStud: fit.borePctOfStud,
831
+ needsNailPlate: fit.needsNailPlate,
832
+ codeCompliant: fit.fits,
833
+ codeRef: fit.codeRef,
834
+ note: fit.reason,
835
+ })
836
+ }
837
+ }
838
+ }
839
+ }
840
+
841
+ return penetrations
842
+ }