Prompt specification
Build or customize the Three.js 3D scene "Moving an Idler Changes Belt Path" 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: Moving an Idler Changes Belt Path
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/moving-an-idler-changes-belt-path-x2012
Scene Description Prompt:
Create a standalone low-poly scene in one HTML file using Three.js from cdnjs. Create a bounded belt-routing tool with a movable idler. Recalculate the path length and contact geometry, showing when a fixed-length belt cannot fit the new arrangement.
Working Three.js Starter (moving-an-idler-changes-belt-path-x2012):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Low-Poly Belt Routing Tool</title>
<style>
:root {
color-scheme: dark;
--bg: #071116;
--panel: rgba(11, 23, 29, 0.92);
--border: rgba(155, 214, 221, 0.16);
--text: #e6f3f2;
--muted: #8ca8aa;
--cyan: #65d7d0;
--amber: #ffbd59;
--red: #ff6675;
--green: #75dfa3;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.panel {
position: fixed;
top: 18px;
left: 18px;
z-index: 10;
width: min(350px, calc(100vw - 36px));
max-height: calc(100vh - 36px);
overflow: auto;
padding: 18px;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 20px 70px rgba(0, 0, 0, 0.38);
backdrop-filter: blur(16px);
scrollbar-width: thin;
scrollbar-color: #38555a transparent;
}
.eyebrow {
margin-bottom: 7px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 24px;
line-height: 1.05;
letter-spacing: -0.035em;
}
.intro {
margin: 9px 0 17px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-bottom: 12px;
}
.metric {
min-height: 72px;
padding: 12px;
border: 1px solid var(--border);
border-radius: 11px;
background: rgba(255, 255, 255, 0.025);
}
.metric-label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.metric-value {
font-size: 23px;
font-weight: 760;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.metric-value small {
margin-left: 3px;
color: var(--muted);
font-size: 12px;
font-weight: 600;
letter-spacing: 0;
}
.fixed-control {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 13px;
padding: 10px 12px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.fixed-control label {
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.fixed-control input {
width: 92px;
padding: 7px 8px;
border: 1px solid #38565c;
border-radius: 7px;
outline: none;
background: #09161b;
color: var(--text);
font: inherit;
font-size: 14px;
font-weight: 700;
text-align: right;
}
.fixed-control input:focus {
border-color: var(--cyan);
}
.status {
padding: 12px 13px;
border: 1px solid var(--border);
border-radius: 11px;
background: rgba(255, 255, 255, 0.03);
}
.status.good {
border-color: rgba(117, 223, 163, 0.34);
background: rgba(117, 223, 163, 0.075);
}
.status.warn {
border-color: rgba(255, 189, 89, 0.38);
background: rgba(255, 189, 89, 0.075);
}
.status.bad {
border-color: rgba(255, 102, 117, 0.48);
background: rgba(255, 102, 117, 0.09);
}
.status-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 13px;
font-weight: 850;
letter-spacing: 0.075em;
}
.status.good .status-title {
color: var(--green);
}
.status.warn .status-title {
color: var(--amber);
}
.status.bad .status-title {
color: var(--red);
}
.status-dot {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 14px currentColor;
}
.status-detail {
margin-top: 6px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.length-track {
position: relative;
height: 9px;
margin: 17px 0 7px;
overflow: visible;
border-radius: 20px;
background: #14262c;
}
.required-fill {
position: absolute;
inset: 0 auto 0 0;
width: 0;
border-radius: inherit;
background: linear-gradient(90deg, #3aaba8, var(--cyan));
transition: width 80ms linear, background 160ms ease;
}
.required-fill.over {
background: linear-gradient(90deg, #a52d43, var(--red));
}
.fixed-marker {
position: absolute;
top: -4px;
width: 2px;
height: 17px;
border-radius: 2px;
background: var(--amber);
box-shadow: 0 0 8px rgba(255, 189, 89, 0.45);
transition: left 80ms linear;
}
.track-caption {
display: flex;
justify-content: space-between;
color: #6f8c90;
font-size: 10px;
}
.section-title {
margin: 18px 0 9px;
color: #bcd0d1;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.control-row {
margin-bottom: 11px;
}
.control-label {
display: flex;
justify-content: space-between;
margin-bottom: 6px;
color: var(--muted);
font-size: 11px;
}
.control-label output {
color: var(--text);
font-weight: 700;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0;
border-radius: 10px;
outline: none;
appearance: none;
background: #263d43;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 2px solid #14262c;
border-radius: 50%;
appearance: none;
background: var(--cyan);
box-shadow: 0 0 0 1px rgba(101, 215, 208, 0.4);
}
input[type="range"]::-moz-range-thumb {
width: 13px;
height: 13px;
border: 2px solid #14262c;
border-radius: 50%;
background: var(--cyan);
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 14px;
}
button {
padding: 10px 11px;
border: 1px solid #355159;
border-radius: 9px;
outline: none;
background: #12262d;
color: var(--text);
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition: border-color 120ms ease, background 120ms ease, transform 120ms ease;
}
button:hover {
border-color: var(--cyan);
background: #173139;
transform: translateY(-1px);
}
button.danger {
border-color: rgba(255, 102, 117, 0.4);
background: rgba(255, 102, 117, 0.09);
}
table {
width: 100%;
border-collapse: collapse;
font-size: 11px;
}
th {
padding: 0 0 7px;
color: #6f8c90;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.08em;
text-align: right;
text-transform: uppercase;
}
th:first-child,
td:first-child {
text-align: left;
}
td {
padding: 7px 0;
border-top: 1px solid rgba(155, 214, 221, 0.09);
color: #d9e8e7;
font-variant-numeric: tabular-nums;
text-align: right;
}
td:first-child {
color: var(--muted);
}
td.idler-name {
color: var(--amber);
font-weight: 750;
}
.formula {
margin-top: 9px;
padding: 9px 10px;
border-radius: 8px;
background: #08161b;
color: #91aaad;
font: 11px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.note {
margin: 11px 0 0;
color: #718d90;
font-size: 10px;
line-height: 1.5;
}
.world-label {
position: fixed;
z-index: 4;
min-width: 78px;
padding: 6px 8px;
border: 1px solid rgba(255, 189, 89, 0.42);
border-radius: 7px;
background: rgba(8, 18, 23, 0.88);
box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
color: #dcebea;
font-size: 9px;
line-height: 1.35;
text-align: center;
pointer-events: none;
transform: translate(-50%, -100%);
}
.world-label b {
display: block;
color: var(--amber);
font-size: 9px;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.world-label span {
color: #a8bfc0;
font-variant-numeric: tabular-nums;
}
.zone-label {
position: fixed;
z-index: 3;
padding: 4px 7px;
border: 1px dashed rgba(255, 189, 89, 0.42);
border-radius: 5px;
color: rgba(255, 189, 89, 0.8);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.12em;
pointer-events: none;
transform: translate(-50%, -50%);
}
.warning {
position: fixed;
top: 20px;
left: 50%;
z-index: 8;
padding: 10px 16px;
border: 1px solid rgba(255, 102, 117, 0.65);
border-radius: 999px;
background: rgba(74, 13, 25, 0.92);
box-shadow: 0 8px 35px rgba(0, 0, 0, 0.42), 0 0 25px rgba(255, 102, 117, 0.12);
color: #ffd6dc;
font-size: 11px;
font-weight: 850;
letter-spacing: 0.08em;
opacity: 0;
pointer-events: none;
transform: translate(-50%, -12px);
transition: opacity 160ms ease, transform 160ms ease;
}
.warning.show {
opacity: 1;
transform: translate(-50%, 0);
}
.help {
position: fixed;
right: 18px;
bottom: 16px;
z-index: 5;
padding: 8px 11px;
border: 1px solid var(--border);
border-radius: 8px;
background: rgba(8, 18, 23, 0.78);
color: #8ca8aa;
font-size: 10px;
pointer-events: none;
}
.help strong {
color: var(--amber);
}
@media (max-width: 700px) {
.panel {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
max-height: 54vh;
padding: 14px;
}
h1 {
font-size: 20px;
}
.help {
right: 10px;
bottom: 10px;
}
.world-label {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive 3D belt routing scene"></canvas>
<aside class="panel">
<div class="eyebrow">Routing Lab 01</div>
<h1>Belt Fit Checker</h1>
<p class="intro">
Drag the amber idler inside its bounded travel area. The minimum belt path,
pulley contact angles, and fixed-length fit are recalculated live.
</p>
<div class="metric-grid">
<div class="metric">
<span class="metric-label">Required length</span>
<span class="metric-value"><span id="requiredLength">—</span><small>m</small></span>
</div>
<div class="metric">
<span class="metric-label">Length margin</span>
<span class="metric-value"><span id="lengthMargin">—</span><small>m</small></span>
</div>
</div>
<div class="fixed-control">
<label for="fixedLength">Fixed belt length</label>
<input
id="fixedLength"
type="number"
min="15"
max="20"
step="0.01"
value="17.30"
aria-label="Fixed belt length in meters"
/>
</div>
<div id="statusBox" class="status good">
<div class="status-title">
<span class="status-dot"></span>
<span id="statusTitle">BELT FITS</span>
</div>
<div id="statusDetail" class="status-detail"></div>
</div>
<div class="length-track" aria-hidden="true">
<div id="requiredFill" class="required-fill"></div>
<div id="fixedMarker" class="fixed-marker"></div>
</div>
<div class="track-caption">
<span>Required route</span>
<span>Amber mark = fixed belt</span>
</div>
<div class="section-title">Idler Position</div>
<div class="control-row">
<div class="control-label">
<span>Horizontal travel</span>
<output id="xOutput">0.00 m</output>
</div>
<input id="xSlider" type="range" min="-1.7" max="1.7" step="0.01" value="0" />
</div>
<div class="control-row">
<div class="control-label">
<span>Depth travel</span>
<output id="zOutput">−1.00 m</output>
</div>
<input id="zSlider" type="range" min="-1.8" max="-0.45" step="0.01" value="-1" />
</div>
<div class="buttons">
<button id="resetRoute" type="button">Reset route</button>
<button id="worstCase" class="danger" type="button">Worst-case spot</button>
</div>
<div class="section-title">Contact Geometry</div>
<table>
<thead>
<tr>
<th>Pulley</th>
<th>Wrap</th>
<th>Arc</th>
</tr>
</thead>
<tbody>
<tr>
<td>Left drive</td>
<td id="angleA">—</td>
<td id="arcA">—</td>
</tr>
<tr>
<td class="idler-name">Movable idler</td>
<td id="angleC">—</td>
<td id="arcC">—</td>
</tr>
<tr>
<td>Right drive</td>
<td id="angleB">—</td>
<td id="arcB">—</td>
</tr>
</tbody>
</table>
<div id="formula" class="formula"></div>
<p class="note">
The displayed length is the minimum inner-surface route. Any positive margin
is slack; a negative margin means the fixed belt is too short.
All three pulleys have equal radius.
</p>
</aside>
<div id="labelA" class="world-label">
<b>Left drive</b>
<span>—</span>
</div>
<div id="labelC" class="world-label">
<b>Idler</b>
<span>—</span>
</div>
<div id="labelB" class="world-label">
<b>Right drive</b>
<span>—</span>
</div>
<div id="zoneLabel" class="zone-label">IDLER TRAVEL LIMIT</div>
<div id="warning" class="warning">ROUTE EXCEEDS FIXED BELT</div>
<div class="help">
<strong>Drag idler</strong> to route · <strong>Drag background</strong> to orbit ·
<strong>Scroll</strong> 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";
// -------------------------------------------------------------------------
// State
// -------------------------------------------------------------------------
const canvas = document.getElementById("scene");
const PULLEY_RADIUS = 0.62;
const BELT_THICKNESS = 0.075;
const BELT_HEIGHT = 0.26;
const BELT_Y = 0.5;
const RENDER_RADIUS = PULLEY_RADIUS + BELT_THICKNESS * 0.5;
const LEFT_DRIVE = { x: -3.2, z: 0.2, name: "Left drive" };
const RIGHT_DRIVE = { x: 3.2, z: 0.2, name: "Right drive" };
const idler = { x: 0, z: -1.0, name: "Movable idler" };
const bounds = {
minX: -1.7,
maxX: 1.7,
minZ: -1.8,
maxZ: -0.45
};
let fixedLength = 17.3;
let currentRoute = null;
const requiredLengthEl = document.getElementById("requiredLength");
const lengthMarginEl = document.getElementById("lengthMargin");
const fixedLengthInput = document.getElementById("fixedLength");
const statusBox = document.getElementById("statusBox");
const statusTitle = document.getElementById("statusTitle");
const statusDetail = document.getElementById("statusDetail");
const requiredFill = document.getElementById("requiredFill");
const fixedMarker = document.getElementById("fixedMarker");
const xSlider = document.getElementById("xSlider");
const zSlider = document.getElementById("zSlider");
const xOutput = document.getElementById("xOutput");
const zOutput = document.getElementById("zOutput");
const formulaEl = document.getElementById("formula");
const warning = document.getElementById("warning");
const angleEls = [
document.getElementById("angleA"),
document.getElementById("angleC"),
document.getElementById("angleB")
];
const arcEls = [
document.getElementById("arcA"),
document.getElementById("arcC"),
document.getElementById("arcB")
];
const worldLabels = [
document.getElementById("labelA"),
document.getElementById("labelC"),
document.getElementById("labelB")
];
const zoneLabel = document.getElementById("zoneLabel");
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071116);
scene.fog = new THREE.Fog(0x071116, 15, 29);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
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.12;
const hemisphere = new THREE.HemisphereLight(0xbde9ef, 0x152229, 2.0);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff1d2, 3.1);
keyLight.position.set(4.5, 9, 5.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 24;
keyLight.shadow.bias = -0.00035;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x59d7d4, 1.4);
rimLight.position.set(-6, 4, -5);
scene.add(rimLight);
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0x0c191e,
roughness: 0.95,
metalness: 0.02
});
const floor = new THREE.Mesh(new THREE.PlaneGeometry(12, 8), floorMaterial);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.015;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(12, 24, 0x315057, 0x1a3036);
grid.position.y = 0.005;
grid.scale.z = 0.7;
grid.material.transparent = true;
grid.material.opacity = 0.58;
scene.add(grid);
// Translucent bounded travel region.
const zoneWidth = bounds.maxX - bounds.minX;
const zoneDepth = bounds.maxZ - bounds.minZ;
const zoneCenterX = (bounds.minX + bounds.maxX) * 0.5;
const zoneCenterZ = (bounds.minZ + bounds.maxZ) * 0.5;
const zoneFill = new THREE.Mesh(
new THREE.PlaneGeometry(zoneWidth, zoneDepth),
new THREE.MeshBasicMaterial({
color: 0xffb84d,
transparent: true,
opacity: 0.055,
depthWrite: false,
side: THREE.DoubleSide
})
);
zoneFill.rotation.x = -Math.PI / 2;
zoneFill.position.set(zoneCenterX, 0.018, zoneCenterZ);
scene.add(zoneFill);
const zonePoints = [
new THREE.Vector3(bounds.minX, 0.028, bounds.minZ),
new THREE.Vector3(bounds.maxX, 0.028, bounds.minZ),
new THREE.Vector3(bounds.maxX, 0.028, bounds.maxZ),
new THREE.Vector3(bounds.minX, 0.028, bounds.maxZ),
new THREE.Vector3(bounds.minX, 0.028, bounds.minZ)
];
const zoneLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(zonePoints),
new THREE.LineDashedMaterial({
color: 0xffbd59,
dashSize: 0.12,
gapSize: 0.075,
transparent: true,
opacity: 0.72
})
);
zoneLine.computeLineDistances();
scene.add(zoneLine);
const fixedMetal = new THREE.MeshStandardMaterial({
color: 0x3b5158,
roughness: 0.58,
metalness: 0.42,
flatShading: true
});
const fixedAccent = new THREE.MeshStandardMaterial({
color: 0x60c8c4,
roughness: 0.48,
metalness: 0.28,
flatShading: true
});
const idlerMetal = new THREE.MeshStandardMaterial({
color: 0xffa938,
roughness: 0.5,
metalness: 0.24,
flatShading: true
});
const idlerAccent = new THREE.MeshStandardMaterial({
color: 0xffd277,
roughness: 0.42,
metalness: 0.22,
flatShading: true
});
const darkMetal = new THREE.MeshStandardMaterial({
color: 0x17282e,
roughness: 0.55,
metalness: 0.55,
flatShading: true
});
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0x17292f,
roughness: 0.8,
metalness: 0.18,
flatShading: true
});
function createPulley(isIdler = false) {
const group = new THREE.Group();
const bodyMaterial = isIdler ? idlerMetal : fixedMetal;
const accentMaterial = isIdler ? idlerAccent : fixedAccent;
const body = new THREE.Mesh(
new THREE.CylinderGeometry(
PULLEY_RADIUS,
PULLEY_RADIUS,
0.54,
16,
1,
false
),
bodyMaterial
);
body.position.y = 0.5;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
// Flanges sit above and below the belt's vertical band.
for (const y of [0.225, 0.775]) {
const flange = new THREE.Mesh(
new THREE.CylinderGeometry(
PULLEY_RADIUS + 0.105,
PULLEY_RADIUS + 0.105,
0.075,
16
),
accentMaterial
);
flange.position.y = y;
flange.castShadow = true;
group.add(flange);
}
const hub = new THREE.Mesh(
new THREE.CylinderGeometry(0.245, 0.245, 0.86, 12),
darkMetal
);
hub.position.y = 0.48;
hub.castShadow = true;
group.add(hub);
const cap = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.13, 0.06, 12),
accentMaterial
);
cap.position.y = 0.94;
cap.castShadow = true;
group.add(cap);
const base = new THREE.Mesh(
new THREE.BoxGeometry(0.66, 0.1, 0.66),
baseMaterial
);
base.position.y = 0.05;
base.castShadow = true;
base.receiveShadow = true;
group.add(base);
group.userData.draggable = isIdler;
return group;
}
const leftPulley = createPulley(false);
leftPulley.position.set(LEFT_DRIVE.x, 0, LEFT_DRIVE.z);
scene.add(leftPulley);
const rightPulley = createPulley(false);
rightPulley.position.set(RIGHT_DRIVE.x, 0, RIGHT_DRIVE.z);
scene.add(rightPulley);
const idlerPulley = createPulley(true);
idlerPulley.position.set(idler.x, 0, idler.z);
scene.add(idlerPulley);
const beltMaterial = new THREE.MeshStandardMaterial({
color: 0x284651,
roughness: 0.66,
metalness: 0.08,
side: THREE.DoubleSide
});
const contactMaterial = new THREE.MeshBasicMaterial({
color: 0xffc35b
});
const markerMaterial = new THREE.MeshBasicMaterial({
color: 0xffe39b
});
const dynamicGroup = new THREE.Group();
scene.add(dynamicGroup);
// -------------------------------------------------------------------------
// Exact equal-radius convex belt route
// -------------------------------------------------------------------------
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function distance2D(a, b) {
return Math.hypot(b.x - a.x, b.z - a.z);
}
function rightNormal(a, b) {
const dx = b.x - a.x;
const dz = b.z - a.z;
const length = Math.hypot(dx, dz);
return { x: dz / length, z: -dx / length };
}
function positiveAngleDifference(a, b) {
let delta = b - a;
delta = Math.atan2(Math.sin(delta), Math.cos(delta));
if (delta < 0) delta += Math.PI * 2;
return delta;
}
function cleanPathPoints(points) {
const cleaned = [];
for (const point of points) {
const previous = cleaned[cleaned.length - 1];
if (!previous || Math.hypot(point.x - previous.x, point.z - previous.z) > 1e-7) {
cleaned.push(point);
}
}
if (
cleaned.length > 1 &&
Math.hypot(
cleaned[0].x - cleaned[cleaned.length - 1].x,
cleaned[0].z - cleaned[cleaned.length - 1].z
) < 1e-7
) {
cleaned.pop();
}
return cleaned;
}
function buildRoute() {
// The bounded idler always remains below the line between the drive
// pulleys, so the convex order is Left -> Idler -> Right.
const centers = [
{ ...LEFT_DRIVE },
{ ...idler },
{ ...RIGHT_DRIVE }
];
const vertices = [];
let perimeter = 0;
for (let i = 0; i < centers.length; i++) {
const previous = centers[(i + 2) % centers.length];
const current = centers[i];
const next = centers[(i + 1) % centers.length];
const incomingNormal = rightNormal(previous, current);
const outgoingNormal = rightNormal(current, next);
const incomingAngle = Math.atan2(incomingNormal.z, incomingNormal.x);
const outgoingAngle = Math.atan2(outgoingNormal.z, outgoingNormal.x);
const wrapAngle = positiveAngleDifference(incomingAngle, outgoingAngle);
perimeter += distance2D(current, next);
vertices.push({
center: current,
incomingNormal,
outgoingNormal,
incomingAngle,
outgoingAngle,
wrapAngle,
arcLength: PULLEY_RADIUS * wrapAngle
});
}
// Centerline path: circular contact arcs joined by common tangents.
const rawPoints = [];
for (let i = 0; i < vertices.length; i++) {
const vertex = vertices[i];
const nextVertex = vertices[(i + 1) % vertices.length];
const segments = Math.max(3, Math.ceil((vertex.wrapAngle / (Math.PI * 2)) * 32));
for (let j = 0; j <= segments; j++) {
const angle = vertex.incomingAngle + vertex.wrapAngle * (j / segments);
rawPoints.push({
x: vertex.center.x + Math.cos(angle) * RENDER_RADIUS,
z: vertex.center.z + Math.sin(angle) * RENDER_RADIUS
});
}
// The next vertex's incoming tangent uses the same normal as this
// vertex's outgoing tangent, because all radii are equal.
rawPoints.push({
x: nextVertex.center.x + vertex.outgoingNormal.x * RENDER_RADIUS,
z: nextVertex.center.z + vertex.outgoingNormal.z * RENDER_RADIUS
});
}
const points = cleanPathPoints(rawPoints);
const arcTotal = vertices.reduce((sum, vertex) => sum + vertex.arcLength, 0);
const totalLength = perimeter + arcTotal;
return {
centers,
vertices,
points,
perimeter,
arcTotal,
totalLength
};
}
// -------------------------------------------------------------------------
// Belt mesh
// -------------------------------------------------------------------------
function buildBeltMesh(pathPoints) {
const positions = [];
const indices = [];
const count = pathPoints.length;
const halfThickness = BELT_THICKNESS * 0.5;
const halfHeight = BELT_HEIGHT * 0.5;
for (let i = 0; i < count; i++) {
const previous = pathPoints[(i - 1 + count) % count];
const current = pathPoints[i];
const next = pathPoints[(i + 1) % count];
let tangentX = next.x - previous.x;
let tangentZ = next.z - previous.z;
const tangentLength = Math.hypot(tangentX, tangentZ) || 1;
tangentX /= tangentLength;
tangentZ /= tangentLength;
// Left normal in the XZ plane.
const radialX = -tangentZ;
const radialZ = tangentX;
const outerX = current.x - radialX * halfThickness;
const outerZ = current.z - radialZ * halfThickness;
const innerX = current.x + radialX * halfThickness;
const innerZ = current.z + radialZ * halfThickness;
positions.push(
outerX, BELT_Y - halfHeight, outerZ,
innerX, BELT_Y - halfHeight, innerZ,
innerX, BELT_Y + halfHeight, innerZ,
outerX, BELT_Y + halfHeight, outerZ
);
}
for (let i = 0; i < count; i++) {
const nextRing = (i + 1) % count;
for (let side = 0; side < 4; side++) {
const nextSide = (side + 1) % 4;
const a = i * 4 + side;
const b = i * 4 + nextSide;
const c = nextRing * 4 + side;
const d = nextRing * 4 + nextSide;
indices.push(a, b, d, a, d, c);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(geometry, beltMaterial);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function clearDynamicGeometry() {
for (const child of [...dynamicGroup.children]) {
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
dynamicGroup.remove(child);
}
}
function buildContactGeometry(route) {
const topY = BELT_Y + BELT_HEIGHT * 0.5 + 0.022;
route.vertices.forEach((vertex) => {
const points = [];
const segments = Math.max(5, Math.ceil((vertex.wrapAngle / (Math.PI * 2)) * 24));
for (let i = 0; i <= segments; i++) {
const angle =
vertex.incomingAngle + vertex.wrapAngle * (i / segments);
points.push(
new THREE.Vector3(
vertex.center.x + Math.cos(angle) * (PULLEY_RADIUS + 0.025),
topY,
vertex.center.z + Math.sin(angle) * (PULLEY_RADIUS + 0.025)
)
);
}
const curve = new THREE.CatmullRomCurve3(points, false, "centripetal");
const tube = new THREE.Mesh(
new THREE.TubeGeometry(
curve,
Math.max(8, segments),
0.016,
4,
false
),
contactMaterial
);
dynamicGroup.add(tube);
for (const angle of [vertex.incomingAngle, vertex.outgoingAngle]) {
const marker = new THREE.Mesh(
new THREE.SphereGeometry(0.045, 8, 6),
markerMaterial
);
marker.position.set(
vertex.center.x + Math.cos(angle) * (PULLEY_RADIUS + 0.025),
topY + 0.005,
vertex.center.z + Math.sin(angle) * (PULLEY_RADIUS + 0.025)
);
dynamicGroup.add(marker);
}
});
}
// -------------------------------------------------------------------------
// Interface updates
// -------------------------------------------------------------------------
function updateUI(route) {
const required = route.totalLength;
const margin = fixedLength - required;
const bad = margin < -0.005;
const snug = !bad && margin < 0.08;
requiredLengthEl.textContent = required.toFixed(2);
lengthMarginEl.textContent = `${margin >= 0 ? "+" : ""}${margin.toFixed(2)}`;
statusBox.className = `status ${bad ? "bad" : snug ? "warn" : "good"}`;
if (bad) {
statusTitle.textContent = "CANNOT FIT";
statusDetail.textContent =
`The route is ${Math.abs(margin).toFixed(2)} m longer than the fixed belt.`;
} else if (snug) {
statusTitle.textContent = "SNUG FIT";
statusDetail.textContent =
`The belt fits with only ${margin.toFixed(2)} m of slack.`;
} else {
statusTitle.textContent = "BELT FITS";
statusDetail.textContent =
`The belt fits with ${margin.toFixed(2)} m of slack remaining.`;
}
const scaleMax = Math.max(18, fixedLength * 1.12, required * 1.08);
requiredFill.style.width = `${Math.min(100, (required / scaleMax) * 100)}%`;
requiredFill.classList.toggle("over", bad);
fixedMarker.style.left = `${clamp((fixedLength / scaleMax) * 100, 0, 100)}%`;
route.vertices.forEach((vertex, index) => {
const degrees = THREE.MathUtils.radToDeg(vertex.wrapAngle);
angleEls[index].textContent = `${degrees.toFixed(1)}°`;
arcEls[index].textContent = `${vertex.arcLength.toFixed(2)} m`;
const labelSpan = worldLabels[index].querySelector("span");
labelSpan.textContent = `${degrees.toFixed(1)}° wrap`;
});
formulaEl.textContent =
`${route.perimeter.toFixed(2)} m spans + ` +
`${route.arcTotal.toFixed(2)} m arcs = ${required.toFixed(2)} m`;
beltMaterial.color.set(bad ? 0x9e3343 : 0x284651);
beltMaterial.emissive.set(bad ? 0x280006 : 0x000000);
warning.classList.toggle("show", bad);
warning.textContent =
`ROUTE EXCEEDS FIXED BELT BY ${Math.abs(margin).toFixed(2)} m`;
}
function updateRoute() {
currentRoute = buildRoute();
clearDynamicGeometry();
const belt = buildBeltMesh(currentRoute.points);
dynamicGroup.add(belt);
buildContactGeometry(currentRoute);
updateUI(currentRoute);
}
function setIdler(x, z) {
idler.x = clamp(x, bounds.minX, bounds.maxX);
idler.z = clamp(z, bounds.minZ, bounds.maxZ);
idlerPulley.position.set(idler.x, 0, idler.z);
xSlider.value = idler.x.toFixed(2);
zSlider.value = idler.z.toFixed(2);
xOutput.textContent = `${idler.x.toFixed(2)} m`;
zOutput.textContent = `${idler.z.toFixed(2)} m`;
updateRoute();
}
xSlider.addEventListener("input", () => {
setIdler(Number(xSlider.value), idler.z);
});
zSlider.addEventListener("input", () => {
setIdler(idler.x, Number(zSlider.value));
});
fixedLengthInput.addEventListener("input", () => {
const parsed = Number(fixedLengthInput.value);
if (Number.isFinite(parsed)) {
fixedLength = clamp(parsed, 15, 20);
updateUI(currentRoute);
}
});
document.getElementById("resetRoute").addEventListener("click", () => {
setIdler(0, -1.0);
});
document.getElementById("worstCase").addEventListener("click", () => {
setIdler(bounds.maxX, bounds.minZ);
});
// -------------------------------------------------------------------------
// Direct camera controls and idler dragging
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 0.25, -0.35);
let cameraAzimuth = 0.62;
let cameraPolar = 0.82;
let cameraRadius = 12.8;
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -BELT_Y);
const dragPoint = new THREE.Vector3();
let draggingIdler = false;
let orbiting = false;
let lastPointerX = 0;
let lastPointerY = 0;
let dragOffsetX = 0;
let dragOffsetZ = 0;
function updateCamera() {
const sinPolar = Math.sin(cameraPolar);
camera.position.set(
cameraTarget.x + cameraRadius * sinPolar * Math.sin(cameraAzimuth),
cameraTarget.y + cameraRadius * Math.cos(cameraPolar),
cameraTarget.z + cameraRadius * sinPolar * Math.cos(cameraAzimuth)
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
function updatePointer(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
canvas.addEventListener("pointerdown", (event) => {
updatePointer(event);
const hits = raycaster.intersectObject(idlerPulley, true);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (hits.length > 0) {
draggingIdler = true;
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
dragOffsetX = idler.x - dragPoint.x;
dragOffsetZ = idler.z - dragPoint.z;
}
} else {
orbiting = true;
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "move";
}
});
canvas.addEventListener("pointermove", (event) => {
if (draggingIdler) {
updatePointer(event);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
setIdler(dragPoint.x + dragOffsetX, dragPoint.z + dragOffsetZ);
}
} else if (orbiting) {
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
cameraAzimuth -= deltaX * 0.006;
cameraPolar = clamp(cameraPolar + deltaY * 0.005, 0.34, 1.24);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
updateCamera();
}
});
function endPointerInteraction(event) {
draggingIdler = false;
orbiting = false;
canvas.style.cursor = "default";
if (event && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endPointerInteraction);
canvas.addEventListener("pointercancel", endPointerInteraction);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
8,
18
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", () => {
cameraAzimuth = 0.62;
cameraPolar = 0.82;
cameraRadius = 12.8;
updateCamera();
});
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
// -------------------------------------------------------------------------
// Screen-space labels and render loop
// -------------------------------------------------------------------------
function positionScreenLabel(element, worldPosition) {
const projected = worldPosition.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1;
element.style.display = visible ? "block" : "none";
if (!visible) return;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
function updateWorldLabels() {
currentRoute.vertices.forEach((vertex, index) => {
positionScreenLabel(
worldLabels[index],
new THREE.Vector3(vertex.center.x, 1.08, vertex.center.z)
);
});
positionScreenLabel(
zoneLabel,
new THREE.Vector3(zoneCenterX, 0.07, bounds.minZ - 0.13)
);
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", resize);
function animate() {
requestAnimationFrame(animate);
updateWorldLabels();
renderer.render(scene, camera);
}
setIdler(idler.x, idler.z);
updateCamera();
animate();
</script>
</body>
</html>
```