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:
505
scripts/audit_showcase_extraction.py
Executable file
505
scripts/audit_showcase_extraction.py
Executable file
@@ -0,0 +1,505 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Audit extraction coverage so the agent can judge what may be missing."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from collections import Counter, 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
|
||||
|
||||
|
||||
HIGH_RISK_TYPES = {
|
||||
"INSERT",
|
||||
"HATCH",
|
||||
"SOLID",
|
||||
"3DFACE",
|
||||
"REGION",
|
||||
"ACAD_PROXY_ENTITY",
|
||||
"DIMENSION",
|
||||
"TEXT",
|
||||
"MTEXT",
|
||||
"IMAGE",
|
||||
"WIPEOUT",
|
||||
}
|
||||
|
||||
|
||||
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="Generated building_spec.json")
|
||||
parser.add_argument("--out", default="work/cad_showcase/extraction_audit", help="Output path stem or folder")
|
||||
parser.add_argument("--vendor-dir", default="work/vendor")
|
||||
parser.add_argument(
|
||||
"--no-strict-gates",
|
||||
action="store_true",
|
||||
help="Report gate failures without a nonzero exit code",
|
||||
)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def iter_block_contents(entity, max_depth: int, depth: int = 0):
|
||||
"""Yield every leaf entity inside an INSERT, regardless of extraction config."""
|
||||
if depth >= max_depth:
|
||||
return
|
||||
try:
|
||||
from ezdxf import explode as ezdxf_explode
|
||||
|
||||
virtual_entities = list(ezdxf_explode.virtual_block_reference_entities(entity))
|
||||
except Exception:
|
||||
return
|
||||
for virtual_entity in virtual_entities:
|
||||
if virtual_entity.dxftype() == "INSERT":
|
||||
yield from iter_block_contents(virtual_entity, max_depth, depth + 1)
|
||||
else:
|
||||
yield virtual_entity
|
||||
|
||||
|
||||
def output_paths(output: Path) -> tuple[Path, Path]:
|
||||
if output.suffix:
|
||||
return output.with_suffix(".json"), output.with_suffix(".md")
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
return output / "extraction_audit.json", output / "extraction_audit.md"
|
||||
|
||||
|
||||
def segment_length_source(segment: tuple[tuple[float, float], tuple[float, float]]) -> float:
|
||||
(sx, sy), (ex, ey) = segment
|
||||
return math.hypot(ex - sx, ey - sy)
|
||||
|
||||
|
||||
def inspect_entity(
|
||||
entity,
|
||||
patterns: dict[str, list[str]],
|
||||
config: dict[str, Any],
|
||||
max_chord: float,
|
||||
fallback_layer: str = "",
|
||||
block_name: str = "",
|
||||
) -> dict[str, Any]:
|
||||
layer = derive.entity_layer(entity)
|
||||
dxftype = entity.dxftype()
|
||||
category = derive.category_for_entity(
|
||||
entity,
|
||||
patterns,
|
||||
config,
|
||||
fallback_layer=fallback_layer,
|
||||
block_name=block_name,
|
||||
)
|
||||
segments = derive.entity_segments(entity, max_chord)
|
||||
supported_length = sum(segment_length_source(segment) for segment in segments)
|
||||
return {
|
||||
"layer": layer,
|
||||
"type": dxftype,
|
||||
"category": category,
|
||||
"segment_count": len(segments),
|
||||
"supported_length": supported_length,
|
||||
"high_risk": dxftype in HIGH_RISK_TYPES,
|
||||
"insert_name": block_name or (str(entity.dxf.name) if dxftype == "INSERT" and entity.dxf.hasattr("name") else ""),
|
||||
}
|
||||
|
||||
|
||||
def source_files_from_config(dxf_dir: Path, config: dict[str, Any]) -> list[Path]:
|
||||
drawings = config.get("drawings")
|
||||
if drawings:
|
||||
return [dxf_dir / drawing["file"] for drawing in drawings if (dxf_dir / drawing["file"]).exists()]
|
||||
return sorted(dxf_dir.glob("*.dxf"))
|
||||
|
||||
|
||||
def spec_counts(spec: dict[str, Any]) -> dict[str, dict[str, int]]:
|
||||
categories = [key for key in spec.get("categories", {}) if key != "slab"]
|
||||
result = {}
|
||||
for floor_key, floor in spec.get("floors", {}).items():
|
||||
result[floor_key] = {
|
||||
category: len(floor.get("segments", {}).get(category, []))
|
||||
for category in categories
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_dir: Path) -> 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(config.get("scale", config.get("scale_to_meters", 0.001)))
|
||||
|
||||
file_reports = []
|
||||
global_entity_types = Counter()
|
||||
global_layer_counts = Counter()
|
||||
global_high_risk = Counter()
|
||||
global_insert_names = Counter()
|
||||
layer_lengths: dict[str, dict[str, Any]] = defaultdict(
|
||||
lambda: {
|
||||
"entity_count": 0,
|
||||
"supported_length_source": 0.0,
|
||||
"classified_length_source": 0.0,
|
||||
"categories": Counter(),
|
||||
"entity_types": Counter(),
|
||||
"high_risk_types": Counter(),
|
||||
}
|
||||
)
|
||||
total_supported = 0.0
|
||||
classified_supported = 0.0
|
||||
captured_from_blocks = 0.0
|
||||
excludes = derive.exclude_layer_patterns(config)
|
||||
max_block_depth = int(config.get("expand_blocks_max_depth", 2))
|
||||
block_layer_lengths: dict[str, dict[str, Any]] = defaultdict(
|
||||
lambda: {"supported_length_source": 0.0, "entity_count": 0, "category": None}
|
||||
)
|
||||
|
||||
for path in source_files_from_config(dxf_dir, config):
|
||||
doc = derive.read_doc(path, ezdxf, recover)
|
||||
file_total_supported = 0.0
|
||||
file_classified_supported = 0.0
|
||||
file_entity_types = Counter()
|
||||
file_high_risk = Counter()
|
||||
file_layers = Counter()
|
||||
file_insert_names = Counter()
|
||||
|
||||
for source_entity in doc.modelspace():
|
||||
if source_entity.dxftype() == "INSERT":
|
||||
insert_name = str(source_entity.dxf.name) if source_entity.dxf.hasattr("name") else ""
|
||||
global_high_risk["INSERT"] += 1
|
||||
file_high_risk["INSERT"] += 1
|
||||
if insert_name:
|
||||
global_insert_names[insert_name] += 1
|
||||
file_insert_names[insert_name] += 1
|
||||
# Config-independent accounting of geometry locked inside blocks,
|
||||
# so missing block expansion cannot hide behind a high coverage number.
|
||||
for inner in iter_block_contents(source_entity, max_block_depth):
|
||||
inner_length = sum(
|
||||
segment_length_source(segment)
|
||||
for segment in derive.entity_segments(inner, max_chord)
|
||||
)
|
||||
if inner_length <= 0:
|
||||
continue
|
||||
inner_layer = derive.entity_layer(inner)
|
||||
record = block_layer_lengths[inner_layer]
|
||||
record["supported_length_source"] += inner_length
|
||||
record["entity_count"] += 1
|
||||
if record["category"] is None:
|
||||
record["category"] = derive.match_category(inner_layer, patterns, excludes) or ""
|
||||
for entity, fallback_layer, block_name in derive.iter_model_entities(source_entity, config):
|
||||
item = inspect_entity(entity, patterns, config, max_chord, fallback_layer, block_name)
|
||||
layer = item["layer"]
|
||||
dxftype = item["type"]
|
||||
length = float(item["supported_length"])
|
||||
category = item["category"]
|
||||
|
||||
global_entity_types[dxftype] += 1
|
||||
global_layer_counts[layer] += 1
|
||||
file_entity_types[dxftype] += 1
|
||||
file_layers[layer] += 1
|
||||
|
||||
layer_lengths[layer]["entity_count"] += 1
|
||||
layer_lengths[layer]["supported_length_source"] += length
|
||||
layer_lengths[layer]["entity_types"][dxftype] += 1
|
||||
if category:
|
||||
layer_lengths[layer]["categories"][category] += 1
|
||||
layer_lengths[layer]["classified_length_source"] += length
|
||||
classified_supported += length
|
||||
file_classified_supported += length
|
||||
if block_name:
|
||||
captured_from_blocks += length
|
||||
total_supported += length
|
||||
file_total_supported += length
|
||||
|
||||
if item["high_risk"]:
|
||||
# Top-level INSERTs were already counted above.
|
||||
if not (dxftype == "INSERT" and entity is source_entity):
|
||||
global_high_risk[dxftype] += 1
|
||||
file_high_risk[dxftype] += 1
|
||||
layer_lengths[layer]["high_risk_types"][dxftype] += 1
|
||||
if item["insert_name"] and entity is not source_entity:
|
||||
global_insert_names[item["insert_name"]] += 1
|
||||
file_insert_names[item["insert_name"]] += 1
|
||||
|
||||
file_reports.append(
|
||||
{
|
||||
"file": path.name,
|
||||
"entity_types": dict(file_entity_types.most_common()),
|
||||
"top_layers": dict(file_layers.most_common(20)),
|
||||
"high_risk_types": dict(file_high_risk.most_common()),
|
||||
"insert_names": dict(file_insert_names.most_common(20)),
|
||||
"supported_length_meters": round(file_total_supported * scale, 3),
|
||||
"classified_supported_length_meters": round(file_classified_supported * scale, 3),
|
||||
"supported_length_coverage": round(file_classified_supported / file_total_supported, 4)
|
||||
if file_total_supported
|
||||
else None,
|
||||
}
|
||||
)
|
||||
|
||||
unclassified_layers = []
|
||||
classified_layers = []
|
||||
for layer, data in layer_lengths.items():
|
||||
record = {
|
||||
"layer": layer,
|
||||
"entity_count": data["entity_count"],
|
||||
"supported_length_meters": round(data["supported_length_source"] * scale, 3),
|
||||
"classified_length_meters": round(data["classified_length_source"] * scale, 3),
|
||||
"categories": dict(data["categories"].most_common()),
|
||||
"entity_types": dict(data["entity_types"].most_common(10)),
|
||||
"high_risk_types": dict(data["high_risk_types"].most_common()),
|
||||
}
|
||||
if data["classified_length_source"] > 0:
|
||||
classified_layers.append(record)
|
||||
else:
|
||||
unclassified_layers.append(record)
|
||||
|
||||
unclassified_layers.sort(key=lambda item: (-item["supported_length_meters"], -item["entity_count"], item["layer"]))
|
||||
classified_layers.sort(key=lambda item: (-item["classified_length_meters"], item["layer"]))
|
||||
|
||||
block_locked_layers = []
|
||||
block_locked_total = 0.0
|
||||
block_locked_classifiable = 0.0
|
||||
for layer, data in block_layer_lengths.items():
|
||||
length = float(data["supported_length_source"])
|
||||
block_locked_total += length
|
||||
if data["category"]:
|
||||
block_locked_classifiable += length
|
||||
block_locked_layers.append(
|
||||
{
|
||||
"layer": layer,
|
||||
"category": data["category"] or None,
|
||||
"entity_count": data["entity_count"],
|
||||
"supported_length_meters": round(length * scale, 3),
|
||||
}
|
||||
)
|
||||
block_locked_layers.sort(key=lambda item: -item["supported_length_meters"])
|
||||
|
||||
report = {
|
||||
"dxf_dir": str(dxf_dir),
|
||||
"coverage": {
|
||||
"supported_length_meters": round(total_supported * scale, 3),
|
||||
"classified_supported_length_meters": round(classified_supported * scale, 3),
|
||||
"supported_length_coverage": round(classified_supported / total_supported, 4)
|
||||
if total_supported
|
||||
else None,
|
||||
"block_locked_length_meters": round(block_locked_total * scale, 3),
|
||||
"block_locked_classifiable_length_meters": round(block_locked_classifiable * scale, 3),
|
||||
"block_captured_classified_length_meters": round(captured_from_blocks * scale, 3),
|
||||
},
|
||||
"spec_counts": spec_counts(spec),
|
||||
"files": file_reports,
|
||||
"classified_layers": classified_layers,
|
||||
"unclassified_layers": unclassified_layers[:80],
|
||||
"block_locked_layers": block_locked_layers[:40],
|
||||
"high_risk_entity_types": dict(global_high_risk.most_common()),
|
||||
"top_insert_names": dict(global_insert_names.most_common(50)),
|
||||
"entity_types": dict(global_entity_types.most_common()),
|
||||
"top_layers": dict(global_layer_counts.most_common(50)),
|
||||
"agent_questions": agent_questions(unclassified_layers, global_high_risk, global_insert_names),
|
||||
}
|
||||
report["gates"] = evaluate_gates(report)
|
||||
return report
|
||||
|
||||
|
||||
GATE_GLAZING_MIN_METERS = 5.0
|
||||
|
||||
|
||||
def evaluate_gates(report: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""Hard checks that must pass before 3D generation.
|
||||
|
||||
A gate FAIL means the extraction is known-incomplete in a way that high
|
||||
coverage numbers cannot excuse; fix the config (block expansion, layer
|
||||
mapping, source re-export) and re-run instead of accepting the model.
|
||||
"""
|
||||
gates: list[dict[str, Any]] = []
|
||||
|
||||
spec_glazing_segments = sum(
|
||||
counts.get("glazing", 0) for counts in report["spec_counts"].values()
|
||||
)
|
||||
locked_glazing_meters = sum(
|
||||
item["supported_length_meters"]
|
||||
for item in report["block_locked_layers"]
|
||||
if item["category"] == "glazing"
|
||||
)
|
||||
glazing_named_blocks = [
|
||||
name
|
||||
for name in report["top_insert_names"]
|
||||
if derive.match_patterns(name, derive.GLAZING_BLOCK_PATTERNS)
|
||||
]
|
||||
glazing_evidence = locked_glazing_meters >= GATE_GLAZING_MIN_METERS or bool(glazing_named_blocks)
|
||||
if not glazing_evidence:
|
||||
status, detail = "SKIP", "No curtain-wall/glazing evidence in blocks or block names."
|
||||
elif spec_glazing_segments > 0:
|
||||
status = "PASS"
|
||||
detail = (
|
||||
f"Spec contains {spec_glazing_segments} glazing segments; "
|
||||
f"~{round(locked_glazing_meters, 1)} m of glazing-layer geometry found inside blocks."
|
||||
)
|
||||
else:
|
||||
status = "FAIL"
|
||||
detail = (
|
||||
f"Glazing evidence exists (~{round(locked_glazing_meters, 1)} m on glazing layers inside blocks; "
|
||||
f"block names: {', '.join(glazing_named_blocks[:3]) or 'none'}) but the spec has 0 glazing segments. "
|
||||
"Enable block expansion / classify_block_contents or fix glazing layer mapping, then re-run."
|
||||
)
|
||||
gates.append({"name": "glazing_captured", "status": status, "detail": detail})
|
||||
|
||||
annotation_classified = [
|
||||
item["layer"]
|
||||
for item in report["classified_layers"]
|
||||
if derive.match_patterns(item["layer"], ["*-IDEN", "*ANNO*", "*-DIMS"])
|
||||
]
|
||||
gates.append(
|
||||
{
|
||||
"name": "no_annotation_layers_classified",
|
||||
"status": "WARN" if annotation_classified else "PASS",
|
||||
"detail": (
|
||||
f"Annotation/identification layers classified as geometry: {', '.join(annotation_classified[:5])}. "
|
||||
"These are tags, not elements; exclude them."
|
||||
if annotation_classified
|
||||
else "No annotation/identification layers classified."
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
coverage = report["coverage"]
|
||||
locked_classifiable = float(coverage["block_locked_classifiable_length_meters"])
|
||||
captured = float(coverage["block_captured_classified_length_meters"])
|
||||
if locked_classifiable > 0 and captured < 0.5 * locked_classifiable:
|
||||
gates.append(
|
||||
{
|
||||
"name": "block_locked_geometry_captured",
|
||||
"status": "WARN",
|
||||
"detail": (
|
||||
f"~{round(locked_classifiable, 1)} m of classifiable geometry sits inside blocks but only "
|
||||
f"~{round(captured, 1)} m was captured. Review block expansion settings."
|
||||
),
|
||||
}
|
||||
)
|
||||
else:
|
||||
gates.append(
|
||||
{
|
||||
"name": "block_locked_geometry_captured",
|
||||
"status": "PASS",
|
||||
"detail": (
|
||||
f"Captured ~{round(captured, 1)} m of ~{round(locked_classifiable, 1)} m "
|
||||
"classifiable block-locked geometry."
|
||||
),
|
||||
}
|
||||
)
|
||||
return gates
|
||||
|
||||
|
||||
def agent_questions(unclassified_layers: list[dict], high_risk: Counter, insert_names: Counter) -> list[str]:
|
||||
questions = []
|
||||
if unclassified_layers:
|
||||
top = [item for item in unclassified_layers if item["supported_length_meters"] > 0][:8]
|
||||
if top:
|
||||
names = ", ".join(f"`{item['layer']}`" for item in top[:5])
|
||||
questions.append(f"Review unclassified geometry layers with significant length: {names}.")
|
||||
if high_risk.get("INSERT", 0):
|
||||
questions.append("Decide whether INSERT/block geometry must be recursively expanded before modeling.")
|
||||
if high_risk.get("HATCH", 0):
|
||||
questions.append("Check whether hatches represent walls/slabs/columns that line extraction missed.")
|
||||
if insert_names:
|
||||
names = ", ".join(f"`{name}`" for name, _count in insert_names.most_common(5))
|
||||
questions.append(f"Inspect frequent block names: {names}.")
|
||||
questions.append("Compare SVG overlays against CAD intent before accepting the model.")
|
||||
return questions
|
||||
|
||||
|
||||
def markdown(report: dict[str, Any]) -> str:
|
||||
coverage = report["coverage"]
|
||||
lines = [
|
||||
"# Extraction Audit",
|
||||
"",
|
||||
"Use this as evidence for Agent judgment. High coverage does not prove correctness; low coverage or high-risk entities require review.",
|
||||
"",
|
||||
"## Gates",
|
||||
"",
|
||||
]
|
||||
for gate in report.get("gates", []):
|
||||
lines.append(f"- **{gate['status']}** `{gate['name']}`: {gate['detail']}")
|
||||
lines.extend(
|
||||
[
|
||||
"",
|
||||
"## Coverage",
|
||||
"",
|
||||
f"- Supported vector length: `{coverage['supported_length_meters']}` m",
|
||||
f"- Classified supported length: `{coverage['classified_supported_length_meters']}` m",
|
||||
f"- Supported-length coverage: `{coverage['supported_length_coverage']}` "
|
||||
"(modelspace linework only — block-locked geometry is NOT in this denominator)",
|
||||
f"- Block-locked geometry: `{coverage['block_locked_length_meters']}` m total, "
|
||||
f"`{coverage['block_locked_classifiable_length_meters']}` m classifiable, "
|
||||
f"`{coverage['block_captured_classified_length_meters']}` m captured into the spec",
|
||||
"",
|
||||
"## Agent Questions",
|
||||
"",
|
||||
]
|
||||
)
|
||||
for question in report["agent_questions"]:
|
||||
lines.append(f"- {question}")
|
||||
lines.extend(["", "## Block-Locked Geometry By Layer", ""])
|
||||
for item in report.get("block_locked_layers", [])[:15]:
|
||||
lines.append(
|
||||
f"- `{item['layer']}` (category: {item['category'] or 'unclassified'}): "
|
||||
f"entities `{item['entity_count']}`, length `{item['supported_length_meters']}` m"
|
||||
)
|
||||
lines.extend(["", "## Spec Counts", ""])
|
||||
for floor_key, counts in report["spec_counts"].items():
|
||||
parts = ", ".join(f"{key}: {value}" for key, value in counts.items())
|
||||
lines.append(f"- `{floor_key}`: {parts}")
|
||||
lines.extend(["", "## High Risk Entity Types", ""])
|
||||
for key, value in report["high_risk_entity_types"].items():
|
||||
lines.append(f"- `{key}`: {value}")
|
||||
lines.extend(["", "## Top Unclassified Geometry Layers", ""])
|
||||
for layer in report["unclassified_layers"][:20]:
|
||||
lines.append(
|
||||
f"- `{layer['layer']}`: entities `{layer['entity_count']}`, "
|
||||
f"supported length `{layer['supported_length_meters']}` m, "
|
||||
f"types `{layer['entity_types']}`"
|
||||
)
|
||||
lines.extend(["", "## Classified Layers", ""])
|
||||
for layer in report["classified_layers"][:30]:
|
||||
lines.append(
|
||||
f"- `{layer['layer']}`: `{layer['categories']}`, "
|
||||
f"classified length `{layer['classified_length_meters']}` m"
|
||||
)
|
||||
lines.extend(["", "## Files", ""])
|
||||
for item in report["files"]:
|
||||
lines.append(
|
||||
f"- `{item['file']}`: coverage `{item['supported_length_coverage']}`, "
|
||||
f"high-risk `{item['high_risk_types']}`"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
config = derive.read_json(Path(args.config))
|
||||
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
|
||||
report = audit(Path(args.dxf_dir), config, spec, Path(args.vendor_dir))
|
||||
json_path, md_path = output_paths(Path(args.out))
|
||||
json_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
md_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
json_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
md_path.write_text(markdown(report), encoding="utf-8")
|
||||
failed_gates = [gate for gate in report.get("gates", []) if gate["status"] == "FAIL"]
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"json": str(json_path),
|
||||
"markdown": str(md_path),
|
||||
"gates": {gate["name"]: gate["status"] for gate in report.get("gates", [])},
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
if failed_gates and not args.no_strict_gates:
|
||||
for gate in failed_gates:
|
||||
print(f"GATE FAIL [{gate['name']}]: {gate['detail']}", file=sys.stderr)
|
||||
return 3
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
757
scripts/build_blender_showcase.py
Executable file
757
scripts/build_blender_showcase.py
Executable file
@@ -0,0 +1,757 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate a Blender scene, GLB, preview PNG, and model metadata from building_spec.json."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
CATEGORY_DRAW_ORDER = (
|
||||
"grid",
|
||||
"floor_lines",
|
||||
"detail_lines",
|
||||
"doors",
|
||||
"railings",
|
||||
"roof",
|
||||
"glazing",
|
||||
"walls",
|
||||
"columns",
|
||||
"beams",
|
||||
)
|
||||
|
||||
DEFAULT_CATEGORY_COLORS = {
|
||||
"slab": "#c8ccc2",
|
||||
"roof": "#b8ae98",
|
||||
"walls": "#d4cbb8",
|
||||
"glazing": "#79b8c9",
|
||||
"columns": "#f58a1f",
|
||||
"beams": "#1f66c2",
|
||||
"railings": "#6f746d",
|
||||
"doors": "#8a6a45",
|
||||
"detail_lines": "#8c9088",
|
||||
"floor_lines": "#18a058",
|
||||
"grid": "#20242a",
|
||||
}
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
argv = sys.argv
|
||||
if "--" in argv:
|
||||
argv = argv[argv.index("--") + 1 :]
|
||||
else:
|
||||
argv = []
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--spec", required=True, help="Path to building_spec.json")
|
||||
parser.add_argument("--out-dir", required=True, help="Output folder")
|
||||
parser.add_argument("--name", default="cad_building_showcase", help="Base output file name")
|
||||
parser.add_argument("--render", action="store_true", default=True, help="Render preview PNG")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def clear_scene(bpy):
|
||||
bpy.ops.object.select_all(action="SELECT")
|
||||
bpy.ops.object.delete()
|
||||
for datablocks in (
|
||||
bpy.data.meshes,
|
||||
bpy.data.curves,
|
||||
bpy.data.materials,
|
||||
bpy.data.images,
|
||||
bpy.data.lights,
|
||||
bpy.data.cameras,
|
||||
):
|
||||
for item in list(datablocks):
|
||||
if item.users == 0:
|
||||
datablocks.remove(item)
|
||||
|
||||
|
||||
def make_material(bpy, name: str, color_hex: str, alpha: float = 1.0, roughness: float = 0.75):
|
||||
color_hex = color_hex.lstrip("#")
|
||||
r = int(color_hex[0:2], 16) / 255.0
|
||||
g = int(color_hex[2:4], 16) / 255.0
|
||||
b = int(color_hex[4:6], 16) / 255.0
|
||||
color = (r, g, b, alpha)
|
||||
mat = bpy.data.materials.new(name)
|
||||
mat.diffuse_color = color
|
||||
mat.use_nodes = True
|
||||
bsdf = mat.node_tree.nodes.get("Principled BSDF")
|
||||
if bsdf:
|
||||
bsdf.inputs["Base Color"].default_value = color
|
||||
bsdf.inputs["Roughness"].default_value = roughness
|
||||
if "Alpha" in bsdf.inputs:
|
||||
bsdf.inputs["Alpha"].default_value = alpha
|
||||
if alpha < 1.0:
|
||||
mat.blend_method = "BLEND"
|
||||
mat.show_transparent_back = True
|
||||
return mat
|
||||
|
||||
|
||||
def create_box_mesh(bpy, name: str, boxes: list[list[float]], material, floor_key: str, category: str):
|
||||
verts = []
|
||||
faces = []
|
||||
for box in boxes:
|
||||
x1, y1, x2, y2, z0, z1 = box
|
||||
idx = len(verts)
|
||||
verts.extend(
|
||||
[
|
||||
(x1, y1, z0),
|
||||
(x2, y1, z0),
|
||||
(x2, y2, z0),
|
||||
(x1, y2, z0),
|
||||
(x1, y1, z1),
|
||||
(x2, y1, z1),
|
||||
(x2, y2, z1),
|
||||
(x1, y2, z1),
|
||||
]
|
||||
)
|
||||
faces.extend(
|
||||
[
|
||||
(idx + 0, idx + 1, idx + 2, idx + 3),
|
||||
(idx + 4, idx + 7, idx + 6, idx + 5),
|
||||
(idx + 0, idx + 4, idx + 5, idx + 1),
|
||||
(idx + 1, idx + 5, idx + 6, idx + 2),
|
||||
(idx + 2, idx + 6, idx + 7, idx + 3),
|
||||
(idx + 3, idx + 7, idx + 4, idx + 0),
|
||||
]
|
||||
)
|
||||
mesh = bpy.data.meshes.new(f"{name}Mesh")
|
||||
mesh.from_pydata(verts, [], faces)
|
||||
mesh.update()
|
||||
mesh.validate(verbose=False) # drop degenerate faces so exported normals never become NaN
|
||||
obj = bpy.data.objects.new(name, mesh)
|
||||
bpy.context.collection.objects.link(obj)
|
||||
obj.data.materials.append(material)
|
||||
obj["floor"] = floor_key
|
||||
obj["category"] = category
|
||||
return obj
|
||||
|
||||
|
||||
def clean_polygon_points(coords: list[list[float]]) -> list[tuple[float, float]]:
|
||||
points = [(float(x), float(y)) for x, y in coords]
|
||||
if len(points) > 1 and points[0] == points[-1]:
|
||||
points = points[:-1]
|
||||
cleaned = []
|
||||
for point in points:
|
||||
if not cleaned or point != cleaned[-1]:
|
||||
cleaned.append(point)
|
||||
return cleaned
|
||||
|
||||
|
||||
def create_polygon_prism_mesh(
|
||||
bpy,
|
||||
name: str,
|
||||
polygons: list[list[list[float]]],
|
||||
z0: float,
|
||||
z1: float,
|
||||
material,
|
||||
floor_key: str,
|
||||
category: str,
|
||||
):
|
||||
from mathutils import Vector
|
||||
from mathutils.geometry import tessellate_polygon
|
||||
|
||||
verts = []
|
||||
faces = []
|
||||
for coords in polygons:
|
||||
points = clean_polygon_points(coords)
|
||||
if len(points) < 3:
|
||||
continue
|
||||
base = len(verts)
|
||||
verts.extend([(x, y, z0) for x, y in points])
|
||||
verts.extend([(x, y, z1) for x, y in points])
|
||||
n = len(points)
|
||||
try:
|
||||
triangles = tessellate_polygon([[Vector((x, y, 0.0)) for x, y in points]])
|
||||
except Exception:
|
||||
triangles = []
|
||||
for triangle in triangles:
|
||||
faces.append(tuple(base + n + index for index in triangle))
|
||||
faces.append(tuple(base + index for index in reversed(triangle)))
|
||||
for index in range(n):
|
||||
next_index = (index + 1) % n
|
||||
faces.append((base + index, base + next_index, base + n + next_index, base + n + index))
|
||||
if not verts or not faces:
|
||||
return None
|
||||
mesh = bpy.data.meshes.new(f"{name}Mesh")
|
||||
mesh.from_pydata(verts, [], faces)
|
||||
mesh.update()
|
||||
mesh.validate(verbose=False) # drop degenerate faces so exported normals never become NaN
|
||||
obj = bpy.data.objects.new(name, mesh)
|
||||
bpy.context.collection.objects.link(obj)
|
||||
obj.data.materials.append(material)
|
||||
obj["floor"] = floor_key
|
||||
obj["category"] = category
|
||||
return obj
|
||||
|
||||
|
||||
def segment_prism(segment: dict, z0: float, z1: float):
|
||||
x1, y1 = segment["start"]
|
||||
x2, y2 = segment["end"]
|
||||
dx = x2 - x1
|
||||
dy = y2 - y1
|
||||
length = math.hypot(dx, dy)
|
||||
if length <= 1e-7:
|
||||
return None
|
||||
half_width = max(float(segment.get("width", 0.1)), 0.005) / 2.0
|
||||
nx = -dy / length * half_width
|
||||
ny = dx / length * half_width
|
||||
return [
|
||||
(x1 + nx, y1 + ny, z0),
|
||||
(x2 + nx, y2 + ny, z0),
|
||||
(x2 - nx, y2 - ny, z0),
|
||||
(x1 - nx, y1 - ny, z0),
|
||||
(x1 + nx, y1 + ny, z1),
|
||||
(x2 + nx, y2 + ny, z1),
|
||||
(x2 - nx, y2 - ny, z1),
|
||||
(x1 - nx, y1 - ny, z1),
|
||||
]
|
||||
|
||||
|
||||
def create_segment_mesh(bpy, name: str, segments: list[dict], z0: float, z1: float, material, floor_key: str, category: str):
|
||||
verts = []
|
||||
faces = []
|
||||
for segment in segments:
|
||||
segment_z0 = float(segment.get("_z0", z0))
|
||||
segment_z1 = float(segment.get("_z1", z1))
|
||||
prism = segment_prism(segment, segment_z0, segment_z1)
|
||||
if not prism:
|
||||
continue
|
||||
idx = len(verts)
|
||||
verts.extend(prism)
|
||||
faces.extend(
|
||||
[
|
||||
(idx + 0, idx + 1, idx + 2, idx + 3),
|
||||
(idx + 4, idx + 7, idx + 6, idx + 5),
|
||||
(idx + 0, idx + 4, idx + 5, idx + 1),
|
||||
(idx + 1, idx + 5, idx + 6, idx + 2),
|
||||
(idx + 2, idx + 6, idx + 7, idx + 3),
|
||||
(idx + 3, idx + 7, idx + 4, idx + 0),
|
||||
]
|
||||
)
|
||||
if not verts:
|
||||
return None
|
||||
mesh = bpy.data.meshes.new(f"{name}Mesh")
|
||||
mesh.from_pydata(verts, [], faces)
|
||||
mesh.update()
|
||||
mesh.validate(verbose=False) # drop degenerate faces so exported normals never become NaN
|
||||
obj = bpy.data.objects.new(name, mesh)
|
||||
bpy.context.collection.objects.link(obj)
|
||||
obj.data.materials.append(material)
|
||||
obj["floor"] = floor_key
|
||||
obj["category"] = category
|
||||
return obj
|
||||
|
||||
|
||||
def create_label(bpy, name: str, body: str, location: tuple[float, float, float], size: float, material):
|
||||
curve = bpy.data.curves.new(f"{name}Curve", "FONT")
|
||||
curve.body = body
|
||||
curve.align_x = "LEFT"
|
||||
curve.align_y = "CENTER"
|
||||
curve.size = size
|
||||
curve.extrude = 0.02
|
||||
obj = bpy.data.objects.new(name, curve)
|
||||
obj.location = location
|
||||
bpy.context.collection.objects.link(obj)
|
||||
obj.data.materials.append(material)
|
||||
return obj
|
||||
|
||||
|
||||
def is_roof_floor(floor_key: str, floor: dict) -> bool:
|
||||
text = f"{floor_key} {floor.get('name', '')}".upper()
|
||||
return "RF" in text or "ROOF" in text or "屋顶" in text or "屋面" in text
|
||||
|
||||
|
||||
def z_window_for_category(category: str, z: float, height: float, floor_key: str, floor: dict) -> tuple[float, float]:
|
||||
if category in {"walls", "columns", "glazing"}:
|
||||
if category == "columns" and is_roof_floor(floor_key, floor):
|
||||
return z, z + min(height, 1.15)
|
||||
return z, z + height
|
||||
if category == "beams":
|
||||
return z + max(height - 0.55, 0.1), z + height
|
||||
if category == "roof":
|
||||
return z - 0.35, z + 0.08
|
||||
if category == "railings":
|
||||
return z + 0.05, z + min(1.20, height)
|
||||
if category == "doors":
|
||||
return z + 0.02, z + min(2.30, height)
|
||||
if category in {"floor_lines", "detail_lines"}:
|
||||
return z + 0.03, z + 0.09
|
||||
if category == "grid":
|
||||
return z + 0.01, z + 0.04
|
||||
return z + 0.03, z + min(0.12, height)
|
||||
|
||||
|
||||
def union_bounds(bounds_list: list[list[float]]) -> list[float] | None:
|
||||
bounds = [math.inf, math.inf, -math.inf, -math.inf]
|
||||
for item in bounds_list:
|
||||
if not item:
|
||||
continue
|
||||
bounds[0] = min(bounds[0], float(item[0]))
|
||||
bounds[1] = min(bounds[1], float(item[1]))
|
||||
bounds[2] = max(bounds[2], float(item[2]))
|
||||
bounds[3] = max(bounds[3], float(item[3]))
|
||||
if not math.isfinite(bounds[0]):
|
||||
return None
|
||||
return bounds
|
||||
|
||||
|
||||
def bounds_from_floor_keys(spec: dict, floor_keys: list[str]) -> list[float] | None:
|
||||
return union_bounds(
|
||||
[
|
||||
spec.get("floors", {}).get(str(key), {}).get("bounds")
|
||||
for key in floor_keys
|
||||
if spec.get("floors", {}).get(str(key), {}).get("bounds")
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def footprint_polygons_from_floor_keys(spec: dict, floor_keys: list[str]) -> list[list[list[float]]]:
|
||||
polygons = []
|
||||
for key in floor_keys:
|
||||
floor = spec.get("floors", {}).get(str(key))
|
||||
if not floor:
|
||||
continue
|
||||
polygons.extend(floor.get("footprint", {}).get("polygons", []))
|
||||
return polygons
|
||||
|
||||
|
||||
def generated_roof_bounds(spec: dict) -> list[dict]:
|
||||
config = spec.get("source", {}).get("config", {})
|
||||
roofs = []
|
||||
for index, roof in enumerate(config.get("roof_specs", []), start=1):
|
||||
floor_key = str(roof.get("floor_key") or roof.get("key") or f"ROOF_{index}")
|
||||
floor = spec.get("floors", {}).get(floor_key)
|
||||
if not floor:
|
||||
continue
|
||||
bounds_from = list(roof.get("bounds_from", [floor_key]))
|
||||
footprint_from = list(roof.get("footprint_from", bounds_from))
|
||||
footprint_polygons = (
|
||||
footprint_polygons_from_floor_keys(spec, footprint_from)
|
||||
if config.get("use_footprint_roofs", False) or roof.get("use_footprint", False)
|
||||
else []
|
||||
)
|
||||
bounds = roof.get("bounds") or bounds_from_floor_keys(spec, bounds_from)
|
||||
if not bounds:
|
||||
bounds = floor.get("bounds")
|
||||
if not bounds:
|
||||
continue
|
||||
margin = float(roof.get("margin", 0.4))
|
||||
roofs.append(
|
||||
{
|
||||
"floor_key": floor_key,
|
||||
"z": float(roof.get("z", floor.get("z", 0.0))),
|
||||
"bounds": [
|
||||
float(bounds[0]) - margin,
|
||||
float(bounds[1]) - margin,
|
||||
float(bounds[2]) + margin,
|
||||
float(bounds[3]) + margin,
|
||||
],
|
||||
"thickness": float(roof.get("thickness", 0.35)),
|
||||
"polygons": footprint_polygons,
|
||||
}
|
||||
)
|
||||
if roofs:
|
||||
return roofs
|
||||
|
||||
for key, floor in spec.get("floors", {}).items():
|
||||
if is_roof_floor(key, floor) and floor.get("bounds"):
|
||||
roofs.append(
|
||||
{
|
||||
"floor_key": key,
|
||||
"z": float(floor.get("z", 0.0)),
|
||||
"bounds": floor["bounds"],
|
||||
"thickness": 0.35,
|
||||
"polygons": floor.get("footprint", {}).get("polygons", []),
|
||||
}
|
||||
)
|
||||
return roofs
|
||||
|
||||
|
||||
def point_in_bounds(point: tuple[float, float], bounds: list[float], margin: float) -> bool:
|
||||
x, y = point
|
||||
return bounds[0] - margin <= x <= bounds[2] + margin and bounds[1] - margin <= y <= bounds[3] + margin
|
||||
|
||||
|
||||
def point_in_polygon(point: tuple[float, float], polygon: list[list[float]]) -> bool:
|
||||
x, y = point
|
||||
inside = False
|
||||
if len(polygon) < 3:
|
||||
return False
|
||||
j = len(polygon) - 1
|
||||
for i, current in enumerate(polygon):
|
||||
xi, yi = float(current[0]), float(current[1])
|
||||
xj, yj = float(polygon[j][0]), float(polygon[j][1])
|
||||
crosses = (yi > y) != (yj > y)
|
||||
if crosses:
|
||||
x_at_y = (xj - xi) * (y - yi) / ((yj - yi) or 1e-12) + xi
|
||||
if x < x_at_y:
|
||||
inside = not inside
|
||||
j = i
|
||||
return inside
|
||||
|
||||
|
||||
def point_in_or_near_polygons(point: tuple[float, float], polygons: list[list[list[float]]], margin: float) -> bool:
|
||||
for polygon in polygons:
|
||||
if point_in_polygon(point, polygon):
|
||||
return True
|
||||
points = clean_polygon_points(polygon)
|
||||
for index, start in enumerate(points):
|
||||
end = points[(index + 1) % len(points)]
|
||||
if point_segment_distance(point, start, end) <= margin:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def floor_group(floor_key: str) -> str:
|
||||
if floor_key.startswith("AUX_"):
|
||||
return "AUX"
|
||||
if floor_key in {"B1", "B1M"}:
|
||||
return "BASE"
|
||||
return "MAIN"
|
||||
|
||||
|
||||
def point_segment_distance(point: tuple[float, float], start: tuple[float, float], end: tuple[float, float]) -> float:
|
||||
px, py = point
|
||||
ax, ay = start
|
||||
bx, by = end
|
||||
dx = bx - ax
|
||||
dy = by - ay
|
||||
length_sq = dx * dx + dy * dy
|
||||
if length_sq <= 1e-12:
|
||||
return math.hypot(px - ax, py - ay)
|
||||
t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / length_sq))
|
||||
return math.hypot(px - (ax + t * dx), py - (ay + t * dy))
|
||||
|
||||
|
||||
def column_has_upper_support(point: tuple[float, float], floor_key: str, floor: dict, spec: dict, config: dict) -> bool:
|
||||
floor_top = float(floor["z"]) + float(floor.get("height", 4.2))
|
||||
support_distance = float(config.get("column_support_distance", 1.1))
|
||||
z_tolerance = float(config.get("column_support_z_tolerance", 0.65))
|
||||
structural_categories = set(config.get("column_support_categories", ["walls", "glazing", "columns", "beams"]))
|
||||
require_upper_plate = bool(config.get("column_support_requires_upper_plate", True))
|
||||
allow_plate_only = bool(config.get("column_support_allow_plate_only", False))
|
||||
group = floor_group(floor_key)
|
||||
|
||||
for other_key, other in spec.get("floors", {}).items():
|
||||
if floor_group(other_key) != group:
|
||||
continue
|
||||
other_z = float(other.get("z", 0.0))
|
||||
if not (floor_top - 0.05 <= other_z <= floor_top + z_tolerance):
|
||||
continue
|
||||
upper_polygons = other.get("footprint", {}).get("polygons", [])
|
||||
if upper_polygons:
|
||||
has_upper_plate = point_in_or_near_polygons(point, upper_polygons, support_distance)
|
||||
if has_upper_plate and allow_plate_only:
|
||||
return True
|
||||
if require_upper_plate and not has_upper_plate:
|
||||
continue
|
||||
for category in structural_categories:
|
||||
for segment in other.get("segments", {}).get(category, []):
|
||||
distance = point_segment_distance(point, tuple(segment["start"]), tuple(segment["end"]))
|
||||
if distance <= support_distance:
|
||||
return True
|
||||
|
||||
roof_z_tolerance = float(config.get("column_roof_support_z_tolerance", 0.65))
|
||||
for roof in generated_roof_bounds(spec):
|
||||
if floor_group(str(roof["floor_key"])) != group:
|
||||
continue
|
||||
if abs(float(roof["z"]) - floor_top) > roof_z_tolerance:
|
||||
continue
|
||||
roof_polygons = roof.get("polygons", [])
|
||||
if roof_polygons and point_in_or_near_polygons(point, roof_polygons, support_distance):
|
||||
return True
|
||||
if not roof_polygons and point_in_bounds(point, roof["bounds"], support_distance):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def adjusted_column_segments(segments: list[dict], floor_key: str, floor: dict, spec: dict) -> list[dict]:
|
||||
config = spec.get("source", {}).get("config", {})
|
||||
if not config.get("shorten_unsupported_columns", False):
|
||||
return segments
|
||||
floor_filter = {str(key) for key in config.get("shorten_unsupported_columns_floor_keys", [])}
|
||||
if floor_filter and floor_key not in floor_filter:
|
||||
return segments
|
||||
z = float(floor["z"])
|
||||
height = float(floor.get("height", 4.2))
|
||||
short_height = min(float(config.get("unsupported_column_height", 1.2)), height)
|
||||
adjusted = []
|
||||
for segment in segments:
|
||||
start = segment["start"]
|
||||
end = segment["end"]
|
||||
midpoint = ((start[0] + end[0]) / 2.0, (start[1] + end[1]) / 2.0)
|
||||
item = dict(segment)
|
||||
if not column_has_upper_support(midpoint, floor_key, floor, spec, config):
|
||||
item["_z0"] = z
|
||||
item["_z1"] = z + short_height
|
||||
adjusted.append(item)
|
||||
return adjusted
|
||||
|
||||
|
||||
def add_floor(bpy, floor_key: str, floor: dict, materials: dict[str, object], spec: dict):
|
||||
z = float(floor["z"])
|
||||
height = float(floor.get("height", 4.2))
|
||||
config = spec.get("source", {}).get("config", {})
|
||||
bounds = floor["bounds"]
|
||||
margin = 1.2
|
||||
slab_thickness = float(floor.get("slab_thickness", config.get("slab_thickness", 0.25)))
|
||||
slab_box = [
|
||||
bounds[0] - margin,
|
||||
bounds[1] - margin,
|
||||
bounds[2] + margin,
|
||||
bounds[3] + margin,
|
||||
z - slab_thickness,
|
||||
z,
|
||||
]
|
||||
footprint = floor.get("footprint", {})
|
||||
footprint_polygons = footprint.get("polygons", []) if config.get("use_footprint_slabs", False) else []
|
||||
if footprint_polygons:
|
||||
create_polygon_prism_mesh(
|
||||
bpy,
|
||||
f"{floor_key}__slab",
|
||||
footprint_polygons,
|
||||
z - slab_thickness,
|
||||
z,
|
||||
materials["slab"],
|
||||
floor_key,
|
||||
"slab",
|
||||
)
|
||||
else:
|
||||
create_box_mesh(bpy, f"{floor_key}__slab", [slab_box], materials["slab"], floor_key, "slab")
|
||||
# Cap slabs close the tops of columns at setbacks and over basement parking
|
||||
# (computed by derive_showcase_spec.py and stored as floor["caps"]). They share
|
||||
# the slab category; Blender de-dups the object name and the Web viewer strips the suffix.
|
||||
for cap in floor.get("caps", []):
|
||||
cap_polys = cap.get("polygons", [])
|
||||
if not cap_polys:
|
||||
continue
|
||||
cap_z = float(cap.get("z", z + height))
|
||||
create_polygon_prism_mesh(
|
||||
bpy,
|
||||
f"{floor_key}__slab",
|
||||
cap_polys,
|
||||
cap_z - slab_thickness,
|
||||
cap_z,
|
||||
materials["slab"],
|
||||
floor_key,
|
||||
"slab",
|
||||
)
|
||||
floor_segments = floor.get("segments", {})
|
||||
known = [category for category in CATEGORY_DRAW_ORDER if floor_segments.get(category)]
|
||||
extra = sorted(category for category in floor_segments if category not in CATEGORY_DRAW_ORDER and floor_segments.get(category))
|
||||
for category in known + extra:
|
||||
segments = floor.get("segments", {}).get(category, [])
|
||||
if not segments:
|
||||
continue
|
||||
if category == "columns":
|
||||
segments = adjusted_column_segments(segments, floor_key, floor, spec)
|
||||
z0, z1 = z_window_for_category(category, z, height, floor_key, floor)
|
||||
create_segment_mesh(
|
||||
bpy,
|
||||
f"{floor_key}__{category}",
|
||||
segments,
|
||||
z0,
|
||||
z1,
|
||||
materials[category],
|
||||
floor_key,
|
||||
category,
|
||||
)
|
||||
if config.get("show_floor_labels", False):
|
||||
create_label(
|
||||
bpy,
|
||||
f"{floor_key}__label",
|
||||
floor.get("name", floor_key),
|
||||
(bounds[0], bounds[3] + 2.0, z + 0.08),
|
||||
1.8,
|
||||
materials["text"],
|
||||
)
|
||||
|
||||
|
||||
def scene_bounds(spec: dict) -> tuple[list[float], float]:
|
||||
bounds = [math.inf, math.inf, -math.inf, -math.inf]
|
||||
max_z = 0.0
|
||||
for floor in spec["floors"].values():
|
||||
b = floor["bounds"]
|
||||
bounds[0] = min(bounds[0], b[0])
|
||||
bounds[1] = min(bounds[1], b[1])
|
||||
bounds[2] = max(bounds[2], b[2])
|
||||
bounds[3] = max(bounds[3], b[3])
|
||||
max_z = max(max_z, float(floor["z"]) + float(floor.get("height", 4.2)))
|
||||
if not math.isfinite(bounds[0]):
|
||||
bounds = [0, 0, 1, 1]
|
||||
return bounds, max_z
|
||||
|
||||
|
||||
def add_generated_roofs(bpy, spec: dict, materials: dict[str, object]):
|
||||
for roof in generated_roof_bounds(spec):
|
||||
bounds = roof["bounds"]
|
||||
z = float(roof["z"])
|
||||
thickness = float(roof["thickness"])
|
||||
polygons = roof.get("polygons", [])
|
||||
if polygons:
|
||||
create_polygon_prism_mesh(
|
||||
bpy,
|
||||
f"{roof['floor_key']}__roof",
|
||||
polygons,
|
||||
z - thickness,
|
||||
z + 0.08,
|
||||
materials["roof"],
|
||||
str(roof["floor_key"]),
|
||||
"roof",
|
||||
)
|
||||
else:
|
||||
box = [bounds[0], bounds[1], bounds[2], bounds[3], z - thickness, z + 0.08]
|
||||
create_box_mesh(
|
||||
bpy,
|
||||
f"{roof['floor_key']}__roof",
|
||||
[box],
|
||||
materials["roof"],
|
||||
str(roof["floor_key"]),
|
||||
"roof",
|
||||
)
|
||||
|
||||
|
||||
def setup_scene(bpy, spec: dict):
|
||||
from mathutils import Vector
|
||||
|
||||
bpy.context.scene.unit_settings.system = "METRIC"
|
||||
bpy.context.scene.unit_settings.scale_length = 1.0
|
||||
try:
|
||||
bpy.context.scene.render.engine = "BLENDER_EEVEE"
|
||||
except TypeError:
|
||||
pass
|
||||
if bpy.context.scene.world:
|
||||
bpy.context.scene.world.color = (0.78, 0.82, 0.86)
|
||||
|
||||
category_defs = dict(spec.get("categories", {}))
|
||||
for floor in spec.get("floors", {}).values():
|
||||
for key in floor.get("segments", {}):
|
||||
category_defs.setdefault(key, {"color": DEFAULT_CATEGORY_COLORS.get(key, "#cccccc")})
|
||||
for key, color in DEFAULT_CATEGORY_COLORS.items():
|
||||
category_defs.setdefault(key, {"color": color})
|
||||
|
||||
alpha_by_category = {
|
||||
"slab": 0.72,
|
||||
"roof": 0.95,
|
||||
"glazing": 0.38,
|
||||
"floor_lines": 0.95,
|
||||
"grid": 0.95,
|
||||
"detail_lines": 0.82,
|
||||
"doors": 0.90,
|
||||
}
|
||||
materials = {
|
||||
key: make_material(
|
||||
bpy,
|
||||
key.replace("_", " "),
|
||||
category_defs.get(key, {}).get("color", DEFAULT_CATEGORY_COLORS.get(key, "#cccccc")),
|
||||
alpha_by_category.get(key, 1.0),
|
||||
)
|
||||
for key in category_defs
|
||||
}
|
||||
materials["text"] = make_material(bpy, "text", "#111111", 1.0)
|
||||
|
||||
for floor_key, floor in spec["floors"].items():
|
||||
add_floor(bpy, floor_key, floor, materials, spec)
|
||||
add_generated_roofs(bpy, spec, materials)
|
||||
|
||||
bounds, max_z = scene_bounds(spec)
|
||||
cx = (bounds[0] + bounds[2]) / 2.0
|
||||
cy = (bounds[1] + bounds[3]) / 2.0
|
||||
sx = max(bounds[2] - bounds[0], 1.0)
|
||||
sy = max(bounds[3] - bounds[1], 1.0)
|
||||
|
||||
bpy.ops.object.light_add(type="SUN", location=(0, 0, max_z + 30))
|
||||
sun = bpy.context.object
|
||||
sun.name = "Sun"
|
||||
sun.data.energy = 2.2
|
||||
sun.rotation_euler = (math.radians(45), 0, math.radians(35))
|
||||
|
||||
bpy.ops.object.light_add(type="AREA", location=(cx - sx * 0.25, cy - sy * 0.7, max_z + 40))
|
||||
area = bpy.context.object
|
||||
area.name = "Large softbox"
|
||||
area.data.energy = 600
|
||||
area.data.size = max(sx, sy) * 0.55
|
||||
|
||||
cam_distance = max(sx, sy, max_z) * 0.95
|
||||
bpy.ops.object.camera_add(location=(cx - cam_distance, cy - cam_distance * 0.85, max_z + cam_distance * 0.65))
|
||||
camera = bpy.context.object
|
||||
camera.name = "Camera - showcase overview"
|
||||
direction = Vector((cx, cy, max_z * 0.35)) - camera.location
|
||||
camera.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler()
|
||||
camera.data.type = "ORTHO"
|
||||
camera.data.ortho_scale = max(sx, sy) * 1.18
|
||||
bpy.context.scene.camera = camera
|
||||
|
||||
bpy.context.scene.render.resolution_x = 1800
|
||||
bpy.context.scene.render.resolution_y = 1200
|
||||
bpy.context.scene.view_settings.view_transform = "Standard"
|
||||
bpy.context.scene.view_settings.look = "Medium High Contrast"
|
||||
return bounds, max_z
|
||||
|
||||
|
||||
def metadata(spec: dict, bounds: list[float], max_z: float, name: str) -> dict:
|
||||
config = spec.get("source", {}).get("config", {})
|
||||
return {
|
||||
"project": spec.get("project", {"name": name}),
|
||||
"floors": [
|
||||
{"key": key, "name": floor.get("name", key), "z": floor.get("z", 0), "height": floor.get("height", 4.2)}
|
||||
for key, floor in spec.get("floors", {}).items()
|
||||
],
|
||||
"categories": spec.get("categories", {}),
|
||||
"viewer_defaults": {
|
||||
"disabled_categories": list(config.get("default_disabled_categories", [])),
|
||||
},
|
||||
"bounds": {"xy": bounds, "max_z": max_z},
|
||||
"files": {"glb": f"{name}.glb", "blend": f"{name}.blend", "preview": f"{name}.png"},
|
||||
}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
try:
|
||||
import bpy # type: ignore
|
||||
except ImportError as exc:
|
||||
raise SystemExit("Run this script with Blender: blender -b --python build_blender_showcase.py -- --spec ...") from exc
|
||||
|
||||
spec_path = Path(args.spec)
|
||||
out_dir = Path(args.out_dir)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
spec = json.loads(spec_path.read_text(encoding="utf-8"))
|
||||
clear_scene(bpy)
|
||||
bounds, max_z = setup_scene(bpy, spec)
|
||||
|
||||
blend_path = out_dir / f"{args.name}.blend"
|
||||
glb_path = out_dir / f"{args.name}.glb"
|
||||
png_path = out_dir / f"{args.name}.png"
|
||||
metadata_path = out_dir / "model_metadata.json"
|
||||
bpy.ops.wm.save_as_mainfile(filepath=str(blend_path))
|
||||
# Draco compression keeps the Web GLB lightweight (typically -85~92% size).
|
||||
# The Web template registers a DRACOLoader to decode it; keep both in sync.
|
||||
bpy.ops.export_scene.gltf(
|
||||
filepath=str(glb_path),
|
||||
export_format="GLB",
|
||||
export_draco_mesh_compression_enable=True,
|
||||
export_draco_mesh_compression_level=6,
|
||||
export_draco_position_quantization=14,
|
||||
export_draco_normal_quantization=10,
|
||||
export_draco_generic_quantization=12,
|
||||
)
|
||||
if args.render:
|
||||
bpy.context.scene.render.filepath = str(png_path)
|
||||
bpy.ops.render.render(write_still=True)
|
||||
metadata_path.write_text(json.dumps(metadata(spec, bounds, max_z, args.name), ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(json.dumps({
|
||||
"blend": str(blend_path),
|
||||
"glb": str(glb_path),
|
||||
"png": str(png_path),
|
||||
"metadata": str(metadata_path),
|
||||
"objects": len(bpy.data.objects),
|
||||
}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
392
scripts/build_ifc_poc.py
Executable file
392
scripts/build_ifc_poc.py
Executable file
@@ -0,0 +1,392 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create a semantic IFC proof-of-concept from building_spec.json."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--spec", required=True, help="Path to building_spec.json")
|
||||
parser.add_argument("--out-ifc", required=True, help="Output IFC file")
|
||||
parser.add_argument("--out-report", help="Output validation report JSON")
|
||||
parser.add_argument("--out-notes", help="Output Markdown notes")
|
||||
parser.add_argument("--vendor-dir", default="work/vendor")
|
||||
parser.add_argument("--project-name", default="CAD to IFC POC")
|
||||
parser.add_argument("--max-walls-per-floor", type=int, default=0, help="0 means no limit")
|
||||
parser.add_argument("--max-columns-per-floor", type=int, default=0, help="0 means no limit")
|
||||
parser.add_argument("--max-beams-per-floor", type=int, default=0, help="0 means no limit")
|
||||
parser.add_argument("--validate-geometry", action="store_true")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def import_deps(vendor_dir: Path):
|
||||
if vendor_dir.exists():
|
||||
sys.path.insert(0, str(vendor_dir.resolve()))
|
||||
try:
|
||||
import numpy as np # type: ignore
|
||||
import ifcopenshell # type: ignore
|
||||
import ifcopenshell.api.aggregate # type: ignore
|
||||
import ifcopenshell.api.context # type: ignore
|
||||
import ifcopenshell.api.geometry # type: ignore
|
||||
import ifcopenshell.api.project # type: ignore
|
||||
import ifcopenshell.api.pset # type: ignore
|
||||
import ifcopenshell.api.root # type: ignore
|
||||
import ifcopenshell.api.spatial # type: ignore
|
||||
import ifcopenshell.api.unit # type: ignore
|
||||
except ImportError as exc:
|
||||
raise SystemExit(
|
||||
"Missing dependency: ifcopenshell and/or numpy. Install locally with:\n"
|
||||
f" python3 -m pip install --target {vendor_dir} ifcopenshell numpy"
|
||||
) from exc
|
||||
return np, ifcopenshell
|
||||
|
||||
|
||||
def placement_matrix(np, x=0.0, y=0.0, z=0.0, angle=0.0):
|
||||
c = math.cos(angle)
|
||||
s = math.sin(angle)
|
||||
return np.array(
|
||||
[
|
||||
[c, -s, 0.0, x],
|
||||
[s, c, 0.0, y],
|
||||
[0.0, 0.0, 1.0, z],
|
||||
[0.0, 0.0, 0.0, 1.0],
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def make_model(np, ifcopenshell, spec: dict, project_name: str):
|
||||
model = ifcopenshell.api.project.create_file(version="IFC4")
|
||||
project = ifcopenshell.api.root.create_entity(model, ifc_class="IfcProject", name=project_name)
|
||||
ifcopenshell.api.unit.assign_unit(model, length={"is_metric": True, "raw": "METERS"})
|
||||
model_context = ifcopenshell.api.context.add_context(model, context_type="Model")
|
||||
body_context = ifcopenshell.api.context.add_context(
|
||||
model,
|
||||
context_type="Model",
|
||||
context_identifier="Body",
|
||||
target_view="MODEL_VIEW",
|
||||
parent=model_context,
|
||||
)
|
||||
site = ifcopenshell.api.root.create_entity(model, ifc_class="IfcSite", name="CAD Site")
|
||||
building = ifcopenshell.api.root.create_entity(
|
||||
model,
|
||||
ifc_class="IfcBuilding",
|
||||
name=spec.get("project", {}).get("name", "CAD Building"),
|
||||
)
|
||||
ifcopenshell.api.aggregate.assign_object(model, products=[site], relating_object=project)
|
||||
ifcopenshell.api.aggregate.assign_object(model, products=[building], relating_object=site)
|
||||
for obj in (project, site, building):
|
||||
ifcopenshell.api.geometry.edit_object_placement(model, product=obj)
|
||||
|
||||
pset = ifcopenshell.api.pset.add_pset(model, product=project, name="CAD2BIM_Project")
|
||||
ifcopenshell.api.pset.edit_pset(
|
||||
model,
|
||||
pset=pset,
|
||||
properties={
|
||||
"Source": json.dumps(spec.get("source", {}), ensure_ascii=False)[:1200],
|
||||
"Method": "CAD/DXF -> building_spec.json -> IfcOpenShell",
|
||||
"Purpose": "BIM replacement feasibility proof",
|
||||
},
|
||||
)
|
||||
return model, body_context, building
|
||||
|
||||
|
||||
def add_storey(np, ifcopenshell, model, building, floor_key: str, floor: dict):
|
||||
storey = ifcopenshell.api.root.create_entity(
|
||||
model,
|
||||
ifc_class="IfcBuildingStorey",
|
||||
name=floor.get("name", floor_key),
|
||||
)
|
||||
storey.Elevation = float(floor.get("z", 0.0))
|
||||
ifcopenshell.api.aggregate.assign_object(model, products=[storey], relating_object=building)
|
||||
ifcopenshell.api.geometry.edit_object_placement(
|
||||
model,
|
||||
product=storey,
|
||||
matrix=placement_matrix(np, z=float(floor.get("z", 0.0))),
|
||||
)
|
||||
return storey
|
||||
|
||||
|
||||
def segment_length(segment: dict) -> float:
|
||||
sx, sy = segment["start"]
|
||||
ex, ey = segment["end"]
|
||||
return math.hypot(ex - sx, ey - sy)
|
||||
|
||||
|
||||
def add_cad_pset(ifcopenshell, model, element, floor_key: str, category: str, segment: dict | None = None, source_index: int | None = None):
|
||||
pset = ifcopenshell.api.pset.add_pset(model, product=element, name="CAD2BIM_Source")
|
||||
props = {
|
||||
"FloorKey": floor_key,
|
||||
"Category": category,
|
||||
"GeneratedFrom": "building_spec.json",
|
||||
}
|
||||
if segment:
|
||||
props.update(
|
||||
{
|
||||
"SourceLayer": segment.get("layer", ""),
|
||||
"SourceType": segment.get("source_type", ""),
|
||||
"SourceIndex": int(source_index or 0),
|
||||
"LengthMeters": round(segment_length(segment), 4),
|
||||
}
|
||||
)
|
||||
ifcopenshell.api.pset.edit_pset(model, pset=pset, properties=props)
|
||||
|
||||
|
||||
def add_slab(np, ifcopenshell, model, body_context, storey, floor_key: str, floor: dict):
|
||||
min_x, min_y, max_x, max_y = floor["bounds"]
|
||||
margin = float(floor.get("slab_margin", 1.2))
|
||||
thickness = float(floor.get("slab_thickness", 0.25))
|
||||
min_x -= margin
|
||||
min_y -= margin
|
||||
max_x += margin
|
||||
max_y += margin
|
||||
width = max_x - min_x
|
||||
depth = max_y - min_y
|
||||
polyline = [(0.0, 0.0), (width, 0.0), (width, depth), (0.0, depth), (0.0, 0.0)]
|
||||
slab = ifcopenshell.api.root.create_entity(
|
||||
model,
|
||||
ifc_class="IfcSlab",
|
||||
predefined_type="FLOOR",
|
||||
name=f"{floor_key} Slab",
|
||||
)
|
||||
representation = ifcopenshell.api.geometry.add_slab_representation(
|
||||
model,
|
||||
context=body_context,
|
||||
depth=thickness,
|
||||
direction_sense="POSITIVE",
|
||||
polyline=polyline,
|
||||
)
|
||||
ifcopenshell.api.geometry.assign_representation(model, product=slab, representation=representation)
|
||||
ifcopenshell.api.geometry.edit_object_placement(
|
||||
model,
|
||||
product=slab,
|
||||
matrix=placement_matrix(np, min_x, min_y, -thickness),
|
||||
)
|
||||
ifcopenshell.api.spatial.assign_container(model, products=[slab], relating_structure=storey)
|
||||
add_cad_pset(ifcopenshell, model, slab, floor_key, "slab")
|
||||
return slab
|
||||
|
||||
|
||||
def add_segment_element(ifcopenshell, model, body_context, storey, floor_key: str, floor: dict, category: str, segment: dict, source_index: int):
|
||||
length = segment_length(segment)
|
||||
if length < 0.05:
|
||||
return None
|
||||
floor_height = float(floor.get("height", 4.2))
|
||||
if category == "walls":
|
||||
ifc_class = "IfcWall"
|
||||
name = f"{floor_key} Wall {source_index:04d}"
|
||||
height = max(0.5, floor_height - 0.1)
|
||||
elevation = 0.0
|
||||
thickness = max(0.08, min(0.45, float(segment.get("width", 0.20))))
|
||||
elif category == "columns":
|
||||
ifc_class = "IfcColumn"
|
||||
name = f"{floor_key} Column {source_index:04d}"
|
||||
height = max(0.5, floor_height)
|
||||
elevation = 0.0
|
||||
thickness = max(0.10, min(0.60, float(segment.get("width", 0.30))))
|
||||
elif category == "beams":
|
||||
ifc_class = "IfcBeam"
|
||||
name = f"{floor_key} Beam {source_index:04d}"
|
||||
height = min(0.65, max(0.25, floor_height * 0.10))
|
||||
elevation = max(0.0, floor_height - height)
|
||||
thickness = max(0.08, min(0.60, float(segment.get("width", 0.25))))
|
||||
else:
|
||||
return None
|
||||
|
||||
sx, sy = segment["start"]
|
||||
ex, ey = segment["end"]
|
||||
element = ifcopenshell.api.root.create_entity(model, ifc_class=ifc_class, name=name)
|
||||
representation = ifcopenshell.api.geometry.create_2pt_wall(
|
||||
model,
|
||||
element=element,
|
||||
context=body_context,
|
||||
p1=(sx, sy),
|
||||
p2=(ex, ey),
|
||||
elevation=elevation,
|
||||
height=height,
|
||||
thickness=thickness,
|
||||
is_si=True,
|
||||
)
|
||||
ifcopenshell.api.geometry.assign_representation(model, product=element, representation=representation)
|
||||
ifcopenshell.api.spatial.assign_container(model, products=[element], relating_structure=storey)
|
||||
add_cad_pset(ifcopenshell, model, element, floor_key, category, segment=segment, source_index=source_index)
|
||||
return element
|
||||
|
||||
|
||||
def select_segments(segments: list[dict], limit: int) -> list[tuple[int, dict]]:
|
||||
if limit <= 0 or len(segments) <= limit:
|
||||
return list(enumerate(segments, start=1))
|
||||
step = len(segments) / limit
|
||||
result = []
|
||||
used: set[int] = set()
|
||||
for i in range(limit):
|
||||
idx = min(len(segments) - 1, int(i * step))
|
||||
if idx in used:
|
||||
continue
|
||||
used.add(idx)
|
||||
result.append((idx + 1, segments[idx]))
|
||||
return result
|
||||
|
||||
|
||||
def validate_ifc(ifcopenshell, path: Path, validate_geometry: bool) -> dict:
|
||||
model = ifcopenshell.open(str(path))
|
||||
counts = {
|
||||
"IfcProject": len(model.by_type("IfcProject")),
|
||||
"IfcSite": len(model.by_type("IfcSite")),
|
||||
"IfcBuilding": len(model.by_type("IfcBuilding")),
|
||||
"IfcBuildingStorey": len(model.by_type("IfcBuildingStorey")),
|
||||
"IfcSlab": len(model.by_type("IfcSlab")),
|
||||
"IfcWall": len(model.by_type("IfcWall")),
|
||||
"IfcColumn": len(model.by_type("IfcColumn")),
|
||||
"IfcBeam": len(model.by_type("IfcBeam")),
|
||||
"IfcRelContainedInSpatialStructure": len(model.by_type("IfcRelContainedInSpatialStructure")),
|
||||
"IfcPropertySet": len(model.by_type("IfcPropertySet")),
|
||||
"IfcExtrudedAreaSolid": len(model.by_type("IfcExtrudedAreaSolid")),
|
||||
}
|
||||
storeys = []
|
||||
for storey in model.by_type("IfcBuildingStorey"):
|
||||
contained = []
|
||||
for rel in storey.ContainsElements or []:
|
||||
contained.extend(rel.RelatedElements or [])
|
||||
storeys.append(
|
||||
{
|
||||
"name": storey.Name,
|
||||
"elevation": storey.Elevation,
|
||||
"contained_count": len(contained),
|
||||
"contained_types": {
|
||||
ifc_type: len([e for e in contained if e.is_a(ifc_type)])
|
||||
for ifc_type in ("IfcSlab", "IfcWall", "IfcColumn", "IfcBeam")
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
geometry_failures = []
|
||||
if validate_geometry:
|
||||
import ifcopenshell.geom as geom # type: ignore
|
||||
|
||||
settings = geom.settings()
|
||||
settings.set(settings.USE_WORLD_COORDS, True)
|
||||
for ifc_type in ("IfcSlab", "IfcWall", "IfcColumn", "IfcBeam"):
|
||||
for element in model.by_type(ifc_type):
|
||||
try:
|
||||
geom.create_shape(settings, element)
|
||||
except Exception as exc:
|
||||
geometry_failures.append(
|
||||
{"ifc_type": ifc_type, "name": element.Name, "error": str(exc)}
|
||||
)
|
||||
|
||||
return {
|
||||
"ifc_path": str(path),
|
||||
"schema": model.schema,
|
||||
"entity_counts": counts,
|
||||
"storeys": storeys,
|
||||
"geometry_validation": {
|
||||
"enabled": validate_geometry,
|
||||
"failure_count": len(geometry_failures),
|
||||
"failures": geometry_failures[:50],
|
||||
},
|
||||
"file_size_bytes": path.stat().st_size,
|
||||
}
|
||||
|
||||
|
||||
def make_notes(report: dict) -> str:
|
||||
counts = report["entity_counts"]
|
||||
lines = [
|
||||
"# IFC BIM Proof Notes",
|
||||
"",
|
||||
"This IFC is a feasibility proof generated from CAD-derived linework. It contains semantic IFC entities, but it is not automatically a production BIM replacement.",
|
||||
"",
|
||||
"## IFC Output",
|
||||
"",
|
||||
f"- File: `{report['ifc_path']}`",
|
||||
f"- Schema: `{report['schema']}`",
|
||||
f"- Size: `{report['file_size_bytes']}` bytes",
|
||||
"",
|
||||
"## Entity Counts",
|
||||
"",
|
||||
]
|
||||
for key in ("IfcBuildingStorey", "IfcSlab", "IfcWall", "IfcColumn", "IfcBeam", "IfcPropertySet", "IfcExtrudedAreaSolid"):
|
||||
lines.append(f"- `{key}`: {counts.get(key, 0)}")
|
||||
lines.extend(["", "## Storey Containment", ""])
|
||||
for storey in report["storeys"]:
|
||||
lines.append(f"- `{storey['name']}` at elevation `{storey['elevation']}`: {storey['contained_count']} elements")
|
||||
for key, value in storey["contained_types"].items():
|
||||
lines.append(f" - `{key}`: {value}")
|
||||
gv = report["geometry_validation"]
|
||||
lines.extend(
|
||||
[
|
||||
"",
|
||||
"## Geometry Validation",
|
||||
"",
|
||||
f"- Enabled: `{gv['enabled']}`",
|
||||
f"- Failures: `{gv['failure_count']}`",
|
||||
"",
|
||||
"## BIM Replacement Gaps",
|
||||
"",
|
||||
"- Add/validate openings, doors, windows, rooms/spaces, materials, quantities, classifications, georeferencing, discipline coordination, and object naming before calling this a BIM replacement.",
|
||||
]
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
np, ifcopenshell = import_deps(Path(args.vendor_dir))
|
||||
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
|
||||
model, body_context, building = make_model(np, ifcopenshell, spec, args.project_name)
|
||||
created = {"IfcSlab": 0, "IfcWall": 0, "IfcColumn": 0, "IfcBeam": 0}
|
||||
limits = {
|
||||
"walls": args.max_walls_per_floor,
|
||||
"columns": args.max_columns_per_floor,
|
||||
"beams": args.max_beams_per_floor,
|
||||
}
|
||||
source_counts = {}
|
||||
|
||||
for floor_key, floor in spec.get("floors", {}).items():
|
||||
storey = add_storey(np, ifcopenshell, model, building, floor_key, floor)
|
||||
add_slab(np, ifcopenshell, model, body_context, storey, floor_key, floor)
|
||||
created["IfcSlab"] += 1
|
||||
source_counts[floor_key] = {}
|
||||
for category in ("walls", "columns", "beams"):
|
||||
segments = floor.get("segments", {}).get(category, [])
|
||||
source_counts[floor_key][category] = len(segments)
|
||||
for source_index, segment in select_segments(segments, limits[category]):
|
||||
element = add_segment_element(
|
||||
ifcopenshell,
|
||||
model,
|
||||
body_context,
|
||||
storey,
|
||||
floor_key,
|
||||
floor,
|
||||
category,
|
||||
segment,
|
||||
source_index,
|
||||
)
|
||||
if element:
|
||||
created[element.is_a()] += 1
|
||||
|
||||
out_ifc = Path(args.out_ifc)
|
||||
out_ifc.parent.mkdir(parents=True, exist_ok=True)
|
||||
model.write(str(out_ifc))
|
||||
report = validate_ifc(ifcopenshell, out_ifc, args.validate_geometry)
|
||||
report["created_from_script"] = created
|
||||
report["source_segment_counts"] = source_counts
|
||||
report["limits_per_floor"] = limits
|
||||
|
||||
out_report = Path(args.out_report) if args.out_report else out_ifc.with_suffix(".report.json")
|
||||
out_notes = Path(args.out_notes) if args.out_notes else out_ifc.with_suffix(".notes.md")
|
||||
out_report.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_notes.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_report.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
out_notes.write_text(make_notes(report), encoding="utf-8")
|
||||
print(json.dumps({"ifc": str(out_ifc), "report": str(out_report), "notes": str(out_notes), "created": created}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
165
scripts/build_showcase_variants.py
Normal file
165
scripts/build_showcase_variants.py
Normal file
@@ -0,0 +1,165 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create overview/standard/detail showcase variants from a building spec.
|
||||
|
||||
The script writes filtered spec files for each variant and can optionally call
|
||||
Blender to produce GLBs. Its manifest is consumed by write_web_showcase.py.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import copy
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
VARIANTS = [
|
||||
{
|
||||
"key": "overview",
|
||||
"label": "总览轻量版",
|
||||
"description": "Walls, glazing, roofs, columns, beams, and generated slabs.",
|
||||
"categories": ["walls", "glazing", "roof", "columns", "beams"],
|
||||
},
|
||||
{
|
||||
"key": "standard",
|
||||
"label": "展示标准版",
|
||||
"description": "Default Web presentation model with railings and doors.",
|
||||
"categories": ["walls", "glazing", "roof", "columns", "beams", "railings", "doors"],
|
||||
},
|
||||
{
|
||||
"key": "detail",
|
||||
"label": "完整审图版",
|
||||
"description": "Full extracted linework for audit and review.",
|
||||
"categories": None,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def default_blender() -> str:
|
||||
return "/Applications/Blender.app/Contents/MacOS/Blender"
|
||||
|
||||
|
||||
def default_build_script() -> Path:
|
||||
return Path(__file__).resolve().with_name("build_blender_showcase.py")
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--spec", required=True, help="Source building_spec.json")
|
||||
parser.add_argument("--out-dir", required=True, help="Output folder for variant specs/manifest/artifacts")
|
||||
parser.add_argument("--name", default="cad_building_showcase", help="Project/model base name")
|
||||
parser.add_argument("--build", action="store_true", help="Run Blender for each generated variant")
|
||||
parser.add_argument("--blender", default=default_blender(), help="Blender executable path")
|
||||
parser.add_argument("--build-script", default=str(default_build_script()), help="build_blender_showcase.py path")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def filtered_spec(source: dict[str, Any], variant: dict[str, Any]) -> dict[str, Any]:
|
||||
spec = copy.deepcopy(source)
|
||||
keep = variant.get("categories")
|
||||
config = spec.setdefault("source", {}).setdefault("config", {})
|
||||
disabled = [key for key in config.get("default_disabled_categories", []) if key != "slab"]
|
||||
config["default_disabled_categories"] = disabled
|
||||
config["showcase_variant"] = variant["key"]
|
||||
config["showcase_variant_categories"] = keep or "all"
|
||||
|
||||
if keep is None:
|
||||
return spec
|
||||
keep_set = set(keep)
|
||||
for floor in spec.get("floors", {}).values():
|
||||
segments = floor.get("segments", {})
|
||||
for category in list(segments):
|
||||
if category not in keep_set:
|
||||
segments[category] = []
|
||||
return spec
|
||||
|
||||
|
||||
def write_variant_specs(spec: dict[str, Any], out_dir: Path) -> list[dict[str, Any]]:
|
||||
spec_dir = out_dir / "variant_specs"
|
||||
spec_dir.mkdir(parents=True, exist_ok=True)
|
||||
entries = []
|
||||
for variant in VARIANTS:
|
||||
key = variant["key"]
|
||||
variant_spec = filtered_spec(spec, variant)
|
||||
spec_path = spec_dir / f"{key}.json"
|
||||
spec_path.write_text(json.dumps(variant_spec, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
entries.append({**variant, "spec_path": spec_path})
|
||||
return entries
|
||||
|
||||
|
||||
def run_blender(entries: list[dict[str, Any]], out_dir: Path, blender: str, build_script: Path):
|
||||
if not build_script.exists():
|
||||
raise SystemExit(f"Blender build script not found: {build_script}")
|
||||
for entry in entries:
|
||||
key = entry["key"]
|
||||
variant_dir = out_dir / "variants" / key
|
||||
variant_dir.mkdir(parents=True, exist_ok=True)
|
||||
subprocess.run(
|
||||
[
|
||||
blender,
|
||||
"-b",
|
||||
"--python",
|
||||
str(build_script),
|
||||
"--",
|
||||
"--spec",
|
||||
str(entry["spec_path"]),
|
||||
"--out-dir",
|
||||
str(variant_dir),
|
||||
"--name",
|
||||
key,
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
|
||||
|
||||
def relative_to_out(path: Path, out_dir: Path) -> str:
|
||||
try:
|
||||
return str(path.relative_to(out_dir))
|
||||
except ValueError:
|
||||
return str(path)
|
||||
|
||||
|
||||
def write_manifest(entries: list[dict[str, Any]], out_dir: Path, name: str) -> Path:
|
||||
variants = []
|
||||
for entry in entries:
|
||||
key = entry["key"]
|
||||
variant_dir = out_dir / "variants" / key
|
||||
variants.append(
|
||||
{
|
||||
"key": key,
|
||||
"label": entry["label"],
|
||||
"description": entry["description"],
|
||||
"file": f"{key}.glb",
|
||||
"source_glb": relative_to_out(variant_dir / f"{key}.glb", out_dir),
|
||||
"metadata": relative_to_out(variant_dir / "model_metadata.json", out_dir),
|
||||
"spec": relative_to_out(entry["spec_path"], out_dir),
|
||||
}
|
||||
)
|
||||
manifest = {
|
||||
"name": name,
|
||||
"default_key": "standard",
|
||||
"variants": variants,
|
||||
}
|
||||
manifest_path = out_dir / "variants_manifest.json"
|
||||
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
return manifest_path
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
spec_path = Path(args.spec)
|
||||
out_dir = Path(args.out_dir)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
spec = json.loads(spec_path.read_text(encoding="utf-8"))
|
||||
entries = write_variant_specs(spec, out_dir)
|
||||
if args.build:
|
||||
run_blender(entries, out_dir, args.blender, Path(args.build_script))
|
||||
manifest_path = write_manifest(entries, out_dir, args.name)
|
||||
print(json.dumps({"manifest": str(manifest_path)}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
359
scripts/cad_dxf_report.py
Executable file
359
scripts/cad_dxf_report.py
Executable file
@@ -0,0 +1,359 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Batch convert/read CAD drawings and generate a DXF inventory report."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
CAD_SUFFIXES = {".dwg", ".dxf"}
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--input", required=True, help="Folder containing DWG/DXF files")
|
||||
parser.add_argument("--work", default="work/cad_showcase", help="Intermediate work folder")
|
||||
parser.add_argument("--output", default="outputs/cad_read_report", help="Output path stem or folder")
|
||||
parser.add_argument("--vendor-dir", default="work/vendor", help="Optional Python vendor dir containing ezdxf")
|
||||
parser.add_argument("--no-convert", action="store_true", help="Skip DWG conversion and only read existing DXF files")
|
||||
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 bbox, 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, bbox, recover
|
||||
|
||||
|
||||
def safe_name(path: Path, used: set[str]) -> str:
|
||||
stem = path.stem
|
||||
candidate = f"{stem}.dxf"
|
||||
index = 2
|
||||
while candidate in used:
|
||||
candidate = f"{stem}-{index}.dxf"
|
||||
index += 1
|
||||
used.add(candidate)
|
||||
return candidate
|
||||
|
||||
|
||||
def find_cad_files(input_dir: Path) -> list[Path]:
|
||||
return sorted(
|
||||
path for path in input_dir.rglob("*")
|
||||
if path.is_file() and path.suffix.lower() in CAD_SUFFIXES
|
||||
)
|
||||
|
||||
|
||||
def run_dwg2dxf(source: Path, dest: Path) -> dict:
|
||||
exe = shutil.which("dwg2dxf")
|
||||
if not exe:
|
||||
return {
|
||||
"source": str(source),
|
||||
"dest": str(dest),
|
||||
"status": "missing_dwg2dxf",
|
||||
"message": "Install LibreDWG or use ODA/QCAD/FreeCAD to convert DWG to DXF.",
|
||||
}
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
cmd = [exe, "-y", "-o", str(dest), str(source)]
|
||||
proc = subprocess.run(cmd, text=True, capture_output=True)
|
||||
return {
|
||||
"source": str(source),
|
||||
"dest": str(dest),
|
||||
"status": "ok" if proc.returncode == 0 and dest.exists() else "failed",
|
||||
"returncode": proc.returncode,
|
||||
"stdout": proc.stdout[-2000:],
|
||||
"stderr": proc.stderr[-2000:],
|
||||
}
|
||||
|
||||
|
||||
def sanitize_dxf_comments(source: Path, dest: Path) -> int:
|
||||
"""Remove DXF group code 999 comment pairs that can break brittle importers."""
|
||||
lines = source.read_text(errors="ignore").splitlines(keepends=True)
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
cleaned: list[str] = []
|
||||
removed = 0
|
||||
index = 0
|
||||
while index < len(lines):
|
||||
if lines[index].strip() == "999":
|
||||
removed += 1
|
||||
index += 2
|
||||
continue
|
||||
cleaned.append(lines[index])
|
||||
index += 1
|
||||
dest.write_text("".join(cleaned), encoding="utf-8", errors="ignore")
|
||||
return removed
|
||||
|
||||
|
||||
def bbox_tuple(box) -> dict | None:
|
||||
if not box or not box.has_data:
|
||||
return None
|
||||
extmin = box.extmin
|
||||
extmax = box.extmax
|
||||
return {
|
||||
"min": [round(extmin.x, 3), round(extmin.y, 3), round(extmin.z, 3)],
|
||||
"max": [round(extmax.x, 3), round(extmax.y, 3), round(extmax.z, 3)],
|
||||
"size": [
|
||||
round(extmax.x - extmin.x, 3),
|
||||
round(extmax.y - extmin.y, 3),
|
||||
round(extmax.z - extmin.z, 3),
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def guess_unit_scale(bbox_data: dict | None, insunits: int) -> dict:
|
||||
if insunits == 6:
|
||||
return {"source_units": "meters", "scale_to_meters": 1.0, "confidence": "header"}
|
||||
if insunits == 4:
|
||||
return {"source_units": "millimeters", "scale_to_meters": 0.001, "confidence": "header"}
|
||||
if not bbox_data:
|
||||
return {"source_units": "unknown", "scale_to_meters": 1.0, "confidence": "none"}
|
||||
sx, sy, _ = bbox_data.get("size", [0, 0, 0])
|
||||
largest = max(abs(sx), abs(sy))
|
||||
if largest > 1000:
|
||||
return {"source_units": "millimeters", "scale_to_meters": 0.001, "confidence": "bbox_heuristic"}
|
||||
return {"source_units": "meters_or_unknown", "scale_to_meters": 1.0, "confidence": "bbox_heuristic"}
|
||||
|
||||
|
||||
def read_doc(path: Path, ezdxf, recover):
|
||||
try:
|
||||
return ezdxf.readfile(path), []
|
||||
except ezdxf.DXFError:
|
||||
doc, auditor = recover.readfile(path)
|
||||
return doc, [str(error) for error in auditor.errors]
|
||||
|
||||
|
||||
# A floor-plan sheet whose real geometry lives in unbound XREFs exports as a
|
||||
# near-empty shell (a few dozen annotation entities). Modeling it silently
|
||||
# produces a missing floor, so it must be flagged before extraction.
|
||||
NEAR_EMPTY_ENTITY_THRESHOLD = 60
|
||||
BLK_XREF_FLAGS = 4 | 8 # BLK_XREF | BLK_XREF_OVERLAY
|
||||
|
||||
|
||||
def xref_definitions(doc) -> list[dict]:
|
||||
xrefs = []
|
||||
for block in doc.blocks:
|
||||
try:
|
||||
head = block.block
|
||||
flags = int(head.dxf.get("flags", 0))
|
||||
is_xref = bool(flags & BLK_XREF_FLAGS) or bool(getattr(block.block_record, "is_xref", False))
|
||||
if is_xref:
|
||||
xrefs.append(
|
||||
{
|
||||
"name": str(block.name),
|
||||
"path": str(head.dxf.get("xref_path", "") or ""),
|
||||
"overlay": bool(flags & 8),
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
continue
|
||||
return xrefs
|
||||
|
||||
|
||||
def file_warnings(item: dict) -> list[str]:
|
||||
warnings = []
|
||||
entities = item.get("modelspace_entities")
|
||||
xrefs = item.get("xref_definitions", [])
|
||||
if entities is None:
|
||||
return warnings
|
||||
if xrefs and entities < NEAR_EMPTY_ENTITY_THRESHOLD:
|
||||
names = ", ".join(x["name"] for x in xrefs[:4])
|
||||
warnings.append(
|
||||
f"likely_xref_shell: only {entities} entities but {len(xrefs)} XREF definition(s) ({names}). "
|
||||
"Real geometry lives in the external reference. Bind/insert the XREFs in CAD and re-export this DXF "
|
||||
"before modeling, otherwise this sheet contributes an empty floor."
|
||||
)
|
||||
elif entities < NEAR_EMPTY_ENTITY_THRESHOLD:
|
||||
warnings.append(
|
||||
f"near_empty: only {entities} entities (annotation shell?). "
|
||||
"Confirm with the user whether this sheet should contain geometry; if it is a plan, "
|
||||
"the source export is incomplete (unbound XREF or wrong layout)."
|
||||
)
|
||||
elif xrefs:
|
||||
names = ", ".join(x["name"] for x in xrefs[:4])
|
||||
warnings.append(
|
||||
f"has_xref_definitions: {len(xrefs)} XREF definition(s) ({names}). "
|
||||
"Entities inside unbound XREFs are NOT in modelspace; verify nothing essential is referenced externally."
|
||||
)
|
||||
return warnings
|
||||
|
||||
|
||||
def inspect_file(path: Path, ezdxf, bbox, recover) -> dict:
|
||||
messages: list[str] = []
|
||||
try:
|
||||
doc, recover_messages = read_doc(path, ezdxf, recover)
|
||||
messages.extend(recover_messages)
|
||||
msp = doc.modelspace()
|
||||
entities = list(msp)
|
||||
type_counts = Counter(entity.dxftype() for entity in entities)
|
||||
layer_counts = Counter(
|
||||
str(entity.dxf.layer)
|
||||
for entity in entities
|
||||
if entity.dxf.hasattr("layer")
|
||||
)
|
||||
try:
|
||||
geometry_bbox = bbox_tuple(bbox.extents(entities, fast=True))
|
||||
except Exception as exc: # bbox can fail on unsupported proxy geometry.
|
||||
geometry_bbox = None
|
||||
messages.append(f"bbox failed: {exc}")
|
||||
layers = []
|
||||
for layer in doc.layers:
|
||||
name = layer.dxf.name
|
||||
layers.append(
|
||||
{
|
||||
"name": name,
|
||||
"color": int(layer.dxf.color),
|
||||
"is_off": bool(layer.is_off()),
|
||||
"is_frozen": bool(layer.is_frozen()),
|
||||
"entity_count": layer_counts.get(name, 0),
|
||||
}
|
||||
)
|
||||
header = doc.header
|
||||
insunits = int(header.get("$INSUNITS", 0) or 0)
|
||||
result = {
|
||||
"file": path.name,
|
||||
"path": str(path),
|
||||
"status": "ok",
|
||||
"acadver": str(header.get("$ACADVER", "")),
|
||||
"insunits": insunits,
|
||||
"measurement": int(header.get("$MEASUREMENT", 0) or 0),
|
||||
"unit_guess": guess_unit_scale(geometry_bbox, insunits),
|
||||
"modelspace_entities": len(entities),
|
||||
"entity_types": dict(type_counts.most_common()),
|
||||
"top_layers": [
|
||||
{"name": name, "entity_count": count}
|
||||
for name, count in layer_counts.most_common(30)
|
||||
],
|
||||
"layer_count": len(layers),
|
||||
"layers": sorted(layers, key=lambda item: (-item["entity_count"], item["name"])),
|
||||
"bbox": geometry_bbox,
|
||||
"messages": messages,
|
||||
"xref_definitions": xref_definitions(doc),
|
||||
}
|
||||
result["warnings"] = file_warnings(result)
|
||||
return result
|
||||
except Exception as exc:
|
||||
return {"file": path.name, "path": str(path), "status": "failed", "messages": [str(exc)]}
|
||||
|
||||
|
||||
def markdown_report(results: list[dict], conversions: list[dict], input_dir: Path) -> str:
|
||||
lines = [
|
||||
"# CAD Read Report",
|
||||
"",
|
||||
f"Input: `{input_dir}`",
|
||||
"",
|
||||
]
|
||||
all_warnings = [(item["file"], warning) for item in results for warning in item.get("warnings", [])]
|
||||
if all_warnings:
|
||||
lines.extend(["## Warnings (resolve before modeling)", ""])
|
||||
for file_name, warning in all_warnings:
|
||||
lines.append(f"- `{file_name}`: {warning}")
|
||||
lines.append("")
|
||||
lines.extend([
|
||||
"## Files",
|
||||
"",
|
||||
"| File | Status | Entities | Layers | Size X | Size Y | Unit Guess | Main Types |",
|
||||
"| --- | --- | ---: | ---: | ---: | ---: | --- | --- |",
|
||||
])
|
||||
for item in results:
|
||||
bbox_data = item.get("bbox") or {}
|
||||
size = bbox_data.get("size", ["", "", ""])
|
||||
unit = item.get("unit_guess", {})
|
||||
unit_text = f"{unit.get('source_units', '')} x{unit.get('scale_to_meters', '')}"
|
||||
types = ", ".join(f"{k}:{v}" for k, v in list(item.get("entity_types", {}).items())[:5])
|
||||
lines.append(
|
||||
f"| {item['file']} | {item.get('status', '')} | {item.get('modelspace_entities', '')} | "
|
||||
f"{item.get('layer_count', '')} | {size[0]} | {size[1]} | {unit_text} | {types} |"
|
||||
)
|
||||
if conversions:
|
||||
lines.extend(["", "## DWG Conversion", ""])
|
||||
for conv in conversions:
|
||||
lines.append(f"- `{Path(conv['source']).name}` -> `{Path(conv['dest']).name}`: {conv['status']}")
|
||||
lines.extend(["", "## Top Layers", ""])
|
||||
for item in results:
|
||||
lines.append(f"### {item['file']}")
|
||||
for layer in item.get("top_layers", [])[:12]:
|
||||
lines.append(f"- `{layer['name']}`: {layer['entity_count']}")
|
||||
for message in item.get("messages", [])[:8]:
|
||||
lines.append(f"- message: `{message}`")
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def output_paths(output: Path) -> tuple[Path, Path]:
|
||||
if output.suffix:
|
||||
return output.with_suffix(".json"), output.with_suffix(".md")
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
return output / "cad_read_report.json", output / "cad_read_report.md"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
input_dir = Path(args.input)
|
||||
work_dir = Path(args.work)
|
||||
raw_dir = work_dir / "dxf_raw"
|
||||
clean_dir = work_dir / "dxf_sanitized"
|
||||
vendor_dir = Path(args.vendor_dir)
|
||||
ezdxf, bbox, recover = import_ezdxf(vendor_dir)
|
||||
|
||||
if not input_dir.exists():
|
||||
raise SystemExit(f"Input folder not found: {input_dir}")
|
||||
|
||||
raw_dir.mkdir(parents=True, exist_ok=True)
|
||||
clean_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
used_names: set[str] = set()
|
||||
conversions: list[dict] = []
|
||||
raw_dxfs: list[Path] = []
|
||||
for source in find_cad_files(input_dir):
|
||||
dest = raw_dir / safe_name(source, used_names)
|
||||
if source.suffix.lower() == ".dwg":
|
||||
if args.no_convert:
|
||||
continue
|
||||
conversion = run_dwg2dxf(source, dest)
|
||||
conversions.append(conversion)
|
||||
if conversion["status"] == "ok":
|
||||
raw_dxfs.append(dest)
|
||||
else:
|
||||
shutil.copy2(source, dest)
|
||||
raw_dxfs.append(dest)
|
||||
|
||||
sanitized: list[Path] = []
|
||||
for raw in raw_dxfs:
|
||||
dest = clean_dir / raw.name
|
||||
removed = sanitize_dxf_comments(raw, dest)
|
||||
sanitized.append(dest)
|
||||
if removed:
|
||||
conversions.append({"source": str(raw), "dest": str(dest), "status": f"sanitized_{removed}_comments"})
|
||||
|
||||
results = [inspect_file(path, ezdxf, bbox, recover) for path in sorted(sanitized)]
|
||||
json_path, md_path = output_paths(Path(args.output))
|
||||
json_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
md_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
payload = {
|
||||
"input": str(input_dir),
|
||||
"work": str(work_dir),
|
||||
"dxf_sanitized": str(clean_dir),
|
||||
"conversions": conversions,
|
||||
"files": results,
|
||||
}
|
||||
json_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
md_path.write_text(markdown_report(results, conversions, input_dir), encoding="utf-8")
|
||||
print(json.dumps({"json": str(json_path), "markdown": str(md_path), "files": len(results)}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
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())
|
||||
196
scripts/draw_coverage_overlay.py
Executable file
196
scripts/draw_coverage_overlay.py
Executable 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())
|
||||
95
scripts/extract_ifc_meshes.py
Executable file
95
scripts/extract_ifc_meshes.py
Executable file
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extract IFC product geometry into a compact JSON mesh bundle for rendering."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
DEFAULT_TYPES = ("IfcSlab", "IfcWall", "IfcColumn", "IfcBeam")
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--ifc", required=True, help="Source IFC")
|
||||
parser.add_argument("--out", required=True, help="Output mesh JSON")
|
||||
parser.add_argument("--vendor-dir", default="work/vendor")
|
||||
parser.add_argument("--types", nargs="*", default=list(DEFAULT_TYPES))
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def import_ifcopenshell(vendor_dir: Path):
|
||||
if vendor_dir.exists():
|
||||
sys.path.insert(0, str(vendor_dir.resolve()))
|
||||
try:
|
||||
import ifcopenshell # type: ignore
|
||||
import ifcopenshell.geom as geom # type: ignore
|
||||
except ImportError as exc:
|
||||
raise SystemExit(
|
||||
"Missing dependency: ifcopenshell. Install locally with:\n"
|
||||
f" python3 -m pip install --target {vendor_dir} ifcopenshell"
|
||||
) from exc
|
||||
return ifcopenshell, geom
|
||||
|
||||
|
||||
def append_shape(group: dict, shape):
|
||||
verts = list(shape.geometry.verts)
|
||||
faces = list(shape.geometry.faces)
|
||||
offset = len(group["vertices"])
|
||||
for index in range(0, len(verts), 3):
|
||||
group["vertices"].append(
|
||||
[
|
||||
round(float(verts[index]), 5),
|
||||
round(float(verts[index + 1]), 5),
|
||||
round(float(verts[index + 2]), 5),
|
||||
]
|
||||
)
|
||||
for index in range(0, len(faces), 3):
|
||||
group["faces"].append([faces[index] + offset, faces[index + 1] + offset, faces[index + 2] + offset])
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
ifcopenshell, geom = import_ifcopenshell(Path(args.vendor_dir))
|
||||
model = ifcopenshell.open(str(Path(args.ifc)))
|
||||
settings = geom.settings()
|
||||
settings.set(settings.USE_WORLD_COORDS, True)
|
||||
groups = {
|
||||
ifc_type: {"ifc_type": ifc_type, "vertices": [], "faces": [], "elements": 0}
|
||||
for ifc_type in args.types
|
||||
}
|
||||
failures = []
|
||||
for ifc_type in args.types:
|
||||
for element in model.by_type(ifc_type):
|
||||
try:
|
||||
shape = geom.create_shape(settings, element)
|
||||
append_shape(groups[ifc_type], shape)
|
||||
groups[ifc_type]["elements"] += 1
|
||||
except Exception as exc:
|
||||
failures.append({"ifc_type": ifc_type, "name": element.Name, "error": str(exc)})
|
||||
payload = {
|
||||
"source_ifc": str(args.ifc),
|
||||
"schema": model.schema,
|
||||
"groups": list(groups.values()),
|
||||
"failures": failures,
|
||||
"summary": {
|
||||
ifc_type: {
|
||||
"elements": groups[ifc_type]["elements"],
|
||||
"vertices": len(groups[ifc_type]["vertices"]),
|
||||
"faces": len(groups[ifc_type]["faces"]),
|
||||
}
|
||||
for ifc_type in args.types
|
||||
},
|
||||
}
|
||||
out = Path(args.out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
|
||||
print(json.dumps({"out": str(out), "summary": payload["summary"], "failures": len(failures)}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
179
scripts/render_ifc_meshes_blender.py
Executable file
179
scripts/render_ifc_meshes_blender.py
Executable file
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Render IFC mesh JSON with Blender and export a GLB/PNG preview."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
COLORS = {
|
||||
"IfcSlab": (0.72, 0.74, 0.70, 0.34),
|
||||
"IfcWall": (0.78, 0.76, 0.68, 1.0),
|
||||
"IfcColumn": (1.00, 0.46, 0.10, 1.0),
|
||||
"IfcBeam": (0.05, 0.28, 0.82, 1.0),
|
||||
}
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
argv = sys.argv
|
||||
if "--" in argv:
|
||||
argv = argv[argv.index("--") + 1 :]
|
||||
else:
|
||||
argv = []
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--meshes", required=True, help="Mesh JSON from extract_ifc_meshes.py")
|
||||
parser.add_argument("--out-dir", required=True)
|
||||
parser.add_argument("--name", default="ifc_render")
|
||||
return parser.parse_args(argv)
|
||||
|
||||
|
||||
def clear_scene(bpy):
|
||||
bpy.ops.object.select_all(action="SELECT")
|
||||
bpy.ops.object.delete()
|
||||
for datablocks in (bpy.data.meshes, bpy.data.materials, bpy.data.lights, bpy.data.cameras, bpy.data.curves):
|
||||
for item in list(datablocks):
|
||||
if item.users == 0:
|
||||
datablocks.remove(item)
|
||||
|
||||
|
||||
def make_material(bpy, name: str, color: tuple[float, float, float, float]):
|
||||
mat = bpy.data.materials.new(name)
|
||||
mat.diffuse_color = color
|
||||
mat.use_nodes = True
|
||||
bsdf = mat.node_tree.nodes.get("Principled BSDF")
|
||||
if bsdf:
|
||||
bsdf.inputs["Base Color"].default_value = color
|
||||
bsdf.inputs["Roughness"].default_value = 0.62
|
||||
if "Alpha" in bsdf.inputs:
|
||||
bsdf.inputs["Alpha"].default_value = color[3]
|
||||
if color[3] < 1.0:
|
||||
mat.blend_method = "BLEND"
|
||||
mat.show_transparent_back = True
|
||||
return mat
|
||||
|
||||
|
||||
def create_mesh_object(bpy, group: dict, material):
|
||||
mesh = bpy.data.meshes.new(group["ifc_type"] + "Mesh")
|
||||
mesh.from_pydata(group["vertices"], [], group["faces"])
|
||||
mesh.update()
|
||||
obj = bpy.data.objects.new(group["ifc_type"], mesh)
|
||||
bpy.context.collection.objects.link(obj)
|
||||
obj.data.materials.append(material)
|
||||
obj["IFC_TYPE"] = group["ifc_type"]
|
||||
obj["IFC_ELEMENT_COUNT"] = group["elements"]
|
||||
return obj
|
||||
|
||||
|
||||
def scene_bounds(objects, Vector):
|
||||
mins = [float("inf"), float("inf"), float("inf")]
|
||||
maxs = [float("-inf"), float("-inf"), float("-inf")]
|
||||
for obj in objects:
|
||||
for corner in obj.bound_box:
|
||||
point = obj.matrix_world @ Vector(corner)
|
||||
for index in range(3):
|
||||
mins[index] = min(mins[index], point[index])
|
||||
maxs[index] = max(maxs[index], point[index])
|
||||
if not objects:
|
||||
return [0, 0, 0], [1, 1, 1]
|
||||
return mins, maxs
|
||||
|
||||
|
||||
def add_label(bpy, text: str, location: tuple[float, float, float], size: float, material):
|
||||
curve = bpy.data.curves.new(text + "Curve", "FONT")
|
||||
curve.body = text
|
||||
curve.size = size
|
||||
curve.align_x = "LEFT"
|
||||
curve.align_y = "CENTER"
|
||||
obj = bpy.data.objects.new(text, curve)
|
||||
obj.location = location
|
||||
bpy.context.collection.objects.link(obj)
|
||||
obj.data.materials.append(material)
|
||||
|
||||
|
||||
def setup_render(bpy, objects: list):
|
||||
from mathutils import Vector
|
||||
|
||||
mins, maxs = scene_bounds(objects, Vector)
|
||||
center = [(mins[i] + maxs[i]) / 2.0 for i in range(3)]
|
||||
size = [max(maxs[i] - mins[i], 1.0) for i in range(3)]
|
||||
|
||||
bpy.context.scene.unit_settings.system = "METRIC"
|
||||
try:
|
||||
bpy.context.scene.render.engine = "BLENDER_EEVEE"
|
||||
except TypeError:
|
||||
pass
|
||||
bpy.context.scene.view_settings.view_transform = "Standard"
|
||||
bpy.context.scene.view_settings.look = "Medium High Contrast"
|
||||
if bpy.context.scene.world:
|
||||
bpy.context.scene.world.color = (0.78, 0.82, 0.86)
|
||||
bpy.context.scene.render.resolution_x = 1800
|
||||
bpy.context.scene.render.resolution_y = 1200
|
||||
|
||||
bpy.ops.object.light_add(type="SUN", location=(0, 0, maxs[2] + 40))
|
||||
sun = bpy.context.object
|
||||
sun.name = "Sun"
|
||||
sun.data.energy = 2.4
|
||||
sun.rotation_euler = (math.radians(48), 0, math.radians(35))
|
||||
|
||||
bpy.ops.object.light_add(type="AREA", location=(center[0] - 30, center[1] - 40, maxs[2] + 45))
|
||||
area = bpy.context.object
|
||||
area.name = "Softbox"
|
||||
area.data.energy = 700
|
||||
area.data.size = max(size[0], size[1]) * 0.55
|
||||
|
||||
distance = max(size) * 0.95
|
||||
bpy.ops.object.camera_add(location=(center[0] - distance, center[1] - distance * 0.95, maxs[2] + distance * 0.70))
|
||||
camera = bpy.context.object
|
||||
direction = Vector((center[0], center[1], center[2])) - camera.location
|
||||
camera.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler()
|
||||
camera.data.type = "ORTHO"
|
||||
camera.data.ortho_scale = max(size[0], size[1]) * 1.10
|
||||
bpy.context.scene.camera = camera
|
||||
|
||||
text_mat = make_material(bpy, "label black", (0.02, 0.02, 0.018, 1.0))
|
||||
add_label(
|
||||
bpy,
|
||||
"IFC render: IfcWall / IfcColumn / IfcBeam / IfcSlab",
|
||||
(mins[0], maxs[1] + 3.0, maxs[2] + 0.4),
|
||||
2.2,
|
||||
text_mat,
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
try:
|
||||
import bpy # type: ignore
|
||||
except ImportError as exc:
|
||||
raise SystemExit("Run this script with Blender: blender -b --python render_ifc_meshes_blender.py -- --meshes ...") from exc
|
||||
payload = json.loads(Path(args.meshes).read_text(encoding="utf-8"))
|
||||
out_dir = Path(args.out_dir)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
clear_scene(bpy)
|
||||
materials = {
|
||||
ifc_type: make_material(bpy, ifc_type + " material", COLORS.get(ifc_type, (0.8, 0.8, 0.8, 1.0)))
|
||||
for ifc_type in [group["ifc_type"] for group in payload["groups"]]
|
||||
}
|
||||
objects = [
|
||||
create_mesh_object(bpy, group, materials[group["ifc_type"]])
|
||||
for group in payload["groups"]
|
||||
if group["vertices"] and group["faces"]
|
||||
]
|
||||
setup_render(bpy, objects)
|
||||
blend_path = out_dir / f"{args.name}.blend"
|
||||
glb_path = out_dir / f"{args.name}.glb"
|
||||
png_path = out_dir / f"{args.name}.png"
|
||||
bpy.ops.wm.save_as_mainfile(filepath=str(blend_path))
|
||||
bpy.ops.export_scene.gltf(filepath=str(glb_path), export_format="GLB")
|
||||
bpy.context.scene.render.filepath = str(png_path)
|
||||
bpy.ops.render.render(write_still=True)
|
||||
print(json.dumps({"blend": str(blend_path), "glb": str(glb_path), "png": str(png_path), "mesh_objects": [obj.name for obj in objects]}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
399
scripts/spec_to_glb.py
Normal file
399
scripts/spec_to_glb.py
Normal file
@@ -0,0 +1,399 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Blender-free building_spec.json -> GLB exporter.
|
||||
|
||||
Replicates the geometry rules of the skill's build_blender_showcase.py
|
||||
(segment prisms, z-windows, footprint slabs, generated roofs, floor__category
|
||||
naming) using trimesh, so the lightweight Web showcase can be produced without
|
||||
a Blender install. The Web viewer recolours meshes by category from
|
||||
model_metadata.json, so only correct node names + geometry are required.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, json, math
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
import trimesh
|
||||
from shapely.geometry import Polygon
|
||||
|
||||
CATEGORY_DRAW_ORDER = ("grid","floor_lines","detail_lines","doors","railings",
|
||||
"roof","glazing","walls","columns","beams")
|
||||
|
||||
def is_roof_floor(floor_key, floor):
|
||||
t = f"{floor_key} {floor.get('name','')}".upper()
|
||||
return any(k in t for k in ("RF","ROOF","屋顶","屋面"))
|
||||
|
||||
def z_window(category, z, height, floor_key, floor):
|
||||
if category in {"walls","columns","glazing"}:
|
||||
if category == "columns" and is_roof_floor(floor_key, floor):
|
||||
return z, z + min(height, 1.15)
|
||||
return z, z + height
|
||||
if category == "beams": return z + max(height-0.55, 0.1), z + height
|
||||
if category == "roof": return z - 0.35, z + 0.08
|
||||
if category == "railings":return z + 0.05, z + min(1.20, height)
|
||||
if category == "doors": return z + 0.02, z + min(2.30, height)
|
||||
if category in {"floor_lines","detail_lines"}: return z + 0.03, z + 0.09
|
||||
if category == "grid": return z + 0.01, z + 0.04
|
||||
return z + 0.03, z + min(0.12, height)
|
||||
|
||||
# 12-triangle box from 8 corner verts
|
||||
_BOX_TRIS = np.array([
|
||||
[0,1,2],[0,2,3], # bottom
|
||||
[4,6,5],[4,7,6], # top
|
||||
[0,4,5],[0,5,1],
|
||||
[1,5,6],[1,6,2],
|
||||
[2,6,7],[2,7,3],
|
||||
[3,7,4],[3,4,0],
|
||||
], dtype=np.int64)
|
||||
|
||||
def segment_box_verts(seg, z0, z1):
|
||||
x1,y1 = seg["start"]; x2,y2 = seg["end"]
|
||||
dx,dy = x2-x1, y2-y1
|
||||
L = math.hypot(dx,dy)
|
||||
if L <= 1e-7: return None
|
||||
hw = max(float(seg.get("width",0.1)), 0.005)/2.0
|
||||
nx,ny = -dy/L*hw, dx/L*hw
|
||||
z0 = float(seg.get("_z0", z0)); z1 = float(seg.get("_z1", z1))
|
||||
return np.array([
|
||||
(x1+nx,y1+ny,z0),(x2+nx,y2+ny,z0),(x2-nx,y2-ny,z0),(x1-nx,y1-ny,z0),
|
||||
(x1+nx,y1+ny,z1),(x2+nx,y2+ny,z1),(x2-nx,y2-ny,z1),(x1-nx,y1-ny,z1),
|
||||
], dtype=np.float64)
|
||||
|
||||
def mesh_from_segments(segments, z0, z1):
|
||||
V=[]; F=[]; base=0
|
||||
for seg in segments:
|
||||
v = segment_box_verts(seg, z0, z1)
|
||||
if v is None: continue
|
||||
V.append(v); F.append(_BOX_TRIS+base); base+=8
|
||||
if not V: return None
|
||||
return trimesh.Trimesh(vertices=np.vstack(V), faces=np.vstack(F), process=False)
|
||||
|
||||
def mesh_from_polygons(polygons, z0, z1):
|
||||
parts=[]
|
||||
for coords in polygons:
|
||||
pts=[(float(x),float(y)) for x,y in coords]
|
||||
if len(pts)>=2 and pts[0]==pts[-1]: pts=pts[:-1]
|
||||
if len(pts)<3: continue
|
||||
try:
|
||||
poly=Polygon(pts)
|
||||
if not poly.is_valid: poly=poly.buffer(0)
|
||||
if poly.is_empty or poly.area<=0: continue
|
||||
m=trimesh.creation.extrude_polygon(poly, height=max(z1-z0,1e-4))
|
||||
m.apply_translation((0,0,z0))
|
||||
parts.append(m)
|
||||
except Exception:
|
||||
continue
|
||||
if not parts: return None
|
||||
return trimesh.util.concatenate(parts) if len(parts)>1 else parts[0]
|
||||
|
||||
def hex_rgba(hex_color, alpha):
|
||||
h=hex_color.lstrip("#")
|
||||
return [int(h[0:2],16)/255, int(h[2:4],16)/255, int(h[4:6],16)/255, alpha]
|
||||
|
||||
ALPHA={"slab":0.72,"roof":0.95,"glazing":0.38,"floor_lines":0.95,"grid":0.95,
|
||||
"detail_lines":0.82,"doors":0.90}
|
||||
|
||||
def merge_collinear(segs, angle_tol_deg=6.0, offset_tol=0.30, gap_tol=3.6):
|
||||
"""Merge collinear, near-touching segments into continuous spans (for glazing bands)."""
|
||||
groups={}
|
||||
keep=[]
|
||||
for s in segs:
|
||||
a=s["start"]; b=s["end"]
|
||||
dx=b[0]-a[0]; dy=b[1]-a[1]; L=math.hypot(dx,dy)
|
||||
if L<1e-6:
|
||||
keep.append(s); continue
|
||||
ang=math.atan2(dy,dx)%math.pi
|
||||
akey=round(ang/math.radians(angle_tol_deg))
|
||||
nx,ny=-dy/L,dx/L
|
||||
off=a[0]*nx+a[1]*ny
|
||||
okey=round(off/offset_tol)
|
||||
groups.setdefault((akey,okey),[]).append((a,b,nx,ny,float(s.get("width",0.06)),s.get("layer",""),math.radians(angle_tol_deg)*akey))
|
||||
out=list(keep)
|
||||
for (akey,okey),items in groups.items():
|
||||
a0,b0,nx,ny,w,layer,_=items[0]
|
||||
dirx,diry=-ny,nx
|
||||
offv=a0[0]*nx+a0[1]*ny
|
||||
intervals=[]
|
||||
for (a,b,*_r) 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:
|
||||
p0=(offv*nx+lo*dirx, offv*ny+lo*diry)
|
||||
p1=(offv*nx+hi*dirx, offv*ny+hi*diry)
|
||||
out.append({"start":[p0[0],p0[1]],"end":[p1[0],p1[1]],"width":w,"layer":layer,"source_type":"merged"})
|
||||
return out
|
||||
|
||||
def _shapely_union(polys):
|
||||
from shapely.geometry import Polygon
|
||||
from shapely.ops import unary_union
|
||||
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=2.0):
|
||||
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([[float(x),float(y)] for x,y in g.exterior.coords])
|
||||
return res
|
||||
|
||||
def setback_cap_polys(spec, fk, fl, own_polys):
|
||||
"""Cap ring = own footprint minus the footprint of the floor directly above (same group)."""
|
||||
z=float(fl["z"]); h=float(fl.get("height",4.2)); ftop=z+h
|
||||
grp=floor_group(fk)
|
||||
upper=[]
|
||||
for ok,ot in spec["floors"].items():
|
||||
if ok==fk or 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 not upper:
|
||||
# top of a basement stack -> cap the WHOLE footprint (ground / podium deck over parking)
|
||||
if grp=="BASE" and own_u is not None:
|
||||
return _shapely_to_polys(own_u.buffer(0.5), min_area=3.0)
|
||||
return [] # above-ground top handled by generated roof caps
|
||||
up_u=_shapely_union(upper)
|
||||
if own_u is None or up_u is None: return []
|
||||
try:
|
||||
# buffer own footprint outward so the cap also covers perimeter colonnade columns
|
||||
ring=own_u.buffer(1.3).difference(up_u.buffer(0.05))
|
||||
except Exception:
|
||||
return []
|
||||
return _shapely_to_polys(ring, min_area=3.0)
|
||||
|
||||
def floor_group(fk):
|
||||
if fk.startswith("AUX_"): return "AUX"
|
||||
if fk in {"B1","B1M"}: return "BASE"
|
||||
return "MAIN"
|
||||
|
||||
def _pt_seg_dist(p, a, b):
|
||||
px,py=p; ax,ay=a; bx,by=b
|
||||
dx,dy=bx-ax,by-ay
|
||||
L=dx*dx+dy*dy
|
||||
if L<=1e-12: return math.hypot(px-ax,py-ay)
|
||||
t=max(0.0,min(1.0,((px-ax)*dx+(py-ay)*dy)/L))
|
||||
return math.hypot(px-(ax+t*dx), py-(ay+t*dy))
|
||||
|
||||
def _pt_in_poly(p, poly):
|
||||
x,y=p; inside=False; n=len(poly)
|
||||
if n<3: return False
|
||||
j=n-1
|
||||
for i in range(n):
|
||||
xi,yi=float(poly[i][0]),float(poly[i][1])
|
||||
xj,yj=float(poly[j][0]),float(poly[j][1])
|
||||
if (yi>y)!=(yj>y):
|
||||
xat=(xj-xi)*(y-yi)/((yj-yi) or 1e-12)+xi
|
||||
if x<xat: inside=not inside
|
||||
j=i
|
||||
return inside
|
||||
|
||||
def _near_polys(p, polys, margin):
|
||||
for poly in polys:
|
||||
if _pt_in_poly(p, poly): return True
|
||||
pts=[(float(x),float(y)) for x,y in poly]
|
||||
for i in range(len(pts)):
|
||||
if _pt_seg_dist(p, pts[i], pts[(i+1)%len(pts)])<=margin: return True
|
||||
return False
|
||||
|
||||
def column_supported(pt, fk, fl, spec, cfg, roofs):
|
||||
ftop=float(fl["z"])+float(fl.get("height",4.2))
|
||||
sd=float(cfg.get("column_support_distance",1.1))
|
||||
ztol=float(cfg.get("column_support_z_tolerance",0.65))
|
||||
scats=set(cfg.get("column_support_categories",["walls","glazing","columns","beams"]))
|
||||
req_plate=bool(cfg.get("column_support_requires_upper_plate",True))
|
||||
plate_only=bool(cfg.get("column_support_allow_plate_only",False))
|
||||
grp=floor_group(fk)
|
||||
for ok,ot in spec["floors"].items():
|
||||
if floor_group(ok)!=grp: continue
|
||||
oz=float(ot.get("z",0.0))
|
||||
if not (ftop-0.05<=oz<=ftop+ztol): continue
|
||||
ups=ot.get("footprint",{}).get("polygons",[])
|
||||
if ups:
|
||||
has=_near_polys(pt,ups,sd)
|
||||
if has and plate_only: return True
|
||||
if req_plate and not has: continue
|
||||
for c in scats:
|
||||
for s in ot.get("segments",{}).get(c,[]):
|
||||
if _pt_seg_dist(pt,tuple(s["start"]),tuple(s["end"]))<=sd: return True
|
||||
rtol=float(cfg.get("column_roof_support_z_tolerance",0.65))
|
||||
for r in roofs:
|
||||
if floor_group(str(r["floor_key"]))!=grp: continue
|
||||
if abs(float(r["z"])-ftop)>rtol: continue
|
||||
if r["polygons"] and _near_polys(pt,r["polygons"],sd): return True
|
||||
return False
|
||||
|
||||
def adjust_columns(segs, fk, fl, spec, cfg, roofs):
|
||||
if not cfg.get("shorten_unsupported_columns",False): return segs
|
||||
flt={str(k) for k in cfg.get("shorten_unsupported_columns_floor_keys",[])}
|
||||
if flt and fk not in flt: return segs
|
||||
z=float(fl["z"]); h=float(fl.get("height",4.2))
|
||||
sh=min(float(cfg.get("unsupported_column_height",1.2)),h)
|
||||
out=[]
|
||||
for s in segs:
|
||||
a=s["start"]; b=s["end"]
|
||||
mid=((a[0]+b[0])/2.0,(a[1]+b[1])/2.0)
|
||||
it=dict(s)
|
||||
if not column_supported(mid,fk,fl,spec,cfg,roofs):
|
||||
it["_z0"]=z; it["_z1"]=z+sh
|
||||
out.append(it)
|
||||
return out
|
||||
|
||||
def roof_specs(spec):
|
||||
cfg=spec.get("source",{}).get("config",{})
|
||||
floors=spec.get("floors",{})
|
||||
out=[]
|
||||
for r in cfg.get("roof_specs",[]):
|
||||
fk=str(r.get("floor_key"))
|
||||
fl=floors.get(fk)
|
||||
if not fl: continue
|
||||
ffrom=list(r.get("footprint_from",[fk]))
|
||||
polys=[]
|
||||
for k in ffrom:
|
||||
polys.extend(floors.get(k,{}).get("footprint",{}).get("polygons",[]))
|
||||
out.append({"floor_key":fk,"z":float(r.get("z",fl.get("z",0.0))),
|
||||
"thickness":float(r.get("thickness",0.35)),"polygons":polys,
|
||||
"bounds":r.get("bounds") or fl.get("bounds")})
|
||||
return out
|
||||
|
||||
def build_scene(spec, categories):
|
||||
cfg=spec.get("source",{}).get("config",{})
|
||||
use_fp_slab=cfg.get("use_footprint_slabs",False)
|
||||
slab_th=float(cfg.get("slab_thickness",0.25))
|
||||
cat_defs=spec.get("categories",{})
|
||||
scene=trimesh.Scene()
|
||||
mats={}
|
||||
def material(cat):
|
||||
if cat in mats: return mats[cat]
|
||||
color=cat_defs.get(cat,{}).get("color","#cccccc")
|
||||
m=trimesh.visual.material.PBRMaterial(
|
||||
name=cat, baseColorFactor=hex_rgba(color, ALPHA.get(cat,1.0)),
|
||||
metallicFactor=0.02, roughnessFactor=0.75,
|
||||
alphaMode=("BLEND" if ALPHA.get(cat,1.0)<1 else "OPAQUE"))
|
||||
mats[cat]=m; return m
|
||||
def add(name, mesh, cat):
|
||||
if mesh is None or mesh.faces.shape[0]==0: return
|
||||
# bake flat normals: unweld so each face has unique verts -> exported NORMAL is per-face
|
||||
tris = mesh.vertices[mesh.faces]
|
||||
v = tris.reshape(-1, 3)
|
||||
f = np.arange(len(v)).reshape(-1, 3)
|
||||
mesh = trimesh.Trimesh(vertices=v, faces=f, process=False)
|
||||
# drop degenerate (near-zero-area) faces so normals never become NaN
|
||||
tri=mesh.vertices[mesh.faces]
|
||||
area=np.linalg.norm(np.cross(tri[:,1]-tri[:,0], tri[:,2]-tri[:,0]), axis=1)*0.5
|
||||
good=np.isfinite(area) & (area>1e-9)
|
||||
if not good.all():
|
||||
mesh.update_faces(good); mesh.remove_unreferenced_vertices()
|
||||
if mesh.faces.shape[0]==0: return
|
||||
# convert Z-up -> glTF-standard Y-up: (x,y,z) -> (x, z, -y)
|
||||
mesh.apply_transform(np.array([[1,0,0,0],[0,0,1,0],[0,-1,0,0],[0,0,0,1.0]]))
|
||||
if not np.isfinite(mesh.vertices).all(): return
|
||||
vn=np.array(mesh.vertex_normals, dtype=np.float64) # force + sanitize
|
||||
badrows=~np.isfinite(vn).all(axis=1)
|
||||
if badrows.any():
|
||||
vn[badrows]=[0.0,1.0,0.0]
|
||||
mesh.vertex_normals=vn
|
||||
try:
|
||||
mesh.visual=trimesh.visual.TextureVisuals(material=material(cat))
|
||||
except Exception:
|
||||
pass
|
||||
scene.add_geometry(mesh, geom_name=name, node_name=name)
|
||||
|
||||
want=None if categories in (None,"all") else set(categories)
|
||||
roofs=roof_specs(spec)
|
||||
for fk,fl in spec["floors"].items():
|
||||
z=float(fl["z"]); h=float(fl.get("height",4.2))
|
||||
# slab (bottom plate + setback cap ring at this floor's top to cap columns)
|
||||
if want is None or "slab" in want:
|
||||
polys=fl.get("footprint",{}).get("polygons",[]) if use_fp_slab else []
|
||||
parts=[]
|
||||
if polys:
|
||||
parts.append(mesh_from_polygons(polys, z-slab_th, z))
|
||||
cap_polys=setback_cap_polys(spec, fk, fl, polys)
|
||||
if cap_polys:
|
||||
parts.append(mesh_from_polygons(cap_polys, z+h-slab_th, z+h))
|
||||
else:
|
||||
b=fl["bounds"]; mg=1.2
|
||||
parts.append(mesh_from_polygons(
|
||||
[[[b[0]-mg,b[1]-mg],[b[2]+mg,b[1]-mg],[b[2]+mg,b[3]+mg],[b[0]-mg,b[3]+mg]]],
|
||||
z-slab_th, z))
|
||||
parts=[p for p in parts if p is not None]
|
||||
if parts:
|
||||
add(f"{fk}__slab", parts[0] if len(parts)==1 else trimesh.util.concatenate(parts), "slab")
|
||||
segs=fl.get("segments",{})
|
||||
present=[c for c in CATEGORY_DRAW_ORDER if segs.get(c)]
|
||||
extra=sorted(c for c in segs if c not in CATEGORY_DRAW_ORDER and segs.get(c))
|
||||
for cat in present+extra:
|
||||
if want is not None and cat not in want: continue
|
||||
z0,z1=z_window(cat,z,h,fk,fl)
|
||||
seglist=segs[cat]
|
||||
if cat=="columns":
|
||||
seglist=adjust_columns(seglist, fk, fl, spec, cfg, roofs)
|
||||
if cat=="glazing":
|
||||
seglist=merge_collinear(seglist)
|
||||
add(f"{fk}__{cat}", mesh_from_segments(seglist, z0, z1), cat)
|
||||
# generated roofs
|
||||
if want is None or "roof" in want:
|
||||
for r in roof_specs(spec):
|
||||
z=r["z"]; th=r["thickness"]
|
||||
if r["polygons"]:
|
||||
add(f"{r['floor_key']}__roof", mesh_from_polygons(r["polygons"], z-th, z+0.08), "roof")
|
||||
elif r["bounds"]:
|
||||
b=r["bounds"]
|
||||
add(f"{r['floor_key']}__roof", mesh_from_polygons(
|
||||
[[[b[0],b[1]],[b[2],b[1]],[b[2],b[3]],[b[0],b[3]]]], z-th, z+0.08), "roof")
|
||||
return scene
|
||||
|
||||
def scene_bounds(spec):
|
||||
bx=[math.inf,math.inf,-math.inf,-math.inf]; maxz=0.0
|
||||
for fl in spec["floors"].values():
|
||||
b=fl["bounds"]
|
||||
bx[0]=min(bx[0],b[0]); bx[1]=min(bx[1],b[1])
|
||||
bx[2]=max(bx[2],b[2]); bx[3]=max(bx[3],b[3])
|
||||
maxz=max(maxz,float(fl["z"])+float(fl.get("height",4.2)))
|
||||
return bx,maxz
|
||||
|
||||
def write_metadata(spec, name, out):
|
||||
cfg=spec.get("source",{}).get("config",{})
|
||||
bx,maxz=scene_bounds(spec)
|
||||
meta={
|
||||
"project":spec.get("project",{"name":name}),
|
||||
"floors":[{"key":k,"name":f.get("name",k),"z":f.get("z",0),"height":f.get("height",4.2)}
|
||||
for k,f in spec["floors"].items()],
|
||||
"categories":spec.get("categories",{}),
|
||||
"viewer_defaults":{"disabled_categories":list(cfg.get("default_disabled_categories",[]))},
|
||||
"bounds":{"xy":bx,"max_z":maxz},
|
||||
"files":{"glb":f"{name}.glb"},
|
||||
}
|
||||
Path(out).write_text(json.dumps(meta,ensure_ascii=False,indent=2),encoding="utf-8")
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser()
|
||||
ap.add_argument("--spec",required=True)
|
||||
ap.add_argument("--out",required=True)
|
||||
ap.add_argument("--metadata-out")
|
||||
ap.add_argument("--name",default="model")
|
||||
ap.add_argument("--categories",default="all",help="'all' or comma list incl. slab")
|
||||
a=ap.parse_args()
|
||||
spec=json.loads(Path(a.spec).read_text(encoding="utf-8"))
|
||||
cats = None if a.categories=="all" else [c.strip() for c in a.categories.split(",") if c.strip()]
|
||||
scene=build_scene(spec,cats)
|
||||
Path(a.out).parent.mkdir(parents=True,exist_ok=True)
|
||||
scene.export(a.out)
|
||||
tris=sum(int(g.faces.shape[0]) for g in scene.geometry.values())
|
||||
verts=sum(int(g.vertices.shape[0]) for g in scene.geometry.values())
|
||||
if a.metadata_out: write_metadata(spec,a.name,a.metadata_out)
|
||||
print(json.dumps({"out":a.out,"nodes":len(scene.geometry),"triangles":tris,
|
||||
"vertices":verts,"bytes":Path(a.out).stat().st_size},ensure_ascii=False))
|
||||
|
||||
if __name__=="__main__":
|
||||
main()
|
||||
124
scripts/verify_showcase.py
Normal file
124
scripts/verify_showcase.py
Normal file
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify a building_spec.json (+ optional GLBs) without Blender.
|
||||
|
||||
Outputs:
|
||||
- a text report: per-floor segment counts, footprint area, cap presence,
|
||||
glazing continuity, and (for any GLBs passed) node/vertex counts, file size
|
||||
and a pass/fail against a size budget;
|
||||
- orthographic elevation/plan previews (front / side / top) as a PNG, so the
|
||||
Agent can eyeball completeness and orientation before accepting the model.
|
||||
|
||||
Usage:
|
||||
python3 verify_showcase.py --spec building_spec.json \
|
||||
[--glb overview.glb standard.glb detail.glb] \
|
||||
[--out verify_previews.png] \
|
||||
[--budget-mb 0.6]
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import argparse, json, math, sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def load_spec(path: Path) -> dict:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def glb_stats(path: Path):
|
||||
"""Node + vertex count and byte size; works on Draco GLBs (accessor.count kept)."""
|
||||
try:
|
||||
from pygltflib import GLTF2
|
||||
except Exception:
|
||||
return {"file": path.name, "bytes": path.stat().st_size, "note": "pygltflib not installed"}
|
||||
g = GLTF2().load(str(path))
|
||||
verts = 0
|
||||
for m in g.meshes:
|
||||
for p in m.primitives:
|
||||
if p.attributes.POSITION is not None:
|
||||
verts += g.accessors[p.attributes.POSITION].count
|
||||
return {
|
||||
"file": path.name,
|
||||
"bytes": path.stat().st_size,
|
||||
"meshes": len(g.meshes),
|
||||
"vertices": verts,
|
||||
"draco": any("KHR_draco_mesh_compression" in (e or "") for e in (g.extensionsUsed or [])),
|
||||
}
|
||||
|
||||
|
||||
def text_report(spec: dict, glbs: list[Path], budget_mb: float) -> str:
|
||||
lines = ["# Showcase verification", ""]
|
||||
floors = spec.get("floors", {})
|
||||
lines.append(f"{'floor':7} {'z':>6} {'h':>4} {'fp_area':>8} {'caps':>4} segments")
|
||||
for k, f in floors.items():
|
||||
segs = {c: len(v) for c, v in f.get("segments", {}).items() if v}
|
||||
fp = f.get("footprint", {}).get("area")
|
||||
caps = len(f.get("caps", []))
|
||||
merged = sum(1 for s in f.get("segments", {}).get("glazing", []) if s.get("source_type") == "merged")
|
||||
glz = len(f.get("segments", {}).get("glazing", []))
|
||||
cont = f" glazing_continuous={merged}/{glz}" if glz else ""
|
||||
lines.append(f"{k:7} {f.get('z',0):>6.1f} {f.get('height',0):>4.1f} {str(fp):>8} {caps:>4} {segs}{cont}")
|
||||
lines.append("")
|
||||
if glbs:
|
||||
lines.append("## GLB budget")
|
||||
budget = budget_mb * 1024 * 1024
|
||||
for p in glbs:
|
||||
st = glb_stats(p)
|
||||
mb = st["bytes"] / 1024 / 1024
|
||||
ok = "OK" if st["bytes"] <= budget else "OVER"
|
||||
extra = f" verts={st.get('vertices','?')} draco={st.get('draco','?')}"
|
||||
lines.append(f" {st['file']:20} {mb:6.2f} MB [{ok} vs {budget_mb}MB]{extra}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def render_previews(spec: dict, out: Path) -> bool:
|
||||
try:
|
||||
import numpy as np # noqa
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
except Exception:
|
||||
return False
|
||||
floors = spec["floors"]
|
||||
cmap = plt.get_cmap("turbo")
|
||||
keys = list(floors.keys())
|
||||
fcolor = {k: cmap(i / max(1, len(keys) - 1)) for i, k in enumerate(keys)}
|
||||
fig = plt.figure(figsize=(22, 7))
|
||||
# front elevation (X vs Z), side elevation (Y vs Z), plan (X vs Y)
|
||||
for sub, (ax_h, ax_v, title) in enumerate([(0, 2, "Front elevation (X-Z)"),
|
||||
(1, 2, "Side elevation (Y-Z)"),
|
||||
(0, 1, "Plan overlay (X-Y)")]):
|
||||
ax = fig.add_subplot(1, 3, sub + 1)
|
||||
for k, f in floors.items():
|
||||
z = float(f["z"]); h = float(f.get("height", 4.2))
|
||||
for cat, col in [("walls", "#8a7f6a"), ("columns", "#f58a1f"), ("glazing", "#5aa9c9")]:
|
||||
for s in f.get("segments", {}).get(cat, []):
|
||||
a, b = s["start"], s["end"]
|
||||
p = [a, b]
|
||||
if ax_v == 2: # elevation: vertical extent z..z+h at midpoint of horizontal axis
|
||||
ah0, ah1 = a[ax_h], b[ax_h]
|
||||
ax.plot([ah0, ah1], [z + h * 0.5, z + h * 0.5], color=col, lw=0.2, alpha=0.35)
|
||||
else: # plan
|
||||
ax.plot([a[ax_h], b[ax_h]], [a[ax_v], b[ax_v]], color=col, lw=0.15, alpha=0.4)
|
||||
ax.set_title(title)
|
||||
if ax_v == 1:
|
||||
ax.set_aspect("equal")
|
||||
plt.tight_layout()
|
||||
plt.savefig(out, dpi=120)
|
||||
return True
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument("--spec", required=True)
|
||||
ap.add_argument("--glb", nargs="*", default=[])
|
||||
ap.add_argument("--out", default="verify_previews.png")
|
||||
ap.add_argument("--budget-mb", type=float, default=0.6)
|
||||
a = ap.parse_args()
|
||||
spec = load_spec(Path(a.spec))
|
||||
print(text_report(spec, [Path(p) for p in a.glb], a.budget_mb))
|
||||
ok = render_previews(spec, Path(a.out))
|
||||
print(f"\npreviews: {'written ' + a.out if ok else 'skipped (matplotlib not installed)'}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
157
scripts/write_web_showcase.py
Executable file
157
scripts/write_web_showcase.py
Executable file
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Instantiate the static Three.js web showcase template."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import shutil
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def default_template() -> Path:
|
||||
return Path(__file__).resolve().parents[1] / "assets" / "web-showcase-template"
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--template", default=str(default_template()), help="Template folder")
|
||||
parser.add_argument("--glb", help="Source default GLB model")
|
||||
parser.add_argument("--metadata", help="model_metadata.json from Blender script")
|
||||
parser.add_argument("--variants-manifest", help="Manifest from build_showcase_variants.py")
|
||||
parser.add_argument("--out-dir", required=True, help="Web output folder")
|
||||
parser.add_argument("--title", default="CAD 建筑 Web 展示模型")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def copy_template(template: Path, out_dir: Path):
|
||||
if not template.exists():
|
||||
raise SystemExit(f"Template not found: {template}")
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
for item in template.iterdir():
|
||||
dest = out_dir / item.name
|
||||
if item.is_dir():
|
||||
shutil.copytree(item, dest, dirs_exist_ok=True)
|
||||
else:
|
||||
shutil.copy2(item, dest)
|
||||
|
||||
|
||||
def patch_index(out_dir: Path, title: str, build: str):
|
||||
"""Fill template placeholders and stamp a cache-busting build token.
|
||||
|
||||
Browsers cache ES modules and GLB aggressively; the ?v=<build> query on
|
||||
app.js / model.glb / model_metadata.json forces a reload after a rebuild.
|
||||
"""
|
||||
for name in ("index.html", "app.js"):
|
||||
path = out_dir / name
|
||||
if not path.exists():
|
||||
continue
|
||||
text = path.read_text(encoding="utf-8")
|
||||
text = text.replace("{{TITLE}}", title).replace("{{BUILD}}", build)
|
||||
path.write_text(text, encoding="utf-8")
|
||||
|
||||
|
||||
def resolve_manifest_path(manifest_path: Path, value: str) -> Path:
|
||||
path = Path(value)
|
||||
return path if path.is_absolute() else manifest_path.parent / path
|
||||
|
||||
|
||||
def load_variants(manifest_path: Path | None) -> tuple[dict | None, list[dict]]:
|
||||
if not manifest_path:
|
||||
return None, []
|
||||
if not manifest_path.exists():
|
||||
raise SystemExit(f"Variants manifest not found: {manifest_path}")
|
||||
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||
variants = list(manifest.get("variants", []))
|
||||
if not variants:
|
||||
raise SystemExit(f"Variants manifest has no variants: {manifest_path}")
|
||||
return manifest, variants
|
||||
|
||||
|
||||
def default_variant(manifest: dict | None, variants: list[dict]) -> dict | None:
|
||||
if not variants:
|
||||
return None
|
||||
default_key = (manifest or {}).get("default_key", "standard")
|
||||
for variant in variants:
|
||||
if variant.get("key") == default_key:
|
||||
return variant
|
||||
return variants[0]
|
||||
|
||||
|
||||
def copy_variant_assets(manifest_path: Path | None, variants: list[dict], out_dir: Path) -> list[dict]:
|
||||
web_variants = []
|
||||
for variant in variants:
|
||||
source_value = variant.get("source_glb") or variant.get("source") or variant.get("file")
|
||||
if not source_value:
|
||||
raise SystemExit(f"Variant is missing source_glb/source/file: {variant}")
|
||||
source = resolve_manifest_path(manifest_path, source_value) if manifest_path else Path(source_value)
|
||||
if not source.exists():
|
||||
raise SystemExit(f"Variant GLB not found: {source}")
|
||||
dest_name = Path(variant.get("file") or f"{variant.get('key', source.stem)}.glb").name
|
||||
shutil.copy2(source, out_dir / dest_name)
|
||||
web_variant = {
|
||||
"key": variant.get("key", Path(dest_name).stem),
|
||||
"label": variant.get("label", variant.get("key", dest_name)),
|
||||
"file": dest_name,
|
||||
}
|
||||
if variant.get("description"):
|
||||
web_variant["description"] = variant["description"]
|
||||
web_variants.append(web_variant)
|
||||
return web_variants
|
||||
|
||||
|
||||
def inferred_default_glb(args_glb: str | None, manifest_path: Path | None, manifest: dict | None, variants: list[dict]) -> Path:
|
||||
if args_glb:
|
||||
return Path(args_glb)
|
||||
variant = default_variant(manifest, variants)
|
||||
if not variant:
|
||||
raise SystemExit("Either --glb or --variants-manifest is required")
|
||||
source_value = variant.get("source_glb") or variant.get("source") or variant.get("file")
|
||||
return resolve_manifest_path(manifest_path, source_value) if manifest_path else Path(source_value)
|
||||
|
||||
|
||||
def inferred_metadata(args_metadata: str | None, manifest_path: Path | None, manifest: dict | None, variants: list[dict]) -> Path:
|
||||
if args_metadata:
|
||||
return Path(args_metadata)
|
||||
variant = default_variant(manifest, variants)
|
||||
metadata_value = variant.get("metadata") if variant else None
|
||||
if not metadata_value:
|
||||
raise SystemExit("Either --metadata or a default variant metadata entry is required")
|
||||
return resolve_manifest_path(manifest_path, metadata_value) if manifest_path else Path(metadata_value)
|
||||
|
||||
|
||||
def write_assets(glb: Path, metadata: Path, out_dir: Path, web_variants: list[dict]):
|
||||
if not glb.exists():
|
||||
raise SystemExit(f"GLB not found: {glb}")
|
||||
if not metadata.exists():
|
||||
raise SystemExit(f"Metadata not found: {metadata}")
|
||||
shutil.copy2(glb, out_dir / "model.glb")
|
||||
meta = json.loads(metadata.read_text(encoding="utf-8"))
|
||||
meta.setdefault("files", {})["glb"] = "model.glb"
|
||||
if web_variants:
|
||||
meta["model_variants"] = web_variants
|
||||
(out_dir / "model_metadata.json").write_text(
|
||||
json.dumps(meta, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = parse_args()
|
||||
out_dir = Path(args.out_dir)
|
||||
manifest_path = Path(args.variants_manifest) if args.variants_manifest else None
|
||||
manifest, variants = load_variants(manifest_path)
|
||||
copy_template(Path(args.template), out_dir)
|
||||
build = str(int(time.time()))
|
||||
patch_index(out_dir, args.title, build)
|
||||
web_variants = copy_variant_assets(manifest_path, variants, out_dir)
|
||||
glb = inferred_default_glb(args.glb, manifest_path, manifest, variants)
|
||||
metadata = inferred_metadata(args.metadata, manifest_path, manifest, variants)
|
||||
write_assets(glb, metadata, out_dir, web_variants)
|
||||
print(json.dumps({"web_dir": str(out_dir), "entry": str(out_dir / "index.html")}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user