/* global THREE, OCCUPANCY_DATA */
(function () {
"use strict";
const data = window.OCCUPANCY_DATA;
const $ = (id) => document.getElementById(id);
const fmtInt = new Intl.NumberFormat("en-US");
function showError(message) {
const el = $("error");
if (!el) return;
el.hidden = false;
el.innerHTML = message;
const loading = $("loading");
if (loading) loading.classList.add("hidden");
}
if (!data) {
showError(
"没有找到 web/data.js。
请先在项目根目录运行:" +
"ven/bin/python src/inference.py
" +
"然后重新打开本页(或运行 python src/serve.py)。"
);
return;
}
const meta = data.meta;
const VREF = meta.volumeRefM3;
// ---------------------------------------------------------------- helpers
function b64bytes(b64) {
const bin = atob(b64);
const out = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
return out;
}
function decodeF32(b64) {
return new Float32Array(b64bytes(b64).buffer);
}
function decodeU32(b64) {
return new Uint32Array(b64bytes(b64).buffer);
}
function decodeU16(b64) {
return new Uint16Array(b64bytes(b64).buffer);
}
function clamp(v, lo, hi) {
return Math.max(lo, Math.min(hi, v));
}
function pct(v, digits) {
return (v * 100).toFixed(digits == null ? 1 : digits);
}
function signedPct(v, digits) {
const s = (v * 100).toFixed(digits == null ? 1 : digits);
return (v > 0 ? "+" : "") + s;
}
// ------------------------------------------------------------------ state
const defaultIndex = Math.max(
0,
data.sizes.findIndex((s) => s.sizeCm === meta.defaultSizeCm)
);
const state = {
sizeIndex: defaultIndex,
threshold: clamp(meta.defaultThresholdPct / 100, 0, 1),
cubeMode: "aabb",
showCar: true,
showVoxels: true,
showCube: true,
showGrid: true,
autoRotate: false,
viewMode: "car",
};
let current = null;
const sizeCache = new Map();
// ------------------------------------------------------------- size data
function getSizeData(index) {
if (sizeCache.has(index)) return sizeCache.get(index);
const sd = data.sizes[index];
const dims = sd.dims;
const indices = decodeU32(sd.indicesB64);
const rawFrac = decodeU16(sd.fractionsB64);
const n = indices.length;
// Sorting by fraction descending turns "fraction >= threshold" into a
// prefix of the instance buffer, so changing the threshold only needs
// `mesh.count = prefixLength` — no per-instance matrix update.
const order = new Array(n);
for (let i = 0; i < n; i++) order[i] = i;
order.sort((a, b) => rawFrac[b] - rawFrac[a]);
const positions = new Float32Array(n * 3);
const colors = new Float32Array(n * 3);
const fracs = new Uint16Array(n);
const origin = sd.originM;
const s = sd.sizeM;
const zmin = meta.bboxMinMm[2] / 1000;
const zmax = meta.bboxMaxMm[2] / 1000;
const zspan = Math.max(1e-6, zmax - zmin);
const col = new THREE.Color();
for (let q = 0; q < n; q++) {
const src = order[q];
const idx = indices[src];
const k = idx % dims[2];
const t = Math.floor(idx / dims[2]);
const j = t % dims[1];
const i = Math.floor(t / dims[1]);
const x = origin[0] + (i + 0.5) * s;
const y = origin[1] + (j + 0.5) * s;
const z = origin[2] + (k + 0.5) * s;
positions[q * 3] = x;
positions[q * 3 + 1] = y;
positions[q * 3 + 2] = z;
const h = clamp((z - zmin) / zspan, 0, 1);
col.setHSL(0.56 - 0.52 * h, 0.95, 0.5);
colors[q * 3] = col.r;
colors[q * 3 + 1] = col.g;
colors[q * 3 + 2] = col.b;
fracs[q] = rawFrac[src];
}
// Histograms: suffix sums give N(t) and sum(fraction) for any threshold.
const count = new Uint32Array(1001);
const sumFrac = new Float64Array(1001);
for (let q = 0; q < n; q++) {
const f = fracs[q];
count[f] += 1;
sumFrac[f] += f;
}
const nGe = new Float64Array(1001);
const fGe = new Float64Array(1001);
let nc = 0;
let fs = 0;
for (let f = 1000; f >= 0; f--) {
nc += count[f];
fs += sumFrac[f];
nGe[f] = nc;
fGe[f] = fs;
}
const obj = {
sd,
n,
positions,
colors,
fracs,
nGe,
fGe,
};
sizeCache.set(index, obj);
return obj;
}
// ------------------------------------------------------------- three.js
const viewport = $("viewport");
let renderer;
try {
renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance",
});
} catch (err) {
showError("无法创建 WebGL 上下文:" + String(err));
return;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(viewport.clientWidth || 800, viewport.clientHeight || 600);
renderer.outputEncoding = THREE.sRGBEncoding;
renderer.toneMapping = THREE.NoToneMapping;
renderer.toneMappingExposure = 1.0;
renderer.domElement.style.zIndex = "0";
viewport.insertBefore(renderer.domElement, viewport.firstChild);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07101d);
scene.fog = new THREE.Fog(0x07101d, 38, 120);
const camera = new THREE.PerspectiveCamera(
42,
(viewport.clientWidth || 800) / (viewport.clientHeight || 600),
0.05,
250
);
camera.position.set(12, 8, 14);
const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.07;
controls.screenSpacePanning = true;
controls.minDistance = 1.6;
controls.maxDistance = 90;
controls.maxPolarAngle = Math.PI / 2 - 0.02;
controls.autoRotateSpeed = 0.7;
// Model coordinates are x = length, y = width, z = up. Rotate the whole
// model group so three.js' y axis becomes the car's height.
const modelRoot = new THREE.Group();
modelRoot.rotation.x = -Math.PI / 2;
scene.add(modelRoot);
// Lights
scene.add(new THREE.AmbientLight(0xb8d4f0, 0.18));
scene.add(new THREE.HemisphereLight(0xbfe6ff, 0x22130a, 0.28));
const key = new THREE.DirectionalLight(0xffffff, 0.65);
key.position.set(9, 13, 7);
scene.add(key);
const rim = new THREE.DirectionalLight(0x5ab8ff, 0.35);
rim.position.set(-10, 7, -9);
scene.add(rim);
const warm = new THREE.PointLight(0xffa04a, 0.25, 24);
warm.position.set(4.5, 3.5, 2);
scene.add(warm);
// Ground
const ground = new THREE.Mesh(
new THREE.CircleGeometry(9.5, 96),
new THREE.MeshBasicMaterial({
color: 0x050b13,
transparent: true,
opacity: 0.85,
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.012;
scene.add(ground);
const grid = new THREE.GridHelper(16, 32, 0x22405f, 0x102036);
grid.position.y = 0;
grid.material.transparent = true;
grid.material.opacity = 0.6;
scene.add(grid);
// Car mesh ------------------------------------------------------------
const carGeom = new THREE.BufferGeometry();
{
const pos = decodeF32(data.mesh.positionsB64);
const idx = decodeU32(data.mesh.indicesB64);
carGeom.setAttribute("position", new THREE.BufferAttribute(pos, 3));
carGeom.setIndex(new THREE.BufferAttribute(idx, 1));
carGeom.computeVertexNormals();
carGeom.computeBoundingSphere();
}
const carMat = new THREE.MeshPhysicalMaterial({
color: 0x4fb8e8,
metalness: 0.12,
roughness: 0.28,
clearcoat: 0.25,
clearcoatRoughness: 0.3,
transparent: true,
opacity: 0.2,
side: THREE.DoubleSide,
depthWrite: false,
depthTest: false,
emissive: 0x0a2a40,
emissiveIntensity: 0.6,
});
const carMesh = new THREE.Mesh(carGeom, carMat);
carMesh.renderOrder = 20;
modelRoot.add(carMesh);
// Bounding cubes ------------------------------------------------------
const axisCube = meta.axisCube;
const minCube = meta.minCube;
const uprightBox = meta.uprightBox || {
dims_m: meta.dimsM,
volume_m3: meta.dimsM[0] * meta.dimsM[1] * meta.dimsM[2],
center_m: [
(meta.bboxMinMm[0] + meta.bboxMaxMm[0]) / 2000,
(meta.bboxMinMm[1] + meta.bboxMaxMm[1]) / 2000,
(meta.bboxMinMm[2] + meta.bboxMaxMm[2]) / 2000,
],
rotation: null,
};
function makeEnvelopeGroup(center, dims, rotation, color, opacity) {
const group = new THREE.Group();
group.position.set(center[0], center[1], center[2]);
if (rotation) {
const R = rotation;
const m = new THREE.Matrix4().set(
R[0][0], R[0][1], R[0][2], 0,
R[1][0], R[1][1], R[1][2], 0,
R[2][0], R[2][1], R[2][2], 0,
0, 0, 0, 1
);
group.setRotationFromMatrix(m);
}
const geom = new THREE.BoxGeometry(dims[0], dims[1], dims[2]);
// Wireframe only: a translucent face filled the viewport and hid the car.
// depthTest=false keeps the envelope readable through the car/voxels.
const edgeMat = new THREE.LineBasicMaterial({
color: color,
transparent: true,
opacity: opacity,
depthWrite: false,
depthTest: false,
});
const edges = new THREE.LineSegments(new THREE.EdgesGeometry(geom), edgeMat);
edges.renderOrder = 30;
group.add(edges);
return group;
}
const axisGroup = makeEnvelopeGroup(
axisCube.center_m,
[axisCube.side_m, axisCube.side_m, axisCube.side_m],
null,
0xff9a3c,
0.9
);
const minGroup = makeEnvelopeGroup(
minCube.center_m,
[minCube.side_m, minCube.side_m, minCube.side_m],
minCube.rotation,
0xb388ff,
0.95
);
const boxGroup = makeEnvelopeGroup(
uprightBox.center_m,
uprightBox.dims_m,
null,
0x5dffb0,
0.95
);
modelRoot.add(axisGroup);
modelRoot.add(minGroup);
modelRoot.add(boxGroup);
// Voxel instancing ----------------------------------------------------
const boxGeom = new THREE.BoxGeometry(1, 1, 1, 1, 1, 1);
// three.js r128 only multiplies vColor into the fragment colour when
// USE_COLOR is defined (instanceColor alone is not enough). A white
// per-vertex colour attribute + vertexColors makes the per-instance colours
// visible without tinting the boxes.
{
const n = boxGeom.attributes.position.count;
const white = new Float32Array(n * 3);
white.fill(1);
boxGeom.setAttribute("color", new THREE.BufferAttribute(white, 3));
}
const voxelMat = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.65,
metalness: 0.02,
transparent: false,
opacity: 1.0,
emissive: 0x000a12,
emissiveIntensity: 0.4,
});
let voxelMesh = null;
function rebuildVoxels(index) {
const obj = getSizeData(index);
if (voxelMesh) {
modelRoot.remove(voxelMesh);
voxelMesh = null;
}
const mesh = new THREE.InstancedMesh(boxGeom, voxelMat, obj.n);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.frustumCulled = false;
mesh.renderOrder = 10;
const m = new THREE.Matrix4();
const q = new THREE.Quaternion();
const pos = new THREE.Vector3();
const scale = new THREE.Vector3(
obj.sd.sizeM,
obj.sd.sizeM,
obj.sd.sizeM
);
for (let i = 0; i < obj.n; i++) {
pos.set(
obj.positions[i * 3],
obj.positions[i * 3 + 1],
obj.positions[i * 3 + 2]
);
m.compose(pos, q, scale);
mesh.setMatrixAt(i, m);
}
const col = new THREE.Color();
for (let i = 0; i < obj.n; i++) {
col.setRGB(
obj.colors[i * 3],
obj.colors[i * 3 + 1],
obj.colors[i * 3 + 2]
);
mesh.setColorAt(i, col);
}
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
mesh.count = obj.n;
modelRoot.add(mesh);
voxelMesh = mesh;
current = obj;
updateVisibility();
}
// ------------------------------------------------------------- metrics
function thresholdIndex() {
return clamp(Math.round(state.threshold * 1000), 0, 1000);
}
function currentEnvelope() {
if (state.cubeMode === "box") return uprightBox;
if (state.cubeMode === "min") return meta.minCube;
return meta.axisCube;
}
function envelopeDims(env) {
return env.dims_m || [env.side_m, env.side_m, env.side_m];
}
function metrics() {
if (!current) return null;
const t = thresholdIndex();
const n = current.nGe[t];
const sumFrac = current.fGe[t];
const cellVol = current.sd.sizeM ** 3;
const vFit = n * cellVol;
const vTrueIn = (sumFrac / 1000) * cellVol;
const env = currentEnvelope();
const envVol = env.volume_m3;
const envDims = envelopeDims(env);
const precision = vFit > 0 ? vTrueIn / vFit : 0;
const recall = vTrueIn / VREF;
const union = vFit + VREF - vTrueIn;
const iou = union > 0 ? vTrueIn / union : 0;
return {
n,
vFit,
vTrueIn,
precision,
recall,
iou,
error: (vFit - VREF) / VREF,
occupancy: vFit / envVol,
trueOccupancy: VREF / envVol,
envVol,
envDims,
cover: current.n,
};
}
function updateStats() {
const m = metrics();
if (!m) return;
$("vFit").textContent = m.vFit.toFixed(3);
const errEl = $("vErr");
errEl.textContent = signedPct(m.error, 1);
errEl.classList.remove("pos", "neg");
if (m.error > 0.001) errEl.classList.add("pos");
if (m.error < -0.001) errEl.classList.add("neg");
$("vCount").textContent = fmtInt.format(m.n);
$("vIou").textContent = m.iou.toFixed(3);
$("vPrec").textContent = pct(m.precision, 1) + "%";
$("vRec").textContent = pct(m.recall, 1) + "%";
$("vCubeSide").textContent = m.envDims.map((v) => v.toFixed(3)).join(" × ");
$("vCubeVol").textContent = m.envVol.toFixed(2);
$("vOcc").textContent = pct(m.occupancy, 2);
$("vTrueOcc").textContent = pct(m.trueOccupancy, 2);
$("vRef").textContent = VREF.toFixed(3);
$("vCad").textContent = meta.volumeCadSumM3.toFixed(3);
$("vCover").textContent = fmtInt.format(m.cover);
$("thrHint").textContent =
"保留占据概率 ≥ " + Math.round(state.threshold * 100) + "% 的立方体";
$("cubeHint").textContent =
state.cubeMode === "aabb"
? "轴对齐立方体;边长 = 车辆最大尺寸"
: state.cubeMode === "min"
? "旋转数值最优;含 20 mm 网格余量"
: "最小正置长方体;紧贴车辆轴对齐包围盒";
const envRows = [
["aabb", "立方体", meta.axisCube.volume_m3],
["min", "旋转最小", meta.minCube.volume_m3],
["box", "正置长方体", uprightBox.volume_m3],
];
$("envCompare").innerHTML = envRows
.map(([mode, label, vol]) => {
const on = state.cubeMode === mode ? "on" : "";
return `
" +
String(err && err.message ? err.message : err) +
"python src/serve.py 后通过 HTTP 打开。"
);
}
// Debug handle (handy from the console / automated screenshots).
window.__OCC_DEBUG = {
scene,
camera,
controls,
modelRoot,
carMesh,
axisGroup,
minGroup,
boxGroup,
get voxelMesh() {
return voxelMesh;
},
};
})();