Prompt specification
Build or customize the Three.js 3D scene "Buffer Placement Versus Width Experiment" 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 Placement Versus Width Experiment
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/buffer-placement-versus-width-experiment-x3968
Scene Description Prompt:
Create a standalone HTML scene with Three.js from cdnjs comparing low-poly riparian buffer widths and placements under synthetic sediment-retention rules.
Working Three.js Starter (buffer-placement-versus-width-experiment-x3968):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Riparian Buffer Lab</title>
<style>
:root {
--ink: #193129;
--muted: #62766d;
--paper: #f4f2e9;
--panel: rgba(255, 255, 252, 0.94);
--line: #d7ddd4;
--a: #10a99a;
--a-light: #d7f4ed;
--b: #e79a25;
--b-light: #fff0cf;
--water: #3c93b4;
--shadow: 0 16px 40px rgba(31, 52, 42, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
}
body {
display: grid;
grid-template-rows: 72px minmax(0, 1fr) 252px;
overflow: hidden;
color: var(--ink);
background: var(--paper);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
header {
z-index: 5;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 22px;
border-bottom: 1px solid var(--line);
background: rgba(250, 249, 243, 0.96);
}
.brand {
display: flex;
align-items: center;
min-width: 0;
gap: 12px;
}
.brand-mark {
display: grid;
flex: 0 0 42px;
width: 42px;
height: 42px;
place-items: center;
border-radius: 13px;
color: white;
background: var(--ink);
box-shadow: 0 8px 20px rgba(25, 49, 41, 0.18);
}
.brand-mark svg {
width: 27px;
height: 27px;
}
.brand-copy {
min-width: 0;
}
.eyebrow {
margin: 0 0 2px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 18px;
font-weight: 780;
letter-spacing: -0.02em;
white-space: nowrap;
}
.header-meta {
display: flex;
align-items: center;
gap: 12px;
}
.load-chip {
padding: 7px 10px;
border: 1px solid #cddbd1;
border-radius: 999px;
color: #476257;
background: #eef5ef;
font-size: 11px;
font-weight: 700;
white-space: nowrap;
}
.toolbar {
display: flex;
gap: 7px;
}
.tool-button {
min-height: 34px;
padding: 7px 11px;
border: 1px solid var(--line);
border-radius: 10px;
background: white;
cursor: pointer;
font-size: 12px;
font-weight: 700;
transition:
transform 120ms ease,
border-color 120ms ease,
background 120ms ease;
}
.tool-button:hover {
border-color: #aebdb4;
background: #f9faf6;
transform: translateY(-1px);
}
.tool-button[aria-pressed="false"] {
color: var(--muted);
background: #eef0eb;
}
#stage {
position: relative;
min-height: 0;
overflow: hidden;
background: #dbe4df;
}
canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
#split-line {
position: absolute;
z-index: 2;
top: 0;
bottom: 0;
left: 50%;
width: 1px;
pointer-events: none;
background: rgba(255, 255, 255, 0.8);
box-shadow: 0 0 0 1px rgba(42, 67, 57, 0.1);
}
.pane-label {
position: absolute;
z-index: 3;
top: 15px;
left: 15px;
width: min(355px, calc(50% - 30px));
padding: 12px 13px;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 14px;
pointer-events: none;
background: rgba(255, 255, 252, 0.86);
box-shadow: var(--shadow);
backdrop-filter: blur(10px);
}
.pane-label.b {
left: calc(50% + 15px);
}
.pane-heading {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 8px;
}
.scenario-letter {
display: grid;
width: 28px;
height: 28px;
place-items: center;
border-radius: 9px;
color: white;
background: var(--a);
font-size: 13px;
font-weight: 850;
}
.scenario-letter.b {
background: var(--b);
}
.pane-title {
font-size: 13px;
font-weight: 820;
letter-spacing: -0.01em;
}
.pane-subtitle {
margin-left: auto;
color: var(--muted);
font-size: 10px;
font-weight: 650;
}
.metric-row {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 7px;
}
.metric {
padding: 7px 8px;
border: 1px solid rgba(209, 218, 210, 0.9);
border-radius: 9px;
background: rgba(255, 255, 255, 0.62);
}
.metric strong {
display: block;
margin-bottom: 1px;
color: var(--ink);
font-size: 14px;
font-variant-numeric: tabular-nums;
}
.metric span {
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
}
#comparison-badge {
position: absolute;
z-index: 4;
bottom: 16px;
left: 50%;
max-width: calc(100% - 30px);
padding: 9px 14px;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 999px;
pointer-events: none;
background: rgba(25, 49, 41, 0.9);
box-shadow: var(--shadow);
color: white;
font-size: 11px;
font-weight: 750;
text-align: center;
transform: translateX(-50%);
backdrop-filter: blur(8px);
}
#legend {
position: absolute;
z-index: 3;
bottom: 17px;
left: 15px;
display: flex;
gap: 11px;
padding: 8px 10px;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 11px;
pointer-events: none;
background: rgba(255, 255, 252, 0.78);
color: #52665d;
font-size: 10px;
font-weight: 700;
backdrop-filter: blur(8px);
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
}
.swatch {
width: 10px;
height: 10px;
border-radius: 3px;
}
.swatch.a {
background: var(--a);
}
.swatch.b {
background: var(--b);
}
.swatch.water {
background: var(--water);
}
#controls {
z-index: 5;
display: grid;
grid-template-columns: minmax(280px, 1fr) minmax(280px, 1fr) minmax(245px, 0.82fr);
gap: 12px;
min-height: 0;
padding: 12px;
overflow: auto;
border-top: 1px solid var(--line);
background: #f8f7f1;
}
.control-card {
min-width: 0;
padding: 13px 14px;
border: 1px solid var(--line);
border-radius: 15px;
background: var(--panel);
box-shadow: 0 4px 15px rgba(36, 58, 48, 0.05);
}
.scenario-card {
position: relative;
overflow: hidden;
}
.scenario-card::before {
position: absolute;
top: 0;
bottom: 0;
left: 0;
width: 4px;
background: var(--a);
content: "";
}
.scenario-card.b::before {
background: var(--b);
}
.card-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
}
.card-heading h2 {
margin: 0;
font-size: 13px;
font-weight: 820;
}
.card-heading p {
margin: 2px 0 0;
color: var(--muted);
font-size: 10px;
}
.model-result {
color: var(--a);
font-size: 12px;
font-weight: 850;
white-space: nowrap;
}
.scenario-card.b .model-result {
color: #bd7411;
}
.control-block {
display: grid;
grid-template-columns: 92px 1fr 54px;
align-items: center;
gap: 9px;
margin-top: 9px;
}
.control-block label {
color: #53675e;
font-size: 10px;
font-weight: 750;
}
.range-value {
padding: 4px 6px;
border-radius: 7px;
background: #eef1eb;
color: var(--ink);
font-size: 10px;
font-weight: 800;
text-align: center;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 999px;
outline: none;
accent-color: var(--a);
cursor: pointer;
}
.scenario-card.b input[type="range"] {
accent-color: var(--b);
}
.bank-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 11px;
}
.bank-row > span {
color: #53675e;
font-size: 10px;
font-weight: 750;
}
.bank-buttons {
display: flex;
padding: 2px;
border: 1px solid var(--line);
border-radius: 9px;
background: #eef0eb;
}
.bank-buttons button {
padding: 5px 8px;
border: 0;
border-radius: 6px;
color: var(--muted);
background: transparent;
cursor: pointer;
font-size: 9px;
font-weight: 800;
}
.bank-buttons button.active {
color: var(--ink);
background: white;
box-shadow: 0 2px 6px rgba(40, 58, 50, 0.12);
}
.rules-card {
color: #43574e;
font-size: 10px;
line-height: 1.45;
}
.rules-card h2 {
margin: 0 0 8px;
color: var(--ink);
font-size: 13px;
}
.formula {
margin: 7px 0;
padding: 8px;
border: 1px solid #dbe2da;
border-radius: 9px;
color: #29473c;
background: #f1f5ee;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
line-height: 1.55;
}
.rule-list {
display: grid;
gap: 3px;
margin: 8px 0 0;
padding-left: 15px;
}
.disclaimer {
margin-top: 8px;
color: #78877f;
font-size: 9px;
font-style: italic;
}
@media (max-width: 900px) {
body {
grid-template-rows: 68px minmax(300px, 1fr) 320px;
}
header {
padding: 0 14px;
}
.load-chip {
display: none;
}
#controls {
grid-template-columns: 1fr 1fr;
}
.rules-card {
grid-column: 1 / -1;
}
.pane-label {
width: calc(50% - 30px);
}
.pane-subtitle {
display: none;
}
}
@media (max-width: 700px) {
body {
grid-template-rows: 64px minmax(340px, 1fr) 380px;
}
header {
gap: 8px;
}
.brand-mark {
flex-basis: 36px;
width: 36px;
height: 36px;
}
h1 {
font-size: 15px;
}
.brand .eyebrow {
display: none;
}
.toolbar {
gap: 4px;
}
.tool-button {
padding: 6px 8px;
font-size: 10px;
}
#split-line {
top: 50%;
right: 0;
bottom: auto;
left: 0;
width: auto;
height: 1px;
}
.pane-label,
.pane-label.b {
top: 12px;
left: 12px;
width: calc(100% - 24px);
}
.pane-label.b {
top: calc(50% + 12px);
}
.pane-label {
padding: 8px 10px;
}
.metric {
padding: 5px 7px;
}
.metric strong {
font-size: 12px;
}
#legend {
display: none;
}
#comparison-badge {
bottom: 10px;
width: max-content;
font-size: 9px;
}
#controls {
grid-template-columns: 1fr;
padding: 10px;
}
.rules-card {
grid-column: auto;
}
}
</style>
</head>
<body>
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<svg viewBox="0 0 32 32" fill="none">
<path d="M5 21c5-6 8-5 12-9 3-3 5-6 10-6" stroke="#9de2d5" stroke-width="3" stroke-linecap="round"/>
<path d="M4 26c6-5 10-3 14-7 3-3 5-7 10-7" stroke="#f1bd5d" stroke-width="3" stroke-linecap="round"/>
<circle cx="8" cy="8" r="3" fill="#f5f3e7"/>
</svg>
</div>
<div class="brand-copy">
<p class="eyebrow">Synthetic landscape comparison</p>
<h1>Riparian Buffer Lab</h1>
</div>
</div>
<div class="header-meta">
<div class="load-chip">420 t/yr incoming sediment</div>
<div class="toolbar">
<button class="tool-button" id="trees-toggle" aria-pressed="true">Trees on</button>
<button class="tool-button" id="top-view">Top view</button>
<button class="tool-button" id="reset-view">Reset</button>
</div>
</div>
</header>
<main id="stage">
<div id="split-line"></div>
<section class="pane-label a" aria-label="Scenario A results">
<div class="pane-heading">
<span class="scenario-letter">A</span>
<span class="pane-title">Reference</span>
<span class="pane-subtitle" id="summary-a"></span>
</div>
<div class="metric-row">
<div class="metric"><strong id="ret-a">—</strong><span>Retention</span></div>
<div class="metric"><strong id="captured-a">—</strong><span>Captured t/yr</span></div>
<div class="metric"><strong id="area-a">—</strong><span>Area m²</span></div>
</div>
</section>
<section class="pane-label b" aria-label="Scenario B results">
<div class="pane-heading">
<span class="scenario-letter b">B</span>
<span class="pane-title">Alternative</span>
<span class="pane-subtitle" id="summary-b"></span>
</div>
<div class="metric-row">
<div class="metric"><strong id="ret-b">—</strong><span>Retention</span></div>
<div class="metric"><strong id="captured-b">—</strong><span>Captured t/yr</span></div>
<div class="metric"><strong id="area-b">—</strong><span>Area m²</span></div>
</div>
</section>
<div id="legend">
<span class="legend-item"><i class="swatch a"></i>Scenario A</span>
<span class="legend-item"><i class="swatch b"></i>Scenario B</span>
<span class="legend-item"><i class="swatch water"></i>Channel</span>
</div>
<div id="comparison-badge" aria-live="polite"></div>
</main>
<section id="controls" aria-label="Scenario controls">
<article class="control-card scenario-card">
<div class="card-heading">
<div>
<h2>Scenario A · Reference</h2>
<p>Bank-side, continuous buffer</p>
</div>
<span class="model-result" id="result-a"></span>
</div>
<div class="control-block">
<label for="width-a">Buffer width</label>
<input id="width-a" type="range" min="4" max="28" step="1" value="10">
<output class="range-value" id="width-a-out">10 m</output>
</div>
<div class="control-block">
<label for="setback-a">River setback</label>
<input id="setback-a" type="range" min="0" max="8" step="1" value="0">
<output class="range-value" id="setback-a-out">0 m</output>
</div>
<div class="bank-row">
<span>Placement</span>
<div class="bank-buttons" aria-label="Scenario A placement">
<button data-scenario="a" data-bank="both" class="active">Both</button>
<button data-scenario="a" data-bank="north">North</button>
<button data-scenario="a" data-bank="south">South</button>
</div>
</div>
</article>
<article class="control-card scenario-card b">
<div class="card-heading">
<div>
<h2>Scenario B · Alternative</h2>
<p>Compare width, bank side, and setback</p>
</div>
<span class="model-result" id="result-b"></span>
</div>
<div class="control-block">
<label for="width-b">Buffer width</label>
<input id="width-b" type="range" min="4" max="28" step="1" value="24">
<output class="range-value" id="width-b-out">24 m</output>
</div>
<div class="control-block">
<label for="setback-b">River setback</label>
<input id="setback-b" type="range" min="0" max="8" step="1" value="4">
<output class="range-value" id="setback-b-out">4 m</output>
</div>
<div class="bank-row">
<span>Placement</span>
<div class="bank-buttons" aria-label="Scenario B placement">
<button data-scenario="b" data-bank="both" class="active">Both</button>
<button data-scenario="b" data-bank="north">North</button>
<button data-scenario="b" data-bank="south">South</button>
</div>
</div>
</article>
<aside class="control-card rules-card">
<h2>Synthetic retention rules</h2>
<div class="formula">
Retention = 82% × [1 − e<sup>−w/12</sup>]<br>
× bank factor × setback factor
</div>
<ul class="rule-list">
<li><strong>Both banks:</strong> factor 1.00</li>
<li><strong>One bank:</strong> factor 0.66</li>
<li><strong>Setback:</strong> −2.5% per metre, capped at 30%</li>
<li><strong>Captured load:</strong> incoming sediment × retention</li>
</ul>
<p class="disclaimer">
Illustrative rules only; not calibrated to a real watershed.
</p>
</aside>
</section>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and state
// -------------------------------------------------------------------------
const COLORS = {
a: 0x10a99a,
b: 0xe79a25,
water: 0x3c93b4,
terrain: 0x7f9b69,
terrainLight: 0xa7b77c,
bank: 0xc6aa78
};
const TERRAIN_WIDTH = 84;
const TERRAIN_DEPTH = 92;
const RIVER_HALF_WIDTH = 2.6;
const RIVER_LENGTH = 82;
const SEDIMENT_LOAD = 420;
const configs = {
a: { width: 10, setback: 0, bank: "both" },
b: { width: 24, setback: 4, bank: "both" }
};
const stage = document.querySelector("#stage");
const mobileQuery = window.matchMedia("(max-width: 700px)");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Interactive 3D comparison. Drag to orbit, shift-drag to pan, and scroll to zoom."
);
stage.prepend(renderer.domElement);
const camera = new THREE.PerspectiveCamera(40, 1, 0.1, 400);
const cameraState = {
theta: -0.52,
phi: 1.05,
radius: 108,
target: new THREE.Vector3(0, 0, 0)
};
const spherical = new THREE.Spherical();
// -------------------------------------------------------------------------
// Deterministic terrain functions
// -------------------------------------------------------------------------
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function smoothstep(edge0, edge1, value) {
const t = clamp((value - edge0) / (edge1 - edge0), 0, 1);
return t * t * (3 - 2 * t);
}
function hash2(x, z) {
const value = Math.sin(x * 127.1 + z * 311.7) * 43758.5453123;
return value - Math.floor(value);
}
function valueNoise(x, z) {
const ix = Math.floor(x);
const iz = Math.floor(z);
const fx = x - ix;
const fz = z - iz;
const ux = fx * fx * (3 - 2 * fx);
const uz = fz * fz * (3 - 2 * fz);
const a = hash2(ix, iz);
const b = hash2(ix + 1, iz);
const c = hash2(ix, iz + 1);
const d = hash2(ix + 1, iz + 1);
return THREE.MathUtils.lerp(
THREE.MathUtils.lerp(a, b, ux),
THREE.MathUtils.lerp(c, d, ux),
uz
);
}
function riverZ(x) {
return (
3.4 * Math.sin(x * 0.085) +
1.3 * Math.sin(x * 0.19 + 0.7)
);
}
function terrainHeight(x, z) {
const distance = Math.abs(z - riverZ(x));
const noise =
valueNoise(x * 0.085, z * 0.085) * 0.72 +
valueNoise(x * 0.23, z * 0.23) * 0.28;
if (distance < RIVER_HALF_WIDTH) {
return -0.24 + distance * 0.075;
}
const bankRise = smoothstep(RIVER_HALF_WIDTH, 11, distance);
return (
-0.032 +
bankRise * (0.52 + noise * 1.25 + 0.0009 * x * x)
);
}
function mulberry32(seed) {
return function random() {
let t = (seed += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
// -------------------------------------------------------------------------
// Geometry builders
// -------------------------------------------------------------------------
function createTerrain() {
const positions = [];
const colors = [];
const subdivisionsX = 42;
const subdivisionsZ = 42;
const cellX = TERRAIN_WIDTH / subdivisionsX;
const cellZ = TERRAIN_DEPTH / subdivisionsZ;
const colorA = new THREE.Color(COLORS.terrain);
const colorB = new THREE.Color(COLORS.terrainLight);
const bankColor = new THREE.Color(COLORS.bank);
function pushTriangle(a, b, c) {
positions.push(
a.x, terrainHeight(a.x, a.z), a.z,
b.x, terrainHeight(b.x, b.z), b.z,
c.x, terrainHeight(c.x, c.z), c.z
);
const mx = (a.x + b.x + c.x) / 3;
const mz = (a.z + b.z + c.z) / 3;
const distance = Math.abs(mz - riverZ(mx));
const noise = hash2(Math.floor(mx), Math.floor(mz));
const color = colorA.clone().lerp(colorB, noise * 0.66);
if (distance < 3.4) {
color.lerp(bankColor, 0.7);
}
for (let i = 0; i < 3; i++) {
colors.push(color.r, color.g, color.b);
}
}
for (let iz = 0; iz < subdivisionsZ; iz++) {
for (let ix = 0; ix < subdivisionsX; ix++) {
const x0 = -TERRAIN_WIDTH / 2 + ix * cellX;
const x1 = x0 + cellX;
const z0 = -TERRAIN_DEPTH / 2 + iz * cellZ;
const z1 = z0 + cellZ;
const p00 = { x: x0, z: z0 };
const p10 = { x: x1, z: z0 };
const p01 = { x: x0, z: z1 };
const p11 = { x: x1, z: z1 };
pushTriangle(p00, p11, p10);
pushTriangle(p00, p01, p11);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3)
);
geometry.computeVertexNormals();
const material = new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.96,
metalness: 0,
flatShading: true
});
const mesh = new THREE.Mesh(geometry, material);
mesh.receiveShadow = true;
return mesh;
}
function createTerrainSkirt() {
const positions = [];
const segments = 42;
function addSide(a, b) {
const ay = terrainHeight(a.x, a.z);
const by = terrainHeight(b.x, b.z);
const bottomA = { x: a.x, y: -0.46, z: a.z };
const bottomB = { x: b.x, y: -0.46, z: b.z };
positions.push(
a.x, ay, a.z,
b.x, by, b.z,
bottomA.x, bottomA.y, bottomA.z,
b.x, by, b.z,
bottomB.x, bottomB.y, bottomB.z,
bottomA.x, bottomA.y, bottomA.z
);
}
for (let i = 0; i < segments; i++) {
const x0 = -TERRAIN_WIDTH / 2 + (i / segments) * TERRAIN_WIDTH;
const x1 = -TERRAIN_WIDTH / 2 + ((i + 1) / segments) * TERRAIN_WIDTH;
addSide(
{ x: x0, z: -TERRAIN_DEPTH / 2 },
{ x: x1, z: -TERRAIN_DEPTH / 2 }
);
addSide(
{ x: x1, z: TERRAIN_DEPTH / 2 },
{ x: x0, z: TERRAIN_DEPTH / 2 }
);
}
for (let i = 0; i < segments; i++) {
const z0 = -TERRAIN_DEPTH / 2 + (i / segments) * TERRAIN_DEPTH;
const z1 = -TERRAIN_DEPTH / 2 + ((i + 1) / segments) * TERRAIN_DEPTH;
addSide(
{ x: -TERRAIN_WIDTH / 2, z: z1 },
{ x: -TERRAIN_WIDTH / 2, z: z0 }
);
addSide(
{ x: TERRAIN_WIDTH / 2, z: z0 },
{ x: TERRAIN_WIDTH / 2, z: z1 }
);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.computeVertexNormals();
return new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color: 0x80664b,
roughness: 1,
side: THREE.DoubleSide,
flatShading: true
})
);
}
function createBase() {
const geometry = new THREE.BoxGeometry(
TERRAIN_WIDTH + 0.5,
2.4,
TERRAIN_DEPTH + 0.5
);
const material = new THREE.MeshStandardMaterial({
color: 0x765f48,
roughness: 1
});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.y = -1.66;
mesh.receiveShadow = true;
return mesh;
}
function createRiver() {
const positions = [];
const samples = 84;
for (let i = 0; i < samples; i++) {
const x0 = -TERRAIN_WIDTH / 2 + (i / samples) * TERRAIN_WIDTH;
const x1 = -TERRAIN_WIDTH / 2 + ((i + 1) / samples) * TERRAIN_WIDTH;
const z00 = riverZ(x0) - RIVER_HALF_WIDTH;
const z01 = riverZ(x0) + RIVER_HALF_WIDTH;
const z10 = riverZ(x1) - RIVER_HALF_WIDTH;
const z11 = riverZ(x1) + RIVER_HALF_WIDTH;
positions.push(
x0, 0.015, z00,
x1, 0.015, z11,
x1, 0.015, z10,
x0, 0.015, z00,
x0, 0.015, z01,
x1, 0.015, z11
);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.computeVertexNormals();
const material = new THREE.MeshStandardMaterial({
color: COLORS.water,
roughness: 0.24,
metalness: 0.08,
transparent: true,
opacity: 0.88,
side: THREE.DoubleSide
});
const mesh = new THREE.Mesh(geometry, material);
mesh.receiveShadow = true;
return mesh;
}
function createSurfaceRibbon(side, startOffset, ribbonWidth, lift = 0.065) {
const positions = [];
const samples = 76;
for (let i = 0; i < samples; i++) {
const x0 = -TERRAIN_WIDTH / 2 + (i / samples) * TERRAIN_WIDTH;
const x1 = -TERRAIN_WIDTH / 2 + ((i + 1) / samples) * TERRAIN_WIDTH;
const inner0 = riverZ(x0) + side * startOffset;
const outer0 = inner0 + side * ribbonWidth;
const inner1 = riverZ(x1) + side * startOffset;
const outer1 = inner1 + side * ribbonWidth;
const a = {
x: x0,
y: terrainHeight(x0, inner0) + lift,
z: inner0
};
const b = {
x: x0,
y: terrainHeight(x0, outer0) + lift,
z: outer0
};
const c = {
x: x1,
y: terrainHeight(x1, inner1) + lift,
z: inner1
};
const d = {
x: x1,
y: terrainHeight(x1, outer1) + lift,
z: outer1
};
if (side > 0) {
positions.push(
a.x, a.y, a.z,
b.x, b.y, b.z,
c.x, c.y, c.z,
a.x, a.y, a.z,
c.x, c.y, c.z,
d.x, d.y, d.z
);
} else {
positions.push(
a.x, a.y, a.z,
c.x, c.y, c.z,
b.x, b.y, b.z,
a.x, a.y, a.z,
d.x, d.y, d.z,
c.x, c.y, c.z
);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.computeVertexNormals();
return geometry;
}
function createBankStrip(side) {
const material = new THREE.MeshStandardMaterial({
color: COLORS.bank,
roughness: 1,
side: THREE.DoubleSide
});
const mesh = new THREE.Mesh(
createSurfaceRibbon(side, 2.55, 1.75, 0.038),
material
);
mesh.receiveShadow = true;
return mesh;
}
function createOutline(side, startOffset, ribbonWidth, color) {
const points = [];
const samples = 76;
for (let i = 0; i <= samples; i++) {
const x = -TERRAIN_WIDTH / 2 + (i / samples) * TERRAIN_WIDTH;
const inner = riverZ(x) + side * startOffset;
const outer = inner + side * ribbonWidth;
points.push(
new THREE.Vector3(
x,
terrainHeight(x, inner) + 0.12,
inner
),
new THREE.Vector3(
x,
terrainHeight(x, outer) + 0.12,
outer
)
);
}
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.82
});
return new THREE.Line(geometry, material);
}
function createTrees(positions, canopyColor, seedOffset = 0) {
const group = new THREE.Group();
if (!positions.length) {
return group;
}
const random = mulberry32(9000 + seedOffset);
const trunkGeometry = new THREE.CylinderGeometry(0.08, 0.13, 1.05, 5);
const canopyGeometry = new THREE.ConeGeometry(0.66, 1.85, 5);
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x735139,
roughness: 1,
flatShading: true
});
const canopyMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.9,
flatShading: true
});
const trunks = new THREE.InstancedMesh(
trunkGeometry,
trunkMaterial,
positions.length
);
const canopies = new THREE.InstancedMesh(
canopyGeometry,
canopyMaterial,
positions.length
);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
positions.forEach((position, index) => {
const scale = position.scale ?? 0.8 + random() * 0.55;
dummy.position.set(
position.x,
position.y + 0.52 * scale,
position.z
);
dummy.rotation.set(0, random() * Math.PI, 0);
dummy.scale.set(scale, scale, scale);
dummy.updateMatrix();
trunks.setMatrixAt(index, dummy.matrix);
dummy.position.set(
position.x,
position.y + 1.46 * scale,
position.z
);
dummy.rotation.set(0, random() * Math.PI, 0);
dummy.scale.set(scale, scale, scale);
dummy.updateMatrix();
canopies.setMatrixAt(index, dummy.matrix);
color.set(canopyColor);
color.offsetHSL(
(random() - 0.5) * 0.035,
(random() - 0.5) * 0.08,
(random() - 0.5) * 0.08
);
canopies.setColorAt(index, color);
});
trunks.instanceMatrix.needsUpdate = true;
canopies.instanceMatrix.needsUpdate = true;
if (canopies.instanceColor) {
canopies.instanceColor.needsUpdate = true;
}
trunks.castShadow = true;
canopies.castShadow = true;
group.add(trunks, canopies);
return group;
}
function createContextTrees() {
const random = mulberry32(417);
const positions = [];
while (positions.length < 115) {
const x = (random() - 0.5) * (TERRAIN_WIDTH - 3);
const z = (random() - 0.5) * (TERRAIN_DEPTH - 3);
const distance = Math.abs(z - riverZ(x));
if (distance < 17) {
continue;
}
positions.push({
x,
y: terrainHeight(x, z),
z,
scale: 0.55 + random() * 0.45
});
}
return createTrees(positions, 0x557653, 10);
}
function disposeGroup(group) {
group.traverse((object) => {
if (object.geometry) {
object.geometry.dispose();
}
if (object.material) {
const materials = Array.isArray(object.material)
? object.material
: [object.material];
materials.forEach((material) => material.dispose());
}
});
}
// -------------------------------------------------------------------------
// Scene setup
// -------------------------------------------------------------------------
function makeScene() {
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdbe4df);
scene.fog = new THREE.Fog(0xdbe4df, 98, 185);
const staticGroup = new THREE.Group();
const contextGroup = createContextTrees();
const bufferGroup = new THREE.Group();
const vegetationGroup = new THREE.Group();
staticGroup.add(
createBase(),
createTerrainSkirt(),
createTerrain(),
createBankStrip(1),
createBankStrip(-1),
createRiver()
);
scene.add(staticGroup, contextGroup, bufferGroup, vegetationGroup);
const hemisphere = new THREE.HemisphereLight(
0xf5fff8,
0x65735d,
2.15
);
const sun = new THREE.DirectionalLight(0xfff1d3, 3.15);
sun.position.set(-34, 58, 31);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -58;
sun.shadow.camera.right = 58;
sun.shadow.camera.top = 58;
sun.shadow.camera.bottom = -58;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 145;
sun.shadow.bias = -0.00045;
scene.add(hemisphere, sun);
return {
scene,
staticGroup,
contextGroup,
bufferGroup,
vegetationGroup
};
}
const viewA = makeScene();
const viewB = makeScene();
function sidesFor(config) {
if (config.bank === "north") return [1];
if (config.bank === "south") return [-1];
return [1, -1];
}
function updateBuffer(view, config, color, seed) {
disposeGroup(view.bufferGroup);
disposeGroup(view.vegetationGroup);
view.bufferGroup = new THREE.Group();
view.vegetationGroup = new THREE.Group();
const sides = sidesFor(config);
const startOffset = RIVER_HALF_WIDTH + config.setback;
const random = mulberry32(seed);
const bufferMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.88,
metalness: 0,
transparent: true,
opacity: 0.7,
depthWrite: false,
side: THREE.DoubleSide,
polygonOffset: true,
polygonOffsetFactor: -1,
polygonOffsetUnits: -1
});
for (const side of sides) {
const ribbon = new THREE.Mesh(
createSurfaceRibbon(side, startOffset, config.width, 0.085),
bufferMaterial
);
ribbon.receiveShadow = true;
view.bufferGroup.add(ribbon);
view.bufferGroup.add(
createOutline(side, startOffset, config.width, color)
);
}
const treePositions = [];
const desiredTrees = Math.round(config.width * sides.length * 3.2);
let attempts = 0;
while (treePositions.length < desiredTrees && attempts < desiredTrees * 12) {
attempts++;
const side = sides[Math.floor(random() * sides.length)];
const x = (random() - 0.5) * (TERRAIN_WIDTH - 3);
const inner = riverZ(x) + side * startOffset;
const outer = inner + side * config.width;
const z = THREE.MathUtils.lerp(inner, outer, random());
treePositions.push({
x,
y: terrainHeight(x, z),
z,
scale: 0.72 + random() * 0.48
});
}
const treeColor = color === COLORS.a ? 0x287f61 : 0x8a642b;
view.vegetationGroup.add(
createTrees(treePositions, treeColor, seed + 30)
);
view.scene.add(view.bufferGroup, view.vegetationGroup);
}
// -------------------------------------------------------------------------
// Synthetic model and interface
// -------------------------------------------------------------------------
function calculateMetrics(config) {
const widthFactor = 1 - Math.exp(-config.width / 12);
const bankFactor = config.bank === "both" ? 1 : 0.66;
const setbackFactor = 1 - Math.min(0.3, config.setback * 0.025);
const retention = 0.82 * widthFactor * bankFactor * setbackFactor;
return {
retention,
retentionPercent: retention * 100,
captured: SEDIMENT_LOAD * retention,
area: config.width * RIVER_LENGTH * sidesFor(config).length
};
}
function bankLabel(bank) {
if (bank === "north") return "north bank";
if (bank === "south") return "south bank";
return "both banks";
}
function updateSummary(key) {
const config = configs[key];
const metrics = calculateMetrics(config);
document.querySelector(`#width-${key}-out`).textContent =
`${config.width} m`;
document.querySelector(`#setback-${key}-out`).textContent =
`${config.setback} m`;
document.querySelector(`#ret-${key}`).textContent =
`${metrics.retentionPercent.toFixed(1)}%`;
document.querySelector(`#captured-${key}`).textContent =
metrics.captured.toFixed(1);
document.querySelector(`#area-${key}`).textContent =
Math.round(metrics.area).toLocaleString();
document.querySelector(`#summary-${key}`).textContent =
`${config.width} m · ${bankLabel(config.bank)}`;
document.querySelector(`#result-${key}`).textContent =
`${metrics.captured.toFixed(1)} t/yr captured`;
document
.querySelectorAll(`.bank-buttons button[data-scenario="${key}"]`)
.forEach((button) => {
button.classList.toggle("active", button.dataset.bank === config.bank);
button.setAttribute(
"aria-pressed",
String(button.dataset.bank === config.bank)
);
});
}
function updateComparison() {
const a = calculateMetrics(configs.a);
const b = calculateMetrics(configs.b);
const difference = b.captured - a.captured;
const badge = document.querySelector("#comparison-badge");
if (Math.abs(difference) < 0.05) {
badge.textContent = "Both scenarios have the same modeled sediment capture";
return;
}
const winner = difference > 0 ? "B" : "A";
const magnitude = Math.abs(difference);
const relative =
a.captured > 0 ? (magnitude / a.captured) * 100 : 0;
badge.textContent =
`Scenario ${winner} captures ${magnitude.toFixed(1)} t/yr more ` +
`(${relative.toFixed(0)}% versus A) · B area Δ ` +
`${Math.round(b.area - a.area).toLocaleString()} m²`;
}
function refreshInterface() {
updateSummary("a");
updateSummary("b");
updateComparison();
}
function changeScenario(key, property, value) {
configs[key][property] = value;
if (key === "a") {
updateBuffer(viewA, configs.a, COLORS.a, 100);
} else {
updateBuffer(viewB, configs.b, COLORS.b, 200);
}
refreshInterface();
}
document.querySelectorAll('input[type="range"]').forEach((input) => {
input.addEventListener("input", () => {
const key = input.id.startsWith("width-a")
? "a"
: input.id.startsWith("width-b")
? "b"
: input.id.startsWith("setback-a")
? "a"
: "b";
const property = input.id.startsWith("width") ? "width" : "setback";
changeScenario(key, property, Number(input.value));
});
});
document.querySelectorAll(".bank-buttons button").forEach((button) => {
button.addEventListener("click", () => {
changeScenario(
button.dataset.scenario,
"bank",
button.dataset.bank
);
});
});
// -------------------------------------------------------------------------
// Direct camera controls: orbit, pan, zoom, keyboard
// -------------------------------------------------------------------------
function updateCamera() {
cameraState.phi = clamp(cameraState.phi, 0.06, 1.48);
cameraState.radius = clamp(cameraState.radius, 34, 165);
spherical.set(
cameraState.radius,
cameraState.phi,
cameraState.theta
);
camera.position
.setFromSpherical(spherical)
.add(cameraState.target);
camera.lookAt(cameraState.target);
}
const pointer = {
active: false,
mode: "rotate",
x: 0,
y: 0
};
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
pointer.active = true;
pointer.mode = event.button === 2 || event.shiftKey ? "pan" : "rotate";
pointer.x = event.clientX;
pointer.y = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
event.preventDefault();
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointer.active) return;
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
pointer.x = event.clientX;
pointer.y = event.clientY;
if (pointer.mode === "rotate") {
cameraState.theta -= dx * 0.005;
cameraState.phi -= dy * 0.005;
} else {
const scale = cameraState.radius * 0.0013;
cameraState.target.x -=
dx * scale * Math.cos(cameraState.theta);
cameraState.target.z +=
dx * scale * Math.sin(cameraState.theta);
cameraState.target.z -= dy * scale * 0.72;
cameraState.target.x -=
dy * scale * 0.34 * Math.sin(cameraState.theta);
}
updateCamera();
});
function releasePointer(event) {
pointer.active = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius *= Math.exp(event.deltaY * 0.001);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("keydown", (event) => {
const handled = ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "+", "-", "="];
if (!handled.includes(event.key)) return;
event.preventDefault();
if (event.key === "ArrowLeft") cameraState.theta -= 0.08;
if (event.key === "ArrowRight") cameraState.theta += 0.08;
if (event.key === "ArrowUp") cameraState.phi -= 0.06;
if (event.key === "ArrowDown") cameraState.phi += 0.06;
if (event.key === "+" || event.key === "=") cameraState.radius *= 0.9;
if (event.key === "-") cameraState.radius *= 1.1;
updateCamera();
});
function resetCamera() {
cameraState.theta = -0.52;
cameraState.phi = 1.05;
cameraState.radius = 108;
cameraState.target.set(0, 0, 0);
updateCamera();
}
document.querySelector("#reset-view").addEventListener("click", resetCamera);
document.querySelector("#top-view").addEventListener("click", () => {
cameraState.theta = 0;
cameraState.phi = 0.07;
cameraState.radius = 112;
cameraState.target.set(0, 0, 0);
updateCamera();
});
const treesToggle = document.querySelector("#trees-toggle");
treesToggle.addEventListener("click", () => {
const visible = treesToggle.getAttribute("aria-pressed") !== "true";
treesToggle.setAttribute("aria-pressed", String(visible));
treesToggle.textContent = visible ? "Trees on" : "Trees off";
for (const view of [viewA, viewB]) {
view.vegetationGroup.visible = visible;
view.contextGroup.visible = visible;
}
});
// -------------------------------------------------------------------------
// Split rendering and resize
// -------------------------------------------------------------------------
let stageWidth = 1;
let stageHeight = 1;
function resize() {
stageWidth = Math.max(1, stage.clientWidth);
stageHeight = Math.max(1, stage.clientHeight);
renderer.setSize(stageWidth, stageHeight, false);
const paneWidth = mobileQuery.matches
? stageWidth
: Math.floor(stageWidth / 2);
const paneHeight = mobileQuery.matches
? Math.floor(stageHeight / 2)
: stageHeight;
camera.aspect = paneWidth / paneHeight;
camera.updateProjectionMatrix();
updateCamera();
}
function render() {
renderer.setScissorTest(true);
if (mobileQuery.matches) {
const half = Math.floor(stageHeight / 2);
renderer.setViewport(0, half, stageWidth, stageHeight - half);
renderer.setScissor(0, half, stageWidth, stageHeight - half);
renderer.render(viewA.scene, camera);
renderer.setViewport(0, 0, stageWidth, half);
renderer.setScissor(0, 0, stageWidth, half);
renderer.render(viewB.scene, camera);
} else {
const half = Math.floor(stageWidth / 2);
renderer.setViewport(0, 0, half, stageHeight);
renderer.setScissor(0, 0, half, stageHeight);
renderer.render(viewA.scene, camera);
renderer.setViewport(half, 0, stageWidth - half, stageHeight);
renderer.setScissor(half, 0, stageWidth - half, stageHeight);
renderer.render(viewB.scene, camera);
}
renderer.setScissorTest(false);
requestAnimationFrame(render);
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(stage);
mobileQuery.addEventListener("change", resize);
// Initial state
updateBuffer(viewA, configs.a, COLORS.a, 100);
updateBuffer(viewB, configs.b, COLORS.b, 200);
refreshInterface();
resize();
render();
</script>
</body>
</html>
```