@kruschdev/pascal-mep-kernel 0.1.0 → 0.1.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.
@@ -7,11 +7,11 @@ import {
7
7
  round22,
8
8
  round32,
9
9
  round42
10
- } from "./chunk-jfzqztgh.js";
10
+ } from "./chunk-yd3hcm7n.js";
11
11
  import {
12
12
  countPathOpeningPrismHits2,
13
13
  findNearestWallToPoint2
14
- } from "./chunk-2e23cyn0.js";
14
+ } from "./chunk-kmtew7g8.js";
15
15
 
16
16
  // src/router/cavity-graph.ts
17
17
  var DEFAULT_ROOF_CLEARANCE_M = 0.14;
@@ -160,9 +160,22 @@ function computeWallSplitParameters(walls, halfXZ, subdivStepM) {
160
160
  }
161
161
  let finalTs = deduplicateSortedNumbers(withSubdiv, WALL_STATION_DEDUPE_M, 0, w.lengthM);
162
162
  if (finalTs.length > MAX_STATIONS_PER_WALL) {
163
- finalTs = baseSorted.length <= MAX_STATIONS_PER_WALL ? baseSorted : baseSorted.slice(0, MAX_STATIONS_PER_WALL);
164
- if (finalTs[finalTs.length - 1] !== w.lengthM) {
165
- finalTs[finalTs.length - 1] = w.lengthM;
163
+ if (baseSorted.length <= MAX_STATIONS_PER_WALL) {
164
+ finalTs = baseSorted;
165
+ } else {
166
+ const sampled = [];
167
+ const lastIdx = baseSorted.length - 1;
168
+ for (let k = 0;k < MAX_STATIONS_PER_WALL; k++) {
169
+ const idx = Math.round(k * lastIdx / (MAX_STATIONS_PER_WALL - 1));
170
+ const val = baseSorted[idx];
171
+ if (sampled.length === 0 || val > sampled[sampled.length - 1] + 0.000001) {
172
+ sampled.push(val);
173
+ }
174
+ }
175
+ finalTs = sampled;
176
+ if (finalTs[finalTs.length - 1] !== w.lengthM) {
177
+ finalTs[finalTs.length - 1] = w.lengthM;
178
+ }
166
179
  }
167
180
  }
168
181
  result.push(finalTs);
@@ -190,7 +203,8 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
190
203
  const requestedGridStepM = typeof opts.plenumGridStepM === "number" && Number.isFinite(opts.plenumGridStepM) && opts.plenumGridStepM > 0.1 ? opts.plenumGridStepM : DEFAULT_PLENUM_GRID_STEP_M;
191
204
  const includeSubFloorLayer = opts.includeSubFloorLayer !== false;
192
205
  const subFloorBand = opts.subFloorBand === "crawlspace" ? "crawlspace" : "under-slab";
193
- const subFloorY = includeSubFloorLayer ? round32(typeof opts.subFloorElevationM === "number" && Number.isFinite(opts.subFloorElevationM) ? opts.subFloorElevationM : DEFAULT_SUB_FLOOR_ELEVATION_M) : null;
206
+ const maxAllowedSubFloorY = floor3(-Math.max(halfY, 0.05));
207
+ const subFloorY = includeSubFloorLayer ? round32(Math.min(maxAllowedSubFloorY, typeof opts.subFloorElevationM === "number" && Number.isFinite(opts.subFloorElevationM) ? opts.subFloorElevationM : DEFAULT_SUB_FLOOR_ELEVATION_M)) : null;
194
208
  const levelH = anatomy.getLevelHeightM(levelId);
195
209
  const walls = [...anatomy.getWalls(levelId)].sort((a, b) => a.id.localeCompare(b.id));
196
210
  const openingPrisms = anatomy.getOpeningPrisms(levelId);
@@ -336,6 +350,16 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
336
350
  }
337
351
  }
338
352
  if (bestId !== -1) {
353
+ const ev = vertices[bestId];
354
+ const nextMaxClearY = ev.maxClearY !== undefined ? Math.min(ev.maxClearY, floor3(maxClearY)) : floor3(maxClearY);
355
+ const nextIsRiserPier = Boolean(ev.isRiserPier && isRiserPier);
356
+ if (nextMaxClearY !== ev.maxClearY || nextIsRiserPier !== Boolean(ev.isRiserPier)) {
357
+ vertices[bestId] = {
358
+ ...ev,
359
+ isRiserPier: nextIsRiserPier,
360
+ maxClearY: nextMaxClearY
361
+ };
362
+ }
339
363
  return bestId;
340
364
  }
341
365
  const id = addVertex({
@@ -582,7 +606,7 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
582
606
  }
583
607
  } else {
584
608
  roofCol[iz] = roofShell.roofEnvelopeY(x, z);
585
- if (roofShell.isFlatRoof && roofShell.segments.length <= 1)
609
+ if (roofShell.isFlatRoof && roofShell.segments.length === 0)
586
610
  singleSegCol[iz] = 1;
587
611
  }
