Prompt specification
Build or customize the Three.js 3D scene "Two Meshing Gear Direction Study" 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: Two Meshing Gear Direction Study
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/two-meshing-gear-direction-study-x3449
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing gear ratios and rotation directions. Model two simple gears with stated tooth counts and marked spokes. Animate opposite rotation with the correct speed ratio and visibly compatible center spacing. Low-poly.
Working Three.js Starter (two-meshing-gear-direction-study-x3449):
```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 Ratio Demonstration</title>
<style>
:root {
color-scheme: dark;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #080d18;
color: #eef6ff;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
.panel {
position: fixed;
z-index: 10;
top: 20px;
left: 20px;
width: min(330px, calc(100vw - 40px));
padding: 18px;
border: 1px solid rgba(148, 163, 184, 0.22);
border-radius: 16px;
background: rgba(10, 17, 31, 0.84);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(14px);
}
.eyebrow {
color: #7dd3fc;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 14px;
font-size: 30px;
line-height: 1;
letter-spacing: -0.04em;
}
.ratio-row {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
gap: 10px;
margin-bottom: 14px;
}
.gear-stat {
padding: 11px 8px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 10px;
text-align: center;
background: rgba(255, 255, 255, 0.035);
}
.gear-stat strong {
display: block;
font-size: 20px;
}
.gear-stat span {
display: block;
margin-top: 3px;
color: #a9b7ca;
font-size: 11px;
}
.ratio-arrow {
color: #facc15;
font-size: 23px;
font-weight: 800;
}
.equation {
margin: 9px 0;
padding: 9px 11px;
border-radius: 9px;
background: rgba(125, 211, 252, 0.07);
color: #c9e8fb;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
.direction-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 14px 0;
}
.direction {
padding: 10px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
font-size: 12px;
}
.direction b {
display: block;
margin-bottom: 4px;
font-size: 14px;
}
.driver-direction b {
color: #fb923c;
}
.driven-direction b {
color: #38bdf8;
}
.control-label {
display: flex;
justify-content: space-between;
align-items: center;
margin: 15px 0 8px;
color: #b8c5d6;
font-size: 12px;
}
.control-label output {
color: #f8fafc;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
input[type="range"] {
width: 100%;
accent-color: #facc15;
cursor: pointer;
}
.buttons {
display: flex;
gap: 8px;
margin-top: 12px;
}
button {
flex: 1;
padding: 9px 10px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 9px;
background: rgba(255, 255, 255, 0.06);
color: #eef6ff;
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
}
button:hover {
background: rgba(255, 255, 255, 0.11);
}
.status {
display: inline-flex;
align-items: center;
gap: 6px;
margin-top: 12px;
color: #86efac;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.status::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 9px currentColor;
content: "";
}
.status.paused {
color: #fbbf24;
}
.hint {
position: fixed;
z-index: 10;
right: 18px;
bottom: 16px;
padding: 9px 12px;
border: 1px solid rgba(148, 163, 184, 0.18);
border-radius: 999px;
background: rgba(10, 17, 31, 0.74);
color: #9fb0c5;
font-size: 11px;
pointer-events: none;
}
@media (max-width: 650px) {
.panel {
top: 10px;
left: 10px;
width: min(300px, calc(100vw - 20px));
padding: 14px;
}
h1 {
font-size: 25px;
}
.hint {
right: 10px;
bottom: 10px;
}
}
</style>
</head>
<body>
<div id="scene" aria-label="Animated low-poly meshed gears"></div>
<section class="panel" aria-label="Gear ratio information">
<div class="eyebrow">External Gear Train</div>
<h1>12T : 24T</h1>
<div class="ratio-row">
<div class="gear-stat">
<strong>12</strong>
<span>teeth · driver</span>
</div>
<div class="ratio-arrow">→</div>
<div class="gear-stat">
<strong>24</strong>
<span>teeth · driven</span>
</div>
</div>
<div class="equation">Speed ratio = 12 / 24 = 1 : 2</div>
<div class="equation">ω₂ = −(N₁ / N₂)ω₁ = −½ω₁</div>
<div class="direction-grid">
<div class="direction driver-direction">
<b>↺ CCW</b>
12-tooth driver
</div>
<div class="direction driven-direction">
<b>↻ CW</b>
24-tooth driven gear
</div>
</div>
<div class="equation">Center distance = r₁ + r₂ = 3 + 6 = 9 units</div>
<label class="control-label" for="speed">
<span>Target driver speed</span>
<output id="speedValue">6.0 rpm</output>
</label>
<input
id="speed"
type="range"
min="0"
max="12"
step="0.5"
value="6"
>
<div class="buttons">
<button id="playPause" type="button">Pause</button>
<button id="resetCamera" type="button">Reset camera</button>
</div>
<div id="status" class="status">Running</div>
</section>
<div class="hint">Drag to orbit · Wheel or pinch to zoom</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 sceneHost = document.getElementById("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x080d18);
scene.fog = new THREE.Fog(0x080d18, 28, 65);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
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;
sceneHost.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(3, -0.75, 0);
let cameraRadius = 21;
let cameraTheta = 0;
let cameraPhi = Math.PI / 2;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
function fitCamera() {
const aspect = window.innerWidth / window.innerHeight;
const verticalFOV = THREE.MathUtils.degToRad(camera.fov);
const requiredWidth = 21.5;
const requiredHeight = 16.2;
const distanceForHeight =
requiredHeight / (2 * Math.tan(verticalFOV / 2));
const distanceForWidth =
requiredWidth / (2 * Math.tan(verticalFOV / 2) * aspect);
cameraRadius = Math.max(distanceForHeight, distanceForWidth) * 1.04;
updateCamera();
}
updateCamera();
fitCamera();
// -------------------------------------------------------------------------
// Lighting and backdrop
// -------------------------------------------------------------------------
const hemisphere = new THREE.HemisphereLight(0x9bd8ff, 0x111827, 1.65);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(-5, 9, 14);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -16;
keyLight.shadow.camera.right = 16;
keyLight.shadow.camera.top = 13;
keyLight.shadow.camera.bottom = -13;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 45;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x38bdf8, 22, 30, 2);
rimLight.position.set(11, -2, 8);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xf97316, 17, 24, 2);
warmLight.position.set(-9, 5, 7);
scene.add(warmLight);
const backdrop = new THREE.Mesh(
new THREE.PlaneGeometry(80, 50),
new THREE.MeshStandardMaterial({
color: 0x0b1220,
roughness: 0.95,
metalness: 0.02
})
);
backdrop.position.set(3, 0, -1.15);
backdrop.receiveShadow = true;
scene.add(backdrop);
// -------------------------------------------------------------------------
// Gear geometry
//
// Module m = 0.5 units/tooth:
// pitch radius = m * tooth count / 2
// 12T: r = 3
// 24T: r = 6
// Center distance = 3 + 6 = 9.
// -------------------------------------------------------------------------
const MODULE = 0.5;
const DRIVER_TEETH = 12;
const DRIVEN_TEETH = 24;
const DRIVER_CENTER = new THREE.Vector3(-3, 0, 0);
const DRIVEN_CENTER = new THREE.Vector3(6, 0, 0);
const bodyMaterialSmall = new THREE.MeshStandardMaterial({
color: 0xf59e0b,
roughness: 0.48,
metalness: 0.48,
flatShading: true
});
const bodyMaterialLarge = new THREE.MeshStandardMaterial({
color: 0x0ea5e9,
roughness: 0.48,
metalness: 0.48,
flatShading: true
});
const spokeMaterial = new THREE.MeshStandardMaterial({
color: 0xf1f5f9,
roughness: 0.58,
metalness: 0.22,
flatShading: true
});
const indexMaterial = new THREE.MeshStandardMaterial({
color: 0xfacc15,
emissive: 0x6b4b00,
emissiveIntensity: 0.45,
roughness: 0.42,
metalness: 0.25,
flatShading: true
});
const hubMaterial = new THREE.MeshStandardMaterial({
color: 0x172033,
roughness: 0.38,
metalness: 0.7,
flatShading: true
});
const capMaterial = new THREE.MeshStandardMaterial({
color: 0xe2e8f0,
roughness: 0.35,
metalness: 0.72,
flatShading: true
});
function makeGearShape(toothCount, pitchRadius) {
const shape = new THREE.Shape();
const toothPitch = (Math.PI * 2) / toothCount;
const outerRadius = pitchRadius + MODULE;
const rootRadius = pitchRadius - 1.25 * MODULE;
let firstPoint = true;
for (let tooth = 0; tooth < toothCount; tooth++) {
const centerAngle = tooth * toothPitch;
// Trapezoidal low-poly tooth profile.
const profile = [
[-0.50, rootRadius],
[-0.32, rootRadius],
[-0.25, pitchRadius],
[-0.14, outerRadius],
[ 0.14, outerRadius],
[ 0.25, pitchRadius],
[ 0.32, rootRadius]
];
for (const [angleFactor, radius] of profile) {
const angle = centerAngle + angleFactor * toothPitch;
const x = Math.cos(angle) * radius;
const y = Math.sin(angle) * radius;
if (firstPoint) {
shape.moveTo(x, y);
firstPoint = false;
} else {
shape.lineTo(x, y);
}
}
}
shape.closePath();
return shape;
}
function makeGear({
toothCount,
position,
bodyMaterial,
hubRadius,
holeRadius,
spokeCount
}) {
const group = new THREE.Group();
group.position.copy(position);
const pitchRadius = (MODULE * toothCount) / 2;
const shape = makeGearShape(toothCount, pitchRadius);
const centerHole = new THREE.Path();
centerHole.absarc(0, 0, holeRadius, 0, Math.PI * 2, true);
shape.holes.push(centerHole);
const depth = 0.72;
const geometry = new THREE.ExtrudeGeometry(shape, {
depth,
steps: 1,
bevelEnabled: true,
bevelSegments: 1,
bevelSize: 0.055,
bevelThickness: 0.055,
curveSegments: 2
});
geometry.translate(0, 0, -depth / 2);
geometry.computeVertexNormals();
const body = new THREE.Mesh(geometry, bodyMaterial);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const hub = new THREE.Mesh(
new THREE.CylinderGeometry(
hubRadius,
hubRadius,
1.08,
12,
1,
false
),
hubMaterial
);
hub.rotation.x = Math.PI / 2;
hub.position.z = 0.04;
hub.castShadow = true;
hub.receiveShadow = true;
group.add(hub);
const spokeLength = holeRadius - hubRadius + 0.34;
const spokeCenter = (holeRadius + hubRadius) / 2;
const spokeWidth = toothCount === 12 ? 0.25 : 0.34;
for (let i = 0; i < spokeCount; i++) {
const angle = (i / spokeCount) * Math.PI * 2;
const isIndexSpoke = i === 0;
const spoke = new THREE.Mesh(
new THREE.BoxGeometry(spokeLength, spokeWidth, 0.26),
isIndexSpoke ? indexMaterial : spokeMaterial
);
spoke.position.set(
Math.cos(angle) * spokeCenter,
Math.sin(angle) * spokeCenter,
0.53
);
spoke.rotation.z = angle;
spoke.castShadow = true;
spoke.receiveShadow = true;
group.add(spoke);
if (isIndexSpoke) {
const marker = new THREE.Mesh(
new THREE.SphereGeometry(0.105, 8, 5),
indexMaterial
);
marker.position.set(
Math.cos(angle) * (holeRadius - 0.05),
Math.sin(angle) * (holeRadius - 0.05),
0.72
);
group.add(marker);
}
}
const cap = new THREE.Mesh(
new THREE.CylinderGeometry(
hubRadius * 0.42,
hubRadius * 0.42,
1.14,
10
),
capMaterial
);
cap.rotation.x = Math.PI / 2;
cap.position.z = 0.09;
cap.castShadow = true;
group.add(cap);
const axleDot = new THREE.Mesh(
new THREE.CylinderGeometry(
hubRadius * 0.14,
hubRadius * 0.14,
1.2,
8
),
hubMaterial
);
axleDot.rotation.x = Math.PI / 2;
axleDot.position.z = 0.12;
group.add(axleDot);
return group;
}
function addDirectionArrow(group, radius, counterClockwise, color) {
const arrowMaterial = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.35,
roughness: 0.5,
metalness: 0.15,
flatShading: true
});
const points = [];
const segments = 28;
const start = counterClockwise ? -2.4 : 2.4;
const end = counterClockwise ? 2.0 : -2.0;
for (let i = 0; i <= segments; i++) {
const t = i / segments;
const angle = THREE.MathUtils.lerp(start, end, t);
points.push(
new THREE.Vector3(
Math.cos(angle) * radius,
Math.sin(angle) * radius,
0.86
)
);
}
const curve = new THREE.CatmullRomCurve3(points);
const tube = new THREE.Mesh(
new THREE.TubeGeometry(curve, 32, 0.038, 5, false),
arrowMaterial
);
group.add(tube);
const endAngle = end;
const tangent = counterClockwise
? new THREE.Vector3(-Math.sin(endAngle), Math.cos(endAngle), 0)
: new THREE.Vector3(Math.sin(endAngle), -Math.cos(endAngle), 0);
const arrowhead = new THREE.Mesh(
new THREE.ConeGeometry(0.115, 0.29, 6),
arrowMaterial
);
arrowhead.position.copy(curve.getPoint(1));
arrowhead.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
tangent.normalize()
);
group.add(arrowhead);
}
const driverGear = makeGear({
toothCount: DRIVER_TEETH,
position: DRIVER_CENTER,
bodyMaterial: bodyMaterialSmall,
hubRadius: 0.68,
holeRadius: 1.48,
spokeCount: 6
});
const drivenGear = makeGear({
toothCount: DRIVEN_TEETH,
position: DRIVEN_CENTER,
bodyMaterial: bodyMaterialLarge,
hubRadius: 1.0,
holeRadius: 3.05,
spokeCount: 6
});
addDirectionArrow(driverGear, 1.12, true, 0xfb7185);
addDirectionArrow(drivenGear, 1.68, false, 0x86efac);
scene.add(driverGear, drivenGear);
// -------------------------------------------------------------------------
// Pitch circles, contact marker, and center-distance annotation
// -------------------------------------------------------------------------
function addPitchCircle(center, radius, color) {
const points = [];
for (let i = 0; i <= 160; i++) {
const angle = (i / 160) * Math.PI * 2;
points.push(
new THREE.Vector3(
center.x + Math.cos(angle) * radius,
center.y + Math.sin(angle) * radius,
-0.56
)
);
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineDashedMaterial({
color,
dashSize: 0.16,
gapSize: 0.11,
transparent: true,
opacity: 0.58
});
const line = new THREE.Line(geometry, material);
line.computeLineDistances();
scene.add(line);
}
addPitchCircle(DRIVER_CENTER, 3, 0xfbbf24);
addPitchCircle(DRIVEN_CENTER, 6, 0x38bdf8);
const contactPoint = new THREE.Mesh(
new THREE.SphereGeometry(0.095, 10, 6),
new THREE.MeshBasicMaterial({ color: 0xfacc15 })
);
contactPoint.position.set(0, 0, 0.98);
scene.add(contactPoint);
const dimensionMaterial = new THREE.LineBasicMaterial({
color: 0x94a3b8,
transparent: true,
opacity: 0.6
});
const dimensionY = -7.25;
const dimensionZ = -0.72;
const dimensionPoints = [
new THREE.Vector3(-3, dimensionY, dimensionZ),
new THREE.Vector3(6, dimensionY, dimensionZ)
];
scene.add(
new THREE.Line(
new THREE.BufferGeometry().setFromPoints(dimensionPoints),
dimensionMaterial
)
);
for (const x of [-3, 6]) {
const tick = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(x, dimensionY - 0.16, dimensionZ),
new THREE.Vector3(x, dimensionY + 0.16, dimensionZ)
]),
dimensionMaterial
);
scene.add(tick);
}
const extensionMaterial = new THREE.LineDashedMaterial({
color: 0x64748b,
dashSize: 0.15,
gapSize: 0.12,
transparent: true,
opacity: 0.5
});
for (const x of [-3, 6]) {
const extension = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(x, -6.48, dimensionZ),
new THREE.Vector3(x, dimensionY, dimensionZ)
]),
extensionMaterial
);
extension.computeLineDistances();
scene.add(extension);
}
// -------------------------------------------------------------------------
// Canvas sprite labels
// -------------------------------------------------------------------------
function roundedRectangle(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 createLabel(title, subtitle, accent, width, height) {
const canvas = document.createElement("canvas");
canvas.width = 768;
canvas.height = 192;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
roundedRectangle(context, 8, 8, 752, 176, 24);
context.fillStyle = "rgba(7, 13, 25, 0.91)";
context.fill();
context.strokeStyle = accent;
context.lineWidth = 5;
context.stroke();
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = "#f8fafc";
context.font = "800 48px system-ui, sans-serif";
context.fillText(title, 384, 72);
context.fillStyle = accent;
context.font = "600 29px system-ui, sans-serif";
context.fillText(subtitle, 384, 130);
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(width, height, 1);
sprite.renderOrder = 20;
return sprite;
}
const driverLabel = createLabel(
"12 TEETH · DRIVER",
"CCW | 1× speed",
"#fb923c",
3.7,
0.92
);
driverLabel.position.set(-3, -4.08, 1.0);
scene.add(driverLabel);
const drivenLabel = createLabel(
"24 TEETH · DRIVEN",
"CW | ½ speed",
"#38bdf8",
4.15,
1.03
);
drivenLabel.position.set(6, -6.92, 1.0);
scene.add(drivenLabel);
const distanceLabel = createLabel(
"CENTER DISTANCE = 9 UNITS",
"Pitch radii: 3 + 6",
"#facc15",
5.3,
1.32
);
distanceLabel.position.set(1.5, -8.0, 0.5);
scene.add(distanceLabel);
// -------------------------------------------------------------------------
// Animation
//
// Exact external-gear relationship:
// theta2 = phase - (N1 / N2) * theta1
//
// The 7.5-degree phase places a gap in the large gear opposite the
// small gear's initial tooth.
// -------------------------------------------------------------------------
const speedInput = document.getElementById("speed");
const speedValue = document.getElementById("speedValue");
const playPauseButton = document.getElementById("playPause");
const resetCameraButton = document.getElementById("resetCamera");
const statusElement = document.getElementById("status");
let targetRPM = Number(speedInput.value);
let isPlaying = true;
let driverAngle = 0;
const drivenPhase = Math.PI / DRIVEN_TEETH;
const angularRatio = DRIVER_TEETH / DRIVEN_TEETH;
function updateReadouts() {
const activeRPM = isPlaying ? targetRPM : 0;
speedValue.value = `${targetRPM.toFixed(1)} rpm`;
playPauseButton.textContent = isPlaying ? "Pause" : "Resume";
statusElement.textContent = isPlaying ? "Running" : "Paused";
statusElement.classList.toggle("paused", !isPlaying);
// Readout is also mirrored in the panel title attributes for clarity.
driverGear.userData.actualRPM = activeRPM;
drivenGear.userData.actualRPM = -activeRPM * angularRatio;
}
speedInput.addEventListener("input", () => {
targetRPM = Number(speedInput.value);
updateReadouts();
});
playPauseButton.addEventListener("click", () => {
isPlaying = !isPlaying;
updateReadouts();
});
resetCameraButton.addEventListener("click", () => {
cameraTheta = 0;
cameraPhi = Math.PI / 2;
fitCamera();
});
updateReadouts();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (isPlaying) {
const radiansPerSecond = (targetRPM * Math.PI * 2) / 60;
driverAngle += radiansPerSecond * delta;
}
driverGear.rotation.z = driverAngle;
drivenGear.rotation.z =
drivenPhase - angularRatio * driverAngle;
renderer.render(scene, camera);
}
animate();
// -------------------------------------------------------------------------
// Direct camera controls: drag to orbit, wheel/pinch to zoom
// -------------------------------------------------------------------------
const pointers = new Map();
let pinchStartDistance = 0;
let pinchStartRadius = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
const previous = pointers.get(event.pointerId);
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1) {
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi - dy * 0.006,
0.38,
Math.PI - 0.38
);
updateCamera();
} else if (pointers.size === 2) {
const values = [...pointers.values()];
const distance = Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
if (pinchStartDistance === 0) {
pinchStartDistance = distance;
pinchStartRadius = cameraRadius;
} else {
cameraRadius = THREE.MathUtils.clamp(
pinchStartRadius * (pinchStartDistance / Math.max(distance, 1)),
11,
65
);
updateCamera();
}
}
});
function removePointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) {
pinchStartDistance = 0;
pinchStartRadius = 0;
}
}
renderer.domElement.addEventListener("pointerup", removePointer);
renderer.domElement.addEventListener("pointercancel", removePointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
11,
65
);
updateCamera();
},
{ passive: false }
);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
fitCamera();
});
</script>
</body>
</html>
```