Prompt specification
Build or customize the Three.js 3D scene "Shoreline vegetation connectivity model" 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: Shoreline vegetation connectivity model
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/shoreline-vegetation-connectivity-model-x0752
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing mangrove establishment. Create a schematic estuary with adjustable planting patches and tidal channels; users inspect habitat connections and sediment-retention illustrations without treating them as coastal-engineering forecasts. Low-poly.
Working Three.js Starter (shoreline-vegetation-connectivity-model-x0752):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mangrove Establishment — Schematic Estuary</title>
<style>
:root {
--ink: #17332e;
--muted: #62736b;
--panel: rgba(249, 247, 238, 0.94);
--panel-solid: #f7f4e9;
--line: rgba(35, 72, 61, 0.17);
--green: #315f49;
--green-2: #6c8c62;
--water: #4e9695;
--gold: #bd8c42;
--shadow: 0 18px 50px rgba(29, 54, 46, 0.18);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #b9d2c8;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#viewport {
position: fixed;
inset: 0;
overflow: hidden;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
cursor: grab;
}
#viewport canvas:active {
cursor: grabbing;
}
.topbar {
position: fixed;
z-index: 20;
top: 0;
left: 0;
right: 0;
min-height: 76px;
display: flex;
align-items: center;
gap: 18px;
padding: 13px 20px;
background: rgba(248, 246, 235, 0.92);
border-bottom: 1px solid var(--line);
backdrop-filter: blur(14px);
box-shadow: 0 6px 25px rgba(36, 65, 55, 0.08);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
position: relative;
flex: 0 0 38px;
width: 38px;
height: 38px;
border-radius: 50%;
background: var(--green);
overflow: hidden;
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
left: 19px;
bottom: 5px;
width: 2px;
height: 25px;
background: #e9e4ca;
transform-origin: bottom;
}
.brand-mark::before {
transform: rotate(-29deg);
}
.brand-mark::after {
transform: rotate(31deg);
}
.brand-copy {
min-width: 0;
}
.eyebrow {
margin: 0 0 3px;
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.17em;
text-transform: uppercase;
}
h1 {
margin: 0;
overflow: hidden;
color: var(--ink);
font-size: clamp(17px, 2vw, 23px);
font-weight: 720;
letter-spacing: -0.035em;
line-height: 1.05;
text-overflow: ellipsis;
white-space: nowrap;
}
.subtitle {
margin-top: 4px;
color: var(--muted);
font-size: 12px;
}
.top-actions {
display: flex;
align-items: center;
gap: 8px;
margin-left: auto;
}
.badge {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 8px 11px;
border: 1px solid rgba(177, 123, 44, 0.28);
border-radius: 999px;
color: #79561e;
background: rgba(244, 221, 172, 0.42);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
white-space: nowrap;
}
.badge::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: #c58d35;
box-shadow: 0 0 0 4px rgba(197, 141, 53, 0.13);
}
.action-button,
.mobile-button {
min-height: 36px;
padding: 8px 12px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.58);
cursor: pointer;
font-size: 12px;
font-weight: 650;
transition:
background 150ms ease,
transform 150ms ease;
}
.action-button:hover,
.mobile-button:hover {
background: white;
transform: translateY(-1px);
}
.action-button.active {
color: white;
border-color: var(--green);
background: var(--green);
}
.mobile-button {
display: none;
}
.sidebar {
position: fixed;
z-index: 15;
top: 92px;
bottom: 18px;
left: 18px;
width: 320px;
padding: 16px;
overflow: auto;
border: 1px solid rgba(41, 78, 65, 0.13);
border-radius: 18px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(17px);
scrollbar-width: thin;
scrollbar-color: rgba(49, 95, 73, 0.25) transparent;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 15px;
}
.panel-heading h2 {
margin: 0;
font-size: 15px;
letter-spacing: -0.015em;
}
.panel-heading span {
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.section {
padding: 13px 0;
border-top: 1px solid var(--line);
}
.section:first-of-type {
padding-top: 0;
border-top: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.control {
margin-bottom: 13px;
}
.control:last-child {
margin-bottom: 0;
}
.control-line {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 7px;
}
.control-line label {
color: #304a40;
font-size: 12px;
font-weight: 600;
}
output {
color: var(--green);
font-size: 11px;
font-weight: 750;
white-space: nowrap;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 4px 0;
border-radius: 99px;
appearance: none;
background: linear-gradient(
to right,
var(--green) 0%,
var(--green) var(--range-fill, 50%),
rgba(49, 95, 73, 0.16) var(--range-fill, 50%),
rgba(49, 95, 73, 0.16) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid var(--panel-solid);
border-radius: 50%;
appearance: none;
background: var(--green);
box-shadow: 0 0 0 1px rgba(49, 95, 73, 0.4);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid var(--panel-solid);
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 1px rgba(49, 95, 73, 0.4);
}
.patch-row {
margin-bottom: 11px;
padding: 10px;
border: 1px solid rgba(49, 95, 73, 0.1);
border-radius: 11px;
background: rgba(255, 255, 255, 0.38);
}
.patch-row:last-child {
margin-bottom: 0;
}
.patch-row .control-line {
margin-bottom: 5px;
}
.patch-name {
display: flex;
align-items: center;
gap: 7px;
font-size: 11px;
font-weight: 650;
}
.patch-swatch {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--swatch);
transform: rotate(45deg);
}
.layer-list {
display: grid;
gap: 9px;
}
.layer-toggle {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
color: #304a40;
font-size: 12px;
font-weight: 600;
cursor: pointer;
}
.layer-description {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
font-weight: 450;
}
.toggle {
position: relative;
flex: 0 0 34px;
width: 34px;
height: 19px;
}
.toggle input {
position: absolute;
width: 1px;
height: 1px;
opacity: 0;
}
.toggle-track {
position: absolute;
inset: 0;
border-radius: 99px;
background: rgba(49, 95, 73, 0.2);
transition: background 160ms ease;
}
.toggle-track::after {
content: "";
position: absolute;
top: 3px;
left: 3px;
width: 13px;
height: 13px;
border-radius: 50%;
background: white;
box-shadow: 0 1px 4px rgba(31, 55, 46, 0.22);
transition: transform 160ms ease;
}
.toggle input:checked + .toggle-track {
background: var(--green);
}
.toggle input:checked + .toggle-track::after {
transform: translateX(15px);
}
.legend {
display: grid;
gap: 8px;
}
.legend-item {
display: flex;
align-items: center;
gap: 9px;
color: #4d6259;
font-size: 10px;
}
.legend-symbol {
flex: 0 0 24px;
width: 24px;
height: 13px;
border-radius: 3px;
}
.legend-symbol.water {
background: rgba(78, 150, 149, 0.48);
border: 1px solid rgba(54, 119, 120, 0.38);
}
.legend-symbol.mangrove {
background: #507e54;
clip-path: polygon(50% 0, 78% 24%, 100% 55%, 73% 48%, 73% 100%, 27% 100%, 27% 48%, 0 55%, 22% 24%);
}
.legend-symbol.link {
height: 0;
border-top: 2px dashed #558267;
border-radius: 0;
}
.legend-symbol.sediment {
height: 5px;
border-radius: 99px;
background: repeating-linear-gradient(
90deg,
#c29449 0 4px,
transparent 4px 7px
);
}
.instructions {
margin-top: 13px;
padding: 10px;
border-radius: 10px;
color: var(--muted);
background: rgba(49, 95, 73, 0.055);
font-size: 10px;
line-height: 1.55;
}
.info-card {
position: fixed;
z-index: 12;
top: 94px;
right: 18px;
width: 278px;
padding: 16px;
border: 1px solid rgba(41, 78, 65, 0.13);
border-radius: 17px;
background: rgba(249, 247, 238, 0.92);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
}
.info-kicker {
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.info-card h2 {
margin: 6px 0 3px;
font-size: 20px;
letter-spacing: -0.035em;
}
.info-subtitle {
margin: 0 0 13px;
color: var(--muted);
font-size: 11px;
}
.metric-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 8px 0;
border-top: 1px solid var(--line);
font-size: 11px;
}
.metric-row span:first-child {
color: var(--muted);
}
.metric-row strong {
color: var(--green);
font-size: 12px;
}
.metric-bar {
height: 4px;
margin-top: 7px;
overflow: hidden;
border-radius: 99px;
background: rgba(49, 95, 73, 0.12);
}
.metric-bar > span {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: var(--green);
transition: width 250ms ease;
}
.info-note {
margin: 12px 0 0;
color: #53675e;
font-size: 10px;
line-height: 1.55;
}
.bottom-bar {
position: fixed;
z-index: 11;
right: 18px;
bottom: 18px;
left: 356px;
display: flex;
align-items: center;
gap: 15px;
padding: 11px 14px;
border: 1px solid rgba(41, 78, 65, 0.11);
border-radius: 14px;
background: rgba(249, 247, 238, 0.88);
box-shadow: 0 10px 35px rgba(29, 54, 46, 0.12);
backdrop-filter: blur(13px);
}
.readout {
display: flex;
align-items: center;
gap: 16px;
padding-right: 15px;
border-right: 1px solid var(--line);
}
.readout-item {
min-width: 86px;
}
.readout-value {
display: block;
color: var(--green);
font-size: 13px;
font-weight: 800;
}
.readout-label {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.03em;
}
.disclaimer {
color: #675d48;
font-size: 10px;
line-height: 1.45;
}
.disclaimer strong {
color: #75551e;
}
#labels {
position: fixed;
z-index: 8;
inset: 0;
overflow: hidden;
pointer-events: none;
}
.map-label {
position: absolute;
min-width: 88px;
padding: 6px 8px;
border: 1px solid rgba(38, 73, 60, 0.2);
border-radius: 8px;
color: #26493b;
background: rgba(250, 248, 237, 0.88);
box-shadow: 0 5px 18px rgba(28, 55, 45, 0.12);
cursor: pointer;
pointer-events: auto;
transform: translate(-50%, -100%);
transition:
background 150ms ease,
border-color 150ms ease;
backdrop-filter: blur(7px);
}
.map-label:hover,
.map-label.selected {
border-color: rgba(49, 95, 73, 0.75);
background: rgba(255, 255, 252, 0.97);
}
.map-label strong {
display: block;
font-size: 10px;
line-height: 1.1;
}
.map-label small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8px;
}
@media (max-width: 900px) {
.subtitle,
.badge {
display: none;
}
.topbar {
gap: 10px;
padding: 11px 12px;
}
.mobile-button {
display: inline-block;
}
.brand-copy {
display: none;
}
.sidebar {
top: 84px;
bottom: 12px;
left: 12px;
width: min(320px, calc(100vw - 24px));
transform: translateX(calc(-100% - 20px));
transition: transform 180ms ease;
}
body.controls-open .sidebar {
transform: translateX(0);
}
.info-card {
top: 84px;
right: 12px;
width: 250px;
}
.bottom-bar {
right: 12px;
bottom: 12px;
left: 12px;
align-items: stretch;
flex-direction: column;
gap: 8px;
}
.readout {
justify-content: space-between;
padding-right: 0;
padding-bottom: 8px;
border-right: 0;
border-bottom: 1px solid var(--line);
}
}
@media (max-width: 560px) {
.action-button {
padding: 8px 9px;
font-size: 10px;
}
.action-button.optional {
display: none;
}
.info-card {
width: 220px;
padding: 13px;
}
.info-card h2 {
font-size: 17px;
}
.info-note {
display: none;
}
.map-label {
min-width: 70px;
padding: 5px 6px;
}
.map-label strong {
font-size: 8px;
}
}
</style>
</head>
<body>
<div id="viewport" aria-label="Interactive low-poly schematic mangrove estuary"></div>
<div id="labels" aria-label="Mangrove patch labels"></div>
<header class="topbar">
<button
id="panelToggle"
class="mobile-button"
type="button"
aria-expanded="false"
aria-controls="controlPanel"
>
Controls
</button>
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div class="brand-copy">
<p class="eyebrow">Estuary Atlas / Interactive Illustration</p>
<h1>Mangrove establishment</h1>
<div class="subtitle">Planting patches, tidal connections, and sediment retention</div>
</div>
</div>
<div class="top-actions">
<span class="badge">Schematic · not a forecast</span>
<button id="overviewButton" class="action-button" type="button">Overview</button>
<button id="planButton" class="action-button optional" type="button">Plan view</button>
<button id="pulseButton" class="action-button" type="button">Run tide pulse</button>
</div>
</header>
<aside id="controlPanel" class="sidebar" aria-label="Scene controls">
<div class="panel-heading">
<h2>Scene controls</h2>
<span>Illustrative</span>
</div>
<section class="section">
<div class="section-title">
<span>Estuary geometry</span>
<span>01</span>
</div>
<div class="control">
<div class="control-line">
<label for="tideRange">Water level</label>
<output id="tideOutput" for="tideRange"></output>
</div>
<input id="tideRange" type="range" min="-0.5" max="0.8" step="0.01" value="0.12" />
</div>
<div class="control">
<div class="control-line">
<label for="sinuosityRange">Channel sinuosity</label>
<output id="sinuosityOutput" for="sinuosityRange"></output>
</div>
<input id="sinuosityRange" type="range" min="0" max="1" step="0.01" value="0.55" />
</div>
<div class="control">
<div class="control-line">
<label for="branchDensityRange">Connected tributaries</label>
<output id="branchDensityOutput" for="branchDensityRange"></output>
</div>
<input id="branchDensityRange" type="range" min="0" max="100" step="1" value="65" />
</div>
<div class="control">
<div class="control-line">
<label for="branchWidthRange">Tributary width</label>
<output id="branchWidthOutput" for="branchWidthRange"></output>
</div>
<input id="branchWidthRange" type="range" min="0.6" max="3" step="0.1" value="1.4" />
</div>
<div class="control">
<div class="control-line">
<label for="maturityRange">Canopy establishment</label>
<output id="maturityOutput" for="maturityRange"></output>
</div>
<input id="maturityRange" type="range" min="0" max="1" step="0.01" value="0.45" />
</div>
</section>
<section class="section">
<div class="section-title">
<span>Planting patches</span>
<span>02</span>
</div>
<div id="patchControls"></div>
</section>
<section class="section">
<div class="section-title">
<span>Illustration layers</span>
<span>03</span>
</div>
<div class="layer-list">
<label class="layer-toggle">
<span>
Habitat connections
<span class="layer-description">Dashed links between schematic refuges and patches</span>
</span>
<span class="toggle">
<input id="linksToggle" type="checkbox" checked />
<span class="toggle-track"></span>
</span>
</label>
<label class="layer-toggle">
<span>
Sediment retention
<span class="layer-description">Gold tracers collect at illustrated planting edges</span>
</span>
<span class="toggle">
<input id="sedimentToggle" type="checkbox" checked />
<span class="toggle-track"></span>
</span>
</label>
<label class="layer-toggle">
<span>
Tidal flow arrows
<span class="layer-description">Directional cues for the schematic channel network</span>
</span>
<span class="toggle">
<input id="flowToggle" type="checkbox" checked />
<span class="toggle-track"></span>
</span>
</label>
<label class="layer-toggle">
<span>
Patch labels
<span class="layer-description">Names and planting coverage</span>
</span>
<span class="toggle">
<input id="labelsToggle" type="checkbox" checked />
<span class="toggle-track"></span>
</span>
</label>
</div>
</section>
<section class="section">
<div class="section-title">
<span>Reading the scene</span>
<span>04</span>
</div>
<div class="legend">
<div class="legend-item">
<span class="legend-symbol water"></span>
<span>Tidal water and branching channels</span>
</div>
<div class="legend-item">
<span class="legend-symbol mangrove"></span>
<span>Low-poly mangrove establishment patches</span>
</div>
<div class="legend-item">
<span class="legend-symbol link"></span>
<span>Illustrative habitat connectivity</span>
</div>
<div class="legend-item">
<span class="legend-symbol sediment"></span>
<span>Schematic sediment tracers</span>
</div>
</div>
<div class="instructions">
<strong>Camera:</strong> drag to orbit, scroll to zoom, shift-drag or right-drag to pan.
Select a patch to inspect its relative habitat and retention indicators.
</div>
</section>
</aside>
<aside id="infoCard" class="info-card" aria-live="polite">
<div class="info-kicker">Selected planting patch</div>
<h2 id="patchTitle">Heron Bank</h2>
<p id="patchSubtitle" class="info-subtitle">Relative illustration metrics</p>
<div class="metric-row">
<span>Planting coverage</span>
<strong id="patchCoverage">54%</strong>
</div>
<div class="metric-row">
<span>Habitat-link score</span>
<strong id="patchHabitat">68 / 100</strong>
</div>
<div class="metric-bar"><span id="patchHabitatBar"></span></div>
<div class="metric-row">
<span>Retention illustration</span>
<strong id="patchRetention">61 / 100</strong>
</div>
<div class="metric-bar"><span id="patchRetentionBar"></span></div>
<div class="metric-row">
<span>Channel relationship</span>
<strong id="patchChannel">Nearby</strong>
</div>
<p id="patchNote" class="info-note"></p>
</aside>
<footer class="bottom-bar">
<div class="readout">
<div class="readout-item">
<span id="linkScore" class="readout-value">—</span>
<span class="readout-label">Habitat link · relative</span>
</div>
<div class="readout-item">
<span id="tracerReadout" class="readout-value">—</span>
<span class="readout-label">Tracers settled · schematic</span>
</div>
<div class="readout-item">
<span id="channelReadout" class="readout-value">—</span>
<span class="readout-label">Tributaries shown</span>
</div>
</div>
<div class="disclaimer">
<strong>Teaching illustration only.</strong>
Geometry, habitat links, and tracer behavior are not calibrated hydrodynamic,
sediment, or coastal-engineering forecasts. Do not use this display for planning,
design, permitting, or regulatory decisions.
</div>
</footer>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const state = {
tide: 0.12,
sinuosity: 0.55,
branchDensity: 65,
branchWidth: 1.4,
maturity: 0.45,
coverage: [78, 54, 88, 42, 70],
links: true,
sediment: true,
flow: true,
labels: true,
selectedPatch: 1,
pulsing: false,
pulseStarted: 0
};
const patchDefinitions = [
{
name: "Upper Nursery",
z: -29,
side: -1,
color: "#557f52",
seed: 1
},
{
name: "Heron Bank",
z: -14,
side: 1,
color: "#477653",
seed: 2
},
{
name: "Reed Spit",
z: 1,
side: -1,
color: "#628653",
seed: 3
},
{
name: "Middle Bench",
z: 15,
side: 1,
color: "#50794e",
seed: 4
},
{
name: "Bayward Edge",
z: 27,
side: -1,
color: "#6a8e57",
seed: 5
}
];
const viewport = $("viewport");
const scene = new THREE.Scene();
scene.background = new THREE.Color("#b9d2c8");
scene.fog = new THREE.Fog("#b9d2c8", 100, 180);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
300
);
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.08;
renderer.domElement.setAttribute(
"aria-label",
"Low-poly interactive estuary with mangrove patches and tidal channels"
);
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf3f6e7, 0x53695b, 2.0);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1cd, 2.25);
sun.position.set(-35, 70, 28);
scene.add(sun);
const fill = new THREE.DirectionalLight(0x91c5c7, 0.65);
fill.position.set(45, 22, -35);
scene.add(fill);
const terrainGroup = new THREE.Group();
const waterGroup = new THREE.Group();
const patchGroup = new THREE.Group();
const linksGroup = new THREE.Group();
const flowGroup = new THREE.Group();
const sedimentGroup = new THREE.Group();
const haloGroup = new THREE.Group();
sedimentGroup.add(haloGroup);
scene.add(
terrainGroup,
waterGroup,
patchGroup,
linksGroup,
flowGroup,
sedimentGroup
);
const ocean = new THREE.Mesh(
new THREE.PlaneGeometry(220, 220),
new THREE.MeshStandardMaterial({
color: 0x76aaa7,
roughness: 0.82,
metalness: 0,
flatShading: true
})
);
ocean.rotation.x = -Math.PI / 2;
ocean.position.y = -2.5;
scene.add(ocean);
const selectionRing = new THREE.Mesh(
new THREE.RingGeometry(1, 1.1, 6),
new THREE.MeshBasicMaterial({
color: 0xf7f1d8,
transparent: true,
opacity: 0.85,
side: THREE.DoubleSide,
depthWrite: false
})
);
selectionRing.rotation.x = -Math.PI / 2;
selectionRing.renderOrder = 5;
scene.add(selectionRing);
let branchPolylines = [];
let patchCenters = [];
let patchProxies = [];
let flowEntries = [];
let particleData = [];
let particleGeometry;
let particlePoints;
let settledParticleCount = 0;
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const projected = new THREE.Vector3();
const orbit = {
yaw: 0.64,
pitch: 0.72,
radius: 84,
target: new THREE.Vector3(0, 0, 0)
};
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function smoothstep(min, max, value) {
const t = clamp((value - min) / (max - min), 0, 1);
return t * t * (3 - 2 * t);
}
function signed(value) {
return `${value >= 0 ? "+" : ""}${value.toFixed(2)} rel.`;
}
function random(index) {
const value = Math.sin(index * 12.9898 + 78.233) * 43758.5453;
return value - Math.floor(value);
}
function disposeObject(object) {
object.traverse((child) => {
if (child.geometry) {
child.geometry.dispose();
}
if (child.material) {
const materials = Array.isArray(child.material)
? child.material
: [child.material];
materials.forEach((material) => material.dispose());
}
});
}
function clearGroup(group) {
while (group.children.length > 0) {
const child = group.children.pop();
disposeObject(child);
}
}
function branchCount() {
if (state.branchDensity < 20) return 1;
if (state.branchDensity < 45) return 2;
if (state.branchDensity < 70) return 3;
return 4;
}
function mainCenter(z) {
return (
3.5 * Math.sin(z * 0.045) +
state.sinuosity * 8 * Math.sin(z * 0.12 + 0.35)
);
}
function mainHalfWidth(z) {
const downstream = smoothstep(-42, 42, z);
return 5.5 + 20 * Math.pow(downstream, 1.38);
}
function makeBranches() {
const definitions = [
{ anchor: -27, endZ: -15, side: -1 },
{ anchor: -10, endZ: 2, side: 1 },
{ anchor: 7, endZ: 19, side: -1 },
{ anchor: 22, endZ: 33, side: 1 }
];
return definitions.slice(0, branchCount()).map((definition, branchIndex) => {
const startX = mainCenter(definition.anchor);
const endX = definition.side * (28 + branchIndex * 1.5);
const bend = definition.side * (8 + state.sinuosity * 7);
const span = definition.endZ - definition.anchor;
const curve = new THREE.CatmullRomCurve3(
[
new THREE.Vector3(startX, 0, definition.anchor),
new THREE.Vector3(
startX + bend * 0.55,
0,
definition.anchor + span * 0.28
),
new THREE.Vector3(
endX * 0.62 + definition.side * state.sinuosity * 3,
0,
definition.endZ - span * 0.22
),
new THREE.Vector3(endX, 0, definition.endZ)
],
false,
"catmullrom",
0.5
);
return {
points: curve.getPoints(24).map((point) => {
point.y = 0;
return point;
}),
side: definition.side
};
});
}
function pointToSegmentDistanceSquared(point, a, b) {
const abX = b.x - a.x;
const abZ = b.z - a.z;
const apX = point.x - a.x;
const apZ = point.z - a.z;
const denominator = abX * abX + abZ * abZ;
const t =
denominator === 0
? 0
: clamp((apX * abX + apZ * abZ) / denominator, 0, 1);
const dx = point.x - (a.x + abX * t);
const dz = point.z - (a.z + abZ * t);
return dx * dx + dz * dz;
}
function distanceToPolyline(point, points) {
let minimum = Infinity;
for (let index = 0; index < points.length - 1; index += 1) {
minimum = Math.min(
minimum,
pointToSegmentDistanceSquared(
point,
points[index],
points[index + 1]
)
);
}
return Math.sqrt(minimum);
}
function terrainHeight(x, z, branches = branchPolylines) {
const center = mainCenter(z);
const halfWidth = mainHalfWidth(z);
const mainDistance = Math.abs(x - center);
let height = -2.25;
if (mainDistance >= halfWidth) {
height =
-2.25 +
3.75 * smoothstep(halfWidth, halfWidth + 5, mainDistance);
}
const noise =
Math.sin(x * 0.31 + z * 0.11) * 0.17 +
Math.cos(z * 0.19 - x * 0.13) * 0.12;
height += noise * smoothstep(halfWidth, halfWidth + 3, mainDistance);
height -= smoothstep(34, 46, z) * 3.5;
branches.forEach((branch) => {
const distance = distanceToPolyline({ x, z }, branch.points);
const blend = smoothstep(
state.branchWidth,
state.branchWidth + 2.2,
distance
);
const carved = THREE.MathUtils.lerp(-1.85, height, blend);
height = Math.min(height, carved);
});
return height;
}
function terrainColor(height, x, z) {
const variation = (Math.sin(x * 0.42 + z * 0.19) + 1) * 0.025;
if (height < 0.08) {
return new THREE.Color("#789794").offsetHSL(0, 0, variation);
}
if (height < 1.0) {
return new THREE.Color("#c0b27e").offsetHSL(0, 0, variation);
}
return new THREE.Color("#7f9069").offsetHSL(
0.01,
variation * 0.5,
variation
);
}
function buildTerrain() {
clearGroup(terrainGroup);
const xSegments = 42;
const zSegments = 66;
const positions = [];
const colors = [];
const indices = [];
for (let zIndex = 0; zIndex <= zSegments; zIndex += 1) {
const z = -45 + (90 * zIndex) / zSegments;
for (let xIndex = 0; xIndex <= xSegments; xIndex += 1) {
const x = -53 + (106 * xIndex) / xSegments;
const height = terrainHeight(x, z);
const color = terrainColor(height, x, z);
positions.push(x, height, z);
colors.push(color.r, color.g, color.b);
}
}
for (let zIndex = 0; zIndex < zSegments; zIndex += 1) {
for (let xIndex = 0; xIndex < xSegments; xIndex += 1) {
const a = zIndex * (xSegments + 1) + xIndex;
const b = a + 1;
const c = a + xSegments + 1;
const d = c + 1;
if ((xIndex + zIndex) % 2 === 0) {
indices.push(a, c, b, b, c, d);
} else {
indices.push(a, d, b, a, 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();
const material = new THREE.MeshStandardMaterial({
vertexColors: true,
flatShading: true,
roughness: 1,
metalness: 0
});
const terrain = new THREE.Mesh(geometry, material);
terrain.receiveShadow = true;
terrainGroup.add(terrain);
}
function ribbonGeometry(points, width) {
const positions = [];
const indices = [];
points.forEach((point, index) => {
const previous = points[Math.max(0, index - 1)];
const next = points[Math.min(points.length - 1, index + 1)];
const tangentX = next.x - previous.x;
const tangentZ = next.z - previous.z;
const length = Math.hypot(tangentX, tangentZ) || 1;
const normalX = -tangentZ / length;
const normalZ = tangentX / length;
const halfWidth = width * 0.5;
positions.push(
point.x + normalX * halfWidth,
0,
point.z + normalZ * halfWidth
);
positions.push(
point.x - normalX * halfWidth,
0,
point.z - normalZ * halfWidth
);
});
for (let index = 0; index < points.length - 1; index += 1) {
const a = index * 2;
const b = a + 1;
const c = a + 2;
const d = a + 3;
indices.push(a, c, b, b, c, d);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
function buildWater() {
clearGroup(waterGroup);
const waterMaterial = new THREE.MeshStandardMaterial({
color: 0x4f9695,
transparent: true,
opacity: 0.84,
depthWrite: false,
roughness: 0.32,
metalness: 0,
side: THREE.DoubleSide,
flatShading: true
});
const mainPoints = [];
for (let z = -44; z <= 45; z += 1.6) {
mainPoints.push(new THREE.Vector3(mainCenter(z), 0, z));
}
const mainWidth =
mainHalfWidth(0) +
0.7 +
state.tide * 2.2;
const mainWater = new THREE.Mesh(
ribbonGeometry(mainPoints, mainWidth),
waterMaterial
);
mainWater.renderOrder = 2;
waterGroup.add(mainWater);
branchPolylines.forEach((branch) => {
const width = state.branchWidth + 0.45 + state.tide * 0.8;
const branchWater = new THREE.Mesh(
ribbonGeometry(branch.points, width),
waterMaterial
);
branchWater.renderOrder = 2;
waterGroup.add(branchWater);
const end = branch.points[branch.points.length - 1];
const pool = new THREE.Mesh(
new THREE.CircleGeometry(width * 0.58, 8),
waterMaterial
);
pool.rotation.x = -Math.PI / 2;
pool.position.set(end.x, 0, end.z);
pool.renderOrder = 2;
waterGroup.add(pool);
});
const bay = new THREE.Mesh(
new THREE.CircleGeometry(1, 48),
waterMaterial
);
bay.rotation.x = -Math.PI / 2;
bay.scale.set(31, 20, 1);
bay.position.set(mainCenter(40), 0, 40);
bay.renderOrder = 1;
waterGroup.add(bay);
waterGroup.position.y = state.tide;
}
function calculatePatchCenters() {
patchCenters = patchDefinitions.map((definition) => {
const x =
mainCenter(definition.z) +
definition.side * (mainHalfWidth(definition.z) + 3.8);
return {
x,
z: definition.z,
y: terrainHeight(x, definition.z)
};
});
}
function buildPatches() {
clearGroup(patchGroup);
patchProxies = [];
calculatePatchCenters();
const trunkGeometry = new THREE.CylinderGeometry(0.15, 0.24, 1.75, 5);
const canopyGeometry = new THREE.IcosahedronGeometry(1.1, 0);
const proxyGeometry = new THREE.SphereGeometry(1, 8, 6);
patchDefinitions.forEach((definition, patchIndex) => {
const coverage = state.coverage[patchIndex];
const center = patchCenters[patchIndex];
const radius = 3 + coverage * 0.045;
const targetCount = coverage === 0
? 0
: Math.max(3, Math.round(coverage * 0.33));
const trees = [];
for (let treeIndex = 0; treeIndex < targetCount; treeIndex += 1) {
const seed = definition.seed * 1000 + treeIndex * 17;
const angle = random(seed) * Math.PI * 2;
const distance = Math.sqrt(random(seed + 1)) * radius;
const x = center.x + Math.cos(angle) * distance;
const z = center.z + Math.sin(angle) * distance * 0.72;
const y = terrainHeight(x, z);
if (y < 0.28) continue;
trees.push({
x,
y,
z,
angle: random(seed + 2) * Math.PI * 2,
scale: 0.76 + random(seed + 3) * 0.44,
tint: random(seed + 4)
});
}
if (trees.length > 0) {
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x6b5842,
flatShading: true,
roughness: 1
});
const canopyMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
flatShading: true,
roughness: 0.95,
vertexColors: true
});
const trunks = new THREE.InstancedMesh(
trunkGeometry,
trunkMaterial,
trees.length
);
const canopies = new THREE.InstancedMesh(
canopyGeometry,
canopyMaterial,
trees.length
);
const transform = new THREE.Object3D();
const color = new THREE.Color(definition.color);
trees.forEach((tree, treeIndex) => {
const maturityScale =
0.48 + state.maturity * 0.72 + tree.tint * 0.12;
transform.position.set(
tree.x,
tree.y + 0.85 * maturityScale,
tree.z
);
transform.rotation.set(0, tree.angle, 0);
transform.scale.set(
tree.scale,
maturityScale,
tree.scale
);
transform.updateMatrix();
trunks.setMatrixAt(treeIndex, transform.matrix);
transform.position.set(
tree.x,
tree.y + (1.65 + state.maturity * 0.75) * maturityScale,
tree.z
);
transform.rotation.set(
random(treeIndex + 50) * 0.25,
tree.angle + 0.4,
random(treeIndex + 70) * 0.18
);
transform.scale.set(
tree.scale * (0.88 + state.maturity * 0.24),
tree.scale * (0.78 + state.maturity * 0.3),
tree.scale * (0.88 + state.maturity * 0.24)
);
transform.updateMatrix();
canopies.setMatrixAt(treeIndex, transform.matrix);
const instanceColor = color
.clone()
.offsetHSL(
(tree.tint - 0.5) * 0.035,
(tree.tint - 0.5) * 0.08,
(tree.tint - 0.5) * 0.12
);
canopies.setColorAt(treeIndex, instanceColor);
});
trunks.instanceMatrix.needsUpdate = true;
canopies.instanceMatrix.needsUpdate = true;
if (canopies.instanceColor) canopies.instanceColor.needsUpdate = true;
patchGroup.add(trunks, canopies);
}
const proxy = new THREE.Mesh(
proxyGeometry,
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
})
);
proxy.scale.setScalar(radius + 1.2);
proxy.position.set(center.x, center.y + 2, center.z);
proxy.userData.patchIndex = patchIndex;
patchGroup.add(proxy);
patchProxies.push(proxy);
});
buildHalos();
}
function buildHalos() {
clearGroup(haloGroup);
patchCenters.forEach((center, patchIndex) => {
const coverage = state.coverage[patchIndex];
if (coverage === 0) return;
const radius = 3 + coverage * 0.045;
const halo = new THREE.Mesh(
new THREE.RingGeometry(radius * 0.72, radius, 24),
new THREE.MeshBasicMaterial({
color: 0xd1a051,
transparent: true,
opacity: 0.19,
side: THREE.DoubleSide,
depthWrite: false
})
);
halo.rotation.x = -Math.PI / 2;
halo.position.set(center.x, center.y + 0.13, center.z);
halo.renderOrder = 4;
halo.userData.baseRadius = radius;
haloGroup.add(halo);
});
}
function habitatScore(patchIndex) {
const coverage = state.coverage[patchIndex];
const center = patchCenters[patchIndex];
let nearestBranch = Infinity;
branchPolylines.forEach((branch) => {
nearestBranch = Math.min(
nearestBranch,
distanceToPolyline(center, branch.points)
);
});
const nearby = nearestBranch < state.branchWidth + 6;
return clamp(
Math.round(
coverage * 0.58 +
state.branchDensity * 0.22 +
state.branchWidth * 2.5 +
(nearby ? 8 : 0)
),
0,
100
);
}
function retentionScore(patchIndex) {
const coverage = state.coverage[patchIndex];
const center = patchCenters[patchIndex];
let nearestBranch = Infinity;
branchPolylines.forEach((branch) => {
nearestBranch = Math.min(
nearestBranch,
distanceToPolyline(center, branch.points)
);
});
const nearChannel = nearestBranch < state.branchWidth + 5;
return clamp(
Math.round(
coverage * 0.7 +
(nearChannel ? 17 : 7) +
state.maturity * 5
),
0,
100
);
}
function channelRelationship(patchIndex) {
const center = patchCenters[patchIndex];
let nearest = Infinity;
branchPolylines.forEach((branch) => {
nearest = Math.min(
nearest,
distanceToPolyline(center, branch.points)
);
});
if (nearest < state.branchWidth + 4) return "Directly adjacent";
if (nearest < state.branchWidth + 10) return "Nearby";
return "Separated";
}
function buildLinks() {
clearGroup(linksGroup);
calculatePatchCenters();
const source = new THREE.Vector3(
mainCenter(-39),
terrainHeight(mainCenter(-39), -39) + 2.7,
-39
);
const refuge = new THREE.Vector3(
mainCenter(38),
terrainHeight(mainCenter(38), 38) + 2.7,
38
);
const nodes = [
source,
...patchCenters.map(
(center) => new THREE.Vector3(center.x, center.y + 2.7, center.z)
),
refuge
];
for (let index = 0; index < nodes.length - 1; index += 1) {
const start = nodes[index];
const end = nodes[index + 1];
const control = start.clone().add(end).multiplyScalar(0.5);
control.y = Math.max(start.y, end.y) + 2.1;
control.x += index % 2 === 0 ? 1.2 : -1.2;
const curve = new THREE.QuadraticBezierCurve3(start, control, end);
const points = curve.getPoints(24);
const patchA = clamp(index - 1, 0, patchDefinitions.length - 1);
const patchB = clamp(index, 0, patchDefinitions.length - 1);
const score =
(habitatScore(patchA) + habitatScore(patchB)) * 0.5;
const color =
score > 65
? new THREE.Color("#4f8264")
: new THREE.Color("#b68c45");
const line = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(points),
new THREE.LineDashedMaterial({
color,
transparent: true,
opacity: 0.82,
dashSize: 1.05,
gapSize: 0.62,
depthWrite: false
})
);
line.computeLineDistances();
line.renderOrder = 4;
linksGroup.add(line);
}
nodes.forEach((node, index) => {
const marker = new THREE.Mesh(
new THREE.OctahedronGeometry(index === 0 || index === nodes.length - 1
? 0.8
: 0.58, 0),
new THREE.MeshBasicMaterial({
color:
index === 0 || index === nodes.length - 1
? 0xd1a052
: 0xf2efda,
transparent: true,
opacity: 0.92
})
);
marker.position.copy(node);
marker.renderOrder = 5;
linksGroup.add(marker);
});
linksGroup.visible = state.links;
}
function buildFlow() {
clearGroup(flowGroup);
flowEntries = [];
for (let index = 0; index < 9; index += 1) {
const z = -35 + index * 8.6;
const arrow = new THREE.ArrowHelper(
new THREE.Vector3(0, 0, 1),
new THREE.Vector3(mainCenter(z), state.tide + 0.25, z),
2.8,
0xc5f0e5,
0.75,
0.55
);
arrow.line.material.transparent = true;
arrow.line.material.opacity = 0.82;
arrow.cone.material.transparent = true;
arrow.cone.material.opacity = 0.9;
arrow.renderOrder = 4;
arrow.userData.baseZ = z;
arrow.userData.phase = index * 0.73;
arrow.userData.main = true;
flowGroup.add(arrow);
flowEntries.push(arrow);
}
branchPolylines.forEach((branch, branchIndex) => {
const pointIndex = Math.floor(branch.points.length * 0.64);
const point = branch.points[pointIndex];
const previous = branch.points[Math.max(0, pointIndex - 1)];
const next = branch.points[Math.min(branch.points.length - 1, pointIndex + 1)];
const direction = next.clone().sub(previous).normalize();
const arrow = new THREE.ArrowHelper(
direction,
new THREE.Vector3(point.x, state.tide + 0.25, point.z),
2.4,
0xc5f0e5,
0.65,
0.48
);
arrow.line.material.transparent = true;
arrow.line.material.opacity = 0.75;
arrow.cone.material.transparent = true;
arrow.cone.material.opacity = 0.88;
arrow.userData.main = false;
arrow.userData.branchIndex = branchIndex;
flowGroup.add(arrow);
flowEntries.push(arrow);
});
flowGroup.visible = state.flow;
}
function initializeParticles() {
const count = 220;
const positions = new Float32Array(count * 3);
const colors = new Float32Array(count * 3);
const suspendedColor = new THREE.Color("#d5a34f");
const settledColor = new THREE.Color("#8e7142");
particleData = [];
for (let index = 0; index < count; index += 1) {
const z = -42 + random(index * 3 + 1) * 80;
const lane = (random(index * 3 + 2) - 0.5) * 1.6;
const x = mainCenter(z) + lane * mainHalfWidth(z) * 0.82;
let nearestPatch = 0;
let nearestDistance = Infinity;
patchCenters.forEach((center, patchIndex) => {
const distance = Math.abs(center.z - z);
if (distance < nearestDistance) {
nearestDistance = distance;
nearestPatch = patchIndex;
}
});
particleData.push({
z,
x,
lane,
speed: 0.55 + random(index * 3 + 3) * 0.9,
patchIndex: nearestPatch,
captureRoll: random(index * 7 + 11),
offset: (random(index * 7 + 12) - 0.5) * 3.4,
mode: "moving",
t: 0,
sx: x,
sz: z,
sy: state.tide + 0.16,
tx: x,
tz: z,
ty: state.tide + 0.16
});
positions[index * 3] = x;
positions[index * 3 + 1] = state.tide + 0.16;
positions[index * 3 + 2] = z;
colors[index * 3] = suspendedColor.r;
colors[index * 3 + 1] = suspendedColor.g;
colors[index * 3 + 2] = suspendedColor.b;
}
particleGeometry = new THREE.BufferGeometry();
particleGeometry.setAttribute(
"position",
new THREE.BufferAttribute(positions, 3)
);
particleGeometry.setAttribute(
"color",
new THREE.BufferAttribute(colors, 3)
);
particlePoints = new THREE.Points(
particleGeometry,
new THREE.PointsMaterial({
size: 0.34,
vertexColors: true,
transparent: true,
opacity: 0.88,
depthWrite: false,
sizeAttenuation: true
})
);
particlePoints.frustumCulled = false;
particlePoints.renderOrder = 6;
sedimentGroup.add(particlePoints);
settledParticleCount = 0;
}
function resetParticle(particle, index) {
particle.z = -43 - random(index * 11) * 4;
particle.lane = (random(index * 13 + 4) - 0.5) * 1.6;
particle.x =
mainCenter(particle.z) +
particle.lane * mainHalfWidth(particle.z) * 0.82;
particle.mode = "moving";
particle.t = 0;
particle.speed = 0.55 + random(index * 3 + 3) * 0.9;
particle.captureRoll = random(index * 7 + 11);
}
function currentWaterLevel() {
if (!state.pulsing) return state.tide;
const elapsed = (performance.now() - state.pulseStarted) / 1000;
const progress = clamp(elapsed / 10, 0, 1);
return state.tide + Math.sin(progress * Math.PI) * 0.38;
}
function updateParticles(delta) {
if (!particleGeometry) return;
const positions = particleGeometry.attributes.position.array;
const colors = particleGeometry.attributes.color.array;
const suspendedColor = new THREE.Color("#d5a34f");
const settledColor = new THREE.Color("#8e7142");
const level = currentWaterLevel();
let settled = 0;
let colorsChanged = false;
particleData.forEach((particle, index) => {
if (particle.mode === "settled") {
settled += 1;
return;
}
if (particle.mode === "settling") {
particle.t += delta * (0.48 + Math.max(0, level) * 0.75);
const t = clamp(particle.t, 0, 1);
particle.x = THREE.MathUtils.lerp(particle.sx, particle.tx, t);
particle.z = THREE.MathUtils.lerp(particle.sz, particle.tz, t);
particle.y = THREE.MathUtils.lerp(particle.sy, particle.ty, t);
if (t >= 1) {
particle.mode = "settled";
settled += 1;
colors[index * 3] = settledColor.r;
colors[index * 3 + 1] = settledColor.g;
colors[index * 3 + 2] = settledColor.b;
colorsChanged = true;
}
} else {
particle.z += delta * (1.1 + Math.max(0, level) * 1.65) * particle.speed;
particle.x =
mainCenter(particle.z) +
particle.lane * mainHalfWidth(particle.z) * 0.82;
particle.y = level + 0.16;
const patch = patchCenters[particle.patchIndex];
const definition = patchDefinitions[particle.patchIndex];
const sideMatches = Math.sign(particle.lane) === definition.side;
const inCaptureZone =
particle.z > patch.z - 3.2 && particle.z < patch.z + 3.2;
if (
sideMatches &&
inCaptureZone &&
particle.captureRoll <
(state.coverage[particle.patchIndex] / 100) * 0.78
) {
particle.mode = "settling";
particle.t = 0;
particle.sx = particle.x;
particle.sz = particle.z;
particle.sy = particle.y;
particle.tx = patch.x - definition.side * 2.4;
particle.tz = patch.z + particle.offset;
particle.ty = terrainHeight(particle.tx, particle.tz) + 0.24;
} else if (particle.z > 44) {
resetParticle(particle, index);
}
}
positions[index * 3] = particle.x;
positions[index * 3 + 1] = particle.y;
positions[index * 3 + 2] = particle.z;
if (particle.mode === "moving") {
colors[index * 3] = suspendedColor.r;
colors[index * 3 + 1] = suspendedColor.g;
colors[index * 3 + 2] = suspendedColor.b;
colorsChanged = true;
}
});
particleGeometry.attributes.position.needsUpdate = true;
if (colorsChanged) {
particleGeometry.attributes.color.needsUpdate = true;
}
settledParticleCount = settled;
}
function updateFlow(time) {
const level = currentWaterLevel();
flowEntries.forEach((arrow) => {
if (arrow.userData.main) {
const baseZ = arrow.userData.baseZ;
const z =
((baseZ + time * 1.25 + arrow.userData.phase + 44) % 88) - 44;
const x = mainCenter(z);
const direction = new THREE.Vector3(
mainCenter(z + 0.2) - mainCenter(z - 0.2),
0,
0.4
).normalize();
arrow.position.set(x, level + 0.25, z);
arrow.setDirection(direction);
} else {
arrow.position.y = level + 0.25;
}
});
}
function updateSelection(time) {
const patchIndex = state.selectedPatch;
const center = patchCenters[patchIndex];
if (!center) return;
const radius = 3.8 + state.coverage[patchIndex] * 0.05;
selectionRing.position.set(center.x, center.y + 0.18, center.z);
selectionRing.scale.setScalar(radius * (1 + Math.sin(time * 2) * 0.018));
selectionRing.material.opacity = 0.62 + Math.sin(time * 2) * 0.16;
}
function updateHaloAnimation(time) {
haloGroup.children.forEach((halo, index) => {
const pulse = 1 + Math.sin(time * 1.8 + index * 0.8) * 0.025;
halo.scale.setScalar(pulse);
halo.material.opacity =
0.14 + Math.sin(time * 1.8 + index * 0.8) * 0.045;
});
}
function updateInfo() {
const patchIndex = state.selectedPatch;
const definition = patchDefinitions[patchIndex];
const habitat = habitatScore(patchIndex);
const retention = retentionScore(patchIndex);
const relationship = channelRelationship(patchIndex);
$("patchTitle").textContent = definition.name;
$("patchSubtitle").textContent = "Relative illustration metrics";
$("patchCoverage").textContent = `${state.coverage[patchIndex]}%`;
$("patchHabitat").textContent = `${habitat} / 100`;
$("patchRetention").textContent = `${retention} / 100`;
$("patchChannel").textContent = relationship;
$("patchHabitatBar").style.width = `${habitat}%`;
$("patchRetentionBar").style.width = `${retention}%`;
if (habitat > 70) {
$("patchNote").textContent =
"The dashed network indicates a comparatively continuous illustrative route through the channel-and-patch sequence.";
} else if (habitat > 45) {
$("patchNote").textContent =
"This patch has a partial illustrative link to the network; gaps in adjacent vegetation or channel continuity remain visible.";
} else {
$("patchNote").textContent =
"The diagram shows a relatively isolated patch, useful for exploring how nearby channels and adjacent planting affect connectivity.";
}
}
function updateReadout() {
const average =
state.coverage.reduce((sum, value) => sum + value, 0) /
state.coverage.length;
const overallLink = clamp(
Math.round(
average * 0.55 +
branchCount() * 6 +
state.branchWidth * 4
),
0,
100
);
$("linkScore").textContent = `${overallLink}/100`;
$("tracerReadout").textContent =
`${settledParticleCount}/${particleData.length || 220}`;
$("channelReadout").textContent = `${branchCount()} / 4`;
}
function updateLabels() {
patchCenters.forEach((center, index) => {
const label = document.querySelector(`[data-patch-label="${index}"]`);
if (!label) return;
projected.set(center.x, center.y + 4.4, center.z).project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.2 &&
Math.abs(projected.y) < 1.2;
label.style.display = visible && state.labels ? "block" : "none";
if (visible) {
const x = (projected.x * 0.5 + 0.5) * window.innerWidth;
const y = (-projected.y * 0.5 + 0.5) * window.innerHeight;
label.style.left = `${x}px`;
label.style.top = `${y}px`;
}
});
}
function selectPatch(index) {
state.selectedPatch = index;
document.querySelectorAll("[data-patch-label]").forEach((label) => {
label.classList.toggle(
"selected",
Number(label.dataset.patchLabel) === index
);
});
updateInfo();
}
function buildPatchUI() {
const controls = $("patchControls");
const labels = $("labels");
patchDefinitions.forEach((definition, index) => {
const control = document.createElement("div");
control.className = "patch-row";
control.innerHTML = `
<div class="control-line">
<label class="patch-name" for="patchRange${index}">
<span class="patch-swatch" style="--swatch:${definition.color}"></span>
${definition.name}
</label>
<output id="patchOutput${index}" for="patchRange${index}"></output>
</div>
<input
id="patchRange${index}"
type="range"
min="0"
max="100"
step="1"
value="${state.coverage[index]}"
/>
`;
controls.appendChild(control);
const range = control.querySelector("input");
const output = control.querySelector("output");
const updateOutput = () => {
output.textContent = `${range.value}% cover`;
const percent = ((range.value - range.min) / (range.max - range.min)) * 100;
range.style.setProperty("--range-fill", `${percent}%`);
};
updateOutput();
range.addEventListener("input", () => {
state.coverage[index] = Number(range.value);
updateOutput();
buildPatches();
buildLinks();
updateInfo();
updateReadout();
});
const label = document.createElement("button");
label.type = "button";
label.className = "map-label";
label.dataset.patchLabel = String(index);
label.innerHTML = `
<strong>${definition.name}</strong>
<small>${state.coverage[index]}% planting coverage</small>
`;
label.addEventListener("pointerdown", (event) => event.stopPropagation());
label.addEventListener("click", () => selectPatch(index));
labels.appendChild(label);
});
}
function updateRangeOutput(input, output, formatter) {
output.textContent = formatter(Number(input.value));
const percent =
((Number(input.value) - Number(input.min)) /
(Number(input.max) - Number(input.min))) *
100;
input.style.setProperty("--range-fill", `${percent}%`);
}
function rebuildLandscape() {
branchPolylines = makeBranches();
buildTerrain();
buildWater();
buildPatches();
buildLinks();
buildFlow();
updateInfo();
updateReadout();
}
function bindControls() {
const tide = $("tideRange");
const sinuosity = $("sinuosityRange");
const density = $("branchDensityRange");
const width = $("branchWidthRange");
const maturity = $("maturityRange");
updateRangeOutput(tide, $("tideOutput"), signed);
updateRangeOutput(
sinuosity,
$("sinuosityOutput"),
(value) => `${Math.round(value * 100)}%`
);
updateRangeOutput(
density,
$("branchDensityOutput"),
() => `${branchCount()} / 4`
);
updateRangeOutput(
width,
$("branchWidthOutput"),
(value) => `${value.toFixed(1)}×`
);
updateRangeOutput(
maturity,
$("maturityOutput"),
(value) => `${Math.round(value * 100)}% established`
);
tide.addEventListener("input", () => {
state.tide = Number(tide.value);
updateRangeOutput(tide, $("tideOutput"), signed);
buildWater();
});
sinuosity.addEventListener("input", () => {
state.sinuosity = Number(sinuosity.value);
updateRangeOutput(
sinuosity,
$("sinuosityOutput"),
(value) => `${Math.round(value * 100)}%`
);
rebuildLandscape();
});
density.addEventListener("input", () => {
state.branchDensity = Number(density.value);
updateRangeOutput(
density,
$("branchDensityOutput"),
() => `${branchCount()} / 4`
);
rebuildLandscape();
});
width.addEventListener("input", () => {
state.branchWidth = Number(width.value);
updateRangeOutput(
width,
$("branchWidthOutput"),
(value) => `${value.toFixed(1)}×`
);
rebuildLandscape();
});
maturity.addEventListener("input", () => {
state.maturity = Number(maturity.value);
updateRangeOutput(
maturity,
$("maturityOutput"),
(value) => `${Math.round(value * 100)}% established`
);
buildPatches();
buildLinks();
updateInfo();
});
$("linksToggle").addEventListener("change", (event) => {
state.links = event.target.checked;
linksGroup.visible = state.links;
});
$("sedimentToggle").addEventListener("change", (event) => {
state.sediment = event.target.checked;
sedimentGroup.visible = state.sediment;
});
$("flowToggle").addEventListener("change", (event) => {
state.flow = event.target.checked;
flowGroup.visible = state.flow;
});
$("labelsToggle").addEventListener("change", (event) => {
state.labels = event.target.checked;
});
$("overviewButton").addEventListener("click", () => {
orbit.yaw = 0.64;
orbit.pitch = 0.72;
orbit.radius = 84;
orbit.target.set(0, 0, 0);
});
$("planButton").addEventListener("click", () => {
orbit.yaw = 0;
orbit.pitch = 1.46;
orbit.radius = 91;
orbit.target.set(0, 0, 0);
});
$("pulseButton").addEventListener("click", () => {
state.pulsing = true;
state.pulseStarted = performance.now();
$("pulseButton").classList.add("active");
$("pulseButton").textContent = "Tide pulse active";
});
$("panelToggle").addEventListener("click", () => {
const open = document.body.classList.toggle("controls-open");
$("panelToggle").setAttribute("aria-expanded", String(open));
});
}
function updateCamera() {
const spherical = new THREE.Spherical(
orbit.radius,
orbit.pitch,
orbit.yaw
);
camera.position.setFromSpherical(spherical).add(orbit.target);
camera.lookAt(orbit.target);
}
function raycastPatch(clientX, clientY) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(patchProxies, false);
if (hits.length > 0) {
selectPatch(hits[0].object.userData.patchIndex);
}
}
function setupCameraControls() {
const canvas = renderer.domElement;
let pointerDown = false;
let panning = false;
let moved = 0;
let previousX = 0;
let previousY = 0;
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
pointerDown = true;
panning = event.button === 2 || event.shiftKey;
moved = 0;
previousX = event.clientX;
previousY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!pointerDown) {
raycastPatch(event.clientX, event.clientY);
return;
}
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
moved += Math.abs(dx) + Math.abs(dy);
previousX = event.clientX;
previousY = event.clientY;
if (panning) {
const scale = orbit.radius * 0.0012;
orbit.target.x -= dx * scale;
orbit.target.z += dy * scale;
orbit.target.x = clamp(orbit.target.x, -35, 35);
orbit.target.z = clamp(orbit.target.z, -35, 35);
} else {
orbit.yaw -= dx * 0.006;
orbit.pitch = clamp(orbit.pitch + dy * 0.005, 0.24, 1.49);
}
});
canvas.addEventListener("pointerup", (event) => {
if (pointerDown && moved < 6 && event.button !== 2) {
raycastPatch(event.clientX, event.clientY);
}
pointerDown = false;
panning = false;
});
canvas.addEventListener("pointercancel", () => {
pointerDown = false;
panning = false;
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = clamp(
orbit.radius + event.deltaY * 0.055,
34,
132
);
},
{ passive: false }
);
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", resize);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
const time = performance.now() / 1000;
if (state.pulsing) {
const pulseElapsed = (performance.now() - state.pulseStarted) / 1000;
if (pulseElapsed > 10) {
state.pulsing = false;
$("pulseButton").classList.remove("active");
$("pulseButton").textContent = "Run tide pulse";
}
}
updateCamera();
waterGroup.position.y = currentWaterLevel();
updateFlow(time);
updateParticles(delta);
updateSelection(time);
updateHaloAnimation(time);
updateLabels();
if (Math.floor(elapsed * 2) !== Math.floor((elapsed - delta) * 2)) {
updateReadout();
}
renderer.render(scene, camera);
}
buildPatchUI();
bindControls();
rebuildLandscape();
initializeParticles();
setupCameraControls();
selectPatch(state.selectedPatch);
updateReadout();
animate();
</script>
</body>
</html>
```