Prompt specification
Build or customize the Three.js 3D scene "Rain beads around a drainage divide" 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 around a drainage divide
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/rain-beads-around-a-drainage-divide-x1358
Scene Description Prompt:
Make one HTML file using Three.js from cdnjs for this voxel scene: Create a small sloping terrain with a visible drainage divide. Animate rain beads following surface gradients, and keep each basin's particles within its own outlet network.
Working Three.js Starter (rain-beads-around-a-drainage-divide-x1358):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Drainage Basins</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(10, 19, 24, 0.82);
--line: rgba(255, 255, 255, 0.14);
--amber: #ffb34f;
--cyan: #50ddff;
--divide: #f2d06b;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #0a1318;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#app,
canvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
}
canvas {
touch-action: none;
}
.panel {
position: fixed;
z-index: 10;
top: 18px;
left: 18px;
width: min(360px, calc(100vw - 36px));
padding: 17px 18px;
border: 1px solid var(--line);
border-radius: 14px;
background: var(--panel);
color: #eef7f8;
box-shadow: 0 14px 40px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(12px);
pointer-events: none;
}
.eyebrow {
margin-bottom: 5px;
color: #9bb1b8;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(20px, 3vw, 28px);
line-height: 1.08;
letter-spacing: -0.025em;
}
.description {
margin: 10px 0 14px;
color: #b9c9ce;
font-size: 12px;
line-height: 1.55;
}
.legend {
display: grid;
gap: 7px;
padding-top: 12px;
border-top: 1px solid var(--line);
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
color: #d6e2e5;
font-size: 12px;
}
.swatch {
width: 19px;
height: 5px;
border-radius: 5px;
box-shadow: 0 0 12px currentColor;
}
.swatch.amber {
color: var(--amber);
background: var(--amber);
}
.swatch.cyan {
color: var(--cyan);
background: var(--cyan);
}
.swatch.divide {
color: var(--divide);
background: var(--divide);
}
.controls {
position: fixed;
z-index: 10;
right: 18px;
bottom: 18px;
padding: 9px 12px;
border: 1px solid var(--line);
border-radius: 999px;
background: var(--panel);
color: #b9c9ce;
font-size: 11px;
backdrop-filter: blur(12px);
pointer-events: none;
}
#labels {
position: fixed;
inset: 0;
z-index: 5;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
left: 0;
top: 0;
transform: translate(-50%, -50%);
padding: 5px 8px;
border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: 7px;
background: rgba(6, 13, 17, 0.72);
color: white;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
white-space: nowrap;
box-shadow: 0 5px 16px rgba(0, 0, 0, 0.24);
backdrop-filter: blur(7px);
}
#divide-label {
color: var(--divide);
}
#left-label {
color: var(--amber);
}
#right-label {
color: var(--cyan);
}
@media (max-width: 700px) {
.panel {
top: 10px;
left: 10px;
width: min(330px, calc(100vw - 20px));
padding: 13px 14px;
}
.description {
margin-bottom: 10px;
}
.controls {
right: 10px;
bottom: 10px;
}
}
</style>
</head>
<body>
<div id="app"></div>
<section class="panel">
<div class="eyebrow">Gradient-locked hydrology</div>
<h1>Two independent voxel watersheds</h1>
<p class="description">
A raised drainage divide splits the terrain into separate catchments.
Rain beads land on downhill channel beds, then remain inside their
matching outlet network.
</p>
<div class="legend">
<div class="legend-row">
<span class="swatch amber"></span>
Amber basin and outlet tree
</div>
<div class="legend-row">
<span class="swatch cyan"></span>
Cyan basin and outlet tree
</div>
<div class="legend-row">
<span class="swatch divide"></span>
Raised drainage divide
</div>
</div>
</section>
<div id="labels">
<div id="divide-label" class="world-label">Drainage divide</div>
<div id="left-label" class="world-label">Amber outlet</div>
<div id="right-label" class="world-label">Cyan outlet</div>
</div>
<div class="controls">Drag to orbit · Shift-drag to pan · Wheel 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";
// -------------------------------------------------------------------------
// Scene setup
// -------------------------------------------------------------------------
const app = document.querySelector("#app");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a1318);
scene.fog = new THREE.Fog(0x0a1318, 18, 34);
const camera = new THREE.PerspectiveCamera(
43,
innerWidth / innerHeight,
0.1,
70
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(devicePixelRatio, 1.8));
renderer.setSize(innerWidth, 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",
"Interactive voxel terrain showing two separate drainage basins"
);
app.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(
0xc6e6f2,
0x26352d,
2.15
);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1cf, 3.2);
sun.position.set(-5, 11, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 10;
sun.shadow.camera.top = 10;
sun.shadow.camera.bottom = -10;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 28;
sun.shadow.bias = -0.00025;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x5ac9ff, 1.15);
rimLight.position.set(7, 5, -8);
scene.add(rimLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
new THREE.MeshStandardMaterial({
color: 0x081015,
roughness: 1
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.39;
ground.receiveShadow = true;
scene.add(ground);
// -------------------------------------------------------------------------
// Dimensions and constants
// -------------------------------------------------------------------------
const TERRAIN_WIDTH = 12;
const TERRAIN_DEPTH = 10;
const GRID_X = 60;
const GRID_Z = 50;
const CELL_X = TERRAIN_WIDTH / GRID_X;
const CELL_Z = TERRAIN_DEPTH / GRID_Z;
const HEIGHT_STEP = 0.12;
const CHANNEL_RADIUS = 0.62;
const AMBER = new THREE.Color(0xffb34f);
const CYAN = new THREE.Color(0x50ddff);
const DIVIDE_COLOR = new THREE.Color(0xf2d06b);
const edgeById = new Map();
const channelSegments = [];
function smoothstep(min, max, value) {
const x = THREE.MathUtils.clamp((value - min) / (max - min), 0, 1);
return x * x * (3 - 2 * x);
}
function divideX(z) {
return 0.25 * Math.sin(z * 0.68);
}
// -------------------------------------------------------------------------
// Build independent outlet networks.
//
// Every edge points downhill. The `next` relationship creates a rooted
// tree ending at the corresponding basin's outlet. No route crosses the
// central divide.
// -------------------------------------------------------------------------
function makeNetwork(id, color) {
return {
id,
color,
edges: [],
feeders: [],
trunk: null,
outlet: null
};
}
const leftNetwork = makeNetwork("left", AMBER);
const rightNetwork = makeNetwork("right", CYAN);
function buildEdge(network, id, coordinates, nextId) {
const flatPoints = coordinates.map(
([x, , z]) => new THREE.Vector3(x, 0, z)
);
const flatCurve = new THREE.CatmullRomCurve3(
flatPoints,
false,
"centripetal"
);
const planarPoints = flatCurve.getSpacedPoints(48);
const distances = [0];
for (let i = 1; i < planarPoints.length; i++) {
distances.push(
distances[i - 1] +
planarPoints[i].distanceTo(planarPoints[i - 1])
);
}
const totalDistance = distances.at(-1);
const startHeight = coordinates[0][1];
const endHeight = coordinates.at(-1)[1];
// Reapply a strictly descending elevation along the smoothed path.
const samples = planarPoints.map((point, index) => {
const t = distances[index] / totalDistance;
return new THREE.Vector3(
point.x,
THREE.MathUtils.lerp(startHeight, endHeight, t),
point.z
);
});
const edge = {
id,
network,
next: nextId,
samples,
distances,
length: totalDistance,
start: samples[0].clone(),
end: samples.at(-1).clone()
};
network.edges.push(edge);
edgeById.set(id, edge);
for (let i = 0; i < samples.length - 1; i++) {
const a = samples[i];
const b = samples[i + 1];
const dx = b.x - a.x;
const dz = b.z - a.z;
channelSegments.push({
ax: a.x,
az: a.z,
ay: a.y,
bx: b.x,
bz: b.z,
by: b.y,
dx,
dz,
lengthSquared: dx * dx + dz * dz
});
}
return edge;
}
// Amber basin
buildEdge(leftNetwork, "L_A", [
[-0.45, 1.95, 3.30],
[-1.05, 1.74, 2.95],
[-1.70, 1.56, 2.25],
[-2.05, 1.40, 1.30]
], "L_CJ");
buildEdge(leftNetwork, "L_B", [
[-0.45, 1.96, 1.55],
[-1.25, 1.70, 1.40],
[-2.05, 1.40, 1.30]
], "L_CJ");
buildEdge(leftNetwork, "L_C", [
[-0.45, 1.96, -0.15],
[-1.30, 1.68, -0.55],
[-2.25, 1.40, -0.55]
], "L_FJ");
buildEdge(leftNetwork, "L_D", [
[-0.45, 1.93, -2.55],
[-1.10, 1.71, -2.30],
[-1.95, 1.52, -1.65],
[-2.25, 1.40, -0.55]
], "L_FJ");
buildEdge(leftNetwork, "L_CJ", [
[-2.05, 1.40, 1.30],
[-2.30, 1.32, 0.10]
], "L_TRUNK");
buildEdge(leftNetwork, "L_FJ", [
[-2.25, 1.40, -0.55],
[-2.30, 1.32, 0.10]
], "L_TRUNK");
buildEdge(leftNetwork, "L_TRUNK", [
[-2.30, 1.32, 0.10],
[-3.25, 1.14, 0.35],
[-4.25, 0.97, 0.05],
[-5.85, 0.75, 0.00]
], null);
leftNetwork.feeders = ["L_A", "L_B", "L_C", "L_D"];
leftNetwork.trunk = "L_TRUNK";
leftNetwork.outlet = new THREE.Vector3(-5.85, 0.75, 0);
// Cyan basin
buildEdge(rightNetwork, "R_A", [
[0.45, 1.95, -3.30],
[1.05, 1.74, -2.95],
[1.70, 1.56, -2.25],
[2.05, 1.40, -1.30]
], "R_CJ");
buildEdge(rightNetwork, "R_B", [
[0.45, 1.96, -1.55],
[1.25, 1.70, -1.40],
[2.05, 1.40, -1.30]
], "R_CJ");
buildEdge(rightNetwork, "R_C", [
[0.45, 1.96, 0.15],
[1.30, 1.68, 0.55],
[2.25, 1.40, 0.55]
], "R_FJ");
buildEdge(rightNetwork, "R_D", [
[0.45, 1.93, 2.55],
[1.10, 1.71, 2.30],
[1.95, 1.52, 1.65],
[2.25, 1.40, 0.55]
], "R_FJ");
buildEdge(rightNetwork, "R_CJ", [
[2.05, 1.40, -1.30],
[2.30, 1.32, -0.10]
], "R_TRUNK");
buildEdge(rightNetwork, "R_FJ", [
[2.25, 1.40, 0.55],
[2.30, 1.32, -0.10]
], "R_TRUNK");
buildEdge(rightNetwork, "R_TRUNK", [
[2.30, 1.32, -0.10],
[3.25, 1.14, -0.35],
[4.25, 0.97, -0.05],
[5.85, 0.75, 0.00]
], null);
rightNetwork.feeders = ["R_A", "R_B", "R_C", "R_D"];
rightNetwork.trunk = "R_TRUNK";
rightNetwork.outlet = new THREE.Vector3(5.85, 0.75, 0);
// -------------------------------------------------------------------------
// Continuous terrain used to carve the channel beds.
// -------------------------------------------------------------------------
function heightAt(x, z) {
const distanceFromDivide = x - divideX(z);
// Broad outward slopes plus a raised central ridge.
let height =
1.90 -
0.13 * Math.abs(distanceFromDivide) +
0.45 * Math.exp(-Math.pow(distanceFromDivide / 0.78, 2));
// Low-amplitude terrain variation.
height +=
0.055 *
Math.sin(x * 1.10 + z * 0.35) *
Math.cos(z * 0.90);
height += 0.025 * Math.sin(x * 2.20 - z * 0.60);
// Find the nearest channel segment.
let nearestDistance = Infinity;
let channelHeight = height;
for (const segment of channelSegments) {
const px = x - segment.ax;
const pz = z - segment.az;
const t = THREE.MathUtils.clamp(
(
px * segment.dx +
pz * segment.dz
) / Math.max(segment.lengthSquared, 0.000001),
0,
1
);
const nearestX = segment.ax + segment.dx * t;
const nearestZ = segment.az + segment.dz * t;
const distance = Math.hypot(x - nearestX, z - nearestZ);
if (distance < nearestDistance) {
nearestDistance = distance;
channelHeight = THREE.MathUtils.lerp(
segment.ay,
segment.by,
t
);
}
}
// Carve a smooth trench into the voxel terrain.
if (nearestDistance < CHANNEL_RADIUS) {
const influence =
1 - smoothstep(0.08, CHANNEL_RADIUS, nearestDistance);
height = THREE.MathUtils.lerp(
height,
channelHeight,
influence * 0.96
);
}
return height;
}
// -------------------------------------------------------------------------
// Voxel terrain
// -------------------------------------------------------------------------
const heights = new Float32Array(GRID_X * GRID_Z);
const blockGeometry = new THREE.BoxGeometry(
CELL_X * 0.94,
1,
CELL_Z * 0.94
);
const blockMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.92,
metalness: 0.02
});
const blocks = new THREE.InstancedMesh(
blockGeometry,
blockMaterial,
GRID_X * GRID_Z
);
blocks.castShadow = true;
blocks.receiveShadow = true;
blocks.frustumCulled = false;
const dummy = new THREE.Object3D();
const leftGround = new THREE.Color(0x315f58);
const rightGround = new THREE.Color(0x355f70);
const paleGround = new THREE.Color(0x718b78);
let blockIndex = 0;
for (let iz = 0; iz < GRID_Z; iz++) {
for (let ix = 0; ix < GRID_X; ix++) {
const x =
-TERRAIN_WIDTH / 2 + (ix + 0.5) * CELL_X;
const z =
-TERRAIN_DEPTH / 2 + (iz + 0.5) * CELL_Z;
const rawHeight = heightAt(x, z);
const quantizedHeight =
Math.max(0.24, Math.round(rawHeight / HEIGHT_STEP) * HEIGHT_STEP);
heights[iz * GRID_X + ix] = quantizedHeight;
dummy.position.set(x, quantizedHeight / 2, z);
dummy.scale.set(1, quantizedHeight, 1);
dummy.updateMatrix();
blocks.setMatrixAt(blockIndex, dummy.matrix);
const distanceFromDivide = Math.abs(x - divideX(z));
const isDivide = distanceFromDivide < 0.34;
const color = (x < divideX(z) ? leftGround : rightGround).clone();
const elevationTint = THREE.MathUtils.clamp(
(quantizedHeight - 0.7) / 1.7,
0,
1
);
color.lerp(paleGround, elevationTint * 0.28);
if (isDivide) {
color.lerp(DIVIDE_COLOR, 0.76);
}
const variation = 0.91 + Math.random() * 0.16;
color.multiplyScalar(variation);
blocks.setColorAt(blockIndex, color);
blockIndex++;
}
}
blocks.instanceMatrix.needsUpdate = true;
blocks.instanceColor.needsUpdate = true;
scene.add(blocks);
const platform = new THREE.Mesh(
new THREE.BoxGeometry(
TERRAIN_WIDTH + 0.42,
0.36,
TERRAIN_DEPTH + 0.42
),
new THREE.MeshStandardMaterial({
color: 0x15242a,
roughness: 0.85,
metalness: 0.08
})
);
platform.position.y = -0.18;
platform.receiveShadow = true;
platform.castShadow = true;
scene.add(platform);
function surfaceTopAt(x, z) {
const ix = THREE.MathUtils.clamp(
Math.floor((x + TERRAIN_WIDTH / 2) / CELL_X),
0,
GRID_X - 1
);
const iz = THREE.MathUtils.clamp(
Math.floor((z + TERRAIN_DEPTH / 2) / CELL_Z),
0,
GRID_Z - 1
);
return heights[iz * GRID_X + ix];
}
// -------------------------------------------------------------------------
// Drainage channels and outlets
// -------------------------------------------------------------------------
function edgePointAt(edge, distance) {
const d = THREE.MathUtils.clamp(distance, 0, edge.length);
let low = 0;
let high = edge.distances.length - 1;
while (low < high - 1) {
const middle = (low + high) >> 1;
if (edge.distances[middle] <= d) {
low = middle;
} else {
high = middle;
}
}
const startDistance = edge.distances[low];
const endDistance = edge.distances[high];
const span = Math.max(endDistance - startDistance, 0.000001);
const t = (d - startDistance) / span;
return new THREE.Vector3().lerpVectors(
edge.samples[low],
edge.samples[high],
t
);
}
function makeChannelTube(edge, radius, verticalOffset, material) {
const curvePoints = edge.samples.map(
(point) =>
new THREE.Vector3(
point.x,
surfaceTopAt(point.x, point.z) + verticalOffset,
point.z
)
);
const curve = new THREE.CatmullRomCurve3(
curvePoints,
false,
"centripetal"
);
const geometry = new THREE.TubeGeometry(
curve,
Math.max(18, Math.ceil(edge.length * 9)),
radius,
6,
false
);
const mesh = new THREE.Mesh(geometry, material);
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
for (const network of [leftNetwork, rightNetwork]) {
const grooveMaterial = new THREE.MeshBasicMaterial({
color: 0x0a1519,
transparent: true,
opacity: 0.84,
depthWrite: false
});
const flowMaterial = new THREE.MeshStandardMaterial({
color: network.color,
emissive: network.color,
emissiveIntensity: 1.2,
roughness: 0.32,
metalness: 0.05
});
for (const edge of network.edges) {
makeChannelTube(edge, 0.078, 0.004, grooveMaterial);
makeChannelTube(edge, 0.026, 0.048, flowMaterial);
}
// Outlet collection ring.
const outlet = network.outlet;
const outletY =
surfaceTopAt(outlet.x, outlet.z) + 0.065;
const outletRing = new THREE.Mesh(
new THREE.TorusGeometry(0.23, 0.038, 8, 28),
new THREE.MeshStandardMaterial({
color: network.color,
emissive: network.color,
emissiveIntensity: 1.35,
roughness: 0.25
})
);
outletRing.rotation.x = Math.PI / 2;
outletRing.position.set(outlet.x, outletY, outlet.z);
scene.add(outletRing);
const outletDisc = new THREE.Mesh(
new THREE.CircleGeometry(0.19, 28),
new THREE.MeshBasicMaterial({
color: network.color,
transparent: true,
opacity: 0.36,
side: THREE.DoubleSide,
depthWrite: false
})
);
outletDisc.rotation.x = -Math.PI / 2;
outletDisc.position.set(outlet.x, outletY - 0.01, outlet.z);
scene.add(outletDisc);
// Direction arrows on the lower trunk.
const trunk = edgeById.get(network.trunk);
const arrowGeometry = new THREE.ConeGeometry(
0.075,
0.19,
5
);
const arrowMaterial = new THREE.MeshStandardMaterial({
color: network.color,
emissive: network.color,
emissiveIntensity: 1.2,
roughness: 0.3
});
for (const fraction of [0.24, 0.53, 0.80]) {
const p1 = edgePointAt(trunk, trunk.length * fraction);
const p2 = edgePointAt(
trunk,
Math.min(trunk.length, trunk.length * fraction + 0.06)
);
const arrow = new THREE.Mesh(
arrowGeometry,
arrowMaterial
);
const tangent = p2.clone().sub(p1);
tangent.y = 0;
tangent.normalize();
arrow.position.set(
p1.x,
surfaceTopAt(p1.x, p1.z) + 0.17,
p1.z
);
arrow.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
tangent
);
scene.add(arrow);
}
// Glowing junctions.
const junctions = [
[-2.05, 1.30],
[-2.25, -0.55],
[-2.30, 0.10],
[2.05, -1.30],
[2.25, 0.55],
[2.30, -0.10]
];
for (const [x, z] of junctions) {
if (
Math.sign(x) !==
Math.sign(network.outlet.x)
) {
continue;
}
const junction = new THREE.Mesh(
new THREE.SphereGeometry(0.075, 10, 8),
new THREE.MeshStandardMaterial({
color: network.color,
emissive: network.color,
emissiveIntensity: 1.45,
roughness: 0.25
})
);
junction.position.set(
x,
surfaceTopAt(x, z) + 0.085,
z
);
scene.add(junction);
}
}
// -------------------------------------------------------------------------
// Raised drainage divide marker
// -------------------------------------------------------------------------
const dividePoints = [];
for (let i = 0; i <= 120; i++) {
const z = THREE.MathUtils.lerp(-4.9, 4.9, i / 120);
const x = divideX(z);
dividePoints.push(
new THREE.Vector3(
x,
surfaceTopAt(x, z) + 0.075,
z
)
);
}
const divideCurve = new THREE.CatmullRomCurve3(
dividePoints,
false,
"centripetal"
);
const divideMarker = new THREE.Mesh(
new THREE.TubeGeometry(divideCurve, 160, 0.023, 6, false),
new THREE.MeshBasicMaterial({
color: DIVIDE_COLOR
})
);
scene.add(divideMarker);
// -------------------------------------------------------------------------
// Rain bead particles
//
// A bead's complete route is fixed at spawn time. Its route can only
// follow edges belonging to one network, ensuring basin containment.
// -------------------------------------------------------------------------
const BEADS_PER_BASIN = 46;
const TOTAL_BEADS = BEADS_PER_BASIN * 2;
const beadGeometry = new THREE.SphereGeometry(0.075, 9, 7);
const beadMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff
});
const beadMesh = new THREE.InstancedMesh(
beadGeometry,
beadMaterial,
TOTAL_BEADS
);
beadMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
beadMesh.frustumCulled = false;
scene.add(beadMesh);
const beadData = [];
let beadIndex = 0;
function routeFrom(edgeId) {
const route = [];
let currentId = edgeId;
while (currentId) {
const edge = edgeById.get(currentId);
route.push(edge);
currentId = edge.next;
}
return route;
}
function spawnParticle(particle, network) {
const useFeeder = Math.random() < 0.84;
const startId = useFeeder
? network.feeders[
Math.floor(Math.random() * network.feeders.length)
]
: network.trunk;
particle.route = routeFrom(startId);
particle.routeIndex = 0;
particle.startFraction = 0.04 + Math.random() * 0.78;
particle.distance =
particle.route[0].length * particle.startFraction;
const point = edgePointAt(
particle.route[0],
particle.distance
);
const ground = Math.max(
point.y,
surfaceTopAt(point.x, point.z)
);
particle.x = point.x;
particle.z = point.z;
particle.y = ground + 1.4 + Math.random() * 4.2;
particle.ground = ground;
particle.fallSpeed = 3.8 + Math.random() * 2.7;
particle.flowSpeed = 0.82 + Math.random() * 0.58;
particle.state = "fall";
particle.poolTime = 0;
particle.scale = 1;
}
for (const network of [leftNetwork, rightNetwork]) {
for (let i = 0; i < BEADS_PER_BASIN; i++) {
const particle = {
network
};
spawnParticle(particle, network);
beadData.push(particle);
beadMesh.setColorAt(
beadIndex,
network.color
);
beadIndex++;
}
}
beadMesh.instanceColor.needsUpdate = true;
function updateBeads(delta) {
for (let i = 0; i < beadData.length; i++) {
const particle = beadData[i];
if (particle.state === "fall") {
particle.y -= particle.fallSpeed * delta;
particle.scale = 0.92;
if (particle.y <= particle.ground + 0.095) {
particle.y = particle.ground + 0.095;
particle.state = "runoff";
}
} else if (particle.state === "runoff") {
let edge =
particle.route[particle.routeIndex];
while (
particle.distance >= edge.length &&
particle.state === "runoff"
) {
particle.distance -= edge.length;
if (
particle.routeIndex + 1 <
particle.route.length
) {
particle.routeIndex++;
edge = particle.route[particle.routeIndex];
} else {
particle.state = "pool";
particle.poolTime = 1.1 + Math.random() * 1.3;
const outlet = particle.network.outlet;
particle.x = outlet.x;
particle.z = outlet.z;
particle.ground = surfaceTopAt(
outlet.x,
outlet.z
);
particle.y = particle.ground + 0.115;
}
}
if (particle.state === "runoff") {
const point = edgePointAt(
edge,
particle.distance
);
particle.x = point.x;
particle.z = point.z;
particle.y =
Math.max(
point.y,
surfaceTopAt(point.x, point.z)
) + 0.105;
particle.scale = 1;
}
} else if (particle.state === "pool") {
particle.poolTime -= delta;
particle.y =
particle.ground +
0.115 +
Math.sin(performance.now() * 0.008 + i) * 0.018;
particle.scale = THREE.MathUtils.clamp(
particle.poolTime / 0.65,
0.15,
1
);
if (particle.poolTime <= 0) {
spawnParticle(
particle,
particle.network
);
}
}
dummy.position.set(
particle.x,
particle.y,
particle.z
);
dummy.scale.setScalar(particle.scale);
dummy.updateMatrix();
beadMesh.setMatrixAt(i, dummy.matrix);
}
beadMesh.instanceMatrix.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Custom orbit, pan, and zoom controls
// -------------------------------------------------------------------------
const orbit = {
yaw: 0.72,
pitch: 0.60,
radius: 14.8,
target: new THREE.Vector3(0, 1.05, 0)
};
function updateCamera() {
const horizontal = orbit.radius * Math.cos(orbit.pitch);
camera.position.set(
orbit.target.x +
horizontal * Math.sin(orbit.yaw),
orbit.target.y +
orbit.radius * Math.sin(orbit.pitch),
orbit.target.z +
horizontal * Math.cos(orbit.yaw)
);
camera.lookAt(orbit.target);
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener(
"pointerdown",
(event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
}
);
renderer.domElement.addEventListener(
"pointermove",
(event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
if (event.shiftKey) {
const right = new THREE.Vector3(
Math.cos(orbit.yaw),
0,
-Math.sin(orbit.yaw)
);
const forward = new THREE.Vector3(
-Math.sin(orbit.yaw),
0,
-Math.cos(orbit.yaw)
);
const panScale = orbit.radius * 0.0014;
orbit.target.addScaledVector(
right,
-dx * panScale
);
orbit.target.addScaledVector(
forward,
dy * panScale
);
orbit.target.x = THREE.MathUtils.clamp(
orbit.target.x,
-4,
4
);
orbit.target.z = THREE.MathUtils.clamp(
orbit.target.z,
-4,
4
);
} else {
orbit.yaw -= dx * 0.006;
orbit.pitch = THREE.MathUtils.clamp(
orbit.pitch + dy * 0.005,
0.18,
1.28
);
}
updateCamera();
}
);
function stopDragging(event) {
dragging = false;
if (
renderer.domElement.hasPointerCapture?.(event.pointerId)
) {
renderer.domElement.releasePointerCapture(
event.pointerId
);
}
}
renderer.domElement.addEventListener(
"pointerup",
stopDragging
);
renderer.domElement.addEventListener(
"pointercancel",
stopDragging
);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
8.2,
24
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener(
"dblclick",
() => {
orbit.yaw = 0.72;
orbit.pitch = 0.60;
orbit.radius = 14.8;
orbit.target.set(0, 1.05, 0);
updateCamera();
}
);
updateCamera();
// -------------------------------------------------------------------------
// World-space labels
// -------------------------------------------------------------------------
const divideLabel = document.querySelector("#divide-label");
const leftLabel = document.querySelector("#left-label");
const rightLabel = document.querySelector("#right-label");
function placeLabel(element, position) {
const projected = position.clone().project(camera);
if (
projected.z < -1 ||
projected.z > 1 ||
Math.abs(projected.x) > 1.2 ||
Math.abs(projected.y) > 1.2
) {
element.style.opacity = "0";
return;
}
element.style.opacity = "1";
element.style.left =
`${(projected.x * 0.5 + 0.5) * innerWidth}px`;
element.style.top =
`${(-projected.y * 0.5 + 0.5) * innerHeight}px`;
}
function updateLabels() {
placeLabel(
divideLabel,
new THREE.Vector3(
divideX(0),
surfaceTopAt(0, 0) + 0.72,
0
)
);
placeLabel(
leftLabel,
new THREE.Vector3(
leftNetwork.outlet.x,
surfaceTopAt(
leftNetwork.outlet.x,
leftNetwork.outlet.z
) + 0.34,
leftNetwork.outlet.z
)
);
placeLabel(
rightLabel,
new THREE.Vector3(
rightNetwork.outlet.x,
surfaceTopAt(
rightNetwork.outlet.x,
rightNetwork.outlet.z
) + 0.34,
rightNetwork.outlet.z
)
);
}
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function resize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(
Math.min(devicePixelRatio, 1.8)
);
renderer.setSize(innerWidth, innerHeight);
}
addEventListener("resize", resize);
const clock = new THREE.Clock();
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
updateBeads(delta);
camera.updateMatrixWorld();
updateLabels();
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```