Files
zhengwr 919b35391d
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
fix: tighten viewer framing and localize site controls
2026-07-21 21:10:43 +08:00

992 lines
38 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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";
import { mergeGeometries } from "three/addons/utils/BufferGeometryUtils.js";
// ───────────────────────── DOM ─────────────────────────
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 variantControls = document.querySelector("#variant-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 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 = [
"slab", "roof", "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 floorGroups = new Map();
const buildingGroups = new Map(); // building key -> Set of floor keys
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 = {
floors: {},
categories: {},
autoRotate: false,
selected: null,
bounds: null,
};
// ───────────────────────── Scene Setup ─────────────────────────
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;
// Static scene: bake shadows once per change, not per frame.
renderer.shadowMap.autoUpdate = false;
renderer.shadowMap.needsUpdate = true;
renderer.localClippingEnabled = true;
const camera = new THREE.PerspectiveCamera(36, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.up.set(0, 1, 0);
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.08;
controls.screenSpacePanning = true;
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));
const pmrem = new THREE.PMREMGenerator(renderer);
scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
if ("environmentIntensity" in scene) scene.environmentIntensity = 0.85;
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);
// ───────────────────────── Metadata + Init ─────────────────────────
const metadata = await fetch(`./model_metadata.json?v=${CACHE_BUST}`).then((r) => r.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 展示模型";
// 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);
buildInterface(metadata);
restoreStateFromHash();
// ───────────────────────── Progressive Loading ─────────────────────────
const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath("./node_modules/three/examples/jsm/libs/draco/");
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(
`./${firstFile}?v=${CACHE_BUST}`,
(gltf) => {
ingestModel(gltf.scene, metadata, firstTag);
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");
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) => {
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();
// ───────────────────────── State Init ─────────────────────────
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);
}
// ───────────────────────── Interface Builder ─────────────────────────
function buildInterface(meta) {
buildFloorControls(meta);
buildCategoryControls(meta);
buildDownloadControls(meta);
buildVariantControls(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));
serializeStateToHash();
});
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");
serializeStateToHash();
});
autoRotateButton.addEventListener("click", () => {
state.autoRotate = !state.autoRotate;
autoRotateButton.classList.toggle("active", state.autoRotate);
controls.autoRotate = state.autoRotate;
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);
}
// ───────────────────────── 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) {
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;
}),
);
}
// ───────────────────────── 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 }) {
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;
}
// ───────────────────────── 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 || []) {
let group = floorGroups.get(floor.key);
if (!group) {
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);
});
// Collect meshes by (floor, category) for merging
const mergeBuckets = new Map(); // "floor__category" -> { geometries: [], floor, category }
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;
continue;
}
const category = parsed.category;
if (!categoryOrder.includes(category)) {
floorGroups.get(parsed.floor).add(mesh);
continue;
}
// Assign material before merging
const material = materialForCategory(category, meta);
// 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);
}
}
if (meta.site_trees?.length) addInstancedTrees(meta.site_trees);
state.bounds = new THREE.Box3().setFromObject(modelRoot);
fitShadowsAndGround(state.bounds);
invalidate({ shadows: true });
}
function addInstancedTrees(points) {
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) {
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;
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);
}
// ───────────────────────── Name Parsing ─────────────────────────
function parseObjectName(name) {
const match = name.match(/^(.+)__(.+)$/);
if (!match) return null;
const category = match[2].replace(/\.\d+$/, "");
return { floor: match[1], category };
}
function labelForObject({ floor, category }) {
return `${floor} ${metadata.categories?.[category]?.label || category}`;
}
// ───────────────────────── Materials ─────────────────────────
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") {
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 === "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);
}
// ───────────────────────── Explode / Section / Visibility ─────────────────────────
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;
}
updateStats();
invalidate({ shadows: true });
}
function applySection(height) {
const max = Number(sectionInput.max);
sectionPlane.constant = height >= max ? 9999 : height;
sectionValue.textContent = height >= max ? "关闭" : `${height.toFixed(2)}m`;
invalidate({ shadows: true });
}
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) {
group.visible = Boolean(state.floors[floorKey]);
}
updateStats();
invalidate({ shadows: true });
}
// ───────────────────────── Stats (with draw call count) ─────────────────────────
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);
// 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 = "";
for (const item of [
["楼层", `${activeFloors}/${(metadata.floors || []).length}`],
["构件", `${activeCategories}/${categoryOrder.length}`],
["顶点", vertices.toLocaleString("zh-CN")],
["绘制批次", drawCalls.toString()],
]) {
const cell = document.createElement("div");
cell.innerHTML = `<dt>${item[0]}</dt><dd>${item[1]}</dd>`;
stats.append(cell);
}
}
// ───────────────────────── Camera ─────────────────────────
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.22, center.z);
} else if (preset === "side") {
camera.position.set(center.x, center.y + maxSize * 0.18, center.z + maxSize * 1.15);
} else {
// 园区模型默认占据更多画面;OrbitControls 仍允许用户自由拉远。
const d = maxSize * 1.15;
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();
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() {
const link = document.createElement("a");
link.download = "cad-building-showcase.png";
link.href = renderer.domElement.toDataURL("image/png");
link.click();
}
// ───────────────────────── Raycast Picking ─────────────────────────
window.addEventListener("pointerdown", (event) => {
// Ignore clicks on UI panels
if (event.target !== canvas) return;
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;
const mergedInfo = object.userData.mergedCount ? ` (${object.userData.mergedCount} 合并)` : "";
inspect.querySelector(".inspect-body").textContent = `楼层 ${object.userData.floor} / 类别 ${object.userData.category}${mergedInfo}`;
});
// ───────────────────────── Resize ─────────────────────────
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// ───────────────────────── Animation Loop ─────────────────────────
function animate() {
requestAnimationFrame(animate);
const moved = controls.update(); // true while damping/autoRotate move the camera
if (pendingCameraRestore && modelRoot.children.length > 0) {
applyPendingCamera();
invalidate();
}
if (moved || renderPending) {
renderer.render(scene, camera);
window.__renders += 1;
renderPending = false;
}
}
animate();