Prompt specification
Build or customize the Three.js 3D scene "Small Settlement Water Allocation" 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: Small Settlement Water Allocation
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/small-settlement-water-allocation-x3558
Scene Description Prompt:
Make a voxel Three.js scene in a self-contained HTML file using cdnjs: small settlement water allocation. Animate households drawing from a limited reservoir each round. Separate stored water, inflow, and unmet demand, and never create resources merely because more houses appear.
Working Three.js Starter (small-settlement-water-allocation-x3558):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Dewdrop Settlement — Voxel Water Allocation</title>
<style>
:root {
color-scheme: dark;
--ink: #eaf8f4;
--muted: #93aaa8;
--panel: rgba(9, 24, 29, 0.91);
--line: rgba(180, 230, 220, 0.14);
--blue: #45c7e6;
--blue-soft: #a9edff;
--green: #77e0a0;
--sand: #e4bd77;
--red: #ff746c;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #08151b;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button {
font: inherit;
}
#scene,
#labels {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
#labels {
pointer-events: none;
overflow: hidden;
}
.world-label {
position: absolute;
left: 0;
top: 0;
padding: 6px 9px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 8px;
background: rgba(5, 18, 23, 0.82);
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.22);
color: white;
font-size: 10px;
line-height: 1.25;
letter-spacing: 0.06em;
text-transform: uppercase;
white-space: nowrap;
transform: translate(-1000px, -1000px);
}
.world-label b {
display: block;
color: var(--blue-soft);
font-size: 11px;
}
.world-label span {
color: #c8d9d7;
}
.world-label.reservoir {
border-color: rgba(69, 199, 230, 0.35);
}
.brand {
position: fixed;
top: 22px;
left: 24px;
z-index: 5;
max-width: 430px;
pointer-events: none;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.45);
}
.eyebrow {
margin-bottom: 7px;
color: var(--blue-soft);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
.brand h1 {
margin: 0;
font-size: clamp(25px, 3vw, 42px);
font-weight: 780;
line-height: 1;
letter-spacing: -0.04em;
}
.brand p {
max-width: 390px;
margin: 10px 0 0;
color: #b7cbc8;
font-size: 13px;
line-height: 1.5;
}
.panel {
position: fixed;
z-index: 6;
top: 20px;
right: 20px;
width: 350px;
max-height: calc(100vh - 40px);
overflow: auto;
padding: 17px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.34);
backdrop-filter: blur(16px);
}
.panel::-webkit-scrollbar {
width: 6px;
}
.panel::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.12);
border-radius: 8px;
}
.panel-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.round-pill {
display: inline-flex;
align-items: center;
min-height: 27px;
padding: 0 10px;
border: 1px solid rgba(69, 199, 230, 0.28);
border-radius: 999px;
background: rgba(69, 199, 230, 0.08);
color: var(--blue-soft);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.status {
color: var(--muted);
font-size: 11px;
text-align: right;
}
.status::before {
content: "";
display: inline-block;
width: 6px;
height: 6px;
margin-right: 6px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 10px rgba(119, 224, 160, 0.6);
vertical-align: 1px;
}
.status.busy::before {
background: var(--sand);
box-shadow: 0 0 10px rgba(228, 189, 119, 0.65);
}
.stored-card {
padding: 14px;
border: 1px solid rgba(69, 199, 230, 0.19);
border-radius: 13px;
background:
linear-gradient(135deg, rgba(69, 199, 230, 0.1), transparent),
rgba(255, 255, 255, 0.025);
}
.stored-head {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
}
.label {
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.stored-number {
margin-top: 3px;
font-size: 31px;
font-weight: 780;
line-height: 1;
letter-spacing: -0.05em;
}
.stored-number small {
color: var(--muted);
font-size: 12px;
font-weight: 650;
letter-spacing: 0;
}
.capacity {
color: var(--muted);
font-size: 10px;
text-align: right;
}
.bar {
height: 7px;
margin-top: 13px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.08);
}
.bar > div {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #229fc7, var(--blue));
box-shadow: 0 0 15px rgba(69, 199, 230, 0.4);
transition: width 120ms linear;
}
.metric-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
margin-top: 10px;
}
.metric {
min-height: 69px;
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.025);
}
.metric .value {
margin-top: 5px;
font-size: 20px;
font-weight: 760;
line-height: 1;
}
.metric .value small {
color: var(--muted);
font-size: 10px;
font-weight: 650;
}
.metric.inflow .value {
color: var(--blue);
}
.metric.delivered .value {
color: var(--green);
}
.metric.unmet .value {
color: var(--red);
}
.balance {
margin-top: 10px;
padding: 11px 12px;
border-left: 3px solid var(--green);
border-radius: 5px 10px 10px 5px;
background: rgba(119, 224, 160, 0.06);
}
.balance-title {
color: #b8d7c8;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
#balanceEquation {
margin-top: 6px;
color: #e7f7ef;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
line-height: 1.55;
}
#unmetNote {
margin-top: 5px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.history {
margin-top: 14px;
}
.history-head {
display: grid;
grid-template-columns: 34px 1fr 36px 36px 36px;
gap: 4px;
padding-bottom: 6px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.history-head span:not(:first-child) {
text-align: right;
}
.history-row {
display: grid;
grid-template-columns: 34px 1fr 36px 36px 36px;
align-items: center;
gap: 4px;
padding: 7px 0;
border-top: 1px solid rgba(255, 255, 255, 0.055);
color: #c8d7d4;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
}
.history-row span:not(:first-child) {
text-align: right;
}
.history-row .inflow {
color: var(--blue);
}
.history-row .delivered {
color: var(--green);
}
.history-row .unmet {
color: var(--red);
}
.empty-history {
padding: 10px 0;
color: var(--muted);
font-size: 11px;
}
.rule {
margin-top: 13px;
padding: 11px;
border: 1px dashed rgba(228, 189, 119, 0.27);
border-radius: 10px;
color: #d8c6a8;
font-size: 10px;
line-height: 1.55;
}
.rule strong {
color: #f2d7a8;
}
.controls {
position: fixed;
z-index: 7;
bottom: 20px;
left: 50%;
display: flex;
align-items: center;
gap: 9px;
padding: 8px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(8, 24, 29, 0.9);
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.3);
transform: translateX(-50%);
backdrop-filter: blur(14px);
}
.controls button {
min-height: 42px;
padding: 0 16px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 9px;
background: rgba(255, 255, 255, 0.055);
color: #d6e5e2;
cursor: pointer;
font-size: 12px;
font-weight: 750;
transition:
transform 120ms ease,
background 120ms ease,
opacity 120ms ease;
}
.controls button:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.11);
transform: translateY(-1px);
}
.controls button.primary {
min-width: 132px;
border-color: rgba(69, 199, 230, 0.38);
background: var(--blue);
color: #062027;
}
.controls button:disabled {
cursor: wait;
opacity: 0.48;
}
.event {
position: fixed;
z-index: 5;
left: 24px;
bottom: 24px;
max-width: 380px;
padding: 11px 13px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(8, 24, 29, 0.8);
color: #b9cac7;
font-size: 11px;
line-height: 1.5;
pointer-events: none;
backdrop-filter: blur(12px);
}
.event strong {
color: var(--ink);
}
.hint {
position: fixed;
z-index: 4;
right: 24px;
bottom: 24px;
color: rgba(210, 230, 225, 0.58);
font-size: 10px;
letter-spacing: 0.05em;
pointer-events: none;
}
@media (max-width: 780px) {
.brand {
top: 14px;
left: 14px;
max-width: 52%;
}
.brand h1 {
font-size: 25px;
}
.brand p {
display: none;
}
.panel {
top: auto;
right: 12px;
bottom: 78px;
left: 12px;
width: auto;
max-height: 44vh;
padding: 13px;
}
.history,
.rule {
display: none;
}
.controls {
bottom: 12px;
}
.event,
.hint {
display: none;
}
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive voxel water allocation settlement"></div>
<div id="labels" aria-hidden="true"></div>
<header class="brand">
<div class="eyebrow">Shared-resource simulation</div>
<h1>Dewdrop Settlement</h1>
<p>
One shared reservoir. Fair household draws. Stored water, rainfall inflow,
and unmet demand are always tracked separately.
</p>
</header>
<aside class="panel" aria-label="Water allocation ledger">
<div class="panel-head">
<span class="round-pill" id="roundNumber">Round 0</span>
<span class="status" id="statusText">Ready</span>
</div>
<section class="stored-card">
<div class="stored-head">
<div>
<div class="label">Water remaining in reservoir</div>
<div class="stored-number">
<span id="storedValue">24</span> <small>m³</small>
</div>
</div>
<div class="capacity">
Capacity<br /><strong id="capacityValue">160 m³</strong>
</div>
</div>
<div class="bar"><div id="storedBar"></div></div>
</section>
<section class="metric-grid">
<div class="metric inflow">
<div class="label">Inflow this round</div>
<div class="value"><span id="inflowValue">0</span> <small>m³</small></div>
</div>
<div class="metric">
<div class="label">Household demand</div>
<div class="value"><span id="demandValue">0</span> <small>m³</small></div>
</div>
<div class="metric delivered">
<div class="label">Delivered</div>
<div class="value"><span id="deliveredValue">0</span> <small>m³</small></div>
</div>
<div class="metric unmet">
<div class="label">Unmet demand</div>
<div class="value"><span id="unmetValue">0</span> <small>m³</small></div>
</div>
</section>
<section class="balance">
<div class="balance-title">Conservation check</div>
<div id="balanceEquation">
24 initial + 0 inflow = 24 stored + 0 delivered
</div>
<div id="unmetNote">
Unmet demand is not water and never enters the reservoir balance.
</div>
</section>
<section class="history">
<div class="history-head">
<span>Round</span>
<span></span>
<span>In</span>
<span>Out</span>
<span>Unmet</span>
</div>
<div id="history">
<div class="empty-history">No rounds completed yet.</div>
</div>
</section>
<div class="rule">
<strong>Conservation rule:</strong> new homes add demand only.
Rainfall inflow comes from a fixed round schedule, never from the number
of houses.
</div>
</aside>
<div class="controls">
<button id="resetButton" type="button">Reset</button>
<button id="runButton" class="primary" type="button">Run round 1</button>
</div>
<div class="event" id="eventText" aria-live="polite">
<strong>Initial endowment:</strong> 24 m³. Future rainfall is scheduled
independently of household count.
</div>
<div class="hint">Drag to orbit · Wheel to zoom · Arrow keys to rotate</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Simulation constants
// ------------------------------------------------------------
const INITIAL_STORED = 24;
const RESERVOIR_CAPACITY = 160;
const DEMAND_PER_HOUSEHOLD = 7;
// This schedule is independent of household count.
const INFLOW_SCHEDULE = [14, 12, 16, 10, 18, 13, 15, 9, 17, 11];
// A new household joins on rounds 3, 6, and 8.
// Joining changes demand only; it never changes stored water or inflow.
const HOUSEHOLD_SCHEDULE = [2, 2, 3, 3, 3, 4, 4, 5, 5, 5];
const HOUSE_POSITIONS = [
new THREE.Vector3(4.0, 0, -5.0),
new THREE.Vector3(7.0, 0, -5.0),
new THREE.Vector3(4.0, 0, 0.0),
new THREE.Vector3(7.0, 0, 0.0),
new THREE.Vector3(4.0, 0, 5.0)
];
const state = {
round: 0,
stored: INITIAL_STORED,
totalInflow: 0,
totalDelivered: 0,
totalUnmet: 0,
totalDemand: 0,
lastRecord: {
inflow: 0,
demand: 0,
delivered: 0,
unmet: 0
},
records: []
};
let visualStored = INITIAL_STORED;
let roundAnimation = null;
// ------------------------------------------------------------
// DOM references
// ------------------------------------------------------------
const sceneHost = document.getElementById("scene");
const labelsHost = document.getElementById("labels");
const ui = {
roundNumber: document.getElementById("roundNumber"),
statusText: document.getElementById("statusText"),
storedValue: document.getElementById("storedValue"),
storedBar: document.getElementById("storedBar"),
capacityValue: document.getElementById("capacityValue"),
inflowValue: document.getElementById("inflowValue"),
demandValue: document.getElementById("demandValue"),
deliveredValue: document.getElementById("deliveredValue"),
unmetValue: document.getElementById("unmetValue"),
balanceEquation: document.getElementById("balanceEquation"),
unmetNote: document.getElementById("unmetNote"),
history: document.getElementById("history"),
eventText: document.getElementById("eventText"),
runButton: document.getElementById("runButton"),
resetButton: document.getElementById("resetButton")
};
ui.capacityValue.textContent = `${RESERVOIR_CAPACITY} m³`;
// ------------------------------------------------------------
// Three.js setup
// ------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x091920);
scene.fog = new THREE.Fog(0x091920, 31, 67);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
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.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
sceneHost.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xbfe9f4, 0x314237, 1.8);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff0cf, 3.1);
sun.position.set(8, 18, 12);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -18;
sun.shadow.camera.right = 18;
sun.shadow.camera.top = 16;
sun.shadow.camera.bottom = -16;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 50;
sun.shadow.bias = -0.0004;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x66cce8, 0.55);
fill.position.set(-12, 8, -9);
scene.add(fill);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const materialCache = new Map();
function getMaterial(color) {
if (color && color.isMaterial) return color;
if (!materialCache.has(color)) {
materialCache.set(
color,
new THREE.MeshStandardMaterial({
color,
roughness: 0.86,
metalness: 0.02
})
);
}
return materialCache.get(color);
}
function box(parent, sx, sy, sz, color, x = 0, y = 0, z = 0) {
const mesh = new THREE.Mesh(unitBox, getMaterial(color));
mesh.scale.set(sx, sy, sz);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// ------------------------------------------------------------
// Ground and paths
// ------------------------------------------------------------
box(scene, 24.4, 0.62, 18.4, 0x243d38, 0, -0.39, 0);
const tileGeometry = new THREE.BoxGeometry(1, 1, 1);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 1,
vertexColors: true
});
const tileColumns = 12;
const tileRows = 9;
const tileMesh = new THREE.InstancedMesh(
tileGeometry,
tileMaterial,
tileColumns * tileRows
);
const dummy = new THREE.Object3D();
const tilePalette = [0x345348, 0x3b594d, 0x304c43, 0x405d50];
let tileIndex = 0;
for (let row = 0; row < tileRows; row++) {
for (let col = 0; col < tileColumns; col++) {
const x = -11 + col * 2;
const z = -8 + row * 2;
dummy.position.set(x, -0.03, z);
dummy.scale.set(1.92, 0.16, 1.92);
dummy.updateMatrix();
tileMesh.setMatrixAt(tileIndex, dummy.matrix);
tileMesh.setColorAt(
tileIndex,
new THREE.Color(tilePalette[(row * 7 + col * 3) % tilePalette.length])
);
tileIndex++;
}
}
tileMesh.instanceMatrix.needsUpdate = true;
tileMesh.instanceColor.needsUpdate = true;
tileMesh.receiveShadow = true;
scene.add(tileMesh);
// Walkways connect the distribution point to each household row.
const pathMaterial = 0xa98b61;
for (const z of [-3.4, 1.6, 6.6]) {
box(scene, 10.2, 0.08, 0.82, pathMaterial, 3.8, 0.08, z);
}
box(scene, 0.82, 0.08, 10.8, pathMaterial, -1.25, 0.085, 1.6);
// ------------------------------------------------------------
// Voxel reservoir
// ------------------------------------------------------------
const reservoir = new THREE.Group();
reservoir.position.x = -5.5;
scene.add(reservoir);
box(reservoir, 7.3, 0.45, 5.4, 0x263e42, 0, 0.24, 0);
// Back and side walls are taller; the front wall is lower for visibility.
box(reservoir, 7.4, 2.55, 0.42, 0x6d8584, 0, 1.45, -2.6);
box(reservoir, 0.42, 2.3, 5.0, 0x6d8584, -3.48, 1.3, 0);
box(reservoir, 0.42, 2.3, 5.0, 0x5f7776, 3.48, 1.3, 0);
box(reservoir, 7.4, 0.9, 0.42, 0x526c6c, 0, 0.62, 2.6);
box(reservoir, 6.35, 0.12, 4.45, 0x17373d, 0, 0.43, 0);
const reservoirWaterCells = [];
const waterX = [-2.25, -0.75, 0.75, 2.25];
const waterZ = [-1.32, 0, 1.32];
for (const x of waterX) {
for (const z of waterZ) {
const cell = box(
reservoir,
1.39,
0.1,
1.22,
0x28a9d1,
x,
0.48,
z
);
cell.castShadow = false;
reservoirWaterCells.push(cell);
}
}
function updateReservoirWater(amount) {
const ratio = THREE.MathUtils.clamp(
amount / RESERVOIR_CAPACITY,
0,
1
);
const height = ratio * 1.9;
for (const cell of reservoirWaterCells) {
cell.visible = height > 0.015;
cell.scale.y = Math.max(0.025, height);
cell.position.y = 0.5 + cell.scale.y / 2;
}
}
// Voxel intake tower.
box(reservoir, 0.8, 2.7, 0.8, 0x718c87, 2.85, 1.62, -1.85);
box(reservoir, 1.2, 0.35, 1.2, 0x8ea6a0, 2.85, 3.05, -1.85);
box(reservoir, 0.35, 0.75, 0.35, 0x1e4650, 3.25, 2.35, -1.45);
// ------------------------------------------------------------
// Rain cloud above the reservoir
// ------------------------------------------------------------
const rainCloud = new THREE.Group();
rainCloud.position.set(-5.5, 6.4, 0.2);
rainCloud.visible = false;
scene.add(rainCloud);
const cloudMaterial = new THREE.MeshStandardMaterial({
color: 0xcbdfe0,
roughness: 1
});
box(rainCloud, 3.0, 0.8, 1.25, cloudMaterial, 0, 0, 0);
box(rainCloud, 1.4, 1.1, 1.0, cloudMaterial, -0.85, 0.45, 0);
box(rainCloud, 1.2, 1.35, 1.15, cloudMaterial, 0.2, 0.55, -0.05);
box(rainCloud, 1.5, 0.75, 0.95, cloudMaterial, 1.35, 0.1, 0);
const rainDrops = [];
for (let i = 0; i < 10; i++) {
const drop = box(
rainCloud,
0.09,
0.33,
0.09,
0x5fd7f1,
-1.65 + (i % 5) * 0.8,
-1,
-0.45 + Math.floor(i / 5) * 0.85
);
drop.castShadow = false;
rainDrops.push(drop);
}
// ------------------------------------------------------------
// Shared distribution point
// ------------------------------------------------------------
const distributionPoint = new THREE.Group();
distributionPoint.position.set(-1.25, 0, 0);
scene.add(distributionPoint);
box(distributionPoint, 2.0, 0.22, 2.0, 0x768b82, 0, 0.17, 0);
box(distributionPoint, 0.85, 0.9, 0.85, 0x37545c, -0.3, 0.73, -0.45);
box(distributionPoint, 0.95, 0.22, 0.95, 0x67d0e7, -0.3, 1.28, -0.45);
box(distributionPoint, 0.22, 1.2, 0.22, 0x81958f, 0.65, 0.82, 0.45);
box(distributionPoint, 1.35, 0.55, 0.16, 0x718984, 0.65, 1.43, 0.45);
// ------------------------------------------------------------
// Settlement decorations
// ------------------------------------------------------------
function makeTree(x, z, scale = 1) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
box(tree, 0.42, 1.7, 0.42, 0x6f5039, 0, 0.85, 0);
box(tree, 1.8, 1.0, 1.7, 0x2f6950, 0, 2.0, 0);
box(tree, 1.3, 0.9, 1.3, 0x3b7c59, -0.25, 2.7, 0.1);
box(tree, 1.05, 0.75, 1.05, 0x478b61, 0.55, 2.45, -0.2);
scene.add(tree);
}
[
[-10.2, -7.0, 1.05],
[-10.0, 6.8, 0.9],
[-2.0, -7.1, 0.75],
[0.0, 7.0, 0.72],
[9.7, 6.8, 1.0],
[10.0, -6.8, 0.85],
[10.0, 0.0, 0.65]
].forEach(([x, z, s]) => makeTree(x, z, s));
function makeRock(x, z, scale = 1) {
const rock = new THREE.Group();
rock.position.set(x, 0, z);
rock.scale.setScalar(scale);
box(rock, 0.95, 0.55, 0.75, 0x6b7972, 0, 0.28, 0);
box(rock, 0.55, 0.42, 0.48, 0x829087, 0.38, 0.58, 0.05);
scene.add(rock);
}
makeRock(-10.5, 2.5, 0.75);
makeRock(9.7, -2.7, 0.65);
makeRock(1.0, -7.3, 0.55);
// Distant voxel hills.
for (let i = 0; i < 7; i++) {
const hillHeight = 1.2 + (i % 3) * 0.55;
box(
scene,
4.5,
hillHeight,
2.3,
i % 2 ? 0x233d3b : 0x294641,
-11 + i * 3.6,
hillHeight / 2 - 0.15,
-9.6
);
}
// ------------------------------------------------------------
// Households and animated walkers
// ------------------------------------------------------------
const houses = [];
const people = [];
const worldLabels = [];
function addWorldLabel(className) {
const element = document.createElement("div");
element.className = `world-label ${className}`;
labelsHost.appendChild(element);
worldLabels.push(element);
return element;
}
const reservoirLabel = addWorldLabel("reservoir");
reservoirLabel.innerHTML =
"<b>Shared reservoir</b><span>24 m³ stored</span>";
function createPerson(house, index) {
const group = new THREE.Group();
scene.add(group);
box(group, 0.18, 0.43, 0.2, 0x263b4b, -0.13, 0.28, 0);
box(group, 0.18, 0.43, 0.2, 0x263b4b, 0.13, 0.28, 0);
box(group, 0.43, 0.52, 0.3, index % 2 ? 0xd96f55 : 0x3f9b9a, 0, 0.74, 0);
box(group, 0.33, 0.33, 0.33, 0xe9b88c, 0, 1.18, 0);
box(group, 0.12, 0.4, 0.12, 0xe9b88c, -0.28, 0.72, 0);
const bucket = new THREE.Group();
bucket.position.set(0.42, 0.43, 0.04);
group.add(bucket);
box(bucket, 0.32, 0.34, 0.32, 0x526a70, 0, 0, 0);
const bucketFill = box(
bucket,
0.25,
0.08,
0.25,
0x36c3e4,
0,
0.13,
0
);
bucketFill.visible = false;
const unmetBadge = box(
group,
0.18,
0.18,
0.18,
0xff5d58,
0,
1.56,
0
);
unmetBadge.visible = false;
const start = new THREE.Vector3(
house.position.x,
0.08,
house.position.z + 1.65
);
const outwardRoute = [
start.clone(),
new THREE.Vector3(house.position.x - 2.0, 0.08, house.position.z + 1.65),
new THREE.Vector3(-1.25, 0.08, house.position.z + 1.65),
new THREE.Vector3(-1.25, 0.08, 0)
];
group.position.copy(start);
const person = {
group,
bucketFill,
unmetBadge,
house,
start,
outwardRoute,
allocation: 0,
unmet: DEMAND_PER_HOUSEHOLD,
arrived: false
};
people.push(person);
return person;
}
function addHouse(index, animateBirth = true) {
const position = HOUSE_POSITIONS[index];
const house = new THREE.Group();
house.position.copy(position);
scene.add(house);
box(house, 2.75, 0.25, 2.65, 0x5e665c, 0, 0.14, 0);
box(house, 2.4, 1.65, 2.3, 0xe3d4b6, 0, 1.08, 0);
// Stepped voxel roof.
box(house, 2.85, 0.3, 2.7, 0x9f4f3f, 0, 2.02, 0);
box(house, 2.25, 0.3, 2.1, 0xb65d48, 0, 2.32, 0);
box(house, 1.45, 0.3, 1.35, 0xc76d52, 0, 2.62, 0);
box(house, 0.55, 1.08, 0.08, 0x526c68, 0, 0.67, 1.18);
box(house, 0.54, 0.5, 0.08, 0x75c9dc, 0.7, 1.22, 1.19);
box(house, 0.08, 0.5, 0.54, 0x75c9dc, -1.22, 1.22, 0.55);
box(house, 0.38, 0.85, 0.38, 0x725b4d, 0.72, 2.9, -0.48);
// Small household cistern.
box(house, 0.58, 0.8, 0.58, 0x4d6264, -1.58, 0.5, 0.38);
const cisternWater = box(
house,
0.42,
0.08,
0.42,
0x35b9dc,
-1.58,
0.18,
0.38
);
cisternWater.visible = false;
const lampMaterial = new THREE.MeshStandardMaterial({
color: 0x77e0a0,
emissive: 0x77e0a0,
emissiveIntensity: 0.45,
roughness: 0.5
});
const statusLamp = box(
house,
0.18,
0.18,
0.18,
lampMaterial,
0.98,
2.53,
0.62
);
const label = addWorldLabel("house");
label.innerHTML = `<b>House ${index + 1}</b><span>Needs 7 m³</span>`;
const houseData = {
index,
group: house,
position: position.clone(),
cisternWater,
cisternLevel: 0,
cisternTarget: 0,
statusLamp,
label,
bornAt: animateBirth ? performance.now() : performance.now() - 1000
};
house.scale.setScalar(animateBirth ? 0.001 : 1);
houses.push(houseData);
createPerson(houseData, index);
return houseData;
}
function removeAllHouseholds() {
for (const house of houses) {
scene.remove(house.group);
house.label.remove();
}
for (const person of people) {
scene.remove(person.group);
}
houses.length = 0;
people.length = 0;
while (worldLabels.length > 1) {
worldLabels.pop().remove();
}
}
addHouse(0);
addHouse(1);
// ------------------------------------------------------------
// Direct camera controls: orbit, zoom, keyboard
// ------------------------------------------------------------
const controls = {
theta: 0.58,
phi: 0.93,
radius: 30,
targetTheta: 0.58,
targetPhi: 0.93,
targetRadius: 30,
dragging: false,
lastX: 0,
lastY: 0
};
const canvas = renderer.domElement;
canvas.addEventListener("pointerdown", (event) => {
controls.dragging = true;
controls.lastX = event.clientX;
controls.lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!controls.dragging) return;
const dx = event.clientX - controls.lastX;
const dy = event.clientY - controls.lastY;
controls.lastX = event.clientX;
controls.lastY = event.clientY;
controls.targetTheta -= dx * 0.006;
controls.targetPhi = THREE.MathUtils.clamp(
controls.targetPhi - dy * 0.005,
0.42,
1.34
);
});
function endDrag(event) {
controls.dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
controls.targetRadius = THREE.MathUtils.clamp(
controls.targetRadius + event.deltaY * 0.018,
19,
43
);
},
{ passive: false }
);
window.addEventListener("keydown", (event) => {
if (event.key === "ArrowLeft") controls.targetTheta -= 0.08;
if (event.key === "ArrowRight") controls.targetTheta += 0.08;
if (event.key === "ArrowUp") {
controls.targetPhi = Math.max(0.42, controls.targetPhi - 0.06);
}
if (event.key === "ArrowDown") {
controls.targetPhi = Math.min(1.34, controls.targetPhi + 0.06);
}
});
function updateCamera(dt) {
const smoothing = 1 - Math.exp(-dt * 9);
controls.theta = THREE.MathUtils.lerp(
controls.theta,
controls.targetTheta,
smoothing
);
controls.phi = THREE.MathUtils.lerp(
controls.phi,
controls.targetPhi,
smoothing
);
controls.radius = THREE.MathUtils.lerp(
controls.radius,
controls.targetRadius,
smoothing
);
const sinPhi = Math.sin(controls.phi);
camera.position.set(
Math.sin(controls.targetTheta) * sinPhi * controls.radius,
Math.cos(controls.phi) * controls.radius,
Math.cos(controls.targetTheta) * sinPhi * controls.radius
);
camera.lookAt(0, 0.8, 0);
}
// ------------------------------------------------------------
// Allocation logic
// ------------------------------------------------------------
function targetHouseholdCount(round) {
return HOUSEHOLD_SCHEDULE[
Math.min(round - 1, HOUSEHOLD_SCHEDULE.length - 1)
];
}
function inflowForRound(round) {
return INFLOW_SCHEDULE[(round - 1) % INFLOW_SCHEDULE.length];
}
function fairAllocations(available, householdCount, round) {
const totalDemand = householdCount * DEMAND_PER_HOUSEHOLD;
if (available >= totalDemand) {
return Array(householdCount).fill(DEMAND_PER_HOUSEHOLD);
}
const base = Math.floor(available / householdCount);
const remainder = available % householdCount;
const allocations = Array.from({ length: householdCount }, (_, i) =>
Math.min(
DEMAND_PER_HOUSEHOLD,
base + (i < remainder ? 1 : 0)
)
);
// Rotate the small remainder between rounds so no home is favored.
const offset = (round - 1) % householdCount;
return allocations.map((_, i) => allocations[(i + offset) % householdCount]);
}
function pointAlongRoute(route, t) {
const clamped = THREE.MathUtils.clamp(t, 0, 1);
const lengths = [];
let totalLength = 0;
for (let i = 0; i < route.length - 1; i++) {
const length = route[i].distanceTo(route[i + 1]);
lengths.push(length);
totalLength += length;
}
let distance = clamped * totalLength;
for (let i = 0; i < lengths.length; i++) {
if (distance <= lengths[i] || i === lengths.length - 1) {
const segmentT = lengths[i] === 0 ? 0 : distance / lengths[i];
return route[i].clone().lerp(route[i + 1], segmentT);
}
distance -= lengths[i];
}
return route[route.length - 1].clone();
}
function setPersonAllocation(person, allocation) {
person.allocation = allocation;
person.unmet = DEMAND_PER_HOUSEHOLD - allocation;
person.arrived = false;
person.bucketFill.visible = false;
person.unmetBadge.visible = false;
const fillHeight = Math.max(0.05, (allocation / DEMAND_PER_HOUSEHOLD) * 0.35);
person.bucketFill.scale.y = fillHeight;
person.bucketFill.position.y = 0.1 + fillHeight / 2;
}
function runRound() {
if (roundAnimation) return;
state.round += 1;
const desiredHouseholds = targetHouseholdCount(state.round);
let newHouseholds = 0;
// IMPORTANT:
// Adding a household changes ONLY the household list and future demand.
// It must never add to state.stored, state.totalInflow, or water cells.
while (people.length < desiredHouseholds) {
addHouse(people.length, true);
newHouseholds++;
}
const householdCount = people.length;
const totalDemand = householdCount * DEMAND_PER_HOUSEHOLD;
const inflow = inflowForRound(state.round);
const availableForDrawing = state.stored + inflow;
const allocations = fairAllocations(
availableForDrawing,
householdCount,
state.round
);
const totalDelivered = allocations.reduce((sum, value) => sum + value, 0);
const totalUnmet = totalDemand - totalDelivered;
const finalStock = availableForDrawing - totalDelivered;
allocations.forEach((allocation, index) => {
setPersonAllocation(people[index], allocation);
people[index].house.cisternTarget = 0;
people[index].house.label.innerHTML =
`<b>House ${index + 1}</b><span>Needs 7 m³</span>`;
});
const start = performance.now();
const drawStart = 700;
const stagger = 330;
const tripDuration = 1650;
roundAnimation = {
start,
drawStart,
stagger,
tripDuration,
inflow,
totalDemand,
totalDelivered,
totalUnmet,
finalStock,
targetStock: state.stored + inflow,
phase: "inflow",
newHouseholds
};
ui.runButton.disabled = true;
ui.resetButton.disabled = true;
ui.statusText.textContent = "Rainfall inflow arriving";
ui.statusText.classList.add("busy");
if (newHouseholds > 0) {
ui.eventText.innerHTML =
`<strong>Round ${state.round}:</strong> ${newHouseholds} new ` +
`household${newHouseholds === 1 ? "" : "s"} joined. ` +
`Demand increased by ${newHouseholds * DEMAND_PER_HOUSEHOLD} m³; ` +
`inflow remains ${inflow} m³.`;
} else {
ui.eventText.innerHTML =
`<strong>Round ${state.round}:</strong> ${inflow} m³ of scheduled ` +
`rainfall enters the reservoir. ${householdCount} households ` +
`request ${totalDemand} m³.`;
}
updateUI();
}
function finishRound() {
if (!roundAnimation) return;
const animation = roundAnimation;
state.stored = animation.finalStock;
state.totalInflow += animation.inflow;
state.totalDelivered += animation.totalDelivered;
state.totalUnmet += animation.totalUnmet;
state.totalDemand += animation.totalDemand;
state.lastRecord = {
inflow: animation.inflow,
demand: animation.totalDemand,
delivered: animation.totalDelivered,
unmet: animation.totalUnmet
};
state.records.push({ round: state.round, ...state.lastRecord });
visualStored = state.stored;
updateReservoirWater(visualStored);
rainCloud.visible = false;
roundAnimation = null;
// Hard conservation invariant:
// initial stored + all actual inflow = remaining stored + all delivered.
// Unmet demand is deliberately excluded because it was never supplied.
console.assert(
Math.abs(
state.stored +
state.totalDelivered -
(INITIAL_STORED + state.totalInflow)
) < 0.000001,
"Water conservation invariant failed"
);
ui.runButton.disabled = false;
ui.resetButton.disabled = false;
ui.statusText.textContent = "Ready for next round";
ui.statusText.classList.remove("busy");
if (animation.totalUnmet > 0) {
ui.eventText.innerHTML =
`<strong>Round ${state.round} complete:</strong> ` +
`${animation.totalDelivered} m³ delivered; ` +
`<strong>${animation.totalUnmet} m³ unmet</strong>. ` +
`Unmet demand did not reduce the reservoir because no water was delivered.`;
} else {
ui.eventText.innerHTML =
`<strong>Round ${state.round} complete:</strong> all ` +
`${animation.totalDemand} m³ of demand was met. ` +
`The reservoir balance remains exact.`;
}
updateUI();
updateHistory();
}
// ------------------------------------------------------------
// UI rendering
// ------------------------------------------------------------
function updateStoredReadout() {
const amount = roundAnimation ? visualStored : state.stored;
ui.storedValue.textContent = Math.round(amount);
ui.storedBar.style.width =
`${THREE.MathUtils.clamp(amount / RESERVOIR_CAPACITY, 0, 1) * 100}%`;
}
function updateUI() {
const active = roundAnimation;
const record = active
? {
inflow: active.inflow,
demand: active.totalDemand,
delivered: active.totalDelivered,
unmet: active.totalUnmet
}
: state.lastRecord;
const projectedInflow = state.totalInflow + (active ? active.inflow : 0);
const projectedDelivered = state.totalDelivered + (active ? active.totalDelivered : 0);
const projectedUnmet = state.totalUnmet + (active ? active.totalUnmet : 0);
const projectedStored = active
? active.finalStock
: state.stored;
ui.roundNumber.textContent = `Round ${state.round}`;
ui.inflowValue.textContent = record.inflow;
ui.demandValue.textContent = record.demand;
ui.deliveredValue.textContent = record.delivered;
ui.unmetValue.textContent = record.unmet;
ui.balanceEquation.textContent =
`${INITIAL_STORED} initial + ${projectedInflow} inflow = ` +
`${projectedStored} stored + ${projectedDelivered} delivered`;
ui.unmetNote.textContent =
`Cumulative unmet demand: ${projectedUnmet} m³. ` +
`It is tracked as demand, never inserted into the water balance.`;
ui.runButton.textContent = active
? "Allocating…"
: `Run round ${state.round + 1}`;
updateStoredReadout();
}
function updateHistory() {
if (!state.records.length) {
ui.history.innerHTML =
'<div class="empty-history">No rounds completed yet.</div>';
return;
}
ui.history.innerHTML = state.records
.slice(-6)
.reverse()
.map(
(record) => `
<div class="history-row">
<span>R${record.round}</span>
<span></span>
<span class="inflow">${record.inflow}</span>
<span class="delivered">${record.delivered}</span>
<span class="unmet">${record.unmet}</span>
</div>
`
)
.join("");
}
ui.runButton.addEventListener("click", runRound);
ui.resetButton.addEventListener("click", () => {
if (roundAnimation) return;
removeAllHouseholds();
state.round = 0;
state.stored = INITIAL_STORED;
state.totalInflow = 0;
state.totalDelivered = 0;
state.totalUnmet = 0;
state.totalDemand = 0;
state.lastRecord = {
inflow: 0,
demand: 0,
delivered: 0,
unmet: 0
};
state.records = [];
visualStored = INITIAL_STORED;
updateReservoirWater(visualStored);
addHouse(0);
addHouse(1);
ui.statusText.textContent = "Ready";
ui.statusText.classList.remove("busy");
ui.eventText.innerHTML =
"<strong>Simulation reset:</strong> 24 m³ initial endowment. " +
"Future rainfall remains independent of household count.";
updateUI();
updateHistory();
});
// ------------------------------------------------------------
// Animation
// ------------------------------------------------------------
function updateRoundAnimation(now, dt) {
if (!roundAnimation) return;
const animation = roundAnimation;
const elapsed = now - animation.start;
if (elapsed < animation.drawStart) {
animation.phase = "inflow";
rainCloud.visible = true;
animation.targetStock = state.stored + animation.inflow;
if (ui.statusText.textContent !== "Rainfall inflow arriving") {
ui.statusText.textContent = "Rainfall inflow arriving";
}
} else {
animation.phase = "drawing";
rainCloud.visible = false;
if (ui.statusText.textContent !== "Households drawing in order") {
ui.statusText.textContent = "Households drawing in order";
}
}
for (let i = 0; i < people.length; i++) {
const person = people[i];
const personStart = animation.drawStart + i * animation.stagger;
const progress = THREE.MathUtils.clamp(
(elapsed - personStart) / animation.tripDuration,
0,
1
);
let position;
let direction;
if (progress <= 0.5) {
const outward = progress * 2;
position = pointAlongRoute(person.outwardRoute, outward);
direction = person.outwardRoute[1].clone().sub(person.start);
} else {
const returnProgress = (1 - progress) * 2;
const reversed = [...person.outwardRoute].reverse();
position = pointAlongRoute(reversed, returnProgress);
direction = person.outwardRoute[person.outwardRoute.length - 1]
.clone()
.sub(person.outwardRoute[person.outwardRoute.length - 2]);
}
if (progress > 0 && progress < 1) {
person.group.position.copy(position);
person.group.position.y +=
0.08 + Math.abs(Math.sin(elapsed * 0.012 + i)) * 0.035;
if (direction.lengthSq() > 0.001) {
person.group.rotation.y = Math.atan2(direction.x, direction.z);
}
}
if (progress >= 0.5 && !person.arrived) {
person.arrived = true;
// Water leaves the shared reservoir only when the household
// actually receives its allocation.
animation.targetStock = Math.max(
0,
animation.targetStock - person.allocation
);
person.bucketFill.visible = person.allocation > 0;
person.unmetBadge.visible = person.unmet > 0;
const lampColor = person.unmet > 0 ? 0xff625c : 0x77e0a0;
person.house.statusLamp.material.color.setHex(lampColor);
person.house.statusLamp.material.emissive.setHex(lampColor);
person.house.cisternTarget = person.allocation / DEMAND_PER_HOUSEHOLD;
person.house.label.innerHTML =
`<b>House ${person.house.index + 1}</b>` +
`<span>${person.unmet > 0
? `+${person.allocation} · ${person.unmet} unmet`
: `+${person.allocation} m³`}</span>`;
}
}
visualStored = THREE.MathUtils.lerp(
visualStored,
animation.targetStock,
1 - Math.exp(-dt * 6)
);
updateReservoirWater(visualStored);
updateStoredReadout();
const totalDuration =
animation.drawStart +
(people.length - 1) * animation.stagger +
animation.tripDuration +
180;
if (elapsed >= totalDuration) {
visualStored = animation.finalStock;
finishRound();
}
}
function updateRain(elapsed) {
rainDrops.forEach((drop, index) => {
const cycle = (elapsed * 0.009 + index * 0.137) % 1;
drop.position.y = -0.35 - cycle * 3.2;
});
}
function updateHouses(now, dt) {
for (const house of houses) {
const age = (now - house.bornAt) / 520;
const scale = age >= 1
? 1
: 1 - Math.pow(1 - Math.max(0, age), 3);
house.group.scale.setScalar(Math.max(0.001, scale));
house.cisternLevel = THREE.MathUtils.lerp(
house.cisternLevel,
house.cisternTarget,
1 - Math.exp(-dt * 5)
);
house.cisternWater.visible = house.cisternLevel > 0.01;
house.cisternWater.scale.y = Math.max(0.04, house.cisternLevel * 0.58);
house.cisternWater.position.y = 0.16 + house.cisternWater.scale.y / 2;
}
}
// ------------------------------------------------------------
// Screen-space labels
// ------------------------------------------------------------
const projected = new THREE.Vector3();
function projectLabel(element, x, y, z) {
projected.set(x, y, z).project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
Math.abs(projected.x) < 1.2 &&
Math.abs(projected.y) < 1.2;
element.style.display = visible ? "block" : "none";
if (!visible) return;
const screenX = (projected.x * 0.5 + 0.5) * window.innerWidth;
const screenY = (-projected.y * 0.5 + 0.5) * window.innerHeight;
element.style.transform =
`translate(${screenX}px, ${screenY}px) translate(-50%, -100%)`;
}
function updateLabels() {
projectLabel(reservoirLabel, -5.5, 3.35, 0);
reservoirLabel.querySelector("span").textContent =
`${Math.round(roundAnimation ? visualStored : state.stored)} m³ stored`;
for (const house of houses) {
projectLabel(
house.label,
house.position.x,
3.35,
house.position.z
);
}
}
// ------------------------------------------------------------
// Resize and render loop
// ------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
let previousTime = performance.now();
function animate(now) {
requestAnimationFrame(animate);
const dt = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
updateCamera(dt);
updateRoundAnimation(now, dt);
updateRain(now - (roundAnimation?.start ?? now));
updateHouses(now, dt);
updateLabels();
renderer.render(scene, camera);
}
updateReservoirWater(visualStored);
updateUI();
updateHistory();
requestAnimationFrame(animate);
</script>
</body>
</html>
```