Initial commit: cad-building-showcase skill

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

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

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

22
.gitignore vendored Normal file
View File

@@ -0,0 +1,22 @@
# Large input/output data — regenerated from source, not committed
work/
outputs/
_output_building_complex/
source_cad/
source_cad_burj/
# Caches / OS / tooling state
__pycache__/
*.pyc
.DS_Store
.omc/
.playwright-mcp/
node_modules/
*.draco.glb
# Session debug artifacts (screenshots + browser snapshots)
/*.png
/home*.md
/plugins*.md
/b8191.md
/final-plugins.md

156
SKILL.md Normal file
View File

@@ -0,0 +1,156 @@
---
name: cad-building-showcase
description: Agent-led workflow for generating and auditing architectural 3D web showcase models from CAD drawing folders. Use when Codex is given DWG/DXF/PDF CAD plans, XREF folders, floor plans, building drawings, or asks like "用 CAD 图纸生成 3D 建筑演示模型", "把所有 CAD 图纸做成 Web 展示模型", "DWG/DXF 转 Blender/GLB", "建筑平面图生成完整建筑展示模型", or asks whether CAD-derived output can replace BIM. This skill is specifically for cases where an Agent must inspect CAD reports, decide layer/floor/block rules, run scripts, audit coverage, and iterate; not for blind one-shot script conversion.
---
# CAD Building Showcase
## Outcome
Create a usable architectural demonstration model through Agent judgment plus deterministic scripts. Do not treat this as blind CAD conversion. The target deliverables are:
- CAD read report: converted/sanitized DXF inventory, layer counts, entity counts, drawing bounds, likely units.
- Agent extraction config: explicit layer mapping, floor split/alignment, unit scale, curve and filtering rules.
- `building_spec.json`: normalized floor-by-floor geometry in meters.
- Extraction audit: coverage, unclassified layers, high-risk entity types, block/INSERT signals, and Agent questions.
- 2D overlay review: SVG overlays comparing source CAD vectors with extracted model geometry.
- Blender scene: `.blend`, `.glb`, and preview `.png`.
- Web showcase: static Three.js viewer with floor/component toggles, floor explode, section height, camera presets, screenshot, and GLB download.
- Lightweight variants: produce at least overview, standard, and detail GLB variants when the user asks for Web/digital-twin presentation. The Web viewer should default to the standard variant and expose download links for all variants.
- Notes file: source drawings, assumptions, extraction limits, and verification results.
If the user asks to replace BIM, branch explicitly to IFC/BIM validation. Treat Web showcase and BIM replacement as separate products.
## Agent Decision Loop
The Agent owns interpretation. Scripts are tools for evidence and repeatable execution.
1. Inspect first, do not model blind.
- Run `cad_dxf_report.py`.
- Read top layers, entity types, bounding boxes, units, and high-risk entities.
- Form hypotheses: which drawings are floor plans, which layers are walls/glazing/roof/columns/beams/railings/doors/detail lines/grid, whether blocks or hatches matter, and how floors align.
2. Write an explicit extraction config.
- Decide layer mappings, floor splits, offsets, origin strategy, curve chord length, and category-specific line-length filters.
- Use `references/pipeline.md`, `references/building_spec_schema.md`, and `references/a208_case_notes.md` as calibration.
3. Extract, audit, and review overlays before accepting.
- Run `derive_showcase_spec.py`.
- Run `audit_showcase_extraction.py`.
- Run `draw_coverage_overlay.py`.
- Inspect unclassified layers, high-risk `INSERT`/`HATCH` counts, and overlay SVGs. If major geometry is red/unclassified or missing, adjust config or parsing strategy and repeat.
4. Generate and verify the 3D/Web model only after the extraction passes review.
- Run Blender/GLB generation and Web template assembly.
- Verify preview image, Web controls, console logs, and mobile layout.
5. Report confidence and limits.
- State whether the output is Web showcase, LOD-like massing, IFC/BIM proof, or not sufficient.
- Include what was not modeled and what evidence supports that judgment.
## Command Workflow
1. Prepare the CAD folder.
- Work from a folder under the current workspace when possible. On macOS, avoid direct reads from `Downloads` if TCC blocks access; ask the user to move/copy the CAD folder into the workspace.
- Preserve the original CAD folder. Put converted/intermediate files in `work/`.
- If DWG files are present, prefer `libredwg` `dwg2dxf` for batch conversion. Use ODA/QCAD/FreeCAD only as fallback — EXCEPT for drawings containing `3DSOLID`/ACIS entities: libredwg silently drops ACIS data (R2013+ stores it in the ACDSDATA section), so 3D-solid DWGs must go through ODA File Converter (`/Applications/ODAFileConverter.app/Contents/MacOS/ODAFileConverter <abs_in_dir> <abs_out_dir> ACAD2004 DXF 0 1 "*.dwg"`). ODA reports bad arguments via GUI dialogs, not stderr: both directories must exist as absolute paths, and a silent exit-0 with no output means a dialog is blocking on screen.
3D-solid DWG branch: if the read report shows `3DSOLID`/`MESH` as the main types (typically also flagged `near_empty` for plan purposes), the floor-plan extrusion pipeline does not apply. Convert via ODA, then tessellate with `ezdxf.acis` (`load_dxf` → `mesh_from_body`, which returns a list of meshes). Only polyhedral/flat ACIS faces tessellate; count curved records (`cone-surface`, `spline-surface`, ...) in the SAT text and report them as not extractable. Export captured meshes + `MESH` entities to OBJ/GLB (OBJ is Z-up: import into Blender with `up_axis='Z'`). If curved skin dominates, tell the user to export OBJ/STL/STEP from a full CAD kernel (AutoCAD/BricsCAD) instead of promising a complete model.
2. Generate a CAD read report.
- Run `scripts/cad_dxf_report.py` from this skill.
- Install missing parser dependencies into the current project work area, not globally:
`python3 -m pip install --target work/vendor ezdxf`
- Inspect the Markdown/JSON report before modeling. Confirm drawings, units, bounding boxes, and the top layers for walls/glazing/roof/columns/beams/railings/doors/detail lines/floor lines/grid.
- Resolve the report's `Warnings` section before modeling. `likely_xref_shell` / `near_empty` means a sheet's real geometry lives in unbound XREFs and will silently become a missing floor: ask the user to bind/insert the XREFs in CAD and re-export that DXF (do not model the shell and report the floor as done).
3. Build the extraction config and `building_spec.json`.
- Use `references/pipeline.md` and `references/building_spec_schema.md`.
- Map CAD layers to normalized categories: `walls`, `glazing`, `roof`, `columns`, `beams`, `railings`, `doors`, `detail_lines`, `floor_lines`, and `grid`.
- Identify one drawing per floor or split sheets that contain multiple floor plans side by side.
- Align floors by structural grid or repeated control axes. Use millimeters-to-meters scale (`0.001`) unless the report proves the CAD is already in meters.
- When CAD linework has enough exterior/interior boundary signal, enable generated footprints for floor slabs and roof caps. Prefer footprint polygons over rectangular floor bounds for visual/digital-twin presentation.
- Run `scripts/derive_showcase_spec.py` to extract line/polyline geometry into `building_spec.json`.
4. Audit extraction before 3D generation.
- Run `scripts/audit_showcase_extraction.py`.
- Run `scripts/draw_coverage_overlay.py`.
- The audit enforces hard gates and exits with code 3 on failure (e.g. glazing evidence exists in blocks but the spec has 0 glazing segments). A failed gate means the extraction is known-incomplete: fix the config or source export and re-run; never bypass with `--no-strict-gates` just to proceed.
- The headline coverage ratio counts modelspace linework only. Read the `Block-Locked Geometry By Layer` section too — geometry inside INSERT blocks is reported separately and a 96% coverage can coexist with an entirely missing curtain wall.
- Review the Markdown audit and SVG overlays. Iterate config if important geometry remains unclassified or hidden in high-risk entity types.
5. Generate Blender/GLB.
- Use Blender CLI:
`/Applications/Blender.app/Contents/MacOS/Blender -b --python <skill>/scripts/build_blender_showcase.py -- --spec work/building_spec.json --out-dir outputs/<project> --name <project>`
- Use Blender MCP only after the CLI artifact exists, for inspection, scene tuning, or interactive refinement.
6. Generate the Web showcase.
- For digital-twin-style Web delivery, keep generated slabs visible by default and create three filtered specs/models:
- `overview`: walls, glazing, roof, columns, beams, and generated slabs.
- `standard`: overview plus railings and doors; use this as the default Web model.
- `detail`: full extraction, including grid, floor lines, and detail lines for audit/review.
- Run `scripts/build_showcase_variants.py --build` to write the filtered specs, call Blender for all three GLBs, and create `variants_manifest.json`.
- Run `scripts/write_web_showcase.py --variants-manifest ...` to copy the template, use the standard model as `model.glb`, copy all variant GLBs, and add `model_variants` to `model_metadata.json`.
- Use the single-GLB `write_web_showcase.py --glb ... --metadata ...` path only when the user explicitly wants a quick one-model preview.
- Install local web deps in that output folder:
`npm install --prefix outputs/<project>/web three@0.181.2 lucide@0.468.0`
- Start a local server from the web output folder and give the user the URL.
7. Verify before final delivery.
- Open the preview PNG or render another screenshot; check that geometry is nonblank and framed.
- Open the Web viewer in the Browser plugin on desktop and mobile widths.
- Check console logs are clean, controls work, mobile panels do not overlap, and the GLB loads.
- Report model precision honestly: showcase model, LOD-like massing/structural visualization, or IFC/BIM proof.
## Modeling Rules
- Prefer stable, layered massing over overfitted geometry. CAD floor plans often contain annotations, dimensions, hatches, XREF artifacts, and duplicated lines.
- Use linework from walls/glazing/columns/beams/railings/doors as visual extrusions. Generate explicit `roof`/roof-cover geometry when roof drawings are sparse or when top-floor columns need an overhead cap. Keep generic detail layers as low plan detail unless the Agent has evidence they are vertical building elements. Do not claim parametric wall joins, rooms, MEP, quantities, or code-compliant BIM unless IFC semantics and validation are generated.
- Keep 3D floor labels off by default. The Web UI already names floors; generated in-scene text usually clutters the building view.
- Prefer CAD-derived footprint polygon `slab` meshes over rectangular `bounds` slabs. Generate the footprint from mapped wall/glazing/floor-line/railing/column vectors, simplify it, and cap it to a small number of high-area polygons. For digital-twin-style presentation, use a looser concave hull so floor plates read as continuous platforms instead of leaving avoidable visual voids. Treat this as a visual floor/roof plate, not a BIM-grade slab with validated openings and joins.
- For presentation models, make slab edges visible in side views: use a display thickness around 0.35-0.40 m, render slabs double-sided in the Web viewer, and avoid very low slab opacity. Otherwise transparent glazing can make floor plates look missing even when the footprint is present.
- Keep `slab` available as a toggle. Default it on for presentation/digital-twin models; default it off only for audit views where slabs obscure linework review.
- For generated roof caps, do not blindly union lower floor footprints into the roof geometry. Use the roof floor's own `footprint_from` source unless there is clear CAD evidence that a canopy/overhang exists.
- For columns that visually stand without anything above, do not rely on broad floor bounds or broad footprint alone to infer support. Require an adjacent upper floor/roof plate and nearby upper structural geometry; shorten unsupported display columns unless the Agent has evidence they are meant to be full-height freestanding elements.
- Keep floors separable in object names and metadata. The Web viewer expects objects named `<floor_key>__<category>`.
- Use neutral, readable colors and transparent slabs. Avoid a single-hue scene.
- Document every assumption that affects geometry: layer mapping, floor heights, sheet splits, coordinate offsets, unit scale, and ignored entity types.
- Curtain walls/glazing are frequently inside INSERT blocks (e.g. `系统嵌板/幕墙` blocks resolving to layer `A-GLAZ-CURT`). `derive_showcase_spec.py` handles this two ways: block-name expansion (`GLAZING_BLOCK_PATTERNS`, fragile — DWG→DXF conversion can mangle CJK names like `系统嵌板`→`系统嵌`) and layer-based probing (`classify_block_contents`, default on): every INSERT — including wrapper/sheet blocks — is expanded up to `expand_blocks_max_depth` and sub-entities are kept only when their own layer classifies into `block_content_categories` (default glazing/railings/doors). Check the audit's glazing gate and block-locked section before accepting.
- Identification/annotation layers (`*-IDEN`: door tags, axis numbers, area labels) are excluded from classification by default (`exclude_layers`), so `A-DOOR-IDEN` no longer counts as door geometry. If a category only ever matched an `*-IDEN` layer, the drawing has no real geometry for it — say so instead of modeling tags.
- CAD draws curtain walls as sparse panel/mullion segments; `derive_showcase_spec.py` merges collinear glazing into continuous bands (`merge_glazing`, `glazing_gap_tol`). Only bridge gaps that contain no opaque wall on the same line.
- Prefer capping column tops over shortening them. `derive_showcase_spec.py` stores `floor.caps` (setback overhang rings for above-ground floors, full ground/podium deck for the top basement level) which both backends extrude as slab caps; this avoids stray topless columns and odd short stubs.
- Coordinate convention: GLB is glTF-standard **Y-up**; the Web viewer sets `camera.up=(0,1,0)`, sections/explode along Y, and registers a `DRACOLoader`. Keep GLB up-axis and viewer up-axis in sync, otherwise the building renders lying on its side.
- Lightweighting: export Draco-compressed GLB (Blender built-in, or `tools/compress.mjs`); the viewer must register `DRACOLoader` (it does). Sanitize degenerate faces / NaN normals before export so strict importers (Blender, online viewers) accept the file.
## Bundled Resources
- `scripts/cad_dxf_report.py`: batch DWG/DXF conversion, DXF sanitizing, and read report generation, including XREF-shell / near-empty sheet warnings.
- `scripts/derive_showcase_spec.py`: configurable extraction from DXF line/polyline layers into a normalized building spec, with block-content probing for glazing/railings/doors locked inside INSERTs.
- `scripts/audit_showcase_extraction.py`: coverage and risk audit with hard gates (exit 3 on failure) and block-locked geometry accounting, for Agent review before 3D generation.
- `scripts/draw_coverage_overlay.py`: SVG overlays comparing source CAD vectors to extracted model geometry.
- `scripts/verify_showcase.py`: Blender-free QA from `building_spec.json` (+ optional GLBs): per-floor segment/cap/glazing-continuity report, GLB size-budget check, and orthographic front/side/plan previews.
- `scripts/build_blender_showcase.py`: Blender CLI renderer/exporter from `building_spec.json` to `.blend`, `.glb`, `.png`, and metadata. GLB is Draco-compressed by default.
- `scripts/spec_to_glb.py`: Blender-free `building_spec.json` -> GLB exporter (trimesh). Use when Blender is unavailable; produces the same `<floor>__<category>` naming, Y-up, flat normals, glazing merge, and setback/basement caps.
- `tools/compress.mjs`: gltf-transform Draco compressor (`node tools/compress.mjs in.glb out.glb`); alternative to Blender's built-in Draco, usually smaller.
- `scripts/build_showcase_variants.py`: creates overview/standard/detail filtered specs, optionally builds their GLBs, and writes a manifest for Web delivery.
- `scripts/write_web_showcase.py`: copies the static Web viewer template and model assets into an output folder.
- `scripts/build_ifc_poc.py`: optional IFC4 semantic proof-of-concept generator from `building_spec.json`.
- `scripts/extract_ifc_meshes.py`: extracts IFC geometry to JSON for render verification.
- `scripts/render_ifc_meshes_blender.py`: renders IFC geometry in Blender and exports `.blend`, `.glb`, and `.png`.
- `references/pipeline.md`: detailed CAD-to-model procedure and quality gates.
- `references/building_spec_schema.md`: expected JSON contract between CAD extraction, Blender, and Web viewer.
- `references/agent_review.md`: acceptance/iteration/BIM-claim checklist for Agent judgment.
- `references/a208_case_notes.md`: proven details from the A208 DWG/DXF/Blender/Web/IFC run.
- `references/optimization_notes.md`: lightweighting + completeness lessons (Draco/DRACOLoader, glTF Y-up convention, block-locked glazing, glazing continuity, column-top caps, NaN sanitation, verification).
- `assets/web-showcase-template/`: static Three.js viewer template (Y-up, registers DRACOLoader, cache-busting `?v=` build token).
- `tests/test_extraction_pipeline.py`: synthetic-DXF regression test for block-locked glazing capture, `*-IDEN` exclusion, audit gates, and XREF-shell warnings. Run it after changing extraction/audit/report scripts.
## BIM Branch
When the user asks whether the model can replace BIM:
- Say that the Web showcase model cannot replace BIM by itself.
- Create IFC only if the task explicitly needs BIM-like semantics.
- Use `scripts/build_ifc_poc.py` with IfcOpenShell to generate and validate IFC entity counts, schema validity, geometry generation, storeys, and property sets.
- Use `scripts/extract_ifc_meshes.py` and `scripts/render_ifc_meshes_blender.py` when the user asks to see the IFC render effect or when Blender cannot import IFC directly.
- State the remaining BIM gaps: wall/slab joins, object classifications, openings, doors/windows, room spaces, quantities, materials, levels, georeferencing, and discipline coordination.

4
agents/openai.yaml Normal file
View File

@@ -0,0 +1,4 @@
interface:
display_name: "CAD Building Showcase"
short_description: "Agent-led CAD drawing audit and architectural web showcase generation."
default_prompt: "Inspect and audit a CAD drawing folder, then generate a verified architectural 3D web showcase model."

View File

@@ -0,0 +1,431 @@
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
const canvas = document.querySelector("#scene");
const loading = document.querySelector("#loading");
const loadingFill = document.querySelector("#loading-fill");
const loadingText = document.querySelector("#loading-text");
const floorControls = document.querySelector("#floor-controls");
const categoryControls = document.querySelector("#category-controls");
const downloadControls = document.querySelector("#download-controls");
const stats = document.querySelector("#stats");
const inspect = document.querySelector("#inspect");
const explodeInput = document.querySelector("#explode");
const explodeValue = document.querySelector("#explode-value");
const sectionInput = document.querySelector("#section");
const sectionValue = document.querySelector("#section-value");
const autoRotateButton = document.querySelector("#auto-rotate");
const preferredCategoryOrder = [
"slab",
"roof",
"walls",
"glazing",
"columns",
"beams",
"railings",
"doors",
"detail_lines",
"floor_lines",
"grid",
];
const objectRegistry = [];
const floorGroups = new Map();
const materialByCategory = new Map();
const state = {
floors: {},
categories: {},
autoRotate: false,
selected: null,
bounds: null,
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x272a2d);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
preserveDrawingBuffer: true,
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.2;
renderer.shadowMap.enabled = true;
renderer.localClippingEnabled = true;
const camera = new THREE.PerspectiveCamera(36, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.up.set(0, 1, 0); // glTF-standard Y-up; required so OrbitControls.maxPolarAngle allows bird's-eye angles
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.08;
controls.screenSpacePanning = true;
controls.maxPolarAngle = Math.PI * 0.49;
scene.add(new THREE.HemisphereLight(0xf7f3e8, 0x20262a, 1.45));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.6);
keyLight.position.set(-45, -62, 85);
keyLight.castShadow = true;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x9fd4ff, 1.15);
fillLight.position.set(80, 55, 48);
scene.add(fillLight);
const modelRoot = new THREE.Group();
modelRoot.name = "cad_web_model";
scene.add(modelRoot);
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const sectionPlane = new THREE.Plane(new THREE.Vector3(0, -1, 0), 9999); // Y-up: clip above section height on Y
const metadata = await fetch("./model_metadata.json?v={{BUILD}}").then((response) => response.json());
const categoryOrder = preferredCategoryOrder.filter((key) => metadata.categories?.[key]);
document.querySelector("#project-name").textContent = metadata.project?.name || "CAD 建筑模型";
document.querySelector("#project-description").textContent = metadata.project?.description || "Web 展示模型";
initialiseState(metadata);
buildInterface(metadata);
const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath("./node_modules/three/examples/jsm/libs/draco/"); // shipped with three; works offline
loader.setDRACOLoader(dracoLoader);
loader.load(
"./model.glb?v={{BUILD}}",
(gltf) => {
ingestModel(gltf.scene, metadata);
applyExplode(Number(explodeInput.value));
const maxZ = Math.max(6, Math.ceil((metadata.bounds?.max_z || 12) + 2));
sectionInput.max = String(maxZ);
sectionInput.value = String(maxZ);
sectionValue.textContent = "关闭";
applySection(maxZ);
fitCamera("overview");
updateStats();
updateVisibility();
loading.classList.add("hidden");
},
(event) => {
if (!event.total) return;
const pct = Math.max(8, Math.min(100, Math.round((event.loaded / event.total) * 100)));
loadingFill.style.width = `${pct}%`;
loadingText.textContent = `加载模型 ${pct}%`;
},
(error) => {
loadingText.textContent = "模型加载失败";
console.error(error);
},
);
if (window.lucide) window.lucide.createIcons();
function initialiseState(meta) {
const disabledCategories = new Set(meta.viewer_defaults?.disabled_categories || []);
for (const floor of meta.floors || []) state.floors[floor.key] = true;
for (const key of categoryOrder) state.categories[key] = !disabledCategories.has(key);
}
function buildInterface(meta) {
floorControls.replaceChildren(
...(meta.floors || []).map((floor) =>
createToggle({
key: floor.key,
label: floor.key,
checked: state.floors[floor.key],
onChange: (checked) => {
state.floors[floor.key] = checked;
updateVisibility();
},
}),
),
);
categoryControls.replaceChildren(
...categoryOrder.map((key) =>
createToggle({
key,
label: meta.categories[key].label || key,
color: meta.categories[key].color,
checked: state.categories[key],
onChange: (checked) => {
state.categories[key] = checked;
updateVisibility();
},
}),
),
);
buildDownloadControls(meta);
explodeInput.addEventListener("input", () => {
const value = Number(explodeInput.value);
explodeValue.textContent = `${value.toFixed(value % 1 ? 1 : 0)}m`;
applyExplode(value);
});
sectionInput.addEventListener("input", () => applySection(Number(sectionInput.value)));
document.querySelectorAll("[data-preset]").forEach((button) => {
button.addEventListener("click", () => fitCamera(button.dataset.preset));
});
document.querySelector("#reset-view").addEventListener("click", () => {
explodeInput.value = "0";
explodeValue.textContent = "0m";
sectionInput.value = sectionInput.max;
sectionValue.textContent = "关闭";
applyExplode(0);
applySection(Number(sectionInput.max));
fitCamera("overview");
});
autoRotateButton.addEventListener("click", () => {
state.autoRotate = !state.autoRotate;
autoRotateButton.classList.toggle("active", state.autoRotate);
controls.autoRotate = state.autoRotate;
controls.autoRotateSpeed = 0.8;
});
document.querySelector("#snapshot").addEventListener("click", downloadSnapshot);
}
function buildDownloadControls(meta) {
const variants = meta.model_variants?.length
? meta.model_variants
: [{ key: "current", label: "当前 GLB", file: meta.files?.glb || "model.glb" }];
downloadControls.replaceChildren(
...variants.map((variant) => {
const link = document.createElement("a");
link.className = "download-link";
link.href = variant.file;
link.download = variant.file.split("/").pop() || "model.glb";
link.title = variant.description || variant.label || variant.key;
link.textContent = variant.label || variant.key;
return link;
}),
);
}
function createToggle({ key, label, color, checked, onChange }) {
const root = document.createElement("label");
root.className = "toggle";
root.dataset.key = key;
const input = document.createElement("input");
input.type = "checkbox";
input.checked = checked;
input.addEventListener("change", () => onChange(input.checked));
root.append(input);
if (color) {
const swatch = document.createElement("span");
swatch.className = "swatch";
swatch.style.background = color;
root.append(swatch);
}
const text = document.createElement("span");
text.textContent = label;
root.append(text);
return root;
}
function ingestModel(gltfScene, meta) {
for (const floor of meta.floors || []) {
const group = new THREE.Group();
group.name = floor.key;
floorGroups.set(floor.key, group);
modelRoot.add(group);
}
gltfScene.updateMatrixWorld(true);
const meshes = [];
gltfScene.traverse((node) => {
if (node.isMesh) meshes.push(node);
});
for (const mesh of meshes) {
const parsed = parseObjectName(mesh.name);
mesh.updateWorldMatrix(true, false);
mesh.geometry.applyMatrix4(mesh.matrixWorld);
mesh.position.set(0, 0, 0);
mesh.rotation.set(0, 0, 0);
mesh.scale.set(1, 1, 1);
mesh.updateMatrix();
if (!parsed || !floorGroups.has(parsed.floor)) {
modelRoot.add(mesh);
continue;
}
mesh.castShadow = !["grid", "floor_lines", "detail_lines", "glazing"].includes(parsed.category);
mesh.receiveShadow = true;
mesh.userData.floor = parsed.floor;
mesh.userData.category = parsed.category;
mesh.userData.label = labelForObject(parsed);
if (categoryOrder.includes(parsed.category)) {
mesh.material = materialForCategory(parsed.category, meta);
addEdges(mesh, parsed.category);
objectRegistry.push(mesh);
}
floorGroups.get(parsed.floor).add(mesh);
}
state.bounds = new THREE.Box3().setFromObject(modelRoot);
}
function parseObjectName(name) {
const match = name.match(/^(.+)__(.+)$/);
if (!match) return null;
// strip Blender's auto de-dup suffix (e.g. "1F__slab.001" -> category "slab")
const category = match[2].replace(/\.\d+$/, "");
return { floor: match[1], category };
}
function labelForObject({ floor, category }) {
return `${floor} ${metadata.categories?.[category]?.label || category}`;
}
function materialForCategory(category, meta) {
if (materialByCategory.has(category)) return materialByCategory.get(category);
const color = new THREE.Color(meta.categories[category]?.color || "#cccccc");
const opacity =
category === "slab"
? 0.64
: category === "roof"
? 0.95
: category === "glazing"
? 0.36
: category === "detail_lines"
? 0.72
: category === "grid" || category === "floor_lines"
? 0.88
: category === "doors"
? 0.90
: 1;
const material = new THREE.MeshStandardMaterial({
color,
transparent: opacity < 1,
opacity,
depthWrite: category === "slab" ? true : opacity >= 0.8,
roughness: 0.74,
metalness: 0.02,
side: category === "slab" || category === "roof" ? THREE.DoubleSide : THREE.FrontSide,
clippingPlanes: [sectionPlane],
});
materialByCategory.set(category, material);
return material;
}
function addEdges(mesh, category) {
if (["grid", "floor_lines", "detail_lines", "glazing"].includes(category)) return;
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry, 35),
new THREE.LineBasicMaterial({ color: 0x101214, transparent: true, opacity: 0.28 }),
);
mesh.add(edges);
}
function applyExplode(distance) {
const floors = metadata.floors || [];
for (const [index, floor] of floors.entries()) {
const group = floorGroups.get(floor.key);
if (group) group.position.y = index * distance; // Y-up: explode floors along Y
}
updateStats();
}
function applySection(height) {
const max = Number(sectionInput.max);
sectionPlane.constant = height >= max ? 9999 : height;
sectionValue.textContent = height >= max ? "关闭" : `${height.toFixed(2)}m`;
}
function updateVisibility() {
for (const mesh of objectRegistry) {
mesh.visible = Boolean(state.floors[mesh.userData.floor] && state.categories[mesh.userData.category]);
}
for (const [floorKey, group] of floorGroups.entries()) {
group.visible = Boolean(state.floors[floorKey]);
}
updateStats();
}
function updateStats() {
const activeFloors = Object.values(state.floors).filter(Boolean).length;
const activeCategories = Object.values(state.categories).filter(Boolean).length;
const visibleMeshes = objectRegistry.filter((mesh) => mesh.visible !== false);
const vertices = visibleMeshes.reduce((sum, mesh) => sum + mesh.geometry.attributes.position.count, 0);
stats.innerHTML = "";
for (const item of [
["楼层", `${activeFloors}/${(metadata.floors || []).length}`],
["构件", `${activeCategories}/${categoryOrder.length}`],
["顶点", vertices.toLocaleString("zh-CN")],
]) {
const cell = document.createElement("div");
cell.innerHTML = `<dt>${item[0]}</dt><dd>${item[1]}</dd>`;
stats.append(cell);
}
}
function fitCamera(preset) {
const box = new THREE.Box3().setFromObject(modelRoot);
state.bounds = box;
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
const maxSize = Math.max(size.x, size.y, size.z, 1);
if (preset === "top") {
camera.position.set(center.x, center.y + maxSize * 1.45, center.z);
} else if (preset === "side") {
camera.position.set(center.x, center.y + maxSize * 0.18, center.z + maxSize * 1.35);
} else {
// bird's-eye 3/4 aerial (~55° looking down); Y is up (glTF standard)
const d = maxSize * 1.4;
const L = Math.hypot(0.55, 1.0, 0.7);
camera.position.set(center.x - (0.55 / L) * d, center.y + (1.0 / L) * d, center.z + (0.7 / L) * d);
}
camera.near = 0.1;
camera.far = maxSize * 8;
camera.updateProjectionMatrix();
controls.target.copy(center);
controls.update();
}
function downloadSnapshot() {
const link = document.createElement("a");
link.download = "cad-building-showcase.png";
link.href = renderer.domElement.toDataURL("image/png");
link.click();
}
window.addEventListener("pointerdown", (event) => {
pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObjects(objectRegistry, true)[0];
if (!hit) {
inspect.querySelector(".inspect-title").textContent = "未选择";
inspect.querySelector(".inspect-body").textContent = "点击模型中的楼层或构件类型";
return;
}
const object = objectRegistry.find((mesh) => mesh === hit.object || mesh.children.includes(hit.object));
if (!object) return;
inspect.querySelector(".inspect-title").textContent = object.userData.label;
inspect.querySelector(".inspect-body").textContent = `楼层 ${object.userData.floor} / 类别 ${object.userData.category}`;
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
function animate() {
requestAnimationFrame(animate);
controls.update();
renderer.render(scene, camera);
}
animate();

View File

@@ -0,0 +1,103 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{{TITLE}}</title>
<link rel="stylesheet" href="./styles.css" />
<script type="importmap">
{
"imports": {
"three": "./node_modules/three/build/three.module.js",
"three/addons/": "./node_modules/three/examples/jsm/"
}
}
</script>
</head>
<body>
<main id="app-shell">
<canvas id="scene"></canvas>
<section class="panel project-panel" aria-label="项目">
<div class="project-title">
<span class="mark"></span>
<div>
<h1 id="project-name">CAD 建筑模型</h1>
<p id="project-description">Web 展示模型</p>
</div>
</div>
<dl class="stats-grid" id="stats"></dl>
</section>
<section class="panel controls-panel" aria-label="控制">
<div class="control-group">
<div class="group-label">楼层</div>
<div class="segmented" id="floor-controls"></div>
</div>
<div class="control-group">
<div class="group-label">构件</div>
<div class="toggle-grid" id="category-controls"></div>
</div>
<div class="control-group">
<div class="group-label">下载</div>
<div class="download-list" id="download-controls"></div>
</div>
<div class="control-group">
<label class="range-row">
<span>楼层展开</span>
<output id="explode-value">0m</output>
</label>
<input id="explode" type="range" min="0" max="16" value="0" step="0.5" />
</div>
<div class="control-group">
<label class="range-row">
<span>剖切高度</span>
<output id="section-value">关闭</output>
</label>
<input id="section" type="range" min="0" max="24" value="24" step="0.25" />
</div>
</section>
<nav class="toolbar" aria-label="视图工具">
<button class="tool-button" data-preset="overview" title="总览" aria-label="总览">
<i data-lucide="home"></i>
</button>
<button class="tool-button" data-preset="top" title="顶视" aria-label="顶视">
<i data-lucide="scan"></i>
</button>
<button class="tool-button" data-preset="side" title="侧视" aria-label="侧视">
<i data-lucide="panel-top"></i>
</button>
<button class="tool-button" id="auto-rotate" title="自动旋转" aria-label="自动旋转">
<i data-lucide="rotate-3d"></i>
</button>
<button class="tool-button" id="reset-view" title="重置视角" aria-label="重置视角">
<i data-lucide="rotate-ccw"></i>
</button>
<button class="tool-button" id="snapshot" title="截图" aria-label="截图">
<i data-lucide="camera"></i>
</button>
<a class="tool-button" href="./model.glb" download title="下载 GLB" aria-label="下载 GLB">
<i data-lucide="download"></i>
</a>
</nav>
<section class="panel inspect-panel" id="inspect" aria-label="选择">
<div class="inspect-title">未选择</div>
<div class="inspect-body">点击模型中的楼层或构件类型</div>
</section>
<div class="loading" id="loading">
<div class="loading-bar"><span id="loading-fill"></span></div>
<div id="loading-text">加载模型</div>
</div>
</main>
<script src="./node_modules/lucide/dist/umd/lucide.js"></script>
<script type="module" src="./app.js?v={{BUILD}}"></script>
</body>
</html>

View File

@@ -0,0 +1,10 @@
{
"name": "cad-building-showcase-viewer",
"version": "1.0.0",
"private": true,
"type": "module",
"dependencies": {
"lucide": "0.468.0",
"three": "0.181.2"
}
}

View File

@@ -0,0 +1,313 @@
:root {
color-scheme: dark;
--bg: #272a2d;
--panel: rgba(246, 244, 236, 0.92);
--panel-dark: #202326;
--ink: #151719;
--muted: #65707b;
--line: rgba(21, 23, 25, 0.14);
--accent: #2f7d70;
--blue: #2e5f9f;
--shadow: 0 18px 45px rgba(0, 0, 0, 0.24);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
html,
body,
#app-shell {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
}
body {
background: var(--bg);
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
}
.panel {
position: fixed;
border: 1px solid rgba(255, 255, 255, 0.42);
border-radius: 8px;
background: var(--panel);
color: var(--ink);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
}
.project-panel {
top: 20px;
left: 20px;
width: min(360px, calc(100vw - 40px));
padding: 16px;
}
.project-title {
display: grid;
grid-template-columns: 12px minmax(0, 1fr);
gap: 12px;
align-items: center;
}
.mark {
width: 12px;
height: 44px;
border-radius: 3px;
background: linear-gradient(180deg, #2f7d70, #c58b2c);
}
h1 {
margin: 0;
color: var(--ink);
font-size: 19px;
line-height: 1.2;
letter-spacing: 0;
}
p {
margin: 4px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.35;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
margin: 14px 0 0;
}
.stats-grid div {
min-width: 0;
padding: 8px;
border-radius: 6px;
background: rgba(255, 255, 255, 0.58);
border: 1px solid var(--line);
}
.stats-grid dt {
color: var(--muted);
font-size: 11px;
}
.stats-grid dd {
margin: 3px 0 0;
color: var(--ink);
font-size: 14px;
font-weight: 700;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.controls-panel {
left: 20px;
bottom: 20px;
width: min(384px, calc(100vw - 40px));
padding: 14px;
}
.control-group + .control-group {
margin-top: 13px;
padding-top: 13px;
border-top: 1px solid var(--line);
}
.group-label,
.range-row {
margin-bottom: 8px;
color: var(--muted);
font-size: 12px;
font-weight: 700;
}
.range-row {
display: flex;
justify-content: space-between;
margin-bottom: 8px;
}
.segmented,
.toggle-grid,
.download-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.toggle {
min-height: 32px;
display: inline-flex;
align-items: center;
gap: 7px;
padding: 6px 9px;
border: 1px solid var(--line);
border-radius: 6px;
background: rgba(255, 255, 255, 0.58);
color: var(--ink);
font-size: 12px;
font-weight: 700;
cursor: pointer;
user-select: none;
}
.toggle input {
width: 13px;
height: 13px;
accent-color: var(--accent);
}
.swatch {
width: 11px;
height: 11px;
border-radius: 50%;
border: 1px solid rgba(0, 0, 0, 0.2);
}
.download-link {
min-height: 32px;
display: inline-flex;
align-items: center;
padding: 6px 10px;
border: 1px solid var(--line);
border-radius: 6px;
background: rgba(255, 255, 255, 0.58);
color: var(--ink);
font-size: 12px;
font-weight: 800;
text-decoration: none;
}
.download-link:hover {
background: rgba(47, 125, 112, 0.16);
}
input[type="range"] {
width: 100%;
accent-color: var(--blue);
}
.toolbar {
position: fixed;
right: 20px;
top: 20px;
display: flex;
gap: 8px;
padding: 8px;
border-radius: 8px;
background: rgba(32, 35, 38, 0.86);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
}
.tool-button {
width: 40px;
height: 40px;
display: grid;
place-items: center;
border: 1px solid rgba(255, 255, 255, 0.16);
border-radius: 7px;
background: rgba(255, 255, 255, 0.08);
color: #f4f3ef;
cursor: pointer;
text-decoration: none;
}
.tool-button:hover,
.tool-button.active {
background: #2f7d70;
}
.tool-button svg {
width: 19px;
height: 19px;
}
.inspect-panel {
right: 20px;
bottom: 20px;
width: min(300px, calc(100vw - 40px));
padding: 14px;
}
.inspect-title {
font-size: 14px;
font-weight: 800;
}
.inspect-body {
margin-top: 5px;
color: var(--muted);
font-size: 12px;
line-height: 1.4;
}
.loading {
position: fixed;
inset: 0;
display: grid;
place-items: center;
gap: 12px;
align-content: center;
background: rgba(39, 42, 45, 0.82);
color: #f6f4ec;
font-size: 13px;
}
.loading.hidden {
display: none;
}
.loading-bar {
width: min(320px, 76vw);
height: 6px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.22);
}
.loading-bar span {
display: block;
width: 12%;
height: 100%;
background: #d1a445;
}
@media (max-width: 760px) {
.project-panel {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
}
.toolbar {
top: auto;
right: 10px;
bottom: 10px;
}
.controls-panel {
left: 10px;
bottom: 72px;
width: calc(100vw - 20px);
max-height: 43vh;
overflow: auto;
}
.inspect-panel {
display: none;
}
}

View File

@@ -0,0 +1,118 @@
# A208 Case Notes
These notes capture the proven workflow from the A208 CAD-to-3D exploration. Use them as calibration, not as hardcoded constants.
## Source Set
The test project used 11 DWG floor-plan drawings from an XREF folder:
- A202 basement
- A205 basement mezzanine
- A208 main building 1F/2F
- A209 main building 3F/4F
- A210 main building 5F/6F
- A211 main building 7F/8F
- A212 main building roof
- A213 auxiliary building 1F
- A214 auxiliary building mezzanine
- A215 auxiliary building 2F
- A216 auxiliary building roof
DWG versions were AutoCAD 2004/2007-era files.
## Conversion and Reading
- FreeCAD 1.0.2 CLI existed at `/Applications/FreeCAD.app/Contents/Resources/bin/freecadcmd`.
- FreeCAD DXF import was brittle on LibreDWG-generated DXF because of `999` comment records and unsupported CAD entities such as `HATCH`, `VIEWPORT`, and `DIMENSION`.
- `libredwg` `dwg2dxf` plus `ezdxf` was the robust read path.
- Sanitizing DXF `999` comment pairs made files more compatible with other importers.
## Useful Layer Signals
For A208, useful layers included:
- `I-WALL`, `A-WALL`, `L-SITE-WALL`: walls
- `S-COLS`: columns
- `S-STRS`, `S-STRS-MBND`: beams/structure
- `A-FLOR`, `A-FLOR-OVHD`: floor detail
- `S-GRID`: structural grid
Avoid treating dimensions, hatches, text, and annotation layers as 3D geometry unless the goal is a drawing overlay.
## A208 Split and Alignment
A208 placed 1F and 2F side by side in one drawing. The working split used x=0 in source millimeter coordinates:
- Left side: 1F
- Right side: 2F
- 2F alignment shift: about `-158029.255 mm` in X
This shift was inferred from grid/plan alignment. It should not be reused for other drawings without checking grids.
## Extraction Details That Improved Quality
The A208-specific script handled:
- `LINE`
- `ARC`
- `CIRCLE`
- `LWPOLYLINE`
- `SPLINE`
It also used category-specific minimum segment lengths:
- walls: `0.25 m`
- columns: `0.18 m`
- beams: `0.35 m`
- floor lines: `0.40 m`
- grid: `1.0 m`
This filtered CAD noise better than one global line-length threshold.
## Showcase Model Result
The A208 massing/showcase model contained:
- floors: 2
- Blender scene objects: 17
- GLB and preview render generated successfully
- Web viewer verified on desktop and mobile
- Web controls verified: floor toggles, category toggles, explode slider, section slider, camera presets, screenshot, GLB download
This is best described as Web showcase / LOD100-150-like massing visualization, not BIM.
## Full-Building Presentation Calibration
The later full-building run expanded the workflow from a two-floor proof to a multi-floor Web presentation model. Treat these as calibration decisions, not constants:
- Use `generate_footprints: true`, `use_footprint_slabs: true`, and `use_footprint_roofs: true` when the user expects a complete interior/exterior presentation.
- Include `columns` in `footprint_categories` when column rows define platform or podium extents that wall/glazing linework misses.
- Keep `slab` enabled by default for presentation/digital-twin views. Use a display `slab_thickness` around `0.35-0.40 m`, double-sided Web materials, and opacity high enough that slab edges read through glazing.
- Keep in-scene floor labels/text off by default; CAD text-like transparent planes clutter the model and are not needed when the Web UI already names floors.
- For generated roof caps, use the roof floor's own `footprint_from` source. Broadly unioning lower floor footprints can create roof plates that protrude into empty areas.
- For 1F/podium columns, require an upper plate plus nearby upper structure before keeping them full height. Shorten unsupported display columns unless there is CAD evidence that they are freestanding architectural elements.
- Produce three Web variants for delivery: `overview` for fast browsing, `standard` as the default visible model, and `detail` for extraction review.
## IFC Proof Result
The IFC proof generated:
- `IfcBuildingStorey`: 2
- `IfcSlab`: 2
- `IfcWall`: 320
- `IfcColumn`: 160
- `IfcBeam`: 160
- `IfcPropertySet`: 643
- `IfcExtrudedAreaSolid`: 642
Geometry extraction succeeded with zero failures in the tested run. This validates a BIM-feasibility route, but still does not prove production BIM replacement.
## Blender IFC Viewing
The tested Blender 5.1.1 environment did not have a direct IFC import operator or Bonsai/BlenderBIM installed. The working visualization route was:
1. Generate IFC with IfcOpenShell.
2. Extract IFC product geometry with IfcOpenShell.
3. Render extracted meshes in Blender.
Use Bonsai/BlenderBIM only when installed and compatible with the current Blender Python version.

View File

@@ -0,0 +1,59 @@
# Agent Review Checklist
Use this checklist after `building_spec.json`, extraction audit, and overlay SVGs exist.
## Accept for Web Showcase
Accept when:
- Main floor outlines, walls, columns, beams, floor detail, and grid are visible in overlays.
- Unclassified geometry is mostly annotation, dimensions, text, furniture, landscaping, or detail symbols.
- High-risk `INSERT`/`HATCH` entities are either irrelevant or visually accounted for by extracted linework.
- Blender preview is nonblank, correctly framed, and visually matches the floor-plan intent.
- Web viewer loads with clean console logs and controls work.
- Presentation/digital-twin views show readable slab edges from side views; floor plates do not disappear behind glazing.
- Generated roofs use roof-floor footprints unless CAD evidence supports a canopy/overhang.
- Ground/podium columns that have no upper plate plus nearby upper structure are shortened or documented as intentional.
- Web delivery exposes overview, standard, and detail GLB downloads when lightweight variants were requested.
State known gaps in the notes.
## Iterate Extraction
Return to config or parser work when:
- Red dashed overlay geometry forms obvious walls, columns, beams, grids, stairs, or slab outlines.
- A large unclassified layer has high supported vector length and architectural names.
- Frequent `INSERT` blocks likely contain architectural geometry.
- `HATCH` or `SOLID` represents primary filled walls/columns and line extraction missed it.
- Multiple floors are misaligned after overlay/Blender review.
- Generated slabs are much larger/smaller than the true building footprint.
- Slabs are technically present but visually unreadable from side views.
- Generated roof caps extend across unrelated lower-floor footprints.
- Many columns stand full-height with no upper floor/roof or nearby upper structural support.
- Web/digital-twin output has only one heavy GLB when the user requested lightweight download tiers.
## Escalate Beyond Line Extraction
Use additional strategies when needed:
- Recursive block expansion for `INSERT`.
- Hatch boundary extraction for filled wall/slab/column regions.
- OCR/title-block reading for floor labels when filenames are ambiguous.
- Manual floor split rectangles for complex sheet layouts.
- Footprint tuning with wall/glazing/floor-line/railing/column source categories.
- Variant generation with `build_showcase_variants.py` before writing the Web viewer.
- IFC/BIM generation only after extracted geometry passes showcase-level review.
## BIM Claim Rules
Never call the Web showcase a BIM replacement.
Call it an IFC/BIM proof only when:
- IFC entities exist with storeys and spatial containment.
- `IfcWall`, `IfcColumn`, `IfcBeam`, `IfcSlab` counts are reported.
- IfcOpenShell geometry generation succeeds or failures are explained.
- Remaining gaps are listed: openings, rooms/spaces, doors/windows, quantities, materials, classifications, georeferencing, and coordination.
Call it a BIM replacement candidate only after discipline-specific semantic validation, quantity validation, and human review.

View File

@@ -0,0 +1,182 @@
# building_spec.json Schema
Use `building_spec.json` as the contract between CAD extraction, Blender generation, and the Web showcase.
## Top Level
```json
{
"project": {
"name": "Project name",
"description": "Short user-facing description"
},
"source": {
"cad_folder": "work/XREF",
"report": "outputs/cad_read_report.json",
"config": {
"generate_footprints": true,
"use_footprint_slabs": true,
"use_footprint_roofs": true,
"footprint_categories": ["walls", "glazing", "floor_lines", "railings", "columns"],
"slab_thickness": 0.38,
"default_disabled_categories": []
}
},
"units": {
"source": "millimeters",
"scale_to_meters": 0.001,
"origin_source": [0.0, 0.0]
},
"categories": {
"walls": {"label": "墙体", "color": "#d4cbb8"},
"glazing": {"label": "玻璃/幕墙", "color": "#79b8c9"},
"roof": {"label": "屋顶/屋盖", "color": "#b8ae98"},
"columns": {"label": "柱", "color": "#f58a1f"},
"beams": {"label": "梁/结构", "color": "#1f66c2"},
"railings": {"label": "栏杆/扶手", "color": "#6f746d"},
"doors": {"label": "门/开启线", "color": "#8a6a45"},
"detail_lines": {"label": "平面细节", "color": "#8c9088"},
"floor_lines": {"label": "楼面线", "color": "#18a058"},
"grid": {"label": "轴网", "color": "#20242a"},
"slab": {"label": "楼板", "color": "#c8ccc2"}
},
"floors": {
"1F": {
"name": "首层",
"z": 0.0,
"height": 4.2,
"bounds": [0.0, 0.0, 80.0, 42.0],
"source_file": "A208.dxf",
"footprint": {
"method": "concave_hull",
"source_categories": ["walls", "glazing", "floor_lines", "railings", "columns"],
"area": 3120.4,
"polygons": [
[[0.0, 0.0], [80.0, 0.0], [80.0, 42.0], [0.0, 42.0]]
]
},
"segments": {
"walls": [],
"glazing": [],
"roof": [],
"columns": [],
"beams": [],
"railings": [],
"doors": [],
"detail_lines": [],
"floor_lines": [],
"grid": []
}
}
}
}
```
## Segment Shape
Each segment is a straight prism centerline in meters:
```json
{
"start": [12.0, 3.5],
"end": [18.0, 3.5],
"width": 0.2,
"layer": "I-WALL",
"source_type": "LINE"
}
```
Use short chord segments for polylines and arcs. The showcase model does not need exact NURBS/curve preservation unless the user asks for close-up modeling.
`derive_showcase_spec.py` supports `LINE`, `LWPOLYLINE`, `POLYLINE`, `ARC`, `CIRCLE`, and `SPLINE` by converting curves into short line segments. Configure curve density with `curve_chord_source_length`.
It can also expand `INSERT` blocks when the Agent enables `expand_blocks`. Keep the block expansion decision in the config so the final notes can explain whether block geometry was used.
## Category Semantics
- `walls`: vertical extrusions from floor `z` to `z + height`. Include architectural wall layers and obvious site/partition wall layers.
- `glazing`: transparent full-height extrusions for curtain wall, window wall, or glass layers. Keep separate from opaque walls so missing walls are not confused with glass.
- `roof`: opaque or near-opaque cover geometry for roof slabs, canopies, or generated roof caps. It may be generated from `roof_specs` instead of direct CAD roof line segments when roof drawings are sparse.
- `columns`: vertical extrusions from floor `z` to `z + height`. For CAD outlines, extrude the visible outline linework rather than trying to infer a single solid column unless the source is clean.
- `beams`: horizontal extrusions near the floor ceiling, normally `z + height - beam_drop` to `z + height`.
- `railings`: low vertical extrusions, normally about 1.1-1.2 m above the floor.
- `doors`: door leaf/opening arcs and swing lines, normally about 2.1-2.3 m above the floor for visual context.
- `detail_lines`: low plan strips for generic details, parking, area, thin detail, and other high-value linework that should remain visible without being misclassified as vertical walls.
- `floor_lines`: low visual strips just above the slab. Use for floor finish edges and important plan guide lines that are not better represented by a specific category.
- `grid`: thin low strips. Use for axes/control grid only; keep toggleable.
- `slab`: generated by Blender script from each floor `footprint.polygons` when present, otherwise from `bounds`. A footprint slab is a CAD-derived visual plate, not a validated BIM slab with openings, joins, quantities, or fire/acoustic properties.
## Footprint Shape
`derive_showcase_spec.py` can generate `floor.footprint` when the Agent enables footprint generation in the extraction config.
- `method`: usually `concave_hull`.
- `source_categories`: categories used to collect source points, commonly `walls`, `glazing`, `floor_lines`, `railings`, and `columns`.
- `area`: total footprint polygon area in square meters after simplification.
- `polygons`: one or more closed polygon rings in meters. Keep only high-confidence, high-area polygons; do not include annotation islands or tiny hatch fragments.
Blender uses these polygons for generated `slab` meshes and can also use them for generated roof/roof-cap meshes. This improves visual accuracy compared with rectangular bounds but is still a presentation approximation unless BIM semantics are generated separately.
## Generation Config Keys
Common `source.config` keys used by `derive_showcase_spec.py` and `build_blender_showcase.py`:
- `generate_footprints`: enables CAD-derived `floor.footprint`.
- `footprint_categories`: source segment categories for footprints. For presentation models, include `columns` when column rows define usable floor plate extents.
- `footprint_concave_ratio`, `footprint_simplify_tolerance`, `footprint_min_area`, `footprint_max_polygons`: tune the concave hull and remove noise.
- `use_footprint_slabs`: use `floor.footprint.polygons` instead of rectangular `bounds` for generated `slab`.
- `use_footprint_roofs`: allow `roof_specs[].footprint_from` polygons to drive generated roof caps.
- `slab_thickness`: display thickness in meters. Use about `0.35-0.40` for Web presentation so floor edges remain visible through glazing.
- `roof_specs[]`: generated roof/canopy definitions. Use `floor_key`, `bounds_from`, and `footprint_from`; do not union lower-floor footprints unless there is CAD evidence for an overhang.
- `shorten_unsupported_columns`: shortens display columns that have no upper support.
- `shorten_unsupported_columns_floor_keys`: optional floor-key filter, commonly ground or podium levels.
- `unsupported_column_height`: shortened display height in meters.
- `column_support_distance`: XY tolerance for matching upper structural support.
- `column_support_requires_upper_plate`: require an adjacent upper floor/roof footprint before accepting nearby upper structure as support.
- `column_support_allow_plate_only`: if true, an upper plate alone is enough support; leave false when broad footprints would keep too many isolated columns.
## Object Naming
Blender objects for Web output must use:
```text
<floor_key>__<category>
```
Examples:
- `1F__walls`
- `RF__roof`
- `B1__columns`
- `RF__grid`
The Web template parses this double-underscore pattern.
## Metadata
`build_blender_showcase.py` writes `model_metadata.json` for the Web viewer. Keep it aligned with `building_spec.json` and include:
- project name/description
- ordered floors with keys/names/z values
- category labels/colors
- model bounds
- generated file names
- optional `viewer_defaults.disabled_categories`; keep `slab` enabled for presentation/digital-twin views
- optional `model_variants`, normally written by `write_web_showcase.py` from `variants_manifest.json`, for example:
```json
[
{"key": "overview", "label": "总览轻量版", "file": "overview.glb"},
{"key": "standard", "label": "展示标准版", "file": "standard.glb"},
{"key": "detail", "label": "完整审图版", "file": "detail.glb"}
]
```
## Precision Labels
Use these labels in notes:
- `Web showcase`: visual architectural walkthrough/exploded diagram from CAD linework.
- `Massing/LOD100-150`: slabs, walls, columns, beams, floor lines, grid; not parametric BIM.
- `BIM proof`: IFC entities exist and validate, but may not be production BIM.
- `BIM replacement candidate`: only after semantic IFC, openings, spaces, quantities, materials, levels, and coordination checks pass.

View File

@@ -0,0 +1,112 @@
# Skill 优化建议(来自主辅楼建筑群 11 张图实战复盘)
本文记录在一次完整实战(A202/A205/A208–A213 共 11 张 CAD 平面图 → 轻量化 Web 展示模型)中暴露的问题与已验证的修复,作为对 skill 脚本与模板的具体改进建议。修复均已在该项目落地验证。
---
## 0. 一句话结论
- **轻量化的关键 = Draco 压缩 + 查看器挂 DRACOLoader(成对)**,实测体积 ~3–4MB → ~0.4–0.6MB(−92%)。
- **最该修的潜在 bug = glTF 上方向约定不统一**(模板按 Z-up 写,Blender 默认导出 Y-up),会让建筑“躺倒”。
- 几何完整性(块内幕墙、玻璃连续、柱头封顶、地下室顶板)需要新增专门步骤,CAD 平面图本身不会自动给出这些。
---
## 1. 轻量化(最高优先级)
### 1.1 GLB 压缩(`build_blender_showcase.py`)
现状是裸导出:
```python
bpy.ops.export_scene.gltf(filepath=str(glb_path), export_format="GLB")
```
建议二选一:
- Blender 自带 Draco:`export_draco_mesh_compression_enable=True, export_draco_mesh_compression_level=6`。
- 更彻底(推荐):导出后跑 `gltf-transform`,顺序 `weld → dedup → prune → draco(quantizePosition=14, quantizeNormal=10, quantizeGeneric=12)`。本项目用的 node 脚本见 `tools/compress.mjs`(可随 skill 附带)。
### 1.2 查看器必须挂解码器(`assets/web-showcase-template/app.js`)
模板只有 `new GLTFLoader()`,压了 Draco 会**直接加载失败**。补:
```js
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath("./node_modules/three/examples/jsm/libs/draco/"); // three 自带,离线可用
loader.setDRACOLoader(dracoLoader);
```
`npm install three` 已含解码器 wasm,无需 CDN。
### 1.3 变体即 LOD
overview/standard/detail 按构件类别过滤(现有机制即可),默认 standard。若要再轻,可对 overview 做几何减面(当前仅图层过滤,不是真减面)。
---
## 2. 上方向约定(潜在严重 bug,强烈建议修)
模板 `app.js` 通篇按 **Z 为上**写:`group.position.z`(楼层展开)、`new THREE.Plane(new THREE.Vector3(0,0,-1))`(剖切)、相机 `center.z + maxSize`。但 `bpy.ops.export_scene.gltf` 默认 `export_yup=True`,导出的是 **Y-up**。两者不一致 → 建筑在 three / Blender / 任何标准查看器里**躺倒**。
**建议锁死标准 Y-up:**
- GLB 保持 Y-up(Blender 默认即可;纯 Python 后端需显式把 Z-up 旋到 Y-up:`(x,y,z)->(x,z,-y)`)。
- 查看器:
- `camera.up.set(0,1,0)`(否则 OrbitControls 的 `maxPolarAngle` 会把相机钳在近水平轨道,**俯视/鸟瞰放不开**——这是另一个隐藏坑)。
- 剖切面法线 `(0,-1,0)`;楼层展开走 `.y`;相机预设 top/side/overview 按 Y-up 重写。
---
## 3. 几何完整性(CAD 平面图 → 体量模型新增步骤)
### 3.1 块内几何要定向展开(已升级为按图层探测)
幕墙/门窗常封装在 INSERT 块里。本项目玻璃在 `系统嵌板 - SZ_玻璃…`、`幕墙平拼…` 块内,展开后落在图层 `A-GLAZ-CURT`。按块名定向展开(`["*幕墙*","*玻璃*","*嵌板*","*GLAZ*","*CURT*"]`)是第一道防线,但实战证明**块名匹配不可靠**:
- DWG→DXF 转换会损坏中文块名(`系统嵌板`→`系统嵌`、`偏移`→`偏`),模式匹配不上;
- 幕墙嵌板常套在排版/包裹块里,父块名不命中就永远扫不到内层。
`derive_showcase_spec.py` 现已内置**按块内实体图层分类**(`classify_block_contents`,默认开):展开所有 INSERT 到 `expand_blocks_max_depth`,只保留自身图层能归类到 `block_content_categories`(默认 glazing/railings/doors)的子实体。配套的 `audit_showcase_extraction.py` 增加了:
- **块内锁定几何统计**(与配置无关的全量展开核算),96% 覆盖率再也藏不住整面幕墙缺失;
- **glazing 硬门禁**:图中存在幕墙证据(块内玻璃图层长度 / 幕墙命名块)而 spec glazing=0 时审计直接 FAIL(exit 3)。
另外 `*-IDEN` 标识图层(`A-DOOR-IDEN` 等)默认排除出分类(`exclude_layers`),门标号不再被当成门几何;`cad_dxf_report.py` 会在建模前对 XREF 空壳图(如本项目 A212/A214/A215/A216)输出 `likely_xref_shell` 警告。回归测试见 `tests/test_extraction_pipeline.py`。
### 3.2 立面玻璃连续化
CAD 把幕墙画成稀疏分格板(实测 8F:1.42m 板 / 每 4.5m 一块 / 中间 3.08m 空)。逐段挤出 = 隔空竖条。需做**共线合并 + 桥接窗间缝**:按 (角度, 垂距) 分组,沿线方向合并区间,`gap_tol` 取得比窗间缝大(本项目 3.6m)即连成整条玻璃带。注意先确认缝里**没有墙**(本项目实测该立面墙长 0m)再桥接,避免把实墙盖成玻璃。
### 3.3 柱头封顶(比 `shorten_unsupported_columns` 更好)
现有的“无支撑柱缩短”会产生突兀的 1.2m 矮柱。更自然的做法是**生成盖板**:
- 地上退台层:`cap = 本层footprint(外扩~1.3m) − 上层footprint`,在 `z+h` 处挤薄板(退台屋面/雨棚)。外扩是为了盖住凹包络切掉的外圈柱廊柱。
- **地下室顶层**:直接把整层 footprint 在 z=0 封成地面/顶板(停车区上方的地坪)。
- 顶层(8F)/辅楼顶:用现有 `roof_specs` 屋顶盖。
### 3.4 ⚠ `floor_group` 的 bug
`build_blender_showcase.py` 的 `floor_group()` 把 `B1/B1M` 归 BASE、地上归 MAIN、`AUX_` 归 AUX,柱支撑/封顶只在**同组**内找上层。结果:**地下室顶层(B1M)永远找不到地上的 1F 作为上层,拿不到顶板**——本项目 983 根地下柱有 397 根(40%)露顶。修复:地下室顶层特判为“整层封顶”,或允许跨组找上方 footprint。
---
## 4. 健壮性
- 生成的盖板(shapely 差集)可能产生退化/狭长面 → 法线 NaN → Blender 导入报 `Bad glTF: json contained NaN`。导出前必须:**丢弃零面积面**(`area>1e-9`)+ **钳 NaN/Inf 法线**(置默认向上)。
- 检查顶点 `isfinite`,跳过非法网格。
---
## 5. 验证 / QA(应做成标准动作)
这次定位问题全靠这些,建议固化进 skill 验证步骤:
- **正交立面 + 顶视渲染**:一眼看出整层缺失、躺倒、退台是否合理。
- **覆盖率叠合图**(`draw_coverage_overlay.py` 已有):红虚线=未提取,客观回答“是否缺料”。本项目支持长度覆盖率 96%。
- **量化报告**:柱头封顶率、玻璃连续段数变化、各变体 GLB 体积预算(如 overview ≤ 0.5MB)。
- **早验证原则**:生成后立即开查看器/渲立面再下结论。本次迭代 8 版的主要原因是“先猜后验”(误判朝向、误判窗间缝是墙),早点眼见为实可省大量来回。
---
## 6. 环境 / 可移植性
- skill 硬依赖 Blender + `dwg2dxf`;受限沙箱(无 root、无 Blender、PyPI 无 bpy)两者皆无。建议:
1. 文档明确宿主机前置条件;
2. 提供**纯 Python 后端**(`trimesh` + `gltf-transform`)作为无 Blender 的可移植替代——本项目即用它跑通全流程(见 `spec_to_glb.py`),且天然产出轻量化 GLB;
3. 无转换器时优雅回退到“请用户提供 DXF”。
- Web 输出加 **cache-busting(`?v=` 或内容哈希)+ 可见构建版本号**:浏览器对 ES 模块/GLB 缓存极顽固,否则用户刷新看不到更新(本次踩坑多轮)。
---
## 7. 可直接并入 skill 的产物
本项目沉淀、建议提升为 skill 资源:
- `spec_to_glb.py`:无 Blender 的 spec→GLB 导出器(含 z 窗口、segment 棱柱、footprint 楼板、玻璃共线合并、退台/地下封顶、Y-up、NaN 清洗、`楼层__类别` 命名)。
- `tools/compress.mjs`:gltf-transform Draco 压缩脚本。
- `app.js` 的 DRACOLoader + Y-up 改动。

347
references/pipeline.md Normal file
View File

@@ -0,0 +1,347 @@
# CAD to Web Building Showcase Pipeline
## 1. Inventory and Conversion
Start by listing source files and preserving names. CAD drawing names often encode floor numbers, building zones, and drawing type.
Recommended workspace layout:
```text
work/
cad_showcase/
dxf_raw/
dxf_sanitized/
reports/
building_spec.json
outputs/
<project>/
<project>.blend
<project>.glb
<project>.png
web/
```
For DWG conversion:
```bash
dwg2dxf -y -o work/cad_showcase/dxf_raw/A208.dxf "work/XREF/A208 - 主楼首层、二层平面图.dwg"
```
LibreDWG DXF files may contain `999` comment records. Sanitize before using brittle importers. `ezdxf.recover` usually tolerates them, but sanitizing keeps the files friendlier to FreeCAD and other tools.
## 2. CAD Read Report
Run:
```bash
python3 <skill>/scripts/cad_dxf_report.py --input work/XREF --work work/cad_showcase --output outputs/cad_read_report
```
If `ezdxf` is missing:
```bash
python3 -m pip install --target work/vendor ezdxf
```
Read the report and identify:
- Which drawings are plans versus elevations/details.
- Whether the unit scale is probably millimeters or meters.
- Main modelspace bounding boxes.
- Layer counts and top layers.
- Entity types that matter: `LINE`, `LWPOLYLINE`, `POLYLINE`, `INSERT`, `HATCH`, `TEXT`, `MTEXT`, `DIMENSION`.
## 3. Layer Mapping
Default layer heuristics:
| Category | Common layer names |
| --- | --- |
| walls | `I-WALL`, `A-WALL`, `L-SITE-WALL`, names containing `WALL`, `墙` |
| glazing | `A-GLAZ*`, names containing `GLAZ`, `CURT`, `WINDOW`, `幕墙`, `玻璃`, `窗` |
| roof | `A-ROOF`, `A-FLOR-ROOF`, `A-FLOR-OVHD`, names containing `ROOF`, `屋面`, `屋顶`, `雨棚` |
| columns | `S-COLS`, names containing `COL`, `COLUMN`, `柱` |
| beams | `S-STRS`, `S-STRS-MBND`, names containing `BEAM`, `梁`, `结构` |
| railings | names containing `RAIL`, `HANDRAIL`, `栏杆`, `扶手` |
| doors | names containing `DOOR`, `DR`, `门`, `开启` |
| detail_lines | `A-GENM`, `A-DETL*`, parking/area/detail layers that should stay as low plan context |
| floor_lines | `A-FLOR`, `A-FLOR-OVHD`, names containing `FLOOR`, `FLOR`, `楼面`, `地面` |
| grid | `S-GRID`, names containing `GRID`, `轴网`, `轴线` |
Do not include annotation/dimension/text layers in geometry categories unless the user wants a drawing-like overlay.
## 4. Floor Detection and Alignment
Many architectural sheets place multiple floor plans side by side. Do not assume one DWG equals one floor.
Use this order of evidence:
1. File name and drawing title.
2. Text labels in modelspace/paperspace.
3. Large separated plan clusters in the drawing bounding box.
4. `S-GRID` or equivalent structural axis layers.
5. Repeated column/grid patterns across floors.
For side-by-side plans, create a config with one `floors[]` entry per floor, each with a source `clip` rectangle and optional `offset`.
Example:
```json
{
"project_name": "Main Building",
"scale": 0.001,
"origin_strategy": "center",
"floor_height": 4.2,
"curve_chord_source_length": 750,
"expand_blocks": false,
"expand_blocks_max_depth": 2,
"block_insert_layer_fallback": true,
"generate_footprints": true,
"use_footprint_slabs": true,
"use_footprint_roofs": true,
"footprint_categories": ["walls", "glazing", "floor_lines", "railings", "columns"],
"footprint_concave_ratio": 0.85,
"footprint_simplify_tolerance": 0.12,
"slab_thickness": 0.38,
"default_disabled_categories": [],
"shorten_unsupported_columns": true,
"shorten_unsupported_columns_floor_keys": ["1F"],
"unsupported_column_height": 1.2,
"column_support_distance": 0.55,
"column_support_requires_upper_plate": true,
"column_support_allow_plate_only": false,
"block_name_categories": {
"walls": ["*WALL*", "*墙*"],
"glazing": ["*GLAZ*", "*CURT*", "*幕墙*", "*玻璃*"],
"columns": ["*COL*", "*柱*"],
"beams": ["*BEAM*", "*梁*"]
},
"min_length_meters_by_category": {
"walls": 0.25,
"columns": 0.18,
"beams": 0.35,
"floor_lines": 0.40,
"grid": 1.0
},
"drawings": [
{
"file": "A208.dxf",
"split_x": 0,
"floors": [
{"key": "1F", "name": "首层", "side": "left"},
{"key": "2F", "name": "二层", "side": "right", "offset": [-158029.255, 0]}
]
}
],
"layers": {
"walls": ["I-WALL", "A-WALL", "L-SITE-WALL"],
"glazing": ["A-GLAZ*"],
"roof": ["A-ROOF", "A-FLOR-ROOF"],
"columns": ["S-COLS"],
"beams": ["S-STRS", "S-STRS-MBND"],
"railings": ["*RAIL*"],
"doors": ["*DOOR*", "*DR*"],
"detail_lines": ["A-GENM", "A-DETL*", "*PRKG*", "A-AREA"],
"floor_lines": ["A-FLOR", "A-FLOR-OVHD"],
"grid": ["S-GRID"]
},
"roof_specs": [
{
"floor_key": "RF",
"bounds_from": ["RF"],
"footprint_from": ["RF"],
"thickness": 0.35,
"margin": 0.4
}
]
}
```
In the A208 test project, 1F and 2F were on the same sheet and the second floor required an X shift of about `-158029.255 mm` to align the grids. Treat this as an example, not a constant.
Use `origin_strategy: "center"` for large CAD coordinates. It mirrors the A208 proven workflow and keeps Blender/Web coordinates numerically stable.
Use `clip` rectangles for irregular sheet layouts. Use `split_x` plus `side` when a sheet cleanly places plans left/right; this is less likely to accidentally cut off geometry than a tight clip rectangle.
Keep `expand_blocks` false for the first pass. If the audit shows important geometry in `INSERT`, set `expand_blocks` to `true` or to a list of block-name patterns, then rerun extraction/audit/overlays. When virtual block entities live on layer `0`, `block_insert_layer_fallback: true` lets the parent INSERT layer participate in category matching.
## 5. Spec Extraction
Run:
```bash
python3 <skill>/scripts/derive_showcase_spec.py --dxf-dir work/cad_showcase/dxf_sanitized --config work/cad_showcase/config.json --out work/cad_showcase/building_spec.json
```
Review `building_spec.json` before rendering:
- Floors are ordered correctly.
- Bounds are plausible in meters.
- Each major floor has nonzero `walls`, `columns`, and `grid` or `floor_lines`.
- Segment counts are not dominated by dimensions/hatches/annotations.
- Footprint polygons exist when slabs/roofs are meant to follow CAD floor plates.
- `default_disabled_categories` does not hide `slab` for presentation/digital-twin views.
## 6. Agent Audit and Overlay Review
Do not proceed to Blender until the Agent has reviewed extraction evidence.
Run the audit:
```bash
python3 <skill>/scripts/audit_showcase_extraction.py \
--dxf-dir work/cad_showcase/dxf_sanitized \
--config work/cad_showcase/config.json \
--spec work/cad_showcase/building_spec.json \
--out work/cad_showcase/extraction_audit \
--vendor-dir work/vendor
```
Generate 2D overlays:
```bash
python3 <skill>/scripts/draw_coverage_overlay.py \
--dxf-dir work/cad_showcase/dxf_sanitized \
--config work/cad_showcase/config.json \
--spec work/cad_showcase/building_spec.json \
--out-dir work/cad_showcase/overlays \
--vendor-dir work/vendor
```
Agent review rules:
- Treat `INSERT`, `HATCH`, `ACAD_PROXY_ENTITY`, `SOLID`, `3DFACE`, and large unclassified layers as potential missing-model risks.
- Open overlay SVGs. Gray means source vectors already classified, red dashed means source vectors not classified, color means extracted model geometry.
- If red dashed geometry forms walls, columns, beams, stairs, grids, or floor outlines, update layer mapping or parser strategy and rerun extraction.
- If frequent blocks appear in the audit, inspect block names and decide whether to recursively explode block geometry.
- If hatches carry wall/slab/column information, do not rely only on line extraction.
- Continue only when missing geometry is acceptable for the requested output level.
## 7. Blender Generation
Run:
```bash
/Applications/Blender.app/Contents/MacOS/Blender -b \
--python <skill>/scripts/build_blender_showcase.py -- \
--spec work/cad_showcase/building_spec.json \
--out-dir outputs/<project> \
--name <project>
```
Expected outputs:
- `<project>.blend`
- `<project>.glb`
- `<project>.png`
- `model_metadata.json`
If Blender CLI fails, verify the path. On this machine, the app path has been:
```text
/Applications/Blender.app/Contents/MacOS/Blender
```
## 8. Web Showcase
For a quick single-model preview, run:
```bash
python3 <skill>/scripts/write_web_showcase.py \
--template <skill>/assets/web-showcase-template \
--glb outputs/<project>/<project>.glb \
--metadata outputs/<project>/model_metadata.json \
--out-dir outputs/<project>/web \
--title "<project> Web 展示模型"
```
For Web or digital-twin presentation, generate three reusable variants and let the Web writer consume the manifest:
```bash
python3 <skill>/scripts/build_showcase_variants.py \
--spec work/cad_showcase/building_spec.json \
--out-dir outputs/<project>/variants \
--name <project> \
--build \
--blender /Applications/Blender.app/Contents/MacOS/Blender
python3 <skill>/scripts/write_web_showcase.py \
--template <skill>/assets/web-showcase-template \
--variants-manifest outputs/<project>/variants/variants_manifest.json \
--out-dir outputs/<project>/web \
--title "<project> Web 展示模型"
npm install --prefix outputs/<project>/web three@0.181.2 lucide@0.468.0
python3 -m http.server 8188 --directory outputs/<project>/web
```
The manifest path makes `standard` the default `model.glb`, copies `overview.glb`, `standard.glb`, and `detail.glb`, and writes `model_variants` for the download controls.
Use another port if 8188 is occupied.
Notes:
- GLBs are Draco-compressed (Blender built-in, or post-process with `node tools/compress.mjs in.glb out.glb`). `npm install three` ships the matching decoder under `node_modules/three/examples/jsm/libs/draco/`; the template already registers a `DRACOLoader` pointing there, so no CDN is needed.
- The template is glTF-standard **Y-up**. If you swap in a Z-up GLB the building will render lying down — keep GLB and viewer on the same up-axis.
- `write_web_showcase.py` stamps a `?v=<build>` token on `app.js` / `model.glb` / `model_metadata.json` to defeat browser caching; if a user reports "no change after rebuild", confirm the served folder and hard-refresh.
## 9. Verification
Run the Blender-free QA pass first, then eyeball the previews before opening the Web viewer:
```bash
python3 <skill>/scripts/verify_showcase.py \
--spec work/cad_showcase/building_spec.json \
--glb outputs/<project>/variants/overview.glb outputs/<project>/variants/standard.glb outputs/<project>/variants/detail.glb \
--out outputs/<project>/verify_previews.png --budget-mb 0.6
```
It prints per-floor segment/cap/glazing-continuity counts and a GLB size-budget pass/fail, and writes front/side/plan orthographic previews. Use these to catch missing floors, a lying-down (wrong up-axis) model, uncapped columns, or discontinuous glazing **before** declaring the model done — early visual verification avoids most rework.
Minimum verification:
- Preview PNG is nonblank, building is framed, and floors are visible.
- GLB file exists and has reasonable size.
- Browser loads the Web viewer with zero console errors.
- Floor toggles, component toggles, explode slider, section slider, presets, screenshot, and GLB download work.
- Variant download links exist for overview, standard, and detail when the task is Web/digital-twin presentation.
- Slabs are visible from side views; transparent glazing should not make floor plates look missing.
- Roof caps do not visibly overrun unrelated lower floor footprints.
- Ground-level columns that have no upper support are not left full-height without explanation.
- Mobile viewport around 390 px wide has no incoherent overlap.
- Extraction audit is attached or summarized, including high-risk entity counts and unclassified layers.
- Overlay review result is stated: accepted, accepted with known gaps, or rejected and iterated.
For BIM branch:
- Validate IFC schema with IfcOpenShell.
- Count `IfcBuildingStorey`, `IfcSlab`, `IfcWall`, `IfcColumn`, `IfcBeam`, and property sets.
- Run geometry extraction on all products.
- Do not claim BIM replacement unless semantic and geometric validation has passed.
Generate IFC:
```bash
python3 <skill>/scripts/build_ifc_poc.py \
--spec work/cad_showcase/building_spec.json \
--out-ifc outputs/<project>/<project>_bim_poc.ifc \
--out-report outputs/<project>/<project>_bim_poc_report.json \
--out-notes outputs/<project>/<project>_bim_poc_notes.md \
--vendor-dir work/vendor \
--validate-geometry
```
Render IFC geometry when Blender cannot import IFC directly:
```bash
python3 <skill>/scripts/extract_ifc_meshes.py \
--ifc outputs/<project>/<project>_bim_poc.ifc \
--out work/cad_showcase/<project>_ifc_meshes.json \
--vendor-dir work/vendor
/Applications/Blender.app/Contents/MacOS/Blender -b \
--python <skill>/scripts/render_ifc_meshes_blender.py -- \
--meshes work/cad_showcase/<project>_ifc_meshes.json \
--out-dir outputs/<project> \
--name <project>_ifc_render
```

View 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
View 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
View 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())

View 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
View 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
View 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
View File

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

95
scripts/extract_ifc_meshes.py Executable file
View 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())

View 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
View 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
View 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
View 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())

View File

@@ -0,0 +1,207 @@
#!/usr/bin/env python3
"""Regression test for the CAD extraction pipeline improvements.
Reproduces the failure modes found in the 主辅楼 run with synthetic DXF files:
- curtain-wall glazing locked inside INSERT blocks (incl. wrapper blocks and
blocks whose CJK names were mangled by DWG->DXF conversion)
- annotation layers (*-IDEN) matching broad category patterns like A-DOOR*
- floor-plan sheets exported as near-empty XREF shells
Run: python3 tests/test_extraction_pipeline.py
"""
from __future__ import annotations
import json
import shutil
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
WORK = ROOT / "work" / "pipeline_test"
VENDOR = ROOT / "work" / "vendor"
sys.path.insert(0, str(VENDOR.resolve()))
import ezdxf # noqa: E402
FAILURES: list[str] = []
def check(name: str, condition: bool, detail: str = "") -> None:
status = "ok" if condition else "FAIL"
print(f"[{status}] {name}" + (f" — {detail}" if detail and not condition else ""))
if not condition:
FAILURES.append(name)
def make_plan_dxf(path: Path) -> None:
doc = ezdxf.new("R2010", setup=True)
for layer in (
"I-WALL", "A-GLAZ-CURT", "S-GRID-IDEN", "A-ANNO-DIMS",
"A-DOOR-IDEN", "A-DOOR", "A-DETL",
):
doc.layers.add(layer)
msp = doc.modelspace()
# Walls: building outline 40m x 20m (mm units).
for start, end in [
((0, 0), (40000, 0)), ((40000, 0), (40000, 20000)),
((40000, 20000), (0, 20000)), ((0, 20000), (0, 0)),
]:
msp.add_line(start, end, dxfattribs={"layer": "I-WALL"})
# Filler detail lines so the sheet is not "near empty" (>60 entities).
for i in range(70):
msp.add_line((1000 + i * 100, 5000), (1000 + i * 100, 5500), dxfattribs={"layer": "A-DETL"})
# Case 1: glazing block whose CJK name was mangled in conversion
# ("系统嵌板" -> "系统嵌"); matched by the widened GLAZING_BLOCK_PATTERNS.
mangled = doc.blocks.new(name="系统嵌 - SZ_ _偏100_-407498-平图")
mangled.add_line((0, 0), (3000, 0), dxfattribs={"layer": "A-GLAZ-CURT"})
for i in range(4):
msp.add_blockref("系统嵌 - SZ_ _偏100_-407498-平图", (i * 4000, 0))
# Case 2: glazing nested inside a wrapper block whose name matches nothing.
panel = doc.blocks.new(name="PNL-407498")
panel.add_line((0, 0), (0, 3000), dxfattribs={"layer": "A-GLAZ-CURT"})
wrapper = doc.blocks.new(name="SHEET-WRAP")
for i in range(3):
wrapper.add_blockref("PNL-407498", (40000, i * 5000))
msp.add_blockref("SHEET-WRAP", (0, 0))
# Annotation block content that must stay out of the spec.
axis = doc.blocks.new(name="轴号-01")
axis.add_circle((0, 0), 400, dxfattribs={"layer": "S-GRID-IDEN"})
axis.add_line((0, 0), (0, 2000), dxfattribs={"layer": "A-ANNO-DIMS"})
for i in range(5):
msp.add_blockref("轴号-01", (i * 8000, 22000))
# Door tag lines (annotation) vs a real door swing arc.
msp.add_line((5000, 0), (5800, 0), dxfattribs={"layer": "A-DOOR-IDEN"})
msp.add_arc((10000, 0), 900, 0, 90, dxfattribs={"layer": "A-DOOR"})
doc.saveas(path)
def make_xref_shell_dxf(path: Path) -> None:
doc = ezdxf.new("R2010")
doc.layers.add("A-ANNO-SYMB")
doc.add_xref_def(filename="../XREF/roof_geometry.dwg", name="XREF-ROOF")
msp = doc.modelspace()
msp.add_text("屋顶平面图", dxfattribs={"layer": "A-ANNO-SYMB"})
for i in range(4):
msp.add_line((i * 1000, 0), (i * 1000, 500), dxfattribs={"layer": "A-ANNO-SYMB"})
doc.saveas(path)
def run(cmd: list[str]) -> subprocess.CompletedProcess:
return subprocess.run(cmd, cwd=ROOT, text=True, capture_output=True)
def main() -> int:
if WORK.exists():
shutil.rmtree(WORK)
dxf_dir = WORK / "dxf"
dxf_dir.mkdir(parents=True)
make_plan_dxf(dxf_dir / "plan.dxf")
make_xref_shell_dxf(dxf_dir / "roof.dxf")
# --- cad_dxf_report: XREF shell must be flagged, plan must not ---
proc = run([
sys.executable, "scripts/cad_dxf_report.py",
"--input", str(dxf_dir), "--work", str(WORK / "report_work"),
"--output", str(WORK / "read_report"), "--vendor-dir", str(VENDOR),
])
check("cad_dxf_report runs", proc.returncode == 0, proc.stderr[-800:])
report = json.loads((WORK / "read_report" / "cad_read_report.json").read_text(encoding="utf-8"))
by_file = {item["file"]: item for item in report["files"]}
roof_warnings = " ".join(by_file.get("roof.dxf", {}).get("warnings", []))
check("roof.dxf flagged as XREF shell", "likely_xref_shell" in roof_warnings, roof_warnings)
check("plan.dxf has no warnings", not by_file.get("plan.dxf", {}).get("warnings"), str(by_file.get("plan.dxf", {}).get("warnings")))
md = (WORK / "read_report" / "cad_read_report.md").read_text(encoding="utf-8")
check("markdown has warnings section", "Warnings (resolve before modeling)" in md)
# --- derive with default config: glazing captured from blocks ---
config = {
"scale": 0.001,
"drawings": [{"file": "plan.dxf", "floors": [{"key": "1F", "name": "首层", "z": 0.0, "height": 4.2}]}],
}
config_path = WORK / "config.json"
config_path.write_text(json.dumps(config, ensure_ascii=False), encoding="utf-8")
spec_path = WORK / "building_spec.json"
proc = run([
sys.executable, "scripts/derive_showcase_spec.py",
"--dxf-dir", str(dxf_dir), "--config", str(config_path),
"--out", str(spec_path), "--vendor-dir", str(VENDOR),
])
check("derive runs", proc.returncode == 0, proc.stderr[-800:])
spec = json.loads(spec_path.read_text(encoding="utf-8"))
segments = spec["floors"]["1F"]["segments"]
glazing_layers = {seg.get("layer") for seg in segments.get("glazing", [])}
check("glazing captured from blocks", len(segments.get("glazing", [])) >= 2, str(segments.get("glazing")))
check("glazing came from A-GLAZ-CURT", glazing_layers <= {"A-GLAZ-CURT"}, str(glazing_layers))
# Both capture paths must contribute: 4 mangled-name inserts are horizontal
# (y const), 3 probe-only nested panels are vertical (x const at 40m).
has_vertical = any(
abs(seg["start"][0] - seg["end"][0]) < 1e-6 for seg in segments.get("glazing", [])
)
check("probe path captured nested wrapper glazing", has_vertical)
check("walls captured", len(segments.get("walls", [])) >= 4)
check("door swing arc classified as doors", len(segments.get("doors", [])) > 0)
door_layers = {seg.get("layer") for seg in segments.get("doors", [])}
check("A-DOOR-IDEN excluded from doors", "A-DOOR-IDEN" not in door_layers, str(door_layers))
all_layers = {seg.get("layer") for segs in segments.values() for seg in segs}
check("S-GRID-IDEN/A-ANNO-DIMS not extracted", not ({"S-GRID-IDEN", "A-ANNO-DIMS"} & all_layers), str(all_layers))
# --- audit with default config: gates pass, exit 0 ---
proc = run([
sys.executable, "scripts/audit_showcase_extraction.py",
"--dxf-dir", str(dxf_dir), "--config", str(config_path), "--spec", str(spec_path),
"--out", str(WORK / "audit_ok"), "--vendor-dir", str(VENDOR),
])
check("audit (glazing captured) exits 0", proc.returncode == 0, proc.stderr[-800:])
audit = json.loads((WORK / "audit_ok" / "extraction_audit.json").read_text(encoding="utf-8"))
gates = {gate["name"]: gate["status"] for gate in audit["gates"]}
check("glazing gate PASS", gates.get("glazing_captured") == "PASS", str(gates))
check("annotation gate PASS", gates.get("no_annotation_layers_classified") == "PASS", str(gates))
locked = audit["coverage"]["block_locked_length_meters"]
check("block-locked length reported", locked > 0, str(audit["coverage"]))
# --- derive+audit with expansion disabled: glazing gate must FAIL (exit 3) ---
config_off = dict(config)
config_off.update({"classify_block_contents": False, "expand_glazing_blocks": False})
config_off_path = WORK / "config_off.json"
config_off_path.write_text(json.dumps(config_off, ensure_ascii=False), encoding="utf-8")
spec_off_path = WORK / "building_spec_off.json"
proc = run([
sys.executable, "scripts/derive_showcase_spec.py",
"--dxf-dir", str(dxf_dir), "--config", str(config_off_path),
"--out", str(spec_off_path), "--vendor-dir", str(VENDOR),
])
check("derive (expansion off) runs", proc.returncode == 0, proc.stderr[-800:])
spec_off = json.loads(spec_off_path.read_text(encoding="utf-8"))
check(
"expansion off reproduces glazing=0",
len(spec_off["floors"]["1F"]["segments"].get("glazing", [])) == 0,
)
proc = run([
sys.executable, "scripts/audit_showcase_extraction.py",
"--dxf-dir", str(dxf_dir), "--config", str(config_off_path), "--spec", str(spec_off_path),
"--out", str(WORK / "audit_fail"), "--vendor-dir", str(VENDOR),
])
check("audit gate failure exits 3", proc.returncode == 3, f"rc={proc.returncode} {proc.stderr[-400:]}")
audit_fail = json.loads((WORK / "audit_fail" / "extraction_audit.json").read_text(encoding="utf-8"))
gates_fail = {gate["name"]: gate["status"] for gate in audit_fail["gates"]}
check("glazing gate FAIL when blocks unexpanded", gates_fail.get("glazing_captured") == "FAIL", str(gates_fail))
print()
if FAILURES:
print(f"{len(FAILURES)} check(s) failed: {FAILURES}")
return 1
print("All checks passed.")
return 0
if __name__ == "__main__":
raise SystemExit(main())

24
tools/compress.mjs Normal file
View File

@@ -0,0 +1,24 @@
import { NodeIO } from '@gltf-transform/core';
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
import { weld, dedup, prune, draco } from '@gltf-transform/functions';
import draco3d from 'draco3dgltf';
const [,, inPath, outPath] = process.argv;
if (!inPath || !outPath) { console.error('usage: compress.mjs in.glb out.glb'); process.exit(1); }
const io = new NodeIO()
.registerExtensions(ALL_EXTENSIONS)
.registerDependencies({
'draco3d.encoder': await draco3d.createEncoderModule(),
'draco3d.decoder': await draco3d.createDecoderModule(),
});
const doc = await io.read(inPath);
await doc.transform(
weld(),
dedup(),
prune(),
draco({ method: 'edgebreaker', quantizePosition: 14, quantizeNormal: 10, quantizeGeneric: 12 }),
);
await io.write(outPath, doc);
console.log('compressed ->', outPath);