Compare commits

..

25 Commits

Author SHA1 Message Date
919b35391d fix: tighten viewer framing and localize site controls
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled
2026-07-21 21:10:43 +08:00
84a591c95a fix: resolve CAD paths from task workdir
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled
2026-07-21 17:14:19 +08:00
adbd476957 test: target generated floor labels in smoke
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled
2026-07-21 15:37:03 +08:00
d18c2fcc41 test: wait for viewer floor controls before smoke
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled
2026-07-21 15:32:54 +08:00
6c207b0538 test: exercise floor state in browser smoke
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled
2026-07-21 15:30:24 +08:00
f2c24f4590 fix: preserve Unicode floor state in viewer URLs
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled
2026-07-21 15:20:43 +08:00
8cc64f2e58 fix: generate showcase thumbnails deterministically
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled
2026-07-21 14:53:23 +08:00
e0cd974c6b fix: distinguish Revit view wrappers from family blocks
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled
2026-07-21 14:38:30 +08:00
20ef26db9f fix: codify split roof and campus assembly
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled
2026-07-21 14:05:06 +08:00
a38e5796ea fix: resolve Node outside daemon PATH
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled
2026-07-21 13:52:41 +08:00
a3be794e19 fix: make CAD conversion recovery deterministic
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled
2026-07-21 13:49:18 +08:00
9d7d3cb973 fix: enforce Revit roof views and orphan geometry gates
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled
2026-07-21 13:10:04 +08:00
a29d1be3b2 fix: localize viewer render metric 2026-07-21 12:06:44 +08:00
b577a262a1 fix: localize model variant descriptions 2026-07-21 11:19:38 +08:00
87afe63313 fix: detect Revit floor frames deterministically 2026-07-21 11:03:38 +08:00
c12d1d57cb fix: close remaining CAD delivery review gaps 2026-07-11 15:26:43 +08:00
6c1336fa59 fix: close audited CAD delivery gate gaps 2026-07-10 15:58:51 +08:00
a761175c09 fix: enforce complete building and offline viewer gates 2026-07-10 14:04:10 +08:00
cab4d320c0 fix: automate GLB compression and real viewport smoke 2026-07-10 13:19:47 +08:00
78ec1fbdcc fix: enforce strict CAD showcase delivery gates 2026-07-10 12:38:12 +08:00
8b1b1d5e89 feat: harden CAD showcase skill and delivery pipeline 2026-07-10 09:21:13 +08:00
a6856f903d Windows support: install-path probing + platform notes
- Blender discovery adds the Windows versioned install dir (Program Files/
  Blender Foundation/Blender */blender.exe); ODA adds Program Files/ODA
  (both still env > PATH first; shutil.which resolves .exe via PATHEXT)
- README cross-platform section: pathlib + explicit UTF-8 I/O + bytes-decoded
  subprocesses throughout; Windows advice (PYTHONUTF8=1, LongPathsEnabled,
  ODA as the primary DWG path since libredwg is rare there)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 15:10:44 +08:00
b871a2f8bd Portability: Blender/ODA discovery via env > PATH > macOS default
The two hardcoded macOS paths in code become last-resort defaults:
- build_showcase_variants: env BLENDER > shutil.which("blender") > app bundle
- cad_dxf_report: env ODA_CONVERTER > shutil.which("ODAFileConverter") > app
  bundle (env override existed already; PATH lookup is new)
Docs annotate the macOS example paths with the discovery order.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 15:05:32 +08:00
23cf3af678 Web template: adopt session-evolved features + render-on-demand everywhere
Ported from the test3d-5 session build: in-page variant switching, share
link (full state in URL hash), auto tour, toast, building-grouped floor
toggles, per-(floor,category) geometry merge (draw calls), progressive
overview->standard loading. Hardened during the port: {{BUILD}} placeholder
restored (Date.now() defeated caching), single-GLB deployments skip the
phantom overview.glb phase, building-group fallback now derives from
floor-key prefixes (assemble_campus convention) instead of a hardcoded "A"
test, bookmarks completed (list + restore + remove + hash persistence).

Render-on-demand lands in BOTH the template and the offline viewer: static
scenes rendered at 60fps pegged the GPU/fans for identical frames —
invalidate()-driven rendering + shadowMap.autoUpdate=false (bake per
change). 27号 measured: template web 0 frames over 3s idle, offline viewer
25 frames total through load; features browser-verified (tour, bookmarks,
hash restore), zero console errors. window.__renders is the diagnostic
counter — idle growth must be 0.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-04 12:55:03 +08:00
eb7eea2861 README: installation guide for agent CLIs (Claude Code / opencode / Codex)
- Claude Code: clone into ~/.claude/skills (SKILL.md frontmatter already
  Anthropic skill format, auto-discovered/triggered)
- opencode / Codex and other AGENTS.md-based tools: clone anywhere + an
  AGENTS.md pointer (read SKILL.md first, obey DoD gates, run the suite)
- generic fallback preamble for any agent; runtime dependency list

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 11:52:26 +08:00
58 changed files with 9253 additions and 1492 deletions

54
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,54 @@
name: ci
on:
push:
pull_request:
jobs:
test:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
python: ["3.10", "3.12"]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
cache: pip
- uses: actions/setup-node@v4
with:
node-version: "20"
cache: npm
- run: python -m pip install -r requirements-qa.txt
- run: npm ci
- run: python -m compileall -q scripts tests
- run: ruff format --check scripts tests
- run: ruff check scripts tests
- run: node --check assets/web-showcase-template/app.js
- run: node --check scripts/dwg_dump_json.mjs
- run: node --check scripts/web_smoke_test.mjs
- run: node --check tools/compress.mjs
- run: pytest tests/test_contracts.py tests/test_delivery.py
- run: python tests/test_extraction_pipeline.py
browser-smoke:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
- uses: actions/setup-node@v4
with:
node-version: "20"
cache: npm
- run: python -m pip install -r requirements-qa.txt
- run: npm ci
- run: npx playwright install --with-deps chromium
- run: pytest tests/test_browser_smoke.py
env:
RUN_BROWSER_SMOKE: "1"

View File

@@ -2,9 +2,56 @@
把中国建筑施工图(DWG/DXF,天正 t3/t8 导出为主)自动转成可交互的 3D 展示模型(GLB + 离线单文件 Web viewer),并支持多栋厂区按总平面装配。Agent-led:脚本负责证据与可重复执行,判读权在 Agent;任何门禁失败即停,不静默出错模型。 把中国建筑施工图(DWG/DXF,天正 t3/t8 导出为主)自动转成可交互的 3D 展示模型(GLB + 离线单文件 Web viewer),并支持多栋厂区按总平面装配。Agent-led:脚本负责证据与可重复执行,判读权在 Agent;任何门禁失败即停,不静默出错模型。
## 安装到 Agent CLI
`SKILL.md` 自带 frontmatter(`name`/`description`),符合 Anthropic skill 格式;本仓库即 skill 本体,克隆即装。
**Claude Code**(原生 skill 机制,自动发现与触发):
```bash
# 全局(所有项目可用)
git clone ssh://git.latent.chat/zhengweirong/cad-building-showcase.git \
~/.claude/skills/cad-building-showcase
# 或装进单个项目
git clone ... <project>/.claude/skills/cad-building-showcase
```
装好后对 Claude Code 说"把这套 DWG 做成 3D 展示模型"即可自动触发,或显式 `/cad-building-showcase`。
**opencode / Codex CLI / 其他 AGENTS.md 系工具**(无 skill 机制,用指令文件指路):
```bash
git clone ... tools/cad-building-showcase # 克隆到项目内任意位置(或 git submodule)
```
然后在项目的 `AGENTS.md`(opencode、Codex 都读它)加一段:
```markdown
## CAD → 3D 展示模型
处理 DWG/DXF 转 3D/Web 展示任务时,必须先完整阅读
tools/cad-building-showcase/SKILL.md 并遵守其中 Hard Definition of Done:
门禁失败即停下修复,绝不绕过;改动任何脚本后必须跑
`pytest tools/cad-building-showcase/tests/test_contracts.py tools/cad-building-showcase/tests/test_delivery.py`
与 `python3 tools/cad-building-showcase/tests/test_extraction_pipeline.py` 且全绿。
```
**任何其他 Agent 的兜底用法**:把上面那段话作为任务开场白直接粘给它——skill 的全部约定都在 `SKILL.md` 里,脚本自含 CLI(`--help` 可查),不依赖宿主工具的任何私有机制。
**运行依赖**:Python ≥3.10,核心运行 `pip install -r requirements-core.txt`,交付验证再装 `requirements-delivery.txt`;Node ≥18。可选:libredwg、ODA File Converter、Blender、IfcOpenShell。先运行 `python3 scripts/cad_showcase.py doctor` 检查环境。
**跨平台**:脚本全用 pathlib + 显式 UTF-8 I/O + 子进程 bytes 解码,macOS/Linux/Windows 均可跑。工具发现顺序:Blender = env `BLENDER` → PATH → 平台安装默认(macOS 应用包 / Windows `Program Files\Blender Foundation`);ODA = env `ODA_CONVERTER` → PATH → 平台默认(Windows 含 `Program Files\ODA`)。Windows 建议:设 `PYTHONUTF8=1`(防重定向输出按 GBK 解码)、开启 LongPathsEnabled(中文长文件名的深层 work/ 目录可能触及 260 字符 MAX_PATH);Windows 上 libredwg 少见,DWG 转换以 ODA 为主路径。
## 用法 ## 用法
入口是 `SKILL.md`(操作手册):决策循环、One-Shot Definition of Done 七条门禁、天正图层方言预设、多栋厂区流程。核心链路: 入口是 `SKILL.md`(决策树与硬门禁),详细分支按需读取 `references/`。推荐统一 CLI:
```bash
python3 scripts/cad_showcase.py inspect --input <cad> --work work/<project> --output outputs/<project>/read_report
python3 scripts/cad_showcase.py run --dxf-dir <dxf> --config <config> --source-report <cad_read_report.json> --scope-manifest work/<project>/scope_manifest.json --out-dir outputs/<project> --name <project> --backend trimesh --web --offline --resume
```
核心链路:
``` ```
cad_dxf_report.py 读图报告(警告:多框图纸/缓存XREF/陌生图层方言…) cad_dxf_report.py 读图报告(警告:多框图纸/缓存XREF/陌生图层方言…)
@@ -13,7 +60,7 @@ detect_sheet_frames.py 图框检测(图签块定框、网格投票/墙剖面
derive_showcase_spec.py 按 config 提取 building_spec.json(分簇 footprint/楼板/顶盖) derive_showcase_spec.py 按 config 提取 building_spec.json(分簇 footprint/楼板/顶盖)
audit_showcase_extraction.py 硬门禁审计(楼层对齐+跨层基准、幕墙、框收支表、 audit_showcase_extraction.py 硬门禁审计(楼层对齐+跨层基准、幕墙、框收支表、
面积/层数互证…),FAIL 即退出码 3 面积/层数互证…),FAIL 即退出码 3
spec_to_glb.py GLB 生成;write_offline_viewer.py 离线单文件 viewer spec_to_glb.py GLB 生成;write_offline_viewer.py 离线单文件 viewer(使用 raw GLB)
register_site_outlines.py / massing_from_outline.py / assemble_campus.py register_site_outlines.py / massing_from_outline.py / assemble_campus.py
总平面配准(点-边ICP)、无图纸楼体量、厂区装配 总平面配准(点-边ICP)、无图纸楼体量、厂区装配
``` ```
@@ -21,18 +68,20 @@ register_site_outlines.py / massing_from_outline.py / assemble_campus.py
## 目录 ## 目录
- `scripts/` 全部流水线脚本(自含 CLI,`--help` 有说明) - `scripts/` 全部流水线脚本(自含 CLI,`--help` 有说明)
- `tests/test_extraction_pipeline.py` 回归套件(改任何脚本后必跑) - `schemas/` extraction config、building spec、variants manifest 的版本化 JSON Schema
- `references/` 案例记录与校准资料:`pipeline.md`(详细流程)、 - `tests/` 契约/交付测试 + 合成 DXF 全链路回归
`generalization_test_log.md`(泛化测试与缺口修复清单)、 - `references/` 当前运行规范;历史复盘移到 `docs/history/`,不再作为 Agent 运行上下文
`贝昂CAD诊断与skill优化.md`(首个案例全程) - `assets/` Web 模板与离线 viewer 内联库;离线交付必须通过真实 `file://` 浏览器 smoke
- `assets/` Web 模板与离线 viewer 内联库
`work/`、`outputs/`、源 CAD 均不入库(见 `.gitignore`),由脚本从源数据再生。 `work/`、`outputs/`、源 CAD 均不入库(见 `.gitignore`),由脚本从源数据再生。
## 验证纪律 ## 验证纪律
```bash ```bash
python3 tests/test_extraction_pipeline.py # 必须全绿 pytest tests/test_contracts.py tests/test_delivery.py
python3 tests/test_extraction_pipeline.py
ruff format --check scripts tests && ruff check scripts tests
npm run check:js
``` ```
已在四套真实图纸上端到端验证:贝昂科技厂区(基线)、黄桥文体中心、13号地块(双塔+酒店厂区)、27号地块(7栋混合厂区)。质量对比表见 `references/generalization_test_log.md`。 已在四套真实图纸上端到端验证:贝昂科技厂区(基线)、黄桥文体中心、13号地块(双塔+酒店厂区)、27号地块(7栋混合厂区)。历史质量对比见 `docs/history/generalization_test_log.md`。

314
SKILL.md
View File

@@ -1,211 +1,171 @@
--- ---
name: cad-building-showcase 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. description: Agent-led workflow for auditing DWG/DXF architectural drawings and generating verified building_spec.json, Blender or lightweight GLB models, offline/served Three.js showcases, multi-building campus assemblies, and optional IFC proofs. Use for CAD floor-plan folders, XREF-heavy Chinese construction drawings, TArch/天正 exports, multi-frame sheets, DWG/DXF-to-3D/Web requests, campus placement, 3DSOLID/MESH extraction, or questions about whether CAD-derived output can replace BIM. Do not use for PDF-only plans unless the user first supplies or authorizes a separate PDF-to-vector/CAD conversion workflow.
--- ---
# CAD Building Showcase # CAD Building Showcase
## Outcome ## 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: Produce an evidence-backed architectural showcase, not a blind CAD conversion. Deliver as applicable:
- CAD read report: converted/sanitized DXF inventory, layer counts, entity counts, drawing bounds, likely units. - sanitized DXF inventory and source gate report;
- Agent extraction config: explicit layer mapping, floor split/alignment, unit scale, curve and filtering rules. - versioned extraction config and `building_spec.json`;
- `building_spec.json`: normalized floor-by-floor geometry in meters. - extraction audit and per-floor SVG overlays;
- Extraction audit: coverage, unclassified layers, high-risk entity types, block/INSERT signals, and Agent questions. - overview/standard/detail GLBs plus metadata;
- 2D overlay review: SVG overlays comparing source CAD vectors with extracted model geometry. - Blender scene/preview when Blender is selected;
- Blender scene: `.blend`, `.glb`, and preview `.png`. - served Web viewer and/or offline single-file viewer;
- Web showcase: static Three.js viewer with floor/component toggles, floor explode, section height, camera presets, screenshot, and GLB download. - `scope_manifest.json` accounting for every requested building and the site;
- 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. - `evidence_manifest.json` with machine-readable final checks;
- Notes file: source drawings, assumptions, extraction limits, and verification results. - notes stating assumptions, missing geometry, source limitations, and confidence level.
If the user asks to replace BIM, branch explicitly to IFC/BIM validation. Treat Web showcase and BIM replacement as separate products. Treat Web showcase, massing, 3D-solid extraction, and BIM/IFC as separate products.
## Reference Router
Read only the branches needed for the current task:
- Standard extraction/config/schema: `references/pipeline.md` and `references/building_spec_schema.md`.
- Input conversion, dependencies, PDF boundary, 3DSOLID/MESH: `references/input_formats.md`.
- Multi-frame sheets and TArch/天正 mappings: `references/multi_frame_tarch.md`.
- Multi-building sites, placement, context, gaps: `references/campus_workflow.md`.
- GLB variants, Web/offline delivery, browser and final QA: `references/web_delivery.md`.
- IFC/BIM claims and validation: `references/bim_branch.md`.
- Acceptance judgment: `references/agent_review.md`.
- Calibration only, never constants: `references/a208_case_notes.md` and `references/optimization_notes.md`.
## Agent Decision Loop ## Agent Decision Loop
The Agent owns interpretation. Scripts are tools for evidence and repeatable execution. 1. Inspect before modeling.
- Run `python3 scripts/cad_showcase.py inspect --input <cad> --work <work> --output <report>`.
- Require source gate `all_sources_converted_and_readable=PASS`.
- Read warnings, units, bounds, entity types, top layers, XREF/block signals, and plan-title counts.
1. Inspect first, do not model blind. 2. Select the branch.
- Run `cad_dxf_report.py`. - Use standard line extraction for architectural DWG/DXF plans.
- Read top layers, entity types, bounding boxes, units, and high-risk entities. - Use `detect_sheet_frames.py` for multi-frame sheets. If the source report finds two or more plan identities in one drawing, `--frames` is mandatory; do not let `frame_ledger` become `NOT_APPLICABLE`.
- 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. - Treat detector clips as proposals. If Revit views share world coordinates, keep the detector's per-floor `include_block_names` plus top-level `expand_block_names`; clips alone cannot separate overlapping views. For non-Revit overlap, split by title/wall clusters. Area and cross-floor gates must pass before modeling.
- Keep `屋面平面图` (`RF`) and `机房小屋面` (`PH`) as distinct source identities. One overlapping RF clip may not satisfy both; resolve their view-suffixed blocks, heights, and roof-cap roles from the drawing evidence.
- When RF and PH are both floor keys, put them in separate `cap_groups` and give each an explicit evidence-derived `roof_specs` elevation. This prevents the automatic setback-cap calculation from creating a duplicate full-roof plate between the main roof and machine-room roof.
- Model each building separately before campus assembly.
- A campus request must run and audit one config per building, then use `assemble_campus.py`; do not merge building configs into one shortcut run, even when their source coordinates already share a site system.
- For multi-building/campus requests, write `scope_manifest.json` before modeling. Copy every requested building ID from the user/source inventory; never shrink scope to the easiest drawing set.
- Use `--converter oda` plus `extract_3d_solids.py` for known 3DSOLID/ACIS drawings. For ordinary DWG input, `--converter auto` tries native LibreDWG, then the packaged WASM bridge, then ODA; do not manually assemble the WASM commands unless the report records a converter failure.
- Stop and request DWG/DXF/vector conversion for PDF-only input.
2. Write an explicit extraction config. 3. Write and validate an explicit config.
- Decide layer mappings, floor splits, offsets, origin strategy, curve chord length, and category-specific line-length filters. - Set layer mappings, scale, floor clips/offsets/order, heights, origin, block rules, footprints, caps, and evidence values.
- Use `references/pipeline.md`, `references/building_spec_schema.md`, and `references/a208_case_notes.md` as calibration. - Run `python3 scripts/showcase_schema.py config <config.json> --dxf-dir <sanitized-dxf>`.
- Treat unknown keys, missing drawings, duplicate floor keys, incomplete `floor_order`, and invalid values as hard failures.
3. Extract, audit, and review overlays before accepting. 4. Extract, audit, and review overlays.
- Run `derive_showcase_spec.py`. - Prefer the resumable entry point after the config is approved:
- Run `audit_showcase_extraction.py`. `python3 scripts/cad_showcase.py run --dxf-dir <dxf> --config <config> --source-report <cad_read_report.json> --scope-manifest <scope_manifest.json> --out-dir <out> --name <name> --frames <frames.json> --backend trimesh`.
- Run `draw_coverage_overlay.py`. - Use `--backend blender` when `.blend` and Blender preview are required.
- 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. - Never pass `--no-strict-gates` to proceed toward delivery.
- Treat applicable audit `WARN`/`SKIP` as `BLOCKED`, not success. `NOT_APPLICABLE` means the optional check was not armed and is non-blocking. Continue past WARN/SKIP only with an explicit `--waiver 'audit:<gate>=<evidence-based reason>'`; retain it in final evidence.
- A waiver must be explicitly approved by the user. The Agent must not invent one, and must never use one when the user says “no waivers/不要豁免”.
- Search all source sheets for economic-index tables, storey labels, and elevation ladders before declaring area/storey evidence absent. If a typical plan represents repeated floors, instantiate the source-supported repetitions; a final full-building model may not jump from F2 directly to F16.
- Open the SVG overlays. Iterate if red/unclassified geometry forms walls, glazing, columns, beams, grids, stairs, slabs, roofs, or whole building wings.
- Resolve every `disconnected_footprints` failure. A small remote polygon is usually a leaked sheet component that becomes a floating fin; only record `allowed_disconnected_footprints` when the source visibly proves a legitimate detached stair/canopy and include the reason.
- Treat every geometry-loss warning from derive (`isolated_cluster`, `unsupported_roof`, `floor_order`, `topless_group`) as a stop condition. Tune the config or restore/model the geometry; do not accept a successful exit code with these warnings.
4. Generate and verify the 3D/Web model only after the extraction passes review. 5. Verify actual deliverables.
- Run Blender/GLB generation and Web template assembly. - Require `verify_showcase.py --strict` and `verify_delivery.py` to pass.
- Verify preview image, Web controls, console logs, and mobile layout. - Inspect at least one iso/front/side/plan render personally.
- For served Web output, use `cad_showcase.py run --web`; it Draco-compresses Trimesh GLBs, starts a temporary local server, runs `web_smoke_test.mjs` at real 1440×900 and 390×844 viewports, and feeds the report to final verification automatically.
- Use the `thumbnail.png` emitted by the Web smoke. It is exported directly from the WebGL canvas with the canonical camera; do not manually crop the browser screenshot or iterate on UI-free framing.
- For `--offline`, the pipeline embeds the retained uncompressed `standard.raw.glb`, opens `viewer.html` through a real `file://` Chromium page, and records `offline_browser_smoke_report.json`. Never embed a Draco GLB in the r147 offline viewer unless a matching offline decoder is bundled and tested.
- Confirm idle `window.__renders` does not grow, GLBs decode, variants exist, controls work, and console errors are zero.
5. Report confidence and limits. 6. Report confidence and limits.
- State whether the output is Web showcase, LOD-like massing, IFC/BIM proof, or not sufficient. - Label the result `Web showcase`, `Massing/LOD100-150`, `3D-solid partial extraction`, or `IFC/BIM proof`.
- Include what was not modeled and what evidence supports that judgment. - State what was not modeled and cite report/gate/image evidence.
## One-Shot Definition of Done ## Hard Definition of Done
The pipeline is designed so a first pass either succeeds or STOPS at a loud gate. Do not hand over a model unless every line below has evidence (a report line, a gate status, or an image): Do not hand over a model unless every applicable item has evidence:
1. Read report clean: every `Warnings` entry resolved. `multi_frame_sheet` -> ran `detect_sheet_frames.py` and used its clip/offset config; `cached_xref_content` -> the XREF content is CACHED as in-file block definitions, expand blocks (≈bind) instead of asking for a re-export; `likely_xref_shell` (no cached content) -> user re-exported with XREFs bound. 1. `cad_read_report.json.gate.status == PASS`; no unresolved conversion/read failure. A reasoned partial `WARN` is usable only with a user-approved `cad_source_report` waiver and must remain visible in evidence.
2. Frame alignment proven: detect report shows `grid-aligned, votes x>=3 y>=3` per floor (any `WEAK grid match` floor was verified on its overlay SVG). 2. Config and spec pass their versioned JSON Schemas.
3. Audit exit code 0, and gates `floors_aligned` / `glazing_captured` / `no_annotation_layers_classified` all PASS. `floors_aligned` also cross-checks every floor's wall profile against the group's reference floor (a strong correlation peak at a non-zero shift = "self-consistent but misplaced", the 13号 F3 错槽 pattern that envelope centers cannot see). Never pass `--no-strict-gates` to proceed. 3. Every configured source exists, every floor key is unique, every floor is nonempty, and `floor_order` has no gaps/ghosts.
Leak gates (SKIP unless armed — arm them on every new project, they are the cross-evidence net): `--frames <detect out-config>` arms `frame_ledger` (every detected plan frame must be used by the config or listed in `discarded_frames` with a reason — silently ignored frames are where wings vanish); config `declared_areas_m2` arms `area_declared` (model footprint area vs 经济技术指标表/标注, ±15% default — 1#B lost half the building and only the site plan showed it); config `expected_storeys_above_ground` arms `storey_count` (vs 总图 `22F` labels / elevation ladder). 4. Multi-frame projects pass `frame_ledger`; `--frames` is mandatory when the source reports multiple plan identities, and every detected frame key and required block selector is mapped one-to-one or appears in `discarded_frames` with a reason. `RF` and `PH` cannot satisfy each other merely because their clips overlap.
4. No `WARNING topless_group` from derive (roof handled via caps or `roof_specs`), and no `WARNING mesh_from_polygons` from the GLB build (else slabs/roofs silently vanished — install mapbox_earcut). 5. A required single-building/campus `scope_manifest.json` matches the requested scope and its artifacts exist.
5. Visual check done by the Agent, not assumed: `verify_showcase.py` previews plus one rendered iso/plan image actually LOOKED AT (floors stacked, roof present, no slab fins beyond facade — default `cap_buffer` 1.3 is for colonnades, use ~0.1 otherwise; and check the AIR between separate masses in the front/side views — bridged footprint hulls lay slab plates between twin towers, invisible in top views and to every gate). 6. Numbered floors are vertically continuous; representative typical-floor drawings are repeated into source-supported storeys instead of leaving large empty gaps.
6. Campus placement (if 总图/定位图 exists): building envelope dims match the site rect 1:1 (e.g. 面积核算 frame), rotation taken from the rect edge angle, 180° flip disambiguated by an asymmetric feature (machine rooms / basement / entrance), and a top-view overlay image confirms the building inside its site rect. Neighbour gaps measured numerically: no overlaps, 贴建 joints 0.15-0.3 m with corroborating evidence, buildings inside 红线. 7. Audit exits 0 and every gate is `PASS`; `WARN`/`SKIP` block delivery unless a named, user-approved waiver is recorded in evidence.
7. `tests/test_extraction_pipeline.py` passes after ANY script change. 8. Derive emits no `WARNING topless_group`; GLB build emits no `WARNING mesh_from_polygons`.
9. Campus output contains every requested building and the site as `PASS`, with existing artifacts; a `BLOCKED` entry means the campus request is not complete.
10. Campus output has proven transforms, no unexplained overlap, numeric neighbour gaps, boundary containment, and a top-view placement image.
11. `disconnected_footprints` passes; iso/front/side/plan review shows no floating fins, orphan slabs, duplicated roof volumes, or unexplained detached geometry.
12. `verify_delivery.py` writes `evidence_manifest.json` with overall `PASS`; `BLOCKED`/`FAIL` must never be described as complete, and a human has looked at the render.
13. Served Web delivery includes a passing desktop/mobile browser smoke report whose viewport checks prove 1440×900 and 390×844. If Chromium cannot run, report `BLOCKED`; do not substitute the offline viewer for the requested Web template.
14. Offline delivery includes a passing `file://` browser smoke report proving the readiness marker, canvas, and first render; an embedded payload check alone is insufficient.
15. After any script/schema/template change, run:
- `pytest tests/test_contracts.py tests/test_delivery.py`
- `python3 tests/test_extraction_pipeline.py`
- `ruff format --check scripts tests && ruff check scripts tests`
- `npm run check:js`
## Command Workflow ## Core Commands
1. Prepare the CAD folder. Check prerequisites:
- 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.
- No native converter available (Linux sandbox, no ODA/libredwg)? Use the WASM fallback: `npm install @mlightcad/libredwg-web`, then `node scripts/dwg_dump_json.mjs in.dwg dump.json --module-dir <node_modules>` and `python3 scripts/dwgjson_to_dxf.py --json dump.json --out work/dxf_raw/file.dxf`. This carries LINE/PLINE/ARC/CIRCLE/ELLIPSE/SPLINE/TEXT/INSERT + full block definitions (enough for the extraction pipeline), but drops HATCH/DIMENSION/ATTRIB — do not use it to judge hatch-only column fills or attribute-held axis numbers.
- Multi-discipline sets (建筑/结构/给排水/电气/暖通 subfolders): model from 建筑 (architecture) only by default; pull 结构 later just for columns/beams if the showcase needs structure. Never feed all disciplines into one extraction pass.
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. ```bash
python3 scripts/cad_showcase.py doctor
```
2. Generate a CAD read report. Inspect/convert sources:
- 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.
- `unknown_layer_dialect` warning = a plan file whose layers match no known wall naming (*WALL*/*墙*): a design-institute convention this pipeline has never seen. Build the layer mapping consciously from the top-layers list before modeling — patterns age, and a wrong mapping extracts nothing silently.
- Resolve the report's `Warnings` section before modeling. `cached_xref_content` means the "empty" sheet's INSERT stubs reference block definitions cached INSIDE the file (AutoCAD keeps unbound-XREF content as blocks; both libredwg and ODA export the cache) — expand blocks in detect/derive (`expand_blocks` ≈ bind), no re-export needed. Only `likely_xref_shell` / `near_empty` WITHOUT cached content means geometry truly lives outside: 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`. ```bash
- Use `references/pipeline.md` and `references/building_spec_schema.md`. python3 scripts/cad_showcase.py inspect \
- Map CAD layers to normalized categories: `walls`, `glazing`, `roof`, `columns`, `beams`, `railings`, `doors`, `detail_lines`, `floor_lines`, and `grid`. --input <cad-folder> --work work/<project> --output outputs/<project>/cad_read_report \
- Identify one drawing per floor or split sheets that contain multiple floor plans side by side. --converter auto
- MULTI-FRAME SHEETS (the common Chinese pattern: one DWG per building holding ALL its plans + elevations + sections stacked in modelspace): run `scripts/detect_sheet_frames.py` on the sanitized DXF. It finds `XX平面图` title texts (filtering catalog rows and title-block copies; titles INSIDE cached-xref blocks are scanned too), prefers title-block frame INSERTs (`A0_V1`/`A0+0.5_V1`/`*图框*`… world bboxes) as clip windows — pitch-sized windows halve elongated sheets (13号 加长A0 held two towers in one frame) — refines each clip to the wall bbox inside it, and computes per-floor `offset`s by voting-based grid-line correlation (label-free; TArch grids live on layer `DOTE`, not `AXIS`). When a frame has NO axis geometry at all, it falls back to wall-profile correlation (length-weighted wall-position histograms, x and y independently, coverage+peak-ratio gated) before surrendering to the clip-corner anchor — clip corners track wall bboxes and drift by whole bays when balconies differ. Auxiliary-titled frames (非机动坡道/无障碍改造/人防…) are flagged and never become the alignment reference (a bike-ramp frame once anchored a whole tower to nothing). Never model such a file as one floor (all sheets superimpose) and never stack frames without offsets (floors staircase away diagonally — the classic broken output). Multi-floor titles (四、六、八层平面图 / 十一至十四层平面图) are expanded into one config entry per storey sharing the frame's clip/offset — hand-copying N entries is where floors silently vanished (13号 b2). Read its report: `WEAK grid match` floors need overlay verification; `wall-correlated` floors deserve one overlay check too; elevation/section frames are listed for floor heights with a PER-FRAME `ladder:` of DIM_ELEV values plus a `suggested storey table` line (uniform-step chain) — the suggestion is evidence, not a decision: fill `z`/`height` yourself after checking the 剖面 ladder (stair sections beat at half-storey rhythm; podium/machine floors differ). Frame clips can swallow the sheet above/below (refine bbox includes between-sheet strips): if a floor's footprint depth is ~2-4x its siblings, cluster its wall y-midpoints and cut the clip band to the plan's own row. ```
- 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.
- Floor keys: `floor_sort_key` treats a leading `B` as basement (sorted below ground). Do not invent keys like `B1F` for "Building 1 Floor" — use per-building specs instead, and set explicit `floor_order` whenever keys are nonstandard.
- 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. Footprints are hulled PER proximity cluster (`footprint_cluster_linkage`, 6 m): a floor holding two disconnected masses (13号 twin towers in one floor key) gets separate hulls — a single concave hull would bridge the void and `use_footprint_slabs` would lay plates across it; genuinely linked wings stay merged because the 连廊 walls connect the clusters.
- Run `scripts/derive_showcase_spec.py` to extract line/polyline geometry into `building_spec.json`.
4. Audit extraction before 3D generation. Run from an Agent-approved extraction config:
- 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.
- CLIP-SCOPE CAVEAT: audit accounting is file-global while clip-based extraction is frame-scoped. On multi-frame sheets a healthy extraction can still show ~40% coverage and a block-locked WARN, because elevations/sections/details inflate the denominator. Judge such runs by the per-floor overlays and segment counts, not the headline ratio.
- 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. ```bash
- Use Blender CLI: python3 scripts/cad_showcase.py run \
`/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>` --dxf-dir work/<project>/dxf_sanitized \
- Use Blender MCP only after the CLI artifact exists, for inspection, scene tuning, or interactive refinement. --config work/<project>/extract_config.json \
--source-report outputs/<project>/cad_read_report/cad_read_report.json \
--frames work/<project>/frames_config.json \
--out-dir outputs/<project> --name <project> \
--backend trimesh --web --offline --scope-manifest work/<project>/scope_manifest.json --resume
```
6. Generate the Web showcase. For a known ACIS/3DSOLID source, force ODA during inspection; do not let an apparently nonempty libredwg conversion hide dropped solids:
- 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.
- Share-by-file delivery (no server, no network — mainland-China CDNs hang): `scripts/write_offline_viewer.py --spec ... --glb ... --out viewer.html` emits a fully self-contained HTML (three r147 UMD + pako inlined from `assets/offline-viewer-libs/`, GLB gzip-embedded, ACES + IBL + shadows + physical glass + instanced trees + grouped toggles + click-to-inspect, loading failures shown on screen). Smoke-test headlessly in node: decode the embedded payload and GLTFLoader().parse it.
- 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. ```bash
- Open the preview PNG or render another screenshot; check that geometry is nonblank and framed. python3 scripts/cad_showcase.py inspect ... --converter oda
- Open the Web viewer in the Browser plugin on desktop and mobile widths. python3 scripts/extract_3d_solids.py \
- Check console logs are clean, controls work, mobile panels do not overlap, and the GLB loads. --dxf work/<project>/dxf_sanitized/model.dxf \
- Report model precision honestly: showcase model, LOD-like massing/structural visualization, or IFC/BIM proof. --out-glb outputs/<project>/solids.glb \
--report outputs/<project>/solids_report.json
```
8. Raise presentation quality when the user wants "digital-twin" polish. ## Modeling and Honesty Rules
- Follow `references/web_presentation_notes.md` in tier order: official template + Draco + ACES/RoomEnvironment lighting + physical glass first (cheap, big win); then geometry upgrades (merged wall solids, mullion grids, road/green surfaces, instanced trees); then interaction (click-to-inspect from GLB extras, camera tours, progressive per-building loading).
- Polish never excuses a wrong model, and enhancements derived from plan linework must not be presented as BIM-verified elements.
## Multi-Building Campuses (厂区/园区 sets) - Prefer stable layered geometry over overfitted CAD noise.
- Preserve floor/category naming as `<floor_key>__<category>` and glTF Y-up.
- Keep source originals unchanged; write intermediates under `work/` and deliveries under `outputs/`.
- Start each independent attempt in a new project directory. Reusing a prior directory requires an explicit user request and a recorded provenance note.
- Use CAD-derived footprint polygons for slabs/roofs when evidence is sufficient; do not present generated caps, hulls, mullions, wall unions, or massings as BIM-verified geometry.
- Keep slabs visible for presentation, grids/details toggleable, and in-scene labels off by default.
- Never claim rooms, openings, quantities, materials, MEP coordination, code compliance, or production BIM unless the IFC branch explicitly generates and validates them.
- A missing building stays missing or becomes an explicitly labeled outline massing; never invent detail to make a scene look complete.
A folder like `建筑-1#厂房 / 2#厂房 / 3#辅房 / 总图` is a CAMPUS: several buildings plus a site plan — NOT floors of one building. Never map "one DWG = one floor" here. ## Bundled Entry Points
- Model each building separately: one detect-frames pass, one extraction config, one `building_spec.json`/GLB per building DWG. Small structures (机械停车坑/水池) are usually one or two frames. - `scripts/cad_showcase.py`: doctor, source inspection, resumable deterministic pipeline, state ledger.
- Assemble with `scripts/assemble_campus.py`: record each building's transform (model anchor -> surveying anchor + campus rotation) in `site_manifest.json` and let the script do the merge — it also runs the mandatory neighbour-gap check automatically. Buildings on one campus can face different ways (27号: 4#楼 sits ~27° off its siblings): a per-building `rotation_deg` in the manifest overrides the global one. - `scripts/showcase_schema.py` + `schemas/`: config/spec/manifest validation and shared floor-group contract.
- Units differ by sheet type: building plans are almost always millimeters (`scale 0.001`), while 总图 site plans are often METERS at real surveying coordinates (huge x/y like 349xxx/663xxx, texts ~2-4 units tall). The extraction config has a single global `scale`, so never mix a meters site plan and mm building plans in one spec. - `scripts/cad_dxf_report.py`: DWG/DXF conversion, sanitizing, inventory, source gate.
- Place buildings with a site manifest: from 总图/定位图 (prefer a "带轴号(可点坐标)" version if present) measure each building's anchor point and rotation, then assemble per-building GLBs in the viewer/scene with those transforms. Record the manifest (building -> position/rotation/source) in the notes file. - `scripts/detect_sheet_frames.py`: frame detection, grid/wall correlation, title expansion, elevation evidence.
- Proven placement recipe (贝昂 case): find the building's envelope rectangle in the site drawing (layer 面积核算/建筑轮廓线) — its edge lengths must equal the model's wall-envelope bbox 1:1 (here 90.2 x 42.2 m exactly), edge angle gives rotation (7.57°), the corner matching the model's (min x, min y) gives translation. Resolve the 180° flip by densest-feature voting (e.g. machine-room walls inside a known sub-rect). Then EITHER merge at spec level (transform all segments/footprints/caps into site-local meters and append a SITE context floor) and export one GLB, OR keep per-building GLBs plus transforms in the manifest. Pick a site-local origin (用地红线 min corner), never raw surveying coordinates — float32 breaks at 349 km. - `scripts/derive_showcase_spec.py`: normalized extraction and canonical caps.
- Anchor placement on WALL evidence, never roof/eave envelopes: 屋面 outlines include canopies and asymmetric overhangs — concentric placement against one put 2# 0.45 m off (26 cm INSIDE its neighbour). Best anchors, in order: corner coordinate callouts (X=/Y= texts), wall lines, envelope rects whose edges equal the wall bbox exactly. - `scripts/audit_showcase_extraction.py` + `scripts/draw_coverage_overlay.py`: gates and visual coverage evidence.
- Site plans without per-building envelope rects (27号 pattern): building outlines may hide on odd layers (EVTR!) — match each closed polyline to its nearest 楼栋 label, then register the model footprint onto the outline with `scripts/register_site_outlines.py` (point-to-edge ICP: brute-force angle + translation refine, trim worst 10%; emits a manifest-ready placement + residual). Constrain `--angle-window` when the outline is visibly axis-aligned — balcony bumps love a tilted false minimum (2# found a 10.75° pit). A building with NO drawn outline can still be anchored from its DIM_COOR corner callouts alone (pair X=/Y= texts, drop points that fall on the garage outline / fire-pad rects), and registering the UNION of several floors' footprints (`--floors F1 F2 F4`) beats one floor when upper wings overhang. Judge residuals: 0.06 m = outline equals model; 0.5-1 m normal with balconies; >2 m = wrong outline/floors, check the overlay. Surveying convention on both 13号/27号 site plans: drawing x = 测绘Y (east), drawing y = 测绘X (north), meters. - `scripts/spec_to_glb.py` / `scripts/build_blender_showcase.py`: Y-up GLB/Blender backends consuming the same spec contract.
- Buildings named on the site plan but with NO delivered drawings (27号 3#/4#): `scripts/massing_from_outline.py --outline pts.json --storeys 22 --height 3.0` builds an honest massing spec (outline-edge walls, footprint slabs, top cap, description marked 总图轮廓体量) and prints manifest-ready anchors — never silently fake a detailed model. Storey counts come from the `22F` labels next to each outline; heights from the sibling tower's ladder. - `scripts/build_showcase_variants.py`, `scripts/write_web_showcase.py`, `scripts/write_offline_viewer.py`: delivery assembly.
- Adjacent-building gap sanity check is mandatory: compute the wall-to-wall gap in the shared-edge frame. ~0.15-0.30 m means 贴建 with an expansion joint (变形缝) — corroborate with the neighbour's roof labeled on this building's roof plan and matching floor elevations. Several metres means fire separation. A NEGATIVE gap (overlap) is always a placement bug. Cross-check the chosen position against the boundary: if a hypothesis (e.g. a 10 m fire gap) pushes the building through 用地红线, the hypothesis is wrong. - `scripts/verify_showcase.py`, `scripts/verify_delivery.py`, `scripts/web_smoke_test.mjs`: strict final QA.
- Site context is a deliverable, not decoration — a campus scene with only a few boundary lines reads as broken. Run `scripts/site_context_from_dump.py` on the 总图/定位图 dumps: it emits ready-to-merge floors for ground (用地红线 footprint slab), roads + parking stalls (lines, arcs, block-expanded 车位 INSERTs), fence (围墙 as 1.8 m railings), street trees (行道树 INSERT points as green posts, custom `trees` category), and low-confidence massings for context structures drawn only in the site plan (连廊/门卫/消控室, named by nearest label). It takes one plan-copy window (site sheets usually hold several scheme copies), a per-source unit scale (总图 in meters, 定位图 copies in mm), and an exclude-quad so the real building model replaces its own site outline. Buildings that have their own drawing sets get real models placed by the manifest — never fake them as massings. - `scripts/assemble_campus.py`, `scripts/register_site_outlines.py`, `scripts/site_context_from_dump.py`, `scripts/massing_from_outline.py`: campus branch.
- `scripts/extract_3d_solids.py`: flat ACIS/MESH extraction with curved-surface limitation report.
## TArch / 天正 t3 Export Preset (most Chinese architecture DWGs) - `scripts/build_ifc_poc.py`, `scripts/extract_ifc_meshes.py`, `scripts/render_ifc_meshes_blender.py`: IFC proof branch.
`_t3` exports use TArch layer names that the AIA-style defaults miss. Calibrated mapping:
- `walls: ["WALL"]`, `columns: ["COLUMN", "*COL*"]`, `glazing: ["CURTWALL", ...]`, `roof: ["屋面", "*屋顶*"]`, `detail_lines: ["STAIR", "EVTR", "平面", "开口"]`, `grid: ["DOTE", "AXIS"]` — plan grids are on `DOTE` (dash-dot); `AXIS` often holds only detail-sheet stubs.
- Doors and windows BOTH live on layer `WINDOW` as INSERTs, and the block geometry sits on layer `0` (inherits by insert), so layer-based block probing keeps NOTHING. Use explicit expansion plus block-name classification:
`"expand_blocks": ["$TCHSYS$*", "$DorLib2D$*"]`, `"block_name_categories": {"glazing": ["$TCHSYS$WIN2D*"], "doors": ["$DorLib2D$*"]}`.
- Exclude annotation/frame layers inside clips: `["*-IDEN", "*图签*", "PUB_*", "DIM_*", "*TEXT*", "初审修改", "面积核算", "格子线", "辅注", "SEC-*", "立面", "剖面", "雨水管", "家具"]` (revision clouds live on `初审修改`-style layers).
- TArch column fills may be HATCH-based; if arch plans yield suspiciously few `columns`, take columns/beams from the 结构 set instead of inventing them.
## 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/detect_sheet_frames.py`: multi-frame sheet splitter — finds plan-title frames (column AND row layouts), refines per-floor clips, grid-correlates per-floor offsets, and emits a config skeleton + report, including suggested storey elevations harvested from 剖面/立面 标高 texts.
- `scripts/assemble_campus.py`: manifest-driven campus assembly — transforms per-building specs into site-local meters (prefixing floor keys, re-keying roof_specs), merges site-context floors (dropping massings covered by real models), and enforces the neighbour-gap check (overlap = exit 3; 0.1-0.3 m flagged as expansion-joint candidates).
- `scripts/dwg_dump_json.mjs` + `scripts/dwgjson_to_dxf.py`: WASM libredwg fallback (npm `@mlightcad/libredwg-web`) for DWG->DXF when neither native libredwg nor ODA exists; preserves block definitions and INSERT transforms.
- `scripts/site_context_from_dump.py`: campus site-context floors (ground/roads/parking/fence/trees/context massings) from 总图/定位图 dumps, with per-source unit scale, plan-copy windowing, and an exclude-quad for the really-modeled building.
- `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. Single-pass over expanded entities (floors share one INSERT expansion; block leaf-layer memoization skips irrelevant blocks), so multi-frame configs with many floors stay fast.
- `scripts/audit_showcase_extraction.py`: coverage and risk audit with hard gates (exit 3 on failure) and block-locked geometry accounting (definition-walk with per-block-name caching, no per-INSERT explode), 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).
- `references/web_presentation_notes.md`: tiered visual/interaction/performance upgrade playbook for the Web showcase (template + Draco + ACES/environment lighting + physical glass; merged wall solids, mullions, site surfaces, instanced trees; click-to-inspect, tours, progressive campus loading) with honesty rules for presentation enhancements.
- `assets/web-showcase-template/`: static Three.js viewer template (Y-up, registers DRACOLoader, cache-busting `?v=` build token; RoomEnvironment IBL, model-sized shadow frustum + ground shadow catcher, physical-glass glazing, click-to-inspect).
- `scripts/write_offline_viewer.py` + `assets/offline-viewer-libs/`: fully-offline single-file HTML viewer generator (vendored three r147 UMD + addons + pako; gzip-embedded GLB) for share-by-file delivery where CDNs/servers are unavailable.
- `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.

View File

@@ -3,7 +3,9 @@ import { OrbitControls } from "three/addons/controls/OrbitControls.js";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js"; import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js"; import { DRACOLoader } from "three/addons/loaders/DRACOLoader.js";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js"; import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.js";
import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js";
// ───────────────────────── DOM ─────────────────────────
const canvas = document.querySelector("#scene"); const canvas = document.querySelector("#scene");
const loading = document.querySelector("#loading"); const loading = document.querySelector("#loading");
const loadingFill = document.querySelector("#loading-fill"); const loadingFill = document.querySelector("#loading-fill");
@@ -11,6 +13,7 @@ const loadingText = document.querySelector("#loading-text");
const floorControls = document.querySelector("#floor-controls"); const floorControls = document.querySelector("#floor-controls");
const categoryControls = document.querySelector("#category-controls"); const categoryControls = document.querySelector("#category-controls");
const downloadControls = document.querySelector("#download-controls"); const downloadControls = document.querySelector("#download-controls");
const variantControls = document.querySelector("#variant-controls");
const stats = document.querySelector("#stats"); const stats = document.querySelector("#stats");
const inspect = document.querySelector("#inspect"); const inspect = document.querySelector("#inspect");
const explodeInput = document.querySelector("#explode"); const explodeInput = document.querySelector("#explode");
@@ -18,23 +21,40 @@ const explodeValue = document.querySelector("#explode-value");
const sectionInput = document.querySelector("#section"); const sectionInput = document.querySelector("#section");
const sectionValue = document.querySelector("#section-value"); const sectionValue = document.querySelector("#section-value");
const autoRotateButton = document.querySelector("#auto-rotate"); const autoRotateButton = document.querySelector("#auto-rotate");
const tourButton = document.querySelector("#auto-tour");
const bookmarkButton = document.querySelector("#bookmark");
const shareButton = document.querySelector("#share-link");
const bookmarkList = document.querySelector("#bookmark-list");
// ───────────────────────── Constants ─────────────────────────
const preferredCategoryOrder = [ const preferredCategoryOrder = [
"slab", "slab", "roof", "walls", "glazing", "columns", "beams",
"roof", "railings", "doors", "detail_lines", "floor_lines", "grid",
"walls",
"glazing",
"columns",
"beams",
"railings",
"doors",
"detail_lines",
"floor_lines",
"grid",
]; ];
const SCENE_FLOOR_LABELS = {
SITE: "场地",
ROADS: "道路",
FENCE: "围墙",
TREES: "绿化",
};
const CACHE_BUST = "{{BUILD}}";
// Tour presets — cycle through these viewpoints
const TOUR_PRESETS = ["overview", "side", "top", "overview"];
// ───────────────────────── State ─────────────────────────
const objectRegistry = []; const objectRegistry = [];
const floorGroups = new Map(); const floorGroups = new Map();
const buildingGroups = new Map(); // building key -> Set of floor keys
const materialByCategory = new Map(); const materialByCategory = new Map();
const mergedMeshes = []; // merged geometry meshes for draw-call optimization
const bookmarks = [];
let currentVariant = "standard";
let loadedVariant = null;
let tourActive = false;
let tourIndex = 0;
let tourTimer = null;
const state = { const state = {
floors: {}, floors: {},
categories: {}, categories: {},
@@ -43,14 +63,12 @@ const state = {
bounds: null, bounds: null,
}; };
// ───────────────────────── Scene Setup ─────────────────────────
const scene = new THREE.Scene(); const scene = new THREE.Scene();
scene.background = new THREE.Color(0x272a2d); scene.background = new THREE.Color(0x272a2d);
const renderer = new THREE.WebGLRenderer({ const renderer = new THREE.WebGLRenderer({
canvas, canvas, antialias: true, alpha: false, preserveDrawingBuffer: true,
antialias: true,
alpha: false,
preserveDrawingBuffer: true,
}); });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight); renderer.setSize(window.innerWidth, window.innerHeight);
@@ -58,24 +76,37 @@ renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.2; renderer.toneMappingExposure = 1.2;
renderer.shadowMap.enabled = true; renderer.shadowMap.enabled = true;
// Static scene: bake shadows once per change, not per frame.
renderer.shadowMap.autoUpdate = false;
renderer.shadowMap.needsUpdate = true;
renderer.localClippingEnabled = true; renderer.localClippingEnabled = true;
const camera = new THREE.PerspectiveCamera(36, window.innerWidth / window.innerHeight, 0.1, 1000); 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 camera.up.set(0, 1, 0);
const controls = new OrbitControls(camera, renderer.domElement); const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; controls.enableDamping = true;
controls.dampingFactor = 0.08; controls.dampingFactor = 0.08;
controls.screenSpacePanning = true; controls.screenSpacePanning = true;
controls.maxPolarAngle = Math.PI * 0.49; controls.maxPolarAngle = Math.PI * 0.49;
// Render on demand: a static scene re-rendered at 60 fps pegs the GPU and the
// fans for identical frames. Anything that changes what's on screen calls
// invalidate(); the loop renders only then (or while damping/autoRotate move
// the camera). window.__renders is a diagnostic frame counter.
let renderPending = true;
window.__renders = 0;
function invalidate({ shadows = false } = {}) {
if (shadows) renderer.shadowMap.needsUpdate = true;
renderPending = true;
}
controls.addEventListener("change", () => invalidate());
scene.add(new THREE.HemisphereLight(0xf7f3e8, 0x20262a, 0.9)); scene.add(new THREE.HemisphereLight(0xf7f3e8, 0x20262a, 0.9));
// Image-based lighting: cheap, no HDR download, transforms material readability.
const pmrem = new THREE.PMREMGenerator(renderer); const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture; scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
if ("environmentIntensity" in scene) scene.environmentIntensity = 0.85; if ("environmentIntensity" in scene) scene.environmentIntensity = 0.85;
// Y-up scene: the sun must sit ABOVE the model (positive Y) or shadows break.
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2); const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(-45, 85, 62); keyLight.position.set(-45, 85, 62);
keyLight.castShadow = true; keyLight.castShadow = true;
@@ -93,23 +124,53 @@ scene.add(modelRoot);
const raycaster = new THREE.Raycaster(); const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2(); 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 sectionPlane = new THREE.Plane(new THREE.Vector3(0, -1, 0), 9999);
const metadata = await fetch("./model_metadata.json?v={{BUILD}}").then((response) => response.json()); // ───────────────────────── Metadata + Init ─────────────────────────
const metadata = await fetch(`./model_metadata.json?v=${CACHE_BUST}`).then((r) => r.json());
const categoryOrder = preferredCategoryOrder.filter((key) => metadata.categories?.[key]); const categoryOrder = preferredCategoryOrder.filter((key) => metadata.categories?.[key]);
document.querySelector("#project-name").textContent = metadata.project?.name || "CAD 建筑模型"; document.querySelector("#project-name").textContent = metadata.project?.name || "CAD 建筑模型";
document.querySelector("#project-description").textContent = metadata.project?.description || "Web 展示模型"; document.querySelector("#project-description").textContent = metadata.project?.description || "Web 展示模型";
// Build building->floors mapping
if (metadata.buildings) {
for (const b of metadata.buildings) {
buildingGroups.set(b.key, new Set(b.floors));
}
} else {
// Fallback: group by the campus prefix in front of the floor token
// (assemble_campus keys: 1AF1 / 2-F3 / PDRF ... -> buildings 1A / 2- / PD)
for (const f of metadata.floors || []) {
const m = f.key.match(/^(.*?)(?:B\d+M?|F\d+M?|PH|RF)(?:_\d+)?$/);
const prefix = (m && m[1]) || "";
if (!buildingGroups.has(prefix)) buildingGroups.set(prefix, new Set());
buildingGroups.get(prefix).add(f.key);
}
}
initialiseState(metadata); initialiseState(metadata);
buildInterface(metadata); buildInterface(metadata);
restoreStateFromHash();
// ───────────────────────── Progressive Loading ─────────────────────────
const loader = new GLTFLoader(); const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader(); const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath("./node_modules/three/examples/jsm/libs/draco/"); // shipped with three; works offline dracoLoader.setDecoderPath("./node_modules/three/examples/jsm/libs/draco/");
loader.setDRACOLoader(dracoLoader); loader.setDRACOLoader(dracoLoader);
// Phase 1: load the lightest model first. Single-GLB deployments have no
// model_variants — go straight to model.glb and skip the phase-2 swap.
const modelVariants = metadata.model_variants || [];
const overviewFile = modelVariants.find((v) => v.key === "overview")?.file || null;
const standardFile = modelVariants.find((v) => v.key === "standard")?.file || "model.glb";
const firstFile = overviewFile || standardFile;
const firstTag = overviewFile ? "overview" : "standard";
loadingText.textContent = overviewFile ? "加载总览模型…" : "加载模型…";
loader.load( loader.load(
"./model.glb?v={{BUILD}}", `./${firstFile}?v=${CACHE_BUST}`,
(gltf) => { (gltf) => {
ingestModel(gltf.scene, metadata); ingestModel(gltf.scene, metadata, firstTag);
applyExplode(Number(explodeInput.value)); applyExplode(Number(explodeInput.value));
const maxZ = Math.max(6, Math.ceil((metadata.bounds?.max_z || 12) + 2)); const maxZ = Math.max(6, Math.ceil((metadata.bounds?.max_z || 12) + 2));
sectionInput.max = String(maxZ); sectionInput.max = String(maxZ);
@@ -120,12 +181,54 @@ loader.load(
updateStats(); updateStats();
updateVisibility(); updateVisibility();
loading.classList.add("hidden"); loading.classList.add("hidden");
loadedVariant = firstTag;
currentVariant = firstTag;
updateVariantUI();
// Phase 2: swap to the full model on idle (variant deployments only)
const swap = () => {
if (!overviewFile || standardFile === firstFile) return;
if (loadedVariant !== "overview") return;
loadingText.textContent = "加载标准模型…";
loading.classList.remove("hidden");
loader.load(
`./${standardFile}?v=${CACHE_BUST}`,
(gltf2) => {
// Clear old overview meshes
clearModel();
ingestModel(gltf2.scene, metadata, "standard");
applyExplode(Number(explodeInput.value));
applySection(Number(sectionInput.value));
updateVisibility();
loadedVariant = "standard";
currentVariant = "standard";
updateVariantUI();
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);
setTimeout(() => loading.classList.add("hidden"), 2000);
},
);
};
if ("requestIdleCallback" in window) {
requestIdleCallback(swap, { timeout: 3000 });
} else {
setTimeout(swap, 1500);
}
}, },
(event) => { (event) => {
if (!event.total) return; if (!event.total) return;
const pct = Math.max(8, Math.min(100, Math.round((event.loaded / event.total) * 100))); const pct = Math.max(8, Math.min(100, Math.round((event.loaded / event.total) * 100)));
loadingFill.style.width = `${pct}%`; loadingFill.style.width = `${pct}%`;
loadingText.textContent = `加载模型 ${pct}%`; loadingText.textContent = `加载总览模型 ${pct}%`;
}, },
(error) => { (error) => {
loadingText.textContent = "模型加载失败"; loadingText.textContent = "模型加载失败";
@@ -135,43 +238,19 @@ loader.load(
if (window.lucide) window.lucide.createIcons(); if (window.lucide) window.lucide.createIcons();
// ───────────────────────── State Init ─────────────────────────
function initialiseState(meta) { function initialiseState(meta) {
const disabledCategories = new Set(meta.viewer_defaults?.disabled_categories || []); const disabledCategories = new Set(meta.viewer_defaults?.disabled_categories || []);
for (const floor of meta.floors || []) state.floors[floor.key] = true; for (const floor of meta.floors || []) state.floors[floor.key] = true;
for (const key of categoryOrder) state.categories[key] = !disabledCategories.has(key); for (const key of categoryOrder) state.categories[key] = !disabledCategories.has(key);
} }
// ───────────────────────── Interface Builder ─────────────────────────
function buildInterface(meta) { function buildInterface(meta) {
floorControls.replaceChildren( buildFloorControls(meta);
...(meta.floors || []).map((floor) => buildCategoryControls(meta);
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); buildDownloadControls(meta);
buildVariantControls(meta);
explodeInput.addEventListener("input", () => { explodeInput.addEventListener("input", () => {
const value = Number(explodeInput.value); const value = Number(explodeInput.value);
@@ -179,7 +258,10 @@ function buildInterface(meta) {
applyExplode(value); applyExplode(value);
}); });
sectionInput.addEventListener("input", () => applySection(Number(sectionInput.value))); sectionInput.addEventListener("input", () => {
applySection(Number(sectionInput.value));
serializeStateToHash();
});
document.querySelectorAll("[data-preset]").forEach((button) => { document.querySelectorAll("[data-preset]").forEach((button) => {
button.addEventListener("click", () => fitCamera(button.dataset.preset)); button.addEventListener("click", () => fitCamera(button.dataset.preset));
@@ -193,6 +275,7 @@ function buildInterface(meta) {
applyExplode(0); applyExplode(0);
applySection(Number(sectionInput.max)); applySection(Number(sectionInput.max));
fitCamera("overview"); fitCamera("overview");
serializeStateToHash();
}); });
autoRotateButton.addEventListener("click", () => { autoRotateButton.addEventListener("click", () => {
@@ -202,9 +285,141 @@ function buildInterface(meta) {
controls.autoRotateSpeed = 0.8; controls.autoRotateSpeed = 0.8;
}); });
// Auto-orbit tour
tourButton?.addEventListener("click", () => {
tourActive = !tourActive;
tourButton.classList.toggle("active", tourActive);
if (tourActive) startTour();
else stopTour();
});
// Camera bookmark: saved views get a clickable list and travel in the URL
bookmarkButton?.addEventListener("click", () => {
bookmarks.push({
p: camera.position.toArray().map((n) => +n.toFixed(1)),
t: controls.target.toArray().map((n) => +n.toFixed(1)),
});
renderBookmarkList();
showToast(`已保存视角 ${bookmarks.length}`);
serializeStateToHash();
});
// Share link
shareButton?.addEventListener("click", () => {
serializeStateToHash();
const url = window.location.href;
navigator.clipboard?.writeText(url).then(() => showToast("链接已复制"));
});
document.querySelector("#snapshot").addEventListener("click", downloadSnapshot); document.querySelector("#snapshot").addEventListener("click", downloadSnapshot);
} }
// ───────────────────────── Floor Controls (Building-Grouped) ─────────────────────────
function buildFloorControls(meta) {
let buildings = meta.buildings;
if (!buildings) {
const byPrefix = new Map();
for (const f of meta.floors || []) {
const m = f.key.match(/^(.*?)(?:B\d+M?|F\d+M?|PH|RF)(?:_\d+)?$/);
const prefix = (m && m[1]) || "";
if (!byPrefix.has(prefix)) byPrefix.set(prefix, []);
byPrefix.get(prefix).push(f.key);
}
buildings = [...byPrefix.entries()].map(([prefix, floors]) => ({
key: prefix || "main",
label: prefix || (byPrefix.size > 1 ? "主体" : "全部楼层"),
floors,
}));
}
floorControls.replaceChildren();
for (const building of buildings) {
const groupEl = document.createElement("div");
groupEl.className = "building-group";
// Building header with select-all toggle
const header = document.createElement("label");
header.className = "building-header";
const headerInput = document.createElement("input");
headerInput.type = "checkbox";
headerInput.checked = true;
headerInput.addEventListener("change", () => {
for (const fk of building.floors) {
state.floors[fk] = headerInput.checked;
}
updateVisibility();
updateFloorCheckboxUI();
serializeStateToHash();
});
const headerText = document.createElement("span");
headerText.className = "building-label";
headerText.textContent = building.label;
header.append(headerInput, headerText);
groupEl.append(header);
// Floor toggles
const floorList = document.createElement("div");
floorList.className = "floor-list";
for (const fk of building.floors) {
const floor = (meta.floors || []).find((f) => f.key === fk);
if (!floor) continue;
floorList.append(
createToggle({
key: fk,
label: SCENE_FLOOR_LABELS[fk] || fk,
checked: state.floors[fk],
onChange: (checked) => {
state.floors[fk] = checked;
updateVisibility();
updateBuildingHeaderState(building, headerInput);
serializeStateToHash();
},
}),
);
}
groupEl.append(floorList);
floorControls.append(groupEl);
}
}
function updateFloorCheckboxUI() {
// Update all floor checkboxes to match state
floorControls.querySelectorAll(".toggle").forEach((toggle) => {
const key = toggle.dataset.key;
const input = toggle.querySelector("input");
if (key && state.floors[key] !== undefined) {
input.checked = state.floors[key];
}
});
}
function updateBuildingHeaderState(building, headerInput) {
const allOn = building.floors.every((fk) => state.floors[fk]);
const allOff = building.floors.every((fk) => !state.floors[fk]);
headerInput.checked = allOn;
headerInput.indeterminate = !allOn && !allOff;
}
// ───────────────────────── Category Controls ─────────────────────────
function buildCategoryControls(meta) {
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();
serializeStateToHash();
},
}),
),
);
}
// ───────────────────────── Download Controls ─────────────────────────
function buildDownloadControls(meta) { function buildDownloadControls(meta) {
const variants = meta.model_variants?.length const variants = meta.model_variants?.length
? meta.model_variants ? meta.model_variants
@@ -222,6 +437,64 @@ function buildDownloadControls(meta) {
); );
} }
// ───────────────────────── Variant Controls ─────────────────────────
function buildVariantControls(meta) {
if (!variantControls) return;
const variants = meta.model_variants || [];
variantControls.replaceChildren(
...variants.map((variant) => {
const btn = document.createElement("button");
btn.className = "variant-btn";
btn.dataset.variant = variant.key;
btn.textContent = variant.label || variant.key;
btn.title = variant.description || "";
if (variant.key === currentVariant) btn.classList.add("active");
btn.addEventListener("click", () => switchVariant(variant.key, variants));
return btn;
}),
);
}
function updateVariantUI() {
variantControls?.querySelectorAll(".variant-btn").forEach((btn) => {
btn.classList.toggle("active", btn.dataset.variant === currentVariant);
});
}
function switchVariant(variantKey, variants) {
if (variantKey === loadedVariant) return;
const variant = variants.find((v) => v.key === variantKey);
if (!variant) return;
loadingText.textContent = `加载${variant.label}…`;
loading.classList.remove("hidden");
loader.load(
`./${variant.file}?v=${CACHE_BUST}`,
(gltf) => {
clearModel();
ingestModel(gltf.scene, metadata, variantKey);
applyExplode(Number(explodeInput.value));
applySection(Number(sectionInput.value));
updateVisibility();
loadedVariant = variantKey;
currentVariant = variantKey;
updateVariantUI();
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 = `加载${variant.label} ${pct}%`;
},
(error) => {
loadingText.textContent = "变体加载失败";
console.error(error);
setTimeout(() => loading.classList.add("hidden"), 2000);
},
);
}
// ───────────────────────── Toggle Factory ─────────────────────────
function createToggle({ key, label, color, checked, onChange }) { function createToggle({ key, label, color, checked, onChange }) {
const root = document.createElement("label"); const root = document.createElement("label");
root.className = "toggle"; root.className = "toggle";
@@ -243,12 +516,35 @@ function createToggle({ key, label, color, checked, onChange }) {
return root; return root;
} }
function ingestModel(gltfScene, meta) { // ───────────────────────── Model Ingestion + Merge ─────────────────────────
function clearModel() {
for (const mesh of objectRegistry) {
mesh.geometry?.dispose();
}
objectRegistry.length = 0;
for (const [key, group] of floorGroups) {
while (group.children.length > 0) group.remove(group.children[0]);
}
// Remove merged meshes
for (const m of mergedMeshes) {
m.geometry?.dispose();
m.material?.dispose();
m.parent?.remove(m);
}
mergedMeshes.length = 0;
materialByCategory.clear();
}
function ingestModel(gltfScene, meta, variantTag) {
// Create floor groups
for (const floor of meta.floors || []) { for (const floor of meta.floors || []) {
const group = new THREE.Group(); let group = floorGroups.get(floor.key);
group.name = floor.key; if (!group) {
floorGroups.set(floor.key, group); group = new THREE.Group();
modelRoot.add(group); group.name = floor.key;
floorGroups.set(floor.key, group);
modelRoot.add(group);
}
} }
gltfScene.updateMatrixWorld(true); gltfScene.updateMatrixWorld(true);
@@ -257,6 +553,9 @@ function ingestModel(gltfScene, meta) {
if (node.isMesh) meshes.push(node); if (node.isMesh) meshes.push(node);
}); });
// Collect meshes by (floor, category) for merging
const mergeBuckets = new Map(); // "floor__category" -> { geometries: [], floor, category }
for (const mesh of meshes) { for (const mesh of meshes) {
const parsed = parseObjectName(mesh.name); const parsed = parseObjectName(mesh.name);
mesh.updateWorldMatrix(true, false); mesh.updateWorldMatrix(true, false);
@@ -270,30 +569,75 @@ function ingestModel(gltfScene, meta) {
continue; continue;
} }
if (parsed.category === "trees" && meta.site_trees?.length) { if (parsed.category === "trees" && meta.site_trees?.length) {
mesh.visible = false; // replaced by instanced trunk+crown trees below mesh.visible = false;
continue; continue;
} }
mesh.castShadow = !["grid", "floor_lines", "detail_lines", "glazing"].includes(parsed.category); const category = parsed.category;
mesh.receiveShadow = true; if (!categoryOrder.includes(category)) {
mesh.userData.floor = parsed.floor; floorGroups.get(parsed.floor).add(mesh);
mesh.userData.category = parsed.category; continue;
mesh.userData.label = labelForObject(parsed); }
if (categoryOrder.includes(parsed.category)) {
mesh.material = materialForCategory(parsed.category, meta); // Assign material before merging
addEdges(mesh, parsed.category); const material = materialForCategory(category, meta);
objectRegistry.push(mesh);
// For overview variant or small meshes, keep individual; for standard+, merge
const bucketKey = `${parsed.floor}__${category}`;
if (!mergeBuckets.has(bucketKey)) {
mergeBuckets.set(bucketKey, { geometries: [], floor: parsed.floor, category, material });
}
// Clone geometry with material group for merging
const geom = mesh.geometry.clone();
// Ensure normal and position attributes exist
if (!geom.attributes.normal) geom.computeVertexNormals();
mergeBuckets.get(bucketKey).geometries.push(geom);
}
// Merge geometries per (floor, category) — drastically reduces draw calls
for (const [bucketKey, bucket] of mergeBuckets) {
const group = floorGroups.get(bucket.floor);
if (!group) continue;
if (bucket.geometries.length <= 1) {
// Single mesh — no benefit from merging
const mesh = new THREE.Mesh(bucket.geometries[0] || new THREE.BufferGeometry(), bucket.material);
mesh.name = `${bucket.floor}__${bucket.category}`;
mesh.castShadow = !["grid", "floor_lines", "detail_lines", "glazing"].includes(bucket.category);
mesh.receiveShadow = true;
mesh.userData.floor = bucket.floor;
mesh.userData.category = bucket.category;
mesh.userData.label = labelForObject({ floor: bucket.floor, category: bucket.category });
addEdges(mesh, bucket.category);
objectRegistry.push(mesh);
group.add(mesh);
} else {
// Merge all geometries of same material into one mesh
const merged = mergeGeometries(bucket.geometries, false);
// Clean up source geometries
bucket.geometries.forEach((g) => g.dispose());
const mesh = new THREE.Mesh(merged, bucket.material);
mesh.name = `${bucket.floor}__${bucket.category}`;
mesh.castShadow = !["grid", "floor_lines", "detail_lines", "glazing"].includes(bucket.category);
mesh.receiveShadow = true;
mesh.userData.floor = bucket.floor;
mesh.userData.category = bucket.category;
mesh.userData.label = labelForObject({ floor: bucket.floor, category: bucket.category });
mesh.userData.mergedCount = bucket.geometries.length;
addEdges(mesh, bucket.category);
objectRegistry.push(mesh);
mergedMeshes.push(mesh);
group.add(mesh);
} }
floorGroups.get(parsed.floor).add(mesh);
} }
if (meta.site_trees?.length) addInstancedTrees(meta.site_trees); if (meta.site_trees?.length) addInstancedTrees(meta.site_trees);
state.bounds = new THREE.Box3().setFromObject(modelRoot); state.bounds = new THREE.Box3().setFromObject(modelRoot);
fitShadowsAndGround(state.bounds); fitShadowsAndGround(state.bounds);
invalidate({ shadows: true });
} }
function addInstancedTrees(points) { function addInstancedTrees(points) {
// spec plan coords (x, y) -> Y-up world (x, ?, -y), same mapping as the GLB export
const trunk = new THREE.InstancedMesh( const trunk = new THREE.InstancedMesh(
new THREE.CylinderGeometry(0.14, 0.2, 1.4, 6), new THREE.CylinderGeometry(0.14, 0.2, 1.4, 6),
new THREE.MeshStandardMaterial({ color: 0x6b4a2e, roughness: 0.9, clippingPlanes: [sectionPlane] }), new THREE.MeshStandardMaterial({ color: 0x6b4a2e, roughness: 0.9, clippingPlanes: [sectionPlane] }),
@@ -318,7 +662,6 @@ function addInstancedTrees(points) {
} }
function fitShadowsAndGround(bounds) { function fitShadowsAndGround(bounds) {
// Default directional-shadow frustum is ±5 m — useless for buildings.
const center = bounds.getCenter(new THREE.Vector3()); const center = bounds.getCenter(new THREE.Vector3());
const size = bounds.getSize(new THREE.Vector3()); const size = bounds.getSize(new THREE.Vector3());
const radius = Math.max(size.x, size.z, 20) * 0.75; const radius = Math.max(size.x, size.z, 20) * 0.75;
@@ -333,19 +676,16 @@ function fitShadowsAndGround(bounds) {
new THREE.ShadowMaterial({ opacity: 0.32 }), new THREE.ShadowMaterial({ opacity: 0.32 }),
); );
ground.rotation.x = -Math.PI / 2; ground.rotation.x = -Math.PI / 2;
// Grade sits at y=0 by spec convention; bounds.min.y is the BASEMENT floor
// when one exists, and a catcher 5 m below grade shows shadows detached
// from the building. Clamp to grade unless the whole model floats above it.
const groundY = Math.max(bounds.min.y, Math.min(0, bounds.max.y)) - 0.03; const groundY = Math.max(bounds.min.y, Math.min(0, bounds.max.y)) - 0.03;
ground.position.set(center.x, groundY, center.z); ground.position.set(center.x, groundY, center.z);
ground.receiveShadow = true; ground.receiveShadow = true;
scene.add(ground); scene.add(ground);
} }
// ───────────────────────── Name Parsing ─────────────────────────
function parseObjectName(name) { function parseObjectName(name) {
const match = name.match(/^(.+)__(.+)$/); const match = name.match(/^(.+)__(.+)$/);
if (!match) return null; if (!match) return null;
// strip Blender's auto de-dup suffix (e.g. "1F__slab.001" -> category "slab")
const category = match[2].replace(/\.\d+$/, ""); const category = match[2].replace(/\.\d+$/, "");
return { floor: match[1], category }; return { floor: match[1], category };
} }
@@ -354,11 +694,11 @@ function labelForObject({ floor, category }) {
return `${floor} ${metadata.categories?.[category]?.label || category}`; return `${floor} ${metadata.categories?.[category]?.label || category}`;
} }
// ───────────────────────── Materials ─────────────────────────
function materialForCategory(category, meta) { function materialForCategory(category, meta) {
if (materialByCategory.has(category)) return materialByCategory.get(category); if (materialByCategory.has(category)) return materialByCategory.get(category);
const color = new THREE.Color(meta.categories[category]?.color || "#cccccc"); const color = new THREE.Color(meta.categories[category]?.color || "#cccccc");
if (category === "glazing") { if (category === "glazing") {
// Physical glass (transmission) instead of flat alpha — key perceived-quality win.
const glass = new THREE.MeshPhysicalMaterial({ const glass = new THREE.MeshPhysicalMaterial({
color, metalness: 0, roughness: 0.18, transmission: 0.7, ior: 1.5, thickness: 0.3, color, metalness: 0, roughness: 0.18, transmission: 0.7, ior: 1.5, thickness: 0.3,
transparent: true, depthWrite: false, side: THREE.DoubleSide, clippingPlanes: [sectionPlane], transparent: true, depthWrite: false, side: THREE.DoubleSide, clippingPlanes: [sectionPlane],
@@ -368,26 +708,16 @@ function materialForCategory(category, meta) {
return glass; return glass;
} }
const opacity = const opacity =
category === "slab" category === "slab" ? 0.64
? 0.64 : category === "roof" ? 0.95
: category === "roof" : category === "detail_lines" ? 0.72
? 0.95 : category === "grid" || category === "floor_lines" ? 0.88
: category === "glazing" : category === "doors" ? 0.90
? 0.36 : 1;
: category === "detail_lines"
? 0.72
: category === "grid" || category === "floor_lines"
? 0.88
: category === "doors"
? 0.90
: 1;
const material = new THREE.MeshStandardMaterial({ const material = new THREE.MeshStandardMaterial({
color, color, transparent: opacity < 1, opacity,
transparent: opacity < 1,
opacity,
depthWrite: category === "slab" ? true : opacity >= 0.8, depthWrite: category === "slab" ? true : opacity >= 0.8,
roughness: 0.74, roughness: 0.74, metalness: 0.02,
metalness: 0.02,
side: category === "slab" || category === "roof" ? THREE.DoubleSide : THREE.FrontSide, side: category === "slab" || category === "roof" ? THREE.DoubleSide : THREE.FrontSide,
clippingPlanes: [sectionPlane], clippingPlanes: [sectionPlane],
}); });
@@ -404,41 +734,53 @@ function addEdges(mesh, category) {
mesh.add(edges); mesh.add(edges);
} }
// ───────────────────────── Explode / Section / Visibility ─────────────────────────
function applyExplode(distance) { function applyExplode(distance) {
const floors = metadata.floors || []; const floors = metadata.floors || [];
for (const [index, floor] of floors.entries()) { for (const [index, floor] of floors.entries()) {
const group = floorGroups.get(floor.key); const group = floorGroups.get(floor.key);
if (group) group.position.y = index * distance; // Y-up: explode floors along Y if (group) group.position.y = index * distance;
} }
updateStats(); updateStats();
invalidate({ shadows: true });
} }
function applySection(height) { function applySection(height) {
const max = Number(sectionInput.max); const max = Number(sectionInput.max);
sectionPlane.constant = height >= max ? 9999 : height; sectionPlane.constant = height >= max ? 9999 : height;
sectionValue.textContent = height >= max ? "关闭" : `${height.toFixed(2)}m`; sectionValue.textContent = height >= max ? "关闭" : `${height.toFixed(2)}m`;
invalidate({ shadows: true });
} }
function updateVisibility() { function updateVisibility() {
for (const mesh of objectRegistry) { for (const mesh of objectRegistry) {
mesh.visible = Boolean(state.floors[mesh.userData.floor] && state.categories[mesh.userData.category]); mesh.visible = Boolean(state.floors[mesh.userData.floor] && state.categories[mesh.userData.category]);
} }
for (const [floorKey, group] of floorGroups.entries()) { for (const [floorKey, group] of floorGroups) {
group.visible = Boolean(state.floors[floorKey]); group.visible = Boolean(state.floors[floorKey]);
} }
updateStats(); updateStats();
invalidate({ shadows: true });
} }
// ───────────────────────── Stats (with draw call count) ─────────────────────────
function updateStats() { function updateStats() {
const activeFloors = Object.values(state.floors).filter(Boolean).length; const activeFloors = Object.values(state.floors).filter(Boolean).length;
const activeCategories = Object.values(state.categories).filter(Boolean).length; const activeCategories = Object.values(state.categories).filter(Boolean).length;
const visibleMeshes = objectRegistry.filter((mesh) => mesh.visible !== false); const visibleMeshes = objectRegistry.filter((mesh) => mesh.visible !== false);
const vertices = visibleMeshes.reduce((sum, mesh) => sum + mesh.geometry.attributes.position.count, 0); const vertices = visibleMeshes.reduce((sum, mesh) => sum + mesh.geometry.attributes.position.count, 0);
// Estimate draw calls: each visible mesh = 1 draw call (edges add +1 each)
const drawCalls = visibleMeshes.reduce((sum, mesh) => {
let dc = 1;
if (mesh.children.some((c) => c.isLineSegments)) dc++;
return sum + dc;
}, 0);
stats.innerHTML = ""; stats.innerHTML = "";
for (const item of [ for (const item of [
["楼层", `${activeFloors}/${(metadata.floors || []).length}`], ["楼层", `${activeFloors}/${(metadata.floors || []).length}`],
["构件", `${activeCategories}/${categoryOrder.length}`], ["构件", `${activeCategories}/${categoryOrder.length}`],
["顶点", vertices.toLocaleString("zh-CN")], ["顶点", vertices.toLocaleString("zh-CN")],
["绘制批次", drawCalls.toString()],
]) { ]) {
const cell = document.createElement("div"); const cell = document.createElement("div");
cell.innerHTML = `<dt>${item[0]}</dt><dd>${item[1]}</dd>`; cell.innerHTML = `<dt>${item[0]}</dt><dd>${item[1]}</dd>`;
@@ -446,6 +788,7 @@ function updateStats() {
} }
} }
// ───────────────────────── Camera ─────────────────────────
function fitCamera(preset) { function fitCamera(preset) {
const box = new THREE.Box3().setFromObject(modelRoot); const box = new THREE.Box3().setFromObject(modelRoot);
state.bounds = box; state.bounds = box;
@@ -453,12 +796,12 @@ function fitCamera(preset) {
const size = box.getSize(new THREE.Vector3()); const size = box.getSize(new THREE.Vector3());
const maxSize = Math.max(size.x, size.y, size.z, 1); const maxSize = Math.max(size.x, size.y, size.z, 1);
if (preset === "top") { if (preset === "top") {
camera.position.set(center.x, center.y + maxSize * 1.45, center.z); camera.position.set(center.x, center.y + maxSize * 1.22, center.z);
} else if (preset === "side") { } else if (preset === "side") {
camera.position.set(center.x, center.y + maxSize * 0.18, center.z + maxSize * 1.35); camera.position.set(center.x, center.y + maxSize * 0.18, center.z + maxSize * 1.15);
} else { } else {
// bird's-eye 3/4 aerial (~55° looking down); Y is up (glTF standard) // 园区模型默认占据更多画面;OrbitControls 仍允许用户自由拉远。
const d = maxSize * 1.4; const d = maxSize * 1.15;
const L = Math.hypot(0.55, 1.0, 0.7); 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.position.set(center.x - (0.55 / L) * d, center.y + (1.0 / L) * d, center.z + (0.7 / L) * d);
} }
@@ -467,8 +810,135 @@ function fitCamera(preset) {
camera.updateProjectionMatrix(); camera.updateProjectionMatrix();
controls.target.copy(center); controls.target.copy(center);
controls.update(); controls.update();
serializeStateToHash();
invalidate();
} }
// ───────────────────────── Auto-Orbit Tour ─────────────────────────
function startTour() {
tourIndex = 0;
const next = () => {
if (!tourActive) return;
fitCamera(TOUR_PRESETS[tourIndex % TOUR_PRESETS.length]);
tourIndex++;
tourTimer = setTimeout(next, 5000);
};
next();
}
function stopTour() {
if (tourTimer) clearTimeout(tourTimer);
tourTimer = null;
}
// ───────────────────────── Bookmark List ─────────────────────────
function renderBookmarkList() {
if (!bookmarkList) return;
bookmarkList.replaceChildren(
...bookmarks.map((bm, index) => {
const item = document.createElement("span");
item.className = "bookmark-item";
const go = document.createElement("button");
go.textContent = `视角${index + 1}`;
go.addEventListener("click", () => {
camera.position.set(...bm.p);
controls.target.set(...bm.t);
controls.update();
invalidate();
});
const remove = document.createElement("button");
remove.className = "bookmark-remove";
remove.textContent = "\u00d7";
remove.title = "删除该视角";
remove.addEventListener("click", () => {
bookmarks.splice(index, 1);
renderBookmarkList();
serializeStateToHash();
});
item.append(go, remove);
return item;
}),
);
}
// ───────────────────────── URL Hash State ─────────────────────────
function encodeHashState(value) {
const bytes = new TextEncoder().encode(value);
let binary = "";
for (let index = 0; index < bytes.length; index += 0x8000) {
binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));
}
return btoa(binary).replace(/=/g, "");
}
function decodeHashState(value) {
const padded = value + "=".repeat((4 - (value.length % 4)) % 4);
const binary = atob(padded);
return new TextDecoder().decode(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
}
function serializeStateToHash() {
const hash = {
f: Object.entries(state.floors).filter(([, v]) => !v).map(([k]) => k), // only store disabled
c: Object.entries(state.categories).filter(([, v]) => !v).map(([k]) => k),
s: sectionInput.value,
e: explodeInput.value,
cam: {
p: [camera.position.x, camera.position.y, camera.position.z].map((n) => +n.toFixed(1)),
t: [controls.target.x, controls.target.y, controls.target.z].map((n) => +n.toFixed(1)),
},
b: bookmarks,
};
const encoded = encodeHashState(JSON.stringify(hash));
history.replaceState(null, "", `#${encoded}`);
}
function restoreStateFromHash() {
try {
const raw = window.location.hash.slice(1);
if (!raw) return;
const hash = JSON.parse(decodeHashState(raw));
if (hash.f) for (const fk of hash.f) { if (fk in state.floors) state.floors[fk] = false; }
if (hash.c) for (const ck of hash.c) { if (ck in state.categories) state.categories[ck] = false; }
if (hash.s) { sectionInput.value = hash.s; applySection(Number(hash.s)); }
if (hash.e) { explodeInput.value = hash.e; applyExplode(Number(hash.e)); explodeValue.textContent = `${Number(hash.e).toFixed(Number(hash.e) % 1 ? 1 : 0)}m`; }
if (Array.isArray(hash.b)) {
bookmarks.push(...hash.b.filter((bm) => Array.isArray(bm.p) && Array.isArray(bm.t)));
renderBookmarkList();
}
if (hash.cam?.p && hash.cam?.t) {
pendingCameraRestore = hash.cam;
}
} catch (e) {
// ignore malformed hash
}
}
let pendingCameraRestore = null;
function applyPendingCamera() {
if (!pendingCameraRestore) return;
camera.position.set(...pendingCameraRestore.p);
controls.target.set(...pendingCameraRestore.t);
controls.update();
pendingCameraRestore = null;
}
// ───────────────────────── Toast ─────────────────────────
function showToast(msg) {
let toast = document.querySelector("#toast");
if (!toast) {
toast = document.createElement("div");
toast.id = "toast";
toast.className = "toast";
document.body.append(toast);
}
toast.textContent = msg;
toast.classList.add("show");
clearTimeout(toast._timer);
toast._timer = setTimeout(() => toast.classList.remove("show"), 2200);
}
// ───────────────────────── Screenshot ─────────────────────────
function downloadSnapshot() { function downloadSnapshot() {
const link = document.createElement("a"); const link = document.createElement("a");
link.download = "cad-building-showcase.png"; link.download = "cad-building-showcase.png";
@@ -476,7 +946,10 @@ function downloadSnapshot() {
link.click(); link.click();
} }
// ───────────────────────── Raycast Picking ─────────────────────────
window.addEventListener("pointerdown", (event) => { window.addEventListener("pointerdown", (event) => {
// Ignore clicks on UI panels
if (event.target !== canvas) return;
pointer.x = (event.clientX / window.innerWidth) * 2 - 1; pointer.x = (event.clientX / window.innerWidth) * 2 - 1;
pointer.y = -(event.clientY / window.innerHeight) * 2 + 1; pointer.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(pointer, camera); raycaster.setFromCamera(pointer, camera);
@@ -489,19 +962,30 @@ window.addEventListener("pointerdown", (event) => {
const object = objectRegistry.find((mesh) => mesh === hit.object || mesh.children.includes(hit.object)); const object = objectRegistry.find((mesh) => mesh === hit.object || mesh.children.includes(hit.object));
if (!object) return; if (!object) return;
inspect.querySelector(".inspect-title").textContent = object.userData.label; inspect.querySelector(".inspect-title").textContent = object.userData.label;
inspect.querySelector(".inspect-body").textContent = `楼层 ${object.userData.floor} / 类别 ${object.userData.category}`; const mergedInfo = object.userData.mergedCount ? ` (${object.userData.mergedCount} 合并)` : "";
inspect.querySelector(".inspect-body").textContent = `楼层 ${object.userData.floor} / 类别 ${object.userData.category}${mergedInfo}`;
}); });
// ───────────────────────── Resize ─────────────────────────
window.addEventListener("resize", () => { window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight; camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix(); camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight); renderer.setSize(window.innerWidth, window.innerHeight);
}); });
// ───────────────────────── Animation Loop ─────────────────────────
function animate() { function animate() {
requestAnimationFrame(animate); requestAnimationFrame(animate);
controls.update(); const moved = controls.update(); // true while damping/autoRotate move the camera
renderer.render(scene, camera); if (pendingCameraRestore && modelRoot.children.length > 0) {
applyPendingCamera();
invalidate();
}
if (moved || renderPending) {
renderer.render(scene, camera);
window.__renders += 1;
renderPending = false;
}
} }
animate(); animate();

View File

@@ -4,7 +4,7 @@
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{{TITLE}}</title> <title>{{TITLE}}</title>
<link rel="icon" href="data:," /><!-- keep the console free of favicon 404s --> <link rel="icon" href="data:," />
<link rel="stylesheet" href="./styles.css" /> <link rel="stylesheet" href="./styles.css" />
<script type="importmap"> <script type="importmap">
{ {
@@ -33,7 +33,7 @@
<section class="panel controls-panel" aria-label="控制"> <section class="panel controls-panel" aria-label="控制">
<div class="control-group"> <div class="control-group">
<div class="group-label">楼层</div> <div class="group-label">楼层</div>
<div class="segmented" id="floor-controls"></div> <div id="floor-controls"></div>
</div> </div>
<div class="control-group"> <div class="control-group">
@@ -41,6 +41,11 @@
<div class="toggle-grid" id="category-controls"></div> <div class="toggle-grid" id="category-controls"></div>
</div> </div>
<div class="control-group">
<div class="group-label">模型变体</div>
<div class="variant-list" id="variant-controls"></div>
</div>
<div class="control-group"> <div class="control-group">
<div class="group-label">下载</div> <div class="group-label">下载</div>
<div class="download-list" id="download-controls"></div> <div class="download-list" id="download-controls"></div>
@@ -76,6 +81,16 @@
<button class="tool-button" id="auto-rotate" title="自动旋转" aria-label="自动旋转"> <button class="tool-button" id="auto-rotate" title="自动旋转" aria-label="自动旋转">
<i data-lucide="rotate-3d"></i> <i data-lucide="rotate-3d"></i>
</button> </button>
<button class="tool-button" id="auto-tour" title="自动巡航" aria-label="自动巡航">
<i data-lucide="plane"></i>
</button>
<button class="tool-button" id="bookmark" title="保存视角" aria-label="保存视角">
<i data-lucide="bookmark"></i>
</button>
<button class="tool-button" id="share-link" title="复制分享链接" aria-label="复制分享链接">
<i data-lucide="share-2"></i>
</button>
<div id="bookmark-list" class="bookmark-list"></div>
<button class="tool-button" id="reset-view" title="重置视角" aria-label="重置视角"> <button class="tool-button" id="reset-view" title="重置视角" aria-label="重置视角">
<i data-lucide="rotate-ccw"></i> <i data-lucide="rotate-ccw"></i>
</button> </button>

View File

@@ -85,7 +85,7 @@ p {
.stats-grid { .stats-grid {
display: grid; display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr)); grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px; gap: 8px;
margin: 14px 0 0; margin: 14px 0 0;
} }
@@ -100,13 +100,13 @@ p {
.stats-grid dt { .stats-grid dt {
color: var(--muted); color: var(--muted);
font-size: 11px; font-size: 10px;
} }
.stats-grid dd { .stats-grid dd {
margin: 3px 0 0; margin: 3px 0 0;
color: var(--ink); color: var(--ink);
font-size: 14px; font-size: 13px;
font-weight: 700; font-weight: 700;
white-space: nowrap; white-space: nowrap;
overflow: hidden; overflow: hidden;
@@ -117,9 +117,19 @@ p {
left: 20px; left: 20px;
bottom: 20px; bottom: 20px;
width: min(384px, calc(100vw - 40px)); width: min(384px, calc(100vw - 40px));
max-height: calc(100vh - 280px);
overflow-y: auto;
padding: 14px; padding: 14px;
} }
.controls-panel::-webkit-scrollbar {
width: 6px;
}
.controls-panel::-webkit-scrollbar-thumb {
background: rgba(0,0,0,0.18);
border-radius: 3px;
}
.control-group + .control-group { .control-group + .control-group {
margin-top: 13px; margin-top: 13px;
padding-top: 13px; padding-top: 13px;
@@ -140,9 +150,48 @@ p {
margin-bottom: 8px; margin-bottom: 8px;
} }
.segmented, /* ── Building-grouped floor controls ── */
.toggle-grid, .building-group {
.download-list { margin-bottom: 10px;
}
.building-group:last-child {
margin-bottom: 0;
}
.building-header {
display: flex;
align-items: center;
gap: 7px;
padding: 5px 8px;
border-radius: 6px;
background: rgba(47, 125, 112, 0.1);
color: var(--accent);
font-size: 12px;
font-weight: 800;
cursor: pointer;
user-select: none;
margin-bottom: 5px;
}
.building-header input {
width: 13px;
height: 13px;
accent-color: var(--accent);
}
.building-label {
flex: 1;
}
.floor-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding-left: 4px;
}
.toggle-grid {
display: flex; display: flex;
flex-wrap: wrap; flex-wrap: wrap;
gap: 6px; gap: 6px;
@@ -177,6 +226,36 @@ p {
border: 1px solid rgba(0, 0, 0, 0.2); border: 1px solid rgba(0, 0, 0, 0.2);
} }
/* ── Variant controls ── */
.variant-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.variant-btn {
min-height: 32px;
padding: 6px 12px;
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;
transition: background 0.15s;
}
.variant-btn:hover {
background: rgba(47, 125, 112, 0.12);
}
.variant-btn.active {
background: var(--accent);
color: #fff;
border-color: var(--accent);
}
.download-link { .download-link {
min-height: 32px; min-height: 32px;
display: inline-flex; display: inline-flex;
@@ -205,12 +284,14 @@ input[type="range"] {
right: 20px; right: 20px;
top: 20px; top: 20px;
display: flex; display: flex;
flex-wrap: wrap;
gap: 8px; gap: 8px;
padding: 8px; padding: 8px;
border-radius: 8px; border-radius: 8px;
background: rgba(32, 35, 38, 0.86); background: rgba(32, 35, 38, 0.86);
box-shadow: var(--shadow); box-shadow: var(--shadow);
backdrop-filter: blur(16px); backdrop-filter: blur(16px);
max-width: 200px;
} }
.tool-button { .tool-button {
@@ -284,6 +365,31 @@ input[type="range"] {
width: 12%; width: 12%;
height: 100%; height: 100%;
background: #d1a445; background: #d1a445;
transition: width 0.3s;
}
/* ── Toast ── */
.toast {
position: fixed;
bottom: 80px;
left: 50%;
transform: translateX(-50%) translateY(20px);
padding: 10px 20px;
border-radius: 8px;
background: rgba(32, 35, 38, 0.95);
color: #f6f4ec;
font-size: 13px;
font-weight: 600;
box-shadow: var(--shadow);
opacity: 0;
pointer-events: none;
transition: opacity 0.25s, transform 0.25s;
z-index: 9999;
}
.toast.show {
opacity: 1;
transform: translateX(-50%) translateY(0);
} }
@media (max-width: 760px) { @media (max-width: 760px) {
@@ -297,6 +403,7 @@ input[type="range"] {
top: auto; top: auto;
right: 10px; right: 10px;
bottom: 10px; bottom: 10px;
max-width: 152px;
} }
.controls-panel { .controls-panel {
@@ -310,4 +417,42 @@ input[type="range"] {
.inspect-panel { .inspect-panel {
display: none; display: none;
} }
.stats-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
/* ── Camera bookmarks ─────────────────────────────── */
.bookmark-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
max-width: 220px;
}
.bookmark-item {
display: inline-flex;
align-items: stretch;
border: 1px solid var(--line);
border-radius: 6px;
overflow: hidden;
background: rgba(255, 255, 255, 0.58);
}
.bookmark-item button {
border: 0;
background: transparent;
color: var(--ink);
font-size: 12px;
font-weight: 700;
padding: 4px 8px;
cursor: pointer;
}
.bookmark-item button:hover {
background: rgba(47, 125, 112, 0.12);
}
.bookmark-item .bookmark-remove {
padding: 4px 6px;
font-weight: 400;
opacity: 0.55;
border-left: 1px solid var(--line);
} }

View File

@@ -1,4 +1,4 @@
> 归档:skill 早期迭代时使用的工作提示词,仅作历史记录;文中路径以当时的仓库布局为准。 > 归档:skill 早期迭代时使用的工作提示词,仅作历史记录;文中路径以当时的仓库布局为准。当前规则以 `SKILL.md` 为准。
# Claude Code 提示词:CAD 展示模型 skill 剩余改进项 # Claude Code 提示词:CAD 展示模型 skill 剩余改进项

View File

@@ -1,5 +1,7 @@
# Skill 泛化测试记录(test3d-7 三项目,2026-07-02 起) # Skill 泛化测试记录(test3d-7 三项目,2026-07-02 起)
> 历史工程日志;当前规则以 `SKILL.md` 与 `references/` 为准。
目的:验证 cad-building-showcase skill 在不同 CAD 图纸上能否达到与贝昂案例 目的:验证 cad-building-showcase skill 在不同 CAD 图纸上能否达到与贝昂案例
同等的 3D 模型质量。判定标尺 = One-Shot Definition of Done 七条门禁 + 同等的 3D 模型质量。判定标尺 = One-Shot Definition of Done 七条门禁 +
量化指标 + 固定目检清单,任何门禁失败 → 修 skill(不绕过)→ 重跑。 量化指标 + 固定目检清单,任何门禁失败 → 修 skill(不绕过)→ 重跑。
@@ -330,6 +332,16 @@ glazing 在 walls 之前匹配。3.0m×22 层梯(0..66,机房顶69)。
时点名"陌生方言,先自觉建映射"。 时点名"陌生方言,先自觉建映射"。
三门禁未布防时 SKIP(既有项目零影响),新项目应全部布防。回归 +8 项。 三门禁未布防时 SKIP(既有项目零影响),新项目应全部布防。回归 +8 项。
24. **Web 模板功能移植 + 按需渲染**(test3d-5 会话演进版回收进模板,2026-07-04):
变体页内热切换、分享链接(全状态进 URL hash)、自动巡游、toast、建筑分组
楼层控制(无 buildings 字段时按楼层键前缀回退分组)、按(楼层,类别)合并
网格削 draw call、渐进加载(单 GLB 部署自动跳过二段加载);书签补全
(列表+恢复+删除+入 hash)。**按需渲染**根治"网页开着风扇狂转":静态场景
只在变更时渲染(invalidate() + damping/autoRotate 期间连续),阴影
autoUpdate=false 按变更重烤,模板与离线 viewer 同一契约;27号 实测
模板 web 静止 3 秒 0 帧、离线 viewer 加载全程仅 25 帧。`window.__renders`
为诊断计数,DoD 目检可要求"静止时不增长"。
**仍留档**:⑦ 未命名详图簇(核心筒大样)仍靠 clip 带宽人工剔除,标题纯度 **仍留档**:⑦ 未命名详图簇(核心筒大样)仍靠 clip 带宽人工剔除,标题纯度
只覆盖有名字的辅助框(需要"详图簇 vs 楼层框"的几何判别设计);2# 的 只覆盖有名字的辅助框(需要"详图簇 vs 楼层框"的几何判别设计);2# 的
"十九、二十一层平面图"修改单簇(无障碍改造相关)未并入模型(需用户确认 "十九、二十一层平面图"修改单簇(无障碍改造相关)未并入模型(需用户确认

View File

@@ -1,5 +1,7 @@
# 贝昂科技厂区 CAD:为什么生成错了 + skill 优化记录 # 贝昂科技厂区 CAD:为什么生成错了 + skill 优化记录
> 历史复盘;当前操作规范以 `SKILL.md` 与 `references/` 为准。
日期:2026-07-02 | 源数据:`test3d-6/fs贝昂科技_新建项目cad20250728` 日期:2026-07-02 | 源数据:`test3d-6/fs贝昂科技_新建项目cad20250728`
## 一、错误原因诊断 ## 一、错误原因诊断

61
package-lock.json generated
View File

@@ -4,11 +4,16 @@
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "cad-building-showcase",
"dependencies": { "dependencies": {
"@gltf-transform/core": "^4.4.1", "@gltf-transform/core": "^4.4.1",
"@gltf-transform/extensions": "^4.4.1", "@gltf-transform/extensions": "^4.4.1",
"@gltf-transform/functions": "^4.4.1", "@gltf-transform/functions": "^4.4.1",
"@mlightcad/libredwg-web": "0.7.8",
"draco3dgltf": "^1.5.7" "draco3dgltf": "^1.5.7"
},
"devDependencies": {
"playwright": "^1.52.0"
} }
}, },
"node_modules/@emnapi/runtime": { "node_modules/@emnapi/runtime": {
@@ -528,6 +533,15 @@
"url": "https://opencollective.com/libvips" "url": "https://opencollective.com/libvips"
} }
}, },
"node_modules/@mlightcad/libredwg-web": {
"version": "0.7.8",
"resolved": "https://registry.npmjs.org/@mlightcad/libredwg-web/-/libredwg-web-0.7.8.tgz",
"integrity": "sha512-3ol9nxsCr5YJarcUs8Pv5WM8MvF45H3Gi8M3/GA4o8sahwG0Ehfz8Nh3OnxuX+pxQCt+pm9n8DFCeOf7kaU81A==",
"license": "GPL-3.0",
"engines": {
"node": ">=20"
}
},
"node_modules/@types/ndarray": { "node_modules/@types/ndarray": {
"version": "1.0.14", "version": "1.0.14",
"resolved": "https://registry.npmjs.org/@types/ndarray/-/ndarray-1.0.14.tgz", "resolved": "https://registry.npmjs.org/@types/ndarray/-/ndarray-1.0.14.tgz",
@@ -558,6 +572,21 @@
"integrity": "sha512-LeqcpmoHIyYUi0z70/H3tMkGj8QhqVxq6FJGPjlzR24BNkQ6jyMheMvFKJBI0dzGZrEOUyQEmZ8axM1xRrbRiw==", "integrity": "sha512-LeqcpmoHIyYUi0z70/H3tMkGj8QhqVxq6FJGPjlzR24BNkQ6jyMheMvFKJBI0dzGZrEOUyQEmZ8axM1xRrbRiw==",
"license": "Apache-2.0" "license": "Apache-2.0"
}, },
"node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/iota-array": { "node_modules/iota-array": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/iota-array/-/iota-array-1.0.0.tgz", "resolved": "https://registry.npmjs.org/iota-array/-/iota-array-1.0.0.tgz",
@@ -617,6 +646,38 @@
"sharp": "^0.34.0" "sharp": "^0.34.0"
} }
}, },
"node_modules/playwright": {
"version": "1.61.1",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz",
"integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.61.1"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.61.1",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz",
"integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/property-graph": { "node_modules/property-graph": {
"version": "4.1.0", "version": "4.1.0",
"resolved": "https://registry.npmjs.org/property-graph/-/property-graph-4.1.0.tgz", "resolved": "https://registry.npmjs.org/property-graph/-/property-graph-4.1.0.tgz",

View File

@@ -1,5 +1,16 @@
{ {
"name": "cad-building-showcase",
"private": true,
"scripts": {
"check:js": "node --check assets/web-showcase-template/app.js && node --check scripts/dwg_dump_json.mjs && node --check scripts/web_smoke_test.mjs && node --check scripts/offline_viewer_smoke.mjs && node --check tools/compress.mjs",
"smoke:web": "node scripts/web_smoke_test.mjs",
"smoke:offline": "node scripts/offline_viewer_smoke.mjs"
},
"devDependencies": {
"playwright": "^1.52.0"
},
"dependencies": { "dependencies": {
"@mlightcad/libredwg-web": "0.7.8",
"@gltf-transform/core": "^4.4.1", "@gltf-transform/core": "^4.4.1",
"@gltf-transform/extensions": "^4.4.1", "@gltf-transform/extensions": "^4.4.1",
"@gltf-transform/functions": "^4.4.1", "@gltf-transform/functions": "^4.4.1",

14
pyproject.toml Normal file
View File

@@ -0,0 +1,14 @@
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q"
[tool.ruff]
target-version = "py310"
line-length = 120
[tool.ruff.lint]
select = ["E4", "E7", "E9", "F"]
[tool.ruff.format]
quote-style = "double"
indent-style = "space"

View File

@@ -1,5 +1,12 @@
# A208 Case Notes # A208 Case Notes
## Contents
1. Source/conversion calibration
2. Layer and alignment signals
3. Showcase/IFC results
4. Presentation calibration
These notes capture the proven workflow from the A208 CAD-to-3D exploration. Use them as calibration, not as hardcoded constants. These notes capture the proven workflow from the A208 CAD-to-3D exploration. Use them as calibration, not as hardcoded constants.
## Source Set ## Source Set

29
references/bim_branch.md Normal file
View File

@@ -0,0 +1,29 @@
# BIM and IFC Branch
Use this branch only when the user explicitly requests IFC, BIM-like semantics, or asks whether the showcase can replace BIM.
## Claim Levels
- `Web showcase`: CAD-derived visual model; never BIM replacement.
- `Massing/LOD100-150`: approximate floor/wall/structure visualization.
- `IFC/BIM proof`: IFC entities, storeys, containment, properties, and geometry validation exist.
- `BIM replacement candidate`: require discipline-specific semantics, openings, spaces, quantities, materials, classifications, georeferencing, coordination, and human review. The bundled proof script alone does not reach this level.
## Generate and Validate
Run:
```bash
python3 scripts/build_ifc_poc.py \
--spec outputs/<project>/building_spec.json \
--out-ifc outputs/<project>/<project>_proof.ifc \
--out-report outputs/<project>/<project>_proof_report.json \
--out-notes outputs/<project>/<project>_proof_notes.md \
--vendor-dir work/vendor --validate-geometry
```
Require schema validity, storey/spatial containment, `IfcWall`/`IfcColumn`/`IfcBeam`/`IfcSlab` counts, property sets, and geometry results. Explain every geometry failure.
When Blender cannot import IFC directly, run `extract_ifc_meshes.py` and render with `render_ifc_meshes_blender.py`. Do not imply that a rendered IFC proves production BIM completeness.
Always list remaining gaps: joins, openings, doors/windows, rooms/spaces, quantities, materials, classifications, levels, georeferencing, MEP, and discipline coordination.

View File

@@ -1,19 +1,28 @@
# building_spec.json Schema # building_spec.json Schema
Use `building_spec.json` as the contract between CAD extraction, Blender generation, and the Web showcase. Use `building_spec.json` as the versioned contract between extraction, Blender, trimesh, IFC, and Web delivery. The executable schema is `schemas/building_spec.schema.json`; validate with `python3 scripts/showcase_schema.py spec <file>`.
## Contents
1. Top-level contract
2. Segment/category/footprint semantics
3. Generation config keys
4. Object naming and metadata
5. Precision labels
## Top Level ## Top Level
```json ```json
{ {
"schema_version": 1,
"project": { "project": {
"name": "Project name", "name": "Project name",
"description": "Short user-facing description" "description": "Short user-facing description"
}, },
"source": { "source": {
"cad_folder": "work/XREF", "dxf_dir": "work/cad_showcase/dxf_sanitized",
"report": "outputs/cad_read_report.json",
"config": { "config": {
"config_version": 1,
"generate_footprints": true, "generate_footprints": true,
"use_footprint_slabs": true, "use_footprint_slabs": true,
"use_footprint_roofs": true, "use_footprint_roofs": true,
@@ -66,7 +75,10 @@ Use `building_spec.json` as the contract between CAD extraction, Blender generat
"detail_lines": [], "detail_lines": [],
"floor_lines": [], "floor_lines": [],
"grid": [] "grid": []
} },
"caps": [
{"z": 4.2, "polygons": [[[0, 0], [80, 0], [80, 42], [0, 42]]]}
]
} }
} }
} }
@@ -134,6 +146,9 @@ Common `source.config` keys used by `derive_showcase_spec.py` and `build_blender
- `column_support_distance`: XY tolerance for matching upper structural support. - `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_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. - `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.
- `cap_groups`: ordered `[pattern, group]` pairs used by derive and both exporters; `floor.caps` is the canonical generated-cap geometry.
Unknown config keys, duplicate floor keys, missing source files, incomplete `floor_order`, empty floors, and unsupported schema versions are hard validation failures. The exporters consume canonical `floor.caps`; they do not independently choose another floor grouping.
## Object Naming ## Object Naming

View File

@@ -0,0 +1,75 @@
# Campus and Multi-Building Workflow
## Contents
1. Branch selection
2. Scope contract
3. Placement evidence
4. Site outlines and missing buildings
5. Assembly gates
6. Site context
## Branch Selection
Treat folders such as `1#厂房 / 2#厂房 / 3#辅房 / 总图` as a campus, not floors of one building. Produce one frame-detection run, config, spec, and model per delivered building drawing set. Keep site plans in their own units.
Building plans are usually millimeters; total/site plans may be meters at surveying coordinates. Never combine both in one extraction config. Convert everything to site-local meters before GLB export; raw coordinates hundreds of kilometers from origin lose float32 precision.
## Scope Contract
Before modeling, write `scope_manifest.json` from the user request and source inventory. Do not derive requested scope from whichever config or GLB happened to succeed. Minimum shape:
```json
{
"scope_version": 1,
"mode": "campus",
"requested": ["1#", "2#", "3#"],
"buildings": [
{"id": "1#", "status": "PASS", "artifacts": ["../../outputs/1/model.glb"]},
{"id": "2#", "status": "BLOCKED", "reason": "unresolved XREF", "artifacts": []}
],
"site": {"status": "PASS", "artifacts": ["../../outputs/site_top.png", "../../outputs/campus.glb"]}
}
```
Every `requested` ID must have exactly one ledger entry and there may be no unrequested extras. `PASS` requires at least one verifiable model artifact: a GLB with mesh primitives, a Blender file with a valid header, or a schema-valid `building_spec.json`; an arbitrary non-empty text/JSON file does not satisfy scope. Campus site evidence must include a valid model or readable image. Relative paths resolve from the scope manifest's directory. `BLOCKED` requires a concrete reason and makes the overall campus result `BLOCKED`, not complete. Feed the ledger to `cad_showcase.py run --scope-manifest ...` or `verify_delivery.py --scope-manifest ...`.
## Placement Evidence
Prefer anchors in this order:
1. coordinate callouts;
2. wall lines;
3. envelope rectangles whose dimensions equal the model wall bbox;
4. registered site outlines.
Use wall evidence, not roof/eave envelopes. Derive rotation from a matched edge and resolve the 180-degree ambiguity with an asymmetric feature such as entrances, machine rooms, or basement ramps. Save the source and reasoning in `site_manifest.json`.
For irregular outlines use `register_site_outlines.py`. Constrain the angle window when the building is visibly axis-aligned. Treat residuals roughly as: 0.06m excellent, 0.5-1m plausible with balconies, above 2m likely wrong outline/floors.
## Site Outlines and Missing Buildings
If a building has no delivered drawings but has a site outline and storey label, use `massing_from_outline.py`. Label every such floor/model as total-plan outline massing. Never silently fabricate detailed walls/windows.
Use multiple floor footprints for registration when upper wings/overhangs explain the site outline better than one floor.
## Assembly Gates
Use `assemble_campus.py` with per-building `rotation_deg` where needed. Require:
- no unexplained negative wall-envelope gaps;
- 0.15-0.30m joints corroborated as expansion joints;
- several-meter separations checked against fire/site evidence;
- all buildings inside the red line;
- a top-view overlay or render showing each model inside its site outline;
- numeric envelope dimensions and neighbour gaps in the notes/evidence.
Do not classify a small gap from distance alone. Corroborate a 0.15-0.30m attached-building/expansion-joint interpretation with the neighbour roof shown on the subject building's roof plan and matching floor elevations. A negative gap is always a placement error. A multi-metre hypothesis that pushes either building through the red line is also wrong.
`--allow-overlap` is for a documented shared structure or verified interlocking geometry, not a shortcut around placement bugs.
## Site Context
Use `site_context_from_dump.py` to generate ground/red-line footprints, roads, parking, fences, trees, and low-confidence context massings from one selected site-plan copy. Supply the correct per-dump unit scale, region window, origin, and exclusion quad for real modeled buildings.
Keep site context in every presentation variant. Replace context massings with real models when drawing sets exist. A campus with only boundary sticks is incomplete presentation, but visual completeness never permits fake buildings.

View File

@@ -0,0 +1,86 @@
# Input Formats and Conversion Branches
## Contents
1. Supported inputs
2. DWG conversion selection
3. XREF and cached-block handling
4. 3DSOLID/MESH branch
5. PDF boundary
6. Dependencies and portability
## Supported Inputs
Use this skill directly for architectural DWG/DXF drawing folders and DXF files produced by the bundled WASM bridge. Preserve source folders and write conversions under `work/`.
For multi-discipline sets, model from 建筑 by default. Pull 结构 later for columns/beams only when the requested showcase needs them. Never feed architecture, structure, MEP, and site drawings into one extraction config.
## DWG Conversion Selection
Run `cad_showcase.py inspect` or `cad_dxf_report.py` with an explicit converter policy:
- `--converter auto`: use libredwg first and retry failed/zero-entity conversions with ODA.
- `--converter libredwg`: require libredwg and do not change converter silently.
- `--converter oda`: use ODA for every DWG. Choose this for known 3DSOLID/ACIS drawings and TArch files known to break libredwg.
Tool discovery is environment variable, PATH, then platform defaults:
- Blender: `BLENDER` -> PATH -> macOS/Windows install defaults.
- ODA: `ODA_CONVERTER` -> PATH -> macOS/Windows install defaults.
ODA requires existing absolute input/output directories. On macOS the command shape is `ODAFileConverter <abs_in_dir> <abs_out_dir> ACAD2004 DXF 0 1 "*.dwg"`; create both directories first. Bad arguments are often reported only through a GUI dialog, with empty stderr, and the process may return exit 0 while producing nothing. Treat “exit 0 + no DXF” as failure, check the screen for a blocked dialog, and keep the script's ASCII staging plus produced-file verification.
If native converters are unavailable, `--converter auto` uses the packaged WASM bridge after `npm install`.
For diagnosis or a manual one-file conversion, the equivalent commands are:
```bash
npm install --prefix work/vendor-js @mlightcad/libredwg-web
node scripts/dwg_dump_json.mjs input.dwg work/dump.json \
--module-dir work/vendor-js/node_modules
python3 scripts/dwgjson_to_dxf.py --json work/dump.json --out work/dxf_raw/input.dxf
```
The bridge carries LINE/POLYLINE/ARC/CIRCLE/ELLIPSE/SPLINE/TEXT/INSERT and block definitions. It drops HATCH/DIMENSION/ATTRIB; record that limitation and do not infer hatch-only columns or attribute-held axis labels from the result.
## XREF and Cached Blocks
- `cached_xref_content`: the file contains INSERT stubs plus cached block definitions. Expand blocks in detect/derive; do not ask for a re-export.
- `likely_xref_shell`: the referenced geometry is absent. Ask the user to bind/insert XREFs and re-export DXF.
- `has_xref_definitions`: verify that no essential external content is missing before modeling.
Never treat an unresolved XREF shell as a completed floor.
## 3DSOLID/MESH Branch
Force ODA before inspecting known solid models because libredwg can keep annotations while silently dropping ACIS data. Then run:
```bash
python3 scripts/extract_3d_solids.py \
--dxf work/dxf_sanitized/model.dxf \
--out-glb outputs/model/solids.glb \
--out-obj outputs/model/solids.obj \
--report outputs/model/solids_report.json
```
The extractor supports DXF MESH and flat polygonal ACIS faces. It counts cone/sphere/spline/torus/cylinder/swept/revolution surface records as unsupported. If curved records dominate, request OBJ/STL/STEP exported by AutoCAD, BricsCAD, or another full CAD kernel. Label partial output honestly.
## PDF Boundary
This skill does not natively reconstruct CAD geometry from PDF. For PDF-only input:
- ask for DWG/DXF when precision matters;
- or use a separate PDF/vector/OCR workflow with explicit scale calibration before invoking this skill;
- never treat raster tracing as CAD-equivalent geometry without dimensional evidence.
Do not advertise PDF support merely because a floor plan is visible in a PDF.
## Dependencies and Portability
Install deterministic dependency sets in the project environment:
```bash
python3 -m pip install -r requirements-core.txt
python3 -m pip install -r requirements-delivery.txt
```
Use `cad_showcase.py doctor` before a full run. On Windows set `PYTHONUTF8=1` and enable long paths for deep Chinese file names. Keep optional Blender/IfcOpenShell branches separate from the core Python path.

View File

@@ -0,0 +1,68 @@
# Multi-Frame Sheets and TArch/天正
## Contents
1. Detecting sheet walls
2. Alignment evidence
3. Titles and storeys
4. Clip risks
5. TArch mapping preset
## Detecting Sheet Walls
Chinese architectural DWGs often place all plans, elevations, sections, and details in one modelspace. Run `detect_sheet_frames.py`; never model the whole file as one floor.
The detector:
- scans plan titles in modelspace and cached blocks;
- rejects catalog/title-block copies and auxiliary titles;
- prefers title-block INSERT bboxes over pitch-only windows;
- expands enumerated/ranged titles such as `三、五层` and `十一至十四层`;
- emits a config skeleton plus a Markdown evidence report.
Pass every detector output config to audit with `--frames`. Account for every detected plan frame in extraction config or `discarded_frames` with a nonempty reason.
The detector emits sheet-level proposals. Two different plan titles can sit inside one title-block/frame INSERT and therefore receive the same broad clip (for example `一层平面图` plus `夹层平面图`, or `二层平面图` plus `十六层平面图`). Never duplicate that shared clip across floors. Split it at the wall-cluster gap between title positions, then recompute each floor offset. Use independent declared area/storey evidence to prove the split; a roughly 2× footprint is the characteristic failure signal.
## Alignment Evidence
Prefer structural-grid voting. TArch grids often live on `DOTE`, not `AXIS`. When through grids are absent, accept tick-grid voting. When no axes exist, use wall-profile correlation independently in X/Y. Use clip-corner anchoring only as a weak fallback.
Require overlay review for `WEAK grid match` and `wall-correlated` results. The audit cross-floor datum gate must reject a strong correlation peak at a nonzero shift; envelope centers alone cannot detect a floor placed into the wrong tower slot.
Never stack frames without offsets. That preserves sheet-layout pitch and creates the classic diagonal staircase building.
## Titles and Storeys
Read per-frame elevation ladders from section/elevation frames, but treat suggested storey tables as evidence rather than truth. Stair sections can contain half-storey rhythms; podium, machine-room, and roof heights differ.
Set explicit `z`, `height`, and `floor_order`. The schema rejects floor-order gaps and ghost keys.
## Clip Risks
Title-block or refined clips can still swallow adjacent rows, details, legends, or revision tables. Investigate when a footprint dimension is 2-4x its siblings, exceeds declared area, or contains distant sliver polygons. Tighten both X/Y clip bands or use evidence-backed isolated-cluster filtering; do not simply raise noise thresholds until the artifact disappears. Inspect the final browser screenshot too: repeated floating strips at every storey usually mean off-envelope plan symbols survived the clip.
## TArch Mapping Preset
Start consciously from this calibration, then inspect actual top layers:
- walls: `WALL`, `*WALL*`, `*墙*`
- columns: `COLUMN`, `*COL*`
- glazing: `CURTWALL`, `*GLAZ*`, `*幕墙*`, `*玻璃*`
- roof: `屋面`, `*屋顶*`
- detail: `STAIR`, `EVTR`, `平面`, `开口`
- grid: `DOTE`, `AXIS`
Doors/windows may both be INSERTs on `WINDOW`, with leaf geometry on layer `0`. Use block-name classification:
```json
{
"expand_blocks": ["$TCHSYS$*", "$DorLib2D$*"],
"block_name_categories": {
"glazing": ["$TCHSYS$WIN2D*"],
"doors": ["$DorLib2D$*"]
}
}
```
Exclude annotation/frame layers such as `*-IDEN`, `*图签*`, `PUB_*`, `DIM_*`, `*TEXT*`, `面积核算`, `格子线`, `SEC-*`, `立面`, `剖面`, `家具`. TArch column fills can be HATCH-only; pull structure from the structural drawing set instead of inventing columns.

View File

@@ -1,5 +1,15 @@
# Skill 优化建议(来自主辅楼建筑群 11 张图实战复盘) # Skill 优化建议(来自主辅楼建筑群 11 张图实战复盘)
## Contents
1. Lightweighting
2. Up-axis contract
3. Geometry completeness
4. Robustness
5. QA
6. Portability
7. Reusable artifacts
本文记录在一次完整实战(A202/A205/A208–A213 共 11 张 CAD 平面图 → 轻量化 Web 展示模型)中暴露的问题与已验证的修复,作为对 skill 脚本与模板的具体改进建议。修复均已在该项目落地验证。 本文记录在一次完整实战(A202/A205/A208–A213 共 11 张 CAD 平面图 → 轻量化 Web 展示模型)中暴露的问题与已验证的修复,作为对 skill 脚本与模板的具体改进建议。修复均已在该项目落地验证。
--- ---
@@ -68,7 +78,7 @@ CAD 把幕墙画成稀疏分格板(实测 8F:1.42m 板 / 每 4.5m 一块 /
### 3.3 柱头封顶(比 `shorten_unsupported_columns` 更好) ### 3.3 柱头封顶(比 `shorten_unsupported_columns` 更好)
现有的“无支撑柱缩短”会产生突兀的 1.2m 矮柱。更自然的做法是**生成盖板**: 现有的“无支撑柱缩短”会产生突兀的 1.2m 矮柱。更自然的做法是**生成盖板**:
- 地上退台层:`cap = 本层footprint(外扩~1.3m) − 上层footprint`,在 `z+h` 处挤薄板(退台屋面/雨棚)。外扩是为了盖住凹包络切掉的外圈柱廊柱。 - 地上退台层:`cap = 本层footprint(外扩cap_buffer) − 上层footprint`,在 `z+h` 处挤薄板(退台屋面/雨棚)。普通立面默认 `0.1m`;A208 的外圈柱廊有图纸佐证,才显式使用约 `1.3m`。
- **地下室顶层**:直接把整层 footprint 在 z=0 封成地面/顶板(停车区上方的地坪)。 - **地下室顶层**:直接把整层 footprint 在 z=0 封成地面/顶板(停车区上方的地坪)。
- 顶层(8F)/辅楼顶:用现有 `roof_specs` 屋顶盖。 - 顶层(8F)/辅楼顶:用现有 `roof_specs` 屋顶盖。

View File

@@ -1,5 +1,19 @@
# CAD to Web Building Showcase Pipeline # CAD to Web Building Showcase Pipeline
Prefer `scripts/cad_showcase.py` for source inspection and the resumable post-config pipeline. Use the individual commands below when diagnosing or iterating a specific stage.
## Contents
1. Inventory and conversion
2. CAD read report
3. Layer mapping
4. Floor detection and alignment
5. Spec extraction
6. Audit and overlays
7. Blender generation
8. Web showcase
9. Verification and IFC proof
## 1. Inventory and Conversion ## 1. Inventory and Conversion
Start by listing source files and preserving names. CAD drawing names often encode floor numbers, building zones, and drawing type. Start by listing source files and preserving names. CAD drawing names often encode floor numbers, building zones, and drawing type.
@@ -88,6 +102,7 @@ Example:
```json ```json
{ {
"config_version": 1,
"project_name": "Main Building", "project_name": "Main Building",
"scale": 0.001, "scale": 0.001,
"origin_strategy": "center", "origin_strategy": "center",
@@ -157,12 +172,27 @@ Example:
} }
``` ```
Validate before extraction:
```bash
python3 <skill>/scripts/showcase_schema.py config work/cad_showcase/config.json \
--dxf-dir work/cad_showcase/dxf_sanitized
```
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. 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 `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. 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.
Arm cross-evidence checks whenever the drawings contain the evidence:
- Copy per-floor areas from the 经济技术指标表/area labels into `declared_areas_m2`; use `declared_area_tolerance` only for a justified source convention. A model area off by roughly 100% usually means two plans or two wings were swallowed into one clip, not balcony noise.
- Copy the above-ground count from 总图 labels or elevation/section ladders into `expected_storeys_above_ground`. When one typical plan represents a range, instantiate those floors and record that they are source-supported repetitions.
- Pass every frame-detector config through `--frames`; list deliberately unused frames in `discarded_frames` with reasons.
These checks report `NOT_APPLICABLE` when no independent evidence exists. That is not proof of correctness; document what was searched before leaving them unarmed.
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. 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 ## 5. Spec Extraction
@@ -181,6 +211,7 @@ Review `building_spec.json` before rendering:
- Segment counts are not dominated by dimensions/hatches/annotations. - Segment counts are not dominated by dimensions/hatches/annotations.
- Footprint polygons exist when slabs/roofs are meant to follow CAD floor plates. - 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. - `default_disabled_categories` does not hide `slab` for presentation/digital-twin views.
- Generated cap edges do not protrude as slab fins. `cap_buffer` defaults to `0.1m` for ordinary facade-aligned floors. Set it explicitly around `1.3m` only for evidenced colonnade/overhang cases such as A208, then confirm front/side views.
## 6. Agent Audit and Overlay Review ## 6. Agent Audit and Overlay Review
@@ -216,6 +247,7 @@ Agent review rules:
- If frequent blocks appear in the audit, inspect block names and decide whether to recursively explode block geometry. - 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. - 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. - Continue only when missing geometry is acceptable for the requested output level.
- A floor can be internally self-consistent yet occupy the wrong repeated slot. If wall-profile correlation finds a strong non-zero shift, treat it as the 13号 F3 “错槽” pattern and correct the frame offset rather than trusting envelope centers.
## 7. Blender Generation ## 7. Blender Generation
@@ -236,12 +268,16 @@ Expected outputs:
- `<project>.png` - `<project>.png`
- `model_metadata.json` - `model_metadata.json`
If Blender CLI fails, verify the path. On this machine, the app path has been: If Blender CLI fails, verify the path. The macOS app-bundle path is:
```text ```text
/Applications/Blender.app/Contents/MacOS/Blender /Applications/Blender.app/Contents/MacOS/Blender
``` ```
On Linux/other platforms use `blender` from PATH; scripts discover the
executable via env `BLENDER` > PATH > the macOS default, and ODA File
Converter via env `ODA_CONVERTER` > PATH > its macOS default.
## 8. Web Showcase ## 8. Web Showcase
For a quick single-model preview, run: For a quick single-model preview, run:
@@ -293,10 +329,12 @@ Run the Blender-free QA pass first, then eyeball the previews before opening the
python3 <skill>/scripts/verify_showcase.py \ python3 <skill>/scripts/verify_showcase.py \
--spec work/cad_showcase/building_spec.json \ --spec work/cad_showcase/building_spec.json \
--glb outputs/<project>/variants/overview.glb outputs/<project>/variants/standard.glb outputs/<project>/variants/detail.glb \ --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 --out outputs/<project>/verify_previews.png --budget-mb 25 --strict
``` ```
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. It prints per-floor segment/cap/glazing-continuity counts and a GLB size-budget pass/fail, and writes front/side/plan previews from the spec. Use those previews for stacking and footprint gaps. Use an actual GLB render/browser screenshot to verify Y-up orientation, caps, materials, and slab fins; a spec preview cannot prove exported geometry orientation.
Finish with `verify_delivery.py` and retain its `evidence_manifest.json`; for formal Web delivery include the passing report from `web_smoke_test.mjs`.
Minimum verification: Minimum verification:

View File

@@ -0,0 +1,78 @@
# GLB and Web Delivery
## Contents
1. Variant contract
2. Served viewer
3. Offline viewer
4. Browser smoke test
5. Strict evidence manifest
## Variant Contract
Deliver three variants for Web/digital-twin presentation:
- overview: walls, glazing, roof, columns, beams, slabs;
- standard: overview plus railings and doors; use as default;
- detail: all extracted categories for review.
Generate them with `build_showcase_variants.py` or `cad_showcase.py run`. Validate `variants_manifest.json` and every variant spec. Keep `source_file==site` floors intact across variants.
Both backends retain a decoder-free `.raw.glb` for offline embedding. The Trimesh branch then runs `tools/compress.mjs` (weld, dedup, prune, Draco), while the Blender branch performs a second Blender Draco export for each delivered `.glb`. `verify_showcase.py --strict` must see `draco=True` and every delivered variant within the size budget.
Both GLB backends consume versioned `building_spec.json`. They must preserve `<floor>__<category>` names and glTF Y-up. `floor.caps` is canonical; exporters must not independently infer different cap groups.
## Served Viewer
Use `write_web_showcase.py`, then install local dependencies from the copied exact-version `package.json`. Do not use mainland-unreliable CDNs.
The official template includes on-demand rendering, ACES/RoomEnvironment lighting, physical glass, shadows, grouped floor/category toggles, overview-to-standard progressive load, in-page variant switching, explode/section controls, presets, tour, bookmarks, URL-hash state, screenshot, inspection, and downloads.
Require idle `window.__renders` growth of zero after damping stops.
## Offline Viewer
Use `write_offline_viewer.py` only for double-click/no-server delivery. It embeds vendored Three r147, pako, and a gzip-compressed **uncompressed** GLB. The Trimesh pipeline therefore uses retained `standard.raw.glb`; passing a Draco GLB is a hard error because this offline bundle intentionally has no Draco decoder.
`cad_showcase.py run --offline` automatically opens the result via `file://` in Chromium and writes `offline_browser_smoke_report.json` plus a screenshot. For a manual/custom delivery, run `offline_viewer_smoke.mjs` and pass its report to `verify_delivery.py --offline-browser-report`. Decoding the base64 payload is not proof that GLTFLoader can render it.
The offline viewer intentionally follows an older Three API. Keep its vendored library versions/checksums documented when updating them; do not copy modern template code blindly into r147.
## Browser Smoke Test
`cad_showcase.py run --web` performs this gate automatically. For a manual/custom delivery, serve the Web directory locally, then run:
```bash
node scripts/web_smoke_test.mjs \
--url http://127.0.0.1:8188 \
--out outputs/<project>/browser_smoke_report.json \
--screenshots-dir outputs/<project>/browser_smoke
```
Install Playwright/Chromium first when needed. The script checks real 1440×900/390×844 viewport dimensions, desktop/mobile control visibility, console/page/request failures, and idle render behavior. Feed the report to final verification with `--browser-report`. Supplying `--web-dir` makes the report mandatory: no report is `BLOCKED`, never PASS.
The verifier validates the report contract, not just its top-level `status`: all required named checks must exist and be PASS, viewport details must match exactly, and console/page/request arrays must be present and empty. A hand-written `{status: PASS}` report is invalid.
When an execution tool already has a `run_in_background` option, launch `python3 -m http.server ...` as the foreground command of that background process. Do not append shell `&`; the child server can die with the wrapper. Before presenting the viewer, probe the URL and keep that server process alive. Present the formal `web/index.html` URL when Web was requested; `viewer.html` is a separate offline fallback, not a substitute.
## Strict Evidence Manifest
Run `verify_showcase.py --strict` for spec previews and GLB budgets, then:
```bash
python3 scripts/verify_delivery.py \
--source-report outputs/<project>/cad_read_report.json \
--spec outputs/<project>/building_spec.json \
--audit outputs/<project>/extraction_audit.json --require-audit \
--scope-manifest work/<project>/scope_manifest.json --require-scope-manifest \
--variants-manifest outputs/<project>/delivery/variants_manifest.json \
--web-dir outputs/<project>/web \
--offline-viewer outputs/<project>/viewer.html \
--offline-browser-report outputs/<project>/offline_browser_smoke_report.json \
--render outputs/<project>/verify_previews.png outputs/<project>/iso.png \
--browser-report outputs/<project>/browser_smoke_report.json \
--require-browser-report \
--evidence-out outputs/<project>/evidence_manifest.json
```
The verifier checks schema versions, audit gates, scope artifacts, GLB headers/mesh structure/naming/budgets, render dimensions/foreground occupancy/noise, Web assets/placeholders/features/variants, offline payload, offline `file://` browser load, and served-Web browser report. Only overall `PASS` is complete. Applicable `WARN`/`SKIP` produce overall `BLOCKED` unless the exact check has an explicit `--waiver 'CHECK=REASON'`; `NOT_APPLICABLE` is recorded but non-blocking, and `FAIL` cannot be waived.

View File

@@ -1,7 +1,15 @@
# Web Presentation Upgrades (视觉/交互/性能改进清单) # Web Presentation Upgrades (视觉/交互/性能改进清单)
## Contents
1. Tier 1 defaults
2. Tier 2 geometry quality
3. Tier 3 interaction and scale-out
4. Current implementation status
5. Honesty rules
Prioritized playbook for pushing a working showcase model toward digital-twin Prioritized playbook for pushing a working showcase model toward digital-twin
presentation quality. Apply AFTER the geometry passes the One-Shot Definition presentation quality. Apply AFTER the geometry passes the Hard Definition
of Done — polish never excuses a wrong model. Each item names the code to of Done — polish never excuses a wrong model. Each item names the code to
touch. Ordered by value-per-effort. touch. Ordered by value-per-effort.
@@ -64,16 +72,13 @@ touch. Ordered by value-per-effort.
## Tier 3 — interaction & scale-out ## Tier 3 — interaction & scale-out
10. Click-to-inspect: raycast -> highlight mesh, show floor/category/source 10. Click-to-inspect — PARTIAL: raycast/highlight plus floor/category is done.
layer + drawing file (all present in `building_spec.json`; write it into Source layer + drawing file still require preserved GLB extras; merging
GLB `extras` during export so the viewer needs no extra fetch). currently collapses that provenance.
11. Camera bookmarks + auto-orbit tour; state (visible floors, section 11. Camera bookmarks + auto-orbit tour + URL-hash state — DONE.
height, camera) serialized into the URL hash for sharing. 12. Progressive loading — PARTIAL: overview -> standard global swap is done;
12. Progressive loading for campuses: load `overview` GLB first, swap in per-building idle/selection loading remains future work.
`standard`/`detail` per building on idle or on selection 13. Per-building grouped toggles with floor-key prefix fallback — DONE.
(`build_showcase_variants.py` already produces the variants + manifest).
13. Per-building toggles grouped in the panel (floors nested under building)
once floor keys carry building prefixes (1F1 / 2F1 / 3F1 ...).
14. Instancing & merge policy: merge static same-material meshes per building 14. Instancing & merge policy: merge static same-material meshes per building
(`BufferGeometryUtils.mergeGeometries`) — target < 150 draw calls for a (`BufferGeometryUtils.mergeGeometries`) — target < 150 draw calls for a
5-building campus; keep per-floor granularity only for toggleable nodes. 5-building campus; keep per-floor granularity only for toggleable nodes.
@@ -128,7 +133,8 @@ catcher (was at basement depth — shadows floated detached), and a data-URI
favicon (console stays clean). favicon (console stays clean).
PENDING (Tier 2/3): door/window openings, road/green surfaces (filled PENDING (Tier 2/3): door/window openings, road/green surfaces (filled
polygons), camera tours / URL state, progressive per-building loading. polygons), source-layer/drawing provenance through merged GLB extras, and
progressive per-building loading. Camera tours / URL state are complete.
## Honesty rules for presentation upgrades ## Honesty rules for presentation upgrades

7
requirements-core.txt Normal file
View File

@@ -0,0 +1,7 @@
ezdxf>=1.4,<2
jsonschema>=4.20,<5
mapbox-earcut>=1.0,<2
numpy>=1.26,<3
scipy>=1.13,<2
shapely>=2.0,<3
trimesh>=4.5,<5

View File

@@ -0,0 +1,4 @@
-r requirements-core.txt
matplotlib>=3.8,<4
pillow>=10,<12
pygltflib>=1.16,<2

3
requirements-qa.txt Normal file
View File

@@ -0,0 +1,3 @@
-r requirements-delivery.txt
pytest>=7.4,<9
ruff>=0.5,<1

View File

@@ -0,0 +1,125 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://cad-building-showcase.local/schemas/building-spec-v1.json",
"title": "CAD Building Showcase building_spec.json",
"type": "object",
"required": ["schema_version", "project", "source", "units", "categories", "floors"],
"properties": {
"schema_version": {"const": 1},
"project": {
"type": "object",
"required": ["name", "description"],
"properties": {"name": {"type": "string"}, "description": {"type": "string"}},
"additionalProperties": true
},
"source": {
"type": "object",
"required": ["config"],
"properties": {
"dxf_dir": {"type": "string"},
"report": {"type": "string"},
"config": {"type": "object"}
},
"additionalProperties": true
},
"units": {
"type": "object",
"required": ["source", "scale_to_meters", "origin_source"],
"properties": {
"source": {"type": "string"},
"scale_to_meters": {"type": "number", "exclusiveMinimum": 0},
"origin_source": {"$ref": "#/$defs/point"}
},
"additionalProperties": false
},
"categories": {
"type": "object",
"additionalProperties": {
"type": "object",
"required": ["label", "color"],
"properties": {"label": {"type": "string"}, "color": {"type": "string"}},
"additionalProperties": true
}
},
"floors": {
"type": "object",
"additionalProperties": {"$ref": "#/$defs/floor"}
},
"extraction_report": {"type": "array", "items": {"type": "object"}}
},
"additionalProperties": false,
"$defs": {
"point": {
"type": "array",
"prefixItems": [{"type": "number"}, {"type": "number"}],
"minItems": 2,
"maxItems": 2
},
"rect": {
"type": "array",
"prefixItems": [
{"type": "number"}, {"type": "number"}, {"type": "number"}, {"type": "number"}
],
"minItems": 4,
"maxItems": 4
},
"segment": {
"type": "object",
"required": ["start", "end", "width", "layer", "source_type"],
"properties": {
"start": {"$ref": "#/$defs/point"},
"end": {"$ref": "#/$defs/point"},
"width": {"type": "number", "minimum": 0},
"layer": {"type": "string"},
"source_type": {"type": "string"},
"_z0": {"type": "number"},
"_z1": {"type": "number"}
},
"additionalProperties": true
},
"polygon": {
"type": "array",
"minItems": 3,
"items": {"$ref": "#/$defs/point"}
},
"footprint": {
"type": "object",
"required": ["polygons"],
"properties": {
"method": {"type": "string"},
"source": {"type": "string"},
"source_categories": {"type": "array", "items": {"type": "string"}},
"area": {"type": "number", "minimum": 0},
"polygons": {"type": "array", "items": {"$ref": "#/$defs/polygon"}}
},
"additionalProperties": true
},
"cap": {
"type": "object",
"required": ["z", "polygons"],
"properties": {
"z": {"type": "number"},
"polygons": {"type": "array", "items": {"$ref": "#/$defs/polygon"}}
},
"additionalProperties": false
},
"floor": {
"type": "object",
"required": ["name", "z", "height", "bounds", "source_file", "segments"],
"properties": {
"name": {"type": "string"},
"z": {"type": "number"},
"height": {"type": "number", "exclusiveMinimum": 0},
"bounds": {"$ref": "#/$defs/rect"},
"source_file": {"type": "string"},
"segments": {
"type": "object",
"additionalProperties": {"type": "array", "items": {"$ref": "#/$defs/segment"}}
},
"footprint": {"$ref": "#/$defs/footprint"},
"caps": {"type": "array", "items": {"$ref": "#/$defs/cap"}}
},
"additionalProperties": true
}
}
}

View File

@@ -0,0 +1,192 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://cad-building-showcase.local/schemas/extraction-config-v1.json",
"title": "CAD Building Showcase extraction config",
"type": "object",
"properties": {
"config_version": {"const": 1},
"_comment": {"type": ["string", "array", "object"]},
"project_name": {"type": "string"},
"description": {"type": "string"},
"source_units": {"type": "string"},
"scale": {"type": "number", "exclusiveMinimum": 0},
"scale_to_meters": {"type": "number", "exclusiveMinimum": 0},
"origin": {"$ref": "#/$defs/point"},
"origin_strategy": {"enum": ["center", "min"]},
"floor_height": {"type": "number", "exclusiveMinimum": 0},
"floor_order": {"type": "array", "items": {"type": "string"}, "uniqueItems": true},
"drawings": {
"type": "array",
"items": {"$ref": "#/$defs/drawing"}
},
"discarded_frames": {
"type": "array",
"items": {
"type": "object",
"required": ["name", "reason"],
"properties": {
"name": {"type": "string", "minLength": 1},
"reason": {"type": "string", "minLength": 1}
},
"additionalProperties": false
}
},
"allowed_disconnected_footprints": {
"type": "array",
"items": {
"type": "object",
"required": ["floor_key", "reason"],
"properties": {
"floor_key": {"type": "string", "minLength": 1},
"reason": {"type": "string", "minLength": 1}
},
"additionalProperties": false
}
},
"layers": {"$ref": "#/$defs/patternMap"},
"categories": {
"type": "object",
"additionalProperties": {
"type": "object",
"properties": {
"label": {"type": "string", "minLength": 1},
"color": {"type": "string", "minLength": 1}
},
"additionalProperties": false
}
},
"exclude_layers": {"$ref": "#/$defs/stringList"},
"default_widths": {"$ref": "#/$defs/numberMap"},
"default_disabled_categories": {"$ref": "#/$defs/stringList"},
"min_source_length": {"type": "number", "minimum": 0},
"min_source_length_by_category": {"$ref": "#/$defs/numberMap"},
"min_length_meters": {"type": "number", "minimum": 0},
"min_length_meters_by_category": {"$ref": "#/$defs/numberMap"},
"curve_chord_source_length": {"type": "number", "exclusiveMinimum": 0},
"expand_blocks": {"oneOf": [{"type": "boolean"}, {"$ref": "#/$defs/stringList"}]},
"expand_block_names": {"$ref": "#/$defs/stringList"},
"expand_blocks_max_depth": {"type": "integer", "minimum": 0, "maximum": 16},
"expand_glazing_blocks": {"type": "boolean"},
"classify_block_contents": {"type": "boolean"},
"block_content_categories": {"$ref": "#/$defs/stringList"},
"block_name_categories": {"$ref": "#/$defs/patternMap"},
"block_insert_layer_fallback": {"type": "boolean"},
"generate_footprints": {"type": "boolean"},
"footprint_categories": {"$ref": "#/$defs/stringList"},
"footprint_concave_ratio": {"type": "number", "minimum": 0, "maximum": 1},
"footprint_simplify_tolerance": {"type": "number", "minimum": 0},
"footprint_min_area": {"type": "number", "minimum": 0},
"footprint_max_polygons": {"type": "integer", "minimum": 1},
"footprint_cluster_linkage": {"type": "number", "exclusiveMinimum": 0},
"use_footprint_slabs": {"type": "boolean"},
"use_footprint_roofs": {"type": "boolean"},
"slab_bounds_fallback": {"type": "boolean"},
"slab_thickness": {"type": "number", "exclusiveMinimum": 0},
"generate_caps": {"type": "boolean"},
"cap_buffer": {"type": "number", "minimum": 0},
"cap_groups": {
"type": "array",
"items": {
"type": "array",
"prefixItems": [{"type": "string"}, {"type": "string"}],
"minItems": 2,
"maxItems": 2
}
},
"roof_specs": {"type": "array", "items": {"$ref": "#/$defs/roofSpec"}},
"merge_glazing": {"type": "boolean"},
"glazing_gap_tol": {"type": "number", "minimum": 0},
"merge_wall_solids": {"type": "boolean"},
"glazing_mullions": {"type": "boolean"},
"glazing_panel_w": {"type": "number", "exclusiveMinimum": 0},
"drop_isolated_clusters": {"type": "boolean"},
"cluster_linkage": {"type": "number", "exclusiveMinimum": 0},
"isolation_distance": {"type": "number", "minimum": 0},
"isolation_min_length": {"type": "number", "minimum": 0},
"drop_unsupported_roof_lines": {"type": "boolean"},
"roof_support_distance": {"type": "number", "minimum": 0},
"shorten_unsupported_columns": {"type": "boolean"},
"shorten_unsupported_columns_floor_keys": {"$ref": "#/$defs/stringList"},
"unsupported_column_height": {"type": "number", "minimum": 0},
"column_support_distance": {"type": "number", "minimum": 0},
"column_support_z_tolerance": {"type": "number", "minimum": 0},
"column_roof_support_z_tolerance": {"type": "number", "minimum": 0},
"column_support_categories": {"$ref": "#/$defs/stringList"},
"column_support_requires_upper_plate": {"type": "boolean"},
"column_support_allow_plate_only": {"type": "boolean"},
"show_floor_labels": {"type": "boolean"},
"declared_areas_m2": {"$ref": "#/$defs/numberMap"},
"declared_area_tolerance": {"type": "number", "minimum": 0},
"expected_storeys_above_ground": {"type": "integer", "minimum": 0},
"showcase_variant": {"type": "string"},
"showcase_variant_categories": {"oneOf": [{"type": "string"}, {"$ref": "#/$defs/stringList"}]}
},
"additionalProperties": false,
"$defs": {
"point": {
"type": "array",
"prefixItems": [{"type": "number"}, {"type": "number"}],
"minItems": 2,
"maxItems": 2
},
"rect": {
"type": "array",
"prefixItems": [
{"type": "number"}, {"type": "number"}, {"type": "number"}, {"type": "number"}
],
"minItems": 4,
"maxItems": 4
},
"stringList": {"type": "array", "items": {"type": "string"}},
"numberMap": {"type": "object", "additionalProperties": {"type": "number"}},
"patternMap": {
"type": "object",
"additionalProperties": {"$ref": "#/$defs/stringList"}
},
"floor": {
"type": "object",
"required": ["key"],
"properties": {
"key": {"type": "string", "minLength": 1},
"name": {"type": "string"},
"z": {"type": ["number", "null"]},
"height": {"type": "number", "exclusiveMinimum": 0},
"clip": {"$ref": "#/$defs/rect"},
"offset": {"$ref": "#/$defs/point"},
"side": {"type": "string"},
"split_x": {"type": "number"},
"include_block_names": {"$ref": "#/$defs/stringList"},
"exclude_block_names": {"$ref": "#/$defs/stringList"}
},
"additionalProperties": false
},
"drawing": {
"type": "object",
"required": ["file"],
"properties": {
"file": {"type": "string", "minLength": 1},
"clip": {"$ref": "#/$defs/rect"},
"offset": {"$ref": "#/$defs/point"},
"split_x": {"type": "number"},
"include_block_names": {"$ref": "#/$defs/stringList"},
"exclude_block_names": {"$ref": "#/$defs/stringList"},
"floors": {"type": "array", "items": {"$ref": "#/$defs/floor"}}
},
"additionalProperties": false
},
"roofSpec": {
"type": "object",
"required": ["floor_key"],
"properties": {
"floor_key": {"type": "string"},
"bounds_from": {"$ref": "#/$defs/stringList"},
"footprint_from": {"$ref": "#/$defs/stringList"},
"bounds": {"$ref": "#/$defs/rect"},
"z": {"type": "number"},
"thickness": {"type": "number", "exclusiveMinimum": 0},
"margin": {"type": "number", "minimum": 0}
},
"additionalProperties": false
}
}
}

View File

@@ -0,0 +1,31 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://cad-building-showcase.local/schemas/variants-manifest-v1.json",
"title": "CAD Building Showcase variants manifest",
"type": "object",
"required": ["manifest_version", "name", "default_key", "variants"],
"properties": {
"manifest_version": {"const": 1},
"name": {"type": "string"},
"default_key": {"type": "string"},
"variants": {
"type": "array",
"minItems": 1,
"items": {
"type": "object",
"required": ["key", "label", "file", "source_glb", "metadata", "spec"],
"properties": {
"key": {"type": "string", "minLength": 1},
"label": {"type": "string"},
"description": {"type": "string"},
"file": {"type": "string"},
"source_glb": {"type": "string"},
"metadata": {"type": "string"},
"spec": {"type": "string"}
},
"additionalProperties": false
}
}
},
"additionalProperties": false
}

View File

@@ -40,6 +40,8 @@ import math
import sys import sys
from pathlib import Path from pathlib import Path
import showcase_schema
def parse_args() -> argparse.Namespace: def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__) p = argparse.ArgumentParser(description=__doc__)
@@ -48,8 +50,12 @@ def parse_args() -> argparse.Namespace:
p.add_argument("--out", required=True) p.add_argument("--out", required=True)
p.add_argument("--project-name", default=None) p.add_argument("--project-name", default=None)
p.add_argument("--description", default=None) p.add_argument("--description", default=None)
p.add_argument("--gap-warn", type=float, default=0.10, p.add_argument(
help="warn when two buildings' wall envelopes are closer than this (m); overlap always fails") "--gap-warn",
type=float,
default=0.10,
help="warn when two buildings' wall envelopes are closer than this (m); overlap always fails",
)
p.add_argument("--allow-overlap", action="store_true", help="downgrade overlap FAIL to warning") p.add_argument("--allow-overlap", action="store_true", help="downgrade overlap FAIL to warning")
return p.parse_args() return p.parse_args()
@@ -61,6 +67,7 @@ def make_xf(anchor, survey_m, origin_m, cos_t, sin_t):
def xf(p): def xf(p):
dx, dy = p[0] - ax, p[1] - ay dx, dy = p[0] - ax, p[1] - ay
return [round(dx * cos_t - dy * sin_t + tx, 6), round(dx * sin_t + dy * cos_t + ty, 6)] return [round(dx * cos_t - dy * sin_t + tx, 6), round(dx * sin_t + dy * cos_t + ty, 6)]
return xf return xf
@@ -142,9 +149,15 @@ def main() -> int:
envelopes: dict[str, tuple] = {} envelopes: dict[str, tuple] = {}
for name, b in manifest.get("buildings", {}).items(): for name, b in manifest.get("buildings", {}).items():
if not isinstance(b, dict) or "spec" not in b: if not isinstance(b, dict) or "spec" not in b:
print(f"skip {name}: no spec (status: {b.get('status', '?') if isinstance(b, dict) else b})", file=sys.stderr) print(
f"skip {name}: no spec (status: {b.get('status', '?') if isinstance(b, dict) else b})", file=sys.stderr
)
continue continue
spec = json.loads(Path(b["spec"]).read_text(encoding="utf-8")) spec = showcase_schema.normalize_spec(json.loads(Path(b["spec"]).read_text(encoding="utf-8")))
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
raise SystemExit(f"{name}: {exc}") from exc
if base_spec is None: if base_spec is None:
base_spec = spec base_spec = spec
anchor = b.get("model_anchor_m") or b.get("model_anchor_center_m") or b.get("model_anchor_SE_wall_corner_m") anchor = b.get("model_anchor_m") or b.get("model_anchor_center_m") or b.get("model_anchor_SE_wall_corner_m")
@@ -164,8 +177,11 @@ def main() -> int:
envelopes[name] = env envelopes[name] = env
# re-key this building's roof_specs into the campus config later # re-key this building's roof_specs into the campus config later
b["_roof_specs"] = [ b["_roof_specs"] = [
{**r, "floor_key": prefix + str(r.get("floor_key")), {
"footprint_from": [prefix + str(k) for k in r.get("footprint_from", [r.get("floor_key")])]} **r,
"floor_key": prefix + str(r.get("floor_key")),
"footprint_from": [prefix + str(k) for k in r.get("footprint_from", [r.get("floor_key")])],
}
for r in spec.get("source", {}).get("config", {}).get("roof_specs", []) for r in spec.get("source", {}).get("config", {}).get("roof_specs", [])
] ]
@@ -212,20 +228,31 @@ def main() -> int:
floors.update(placed) floors.update(placed)
campus = base_spec campus = base_spec
campus["schema_version"] = showcase_schema.SCHEMA_VERSION
campus["floors"] = floors campus["floors"] = floors
campus["project"] = { campus["project"] = {
"name": args.project_name or manifest.get("project_name", "厂区"), "name": args.project_name or manifest.get("project_name", "厂区"),
"description": args.description or manifest.get("description", "多栋建筑 + 场地(assemble_campus.py 合成)"), "description": args.description or manifest.get("description", "多栋建筑 + 场地(assemble_campus.py 合成)"),
} }
cfg = campus.setdefault("source", {}).setdefault("config", {}) cfg = campus.setdefault("source", {}).setdefault("config", {})
cfg["roof_specs"] = [r for b in manifest.get("buildings", {}).values() cfg["config_version"] = showcase_schema.CONFIG_VERSION
if isinstance(b, dict) for r in b.get("_roof_specs", [])] cfg["roof_specs"] = [
r for b in manifest.get("buildings", {}).values() if isinstance(b, dict) for r in b.get("_roof_specs", [])
]
cfg["floor_order"] = site_keys + [k for k in placed] cfg["floor_order"] = site_keys + [k for k in placed]
out = Path(args.out) out = Path(args.out)
try:
showcase_schema.validate_spec(campus)
except showcase_schema.ValidationFailure as exc:
raise SystemExit(str(exc)) from exc
out.parent.mkdir(parents=True, exist_ok=True) out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(campus, ensure_ascii=False, indent=1), encoding="utf-8") out.write_text(json.dumps(campus, ensure_ascii=False, indent=1), encoding="utf-8")
print(json.dumps({"out": str(out), "floors": len(floors), "buildings": len(envelopes), print(
"site_floors": len(site_keys)}, ensure_ascii=False)) json.dumps(
{"out": str(out), "floors": len(floors), "buildings": len(envelopes), "site_floors": len(site_keys)},
ensure_ascii=False,
)
)
return 0 return 0

View File

@@ -14,6 +14,7 @@ from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent)) sys.path.insert(0, str(Path(__file__).resolve().parent))
import derive_showcase_spec as derive # noqa: E402 import derive_showcase_spec as derive # noqa: E402
import showcase_schema # noqa: E402
HIGH_RISK_TYPES = { HIGH_RISK_TYPES = {
@@ -48,8 +49,8 @@ def parse_args() -> argparse.Namespace:
nargs="*", nargs="*",
default=None, default=None,
help="detect_sheet_frames out-config JSON(s): enables the frame-ledger gate " help="detect_sheet_frames out-config JSON(s): enables the frame-ledger gate "
"(every detected plan frame must be in the extraction config or listed " "(every detected plan frame must be in the extraction config or listed "
"in config discarded_frames with a reason)", "in config discarded_frames with a reason)",
) )
return parser.parse_args() return parser.parse_args()
@@ -87,10 +88,7 @@ def block_layer_unit_lengths(doc, name: str, max_chord: float, max_depth: int, d
for layer, length in block_layer_unit_lengths(doc, inner_name, max_chord, max_depth, depth + 1).items(): for layer, length in block_layer_unit_lengths(doc, inner_name, max_chord, max_depth, depth + 1).items():
totals[layer] += length * factor totals[layer] += length * factor
else: else:
length = sum( length = sum(segment_length_source(segment) for segment in derive.entity_segments(inner, max_chord))
segment_length_source(segment)
for segment in derive.entity_segments(inner, max_chord)
)
if length > 0: if length > 0:
totals[derive.entity_layer(inner)] += length totals[derive.entity_layer(inner)] += length
result = dict(totals) result = dict(totals)
@@ -141,7 +139,8 @@ def inspect_entity(
"supported_length": supported_length, "supported_length": supported_length,
"sample": sample, "sample": sample,
"high_risk": dxftype in HIGH_RISK_TYPES, "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 ""), "insert_name": block_name
or (str(entity.dxf.name) if dxftype == "INSERT" and entity.dxf.hasattr("name") else ""),
} }
@@ -168,15 +167,17 @@ def spec_counts(spec: dict[str, Any]) -> dict[str, dict[str, int]]:
categories = [key for key in spec.get("categories", {}) if key != "slab"] categories = [key for key in spec.get("categories", {}) if key != "slab"]
result = {} result = {}
for floor_key, floor in spec.get("floors", {}).items(): for floor_key, floor in spec.get("floors", {}).items():
result[floor_key] = { result[floor_key] = {category: len(floor.get("segments", {}).get(category, [])) for category in categories}
category: len(floor.get("segments", {}).get(category, []))
for category in categories
}
return result return result
def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_dir: Path, def audit(
frames: list[dict[str, Any]] | None = None) -> dict[str, Any]: dxf_dir: Path,
config: dict[str, Any],
spec: dict[str, Any],
vendor_dir: Path,
frames: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
ezdxf, recover = derive.import_ezdxf(vendor_dir) ezdxf, recover = derive.import_ezdxf(vendor_dir)
patterns = derive.layer_patterns(config) patterns = derive.layer_patterns(config)
max_chord = float(config.get("curve_chord_source_length", 750.0)) max_chord = float(config.get("curve_chord_source_length", 750.0))
@@ -232,9 +233,7 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
sx = abs(float(source_entity.dxf.get("xscale", 1.0) or 1.0)) sx = abs(float(source_entity.dxf.get("xscale", 1.0) or 1.0))
sy = abs(float(source_entity.dxf.get("yscale", 1.0) or 1.0)) sy = abs(float(source_entity.dxf.get("yscale", 1.0) or 1.0))
factor = (sx + sy) / 2.0 factor = (sx + sy) / 2.0
unit_lengths = block_layer_unit_lengths( unit_lengths = block_layer_unit_lengths(doc, insert_name, max_chord, max_block_depth)
doc, insert_name, max_chord, max_block_depth
)
for inner_layer, unit_length in unit_lengths.items(): for inner_layer, unit_length in unit_lengths.items():
inner_length = unit_length * factor inner_length = unit_length * factor
if inner_length <= 0: if inner_length <= 0:
@@ -343,9 +342,7 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
"coverage": { "coverage": {
"supported_length_meters": round(total_supported * scale, 3), "supported_length_meters": round(total_supported * scale, 3),
"classified_supported_length_meters": round(classified_supported * scale, 3), "classified_supported_length_meters": round(classified_supported * scale, 3),
"supported_length_coverage": round(classified_supported / total_supported, 4) "supported_length_coverage": round(classified_supported / total_supported, 4) if total_supported else None,
if total_supported
else None,
"block_locked_length_meters": round(block_locked_total * scale, 3), "block_locked_length_meters": round(block_locked_total * scale, 3),
"block_locked_classifiable_length_meters": round(block_locked_classifiable * scale, 3), "block_locked_classifiable_length_meters": round(block_locked_classifiable * scale, 3),
"block_captured_classified_length_meters": round(captured_from_blocks * scale, 3), "block_captured_classified_length_meters": round(captured_from_blocks * scale, 3),
@@ -390,9 +387,7 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
xs = [v for s in walls for v in (s["start"][0], s["end"][0])] xs = [v for s in walls for v in (s["start"][0], s["end"][0])]
ys = [v for s in walls for v in (s["start"][1], s["end"][1])] ys = [v for s in walls for v in (s["start"][1], s["end"][1])]
size = max(max(xs) - min(xs), max(ys) - min(ys)) size = max(max(xs) - min(xs), max(ys) - min(ys))
groups[derive._cap_floor_group(fk, config)].append( groups[derive._cap_floor_group(fk, config)].append((fk, (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2, size))
(fk, (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2, size)
)
worst: tuple[float, str] | None = None worst: tuple[float, str] | None = None
for grp, items in groups.items(): for grp, items in groups.items():
if len(items) < 2: if len(items) < 2:
@@ -402,7 +397,10 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
for j in range(i + 1, len(items)): for j in range(i + 1, len(items)):
dist = math.hypot(items[i][1] - items[j][1], items[i][2] - items[j][2]) dist = math.hypot(items[i][1] - items[j][1], items[i][2] - items[j][2])
if dist > limit and (worst is None or dist > worst[0]): if dist > limit and (worst is None or dist > worst[0]):
worst = (dist, f"{grp}: {items[i][0]} vs {items[j][0]} centers {round(dist, 1)} m apart (limit {round(limit, 1)})") worst = (
dist,
f"{grp}: {items[i][0]} vs {items[j][0]} centers {round(dist, 1)} m apart (limit {round(limit, 1)})",
)
if worst: if worst:
return { return {
"name": "floors_aligned", "name": "floors_aligned",
@@ -432,16 +430,15 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
for grp, keys in by_group.items(): for grp, keys in by_group.items():
if len(keys) < 2: if len(keys) < 2:
continue continue
ref_key = max(keys, key=lambda k: sum( ref_key = max(keys, key=lambda k: sum(math.hypot(s[2] - s[0], s[3] - s[1]) for s in wall_segs[k]))
math.hypot(s[2] - s[0], s[3] - s[1]) for s in wall_segs[k]))
ref_x = wall_profile(wall_segs[ref_key], 0, axis_tol=0.02, min_len=0.4) ref_x = wall_profile(wall_segs[ref_key], 0, axis_tol=0.02, min_len=0.4)
ref_y = wall_profile(wall_segs[ref_key], 1, axis_tol=0.02, min_len=0.4) ref_y = wall_profile(wall_segs[ref_key], 1, axis_tol=0.02, min_len=0.4)
def zero_cov(ref_prof, prof, tol: float = 0.25) -> float: def zero_cov(ref_prof, prof, tol: float = 0.25) -> float:
total = sum(w for _, w in prof) total = sum(w for _, w in prof)
if total <= 0: if total <= 0:
return 0.0 return 0.0
matched = sum(w for p, w in prof matched = sum(w for p, w in prof if any(abs(p - rp) <= tol for rp, _ in ref_prof))
if any(abs(p - rp) <= tol for rp, _ in ref_prof))
return matched / total return matched / total
for fk in keys: for fk in keys:
@@ -455,8 +452,7 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
# let any small profile "match" somewhere: 27号 1#A PH) # let any small profile "match" somewhere: 27号 1#A PH)
if shift is not None and zero_cov(ref_prof, prof) >= 0.7 * cov: if shift is not None and zero_cov(ref_prof, prof) >= 0.7 * cov:
continue continue
if (shift is not None and cov >= 0.45 and ratio >= 1.5 if shift is not None and cov >= 0.45 and ratio >= 1.5 and abs(shift) > 1.0:
and abs(shift) > 1.0):
return { return {
"name": "floors_aligned", "name": "floors_aligned",
"status": "FAIL", "status": "FAIL",
@@ -475,32 +471,44 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
} }
def evaluate_gates(report: dict[str, Any], spec: dict[str, Any], config: dict[str, Any], def evaluate_gates(
frames: list[dict[str, Any]] | None = None) -> list[dict[str, Any]]: report: dict[str, Any], spec: dict[str, Any], config: dict[str, Any], frames: list[dict[str, Any]] | None = None
) -> list[dict[str, Any]]:
"""Hard checks that must pass before 3D generation. """Hard checks that must pass before 3D generation.
A gate FAIL means the extraction is known-incomplete in a way that high A gate FAIL means the extraction is known-incomplete in a way that high
coverage numbers cannot excuse; fix the config (block expansion, layer coverage numbers cannot excuse; fix the config (block expansion, layer
mapping, source re-export) and re-run instead of accepting the model. mapping, source re-export) and re-run instead of accepting the model.
""" """
gates: list[dict[str, Any]] = [floors_alignment_gate(spec, config)] gates: list[dict[str, Any]] = [
{
"name": "all_config_drawings_present",
"status": "PASS",
"detail": "Every configured source drawing exists and passed config validation.",
},
{
"name": "unique_floor_keys",
"status": "PASS",
"detail": "Configured floor keys are unique.",
},
{
"name": "every_floor_nonempty",
"status": "PASS",
"detail": "Every floor contains segments, footprint polygons, or caps.",
},
floors_alignment_gate(spec, config),
]
spec_glazing_segments = sum( spec_glazing_segments = sum(counts.get("glazing", 0) for counts in report["spec_counts"].values())
counts.get("glazing", 0) for counts in report["spec_counts"].values()
)
locked_glazing_meters = sum( locked_glazing_meters = sum(
item["supported_length_meters"] item["supported_length_meters"] for item in report["block_locked_layers"] if item["category"] == "glazing"
for item in report["block_locked_layers"]
if item["category"] == "glazing"
) )
glazing_named_blocks = [ glazing_named_blocks = [
name name for name in report["top_insert_names"] if derive.match_patterns(name, derive.GLAZING_BLOCK_PATTERNS)
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) glazing_evidence = locked_glazing_meters >= GATE_GLAZING_MIN_METERS or bool(glazing_named_blocks)
if not glazing_evidence: if not glazing_evidence:
status, detail = "SKIP", "No curtain-wall/glazing evidence in blocks or block names." status, detail = "NOT_APPLICABLE", "No curtain-wall/glazing evidence in blocks or block names."
elif spec_glazing_segments > 0: elif spec_glazing_segments > 0:
status = "PASS" status = "PASS"
detail = ( detail = (
@@ -560,6 +568,8 @@ def evaluate_gates(report: dict[str, Any], spec: dict[str, Any], config: dict[st
} }
) )
gates.append(frame_ledger_gate(config, frames)) gates.append(frame_ledger_gate(config, frames))
gates.append(disconnected_footprints_gate(spec, config))
gates.append(vertical_storey_continuity_gate(spec))
gates.append(declared_area_gate(spec, config)) gates.append(declared_area_gate(spec, config))
gates.append(storey_count_gate(spec, config)) gates.append(storey_count_gate(spec, config))
return gates return gates
@@ -586,8 +596,11 @@ def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | Non
`"discarded_frames": [{"name": ..., "reason": ...}]`. `"discarded_frames": [{"name": ..., "reason": ...}]`.
""" """
if not frames: if not frames:
return {"name": "frame_ledger", "status": "SKIP", return {
"detail": "No --frames given; frame ledger not checked."} "name": "frame_ledger",
"status": "NOT_APPLICABLE",
"detail": "No --frames given; frame ledger is not armed for this project.",
}
discarded = {str(d.get("name", "")) for d in config.get("discarded_frames", [])} discarded = {str(d.get("name", "")) for d in config.get("discarded_frames", [])}
cfg_by_file: dict[str, list[dict[str, Any]]] = {} cfg_by_file: dict[str, list[dict[str, Any]]] = {}
for drawing in config.get("drawings", []) or []: for drawing in config.get("drawings", []) or []:
@@ -598,18 +611,30 @@ def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | Non
for drawing in fcfg.get("drawings", []) or []: for drawing in fcfg.get("drawings", []) or []:
file = str(drawing.get("file", "")) file = str(drawing.get("file", ""))
cfg_floors = cfg_by_file.get(file, []) cfg_floors = cfg_by_file.get(file, [])
used_cfg: set[int] = set()
for frame in drawing.get("floors", []) or []: for frame in drawing.get("floors", []) or []:
total += 1 total += 1
name = str(frame.get("name", "")) name = str(frame.get("name", ""))
key = str(frame.get("key", ""))
clip = frame.get("clip") clip = frame.get("clip")
if name in discarded: if name in discarded:
continue continue
if clip and any( matches = [
fl.get("clip") and _rect_overlap_ratio(clip, fl["clip"]) >= 0.3 index
for fl in cfg_floors for index, floor in enumerate(cfg_floors)
): if index not in used_cfg
and str(floor.get("key", "")) == key
and set(frame.get("include_block_names", []) or []).issubset(
set(floor.get("include_block_names", []) or [])
)
and clip
and floor.get("clip")
and _rect_overlap_ratio(clip, floor["clip"]) >= 0.3
]
if matches:
used_cfg.add(matches[0])
continue continue
unaccounted.append(f"{file}: {frame.get('key', '?')} {name}") unaccounted.append(f"{file}: {key or '?'} {name}")
if unaccounted: if unaccounted:
shown = "; ".join(unaccounted[:12]) + (" …" if len(unaccounted) > 12 else "") shown = "; ".join(unaccounted[:12]) + (" …" if len(unaccounted) > 12 else "")
return { return {
@@ -621,8 +646,98 @@ def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | Non
"floors/wings vanish — use them or discard them WITH a reason." "floors/wings vanish — use them or discard them WITH a reason."
), ),
} }
return {"name": "frame_ledger", "status": "PASS", return {
"detail": f"All {total} detected plan frames are used or explicitly discarded."} "name": "frame_ledger",
"status": "PASS",
"detail": f"All {total} detected plan frames are used or explicitly discarded.",
}
def _polygon_area(points: list[list[float]]) -> float:
if len(points) < 3:
return 0.0
return (
abs(
sum(
float(points[index][0]) * float(points[(index + 1) % len(points)][1])
- float(points[(index + 1) % len(points)][0]) * float(points[index][1])
for index in range(len(points))
)
)
/ 2.0
)
def _polygon_bounds(points: list[list[float]]) -> list[float]:
xs = [float(point[0]) for point in points]
ys = [float(point[1]) for point in points]
return [min(xs), min(ys), max(xs), max(ys)]
def _bounds_gap(a: list[float], b: list[float]) -> float:
dx = max(0.0, max(a[0] - b[2], b[0] - a[2]))
dy = max(0.0, max(a[1] - b[3], b[1] - a[3]))
return math.hypot(dx, dy)
def disconnected_footprints_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
"""Reject small, remote footprint islands unless they are explained.
A stray but substantial curtain-wall/component cluster can survive the
line-level isolated-cluster filter and become a tall floating fin. The
generated footprint exposes it deterministically. Legitimate detached
stairs/canopies must be acknowledged with a floor key and reason.
"""
allowed = {
str(item.get("floor_key", ""))
for item in config.get("allowed_disconnected_footprints", []) or []
if isinstance(item, dict) and str(item.get("reason", "")).strip()
}
problems: list[str] = []
checked = 0
for floor_key, floor in spec.get("floors", {}).items():
polygons = [
polygon
for polygon in (floor.get("footprint") or {}).get("polygons", []) or []
if isinstance(polygon, list) and len(polygon) >= 3
]
if len(polygons) < 2 or str(floor_key) in allowed:
continue
checked += 1
measured = sorted(
[(_polygon_area(polygon), _polygon_bounds(polygon)) for polygon in polygons],
key=lambda item: item[0],
reverse=True,
)
main_area, main_bounds = measured[0]
if main_area <= 0:
continue
for area, bounds in measured[1:]:
ratio = area / main_area
gap = _bounds_gap(main_bounds, bounds)
if ratio < 0.05 and gap > 2.0:
problems.append(
f"{floor_key}: {area:.1f} m² island is {ratio:.1%} of the main footprint and {gap:.1f} m away"
)
if problems:
return {
"name": "disconnected_footprints",
"status": "FAIL",
"detail": (
"Small remote footprint islands would render as floating/orphan building parts: "
+ "; ".join(problems)
+ ". Fix the clip/layer/block mapping, or document a legitimate detached element in "
"allowed_disconnected_footprints with floor_key and reason."
),
}
return {
"name": "disconnected_footprints",
"status": "PASS",
"detail": (
f"No unexplained small remote footprint islands across {len(spec.get('floors', {}))} floor(s)"
+ (f" ({checked} multi-component floor(s) checked)." if checked else ".")
),
}
def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]: def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
@@ -635,8 +750,11 @@ def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str
""" """
declared = config.get("declared_areas_m2") declared = config.get("declared_areas_m2")
if not declared: if not declared:
return {"name": "area_declared", "status": "SKIP", return {
"detail": "No declared_areas_m2 in config; area cross-check not requested."} "name": "area_declared",
"status": "NOT_APPLICABLE",
"detail": "No declared_areas_m2 in config; area cross-check is not armed.",
}
tol = float(config.get("declared_area_tolerance", 0.15)) tol = float(config.get("declared_area_tolerance", 0.15))
problems = [] problems = []
for key, want in declared.items(): for key, want in declared.items():
@@ -649,19 +767,80 @@ def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str
if got <= 0: if got <= 0:
problems.append(f"{key}: no footprint area in spec") problems.append(f"{key}: no footprint area in spec")
elif abs(got - want) / want > tol: elif abs(got - want) / want > tol:
problems.append(f"{key}: model {round(got, 1)} m² vs declared {round(want, 1)} m² " problems.append(
f"({round(100 * (got - want) / want):+d}%)") f"{key}: model {round(got, 1)} m² vs declared {round(want, 1)} m² "
f"({round(100 * (got - want) / want):+d}%)"
)
if problems: if problems:
return { return {
"name": "area_declared", "name": "area_declared",
"status": "FAIL", "status": "FAIL",
"detail": ("Footprint area disagrees with the declared evidence: " "detail": (
+ "; ".join(problems) "Footprint area disagrees with the declared evidence: "
+ f" (tolerance ±{round(tol * 100)}%). A missing wing / swallowed neighbour " + "; ".join(problems)
"sheet moves the area far more than balconies do."), + f" (tolerance ±{round(tol * 100)}%). A missing wing / swallowed neighbour "
"sheet moves the area far more than balconies do."
),
} }
return {"name": "area_declared", "status": "PASS", return {
"detail": f"{len(declared)} floor area(s) within ±{round(tol * 100)}% of declared values."} "name": "area_declared",
"status": "PASS",
"detail": f"{len(declared)} floor area(s) within ±{round(tol * 100)}% of declared values.",
}
def vertical_storey_continuity_gate(spec: dict[str, Any]) -> dict[str, Any]:
"""A final full-building model may not jump from F2 directly to F16.
Representative typical-floor drawings are source evidence, not permission
to leave the repeated storeys absent from the delivered building. The
repeated floors must be instantiated and labelled as derived repetitions.
"""
import re as _re
numbered: list[tuple[int, str, dict[str, Any]]] = []
for key, floor in spec.get("floors", {}).items():
match = _re.fullmatch(r"F(\d+)", str(key))
if match:
numbered.append((int(match.group(1)), str(key), floor))
numbered.sort()
if len(numbered) < 2:
return {
"name": "vertical_storey_continuity",
"status": "PASS",
"detail": f"{len(numbered)} numbered storey; no internal continuity gap to test.",
}
missing: list[str] = []
z_gaps: list[str] = []
for (left_no, left_key, left), (right_no, right_key, right) in zip(numbered, numbered[1:]):
if right_no != left_no + 1:
missing.append(f"{left_key}->{right_key}")
continue
left_z = float(left.get("z", 0.0))
right_z = float(right.get("z", 0.0))
nominal = max(float(left.get("height", 0.0)), float(right.get("height", 0.0)), 1.0)
if right_z - left_z > max(8.0, nominal * 2.0):
z_gaps.append(f"{left_key}->{right_key}={round(right_z - left_z, 2)}m")
if missing or z_gaps:
parts = []
if missing:
parts.append("missing numbered ranges " + ", ".join(missing))
if z_gaps:
parts.append("unexplained elevation gaps " + ", ".join(z_gaps))
return {
"name": "vertical_storey_continuity",
"status": "WARN",
"detail": (
"; ".join(parts)
+ ". Instantiate source-supported repeated typical floors; do not deliver separated floor islands."
),
}
return {
"name": "vertical_storey_continuity",
"status": "PASS",
"detail": f"Numbered storeys are contiguous from {numbered[0][1]} to {numbered[-1][1]}.",
}
def storey_count_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]: def storey_count_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
@@ -672,20 +851,29 @@ def storey_count_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str,
""" """
expected = config.get("expected_storeys_above_ground") expected = config.get("expected_storeys_above_ground")
if expected is None: if expected is None:
return {"name": "storey_count", "status": "SKIP", return {
"detail": "No expected_storeys_above_ground in config; count cross-check not requested."} "name": "storey_count",
"status": "NOT_APPLICABLE",
"detail": "No expected_storeys_above_ground in config; count cross-check is not armed.",
}
import re as _re import re as _re
actual = sum(1 for k in spec.get("floors", {}) if _re.fullmatch(r"F\d+", str(k))) actual = sum(1 for k in spec.get("floors", {}) if _re.fullmatch(r"F\d+", str(k)))
if actual != int(expected): if actual != int(expected):
return { return {
"name": "storey_count", "name": "storey_count",
"status": "FAIL", "status": "FAIL",
"detail": (f"Spec has {actual} above-ground storeys (F<n> keys) but the declared " "detail": (
f"count is {expected} (总图 label / elevation ladder). A silently dropped " f"Spec has {actual} above-ground storeys (F<n> keys) but the declared "
"floor_order entry or an unexpanded multi-floor frame is the usual cause."), f"count is {expected} (总图 label / elevation ladder). A silently dropped "
"floor_order entry or an unexpanded multi-floor frame is the usual cause."
),
} }
return {"name": "storey_count", "status": "PASS", return {
"detail": f"{actual} above-ground storeys match the declared count."} "name": "storey_count",
"status": "PASS",
"detail": f"{actual} above-ground storeys match the declared count.",
}
def agent_questions(unclassified_layers: list[dict], high_risk: Counter, insert_names: Counter) -> list[str]: def agent_questions(unclassified_layers: list[dict], high_risk: Counter, insert_names: Counter) -> list[str]:
@@ -727,11 +915,15 @@ def markdown(report: dict[str, Any]) -> str:
f"- Classified supported length: `{coverage['classified_supported_length_meters']}` m", f"- Classified supported length: `{coverage['classified_supported_length_meters']}` m",
f"- Supported-length coverage: `{coverage['supported_length_coverage']}` " f"- Supported-length coverage: `{coverage['supported_length_coverage']}` "
"(modelspace linework only — block-locked geometry is NOT in this denominator)", "(modelspace linework only — block-locked geometry is NOT in this denominator)",
*([ *(
f"- CLIP-SCOPED coverage: `{coverage['clipped_supported_length_coverage']}` over " [
f"`{coverage['clipped_supported_length_meters']}` m inside floor clips — " f"- CLIP-SCOPED coverage: `{coverage['clipped_supported_length_coverage']}` over "
"on multi-frame sheets judge extraction by THIS number, not the file-global one" f"`{coverage['clipped_supported_length_meters']}` m inside floor clips — "
] if coverage.get("clipped_supported_length_coverage") is not None else []), "on multi-frame sheets judge extraction by THIS number, not the file-global one"
]
if coverage.get("clipped_supported_length_coverage") is not None
else []
),
f"- Block-locked geometry: `{coverage['block_locked_length_meters']}` m total, " f"- Block-locked geometry: `{coverage['block_locked_length_meters']}` m total, "
f"`{coverage['block_locked_classifiable_length_meters']}` m classifiable, " f"`{coverage['block_locked_classifiable_length_meters']}` m classifiable, "
f"`{coverage['block_captured_classified_length_meters']}` m captured into the spec", f"`{coverage['block_captured_classified_length_meters']}` m captured into the spec",
@@ -765,14 +957,12 @@ def markdown(report: dict[str, Any]) -> str:
lines.extend(["", "## Classified Layers", ""]) lines.extend(["", "## Classified Layers", ""])
for layer in report["classified_layers"][:30]: for layer in report["classified_layers"][:30]:
lines.append( lines.append(
f"- `{layer['layer']}`: `{layer['categories']}`, " f"- `{layer['layer']}`: `{layer['categories']}`, classified length `{layer['classified_length_meters']}` m"
f"classified length `{layer['classified_length_meters']}` m"
) )
lines.extend(["", "## Files", ""]) lines.extend(["", "## Files", ""])
for item in report["files"]: for item in report["files"]:
lines.append( lines.append(
f"- `{item['file']}`: coverage `{item['supported_length_coverage']}`, " f"- `{item['file']}`: coverage `{item['supported_length_coverage']}`, high-risk `{item['high_risk_types']}`"
f"high-risk `{item['high_risk_types']}`"
) )
return "\n".join(lines) return "\n".join(lines)
@@ -781,6 +971,12 @@ def main() -> int:
args = parse_args() args = parse_args()
config = derive.read_json(Path(args.config)) config = derive.read_json(Path(args.config))
spec = json.loads(Path(args.spec).read_text(encoding="utf-8")) spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
try:
config = showcase_schema.validate_config(config, Path(args.dxf_dir))
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
frames = None frames = None
if args.frames: if args.frames:
frames = [json.loads(Path(p).read_text(encoding="utf-8")) for p in args.frames] frames = [json.loads(Path(p).read_text(encoding="utf-8")) for p in args.frames]

View File

@@ -9,6 +9,8 @@ import math
import sys import sys
from pathlib import Path from pathlib import Path
import showcase_schema
CATEGORY_DRAW_ORDER = ( CATEGORY_DRAW_ORDER = (
"grid", "grid",
@@ -43,7 +45,7 @@ def parse_args() -> argparse.Namespace:
if "--" in argv: if "--" in argv:
argv = argv[argv.index("--") + 1 :] argv = argv[argv.index("--") + 1 :]
else: else:
argv = [] argv = argv[1:]
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--spec", required=True, help="Path to building_spec.json") 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("--out-dir", required=True, help="Output folder")
@@ -210,7 +212,9 @@ def segment_prism(segment: dict, z0: float, z1: float):
] ]
def create_segment_mesh(bpy, name: str, segments: list[dict], z0: float, z1: float, material, floor_key: str, category: str): def create_segment_mesh(
bpy, name: str, segments: list[dict], z0: float, z1: float, material, floor_key: str, category: str
):
verts = [] verts = []
faces = [] faces = []
for segment in segments: for segment in segments:
@@ -288,7 +292,9 @@ def extend_shared_wall_ends(segments: list[dict], tol: float = 1e-3) -> list[dic
return out return out
def create_merged_wall_mesh(bpy, name: str, segments: list[dict], z0: float, z1: float, material, floor_key: str, category: str): def create_merged_wall_mesh(
bpy, name: str, segments: list[dict], z0: float, z1: float, material, floor_key: str, category: str
):
"""Union wall-segment rectangles into one continuous solid (config """Union wall-segment rectangles into one continuous solid (config
{"merge_wall_solids": true}) — removes corner seams and z-fighting at {"merge_wall_solids": true}) — removes corner seams and z-fighting at
junctions. Blender-native: delaunay_2d_cdt (output_type=1) triangulates the junctions. Blender-native: delaunay_2d_cdt (output_type=1) triangulates the
@@ -339,7 +345,9 @@ def create_merged_wall_mesh(bpy, name: str, segments: list[dict], z0: float, z1:
return obj return obj
def glazing_mullion_segments(bands: list[dict], z0: float, z1: float, panel_w: float = 1.5, profile: float = 0.06, depth: float = 0.10) -> list[dict]: def glazing_mullion_segments(
bands: list[dict], z0: float, z1: float, panel_w: float = 1.5, profile: float = 0.06, depth: float = 0.10
) -> list[dict]:
"""Curtain-wall panel grid over glazing bands (mirror of spec_to_glb). """Curtain-wall panel grid over glazing bands (mirror of spec_to_glb).
Emits pseudo wall segments (thin box profiles, rendered into the Emits pseudo wall segments (thin box profiles, rendered into the
@@ -361,18 +369,28 @@ def glazing_mullion_segments(bands: list[dict], z0: float, z1: float, panel_w: f
for i in range(panels + 1): for i in range(panels + 1):
t = i * step t = i * step
cx, cy = start[0] + ux * t, start[1] + uy * t cx, cy = start[0] + ux * t, start[1] + uy * t
out.append({ out.append(
"start": [cx - ux * profile / 2.0, cy - uy * profile / 2.0], {
"end": [cx + ux * profile / 2.0, cy + uy * profile / 2.0], "start": [cx - ux * profile / 2.0, cy - uy * profile / 2.0],
"width": depth, "layer": segment.get("layer", ""), "source_type": "mullion", "end": [cx + ux * profile / 2.0, cy + uy * profile / 2.0],
}) "width": depth,
"layer": segment.get("layer", ""),
"source_type": "mullion",
}
)
thickness = 0.08 thickness = 0.08
for tz0, tz1 in ((z0, z0 + thickness), (z1 - thickness, z1)): for tz0, tz1 in ((z0, z0 + thickness), (z1 - thickness, z1)):
out.append({ out.append(
"start": [float(start[0]), float(start[1])], "end": [float(end[0]), float(end[1])], {
"width": depth, "layer": segment.get("layer", ""), "source_type": "transom", "start": [float(start[0]), float(start[1])],
"_z0": tz0, "_z1": tz1, "end": [float(end[0]), float(end[1])],
}) "width": depth,
"layer": segment.get("layer", ""),
"source_type": "transom",
"_z0": tz0,
"_z1": tz1,
}
)
return out return out
@@ -536,12 +554,8 @@ def point_in_or_near_polygons(point: tuple[float, float], polygons: list[list[li
return False return False
def floor_group(floor_key: str) -> str: def floor_group(floor_key: str, config: dict | None = None) -> str:
if floor_key.startswith("AUX_"): return showcase_schema.floor_group(floor_key, config)
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: def point_segment_distance(point: tuple[float, float], start: tuple[float, float], end: tuple[float, float]) -> float:
@@ -564,10 +578,10 @@ def column_has_upper_support(point: tuple[float, float], floor_key: str, floor:
structural_categories = set(config.get("column_support_categories", ["walls", "glazing", "columns", "beams"])) structural_categories = set(config.get("column_support_categories", ["walls", "glazing", "columns", "beams"]))
require_upper_plate = bool(config.get("column_support_requires_upper_plate", True)) require_upper_plate = bool(config.get("column_support_requires_upper_plate", True))
allow_plate_only = bool(config.get("column_support_allow_plate_only", False)) allow_plate_only = bool(config.get("column_support_allow_plate_only", False))
group = floor_group(floor_key) group = floor_group(floor_key, config)
for other_key, other in spec.get("floors", {}).items(): for other_key, other in spec.get("floors", {}).items():
if floor_group(other_key) != group: if floor_group(other_key, config) != group:
continue continue
other_z = float(other.get("z", 0.0)) other_z = float(other.get("z", 0.0))
if not (floor_top - 0.05 <= other_z <= floor_top + z_tolerance): if not (floor_top - 0.05 <= other_z <= floor_top + z_tolerance):
@@ -587,7 +601,7 @@ def column_has_upper_support(point: tuple[float, float], floor_key: str, floor:
roof_z_tolerance = float(config.get("column_roof_support_z_tolerance", 0.65)) roof_z_tolerance = float(config.get("column_roof_support_z_tolerance", 0.65))
for roof in generated_roof_bounds(spec): for roof in generated_roof_bounds(spec):
if floor_group(str(roof["floor_key"])) != group: if floor_group(str(roof["floor_key"]), config) != group:
continue continue
if abs(float(roof["z"]) - floor_top) > roof_z_tolerance: if abs(float(roof["z"]) - floor_top) > roof_z_tolerance:
continue continue
@@ -679,10 +693,15 @@ def add_floor(bpy, floor_key: str, floor: dict, materials: dict[str, object], sp
if config.get("glazing_mullions", False) and floor_segments.get("glazing"): if config.get("glazing_mullions", False) and floor_segments.get("glazing"):
gz0, gz1 = z_window_for_category("glazing", z, height, floor_key, floor) gz0, gz1 = z_window_for_category("glazing", z, height, floor_key, floor)
mullion_segments = glazing_mullion_segments( mullion_segments = glazing_mullion_segments(
floor_segments["glazing"], gz0, gz1, panel_w=float(config.get("glazing_panel_w", 1.5)), floor_segments["glazing"],
gz0,
gz1,
panel_w=float(config.get("glazing_panel_w", 1.5)),
) )
known = [category for category in CATEGORY_DRAW_ORDER if floor_segments.get(category)] 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)) extra = sorted(
category for category in floor_segments if category not in CATEGORY_DRAW_ORDER and floor_segments.get(category)
)
if mullion_segments and "walls" not in known: if mullion_segments and "walls" not in known:
known.append("walls") # glazing-only floor still needs a walls object for the grid known.append("walls") # glazing-only floor still needs a walls object for the grid
for category in known + extra: for category in known + extra:
@@ -694,7 +713,14 @@ def add_floor(bpy, floor_key: str, floor: dict, materials: dict[str, object], sp
z0, z1 = z_window_for_category(category, z, height, floor_key, floor) z0, z1 = z_window_for_category(category, z, height, floor_key, floor)
if category == "walls" and config.get("merge_wall_solids", False) and segments: if category == "walls" and config.get("merge_wall_solids", False) and segments:
merged = create_merged_wall_mesh( merged = create_merged_wall_mesh(
bpy, f"{floor_key}__walls", segments, z0, z1, materials[category], floor_key, category, bpy,
f"{floor_key}__walls",
segments,
z0,
z1,
materials[category],
floor_key,
category,
) )
if merged is not None: if merged is not None:
segments = [] # walls handled; mullions (if any) get their own pass below segments = [] # walls handled; mullions (if any) get their own pass below
@@ -849,6 +875,8 @@ def setup_scene(bpy, spec: dict):
def metadata(spec: dict, bounds: list[float], max_z: float, name: str) -> dict: def metadata(spec: dict, bounds: list[float], max_z: float, name: str) -> dict:
config = spec.get("source", {}).get("config", {}) config = spec.get("source", {}).get("config", {})
return { return {
"metadata_version": 1,
"schema_version": spec.get("schema_version"),
"project": spec.get("project", {"name": name}), "project": spec.get("project", {"name": name}),
"floors": [ "floors": [
{"key": key, "name": floor.get("name", key), "z": floor.get("z", 0), "height": floor.get("height", 4.2)} {"key": key, "name": floor.get("name", key), "z": floor.get("z", 0), "height": floor.get("height", 4.2)}
@@ -868,20 +896,30 @@ def main() -> int:
try: try:
import bpy # type: ignore import bpy # type: ignore
except ImportError as exc: except ImportError as exc:
raise SystemExit("Run this script with Blender: blender -b --python build_blender_showcase.py -- --spec ...") from exc raise SystemExit(
"Run this script with Blender: blender -b --python build_blender_showcase.py -- --spec ..."
) from exc
spec_path = Path(args.spec) spec_path = Path(args.spec)
out_dir = Path(args.out_dir) out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True) out_dir.mkdir(parents=True, exist_ok=True)
spec = json.loads(spec_path.read_text(encoding="utf-8")) spec = showcase_schema.normalize_spec(json.loads(spec_path.read_text(encoding="utf-8")))
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
clear_scene(bpy) clear_scene(bpy)
bounds, max_z = setup_scene(bpy, spec) bounds, max_z = setup_scene(bpy, spec)
blend_path = out_dir / f"{args.name}.blend" blend_path = out_dir / f"{args.name}.blend"
glb_path = out_dir / f"{args.name}.glb" glb_path = out_dir / f"{args.name}.glb"
raw_glb_path = out_dir / f"{args.name}.raw.glb"
png_path = out_dir / f"{args.name}.png" png_path = out_dir / f"{args.name}.png"
metadata_path = out_dir / "model_metadata.json" metadata_path = out_dir / "model_metadata.json"
bpy.ops.wm.save_as_mainfile(filepath=str(blend_path)) bpy.ops.wm.save_as_mainfile(filepath=str(blend_path))
# Retain a decoder-free GLB for the self-contained r147 offline viewer.
bpy.ops.export_scene.gltf(filepath=str(raw_glb_path), export_format="GLB")
# Draco compression keeps the Web GLB lightweight (typically -85~92% size). # Draco compression keeps the Web GLB lightweight (typically -85~92% size).
# The Web template registers a DRACOLoader to decode it; keep both in sync. # The Web template registers a DRACOLoader to decode it; keep both in sync.
bpy.ops.export_scene.gltf( bpy.ops.export_scene.gltf(
@@ -896,14 +934,22 @@ def main() -> int:
if args.render: if args.render:
bpy.context.scene.render.filepath = str(png_path) bpy.context.scene.render.filepath = str(png_path)
bpy.ops.render.render(write_still=True) 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") metadata_path.write_text(
print(json.dumps({ json.dumps(metadata(spec, bounds, max_z, args.name), ensure_ascii=False, indent=2), encoding="utf-8"
"blend": str(blend_path), )
"glb": str(glb_path), print(
"png": str(png_path), json.dumps(
"metadata": str(metadata_path), {
"objects": len(bpy.data.objects), "blend": str(blend_path),
}, ensure_ascii=False)) "glb": str(glb_path),
"raw_glb": str(raw_glb_path),
"png": str(png_path),
"metadata": str(metadata_path),
"objects": len(bpy.data.objects),
},
ensure_ascii=False,
)
)
return 0 return 0

View File

@@ -9,6 +9,8 @@ import math
import sys import sys
from pathlib import Path from pathlib import Path
import showcase_schema
def parse_args() -> argparse.Namespace: def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
@@ -118,7 +120,15 @@ def segment_length(segment: dict) -> float:
return math.hypot(ex - sx, ey - sy) 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): 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") pset = ifcopenshell.api.pset.add_pset(model, product=element, name="CAD2BIM_Source")
props = { props = {
"FloorKey": floor_key, "FloorKey": floor_key,
@@ -172,7 +182,17 @@ def add_slab(np, ifcopenshell, model, body_context, storey, floor_key: str, floo
return slab return slab
def add_segment_element(ifcopenshell, model, body_context, storey, floor_key: str, floor: dict, category: str, segment: dict, source_index: int): 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) length = segment_length(segment)
if length < 0.05: if length < 0.05:
return None return None
@@ -276,9 +296,7 @@ def validate_ifc(ifcopenshell, path: Path, validate_geometry: bool) -> dict:
try: try:
geom.create_shape(settings, element) geom.create_shape(settings, element)
except Exception as exc: except Exception as exc:
geometry_failures.append( geometry_failures.append({"ifc_type": ifc_type, "name": element.Name, "error": str(exc)})
{"ifc_type": ifc_type, "name": element.Name, "error": str(exc)}
)
return { return {
"ifc_path": str(path), "ifc_path": str(path),
@@ -310,7 +328,15 @@ def make_notes(report: dict) -> str:
"## Entity Counts", "## Entity Counts",
"", "",
] ]
for key in ("IfcBuildingStorey", "IfcSlab", "IfcWall", "IfcColumn", "IfcBeam", "IfcPropertySet", "IfcExtrudedAreaSolid"): for key in (
"IfcBuildingStorey",
"IfcSlab",
"IfcWall",
"IfcColumn",
"IfcBeam",
"IfcPropertySet",
"IfcExtrudedAreaSolid",
):
lines.append(f"- `{key}`: {counts.get(key, 0)}") lines.append(f"- `{key}`: {counts.get(key, 0)}")
lines.extend(["", "## Storey Containment", ""]) lines.extend(["", "## Storey Containment", ""])
for storey in report["storeys"]: for storey in report["storeys"]:
@@ -337,7 +363,11 @@ def make_notes(report: dict) -> str:
def main() -> int: def main() -> int:
args = parse_args() args = parse_args()
np, ifcopenshell = import_deps(Path(args.vendor_dir)) np, ifcopenshell = import_deps(Path(args.vendor_dir))
spec = json.loads(Path(args.spec).read_text(encoding="utf-8")) spec = showcase_schema.normalize_spec(json.loads(Path(args.spec).read_text(encoding="utf-8")))
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
raise SystemExit(str(exc)) from exc
model, body_context, building = make_model(np, ifcopenshell, spec, args.project_name) model, body_context, building = make_model(np, ifcopenshell, spec, args.project_name)
created = {"IfcSlab": 0, "IfcWall": 0, "IfcColumn": 0, "IfcBeam": 0} created = {"IfcSlab": 0, "IfcWall": 0, "IfcColumn": 0, "IfcBeam": 0}
limits = { limits = {
@@ -384,7 +414,12 @@ def main() -> int:
out_notes.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_report.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
out_notes.write_text(make_notes(report), 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)) print(
json.dumps(
{"ifc": str(out_ifc), "report": str(out_report), "notes": str(out_notes), "created": created},
ensure_ascii=False,
)
)
return 0 return 0

View File

@@ -8,36 +8,53 @@ Blender to produce GLBs. Its manifest is consumed by write_web_showcase.py.
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import sys
import glob
import shutil
import os
import copy import copy
import json import json
import subprocess import subprocess
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
import showcase_schema
VARIANTS = [ VARIANTS = [
{ {
"key": "overview", "key": "overview",
"label": "总览轻量版", "label": "总览轻量版",
"description": "Walls, glazing, roofs, columns, beams, and generated slabs.", "description": "保留墙体、玻璃幕墙、屋顶、柱梁和楼板,适合快速总览。",
"categories": ["walls", "glazing", "roof", "columns", "beams"], "categories": ["walls", "glazing", "roof", "columns", "beams"],
}, },
{ {
"key": "standard", "key": "standard",
"label": "展示标准版", "label": "展示标准版",
"description": "Default Web presentation model with railings and doors.", "description": "标准网页展示模型,包含栏杆和门等主要细节。",
"categories": ["walls", "glazing", "roof", "columns", "beams", "railings", "doors"], "categories": ["walls", "glazing", "roof", "columns", "beams", "railings", "doors"],
}, },
{ {
"key": "detail", "key": "detail",
"label": "完整审图版", "label": "完整审图版",
"description": "Full extracted linework for audit and review.", "description": "保留完整提取线条,适合细节查看和复核。",
"categories": None, "categories": None,
}, },
] ]
def default_blender() -> str: def default_blender() -> str:
"""Blender executable: env BLENDER > PATH > platform install defaults."""
override = os.environ.get("BLENDER")
if override:
return override
found = shutil.which("blender")
if found:
return found
if sys.platform == "win32":
hits = sorted(glob.glob(r"C:/Program Files/Blender Foundation/Blender */blender.exe"))
if hits:
return hits[-1]
return "/Applications/Blender.app/Contents/MacOS/Blender" return "/Applications/Blender.app/Contents/MacOS/Blender"
@@ -145,10 +162,12 @@ def write_manifest(entries: list[dict[str, Any]], out_dir: Path, name: str) -> P
} }
) )
manifest = { manifest = {
"manifest_version": showcase_schema.MANIFEST_VERSION,
"name": name, "name": name,
"default_key": "standard", "default_key": "standard",
"variants": variants, "variants": variants,
} }
showcase_schema.validate_manifest(manifest)
manifest_path = out_dir / "variants_manifest.json" manifest_path = out_dir / "variants_manifest.json"
manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8") manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
return manifest_path return manifest_path
@@ -159,7 +178,12 @@ def main() -> int:
spec_path = Path(args.spec) spec_path = Path(args.spec)
out_dir = Path(args.out_dir) out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True) out_dir.mkdir(parents=True, exist_ok=True)
spec = json.loads(spec_path.read_text(encoding="utf-8")) spec = showcase_schema.normalize_spec(json.loads(spec_path.read_text(encoding="utf-8")))
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
entries = write_variant_specs(spec, out_dir) entries = write_variant_specs(spec, out_dir)
if args.build: if args.build:
run_blender(entries, out_dir, args.blender, Path(args.build_script)) run_blender(entries, out_dir, args.blender, Path(args.build_script))

View File

@@ -4,17 +4,21 @@
from __future__ import annotations from __future__ import annotations
import argparse import argparse
import glob
import fnmatch import fnmatch
import json import json
import os import os
import re
import shutil import shutil
import subprocess import subprocess
import sys import sys
from collections import Counter from collections import Counter, defaultdict
from pathlib import Path from pathlib import Path
CAD_SUFFIXES = {".dwg", ".dxf"} CAD_SUFFIXES = {".dwg", ".dxf"}
SCRIPT_DIR = Path(__file__).resolve().parent
ROOT = SCRIPT_DIR.parent
def parse_args() -> argparse.Namespace: def parse_args() -> argparse.Namespace:
@@ -23,7 +27,17 @@ def parse_args() -> argparse.Namespace:
parser.add_argument("--work", default="work/cad_showcase", help="Intermediate work folder") 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("--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("--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") parser.add_argument(
"--no-convert", action="store_true", help="Skip DWG conversion and only read existing DXF files"
)
parser.add_argument(
"--converter",
choices=("auto", "libredwg", "oda"),
default="auto",
help="auto=libredwg then ODA fallback; choose oda explicitly for 3DSOLID/ACIS drawings",
)
parser.add_argument("--allow-partial", action="store_true", help="Write a partial report instead of failing")
parser.add_argument("--partial-reason", help="Required justification when --allow-partial is used")
return parser.parse_args() return parser.parse_args()
@@ -35,8 +49,7 @@ def import_ezdxf(vendor_dir: Path):
from ezdxf import bbox, recover # type: ignore from ezdxf import bbox, recover # type: ignore
except ImportError as exc: except ImportError as exc:
raise SystemExit( raise SystemExit(
"Missing dependency: ezdxf. Install locally with:\n" f"Missing dependency: ezdxf. Install locally with:\n python3 -m pip install --target {vendor_dir} ezdxf"
f" python3 -m pip install --target {vendor_dir} ezdxf"
) from exc ) from exc
return ezdxf, bbox, recover return ezdxf, bbox, recover
@@ -53,10 +66,7 @@ def safe_name(path: Path, used: set[str]) -> str:
def find_cad_files(input_dir: Path) -> list[Path]: def find_cad_files(input_dir: Path) -> list[Path]:
return sorted( return sorted(path for path in input_dir.rglob("*") if path.is_file() and path.suffix.lower() in CAD_SUFFIXES)
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: def run_dwg2dxf(source: Path, dest: Path) -> dict:
@@ -85,11 +95,136 @@ def run_dwg2dxf(source: Path, dest: Path) -> dict:
} }
def libredwg_wasm_module_dir() -> Path | None:
"""Resolve the packaged WASM libredwg module without installing at runtime."""
override = os.environ.get("CAD_LIBREDWG_MODULE_DIR")
candidates = [Path(override)] if override else []
candidates.append(ROOT / "node_modules")
for candidate in candidates:
package = candidate / "@mlightcad" / "libredwg-web"
if (package / "dist" / "libredwg-web.js").exists() and (package / "wasm").is_dir():
return candidate
return None
def node_executable() -> str | None:
"""Resolve Node from env, PATH, or common platform install locations."""
override = os.environ.get("NODE")
if override:
return override if Path(override).exists() else None
found = shutil.which("node")
if found:
return found
candidates = []
if sys.platform == "darwin":
candidates.extend((Path("/opt/homebrew/bin/node"), Path("/usr/local/bin/node")))
elif sys.platform == "win32":
candidates.extend(
Path(path) / "nodejs" / "node.exe"
for path in (os.environ.get("ProgramFiles"), os.environ.get("ProgramFiles(x86)"))
if path
)
for candidate in candidates:
if candidate.exists():
return str(candidate)
return None
def run_wasm_libredwg(source: Path, dest: Path, work_dir: Path, vendor_dir: Path) -> dict:
"""Convert one DWG through the packaged libredwg WASM bridge."""
node = node_executable()
module_dir = libredwg_wasm_module_dir()
if not node:
return {
"source": str(source),
"dest": str(dest),
"status": "missing_node",
"message": "Install Node.js or set NODE to its executable path.",
}
if module_dir is None:
return {
"source": str(source),
"dest": str(dest),
"status": "missing_libredwg_wasm",
"message": (
"Install the toolchain Node dependencies with `npm install` or set "
"CAD_LIBREDWG_MODULE_DIR to a node_modules directory containing "
"@mlightcad/libredwg-web."
),
}
dump_dir = work_dir / "dwg_json"
dump_dir.mkdir(parents=True, exist_ok=True)
dump = dump_dir / f"{dest.stem}.json"
dest.parent.mkdir(parents=True, exist_ok=True)
try:
dump_proc = subprocess.run(
[
node,
str(SCRIPT_DIR / "dwg_dump_json.mjs"),
str(source),
str(dump),
"--module-dir",
str(module_dir),
],
capture_output=True,
timeout=600,
)
if dump_proc.returncode != 0 or not dump.exists():
return {
"source": str(source),
"dest": str(dest),
"status": "wasm_dump_failed",
"returncode": dump_proc.returncode,
"stdout": dump_proc.stdout.decode("utf-8", errors="replace")[-2000:],
"stderr": dump_proc.stderr.decode("utf-8", errors="replace")[-2000:],
}
rebuild_proc = subprocess.run(
[
sys.executable,
str(SCRIPT_DIR / "dwgjson_to_dxf.py"),
"--json",
str(dump),
"--out",
str(dest),
"--vendor-dir",
str(vendor_dir),
],
capture_output=True,
timeout=600,
)
except subprocess.TimeoutExpired as exc:
return {
"source": str(source),
"dest": str(dest),
"status": "wasm_timeout",
"message": str(exc),
}
return {
"source": str(source),
"dest": str(dest),
"status": "wasm_ok" if rebuild_proc.returncode == 0 and dest.exists() else "wasm_rebuild_failed",
"returncode": rebuild_proc.returncode,
"stdout": rebuild_proc.stdout.decode("utf-8", errors="replace")[-2000:],
"stderr": rebuild_proc.stderr.decode("utf-8", errors="replace")[-2000:],
}
def oda_converter() -> str | None: def oda_converter() -> str | None:
"""ODA File Converter path (env ODA_CONVERTER overrides the macOS default).""" """ODA File Converter: env ODA_CONVERTER > PATH > macOS app-bundle default."""
override = os.environ.get("ODA_CONVERTER") override = os.environ.get("ODA_CONVERTER")
if override: if override:
return override if Path(override).exists() else None return override if Path(override).exists() else None
found = shutil.which("ODAFileConverter")
if found:
return found
if sys.platform == "win32":
hits = sorted(
glob.glob(r"C:/Program Files/ODA/*/ODAFileConverter.exe")
+ glob.glob(r"C:/Program Files (x86)/ODA/*/ODAFileConverter.exe")
)
if hits:
return hits[-1]
default = Path("/Applications/ODAFileConverter.app/Contents/MacOS/ODAFileConverter") default = Path("/Applications/ODAFileConverter.app/Contents/MacOS/ODAFileConverter")
return str(default) if default.exists() else None return str(default) if default.exists() else None
@@ -118,7 +253,8 @@ def run_oda_batch(sources: list[Path], work_dir: Path) -> dict[Path, Path]:
try: try:
subprocess.run( subprocess.run(
[exe, str(in_dir.resolve()), str(out_dir.resolve()), "ACAD2018", "DXF", "0", "1", "*.dwg"], [exe, str(in_dir.resolve()), str(out_dir.resolve()), "ACAD2018", "DXF", "0", "1", "*.dwg"],
capture_output=True, timeout=1800, capture_output=True,
timeout=1800,
) )
except (subprocess.TimeoutExpired, OSError): except (subprocess.TimeoutExpired, OSError):
return {} return {}
@@ -229,15 +365,23 @@ def xref_definitions(doc) -> list[dict]:
return xrefs return xrefs
import re as _re PLAN_TITLE_RE = re.compile(r"平面图$")
PLAN_TITLE_EXCLUDE_RE = re.compile(r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
PLAN_TITLE_RE = _re.compile(r"平面图$") PLAN_TITLE_EXCLUDE_LAYERS = ("*图签*", "*PUB_TAB*", "*TTLB*", "*TK*", "*图框*", "*目录*")
PLAN_TITLE_EXCLUDE_RE = _re.compile(r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)") CAD_TEXT_FORMAT_RE = re.compile(r"\\[LlOoKk]|%%[UuOoKk]")
FLOOR_TOKEN_RE = re.compile(
r"机房小屋面|机房屋面|"
r"地下[一二三四五六七八九十\d]+层夹层|"
r"地下[一二三四五六七八九十\d]+层|"
r"[一二三四五六七八九十\d]+层夹层|"
r"[一二三四五六七八九十\d]+层|"
r"首层|底层|夹层|屋顶层|屋顶|屋面|机房层|电梯机房"
)
# AutoCAD MIF escapes (\M+5XXXX): CJK text in pre-Unicode DWGs survives # AutoCAD MIF escapes (\M+5XXXX): CJK text in pre-Unicode DWGs survives
# DXF conversion as literal escape sequences, so title matching must decode # DXF conversion as literal escape sequences, so title matching must decode
# them first. The digit selects the codepage; XXXX is the hex byte pair. # them first. The digit selects the codepage; XXXX is the hex byte pair.
MIF_RE = _re.compile(r"\\M\+([1-5])([0-9A-Fa-f]{4})") MIF_RE = re.compile(r"\\M\+([1-5])([0-9A-Fa-f]{4})")
MIF_CODEPAGES = {"1": "cp932", "2": "big5", "3": "cp949", "4": "johab", "5": "gbk"} MIF_CODEPAGES = {"1": "cp932", "2": "big5", "3": "cp949", "4": "johab", "5": "gbk"}
@@ -245,7 +389,7 @@ def decode_mif(text: str) -> str:
if "\\M+" not in text: if "\\M+" not in text:
return text return text
def repl(match: "_re.Match[str]") -> str: def repl(match: "re.Match[str]") -> str:
value = int(match.group(2), 16) value = int(match.group(2), 16)
raw = value.to_bytes(2, "big") if value > 0xFF else value.to_bytes(1, "big") raw = value.to_bytes(2, "big") if value > 0xFF else value.to_bytes(1, "big")
try: try:
@@ -256,27 +400,77 @@ def decode_mif(text: str) -> str:
return MIF_RE.sub(repl, text) return MIF_RE.sub(repl, text)
def normalize_cad_text(text: str) -> str:
text = CAD_TEXT_FORMAT_RE.sub("", decode_mif(text))
return text.replace("\\P", " ").strip()
def floor_identities(label: str) -> list[tuple[str, str]]:
"""``(building qualifier, floor)`` identities from labels/INSERT names."""
label = normalize_cad_text(label).replace("_", "、")
if label.endswith(("机房小屋面", "机房屋面")):
return [("", "PH")]
if not label.endswith("平面图") or len(label) > 50:
return []
head = label[:-3]
matches = list(FLOOR_TOKEN_RE.finditer(head))
tokens = [match.group(0) for match in matches]
qualifier = re.sub(r"[、,,\s]+$", "", head[: matches[0].start()]) if matches else ""
if len(qualifier) > 12:
qualifier = ""
out = []
for token in tokens:
if token in {"屋顶层", "屋顶", "屋面"}:
out.append("RF")
elif token in {"机房小屋面", "机房屋面", "机房层", "电梯机房"}:
out.append("PH")
elif token == "首层":
out.append("F1")
elif token == "底层":
out.append("B1")
elif token == "夹层":
out.append("F1M")
else:
out.append(token)
return [(qualifier, identity) for identity in out] or [("", label)]
def count_plan_titles(entities) -> int: def count_plan_titles(entities) -> int:
"""Distinct plan-frame titles in modelspace (multi-frame sheet detector).""" """Distinct plan floors from visible titles and Revit INSERT-name suffixes."""
seen = set() floor_qualifiers: dict[str, set[str]] = defaultdict(set)
for entity in entities: for entity in entities:
kind = entity.dxftype() kind = entity.dxftype()
if kind == "INSERT":
try:
suffix = str(entity.dxf.name).rsplit("-", 1)[-1]
except Exception:
continue
for qualifier, floor in floor_identities(suffix):
floor_qualifiers[floor].add(qualifier)
continue
if kind not in {"TEXT", "MTEXT"}: if kind not in {"TEXT", "MTEXT"}:
continue continue
try:
layer = str(entity.dxf.layer)
except Exception:
layer = ""
if any(fnmatch.fnmatch(layer.upper(), pattern.upper()) for pattern in PLAN_TITLE_EXCLUDE_LAYERS):
continue
try: try:
text = str(entity.dxf.text if kind == "TEXT" else entity.plain_text() or "").strip() text = str(entity.dxf.text if kind == "TEXT" else entity.plain_text() or "").strip()
except Exception: except Exception:
continue continue
text = decode_mif(text) text = normalize_cad_text(text)
if not text or len(text) > 40: if not text or len(text) > 40:
continue continue
if PLAN_TITLE_RE.search(text) and not PLAN_TITLE_EXCLUDE_RE.search(text): if PLAN_TITLE_RE.search(text) and not PLAN_TITLE_EXCLUDE_RE.search(text):
try: for qualifier, floor in floor_identities(text):
pos = entity.dxf.insert floor_qualifiers[floor].add(qualifier)
seen.add((text, round(float(pos.x) / 5000), round(float(pos.y) / 5000))) # Revit repeats the same floor suffix across hundreds of family INSERTs;
except Exception: # a sheet-title block may add ``主楼`` while families remain unqualified.
seen.add((text, 0, 0)) # Count that as one frame, but retain two genuinely different qualified
return len(seen) # buildings that both contain (say) an F1 plan in the same modelspace.
return sum(max(1, len({q for q in qualifiers if q})) for qualifiers in floor_qualifiers.values())
def insert_block_content(doc, entities) -> list[dict]: def insert_block_content(doc, entities) -> list[dict]:
@@ -319,11 +513,14 @@ def file_warnings(item: dict) -> list[str]:
# pipeline has never seen — the layer mapping must be built consciously, # pipeline has never seen — the layer mapping must be built consciously,
# or extraction silently captures nothing (patterns age, invariants don't). # or extraction silently captures nothing (patterns age, invariants don't).
wall_dialects = ("*WALL*", "*墙*", "*QIANG*") wall_dialects = ("*WALL*", "*墙*", "*QIANG*")
layer_names = [l["name"] for l in item.get("layers", []) if l.get("entity_count", 0) > 0] layer_names = [layer["name"] for layer in item.get("layers", []) if layer.get("entity_count", 0) > 0]
if (plan_titles >= 1 and (entities or 0) >= 400 if (
and layer_names plan_titles >= 1
and not any(fnmatch.fnmatch(n.upper(), p.upper()) for n in layer_names for p in wall_dialects)): and (entities or 0) >= 400
tops = ", ".join(l["name"] for l in item.get("top_layers", [])[:8]) and layer_names
and not any(fnmatch.fnmatch(n.upper(), p.upper()) for n in layer_names for p in wall_dialects)
):
tops = ", ".join(layer["name"] for layer in item.get("top_layers", [])[:8])
warnings.append( warnings.append(
f"unknown_layer_dialect: {plan_titles} plan title(s) but no wall-like layer " f"unknown_layer_dialect: {plan_titles} plan title(s) but no wall-like layer "
f"(*WALL*/*墙*) among {len(layer_names)} populated layers — an unfamiliar design-institute " f"(*WALL*/*墙*) among {len(layer_names)} populated layers — an unfamiliar design-institute "
@@ -369,11 +566,7 @@ def inspect_file(path: Path, ezdxf, bbox, recover) -> dict:
msp = doc.modelspace() msp = doc.modelspace()
entities = list(msp) entities = list(msp)
type_counts = Counter(entity.dxftype() for entity in entities) type_counts = Counter(entity.dxftype() for entity in entities)
layer_counts = Counter( layer_counts = Counter(str(entity.dxf.layer) for entity in entities if entity.dxf.hasattr("layer"))
str(entity.dxf.layer)
for entity in entities
if entity.dxf.hasattr("layer")
)
try: try:
geometry_bbox = bbox_tuple(bbox.extents(entities, fast=True)) geometry_bbox = bbox_tuple(bbox.extents(entities, fast=True))
except Exception as exc: # bbox can fail on unsupported proxy geometry. except Exception as exc: # bbox can fail on unsupported proxy geometry.
@@ -404,10 +597,7 @@ def inspect_file(path: Path, ezdxf, bbox, recover) -> dict:
"modelspace_entities": len(entities), "modelspace_entities": len(entities),
"plan_title_count": count_plan_titles(entities), "plan_title_count": count_plan_titles(entities),
"entity_types": dict(type_counts.most_common()), "entity_types": dict(type_counts.most_common()),
"top_layers": [ "top_layers": [{"name": name, "entity_count": count} for name, count in layer_counts.most_common(30)],
{"name": name, "entity_count": count}
for name, count in layer_counts.most_common(30)
],
"layer_count": len(layers), "layer_count": len(layers),
"layers": sorted(layers, key=lambda item: (-item["entity_count"], item["name"])), "layers": sorted(layers, key=lambda item: (-item["entity_count"], item["name"])),
"bbox": geometry_bbox, "bbox": geometry_bbox,
@@ -434,12 +624,14 @@ def markdown_report(results: list[dict], conversions: list[dict], input_dir: Pat
for file_name, warning in all_warnings: for file_name, warning in all_warnings:
lines.append(f"- `{file_name}`: {warning}") lines.append(f"- `{file_name}`: {warning}")
lines.append("") lines.append("")
lines.extend([ lines.extend(
"## Files", [
"", "## Files",
"| File | Status | Entities | Layers | Size X | Size Y | Unit Guess | Main Types |", "",
"| --- | --- | ---: | ---: | ---: | ---: | --- | --- |", "| File | Status | Entities | Layers | Size X | Size Y | Unit Guess | Main Types |",
]) "| --- | --- | ---: | ---: | ---: | ---: | --- | --- |",
]
)
for item in results: for item in results:
bbox_data = item.get("bbox") or {} bbox_data = item.get("bbox") or {}
size = bbox_data.get("size", ["", "", ""]) size = bbox_data.get("size", ["", "", ""])
@@ -505,21 +697,59 @@ def main() -> int:
if not input_dir.exists(): if not input_dir.exists():
raise SystemExit(f"Input folder not found: {input_dir}") raise SystemExit(f"Input folder not found: {input_dir}")
if args.allow_partial and not (args.partial_reason or "").strip():
raise SystemExit("--allow-partial requires --partial-reason")
cad_files = find_cad_files(input_dir)
generated_inputs = []
for source in cad_files:
resolved = source.resolve()
for generated_dir in (raw_dir.resolve(), clean_dir.resolve()):
if resolved == generated_dir or generated_dir in resolved.parents:
generated_inputs.append(source)
break
if generated_inputs:
examples = ", ".join(str(path) for path in generated_inputs[:3])
raise SystemExit(
"Input CAD files are inside generated work directories and would be deleted before inspection: "
f"{examples}. Use a separate --input directory such as out/dxf_src."
)
# These folders are generated intermediates. Recreate them so a source
# removed between runs cannot survive as a stale DXF and enter modeling.
shutil.rmtree(raw_dir, ignore_errors=True)
shutil.rmtree(clean_dir, ignore_errors=True)
raw_dir.mkdir(parents=True, exist_ok=True) raw_dir.mkdir(parents=True, exist_ok=True)
clean_dir.mkdir(parents=True, exist_ok=True) clean_dir.mkdir(parents=True, exist_ok=True)
used_names: set[str] = set() used_names: set[str] = set()
conversions: list[dict] = [] conversions: list[dict] = []
raw_dxfs: list[Path] = [] raw_dxfs: list[Path] = []
for source in find_cad_files(input_dir): assigned = [(source, raw_dir / safe_name(source, used_names)) for source in cad_files]
dest = raw_dir / safe_name(source, used_names) oda_outputs: dict[Path, Path] = {}
if args.converter == "oda" and not args.no_convert:
oda_outputs = run_oda_batch(
[source for source, _dest in assigned if source.suffix.lower() == ".dwg"],
work_dir,
)
for source, dest in assigned:
if source.suffix.lower() == ".dwg": if source.suffix.lower() == ".dwg":
if args.no_convert: if args.no_convert:
continue continue
conversion = run_dwg2dxf(source, dest) if args.converter == "oda":
produced = oda_outputs.get(source)
if produced:
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(produced, dest)
conversion = {"source": str(source), "dest": str(dest), "status": "oda_ok"}
else:
conversion = {"source": str(source), "dest": str(dest), "status": "oda_failed"}
else:
conversion = run_dwg2dxf(source, dest)
if conversion["status"] != "ok":
conversion = run_wasm_libredwg(source, dest, work_dir, vendor_dir)
conversions.append(conversion) conversions.append(conversion)
if conversion["status"] == "ok": if conversion["status"] in {"ok", "wasm_ok", "oda_ok"}:
raw_dxfs.append(dest) raw_dxfs.append(dest)
else: else:
if source.resolve() != dest.resolve(): if source.resolve() != dest.resolve():
@@ -551,10 +781,10 @@ def main() -> int:
if src and (item.get("status") == "failed" or item.get("modelspace_entities") == 0): if src and (item.get("status") == "failed" or item.get("modelspace_entities") == 0):
retry[item["file"]] = src retry[item["file"]] = src
for c in list(conversions): for c in list(conversions):
if c.get("status") in {"failed", "missing_dwg2dxf"} and str(c.get("source", "")).lower().endswith(".dwg"): if c.get("status") not in {"ok", "wasm_ok", "oda_ok"} and str(c.get("source", "")).lower().endswith(".dwg"):
name = Path(c["dest"]).name if c.get("dest") else Path(c["source"]).with_suffix(".dxf").name name = Path(c["dest"]).name if c.get("dest") else Path(c["source"]).with_suffix(".dxf").name
retry.setdefault(name, Path(c["source"])) retry.setdefault(name, Path(c["source"]))
if retry: if retry and args.converter == "auto":
produced = run_oda_batch(list(retry.values()), work_dir) produced = run_oda_batch(list(retry.values()), work_dir)
for name, src in retry.items(): for name, src in retry.items():
out = produced.get(src) out = produced.get(src)
@@ -581,17 +811,60 @@ def main() -> int:
json_path.parent.mkdir(parents=True, exist_ok=True) json_path.parent.mkdir(parents=True, exist_ok=True)
md_path.parent.mkdir(parents=True, exist_ok=True) md_path.parent.mkdir(parents=True, exist_ok=True)
payload = { payload = {
"input": str(input_dir), "report_version": 1,
"work": str(work_dir), "input": str(input_dir.resolve()),
"dxf_sanitized": str(clean_dir), "work": str(work_dir.resolve()),
"dxf_sanitized": str(clean_dir.resolve()),
"conversions": conversions, "conversions": conversions,
"files": results, "files": results,
} }
# --no-convert is a diagnostic convenience, not permission to silently
# exclude DWGs from the source ledger. A mixed folder therefore fails the
# hard gate until every DWG is converted or the run is explicitly partial.
dwg_sources = {str(path) for path in cad_files if path.suffix.lower() == ".dwg"}
successful_dwg_sources = {
str(item.get("source"))
for item in conversions
if item.get("status") in {"ok", "wasm_ok", "oda_ok", "oda_fallback_ok"}
}
unresolved_dwgs = sorted(dwg_sources - successful_dwg_sources)
failed_files = [item.get("file", "?") for item in results if item.get("status") != "ok"]
empty_files = [
item.get("file", "?") for item in results if item.get("status") == "ok" and item.get("modelspace_entities") == 0
]
issues = []
if not cad_files:
issues.append("input contains no DWG/DXF files")
if unresolved_dwgs:
issues.append("unconverted DWG files: " + ", ".join(Path(path).name for path in unresolved_dwgs))
if failed_files:
issues.append("unreadable DXF files: " + ", ".join(failed_files))
if empty_files:
issues.append("zero-entity DXF files: " + ", ".join(empty_files))
if not results:
issues.append("no readable DXF files were produced")
payload["gate"] = {
"name": "all_sources_converted_and_readable",
"status": "WARN" if issues and args.allow_partial else ("FAIL" if issues else "PASS"),
"detail": "; ".join(issues) if issues else f"{len(results)} DXF file(s) readable",
"partial_reason": args.partial_reason if issues and args.allow_partial else None,
}
payload = scrub_surrogates(payload) payload = scrub_surrogates(payload)
results = payload["files"] results = payload["files"]
json_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") 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") gate = payload["gate"]
gate_md = (
"## Source Gate\n\n"
f"- **{gate['status']}** `{gate['name']}`: {gate['detail']}"
+ (f"\n- Partial reason: {gate['partial_reason']}" if gate.get("partial_reason") else "")
+ "\n\n"
)
md_path.write_text(gate_md + 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)) print(json.dumps({"json": str(json_path), "markdown": str(md_path), "files": len(results)}, ensure_ascii=False))
if issues and not args.allow_partial:
for issue in issues:
print(f"GATE FAIL [all_sources_converted_and_readable]: {issue}", file=sys.stderr)
return 3
return 0 return 0

871
scripts/cad_showcase.py Normal file
View File

@@ -0,0 +1,871 @@
#!/usr/bin/env python3
"""Resumable command-line orchestrator for the deterministic showcase pipeline."""
from __future__ import annotations
import argparse
import hashlib
import importlib.metadata
import json
import os
import shutil
import socket
import subprocess
import sys
import time
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import showcase_schema
from build_showcase_variants import default_blender
from cad_dxf_report import oda_converter
from delivery_waivers import apply_waivers, parse_waivers
ROOT = Path(__file__).resolve().parent.parent
SCRIPTS = ROOT / "scripts"
def now() -> str:
return datetime.now(timezone.utc).isoformat()
DERIVE_FORBIDDEN_WARNINGS = (
"WARNING isolated_cluster",
"WARNING unsupported_roof",
"WARNING floor_order",
"WARNING topless_group",
)
def fingerprint(
config: Path,
source_report: Path,
dxf_dir: Path,
extra_inputs: tuple[Path, ...] = (),
) -> str:
"""Hash source data and pipeline code so resume cannot reuse stale work."""
digest = hashlib.sha256()
tracked = [config, source_report, *extra_inputs, *sorted(dxf_dir.glob("*.dxf"))]
tracked.extend(sorted(SCRIPTS.glob("*.py")))
tracked.extend(sorted(SCRIPTS.glob("*.mjs")))
tracked.extend(sorted((ROOT / "schemas").glob("*.json")))
tracked.extend(sorted(path for path in (ROOT / "tools").rglob("*") if path.is_file()))
tracked.extend(sorted(path for path in (ROOT / "assets" / "web-showcase-template").rglob("*") if path.is_file()))
tracked.extend(sorted(path for path in (ROOT / "assets" / "offline-viewer-libs").rglob("*") if path.is_file()))
tracked.extend(path for path in (ROOT / "package.json", ROOT / "package-lock.json") if path.exists())
for path in sorted(set(tracked), key=lambda item: str(item)):
if not path.is_file():
continue
digest.update(str(path.relative_to(ROOT) if path.is_relative_to(ROOT) else path).encode("utf-8"))
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def output_ready(path: Path) -> bool:
if not path.exists():
return False
if path.is_file():
return path.stat().st_size > 0
return any(path.iterdir())
class Pipeline:
def __init__(self, state_path: Path, input_fingerprint: str, resume: bool):
self.path = state_path
self.resume = resume
if state_path.exists():
try:
current = json.loads(state_path.read_text(encoding="utf-8"))
except Exception as exc:
raise SystemExit(f"Pipeline state is corrupt and was not overwritten: {state_path}: {exc}") from exc
else:
current = {}
if current.get("input_fingerprint") != input_fingerprint:
if resume and current:
print(
json.dumps(
{
"status": "INVALIDATED",
"reason": "input fingerprint changed",
"state": str(state_path),
},
ensure_ascii=False,
)
)
current = {}
self.state: dict[str, Any] = {
"state_version": 1,
"input_fingerprint": input_fingerprint,
"started_at": current.get("started_at", now()),
"updated_at": now(),
"steps": current.get("steps", {}),
}
self.save()
def save(self) -> None:
self.state["updated_at"] = now()
self.path.parent.mkdir(parents=True, exist_ok=True)
temporary = self.path.with_name(f".{self.path.name}.{os.getpid()}.tmp")
try:
with temporary.open("w", encoding="utf-8") as stream:
json.dump(self.state, stream, ensure_ascii=False, indent=2)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, self.path)
finally:
temporary.unlink(missing_ok=True)
def run(
self,
name: str,
command: list[str],
outputs: list[Path],
forbidden_stderr: tuple[str, ...] = (),
) -> None:
old = self.state["steps"].get(name, {})
if (
self.resume
and old.get("status") == "PASS"
and old.get("command") == command
and all(output_ready(path) for path in outputs)
):
print(json.dumps({"step": name, "status": "SKIP", "reason": "resume"}, ensure_ascii=False))
return
started = now()
proc = subprocess.run(command, cwd=ROOT, text=True, capture_output=True)
forbidden_hits = [pattern for pattern in forbidden_stderr if pattern in proc.stderr]
effective_code = proc.returncode or (3 if forbidden_hits else 0)
entry = {
"status": "PASS" if effective_code == 0 else "FAIL",
"started_at": started,
"finished_at": now(),
"returncode": effective_code,
"command": command,
"outputs": [str(path) for path in outputs],
"stdout_tail": proc.stdout[-4000:],
"stderr_tail": proc.stderr[-4000:],
"forbidden_stderr_hits": forbidden_hits,
}
self.state["steps"][name] = entry
self.save()
if proc.stdout:
print(proc.stdout, end="")
if proc.stderr:
print(proc.stderr, file=sys.stderr, end="")
if forbidden_hits:
print(f"GATE FAIL [{name}]: forbidden warning(s): {', '.join(forbidden_hits)}", file=sys.stderr)
if effective_code != 0:
raise SystemExit(effective_code)
missing = [str(path) for path in outputs if not output_ready(path)]
if missing:
entry["status"] = "FAIL"
entry["stderr_tail"] += "\nMissing expected outputs: " + ", ".join(missing)
self.save()
raise SystemExit(f"Step {name} did not create expected outputs: {missing}")
def python_script(name: str, *args: str) -> list[str]:
return [sys.executable, str(SCRIPTS / name), *args]
def resolve_executable(name: str) -> str:
"""Resolve command shims portably (notably npm.cmd on Windows)."""
candidates = [name]
if sys.platform == "win32":
candidates = [f"{name}.cmd", f"{name}.exe", name]
for candidate in candidates:
found = shutil.which(candidate)
if found:
return found
raise SystemExit(f"Required executable not found on PATH: {name}")
def npm_command(*args: str) -> list[str]:
return [resolve_executable("npm"), *args]
def node_script(path: Path, *args: str) -> list[str]:
return [resolve_executable("node"), str(path), *args]
def enforce_audit_gates(pipeline: Pipeline, audit_path: Path, waivers: dict[str, str]) -> bool:
report = json.loads(audit_path.read_text(encoding="utf-8"))
checks = [
{
"name": f"audit:{gate.get('name', 'unnamed')}",
"status": str(gate.get("status", "FAIL")),
"detail": str(gate.get("detail", "")),
}
for gate in report.get("gates", [])
]
audit_waivers = {name: reason for name, reason in waivers.items() if name.startswith("audit:")}
apply_waivers(checks, audit_waivers)
waived = [
{
"name": check["name"],
"original_status": check["original_status"],
"reason": check["waiver_reason"],
}
for check in checks
if "waiver_reason" in check
]
blocked = [check for check in checks if check.get("status") not in {"PASS", "NOT_APPLICABLE"}]
pipeline.state["audit_waivers"] = waived
if blocked:
pipeline.state["status"] = "BLOCKED"
pipeline.state["blocked_gates"] = blocked
pipeline.save()
for gate in blocked:
print(f"GATE BLOCKED [{gate['name']}]: {gate['detail']}", file=sys.stderr)
return False
pipeline.save()
return True
def preflight_waiver_targets(
args: argparse.Namespace,
source_report: dict[str, Any],
audit_report: dict[str, Any],
scope_manifest: Path,
waivers: dict[str, str],
) -> list[dict[str, Any]]:
"""Return invalid waiver checks before overlays/model builds begin.
The orchestrator knows every check that can legitimately be WARN/SKIP by
this point. Browser/offline checks generated by this pipeline are expected
to PASS; the only future SKIP is an explicitly required browser report when
no served Web delivery was requested.
"""
source_gate = source_report.get("gate") or {}
checks = [
{
"name": "cad_source_report",
"status": str(source_gate.get("status", "FAIL")),
"detail": str(source_gate.get("detail", "")),
}
]
checks.extend(
{
"name": f"audit:{gate.get('name', 'unnamed')}",
"status": str(gate.get("status", "FAIL")),
"detail": str(gate.get("detail", "")),
}
for gate in audit_report.get("gates", [])
)
try:
scope = json.loads(scope_manifest.read_text(encoding="utf-8"))
requested = scope.get("requested", [])
raw_buildings = scope.get("buildings", [])
if not isinstance(raw_buildings, list):
raw_buildings = []
buildings = {str(item.get("id", "")): item for item in raw_buildings if isinstance(item, dict)}
for building_id in requested if isinstance(requested, list) else []:
item = buildings.get(str(building_id), {})
status = str(item.get("status", "FAIL"))
reason = str(item.get("reason", "")).strip()
check_status = "WARN" if status == "BLOCKED" and reason else "PASS" if status == "PASS" else "FAIL"
checks.append(
{
"name": f"scope:building:{building_id}",
"status": check_status,
"detail": reason or f"Scope building status is {status}",
}
)
if scope.get("mode") == "campus":
site = scope.get("site", {}) if isinstance(scope.get("site"), dict) else {}
status = str(site.get("status", "FAIL"))
reason = str(site.get("reason", "")).strip()
check_status = "WARN" if status == "BLOCKED" and reason else "PASS" if status == "PASS" else "FAIL"
checks.append(
{
"name": "scope:site",
"status": check_status,
"detail": reason or f"Campus site status is {status}",
}
)
except (OSError, json.JSONDecodeError):
# Final scope verification reports the malformed manifest. With no
# trustworthy target inventory, every scope waiver remains unused.
pass
if args.web:
checks.append({"name": "browser:smoke", "status": "PASS", "detail": "Generated browser smoke required"})
elif args.require_browser_report:
checks.append(
{
"name": "browser:smoke",
"status": "SKIP",
"detail": "Required browser report without a served Web delivery",
}
)
if args.offline:
checks.append(
{
"name": "offline:browser-smoke",
"status": "PASS",
"detail": "Generated offline browser smoke required",
}
)
apply_waivers(checks, waivers)
return [
check for check in checks if check.get("status") == "FAIL" and str(check.get("name", "")).startswith("waiver:")
]
def multi_frame_source_files(source_report: dict[str, Any]) -> list[str]:
"""Return source drawings that require a detector-backed frame ledger.
A single modelspace can contain several floor plans. In that case a
hand-written extraction config is not enough evidence: every detected
frame must be mapped or explicitly discarded. Accept either the structured
count or the compatible warning emitted by older source inspectors.
"""
required: list[str] = []
for item in source_report.get("files", []) or []:
if not isinstance(item, dict) or item.get("status") != "ok":
continue
warnings = [str(value) for value in item.get("warnings", []) or []]
if int(item.get("plan_title_count", 0) or 0) >= 2 or any(
"multi_frame_sheet" in warning for warning in warnings
):
required.append(str(item.get("file", "?")))
return required
def available_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as stream:
stream.bind(("127.0.0.1", 0))
return int(stream.getsockname()[1])
def wait_for_http(url: str, timeout: float = 20.0) -> None:
deadline = time.monotonic() + timeout
last_error: Exception | None = None
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(url, timeout=1) as response:
if response.status < 500:
return
except Exception as exc: # pragma: no cover - timing depends on host
last_error = exc
time.sleep(0.2)
raise RuntimeError(f"Local Web server did not become ready: {last_error}")
def ensure_node_runtime(pipeline: Pipeline, *, browser: bool) -> None:
pipeline.run(
"node_dependencies",
npm_command("install", "--prefix", str(ROOT), "--ignore-scripts"),
[
ROOT / "node_modules" / "playwright" / "package.json",
ROOT / "node_modules" / "@gltf-transform" / "core" / "package.json",
],
)
if browser:
pipeline.run(
"browser_runtime",
node_script(ROOT / "node_modules" / "playwright" / "cli.js", "install", "chromium"),
[],
)
def run_browser_smoke(pipeline: Pipeline, web_dir: Path, report: Path, screenshots: Path, thumbnail: Path) -> None:
"""Serve the formal Web bundle and mechanically prove desktop/mobile loading."""
report.parent.mkdir(parents=True, exist_ok=True)
port = available_port()
url = f"http://127.0.0.1:{port}/"
server = subprocess.Popen(
[
sys.executable,
"-m",
"http.server",
str(port),
"--bind",
"127.0.0.1",
"--directory",
str(web_dir),
],
cwd=ROOT,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
try:
wait_for_http(url)
pipeline.run(
"browser_smoke",
node_script(
SCRIPTS / "web_smoke_test.mjs",
"--url",
url,
"--out",
str(report),
"--screenshots-dir",
str(screenshots),
"--thumbnail-out",
str(thumbnail),
),
[report, screenshots, thumbnail],
)
finally:
server.terminate()
try:
server.wait(timeout=5)
except subprocess.TimeoutExpired: # pragma: no cover - defensive cleanup
server.kill()
server.wait(timeout=5)
def run_offline_browser_smoke(pipeline: Pipeline, viewer: Path, report: Path, screenshot: Path) -> None:
"""Open the single-file viewer through file:// and prove that its model renders."""
pipeline.run(
"offline_browser_smoke",
node_script(
SCRIPTS / "offline_viewer_smoke.mjs",
"--viewer",
str(viewer),
"--out",
str(report),
"--screenshot",
str(screenshot),
),
[report, screenshot],
)
def doctor() -> int:
modules = ["ezdxf", "jsonschema", "numpy", "scipy", "shapely", "trimesh", "matplotlib", "PIL", "pygltflib"]
checks = []
failed = False
for module in modules:
try:
version = importlib.metadata.version("pillow" if module == "PIL" else module)
checks.append({"name": module, "status": "PASS", "version": version})
except Exception as exc:
checks.append({"name": module, "status": "FAIL", "detail": str(exc)})
failed = True
for executable in ("node", "npm", "dwg2dxf"):
try:
path = resolve_executable(executable)
except SystemExit:
path = None
checks.append({"name": executable, "status": "PASS" if path else "OPTIONAL", "path": path})
wasm_module = ROOT / "node_modules" / "@mlightcad" / "libredwg-web"
checks.append(
{
"name": "libredwg-wasm",
"status": "PASS" if (wasm_module / "dist" / "libredwg-web.js").exists() else "OPTIONAL",
"path": str(wasm_module) if wasm_module.exists() else None,
}
)
for executable, resolver in (("ODAFileConverter", oda_converter), ("blender", default_blender)):
candidate = resolver()
path = candidate if candidate and Path(candidate).exists() else None
checks.append({"name": executable, "status": "PASS" if path else "OPTIONAL", "path": path})
print(json.dumps({"status": "FAIL" if failed else "PASS", "checks": checks}, ensure_ascii=False, indent=2))
return 3 if failed else 0
def inspect_command(args: argparse.Namespace) -> int:
# Internal pipeline scripts run from ROOT so their bundled assets and
# schemas have a stable base. User-provided paths, however, are relative
# to the directory where cad_showcase.py was invoked (the Task workdir),
# not to this repository. Resolve them before crossing that cwd boundary.
input_dir = Path(args.input).resolve()
work_dir = Path(args.work).resolve()
output_dir = Path(args.output).resolve()
vendor_dir = Path(args.vendor_dir).resolve()
command = python_script(
"cad_dxf_report.py",
"--input",
str(input_dir),
"--work",
str(work_dir),
"--output",
str(output_dir),
"--vendor-dir",
str(vendor_dir),
"--converter",
args.converter,
)
if args.allow_partial:
command.extend(["--allow-partial", "--partial-reason", args.partial_reason])
if args.no_convert:
command.append("--no-convert")
return subprocess.run(command, cwd=ROOT).returncode
def build_with_trimesh(pipeline: Pipeline, bundle: Path) -> list[Path]:
glbs = []
for key in ("overview", "standard", "detail"):
spec = bundle / "variant_specs" / f"{key}.json"
out_dir = bundle / "variants" / key
raw_glb = out_dir / f"{key}.raw.glb"
glb = out_dir / f"{key}.glb"
metadata = out_dir / "model_metadata.json"
pipeline.run(
f"glb_{key}",
python_script(
"spec_to_glb.py",
"--spec",
str(spec),
"--out",
str(raw_glb),
"--metadata-out",
str(metadata),
"--name",
key,
),
[raw_glb, metadata],
forbidden_stderr=("WARNING mesh_from_polygons",),
)
pipeline.run(
f"compress_{key}",
node_script(ROOT / "tools" / "compress.mjs", str(raw_glb), str(glb)),
[glb],
)
glbs.append(glb)
return glbs
def run_pipeline(args: argparse.Namespace) -> int:
dxf_dir = Path(args.dxf_dir).resolve()
config = Path(args.config).resolve()
source_report = Path(args.source_report).resolve()
scope_manifest = Path(args.scope_manifest).resolve()
frame_inputs = tuple(Path(path).resolve() for path in args.frames)
vendor_dir = Path(args.vendor_dir).resolve()
try:
waivers = parse_waivers(args.waiver)
except ValueError as exc:
print(f"GATE FAIL [waiver]: {exc}", file=sys.stderr)
return 3
try:
report = json.loads(source_report.read_text(encoding="utf-8"))
showcase_schema.validate_source_report(report, dxf_dir)
except (OSError, json.JSONDecodeError, showcase_schema.ValidationFailure) as exc:
print(f"GATE FAIL [source_report]: {exc}", file=sys.stderr)
return 3
source_status = str((report.get("gate") or {}).get("status", "FAIL"))
source_checks = [
{
"name": "cad_source_report",
"status": source_status,
"detail": str((report.get("gate") or {}).get("detail", "")),
}
]
source_waivers = {name: reason for name, reason in waivers.items() if name == "cad_source_report"}
apply_waivers(source_checks, source_waivers)
if source_checks[0]["status"] == "WARN":
print(
"GATE BLOCKED [cad_source_report]: partial source report requires "
"--waiver 'cad_source_report=<user-approved reason>'",
file=sys.stderr,
)
return 3
invalid_source_waiver = next((check for check in source_checks if check["status"] == "FAIL"), None)
if invalid_source_waiver:
print(
f"GATE FAIL [{invalid_source_waiver['name']}]: {invalid_source_waiver['detail']}",
file=sys.stderr,
)
return 3
multi_frame_files = multi_frame_source_files(report)
if multi_frame_files and not frame_inputs:
print(
"GATE FAIL [frame_ledger_required]: multi-plan source drawing(s) require "
"detect_sheet_frames output via --frames: " + ", ".join(multi_frame_files),
file=sys.stderr,
)
return 3
out_dir = Path(args.out_dir).resolve()
out_dir.mkdir(parents=True, exist_ok=True)
pipeline = Pipeline(
out_dir / "pipeline_state.json",
fingerprint(config, source_report, dxf_dir, (scope_manifest, *frame_inputs)),
args.resume,
)
if source_status == "WARN":
pipeline.state["source_waiver"] = {
"check": "cad_source_report",
"reason": waivers["cad_source_report"],
}
pipeline.save()
spec = out_dir / "building_spec.json"
audit = out_dir / "extraction_audit.json"
audit_md = out_dir / "extraction_audit.md"
overlays = out_dir / "overlays"
pipeline.run(
"derive",
python_script(
"derive_showcase_spec.py",
"--dxf-dir",
str(dxf_dir),
"--config",
str(config),
"--out",
str(spec),
"--vendor-dir",
str(vendor_dir),
),
[spec],
forbidden_stderr=DERIVE_FORBIDDEN_WARNINGS,
)
audit_cmd = python_script(
"audit_showcase_extraction.py",
"--dxf-dir",
str(dxf_dir),
"--config",
str(config),
"--spec",
str(spec),
"--out",
str(audit),
"--vendor-dir",
str(vendor_dir),
)
if frame_inputs:
audit_cmd.extend(["--frames", *[str(path) for path in frame_inputs]])
pipeline.run("audit", audit_cmd, [audit, audit_md])
audit_report = json.loads(audit.read_text(encoding="utf-8"))
invalid_waivers = preflight_waiver_targets(args, report, audit_report, scope_manifest, waivers)
if invalid_waivers:
pipeline.state["status"] = "BLOCKED"
pipeline.state["invalid_waivers"] = invalid_waivers
pipeline.save()
for check in invalid_waivers:
print(f"GATE FAIL [{check['name']}]: {check['detail']}", file=sys.stderr)
return 3
if not enforce_audit_gates(pipeline, audit, waivers):
return 3
pipeline.run(
"overlays",
python_script(
"draw_coverage_overlay.py",
"--dxf-dir",
str(dxf_dir),
"--config",
str(config),
"--spec",
str(spec),
"--out-dir",
str(overlays),
"--vendor-dir",
str(vendor_dir),
),
[overlays],
)
bundle = out_dir / "delivery"
manifest = bundle / "variants_manifest.json"
variant_cmd = python_script(
"build_showcase_variants.py",
"--spec",
str(spec),
"--out-dir",
str(bundle),
"--name",
args.name,
)
if args.backend == "blender":
variant_cmd.append("--build")
if args.blender:
variant_cmd.extend(["--blender", args.blender])
pipeline.run("variants", variant_cmd, [manifest, bundle / "variant_specs" / "standard.json"])
if args.backend == "trimesh" or args.web or args.offline:
ensure_node_runtime(pipeline, browser=args.web or args.offline)
if args.backend == "trimesh":
glbs = build_with_trimesh(pipeline, bundle)
else:
glbs = [bundle / "variants" / key / f"{key}.glb" for key in ("overview", "standard", "detail")]
web_dir = out_dir / "web"
if args.web:
pipeline.run(
"web",
python_script(
"write_web_showcase.py",
"--variants-manifest",
str(manifest),
"--out-dir",
str(web_dir),
"--title",
args.name,
),
[web_dir / "index.html", web_dir / "model.glb", web_dir / "model_metadata.json"],
)
if not args.skip_web_deps:
pipeline.run(
"web_dependencies",
npm_command("install", "--prefix", str(web_dir), "--ignore-scripts"),
[web_dir / "node_modules" / "three" / "build" / "three.module.js"],
)
browser_report = (
Path(args.browser_report).resolve() if args.browser_report else out_dir / "browser_smoke_report.json"
)
run_browser_smoke(
pipeline,
web_dir,
browser_report,
out_dir / "browser_smoke",
out_dir / "thumbnail.png",
)
standard = bundle / "variants" / "standard" / "standard.glb"
offline = out_dir / "viewer.html"
offline_browser_report = out_dir / "offline_browser_smoke_report.json"
if args.offline:
offline_source = standard.with_name("standard.raw.glb")
if not offline_source.exists():
offline_source = standard
pipeline.run(
"offline",
python_script(
"write_offline_viewer.py",
"--spec",
str(spec),
"--glb",
str(offline_source),
"--out",
str(offline),
"--title",
args.name,
),
[offline],
)
run_offline_browser_smoke(
pipeline,
offline,
offline_browser_report,
out_dir / "offline_browser_smoke.png",
)
preview = out_dir / "verify_previews.png"
pipeline.run(
"preview",
python_script(
"verify_showcase.py",
"--spec",
str(spec),
"--glb",
*[str(path) for path in glbs],
"--out",
str(preview),
"--budget-mb",
str(args.budget_mb),
"--strict",
),
[preview],
)
evidence = out_dir / "evidence_manifest.json"
verify_cmd = python_script(
"verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--variants-manifest",
str(manifest),
"--render",
str(preview),
"--audit",
str(audit),
"--require-audit",
"--budget-mb",
str(args.budget_mb),
"--evidence-out",
str(evidence),
"--scope-manifest",
str(scope_manifest),
"--require-scope-manifest",
)
if args.web:
verify_cmd.extend(
["--web-dir", str(web_dir), "--browser-report", str(browser_report), "--require-browser-report"]
)
if args.offline:
verify_cmd.extend(
[
"--offline-viewer",
str(offline),
"--offline-browser-report",
str(offline_browser_report),
]
)
if args.require_browser_report and not args.web:
verify_cmd.append("--require-browser-report")
for value in args.waiver:
verify_cmd.extend(["--waiver", value])
pipeline.run("delivery_verification", verify_cmd, [evidence])
verification = json.loads(evidence.read_text(encoding="utf-8"))
if verification.get("status") != "PASS":
pipeline.state["status"] = "BLOCKED"
pipeline.save()
print(f"GATE BLOCKED [delivery_verification]: {verification.get('status')}", file=sys.stderr)
return 3
pipeline.state["status"] = "PASS"
pipeline.state["finished_at"] = now()
pipeline.save()
print(json.dumps({"status": "PASS", "out_dir": str(out_dir), "evidence": str(evidence)}, ensure_ascii=False))
return 0
def parser() -> argparse.ArgumentParser:
root = argparse.ArgumentParser(description=__doc__)
sub = root.add_subparsers(dest="command", required=True)
sub.add_parser("doctor", help="Check Python, Node, CAD converter, and Blender prerequisites")
inspect = sub.add_parser("inspect", help="Convert/read a CAD folder and enforce the source gate")
inspect.add_argument("--input", required=True)
inspect.add_argument("--work", required=True)
inspect.add_argument("--output", required=True)
inspect.add_argument("--vendor-dir", default="work/vendor")
inspect.add_argument("--converter", choices=("auto", "libredwg", "oda"), default="auto")
inspect.add_argument("--no-convert", action="store_true")
inspect.add_argument("--allow-partial", action="store_true")
inspect.add_argument("--partial-reason", default="")
run = sub.add_parser("run", help="Run extract -> audit -> overlays -> variants -> verify from an approved config")
run.add_argument("--dxf-dir", required=True)
run.add_argument("--config", required=True)
run.add_argument("--source-report", required=True, help="Passing cad_read_report.json for this sanitized DXF dir")
run.add_argument("--out-dir", required=True)
run.add_argument("--name", default="cad_building_showcase")
run.add_argument("--vendor-dir", default="work/vendor")
run.add_argument("--frames", nargs="*", default=[])
run.add_argument("--backend", choices=("trimesh", "blender"), default="trimesh")
run.add_argument("--blender")
run.add_argument("--web", action="store_true")
run.add_argument("--skip-web-deps", action="store_true")
run.add_argument("--offline", action="store_true")
run.add_argument("--browser-report")
run.add_argument("--require-browser-report", action="store_true")
run.add_argument(
"--scope-manifest",
required=True,
help="Required single-building/campus scope ledger included in final verification",
)
run.add_argument(
"--waiver",
action="append",
default=[],
metavar="CHECK=REASON",
help="Explicitly acknowledge one WARN/SKIP audit or delivery check",
)
run.add_argument("--budget-mb", type=float, default=25.0)
run.add_argument("--resume", action="store_true")
return root
def main() -> int:
args = parser().parse_args()
if args.command == "doctor":
return doctor()
if args.command == "inspect":
return inspect_command(args)
return run_pipeline(args)
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -0,0 +1,59 @@
"""Shared parsing and application rules for explicit delivery waivers."""
from __future__ import annotations
from typing import Any
WAIVABLE_STATUSES = frozenset({"WARN", "SKIP"})
def parse_waivers(values: list[str]) -> dict[str, str]:
"""Parse CHECK=REASON values and reject malformed or duplicate entries."""
waivers: dict[str, str] = {}
for value in values:
name, separator, reason = value.partition("=")
name = name.strip()
reason = reason.strip()
if not separator or not name or not reason:
raise ValueError(f"Invalid waiver {value!r}; expected CHECK=REASON")
if name in waivers:
raise ValueError(f"Duplicate waiver for {name!r}")
waivers[name] = reason
return waivers
def apply_waivers(checks: list[dict[str, Any]], waivers: dict[str, str]) -> None:
"""Apply waivers to WARN/SKIP checks and add FAIL checks for invalid targets.
Passing a namespace-specific subset lets an earlier pipeline stage reject
misspelled, unused, PASS, FAIL, or NOT_APPLICABLE targets before expensive
downstream work begins. Final verification calls the same function with the
complete waiver map, so both stages have identical semantics.
"""
by_name = {str(check.get("name", "")): check for check in checks}
for name, reason in waivers.items():
check = by_name.get(name)
if check is None:
checks.append(
{
"name": f"waiver:{name}",
"status": "FAIL",
"detail": f"Unused or misspelled waiver: {name}",
}
)
continue
status = str(check.get("status", "FAIL"))
if status not in WAIVABLE_STATUSES:
checks.append(
{
"name": f"waiver:{name}",
"status": "FAIL",
"detail": f"Waivers may only acknowledge WARN/SKIP checks; {name} is {status}",
}
)
continue
check["original_status"] = status
check["status"] = "PASS"
check["waiver_reason"] = reason
check["detail"] = f"WAIVED ({reason}): {check.get('detail', '')}"

View File

@@ -13,6 +13,8 @@ from collections import defaultdict
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
import showcase_schema
DEFAULT_CATEGORIES = { DEFAULT_CATEGORIES = {
"walls": {"label": "墙体", "color": "#d4cbb8", "width": 0.20}, "walls": {"label": "墙体", "color": "#d4cbb8", "width": 0.20},
@@ -78,16 +80,15 @@ def import_ezdxf(vendor_dir: Path):
from ezdxf import recover # type: ignore from ezdxf import recover # type: ignore
except ImportError as exc: except ImportError as exc:
raise SystemExit( raise SystemExit(
"Missing dependency: ezdxf. Install locally with:\n" f"Missing dependency: ezdxf. Install locally with:\n python3 -m pip install --target {vendor_dir} ezdxf"
f" python3 -m pip install --target {vendor_dir} ezdxf"
) from exc ) from exc
return ezdxf, recover return ezdxf, recover
def read_json(path: Path | None) -> dict[str, Any]: def read_json(path: Path | None) -> dict[str, Any]:
if not path: if not path:
return {} return showcase_schema.normalize_config({})
return json.loads(path.read_text(encoding="utf-8")) return showcase_schema.normalize_config(json.loads(path.read_text(encoding="utf-8")))
def read_doc(path: Path, ezdxf, recover): def read_doc(path: Path, ezdxf, recover):
@@ -243,6 +244,23 @@ def match_patterns(value: str, patterns: list[str]) -> bool:
return any(fnmatch.fnmatch(upper_value, str(pattern).upper()) for pattern in patterns) return any(fnmatch.fnmatch(upper_value, str(pattern).upper()) for pattern in patterns)
def block_matches_floor(block_name: str, floor: dict[str, Any], drawing: dict[str, Any]) -> bool:
"""Apply source-view block selectors before expanding a Revit sheet.
Revit DXF exports can place several views at identical world coordinates;
their top-level INSERT names retain the view suffix (for example
``-屋面平面图`` vs ``-机房小屋面``). A clip cannot separate those views, so
the floor config must be able to select the corresponding block family.
"""
includes = list(floor.get("include_block_names", drawing.get("include_block_names", [])) or [])
excludes = list(floor.get("exclude_block_names", drawing.get("exclude_block_names", [])) or [])
if includes and (not block_name or not match_patterns(block_name, includes)):
return False
if excludes and block_name and match_patterns(block_name, excludes):
return False
return True
def block_category(block_name: str, config: dict[str, Any]) -> str | None: def block_category(block_name: str, config: dict[str, Any]) -> str | None:
for category, patterns in config.get("block_name_categories", {}).items(): for category, patterns in config.get("block_name_categories", {}).items():
if match_patterns(block_name, list(patterns)): if match_patterns(block_name, list(patterns)):
@@ -405,10 +423,7 @@ def polyline_points(entity) -> list[tuple[float, float]]:
if entity.dxftype() == "LWPOLYLINE": if entity.dxftype() == "LWPOLYLINE":
return [(float(x), float(y)) for x, y in entity.get_points("xy")] return [(float(x), float(y)) for x, y in entity.get_points("xy")]
if entity.dxftype() == "POLYLINE": if entity.dxftype() == "POLYLINE":
return [ return [(float(vertex.dxf.location.x), float(vertex.dxf.location.y)) for vertex in entity.vertices]
(float(vertex.dxf.location.x), float(vertex.dxf.location.y))
for vertex in entity.vertices
]
return [] return []
@@ -489,10 +504,7 @@ def collect_raw_segments(
recover, recover,
) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]]]: ) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]]]:
patterns = layer_patterns(config) patterns = layer_patterns(config)
default_widths = { default_widths = {key: float(value.get("width", 0.1)) for key, value in DEFAULT_CATEGORIES.items()}
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()}) 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))) 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_length = float(config.get("min_source_length", 1.0))
@@ -532,6 +544,12 @@ def collect_raw_segments(
ignored_by_type: dict[str, int] = defaultdict(int) ignored_by_type: dict[str, int] = defaultdict(int)
for entity in entities: for entity in entities:
root_block_name = (
str(entity.dxf.name) if entity.dxftype() == "INSERT" and entity.dxf.hasattr("name") else ""
)
eligible_floors = [item for item in floor_specs if block_matches_floor(root_block_name, item[0], drawing)]
if not eligible_floors:
continue
for extracted_entity, fallback_layer, block_name in iter_model_entities(entity, config): for extracted_entity, fallback_layer, block_name in iter_model_entities(entity, config):
layer = entity_layer(extracted_entity) layer = entity_layer(extracted_entity)
category = category_for_entity( category = category_for_entity(
@@ -552,7 +570,7 @@ def collect_raw_segments(
min_source = min_source_by_category.get(category, min_source_length) min_source = min_source_by_category.get(category, min_source_length)
min_meters = min_meters_by_category.get(category, min_meters_length) min_meters = min_meters_by_category.get(category, min_meters_length)
for start, end in segments: for start, end in segments:
for floor, key, offset in floor_specs: for floor, key, offset in eligible_floors:
if not segment_matches_floor(start, end, floor, drawing): if not segment_matches_floor(start, end, floor, drawing):
continue continue
trimmed = clip_segment_to_rect(start, end, floor.get("clip", drawing.get("clip"))) trimmed = clip_segment_to_rect(start, end, floor.get("clip", drawing.get("clip")))
@@ -731,7 +749,9 @@ def generated_footprint(segments: dict[str, list[dict[str, Any]]], config: dict[
} }
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]]: 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. """Merge collinear, near-touching segments into continuous spans.
CAD curtain walls are often drawn as sparse panel/mullion segments with gaps; CAD curtain walls are often drawn as sparse panel/mullion segments with gaps;
@@ -742,10 +762,14 @@ def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offs
groups: dict[tuple, list] = {} groups: dict[tuple, list] = {}
keep: list[dict[str, Any]] = [] keep: list[dict[str, Any]] = []
for s in segs: for s in segs:
a = s["start"]; b = s["end"] a = s["start"]
dx = b[0] - a[0]; dy = b[1] - a[1]; length = math.hypot(dx, dy) b = s["end"]
dx = b[0] - a[0]
dy = b[1] - a[1]
length = math.hypot(dx, dy)
if length < 1e-6: if length < 1e-6:
keep.append(s); continue keep.append(s)
continue
ang = math.atan2(dy, dx) % math.pi ang = math.atan2(dy, dx) % math.pi
akey = round(ang / math.radians(angle_tol_deg)) akey = round(ang / math.radians(angle_tol_deg))
nx, ny = -dy / length, dx / length nx, ny = -dy / length, dx / length
@@ -757,8 +781,9 @@ def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offs
dirx, diry = -ny, nx dirx, diry = -ny, nx
offv = a0[0] * nx + a0[1] * ny offv = a0[0] * nx + a0[1] * ny
intervals = [] intervals = []
for (a, b, *_rest) in items: for a, b, *_rest in items:
t0 = a[0] * dirx + a[1] * diry; t1 = b[0] * dirx + b[1] * diry t0 = a[0] * dirx + a[1] * diry
t1 = b[0] * dirx + b[1] * diry
intervals.append([min(t0, t1), max(t0, t1)]) intervals.append([min(t0, t1), max(t0, t1)])
intervals.sort() intervals.sort()
merged = [intervals[0][:]] merged = [intervals[0][:]]
@@ -768,11 +793,15 @@ def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offs
else: else:
merged.append([lo, hi]) merged.append([lo, hi])
for lo, hi in merged: for lo, hi in merged:
out.append({ 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)], "start": [round(offv * nx + lo * dirx, 6), round(offv * ny + lo * diry, 6)],
"width": width, "layer": layer, "source_type": "merged", "end": [round(offv * nx + hi * dirx, 6), round(offv * ny + hi * diry, 6)],
}) "width": width,
"layer": layer,
"source_type": "merged",
}
)
return out return out
@@ -783,14 +812,7 @@ def _cap_floor_group(fk: str, config: dict[str, Any] | None = None) -> str:
(fnmatch patterns, first match wins). Defaults reproduce the A208 case: (fnmatch patterns, first match wins). Defaults reproduce the A208 case:
AUX_* prefix = annex tower, B1/B1M = basement, everything else = main. AUX_* prefix = annex tower, B1/B1M = basement, everything else = main.
""" """
for pattern, group in (config or {}).get("cap_groups", []): return showcase_schema.floor_group(fk, config)
if fnmatch.fnmatch(fk.upper(), str(pattern).upper()):
return str(group)
if fk.startswith("AUX_"):
return "AUX"
if fk in {"B1", "B1M"}:
return "BASE"
return "MAIN"
def _shapely_union(polys: list): def _shapely_union(polys: list):
@@ -833,7 +855,9 @@ def compute_caps(floors: dict[str, Any], config: dict[str, Any]) -> None:
""" """
if not config.get("generate_caps", True): if not config.get("generate_caps", True):
return return
buf = float(config.get("cap_buffer", 1.3)) # Ordinary facade-aligned floors need only a small tolerance. Colonnade or
# broad-overhang projects such as A208 must opt into a larger value.
buf = float(config.get("cap_buffer", 0.1))
for fk, fl in floors.items(): for fk, fl in floors.items():
own_polys = fl.get("footprint", {}).get("polygons", []) own_polys = fl.get("footprint", {}).get("polygons", [])
if not own_polys: if not own_polys:
@@ -857,12 +881,21 @@ def compute_caps(floors: dict[str, Any], config: dict[str, Any]) -> None:
polys = [] # roof_specs handles above-ground tops polys = [] # roof_specs handles above-ground tops
else: else:
up_u = _shapely_union(upper) 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 [] # A 0.1 m facade tolerance creates a thin evidence ring whose area
# can be below the generic 3 m² polygon-noise threshold on small
# buildings. Caps are already footprint-derived, so retain them.
polys = (
_shapely_to_polys(own_u.buffer(buf).difference(up_u.buffer(0.05)), min_area=0.25)
if up_u is not None
else []
)
if polys: if polys:
fl.setdefault("caps", []).append({"z": round(ftop, 6), "polygons": polys}) fl.setdefault("caps", []).append({"z": round(ftop, 6), "polygons": polys})
def drop_isolated_clusters(segments: dict[str, list[dict[str, Any]]], config: dict[str, Any], floor_key: str) -> dict[str, list[dict[str, Any]]]: def drop_isolated_clusters(
segments: dict[str, list[dict[str, Any]]], config: dict[str, Any], floor_key: str
) -> dict[str, list[dict[str, Any]]]:
"""Drop tiny segment clusters far away from the floor's main mass. """Drop tiny segment clusters far away from the floor's main mass.
Sheet legends and title blocks draw window/door symbols with REAL geometry Sheet legends and title blocks draw window/door symbols with REAL geometry
@@ -925,8 +958,10 @@ def drop_isolated_clusters(segments: dict[str, list[dict[str, Any]]], config: di
seg = items[idx][2] seg = items[idx][2]
(x1, y1), (x2, y2) = seg["start"], seg["end"] (x1, y1), (x2, y2) = seg["start"], seg["end"]
total += math.hypot(x2 - x1, y2 - y1) total += math.hypot(x2 - x1, y2 - y1)
bx[0] = min(bx[0], x1, x2); bx[1] = min(bx[1], y1, y2) bx[0] = min(bx[0], x1, x2)
bx[2] = max(bx[2], x1, x2); bx[3] = max(bx[3], y1, y2) bx[1] = min(bx[1], y1, y2)
bx[2] = max(bx[2], x1, x2)
bx[3] = max(bx[3], y1, y2)
return total, bx return total, bx
stats = {root: cluster_stats(idx_list) for root, idx_list in clusters.items()} stats = {root: cluster_stats(idx_list) for root, idx_list in clusters.items()}
@@ -1051,7 +1086,9 @@ def finalize_spec(
if key not in floor_data: if key not in floor_data:
continue continue
floor = floor_data[key] floor = floor_data[key]
segments: dict[str, list[dict[str, Any]]] = {category: [] for category in DEFAULT_CATEGORIES if category != "slab"} segments: dict[str, list[dict[str, Any]]] = {
category: [] for category in DEFAULT_CATEGORIES if category != "slab"
}
xs: list[float] = [] xs: list[float] = []
ys: list[float] = [] ys: list[float] = []
for category, raw_segments in floor["segments_source"].items(): for category, raw_segments in floor["segments_source"].items():
@@ -1131,14 +1168,12 @@ def finalize_spec(
file=sys.stderr, file=sys.stderr,
) )
categories = { categories = {key: {"label": value["label"], "color": value["color"]} for key, value in DEFAULT_CATEGORIES.items()}
key: {"label": value["label"], "color": value["color"]}
for key, value in DEFAULT_CATEGORIES.items()
}
for key, value in config.get("categories", {}).items(): for key, value in config.get("categories", {}).items():
categories.setdefault(key, {}).update(value) categories.setdefault(key, {}).update(value)
return { return {
"schema_version": showcase_schema.SCHEMA_VERSION,
"project": { "project": {
"name": config.get("project_name", "CAD Building Showcase"), "name": config.get("project_name", "CAD Building Showcase"),
"description": config.get("description", "建筑 CAD 生成的 Web 展示模型"), "description": config.get("description", "建筑 CAD 生成的 Web 展示模型"),
@@ -1164,9 +1199,19 @@ def main() -> int:
if not dxf_dir.exists(): if not dxf_dir.exists():
raise SystemExit(f"DXF folder not found: {dxf_dir}") raise SystemExit(f"DXF folder not found: {dxf_dir}")
config = read_json(Path(args.config) if args.config else None) config = read_json(Path(args.config) if args.config else None)
try:
config = showcase_schema.validate_config(config, dxf_dir)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
ezdxf, recover = import_ezdxf(Path(args.vendor_dir)) ezdxf, recover = import_ezdxf(Path(args.vendor_dir))
floor_data, extraction_report = collect_raw_segments(dxf_dir, config, ezdxf, recover) floor_data, extraction_report = collect_raw_segments(dxf_dir, config, ezdxf, recover)
spec = finalize_spec(floor_data, config, extraction_report, dxf_dir) spec = finalize_spec(floor_data, config, extraction_report, dxf_dir)
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
out = Path(args.out) out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True) out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(spec, ensure_ascii=False, indent=2), encoding="utf-8") out.write_text(json.dumps(spec, ensure_ascii=False, indent=2), encoding="utf-8")

View File

@@ -37,6 +37,8 @@ import sys
from collections import Counter, defaultdict from collections import Counter, defaultdict
from pathlib import Path from pathlib import Path
import showcase_schema
PLAN_TITLE = re.compile(r"平面图$") PLAN_TITLE = re.compile(r"平面图$")
PLAN_EXCLUDE = re.compile(r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)") PLAN_EXCLUDE = re.compile(r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
OTHER_TITLE = re.compile(r"(立面图|剖面图)$") OTHER_TITLE = re.compile(r"(立面图|剖面图)$")
@@ -45,6 +47,20 @@ OTHER_TITLE = re.compile(r"(立面图|剖面图)$")
# literal escape sequences, invisible to the 平面图 regexes until decoded. # literal escape sequences, invisible to the 平面图 regexes until decoded.
MIF_RE = re.compile(r"\\M\+([1-5])([0-9A-Fa-f]{4})") MIF_RE = re.compile(r"\\M\+([1-5])([0-9A-Fa-f]{4})")
MIF_CODEPAGES = {"1": "cp932", "2": "big5", "3": "cp949", "4": "johab", "5": "gbk"} MIF_CODEPAGES = {"1": "cp932", "2": "big5", "3": "cp949", "4": "johab", "5": "gbk"}
CAD_TEXT_FORMAT_RE = re.compile(r"\\[LlOoKk]|%%[UuOoKk]")
# Revit/AutoCAD exports often keep the only reliable floor identity in block
# names (for example ``...-首层平面图``) while the visible title text lives in
# the title block at paper coordinates. Keep the vocabulary deliberately
# narrow: arbitrary INSERT names ending in 平面图 must not become floor frames.
FLOOR_TOKEN_RE = re.compile(
r"机房小屋面|机房屋面|"
r"地下[一二三四五六七八九十\d]+层夹层|"
r"地下[一二三四五六七八九十\d]+层|"
r"[一二三四五六七八九十\d]+层夹层|"
r"[一二三四五六七八九十\d]+层|"
r"首层|底层|夹层|屋顶层|屋顶|屋面|机房层|电梯机房"
)
def decode_mif(text: str) -> str: def decode_mif(text: str) -> str:
@@ -60,15 +76,58 @@ def decode_mif(text: str) -> str:
return match.group(0) return match.group(0)
return MIF_RE.sub(repl, text) return MIF_RE.sub(repl, text)
def normalize_cad_text(text: str) -> str:
"""Decode CJK escapes and remove common TEXT/MTEXT decoration codes."""
text = decode_mif(text)
text = CAD_TEXT_FORMAT_RE.sub("", text)
return text.replace("\\P", " ").strip()
def floor_titles_from_label(label: str) -> list[str]:
"""Expand a Chinese plan label into one normalized title per floor.
``主楼首层_二层平面图`` becomes ``主楼首层平面图`` and
``主楼二层平面图``. The building qualifier is retained for the report;
floor identity is normalized separately by :func:`floor_base_key`.
"""
label = normalize_cad_text(label).replace("_", "、")
if label.endswith(("机房小屋面", "机房屋面")):
return [label]
if not label.endswith("平面图") or len(label) > 50:
return []
head = label[:-3]
matches = list(FLOOR_TOKEN_RE.finditer(head))
if not matches:
return [label]
qualifier = re.sub(r"[、,,\s]+$", "", head[: matches[0].start()])
# A long prefix is normally an element/family name, not a building label.
if len(qualifier) > 12:
qualifier = ""
return [f"{qualifier}{match.group(0)}平面图" for match in matches]
def floor_titles_from_insert_name(name: str) -> list[str]:
"""Return floor labels encoded in the final component of an INSERT name."""
suffix = normalize_cad_text(name).rsplit("-", 1)[-1].strip()
return floor_titles_from_label(suffix)
CN_NUM = {"一": 1, "二": 2, "三": 3, "四": 4, "五": 5, "六": 6, "七": 7, "八": 8, "九": 9, "十": 10} CN_NUM = {"一": 1, "二": 2, "三": 3, "四": 4, "五": 5, "六": 6, "七": 7, "八": 8, "九": 9, "十": 10}
FLOOR_NAME_KEY = [ FLOOR_NAME_KEY = [
(re.compile(r"地下(?P<n>[一二三四五六七八九十\d]+)层夹层"), lambda m: f"B{_cn(m.group('n'))}M"), (re.compile(r"地下(?P<n>[一二三四五六七八九十\d]+)层夹层"), lambda m: f"B{_cn(m.group('n'))}M"),
(re.compile(r"地下(?P<n>[一二三四五六七八九十\d]+)层"), lambda m: f"B{_cn(m.group('n'))}"), (re.compile(r"地下(?P<n>[一二三四五六七八九十\d]+)层"), lambda m: f"B{_cn(m.group('n'))}"),
(re.compile(r"屋顶机房|机房层|电梯机房"), lambda m: "PH"), (re.compile(r"机房小屋面|机房屋面|屋顶机房|机房层|电梯机房"), lambda m: "PH"),
(re.compile(r"屋顶|屋面|顶板"), lambda m: "RF"), (re.compile(r"屋顶|屋面|顶板"), lambda m: "RF"),
(re.compile(r"首层"), lambda m: "F1"),
(re.compile(r"(?P<n>[一二三四五六七八九十\d]+)层夹层"), lambda m: f"F{_cn(m.group('n'))}M"), (re.compile(r"(?P<n>[一二三四五六七八九十\d]+)层夹层"), lambda m: f"F{_cn(m.group('n'))}M"),
(re.compile(r"(?P<n>[一二三四五六七八九十\d]+)层"), lambda m: f"F{_cn(m.group('n'))}"), (re.compile(r"(?P<n>[一二三四五六七八九十\d]+)层"), lambda m: f"F{_cn(m.group('n'))}"),
(re.compile(r"地下|底层"), lambda m: "B1"), (re.compile(r"地下|底层"), lambda m: "B1"),
# A bare 夹层 in Chinese architectural sets conventionally means the
# mezzanine above the first floor. Keep the key sortable and consistent
# with explicit 一层夹层 rather than emitting a nonstandard bare ``M``.
(re.compile(r"夹层"), lambda m: "F1M"),
] ]
@@ -124,22 +183,30 @@ def parse_args() -> argparse.Namespace:
parser.add_argument("--out-config", default="work/frames_config.json") parser.add_argument("--out-config", default="work/frames_config.json")
parser.add_argument("--out-report", default="work/frames_report.md") parser.add_argument("--out-report", default="work/frames_report.md")
parser.add_argument("--vendor-dir", default="work/vendor") parser.add_argument("--vendor-dir", default="work/vendor")
parser.add_argument("--title-regex", default=r"平面图$", parser.add_argument(
help="Plan-frame title pattern; e.g. '(?i)(FLOOR )?PLAN$' for English sets") "--title-regex", default=r"平面图$", help="Plan-frame title pattern; e.g. '(?i)(FLOOR )?PLAN$' for English sets"
)
parser.add_argument("--title-exclude-regex", default=r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)") parser.add_argument("--title-exclude-regex", default=r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
parser.add_argument("--title-exclude-layers", default="*图签*,*PUB_TAB*,*TK*,*图框*,*目录*") parser.add_argument("--title-exclude-layers", default="*图签*,*PUB_TAB*,*TTLB*,*TK*,*图框*,*目录*")
# Wildcards matter: design institutes prefix layers (13号地块: A_DOTE/A_AXIS), # Wildcards matter: design institutes prefix layers (13号地块: A_DOTE/A_AXIS),
# and an exact "DOTE" token silently zeroes the grid-correlation votes. # and an exact "DOTE" token silently zeroes the grid-correlation votes.
parser.add_argument("--axis-layers", default="*AXIS*,*DOTE*,*轴线*,*轴网*,S-GRID,*GRID*", parser.add_argument(
help="TArch t3 exports draw plan grids on DOTE; AXIS often only holds detail-sheet stubs") "--axis-layers",
default="*AXIS*,*DOTE*,*轴线*,*轴网*,S-GRID,*GRID*",
help="TArch t3 exports draw plan grids on DOTE; AXIS often only holds detail-sheet stubs",
)
parser.add_argument("--wall-layers", default="WALL,*WALL*,*墙*") parser.add_argument("--wall-layers", default="WALL,*WALL*,*墙*")
parser.add_argument("--refine-fallback-layers", parser.add_argument(
default="*屋面*,*ROOF*,A-ROOF*|*RAIL*,*栏杆*,STAIR,*FLOR*", "--refine-fallback-layers",
help="'|'-separated layer groups tried in order when no walls exist in a frame (e.g. roof plans)") default="*屋面*,*ROOF*,A-ROOF*|*RAIL*,*栏杆*,STAIR,*FLOR*",
parser.add_argument("--frame-aspect", type=float, default=1.5, help="'|'-separated layer groups tried in order when no walls exist in a frame (e.g. roof plans)",
help="Initial clip width = pitch * aspect (A1 landscape + margin)") )
parser.add_argument("--grid-bin", type=float, default=60.0, parser.add_argument(
help="Cluster tolerance (source units) for axis positions and vote bins") "--frame-aspect", type=float, default=1.5, help="Initial clip width = pitch * aspect (A1 landscape + margin)"
)
parser.add_argument(
"--grid-bin", type=float, default=60.0, help="Cluster tolerance (source units) for axis positions and vote bins"
)
return parser.parse_args() return parser.parse_args()
@@ -162,22 +229,24 @@ def match_any(value: str, patterns: list[str]) -> bool:
def entity_text(entity) -> str: def entity_text(entity) -> str:
try: try:
if entity.dxftype() == "TEXT": if entity.dxftype() == "TEXT":
return decode_mif(str(entity.dxf.text or "").strip()) return normalize_cad_text(str(entity.dxf.text or ""))
if entity.dxftype() == "MTEXT": if entity.dxftype() == "MTEXT":
return decode_mif(str(entity.plain_text() or "").strip()) return normalize_cad_text(str(entity.plain_text() or ""))
except Exception: except Exception:
pass pass
return "" return ""
def floor_key_for(name: str, used: set[str]) -> str: def floor_base_key(name: str) -> str:
for pattern, keyfn in FLOOR_NAME_KEY: for pattern, keyfn in FLOOR_NAME_KEY:
match = pattern.search(name) match = pattern.search(name)
if match: if match:
key = keyfn(match) return keyfn(match)
break return re.sub(r"[^0-9A-Za-z]+", "_", name)[:12] or "FLOOR"
else:
key = re.sub(r"[^0-9A-Za-z]+", "_", name)[:12] or "FLOOR"
def floor_key_for(name: str, used: set[str]) -> str:
key = floor_base_key(name)
base, i = key, 2 base, i = key, 2
while key in used: while key in used:
key = f"{base}_{i}" key = f"{base}_{i}"
@@ -228,6 +297,67 @@ def segments_in(entities, clip, layers):
return out return out
def plan_geometry_components(entities, layers):
"""Connected raster components of wall/grid geometry as frame bboxes.
Revit exports may flatten two plans side by side and leave their visible
titles in the paper title block. Long wall/grid segments still form two
disconnected spatial nets. Rasterizing only those structural layers is
deliberately simpler and safer than clustering every annotation entity.
"""
selected = []
lengths = []
for layer, sx, sy, ex, ey in entities:
if not match_any(layer, layers):
continue
length = math.hypot(ex - sx, ey - sy)
if length < 500.0:
continue
selected.append((sx, sy, ex, ey, length))
lengths.append(length)
if not selected:
return []
cell = max(200.0, min(3000.0, statistics.median(lengths) * 0.75))
occupied = set()
for sx, sy, ex, ey, length in selected:
steps = max(1, math.ceil(length / cell))
for i in range(steps + 1):
t = i / steps
occupied.add((round((sx + (ex - sx) * t) / cell), round((sy + (ey - sy) * t) / cell)))
components = []
while occupied:
seed = occupied.pop()
stack = [seed]
cells = [seed]
while stack:
cx, cy = stack.pop()
for nx in range(cx - 1, cx + 2):
for ny in range(cy - 1, cy + 2):
if (nx, ny) in occupied:
occupied.remove((nx, ny))
stack.append((nx, ny))
cells.append((nx, ny))
if len(cells) < 10:
continue
xs = [c[0] for c in cells]
ys = [c[1] for c in cells]
bbox = [min(xs) * cell, min(ys) * cell, (max(xs) + 1) * cell, (max(ys) + 1) * cell]
if bbox[2] - bbox[0] >= cell * 3 and bbox[3] - bbox[1] >= cell * 3:
components.append({"bbox": bbox, "cells": len(cells), "cell": cell})
return sorted(components, key=lambda item: item["cells"], reverse=True)
def robust_point_bbox(points):
"""2-98% bbox, trimming sparse title-block/origin outliers."""
if len(points) < 5:
return None
xs = sorted(p[0] for p in points)
ys = sorted(p[1] for p in points)
lo = max(0, int(len(points) * 0.02))
hi = min(len(points) - 1, int(len(points) * 0.98))
return [xs[lo], ys[lo], xs[hi], ys[hi]]
# A plan title is "pure" when everything before 平面图 is floor vocabulary # A plan title is "pure" when everything before 平面图 is floor vocabulary
# (numbers, 地下/夹层/标准层/机房/屋顶...). Any other prefix (非机动坡道/ # (numbers, 地下/夹层/标准层/机房/屋顶...). Any other prefix (非机动坡道/
# 无障碍住房改造/人防...) marks an auxiliary structure or a revision sheet: # 无障碍住房改造/人防...) marks an auxiliary structure or a revision sheet:
@@ -235,7 +365,7 @@ def segments_in(entities, clip, layers):
# alignment reference (27号 2#: the bike-ramp frame grabbed F1 and every # alignment reference (27号 2#: the bike-ramp frame grabbed F1 and every
# tower frame went WEAK against it). # tower frame went WEAK against it).
PURE_TITLE_RE = re.compile( PURE_TITLE_RE = re.compile(
r"[0-9一二三四五六七八九十百零两FBM#\s层地下夹标准机房屋顶跃阁避难设备转换裙塔、,,~~至\-—.]*平面图$" r"[0-9一二三四五六七八九十百零两FBM#\s层地下夹标准机房屋顶面跃阁避难设备转换裙塔、,,~~至\-—.]*平面图$"
) )
@@ -304,8 +434,7 @@ def correlate_shift(ref_pos, src_pos, coarse: float = 500.0, fine: float = 50.0)
if not fine_votes: if not fine_votes:
return None, 0.0, 0.0 return None, 0.0, 0.0
fb = max(fine_votes, key=lambda k: fine_votes[k]) fb = max(fine_votes, key=lambda k: fine_votes[k])
sel = [(rp - sp, min(rw, sw)) for rp, rw in ref_pos for sp, sw in src_pos sel = [(rp - sp, min(rw, sw)) for rp, rw in ref_pos for sp, sw in src_pos if abs((rp - sp) - fb * fine) <= fine]
if abs((rp - sp) - fb * fine) <= fine]
mass = sum(w for _, w in sel) mass = sum(w for _, w in sel)
shift = sum(d * w for d, w in sel) / mass if mass else center shift = sum(d * w for d, w in sel) / mass if mass else center
return shift, coverage, ratio return shift, coverage, ratio
@@ -329,13 +458,24 @@ def main() -> int:
plan_exclude = re.compile(args.title_exclude_regex) if args.title_exclude_regex else None plan_exclude = re.compile(args.title_exclude_regex) if args.title_exclude_regex else None
titles, others = [], [] titles, others = [], []
lines = [] # (layer, sx, sy, ex, ey) for LINE and polyline edges lines = [] # (layer, sx, sy, ex, ey) for LINE and polyline edges
insert_title_points: dict[str, list[tuple[float, float]]] = defaultdict(list)
insert_title_labels: dict[str, Counter] = defaultdict(Counter)
insert_title_lines: dict[str, list[tuple[str, float, float, float, float]]] = defaultdict(list)
# Plan grids are not always modelspace lines: TArch exports may wrap each # Plan grids are not always modelspace lines: TArch exports may wrap each
# frame's axis system in an anonymous block (黄桥: A$C... wrappers holding # frame's axis system in an anonymous block (黄桥: A$C... wrappers holding
# hundreds of DOTE lines while msp has ~8). Expand INSERTs — but only # hundreds of DOTE lines while msp has ~8). Expand INSERTs — but only
# blocks that actually contain axis/wall-layer curves (memoized per block # blocks that actually contain axis/wall-layer curves (memoized per block
# name), or a sheet full of door/furniture blocks slows the scan for nothing. # name), or a sheet full of door/furniture blocks slows the scan for nothing.
expand_patterns = axis_layers + wall_layers refine_patterns = [
pattern.strip()
for group in args.refine_fallback_layers.split("|")
for pattern in group.split(",")
if pattern.strip()
]
# Roof-only cached blocks can have no WALL/GRID layer at all. They still
# need expansion so roof/railing/floor geometry can seed the frame clip.
expand_patterns = axis_layers + wall_layers + refine_patterns
block_memo: dict[str, bool] = {} block_memo: dict[str, bool] = {}
def block_has_expandable(name: str, depth: int = 0) -> bool: def block_has_expandable(name: str, depth: int = 0) -> bool:
@@ -425,10 +565,12 @@ def main() -> int:
vk = ve.dxftype() vk = ve.dxftype()
if vk == "LINE": if vk == "LINE":
for p in (ve.dxf.start, ve.dxf.end): for p in (ve.dxf.start, ve.dxf.end):
xs_fb.append(float(p.x)); ys_fb.append(float(p.y)) xs_fb.append(float(p.x))
ys_fb.append(float(p.y))
elif vk == "LWPOLYLINE": elif vk == "LWPOLYLINE":
for px, py in ve.get_points("xy"): for px, py in ve.get_points("xy"):
xs_fb.append(float(px)); ys_fb.append(float(py)) xs_fb.append(float(px))
ys_fb.append(float(py))
except Exception: except Exception:
continue continue
if not xs_fb: if not xs_fb:
@@ -440,8 +582,28 @@ def main() -> int:
for entity in msp: for entity in msp:
kind = entity.dxftype() kind = entity.dxftype()
if kind == "INSERT": if kind == "INSERT":
if block_has_expandable(str(entity.dxf.name)): name = str(entity.dxf.name)
expanded_start = len(lines)
if block_has_expandable(name):
collect_insert_lines(entity) collect_insert_lines(entity)
expanded = lines[expanded_start:]
insert_titles = floor_titles_from_insert_name(name)
if insert_titles:
try:
pos = entity.dxf.insert
point = (float(pos.x), float(pos.y))
except Exception:
point = None
for insert_title in insert_titles:
key = floor_base_key(insert_title)
insert_title_labels[key][insert_title] += 1
if point is not None:
insert_title_points[key].append(point)
# A large plan/XREF block carries its own transformed wall
# geometry. Small family blocks (doors, railings, tags)
# are useful as point votes but must not define the clip.
if len(expanded) >= 50:
insert_title_lines[key].extend(expanded)
continue continue
if kind in {"TEXT", "MTEXT"}: if kind in {"TEXT", "MTEXT"}:
classify_text(entity, kind) classify_text(entity, kind)
@@ -457,6 +619,114 @@ def main() -> int:
for a, b in zip(pts, pts[1:]): for a, b in zip(pts, pts[1:]):
lines.append((layer, a[0], a[1], b[0], b[1])) lines.append((layer, a[0], a[1], b[0], b[1]))
# Some Revit exports have no usable plan-title text outside the title
# block. Hundreds of INSERT names still end in ``-首层平面图`` /
# ``-二层平面图``. Turn those repeated, spatially distributed names into
# frame seeds. This is deterministic evidence from the DWG, not a guess
# from the filename.
component_layers = wall_layers + axis_layers + refine_patterns
geometry_components = plan_geometry_components(lines, component_layers)
# Assign each floor identity to the geometry component containing the most
# same-floor INSERT positions. Greedy by confidence keeps adjacent floors
# from both selecting the same plan when Revit reuses a few family blocks
# across views.
component_choice = {}
ranked_keys = []
for key in insert_title_labels:
points = insert_title_points.get(key, [])
expanded = insert_title_lines.get(key, [])
evidence = points if len(points) >= 5 else [((sx + ex) / 2, (sy + ey) / 2) for _, sx, sy, ex, ey in expanded]
scores = []
for index, component in enumerate(geometry_components):
x1, y1, x2, y2 = component["bbox"]
pad = component["cell"] * 2
score = sum(1 for x, y in evidence if x1 - pad <= x <= x2 + pad and y1 - pad <= y <= y2 + pad)
scores.append((score, component["cells"], index))
scores.sort(reverse=True)
best = scores[0][0] if scores else 0
second = scores[1][0] if len(scores) > 1 else 0
ranked_keys.append((best - second, best, key, scores))
used_components = set()
preserve_component_union_keys = set()
for _, best, key, scores in sorted(ranked_keys, reverse=True):
if best <= 0:
continue
choice = next((index for score, _, index in scores if score > 0 and index not in used_components), None)
if choice is not None:
component_choice[key] = geometry_components[choice]
used_components.add(choice)
if len(insert_title_labels) == 1:
only_key = next(iter(insert_title_labels))
if len(geometry_components) == 1:
component_choice[only_key] = geometry_components[0]
elif len(insert_title_lines.get(only_key, [])) >= 50:
# One logical roof floor can contain several disconnected nets
# (main roof + machine-room roofs). Keep their expanded union.
component_choice.pop(only_key, None)
preserve_component_union_keys.add(only_key)
for key, labels in insert_title_labels.items():
points = insert_title_points.get(key, [])
expanded = insert_title_lines.get(key, [])
strong_insert_evidence = len(points) >= 5 or len(expanded) >= 50 or key in component_choice
if strong_insert_evidence:
titles = [t for t in titles if floor_base_key(t["name"]) != key]
elif any(floor_base_key(t["name"]) == key for t in titles):
continue
label = labels.most_common(1)[0][0]
clip_hint = None
component = component_choice.get(key)
if component is not None:
clip_hint = list(component["bbox"])
point_bbox = robust_point_bbox(points)
if len(insert_title_labels) == 1 and point_bbox is not None:
union = [
min(clip_hint[0], point_bbox[0]),
min(clip_hint[1], point_bbox[1]),
max(clip_hint[2], point_bbox[2]),
max(clip_hint[3], point_bbox[3]),
]
if union != clip_hint:
clip_hint = union
preserve_component_union_keys.add(key)
elif len(points) >= 5:
clip_hint = robust_point_bbox(points)
elif len(expanded) >= 50:
xs = [v for _, sx, _, ex, _ in expanded for v in (sx, ex)]
ys_ = [v for _, _, sy, _, ey in expanded for v in (sy, ey)]
if xs and ys_:
clip_hint = [min(xs), min(ys_), max(xs), max(ys_)]
if clip_hint is not None:
width = max(clip_hint[2] - clip_hint[0], 1.0)
height = max(clip_hint[3] - clip_hint[1], 1.0)
margin = max(3000.0, min(max(width, height) * 0.08, 15000.0))
clip_hint = [clip_hint[0] - margin, clip_hint[1] - margin, clip_hint[2] + margin, clip_hint[3] + margin]
x = (clip_hint[0] + clip_hint[2]) / 2
y = (clip_hint[1] + clip_hint[3]) / 2
elif points:
x = statistics.median(p[0] for p in points)
y = statistics.median(p[1] for p in points)
else:
continue
titles.append(
{
"name": label,
"x": x,
"y": y,
"h": 1.0,
"layer": "INSERT_NAME",
"_clip_hint": clip_hint,
"_preserve_component_union": key in preserve_component_union_keys,
# Only a small number of large top-level view wrappers can be
# used as root INSERT selectors. Repeated family/component
# blocks also end in the view name in many Revit exports; using
# their suffix as a root filter drops unrelated wall/column
# INSERTs from the same floor.
**({"_include_block_names": [f"*-{label}"]} if 1 <= len(points) <= 3 and len(expanded) >= 50 else {}),
}
)
if not titles: if not titles:
print(json.dumps({"error": "no plan titles found"}, ensure_ascii=False)) print(json.dumps({"error": "no plan titles found"}, ensure_ascii=False))
return 1 return 1
@@ -501,32 +771,46 @@ def main() -> int:
notes = [] notes = []
refine_groups = [wall_layers] + [ refine_groups = [wall_layers] + [
[p.strip() for p in group.split(",") if p.strip()] [p.strip() for p in group.split(",") if p.strip()]
for group in args.refine_fallback_layers.split("|") if group.strip() for group in args.refine_fallback_layers.split("|")
if group.strip()
] ]
for t in titles: for t in titles:
rough = [t["x"] - clip_w * 0.55, t["y"] - pitch * 0.06, t["x"] + clip_w * 0.55, t["y"] + clip_h] rough = t.get("_clip_hint") or [
if pitch_x and not pitch_y: t["x"] - clip_w * 0.55,
t["y"] - pitch * 0.06,
t["x"] + clip_w * 0.55,
t["y"] + clip_h,
]
if pitch_x and not pitch_y and not t.get("_clip_hint"):
# row layout: title x may sit anywhere under its frame; centre on it # row layout: title x may sit anywhere under its frame; centre on it
rough = [t["x"] - clip_w * 0.6, t["y"] - clip_h * 0.04, t["x"] + clip_w * 0.6, t["y"] + clip_h] rough = [t["x"] - clip_w * 0.6, t["y"] - clip_h * 0.04, t["x"] + clip_w * 0.6, t["y"] + clip_h]
frame_rect = next((r for r in frame_rects frame_rect = next((r for r in frame_rects if r[0] <= t["x"] <= r[2] and r[1] <= t["y"] <= r[3]), None)
if r[0] <= t["x"] <= r[2] and r[1] <= t["y"] <= r[3]), None)
if frame_rect is not None: if frame_rect is not None:
fw, fh = frame_rect[2] - frame_rect[0], frame_rect[3] - frame_rect[1] fw, fh = frame_rect[2] - frame_rect[0], frame_rect[3] - frame_rect[1]
rough = [frame_rect[0] + fw * 0.01, frame_rect[1] + fh * 0.01, rough = [
frame_rect[2] - fw * 0.01, frame_rect[3] - fh * 0.01] frame_rect[0] + fw * 0.01,
frame_rect[1] + fh * 0.01,
frame_rect[2] - fw * 0.01,
frame_rect[3] - fh * 0.01,
]
notes.append(f"{t['name']}: frame-block rect used for clip window ({fw / 1000:.1f}x{fh / 1000:.1f} m)") notes.append(f"{t['name']}: frame-block rect used for clip window ({fw / 1000:.1f}x{fh / 1000:.1f} m)")
clip = None clip = rough if t.get("_preserve_component_union") else None
for group in refine_groups: if clip is None:
found = segments_in(lines, rough, group) for group in refine_groups:
if len(found) >= 10: found = segments_in(lines, rough, group)
xs = [v for s in found for v in (s[0], s[2])] if len(found) >= 10:
ys_ = [v for s in found for v in (s[1], s[3])] xs = [v for s in found for v in (s[0], s[2])]
margin = pitch * 0.06 ys_ = [v for s in found for v in (s[1], s[3])]
clip = [min(xs) - margin, min(ys_) - margin, max(xs) + margin, max(ys_) + margin] margin = pitch * 0.06
if frame_rect is not None: # never swallow the neighbour sheet clip = [min(xs) - margin, min(ys_) - margin, max(xs) + margin, max(ys_) + margin]
clip = [max(clip[0], rough[0]), max(clip[1], rough[1]), if frame_rect is not None: # never swallow the neighbour sheet
min(clip[2], rough[2]), min(clip[3], rough[3])] clip = [
break max(clip[0], rough[0]),
max(clip[1], rough[1]),
min(clip[2], rough[2]),
min(clip[3], rough[3]),
]
break
if clip is None: if clip is None:
clip = rough clip = rough
if frame_rect is None: if frame_rect is None:
@@ -554,7 +838,7 @@ def main() -> int:
f"{t['name']}: auxiliary-titled frame (qualifier '{qualifier}') — likely a " f"{t['name']}: auxiliary-titled frame (qualifier '{qualifier}') — likely a "
"separate structure or revision sheet; excluded from reference candidacy" "separate structure or revision sheet; excluded from reference candidacy"
) )
floors.append({ floor = {
"key": floor_key_for(t["name"], used_keys), "key": floor_key_for(t["name"], used_keys),
"name": t["name"], "name": t["name"],
"clip": [round(c, 1) for c in clip], "clip": [round(c, 1) for c in clip],
@@ -562,13 +846,17 @@ def main() -> int:
"_hy": cluster_positions(horiz, args.grid_bin), "_hy": cluster_positions(horiz, args.grid_bin),
"_walls": segments_in(lines, clip, wall_layers), "_walls": segments_in(lines, clip, wall_layers),
"_aux": bool(qualifier), "_aux": bool(qualifier),
}) }
if t.get("_include_block_names"):
floor["include_block_names"] = list(t["_include_block_names"])
floors.append(floor)
def ref_rank(f): def ref_rank(f):
# never anchor on auxiliary structures (bike ramps, 人防 revisions...); # never anchor on auxiliary structures (bike ramps, 人防 revisions...);
# prefer a pure ground-floor plan, then the richest grid # prefer a pure ground-floor plan, then the richest grid
f1_family = 0 if re.match(r"^F1(_\d+)?$", f["key"]) else 1 f1_family = 0 if re.match(r"^F1(_\d+)?$", f["key"]) else 1
return (1 if f["_aux"] else 0, f1_family, -(len(f["_vx"]) + len(f["_hy"]))) return (1 if f["_aux"] else 0, f1_family, -(len(f["_vx"]) + len(f["_hy"])))
reference = sorted(floors, key=ref_rank)[0] reference = sorted(floors, key=ref_rank)[0]
alignment = [] alignment = []
@@ -587,12 +875,9 @@ def main() -> int:
# Grid voting failed (no axis geometry in this frame). Try wall-profile # Grid voting failed (no axis geometry in this frame). Try wall-profile
# correlation before surrendering to the clip-corner anchor, which is # correlation before surrendering to the clip-corner anchor, which is
# off by whole bays whenever wall bboxes differ between floors. # off by whole bays whenever wall bboxes differ between floors.
wdx, covx, ratx = correlate_shift(wall_profile(reference["_walls"], 0), wdx, covx, ratx = correlate_shift(wall_profile(reference["_walls"], 0), wall_profile(f["_walls"], 0))
wall_profile(f["_walls"], 0)) wdy, covy, raty = correlate_shift(wall_profile(reference["_walls"], 1), wall_profile(f["_walls"], 1))
wdy, covy, raty = correlate_shift(wall_profile(reference["_walls"], 1), if wdx is not None and wdy is not None and covx >= 0.35 and covy >= 0.35 and ratx >= 1.5 and raty >= 1.5:
wall_profile(f["_walls"], 1))
if (wdx is not None and wdy is not None
and covx >= 0.35 and covy >= 0.35 and ratx >= 1.5 and raty >= 1.5):
f["offset"] = [round(wdx, 1), round(wdy, 1)] f["offset"] = [round(wdx, 1), round(wdy, 1)]
alignment.append( alignment.append(
f"{f['key']}: wall-correlated (votes x={vx} y={vy}; coverage x={covx:.2f} " f"{f['key']}: wall-correlated (votes x={vx} y={vy}; coverage x={covx:.2f} "
@@ -600,8 +885,7 @@ def main() -> int:
f"offset={f['offset']}{aux_tag} — verify overlay!" f"offset={f['offset']}{aux_tag} — verify overlay!"
) )
continue continue
f["offset"] = [round(reference["clip"][0] - f["clip"][0], 1), f["offset"] = [round(reference["clip"][0] - f["clip"][0], 1), round(reference["clip"][1] - f["clip"][1], 1)]
round(reference["clip"][1] - f["clip"][1], 1)]
alignment.append( alignment.append(
f"{f['key']}: WEAK grid match (votes x={vx} y={vy}); clip-corner fallback offset={f['offset']}{aux_tag} — verify overlay!" f"{f['key']}: WEAK grid match (votes x={vx} y={vy}); clip-corner fallback offset={f['offset']}{aux_tag} — verify overlay!"
) )
@@ -609,6 +893,30 @@ def main() -> int:
for f in floors: for f in floors:
f.pop("_vx"), f.pop("_hy"), f.pop("_walls"), f.pop("_aux") f.pop("_vx"), f.pop("_hy"), f.pop("_walls"), f.pop("_aux")
# Identical/near-identical inferred clips for different keys are not two
# trustworthy frames. Keep the skeleton for inspection, but say plainly
# that cross-floor overlay must resolve which view belongs in the stack.
for i, left in enumerate(floors):
for right in floors[i + 1 :]:
ax1, ay1, ax2, ay2 = left["clip"]
bx1, by1, bx2, by2 = right["clip"]
overlap = max(0.0, min(ax2, bx2) - max(ax1, bx1)) * max(0.0, min(ay2, by2) - max(ay1, by1))
smaller = min(max((ax2 - ax1) * (ay2 - ay1), 1.0), max((bx2 - bx1) * (by2 - by1), 1.0))
if overlap / smaller >= 0.8:
left_blocks = set(left.get("include_block_names", []))
right_blocks = set(right.get("include_block_names", []))
if left_blocks and right_blocks and left_blocks.isdisjoint(right_blocks):
notes.append(
f"OVERLAPPING clips separated by Revit view identity: {left['key']} uses "
f"{sorted(left_blocks)}, {right['key']} uses {sorted(right_blocks)}"
)
else:
notes.append(
f"AMBIGUOUS overlapping inferred frames: {left['key']} and {right['key']} "
f"overlap {overlap / smaller:.0%}; resolve by cross-floor overlay and keep/discard "
"explicitly — do not model both blindly"
)
# Expand multi-floor titles (四、六、八层 / 十一至十四层) into one config # Expand multi-floor titles (四、六、八层 / 十一至十四层) into one config
# entry per storey sharing the frame's clip/offset — hand-copying N entries # entry per storey sharing the frame's clip/offset — hand-copying N entries
# is where floors silently vanished (13号 b2 F11-F16). z/height stay with # is where floors silently vanished (13号 b2 F11-F16). z/height stay with
@@ -626,34 +934,60 @@ def main() -> int:
covers = covered_floor_numbers(f["name"]) covers = covered_floor_numbers(f["name"])
if covers: if covers:
for n in covers: for n in covers:
config_floors.append({"key": _unique_key(f"F{n}"), "name": f"{n}层({f['name']})", config_floors.append(
"clip": f["clip"], "offset": f["offset"]}) {
notes.append(f"{f['name']}: multi-floor title expanded to " "key": _unique_key(f"F{n}"),
f"{', '.join('F' + str(n) for n in covers)} (same clip/offset; fill z/height per storey)") "name": f"{n}层({f['name']})",
"clip": f["clip"],
"offset": f["offset"],
**({"include_block_names": f["include_block_names"]} if f.get("include_block_names") else {}),
}
)
notes.append(
f"{f['name']}: multi-floor title expanded to "
f"{', '.join('F' + str(n) for n in covers)} (same clip/offset; fill z/height per storey)"
)
else: else:
config_floors.append({"key": _unique_key(f["key"]), "name": f["name"], config_floors.append(
"clip": f["clip"], "offset": f["offset"]}) {
"key": _unique_key(f["key"]),
"name": f["name"],
"clip": f["clip"],
"offset": f["offset"],
**({"include_block_names": f["include_block_names"]} if f.get("include_block_names") else {}),
}
)
view_block_patterns = sorted(
{pattern for floor in config_floors for pattern in floor.get("include_block_names", [])}
)
config = { config = {
"config_version": showcase_schema.CONFIG_VERSION,
"project_name": path.stem, "project_name": path.stem,
"scale": 0.001, "scale": 0.001,
"floor_height": 4.2, "floor_height": 4.2,
"_comment": "Review floor order/keys/z/heights (use elevation/section frames). offset stacks each frame onto the reference frame; origin_strategy normalizes globally.", "_comment": "Review floor order/keys/z/heights (use elevation/section frames). offset stacks each frame onto the reference frame; origin_strategy normalizes globally.",
"origin_strategy": "min", "origin_strategy": "min",
"drawings": [{ **({"expand_block_names": view_block_patterns} if view_block_patterns else {}),
"file": path.name, "drawings": [
"floors": config_floors, {
}], "file": path.name,
"floors": config_floors,
}
],
} }
out_config = Path(args.out_config) out_config = Path(args.out_config)
out_config.parent.mkdir(parents=True, exist_ok=True) out_config.parent.mkdir(parents=True, exist_ok=True)
out_config.write_text(json.dumps(config, ensure_ascii=False, indent=2), encoding="utf-8") out_config.write_text(json.dumps(config, ensure_ascii=False, indent=2), encoding="utf-8")
report = [ report = [
f"# Sheet Frame Detection: {path.name}", "", f"# Sheet Frame Detection: {path.name}",
"",
f"- plan frames: {len(floors)} (sheet pitch ≈ {round(pitch, 1)})", f"- plan frames: {len(floors)} (sheet pitch ≈ {round(pitch, 1)})",
f"- reference frame: {reference['key']} ({reference['name']})", "", f"- reference frame: {reference['key']} ({reference['name']})",
"## Floors", "", "",
"## Floors",
"",
] ]
for f in floors: for f in floors:
report.append(f"- `{f['key']}` {f['name']} clip={f['clip']} offset={f['offset']}") report.append(f"- `{f['key']}` {f['name']} clip={f['clip']} offset={f['offset']}")
@@ -674,8 +1008,10 @@ def main() -> int:
elev_re = re.compile(r"^-?\d{1,3}\.\d{3}$") elev_re = re.compile(r"^-?\d{1,3}\.\d{3}$")
votes: Counter = Counter() votes: Counter = Counter()
ladders: dict[str, set] = {o["name"]: set() for o in frames_e} ladders: dict[str, set] = {o["name"]: set() for o in frames_e}
boxes = [(o["name"], o["x"] - clip_w * 0.6, o["y"] - pitch * 0.06, boxes = [
o["x"] + clip_w * 0.6, o["y"] + clip_h) for o in frames_e] (o["name"], o["x"] - clip_w * 0.6, o["y"] - pitch * 0.06, o["x"] + clip_w * 0.6, o["y"] + clip_h)
for o in frames_e
]
for entity in msp: for entity in msp:
if entity.dxftype() != "TEXT": if entity.dxftype() != "TEXT":
continue continue
@@ -701,10 +1037,16 @@ def main() -> int:
report.append(line) report.append(line)
levels = sorted(v for v, n in votes.items() if n >= 2 or (votes[v] >= 1 and -20 < v < 150)) levels = sorted(v for v, n in votes.items() if n >= 2 or (votes[v] >= 1 and -20 < v < 150))
if levels: if levels:
report.extend(["", "## Suggested storey elevations (from 剖面/立面 标高 texts)", "", report.extend(
"- " + ", ".join(f"{v:+.3f}" for v in levels), [
"- Interpret with judgment: entries include 室外地坪/女儿墙/雨棚; " "",
"storey z = consecutive major levels, height = difference."]) "## Suggested storey elevations (from 剖面/立面 标高 texts)",
"",
"- " + ", ".join(f"{v:+.3f}" for v in levels),
"- Interpret with judgment: entries include 室外地坪/女儿墙/雨棚; "
"storey z = consecutive major levels, height = difference.",
]
)
# Uniform-step suggestion: the dominant consecutive difference and # Uniform-step suggestion: the dominant consecutive difference and
# its longest chain. A SUGGESTION for the Agent to verify against # its longest chain. A SUGGESTION for the Agent to verify against
# the 剖面 — stair sections beat at half-storey rhythm (2.25 for a # the 剖面 — stair sections beat at half-storey rhythm (2.25 for a
@@ -732,12 +1074,20 @@ def main() -> int:
report.append( report.append(
f"- suggested storey table: uniform step {step} m x {len(best_chain) - 1} " f"- suggested storey table: uniform step {step} m x {len(best_chain) - 1} "
f"storeys, z {best_chain[0]:+.3f} → {best_chain[-1]:+.3f} — verify against " f"storeys, z {best_chain[0]:+.3f} → {best_chain[-1]:+.3f} — verify against "
"剖面/立面 per-frame ladders (podium and machine floors may differ)") "剖面/立面 per-frame ladders (podium and machine floors may differ)"
)
Path(args.out_report).write_text("\n".join(report) + "\n", encoding="utf-8") Path(args.out_report).write_text("\n".join(report) + "\n", encoding="utf-8")
print(json.dumps({ print(
"config": str(out_config), "report": args.out_report, json.dumps(
"floors": [f["key"] for f in floors], "pitch": round(pitch, 1), {
}, ensure_ascii=False)) "config": str(out_config),
"report": args.out_report,
"floors": [f["key"] for f in floors],
"pitch": round(pitch, 1),
},
ensure_ascii=False,
)
)
return 0 return 0

View File

@@ -15,6 +15,7 @@ from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent)) sys.path.insert(0, str(Path(__file__).resolve().parent))
import derive_showcase_spec as derive # noqa: E402 import derive_showcase_spec as derive # noqa: E402
import showcase_schema # noqa: E402
CATEGORY_COLORS = { CATEGORY_COLORS = {
@@ -41,7 +42,9 @@ def parse_args() -> argparse.Namespace:
return parser.parse_args() 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]: def source_to_meters(
point: tuple[float, float], offset: tuple[float, float], origin: tuple[float, float], scale: float
) -> tuple[float, float]:
return ( return (
(point[0] + offset[0] - origin[0]) * scale, (point[0] + offset[0] - origin[0]) * scale,
(point[1] + offset[1] - origin[1]) * scale, (point[1] + offset[1] - origin[1]) * scale,
@@ -53,7 +56,9 @@ def line_length(segment: tuple[tuple[float, float], tuple[float, float]]) -> flo
return math.hypot(ex - sx, ey - sy) 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]]]: 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) ezdxf, recover = derive.import_ezdxf(vendor_dir)
patterns = derive.layer_patterns(config) patterns = derive.layer_patterns(config)
max_chord = float(config.get("curve_chord_source_length", 750.0)) max_chord = float(config.get("curve_chord_source_length", 750.0))
@@ -139,8 +144,7 @@ def draw_floor_svg(floor_key: str, floor: dict[str, Any], source_segments: list[
extracted_segments.append({**segment, "category": category, "source_type": "extracted"}) extracted_segments.append({**segment, "category": category, "source_type": "extracted"})
lines = [ lines = [
'<svg xmlns="http://www.w3.org/2000/svg" width="1800" height="1200" ' f'<svg xmlns="http://www.w3.org/2000/svg" width="1800" height="1200" viewBox="{view_box}">',
f'viewBox="{view_box}">',
"<style>", "<style>",
"text{font-family:Arial,sans-serif;font-size:1.2px;fill:#111}", "text{font-family:Arial,sans-serif;font-size:1.2px;fill:#111}",
".legend text{font-size:1.1px}", ".legend text{font-size:1.1px}",
@@ -177,6 +181,12 @@ def main() -> int:
dxf_dir = Path(args.dxf_dir) dxf_dir = Path(args.dxf_dir)
config = derive.read_json(Path(args.config)) config = derive.read_json(Path(args.config))
spec = json.loads(Path(args.spec).read_text(encoding="utf-8")) spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
try:
config = showcase_schema.validate_config(config, dxf_dir)
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
out_dir = Path(args.out_dir) out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True) out_dir.mkdir(parents=True, exist_ok=True)
source_by_floor = collect_source_segments(dxf_dir, config, spec, Path(args.vendor_dir)) source_by_floor = collect_source_segments(dxf_dir, config, spec, Path(args.vendor_dir))
@@ -187,7 +197,9 @@ def main() -> int:
outputs.append(str(out_path)) outputs.append(str(out_path))
index = out_dir / "index.html" 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) 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") 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)) print(json.dumps({"out_dir": str(out_dir), "files": outputs}, ensure_ascii=False))
return 0 return 0

View File

@@ -33,9 +33,7 @@ def import_ezdxf(vendor_dir: Path):
try: try:
import ezdxf # type: ignore import ezdxf # type: ignore
except ImportError as exc: except ImportError as exc:
raise SystemExit( raise SystemExit(f"Missing ezdxf. Install with: python3 -m pip install --target {vendor_dir} ezdxf") from exc
f"Missing ezdxf. Install with: python3 -m pip install --target {vendor_dir} ezdxf"
) from exc
return ezdxf return ezdxf
@@ -59,8 +57,12 @@ def add_entity(space, ent: dict) -> None:
major = (ent["mj"][0], ent["mj"][1], 0.0) major = (ent["mj"][0], ent["mj"][1], 0.0)
if math.hypot(major[0], major[1]) > 0: if math.hypot(major[0], major[1]) > 0:
space.add_ellipse( space.add_ellipse(
ent["c"], major_axis=major, ratio=max(min(ent.get("ratio", 1.0), 1.0), 1e-6), ent["c"],
start_param=ent.get("sa", 0.0), end_param=ent.get("ea", math.tau), dxfattribs=attribs, major_axis=major,
ratio=max(min(ent.get("ratio", 1.0), 1.0), 1e-6),
start_param=ent.get("sa", 0.0),
end_param=ent.get("ea", math.tau),
dxfattribs=attribs,
) )
elif kind == "SPLINE": elif kind == "SPLINE":
space.add_lwpolyline([(v[0], v[1]) for v in ent["v"]], dxfattribs=attribs) space.add_lwpolyline([(v[0], v[1]) for v in ent["v"]], dxfattribs=attribs)
@@ -68,13 +70,16 @@ def add_entity(space, ent: dict) -> None:
text = ent.get("text", "") text = ent.get("text", "")
if text: if text:
space.add_text( space.add_text(
text, height=max(float(ent.get("h", 250.0) or 250.0), 1e-3), dxfattribs=attribs, text,
height=max(float(ent.get("h", 250.0) or 250.0), 1e-3),
dxfattribs=attribs,
).set_placement(ent["p"]) ).set_placement(ent["p"])
elif kind == "INSERT": elif kind == "INSERT":
rotation = ent.get("rot", 0.0) rotation = ent.get("rot", 0.0)
rotation = math.degrees(rotation) if abs(rotation) <= math.tau + 0.01 else rotation rotation = math.degrees(rotation) if abs(rotation) <= math.tau + 0.01 else rotation
space.add_blockref( space.add_blockref(
ent["name"], ent["p"], ent["name"],
ent["p"],
dxfattribs={ dxfattribs={
**attribs, **attribs,
"xscale": ent.get("sx", 1.0) or 1.0, "xscale": ent.get("sx", 1.0) or 1.0,

View File

@@ -0,0 +1,176 @@
#!/usr/bin/env python3
"""Extract flat ACIS 3DSOLID faces and DXF MESH entities to Y-up OBJ/GLB."""
from __future__ import annotations
import argparse
import json
import sys
from collections import Counter
from pathlib import Path
CURVED_RECORDS = (
"cone-surface",
"sphere-surface",
"spline-surface",
"torus-surface",
"cylinder-surface",
"swept-surface",
"revolution-surface",
)
def import_dependencies(vendor_dir: Path):
if vendor_dir.exists():
sys.path.insert(0, str(vendor_dir.resolve()))
try:
import ezdxf
import numpy as np
import trimesh
from ezdxf.acis import api as acis
except ImportError as exc:
raise SystemExit("Install requirements-core.txt (ezdxf, numpy, trimesh) before extracting solids") from exc
return ezdxf, np, trimesh, acis
def triangles_from_face_vertices(faces) -> list[list[tuple[float, float, float]]]:
triangles = []
for face in faces:
points = [(float(point.x), float(point.y), float(point.z)) for point in face]
if len(points) == 3:
triangles.append(points)
elif len(points) > 3:
for index in range(1, len(points) - 1):
triangles.append([points[0], points[index], points[index + 1]])
return triangles
def mesh_entity_triangles(entity) -> list[list[tuple[float, float, float]]]:
vertices = [
(
float(point.x if hasattr(point, "x") else point[0]),
float(point.y if hasattr(point, "y") else point[1]),
float(point.z if hasattr(point, "z") else point[2]),
)
for point in entity.vertices
]
triangles = []
for face in entity.faces:
indices = [int(index) for index in face]
if len(indices) < 3:
continue
for index in range(1, len(indices) - 1):
triangles.append([vertices[indices[0]], vertices[indices[index]], vertices[indices[index + 1]]])
return triangles
def trimesh_from_triangles(triangles, np, trimesh):
if not triangles:
return None
vertices = np.asarray(triangles, dtype=np.float64).reshape(-1, 3)
faces = np.arange(len(vertices), dtype=np.int64).reshape(-1, 3)
finite = np.isfinite(vertices).all(axis=1)
if not finite.all():
good_faces = finite.reshape(-1, 3).all(axis=1)
faces = faces[good_faces]
if len(faces) == 0:
return None
mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False)
tri = mesh.vertices[mesh.faces]
areas = np.linalg.norm(np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0]), axis=1) * 0.5
mesh.update_faces(np.isfinite(areas) & (areas > 1e-9))
mesh.remove_unreferenced_vertices()
if len(mesh.faces) == 0:
return None
# DXF/OBJ is Z-up; glTF is Y-up.
mesh.apply_transform(np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1.0]]))
return mesh
def acis_text(entity) -> str:
sat = getattr(entity, "sat", None)
if sat:
return "\n".join(str(item) for item in sat)
sab = getattr(entity, "sab", None)
return bytes(sab or b"").decode("latin1", errors="ignore")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dxf", required=True, help="ODA-converted R2000+ DXF containing 3DSOLID/MESH")
parser.add_argument("--out-glb", required=True)
parser.add_argument("--out-obj")
parser.add_argument("--report", required=True)
parser.add_argument("--vendor-dir", default="work/vendor")
args = parser.parse_args()
ezdxf, np, trimesh, acis = import_dependencies(Path(args.vendor_dir))
doc = ezdxf.readfile(args.dxf)
scene = trimesh.Scene()
report = {
"report_version": 1,
"source": str(Path(args.dxf)),
"entities": Counter(),
"acis_bodies": 0,
"captured_meshes": 0,
"captured_triangles": 0,
"curved_records": Counter(),
"failures": [],
}
index = 0
for entity in doc.modelspace():
kind = entity.dxftype()
if kind not in {"3DSOLID", "BODY", "REGION", "MESH"}:
continue
report["entities"][kind] += 1
if kind == "MESH":
candidates = [mesh_entity_triangles(entity)]
else:
text = acis_text(entity).lower()
for record in CURVED_RECORDS:
report["curved_records"][record] += text.count(record)
candidates = []
try:
bodies = acis.load_dxf(entity)
report["acis_bodies"] += len(bodies)
for body in bodies:
for mesh in acis.mesh_from_body(body, merge_lumps=False):
candidates.append(triangles_from_face_vertices(mesh.tessellation(max_vertex_count=3)))
except Exception as exc:
report["failures"].append({"handle": entity.dxf.handle, "type": kind, "error": str(exc)})
for triangles in candidates:
mesh = trimesh_from_triangles(triangles, np, trimesh)
if mesh is None:
continue
index += 1
scene.add_geometry(mesh, node_name=f"SOLID_{index:03d}__mesh", geom_name=f"SOLID_{index:03d}__mesh")
report["captured_meshes"] += 1
report["captured_triangles"] += int(len(mesh.faces))
report["entities"] = dict(report["entities"])
report["curved_records"] = {key: value for key, value in report["curved_records"].items() if value}
curved_total = sum(report["curved_records"].values())
report["status"] = "PASS" if report["captured_meshes"] else "FAIL"
report["limitations"] = (
f"{curved_total} curved ACIS surface record(s) require a full CAD kernel and were not tessellated."
if curved_total
else "Only flat polygonal ACIS faces and DXF MESH entities are supported."
)
report_path = Path(args.report)
report_path.parent.mkdir(parents=True, exist_ok=True)
report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
if not report["captured_meshes"]:
print("GATE FAIL [solid_mesh_captured]: no flat ACIS/MESH geometry could be extracted", file=sys.stderr)
return 3
glb = Path(args.out_glb)
glb.parent.mkdir(parents=True, exist_ok=True)
scene.export(glb)
if args.out_obj:
obj = Path(args.out_obj)
obj.parent.mkdir(parents=True, exist_ok=True)
scene.export(obj)
print(json.dumps({"glb": str(glb), "meshes": index, "report": str(report_path)}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -57,10 +57,7 @@ def main() -> int:
model = ifcopenshell.open(str(Path(args.ifc))) model = ifcopenshell.open(str(Path(args.ifc)))
settings = geom.settings() settings = geom.settings()
settings.set(settings.USE_WORLD_COORDS, True) settings.set(settings.USE_WORLD_COORDS, True)
groups = { groups = {ifc_type: {"ifc_type": ifc_type, "vertices": [], "faces": [], "elements": 0} for ifc_type in args.types}
ifc_type: {"ifc_type": ifc_type, "vertices": [], "faces": [], "elements": 0}
for ifc_type in args.types
}
failures = [] failures = []
for ifc_type in args.types: for ifc_type in args.types:
for element in model.by_type(ifc_type): for element in model.by_type(ifc_type):

View File

@@ -23,10 +23,11 @@ import argparse
import json import json
from pathlib import Path from pathlib import Path
import showcase_schema
def main() -> int: def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--outline", required=True, help="JSON [[x,y],...] site meters") parser.add_argument("--outline", required=True, help="JSON [[x,y],...] site meters")
parser.add_argument("--storeys", type=int, required=True) parser.add_argument("--storeys", type=int, required=True)
parser.add_argument("--height", type=float, default=3.0, help="storey height (m)") parser.add_argument("--height", type=float, default=3.0, help="storey height (m)")
@@ -53,13 +54,16 @@ def main() -> int:
floors = {} floors = {}
for i in range(1, args.storeys + 1): for i in range(1, args.storeys + 1):
walls = [{"start": a, "end": b, "width": args.wall_width, "layer": "MASSING"} walls = [
for a, b in zip(poly, poly[1:] + poly[:1])] {"start": a, "end": b, "width": args.wall_width, "layer": "MASSING", "source_type": "site_outline"}
for a, b in zip(poly, poly[1:] + poly[:1])
]
floors[f"F{i}"] = { floors[f"F{i}"] = {
"name": f"{i}层(总图轮廓体量)", "name": f"{i}层(总图轮廓体量)",
"z": round((i - 1) * args.height, 3), "z": round((i - 1) * args.height, 3),
"height": args.height, "height": args.height,
"bounds": bounds, "bounds": bounds,
"source_file": "site_outline",
"segments": {"walls": walls}, "segments": {"walls": walls},
"footprint": {"source": "site_outline", "polygons": [poly]}, "footprint": {"source": "site_outline", "polygons": [poly]},
"caps": [{"z": top_z, "polygons": [poly]}] if i == args.storeys else [], "caps": [{"z": top_z, "polygons": [poly]}] if i == args.storeys else [],
@@ -67,30 +71,51 @@ def main() -> int:
label = args.label or args.name label = args.label or args.name
spec = { spec = {
"project": args.name, "schema_version": showcase_schema.SCHEMA_VERSION,
"description": (f"{label}:无交付图纸,按总平面轮廓×{args.storeys}层×{args.height}m " "project": {
"出体量(诚实标注,非详图模型)"), "name": args.name,
"units": {"scale": 0.001, "origin_source": [ox, oy]}, "description": (
f"{label}:无交付图纸,按总平面轮廓×{args.storeys}层×{args.height}m 出体量(诚实标注,非详图模型)"
),
},
"units": {"source": "meters", "scale_to_meters": 1.0, "origin_source": [ox, oy]},
"categories": { "categories": {
"walls": {"label": "墙体(体量)", "color": "#d4cbb8", "width": args.wall_width}, "walls": {"label": "墙体(体量)", "color": "#d4cbb8", "width": args.wall_width},
"slab": {"label": "楼板", "color": "#c8ccc2", "width": 0.0}, "slab": {"label": "楼板", "color": "#c8ccc2", "width": 0.0},
}, },
"source": {"config": {"use_footprint_slabs": True, "generate_caps": True, "source": {
"roof_specs": [], "project_name": args.name}}, "config": {
"config_version": showcase_schema.CONFIG_VERSION,
"use_footprint_slabs": True,
"generate_caps": True,
"roof_specs": [],
"project_name": args.name,
}
},
"floors": floors, "floors": floors,
} }
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
raise SystemExit(str(exc)) from exc
out = Path(args.out) out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True) out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(spec, ensure_ascii=False), encoding="utf-8") out.write_text(json.dumps(spec, ensure_ascii=False), encoding="utf-8")
ctr = [round(sum(p[0] for p in poly) / len(poly), 3), ctr = [round(sum(p[0] for p in poly) / len(poly), 3), round(sum(p[1] for p in poly) / len(poly), 3)]
round(sum(p[1] for p in poly) / len(poly), 3)] print(
print(json.dumps({ json.dumps(
"out": str(out), "floors": args.storeys, "top_z": top_z, {
"model_anchor_m": ctr, "out": str(out),
"survey_anchor_m": [round(ctr[0] + ox, 3), round(ctr[1] + oy, 3)], "floors": args.storeys,
"rotation_deg": 0.0, "top_z": top_z,
}, ensure_ascii=False)) "model_anchor_m": ctr,
"survey_anchor_m": [round(ctr[0] + ox, 3), round(ctr[1] + oy, 3)],
"rotation_deg": 0.0,
},
ensure_ascii=False,
)
)
return 0 return 0

View File

@@ -0,0 +1,97 @@
#!/usr/bin/env node
/** Prove that the self-contained offline viewer loads from file:// in Chromium. */
import fs from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";
function arg(name, fallback = null) {
const index = process.argv.indexOf(name);
return index >= 0 && process.argv[index + 1] ? process.argv[index + 1] : fallback;
}
const viewer = arg("--viewer");
const out = arg("--out", "offline_browser_smoke_report.json");
const screenshot = arg("--screenshot", "offline_browser_smoke.png");
if (!viewer) {
throw new Error("Usage: offline_viewer_smoke.mjs --viewer viewer.html --out report.json --screenshot smoke.png");
}
let chromium;
try {
({ chromium } = await import("playwright"));
} catch (error) {
throw new Error("Missing Playwright. Install dependencies and Chromium before running this smoke test.", {
cause: error,
});
}
await fs.mkdir(path.dirname(out), { recursive: true });
await fs.mkdir(path.dirname(screenshot), { recursive: true });
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
const consoleErrors = [];
const pageErrors = [];
const failedRequests = [];
const checks = [];
page.on("console", (message) => {
if (message.type() === "error") consoleErrors.push(message.text());
});
page.on("pageerror", (error) => pageErrors.push(error.message));
page.on("requestfailed", (request) => failedRequests.push(`${request.url()} ${request.failure()?.errorText || "failed"}`));
try {
const url = pathToFileURL(path.resolve(viewer)).href;
await page.goto(url, { waitUntil: "load", timeout: 60000 });
await page.waitForFunction(
() => window.__offlineReady || document.getElementById("load")?.textContent?.includes("加载失败"),
null,
{ timeout: 60000 },
);
const state = await page.evaluate(() => ({
viewport: { width: window.innerWidth, height: window.innerHeight },
ready: window.__offlineReady || null,
loadText: document.getElementById("load")?.textContent || "",
canvas: Boolean(document.querySelector("canvas")),
renders: window.__renders || 0,
}));
const viewportPass = state.viewport.width === 1440 && state.viewport.height === 900;
checks.push({
name: "offline:viewport",
status: viewportPass ? "PASS" : "FAIL",
detail: `${state.viewport.width}x${state.viewport.height} expected 1440x900`,
});
checks.push({
name: "offline:model-ready",
status: state.ready?.meshes > 0 && !state.loadText ? "PASS" : "FAIL",
detail: state.ready ? `${state.ready.meshes} mesh(es)` : state.loadText || "readiness marker missing",
});
checks.push({ name: "offline:canvas", status: state.canvas ? "PASS" : "FAIL" });
checks.push({
name: "offline:render",
status: state.renders > 0 ? "PASS" : "FAIL",
detail: `${state.renders} render(s)`,
});
await page.screenshot({ path: screenshot, fullPage: true });
} catch (error) {
checks.push({ name: "offline:load", status: "FAIL", detail: error.message });
await page.screenshot({ path: screenshot, fullPage: true }).catch(() => {});
} finally {
await page.close();
await browser.close();
}
const failedChecks = checks.filter((item) => item.status === "FAIL");
const status = failedChecks.length || consoleErrors.length || pageErrors.length || failedRequests.length ? "FAIL" : "PASS";
const report = {
status,
detail: `${checks.length - failedChecks.length}/${checks.length} checks passed`,
viewer: path.resolve(viewer),
checks,
console_errors: consoleErrors,
page_errors: pageErrors,
failed_requests: failedRequests,
};
await fs.writeFile(out, JSON.stringify(report, null, 2));
process.stdout.write(`${JSON.stringify({ status, report: out })}\n`);
if (status === "FAIL") process.exitCode = 3;

View File

@@ -39,6 +39,8 @@ import math
import sys import sys
from pathlib import Path from pathlib import Path
import showcase_schema
def dist_pt_seg(p, a, b) -> float: def dist_pt_seg(p, a, b) -> float:
ax, ay = a ax, ay = a
@@ -66,8 +68,7 @@ def rot(p, th, c):
return (x * ct - y * st, x * st + y * ct) return (x * ct - y * st, x * st + y * ct)
def register(model_polys, site_pts, angle_window=None, coarse=1.0, refine=0.05, def register(model_polys, site_pts, angle_window=None, coarse=1.0, refine=0.05, trim=0.9):
trim=0.9):
"""Best (theta_deg, translation, score) overlaying model polygons on points. """Best (theta_deg, translation, score) overlaying model polygons on points.
score = trimmed mean distance from each site point to the nearest score = trimmed mean distance from each site point to the nearest
@@ -80,9 +81,10 @@ def register(model_polys, site_pts, angle_window=None, coarse=1.0, refine=0.05,
def score_at(th_deg, t): def score_at(th_deg, t):
th = math.radians(th_deg) th = math.radians(th_deg)
edges = [((rot(a, th, mc)[0] + t[0], rot(a, th, mc)[1] + t[1]), edges = [
(rot(b, th, mc)[0] + t[0], rot(b, th, mc)[1] + t[1])) ((rot(a, th, mc)[0] + t[0], rot(a, th, mc)[1] + t[1]), (rot(b, th, mc)[0] + t[0], rot(b, th, mc)[1] + t[1]))
for a, b in edges_m] for a, b in edges_m
]
ds = sorted(min(dist_pt_seg(p, a, b) for a, b in edges) for p in site_pts) ds = sorted(min(dist_pt_seg(p, a, b) for a, b in edges) for p in site_pts)
k = max(1, int(len(ds) * trim)) k = max(1, int(len(ds) * trim))
return sum(ds[:k]) / k return sum(ds[:k]) / k
@@ -99,9 +101,13 @@ def register(model_polys, site_pts, angle_window=None, coarse=1.0, refine=0.05,
t = list(best[1]) t = list(best[1])
for _ in range(4): for _ in range(4):
thr = math.radians(th0) thr = math.radians(th0)
edges = [((rot(a, thr, mc)[0] + t[0], rot(a, thr, mc)[1] + t[1]), edges = [
(rot(b, thr, mc)[0] + t[0], rot(b, thr, mc)[1] + t[1])) (
for a, b in edges_m] (rot(a, thr, mc)[0] + t[0], rot(a, thr, mc)[1] + t[1]),
(rot(b, thr, mc)[0] + t[0], rot(b, thr, mc)[1] + t[1]),
)
for a, b in edges_m
]
vecs = [] vecs = []
for p in site_pts: for p in site_pts:
dmin, q = 1e9, None dmin, q = 1e9, None
@@ -134,20 +140,26 @@ def register(model_polys, site_pts, angle_window=None, coarse=1.0, refine=0.05,
def main() -> int: def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--spec", required=True, help="building_spec.json") parser.add_argument("--spec", required=True, help="building_spec.json")
parser.add_argument("--floors", nargs="+", required=True, parser.add_argument(
help="floor keys whose footprints form the registration target") "--floors", nargs="+", required=True, help="floor keys whose footprints form the registration target"
parser.add_argument("--site-points", required=True, )
help="JSON: [[x,y],...] site outline vertices / corner callouts (m)") parser.add_argument(
parser.add_argument("--angle-window", nargs=2, type=float, default=None, "--site-points", required=True, help="JSON: [[x,y],...] site outline vertices / corner callouts (m)"
metavar=("LO", "HI"), help="restrict rotation search (deg)") )
parser.add_argument(
"--angle-window", nargs=2, type=float, default=None, metavar=("LO", "HI"), help="restrict rotation search (deg)"
)
parser.add_argument("--out", required=True) parser.add_argument("--out", required=True)
parser.add_argument("--prefix", default="", help="building prefix for the manifest entry") parser.add_argument("--prefix", default="", help="building prefix for the manifest entry")
args = parser.parse_args() args = parser.parse_args()
spec = json.loads(Path(args.spec).read_text(encoding="utf-8")) spec = showcase_schema.normalize_spec(json.loads(Path(args.spec).read_text(encoding="utf-8")))
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
raise SystemExit(str(exc)) from exc
polys = [] polys = []
for fk in args.floors: for fk in args.floors:
floor = spec.get("floors", {}).get(fk) floor = spec.get("floors", {}).get(fk)
@@ -155,8 +167,9 @@ def main() -> int:
raise SystemExit(f"floor {fk!r} not in spec") raise SystemExit(f"floor {fk!r} not in spec")
polys.extend((floor.get("footprint") or {}).get("polygons") or []) polys.extend((floor.get("footprint") or {}).get("polygons") or [])
if not polys: if not polys:
raise SystemExit("no footprint polygons on the requested floors — " raise SystemExit(
"enable generate_footprints or pick other floors") "no footprint polygons on the requested floors — enable generate_footprints or pick other floors"
)
raw = json.loads(Path(args.site_points).read_text(encoding="utf-8")) raw = json.loads(Path(args.site_points).read_text(encoding="utf-8"))
site_pts = raw.get("points") if isinstance(raw, dict) else raw site_pts = raw.get("points") if isinstance(raw, dict) else raw
site_pts = [(float(p[0]), float(p[1])) for p in site_pts] site_pts = [(float(p[0]), float(p[1])) for p in site_pts]
@@ -185,12 +198,19 @@ def main() -> int:
out = Path(args.out) out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True) out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(result, ensure_ascii=False, indent=1), encoding="utf-8") out.write_text(json.dumps(result, ensure_ascii=False, indent=1), encoding="utf-8")
print(json.dumps({"out": str(out), "rotation_deg": result["rotation_deg"], print(
"residual_m": result["residual_m"]}, ensure_ascii=False)) json.dumps(
{"out": str(out), "rotation_deg": result["rotation_deg"], "residual_m": result["residual_m"]},
ensure_ascii=False,
)
)
if score > 2.0: if score > 2.0:
print(f"WARNING residual {score:.2f} m is high — wrong outline, wrong floors, " print(
"or the site points include strays (garage outline / fire pads); " f"WARNING residual {score:.2f} m is high — wrong outline, wrong floors, "
"plot the overlay before trusting this placement.", file=sys.stderr) "or the site points include strays (garage outline / fire pads); "
"plot the overlay before trusting this placement.",
file=sys.stderr,
)
return 0 return 0

View File

@@ -23,7 +23,7 @@ def parse_args() -> argparse.Namespace:
if "--" in argv: if "--" in argv:
argv = argv[argv.index("--") + 1 :] argv = argv[argv.index("--") + 1 :]
else: else:
argv = [] argv = argv[1:]
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--meshes", required=True, help="Mesh JSON from extract_ifc_meshes.py") parser.add_argument("--meshes", required=True, help="Mesh JSON from extract_ifc_meshes.py")
parser.add_argument("--out-dir", required=True) parser.add_argument("--out-dir", required=True)
@@ -149,7 +149,9 @@ def main() -> int:
try: try:
import bpy # type: ignore import bpy # type: ignore
except ImportError as exc: except ImportError as exc:
raise SystemExit("Run this script with Blender: blender -b --python render_ifc_meshes_blender.py -- --meshes ...") from 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")) payload = json.loads(Path(args.meshes).read_text(encoding="utf-8"))
out_dir = Path(args.out_dir) out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True) out_dir.mkdir(parents=True, exist_ok=True)
@@ -171,7 +173,17 @@ def main() -> int:
bpy.ops.export_scene.gltf(filepath=str(glb_path), export_format="GLB") bpy.ops.export_scene.gltf(filepath=str(glb_path), export_format="GLB")
bpy.context.scene.render.filepath = str(png_path) bpy.context.scene.render.filepath = str(png_path)
bpy.ops.render.render(write_still=True) 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)) 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 return 0

312
scripts/showcase_schema.py Normal file
View File

@@ -0,0 +1,312 @@
#!/usr/bin/env python3
"""Shared schema and semantic validation for CAD showcase artifacts."""
from __future__ import annotations
import argparse
import copy
import fnmatch
import json
from pathlib import Path
from typing import Any
SCHEMA_VERSION = 1
CONFIG_VERSION = 1
MANIFEST_VERSION = 1
REPORT_VERSION = 1
ROOT = Path(__file__).resolve().parent.parent
SCHEMA_DIR = ROOT / "schemas"
LEGACY_CATEGORY_STYLES = {
"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"},
}
class ValidationFailure(ValueError):
"""Raised when a config or generated artifact violates the contract."""
def _validator(schema_name: str):
try:
import jsonschema
except ImportError:
return None
schema = json.loads((SCHEMA_DIR / schema_name).read_text(encoding="utf-8"))
return jsonschema.Draft202012Validator(schema)
def _format_errors(errors) -> list[str]:
result = []
for error in sorted(errors, key=lambda item: list(item.absolute_path)):
path = ".".join(str(part) for part in error.absolute_path) or "$"
result.append(f"{path}: {error.message}")
return result
def schema_errors(data: dict[str, Any], schema_name: str) -> list[str]:
validator = _validator(schema_name)
if validator is not None:
return _format_errors(validator.iter_errors(data))
# Blender ships an isolated Python without project dependencies. Keep a
# small structural fallback so direct Blender runs still fail on broken
# artifacts; normal CPython runs use the full Draft 2020-12 schemas.
if schema_name == "building_spec.schema.json":
required = {"schema_version", "project", "source", "units", "categories", "floors"}
elif schema_name == "extraction_config.schema.json":
required = {"config_version"}
else:
required = {"manifest_version", "name", "default_key", "variants"}
return [f"$: missing required property {key!r}" for key in sorted(required - set(data))]
def normalize_config(config: dict[str, Any]) -> dict[str, Any]:
"""Attach the current version while keeping legacy v0 configs readable."""
normalized = dict(config)
normalized.setdefault("config_version", CONFIG_VERSION)
if normalized.get("origin_strategy") == "min_corner":
normalized["origin_strategy"] = "min"
return normalized
def normalize_spec(spec: dict[str, Any]) -> dict[str, Any]:
"""Read pre-versioning artifacts while emitting only the current contract."""
normalized = copy.deepcopy(spec)
normalized.setdefault("schema_version", SCHEMA_VERSION)
project = normalized.get("project", {})
if isinstance(project, str):
project = {"name": project, "description": str(normalized.pop("description", ""))}
else:
project = dict(project)
project.setdefault("name", "CAD Building Showcase")
project.setdefault("description", str(normalized.pop("description", "")))
normalized["project"] = project
source = dict(normalized.get("source", {}))
source["config"] = normalize_config(dict(source.get("config", {})))
normalized["source"] = source
raw_units = normalized.get("units", {})
units = {"source": raw_units} if isinstance(raw_units, str) else dict(raw_units)
scale = float(units.pop("scale", units.get("scale_to_meters", 0.001)))
units.setdefault("source", "millimeters" if scale == 0.001 else "unknown")
units.setdefault("scale_to_meters", scale)
units.setdefault("origin_source", [0.0, 0.0])
normalized["units"] = units
raw_categories = normalized.get("categories", {})
categories = copy.deepcopy(raw_categories) if isinstance(raw_categories, dict) else {}
configured_categories = source["config"].get("categories", {})
used_categories = {
category
for floor in normalized.get("floors", {}).values()
for category, segments in floor.get("segments", {}).items()
if segments
}
if source["config"].get("use_footprint_slabs"):
used_categories.add("slab")
for category in sorted(used_categories):
if category in categories:
continue
style = dict(LEGACY_CATEGORY_STYLES.get(category, {"label": category, "color": "#8c9088"}))
override = configured_categories.get(category, {}) if isinstance(configured_categories, dict) else {}
if isinstance(override, dict):
style.update({key: override[key] for key in ("label", "color") if key in override})
categories[category] = style
normalized["categories"] = categories
for floor in normalized.get("floors", {}).values():
floor.setdefault("source_file", "unknown")
for category, segments in floor.get("segments", {}).items():
for segment in segments:
segment.setdefault("width", 0.1)
segment.setdefault("layer", "")
segment.setdefault("source_type", "legacy")
return normalized
def floor_group(floor_key: str, config: dict[str, Any] | None = None) -> str:
"""Return the configured stack group used by caps and support checks."""
for pattern, group in (config or {}).get("cap_groups", []):
if fnmatch.fnmatch(floor_key.upper(), str(pattern).upper()):
return str(group)
if floor_key.startswith("AUX_"):
return "AUX"
if floor_key in {"B1", "B1M"}:
return "BASE"
return "MAIN"
def config_semantic_errors(config: dict[str, Any], dxf_dir: Path | None = None) -> list[str]:
errors: list[str] = []
seen: dict[str, str] = {}
drawings = config.get("drawings", []) or []
if not drawings:
errors.append("drawings: extraction config contains no drawings")
for drawing in drawings:
file_name = str(drawing.get("file", ""))
if dxf_dir is not None and file_name and not (dxf_dir / file_name).exists():
errors.append(f"drawings[{file_name}]: source DXF does not exist under {dxf_dir}")
floors = drawing.get("floors") or [{"key": Path(file_name).stem}]
for floor in floors:
key = str(floor.get("key", ""))
location = f"{file_name}:{floor.get('name', key)}"
if key in seen:
errors.append(f"duplicate floor key {key!r}: used by both {seen[key]} and {location}")
else:
seen[key] = location
order = config.get("floor_order") or []
missing = sorted(set(seen) - set(order)) if order else []
ghosts = sorted(set(order) - set(seen)) if order else []
if missing:
errors.append(f"floor_order omits configured floor keys: {missing}")
if ghosts:
errors.append(f"floor_order contains unknown floor keys: {ghosts}")
return errors
def validate_config(config: dict[str, Any], dxf_dir: Path | None = None) -> dict[str, Any]:
normalized = normalize_config(config)
errors = schema_errors(normalized, "extraction_config.schema.json")
errors.extend(config_semantic_errors(normalized, dxf_dir))
if errors:
raise ValidationFailure("Invalid extraction config:\n- " + "\n- ".join(errors))
return normalized
def spec_semantic_errors(spec: dict[str, Any]) -> list[str]:
errors: list[str] = []
floors = spec.get("floors", {})
categories = set(spec.get("categories", {}))
if not floors:
errors.append("floors: spec contains no floors")
for key, floor in floors.items():
unknown_categories = sorted(
category for category, items in floor.get("segments", {}).items() if items and category not in categories
)
if unknown_categories:
errors.append(f"floors.{key}.segments: categories missing from spec.categories: {unknown_categories}")
segment_count = sum(len(items) for items in floor.get("segments", {}).values())
polygon_count = len((floor.get("footprint") or {}).get("polygons", []))
cap_count = sum(len(cap.get("polygons", [])) for cap in floor.get("caps", []))
if segment_count == 0 and polygon_count == 0 and cap_count == 0:
errors.append(f"floors.{key}: floor has no segments, footprint polygons, or caps")
for item in spec.get("extraction_report", []):
if item.get("status") != "ok":
errors.append(f"extraction_report: {item.get('file', '?')} status={item.get('status', '?')}")
return errors
def validate_spec(spec: dict[str, Any]) -> dict[str, Any]:
errors = schema_errors(spec, "building_spec.schema.json")
embedded_config = normalize_config(dict(spec.get("source", {}).get("config", {})))
errors.extend(f"source.config.{item}" for item in schema_errors(embedded_config, "extraction_config.schema.json"))
errors.extend(spec_semantic_errors(spec))
if errors:
raise ValidationFailure("Invalid building spec:\n- " + "\n- ".join(errors))
return spec
def validate_manifest(manifest: dict[str, Any]) -> dict[str, Any]:
errors = schema_errors(manifest, "variants_manifest.schema.json")
keys = [item.get("key") for item in manifest.get("variants", [])]
if len(keys) != len(set(keys)):
errors.append("variants: duplicate variant keys")
if manifest.get("default_key") not in keys:
errors.append("default_key: does not reference a variant key")
if errors:
raise ValidationFailure("Invalid variants manifest:\n- " + "\n- ".join(errors))
return manifest
def validate_source_report(report: dict[str, Any], expected_dxf_dir: Path | None = None) -> dict[str, Any]:
if not isinstance(report, dict):
raise ValidationFailure("Invalid CAD source report:\n- $: expected a JSON object")
errors = []
if report.get("report_version") != REPORT_VERSION:
errors.append(f"report_version: expected {REPORT_VERSION}, got {report.get('report_version')!r}")
gate = report.get("gate") or {}
if not isinstance(gate, dict):
gate = {}
gate_status = gate.get("status")
if gate.get("name") != "all_sources_converted_and_readable" or gate_status not in {"PASS", "WARN"}:
errors.append(
f"gate: all_sources_converted_and_readable must be PASS or a reasoned partial WARN, got {gate_status!r}"
)
if gate_status == "WARN" and not str(gate.get("partial_reason", "")).strip():
errors.append("gate.partial_reason: WARN source reports require a non-empty partial reason")
files = report.get("files")
if not isinstance(files, list) or not files:
errors.append("files: report contains no inspected DXF files")
else:
readable = 0
for index, item in enumerate(files):
if not isinstance(item, dict):
errors.append(f"files[{index}]: expected an object")
continue
try:
entity_count = int(item.get("modelspace_entities", 0) or 0)
except (TypeError, ValueError):
entity_count = 0
if item.get("status") == "ok" and entity_count > 0:
readable += 1
elif gate_status == "PASS":
errors.append(
f"files[{index}]: {item.get('file', '?')} is not readable and nonempty "
f"(status={item.get('status')!r}, entities={item.get('modelspace_entities')!r})"
)
if readable == 0:
errors.append("files: partial reports still require at least one readable nonempty DXF")
if expected_dxf_dir is not None:
reported = Path(str(report.get("dxf_sanitized", "")))
if not reported.is_absolute():
reported = ROOT / reported
if reported.resolve() != expected_dxf_dir.resolve():
errors.append(
f"dxf_sanitized: report points to {reported.resolve()}, expected {expected_dxf_dir.resolve()}"
)
elif expected_dxf_dir.exists():
report_items = files if isinstance(files, list) else []
reported_files = {str(item.get("file")) for item in report_items if isinstance(item, dict)}
actual_files = {path.name for path in expected_dxf_dir.glob("*.dxf")}
if reported_files != actual_files:
errors.append(
"files: source report and sanitized directory differ "
f"(missing={sorted(actual_files - reported_files)}, stale={sorted(reported_files - actual_files)})"
)
if errors:
raise ValidationFailure("Invalid CAD source report:\n- " + "\n- ".join(errors))
return report
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("kind", choices=("config", "spec", "manifest", "source-report"))
parser.add_argument("path")
parser.add_argument("--dxf-dir", help="Required for checking config source-file existence")
args = parser.parse_args()
try:
data = json.loads(Path(args.path).read_text(encoding="utf-8"))
if args.kind == "config":
validate_config(data, Path(args.dxf_dir) if args.dxf_dir else None)
elif args.kind == "spec":
validate_spec(data)
elif args.kind == "manifest":
validate_manifest(data)
else:
validate_source_report(data, Path(args.dxf_dir) if args.dxf_dir else None)
except (OSError, json.JSONDecodeError, ValidationFailure, TypeError, ValueError, AttributeError) as exc:
print(str(exc))
return 3
print(json.dumps({"status": "PASS", "kind": args.kind, "path": args.path}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -25,16 +25,31 @@ import json
import math import math
from pathlib import Path from pathlib import Path
ROAD_LAYERS = {"Z5-车行道": 0.30, "Z5-道路中心线": 0.10, "Z6-其他符号": 0.12, ROAD_LAYERS = {
"Z2-绿化控制线": 0.08, "Z2-建筑退界线": 0.08, "竖向": 0.08} "Z5-车行道": 0.30,
"Z5-道路中心线": 0.10,
"Z6-其他符号": 0.12,
"Z2-绿化控制线": 0.08,
"Z2-建筑退界线": 0.08,
"竖向": 0.08,
}
PARKING_LAYERS = {"Z3-车位": 0.08} PARKING_LAYERS = {"Z3-车位": 0.08}
FENCE_LAYERS = {"Z3-围墙": 0.15} FENCE_LAYERS = {"Z3-围墙": 0.15}
BOUNDARY_LAYERS = ["Z2-用地红线"] BOUNDARY_LAYERS = ["Z2-用地红线"]
TREE_LAYERS = ["Z4-树层(行道树)", "*树*"] TREE_LAYERS = ["Z4-树层(行道树)", "*树*"]
MASSING_LAYERS = ["平面", "屋面", "面积核算", "*建筑轮廓*"] MASSING_LAYERS = ["平面", "屋面", "面积核算", "*建筑轮廓*"]
MASSING_HEIGHTS = [("2#", 24.0), ("3#", 8.5), ("辅房", 8.5), ("门卫", 3.5), MASSING_HEIGHTS = [
("停车", 4.0), ("污水", 2.0), ("水池", 2.0), ("消控", 3.5), ("2#", 24.0),
("连廊", 4.5), ("钢楼梯", 6.5)] ("3#", 8.5),
("辅房", 8.5),
("门卫", 3.5),
("停车", 4.0),
("污水", 2.0),
("水池", 2.0),
("消控", 3.5),
("连廊", 4.5),
("钢楼梯", 6.5),
]
MASSING_SKIP = ("出入口",) # gate openings marked as small rects; not volumes MASSING_SKIP = ("出入口",) # gate openings marked as small rects; not volumes
LABEL_SKIP = __import__("re").compile(r"^[XxYy]=|^[-+]?\d+([.,]\d+)?$") LABEL_SKIP = __import__("re").compile(r"^[XxYy]=|^[-+]?\d+([.,]\d+)?$")
DEFAULT_MASSING_H = 6.0 DEFAULT_MASSING_H = 6.0
@@ -43,14 +58,35 @@ DEFAULT_MASSING_H = 6.0
def parse_args() -> argparse.Namespace: def parse_args() -> argparse.Namespace:
p = argparse.ArgumentParser(description=__doc__) p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--dump", action="append", required=True, help="dump JSON path (repeatable)") p.add_argument("--dump", action="append", required=True, help="dump JSON path (repeatable)")
p.add_argument("--scale", action="append", required=True, type=float, p.add_argument(
help="units->meters factor for the matching --dump (1.0 for m, 0.001 for mm)") "--scale",
p.add_argument("--region", nargs=4, type=float, required=True, metavar=("X0", "Y0", "X1", "Y1"), action="append",
help="surveying-meter window selecting ONE plan copy") required=True,
p.add_argument("--origin", nargs=2, type=float, required=True, type=float,
help="campus local origin in surveying meters (e.g. 红线 min corner)") help="units->meters factor for the matching --dump (1.0 for m, 0.001 for mm)",
p.add_argument("--exclude-quad", nargs=8, type=float, default=None, )
help="4 corners (m) of the real-model building; site geometry inside is dropped") p.add_argument(
"--region",
nargs=4,
type=float,
required=True,
metavar=("X0", "Y0", "X1", "Y1"),
help="surveying-meter window selecting ONE plan copy",
)
p.add_argument(
"--origin",
nargs=2,
type=float,
required=True,
help="campus local origin in surveying meters (e.g. 红线 min corner)",
)
p.add_argument(
"--exclude-quad",
nargs=8,
type=float,
default=None,
help="4 corners (m) of the real-model building; site geometry inside is dropped",
)
p.add_argument("--out", required=True) p.add_argument("--out", required=True)
return p.parse_args() return p.parse_args()
@@ -59,8 +95,10 @@ def flatten_arc(c, r, sa, ea, scale):
if ea < sa: if ea < sa:
ea += math.tau ea += math.tau
steps = max(8, min(48, int(abs(ea - sa) * r * scale / 1.5) + 8)) steps = max(8, min(48, int(abs(ea - sa) * r * scale / 1.5) + 8))
return [(c[0] + math.cos(sa + (ea - sa) * i / steps) * r, return [
c[1] + math.sin(sa + (ea - sa) * i / steps) * r) for i in range(steps + 1)] (c[0] + math.cos(sa + (ea - sa) * i / steps) * r, c[1] + math.sin(sa + (ea - sa) * i / steps) * r)
for i in range(steps + 1)
]
def in_quad(pt, quad): def in_quad(pt, quad):
@@ -82,6 +120,7 @@ def in_quad(pt, quad):
def match(layer: str, patterns) -> bool: def match(layer: str, patterns) -> bool:
import fnmatch import fnmatch
return any(fnmatch.fnmatch(layer, p) for p in patterns) return any(fnmatch.fnmatch(layer, p) for p in patterns)
@@ -109,7 +148,8 @@ def main() -> int:
if math.hypot(b[0] - a[0], b[1] - a[1]) < 0.15: if math.hypot(b[0] - a[0], b[1] - a[1]) < 0.15:
return return
segs[floor].setdefault(cat, []).append( segs[floor].setdefault(cat, []).append(
{"start": local(a), "end": local(b), "width": width, "layer": layer, "source_type": "SITE"}) {"start": local(a), "end": local(b), "width": width, "layer": layer, "source_type": "SITE"}
)
for dump_path, scale in zip(args.dump, args.scale): for dump_path, scale in zip(args.dump, args.scale):
d = json.loads(Path(dump_path).read_text(encoding="utf-8")) d = json.loads(Path(dump_path).read_text(encoding="utf-8"))
@@ -127,6 +167,7 @@ def main() -> int:
def tf(pt): def tf(pt):
tx, ty = pt[0] * sx, pt[1] * sy tx, ty = pt[0] * sx, pt[1] * sy
return (px + tx * cr - ty * srr, py + tx * srr + ty * cr) return (px + tx * cr - ty * srr, py + tx * srr + ty * cr)
for be in blocks.get(name, []): for be in blocks.get(name, []):
if be["t"] == "LINE": if be["t"] == "LINE":
yield "seg", (tf(be["a"]), tf(be["b"])) yield "seg", (tf(be["a"]), tf(be["b"]))
@@ -199,39 +240,80 @@ def main() -> int:
xs = [p[0] for p in mpts] xs = [p[0] for p in mpts]
ys = [p[1] for p in mpts] ys = [p[1] for p in mpts]
w, h = max(xs) - min(xs), max(ys) - min(ys) w, h = max(xs) - min(xs), max(ys) - min(ys)
if (len(mpts) >= 4 and w >= 3.0 and h >= 3.0 and if (
max(w, h) / max(min(w, h), 0.1) <= 8.0 and not in_quad((mx, my), quad)): len(mpts) >= 4
and w >= 3.0
and h >= 3.0
and max(w, h) / max(min(w, h), 0.1) <= 8.0
and not in_quad((mx, my), quad)
):
massings.append({"pts": [local(p) for p in mpts], "c": (mx, my), "w": w, "h": h}) massings.append({"pts": [local(p) for p in mpts], "c": (mx, my), "w": w, "h": h})
floors = {} floors = {}
if boundary_polys: if boundary_polys:
biggest = max(boundary_polys, key=lambda poly: (max(p[0] for p in poly) - min(p[0] for p in poly)) * biggest = max(
(max(p[1] for p in poly) - min(p[1] for p in poly))) boundary_polys,
floors["SITE"] = {"name": "场地地面", "z": -0.45, "height": 0.45, key=lambda poly: (max(p[0] for p in poly) - min(p[0] for p in poly))
"bounds": [0, 0, x1 - x0, y1 - y0], "source_file": "site", * (max(p[1] for p in poly) - min(p[1] for p in poly)),
"segments": {}, "footprint": {"source": "用地红线", "polygons": [biggest]}} )
floors["ROADS"] = {"name": "道路/车位", "z": 0.02, "height": 0.05, floors["SITE"] = {
"bounds": [0, 0, x1 - x0, y1 - y0], "source_file": "site", "name": "场地地面",
"segments": segs["ROADS"]} "z": -0.45,
"height": 0.45,
"bounds": [0, 0, x1 - x0, y1 - y0],
"source_file": "site",
"segments": {},
"footprint": {"source": "用地红线", "polygons": [biggest]},
}
floors["ROADS"] = {
"name": "道路/车位",
"z": 0.02,
"height": 0.05,
"bounds": [0, 0, x1 - x0, y1 - y0],
"source_file": "site",
"segments": segs["ROADS"],
}
if segs["FENCE"]: if segs["FENCE"]:
floors["FENCE"] = {"name": "围墙", "z": 0.0, "height": 1.8, floors["FENCE"] = {
"bounds": [0, 0, x1 - x0, y1 - y0], "source_file": "site", "name": "围墙",
"segments": segs["FENCE"]} "z": 0.0,
"height": 1.8,
"bounds": [0, 0, x1 - x0, y1 - y0],
"source_file": "site",
"segments": segs["FENCE"],
}
if trees: if trees:
tree_segs = [] tree_segs = []
for p in trees: for p in trees:
lp = local(p) lp = local(p)
tree_segs.append({"start": [lp[0] - 0.3, lp[1]], "end": [lp[0] + 0.3, lp[1]], tree_segs.append(
"width": 2.4, "layer": "行道树", "source_type": "TREE"}) {
floors["TREES"] = {"name": "行道树", "z": 0.0, "height": 3.5, "start": [lp[0] - 0.3, lp[1]],
"bounds": [0, 0, x1 - x0, y1 - y0], "source_file": "site", "end": [lp[0] + 0.3, lp[1]],
"segments": {"trees": tree_segs}} "width": 2.4,
"layer": "行道树",
"source_type": "TREE",
}
)
floors["TREES"] = {
"name": "行道树",
"z": 0.0,
"height": 3.5,
"bounds": [0, 0, x1 - x0, y1 - y0],
"source_file": "site",
"segments": {"trees": tree_segs},
}
# de-duplicate massings (copies drawn twice) and name them by nearest label # de-duplicate massings (copies drawn twice) and name them by nearest label
kept = [] kept = []
for m in sorted(massings, key=lambda m: -(m["w"] * m["h"])): for m in sorted(massings, key=lambda m: -(m["w"] * m["h"])):
if any(abs(m["c"][0] - k["c"][0]) < 2 and abs(m["c"][1] - k["c"][1]) < 2 and if any(
abs(m["w"] - k["w"]) < 2 and abs(m["h"] - k["h"]) < 2 for k in kept): abs(m["c"][0] - k["c"][0]) < 2
and abs(m["c"][1] - k["c"][1]) < 2
and abs(m["w"] - k["w"]) < 2
and abs(m["h"] - k["h"]) < 2
for k in kept
):
continue continue
kept.append(m) kept.append(m)
for idx, m in enumerate(kept, start=1): for idx, m in enumerate(kept, start=1):
@@ -245,22 +327,37 @@ def main() -> int:
if any(key in name for key in MASSING_SKIP): if any(key in name for key in MASSING_SKIP):
continue continue
height = next((hh for key, hh in MASSING_HEIGHTS if key in name), DEFAULT_MASSING_H) height = next((hh for key, hh in MASSING_HEIGHTS if key in name), DEFAULT_MASSING_H)
wsegs = [{"start": a, "end": b, "width": 0.25, "layer": "massing", "source_type": "SITE"} wsegs = [
for a, b in zip(m["pts"], m["pts"][1:])] {"start": a, "end": b, "width": 0.25, "layer": "massing", "source_type": "SITE"}
for a, b in zip(m["pts"], m["pts"][1:])
]
if m["pts"][0] != m["pts"][-1]: if m["pts"][0] != m["pts"][-1]:
wsegs.append({"start": m["pts"][-1], "end": m["pts"][0], "width": 0.25, wsegs.append(
"layer": "massing", "source_type": "SITE"}) {"start": m["pts"][-1], "end": m["pts"][0], "width": 0.25, "layer": "massing", "source_type": "SITE"}
floors[f"CTX{idx}"] = {"name": f"体量-{name}", "z": 0.0, "height": height, )
"bounds": [0, 0, x1 - x0, y1 - y0], "source_file": "site", floors[f"CTX{idx}"] = {
"segments": {"walls": wsegs}, "name": f"体量-{name}",
"footprint": {"source": "site_outline", "polygons": [m["pts"]]}} "z": 0.0,
"height": height,
"bounds": [0, 0, x1 - x0, y1 - y0],
"source_file": "site",
"segments": {"walls": wsegs},
"footprint": {"source": "site_outline", "polygons": [m["pts"]]},
}
out = {"floors": floors, out = {"floors": floors, "categories": {"trees": {"label": "行道树", "color": "#3e7d4f"}}}
"categories": {"trees": {"label": "行道树", "color": "#3e7d4f"}}}
Path(args.out).write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8") Path(args.out).write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
print(json.dumps({"out": args.out, print(
"floors": {k: {c: len(s) for c, s in v.get("segments", {}).items()} for k, v in floors.items()}, json.dumps(
"trees": len(trees), "massings": len(kept)}, ensure_ascii=False)) {
"out": args.out,
"floors": {k: {c: len(s) for c, s in v.get("segments", {}).items()} for k, v in floors.items()},
"trees": len(trees),
"massings": len(kept),
},
ensure_ascii=False,
)
)
return 0 return 0

File diff suppressed because it is too large Load Diff

634
scripts/verify_delivery.py Normal file
View File

@@ -0,0 +1,634 @@
#!/usr/bin/env python3
"""Strict, machine-readable verification for final CAD showcase delivery."""
from __future__ import annotations
import argparse
import base64
import gzip
import hashlib
import json
import re
import statistics
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
import showcase_schema
from delivery_waivers import apply_waivers, parse_waivers
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def add_check(checks: list[dict[str, Any]], name: str, status: str, detail: str, **data) -> None:
checks.append({"name": name, "status": status, "detail": detail, **data})
def inspect_glb(path: Path, budget_mb: float, checks: list[dict[str, Any]]) -> dict[str, Any] | None:
if not path.exists() or path.stat().st_size == 0:
add_check(checks, f"glb:{path.name}", "FAIL", f"Missing or empty GLB: {path}")
return None
with path.open("rb") as stream:
header = stream.read(4)
if header != b"glTF":
add_check(checks, f"glb:{path.name}", "FAIL", "File does not have a GLB header")
return None
try:
from pygltflib import GLTF2
model = GLTF2().load(str(path))
nodes = [node.name or "" for node in model.nodes]
named = [name for name in nodes if "__" in name]
meshes = len(model.meshes or [])
primitives = sum(len(mesh.primitives) for mesh in model.meshes or [])
if meshes == 0 or primitives == 0:
add_check(checks, f"glb:{path.name}", "FAIL", "GLB contains no mesh primitives")
return None
if not named:
add_check(checks, f"glb:{path.name}:names", "FAIL", "No <floor>__<category> node names found")
else:
add_check(checks, f"glb:{path.name}:names", "PASS", f"{len(named)} named node(s)")
extensions = list(model.extensionsUsed or [])
detail = f"{meshes} meshes, {primitives} primitives, {path.stat().st_size / 1024 / 1024:.2f} MB"
status = "PASS" if path.stat().st_size <= budget_mb * 1024 * 1024 else "FAIL"
if status == "FAIL":
detail += f"; exceeds {budget_mb:.2f} MB budget"
add_check(checks, f"glb:{path.name}:structure", status, detail)
return {
"path": str(path),
"bytes": path.stat().st_size,
"sha256": sha256(path),
"meshes": meshes,
"primitives": primitives,
"nodes": named,
"extensions": extensions,
}
except Exception as exc:
add_check(checks, f"glb:{path.name}", "FAIL", f"GLB parser failed: {exc}")
return None
def inspect_render(path: Path, checks: list[dict[str, Any]]) -> None:
if not path.exists() or path.stat().st_size == 0:
add_check(checks, f"render:{path.name}", "FAIL", f"Missing render: {path}")
return
try:
from PIL import Image, ImageStat
image = Image.open(path).convert("RGB")
sample = image.resize((128, 128))
stat = ImageStat.Stat(sample)
spread = max(stat.var)
pixels = list(sample.getdata())
border = []
for index in range(128):
border.extend((sample.getpixel((index, 0)), sample.getpixel((index, 127))))
for index in range(1, 127):
border.extend((sample.getpixel((0, index)), sample.getpixel((127, index))))
background = tuple(int(statistics.median(pixel[channel] for pixel in border)) for channel in range(3))
foreground = [max(abs(pixel[channel] - background[channel]) for channel in range(3)) > 12 for pixel in pixels]
occupancy = sum(foreground) / len(foreground)
xs = [index % 128 for index, present in enumerate(foreground) if present]
ys = [index // 128 for index, present in enumerate(foreground) if present]
bbox_w = max(xs) - min(xs) + 1 if xs else 0
bbox_h = max(ys) - min(ys) + 1 if ys else 0
def luminance(pixel: tuple[int, int, int]) -> float:
return pixel[0] * 0.2126 + pixel[1] * 0.7152 + pixel[2] * 0.0722
transitions = 0
comparisons = 0
for y in range(128):
for x in range(128):
here = luminance(sample.getpixel((x, y)))
if x + 1 < 128:
transitions += abs(here - luminance(sample.getpixel((x + 1, y)))) > 45
comparisons += 1
if y + 1 < 128:
transitions += abs(here - luminance(sample.getpixel((x, y + 1)))) > 45
comparisons += 1
edge_ratio = transitions / comparisons
status = (
"PASS"
if image.width >= 320
and image.height >= 240
and spread > 2.0
and 0.01 <= occupancy <= 0.95
and bbox_w >= 24
and bbox_h >= 24
and edge_ratio < 0.45
else "FAIL"
)
add_check(
checks,
f"render:{path.name}",
status,
(
f"{image.width}x{image.height}, variance {spread:.2f}, "
f"foreground {occupancy:.1%}, bbox {bbox_w}x{bbox_h}/128, edge ratio {edge_ratio:.3f}"
),
)
except Exception as exc:
add_check(checks, f"render:{path.name}", "FAIL", f"Image inspection failed: {exc}")
def inspect_web(web_dir: Path, checks: list[dict[str, Any]]) -> None:
required = [
"index.html",
"app.js",
"styles.css",
"model.glb",
"model_metadata.json",
"node_modules/three/build/three.module.js",
"node_modules/lucide/dist/umd/lucide.js",
]
missing = [name for name in required if not (web_dir / name).exists()]
if missing:
add_check(checks, "web:files", "FAIL", "Missing Web files: " + ", ".join(missing))
return
text = (web_dir / "index.html").read_text(encoding="utf-8") + (web_dir / "app.js").read_text(encoding="utf-8")
placeholders = sorted(set(re.findall(r"\{\{[^}]+\}\}", text)))
if placeholders:
add_check(checks, "web:placeholders", "FAIL", f"Unexpanded placeholders: {placeholders}")
else:
add_check(checks, "web:placeholders", "PASS", "Template placeholders expanded")
features = ("window.__renders", "invalidate(", "DRACOLoader", "restoreStateFromHash", "switchVariant")
absent = [feature for feature in features if feature not in text]
add_check(
checks,
"web:features",
"FAIL" if absent else "PASS",
"Missing features: " + ", ".join(absent) if absent else "Required viewer features present",
)
try:
metadata = json.loads((web_dir / "model_metadata.json").read_text(encoding="utf-8"))
missing_variants = []
for item in metadata.get("model_variants", []):
file_name = item.get("file")
if not isinstance(file_name, str) or not file_name or not (web_dir / file_name).is_file():
missing_variants.append(file_name or "<missing file>")
add_check(
checks,
"web:variants",
"FAIL" if missing_variants else "PASS",
"Missing variant assets: " + ", ".join(missing_variants)
if missing_variants
else "Variant assets accounted for",
)
except Exception as exc:
add_check(checks, "web:metadata", "FAIL", f"Metadata parse failed: {exc}")
def inspect_offline(path: Path, checks: list[dict[str, Any]]) -> None:
if not path.exists():
add_check(checks, "offline:viewer", "FAIL", f"Offline viewer missing: {path}")
return
text = path.read_text(encoding="utf-8")
match = re.search(r'const GLB_B64="([A-Za-z0-9+/=]+)";', text)
if not match:
add_check(checks, "offline:payload", "FAIL", "Embedded GLB payload not found")
return
try:
payload = gzip.decompress(base64.b64decode(match.group(1)))
if payload[:4] != b"glTF":
raise ValueError("decoded payload is not a GLB")
add_check(checks, "offline:payload", "PASS", f"Decoded {len(payload)} GLB bytes")
except Exception as exc:
add_check(checks, "offline:payload", "FAIL", f"Embedded payload decode failed: {exc}")
WEB_BROWSER_CHECKS = {
"desktop:viewport",
"desktop:#floor-controls",
"desktop:#category-controls",
"desktop:#explode",
"desktop:#section",
"desktop:#snapshot",
"desktop:idle-render",
"mobile:viewport",
"mobile:#floor-controls",
"mobile:#category-controls",
"mobile:#explode",
"mobile:#section",
"mobile:#snapshot",
"mobile:idle-render",
}
OFFLINE_BROWSER_CHECKS = {
"offline:viewport",
"offline:model-ready",
"offline:canvas",
"offline:render",
}
def inspect_browser_report(path: Path, checks: list[dict[str, Any]], name: str = "browser:smoke") -> None:
try:
report = json.loads(path.read_text(encoding="utf-8"))
report_checks = report.get("checks")
if not isinstance(report_checks, list) or not report_checks:
raise ValueError("checks must be a non-empty list")
by_name: dict[str, dict[str, Any]] = {}
for item in report_checks:
if not isinstance(item, dict) or not isinstance(item.get("name"), str):
raise ValueError("every browser check must be an object with a name")
if item["name"] in by_name:
raise ValueError(f"duplicate browser check: {item['name']}")
by_name[item["name"]] = item
required = OFFLINE_BROWSER_CHECKS if name == "offline:browser-smoke" else WEB_BROWSER_CHECKS
missing = sorted(required - set(by_name))
failed = sorted(item_name for item_name, item in by_name.items() if item.get("status") != "PASS")
if missing:
raise ValueError("missing required checks: " + ", ".join(missing))
if failed:
raise ValueError("non-PASS checks: " + ", ".join(failed))
expected_viewports = (
{"offline:viewport": "1440x900 expected 1440x900"}
if name == "offline:browser-smoke"
else {
"desktop:viewport": "1440x900 expected 1440x900",
"mobile:viewport": "390x844 expected 390x844",
}
)
for check_name, expected_detail in expected_viewports.items():
if by_name[check_name].get("detail") != expected_detail:
raise ValueError(f"{check_name} has untrusted viewport evidence: {by_name[check_name].get('detail')!r}")
for error_key in ("console_errors", "page_errors", "failed_requests"):
if not isinstance(report.get(error_key), list):
raise ValueError(f"{error_key} must be a list")
passed = (
report.get("status") == "PASS"
and not report.get("console_errors")
and not report.get("page_errors")
and not report.get("failed_requests")
)
detail = f"validated {len(required)}/{len(required)} required checks; " + (
report.get("detail") or json.dumps(report, ensure_ascii=False)[:300]
)
add_check(checks, name, "PASS" if passed else "FAIL", detail)
except Exception as exc:
add_check(checks, name, "FAIL", f"Browser report invalid: {exc}")
def inspect_audit(path: Path, checks: list[dict[str, Any]]) -> None:
try:
report = json.loads(path.read_text(encoding="utf-8"))
gates = report.get("gates")
if not isinstance(gates, list) or not gates:
raise ValueError("audit has no gates")
for gate in gates:
status = str(gate.get("status", "FAIL"))
if status not in {"PASS", "WARN", "SKIP", "FAIL", "NOT_APPLICABLE"}:
status = "FAIL"
add_check(
checks,
f"audit:{gate.get('name', 'unnamed')}",
status,
str(gate.get("detail", "Audit gate has no detail")),
)
except Exception as exc:
add_check(checks, "audit:report", "FAIL", f"Extraction audit invalid: {exc}")
def verifiable_model_artifact(path: Path) -> tuple[bool, str]:
"""Reject scope ledgers backed only by arbitrary non-empty files."""
try:
suffix = path.suffix.lower()
if suffix == ".glb":
from pygltflib import GLTF2
model = GLTF2().load(str(path))
primitives = sum(len(mesh.primitives) for mesh in model.meshes or [])
if primitives <= 0:
return False, "GLB has no mesh primitives"
return True, f"GLB with {primitives} primitive(s)"
if suffix == ".blend":
if path.read_bytes()[:7] != b"BLENDER":
return False, "invalid Blender header"
return True, "Blender scene"
if suffix == ".json":
document = json.loads(path.read_text(encoding="utf-8"))
showcase_schema.validate_spec(document)
return True, f"building spec with {len(document['floors'])} floor(s)"
return False, f"unsupported model artifact type {suffix or '<none>'}"
except Exception as exc:
return False, str(exc)
def verifiable_site_artifact(path: Path) -> tuple[bool, str]:
model_ok, model_detail = verifiable_model_artifact(path)
if model_ok:
return True, model_detail
try:
from PIL import Image
with Image.open(path) as image:
image.verify()
if image.width < 320 or image.height < 240:
return False, f"site image too small: {image.width}x{image.height}"
return True, f"site image {image.width}x{image.height}"
except Exception:
return False, model_detail
def inspect_scope(path: Path, checks: list[dict[str, Any]]) -> None:
"""Validate a single-building/campus scope ledger against real artifacts."""
try:
scope = json.loads(path.read_text(encoding="utf-8"))
if scope.get("scope_version") != 1:
raise ValueError("scope_version must be 1")
mode = scope.get("mode")
if mode not in {"single", "campus"}:
raise ValueError("mode must be single or campus")
requested = scope.get("requested")
buildings = scope.get("buildings")
if (
not isinstance(requested, list)
or not requested
or not all(isinstance(item, str) and item for item in requested)
):
raise ValueError("requested must be a non-empty list of building IDs")
if len(set(requested)) != len(requested):
raise ValueError("requested contains duplicate building IDs")
if mode == "single" and len(requested) != 1:
raise ValueError("single mode requires exactly one requested building ID")
if not isinstance(buildings, list):
raise ValueError("buildings must be a list")
by_id: dict[str, dict[str, Any]] = {}
for item in buildings:
building_id = str(item.get("id", ""))
if not building_id or building_id in by_id:
raise ValueError(f"missing or duplicate building id: {building_id!r}")
by_id[building_id] = item
missing = [item for item in requested if item not in by_id]
unexpected = sorted(set(by_id) - set(requested))
if missing or unexpected:
add_check(
checks,
"scope:inventory",
"FAIL",
(
("Requested buildings missing from ledger: " + ", ".join(missing) if missing else "")
+ ("; " if missing and unexpected else "")
+ ("Unrequested buildings in ledger: " + ", ".join(unexpected) if unexpected else "")
),
)
else:
add_check(
checks, "scope:inventory", "PASS", f"All {len(requested)} requested building(s) are in the ledger"
)
for building_id in requested:
item = by_id.get(building_id)
if not item:
continue
status = item.get("status")
reason = str(item.get("reason", "")).strip()
artifacts = item.get("artifacts", [])
if status == "BLOCKED":
add_check(
checks,
f"scope:building:{building_id}",
"WARN" if reason else "FAIL",
reason or "BLOCKED building has no reason",
)
continue
if status != "PASS":
add_check(checks, f"scope:building:{building_id}", "FAIL", f"Invalid status: {status!r}")
continue
if not isinstance(artifacts, list) or not artifacts:
add_check(checks, f"scope:building:{building_id}", "FAIL", "PASS building has no artifacts")
continue
missing_artifacts = []
verified_models = []
invalid_models = []
for artifact in artifacts:
artifact_path = Path(str(artifact))
if not artifact_path.is_absolute():
artifact_path = path.parent / artifact_path
if not artifact_path.exists() or (artifact_path.is_file() and artifact_path.stat().st_size == 0):
missing_artifacts.append(str(artifact))
continue
verified, detail = verifiable_model_artifact(artifact_path)
if verified:
verified_models.append(f"{artifact}: {detail}")
else:
invalid_models.append(f"{artifact}: {detail}")
failed = bool(missing_artifacts or not verified_models)
add_check(
checks,
f"scope:building:{building_id}",
"FAIL" if failed else "PASS",
"Missing artifacts: " + ", ".join(missing_artifacts)
if missing_artifacts
else (
f"{len(verified_models)} verifiable model artifact(s)"
if verified_models
else "No verifiable GLB/BLEND/building-spec artifact; rejected: " + "; ".join(invalid_models)
),
)
site = scope.get("site", {})
if mode == "campus":
site_status = site.get("status") if isinstance(site, dict) else None
if site_status == "BLOCKED":
reason = str(site.get("reason", "")).strip()
add_check(checks, "scope:site", "WARN" if reason else "FAIL", reason or "Campus site is blocked")
elif site_status != "PASS":
add_check(checks, "scope:site", "FAIL", "Campus scope requires site.status=PASS or BLOCKED")
else:
artifacts = site.get("artifacts", [])
missing_site = []
verified_site = []
for artifact in artifacts if isinstance(artifacts, list) else []:
artifact_path = Path(str(artifact))
if not artifact_path.is_absolute():
artifact_path = path.parent / artifact_path
if not artifact_path.exists() or (artifact_path.is_file() and artifact_path.stat().st_size == 0):
missing_site.append(str(artifact))
continue
verified, detail = verifiable_site_artifact(artifact_path)
if verified:
verified_site.append(f"{artifact}: {detail}")
if not artifacts or missing_site or not verified_site:
add_check(
checks,
"scope:site",
"FAIL",
"Campus site has no artifacts"
if not artifacts
else (
"Missing site artifacts: " + ", ".join(missing_site)
if missing_site
else "Campus site has no verifiable model or image artifact"
),
)
else:
add_check(checks, "scope:site", "PASS", f"{len(verified_site)} verified site artifact(s)")
except Exception as exc:
add_check(checks, "scope:manifest", "FAIL", f"Scope manifest invalid: {exc}")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--spec", required=True)
parser.add_argument("--source-report", required=True)
parser.add_argument("--glb", nargs="*", default=[])
parser.add_argument("--variants-manifest")
parser.add_argument("--web-dir")
parser.add_argument("--offline-viewer")
parser.add_argument("--offline-browser-report")
parser.add_argument("--render", nargs="*", default=[])
parser.add_argument("--audit")
parser.add_argument("--require-audit", action="store_true")
parser.add_argument("--scope-manifest")
parser.add_argument("--require-scope-manifest", action="store_true")
parser.add_argument("--browser-report")
parser.add_argument("--require-browser-report", action="store_true")
parser.add_argument(
"--waiver",
action="append",
default=[],
metavar="CHECK=REASON",
help="Explicitly acknowledge one WARN/SKIP check with a non-empty reason",
)
parser.add_argument("--budget-mb", type=float, default=25.0)
parser.add_argument("--evidence-out", default="evidence_manifest.json")
args = parser.parse_args()
checks: list[dict[str, Any]] = []
artifacts: list[dict[str, Any]] = []
try:
waivers = parse_waivers(args.waiver)
except ValueError as exc:
print(f"GATE FAIL [waiver]: {exc}", file=sys.stderr)
return 3
try:
source_report = json.loads(Path(args.source_report).read_text(encoding="utf-8"))
showcase_schema.validate_source_report(source_report)
source_gate = source_report["gate"]
source_status = str(source_gate.get("status", "FAIL"))
add_check(
checks,
"cad_source_report",
source_status,
(
f"Source gate {source_status}; {len(source_report['files'])} inspected DXF file(s)"
+ (f"; partial reason: {source_gate.get('partial_reason')}" if source_status == "WARN" else "")
),
)
except Exception as exc:
add_check(checks, "cad_source_report", "FAIL", str(exc))
spec_path = Path(args.spec)
try:
spec = json.loads(spec_path.read_text(encoding="utf-8"))
showcase_schema.validate_spec(spec)
add_check(checks, "building_spec", "PASS", f"Schema v{spec['schema_version']}; {len(spec['floors'])} floor(s)")
except Exception as exc:
add_check(checks, "building_spec", "FAIL", str(exc))
glb_paths = [Path(item) for item in args.glb]
if args.variants_manifest:
manifest_path = Path(args.variants_manifest)
try:
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
showcase_schema.validate_manifest(manifest)
add_check(checks, "variants_manifest", "PASS", f"{len(manifest['variants'])} variant(s)")
for variant in manifest["variants"]:
source = Path(variant["source_glb"])
if not source.is_absolute():
source = manifest_path.parent / source
glb_paths.append(source)
spec_file = Path(variant["spec"])
if not spec_file.is_absolute():
spec_file = manifest_path.parent / spec_file
variant_spec = json.loads(spec_file.read_text(encoding="utf-8"))
showcase_schema.validate_spec(variant_spec)
metadata_file = Path(variant["metadata"])
if not metadata_file.is_absolute():
metadata_file = manifest_path.parent / metadata_file
metadata = json.loads(metadata_file.read_text(encoding="utf-8"))
if metadata.get("metadata_version") != 1:
raise ValueError(f"{metadata_file}: metadata_version must be 1")
if metadata.get("schema_version") != variant_spec.get("schema_version"):
raise ValueError(f"{metadata_file}: schema_version does not match {spec_file}")
except Exception as exc:
add_check(checks, "variants_manifest", "FAIL", str(exc))
seen = set()
for path in glb_paths:
resolved = path.resolve()
if resolved in seen:
continue
seen.add(resolved)
artifact = inspect_glb(path, args.budget_mb, checks)
if artifact:
artifacts.append(artifact)
if not glb_paths:
add_check(checks, "glb", "FAIL", "No GLB supplied")
for path in args.render:
inspect_render(Path(path), checks)
if not args.render:
add_check(checks, "render", "FAIL", "At least one inspected render is required")
if args.web_dir:
inspect_web(Path(args.web_dir), checks)
if args.audit:
inspect_audit(Path(args.audit), checks)
elif args.require_audit:
add_check(checks, "audit:report", "FAIL", "Required extraction audit was not supplied")
if args.scope_manifest:
inspect_scope(Path(args.scope_manifest), checks)
elif args.require_scope_manifest:
add_check(checks, "scope:manifest", "FAIL", "Required scope manifest was not supplied")
if args.offline_viewer:
inspect_offline(Path(args.offline_viewer), checks)
if args.offline_browser_report:
inspect_browser_report(Path(args.offline_browser_report), checks, "offline:browser-smoke")
else:
add_check(
checks,
"offline:browser-smoke",
"SKIP",
"Offline viewer has no real file:// browser smoke report",
)
if args.browser_report:
inspect_browser_report(Path(args.browser_report), checks)
elif args.web_dir or args.require_browser_report:
add_check(checks, "browser:smoke", "SKIP", "Formal Web delivery has no browser smoke report")
apply_waivers(checks, waivers)
status = (
"FAIL"
if any(item["status"] == "FAIL" for item in checks)
else "BLOCKED"
if any(item["status"] in {"WARN", "SKIP"} for item in checks)
else "PASS"
)
evidence = {
"evidence_version": 1,
"generated_at": datetime.now(timezone.utc).isoformat(),
"status": status,
"waivers": [{"check": name, "reason": reason} for name, reason in sorted(waivers.items())],
"checks": checks,
"artifacts": artifacts,
}
out = Path(args.evidence_out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(evidence, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps({"status": status, "evidence": str(out), "checks": len(checks)}, ensure_ascii=False))
if status != "PASS":
for item in checks:
if item["status"] in {"FAIL", "WARN", "SKIP"}:
print(f"GATE {status} [{item['name']}]: {item['detail']}", file=sys.stderr)
return 3
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -14,10 +14,15 @@ Usage:
[--out verify_previews.png] \ [--out verify_previews.png] \
[--budget-mb 0.6] [--budget-mb 0.6]
""" """
from __future__ import annotations from __future__ import annotations
import argparse, json, math, sys import argparse
import json
import sys
from pathlib import Path from pathlib import Path
import showcase_schema
def load_spec(path: Path) -> dict: def load_spec(path: Path) -> dict:
return json.loads(path.read_text(encoding="utf-8")) return json.loads(path.read_text(encoding="utf-8"))
@@ -44,8 +49,9 @@ def glb_stats(path: Path):
} }
def text_report(spec: dict, glbs: list[Path], budget_mb: float) -> str: def text_report(spec: dict, glbs: list[Path], budget_mb: float) -> tuple[str, bool]:
lines = ["# Showcase verification", ""] lines = ["# Showcase verification", ""]
failed = False
floors = spec.get("floors", {}) floors = spec.get("floors", {})
lines.append(f"{'floor':7} {'z':>6} {'h':>4} {'fp_area':>8} {'caps':>4} segments") lines.append(f"{'floor':7} {'z':>6} {'h':>4} {'fp_area':>8} {'caps':>4} segments")
for k, f in floors.items(): for k, f in floors.items():
@@ -55,7 +61,7 @@ def text_report(spec: dict, glbs: list[Path], budget_mb: float) -> str:
merged = sum(1 for s in f.get("segments", {}).get("glazing", []) if s.get("source_type") == "merged") merged = sum(1 for s in f.get("segments", {}).get("glazing", []) if s.get("source_type") == "merged")
glz = len(f.get("segments", {}).get("glazing", [])) glz = len(f.get("segments", {}).get("glazing", []))
cont = f" glazing_continuous={merged}/{glz}" if glz else "" 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(f"{k:7} {f.get('z', 0):>6.1f} {f.get('height', 0):>4.1f} {str(fp):>8} {caps:>4} {segs}{cont}")
lines.append("") lines.append("")
if glbs: if glbs:
lines.append("## GLB budget") lines.append("## GLB budget")
@@ -64,38 +70,38 @@ def text_report(spec: dict, glbs: list[Path], budget_mb: float) -> str:
st = glb_stats(p) st = glb_stats(p)
mb = st["bytes"] / 1024 / 1024 mb = st["bytes"] / 1024 / 1024
ok = "OK" if st["bytes"] <= budget else "OVER" ok = "OK" if st["bytes"] <= budget else "OVER"
extra = f" verts={st.get('vertices','?')} draco={st.get('draco','?')}" failed = failed or st["bytes"] > budget or not st.get("meshes")
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}") lines.append(f" {st['file']:20} {mb:6.2f} MB [{ok} vs {budget_mb}MB]{extra}")
return "\n".join(lines) return "\n".join(lines), failed
def render_previews(spec: dict, out: Path) -> bool: def render_previews(spec: dict, out: Path) -> bool:
try: try:
import numpy as np # noqa import numpy as np # noqa
import matplotlib import matplotlib
matplotlib.use("Agg") matplotlib.use("Agg")
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
except Exception: except Exception:
return False return False
floors = spec["floors"] 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)) fig = plt.figure(figsize=(22, 7))
# front elevation (X vs Z), side elevation (Y vs Z), plan (X vs Y) # 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)"), for sub, (ax_h, ax_v, title) in enumerate(
(1, 2, "Side elevation (Y-Z)"), [(0, 2, "Front elevation (X-Z)"), (1, 2, "Side elevation (Y-Z)"), (0, 1, "Plan overlay (X-Y)")]
(0, 1, "Plan overlay (X-Y)")]): ):
ax = fig.add_subplot(1, 3, sub + 1) ax = fig.add_subplot(1, 3, sub + 1)
for k, f in floors.items(): for k, f in floors.items():
z = float(f["z"]); h = float(f.get("height", 4.2)) z = float(f["z"])
h = float(f.get("height", 4.2))
for cat, col in [("walls", "#8a7f6a"), ("columns", "#f58a1f"), ("glazing", "#5aa9c9")]: for cat, col in [("walls", "#8a7f6a"), ("columns", "#f58a1f"), ("glazing", "#5aa9c9")]:
for s in f.get("segments", {}).get(cat, []): for s in f.get("segments", {}).get(cat, []):
a, b = s["start"], s["end"] a, b = s["start"], s["end"]
p = [a, b]
if ax_v == 2: # elevation: vertical extent z..z+h at midpoint of horizontal axis if ax_v == 2: # elevation: vertical extent z..z+h at midpoint of horizontal axis
ah0, ah1 = a[ax_h], b[ax_h] 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) ax.fill([ah0, ah1, ah1, ah0], [z, z, z + h, z + h], color=col, lw=0, alpha=0.12)
ax.plot([ah0, ah1], [z + h, z + h], color=col, lw=0.2, alpha=0.5)
else: # plan 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.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) ax.set_title(title)
@@ -112,11 +118,20 @@ def main() -> int:
ap.add_argument("--glb", nargs="*", default=[]) ap.add_argument("--glb", nargs="*", default=[])
ap.add_argument("--out", default="verify_previews.png") ap.add_argument("--out", default="verify_previews.png")
ap.add_argument("--budget-mb", type=float, default=0.6) ap.add_argument("--budget-mb", type=float, default=0.6)
ap.add_argument("--strict", action="store_true", help="Exit 3 on invalid GLB budget/structure or missing preview")
a = ap.parse_args() a = ap.parse_args()
spec = load_spec(Path(a.spec)) spec = showcase_schema.normalize_spec(load_spec(Path(a.spec)))
print(text_report(spec, [Path(p) for p in a.glb], a.budget_mb)) try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
report, failed = text_report(spec, [Path(p) for p in a.glb], a.budget_mb)
print(report)
ok = render_previews(spec, Path(a.out)) ok = render_previews(spec, Path(a.out))
print(f"\npreviews: {'written ' + a.out if ok else 'skipped (matplotlib not installed)'}") print(f"\npreviews: {'written ' + a.out if ok else 'skipped (matplotlib not installed)'}")
if a.strict and (failed or not ok):
return 3
return 0 return 0

119
scripts/web_smoke_test.mjs Normal file
View File

@@ -0,0 +1,119 @@
#!/usr/bin/env node
/** Browser smoke test for the served Three.js showcase viewer. */
import fs from "node:fs/promises";
import path from "node:path";
function arg(name, fallback = null) {
const index = process.argv.indexOf(name);
return index >= 0 && process.argv[index + 1] ? process.argv[index + 1] : fallback;
}
const url = arg("--url");
const out = arg("--out", "browser_smoke_report.json");
const shots = arg("--screenshots-dir", "browser_smoke");
const thumbnailOut = arg("--thumbnail-out");
if (!url) {
throw new Error("Usage: web_smoke_test.mjs --url http://127.0.0.1:8188 --out report.json");
}
let chromium;
try {
({ chromium } = await import("playwright"));
} catch (error) {
throw new Error("Missing Playwright. Install with: npm install -D playwright && npx playwright install chromium", { cause: error });
}
await fs.mkdir(shots, { recursive: true });
if (thumbnailOut) await fs.mkdir(path.dirname(thumbnailOut), { recursive: true });
const browser = await chromium.launch({ headless: true });
const consoleErrors = [];
const pageErrors = [];
const failedRequests = [];
const checks = [];
async function inspect(viewport, name) {
const page = await browser.newPage({ viewport });
page.on("console", (message) => {
if (message.type() === "error") consoleErrors.push(message.text());
});
page.on("pageerror", (error) => pageErrors.push(error.message));
page.on("requestfailed", (request) => failedRequests.push(`${request.url()} ${request.failure()?.errorText || "failed"}`));
await page.goto(url, { waitUntil: "networkidle", timeout: 60000 });
// The loading overlay starts hidden, then becomes visible while metadata and
// the first GLB load. Waiting for "hidden" alone can pass before loading has
// even started. A rendered floor control is the first stable readiness fact.
await page.waitForSelector("#floor-controls label", { state: "visible", timeout: 60000 });
await page.waitForSelector("#loading", { state: "hidden", timeout: 60000 });
const actualViewport = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
const viewportMatches = actualViewport.width === viewport.width && actualViewport.height === viewport.height;
checks.push({
name: `${name}:viewport`,
status: viewportMatches ? "PASS" : "FAIL",
detail: `${actualViewport.width}x${actualViewport.height} expected ${viewport.width}x${viewport.height}`,
});
const selectors = ["#floor-controls", "#category-controls", "#explode", "#section", "#snapshot"];
for (const selector of selectors) {
const visible = await page.locator(selector).isVisible();
checks.push({ name: `${name}:${selector}`, status: visible ? "PASS" : "FAIL" });
}
await page.waitForTimeout(1200);
const before = await page.evaluate(() => window.__renders || 0);
await page.waitForTimeout(1500);
const after = await page.evaluate(() => window.__renders || 0);
checks.push({ name: `${name}:idle-render`, status: after === before ? "PASS" : "FAIL", detail: `${before}->${after}` });
if (name === "desktop") {
const floorLabels = page.locator("#floor-controls label");
const floorLabelCount = await floorLabels.count();
if (floorLabelCount > 0) {
const floorLabel = floorLabels.nth(0);
const label = (await floorLabel.innerText()).trim();
await floorLabel.click();
await page.waitForTimeout(150);
const hashWritten = await page.evaluate(() => window.location.hash.length > 1);
await floorLabel.click();
await page.waitForTimeout(150);
checks.push({
name: "desktop:floor-state",
status: hashWritten ? "PASS" : "FAIL",
detail: hashWritten ? `Floor label serialized to URL hash: ${label}` : `URL hash was not written: ${label}`,
});
}
}
if (name === "desktop" && thumbnailOut) {
// Export the renderer itself. Cropping a page screenshot retains UI panels
// and makes Agents guess at a dark-background crop; the canvas is already
// the canonical customer model view. Zoom out a fixed amount so the white
// model remains a compact subject on the dark exhibit background.
const canvas = page.locator("#scene");
await canvas.hover();
await page.mouse.wheel(0, 1800);
await page.waitForTimeout(500);
const dataUrl = await canvas.evaluate((element) => element.toDataURL("image/png"));
await fs.writeFile(thumbnailOut, Buffer.from(dataUrl.split(",", 2)[1], "base64"));
}
await page.screenshot({ path: path.join(shots, `${name}.png`), fullPage: true });
await page.close();
}
try {
await inspect({ width: 1440, height: 900 }, "desktop");
await inspect({ width: 390, height: 844 }, "mobile");
} finally {
await browser.close();
}
const failedChecks = checks.filter((item) => item.status === "FAIL");
const status = failedChecks.length || consoleErrors.length || pageErrors.length || failedRequests.length ? "FAIL" : "PASS";
const report = {
status,
detail: `${checks.length - failedChecks.length}/${checks.length} checks passed`,
url,
checks,
console_errors: consoleErrors,
page_errors: pageErrors,
failed_requests: failedRequests,
};
await fs.writeFile(out, JSON.stringify(report, null, 2));
process.stdout.write(`${JSON.stringify({ status, report: out })}\n`);
if (status === "FAIL") process.exitCode = 3;

View File

@@ -26,9 +26,13 @@ from __future__ import annotations
import argparse import argparse
import base64 import base64
import gzip import gzip
import html as html_lib
import json import json
import struct
from pathlib import Path from pathlib import Path
import showcase_schema
SKILL_ROOT = Path(__file__).resolve().parent.parent SKILL_ROOT = Path(__file__).resolve().parent.parent
@@ -51,10 +55,27 @@ def group_of(key: str) -> str:
return "主体" return "主体"
MAIN_JS = r''' def glb_extensions(path: Path) -> set[str]:
"""Return extensionsUsed from the GLB JSON chunk without extra dependencies."""
data = path.read_bytes()
if len(data) < 20 or data[:4] != b"glTF":
raise SystemExit(f"Not a valid GLB: {path}")
chunk_length, chunk_type = struct.unpack_from("<II", data, 12)
if chunk_type != 0x4E4F534A or 20 + chunk_length > len(data):
raise SystemExit(f"GLB JSON chunk is missing or truncated: {path}")
document = json.loads(data[20 : 20 + chunk_length].decode("utf-8").rstrip("\x00 \t\r\n"))
return set(document.get("extensionsUsed", []))
def script_json(value) -> str:
"""Serialize JSON for an inline script without allowing an early script close."""
return json.dumps(value, ensure_ascii=False).replace("</", "<\\/")
MAIN_JS = r"""
(async function(){ (async function(){
const $load = document.getElementById('load'); const $load = document.getElementById('load');
const fail = m => { $load.style.display='flex'; $load.innerHTML = '<div style="max-width:520px;text-align:center">加载失败:'+m+'</div>'; }; const fail = m => { $load.style.display='flex'; $load.textContent = '加载失败:'+m; };
window.addEventListener('error', e => fail(e.message)); window.addEventListener('error', e => fail(e.message));
window.addEventListener('unhandledrejection', e => fail(e.reason && e.reason.message || e.reason)); window.addEventListener('unhandledrejection', e => fail(e.reason && e.reason.message || e.reason));
try { try {
@@ -65,6 +86,7 @@ MAIN_JS = r'''
renderer.outputEncoding = THREE.sRGBEncoding; renderer.outputEncoding = THREE.sRGBEncoding;
renderer.physicallyCorrectLights = true; renderer.physicallyCorrectLights = true;
renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.shadowMap.autoUpdate = false; renderer.shadowMap.needsUpdate = true; // static scene: bake shadows on change only
document.body.appendChild(renderer.domElement); document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene(); const scene = new THREE.Scene();
scene.background = new THREE.Color(0x23272d); scene.background = new THREE.Color(0x23272d);
@@ -73,6 +95,10 @@ MAIN_JS = r'''
scene.environment = pmrem.fromScene(new THREE.RoomEnvironment(), 0.04).texture; scene.environment = pmrem.fromScene(new THREE.RoomEnvironment(), 0.04).texture;
const cam = new THREE.PerspectiveCamera(48, innerWidth/innerHeight, 0.5, 4000); const cam = new THREE.PerspectiveCamera(48, innerWidth/innerHeight, 0.5, 4000);
const controls = new THREE.OrbitControls(cam, renderer.domElement); controls.enableDamping = true; const controls = new THREE.OrbitControls(cam, renderer.domElement); controls.enableDamping = true;
// Render on demand: identical frames at 60fps peg the GPU/fans on a static scene.
let renderPending = true; window.__renders = 0;
const invalidate = (shadows) => { if (shadows) renderer.shadowMap.needsUpdate = true; renderPending = true; };
controls.addEventListener('change', () => invalidate());
const sun = new THREE.DirectionalLight(0xfff3e0, 3.2); const sun = new THREE.DirectionalLight(0xfff3e0, 3.2);
sun.position.set(-120, 180, 140); sun.castShadow = true; sun.position.set(-120, 180, 140); sun.castShadow = true;
sun.shadow.mapSize.set(2048,2048); sun.shadow.bias = -0.0004; sun.shadow.mapSize.set(2048,2048); sun.shadow.bias = -0.0004;
@@ -112,6 +138,7 @@ MAIN_JS = r'''
} }
if (cat === 'trees') o.visible = false; if (cat === 'trees') o.visible = false;
}); });
window.__offlineReady = {meshes:nodes.length};
if (TREES.length) { if (TREES.length) {
const ti = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.14,0.2,1.4,6), const ti = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.14,0.2,1.4,6),
new THREE.MeshStandardMaterial({color:0x6b4a2e, roughness:0.9}), TREES.length); new THREE.MeshStandardMaterial({color:0x6b4a2e, roughness:0.9}), TREES.length);
@@ -129,8 +156,8 @@ MAIN_JS = r'''
} }
const tg = document.getElementById('tg'); const tg = document.getElementById('tg');
const state = {fl:{}, ct:{}}; const state = {fl:{}, ct:{}};
const apply = () => nodes.forEach(o => { const p=(o.name||'').split('__'); const apply = () => { nodes.forEach(o => { const p=(o.name||'').split('__');
o.visible = (state.fl[p[0]]!==false) && (state.ct[p[1]]!==false) && p[1]!=='trees'; }); o.visible = (state.fl[p[0]]!==false) && (state.ct[p[1]]!==false) && p[1]!=='trees'; }); invalidate(true); };
for (const gname in GROUPS) { for (const gname in GROUPS) {
const head = document.createElement('div'); head.className='grp'; const head = document.createElement('div'); head.className='grp';
const btn = document.createElement('button'); btn.textContent='开/关'; const btn = document.createElement('button'); btn.textContent='开/关';
@@ -140,8 +167,9 @@ MAIN_JS = r'''
head.appendChild(document.createTextNode(gname)); head.appendChild(btn); tg.appendChild(head); head.appendChild(document.createTextNode(gname)); head.appendChild(btn); tg.appendChild(head);
GROUPS[gname].forEach(f => { GROUPS[gname].forEach(f => {
const l = document.createElement('label'); const l = document.createElement('label');
l.innerHTML = '<input id="cb_'+f[0]+'" type="checkbox" checked> '+f[0]+' '+f[1]; const input = document.createElement('input'); input.id='cb_'+f[0]; input.type='checkbox'; input.checked=true;
l.querySelector('input').onchange = e => { state.fl[f[0]]=e.target.checked; apply(); }; input.onchange = e => { state.fl[f[0]]=e.target.checked; apply(); };
l.appendChild(input); l.appendChild(document.createTextNode(' '+f[0]+' '+f[1]));
tg.appendChild(l); tg.appendChild(l);
}); });
} }
@@ -152,8 +180,9 @@ MAIN_JS = r'''
for (const k in CATS) { for (const k in CATS) {
if (!used[k] || k==='trees') continue; if (!used[k] || k==='trees') continue;
const l = document.createElement('label'); const l = document.createElement('label');
l.innerHTML = '<input type="checkbox" checked> '+CATS[k]; const input = document.createElement('input'); input.type='checkbox'; input.checked=true;
l.querySelector('input').onchange = e => { state.ct[k]=e.target.checked; apply(); }; input.onchange = e => { state.ct[k]=e.target.checked; apply(); };
l.appendChild(input); l.appendChild(document.createTextNode(' '+CATS[k]));
tg.appendChild(l); tg.appendChild(l);
} }
const ray = new THREE.Raycaster(), ptr = new THREE.Vector2(), info = document.getElementById('info'); const ray = new THREE.Raycaster(), ptr = new THREE.Vector2(), info = document.getElementById('info');
@@ -164,49 +193,73 @@ MAIN_JS = r'''
ptr.x=(e.clientX/innerWidth)*2-1; ptr.y=-(e.clientY/innerHeight)*2+1; ptr.x=(e.clientX/innerWidth)*2-1; ptr.y=-(e.clientY/innerHeight)*2+1;
ray.setFromCamera(ptr, cam); ray.setFromCamera(ptr, cam);
const hit = ray.intersectObjects(nodes.filter(o=>o.visible), false)[0]; const hit = ray.intersectObjects(nodes.filter(o=>o.visible), false)[0];
if (hi) { hi.material = hiMat; hi = null; } if (hi) { hi.material = hiMat; hi = null; invalidate(); }
if (!hit) { info.style.display='none'; return; } if (!hit) { info.style.display='none'; return; }
hi = hit.object; hiMat = hi.material; hi = hit.object; hiMat = hi.material;
hi.material = hiMat.clone(); hi.material.emissive = new THREE.Color(0x2a6bd4); hi.material.emissiveIntensity = 0.55; hi.material = hiMat.clone(); hi.material.emissive = new THREE.Color(0x2a6bd4); hi.material.emissiveIntensity = 0.55;
const p = (hi.name||'').split('__'); const p = (hi.name||'').split('__');
let fname=''; for (const gname in GROUPS) GROUPS[gname].forEach(f => { if (f[0]===p[0]) fname=f[1]; }); let fname=''; for (const gname in GROUPS) GROUPS[gname].forEach(f => { if (f[0]===p[0]) fname=f[1]; });
info.innerHTML = '<b>'+p[0]+'</b> '+fname+'<br>构件:'+(CATS[p[1]]||p[1])+' 节点:'+hi.name; info.replaceChildren();
const strong=document.createElement('b'); strong.textContent=p[0]; info.appendChild(strong);
info.appendChild(document.createTextNode(' '+fname)); info.appendChild(document.createElement('br'));
info.appendChild(document.createTextNode('构件:'+(CATS[p[1]]||p[1])+' 节点:'+hi.name));
info.style.display = 'block'; info.style.display = 'block';
invalidate();
});
invalidate(true);
renderer.setAnimationLoop(() => {
const moved = controls.update();
if (moved || renderPending) { renderer.render(scene, cam); window.__renders += 1; renderPending = false; }
}); });
renderer.setAnimationLoop(() => { controls.update(); renderer.render(scene, cam); });
}, e => fail('GLB 解析错误 '+(e && e.message || e))); }, e => fail('GLB 解析错误 '+(e && e.message || e)));
addEventListener('resize', () => { cam.aspect=innerWidth/innerHeight; cam.updateProjectionMatrix(); renderer.setSize(innerWidth,innerHeight); }); addEventListener('resize', () => { cam.aspect=innerWidth/innerHeight; cam.updateProjectionMatrix(); renderer.setSize(innerWidth,innerHeight); invalidate(); });
} catch (err) { fail(err.message || String(err)); } } catch (err) { fail(err.message || String(err)); }
})(); })();
''' """
CSS = ( CSS = (
'body{margin:0;background:#1c1f24;color:#e8e6e0;font:14px/1.5 -apple-system,"PingFang SC",sans-serif;overflow:hidden}' 'body{margin:0;background:#1c1f24;color:#e8e6e0;font:14px/1.5 -apple-system,"PingFang SC",sans-serif;overflow:hidden}'
'#panel{position:fixed;top:12px;left:12px;background:rgba(244,241,232,.97);color:#2a2a26;border-radius:12px;padding:12px 14px;width:242px;max-height:92vh;overflow:auto;box-shadow:0 4px 18px rgba(0,0,0,.45);z-index:5}' "#panel{position:fixed;top:12px;left:12px;background:rgba(244,241,232,.97);color:#2a2a26;border-radius:12px;padding:12px 14px;width:242px;max-height:92vh;overflow:auto;box-shadow:0 4px 18px rgba(0,0,0,.45);z-index:5}"
'#panel h1{font-size:15px;margin:0 0 2px}' "#panel h1{font-size:15px;margin:0 0 2px}"
'#panel .sub{font-size:12px;color:#777;margin-bottom:6px}' "#panel .sub{font-size:12px;color:#777;margin-bottom:6px}"
'#panel label{display:flex;gap:6px;align-items:center;font-size:13px;padding:1px 0;cursor:pointer}' "#panel label{display:flex;gap:6px;align-items:center;font-size:13px;padding:1px 0;cursor:pointer}"
'.grp{border-top:1px solid #ddd;margin-top:8px;padding-top:6px;font-weight:600;font-size:12px;color:#555;display:flex;justify-content:space-between;align-items:center}' ".grp{border-top:1px solid #ddd;margin-top:8px;padding-top:6px;font-weight:600;font-size:12px;color:#555;display:flex;justify-content:space-between;align-items:center}"
'.grp button{font-size:11px;border:none;background:#e5e0d2;border-radius:6px;padding:1px 8px;cursor:pointer}' ".grp button{font-size:11px;border:none;background:#e5e0d2;border-radius:6px;padding:1px 8px;cursor:pointer}"
'#info{position:fixed;bottom:14px;left:14px;background:rgba(30,33,38,.92);border:1px solid #3a3f46;color:#e8e6e0;border-radius:10px;padding:8px 12px;font-size:13px;display:none;max-width:340px;z-index:5}' "#info{position:fixed;bottom:14px;left:14px;background:rgba(30,33,38,.92);border:1px solid #3a3f46;color:#e8e6e0;border-radius:10px;padding:8px 12px;font-size:13px;display:none;max-width:340px;z-index:5}"
'#hint{position:fixed;bottom:10px;right:14px;font-size:12px;color:#9aa;z-index:5}' "#hint{position:fixed;bottom:10px;right:14px;font-size:12px;color:#9aa;z-index:5}"
'#load{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;color:#cfd3c9;font-size:14px;background:#1c1f24;z-index:9}' "#load{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;color:#cfd3c9;font-size:14px;background:#1c1f24;z-index:9}"
) )
def main() -> int: def main() -> int:
args = parse_args() args = parse_args()
spec_path = Path(args.spec)
glb_path = Path(args.glb)
if not glb_path.exists() or glb_path.stat().st_size == 0:
raise SystemExit(f"GLB not found or empty: {glb_path}")
extensions = glb_extensions(glb_path)
if "KHR_draco_mesh_compression" in extensions:
raise SystemExit(
"Offline single-file viewer requires an uncompressed GLB; "
f"KHR_draco_mesh_compression found in {glb_path}. Pass the matching *.raw.glb instead."
)
spec = showcase_schema.normalize_spec(json.loads(spec_path.read_text(encoding="utf-8")))
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
raise SystemExit(str(exc)) from exc
libs = Path(args.libs_dir) libs = Path(args.libs_dir)
parts = {} parts = {}
for name in ("three.min.js", "OrbitControls.js", "GLTFLoader.js", "RoomEnvironment.js", "pako_inflate.min.js"): for name in ("three.min.js", "OrbitControls.js", "GLTFLoader.js", "RoomEnvironment.js", "pako_inflate.min.js"):
path = libs / name path = libs / name
if not path.exists(): if not path.exists():
raise SystemExit(f"Missing offline lib {path}. Populate via: npm pack three@0.147.0 pako@2.1.0 and copy files.") raise SystemExit(
f"Missing offline lib {path}. Populate via: npm pack three@0.147.0 pako@2.1.0 and copy files."
)
parts[name] = path.read_text(encoding="utf-8") parts[name] = path.read_text(encoding="utf-8")
assert "</scr" + "ipt>" not in parts[name] assert "</scr" + "ipt>" not in parts[name]
spec = json.loads(Path(args.spec).read_text(encoding="utf-8")) glb = glb_path.read_bytes()
glb = Path(args.glb).read_bytes()
b64 = base64.b64encode(gzip.compress(glb, 6)).decode() b64 = base64.b64encode(gzip.compress(glb, 6)).decode()
order = spec.get("source", {}).get("config", {}).get("floor_order") or list(spec.get("floors", {})) order = spec.get("source", {}).get("config", {}).get("floor_order") or list(spec.get("floors", {}))
@@ -214,27 +267,34 @@ def main() -> int:
for key in order: for key in order:
if key in spec.get("floors", {}): if key in spec.get("floors", {}):
groups.setdefault(group_of(key), []).append([key, spec["floors"][key].get("name", key)]) groups.setdefault(group_of(key), []).append([key, spec["floors"][key].get("name", key)])
trees = [[round((s["start"][0] + s["end"][0]) / 2, 2), round((s["start"][1] + s["end"][1]) / 2, 2)] trees = [
for s in spec.get("floors", {}).get("TREES", {}).get("segments", {}).get("trees", [])] [round((s["start"][0] + s["end"][0]) / 2, 2), round((s["start"][1] + s["end"][1]) / 2, 2)]
for s in spec.get("floors", {}).get("TREES", {}).get("segments", {}).get("trees", [])
]
cats = {k: v.get("label", k) for k, v in spec.get("categories", {}).items()} cats = {k: v.get("label", k) for k, v in spec.get("categories", {}).items()}
title = args.title or spec.get("project", {}).get("name", "CAD 建筑模型") title = str(args.title or spec.get("project", {}).get("name", "CAD 建筑模型"))
escaped_title = html_lib.escape(title, quote=True)
escaped_subtitle = html_lib.escape(str(args.subtitle), quote=True)
main_js = (MAIN_JS main_js = (
.replace("__GROUPS__", json.dumps(groups, ensure_ascii=False)) MAIN_JS.replace("__GROUPS__", script_json(groups))
.replace("__CATS__", json.dumps(cats, ensure_ascii=False)) .replace("__CATS__", script_json(cats))
.replace("__TREES__", json.dumps(trees))) .replace("__TREES__", script_json(trees))
)
sc_close = "</scr" + "ipt>" sc_close = "</scr" + "ipt>"
html = ( html = (
'<!DOCTYPE html><html lang="zh"><head><meta charset="utf-8">' '<!DOCTYPE html><html lang="zh"><head><meta charset="utf-8">'
f'<title>{title} · 3D 查看器(离线版)</title>' f"<title>{escaped_title} · 3D 查看器(离线版)</title>"
'<meta name="viewport" content="width=device-width, initial-scale=1">' '<meta name="viewport" content="width=device-width, initial-scale=1">'
f'<style>{CSS}</style></head><body>' f"<style>{CSS}</style></head><body>"
'<div id="load">正在初始化…</div>' '<div id="load">正在初始化…</div>'
f'<div id="panel"><h1>{title}</h1><div class="sub">{args.subtitle}</div><div id="tg"></div></div>' f'<div id="panel"><h1>{escaped_title}</h1><div class="sub">{escaped_subtitle}</div><div id="tg"></div></div>'
'<div id="info"></div>' '<div id="info"></div>'
'<div id="hint">拖动旋转 · 滚轮缩放 · 右键平移 · 点击构件查属性</div>' '<div id="hint">拖动旋转 · 滚轮缩放 · 右键平移 · 点击构件查属性</div>'
+ "".join(f"<script>{parts[n]}{sc_close}" for n in + "".join(
("three.min.js", "OrbitControls.js", "GLTFLoader.js", "RoomEnvironment.js", "pako_inflate.min.js")) f"<script>{parts[n]}{sc_close}"
for n in ("three.min.js", "OrbitControls.js", "GLTFLoader.js", "RoomEnvironment.js", "pako_inflate.min.js")
)
+ f'<script>const GLB_B64="{b64}";{sc_close}' + f'<script>const GLB_B64="{b64}";{sc_close}'
+ f"<script>{main_js}{sc_close}" + f"<script>{main_js}{sc_close}"
+ "</body></html>" + "</body></html>"
@@ -242,8 +302,17 @@ def main() -> int:
out = Path(args.out) out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True) out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(html, encoding="utf-8") out.write_text(html, encoding="utf-8")
print(json.dumps({"out": str(out), "kb": len(html) // 1024, print(
"floors": sum(len(v) for v in groups.values()), "trees": len(trees)}, ensure_ascii=False)) json.dumps(
{
"out": str(out),
"kb": len(html) // 1024,
"floors": sum(len(v) for v in groups.values()),
"trees": len(trees),
},
ensure_ascii=False,
)
)
return 0 return 0

View File

@@ -9,6 +9,8 @@ import shutil
import time import time
from pathlib import Path from pathlib import Path
import showcase_schema
def default_template() -> Path: def default_template() -> Path:
return Path(__file__).resolve().parents[1] / "assets" / "web-showcase-template" return Path(__file__).resolve().parents[1] / "assets" / "web-showcase-template"
@@ -63,6 +65,10 @@ def load_variants(manifest_path: Path | None) -> tuple[dict | None, list[dict]]:
if not manifest_path.exists(): if not manifest_path.exists():
raise SystemExit(f"Variants manifest not found: {manifest_path}") raise SystemExit(f"Variants manifest not found: {manifest_path}")
manifest = json.loads(manifest_path.read_text(encoding="utf-8")) manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
try:
showcase_schema.validate_manifest(manifest)
except showcase_schema.ValidationFailure as exc:
raise SystemExit(str(exc)) from exc
variants = list(manifest.get("variants", [])) variants = list(manifest.get("variants", []))
if not variants: if not variants:
raise SystemExit(f"Variants manifest has no variants: {manifest_path}") raise SystemExit(f"Variants manifest has no variants: {manifest_path}")
@@ -101,7 +107,9 @@ def copy_variant_assets(manifest_path: Path | None, variants: list[dict], out_di
return web_variants return web_variants
def inferred_default_glb(args_glb: str | None, manifest_path: Path | None, manifest: dict | None, variants: list[dict]) -> Path: def inferred_default_glb(
args_glb: str | None, manifest_path: Path | None, manifest: dict | None, variants: list[dict]
) -> Path:
if args_glb: if args_glb:
return Path(args_glb) return Path(args_glb)
variant = default_variant(manifest, variants) variant = default_variant(manifest, variants)
@@ -111,7 +119,9 @@ def inferred_default_glb(args_glb: str | None, manifest_path: Path | None, manif
return resolve_manifest_path(manifest_path, source_value) if manifest_path else Path(source_value) 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: def inferred_metadata(
args_metadata: str | None, manifest_path: Path | None, manifest: dict | None, variants: list[dict]
) -> Path:
if args_metadata: if args_metadata:
return Path(args_metadata) return Path(args_metadata)
variant = default_variant(manifest, variants) variant = default_variant(manifest, variants)
@@ -131,16 +141,19 @@ def site_trees_from_spec(spec_path: Path | None) -> list[list[float]]:
if not spec_path or not spec_path.exists(): if not spec_path or not spec_path.exists():
return [] return []
try: try:
spec = json.loads(spec_path.read_text(encoding="utf-8")) spec = showcase_schema.normalize_spec(json.loads(spec_path.read_text(encoding="utf-8")))
except (OSError, json.JSONDecodeError): except (OSError, json.JSONDecodeError):
return [] return []
showcase_schema.validate_spec(spec)
trees = [] trees = []
for floor in spec.get("floors", {}).values(): for floor in spec.get("floors", {}).values():
for seg in floor.get("segments", {}).get("trees", []): for seg in floor.get("segments", {}).get("trees", []):
trees.append([ trees.append(
round((seg["start"][0] + seg["end"][0]) / 2, 2), [
round((seg["start"][1] + seg["end"][1]) / 2, 2), round((seg["start"][0] + seg["end"][0]) / 2, 2),
]) round((seg["start"][1] + seg["end"][1]) / 2, 2),
]
)
return trees return trees

126
tests/test_browser_smoke.py Normal file
View File

@@ -0,0 +1,126 @@
from __future__ import annotations
import json
import os
import shutil
import socket
import subprocess
import sys
import time
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
@pytest.mark.skipif(
os.environ.get("RUN_BROWSER_SMOKE") != "1", reason="set RUN_BROWSER_SMOKE=1 with Playwright installed"
)
def test_served_viewer_in_desktop_and_mobile(tmp_path: Path) -> None:
from test_contracts import minimal_spec
spec = tmp_path / "spec.json"
glb = tmp_path / "model.glb"
metadata = tmp_path / "model_metadata.json"
web = tmp_path / "web"
spec.write_text(json.dumps(minimal_spec()), encoding="utf-8")
subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "spec_to_glb.py"),
"--spec",
str(spec),
"--out",
str(glb),
"--metadata-out",
str(metadata),
],
check=True,
)
subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "write_web_showcase.py"),
"--glb",
str(glb),
"--metadata",
str(metadata),
"--out-dir",
str(web),
],
check=True,
)
npm = shutil.which("npm.cmd" if sys.platform == "win32" else "npm") or shutil.which("npm")
assert npm, "npm executable not found"
subprocess.run([npm, "install", "--prefix", str(web), "--ignore-scripts"], check=True)
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
server = subprocess.Popen(
[sys.executable, "-m", "http.server", str(port), "--bind", "127.0.0.1"],
cwd=web,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
try:
time.sleep(0.8)
report = tmp_path / "browser_report.json"
proc = subprocess.run(
[
"node",
str(ROOT / "scripts" / "web_smoke_test.mjs"),
"--url",
f"http://127.0.0.1:{port}",
"--out",
str(report),
"--screenshots-dir",
str(tmp_path / "screenshots"),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
result = json.loads(report.read_text(encoding="utf-8"))
assert result["status"] == "PASS"
checks = {item["name"]: item for item in result["checks"]}
assert checks["desktop:viewport"]["detail"] == "1440x900 expected 1440x900"
assert checks["mobile:viewport"]["detail"] == "390x844 expected 390x844"
offline = tmp_path / "viewer.html"
subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "write_offline_viewer.py"),
"--spec",
str(spec),
"--glb",
str(glb),
"--out",
str(offline),
],
check=True,
)
offline_report = tmp_path / "offline_browser_report.json"
offline_screenshot = tmp_path / "offline_browser.png"
proc = subprocess.run(
[
"node",
str(ROOT / "scripts" / "offline_viewer_smoke.mjs"),
"--viewer",
str(offline),
"--out",
str(offline_report),
"--screenshot",
str(offline_screenshot),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
offline_result = json.loads(offline_report.read_text(encoding="utf-8"))
assert offline_result["status"] == "PASS"
assert offline_screenshot.exists()
finally:
server.terminate()
server.wait(timeout=10)

864
tests/test_contracts.py Normal file
View File

@@ -0,0 +1,864 @@
from __future__ import annotations
import json
import subprocess
import sys
from pathlib import Path
import pytest
import ezdxf
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import audit_showcase_extraction # noqa: E402
import build_blender_showcase # noqa: E402
import cad_showcase # noqa: E402
import delivery_waivers # noqa: E402
import derive_showcase_spec # noqa: E402
import showcase_schema # noqa: E402
import spec_to_glb # noqa: E402
def minimal_spec() -> dict:
wall = {
"start": [0.0, 0.0],
"end": [10.0, 0.0],
"width": 0.2,
"layer": "WALL",
"source_type": "LINE",
}
return {
"schema_version": 1,
"project": {"name": "test", "description": "contract fixture"},
"source": {"config": {"config_version": 1, "use_footprint_slabs": True}},
"units": {"source": "meters", "scale_to_meters": 1.0, "origin_source": [0.0, 0.0]},
"categories": {
"walls": {"label": "墙", "color": "#cccccc"},
"slab": {"label": "楼板", "color": "#aaaaaa"},
},
"floors": {
"F1": {
"name": "一层",
"z": 0.0,
"height": 3.0,
"bounds": [0.0, 0.0, 10.0, 8.0],
"source_file": "fixture.dxf",
"segments": {"walls": [wall]},
"footprint": {"source": "fixture", "area": 80.0, "polygons": [[[0, 0], [10, 0], [10, 8], [0, 8]]]},
"caps": [{"z": 3.0, "polygons": [[[0, 0], [10, 0], [10, 8], [0, 8]]]}],
}
},
}
def test_config_rejects_unknown_keys() -> None:
with pytest.raises(showcase_schema.ValidationFailure, match="unexpected_typo"):
showcase_schema.validate_config({"config_version": 1, "unexpected_typo": True})
def test_vertical_storey_continuity_rejects_representative_floor_islands() -> None:
spec = minimal_spec()
spec["floors"]["F2"] = {**spec["floors"]["F1"], "name": "二层", "z": 5.0}
spec["floors"]["F16"] = {**spec["floors"]["F1"], "name": "十六层", "z": 59.6}
gate = audit_showcase_extraction.vertical_storey_continuity_gate(spec)
assert gate["status"] == "WARN"
assert "F2->F16" in gate["detail"]
def test_vertical_storey_continuity_accepts_instantiated_typical_floors() -> None:
spec = minimal_spec()
base = spec["floors"]["F1"]
spec["floors"] = {f"F{number}": {**base, "name": f"{number}层", "z": (number - 1) * 3.9} for number in range(1, 17)}
gate = audit_showcase_extraction.vertical_storey_continuity_gate(spec)
assert gate["status"] == "PASS"
def test_config_requires_at_least_one_drawing() -> None:
with pytest.raises(showcase_schema.ValidationFailure, match="contains no drawings"):
showcase_schema.validate_config({"config_version": 1})
def test_config_rejects_duplicate_floor_keys(tmp_path: Path) -> None:
(tmp_path / "a.dxf").touch()
(tmp_path / "b.dxf").touch()
config = {
"config_version": 1,
"drawings": [
{"file": "a.dxf", "floors": [{"key": "F1"}]},
{"file": "b.dxf", "floors": [{"key": "F1"}]},
],
}
with pytest.raises(showcase_schema.ValidationFailure, match="duplicate floor key"):
showcase_schema.validate_config(config, tmp_path)
def test_config_rejects_missing_source(tmp_path: Path) -> None:
config = {"config_version": 1, "drawings": [{"file": "missing.dxf", "floors": [{"key": "F1"}]}]}
with pytest.raises(showcase_schema.ValidationFailure, match="does not exist"):
showcase_schema.validate_config(config, tmp_path)
def test_source_report_requires_reason_for_partial_gate() -> None:
report = {
"report_version": 1,
"gate": {"name": "all_sources_converted_and_readable", "status": "WARN"},
"files": [{"file": "partial.dxf", "status": "ok", "modelspace_entities": 1}],
}
with pytest.raises(showcase_schema.ValidationFailure, match="partial reason"):
showcase_schema.validate_source_report(report)
def test_source_report_accepts_reasoned_partial_gate() -> None:
report = {
"report_version": 1,
"gate": {
"name": "all_sources_converted_and_readable",
"status": "WARN",
"partial_reason": "One optional elevation DWG is unavailable",
},
"files": [{"file": "partial.dxf", "status": "ok", "modelspace_entities": 1}],
}
assert showcase_schema.validate_source_report(report) == report
def test_unarmed_cross_evidence_gates_are_not_applicable() -> None:
spec = minimal_spec()
assert audit_showcase_extraction.frame_ledger_gate({}, None)["status"] == "NOT_APPLICABLE"
assert audit_showcase_extraction.declared_area_gate(spec, {})["status"] == "NOT_APPLICABLE"
assert audit_showcase_extraction.storey_count_gate(spec, {})["status"] == "NOT_APPLICABLE"
def test_multi_frame_source_requires_detector_ledger() -> None:
report = {
"files": [
{"file": "A212.dxf", "status": "ok", "plan_title_count": 2},
{"file": "A213.dxf", "status": "ok", "plan_title_count": 1},
]
}
assert cad_showcase.multi_frame_source_files(report) == ["A212.dxf"]
def test_frame_ledger_requires_distinct_floor_identity_even_when_roof_clips_overlap() -> None:
frames = [
{
"drawings": [
{
"file": "A212.dxf",
"floors": [
{
"key": "RF",
"name": "屋面平面图",
"clip": [0, 0, 100, 100],
"include_block_names": ["*-屋面平面图"],
},
{
"key": "PH",
"name": "机房小屋面",
"clip": [0, 0, 100, 100],
"include_block_names": ["*-机房小屋面"],
},
],
}
]
}
]
config = {
"drawings": [
{
"file": "A212.dxf",
"floors": [
{"key": "RF", "clip": [0, 0, 100, 100]},
{"key": "PH", "clip": [0, 0, 100, 100]},
],
}
]
}
gate = audit_showcase_extraction.frame_ledger_gate(config, frames)
assert gate["status"] == "FAIL"
assert "屋面平面图" in gate["detail"]
config["drawings"][0]["floors"][0]["include_block_names"] = ["*-屋面平面图"]
config["drawings"][0]["floors"][1]["include_block_names"] = ["*-机房小屋面"]
assert audit_showcase_extraction.frame_ledger_gate(config, frames)["status"] == "PASS"
def test_revit_view_block_selector_separates_overlapping_floor_views() -> None:
rf = {"include_block_names": ["*-屋面平面图"]}
drawing: dict = {}
assert derive_showcase_spec.block_matches_floor("墙族-123-屋面平面图", rf, drawing)
assert not derive_showcase_spec.block_matches_floor("墙族-456-机房小屋面", rf, drawing)
assert not derive_showcase_spec.block_matches_floor("", rf, drawing)
def test_disconnected_footprint_island_fails_until_explicitly_explained() -> None:
spec = minimal_spec()
spec["floors"]["F1"]["footprint"]["polygons"].append([[25.0, 0.0], [26.0, 0.0], [26.0, 1.0], [25.0, 1.0]])
failed = audit_showcase_extraction.disconnected_footprints_gate(spec, {})
assert failed["status"] == "FAIL"
assert "F1" in failed["detail"]
accepted = audit_showcase_extraction.disconnected_footprints_gate(
spec,
{"allowed_disconnected_footprints": [{"floor_key": "F1", "reason": "独立雨棚,有柱网证据"}]},
)
assert accepted["status"] == "PASS"
def test_annotation_is_waivable_warn_and_absent_glazing_is_not_applicable() -> None:
report = {
"spec_counts": {"F1": {"glazing": 0}},
"block_locked_layers": [],
"top_insert_names": [],
"classified_layers": [{"layer": "A-ANNO-DIMS"}],
"coverage": {
"block_locked_classifiable_length_meters": 0,
"block_captured_classified_length_meters": 0,
},
}
gates = {
gate["name"]: gate["status"]
for gate in audit_showcase_extraction.evaluate_gates(report, minimal_spec(), {}, None)
}
assert gates["no_annotation_layers_classified"] == "WARN"
assert gates["glazing_captured"] == "NOT_APPLICABLE"
def test_config_rejects_malformed_category_overrides() -> None:
config = {
"config_version": 1,
"drawings": [{"file": "fixture.dxf", "floors": [{"key": "F1"}]}],
"categories": {"walls": "not-an-object"},
}
with pytest.raises(showcase_schema.ValidationFailure, match="categories.walls"):
showcase_schema.validate_config(config)
def test_all_derive_geometry_loss_warnings_are_forbidden() -> None:
assert set(cad_showcase.DERIVE_FORBIDDEN_WARNINGS) == {
"WARNING isolated_cluster",
"WARNING unsupported_roof",
"WARNING floor_order",
"WARNING topless_group",
}
def test_waivers_share_one_implementation_and_reject_not_applicable_targets(tmp_path: Path) -> None:
import verify_delivery
assert cad_showcase.parse_waivers is delivery_waivers.parse_waivers
assert verify_delivery.parse_waivers is delivery_waivers.parse_waivers
audit = tmp_path / "audit.json"
audit.write_text(
json.dumps(
{
"gates": [
{
"name": "frame_ledger",
"status": "NOT_APPLICABLE",
"detail": "No frame report supplied",
}
]
}
),
encoding="utf-8",
)
pipeline = cad_showcase.Pipeline(tmp_path / "state.json", "fingerprint", resume=False)
assert not cad_showcase.enforce_audit_gates(
pipeline,
audit,
{"audit:frame_ledger": "pre-approved in case this gate becomes armed"},
)
state = json.loads((tmp_path / "state.json").read_text(encoding="utf-8"))
blocked = state["blocked_gates"]
assert blocked[0]["name"] == "waiver:audit:frame_ledger"
assert "NOT_APPLICABLE" in blocked[0]["detail"]
def test_audit_waiver_typo_fails_before_downstream_work(tmp_path: Path) -> None:
audit = tmp_path / "audit.json"
audit.write_text(
json.dumps({"gates": [{"name": "floors_aligned", "status": "PASS", "detail": "aligned"}]}),
encoding="utf-8",
)
pipeline = cad_showcase.Pipeline(tmp_path / "state.json", "fingerprint", resume=False)
assert not cad_showcase.enforce_audit_gates(
pipeline,
audit,
{"audit:floors_aligend": "typo must not survive to final verification"},
)
state = json.loads((tmp_path / "state.json").read_text(encoding="utf-8"))
assert state["blocked_gates"][0]["name"] == "waiver:audit:floors_aligend"
def test_waiver_preflight_rejects_misspelled_namespace_and_extra_future_waiver(tmp_path: Path) -> None:
scope = tmp_path / "scope.json"
scope.write_text(
json.dumps(
{
"scope_version": 1,
"mode": "single",
"requested": ["main"],
"buildings": [{"id": "main", "status": "PASS", "artifacts": ["future.glb"]}],
}
),
encoding="utf-8",
)
args = cad_showcase.parser().parse_args(
[
"run",
"--dxf-dir",
str(tmp_path),
"--config",
str(tmp_path / "config.json"),
"--source-report",
str(tmp_path / "source.json"),
"--out-dir",
str(tmp_path / "out"),
"--scope-manifest",
str(scope),
"--web",
]
)
invalid = cad_showcase.preflight_waiver_targets(
args,
{"gate": {"status": "PASS"}},
{"gates": [{"name": "floors_aligned", "status": "WARN", "detail": "needs evidence"}]},
scope,
{
"audti:floors_aligned": "misspelled namespace",
"browser:smoke": "cannot pre-waive a generated PASS check",
},
)
assert {check["name"] for check in invalid} == {
"waiver:audti:floors_aligned",
"waiver:browser:smoke",
}
def test_default_cap_buffer_is_small_and_large_overhang_is_explicit() -> None:
pytest.importorskip("shapely")
base_floor = {
"name": "一层",
"z": 0.0,
"height": 3.0,
"bounds": [0.0, 0.0, 10.0, 10.0],
"source_file": "fixture.dxf",
"segments": {},
"footprint": {"polygons": [[[0, 0], [10, 0], [10, 10], [0, 10]]]},
}
upper_floor = {**base_floor, "name": "二层", "z": 3.0}
floors = {"F1": json.loads(json.dumps(base_floor)), "F2": json.loads(json.dumps(upper_floor))}
derive_showcase_spec.compute_caps(floors, {})
default_max_x = max(point[0] for polygon in floors["F1"]["caps"][0]["polygons"] for point in polygon)
assert default_max_x == pytest.approx(10.1)
floors = {"F1": json.loads(json.dumps(base_floor)), "F2": json.loads(json.dumps(upper_floor))}
derive_showcase_spec.compute_caps(floors, {"cap_buffer": 1.3})
colonnade_max_x = max(point[0] for polygon in floors["F1"]["caps"][0]["polygons"] for point in polygon)
assert colonnade_max_x == pytest.approx(11.3)
def test_pipeline_fails_on_derive_geometry_loss_warning(tmp_path: Path) -> None:
pipeline = cad_showcase.Pipeline(tmp_path / "state.json", "fingerprint", resume=False)
command = [
sys.executable,
"-c",
"import sys; print('WARNING isolated_cluster F1: dropped geometry', file=sys.stderr)",
]
with pytest.raises(SystemExit):
pipeline.run("derive", command, [], forbidden_stderr=cad_showcase.DERIVE_FORBIDDEN_WARNINGS)
state = json.loads((tmp_path / "state.json").read_text(encoding="utf-8"))
assert state["steps"]["derive"]["status"] == "FAIL"
assert state["steps"]["derive"]["forbidden_stderr_hits"] == ["WARNING isolated_cluster"]
def test_windows_command_resolution_uses_cmd_shims(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(cad_showcase.sys, "platform", "win32")
monkeypatch.setattr(
cad_showcase.shutil,
"which",
lambda candidate: f"C:/tools/{candidate}" if candidate in {"npm.cmd", "node.exe"} else None,
)
assert cad_showcase.npm_command("install")[0] == "C:/tools/npm.cmd"
assert cad_showcase.node_script(Path("smoke.mjs"))[0] == "C:/tools/node.exe"
def test_resume_fingerprint_tracks_tools_offline_libs_and_extra_inputs(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
root = tmp_path / "skill"
scripts = root / "scripts"
dxf_dir = tmp_path / "dxf"
for directory in (
scripts,
root / "schemas",
root / "tools",
root / "assets" / "web-showcase-template",
root / "assets" / "offline-viewer-libs",
dxf_dir,
):
directory.mkdir(parents=True, exist_ok=True)
config = tmp_path / "config.json"
source = tmp_path / "source.json"
frames = tmp_path / "frames.json"
config.write_text("{}", encoding="utf-8")
source.write_text("{}", encoding="utf-8")
frames.write_text("{}", encoding="utf-8")
(dxf_dir / "plan.dxf").write_text("DXF", encoding="utf-8")
(scripts / "step.py").write_text("pass", encoding="utf-8")
compressor = root / "tools" / "compress.mjs"
compressor.write_text("v1", encoding="utf-8")
offline_lib = root / "assets" / "offline-viewer-libs" / "three.min.js"
offline_lib.write_text("v1", encoding="utf-8")
monkeypatch.setattr(cad_showcase, "ROOT", root)
monkeypatch.setattr(cad_showcase, "SCRIPTS", scripts)
first = cad_showcase.fingerprint(config, source, dxf_dir, (frames,))
compressor.write_text("v2", encoding="utf-8")
second = cad_showcase.fingerprint(config, source, dxf_dir, (frames,))
offline_lib.write_text("v2", encoding="utf-8")
third = cad_showcase.fingerprint(config, source, dxf_dir, (frames,))
frames.write_text('{"changed": true}', encoding="utf-8")
fourth = cad_showcase.fingerprint(config, source, dxf_dir, (frames,))
assert len({first, second, third, fourth}) == 4
def test_pipeline_state_is_atomic_and_corruption_is_loud(tmp_path: Path) -> None:
state = tmp_path / "pipeline_state.json"
pipeline = cad_showcase.Pipeline(state, "fingerprint", resume=False)
pipeline.state["proof"] = "saved"
pipeline.save()
assert json.loads(state.read_text(encoding="utf-8"))["proof"] == "saved"
assert not list(tmp_path.glob(".pipeline_state.json.*.tmp"))
state.write_text("{truncated", encoding="utf-8")
with pytest.raises(SystemExit, match="corrupt and was not overwritten"):
cad_showcase.Pipeline(state, "fingerprint", resume=True)
assert state.read_text(encoding="utf-8") == "{truncated"
def test_doctor_uses_platform_tool_resolvers(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys) -> None:
oda = tmp_path / "ODAFileConverter"
blender = tmp_path / "blender"
oda.touch()
blender.touch()
monkeypatch.setattr(cad_showcase, "oda_converter", lambda: str(oda))
monkeypatch.setattr(cad_showcase, "default_blender", lambda: str(blender))
assert cad_showcase.doctor() == 0
report = json.loads(capsys.readouterr().out)
checks = {item["name"]: item for item in report["checks"]}
assert checks["ODAFileConverter"] == {"name": "ODAFileConverter", "status": "PASS", "path": str(oda)}
assert checks["blender"] == {"name": "blender", "status": "PASS", "path": str(blender)}
def test_spec_schema_and_backend_group_contract() -> None:
spec = minimal_spec()
showcase_schema.validate_spec(spec)
config = {"cap_groups": [["TOWER_A_*", "A"], ["B*", "BASEMENT"]]}
assert showcase_schema.floor_group("TOWER_A_F3", config) == "A"
assert spec_to_glb.floor_group("TOWER_A_F3", config) == "A"
assert build_blender_showcase.floor_group("TOWER_A_F3", config) == "A"
def test_normalize_spec_backfills_categories_used_by_legacy_segments() -> None:
legacy = minimal_spec()
legacy.pop("schema_version")
legacy.pop("categories")
legacy["floors"]["F1"]["segments"]["legacy_custom"] = [
{"start": [0, 0], "end": [0, 1], "width": 0.1, "layer": "OLD", "source_type": "LINE"}
]
normalized = showcase_schema.normalize_spec(legacy)
assert normalized["categories"]["walls"] == {"label": "墙体", "color": "#d4cbb8"}
assert normalized["categories"]["slab"] == {"label": "楼板", "color": "#c8ccc2"}
assert normalized["categories"]["legacy_custom"] == {"label": "legacy_custom", "color": "#8c9088"}
showcase_schema.validate_spec(normalized)
def test_spec_rejects_segment_category_without_metadata() -> None:
spec = minimal_spec()
spec["floors"]["F1"]["segments"]["unregistered"] = [
{"start": [0, 0], "end": [1, 0], "width": 0.1, "layer": "X", "source_type": "LINE"}
]
with pytest.raises(showcase_schema.ValidationFailure, match="missing from spec.categories"):
showcase_schema.validate_spec(spec)
def test_report_empty_input_is_a_hard_failure(tmp_path: Path) -> None:
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "cad_showcase.py"),
"inspect",
"--input",
str(tmp_path),
"--work",
str(tmp_path / "work"),
"--output",
str(tmp_path / "report"),
],
text=True,
capture_output=True,
)
assert proc.returncode == 3
assert "all_sources_converted_and_readable" in proc.stderr
def test_inspect_resolves_relative_paths_from_invocation_directory(tmp_path: Path) -> None:
source_dir = tmp_path / "in" / "cad"
source_dir.mkdir(parents=True)
doc = ezdxf.new("R2010")
doc.modelspace().add_line((0, 0), (1000, 0), dxfattribs={"layer": "WALL"})
doc.saveas(source_dir / "plan.dxf")
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "cad_showcase.py"),
"inspect",
"--input",
"in/cad",
"--work",
"out/work",
"--output",
"out/report",
"--no-convert",
],
cwd=tmp_path,
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
report = json.loads((tmp_path / "out" / "report" / "cad_read_report.json").read_text(encoding="utf-8"))
assert report["gate"]["status"] == "PASS"
assert (tmp_path / "out" / "work" / "dxf_sanitized" / "plan.dxf").is_file()
def test_partial_report_requires_and_records_a_reason(tmp_path: Path) -> None:
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "cad_showcase.py"),
"inspect",
"--input",
str(tmp_path),
"--work",
str(tmp_path / "work"),
"--output",
str(tmp_path / "report"),
"--allow-partial",
"--partial-reason",
"inventory-only test",
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
report = json.loads((tmp_path / "report" / "cad_read_report.json").read_text(encoding="utf-8"))
assert report["gate"]["status"] == "WARN"
assert report["gate"]["partial_reason"] == "inventory-only test"
def test_no_convert_cannot_hide_dwg_sources(tmp_path: Path) -> None:
ezdxf.new("R2010").saveas(tmp_path / "readable.dxf")
(tmp_path / "unconverted.dwg").write_bytes(b"not converted")
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "cad_dxf_report.py"),
"--input",
str(tmp_path),
"--work",
str(tmp_path / "work"),
"--output",
str(tmp_path / "report"),
"--no-convert",
],
text=True,
capture_output=True,
)
assert proc.returncode == 3
report = json.loads((tmp_path / "report" / "cad_read_report.json").read_text(encoding="utf-8"))
assert "unconverted.dwg" in report["gate"]["detail"]
def test_report_refuses_to_delete_input_inside_generated_work_dir(tmp_path: Path) -> None:
work = tmp_path / "work"
source_dir = work / "dxf_raw"
source_dir.mkdir(parents=True)
source = source_dir / "roof.dxf"
ezdxf.new("R2010").saveas(source)
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "cad_dxf_report.py"),
"--input",
str(source_dir),
"--work",
str(work),
"--output",
str(tmp_path / "report"),
"--no-convert",
],
text=True,
capture_output=True,
)
assert proc.returncode != 0
assert "would be deleted before inspection" in proc.stderr
assert source.exists()
def test_variants_manifest_is_versioned(tmp_path: Path) -> None:
spec_path = tmp_path / "spec.json"
spec_path.write_text(json.dumps(minimal_spec()), encoding="utf-8")
out = tmp_path / "variants"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "build_showcase_variants.py"),
"--spec",
str(spec_path),
"--out-dir",
str(out),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
manifest = json.loads((out / "variants_manifest.json").read_text(encoding="utf-8"))
assert manifest["manifest_version"] == 1
showcase_schema.validate_manifest(manifest)
def test_massing_output_conforms_to_schema(tmp_path: Path) -> None:
outline = tmp_path / "outline.json"
outline.write_text(json.dumps([[0, 0], [10, 0], [10, 8], [0, 8]]), encoding="utf-8")
out = tmp_path / "massing.json"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "massing_from_outline.py"),
"--outline",
str(outline),
"--storeys",
"3",
"--name",
"massing",
"--out",
str(out),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
showcase_schema.validate_spec(json.loads(out.read_text(encoding="utf-8")))
def test_orchestrator_runs_resumable_trimesh_pipeline(tmp_path: Path) -> None:
input_dir = tmp_path / "dxf"
input_dir.mkdir()
doc = ezdxf.new("R2010")
doc.layers.add("WALL")
model = doc.modelspace()
for start, end in [
((0, 0), (10000, 0)),
((10000, 0), (10000, 8000)),
((10000, 8000), (0, 8000)),
((0, 8000), (0, 0)),
]:
model.add_line(start, end, dxfattribs={"layer": "WALL"})
doc.saveas(input_dir / "plan.dxf")
report_work = tmp_path / "report_work"
report_out = tmp_path / "source_report"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "cad_dxf_report.py"),
"--input",
str(input_dir),
"--work",
str(report_work),
"--output",
str(report_out),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
dxf_dir = report_work / "dxf_sanitized"
source_report = report_out / "cad_read_report.json"
config = {
"config_version": 1,
"project_name": "orchestrator-test",
"scale": 0.001,
"generate_footprints": True,
"use_footprint_slabs": True,
"layers": {"walls": ["WALL"]},
"roof_specs": [{"floor_key": "F1", "footprint_from": ["F1"], "z": 3.0, "thickness": 0.3}],
"drawings": [{"file": "plan.dxf", "floors": [{"key": "F1", "z": 0.0, "height": 3.0}]}],
}
config_path = tmp_path / "config.json"
config_path.write_text(json.dumps(config), encoding="utf-8")
out = tmp_path / "out"
scope_manifest = tmp_path / "scope_manifest.json"
scope_manifest.write_text(
json.dumps(
{
"scope_version": 1,
"mode": "single",
"requested": ["orchestrator-test"],
"buildings": [
{
"id": "orchestrator-test",
"status": "PASS",
"artifacts": [str(out / "building_spec.json")],
}
],
}
),
encoding="utf-8",
)
command = [
sys.executable,
str(ROOT / "scripts" / "cad_showcase.py"),
"run",
"--dxf-dir",
str(dxf_dir),
"--config",
str(config_path),
"--source-report",
str(source_report),
"--scope-manifest",
str(scope_manifest),
"--out-dir",
str(out),
"--name",
"orchestrator-test",
"--budget-mb",
"5",
]
proc = subprocess.run(command, text=True, capture_output=True)
assert proc.returncode == 0, proc.stderr
evidence = json.loads((out / "evidence_manifest.json").read_text(encoding="utf-8"))
assert evidence["status"] == "PASS"
assert any(check["name"] == "cad_source_report" and check["status"] == "PASS" for check in evidence["checks"])
proc = subprocess.run([*command, "--resume"], text=True, capture_output=True)
assert proc.returncode == 0, proc.stderr
assert '"status": "SKIP"' in proc.stdout
proc = subprocess.run([*command[:-1], "6", "--resume"], text=True, capture_output=True)
assert proc.returncode == 0, proc.stderr
state = json.loads((out / "pipeline_state.json").read_text(encoding="utf-8"))
assert state["steps"]["preview"]["command"][-3:] == ["--budget-mb", "6.0", "--strict"]
def test_mesh_branch_exports_y_up_glb(tmp_path: Path) -> None:
doc = ezdxf.new("R2010")
mesh = doc.modelspace().add_mesh()
with mesh.edit_data() as data:
data.vertices = [(0, 0, 0), (2, 0, 0), (2, 1, 0), (0, 1, 0), (0, 0, 3), (2, 0, 3), (2, 1, 3), (0, 1, 3)]
data.faces = [(0, 1, 2, 3), (4, 7, 6, 5), (0, 4, 5, 1), (1, 5, 6, 2), (2, 6, 7, 3), (3, 7, 4, 0)]
source = tmp_path / "mesh.dxf"
doc.saveas(source)
glb = tmp_path / "mesh.glb"
report = tmp_path / "mesh_report.json"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "extract_3d_solids.py"),
"--dxf",
str(source),
"--out-glb",
str(glb),
"--report",
str(report),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
data = json.loads(report.read_text(encoding="utf-8"))
assert data["captured_meshes"] == 1
assert data["captured_triangles"] == 12
assert glb.read_bytes()[:4] == b"glTF"
def test_dwg_json_fallback_preserves_blocks_and_inserts(tmp_path: Path) -> None:
payload = {
"insunits": 4,
"layers": [{"name": "WALL", "color": 7}],
"blocks": {
"WINDOW": [
{"t": "LINE", "a": [0, 0], "b": [1000, 0], "layer": "WALL"},
]
},
"entities": [
{"t": "LINE", "a": [0, 0], "b": [5000, 0], "layer": "WALL"},
{"t": "INSERT", "name": "WINDOW", "p": [1000, 0], "layer": "WALL"},
],
}
source = tmp_path / "dump.json"
source.write_text(json.dumps(payload), encoding="utf-8")
out = tmp_path / "rebuilt.dxf"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "dwgjson_to_dxf.py"),
"--json",
str(source),
"--out",
str(out),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
result = json.loads(proc.stdout)
assert result == {"out": str(out), "added": 2, "skipped": 0, "blocks": 1}
rebuilt = ezdxf.readfile(out)
assert "WINDOW" in rebuilt.blocks
assert [entity.dxftype() for entity in rebuilt.modelspace()] == ["LINE", "INSERT"]
def test_site_context_dump_builds_boundary_and_roads(tmp_path: Path) -> None:
payload = {
"entities": [
{
"t": "LWPOLYLINE",
"v": [[100, 200], [120, 200], [120, 215], [100, 215]],
"closed": True,
"layer": "Z2-用地红线",
},
{"t": "LINE", "a": [102, 202], "b": [118, 202], "layer": "Z5-车行道"},
]
}
source = tmp_path / "site_dump.json"
source.write_text(json.dumps(payload), encoding="utf-8")
out = tmp_path / "site_context.json"
proc = subprocess.run(
[
sys.executable,
str(ROOT / "scripts" / "site_context_from_dump.py"),
"--dump",
str(source),
"--scale",
"1",
"--region",
"95",
"195",
"125",
"220",
"--origin",
"100",
"200",
"--out",
str(out),
],
text=True,
capture_output=True,
)
assert proc.returncode == 0, proc.stderr
fragment = json.loads(out.read_text(encoding="utf-8"))
assert set(fragment["floors"]) == {"SITE", "ROADS"}
assert fragment["floors"]["SITE"]["footprint"]["polygons"][0][0] == [0, 0]
assert len(fragment["floors"]["ROADS"]["segments"]["floor_lines"]) == 4
assert len(fragment["floors"]["ROADS"]["segments"]["detail_lines"]) == 1

608
tests/test_delivery.py Normal file
View File

@@ -0,0 +1,608 @@
from __future__ import annotations
import json
import subprocess
import sys
from pathlib import Path
from PIL import Image, ImageDraw
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import showcase_schema # noqa: E402
from test_contracts import minimal_spec # noqa: E402
def run(*args: str) -> subprocess.CompletedProcess[str]:
return subprocess.run(list(args), cwd=ROOT, text=True, capture_output=True)
def build_fixture(tmp_path: Path) -> tuple[Path, Path, Path]:
spec = tmp_path / "spec.json"
glb = tmp_path / "model.glb"
metadata = tmp_path / "model_metadata.json"
spec.write_text(json.dumps(minimal_spec()), encoding="utf-8")
proc = run(
sys.executable,
"scripts/spec_to_glb.py",
"--spec",
str(spec),
"--out",
str(glb),
"--metadata-out",
str(metadata),
)
assert proc.returncode == 0, proc.stderr
return spec, glb, metadata
def render_fixture(path: Path) -> None:
image = Image.new("RGB", (640, 480), "white")
draw = ImageDraw.Draw(image)
draw.rectangle((100, 120, 540, 400), fill="#4477aa", outline="black", width=4)
image.save(path)
def source_report_fixture(tmp_path: Path) -> Path:
path = tmp_path / "cad_read_report.json"
path.write_text(
json.dumps(
{
"report_version": 1,
"dxf_sanitized": str(tmp_path),
"gate": {"name": "all_sources_converted_and_readable", "status": "PASS"},
"files": [{"file": "fixture.dxf", "status": "ok", "modelspace_entities": 1}],
}
),
encoding="utf-8",
)
return path
def browser_report_payload(*, offline: bool = False) -> dict:
if offline:
checks = [
{"name": "offline:viewport", "status": "PASS", "detail": "1440x900 expected 1440x900"},
{"name": "offline:model-ready", "status": "PASS", "detail": "1 mesh(es)"},
{"name": "offline:canvas", "status": "PASS"},
{"name": "offline:render", "status": "PASS", "detail": "1 render(s)"},
]
else:
checks = []
for viewport, detail in (
("desktop", "1440x900 expected 1440x900"),
("mobile", "390x844 expected 390x844"),
):
checks.append({"name": f"{viewport}:viewport", "status": "PASS", "detail": detail})
for selector in ("#floor-controls", "#category-controls", "#explode", "#section", "#snapshot"):
checks.append({"name": f"{viewport}:{selector}", "status": "PASS"})
checks.append({"name": f"{viewport}:idle-render", "status": "PASS", "detail": "3->3"})
return {
"status": "PASS",
"detail": f"{len(checks)}/{len(checks)} checks passed",
"checks": checks,
"console_errors": [],
"page_errors": [],
"failed_requests": [],
}
def test_strict_delivery_passes_for_glb_render_and_offline_viewer(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
render = tmp_path / "render.png"
render_fixture(render)
offline = tmp_path / "viewer.html"
proc = run(
sys.executable,
"scripts/write_offline_viewer.py",
"--spec",
str(spec),
"--glb",
str(glb),
"--out",
str(offline),
)
assert proc.returncode == 0, proc.stderr
offline_browser_report = tmp_path / "offline_browser_smoke_report.json"
offline_browser_report.write_text(
json.dumps(browser_report_payload(offline=True)),
encoding="utf-8",
)
evidence = tmp_path / "evidence.json"
source_report = source_report_fixture(tmp_path)
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--offline-viewer",
str(offline),
"--offline-browser-report",
str(offline_browser_report),
"--evidence-out",
str(evidence),
)
assert proc.returncode == 0, proc.stderr
report = json.loads(evidence.read_text(encoding="utf-8"))
assert report["status"] == "PASS"
assert any(item["name"] == "offline:payload" and item["status"] == "PASS" for item in report["checks"])
assert any(item["name"] == "offline:browser-smoke" and item["status"] == "PASS" for item in report["checks"])
def test_browser_report_cannot_forge_pass_without_required_checks(tmp_path: Path) -> None:
import verify_delivery
path = tmp_path / "forged.json"
path.write_text(
json.dumps(
{
"status": "PASS",
"checks": [],
"console_errors": [],
"page_errors": [],
"failed_requests": [],
}
),
encoding="utf-8",
)
checks: list[dict] = []
verify_delivery.inspect_browser_report(path, checks)
assert checks[0]["status"] == "FAIL"
assert "non-empty list" in checks[0]["detail"]
def test_render_gate_rejects_high_variance_noise(tmp_path: Path) -> None:
import verify_delivery
noisy = Image.new("RGB", (640, 480))
pixels = noisy.load()
for y in range(noisy.height):
for x in range(noisy.width):
pixels[x, y] = (255, 255, 255) if (x + y) % 2 else (0, 0, 0)
path = tmp_path / "noise.png"
noisy.save(path)
checks: list[dict] = []
verify_delivery.inspect_render(path, checks)
assert checks[0]["status"] == "FAIL"
def test_offline_viewer_without_real_browser_report_is_blocked(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
render = tmp_path / "render.png"
render_fixture(render)
offline = tmp_path / "viewer.html"
proc = run(
sys.executable,
"scripts/write_offline_viewer.py",
"--spec",
str(spec),
"--glb",
str(glb),
"--out",
str(offline),
)
assert proc.returncode == 0, proc.stderr
source_report = source_report_fixture(tmp_path)
evidence = tmp_path / "evidence.json"
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--offline-viewer",
str(offline),
"--evidence-out",
str(evidence),
)
assert proc.returncode == 3
report = json.loads(evidence.read_text(encoding="utf-8"))
assert report["status"] == "BLOCKED"
assert any(item["name"] == "offline:browser-smoke" and item["status"] == "SKIP" for item in report["checks"])
def test_offline_viewer_escapes_html_and_inline_script_data(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
document = json.loads(spec.read_text(encoding="utf-8"))
document["project"]["name"] = '<Tower & Co></script><script>alert("title")</script>'
document["floors"]["F1"]["name"] = '首层</script><script>alert("floor")</script>'
document["categories"]["walls"]["label"] = "墙<&>"
spec.write_text(json.dumps(document), encoding="utf-8")
offline = tmp_path / "viewer.html"
proc = run(
sys.executable,
"scripts/write_offline_viewer.py",
"--spec",
str(spec),
"--glb",
str(glb),
"--out",
str(offline),
"--subtitle",
"<unsafe & subtitle>",
)
assert proc.returncode == 0, proc.stderr
text = offline.read_text(encoding="utf-8")
assert "&lt;Tower &amp; Co&gt;&lt;/script&gt;" in text
assert "&lt;unsafe &amp; subtitle&gt;" in text
assert '首层<\\/script><script>alert(\\"floor\\")<\\/script>' in text
assert '首层</script><script>alert("floor")</script>' not in text
def test_web_variant_entry_requires_a_nonempty_file(tmp_path: Path) -> None:
import verify_delivery
web = tmp_path / "web"
for relative in (
"index.html",
"app.js",
"styles.css",
"model.glb",
"node_modules/three/build/three.module.js",
"node_modules/lucide/dist/umd/lucide.js",
):
target = web / relative
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(
"window.__renders; invalidate(); DRACOLoader; restoreStateFromHash; switchVariant", encoding="utf-8"
)
(web / "model_metadata.json").write_text(json.dumps({"model_variants": [{"key": "standard", "file": ""}]}))
checks: list[dict] = []
verify_delivery.inspect_web(web, checks)
variant_check = next(item for item in checks if item["name"] == "web:variants")
assert variant_check["status"] == "FAIL"
assert "<missing file>" in variant_check["detail"]
def test_strict_delivery_requires_a_render(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
source_report = source_report_fixture(tmp_path)
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--evidence-out",
str(tmp_path / "evidence.json"),
)
assert proc.returncode == 3
assert "At least one inspected render is required" in proc.stderr
def test_web_writer_and_static_delivery_checks(tmp_path: Path) -> None:
spec, glb, metadata = build_fixture(tmp_path)
web = tmp_path / "web"
proc = run(
sys.executable,
"scripts/write_web_showcase.py",
"--glb",
str(glb),
"--metadata",
str(metadata),
"--out-dir",
str(web),
)
assert proc.returncode == 0, proc.stderr
for relative in ("node_modules/three/build/three.module.js", "node_modules/lucide/dist/umd/lucide.js"):
target = web / relative
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text("// test dependency", encoding="utf-8")
render = tmp_path / "render.png"
render_fixture(render)
source_report = source_report_fixture(tmp_path)
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--web-dir",
str(web),
"--evidence-out",
str(tmp_path / "web_evidence.json"),
)
assert proc.returncode == 3
assert "browser:smoke" in proc.stderr
browser_report = tmp_path / "browser_smoke_report.json"
browser_report.write_text(
json.dumps(browser_report_payload()),
encoding="utf-8",
)
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--web-dir",
str(web),
"--browser-report",
str(browser_report),
"--evidence-out",
str(tmp_path / "web_evidence.json"),
)
assert proc.returncode == 0, proc.stderr
def test_reasoned_partial_source_can_only_pass_with_named_waiver(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
render = tmp_path / "render.png"
render_fixture(render)
source_report = source_report_fixture(tmp_path)
source = json.loads(source_report.read_text(encoding="utf-8"))
source["gate"] = {
"name": "all_sources_converted_and_readable",
"status": "WARN",
"detail": "one optional elevation is missing",
"partial_reason": "User approved plan-only delivery",
}
source_report.write_text(json.dumps(source), encoding="utf-8")
evidence = tmp_path / "evidence.json"
base = [
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--evidence-out",
str(evidence),
]
proc = run(*base)
assert proc.returncode == 3
assert json.loads(evidence.read_text(encoding="utf-8"))["status"] == "BLOCKED"
proc = run(*base, "--waiver", "cad_source_report=User approved plan-only delivery")
assert proc.returncode == 0, proc.stderr
report = json.loads(evidence.read_text(encoding="utf-8"))
source_check = next(item for item in report["checks"] if item["name"] == "cad_source_report")
assert source_check["original_status"] == "WARN"
def test_warn_or_skip_blocks_without_explicit_reasoned_waiver(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
render = tmp_path / "render.png"
render_fixture(render)
source_report = source_report_fixture(tmp_path)
evidence = tmp_path / "evidence.json"
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--require-browser-report",
"--evidence-out",
str(evidence),
)
assert proc.returncode == 3
assert json.loads(evidence.read_text(encoding="utf-8"))["status"] == "BLOCKED"
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--require-browser-report",
"--waiver",
"browser:smoke=No browser is available in this offline-only benchmark",
"--evidence-out",
str(evidence),
)
assert proc.returncode == 0, proc.stderr
report = json.loads(evidence.read_text(encoding="utf-8"))
smoke = next(item for item in report["checks"] if item["name"] == "browser:smoke")
assert smoke["status"] == "PASS"
assert smoke["original_status"] == "SKIP"
assert smoke["waiver_reason"]
def test_campus_scope_cannot_pass_with_a_missing_requested_building(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
render = tmp_path / "render.png"
render_fixture(render)
source_report = source_report_fixture(tmp_path)
site = tmp_path / "site.png"
render_fixture(site)
scope = tmp_path / "scope_manifest.json"
scope.write_text(
json.dumps(
{
"scope_version": 1,
"mode": "campus",
"requested": ["1#", "2#"],
"buildings": [
{"id": "1#", "status": "PASS", "artifacts": [glb.name]},
{"id": "2#", "status": "BLOCKED", "reason": "No readable source drawing", "artifacts": []},
],
"site": {"status": "PASS", "artifacts": [site.name]},
}
),
encoding="utf-8",
)
evidence = tmp_path / "evidence.json"
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--scope-manifest",
str(scope),
"--evidence-out",
str(evidence),
)
assert proc.returncode == 3
report = json.loads(evidence.read_text(encoding="utf-8"))
assert report["status"] == "BLOCKED"
assert any(item["name"] == "scope:building:2#" and item["status"] == "WARN" for item in report["checks"])
def test_scope_rejects_arbitrary_nonempty_artifact(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
render = tmp_path / "render.png"
render_fixture(render)
source_report = source_report_fixture(tmp_path)
fake = tmp_path / "looks-done.txt"
fake.write_text("not a model", encoding="utf-8")
scope = tmp_path / "scope_manifest.json"
scope.write_text(
json.dumps(
{
"scope_version": 1,
"mode": "single",
"requested": ["11#"],
"buildings": [{"id": "11#", "status": "PASS", "artifacts": [fake.name]}],
}
),
encoding="utf-8",
)
evidence = tmp_path / "evidence.json"
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--scope-manifest",
str(scope),
"--evidence-out",
str(evidence),
)
assert proc.returncode == 3
report = json.loads(evidence.read_text(encoding="utf-8"))
check = next(item for item in report["checks"] if item["name"] == "scope:building:11#")
assert check["status"] == "FAIL"
assert "No verifiable" in check["detail"]
def test_required_audit_and_scope_cannot_be_omitted(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
render = tmp_path / "render.png"
render_fixture(render)
source_report = source_report_fixture(tmp_path)
evidence = tmp_path / "evidence.json"
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--spec",
str(spec),
"--source-report",
str(source_report),
"--glb",
str(glb),
"--render",
str(render),
"--require-audit",
"--require-scope-manifest",
"--evidence-out",
str(evidence),
)
assert proc.returncode == 3
failed = {
item["name"] for item in json.loads(evidence.read_text(encoding="utf-8"))["checks"] if item["status"] == "FAIL"
}
assert {"audit:report", "scope:manifest"} <= failed
def test_variants_manifest_requires_metadata_artifact(tmp_path: Path) -> None:
spec, glb, _metadata = build_fixture(tmp_path)
render = tmp_path / "render.png"
render_fixture(render)
source_report = source_report_fixture(tmp_path)
manifest = tmp_path / "variants_manifest.json"
manifest.write_text(
json.dumps(
{
"manifest_version": 1,
"name": "missing-metadata",
"default_key": "standard",
"variants": [
{
"key": "standard",
"label": "standard",
"file": glb.name,
"source_glb": glb.name,
"metadata": "missing_metadata.json",
"spec": spec.name,
}
],
}
),
encoding="utf-8",
)
proc = run(
sys.executable,
"scripts/verify_delivery.py",
"--source-report",
str(source_report),
"--spec",
str(spec),
"--variants-manifest",
str(manifest),
"--render",
str(render),
"--evidence-out",
str(tmp_path / "evidence.json"),
)
assert proc.returncode == 3
assert "missing_metadata.json" in proc.stderr
def test_schema_validator_rejects_legacy_spec_in_strict_mode() -> None:
legacy = minimal_spec()
legacy.pop("schema_version")
try:
showcase_schema.validate_spec(legacy)
except showcase_schema.ValidationFailure:
return
raise AssertionError("strict validator accepted a spec without schema_version")

File diff suppressed because it is too large Load Diff