Prompt specification
Build or customize the Three.js 3D scene "Polyhedron vertex edge face model" 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: Polyhedron vertex edge face model
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/polyhedron-vertex-edge-face-model-x1721
Scene Description Prompt:
Polyhedron vertex edge face model. Build a convex polyhedron with selectable vertices, edges, and faces; count each category and display Euler's relation for the stated topological class. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (polyhedron-vertex-edge-face-model-x1721):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Polyhedron Topology Explorer</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(11, 23, 40, 0.82);
--panel-border: rgba(154, 196, 226, 0.16);
--text: #eef7ff;
--muted: #8ea8bd;
--cyan: #72e4ff;
--gold: #ffd166;
--green: #7ce6b1;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
background:
radial-gradient(circle at 32% 30%, #15324b 0%, transparent 34%),
radial-gradient(circle at 72% 65%, #102b3d 0%, transparent 32%),
linear-gradient(145deg, #07111f, #050b14 70%);
}
button {
font: inherit;
}
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.brand {
position: fixed;
z-index: 5;
top: 28px;
left: 30px;
pointer-events: none;
user-select: none;
}
.brand-kicker {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 9px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
.brand-kicker::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 14px var(--cyan);
content: "";
}
.brand h1 {
margin: 0;
font-size: clamp(28px, 4vw, 48px);
font-weight: 760;
letter-spacing: -0.045em;
line-height: 1;
}
.brand p {
max-width: 430px;
margin: 10px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.panel {
position: fixed;
z-index: 10;
top: 24px;
right: 24px;
width: 342px;
max-height: calc(100vh - 48px);
overflow: auto;
padding: 18px;
border: 1px solid var(--panel-border);
border-radius: 22px;
background: var(--panel);
box-shadow:
0 24px 80px rgba(0, 0, 0, 0.38),
inset 0 1px 0 rgba(255, 255, 255, 0.04);
backdrop-filter: blur(18px) saturate(135%);
-webkit-backdrop-filter: blur(18px) saturate(135%);
scrollbar-width: thin;
scrollbar-color: #28455e transparent;
}
.topology {
display: grid;
grid-template-columns: auto 1fr;
gap: 3px 12px;
align-items: center;
padding: 13px 14px;
border: 1px solid rgba(114, 228, 255, 0.15);
border-radius: 14px;
background:
linear-gradient(135deg, rgba(114, 228, 255, 0.08), transparent),
rgba(4, 12, 23, 0.28);
}
.topology-icon {
grid-row: 1 / span 2;
display: grid;
width: 38px;
height: 38px;
place-items: center;
border: 1px solid rgba(114, 228, 255, 0.32);
border-radius: 11px;
color: var(--cyan);
background: rgba(114, 228, 255, 0.08);
font-size: 20px;
}
.eyebrow {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.topology strong {
font-size: 13px;
font-weight: 700;
}
.section {
margin-top: 18px;
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.section-heading h2 {
margin: 0;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.section-heading span {
color: var(--muted);
font-size: 10px;
}
.counts {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.count-card {
position: relative;
overflow: hidden;
padding: 12px;
border: 1px solid rgba(157, 197, 226, 0.13);
border-radius: 13px;
background: rgba(255, 255, 255, 0.035);
}
.count-card::after {
position: absolute;
right: -13px;
bottom: -18px;
color: rgba(255, 255, 255, 0.035);
font-size: 58px;
font-weight: 900;
content: attr(data-symbol);
}
.count-label {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.count-value {
display: block;
margin-top: 3px;
font-size: 27px;
font-weight: 760;
letter-spacing: -0.04em;
}
.equation-card {
margin-top: 9px;
padding: 14px;
border: 1px solid rgba(124, 230, 177, 0.16);
border-radius: 14px;
background:
linear-gradient(135deg, rgba(124, 230, 177, 0.07), transparent),
rgba(255, 255, 255, 0.025);
}
.equation {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
font-size: 24px;
font-weight: 740;
letter-spacing: -0.035em;
}
.equation i {
color: var(--muted);
font-style: normal;
font-weight: 500;
}
.equation strong {
color: var(--green);
}
.euler-formula {
margin-top: 7px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
text-align: center;
}
.euler-status {
margin-top: 9px;
color: var(--green);
font-size: 11px;
font-weight: 700;
text-align: center;
}
.tools {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.tool {
display: flex;
min-width: 0;
flex-direction: column;
align-items: flex-start;
gap: 7px;
padding: 10px;
border: 1px solid rgba(157, 197, 226, 0.13);
border-radius: 12px;
color: var(--muted);
background: rgba(255, 255, 255, 0.025);
cursor: pointer;
transition:
border-color 160ms ease,
background 160ms ease,
color 160ms ease,
transform 160ms ease;
}
.tool:hover {
transform: translateY(-1px);
border-color: rgba(114, 228, 255, 0.32);
color: var(--text);
}
.tool.active {
border-color: rgba(114, 228, 255, 0.62);
color: var(--cyan);
background: rgba(114, 228, 255, 0.1);
box-shadow: inset 0 0 18px rgba(114, 228, 255, 0.035);
}
.tool-top {
display: flex;
width: 100%;
align-items: center;
justify-content: space-between;
}
.tool-symbol {
font-size: 16px;
font-weight: 850;
}
.tool-count {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
}
.tool-name {
font-size: 11px;
font-weight: 700;
}
.selection-card {
min-height: 108px;
padding: 13px;
border: 1px solid rgba(157, 197, 226, 0.13);
border-radius: 14px;
background: rgba(255, 255, 255, 0.025);
}
.selection-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 10px;
}
#selectionTitle {
margin: 0;
font-size: 13px;
font-weight: 750;
}
#selectionMeta {
margin: 5px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
#selectionList {
display: grid;
max-height: 116px;
margin-top: 10px;
gap: 5px;
overflow: auto;
scrollbar-width: thin;
}
.selection-item {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 7px;
border-radius: 8px;
color: #c9d9e7;
background: rgba(255, 255, 255, 0.035);
font-size: 10px;
}
.item-badge {
min-width: 34px;
color: var(--gold);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 800;
}
.empty-selection {
margin-top: 14px;
color: #718a9e;
font-size: 10px;
line-height: 1.55;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 10px;
}
.action-button {
padding: 9px 11px;
border: 1px solid rgba(157, 197, 226, 0.15);
border-radius: 10px;
color: #bdd0df;
background: rgba(255, 255, 255, 0.035);
cursor: pointer;
font-size: 10px;
font-weight: 700;
transition: 150ms ease;
}
.action-button:hover:not(:disabled) {
border-color: rgba(114, 228, 255, 0.34);
color: var(--cyan);
background: rgba(114, 228, 255, 0.07);
}
.action-button:disabled {
cursor: default;
opacity: 0.35;
}
.hint {
position: fixed;
z-index: 4;
bottom: 25px;
left: 30px;
display: flex;
flex-wrap: wrap;
max-width: 520px;
gap: 8px 16px;
color: #7892a7;
font-size: 10px;
pointer-events: none;
}
.hint span {
display: flex;
align-items: center;
gap: 6px;
}
.key {
display: inline-grid;
min-width: 20px;
height: 20px;
place-items: center;
padding: 0 5px;
border: 1px solid rgba(157, 197, 226, 0.18);
border-radius: 5px;
color: #b6cad9;
background: rgba(255, 255, 255, 0.04);
font-size: 9px;
}
#tooltip {
position: fixed;
z-index: 30;
display: none;
padding: 7px 9px;
border: 1px solid rgba(114, 228, 255, 0.24);
border-radius: 8px;
color: var(--cyan);
background: rgba(6, 15, 27, 0.92);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
pointer-events: none;
}
@media (max-width: 760px) {
#stage {
bottom: 46vh;
}
.brand {
top: 17px;
left: 17px;
}
.brand h1 {
font-size: 30px;
}
.brand p {
max-width: calc(100vw - 34px);
font-size: 11px;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: calc(46vh - 20px);
padding: 14px;
border-radius: 17px;
}
.hint {
display: none;
}
.equation {
font-size: 21px;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<header class="brand">
<div class="brand-kicker">Topology Studio</div>
<h1>Icosahedron</h1>
<p>
Explore the vertices, edges, and faces of a convex low-poly polyhedron.
</p>
</header>
<aside class="panel" aria-label="Polyhedron topology controls">
<section class="topology">
<div class="topology-icon">◇</div>
<div class="eyebrow">Topological class</div>
<strong>Closed convex polyhedron · genus 0</strong>
</section>
<section class="section">
<div class="section-heading">
<h2>Element counts</h2>
<span>Combinatorial structure</span>
</div>
<div class="counts">
<div class="count-card" data-symbol="V">
<span class="count-label">Vertices</span>
<strong class="count-value" id="vertexCount">12</strong>
</div>
<div class="count-card" data-symbol="E">
<span class="count-label">Edges</span>
<strong class="count-value" id="edgeCount">30</strong>
</div>
<div class="count-card" data-symbol="F">
<span class="count-label">Faces</span>
<strong class="count-value" id="faceCount">20</strong>
</div>
</div>
<div class="equation-card">
<div class="equation" aria-label="Euler characteristic calculation">
<span id="eulerV">12</span>
<i>−</i>
<span id="eulerE">30</span>
<i>+</i>
<span id="eulerF">20</span>
<i>=</i>
<strong id="eulerResult">2</strong>
</div>
<div class="euler-formula">
V − E + F = 2 − 2g, g = 0
</div>
<div class="euler-status" id="eulerStatus">
✓ Euler characteristic χ = 2
</div>
</div>
</section>
<section class="section">
<div class="section-heading">
<h2>Selection tool</h2>
<span>Keys 1 / 2 / 3</span>
</div>
<div class="tools" role="group" aria-label="Element selection mode">
<button class="tool active" data-mode="vertex" aria-pressed="true">
<span class="tool-top">
<span class="tool-symbol">V</span>
<span class="tool-count">12</span>
</span>
<span class="tool-name">Vertices</span>
</button>
<button class="tool" data-mode="edge" aria-pressed="false">
<span class="tool-top">
<span class="tool-symbol">E</span>
<span class="tool-count">30</span>
</span>
<span class="tool-name">Edges</span>
</button>
<button class="tool" data-mode="face" aria-pressed="false">
<span class="tool-top">
<span class="tool-symbol">F</span>
<span class="tool-count">20</span>
</span>
<span class="tool-name">Faces</span>
</button>
</div>
</section>
<section class="section">
<div class="section-heading">
<h2>Selection</h2>
<span>Shift-click to add</span>
</div>
<div class="selection-card">
<div class="selection-header">
<div>
<h3 id="selectionTitle">Nothing selected</h3>
<p id="selectionMeta">Choose a tool and click an element.</p>
</div>
</div>
<div id="selectionList"></div>
<div class="empty-selection" id="emptySelection">
Click an element in the viewport. Use Shift or Ctrl-click to select
several elements of the same type.
</div>
</div>
<div class="actions">
<button class="action-button" id="clearSelection" disabled>
Clear selection
</button>
<button class="action-button" id="resetView">Reset view</button>
</div>
</section>
</aside>
<div class="hint" aria-hidden="true">
<span><b class="key">Drag</b> orbit</span>
<span><b class="key">Wheel</b> zoom</span>
<span><b class="key">Right-drag</b> pan</span>
<span><b class="key">1</b><b class="key">2</b><b class="key">3</b> tools</span>
<span><b class="key">R</b> reset</span>
<span><b class="key">Esc</b> clear</span>
</div>
<div id="tooltip"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const stage = document.getElementById("stage");
const tooltip = document.getElementById("tooltip");
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
42,
stage.clientWidth / stage.clientHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(stage.clientWidth, stage.clientHeight, false);
renderer.setClearColor(0x07111f, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Interactive three-dimensional icosahedron"
);
stage.appendChild(renderer.domElement);
const ambientLight = new THREE.HemisphereLight(0xa6d9ff, 0x10202d, 1.65);
scene.add(ambientLight);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.65);
keyLight.position.set(4.5, 6, 5.5);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x55d6ff, 1.65);
rimLight.position.set(-5, 1.5, -4);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffc857, 0.85, 12);
warmLight.position.set(3, -2.5, 3);
scene.add(warmLight);
const grid = new THREE.GridHelper(
8,
16,
0x2d6680,
0x17364c
);
grid.position.y = -1.45;
grid.material.transparent = true;
grid.material.opacity = 0.2;
grid.material.depthWrite = false;
scene.add(grid);
const model = new THREE.Group();
model.rotation.set(-0.11, 0.34, 0.08);
scene.add(model);
// -------------------------------------------------------------------------
// Exact regular icosahedron topology
// -------------------------------------------------------------------------
const phi = (1 + Math.sqrt(5)) / 2;
const rawVertices = [
[-1, phi, 0],
[1, phi, 0],
[-1, -phi, 0],
[1, -phi, 0],
[0, -1, phi],
[0, 1, phi],
[0, -1, -phi],
[0, 1, -phi],
[phi, 0, -1],
[phi, 0, 1],
[-phi, 0, -1],
[-phi, 0, 1]
];
const vertices = rawVertices.map(([x, y, z]) =>
new THREE.Vector3(x, y, z).normalize()
);
const faces = [
[0, 11, 5], [0, 5, 1], [0, 1, 7], [0, 7, 10], [0, 10, 11],
[1, 5, 9], [5, 11, 4], [11, 10, 2], [10, 7, 6], [7, 1, 8],
[3, 9, 4], [3, 4, 2], [3, 2, 6], [3, 6, 8], [3, 8, 9],
[4, 9, 5], [2, 4, 11], [6, 2, 10], [8, 6, 7], [9, 8, 1]
];
const edgeMap = new Map();
for (const [a, b, c] of faces) {
for (const [start, end] of [[a, b], [b, c], [c, a]]) {
const low = Math.min(start, end);
const high = Math.max(start, end);
const key = `${low}-${high}`;
if (!edgeMap.has(key)) {
edgeMap.set(key, { a: start, b: end });
}
}
}
const edges = [...edgeMap.values()];
const V = vertices.length;
const E = edges.length;
const F = faces.length;
const genus = 0;
const eulerExpected = 2 - 2 * genus;
const eulerActual = V - E + F;
// -------------------------------------------------------------------------
// Visual meshes
// -------------------------------------------------------------------------
const faceMeshes = [];
const edgeMeshes = [];
const vertexMeshes = [];
const pickables = {
vertex: vertexMeshes,
edge: edgeMeshes,
face: faceMeshes
};
const selected = {
vertex: new Set(),
edge: new Set(),
face: new Set()
};
let selectedKind = null;
let mode = "vertex";
let hover = null;
const COLORS = {
edge: new THREE.Color(0x9abbd1),
vertex: new THREE.Color(0xeaf6ff),
selected: new THREE.Color(0xffd166),
hover: new THREE.Color(0x72e4ff)
};
// Faces: independent triangular meshes permit reliable face picking.
for (let i = 0; i < faces.length; i++) {
const [a, b, c] = faces[i];
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array([
vertices[a].x * 1.004,
vertices[a].y * 1.004,
vertices[a].z * 1.004,
vertices[b].x * 1.004,
vertices[b].y * 1.004,
vertices[b].z * 1.004,
vertices[c].x * 1.004,
vertices[c].y * 1.004,
vertices[c].z * 1.004
]);
geometry.setAttribute(
"position",
new THREE.BufferAttribute(positions, 3)
);
geometry.computeVertexNormals();
const baseColor = new THREE.Color().setHSL(
0.54 + (i % 6) * 0.012,
0.52,
0.43 + (i % 3) * 0.025
);
const material = new THREE.MeshStandardMaterial({
color: baseColor,
roughness: 0.72,
metalness: 0.08,
flatShading: true,
side: THREE.DoubleSide,
emissive: 0x000000,
emissiveIntensity: 0
});
const mesh = new THREE.Mesh(geometry, material);
mesh.userData = {
kind: "face",
index: i,
baseColor
};
model.add(mesh);
faceMeshes.push(mesh);
}
// Edges: low-sided cylinders provide thicker, raycastable geometry.
const cylinderGeometry = new THREE.CylinderGeometry(
1,
1,
1,
6,
1,
false
);
const upAxis = new THREE.Vector3(0, 1, 0);
for (let i = 0; i < edges.length; i++) {
const { a, b } = edges[i];
const start = vertices[a].clone().multiplyScalar(1.014);
const end = vertices[b].clone().multiplyScalar(1.014);
const direction = end.clone().sub(start);
const length = direction.length();
const material = new THREE.MeshStandardMaterial({
color: COLORS.edge,
roughness: 0.42,
metalness: 0.28,
emissive: 0x000000,
emissiveIntensity: 0
});
const mesh = new THREE.Mesh(cylinderGeometry, material);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
upAxis,
direction.clone().normalize()
);
mesh.scale.set(0.024, length, 0.024);
mesh.userData = {
kind: "edge",
index: i,
a,
b,
baseColor: COLORS.edge
};
model.add(mesh);
edgeMeshes.push(mesh);
}
// Vertices: small faceted icosahedral markers.
const vertexGeometry = new THREE.IcosahedronGeometry(0.075, 0);
for (let i = 0; i < vertices.length; i++) {
const material = new THREE.MeshStandardMaterial({
color: COLORS.vertex,
roughness: 0.35,
metalness: 0.22,
flatShading: true,
emissive: 0x000000,
emissiveIntensity: 0
});
const mesh = new THREE.Mesh(vertexGeometry, material);
mesh.position.copy(vertices[i]).multiplyScalar(1.035);
mesh.userData = {
kind: "vertex",
index: i,
baseColor: COLORS.vertex
};
model.add(mesh);
vertexMeshes.push(mesh);
}
// -------------------------------------------------------------------------
// Counts and Euler relation
// -------------------------------------------------------------------------
document.getElementById("vertexCount").textContent = V;
document.getElementById("edgeCount").textContent = E;
document.getElementById("faceCount").textContent = F;
document.getElementById("eulerV").textContent = V;
document.getElementById("eulerE").textContent = E;
document.getElementById("eulerF").textContent = F;
document.getElementById("eulerResult").textContent = eulerActual;
const eulerStatus = document.getElementById("eulerStatus");
if (eulerActual === eulerExpected) {
eulerStatus.textContent = "✓ Euler characteristic χ = 2";
eulerStatus.style.color = "var(--green)";
} else {
eulerStatus.textContent =
`Expected ${eulerExpected}, received ${eulerActual}`;
eulerStatus.style.color = "#ff8f8f";
}
// -------------------------------------------------------------------------
// Camera controls, implemented without Three.js addons
// -------------------------------------------------------------------------
const orbit = {
theta: 0.73,
phi: 1.08,
radius: 4.15,
target: new THREE.Vector3(0, 0, 0)
};
const initialOrbit = {
theta: orbit.theta,
phi: orbit.phi,
radius: orbit.radius
};
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.cos(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.sin(orbit.theta)
);
camera.lookAt(orbit.target);
camera.updateMatrixWorld();
}
function resetView() {
orbit.theta = initialOrbit.theta;
orbit.phi = initialOrbit.phi;
orbit.radius = initialOrbit.radius;
orbit.target.set(0, 0, 0);
updateCamera();
}
updateCamera();
// -------------------------------------------------------------------------
// Picking and appearance
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function setPointerFromEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function pick(event) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(pickables[mode], false);
if (!hits.length) {
return null;
}
const object = hits[0].object;
return {
kind: object.userData.kind,
index: object.userData.index
};
}
function styleMesh(mesh) {
const { kind, index } = mesh.userData;
const isSelected = selected[kind].has(index);
const isHovered =
hover && hover.kind === kind && hover.index === index;
let color;
let emissive = 0x000000;
let emissiveIntensity = 0;
if (isSelected) {
color = COLORS.selected;
emissive = 0x8a5d00;
emissiveIntensity = 0.36;
} else if (isHovered) {
color = COLORS.hover;
emissive = 0x075666;
emissiveIntensity = 0.42;
} else if (kind === "face") {
color = mesh.userData.baseColor;
} else {
color = mesh.userData.baseColor;
}
mesh.material.color.copy(color);
mesh.material.emissive.setHex(emissive);
mesh.material.emissiveIntensity = emissiveIntensity;
}
function updateAppearance() {
faceMeshes.forEach(styleMesh);
edgeMeshes.forEach(styleMesh);
vertexMeshes.forEach(styleMesh);
}
function updateHover(nextHover) {
const changed =
(!hover && nextHover) ||
(hover && !nextHover) ||
(hover &&
nextHover &&
(hover.kind !== nextHover.kind || hover.index !== nextHover.index));
hover = nextHover;
if (changed) {
updateAppearance();
}
if (hover) {
const prefix = {
vertex: "Vertex",
edge: "Edge",
face: "Face"
}[hover.kind];
const number = String(hover.index + 1).padStart(2, "0");
tooltip.textContent = `${prefix} ${number}`;
tooltip.style.display = "block";
} else {
tooltip.style.display = "none";
}
}
function elementLabel(kind, index) {
if (kind === "vertex") {
return `V${String(index + 1).padStart(2, "0")}`;
}
if (kind === "edge") {
return `E${String(index + 1).padStart(2, "0")}`;
}
return `F${String(index + 1).padStart(2, "0")}`;
}
function elementDescription(kind, index) {
if (kind === "vertex") {
const p = vertices[index];
return `(${p.x.toFixed(2)}, ${p.y.toFixed(2)}, ${p.z.toFixed(2)})`;
}
if (kind === "edge") {
const edge = edges[index];
const a = vertices[edge.a];
const b = vertices[edge.b];
const length = a.distanceTo(b);
return `${elementLabel("vertex", edge.a)} ↔ ${elementLabel("vertex", edge.b)} · length ${length.toFixed(3)}`;
}
const [a, b, c] = faces[index];
const cross = new THREE.Vector3()
.subVectors(vertices[b], vertices[a])
.cross(new THREE.Vector3().subVectors(vertices[c], vertices[a]));
const area = cross.length() * 0.5;
return `${elementLabel("vertex", a)}, ${elementLabel("vertex", b)}, ${elementLabel("vertex", c)} · area ${area.toFixed(3)}`;
}
function renderSelection() {
const selectionTitle = document.getElementById("selectionTitle");
const selectionMeta = document.getElementById("selectionMeta");
const selectionList = document.getElementById("selectionList");
const emptySelection = document.getElementById("emptySelection");
const clearButton = document.getElementById("clearSelection");
selectionList.replaceChildren();
const count = selectedKind
? selected[selectedKind].size
: 0;
document.querySelectorAll(".tool").forEach((button) => {
const buttonMode = button.dataset.mode;
const selectedCount = selected[buttonMode].size;
button.querySelector(".tool-count").textContent =
selectedCount > 0
? `${selectedCount}/${pickables[buttonMode].length}`
: String(pickables[buttonMode].length);
});
clearButton.disabled = count === 0;
if (!count) {
selectionTitle.textContent = "Nothing selected";
selectionMeta.textContent = "Choose a tool and click an element.";
emptySelection.style.display = "block";
return;
}
const kindName = {
vertex: "vertex",
edge: "edge",
face: "face"
}[selectedKind];
selectionTitle.textContent =
count === 1
? `${kindName[0].toUpperCase()}${kindName.slice(1)} ${String([...selected[selectedKind]][0] + 1).padStart(2, "0")}`
: `${count} ${kindName}s selected`;
selectionMeta.textContent =
count === 1
? elementDescription(selectedKind, [...selected[selectedKind]][0])
: "Shift-click or Ctrl-click to adjust this selection.";
emptySelection.style.display = "none";
for (const index of selected[selectedKind]) {
const item = document.createElement("div");
item.className = "selection-item";
const badge = document.createElement("span");
badge.className = "item-badge";
badge.textContent = elementLabel(selectedKind, index);
const description = document.createElement("span");
description.textContent = elementDescription(selectedKind, index);
item.append(badge, description);
selectionList.appendChild(item);
}
}
function selectElement(hit, additive) {
if (!hit) {
if (!additive) {
selected.vertex.clear();
selected.edge.clear();
selected.face.clear();
selectedKind = null;
renderSelection();
updateAppearance();
}
return;
}
if (!additive || selectedKind !== hit.kind) {
selected.vertex.clear();
selected.edge.clear();
selected.face.clear();
selectedKind = hit.kind;
}
const set = selected[hit.kind];
if (additive && set.has(hit.index)) {
set.delete(hit.index);
} else {
set.add(hit.index);
}
renderSelection();
updateAppearance();
}
function setMode(nextMode) {
mode = nextMode;
hover = null;
tooltip.style.display = "none";
document.querySelectorAll(".tool").forEach((button) => {
const active = button.dataset.mode === mode;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
renderer.domElement.style.cursor = "grab";
updateAppearance();
}
document.querySelectorAll(".tool").forEach((button) => {
button.addEventListener("click", () => {
setMode(button.dataset.mode);
});
});
document.getElementById("clearSelection").addEventListener("click", () => {
selected.vertex.clear();
selected.edge.clear();
selected.face.clear();
selectedKind = null;
renderSelection();
updateAppearance();
});
document.getElementById("resetView").addEventListener("click", resetView);
// -------------------------------------------------------------------------
// Pointer interaction: orbit, pan, zoom, and click selection
// -------------------------------------------------------------------------
let pointerDown = false;
let dragMode = "orbit";
let pointerStart = { x: 0, y: 0 };
let previousPointer = { x: 0, y: 0 };
let dragDistance = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
pointerDown = true;
dragDistance = 0;
dragMode = event.button === 2 ? "pan" : "orbit";
pointerStart = { x: event.clientX, y: event.clientY };
previousPointer = { ...pointerStart };
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
renderer.domElement.focus();
event.preventDefault();
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (pointerDown) {
const dx = event.clientX - previousPointer.x;
const dy = event.clientY - previousPointer.y;
dragDistance = Math.max(
dragDistance,
Math.hypot(
event.clientX - pointerStart.x,
event.clientY - pointerStart.y
)
);
if (dragMode === "orbit") {
orbit.theta -= dx * 0.008;
orbit.phi = THREE.MathUtils.clamp(
orbit.phi - dy * 0.008,
0.16,
Math.PI - 0.16
);
} else {
camera.updateMatrixWorld();
const right = new THREE.Vector3()
.setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3()
.setFromMatrixColumn(camera.matrix, 1);
const panScale = orbit.radius * 0.00135;
orbit.target
.addScaledVector(right, -dx * panScale)
.addScaledVector(up, dy * panScale);
}
previousPointer = { x: event.clientX, y: event.clientY };
updateCamera();
return;
}
const hit = pick(event);
updateHover(hit);
renderer.domElement.style.cursor = hit ? "pointer" : "grab";
if (hit) {
const tooltipWidth = tooltip.offsetWidth || 90;
const tooltipHeight = tooltip.offsetHeight || 28;
tooltip.style.left =
Math.min(event.clientX + 14, window.innerWidth - tooltipWidth - 10) +
"px";
tooltip.style.top =
Math.min(event.clientY + 14, window.innerHeight - tooltipHeight - 10) +
"px";
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
const wasClick = !pointerDown || dragDistance < 5;
pointerDown = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
if (event.button === 0 && wasClick) {
const hit = pick(event);
selectElement(hit, event.shiftKey || event.ctrlKey || event.metaKey);
}
renderer.domElement.style.cursor = hover ? "pointer" : "grab";
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = false;
renderer.domElement.style.cursor = "grab";
});
renderer.domElement.addEventListener("pointerleave", () => {
if (!pointerDown) {
updateHover(null);
}
});
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
2.55,
7.5
);
updateCamera();
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (event.target.matches("input, textarea")) {
return;
}
if (event.key === "1") {
setMode("vertex");
} else if (event.key === "2") {
setMode("edge");
} else if (event.key === "3") {
setMode("face");
} else if (event.key.toLowerCase() === "r") {
resetView();
} else if (event.key === "Escape") {
selected.vertex.clear();
selected.edge.clear();
selected.face.clear();
selectedKind = null;
renderSelection();
updateAppearance();
}
});
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function resize() {
const width = stage.clientWidth;
const height = stage.clientHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
updateCamera();
}
window.addEventListener("resize", resize);
renderSelection();
updateAppearance();
resize();
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```