Initial commit: cad-building-showcase skill

Agent-led CAD-drawing → 3D web showcase pipeline. Inspects CAD reports,
maps layers/floors, extracts a normalized building spec (with block-probed
glazing and audit gates), builds Blender/trimesh GLB variants, and assembles
a Three.js web viewer. Includes XREF-shell detection and a regression test.

Large inputs/outputs (work/, outputs/, source_cad/, renders) are gitignored.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-12 16:16:04 +08:00
commit a6ac166049
26 changed files with 6228 additions and 0 deletions

196
scripts/draw_coverage_overlay.py Executable file
View File

@@ -0,0 +1,196 @@
#!/usr/bin/env python3
"""Draw SVG overlays comparing source CAD vectors with extracted showcase geometry."""
from __future__ import annotations
import argparse
import html
import json
import math
import sys
from collections import defaultdict
from pathlib import Path
from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent))
import derive_showcase_spec as derive # noqa: E402
CATEGORY_COLORS = {
"walls": "#c44e30",
"glazing": "#79b8c9",
"roof": "#b8ae98",
"columns": "#f58a1f",
"beams": "#1f66c2",
"railings": "#6f746d",
"doors": "#8a6a45",
"detail_lines": "#8c9088",
"floor_lines": "#18a058",
"grid": "#20242a",
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dxf-dir", required=True, help="Sanitized DXF folder")
parser.add_argument("--config", required=True, help="Extraction config JSON")
parser.add_argument("--spec", required=True, help="building_spec.json")
parser.add_argument("--out-dir", required=True, help="Output folder for floor SVG overlays")
parser.add_argument("--vendor-dir", default="work/vendor")
return parser.parse_args()
def source_to_meters(point: tuple[float, float], offset: tuple[float, float], origin: tuple[float, float], scale: float) -> tuple[float, float]:
return (
(point[0] + offset[0] - origin[0]) * scale,
(point[1] + offset[1] - origin[1]) * scale,
)
def line_length(segment: tuple[tuple[float, float], tuple[float, float]]) -> float:
(sx, sy), (ex, ey) = segment
return math.hypot(ex - sx, ey - sy)
def collect_source_segments(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_dir: Path) -> dict[str, list[dict[str, Any]]]:
ezdxf, recover = derive.import_ezdxf(vendor_dir)
patterns = derive.layer_patterns(config)
max_chord = float(config.get("curve_chord_source_length", 750.0))
scale = float(spec.get("units", {}).get("scale_to_meters", config.get("scale", 0.001)))
origin_values = spec.get("units", {}).get("origin_source", [0.0, 0.0])
origin = (float(origin_values[0]), float(origin_values[1]))
result: dict[str, list[dict[str, Any]]] = defaultdict(list)
drawings = config.get("drawings")
if not drawings:
drawings = [{"file": path.name, "floors": [{"key": path.stem}]} for path in sorted(dxf_dir.glob("*.dxf"))]
for drawing in drawings:
path = dxf_dir / drawing["file"]
if not path.exists():
continue
doc = derive.read_doc(path, ezdxf, recover)
floors = drawing.get("floors") or [{"key": path.stem}]
for floor in floors:
floor_key = str(floor["key"])
offset_values = floor.get("offset", drawing.get("offset", [0, 0]))
offset = (float(offset_values[0]), float(offset_values[1]))
for source_entity in doc.modelspace():
for entity, fallback_layer, block_name in derive.iter_model_entities(source_entity, config):
layer = derive.entity_layer(entity)
category = derive.category_for_entity(
entity,
patterns,
config,
fallback_layer=fallback_layer,
block_name=block_name,
)
for start, end in derive.entity_segments(entity, max_chord):
if line_length((start, end)) <= 0:
continue
if not derive.segment_matches_floor(start, end, floor, drawing):
continue
p1 = source_to_meters(start, offset, origin, scale)
p2 = source_to_meters(end, offset, origin, scale)
result[floor_key].append(
{
"start": p1,
"end": p2,
"category": category or "unclassified",
"layer": layer,
"source_type": entity.dxftype(),
"block_name": block_name,
}
)
return result
def bounds_for_floor(floor: dict[str, Any], source_segments: list[dict[str, Any]]) -> list[float]:
xs = [floor["bounds"][0], floor["bounds"][2]]
ys = [floor["bounds"][1], floor["bounds"][3]]
for segment in source_segments:
xs.extend([segment["start"][0], segment["end"][0]])
ys.extend([segment["start"][1], segment["end"][1]])
margin = 2.0
return [min(xs) - margin, min(ys) - margin, max(xs) + margin, max(ys) + margin]
def svg_line(segment: dict[str, Any], color: str, width: float, opacity: float, extra: str = "") -> str:
sx, sy = segment["start"]
ex, ey = segment["end"]
title = html.escape(f"{segment.get('category', '')} {segment.get('layer', '')} {segment.get('source_type', '')}")
return (
f'<line x1="{sx:.4f}" y1="{sy:.4f}" x2="{ex:.4f}" y2="{ey:.4f}" '
f'stroke="{color}" stroke-width="{width}" stroke-opacity="{opacity}" '
f'stroke-linecap="round" {extra}><title>{title}</title></line>'
)
def draw_floor_svg(floor_key: str, floor: dict[str, Any], source_segments: list[dict[str, Any]], out_path: Path):
bounds = bounds_for_floor(floor, source_segments)
min_x, min_y, max_x, max_y = bounds
width = max_x - min_x
height = max_y - min_y
view_box = f"{min_x:.4f} {-max_y:.4f} {width:.4f} {height:.4f}"
extracted_segments = []
for category, segments in floor.get("segments", {}).items():
for segment in segments:
extracted_segments.append({**segment, "category": category, "source_type": "extracted"})
lines = [
'<svg xmlns="http://www.w3.org/2000/svg" width="1800" height="1200" '
f'viewBox="{view_box}">',
"<style>",
"text{font-family:Arial,sans-serif;font-size:1.2px;fill:#111}",
".legend text{font-size:1.1px}",
"</style>",
'<rect x="-100000" y="-100000" width="200000" height="200000" fill="#fbfaf6"/>',
'<g transform="scale(1,-1)">',
]
for segment in source_segments:
category = segment["category"]
if category == "unclassified":
lines.append(svg_line(segment, "#b00020", 0.045, 0.40, 'stroke-dasharray="0.25 0.18"'))
else:
lines.append(svg_line(segment, "#a9a9a9", 0.025, 0.32))
for segment in extracted_segments:
color = CATEGORY_COLORS.get(segment["category"], "#000000")
stroke_width = 0.10 if segment["category"] in {"walls", "columns", "beams", "glazing"} else 0.055
lines.append(svg_line(segment, color, stroke_width, 0.90))
lines.extend(
[
"</g>",
f'<text x="{min_x + 1:.4f}" y="{-max_y + 2:.4f}">{html.escape(floor_key)} extraction overlay</text>',
f'<text x="{min_x + 1:.4f}" y="{-max_y + 3.8:.4f}">gray=source classified, red dashed=source unclassified, color=extracted model</text>',
"</svg>",
]
)
out_path.write_text("\n".join(lines), encoding="utf-8")
def main() -> int:
args = parse_args()
dxf_dir = Path(args.dxf_dir)
config = derive.read_json(Path(args.config))
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
source_by_floor = collect_source_segments(dxf_dir, config, spec, Path(args.vendor_dir))
outputs = []
for floor_key, floor in spec.get("floors", {}).items():
out_path = out_dir / f"{floor_key}_overlay.svg"
draw_floor_svg(floor_key, floor, source_by_floor.get(floor_key, []), out_path)
outputs.append(str(out_path))
index = out_dir / "index.html"
links = "\n".join(f'<li><a href="{Path(path).name}">{html.escape(Path(path).name)}</a></li>' for path in outputs)
index.write_text(f"<!doctype html><meta charset='utf-8'><title>CAD Overlay</title><ul>{links}</ul>", encoding="utf-8")
print(json.dumps({"out_dir": str(out_dir), "files": outputs}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())