Prompt specification
Build or customize the Three.js 3D scene "Bridge-and-tunnel topology gallery" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Bridge-and-tunnel topology gallery
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/bridge-and-tunnel-topology-gallery-x1723
Scene Description Prompt:
Create a standalone voxel scene in one HTML file using Three.js from cdnjs. Compose simple solid models with and without holes beside their surface meshes; explain that topology changes when holes are introduced rather than treating all solids identically.
Working Three.js Starter (bridge-and-tunnel-topology-gallery-x1723):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Topology Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07111d;
--panel: rgba(9, 25, 39, 0.86);
--line: rgba(133, 220, 238, 0.22);
--text: #e8f8ff;
--muted: #91adbd;
--solid: #ffab58;
--surface: #4bd9ed;
--tunnel: #bd91ff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
color: var(--text);
}
#app {
position: fixed;
inset: 0;
}
#app canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.ui {
position: fixed;
inset: 0;
pointer-events: none;
}
.topbar {
position: absolute;
top: 22px;
left: 24px;
right: 24px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
}
.brand {
padding: 13px 16px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(6, 18, 30, 0.74);
backdrop-filter: blur(12px);
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.18);
}
.brand strong {
display: block;
font-size: 13px;
letter-spacing: 0.18em;
}
.brand span {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 12px;
}
.tools {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 12px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(6, 18, 30, 0.74);
backdrop-filter: blur(12px);
pointer-events: auto;
}
.legend {
display: flex;
gap: 12px;
color: var(--muted);
font-size: 11px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
.solid {
color: var(--solid);
}
.surface {
color: var(--surface);
}
.tunnel {
color: var(--tunnel);
}
button {
border: 1px solid rgba(120, 220, 238, 0.28);
border-radius: 8px;
padding: 8px 11px;
background: rgba(52, 157, 179, 0.12);
color: var(--text);
font: inherit;
font-size: 12px;
cursor: pointer;
transition:
background 150ms ease,
border-color 150ms ease;
}
button:hover {
background: rgba(52, 157, 179, 0.25);
border-color: rgba(120, 220, 238, 0.55);
}
.explain {
position: absolute;
left: 24px;
bottom: 24px;
width: min(670px, calc(100vw - 48px));
padding: 17px 18px 16px;
border: 1px solid var(--line);
border-radius: 14px;
background: var(--panel);
backdrop-filter: blur(16px);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.3);
}
.eyebrow {
margin-bottom: 11px;
color: #7fd9e9;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.17em;
}
.compare {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.card {
min-width: 0;
padding: 11px 12px;
border: 1px solid rgba(130, 210, 230, 0.12);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.card h3 {
margin: 0 0 6px;
font-size: 12px;
font-weight: 650;
}
.metric {
color: var(--surface);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 14px;
font-weight: 700;
}
.card:last-child .metric {
color: var(--tunnel);
}
.card p {
margin: 6px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.takeaway {
margin: 12px 0 0;
color: #c6dbe5;
font-size: 12px;
line-height: 1.5;
}
.takeaway strong {
color: var(--text);
}
.hint {
position: absolute;
right: 24px;
bottom: 25px;
padding: 9px 12px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(6, 18, 30, 0.72);
color: var(--muted);
font-size: 11px;
backdrop-filter: blur(10px);
}
@media (max-width: 760px) {
.topbar {
top: 12px;
left: 12px;
right: 12px;
}
.brand {
padding: 10px 12px;
}
.brand span,
.legend,
.hint {
display: none;
}
.tools {
padding: 7px;
}
.explain {
left: 12px;
bottom: 12px;
width: calc(100vw - 24px);
padding: 13px;
}
.takeaway {
font-size: 11px;
}
}
@media (max-width: 480px) {
.compare {
grid-template-columns: 1fr;
}
.card p {
display: none;
}
}
</style>
</head>
<body>
<div id="app"></div>
<div class="ui">
<header class="topbar">
<div class="brand">
<strong>VOXEL TOPOLOGY LAB</strong>
<span>Filled voxels and their extracted boundary surfaces</span>
</div>
<div class="tools">
<div class="legend">
<span class="solid"><i class="dot"></i>Solid</span>
<span class="surface"><i class="dot"></i>Surface</span>
<span class="tunnel"><i class="dot"></i>Tunnel wall</span>
</div>
<button id="reset" type="button">Reset view</button>
</div>
</header>
<section class="explain">
<div class="eyebrow">THE HOLE CHANGES THE TOPOLOGY</div>
<div class="compare">
<article class="card">
<h3>Closed block</h3>
<div class="metric" id="closed-metric">χ = 2 · genus 0</div>
<p>
One connected body with no handle. Its boundary is
sphere-like.
</p>
</article>
<article class="card">
<h3>Through-hole block</h3>
<div class="metric" id="hole-metric">χ = 0 · genus 1</div>
<p>
Still one connected body, but the tunnel adds one handle
to its boundary.
</p>
</article>
</div>
<p class="takeaway">
<strong>The solid and surface versions represent the same occupancy,
but they are not topologically interchangeable.</strong>
Filling every occupied voxel produces the solid; retaining only
faces between occupied and empty space produces the surface mesh.
The through-hole changes the boundary from genus 0 to genus 1.
</p>
</section>
<div class="hint">Drag to orbit · Wheel or pinch to zoom · Double-click to reset</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer, camera, and lighting
// -------------------------------------------------------------------------
const app = document.getElementById("app");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
app.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111d);
scene.fog = new THREE.Fog(0x07111d, 20, 38);
const camera = new THREE.PerspectiveCamera(
39,
window.innerWidth / window.innerHeight,
0.1,
100
);
const hemisphere = new THREE.HemisphereLight(
0xc7efff,
0x101522,
1.65
);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(5, 13, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -13;
keyLight.shadow.camera.right = 13;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0003;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x35d8ff, 18, 12, 2);
cyanLight.position.set(-5, 5, 4);
scene.add(cyanLight);
const violetLight = new THREE.PointLight(0xa56fff, 20, 12, 2);
violetLight.position.set(5, 5, 3);
scene.add(violetLight);
// -------------------------------------------------------------------------
// Ground and plinths
// -------------------------------------------------------------------------
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(40, 40),
new THREE.MeshStandardMaterial({
color: 0x081521,
roughness: 0.94,
metalness: 0.02
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.025;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(
32,
32,
0x287184,
0x153947
);
grid.position.y = -0.012;
grid.material.transparent = true;
grid.material.opacity = 0.22;
scene.add(grid);
const plinthGeometry = new THREE.BoxGeometry(3.46, 0.12, 3.46);
const plinthMaterial = new THREE.MeshStandardMaterial({
color: 0x0b2533,
roughness: 0.64,
metalness: 0.2
});
const plinthEdgeMaterial = new THREE.LineBasicMaterial({
color: 0x286174,
transparent: true,
opacity: 0.6
});
function addPlinth(x) {
const plinth = new THREE.Mesh(plinthGeometry, plinthMaterial);
plinth.position.set(x, 0.06, 0);
plinth.castShadow = true;
plinth.receiveShadow = true;
scene.add(plinth);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(plinthGeometry),
plinthEdgeMaterial
);
edges.position.copy(plinth.position);
edges.position.y += 0.001;
scene.add(edges);
}
// -------------------------------------------------------------------------
// Voxel occupancy
//
// A 7 x 7 x 7 grid. The tunnel removes a 3 x 3 column through the entire
// Z axis, leaving a thick wall around the opening.
// -------------------------------------------------------------------------
const GRID_SIZE = 7;
const CELL_SIZE = 0.42;
const MODEL_SIZE = GRID_SIZE * CELL_SIZE;
const MODEL_Y = 0.12 + MODEL_SIZE * 0.5;
const cellKey = (x, y, z) => `${x},${y},${z}`;
function buildOccupancy(hasHole) {
const occupancy = new Map();
for (let z = 0; z < GRID_SIZE; z++) {
for (let y = 0; y < GRID_SIZE; y++) {
for (let x = 0; x < GRID_SIZE; x++) {
const insideTunnel =
x >= 2 && x <= 4 &&
y >= 2 && y <= 4;
if (hasHole && insideTunnel) {
continue;
}
occupancy.set(cellKey(x, y, z), { x, y, z });
}
}
}
return occupancy;
}
const closedOccupancy = buildOccupancy(false);
const holedOccupancy = buildOccupancy(true);
function countComponents(occupancy) {
const visited = new Set();
let components = 0;
for (const key of occupancy.keys()) {
if (visited.has(key)) continue;
components++;
const stack = [key];
visited.add(key);
while (stack.length) {
const current = stack.pop();
const [x, y, z] = current.split(",").map(Number);
const neighbors = [
[x + 1, y, z],
[x - 1, y, z],
[x, y + 1, z],
[x, y - 1, z],
[x, y, z + 1],
[x, y, z - 1]
];
for (const [nx, ny, nz] of neighbors) {
const nextKey = cellKey(nx, ny, nz);
if (occupancy.has(nextKey) && !visited.has(nextKey)) {
visited.add(nextKey);
stack.push(nextKey);
}
}
}
}
return components;
}
// -------------------------------------------------------------------------
// Filled solid voxel model
// -------------------------------------------------------------------------
function createSolid(occupancy) {
const cells = [...occupancy.values()];
const geometry = new THREE.BoxGeometry(
CELL_SIZE,
CELL_SIZE,
CELL_SIZE
);
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.58,
metalness: 0.08
});
const mesh = new THREE.InstancedMesh(
geometry,
material,
cells.length
);
const dummy = new THREE.Object3D();
const baseColor = new THREE.Color(0xffa654);
cells.forEach((cell, index) => {
dummy.position.set(
(cell.x + 0.5 - GRID_SIZE * 0.5) * CELL_SIZE,
(cell.y + 0.5 - GRID_SIZE * 0.5) * CELL_SIZE,
(cell.z + 0.5 - GRID_SIZE * 0.5) * CELL_SIZE
);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
const variation =
((cell.x * 17 + cell.y * 11 + cell.z * 5) % 7 - 3) * 0.025;
const color = baseColor.clone();
color.offsetHSL(0, 0, variation);
mesh.setColorAt(index, color);
});
mesh.instanceMatrix.needsUpdate = true;
mesh.instanceColor.needsUpdate = true;
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.computeBoundingBox();
mesh.computeBoundingSphere();
return mesh;
}
// -------------------------------------------------------------------------
// Surface extraction
//
// Only faces between an occupied voxel and empty space are retained.
// Topology is counted independently of the render vertices so the
// Euler characteristic remains meaningful.
// -------------------------------------------------------------------------
const FACE_DEFINITIONS = [
{
delta: [1, 0, 0],
normal: [1, 0, 0],
corners: [
[1, 0, 0],
[1, 1, 0],
[1, 1, 1],
[1, 0, 1]
]
},
{
delta: [-1, 0, 0],
normal: [-1, 0, 0],
corners: [
[0, 0, 1],
[0, 1, 1],
[0, 1, 0],
[0, 0, 0]
]
},
{
delta: [0, 1, 0],
normal: [0, 1, 0],
corners: [
[0, 1, 1],
[1, 1, 1],
[1, 1, 0],
[0, 1, 0]
]
},
{
delta: [0, -1, 0],
normal: [0, -1, 0],
corners: [
[0, 0, 0],
[1, 0, 0],
[1, 0, 1],
[0, 0, 1]
]
},
{
delta: [0, 0, 1],
normal: [0, 0, 1],
corners: [
[0, 0, 1],
[1, 0, 1],
[1, 1, 1],
[0, 1, 1]
]
},
{
delta: [0, 0, -1],
normal: [0, 0, -1],
corners: [
[1, 0, 0],
[0, 0, 0],
[0, 1, 0],
[1, 1, 0]
]
}
];
function createSurface(occupancy, hasHole) {
const renderPositions = [];
const renderNormals = [];
const renderColors = [];
const edgePositions = [];
const vertexIds = new Map();
const vertexCoordinates = [];
const edgeSet = new Set();
const edgePairs = [];
let faceCount = 0;
function registerVertex(coordinate) {
const key = coordinate.join(",");
if (!vertexIds.has(key)) {
const id = vertexIds.size;
vertexIds.set(key, id);
vertexCoordinates[id] = coordinate;
}
return vertexIds.get(key);
}
function registerEdge(a, b) {
const low = Math.min(a, b);
const high = Math.max(a, b);
const key = `${low}:${high}`;
if (!edgeSet.has(key)) {
edgeSet.add(key);
edgePairs.push([low, high]);
}
}
for (const cell of occupancy.values()) {
for (const face of FACE_DEFINITIONS) {
const nx = cell.x + face.delta[0];
const ny = cell.y + face.delta[1];
const nz = cell.z + face.delta[2];
// A neighboring occupied voxel hides this face.
if (occupancy.has(cellKey(nx, ny, nz))) {
continue;
}
faceCount++;
const corners = face.corners.map(offset => [
cell.x + offset[0],
cell.y + offset[1],
cell.z + offset[2]
]);
const ids = corners.map(registerVertex);
for (let i = 0; i < 4; i++) {
registerEdge(ids[i], ids[(i + 1) % 4]);
}
const localCorners = corners.map(coordinate => [
(coordinate[0] - GRID_SIZE * 0.5) * CELL_SIZE,
(coordinate[1] - GRID_SIZE * 0.5) * CELL_SIZE,
(coordinate[2] - GRID_SIZE * 0.5) * CELL_SIZE
]);
// Side walls facing into the through-hole receive a violet color.
const isTunnelWall =
hasHole &&
nx >= 2 && nx <= 4 &&
ny >= 2 && ny <= 4 &&
nz >= 0 && nz < GRID_SIZE;
let faceColor = new THREE.Color(
isTunnelWall ? 0xbd91ff : 0x4bd9ed
);
if (face.normal[1] > 0) {
faceColor.multiplyScalar(1.08);
} else if (face.normal[1] < 0) {
faceColor.multiplyScalar(0.78);
} else if (face.normal[2] !== 0) {
faceColor.multiplyScalar(0.92);
} else {
faceColor.multiplyScalar(0.84);
}
const triangles = [
[0, 1, 2],
[0, 2, 3]
];
for (const triangle of triangles) {
for (const index of triangle) {
renderPositions.push(...localCorners[index]);
renderNormals.push(...face.normal);
renderColors.push(
faceColor.r,
faceColor.g,
faceColor.b
);
}
}
}
}
for (const [a, b] of edgePairs) {
const coordinateA = vertexCoordinates[a];
const coordinateB = vertexCoordinates[b];
edgePositions.push(
(coordinateA[0] - GRID_SIZE * 0.5) * CELL_SIZE,
(coordinateA[1] - GRID_SIZE * 0.5) * CELL_SIZE,
(coordinateA[2] - GRID_SIZE * 0.5) * CELL_SIZE,
(coordinateB[0] - GRID_SIZE * 0.5) * CELL_SIZE,
(coordinateB[1] - GRID_SIZE * 0.5) * CELL_SIZE,
(coordinateB[2] - GRID_SIZE * 0.5) * CELL_SIZE
);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(renderPositions, 3)
);
geometry.setAttribute(
"normal",
new THREE.Float32BufferAttribute(renderNormals, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(renderColors, 3)
);
geometry.computeBoundingSphere();
const edgeGeometry = new THREE.BufferGeometry();
edgeGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(edgePositions, 3)
);
edgeGeometry.computeBoundingSphere();
const vertexCount = vertexIds.size;
const edgeCount = edgeSet.size;
const eulerCharacteristic = vertexCount - edgeCount + faceCount;
const genus = (2 - eulerCharacteristic) / 2;
return {
geometry,
edgeGeometry,
metrics: {
vertices: vertexCount,
edges: edgeCount,
faces: faceCount,
eulerCharacteristic,
genus
}
};
}
const closedSurface = createSurface(closedOccupancy, false);
const holedSurface = createSurface(holedOccupancy, true);
const surfaceMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.34,
metalness: 0.16,
polygonOffset: true,
polygonOffsetFactor: 1,
polygonOffsetUnits: 1
});
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0xd2fbff,
transparent: true,
opacity: 0.36,
depthWrite: false
});
function createSurfaceObject(surface, x) {
const group = new THREE.Group();
group.position.set(x, MODEL_Y, 0);
const mesh = new THREE.Mesh(
surface.geometry,
surfaceMaterial
);
mesh.castShadow = true;
mesh.receiveShadow = true;
group.add(mesh);
const edges = new THREE.LineSegments(
surface.edgeGeometry,
edgeMaterial
);
edges.renderOrder = 3;
group.add(edges);
scene.add(group);
return group;
}
// -------------------------------------------------------------------------
// Scene layout: each solid is placed beside its corresponding surface mesh
// -------------------------------------------------------------------------
const positions = {
closedSolid: -6.2,
closedSurface: -2.3,
holedSolid: 2.3,
holedSurface: 6.2
};
for (const x of Object.values(positions)) {
addPlinth(x);
}
const closedSolid = createSolid(closedOccupancy);
closedSolid.position.set(
positions.closedSolid,
MODEL_Y,
0
);
scene.add(closedSolid);
const holedSolid = createSolid(holedOccupancy);
holedSolid.position.set(
positions.holedSolid,
MODEL_Y,
0
);
scene.add(holedSolid);
createSurfaceObject(closedSurface, positions.closedSurface);
createSurfaceObject(holedSurface, positions.holedSurface);
// -------------------------------------------------------------------------
// Canvas-generated scene labels
// -------------------------------------------------------------------------
function roundedRect(context, x, y, width, height, radius) {
context.beginPath();
context.moveTo(x + radius, y);
context.lineTo(x + width - radius, y);
context.quadraticCurveTo(x + width, y, x + width, y + radius);
context.lineTo(x + width, y + height - radius);
context.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
context.lineTo(x + radius, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - radius);
context.lineTo(x, y + radius);
context.quadraticCurveTo(x, y, x + radius, y);
context.closePath();
}
function createBadge(text, color, worldWidth) {
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
const font = "700 52px system-ui, sans-serif";
context.font = font;
const measuredWidth = context.measureText(text).width;
const width = Math.ceil(measuredWidth + 80);
const height = 116;
canvas.width = width;
canvas.height = height;
context.clearRect(0, 0, width, height);
roundedRect(
context,
3,
3,
width - 6,
height - 6,
24
);
context.fillStyle = "rgba(5, 18, 29, 0.90)";
context.fill();
context.strokeStyle = color;
context.lineWidth = 3;
context.stroke();
context.font = font;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = color;
context.fillText(text, width * 0.5, height * 0.5 + 1);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(
worldWidth,
worldWidth * height / width,
1
);
sprite.renderOrder = 10;
return sprite;
}
function addLabel(text, color, x, y, width) {
const label = createBadge(text, color, width);
label.position.set(x, y, 0);
scene.add(label);
}
addLabel(
"PAIR 01 · CLOSED BLOCK",
"#68e3f4",
-4.25,
4.02,
4.55
);
addLabel(
"PAIR 02 · THROUGH-HOLE",
"#c39cff",
4.25,
4.02,
4.75
);
addLabel(
"SOLID · NO HOLE",
"#ffab58",
positions.closedSolid,
3.31,
3.10
);
addLabel(
"SURFACE · GENUS 0",
"#4bd9ed",
positions.closedSurface,
3.31,
3.10
);
addLabel(
"SOLID · 1 TUNNEL",
"#ffab58",
positions.holedSolid,
3.31,
3.10
);
addLabel(
"SURFACE · GENUS 1",
"#bd91ff",
positions.holedSurface,
3.31,
3.10
);
// -------------------------------------------------------------------------
// Topology statistics in the explanatory panel
// -------------------------------------------------------------------------
const closedComponents = countComponents(closedOccupancy);
const holedComponents = countComponents(holedOccupancy);
document.getElementById("closed-metric").textContent =
`χ = ${closedSurface.metrics.eulerCharacteristic} · ` +
`genus ${closedSurface.metrics.genus}`;
document.getElementById("hole-metric").textContent =
`χ = ${holedSurface.metrics.eulerCharacteristic} · ` +
`genus ${holedSurface.metrics.genus}`;
// -------------------------------------------------------------------------
// Custom camera controls: orbit, wheel zoom, and two-finger pinch zoom
// -------------------------------------------------------------------------
const cameraState = {
theta: 0.18,
phi: 1.19,
radius: 18,
target: new THREE.Vector3(0, 1.42, 0)
};
const spherical = new THREE.Spherical();
function defaultRadius() {
const aspect = window.innerWidth / window.innerHeight;
if (aspect < 1) return 42;
if (aspect < 1.4) return 23;
return 18;
}
function applyCamera() {
spherical.set(
cameraState.radius,
cameraState.phi,
cameraState.theta
);
camera.position
.setFromSpherical(spherical)
.add(cameraState.target);
camera.lookAt(cameraState.target);
}
function resetView() {
cameraState.theta = 0.18;
cameraState.phi = 1.19;
cameraState.radius = defaultRadius();
applyCamera();
}
resetView();
const pointers = new Map();
let previousPinchDistance = 0;
function pointerDistance() {
const values = [...pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
renderer.domElement.addEventListener("pointerdown", event => {
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
renderer.domElement.setPointerCapture(event.pointerId);
if (pointers.size === 2) {
previousPinchDistance = pointerDistance();
}
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointers.has(event.pointerId)) return;
const previous = pointers.get(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1) {
const deltaX = event.clientX - previous.x;
const deltaY = event.clientY - previous.y;
cameraState.theta -= deltaX * 0.005;
cameraState.phi -= deltaY * 0.005;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi,
0.34,
1.48
);
applyCamera();
} else if (pointers.size === 2) {
const distance = pointerDistance();
if (previousPinchDistance > 0 && distance > 0) {
cameraState.radius *=
previousPinchDistance / distance;
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius,
8,
48
);
applyCamera();
}
previousPinchDistance = distance;
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
previousPinchDistance = pointers.size === 2
? pointerDistance()
: 0;
}
renderer.domElement.addEventListener(
"pointerup",
releasePointer
);
renderer.domElement.addEventListener(
"pointercancel",
releasePointer
);
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraState.radius *= Math.exp(event.deltaY * 0.001);
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius,
8,
48
);
applyCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetView);
document.getElementById("reset").addEventListener("click", resetView);
document.addEventListener("keydown", event => {
if (event.key.toLowerCase() === "r") {
resetView();
}
});
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(
Math.min(window.devicePixelRatio, 2)
);
renderer.setSize(
window.innerWidth,
window.innerHeight
);
});
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```