Prompt specification
Build or customize the Three.js 3D scene "Buffer-width comparison exhibit" 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: Buffer-width comparison exhibit
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/buffer-width-comparison-exhibit-x1064
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring farm soil erosion control. Create an adjustable farm-edge model with fictional runoff and trapping parameters; users compare sediment reaching the stream while labels prohibit treating results as real watershed forecasts. Low-poly.
Working Three.js Starter (buffer-width-comparison-exhibit-x1064):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#e9eadf" />
<title>Farm Edge Lab — Fictional Soil Erosion Control</title>
<style>
:root {
--ink: #203128;
--muted: #687269;
--paper: rgba(250, 249, 241, 0.92);
--line: rgba(32, 49, 40, 0.15);
--green: #315b43;
--green-light: #dbe6d7;
--soil: #b86532;
--soil-light: #f2dfcd;
--water: #4b91a5;
--warning: #a64f29;
--shadow: 0 18px 50px rgba(36, 48, 37, 0.14);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e9eadf;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
button {
color: inherit;
cursor: pointer;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
cursor: grab;
touch-action: none;
outline: none;
}
#scene:active { cursor: grabbing; }
.topbar {
position: fixed;
z-index: 30;
top: 14px;
left: 14px;
right: 14px;
min-height: 68px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 12px 16px;
border: 1px solid rgba(255,255,255,0.65);
border-radius: 18px;
background: rgba(250,249,241,0.86);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
position: relative;
width: 39px;
height: 39px;
flex: 0 0 auto;
border-radius: 12px;
background: var(--green);
overflow: hidden;
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
left: 7px;
right: 7px;
height: 5px;
border-radius: 4px;
background: #d9dfbd;
transform: skewY(-13deg);
}
.brand-mark::before { top: 10px; }
.brand-mark::after { top: 22px; }
h1 {
margin: 0;
font-size: clamp(17px, 2vw, 23px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.subtitle {
margin-top: 5px;
color: var(--muted);
font-size: 12px;
letter-spacing: 0.025em;
}
.header-right {
display: flex;
align-items: center;
gap: 10px;
}
.forecast-chip {
display: flex;
align-items: center;
gap: 8px;
max-width: 360px;
padding: 9px 12px;
border: 1px solid rgba(166,79,41,0.24);
border-radius: 999px;
background: #f7e7d9;
color: #783b21;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.forecast-chip::before {
content: "!";
display: grid;
place-items: center;
width: 18px;
height: 18px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--warning);
color: white;
font-size: 12px;
}
.camera-tools {
display: flex;
gap: 6px;
}
.icon-button {
width: 34px;
height: 34px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255,255,255,0.7);
font-size: 17px;
line-height: 1;
}
.icon-button:hover { background: white; }
.panel {
position: fixed;
z-index: 20;
border: 1px solid rgba(255,255,255,0.7);
border-radius: 18px;
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
}
#controls {
top: 96px;
bottom: 18px;
left: 14px;
width: 302px;
padding: 17px;
overflow: auto;
scrollbar-width: thin;
}
.eyebrow {
margin-bottom: 7px;
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.panel h2 {
margin: 0;
font-size: 19px;
letter-spacing: -0.025em;
}
.intro {
margin: 8px 0 15px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.divider {
height: 1px;
margin: 14px 0;
background: var(--line);
}
.control {
margin: 0 0 15px;
}
.control-heading {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin-bottom: 8px;
}
.control-heading label {
font-size: 12px;
font-weight: 700;
}
output {
min-width: 76px;
padding: 4px 7px;
border-radius: 7px;
background: var(--green-light);
color: var(--green);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 800;
text-align: center;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 4px 0;
appearance: none;
border-radius: 999px;
background: linear-gradient(90deg, #6c8d69, #d8c9a9);
outline: none;
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
appearance: none;
border: 3px solid #f9f8ef;
border-radius: 50%;
background: var(--green);
box-shadow: 0 2px 7px rgba(31,49,38,0.28);
cursor: ew-resize;
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 3px solid #f9f8ef;
border-radius: 50%;
background: var(--green);
box-shadow: 0 2px 7px rgba(31,49,38,0.28);
cursor: ew-resize;
}
.range-ends {
display: flex;
justify-content: space-between;
margin-top: 4px;
color: #899087;
font-size: 9px;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.button {
min-height: 37px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255,255,255,0.75);
font-size: 11px;
font-weight: 800;
}
.button.primary {
border-color: var(--green);
background: var(--green);
color: white;
}
.button:hover { transform: translateY(-1px); }
details {
margin-top: 13px;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
summary {
color: var(--ink);
font-weight: 800;
cursor: pointer;
}
.formula {
margin-top: 9px;
padding: 10px;
border-radius: 10px;
background: rgba(49,91,67,0.07);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
}
#metrics {
top: 96px;
right: 14px;
width: 326px;
padding: 17px;
}
.metric-title {
margin: 0;
font-size: 18px;
line-height: 1.15;
letter-spacing: -0.03em;
}
.metric-subtitle {
margin-top: 6px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.comparison {
margin-top: 15px;
}
.comparison-row {
margin-top: 12px;
}
.comparison-label {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 8px;
margin-bottom: 6px;
font-size: 11px;
}
.comparison-label strong {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 15px;
}
.bar-track {
height: 9px;
overflow: hidden;
border-radius: 999px;
background: rgba(32,49,40,0.08);
}
.bar {
width: 100%;
height: 100%;
border-radius: inherit;
transition: width 180ms ease;
}
.bar.untreated { background: var(--soil); }
.bar.treated { background: var(--green); }
.metric-cards {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-top: 15px;
}
.mini-card {
min-width: 0;
padding: 10px 8px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255,255,255,0.5);
}
.mini-card span {
display: block;
overflow: hidden;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.05em;
text-overflow: ellipsis;
text-transform: uppercase;
white-space: nowrap;
}
.mini-card strong {
display: block;
margin-top: 5px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 16px;
}
.metric-note {
margin: 13px 0 0;
padding: 10px;
border-left: 3px solid var(--warning);
border-radius: 0 8px 8px 0;
background: #f7e7d9;
color: #6d3d28;
font-size: 10px;
line-height: 1.45;
}
#forecast-warning {
position: fixed;
z-index: 18;
left: 332px;
right: 356px;
bottom: 18px;
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
padding: 10px 14px;
border: 1px solid rgba(166,79,41,0.22);
border-radius: 12px;
background: rgba(250, 237, 225, 0.92);
color: #713b23;
box-shadow: 0 8px 30px rgba(57,46,31,0.09);
backdrop-filter: blur(10px);
font-size: 10px;
text-align: center;
}
#forecast-warning strong {
letter-spacing: 0.06em;
text-transform: uppercase;
white-space: nowrap;
}
#labels {
position: fixed;
z-index: 8;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.scene-label {
position: absolute;
display: flex;
align-items: center;
gap: 7px;
padding: 7px 9px;
border: 1px solid rgba(32,49,40,0.13);
border-radius: 10px;
background: rgba(251,250,243,0.88);
box-shadow: 0 5px 18px rgba(35,45,36,0.11);
color: var(--ink);
font-size: 10px;
font-weight: 800;
white-space: nowrap;
transform: translate(-50%, -50%);
backdrop-filter: blur(7px);
}
.scene-label .tag {
display: grid;
place-items: center;
width: 20px;
height: 20px;
border-radius: 6px;
background: var(--green);
color: white;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
}
.scene-label.soil .tag { background: var(--soil); }
.scene-label.water .tag { background: var(--water); }
.scene-label.warning-label {
border-color: rgba(166,79,41,0.25);
background: rgba(249,231,216,0.92);
color: #743b23;
}
#camera-hint {
position: fixed;
z-index: 9;
left: 333px;
bottom: 71px;
color: rgba(32,49,40,0.6);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
pointer-events: none;
}
@media (max-width: 980px) {
.forecast-chip { max-width: 230px; }
.forecast-chip { font-size: 8px; }
#metrics { width: 286px; }
#forecast-warning { right: 316px; }
#camera-hint { display: none; }
}
@media (max-width: 720px) {
.topbar {
top: 8px;
left: 8px;
right: 8px;
min-height: 58px;
padding: 9px 11px;
}
.brand-mark { width: 34px; height: 34px; }
.subtitle { display: none; }
.forecast-chip { display: none; }
.camera-tools { gap: 4px; }
.icon-button { width: 31px; height: 31px; }
#controls {
top: auto;
left: 8px;
right: 8px;
bottom: 8px;
width: auto;
max-height: 39vh;
padding: 14px;
border-radius: 15px;
}
#controls .intro,
#controls details,
#controls .divider {
display: none;
}
#metrics {
top: 76px;
right: 8px;
width: 220px;
padding: 12px;
border-radius: 14px;
}
.metric-title { font-size: 14px; }
.metric-subtitle { display: none; }
.comparison { margin-top: 9px; }
.comparison-row { margin-top: 8px; }
.metric-cards { margin-top: 9px; gap: 4px; }
.mini-card { padding: 7px 5px; }
.mini-card strong { font-size: 13px; }
.metric-note { display: none; }
#forecast-warning {
top: 76px;
left: 8px;
right: 238px;
bottom: auto;
padding: 8px;
border-radius: 12px;
font-size: 8px;
}
#forecast-warning strong {
white-space: normal;
}
#forecast-warning span { display: none; }
.scene-label { font-size: 8px; padding: 5px 7px; }
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive low-poly farm edge model comparing an untreated field edge with a vegetated buffer."></canvas>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>Farm Edge Lab</h1>
<div class="subtitle">Soil erosion control · interactive fictional scenario</div>
</div>
</div>
<div class="header-right">
<div class="forecast-chip">Fictional scenario · not a watershed forecast</div>
<div class="camera-tools" aria-label="Camera controls">
<button class="icon-button" id="zoom-in" title="Zoom in" aria-label="Zoom in">+</button>
<button class="icon-button" id="zoom-out" title="Zoom out" aria-label="Zoom out">−</button>
<button class="icon-button" id="reset-view" title="Reset camera" aria-label="Reset camera">↺</button>
</div>
</div>
</header>
<aside id="controls" class="panel" aria-label="Fictional model parameters">
<div class="eyebrow">Scenario controls</div>
<h2>Invent a storm. Tune the edge.</h2>
<p class="intro">
Plot A and Plot B share the same fictional storm, soil, runoff, and slope.
Only Plot B receives an adjustable grass filter.
</p>
<div class="control">
<div class="control-heading">
<label for="storm">Storm pulse</label>
<output id="storm-out" for="storm">0.90 ×</output>
</div>
<input id="storm" type="range" min="0.4" max="1.5" step="0.05" value="0.9" />
<div class="range-ends"><span>light</span><span>heavy</span></div>
</div>
<div class="control">
<div class="control-heading">
<label for="runoff">Runoff coefficient</label>
<output id="runoff-out" for="runoff">55%</output>
</div>
<input id="runoff" type="range" min="0.1" max="1" step="0.05" value="0.55" />
<div class="range-ends"><span>limited</span><span>high</span></div>
</div>
<div class="control">
<div class="control-heading">
<label for="soil">Soil exposure</label>
<output id="soil-out" for="soil">0.70 ×</output>
</div>
<input id="soil" type="range" min="0.2" max="1.4" step="0.05" value="0.7" />
<div class="range-ends"><span>covered</span><span>bare</span></div>
</div>
<div class="control">
<div class="control-heading">
<label for="slope">Field slope</label>
<output id="slope-out" for="slope">6%</output>
</div>
<input id="slope" type="range" min="2" max="12" step="1" value="6" />
<div class="range-ends"><span>gentle</span><span>steep</span></div>
</div>
<div class="divider"></div>
<div class="eyebrow">Plot B treatment</div>
<div class="control">
<div class="control-heading">
<label for="width">Grass-filter width</label>
<output id="width-out" for="width">1.2 model m</output>
</div>
<input id="width" type="range" min="0" max="2.2" step="0.1" value="1.2" />
<div class="range-ends"><span>none</span><span>wide</span></div>
</div>
<div class="control">
<div class="control-heading">
<label for="capture">Trapping strength</label>
<output id="capture-out" for="capture">70%</output>
</div>
<input id="capture" type="range" min="0" max="95" step="5" value="70" />
<div class="range-ends"><span>weak</span><span>strong</span></div>
</div>
<div class="button-row">
<button id="replay" class="button primary">Replay pulse</button>
<button id="pause" class="button">Pause flow</button>
</div>
<details>
<summary>About this toy model</summary>
<div class="formula">
runoff potential = storm × runoff × soil × √slope<br>
filtered load = untreated load × (1 − capture) × bypass
</div>
<p>
The equation, coefficients, units, and landscape are invented for interaction.
“Model metres” are visual units, not measurements of a real site.
</p>
</details>
</aside>
<section id="metrics" class="panel" aria-label="Fictional sediment comparison" aria-live="polite">
<div class="eyebrow">Fictional comparison</div>
<h2 class="metric-title">Sediment reaching the stream</h2>
<p class="metric-subtitle">
Relative index under the same invented conditions. FU means fictional units.
</p>
<div class="comparison">
<div class="comparison-row">
<div class="comparison-label">
<span>A · Untreated edge</span>
<strong id="baseline-value">55 FU</strong>
</div>
<div class="bar-track"><div id="baseline-bar" class="bar untreated"></div></div>
</div>
<div class="comparison-row">
<div class="comparison-label">
<span>B · Filtered edge</span>
<strong id="treated-value">16 FU</strong>
</div>
<div class="bar-track"><div id="treated-bar" class="bar treated"></div></div>
</div>
</div>
<div class="metric-cards">
<div class="mini-card">
<span>Toy reduction</span>
<strong id="reduction-value">71%</strong>
</div>
<div class="mini-card">
<span>Trapped FU</span>
<strong id="trapped-value">39</strong>
</div>
<div class="mini-card">
<span>Runoff index</span>
<strong id="runoff-value">11.0</strong>
</div>
</div>
<p class="metric-note">
<strong>Not a forecast.</strong> These fictional units are not calibrated to any
watershed and must not be used for planning, permitting, engineering, or
real-world risk decisions.
</p>
</section>
<div id="labels" aria-hidden="true">
<div id="label-a" class="scene-label soil"><span class="tag">A</span> Untreated farm edge</div>
<div id="label-b" class="scene-label"><span class="tag">B</span> Filtered farm edge</div>
<div id="label-buffer" class="scene-label"><span class="tag">↯</span> Fictional trapping zone</div>
<div id="label-flow" class="scene-label water"><span class="tag">↓</span> Invented runoff</div>
<div id="label-stream" class="scene-label warning-label"><span class="tag">!</span> Fictional stream — not a forecast</div>
</div>
<div id="camera-hint">Drag to orbit · shift-drag to pan · wheel to zoom</div>
<div id="forecast-warning" role="note">
<strong>Not a watershed forecast</strong>
<span>Illustrative fictional parameters only — do not use for planning or design.</span>
</div>
<noscript>This interactive scene requires JavaScript.</noscript>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// State and model
// ------------------------------------------------------------
const $ = (id) => document.getElementById(id);
const clamp = THREE.MathUtils.clamp;
const state = {
storm: 0.9,
runoff: 0.55,
soil: 0.7,
slope: 6,
width: 1.2,
capture: 70,
animate: true
};
function effectiveCapture() {
const widthFactor = state.width / 1.1;
const soilFactor = 0.72 + 0.28 * state.soil;
return 1 - Math.exp(-1.65 * (state.capture / 100) * widthFactor * soilFactor);
}
function computeModel() {
const runoffPotential =
14 +
72 *
((0.30 + 0.70 * state.runoff) *
(0.55 + 0.45 * state.storm) *
(0.45 + 0.55 * state.soil) *
Math.sqrt(state.slope / 6));
const untreated = runoffPotential;
const bypass = 0.04 + 0.10 * state.runoff * (1 - state.capture / 100);
const treated = untreated * (1 - effectiveCapture()) * (1 - bypass);
const reduction = untreated > 0 ? 1 - treated / untreated : 0;
return {
untreated,
treated,
reduction,
trapped: Math.max(0, untreated - treated),
runoffIndex: 22 * state.storm * state.runoff
};
}
// ------------------------------------------------------------
// Renderer, camera, and direct camera controls
// ------------------------------------------------------------
const canvas = $("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe9eadf);
scene.fog = new THREE.Fog(0xe9eadf, 35, 62);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 0.45, 0.35);
let cameraYaw = 0.49;
let cameraPitch = 0.88;
let cameraRadius = 24.5;
function applyCamera() {
const sinPitch = Math.sin(cameraPitch);
camera.position.set(
cameraTarget.x + cameraRadius * sinPitch * Math.sin(cameraYaw),
cameraTarget.y + cameraRadius * Math.cos(cameraPitch),
cameraTarget.z + cameraRadius * sinPitch * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraYaw = 0.49;
cameraPitch = 0.88;
cameraRadius = 24.5;
cameraTarget.set(0, 0.45, 0.35);
applyCamera();
}
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (event.shiftKey) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3().crossVectors(forward, camera.up).normalize();
cameraTarget.addScaledVector(right, -dx * cameraRadius * 0.0012);
cameraTarget.addScaledVector(forward, dy * cameraRadius * 0.0012);
cameraTarget.x = clamp(cameraTarget.x, -5, 5);
cameraTarget.z = clamp(cameraTarget.z, -3, 4);
} else {
cameraYaw -= dx * 0.005;
cameraPitch = clamp(cameraPitch + dy * 0.004, 0.48, 1.22);
}
applyCamera();
});
function endDrag(event) {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("wheel", (event) => {
event.preventDefault();
cameraRadius = clamp(cameraRadius * Math.exp(event.deltaY * 0.001), 13, 38);
applyCamera();
}, { passive: false });
$("zoom-in").addEventListener("click", () => {
cameraRadius = clamp(cameraRadius * 0.86, 13, 38);
applyCamera();
});
$("zoom-out").addEventListener("click", () => {
cameraRadius = clamp(cameraRadius * 1.16, 13, 38);
applyCamera();
});
$("reset-view").addEventListener("click", resetCamera);
// ------------------------------------------------------------
// Lighting
// ------------------------------------------------------------
const hemisphere = new THREE.HemisphereLight(0xf8fbff, 0x7a795f, 2.25);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff2d7, 3.3);
sun.position.set(-9, 15, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -16;
sun.shadow.camera.right = 16;
sun.shadow.camera.top = 14;
sun.shadow.camera.bottom = -14;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 42;
sun.shadow.bias = -0.00025;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb8d5db, 0.65);
fill.position.set(9, 7, -8);
scene.add(fill);
// ------------------------------------------------------------
// Geometry helpers
// ------------------------------------------------------------
const plotCenters = [-4.45, 4.45];
const plotWidth = 7.05;
const fieldStartZ = -4.6;
const fieldEndZ = 3.35;
const bufferStartZ = 1.0;
function hash01(index, seed = 0) {
const value = Math.sin((index + 1) * 12.9898 + seed * 78.233) * 43758.5453;
return value - Math.floor(value);
}
function terrainHeight(z) {
const t = clamp((z - fieldStartZ) / (fieldEndZ - fieldStartZ), 0, 1);
return 1.42 - t * 1.14;
}
function makeSurfaceGeometry(cx, width, z0, z1, colorHex, seed = 0) {
const segX = 8;
const segZ = 10;
const positions = [];
const colors = [];
const indices = [];
const color = new THREE.Color(colorHex);
for (let iz = 0; iz <= segZ; iz++) {
const z = THREE.MathUtils.lerp(z0, z1, iz / segZ);
for (let ix = 0; ix <= segX; ix++) {
const x = cx - width / 2 + (ix / segX) * width;
positions.push(x, terrainHeight(z), z);
const c = color.clone();
c.offsetHSL(0, 0, (hash01(iz * 31 + ix, seed) - 0.5) * 0.075);
colors.push(c.r, c.g, c.b);
}
}
for (let iz = 0; iz < segZ; iz++) {
for (let ix = 0; ix < segX; ix++) {
const a = iz * (segX + 1) + ix;
const b = a + 1;
const c = a + segX + 1;
const d = c + 1;
indices.push(a, c, b, b, c, d);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
function addTerrainSkirt(cx, width, z0, z1) {
const positions = [];
function quad(a, b, c, d) {
positions.push(...a, ...b, ...d, ...b, ...c, ...d);
}
const segments = 8;
for (let i = 0; i < segments; i++) {
const za = THREE.MathUtils.lerp(z0, z1, i / segments);
const zb = THREE.MathUtils.lerp(z0, z1, (i + 1) / segments);
quad(
[cx - width / 2, terrainHeight(za), za],
[cx - width / 2, terrainHeight(zb), zb],
[cx - width / 2, 0, zb],
[cx - width / 2, 0, za]
);
quad(
[cx + width / 2, terrainHeight(zb), zb],
[cx + width / 2, terrainHeight(za), za],
[cx + width / 2, 0, za],
[cx + width / 2, 0, zb]
);
}
for (let i = 0; i < segments; i++) {
const xa = cx - width / 2 + (i / segments) * width;
const xb = cx - width / 2 + ((i + 1) / segments) * width;
quad(
[xa, terrainHeight(z1), z1],
[xb, terrainHeight(z1), z1],
[xb, 0, z1],
[xa, 0, z1]
);
quad(
[xb, terrainHeight(z0), z0],
[xa, terrainHeight(z0), z0],
[xa, 0, z0],
[xb, 0, z0]
);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color: 0x8c6544,
roughness: 1,
flatShading: true
})
);
mesh.receiveShadow = true;
scene.add(mesh);
}
function addTerrain(cx, width, color) {
addTerrainSkirt(cx, width, fieldStartZ, fieldEndZ);
const geometry = makeSurfaceGeometry(cx, width, fieldStartZ, fieldEndZ, color, cx + 3);
const mesh = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 1,
flatShading: true
})
);
mesh.receiveShadow = true;
mesh.castShadow = true;
scene.add(mesh);
}
function addBox(width, height, depth, color, x, y, z, parent = scene) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
new THREE.MeshStandardMaterial({ color, roughness: 0.95, flatShading: true })
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// ------------------------------------------------------------
// Diorama
// ------------------------------------------------------------
const base = addBox(18.6, 0.8, 11.6, 0xb9aa86, 0, -0.4, 0.1);
base.castShadow = false;
const baseEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(base.geometry),
new THREE.LineBasicMaterial({ color: 0x8b7a5f, transparent: true, opacity: 0.35 })
);
baseEdges.position.copy(base.position);
scene.add(baseEdges);
addTerrain(plotCenters[0], plotWidth, 0xa97950);
addTerrain(plotCenters[1], plotWidth, 0xa97950);
const pathGeometry = makeSurfaceGeometry(0, 0.62, -4.8, 3.35, 0xc8b48a, 42);
const path = new THREE.Mesh(
pathGeometry,
new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 1, flatShading: true })
);
path.position.y = 0.015;
path.receiveShadow = true;
scene.add(path);
// Faceted stream.
const streamGeometry = new THREE.PlaneGeometry(18.05, 1.46, 18, 2);
streamGeometry.rotateX(-Math.PI / 2);
const stream = new THREE.Mesh(
streamGeometry,
new THREE.MeshStandardMaterial({
color: 0x5d9eae,
roughness: 0.52,
metalness: 0.04,
flatShading: true
})
);
stream.position.set(0, 0.075, 4.14);
stream.receiveShadow = true;
scene.add(stream);
// Stream-bank stones.
const rockGeometry = new THREE.DodecahedronGeometry(0.18, 0);
for (let i = 0; i < 28; i++) {
const rock = new THREE.Mesh(
rockGeometry,
new THREE.MeshStandardMaterial({
color: i % 3 === 0 ? 0x9a927d : 0xb0a68d,
roughness: 1,
flatShading: true
})
);
rock.position.set(
-8.7 + i * 0.65,
0.12,
4.86 + (hash01(i, 8) - 0.5) * 0.14
);
rock.scale.set(
0.65 + hash01(i, 9) * 0.75,
0.45 + hash01(i, 10) * 0.45,
0.65 + hash01(i, 11) * 0.75
);
rock.rotation.set(hash01(i, 12), hash01(i, 13) * 6, hash01(i, 14));
rock.castShadow = true;
scene.add(rock);
}
// Animated pale streaks on the water.
const streamStreaks = [];
const streakMaterial = new THREE.MeshBasicMaterial({
color: 0xc9e8e8,
transparent: true,
opacity: 0.48,
depthWrite: false
});
for (let i = 0; i < 24; i++) {
const streak = new THREE.Mesh(
new THREE.BoxGeometry(0.42 + hash01(i, 19) * 0.8, 0.012, 0.025),
streakMaterial
);
streak.position.set(-8.7 + hash01(i, 20) * 17.4, 0.095, 3.55 + hash01(i, 21) * 1.2);
streak.userData.speed = 0.18 + hash01(i, 22) * 0.32;
streamStreaks.push(streak);
scene.add(streak);
}
// Crop rows, represented as low-poly instanced stalks.
const cropGeometry = new THREE.ConeGeometry(0.09, 0.42, 5);
cropGeometry.translate(0, 0.21, 0);
const cropMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1,
flatShading: true
});
for (let plotIndex = 0; plotIndex < 2; plotIndex++) {
const cx = plotCenters[plotIndex];
const rows = 10;
const columns = 12;
const crops = new THREE.InstancedMesh(cropGeometry, cropMaterial, rows * columns);
crops.castShadow = true;
crops.receiveShadow = true;
const matrix = new THREE.Matrix4();
const quaternion = new THREE.Quaternion();
const scale = new THREE.Vector3();
const position = new THREE.Vector3();
const color = new THREE.Color();
let instance = 0;
for (let row = 0; row < rows; row++) {
const z = -3.95 + row * 0.43;
for (let column = 0; column < columns; column++) {
const x = cx - plotWidth * 0.43 + column * 0.55 + (row % 2) * 0.12;
position.set(x, terrainHeight(z) + 0.015, z);
quaternion.setFromEuler(new THREE.Euler(0, hash01(instance, 30) * Math.PI, 0));
const s = 0.72 + hash01(instance, 31) * 0.48;
scale.set(s, s * (0.85 + hash01(instance, 32) * 0.35), s);
matrix.compose(position, quaternion, scale);
crops.setMatrixAt(instance, matrix);
color.setHSL(
0.21 + hash01(instance, 33) * 0.055,
0.34 + hash01(instance, 34) * 0.16,
0.34 + hash01(instance, 35) * 0.10
);
crops.setColorAt(instance, color);
instance++;
}
}
crops.instanceMatrix.needsUpdate = true;
if (crops.instanceColor) crops.instanceColor.needsUpdate = true;
scene.add(crops);
// Darker furrows.
for (let row = 0; row < rows; row++) {
const z = -3.94 + row * 0.43;
addBox(
plotWidth * 0.87,
0.028,
0.07,
0x7c553b,
cx,
terrainHeight(z) + 0.018,
z
);
}
}
// Low-poly trees along the back edge.
function addTree(x, z, size) {
const group = new THREE.Group();
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.09, 0.13, 0.72, 5),
new THREE.MeshStandardMaterial({ color: 0x755238, roughness: 1, flatShading: true })
);
trunk.position.y = 0.36;
trunk.castShadow = true;
group.add(trunk);
const crown = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.42, 0),
new THREE.MeshStandardMaterial({ color: 0x577a4c, roughness: 1, flatShading: true })
);
crown.position.y = 0.93;
crown.scale.set(0.9, 1.15, 0.9);
crown.castShadow = true;
group.add(crown);
group.position.set(x, 0.02, z);
group.scale.setScalar(size);
scene.add(group);
}
addTree(-7.85, -5.05, 1.0);
addTree(-6.75, -5.18, 0.78);
addTree(6.65, -5.12, 0.85);
addTree(7.85, -5.0, 1.08);
// Rear fence.
const fenceY = terrainHeight(-4.83) + 0.38;
for (let x = -8.3; x <= 8.3; x += 1.55) {
addBox(0.085, 0.78, 0.085, 0x8f6e48, x, fenceY, -4.83);
}
addBox(16.7, 0.075, 0.07, 0xa17b4f, 0, fenceY + 0.16, -4.83);
addBox(16.7, 0.075, 0.07, 0xa17b4f, 0, fenceY - 0.14, -4.83);
// ------------------------------------------------------------
// Dynamic vegetated filter
// ------------------------------------------------------------
const treatmentX = plotCenters[1];
let bufferSurface = null;
const bufferSurfaceMaterial = new THREE.MeshStandardMaterial({
color: 0x71855a,
vertexColors: true,
transparent: true,
opacity: 0.86,
roughness: 1,
flatShading: true,
side: THREE.DoubleSide
});
const grassGeometry = new THREE.ConeGeometry(0.085, 0.36, 4);
grassGeometry.translate(0, 0.18, 0);
const grassMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1,
flatShading: true
});
const grass = new THREE.InstancedMesh(grassGeometry, grassMaterial, 130);
grass.castShadow = true;
grass.receiveShadow = true;
scene.add(grass);
const depositGeometry = new THREE.IcosahedronGeometry(0.12, 0);
const depositMaterial = new THREE.MeshStandardMaterial({
color: 0xb76532,
roughness: 1,
flatShading: true
});
const deposits = new THREE.InstancedMesh(depositGeometry, depositMaterial, 70);
deposits.castShadow = true;
scene.add(deposits);
const depositPatch = new THREE.Mesh(
new THREE.CircleGeometry(0.62, 18),
new THREE.MeshBasicMaterial({
color: 0xad6233,
transparent: true,
opacity: 0.23,
depthWrite: false,
side: THREE.DoubleSide
})
);
depositPatch.rotation.x = -Math.PI / 2;
scene.add(depositPatch);
function updateBuffer() {
const width = state.width;
if (bufferSurface) {
scene.remove(bufferSurface);
bufferSurface.geometry.dispose();
bufferSurface = null;
}
if (width > 0.01) {
const geometry = makeSurfaceGeometry(
treatmentX,
plotWidth * 0.96,
bufferStartZ,
bufferStartZ + width,
0x72885b,
73
);
bufferSurface = new THREE.Mesh(geometry, bufferSurfaceMaterial);
bufferSurface.position.y = 0.025;
bufferSurface.receiveShadow = true;
scene.add(bufferSurface);
}
const grassCount = Math.round(18 + width * 48);
const matrix = new THREE.Matrix4();
const quaternion = new THREE.Quaternion();
const position = new THREE.Vector3();
const scale = new THREE.Vector3();
const color = new THREE.Color();
for (let i = 0; i < grass.count; i++) {
const active = i < grassCount && width > 0.01;
if (!active) {
matrix.makeScale(0, 0, 0);
grass.setMatrixAt(i, matrix);
continue;
}
const x = treatmentX + (hash01(i, 90) - 0.5) * plotWidth * 0.9;
const z = bufferStartZ + 0.07 + hash01(i, 91) * Math.max(0.03, width - 0.12);
position.set(x, terrainHeight(z) + 0.035, z);
quaternion.setFromEuler(
new THREE.Euler(
(hash01(i, 92) - 0.5) * 0.15,
hash01(i, 93) * Math.PI,
(hash01(i, 94) - 0.5) * 0.15
)
);
const s = 0.72 + hash01(i, 95) * 0.55;
scale.set(s, s, s);
matrix.compose(position, quaternion, scale);
grass.setMatrixAt(i, matrix);
color.setHSL(
0.20 + hash01(i, 96) * 0.065,
0.30 + hash01(i, 97) * 0.20,
0.33 + hash01(i, 98) * 0.10
);
grass.setColorAt(i, color);
}
grass.count = grassCount;
grass.instanceMatrix.needsUpdate = true;
if (grass.instanceColor) grass.instanceColor.needsUpdate = true;
const model = computeModel();
const trappedFraction = model.untreated > 0 ? model.trapped / model.untreated : 0;
const depositCount = Math.round(trappedFraction * 70 * Math.min(1, width / 1.3));
for (let i = 0; i < deposits.count; i++) {
if (i >= depositCount || width <= 0.01) {
matrix.makeScale(0, 0, 0);
deposits.setMatrixAt(i, matrix);
continue;
}
const x = treatmentX + (hash01(i, 100) - 0.5) * plotWidth * 0.85;
const z = bufferStartZ + 0.12 + hash01(i, 101) * Math.max(0.03, width - 0.18);
position.set(x, terrainHeight(z) + 0.085, z);
quaternion.setFromEuler(
new THREE.Euler(hash01(i, 102) * 3, hash01(i, 103) * 6, hash01(i, 104) * 3)
);
const s = 0.55 + hash01(i, 105) * 0.85;
scale.set(s, s * 0.55, s);
matrix.compose(position, quaternion, scale);
deposits.setMatrixAt(i, matrix);
}
deposits.count = depositCount;
deposits.instanceMatrix.needsUpdate = true;
const patchZ = bufferStartZ + width * 0.52;
depositPatch.position.set(
treatmentX + (hash01(4, 110) - 0.5) * 1.1,
terrainHeight(patchZ) + 0.045,
patchZ
);
depositPatch.scale.set(
0.8 + width * 0.55,
0.45 + width * 0.35,
1
);
depositPatch.material.opacity = width > 0 ? 0.12 + trappedFraction * 0.28 : 0;
}
// ------------------------------------------------------------
// Flow and sediment particle systems
// ------------------------------------------------------------
const maxWaterParticles = 130;
const maxSedimentParticles = 75;
function createFlowSet(cx, treatment) {
const waterGeometry = new THREE.BufferGeometry();
const waterPositions = new Float32Array(maxWaterParticles * 3);
waterGeometry.setAttribute(
"position",
new THREE.BufferAttribute(waterPositions, 3).setUsage(THREE.DynamicDrawUsage)
);
waterGeometry.setDrawRange(0, 0);
const water = new THREE.Points(
waterGeometry,
new THREE.PointsMaterial({
color: 0x8ed7e5,
size: 0.075,
transparent: true,
opacity: 0.88,
depthWrite: false,
sizeAttenuation: true
})
);
scene.add(water);
const sedimentGeometry = new THREE.BufferGeometry();
const sedimentPositions = new Float32Array(maxSedimentParticles * 3);
sedimentGeometry.setAttribute(
"position",
new THREE.BufferAttribute(sedimentPositions, 3).setUsage(THREE.DynamicDrawUsage)
);
sedimentGeometry.setDrawRange(0, 0);
const sediment = new THREE.Points(
sedimentGeometry,
new THREE.PointsMaterial({
color: 0xd26f34,
size: 0.115,
transparent: true,
opacity: 0.95,
depthWrite: false,
sizeAttenuation: true
})
);
scene.add(sediment);
const waterParticles = [];
const sedimentParticles = [];
for (let i = 0; i < maxWaterParticles; i++) {
waterParticles.push({
x: cx + (Math.random() - 0.5) * plotWidth * 0.87,
z: -4 + Math.random() * 7.4,
speed: 0.45 + Math.random() * 0.55
});
}
for (let i = 0; i < maxSedimentParticles; i++) {
sedimentParticles.push({
x: cx + (Math.random() - 0.5) * plotWidth * 0.86,
z: -3.9 + Math.random() * 2.2,
speed: 0.34 + Math.random() * 0.42,
decided: false,
trapped: false,
trapZ: 1.1,
hold: 0
});
}
return {
cx,
treatment,
water,
waterGeometry,
waterPositions,
waterParticles,
sediment,
sedimentGeometry,
sedimentPositions,
sedimentParticles,
waterCount: 0,
sedimentCount: 0
};
}
const flowSets = [
createFlowSet(plotCenters[0], false),
createFlowSet(plotCenters[1], true)
];
function resetParticle(p, set, sediment = false) {
p.x = set.cx + (Math.random() - 0.5) * plotWidth * (sediment ? 0.86 : 0.88);
p.z = -4.05 + Math.random() * (sediment ? 2.0 : 7.6);
p.speed = sediment
? 0.32 + Math.random() * 0.42
: 0.48 + Math.random() * 0.58;
p.decided = false;
p.trapped = false;
p.hold = 0;
p.trapZ = bufferStartZ + 0.06 + Math.random() * Math.max(0.03, state.width - 0.1);
}
function resetAllParticles() {
for (const set of flowSets) {
set.waterParticles.forEach((p) => resetParticle(p, set, false));
set.sedimentParticles.forEach((p) => resetParticle(p, set, true));
}
}
function updateFlowCounts() {
for (const set of flowSets) {
set.waterCount = Math.min(
maxWaterParticles,
Math.round(18 + 73 * state.storm * state.runoff)
);
set.sedimentCount = Math.min(
maxSedimentParticles,
Math.round(8 + 48 * state.runoff * state.soil)
);
}
}
function updateFlowSet(set, dt) {
const waterSpeedFactor = 0.62 + state.storm * 0.45;
for (let i = 0; i < set.waterCount; i++) {
const p = set.waterParticles[i];
p.z += p.speed * dt * waterSpeedFactor;
if (p.z > 3.63) resetParticle(p, set, false);
const z = clamp(p.z, fieldStartZ, fieldEndZ);
const wobble = Math.sin(p.z * 2.7 + i) * 0.025;
set.waterPositions[i * 3] = p.x + wobble;
set.waterPositions[i * 3 + 1] = terrainHeight(z) + 0.12;
set.waterPositions[i * 3 + 2] = p.z;
}
set.waterGeometry.setDrawRange(0, set.waterCount);
set.waterGeometry.attributes.position.needsUpdate = true;
const trapChance = effectiveCapture() * 0.97;
for (let i = 0; i < set.sedimentCount; i++) {
const p = set.sedimentParticles[i];
if (p.hold > 0) {
p.hold -= dt;
if (p.hold <= 0) resetParticle(p, set, true);
} else {
p.z += p.speed * dt * (0.65 + state.storm * 0.38);
if (set.treatment && !p.decided && p.z >= bufferStartZ) {
p.decided = true;
p.trapped = Math.random() < trapChance;
p.trapZ = bufferStartZ + 0.05 +
Math.random() * Math.max(0.03, state.width - 0.08);
}
if (p.trapped && p.z >= p.trapZ) {
p.z = p.trapZ;
} else if (p.z > 3.47) {
p.z = 3.47;
p.hold = 0.45;
}
}
const z = clamp(p.z, fieldStartZ, fieldEndZ);
set.sedimentPositions[i * 3] = p.x;
set.sedimentPositions[i * 3 + 1] = terrainHeight(z) + 0.16;
set.sedimentPositions[i * 3 + 2] = p.z;
}
set.sedimentGeometry.setDrawRange(0, set.sedimentCount);
set.sedimentGeometry.attributes.position.needsUpdate = true;
}
// Plumes in the receiving stream scale with the fictional load.
const plumeMaterial = new THREE.MeshBasicMaterial({
color: 0xc8783c,
transparent: true,
opacity: 0.28,
depthWrite: false,
side: THREE.DoubleSide
});
const baselinePlume = new THREE.Mesh(new THREE.CircleGeometry(0.72, 18), plumeMaterial);
baselinePlume.rotation.x = -Math.PI / 2;
baselinePlume.position.set(plotCenters[0], 0.105, 3.55);
scene.add(baselinePlume);
const treatedPlume = new THREE.Mesh(
new THREE.CircleGeometry(0.72, 18),
plumeMaterial.clone()
);
treatedPlume.rotation.x = -Math.PI / 2;
treatedPlume.position.set(plotCenters[1], 0.106, 3.55);
scene.add(treatedPlume);
// ------------------------------------------------------------
// Stylized rain
// ------------------------------------------------------------
const maxRainDrops = 110;
const rainGeometry = new THREE.BufferGeometry();
const rainPositions = new Float32Array(maxRainDrops * 2 * 3);
rainGeometry.setAttribute(
"position",
new THREE.BufferAttribute(rainPositions, 3).setUsage(THREE.DynamicDrawUsage)
);
rainGeometry.setDrawRange(0, 0);
const rain = new THREE.LineSegments(
rainGeometry,
new THREE.LineBasicMaterial({
color: 0x8eb5bd,
transparent: true,
opacity: 0.35,
depthWrite: false
})
);
scene.add(rain);
const rainDrops = [];
for (let i = 0; i < maxRainDrops; i++) {
rainDrops.push({
x: -8.5 + Math.random() * 17,
y: 2 + Math.random() * 7,
z: -4.8 + Math.random() * 9.3,
speed: 4.3 + Math.random() * 2.8,
length: 0.28 + Math.random() * 0.32
});
}
function updateRain(dt) {
const count = Math.min(maxRainDrops, Math.round(24 + state.storm * 60));
for (let i = 0; i < count; i++) {
const drop = rainDrops[i];
drop.y -= drop.speed * dt;
drop.x -= dt * 0.2;
if (drop.y < 0.1) {
drop.y = 8.3 + Math.random() * 1.6;
drop.x = -8.5 + Math.random() * 17;
drop.z = -4.8 + Math.random() * 9.3;
}
const offset = i * 6;
rainPositions[offset] = drop.x;
rainPositions[offset + 1] = drop.y;
rainPositions[offset + 2] = drop.z;
rainPositions[offset + 3] = drop.x - 0.035;
rainPositions[offset + 4] = drop.y - drop.length;
rainPositions[offset + 5] = drop.z + 0.015;
}
rainGeometry.setDrawRange(0, count * 2);
rainGeometry.attributes.position.needsUpdate = true;
rain.material.opacity = 0.18 + state.storm * 0.17;
}
// ------------------------------------------------------------
// UI and model updates
// ------------------------------------------------------------
const inputs = ["storm", "runoff", "soil", "slope", "width", "capture"];
function updateOutputs() {
$("storm-out").textContent = `${state.storm.toFixed(2)} ×`;
$("runoff-out").textContent = `${Math.round(state.runoff * 100)}%`;
$("soil-out").textContent = `${state.soil.toFixed(2)} ×`;
$("slope-out").textContent = `${Math.round(state.slope)}%`;
$("width-out").textContent = `${state.width.toFixed(1)} model m`;
$("capture-out").textContent = `${Math.round(state.capture)}%`;
}
function updateMetrics() {
const model = computeModel();
const baseline = Math.round(model.untreated);
const treated = Math.round(model.treated);
const reduction = Math.round(model.reduction * 100);
$("baseline-value").textContent = `${baseline} FU`;
$("treated-value").textContent = `${treated} FU`;
$("reduction-value").textContent = `${reduction}%`;
$("trapped-value").textContent = String(Math.round(model.trapped));
$("runoff-value").textContent = model.runoffIndex.toFixed(1);
$("baseline-bar").style.width = "100%";
$("treated-bar").style.width = `${clamp(model.reduction * 100, 0, 100)}%`;
baselinePlume.scale.set(
0.65 + model.untreated / 80,
0.35 + model.untreated / 180,
1
);
baselinePlume.material.opacity = 0.13 + model.untreated / 320;
treatedPlume.scale.set(
0.25 + model.treated / 75,
0.22 + model.treated / 180,
1
);
treatedPlume.material.opacity = 0.07 + model.treated / 390;
}
function updateModel() {
updateOutputs();
updateBuffer();
updateMetrics();
updateFlowCounts();
}
inputs.forEach((id) => {
$(id).addEventListener("input", (event) => {
state[id] = Number(event.target.value);
updateModel();
});
});
$("replay").addEventListener("click", () => {
state.animate = true;
$("pause").textContent = "Pause flow";
resetAllParticles();
});
$("pause").addEventListener("click", () => {
state.animate = !state.animate;
$("pause").textContent = state.animate ? "Pause flow" : "Resume flow";
});
// ------------------------------------------------------------
// Labels
// ------------------------------------------------------------
const projected = new THREE.Vector3();
function placeLabel(id, worldPosition, offsetX = 0, offsetY = 0) {
const element = $(id);
projected.copy(worldPosition).project(camera);
const visible = projected.z > -1 && projected.z < 1;
const x = (projected.x * 0.5 + 0.5) * window.innerWidth + offsetX;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight + offsetY;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
element.style.opacity = visible ? "1" : "0";
}
function updateLabels() {
placeLabel("label-a", new THREE.Vector3(-4.45, 1.85, -3.15), 0, -8);
placeLabel("label-b", new THREE.Vector3(4.45, 1.85, -3.15), 0, -8);
const bufferCenter = bufferStartZ + state.width * 0.5;
placeLabel(
"label-buffer",
new THREE.Vector3(treatmentX + 1.45, terrainHeight(bufferCenter) + 0.55, bufferCenter),
52,
0
);
placeLabel(
"label-flow",
new THREE.Vector3(-4.45, terrainHeight(-0.3) + 0.55, -0.3),
-60,
0
);
placeLabel(
"label-stream",
new THREE.Vector3(0, 0.35, 4.2),
0,
36
);
}
// ------------------------------------------------------------
// Resize and animation loop
// ------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height, false);
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
camera.aspect = width / height;
camera.fov = width < 720 ? 49 : 38;
camera.updateProjectionMatrix();
applyCamera();
}
window.addEventListener("resize", resize);
resize();
resetCamera();
updateModel();
resetAllParticles();
let previousTime = performance.now();
function animate(now) {
const dt = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (state.animate) {
updateRain(dt);
flowSets.forEach((set) => updateFlowSet(set, dt));
for (const streak of streamStreaks) {
streak.position.x += streak.userData.speed * dt;
if (streak.position.x > 9) streak.position.x = -9;
}
}
updateLabels();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```