Prompt specification
Build or customize the Three.js 3D scene "Rain beads choosing two valleys" 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: Rain beads choosing two valleys
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/rain-beads-choosing-two-valleys-x1194
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts watershed divides. Drop tracer beads on opposite sides of a ridge and guide each downhill into its own stream; make the divide visible and prevent uphill motion. Stylized solid forms.
Working Three.js Starter (rain-beads-choosing-two-valleys-x1194):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Watershed Divide — Three.js</title>
<style>
:root {
color-scheme: light;
--ink: #173433;
--panel: rgba(248, 244, 230, 0.9);
--coral: #ee684e;
--teal: #35b8c4;
--gold: #c99b4b;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dbe9e6;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--ink);
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.panel {
position: absolute;
z-index: 10;
border: 1px solid rgba(23, 52, 51, 0.14);
background: var(--panel);
box-shadow: 0 12px 35px rgba(35, 65, 60, 0.14);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
#info {
top: 20px;
left: 20px;
width: min(330px, calc(100vw - 40px));
padding: 18px 20px 16px;
border-radius: 18px;
pointer-events: none;
}
.eyebrow {
margin-bottom: 6px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
opacity: 0.62;
}
h1 {
margin: 0 0 8px;
font-size: 25px;
line-height: 1.05;
letter-spacing: -0.035em;
}
.subtitle {
margin: 0 0 15px;
font-size: 13px;
line-height: 1.45;
opacity: 0.75;
}
.legend {
display: grid;
gap: 8px;
padding-top: 12px;
border-top: 1px solid rgba(23, 52, 51, 0.12);
font-size: 12px;
font-weight: 650;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
}
.dot {
width: 11px;
height: 11px;
flex: 0 0 auto;
border-radius: 50%;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.08);
}
.dot.coral {
background: var(--coral);
}
.dot.teal {
background: var(--teal);
}
.dot.gold {
background: var(--gold);
border-radius: 3px;
transform: rotate(45deg);
}
#controls {
left: 20px;
bottom: 20px;
display: flex;
gap: 8px;
padding: 8px;
border-radius: 14px;
}
button {
appearance: none;
border: 0;
border-radius: 9px;
padding: 10px 13px;
background: #173433;
color: #fffdf3;
font: inherit;
font-size: 12px;
font-weight: 750;
cursor: pointer;
transition: transform 140ms ease, background 140ms ease;
}
button:hover {
transform: translateY(-1px);
background: #28514e;
}
button.secondary {
background: rgba(23, 52, 51, 0.1);
color: var(--ink);
}
button.secondary:hover {
background: rgba(23, 52, 51, 0.17);
}
#hint {
position: absolute;
right: 20px;
bottom: 20px;
z-index: 10;
max-width: 285px;
padding: 10px 13px;
border-radius: 12px;
background: rgba(248, 244, 230, 0.78);
font-size: 11px;
line-height: 1.4;
opacity: 0.8;
pointer-events: none;
}
.world-label {
position: absolute;
z-index: 5;
top: 0;
left: 0;
padding: 6px 9px;
border: 1px solid rgba(23, 52, 51, 0.15);
border-radius: 8px;
background: rgba(255, 253, 243, 0.9);
box-shadow: 0 5px 16px rgba(35, 65, 60, 0.11);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.09em;
text-transform: uppercase;
white-space: nowrap;
pointer-events: none;
will-change: transform;
}
#ridge-label {
color: #8d6326;
border-color: rgba(141, 99, 38, 0.25);
}
#left-label {
color: #b94532;
}
#right-label {
color: #167d87;
}
@media (max-width: 700px) {
#info {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 14px 16px;
}
h1 {
font-size: 21px;
}
.subtitle {
display: none;
}
.legend {
grid-template-columns: repeat(3, auto);
gap: 12px;
}
#controls {
left: 12px;
bottom: 12px;
}
#hint {
display: none;
}
}
</style>
</head>
<body>
<section id="info" class="panel">
<div class="eyebrow">Catchment / 02</div>
<h1>Watershed Divide</h1>
<p class="subtitle">
Tracer beads are released on opposite slopes. Each bead follows local
downhill flow into a different stream without crossing the divide.
</p>
<div class="legend">
<div class="legend-row">
<span class="dot coral"></span>
<span>Western catchment</span>
</div>
<div class="legend-row">
<span class="dot teal"></span>
<span>Eastern catchment</span>
</div>
<div class="legend-row">
<span class="dot gold"></span>
<span>Watershed divide</span>
</div>
</div>
</section>
<nav id="controls" class="panel" aria-label="Scene controls">
<button id="release" type="button">Release tracers</button>
<button id="pause" class="secondary" type="button">Pause</button>
</nav>
<div id="hint">
Drag to orbit · Scroll to zoom<br />
Uphill steps are rejected by the terrain constraint.
</div>
<div id="ridge-label" class="world-label">Watershed divide</div>
<div id="left-label" class="world-label">Western stream</div>
<div id="right-label" class="world-label">Eastern stream</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 scene = new THREE.Scene();
scene.background = new THREE.Color(0xdbe9e6);
scene.fog = new THREE.Fog(0xdbe9e6, 44, 88);
const camera = new THREE.PerspectiveCamera(
43,
innerWidth / innerHeight,
0.1,
160
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
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", "Interactive watershed landscape");
document.body.prepend(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xf4fff4, 0x617468, 2.1));
const sun = new THREE.DirectionalLight(0xfff2cf, 3.1);
sun.position.set(-13, 24, 15);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -25;
sun.shadow.camera.right = 25;
sun.shadow.camera.top = 25;
sun.shadow.camera.bottom = -25;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.bias = -0.0004;
scene.add(sun);
const terrainGroup = new THREE.Group();
scene.add(terrainGroup);
const WIDTH = 36;
const DEPTH = 28;
const SEGMENTS_X = 64;
const SEGMENTS_Z = 48;
const VALLEY_DISTANCE = 5.3;
const COLORS = {
left: 0xee684e,
right: 0x35b8c4,
ridge: 0xc99b4b,
leftGround: 0x78966c,
rightGround: 0x739778,
bank: 0x3f6c57
};
// The ridge meanders down the middle of the landscape.
function ridgeCenter(z) {
return (
1.15 * Math.sin(z * 0.16) +
0.56 * Math.sin(z * 0.39 + 0.4)
);
}
// Smooth, deterministic terrain. Both valleys slope toward the front (+Z).
function terrainHeight(x, z) {
const d = x - ridgeCenter(z);
const distance = Math.abs(d);
const ridge =
5.8 * Math.exp(-(d * d) / (2 * 2.35 * 2.35));
const valley =
0.06 * Math.pow(distance - VALLEY_DISTANCE, 2);
const downstreamSlope = 0.055 * (13 - z);
const rolling =
0.1 * Math.sin(z * 0.24) +
0.07 * Math.cos(x * 0.19);
return 0.05 + downstreamSlope + ridge + valley + rolling;
}
function addSolidTerrain() {
const geometry = new THREE.BufferGeometry();
const positions = [];
const colors = [];
const indices = [];
const leftGround = new THREE.Color(COLORS.leftGround);
const rightGround = new THREE.Color(COLORS.rightGround);
const ridgeColor = new THREE.Color(COLORS.ridge);
const bankColor = new THREE.Color(COLORS.bank);
for (let iz = 0; iz <= SEGMENTS_Z; iz++) {
const z = -DEPTH / 2 + (iz / SEGMENTS_Z) * DEPTH;
for (let ix = 0; ix <= SEGMENTS_X; ix++) {
const x = -WIDTH / 2 + (ix / SEGMENTS_X) * WIDTH;
const y = terrainHeight(x, z);
positions.push(x, y, z);
const d = x - ridgeCenter(z);
const crestDistance = Math.abs(d);
const valleyDistance = Math.abs(Math.abs(d) - VALLEY_DISTANCE);
const color = (d < 0 ? leftGround : rightGround).clone();
if (crestDistance < 0.82) {
color.lerp(
ridgeColor,
THREE.MathUtils.smoothstep(crestDistance, 0.82, 0.08)
);
}
if (valleyDistance < 1.05) {
color.lerp(
bankColor,
0.58 * (1 - THREE.MathUtils.smoothstep(valleyDistance, 0.25, 1.05))
);
}
const variation =
0.035 * Math.sin(ix * 1.73 + iz * 0.91) +
0.025 * Math.cos(ix * 0.47 - iz * 1.31);
color.offsetHSL(0, 0, variation);
colors.push(color.r, color.g, color.b);
}
}
const row = SEGMENTS_X + 1;
for (let iz = 0; iz < SEGMENTS_Z; iz++) {
for (let ix = 0; ix < SEGMENTS_X; ix++) {
const a = iz * row + ix;
const b = a + 1;
const c = a + row;
const d = c + 1;
indices.push(a, c, b, b, c, d);
}
}
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const material = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.96,
metalness: 0,
flatShading: true
});
const terrain = new THREE.Mesh(geometry, material);
terrain.receiveShadow = true;
terrain.castShadow = true;
terrainGroup.add(terrain);
// A solid perimeter skirt closes the elevated terrain into a slab.
const perimeter = [];
for (let i = 0; i <= 32; i++) {
perimeter.push([
-WIDTH / 2 + (i / 32) * WIDTH,
DEPTH / 2
]);
}
for (let i = 1; i <= 28; i++) {
perimeter.push([
WIDTH / 2,
DEPTH / 2 - (i / 28) * DEPTH
]);
}
for (let i = 1; i <= 32; i++) {
perimeter.push([
WIDTH / 2 - (i / 32) * WIDTH,
-DEPTH / 2
]);
}
for (let i = 1; i <= 28; i++) {
perimeter.push([
-WIDTH / 2,
-DEPTH / 2 + (i / 28) * DEPTH
]);
}
const skirtPositions = [];
const skirtIndices = [];
const bottom = -1.48;
for (let i = 0; i < perimeter.length; i++) {
const a = perimeter[i];
const b = perimeter[(i + 1) % perimeter.length];
const ay = terrainHeight(a[0], a[1]);
const by = terrainHeight(b[0], b[1]);
const base = skirtPositions.length / 3;
skirtPositions.push(
a[0], ay, a[1],
b[0], by, b[1],
b[0], bottom, b[1],
a[0], bottom, a[1]
);
skirtIndices.push(
base, base + 1, base + 2,
base, base + 2, base + 3
);
}
const skirtGeometry = new THREE.BufferGeometry();
skirtGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(skirtPositions, 3)
);
skirtGeometry.setIndex(skirtIndices);
skirtGeometry.computeVertexNormals();
const skirt = new THREE.Mesh(
skirtGeometry,
new THREE.MeshStandardMaterial({
color: 0x4a5c47,
roughness: 1,
side: THREE.DoubleSide
})
);
skirt.castShadow = true;
skirt.receiveShadow = true;
terrainGroup.add(skirt);
const base = new THREE.Mesh(
new THREE.BoxGeometry(WIDTH, 0.3, DEPTH),
new THREE.MeshStandardMaterial({
color: 0x344638,
roughness: 1
})
);
base.position.y = -1.64;
base.receiveShadow = true;
terrainGroup.add(base);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(120, 120),
new THREE.MeshStandardMaterial({
color: 0xd4e3de,
roughness: 1
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -1.82;
ground.receiveShadow = true;
scene.add(ground);
}
addSolidTerrain();
// -------------------------------------------------------------------------
// Ridge ribbon and survey markers
// -------------------------------------------------------------------------
function addRidgeRibbon() {
const positions = [];
const indices = [];
for (let i = 0; i < 54; i++) {
const z0 = -13.7 + (i / 54) * 27.4;
const z1 = -13.7 + ((i + 1) / 54) * 27.4;
const c0 = ridgeCenter(z0);
const c1 = ridgeCenter(z1);
const base = positions.length / 3;
positions.push(
c0 - 0.22, terrainHeight(c0 - 0.22, z0) + 0.055, z0,
c0 + 0.22, terrainHeight(c0 + 0.22, z0) + 0.055, z0,
c1 + 0.22, terrainHeight(c1 + 0.22, z1) + 0.055, z1,
c1 - 0.22, terrainHeight(c1 - 0.22, z1) + 0.055, z1
);
indices.push(base, base + 1, base + 2, base, base + 2, base + 3);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const ribbon = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color: COLORS.ridge,
roughness: 0.82,
polygonOffset: true,
polygonOffsetFactor: -1,
polygonOffsetUnits: -1
})
);
ribbon.receiveShadow = true;
terrainGroup.add(ribbon);
const postGeometry = new THREE.CylinderGeometry(0.065, 0.09, 0.9, 6);
const capGeometry = new THREE.OctahedronGeometry(0.3, 0);
const postMaterial = new THREE.MeshStandardMaterial({
color: 0x40534b,
roughness: 0.9
});
const capMaterial = new THREE.MeshStandardMaterial({
color: COLORS.ridge,
roughness: 0.65,
emissive: COLORS.ridge,
emissiveIntensity: 0.08
});
for (let z = -12; z <= 12; z += 4) {
const x = ridgeCenter(z);
const y = terrainHeight(x, z);
const post = new THREE.Mesh(postGeometry, postMaterial);
post.position.set(x, y + 0.45, z);
post.castShadow = true;
const cap = new THREE.Mesh(capGeometry, capMaterial);
cap.position.set(x, y + 1.08, z);
cap.rotation.y = z * 0.2;
cap.castShadow = true;
terrainGroup.add(post, cap);
}
}
addRidgeRibbon();
// -------------------------------------------------------------------------
// Streams
// -------------------------------------------------------------------------
function streamPoint(side, z, lift = 0) {
const x = ridgeCenter(z) + side * VALLEY_DISTANCE;
return new THREE.Vector3(
x,
terrainHeight(x, z) + lift,
z
);
}
function addStream(side, color) {
const controls = [];
for (let z = -13.5; z <= 12.9; z += 0.75) {
controls.push(streamPoint(side, z, 0.06));
}
const curve = new THREE.CatmullRomCurve3(
controls,
false,
"catmullrom",
0.15
);
const bank = new THREE.Mesh(
new THREE.TubeGeometry(curve, 110, 0.3, 8, false),
new THREE.MeshStandardMaterial({
color: 0x365c50,
roughness: 0.95
})
);
bank.receiveShadow = true;
terrainGroup.add(bank);
const water = new THREE.Mesh(
new THREE.TubeGeometry(curve, 110, 0.16, 8, false),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.13,
roughness: 0.25,
metalness: 0.05
})
);
water.receiveShadow = true;
terrainGroup.add(water);
// Small solid arrows make the downstream direction explicit.
const arrowGeometry = new THREE.ConeGeometry(0.24, 0.72, 4);
const arrowMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color(color).lerp(new THREE.Color(0xffffff), 0.38),
roughness: 0.45,
emissive: color,
emissiveIntensity: 0.08
});
for (const z of [-8, -3, 2, 7, 11]) {
const p0 = streamPoint(side, z, 0.34);
const p1 = streamPoint(side, z + 0.5, 0.34);
const tangent = p1.clone().sub(p0).normalize();
const arrow = new THREE.Mesh(arrowGeometry, arrowMaterial);
arrow.position.copy(p0);
arrow.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
tangent
);
arrow.castShadow = true;
terrainGroup.add(arrow);
}
}
addStream(-1, COLORS.left);
addStream(1, COLORS.right);
// -------------------------------------------------------------------------
// Stylized low-poly trees
// -------------------------------------------------------------------------
function addTrees() {
let seed = 72341;
const random = () => {
seed = (1664525 * seed + 1013904223) >>> 0;
return seed / 4294967296;
};
const trunkGeometry = new THREE.CylinderGeometry(0.11, 0.16, 0.9, 6);
const crownGeometry = new THREE.ConeGeometry(0.72, 1.7, 6);
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x6f513a,
roughness: 1
});
const crownMaterial = new THREE.MeshStandardMaterial({
color: 0x416b52,
roughness: 0.96,
flatShading: true
});
let placed = 0;
let attempts = 0;
while (placed < 24 && attempts < 500) {
attempts++;
const x = -16.5 + random() * 33;
const z = -12.6 + random() * 24.8;
const d = Math.abs(x - ridgeCenter(z));
const distanceToStream = Math.abs(d - VALLEY_DISTANCE);
if (d < 1.35 || distanceToStream < 1.15) continue;
const y = terrainHeight(x, z);
const scale = 0.78 + random() * 0.48;
const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial);
trunk.position.set(x, y + 0.45 * scale, z);
trunk.scale.setScalar(scale);
trunk.castShadow = true;
const crown = new THREE.Mesh(crownGeometry, crownMaterial);
crown.position.set(x, y + 1.55 * scale, z);
crown.scale.set(scale, scale, scale);
crown.rotation.y = random() * Math.PI;
crown.castShadow = true;
terrainGroup.add(trunk, crown);
placed++;
}
}
addTrees();
// -------------------------------------------------------------------------
// Tracer routes and downhill-constrained movement
// -------------------------------------------------------------------------
function buildRoute(side, startZ) {
const points = [];
const cumulative = [];
// Approach: outward from the ridge toward the side's stream.
for (let i = 0; i <= 26; i++) {
const u = i / 26;
const z = startZ + u * 0.7;
const distance = THREE.MathUtils.lerp(1.8, VALLEY_DISTANCE, u);
const x = ridgeCenter(z) + side * distance;
points.push(new THREE.Vector3(x, terrainHeight(x, z), z));
}
// Downstream: follow the valley toward the front edge.
const flowStart = startZ + 0.7;
for (let i = 1; i <= 110; i++) {
const z = THREE.MathUtils.lerp(flowStart, 12.35, i / 110);
const x = ridgeCenter(z) + side * VALLEY_DISTANCE;
points.push(new THREE.Vector3(x, terrainHeight(x, z), z));
}
let length = 0;
cumulative.push(0);
for (let i = 1; i < points.length; i++) {
length += points[i].distanceTo(points[i - 1]);
cumulative.push(length);
}
return { points, cumulative, length };
}
function sampleRoute(route, distance) {
const target = THREE.MathUtils.clamp(distance, 0, route.length);
let low = 0;
let high = route.cumulative.length - 1;
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (route.cumulative[mid] < target) {
low = mid + 1;
} else {
high = mid;
}
}
const index = Math.max(1, low);
const previousDistance = route.cumulative[index - 1];
const nextDistance = route.cumulative[index];
const segmentLength = Math.max(nextDistance - previousDistance, 0.0001);
const alpha = (target - previousDistance) / segmentLength;
return route.points[index - 1].clone().lerp(
route.points[index],
THREE.MathUtils.clamp(alpha, 0, 1)
);
}
function staysInCatchment(side, point) {
const divide = ridgeCenter(point.z);
return side < 0 ? point.x < divide - 0.04 : point.x > divide + 0.04;
}
function isDownhill(current, candidate) {
const currentHeight = terrainHeight(current.x, current.z);
const candidateHeight = terrainHeight(candidate.x, candidate.z);
// The tiny tolerance prevents numerical noise from rejecting level flow.
return candidateHeight <= currentHeight + 0.006;
}
function downhillGradientStep(current, side, step) {
const epsilon = 0.12;
const gx =
(terrainHeight(current.x + epsilon, current.z) -
terrainHeight(current.x - epsilon, current.z)) /
(2 * epsilon);
const gz =
(terrainHeight(current.x, current.z + epsilon) -
terrainHeight(current.x, current.z - epsilon)) /
(2 * epsilon);
const direction = new THREE.Vector2(-gx, -gz);
if (direction.lengthSq() < 0.000001) return null;
direction.normalize();
const candidate = new THREE.Vector3(
current.x + direction.x * step,
0,
current.z + direction.y * step
);
if (!staysInCatchment(side, candidate)) return null;
if (!isDownhill(current, candidate)) return null;
return candidate;
}
const beadGeometry = new THREE.SphereGeometry(0.22, 14, 10);
const beadMaterials = {
left: new THREE.MeshStandardMaterial({
color: COLORS.left,
emissive: COLORS.left,
emissiveIntensity: 0.24,
roughness: 0.3
}),
right: new THREE.MeshStandardMaterial({
color: COLORS.right,
emissive: COLORS.right,
emissiveIntensity: 0.24,
roughness: 0.3
})
};
const beads = [];
function createBead(side, index, startZ) {
const x = ridgeCenter(startZ) + side * 1.8;
const ground = terrainHeight(x, startZ);
const mesh = new THREE.Mesh(
beadGeometry,
side < 0 ? beadMaterials.left : beadMaterials.right
);
mesh.castShadow = true;
mesh.position.set(x, ground + 4.8, startZ);
mesh.visible = false;
scene.add(mesh);
const bead = {
side,
index,
startZ,
route: buildRoute(side, startZ),
mesh,
state: "waiting",
age: 0,
delay: index * 0.85,
progress: 0,
verticalVelocity: 0,
doneTime: 0,
ground
};
beads.push(bead);
return bead;
}
function resetBead(bead, initialDelay = true) {
const x = ridgeCenter(bead.startZ) + bead.side * 1.8;
bead.ground = terrainHeight(x, bead.startZ);
bead.state = "waiting";
bead.age = 0;
bead.delay = initialDelay ? bead.index * 0.85 : 0.25;
bead.progress = 0;
bead.verticalVelocity = 0;
bead.doneTime = 0;
bead.mesh.visible = false;
bead.mesh.position.set(x, bead.ground + 4.8, bead.startZ);
}
function releaseTracers() {
beads.length = 0;
const startZ = [-8.4, -7.0, -5.6, -4.2];
startZ.forEach((z, i) => createBead(-1, i, z));
startZ.forEach((z, i) => createBead(1, i, z));
for (const bead of beads) {
bead.mesh.visible = true;
}
}
releaseTracers();
function updateBeads(dt, time) {
for (const bead of beads) {
bead.age += dt;
if (bead.state === "waiting") {
bead.mesh.visible = bead.age >= bead.delay;
if (bead.mesh.visible) {
bead.state = "dropping";
bead.verticalVelocity = 0;
}
continue;
}
if (bead.state === "dropping") {
bead.verticalVelocity -= 15 * dt;
bead.mesh.position.y += bead.verticalVelocity * dt;
const ground =
terrainHeight(bead.mesh.position.x, bead.mesh.position.z) +
0.24;
if (bead.mesh.position.y <= ground) {
bead.mesh.position.y = ground;
bead.verticalVelocity = 0;
bead.state = "sliding";
bead.progress = 0;
}
continue;
}
if (bead.state === "sliding") {
const speed = 2.65;
const nextDistance = Math.min(
bead.route.length,
bead.progress + speed * dt
);
const current = bead.mesh.position;
const candidate = sampleRoute(bead.route, nextDistance);
// Both conditions are mandatory:
// 1. terrain elevation cannot increase;
// 2. a bead cannot cross into the neighboring catchment.
if (
isDownhill(current, candidate) &&
staysInCatchment(bead.side, candidate)
) {
bead.progress = nextDistance;
bead.mesh.position.x = candidate.x;
bead.mesh.position.z = candidate.z;
} else {
// Gradient fallback also obeys the no-uphill rule.
const fallback = downhillGradientStep(
current,
bead.side,
speed * dt * 0.45
);
if (fallback) {
bead.mesh.position.x = fallback.x;
bead.mesh.position.z = fallback.z;
}
}
bead.ground = terrainHeight(
bead.mesh.position.x,
bead.mesh.position.z
);
bead.mesh.position.y =
bead.ground + 0.24 + Math.sin(time * 9 + bead.index) * 0.018;
if (bead.progress >= bead.route.length - 0.001) {
bead.state = "done";
bead.doneTime = 0;
}
continue;
}
if (bead.state === "done") {
bead.doneTime += dt;
bead.ground = terrainHeight(
bead.mesh.position.x,
bead.mesh.position.z
);
bead.mesh.position.y =
bead.ground + 0.25 + Math.sin(time * 3 + bead.index) * 0.045;
if (bead.doneTime > 2.3) {
resetBead(bead, false);
}
}
}
}
// -------------------------------------------------------------------------
// Custom orbit camera — no examples/addons are imported
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 1.2, -0.5);
let cameraTheta = 0.68;
let cameraPhi = 0.88;
let cameraRadius = 39;
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.cos(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.sin(cameraTheta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousPointerX;
const dy = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi + dy * 0.005,
0.28,
1.34
);
updateCamera();
});
function endDrag(event) {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius + event.deltaY * 0.025,
24,
66
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
// -------------------------------------------------------------------------
// Projected HTML labels
// -------------------------------------------------------------------------
const labelElements = {
ridge: document.querySelector("#ridge-label"),
left: document.querySelector("#left-label"),
right: document.querySelector("#right-label")
};
const projected = new THREE.Vector3();
function positionLabel(element, worldPosition) {
projected.copy(worldPosition).project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.15 &&
Math.abs(projected.y) < 1.15;
element.style.opacity = visible ? "1" : "0";
if (!visible) return;
const x = (projected.x * 0.5 + 0.5) * innerWidth;
const y = (-projected.y * 0.5 + 0.5) * innerHeight;
element.style.transform =
`translate(${x}px, ${y}px) translate(-50%, -50%)`;
}
function updateLabels() {
const ridgeZ = -1.5;
const ridgeX = ridgeCenter(ridgeZ);
positionLabel(
labelElements.ridge,
new THREE.Vector3(
ridgeX,
terrainHeight(ridgeX, ridgeZ) + 1.7,
ridgeZ
)
);
const streamZ = 7.2;
const leftX = ridgeCenter(streamZ) - VALLEY_DISTANCE;
const rightX = ridgeCenter(streamZ) + VALLEY_DISTANCE;
positionLabel(
labelElements.left,
new THREE.Vector3(
leftX,
terrainHeight(leftX, streamZ) + 0.85,
streamZ
)
);
positionLabel(
labelElements.right,
new THREE.Vector3(
rightX,
terrainHeight(rightX, streamZ) + 0.85,
streamZ
)
);
}
// -------------------------------------------------------------------------
// UI and animation loop
// -------------------------------------------------------------------------
let paused = false;
document.querySelector("#release").addEventListener("click", () => {
releaseTracers();
});
document.querySelector("#pause").addEventListener("click", (event) => {
paused = !paused;
event.currentTarget.textContent = paused ? "Resume" : "Pause";
});
const clock = new THREE.Clock();
let elapsed = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.035);
if (!paused) {
elapsed += dt;
updateBeads(dt, elapsed);
}
updateLabels();
renderer.render(scene, camera);
}
animate();
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
</script>
</body>
</html>
```