Compiling Natural-Language Floor Plan Prompts Into Watertight 2D/3D CAD Wall Graphs in TypeScript
Ask a general-purpose image model to draw a "1,200 sq ft 2-bedroom ADU floor plan with an L-shaped kitchen and 36-inch hallways," and you get an attractive bitmap that falls apart the moment a contractor puts a scale rul
Ask a general-purpose image model to draw a "1,200 sq ft 2-bedroom ADU floor plan with an L-shaped kitchen and 36-inch hallways," and you get an attractive bitmap that falls apart the moment a contractor puts a scale ruler on it. Exterior walls drift out of square, closets overlap bathrooms, text labels garble dimensions, and nothing can be edited as a vector wall or exported to AutoCAD .DXF.
To ship an AI floor plan generator that produces real editable CAD files in the browser, we split the pipeline cleanly in two: an LLM proposes structured room layout intent, and a deterministic TypeScript compiler snaps, validates, closes, and exports the 2D/3D wall graph.
1. The Intermediate Representation (IR): Rooms First, Walls Second
Asking a model to output raw (x1, y1, x2, y2) wall coordinates directly causes floating gaps (0.4 ft off-axis), double-drawn shared interior partitions, and doors floating outside wall segments. Instead, constrain the model to emit snapped room rectangles on a 6-inch (0.5 ft) structural grid, then compile shared edges into single canonical walls.
export interface ProposedRoom {
id: string;
label: string;
xFt: number;
yFt: number;
widthFt: number;
depthFt: number;
roomType: "living" | "kitchen" | "bedroom" | "bath" | "hall" | "garage" | "utility";
}
export interface WallSegment {
id: string;
x1In: number;
y1In: number;
x2In: number;
y2In: number;
thicknessIn: number;
isExterior: boolean;
}
const GRID_IN = 6; // 6-inch snap grid keeps lumber & drywall framing sane
export function snapInches(feet: number): number {
return Math.round((feet * 12) / GRID_IN) * GRID_IN;
}
2. Deduplicating Shared Edges and Detecting Exterior vs. Interior Walls
When two rooms share a boundary (say a bedroom east wall and a hallway west wall), naive rectangle-to-wall conversion creates duplicate overlapping lines that corrupt both PDF lineweights and .DXF framing length totals.
By decomposing every horizontal and vertical room edge along collinear split points (every vertex coordinate projected onto that axis), we obtain atomic unit segments. A segment with coverageCount === 1 is an exterior envelope wall (6.0" or 6.5" framing); a segment with coverageCount === 2 is a shared interior partition (4.5" 2x4 framing).
interface AtomicEdge {
axis: "H" | "V";
coord: number; // y for H, x for V
start: number;
end: number;
roomIds: string[];
}
export function compileWatertightWalls(rooms: ProposedRoom[]): WallSegment[] {
const xCoords = new Set<number>();
const yCoords = new Set<number>();
const snapped = rooms.map((r) => {
const x1 = snapInches(r.xFt);
const y1 = snapInches(r.yFt);
const x2 = x1 + Math.max(GRID_IN * 2, snapInches(r.widthFt));
const y2 = y1 + Math.max(GRID_IN * 2, snapInches(r.depthFt));
xCoords.add(x1);
xCoords.add(x2);
yCoords.add(y1);
yCoords.add(y2);
return { ...r, x1, y1, x2, y2 };
});
const xs = [...xCoords].sort((a, b) => a - b);
const ys = [...yCoords].sort((a, b) => a - b);
const edgeMap = new Map<string, AtomicEdge>();
const addSegment = (axis: "H" | "V", coord: number, start: number, end: number, roomId: string) => {
const key = `${axis}:${coord}:${start}:${end}`;
const existing = edgeMap.get(key);
if (existing) {
if (!existing.roomIds.includes(roomId)) existing.roomIds.push(roomId);
} else {
edgeMap.set(key, { axis, coord, start, end, roomIds: [roomId] });
}
};
for (const r of snapped) {
for (let i = 0; i < xs.length - 1; i++) {
if (xs[i] >= r.x1 && xs[i + 1] <= r.x2) {
addSegment("H", r.y1, xs[i], xs[i + 1], r.id);
addSegment("H", r.y2, xs[i], xs[i + 1], r.id);
}
}
for (let j = 0; j < ys.length - 1; j++) {
if (ys[j] >= r.y1 && ys[j + 1] <= r.y2) {
addSegment("V", r.x1, ys[j], ys[j + 1], r.id);
addSegment("V", r.x2, ys[j], ys[j + 1], r.id);
}
}
}
return [...edgeMap.values()].map((e, idx) => {
const isExterior = e.roomIds.length === 1;
return {
id: `W-${idx + 1}`,
x1In: e.axis === "H" ? e.start : e.coord,
y1In: e.axis === "H" ? e.coord : e.start,
x2In: e.axis === "H" ? e.end : e.coord,
y2In: e.axis === "H" ? e.coord : e.end,
thicknessIn: isExterior ? 6.0 : 4.5,
isExterior,
};
});
}
Merging adjacent collinear atomic segments with matching isExterior flags then reduces the wall count while preserving exact T-junction nodes for corner snapping and 3D mesh extrusion.
3. Enforcing Door and Window Opening Clearances Deterministically
A prompt might generate a 36-inch bedroom door on a 38-inch shared wall segment, leaving only 1 inch of trimmer/king-stud jamb clearance on each side. Before accepting any opening onto a wall, our compiler enforces minimum jamb margins and automatically clamps or shifts the offset:
export interface WallOpening {
id: string;
wallId: string;
kind: "door" | "window" | "cased_opening";
widthIn: number;
offsetFromStartIn: number;
}
export function clampOpeningToWall(
wall: WallSegment,
opening: WallOpening,
minJambMarginIn = 6
): WallOpening | null {
const wallLengthIn = Math.hypot(wall.x2In - wall.x1In, wall.y2In - wall.y1In);
const maxWidthIn = wallLengthIn - minJambMarginIn * 2;
if (maxWidthIn < 24) {
// Wall segment too narrow for a standard 24-inch door or window
return null;
}
const safeWidth = Math.min(opening.widthIn, maxWidthIn);
const maxOffset = wallLengthIn - minJambMarginIn - safeWidth;
const safeOffset = Math.max(
minJambMarginIn,
Math.min(opening.offsetFromStartIn, maxOffset)
);
return {
...opening,
widthIn: Math.round(safeWidth),
offsetFromStartIn: Math.round(safeOffset),
};
}
4. Validating Connectivity Before Rendering 2D/3D
One subtle failure mode of AI-proposed room grids is a sealed room with no door connected to a hallway or living zone. Running a simple breadth-first search (BFS) over the room adjacency graph through valid door openings guarantees every habitable room is reachable from the entry node before the user ever sees the floor plan:
export function findUnreachableRooms(
roomIds: string[],
entryRoomId: string,
doorEdges: Array<[string, string]>
): string[] {
const adj = new Map<string, string[]>();
for (const id of roomIds) adj.set(id, []);
for (const [a, b] of doorEdges) {
adj.get(a)?.push(b);
adj.get(b)?.push(a);
}
const visited = new Set<string>();
const queue = [entryRoomId];
visited.add(entryRoomId);
while (queue.length > 0) {
const curr = queue.shift()!;
for (const next of adj.get(curr) ?? []) {
if (!visited.has(next)) {
visited.add(next);
queue.push(next);
}
}
}
return roomIds.filter((id) => !visited.has(id));
}
When findUnreachableRooms() returns a non-empty list, the compiler injects a standard 32-inch interior swing door on the longest shared interior wall connecting that isolated room to the visited component.
5. From Watertight Wall Graph to Interactive 3D, Vector PDF, and R12 .DXF
Once the wall graph is watertight and unit-tested, every downstream output reads from the exact same immutable model:
- Live 2D CAD Canvas: Ortho snapping, dimension strings, furniture clearances, and drag-to-resize walls.
- Live Three.js 3D Cutaway: Extrudes exterior and interior wall polygons with accurate door/window cutouts directly in WebGL.
-
Scaled Vector PDF & AutoCAD R12
.DXF: Outputs1/4"=1'-0"vector sheets (A-101throughM-101) and 8-layer ASCII.DXF($INSUNITS=1US inches) via our blueprint and DXF generator and sketch-to-CAD pipeline.
Try generating a floor plan from plain English free in the browser at PlanCaliber (2 free AI generations/day, full 2D/3D editing, and instant watermarked proof PNGs; optional one-time $9 2-sheet clean vector PDF or $19 full 5-sheet PDF + layered .DXF + 3D .OBJ + framing/drywall CSV, with no recurring subscription and 14-day instant refunds). Generated plans are for preliminary space planning and estimating; always field-verify dimensions and local code compliance before construction.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.