Prompt specification
Build or customize the Three.js 3D scene "Clothespin cargo crane puzzle" 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: Clothespin cargo crane puzzle
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/clothespin-cargo-crane-puzzle-x0004
Scene Description Prompt:
Create a standalone low-poly scene in one HTML file using Three.js from cdnjs. Construct a tabletop crane that uses an oversized clothespin gripper; users open and close its jaws to transfer blocks between marked docks without teleporting them.
Working Three.js Starter (clothespin-cargo-crane-puzzle-x0004):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Clampworks — Tabletop Crane</title>
<style>
:root {
--ink: #17323a;
--muted: #60777d;
--panel: rgba(250, 252, 248, 0.94);
--line: rgba(23, 50, 58, 0.13);
--accent: #ef6a5b;
--green: #2d806c;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce6e6;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#stage {
position: fixed;
inset: 0;
}
canvas {
display: block;
touch-action: none;
outline: none;
}
.panel {
position: fixed;
z-index: 10;
background: var(--panel);
border: 1px solid rgba(255, 255, 255, 0.74);
box-shadow: 0 18px 50px rgba(32, 59, 62, 0.17);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
#titleCard {
top: 18px;
left: 18px;
width: 280px;
padding: 17px 18px 15px;
border-radius: 17px;
}
.eyebrow {
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 4px 0 3px;
font-size: 25px;
line-height: 1.05;
letter-spacing: -0.045em;
}
.subtitle {
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
#controls {
left: 18px;
bottom: 18px;
width: 280px;
padding: 15px;
border-radius: 18px;
}
.control-section + .control-section {
margin-top: 14px;
padding-top: 14px;
border-top: 1px solid var(--line);
}
.row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.label {
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.value {
color: var(--muted);
font-size: 11px;
font-variant-numeric: tabular-nums;
}
#gripButton {
width: 100%;
min-height: 48px;
margin-top: 9px;
border: 0;
border-radius: 12px;
background: var(--accent);
color: white;
font: inherit;
font-size: 12px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
box-shadow: 0 7px 16px rgba(239, 106, 91, 0.25);
transition: transform 120ms ease, background 120ms ease, box-shadow 120ms ease;
}
#gripButton:hover { transform: translateY(-1px); }
#gripButton:active { transform: translateY(1px); }
#gripButton.open {
background: var(--green);
box-shadow: 0 7px 16px rgba(45, 128, 108, 0.22);
}
#dockButtons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 7px;
margin-top: 10px;
}
#dockButtons button {
height: 38px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.75);
color: var(--ink);
font: inherit;
font-size: 12px;
font-weight: 800;
cursor: pointer;
transition: 150ms ease;
}
#dockButtons button:hover {
transform: translateY(-1px);
background: white;
}
#dockButtons button.selected {
color: white;
border-color: transparent;
background: var(--dock-color);
box-shadow: 0 5px 12px color-mix(in srgb, var(--dock-color) 32%, transparent);
}
input[type="range"] {
width: 100%;
margin: 11px 0 3px;
accent-color: var(--green);
cursor: ns-resize;
}
#status {
margin-top: 12px;
padding: 10px 11px;
border-radius: 11px;
background: rgba(23, 50, 58, 0.06);
font-size: 12px;
font-weight: 700;
line-height: 1.35;
}
#status.holding {
color: #17634f;
background: rgba(45, 128, 108, 0.12);
}
.steps {
margin: 9px 0 0;
padding-left: 18px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
#cameraHelp {
right: 18px;
bottom: 18px;
max-width: 330px;
padding: 11px 14px;
border-radius: 13px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
#cameraHelp strong {
color: var(--ink);
}
#toast {
position: fixed;
z-index: 30;
top: 22px;
left: 50%;
max-width: min(460px, calc(100vw - 40px));
padding: 11px 16px;
border-radius: 999px;
background: rgba(23, 50, 58, 0.91);
color: white;
font-size: 12px;
font-weight: 700;
text-align: center;
pointer-events: none;
opacity: 0;
transform: translate(-50%, -12px);
transition: opacity 180ms ease, transform 180ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 720px) {
#titleCard {
top: 10px;
left: 10px;
width: calc(100% - 20px);
padding: 12px 14px;
}
h1 { font-size: 21px; }
.subtitle { display: none; }
#controls {
left: 10px;
bottom: 10px;
width: calc(100% - 20px);
padding: 12px;
}
.steps, #cameraHelp { display: none; }
}
</style>
</head>
<body>
<div id="stage"></div>
<section id="titleCard" class="panel">
<div class="eyebrow">Tabletop logistics / 01</div>
<h1>Clampworks</h1>
<div class="subtitle">
Drive the gantry, lower the oversized clothespin, and carry blocks between docks.
Every load moves continuously under spring force—nothing snaps into place.
</div>
</section>
<section id="controls" class="panel">
<div class="control-section">
<div class="row">
<span class="label">Gripper</span>
<span class="value" id="gripState">OPEN</span>
</div>
<button id="gripButton" type="button">Close jaws</button>
</div>
<div class="control-section">
<div class="row">
<span class="label">Travel to dock</span>
<span class="value">CLICK A MARKER</span>
</div>
<div id="dockButtons"></div>
</div>
<div class="control-section">
<div class="row">
<span class="label">Hoist height</span>
<span class="value" id="hoistValue">3.2 m</span>
</div>
<input id="hoist" type="range" min="1.25" max="5.1" step="0.01" value="3.2" />
</div>
<div id="status">Ready at Dock A. Lower the gripper to pick up a block.</div>
<ol class="steps">
<li>Choose a dock and lower the gripper.</li>
<li>Close the jaws around the block.</li>
<li>Raise, travel, lower, then open to release.</li>
</ol>
</section>
<div id="cameraHelp" class="panel">
<strong>Camera:</strong> drag to orbit · right-drag or Shift-drag to pan ·
wheel to zoom · click a dock to travel · click the jaws to toggle them.<br />
<strong>Keys:</strong> Space = jaws · arrows = travel · R/F = raise/lower.
</div>
<div id="toast"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const stage = document.getElementById("stage");
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.domElement.setAttribute("aria-label", "Interactive tabletop crane scene");
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce6e6);
scene.fog = new THREE.Fog(0xdce6e6, 30, 62);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
scene.add(new THREE.HemisphereLight(0xf5fbff, 0x8b735d, 2.2));
const sun = new THREE.DirectionalLight(0xfff3dc, 3.2);
sun.position.set(9, 16, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -14;
sun.shadow.camera.right = 14;
sun.shadow.camera.top = 14;
sun.shadow.camera.bottom = -14;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 38;
sun.shadow.bias = -0.0003;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb9d9ef, 0.8);
fill.position.set(-10, 7, -9);
scene.add(fill);
const materials = {
steel: new THREE.MeshStandardMaterial({
color: 0x245963, roughness: 0.68, metalness: 0.22, flatShading: true
}),
darkSteel: new THREE.MeshStandardMaterial({
color: 0x17343b, roughness: 0.58, metalness: 0.28, flatShading: true
}),
paleSteel: new THREE.MeshStandardMaterial({
color: 0xd6e2df, roughness: 0.74, metalness: 0.12, flatShading: true
}),
yellow: new THREE.MeshStandardMaterial({
color: 0xf3b83e, roughness: 0.76, flatShading: true
}),
wood: new THREE.MeshStandardMaterial({
color: 0xc98145, roughness: 0.9, flatShading: true
}),
woodLight: new THREE.MeshStandardMaterial({
color: 0xe0a45d, roughness: 0.88, flatShading: true
}),
rubber: new THREE.MeshStandardMaterial({
color: 0x26363a, roughness: 0.96, flatShading: true
}),
tableEdge: new THREE.MeshStandardMaterial({
color: 0x75543c, roughness: 0.95, flatShading: true
})
};
function makeBox(w, h, d, material, x, y, z, parent = scene) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeCylinder(radius, height, material, x, y, z, parent = scene, segments = 10) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, height, segments),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function damp(a, b, lambda, dt) {
return a + (b - a) * (1 - Math.exp(-lambda * dt));
}
// -------------------------------------------------------------------------
// Table and surrounding floor
// -------------------------------------------------------------------------
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(90, 90),
new THREE.MeshStandardMaterial({ color: 0xcbd6d3, roughness: 1 })
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -2.35;
floor.receiveShadow = true;
scene.add(floor);
makeBox(17.8, 0.35, 13.2, materials.tableEdge, 0, -0.43, 0);
const plankColors = [0xcfa878, 0xd8b184, 0xc99b6a, 0xd5ad7d];
for (let i = 0; i < 8; i++) {
const plankMaterial = new THREE.MeshStandardMaterial({
color: plankColors[i % plankColors.length],
roughness: 0.94,
flatShading: true
});
makeBox(17.35, 0.38, 1.54, plankMaterial, 0, -0.19, -5.63 + i * 1.61);
}
for (const x of [-7.4, 7.4]) {
for (const z of [-5.0, 5.0]) {
makeBox(0.8, 1.75, 0.8, materials.tableEdge, x, -1.28, z);
makeBox(1.0, 0.16, 1.0, materials.darkSteel, x, -2.18, z);
}
}
// -------------------------------------------------------------------------
// Gantry crane
// -------------------------------------------------------------------------
const CRANE_X = 7.15;
const CRANE_Z = 4.75;
for (const x of [-CRANE_X, CRANE_X]) {
for (const z of [-CRANE_Z, CRANE_Z]) {
makeBox(1.05, 0.22, 1.05, materials.darkSteel, x, 0.11, z);
makeBox(0.42, 6.15, 0.42, materials.steel, x, 3.18, z);
makeBox(0.74, 0.16, 0.74, materials.yellow, x, 0.29, z);
}
// Long rails let the bridge travel along Z.
makeBox(0.38, 0.38, 10.15, materials.steel, x, 6.48, 0);
makeBox(0.13, 0.08, 10.05, materials.yellow, x - Math.sign(x) * 0.23, 6.69, 0);
}
const bridge = new THREE.Group();
scene.add(bridge);
makeBox(14.95, 0.48, 0.56, materials.steel, 0, 6.48, 0, bridge);
makeBox(14.25, 0.10, 0.12, materials.yellow, 0, 6.76, 0, bridge);
for (const x of [-CRANE_X, CRANE_X]) {
makeBox(0.72, 0.70, 0.82, materials.darkSteel, x, 6.40, 0, bridge);
makeBox(0.38, 0.22, 0.88, materials.yellow, x, 6.80, 0, bridge);
}
const trolley = new THREE.Group();
bridge.add(trolley);
makeBox(1.12, 0.55, 0.86, materials.darkSteel, 0, 6.06, 0, trolley);
makeBox(0.66, 0.28, 0.62, materials.yellow, 0, 5.70, 0, trolley);
const pulley = makeCylinder(0.20, 0.16, materials.rubber, 0, 5.55, 0, trolley, 12);
pulley.rotation.x = Math.PI / 2;
// Oversized clothespin gripper.
const jawRoot = new THREE.Group();
scene.add(jawRoot);
makeBox(1.32, 0.38, 0.54, materials.woodLight, 0, 0.40, 0, jawRoot);
makeBox(0.56, 0.25, 0.62, materials.darkSteel, 0, 0.49, 0, jawRoot);
const pivotPin = makeCylinder(0.12, 1.32, materials.darkSteel, 0, 0.35, 0, jawRoot, 12);
pivotPin.rotation.x = Math.PI / 2;
for (let i = 0; i < 6; i++) {
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.18, 0.035, 6, 14),
materials.yellow
);
ring.position.set(0, 0.35, -0.18 + i * 0.072);
ring.castShadow = true;
jawRoot.add(ring);
}
const jawPickables = [];
function makeJaw(side) {
const pivot = new THREE.Group();
pivot.position.set(side * 0.5, 0.35, 0);
jawRoot.add(pivot);
const arm = makeBox(
0.34, 1.55, 0.49,
side < 0 ? materials.wood : materials.woodLight,
0, -0.74, 0,
pivot
);
const pad = makeBox(
0.18, 0.38, 0.55,
materials.rubber,
0, -1.39, 0,
pivot
);
arm.userData.action = "toggle-grip";
pad.userData.action = "toggle-grip";
jawPickables.push(arm, pad);
return pivot;
}
const leftJaw = makeJaw(-1);
const rightJaw = makeJaw(1);
const cable = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 0.035, 1, 8),
materials.darkSteel
);
cable.castShadow = true;
scene.add(cable);
const upVector = new THREE.Vector3(0, 1, 0);
const cableDirection = new THREE.Vector3();
const cableMidpoint = new THREE.Vector3();
function placeCable(start, end) {
cableDirection.subVectors(end, start);
const length = cableDirection.length();
cableMidpoint.addVectors(start, end).multiplyScalar(0.5);
cable.position.copy(cableMidpoint);
cable.scale.set(1, length, 1);
cable.quaternion.setFromUnitVectors(upVector, cableDirection.normalize());
}
// -------------------------------------------------------------------------
// Dock markers and labels
// -------------------------------------------------------------------------
function makeTextSprite(text, accent = "#2d806c") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 160;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(250,252,248,0.95)";
ctx.fillRect(8, 8, 496, 144);
ctx.fillStyle = accent;
ctx.fillRect(8, 8, 24, 144);
ctx.strokeStyle = "rgba(23,50,58,0.15)";
ctx.lineWidth = 5;
ctx.strokeRect(8, 8, 496, 144);
ctx.fillStyle = "#17323a";
ctx.font = "800 66px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 268, 82);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
})
);
sprite.scale.set(1.45, 0.45, 1);
return sprite;
}
const docks = [];
const dockHitMeshes = [];
const dockDefinitions = [
{ id: "A", x: -4.4, z: -2.55, color: 0xef6a5b, css: "#ef6a5b" },
{ id: "B", x: 4.4, z: -2.55, color: 0xf2b83f, css: "#f2b83f" },
{ id: "C", x: 4.4, z: 2.55, color: 0x4b8fe8, css: "#4b8fe8" },
{ id: "D", x: -4.4, z: 2.55, color: 0x58b98a, css: "#58b98a" }
];
function createDock(def, index) {
const group = new THREE.Group();
group.position.set(def.x, 0, def.z);
scene.add(group);
const baseMaterial = new THREE.MeshStandardMaterial({
color: def.color,
emissive: def.color,
emissiveIntensity: 0.08,
roughness: 0.82,
transparent: true,
opacity: 0.33,
depthWrite: false
});
const base = new THREE.Mesh(new THREE.CircleGeometry(1.08, 32), baseMaterial);
base.rotation.x = -Math.PI / 2;
base.position.y = 0.018;
base.receiveShadow = true;
group.add(base);
const ringMaterial = new THREE.MeshBasicMaterial({
color: def.color,
transparent: true,
opacity: 0.85,
side: THREE.DoubleSide,
depthWrite: false
});
const ring = new THREE.Mesh(new THREE.RingGeometry(0.86, 1.04, 32), ringMaterial);
ring.rotation.x = -Math.PI / 2;
ring.position.y = 0.027;
group.add(ring);
for (let i = 0; i < 4; i++) {
const angle = i * Math.PI / 2;
const tick = makeBox(
0.28, 0.035, 0.08,
new THREE.MeshBasicMaterial({ color: def.color }),
Math.sin(angle) * 1.20,
0.04,
Math.cos(angle) * 1.20,
group
);
tick.rotation.y = angle;
}
const label = makeTextSprite(`DOCK ${def.id}`, def.css);
label.position.set(0, 0.24, 1.37);
group.add(label);
const hit = new THREE.Mesh(
new THREE.CircleGeometry(1.32, 32),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
side: THREE.DoubleSide
})
);
hit.rotation.x = -Math.PI / 2;
hit.position.y = 0.04;
hit.userData.dockIndex = index;
group.add(hit);
dockHitMeshes.push(hit);
docks.push({
...def,
group,
base,
ring,
label
});
}
dockDefinitions.forEach(createDock);
// -------------------------------------------------------------------------
// Blocks
// -------------------------------------------------------------------------
const blocks = [];
function createBlock(name, x, z, width, height, depth, color) {
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
flatShading: true,
emissive: 0x000000,
emissiveIntensity: 0
});
const mesh = new THREE.Mesh(new THREE.BoxGeometry(width, height, depth), material);
mesh.position.set(x, height / 2 + 0.005, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry),
new THREE.LineBasicMaterial({ color: 0x20383e, transparent: true, opacity: 0.5 })
);
mesh.add(edges);
makeBox(
width * 0.48, 0.035, depth * 0.17,
new THREE.MeshStandardMaterial({ color: 0xf5e3bd, roughness: 0.8 }),
0, height / 2 + 0.022, 0,
mesh
);
const label = makeTextSprite(name, "#17323a");
label.scale.set(0.55, 0.19, 1);
scene.add(label);
blocks.push({
name,
mesh,
material,
label,
width,
height,
depth,
velocity: new THREE.Vector3()
});
}
createBlock("01", docks[0].x, docks[0].z, 0.76, 0.76, 0.76, 0xe96858);
createBlock("02", docks[2].x, docks[2].z, 0.78, 0.78, 0.78, 0x4b8fe8);
createBlock("03", docks[3].x, docks[3].z, 0.80, 0.64, 0.78, 0xe8b541);
// -------------------------------------------------------------------------
// Crane state and physical block handling
// -------------------------------------------------------------------------
const gantry = {
x: docks[0].x,
z: docks[0].z,
y: 3.2,
desiredX: docks[0].x,
desiredZ: docks[0].z,
desiredY: 3.2,
closure: 0,
closureTarget: 0
};
const gripPoint = new THREE.Vector3();
let heldBlock = null;
let selectedDock = 0;
function updateGripPoint() {
gripPoint.set(gantry.x, gantry.y - 1.04, gantry.z);
}
function tryGripBlock() {
if (heldBlock || gantry.closureTarget < 0.5 || gantry.closure < 0.72) return;
updateGripPoint();
let best = null;
let bestDistance = Infinity;
for (const block of blocks) {
const p = block.mesh.position;
const dx = Math.abs(p.x - gripPoint.x);
const dz = Math.abs(p.z - gripPoint.z);
const dy = Math.abs(p.y - gripPoint.y);
const insideJaw =
dx < block.width * 0.5 + 0.25 &&
dz < block.depth * 0.5 + 0.25 &&
dy < 0.56;
if (insideJaw) {
const distance = dx * dx + dz * dz + dy * dy;
if (distance < bestDistance) {
best = block;
bestDistance = distance;
}
}
}
if (best) {
heldBlock = best;
best.material.emissive.setHex(0x245943);
best.material.emissiveIntensity = 0.26;
showToast(`${best.name} pinched — raise before traveling.`);
}
}
function releaseBlock() {
if (!heldBlock) return;
const name = heldBlock.name;
heldBlock.material.emissive.setHex(0x000000);
heldBlock.material.emissiveIntensity = 0;
heldBlock = null;
showToast(`${name} released.`);
}
function physicsStep(dt) {
gantry.x = damp(gantry.x, gantry.desiredX, 5.0, dt);
gantry.z = damp(gantry.z, gantry.desiredZ, 5.0, dt);
gantry.y = damp(gantry.y, gantry.desiredY, 6.5, dt);
gantry.closure = damp(gantry.closure, gantry.closureTarget, 9.0, dt);
updateGripPoint();
if (heldBlock && gantry.closure < 0.42) {
releaseBlock();
}
tryGripBlock();
for (const block of blocks) {
const p = block.mesh.position;
const v = block.velocity;
if (block === heldBlock) {
// A damped spring pulls the load toward the jaws. It is never snapped.
const ax = (gripPoint.x - p.x) * 44 - v.x * 10.5;
const az = (gripPoint.z - p.z) * 44 - v.z * 10.5;
const ay = (gripPoint.y - p.y) * 44 + 9.8 - v.y * 10.5;
v.x += ax * dt;
v.y += ay * dt;
v.z += az * dt;
const speed = v.length();
if (speed > 8) v.multiplyScalar(8 / speed);
} else {
v.y -= 9.8 * dt;
v.x *= Math.exp(-2.7 * dt);
v.z *= Math.exp(-2.7 * dt);
}
p.addScaledVector(v, dt);
const halfHeight = block.height / 2;
if (p.y < halfHeight + 0.005) {
p.y = halfHeight + 0.005;
if (v.y < 0) v.y = Math.abs(v.y) > 0.8 ? -v.y * 0.10 : 0;
v.x *= 0.84;
v.z *= 0.84;
}
// Keep blocks on the tabletop without teleporting them.
if (p.x < -8.05) {
p.x = -8.05;
v.x = Math.abs(v.x) * 0.25;
}
if (p.x > 8.05) {
p.x = 8.05;
v.x = -Math.abs(v.x) * 0.25;
}
if (p.z < -5.85) {
p.z = -5.85;
v.z = Math.abs(v.z) * 0.25;
}
if (p.z > 5.85) {
p.z = 5.85;
v.z = -Math.abs(v.z) * 0.25;
}
// A slight visual lean follows travel, while the load remains upright.
const targetTiltX = block === heldBlock ? THREE.MathUtils.clamp(-v.z * 0.025, -0.09, 0.09) : 0;
const targetTiltZ = block === heldBlock ? THREE.MathUtils.clamp(v.x * 0.025, -0.09, 0.09) : 0;
block.mesh.rotation.x = damp(block.mesh.rotation.x, targetTiltX, 8, dt);
block.mesh.rotation.z = damp(block.mesh.rotation.z, targetTiltZ, 8, dt);
}
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
const gripButton = document.getElementById("gripButton");
const gripState = document.getElementById("gripState");
const hoistSlider = document.getElementById("hoist");
const hoistValue = document.getElementById("hoistValue");
const statusElement = document.getElementById("status");
const dockButtons = document.getElementById("dockButtons");
const toastElement = document.getElementById("toast");
dockButtons.innerHTML = docks.map((dock, index) => `
<button
type="button"
data-dock="${index}"
style="--dock-color:${dock.css}"
title="Travel to Dock ${dock.id}"
>${dock.id}</button>
`).join("");
const dockButtonElements = [...dockButtons.querySelectorAll("button")];
function updateDockSelection() {
dockButtonElements.forEach((button, index) => {
button.classList.toggle("selected", index === selectedDock);
});
}
function selectDock(index) {
selectedDock = index;
const dock = docks[index];
gantry.desiredX = dock.x;
gantry.desiredZ = dock.z;
updateDockSelection();
showToast(
heldBlock
? `Traveling to Dock ${dock.id} with block ${heldBlock.name}.`
: `Traveling to Dock ${dock.id}.`
);
}
function clearDockSelection() {
selectedDock = -1;
updateDockSelection();
}
function toggleGrip() {
gantry.closureTarget = gantry.closureTarget > 0.5 ? 0 : 1;
gripButton.textContent = gantry.closureTarget > 0.5 ? "Open jaws" : "Close jaws";
gripButton.classList.toggle("open", gantry.closureTarget > 0.5);
gripState.textContent = gantry.closureTarget > 0.5 ? "CLOSING / CLOSED" : "OPEN";
}
dockButtonElements.forEach(button => {
button.addEventListener("click", () => selectDock(Number(button.dataset.dock)));
});
gripButton.addEventListener("click", toggleGrip);
hoistSlider.addEventListener("input", () => {
gantry.desiredY = Number(hoistSlider.value);
hoistValue.textContent = `${gantry.desiredY.toFixed(1)} m`;
});
let toastTimer = 0;
function showToast(message) {
toastElement.textContent = message;
toastElement.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toastElement.classList.remove("show"), 2200);
}
// -------------------------------------------------------------------------
// Custom camera controls — implemented directly, without camera addons
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 1.65, 0),
azimuth: 0.72,
polar: 1.03,
radius: 20.5
};
function updateCamera() {
const s = Math.sin(cameraState.polar);
camera.position.set(
cameraState.target.x + cameraState.radius * s * Math.sin(cameraState.azimuth),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.polar),
cameraState.target.z + cameraState.radius * s * Math.cos(cameraState.azimuth)
);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const pointerState = {
down: false,
button: 0,
x: 0,
y: 0,
lastX: 0,
lastY: 0,
moved: 0
};
const cameraRight = new THREE.Vector3();
const cameraForward = new THREE.Vector3();
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
renderer.domElement.addEventListener("pointerdown", event => {
pointerState.down = true;
pointerState.button = event.button;
pointerState.x = event.clientX;
pointerState.y = event.clientY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
pointerState.moved = 0;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointerState.down) return;
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
pointerState.moved += Math.abs(dx) + Math.abs(dy);
if (pointerState.button === 2 || event.shiftKey) {
cameraRight.setFromMatrixColumn(camera.matrixWorld, 0).normalize();
cameraForward.set(0, 0, -1).applyQuaternion(camera.quaternion);
cameraForward.y = 0;
cameraForward.normalize();
const factor = cameraState.radius * 0.0015;
cameraState.target.addScaledVector(cameraRight, -dx * factor);
cameraState.target.addScaledVector(cameraForward, dy * factor);
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -9, 9);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -8, 8);
cameraState.target.y = THREE.MathUtils.clamp(cameraState.target.y, 0.3, 4.5);
} else {
cameraState.azimuth -= dx * 0.006;
cameraState.polar = THREE.MathUtils.clamp(
cameraState.polar - dy * 0.005,
0.42,
1.38
);
}
});
renderer.domElement.addEventListener("pointerup", event => {
pointerState.down = false;
renderer.domElement.releasePointerCapture(event.pointerId);
if (pointerState.moved > 7 || pointerState.button !== 0) return;
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(
[...dockHitMeshes, ...jawPickables],
false
);
if (hits.length) {
const hit = hits[0].object;
if (hit.userData.dockIndex !== undefined) {
selectDock(hit.userData.dockIndex);
} else if (hit.userData.action === "toggle-grip") {
toggleGrip();
}
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerState.down = false;
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
10,
33
);
}, { passive: false });
// -------------------------------------------------------------------------
// Keyboard controls
// -------------------------------------------------------------------------
const pressedKeys = new Set();
window.addEventListener("keydown", event => {
const tag = event.target.tagName;
if (["INPUT", "BUTTON", "SELECT", "TEXTAREA"].includes(tag)) return;
if (event.code === "Space") {
event.preventDefault();
if (!event.repeat) toggleGrip();
return;
}
if (event.code === "ArrowLeft" || event.code === "ArrowRight") {
event.preventDefault();
gantry.desiredX += event.code === "ArrowLeft" ? -0.25 : 0.25;
gantry.desiredX = THREE.MathUtils.clamp(gantry.desiredX, -7.2, 7.2);
clearDockSelection();
}
if (event.code === "ArrowUp" || event.code === "ArrowDown") {
event.preventDefault();
gantry.desiredZ += event.code === "ArrowUp" ? -0.25 : 0.25;
gantry.desiredZ = THREE.MathUtils.clamp(gantry.desiredZ, -4.8, 4.8);
clearDockSelection();
}
if (event.code === "KeyR" || event.code === "KeyF") {
pressedKeys.add(event.code);
}
});
window.addEventListener("keyup", event => {
pressedKeys.delete(event.code);
});
window.addEventListener("blur", () => pressedKeys.clear());
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
const cableStart = new THREE.Vector3();
const cableEnd = new THREE.Vector3();
let statusTimer = 0;
let elapsed = 0;
function updateVisuals(dt) {
bridge.position.z = gantry.z;
trolley.position.x = gantry.x;
jawRoot.position.set(gantry.x, gantry.y, gantry.z);
leftJaw.rotation.z = -0.34 + gantry.closure * 0.42;
rightJaw.rotation.z = 0.34 - gantry.closure * 0.42;
cableStart.set(gantry.x, 5.53, gantry.z);
cableEnd.set(gantry.x, gantry.y + 0.42, gantry.z);
placeCable(cableStart, cableEnd);
for (const block of blocks) {
block.label.position.copy(block.mesh.position);
block.label.position.y += block.height / 2 + 0.38;
}
for (let i = 0; i < docks.length; i++) {
const dock = docks[i];
const selected = i === selectedDock;
const pulse = selected ? 1 + Math.sin(elapsed * 3.5) * 0.035 : 1;
dock.ring.scale.setScalar(pulse);
dock.ring.material.opacity = selected ? 1 : 0.72;
dock.base.material.emissiveIntensity = selected ? 0.30 : 0.07;
dock.label.material.opacity = selected ? 1 : 0.80;
}
if (pressedKeys.has("KeyR")) {
gantry.desiredY = Math.min(5.1, gantry.desiredY + dt * 0.9);
}
if (pressedKeys.has("KeyF")) {
gantry.desiredY = Math.max(1.25, gantry.desiredY - dt * 0.9);
}
hoistSlider.value = gantry.desiredY.toFixed(2);
hoistValue.textContent = `${gantry.desiredY.toFixed(1)} m`;
statusTimer += dt;
if (statusTimer > 0.12) {
statusTimer = 0;
if (heldBlock) {
statusElement.textContent = `Holding block ${heldBlock.name}. Raise, travel, lower, and open the jaws.`;
statusElement.classList.add("holding");
} else {
statusElement.classList.remove("holding");
if (gantry.closureTarget > 0.5 && gantry.closure < 0.72) {
statusElement.textContent = "Closing the clothespin…";
} else if (selectedDock >= 0) {
statusElement.textContent = `Crane aligned with Dock ${docks[selectedDock].id}. Lower the gripper to grab a block.`;
} else {
statusElement.textContent = "Crane in free-travel mode. Click a dock to line up with a marker.";
}
}
}
}
function animate() {
const dt = Math.min(clock.getDelta(), 0.05);
elapsed += dt;
// Fixed-size substeps keep the spring/contact behavior stable.
const fixedStep = 1 / 120;
let remaining = dt;
while (remaining > 0) {
const step = Math.min(fixedStep, remaining);
physicsStep(step);
remaining -= step;
}
updateVisuals(dt);
updateCamera();
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
updateDockSelection();
updateCamera();
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```