|
|
|
|
@@ -3,7 +3,9 @@ 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");
|
|
|
|
|
@@ -11,6 +13,7 @@ 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");
|
|
|
|
|
@@ -18,23 +21,34 @@ 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",
|
|
|
|
|
"slab", "roof", "walls", "glazing", "columns", "beams",
|
|
|
|
|
"railings", "doors", "detail_lines", "floor_lines", "grid",
|
|
|
|
|
];
|
|
|
|
|
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: {},
|
|
|
|
|
@@ -43,14 +57,12 @@ const state = {
|
|
|
|
|
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,
|
|
|
|
|
canvas, antialias: true, alpha: false, preserveDrawingBuffer: true,
|
|
|
|
|
});
|
|
|
|
|
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
|
|
|
|
renderer.setSize(window.innerWidth, window.innerHeight);
|
|
|
|
|
@@ -58,24 +70,37 @@ 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); // 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);
|
|
|
|
|
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));
|
|
|
|
|
|
|
|
|
|
// 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;
|
|
|
|
|
@@ -93,23 +118,53 @@ 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 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]);
|
|
|
|
|
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/"); // shipped with three; works offline
|
|
|
|
|
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(
|
|
|
|
|
"./model.glb?v={{BUILD}}",
|
|
|
|
|
`./${firstFile}?v=${CACHE_BUST}`,
|
|
|
|
|
(gltf) => {
|
|
|
|
|
ingestModel(gltf.scene, metadata);
|
|
|
|
|
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);
|
|
|
|
|
@@ -120,12 +175,54 @@ loader.load(
|
|
|
|
|
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}%`;
|
|
|
|
|
loadingText.textContent = `加载总览模型 ${pct}%`;
|
|
|
|
|
},
|
|
|
|
|
(error) => {
|
|
|
|
|
loadingText.textContent = "模型加载失败";
|
|
|
|
|
@@ -135,43 +232,19 @@ loader.load(
|
|
|
|
|
|
|
|
|
|
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) {
|
|
|
|
|
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();
|
|
|
|
|
},
|
|
|
|
|
}),
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
buildFloorControls(meta);
|
|
|
|
|
buildCategoryControls(meta);
|
|
|
|
|
buildDownloadControls(meta);
|
|
|
|
|
buildVariantControls(meta);
|
|
|
|
|
|
|
|
|
|
explodeInput.addEventListener("input", () => {
|
|
|
|
|
const value = Number(explodeInput.value);
|
|
|
|
|
@@ -179,7 +252,10 @@ function buildInterface(meta) {
|
|
|
|
|
applyExplode(value);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
sectionInput.addEventListener("input", () => applySection(Number(sectionInput.value)));
|
|
|
|
|
sectionInput.addEventListener("input", () => {
|
|
|
|
|
applySection(Number(sectionInput.value));
|
|
|
|
|
serializeStateToHash();
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
document.querySelectorAll("[data-preset]").forEach((button) => {
|
|
|
|
|
button.addEventListener("click", () => fitCamera(button.dataset.preset));
|
|
|
|
|
@@ -193,6 +269,7 @@ function buildInterface(meta) {
|
|
|
|
|
applyExplode(0);
|
|
|
|
|
applySection(Number(sectionInput.max));
|
|
|
|
|
fitCamera("overview");
|
|
|
|
|
serializeStateToHash();
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
autoRotateButton.addEventListener("click", () => {
|
|
|
|
|
@@ -202,9 +279,141 @@ function buildInterface(meta) {
|
|
|
|
|
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: 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
|
|
|
|
|
@@ -222,6 +431,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 }) {
|
|
|
|
|
const root = document.createElement("label");
|
|
|
|
|
root.className = "toggle";
|
|
|
|
|
@@ -243,12 +510,35 @@ function createToggle({ key, label, color, checked, onChange }) {
|
|
|
|
|
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 || []) {
|
|
|
|
|
const group = new THREE.Group();
|
|
|
|
|
group.name = floor.key;
|
|
|
|
|
floorGroups.set(floor.key, group);
|
|
|
|
|
modelRoot.add(group);
|
|
|
|
|
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);
|
|
|
|
|
@@ -257,6 +547,9 @@ function ingestModel(gltfScene, meta) {
|
|
|
|
|
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);
|
|
|
|
|
@@ -270,30 +563,75 @@ function ingestModel(gltfScene, meta) {
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
if (parsed.category === "trees" && meta.site_trees?.length) {
|
|
|
|
|
mesh.visible = false; // replaced by instanced trunk+crown trees below
|
|
|
|
|
mesh.visible = false;
|
|
|
|
|
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);
|
|
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
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);
|
|
|
|
|
invalidate({ shadows: true });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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] }),
|
|
|
|
|
@@ -318,7 +656,6 @@ function addInstancedTrees(points) {
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
@@ -333,19 +670,16 @@ function fitShadowsAndGround(bounds) {
|
|
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ───────────────────────── Name Parsing ─────────────────────────
|
|
|
|
|
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 };
|
|
|
|
|
}
|
|
|
|
|
@@ -354,11 +688,11 @@ 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") {
|
|
|
|
|
// 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],
|
|
|
|
|
@@ -368,26 +702,16 @@ function materialForCategory(category, meta) {
|
|
|
|
|
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;
|
|
|
|
|
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,
|
|
|
|
|
color, transparent: opacity < 1, opacity,
|
|
|
|
|
depthWrite: category === "slab" ? true : opacity >= 0.8,
|
|
|
|
|
roughness: 0.74,
|
|
|
|
|
metalness: 0.02,
|
|
|
|
|
roughness: 0.74, metalness: 0.02,
|
|
|
|
|
side: category === "slab" || category === "roof" ? THREE.DoubleSide : THREE.FrontSide,
|
|
|
|
|
clippingPlanes: [sectionPlane],
|
|
|
|
|
});
|
|
|
|
|
@@ -404,41 +728,53 @@ function addEdges(mesh, category) {
|
|
|
|
|
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; // Y-up: explode floors along Y
|
|
|
|
|
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.entries()) {
|
|
|
|
|
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")],
|
|
|
|
|
["Draw Calls", drawCalls.toString()],
|
|
|
|
|
]) {
|
|
|
|
|
const cell = document.createElement("div");
|
|
|
|
|
cell.innerHTML = `<dt>${item[0]}</dt><dd>${item[1]}</dd>`;
|
|
|
|
|
@@ -446,6 +782,7 @@ function updateStats() {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ───────────────────────── Camera ─────────────────────────
|
|
|
|
|
function fitCamera(preset) {
|
|
|
|
|
const box = new THREE.Box3().setFromObject(modelRoot);
|
|
|
|
|
state.bounds = box;
|
|
|
|
|
@@ -457,7 +794,6 @@ function fitCamera(preset) {
|
|
|
|
|
} 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);
|
|
|
|
|
@@ -467,8 +803,120 @@ function fitCamera(preset) {
|
|
|
|
|
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 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 = btoa(JSON.stringify(hash)).replace(/=/g, "");
|
|
|
|
|
history.replaceState(null, "", `#${encoded}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function restoreStateFromHash() {
|
|
|
|
|
try {
|
|
|
|
|
const raw = window.location.hash.slice(1);
|
|
|
|
|
if (!raw) return;
|
|
|
|
|
const hash = JSON.parse(atob(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";
|
|
|
|
|
@@ -476,7 +924,10 @@ function downloadSnapshot() {
|
|
|
|
|
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);
|
|
|
|
|
@@ -489,19 +940,30 @@ window.addEventListener("pointerdown", (event) => {
|
|
|
|
|
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}`;
|
|
|
|
|
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);
|
|
|
|
|
controls.update();
|
|
|
|
|
renderer.render(scene, camera);
|
|
|
|
|
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();
|
|
|
|
|
|