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:
812
scripts/derive_showcase_spec.py
Executable file
812
scripts/derive_showcase_spec.py
Executable file
@@ -0,0 +1,812 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extract a normalized building_spec.json from sanitized DXF files."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import fnmatch
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
DEFAULT_CATEGORIES = {
|
||||
"walls": {"label": "墙体", "color": "#d4cbb8", "width": 0.20},
|
||||
"glazing": {"label": "玻璃/幕墙", "color": "#79b8c9", "width": 0.055},
|
||||
"roof": {"label": "屋顶/屋盖", "color": "#b8ae98", "width": 0.0},
|
||||
"columns": {"label": "柱", "color": "#f58a1f", "width": 0.45},
|
||||
"beams": {"label": "梁/结构", "color": "#1f66c2", "width": 0.35},
|
||||
"railings": {"label": "栏杆/扶手", "color": "#6f746d", "width": 0.055},
|
||||
"doors": {"label": "门/开启线", "color": "#8a6a45", "width": 0.045},
|
||||
"detail_lines": {"label": "平面细节", "color": "#8c9088", "width": 0.025},
|
||||
"floor_lines": {"label": "楼面线", "color": "#18a058", "width": 0.04},
|
||||
"grid": {"label": "轴网", "color": "#20242a", "width": 0.02},
|
||||
"slab": {"label": "楼板", "color": "#c8ccc2", "width": 0.0},
|
||||
}
|
||||
|
||||
DEFAULT_LAYER_HINTS = {
|
||||
"walls": ["I-WALL", "A-WALL", "L-SITE-WALL", "*WALL*", "*墙*"],
|
||||
"glazing": ["A-GLAZ*", "*GLAZ*", "*CURT*", "*幕墙*", "*玻璃*"],
|
||||
"roof": ["A-ROOF*", "*ROOF*", "*屋顶*", "*屋面*"],
|
||||
"columns": ["S-COLS", "*COL*", "*COLUMN*", "*柱*"],
|
||||
"beams": ["S-STRS", "S-STRS-MBND", "*BEAM*", "*梁*", "*结构*"],
|
||||
"railings": ["A-FLOR-HRAL*", "*HRAL*", "*RAIL*", "*HANDRAIL*", "*栏杆*", "*扶手*"],
|
||||
"doors": ["A-DOOR*", "*DOOR*", "*门*"],
|
||||
"detail_lines": ["A-GENM", "A-DETL*", "C-PRKG", "*PRKG*", "*PARK*", "A-AREA", "A-FLOR-LEVL"],
|
||||
"floor_lines": ["A-FLOR", "A-FLOR-OVHD", "*FLOOR*", "*FLOR*", "*楼面*", "*地面*"],
|
||||
"grid": ["S-GRID", "*GRID*", "*轴网*", "*轴线*"],
|
||||
}
|
||||
|
||||
# Curtain-wall / glazing geometry is commonly locked inside INSERT blocks whose
|
||||
# exploded entities sit on glazing layers (e.g. A-GLAZ-CURT). Expanding only these
|
||||
# block-name patterns by default captures glass without pulling in axis-number /
|
||||
# dimension blocks. Disable with config {"expand_glazing_blocks": false}.
|
||||
# DWG->DXF conversion can mangle CJK block names ("系统嵌板"->"系统嵌"), so the
|
||||
# patterns are deliberately loose; layer-based probing below is the robust path.
|
||||
GLAZING_BLOCK_PATTERNS = ["*幕墙*", "*玻璃*", "*嵌板*", "*系统嵌*", "*GLAZ*", "*CURT*", "*幕*"]
|
||||
|
||||
# Block-name matching alone misses geometry inside wrapper/sheet blocks and any
|
||||
# block whose name was mangled during conversion. Probe mode therefore expands
|
||||
# every INSERT up to expand_blocks_max_depth and keeps only sub-entities whose
|
||||
# own layer classifies into one of these categories. Disable with
|
||||
# {"classify_block_contents": false}; widen with {"block_content_categories": [...]}.
|
||||
DEFAULT_BLOCK_CONTENT_CATEGORIES = ["glazing", "railings", "doors"]
|
||||
|
||||
# Identification/annotation layers (door tags, axis numbers, area labels) match
|
||||
# broad category patterns like "A-DOOR*" but carry no element geometry.
|
||||
DEFAULT_EXCLUDE_LAYER_PATTERNS = ["*-IDEN"]
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--dxf-dir", required=True, help="Folder containing sanitized DXF files")
|
||||
parser.add_argument("--config", help="Extraction config JSON. If omitted, one floor per DXF is generated.")
|
||||
parser.add_argument("--out", default="work/cad_showcase/building_spec.json")
|
||||
parser.add_argument("--vendor-dir", default="work/vendor")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def import_ezdxf(vendor_dir: Path):
|
||||
if vendor_dir.exists():
|
||||
sys.path.insert(0, str(vendor_dir.resolve()))
|
||||
try:
|
||||
import ezdxf # type: ignore
|
||||
from ezdxf import recover # type: ignore
|
||||
except ImportError as exc:
|
||||
raise SystemExit(
|
||||
"Missing dependency: ezdxf. Install locally with:\n"
|
||||
f" python3 -m pip install --target {vendor_dir} ezdxf"
|
||||
) from exc
|
||||
return ezdxf, recover
|
||||
|
||||
|
||||
def read_json(path: Path | None) -> dict[str, Any]:
|
||||
if not path:
|
||||
return {}
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def read_doc(path: Path, ezdxf, recover):
|
||||
try:
|
||||
return ezdxf.readfile(path)
|
||||
except ezdxf.DXFError:
|
||||
doc, _auditor = recover.readfile(path)
|
||||
return doc
|
||||
|
||||
|
||||
def point_in_clip(point: tuple[float, float], clip: list[float] | None) -> bool:
|
||||
if not clip:
|
||||
return True
|
||||
x1, y1, x2, y2 = clip
|
||||
xmin, xmax = sorted((x1, x2))
|
||||
ymin, ymax = sorted((y1, y2))
|
||||
return xmin <= point[0] <= xmax and ymin <= point[1] <= ymax
|
||||
|
||||
|
||||
def flatten_arc(entity, max_chord: float) -> list[tuple[float, float]]:
|
||||
center = entity.dxf.center
|
||||
radius = float(entity.dxf.radius)
|
||||
start = math.radians(float(entity.dxf.start_angle))
|
||||
end = math.radians(float(entity.dxf.end_angle))
|
||||
if end < start:
|
||||
end += math.tau
|
||||
arc_len = abs(end - start) * radius
|
||||
steps = max(8, min(96, int(max(arc_len / max(max_chord, 1.0), 8))))
|
||||
return [
|
||||
(
|
||||
float(center.x + math.cos(start + (end - start) * i / steps) * radius),
|
||||
float(center.y + math.sin(start + (end - start) * i / steps) * radius),
|
||||
)
|
||||
for i in range(steps + 1)
|
||||
]
|
||||
|
||||
|
||||
def flatten_circle(entity, max_chord: float) -> list[tuple[float, float]]:
|
||||
center = entity.dxf.center
|
||||
radius = float(entity.dxf.radius)
|
||||
circumference = math.tau * radius
|
||||
steps = max(24, min(144, int(max(circumference / max(max_chord, 1.0), 24))))
|
||||
return [
|
||||
(
|
||||
float(center.x + math.cos(math.tau * i / steps) * radius),
|
||||
float(center.y + math.sin(math.tau * i / steps) * radius),
|
||||
)
|
||||
for i in range(steps + 1)
|
||||
]
|
||||
|
||||
|
||||
def flatten_spline(entity, max_chord: float) -> list[tuple[float, float]]:
|
||||
try:
|
||||
points = list(entity.flattening(distance=max(max_chord, 1.0)))
|
||||
except Exception:
|
||||
return []
|
||||
return [(float(point.x), float(point.y)) for point in points]
|
||||
|
||||
|
||||
def segment_in_clip(start: tuple[float, float], end: tuple[float, float], clip: list[float] | None) -> bool:
|
||||
midpoint = ((start[0] + end[0]) / 2.0, (start[1] + end[1]) / 2.0)
|
||||
return point_in_clip(midpoint, clip) or point_in_clip(start, clip) or point_in_clip(end, clip)
|
||||
|
||||
|
||||
def segment_matches_floor(
|
||||
start: tuple[float, float],
|
||||
end: tuple[float, float],
|
||||
floor: dict[str, Any],
|
||||
drawing: dict[str, Any],
|
||||
) -> bool:
|
||||
clip = floor.get("clip", drawing.get("clip"))
|
||||
if clip:
|
||||
return segment_in_clip(start, end, clip)
|
||||
split_x = floor.get("split_x", drawing.get("split_x"))
|
||||
side = floor.get("side")
|
||||
if split_x is not None and side:
|
||||
midpoint_x = (start[0] + end[0]) / 2.0
|
||||
if str(side).lower() in {"left", "west", "negative", "lt"}:
|
||||
return midpoint_x < float(split_x)
|
||||
if str(side).lower() in {"right", "east", "positive", "gt"}:
|
||||
return midpoint_x >= float(split_x)
|
||||
return True
|
||||
|
||||
|
||||
def layer_patterns(config: dict[str, Any]) -> dict[str, list[str]]:
|
||||
merged = {key: list(value) for key, value in DEFAULT_LAYER_HINTS.items()}
|
||||
for key, patterns in config.get("layers", {}).items():
|
||||
merged[key] = list(patterns)
|
||||
return merged
|
||||
|
||||
|
||||
def exclude_layer_patterns(config: dict[str, Any]) -> list[str]:
|
||||
return list(config.get("exclude_layers", DEFAULT_EXCLUDE_LAYER_PATTERNS))
|
||||
|
||||
|
||||
def match_category(
|
||||
layer: str,
|
||||
patterns_by_category: dict[str, list[str]],
|
||||
exclude_patterns: list[str] | None = None,
|
||||
) -> str | None:
|
||||
upper_layer = layer.upper()
|
||||
for pattern in exclude_patterns or []:
|
||||
if fnmatch.fnmatch(upper_layer, str(pattern).upper()):
|
||||
return None
|
||||
for category, patterns in patterns_by_category.items():
|
||||
for pattern in patterns:
|
||||
upper_pattern = str(pattern).upper()
|
||||
if fnmatch.fnmatch(upper_layer, upper_pattern):
|
||||
return category
|
||||
return None
|
||||
|
||||
|
||||
def match_patterns(value: str, patterns: list[str]) -> bool:
|
||||
upper_value = value.upper()
|
||||
return any(fnmatch.fnmatch(upper_value, str(pattern).upper()) for pattern in patterns)
|
||||
|
||||
|
||||
def block_category(block_name: str, config: dict[str, Any]) -> str | None:
|
||||
for category, patterns in config.get("block_name_categories", {}).items():
|
||||
if match_patterns(block_name, list(patterns)):
|
||||
return category
|
||||
return None
|
||||
|
||||
|
||||
def entity_layer(entity) -> str:
|
||||
return str(entity.dxf.layer) if entity.dxf.hasattr("layer") else ""
|
||||
|
||||
|
||||
def category_for_entity(
|
||||
entity,
|
||||
patterns_by_category: dict[str, list[str]],
|
||||
config: dict[str, Any],
|
||||
fallback_layer: str = "",
|
||||
block_name: str = "",
|
||||
) -> str | None:
|
||||
excludes = exclude_layer_patterns(config)
|
||||
category = match_category(entity_layer(entity), patterns_by_category, excludes)
|
||||
if not category and fallback_layer and config.get("block_insert_layer_fallback", True):
|
||||
category = match_category(fallback_layer, patterns_by_category, excludes)
|
||||
if not category and block_name:
|
||||
category = block_category(block_name, config)
|
||||
return category
|
||||
|
||||
|
||||
def should_expand_insert(entity, config: dict[str, Any]) -> bool:
|
||||
if entity.dxftype() != "INSERT":
|
||||
return False
|
||||
block_name = str(entity.dxf.name) if entity.dxf.hasattr("name") else ""
|
||||
expand_blocks = config.get("expand_blocks", False)
|
||||
if isinstance(expand_blocks, bool) and expand_blocks:
|
||||
return True
|
||||
if isinstance(expand_blocks, list) and match_patterns(block_name, expand_blocks):
|
||||
return True
|
||||
if config.get("expand_glazing_blocks", True) and match_patterns(block_name, GLAZING_BLOCK_PATTERNS):
|
||||
return True
|
||||
expand_block_names = config.get("expand_block_names", [])
|
||||
return bool(expand_block_names and match_patterns(block_name, list(expand_block_names)))
|
||||
|
||||
|
||||
_PROBE_CACHE: dict[int, tuple[dict[str, list[str]], list[str], set[str]]] = {}
|
||||
|
||||
|
||||
def _probe_rules(config: dict[str, Any]) -> tuple[dict[str, list[str]], list[str], set[str]]:
|
||||
cached = _PROBE_CACHE.get(id(config))
|
||||
if cached is None:
|
||||
cached = (
|
||||
layer_patterns(config),
|
||||
exclude_layer_patterns(config),
|
||||
set(config.get("block_content_categories", DEFAULT_BLOCK_CONTENT_CATEGORIES)),
|
||||
)
|
||||
_PROBE_CACHE[id(config)] = cached
|
||||
return cached
|
||||
|
||||
|
||||
def probe_keep_entity(entity, config: dict[str, Any]) -> bool:
|
||||
"""Keep a probed block sub-entity only if its own layer classifies."""
|
||||
patterns, excludes, allowed = _probe_rules(config)
|
||||
category = match_category(entity_layer(entity), patterns, excludes)
|
||||
return category is not None and category in allowed
|
||||
|
||||
|
||||
def iter_model_entities(entity, config: dict[str, Any], depth: int = 0):
|
||||
"""Yield (entity, fallback_layer, block_name) tuples to inspect/extract.
|
||||
|
||||
INSERT handling, in priority order:
|
||||
- Explicit expansion (expand_blocks / glazing block-name patterns): yield all
|
||||
sub-entities, with the insert layer as classification fallback.
|
||||
- Probe expansion (classify_block_contents, default on): descend into every
|
||||
block — including wrapper/sheet blocks and blocks with mangled names — but
|
||||
keep only sub-entities whose own layer classifies into
|
||||
block_content_categories. This is what captures curtain-wall glazing that
|
||||
block-name matching misses.
|
||||
"""
|
||||
if entity.dxftype() != "INSERT":
|
||||
yield entity, "", ""
|
||||
return
|
||||
|
||||
explicit = should_expand_insert(entity, config)
|
||||
probe = bool(config.get("classify_block_contents", True))
|
||||
max_depth = int(config.get("expand_blocks_max_depth", 2))
|
||||
if (not explicit and not probe) or depth >= max_depth:
|
||||
yield entity, "", ""
|
||||
return
|
||||
|
||||
insert_layer = entity_layer(entity)
|
||||
block_name = str(entity.dxf.name) if entity.dxf.hasattr("name") else ""
|
||||
try:
|
||||
from ezdxf import explode as ezdxf_explode
|
||||
|
||||
virtual_entities = list(ezdxf_explode.virtual_block_reference_entities(entity))
|
||||
except Exception:
|
||||
yield entity, "", ""
|
||||
return
|
||||
for virtual_entity in virtual_entities:
|
||||
if virtual_entity.dxftype() == "INSERT":
|
||||
yield from iter_model_entities(virtual_entity, config, depth + 1)
|
||||
elif explicit:
|
||||
yield virtual_entity, insert_layer, block_name
|
||||
elif probe_keep_entity(virtual_entity, config):
|
||||
yield virtual_entity, "", block_name
|
||||
|
||||
|
||||
def polyline_points(entity) -> list[tuple[float, float]]:
|
||||
if entity.dxftype() == "LWPOLYLINE":
|
||||
return [(float(x), float(y)) for x, y in entity.get_points("xy")]
|
||||
if entity.dxftype() == "POLYLINE":
|
||||
return [
|
||||
(float(vertex.dxf.location.x), float(vertex.dxf.location.y))
|
||||
for vertex in entity.vertices
|
||||
]
|
||||
return []
|
||||
|
||||
|
||||
def points_from_entity(entity, max_chord: float) -> list[tuple[float, float]]:
|
||||
dxftype = entity.dxftype()
|
||||
if dxftype == "LINE":
|
||||
return [
|
||||
(float(entity.dxf.start.x), float(entity.dxf.start.y)),
|
||||
(float(entity.dxf.end.x), float(entity.dxf.end.y)),
|
||||
]
|
||||
if dxftype in {"LWPOLYLINE", "POLYLINE"}:
|
||||
return polyline_points(entity)
|
||||
if dxftype == "ARC":
|
||||
return flatten_arc(entity, max_chord)
|
||||
if dxftype == "CIRCLE":
|
||||
return flatten_circle(entity, max_chord)
|
||||
if dxftype == "SPLINE":
|
||||
return flatten_spline(entity, max_chord)
|
||||
return []
|
||||
|
||||
|
||||
def entity_segments(entity, max_chord: float) -> list[tuple[tuple[float, float], tuple[float, float]]]:
|
||||
points = points_from_entity(entity, max_chord)
|
||||
if len(points) < 2:
|
||||
return []
|
||||
pairs = list(zip(points, points[1:]))
|
||||
if entity.dxftype() in {"LWPOLYLINE", "POLYLINE"}:
|
||||
closed = bool(getattr(entity, "closed", False) or getattr(entity, "is_closed", False))
|
||||
if closed and len(points) > 2 and points[0] != points[-1]:
|
||||
pairs.append((points[-1], points[0]))
|
||||
return pairs
|
||||
|
||||
|
||||
def cleaned_segment(
|
||||
start: tuple[float, float],
|
||||
end: tuple[float, float],
|
||||
offset: tuple[float, float],
|
||||
min_source_length: float,
|
||||
min_meters_length: float,
|
||||
scale: float,
|
||||
) -> tuple[tuple[float, float], tuple[float, float]] | None:
|
||||
sx, sy = start[0] + offset[0], start[1] + offset[1]
|
||||
ex, ey = end[0] + offset[0], end[1] + offset[1]
|
||||
source_length = math.hypot(ex - sx, ey - sy)
|
||||
if source_length < min_source_length or source_length * scale < min_meters_length:
|
||||
return None
|
||||
return (sx, sy), (ex, ey)
|
||||
|
||||
|
||||
def auto_drawings(dxf_dir: Path) -> list[dict[str, Any]]:
|
||||
drawings = []
|
||||
for index, path in enumerate(sorted(dxf_dir.glob("*.dxf")), start=1):
|
||||
key = f"F{index:02d}"
|
||||
drawings.append(
|
||||
{
|
||||
"file": path.name,
|
||||
"floors": [{"key": key, "name": path.stem}],
|
||||
}
|
||||
)
|
||||
return drawings
|
||||
|
||||
|
||||
def floor_sort_key(key: str) -> tuple[int, str]:
|
||||
text = key.upper()
|
||||
if text.startswith("B"):
|
||||
number = int(re.sub(r"\D", "", text) or "1")
|
||||
return (-number, text)
|
||||
if text in {"RF", "ROOF"}:
|
||||
return (999, text)
|
||||
number = int(re.sub(r"\D", "", text) or "0")
|
||||
return (number, text)
|
||||
|
||||
|
||||
def collect_raw_segments(
|
||||
dxf_dir: Path,
|
||||
config: dict[str, Any],
|
||||
ezdxf,
|
||||
recover,
|
||||
) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]]]:
|
||||
patterns = layer_patterns(config)
|
||||
default_widths = {
|
||||
key: float(value.get("width", 0.1))
|
||||
for key, value in DEFAULT_CATEGORIES.items()
|
||||
}
|
||||
default_widths.update({key: float(value) for key, value in config.get("default_widths", {}).items()})
|
||||
scale = float(config.get("scale", config.get("scale_to_meters", 0.001)))
|
||||
min_source_length = float(config.get("min_source_length", 1.0))
|
||||
min_source_by_category = {
|
||||
key: float(value) for key, value in config.get("min_source_length_by_category", {}).items()
|
||||
}
|
||||
min_meters_length = float(config.get("min_length_meters", 0.0))
|
||||
min_meters_by_category = {
|
||||
key: float(value) for key, value in config.get("min_length_meters_by_category", {}).items()
|
||||
}
|
||||
max_chord = float(config.get("curve_chord_source_length", 750.0))
|
||||
drawings = config.get("drawings") or auto_drawings(dxf_dir)
|
||||
floor_data: dict[str, dict[str, Any]] = {}
|
||||
extraction_report: list[dict[str, Any]] = []
|
||||
|
||||
for drawing in drawings:
|
||||
path = dxf_dir / drawing["file"]
|
||||
if not path.exists():
|
||||
extraction_report.append({"file": drawing["file"], "status": "missing"})
|
||||
continue
|
||||
doc = read_doc(path, ezdxf, recover)
|
||||
entities = list(doc.modelspace())
|
||||
floors = drawing.get("floors") or [{"key": Path(drawing["file"]).stem, "name": Path(drawing["file"]).stem}]
|
||||
|
||||
for floor in floors:
|
||||
key = str(floor["key"])
|
||||
offset_values = floor.get("offset", drawing.get("offset", [0, 0]))
|
||||
offset = (float(offset_values[0]), float(offset_values[1]))
|
||||
segments_by_category: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
||||
ignored_by_type: dict[str, int] = defaultdict(int)
|
||||
included = 0
|
||||
|
||||
for entity in entities:
|
||||
for extracted_entity, fallback_layer, block_name in iter_model_entities(entity, config):
|
||||
layer = entity_layer(extracted_entity)
|
||||
category = category_for_entity(
|
||||
extracted_entity,
|
||||
patterns,
|
||||
config,
|
||||
fallback_layer=fallback_layer,
|
||||
block_name=block_name,
|
||||
)
|
||||
if not category:
|
||||
ignored_by_type[extracted_entity.dxftype()] += 1
|
||||
continue
|
||||
for start, end in entity_segments(extracted_entity, max_chord):
|
||||
if not segment_matches_floor(start, end, floor, drawing):
|
||||
continue
|
||||
seg = cleaned_segment(
|
||||
start,
|
||||
end,
|
||||
offset,
|
||||
min_source_by_category.get(category, min_source_length),
|
||||
min_meters_by_category.get(category, min_meters_length),
|
||||
scale,
|
||||
)
|
||||
if not seg:
|
||||
continue
|
||||
clean_start, clean_end = seg
|
||||
segments_by_category[category].append(
|
||||
{
|
||||
"start_source": clean_start,
|
||||
"end_source": clean_end,
|
||||
"width": default_widths.get(category, 0.1),
|
||||
"layer": layer,
|
||||
"source_type": extracted_entity.dxftype(),
|
||||
"block_name": block_name,
|
||||
"fallback_layer": fallback_layer,
|
||||
}
|
||||
)
|
||||
included += 1
|
||||
|
||||
floor_data[key] = {
|
||||
"key": key,
|
||||
"name": str(floor.get("name", key)),
|
||||
"z": floor.get("z"),
|
||||
"height": float(floor.get("height", config.get("floor_height", 4.2))),
|
||||
"source_file": path.name,
|
||||
"segments_source": dict(segments_by_category),
|
||||
}
|
||||
extraction_report.append(
|
||||
{
|
||||
"file": path.name,
|
||||
"floor": key,
|
||||
"status": "ok",
|
||||
"segments": included,
|
||||
"ignored_entity_types": dict(sorted(ignored_by_type.items())),
|
||||
}
|
||||
)
|
||||
return floor_data, extraction_report
|
||||
|
||||
|
||||
def source_origin(floor_data: dict[str, dict[str, Any]], config: dict[str, Any]) -> tuple[float, float]:
|
||||
if "origin" in config:
|
||||
origin = config["origin"]
|
||||
return float(origin[0]), float(origin[1])
|
||||
xs: list[float] = []
|
||||
ys: list[float] = []
|
||||
for floor in floor_data.values():
|
||||
for segments in floor["segments_source"].values():
|
||||
for segment in segments:
|
||||
xs.extend([segment["start_source"][0], segment["end_source"][0]])
|
||||
ys.extend([segment["start_source"][1], segment["end_source"][1]])
|
||||
if not xs:
|
||||
return 0.0, 0.0
|
||||
if config.get("origin_strategy", "min") == "center":
|
||||
return (min(xs) + max(xs)) / 2.0, (min(ys) + max(ys)) / 2.0
|
||||
return min(xs), min(ys)
|
||||
|
||||
|
||||
def to_meters(point: tuple[float, float], origin: tuple[float, float], scale: float) -> list[float]:
|
||||
return [
|
||||
round((point[0] - origin[0]) * scale, 6),
|
||||
round((point[1] - origin[1]) * scale, 6),
|
||||
]
|
||||
|
||||
|
||||
def generated_footprint(segments: dict[str, list[dict[str, Any]]], config: dict[str, Any]) -> dict[str, Any] | None:
|
||||
if not config.get("generate_footprints", False):
|
||||
return None
|
||||
try:
|
||||
from shapely import MultiPoint, concave_hull # type: ignore
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
categories = list(config.get("footprint_categories", ["walls", "glazing", "floor_lines", "railings", "columns"]))
|
||||
points: list[tuple[float, float]] = []
|
||||
for category in categories:
|
||||
for segment in segments.get(category, []):
|
||||
start = segment.get("start")
|
||||
end = segment.get("end")
|
||||
if not start or not end:
|
||||
continue
|
||||
points.append((float(start[0]), float(start[1])))
|
||||
points.append((float(end[0]), float(end[1])))
|
||||
unique_points = sorted(set(points))
|
||||
if len(unique_points) < 4:
|
||||
return None
|
||||
|
||||
ratio = float(config.get("footprint_concave_ratio", 0.35))
|
||||
simplify = float(config.get("footprint_simplify_tolerance", 0.12))
|
||||
min_area = float(config.get("footprint_min_area", 8.0))
|
||||
try:
|
||||
hull = concave_hull(MultiPoint(unique_points), ratio=ratio)
|
||||
if simplify > 0:
|
||||
hull = hull.simplify(simplify, preserve_topology=True)
|
||||
if hull.is_empty or hull.area < min_area:
|
||||
return None
|
||||
if hull.geom_type == "Polygon":
|
||||
polygons = [hull]
|
||||
elif hull.geom_type == "MultiPolygon":
|
||||
polygons = list(hull.geoms)
|
||||
else:
|
||||
return None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
result_polygons = []
|
||||
for polygon in sorted(polygons, key=lambda item: item.area, reverse=True):
|
||||
if polygon.area < min_area:
|
||||
continue
|
||||
coords = [[round(float(x), 6), round(float(y), 6)] for x, y in polygon.exterior.coords]
|
||||
if len(coords) > 3:
|
||||
result_polygons.append(coords)
|
||||
max_polygons = int(config.get("footprint_max_polygons", 3))
|
||||
if len(result_polygons) >= max_polygons:
|
||||
break
|
||||
if not result_polygons:
|
||||
return None
|
||||
return {
|
||||
"source": "concave_hull",
|
||||
"categories": categories,
|
||||
"polygons": result_polygons,
|
||||
"area": round(sum(abs(polygon.area) for polygon in polygons), 3),
|
||||
}
|
||||
|
||||
|
||||
def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offset_tol: float = 0.30, gap_tol: float = 3.6) -> list[dict[str, Any]]:
|
||||
"""Merge collinear, near-touching segments into continuous spans.
|
||||
|
||||
CAD curtain walls are often drawn as sparse panel/mullion segments with gaps;
|
||||
extruding each one gives a row of disconnected glass fins. Merging along each
|
||||
facade line (bridging gaps up to ``gap_tol``) yields continuous glazing bands.
|
||||
Only bridge gaps that contain no opaque wall on the same line.
|
||||
"""
|
||||
groups: dict[tuple, list] = {}
|
||||
keep: list[dict[str, Any]] = []
|
||||
for s in segs:
|
||||
a = s["start"]; b = s["end"]
|
||||
dx = b[0] - a[0]; dy = b[1] - a[1]; length = math.hypot(dx, dy)
|
||||
if length < 1e-6:
|
||||
keep.append(s); continue
|
||||
ang = math.atan2(dy, dx) % math.pi
|
||||
akey = round(ang / math.radians(angle_tol_deg))
|
||||
nx, ny = -dy / length, dx / length
|
||||
okey = round((a[0] * nx + a[1] * ny) / offset_tol)
|
||||
groups.setdefault((akey, okey), []).append((a, b, nx, ny, float(s.get("width", 0.06)), s.get("layer", "")))
|
||||
out = list(keep)
|
||||
for items in groups.values():
|
||||
a0, b0, nx, ny, width, layer = items[0]
|
||||
dirx, diry = -ny, nx
|
||||
offv = a0[0] * nx + a0[1] * ny
|
||||
intervals = []
|
||||
for (a, b, *_rest) in items:
|
||||
t0 = a[0] * dirx + a[1] * diry; t1 = b[0] * dirx + b[1] * diry
|
||||
intervals.append([min(t0, t1), max(t0, t1)])
|
||||
intervals.sort()
|
||||
merged = [intervals[0][:]]
|
||||
for lo, hi in intervals[1:]:
|
||||
if lo <= merged[-1][1] + gap_tol:
|
||||
merged[-1][1] = max(merged[-1][1], hi)
|
||||
else:
|
||||
merged.append([lo, hi])
|
||||
for lo, hi in merged:
|
||||
out.append({
|
||||
"start": [round(offv * nx + lo * dirx, 6), round(offv * ny + lo * diry, 6)],
|
||||
"end": [round(offv * nx + hi * dirx, 6), round(offv * ny + hi * diry, 6)],
|
||||
"width": width, "layer": layer, "source_type": "merged",
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _cap_floor_group(fk: str) -> str:
|
||||
if fk.startswith("AUX_"):
|
||||
return "AUX"
|
||||
if fk in {"B1", "B1M"}:
|
||||
return "BASE"
|
||||
return "MAIN"
|
||||
|
||||
|
||||
def _shapely_union(polys: list):
|
||||
try:
|
||||
from shapely.geometry import Polygon
|
||||
from shapely.ops import unary_union
|
||||
except Exception:
|
||||
return None
|
||||
gs = []
|
||||
for p in polys:
|
||||
try:
|
||||
g = Polygon(p)
|
||||
if not g.is_valid:
|
||||
g = g.buffer(0)
|
||||
if not g.is_empty and g.area > 0:
|
||||
gs.append(g)
|
||||
except Exception:
|
||||
pass
|
||||
return unary_union(gs) if gs else None
|
||||
|
||||
|
||||
def _shapely_to_polys(geom, min_area: float = 3.0) -> list[list[list[float]]]:
|
||||
res = []
|
||||
if geom is None or geom.is_empty:
|
||||
return res
|
||||
geoms = [geom] if geom.geom_type == "Polygon" else list(getattr(geom, "geoms", []))
|
||||
for g in geoms:
|
||||
if g.geom_type != "Polygon" or g.area < min_area:
|
||||
continue
|
||||
res.append([[round(float(x), 6), round(float(y), 6)] for x, y in g.exterior.coords])
|
||||
return res
|
||||
|
||||
|
||||
def compute_caps(floors: dict[str, Any], config: dict[str, Any]) -> None:
|
||||
"""Store floor['caps'] = [{z, polygons}] that close column tops.
|
||||
|
||||
- Above-ground setback floor: cap = own_footprint(buffered) - upper_footprint.
|
||||
- Basement top (no same-group upper): cap = full footprint (ground/podium deck).
|
||||
Requires shapely; silently no-ops if unavailable or footprints missing.
|
||||
"""
|
||||
if not config.get("generate_caps", True):
|
||||
return
|
||||
buf = float(config.get("cap_buffer", 1.3))
|
||||
for fk, fl in floors.items():
|
||||
own_polys = fl.get("footprint", {}).get("polygons", [])
|
||||
if not own_polys:
|
||||
continue
|
||||
ftop = float(fl["z"]) + float(fl.get("height", 4.2))
|
||||
grp = _cap_floor_group(fk)
|
||||
upper = []
|
||||
for ok, ot in floors.items():
|
||||
if ok == fk or _cap_floor_group(ok) != grp:
|
||||
continue
|
||||
if abs(float(ot.get("z", 0.0)) - ftop) > 0.8:
|
||||
continue
|
||||
upper.extend(ot.get("footprint", {}).get("polygons", []))
|
||||
own_u = _shapely_union(own_polys)
|
||||
if own_u is None:
|
||||
return # shapely unavailable
|
||||
if not upper:
|
||||
if grp == "BASE":
|
||||
polys = _shapely_to_polys(own_u.buffer(0.5))
|
||||
else:
|
||||
polys = [] # roof_specs handles above-ground tops
|
||||
else:
|
||||
up_u = _shapely_union(upper)
|
||||
polys = _shapely_to_polys(own_u.buffer(buf).difference(up_u.buffer(0.05))) if up_u is not None else []
|
||||
if polys:
|
||||
fl.setdefault("caps", []).append({"z": round(ftop, 6), "polygons": polys})
|
||||
|
||||
|
||||
def finalize_spec(
|
||||
floor_data: dict[str, dict[str, Any]],
|
||||
config: dict[str, Any],
|
||||
extraction_report: list[dict[str, Any]],
|
||||
dxf_dir: Path,
|
||||
) -> dict[str, Any]:
|
||||
scale = float(config.get("scale", config.get("scale_to_meters", 0.001)))
|
||||
origin = source_origin(floor_data, config)
|
||||
ordered_keys = config.get("floor_order") or sorted(floor_data.keys(), key=floor_sort_key)
|
||||
floors: dict[str, Any] = {}
|
||||
|
||||
for index, key in enumerate(ordered_keys):
|
||||
if key not in floor_data:
|
||||
continue
|
||||
floor = floor_data[key]
|
||||
segments: dict[str, list[dict[str, Any]]] = {category: [] for category in DEFAULT_CATEGORIES if category != "slab"}
|
||||
xs: list[float] = []
|
||||
ys: list[float] = []
|
||||
for category, raw_segments in floor["segments_source"].items():
|
||||
for raw in raw_segments:
|
||||
start = to_meters(raw["start_source"], origin, scale)
|
||||
end = to_meters(raw["end_source"], origin, scale)
|
||||
xs.extend([start[0], end[0]])
|
||||
ys.extend([start[1], end[1]])
|
||||
segments.setdefault(category, []).append(
|
||||
{
|
||||
"start": start,
|
||||
"end": end,
|
||||
"width": float(raw["width"]),
|
||||
"layer": raw["layer"],
|
||||
"source_type": raw["source_type"],
|
||||
}
|
||||
)
|
||||
bounds = [
|
||||
round(min(xs), 6) if xs else 0.0,
|
||||
round(min(ys), 6) if ys else 0.0,
|
||||
round(max(xs), 6) if xs else 1.0,
|
||||
round(max(ys), 6) if ys else 1.0,
|
||||
]
|
||||
floor_height = float(floor["height"])
|
||||
z = float(floor["z"]) if floor["z"] is not None else index * floor_height
|
||||
floors[key] = {
|
||||
"name": floor["name"],
|
||||
"z": round(z, 6),
|
||||
"height": floor_height,
|
||||
"bounds": bounds,
|
||||
"source_file": floor["source_file"],
|
||||
"segments": segments,
|
||||
}
|
||||
footprint = generated_footprint(segments, config)
|
||||
if footprint:
|
||||
floors[key]["footprint"] = footprint
|
||||
|
||||
# Post-process: make facade glazing continuous, and cap column tops.
|
||||
if config.get("merge_glazing", True):
|
||||
for floor in floors.values():
|
||||
glz = floor.get("segments", {}).get("glazing")
|
||||
if glz:
|
||||
floor["segments"]["glazing"] = merge_collinear(
|
||||
glz,
|
||||
gap_tol=float(config.get("glazing_gap_tol", 3.6)),
|
||||
)
|
||||
compute_caps(floors, config)
|
||||
|
||||
categories = {
|
||||
key: {"label": value["label"], "color": value["color"]}
|
||||
for key, value in DEFAULT_CATEGORIES.items()
|
||||
}
|
||||
for key, value in config.get("categories", {}).items():
|
||||
categories.setdefault(key, {}).update(value)
|
||||
|
||||
return {
|
||||
"project": {
|
||||
"name": config.get("project_name", "CAD Building Showcase"),
|
||||
"description": config.get("description", "建筑 CAD 生成的 Web 展示模型"),
|
||||
},
|
||||
"source": {
|
||||
"dxf_dir": str(dxf_dir),
|
||||
"config": config,
|
||||
},
|
||||
"units": {
|
||||
"source": config.get("source_units", "millimeters"),
|
||||
"scale_to_meters": scale,
|
||||
"origin_source": [origin[0], origin[1]],
|
||||
},
|
||||
"categories": categories,
|
||||
"floors": floors,
|
||||
"extraction_report": extraction_report,
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
dxf_dir = Path(args.dxf_dir)
|
||||
if not dxf_dir.exists():
|
||||
raise SystemExit(f"DXF folder not found: {dxf_dir}")
|
||||
config = read_json(Path(args.config) if args.config else None)
|
||||
ezdxf, recover = import_ezdxf(Path(args.vendor_dir))
|
||||
floor_data, extraction_report = collect_raw_segments(dxf_dir, config, ezdxf, recover)
|
||||
spec = finalize_spec(floor_data, config, extraction_report, dxf_dir)
|
||||
out = Path(args.out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(spec, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(json.dumps({"out": str(out), "floors": len(spec["floors"])}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user