588
612
  } else {
@@ -618,11 +642,16 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
618
642
  const layerIds = [];
619
643
  if (!bounds || gridCols === 0 || gridRows === 0)
620
644
  return { vertexIds: layerIds };
645
+ const layerOpeningPrisms = band === "under-slab" || band === "crawlspace" ? [] : openingPrisms.filter((p) => layerY + halfY >= p.yMin - 0.000001 && layerY - halfY <= p.yMax + 0.000001);
646
+ const hasLayerOpenings = layerOpeningPrisms.length > 0;
621
647
  const isPointLegal = (x, z) => {
622
648
  if (!isFootprintStrictPointInside(x, z))
623
649
  return false;
624
650
  if (checkRoof && !isRoofPointClear(x, layerY, z))
625
651
  return false;
652
+ if (hasLayerOpenings && pointIntersectsAnyOpening(x, layerY, z, layerOpeningPrisms, openingPad)) {
653
+ return false;
654
+ }
626
655
  return true;
627
656
  };
628
657
  const isEdgeLegal = (a, b) => {
@@ -630,6 +659,9 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
630
659
  return false;
631
660
  if (checkRoof && !isRoofSegmentClear(a, b))
632
661
  return false;
662
+ if (hasLayerOpenings && segmentIntersectsAnyOpening(a, b, layerOpeningPrisms, openingPad)) {
663
+ return false;
664
+ }
633
665
  return true;
634
666
  };
635
667
  const gridIds = Array.from({ length: gridCols }, () => new Array(gridRows).fill(-1));
@@ -644,7 +676,11 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
644
676
  if (checkRoof && roofShell.hasRoofAbove && layerY + roofTopOffset > roofY + 0.000001)
645
677
  continue;
646
678
  const z = gridZ[iz];
647
- const maxClearY = checkRoof && roofShell.hasRoofAbove ? floor3(roofY - roofTopOffset) : round32(levelH);
679
+ if (hasLayerOpenings && pointIntersectsAnyOpening(x, layerY, z, layerOpeningPrisms, openingPad)) {
680
+ continue;
681
+ }
682
+ const defaultMaxClearY = layerY < 0 ? floor3(-halfY) : round32(levelH);
683
+ const maxClearY = checkRoof && roofShell.hasRoofAbove ? floor3(roofY - roofTopOffset) : defaultMaxClearY;
648
684
  const id = addVertex({
649
685
  pos: [x, layerY, z],
650
686
  band,
@@ -663,7 +699,7 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
663
699
  const uRoofFast = !checkRoof || !roofShell.hasRoofAbove || gridRoofOnSingleSeg[ix][iz] === 1;
664
700
  if (ix + 1 < gridCols && gridEdgeEastInside[ix][iz]) {
665
701
  const vid = gridIds[ix + 1][iz];
666
- if (vid !== -1 && (uRoofFast && gridRoofOnSingleSeg[ix + 1][iz] === 1 || !checkRoof || isRoofSegmentClear(pa, vertices[vid].pos))) {
702
+ if (vid !== -1 && (uRoofFast && gridRoofOnSingleSeg[ix + 1][iz] === 1 || !checkRoof || isRoofSegmentClear(pa, vertices[vid].pos)) && (!hasLayerOpenings || !segmentIntersectsAnyOpening(pa, vertices[vid].pos, layerOpeningPrisms, openingPad))) {
667
703
  addUndirectedEdge(uid, vid, {
668
704
  isWallEdge: false,
669
705
  isVerticalTransition: false,
@@ -674,7 +710,7 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
674
710
  }
675
711
  if (iz + 1 < gridRows && gridEdgeSouthInside[ix][iz]) {
676
712
  const vid = gridIds[ix][iz + 1];
677
- if (vid !== -1 && (uRoofFast && gridRoofOnSingleSeg[ix][iz + 1] === 1 || !checkRoof || isRoofSegmentClear(pa, vertices[vid].pos))) {
713
+ if (vid !== -1 && (uRoofFast && gridRoofOnSingleSeg[ix][iz + 1] === 1 || !checkRoof || isRoofSegmentClear(pa, vertices[vid].pos)) && (!hasLayerOpenings || !segmentIntersectsAnyOpening(pa, vertices[vid].pos, layerOpeningPrisms, openingPad))) {
678
714
  addUndirectedEdge(uid, vid, {
679
715
  isWallEdge: false,
680
716
  isVerticalTransition: false,
@@ -694,6 +730,9 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
694
730
  const pb = vertices[vid].pos;
695
731
  if (!isFootprintLayerSegInside(pa, pb))
696
732
  continue;
733
+ if (hasLayerOpenings && segmentIntersectsAnyOpening(pa, pb, layerOpeningPrisms, openingPad)) {
734
+ continue;
735
+ }
697
736
  if (uRoofFast && gridRoofOnSingleSeg[ix + 1][nz] === 1 || !checkRoof || isRoofSegmentClear(pa, pb)) {
698
737
  addUndirectedEdge(uid, vid, {
699
738
  isWallEdge: false,
@@ -749,7 +788,8 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
749
788
  return existing;
750
789
  if (!allowCreate)
751
790
  return -1;
752
- const cornerMaxClearY = checkRoof && roofShell.hasRoofAbove ? floor3(roofShell.roofEnvelopeY(cx, cz) - roofTopOffset) : round32(levelH);
791
+ const defaultCornerMaxClearY = layerY < 0 ? floor3(-halfY) : round32(levelH);
792
+ const cornerMaxClearY = checkRoof && roofShell.hasRoofAbove ? floor3(roofShell.roofEnvelopeY(cx, cz) - roofTopOffset) : defaultCornerMaxClearY;
753
793
  const cid = addVertex({
754
794
  pos: [cx, layerY, cz],
755
795
  band,
@@ -781,7 +821,8 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
781
821
  }
782
822
  if (tooClose)
783
823
  continue;
784
- const maxClearY = checkRoof && roofShell.hasRoofAbove ? floor3(roofShell.roofEnvelopeY(seed.x, seed.z) - roofTopOffset) : round32(levelH);
824
+ const defaultSeedMaxClearY = layerY < 0 ? floor3(-halfY) : round32(levelH);
825
+ const maxClearY = checkRoof && roofShell.hasRoofAbove ? floor3(roofShell.roofEnvelopeY(seed.x, seed.z) - roofTopOffset) : defaultSeedMaxClearY;
785
826
  const newId = addVertex({
786
827
  pos: seedPos,
787
828
  band,
@@ -855,10 +896,10 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
855
896
  }
856
897
  return { vertexIds: layerIds };
857
898
  };
858
- const plenumLayer = buildHorizontalLayer("overhead-plenum", ceilingPlenumY, true, false, COST_OVERHEAD_PLENUM);
899
+ const plenumLayer = ceilingPlenumY > 0.1 ? buildHorizontalLayer("overhead-plenum", ceilingPlenumY, true, false, COST_OVERHEAD_PLENUM) : { vertexIds: [] };
859
900
  const atticLayer = atticY !== null ? buildHorizontalLayer("attic", atticY, true, true, COST_ATTIC) : { vertexIds: [] };
860
901
  const subFloorLayer = subFloorY !== null ? buildHorizontalLayer(subFloorBand, subFloorY, false, false, COST_SUB_FLOOR) : { vertexIds: [] };
861
- const connectToNearestInLayer = (srcId, targetLayerIds, maxRadiusM, checkRoof, checkOpenings) => {
902
+ const connectToNearestInLayer = (srcId, targetLayerIds, maxRadiusM, checkRoof, checkOpenings, preferOrthogonal = false) => {
862
903
  if (targetLayerIds.length === 0)
863
904
  return false;
864
905
  const srcPos = vertices[srcId].pos;
@@ -878,7 +919,134 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
878
919
  for (let i = 0;i < candidates.length; i++) {
879
920
  const cand = candidates[i];
880
921
  const tid = cand.id;
881
- const targetPos = vertices[tid].pos;
922
+ const targetVertex = vertices[tid];
923
+ const targetPos = targetVertex.pos;
924
+ const dx = Math.abs(targetPos[0] - srcPos[0]);
925
+ const dy = Math.abs(targetPos[1] - srcPos[1]);
926
+ const dz = Math.abs(targetPos[2] - srcPos[2]);
927
+ const horizDist = Math.hypot(dx, dz);
928
+ if (preferOrthogonal && horizDist > 0.002) {
929
+ const isAxisAligned = dx <= 0.001 || dz <= 0.001;
930
+ if (dy <= 0.001) {
931
+ if (isAxisAligned) {
932
+ const directOk = isFootprintLayerSegInside(srcPos, targetPos) && (!checkRoof || isRoofSegmentClear(srcPos, targetPos)) && (!checkOpenings || !segmentIntersectsAnyOpening(srcPos, targetPos, openingPrisms, openingPad));
933
+ if (directOk) {
934
+ addUndirectedEdge(srcId, tid, {
935
+ isWallEdge: false,
936
+ isVerticalTransition: false,
937
+ baseCostWeight: COST_LAYER_TRANSITION,
938
+ bandOverride: targetVertex.band
939
+ });
940
+ return true;
941
+ }
942
+ } else if (vertices.length + 1 <= MAX_TOTAL_VERTICES_TARGET) {
943
+ const corners = [
944
+ [srcPos[0], targetPos[1], targetPos[2]],
945
+ [targetPos[0], targetPos[1], srcPos[2]]
946
+ ];
947
+ for (let ki = 0;ki < corners.length; ki++) {
948
+ const cornerPos = corners[ki];
949
+ const seg1Ok = isFootprintLayerSegInside(srcPos, cornerPos) && (!checkRoof || isRoofSegmentClear(srcPos, cornerPos)) && (!checkOpenings || !segmentIntersectsAnyOpening(srcPos, cornerPos, openingPrisms, openingPad));
950
+ if (!seg1Ok)
951
+ continue;
952
+ const seg2Ok = isFootprintLayerSegInside(cornerPos, targetPos) && (!checkRoof || isRoofSegmentClear(cornerPos, targetPos)) && (!checkOpenings || !segmentIntersectsAnyOpening(cornerPos, targetPos, openingPrisms, openingPad));
953
+ if (!seg2Ok)
954
+ continue;
955
+ const cornerMaxClearY = targetPos[1] < 0 ? floor3(-halfY) : checkRoof && roofShell.hasRoofAbove ? floor3(roofShell.roofEnvelopeY(cornerPos[0], cornerPos[2]) - roofTopOffset) : round32(levelH);
956
+ const cornerId = addVertex({
957
+ pos: cornerPos,
958
+ band: targetVertex.band,
959
+ maxClearY: cornerMaxClearY
960
+ });
961
+ addUndirectedEdge(srcId, cornerId, {
962
+ isWallEdge: false,
963
+ isVerticalTransition: false,
964
+ baseCostWeight: COST_LAYER_TRANSITION,
965
+ bandOverride: targetVertex.band
966
+ });
967
+ addUndirectedEdge(cornerId, tid, {
968
+ isWallEdge: false,
969
+ isVerticalTransition: false,
970
+ baseCostWeight: COST_LAYER_TRANSITION,
971
+ bandOverride: targetVertex.band
972
+ });
973
+ return true;
974
+ }
975
+ }
976
+ } else if (vertices.length + 2 <= MAX_TOTAL_VERTICES_TARGET) {
977
+ const plumbPos = [srcPos[0], targetPos[1], srcPos[2]];
978
+ const plumbOk = (!checkRoof || isRoofSegmentClear(srcPos, plumbPos)) && (!checkOpenings || !segmentIntersectsAnyOpening(srcPos, plumbPos, openingPrisms, openingPad));
979
+ if (plumbOk) {
980
+ if (isAxisAligned) {
981
+ const legOk = isFootprintLayerSegInside(plumbPos, targetPos) && (!checkRoof || isRoofSegmentClear(plumbPos, targetPos)) && (!checkOpenings || !segmentIntersectsAnyOpening(plumbPos, targetPos, openingPrisms, openingPad));
982
+ if (legOk) {
983
+ const plumbMaxClearY = targetPos[1] < 0 ? floor3(-halfY) : checkRoof && roofShell.hasRoofAbove ? floor3(roofShell.roofEnvelopeY(plumbPos[0], plumbPos[2]) - roofTopOffset) : round32(levelH);
984
+ const plumbId = addVertex({
985
+ pos: plumbPos,
986
+ band: targetVertex.band,
987
+ maxClearY: plumbMaxClearY
988
+ });
989
+ addUndirectedEdge(srcId, plumbId, {
990
+ isWallEdge: false,
991
+ isVerticalTransition: true,
992
+ baseCostWeight: COST_LAYER_TRANSITION
993
+ });
994
+ addUndirectedEdge(plumbId, tid, {
995
+ isWallEdge: false,
996
+ isVerticalTransition: false,
997
+ baseCostWeight: COST_LAYER_TRANSITION,
998
+ bandOverride: targetVertex.band
999
+ });
1000
+ return true;
1001
+ }
1002
+ } else {
1003
+ const corners = [
1004
+ [plumbPos[0], targetPos[1], targetPos[2]],
1005
+ [targetPos[0], targetPos[1], plumbPos[2]]
1006
+ ];
1007
+ for (let ki = 0;ki < corners.length; ki++) {
1008
+ const cornerPos = corners[ki];
1009
+ const seg1Ok = isFootprintLayerSegInside(plumbPos, cornerPos) && (!checkRoof || isRoofSegmentClear(plumbPos, cornerPos)) && (!checkOpenings || !segmentIntersectsAnyOpening(plumbPos, cornerPos, openingPrisms, openingPad));
1010
+ if (!seg1Ok)
1011
+ continue;
1012
+ const seg2Ok = isFootprintLayerSegInside(cornerPos, targetPos) && (!checkRoof || isRoofSegmentClear(cornerPos, targetPos)) && (!checkOpenings || !segmentIntersectsAnyOpening(cornerPos, targetPos, openingPrisms, openingPad));
1013
+ if (!seg2Ok)
1014
+ continue;
1015
+ const plumbMaxClearY = targetPos[1] < 0 ? floor3(-halfY) : checkRoof && roofShell.hasRoofAbove ? floor3(roofShell.roofEnvelopeY(plumbPos[0], plumbPos[2]) - roofTopOffset) : round32(levelH);
1016
+ const cornerMaxClearY = targetPos[1] < 0 ? floor3(-halfY) : checkRoof && roofShell.hasRoofAbove ? floor3(roofShell.roofEnvelopeY(cornerPos[0], cornerPos[2]) - roofTopOffset) : round32(levelH);
1017
+ const plumbId = addVertex({
1018
+ pos: plumbPos,
1019
+ band: targetVertex.band,
1020
+ maxClearY: plumbMaxClearY
1021
+ });
1022
+ const cornerId = addVertex({
1023
+ pos: cornerPos,
1024
+ band: targetVertex.band,
1025
+ maxClearY: cornerMaxClearY
1026
+ });
1027
+ addUndirectedEdge(srcId, plumbId, {
1028
+ isWallEdge: false,
1029
+ isVerticalTransition: true,
1030
+ baseCostWeight: COST_LAYER_TRANSITION
1031
+ });
1032
+ addUndirectedEdge(plumbId, cornerId, {
1033
+ isWallEdge: false,
1034
+ isVerticalTransition: false,
1035
+ baseCostWeight: COST_LAYER_TRANSITION,
1036
+ bandOverride: targetVertex.band
1037
+ });
1038
+ addUndirectedEdge(cornerId, tid, {
1039
+ isWallEdge: false,
1040
+ isVerticalTransition: false,
1041
+ baseCostWeight: COST_LAYER_TRANSITION,
1042
+ bandOverride: targetVertex.band
1043
+ });
1044
+ return true;
1045
+ }
1046
+ }
1047
+ }
1048
+ }
1049
+ }
882
1050
  if (cand.distSq > 0.00000001 && !isFootprintLayerSegInside(srcPos, targetPos))
883
1051
  continue;
884
1052
  if (checkRoof && !isRoofSegmentClear(srcPos, targetPos))
@@ -888,7 +1056,7 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
888
1056
  }
889
1057
  addUndirectedEdge(srcId, tid, {
890
1058
  isWallEdge: false,
891
- isVerticalTransition: true,
1059
+ isVerticalTransition: dy > 0.001,
892
1060
  baseCostWeight: COST_LAYER_TRANSITION
893
1061
  });
894
1062
  return true;
@@ -901,14 +1069,14 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
901
1069
  const topPlateIds = wallBandVertexIds["top-plate"];
902
1070
  for (let i = 0;i < topPlateIds.length; i++) {
903
1071
  const tpId = topPlateIds[i];
904
- connectToNearestInLayer(tpId, plenumLayer.vertexIds, wallToPlenumRadius, true, true);
1072
+ connectToNearestInLayer(tpId, plenumLayer.vertexIds, wallToPlenumRadius, true, true, true);
905
1073
  if (atticLayer.vertexIds.length > 0) {
906
- connectToNearestInLayer(tpId, atticLayer.vertexIds, wallToAtticRadius, true, true);
1074
+ connectToNearestInLayer(tpId, atticLayer.vertexIds, wallToAtticRadius, true, true, false);
907
1075
  }
908
1076
  }
909
1077
  for (let i = 0;i < atticLayer.vertexIds.length; i++) {
910
1078
  const avId = atticLayer.vertexIds[i];
911
- connectToNearestInLayer(avId, plenumLayer.vertexIds, plenumToAtticRadius, true, false);
1079
+ connectToNearestInLayer(avId, plenumLayer.vertexIds, plenumToAtticRadius, true, true, false);
912
1080
  }
913
1081
  if (subFloorLayer.vertexIds.length > 0) {
914
1082
  const connectedPierRoots = new Set;
@@ -922,7 +1090,7 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
922
1090
  if (rootId === undefined || connectedPierRoots.has(rootId))
923
1091
  continue;
924
1092
  connectedPierRoots.add(rootId);
925
- connectToNearestInLayer(rootId, subFloorLayer.vertexIds, wallToPlenumRadius, false, true);
1093
+ connectToNearestInLayer(rootId, subFloorLayer.vertexIds, wallToPlenumRadius, false, true, true);
926
1094
  }
927
1095
  }
928
1096
  }
@@ -943,6 +1111,8 @@ function compileLegalCavityGraph2(anatomy, levelId, opts = {}) {
943
1111
  };
944
1112
  }
945
1113
  function findLegalWallRiserPier2(graph, wallId, desiredT, fromY, toY) {
1114
+ if (!Number.isFinite(desiredT) || !Number.isFinite(fromY) || !Number.isFinite(toY))
1115
+ return null;
946
1116
  const piers = graph.wallRiserPiers.get(wallId);
947
1117
  if (!piers || piers.length === 0)
948
1118
  return null;
@@ -969,7 +1139,7 @@ function findLegalWallRiserPier2(graph, wallId, desiredT, fromY, toY) {
969
1139
  var DEFAULT_ROOF_CLEARANCE_M2 = 0.14;
970
1140
  var DEFAULT_MIN_SLOPE_IN_PER_FT = 0.25;
971
1141
  var UPHILL_TOL_M = 0.002;
972
- var DIR_BUCKETS = 13;
1142
+ var DIR_BUCKETS = 19;
973
1143
  var CLASH_PENALTY = 5000;
974
1144
  var OPENING_PENALTY = 2000;
975
1145
  var ROOF_PENALTY = 2000;
@@ -1086,8 +1256,10 @@ function dirToBucket(d) {
1086
1256
  const az = Math.abs(z);
1087
1257
  if (ay >= 0.85)
1088
1258
  return y >= 0 ? 5 : 6;
1089
- if (ay > 0.25)
1090
- return y >= 0 ? 11 : 12;
1259
+ if (ay > 0.25) {
1260
+ const quad = x >= 0 ? z >= 0 ? 0 : 1 : z >= 0 ? 2 : 3;
1261
+ return (y >= 0 ? 11 : 15) + quad;
1262
+ }
1091
1263
  if (ax >= 0.85)
1092
1264
  return x >= 0 ? 1 : 2;
1093
1265
  if (az >= 0.85)
@@ -1163,7 +1335,7 @@ function checkSegmentPhysicsOk(a, b, ctx) {
1163
1335
  }
1164
1336
  return true;
1165
1337
  }
1166
- function evaluatePolyline(rawPoints, ctx, allowExteriorEndpointMargin) {
1338
+ function evaluatePolyline(rawPoints, ctx, allowStartExteriorMargin, allowEndExteriorMargin = allowStartExteriorMargin) {
1167
1339
  const points = compactPolyline(rawPoints);
1168
1340
  const clashSet = new Set;
1169
1341
  let openingHits = 0;
@@ -1173,7 +1345,6 @@ function evaluatePolyline(rawPoints, ctx, allowExteriorEndpointMargin) {
1173
1345
  let internalBendDeg = 0;
1174
1346
  let firstDir = null;
1175
1347
  let lastDir = null;
1176
- const fpOpts = allowExteriorEndpointMargin ? { skipExteriorEndpointMarginM: 0.35 } : undefined;
1177
1348
  for (let i = 1;i < points.length; i++) {
1178
1349
  const a = points[i - 1];
1179
1350
  const b = points[i];
@@ -1195,8 +1366,17 @@ function evaluatePolyline(rawPoints, ctx, allowExteriorEndpointMargin) {
1195
1366
  if (segmentHitsAnyOpening(a, b, ctx.openingPrisms)) {
1196
1367
  openingHits += 1;
1197
1368
  }
1198
- if (footprintOk && !ctx.footprint.isSegmentInside(a, b, fpOpts)) {
1199
- footprintOk = false;
1369
+ if (footprintOk) {
1370
+ const segStartSkip = i === 1 && allowStartExteriorMargin;
1371
+ const segEndSkip = i === points.length - 1 && allowEndExteriorMargin;
1372
+ const segFpOpts = segStartSkip || segEndSkip ? {
1373
+ skipExteriorEndpointMarginM: 0.35,
1374
+ allowStartExteriorSkip: segStartSkip,
1375
+ allowEndExteriorSkip: segEndSkip
1376
+ } : undefined;
1377
+ if (!ctx.footprint.isSegmentInside(a, b, segFpOpts)) {
1378
+ footprintOk = false;
1379
+ }
1200
1380
  }
1201
1381
  if (physicsHardOk && !checkSegmentPhysicsOk(a, b, ctx)) {
1202
1382
  physicsHardOk = false;
@@ -1361,8 +1541,9 @@ function buildSpliceCandidatePolylines(a, b, role, mode, wall) {
1361
1541
  }
1362
1542
  return candidates;
1363
1543
  }
1364
- function evaluateSpliceBatch(endpoint, role, candidates, wallMap, ctx, endpointExterior) {
1544
+ function evaluateSpliceBatch(endpoint, role, candidates, wallMap, ctx, endpointExterior, maxBendDegrees) {
1365
1545
  const results = [];
1546
+ const validMaxBend = typeof maxBendDegrees === "number" && Number.isFinite(maxBendDegrees) ? maxBendDegrees : undefined;
1366
1547
  for (const v of candidates) {
1367
1548
  const a = role === "enter" ? endpoint : v.pos;
1368
1549
  const b = role === "enter" ? v.pos : endpoint;
@@ -1387,19 +1568,26 @@ function evaluateSpliceBatch(endpoint, role, candidates, wallMap, ctx, endpointE
1387
1568
  ranked.sort((x, y) => x.rawLen - y.rawLen);
1388
1569
  let bestClean = null;
1389
1570
  let bestCleanScore = Number.POSITIVE_INFINITY;
1571
+ const bestCleanByDir = new Map;
1390
1572
  let bestAny = null;
1391
1573
  let bestAnyScore = Number.POSITIVE_INFINITY;
1392
1574
  for (let ri = 0;ri < ranked.length; ri++) {
1393
1575
  const cand = ranked[ri];
1394
- if (bestClean !== null && cand.rawLen >= bestCleanScore - 0.000000001) {
1395
- break;
1396
- }
1397
- const ev = evaluatePolyline(cand.pts, ctx, endpointExterior);
1576
+ const ev = evaluatePolyline(cand.pts, ctx, role === "enter" && endpointExterior, role === "exit" && endpointExterior);
1398
1577
  const baseScore = ev.lengthM + ev.internalBendDeg * BEND_COST_PER_DEG;
1399
- const totalScore = baseScore + evalPenalty(ev);
1400
- if (isHardClean(ev) && baseScore < bestCleanScore) {
1401
- bestClean = ev;
1402
- bestCleanScore = baseScore;
1578
+ const bendExcessPen = validMaxBend !== undefined && ev.internalBendDeg > validMaxBend + 0.001 ? 200 * (ev.internalBendDeg - validMaxBend) / 90 : 0;
1579
+ const totalScore = baseScore + bendExcessPen + evalPenalty(ev);
1580
+ const bendOk = validMaxBend === undefined || ev.internalBendDeg <= validMaxBend + 0.001;
1581
+ if (isHardClean(ev) && bendOk) {
1582
+ if (baseScore < bestCleanScore) {
1583
+ bestClean = ev;
1584
+ bestCleanScore = baseScore;
1585
+ }
1586
+ const joinBucket = dirToBucket(role === "enter" ? ev.lastDir : ev.firstDir);
1587
+ const existingDir = bestCleanByDir.get(joinBucket);
1588
+ if (!existingDir || baseScore < existingDir.score) {
1589
+ bestCleanByDir.set(joinBucket, { ev, score: baseScore });
1590
+ }
1403
1591
  }
1404
1592
  if (totalScore < bestAnyScore) {
1405
1593
  bestAny = ev;
@@ -1407,21 +1595,23 @@ function evaluateSpliceBatch(endpoint, role, candidates, wallMap, ctx, endpointE
1407
1595
  }
1408
1596
  }
1409
1597
  if (bestAny) {
1598
+ const hardCleanByDir = [...bestCleanByDir.values()].sort((x, y) => x.score - y.score).map((x) => x.ev);
1410
1599
  results.push({
1411
1600
  vertexId: v.id,
1412
1601
  band: v.band,
1413
1602
  isWallEdge: WALL_BANDS2.has(v.band),
1414
1603
  hardClean: bestClean,
1604
+ hardCleanByDir,
1415
1605
  bestFallback: bestAny
1416
1606
  });
1417
1607
  }
1418
1608
  }
1419
1609
  return results;
1420
1610
  }
1421
- function buildSpliceConnections(endpoint, role, graph, allowedBandSet, wallMap, ctx) {
1611
+ function buildSpliceConnections(endpoint, role, graph, allowedBandSet, wallMap, ctx, maxBendDegrees) {
1422
1612
  const endpointExterior = !ctx.footprint.isPointInside(endpoint[0], endpoint[2]);
1423
1613
  const localCandidates = selectCandidateSpliceVertices(endpoint, graph, allowedBandSet, false);
1424
- const localResults = evaluateSpliceBatch(endpoint, role, localCandidates, wallMap, ctx, endpointExterior);
1614
+ const localResults = evaluateSpliceBatch(endpoint, role, localCandidates, wallMap, ctx, endpointExterior, maxBendDegrees);
1425
1615
  if (localResults.some((s) => s.hardClean !== null)) {
1426
1616
  return localResults;
1427
1617
  }
@@ -1431,7 +1621,7 @@ function buildSpliceConnections(endpoint, role, graph, allowedBandSet, wallMap,
1431
1621
  return localResults;
1432
1622
  return [
1433
1623
  ...localResults,
1434
- ...evaluateSpliceBatch(endpoint, role, expandedCandidates, wallMap, ctx, endpointExterior)
1624
+ ...evaluateSpliceBatch(endpoint, role, expandedCandidates, wallMap, ctx, endpointExterior, maxBendDegrees)
1435
1625
  ];
1436
1626
  }
1437
1627
  function resolveSharedDirectBand(from, to, graph, walls, allowedBandSet, mode) {
@@ -1665,12 +1855,13 @@ function runConstrainedAStar(params) {
1665
1855
  break;
1666
1856
  }
1667
1857
  if (cur.nodeId === START_ID) {
1668
- if (directShortcut && isHardClean(directShortcut.eval)) {
1858
+ if (directShortcut && (allowDegraded || isHardClean(directShortcut.eval))) {
1669
1859
  const ev = directShortcut.eval;
1670
1860
  const bend = ev.internalBendDeg;
1671
1861
  if (maxBendDeg === undefined || bend <= maxBendDeg + 0.001 || allowDegraded) {
1672
1862
  const bendExcessPen = maxBendDeg !== undefined && bend > maxBendDeg + 0.001 ? 200 * (bend - maxBendDeg) / 90 : 0;
1673
- const gNext = ev.lengthM * wallFactorFor(directShortcut.isWall) + bend * BEND_COST_PER_DEG + bendExcessPen;
1863
+ const penalty = allowDegraded ? evalPenalty(ev) : 0;
1864
+ const gNext = ev.lengthM * wallFactorFor(directShortcut.isWall) + bend * BEND_COST_PER_DEG + bendExcessPen + penalty;
1674
1865
  const bucket = dirToBucket(ev.lastDir);
1675
1866
  const nextKey = GOAL_ID * DIR_BUCKETS + bucket;
1676
1867
  const entrySeq = nextSeq++;
@@ -1695,38 +1886,39 @@ function runConstrainedAStar(params) {
1695
1886
  }
1696
1887
  }
1697
1888
  for (const splice of startSplices) {
1698
- const ev = allowDegraded ? splice.hardClean ?? splice.bestFallback : splice.hardClean;
1699
- if (!ev)
1700
- continue;
1701
- const bend = ev.internalBendDeg;
1702
- if (!allowDegraded && maxBendDeg !== undefined && bend > maxBendDeg + 0.001)
1703
- continue;
1704
- const bendExcessPen = maxBendDeg !== undefined && bend > maxBendDeg + 0.001 ? 200 * (bend - maxBendDeg) / 90 : 0;
1705
- const penalty = allowDegraded ? evalPenalty(ev) : 0;
1706
- const gNext = ev.lengthM * wallFactorFor(splice.isWallEdge) + bend * BEND_COST_PER_DEG + bendExcessPen + penalty;
1707
- const bucket = dirToBucket(ev.lastDir);
1708
- const nextKey = splice.vertexId * DIR_BUCKETS + bucket;
1709
- const entrySeq = nextSeq++;
1710
- if (tryAcceptLabel(nextKey, gNext, bend, entrySeq)) {
1711
- const v = graph.vertices[splice.vertexId];
1712
- parentState.set(entrySeq, {
1713
- prevSeq: cur.seq,
1714
- prevNode: START_ID,
1715
- points: ev.points,
1716
- band: splice.band,
1717
- wallId: v.wallId
1718
- });
1719
- const h = dist32(v.pos, to) * minWeightScale;
1720
- heap.push({
1721
- f: gNext + h,
1722
- g: gNext,
1723
- seq: entrySeq,
1724
- nodeId: splice.vertexId,
1725
- dirBucket: bucket,
1726
- dir: ev.lastDir,
1727
- bendDeg: bend,
1728
- stateKey: nextKey
1729
- });
1889
+ const spliceVariants = splice.hardCleanByDir.length > 0 ? splice.hardCleanByDir : allowDegraded ? [splice.bestFallback] : [];
1890
+ for (let si = 0;si < spliceVariants.length; si++) {
1891
+ const ev = spliceVariants[si];
1892
+ const bend = ev.internalBendDeg;
1893
+ if (!allowDegraded && maxBendDeg !== undefined && bend > maxBendDeg + 0.001)
1894
+ continue;
1895
+ const bendExcessPen = maxBendDeg !== undefined && bend > maxBendDeg + 0.001 ? 200 * (bend - maxBendDeg) / 90 : 0;
1896
+ const penalty = allowDegraded ? evalPenalty(ev) : 0;
1897
+ const gNext = ev.lengthM * wallFactorFor(splice.isWallEdge) + bend * BEND_COST_PER_DEG + bendExcessPen + penalty;
1898
+ const bucket = dirToBucket(ev.lastDir);
1899
+ const nextKey = splice.vertexId * DIR_BUCKETS + bucket;
1900
+ const entrySeq = nextSeq++;
1901
+ if (tryAcceptLabel(nextKey, gNext, bend, entrySeq)) {
1902
+ const v = graph.vertices[splice.vertexId];
1903
+ parentState.set(entrySeq, {
1904
+ prevSeq: cur.seq,
1905
+ prevNode: START_ID,
1906
+ points: ev.points,
1907
+ band: splice.band,
1908
+ wallId: v.wallId
1909
+ });
1910
+ const h = dist32(v.pos, to) * minWeightScale;
1911
+ heap.push({
1912
+ f: gNext + h,
1913
+ g: gNext,
1914
+ seq: entrySeq,
1915
+ nodeId: splice.vertexId,
1916
+ dirBucket: bucket,
1917
+ dir: ev.lastDir,
1918
+ bendDeg: bend,
1919
+ stateKey: nextKey
1920
+ });
1921
+ }
1730
1922
  }
1731
1923
  }
1732
1924
  continue;
@@ -1734,12 +1926,14 @@ function runConstrainedAStar(params) {
1734
1926
  const uVertex = graph.vertices[cur.nodeId];
1735
1927
  const goalSplice = goalSplicesByVertex.get(cur.nodeId);
1736
1928
  if (goalSplice) {
1737
- const ev = allowDegraded ? goalSplice.hardClean ?? goalSplice.bestFallback : goalSplice.hardClean;
1738
- if (ev) {
1929
+ const goalVariants = goalSplice.hardCleanByDir.length > 0 ? goalSplice.hardCleanByDir : allowDegraded ? [goalSplice.bestFallback] : [];
1930
+ for (let gi = 0;gi < goalVariants.length; gi++) {
1931
+ const ev = goalVariants[gi];
1739
1932
  const joinTurn = turnAngleDeg(cur.dir, ev.firstDir);
1740
1933
  const nextBend = cur.bendDeg + joinTurn + ev.internalBendDeg;
1741
1934
  if (allowDegraded || maxBendDeg === undefined || nextBend <= maxBendDeg + 0.001) {
1742
- const bendExcessPen = maxBendDeg !== undefined && nextBend > maxBendDeg + 0.001 ? 200 * (nextBend - maxBendDeg) / 90 : 0;
1935
+ const incBendExcess = maxBendDeg !== undefined && nextBend > maxBendDeg + 0.001 ? Math.max(0, nextBend - Math.max(maxBendDeg, cur.bendDeg)) : 0;
1936
+ const bendExcessPen = incBendExcess > 0 ? 200 * incBendExcess / 90 : 0;
1743
1937
  const penalty = allowDegraded ? evalPenalty(ev) : 0;
1744
1938
  const gNext = cur.g + ev.lengthM * wallFactorFor(goalSplice.isWallEdge) + (joinTurn + ev.internalBendDeg) * BEND_COST_PER_DEG + bendExcessPen + penalty;
1745
1939
  const bucket = dirToBucket(ev.lastDir ?? cur.dir);
@@ -1782,7 +1976,8 @@ function runConstrainedAStar(params) {
1782
1976
  const nextBend = cur.bendDeg + turn;
1783
1977
  if (!allowDegraded && maxBendDeg !== undefined && nextBend > maxBendDeg + 0.001)
1784
1978
  continue;
1785
- const bendExcessPen = maxBendDeg !== undefined && nextBend > maxBendDeg + 0.001 ? 200 * (nextBend - maxBendDeg) / 90 : 0;
1979
+ const incBendExcess = maxBendDeg !== undefined && nextBend > maxBendDeg + 0.001 ? Math.max(0, nextBend - Math.max(maxBendDeg, cur.bendDeg)) : 0;
1980
+ const bendExcessPen = incBendExcess > 0 ? 200 * incBendExcess / 90 : 0;
1786
1981
  const baseW = Number.isFinite(edge.baseCostWeight) && edge.baseCostWeight > 0 ? edge.baseCostWeight : 1;
1787
1982
  const stepLen = Number.isFinite(edge.lengthM) && edge.lengthM >= 0 ? edge.lengthM : dist32(uVertex.pos, vVertex.pos);
1788
1983
  const gNext = cur.g + stepLen * baseW * wallFactorFor(edge.isWallEdge) + turn * BEND_COST_PER_DEG + bendExcessPen + (allowDegraded ? ev.penalty : 0);
@@ -1863,7 +2058,8 @@ function applyLateralStagger(rawPoints, wallIdsByPoint, staggerM, wallMap, ctx,
1863
2058
  }
1864
2059
  const firstPt = rawPoints[0];
1865
2060
  const lastPt = rawPoints[rawPoints.length - 1];
1866
- const allowExteriorEndpointMargin = !ctx.footprint.isPointInside(firstPt[0], firstPt[2]) || !ctx.footprint.isPointInside(lastPt[0], lastPt[2]);
2061
+ const allowStartExteriorMargin = !ctx.footprint.isPointInside(firstPt[0], firstPt[2]);
2062
+ const allowEndExteriorMargin = !ctx.footprint.isPointInside(lastPt[0], lastPt[2]);
1867
2063
  const segCount = rawPoints.length - 1;
1868
2064
  const segWalls = new Array(segCount).fill(undefined);
1869
2065
  let hasWallSeg = false;
@@ -1920,7 +2116,7 @@ function applyLateralStagger(rawPoints, wallIdsByPoint, staggerM, wallMap, ctx,
1920
2116
  const off = staggerM * sign * (wallNormalSign.get(w.id) ?? 1);
1921
2117
  return [pt[0] + w.nx * off, pt[1], pt[2] + w.nz * off];
1922
2118
  };
1923
- const baseEval = evaluatePolyline(rawPoints, ctx, allowExteriorEndpointMargin);
2119
+ const baseEval = evaluatePolyline(rawPoints, ctx, allowStartExteriorMargin, allowEndExteriorMargin);
1924
2120
  for (const sign of [1, -1]) {
1925
2121
  const out = [firstPt];
1926
2122
  const firstWall = segWalls[0];
@@ -1977,24 +2173,30 @@ function applyLateralStagger(rawPoints, wallIdsByPoint, staggerM, wallMap, ctx,
1977
2173
  if (maxBendDegrees !== undefined && Number.isFinite(maxBendDegrees) && countPathBendDegrees2(compacted) > maxBendDegrees + 0.01) {
1978
2174
  continue;
1979
2175
  }
1980
- const testEval = evaluatePolyline(compacted, ctx, allowExteriorEndpointMargin);
1981
- if (testEval.clashNodeIds.length <= baseEval.clashNodeIds.length && testEval.openingHits <= baseEval.openingHits && (!baseEval.roofOk || testEval.roofOk) && (!baseEval.footprintOk || testEval.footprintOk)) {
2176
+ const testEval = evaluatePolyline(compacted, ctx, allowStartExteriorMargin, allowEndExteriorMargin);
2177
+ if (testEval.clashNodeIds.length <= baseEval.clashNodeIds.length && testEval.openingHits <= baseEval.openingHits && (!baseEval.roofOk || testEval.roofOk) && (!baseEval.footprintOk || testEval.footprintOk) && (!baseEval.physicsHardOk || testEval.physicsHardOk)) {
1982
2178
  return compacted;
1983
2179
  }
1984
2180
  }
1985
2181
  return rawPoints;
1986
2182
  }
1987
- function shapeEuclideanCavity(waypoints, vertexBands, ctx) {
2183
+ function shapeEuclideanCavity(waypoints, vertexBands, ctx, maxBendDegrees, startExterior = false, endExterior = false) {
2184
+ const compactedBase = compactPolyline(waypoints);
1988
2185
  if (waypoints.length <= 2)
1989
- return compactPolyline(waypoints);
1990
- const canShortcut = (a, b) => {
2186
+ return compactedBase;
2187
+ const canShortcut = (a, b, allowStartSkip, allowEndSkip) => {
1991
2188
  if (ctx.occupancy.segmentClashes(a, b, ctx.clashParams).length > 0)
1992
2189
  return false;
1993
2190
  if (segmentHitsAnyOpening(a, b, ctx.openingPrisms))
1994
2191
  return false;
1995
2192
  if (!ctx.roofShell.isPathClearOfRoof([a, b], ctx.halfY, ctx.roofClearanceM))
1996
2193
  return false;
1997
- if (!ctx.footprint.isSegmentInside(a, b))
2194
+ const fpOpts = allowStartSkip || allowEndSkip ? {
2195
+ skipExteriorEndpointMarginM: 0.35,
2196
+ allowStartExteriorSkip: allowStartSkip,
2197
+ allowEndExteriorSkip: allowEndSkip
2198
+ } : undefined;
2199
+ if (!ctx.footprint.isSegmentInside(a, b, fpOpts))
1998
2200
  return false;
1999
2201
  if (ctx.minHorizY !== undefined && distXZ2(a, b) > 0.01) {
2000
2202
  if (a[1] < ctx.minHorizY - 0.0001 || b[1] < ctx.minHorizY - 0.0001)
@@ -2023,7 +2225,9 @@ function shapeEuclideanCavity(waypoints, vertexBands, ctx) {
2023
2225
  }
2024
2226
  if (!spanValid)
2025
2227
  continue;
2026
- if (canShortcut(waypoints[i], waypoints[j])) {
2228
+ const segStartSkip = i === 0 && startExterior;
2229
+ const segEndSkip = j === waypoints.length - 1 && endExterior;
2230
+ if (canShortcut(waypoints[i], waypoints[j], segStartSkip, segEndSkip)) {
2027
2231
  bestJ = j;
2028
2232
  break;
2029
2233
  }
@@ -2032,7 +2236,11 @@ function shapeEuclideanCavity(waypoints, vertexBands, ctx) {
2032
2236
  result.push(waypoints[bestJ]);
2033
2237
  i = bestJ;
2034
2238
  }
2035
- return compactPolyline(result);
2239
+ const compacted = compactPolyline(result);
2240
+ if (typeof maxBendDegrees === "number" && Number.isFinite(maxBendDegrees) && countPathBendDegrees2(compacted) > maxBendDegrees + 0.01 && countPathBendDegrees2(compactedBase) <= maxBendDegrees + 0.01) {
2241
+ return compactedBase;
2242
+ }
2243
+ return compacted;
2036
2244
  }
2037
2245
  function buildGravitySlopedCandidate(pts, slopeRatio, remHorizM, toY, anchorToTargetStart, hasHeadForTarget) {
2038
2246
  const out = [pts[0]];
@@ -2080,7 +2288,7 @@ function buildGravitySlopedCandidate(pts, slopeRatio, remHorizM, toY, anchorToTa
2080
2288
  }
2081
2289
  return out.length >= 2 ? compactPolyline(out) : [pts[0], [pts[pts.length - 1][0], curY, pts[pts.length - 1][2]]];
2082
2290
  }
2083
- function shapeGravitySlope(rawPoints, minSlopeInPerFt, ctx, allowExteriorEndpointMargin) {
2291
+ function shapeGravitySlope(rawPoints, minSlopeInPerFt, ctx, allowStartExteriorMargin, allowEndExteriorMargin) {
2084
2292
  const pts = compactPolyline(rawPoints);
2085
2293
  if (pts.length < 2) {
2086
2294
  return { path: pts, slopeInPerFt: undefined };
@@ -2098,9 +2306,9 @@ function shapeGravitySlope(rawPoints, minSlopeInPerFt, ctx, allowExteriorEndpoin
2098
2306
  if (hasHeadForTarget) {
2099
2307
  const targetAnchored = buildGravitySlopedCandidate(pts, slopeRatio, remHorizM, toY, true, true);
2100
2308
  const trenchAnchored = buildGravitySlopedCandidate(pts, slopeRatio, remHorizM, toY, false, true);
2101
- const evalTarget = evaluatePolyline(targetAnchored, ctx, allowExteriorEndpointMargin);
2309
+ const evalTarget = evaluatePolyline(targetAnchored, ctx, allowStartExteriorMargin, allowEndExteriorMargin);
2102
2310
  const penTarget = evalPenalty(evalTarget);
2103
- const evalTrench = evaluatePolyline(trenchAnchored, ctx, allowExteriorEndpointMargin);
2311
+ const evalTrench = evaluatePolyline(trenchAnchored, ctx, allowStartExteriorMargin, allowEndExteriorMargin);
2104
2312
  const penTrench = evalPenalty(evalTrench);
2105
2313
  if (penTrench < penTarget) {
2106
2314
  finalPts = trenchAnchored;
@@ -2111,7 +2319,7 @@ function shapeGravitySlope(rawPoints, minSlopeInPerFt, ctx, allowExteriorEndpoin
2111
2319
  }
2112
2320
  } else {
2113
2321
  finalPts = buildGravitySlopedCandidate(pts, slopeRatio, remHorizM, toY, false, false);
2114
- evaluatePolyline(finalPts, ctx, allowExteriorEndpointMargin);
2322
+ evaluatePolyline(finalPts, ctx, allowStartExteriorMargin, allowEndExteriorMargin);
2115
2323
  }
2116
2324
  let totalHorizM = 0;
2117
2325
  let totalHorizDropM = 0;
@@ -2127,7 +2335,7 @@ function shapeGravitySlope(rawPoints, minSlopeInPerFt, ctx, allowExteriorEndpoin
2127
2335
  const slopeInPerFt = totalHorizM > 0.0001 ? round42(totalHorizDropM / totalHorizM * 12) : undefined;
2128
2336
  return { path: finalPts, slopeInPerFt };
2129
2337
  }
2130
- function shapeNonDescendingVent(rawPoints, from, to, minHorizontalElevationM, ctx, allowExteriorEndpointMargin) {
2338
+ function shapeNonDescendingVent(rawPoints, from, to, minHorizontalElevationM, ctx, allowStartExteriorMargin, allowEndExteriorMargin) {
2131
2339
  const pts = compactPolyline(rawPoints);
2132
2340
  if (pts.length < 2)
2133
2341
  return pts;
@@ -2136,24 +2344,37 @@ function shapeNonDescendingVent(rawPoints, from, to, minHorizontalElevationM, ct
2136
2344
  const ceilingY = Math.max(floorY, tieInY);
2137
2345
  const out = [pts[0]];
2138
2346
  let curY = pts[0][1];
2347
+ let accumBelowFloorHorizM = 0;
2139
2348
  for (let i = 1;i < pts.length; i++) {
2140
2349
  const prev = out[out.length - 1];
2141
2350
  const raw = pts[i];
2142
2351
  const hDist = distXZ2(prev, raw);
2143
2352
  const isLast = i === pts.length - 1;
2353
+ const targetY = Math.max(curY, Math.min(raw[1], ceilingY));
2144
2354
  if (hDist < 0.0001) {
2145
- const targetY = Math.max(curY, Math.min(raw[1], ceilingY));
2146
2355
  if (targetY > curY + 0.0001) {
2147
2356
  out.push([raw[0], targetY, raw[2]]);
2148
2357
  curY = targetY;
2149
2358
  }
2150
2359
  continue;
2151
2360
  }
2361
+ if (curY < floorY - 0.0001 && targetY < floorY - 0.0001 && hDist <= 0.01 && accumBelowFloorHorizM + hDist <= 0.01 - 0.000001) {
2362
+ if (targetY > curY + 0.0001) {
2363
+ out.push([prev[0], targetY, prev[2]]);
2364
+ curY = targetY;
2365
+ }
2366
+ accumBelowFloorHorizM += hDist;
2367
+ out.push([raw[0], curY, raw[2]]);
2368
+ continue;
2369
+ }
2152
2370
  const clampedRawY = Math.min(raw[1], ceilingY);
2153
2371
  const horizY = Math.min(ceilingY, Math.max(curY, floorY, clampedRawY));
2154
2372
  if (horizY > curY + 0.0001) {
2155
2373
  out.push([prev[0], horizY, prev[2]]);
2156
2374
  curY = horizY;
2375
+ if (curY >= floorY - 0.0001) {
2376
+ accumBelowFloorHorizM = 0;
2377
+ }
2157
2378
  }
2158
2379
  out.push([raw[0], curY, raw[2]]);
2159
2380
  if (isLast && tieInY > curY + 0.0001) {
@@ -2162,7 +2383,7 @@ function shapeNonDescendingVent(rawPoints, from, to, minHorizontalElevationM, ct
2162
2383
  }
2163
2384
  }
2164
2385
  const shaped = compactPolyline(out);
2165
- evaluatePolyline(shaped, ctx, allowExteriorEndpointMargin);
2386
+ evaluatePolyline(shaped, ctx, allowStartExteriorMargin, allowEndExteriorMargin);
2166
2387
  return shaped;
2167
2388
  }
2168
2389
  function buildDisconnectedFallbackPath(from, to, mode, graph, allowedBands) {
@@ -2172,16 +2393,16 @@ function buildDisconnectedFallbackPath(from, to, mode, graph, allowedBands) {
2172
2393
  const primaryBand = allowedBands[0];
2173
2394
  const cruiseY = primaryBand === "attic" && graph.atticY !== null ? graph.atticY : (primaryBand === "under-slab" || primaryBand === "crawlspace") && graph.subFloorY !== null ? graph.subFloorY : primaryBand === "overhead-plenum" ? graph.ceilingPlenumY : mode === "gravity-slope" ? Math.min(from[1], to[1]) : Math.max(from[1], to[1]);
2174
2395
  const pts = [from];
2175
- if (Math.abs(cruiseY - from[1]) > 0.03) {
2396
+ if (Math.abs(cruiseY - from[1]) > 0.0001) {
2176
2397
  pts.push([from[0], cruiseY, from[2]]);
2177
2398
  }
2178
- if (Math.abs(to[0] - from[0]) > 0.03 && Math.abs(to[2] - from[2]) > 0.03) {
2399
+ if (Math.abs(to[0] - from[0]) > 0.0001 && Math.abs(to[2] - from[2]) > 0.0001) {
2179
2400
  pts.push([to[0], cruiseY, from[2]]);
2180
2401
  }
2181
- pts.push([to[0], cruiseY, to[2]]);
2182
- if (Math.abs(to[1] - cruiseY) > 0.03) {
2183
- pts.push(to);
2402
+ if (Math.abs(to[1] - cruiseY) > 0.0001) {
2403
+ pts.push([to[0], cruiseY, to[2]]);
2184
2404
  }
2405
+ pts.push(to);
2185
2406
  return compactPolyline(pts);
2186
2407
  }
2187
2408
  function routeInLegalCavities2(params) {
@@ -2246,7 +2467,7 @@ function routeInLegalCavities2(params) {
2246
2467
  }
2247
2468
  let minBaseWeight = 1;
2248
2469
  if (typeof graph.minBaseWeight === "number" && Number.isFinite(graph.minBaseWeight) && graph.minBaseWeight > 0) {
2249
- minBaseWeight = graph.minBaseWeight;
2470
+ minBaseWeight = Math.min(1, graph.minBaseWeight);
2250
2471
  } else {
2251
2472
  for (let u = 0;u < graph.adjacency.length; u++) {
2252
2473
  const edges = graph.adjacency[u];
@@ -2260,16 +2481,18 @@ function routeInLegalCavities2(params) {
2260
2481
  }
2261
2482
  }
2262
2483
  }
2263
- const minWeightScale = Math.max(0.1, minBaseWeight * (request.preferWallFollowing ? 0.85 : 1));
2484
+ const minWeightScale = Math.max(0.000001, minBaseWeight * (request.preferWallFollowing ? 0.85 : 1));
2485
+ const startExterior = !footprint.isPointInside(from[0], from[2]);
2486
+ const endExterior = !footprint.isPointInside(to[0], to[2]);
2264
2487
  const sharedDirect = resolveSharedDirectBand(from, to, graph, walls, allowedBandSet, request.mode);
2265
2488
  const skipWallDirectForStagger = sharedDirect?.isWall === true && request.mode === "orthogonal" && typeof request.lateralStaggerM === "number" && Math.abs(request.lateralStaggerM) > 0.0001;
2266
2489
  const directShortcut = sharedDirect && !skipWallDirectForStagger ? {
2267
- eval: evaluatePolyline([from, to], ctx, false),
2490
+ eval: evaluatePolyline([from, to], ctx, startExterior, endExterior),
2268
2491
  band: sharedDirect.band,
2269
2492
  isWall: sharedDirect.isWall
2270
2493
  } : null;
2271
- const startSplices = buildSpliceConnections(from, "enter", graph, allowedBandSet, wallMap, ctx);
2272
- const goalSplices = buildSpliceConnections(to, "exit", graph, allowedBandSet, wallMap, ctx);
2494
+ const startSplices = buildSpliceConnections(from, "enter", graph, allowedBandSet, wallMap, ctx, request.maxBendDegrees);
2495
+ const goalSplices = buildSpliceConnections(to, "exit", graph, allowedBandSet, wallMap, ctx, request.maxBendDegrees);
2273
2496
  const goalSplicesByVertex = new Map;
2274
2497
  for (const gs of goalSplices)
2275
2498
  goalSplicesByVertex.set(gs.vertexId, gs);
@@ -2323,7 +2546,6 @@ function routeInLegalCavities2(params) {
2323
2546
  return;
2324
2547
  });
2325
2548
  }
2326
- const hasExteriorEndpoint = !footprint.isPointInside(from[0], from[2]) || !footprint.isPointInside(to[0], to[2]);
2327
2549
  let shapedPath = compactPolyline(rawPath);
2328
2550
  let slopeInPerFt;
2329
2551
  if (request.mode === "orthogonal") {
@@ -2332,15 +2554,22 @@ function routeInLegalCavities2(params) {
2332
2554
  }
2333
2555
  shapedPath = compactPolyline(shapedPath);
2334
2556
  } else if (request.mode === "euclidean-cavity") {
2335
- shapedPath = shapeEuclideanCavity(rawPath, vertexBands, ctx);
2557
+ shapedPath = shapeEuclideanCavity(rawPath, vertexBands, ctx, request.maxBendDegrees, startExterior, endExterior);
2336
2558
  } else if (request.mode === "gravity-slope") {
2337
- const sloped = shapeGravitySlope(shapedPath, minSlopeInPerFt, ctx, hasExteriorEndpoint);
2559
+ const sloped = shapeGravitySlope(shapedPath, minSlopeInPerFt, ctx, startExterior, endExterior);
2338
2560
  shapedPath = sloped.path;
2339
2561
  slopeInPerFt = sloped.slopeInPerFt;
2340
2562
  } else if (request.mode === "non-descending-vent") {
2341
- shapedPath = shapeNonDescendingVent(shapedPath, from, to, minHorizY, ctx, hasExteriorEndpoint);
2563
+ shapedPath = shapeNonDescendingVent(shapedPath, from, to, minHorizY, ctx, startExterior, endExterior);
2564
+ }
2565
+ const roundedPath = [];
2566
+ for (let i = 0;i < shapedPath.length; i++) {
2567
+ const pt = roundVec3(shapedPath[i]);
2568
+ const prev = roundedPath[roundedPath.length - 1];
2569
+ if (!prev || prev[0] !== pt[0] || prev[1] !== pt[1] || prev[2] !== pt[2]) {
2570
+ roundedPath.push(pt);
2571
+ }
2342
2572
  }
2343
- const roundedPath = shapedPath.map(roundVec3);
2344
2573
  if (roundedPath.length === 0) {
2345
2574
  roundedPath.push(roundVec3(from), roundVec3(to));
2346
2575
  } else if (roundedPath.length === 1) {
@@ -2397,16 +2626,32 @@ function finalizeRouteResult(params) {
2397
2626
  const roofViolation = !roofShell.isPathClearOfRoof(path, halfY, roofClearanceM);
2398
2627
  const sanitizedFrom = sanitizeVec3(request.from);
2399
2628
  const sanitizedTo = sanitizeVec3(request.to);
2400
- const hasExteriorEndpoint = !footprint.isPointInside(sanitizedFrom[0], sanitizedFrom[2]) || !footprint.isPointInside(sanitizedTo[0], sanitizedTo[2]);
2401
- const outdoorVoidViolation = hasExteriorEndpoint ? footprint.pathCrossesOutdoorVoid(path, { skipExteriorEndpointMarginM: 0.35 }) : footprint.pathCrossesOutdoorVoid(path);
2629
+ const startExterior = !footprint.isPointInside(sanitizedFrom[0], sanitizedFrom[2]);
2630
+ const endExterior = !footprint.isPointInside(sanitizedTo[0], sanitizedTo[2]);
2631
+ const outdoorVoidViolation = startExterior || endExterior ? footprint.pathCrossesOutdoorVoid(path, {
2632
+ skipExteriorEndpointMarginM: 0.35,
2633
+ allowStartExteriorSkip: startExterior,
2634
+ allowEndExteriorSkip: endExterior
2635
+ }) : footprint.pathCrossesOutdoorVoid(path);
2402
2636
  const lengthM = round42(polylineLengthM2(path));
2403
2637
  const horizontalLengthM = round42(polylineHorizontalLengthM2(path));
2404
2638
  const bendDegrees = round22(countPathBendDegrees2(path));
2405
2639
  const { elbows90, elbows45 } = countPathElbows2(path);
2406
2640
  const elbowCount = elbows90 + elbows45;
2407
2641
  const bendViolation = typeof request.maxBendDegrees === "number" && Number.isFinite(request.maxBendDegrees) && bendDegrees > request.maxBendDegrees + 0.01;
2642
+ const minHorizY = typeof request.minHorizontalElevationM === "number" && Number.isFinite(request.minHorizontalElevationM) ? request.minHorizontalElevationM : undefined;
2408
2643
  let physicsViolation = false;
2409
- if (request.mode === "gravity-slope" && path.length >= 2) {
2644
+ if (minHorizY !== undefined && path.length >= 2) {
2645
+ for (let i = 1;i < path.length; i++) {
2646
+ const a = path[i - 1];
2647
+ const b = path[i];
2648
+ if (distXZ2(a, b) > 0.01 && (a[1] < minHorizY - 0.001 || b[1] < minHorizY - 0.001)) {
2649
+ physicsViolation = true;
2650
+ break;
2651
+ }
2652
+ }
2653
+ }
2654
+ if (!physicsViolation && request.mode === "gravity-slope" && path.length >= 2) {
2410
2655
  const fromY = sanitizedFrom[1];
2411
2656
  const toY = sanitizedTo[1];
2412
2657
  const slopeRatio = (typeof request.minSlopeInPerFt === "number" && Number.isFinite(request.minSlopeInPerFt) && request.minSlopeInPerFt >= 0 ? request.minSlopeInPerFt : DEFAULT_MIN_SLOPE_IN_PER_FT) / 12;
@@ -2429,21 +2674,23 @@ function finalizeRouteResult(params) {
2429
2674
  physicsViolation = true;
2430
2675
  }
2431
2676
  }
2432
- } else if (request.mode === "non-descending-vent" && path.length >= 2) {
2677
+ } else if (!physicsViolation && request.mode === "non-descending-vent" && path.length >= 2) {
2678
+ const fromY = sanitizedFrom[1];
2433
2679
  const toY = sanitizedTo[1];
2434
- const minHorizY = typeof request.minHorizontalElevationM === "number" && Number.isFinite(request.minHorizontalElevationM) ? request.minHorizontalElevationM : undefined;
2435
- for (let i = 1;i < path.length; i++) {
2680
+ const ceilingEnforced = minHorizY === undefined || minHorizY <= toY + UPHILL_TOL_M;
2681
+ if (fromY > toY + UPHILL_TOL_M) {
2682
+ physicsViolation = true;
2683
+ }
2684
+ for (let i = 1;!physicsViolation && i < path.length; i++) {
2436
2685
  const a = path[i - 1];
2437
2686
  const b = path[i];
2438
2687
  if (b[1] - a[1] < -UPHILL_TOL_M) {
2439
2688
  physicsViolation = true;
2440
2689
  break;
2441
2690
  }
2442
- if (minHorizY !== undefined && distXZ2(a, b) > 0.01) {
2443
- if (a[1] < minHorizY - 0.001 || b[1] < minHorizY - 0.001) {
2444
- physicsViolation = true;
2445
- break;
2446
- }
2691
+ if (ceilingEnforced && (a[1] > toY + UPHILL_TOL_M || b[1] > toY + UPHILL_TOL_M)) {
2692
+ physicsViolation = true;
2693
+ break;
2447
2694
  }
2448
2695
  }
2449
2696
  if (!physicsViolation) {