Prompt specification
Build or customize the Three.js 3D scene "Clockwork Door Gear Workshop" 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: Clockwork Door Gear Workshop
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/clockwork-door-gear-workshop-x3451
Scene Description Prompt:
Build an original workshop with fixed shafts, interchangeable gears, and a target dial. Require compatible spacing and declared ratios rather than arbitrary decorative gear motion. Build this with Three.js from cdnjs as a voxel scene in one self-contained HTML file.
Working Three.js Starter (clockwork-door-gear-workshop-x3451):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ratio Forge — Voxel Gear Workshop</title>
<style>
:root {
--ink: #172027;
--panel: #202b31;
--panel-2: #29363d;
--cream: #f2e8cf;
--muted: #a9b4b4;
--orange: #ff9d4d;
--teal: #65d3c3;
--blue: #76a9ff;
--green: #8ee08b;
--red: #ff6f61;
--line: rgba(242, 232, 207, 0.14);
--shadow: 0 16px 44px rgba(12, 18, 21, 0.32);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #aebbb7;
color: var(--cream);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
select,
input {
font: inherit;
}
button,
select {
border-radius: 4px;
}
button {
cursor: pointer;
}
button:focus-visible,
select:focus-visible,
input:focus-visible {
outline: 2px solid var(--orange);
outline-offset: 2px;
}
#stage,
#three-canvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
}
#three-canvas {
display: block;
touch-action: none;
cursor: grab;
}
.scene-chrome {
position: fixed;
inset: 0;
pointer-events: none;
}
.brand {
position: absolute;
top: 24px;
left: 26px;
display: flex;
align-items: center;
gap: 13px;
color: var(--ink);
text-shadow: 0 1px rgba(255, 255, 255, 0.3);
}
.brand-mark {
width: 42px;
height: 42px;
display: grid;
place-items: center;
background: var(--ink);
color: var(--orange);
border: 3px solid rgba(23, 32, 39, 0.25);
box-shadow: 5px 5px 0 rgba(23, 32, 39, 0.2);
font-weight: 900;
font-size: 20px;
}
.brand h1 {
margin: 0;
font-size: 19px;
letter-spacing: 0.16em;
line-height: 1;
font-weight: 900;
}
.brand p {
margin: 6px 0 0;
font: 700 10px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.14em;
text-transform: uppercase;
opacity: 0.75;
}
.panel {
position: absolute;
top: 20px;
right: 20px;
bottom: 20px;
width: min(372px, calc(100vw - 40px));
overflow-y: auto;
padding: 19px;
background: rgba(27, 37, 43, 0.96);
border: 1px solid rgba(255, 255, 255, 0.11);
box-shadow: var(--shadow);
scrollbar-width: thin;
scrollbar-color: #607078 transparent;
pointer-events: auto;
}
.panel::before {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: linear-gradient(
90deg,
var(--orange) 0 33%,
var(--teal) 33% 66%,
var(--blue) 66% 100%
);
}
.panel-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
margin-bottom: 17px;
}
.eyebrow {
margin: 0 0 5px;
color: var(--orange);
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.panel h2 {
margin: 0;
font-size: 23px;
line-height: 1.08;
letter-spacing: -0.03em;
}
.module-chip {
flex: none;
padding: 7px 8px;
border: 1px solid var(--line);
color: var(--muted);
font: 700 9px/1.1 ui-monospace, SFMono-Regular, Menlo, monospace;
text-align: right;
text-transform: uppercase;
}
.section {
margin-top: 15px;
padding: 14px;
background: var(--panel-2);
border: 1px solid var(--line);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin: 0 0 11px;
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.section-title span:last-child {
color: var(--muted);
font-size: 9px;
letter-spacing: 0.04em;
text-align: right;
}
.target-readout {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
}
#targetValue {
color: var(--cream);
font: 900 31px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: -0.06em;
}
.match-badge {
padding: 6px 8px;
border: 1px solid currentColor;
color: var(--red);
font: 900 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
}
.match-badge.match {
color: var(--green);
}
input[type="range"] {
width: 100%;
height: 20px;
margin: 0;
accent-color: var(--orange);
cursor: ew-resize;
}
.range-labels {
display: flex;
justify-content: space-between;
margin-top: 3px;
color: var(--muted);
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.presets {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-top: 11px;
}
.preset,
.small-button,
.run-button {
border: 1px solid rgba(242, 232, 207, 0.18);
color: var(--cream);
background: #202a30;
transition:
background 120ms ease,
border-color 120ms ease,
transform 120ms ease;
}
.preset {
padding: 8px 4px;
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.preset:hover,
.small-button:hover,
.run-button:hover:not(:disabled) {
border-color: var(--orange);
background: #344047;
}
.preset:active,
.small-button:active,
.run-button:active:not(:disabled) {
transform: translateY(1px);
}
.fit-button {
width: 100%;
margin-top: 8px;
padding: 9px;
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.05em;
}
.gear-card {
--shaft: var(--orange);
position: relative;
margin-top: 9px;
padding: 11px 11px 10px 13px;
background: #1c262c;
border: 1px solid var(--line);
}
.gear-card::before {
content: "";
position: absolute;
top: -1px;
bottom: -1px;
left: -1px;
width: 4px;
background: var(--shaft);
}
.gear-card.a {
--shaft: var(--orange);
}
.gear-card.b {
--shaft: var(--teal);
}
.gear-card.c {
--shaft: var(--blue);
}
.gear-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
}
.gear-head strong {
font-size: 12px;
}
.gear-head span {
color: var(--shaft);
font: 900 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
text-transform: uppercase;
}
select {
width: 100%;
padding: 9px 30px 9px 10px;
color: var(--cream);
background: #11191e;
border: 1px solid #3d4a50;
border-radius: 3px;
font: 700 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
cursor: pointer;
}
.gear-meta {
display: flex;
justify-content: space-between;
gap: 8px;
margin-top: 7px;
color: var(--muted);
font: 700 9px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.gear-meta b {
color: var(--shaft);
}
.checks {
display: grid;
gap: 7px;
}
.check-row {
display: grid;
grid-template-columns: 57px 1fr auto;
align-items: center;
gap: 9px;
padding: 8px 9px;
background: #1c262c;
border: 1px solid var(--line);
font: 700 10px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.check-row .name {
color: var(--muted);
}
.check-row .result {
text-align: right;
}
.ok {
color: var(--green);
}
.bad {
color: var(--red);
}
.ratio-table {
display: grid;
gap: 7px;
}
.ratio-line {
display: flex;
justify-content: space-between;
gap: 12px;
padding-bottom: 7px;
border-bottom: 1px dashed var(--line);
font: 700 10px/1.35 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.ratio-line:last-child {
padding-bottom: 0;
border-bottom: 0;
}
.ratio-line span:first-child {
color: var(--muted);
}
.ratio-line b {
color: var(--cream);
text-align: right;
}
.status-box {
margin-top: 14px;
padding: 11px;
background: #172126;
border-left: 4px solid var(--red);
}
.status-box.valid {
border-left-color: var(--green);
}
.status-box strong {
display: block;
margin-bottom: 4px;
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.status-box p {
margin: 0;
color: var(--muted);
font: 700 10px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.run-button {
width: 100%;
margin-top: 12px;
padding: 13px;
color: #182127;
background: var(--orange);
border-color: var(--orange);
font: 900 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.run-button.running {
color: var(--cream);
background: #35434a;
border-color: var(--green);
}
.run-button:disabled {
color: #748087;
background: #29343a;
border-color: #3b474d;
cursor: not-allowed;
}
.view-controls {
position: absolute;
left: 24px;
bottom: 24px;
display: flex;
gap: 7px;
pointer-events: auto;
}
.small-button {
padding: 9px 11px;
background: rgba(28, 38, 44, 0.9);
box-shadow: 0 5px 16px rgba(20, 30, 34, 0.16);
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.scene-hint {
position: absolute;
left: 24px;
bottom: 69px;
color: rgba(23, 32, 39, 0.74);
font: 800 9px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.live-chip {
position: absolute;
top: 25px;
right: 412px;
display: flex;
align-items: center;
gap: 8px;
padding: 8px 10px;
color: var(--ink);
background: rgba(242, 232, 207, 0.76);
border: 1px solid rgba(23, 32, 39, 0.16);
font: 900 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.live-dot {
width: 8px;
height: 8px;
background: var(--red);
box-shadow: 0 0 0 3px rgba(255, 111, 97, 0.18);
}
.live-dot.on {
background: var(--green);
box-shadow: 0 0 0 3px rgba(142, 224, 139, 0.2);
}
@media (max-width: 900px) {
.brand {
top: 14px;
left: 14px;
}
.brand p,
.scene-hint,
.live-chip {
display: none;
}
.panel {
top: auto;
left: 10px;
right: 10px;
bottom: 10px;
width: auto;
max-height: 43vh;
padding: 15px;
}
.view-controls {
left: 12px;
bottom: calc(43vh + 22px);
}
}
@media (max-height: 760px) and (min-width: 901px) {
.panel {
top: 10px;
bottom: 10px;
}
.section {
padding: 11px;
margin-top: 10px;
}
.brand {
top: 16px;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<div class="scene-chrome">
<header class="brand">
<div class="brand-mark">R</div>
<div>
<h1>RATIO FORGE</h1>
<p>Fixed-shaft voxel workshop</p>
</div>
</header>
<div class="live-chip">
<span id="liveDot" class="live-dot"></span>
<span id="liveText">Drive locked</span>
</div>
<div class="scene-hint">
Drag to orbit · Wheel to zoom · Click a gear to edit
</div>
<div class="view-controls">
<button id="resetView" class="small-button">RESET VIEW</button>
<button id="topView" class="small-button">TOP VIEW</button>
</div>
<aside class="panel" aria-label="Gear workshop controls">
<div class="panel-header">
<div>
<p class="eyebrow">Calibration bench</p>
<h2>Target the train.</h2>
</div>
<div class="module-chip">
Common module<br />
0.15 units
</div>
</div>
<section class="section">
<h3 class="section-title">
<span>01 / Reduction target</span>
<span>input turns : output turns</span>
</h3>
<div class="target-readout">
<strong id="targetValue">2.00:1</strong>
<span id="targetMatch" class="match-badge">MATCH</span>
</div>
<input
id="targetSlider"
type="range"
min="1"
max="3"
step="0.01"
value="2"
aria-label="Target reduction ratio"
/>
<div class="range-labels">
<span>1.00:1</span>
<span>2.00:1</span>
<span>3.00:1</span>
</div>
<div class="presets" aria-label="Target ratio presets">
<button class="preset" data-target="1.25">1.25:1</button>
<button class="preset" data-target="1.50">1.50:1</button>
<button class="preset" data-target="1.67">5:3</button>
<button class="preset" data-target="2.00">2:1</button>
<button class="preset" data-target="2.20">2.2:1</button>
<button class="preset" data-target="2.50">2.5:1</button>
</div>
<button id="fitTarget" class="small-button fit-button">
FIND MATCHING TRAIN
</button>
</section>
<section class="section">
<h3 class="section-title">
<span>02 / Interchangeable gears</span>
<span>Pitch radius = teeth × 0.075</span>
</h3>
<div class="gear-card a">
<div class="gear-head">
<strong>Shaft A · Drive</strong>
<span>Input</span>
</div>
<select id="gearA" aria-label="Gear on shaft A"></select>
<div class="gear-meta">
<span id="ratioA">To B: —</span>
<b id="radiusA">R 0.90</b>
</div>
</div>
<div class="gear-card b">
<div class="gear-head">
<strong>Shaft B · Idler</strong>
<span>Fixed axis</span>
</div>
<select id="gearB" aria-label="Gear on shaft B"></select>
<div class="gear-meta">
<span id="ratioB">To C: —</span>
<b id="radiusB">R 1.35</b>
</div>
</div>
<div class="gear-card c">
<div class="gear-head">
<strong>Shaft C · Output</strong>
<span>Driven</span>
</div>
<select id="gearC" aria-label="Gear on shaft C"></select>
<div class="gear-meta">
<span id="ratioC">Train: —</span>
<b id="radiusC">R 1.80</b>
</div>
</div>
</section>
<section class="section">
<h3 class="section-title">
<span>03 / Mechanical proof</span>
<span>External spur mesh</span>
</h3>
<div class="checks">
<div class="check-row">
<span class="name">A → B</span>
<span id="spacingAB">—</span>
<span id="checkAB" class="result">—</span>
</div>
<div class="check-row">
<span class="name">B → C</span>
<span id="spacingBC">—</span>
<span id="checkBC" class="result">—</span>
</div>
</div>
<div class="ratio-table" style="margin-top: 11px">
<div class="ratio-line">
<span>Mesh ratio A:B</span>
<b id="declaredAB">—</b>
</div>
<div class="ratio-line">
<span>Mesh ratio B:C</span>
<b id="declaredBC">—</b>
</div>
<div class="ratio-line">
<span>Output / input speed</span>
<b id="speedRatio">—</b>
</div>
<div class="ratio-line">
<span>Actual reduction</span>
<b id="actualReduction">—</b>
</div>
</div>
</section>
<div id="statusBox" class="status-box" role="status" aria-live="polite">
<strong id="statusTitle">Inspecting train</strong>
<p id="statusText">Checking shaft spacing and declared ratios.</p>
</div>
<button id="runButton" class="run-button" disabled>Engage drive</button>
</aside>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Mechanical constants
// -------------------------------------------------------------------------
const MODULE = 0.15;
const PITCH_RADIUS_PER_TOOTH = MODULE / 2;
// The shafts cannot move. These center distances are therefore fixed.
const CENTER_AB = 2.25;
const CENTER_BC = 3.15;
const SHAFTS = [
{ id: "A", x: -0.8, color: 0xff9d4d, css: "#ff9d4d", label: "DRIVE" },
{ id: "B", x: 1.45, color: 0x65d3c3, css: "#65d3c3", label: "IDLER" },
{ id: "C", x: 4.6, color: 0x76a9ff, css: "#76a9ff", label: "OUTPUT" }
];
const GEAR_Y = 1.48;
const CATALOG = Array.from({ length: 16 }, (_, i) => 6 + i * 2);
const state = {
teeth: [12, 18, 24],
target: 2,
running: false,
driveAngle: 0
};
const ui = {
selects: [
document.getElementById("gearA"),
document.getElementById("gearB"),
document.getElementById("gearC")
],
targetSlider: document.getElementById("targetSlider"),
targetValue: document.getElementById("targetValue"),
targetMatch: document.getElementById("targetMatch"),
runButton: document.getElementById("runButton"),
fitTarget: document.getElementById("fitTarget"),
statusBox: document.getElementById("statusBox"),
statusTitle: document.getElementById("statusTitle"),
statusText: document.getElementById("statusText"),
liveDot: document.getElementById("liveDot"),
liveText: document.getElementById("liveText")
};
let assessment = null;
function gcd(a, b) {
a = Math.abs(a);
b = Math.abs(b);
while (b) {
[a, b] = [b, a % b];
}
return a || 1;
}
function ratioText(n, d) {
const divisor = gcd(n, d);
return `${n / divisor}:${d / divisor}`;
}
function pitchRadius(teeth) {
return teeth * PITCH_RADIUS_PER_TOOTH;
}
function evaluateTrain() {
const [a, b, c] = state.teeth;
const abRequired = pitchRadius(a) + pitchRadius(b);
const bcRequired = pitchRadius(b) + pitchRadius(c);
const abValid = Math.abs(CENTER_AB - abRequired) < 0.00001;
const bcValid = Math.abs(CENTER_BC - bcRequired) < 0.00001;
const actualReduction = c / a;
const outputSpeedRatio = a / c;
const targetMatch = Math.abs(actualReduction - state.target) <= 0.012;
return {
a,
b,
c,
abRequired,
bcRequired,
abValid,
bcValid,
spacingValid: abValid && bcValid,
actualReduction,
outputSpeedRatio,
targetMatch,
canRun: abValid && bcValid && targetMatch
};
}
function nearestValidTrain(target) {
let best = null;
for (const a of CATALOG) {
const b = 30 - a;
const c = 42 - b;
if (!CATALOG.includes(b) || !CATALOG.includes(c)) continue;
const reduction = c / a;
const error = Math.abs(reduction - target);
if (!best || error < best.error) {
best = { a, b, c, reduction, error };
}
}
return best;
}
// -------------------------------------------------------------------------
// Renderer, scene, camera
// -------------------------------------------------------------------------
const stage = document.getElementById("stage");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.domElement.id = "three-canvas";
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.08;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xaebbb7);
scene.fog = new THREE.Fog(0xaebbb7, 18, 36);
const camera = new THREE.OrthographicCamera(-8, 8, 6, -6, 0.1, 80);
const cameraState = {
target: new THREE.Vector3(-1.7, 1.1, 0),
azimuth: 0.28,
polar: 0.78,
radius: 18,
zoom: 1
};
function updateCamera() {
const { target, azimuth, polar, radius } = cameraState;
const horizontal = Math.sin(polar) * radius;
camera.position.set(
target.x + Math.sin(azimuth) * horizontal,
target.y + Math.cos(polar) * radius,
target.z + Math.cos(azimuth) * horizontal
);
camera.lookAt(target);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
// Preserve the full workshop width on narrow screens.
const viewHeight = Math.max(9.6, 14.8 / aspect);
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
updateCamera();
}
window.addEventListener("resize", resize);
const hemisphere = new THREE.HemisphereLight(0xf4ead2, 0x45545b, 2.0);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffedc6, 3.1);
sun.position.set(-6, 11, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.0007;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x8fc9ff, 1.2);
fill.position.set(8, 5, -7);
scene.add(fill);
// -------------------------------------------------------------------------
// Procedural materials and environment
// -------------------------------------------------------------------------
const materials = {
floor: new THREE.MeshStandardMaterial({
color: 0x88948e,
roughness: 0.94,
metalness: 0.02
}),
wall: new THREE.MeshStandardMaterial({
color: 0x637477,
roughness: 0.92
}),
wood: new THREE.MeshStandardMaterial({
color: 0x9b6843,
roughness: 0.82
}),
woodDark: new THREE.MeshStandardMaterial({
color: 0x65442f,
roughness: 0.88
}),
steel: new THREE.MeshStandardMaterial({
color: 0x35444c,
roughness: 0.4,
metalness: 0.75
}),
steelLight: new THREE.MeshStandardMaterial({
color: 0xa9b8ba,
roughness: 0.28,
metalness: 0.82
}),
dark: new THREE.MeshStandardMaterial({
color: 0x202a30,
roughness: 0.65,
metalness: 0.35
}),
peg: new THREE.MeshStandardMaterial({
color: 0x35464c,
roughness: 0.8
}),
cream: new THREE.MeshStandardMaterial({
color: 0xe9dfc5,
roughness: 0.68
}),
orange: new THREE.MeshStandardMaterial({
color: 0xff9d4d,
roughness: 0.48,
metalness: 0.25
}),
teal: new THREE.MeshStandardMaterial({
color: 0x65d3c3,
roughness: 0.48,
metalness: 0.25
}),
blue: new THREE.MeshStandardMaterial({
color: 0x76a9ff,
roughness: 0.48,
metalness: 0.25
}),
red: new THREE.MeshStandardMaterial({
color: 0xff6f61,
roughness: 0.5,
metalness: 0.2
}),
green: new THREE.MeshStandardMaterial({
color: 0x8ee08b,
roughness: 0.4,
metalness: 0.15,
emissive: 0x274a25,
emissiveIntensity: 0.6
})
};
function box(parent, w, h, d, x, y, z, material, cast = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), material);
mesh.position.set(x, y, z);
mesh.castShadow = cast;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function cylinder(
parent,
radiusTop,
radiusBottom,
height,
segments,
x,
y,
z,
material
) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(
radiusTop,
radiusBottom,
height,
segments,
1,
false
),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function seededRandom(seed) {
let value = seed % 2147483647;
if (value <= 0) value += 2147483646;
return () => {
value = (value * 16807) % 2147483647;
return (value - 1) / 2147483646;
};
}
function createEnvironment() {
const random = seededRandom(8721);
// Voxel floor tiles.
const tileSize = 1.18;
const columns = 19;
const rows = 14;
const tileGeometry = new THREE.BoxGeometry(tileSize, 0.18, tileSize);
const tiles = new THREE.InstancedMesh(
tileGeometry,
materials.floor,
columns * rows
);
const matrix = new THREE.Matrix4();
const color = new THREE.Color();
let index = 0;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < columns; col++) {
const x = (col - (columns - 1) / 2) * tileSize;
const z = (row - (rows - 1) / 2) * tileSize;
matrix.makeTranslation(x, -0.14, z);
tiles.setMatrixAt(index, matrix);
const tone = 0.83 + random() * 0.17;
color.setHSL(0.39, 0.06, tone);
tiles.setColorAt(index, color);
index++;
}
}
tiles.instanceMatrix.needsUpdate = true;
if (tiles.instanceColor) tiles.instanceColor.needsUpdate = true;
tiles.receiveShadow = true;
scene.add(tiles);
// Workshop wall.
box(scene, 23, 9, 0.55, -1, 3.75, -5.7, materials.wall, false);
// Block-like wall courses.
for (let row = 0; row < 7; row++) {
const y = 0.7 + row * 0.75;
const offset = row % 2 ? 0.55 : 0;
for (let col = 0; col < 17; col++) {
const x = -11.2 + col * 1.28 + offset;
if (x > 9.2) continue;
const brickMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color().setHSL(
0.48,
0.06,
0.40 + random() * 0.055
),
roughness: 0.93
});
box(scene, 1.2, 0.67, 0.08, x, y, -5.39, brickMaterial, false);
}
}
// Pegboard.
box(scene, 8.8, 3.3, 0.18, 0.5, 3.75, -5.22, materials.peg, false);
// Peg holes.
const holeGeometry = new THREE.BoxGeometry(0.07, 0.07, 0.03);
const holes = new THREE.InstancedMesh(holeGeometry, materials.dark, 11 * 5);
let holeIndex = 0;
for (let row = 0; row < 5; row++) {
for (let col = 0; col < 11; col++) {
matrix.makeTranslation(
-3.55 + col * 0.78,
2.48 + row * 0.62,
-5.09
);
holes.setMatrixAt(holeIndex++, matrix);
}
}
holes.instanceMatrix.needsUpdate = true;
scene.add(holes);
// Blocky hanging tools.
box(scene, 0.18, 1.55, 0.14, -2.6, 3.65, -5.0, materials.steelLight);
box(scene, 0.72, 0.18, 0.14, -2.48, 4.36, -5.0, materials.steelLight);
box(scene, 0.46, 0.16, 0.16, -0.9, 3.7, -4.98, materials.orange);
box(scene, 0.16, 1.0, 0.16, -0.9, 4.15, -4.98, materials.woodDark);
box(scene, 0.16, 1.2, 0.16, 0.15, 3.65, -4.98, materials.teal);
box(scene, 0.75, 0.16, 0.16, 0.15, 4.2, -4.98, materials.teal);
// Workbench.
box(scene, 14.6, 0.36, 5.1, 0, 0.61, 0, materials.wood);
box(scene, 14.7, 0.13, 0.14, 0, 0.83, 2.45, materials.woodDark);
box(scene, 14.7, 0.13, 0.14, 0, 0.83, -2.45, materials.woodDark);
// Plank seams.
for (let i = 0; i < 8; i++) {
const x = -6.3 + i * 1.8;
box(scene, 0.025, 0.012, 4.9, x, 0.797, 0, materials.woodDark, false);
}
// Bench legs.
for (const x of [-6.25, 5.95]) {
for (const z of [-1.85, 1.85]) {
box(scene, 0.55, 3.1, 0.55, x, -0.98, z, materials.woodDark);
box(scene, 0.7, 0.18, 0.7, x, -2.48, z, materials.dark);
}
}
// Lower shelf and crates.
box(scene, 12.8, 0.18, 3.9, 0, -1.75, 0, materials.woodDark);
box(scene, 1.5, 0.9, 1.2, -4.8, -1.23, 0.4, materials.woodDark);
box(scene, 1.2, 0.7, 1.0, -3.0, -1.36, -0.65, materials.wood);
box(scene, 1.35, 0.65, 0.9, 3.7, -1.4, 0.5, materials.woodDark);
// Work lamp.
box(scene, 0.65, 0.14, 0.65, -5.8, 0.92, -1.65, materials.dark);
box(scene, 0.12, 2.3, 0.12, -5.8, 1.9, -1.65, materials.steel);
box(scene, 1.05, 0.22, 0.5, -5.25, 2.98, -1.65, materials.orange);
box(scene, 0.75, 0.06, 0.3, -5.25, 2.84, -1.65, materials.cream);
// Workshop sign.
const signTexture = makeTextTexture(
"RATIO FORGE",
"FIXED AXES / TRUE RATIOS",
"#172027",
"#e8dec3",
768,
220
);
const signMaterial = new THREE.MeshBasicMaterial({
map: signTexture,
transparent: true
});
const sign = new THREE.Mesh(new THREE.PlaneGeometry(5.4, 1.55), signMaterial);
sign.position.set(2.6, 4.65, -5.0);
scene.add(sign);
// Small calibration blocks.
for (let i = 0; i < 5; i++) {
box(
scene,
0.5,
0.22 + i * 0.08,
0.5,
6.0,
0.92 + (0.22 + i * 0.08) / 2,
1.35,
i % 2 ? materials.teal : materials.orange
);
}
}
function makeTextTexture(
title,
subtitle,
foreground = "#ffffff",
background = "#172027",
width = 512,
height = 128
) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
ctx.fillStyle = background;
ctx.fillRect(0, 0, width, height);
ctx.strokeStyle = foreground;
ctx.globalAlpha = 0.25;
ctx.lineWidth = 5;
ctx.strokeRect(8, 8, width - 16, height - 16);
ctx.globalAlpha = 1;
ctx.fillStyle = foreground;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = `900 ${Math.round(height * 0.35)}px ui-monospace, monospace`;
ctx.fillText(title, width / 2, height * 0.43);
if (subtitle) {
ctx.globalAlpha = 0.72;
ctx.font = `700 ${Math.round(height * 0.11)}px ui-monospace, monospace`;
ctx.fillText(subtitle, width / 2, height * 0.73);
ctx.globalAlpha = 1;
}
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
return texture;
}
function makeLabelSprite(text, color = "#172027") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(242,232,207,0.92)";
ctx.fillRect(0, 12, 512, 104);
ctx.strokeStyle = color;
ctx.lineWidth = 8;
ctx.strokeRect(4, 16, 504, 96);
ctx.fillStyle = color;
ctx.font = "900 45px ui-monospace, monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 65);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(1.65, 0.41, 1);
return sprite;
}
// -------------------------------------------------------------------------
// Fixed shaft hardware
// -------------------------------------------------------------------------
let driveLampMaterial;
function createFixedShafts() {
SHAFTS.forEach((shaft, index) => {
const group = new THREE.Group();
group.position.x = shaft.x;
scene.add(group);
// Bearing base and clamps.
box(group, 1.05, 0.17, 1.05, 0, 0.89, 0, materials.steel);
box(group, 0.58, 0.32, 0.58, 0, 1.08, 0, materials.dark);
box(group, 0.48, 0.17, 0.48, 0, 1.29, 0, materials.steelLight);
for (const x of [-0.38, 0.38]) {
for (const z of [-0.38, 0.38]) {
box(group, 0.13, 0.09, 0.13, x, 1.02, z, materials.cream);
}
}
// Vertical fixed shaft.
cylinder(group, 0.105, 0.105, 1.15, 12, 0, 1.35, 0, materials.steelLight);
const label = makeLabelSprite(
`${shaft.id} · ${shaft.label}`,
index === 0 ? "#a85a23" : index === 1 ? "#277d76" : "#3869b6"
);
label.position.set(0, 2.72, 0);
group.add(label);
});
// A status lamp next to the drive shaft.
const lampBase = new THREE.Group();
lampBase.position.set(-2.12, 0.9, 1.6);
scene.add(lampBase);
box(lampBase, 0.55, 0.15, 0.55, 0, 0, 0, materials.dark);
cylinder(lampBase, 0.17, 0.2, 0.34, 8, 0, 0.22, 0, materials.steelLight);
driveLampMaterial = materials.green.clone();
driveLampMaterial.emissiveIntensity = 0;
const lamp = cylinder(
lampBase,
0.16,
0.18,
0.25,
8,
0,
0.48,
0,
driveLampMaterial
);
lamp.castShadow = false;
}
// -------------------------------------------------------------------------
// Voxel gear construction
// -------------------------------------------------------------------------
const mechanismRoot = new THREE.Group();
scene.add(mechanismRoot);
let gearRoots = [];
function disposeObject(root) {
root.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
const objectMaterials = Array.isArray(object.material)
? object.material
: [object.material];
for (const material of objectMaterials) {
if (material.map) material.map.dispose();
material.dispose();
}
}
});
}
function createVoxelGear(teeth, color, shaftIndex) {
const root = new THREE.Group();
root.position.set(SHAFTS[shaftIndex].x, GEAR_Y, 0);
root.userData.shaftIndex = shaftIndex;
const spinner = new THREE.Group();
root.add(spinner);
const pitchR = pitchRadius(teeth);
const rimRadius = Math.max(0.34, pitchR - 0.17);
const gearMaterial = new THREE.MeshStandardMaterial({
color: 0x344149,
roughness: 0.38,
metalness: 0.76
});
const accentMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.42,
metalness: 0.5
});
const edgeMaterial = new THREE.MeshStandardMaterial({
color: 0x172027,
roughness: 0.55,
metalness: 0.55
});
// Low-sided rim reads as a voxel/part rather than a smooth industrial disc.
const rim = new THREE.Mesh(
new THREE.CylinderGeometry(rimRadius, rimRadius, 0.25, teeth),
gearMaterial
);
rim.castShadow = true;
rim.receiveShadow = true;
spinner.add(rim);
// Shared geometry for all square teeth.
const toothGeometry = new THREE.BoxGeometry(
MODULE * 1.05,
0.34,
MODULE * 1.55
);
for (let i = 0; i < teeth; i++) {
const angle = (i / teeth) * Math.PI * 2;
const tooth = new THREE.Mesh(toothGeometry, accentMaterial);
tooth.position.set(
Math.sin(angle) * (pitchR + 0.015),
0,
Math.cos(angle) * (pitchR + 0.015)
);
tooth.rotation.y = angle;
tooth.castShadow = true;
tooth.receiveShadow = true;
spinner.add(tooth);
}
// Four voxel spokes.
const spokeGeometry = new THREE.BoxGeometry(
Math.max(0.1, pitchR * 0.19),
0.18,
rimRadius * 1.25
);
for (let i = 0; i < 4; i++) {
const angle = (i / 4) * Math.PI * 2 + Math.PI / 4;
const spoke = new THREE.Mesh(spokeGeometry, accentMaterial);
spoke.position.set(
Math.sin(angle) * rimRadius * 0.27,
0.11,
Math.cos(angle) * rimRadius * 0.27
);
spoke.rotation.y = angle;
spoke.castShadow = true;
spinner.add(spoke);
}
// Dark inset-like blocks suggest openings without CSG.
const insetGeometry = new THREE.BoxGeometry(
Math.max(0.12, pitchR * 0.28),
0.025,
Math.max(0.15, pitchR * 0.35)
);
for (let i = 0; i < 4; i++) {
const angle = (i / 4) * Math.PI * 2;
const inset = new THREE.Mesh(insetGeometry, edgeMaterial);
inset.position.set(
Math.sin(angle) * rimRadius * 0.54,
0.139,
Math.cos(angle) * rimRadius * 0.54
);
inset.rotation.y = angle;
spinner.add(inset);
}
// Hub and cap.
const hubRadius = Math.max(0.18, pitchR * 0.2);
cylinder(
spinner,
hubRadius,
hubRadius,
0.42,
10,
0,
0,
0,
edgeMaterial
);
cylinder(
spinner,
hubRadius * 0.62,
hubRadius * 0.62,
0.12,
8,
0,
0.26,
0,
accentMaterial
);
// One visible timing marker makes the constrained rotation easy to read.
const marker = new THREE.Mesh(
new THREE.BoxGeometry(
Math.max(0.11, pitchR * 0.15),
0.08,
Math.max(0.18, pitchR * 0.25)
),
materials.cream
);
marker.position.set(0, 0.19, rimRadius * 0.62);
spinner.add(marker);
root.userData.spinner = spinner;
return root;
}
function rebuildGears() {
for (const gear of gearRoots) {
mechanismRoot.remove(gear);
disposeObject(gear);
}
gearRoots = [];
SHAFTS.forEach((shaft, index) => {
const gear = createVoxelGear(state.teeth[index], shaft.color, index);
mechanismRoot.add(gear);
gearRoots.push(gear);
});
applyDerivedRotation();
}
function applyDerivedRotation() {
if (!assessment || gearRoots.length !== 3) return;
const { a, b, c } = assessment;
// Every angle is derived from the drive angle and the declared tooth ratios.
// External meshes reverse direction; phase constants align tooth and gap.
const thetaA = state.driveAngle;
const thetaB = -thetaA * (a / b) + Math.PI / b;
const thetaC = -thetaB * (b / c) + Math.PI / c;
gearRoots[0].userData.spinner.rotation.y = thetaA;
gearRoots[1].userData.spinner.rotation.y = thetaB;
gearRoots[2].userData.spinner.rotation.y = thetaC;
}
// -------------------------------------------------------------------------
// Physical target dial
// -------------------------------------------------------------------------
let targetNeedle;
let actualMarker;
let dialDisplayTexture;
let dialDisplayCanvas;
let dialDisplayContext;
function createTargetDial() {
const group = new THREE.Group();
group.position.set(-4.25, 2.36, -0.52);
scene.add(group);
// Stand.
box(group, 0.16, 1.8, 0.16, 0, -1.35, -0.08, materials.steel);
box(group, 0.8, 0.14, 0.7, 0, -2.2, -0.08, materials.dark);
const backing = new THREE.Mesh(
new THREE.CylinderGeometry(1.18, 1.18, 0.24, 32),
materials.dark
);
backing.rotation.x = Math.PI / 2;
backing.castShadow = true;
group.add(backing);
const face = new THREE.Mesh(
new THREE.CircleGeometry(1.08, 32),
materials.cream
);
face.position.z = 0.13;
group.add(face);
// Block-built tick marks.
const tickGeometry = new THREE.BoxGeometry(0.035, 0.15, 0.035);
for (let i = 0; i <= 10; i++) {
const angle = THREE.MathUtils.lerp(-2.1, 2.1, i / 10);
const tick = new THREE.Mesh(tickGeometry, materials.dark);
tick.position.set(
Math.sin(angle) * 0.91,
Math.cos(angle) * 0.91,
0.18
);
tick.rotation.z = -angle;
group.add(tick);
}
// Target needle.
targetNeedle = new THREE.Group();
targetNeedle.position.z = 0.23;
group.add(targetNeedle);
const needleBody = new THREE.Mesh(
new THREE.BoxGeometry(0.075, 0.9, 0.055),
materials.orange
);
needleBody.position.y = 0.38;
needleBody.castShadow = true;
targetNeedle.add(needleBody);
const needleHub = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.13, 0.08, 12),
materials.orange
);
needleHub.rotation.x = Math.PI / 2;
targetNeedle.add(needleHub);
// Green marker for the actual train reduction.
actualMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.11, 0.19, 0.07),
materials.teal
);
actualMarker.position.z = 0.25;
group.add(actualMarker);
// Dynamic digital readout mounted inside the dial face.
dialDisplayCanvas = document.createElement("canvas");
dialDisplayCanvas.width = 512;
dialDisplayCanvas.height = 160;
dialDisplayContext = dialDisplayCanvas.getContext("2d");
dialDisplayTexture = new THREE.CanvasTexture(dialDisplayCanvas);
dialDisplayTexture.colorSpace = THREE.SRGBColorSpace;
const display = new THREE.Mesh(
new THREE.PlaneGeometry(1.25, 0.39),
new THREE.MeshBasicMaterial({ map: dialDisplayTexture })
);
display.position.set(0, -0.68, 0.2);
group.add(display);
const label = makeLabelSprite("TARGET", "#9b5828");
label.scale.set(1.12, 0.28, 1);
label.position.set(0, 0.72, 0.2);
group.add(label);
}
function dialAngle(reduction) {
const normalized = THREE.MathUtils.clamp((reduction - 1) / 2, 0, 1);
return THREE.MathUtils.lerp(-2.1, 2.1, normalized);
}
function updateDial() {
if (!assessment || !targetNeedle) return;
targetNeedle.rotation.z = dialAngle(state.target);
const actualRatio = assessment.spacingValid
? assessment.actualReduction
: 1;
actualMarker.rotation.z = dialAngle(actualRatio);
actualMarker.position.x = Math.sin(dialAngle(actualRatio)) * 0.82;
actualMarker.position.y = Math.cos(dialAngle(actualRatio)) * 0.82;
const ctx = dialDisplayContext;
ctx.fillStyle = "#172027";
ctx.fillRect(0, 0, 512, 160);
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = assessment.targetMatch ? "#8ee08b" : "#ff8b7e";
ctx.font = "900 69px ui-monospace, monospace";
ctx.fillText(`${state.target.toFixed(2)}:1`, 256, 68);
ctx.fillStyle = "#aeb9b9";
ctx.font = "800 25px ui-monospace, monospace";
ctx.fillText("TARGET REDUCTION", 256, 125);
dialDisplayTexture.needsUpdate = true;
}
// -------------------------------------------------------------------------
// UI and validation
// -------------------------------------------------------------------------
function populateGearSelects() {
ui.selects.forEach((select, index) => {
select.innerHTML = CATALOG.map((teeth) => {
const radius = pitchRadius(teeth);
return `<option value="${teeth}">${teeth}T · pitch radius ${radius.toFixed(2)}</option>`;
}).join("");
select.value = String(state.teeth[index]);
select.addEventListener("change", () => {
state.teeth[index] = Number(select.value);
state.running = false;
assessment = evaluateTrain();
rebuildGears();
updateUI();
});
});
}
function updateUI() {
assessment = evaluateTrain();
const [a, b, c] = state.teeth;
const recommendation = nearestValidTrain(state.target);
ui.targetValue.textContent = `${state.target.toFixed(2)}:1`;
ui.targetMatch.textContent = assessment.targetMatch ? "MATCH" : "OFF TARGET";
ui.targetMatch.classList.toggle("match", assessment.targetMatch);
document.getElementById("radiusA").textContent =
`R ${pitchRadius(a).toFixed(2)}`;
document.getElementById("radiusB").textContent =
`R ${pitchRadius(b).toFixed(2)}`;
document.getElementById("radiusC").textContent =
`R ${pitchRadius(c).toFixed(2)}`;
document.getElementById("ratioA").textContent =
`To B: ${ratioText(a, b)} teeth · reversed`;
document.getElementById("ratioB").textContent =
`To C: ${ratioText(b, c)} teeth · reversed`;
document.getElementById("ratioC").textContent =
`Train: ${ratioText(a, c)} output speed`;
document.getElementById("spacingAB").textContent =
`${CENTER_AB.toFixed(2)} / ${assessment.abRequired.toFixed(2)} u`;
document.getElementById("spacingBC").textContent =
`${CENTER_BC.toFixed(2)} / ${assessment.bcRequired.toFixed(2)} u`;
const checkAB = document.getElementById("checkAB");
const checkBC = document.getElementById("checkBC");
checkAB.textContent = assessment.abValid ? "FIT" : "LOCKED";
checkAB.className = `result ${assessment.abValid ? "ok" : "bad"}`;
checkBC.textContent = assessment.bcValid ? "FIT" : "LOCKED";
checkBC.className = `result ${assessment.bcValid ? "ok" : "bad"}`;
document.getElementById("declaredAB").textContent =
`−${a}:${b} (${ratioText(a, b)} magnitude)`;
document.getElementById("declaredBC").textContent =
`−${b}:${c} (${ratioText(b, c)} magnitude)`;
document.getElementById("speedRatio").textContent =
`${ratioText(a, c)} (${assessment.outputSpeedRatio.toFixed(3)})`;
document.getElementById("actualReduction").textContent =
`${ratioText(c, a)} (${assessment.actualReduction.toFixed(3)})`;
ui.statusBox.classList.toggle("valid", assessment.canRun);
if (!assessment.abValid) {
ui.statusTitle.textContent = "Mesh A–B is incompatible";
ui.statusText.textContent =
`Fixed spacing is ${CENTER_AB.toFixed(2)} u, but ${a}T + ${b}T ` +
`needs ${assessment.abRequired.toFixed(2)} u. The drive remains locked.`;
} else if (!assessment.bcValid) {
ui.statusTitle.textContent = "Mesh B–C is incompatible";
ui.statusText.textContent =
`Fixed spacing is ${CENTER_BC.toFixed(2)} u, but ${b}T + ${c}T ` +
`needs ${assessment.bcRequired.toFixed(2)} u. The drive remains locked.`;
} else if (!assessment.targetMatch) {
ui.statusTitle.textContent = "Spacing valid · target not met";
ui.statusText.textContent =
`This train reduces ${assessment.actualReduction.toFixed(3)}:1. ` +
(recommendation
? `Closest available train is ${recommendation.a}T / ${recommendation.b}T / ${recommendation.c}T at ${recommendation.reduction.toFixed(3)}:1.`
: "Choose a different gear train.");
} else {
ui.statusTitle.textContent = state.running
? "Train verified and engaged"
: "Train verified · ready to engage";
ui.statusText.textContent =
`Both pitch-circle spacing checks pass. Declared reduction is ` +
`${ratioText(c, a)} (${assessment.actualReduction.toFixed(3)}:1), ` +
`matching the dial target.`;
}
ui.runButton.disabled = !assessment.canRun;
ui.runButton.textContent = state.running ? "Disengage drive" : "Engage drive";
ui.runButton.classList.toggle("running", state.running);
ui.liveDot.classList.toggle("on", state.running);
ui.liveText.textContent = state.running ? "Drive engaged" : "Drive locked";
driveLampMaterial.emissiveIntensity = state.running ? 2.4 : 0;
driveLampMaterial.color.setHex(state.running ? 0x8ee08b : 0x34443d);
updateDial();
applyDerivedRotation();
}
ui.targetSlider.addEventListener("input", () => {
state.target = Number(ui.targetSlider.value);
state.running = false;
updateUI();
});
document.querySelectorAll(".preset").forEach((button) => {
button.addEventListener("click", () => {
state.target = Number(button.dataset.target);
ui.targetSlider.value = String(state.target);
state.running = false;
updateUI();
});
});
ui.fitTarget.addEventListener("click", () => {
const best = nearestValidTrain(state.target);
if (!best) return;
state.teeth = [best.a, best.b, best.c];
// Snap explicitly requested custom targets to the nearest attainable ratio.
if (best.error > 0.012) {
state.target = best.reduction;
ui.targetSlider.value = best.reduction.toFixed(2);
}
state.running = false;
ui.selects.forEach((select, index) => {
select.value = String(state.teeth[index]);
});
assessment = evaluateTrain();
rebuildGears();
updateUI();
});
ui.runButton.addEventListener("click", () => {
if (state.running) {
state.running = false;
} else if (assessment?.canRun) {
state.running = true;
}
updateUI();
});
// -------------------------------------------------------------------------
// Direct camera controls, without importing any examples or addons
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const drag = {
active: false,
moved: false,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0
};
function setPointerFromEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function pickGear(event) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(gearRoots, true);
if (!hits.length) return null;
let object = hits[0].object;
while (object && object.userData.shaftIndex === undefined) {
object = object.parent;
}
return object?.userData.shaftIndex ?? null;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
drag.active = true;
drag.moved = false;
drag.startX = drag.lastX = event.clientX;
drag.startY = drag.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (drag.active) {
const dx = event.clientX - drag.lastX;
const dy = event.clientY - drag.lastY;
if (
Math.abs(event.clientX - drag.startX) +
Math.abs(event.clientY - drag.startY) >
4
) {
drag.moved = true;
}
cameraState.azimuth -= dx * 0.006;
cameraState.polar = THREE.MathUtils.clamp(
cameraState.polar + dy * 0.005,
0.22,
1.35
);
drag.lastX = event.clientX;
drag.lastY = event.clientY;
updateCamera();
} else {
const shaftIndex = pickGear(event);
renderer.domElement.style.cursor = shaftIndex === null ? "grab" : "pointer";
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
drag.active = false;
renderer.domElement.style.cursor = "grab";
if (!drag.moved) {
const shaftIndex = pickGear(event);
if (shaftIndex !== null) {
const select = ui.selects[shaftIndex];
select.focus();
select.scrollIntoView({ behavior: "smooth", block: "nearest" });
}
}
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
drag.active = false;
renderer.domElement.style.cursor = "grab";
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.65,
1.75
);
updateCamera();
},
{ passive: false }
);
document.getElementById("resetView").addEventListener("click", () => {
cameraState.azimuth = 0.28;
cameraState.polar = 0.78;
cameraState.zoom = 1;
updateCamera();
});
document.getElementById("topView").addEventListener("click", () => {
cameraState.azimuth = 0;
cameraState.polar = 0.22;
cameraState.zoom = 1.08;
updateCamera();
});
// -------------------------------------------------------------------------
// Boot and animation loop
// -------------------------------------------------------------------------
createEnvironment();
createFixedShafts();
createTargetDial();
populateGearSelects();
assessment = evaluateTrain();
rebuildGears();
updateUI();
resize();
updateCamera();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
if (state.running && assessment?.canRun) {
// The only animated mechanical input is the motor angle.
// All other gear angles are calculated from declared ratios.
state.driveAngle += delta * 1.35;
}
applyDerivedRotation();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```