Prompt specification
Build or customize the Three.js 3D scene "Remove-and-restore barrier 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: Remove-and-restore barrier experiment
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/remove-and-restore-barrier-experiment-x0652
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring beaver dams and wetlands. Create a classroom watershed model with a removable dam section; users compare water extent and exposed ground under explicit simplified flow rules without claiming ecological predictions. Low-poly.
Working Three.js Starter (remove-and-restore-barrier-experiment-x0652):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Watershed Lab — Beaver Dam Classroom Model</title>
<style>
:root {
--ink: #17342e;
--muted: #59716a;
--panel: rgba(250, 252, 247, 0.94);
--line: rgba(28, 70, 60, 0.14);
--green: #267a5e;
--green-dark: #195641;
--teal: #168c9b;
--blue: #287fbd;
--amber: #cf7b37;
--shadow: 0 18px 48px rgba(24, 55, 47, 0.17);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dce9e5;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
.topbar {
position: fixed;
z-index: 5;
top: 20px;
left: 24px;
right: 24px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
}
.brand-mark {
width: 43px;
height: 43px;
display: grid;
place-items: center;
border-radius: 13px;
color: white;
background: var(--green-dark);
box-shadow: var(--shadow);
font-size: 24px;
}
.brand h1 {
margin: 0;
font-size: clamp(19px, 2vw, 27px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 12px;
font-weight: 650;
letter-spacing: 0.075em;
text-transform: uppercase;
}
.warning {
border: 1px solid rgba(157, 96, 39, 0.2);
border-radius: 999px;
padding: 9px 13px;
background: rgba(255, 247, 231, 0.9);
color: #84531f;
box-shadow: 0 8px 25px rgba(69, 68, 45, 0.09);
font-size: 12px;
font-weight: 750;
white-space: nowrap;
}
.panel {
position: fixed;
z-index: 6;
top: 86px;
left: 24px;
width: 342px;
max-height: calc(100vh - 110px);
overflow: auto;
padding: 17px;
border: 1px solid rgba(255, 255, 255, 0.76);
border-radius: 20px;
background: var(--panel);
backdrop-filter: blur(18px) saturate(1.15);
box-shadow: var(--shadow);
scrollbar-width: thin;
}
.section {
padding-bottom: 15px;
margin-bottom: 15px;
border-bottom: 1px solid var(--line);
}
.section:last-child {
padding-bottom: 0;
margin-bottom: 0;
border-bottom: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 0 0 10px;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.075em;
text-transform: uppercase;
color: #365b51;
}
.scenario {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
padding: 5px;
border-radius: 13px;
background: #e8eee9;
}
.scenario button {
min-height: 44px;
border: 0;
border-radius: 10px;
color: #476159;
background: transparent;
cursor: pointer;
font-size: 13px;
font-weight: 750;
transition: 160ms ease;
}
.scenario button:hover {
background: rgba(255, 255, 255, 0.55);
}
.scenario button.active {
color: white;
background: var(--green);
box-shadow: 0 5px 13px rgba(32, 102, 80, 0.2);
}
.dam-toggle {
width: 100%;
min-height: 43px;
margin-top: 9px;
border: 1px solid rgba(207, 123, 55, 0.32);
border-radius: 11px;
color: #88501f;
background: #fff4e6;
cursor: pointer;
font-weight: 750;
}
.dam-toggle:hover {
background: #ffebd5;
}
.scenario-note {
min-height: 34px;
margin: 9px 2px 0;
color: var(--muted);
font-size: 12px;
line-height: 1.4;
}
.rain-value {
color: var(--teal);
font-size: 16px;
font-weight: 850;
letter-spacing: -0.02em;
text-transform: none;
}
input[type="range"] {
width: 100%;
margin: 3px 0 0;
accent-color: var(--teal);
cursor: pointer;
}
.range-ends {
display: flex;
justify-content: space-between;
margin-top: 3px;
color: #71837d;
font-size: 10px;
font-weight: 650;
}
.compare-table {
width: 100%;
border-collapse: collapse;
font-size: 12px;
}
.compare-table th {
padding: 6px 4px 9px;
color: #688078;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.04em;
text-align: right;
text-transform: uppercase;
}
.compare-table th:first-child {
text-align: left;
}
.compare-table td {
padding: 9px 4px;
border-top: 1px solid var(--line);
text-align: right;
font-variant-numeric: tabular-nums;
}
.compare-table td:first-child {
text-align: left;
color: #49635b;
font-weight: 650;
}
.compare-table td strong {
color: var(--ink);
}
.delta-card {
margin-top: 10px;
padding: 11px 12px;
border-radius: 12px;
color: #315248;
background: #e9f2eb;
font-size: 12px;
line-height: 1.45;
}
.delta-card strong {
color: var(--green-dark);
}
.check-row {
display: flex;
align-items: center;
gap: 8px;
margin-top: 10px;
color: #49635b;
font-size: 12px;
font-weight: 650;
cursor: pointer;
}
.check-row input {
accent-color: var(--teal);
}
details {
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.54);
}
summary {
padding: 11px 12px;
cursor: pointer;
color: #35584e;
font-size: 12px;
font-weight: 800;
}
.rules {
margin: 0;
padding: 0 14px 13px 29px;
color: #526a62;
font-size: 11.5px;
line-height: 1.5;
}
.rules li {
margin: 6px 0;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.button-row button {
min-height: 38px;
border: 1px solid var(--line);
border-radius: 10px;
color: #3d5e54;
background: rgba(255, 255, 255, 0.68);
cursor: pointer;
font-size: 12px;
font-weight: 750;
}
.button-row button:hover {
background: white;
}
#labels {
position: fixed;
z-index: 4;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.scene-label {
position: absolute;
left: 0;
top: 0;
padding: 6px 9px;
border: 1px solid rgba(255, 255, 255, 0.75);
border-radius: 8px;
color: #274b42;
background: rgba(250, 253, 247, 0.84);
box-shadow: 0 6px 18px rgba(31, 66, 56, 0.12);
backdrop-filter: blur(8px);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.02em;
white-space: nowrap;
transform: translate(-50%, -50%);
transition: opacity 120ms ease;
}
.scene-label::after {
content: "";
position: absolute;
left: 50%;
top: 100%;
width: 1px;
height: 17px;
background: rgba(35, 73, 62, 0.42);
}
.bottom-bar {
position: fixed;
z-index: 5;
right: 24px;
bottom: 20px;
display: flex;
align-items: center;
gap: 13px;
padding: 10px 13px;
border: 1px solid rgba(255, 255, 255, 0.74);
border-radius: 13px;
background: rgba(249, 252, 247, 0.88);
box-shadow: var(--shadow);
backdrop-filter: blur(14px);
color: #4d675f;
font-size: 11px;
font-weight: 650;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.swatch {
width: 13px;
height: 13px;
border-radius: 4px;
background: #3bb4c1;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.08);
}
.swatch.ghost {
background: rgba(40, 127, 189, 0.28);
border: 1px solid rgba(40, 127, 189, 0.55);
}
.swatch.exposed {
background: rgba(207, 123, 55, 0.28);
border: 1px solid rgba(207, 123, 55, 0.58);
}
.hint {
padding-left: 12px;
border-left: 1px solid var(--line);
}
@media (max-width: 760px) {
.topbar {
top: 12px;
left: 12px;
right: 12px;
}
.brand p,
.warning {
display: none;
}
.brand-mark {
width: 38px;
height: 38px;
border-radius: 11px;
}
.panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 43vh;
padding: 14px;
border-radius: 17px;
}
.bottom-bar {
display: none;
}
.scene-label {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div id="labels" aria-hidden="true">
<div class="scene-label" id="labelDam">Removable dam section</div>
<div class="scene-label" id="labelUpper">Upper wetland</div>
<div class="scene-label" id="labelLower">Downstream wetland</div>
</div>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">≈</div>
<div>
<h1>Watershed Lab</h1>
<p>Beaver dam & wetland model</p>
</div>
</div>
<div class="warning">Simplified classroom model · not an ecological prediction</div>
</header>
<aside class="panel" aria-label="Watershed model controls">
<section class="section">
<h2 class="section-title">Dam configuration</h2>
<div class="scenario" role="group" aria-label="Dam scenario">
<button id="intactButton" class="active" aria-pressed="true">
Dam intact
</button>
<button id="removedButton" aria-pressed="false">
Section removed
</button>
</div>
<button class="dam-toggle" id="damToggle">
Remove center section
</button>
<p class="scenario-note" id="scenarioNote">
The full dam holds a higher upstream pool.
</p>
</section>
<section class="section">
<h2 class="section-title">
Rainfall event
<span class="rain-value" id="rainValue">0 mm</span>
</h2>
<input
id="rainInput"
type="range"
min="0"
max="30"
step="1"
value="0"
aria-label="Rainfall in millimeters per event"
/>
<div class="range-ends">
<span>0 mm</span>
<span>30 mm</span>
</div>
</section>
<section class="section">
<h2 class="section-title">Model comparison</h2>
<table class="compare-table">
<thead>
<tr>
<th>Metric</th>
<th>Intact</th>
<th>Removed</th>
</tr>
</thead>
<tbody>
<tr>
<td>Upstream water extent</td>
<td><strong id="intactArea">—</strong></td>
<td><strong id="removedArea">—</strong></td>
</tr>
<tr>
<td>Exposed pond-bed ground</td>
<td><strong id="intactExposed">—</strong></td>
<td><strong id="removedExposed">—</strong></td>
</tr>
<tr>
<td>Modeled pool stage</td>
<td><strong id="intactStage">—</strong></td>
<td><strong id="removedStage">—</strong></td>
</tr>
</tbody>
</table>
<div class="delta-card" id="deltaText">
Comparing the two outlet configurations…
</div>
<label class="check-row">
<input id="compareCheck" type="checkbox" checked />
<span id="compareLegend">Blue ghost: former intact-pool footprint</span>
</label>
<div class="delta-card" id="downstreamNote">
The downstream wetland pool is held fixed so that the comparison isolates
the main dam outlet.
</div>
</section>
<section class="section">
<details>
<summary>Explicit simplified rules</summary>
<ol class="rules">
<li>
The study area is the upper basin upstream of the main beaver dam.
One grid cell represents 0.75 m × 0.75 m of model ground.
</li>
<li>
Each rainfall millimeter raises the candidate pool stage by 0.007 m
before it reaches its outlet.
</li>
<li>
The intact outlet is capped at a 0.96 m crest. Removing the center
section lowers the effective outlet to a 0.62 m sill.
</li>
<li>
Starting stages are 0.82 m for the intact pool and 0.58 m for the
opened pool. These are prescribed teaching assumptions.
</li>
<li>
Water occupies only low cells connected to the modeled stream.
Isolated depressions are not counted.
</li>
<li>
Exposed ground means eligible upper-basin pond-bed ground not
covered by water in that scenario.
</li>
<li>
The downstream pool remains fixed. The model omits sediment,
vegetation change, real hydrographs, wildlife behavior, and
ecological outcomes.
</li>
</ol>
</details>
</section>
<section class="section">
<div class="button-row">
<button id="resetView">Reset view</button>
<button id="resetModel">Reset model</button>
</div>
</section>
</aside>
<div class="bottom-bar">
<div class="legend-item">
<span class="swatch"></span>
<span>Modeled water</span>
</div>
<div class="legend-item">
<span class="swatch ghost"></span>
<span>Comparison extent</span>
</div>
<div class="hint">Drag: orbit · Wheel/pinch: zoom · Right-drag: pan</div>
</div>
<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 NX = 72;
const NZ = 54;
const CELL = 0.75;
const CELL_AREA = CELL * CELL;
const WIDTH = NX * CELL;
const DEPTH = NZ * CELL;
const MAIN_DAM_Z = 3.4;
const SECONDARY_DAM_Z = 12.25;
const INTACT_BASE_STAGE = 0.82;
const REMOVED_BASE_STAGE = 0.58;
const INTACT_CREST = 0.96;
const REMOVED_SILL = 0.62;
const RAIN_STAGE_RESPONSE = 0.007;
const DOWNSTREAM_STAGE = 0.38;
let selectedScenario = "intact";
let rainfall = 0;
let showComparison = true;
const sceneHost = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Interactive low-poly watershed model. Drag to orbit and scroll to zoom."
);
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce9e5);
scene.fog = new THREE.Fog(0xdce9e5, 85, 145);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
240
);
const hemi = new THREE.HemisphereLight(0xf2fbff, 0x5b6950, 2.25);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff3d2, 3.1);
sun.position.set(-28, 48, 24);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -45;
sun.shadow.camera.right = 45;
sun.shadow.camera.top = 40;
sun.shadow.camera.bottom = -40;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 120;
sun.shadow.bias = -0.0008;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb8d9e5, 0.8);
fill.position.set(30, 18, -30);
scene.add(fill);
// -------------------------------------------------------------------------
// Procedural terrain
// -------------------------------------------------------------------------
function channelCenter(z) {
return (
1.8 * Math.sin((z + 3) * 0.13) -
0.7 * Math.sin(z * 0.09) +
0.4 * Math.cos(z * 0.2)
);
}
function terrainHeight(x, z) {
const upstreamDistance = 18 - z;
const dx = x - channelCenter(z);
// A rising upstream valley that drains toward the lower foreground.
let h = 0.18 + 0.006 * upstreamDistance + 0.0008 * upstreamDistance ** 2;
// Cross-valley banks.
h += 0.0165 * dx * dx;
// Small, deterministic low-poly surface variation.
h += 0.035 * Math.sin(x * 0.62 + z * 0.31);
h += 0.025 * Math.cos(x * 0.29 - z * 0.48);
// Two broad wetland depressions downstream of the main dam.
h -= 0.12 *
Math.exp(-((z - 8.7) ** 2) / 12 - (dx - 3.8) ** 2 / 8);
h -= 0.09 *
Math.exp(-((z - 15) ** 2) / 10 - (dx + 3.2) ** 2 / 7);
return h;
}
const cornerHeights = [];
for (let j = 0; j <= NZ; j++) {
const row = [];
for (let i = 0; i <= NX; i++) {
row.push(
terrainHeight(-WIDTH / 2 + i * CELL, -DEPTH / 2 + j * CELL)
);
}
cornerHeights.push(row);
}
const cellHeights = new Float32Array(NX * NZ);
const cellX = new Float32Array(NX * NZ);
const cellZ = new Float32Array(NX * NZ);
for (let j = 0; j < NZ; j++) {
for (let i = 0; i < NX; i++) {
const index = j * NX + i;
cellHeights[index] =
(cornerHeights[j][i] +
cornerHeights[j][i + 1] +
cornerHeights[j + 1][i] +
cornerHeights[j + 1][i + 1]) *
0.25;
cellX[index] = -WIDTH / 2 + (i + 0.5) * CELL;
cellZ[index] = -DEPTH / 2 + (j + 0.5) * CELL;
}
}
function colorForTerrain(x, z, h) {
const dx = Math.abs(x - channelCenter(z));
const color = new THREE.Color();
if (z > 6 && h < 0.56) {
color.set("#899b68");
color.offsetHSL(0, 0, Math.sin(x * 0.7 + z * 0.4) * 0.025);
} else if (dx < 1.65) {
color.set("#a69670");
color.offsetHSL(0, 0, Math.sin(z * 1.2) * 0.018);
} else if (z < MAIN_DAM_Z && h < 1.15) {
color.set("#76926b");
} else {
color.set("#66845f");
color.offsetHSL(
0.01,
-0.02,
Math.sin(x * 0.42 + z * 0.29) * 0.045
);
}
return color;
}
const terrainPositions = [];
const terrainColors = [];
for (let j = 0; j < NZ; j++) {
for (let i = 0; i < NX; i++) {
const x0 = -WIDTH / 2 + i * CELL;
const x1 = x0 + CELL;
const z0 = -DEPTH / 2 + j * CELL;
const z1 = z0 + CELL;
const p00 = new THREE.Vector3(x0, cornerHeights[j][i], z0);
const p10 = new THREE.Vector3(x1, cornerHeights[j][i + 1], z0);
const p01 = new THREE.Vector3(x0, cornerHeights[j + 1][i], z1);
const p11 = new THREE.Vector3(x1, cornerHeights[j + 1][i + 1], z1);
const triangles = [
[p00, p01, p11],
[p00, p11, p10]
];
for (const triangle of triangles) {
const averageHeight =
(triangle[0].y + triangle[1].y + triangle[2].y) / 3;
const averageX =
(triangle[0].x + triangle[1].x + triangle[2].x) / 3;
const averageZ =
(triangle[0].z + triangle[1].z + triangle[2].z) / 3;
const color = colorForTerrain(averageX, averageZ, averageHeight);
for (const point of triangle) {
terrainPositions.push(point.x, point.y, point.z);
terrainColors.push(color.r, color.g, color.b);
}
}
}
}
const terrainGeometry = new THREE.BufferGeometry();
terrainGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(terrainPositions, 3)
);
terrainGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(terrainColors, 3)
);
terrainGeometry.computeVertexNormals();
const terrain = new THREE.Mesh(
terrainGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.92,
metalness: 0,
flatShading: true
})
);
terrain.receiveShadow = true;
scene.add(terrain);
// The vertical sides make the landscape read as a classroom diorama.
const skirtPositions = [];
const bottom = -0.14;
function addSkirtEdge(x0, z0, x1, z1, h0, h1) {
skirtPositions.push(
x0, h0, z0,
x0, bottom, z0,
x1, bottom, z1,
x0, h0, z0,
x1, bottom, z1,
x1, h1, z1
);
}
for (let i = 0; i < NX; i++) {
const x0 = -WIDTH / 2 + i * CELL;
const x1 = x0 + CELL;
addSkirtEdge(
x0, -DEPTH / 2, x1, -DEPTH / 2,
cornerHeights[0][i], cornerHeights[0][i + 1]
);
addSkirtEdge(
x1, DEPTH / 2, x0, DEPTH / 2,
cornerHeights[NZ][i + 1], cornerHeights[NZ][i]
);
}
for (let j = 0; j < NZ; j++) {
const z0 = -DEPTH / 2 + j * CELL;
const z1 = z0 + CELL;
addSkirtEdge(
-WIDTH / 2, z1, -WIDTH / 2, z0,
cornerHeights[j + 1][0], cornerHeights[j][0]
);
addSkirtEdge(
WIDTH / 2, z0, WIDTH / 2, z1,
cornerHeights[j][NX], cornerHeights[j + 1][NX]
);
}
const skirtGeometry = new THREE.BufferGeometry();
skirtGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(skirtPositions, 3)
);
skirtGeometry.computeVertexNormals();
const skirt = new THREE.Mesh(
skirtGeometry,
new THREE.MeshStandardMaterial({
color: 0x79664a,
roughness: 1,
side: THREE.DoubleSide
})
);
skirt.receiveShadow = true;
scene.add(skirt);
const base = new THREE.Mesh(
new THREE.BoxGeometry(WIDTH + 1.25, 1.05, DEPTH + 1.25),
new THREE.MeshStandardMaterial({
color: 0x304c45,
roughness: 0.72,
metalness: 0.05
})
);
base.position.y = -0.69;
base.castShadow = true;
base.receiveShadow = true;
scene.add(base);
const shadowFloor = new THREE.Mesh(
new THREE.PlaneGeometry(220, 220),
new THREE.ShadowMaterial({ color: 0x365148, opacity: 0.15 })
);
shadowFloor.rotation.x = -Math.PI / 2;
shadowFloor.position.y = -1.225;
shadowFloor.receiveShadow = true;
scene.add(shadowFloor);
// -------------------------------------------------------------------------
// Beaver dams, lodge, and animals
// -------------------------------------------------------------------------
const logMaterial = new THREE.MeshStandardMaterial({
color: 0x765033,
roughness: 0.96,
flatShading: true
});
const removableLogMaterial = new THREE.MeshStandardMaterial({
color: 0x9a693b,
roughness: 0.93,
flatShading: true
});
const mudMaterial = new THREE.MeshStandardMaterial({
color: 0x65523c,
roughness: 1,
flatShading: true
});
const markerMaterial = new THREE.MeshStandardMaterial({
color: 0xde873e,
roughness: 0.72,
flatShading: true
});
function cylinderBetween(a, b, radius, material, radialSegments = 6) {
const direction = new THREE.Vector3().subVectors(b, a);
const length = direction.length();
const geometry = new THREE.CylinderGeometry(
radius,
radius * 1.05,
length,
radialSegments,
1,
false
);
const mesh = new THREE.Mesh(geometry, material);
mesh.position.copy(a).add(b).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function addLog(group, x1, x2, z, y, radius, material = logMaterial) {
group.add(
cylinderBetween(
new THREE.Vector3(x1, y, z),
new THREE.Vector3(x2, y + 0.035, z + 0.08),
radius,
material,
7
)
);
}
const mainDamGroup = new THREE.Group();
const centralDamGroup = new THREE.Group();
scene.add(mainDamGroup, centralDamGroup);
const mainCenterX = channelCenter(MAIN_DAM_Z);
const mainMud = new THREE.Mesh(
new THREE.BoxGeometry(11.4, 0.23, 0.9),
mudMaterial
);
mainMud.position.set(mainCenterX, 0.48, MAIN_DAM_Z);
mainMud.castShadow = true;
mainMud.receiveShadow = true;
mainDamGroup.add(mainMud);
for (let i = 0; i < 5; i++) {
const z = MAIN_DAM_Z - 0.33 + i * 0.16;
const y = 0.85 + Math.sin(i * 1.7) * 0.035;
addLog(
mainDamGroup,
mainCenterX - 5.7,
mainCenterX - 1.5,
z,
y,
0.16
);
addLog(
mainDamGroup,
mainCenterX + 1.5,
mainCenterX + 5.7,
z,
y + 0.025,
0.16
);
}
for (let i = 0; i < 3; i++) {
addLog(
centralDamGroup,
mainCenterX - 1.5,
mainCenterX + 1.5,
MAIN_DAM_Z - 0.24 + i * 0.24,
0.88 + Math.sin(i * 2.1) * 0.025,
0.165,
removableLogMaterial
);
}
// Orange stakes mark the removable center section.
for (const side of [-1, 1]) {
const stake = new THREE.Mesh(
new THREE.CylinderGeometry(0.095, 0.12, 1.45, 6),
markerMaterial
);
stake.position.set(mainCenterX + side * 1.48, 0.94, MAIN_DAM_Z);
stake.castShadow = true;
mainDamGroup.add(stake);
}
const secondaryCenterX = channelCenter(SECONDARY_DAM_Z);
const secondaryDam = new THREE.Group();
scene.add(secondaryDam);
const secondaryMud = new THREE.Mesh(
new THREE.BoxGeometry(6.2, 0.16, 0.75),
mudMaterial
);
secondaryMud.position.set(secondaryCenterX, 0.29, SECONDARY_DAM_Z);
secondaryMud.castShadow = true;
secondaryDam.add(secondaryMud);
for (let i = 0; i < 4; i++) {
addLog(
secondaryDam,
secondaryCenterX - 3.2,
secondaryCenterX + 3.2,
SECONDARY_DAM_Z - 0.24 + i * 0.16,
0.47 + Math.sin(i * 1.4) * 0.025,
0.13
);
}
function createLodge() {
const group = new THREE.Group();
const x = channelCenter(0.2) + 4.25;
const z = 0.35;
const ground = terrainHeight(x, z);
const dome = new THREE.Mesh(
new THREE.DodecahedronGeometry(1, 1),
new THREE.MeshStandardMaterial({
color: 0x60442f,
roughness: 1,
flatShading: true
})
);
dome.scale.set(1.45, 0.78, 1.15);
dome.position.set(x, ground + 0.36, z);
dome.castShadow = true;
dome.receiveShadow = true;
group.add(dome);
const entrance = new THREE.Mesh(
new THREE.CircleGeometry(0.34, 10),
new THREE.MeshBasicMaterial({ color: 0x171916 })
);
entrance.position.set(x, ground + 0.29, z + 1.06);
group.add(entrance);
return group;
}
scene.add(createLodge());
function createBeaver(x, z, rotation, scale = 1) {
const group = new THREE.Group();
const fur = new THREE.MeshStandardMaterial({
color: 0x68442f,
roughness: 0.95,
flatShading: true
});
const dark = new THREE.MeshStandardMaterial({
color: 0x34251e,
roughness: 1,
flatShading: true
});
const body = new THREE.Mesh(
new THREE.SphereGeometry(0.38, 8, 6),
fur
);
body.scale.set(1.25, 0.7, 0.78);
body.position.set(0, 0.3, 0);
body.castShadow = true;
group.add(body);
const head = new THREE.Mesh(
new THREE.SphereGeometry(0.27, 8, 6),
fur
);
head.position.set(0.42, 0.43, 0);
head.castShadow = true;
group.add(head);
const snout = new THREE.Mesh(
new THREE.SphereGeometry(0.16, 7, 5),
dark
);
snout.scale.set(1.2, 0.72, 0.8);
snout.position.set(0.67, 0.38, 0);
group.add(snout);
const tail = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.3, 0),
dark
);
tail.scale.set(1.45, 0.28, 0.8);
tail.position.set(-0.55, 0.2, 0);
tail.castShadow = true;
group.add(tail);
const eyeMaterial = new THREE.MeshBasicMaterial({ color: 0x080b09 });
for (const side of [-1, 1]) {
const eye = new THREE.Mesh(
new THREE.SphereGeometry(0.035, 6, 4),
eyeMaterial
);
eye.position.set(0.55, 0.52, side * 0.19);
group.add(eye);
}
group.position.set(x, terrainHeight(x, z) + 0.03, z);
group.rotation.y = rotation;
group.scale.setScalar(scale);
return group;
}
scene.add(createBeaver(channelCenter(6.1) + 1.4, 6.1, -0.35, 0.9));
scene.add(createBeaver(channelCenter(8.1) - 1.2, 8.1, 2.65, 0.78));
// -------------------------------------------------------------------------
// Instanced vegetation and rocks
// -------------------------------------------------------------------------
let randomSeed = 74291;
function random() {
randomSeed = (randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
const treePositions = [];
for (let attempt = 0; attempt < 900 && treePositions.length < 48; attempt++) {
const x = -WIDTH / 2 + 1.5 + random() * (WIDTH - 3);
const z = -DEPTH / 2 + 1.5 + random() * (DEPTH - 3);
const distanceFromChannel = Math.abs(x - channelCenter(z));
const height = terrainHeight(x, z);
if (distanceFromChannel < 5.6) continue;
if (z > 6 && height < 0.55) continue;
if (z > -17 && z < 4 && distanceFromChannel < 8) continue;
treePositions.push({
x,
z,
y: height,
scale: 0.72 + random() * 0.65,
rotation: random() * Math.PI * 2
});
}
const trunkMesh = new THREE.InstancedMesh(
new THREE.CylinderGeometry(0.11, 0.18, 1, 5),
new THREE.MeshStandardMaterial({
color: 0x73533a,
roughness: 1,
flatShading: true
}),
treePositions.length
);
const canopyMesh = new THREE.InstancedMesh(
new THREE.ConeGeometry(0.78, 1.55, 6),
new THREE.MeshStandardMaterial({
color: 0x4e7956,
roughness: 0.96,
flatShading: true
}),
treePositions.length
);
const dummy = new THREE.Object3D();
treePositions.forEach((tree, index) => {
dummy.position.set(tree.x, tree.y + 0.53 * tree.scale, tree.z);
dummy.rotation.set(0, tree.rotation, 0);
dummy.scale.set(tree.scale, tree.scale, tree.scale);
dummy.updateMatrix();
trunkMesh.setMatrixAt(index, dummy.matrix);
dummy.position.set(tree.x, tree.y + 1.37 * tree.scale, tree.z);
dummy.rotation.set(0, tree.rotation + 0.4, 0);
dummy.scale.set(tree.scale, tree.scale, tree.scale);
dummy.updateMatrix();
canopyMesh.setMatrixAt(index, dummy.matrix);
});
trunkMesh.castShadow = true;
trunkMesh.receiveShadow = true;
canopyMesh.castShadow = true;
canopyMesh.receiveShadow = true;
scene.add(trunkMesh, canopyMesh);
const rockData = [];
for (let attempt = 0; attempt < 400 && rockData.length < 34; attempt++) {
const x = -WIDTH / 2 + 1 + random() * (WIDTH - 2);
const z = -DEPTH / 2 + 1 + random() * (DEPTH - 2);
const height = terrainHeight(x, z);
if (Math.abs(x - channelCenter(z)) < 2.1 && z < MAIN_DAM_Z) continue;
rockData.push({ x, z, y: height, scale: 0.25 + random() * 0.55 });
}
const rockMesh = new THREE.InstancedMesh(
new THREE.DodecahedronGeometry(0.5, 0),
new THREE.MeshStandardMaterial({
color: 0x8b9287,
roughness: 1,
flatShading: true
}),
rockData.length
);
rockData.forEach((rock, index) => {
dummy.position.set(rock.x, rock.y + rock.scale * 0.28, rock.z);
dummy.rotation.set(random(), random() * Math.PI, random() * 0.4);
dummy.scale.set(rock.scale, rock.scale * 0.7, rock.scale);
dummy.updateMatrix();
rockMesh.setMatrixAt(index, dummy.matrix);
});
rockMesh.castShadow = true;
rockMesh.receiveShadow = true;
scene.add(rockMesh);
const reedData = [];
for (let attempt = 0; attempt < 900 && reedData.length < 115; attempt++) {
const x = -WIDTH / 2 + 1 + random() * (WIDTH - 2);
const z = 5.5 + random() * 12.5;
const height = terrainHeight(x, z);
const distanceFromChannel = Math.abs(x - channelCenter(z));
if (height > 0.54 || distanceFromChannel < 0.7) continue;
reedData.push({
x,
z,
y: height,
scale: 0.55 + random() * 0.9
});
}
const reedMesh = new THREE.InstancedMesh(
new THREE.CylinderGeometry(0.018, 0.035, 1, 4),
new THREE.MeshStandardMaterial({
color: 0x789453,
roughness: 1,
flatShading: true
}),
reedData.length
);
reedData.forEach((reed, index) => {
dummy.position.set(reed.x, reed.y + reed.scale * 0.5, reed.z);
dummy.rotation.set(
(random() - 0.5) * 0.15,
random() * Math.PI,
(random() - 0.5) * 0.15
);
dummy.scale.set(1, reed.scale, 1);
dummy.updateMatrix();
reedMesh.setMatrixAt(index, dummy.matrix);
});
reedMesh.castShadow = true;
scene.add(reedMesh);
// -------------------------------------------------------------------------
// Hydrology: connected-cell flood calculation
// -------------------------------------------------------------------------
function connectedFlood(level, zMin, zMax, sourceZ, sourceHalfWidth = 1.4) {
const visited = new Uint8Array(NX * NZ);
const queue = [];
const sourceJ = Math.max(
0,
Math.min(
NZ - 1,
Math.round((sourceZ + DEPTH / 2) / CELL - 0.5)
)
);
for (let i = 0; i < NX; i++) {
const index = sourceJ * NX + i;
const withinZ = cellZ[index] >= zMin && cellZ[index] <= zMax;
const nearChannel =
Math.abs(cellX[index] - channelCenter(cellZ[index])) <
sourceHalfWidth;
if (
withinZ &&
nearChannel &&
cellHeights[index] < level - 0.003
) {
visited[index] = 1;
queue.push(index);
}
}
let head = 0;
while (head < queue.length) {
const index = queue[head++];
const i = index % NX;
const j = Math.floor(index / NX);
const neighbors = [];
if (i > 0) neighbors.push(index - 1);
if (i < NX - 1) neighbors.push(index + 1);
if (j > 0) neighbors.push(index - NX);
if (j < NZ - 1) neighbors.push(index + NX);
for (const neighbor of neighbors) {
if (visited[neighbor]) continue;
const z = cellZ[neighbor];
if (z < zMin || z > zMax) continue;
if (cellHeights[neighbor] >= level - 0.003) continue;
visited[neighbor] = 1;
queue.push(neighbor);
}
}
const cells = [];
for (let index = 0; index < visited.length; index++) {
if (visited[index]) cells.push(index);
}
return { visited, cells };
}
const downstreamFlood = connectedFlood(
DOWNSTREAM_STAGE,
MAIN_DAM_Z + 0.3,
SECONDARY_DAM_Z + 0.25,
SECONDARY_DAM_Z - 0.18,
1.15
);
const upstreamBedArea = (() => {
let count = 0;
for (let index = 0; index < cellHeights.length; index++) {
if (
cellZ[index] < MAIN_DAM_Z &&
cellHeights[index] <= INTACT_CREST + 0.03
) {
count++;
}
}
return count * CELL_AREA;
})();
function makeCellSurfaceGeometry(cells, level) {
const positions = [];
for (const index of cells) {
const i = index % NX;
const j = Math.floor(index / NX);
const x0 = -WIDTH / 2 + i * CELL;
const x1 = x0 + CELL;
const z0 = -DEPTH / 2 + j * CELL;
const z1 = z0 + CELL;
positions.push(
x0, level, z0,
x0, level, z1,
x1, level, z1,
x0, level, z0,
x1, level, z1,
x1, level, z0
);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.computeVertexNormals();
return geometry;
}
function makeTerrainOverlayGeometry(cells, offset = 0.025) {
const positions = [];
for (const index of cells) {
const i = index % NX;
const j = Math.floor(index / NX);
const x0 = -WIDTH / 2 + i * CELL;
const x1 = x0 + CELL;
const z0 = -DEPTH / 2 + j * CELL;
const z1 = z0 + CELL;
const p00 = new THREE.Vector3(x0, terrainHeight(x0, z0) + offset, z0);
const p10 = new THREE.Vector3(x1, terrainHeight(x1, z0) + offset, z0);
const p01 = new THREE.Vector3(x0, terrainHeight(x0, z1) + offset, z1);
const p11 = new THREE.Vector3(x1, terrainHeight(x1, z1) + offset, z1);
for (const point of [p00, p01, p11, p00, p11, p10]) {
positions.push(point.x, point.y, point.z);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.computeVertexNormals();
return geometry;
}
function makeStreamGeometry() {
const positions = [];
const indices = [];
const samples = 90;
for (let i = 0; i <= samples; i++) {
const z = MAIN_DAM_Z + 0.15 + (19.4 - MAIN_DAM_Z) * (i / samples);
const center = channelCenter(z);
const halfWidth = 0.48;
positions.push(
center - halfWidth,
terrainHeight(center - halfWidth, z) + 0.075,
z,
center + halfWidth,
terrainHeight(center + halfWidth, z) + 0.075,
z
);
if (i < samples) {
const a = i * 2;
indices.push(a, a + 1, a + 3, a, a + 3, a + 2);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
const waterGroup = new THREE.Group();
scene.add(waterGroup);
const waterMaterial = new THREE.MeshStandardMaterial({
color: 0x43b4c0,
roughness: 0.28,
metalness: 0.04,
transparent: true,
opacity: 0.78,
depthWrite: false,
side: THREE.DoubleSide
});
const streamMaterial = new THREE.MeshStandardMaterial({
color: 0x299fb3,
roughness: 0.25,
transparent: true,
opacity: 0.83,
depthWrite: false,
side: THREE.DoubleSide
});
const ghostMaterial = new THREE.MeshBasicMaterial({
color: 0x287fbd,
transparent: true,
opacity: 0.27,
depthWrite: false,
side: THREE.DoubleSide
});
const exposedMaterial = new THREE.MeshBasicMaterial({
color: 0xcf7b37,
transparent: true,
opacity: 0.25,
depthWrite: false,
side: THREE.DoubleSide
});
function clearWaterGroup() {
while (waterGroup.children.length) {
const child = waterGroup.children.pop();
if (child.geometry) child.geometry.dispose();
}
}
function updateModel() {
const intactStage = Math.min(
INTACT_CREST,
INTACT_BASE_STAGE + rainfall * RAIN_STAGE_RESPONSE
);
const removedStage = Math.min(
REMOVED_SILL,
REMOVED_BASE_STAGE + rainfall * RAIN_STAGE_RESPONSE
);
const intactFlood = connectedFlood(
intactStage,
-DEPTH / 2,
MAIN_DAM_Z + 0.2,
MAIN_DAM_Z - 0.18,
1.4
);
const removedFlood = connectedFlood(
removedStage,
-DEPTH / 2,
MAIN_DAM_Z + 0.2,
MAIN_DAM_Z - 0.18,
1.4
);
const intactArea = intactFlood.cells.length * CELL_AREA;
const removedArea = removedFlood.cells.length * CELL_AREA;
const intactExposed = upstreamBedArea - intactArea;
const removedExposed = upstreamBedArea - removedArea;
document.getElementById("intactArea").textContent =
`${intactArea.toFixed(1)} m²`;
document.getElementById("removedArea").textContent =
`${removedArea.toFixed(1)} m²`;
document.getElementById("intactExposed").textContent =
`${intactExposed.toFixed(1)} m²`;
document.getElementById("removedExposed").textContent =
`${removedExposed.toFixed(1)} m²`;
document.getElementById("intactStage").textContent =
`${intactStage.toFixed(2)} m`;
document.getElementById("removedStage").textContent =
`${removedStage.toFixed(2)} m`;
const areaDifference = Math.abs(intactArea - removedArea);
const moreExposed = removedExposed - intactExposed;
document.getElementById("deltaText").innerHTML =
`With the section removed, modeled upstream water is ` +
`<strong>${areaDifference.toFixed(1)} m² lower</strong> and ` +
`<strong>${Math.abs(moreExposed).toFixed(1)} m² more pond-bed ground ` +
`is exposed</strong> in this prescribed steady-state snapshot.`;
document.getElementById("downstreamNote").innerHTML =
`Downstream wetland water extent is fixed at ` +
`<strong>${(downstreamFlood.cells.length * CELL_AREA).toFixed(1)} m²</strong>. ` +
`This isolates the mechanical effect of the main dam outlet.`;
clearWaterGroup();
const activeFlood =
selectedScenario === "intact" ? intactFlood : removedFlood;
const activeStage =
selectedScenario === "intact" ? intactStage : removedStage;
const activeWater = new THREE.Mesh(
makeCellSurfaceGeometry(activeFlood.cells, activeStage),
waterMaterial.clone()
);
activeWater.material.color.set(
selectedScenario === "intact" ? 0x43b4c0 : 0x3ca9b8
);
activeWater.material.opacity = 0.78;
activeWater.renderOrder = 2;
activeWater.receiveShadow = true;
waterGroup.add(activeWater);
const downstreamWater = new THREE.Mesh(
makeCellSurfaceGeometry(
downstreamFlood.cells,
DOWNSTREAM_STAGE
),
waterMaterial.clone()
);
downstreamWater.material.opacity = 0.7;
downstreamWater.renderOrder = 2;
waterGroup.add(downstreamWater);
const stream = new THREE.Mesh(
makeStreamGeometry(),
streamMaterial
);
stream.renderOrder = 3;
waterGroup.add(stream);
const differentCells = intactFlood.cells.filter(
(index) => !removedFlood.visited[index]
);
if (showComparison && differentCells.length) {
if (selectedScenario === "removed") {
const ghost = new THREE.Mesh(
makeCellSurfaceGeometry(
differentCells,
intactStage + 0.018
),
ghostMaterial
);
ghost.renderOrder = 4;
waterGroup.add(ghost);
} else {
const potentialExposure = new THREE.Mesh(
makeTerrainOverlayGeometry(differentCells),
exposedMaterial
);
potentialExposure.renderOrder = 4;
waterGroup.add(potentialExposure);
}
}
centralDamGroup.visible = selectedScenario === "intact";
syncControls();
}
function syncControls() {
const intactButton = document.getElementById("intactButton");
const removedButton = document.getElementById("removedButton");
const damToggle = document.getElementById("damToggle");
const scenarioNote = document.getElementById("scenarioNote");
const compareLegend = document.getElementById("compareLegend");
const intact = selectedScenario === "intact";
intactButton.classList.toggle("active", intact);
removedButton.classList.toggle("active", !intact);
intactButton.setAttribute("aria-pressed", String(intact));
removedButton.setAttribute("aria-pressed", String(!intact));
damToggle.textContent = intact
? "Remove center section"
: "Replace center section";
scenarioNote.textContent = intact
? "The full dam holds a higher upstream pool."
: "The center section is out, lowering the modeled outlet.";
compareLegend.textContent = intact
? "Amber overlay: ground exposed by removing the section"
: "Blue ghost: former intact-pool footprint";
document.getElementById("labelDam").textContent = intact
? "Removable dam section — in place"
: "Removable dam section — removed";
}
// -------------------------------------------------------------------------
// Flow markers
// -------------------------------------------------------------------------
const flowParticles = [];
const flowGeometry = new THREE.SphereGeometry(0.095, 6, 4);
const flowMaterial = new THREE.MeshBasicMaterial({
color: 0xbef6ff,
transparent: true,
opacity: 0.9
});
for (let i = 0; i < 13; i++) {
const particle = new THREE.Mesh(flowGeometry, flowMaterial);
scene.add(particle);
flowParticles.push(particle);
}
function animateFlow(time) {
flowParticles.forEach((particle, index) => {
const z =
MAIN_DAM_Z + 0.5 +
((time * 1.75 + index * 1.43) % (18.8 - MAIN_DAM_Z));
const x = channelCenter(z);
const ground = terrainHeight(x, z);
particle.position.set(x, Math.max(ground + 0.13, DOWNSTREAM_STAGE + 0.04), z);
});
}
// -------------------------------------------------------------------------
// Labels
// -------------------------------------------------------------------------
const labelElements = {
dam: document.getElementById("labelDam"),
upper: document.getElementById("labelUpper"),
lower: document.getElementById("labelLower")
};
const labelPositions = {
dam: new THREE.Vector3(
mainCenterX,
1.65,
MAIN_DAM_Z
),
upper: new THREE.Vector3(
channelCenter(-4) - 3.1,
terrainHeight(channelCenter(-4) - 3.1, -4) + 1.05,
-4
),
lower: new THREE.Vector3(
channelCenter(9.5) + 3.4,
terrainHeight(channelCenter(9.5) + 3.4, 9.5) + 1,
9.5
)
};
const projected = new THREE.Vector3();
function updateLabels() {
for (const [key, element] of Object.entries(labelElements)) {
projected.copy(labelPositions[key]).project(camera);
const visible = projected.z > -1 && projected.z < 1;
element.style.opacity = visible ? "1" : "0";
if (visible) {
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.transform = `translate(${x}px, ${y}px) translate(-50%, -50%)`;
}
}
}
// -------------------------------------------------------------------------
// Custom camera controls: orbit, pan, wheel zoom, and pinch zoom
// -------------------------------------------------------------------------
const controls = {
target: new THREE.Vector3(0, 0.45, 0),
desiredTarget: new THREE.Vector3(0, 0.45, 0),
theta: 0.46,
desiredTheta: 0.46,
phi: 0.89,
desiredPhi: 0.89,
radius: 72,
desiredRadius: 72
};
function resetView() {
controls.desiredTarget.set(0, 0.45, 0);
controls.desiredTheta = 0.46;
controls.desiredPhi = 0.89;
controls.desiredRadius = 72;
}
function updateCamera(dt) {
const smoothing = 1 - Math.exp(-dt * 10);
controls.theta +=
(controls.desiredTheta - controls.theta) * smoothing;
controls.phi +=
(controls.desiredPhi - controls.phi) * smoothing;
controls.radius +=
(controls.desiredRadius - controls.radius) * smoothing;
controls.target.lerp(controls.desiredTarget, smoothing);
const sinPhi = Math.sin(controls.phi);
camera.position.set(
controls.target.x +
controls.radius * sinPhi * Math.sin(controls.theta),
controls.target.y + controls.radius * Math.cos(controls.phi),
controls.target.z +
controls.radius * sinPhi * Math.cos(controls.theta)
);
camera.lookAt(controls.target);
camera.updateMatrixWorld();
}
const pointerMap = new Map();
let pinchDistance = 0;
function pointerDistance() {
const points = [...pointerMap.values()];
if (points.length < 2) return 0;
return Math.hypot(
points[0].x - points[1].x,
points[0].y - points[1].y
);
}
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointerMap.set(event.pointerId, {
x: event.clientX,
y: event.clientY,
button: event.button
});
if (pointerMap.size >= 2) {
pinchDistance = pointerDistance();
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
const previous = pointerMap.get(event.pointerId);
if (!previous) return;
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
previous.x = event.clientX;
previous.y = event.clientY;
if (pointerMap.size >= 2) {
const newDistance = pointerDistance();
if (newDistance > 0 && pinchDistance > 0) {
controls.desiredRadius *=
pinchDistance / newDistance;
controls.desiredRadius = THREE.MathUtils.clamp(
controls.desiredRadius,
34,
105
);
}
pinchDistance = newDistance;
return;
}
const wantsPan =
event.pointerType === "mouse" &&
(event.shiftKey || previous.button === 2);
if (wantsPan) {
const right = new THREE.Vector3()
.setFromMatrixColumn(camera.matrixWorld, 0);
right.y = 0;
right.normalize();
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const scale = controls.radius * 0.00135;
controls.desiredTarget.addScaledVector(right, -dx * scale);
controls.desiredTarget.addScaledVector(forward, dy * scale);
controls.desiredTarget.x = THREE.MathUtils.clamp(
controls.desiredTarget.x,
-18,
18
);
controls.desiredTarget.z = THREE.MathUtils.clamp(
controls.desiredTarget.z,
-18,
18
);
} else {
controls.desiredTheta -= dx * 0.006;
controls.desiredPhi = THREE.MathUtils.clamp(
controls.desiredPhi - dy * 0.005,
0.28,
1.43
);
}
});
function endPointer(event) {
pointerMap.delete(event.pointerId);
pinchDistance = pointerDistance();
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
controls.desiredRadius *= Math.exp(event.deltaY * 0.001);
controls.desiredRadius = THREE.MathUtils.clamp(
controls.desiredRadius,
34,
105
);
},
{ passive: false }
);
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
document.getElementById("intactButton").addEventListener("click", () => {
selectedScenario = "intact";
updateModel();
});
document.getElementById("removedButton").addEventListener("click", () => {
selectedScenario = "removed";
updateModel();
});
document.getElementById("damToggle").addEventListener("click", () => {
selectedScenario =
selectedScenario === "intact" ? "removed" : "intact";
updateModel();
});
document.getElementById("rainInput").addEventListener("input", (event) => {
rainfall = Number(event.target.value);
document.getElementById("rainValue").textContent =
`${rainfall} mm`;
updateModel();
});
document.getElementById("compareCheck").addEventListener("change", (event) => {
showComparison = event.target.checked;
updateModel();
});
document.getElementById("resetView").addEventListener("click", resetView);
document.getElementById("resetModel").addEventListener("click", () => {
rainfall = 0;
selectedScenario = "intact";
document.getElementById("rainInput").value = "0";
document.getElementById("rainValue").textContent = "0 mm";
updateModel();
resetView();
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
// -------------------------------------------------------------------------
// Render loop
// -------------------------------------------------------------------------
updateModel();
updateCamera(1);
let previousTime = performance.now();
function animate(time) {
const dt = Math.min((time - previousTime) / 1000, 0.05);
previousTime = time;
updateCamera(dt);
animateFlow(time / 1000);
updateLabels();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```