Prompt specification
Build or customize the Three.js 3D scene "Blocked Drain Counterfactual Neighborhood" 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: Blocked Drain Counterfactual Neighborhood
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/blocked-drain-counterfactual-neighborhood-x3984
Scene Description Prompt:
Block a drain in a voxel neighborhood's toy runoff model; compare accumulation and alternate water paths under stated assumptions. Three.js from cdnjs, standalone HTML.
Working Three.js Starter (blocked-drain-counterfactual-neighborhood-x3984):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Runoff — Blocked Drain Study</title>
<style>
:root {
--bg: #07131c;
--panel: rgba(11, 26, 38, 0.88);
--panel-edge: rgba(150, 205, 230, 0.16);
--text: #e8f5fb;
--muted: #91a8b6;
--cyan: #49d7f5;
--orange: #ffb547;
--green: #51dfad;
--purple: #ae8cff;
--red: #ff6277;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
canvas {
display: block;
touch-action: none;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--panel-edge);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.brand {
top: 18px;
left: 18px;
width: 340px;
padding: 15px 17px;
pointer-events: none;
}
.eyebrow {
margin-bottom: 5px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 21px;
line-height: 1.15;
letter-spacing: -0.025em;
}
.subtitle {
margin-top: 7px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
#controls {
top: 118px;
left: 18px;
width: 340px;
max-height: calc(100vh - 138px);
padding: 16px;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: #355064 transparent;
}
.section-title {
margin: 0 0 10px;
color: #cfe3ed;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.status-row,
.button-row,
.check-row {
display: flex;
align-items: center;
gap: 9px;
}
.status-row {
justify-content: space-between;
margin-bottom: 12px;
}
.status {
display: inline-flex;
align-items: center;
gap: 7px;
color: var(--muted);
font-size: 12px;
}
.status::before {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 13px rgba(81, 223, 173, 0.8);
content: "";
}
.status.blocked::before {
background: var(--red);
box-shadow: 0 0 13px rgba(255, 98, 119, 0.85);
}
button {
border: 1px solid rgba(160, 210, 235, 0.2);
border-radius: 10px;
padding: 10px 12px;
background: rgba(255, 255, 255, 0.055);
color: var(--text);
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition: 160ms ease;
}
button:hover {
border-color: rgba(160, 220, 245, 0.45);
background: rgba(255, 255, 255, 0.1);
transform: translateY(-1px);
}
button:focus-visible,
input:focus-visible,
summary:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 3px;
}
#blockButton {
width: 100%;
border-color: rgba(255, 98, 119, 0.35);
background: rgba(255, 98, 119, 0.13);
color: #ffd5db;
}
#blockButton.blocked {
border-color: rgba(255, 181, 71, 0.38);
background: rgba(255, 181, 71, 0.14);
color: #ffe5b8;
}
.control {
margin-top: 17px;
}
.control label {
display: flex;
justify-content: space-between;
margin-bottom: 8px;
color: #c8dce7;
font-size: 12px;
}
.control output {
color: var(--cyan);
font-weight: 800;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
.check-row {
margin-top: 13px;
color: var(--muted);
font-size: 12px;
user-select: none;
}
input[type="checkbox"] {
accent-color: var(--cyan);
}
.divider {
height: 1px;
margin: 16px 0;
background: rgba(170, 210, 230, 0.11);
}
.stat-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.stat {
min-height: 72px;
padding: 11px;
border: 1px solid rgba(160, 210, 235, 0.1);
border-radius: 11px;
background: rgba(255, 255, 255, 0.035);
}
.stat .label {
color: var(--muted);
font-size: 10px;
line-height: 1.3;
text-transform: uppercase;
letter-spacing: 0.07em;
}
.stat .value {
margin-top: 7px;
font-size: 20px;
font-weight: 800;
letter-spacing: -0.03em;
}
.stat .unit {
color: var(--muted);
font-size: 11px;
font-weight: 500;
}
.stat.highlight .value { color: var(--orange); }
.stat.cyan .value { color: var(--cyan); }
.chart {
margin-top: 13px;
}
.chart-row {
margin-bottom: 10px;
}
.chart-head {
display: flex;
justify-content: space-between;
margin-bottom: 4px;
color: #c7dbe6;
font-size: 11px;
}
.chart-head strong {
color: var(--text);
font-size: 11px;
}
.bar-track {
position: relative;
height: 15px;
margin-top: 3px;
overflow: hidden;
border-radius: 5px;
background: rgba(255, 255, 255, 0.055);
}
.bar {
position: absolute;
inset: 0 auto 0 0;
min-width: 0;
border-radius: 5px;
transition: width 280ms ease;
}
.bar.baseline {
background: linear-gradient(90deg, #279fc0, var(--cyan));
}
.bar.blocked {
background: linear-gradient(90deg, #d78027, var(--orange));
}
.chart-key {
display: flex;
gap: 15px;
margin-top: 9px;
color: var(--muted);
font-size: 10px;
}
.chart-key span::before {
display: inline-block;
width: 12px;
height: 3px;
margin-right: 5px;
border-radius: 3px;
vertical-align: middle;
background: var(--cyan);
content: "";
}
.chart-key span:last-child::before {
background: var(--orange);
}
.note {
margin-top: 12px;
padding: 10px;
border-left: 2px solid var(--orange);
border-radius: 0 7px 7px 0;
background: rgba(255, 181, 71, 0.065);
color: #cbd8df;
font-size: 11px;
line-height: 1.45;
}
#legend {
top: 18px;
right: 18px;
width: 235px;
padding: 13px 15px;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
margin-top: 8px;
color: #bdd0db;
font-size: 11px;
}
.swatch {
width: 18px;
height: 3px;
border-radius: 3px;
background: var(--cyan);
box-shadow: 0 0 8px currentColor;
}
.swatch.orange { background: var(--orange); }
.swatch.purple { background: var(--purple); }
.swatch.green { background: var(--green); }
.swatch.red { background: var(--red); }
#assumptions {
right: 18px;
bottom: 18px;
width: 365px;
max-height: 48vh;
padding: 13px 15px;
overflow: auto;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
#assumptions summary {
color: #d7e8f0;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
}
#assumptions ol {
margin: 12px 0 0;
padding-left: 19px;
}
#assumptions li {
margin-bottom: 7px;
}
#viewControls {
position: fixed;
z-index: 10;
bottom: 18px;
left: 50%;
display: flex;
gap: 7px;
padding: 7px;
border: 1px solid var(--panel-edge);
border-radius: 13px;
background: var(--panel);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.35);
transform: translateX(-50%);
}
#viewControls button {
padding: 8px 10px;
background: transparent;
}
.map-label {
position: fixed;
z-index: 6;
min-width: 92px;
padding: 6px 8px;
border: 1px solid rgba(160, 220, 245, 0.25);
border-radius: 8px;
background: rgba(7, 19, 28, 0.82);
box-shadow: 0 6px 22px rgba(0, 0, 0, 0.25);
color: #dff4fb;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.07em;
line-height: 1.35;
text-align: center;
text-transform: uppercase;
pointer-events: none;
transform: translate(-50%, -100%);
white-space: nowrap;
}
.map-label span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
font-weight: 600;
letter-spacing: 0;
text-transform: none;
}
#toast {
position: fixed;
z-index: 30;
bottom: 84px;
left: 50%;
padding: 9px 13px;
border: 1px solid rgba(160, 220, 245, 0.25);
border-radius: 9px;
background: rgba(7, 19, 28, 0.94);
color: #dff4fb;
font-size: 12px;
opacity: 0;
pointer-events: none;
transform: translate(-50%, 8px);
transition: 180ms ease;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
#loading {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
background: var(--bg);
color: var(--cyan);
font-size: 12px;
letter-spacing: 0.12em;
text-transform: uppercase;
transition: opacity 350ms ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 820px) {
.brand {
width: calc(100vw - 36px);
}
#controls {
top: auto;
bottom: 76px;
width: calc(100vw - 36px);
max-height: 48vh;
}
#legend {
top: 118px;
right: 18px;
width: 185px;
}
#assumptions {
display: none;
}
#viewControls {
left: 18px;
transform: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<header class="panel brand">
<div class="eyebrow">Neighborhood Water Lab</div>
<h1>Voxel Runoff: Blocked Drain</h1>
<div class="subtitle">
Compare storm capture, sump accumulation, and modeled overflow routes in a
16 × 16 voxel neighborhood.
</div>
</header>
<section class="panel" id="controls">
<div class="section-title">Scenario</div>
<div class="status-row">
<div class="status" id="statusText">Main drain open</div>
<button id="blockButton">⊘ Block main drain</button>
</div>
<div class="control">
<label for="rainDepth">
Uniform storm depth
<output id="rainOutput">24 mm</output>
</label>
<input id="rainDepth" type="range" min="8" max="45" step="1" value="24">
</div>
<div class="check-row">
<input id="showPaths" type="checkbox" checked>
<label for="showPaths">Show comparison routes</label>
</div>
<div class="check-row">
<input id="showRain" type="checkbox" checked>
<label for="showRain">Show animated rainfall</label>
</div>
<div class="divider"></div>
<div class="section-title">Storm Balance</div>
<div class="stat-grid">
<div class="stat cyan">
<div class="label">Total storm input</div>
<div class="value"><span id="totalVolume">614</span> <span class="unit">m³</span></div>
</div>
<div class="stat">
<div class="label">Main drain: open</div>
<div class="value"><span id="openMain">0</span> <span class="unit">m³</span></div>
</div>
<div class="stat highlight">
<div class="label">Blocked sump storage</div>
<div class="value"><span id="storedVolume">0</span> <span class="unit">m³</span></div>
</div>
<div class="stat highlight">
<div class="label">Emergency overflow</div>
<div class="value"><span id="overflowVolume">0</span> <span class="unit">m³</span></div>
</div>
</div>
<div class="divider"></div>
<div class="section-title">Drain Capture Comparison</div>
<div class="chart">
<div class="chart-row">
<div class="chart-head">
<span>Main drain</span>
<strong><span id="mainBaseText">0</span> → <span id="mainBlockedText">0</span> m³</strong>
</div>
<div class="bar-track"><div class="bar baseline" id="mainBaseBar"></div></div>
<div class="bar-track"><div class="bar blocked" id="mainBlockedBar"></div></div>
</div>
<div class="chart-row">
<div class="chart-head">
<span>East drain</span>
<strong><span id="eastBaseText">0</span> → <span id="eastBlockedText">0</span> m³</strong>
</div>
<div class="bar-track"><div class="bar baseline" id="eastBaseBar"></div></div>
<div class="bar-track"><div class="bar blocked" id="eastBlockedBar"></div></div>
</div>
<div class="chart-row">
<div class="chart-head">
<span>North drain</span>
<strong><span id="northBaseText">0</span> → <span id="northBlockedText">0</span> m³</strong>
</div>
<div class="bar-track"><div class="bar baseline" id="northBaseBar"></div></div>
<div class="bar-track"><div class="bar blocked" id="northBlockedBar"></div></div>
</div>
<div class="chart-key">
<span>Open baseline</span>
<span>Blocked scenario</span>
</div>
</div>
<div class="note" id="scenarioNote"></div>
</section>
<aside class="panel" id="legend">
<div class="section-title">Route Key</div>
<div class="legend-row"><i class="swatch"></i>Open baseline → main</div>
<div class="legend-row"><i class="swatch purple"></i>Open baseline → east</div>
<div class="legend-row"><i class="swatch green"></i>Open baseline → north</div>
<div class="legend-row"><i class="swatch orange"></i>Blocked overflow route</div>
<div class="legend-row"><i class="swatch red"></i>Blocked drain</div>
</aside>
<details class="panel" id="assumptions">
<summary>Model assumptions & limits</summary>
<ol>
<li>
The board is a 16 × 16 grid. Each voxel parcel represents 100 m².
Uniform rainfall is applied once to every parcel, including rooftops.
</li>
<li>
Roof rain is transferred instantly to the lowest adjacent passable parcel.
There is no detention, infiltration, evaporation, sewer surcharge, or
rainfall timing.
</li>
<li>
Water uses least-cost open-channel routing over unoccupied parcels.
Moving one parcel costs 1 + 18 × uphill height + 0.55 × downhill
height. The toy routing ignores momentum and pipe hydraulics.
</li>
<li>
The blocked main sump stores up to 45 m³. Additional water follows the
least-cost modeled emergency path from the sump to one alternate drain.
The other drains retain their open-baseline catchments.
</li>
<li>
The comparison uses the same storm in both scenarios and preserves
total volume. This is an explanatory neighborhood model, not an
engineering drainage forecast.
</li>
</ol>
</details>
<div id="viewControls">
<button id="orbitView" title="Reset oblique camera">Oblique</button>
<button id="topView" title="Top-down camera">Top</button>
<button id="zoomIn" title="Zoom in">+</button>
<button id="zoomOut" title="Zoom out">-</button>
</div>
<div class="map-label" id="label-main">Main drain<span>0 m³</span></div>
<div class="map-label" id="label-east">East drain<span>0 m³</span></div>
<div class="map-label" id="label-north">North drain<span>0 m³</span></div>
<div id="toast"></div>
<div id="loading">Building neighborhood model…</div>
<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 N = 16;
const HALF = (N - 1) / 2;
const PARCEL_AREA = 100;
const SUMP_CAPACITY = 45;
const COLORS = {
cyan: 0x49d7f5,
orange: 0xffb547,
green: 0x51dfad,
purple: 0xae8cff,
red: 0xff6277
};
const state = {
rainMm: 24,
blocked: true,
showPaths: true,
showRain: true
};
const drainDefs = [
{ id: "main", name: "Main drain", index: 15 * N + 2, color: COLORS.cyan },
{ id: "east", name: "East drain", index: 11 * N + 14, color: COLORS.purple },
{ id: "north", name: "North drain", index: 2 * N + 8, color: COLORS.green }
];
function mulberry32(seed) {
return function () {
let t = seed += 0x6D2B79F5;
t = Math.imul(t ^ t >>> 15, t | 1);
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
return ((t ^ t >>> 14) >>> 0) / 4294967296;
};
}
const random = mulberry32(73421);
const terrain = new Float32Array(N * N);
const land = new Array(N * N);
const occupied = new Uint8Array(N * N);
const buildingLevels = new Uint8Array(N * N);
function worldX(x) { return x - HALF; }
function worldZ(z) { return z - HALF; }
function cellIndex(x, z) { return z * N + x; }
function cellX(index) { return index % N; }
function cellZ(index) { return Math.floor(index / N); }
function segmentDistance(px, pz, ax, az, bx, bz) {
const vx = bx - ax;
const vz = bz - az;
const wx = px - ax;
const wz = pz - az;
const t = Math.max(0, Math.min(1,
(wx * vx + wz * vz) / Math.max(0.0001, vx * vx + vz * vz)
));
const dx = px - (ax + t * vx);
const dz = pz - (az + t * vz);
return Math.hypot(dx, dz);
}
function isPark(x, z) {
return (
(x >= 10 && x <= 13 && z >= 3 && z <= 6) ||
(x >= 2 && x <= 5 && z >= 10 && z <= 13)
);
}
function isRoad(x, z) {
return x === 7 || x === 8 || z === 7 || z === 8;
}
// Synthetic terrain: three drainage bowls plus a shallow emergency corridor.
for (let z = 0; z < N; z++) {
for (let x = 0; x < N; x++) {
const i = cellIndex(x, z);
let h = 1.42 +
0.08 * Math.sin(x * 0.72 + z * 0.31) +
0.045 * Math.cos(z * 0.88 - x * 0.23);
const dm = Math.hypot(x - 2, z - 13);
const de = Math.hypot(x - 14, z - 11);
const dn = Math.hypot(x - 8, z - 2);
h -= 1.34 * Math.exp(-(dm * dm) / 34);
h -= 0.98 * Math.exp(-(de * de) / 39);
h -= 0.87 * Math.exp(-(dn * dn) / 43);
const corridorA = segmentDistance(x, z, 2, 13, 14, 13);
const corridorB = segmentDistance(x, z, 14, 13, 14, 11);
const corridor = Math.min(corridorA, corridorB);
h = Math.min(h, 0.35 + corridor * 0.012);
terrain[i] = Math.max(0.12, h);
}
}
// Land use and occupied building parcels.
for (let z = 0; z < N; z++) {
for (let x = 0; x < N; x++) {
const i = cellIndex(x, z);
const drainCell = drainDefs.some(d => d.index === i);
if (drainCell) land[i] = "drain";
else if (isRoad(x, z)) land[i] = "road";
else if (isPark(x, z)) land[i] = "park";
else land[i] = "lot";
if (
!drainCell &&
land[i] === "lot" &&
Math.abs(x - 2) + Math.abs(z - 13) > 1 &&
Math.abs(x - 14) + Math.abs(z - 11) > 1 &&
Math.abs(x - 8) + Math.abs(z - 2) > 1 &&
random() < 0.49
) {
occupied[i] = 1;
buildingLevels[i] = 1 + Math.floor(random() * 3);
}
}
}
// ---------- Three.js scene ----------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07131c);
scene.fog = new THREE.FogExp2(0x07131c, 0.018);
const camera = new THREE.PerspectiveCamera(
43, innerWidth / innerHeight, 0.1, 150
);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
$("scene").appendChild(renderer.domElement);
const cameraState = {
target: new THREE.Vector3(0, 0.35, 0),
radius: 29,
theta: 0.72,
phi: 0.91
};
function updateCamera() {
const s = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + cameraState.radius * s * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z + cameraState.radius * s * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xbfe9ff, 0x18232b, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 2.6);
sun.position.set(9, 18, 11);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 15;
sun.shadow.camera.bottom = -15;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
sun.shadow.bias = -0.0005;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x5ab9dc, 1.1);
rim.position.set(-12, 9, -8);
scene.add(rim);
const board = new THREE.Mesh(
new THREE.BoxGeometry(N + 0.8, 0.46, N + 0.8),
new THREE.MeshStandardMaterial({
color: 0x142633,
roughness: 0.88,
metalness: 0.06
})
);
board.position.y = -0.73;
board.receiveShadow = true;
scene.add(board);
const boardEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(board.geometry),
new THREE.LineBasicMaterial({
color: 0x3c6478,
transparent: true,
opacity: 0.5
})
);
boardEdges.position.copy(board.position);
scene.add(boardEdges);
const terrainMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.94, 1, 0.94),
new THREE.MeshStandardMaterial({
roughness: 0.92,
metalness: 0.02,
vertexColors: true
}),
N * N
);
terrainMesh.receiveShadow = true;
terrainMesh.castShadow = true;
const dummy = new THREE.Object3D();
const terrainColor = new THREE.Color();
for (let z = 0; z < N; z++) {
for (let x = 0; x < N; x++) {
const i = cellIndex(x, z);
const h = terrain[i];
dummy.position.set(worldX(x), -0.5 + (h + 0.5) / 2, worldZ(z));
dummy.scale.set(1, h + 0.5, 1);
dummy.updateMatrix();
terrainMesh.setMatrixAt(i, dummy.matrix);
if (land[i] === "road") terrainColor.setHex(0x263945);
else if (land[i] === "park") terrainColor.setHex(0x315d50);
else if (land[i] === "drain") terrainColor.setHex(0x152630);
else terrainColor.setHex(0x40515a);
const variation = 0.9 + 0.16 * ((x * 17 + z * 31) % 7) / 6;
terrainColor.multiplyScalar(variation);
terrainMesh.setColorAt(i, terrainColor);
}
}
terrainMesh.instanceMatrix.needsUpdate = true;
terrainMesh.instanceColor.needsUpdate = true;
scene.add(terrainMesh);
// Instanced voxel buildings.
const buildingInstances = [];
const buildingPalette = [
0x8aa6b1, 0x6f8996, 0xa4b7ba, 0x57727f,
0x8797a1, 0x9b817c, 0x6a8490
];
for (let z = 0; z < N; z++) {
for (let x = 0; x < N; x++) {
const i = cellIndex(x, z);
if (!occupied[i]) continue;
for (let layer = 0; layer < buildingLevels[i]; layer++) {
buildingInstances.push({
x, z, layer,
color: buildingPalette[Math.floor(random() * buildingPalette.length)]
});
}
}
}
const buildingMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.83, 0.72, 0.83),
new THREE.MeshStandardMaterial({
roughness: 0.74,
metalness: 0.06,
vertexColors: true
}),
buildingInstances.length
);
buildingInstances.forEach((b, i) => {
dummy.position.set(
worldX(b.x),
terrain[cellIndex(b.x, b.z)] + 0.36 + b.layer * 0.72,
worldZ(b.z)
);
dummy.scale.set(1, 1, 1);
dummy.updateMatrix();
buildingMesh.setMatrixAt(i, dummy.matrix);
buildingMesh.setColorAt(i, new THREE.Color(b.color));
});
buildingMesh.instanceMatrix.needsUpdate = true;
buildingMesh.instanceColor.needsUpdate = true;
buildingMesh.castShadow = true;
buildingMesh.receiveShadow = true;
scene.add(buildingMesh);
// Small park trees.
const trunkGeometry = new THREE.CylinderGeometry(0.055, 0.07, 0.42, 7);
const crownGeometry = new THREE.IcosahedronGeometry(0.25, 1);
const trunkMaterial = new THREE.MeshStandardMaterial({ color: 0x624838 });
const crownMaterial = new THREE.MeshStandardMaterial({ color: 0x4d9470 });
for (let z = 0; z < N; z++) {
for (let x = 0; x < N; x++) {
const i = cellIndex(x, z);
if (
land[i] === "park" &&
!occupied[i] &&
(x * 5 + z * 3) % 4 === 0
) {
const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial);
trunk.position.set(worldX(x), terrain[i] + 0.21, worldZ(z));
trunk.castShadow = true;
scene.add(trunk);
const crown = new THREE.Mesh(crownGeometry, crownMaterial);
crown.position.set(worldX(x), terrain[i] + 0.58, worldZ(z));
crown.scale.y = 1.15;
crown.castShadow = true;
scene.add(crown);
}
}
}
// ---------- Drain objects ----------
const drainVisuals = [];
const drainHitMeshes = [];
drainDefs.forEach((def, drainNumber) => {
const x = cellX(def.index);
const z = cellZ(def.index);
const group = new THREE.Group();
group.position.set(worldX(x), terrain[def.index], worldZ(z));
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.30, 0.055, 8, 28),
new THREE.MeshStandardMaterial({
color: def.color,
emissive: def.color,
emissiveIntensity: 1.2,
roughness: 0.35
})
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.07;
group.add(ring);
const core = new THREE.Mesh(
new THREE.CylinderGeometry(0.19, 0.22, 0.12, 16),
new THREE.MeshStandardMaterial({
color: 0x0a1118,
emissive: def.color,
emissiveIntensity: 0.35,
roughness: 0.65
})
);
core.position.y = 0.04;
group.add(core);
const pulse = new THREE.Mesh(
new THREE.TorusGeometry(0.32, 0.018, 6, 28),
new THREE.MeshBasicMaterial({
color: def.color,
transparent: true,
opacity: 0.55,
depthWrite: false
})
);
pulse.rotation.x = Math.PI / 2;
pulse.position.y = 0.075;
group.add(pulse);
const blockage = new THREE.Group();
const barMaterial = new THREE.MeshStandardMaterial({
color: COLORS.red,
emissive: COLORS.red,
emissiveIntensity: 0.65,
roughness: 0.4
});
for (const angle of [-Math.PI / 4, Math.PI / 4]) {
const bar = new THREE.Mesh(
new THREE.BoxGeometry(0.78, 0.10, 0.11),
barMaterial
);
bar.rotation.y = angle;
bar.position.y = 0.24;
blockage.add(bar);
}
blockage.visible = false;
group.add(blockage);
const gauge = new THREE.Mesh(
new THREE.CylinderGeometry(0.085, 0.085, 1, 10),
new THREE.MeshBasicMaterial({
color: def.color,
transparent: true,
opacity: 0.25,
depthWrite: false
})
);
group.add(gauge);
const hit = new THREE.Mesh(
new THREE.CylinderGeometry(0.5, 0.5, 0.7, 12),
new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false
})
);
hit.position.y = 0.2;
hit.userData.drainNumber = drainNumber;
group.add(hit);
drainHitMeshes.push(hit);
scene.add(group);
drainVisuals.push({
def,
group,
ring,
core,
pulse,
blockage,
gauge
});
});
const mainDrain = drainVisuals[0];
const pool = new THREE.Mesh(
new THREE.CircleGeometry(1, 48),
new THREE.MeshPhysicalMaterial({
color: 0x3fbde0,
emissive: 0x0e6075,
emissiveIntensity: 0.35,
transparent: true,
opacity: 0.58,
roughness: 0.22,
metalness: 0.05,
depthWrite: false
})
);
pool.rotation.x = -Math.PI / 2;
pool.position.set(
worldX(cellX(mainDrain.def.index)),
terrain[mainDrain.def.index] + 0.035,
worldZ(cellZ(mainDrain.def.index))
);
scene.add(pool);
// ---------- Hydrology graph ----------
const distances = [];
const nextCells = [];
function edgeCost(from, to) {
const rise = Math.max(0, terrain[to] - terrain[from]);
const drop = Math.max(0, terrain[from] - terrain[to]);
return 1 + rise * 18 + drop * 0.55;
}
function dijkstra(drainIndex) {
const count = N * N;
const dist = new Float64Array(count);
const next = new Int32Array(count);
const visited = new Uint8Array(count);
dist.fill(Infinity);
next.fill(-1);
dist[drainIndex] = 0;
for (let iteration = 0; iteration < count; iteration++) {
let current = -1;
let best = Infinity;
for (let i = 0; i < count; i++) {
if (!visited[i] && dist[i] < best) {
best = dist[i];
current = i;
}
}
if (current === -1) break;
visited[current] = 1;
const cx = cellX(current);
const cz = cellZ(current);
const neighbors = [];
if (cx > 0) neighbors.push(current - 1);
if (cx < N - 1) neighbors.push(current + 1);
if (cz > 0) neighbors.push(current - N);
if (cz < N - 1) neighbors.push(current + N);
for (const neighbor of neighbors) {
if (occupied[neighbor] || visited[neighbor]) continue;
// The edge is traveled from neighbor toward current.
const candidate = dist[current] + edgeCost(neighbor, current);
if (candidate < dist[neighbor]) {
dist[neighbor] = candidate;
next[neighbor] = current;
}
}
}
return { dist, next };
}
drainDefs.forEach(def => {
const result = dijkstra(def.index);
distances.push(result.dist);
nextCells.push(result.next);
});
function routeCells(source, drainIndex, next = nextCells[drainIndex]) {
const cells = [source];
let current = source;
let guard = 0;
while (
current !== drainIndex &&
next[current] >= 0 &&
guard++ < N * N
) {
current = next[current];
cells.push(current);
}
return cells;
}
function cellsToPoints(cells, lift = 0.18) {
return cells.map(i => new THREE.Vector3(
worldX(cellX(i)),
terrain[i] + lift,
worldZ(cellZ(i))
));
}
let model = null;
function calculateModel() {
const perCellVolume = state.rainMm * 0.1;
const sourceVolumes = new Float64Array(N * N);
const baseline = [0, 0, 0];
const sourceRecords = [[], [], []];
// Every parcel receives rain. Roof runoff goes to the lowest adjacent
// passable parcel, while street, park, and drain cells retain their rain.
for (let z = 0; z < N; z++) {
for (let x = 0; x < N; x++) {
const i = cellIndex(x, z);
const volume = perCellVolume;
if (!occupied[i]) {
sourceVolumes[i] += volume;
continue;
}
const neighbors = [];
if (x > 0) neighbors.push(i - 1);
if (x < N - 1) neighbors.push(i + 1);
if (z > 0) neighbors.push(i - N);
if (z < N - 1) neighbors.push(i + N);
const passable = neighbors.filter(n => !occupied[n]);
if (!passable.length) continue;
const receiver = passable.reduce((best, n) =>
terrain[n] < terrain[best] ? n : best
);
sourceVolumes[receiver] += volume;
}
}
for (let i = 0; i < N * N; i++) {
if (sourceVolumes[i] <= 0) continue;
let bestDrain = -1;
let bestCost = Infinity;
for (let d = 0; d < drainDefs.length; d++) {
if (distances[d][i] < bestCost) {
bestCost = distances[d][i];
bestDrain = d;
}
}
if (bestDrain === -1 || !Number.isFinite(bestCost)) continue;
baseline[bestDrain] += sourceVolumes[i];
sourceRecords[bestDrain].push({
index: i,
volume: sourceVolumes[i]
});
}
sourceRecords.forEach(records => {
records.sort((a, b) => b.volume - a.volume);
});
const stored = Math.min(SUMP_CAPACITY, baseline[0]);
const overflow = Math.max(0, baseline[0] - stored);
// The overflow outlet is whichever alternate is least costly when
// traveling from the blocked main sump.
const spillAlt = distances[1][drainDefs[0].index] <=
distances[2][drainDefs[0].index] ? 1 : 2;
const blocked = [
stored,
baseline[1] + (spillAlt === 1 ? overflow : 0),
baseline[2] + (spillAlt === 2 ? overflow : 0)
];
return {
perCellVolume,
total: perCellVolume * N * N,
baseline,
blocked,
stored,
overflow,
spillAlt,
sourceRecords
};
}
// ---------- Route visualization ----------
const baselineRoutes = new THREE.Group();
const blockedRoutes = new THREE.Group();
scene.add(baselineRoutes, blockedRoutes);
function addRouteLine(group, cells, color, opacity = 0.55, dashed = false) {
if (cells.length < 2) return;
const geometry = new THREE.BufferGeometry().setFromPoints(
cellsToPoints(cells, 0.17)
);
const material = dashed
? new THREE.LineDashedMaterial({
color,
transparent: true,
opacity,
dashSize: 0.22,
gapSize: 0.13,
depthWrite: false
})
: new THREE.LineBasicMaterial({
color,
transparent: true,
opacity,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
if (dashed) line.computeLineDistances();
group.add(line);
}
function addTube(group, points, color, radius = 0.045) {
if (points.length < 2) return;
const curve = new THREE.CurvePath();
for (let i = 0; i < points.length - 1; i++) {
curve.add(new THREE.LineCurve3(points[i], points[i + 1]));
}
const geometry = new THREE.TubeGeometry(
curve,
Math.max(20, points.length * 3),
radius,
6,
false
);
const mesh = new THREE.Mesh(
geometry,
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.9,
depthWrite: false
})
);
group.add(mesh);
}
function makeParticleMesh(paths, color) {
const geometry = new THREE.SphereGeometry(0.072, 8, 8);
const material = new THREE.MeshBasicMaterial({ color });
const mesh = new THREE.InstancedMesh(geometry, material, Math.max(1, paths.length));
mesh.frustumCulled = false;
mesh.count = paths.length;
const data = paths.map(points => {
const cumulative = [0];
let total = 0;
for (let i = 1; i < points.length; i++) {
total += points[i].distanceTo(points[i - 1]);
cumulative.push(total);
}
return { points, cumulative, total };
});
scene.add(mesh);
return { mesh, data };
}
function samplePolyline(path, t) {
if (!path.points.length) return new THREE.Vector3();
if (path.points.length === 1 || path.total <= 0) return path.points[0];
const distance = ((t % 1) + 1) % 1 * path.total;
for (let i = 1; i < path.cumulative.length; i++) {
if (distance <= path.cumulative[i]) {
const segmentLength =
path.cumulative[i] - path.cumulative[i - 1];
const local = segmentLength > 0
? (distance - path.cumulative[i - 1]) / segmentLength
: 0;
return path.points[i - 1].clone().lerp(path.points[i], local);
}
}
return path.points[path.points.length - 1].clone();
}
let baselineParticles;
let blockedParticles;
function buildRoutes() {
const mainSources = model.sourceRecords[0];
const eastSources = model.sourceRecords[1];
const northSources = model.sourceRecords[2];
mainSources.slice(0, 10).forEach(record => {
addRouteLine(
baselineRoutes,
routeCells(record.index, 0),
COLORS.cyan,
0.58
);
});
eastSources.slice(0, 4).forEach(record => {
addRouteLine(
baselineRoutes,
routeCells(record.index, 1),
COLORS.purple,
0.32
);
});
northSources.slice(0, 4).forEach(record => {
addRouteLine(
baselineRoutes,
routeCells(record.index, 2),
COLORS.green,
0.32
);
});
const spillCells = routeCells(
drainDefs[0].index,
model.spillAlt,
nextCells[model.spillAlt]
);
const baselinePaths = [
...mainSources.slice(0, 8).map(r =>
cellsToPoints(routeCells(r.index, 0), 0.2)
),
...eastSources.slice(0, 2).map(r =>
cellsToPoints(routeCells(r.index, 1), 0.2)
),
...northSources.slice(0, 2).map(r =>
cellsToPoints(routeCells(r.index, 2), 0.2)
)
];
baselineParticles = makeParticleMesh(baselinePaths, COLORS.cyan);
const combinedPaths = mainSources.slice(0, 6).map(record => {
const toMain = routeCells(record.index, 0);
const combined = [...toMain, ...spillCells.slice(1)];
return cellsToPoints(combined, 0.22);
});
combinedPaths.forEach((points, i) => {
addRouteLine(
blockedRoutes,
pointsToCells(points),
COLORS.orange,
i === 0 ? 0.85 : 0.48,
i !== 0
);
if (i === 0) addTube(blockedRoutes, points, COLORS.orange, 0.05);
});
blockedParticles = makeParticleMesh(combinedPaths, COLORS.orange);
}
function pointsToCells(points) {
return points.map(point => {
const x = Math.round(point.x + HALF);
const z = Math.round(point.z + HALF);
return cellIndex(
Math.max(0, Math.min(N - 1, x)),
Math.max(0, Math.min(N - 1, z))
);
});
}
// ---------- Rain ----------
const RAIN_COUNT = 260;
const rainPositions = new Float32Array(RAIN_COUNT * 6);
const rainData = [];
for (let i = 0; i < RAIN_COUNT; i++) {
rainData.push({
x: (random() - 0.5) * (N + 1),
z: (random() - 0.5) * (N + 1),
y: random() * 13,
speed: 7 + random() * 5,
length: 0.25 + random() * 0.35
});
}
const rainGeometry = new THREE.BufferGeometry();
rainGeometry.setAttribute(
"position",
new THREE.BufferAttribute(rainPositions, 3)
);
const rainLines = new THREE.LineSegments(
rainGeometry,
new THREE.LineBasicMaterial({
color: 0x9edcf1,
transparent: true,
opacity: 0.27,
depthWrite: false
})
);
rainLines.frustumCulled = false;
scene.add(rainLines);
function updateRain(dt) {
rainLines.visible = state.showRain;
if (!state.showRain) return;
const activeCount = Math.min(
RAIN_COUNT,
Math.floor(75 + state.rainMm * 3.8)
);
rainGeometry.setDrawRange(0, activeCount * 2);
for (let i = 0; i < activeCount; i++) {
const drop = rainData[i];
drop.y -= drop.speed * dt;
const x = Math.max(0, Math.min(N - 1,
Math.floor(drop.x + HALF + 0.5)
));
const z = Math.max(0, Math.min(N - 1,
Math.floor(drop.z + HALF + 0.5)
));
const ground = terrain[cellIndex(x, z)];
if (drop.y < ground + 0.05) {
drop.y = 11 + random() * 2;
drop.x = (random() - 0.5) * (N + 1);
drop.z = (random() - 0.5) * (N + 1);
}
const j = i * 6;
rainPositions[j] = drop.x;
rainPositions[j + 1] = drop.y;
rainPositions[j + 2] = drop.z;
rainPositions[j + 3] = drop.x + 0.035;
rainPositions[j + 4] = drop.y - drop.length;
rainPositions[j + 5] = drop.z + 0.02;
}
rainGeometry.attributes.position.needsUpdate = true;
}
// ---------- UI and scenario ----------
function formatVolume(value) {
if (value >= 100) return Math.round(value).toLocaleString();
if (value >= 10) return value.toFixed(0);
return value.toFixed(1);
}
function setBar(id, value) {
const percent = model.total > 0 ? (value / model.total) * 100 : 0;
$(id).style.width = `${Math.max(0, Math.min(100, percent))}%`;
}
function updateUI() {
const b = model.baseline;
const blockedValues = model.blocked;
const currentValues = state.blocked ? blockedValues : b;
$("totalVolume").textContent = formatVolume(model.total);
$("openMain").textContent = formatVolume(b[0]);
$("storedVolume").textContent = formatVolume(model.stored);
$("overflowVolume").textContent = formatVolume(model.overflow);
const ids = ["main", "east", "north"];
ids.forEach((id, i) => {
$(`${id}BaseText`).textContent = formatVolume(b[i]);
$(`${id}BlockedText`).textContent = formatVolume(blockedValues[i]);
setBar(`${id}BaseBar`, b[i]);
setBar(`${id}BlockedBar`, blockedValues[i]);
});
$("statusText").textContent = state.blocked
? "Main drain blocked"
: "Main drain open";
$("statusText").classList.toggle("blocked", state.blocked);
$("blockButton").textContent = state.blocked
? "↻ Reopen main drain"
: "⊘ Block main drain";
$("blockButton").classList.toggle("blocked", state.blocked);
const spillName = drainDefs[model.spillAlt].name;
$("scenarioNote").textContent = state.blocked
? model.overflow > 0
? `${formatVolume(model.stored)} m³ remains in the blocked sump. ` +
`${formatVolume(model.overflow)} m³ follows the least-cost emergency ` +
`route to the ${spillName.toLowerCase()}.`
: `The blocked sump stores the full modeled main-drain catchment; ` +
`no emergency overflow is generated at this storm depth.`
: `With the main drain open, the baseline catchment is distributed ` +
`among all three drains. Blocking it redirects overflow to an alternate.`;
drainVisuals.forEach((visual, i) => {
const height = Math.max(0.025, Math.min(5.8, currentValues[i] / 48));
visual.gauge.scale.y = height;
visual.gauge.position.y = height / 2;
});
const poolRadius = model.stored > 0
? 0.28 + 1.28 * Math.sqrt(model.stored / SUMP_CAPACITY)
: 0;
pool.scale.set(poolRadius, poolRadius, 1);
pool.visible = state.blocked && model.stored > 0;
mainDrain.blockage.visible = state.blocked;
const mainColor = state.blocked ? COLORS.red : COLORS.cyan;
mainDrain.ring.material.color.setHex(mainColor);
mainDrain.ring.material.emissive.setHex(mainColor);
mainDrain.core.material.emissive.setHex(mainColor);
baselineRoutes.visible = state.showPaths;
blockedRoutes.visible = state.showPaths && state.blocked && model.overflow > 0;
baselineParticles.mesh.visible = state.showPaths;
blockedParticles.mesh.visible =
state.showPaths && state.blocked && model.overflow > 0;
const labels = ["label-main", "label-east", "label-north"];
labels.forEach((id, i) => {
const label = $(id);
label.innerHTML = state.blocked && i === 0
? `Main drain · blocked<span>${formatVolume(currentValues[i])} m³ stored</span>`
: `${drainDefs[i].name}<span>${formatVolume(currentValues[i])} m³</span>`;
});
}
function recompute() {
model = calculateModel();
updateUI();
}
function toggleBlocked() {
state.blocked = !state.blocked;
updateUI();
showToast(
state.blocked
? "Main drain blocked: runoff now accumulates and may spill."
: "Main drain reopened: baseline capture restored."
);
}
let toastTimer;
function showToast(message) {
$("toast").textContent = message;
$("toast").classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => $("toast").classList.remove("visible"), 2800);
}
$("blockButton").addEventListener("click", toggleBlocked);
$("rainDepth").addEventListener("input", event => {
state.rainMm = Number(event.target.value);
$("rainOutput").textContent = `${state.rainMm} mm`;
recompute();
});
$("showPaths").addEventListener("change", event => {
state.showPaths = event.target.checked;
updateUI();
});
$("showRain").addEventListener("change", event => {
state.showRain = event.target.checked;
});
// ---------- Direct camera controls ----------
let pointerDown = false;
let pointerButton = 0;
let pointerMoved = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
pointerDown = true;
pointerButton = event.button;
pointerMoved = false;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointerDown) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
if (Math.abs(dx) + Math.abs(dy) > 2) pointerMoved = true;
const panMode = pointerButton === 2 || pointerButton === 1 || event.shiftKey;
if (panMode) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3().crossVectors(
forward, camera.up
).normalize();
const panScale = cameraState.radius * 0.0017;
cameraState.target.addScaledVector(right, -dx * panScale);
cameraState.target.addScaledVector(forward, -dy * panScale);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.006,
0.08,
1.46
);
}
updateCamera();
});
renderer.domElement.addEventListener("pointerup", event => {
if (pointerDown && !pointerMoved && pointerButton === 0) {
const mouse = new THREE.Vector2(
event.clientX / innerWidth * 2 - 1,
-(event.clientY / innerHeight) * 2 + 1
);
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
const hit = raycaster.intersectObjects(drainHitMeshes, false)[0];
if (hit && hit.object.userData.drainNumber === 0) toggleBlocked();
}
pointerDown = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = false;
});
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
12,
50
);
updateCamera();
}, { passive: false });
$("orbitView").addEventListener("click", () => {
cameraState.target.set(0, 0.35, 0);
cameraState.radius = 29;
cameraState.theta = 0.72;
cameraState.phi = 0.91;
updateCamera();
});
$("topView").addEventListener("click", () => {
cameraState.target.set(0, 0, 0);
cameraState.radius = 27;
cameraState.theta = 0;
cameraState.phi = 0.025;
updateCamera();
});
$("zoomIn").addEventListener("click", () => {
cameraState.radius = Math.max(12, cameraState.radius * 0.86);
updateCamera();
});
$("zoomOut").addEventListener("click", () => {
cameraState.radius = Math.min(50, cameraState.radius * 1.16);
updateCamera();
});
// ---------- Labels and animation ----------
const labelItems = [
{ element: $("label-main"), position: new THREE.Vector3() },
{ element: $("label-east"), position: new THREE.Vector3() },
{ element: $("label-north"), position: new THREE.Vector3() }
];
drainDefs.forEach((def, i) => {
labelItems[i].position.set(
worldX(cellX(def.index)),
terrain[def.index] + 1.05,
worldZ(cellZ(def.index))
);
});
function updateLabels() {
const width = innerWidth;
const height = innerHeight;
labelItems.forEach(item => {
const p = item.position.clone().project(camera);
const visible = p.z > -1 && p.z < 1;
item.element.style.display = visible ? "block" : "none";
if (visible) {
item.element.style.left = `${(p.x * 0.5 + 0.5) * width}px`;
item.element.style.top = `${(-p.y * 0.5 + 0.5) * height}px`;
}
});
}
function updateParticles(system, time) {
if (!system) return;
system.data.forEach((path, i) => {
const phase = (time * 0.075 + i * 0.173) % 1;
const position = samplePolyline(path, phase);
const pulse = 0.85 + 0.25 * Math.sin(time * 5 + i);
dummy.position.copy(position);
dummy.scale.setScalar(pulse);
dummy.updateMatrix();
system.mesh.setMatrixAt(i, dummy.matrix);
});
system.mesh.instanceMatrix.needsUpdate = true;
}
function resize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
}
addEventListener("resize", resize);
// Initialize.
model = calculateModel();
buildRoutes();
updateUI();
const clock = new THREE.Clock();
let elapsed = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
elapsed += dt;
updateRain(dt);
updateParticles(baselineParticles, elapsed);
updateParticles(blockedParticles, elapsed);
drainVisuals.forEach((visual, i) => {
const pulse = 1 + 0.18 * Math.sin(elapsed * 3.1 + i * 1.7);
visual.pulse.scale.setScalar(pulse);
visual.pulse.material.opacity = 0.36 + 0.22 *
(0.5 + 0.5 * Math.sin(elapsed * 3.1 + i));
});
if (pool.visible) {
pool.material.opacity = 0.51 + 0.08 *
Math.sin(elapsed * 2.4);
}
updateLabels();
renderer.render(scene, camera);
}
animate();
requestAnimationFrame(() => $("loading").classList.add("hidden"));
</script>
</body>
</html>
```