Prompt specification
Build or customize the Three.js 3D scene "Interactive watershed boundary explorer" 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: Interactive watershed boundary explorer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/interactive-watershed-boundary-explorer-x1196
Scene Description Prompt:
I'd like to see this as a voxel Three.js scene: interactive watershed boundary explorer. Let a cursor place rain markers on a compact heightfield; trace their descent to one of two outlets and display the watershed assignment without implying hydrologic forecasting. Use cdnjs and return one self-contained HTML file.
Working Three.js Starter (interactive-watershed-boundary-explorer-x1196):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voxel Watershed Boundary Explorer</title>
<style>
:root {
color-scheme: dark;
--bg: #071319;
--panel: rgba(9, 23, 30, 0.82);
--panel-strong: rgba(11, 29, 37, 0.94);
--line: rgba(190, 226, 230, 0.16);
--text: #e8f3f1;
--muted: #96abb0;
--a: #42b9b4;
--b: #e39a4f;
--rain: #76dcff;
--boundary: #f5f1df;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body { color: var(--text); }
#scene {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: crosshair;
}
#labels {
position: fixed;
inset: 0;
pointer-events: none;
overflow: hidden;
}
.panel {
position: fixed;
z-index: 10;
padding: 18px;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(15px);
-webkit-backdrop-filter: blur(15px);
}
.intro {
top: 20px;
left: 20px;
width: min(370px, calc(100vw - 40px));
}
.inspector {
top: 20px;
right: 20px;
width: min(320px, calc(100vw - 40px));
background: var(--panel-strong);
}
.eyebrow {
margin-bottom: 8px;
color: #82c8c6;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(22px, 3vw, 31px);
line-height: 1.06;
letter-spacing: -0.035em;
}
.intro-copy {
margin: 10px 0 14px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.notice {
margin-top: 14px;
padding: 11px 12px;
border: 1px solid rgba(227, 154, 79, 0.25);
border-radius: 10px;
background: rgba(227, 154, 79, 0.08);
color: #d8c5aa;
font-size: 11px;
line-height: 1.45;
}
.notice strong { color: #f0bd7c; }
.section-title {
margin: 17px 0 9px;
color: #d7e6e5;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.legend-row {
display: grid;
grid-template-columns: 13px 1fr auto;
gap: 9px;
align-items: center;
margin: 8px 0;
color: #bfd0d1;
font-size: 12px;
}
.swatch {
width: 11px;
height: 11px;
border-radius: 3px;
box-shadow: inset 0 0 0 1px rgba(255,255,255,.18);
}
.swatch.a { background: var(--a); }
.swatch.b { background: var(--b); }
.count {
min-width: 34px;
padding: 2px 7px;
border-radius: 999px;
background: rgba(255,255,255,.06);
color: #dce9e8;
text-align: right;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.readout {
min-height: 50px;
margin-bottom: 12px;
padding: 11px;
border: 1px solid rgba(255,255,255,.07);
border-radius: 10px;
background: rgba(255,255,255,.035);
color: #c7d8d8;
font-size: 12px;
line-height: 1.45;
}
.readout strong {
display: block;
margin-bottom: 3px;
color: #fff;
font-size: 14px;
}
.toggle {
display: flex;
align-items: center;
gap: 9px;
margin: 9px 0;
color: #bdcecf;
font-size: 12px;
cursor: pointer;
user-select: none;
}
.toggle input {
width: 15px;
height: 15px;
margin: 0;
accent-color: #56c3c0;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 14px;
}
button {
min-height: 36px;
padding: 8px 10px;
border: 1px solid rgba(255,255,255,.12);
border-radius: 9px;
background: rgba(255,255,255,.055);
color: #d9e7e6;
font: inherit;
font-size: 11px;
font-weight: 700;
cursor: pointer;
}
button:hover {
border-color: rgba(118,220,255,.35);
background: rgba(118,220,255,.09);
}
button:active { transform: translateY(1px); }
#status {
min-height: 28px;
margin-top: 10px;
color: #8fb7bb;
font-size: 10px;
line-height: 1.4;
}
.world-label {
position: absolute;
left: 0;
top: 0;
transform: translate(-50%, -100%);
padding: 6px 8px;
border: 1px solid rgba(255,255,255,.17);
border-radius: 8px;
background: rgba(4, 15, 20, .82);
box-shadow: 0 6px 18px rgba(0,0,0,.25);
white-space: nowrap;
font-size: 10px;
font-weight: 800;
letter-spacing: .04em;
will-change: left, top;
}
.world-label.outlet-a {
border-color: rgba(66,185,180,.48);
color: #a5eeea;
}
.world-label.outlet-b {
border-color: rgba(227,154,79,.48);
color: #ffd09b;
}
.world-label.rain {
border-color: rgba(118,220,255,.42);
color: #c5f3ff;
}
.world-label span {
margin-left: 5px;
color: #91a8ad;
font-weight: 600;
}
.footer {
position: fixed;
z-index: 8;
left: 50%;
bottom: 18px;
transform: translateX(-50%);
max-width: calc(100vw - 32px);
padding: 8px 13px;
border: 1px solid rgba(255,255,255,.09);
border-radius: 999px;
background: rgba(5, 17, 22, .72);
color: #91a9ad;
font-size: 10px;
text-align: center;
pointer-events: none;
backdrop-filter: blur(10px);
}
@media (max-width: 760px) {
.intro {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 14px;
}
.intro-copy { display: none; }
.intro .section-title { margin-top: 10px; }
.notice { margin-top: 10px; }
.inspector {
top: auto;
right: 10px;
bottom: 48px;
left: 10px;
width: auto;
padding: 13px;
}
.inspector .section-title { margin-top: 11px; }
.footer { bottom: 9px; }
}
</style>
</head>
<body>
<div id="scene"></div>
<div id="labels"></div>
<section class="panel intro">
<div class="eyebrow">Synthetic terrain · topology only</div>
<h1>Watershed Boundary Explorer</h1>
<p class="intro-copy">
Place rain markers on the voxel terrain. Each marker follows its downhill
path to one of two conceptual outlets, revealing the modeled watershed divide.
</p>
<div class="section-title">Outlet assignment</div>
<div class="legend-row">
<span class="swatch a"></span>
<span>Outlet A · West basin</span>
<span class="count" id="countA">0</span>
</div>
<div class="legend-row">
<span class="swatch b"></span>
<span>Outlet B · East basin</span>
<span class="count" id="countB">0</span>
</div>
<div class="notice">
<strong>Educational model only.</strong>
Routing is computed on a generated heightfield. It is not a rainfall,
runoff, flood, streamflow, or hydrologic forecasting tool.
</div>
</section>
<section class="panel inspector">
<div class="eyebrow">Interactive inspection</div>
<div class="readout" id="selectedReadout">
<strong>No rain marker selected</strong>
Click a voxel to place a marker. Click the same voxel again to remove it.
</div>
<div class="section-title">Visible layers</div>
<label class="toggle">
<input type="checkbox" id="boundaryToggle" checked />
Watershed boundary
</label>
<label class="toggle">
<input type="checkbox" id="networkToggle" checked />
Downhill network
</label>
<label class="toggle">
<input type="checkbox" id="traceToggle" checked />
Selected descent traces
</label>
<div class="section-title">Cursor cell</div>
<div class="readout" id="cursorReadout">
Move over the heightfield to inspect its conceptual outlet assignment.
</div>
<div class="buttons">
<button id="clearMarkers" type="button">Clear markers</button>
<button id="resetView" type="button">Reset camera</button>
</div>
<div id="status" aria-live="polite">Ready.</div>
</section>
<div class="footer">
Click to place / remove rain · drag to orbit · wheel to zoom · C clear · R reset view
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const W = 31;
const D = 21;
const CELL = 1;
const COUNT = W * D;
const EPSILON = 0.012;
const MAX_MARKERS = 12;
const sceneHost = document.getElementById("scene");
const labelHost = document.getElementById("labels");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071319);
scene.fog = new THREE.Fog(0x071319, 44, 88);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.1,
160
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
sceneHost.appendChild(renderer.domElement);
const ambient = new THREE.HemisphereLight(0xbee8ec, 0x152028, 1.65);
scene.add(ambient);
const sun = new THREE.DirectionalLight(0xfff1d4, 2.6);
sun.position.set(-13, 28, 17);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -27;
sun.shadow.camera.right = 27;
sun.shadow.camera.top = 27;
sun.shadow.camera.bottom = -27;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 75;
sun.shadow.bias = -0.0008;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x55bfd0, 1.0);
rimLight.position.set(18, 10, -18);
scene.add(rimLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(90, 90),
new THREE.MeshStandardMaterial({
color: 0x09161c,
roughness: 0.96,
metalness: 0.02
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.045;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(72, 72, 0x33535a, 0x1c3339);
grid.position.y = -0.025;
grid.material.transparent = true;
grid.material.opacity = 0.18;
scene.add(grid);
const indexOf = (x, z) => z * W + x;
const worldX = x => (x - (W - 1) / 2) * CELL;
const worldZ = z => (z - (D - 1) / 2) * CELL;
const outletA = { x: 0, z: D - 1, code: 1, name: "A", side: "West basin" };
const outletB = { x: W - 1, z: D - 1, code: 2, name: "B", side: "East basin" };
const rawHeight = new Float32Array(COUNT);
const effectiveHeight = new Float32Array(COUNT);
const parent = new Int32Array(COUNT);
const outletOf = new Uint8Array(COUNT);
parent.fill(-1);
// A synthetic, warped ridge field. The final downhill network is generated
// by a two-outlet priority flood, guaranteeing every voxel has a descending
// path to one of the two seeded outlets.
for (let z = 0; z < D; z++) {
const t = z / (D - 1);
const warp =
2.35 *
Math.sin(Math.PI * t) *
(0.72 + 0.28 * Math.cos(2 * Math.PI * t));
for (let x = 0; x < W; x++) {
const q = x - warp;
const vertical = D - 1 - z;
const distanceA = Math.hypot(q + 1.5, vertical);
const distanceB = Math.hypot(W - 1 - q + 1.5, vertical);
const roughness =
0.12 * Math.sin(x * 1.67 + z * 0.83) +
0.07 * Math.cos(x * 0.51 - z * 1.19) +
0.04 * Math.sin((x + z) * 2.31);
rawHeight[indexOf(x, z)] =
0.36 * Math.min(distanceA, distanceB) + roughness;
}
}
rawHeight[indexOf(outletA.x, outletA.z)] = 0;
rawHeight[indexOf(outletB.x, outletB.z)] = 0;
class MinHeap {
constructor() {
this.items = [];
this.sequence = 0;
}
less(a, b) {
return a.h < b.h || (a.h === b.h && a.seq < b.seq);
}
push(index, height) {
const item = { index, h: height, seq: this.sequence++ };
const items = this.items;
let i = items.length;
items.push(item);
while (i > 0) {
const parentIndex = (i - 1) >> 1;
if (!this.less(item, items[parentIndex])) break;
items[i] = items[parentIndex];
i = parentIndex;
}
items[i] = item;
}
pop() {
const items = this.items;
const root = items[0];
const last = items.pop();
if (items.length) {
let i = 0;
while (true) {
const left = i * 2 + 1;
const right = left + 1;
if (left >= items.length) break;
const child =
right < items.length && this.less(items[right], items[left])
? right
: left;
if (!this.less(items[child], last)) break;
items[i] = items[child];
i = child;
}
items[i] = last;
}
return root;
}
}
const heap = new MinHeap();
const visited = new Uint8Array(COUNT);
for (const outlet of [outletA, outletB]) {
const i = indexOf(outlet.x, outlet.z);
visited[i] = 1;
effectiveHeight[i] = 0;
outletOf[i] = outlet.code;
heap.push(i, 0);
}
const neighbors = [
[-1, -1], [0, -1], [1, -1],
[-1, 0], [1, 0],
[-1, 1], [0, 1], [1, 1]
];
while (heap.items.length) {
const current = heap.pop();
const currentIndex = current.index;
const x = currentIndex % W;
const z = Math.floor(currentIndex / W);
for (const [dx, dz] of neighbors) {
const nx = x + dx;
const nz = z + dz;
if (nx < 0 || nx >= W || nz < 0 || nz >= D) continue;
const nextIndex = indexOf(nx, nz);
if (visited[nextIndex]) continue;
visited[nextIndex] = 1;
parent[nextIndex] = currentIndex;
outletOf[nextIndex] = outletOf[currentIndex];
const filled = Math.max(
rawHeight[nextIndex],
effectiveHeight[currentIndex] + EPSILON
);
effectiveHeight[nextIndex] = filled;
heap.push(nextIndex, filled);
}
}
const cellTop = i => 0.30 + effectiveHeight[i] * 0.72;
const voxelGeometry = new THREE.BoxGeometry(CELL * 0.91, 1, CELL * 0.91);
const voxelMaterial = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.76,
metalness: 0.035,
flatShading: true
});
const voxels = new THREE.InstancedMesh(voxelGeometry, voxelMaterial, COUNT);
voxels.castShadow = true;
voxels.receiveShadow = true;
voxels.instanceMatrix.setUsage(THREE.StaticDrawUsage);
const dummy = new THREE.Object3D();
const colorA = new THREE.Color(0x42aaa8);
const colorB = new THREE.Color(0xd58a43);
const highlight = new THREE.Color(0xf3efe0);
let countA = 0;
let countB = 0;
for (let z = 0; z < D; z++) {
for (let x = 0; x < W; x++) {
const i = indexOf(x, z);
const top = cellTop(i);
dummy.position.set(worldX(x), top / 2, worldZ(z));
dummy.scale.set(1, top, 1);
dummy.updateMatrix();
voxels.setMatrixAt(i, dummy.matrix);
const color = outletOf[i] === 1 ? colorA : colorB;
const normalizedHeight = THREE.MathUtils.clamp(effectiveHeight[i] / 8, 0, 1);
const variation =
0.025 * Math.sin(x * 1.9 + z * 0.73) +
0.015 * Math.cos(z * 1.41 - x * 0.62);
const instanceColor = color
.clone()
.multiplyScalar(0.82 + normalizedHeight * 0.18 + variation)
.lerp(highlight, normalizedHeight * 0.035);
voxels.setColorAt(i, instanceColor);
if (outletOf[i] === 1) countA++;
else countB++;
}
}
voxels.instanceMatrix.needsUpdate = true;
voxels.instanceColor.needsUpdate = true;
voxels.computeBoundingBox();
voxels.computeBoundingSphere();
scene.add(voxels);
// The watershed divide is the set of edges between voxels assigned to
// different outlets.
const boundaryPoints = [];
let boundaryEdgeCount = 0;
for (let z = 0; z < D; z++) {
for (let x = 0; x < W; x++) {
const i = indexOf(x, z);
if (x + 1 < W) {
const j = indexOf(x + 1, z);
if (outletOf[i] !== outletOf[j]) {
const edgeX = worldX(x) + CELL / 2;
const edgeZ = worldZ(z);
boundaryPoints.push(
new THREE.Vector3(edgeX, cellTop(i) + 0.13, edgeZ),
new THREE.Vector3(edgeX, cellTop(j) + 0.13, edgeZ)
);
boundaryEdgeCount++;
}
}
if (z + 1 < D) {
const j = indexOf(x, z + 1);
if (outletOf[i] !== outletOf[j]) {
const edgeX = worldX(x);
const edgeZ = worldZ(z) + CELL / 2;
boundaryPoints.push(
new THREE.Vector3(edgeX, cellTop(i) + 0.13, edgeZ),
new THREE.Vector3(edgeX, cellTop(j) + 0.13, edgeZ)
);
boundaryEdgeCount++;
}
}
}
}
const boundaryMaterial = new THREE.LineBasicMaterial({
color: 0xf5f1df,
transparent: true,
opacity: 0.95,
depthWrite: false
});
const boundaryLine = new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(boundaryPoints),
boundaryMaterial
);
scene.add(boundaryLine);
// Faint network showing every generated downhill connection.
const networkPoints = [];
for (let i = 0; i < COUNT; i++) {
const p = parent[i];
if (p < 0) continue;
const x = i % W;
const z = Math.floor(i / W);
const px = p % W;
const pz = Math.floor(p / W);
networkPoints.push(
new THREE.Vector3(worldX(x), cellTop(i) + 0.065, worldZ(z)),
new THREE.Vector3(worldX(px), cellTop(p) + 0.065, worldZ(pz))
);
}
const networkLine = new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(networkPoints),
new THREE.LineBasicMaterial({
color: 0xd4ffff,
transparent: true,
opacity: 0.10,
depthWrite: false
})
);
scene.add(networkLine);
const labelEntries = [];
function addWorldLabel(className, html, position) {
const element = document.createElement("div");
element.className = `world-label ${className}`;
element.innerHTML = html;
labelHost.appendChild(element);
const entry = { element, position };
labelEntries.push(entry);
return entry;
}
function createOutletMarker(outlet, color) {
const i = indexOf(outlet.x, outlet.z);
const group = new THREE.Group();
group.position.set(worldX(outlet.x), cellTop(i), worldZ(outlet.z));
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.34, 0.055, 8, 24),
new THREE.MeshBasicMaterial({ color })
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.10;
group.add(ring);
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(0.11, 0.16, 0.60, 8),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.36,
roughness: 0.35
})
);
stem.position.y = 0.42;
group.add(stem);
const cap = new THREE.Mesh(
new THREE.OctahedronGeometry(0.18),
new THREE.MeshStandardMaterial({
color: 0xefffff,
emissive: color,
emissiveIntensity: 0.9,
roughness: 0.28
})
);
cap.position.y = 0.83;
group.add(cap);
scene.add(group);
const label = addWorldLabel(
`outlet-${outlet.name.toLowerCase()}`,
`OUTLET ${outlet.name}<span>${outlet.side}</span>`,
new THREE.Vector3(
worldX(outlet.x),
cellTop(i) + 1.22,
worldZ(outlet.z)
)
);
return { group, cap, label };
}
const outletMarkers = {
1: createOutletMarker(outletA, 0x57d2cb),
2: createOutletMarker(outletB, 0xffb15f)
};
const cursor = new THREE.LineSegments(
new THREE.EdgesGeometry(
new THREE.BoxGeometry(CELL * 0.96, 0.07, CELL * 0.96)
),
new THREE.LineBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.9,
depthTest: false
})
);
cursor.renderOrder = 8;
cursor.visible = false;
scene.add(cursor);
const rainRingGeometry = new THREE.TorusGeometry(0.24, 0.032, 8, 24);
const rainDropGeometry = new THREE.OctahedronGeometry(0.15, 0);
const rainStemGeometry = new THREE.CylinderGeometry(0.022, 0.022, 0.85, 6);
const pulseGeometry = new THREE.SphereGeometry(0.075, 10, 8);
const rainRingMaterial = new THREE.MeshBasicMaterial({
color: 0x76dcff,
transparent: true,
opacity: 0.9
});
const rainDropMaterial = new THREE.MeshStandardMaterial({
color: 0x8ce7ff,
emissive: 0x247aa7,
emissiveIntensity: 1.6,
roughness: 0.24
});
const rainStemMaterial = new THREE.MeshBasicMaterial({
color: 0x76dcff,
transparent: true,
opacity: 0.58
});
const traceMaterial = new THREE.LineBasicMaterial({
color: 0x9ceeff,
transparent: true,
opacity: 0.94,
depthWrite: false
});
const pulseMaterial = new THREE.MeshBasicMaterial({
color: 0xf2ffff,
transparent: true,
opacity: 0.95
});
const markers = [];
const markerByCell = new Map();
let selectedMarker = null;
let nextMarkerId = 1;
function pathForCell(cell) {
const points = [];
const lengths = [];
let total = 0;
let current = cell;
let previous = null;
while (current >= 0) {
const x = current % W;
const z = Math.floor(current / W);
const point = new THREE.Vector3(
worldX(x),
cellTop(current) + 0.16,
worldZ(z)
);
if (previous) {
total += point.distanceTo(previous);
lengths.push(total);
} else {
lengths.push(0);
}
points.push(point);
previous = point;
current = parent[current];
}
return { points, lengths, total };
}
function removeMarker(marker) {
marker.group.removeFromParent();
marker.pathLine.removeFromParent();
marker.pathLine.geometry.dispose();
marker.pulse.removeFromParent();
marker.label.element.remove();
markerByCell.delete(marker.cell);
const index = markers.indexOf(marker);
if (index >= 0) markers.splice(index, 1);
const labelIndex = labelEntries.indexOf(marker.label);
if (labelIndex >= 0) labelEntries.splice(labelIndex, 1);
if (selectedMarker === marker) {
selectedMarker = markers[markers.length - 1] || null;
}
}
function addMarker(cell) {
const existing = markerByCell.get(cell);
if (existing) {
removeMarker(existing);
updateUI("Marker removed.");
return;
}
if (markers.length >= MAX_MARKERS) {
removeMarker(markers[0]);
}
const id = nextMarkerId++;
const x = cell % W;
const z = Math.floor(cell / W);
const outletCode = outletOf[cell];
const outlet = outletCode === 1 ? outletA : outletB;
const group = new THREE.Group();
group.position.set(worldX(x), cellTop(cell), worldZ(z));
const ring = new THREE.Mesh(rainRingGeometry, rainRingMaterial);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.10;
group.add(ring);
const stem = new THREE.Mesh(rainStemGeometry, rainStemMaterial);
stem.position.y = 0.58;
group.add(stem);
const drop = new THREE.Mesh(rainDropGeometry, rainDropMaterial);
drop.position.y = 1.1;
group.add(drop);
scene.add(group);
const path = pathForCell(cell);
const pathLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(path.points),
traceMaterial
);
pathLine.renderOrder = 5;
scene.add(pathLine);
const pulse = new THREE.Mesh(pulseGeometry, pulseMaterial);
pulse.renderOrder = 6;
scene.add(pulse);
const label = addWorldLabel(
"rain",
`R${id}<span>→ ${outlet.name} · ${outlet.side}</span>`,
new THREE.Vector3(
worldX(x),
cellTop(cell) + 1.62,
worldZ(z)
)
);
const marker = {
id,
cell,
x,
z,
outlet,
group,
drop,
stem,
path,
pathLine,
pulse,
label,
phase: id * 0.271
};
markers.push(marker);
markerByCell.set(cell, marker);
selectedMarker = marker;
updateUI(
`Rain marker R${id} assigned to Outlet ${outlet.name} (${outlet.side}).`
);
}
function clearMarkers() {
[...markers].forEach(removeMarker);
selectedMarker = null;
updateUI("All rain markers cleared.");
}
function updateUI(message) {
document.getElementById("countA").textContent = countA.toLocaleString();
document.getElementById("countB").textContent = countB.toLocaleString();
const selectedReadout = document.getElementById("selectedReadout");
if (selectedMarker) {
selectedReadout.innerHTML = `
<strong>Rain marker R${selectedMarker.id}</strong>
Voxel ${selectedMarker.x + 1}.${selectedMarker.z + 1}
descends to Outlet ${selectedMarker.outlet.name} · ${selectedMarker.outlet.side}.
`;
} else {
selectedReadout.innerHTML = `
<strong>No rain marker selected</strong>
Click a voxel to place a marker. Click the same voxel again to remove it.
`;
}
if (message) {
document.getElementById("status").textContent = message;
}
}
const cameraTarget = new THREE.Vector3(0, 2.3, 0);
let azimuth = 0.42;
let polar = 0.88;
let cameraRadius = innerWidth < 700 ? 52 : 43;
function updateCamera() {
const horizontal = Math.sin(polar) * cameraRadius;
camera.position.set(
cameraTarget.x + Math.sin(azimuth) * horizontal,
cameraTarget.y + Math.cos(polar) * cameraRadius,
cameraTarget.z + Math.cos(azimuth) * horizontal
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
function resetCamera() {
azimuth = 0.42;
polar = 0.88;
cameraRadius = innerWidth < 700 ? 52 : 43;
updateCamera();
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let hoveredCell = -1;
function pickCell(event) {
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.intersectObject(voxels, false);
return hits.length ? hits[0].instanceId : -1;
}
function setHoveredCell(cell) {
hoveredCell = cell;
if (cell < 0) {
cursor.visible = false;
document.getElementById("cursorReadout").innerHTML = `
Move over the heightfield to inspect its conceptual outlet assignment.
`;
return;
}
const x = cell % W;
const z = Math.floor(cell / W);
const outlet = outletOf[cell] === 1 ? outletA : outletB;
cursor.visible = true;
cursor.position.set(worldX(x), cellTop(cell) + 0.08, worldZ(z));
document.getElementById("cursorReadout").innerHTML = `
<strong>Voxel ${x + 1}.${z + 1}</strong>
Conceptual downhill assignment: Outlet ${outlet.name} · ${outlet.side}.
`;
}
const canvas = renderer.domElement;
let pointerDown = false;
let pointerMoved = false;
let startX = 0;
let startY = 0;
let lastX = 0;
let lastY = 0;
canvas.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
pointerDown = true;
pointerMoved = false;
startX = lastX = event.clientX;
startY = lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
});
canvas.addEventListener("pointermove", event => {
if (pointerDown) {
const dx = event.clientX - lastX;
const dy = event.clientY - lastY;
if (Math.hypot(event.clientX - startX, event.clientY - startY) > 4) {
pointerMoved = true;
}
if (pointerMoved) {
azimuth -= dx * 0.006;
polar = THREE.MathUtils.clamp(polar - dy * 0.005, 0.38, 1.34);
updateCamera();
}
lastX = event.clientX;
lastY = event.clientY;
} else {
setHoveredCell(pickCell(event));
}
});
canvas.addEventListener("pointerup", event => {
if (!pointerDown) return;
if (!pointerMoved && event.button === 0) {
const cell = pickCell(event);
if (cell >= 0) addMarker(cell);
}
pointerDown = false;
canvas.style.cursor = hoveredCell >= 0 ? "crosshair" : "grab";
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
});
canvas.addEventListener("pointercancel", () => {
pointerDown = false;
pointerMoved = false;
canvas.style.cursor = "crosshair";
});
canvas.addEventListener("pointerleave", () => {
if (!pointerDown) setHoveredCell(-1);
});
canvas.addEventListener("wheel", event => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius + event.deltaY * 0.025,
24,
68
);
updateCamera();
}, { passive: false });
canvas.addEventListener("contextmenu", event => event.preventDefault());
document.getElementById("boundaryToggle").addEventListener("change", event => {
boundaryLine.visible = event.target.checked;
});
document.getElementById("networkToggle").addEventListener("change", event => {
networkLine.visible = event.target.checked;
});
document.getElementById("traceToggle").addEventListener("change", event => {
for (const marker of markers) {
marker.pathLine.visible = event.target.checked;
marker.pulse.visible = event.target.checked;
}
});
document.getElementById("clearMarkers").addEventListener("click", clearMarkers);
document.getElementById("resetView").addEventListener("click", resetCamera);
addEventListener("keydown", event => {
if (event.target instanceof HTMLInputElement) return;
if (event.key.toLowerCase() === "c") clearMarkers();
if (event.key.toLowerCase() === "r") resetCamera();
if (event.key.toLowerCase() === "b") {
const toggle = document.getElementById("boundaryToggle");
toggle.checked = !toggle.checked;
boundaryLine.visible = toggle.checked;
}
if (event.key.toLowerCase() === "f") {
const toggle = document.getElementById("traceToggle");
toggle.checked = !toggle.checked;
for (const marker of markers) {
marker.pathLine.visible = toggle.checked;
marker.pulse.visible = toggle.checked;
}
}
});
function samplePath(marker, progress) {
const target = progress * marker.path.total;
const lengths = marker.path.lengths;
for (let i = 1; i < marker.path.points.length; i++) {
if (target <= lengths[i]) {
const segmentLength = lengths[i] - lengths[i - 1];
const local = segmentLength > 0
? (target - lengths[i - 1]) / segmentLength
: 0;
return marker.path.points[i - 1].clone().lerp(
marker.path.points[i],
THREE.MathUtils.clamp(local, 0, 1)
);
}
}
return marker.path.points[marker.path.points.length - 1].clone();
}
const projected = new THREE.Vector3();
function updateLabels() {
const width = innerWidth;
const height = innerHeight;
for (const entry of labelEntries) {
projected.copy(entry.position).project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.15 &&
projected.x < 1.15 &&
projected.y > -1.15 &&
projected.y < 1.15;
entry.element.style.display = visible ? "block" : "none";
if (visible) {
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
entry.element.style.left = `${x}px`;
entry.element.style.top = `${y}px`;
}
}
}
function animate() {
requestAnimationFrame(animate);
const time = performance.now() * 0.001;
for (const marker of markers) {
const fall = (time * 0.58 + marker.phase) % 1;
marker.drop.position.y = 1.42 - fall * 1.02;
marker.stem.scale.y = 0.75 + fall * 0.25;
marker.stem.position.y = 0.50 + marker.stem.scale.y * 0.075;
const progress = (time * 0.13 + marker.phase) % 1;
marker.pulse.position.copy(samplePath(marker, progress));
}
const pulse = 1 + Math.sin(time * 2.4) * 0.08;
outletMarkers[1].cap.scale.setScalar(pulse);
outletMarkers[2].cap.scale.setScalar(2 - pulse);
renderer.render(scene, camera);
updateLabels();
}
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
});
updateCamera();
updateUI(
`${countA + countB} voxels routed across ${boundaryEdgeCount} boundary edges.`
);
animate();
</script>
</body>
</html>
```