@kruschdev/pascal-plugin-plumbing 0.2.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -43,6 +43,7 @@ import {
43
43
  type WallOpeningSpan,
44
44
  type WallSegment2D,
45
45
  countPathElbows,
46
+ detectPlumbingClashes,
46
47
  extractRoomPolygons,
47
48
  extractWallSegments,
48
49
  mapCanonicalWallsToOpenings,
@@ -56,13 +57,16 @@ import {
56
57
  } from './routing'
57
58
  import { IPC_RULE_THRESHOLDS, getIpcRuleById } from './rules'
58
59
  import {
60
+ type FuelGasGraphSegment,
59
61
  checkDryerVentRun,
62
+ computeFuelGasDevelopedLengths,
60
63
  sizeBuildingDrain,
61
64
  sizeDrainBranch,
62
65
  sizeFuelGasPipe,
63
66
  sizeSupplyPipe,
64
67
  sizeVentStack,
65
68
  sizeWaterHeater,
69
+ wsfuToGpm,
66
70
  } from './sizing'
67
71
  import {
68
72
  type CodeEdition,
@@ -70,6 +74,7 @@ import {
70
74
  FIXTURE_SPECS,
71
75
  type FixtureKind,
72
76
  type FoundationType,
77
+ METERS_TO_FEET,
73
78
  type ManifoldKind,
74
79
  type OccupancyType,
75
80
  PIPE_NOMINAL_INCHES,
@@ -77,6 +82,7 @@ import {
77
82
  type PipeNominalSize,
78
83
  type PlumbingSystem,
79
84
  type SupplyTopology,
85
+ comparePipeSizes,
80
86
  getFixtureDfu,
81
87
  getFixtureWsfu,
82
88
  getPipeOuterDiameterM,
@@ -2042,6 +2048,8 @@ export function planPlumbingAutoPopulate(
2042
2048
  const totalDfu = fixtures.reduce((s, f) => s + f.dfu, 0)
2043
2049
  const iceMakerWsfu = discoveredIceMakers.reduce((s, im) => s + im.wsfuCold, 0)
2044
2050
  const totalWsfu = round2(fixtures.reduce((s, f) => s + f.wsfuTotal, 0) + iceMakerWsfu)
2051
+ const totalHotWsfu = round2(fixtures.reduce((s, f) => s + f.wsfuHot, 0))
2052
+ const hotPeakDemandGpm = wsfuToGpm(totalHotWsfu, 'flush-tank')
2045
2053
  const whFuel =
2046
2054
  resolvedWaterHeaterKind === 'water-heater-tank-gas'
2047
2055
  ? 'gas'
@@ -2055,6 +2063,7 @@ export function planPlumbingAutoPopulate(
2055
2063
  bedrooms: Math.max(2, wcCount + 1),
2056
2064
  occupancy,
2057
2065
  fuelType: whFuel,
2066
+ peakGpm: totalHotWsfu > 0 ? hotPeakDemandGpm : totalWsfu > 0 ? 0 : undefined,
2058
2067
  })
2059
2068
  const resolvedWhCapGal =
2060
2069
  resolvedWaterHeaterKind === 'water-heater-tankless-gas'
@@ -2246,25 +2255,39 @@ export function planPlumbingAutoPopulate(
2246
2255
  minSize: '3/4"',
2247
2256
  flushType,
2248
2257
  })
2249
- const totalHotWsfu = round2(fixtures.reduce((s, f) => s + f.wsfuHot, 0))
2250
2258
  const hotMainSized = sizeSupplyPipe({
2251
2259
  wsfu: Math.max(1, totalHotWsfu),
2252
2260
  material: supplyMaterial,
2253
2261
  isHot: true,
2254
2262
  minSize: '3/4"',
2255
- flushType,
2263
+ flushType: 'flush-tank',
2256
2264
  })
2257
2265
 
2266
+ const whRot = placedWaterHeaterSku?.rot ?? 0
2267
+ const clampSupplyOffset = (px: number, pz: number, margin = 0.08): readonly [number, number] =>
2268
+ walls.length > 0 ? clampToBoundsXZ(px, pz, margin) : [px, pz]
2269
+
2270
+ const [whColdTrunkX, whColdTrunkZ] = clampSupplyOffset(...rotateLocal2D(whPos[0], whPos[2], 0.08, 0, whRot))
2271
+ const [whHotTrunkX, whHotTrunkZ] = clampSupplyOffset(...rotateLocal2D(whPos[0], whPos[2], -0.08, 0, whRot))
2272
+ const [whColdInX, whColdInZ] = clampSupplyOffset(...rotateLocal2D(whPos[0], whPos[2], 0.1, 0, whRot))
2273
+ const [whHotOutX, whHotOutZ] = clampSupplyOffset(...rotateLocal2D(whPos[0], whPos[2], -0.1, 0, whRot))
2274
+ const [manColdInX, manColdInZ] = clampSupplyOffset(
2275
+ ...rotateLocal2D(manifoldPos[0], manifoldPos[2], 0.085, 0, manifoldRotation),
2276
+ )
2277
+ const [manHotInX, manHotInZ] = clampSupplyOffset(
2278
+ ...rotateLocal2D(manifoldPos[0], manifoldPos[2], -0.085, 0, manifoldRotation),
2279
+ )
2280
+
2258
2281
  let coldRiserId: string | undefined
2259
2282
  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]]
2283
+ let coldTrunkOrigin: Vec3 = [whColdTrunkX, 1.45, whColdTrunkZ]
2284
+ let hotTrunkOrigin: Vec3 = [whHotTrunkX, 1.45, whHotTrunkZ]
2262
2285
 
2263
2286
  if (emitWaterHeater && whId) {
2264
- const coldSourcePos: Vec3 = emitMainShutoff ? waterEntryPos : [whPos[0] + 0.1, supplyPlaneY, whPos[2]]
2287
+ const coldSourcePos: Vec3 = emitMainShutoff ? waterEntryPos : [whColdInX, supplyPlaneY, whColdInZ]
2265
2288
  const mainColdRoute = routePressurizedPipeRun({
2266
2289
  from: coldSourcePos,
2267
- to: [whPos[0] + 0.1, 1.55, whPos[2]],
2290
+ to: [whColdInX, 1.55, whColdInZ],
2268
2291
  routingPlaneY: supplyPlaneY,
2269
2292
  nominalSize: mainColdSized.size,
2270
2293
  material: supplyMaterial,
@@ -2299,8 +2322,8 @@ export function planPlumbingAutoPopulate(
2299
2322
  if (manifoldId) {
2300
2323
  // Cold Supply Header: Main Service Tee (WH cold side +0.1) -> PEX Manifold Cold Inlet (+0.085)
2301
2324
  const mainToManifoldCold = routePressurizedPipeRun({
2302
- from: [whPos[0] + 0.1, 1.55, whPos[2]],
2303
- to: [manifoldPos[0] + 0.085, manifoldPos[1], manifoldPos[2]],
2325
+ from: [whColdInX, 1.55, whColdInZ],
2326
+ to: [manColdInX, manifoldPos[1], manColdInZ],
2304
2327
  routingPlaneY: 1.69,
2305
2328
  nominalSize: mainColdSized.size,
2306
2329
  material: supplyMaterial,
@@ -2332,8 +2355,8 @@ export function planPlumbingAutoPopulate(
2332
2355
 
2333
2356
  // Hot Supply Header: WH Hot Outlet Nipple (-0.1) -> PEX Manifold Hot Inlet (-0.085)
2334
2357
  const whToManifoldHot = routePressurizedPipeRun({
2335
- from: [whPos[0] - 0.1, 1.55, whPos[2]],
2336
- to: [manifoldPos[0] - 0.085, manifoldPos[1], manifoldPos[2]],
2358
+ from: [whHotOutX, 1.55, whHotOutZ],
2359
+ to: [manHotInX, manifoldPos[1], manHotInZ],
2337
2360
  routingPlaneY: 1.65,
2338
2361
  nominalSize: hotMainSized.size,
2339
2362
  material: supplyMaterial,
@@ -2368,8 +2391,10 @@ export function planPlumbingAutoPopulate(
2368
2391
  // strictly inside the building footprint at the upper-story manifold / wet core.
2369
2392
  const riserAnchorX = manifoldId ? manifoldPos[0] : whPos[0]
2370
2393
  const riserAnchorZ = manifoldId ? manifoldPos[2] : whPos[2]
2394
+ const riserRot = manifoldId ? manifoldRotation : whRot
2371
2395
  const riserTopY = manifoldId ? manifoldPos[1] : 1.45
2372
- const [coldRiserX, coldRiserZ] = clampToBoundsXZ(riserAnchorX + 0.08, riserAnchorZ, 0.15)
2396
+ const [rawColdRiserX, rawColdRiserZ] = rotateLocal2D(riserAnchorX, riserAnchorZ, 0.08, 0, riserRot)
2397
+ const [coldRiserX, coldRiserZ] = clampSupplyOffset(rawColdRiserX, rawColdRiserZ, 0.12)
2373
2398
  coldTrunkOrigin = [coldRiserX, riserTopY, coldRiserZ]
2374
2399
  const coldRiserRoute = routePressurizedPipeRun({
2375
2400
  from: [coldRiserX, supplyPlaneY, coldRiserZ],
@@ -2404,7 +2429,8 @@ export function planPlumbingAutoPopulate(
2404
2429
  })
2405
2430
 
2406
2431
  if (totalHotWsfu > 0) {
2407
- const [hotRiserX, hotRiserZ] = clampToBoundsXZ(riserAnchorX - 0.08, riserAnchorZ, 0.15)
2432
+ const [rawHotRiserX, rawHotRiserZ] = rotateLocal2D(riserAnchorX, riserAnchorZ, -0.08, 0, riserRot)
2433
+ const [hotRiserX, hotRiserZ] = clampSupplyOffset(rawHotRiserX, rawHotRiserZ, 0.12)
2408
2434
  hotTrunkOrigin = [hotRiserX, riserTopY, hotRiserZ]
2409
2435
  const hotRiserRoute = routePressurizedPipeRun({
2410
2436
  from: [hotRiserX, supplyPlaneY + 0.04, hotRiserZ],
@@ -2596,19 +2622,6 @@ export function planPlumbingAutoPopulate(
2596
2622
  }).fits
2597
2623
  }
2598
2624
 
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
2625
  const electricalDedicatedSpaces = obstacles.filter((o) => o.category === 'electrical-dedicated-space')
2613
2626
  const hitsElectricalDedicatedSpace = (cx: number, cz: number): boolean => {
2614
2627
  if (electricalDedicatedSpaces.length === 0) return false
@@ -2634,8 +2647,122 @@ export function planPlumbingAutoPopulate(
2634
2647
  return true
2635
2648
  }
2636
2649
 
2650
+ const hitsUpperFloorFurnitureOrKeepout = (cx: number, cz: number, concealedInWall: boolean): boolean => {
2651
+ if (crossTradeFloorEquip.some((eq) => Math.hypot(cx - eq.x, cz - eq.z) < 0.55)) return true
2652
+ if (concealedInWall) return false
2653
+ if (fixtures.some((f) => Math.hypot(cx - f.position[0], cz - f.position[2]) < 0.35)) return true
2654
+ const pad = stackPipeRadiusM + 0.1
2655
+ for (const n of Object.values(nodes)) {
2656
+ if (n.visible === false || !FURNISHING_DISCOVERY_NODE_TYPES.has(n.type)) continue
2657
+ if (!belongsToLevel(nodes, n, levelId) || !isFiniteVec3(n.position)) continue
2658
+ if (typeof n.parentId === 'string' && wallById.has(n.parentId)) continue
2659
+ const nx = Number(n.position[0])
2660
+ const nz = Number(n.position[2])
2661
+ const dimsMm = Array.isArray(n.dimensionsMm) ? (n.dimensionsMm as ReadonlyArray<number>) : undefined
2662
+ const w =
2663
+ typeof n.widthM === 'number' && Number.isFinite(n.widthM) && n.widthM > 0.1
2664
+ ? n.widthM
2665
+ : typeof n.width === 'number' && Number.isFinite(n.width) && n.width > 0.1
2666
+ ? n.width
2667
+ : dimsMm && typeof dimsMm[0] === 'number' && dimsMm[0] > 100
2668
+ ? dimsMm[0] / 1000
2669
+ : 0.8
2670
+ const d =
2671
+ typeof n.depthM === 'number' && Number.isFinite(n.depthM) && n.depthM > 0.1
2672
+ ? n.depthM
2673
+ : typeof n.depth === 'number' && Number.isFinite(n.depth) && n.depth > 0.1
2674
+ ? n.depth
2675
+ : dimsMm && typeof dimsMm[2] === 'number' && dimsMm[2] > 100
2676
+ ? dimsMm[2] / 1000
2677
+ : 0.8
2678
+ const rot =
2679
+ typeof n.rotation === 'number' && Number.isFinite(n.rotation)
2680
+ ? n.rotation
2681
+ : Array.isArray(n.rotation) && n.rotation.length >= 2 && Number.isFinite(Number(n.rotation[1]))
2682
+ ? Number(n.rotation[1])
2683
+ : 0
2684
+ const dx = cx - nx
2685
+ const dz = cz - nz
2686
+ const cos = Math.cos(rot)
2687
+ const sin = Math.sin(rot)
2688
+ const lx = Math.abs(dx * cos - dz * sin)
2689
+ const lz = Math.abs(dx * sin + dz * cos)
2690
+ if (lx <= w / 2 + pad && lz <= d / 2 + pad) return true
2691
+ }
2692
+ return false
2693
+ }
2694
+
2695
+ // Prefer a 2x6 wet wall satisfying `irc-r602-6-wet-wall-fit` for the 3"/4" Main DWV Soil & Vent Stack,
2696
+ // reusing a lower-story Main Vent Stack `(sx, sz)` on upper stories whenever it lies inside the upper
2697
+ // story's bounds and is clear of furniture/keep-outs on the upper floor.
2698
+ const wetCapableWalls = walls.filter((w) =>
2699
+ canWallFitPipe(w, mainVentSizing.recommendedSize, [stackX, 1.0, stackZ]),
2700
+ )
2701
+ const stackWallPool = wetCapableWalls.length > 0 ? wetCapableWalls : walls
2702
+ const stackNearWall = nearestWallToPoint(stackX, stackZ, stackWallPool)
2703
+ let stackPt: readonly [number, number] = stackNearWall
2704
+ ? [round2(stackNearWall.point[0]), round2(stackNearWall.point[1])]
2705
+ : [stackX, stackZ]
2706
+ let stackWallId: string | undefined = stackNearWall?.wall.id
2707
+ let reusedLowerStack = false
2708
+
2709
+ if (!isGroundStory && lowerWalledLevelIds.length > 0) {
2710
+ const orderedLowerIds = [...lowerWalledLevelIds].reverse()
2711
+ for (const lowLvlId of orderedLowerIds) {
2712
+ const lowerStack = Object.values(nodes).find(
2713
+ (n) =>
2714
+ n.type === 'plumbing:pipe-run' &&
2715
+ n.isMainVentStack === true &&
2716
+ Array.isArray(n.path) &&
2717
+ n.path.length >= 2 &&
2718
+ isFiniteVec3(n.path[0]) &&
2719
+ belongsToLevel(nodes, n, lowLvlId),
2720
+ )
2721
+ if (!lowerStack || !Array.isArray(lowerStack.path) || !isFiniteVec3(lowerStack.path[0])) continue
2722
+ const sx = round2(Number(lowerStack.path[0][0]))
2723
+ const sz = round2(Number(lowerStack.path[0][2]))
2724
+ const nearUpper = nearestWallToPoint(sx, sz, walls)
2725
+ const coincidentWall =
2726
+ nearUpper && nearUpper.distanceM <= nearUpper.wall.thicknessM / 2 + 0.05 ? nearUpper.wall : null
2727
+ const coincidentAlong = nearUpper && coincidentWall ? coincidentWall.lengthM * nearUpper.t : 0
2728
+ const inUpperInterior =
2729
+ sx >= bounds.minX + 0.08 &&
2730
+ sx <= bounds.maxX - 0.08 &&
2731
+ sz >= bounds.minZ + 0.08 &&
2732
+ sz <= bounds.maxZ - 0.08
2733
+ const onUpperWall =
2734
+ coincidentWall !== null &&
2735
+ sx >= bounds.minX - 0.02 &&
2736
+ sx <= bounds.maxX + 0.02 &&
2737
+ sz >= bounds.minZ - 0.02 &&
2738
+ sz <= bounds.maxZ + 0.02
2739
+ const inConcaveIndoor =
2740
+ indoorRooms.length === 0 ||
2741
+ coincidentWall !== null ||
2742
+ indoorRooms.some((r) => pointInPolygon2D(sx, sz, r.polygon))
2743
+ if (
2744
+ (inUpperInterior || onUpperWall) &&
2745
+ inConcaveIndoor &&
2746
+ isStackPointClear(sx, sz, coincidentWall, coincidentAlong, 0.22) &&
2747
+ !hitsUpperFloorFurnitureOrKeepout(sx, sz, coincidentWall !== null)
2748
+ ) {
2749
+ stackPt = [sx, sz]
2750
+ stackWallId =
2751
+ coincidentWall && canWallFitPipe(coincidentWall, mainVentSizing.recommendedSize, [sx, 1.0, sz])
2752
+ ? coincidentWall.id
2753
+ : undefined
2754
+ reusedLowerStack = true
2755
+ break
2756
+ }
2757
+ }
2758
+ }
2759
+
2637
2760
  const initialAlong = stackNearWall ? stackNearWall.wall.lengthM * stackNearWall.t : 0
2638
- if (!isStackPointClear(stackPt[0], stackPt[1], stackNearWall?.wall ?? null, initialAlong, 0.28)) {
2761
+ if (
2762
+ !reusedLowerStack &&
2763
+ (!isStackPointClear(stackPt[0], stackPt[1], stackNearWall?.wall ?? null, initialAlong, 0.28) ||
2764
+ hitsUpperFloorFurnitureOrKeepout(stackPt[0], stackPt[1], stackNearWall !== null))
2765
+ ) {
2639
2766
  let cleared = false
2640
2767
  const fallbackWalls =
2641
2768
  wetCapableWalls.length > 0 && wetCapableWalls.length < walls.length
@@ -2676,7 +2803,7 @@ export function planPlumbingAutoPopulate(
2676
2803
  }
2677
2804
  pierCandidates.sort((a, b) => a.isWetCapable - b.isWetCapable || a.dist - b.dist)
2678
2805
  for (const pier of pierCandidates) {
2679
- if (isStackPointClear(pier.x, pier.z, pier.wall, pier.t, 0.24)) {
2806
+ if (isStackPointClear(pier.x, pier.z, pier.wall, pier.t, 0.24) && !hitsUpperFloorFurnitureOrKeepout(pier.x, pier.z, true)) {
2680
2807
  stackPt = [pier.x, pier.z]
2681
2808
  stackWallId = pier.wall.id
2682
2809
  cleared = true
@@ -2701,7 +2828,7 @@ export function planPlumbingAutoPopulate(
2701
2828
  if (along < edgeMargin || along > w.lengthM - edgeMargin) continue
2702
2829
  const cx = round2(w.start[0] + w.ux * along)
2703
2830
  const cz = round2(w.start[1] + w.uz * along)
2704
- if (isStackPointClear(cx, cz, w, along, pad)) {
2831
+ if (isStackPointClear(cx, cz, w, along, pad) && !hitsUpperFloorFurnitureOrKeepout(cx, cz, true)) {
2705
2832
  stackPt = [cx, cz]
2706
2833
  stackWallId = w.id
2707
2834
  cleared = true
@@ -2715,7 +2842,7 @@ export function planPlumbingAutoPopulate(
2715
2842
  }
2716
2843
 
2717
2844
  // 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.
2845
+ // clear of ALL structural beams, headers, columns, openings, furniture, and NEC 110.26(E) dedicated spaces.
2719
2846
  if (!cleared) {
2720
2847
  const [bx, bz] = stackPt
2721
2848
  for (const pad of [0.28, 0.14]) {
@@ -2736,7 +2863,7 @@ export function planPlumbingAutoPopulate(
2736
2863
  if (cx < bounds.minX + 0.15 || cx > bounds.maxX - 0.15 || cz < bounds.minZ + 0.15 || cz > bounds.maxZ - 0.15) {
2737
2864
  continue
2738
2865
  }
2739
- if (isStackPointClear(cx, cz, null, 0, pad)) {
2866
+ if (isStackPointClear(cx, cz, null, 0, pad) && !hitsUpperFloorFurnitureOrKeepout(cx, cz, false)) {
2740
2867
  stackPt = [cx, cz]
2741
2868
  stackWallId = undefined
2742
2869
  cleared = true
@@ -2774,6 +2901,13 @@ export function planPlumbingAutoPopulate(
2774
2901
 
2775
2902
  // Route every fixture's DWV branch, Re-Vent, Cold Supply, and Hot Supply
2776
2903
  const supplySourcePos: Vec3 = manifoldId ? manifoldPos : [whPos[0], 1.45, whPos[2]]
2904
+ const supplySourceRot = manifoldId ? manifoldRotation : whRot
2905
+ const [supplyColdOutX, supplyColdOutZ] = clampSupplyOffset(
2906
+ ...rotateLocal2D(supplySourcePos[0], supplySourcePos[2], 0.08, 0, supplySourceRot),
2907
+ )
2908
+ const [supplyHotOutX, supplyHotOutZ] = clampSupplyOffset(
2909
+ ...rotateLocal2D(supplySourcePos[0], supplySourcePos[2], -0.08, 0, supplySourceRot),
2910
+ )
2777
2911
  const coldSupplySourceId = manifoldId ?? whId ?? coldRiserId
2778
2912
  const hotSupplySourceId = manifoldId ?? whId ?? hotRiserId
2779
2913
  let furthestHotFixture: PlannedFixtureSpec | null = null
@@ -2902,7 +3036,7 @@ export function planPlumbingAutoPopulate(
2902
3036
  const coldOrigin: Vec3 =
2903
3037
  supplyTopology === 'trunk-and-branch' && coldTrunkSpine.length >= 2
2904
3038
  ? nearestPointOnSpine(coldTrunkSpine, coldTarget[0], coldTarget[2], supplyPlaneY)
2905
- : [supplySourcePos[0] + 0.08, supplySourcePos[1], supplySourcePos[2]]
3039
+ : [supplyColdOutX, supplySourcePos[1], supplyColdOutZ]
2906
3040
  const coldRoute = routePressurizedPipeRun({
2907
3041
  from: coldOrigin,
2908
3042
  to: coldTarget,
@@ -2943,7 +3077,7 @@ export function planPlumbingAutoPopulate(
2943
3077
  material: supplyMaterial,
2944
3078
  isHot: true,
2945
3079
  minSize: fix.supplySize,
2946
- flushType,
3080
+ flushType: 'flush-tank',
2947
3081
  })
2948
3082
  const rawHotTarget = getFixtureSupplyPoint(fix, 'hot')
2949
3083
  const [hotTx, hotTz] =
@@ -2954,7 +3088,7 @@ export function planPlumbingAutoPopulate(
2954
3088
  const hotOrigin: Vec3 =
2955
3089
  supplyTopology === 'trunk-and-branch' && hotTrunkSpine.length >= 2
2956
3090
  ? nearestPointOnSpine(hotTrunkSpine, hotTarget[0], hotTarget[2], supplyPlaneY + 0.04)
2957
- : [supplySourcePos[0] - 0.08, supplySourcePos[1], supplySourcePos[2]]
3091
+ : [supplyHotOutX, supplySourcePos[1], supplyHotOutZ]
2958
3092
  const hotRoute = routePressurizedPipeRun({
2959
3093
  from: hotOrigin,
2960
3094
  to: hotTarget,
@@ -2999,7 +3133,7 @@ export function planPlumbingAutoPopulate(
2999
3133
  const coldOrigin: Vec3 =
3000
3134
  supplyTopology === 'trunk-and-branch' && coldTrunkSpine.length >= 2
3001
3135
  ? nearestPointOnSpine(coldTrunkSpine, fridge.pos[0], fridge.pos[2], supplyPlaneY)
3002
- : [supplySourcePos[0] + 0.08, supplySourcePos[1], supplySourcePos[2]]
3136
+ : [supplyColdOutX, supplySourcePos[1], supplyColdOutZ]
3003
3137
  const iceRoute = routePressurizedPipeRun({
3004
3138
  from: coldOrigin,
3005
3139
  to: fridge.pos,
@@ -3173,13 +3307,22 @@ export function planPlumbingAutoPopulate(
3173
3307
  electricalDemand: null,
3174
3308
  })
3175
3309
  }
3176
- for (const target of gasTargets) {
3310
+ const measurePolylineFt = (pts: ReadonlyArray<Vec3>): number => {
3311
+ let mLen = 0
3312
+ for (let i = 1; i < pts.length; i++) {
3313
+ const a = pts[i - 1]!
3314
+ const b = pts[i]!
3315
+ mLen += Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2])
3316
+ }
3317
+ return mLen * METERS_TO_FEET
3318
+ }
3319
+ const prelimGasEntries = gasTargets.map((target) => {
3177
3320
  const prelimGasSizing = sizeFuelGasPipe({
3178
3321
  totalBtuh: target.btuh,
3179
- longestRunFt: 40,
3322
+ longestRunFt: IPC_RULE_THRESHOLDS.fuelGasMinSizingLengthPlacementFt,
3180
3323
  material: 'black-iron',
3181
3324
  })
3182
- let gasRoute = routePressurizedPipeRun({
3325
+ const gasRoute = routePressurizedPipeRun({
3183
3326
  from: gasSourcePos,
3184
3327
  to: target.pos,
3185
3328
  routingPlaneY: supplyPlaneY - 0.06,
@@ -3191,31 +3334,53 @@ export function planPlumbingAutoPopulate(
3191
3334
  maxRoofYAt,
3192
3335
  cavityContext,
3193
3336
  })
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,
3337
+ return {
3338
+ target,
3339
+ currentSize: prelimGasSizing.recommendedSize,
3340
+ gasRoute,
3341
+ lengthFt: Math.max(gasRoute.lengthFt, measurePolylineFt(gasRoute.path)),
3342
+ }
3343
+ })
3344
+ for (let pass = 0; pass < 4; pass++) {
3345
+ const networkLongestGasFt = Math.max(
3346
+ IPC_RULE_THRESHOLDS.fuelGasMinSizingLengthPlacementFt,
3347
+ ...prelimGasEntries.map((e) => e.lengthFt),
3348
+ )
3349
+ let anyUpsized = false
3350
+ for (const entry of prelimGasEntries) {
3351
+ const gasSizing = sizeFuelGasPipe({
3352
+ totalBtuh: entry.target.btuh,
3353
+ longestRunFt: networkLongestGasFt,
3205
3354
  material: 'black-iron',
3206
- euclideanInCavity: false,
3207
- obstacles,
3208
- buildingBounds: bounds,
3209
- maxRoofYAt,
3210
- cavityContext,
3211
3355
  })
3356
+ if (gasSizing.recommendedSize !== entry.currentSize) {
3357
+ entry.currentSize = gasSizing.recommendedSize
3358
+ entry.gasRoute = routePressurizedPipeRun({
3359
+ from: gasSourcePos,
3360
+ to: entry.target.pos,
3361
+ routingPlaneY: supplyPlaneY - 0.06,
3362
+ nominalSize: gasSizing.recommendedSize,
3363
+ material: 'black-iron',
3364
+ euclideanInCavity: false,
3365
+ obstacles,
3366
+ buildingBounds: bounds,
3367
+ maxRoofYAt,
3368
+ cavityContext,
3369
+ })
3370
+ entry.lengthFt = Math.max(entry.gasRoute.lengthFt, measurePolylineFt(entry.gasRoute.path))
3371
+ anyUpsized = true
3372
+ }
3212
3373
  }
3374
+ if (!anyUpsized) break
3375
+ }
3376
+ for (const entry of prelimGasEntries) {
3377
+ const { target, currentSize, gasRoute } = entry
3213
3378
  pipeRuns.push({
3214
3379
  id: nextPipeId(),
3215
- name: `${gasSizing.recommendedSize} Fuel Gas Line (${target.name}, ${Math.round(target.btuh / 1000)} kBTU/hr, IFGC 402.4)`,
3380
+ name: `${currentSize} Fuel Gas Line (${target.name}, ${Math.round(target.btuh / 1000)} kBTU/hr, IFGC 402.4)`,
3216
3381
  system: 'fuel-gas',
3217
3382
  material: 'black-iron',
3218
- nominalSize: gasSizing.recommendedSize,
3383
+ nominalSize: currentSize,
3219
3384
  path: gasRoute.path,
3220
3385
  slopeInPerFt: 0,
3221
3386
  dfuLoad: 0,
@@ -3367,6 +3532,7 @@ export type SingleFixtureConnectResult = {
3367
3532
  type ResolvedSupplySource = {
3368
3533
  id: string
3369
3534
  pos: Vec3
3535
+ rot: number
3370
3536
  isManifold: boolean
3371
3537
  spine?: ReadonlyArray<Vec3>
3372
3538
  }
@@ -3579,7 +3745,7 @@ function buildLevelRoutingContext(
3579
3745
  if (trunk) {
3580
3746
  const spine = (trunk.path as Vec3[]).filter(isFiniteVec3)
3581
3747
  if (spine.length >= 2) {
3582
- return { id: trunk.id, pos: spine[0]!, isManifold: false, spine }
3748
+ return { id: trunk.id, pos: spine[0]!, rot: 0, isManifold: false, spine }
3583
3749
  }
3584
3750
  }
3585
3751
  const riser = levelPipes.find(
@@ -3594,17 +3760,25 @@ function buildLevelRoutingContext(
3594
3760
  const pts = (riser.path as Vec3[]).filter(isFiniteVec3)
3595
3761
  if (pts.length >= 2) {
3596
3762
  const topPt = pts[pts.length - 1]!
3597
- return { id: riser.id, pos: [Number(topPt[0]), Number(topPt[1]), Number(topPt[2])], isManifold: false }
3763
+ return { id: riser.id, pos: [Number(topPt[0]), Number(topPt[1]), Number(topPt[2])], rot: 0, isManifold: false }
3598
3764
  }
3599
3765
  }
3600
3766
  return null
3601
3767
  }
3602
3768
 
3769
+ const readNodeYaw = (n: SceneNodeLike): number =>
3770
+ typeof n.rotation === 'number' && Number.isFinite(n.rotation)
3771
+ ? n.rotation
3772
+ : Array.isArray(n.rotation) && n.rotation.length >= 2 && Number.isFinite(Number(n.rotation[1]))
3773
+ ? Number(n.rotation[1])
3774
+ : 0
3775
+
3603
3776
  const resolveSupplyForSystem = (sys: 'cold-water' | 'hot-water'): ResolvedSupplySource | null => {
3604
3777
  if (manifold && isFiniteVec3(manifold.position)) {
3605
3778
  return {
3606
3779
  id: manifold.id,
3607
3780
  pos: [Number(manifold.position[0]), Number(manifold.position[1]), Number(manifold.position[2])],
3781
+ rot: readNodeYaw(manifold),
3608
3782
  isManifold: true,
3609
3783
  }
3610
3784
  }
@@ -3614,6 +3788,7 @@ function buildLevelRoutingContext(
3614
3788
  return {
3615
3789
  id: waterHeater.id,
3616
3790
  pos: [Number(waterHeater.position[0]), 1.45, Number(waterHeater.position[2])],
3791
+ rot: readNodeYaw(waterHeater),
3617
3792
  isManifold: false,
3618
3793
  }
3619
3794
  }
@@ -3622,6 +3797,7 @@ function buildLevelRoutingContext(
3622
3797
  return {
3623
3798
  id: lowerWaterHeater.id,
3624
3799
  pos: [rx, supplyPlaneY, rz],
3800
+ rot: readNodeYaw(lowerWaterHeater),
3625
3801
  isManifold: false,
3626
3802
  }
3627
3803
  }
@@ -3800,10 +3976,18 @@ export function planConnectSingleFixture(
3800
3976
  })
3801
3977
  const rawTarget = getFixtureSupplyPoint(fixture, 'cold')
3802
3978
  const [tx, tz] = fixture.fixtureKind === 'hose-bibb' ? [rawTarget[0], rawTarget[2]] : clampXZ(rawTarget[0], rawTarget[2])
3979
+ const [rawSrcX, rawSrcZ] = rotateLocal2D(
3980
+ coldSupplySource.pos[0],
3981
+ coldSupplySource.pos[2],
3982
+ 0.08,
3983
+ 0,
3984
+ coldSupplySource.rot,
3985
+ )
3986
+ const [srcX, srcZ] = walls.length > 0 ? clampXZ(rawSrcX, rawSrcZ, 0.08) : [rawSrcX, rawSrcZ]
3803
3987
  const fromPt: Vec3 =
3804
3988
  coldSupplySource.spine && coldSupplySource.spine.length >= 2
3805
3989
  ? nearestPointOnPipeSpine(coldSupplySource.spine, tx, tz, supplyPlaneY)
3806
- : [coldSupplySource.pos[0] + 0.08, coldSupplySource.pos[1], coldSupplySource.pos[2]]
3990
+ : [srcX, coldSupplySource.pos[1], srcZ]
3807
3991
  const route = routePressurizedPipeRun({
3808
3992
  from: fromPt,
3809
3993
  to: [tx, rawTarget[1], tz],
@@ -3845,14 +4029,22 @@ export function planConnectSingleFixture(
3845
4029
  material: supplyMaterial,
3846
4030
  isHot: true,
3847
4031
  minSize: fixture.supplySize,
3848
- flushType,
4032
+ flushType: 'flush-tank',
3849
4033
  })
3850
4034
  const rawTarget = getFixtureSupplyPoint(fixture, 'hot')
3851
4035
  const [tx, tz] = fixture.fixtureKind === 'hose-bibb' ? [rawTarget[0], rawTarget[2]] : clampXZ(rawTarget[0], rawTarget[2])
4036
+ const [rawSrcX, rawSrcZ] = rotateLocal2D(
4037
+ hotSupplySource.pos[0],
4038
+ hotSupplySource.pos[2],
4039
+ -0.08,
4040
+ 0,
4041
+ hotSupplySource.rot,
4042
+ )
4043
+ const [srcX, srcZ] = walls.length > 0 ? clampXZ(rawSrcX, rawSrcZ, 0.08) : [rawSrcX, rawSrcZ]
3852
4044
  const fromPt: Vec3 =
3853
4045
  hotSupplySource.spine && hotSupplySource.spine.length >= 2
3854
4046
  ? nearestPointOnPipeSpine(hotSupplySource.spine, tx, tz, supplyPlaneY + 0.04)
3855
- : [hotSupplySource.pos[0] - 0.08, hotSupplySource.pos[1], hotSupplySource.pos[2]]
4047
+ : [srcX, hotSupplySource.pos[1], srcZ]
3856
4048
  const route = routePressurizedPipeRun({
3857
4049
  from: fromPt,
3858
4050
  to: [tx, rawTarget[1], tz],
@@ -3983,11 +4175,79 @@ export function planConnectSingleFixture(
3983
4175
  }
3984
4176
  }
3985
4177
 
4178
+ function collectConnectedFuelGasRunIds(
4179
+ segments: ReadonlyArray<FuelGasGraphSegment>,
4180
+ probeId: string,
4181
+ ): Set<string> {
4182
+ const segIds = new Set(segments.map((s) => s.id))
4183
+ const bySourceNode = new Map<string, string[]>()
4184
+ const byTargetNode = new Map<string, string[]>()
4185
+ const undirected = new Map<string, Set<string>>()
4186
+
4187
+ const linkUndirected = (a: string, b: string) => {
4188
+ if (a === b) return
4189
+ undirected.get(a)?.add(b)
4190
+ undirected.get(b)?.add(a)
4191
+ }
4192
+
4193
+ for (const seg of segments) {
4194
+ undirected.set(seg.id, new Set())
4195
+ if (seg.sourceNodeId) {
4196
+ const list = bySourceNode.get(seg.sourceNodeId)
4197
+ if (list) list.push(seg.id)
4198
+ else bySourceNode.set(seg.sourceNodeId, [seg.id])
4199
+ }
4200
+ if (seg.targetNodeId) {
4201
+ const list = byTargetNode.get(seg.targetNodeId)
4202
+ if (list) list.push(seg.id)
4203
+ else byTargetNode.set(seg.targetNodeId, [seg.id])
4204
+ }
4205
+ }
4206
+
4207
+ for (const ids of bySourceNode.values()) {
4208
+ for (let i = 1; i < ids.length; i++) linkUndirected(ids[0]!, ids[i]!)
4209
+ }
4210
+ for (const ids of byTargetNode.values()) {
4211
+ for (let i = 1; i < ids.length; i++) linkUndirected(ids[0]!, ids[i]!)
4212
+ }
4213
+
4214
+ for (const a of segments) {
4215
+ if (a.targetNodeId) {
4216
+ if (segIds.has(a.targetNodeId) && a.targetNodeId !== a.id) {
4217
+ linkUndirected(a.id, a.targetNodeId)
4218
+ }
4219
+ for (const nextId of bySourceNode.get(a.targetNodeId) ?? []) {
4220
+ if (nextId !== a.id) linkUndirected(a.id, nextId)
4221
+ }
4222
+ }
4223
+ if (a.sourceNodeId && segIds.has(a.sourceNodeId) && a.sourceNodeId !== a.id) {
4224
+ linkUndirected(a.sourceNodeId, a.id)
4225
+ }
4226
+ }
4227
+
4228
+ const visited = new Set<string>()
4229
+ if (!undirected.has(probeId)) return visited
4230
+ const queue: string[] = [probeId]
4231
+ visited.add(probeId)
4232
+ while (queue.length > 0) {
4233
+ const curr = queue.pop()!
4234
+ for (const nb of undirected.get(curr) ?? []) {
4235
+ if (!visited.has(nb)) {
4236
+ visited.add(nb)
4237
+ queue.push(nb)
4238
+ }
4239
+ }
4240
+ }
4241
+ visited.delete(probeId)
4242
+ return visited
4243
+ }
4244
+
3986
4245
  export type PlumbingSyncResult = {
3987
4246
  fellBackToFullAutoPopulate: boolean
3988
4247
  fullPlan?: PlumbingAutoPopulatePlan
3989
4248
  fixtures: PlannedFixtureSpec[]
3990
4249
  pipeRuns: PlannedPipeRunSpec[]
4250
+ replacedPipeIds: string[]
3991
4251
  newlyLinkedFurnishings: number
3992
4252
  connectedFixtures: number
3993
4253
  summary: string
@@ -4039,6 +4299,7 @@ export function planSyncPlumbingFixtures(
4039
4299
  fullPlan,
4040
4300
  fixtures: fullPlan.fixtures,
4041
4301
  pipeRuns: fullPlan.pipeRuns,
4302
+ replacedPipeIds: [],
4042
4303
  newlyLinkedFurnishings: fullPlan.fixtures.filter((f) => Boolean(f.furnishingSourceId)).length,
4043
4304
  connectedFixtures: fullPlan.fixtures.length,
4044
4305
  summary: fullPlan.summary,
@@ -4324,7 +4585,13 @@ export function planSyncPlumbingFixtures(
4324
4585
  }
4325
4586
 
4326
4587
  // 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) {
4588
+ const replacedPipeIds: string[] = []
4589
+ const hasExistingLevelGasPipes = levelPipes.some((p) => p.system === 'fuel-gas')
4590
+ if (
4591
+ newIceMakers.length > 0 ||
4592
+ newDryers.length > 0 ||
4593
+ (options.includeFuelGas !== false && (newGasTargets.length > 0 || hasExistingLevelGasPipes))
4594
+ ) {
4328
4595
  let auxSeq = 1
4329
4596
  const nextAuxPipeId = () => {
4330
4597
  while (usedIds.has(`plumbpipe_sync_${auxSeq}`)) auxSeq += 1
@@ -4334,11 +4601,19 @@ export function planSyncPlumbingFixtures(
4334
4601
  }
4335
4602
 
4336
4603
  if (coldSupplySource) {
4604
+ const [rawColdSrcX, rawColdSrcZ] = rotateLocal2D(
4605
+ coldSupplySource.pos[0],
4606
+ coldSupplySource.pos[2],
4607
+ 0.08,
4608
+ 0,
4609
+ coldSupplySource.rot,
4610
+ )
4611
+ const [coldSrcX, coldSrcZ] = walls.length > 0 ? clampXZ(rawColdSrcX, rawColdSrcZ, 0.08) : [rawColdSrcX, rawColdSrcZ]
4337
4612
  for (const fridge of newIceMakers) {
4338
4613
  const origin: Vec3 =
4339
4614
  coldSupplySource.spine && coldSupplySource.spine.length >= 2
4340
4615
  ? nearestPointOnPipeSpine(coldSupplySource.spine, fridge.pos[0], fridge.pos[2], supplyPlaneY)
4341
- : [coldSupplySource.pos[0] + 0.08, coldSupplySource.pos[1], coldSupplySource.pos[2]]
4616
+ : [coldSrcX, coldSupplySource.pos[1], coldSrcZ]
4342
4617
  const route = routePressurizedPipeRun({
4343
4618
  from: origin,
4344
4619
  to: fridge.pos,
@@ -4375,19 +4650,89 @@ export function planSyncPlumbingFixtures(
4375
4650
  }
4376
4651
  }
4377
4652
 
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
- )
4653
+ const gasMeter =
4654
+ options.includeFuelGas !== false
4655
+ ? Object.values(nodes).find(
4656
+ (n) =>
4657
+ n.type === 'plumbing:equipment' &&
4658
+ n.equipmentKind === 'gas-meter' &&
4659
+ belongsToLevel(nodes, n, levelId) &&
4660
+ isFiniteVec3(n.position),
4661
+ )
4662
+ : undefined
4385
4663
  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])],
4664
+ const gPos: Vec3 = [Number(gasMeter.position[0]), Number(gasMeter.position[1]), Number(gasMeter.position[2])]
4665
+ const measurePathLengthFt = (path: ReadonlyArray<unknown>): number => {
4666
+ let mLen = 0
4667
+ for (let i = 1; i < path.length; i++) {
4668
+ const a = path[i - 1]
4669
+ const b = path[i]
4670
+ if (isFiniteVec3(a) && isFiniteVec3(b)) {
4671
+ mLen += Math.hypot(Number(b[0]) - Number(a[0]), Number(b[1]) - Number(a[1]), Number(b[2]) - Number(a[2]))
4672
+ }
4673
+ }
4674
+ return mLen * METERS_TO_FEET
4675
+ }
4676
+
4677
+ const existingGasEntries = levelPipes
4678
+ .filter((p) => p.system === 'fuel-gas' && Array.isArray(p.path))
4679
+ .flatMap((p) => {
4680
+ const pts = (p.path as unknown[])
4681
+ .filter(isFiniteVec3)
4682
+ .map((pt) => [Number(pt[0]), Number(pt[1]), Number(pt[2])] as Vec3)
4683
+ if (pts.length < 2) return []
4684
+ const rawMat: PipeMaterial =
4685
+ p.material === 'csst' || p.material === 'copper-l' || p.material === 'black-iron'
4686
+ ? p.material
4687
+ : 'black-iron'
4688
+ const sizingMaterial: 'black-iron' | 'csst' = rawMat === 'csst' ? 'csst' : 'black-iron'
4689
+ const origSize: PipeNominalSize =
4690
+ typeof p.nominalSize === 'string' && p.nominalSize in PIPE_NOMINAL_INCHES
4691
+ ? (p.nominalSize as PipeNominalSize)
4692
+ : '1/2"'
4693
+ const btuh = typeof p.gasBtuh === 'number' && Number.isFinite(p.gasBtuh) ? p.gasBtuh : 0
4694
+ return [
4695
+ {
4696
+ pipe: p,
4697
+ id: p.id,
4698
+ currentSize: origSize,
4699
+ material: rawMat,
4700
+ sizingMaterial,
4701
+ btuh,
4702
+ currentPath: pts,
4703
+ lengthFt: measurePathLengthFt(pts),
4704
+ sourceNodeId: typeof p.sourceNodeId === 'string' && p.sourceNodeId ? p.sourceNodeId : undefined,
4705
+ targetNodeId: typeof p.targetNodeId === 'string' && p.targetNodeId ? p.targetNodeId : undefined,
4706
+ upsized: false,
4707
+ },
4708
+ ]
4709
+ })
4710
+
4711
+ // Include any cross-level fuel-gas pipes in the graph so multi-hop developed length matches `auditScenePlumbing` 1:1
4712
+ const levelGasIdSet = new Set(existingGasEntries.map((e) => e.id))
4713
+ const crossLevelGasSegments: FuelGasGraphSegment[] = Object.values(nodes)
4714
+ .filter(
4715
+ (n) =>
4716
+ n.type === 'plumbing:pipe-run' &&
4717
+ n.system === 'fuel-gas' &&
4718
+ !levelGasIdSet.has(n.id) &&
4719
+ Array.isArray(n.path),
4720
+ )
4721
+ .map((n) => ({
4722
+ id: n.id,
4723
+ lengthFt: measurePathLengthFt(n.path as unknown[]),
4724
+ ...(typeof n.sourceNodeId === 'string' && n.sourceNodeId ? { sourceNodeId: n.sourceNodeId } : {}),
4725
+ ...(typeof n.targetNodeId === 'string' && n.targetNodeId ? { targetNodeId: n.targetNodeId } : {}),
4726
+ }))
4727
+
4728
+ const prelimSyncGas = newGasTargets.map((target, idx) => {
4729
+ const prelim = sizeFuelGasPipe({
4730
+ totalBtuh: target.btuh,
4731
+ longestRunFt: IPC_RULE_THRESHOLDS.fuelGasMinSizingLengthPlacementFt,
4732
+ material: 'black-iron',
4733
+ })
4734
+ const gasRoute = routePressurizedPipeRun({
4735
+ from: gPos,
4391
4736
  to: target.pos,
4392
4737
  routingPlaneY: supplyPlaneY - 0.06,
4393
4738
  nominalSize: prelim.recommendedSize,
@@ -4398,31 +4743,201 @@ export function planSyncPlumbingFixtures(
4398
4743
  maxRoofYAt,
4399
4744
  cavityContext,
4400
4745
  })
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,
4746
+ return {
4747
+ segId: `__sync_gas_new_${idx}`,
4748
+ target,
4749
+ currentSize: prelim.recommendedSize,
4750
+ gasRoute,
4751
+ lengthFt: Math.max(gasRoute.lengthFt, measurePathLengthFt(gasRoute.path)),
4752
+ }
4753
+ })
4754
+
4755
+ const METER_PROBE_ID = '__sync_gas_meter_probe__'
4756
+ for (let pass = 0; pass < 4; pass++) {
4757
+ const graphSegments: FuelGasGraphSegment[] = [
4758
+ ...crossLevelGasSegments,
4759
+ ...existingGasEntries.map((e) => ({
4760
+ id: e.id,
4761
+ lengthFt: e.lengthFt,
4762
+ ...(e.sourceNodeId ? { sourceNodeId: e.sourceNodeId } : {}),
4763
+ ...(e.targetNodeId ? { targetNodeId: e.targetNodeId } : {}),
4764
+ })),
4765
+ ...prelimSyncGas.map((s) => ({
4766
+ id: s.segId,
4767
+ lengthFt: s.lengthFt,
4768
+ sourceNodeId: gasMeter.id,
4769
+ targetNodeId: s.target.sourceId,
4770
+ })),
4771
+ { id: METER_PROBE_ID, lengthFt: 0, sourceNodeId: gasMeter.id },
4772
+ ]
4773
+ const dev = computeFuelGasDevelopedLengths(graphSegments)
4774
+ const meterComponentIds = collectConnectedFuelGasRunIds(graphSegments, METER_PROBE_ID)
4775
+ const meterDevelopedFt = dev.byRunId.get(METER_PROBE_ID) ?? 0
4776
+ const syncLongestGasFt = Math.max(
4777
+ IPC_RULE_THRESHOLDS.fuelGasMinSizingLengthPlacementFt,
4778
+ IPC_RULE_THRESHOLDS.fuelGasMinSizingLengthAuditFt,
4779
+ meterDevelopedFt,
4780
+ )
4781
+
4782
+ let changedInPass = false
4783
+ for (const entry of prelimSyncGas) {
4784
+ const sized = sizeFuelGasPipe({
4785
+ totalBtuh: entry.target.btuh,
4786
+ longestRunFt: syncLongestGasFt,
4412
4787
  material: 'black-iron',
4413
- euclideanInCavity: false,
4414
- obstacles,
4415
- buildingBounds: bounds,
4416
- maxRoofYAt,
4417
- cavityContext,
4418
4788
  })
4789
+ if (sized.recommendedSize !== entry.currentSize) {
4790
+ entry.currentSize = sized.recommendedSize
4791
+ entry.gasRoute = routePressurizedPipeRun({
4792
+ from: gPos,
4793
+ to: entry.target.pos,
4794
+ routingPlaneY: supplyPlaneY - 0.06,
4795
+ nominalSize: sized.recommendedSize,
4796
+ material: 'black-iron',
4797
+ euclideanInCavity: false,
4798
+ obstacles,
4799
+ buildingBounds: bounds,
4800
+ maxRoofYAt,
4801
+ cavityContext,
4802
+ })
4803
+ entry.lengthFt = Math.max(entry.gasRoute.lengthFt, measurePathLengthFt(entry.gasRoute.path))
4804
+ changedInPass = true
4805
+ }
4806
+ }
4807
+
4808
+ for (const existing of existingGasEntries) {
4809
+ if (!meterComponentIds.has(existing.id) || existing.btuh <= 0) continue
4810
+ const sized = sizeFuelGasPipe({
4811
+ totalBtuh: existing.btuh,
4812
+ longestRunFt: syncLongestGasFt,
4813
+ material: existing.sizingMaterial,
4814
+ })
4815
+ if (comparePipeSizes(existing.currentSize, sized.recommendedSize) < 0) {
4816
+ existing.currentSize = sized.recommendedSize
4817
+ existing.upsized = true
4818
+ const newRadiusM = getPipeOuterDiameterM(sized.recommendedSize, existing.material) / 2
4819
+ if (detectPlumbingClashes(existing.currentPath, obstacles, newRadiusM).length > 0) {
4820
+ const rerouted = routePressurizedPipeRun({
4821
+ from: existing.currentPath[0]!,
4822
+ to: existing.currentPath[existing.currentPath.length - 1]!,
4823
+ routingPlaneY: existing.currentPath[0]![1] ?? supplyPlaneY - 0.06,
4824
+ nominalSize: sized.recommendedSize,
4825
+ material: existing.material,
4826
+ euclideanInCavity: false,
4827
+ obstacles,
4828
+ buildingBounds: bounds,
4829
+ maxRoofYAt,
4830
+ cavityContext,
4831
+ })
4832
+ existing.currentPath = rerouted.path
4833
+ existing.lengthFt = Math.max(rerouted.lengthFt, measurePathLengthFt(rerouted.path))
4834
+ }
4835
+ changedInPass = true
4836
+ }
4837
+ }
4838
+
4839
+ if (!changedInPass) break
4840
+ }
4841
+
4842
+ const remappedPipeIds = new Map<string, string>()
4843
+ for (const existing of existingGasEntries) {
4844
+ if (existing.upsized) {
4845
+ remappedPipeIds.set(existing.id, nextAuxPipeId())
4846
+ }
4847
+ }
4848
+ let expandedRemap = true
4849
+ while (expandedRemap) {
4850
+ expandedRemap = false
4851
+ for (const existing of existingGasEntries) {
4852
+ if (remappedPipeIds.has(existing.id)) continue
4853
+ if (
4854
+ (existing.sourceNodeId && remappedPipeIds.has(existing.sourceNodeId)) ||
4855
+ (existing.targetNodeId && remappedPipeIds.has(existing.targetNodeId))
4856
+ ) {
4857
+ remappedPipeIds.set(existing.id, nextAuxPipeId())
4858
+ expandedRemap = true
4859
+ }
4860
+ }
4861
+ }
4862
+
4863
+ for (const existing of existingGasEntries) {
4864
+ const replacementId = remappedPipeIds.get(existing.id)
4865
+ if (!replacementId) continue
4866
+ replacedPipeIds.push(existing.id)
4867
+ const nextSourceId = existing.sourceNodeId
4868
+ ? (remappedPipeIds.get(existing.sourceNodeId) ?? existing.sourceNodeId)
4869
+ : undefined
4870
+ const nextTargetId = existing.targetNodeId
4871
+ ? (remappedPipeIds.get(existing.targetNodeId) ?? existing.targetNodeId)
4872
+ : undefined
4873
+ const rawWallId = typeof existing.pipe.wallId === 'string' ? existing.pipe.wallId : undefined
4874
+ const hostWall = rawWallId ? wallById.get(rawWallId) : undefined
4875
+ let safeWallId: string | undefined
4876
+ if (hostWall) {
4877
+ const wallRule = ctx.bones.wallRules.get(hostWall.id)
4878
+ const effThickM = resolveEffectiveWallThicknessM(hostWall.thicknessM, ctx.bones, wallRule)
4879
+ const fit = checkWetWallPipeFit({
4880
+ wallThicknessM: effThickM,
4881
+ pipeSize: existing.currentSize,
4882
+ material: existing.material,
4883
+ isLoadBearing: wallRule?.isLoadBearing ?? false,
4884
+ })
4885
+ const declFit = evaluatePlacementCandidate(
4886
+ [ctx.wetWallFitRule],
4887
+ {
4888
+ id: replacementId,
4889
+ kind: 'plumbing:pipe-run',
4890
+ system: 'fuel-gas',
4891
+ pos: existing.currentPath[0] ?? [0, 0, 0],
4892
+ nominalSizeIn: PIPE_NOMINAL_INCHES[existing.currentSize] ?? 0.5,
4893
+ wallThicknessM: effThickM,
4894
+ },
4895
+ 'placement',
4896
+ )
4897
+ if (fit.fits && declFit.legal) {
4898
+ safeWallId = hostWall.id
4899
+ }
4419
4900
  }
4901
+ const rawName =
4902
+ typeof existing.pipe.name === 'string' && existing.pipe.name.trim()
4903
+ ? existing.pipe.name.trim()
4904
+ : `Fuel Gas Line (${Math.round(existing.btuh / 1000)} kBTU/hr, IFGC 402.4)`
4905
+ const updatedName = existing.upsized
4906
+ ? /^\d+(?:-\d+\/\d+|\/\d+)?"\s+/.test(rawName)
4907
+ ? rawName.replace(/^\d+(?:-\d+\/\d+|\/\d+)?"/, existing.currentSize)
4908
+ : `${existing.currentSize} ${rawName}`
4909
+ : rawName
4910
+ allPipeRuns.push({
4911
+ id: replacementId,
4912
+ name: updatedName,
4913
+ system: 'fuel-gas',
4914
+ material: existing.material,
4915
+ nominalSize: existing.currentSize,
4916
+ path: existing.currentPath,
4917
+ slopeInPerFt: typeof existing.pipe.slopeInPerFt === 'number' ? existing.pipe.slopeInPerFt : 0,
4918
+ dfuLoad: 0,
4919
+ wsfuLoad: 0,
4920
+ gasBtuh: existing.btuh,
4921
+ ...(nextSourceId !== undefined ? { sourceNodeId: nextSourceId } : {}),
4922
+ ...(nextTargetId !== undefined ? { targetNodeId: nextTargetId } : {}),
4923
+ hasCleanout: Boolean(existing.pipe.hasCleanout),
4924
+ hasSedimentTrap: typeof existing.pipe.hasSedimentTrap === 'boolean' ? existing.pipe.hasSedimentTrap : true,
4925
+ hasShutoffWithin6Ft:
4926
+ typeof existing.pipe.hasShutoffWithin6Ft === 'boolean' ? existing.pipe.hasShutoffWithin6Ft : true,
4927
+ isHorizontalSanTee: Boolean(existing.pipe.isHorizontalSanTee),
4928
+ isMainVentStack: false,
4929
+ ...(safeWallId !== undefined ? { wallId: safeWallId } : {}),
4930
+ })
4931
+ }
4932
+
4933
+ for (const entry of prelimSyncGas) {
4934
+ const { target, currentSize, gasRoute } = entry
4420
4935
  allPipeRuns.push({
4421
4936
  id: nextAuxPipeId(),
4422
- name: `${sized.recommendedSize} Fuel Gas Line (${target.name}, ${Math.round(target.btuh / 1000)} kBTU/hr, IFGC 402.4)`,
4937
+ name: `${currentSize} Fuel Gas Line (${target.name}, ${Math.round(target.btuh / 1000)} kBTU/hr, IFGC 402.4)`,
4423
4938
  system: 'fuel-gas',
4424
4939
  material: 'black-iron',
4425
- nominalSize: sized.recommendedSize,
4940
+ nominalSize: currentSize,
4426
4941
  path: gasRoute.path,
4427
4942
  slopeInPerFt: 0,
4428
4943
  dfuLoad: 0,
@@ -4545,11 +5060,12 @@ export function planSyncPlumbingFixtures(
4545
5060
  fellBackToFullAutoPopulate: false,
4546
5061
  fixtures: newFixtures,
4547
5062
  pipeRuns: allPipeRuns,
5063
+ replacedPipeIds,
4548
5064
  newlyLinkedFurnishings,
4549
5065
  connectedFixtures,
4550
5066
  summary:
4551
5067
  newFixtures.length === 0 && allPipeRuns.length === 0
4552
5068
  ? '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).`,
5069
+ : `Synced ${newlyLinkedFurnishings} real-world fixture(s) (${newFixtures.length} rough-in(s)) and routed ${allPipeRuns.length} supply/DWV/vent/gas pipe run(s) across ${connectedFixtures} fixture(s)${replacedPipeIds.length > 0 ? ` (upsized ${replacedPipeIds.length} existing gas run(s) for IFGC 402.4 longest length)` : ''}.`,
4554
5070
  }
4555
5071
  }