Extracting a Multi-Story Structural Shell (2nd Floor & Basement) from a 2D Floor Plan Graph in Pure TypeScript
When someone finishes drafting a first-floor layout and wants to add a second story or a basement foundation, two naive approaches both break down immediately: Duplicate the whole plan: the user inherits every kitchen
When someone finishes drafting a first-floor layout and wants to add a second story or a basement foundation, two naive approaches both break down immediately:
- Duplicate the whole plan: the user inherits every kitchen island, coat closet, and bathroom partition from the ground floor and has to delete 40 items before drawing bedroom walls.
- Start a blank canvas: the exterior foundation outline and stairwell opening almost never align cleanly with the floor below.
In PlanCaliber, we solved this in a single 200-line module (src/lib/cad/levels.ts) that derives a matched 2nd Story Shell or Basement Shell directly from the planar graph of the main floor in one click. Here are the five geometric invariants that make it work reliably on messy real-world user drawings.
1. Extract the Exterior Shell by Face Incidence, Not Wall Type
The first bug you hit in any real floor-plan editor is human behavior: users routinely draw outer perimeter walls using the default "interior" wall tool, or mix "exterior" and "interior" segments around a garage bump-out.
Filtering walls.filter((w) => w.kind === 'exterior') drops mislabeled segments and shatters the building outline. Instead, once our planar-graph room solver (solvePlan) extracts every enclosed room cycle, we count how many solved rooms touch each wall:
const wallRoomCount = new Map<string, number>();
for (const room of solvedSource.rooms) {
for (const wid of new Set(room.boundingWallIds)) {
wallRoomCount.set(wid, (wallRoomCount.get(wid) ?? 0) + 1);
}
}
const outerBoundaryWalls = healedSource.walls.filter((w) => wallRoomCount.get(w.id) === 1);
In a closed planar subdivision of a floor plan:
- Every shared interior partition borders 2 enclosed rooms (
wallRoomCount === 2). - Every true exterior perimeter wall borders exactly 1 enclosed room (
wallRoomCount === 1).
That topological rule extracts the exact building silhouette even if the user never toggled an exterior wall tool once. If a draft is still half-drawn (outerBoundaryWalls.length < 3), we fall back to checking whether explicit kind === 'exterior' walls themselves form a closed room cycle via solvePlan(), and only otherwise keep all walls.
2. Re-Cast Structural Wall Thickness & Foundation Specs
Once we have the exact perimeter wall set and prune unused interior vertices, we re-cast every retained wall as an exterior shell wall with level-appropriate thickness:
const walls: PlanWall[] = shellWallsSource.map((w) => ({
...w,
kind: 'exterior',
thicknessIn: levelKind === 'basement' ? 8.0 : 6.5,
heightIn: 96
}));
-
Basement shell (
A-001):8.0"poured-concrete/CMU foundation perimeter. -
2nd Story shell (
A-102):6.5"framed exterior wall assembly at8'-0"(96") default ceiling height.
3. Facade-Aligned Upper Windows vs. Auto-Centered Basement Egress
Ground-floor front entry doors and sliding patio doors do not belong floating in mid-air on a second storyβnor underground in a basement foundation. On the other hand, keeping upper-level windows stacked over ground-floor windows saves minutes of re-measuring and keeps facade elevations aligned:
let openings: PlanOpening[] = [];
if (levelKind === 'second_floor') {
openings = healedSource.openings
.filter(
(o) =>
wallIdSet.has(o.wallId) &&
(o.kind === 'window' || o.kind === 'egress_window' || o.kind === 'bay_window')
)
.map((o) => ({ ...o, id: makePlanId('win2') }));
} else {
let longestWall: PlanWall | null = null;
let longestLen = 0;
for (const w of walls) {
const a = vertexMap.get(w.startId);
const b = vertexMap.get(w.endId);
if (!a || !b) continue;
const len = Math.hypot(b.x - a.x, b.y - a.y);
if (len > longestLen) {
longestLen = len;
longestWall = w;
}
}
if (longestWall && longestLen >= 60) {
openings = [
{
id: makePlanId('egress'),
wallId: longestWall.id,
offsetIn: Math.round((longestLen / 2) * 4) / 4,
widthIn: 36,
kind: 'egress_window',
sillHeightIn: 40,
headHeightIn: 76,
swing: 'none'
}
];
}
}
For basements, we drop all ground-floor doors/windows and seed one 36" IRC R310 egress window (sillHeightIn: 40, headHeightIn: 76) centered on the longest perimeter wall (>= 60"), rounded to the nearest 1/4" (Math.round((longestLen / 2) * 4) / 4) so CAD dimensions stay clean.
4. Exact (x, y) Stairwell Stacking
Stairwells are the vertical spine tying floors together. While every sofa, sink, and kitchen cabinet is stripped from the derived shell, straight staircases are preserved at their exact coordinates and automatically relabeled for direction of travel:
const fixtures: PlanFixture[] = healedSource.fixtures
.filter((f) => f.kind === 'stairs_straight')
.map((f) => ({
...f,
id: makePlanId('stair'),
label: levelKind === 'second_floor' ? 'Stairs Down to Main' : 'Stairs Up to Main',
code: levelKind === 'second_floor' ? 'STR-DN' : 'STR-UP'
}));
That keeps STR-DN on A-102 and STR-UP on A-001 locked vertically over the main floor's stair footprint to the exact inch.
5. Why Bounding-Box Center Fails for L-Shaped & U-Shaped Houses
Finally, the new empty shell needs a single interior room label (Upper Level Shell or Basement Level) anchored at (cx, cy) inside the building polygon.
The classic mistake is placing that anchor at the bounding-box midpoint ((minX + maxX) / 2, (minY + maxY) / 2). On an L-shaped ranch or U-shaped courtyard house, the bounding-box center lands outside the building in the backyard, causing the room tag to miss the interior polygon completely.
Because we already ran solvePlan(healedSource) in Step 1, we already have verified interior centroids for every room of the main floor:
const largestRoom = [...solvedSource.rooms].sort((a, b) => b.areaSqFt - a.areaSqFt)[0];
const cx = largestRoom
? Math.round(largestRoom.centroid.x)
: Number.isFinite(minX)
? Math.round((minX + maxX) / 2)
: 180;
const cy = largestRoom
? Math.round(largestRoom.centroid.y)
: Number.isFinite(minY)
? Math.round((minY + maxY) / 2)
: 144;
Picking the centroid of the largest solved room guarantees the new shell tag lands strictly inside concave L-shaped, T-shaped, and U-shaped footprintsβfalling back to the bounding-box center only if the source plan had zero closed rooms.
Try Multi-Level Shells & Egress Checks Live
You can test one-click 2nd Story Shell, Basement Shell, and Proposed Remodel cloning in the PlanCaliber ADU & Basement Floor Plan Studio, explore Room Addition Floor Plans, or verify window well and opening dimensions with the free IRC R310 Basement Egress Window Calculator.
(Note: PlanCaliber produces preliminary space-planning and CAD drafting sheets for design coordination; always confirm structural bearing walls, stair geometry, and local building codes with a licensed professional on site.)
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.