Prompt specification
Build or customize the Three.js 3D scene "Allocate water between two ancient field basins" 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: Allocate water between two ancient field basins
Category: Art & Culture · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/allocate-water-between-two-ancient-field-basins-x2304
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows ancient Egyptian agriculture on the Nile floodplain. Let users open schematic gates connecting two field basins. Compare water coverage using a simplified conserved-volume model and avoid claiming exact ancient operating rules. Low-poly.
Working Three.js Starter (allocate-water-between-two-ancient-field-basins-x2304):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Nile Floodplain — Schematic Basin Water Model</title>
<style>
:root {
--ink: #173f38;
--ink-soft: #47675e;
--paper: rgba(255, 250, 232, 0.91);
--paper-solid: #fff9e7;
--line: rgba(35, 78, 67, 0.19);
--a: #d99132;
--b: #2e8795;
--green: #54723b;
--shadow: 0 14px 40px rgba(48, 47, 28, 0.15);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #e8ddbd;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
border: 1px solid var(--line);
color: var(--ink);
background: rgba(255, 255, 255, 0.55);
border-radius: 9px;
padding: 8px 10px;
cursor: pointer;
font-weight: 700;
transition:
background 150ms ease,
transform 150ms ease,
border-color 150ms ease;
}
button:hover {
background: #fffdf4;
border-color: rgba(35, 78, 67, 0.35);
}
button:active {
transform: translateY(1px);
}
button.primary {
color: #fffef4;
background: var(--ink);
border-color: var(--ink);
}
button.primary:hover {
background: #24594e;
}
button:focus-visible,
input:focus-visible {
outline: 3px solid rgba(46, 135, 149, 0.32);
outline-offset: 2px;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene.dragging {
cursor: grabbing;
}
.glass {
background: var(--paper);
border: 1px solid rgba(255, 255, 255, 0.65);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
.intro {
position: fixed;
z-index: 3;
top: 18px;
left: 18px;
width: min(510px, calc(100vw - 36px));
padding: 17px 19px 15px;
border-radius: 16px;
pointer-events: none;
}
.eyebrow {
color: var(--b);
font-size: 11px;
font-weight: 850;
letter-spacing: 0.15em;
text-transform: uppercase;
}
h1 {
margin: 4px 0 6px;
font-family: Georgia, "Times New Roman", serif;
font-size: clamp(25px, 3vw, 38px);
line-height: 1.05;
font-weight: 600;
letter-spacing: -0.025em;
}
.intro p {
margin: 0;
max-width: 470px;
color: var(--ink-soft);
font-size: 13px;
line-height: 1.5;
}
.status-line {
display: flex;
align-items: center;
gap: 8px;
margin-top: 10px;
color: var(--ink-soft);
font-size: 11px;
}
.status-dot {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 4px rgba(84, 114, 59, 0.12);
}
.controls {
position: fixed;
z-index: 4;
top: 18px;
right: 18px;
width: 306px;
padding: 16px;
border-radius: 16px;
}
.controls h2 {
margin: 0 0 3px;
font-size: 16px;
}
.controls .sub {
margin: 0 0 12px;
color: var(--ink-soft);
font-size: 11px;
line-height: 1.45;
}
.gate-card {
padding: 10px;
margin-top: 9px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.34);
}
.gate-card.active {
border-color: rgba(46, 135, 149, 0.52);
background: rgba(46, 135, 149, 0.08);
}
.gate-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 7px;
font-size: 12px;
font-weight: 800;
}
.gate-head output {
color: var(--b);
font-variant-numeric: tabular-nums;
}
.gate-line {
display: grid;
grid-template-columns: 1fr 72px;
align-items: center;
gap: 9px;
}
input[type="range"] {
width: 100%;
accent-color: var(--b);
cursor: pointer;
}
.gate-line button {
padding: 6px 7px;
font-size: 11px;
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 11px;
}
.actions button {
font-size: 11px;
}
.model-note {
margin-top: 12px;
padding-top: 11px;
border-top: 1px solid var(--line);
color: var(--ink-soft);
font-size: 10.5px;
line-height: 1.5;
}
.model-note strong {
color: var(--ink);
}
.equation {
display: inline-block;
margin-top: 5px;
padding: 4px 7px;
border-radius: 6px;
background: rgba(84, 114, 59, 0.09);
color: var(--ink);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
}
.comparison {
position: fixed;
z-index: 3;
left: 50%;
bottom: 17px;
width: min(980px, calc(100vw - 36px));
transform: translateX(-50%);
display: grid;
grid-template-columns: minmax(220px, 1fr) 210px minmax(220px, 1fr);
gap: 9px;
pointer-events: none;
}
.metric,
.conservation {
min-width: 0;
padding: 13px 15px;
border-radius: 14px;
pointer-events: auto;
}
.metric-title {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
font-weight: 850;
}
.basin-badge {
display: grid;
width: 24px;
height: 24px;
place-items: center;
border-radius: 7px;
color: white;
background: var(--a);
font-family: Georgia, serif;
font-size: 14px;
}
.metric.b .basin-badge {
background: var(--b);
}
.coverage-number {
margin-left: auto;
font-size: 20px;
font-weight: 850;
font-variant-numeric: tabular-nums;
}
.bar {
height: 8px;
margin: 8px 0 10px;
overflow: hidden;
border-radius: 99px;
background: rgba(23, 63, 56, 0.1);
}
.bar > span {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: var(--a);
transition: width 120ms linear;
}
.metric.b .bar > span {
background: var(--b);
}
.metric-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 8px;
}
.metric-grid span {
display: block;
color: var(--ink-soft);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.metric-grid strong {
display: block;
margin-top: 2px;
font-size: 13px;
font-variant-numeric: tabular-nums;
}
.conservation {
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
}
.conservation .label {
color: var(--ink-soft);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.conservation .total {
margin: 3px 0;
font-size: 22px;
font-weight: 900;
font-variant-numeric: tabular-nums;
}
.conservation .check {
color: var(--green);
font-size: 11px;
font-weight: 800;
}
.conservation .delta {
margin-top: 8px;
font-size: 10.5px;
color: var(--ink-soft);
}
.conservation .flow {
margin-top: 6px;
min-height: 28px;
color: var(--ink);
font-size: 10.5px;
line-height: 1.35;
}
.clock {
margin-top: 5px;
color: var(--ink-soft);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9.5px;
}
.scene-hint {
position: fixed;
z-index: 2;
left: 50%;
bottom: 166px;
transform: translateX(-50%);
padding: 6px 10px;
border-radius: 99px;
color: rgba(23, 63, 56, 0.78);
background: rgba(255, 250, 232, 0.7);
font-size: 10px;
pointer-events: none;
white-space: nowrap;
}
#loading {
position: fixed;
z-index: 10;
inset: 0;
display: grid;
place-items: center;
color: var(--ink);
background: #e8ddbd;
font-family: Georgia, serif;
font-size: 24px;
}
@media (max-width: 900px) {
.intro {
width: min(430px, calc(100vw - 36px));
}
.intro p {
display: none;
}
.controls {
top: auto;
bottom: 182px;
width: 285px;
}
.comparison {
grid-template-columns: 1fr 1fr;
}
.conservation {
grid-column: 1 / -1;
grid-row: 2;
padding: 9px 12px;
}
.conservation .total {
font-size: 18px;
}
.scene-hint {
bottom: 166px;
left: 18px;
transform: none;
}
}
@media (max-width: 620px) {
.intro {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 12px 14px;
}
.intro p,
.status-line {
display: none;
}
.controls {
right: 10px;
bottom: 204px;
width: 245px;
padding: 12px;
}
.controls .sub,
.model-note {
display: none;
}
.comparison {
width: calc(100vw - 20px);
bottom: 10px;
gap: 6px;
}
.metric,
.conservation {
padding: 10px;
}
.metric-grid {
grid-template-columns: 1fr 1fr;
}
.metric-grid span:last-child,
.metric-grid strong:last-child {
display: none;
}
.coverage-number {
font-size: 17px;
}
.scene-hint {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive low-poly Nile floodplain with two irrigated field basins"></canvas>
<header class="intro glass">
<div class="eyebrow">Interactive floodplain study</div>
<h1>Water for the Fields</h1>
<p>
Open the schematic sluices to move water between two field basins, then compare
wetted area, depth, and stored volume as the water surfaces approach equilibrium.
</p>
<div class="status-line">
<span class="status-dot"></span>
<span>
Illustrative geometry and simplified hydraulics—not a reconstruction of
a particular ancient operating system.
</span>
</div>
</header>
<aside class="controls glass" aria-label="Schematic gate controls">
<h2>Schematic gates</h2>
<p class="sub">
G1 and G2 are parallel links. Each slider sets a conceptual opening fraction.
Click a gate in the scene to toggle it.
</p>
<div class="gate-card" id="gateCard0">
<div class="gate-head">
<span>G1 · Upper link</span>
<output id="gateOutput0">0%</output>
</div>
<div class="gate-line">
<input
id="gateRange0"
type="range"
min="0"
max="100"
value="0"
aria-label="Opening fraction for gate G1"
>
<button id="gateToggle0" aria-pressed="false">Open G1</button>
</div>
</div>
<div class="gate-card" id="gateCard1">
<div class="gate-head">
<span>G2 · Lower link</span>
<output id="gateOutput1">0%</output>
</div>
<div class="gate-line">
<input
id="gateRange1"
type="range"
min="0"
max="100"
value="0"
aria-label="Opening fraction for gate G2"
>
<button id="gateToggle1" aria-pressed="false">Open G2</button>
</div>
</div>
<div class="actions">
<button id="openAll" class="primary">Open both</button>
<button id="closeAll">Close both</button>
<button id="resetSplit">Reset water split</button>
<button id="resetView">Reset view</button>
</div>
<div class="model-note">
<strong>Simplified model.</strong>
Storage uses <span class="equation">V = A · d</span> and transfer uses a
lumped orifice relation,
<span class="equation">Q ∝ A<sub>gate</sub>√|Δh|</span>.
The clock runs at <strong>24×</strong>. Values and opening behavior are schematic.
</div>
</aside>
<section class="comparison" aria-label="Water coverage comparison">
<article class="metric a glass">
<div class="metric-title">
<span class="basin-badge">A</span>
<span>West basin</span>
<span class="coverage-number" id="coverageA">0%</span>
</div>
<div class="bar"><span id="barA"></span></div>
<div class="metric-grid">
<div>
<span>Depth</span>
<strong id="depthA">0.00 m</strong>
</div>
<div>
<span>Wet area</span>
<strong id="areaA">0 m²</strong>
</div>
<div>
<span>Stored</span>
<strong id="volumeA">0 m³</strong>
</div>
</div>
</article>
<article class="conservation glass">
<div class="label">Conserved total</div>
<div class="total">3,800 m³</div>
<div class="check">✓ volume conserved</div>
<div class="delta" id="deltaText">Calculating…</div>
<div class="flow" id="flowText">Gates closed.</div>
<div class="clock" id="clockText">Model time 00:00:00</div>
</article>
<article class="metric b glass">
<div class="metric-title">
<span class="basin-badge">B</span>
<span>East basin</span>
<span class="coverage-number" id="coverageB">0%</span>
</div>
<div class="bar"><span id="barB"></span></div>
<div class="metric-grid">
<div>
<span>Depth</span>
<strong id="depthB">0.00 m</strong>
</div>
<div>
<span>Wet area</span>
<strong id="areaB">0 m²</strong>
</div>
<div>
<span>Stored</span>
<strong id="volumeB">0 m³</strong>
</div>
</div>
</article>
</section>
<div class="scene-hint">Drag to orbit · wheel to zoom · click a gate</div>
<div id="loading">Preparing the floodplain…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Model constants. These are deliberately schematic rather than historical.
// -------------------------------------------------------------------------
const MODEL = Object.freeze({
totalVolume: 3800,
areaA: 660,
areaB: 660,
floorA: 0.20,
floorB: 0.75,
referenceDepth: 4.20,
gateArea: 1.15,
dischargeCoefficient: 0.62,
gravity: 9.81,
timeScale: 24,
initialA: 2500,
initialB: 1300
});
const state = {
volumeA: MODEL.initialA,
volumeB: MODEL.initialB,
elapsedModel: 0,
gates: [
{ open: 0, target: 0, flow: 0 },
{ open: 0, target: 0, flow: 0 }
]
};
const basinDefs = [
{
key: "A",
x: -16,
z: 8,
width: 30,
depth: 22,
floor: MODEL.floorA,
area: MODEL.areaA
},
{
key: "B",
x: 16,
z: 8,
width: 30,
depth: 22,
floor: MODEL.floorB,
area: MODEL.areaB
}
];
const $ = (id) => document.getElementById(id);
const clamp = THREE.MathUtils.clamp;
const fmt = new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 });
// -------------------------------------------------------------------------
// Renderer, camera, and direct camera controls.
// -------------------------------------------------------------------------
const canvas = $("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe8ddbd);
scene.fog = new THREE.Fog(0xe8ddbd, 82, 150);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
250
);
const cameraState = {
target: new THREE.Vector3(0, 1.2, 1),
radius: 67,
yaw: 0.70,
pitch: 0.73
};
function updateCamera() {
const { target, radius, yaw, pitch } = cameraState;
const sinPitch = Math.sin(pitch);
camera.position.set(
target.x + radius * sinPitch * Math.sin(yaw),
target.y + radius * Math.cos(pitch),
target.z + radius * sinPitch * Math.cos(yaw)
);
camera.lookAt(target);
camera.updateMatrixWorld();
}
function resetCamera() {
cameraState.radius = 67;
cameraState.yaw = 0.70;
cameraState.pitch = 0.73;
updateCamera();
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xfff3cf, 0x756b46, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffedc0, 3.2);
sun.position.set(-32, 48, 26);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -65;
sun.shadow.camera.right = 65;
sun.shadow.camera.top = 55;
sun.shadow.camera.bottom = -55;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 130;
sun.shadow.bias = -0.0007;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x8ac6cf, 0.65);
fill.position.set(35, 18, -30);
scene.add(fill);
// -------------------------------------------------------------------------
// Materials and geometry helpers.
// -------------------------------------------------------------------------
function material(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.9,
flatShading: true,
...options
});
}
const materials = {
sand: material(0xd5b875),
sandLight: material(0xe4cb8d),
soil: material(0x8b5a31),
soilDark: material(0x674226),
mudbrick: material(0xb87846),
mudbrickLight: material(0xc99058),
reed: material(0xa98845),
trunk: material(0x76502f),
palm: material(0x4f7837),
palmLight: material(0x6c9144),
cropA: material(0x66873e),
cropB: material(0x4c7338),
cropC: material(0x82964b),
dark: material(0x3e4934),
water: material(0x2f8c99, {
roughness: 0.28,
metalness: 0.04,
transparent: true,
opacity: 0.83,
side: THREE.DoubleSide
}),
river: material(0x397f92, {
roughness: 0.3,
metalness: 0.02,
side: THREE.DoubleSide
}),
wood: material(0x70482a),
woodLight: material(0x95633a)
};
function addBox(parent, size, position, mat, cast = true, receive = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size), mat);
mesh.position.set(...position);
mesh.castShadow = cast;
mesh.receiveShadow = receive;
parent.add(mesh);
return mesh;
}
function addCylinder(
parent,
radiusTop,
radiusBottom,
height,
segments,
position,
mat,
cast = true
) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radiusTop, radiusBottom, height, segments),
mat
);
mesh.position.set(...position);
mesh.castShadow = cast;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeLabel(title, subtitle = "") {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const ctx = labelCanvas.getContext("2d");
ctx.fillStyle = "rgba(22, 57, 49, 0.90)";
ctx.fillRect(0, 0, 512, 128);
ctx.strokeStyle = "rgba(255, 244, 202, 0.38)";
ctx.lineWidth = 4;
ctx.strokeRect(3, 3, 506, 122);
ctx.textAlign = "center";
ctx.fillStyle = "#fff5ce";
ctx.font = "700 40px system-ui, sans-serif";
ctx.fillText(title, 256, subtitle ? 61 : 76);
if (subtitle) {
ctx.fillStyle = "#c6d9b9";
ctx.font = "600 21px system-ui, sans-serif";
ctx.fillText(subtitle, 256, 98);
}
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(8.6, 2.15, 1);
sprite.renderOrder = 20;
return sprite;
}
// -------------------------------------------------------------------------
// Ground, Nile, basin shells, and agricultural surroundings.
// -------------------------------------------------------------------------
addBox(
scene,
[120, 0.3, 90],
[0, -0.18, 0],
materials.sand,
false,
true
);
function riverCenter(x) {
return -25 + Math.sin(x * 0.075) * 1.15 + Math.sin(x * 0.19) * 0.35;
}
function riverHalfWidth(x) {
return 4.6 + Math.sin(x * 0.115) * 0.55 + Math.cos(x * 0.23) * 0.2;
}
function createRiverRibbon(extraWidth, y, mat) {
const positions = [];
const indices = [];
const segments = 70;
for (let i = 0; i <= segments; i++) {
const x = -56 + (112 * i) / segments;
const z = riverCenter(x);
const halfWidth = riverHalfWidth(x) + extraWidth;
positions.push(x, y, z - halfWidth);
positions.push(x, y, z + halfWidth);
}
for (let i = 0; i < segments; i++) {
const a = i * 2;
indices.push(a, a + 1, a + 2, a + 1, a + 3, a + 2);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(geometry, mat);
mesh.receiveShadow = true;
scene.add(mesh);
return mesh;
}
createRiverRibbon(1.25, 0.015, materials.sandLight);
createRiverRibbon(0, 0.075, materials.river);
const channelSlots = [4, 15];
const slotHalfWidth = 1.8;
function addBasinShell(def, index) {
const wallHeight = 4.7;
const wallY = wallHeight / 2;
const outerX = def.x + (index === 0 ? -1 : 1) * def.width / 2;
const innerX = def.x + (index === 0 ? 1 : -1) * def.width / 2;
// Basin floor.
addBox(
scene,
[def.width, 0.24, def.depth],
[def.x, def.floor - 0.12, def.z],
materials.soil,
false,
true
);
// Front and back embankments.
for (const side of [-1, 1]) {
const z = def.z + side * def.depth / 2;
addBox(
scene,
[def.width + 0.8, wallHeight, 0.8],
[def.x, wallY, z],
materials.mudbrick
);
addBox(
scene,
[def.width + 1.1, 0.18, 1.05],
[def.x, wallHeight + 0.04, z],
materials.mudbrickLight
);
}
// Outer side embankment.
addBox(
scene,
[0.8, wallHeight, def.depth],
[outerX, wallY, def.z],
materials.mudbrick
);
addBox(
scene,
[1.05, 0.18, def.depth + 0.4],
[outerX, wallHeight + 0.04, def.z],
materials.mudbrickLight
);
// Inner side embankment, interrupted by the two schematic canal links.
let cursor = def.z - def.depth / 2;
const segments = [];
for (const slot of channelSlots) {
segments.push([cursor, slot - slotHalfWidth]);
cursor = slot + slotHalfWidth;
}
segments.push([cursor, def.z + def.depth / 2]);
for (const [start, end] of segments) {
const length = end - start;
if (length <= 0.05) continue;
const z = (start + end) / 2;
addBox(
scene,
[0.8, wallHeight, length],
[innerX, wallY, z],
materials.mudbrick
);
addBox(
scene,
[1.05, 0.18, length + 0.12],
[innerX, wallHeight + 0.04, z],
materials.mudbrickLight
);
}
const label = makeLabel(`BASIN ${def.key}`, def.key === "A" ? "WEST FIELD" : "EAST FIELD");
label.position.set(def.x, 6.15, def.z - def.depth / 2 - 0.35);
scene.add(label);
}
addBasinShell(basinDefs[0], 0);
addBasinShell(basinDefs[1], 1);
// Central soil strip and canal floors.
addBox(
scene,
[2.6, 0.22, 25],
[0, 0.26, 8],
materials.soilDark,
false,
true
);
for (const z of channelSlots) {
addBox(
scene,
[4.8, 0.28, 3.45],
[0, 0.43, z],
materials.soil,
false,
true
);
}
// -------------------------------------------------------------------------
// Low-poly palms, crops, farm buildings, shaduf, pyramid, and river boat.
// -------------------------------------------------------------------------
function addPalm(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
const trunk = addCylinder(
group,
0.17,
0.31,
4.2,
5,
[0, 2.1, 0],
materials.trunk
);
trunk.rotation.z = 0.055;
const crown = new THREE.Group();
crown.position.y = 4.12;
group.add(crown);
const up = new THREE.Vector3(0, 1, 0);
for (let i = 0; i < 7; i++) {
const angle = (i / 7) * Math.PI * 2 + 0.2;
const geometry = new THREE.ConeGeometry(0.52, 3.05, 3);
geometry.translate(0, 1.525, 0);
const frond = new THREE.Mesh(
geometry,
i % 2 ? materials.palm : materials.palmLight
);
frond.castShadow = true;
frond.quaternion.setFromUnitVectors(
up,
new THREE.Vector3(
Math.cos(angle),
-0.18 + (i % 3) * 0.08,
Math.sin(angle)
).normalize()
);
crown.add(frond);
}
const center = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.38, 0),
materials.trunk
);
center.position.y = 4.1;
center.castShadow = true;
group.add(center);
scene.add(group);
return group;
}
function addCropField(x, z, width, depth, phase = 0) {
addBox(
scene,
[width, 0.12, depth],
[x, 0.06, z],
materials.soil,
false,
true
);
const rowCount = Math.max(3, Math.floor(depth / 1.15));
const rowStep = depth / rowCount;
for (let i = 0; i < rowCount; i++) {
const rowZ = z - depth / 2 + rowStep * (i + 0.5);
const rowMat = [materials.cropA, materials.cropB, materials.cropC][
(i + phase) % 3
];
addBox(
scene,
[width - 0.45, 0.21, 0.34],
[x, 0.23, rowZ],
rowMat,
false,
true
);
const plants = Math.max(3, Math.floor(width / 2.4));
for (let j = 0; j < plants; j++) {
const px = x - width / 2 + 0.9 + (j * (width - 1.8)) / (plants - 1);
const tuft = new THREE.Mesh(
new THREE.ConeGeometry(0.23, 0.62, 3),
(j + i) % 2 ? materials.cropA : materials.cropB
);
tuft.position.set(px, 0.48, rowZ);
tuft.castShadow = true;
scene.add(tuft);
}
}
}
addCropField(-41, 6, 12, 27, 0);
addCropField(41, 6, 12, 27, 1);
addCropField(2, -12, 35, 7, 2);
addCropField(-25, -12, 20, 6, 1);
[
[-49, -20, 1.0],
[-31, -21, 0.82],
[-4, -22, 0.95],
[18, -21, 0.88],
[39, -20, 1.05],
[-34, 25, 0.95],
[32, 25, 1.1]
].forEach(([x, z, s]) => addPalm(x, z, s));
function addHut(x, z, rotation = 0) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.rotation.y = rotation;
addBox(group, [4.1, 2.35, 3.2], [0, 1.175, 0], materials.mudbrick);
addBox(group, [4.45, 0.22, 3.55], [0, 2.36, 0], materials.mudbrickLight);
addBox(group, [0.72, 1.3, 0.08], [0.45, 0.65, 1.64], materials.dark);
addBox(group, [4.2, 0.32, 0.22], [0, 2.64, 1.48], materials.mudbrickLight);
addBox(group, [4.2, 0.32, 0.22], [0, 2.64, -1.48], materials.mudbrickLight);
addBox(group, [0.22, 0.32, 3.2], [2, 2.64, 0], materials.mudbrickLight);
addBox(group, [0.22, 0.32, 3.2], [-2, 2.64, 0], materials.mudbrickLight);
scene.add(group);
}
addHut(30, -12, -0.15);
addHut(36, -10, 0.08);
addHut(-34, -15, 0.12);
function addShaduf(x, z, rotation = 0) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.rotation.y = rotation;
addCylinder(
group,
0.10,
0.15,
4.8,
6,
[0, 2.4, 0],
materials.wood
);
const beam = addBox(
group,
[4.7, 0.18, 0.18],
[0.65, 4.25, 0],
materials.woodLight
);
beam.rotation.z = 0.22;
addBox(
group,
[0.62, 0.68, 0.62],
[-1.35, 4.63, 0],
materials.mudbrick
);
const rope = new THREE.Mesh(
new THREE.CylinderGeometry(0.025, 0.025, 1.5, 4),
materials.dark
);
rope.position.set(2.35, 3.35, 0);
group.add(rope);
addCylinder(
group,
0.34,
0.43,
0.65,
6,
[2.35, 2.52, 0],
materials.woodLight
);
scene.add(group);
}
addShaduf(-27, 13, -0.15);
addShaduf(28, 14, Math.PI + 0.1);
const pyramid = new THREE.Mesh(
new THREE.ConeGeometry(9, 11, 4),
materials.sandLight
);
pyramid.position.set(-43, 5.5, -38);
pyramid.rotation.y = Math.PI / 4;
pyramid.castShadow = true;
pyramid.receiveShadow = true;
scene.add(pyramid);
const smallPyramid = new THREE.Mesh(
new THREE.ConeGeometry(4.8, 6.3, 4),
materials.sand
);
smallPyramid.position.set(-32, 3.15, -41);
smallPyramid.rotation.y = Math.PI / 4;
smallPyramid.castShadow = true;
scene.add(smallPyramid);
const boat = new THREE.Group();
boat.position.set(-8, 0.38, -25);
const hull = new THREE.Mesh(
new THREE.CylinderGeometry(1, 1, 5.2, 6),
materials.wood
);
hull.rotation.z = Math.PI / 2;
hull.scale.set(0.65, 1, 0.45);
hull.castShadow = true;
boat.add(hull);
addBox(boat, [3.9, 0.12, 0.75], [0, 0.45, 0], materials.woodLight);
addCylinder(boat, 0.06, 0.08, 3.7, 5, [-0.4, 2.1, 0], materials.wood);
const sailGeometry = new THREE.BufferGeometry();
sailGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(
[-0.35, 1.0, 0, -0.35, 3.65, 0, 2.35, 1.0, 0],
3
)
);
sailGeometry.computeVertexNormals();
const sail = new THREE.Mesh(
sailGeometry,
material(0xf0dfb4, { side: THREE.DoubleSide })
);
sail.castShadow = true;
boat.add(sail);
scene.add(boat);
// -------------------------------------------------------------------------
// Basin water surfaces and gate assemblies.
// -------------------------------------------------------------------------
const waterGroups = [];
function createWaterSurface(def, index) {
const group = new THREE.Group();
group.position.set(def.x, 0, def.z);
const waterMaterial = materials.water.clone();
if (index === 1) {
waterMaterial.color.set(0x348c96);
}
const plane = new THREE.Mesh(
new THREE.PlaneGeometry(1, 1),
waterMaterial
);
plane.rotation.x = -Math.PI / 2;
plane.receiveShadow = true;
group.add(plane);
const rippleMaterials = [];
for (let i = 0; i < 5; i++) {
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-0.22, 0.025, -0.30 + i * 0.15),
new THREE.Vector3(0.22, 0.025, -0.30 + i * 0.15)
]);
const rippleMaterial = new THREE.LineBasicMaterial({
color: 0xd9f0dd,
transparent: true,
opacity: 0.18,
depthWrite: false
});
const line = new THREE.Line(geometry, rippleMaterial);
group.add(line);
rippleMaterials.push(rippleMaterial);
}
scene.add(group);
return { group, rippleMaterials };
}
basinDefs.forEach((def, index) => {
waterGroups.push(createWaterSurface(def, index));
});
const gateVisuals = [];
const gatePickables = [];
function createGate(index, z) {
const group = new THREE.Group();
group.position.set(0, 0, z);
scene.add(group);
const postHeight = 6.25;
for (const side of [-1, 1]) {
addBox(
group,
[0.38, postHeight, 0.38],
[0, postHeight / 2, side * 1.92],
materials.wood
);
addBox(
group,
[0.5, 0.18, 0.5],
[0, 0.12, side * 1.92],
materials.soilDark
);
}
addBox(
group,
[0.46, 0.42, 4.28],
[0, 5.95, 0],
materials.woodLight
);
const panelHeight = 3.8;
const panel = addBox(
group,
[0.28, panelHeight, 3.42],
[0, 0.45 + panelHeight / 2, 0],
materials.wood
);
panel.userData.gateIndex = index;
gatePickables.push(panel);
for (let i = 0; i < 4; i++) {
addBox(
panel,
[0.31, 0.09, 3.35],
[0, -1.45 + i * 0.95, 0],
materials.woodLight,
false,
false
);
}
const leftWater = addBox(
scene,
[1.72, 0.09, 3.15],
[-1.02, 1, z],
materials.water.clone(),
false,
false
);
const rightWater = addBox(
scene,
[1.72, 0.09, 3.15],
[1.02, 1, z],
materials.water.clone(),
false,
false
);
const streamGeometry = new THREE.BufferGeometry();
streamGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(18), 3)
);
const streamMaterial = new THREE.MeshBasicMaterial({
color: 0x9ce1dd,
transparent: true,
opacity: 0,
side: THREE.DoubleSide,
depthWrite: false
});
const stream = new THREE.Mesh(streamGeometry, streamMaterial);
stream.frustumCulled = false;
scene.add(stream);
const pulses = [];
for (let i = 0; i < 3; i++) {
const pulse = new THREE.Mesh(
new THREE.BoxGeometry(0.12, 0.055, 0.28),
new THREE.MeshBasicMaterial({
color: 0xe6f6d9,
transparent: true,
opacity: 0.7,
depthWrite: false
})
);
pulse.visible = false;
scene.add(pulse);
pulses.push(pulse);
}
const label = makeLabel(index === 0 ? "G1" : "G2", "SCHEMATIC LINK");
label.scale.set(5.4, 1.35, 1);
label.position.set(0, 7.45, 0);
group.add(label);
gateVisuals.push({
group,
panel,
panelHeight,
leftWater,
rightWater,
stream,
streamGeometry,
streamMaterial,
pulses,
z
});
}
createGate(0, channelSlots[0]);
createGate(1, channelSlots[1]);
// -------------------------------------------------------------------------
// Hydrology functions.
// -------------------------------------------------------------------------
function surfaceA() {
return MODEL.floorA + state.volumeA / MODEL.areaA;
}
function surfaceB() {
return MODEL.floorB + state.volumeB / MODEL.areaB;
}
function coverageA() {
return clamp(
(surfaceA() - MODEL.floorA) / MODEL.referenceDepth,
0,
1
);
}
function coverageB() {
return clamp(
(surfaceB() - MODEL.floorB) / MODEL.referenceDepth,
0,
1
);
}
function setEquilibriumVolumes() {
const commonSurface =
(
MODEL.totalVolume +
MODEL.areaA * MODEL.floorA +
MODEL.areaB * MODEL.floorB
) /
(MODEL.areaA + MODEL.areaB);
state.volumeA = MODEL.areaA * (commonSurface - MODEL.floorA);
state.volumeB = MODEL.totalVolume - state.volumeA;
}
function simulate(dt) {
const openingResponse = 1 - Math.exp(-dt * 8);
for (const gate of state.gates) {
gate.open += (gate.target - gate.open) * openingResponse;
if (Math.abs(gate.open - gate.target) < 0.0005) {
gate.open = gate.target;
}
}
const yA = surfaceA();
const yB = surfaceB();
const headDifference = yA - yB;
const absoluteHead = Math.abs(headDifference);
let q0 = 0;
let q1 = 0;
if (absoluteHead > 0.0001) {
const unitFlow =
MODEL.dischargeCoefficient *
MODEL.gateArea *
Math.sqrt(2 * MODEL.gravity * absoluteHead);
q0 = unitFlow * state.gates[0].open;
q1 = unitFlow * state.gates[1].open;
}
state.gates[0].flow = q0;
state.gates[1].flow = q1;
const totalFlow = q0 + q1;
if (totalFlow > 0) {
let transfer = totalFlow * dt * MODEL.timeScale;
if (headDifference > 0) {
transfer = Math.min(transfer, state.volumeA);
state.volumeA -= transfer;
} else {
transfer = Math.min(transfer, state.volumeB);
state.volumeA += transfer;
}
// Enforce the conserved total explicitly.
state.volumeB = MODEL.totalVolume - state.volumeA;
const newHeadDifference = surfaceA() - surfaceB();
// Prevent numerical overshoot from sending the exchange in reverse.
if (
headDifference * newHeadDifference < 0 ||
Math.abs(newHeadDifference) < 0.00001
) {
setEquilibriumVolumes();
}
}
state.elapsedModel += dt * MODEL.timeScale;
}
// -------------------------------------------------------------------------
// Visual updates.
// -------------------------------------------------------------------------
function updateStreamGeometry(gateVisual, yA, yB) {
const positions = gateVisual.streamGeometry.attributes.position.array;
const halfWidth = 0.82;
const z = gateVisual.z;
positions[0] = -0.17;
positions[1] = yA;
positions[2] = z - halfWidth;
positions[3] = -0.17;
positions[4] = yA;
positions[5] = z + halfWidth;
positions[6] = 0.17;
positions[7] = yB;
positions[8] = z + halfWidth;
positions[9] = -0.17;
positions[10] = yA;
positions[11] = z - halfWidth;
positions[12] = 0.17;
positions[13] = yB;
positions[14] = z + halfWidth;
positions[15] = 0.17;
positions[16] = yB;
positions[17] = z - halfWidth;
gateVisual.streamGeometry.attributes.position.needsUpdate = true;
}
function updateScene(elapsed) {
const yA = surfaceA();
const yB = surfaceB();
const coverages = [coverageA(), coverageB()];
basinDefs.forEach((def, index) => {
const surface = index === 0 ? yA : yB;
const scale = Math.sqrt(coverages[index]);
const visual = waterGroups[index];
visual.group.position.y = surface;
visual.group.scale.set(def.width * scale, 1, def.depth * scale);
visual.rippleMaterials.forEach((mat, i) => {
mat.opacity =
0.10 +
0.07 * (0.5 + 0.5 * Math.sin(elapsed * 1.4 + i * 1.3));
});
});
const direction = yA >= yB ? 1 : -1;
gateVisuals.forEach((visual, index) => {
const gate = state.gates[index];
visual.panel.position.y =
0.45 + visual.panelHeight / 2 + gate.open * 3.45;
visual.leftWater.position.y = yA + 0.025;
visual.rightWater.position.y = yB + 0.025;
updateStreamGeometry(visual, yA, yB);
const active = gate.flow > 0.002;
visual.stream.visible = active;
visual.streamMaterial.opacity = active
? clamp(0.2 + gate.flow * 0.1, 0.22, 0.78)
: 0;
visual.pulses.forEach((pulse, pulseIndex) => {
pulse.visible = active;
if (!active) return;
const phase = (elapsed * 1.65 + pulseIndex / 3) % 1;
const x =
direction > 0
? -0.16 + phase * 0.32
: 0.16 - phase * 0.32;
pulse.position.set(
x,
yA + (yB - yA) * phase + 0.06,
visual.z + (pulseIndex - 1) * 0.42
);
});
});
boat.position.x = -8 + Math.sin(elapsed * 0.12) * 4.2;
boat.position.z = -25 + Math.sin(elapsed * 0.09) * 0.65;
boat.rotation.y = Math.sin(elapsed * 0.12) * 0.08;
boat.rotation.z = Math.sin(elapsed * 0.55) * 0.018;
}
// -------------------------------------------------------------------------
// Interface and gate interaction.
// -------------------------------------------------------------------------
function setGateTarget(index, value) {
state.gates[index].target = clamp(value, 0, 1);
updateUI();
}
function toggleGate(index) {
setGateTarget(index, state.gates[index].target > 0 ? 0 : 1);
}
for (let i = 0; i < 2; i++) {
$(`gateRange${i}`).addEventListener("input", (event) => {
setGateTarget(i, Number(event.target.value) / 100);
});
$(`gateToggle${i}`).addEventListener("click", () => {
toggleGate(i);
});
}
$("openAll").addEventListener("click", () => {
state.gates.forEach((gate) => {
gate.target = 1;
});
updateUI();
});
$("closeAll").addEventListener("click", () => {
state.gates.forEach((gate) => {
gate.target = 0;
});
updateUI();
});
$("resetSplit").addEventListener("click", () => {
state.volumeA = MODEL.initialA;
state.volumeB = MODEL.initialB;
state.elapsedModel = 0;
state.gates.forEach((gate) => {
gate.open = 0;
gate.target = 0;
gate.flow = 0;
});
updateUI();
});
$("resetView").addEventListener("click", resetCamera);
function formatClock(seconds) {
const total = Math.floor(seconds);
const hours = Math.floor(total / 3600);
const minutes = Math.floor((total % 3600) / 60);
const secs = total % 60;
return [hours, minutes, secs]
.map((value) => String(value).padStart(2, "0"))
.join(":");
}
function updateUI() {
const covA = coverageA();
const covB = coverageB();
const percentA = covA * 100;
const percentB = covB * 100;
$("coverageA").textContent = `${percentA.toFixed(1)}%`;
$("coverageB").textContent = `${percentB.toFixed(1)}%`;
$("barA").style.width = `${percentA}%`;
$("barB").style.width = `${percentB}%`;
$("depthA").textContent = `${(surfaceA() - MODEL.floorA).toFixed(2)} m`;
$("depthB").textContent = `${(surfaceB() - MODEL.floorB).toFixed(2)} m`;
$("areaA").textContent = `${fmt.format(MODEL.areaA * covA)} m²`;
$("areaB").textContent = `${fmt.format(MODEL.areaB * covB)} m²`;
$("volumeA").textContent = `${fmt.format(state.volumeA)} m³`;
$("volumeB").textContent = `${fmt.format(state.volumeB)} m³`;
const difference = percentA - percentB;
if (Math.abs(difference) < 0.1) {
$("deltaText").textContent = "Near-identical water coverage";
} else if (difference > 0) {
$("deltaText").textContent = `A leads B by ${difference.toFixed(1)} coverage points`;
} else {
$("deltaText").textContent = `B leads A by ${Math.abs(difference).toFixed(1)} coverage points`;
}
const totalFlow = state.gates[0].flow + state.gates[1].flow;
const anyOpen = state.gates.some((gate) => gate.open > 0.002);
if (totalFlow > 0.005) {
const direction = surfaceA() > surfaceB() ? "A → B" : "B → A";
$("flowText").textContent =
`${direction} · ${totalFlow.toFixed(1)} m³/s model flow`;
} else if (anyOpen) {
$("flowText").textContent = "Near equal water surfaces; net flow has ceased";
} else {
$("flowText").textContent = "Gates closed — no transfer";
}
$("clockText").textContent =
`Model time ${formatClock(state.elapsedModel)} · clock ×24`;
for (let i = 0; i < 2; i++) {
const gate = state.gates[i];
const range = $(`gateRange${i}`);
const toggle = $(`gateToggle${i}`);
const card = $(`gateCard${i}`);
range.value = Math.round(gate.target * 100);
$(`gateOutput${i}`).textContent = `${Math.round(gate.open * 100)}%`;
toggle.textContent = gate.target > 0 ? `Close G${i + 1}` : `Open G${i + 1}`;
toggle.setAttribute("aria-pressed", gate.target > 0 ? "true" : "false");
card.classList.toggle("active", gate.target > 0);
}
}
// Raycasting is used only for clicking the visible gate panels.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let dragging = false;
let pointerId = null;
let lastPointerX = 0;
let lastPointerY = 0;
let pointerTravel = 0;
function pickGate(event) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
camera.updateMatrixWorld();
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(gatePickables, false);
return hits.length ? hits[0].object : null;
}
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
pointerId = event.pointerId;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
pointerTravel = 0;
canvas.setPointerCapture(event.pointerId);
canvas.classList.add("dragging");
});
canvas.addEventListener("pointermove", (event) => {
if (dragging && event.pointerId === pointerId) {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
pointerTravel += Math.abs(dx) + Math.abs(dy);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = clamp(cameraState.pitch + dy * 0.0045, 0.30, 1.27);
updateCamera();
} else {
const hit = pickGate(event);
canvas.style.cursor = hit ? "pointer" : "grab";
}
});
canvas.addEventListener("pointerup", (event) => {
if (!dragging || event.pointerId !== pointerId) return;
dragging = false;
canvas.classList.remove("dragging");
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
if (pointerTravel < 7) {
const hit = pickGate(event);
if (hit) {
toggleGate(hit.userData.gateIndex);
}
}
});
canvas.addEventListener("pointercancel", () => {
dragging = false;
canvas.classList.remove("dragging");
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = clamp(
cameraState.radius + event.deltaY * 0.045,
37,
103
);
updateCamera();
},
{ passive: false }
);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// -------------------------------------------------------------------------
// Animation loop.
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let uiTimer = 0;
updateUI();
renderer.setAnimationLoop(() => {
const dt = Math.min(clock.getDelta(), 0.05);
simulate(dt);
updateScene(state.elapsedModel);
uiTimer += dt;
if (uiTimer > 0.075) {
updateUI();
uiTimer = 0;
}
renderer.render(scene, camera);
});
$("loading")?.remove();
</script>
</body>
</html>
```