Files
cad-building-showcase/assets/web-showcase-template/app.js
zhengwr 6ace84ffba Campus pipeline hardening: backend parity, wall union, mullion grids, Draco tooling
Sandbox round (Linux):
- detect_sheet_frames.py: multi-frame sheet splitter (column AND row layouts),
  grid-vote per-floor offsets, section-elevation harvesting for storey heights
- dwg_dump_json.mjs + dwgjson_to_dxf.py: WASM libredwg DWG->DXF fallback
  (blocks/INSERT preserved, ATTRIB->TEXT so axis labels survive)
- assemble_campus.py: manifest-driven campus assembly with mandatory
  neighbour-gap gate (overlap = exit 3, 0.1-0.3m flagged as expansion joints)
- site_context_from_dump.py: site-context floors (ground/roads/parking/
  fence/trees/context massings) from site-plan dumps
- write_offline_viewer.py + assets/offline-viewer-libs/: fully-offline
  single-file viewer (vendored three r147 + pako, gzip-embedded GLB)
- audit: clip-scoped coverage figures; report: multi_frame_sheet warning;
  audit gate floors_aligned catches the diagonal-staircase failure mode

Mac round:
- build_blender_showcase.py now honors slab_bounds_fallback and prefers
  footprint polygons for generated roofs (bounds rects made roof plates jut
  past the facade and buried campuses under full-extent slabs); contract now
  matches spec_to_glb.py exactly
- merge_wall_solids (default off) in BOTH backends: shapely union in
  spec_to_glb.py, native delaunay_2d_cdt union in Blender; endpoint-shared
  wall ends pre-extended w/2 so L-corners close seamlessly (flat caps leave
  a notch a union alone cannot fill) while openings stay flat
- glazing_mullions (default off): curtain-wall panel grid (verticals every
  glazing_panel_w + floor-line transoms) as pseudo wall segments in the
  <floor>__walls node; glass pane kept
- build_showcase_variants.py keeps source_file=="site" floors intact in all
  variants (roads/trees live on filtered categories)
- web template: instanced low-poly trees from metadata site_trees,
  grade-level shadow catcher (was at basement depth), data-URI favicon
- tools/compress.mjs deps pinned (package.json); 15MB campus GLB -> 0.57MB
- tests: 24 -> 52 checks (wall union, mullions, byte-identical defaults)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 17:44:41 +08:00

508 lines
18 KiB
JavaScript

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";
import { RoomEnvironment } from "three/addons/environments/RoomEnvironment.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, 0.9));
// Image-based lighting: cheap, no HDR download, transforms material readability.
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
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);
keyLight.position.set(-45, 85, 62);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x9fd4ff, 0.9);
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;
}
if (parsed.category === "trees" && meta.site_trees?.length) {
mesh.visible = false; // replaced by instanced trunk+crown trees below
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);
}
if (meta.site_trees?.length) addInstancedTrees(meta.site_trees);
state.bounds = new THREE.Box3().setFromObject(modelRoot);
fitShadowsAndGround(state.bounds);
}
function addInstancedTrees(points) {
// spec plan coords (x, y) -> Y-up world (x, ?, -y), same mapping as the GLB export
const trunk = new THREE.InstancedMesh(
new THREE.CylinderGeometry(0.14, 0.2, 1.4, 6),
new THREE.MeshStandardMaterial({ color: 0x6b4a2e, roughness: 0.9, clippingPlanes: [sectionPlane] }),
points.length,
);
const crown = new THREE.InstancedMesh(
new THREE.IcosahedronGeometry(1.5, 1),
new THREE.MeshStandardMaterial({ color: 0x3e7d4f, roughness: 0.8, clippingPlanes: [sectionPlane] }),
points.length,
);
const matrix = new THREE.Matrix4();
points.forEach(([x, y], index) => {
matrix.setPosition(x, 0.7, -y);
trunk.setMatrixAt(index, matrix);
matrix.setPosition(x, 2.2, -y);
crown.setMatrixAt(index, matrix);
});
trunk.castShadow = crown.castShadow = true;
crown.receiveShadow = true;
const group = floorGroups.get("TREES");
(group || modelRoot).add(trunk, crown);
}
function fitShadowsAndGround(bounds) {
// Default directional-shadow frustum is ±5 m — useless for buildings.
const center = bounds.getCenter(new THREE.Vector3());
const size = bounds.getSize(new THREE.Vector3());
const radius = Math.max(size.x, size.z, 20) * 0.75;
keyLight.target.position.copy(center);
scene.add(keyLight.target);
Object.assign(keyLight.shadow.camera, {
left: -radius, right: radius, top: radius, bottom: -radius, near: 5, far: radius * 6,
});
keyLight.shadow.camera.updateProjectionMatrix();
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(radius * 8, radius * 8),
new THREE.ShadowMaterial({ opacity: 0.32 }),
);
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;
ground.position.set(center.x, groundY, center.z);
ground.receiveShadow = true;
scene.add(ground);
}
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");
if (category === "glazing") {
// Physical glass (transmission) instead of flat alpha — key perceived-quality win.
const glass = new THREE.MeshPhysicalMaterial({
color, metalness: 0, roughness: 0.18, transmission: 0.7, ior: 1.5, thickness: 0.3,
transparent: true, depthWrite: false, side: THREE.DoubleSide, clippingPlanes: [sectionPlane],
});
glass.envMapIntensity = 1.2;
materialByCategory.set(category, glass);
return glass;
}
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();