Prompt specification
Build or customize the Three.js 3D scene "Sediment Tokens Meet a Vegetated Strip" 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: Sediment Tokens Meet a Vegetated Strip
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/sediment-tokens-meet-a-vegetated-strip-x3966
Scene Description Prompt:
Make one HTML file using Three.js from cdnjs for this voxel scene: Animate a clearly qualitative runoff model with sediment markers and a vegetated buffer. Track retained and transported markers under a declared toy rule.
Working Three.js Starter (sediment-tokens-meet-a-vegetated-strip-x3966):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Runoff — Sediment Fate Model</title>
<style>
:root {
--bg: #07111f;
--panel: rgba(9, 20, 34, 0.88);
--line: rgba(151, 190, 219, 0.18);
--text: #e8f2fa;
--muted: #9db2c5;
--cyan: #38bdf8;
--amber: #ff8a3d;
--yellow: #facc15;
--pink: #ec4899;
--green: #65a30d;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#viewport {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
#panel {
position: fixed;
z-index: 10;
top: 18px;
left: 18px;
width: 350px;
max-height: calc(100vh - 36px);
overflow: hidden;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.36);
backdrop-filter: blur(14px);
}
#panel header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
padding: 17px 18px 12px;
}
.kicker {
margin-bottom: 4px;
color: #73d4ff;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 23px;
line-height: 1.05;
letter-spacing: -0.035em;
}
.subtitle {
margin: 8px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
#collapse {
width: 29px;
height: 29px;
flex: 0 0 auto;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(255, 255, 255, 0.04);
color: var(--text);
cursor: pointer;
font-size: 18px;
}
#panel.collapsed {
width: 250px;
}
#panel.collapsed .panel-body {
display: none;
}
.panel-body {
max-height: calc(100vh - 105px);
overflow-y: auto;
padding: 0 18px 18px;
scrollbar-width: thin;
scrollbar-color: #355068 transparent;
}
.stats {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
margin: 5px 0 14px;
}
.stat {
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.035);
}
.stat strong {
display: block;
font-size: 22px;
line-height: 1;
font-variant-numeric: tabular-nums;
}
.stat span {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stat.active strong {
color: var(--amber);
}
.stat.retained strong {
color: var(--yellow);
}
.stat.transported strong {
color: var(--pink);
}
.section-title {
margin: 15px 0 8px;
color: #cfe6f6;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.rule {
margin: 0;
padding: 12px 13px 12px 30px;
border: 1px solid rgba(101, 163, 13, 0.3);
border-radius: 12px;
background: rgba(52, 91, 28, 0.13);
color: #d8e8d3;
font-size: 11.5px;
line-height: 1.55;
}
.rule li + li {
margin-top: 7px;
}
.rule b {
color: #f4fbef;
}
.warning {
margin: 9px 0 0;
color: #8fa6b8;
font-size: 10.5px;
line-height: 1.4;
}
.legend {
display: grid;
gap: 7px;
font-size: 11px;
color: #c5d5e1;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
}
.swatch {
width: 11px;
height: 11px;
flex: 0 0 auto;
border-radius: 2px;
box-shadow: 0 0 10px currentColor;
}
.swatch.water {
color: var(--cyan);
background: var(--cyan);
}
.swatch.sediment {
color: var(--amber);
background: var(--amber);
}
.swatch.retained {
color: var(--yellow);
background: var(--yellow);
}
.swatch.transported {
color: var(--pink);
background: var(--pink);
}
.swatch.vegetation {
color: var(--green);
background: var(--green);
}
.controls {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 7px;
margin-top: 15px;
}
button.control {
min-height: 34px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.055);
color: var(--text);
cursor: pointer;
font: inherit;
font-size: 11px;
font-weight: 700;
transition:
background 120ms ease,
transform 120ms ease;
}
button.control:hover {
background: rgba(255, 255, 255, 0.11);
transform: translateY(-1px);
}
button.control.primary {
border-color: rgba(56, 189, 248, 0.45);
background: rgba(14, 116, 144, 0.35);
}
.pulse-row {
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 8px;
margin-top: 11px;
color: var(--muted);
font-size: 9.5px;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.pulse-track {
height: 4px;
overflow: hidden;
border-radius: 4px;
background: rgba(255, 255, 255, 0.09);
}
#pulse-fill {
display: block;
width: 100%;
height: 100%;
transform: scaleX(0);
transform-origin: left;
background: linear-gradient(90deg, #38bdf8, #a5f3fc);
}
#orbit-hint {
position: fixed;
z-index: 5;
top: 19px;
right: 20px;
padding: 9px 12px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(7, 17, 31, 0.72);
color: #a9bed0;
font-size: 10px;
letter-spacing: 0.05em;
pointer-events: none;
backdrop-filter: blur(8px);
}
#inspect {
position: fixed;
z-index: 5;
right: 20px;
bottom: 20px;
max-width: 330px;
padding: 11px 13px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(7, 17, 31, 0.82);
color: #b8cad8;
font-size: 10.5px;
line-height: 1.45;
pointer-events: none;
backdrop-filter: blur(8px);
}
.world-label {
position: fixed;
z-index: 4;
top: 0;
left: 0;
padding: 7px 10px;
border: 1px solid rgba(143, 206, 255, 0.25);
border-left: 3px solid #65a30d;
border-radius: 7px;
background: rgba(7, 17, 31, 0.82);
color: #eaf6ff;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
white-space: nowrap;
pointer-events: none;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.3);
}
.world-label small {
display: block;
margin-top: 3px;
color: #91a9bb;
font-size: 8px;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: none;
}
#outlet-label {
border-left-color: #ec4899;
}
@media (max-width: 720px) {
#panel {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
max-height: 49vh;
}
#panel.collapsed {
width: calc(100vw - 20px);
}
.panel-body {
max-height: calc(49vh - 76px);
}
#orbit-hint {
display: none;
}
#inspect {
right: 10px;
bottom: 10px;
left: 10px;
max-width: none;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<section id="panel">
<header>
<div>
<div class="kicker">Voxel watershed / toy model</div>
<h1>Runoff & Sediment Fate</h1>
<p class="subtitle">
Follow sediment from an eroding slope into a vegetated buffer and
downstream collection tray.
</p>
</div>
<button id="collapse" type="button" aria-label="Collapse panel">−</button>
</header>
<div class="panel-body">
<div class="stats" aria-live="polite">
<div class="stat active">
<strong id="suspended-count">0</strong>
<span>Suspended</span>
</div>
<div class="stat retained">
<strong id="retained-count">0</strong>
<span>Retained</span>
</div>
<div class="stat transported">
<strong id="transported-count">0</strong>
<span>Transported</span>
</div>
<div class="stat">
<strong id="retention-rate">0%</strong>
<span>Observed retention</span>
</div>
</div>
<div class="section-title">Declared toy rule</div>
<ol class="rule">
<li>
<b>Flow:</b> runoff chooses the lowest of the eight neighboring
elevation cells.
</li>
<li>
<b>Pulse:</b> each suspended marker advances at most one cell per
0.58-second pulse.
</li>
<li>
<b>Capture:</b> if the next cell is vegetated, retain the marker with
probability <b>p = 0.62</b>. Randomness is seeded and reproducible.
</li>
<li>
<b>Exit:</b> crossing the right edge counts as transported. A marker
with no downhill neighbor is retained as deposited sediment.
</li>
</ol>
<p class="warning">
This is a deliberately qualitative rule set, not a calibrated hydrologic
or erosion forecast.
</p>
<div class="section-title">Legend</div>
<div class="legend">
<div class="legend-row">
<span class="swatch water"></span>
<span>Cyan dashes show runoff direction</span>
</div>
<div class="legend-row">
<span class="swatch sediment"></span>
<span>Orange voxel = suspended sediment</span>
</div>
<div class="legend-row">
<span class="swatch retained"></span>
<span>Yellow voxel = retained in buffer</span>
</div>
<div class="legend-row">
<span class="swatch transported"></span>
<span>Magenta voxel = transported to outlet</span>
</div>
<div class="legend-row">
<span class="swatch vegetation"></span>
<span>Green voxel clusters = vegetated buffer</span>
</div>
</div>
<div class="controls">
<button id="pause" class="control primary" type="button">Pause</button>
<button id="step" class="control" type="button">Step pulse</button>
<button id="reset" class="control" type="button">Reset</button>
</div>
<div class="pulse-row">
<span>Next pulse</span>
<div class="pulse-track"><i id="pulse-fill"></i></div>
<span id="pulse-number">Pulse 0</span>
</div>
</div>
</section>
<div id="orbit-hint">DRAG TO ORBIT · WHEEL TO ZOOM · CLICK A VOXEL TO INSPECT</div>
<div id="inspect">Click a terrain voxel to inspect its elevation and next flow cell.</div>
<div id="buffer-label" class="world-label">
Vegetated buffer
<small>capture probability = 0.62</small>
</div>
<div id="outlet-label" class="world-label">
Transported outlet
<small>magenta collection tray</small>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Configuration
// ------------------------------------------------------------
const COLS = 29;
const ROWS = 21;
const CELL = 1;
const TOTAL_MARKERS = 96;
const CAPTURE_PROBABILITY = 0.62;
const PULSE_SECONDS = 0.58;
const viewport = document.getElementById("viewport");
const suspendedCountEl = document.getElementById("suspended-count");
const retainedCountEl = document.getElementById("retained-count");
const transportedCountEl = document.getElementById("transported-count");
const retentionRateEl = document.getElementById("retention-rate");
const pulseFillEl = document.getElementById("pulse-fill");
const pulseNumberEl = document.getElementById("pulse-number");
const inspectEl = document.getElementById("inspect");
const pauseButton = document.getElementById("pause");
const stepButton = document.getElementById("step");
const resetButton = document.getElementById("reset");
const panel = document.getElementById("panel");
const collapseButton = document.getElementById("collapse");
const colors = {
suspended: new THREE.Color(0xff8a3d),
retained: new THREE.Color(0xfacc15),
transported: new THREE.Color(0xec4899),
};
// ------------------------------------------------------------
// Renderer, scene, camera
// ------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
viewport.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 56, 105);
const camera = new THREE.OrthographicCamera(-20, 20, 15, -15, 0.1, 160);
const cameraTarget = new THREE.Vector3(1.4, 3.7, 0);
const cameraRadius = 46;
let cameraAzimuth = 0.88;
let cameraElevation = 0.61;
let cameraZoom = 1;
scene.add(new THREE.HemisphereLight(0xbfe9ff, 0x1b2634, 2.1));
const sun = new THREE.DirectionalLight(0xfff0d2, 3.0);
sun.position.set(-13, 27, 15);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -32;
sun.shadow.camera.right = 32;
sun.shadow.camera.top = 28;
sun.shadow.camera.bottom = -28;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 85;
sun.shadow.bias = -0.0005;
sun.target.position.copy(cameraTarget);
scene.add(sun, sun.target);
const rimLight = new THREE.DirectionalLight(0x56c9ff, 1.1);
rimLight.position.set(18, 10, -18);
scene.add(rimLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(180, 180),
new THREE.MeshStandardMaterial({
color: 0x081321,
roughness: 0.94,
metalness: 0,
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.72;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(90, 90, 0x1b3a54, 0x10283b);
grid.position.y = -0.705;
grid.material.transparent = true;
grid.material.opacity = 0.34;
scene.add(grid);
// ------------------------------------------------------------
// Terrain and vegetation definitions
// ------------------------------------------------------------
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function worldX(x) {
return (x - (COLS - 1) / 2) * CELL;
}
function worldZ(z) {
return (z - (ROWS - 1) / 2) * CELL;
}
function centerZ(x) {
return 10 + 1.15 * Math.sin((x - 1) * 0.24);
}
function rawElevation(x, z) {
const distanceFromChannel = z - centerZ(x);
return (
10.4 -
0.35 * x +
0.62 * (1 - Math.exp(-(distanceFromChannel ** 2) / 7)) +
0.025 * Math.sin(x * 0.71 + z * 1.13)
);
}
function terrainLevel(x, z) {
return Math.max(
0.48,
Math.round(rawElevation(x, z) / 0.24) * 0.24
);
}
function isVegetated(x, z) {
const upstreamPatch = z >= 2 && z <= 7;
const downstreamPatch = z >= 14 && z <= 19;
return x >= 8 && x <= 12 && (upstreamPatch || downstreamPatch);
}
function isChannel(x, z) {
return Math.abs(z - centerZ(x)) < 1.45;
}
function addBox(width, height, depth, color, x, y, z) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0.02,
})
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
// Main voxel slab.
addBox(COLS + 0.7, 0.65, ROWS + 0.7, 0x142235, 0, -0.35, 0);
// Terrain voxels.
const terrainData = [];
const terrainGeometry = new THREE.BoxGeometry(0.96, 1, 0.96);
const terrainMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.94,
metalness: 0,
});
const terrainMesh = new THREE.InstancedMesh(
terrainGeometry,
terrainMaterial,
COLS * ROWS
);
terrainMesh.castShadow = true;
terrainMesh.receiveShadow = true;
const dummy = new THREE.Object3D();
const instanceColor = new THREE.Color();
const earthUpstream = new THREE.Color(0x77634f);
const earthDownstream = new THREE.Color(0x53604c);
for (let z = 0; z < ROWS; z++) {
for (let x = 0; x < COLS; x++) {
const index = z * COLS + x;
const level = terrainLevel(x, z);
const vegetated = isVegetated(x, z);
const channel = isChannel(x, z);
terrainData.push({ x, z, level, vegetated, channel });
dummy.position.set(worldX(x), level / 2, worldZ(z));
dummy.rotation.set(0, 0, 0);
dummy.scale.set(1, level, 1);
dummy.updateMatrix();
terrainMesh.setMatrixAt(index, dummy.matrix);
if (vegetated) {
instanceColor.set(0x315b38);
} else if (channel) {
instanceColor.set(0x315b68);
} else {
instanceColor
.copy(earthUpstream)
.lerp(earthDownstream, x / (COLS - 1));
}
const shade = (((x * 17 + z * 31) % 9) - 4) * 0.009;
instanceColor.offsetHSL(0, 0, shade);
terrainMesh.setColorAt(index, instanceColor);
}
}
terrainMesh.instanceMatrix.needsUpdate = true;
terrainMesh.instanceColor.needsUpdate = true;
terrainMesh.computeBoundingSphere();
scene.add(terrainMesh);
// ------------------------------------------------------------
// Voxel vegetation
// ------------------------------------------------------------
const trunkInstances = [];
const canopyInstances = [];
for (let z = 0; z < ROWS; z++) {
for (let x = 0; x < COLS; x++) {
if (!isVegetated(x, z)) continue;
const level = terrainLevel(x, z);
const wx = worldX(x);
const wz = worldZ(z);
const isTree = (x * 3 + z * 5) % 4 === 0;
if (isTree) {
trunkInstances.push({
position: new THREE.Vector3(wx + 0.27, level + 0.36, wz - 0.2),
scale: new THREE.Vector3(0.16, 0.72, 0.16),
});
canopyInstances.push({
position: new THREE.Vector3(wx + 0.27, level + 0.84, wz - 0.2),
scale: new THREE.Vector3(0.66, 0.58, 0.66),
color: new THREE.Color(0x3f7f2f),
});
canopyInstances.push({
position: new THREE.Vector3(wx + 0.27, level + 1.18, wz - 0.2),
scale: new THREE.Vector3(0.48, 0.46, 0.48),
color: new THREE.Color(0x57962f),
});
canopyInstances.push({
position: new THREE.Vector3(wx + 0.27, level + 1.46, wz - 0.2),
scale: new THREE.Vector3(0.27, 0.3, 0.27),
color: new THREE.Color(0x78ad38),
});
} else {
canopyInstances.push({
position: new THREE.Vector3(wx + 0.24, level + 0.22, wz - 0.2),
scale: new THREE.Vector3(0.47, 0.39, 0.47),
color: new THREE.Color(0x4b8a31),
});
canopyInstances.push({
position: new THREE.Vector3(wx + 0.37, level + 0.43, wz - 0.28),
scale: new THREE.Vector3(0.29, 0.3, 0.29),
color: new THREE.Color(0x69a238),
});
}
}
}
const trunkMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0x765039,
roughness: 1,
}),
trunkInstances.length
);
trunkInstances.forEach((item, index) => {
dummy.position.copy(item.position);
dummy.rotation.set(0, 0, 0);
dummy.scale.copy(item.scale);
dummy.updateMatrix();
trunkMesh.setMatrixAt(index, dummy.matrix);
});
trunkMesh.castShadow = true;
trunkMesh.receiveShadow = true;
trunkMesh.instanceMatrix.needsUpdate = true;
scene.add(trunkMesh);
const canopyMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.95,
}),
canopyInstances.length
);
canopyInstances.forEach((item, index) => {
dummy.position.copy(item.position);
dummy.rotation.set(0, 0, 0);
dummy.scale.copy(item.scale);
dummy.updateMatrix();
canopyMesh.setMatrixAt(index, dummy.matrix);
canopyMesh.setColorAt(index, item.color);
});
canopyMesh.castShadow = true;
canopyMesh.receiveShadow = true;
canopyMesh.instanceMatrix.needsUpdate = true;
canopyMesh.instanceColor.needsUpdate = true;
scene.add(canopyMesh);
// ------------------------------------------------------------
// Outlet and transported-marker collection tray
// ------------------------------------------------------------
addBox(1.45, 0.28, 2.1, 0x315365, 15.15, 0.24, 0);
addBox(4.15, 0.28, 5.55, 0x202c3d, 17.0, 0.13, 0);
addBox(4.15, 0.18, 0.16, 0x783454, 17.0, 0.43, -2.7);
addBox(4.15, 0.18, 0.16, 0x783454, 17.0, 0.43, 2.7);
addBox(0.16, 0.18, 5.4, 0x783454, 15.0, 0.43, 0);
addBox(0.16, 0.18, 5.4, 0x783454, 19.0, 0.43, 0);
// Small downstream marker posts.
addBox(0.24, 1.0, 0.24, 0xec4899, 15.05, 0.85, -2.75);
addBox(0.24, 1.0, 0.24, 0xec4899, 18.95, 0.85, 2.75);
// ------------------------------------------------------------
// Animated runoff packets
// ------------------------------------------------------------
const waterPacketCount = (COLS - 1) * 3;
const waterMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0x38bdf8,
emissive: 0x075985,
emissiveIntensity: 0.8,
transparent: true,
opacity: 0.7,
depthWrite: false,
roughness: 0.28,
}),
waterPacketCount
);
waterMesh.frustumCulled = false;
waterMesh.renderOrder = 3;
scene.add(waterMesh);
// ------------------------------------------------------------
// Sediment marker model
// ------------------------------------------------------------
const markerMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.38,
metalness: 0.03,
}),
TOTAL_MARKERS
);
markerMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
markerMesh.frustumCulled = false;
markerMesh.castShadow = true;
scene.add(markerMesh);
let markers = [];
let running = true;
let tickCount = 0;
let pulseClock = 0;
let flowTime = 0;
let transportedSequence = 0;
function mulberry32(seed) {
return function random() {
let value = (seed += 0x6d2b79f5);
value = Math.imul(value ^ (value >>> 15), value | 1);
value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
};
}
function captureRandom(id, pulse) {
let hash = Math.imul(id + 1, 374761393);
hash ^= Math.imul(pulse + 1, 668265263);
hash = Math.imul(hash ^ (hash >>> 13), 1274126177);
return ((hash ^ (hash >>> 16)) >>> 0) / 4294967296;
}
function markerCellPosition(x, z, offsetX = 0, offsetZ = 0) {
return new THREE.Vector3(
worldX(x) + offsetX,
terrainLevel(x, z) + 0.28,
worldZ(z) + offsetZ
);
}
function trayPosition(index) {
const column = index % 10;
const row = Math.floor(index / 10) % 7;
const layer = Math.floor(index / 70);
return new THREE.Vector3(
15.38 + column * 0.34,
0.55 + layer * 0.17,
-2.05 + row * 0.68
);
}
function createMarkers() {
const random = mulberry32(7042);
const created = [];
for (let id = 0; id < TOTAL_MARKERS; id++) {
let x;
let z;
if (id < 66) {
// Sediment supplied across the eroding upper slope.
x = 1 + Math.floor(random() * 7);
z = Math.floor(random() * ROWS);
} else {
// Bank wash already entering the vegetated buffer.
x = 8 + Math.floor(random() * 3);
z =
random() < 0.5
? 2 + Math.floor(random() * 6)
: 14 + Math.floor(random() * 6);
}
const offsetX = (random() - 0.5) * 0.17;
const offsetZ = (random() - 0.5) * 0.17;
created.push({
id,
state: "suspended",
gx: x,
gz: z,
offsetX,
offsetZ,
position: markerCellPosition(x, z, offsetX, offsetZ),
from: new THREE.Vector3(),
to: new THREE.Vector3(),
animation: 1,
duration: 1,
});
}
return created;
}
function moveMarker(marker, target, duration = 0.43) {
marker.from.copy(marker.position);
marker.to.copy(target);
marker.animation = 0;
marker.duration = duration;
}
function updateStats() {
let suspended = 0;
let retained = 0;
let transported = 0;
for (const marker of markers) {
if (marker.state === "suspended") suspended++;
if (marker.state === "retained") retained++;
if (marker.state === "transported") transported++;
}
suspendedCountEl.textContent = suspended;
retainedCountEl.textContent = retained;
transportedCountEl.textContent = transported;
const resolved = retained + transported;
retentionRateEl.textContent =
resolved === 0 ? "—" : `${Math.round((retained / resolved) * 100)}%`;
}
function resetSimulation() {
markers = createMarkers();
tickCount = 0;
pulseClock = 0;
flowTime = 0;
transportedSequence = 0;
updateStats();
}
function downhillCell(x, z) {
const currentLevel = terrainLevel(x, z);
const candidates = [];
for (let dz = -1; dz <= 1; dz++) {
for (let dx = -1; dx <= 1; dx++) {
if (dx === 0 && dz === 0) continue;
const nx = x + dx;
const nz = z + dz;
if (nx < 0 || nx >= COLS || nz < 0 || nz >= ROWS) continue;
const level = terrainLevel(nx, nz);
if (level < currentLevel - 0.001) {
candidates.push({ x: nx, z: nz, level });
}
}
}
if (candidates.length === 0) return null;
const minimum = Math.min(...candidates.map((cell) => cell.level));
const ties = candidates.filter(
(cell) => Math.abs(cell.level - minimum) < 0.001
);
// Prefer the downstream cell when quantized elevations tie.
ties.sort((a, b) => {
if (b.x !== a.x) return b.x - a.x;
return Math.abs(a.z - centerZ(a.x)) - Math.abs(b.z - centerZ(b.x));
});
return ties[0];
}
function simulationPulse() {
tickCount++;
for (const marker of markers) {
if (marker.state !== "suspended") continue;
if (marker.gx >= COLS - 1) {
marker.state = "transported";
const trayTarget = trayPosition(transportedSequence++);
moveMarker(marker, trayTarget, 1.0);
continue;
}
const next = downhillCell(marker.gx, marker.gz);
if (!next) {
marker.state = "retained";
marker.gx = clamp(marker.gx, 0, COLS - 1);
marker.gz = clamp(marker.gz, 0, ROWS - 1);
moveMarker(
marker,
markerCellPosition(
marker.gx,
marker.gz,
marker.offsetX,
marker.offsetZ
),
0.34
);
continue;
}
const captured =
isVegetated(next.x, next.z) &&
captureRandom(marker.id, tickCount) < CAPTURE_PROBABILITY;
marker.gx = next.x;
marker.gz = next.z;
if (captured) {
marker.state = "retained";
moveMarker(
marker,
markerCellPosition(
marker.gx,
marker.gz,
marker.offsetX,
marker.offsetZ
),
0.38
);
} else {
moveMarker(
marker,
markerCellPosition(
marker.gx,
marker.gz,
marker.offsetX,
marker.offsetZ
)
);
}
}
updateStats();
}
// ------------------------------------------------------------
// Marker animation and rendering
// ------------------------------------------------------------
function updateMarkers(delta, elapsed) {
for (let index = 0; index < markers.length; index++) {
const marker = markers[index];
if (marker.animation < 1) {
marker.animation = Math.min(
1,
marker.animation + delta / marker.duration
);
const t = marker.animation;
const eased = t * t * (3 - 2 * t);
marker.position.lerpVectors(marker.from, marker.to, eased);
if (marker.state === "transported") {
marker.position.y += Math.sin(t * Math.PI) * 1.55;
}
}
const renderPosition = marker.position.clone();
if (marker.state === "retained") {
renderPosition.y +=
0.035 + Math.sin(elapsed * 2.4 + marker.id * 0.37) * 0.025;
}
const baseScale =
marker.state === "retained"
? 0.23
: marker.state === "transported"
? 0.18
: 0.19;
const pulse =
marker.state === "retained"
? 1 + Math.sin(elapsed * 2.4 + marker.id) * 0.08
: 1;
dummy.position.copy(renderPosition);
dummy.rotation.set(
0,
marker.state === "suspended"
? elapsed * 0.65 + marker.id
: marker.id * 0.37,
0
);
dummy.scale.setScalar(baseScale * pulse);
dummy.updateMatrix();
markerMesh.setMatrixAt(index, dummy.matrix);
markerMesh.setColorAt(index, colors[marker.state]);
}
markerMesh.instanceMatrix.needsUpdate = true;
markerMesh.instanceColor.needsUpdate = true;
}
function updateWater(elapsed) {
let instance = 0;
for (let x = 0; x < COLS - 1; x++) {
for (let lane = -1; lane <= 1; lane++) {
const phase = (elapsed * 0.19 + x * 0.37 + lane * 0.11) % 1;
const movingX = x + phase;
const channelCenter = centerZ(movingX);
const movingZ = clamp(
Math.round(channelCenter + lane * 0.65),
0,
ROWS - 1
);
const level = terrainLevel(
clamp(Math.round(movingX), 0, COLS - 1),
movingZ
);
dummy.position.set(
worldX(movingX),
level + 0.115,
worldZ(movingZ)
);
dummy.rotation.set(0, 0, 0);
dummy.scale.set(0.58, 0.075, 0.27);
dummy.updateMatrix();
waterMesh.setMatrixAt(instance++, dummy.matrix);
}
}
waterMesh.instanceMatrix.needsUpdate = true;
}
// ------------------------------------------------------------
// Camera controls implemented directly
// ------------------------------------------------------------
function updateCamera() {
camera.position.set(
cameraTarget.x +
cameraRadius *
Math.sin(cameraElevation) *
Math.cos(cameraAzimuth),
cameraTarget.y + cameraRadius * Math.cos(cameraElevation),
cameraTarget.z +
cameraRadius *
Math.sin(cameraElevation) *
Math.sin(cameraAzimuth)
);
camera.lookAt(cameraTarget);
camera.updateMatrixWorld();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const viewHeight = Math.max(25.5, 39 / aspect);
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
const pointer = {
active: false,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
moved: false,
};
renderer.domElement.addEventListener("pointerdown", (event) => {
pointer.active = true;
pointer.moved = false;
pointer.startX = event.clientX;
pointer.startY = event.clientY;
pointer.lastX = event.clientX;
pointer.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointer.active) return;
const dx = event.clientX - pointer.lastX;
const dy = event.clientY - pointer.lastY;
pointer.lastX = event.clientX;
pointer.lastY = event.clientY;
if (
Math.hypot(
event.clientX - pointer.startX,
event.clientY - pointer.startY
) > 4
) {
pointer.moved = true;
}
cameraAzimuth -= dx * 0.006;
cameraElevation = clamp(cameraElevation + dy * 0.0045, 0.34, 1.25);
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
pointer.active = false;
if (!pointer.moved) {
inspectTerrain(event.clientX, event.clientY);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointer.active = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraZoom = clamp(
cameraZoom * Math.exp(-event.deltaY * 0.001),
0.7,
2.4
);
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
},
{ passive: false }
);
// ------------------------------------------------------------
// Terrain inspection
// ------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointerNdc = new THREE.Vector2();
function inspectTerrain(clientX, clientY) {
const rect = renderer.domElement.getBoundingClientRect();
pointerNdc.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointerNdc.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointerNdc, camera);
const hit = raycaster.intersectObject(terrainMesh, false)[0];
if (!hit || hit.instanceId === undefined) {
inspectEl.textContent =
"Click a terrain voxel to inspect its elevation and next flow cell.";
return;
}
const x = hit.instanceId % COLS;
const z = Math.floor(hit.instanceId / COLS);
const next = downhillCell(x, z);
const cellType = isVegetated(x, z)
? "vegetated buffer"
: isChannel(x, z)
? "channel bed"
: "soil / eroding slope";
let routeText;
if (x >= COLS - 1) {
routeText = "Next: downstream outlet; this marker is counted as transported.";
} else if (!next) {
routeText = "Next: no lower neighbor; deposited and counted as retained.";
} else if (isVegetated(next.x, next.z)) {
routeText =
`Next: (${next.x}, ${next.z}), a vegetated buffer cell; ` +
`capture is tested with p = ${CAPTURE_PROBABILITY.toFixed(2)}.`;
} else {
routeText = `Next: lower neighbor at (${next.x}, ${next.z}).`;
}
inspectEl.textContent =
`Cell (${x}, ${z}) — ${cellType}; elevation ${terrainLevel(x, z).toFixed(2)}. ` +
routeText;
}
// ------------------------------------------------------------
// World-space labels
// ------------------------------------------------------------
const bufferLabelEl = document.getElementById("buffer-label");
const outletLabelEl = document.getElementById("outlet-label");
const bufferLabelPosition = new THREE.Vector3(
worldX(10),
terrainLevel(10, 4) + 2.2,
worldZ(4)
);
const outletLabelPosition = new THREE.Vector3(17.0, 2.25, 0);
function positionLabel(element, worldPosition) {
const projected = worldPosition.clone().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;
element.style.display = visible ? "block" : "none";
if (!visible) return;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.transform =
`translate(${x}px, ${y}px) translate(-50%, -100%)`;
}
// ------------------------------------------------------------
// UI
// ------------------------------------------------------------
function setRunning(value) {
running = value;
pauseButton.textContent = running ? "Pause" : "Resume";
}
pauseButton.addEventListener("click", () => {
setRunning(!running);
});
stepButton.addEventListener("click", () => {
setRunning(false);
simulationPulse();
pulseClock = 0;
});
resetButton.addEventListener("click", () => {
resetSimulation();
setRunning(true);
});
collapseButton.addEventListener("click", () => {
const collapsed = panel.classList.toggle("collapsed");
collapseButton.textContent = collapsed ? "+" : "−";
});
window.addEventListener("resize", resize);
// ------------------------------------------------------------
// Main loop
// ------------------------------------------------------------
resetSimulation();
resize();
updateCamera();
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
if (running) {
pulseClock += delta;
flowTime += delta;
while (pulseClock >= PULSE_SECONDS) {
pulseClock -= PULSE_SECONDS;
simulationPulse();
}
}
updateMarkers(delta, elapsed);
updateWater(flowTime);
pulseFillEl.style.transform = `scaleX(${pulseClock / PULSE_SECONDS})`;
pulseNumberEl.textContent = `Pulse ${tickCount}`;
camera.updateMatrixWorld();
positionLabel(bufferLabelEl, bufferLabelPosition);
positionLabel(outletLabelEl, outletLabelPosition);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```