Prompt specification
Build or customize the Three.js 3D scene "Expanding Dot Grid With Pair Distances" 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: Expanding Dot Grid With Pair Distances
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/expanding-dot-grid-with-pair-distances-x3769
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows cosmic expansion represented by an expanding dot grid. Place dots on a uniformly scaling grid and highlight several pairwise separations. Label this a mathematical analogy and distinguish grid coordinates from a physical cosmic map. Low-poly.
Working Three.js Starter (expanding-dot-grid-with-pair-distances-x3769):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Cosmic Expansion — A Mathematical Analogy</title>
<style>
:root {
color-scheme: dark;
--bg: #050713;
--panel: rgba(8, 13, 29, 0.82);
--panel-strong: rgba(10, 17, 36, 0.94);
--line: rgba(146, 178, 224, 0.22);
--text: #edf4ff;
--muted: #9eacc3;
--cyan: #65e6dc;
--amber: #f6c85f;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 68% 30%, rgba(34, 53, 98, 0.28), transparent 38%),
radial-gradient(circle at 24% 70%, rgba(38, 25, 76, 0.22), transparent 42%),
var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#stage,
#labels {
position: fixed;
inset: 0;
}
#stage {
z-index: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
outline: none;
touch-action: none;
}
#stage canvas:active {
cursor: grabbing;
}
#labels {
z-index: 2;
pointer-events: none;
overflow: hidden;
}
.panel {
position: fixed;
z-index: 4;
background: var(--panel);
border: 1px solid var(--line);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(16px) saturate(125%);
-webkit-backdrop-filter: blur(16px) saturate(125%);
clip-path: polygon(
0 0,
calc(100% - 13px) 0,
100% 13px,
100% 100%,
13px 100%,
0 calc(100% - 13px)
);
}
.intro {
top: 24px;
left: 24px;
width: min(460px, calc(100vw - 48px));
padding: 22px 24px 20px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 13px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 7px;
height: 7px;
background: var(--cyan);
box-shadow: 0 0 14px rgba(101, 230, 220, 0.75);
transform: rotate(45deg);
}
h1 {
margin: 0;
max-width: 430px;
font-size: clamp(28px, 3.4vw, 45px);
line-height: 1.03;
letter-spacing: -0.045em;
font-weight: 760;
}
.intro-copy {
margin: 14px 0 0;
max-width: 420px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.equation {
display: inline-flex;
align-items: center;
gap: 10px;
margin-top: 16px;
padding: 9px 12px;
color: #dceaff;
background: rgba(102, 151, 207, 0.08);
border: 1px solid rgba(126, 170, 224, 0.17);
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 12px;
}
.equation strong {
color: var(--amber);
font-weight: 700;
}
.scale-readout {
position: fixed;
z-index: 4;
top: 24px;
right: 24px;
min-width: 156px;
padding: 13px 16px;
background: var(--panel-strong);
border: 1px solid var(--line);
clip-path: polygon(0 0, calc(100% - 10px) 0, 100% 10px, 100% 100%, 0 100%);
pointer-events: none;
}
.scale-readout small {
display: block;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.scale-readout output {
display: block;
margin-top: 3px;
color: var(--amber);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 25px;
font-weight: 700;
}
.scale-readout span {
color: var(--muted);
font-size: 10px;
}
.controls {
right: 24px;
bottom: 24px;
width: 322px;
padding: 16px;
}
.control-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 13px;
}
.control-header strong {
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#status {
color: var(--cyan);
font-size: 10px;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 15px;
}
button {
color: var(--text);
background: rgba(118, 157, 211, 0.09);
border: 1px solid rgba(132, 171, 222, 0.22);
cursor: pointer;
transition: background 140ms ease, border-color 140ms ease, transform 140ms ease;
}
button:hover {
background: rgba(118, 157, 211, 0.17);
border-color: rgba(151, 190, 240, 0.42);
}
button:active {
transform: translateY(1px);
}
.buttons button {
padding: 9px 10px;
font-size: 11px;
font-weight: 700;
}
#play {
color: #071716;
background: var(--cyan);
border-color: transparent;
}
#play:hover {
background: #8af2e9;
}
.range-label {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-bottom: 8px;
color: var(--muted);
font-size: 11px;
}
.range-label output {
color: var(--text);
font-family: "SFMono-Regular", Consolas, monospace;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0 0 15px;
appearance: none;
background: linear-gradient(
to right,
var(--cyan) 0%,
var(--cyan) var(--range, 0%),
rgba(120, 153, 198, 0.2) var(--range, 0%),
rgba(120, 153, 198, 0.2) 100%
);
border-radius: 0;
cursor: ew-resize;
}
input[type="range"]::-webkit-slider-thumb {
width: 13px;
height: 13px;
appearance: none;
background: #dffffc;
border: 2px solid var(--cyan);
border-radius: 50%;
box-shadow: 0 0 13px rgba(101, 230, 220, 0.55);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
background: #dffffc;
border: 2px solid var(--cyan);
border-radius: 50%;
box-shadow: 0 0 13px rgba(101, 230, 220, 0.55);
}
.check {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 14px;
color: var(--muted);
font-size: 11px;
cursor: pointer;
}
.check input {
accent-color: #7d91ad;
}
.legend-title {
margin-bottom: 7px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.legend {
display: grid;
gap: 5px;
}
.legend-item {
display: grid;
grid-template-columns: 12px 18px 1fr auto;
align-items: center;
gap: 7px;
width: 100%;
padding: 6px 7px;
text-align: left;
font-size: 10px;
}
.legend-item.off {
opacity: 0.38;
}
.swatch {
width: 10px;
height: 3px;
background: var(--pair);
box-shadow: 0 0 9px color-mix(in srgb, var(--pair), transparent 45%);
}
.legend-item small,
.legend-item em {
font-style: normal;
font-family: "SFMono-Regular", Consolas, monospace;
}
.legend-item small {
color: var(--muted);
}
.legend-item em {
color: var(--text);
font-size: 9px;
}
.caution {
left: 24px;
bottom: 24px;
width: min(435px, calc(100vw - 48px));
padding: 17px 19px;
background: rgba(25, 16, 31, 0.82);
border-color: rgba(229, 173, 116, 0.24);
}
.caution-title {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
color: #f3c584;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.caution-title::before {
content: "";
width: 9px;
height: 9px;
border: 1px solid #f3c584;
transform: rotate(45deg);
}
.caution p {
margin: 0;
color: #b9b4bd;
font-size: 11px;
line-height: 1.55;
}
.caution p + p {
margin-top: 7px;
}
.caution b {
color: #eadfce;
font-weight: 700;
}
.view-hint {
position: fixed;
z-index: 3;
left: 50%;
bottom: 28px;
transform: translateX(-50%);
color: rgba(192, 205, 225, 0.55);
font-size: 9px;
letter-spacing: 0.08em;
pointer-events: none;
white-space: nowrap;
}
.pair-label,
.axis-label,
.site-label,
.reference-label {
position: absolute;
left: 0;
top: 0;
transform: translate(-50%, -50%);
white-space: nowrap;
pointer-events: none;
}
.pair-label {
padding: 5px 8px;
color: var(--pair);
background: rgba(5, 9, 19, 0.86);
border: 1px solid color-mix(in srgb, var(--pair), transparent 55%);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 10px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.25);
}
.axis-label {
color: #8fa8c7;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 9px;
letter-spacing: 0.04em;
text-shadow: 0 1px 5px #000;
}
.site-label {
padding: 4px 7px;
color: #b9c9df;
background: rgba(5, 9, 19, 0.75);
border-left: 2px solid #6e87aa;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 9px;
}
.reference-label {
color: rgba(174, 190, 212, 0.6);
font-size: 9px;
font-style: italic;
}
#loading {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
background: var(--bg);
color: var(--muted);
font-size: 12px;
letter-spacing: 0.08em;
transition: opacity 300ms ease, visibility 300ms ease;
}
#loading.hidden {
opacity: 0;
visibility: hidden;
}
@media (max-width: 760px) {
.intro {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 16px 17px;
}
.intro h1 {
font-size: 27px;
}
.intro-copy {
display: none;
}
.equation {
margin-top: 12px;
padding: 7px 9px;
font-size: 10px;
}
.scale-readout {
top: 155px;
right: 12px;
min-width: 116px;
padding: 9px 12px;
}
.scale-readout output {
font-size: 20px;
}
.caution {
top: 154px;
bottom: auto;
left: 12px;
width: calc(100vw - 154px);
min-width: 210px;
padding: 11px 12px;
}
.caution-title {
font-size: 8px;
}
.caution p {
font-size: 9px;
}
.caution p + p {
display: none;
}
.controls {
left: 12px;
right: 12px;
bottom: 12px;
width: auto;
padding: 12px;
}
.legend {
grid-template-columns: 1fr 1fr;
}
.legend-item {
grid-template-columns: 10px 13px 1fr;
}
.legend-item em {
display: none;
}
.view-hint {
display: none;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<div id="labels"></div>
<section class="panel intro" aria-labelledby="title">
<div class="eyebrow">Mathematical analogy · not a physical map</div>
<h1 id="title">Cosmic expansion as a uniformly scaling lattice</h1>
<p class="intro-copy">
Every synthetic grid site moves away from the origin while its grid-coordinate
label stays fixed. The colored vectors make the growing pairwise separations visible.
</p>
<div class="equation">
<strong>r′ = a r₀</strong>
<span>and therefore</span>
<strong>Δr′ = a Δr₀</strong>
</div>
</section>
<aside class="scale-readout" aria-live="polite">
<small>Uniform scale factor</small>
<output id="scaleOut">1.00×</output>
<span>coordinate gaps stay fixed</span>
</aside>
<section class="panel controls" aria-label="Animation controls">
<div class="control-header">
<strong>Expansion model</strong>
<span id="status">expanding</span>
</div>
<div class="buttons">
<button id="play" type="button">Pause</button>
<button id="reset" type="button">Reset</button>
</div>
<label class="range-label" for="scaleSlider">
<span>Inspect a scale factor</span>
<output id="rangeOut">1.00×</output>
</label>
<input
id="scaleSlider"
type="range"
min="1"
max="2.8"
step="0.01"
value="1"
aria-label="Uniform lattice scale factor"
/>
<label class="check">
<input id="referenceToggle" type="checkbox" checked />
Show the fixed a = 1 reference lattice
</label>
<div class="legend-title">Highlighted pairwise separations</div>
<div class="legend" id="legend"></div>
</section>
<section class="panel caution" aria-label="Coordinate disclaimer">
<div class="caution-title">Grid coordinates are not cosmic coordinates</div>
<p>
<b>x_grid</b> and <b>y_grid</b> are labels on a synthetic mathematical lattice.
No dot represents a galaxy or sky position.
</p>
<p>
This simplified Euclidean analogy does not depict gravity, spacetime curvature,
an expansion history, measured distances, or a real map of the cosmos.
</p>
</section>
<div class="view-hint">DRAG TO ORBIT · WHEEL TO ZOOM · DOUBLE-CLICK TO RESET VIEW</div>
<div id="loading">Loading the mathematical model…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const stage = document.getElementById("stage");
const labelsLayer = document.getElementById("labels");
const loading = document.getElementById("loading");
const GRID_MIN = -4;
const GRID_MAX = 4;
const GRID_SIDE = GRID_MAX - GRID_MIN + 1;
const MAX_SCALE = 2.8;
const INITIAL_SCALE = 1;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x050713);
scene.fog = new THREE.Fog(0x050713, 38, 125);
let renderer;
try {
renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
} catch (error) {
loading.textContent = "This demonstration requires WebGL.";
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const canvas = renderer.domElement;
canvas.tabIndex = 0;
canvas.setAttribute("role", "img");
canvas.setAttribute(
"aria-label",
"Interactive low-poly dot lattice expanding uniformly from its center"
);
stage.appendChild(canvas);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
250
);
const view = {
azimuth: 0.67,
polar: 0.94,
radius: window.innerWidth < 760 ? 55 : 28
};
function updateCamera() {
const sinPolar = Math.sin(view.polar);
camera.position.set(
view.radius * sinPolar * Math.cos(view.azimuth),
view.radius * Math.cos(view.polar),
view.radius * sinPolar * Math.sin(view.azimuth)
);
camera.lookAt(0, 0, 0);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xa9d8ff, 0x111126, 1.55);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xc7e7ff, 2.4);
keyLight.position.set(7, 11, 5);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x826dff, 1.35);
rimLight.position.set(-9, 4, -7);
scene.add(rimLight);
// A sparse, deliberately simple background star field.
const starPositions = [];
let randomSeed = 9182;
function random() {
randomSeed = (randomSeed * 16807) % 2147483647;
return (randomSeed - 1) / 2147483646;
}
for (let i = 0; i < 620; i++) {
const theta = random() * Math.PI * 2;
const phi = Math.acos(2 * random() - 1);
const radius = 42 + random() * 72;
starPositions.push(
radius * Math.sin(phi) * Math.cos(theta),
radius * Math.cos(phi),
radius * Math.sin(phi) * Math.sin(theta)
);
}
const starGeometry = new THREE.BufferGeometry();
starGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(starPositions, 3)
);
const stars = new THREE.Points(
starGeometry,
new THREE.PointsMaterial({
color: 0x9fb5d6,
size: 0.07,
transparent: true,
opacity: 0.58,
sizeAttenuation: true,
depthWrite: false
})
);
scene.add(stars);
const latticePoints = [];
for (let y = GRID_MIN; y <= GRID_MAX; y++) {
for (let x = GRID_MIN; x <= GRID_MAX; x++) {
latticePoints.push({ x, y });
}
}
// Main lattice dots: low-poly icosahedra in an InstancedMesh.
const dotGeometry = new THREE.IcosahedronGeometry(0.095, 0);
const dotMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.66,
metalness: 0.12,
flatShading: true,
emissive: 0x07172a,
emissiveIntensity: 0.6
});
const dots = new THREE.InstancedMesh(
dotGeometry,
dotMaterial,
latticePoints.length
);
dots.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
dots.frustumCulled = false;
scene.add(dots);
const dummy = new THREE.Object3D();
const dotColor = new THREE.Color();
latticePoints.forEach((point, index) => {
const radius = Math.hypot(point.x, point.y) / Math.hypot(4, 4);
dotColor.setHSL(
0.56 + (1 - radius) * 0.055,
0.57 + (1 - radius) * 0.12,
0.59 + (1 - radius) * 0.12
);
dots.setColorAt(index, dotColor);
});
dots.instanceColor.needsUpdate = true;
// Current grid lines.
const lineSegments = [];
for (let v = GRID_MIN; v <= GRID_MAX; v++) {
for (let u = GRID_MIN; u < GRID_MAX; u++) {
lineSegments.push(
u, v, -0.055, u + 1, v, -0.055,
v, u, -0.055, v, u + 1, -0.055
);
}
}
const lineGeometry = new THREE.BufferGeometry();
lineGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(lineSegments, 3)
);
const gridLines = new THREE.LineSegments(
lineGeometry,
new THREE.LineBasicMaterial({
color: 0x527294,
transparent: true,
opacity: 0.24,
depthWrite: false
})
);
scene.add(gridLines);
const boundaryGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(GRID_MIN - 0.15, -0.04, GRID_MIN - 0.15),
new THREE.Vector3(GRID_MAX + 0.15, -0.04, GRID_MIN - 0.15),
new THREE.Vector3(GRID_MAX + 0.15, -0.04, GRID_MAX + 0.15),
new THREE.Vector3(GRID_MIN - 0.15, -0.04, GRID_MAX + 0.15)
]);
const boundary = new THREE.LineLoop(
boundaryGeometry,
new THREE.LineBasicMaterial({
color: 0x7094bb,
transparent: true,
opacity: 0.4
})
);
scene.add(boundary);
// Fixed a = 1 reference lattice.
const referenceGroup = new THREE.Group();
const referencePositions = [];
for (const point of latticePoints) {
referencePositions.push(point.x, -0.035, point.y);
}
const referenceGeometry = new THREE.BufferGeometry();
referenceGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(referencePositions, 3)
);
const referenceDots = new THREE.Points(
referenceGeometry,
new THREE.PointsMaterial({
color: 0x8798b1,
size: 0.045,
transparent: true,
opacity: 0.38,
depthWrite: false
})
);
referenceGroup.add(referenceDots);
const referenceBoundary = new THREE.LineLoop(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(GRID_MIN - 0.15, -0.045, GRID_MIN - 0.15),
new THREE.Vector3(GRID_MAX + 0.15, -0.045, GRID_MIN - 0.15),
new THREE.Vector3(GRID_MAX + 0.15, -0.045, GRID_MAX + 0.15),
new THREE.Vector3(GRID_MIN - 0.15, -0.045, GRID_MAX + 0.15)
]),
new THREE.LineBasicMaterial({
color: 0x718096,
transparent: true,
opacity: 0.3
})
);
referenceGroup.add(referenceBoundary);
scene.add(referenceGroup);
// Grid axes are explicitly named as lattice axes.
const axesGroup = new THREE.Group();
const xAxis = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(0, 0.015, 0),
4.8,
0x6685a9,
0.16,
0.08
);
const yAxis = new THREE.ArrowHelper(
new THREE.Vector3(0, 0, 1),
new THREE.Vector3(0, 0.015, 0),
4.8,
0x6685a9,
0.16,
0.08
);
axesGroup.add(xAxis, yAxis);
scene.add(axesGroup);
function makeLabel(className, text) {
const element = document.createElement("div");
element.className = className;
element.textContent = text;
labelsLayer.appendChild(element);
return element;
}
const xGridLabel = makeLabel("axis-label", "x_grid");
const yGridLabel = makeLabel("axis-label", "y_grid");
const siteLabel = makeLabel("site-label", "site (3, −3) · grid coords");
const referenceLabel = makeLabel("reference-label", "fixed a = 1 reference");
const pairDefinitions = [
{
id: "A",
color: "#f6c85f",
a: [-2, -1],
b: [2, -1]
},
{
id: "B",
color: "#65e6dc",
a: [-3, 2],
b: [-1, -1]
},
{
id: "C",
color: "#ff6f9f",
a: [1, -3],
b: [3, 1]
},
{
id: "D",
color: "#9b8cff",
a: [-1, 3],
b: [3, 3]
}
];
const legend = document.getElementById("legend");
const pairs = [];
function createEndpoint(color) {
const group = new THREE.Group();
const core = new THREE.Mesh(
new THREE.OctahedronGeometry(0.13, 0),
new THREE.MeshBasicMaterial({ color })
);
const glow = new THREE.Mesh(
new THREE.OctahedronGeometry(0.23, 0),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.12,
depthWrite: false
})
);
group.add(core, glow);
return group;
}
pairDefinitions.forEach((definition) => {
const group = new THREE.Group();
const line = new THREE.Mesh(
new THREE.CylinderGeometry(0.021, 0.021, 1, 6, 1, false),
new THREE.MeshBasicMaterial({
color: definition.color,
transparent: true,
opacity: 0.95
})
);
const endpointA = createEndpoint(definition.color);
const endpointB = createEndpoint(definition.color);
group.add(line, endpointA, endpointB);
scene.add(group);
const label = makeLabel("pair-label", "");
label.style.setProperty("--pair", definition.color);
const distance = Math.hypot(
definition.b[0] - definition.a[0],
definition.b[1] - definition.a[1]
);
label.innerHTML = `${definition.id} · Δ₀ = ${distance.toFixed(2)}`;
const legendButton = document.createElement("button");
legendButton.type = "button";
legendButton.className = "legend-item";
legendButton.style.setProperty("--pair", definition.color);
legendButton.setAttribute("aria-pressed", "true");
legendButton.innerHTML = `
<span class="swatch"></span>
<strong>${definition.id}</strong>
<small>${distance.toFixed(2)} Δ₀</small>
<em></em>
`;
const pair = {
...definition,
group,
line,
endpointA,
endpointB,
label,
distance,
enabled: true,
legendButton,
currentLengthElement: legendButton.querySelector("em")
};
legendButton.addEventListener("click", () => {
pair.enabled = !pair.enabled;
pair.group.visible = pair.enabled;
legendButton.classList.toggle("off", !pair.enabled);
legendButton.setAttribute("aria-pressed", String(pair.enabled));
});
legend.appendChild(legendButton);
pairs.push(pair);
});
const playButton = document.getElementById("play");
const resetButton = document.getElementById("reset");
const scaleSlider = document.getElementById("scaleSlider");
const scaleOut = document.getElementById("scaleOut");
const rangeOut = document.getElementById("rangeOut");
const status = document.getElementById("status");
const referenceToggle = document.getElementById("referenceToggle");
let scale = INITIAL_SCALE;
let playing = true;
function syncPlayState() {
if (playing) {
playButton.textContent = "Pause";
status.textContent = "expanding";
status.style.color = "var(--cyan)";
} else if (scale >= MAX_SCALE - 0.001) {
playButton.textContent = "Replay";
status.textContent = "limit reached";
status.style.color = "var(--amber)";
} else {
playButton.textContent = "Resume";
status.textContent = "paused";
status.style.color = "var(--muted)";
}
}
playButton.addEventListener("click", () => {
if (playing) {
playing = false;
} else {
if (scale >= MAX_SCALE - 0.001) {
scale = INITIAL_SCALE;
}
playing = true;
}
syncPlayState();
});
resetButton.addEventListener("click", () => {
scale = INITIAL_SCALE;
playing = true;
syncPlayState();
});
scaleSlider.addEventListener("input", () => {
scale = Number(scaleSlider.value);
playing = false;
syncPlayState();
});
referenceToggle.addEventListener("change", () => {
referenceGroup.visible = referenceToggle.checked;
});
const yAxisUnit = new THREE.Vector3(0, 1, 0);
function updateLattice() {
latticePoints.forEach((point, index) => {
dummy.position.set(point.x * scale, 0.055, point.y * scale);
dummy.rotation.set(0, 0, 0);
dummy.scale.setScalar(1);
dummy.updateMatrix();
dots.setMatrixAt(index, dummy.matrix);
});
dots.instanceMatrix.needsUpdate = true;
gridLines.scale.setScalar(scale);
boundary.scale.setScalar(scale);
axesGroup.scale.setScalar(scale);
for (const pair of pairs) {
const start = new THREE.Vector3(
pair.a[0] * scale,
0.09,
pair.a[1] * scale
);
const end = new THREE.Vector3(
pair.b[0] * scale,
0.09,
pair.b[1] * scale
);
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
const midpoint = new THREE.Vector3()
.addVectors(start, end)
.multiplyScalar(0.5);
pair.line.position.copy(midpoint);
pair.line.scale.set(1, length, 1);
pair.line.quaternion.setFromUnitVectors(
yAxisUnit,
direction.clone().normalize()
);
pair.endpointA.position.copy(start);
pair.endpointB.position.copy(end);
pair.currentLengthElement.textContent =
`${(pair.distance * scale).toFixed(2)} u`;
}
scaleOut.textContent = `${scale.toFixed(2)}×`;
rangeOut.textContent = `${scale.toFixed(2)}×`;
scaleSlider.value = String(scale);
scaleSlider.style.setProperty(
"--range",
`${((scale - 1) / (MAX_SCALE - 1)) * 100}%`
);
}
function projectLabel(element, worldPosition, enabled = true) {
if (!enabled) {
element.style.display = "none";
return;
}
const projected = worldPosition.clone().project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.08 &&
projected.x < 1.08 &&
projected.y > -1.08 &&
projected.y < 1.08;
if (!visible) {
element.style.display = "none";
return;
}
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.display = "block";
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
function updateLabels() {
for (const pair of pairs) {
const midpoint = new THREE.Vector3(
(pair.a[0] + pair.b[0]) * 0.5 * scale,
0.38,
(pair.a[1] + pair.b[1]) * 0.5 * scale
);
projectLabel(pair.label, midpoint, pair.enabled);
}
projectLabel(
xGridLabel,
new THREE.Vector3(5.05 * scale, 0.1, 0),
true
);
projectLabel(
yGridLabel,
new THREE.Vector3(0, 0.1, 5.05 * scale),
true
);
projectLabel(
siteLabel,
new THREE.Vector3(3 * scale, 0.2, -3 * scale),
true
);
projectLabel(
referenceLabel,
new THREE.Vector3(-4.4, 0.08, -4.4),
referenceGroup.visible
);
}
// Camera controls are implemented directly, without examples or addons.
let dragging = false;
let previousX = 0;
let previousY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
canvas.setPointerCapture(event.pointerId);
canvas.focus({ preventScroll: true });
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousX;
const deltaY = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
view.azimuth -= deltaX * 0.006;
view.polar = THREE.MathUtils.clamp(
view.polar - deltaY * 0.005,
0.28,
1.43
);
updateCamera();
});
function endDrag(event) {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
view.radius = THREE.MathUtils.clamp(
view.radius * Math.exp(event.deltaY * 0.001),
10,
82
);
updateCamera();
},
{ passive: false }
);
function resetView() {
view.azimuth = 0.67;
view.polar = 0.94;
view.radius = window.innerWidth < 760 ? 55 : 28;
updateCamera();
}
canvas.addEventListener("dblclick", resetView);
canvas.addEventListener("keydown", (event) => {
const key = event.key;
let handled = true;
if (key === "ArrowLeft") view.azimuth += 0.08;
else if (key === "ArrowRight") view.azimuth -= 0.08;
else if (key === "ArrowUp") view.polar -= 0.06;
else if (key === "ArrowDown") view.polar += 0.06;
else if (key === "+" || key === "=") view.radius *= 0.9;
else if (key === "-") view.radius *= 1.1;
else if (key === "Home") resetView();
else handled = false;
if (handled) {
event.preventDefault();
view.polar = THREE.MathUtils.clamp(view.polar, 0.28, 1.43);
view.radius = THREE.MathUtils.clamp(view.radius, 10, 82);
updateCamera();
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (playing) {
scale = Math.min(MAX_SCALE, scale + delta * 0.19);
if (scale >= MAX_SCALE) {
playing = false;
syncPlayState();
}
}
updateLattice();
updateLabels();
renderer.render(scene, camera);
}
syncPlayState();
updateLattice();
animate();
loading.classList.add("hidden");
</script>
</body>
</html>
```