Prompt specification
Build or customize the Three.js 3D scene "Gear chain direction experiment" 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: Gear chain direction experiment
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/gear-chain-direction-experiment-x0338
Scene Description Prompt:
Add a third gear between input and output positions; animate how the final direction changes with the number of intermediate engagements while tooth contacts remain coherent. Build this with Three.js from cdnjs as a low-poly scene in one HTML file.
Working Three.js Starter (gear-chain-direction-experiment-x0338):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Three.js Gear Engagement Demo</title>
<style>
:root {
--panel: rgba(15, 23, 42, 0.9);
--border: rgba(148, 163, 184, 0.25);
--text: #e5eefb;
--muted: #9fb0c7;
--orange: #fb923c;
--cyan: #38bdf8;
--green: #4ade80;
}
* {
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;
background: #e8eef5;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#scene canvas.dragging {
cursor: grabbing;
}
.panel {
position: fixed;
z-index: 10;
top: 18px;
left: 18px;
width: min(360px, calc(100vw - 36px));
padding: 18px;
color: var(--text);
background: var(--panel);
border: 1px solid var(--border);
border-radius: 16px;
box-shadow: 0 18px 50px rgba(15, 23, 42, 0.2);
backdrop-filter: blur(12px);
}
h1 {
margin: 0 0 5px;
font-size: 21px;
letter-spacing: -0.02em;
}
.subtitle {
margin: 0 0 16px;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.section-label {
margin: 0 0 8px;
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.button-row {
display: flex;
gap: 8px;
margin-bottom: 14px;
}
button {
appearance: none;
border: 1px solid var(--border);
border-radius: 9px;
padding: 9px 11px;
color: var(--text);
background: rgba(148, 163, 184, 0.09);
font: inherit;
font-size: 13px;
font-weight: 650;
cursor: pointer;
transition:
background 150ms ease,
border-color 150ms ease,
transform 150ms ease;
}
button:hover {
background: rgba(148, 163, 184, 0.18);
transform: translateY(-1px);
}
button:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
.count-button {
flex: 1;
}
button.active {
color: #07111f;
background: var(--cyan);
border-color: var(--cyan);
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin: 14px 0;
}
.stat {
min-width: 0;
padding: 10px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(15, 23, 42, 0.38);
}
.stat span {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 10px;
line-height: 1.25;
text-transform: uppercase;
}
.stat strong {
display: block;
font-size: 15px;
white-space: nowrap;
}
.direction-card {
display: flex;
align-items: center;
gap: 12px;
margin: 14px 0;
padding: 12px;
border: 1px solid rgba(74, 222, 128, 0.28);
border-radius: 12px;
background: rgba(74, 222, 128, 0.08);
}
#directionGlyph {
width: 48px;
color: var(--green);
font-size: 42px;
font-weight: 800;
line-height: 1;
text-align: center;
transform-origin: center;
}
#directionGlyph.pop {
animation: direction-pop 450ms cubic-bezier(0.2, 0.9, 0.25, 1.3);
}
@keyframes direction-pop {
0% {
opacity: 0;
transform: scale(0.55) rotate(-18deg);
}
100% {
opacity: 1;
transform: scale(1) rotate(0);
}
}
.direction-card strong {
display: block;
margin-bottom: 3px;
font-size: 14px;
}
.direction-card small {
color: var(--muted);
font-size: 11px;
}
.note {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.actions {
display: flex;
gap: 8px;
margin-top: 14px;
}
.actions button {
flex: 1;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-top: 13px;
color: var(--muted);
font-size: 11px;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 50%;
}
.swatch.input {
background: var(--orange);
}
.swatch.idler {
background: var(--cyan);
}
.swatch.output {
background: var(--green);
}
.swatch.contact {
background: #fbbf24;
}
#labels {
position: fixed;
inset: 0;
z-index: 4;
overflow: hidden;
pointer-events: none;
}
.gear-label {
position: absolute;
padding: 4px 8px;
color: #dbeafe;
background: rgba(15, 23, 42, 0.78);
border: 1px solid rgba(148, 163, 184, 0.25);
border-radius: 999px;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
white-space: nowrap;
transform: translate(-50%, -50%);
}
.gear-label.input {
color: #fed7aa;
border-color: rgba(251, 146, 60, 0.45);
}
.gear-label.output {
color: #bbf7d0;
border-color: rgba(74, 222, 128, 0.45);
}
.help {
position: fixed;
z-index: 8;
right: 16px;
bottom: 15px;
padding: 8px 11px;
color: rgba(30, 41, 59, 0.72);
background: rgba(255, 255, 255, 0.72);
border: 1px solid rgba(71, 85, 105, 0.12);
border-radius: 8px;
font-size: 11px;
backdrop-filter: blur(8px);
pointer-events: none;
}
@media (max-width: 680px) {
.panel {
top: 10px;
left: 10px;
padding: 14px;
}
h1 {
font-size: 18px;
}
.subtitle {
margin-bottom: 11px;
}
.stats {
margin: 10px 0;
}
.help {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div id="labels"></div>
<section class="panel" aria-label="Gear train controls">
<h1>Intermediate Gear Parity</h1>
<p class="subtitle">
Add or remove intermediate gears. Every external mesh reverses
rotation, so the final direction depends on the engagement count.
</p>
<p class="section-label">Intermediate gears</p>
<div class="button-row" role="group" aria-label="Number of intermediate gears">
<button class="count-button" data-count="1">1 gear</button>
<button class="count-button" data-count="2">2 gears</button>
<button class="count-button active" data-count="3">3 gears</button>
</div>
<div class="stats">
<div class="stat">
<span>Intermediate</span>
<strong id="gearCount">3</strong>
</div>
<div class="stat">
<span>External meshes</span>
<strong id="meshCount">4</strong>
</div>
<div class="stat">
<span>Tooth ratio</span>
<strong>1 : 1</strong>
</div>
</div>
<div class="direction-card">
<div id="directionGlyph" aria-hidden="true">←</div>
<div>
<strong id="directionText">Same direction</strong>
<small id="directionDetail">Counterclockwise output</small>
</div>
</div>
<p class="note">
The amber points mark the active tooth-contact locations. Adjacent
gears use exact pitch-circle spacing and complementary tooth phases.
</p>
<div class="actions">
<button id="pauseButton">Pause</button>
<button id="cycleButton">Auto-cycle</button>
<button id="resetButton">Reset view</button>
</div>
<div class="legend">
<span class="legend-item">
<span class="swatch input"></span>Input
</span>
<span class="legend-item">
<span class="swatch idler"></span>Intermediate
</span>
<span class="legend-item">
<span class="swatch output"></span>Output
</span>
<span class="legend-item">
<span class="swatch contact"></span>Contact
</span>
</div>
</section>
<div class="help">Drag to orbit · Scroll to zoom · Keys 1–3 change gears</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Configuration
// -------------------------------------------------------------------------
const TOOTH_COUNT = 18; // Even count keeps the phase pattern simple.
const MODULE = 0.16;
const PRESSURE_ANGLE = THREE.MathUtils.degToRad(20);
const PITCH_RADIUS = MODULE * TOOTH_COUNT / 2;
const ADDENDUM_RADIUS = PITCH_RADIUS + MODULE;
const ROOT_RADIUS = PITCH_RADIUS - 1.25 * MODULE;
const BASE_RADIUS = PITCH_RADIUS * Math.cos(PRESSURE_ANGLE);
const GEAR_DEPTH = 0.52;
const CENTER_SPACING = PITCH_RADIUS * 2;
const TAU = Math.PI * 2;
const sceneHost = document.getElementById("scene");
const labelHost = document.getElementById("labels");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8eef5);
scene.fog = new THREE.Fog(0xe8eef5, 22, 42);
const camera = new THREE.PerspectiveCamera(
40,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, -0.2, 0);
const cameraState = {
theta: 0.64,
phi: 0.72,
radius: window.innerWidth < 700 ? 17 : 14.3
};
const hemisphere = new THREE.HemisphereLight(
0xeaf4ff,
0x68778c,
2.25
);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(-5, 9, 11);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.normalBias = 0.025;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x93c5fd, 1.25);
rimLight.position.set(8, 3, -7);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(38, 26),
new THREE.MeshStandardMaterial({
color: 0xdbe4ee,
roughness: 0.94,
metalness: 0.02
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -2.45;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(30, 30, 0x94a3b8, 0xb8c4d2);
grid.position.y = -2.435;
grid.material.transparent = true;
grid.material.opacity = 0.26;
grid.material.depthWrite = false;
scene.add(grid);
const baseRail = new THREE.Mesh(
new THREE.BoxGeometry(14.4, 0.18, 1.15),
new THREE.MeshStandardMaterial({
color: 0x334155,
roughness: 0.62,
metalness: 0.22
})
);
baseRail.position.set(0, -2.35, -0.25);
baseRail.receiveShadow = true;
baseRail.castShadow = true;
scene.add(baseRail);
// -------------------------------------------------------------------------
// Low-poly involute-style gear geometry
// -------------------------------------------------------------------------
function polar(radius, angle) {
return new THREE.Vector2(
Math.cos(angle) * radius,
Math.sin(angle) * radius
);
}
function involuteAngle(radius) {
if (radius <= BASE_RADIUS) return 0;
const alpha = Math.acos(BASE_RADIUS / radius);
return Math.tan(alpha) - alpha;
}
function halfToothWidth(radius) {
const halfToothAtPitch = Math.PI / (2 * TOOTH_COUNT);
const involuteAtPitch =
Math.tan(PRESSURE_ANGLE) - PRESSURE_ANGLE;
return (
halfToothAtPitch +
involuteAtPitch -
involuteAngle(radius)
);
}
function createGearShape() {
const shape = new THREE.Shape();
const points = [];
const toothAngle = TAU / TOOTH_COUNT;
const baseHalfWidth = halfToothWidth(BASE_RADIUS);
const rootHalfWidth = baseHalfWidth;
for (let tooth = 0; tooth < TOOTH_COUNT; tooth++) {
const center = tooth * toothAngle;
// Root valley before this tooth.
points.push(polar(ROOT_RADIUS, center - toothAngle * 0.5));
// Left root and radial transition to the base circle.
points.push(polar(ROOT_RADIUS, center - rootHalfWidth));
if (ROOT_RADIUS < BASE_RADIUS - 0.0001) {
points.push(polar(BASE_RADIUS, center - baseHalfWidth));
}
// Left involute flank, sampled into three low-poly segments.
points.push(polar(BASE_RADIUS, center - halfToothWidth(BASE_RADIUS)));
points.push(polar(PITCH_RADIUS, center - halfToothWidth(PITCH_RADIUS)));
points.push(polar(ADDENDUM_RADIUS, center - halfToothWidth(ADDENDUM_RADIUS)));
// Tooth tip.
points.push(polar(ADDENDUM_RADIUS, center));
// Right involute flank.
points.push(polar(ADDENDUM_RADIUS, center + halfToothWidth(ADDENDUM_RADIUS)));
points.push(polar(PITCH_RADIUS, center + halfToothWidth(PITCH_RADIUS)));
points.push(polar(BASE_RADIUS, center + halfToothWidth(BASE_RADIUS)));
// Radial transition back into the root.
points.push(polar(ROOT_RADIUS, center + rootHalfWidth));
}
shape.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
shape.lineTo(points[i].x, points[i].y);
}
shape.closePath();
return shape;
}
const gearGeometry = new THREE.ExtrudeGeometry(createGearShape(), {
depth: GEAR_DEPTH,
steps: 1,
bevelEnabled: false,
curveSegments: 1
});
gearGeometry.translate(0, 0, -GEAR_DEPTH / 2);
gearGeometry.computeVertexNormals();
const hubGeometry = new THREE.CylinderGeometry(
0.36,
0.36,
0.72,
12
);
const capGeometry = new THREE.CylinderGeometry(
0.18,
0.18,
0.12,
10
);
const axleGeometry = new THREE.CylinderGeometry(
0.12,
0.12,
1.55,
10
);
const postGeometry = new THREE.CylinderGeometry(
0.105,
0.15,
2.12,
8
);
const footGeometry = new THREE.BoxGeometry(
0.68,
0.14,
0.72
);
const markerGeometry = new THREE.OctahedronGeometry(0.105, 0);
const supportMaterial = new THREE.MeshStandardMaterial({
color: 0x475569,
roughness: 0.48,
metalness: 0.58,
flatShading: true
});
const contactMaterial = new THREE.MeshBasicMaterial({
color: 0xfbbf24
});
const markerMaterial = new THREE.MeshBasicMaterial({
color: 0xf8fafc
});
const materialCache = new Map();
function getGearMaterials(color) {
const key = String(color);
if (!materialCache.has(key)) {
const face = new THREE.MeshStandardMaterial({
color,
roughness: 0.34,
metalness: 0.38,
flatShading: true,
emissive: new THREE.Color(color).multiplyScalar(0.045)
});
const side = new THREE.MeshStandardMaterial({
color: new THREE.Color(color).multiplyScalar(0.48),
roughness: 0.42,
metalness: 0.46,
flatShading: true
});
materialCache.set(key, [face, side]);
}
return materialCache.get(key);
}
// -------------------------------------------------------------------------
// Train construction
// -------------------------------------------------------------------------
const trainGroup = new THREE.Group();
scene.add(trainGroup);
const inputArrow = new THREE.ArrowHelper(
new THREE.Vector3(-1, 0, 0),
new THREE.Vector3(),
1.65,
0xfb923c,
0.34,
0.2
);
scene.add(inputArrow);
const outputArrow = new THREE.ArrowHelper(
new THREE.Vector3(-1, 0, 0),
new THREE.Vector3(),
1.65,
0x4ade80,
0.34,
0.2
);
scene.add(outputArrow);
const inputColor = 0xf97316;
const outputColor = 0x22c55e;
const idlerColors = [0x0ea5e9, 0x8b5cf6, 0x06b6d4];
let intermediateCount = 3;
let gears = [];
let contacts = [];
let labels = [];
let simulationAngle = 0;
let running = true;
let rebuildStarted = performance.now();
function createLabel(text, className, x) {
const element = document.createElement("div");
element.className = `gear-label ${className}`;
element.textContent = text;
labelHost.appendChild(element);
labels.push({
element,
x,
y: 1.95
});
}
function rebuildTrain() {
trainGroup.clear();
labelHost.replaceChildren();
gears = [];
contacts = [];
labels = [];
const totalGearCount = intermediateCount + 2;
const firstX = -((totalGearCount - 1) * CENTER_SPACING) / 2;
const lastX = -firstX;
const axleLinePoints = [];
for (let index = 0; index < totalGearCount; index++) {
const x = firstX + index * CENTER_SPACING;
const isInput = index === 0;
const isOutput = index === totalGearCount - 1;
const idlerIndex = index - 1;
const color = isInput
? inputColor
: isOutput
? outputColor
: idlerColors[idlerIndex % idlerColors.length];
const role = isInput
? "input"
: isOutput
? "output"
: "idler";
// Alternating rotations preserve the complementary tooth phase.
const sign = index % 2 === 0 ? 1 : -1;
// With an even tooth count, this places a gap opposite a tooth.
const phase = index % 2 === 0 ? 0 : Math.PI / TOOTH_COUNT;
const rotatingGroup = new THREE.Group();
rotatingGroup.position.set(x, 0, 0);
const gearMesh = new THREE.Mesh(
gearGeometry,
getGearMaterials(color)
);
gearMesh.castShadow = true;
gearMesh.receiveShadow = true;
rotatingGroup.add(gearMesh);
const hub = new THREE.Mesh(
hubGeometry,
getGearMaterials(color)[0]
);
hub.rotation.x = Math.PI / 2;
hub.castShadow = true;
rotatingGroup.add(hub);
const cap = new THREE.Mesh(
capGeometry,
supportMaterial
);
cap.rotation.x = Math.PI / 2;
cap.position.z = 0.4;
rotatingGroup.add(cap);
// A face marker makes angular motion easy to follow.
const rotationMarker = new THREE.Mesh(
new THREE.SphereGeometry(0.085, 8, 5),
markerMaterial
);
rotationMarker.position.set(0.73, 0, GEAR_DEPTH / 2 + 0.025);
rotatingGroup.add(rotationMarker);
trainGroup.add(rotatingGroup);
// Static support and axle.
const support = new THREE.Group();
const post = new THREE.Mesh(postGeometry, supportMaterial);
post.position.set(x, -1.14, -0.58);
post.castShadow = true;
support.add(post);
const foot = new THREE.Mesh(footGeometry, supportMaterial);
foot.position.set(x, -2.2, -0.45);
foot.castShadow = true;
foot.receiveShadow = true;
support.add(foot);
const axle = new THREE.Mesh(axleGeometry, supportMaterial);
axle.rotation.x = Math.PI / 2;
axle.position.set(x, 0, -0.28);
axle.castShadow = true;
support.add(axle);
trainGroup.add(support);
gears.push({
group: rotatingGroup,
phase,
sign
});
axleLinePoints.push(new THREE.Vector3(x, 0, -0.47));
if (isInput) {
createLabel("INPUT", "input", x);
} else if (isOutput) {
createLabel("OUTPUT", "output", x);
} else {
createLabel(`IDLER ${idlerIndex + 1}`, "idler", x);
}
}
// A subtle line behind the gears shows the common drive path.
const axleLineGeometry = new THREE.BufferGeometry().setFromPoints(
axleLinePoints
);
const axleLine = new THREE.Line(
axleLineGeometry,
new THREE.LineBasicMaterial({
color: 0x64748b,
transparent: true,
opacity: 0.35
})
);
trainGroup.add(axleLine);
// Contact markers are exactly on the pitch points.
for (let index = 0; index < totalGearCount - 1; index++) {
const contact = new THREE.Mesh(
markerGeometry,
contactMaterial
);
contact.position.set(
firstX + index * CENTER_SPACING + CENTER_SPACING / 2,
0,
0.42
);
contact.userData.phase = index * 0.72;
trainGroup.add(contact);
contacts.push(contact);
}
inputArrow.position.set(firstX, 2.7, 0.35);
outputArrow.position.set(lastX, 2.7, 0.35);
const outputSign = (totalGearCount - 1) % 2 === 0 ? 1 : -1;
// At the top of a gear:
// positive Z rotation moves tangentially toward negative X.
outputArrow.setDirection(
new THREE.Vector3(-outputSign, 0, 0)
);
simulationAngle = 0;
rebuildStarted = performance.now();
trainGroup.scale.setScalar(0.94);
updateStatus(outputSign);
}
const directionGlyph = document.getElementById("directionGlyph");
const directionText = document.getElementById("directionText");
const directionDetail = document.getElementById("directionDetail");
const gearCountElement = document.getElementById("gearCount");
const meshCountElement = document.getElementById("meshCount");
function updateStatus(outputSign) {
const meshCount = intermediateCount + 1;
const sameDirection = outputSign > 0;
gearCountElement.textContent = String(intermediateCount);
meshCountElement.textContent = String(meshCount);
directionGlyph.textContent = sameDirection ? "←" : "→";
directionText.textContent = sameDirection
? "Same direction"
: "Reversed direction";
directionDetail.textContent = sameDirection
? "Counterclockwise output"
: "Clockwise output";
directionGlyph.classList.remove("pop");
void directionGlyph.offsetWidth;
directionGlyph.classList.add("pop");
document.querySelectorAll(".count-button").forEach((button) => {
const selected = Number(button.dataset.count) === intermediateCount;
button.classList.toggle("active", selected);
button.setAttribute("aria-pressed", String(selected));
});
}
function setIntermediateCount(count) {
intermediateCount = count;
rebuildTrain();
}
document.querySelectorAll(".count-button").forEach((button) => {
button.addEventListener("click", () => {
setIntermediateCount(Number(button.dataset.count));
});
});
const pauseButton = document.getElementById("pauseButton");
pauseButton.addEventListener("click", () => {
running = !running;
pauseButton.textContent = running ? "Pause" : "Resume";
});
const cycleButton = document.getElementById("cycleButton");
let cycleTimer = null;
cycleButton.addEventListener("click", () => {
if (cycleTimer !== null) {
clearInterval(cycleTimer);
cycleTimer = null;
cycleButton.textContent = "Auto-cycle";
cycleButton.classList.remove("active");
} else {
cycleTimer = setInterval(() => {
setIntermediateCount((intermediateCount % 3) + 1);
}, 4500);
cycleButton.textContent = "Stop cycle";
cycleButton.classList.add("active");
}
});
// -------------------------------------------------------------------------
// Direct camera controls: no addons or OrbitControls dependency
// -------------------------------------------------------------------------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + dy * 0.005,
0.25,
1.35
);
});
function endDrag(event) {
dragging = false;
renderer.domElement.classList.remove("dragging");
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.009,
9,
24
);
},
{ passive: false }
);
function resetCamera() {
cameraState.theta = 0.64;
cameraState.phi = 0.72;
cameraState.radius = window.innerWidth < 700 ? 17 : 14.3;
}
document.getElementById("resetButton").addEventListener(
"click",
resetCamera
);
function updateCamera() {
const horizontalRadius =
cameraState.radius * Math.sin(cameraState.phi);
camera.position.set(
cameraTarget.x + horizontalRadius * Math.cos(cameraState.theta),
cameraTarget.y + cameraState.radius * Math.sin(cameraState.phi) * Math.sin(cameraState.theta),
cameraTarget.z + cameraState.radius * Math.cos(cameraState.phi)
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
pauseButton.click();
} else if (event.key === "1" || event.key === "2" || event.key === "3") {
setIntermediateCount(Number(event.key));
} else if (event.key.toLowerCase() === "r") {
resetCamera();
}
});
// -------------------------------------------------------------------------
// Labels, resize, and animation
// -------------------------------------------------------------------------
function updateLabels() {
const width = window.innerWidth;
const height = window.innerHeight;
const scale = trainGroup.scale.x;
for (const label of labels) {
const projected = new THREE.Vector3(
label.x * scale,
label.y * scale,
0.35
).project(camera);
const visible = projected.z > -1 && projected.z < 1;
label.element.style.display = visible ? "block" : "none";
label.element.style.left =
`${(projected.x * 0.5 + 0.5) * width}px`;
label.element.style.top =
`${(-projected.y * 0.5 + 0.5) * height}px`;
}
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
const clock = new THREE.Clock();
function animate(now) {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (running) {
simulationAngle += delta * 0.62;
}
// Exact equal-tooth-count relationship:
// omega[i] = -omega[i - 1].
for (const gear of gears) {
gear.group.rotation.z =
gear.phase + gear.sign * simulationAngle;
}
for (const contact of contacts) {
const pulse = 1 + 0.22 * Math.sin(
simulationAngle * 4 + contact.userData.phase
);
contact.scale.setScalar(pulse);
}
const rebuildProgress = THREE.MathUtils.clamp(
(now - rebuildStarted) / 520,
0,
1
);
const eased = 1 - Math.pow(1 - rebuildProgress, 3);
trainGroup.scale.setScalar(0.94 + eased * 0.06);
updateCamera();
updateLabels();
renderer.render(scene, camera);
}
rebuildTrain();
requestAnimationFrame(animate);
</script>
</body>
</html>
```