Initial commit: cad-building-showcase skill

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

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

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

View File

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

View File

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

View File

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

View File

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