Prompt specification
Build or customize the Three.js 3D scene "Nut rotation travel demonstration" 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: Nut rotation travel demonstration
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/nut-rotation-travel-demonstration-x0286
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing nuts and screw threads. Rotate a nut along a fixed rod and mark its displacement after each turn; movement must follow one consistent pitch instead of sliding independently. Low-poly.
Working Three.js Starter (nut-rotation-travel-demonstration-x0286):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pitch-Locked Nut — Three.js</title>
<style>
:root {
color-scheme: dark;
--bg: #0b1119;
--panel: rgba(13, 21, 31, 0.88);
--border: rgba(151, 180, 211, 0.18);
--text: #edf5ff;
--muted: #8fa4ba;
--accent: #ffb44b;
--accent-2: #75d6ff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
canvas {
position: fixed;
inset: 0;
display: block;
touch-action: none;
}
.panel {
position: fixed;
z-index: 10;
top: 22px;
left: 22px;
width: min(350px, calc(100vw - 44px));
padding: 20px;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
user-select: none;
}
.kicker {
margin-bottom: 7px;
color: var(--accent);
font: 700 11px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 25px;
line-height: 1.08;
letter-spacing: -0.035em;
}
.subtitle {
margin: 10px 0 17px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.status {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 14px;
color: var(--accent-2);
font: 700 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 13px currentColor;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.stat {
min-width: 0;
padding: 10px;
border: 1px solid rgba(151, 180, 211, 0.13);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.stat-label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.stat-value {
display: block;
overflow: hidden;
color: var(--text);
font: 700 16px/1.1 ui-monospace, SFMono-Regular, Menlo, monospace;
text-overflow: ellipsis;
white-space: nowrap;
}
.stat-value.accent {
color: var(--accent);
}
.equation {
margin: 13px 0 16px;
padding: 11px 12px;
border-left: 2px solid var(--accent);
border-radius: 2px 8px 8px 2px;
background: rgba(255, 180, 75, 0.06);
color: #d8e4f0;
font: 12px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.equation strong {
color: var(--accent);
}
.controls {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
button {
min-height: 42px;
padding: 10px 12px;
border: 1px solid var(--border);
border-radius: 9px;
background: rgba(255, 255, 255, 0.045);
color: var(--text);
font: 700 12px/1.1 system-ui, sans-serif;
cursor: pointer;
transition:
background 140ms ease,
border-color 140ms ease,
transform 140ms ease;
}
button:hover {
border-color: rgba(255, 180, 75, 0.55);
background: rgba(255, 180, 75, 0.09);
}
button:active {
transform: translateY(1px);
}
button.primary {
border-color: rgba(255, 180, 75, 0.52);
background: var(--accent);
color: #211407;
}
button.primary:hover {
background: #ffc16d;
}
button:disabled {
opacity: 0.38;
cursor: default;
transform: none;
}
.speed {
display: flex;
align-items: center;
gap: 10px;
margin-top: 13px;
color: var(--muted);
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.speed input {
flex: 1;
accent-color: var(--accent);
}
.speed output {
min-width: 46px;
color: var(--text);
text-align: right;
}
.log-panel {
position: fixed;
z-index: 10;
top: 22px;
right: 22px;
width: 220px;
padding: 15px;
border: 1px solid var(--border);
border-radius: 13px;
background: rgba(13, 21, 31, 0.76);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
.log-title {
margin-bottom: 10px;
color: var(--muted);
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.13em;
text-transform: uppercase;
}
#turn-log {
display: grid;
gap: 7px;
}
.log-entry {
display: flex;
justify-content: space-between;
gap: 12px;
padding: 7px 8px;
border-radius: 7px;
background: rgba(255, 180, 75, 0.07);
color: #dce8f3;
font: 11px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.log-entry strong {
color: var(--accent);
}
.hint {
position: fixed;
z-index: 10;
left: 50%;
bottom: 18px;
padding: 9px 13px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(13, 21, 31, 0.7);
color: var(--muted);
font: 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
pointer-events: none;
transform: translateX(-50%);
white-space: nowrap;
}
#loading {
position: fixed;
z-index: 30;
inset: 0;
display: grid;
place-items: center;
background: var(--bg);
color: var(--accent);
font: 700 13px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
text-transform: uppercase;
}
@media (max-width: 760px) {
.panel {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 15px;
}
h1 {
font-size: 21px;
}
.subtitle {
margin-bottom: 12px;
}
.log-panel {
display: none;
}
.hint {
bottom: 12px;
font-size: 9px;
}
}
</style>
</head>
<body>
<div id="loading">Loading Three.js…</div>
<section class="panel" aria-label="Thread motion controls">
<div class="kicker">Kinematic study / 01</div>
<h1>Pitch-locked nut</h1>
<p class="subtitle">
A low-poly nut rotates around a fixed threaded rod. Its axial position is
calculated only from the rotation angle, so it cannot slide independently.
</p>
<div class="status">
<span class="status-dot"></span>
<span id="motion-status">Auto rotation</span>
</div>
<div class="stats">
<div class="stat">
<span class="stat-label">Turns</span>
<span class="stat-value" id="turns-value">0.00</span>
</div>
<div class="stat">
<span class="stat-label">Displacement</span>
<span class="stat-value accent" id="displacement-value">0.00 mm</span>
</div>
<div class="stat">
<span class="stat-label">Angle</span>
<span class="stat-value" id="angle-value">0°</span>
</div>
</div>
<div class="equation">
<strong>x = x₀ + (θ / 2π) × pitch</strong><br>
Constant pitch: <strong>4.00 mm / revolution</strong>
</div>
<div class="controls">
<button class="primary" id="turn-button">Rotate +360°</button>
<button id="auto-button">Pause rotation</button>
<button id="reset-button">Reset</button>
<button id="view-button">Side view</button>
</div>
<label class="speed">
Speed
<input
id="speed-input"
type="range"
min="0.45"
max="2.20"
step="0.05"
value="1.05"
>
<output id="speed-output">1.05×</output>
</label>
</section>
<aside class="log-panel" aria-label="Completed turn log">
<div class="log-title">Completed turns</div>
<div id="turn-log">
<div class="log-entry" style="opacity: 0.55">
<span>Waiting</span><strong>0.00 mm</strong>
</div>
</div>
</aside>
<div class="hint">Drag to orbit · wheel or pinch to zoom</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants
// -------------------------------------------------------------------------
const TAU = Math.PI * 2;
const PITCH_MM = 4.0;
const PITCH_WORLD = 0.9;
const START_X = -4.2;
const MAX_TURNS = 12;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b1119);
scene.fog = new THREE.Fog(0x0b1119, 18, 38);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
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.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.prepend(renderer.domElement);
document.getElementById("loading").remove();
// -------------------------------------------------------------------------
// Lighting and low-poly environment
// -------------------------------------------------------------------------
const hemisphere = new THREE.HemisphereLight(0xc9ddff, 0x17131a, 1.8);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(2, 9, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -13;
keyLight.shadow.camera.right = 13;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0xff9f43, 22, 15, 2);
rimLight.position.set(-3, 2, -5);
scene.add(rimLight);
const coolLight = new THREE.PointLight(0x56c8ff, 16, 14, 2);
coolLight.position.set(5, 1, 5);
scene.add(coolLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(32, 22),
new THREE.MeshStandardMaterial({
color: 0x0e1722,
roughness: 0.92,
metalness: 0.08
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -2.2;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(28, 28, 0x40516a, 0x203043);
grid.position.y = -2.18;
grid.material.transparent = true;
grid.material.opacity = 0.45;
scene.add(grid);
// -------------------------------------------------------------------------
// Materials
// -------------------------------------------------------------------------
const rodMaterial = new THREE.MeshStandardMaterial({
color: 0x82909f,
metalness: 0.88,
roughness: 0.28,
flatShading: true
});
const threadMaterial = new THREE.MeshStandardMaterial({
color: 0xd2dbe5,
metalness: 0.82,
roughness: 0.24,
flatShading: true
});
const nutMaterial = new THREE.MeshStandardMaterial({
color: 0xe99b2f,
metalness: 0.68,
roughness: 0.3,
flatShading: true
});
const darkMetal = new THREE.MeshStandardMaterial({
color: 0x263343,
metalness: 0.72,
roughness: 0.46,
flatShading: true
});
const orangeMaterial = new THREE.MeshStandardMaterial({
color: 0xffc052,
emissive: 0x7a3100,
emissiveIntensity: 0.35,
roughness: 0.4,
metalness: 0.25,
flatShading: true
});
// -------------------------------------------------------------------------
// Fixed rod and constant-pitch thread
// -------------------------------------------------------------------------
const rodLength = 18.4;
const rod = new THREE.Mesh(
new THREE.CylinderGeometry(0.19, 0.19, rodLength, 12, 1, false),
rodMaterial
);
rod.rotation.z = Math.PI / 2;
rod.castShadow = true;
rod.receiveShadow = true;
scene.add(rod);
class HelixCurve extends THREE.Curve {
constructor(length, pitch, radius) {
super();
this.length = length;
this.pitch = pitch;
this.radius = radius;
}
getPoint(t, target = new THREE.Vector3()) {
const x = -this.length / 2 + t * this.length;
const phase = ((x + this.length / 2) / this.pitch) * TAU;
return target.set(
x,
Math.cos(phase) * this.radius,
Math.sin(phase) * this.radius
);
}
}
const helix = new HelixCurve(18.0, PITCH_WORLD, 0.215);
const threadTurns = 18.0 / PITCH_WORLD;
const thread = new THREE.Mesh(
new THREE.TubeGeometry(
helix,
Math.ceil(threadTurns * 18),
0.055,
5,
false
),
threadMaterial
);
thread.castShadow = true;
scene.add(thread);
// Bearing collars and pedestals visually establish that the rod is fixed.
for (const x of [-8.55, 8.55]) {
const bearing = new THREE.Mesh(
new THREE.TorusGeometry(0.39, 0.12, 6, 12),
darkMetal
);
bearing.rotation.y = Math.PI / 2;
bearing.position.x = x;
bearing.castShadow = true;
scene.add(bearing);
const pedestal = new THREE.Mesh(
new THREE.BoxGeometry(0.72, 1.55, 0.78),
darkMetal
);
pedestal.position.set(x, -1.38, 0);
pedestal.castShadow = true;
pedestal.receiveShadow = true;
scene.add(pedestal);
}
// -------------------------------------------------------------------------
// Low-poly hexagonal nut
// -------------------------------------------------------------------------
const nutShape = new THREE.Shape();
const outerRadius = 0.78;
const holeRadius = 0.285;
for (let i = 0; i < 6; i++) {
const a = Math.PI / 6 + (i / 6) * TAU;
const x = Math.cos(a) * outerRadius;
const y = Math.sin(a) * outerRadius;
if (i === 0) {
nutShape.moveTo(x, y);
} else {
nutShape.lineTo(x, y);
}
}
nutShape.closePath();
const nutHole = new THREE.Path();
nutHole.absarc(0, 0, holeRadius, 0, TAU, true);
nutShape.holes.push(nutHole);
const nutDepth = 0.72;
const nutGeometry = new THREE.ExtrudeGeometry(nutShape, {
depth: nutDepth,
steps: 1,
curveSegments: 12,
bevelEnabled: true,
bevelSegments: 1,
bevelSize: 0.055,
bevelThickness: 0.055
});
// Center the extrusion and align its bore with the rod's X axis.
nutGeometry.translate(0, 0, -nutDepth / 2);
nutGeometry.rotateY(Math.PI / 2);
const nutRotor = new THREE.Group();
nutRotor.position.set(START_X, 0, 0);
const nutMesh = new THREE.Mesh(nutGeometry, nutMaterial);
nutMesh.castShadow = true;
nutMesh.receiveShadow = true;
nutRotor.add(nutMesh);
const nutEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(nutGeometry, 28),
new THREE.LineBasicMaterial({
color: 0x70400e,
transparent: true,
opacity: 0.65
})
);
nutRotor.add(nutEdges);
// A contrasting witness mark makes the rotation visible despite the
// hexagonal nut's 60-degree symmetry.
const witnessMark = new THREE.Mesh(
new THREE.BoxGeometry(0.09, 0.25, 0.13),
orangeMaterial
);
witnessMark.position.set(0.41, 0.45, 0);
witnessMark.castShadow = true;
nutRotor.add(witnessMark);
scene.add(nutRotor);
// -------------------------------------------------------------------------
// Ruler and baseline
// -------------------------------------------------------------------------
const rulerZ = 0.62;
const rulerY = -1.48;
const rulerEndX = START_X + MAX_TURNS * PITCH_WORLD;
const rulerPoints = [
new THREE.Vector3(START_X, rulerY, rulerZ),
new THREE.Vector3(rulerEndX, rulerY, rulerZ)
];
for (let i = 0; i <= MAX_TURNS; i++) {
const x = START_X + i * PITCH_WORLD;
rulerPoints.push(
new THREE.Vector3(x, rulerY, rulerZ),
new THREE.Vector3(x, rulerY + 0.22, rulerZ)
);
}
const ruler = new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(rulerPoints),
new THREE.LineBasicMaterial({
color: 0x667b93,
transparent: true,
opacity: 0.75
})
);
scene.add(ruler);
function makeTextSprite(text, accent = "#ffbd62") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(8, 14, 22, 0.84)";
ctx.fillRect(0, 18, 512, 92);
ctx.strokeStyle = accent;
ctx.lineWidth = 3;
ctx.strokeRect(2, 20, 508, 88);
ctx.fillStyle = accent;
ctx.font = "700 35px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 65, 475);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 20;
sprite.userData.texture = texture;
return sprite;
}
const baselineLabel = makeTextSprite("START · 0 mm", "#8fa4ba");
baselineLabel.position.set(START_X, -1.77, 0.92);
baselineLabel.scale.set(1.45, 0.36, 1);
scene.add(baselineLabel);
const turnMarkerGroup = new THREE.Group();
scene.add(turnMarkerGroup);
// -------------------------------------------------------------------------
// Motion state
//
// Important: the nut's X position is never independently animated.
// It is always derived from the current rotation angle:
//
// x = START_X + (angle / 2π) * PITCH_WORLD
//
// This enforces a single constant pitch for every motion mode.
// -------------------------------------------------------------------------
let angle = 0;
let speed = 1.05;
let autoRotate = true;
let manualTurn = null;
let lastMarkedTurn = 0;
const turnButton = document.getElementById("turn-button");
const autoButton = document.getElementById("auto-button");
const resetButton = document.getElementById("reset-button");
const viewButton = document.getElementById("view-button");
const speedInput = document.getElementById("speed-input");
const speedOutput = document.getElementById("speed-output");
const turnsValue = document.getElementById("turns-value");
const displacementValue = document.getElementById("displacement-value");
const angleValue = document.getElementById("angle-value");
const motionStatus = document.getElementById("motion-status");
const turnLog = document.getElementById("turn-log");
function addTurnMarker(turn) {
const x = START_X + turn * PITCH_WORLD;
const displacement = turn * PITCH_MM;
const markerMaterial = new THREE.LineBasicMaterial({
color: 0xffb44b,
transparent: true,
opacity: 0.95,
depthTest: false,
depthWrite: false
});
const line = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(x, rulerY, 0.94),
new THREE.Vector3(x, -0.43, 0.94)
]),
markerMaterial
);
line.renderOrder = 18;
turnMarkerGroup.add(line);
const node = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.09, 0),
orangeMaterial
);
node.position.set(x, -0.43, 0.94);
node.renderOrder = 19;
turnMarkerGroup.add(node);
const label = makeTextSprite(
`TURN ${String(turn).padStart(2, "0")} · +${displacement.toFixed(0)} mm`,
"#ffd08a"
);
label.position.set(x, turn % 2 === 0 ? -1.68 : -2.02, 0.95);
label.scale.set(1.62, 0.4, 1);
turnMarkerGroup.add(label);
const logEntry = document.createElement("div");
logEntry.className = "log-entry";
const name = document.createElement("span");
name.textContent = `Turn ${turn}`;
const amount = document.createElement("strong");
amount.textContent = `+${displacement.toFixed(2)} mm`;
logEntry.append(name, amount);
const waiting = turnLog.querySelector(".log-entry[style]");
if (waiting) {
waiting.remove();
}
turnLog.prepend(logEntry);
while (turnLog.children.length > 6) {
turnLog.lastElementChild.remove();
}
}
function syncTurnMarkers() {
const completedTurn = Math.floor((angle + 1e-7) / TAU);
while (lastMarkedTurn < completedTurn) {
lastMarkedTurn++;
addTurnMarker(lastMarkedTurn);
}
}
function clearTurnMarkers() {
for (const child of [...turnMarkerGroup.children]) {
turnMarkerGroup.remove(child);
if (child.geometry) {
child.geometry.dispose();
}
if (child.material) {
if (child.material.map) {
child.material.map.dispose();
}
child.material.dispose();
}
}
turnLog.innerHTML = `
<div class="log-entry" style="opacity: 0.55">
<span>Waiting</span><strong>0.00 mm</strong>
</div>
`;
}
function resetScene() {
angle = 0;
manualTurn = null;
autoRotate = false;
lastMarkedTurn = 0;
clearTurnMarkers();
applyNutTransform();
updateHUD();
}
function rotateOneTurn() {
autoRotate = false;
manualTurn = null;
const target = Math.min(angle + TAU, MAX_TURNS * TAU);
manualTurn = {
from: angle,
to: target,
elapsed: 0,
duration: 1.8
};
updateHUD();
}
function toggleAuto() {
manualTurn = null;
if (angle >= MAX_TURNS * TAU - 1e-6) {
resetScene();
}
autoRotate = !autoRotate;
updateHUD();
}
function applyNutTransform() {
nutRotor.rotation.x = angle;
// The nut's position is a pure function of rotation.
// There is no independent position tween.
nutRotor.position.x =
START_X + (nutRotor.rotation.x / TAU) * PITCH_WORLD;
}
function updateHUD() {
const turns = angle / TAU;
const displacementMM = turns * PITCH_MM;
const degrees = angle * 180 / Math.PI;
turnsValue.textContent = turns.toFixed(2);
displacementValue.textContent = `${displacementMM.toFixed(2)} mm`;
angleValue.textContent = `${degrees.toFixed(0)}°`;
const atEnd = angle >= MAX_TURNS * TAU - 1e-6;
turnButton.disabled = atEnd;
if (manualTurn) {
motionStatus.textContent = "Turning 360°";
} else if (autoRotate) {
motionStatus.textContent = "Auto rotation";
} else if (atEnd) {
motionStatus.textContent = "Travel limit";
} else {
motionStatus.textContent = "Paused";
}
autoButton.textContent = autoRotate ? "Pause rotation" : "Auto rotate";
}
turnButton.addEventListener("click", rotateOneTurn);
autoButton.addEventListener("click", toggleAuto);
resetButton.addEventListener("click", resetScene);
speedInput.addEventListener("input", () => {
speed = Number(speedInput.value);
speedOutput.textContent = `${speed.toFixed(2)}×`;
});
// -------------------------------------------------------------------------
// Custom camera controls: no examples/addons are imported.
// -------------------------------------------------------------------------
const orbit = {
yaw: 0.36,
pitch: 0.34,
radius: window.innerWidth < 760 ? 38 : 20,
target: new THREE.Vector3(0.4, -0.15, 0)
};
let dragging = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
orbit.yaw -= dx * 0.006;
orbit.pitch = THREE.MathUtils.clamp(
orbit.pitch + dy * 0.004,
-0.08,
1.08
);
});
function endDrag(event) {
dragging = false;
if (
event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
10,
48
);
},
{ passive: false }
);
// Trackpad pinch gestures arrive as wheel events in most browsers.
// Basic two-finger pinch support is included for pointer events.
const activePointers = new Map();
let pinchDistance = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
activePointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!activePointers.has(event.pointerId)) return;
activePointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (activePointers.size === 2) {
const [a, b] = [...activePointers.values()];
const distance = Math.hypot(a.x - b.x, a.y - b.y);
if (pinchDistance > 0) {
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * (pinchDistance / Math.max(distance, 1)),
10,
48
);
}
pinchDistance = distance;
}
});
function removePointer(event) {
activePointers.delete(event.pointerId);
if (activePointers.size < 2) pinchDistance = 0;
}
renderer.domElement.addEventListener("pointerup", removePointer);
renderer.domElement.addEventListener("pointercancel", removePointer);
viewButton.addEventListener("click", () => {
orbit.yaw = 0.02;
orbit.pitch = 0.08;
orbit.radius = window.innerWidth < 760 ? 38 : 20;
orbit.target.set(0.4, -0.15, 0);
});
function updateCamera() {
const horizontalRadius =
orbit.radius * Math.cos(orbit.pitch);
camera.position.set(
orbit.target.x + horizontalRadius * Math.sin(orbit.yaw),
orbit.target.y + orbit.radius * Math.sin(orbit.pitch),
orbit.target.z + horizontalRadius * Math.cos(orbit.yaw)
);
camera.lookAt(orbit.target);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
const dt = Math.min(clock.getDelta(), 0.05);
if (manualTurn) {
manualTurn.elapsed += dt;
const t = Math.min(
manualTurn.elapsed / manualTurn.duration,
1
);
const eased =
t < 0.5
? 4 * t * t * t
: 1 - Math.pow(-2 * t + 2, 3) / 2;
angle = THREE.MathUtils.lerp(
manualTurn.from,
manualTurn.to,
eased
);
if (t >= 1) {
angle = manualTurn.to;
manualTurn = null;
}
} else if (autoRotate) {
angle += dt * speed;
if (angle >= MAX_TURNS * TAU) {
angle = MAX_TURNS * TAU;
autoRotate = false;
}
}
applyNutTransform();
syncTurnMarkers();
updateHUD();
updateCamera();
renderer.render(scene, camera);
}
applyNutTransform();
updateHUD();
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```