如何在 TypeScript 中將自然語言平面圖編譯為拓撲封閉的向量 CAD 圖
Compiling Natural-Language Floor Plans into Watertight Vector CAD Graphs in TypeScript
PlanCaliber 建立了 TypeScript Text-to-CAD 編譯器,把自然語言平面圖轉換為以英寸表示的頂點、牆身及開口拓撲圖,供 CAD 空間規劃使用。系統會先驗證模型輸出的 JSON,並以四個確定性的 TypeScript 流程修正草稿,包括清理無效元素、限制開口位置及排除非居住空間的 GLA 計算。
Ask a standard image generator for a "32×24 2-bedroom backyard ADU with open kitchen and laundry" and you get a pretty raster picture with illegible squiggle dimensions, impossible hallways, and doors that swing straight into kitchen sinks. Ask a text model for raw SVG paths and you get uneditable <line> soup that cannot calculate square footage, snap walls, or export to AutoCAD .DXF.
To make Text-to-CAD actually useful for real residential space planning, the model should never output pixels or raw drawing primitives. Instead, it should emit a topological vertex-wall-opening graph in inches, backed by strict geometric invariants and a deterministic TypeScript healer.
Here is how we built the Text-to-CAD compiler inside PlanCaliber.
1. The Five Ways Raw LLM Floor-Plan JSON Breaks CAD
Even frontier language models routinely fail on five subtle geometric details when generating floor-plan JSON from text:
-
Unsplit T-junctions: An interior bedroom wall ends at
(144, 0)on top of an exterior wall running from(0, 0)to(384, 0), without splitting the exterior wall at(144, 0). Visually it looks closed; topologically, a planar room solver sees an open dead-end edge and reports0 sq ft. -
Door offsets out of bounds: A
36"door placed atoffsetIn: 12on a48"wall protrudes past the corner vertex and corrupts wall miter trimming. - Garage area leaking into Heated GLA: Attached garages or shops are left unmarked, inflating conditioned living area by 400–600 sq ft in violation of ANSI Z765-2021.
-
Micro-skewed angles (
89.2°): Floating-point drift creates near-orthogonal walls that look crooked on a1/4" = 1'-0"printed blueprint and break horizontal/vertical dimension chains. -
Unbounded or uncalibrated dimensions: Prompt says "small 2-bed ADU" and the model invents
4000 px × 3000 pxcoordinates with no physical scale.
2. Constraining the Graph Contract in Inches
Every coordinate in PlanCaliber uses a top-left origin (0, 0) in US inches (1 ft = 12 in), +x East and +y South, snapped to a 6-inch rectilinear grid. When a user provides optional width, depth, or ceiling bounds, we clamp and pass exact inch targets alongside the natural-language description:
export interface TextToCadInput {
prompt: string;
widthFt?: number | null;
depthFt?: number | null;
ceilingFt?: number | null;
}
export function buildFootprintBounds(input: TextToCadInput) {
const clamp = (val: number | null | undefined, min: number, max: number) =>
typeof val === 'number' && Number.isFinite(val) && val >= min && val <= max
? Math.round(val * 2) / 2
: null;
const widthFt = clamp(input.widthFt, 8, 160);
const depthFt = clamp(input.depthFt, 8, 160);
const ceilingFt = clamp(input.ceilingFt, 7, 16) ?? 9;
return {
widthIn: widthFt ? Math.round(widthFt * 12) : null,
depthIn: depthFt ? Math.round(depthFt * 12) : null,
ceilingIn: Math.round(ceilingFt * 12)
};
}
The schema separates topology (vertices and walls by ID) from hosted elements (openings referencing wallId + offsetIn) and semantic zones (roomTags with explicit includeInGla: boolean):
export interface GeneratedPlanGraph {
kind: 'floor_plan' | 'unrelated';
title: string;
ceilingHeightIn: number;
vertices: { id: string; x: number; y: number }[];
walls: {
id: string;
startId: string;
endId: string;
thicknessIn: number; // 6.5 exterior, 4.5 interior
kind: 'exterior' | 'interior';
}[];
openings: {
id: string;
wallId: string;
offsetIn: number; // center distance from startId vertex
widthIn: number;
kind: 'door' | 'double_door' | 'sliding_door' | 'cased_opening' | 'window' | 'egress_window';
sillHeightIn: number;
headHeightIn: number;
swing: 'left-in' | 'right-in' | 'left-out' | 'right-out' | 'none';
}[];
fixtures: {
id: string;
kind: string;
label: string;
code: string;
x: number;
y: number;
widthIn: number;
depthIn: number;
heightIn: number;
rotationDeg: number;
}[];
roomTags: {
id: string;
name: string;
roomType: string;
anchorX: number;
anchorY: number;
includeInGla: boolean; // false for garage, shop, deck_patio
floorFinish: string;
}[];
}
Separating vertices and walls by ID instead of embedding (x1, y1, x2, y2) inside every wall forces the model to reason explicitly about shared corner IDs — and makes T-junction auditing trivial downstream.
3. Fast Schema Gates & Automatic Retry Fallback
Never trust a single raw model response on the critical path. We wrap generation in a strict timeout + JSON validation gate with automatic retry to a faster fallback model if the primary response times out, emits malformed JSON, or produces fewer than 3 walls:
function stripJsonFences(raw: string): string {
return raw
.trim()
.replace(/^```
(?:json)?\s*/i, '')
.replace(/\s*
```$/i, '')
.trim();
}
export function validateRawGraph(rawText: string): GeneratedPlanGraph | null {
let data: Record<string, unknown>;
try {
data = JSON.parse(stripJsonFences(rawText)) as Record<string, unknown>;
} catch {
return null;
}
if (data.kind === 'unrelated') {
return data as unknown as GeneratedPlanGraph;
}
if (
!Array.isArray(data.vertices) ||
data.vertices.length < 3 ||
!Array.isArray(data.walls) ||
data.walls.length < 3
) {
return null;
}
return data as unknown as GeneratedPlanGraph;
}
4. Deterministic Post-Healing Makes It Real CAD
Even with a tight prompt contract, generative output is treated as an untrusted draft until it passes through four deterministic TypeScript passes:
-
Sanitization (
sanitizePlanDocument): Drops unknown fixture/opening enums, enforces valid positive wall thicknesses (6.5"exterior,4.5"interior), clamps openingoffsetInstrictly inside[widthIn / 2 + 4, wallLength - widthIn / 2 - 4]so no door ever cuts through a structural corner, and forcesincludeInGla = falseon unconditioned room types (garage,deck_patio,porch). -
Vertex Welding & T-Junction Splitting (
healPlanDocument): Snaps near-coincident vertices within tolerance (<= 3"), projects near-axis edges onto exact0°/90°axes, and splits any wall crossed by another wall's endpoint into watertight sub-segments sharing one canonical vertex ID. -
Planar Cycle Room Solving (
solvePlan): Traces minimal half-edge cycles to recover exact room polygons, computes shoelace areas in square feet, separates Heated GLA from unconditioned garage/patio area per ANSI Z765-2021, and matches eachroomTagvia point-in-polygon. -
Live Clearance & Material Audit: Checks door widths, hallway clearances, kitchen island aisles, and bathroom fixture clearances, then generates framing stud counts (
16"OC) and4×8drywall sheet takeoffs directly from solved wall linear footage.
Because the output is a genuine parametric graph rather than a bitmap, the user can immediately drag any wall to exact feet-and-inches, inspect the live 3D cutaway, and export true-scale 1/4" = 1'-0" vector PDFs or layered AutoCAD R12 (.DXF) files.
Try Text-to-CAD & Sketch-to-CAD Free in Your Browser
You can test natural-language floor plan generation (plus hand-sketch and PDF tracing) directly in PlanCaliber Studio — no download and no account required to draft, calibrate, and view in 2D + 3D. You can also check our standalone ANSI Z765 Square Footage Calculator or one-time export pricing starting at $9 (no recurring subscription; $19 Full CAD Pack adds 8-layer AutoCAD R12 .DXF, 5-sheet vector PDFs, 3D .OBJ, and CSV material takeoffs).
(Note: PlanCaliber produces preliminary space-planning and drafting documents; always verify finished dimensions and local requirements on site.)
來源:DEV Community · dev.to