Prompt specification
Build or customize the Three.js 3D scene "Multi-Branch Gear Synchronization Challenge" 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: Multi-Branch Gear Synchronization Challenge
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/multi-branch-gear-synchronization-challenge-x3452
Scene Description Prompt:
Make a voxel gear puzzle driving two output dials from one source, enforcing consistent ratios and rotation directions. Three.js from cdnjs, one HTML file.
Working Three.js Starter (multi-branch-gear-synchronization-challenge-x3452):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Gear Puzzle — One Source, Two Dials</title>
<style>
:root {
color-scheme: dark;
--bg: #071119;
--panel: rgba(12, 26, 35, 0.96);
--line: rgba(153, 207, 220, 0.16);
--text: #eaf7fa;
--muted: #91abb4;
--source: #ffbd59;
--a: #42e2d0;
--b: #ff5f91;
--good: #73f2ad;
--warn: #ffbd59;
}
* {
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;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#stage {
position: absolute;
inset: 0 390px 0 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 42%, #132a35 0%, #09161e 55%, #061018 100%);
}
#scene {
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
#labels {
position: absolute;
inset: 0;
pointer-events: none;
overflow: hidden;
}
.scene-label {
position: absolute;
left: 0;
top: 0;
padding: 5px 8px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 4px;
background: rgba(5, 15, 21, 0.84);
box-shadow: 0 5px 16px rgba(0, 0, 0, 0.25);
color: #dceff3;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
white-space: nowrap;
transform: translate(-50%, -50%);
backdrop-filter: blur(5px);
}
.scene-label.source {
color: var(--source);
border-color: rgba(255, 189, 89, 0.35);
}
.scene-label.a {
color: var(--a);
border-color: rgba(66, 226, 208, 0.35);
}
.scene-label.b {
color: var(--b);
border-color: rgba(255, 95, 145, 0.35);
}
.scene-label.output {
font-size: 11px;
padding: 7px 10px;
}
.hero {
position: absolute;
top: 26px;
left: 28px;
max-width: 470px;
pointer-events: none;
text-shadow: 0 2px 16px rgba(0, 0, 0, 0.5);
}
.eyebrow {
color: var(--source);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 7px;
font-size: clamp(26px, 3.2vw, 48px);
line-height: 0.96;
letter-spacing: -0.055em;
text-transform: uppercase;
}
.hero p {
margin: 0;
max-width: 430px;
color: #aac0c8;
font-size: 13px;
line-height: 1.5;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 14px;
}
.legend span {
padding: 6px 8px;
border: 1px solid var(--line);
border-radius: 4px;
background: rgba(7, 17, 25, 0.68);
color: #9fb7c0;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.05em;
}
.camera-hint {
position: absolute;
left: 26px;
bottom: 20px;
color: rgba(190, 215, 222, 0.62);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
letter-spacing: 0.05em;
pointer-events: none;
}
#panel {
position: absolute;
top: 18px;
right: 18px;
bottom: 18px;
width: 354px;
overflow: auto;
padding: 18px;
border: 1px solid var(--line);
border-radius: 14px;
background: var(--panel);
box-shadow:
0 22px 70px rgba(0, 0, 0, 0.42),
inset 0 1px rgba(255, 255, 255, 0.035);
scrollbar-width: thin;
scrollbar-color: #35505b transparent;
}
.panel-title {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 14px;
}
.panel-title h2 {
margin: 0;
font-size: 18px;
letter-spacing: -0.025em;
}
.panel-title p {
margin: 4px 0 0;
color: var(--muted);
font-size: 11px;
}
.chip {
flex: 0 0 auto;
padding: 5px 7px;
border: 1px solid rgba(255, 189, 89, 0.3);
border-radius: 4px;
color: var(--source);
background: rgba(255, 189, 89, 0.06);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.08em;
}
.status {
display: flex;
align-items: center;
gap: 11px;
margin-bottom: 12px;
padding: 11px;
border: 1px solid rgba(255, 189, 89, 0.22);
border-radius: 7px;
background: rgba(255, 189, 89, 0.055);
}
.status.ready {
border-color: rgba(66, 226, 208, 0.28);
background: rgba(66, 226, 208, 0.055);
}
.status.locked {
border-color: rgba(115, 242, 173, 0.32);
background: rgba(115, 242, 173, 0.065);
}
.led {
width: 10px;
height: 10px;
flex: 0 0 auto;
border-radius: 2px;
background: var(--warn);
box-shadow: 0 0 14px rgba(255, 189, 89, 0.65);
}
.ready .led {
background: var(--a);
box-shadow: 0 0 14px rgba(66, 226, 208, 0.65);
}
.locked .led {
background: var(--good);
box-shadow: 0 0 14px rgba(115, 242, 173, 0.65);
}
.status small,
.status strong {
display: block;
}
.status small {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 8px;
letter-spacing: 0.13em;
}
.status strong {
margin-top: 2px;
font-size: 11px;
letter-spacing: 0.02em;
}
.card {
margin-top: 10px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.018);
}
.card.source-card {
border-color: rgba(255, 189, 89, 0.18);
}
.card.branch-a {
border-left: 3px solid var(--a);
}
.card.branch-b {
border-left: 3px solid var(--b);
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.card h3 {
margin: 0;
font-size: 12px;
letter-spacing: 0.01em;
}
.micro {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.04em;
}
.source-controls {
display: grid;
grid-template-columns: 1fr auto;
gap: 10px;
align-items: center;
margin-top: 11px;
}
input[type="range"] {
width: 100%;
accent-color: var(--source);
cursor: pointer;
}
.small-button,
.action {
border: 1px solid var(--line);
border-radius: 5px;
background: #142832;
cursor: pointer;
transition:
background 120ms ease,
border-color 120ms ease,
transform 120ms ease;
}
.small-button {
min-width: 66px;
padding: 7px 9px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.06em;
}
.small-button:hover,
.action:hover:not(:disabled) {
border-color: rgba(255, 255, 255, 0.34);
background: #1b3541;
}
.small-button:active,
.action:active:not(:disabled) {
transform: translateY(1px);
}
.contract {
margin: 11px 0;
padding: 9px 10px;
border-radius: 5px;
background: rgba(0, 0, 0, 0.2);
}
.contract .label,
.contract .value {
display: block;
}
.contract .label {
color: var(--muted);
font-size: 9px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.contract .value {
margin-top: 3px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 14px;
font-weight: 900;
}
.control {
margin-top: 11px;
}
.control-label {
display: flex;
justify-content: space-between;
margin-bottom: 6px;
color: #b5c8ce;
font-size: 10px;
}
.segmented {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 5px;
}
.segmented button {
min-width: 0;
padding: 7px 2px;
border: 1px solid var(--line);
border-radius: 4px;
background: rgba(255, 255, 255, 0.025);
color: #a9bdc4;
cursor: pointer;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 800;
}
.segmented button:hover:not(:disabled) {
border-color: rgba(255, 255, 255, 0.3);
color: white;
}
.segmented button.selected {
color: #071119;
border-color: transparent;
font-weight: 950;
}
.branch-a .segmented button.selected {
background: var(--a);
}
.branch-b .segmented button.selected {
background: var(--b);
}
.segmented button:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.actual {
margin-top: 11px;
padding-top: 10px;
border-top: 1px solid var(--line);
}
.actual strong {
display: block;
margin-top: 4px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
.branch-result {
margin-top: 8px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.04em;
}
.branch-result.good {
color: var(--good);
}
.branch-result.bad {
color: var(--warn);
}
.meter {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 10px;
}
.meter-card {
padding: 11px;
border: 1px solid var(--line);
border-radius: 7px;
background: rgba(0, 0, 0, 0.17);
}
.meter-card.a {
border-top: 2px solid var(--a);
}
.meter-card.b {
border-top: 2px solid var(--b);
}
.meter-card .name {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
}
.meter-card .rpm {
display: block;
margin-top: 6px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 21px;
font-weight: 900;
}
.meter-card .direction {
display: block;
margin-top: 3px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
}
.actions {
display: grid;
grid-template-columns: 1fr auto auto;
gap: 7px;
margin-top: 12px;
}
.action {
padding: 10px 12px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 950;
letter-spacing: 0.055em;
}
.action.primary {
border-color: rgba(115, 242, 173, 0.36);
background: rgba(115, 242, 173, 0.12);
color: var(--good);
}
.action:disabled {
cursor: not-allowed;
opacity: 0.42;
}
.note {
margin: 11px 2px 0;
color: #7f9aa4;
font-size: 10px;
line-height: 1.45;
}
@media (max-width: 850px) {
#stage {
inset: 0 0 49% 0;
}
#panel {
top: auto;
right: 0;
bottom: 0;
left: 0;
width: 100%;
max-height: 49%;
border-right: 0;
border-bottom: 0;
border-left: 0;
border-radius: 14px 14px 0 0;
padding: 14px;
}
.hero {
top: 16px;
left: 17px;
max-width: calc(100% - 34px);
}
.hero h1 {
font-size: 27px;
}
.hero p,
.legend {
display: none;
}
.camera-hint {
left: 16px;
bottom: 10px;
font-size: 8px;
}
.panel-title {
margin-bottom: 10px;
}
}
</style>
</head>
<body>
<main id="stage">
<canvas id="scene" aria-label="Interactive voxel gear mechanism"></canvas>
<div id="labels"></div>
<header class="hero">
<div class="eyebrow">Voxel // Transmission Lab</div>
<h1>One source.<br />Two dials.</h1>
<p>
Configure both compound gear trains. Match each signed ratio contract,
then lock the interlock. Every dial is solved from the same source angle.
</p>
<div class="legend">
<span>EXTERNAL MESH = REVERSE</span>
<span>SHARED SHAFT = LOCKED SPEED</span>
<span>ODD MESHES = REVERSE</span>
</div>
</header>
<div class="camera-hint">DRAG TO ORBIT · WHEEL TO ZOOM · DOUBLE-CLICK TO RESET VIEW</div>
</main>
<aside id="panel">
<div class="panel-title">
<div>
<h2>Ratio Contracts</h2>
<p>Positive is CCW. Negative is CW.</p>
</div>
<div class="chip">PUZZLE 01</div>
</div>
<div id="status" class="status" aria-live="polite">
<span class="led"></span>
<div>
<small>INTERLOCK STATE</small>
<strong id="statusText">RATIO CONTRACTS UNRESOLVED</strong>
</div>
</div>
<section class="card source-card">
<div class="row">
<h3>Source Shaft</h3>
<span class="micro">16T · CCW</span>
</div>
<div class="source-controls">
<input
id="speed"
type="range"
min="4"
max="24"
step="1"
value="12"
aria-label="Source speed in revolutions per minute"
/>
<button id="pause" class="small-button">PAUSE</button>
</div>
<div class="row" style="margin-top: 8px">
<span class="micro">SOURCE SPEED</span>
<span id="sourceRpm" class="micro">12 RPM</span>
</div>
</section>
<section class="card branch-a">
<div class="row">
<h3 style="color: var(--a)">Branch A / Output Dial</h3>
<span class="micro">2 MESHES</span>
</div>
<div class="contract">
<span class="label">Required contract</span>
<span class="value" style="color: var(--a)">+0.500× · CCW</span>
</div>
<div class="control">
<div class="control-label">
<span>Compound drive gear</span>
<span class="micro">SELECT TEETH</span>
</div>
<div id="a-drive" class="segmented"></div>
</div>
<div class="control">
<div class="control-label">
<span>Output gear</span>
<span class="micro">SELECT TEETH</span>
</div>
<div id="a-output" class="segmented"></div>
</div>
<div class="actual">
<div class="row">
<span class="micro">CALCULATED OUTPUT</span>
<span class="micro">12T RELAY PINION</span>
</div>
<strong id="a-actual" style="color: var(--a)">—</strong>
<div id="a-result" class="branch-result bad">RATIO MISMATCH</div>
</div>
</section>
<section class="card branch-b">
<div class="row">
<h3 style="color: var(--b)">Branch B / Output Dial</h3>
<span class="micro">3 MESHES</span>
</div>
<div class="contract">
<span class="label">Required contract</span>
<span class="value" style="color: var(--b)">−0.250× · CW</span>
</div>
<div class="control">
<div class="control-label">
<span>Compound drive gear</span>
<span class="micro">SELECT TEETH</span>
</div>
<div id="b-drive" class="segmented"></div>
</div>
<div class="control">
<div class="control-label">
<span>Output gear</span>
<span class="micro">SELECT TEETH</span>
</div>
<div id="b-output" class="segmented"></div>
</div>
<div class="actual">
<div class="row">
<span class="micro">CALCULATED OUTPUT</span>
<span class="micro">20T IDLER</span>
</div>
<strong id="b-actual" style="color: var(--b)">—</strong>
<div id="b-result" class="branch-result bad">RATIO MISMATCH</div>
</div>
</section>
<div class="meter">
<div class="meter-card a">
<span class="name">OUTPUT A</span>
<span id="a-rpm" class="rpm">0.0</span>
<span id="a-direction" class="direction">RPM · CCW</span>
</div>
<div class="meter-card b">
<span class="name">OUTPUT B</span>
<span id="b-rpm" class="rpm">0.0</span>
<span id="b-direction" class="direction">RPM · CW</span>
</div>
</div>
<div class="actions">
<button id="lock" class="action primary" disabled>CONTRACTS UNRESOLVED</button>
<button id="hint" class="action">HINT</button>
<button id="reset" class="action">RESET</button>
</div>
<p class="note">
Branch A has two external meshes, so it preserves the source direction.
Branch B has three, so it reverses it. Compound gears on the same shaft
always rotate at exactly the same angular speed.
</p>
</aside>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Puzzle data
// -------------------------------------------------------------------------
const SOURCE_TEETH = 16;
const RELAY_TEETH = 12;
const B_IDLER_TEETH = 20;
const TARGET_A = 0.5;
const TARGET_B = -0.25;
const TOOTH_OPTIONS = [16, 24, 32, 40];
const OUTPUT_OPTIONS = [12, 16, 24, 32, 40];
const state = {
driveA: 32,
outputA: 24,
driveB: 24,
outputB: 16,
rpm: 12,
paused: false,
locked: false,
sourceAngle: 0.35
};
const COLORS = {
source: 0xffbd59,
a: 0x42e2d0,
b: 0xff5f91,
steel: 0xb7c9cf,
dark: 0x10232c
};
const PITCH_PER_TOOTH = 0.044;
const radiusOf = teeth => teeth * PITCH_PER_TOOTH;
/*
A:
source -> drive A -> output A
Two meshes preserve direction.
ratio = +(sourceTeeth * relayTeeth) /
(driveA * outputA)
B:
source -> drive B -> idler -> output B
Three meshes reverse direction.
ratio = -(sourceTeeth * relayTeeth) /
(driveB * outputB)
*/
function calculatedRatios() {
const magnitude = (SOURCE_TEETH * RELAY_TEETH);
return {
a: magnitude / (state.driveA * state.outputA),
b: -magnitude / (state.driveB * state.outputB)
};
}
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const stage = document.querySelector("#stage");
const canvas = document.querySelector("#scene");
const labelLayer = document.querySelector("#labels");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071119);
scene.fog = new THREE.Fog(0x071119, 18, 34);
const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 100);
const cameraState = {
azimuth: -0.72,
polar: 0.78,
distance: 14.8,
target: new THREE.Vector3(0.45, 0.25, 0.35)
};
const hemisphere = new THREE.HemisphereLight(0xbdefff, 0x14202a, 2.25);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff1d4, 3.1);
keyLight.position.set(4, -7, 11);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -11;
keyLight.shadow.camera.right = 11;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -9;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(COLORS.a, 18, 14, 2);
cyanLight.position.set(-5, 1, 5);
scene.add(cyanLight);
const pinkLight = new THREE.PointLight(COLORS.b, 16, 14, 2);
pinkLight.position.set(5, 2, 5);
scene.add(pinkLight);
const dynamicRoot = new THREE.Group();
scene.add(dynamicRoot);
const sourceRoot = new THREE.Group();
scene.add(sourceRoot);
let refs = {};
let dynamicLabels = [];
// -------------------------------------------------------------------------
// Materials and voxel construction helpers
// -------------------------------------------------------------------------
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.58,
metalness: options.metalness ?? 0.18,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0
});
}
function makeBox(size, color, position, parent, options = {}) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
material(color, options)
);
mesh.position.copy(position);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? false;
parent.add(mesh);
return mesh;
}
function makeInstancedBoxes(count, color) {
const geometry = new THREE.BoxGeometry(1, 1, 1);
const mesh = new THREE.InstancedMesh(
geometry,
material(color),
count
);
mesh.castShadow = true;
mesh.receiveShadow = true;
const dummy = new THREE.Object3D();
return {
mesh,
dummy,
set(index, x, y, z, rotation, scaleX, scaleY, scaleZ) {
dummy.position.set(x, y, z);
dummy.rotation.set(0, 0, rotation);
dummy.scale.set(scaleX, scaleY, scaleZ);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
},
finish() {
mesh.instanceMatrix.needsUpdate = true;
mesh.computeBoundingSphere();
}
};
}
/*
A gear is deliberately assembled from square blocks:
square teeth, block rim segments, square spokes and a cubic hub.
*/
function buildVoxelGear(teeth, color, depth = 0.28) {
const group = new THREE.Group();
const radius = radiusOf(teeth);
const toothColor = new THREE.Color(color);
const rimColor = toothColor.clone().multiplyScalar(0.67);
const hubColor = toothColor.clone().lerp(new THREE.Color(0xffffff), 0.2);
const toothWidth = Math.min(0.19, Math.max(0.12, 2 * Math.PI * radius / teeth * 0.52));
const toothDepth = 0.21;
const toothSet = makeInstancedBoxes(teeth, color);
for (let i = 0; i < teeth; i++) {
const angle = (i / teeth) * Math.PI * 2;
toothSet.set(
i,
Math.cos(angle) * radius,
Math.sin(angle) * radius,
0,
angle,
toothWidth,
toothDepth,
depth
);
}
toothSet.finish();
group.add(toothSet.mesh);
const rimCount = Math.max(10, Math.round(teeth * 0.68));
const rimRadius = Math.max(0.22, radius - 0.12);
const rimWidth = (2 * Math.PI * rimRadius / rimCount) * 0.78;
const rimSet = makeInstancedBoxes(rimCount, rimColor);
for (let i = 0; i < rimCount; i++) {
const angle = (i / rimCount) * Math.PI * 2;
rimSet.set(
i,
Math.cos(angle) * rimRadius,
Math.sin(angle) * rimRadius,
0,
angle,
rimWidth,
0.19,
depth * 0.88
);
}
rimSet.finish();
group.add(rimSet.mesh);
const spokeCount = 4;
const spokeLength = Math.max(0.2, radius * 0.74);
const spokeWidth = Math.min(0.14, radius * 0.19);
for (let i = 0; i < spokeCount; i++) {
const angle = (i / spokeCount) * Math.PI * 2 + Math.PI / 4;
const spoke = makeBox(
new THREE.Vector3(spokeWidth, spokeLength, depth * 0.72),
rimColor,
new THREE.Vector3(
Math.cos(angle) * radius * 0.35,
Math.sin(angle) * radius * 0.35,
0
),
group
);
spoke.rotation.z = angle;
}
const hubSize = Math.min(0.42, Math.max(0.25, radius * 0.55));
makeBox(
new THREE.Vector3(hubSize, hubSize, depth * 1.12),
hubColor,
new THREE.Vector3(0, 0, 0),
group
);
const boltRadius = Math.min(0.31, radius * 0.4);
for (let i = 0; i < 4; i++) {
const angle = i * Math.PI / 2 + Math.PI / 4;
makeBox(
new THREE.Vector3(0.065, 0.065, depth * 1.2),
COLORS.dark,
new THREE.Vector3(
Math.cos(angle) * boltRadius,
Math.sin(angle) * boltRadius,
0
),
group
);
}
return group;
}
function buildOutputDial(outputRadius, color) {
const group = new THREE.Group();
const radius = outputRadius + 0.35;
const count = 28;
const ringSet = makeInstancedBoxes(count, color);
for (let i = 0; i < count; i++) {
const angle = (i / count) * Math.PI * 2;
const major = i % 3 === 0;
ringSet.set(
i,
Math.cos(angle) * radius,
Math.sin(angle) * radius,
0,
angle,
major ? 0.13 : 0.09,
major ? 0.24 : 0.12,
0.15
);
}
ringSet.finish();
group.add(ringSet.mesh);
const needle = new THREE.Group();
makeBox(
new THREE.Vector3(0.095, radius * 0.72, 0.105),
0xf4fbfc,
new THREE.Vector3(0, radius * 0.31, 0),
needle
);
makeBox(
new THREE.Vector3(0.22, 0.22, 0.14),
color,
new THREE.Vector3(0, radius * 0.65, 0),
needle
);
makeBox(
new THREE.Vector3(0.25, 0.25, 0.18),
COLORS.dark,
new THREE.Vector3(0, 0, 0),
needle
);
group.add(needle);
group.userData.needle = needle;
return group;
}
function addShaft(position, height, color = 0x40545d) {
return makeBox(
new THREE.Vector3(0.18, 0.18, height),
color,
new THREE.Vector3(position.x, position.y, height / 2),
dynamicRoot
);
}
function addRail(from, to, color) {
const direction = new THREE.Vector2().subVectors(to, from);
const length = direction.length();
const rail = makeBox(
new THREE.Vector3(length, 0.055, 0.028),
color,
new THREE.Vector3(
(from.x + to.x) / 2,
(from.y + to.y) / 2,
0.035
),
dynamicRoot,
{ castShadow: false, roughness: 0.9 }
);
rail.rotation.z = Math.atan2(direction.y, direction.x);
rail.material.color.multiplyScalar(0.55);
}
// -------------------------------------------------------------------------
// Base platform
// -------------------------------------------------------------------------
const base = new THREE.Group();
scene.add(base);
const platform = makeBox(
new THREE.Vector3(15.2, 8.2, 0.36),
0x10242d,
new THREE.Vector3(0.4, 0.25, -0.18),
base
);
platform.receiveShadow = true;
const gridMaterial = material(0x213943, {
roughness: 0.95,
metalness: 0.02
});
for (let x = -6.8; x <= 7.6; x += 0.8) {
const line = new THREE.Mesh(
new THREE.BoxGeometry(0.018, 7.7, 0.015),
gridMaterial
);
line.position.set(x, 0.25, 0.012);
base.add(line);
}
for (let y = -3.5; y <= 4; y += 0.8) {
const line = new THREE.Mesh(
new THREE.BoxGeometry(14.7, 0.018, 0.015),
gridMaterial
);
line.position.set(0.4, y, 0.012);
base.add(line);
}
// Raised perimeter blocks.
const borderMaterial = material(0x28434e, { roughness: 0.72 });
for (let x = -7; x <= 7.8; x += 0.8) {
makeBox(
new THREE.Vector3(0.5, 0.13, 0.16),
borderMaterial,
new THREE.Vector3(x, -3.76, 0.08),
base,
{ castShadow: false }
);
makeBox(
new THREE.Vector3(0.5, 0.13, 0.16),
borderMaterial,
new THREE.Vector3(x, 4.26, 0.08),
base,
{ castShadow: false }
);
}
for (let y = -3.2; y <= 3.9; y += 0.8) {
makeBox(
new THREE.Vector3(0.13, 0.5, 0.16),
borderMaterial,
new THREE.Vector3(-7.15, y, 0.08),
base,
{ castShadow: false }
);
makeBox(
new THREE.Vector3(0.13, 0.5, 0.16),
borderMaterial,
new THREE.Vector3(7.95, y, 0.08),
base,
{ castShadow: false }
);
}
// Source gear and crank.
const sourceGear = buildVoxelGear(SOURCE_TEETH, COLORS.source, 0.32);
sourceGear.position.z = 0.24;
sourceRoot.add(sourceGear);
const crank = new THREE.Group();
crank.position.z = 0.48;
sourceRoot.add(crank);
makeBox(
new THREE.Vector3(0.16, 0.86, 0.12),
0xe08a31,
new THREE.Vector3(0, 0.38, 0),
crank
);
makeBox(
new THREE.Vector3(0.34, 0.34, 0.34),
COLORS.source,
new THREE.Vector3(0, 0.83, 0),
crank
);
makeBox(
new THREE.Vector3(0.22, 0.22, 0.42),
0x35474d,
new THREE.Vector3(0, 0, 0),
sourceRoot
);
addShaft(new THREE.Vector2(0, 0), 0.46, 0x465a63);
// -------------------------------------------------------------------------
// Labels
// -------------------------------------------------------------------------
const allLabels = [];
function addSceneLabel(text, className, position) {
const element = document.createElement("div");
element.className = `scene-label ${className}`;
element.textContent = text;
labelLayer.appendChild(element);
const label = {
element,
position: position.clone()
};
allLabels.push(label);
dynamicLabels.push(label);
return label;
}
const sourceLabel = document.createElement("div");
sourceLabel.className = "scene-label source";
sourceLabel.textContent = "16T · SOURCE";
labelLayer.appendChild(sourceLabel);
allLabels.push({
element: sourceLabel,
position: new THREE.Vector3(0, -0.78, 1.0)
});
function clearDynamicLabels() {
for (const label of dynamicLabels) {
label.element.remove();
const index = allLabels.indexOf(label);
if (index !== -1) allLabels.splice(index, 1);
}
dynamicLabels = [];
}
// -------------------------------------------------------------------------
// Mechanism construction
// -------------------------------------------------------------------------
function disposeGroup(group) {
group.traverse(object => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
if (Array.isArray(object.material)) {
object.material.forEach(mat => mat.dispose());
} else {
object.material.dispose();
}
}
});
}
function clearDynamicMechanism() {
for (const child of [...dynamicRoot.children]) {
dynamicRoot.remove(child);
disposeGroup(child);
}
clearDynamicLabels();
}
function buildMechanism() {
clearDynamicMechanism();
const ratios = calculatedRatios();
const sourceRadius = radiusOf(SOURCE_TEETH);
const sourcePosition = new THREE.Vector2(0, 0);
const aDirection = new THREE.Vector2(
Math.cos(THREE.MathUtils.degToRad(150)),
Math.sin(THREE.MathUtils.degToRad(150))
);
const bDirection = new THREE.Vector2(
Math.cos(THREE.MathUtils.degToRad(30)),
Math.sin(THREE.MathUtils.degToRad(30))
);
const aDistance = sourceRadius + radiusOf(state.driveA);
const bDistance = sourceRadius + radiusOf(state.driveB);
const aCompoundPosition = sourcePosition.clone().addScaledVector(aDirection, aDistance);
const bCompoundPosition = sourcePosition.clone().addScaledVector(bDirection, bDistance);
const aOutputDirection = new THREE.Vector2(
Math.cos(THREE.MathUtils.degToRad(205)),
Math.sin(THREE.MathUtils.degToRad(205))
);
const aOutputDistance = radiusOf(RELAY_TEETH) + radiusOf(state.outputA);
const aOutputPosition = aCompoundPosition.clone().addScaledVector(
aOutputDirection,
aOutputDistance
);
const bIdlerDirection = new THREE.Vector2(
Math.cos(THREE.MathUtils.degToRad(80)),
Math.sin(THREE.MathUtils.degToRad(80))
);
const bIdlerDistance = radiusOf(RELAY_TEETH) + radiusOf(B_IDLER_TEETH);
const bIdlerPosition = bCompoundPosition.clone().addScaledVector(
bIdlerDirection,
bIdlerDistance
);
const bOutputDirection = new THREE.Vector2(
Math.cos(THREE.MathUtils.degToRad(-10)),
Math.sin(THREE.MathUtils.degToRad(-10))
);
const bOutputDistance = radiusOf(B_IDLER_TEETH) + radiusOf(state.outputB);
const bOutputPosition = bIdlerPosition.clone().addScaledVector(
bOutputDirection,
bOutputDistance
);
addRail(sourcePosition, aCompoundPosition, COLORS.a);
addRail(aCompoundPosition, aOutputPosition, COLORS.a);
addRail(sourcePosition, bCompoundPosition, COLORS.b);
addRail(bCompoundPosition, bIdlerPosition, COLORS.b);
addRail(bIdlerPosition, bOutputPosition, COLORS.b);
// Branch A compound shaft.
const aCompound = new THREE.Group();
aCompound.position.set(aCompoundPosition.x, aCompoundPosition.y, 0);
dynamicRoot.add(aCompound);
const aDriver = buildVoxelGear(state.driveA, COLORS.a, 0.28);
aDriver.position.z = 0.25;
aCompound.add(aDriver);
const aRelay = buildVoxelGear(RELAY_TEETH, COLORS.steel, 0.25);
aRelay.position.z = 0.66;
aCompound.add(aRelay);
const aOutput = buildVoxelGear(state.outputA, COLORS.a, 0.27);
aOutput.position.set(aOutputPosition.x, aOutputPosition.y, 0.66);
dynamicRoot.add(aOutput);
const aDial = buildOutputDial(radiusOf(state.outputA), COLORS.a);
aDial.position.set(aOutputPosition.x, aOutputPosition.y, 0.93);
dynamicRoot.add(aDial);
// Branch B compound shaft and idler.
const bCompound = new THREE.Group();
bCompound.position.set(bCompoundPosition.x, bCompoundPosition.y, 0);
dynamicRoot.add(bCompound);
const bDriver = buildVoxelGear(state.driveB, COLORS.b, 0.28);
bDriver.position.z = 0.25;
bCompound.add(bDriver);
const bRelay = buildVoxelGear(RELAY_TEETH, COLORS.steel, 0.25);
bRelay.position.z = 0.66;
bCompound.add(bRelay);
const bIdler = buildVoxelGear(B_IDLER_TEETH, COLORS.b, 0.27);
bIdler.position.set(bIdlerPosition.x, bIdlerPosition.y, 0.66);
dynamicRoot.add(bIdler);
const bOutput = buildVoxelGear(state.outputB, COLORS.b, 0.27);
bOutput.position.set(bOutputPosition.x, bOutputPosition.y, 0.66);
dynamicRoot.add(bOutput);
const bDial = buildOutputDial(radiusOf(state.outputB), COLORS.b);
bDial.position.set(bOutputPosition.x, bOutputPosition.y, 0.93);
dynamicRoot.add(bDial);
addShaft(aCompoundPosition, 0.78);
addShaft(bCompoundPosition, 0.78);
addShaft(bIdlerPosition, 0.78);
addShaft(aOutputPosition, 0.78);
addShaft(bOutputPosition, 0.78);
addSceneLabel(
`${state.driveA}T`,
"a",
new THREE.Vector3(aCompoundPosition.x - 0.32, aCompoundPosition.y + 0.44, 1.02)
);
addSceneLabel(
`${RELAY_TEETH}T`,
"a",
new THREE.Vector3(aCompoundPosition.x + 0.42, aCompoundPosition.y - 0.42, 1.05)
);
addSceneLabel(
`${state.outputA}T · A ${formatRatio(ratios.a)}`,
"a output",
new THREE.Vector3(
aOutputPosition.x,
aOutputPosition.y + radiusOf(state.outputA) + 0.72,
1.25
)
);
addSceneLabel(
`${state.driveB}T`,
"b",
new THREE.Vector3(bCompoundPosition.x - 0.36, bCompoundPosition.y + 0.45, 1.02)
);
addSceneLabel(
`${RELAY_TEETH}T`,
"b",
new THREE.Vector3(bCompoundPosition.x + 0.43, bCompoundPosition.y - 0.42, 1.05)
);
addSceneLabel(
`${B_IDLER_TEETH}T`,
"b",
new THREE.Vector3(bIdlerPosition.x - 0.35, bIdlerPosition.y + 0.38, 1.02)
);
addSceneLabel(
`${state.outputB}T · B ${formatRatio(ratios.b)}`,
"b output",
new THREE.Vector3(
bOutputPosition.x,
bOutputPosition.y + radiusOf(state.outputB) + 0.72,
1.25
)
);
refs = {
aCompound,
aOutput,
aDial,
bCompound,
bIdler,
bOutput,
bDial
};
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const speedInput = document.querySelector("#speed");
const pauseButton = document.querySelector("#pause");
const lockButton = document.querySelector("#lock");
const hintButton = document.querySelector("#hint");
const resetButton = document.querySelector("#reset");
const statusElement = document.querySelector("#status");
const statusText = document.querySelector("#statusText");
function formatRatio(value) {
const sign = value < 0 ? "−" : "+";
return `${sign}${Math.abs(value).toFixed(3)}×`;
}
function directionFor(value) {
return value >= 0 ? "CCW" : "CW";
}
function renderSegment(elementId, values, selectedValue, stateKey) {
const container = document.querySelector(`#${elementId}`);
container.innerHTML = "";
for (const value of values) {
const button = document.createElement("button");
button.type = "button";
button.textContent = `${value}T`;
button.dataset.value = value;
button.classList.toggle("selected", value === selectedValue);
button.setAttribute(
"aria-pressed",
value === selectedValue ? "true" : "false"
);
button.addEventListener("click", () => {
if (state.locked) return;
state[stateKey] = value;
state.locked = false;
buildMechanism();
updateUI();
});
container.appendChild(button);
}
}
function renderControls() {
renderSegment("a-drive", TOOTH_OPTIONS, state.driveA, "driveA");
renderSegment("a-output", OUTPUT_OPTIONS, state.outputA, "outputA");
renderSegment("b-drive", TOOTH_OPTIONS, state.driveB, "driveB");
renderSegment("b-output", OUTPUT_OPTIONS, state.outputB, "outputB");
}
function updateSegmentStates() {
const mappings = [
["a-drive", state.driveA],
["a-output", state.outputA],
["b-drive", state.driveB],
["b-output", state.outputB]
];
for (const [id, selected] of mappings) {
const container = document.querySelector(`#${id}`);
for (const button of container.querySelectorAll("button")) {
const isSelected = Number(button.dataset.value) === selected;
button.classList.toggle("selected", isSelected);
button.setAttribute("aria-pressed", isSelected ? "true" : "false");
button.disabled = state.locked;
}
}
}
function updateUI() {
const ratios = calculatedRatios();
const validA = Math.abs(ratios.a - TARGET_A) < 1e-9;
const validB = Math.abs(ratios.b - TARGET_B) < 1e-9;
const validBoth = validA && validB;
document.querySelector("#a-actual").textContent =
`${formatRatio(ratios.a)} · ${directionFor(ratios.a)}`;
document.querySelector("#b-actual").textContent =
`${formatRatio(ratios.b)} · ${directionFor(ratios.b)}`;
const aResult = document.querySelector("#a-result");
const bResult = document.querySelector("#b-result");
aResult.textContent = validA ? "RATIO + DIRECTION MATCH" : "RATIO MISMATCH";
aResult.className = `branch-result ${validA ? "good" : "bad"}`;
bResult.textContent = validB ? "RATIO + DIRECTION MATCH" : "RATIO MISMATCH";
bResult.className = `branch-result ${validB ? "good" : "bad"}`;
statusElement.classList.toggle("ready", validBoth && !state.locked);
statusElement.classList.toggle("locked", state.locked);
if (state.locked) {
statusText.textContent = "CONTRACTS LOCKED · DRIVE SYNCHRONIZED";
} else if (validBoth) {
statusText.textContent = "RATIOS SOLVED · READY TO LOCK";
} else {
statusText.textContent = "RATIO CONTRACTS UNRESOLVED";
}
lockButton.disabled = !validBoth || state.locked;
hintButton.disabled = state.locked;
if (state.locked) {
lockButton.textContent = "CONTRACTS LOCKED";
} else if (validBoth) {
lockButton.textContent = "VERIFY & LOCK";
} else {
lockButton.textContent = "CONTRACTS UNRESOLVED";
}
updateSegmentStates();
}
function updateReadouts() {
const ratios = calculatedRatios();
document.querySelector("#sourceRpm").textContent = `${state.rpm} RPM`;
document.querySelector("#a-rpm").textContent =
(state.rpm * ratios.a).toFixed(1);
document.querySelector("#b-rpm").textContent =
(state.rpm * ratios.b).toFixed(1);
document.querySelector("#a-direction").textContent =
`RPM · ${directionFor(ratios.a)}`;
document.querySelector("#b-direction").textContent =
`RPM · ${directionFor(ratios.b)}`;
}
speedInput.addEventListener("input", () => {
state.rpm = Number(speedInput.value);
updateReadouts();
});
pauseButton.addEventListener("click", () => {
state.paused = !state.paused;
pauseButton.textContent = state.paused ? "RESUME" : "PAUSE";
});
lockButton.addEventListener("click", () => {
const ratios = calculatedRatios();
if (
Math.abs(ratios.a - TARGET_A) < 1e-9 &&
Math.abs(ratios.b - TARGET_B) < 1e-9
) {
state.locked = true;
updateUI();
}
});
hintButton.addEventListener("click", () => {
const ratios = calculatedRatios();
if (Math.abs(ratios.a - TARGET_A) >= 1e-9) {
state.driveA = 24;
state.outputA = 16;
} else if (Math.abs(ratios.b - TARGET_B) >= 1e-9) {
state.driveB = 24;
state.outputB = 32;
}
state.locked = false;
buildMechanism();
updateUI();
});
resetButton.addEventListener("click", () => {
state.driveA = 32;
state.outputA = 24;
state.driveB = 24;
state.outputB = 16;
state.rpm = 12;
state.paused = false;
state.locked = false;
state.sourceAngle = 0.35;
speedInput.value = "12";
pauseButton.textContent = "PAUSE";
renderControls();
buildMechanism();
updateUI();
updateReadouts();
});
// -------------------------------------------------------------------------
// Custom camera controls — no addons
// -------------------------------------------------------------------------
function resetCamera() {
cameraState.azimuth = -0.72;
cameraState.polar = 0.78;
cameraState.distance = 14.8;
cameraState.target.set(0.45, 0.25, 0.35);
}
function updateCamera() {
const sinPolar = Math.sin(cameraState.polar);
const cosPolar = Math.cos(cameraState.polar);
camera.position.set(
cameraState.target.x +
cameraState.distance * sinPolar * Math.cos(cameraState.azimuth),
cameraState.target.y +
cameraState.distance * sinPolar * Math.sin(cameraState.azimuth),
cameraState.target.z +
cameraState.distance * cosPolar
);
camera.lookAt(cameraState.target);
}
let dragging = false;
let previousPointer = { x: 0, y: 0 };
canvas.addEventListener("pointerdown", event => {
dragging = true;
previousPointer.x = event.clientX;
previousPointer.y = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - previousPointer.x;
const dy = event.clientY - previousPointer.y;
previousPointer.x = event.clientX;
previousPointer.y = event.clientY;
cameraState.azimuth -= dx * 0.006;
cameraState.polar = THREE.MathUtils.clamp(
cameraState.polar + dy * 0.005,
0.34,
1.28
);
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance * Math.exp(event.deltaY * 0.001),
8,
23
);
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
window.addEventListener("keydown", event => {
if (event.code === "Space") {
event.preventDefault();
pauseButton.click();
}
if (event.key.toLowerCase() === "r") {
resetCamera();
}
});
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function resize() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
const projected = new THREE.Vector3();
function updateLabels() {
const width = stage.clientWidth;
const height = stage.clientHeight;
for (const label of allLabels) {
projected.copy(label.position).project(camera);
const visible = projected.z > -1 && projected.z < 1;
label.element.style.display = visible ? "block" : "none";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
label.element.style.left = `${x}px`;
label.element.style.top = `${y}px`;
}
}
renderControls();
buildMechanism();
updateUI();
updateReadouts();
resize();
updateCamera();
let previousTime = performance.now();
function animate(now) {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (!state.paused) {
const radiansPerSecond = (state.rpm * Math.PI * 2) / 60;
state.sourceAngle =
(state.sourceAngle + radiansPerSecond * delta) % (Math.PI * 2);
}
/*
All rotations are solved from the one source angle.
No output dial has an independent animation clock.
*/
sourceRoot.rotation.z = state.sourceAngle;
if (refs.aCompound && refs.aOutput && refs.aDial) {
const aDriverAngle =
-state.sourceAngle * (SOURCE_TEETH / state.driveA);
const aOutputAngle =
state.sourceAngle *
(SOURCE_TEETH * RELAY_TEETH) /
(state.driveA * state.outputA);
refs.aCompound.rotation.z = aDriverAngle;
refs.aOutput.rotation.z = aOutputAngle;
refs.aDial.userData.needle.rotation.z = aOutputAngle;
}
if (
refs.bCompound &&
refs.bIdler &&
refs.bOutput &&
refs.bDial
) {
const bDriverAngle =
-state.sourceAngle * (SOURCE_TEETH / state.driveB);
const bIdlerAngle =
state.sourceAngle *
(SOURCE_TEETH * RELAY_TEETH) /
(state.driveB * B_IDLER_TEETH);
const bOutputAngle =
-state.sourceAngle *
(SOURCE_TEETH * RELAY_TEETH) /
(state.driveB * state.outputB);
refs.bCompound.rotation.z = bDriverAngle;
refs.bIdler.rotation.z = bIdlerAngle;
refs.bOutput.rotation.z = bOutputAngle;
refs.bDial.userData.needle.rotation.z = bOutputAngle;
}
updateCamera();
updateLabels();
updateReadouts();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```