Prompt specification
Build or customize the Three.js 3D scene "Forward Clicks Reverse Block" 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: Forward Clicks Reverse Block
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/forward-clicks-reverse-block-x2054
Scene Description Prompt:
Forward clicks reverse block. Animate a simple ratchet rotating forward in steps and resisting reverse motion under a declared kinematic rule. Keep the pawl following visible tooth contact. Please build this with Three.js from cdnjs in one self-contained HTML file, using a 3D cutaway.
Working Three.js Starter (forward-clicks-reverse-block-x2054):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>3D Ratchet — Forward Clicks, Reverse Blocks</title>
<style>
:root {
color-scheme: dark;
--cyan: #54e8ff;
--cyan-soft: rgba(84, 232, 255, 0.16);
--amber: #ffb84d;
--red: #ff5147;
--green: #6dffad;
--panel: rgba(8, 17, 29, 0.82);
--line: rgba(151, 205, 226, 0.18);
--text: #e8f7ff;
--muted: #91a8b7;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 48% 38%, #142c3e 0%, #091522 46%, #040a11 100%);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
position: fixed;
inset: 0;
display: block;
touch-action: none;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
.overlay {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
position: absolute;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 14px;
box-shadow:
0 18px 45px rgba(0, 0, 0, 0.32),
inset 0 1px rgba(255, 255, 255, 0.035);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.title-panel {
top: 22px;
left: 22px;
width: min(390px, calc(100vw - 44px));
padding: 18px 19px 16px;
}
.eyebrow {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
.cutaway-badge {
padding: 5px 7px;
border: 1px solid rgba(84, 232, 255, 0.32);
border-radius: 999px;
background: var(--cyan-soft);
letter-spacing: 0.12em;
}
h1 {
margin: 9px 0 7px;
font-size: clamp(23px, 3vw, 34px);
line-height: 1.03;
letter-spacing: -0.035em;
}
.subtitle {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.telemetry {
top: 22px;
right: 22px;
width: 252px;
padding: 15px;
}
.status {
display: flex;
align-items: center;
gap: 9px;
min-height: 32px;
margin-bottom: 13px;
padding: 8px 10px;
border: 1px solid rgba(109, 255, 173, 0.22);
border-radius: 9px;
background: rgba(109, 255, 173, 0.08);
color: var(--green);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
}
.status::before {
width: 7px;
height: 7px;
flex: 0 0 auto;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 12px currentColor;
content: "";
}
.status[data-state="reverse"] {
color: var(--red);
border-color: rgba(255, 81, 71, 0.3);
background: rgba(255, 81, 71, 0.09);
}
.status[data-state="click"] {
color: var(--amber);
border-color: rgba(255, 184, 77, 0.35);
background: rgba(255, 184, 77, 0.1);
}
.readout {
display: grid;
grid-template-columns: 1fr auto;
gap: 7px 12px;
font-size: 11px;
}
.readout span:nth-child(odd) {
color: var(--muted);
}
.readout span:nth-child(even) {
color: var(--text);
font-variant-numeric: tabular-nums;
}
.load-track {
height: 4px;
margin-top: 13px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.07);
}
.load-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--amber), var(--red));
transition: width 80ms linear;
}
.rule-panel {
left: 22px;
bottom: 22px;
width: min(460px, calc(100vw - 44px));
padding: 16px 18px;
}
.rule-title {
margin-bottom: 9px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.equation {
display: grid;
grid-template-columns: 92px 1fr;
gap: 7px 12px;
align-items: baseline;
color: #c8dce7;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 11px;
line-height: 1.5;
}
.equation b {
color: var(--amber);
font-family: inherit;
font-weight: 700;
}
.rule-note {
margin-top: 11px;
padding-top: 10px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.controls {
position: absolute;
right: 22px;
bottom: 22px;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
width: min(390px, calc(100vw - 44px));
padding: 12px;
pointer-events: auto;
}
button {
appearance: none;
border: 1px solid rgba(151, 205, 226, 0.23);
border-radius: 9px;
padding: 10px 12px;
background: rgba(16, 31, 44, 0.92);
color: #dff7ff;
font: inherit;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.025em;
cursor: pointer;
transition:
border-color 150ms ease,
background 150ms ease,
transform 100ms ease;
}
button:hover {
border-color: rgba(84, 232, 255, 0.55);
background: rgba(25, 48, 65, 0.96);
}
button:active {
transform: translateY(1px);
}
button.active {
border-color: rgba(84, 232, 255, 0.65);
background: rgba(35, 118, 142, 0.3);
color: #bff7ff;
}
button.reverse {
border-color: rgba(255, 81, 71, 0.3);
}
button.reverse:hover,
button.reverse.active {
border-color: rgba(255, 81, 71, 0.72);
background: rgba(135, 31, 31, 0.34);
color: #ffd8d5;
}
.world-label {
position: absolute;
z-index: 2;
padding: 5px 8px;
transform: translate(-50%, -50%);
border: 1px solid rgba(84, 232, 255, 0.22);
border-radius: 6px;
background: rgba(4, 13, 22, 0.78);
color: #c8f6ff;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
white-space: nowrap;
pointer-events: none;
}
#contactLabel {
border-color: rgba(255, 184, 77, 0.36);
color: #ffe0aa;
}
.help {
position: absolute;
left: 50%;
bottom: 25px;
transform: translateX(-50%);
color: rgba(185, 211, 224, 0.55);
font-size: 10px;
letter-spacing: 0.05em;
white-space: nowrap;
}
@media (max-width: 760px) {
.title-panel {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 13px 15px;
}
.title-panel .subtitle {
display: none;
}
.telemetry {
top: 108px;
right: 12px;
width: 205px;
padding: 11px;
}
.rule-panel {
left: 12px;
bottom: 78px;
width: calc(100vw - 24px);
padding: 12px 14px;
}
.equation {
grid-template-columns: 75px 1fr;
font-size: 10px;
}
.rule-note {
display: none;
}
.controls {
right: 12px;
bottom: 12px;
width: calc(100vw - 24px);
}
button {
padding: 9px 10px;
}
.help,
#pawlLabel {
display: none;
}
}
</style>
</head>
<body>
<div id="app"></div>
<div class="overlay">
<section class="panel title-panel">
<div class="eyebrow">
<span>Mechanical constraint study</span>
<span class="cutaway-badge">3D cutaway</span>
</div>
<h1>Forward clicks.<br />Reverse blocks.</h1>
<p class="subtitle">
A twenty-tooth ratchet with a visibly constrained pawl. The drive
advances in discrete indexed steps; an attempted reverse rotation is
absorbed as pawl preload.
</p>
</section>
<section class="panel telemetry">
<div id="status" class="status" data-state="normal">FORWARD · PAWL SET</div>
<div class="readout">
<span>Drive mode</span><span id="modeReadout">Auto demo</span>
<span>Tooth step</span><span id="stepReadout">0001 / 020</span>
<span>Forward angle q</span><span id="angleReadout">0.0°</span>
<span>Contact</span><span id="contactReadout">Root / seated</span>
<span>Reverse q_cmd</span><span id="commandReadout">—</span>
</div>
<div class="load-track">
<div id="loadFill" class="load-fill"></div>
</div>
</section>
<section class="panel rule-panel">
<div class="rule-title">Declared kinematic rule</div>
<div class="equation">
<b>Forward</b>
<span>qₙ → qₙ + 0.88Δ → qₙ + Δ</span>
<b>Reverse</b>
<span>q_actual = max(q_lock, q_cmd)</span>
<b>Constraint</b>
<span>q_cmd < q_lock ⇒ q̇_actual ≥ 0</span>
</div>
<div class="rule-note">
Δ = 2π/20 = 18°. Each forward tooth cycle contains a 14% dwell,
a 68% ramp, and an 18% snap. Reverse motion cannot commit: the
pawl flexes while the wheel angle remains locked.
</div>
</section>
<section class="panel controls">
<button id="autoButton" class="active">Auto demo</button>
<button id="forwardButton">Forward drive</button>
<button id="reverseButton" class="reverse">Reverse test</button>
<button id="resetButton">Reset wheel</button>
<button id="viewButton">Reset view</button>
</section>
<div id="pawlLabel" class="world-label">Flexing pawl</div>
<div id="contactLabel" class="world-label">Tooth contact</div>
<div class="help">Drag to orbit · wheel to zoom · F forward · R reverse</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and renderer
// -------------------------------------------------------------------------
const app = document.querySelector("#app");
const statusEl = document.querySelector("#status");
const modeReadout = document.querySelector("#modeReadout");
const stepReadout = document.querySelector("#stepReadout");
const angleReadout = document.querySelector("#angleReadout");
const contactReadout = document.querySelector("#contactReadout");
const commandReadout = document.querySelector("#commandReadout");
const loadFill = document.querySelector("#loadFill");
const autoButton = document.querySelector("#autoButton");
const forwardButton = document.querySelector("#forwardButton");
const reverseButton = document.querySelector("#reverseButton");
const resetButton = document.querySelector("#resetButton");
const viewButton = document.querySelector("#viewButton");
const pawlLabel = document.querySelector("#pawlLabel");
const contactLabel = document.querySelector("#contactLabel");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111d);
scene.fog = new THREE.Fog(0x07111d, 10, 19);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.18;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
app.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.05,
60
);
// -------------------------------------------------------------------------
// Custom camera controller — no addons
// -------------------------------------------------------------------------
const orbit = {
target: new THREE.Vector3(0, 0.05, 0),
radius: 8.2,
targetRadius: 8.2,
azimuth: 0.68,
targetAzimuth: 0.68,
polar: 1.05,
targetPolar: 1.05,
dragging: false,
lastX: 0,
lastY: 0
};
function updateCamera(dt) {
const damping = 1 - Math.exp(-10 * dt);
orbit.azimuth +=
(orbit.targetAzimuth - orbit.azimuth) * damping;
orbit.polar +=
(orbit.targetPolar - orbit.polar) * damping;
orbit.radius +=
(orbit.targetRadius - orbit.radius) * damping;
const sinPolar = Math.sin(orbit.polar);
camera.position.set(
orbit.target.x +
orbit.radius * sinPolar * Math.sin(orbit.azimuth),
orbit.target.y + orbit.radius * Math.cos(orbit.polar),
orbit.target.z +
orbit.radius * sinPolar * Math.cos(orbit.azimuth)
);
camera.lookAt(orbit.target);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
orbit.dragging = true;
orbit.lastX = event.clientX;
orbit.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!orbit.dragging) return;
const dx = event.clientX - orbit.lastX;
const dy = event.clientY - orbit.lastY;
orbit.lastX = event.clientX;
orbit.lastY = event.clientY;
orbit.targetAzimuth -= dx * 0.006;
orbit.targetPolar = THREE.MathUtils.clamp(
orbit.targetPolar - dy * 0.006,
0.32,
1.48
);
});
function stopDragging(event) {
orbit.dragging = false;
if (
event &&
renderer.domElement.hasPointerCapture?.(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.targetRadius = THREE.MathUtils.clamp(
orbit.targetRadius * Math.exp(event.deltaY * 0.001),
4.8,
14
);
},
{ passive: false }
);
viewButton.addEventListener("click", () => {
orbit.targetAzimuth = 0.68;
orbit.targetPolar = 1.05;
orbit.targetRadius = 8.2;
});
// -------------------------------------------------------------------------
// Lighting and environment
// -------------------------------------------------------------------------
const hemi = new THREE.HemisphereLight(0xb8e9ff, 0x18212b, 1.7);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.4);
keyLight.position.set(4.5, 7.5, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -5;
keyLight.shadow.camera.right = 5;
keyLight.shadow.camera.top = 5;
keyLight.shadow.camera.bottom = -5;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 25;
keyLight.shadow.bias = -0.00015;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x35cfff, 24, 14, 2);
rimLight.position.set(-4, 2, 4);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffa54d, 18, 12, 2);
warmLight.position.set(4, -1, 5);
scene.add(warmLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(40, 40),
new THREE.MeshStandardMaterial({
color: 0x071019,
roughness: 0.86,
metalness: 0.08
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -2.32;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(28, 28, 0x1a5269, 0x102a37);
grid.position.y = -2.305;
grid.material.transparent = true;
grid.material.opacity = 0.26;
scene.add(grid);
// -------------------------------------------------------------------------
// Materials
// -------------------------------------------------------------------------
const housingMaterial = new THREE.MeshStandardMaterial({
color: 0x142331,
roughness: 0.62,
metalness: 0.55
});
const housingEdgeMaterial = new THREE.MeshStandardMaterial({
color: 0x294252,
roughness: 0.48,
metalness: 0.72
});
const cutMaterial = new THREE.MeshStandardMaterial({
color: 0xe98b3b,
roughness: 0.48,
metalness: 0.55,
emissive: 0x3a1603,
emissiveIntensity: 0.18
});
const brassMaterial = new THREE.MeshStandardMaterial({
color: 0xd5a54c,
roughness: 0.28,
metalness: 0.88
});
const brassDarkMaterial = new THREE.MeshStandardMaterial({
color: 0x84652c,
roughness: 0.38,
metalness: 0.84
});
const steelMaterial = new THREE.MeshStandardMaterial({
color: 0xaac4d0,
roughness: 0.3,
metalness: 0.9
});
const blackSteelMaterial = new THREE.MeshStandardMaterial({
color: 0x243746,
roughness: 0.36,
metalness: 0.78
});
// -------------------------------------------------------------------------
// Cutaway housing
// -------------------------------------------------------------------------
const housing = new THREE.Group();
scene.add(housing);
function addBox(
parent,
size,
position,
material,
castShadow = true,
receiveShadow = true
) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
material
);
mesh.position.copy(position);
mesh.castShadow = castShadow;
mesh.receiveShadow = receiveShadow;
parent.add(mesh);
return mesh;
}
addBox(
housing,
new THREE.Vector3(6.35, 4.75, 0.18),
new THREE.Vector3(0, 0.08, -0.82),
housingMaterial
);
addBox(
housing,
new THREE.Vector3(6.65, 0.34, 2.35),
new THREE.Vector3(0, -2.13, -0.12),
housingEdgeMaterial
);
addBox(
housing,
new THREE.Vector3(0.28, 4.5, 1.55),
new THREE.Vector3(-3.02, 0.05, -0.18),
housingEdgeMaterial
);
// The right wall is deliberately sectioned low to expose the pawl.
addBox(
housing,
new THREE.Vector3(0.28, 1.25, 1.55),
new THREE.Vector3(3.02, -1.42, -0.18),
housingEdgeMaterial
);
addBox(
housing,
new THREE.Vector3(3.0, 0.22, 1.55),
new THREE.Vector3(-1.48, 2.22, -0.18),
housingEdgeMaterial
);
addBox(
housing,
new THREE.Vector3(1.05, 0.22, 1.55),
new THREE.Vector3(2.48, 2.22, -0.18),
housingEdgeMaterial
);
// Bright section edges.
addBox(
housing,
new THREE.Vector3(0.3, 0.12, 1.58),
new THREE.Vector3(3.02, -0.79, -0.18),
cutMaterial
);
addBox(
housing,
new THREE.Vector3(0.12, 0.75, 1.58),
new THREE.Vector3(2.94, 1.91, -0.18),
cutMaterial
);
// Ghost outline of the removed front cover.
const coverGeometry = new THREE.BoxGeometry(6.3, 4.65, 0.62);
const coverEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(coverGeometry),
new THREE.LineBasicMaterial({
color: 0x4bc9e8,
transparent: true,
opacity: 0.16
})
);
coverEdges.position.set(0, 0.05, 0.72);
housing.add(coverEdges);
// Bearing behind the wheel.
const bearing = new THREE.Mesh(
new THREE.TorusGeometry(0.94, 0.105, 16, 80),
blackSteelMaterial
);
bearing.position.z = -0.53;
housing.add(bearing);
// Fasteners.
const boltMaterial = new THREE.MeshStandardMaterial({
color: 0x8aa2ad,
roughness: 0.28,
metalness: 0.95
});
const boltGeometry = new THREE.CylinderGeometry(0.085, 0.085, 0.08, 6);
for (const [x, y] of [
[-2.72, -1.78],
[2.72, -1.78],
[-2.72, 1.86],
[2.72, 1.86]
]) {
const bolt = new THREE.Mesh(boltGeometry, boltMaterial);
bolt.rotation.x = Math.PI / 2;
bolt.position.set(x, y, 0.64);
housing.add(bolt);
}
// -------------------------------------------------------------------------
// Sawtooth ratchet geometry
//
// Each tooth is a shallow forward ramp followed by a steep drop.
// The exact same polygon is used for the visible mesh and for the
// ray/polygon contact calculation.
// -------------------------------------------------------------------------
const TOOTH_COUNT = 20;
const TOOTH_PITCH = (Math.PI * 2) / TOOTH_COUNT;
const ROOT_RADIUS = 1.48;
const TIP_RADIUS = 1.92;
const RAMP_FRACTION = 0.88;
const profileVertices = [];
const toothSamples = [
0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.78,
0.82, 0.84, 0.86, 0.88, 0.9, 0.92, 0.94, 0.96, 0.98
];
function toothRadius(u) {
if (u <= RAMP_FRACTION) {
return (
ROOT_RADIUS +
(TIP_RADIUS - ROOT_RADIUS) * (u / RAMP_FRACTION)
);
}
return (
TIP_RADIUS -
(TIP_RADIUS - ROOT_RADIUS) *
((u - RAMP_FRACTION) / (1 - RAMP_FRACTION))
);
}
for (let tooth = 0; tooth < TOOTH_COUNT; tooth++) {
for (const u of toothSamples) {
const angle = (tooth + u) * TOOTH_PITCH;
const radius = toothRadius(u);
profileVertices.push({
angle,
x: Math.cos(angle) * radius,
y: Math.sin(angle) * radius
});
}
}
const profileEdges = [];
for (let i = 0; i < profileVertices.length; i++) {
const a = profileVertices[i];
const b =
i + 1 < profileVertices.length
? profileVertices[i + 1]
: {
angle: Math.PI * 2,
x: ROOT_RADIUS,
y: 0
};
profileEdges.push({
a,
b,
endAngle: b.angle
});
}
const wheelShape = new THREE.Shape();
profileVertices.forEach((vertex, index) => {
if (index === 0) {
wheelShape.moveTo(vertex.x, vertex.y);
} else {
wheelShape.lineTo(vertex.x, vertex.y);
}
});
wheelShape.closePath();
const ringHole = new THREE.Path();
ringHole.absarc(0, 0, 1.07, 0, Math.PI * 2, true);
wheelShape.holes.push(ringHole);
const wheelGeometry = new THREE.ExtrudeGeometry(wheelShape, {
depth: 0.52,
bevelEnabled: true,
bevelSegments: 2,
bevelSize: 0.025,
bevelThickness: 0.025,
curveSegments: 2
});
wheelGeometry.translate(0, 0, -0.26);
const wheelGroup = new THREE.Group();
scene.add(wheelGroup);
const toothedRing = new THREE.Mesh(wheelGeometry, brassMaterial);
toothedRing.castShadow = true;
toothedRing.receiveShadow = true;
wheelGroup.add(toothedRing);
// Radial spokes.
for (let i = 0; i < 7; i++) {
const angle = (i / 7) * Math.PI * 2;
const spoke = new THREE.Mesh(
new THREE.BoxGeometry(0.17, 0.82, 0.28),
brassDarkMaterial
);
spoke.position.set(
Math.cos(angle) * 0.7,
Math.sin(angle) * 0.7,
0
);
spoke.rotation.z = angle - Math.PI / 2;
spoke.castShadow = true;
spoke.receiveShadow = true;
wheelGroup.add(spoke);
}
const hub = new THREE.Mesh(
new THREE.CylinderGeometry(0.39, 0.39, 0.62, 36),
brassMaterial
);
hub.rotation.x = Math.PI / 2;
hub.castShadow = true;
wheelGroup.add(hub);
const hubInset = new THREE.Mesh(
new THREE.CylinderGeometry(0.21, 0.21, 0.67, 32),
blackSteelMaterial
);
hubInset.rotation.x = Math.PI / 2;
hubInset.castShadow = true;
wheelGroup.add(hubInset);
// Fine outline around the tooth tips.
const outlinePoints = profileVertices.map(
(vertex) => new THREE.Vector3(vertex.x, vertex.y, 0.275)
);
outlinePoints.push(outlinePoints[0].clone());
const toothOutline = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(outlinePoints),
new THREE.LineBasicMaterial({
color: 0xffe2a0,
transparent: true,
opacity: 0.38
})
);
wheelGroup.add(toothOutline);
// -------------------------------------------------------------------------
// Pawl mount
// -------------------------------------------------------------------------
const PAWL_ANGLE = 4 * TOOTH_PITCH; // 72 degrees: starts exactly at a root.
const pawlAnchor = new THREE.Vector3(2.08, 1.94, 0.19);
const pawlSupport = addBox(
housing,
new THREE.Vector3(0.9, 0.48, 0.54),
new THREE.Vector3(2.23, 1.92, -0.18),
blackSteelMaterial
);
pawlSupport.rotation.z = -0.12;
const pivot = new THREE.Mesh(
new THREE.CylinderGeometry(0.16, 0.16, 0.7, 28),
steelMaterial
);
pivot.rotation.x = Math.PI / 2;
pivot.position.copy(pawlAnchor);
pivot.castShadow = true;
housing.add(pivot);
const pivotCap = new THREE.Mesh(
new THREE.CylinderGeometry(0.085, 0.085, 0.75, 24),
brassDarkMaterial
);
pivotCap.rotation.x = Math.PI / 2;
pivotCap.position.copy(pawlAnchor);
pivotCap.position.z += 0.03;
housing.add(pivotCap);
// -------------------------------------------------------------------------
// Dynamic compliant pawl
// -------------------------------------------------------------------------
const pawlMaterial = new THREE.MeshStandardMaterial({
color: 0xa9c8d6,
roughness: 0.27,
metalness: 0.92,
emissive: 0x061a20,
emissiveIntensity: 0.25,
side: THREE.DoubleSide
});
const PAWL_SEGMENTS = 16;
const pawlPositions = new Float32Array(
(PAWL_SEGMENTS + 1) * 4 * 3
);
const pawlIndices = [];
for (let i = 0; i < PAWL_SEGMENTS; i++) {
const a = i * 4;
const b = a + 1;
const c = a + 4;
const d = a + 5;
const e = a + 2;
const f = a + 3;
const g = c + 2;
const h = d + 3;
pawlIndices.push(
a, b, c,
b, d, c,
e, g, f,
f, g, h,
a, e, c,
e, g, c,
b, f, d,
f, h, d
);
}
const end = PAWL_SEGMENTS * 4;
pawlIndices.push(
0, 1, 2,
1, 3, 2,
end, end + 2, end + 1,
end + 1, end + 2, end + 3
);
const pawlGeometry = new THREE.BufferGeometry();
pawlGeometry.setAttribute(
"position",
new THREE.BufferAttribute(pawlPositions, 3)
);
pawlGeometry.setIndex(pawlIndices);
pawlGeometry.computeVertexNormals();
const pawlMesh = new THREE.Mesh(pawlGeometry, pawlMaterial);
pawlMesh.castShadow = true;
pawlMesh.receiveShadow = true;
pawlMesh.frustumCulled = false;
scene.add(pawlMesh);
const pawlToe = new THREE.Mesh(
new THREE.SphereGeometry(0.105, 20, 14),
pawlMaterial
);
pawlToe.castShadow = true;
scene.add(pawlToe);
// Visible contact marker.
const contactMaterial = new THREE.MeshStandardMaterial({
color: 0x7ef2ff,
roughness: 0.22,
metalness: 0.28,
emissive: 0x2bd8ff,
emissiveIntensity: 2.1
});
const contactMarker = new THREE.Mesh(
new THREE.SphereGeometry(0.075, 20, 14),
contactMaterial
);
scene.add(contactMarker);
const contactLight = new THREE.PointLight(0x36dcff, 1.5, 2.4, 2);
scene.add(contactLight);
const clickRingMaterial = new THREE.MeshBasicMaterial({
color: 0xffca69,
transparent: true,
opacity: 0,
side: THREE.DoubleSide,
depthWrite: false
});
const clickRing = new THREE.Mesh(
new THREE.RingGeometry(0.11, 0.16, 48),
clickRingMaterial
);
clickRing.visible = false;
scene.add(clickRing);
// -------------------------------------------------------------------------
// Direction arrows
// -------------------------------------------------------------------------
function makeArcArrow(radius, startAngle, endAngle, color, z) {
const points = [];
for (let i = 0; i <= 48; i++) {
const t = i / 48;
const angle = THREE.MathUtils.lerp(
startAngle,
endAngle,
t
);
points.push(
new THREE.Vector3(
Math.cos(angle) * radius,
Math.sin(angle) * radius,
z
)
);
}
const curve = new THREE.CatmullRomCurve3(points);
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.85,
roughness: 0.3,
metalness: 0.2,
transparent: true,
opacity: 0.9
});
const group = new THREE.Group();
const tube = new THREE.Mesh(
new THREE.TubeGeometry(curve, 72, 0.025, 8, false),
material
);
group.add(tube);
const cone = new THREE.Mesh(
new THREE.ConeGeometry(0.085, 0.24, 16),
material
);
cone.position.copy(curve.getPoint(1));
const tangent = curve.getTangent(1).normalize();
cone.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
tangent
);
group.add(cone);
group.userData.material = material;
return group;
}
const forwardArrow = makeArcArrow(
0.64,
2.85,
0.55,
0x54e8ff,
0.37
);
scene.add(forwardArrow);
const reverseArrow = makeArcArrow(
2.18,
-2.25,
-0.42,
0xff5147,
0.4
);
reverseArrow.visible = false;
scene.add(reverseArrow);
// -------------------------------------------------------------------------
// Exact contact calculation
//
// Intersect a radial ray with the actual visible tooth polygon.
// This keeps the pawl endpoint on the rendered tooth edge rather than
// merely near an idealized radius function.
// -------------------------------------------------------------------------
function cross2(ax, ay, bx, by) {
return ax * by - ay * bx;
}
function radialPolygonIntersection(localAngle) {
const beta =
((localAngle % (Math.PI * 2)) + Math.PI * 2) %
(Math.PI * 2);
let edgeIndex = 1;
while (
edgeIndex < profileEdges.length &&
profileEdges[edgeIndex].endAngle < beta
) {
edgeIndex++;
}
const edge = profileEdges[
Math.min(edgeIndex - 1, profileEdges.length - 1)
];
const ax = edge.a.x;
const ay = edge.a.y;
const dx = edge.b.x - ax;
const dy = edge.b.y - ay;
const rx = Math.cos(beta);
const ry = Math.sin(beta);
const denominator = cross2(rx, ry, dx, dy);
if (Math.abs(denominator) < 1e-9) {
return {
x: edge.a.x,
y: edge.a.y
};
}
const radius = cross2(ax, ay, dx, dy) / denominator;
const t = -cross2(ax, ay, rx, ry) / cross2(dx, dy, rx, ry);
return {
x: ax + dx * THREE.MathUtils.clamp(t, 0, 1),
y: ay + dy * THREE.MathUtils.clamp(t, 0, 1)
};
}
const contactPoint = new THREE.Vector3();
function updateContactPoint(theta) {
const localPoint = radialPolygonIntersection(
PAWL_ANGLE + theta
);
// The wheel rotates by -theta.
const c = Math.cos(theta);
const s = Math.sin(theta);
contactPoint.set(
localPoint.x * c + localPoint.y * s,
-localPoint.x * s + localPoint.y * c,
0.19
);
}
const pawlCenter = new THREE.Vector3();
const pawlTangent = new THREE.Vector3();
const pawlSide = new THREE.Vector3();
const pawlControl = new THREE.Vector3();
const pawlDirection = new THREE.Vector3();
function updatePawlGeometry(reverseLoad, clickLoad) {
pawlDirection.subVectors(contactPoint, pawlAnchor);
const length = Math.max(pawlDirection.length(), 0.001);
pawlDirection.divideScalar(length);
pawlSide.set(-pawlDirection.y, pawlDirection.x, 0);
pawlCenter.addVectors(pawlAnchor, contactPoint).multiplyScalar(0.5);
const bend =
0.065 +
reverseLoad * 0.31 +
clickLoad * 0.13;
pawlControl
.copy(pawlCenter)
.addScaledVector(pawlSide, bend);
const position = pawlGeometry.attributes.position;
const array = position.array;
for (let i = 0; i <= PAWL_SEGMENTS; i++) {
const t = i / PAWL_SEGMENTS;
const mt = 1 - t;
// Quadratic Bezier centerline.
const px =
mt * mt * pawlAnchor.x +
2 * mt * t * pawlControl.x +
t * t * contactPoint.x;
const py =
mt * mt * pawlAnchor.y +
2 * mt * t * pawlControl.y +
t * t * contactPoint.y;
// Analytic derivative.
const tx =
2 * mt * (pawlControl.x - pawlAnchor.x) +
2 * t * (contactPoint.x - pawlControl.x);
const ty =
2 * mt * (pawlControl.y - pawlAnchor.y) +
2 * t * (contactPoint.y - pawlControl.y);
const tangentLength = Math.max(
Math.hypot(tx, ty),
0.0001
);
const sideX = -ty / tangentLength;
const sideY = tx / tangentLength;
const width = THREE.MathUtils.lerp(0.27, 0.115, t);
const halfWidth = width * 0.5;
const halfThickness = 0.055;
const base = i * 4;
// left top
array[base * 3] = px + sideX * halfWidth;
array[base * 3 + 1] = py + sideY * halfWidth;
array[base * 3 + 2] = 0.19 + halfThickness;
// right top
array[(base + 1) * 3] = px - sideX * halfWidth;
array[(base + 1) * 3 + 1] = py - sideY * halfWidth;
array[(base + 1) * 3 + 2] = 0.19 + halfThickness;
// left bottom
array[(base + 2) * 3] = px + sideX * halfWidth;
array[(base + 2) * 3 + 1] = py + sideY * halfWidth;
array[(base + 2) * 3 + 2] = 0.19 - halfThickness;
// right bottom
array[(base + 3) * 3] = px - sideX * halfWidth;
array[(base + 3) * 3 + 1] = py - sideY * halfWidth;
array[(base + 3) * 3 + 2] = 0.19 - halfThickness;
}
position.needsUpdate = true;
pawlGeometry.computeVertexNormals();
pawlToe.position.copy(contactPoint);
}
// -------------------------------------------------------------------------
// Kinematic state machine
// -------------------------------------------------------------------------
const FORWARD_CYCLE_SECONDS = 0.72;
const DWELL_END = 0.14;
const SNAP_START = 0.82;
let driveMode = "auto";
let autoSegment = "forward";
let autoTimer = 0;
let fwdPhase = 0;
let stepIndex = 0;
let theta = 0;
let reverseElapsed = 0;
let reverseTravel = 0;
let thetaLock = 0;
let thetaCommand = 0;
let clickAge = 10;
let clickLoad = 0;
let reverseLoad = 0;
function clamp01(value) {
return THREE.MathUtils.clamp(value, 0, 1);
}
function smooth01(value) {
const t = clamp01(value);
return t * t * (3 - 2 * t);
}
function computeForwardTheta() {
let toothOffset;
if (fwdPhase < DWELL_END) {
toothOffset = 0;
} else if (fwdPhase < SNAP_START) {
const u = smooth01(
(fwdPhase - DWELL_END) / (SNAP_START - DWELL_END)
);
toothOffset = 0.88 * TOOTH_PITCH * u;
} else {
const u = smooth01(
(fwdPhase - SNAP_START) / (1 - SNAP_START)
);
toothOffset =
(0.88 + 0.12 * u) * TOOTH_PITCH;
}
return stepIndex * TOOTH_PITCH + toothOffset;
}
function triggerClick() {
clickAge = 0;
clickLoad = 1;
clickRing.visible = true;
clickRing.position.copy(contactPoint);
clickRing.position.z += 0.14;
clickRing.scale.setScalar(1);
clickRingMaterial.opacity = 1;
}
function beginReverse() {
thetaLock = theta;
reverseElapsed = 0;
reverseTravel = 0;
thetaCommand = thetaLock;
}
function setMode(mode) {
driveMode = mode;
if (mode === "reverse") {
beginReverse();
}
if (mode === "auto") {
autoSegment = "forward";
autoTimer = 0;
}
updateButtonStates();
}
function updateButtonStates() {
autoButton.classList.toggle("active", driveMode === "auto");
forwardButton.classList.toggle(
"active",
driveMode === "forward"
);
reverseButton.classList.toggle(
"active",
driveMode === "reverse"
);
}
autoButton.addEventListener("click", () => setMode("auto"));
forwardButton.addEventListener("click", () => setMode("forward"));
reverseButton.addEventListener("click", () => {
setMode("reverse");
});
resetButton.addEventListener("click", () => {
fwdPhase = 0;
stepIndex = 0;
theta = 0;
thetaLock = 0;
thetaCommand = 0;
reverseElapsed = 0;
reverseTravel = 0;
clickAge = 10;
clickLoad = 0;
reverseLoad = 0;
autoSegment = "forward";
autoTimer = 0;
});
window.addEventListener("keydown", (event) => {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLTextAreaElement
) {
return;
}
const key = event.key.toLowerCase();
if (key === "f") setMode("forward");
if (key === "r") setMode("reverse");
if (key === "a") setMode("auto");
});
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
const projected = new THREE.Vector3();
const labelPosition = new THREE.Vector3();
function placeWorldLabel(element, worldPosition) {
projected.copy(worldPosition).project(camera);
labelPosition.copy(worldPosition).project(camera);
const x = (labelPosition.x * 0.5 + 0.5) * window.innerWidth;
const y = (-labelPosition.y * 0.5 + 0.5) * window.innerHeight;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
element.style.display =
projected.z > -1 && projected.z < 1 ? "block" : "none";
}
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
// Auto demonstration: forward for a while, then reverse test.
if (driveMode === "auto") {
autoTimer += dt;
if (autoSegment === "forward" && autoTimer > 4.2) {
autoSegment = "reverse";
autoTimer = 0;
beginReverse();
} else if (
autoSegment === "reverse" &&
autoTimer > 1.7
) {
autoSegment = "forward";
autoTimer = 0;
}
}
const isReverse =
driveMode === "reverse" ||
(driveMode === "auto" && autoSegment === "reverse");
if (!isReverse) {
const previousPhase = fwdPhase;
fwdPhase += dt / FORWARD_CYCLE_SECONDS;
let wrapped = false;
if (fwdPhase >= 1) {
fwdPhase -= 1;
stepIndex += 1;
wrapped = true;
}
theta = computeForwardTheta();
if (
!wrapped &&
previousPhase < SNAP_START &&
fwdPhase >= SNAP_START
) {
triggerClick();
}
} else {
reverseElapsed += dt;
reverseTravel = Math.min(
0.065,
0.016 + reverseElapsed * 0.11
);
thetaCommand = thetaLock - reverseTravel;
// Declared reverse constraint:
// q_actual = max(q_lock, q_cmd)
theta = Math.max(thetaLock, thetaCommand);
}
updateContactPoint(theta);
clickAge += dt;
clickLoad *= Math.exp(-dt * 10);
const reverseTarget = isReverse
? smooth01(reverseElapsed / 0.45)
: 0;
reverseLoad +=
(reverseTarget - reverseLoad) *
(1 - Math.exp(-dt * 9));
updatePawlGeometry(reverseLoad, clickLoad);
wheelGroup.rotation.z = -theta;
contactMarker.position.copy(contactPoint);
contactMarker.position.z += 0.105;
contactLight.position.copy(contactMarker.position);
if (isReverse) {
contactMaterial.color.setHex(0xff665a);
contactMaterial.emissive.setHex(0xff1d12);
contactMaterial.emissiveIntensity = 2.6;
contactLight.color.setHex(0xff3327);
contactLight.intensity = 2.4 + Math.sin(performance.now() * 0.018) * 0.35;
pawlMaterial.emissive.setHex(0xff2016);
pawlMaterial.emissiveIntensity = 0.5 + reverseLoad * 1.1;
reverseArrow.visible = true;
reverseArrow.userData.material.opacity =
0.65 + Math.sin(performance.now() * 0.012) * 0.22;
} else {
contactMaterial.color.setHex(0x7ef2ff);
contactMaterial.emissive.setHex(0x2bd8ff);
contactMaterial.emissiveIntensity = 2.1;
contactLight.color.setHex(0x36dcff);
contactLight.intensity = 1.5;
pawlMaterial.emissive.setHex(0x061a20);
pawlMaterial.emissiveIntensity = 0.25;
reverseArrow.visible = false;
}
// Expanding click ring.
if (clickAge < 0.42) {
clickRing.visible = true;
clickRing.scale.setScalar(1 + clickAge * 5.5);
clickRingMaterial.opacity = Math.max(
0,
1 - clickAge / 0.42
);
} else {
clickRing.visible = false;
}
// HUD.
const degrees =
((theta * 180) / Math.PI % 360 + 360) % 360;
const displayMode =
driveMode === "auto"
? `Auto / ${autoSegment}`
: driveMode === "forward"
? "Forward drive"
: "Reverse test";
modeReadout.textContent = displayMode;
stepReadout.textContent =
`${String((stepIndex % TOOTH_COUNT) + 1).padStart(3, "0")} / ` +
`${String(TOOTH_COUNT).padStart(3, "0")}`;
angleReadout.textContent = `${degrees.toFixed(1)}°`;
if (isReverse) {
statusEl.textContent = "REVERSE BLOCKED";
statusEl.dataset.state = "reverse";
contactReadout.textContent = "Steep face / locked";
commandReadout.textContent =
`${((thetaCommand * 180) / Math.PI).toFixed(1)}° requested`;
loadFill.style.width = `${reverseLoad * 100}%`;
} else {
statusEl.dataset.state =
fwdPhase >= SNAP_START ? "click" : "normal";
if (fwdPhase < DWELL_END) {
statusEl.textContent = "FORWARD · PAWL SET";
contactReadout.textContent = "Root / seated";
} else if (fwdPhase < SNAP_START) {
statusEl.textContent = "FORWARD · RAMP";
contactReadout.textContent = "Ramp / advancing";
} else {
statusEl.textContent = "FORWARD · CLICK";
contactReadout.textContent = "Drop / resetting";
}
commandReadout.textContent = "—";
loadFill.style.width = "0%";
}
updateCamera(dt);
placeWorldLabel(
pawlLabel,
pawlAnchor.clone().add(new THREE.Vector3(0.12, 0.33, 0.1))
);
placeWorldLabel(
contactLabel,
contactPoint.clone().add(new THREE.Vector3(0.24, 0.28, 0.1))
);
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(
Math.min(window.devicePixelRatio, 2)
);
renderer.setSize(
window.innerWidth,
window.innerHeight
);
});
updateCamera(1);
animate();
</script>
</body>
</html>
```