Prompt specification
Build or customize the Three.js 3D scene "Chain around unequal sprockets" 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: Chain around unequal sprockets
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/chain-around-unequal-sprockets-x0250
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring bicycle chains and sprockets. Animate a short closed chain around two sprockets with different tooth counts; use visible markers to compare linked rotation while maintaining a continuous nonintersecting path. Low-poly.
Working Three.js Starter (chain-around-unequal-sprockets-x0250):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Low-Poly Bicycle Chain Drive</title>
<style>
:root {
color-scheme: dark;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, sans-serif;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #071019;
color: #e8f3ff;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
user-select: none;
}
.panel {
position: absolute;
top: 22px;
left: 22px;
width: min(340px, calc(100vw - 44px));
padding: 18px 20px;
border: 1px solid rgba(158, 205, 237, 0.16);
border-radius: 14px;
background: linear-gradient(
145deg,
rgba(13, 29, 43, 0.88),
rgba(6, 16, 25, 0.72)
);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(12px);
}
.eyebrow {
margin: 0 0 5px;
color: #65d8ff;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(21px, 3vw, 30px);
line-height: 1.08;
letter-spacing: -0.035em;
}
.subtitle {
margin: 10px 0 0;
color: #9fb3c5;
font-size: 13px;
line-height: 1.5;
}
.readout {
position: absolute;
top: 22px;
right: 22px;
display: grid;
grid-template-columns: repeat(2, minmax(118px, 1fr));
gap: 8px;
width: min(294px, calc(100vw - 44px));
}
.readout div {
padding: 12px 13px;
border: 1px solid rgba(158, 205, 237, 0.13);
border-radius: 11px;
background: rgba(6, 17, 26, 0.76);
backdrop-filter: blur(10px);
}
.readout strong {
display: block;
margin-top: 3px;
font-size: 17px;
font-variant-numeric: tabular-nums;
}
.big {
color: #ff8755;
}
.small {
color: #52dcff;
}
.readout-label {
color: #8299ac;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.controls {
position: fixed;
left: 22px;
bottom: 22px;
display: flex;
align-items: center;
gap: 10px;
padding: 10px;
border: 1px solid rgba(158, 205, 237, 0.16);
border-radius: 12px;
background: rgba(7, 18, 28, 0.84);
backdrop-filter: blur(12px);
}
button {
min-width: 76px;
padding: 9px 12px;
border: 1px solid rgba(130, 197, 232, 0.24);
border-radius: 8px;
background: #122b3d;
color: #eaf7ff;
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
}
button:hover {
background: #193b52;
}
input[type="range"] {
width: 105px;
accent-color: #52dcff;
}
.hint {
position: fixed;
right: 22px;
bottom: 22px;
color: #7f96a8;
font-size: 11px;
letter-spacing: 0.03em;
pointer-events: none;
transition: opacity 0.3s;
}
.loading {
position: fixed;
inset: 0;
display: grid;
place-items: center;
background: #071019;
color: #6edfff;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.15em;
text-transform: uppercase;
}
@media (max-width: 700px) {
.panel {
top: 12px;
left: 12px;
width: 255px;
padding: 14px;
}
.subtitle {
display: none;
}
.readout {
top: auto;
right: 12px;
bottom: 66px;
width: 244px;
}
.controls {
left: 12px;
bottom: 12px;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<div class="loading" id="loading">Loading chain drive…</div>
<div class="hud">
<section class="panel">
<p class="eyebrow">Low-poly mechanism study</p>
<h1>Bicycle Chain Drive</h1>
<p class="subtitle">
A closed, non-crossing chain wraps around a 24-tooth driver and a
16-tooth driven sprocket. Colored index markers make the linked
rotation easy to compare.
</p>
</section>
<section class="readout">
<div>
<span class="readout-label big">24T driver</span>
<strong id="big-rpm" class="big">0.0 rpm</strong>
</div>
<div>
<span class="readout-label small">16T driven</span>
<strong id="small-rpm" class="small">0.0 rpm</strong>
</div>
<div>
<span class="readout-label">Angle ratio</span>
<strong>2 : 3</strong>
</div>
<div>
<span class="readout-label">Chain links</span>
<strong id="link-count">52</strong>
</div>
</section>
</div>
<div class="controls">
<button id="pause" type="button">Pause</button>
<button id="reset" type="button">Reset</button>
<label class="readout-label" for="speed">Speed</label>
<input
id="speed"
type="range"
min="1"
max="10"
step="0.1"
value="4.8"
aria-label="Chain speed"
>
</div>
<div class="hint" id="hint">Drag to orbit · Wheel to zoom · Double-click to reset</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 TAU = Math.PI * 2;
const BIG_TEETH = 24;
const SMALL_TEETH = 16;
const LINK_COUNT = 52;
const CHAIN_PITCH = 1.65;
/*
Effective pitch radii are chosen so one chain pitch corresponds
exactly to one tooth:
R = N * pitch / (2π)
The center distance is solved so the complete belt length is an
integer number of chain pitches. This makes the chain close exactly
and allows both sprockets to rotate without phase drift.
*/
const BIG_RADIUS = BIG_TEETH * CHAIN_PITCH / TAU;
const SMALL_RADIUS = SMALL_TEETH * CHAIN_PITCH / TAU;
const TARGET_CHAIN_LENGTH = LINK_COUNT * CHAIN_PITCH;
function beltLength(centerDistance) {
const radiusDifference = BIG_RADIUS - SMALL_RADIUS;
const tangentLength = Math.sqrt(
centerDistance * centerDistance -
radiusDifference * radiusDifference
);
const alpha = Math.acos(radiusDifference / centerDistance);
const smallWrap = 2 * alpha * SMALL_RADIUS;
const bigWrap = (TAU - 2 * alpha) * BIG_RADIUS;
return 2 * tangentLength + smallWrap + bigWrap;
}
function solveCenterDistance() {
let low = BIG_RADIUS + SMALL_RADIUS + 0.001;
let high = 100;
for (let iteration = 0; iteration < 100; iteration++) {
const middle = (low + high) * 0.5;
if (beltLength(middle) < TARGET_CHAIN_LENGTH) {
low = middle;
} else {
high = middle;
}
}
return (low + high) * 0.5;
}
const CENTER_DISTANCE = solveCenterDistance();
const LEFT_CENTER = new THREE.Vector2(-CENTER_DISTANCE * 0.5, 0);
const RIGHT_CENTER = new THREE.Vector2(CENTER_DISTANCE * 0.5, 0);
// ---------------------------------------------------------------------
// Renderer, scene, lighting
// ---------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071019);
scene.fog = new THREE.Fog(0x071019, 70, 125);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
200
);
const cameraTarget = new THREE.Vector3(0, 0, 0);
let cameraRadius = 58;
let cameraPolar = 0.18;
let cameraAzimuth = 0;
function updateCamera() {
const sinPolar = Math.sin(cameraPolar);
camera.position.set(
cameraTarget.x + cameraRadius * sinPolar * Math.sin(cameraAzimuth),
cameraTarget.y + cameraRadius * sinPolar * Math.cos(cameraAzimuth),
cameraTarget.z + cameraRadius * Math.cos(cameraPolar)
);
camera.lookAt(cameraTarget);
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xc4ecff, 0x172332, 2.0));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(10, -14, 38);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -25;
keyLight.shadow.camera.right = 25;
keyLight.shadow.camera.top = 25;
keyLight.shadow.camera.bottom = -25;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 100;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x58dfff, 1.8);
rimLight.position.set(-18, 12, 18);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff8755, 22, 50, 2);
warmLight.position.set(-14, -7, 13);
scene.add(warmLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(100, 60),
new THREE.MeshStandardMaterial({
color: 0x0a1721,
roughness: 0.96,
metalness: 0.04
})
);
ground.position.z = -1.45;
ground.receiveShadow = true;
scene.add(ground);
// Subtle technical grid.
const gridVertices = [];
for (let x = -40; x <= 40; x += 4) {
gridVertices.push(x, -30, -1.4, x, 30, -1.4);
}
for (let y = -30; y <= 30; y += 4) {
gridVertices.push(-40, y, -1.4, 40, y, -1.4);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridVertices, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x234052,
transparent: true,
opacity: 0.28
})
);
scene.add(grid);
// ---------------------------------------------------------------------
// Exact closed tangent-and-arc chain path
// ---------------------------------------------------------------------
const radiusDifference = BIG_RADIUS - SMALL_RADIUS;
const alpha = Math.acos(radiusDifference / CENTER_DISTANCE);
const normalY = Math.sqrt(
1 - (radiusDifference / CENTER_DISTANCE) ** 2
);
const topNormal = new THREE.Vector2(
radiusDifference / CENTER_DISTANCE,
normalY
);
const bottomNormal = new THREE.Vector2(
radiusDifference / CENTER_DISTANCE,
-normalY
);
const leftTop = LEFT_CENTER.clone().addScaledVector(
topNormal,
BIG_RADIUS
);
const rightTop = RIGHT_CENTER.clone().addScaledVector(
topNormal,
SMALL_RADIUS
);
const leftBottom = LEFT_CENTER.clone().addScaledVector(
bottomNormal,
BIG_RADIUS
);
const rightBottom = RIGHT_CENTER.clone().addScaledVector(
bottomNormal,
SMALL_RADIUS
);
const topDirection = rightTop.clone().sub(leftTop).normalize();
const bottomDirection = leftBottom.clone().sub(rightBottom).normalize();
const tangentLength = rightTop.distanceTo(leftTop);
const segmentStart = {
top: 0,
smallArc: tangentLength,
bottom: tangentLength + 2 * alpha * SMALL_RADIUS,
bigArc:
2 * tangentLength +
2 * alpha * SMALL_RADIUS
};
const PATH_LENGTH = segmentStart.bigArc + (TAU - 2 * alpha) * BIG_RADIUS;
/*
The path runs clockwise:
top tangent → small sprocket → bottom tangent → big sprocket.
Each section is continuous and tangent to the next. The resulting
outline is the convex hull of the two pitch circles, so it cannot
cross itself.
*/
function samplePath(distance, position, tangent) {
let s = ((distance % PATH_LENGTH) + PATH_LENGTH) % PATH_LENGTH;
if (s < segmentStart.smallArc) {
position.copy(leftTop).addScaledVector(topDirection, s);
tangent.copy(topDirection);
return;
}
if (s < segmentStart.bottom) {
const angle =
alpha - (s - segmentStart.smallArc) / SMALL_RADIUS;
position.set(
RIGHT_CENTER.x + Math.cos(angle) * SMALL_RADIUS,
RIGHT_CENTER.y + Math.sin(angle) * SMALL_RADIUS
);
tangent.set(Math.sin(angle), -Math.cos(angle));
return;
}
if (s < segmentStart.bigArc) {
const amount = s - segmentStart.bottom;
position.copy(rightBottom).addScaledVector(
bottomDirection,
amount
);
tangent.copy(bottomDirection);
return;
}
const angle = -alpha - (s - segmentStart.bigArc) / BIG_RADIUS;
position.set(
LEFT_CENTER.x + Math.cos(angle) * BIG_RADIUS,
LEFT_CENTER.y + Math.sin(angle) * BIG_RADIUS
);
tangent.set(Math.sin(angle), -Math.cos(angle));
}
// ---------------------------------------------------------------------
// Sprockets
// ---------------------------------------------------------------------
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0x263b4e,
metalness: 0.78,
roughness: 0.3,
flatShading: true
});
const hubMaterial = new THREE.MeshStandardMaterial({
color: 0xa9bac8,
metalness: 0.85,
roughness: 0.25,
flatShading: true
});
const axleMaterial = new THREE.MeshStandardMaterial({
color: 0xd7e2e9,
metalness: 0.9,
roughness: 0.18,
flatShading: true
});
const dummy = new THREE.Object3D();
const zAxis = new THREE.Vector3(0, 0, 1);
function createSprocket(center, teeth, radius, accentColor, toothBase) {
const group = new THREE.Group();
group.position.set(center.x, center.y, 0);
const ringRadius = radius - 0.56;
const hubRadius = radius * 0.22;
const toothStep = TAU / teeth;
// Faceted outer ring.
const ring = new THREE.Mesh(
new THREE.TorusGeometry(ringRadius, 0.32, 4, teeth),
bodyMaterial
);
ring.castShadow = true;
ring.receiveShadow = true;
group.add(ring);
// Hub.
const hubGeometry = new THREE.CylinderGeometry(
hubRadius,
hubRadius,
0.72,
10,
1,
false
);
hubGeometry.rotateX(Math.PI / 2);
const hub = new THREE.Mesh(hubGeometry, hubMaterial);
hub.castShadow = true;
group.add(hub);
// Spokes.
const spokeCount = teeth >= 20 ? 6 : 5;
const spokeLength = ringRadius - hubRadius + 0.25;
const spokeCenter = (ringRadius + hubRadius) * 0.5;
const spokeGeometry = new THREE.BoxGeometry(
spokeLength,
0.34,
0.34
);
for (let index = 0; index < spokeCount; index++) {
const angle = index * TAU / spokeCount;
const spoke = new THREE.Mesh(spokeGeometry, bodyMaterial);
spoke.position.set(
Math.cos(angle) * spokeCenter,
Math.sin(angle) * spokeCenter,
0
);
spoke.rotation.z = angle;
spoke.castShadow = true;
group.add(spoke);
}
// Individual low-poly teeth, instanced into one draw call.
const toothGeometry = new THREE.BoxGeometry(0.64, 0.44, 0.34);
const toothMaterial = new THREE.MeshStandardMaterial({
color: accentColor,
metalness: 0.48,
roughness: 0.32,
flatShading: true
});
const toothMesh = new THREE.InstancedMesh(
toothGeometry,
toothMaterial,
teeth
);
for (let index = 0; index < teeth; index++) {
// Half-pitch offset places tooth tips between roller positions.
const angle = toothBase + (index + 0.5) * toothStep;
dummy.position.set(
Math.cos(angle) * (radius + 0.12),
Math.sin(angle) * (radius + 0.12),
0
);
dummy.rotation.set(0, 0, angle);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
toothMesh.setMatrixAt(index, dummy.matrix);
}
toothMesh.castShadow = true;
toothMesh.frustumCulled = false;
group.add(toothMesh);
// Bright index marker: initially aligned on both sprockets.
const markerMaterial = new THREE.MeshStandardMaterial({
color: accentColor,
emissive: accentColor,
emissiveIntensity: 0.52,
metalness: 0.25,
roughness: 0.25,
flatShading: true
});
const markerBar = new THREE.Mesh(
new THREE.BoxGeometry(radius * 0.62, 0.22, 0.8),
markerMaterial
);
markerBar.position.set(radius * 0.48, 0, 0.5);
markerBar.castShadow = true;
group.add(markerBar);
const markerTip = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.43, 0),
markerMaterial
);
markerTip.position.set(radius * 0.83, 0, 0.57);
markerTip.castShadow = true;
group.add(markerTip);
const axleGeometry = new THREE.CylinderGeometry(
radius * 0.075,
radius * 0.075,
1.08,
8
);
axleGeometry.rotateX(Math.PI / 2);
const axle = new THREE.Mesh(axleGeometry, axleMaterial);
axle.castShadow = true;
group.add(axle);
return group;
}
const bigToothBase = -alpha + segmentStart.bigArc / BIG_RADIUS;
const smallToothBase = alpha + segmentStart.smallArc / SMALL_RADIUS;
const bigSprocket = createSprocket(
LEFT_CENTER,
BIG_TEETH,
BIG_RADIUS,
0xff8755,
bigToothBase
);
const smallSprocket = createSprocket(
RIGHT_CENTER,
SMALL_TEETH,
SMALL_RADIUS,
0x52dcff,
smallToothBase
);
scene.add(bigSprocket, smallSprocket);
// ---------------------------------------------------------------------
// World-space labels
// ---------------------------------------------------------------------
function makeLabel(text, colorHex) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 192;
const context = canvas.getContext("2d");
const color = `#${colorHex.toString(16).padStart(6, "0")}`;
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(6, 18, 28, 0.84)";
context.strokeStyle = color;
context.lineWidth = 8;
const x = 14;
const y = 14;
const width = canvas.width - 28;
const height = canvas.height - 28;
const radius = 26;
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();
context.fill();
context.stroke();
context.fillStyle = color;
context.textAlign = "center";
context.textBaseline = "middle";
context.font = "800 62px system-ui, sans-serif";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(7.2, 2.7, 1);
return sprite;
}
const bigLabel = makeLabel("24T DRIVER", 0xff8755);
bigLabel.position.set(
LEFT_CENTER.x,
BIG_RADIUS + 3.1,
0.8
);
const smallLabel = makeLabel("16T DRIVEN", 0x52dcff);
smallLabel.position.set(
RIGHT_CENTER.x,
SMALL_RADIUS + 3.1,
0.8
);
scene.add(bigLabel, smallLabel);
// ---------------------------------------------------------------------
// Chain rollers and paired side plates
// ---------------------------------------------------------------------
const rollerGeometry = new THREE.CylinderGeometry(
0.26,
0.26,
0.54,
8,
1,
false
);
rollerGeometry.rotateX(Math.PI / 2);
const rollerMaterial = new THREE.MeshStandardMaterial({
color: 0xb9cbd8,
metalness: 0.9,
roughness: 0.22,
flatShading: true
});
const rollerMesh = new THREE.InstancedMesh(
rollerGeometry,
rollerMaterial,
LINK_COUNT
);
rollerMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
rollerMesh.castShadow = true;
rollerMesh.frustumCulled = false;
scene.add(rollerMesh);
const plateGeometry = new THREE.BoxGeometry(1, 1, 1);
const plateMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
metalness: 0.72,
roughness: 0.31,
flatShading: true
});
const plateMesh = new THREE.InstancedMesh(
plateGeometry,
plateMaterial,
LINK_COUNT * 2
);
plateMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
plateMesh.castShadow = true;
plateMesh.frustumCulled = false;
scene.add(plateMesh);
const rollerPositions = Array.from(
{ length: LINK_COUNT },
() => new THREE.Vector2()
);
const samplePosition = new THREE.Vector2();
const sampleTangent = new THREE.Vector2();
const plateColorA = new THREE.Color(0xf4b65d);
const plateColorB = new THREE.Color(0xd9903e);
for (let index = 0; index < LINK_COUNT; index++) {
plateMesh.setColorAt(index * 2, plateColorA);
plateMesh.setColorAt(index * 2 + 1, plateColorA);
plateMesh.setColorAt(
(index + 1) * 2,
index % 2 === 0 ? plateColorB : plateColorA
);
plateMesh.setColorAt(
(index + 1) * 2 + 1,
index % 2 === 0 ? plateColorB : plateColorA
);
}
if (plateMesh.instanceColor) {
plateMesh.instanceColor.needsUpdate = true;
}
function updateChain(phase) {
// Roller positions are exactly one pitch apart along the closed path.
for (let index = 0; index < LINK_COUNT; index++) {
samplePath(
phase + index * CHAIN_PITCH,
samplePosition,
sampleTangent
);
rollerPositions[index].copy(samplePosition);
dummy.position.set(
samplePosition.x,
samplePosition.y,
0
);
dummy.quaternion.setFromAxisAngle(zAxis, index * Math.PI / 8);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
rollerMesh.setMatrixAt(index, dummy.matrix);
}
// Each link joins consecutive rollers. Its length is adapted at the
// tangent/arc transitions while the roller centers remain on the path.
for (let index = 0; index < LINK_COUNT; index++) {
const a = rollerPositions[index];
const b = rollerPositions[(index + 1) % LINK_COUNT];
const deltaX = b.x - a.x;
const deltaY = b.y - a.y;
const length = Math.hypot(deltaX, deltaY);
const angle = Math.atan2(deltaY, deltaX);
const middleX = (a.x + b.x) * 0.5;
const middleY = (a.y + b.y) * 0.5;
for (let side = 0; side < 2; side++) {
const instanceIndex = index * 2 + side;
dummy.position.set(
middleX,
middleY,
side === 0 ? -0.38 : 0.38
);
dummy.quaternion.setFromAxisAngle(zAxis, angle);
dummy.scale.set(length + 0.12, 0.34, 0.13);
dummy.updateMatrix();
plateMesh.setMatrixAt(instanceIndex, dummy.matrix);
}
}
rollerMesh.instanceMatrix.needsUpdate = true;
plateMesh.instanceMatrix.needsUpdate = true;
}
// ---------------------------------------------------------------------
// Animation and linked rotation
// ---------------------------------------------------------------------
const clock = new THREE.Clock();
let totalTravel = 0;
let chainSpeed = 4.8;
let paused = false;
const pauseButton = document.getElementById("pause");
const resetButton = document.getElementById("reset");
const speedInput = document.getElementById("speed");
const bigRpm = document.getElementById("big-rpm");
const smallRpm = document.getElementById("small-rpm");
const hint = document.getElementById("hint");
document.getElementById("link-count").textContent = LINK_COUNT;
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
});
resetButton.addEventListener("click", () => {
totalTravel = 0;
});
speedInput.addEventListener("input", () => {
chainSpeed = Number(speedInput.value);
});
renderer.setAnimationLoop(() => {
const delta = Math.min(clock.getDelta(), 0.05);
if (!paused) {
totalTravel += delta * chainSpeed;
}
const phase = totalTravel % PATH_LENGTH;
updateChain(phase);
/*
No-slip rotation:
angular speed = chain speed / pitch radius
Because R is proportional to tooth count:
ω24 / ω16 = 16 / 24 = 2 / 3
totalTravel is intentionally not wrapped, so sprocket rotation
remains perfectly continuous even when the chain phase wraps.
*/
bigSprocket.rotation.z = -totalTravel / BIG_RADIUS;
smallSprocket.rotation.z = -totalTravel / SMALL_RADIUS;
const bigRPM = chainSpeed / BIG_RADIUS * 60 / TAU;
const smallRPM = chainSpeed / SMALL_RADIUS * 60 / TAU;
bigRpm.textContent = `${bigRPM.toFixed(1)} rpm`;
smallRpm.textContent = `${smallRPM.toFixed(1)} rpm`;
renderer.render(scene, camera);
});
// ---------------------------------------------------------------------
// Direct camera controls: no addons or example modules
// ---------------------------------------------------------------------
let dragging = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
hint.style.opacity = "0";
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousX;
const deltaY = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
cameraAzimuth -= deltaX * 0.006;
cameraPolar = THREE.MathUtils.clamp(
cameraPolar + deltaY * 0.006,
0.05,
1.25
);
updateCamera();
});
function endDrag(event) {
dragging = false;
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();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
34,
105
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
totalTravel = 0;
cameraRadius = 58;
cameraPolar = 0.18;
cameraAzimuth = 0;
updateCamera();
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
document.getElementById("loading").remove();
</script>
</body>
</html>
```