Prompt specification
Build or customize the Three.js 3D scene "Runoff carries sediment particles" 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: Runoff carries sediment particles
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/runoff-carries-sediment-particles-x1062
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring farm soil erosion control. Send equal symbolic water pulses down both slopes and track colored sediment units; root-covered regions retain more under a clearly declared illustrative rule. Voxel style.
Working Three.js Starter (runoff-carries-sediment-particles-x1062):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Rooted vs. Bare — Voxel Soil Erosion Lab</title>
<style>
:root {
--ink: #173c31;
--paper: #f4f0dd;
--paper-dark: #e5dfc4;
--green: #78a942;
--lime: #b9ef4a;
--soil: #a7653f;
--water: #42c7e8;
--amber: #f5a623;
--pink: #ec4c8a;
--border: 2px solid var(--ink);
--shadow: 5px 5px 0 rgba(23, 60, 49, 0.92);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce7cf;
color: var(--ink);
font-family: "Courier New", Courier, monospace;
}
button,
select {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.overlay {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
position: absolute;
pointer-events: auto;
background: rgba(244, 240, 221, 0.96);
border: var(--border);
box-shadow: var(--shadow);
}
#intro {
top: 18px;
left: 18px;
width: min(480px, calc(100vw - 36px));
padding: 16px 18px;
}
.eyebrow {
margin-bottom: 6px;
color: #47704e;
font-size: 11px;
font-weight: bold;
letter-spacing: 0.13em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(24px, 3.1vw, 39px);
line-height: 0.98;
letter-spacing: -0.06em;
}
#intro p {
max-width: 430px;
margin: 10px 0 0;
font-family: system-ui, sans-serif;
font-size: 13px;
line-height: 1.45;
}
#rule {
top: 18px;
right: 18px;
width: min(370px, calc(100vw - 36px));
max-height: calc(100vh - 132px);
overflow: auto;
padding: 16px;
}
h2 {
margin: 0 0 9px;
font-size: 18px;
letter-spacing: -0.04em;
}
h3 {
margin: 15px 0 8px;
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.rule-text {
margin: 0;
font-family: system-ui, sans-serif;
font-size: 12px;
line-height: 1.48;
}
.rule-compare {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 12px 0;
}
.rule-compare > div {
padding: 10px;
border: 1px solid var(--ink);
background: #f8f4e6;
}
.rule-compare strong,
.rule-compare b {
display: block;
}
.rule-compare strong {
margin-bottom: 6px;
font-size: 11px;
text-transform: uppercase;
}
.rule-compare b {
font-size: 15px;
}
.root-rule {
border-top: 6px solid var(--green);
}
.bare-rule {
border-top: 6px solid var(--soil);
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 9px;
}
.metric {
padding: 8px;
border: 1px solid var(--ink);
background: rgba(255, 255, 255, 0.42);
font-size: 10px;
line-height: 1.45;
}
.metric b {
display: block;
font-size: 19px;
line-height: 1.1;
}
.legend {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px 10px;
margin: 8px 0 12px;
font-family: system-ui, sans-serif;
font-size: 11px;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 13px;
height: 13px;
flex: 0 0 auto;
border: 1px solid var(--ink);
box-shadow: 2px 2px 0 rgba(23, 60, 49, 0.25);
}
.swatch.water {
background: var(--water);
}
.swatch.mobile {
background: var(--amber);
}
.swatch.retained {
background: var(--lime);
}
.swatch.runoff {
background: var(--pink);
}
.swatch.root {
background: #a97849;
}
#pulseResults {
display: grid;
gap: 8px;
}
.pulse-row {
padding: 8px;
border: 1px solid var(--ink);
background: rgba(255, 255, 255, 0.45);
}
.pulse-head {
display: flex;
justify-content: space-between;
gap: 10px;
margin-bottom: 6px;
font-size: 10px;
font-weight: bold;
}
.pulse-head .state {
color: #6d542c;
}
.track {
display: grid;
grid-template-columns: 67px 1fr;
align-items: center;
gap: 7px;
margin-top: 5px;
}
.track-label {
font-size: 9px;
font-weight: bold;
}
.units {
display: grid;
grid-template-columns: repeat(12, 1fr);
gap: 3px;
}
.unit {
aspect-ratio: 1;
min-width: 7px;
border: 1px solid var(--ink);
background: var(--amber);
transition: background 120ms linear, transform 120ms linear;
}
.unit.retained {
background: var(--lime);
transform: translateY(-1px);
}
.unit.runoff {
background: var(--pink);
}
#controls {
bottom: 18px;
left: 18px;
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
max-width: calc(100vw - 36px);
padding: 11px;
}
button,
select {
min-height: 36px;
padding: 8px 11px;
color: var(--ink);
background: #fffaf0;
border: 2px solid var(--ink);
cursor: pointer;
font-size: 12px;
font-weight: bold;
}
button:hover,
select:hover {
background: var(--lime);
}
button:active {
transform: translate(1px, 1px);
}
#pulseBtn {
background: var(--lime);
}
#autoStatus,
#cameraHelp {
font-size: 10px;
line-height: 1.35;
}
#cameraHelp {
max-width: 290px;
color: #496257;
}
.scene-label {
position: absolute;
z-index: 3;
min-width: 128px;
padding: 7px 9px;
border: 2px solid var(--ink);
background: rgba(244, 240, 221, 0.95);
box-shadow: 4px 4px 0 rgba(23, 60, 49, 0.8);
transform: translate(-50%, -50%);
text-align: center;
pointer-events: none;
font-size: 10px;
font-weight: bold;
line-height: 1.3;
}
.scene-label b {
display: block;
font-size: 12px;
}
#rootLabel {
border-top: 6px solid var(--green);
}
#bareLabel {
border-top: 6px solid var(--soil);
}
#sourceLabel {
border-color: #166c7d;
background: rgba(218, 246, 249, 0.95);
box-shadow: 4px 4px 0 #166c7d;
}
.note {
margin-top: 9px;
color: #57685e;
font-family: system-ui, sans-serif;
font-size: 10px;
line-height: 1.35;
}
@media (max-width: 900px) {
#intro {
padding: 12px 14px;
}
#intro p {
display: none;
}
#rule {
top: auto;
right: 12px;
bottom: 91px;
width: min(350px, calc(100vw - 24px));
max-height: 43vh;
padding: 12px;
}
#controls {
right: 12px;
bottom: 12px;
left: 12px;
max-width: none;
}
#cameraHelp {
display: none;
}
.scene-label {
transform: translate(-50%, -50%) scale(0.85);
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel farm erosion comparison"></canvas>
<div class="overlay">
<section id="intro" class="panel">
<div class="eyebrow">Voxel Soil Lab / Farm Erosion Control</div>
<h1>Same water.<br />Different soil.</h1>
<p>
Equal symbolic pulses travel down a root-covered slope and a bare
control slope. Watch each sediment unit either settle or continue to
the collection toe.
</p>
</section>
<aside id="rule" class="panel">
<h2>Declared illustrative rule</h2>
<p class="rule-text">
Every pulse sends <b>10 symbolic water units</b> and
<b>12 mobile sediment units</b> down each slope. Root-covered soil
retains <b>9 of 12</b> sediment units; bare soil retains
<b>2 of 12</b>. The remaining 3 rooted units and 10 bare units
continue to runoff.
</p>
<div class="rule-compare">
<div class="root-rule">
<strong>Root-covered</strong>
<b>9 / 12 retained</b>
</div>
<div class="bare-rule">
<strong>Bare control</strong>
<b>2 / 12 retained</b>
</div>
</div>
<p class="note">
This is a declared symbolic teaching rule, not a calibrated erosion
forecast. Both slopes receive identical initial water and sediment.
</p>
<h3>Latest pulse</h3>
<div class="metric-grid">
<div class="metric">
ROOT RETAINED
<b id="rootMetric">0 / 9</b>
RUNOFF <span id="rootRunoffMetric">0 / 3</span>
</div>
<div class="metric">
BARE RETAINED
<b id="bareMetric">0 / 2</b>
RUNOFF <span id="bareRunoffMetric">0 / 10</span>
</div>
</div>
<h3>Color key</h3>
<div class="legend">
<div class="legend-item"><span class="swatch water"></span>Water unit</div>
<div class="legend-item"><span class="swatch mobile"></span>Mobile sediment</div>
<div class="legend-item"><span class="swatch retained"></span>Retained sediment</div>
<div class="legend-item"><span class="swatch runoff"></span>Runoff sediment</div>
<div class="legend-item"><span class="swatch root"></span>Visible root network</div>
<div class="legend-item"><span class="swatch" style="background:#7cae50"></span>Root cover</div>
</div>
<h3>Pulse tracker</h3>
<div id="pulseResults"></div>
</aside>
<div id="controls" class="panel">
<button id="pulseBtn" type="button">Release equal pulse</button>
<button id="pauseBtn" type="button">Pause</button>
<button id="resetBtn" type="button">Reset</button>
<button id="cameraBtn" type="button">Reset camera</button>
<select id="speed" aria-label="Simulation speed">
<option value="0.5">0.5× speed</option>
<option value="1" selected>1× speed</option>
<option value="1.5">1.5× speed</option>
<option value="2">2× speed</option>
</select>
<span id="autoStatus">Pulses sent: 0 · Auto: 3</span>
<span id="cameraHelp">
Drag: orbit · wheel: zoom · right/shift-drag: pan · arrows: pan
</span>
</div>
<div id="rootLabel" class="scene-label">
ROOT-COVERED
<b>9 captured / pulse</b>
</div>
<div id="bareLabel" class="scene-label">
BARE CONTROL
<b>2 captured / pulse</b>
</div>
<div id="sourceLabel" class="scene-label">
EQUAL MANIFOLD
<b>10 water units / side</b>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Declared symbolic model
// -------------------------------------------------------------------------
const MODEL = Object.freeze({
waterUnitsPerPulse: 10,
sedimentUnitsPerPulse: 12,
rootRetained: 9,
bareRetained: 2,
pulseDuration: 4.65,
autoPulses: 3
});
const dom = {
canvas: document.querySelector("#scene"),
intro: document.querySelector("#intro"),
rule: document.querySelector("#rule"),
controls: document.querySelector("#controls"),
rootLabel: document.querySelector("#rootLabel"),
bareLabel: document.querySelector("#bareLabel"),
sourceLabel: document.querySelector("#sourceLabel"),
pulseBtn: document.querySelector("#pulseBtn"),
pauseBtn: document.querySelector("#pauseBtn"),
resetBtn: document.querySelector("#resetBtn"),
cameraBtn: document.querySelector("#cameraBtn"),
speed: document.querySelector("#speed"),
autoStatus: document.querySelector("#autoStatus"),
pulseResults: document.querySelector("#pulseResults"),
rootMetric: document.querySelector("#rootMetric"),
rootRunoffMetric: document.querySelector("#rootRunoffMetric"),
bareMetric: document.querySelector("#bareMetric"),
bareRunoffMetric: document.querySelector("#bareRunoffMetric")
};
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
const lerp = (a, b, t) => a + (b - a) * t;
let randomSeed = 73421;
function random() {
randomSeed =
(Math.imul(randomSeed, 1664525) + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
// -------------------------------------------------------------------------
// Renderer, scene, lighting, and camera
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas: dom.canvas,
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce7cf);
scene.fog = new THREE.Fog(0xdce7cf, 30, 58);
const camera = new THREE.OrthographicCamera(-10, 10, 10, -10, 0.1, 100);
const hemisphere = new THREE.HemisphereLight(
0xf4fbdc,
0x6c4935,
2.0
);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1c7, 3.0);
sun.position.set(-9, 18, 11);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 18;
sun.shadow.camera.bottom = -18;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 50;
sun.shadow.bias = -0.0006;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x8bd4ff, 0.7);
fill.position.set(10, 8, -8);
scene.add(fill);
const cameraState = {
theta: 0.72,
phi: 0.73,
zoom: 1,
target: new THREE.Vector3(0, 2.65, -0.1),
initialTheta: 0.72,
initialPhi: 0.73,
initialZoom: 1,
initialTarget: new THREE.Vector3(0, 2.65, -0.1)
};
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
const viewHeight = aspect < 1 ? 22 / aspect : 17.5;
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
}
function updateCamera() {
const radius = 28;
const horizontal = radius * Math.cos(cameraState.phi);
camera.position.set(
cameraState.target.x + horizontal * Math.sin(cameraState.theta),
cameraState.target.y + radius * Math.sin(cameraState.phi),
cameraState.target.z + horizontal * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
}
function resetCamera() {
cameraState.theta = cameraState.initialTheta;
cameraState.phi = cameraState.initialPhi;
cameraState.zoom = cameraState.initialZoom;
cameraState.target.copy(cameraState.initialTarget);
updateCamera();
}
window.addEventListener("resize", resize);
resize();
updateCamera();
// -------------------------------------------------------------------------
// Direct camera controls: orbit, pan, zoom, keyboard
// -------------------------------------------------------------------------
const pointer = {
active: false,
mode: "orbit",
id: null,
x: 0,
y: 0
};
dom.canvas.addEventListener("contextmenu", event => event.preventDefault());
dom.canvas.addEventListener("pointerdown", event => {
pointer.active = true;
pointer.mode =
event.button === 2 || event.shiftKey ? "pan" : "orbit";
pointer.id = event.pointerId;
pointer.x = event.clientX;
pointer.y = event.clientY;
dom.canvas.setPointerCapture(event.pointerId);
});
dom.canvas.addEventListener("pointermove", event => {
if (!pointer.active || event.pointerId !== pointer.id) return;
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
pointer.x = event.clientX;
pointer.y = event.clientY;
if (pointer.mode === "orbit") {
cameraState.theta -= dx * 0.006;
cameraState.phi = clamp(
cameraState.phi + dy * 0.005,
0.25,
1.28
);
} else {
const direction = new THREE.Vector3();
camera.getWorldDirection(direction);
const right = new THREE.Vector3()
.crossVectors(direction, camera.up)
.normalize();
const screenUp = new THREE.Vector3()
.crossVectors(right, direction)
.normalize();
const worldPerPixel =
(camera.top - camera.bottom) /
camera.zoom /
dom.canvas.clientHeight;
cameraState.target
.addScaledVector(right, -dx * worldPerPixel)
.addScaledVector(screenUp, dy * worldPerPixel);
}
updateCamera();
});
function releasePointer(event) {
if (event.pointerId !== pointer.id) return;
pointer.active = false;
pointer.id = null;
}
dom.canvas.addEventListener("pointerup", releasePointer);
dom.canvas.addEventListener("pointercancel", releasePointer);
dom.canvas.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraState.zoom = clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.65,
2.5
);
updateCamera();
},
{ passive: false }
);
window.addEventListener("keydown", event => {
const tag = event.target.tagName;
if (["INPUT", "SELECT", "TEXTAREA", "BUTTON"].includes(tag)) return;
const direction = new THREE.Vector3();
camera.getWorldDirection(direction);
const right = new THREE.Vector3()
.crossVectors(direction, camera.up)
.normalize();
const screenUp = new THREE.Vector3()
.crossVectors(right, direction)
.normalize();
const panAmount = 0.3;
if (event.key === "ArrowLeft") {
cameraState.target.addScaledVector(right, -panAmount);
} else if (event.key === "ArrowRight") {
cameraState.target.addScaledVector(right, panAmount);
} else if (event.key === "ArrowUp") {
cameraState.target.addScaledVector(screenUp, panAmount);
} else if (event.key === "ArrowDown") {
cameraState.target.addScaledVector(screenUp, -panAmount);
} else if (event.key === "+" || event.key === "=") {
cameraState.zoom = clamp(cameraState.zoom * 1.1, 0.65, 2.5);
} else if (event.key === "-" || event.key === "_") {
cameraState.zoom = clamp(cameraState.zoom / 1.1, 0.65, 2.5);
} else if (event.key.toLowerCase() === "c") {
resetCamera();
} else {
return;
}
event.preventDefault();
updateCamera();
});
// -------------------------------------------------------------------------
// Voxel materials and geometry
// -------------------------------------------------------------------------
const boxGeometry = new THREE.BoxGeometry(1, 1, 1);
const materials = {
soil: new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1
}),
grass: new THREE.MeshStandardMaterial({
color: 0x639a43,
roughness: 1
}),
grassLight: new THREE.MeshStandardMaterial({
color: 0x8fbd54,
roughness: 1
}),
root: new THREE.MeshStandardMaterial({
color: 0xb9824e,
roughness: 1
}),
stubble: new THREE.MeshStandardMaterial({
color: 0xc59a4d,
roughness: 1
}),
metal: new THREE.MeshStandardMaterial({
color: 0x446b70,
roughness: 0.7,
metalness: 0.25
}),
tray: new THREE.MeshStandardMaterial({
color: 0x344c49,
roughness: 0.95
}),
water: new THREE.MeshStandardMaterial({
color: 0x42c7e8,
emissive: 0x08758e,
emissiveIntensity: 0.45,
roughness: 0.35
}),
mobile: new THREE.MeshStandardMaterial({
color: 0xf5a623,
emissive: 0x6e2d00,
emissiveIntensity: 0.18,
roughness: 0.8
}),
retained: new THREE.MeshStandardMaterial({
color: 0xb9ef4a,
emissive: 0x416b00,
emissiveIntensity: 0.22,
roughness: 0.8
}),
runoff: new THREE.MeshStandardMaterial({
color: 0xec4c8a,
emissive: 0x6b0c35,
emissiveIntensity: 0.2,
roughness: 0.8
})
};
function addBox(material, x, y, z, sx, sy, sz, castShadow = true) {
const mesh = new THREE.Mesh(boxGeometry, material);
mesh.position.set(x, y, z);
mesh.scale.set(sx, sy, sz);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Voxel ground
// -------------------------------------------------------------------------
const groundWidth = 18;
const groundDepth = 12;
const groundCell = 1.1;
const groundMesh = new THREE.InstancedMesh(
boxGeometry,
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1
}),
groundWidth * groundDepth
);
groundMesh.receiveShadow = true;
groundMesh.frustumCulled = false;
const dummy = new THREE.Object3D();
let groundIndex = 0;
for (let z = 0; z < groundDepth; z++) {
for (let x = 0; x < groundWidth; x++) {
dummy.position.set(
-9.35 + x * groundCell,
-0.13,
-6.05 + z * groundCell
);
dummy.scale.set(1.07, 0.2, 1.07);
dummy.updateMatrix();
groundMesh.setMatrixAt(groundIndex, dummy.matrix);
const color = new THREE.Color(
(x + z) % 2 === 0 ? 0xaec48f : 0xbdd09c
);
groundMesh.setColorAt(groundIndex, color);
groundIndex++;
}
}
groundMesh.instanceMatrix.needsUpdate = true;
if (groundMesh.instanceColor) groundMesh.instanceColor.needsUpdate = true;
scene.add(groundMesh);
// -------------------------------------------------------------------------
// Two terraced voxel slopes
// -------------------------------------------------------------------------
const rows = 9;
const columns = 4;
const cell = 0.82;
const blockHeight = 0.36;
const rowZ0 = -3.8;
const rowZLast = rowZ0 + (rows - 1) * cell;
const slopes = {
root: {
key: "root",
centerX: -4.25,
retained: MODEL.rootRetained,
runoff: MODEL.sedimentUnitsPerPulse - MODEL.rootRetained,
label: "ROOTED"
},
bare: {
key: "bare",
centerX: 4.25,
retained: MODEL.bareRetained,
runoff: MODEL.sedimentUnitsPerPulse - MODEL.bareRetained,
label: "BARE"
}
};
const terrainTransforms = [];
const terrainColors = [];
for (const slope of Object.values(slopes)) {
for (let row = 0; row < rows; row++) {
const layers = 17 - row;
const z = rowZ0 + row * cell;
const top = layers * blockHeight;
for (let column = 0; column < columns; column++) {
const x =
slope.centerX + (column - (columns - 1) / 2) * cell;
for (let layer = 0; layer < layers; layer++) {
const y = (layer + 0.5) * blockHeight;
let color;
if (layer === layers - 1) {
color = slope.key === "root" ? 0x7fae50 : 0xaa7148;
} else if (layer > layers - 5) {
color = 0x8f5939;
} else if (layer > layers - 9) {
color = 0x75462f;
} else {
color = 0x5b392b;
}
terrainTransforms.push({
x,
y,
z,
sx: cell * 0.965,
sy: blockHeight * 0.97,
sz: cell * 0.965
});
terrainColors.push(new THREE.Color(color));
}
// Root-covered surface vegetation.
if (slope.key === "root") {
for (let tuft = 0; tuft < 3; tuft++) {
const offsetX = (random() - 0.5) * 0.38;
const offsetZ = (random() - 0.5) * 0.38;
addBox(
tuft === 1 ? materials.grassLight : materials.grass,
x + offsetX,
top + 0.12 + random() * 0.04,
z + offsetZ,
0.12,
0.22 + random() * 0.14,
0.12
);
}
} else if ((row + column) % 2 === 0) {
// Sparse, dry stubble on the bare control slope.
addBox(
materials.stubble,
x + (random() - 0.5) * 0.18,
top + 0.13,
z + (random() - 0.5) * 0.18,
0.09,
0.25,
0.09
);
}
}
}
}
const terrainMesh = new THREE.InstancedMesh(
boxGeometry,
materials.soil,
terrainTransforms.length
);
terrainMesh.castShadow = true;
terrainMesh.receiveShadow = true;
terrainMesh.frustumCulled = false;
terrainTransforms.forEach((transform, index) => {
dummy.position.set(transform.x, transform.y, transform.z);
dummy.scale.set(transform.sx, transform.sy, transform.sz);
dummy.updateMatrix();
terrainMesh.setMatrixAt(index, dummy.matrix);
terrainMesh.setColorAt(index, terrainColors[index]);
});
terrainMesh.instanceMatrix.needsUpdate = true;
if (terrainMesh.instanceColor) terrainMesh.instanceColor.needsUpdate = true;
scene.add(terrainMesh);
// Visible tan root network on exposed terrace faces.
for (let row = 0; row < rows; row++) {
const layers = 17 - row;
const top = layers * blockHeight;
const z = rowZ0 + row * cell;
for (let column = 0; column < columns; column++) {
const x =
slopes.root.centerX +
(column - (columns - 1) / 2) * cell;
const front = z + cell * 0.49;
addBox(
materials.root,
x,
top - 0.51,
front,
0.075,
0.48,
0.07
);
addBox(
materials.root,
x - 0.12,
top - 0.63,
front,
0.31,
0.07,
0.065
);
addBox(
materials.root,
x + 0.13,
top - 0.76,
front,
0.26,
0.065,
0.065
);
}
}
// A small bare-soil pocket where the two retained bare units settle.
addBox(
new THREE.MeshStandardMaterial({
color: 0x70432d,
roughness: 1
}),
slopes.bare.centerX,
4.71,
-0.45,
1.25,
0.055,
0.86,
false
);
// Equal source manifold.
addBox(materials.metal, 0, 6.48, -4.58, 10.2, 0.13, 0.22);
addBox(materials.metal, 0, 6.79, -4.58, 0.78, 0.58, 0.62);
for (const x of [-5.0, -3.5, 3.5, 5.0]) {
addBox(materials.metal, x, 6.28, -4.58, 0.12, 0.4, 0.12);
}
// Toe collection trays.
for (const slope of Object.values(slopes)) {
const z = 3.85;
addBox(
materials.tray,
slope.centerX,
0.06,
z,
4.35,
0.16,
1.28
);
addBox(
materials.tray,
slope.centerX - 2.12,
0.2,
z,
0.13,
0.42,
1.28
);
addBox(
materials.tray,
slope.centerX + 2.12,
0.2,
z,
0.13,
0.42,
1.28
);
addBox(
materials.tray,
slope.centerX,
0.2,
z + 0.59,
4.35,
0.42,
0.13
);
}
// -------------------------------------------------------------------------
// Path and pulse bookkeeping
// -------------------------------------------------------------------------
function surfaceHeight(z) {
if (z <= rowZ0) return 17 * blockHeight;
if (z >= rowZLast) return (17 - (rows - 1)) * blockHeight;
const row = Math.round((z - rowZ0) / cell);
return (17 - row) * blockHeight;
}
function pathPoint(slope, progress, lateral) {
const z = lerp(-4.58, 3.58, progress);
let base;
if (z <= rowZ0) {
base = 17 * blockHeight;
} else if (z >= rowZLast) {
base = lerp(
(17 - (rows - 1)) * blockHeight,
0.18,
clamp((z - rowZLast) / (3.58 - rowZLast), 0, 1)
);
} else {
base = surfaceHeight(z);
}
return new THREE.Vector3(
slope.centerX + lateral,
base + 0.23,
z
);
}
let pulses = [];
let pulseCounter = 0;
let autoRemaining = MODEL.autoPulses;
let autoTimer = 0.7;
let paused = false;
function makeTrack(label, expectedRetained) {
const track = document.createElement("div");
track.className = "track";
const name = document.createElement("div");
name.className = "track-label";
name.textContent = `${label} · ${expectedRetained} keep`;
const units = document.createElement("div");
units.className = "units";
track.append(name, units);
return { track, units };
}
function createPulse() {
const id = ++pulseCounter;
const pulse = {
id,
age: 0,
water: [],
sediment: [],
done: false,
counts: {
root: { retained: 0, runoff: 0 },
bare: { retained: 0, runoff: 0 }
},
dom: {}
};
const row = document.createElement("div");
row.className = "pulse-row";
const head = document.createElement("div");
head.className = "pulse-head";
const title = document.createElement("span");
title.textContent =
`PULSE ${String(id).padStart(2, "0")} · 10 WATER / SIDE`;
const state = document.createElement("span");
state.className = "state";
state.textContent = "IN MOTION";
head.append(title, state);
row.append(head);
for (const slope of Object.values(slopes)) {
const { track, units } = makeTrack(
slope.label,
slope.retained
);
row.append(track);
const spans = [];
for (let i = 0; i < MODEL.sedimentUnitsPerPulse; i++) {
const span = document.createElement("span");
span.className = "unit";
span.title = `${slope.label}: mobile sediment unit ${i + 1}`;
units.append(span);
spans.push(span);
}
pulse.dom[slope.key] = { state, spans };
}
dom.pulseResults.prepend(row);
while (dom.pulseResults.children.length > 5) {
dom.pulseResults.lastElementChild.remove();
}
for (const slope of Object.values(slopes)) {
// Ten blue units are spawned simultaneously on both slopes.
for (let i = 0; i < MODEL.waterUnitsPerPulse; i++) {
const mesh = new THREE.Mesh(boxGeometry, materials.water);
mesh.scale.setScalar(0.17);
mesh.castShadow = true;
scene.add(mesh);
const lane = i % columns;
const lateral =
(lane - (columns - 1) / 2) * 0.58 +
(random() - 0.5) * 0.1;
pulse.water.push({
mesh,
slope,
lateral,
delay: i * 0.032
});
}
// Deterministically choose which symbolic sediment units are retained.
const order = Array.from(
{ length: MODEL.sedimentUnitsPerPulse },
(_, index) => index
);
for (let i = order.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[order[i], order[j]] = [order[j], order[i]];
}
const retainedIndices = new Set(
order.slice(0, slope.retained)
);
for (let i = 0; i < MODEL.sedimentUnitsPerPulse; i++) {
const mesh = new THREE.Mesh(boxGeometry, materials.mobile);
mesh.scale.setScalar(0.18);
mesh.castShadow = true;
scene.add(mesh);
const retained = retainedIndices.has(i);
const destination =
slope.key === "root"
? 0.25 + random() * 0.48
: 0.45 + random() * 0.12;
const lateral =
slope.key === "bare" && retained
? (random() - 0.5) * 0.5
: (Math.floor(random() * columns) -
(columns - 1) / 2) *
0.58 +
(random() - 0.5) * 0.12;
const delay = 0.25 + random() * 0.35;
const settleTime =
slope.key === "bare" && retained
? 1.7 + random() * 0.35
: retained
? 1.0 + destination * 3.15 + random() * 0.2
: 4.12 + random() * 0.18;
pulse.sediment.push({
mesh,
slope,
retained,
destination,
lateral,
delay,
settleTime,
settled: false,
span: pulse.dom[slope.key].spans[i]
});
}
}
pulses.push(pulse);
updateSummary();
return pulse;
}
function settleSediment(token, pulse) {
token.settled = true;
token.mesh.material = token.retained
? materials.retained
: materials.runoff;
token.span.className =
`unit ${token.retained ? "retained" : "runoff"}`;
token.span.title =
`${token.slope.label}: ${token.retained ? "retained" : "runoff"} sediment`;
const counter =
token.retained ? "retained" : "runoff";
pulse.counts[token.slope.key][counter]++;
}
function updatePulse(pulse, delta) {
pulse.age += delta;
for (const token of pulse.water) {
const progress = clamp(
(pulse.age - token.delay) / (4.02 - token.delay),
0,
1
);
const position = pathPoint(
token.slope,
progress,
token.lateral
);
token.mesh.position.copy(position);
token.mesh.position.y += Math.sin(
pulse.age * 8 + token.delay * 20
) * 0.035;
const scale =
pulse.age < 4.4
? 0.17
: Math.max(0, 0.17 * (1 - (pulse.age - 4.4) / 0.55));
token.mesh.scale.setScalar(scale);
token.mesh.visible = pulse.age < 4.96;
}
for (const token of pulse.sediment) {
if (!token.settled && pulse.age >= token.settleTime) {
settleSediment(token, pulse);
}
const progress = clamp(
(pulse.age - token.delay) /
(token.settleTime - token.delay),
0,
1
);
const position = pathPoint(
token.slope,
progress * token.destination,
token.lateral
);
token.mesh.position.copy(position);
if (token.settled && token.retained) {
// Settled retained units sit partly embedded in the soil surface.
token.mesh.position.y =
surfaceHeight(token.mesh.position.z) + 0.1;
}
if (token.settled && !token.retained) {
// Runoff cubes remain visible in the toe collection trays.
token.mesh.position.y = 0.31 + random() * 0.012;
token.mesh.rotation.y = random() * 0.25;
} else if (!token.settled) {
token.mesh.rotation.y += delta * 1.7;
token.mesh.rotation.z = Math.sin(pulse.age * 5) * 0.12;
}
}
if (!pulse.done && pulse.age >= MODEL.pulseDuration) {
pulse.done = true;
pulse.dom.root.state.textContent = "COMPLETE";
pulse.dom.bare.state.textContent = "COMPLETE";
}
}
function updateSummary() {
const latest = pulses[pulses.length - 1];
if (latest) {
dom.rootMetric.textContent =
`${latest.counts.root.retained} / ${MODEL.rootRetained}`;
dom.rootRunoffMetric.textContent =
`${latest.counts.root.runoff} / ${slopes.root.runoff}`;
dom.bareMetric.textContent =
`${latest.counts.bare.retained} / ${MODEL.bareRetained}`;
dom.bareRunoffMetric.textContent =
`${latest.counts.bare.runoff} / ${slopes.bare.runoff}`;
} else {
dom.rootMetric.textContent = `0 / ${MODEL.rootRetained}`;
dom.rootRunoffMetric.textContent =
`0 / ${slopes.root.runoff}`;
dom.bareMetric.textContent = `0 / ${MODEL.bareRetained}`;
dom.bareRunoffMetric.textContent =
`0 / ${slopes.bare.runoff}`;
}
dom.autoStatus.textContent =
`Pulses sent: ${pulseCounter} · Auto: ${autoRemaining}`;
}
function resetSimulation() {
for (const pulse of pulses) {
for (const token of pulse.water) {
scene.remove(token.mesh);
}
for (const token of pulse.sediment) {
scene.remove(token.mesh);
}
}
pulses = [];
pulseCounter = 0;
autoRemaining = MODEL.autoPulses;
autoTimer = 0.7;
randomSeed = 73421;
dom.pulseResults.replaceChildren();
paused = false;
dom.pauseBtn.textContent = "Pause";
updateSummary();
}
// -------------------------------------------------------------------------
// Interface controls
// -------------------------------------------------------------------------
dom.pulseBtn.addEventListener("click", () => {
createPulse();
});
dom.pauseBtn.addEventListener("click", () => {
paused = !paused;
dom.pauseBtn.textContent = paused ? "Resume" : "Pause";
});
dom.resetBtn.addEventListener("click", resetSimulation);
dom.cameraBtn.addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Screen-space labels
// -------------------------------------------------------------------------
const labelAnchors = {
rootLabel: new THREE.Vector3(-4.25, 7.45, -3.45),
bareLabel: new THREE.Vector3(4.25, 7.45, -3.45),
sourceLabel: new THREE.Vector3(0, 7.72, -4.6)
};
function projectLabel(element, anchor) {
const projected = anchor.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.opacity = visible ? "1" : "0";
element.style.left =
`${((projected.x + 1) / 2) * window.innerWidth}px`;
element.style.top =
`${((-projected.y + 1) / 2) * window.innerHeight}px`;
}
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const realDelta = Math.min(clock.getDelta(), 0.05);
const simulationDelta =
paused ? 0 : realDelta * Number(dom.speed.value);
if (!paused) {
autoTimer -= simulationDelta;
if (autoTimer <= 0 && autoRemaining > 0) {
createPulse();
autoRemaining--;
autoTimer = 6.15;
}
for (const pulse of pulses) {
updatePulse(pulse, simulationDelta);
}
}
updateCamera();
projectLabel(dom.rootLabel, labelAnchors.rootLabel);
projectLabel(dom.bareLabel, labelAnchors.bareLabel);
projectLabel(dom.sourceLabel, labelAnchors.sourceLabel);
renderer.render(scene, camera);
}
updateSummary();
animate();
</script>
</body>
</html>
```