Prompt specification
Build or customize the Three.js 3D scene "Tide-pool shell resource scene" 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: Tide-pool shell resource scene
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/tide-pool-shell-resource-scene-x0695
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows hermit-crab shell use. Compose a shallow tide pool with rocks, algae, several empty shells, and hermit crabs; animals investigate available shelters without every individual following the same path. Stylized solid forms.
Working Three.js Starter (tide-pool-shell-resource-scene-x0695):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Shell Seekers — Tide Pool Shelter Survey</title>
<style>
:root {
color-scheme: light;
--ink: #173c3a;
--muted: #50716b;
--paper: rgba(247, 244, 226, 0.88);
--line: rgba(23, 60, 58, 0.16);
--coral: #df6f4f;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #b9d5cf;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.hud {
position: fixed;
top: 28px;
left: 30px;
width: min(370px, calc(100vw - 60px));
pointer-events: none;
z-index: 2;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 10px;
color: var(--muted);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.live-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--coral);
box-shadow: 0 0 0 5px rgba(223, 111, 79, 0.15);
animation: pulse 2.2s ease-in-out infinite;
}
@keyframes pulse {
50% { box-shadow: 0 0 0 9px rgba(223, 111, 79, 0); }
}
h1 {
margin: 0;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(38px, 5vw, 66px);
font-weight: 500;
line-height: 0.93;
letter-spacing: -0.045em;
text-wrap: balance;
}
.subtitle {
max-width: 330px;
margin: 16px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.legend {
display: inline-flex;
align-items: center;
gap: 10px;
margin-top: 17px;
padding: 9px 12px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(247, 244, 226, 0.72);
backdrop-filter: blur(10px);
color: var(--muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.025em;
}
.legend-ring {
width: 15px;
height: 8px;
border: 2px solid var(--coral);
border-radius: 50%;
box-shadow: 0 0 8px rgba(223, 111, 79, 0.45);
}
.controls {
position: fixed;
right: 26px;
bottom: 25px;
z-index: 3;
display: flex;
align-items: center;
gap: 8px;
padding: 8px;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--paper);
box-shadow: 0 10px 35px rgba(35, 65, 59, 0.12);
backdrop-filter: blur(14px);
}
.hint {
padding: 0 9px 0 7px;
color: var(--muted);
font-size: 11px;
font-weight: 650;
white-space: nowrap;
}
button {
display: grid;
place-items: center;
width: 34px;
height: 34px;
padding: 0;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.64);
color: var(--ink);
font: 700 17px/1 system-ui, sans-serif;
cursor: pointer;
transition: transform 150ms ease, background 150ms ease;
}
button:hover {
transform: translateY(-1px);
background: white;
}
button:active { transform: translateY(0); }
.credit {
position: fixed;
left: 30px;
bottom: 26px;
z-index: 2;
color: rgba(23, 60, 58, 0.62);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.13em;
text-transform: uppercase;
pointer-events: none;
}
@media (max-width: 700px) {
.hud { top: 20px; left: 20px; }
h1 { font-size: 42px; }
.subtitle { max-width: 260px; font-size: 12px; }
.credit { display: none; }
.controls { right: 14px; bottom: 14px; }
.hint { display: none; }
}
</style>
</head>
<body>
<main id="scene" aria-label="Interactive three-dimensional tide pool with hermit crabs"></main>
<section class="hud">
<div class="eyebrow">
<span class="live-dot"></span>
Live tide-pool study
</div>
<h1>Shell Seekers</h1>
<p class="subtitle">
Four hermit crabs search a shallow pool for shelter.
Each animal follows its own wandering route before inspecting a possible new home.
</p>
<div class="legend">
<span class="legend-ring"></span>
Glowing ring = shelter under inspection
</div>
</section>
<nav class="controls" aria-label="Camera controls">
<span class="hint">Drag to orbit · Wheel to zoom · Shift-drag to pan</span>
<button id="zoomIn" aria-label="Zoom in">+</button>
<button id="zoomOut" aria-label="Zoom out">−</button>
<button id="reset" aria-label="Reset camera">↺</button>
</nav>
<div class="credit">4 crabs · 5 empty shells · procedural miniature</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer, scene, lighting
// -------------------------------------------------------------------------
const mount = document.querySelector("#scene");
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;
renderer.domElement.setAttribute(
"aria-label",
"A stylized tide pool with animated hermit crabs and empty shells"
);
mount.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color("#b9d5cf");
scene.fog = new THREE.Fog("#b9d5cf", 15, 34);
const camera = new THREE.PerspectiveCamera(
39,
window.innerWidth / window.innerHeight,
0.1,
80
);
const hemi = new THREE.HemisphereLight("#e8fff4", "#5d6658", 2.25);
scene.add(hemi);
const sun = new THREE.DirectionalLight("#fff1cc", 3.5);
sun.position.set(-5, 10, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -9;
sun.shadow.camera.right = 9;
sun.shadow.camera.top = 8;
sun.shadow.camera.bottom = -8;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 28;
sun.shadow.bias = -0.0006;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const fill = new THREE.DirectionalLight("#9acfd1", 1.2);
fill.position.set(7, 4, -6);
scene.add(fill);
// -------------------------------------------------------------------------
// Utilities
// -------------------------------------------------------------------------
let seed = 84172;
function random() {
seed |= 0;
seed = seed + 0x6D2B79F5 | 0;
let t = Math.imul(seed ^ seed >>> 15, 1 | seed);
t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
return ((t ^ t >>> 14) >>> 0) / 4294967296;
}
function range(min, max) {
return min + (max - min) * random();
}
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0,
flatShading: true,
...options
});
}
const Y_AXIS = new THREE.Vector3(0, 1, 0);
function segment(parent, a, b, radius, mat, radialSegments = 6) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(
radius * 0.82,
radius,
length,
radialSegments,
1
);
const mesh = new THREE.Mesh(geometry, mat);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(Y_AXIS, direction.normalize());
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function setShadow(mesh) {
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function irregularPoolGeometry(rx, rz, roughness, phase = 0) {
const shape = new THREE.Shape();
const count = 48;
for (let i = 0; i <= count; i++) {
const angle = i / count * Math.PI * 2;
const wobble =
1 +
roughness * Math.sin(angle * 3 + phase) +
roughness * 0.55 * Math.sin(angle * 7 - phase * 1.7);
const x = Math.cos(angle) * rx * wobble;
const y = Math.sin(angle) * rz * wobble;
if (i === 0) shape.moveTo(x, y);
else shape.lineTo(x, y);
}
shape.closePath();
const geometry = new THREE.ShapeGeometry(shape, 12);
geometry.rotateX(-Math.PI / 2);
return geometry;
}
// -------------------------------------------------------------------------
// Tide pool terrain
// -------------------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
material("#81968a")
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.66;
ground.receiveShadow = true;
scene.add(ground);
const rockyLedge = setShadow(
new THREE.Mesh(
new THREE.CylinderGeometry(7.4, 7.9, 0.58, 13),
material("#64766d")
)
);
rockyLedge.position.y = -0.37;
rockyLedge.scale.z = 0.7;
scene.add(rockyLedge);
const sand = setShadow(
new THREE.Mesh(
irregularPoolGeometry(5.65, 4.0, 0.035, 0.7),
material("#d5bd82")
)
);
sand.position.y = -0.035;
scene.add(sand);
const waterMaterial = new THREE.MeshStandardMaterial({
color: "#78c3bd",
roughness: 0.2,
metalness: 0.04,
transparent: true,
opacity: 0.34,
depthWrite: false,
side: THREE.DoubleSide
});
const water = new THREE.Mesh(
irregularPoolGeometry(5.32, 3.68, 0.033, 0.7),
waterMaterial
);
water.position.y = 0.025;
water.renderOrder = 2;
water.receiveShadow = true;
scene.add(water);
const shoreline = new THREE.Mesh(
new THREE.TorusGeometry(1, 0.012, 5, 100),
new THREE.MeshBasicMaterial({
color: "#eff8e7",
transparent: true,
opacity: 0.38,
depthWrite: false
})
);
shoreline.rotation.x = Math.PI / 2;
shoreline.scale.set(5.26, 3.61, 1);
shoreline.position.y = 0.052;
shoreline.renderOrder = 3;
scene.add(shoreline);
// -------------------------------------------------------------------------
// Rocks
// -------------------------------------------------------------------------
const rockPalette = [
"#65756f",
"#78857c",
"#536862",
"#8a8f7e",
"#6f817a"
];
function addRock(x, z, sx, sy, sz, color = null) {
const rock = setShadow(
new THREE.Mesh(
new THREE.IcosahedronGeometry(1, 1),
material(color || rockPalette[Math.floor(random() * rockPalette.length)])
)
);
rock.position.set(x, sy * 0.54 - 0.025, z);
rock.scale.set(sx, sy, sz);
rock.rotation.set(range(-0.25, 0.25), range(0, Math.PI), range(-0.2, 0.2));
scene.add(rock);
return rock;
}
// Broken ring of shoreline stones.
for (let i = 0; i < 22; i++) {
const angle = i / 22 * Math.PI * 2 + range(-0.04, 0.04);
const radius = range(0.96, 1.06);
const x = Math.cos(angle) * 5.75 * radius;
const z = Math.sin(angle) * 4.13 * radius;
addRock(
x,
z,
range(0.45, 0.95),
range(0.28, 0.62),
range(0.42, 0.84)
);
}
const obstacles = [
{ x: -3.9, z: -0.15, r: 0.72 },
{ x: 3.9, z: 0.05, r: 0.75 },
{ x: 0.15, z: 3.05, r: 0.64 },
{ x: -3.55, z: 2.15, r: 0.68 },
{ x: 1.35, z: -2.82, r: 0.54 },
{ x: -2.9, z: -2.75, r: 0.55 }
];
obstacles.forEach((o, i) => {
addRock(
o.x,
o.z,
o.r * 1.13,
range(0.58, 0.9),
o.r,
rockPalette[(i + 1) % rockPalette.length]
);
});
// Small submerged pebbles.
for (let i = 0; i < 30; i++) {
const angle = random() * Math.PI * 2;
const radius = Math.sqrt(random());
const x = Math.cos(angle) * radius * 4.9;
const z = Math.sin(angle) * radius * 3.35;
const pebble = setShadow(
new THREE.Mesh(
new THREE.DodecahedronGeometry(range(0.045, 0.11), 0),
material(random() > 0.5 ? "#b8a474" : "#87917d")
)
);
pebble.position.set(x, 0.035, z);
pebble.scale.y = range(0.45, 0.8);
pebble.rotation.set(random(), random(), random());
scene.add(pebble);
}
// -------------------------------------------------------------------------
// Algae and small sea life
// -------------------------------------------------------------------------
const algaePalette = ["#2c7657", "#397f55", "#4e9567", "#256b59"];
function addAlgae(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0.015, z);
group.rotation.y = range(0, Math.PI * 2);
const count = 5 + Math.floor(random() * 4);
for (let i = 0; i < count; i++) {
const pivot = new THREE.Group();
pivot.position.set(range(-0.08, 0.08), 0, range(-0.08, 0.08));
pivot.rotation.z = range(-0.48, 0.48);
pivot.rotation.x = range(-0.25, 0.25);
const h = range(0.38, 0.8) * scale;
const blade = setShadow(
new THREE.Mesh(
new THREE.ConeGeometry(range(0.07, 0.13) * scale, h, 5),
material(algaePalette[i % algaePalette.length])
)
);
blade.position.y = h * 0.5;
blade.scale.z = 0.42;
pivot.add(blade);
group.add(pivot);
}
scene.add(group);
}
addAlgae(-4.1, 0.25, 1.1);
addAlgae(4.05, 0.3, 1.25);
addAlgae(0.0, 3.16, 1.05);
addAlgae(-3.35, 2.45, 0.9);
addAlgae(-2.85, -2.8, 0.8);
addAlgae(4.25, -2.05, 1.0);
addAlgae(-4.4, -1.65, 0.75);
function addStarfish(x, z, rotation = 0) {
const group = new THREE.Group();
group.position.set(x, 0.07, z);
group.rotation.y = rotation;
const mat = material("#d87556");
const center = setShadow(
new THREE.Mesh(new THREE.SphereGeometry(0.18, 8, 6), mat)
);
center.scale.y = 0.45;
group.add(center);
for (let i = 0; i < 5; i++) {
const angle = i / 5 * Math.PI * 2;
const start = new THREE.Vector3(0, 0, 0);
const end = new THREE.Vector3(
Math.cos(angle) * 0.48,
0,
Math.sin(angle) * 0.48
);
const arm = segment(group, start, end, 0.105, mat, 5);
arm.scale.y = 1;
}
scene.add(group);
}
addStarfish(1.55, 0.95, 0.3);
addStarfish(-1.05, -2.55, -0.6);
// -------------------------------------------------------------------------
// Procedural spiral shells
// -------------------------------------------------------------------------
function makeShell(baseColor, ridgeColor, scale = 1) {
const group = new THREE.Group();
const shellMat = material(baseColor, { roughness: 0.72 });
const ridgeMat = material(ridgeColor, { roughness: 0.78 });
const core = setShadow(
new THREE.Mesh(
new THREE.SphereGeometry(1, 12, 8),
shellMat
)
);
core.scale.set(0.45, 0.38, 0.4);
core.scale.z *= 0.92;
group.add(core);
// Raised spiral rib on the visible face.
const spiralPoints = [];
for (let i = 0; i <= 56; i++) {
const t = i / 56;
const angle = -0.45 + t * Math.PI * 4.35;
const radius = 0.265 * (1 - t * 0.88);
spiralPoints.push(
new THREE.Vector3(
-0.08 + Math.cos(angle) * radius,
Math.sin(angle) * radius * 0.83,
0.335 + 0.018 * Math.sin(angle * 0.7)
)
);
}
const spiral = setShadow(
new THREE.Mesh(
new THREE.TubeGeometry(
new THREE.CatmullRomCurve3(spiralPoints),
72,
0.024,
5,
false
),
ridgeMat
)
);
group.add(spiral);
// Aperture and thick lip.
const aperture = new THREE.Mesh(
new THREE.CircleGeometry(0.135, 20),
material("#49392f", { side: THREE.DoubleSide, roughness: 1 })
);
aperture.rotation.y = Math.PI / 2;
aperture.position.set(0.365, -0.025, 0.025);
aperture.scale.set(0.88, 1.15, 1);
group.add(aperture);
const lip = setShadow(
new THREE.Mesh(
new THREE.TorusGeometry(0.139, 0.025, 6, 24),
ridgeMat
)
);
lip.rotation.y = Math.PI / 2;
lip.position.copy(aperture.position);
lip.scale.set(0.88, 1.15, 1);
group.add(lip);
group.scale.setScalar(scale);
group.userData.baseScale = scale;
return group;
}
const shellPalette = [
["#d69a5b", "#f0cf94"],
["#b9674f", "#e4a66e"],
["#e2bd82", "#f3d9a3"],
["#c67d55", "#efb47c"],
["#d8aa72", "#f4d7a0"]
];
const shellSites = [
{ x: 0.65, z: -1.15 },
{ x: -3.0, z: 0.55 },
{ x: 2.25, z: 1.95 },
{ x: -0.6, z: 2.55 },
{ x: 3.55, z: -1.85 }
];
shellSites.forEach((site, i) => {
const colors = shellPalette[i % shellPalette.length];
const shell = makeShell(colors[0], colors[1], range(0.84, 1.04));
shell.position.set(site.x, 0.11, site.z);
shell.rotation.set(range(-0.14, 0.12), range(-0.48, 0.48), range(-0.08, 0.08));
scene.add(shell);
});
// -------------------------------------------------------------------------
// Hermit crabs
// -------------------------------------------------------------------------
const crabPalette = [
["#c95138", "#7e2f29"],
["#df6c43", "#8f3d2d"],
["#b84737", "#71312b"],
["#e37b4c", "#98422d"]
];
function makeCrab(index, start) {
const root = new THREE.Group();
root.position.set(start.x, 0.045, start.z);
root.scale.setScalar(range(0.87, 1.03));
scene.add(root);
const visual = new THREE.Group();
root.add(visual);
const colors = crabPalette[index % crabPalette.length];
const bodyMat = material(colors[0]);
const jointMat = material(colors[1]);
const body = setShadow(
new THREE.Mesh(new THREE.SphereGeometry(1, 10, 7), bodyMat)
);
body.position.set(0, -0.025, 0.03);
body.scale.set(0.27, 0.18, 0.34);
visual.add(body);
// Three articulated legs on each side.
const legs = [];
for (const side of [-1, 1]) {
for (let i = 0; i < 3; i++) {
const z = -0.19 + i * 0.19;
const pivot = new THREE.Group();
pivot.position.set(side * 0.18, -0.035, z);
visual.add(pivot);
const upperEnd = new THREE.Vector3(side * 0.28, -0.17, z * 0.25);
const lowerEnd = new THREE.Vector3(side * 0.45, -0.29, z * 0.5);
segment(pivot, new THREE.Vector3(), upperEnd, 0.055, bodyMat);
segment(pivot, upperEnd, lowerEnd, 0.043, jointMat);
const tip = setShadow(
new THREE.Mesh(new THREE.SphereGeometry(0.055, 7, 5), jointMat)
);
tip.position.copy(lowerEnd);
tip.scale.set(1.2, 0.55, 0.8);
pivot.add(tip);
legs.push({
pivot,
phase: (i % 2) * Math.PI + (side > 0 ? 0.45 : 0)
});
}
}
// Claws and arms.
const claws = [];
for (const side of [-1, 1]) {
const pivot = new THREE.Group();
pivot.position.set(side * 0.2, -0.01, 0.2);
visual.add(pivot);
const elbow = new THREE.Vector3(side * 0.16, 0.02, 0.19);
const wrist = new THREE.Vector3(side * 0.19, 0.035, 0.33);
segment(pivot, new THREE.Vector3(), elbow, 0.047, bodyMat);
segment(pivot, elbow, wrist, 0.042, jointMat);
const palm = setShadow(
new THREE.Mesh(new THREE.SphereGeometry(1, 8, 6), bodyMat)
);
palm.position.set(side * 0.19, 0.045, 0.38);
palm.scale.set(0.105, 0.095, 0.15);
pivot.add(palm);
for (const spread of [-1, 1]) {
const pincer = setShadow(
new THREE.Mesh(new THREE.ConeGeometry(0.045, 0.18, 5), jointMat)
);
pincer.position.set(
side * 0.19 + spread * 0.045,
0.055,
0.51
);
pincer.rotation.x = Math.PI / 2;
pincer.rotation.y = spread * 0.18;
pivot.add(pincer);
}
claws.push({ pivot, phase: side > 0 ? 0.7 : Math.PI + 0.7 });
}
// Stalked eyes.
for (const side of [-1, 1]) {
const startEye = new THREE.Vector3(side * 0.095, 0.07, 0.2);
const endEye = new THREE.Vector3(side * 0.13, 0.25, 0.28);
segment(visual, startEye, endEye, 0.025, jointMat);
const eye = setShadow(
new THREE.Mesh(new THREE.SphereGeometry(0.045, 8, 6), material("#1d2825"))
);
eye.position.copy(endEye);
visual.add(eye);
const glint = new THREE.Mesh(
new THREE.SphereGeometry(0.011, 6, 4),
new THREE.MeshBasicMaterial({ color: "#ffffff" })
);
glint.position.set(endEye.x + 0.014, endEye.y + 0.018, endEye.z + 0.03);
visual.add(glint);
}
// Every crab carries a differently colored home.
const shellColors = shellPalette[(index + 1) % shellPalette.length];
const carriedShell = makeShell(shellColors[0], shellColors[1], 0.73);
carriedShell.position.set(-0.02, 0.285, -0.13);
carriedShell.rotation.set(-0.08, -0.12, 0.06);
visual.add(carriedShell);
// Colored inspection ring for this crab.
const ringMaterial = new THREE.MeshBasicMaterial({
color: ["#ef7853", "#f1a653", "#e55f5e", "#f3c45e"][index],
transparent: true,
opacity: 0,
depthWrite: false,
side: THREE.DoubleSide
});
const inspectionRing = new THREE.Mesh(
new THREE.RingGeometry(0.34, 0.43, 32),
ringMaterial
);
inspectionRing.rotation.x = -Math.PI / 2;
inspectionRing.position.y = 0.072;
inspectionRing.renderOrder = 4;
scene.add(inspectionRing);
return {
index,
root,
visual,
legs,
claws,
carriedShell,
inspectionRing,
ringMaterial,
position: new THREE.Vector3(start.x, 0, start.z),
heading: range(-Math.PI, Math.PI),
state: "roam",
waypoint: new THREE.Vector3(),
targetShell: index % shellSites.length,
cycle: 0,
nextShellAt: 1.4 + index * 2.15,
inspectUntil: 0,
waypointDeadline: 0,
approachAngle: index * 1.73 + 0.4,
movement: 0
};
}
function newWaypoint(crab) {
// Irregular radial routes, with offsets unique to each individual.
const angle = random() * Math.PI * 2;
const radius = range(1.2, 3.45) * (crab.index % 2 ? 0.88 : 1.08);
const x = Math.cos(angle) * radius + (crab.index - 1.5) * 0.2;
const z = Math.sin(angle) * radius * 0.67 + (1.5 - crab.index) * 0.12;
return new THREE.Vector3(x, 0, z);
}
const crabs = [
makeCrab(0, { x: -2.15, z: -1.45 }),
makeCrab(1, { x: 2.35, z: -0.95 }),
makeCrab(2, { x: -1.25, z: 1.65 }),
makeCrab(3, { x: 3.25, z: 1.45 })
];
crabs.forEach(crab => {
crab.waypoint.copy(newWaypoint(crab));
crab.waypointDeadline = range(4, 7);
});
// -------------------------------------------------------------------------
// Bubbles and water glints
// -------------------------------------------------------------------------
const bubbles = [];
const bubbleMaterial = new THREE.MeshBasicMaterial({
color: "#eafff5",
transparent: true,
opacity: 0.35,
depthWrite: false
});
for (let i = 0; i < 16; i++) {
const bubble = new THREE.Mesh(
new THREE.SphereGeometry(range(0.025, 0.065), 7, 5),
bubbleMaterial
);
const x = range(-4.5, 4.5);
const z = range(-3.0, 3.0);
bubble.position.set(x, range(0.06, 1.1), z);
bubble.userData.phase = random() * Math.PI * 2;
bubble.userData.baseX = x;
bubble.userData.baseZ = z;
bubbles.push(bubble);
scene.add(bubble);
}
const glintMaterial = new THREE.MeshBasicMaterial({
color: "#f4fff0",
transparent: true,
opacity: 0.42,
depthWrite: false
});
for (let i = 0; i < 12; i++) {
const glint = new THREE.Mesh(
new THREE.SphereGeometry(1, 6, 4),
glintMaterial
);
const angle = random() * Math.PI * 2;
const radius = range(1, 4.5);
glint.position.set(
Math.cos(angle) * radius,
0.064,
Math.sin(angle) * radius * 0.7
);
glint.scale.set(range(0.07, 0.2), 0.006, range(0.015, 0.035));
glint.rotation.y = range(0, Math.PI);
scene.add(glint);
}
// -------------------------------------------------------------------------
// Custom camera controls: orbit, pan, wheel zoom, and pinch zoom
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 0.1, 0),
yaw: 0.57,
pitch: 0.68,
distance: 12.7
};
const initialCamera = { ...cameraState, target: cameraState.target.clone() };
function updateCamera() {
const { target, yaw, pitch, distance } = cameraState;
camera.position.set(
target.x + Math.sin(yaw) * Math.cos(pitch) * distance,
target.y + Math.sin(pitch) * distance,
target.z + Math.cos(yaw) * Math.cos(pitch) * distance
);
camera.lookAt(target);
}
function resetCamera() {
cameraState.target.copy(initialCamera.target);
cameraState.yaw = initialCamera.yaw;
cameraState.pitch = initialCamera.pitch;
cameraState.distance = initialCamera.distance;
updateCamera();
}
function panCamera(dx, dy) {
const scale = cameraState.distance * 0.0015;
const right = new THREE.Vector3(
Math.cos(cameraState.yaw),
0,
-Math.sin(cameraState.yaw)
);
const forward = new THREE.Vector3(
-Math.sin(cameraState.yaw),
0,
-Math.cos(cameraState.yaw)
);
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(forward, dy * scale);
cameraState.target.x = THREE.MathUtils.clamp(cameraState.target.x, -4, 4);
cameraState.target.z = THREE.MathUtils.clamp(cameraState.target.z, -3, 3);
}
const pointers = new Map();
let pinchDistance = 0;
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", event => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
pinchDistance = Math.hypot(a.x - b.x, a.y - b.y);
}
});
renderer.domElement.addEventListener("pointermove", event => {
const previous = pointers.get(event.pointerId);
if (!previous) return;
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 1) {
if (event.shiftKey || event.buttons === 2) {
panCamera(dx, dy);
} else {
cameraState.yaw -= dx * 0.0055;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.0045,
0.24,
1.25
);
}
} else if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
const distance = Math.hypot(a.x - b.x, a.y - b.y);
if (pinchDistance > 0 && distance > 0) {
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance * (pinchDistance / distance),
6.5,
21
);
}
pinchDistance = distance;
panCamera(dx * 0.45, dy * 0.45);
}
updateCamera();
});
function removePointer(event) {
pointers.delete(event.pointerId);
pinchDistance = 0;
}
renderer.domElement.addEventListener("pointerup", removePointer);
renderer.domElement.addEventListener("pointercancel", removePointer);
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance * Math.exp(event.deltaY * 0.001),
6.5,
21
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
document.querySelector("#zoomIn").addEventListener("click", () => {
cameraState.distance = Math.max(6.5, cameraState.distance - 1);
updateCamera();
});
document.querySelector("#zoomOut").addEventListener("click", () => {
cameraState.distance = Math.min(21, cameraState.distance + 1);
updateCamera();
});
document.querySelector("#reset").addEventListener("click", resetCamera);
window.addEventListener("keydown", event => {
if (event.key === "ArrowLeft") cameraState.yaw += 0.1;
if (event.key === "ArrowRight") cameraState.yaw -= 0.1;
if (event.key === "ArrowUp") cameraState.pitch = Math.min(1.25, cameraState.pitch + 0.07);
if (event.key === "ArrowDown") cameraState.pitch = Math.max(0.24, cameraState.pitch - 0.07);
if (event.key === "+" || event.key === "=") cameraState.distance = Math.max(6.5, cameraState.distance - 0.7);
if (event.key === "-") cameraState.distance = Math.min(21, cameraState.distance + 0.7);
if (event.key.toLowerCase() === "r") resetCamera();
updateCamera();
});
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();
let elapsed = 0;
function angleDifference(a, b) {
return Math.atan2(Math.sin(b - a), Math.cos(b - a));
}
function updateCrab(crab, dt) {
let target = crab.waypoint;
let speed = 0.25 + crab.index * 0.018;
if (crab.state === "roam" && elapsed >= crab.nextShellAt) {
crab.state = "approach";
crab.targetShell = (crab.index + crab.cycle) % shellSites.length;
crab.approachAngle = crab.index * 1.74 + random() * 0.8;
}
if (crab.state === "approach") {
const site = shellSites[crab.targetShell];
const offset = 0.48 + crab.index * 0.035;
target = new THREE.Vector3(
site.x + Math.cos(crab.approachAngle) * offset,
0,
site.z + Math.sin(crab.approachAngle) * offset
);
speed = 0.31 + crab.index * 0.022;
if (crab.position.distanceTo(target) < 0.14) {
crab.state = "inspect";
crab.inspectUntil = elapsed + 2.1 + crab.index * 0.25;
}
} else if (crab.state === "inspect") {
const site = shellSites[crab.targetShell];
target = new THREE.Vector3(site.x, 0, site.z);
speed = 0;
if (elapsed >= crab.inspectUntil) {
crab.state = "roam";
crab.cycle++;
crab.nextShellAt = elapsed + 8 + crab.index * 1.7;
crab.waypoint.copy(newWaypoint(crab));
crab.waypointDeadline = elapsed + range(3.5, 6);
}
} else if (
crab.position.distanceTo(crab.waypoint) < 0.28 ||
elapsed > crab.waypointDeadline
) {
crab.waypoint.copy(newWaypoint(crab));
crab.waypointDeadline = elapsed + range(3.5, 6);
}
const desired = new THREE.Vector3(
target.x - crab.position.x,
0,
target.z - crab.position.z
);
const distance = desired.length();
if (distance > 0.001) {
desired.normalize();
desired.multiplyScalar(Math.min(speed, distance * 1.65));
} else {
desired.set(0, 0, 0);
}
// Local obstacle avoidance gives each route a slightly different shape.
for (const obstacle of obstacles) {
const awayX = crab.position.x - obstacle.x;
const awayZ = crab.position.z - obstacle.z;
const obstacleDistance = Math.hypot(awayX, awayZ);
const safeDistance = obstacle.r + 0.34;
if (obstacleDistance > 0.001 && obstacleDistance < safeDistance) {
const force = (safeDistance - obstacleDistance) * 1.25;
desired.x += awayX / obstacleDistance * force;
desired.z += awayZ / obstacleDistance * force;
}
}
// Stay inside the pool's oval boundary.
const ellipseDistance = Math.sqrt(
Math.pow(crab.position.x / 4.95, 2) +
Math.pow(crab.position.z / 3.35, 2)
);
if (ellipseDistance > 0.88) {
desired.x += -crab.position.x * 0.55;
desired.z += -crab.position.z * 0.55;
}
const oldX = crab.position.x;
const oldZ = crab.position.z;
crab.position.x += desired.x * dt;
crab.position.z += desired.z * dt;
crab.root.position.x = crab.position.x;
crab.root.position.z = crab.position.z;
const traveled = Math.hypot(
crab.position.x - oldX,
crab.position.z - oldZ
);
crab.movement = THREE.MathUtils.lerp(
crab.movement,
THREE.MathUtils.clamp(traveled / Math.max(dt, 0.001) * 3, 0, 1),
0.16
);
if (traveled > 0.0005) {
const desiredHeading = Math.atan2(
crab.position.x - oldX,
crab.position.z - oldZ
);
crab.heading += angleDifference(crab.heading, desiredHeading) *
(1 - Math.exp(-dt * 7));
} else if (crab.state === "inspect") {
const site = shellSites[crab.targetShell];
const desiredHeading = Math.atan2(
site.x - crab.position.x,
site.z - crab.position.z
);
crab.heading += angleDifference(crab.heading, desiredHeading) *
(1 - Math.exp(-dt * 4));
}
crab.root.rotation.y = crab.heading;
const gait = elapsed * (5.1 + crab.index * 0.22) + crab.index * 1.7;
crab.legs.forEach(leg => {
leg.pivot.rotation.y =
Math.sin(gait + leg.phase) * 0.34 * crab.movement;
});
crab.claws.forEach(claw => {
claw.pivot.rotation.y =
Math.sin(gait * 0.72 + claw.phase) * 0.12 * (0.3 + crab.movement);
claw.pivot.rotation.x =
Math.sin(gait * 0.9 + claw.phase) * 0.035;
});
const bob = Math.sin(gait * 2) * 0.018 * crab.movement;
crab.visual.position.y = bob;
crab.visual.rotation.z =
Math.sin(gait * 0.5 + crab.index) * 0.025 * crab.movement;
if (crab.state === "inspect") {
crab.carriedShell.rotation.z =
0.06 + Math.sin(elapsed * 8 + crab.index) * 0.085;
crab.carriedShell.rotation.x =
-0.08 + Math.sin(elapsed * 5 + crab.index) * 0.045;
} else {
crab.carriedShell.rotation.z = THREE.MathUtils.lerp(
crab.carriedShell.rotation.z,
0.06,
dt * 5
);
crab.carriedShell.rotation.x = THREE.MathUtils.lerp(
crab.carriedShell.rotation.x,
-0.08,
dt * 5
);
}
const showingRing =
crab.state === "approach" || crab.state === "inspect";
crab.ringMaterial.opacity = THREE.MathUtils.lerp(
crab.ringMaterial.opacity,
showingRing
? crab.state === "inspect"
? 0.7
: 0.2
: 0,
dt * 8
);
if (showingRing) {
const site = shellSites[crab.targetShell];
crab.inspectionRing.position.x = site.x;
crab.inspectionRing.position.z = site.z;
const pulse = 1 + Math.sin(elapsed * 5 + crab.index) * 0.09;
crab.inspectionRing.scale.setScalar(pulse);
}
}
function animate() {
const dt = Math.min(clock.getDelta(), 0.04);
elapsed += dt;
crabs.forEach(crab => updateCrab(crab, dt));
bubbles.forEach((bubble, i) => {
const travel = (elapsed * (0.08 + i * 0.002) + i * 0.17) % 1.25;
bubble.position.y = 0.07 + travel;
bubble.position.x =
bubble.userData.baseX + Math.sin(elapsed * 0.9 + bubble.userData.phase) * 0.045;
bubble.position.z =
bubble.userData.baseZ + Math.cos(elapsed * 0.7 + bubble.userData.phase) * 0.035;
});
updateCamera();
renderer.render(scene, camera);
}
updateCamera();
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```