Prompt specification
Build or customize the Three.js 3D scene "Village Water Reservoir Scheduling" 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: Village Water Reservoir Scheduling
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/village-water-reservoir-scheduling-x3131
Scene Description Prompt:
Build a voxel village reservoir game with toy seasonal inflows and adjustable household and garden withdrawals; track unmet requests. One HTML file, Three.js from cdnjs.
Working Three.js Starter (village-water-reservoir-scheduling-x3131):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Reservoir Run — Voxel Village Water Game</title>
<style>
:root {
--ink: #19363d;
--muted: #6a8181;
--paper: rgba(251, 252, 244, 0.94);
--line: rgba(38, 78, 78, 0.13);
--teal: #168e8d;
--aqua: #47c1bd;
--orange: #e48a49;
--red: #d95e58;
--shadow: 0 18px 50px rgba(31, 67, 67, 0.18);
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #cfe8ef;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
button { -webkit-tap-highlight-color: transparent; }
#scene {
position: fixed;
inset: 0;
z-index: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
cursor: grab;
}
#scene canvas.dragging { cursor: grabbing; }
.glass {
background: var(--paper);
border: 1px solid rgba(255, 255, 255, 0.72);
box-shadow: var(--shadow);
backdrop-filter: blur(18px) saturate(1.1);
-webkit-backdrop-filter: blur(18px) saturate(1.1);
}
.topbar {
position: fixed;
z-index: 20;
top: 14px;
left: 14px;
width: min(570px, calc(100vw - 410px));
min-width: 430px;
padding: 12px 14px;
border-radius: 18px;
display: flex;
align-items: center;
gap: 12px;
user-select: none;
}
.brand {
width: 44px;
height: 44px;
flex: 0 0 auto;
display: grid;
place-items: center;
border-radius: 13px;
color: white;
background: linear-gradient(145deg, #22aaa4, #147c81);
box-shadow: inset 0 1px 0 rgba(255,255,255,.35),
0 6px 14px rgba(20,124,129,.24);
}
.brand svg { width: 25px; height: 25px; }
.brand-copy { min-width: 0; }
.eyebrow {
margin: 0 0 2px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: .13em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 19px;
line-height: 1.05;
letter-spacing: -.025em;
}
.top-meta {
margin-left: auto;
display: flex;
align-items: center;
gap: 6px;
}
.badge {
padding: 7px 9px;
border-radius: 10px;
background: rgba(31, 119, 115, .09);
color: #276c6a;
font-size: 11px;
font-weight: 800;
white-space: nowrap;
}
.icon-button {
border: 0;
border-radius: 10px;
padding: 8px 10px;
color: var(--ink);
background: rgba(31, 78, 77, .08);
font-size: 11px;
font-weight: 800;
cursor: pointer;
transition: transform .15s, background .15s;
}
.icon-button:hover { background: rgba(31, 78, 77, .14); }
.icon-button:active { transform: translateY(1px); }
.panel {
position: fixed;
z-index: 30;
top: 14px;
right: 14px;
bottom: 14px;
width: 370px;
padding: 18px;
overflow-y: auto;
border-radius: 22px;
scrollbar-width: thin;
scrollbar-color: rgba(33,95,94,.25) transparent;
transition: transform .28s cubic-bezier(.2,.8,.2,1), opacity .2s;
}
.panel.closed {
transform: translateX(calc(100% + 35px));
opacity: 0;
pointer-events: none;
}
.panel::-webkit-scrollbar { width: 6px; }
.panel::-webkit-scrollbar-thumb {
background: rgba(33,95,94,.22);
border-radius: 10px;
}
.panel-head {
display: flex;
align-items: flex-start;
gap: 10px;
margin-bottom: 14px;
}
.panel-head h2 {
margin: 0;
font-size: 21px;
letter-spacing: -.03em;
}
.panel-head p {
margin: 4px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.close-button {
margin-left: auto;
border: 0;
width: 30px;
height: 30px;
border-radius: 9px;
color: var(--muted);
background: rgba(38,75,74,.07);
cursor: pointer;
font-size: 18px;
}
.section {
padding: 14px 0;
border-top: 1px solid var(--line);
}
.section:first-of-type { border-top: 0; padding-top: 0; }
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin: 0 0 11px;
font-size: 11px;
font-weight: 900;
letter-spacing: .09em;
text-transform: uppercase;
}
.section-note {
color: var(--muted);
font-size: 10px;
font-weight: 650;
letter-spacing: 0;
text-transform: none;
}
.storage-head {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
}
.storage-number {
font-size: 31px;
font-weight: 850;
line-height: 1;
letter-spacing: -.045em;
}
.capacity {
margin-top: 5px;
color: var(--muted);
font-size: 11px;
}
.status-pill {
padding: 6px 9px;
border-radius: 999px;
color: #26776c;
background: rgba(47,169,136,.13);
font-size: 10px;
font-weight: 850;
text-align: center;
}
.status-pill.warn {
color: #9a5833;
background: rgba(228,138,73,.15);
}
.status-pill.danger {
color: #a23e43;
background: rgba(217,94,88,.14);
}
.meter {
height: 10px;
margin-top: 12px;
overflow: hidden;
border-radius: 999px;
background: rgba(31,76,77,.09);
}
.meter > span {
display: block;
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #39b8ac, #178b90);
transition: width .35s ease, background .25s;
}
.meter.low > span {
background: linear-gradient(90deg, #f0ad59, #d96452);
}
.mini-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-top: 13px;
}
.mini-metric {
padding: 10px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255,255,255,.42);
}
.mini-metric small {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: .06em;
text-transform: uppercase;
}
.mini-metric strong {
font-size: 14px;
letter-spacing: -.02em;
}
.mini-metric.good strong { color: #168878; }
.mini-metric.warn strong { color: #c66b38; }
.control { margin-bottom: 16px; }
.control:last-child { margin-bottom: 0; }
.control-label {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 12px;
margin-bottom: 7px;
}
.control-label label {
font-size: 12px;
font-weight: 800;
}
.control-label output {
color: #147f7e;
font-size: 12px;
font-weight: 850;
white-space: nowrap;
}
input[type="range"] {
width: 100%;
height: 18px;
margin: 0;
accent-color: var(--teal);
cursor: pointer;
}
.hint {
margin: 4px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.priority-note {
margin: 2px 0 13px;
padding: 9px 10px;
border-radius: 10px;
color: #596f70;
background: rgba(38,113,109,.065);
font-size: 10px;
line-height: 1.45;
}
.unmet-row {
display: grid;
grid-template-columns: 30px 1fr auto;
align-items: center;
gap: 9px;
margin: 9px 0;
}
.unmet-icon {
width: 30px;
height: 30px;
display: grid;
place-items: center;
border-radius: 9px;
color: #267c76;
background: rgba(38,137,130,.1);
font-size: 15px;
font-weight: 900;
}
.unmet-copy strong {
display: block;
font-size: 11px;
}
.unmet-copy small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.unmet-value {
font-size: 11px;
font-weight: 850;
text-align: right;
}
.thin-meter {
grid-column: 2 / 4;
height: 5px;
overflow: hidden;
border-radius: 999px;
background: rgba(30,75,75,.08);
}
.thin-meter span {
display: block;
height: 100%;
width: 0;
border-radius: inherit;
background: var(--red);
transition: width .3s;
}
.cumulative {
margin: 11px 0 0;
color: var(--muted);
font-size: 9px;
line-height: 1.5;
}
.chart-wrap {
padding: 8px 8px 3px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255,255,255,.42);
}
#historyChart {
display: block;
width: 100%;
height: 115px;
overflow: visible;
}
.legend {
display: flex;
gap: 12px;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
}
.legend span::before {
content: "";
display: inline-block;
width: 7px;
height: 7px;
margin-right: 5px;
border-radius: 2px;
background: var(--aqua);
vertical-align: 0;
}
.legend span:nth-child(2)::before { background: var(--orange); }
.legend span:nth-child(3)::before { background: #6f7fa8; }
.goal-box {
margin-top: 12px;
padding: 10px;
border-radius: 11px;
background: rgba(74,116,157,.07);
}
.goal-copy {
display: flex;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
color: #526a82;
font-size: 10px;
font-weight: 750;
}
.goal-box .meter { height: 6px; margin-top: 0; }
.goal-box .meter > span { background: linear-gradient(90deg, #7595be, #5978a6); }
.button-row {
display: flex;
gap: 7px;
margin-bottom: 10px;
}
.button {
flex: 1;
border: 0;
border-radius: 11px;
padding: 10px 11px;
color: var(--ink);
background: rgba(33,88,86,.08);
font-size: 11px;
font-weight: 850;
cursor: pointer;
transition: transform .15s, filter .15s, opacity .15s;
}
.button:hover { filter: brightness(.97); }
.button:active { transform: translateY(1px); }
.button:disabled { opacity: .45; cursor: not-allowed; }
.button.primary {
color: white;
background: linear-gradient(135deg, #1b9e98, #147b81);
box-shadow: 0 6px 14px rgba(20,123,129,.18);
}
.speed-row {
display: flex;
align-items: center;
gap: 5px;
margin-bottom: 10px;
}
.speed-row > span {
margin-right: 4px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
}
.speed {
flex: 1;
border: 1px solid var(--line);
border-radius: 9px;
padding: 7px;
color: var(--muted);
background: rgba(255,255,255,.45);
font-size: 10px;
font-weight: 850;
cursor: pointer;
}
.speed.active {
color: white;
border-color: transparent;
background: #4f777c;
}
.log {
display: flex;
flex-direction: column;
gap: 7px;
margin: 0;
padding: 0;
list-style: none;
}
.log li {
position: relative;
padding-left: 13px;
color: #5d7273;
font-size: 10px;
line-height: 1.4;
}
.log li::before {
content: "";
position: absolute;
top: 5px;
left: 0;
width: 5px;
height: 5px;
border-radius: 2px;
background: #78aaa6;
}
.log li.warn::before { background: var(--orange); }
.log li.danger::before { background: var(--red); }
.log li.good::before { background: #32a876; }
.camera-tip {
position: fixed;
z-index: 10;
left: 16px;
bottom: 16px;
padding: 9px 12px;
border-radius: 12px;
color: rgba(31,64,65,.72);
background: rgba(250,252,245,.73);
border: 1px solid rgba(255,255,255,.62);
backdrop-filter: blur(10px);
font-size: 10px;
user-select: none;
}
.camera-tip button {
margin-left: 8px;
border: 0;
padding: 0;
color: #267c78;
background: none;
font-size: 10px;
font-weight: 850;
cursor: pointer;
}
#toast {
position: fixed;
z-index: 60;
left: 50%;
bottom: 24px;
max-width: min(420px, calc(100vw - 30px));
padding: 11px 15px;
border-radius: 13px;
color: white;
background: rgba(28,65,67,.92);
box-shadow: 0 12px 35px rgba(24,58,59,.25);
font-size: 12px;
font-weight: 700;
text-align: center;
opacity: 0;
transform: translate(-50%, 15px);
pointer-events: none;
transition: opacity .2s, transform .2s;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
#loading {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
color: #276c6a;
background: #d9edf0;
font-size: 14px;
font-weight: 850;
letter-spacing: .08em;
text-transform: uppercase;
transition: opacity .35s;
}
#loading.hidden { opacity: 0; pointer-events: none; }
@media (max-width: 900px) {
.topbar {
width: calc(100vw - 28px);
min-width: 0;
}
.panel {
top: auto;
left: 8px;
right: 8px;
bottom: 8px;
width: auto;
max-height: 57vh;
border-radius: 19px;
}
.panel.closed {
transform: translateY(calc(100% + 25px));
}
.camera-tip { display: none; }
#toast {
bottom: calc(57vh + 20px);
}
}
@media (max-width: 560px) {
.topbar {
top: 8px;
left: 8px;
width: calc(100vw - 16px);
padding: 10px;
}
.brand { width: 38px; height: 38px; }
.brand svg { width: 21px; height: 21px; }
h1 { font-size: 16px; }
.eyebrow { font-size: 8px; }
.top-meta { gap: 4px; }
.badge { padding: 6px 7px; font-size: 9px; }
.icon-button { padding: 8px; font-size: 10px; }
.panel { padding: 15px; }
}
</style>
</head>
<body>
<div id="scene"></div>
<header class="topbar glass">
<div class="brand" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none">
<path d="M12 2.5C9.4 6.1 5.2 10.5 5.2 15a6.8 6.8 0 0 0 13.6 0c0-4.5-4.2-8.9-6.8-12.5Z"
fill="currentColor"/>
<path d="M9 15.4c.2 1.7 1.2 2.7 2.9 3" stroke="#8de3dc"
stroke-width="1.6" stroke-linecap="round"/>
</svg>
</div>
<div class="brand-copy">
<p class="eyebrow">Voxel water stewardship</p>
<h1>Reservoir Run</h1>
</div>
<div class="top-meta">
<span class="badge" id="seasonBadge">Spring</span>
<span class="badge" id="dayBadge">Day 1</span>
<button class="icon-button" id="panelToggle" aria-expanded="true">Hide panel</button>
</div>
</header>
<aside class="panel glass" id="controlPanel" aria-label="Reservoir controls">
<div class="panel-head">
<div>
<h2>Village Water Board</h2>
<p>Balance seasonal supply with homes and gardens.</p>
</div>
<button class="close-button" id="closePanel" aria-label="Close control panel">×</button>
</div>
<section class="section">
<div class="section-title">
<span>Reservoir</span>
<span class="section-note" id="statusPill">Balanced</span>
</div>
<div class="storage-head">
<div>
<div class="storage-number" id="storageText">68.0 kL</div>
<div class="capacity" id="storageCapacityText">of 90 kL capacity</div>
</div>
<div class="status-pill" id="statusText">Supply balanced</div>
</div>
<div class="meter" id="storageMeter">
<span id="storageBar"></span>
</div>
<div class="mini-grid">
<div class="mini-metric good">
<small>Today's inflow</small>
<strong id="inflowText">+6.4 kL</strong>
</div>
<div class="mini-metric warn">
<small>Total request</small>
<strong id="demandText">4.5 kL</strong>
</div>
<div class="mini-metric" id="balanceMetric">
<small>Daily balance</small>
<strong id="balanceText">+1.9 kL</strong>
</div>
</div>
</section>
<section class="section">
<div class="section-title">
<span>Withdrawal controls</span>
<span class="section-note">per user per day</span>
</div>
<div class="control">
<div class="control-label">
<label for="householdSlider">Household use</label>
<output id="householdValue">260 L / home</output>
</div>
<input id="householdSlider" type="range" min="100" max="450" step="10" value="260">
<p class="hint" id="householdHint">8 homes request 2.1 kL before seasonal demand.</p>
</div>
<div class="control">
<div class="control-label">
<label for="gardenSlider">Garden irrigation</label>
<output id="gardenValue">400 L / garden</output>
</div>
<input id="gardenSlider" type="range" min="100" max="900" step="25" value="400">
<p class="hint" id="gardenHint">6 gardens request 2.4 kL before seasonal demand.</p>
</div>
<div class="priority-note">
<strong>Allocation rule:</strong> household requests are served first.
Gardens receive the remaining water.
</div>
</section>
<section class="section">
<div class="section-title">
<span>Unmet requests</span>
<span class="section-note">latest completed day</span>
</div>
<div class="unmet-row">
<div class="unmet-icon">H</div>
<div class="unmet-copy">
<strong>Households</strong>
<small id="cumulativeHouseholds">0 requests left unmet all-time</small>
</div>
<div class="unmet-value" id="unmetHouseholds">0 homes · 0 L</div>
<div class="thin-meter"><span id="unmetHouseholdsBar"></span></div>
</div>
<div class="unmet-row">
<div class="unmet-icon">G</div>
<div class="unmet-copy">
<strong>Gardens</strong>
<small id="cumulativeGardens">0 requests left unmet all-time</small>
</div>
<div class="unmet-value" id="unmetGardens">0 gardens · 0 L</div>
<div class="thin-meter"><span id="unmetGardensBar"></span></div>
</div>
</section>
<section class="section">
<div class="section-title">
<span>Water balance</span>
<span class="section-note">last 12 days</span>
</div>
<div class="chart-wrap">
<svg id="historyChart" viewBox="0 0 300 106" role="img"
aria-label="Daily inflow and demand chart"></svg>
<div class="legend">
<span>Inflow</span>
<span>Demand</span>
<span>Storage</span>
</div>
</div>
<div class="goal-box">
<div class="goal-copy">
<span>Resilient village goal</span>
<span id="goalText">0 / 12 days</span>
</div>
<div class="meter"><span id="goalBar"></span></div>
</div>
</section>
<section class="section">
<div class="section-title">
<span>Actions</span>
<span class="section-note">space = pause</span>
</div>
<div class="speed-row">
<span>Speed</span>
<button class="speed active" data-speed="1">1×</button>
<button class="speed" data-speed="2">2×</button>
<button class="speed" data-speed="4">4×</button>
</div>
<div class="button-row">
<button class="button primary" id="rainBtn">Call rain · +6 kL</button>
<button class="button" id="pauseBtn">Pause</button>
</div>
<div class="button-row">
<button class="button" id="resetBtn">Reset run</button>
</div>
</section>
<section class="section">
<div class="section-title">
<span>Village log</span>
<span class="section-note">newest first</span>
</div>
<ol class="log" id="log" aria-live="polite"></ol>
</section>
</aside>
<div class="camera-tip">
Drag to orbit · Shift/right-drag to pan · Scroll to zoom
<button id="cameraReset">Reset view</button>
</div>
<div id="toast" role="status" aria-live="polite"></div>
<div id="loading">Building the village…</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 CONFIG = {
capacity: 90,
initialStorage: 68,
households: 8,
gardens: 6,
daysPerSeason: 8,
dayDuration: 2.5,
rainBoost: 6
};
const SEASONS = [
{
name: "Spring", inflow: 6.4, demand: 0.90,
sky: "#cfe8ef", grass: "#89b86c", leaf: "#4f9d55",
crop: "#56a54f", water: "#47b8c4"
},
{
name: "Summer", inflow: 3.2, demand: 1.25,
sky: "#d9edf0", grass: "#78aa5e", leaf: "#337b45",
crop: "#438d3f", water: "#35a8b8"
},
{
name: "Autumn", inflow: 5.2, demand: 1.00,
sky: "#eadfc9", grass: "#999b60", leaf: "#d1783f",
crop: "#c1833e", water: "#54aeb0"
},
{
name: "Winter", inflow: 2.4, demand: 1.12,
sky: "#dbe7eb", grass: "#d8e1dc", leaf: "#718b7a",
crop: "#a88765", water: "#8cbfca"
}
];
function freshSimulation() {
return {
day: 1,
speed: 1,
running: true,
storage: CONFIG.initialStorage,
householdRate: 260,
gardenRate: 400,
seasonIndex: 0,
last: null,
history: [],
goodDays: 0,
streak: 0,
totalUnmetHHRequests: 0,
totalUnmetGardenRequests: 0,
totalUnmetHHLiters: 0,
totalUnmetGardenLiters: 0,
rainPending: false,
rainUsedSeason: false,
weatherRain: 0
};
}
let sim = freshSimulation();
let logEntries = [];
let toastTimer = 0;
let dayAccumulator = 0;
// ------------------------------------------------------------
// Three.js scene
// ------------------------------------------------------------
const sceneHost = $("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(SEASONS[0].sky);
scene.fog = new THREE.Fog(SEASONS[0].sky, 48, 90);
const camera = new THREE.OrthographicCamera(-25, 25, 15, -15, 0.1, 150);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 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.08;
renderer.domElement.setAttribute("aria-label", "Interactive voxel village reservoir");
renderer.domElement.tabIndex = 0;
sceneHost.appendChild(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xe9f7ff, 0x6d8055, 2.2);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff1ce, 3.1);
sun.position.set(-12, 22, 14);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -24;
sun.shadow.camera.right = 24;
sun.shadow.camera.top = 20;
sun.shadow.camera.bottom = -20;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 65;
sun.shadow.bias = -0.0006;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x9acfe2, 0.65);
fill.position.set(15, 8, -15);
scene.add(fill);
const geometryCache = new Map();
const materialCache = new Map();
function materialFor(color, options = {}) {
const key = color + JSON.stringify(options);
if (!materialCache.has(key)) {
materialCache.set(key, new THREE.MeshStandardMaterial({
color,
roughness: 0.9,
metalness: 0,
flatShading: true,
...options
}));
}
return materialCache.get(key);
}
function geometryFor(w, h, d) {
const key = `${w.toFixed(3)},${h.toFixed(3)},${d.toFixed(3)}`;
if (!geometryCache.has(key)) {
geometryCache.set(key, new THREE.BoxGeometry(w, h, d));
}
return geometryCache.get(key);
}
function box(parent, w, h, d, x, y, z, color, castShadow = true) {
const material = color && color.isMaterial ? color : materialFor(color);
const mesh = new THREE.Mesh(geometryFor(w, h, d), material);
mesh.position.set(x, y, z);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const interactiveRoots = [];
const roofSnowMeshes = [];
const gardenSnowMeshes = [];
const treeSnowMeshes = [];
const groundMaterial = new THREE.MeshStandardMaterial({
color: SEASONS[0].grass, roughness: 1, flatShading: true
});
const leafMaterial = new THREE.MeshStandardMaterial({
color: SEASONS[0].leaf, roughness: 1, flatShading: true
});
const cropMaterial = new THREE.MeshStandardMaterial({
color: SEASONS[0].crop, roughness: 1, flatShading: true
});
const waterMaterial = new THREE.MeshStandardMaterial({
color: SEASONS[0].water,
roughness: 0.28,
metalness: 0.04,
transparent: true,
opacity: 0.88,
flatShading: true
});
// Diorama base and paths.
box(scene, 32, 1.45, 24, 0, -0.82, 0, "#9b7550");
box(scene, 32, 0.26, 24, 0, -0.02, 0, groundMaterial);
box(scene, 1.35, 0.08, 15, 1.4, 0.14, -2.8, "#d3bd83", false);
box(scene, 15.5, 0.08, 1.25, 7.2, 0.15, 2.6, "#d3bd83", false);
box(scene, 0.85, 0.08, 8.2, -9.1, 0.15, -8.4, "#c4ad79", false);
// Hills behind the reservoir.
const hillBlocks = [
[-12.8, -9.5, 5.0, 2.5, 4.0],
[-9.0, -10.0, 4.5, 3.1, 4.8],
[-5.1, -10.0, 4.0, 2.5, 4.2],
[-1.6, -10.2, 3.6, 2.0, 3.8]
];
hillBlocks.forEach(([x, z, w, h, d]) => {
box(scene, w, h, d, x, h / 2 + 0.08, z, "#799b65");
box(scene, w * .78, h * .45, d * .78, x - .2, h + h * .2, z, "#8cab72");
});
// Reservoir bed, banks, and dam.
box(scene, 12.4, .16, 8.2, -6.5, .13, -2.5, "#477f77", false);
for (let x = -12; x <= -1; x += 1.25) {
box(scene, 1.05, .62, .65, x, .38, -6.55, "#82917a");
box(scene, 1.05, .55, .65, x, .34, 1.55, "#82917a");
}
for (let z = -5.7; z <= 1; z += 1.25) {
box(scene, .65, .58, 1.05, -12.8, .36, z, "#82917a");
}
const waterMesh = new THREE.Mesh(
geometryFor(11.65, 1, 7.25), waterMaterial
);
waterMesh.position.set(-6.5, 1.45, -2.5);
waterMesh.receiveShadow = true;
scene.add(waterMesh);
// Voxel dam.
for (let i = 0; i < 5; i++) {
box(scene, .85, 2.65 - i * .15, 1.25,
.18, 1.36, -5.75 + i * 1.25, "#7d8177");
}
box(scene, .9, .18, 6.8, .18, 2.68, -2.5, "#9aa18e");
// Inlet stream and animated droplets.
for (let i = 0; i < 8; i++) {
box(scene, .7, .09, .65, -9.1, .25, -10 + i * .55, "#55b8bd", false);
}
const droplets = [];
for (let i = 0; i < 10; i++) {
const drop = box(scene, .18, .18, .18, -9.1, .5, -10, "#9ee8e3", false);
droplets.push(drop);
}
// Water glints.
const shimmerMaterial = new THREE.MeshStandardMaterial({
color: "#d8ffff", transparent: true, opacity: .52,
roughness: .3, depthWrite: false
});
const shimmerMeshes = [];
for (let i = 0; i < 13; i++) {
const shimmer = box(
scene, .45 + (i % 3) * .15, .035, .16,
-11.3 + (i * 1.07) % 9.6, 2.7, -5.6 + (i * .83) % 6.1,
shimmerMaterial, false
);
shimmerMeshes.push(shimmer);
}
const reservoirRoot = new THREE.Group();
reservoirRoot.userData.pick = {
type: "reservoir",
label: "Meadow Reservoir"
};
interactiveRoots.push(reservoirRoot);
scene.add(reservoirRoot);
// Houses.
const houseNames = [
"Maple House", "Willow Cottage", "Pine Lodge",
"Clover House", "Birch Cottage", "Cedar Lodge",
"Sunny House", "Brook Cottage"
];
const housePositions = [
[3.2, -4.7], [7.2, -4.7], [11.2, -4.7],
[3.2, -.3], [7.2, -.3], [11.2, -.3]
];
const wallColors = ["#f2d7a1", "#e8c89b", "#f4dfb6", "#d9dfc6"];
const roofColors = ["#b95f46", "#7f4d43", "#c6754d", "#6c6961"];
function addHouse(x, z, index) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.userData.pick = {
type: "home",
label: houseNames[index],
index
};
interactiveRoots.push(group);
scene.add(group);
box(group, 3.05, .22, 2.7, 0, .18, 0, "#a89a78");
box(group, 2.55, 1.55, 2.25, 0, .98, 0, wallColors[index % 4]);
box(group, 3.1, .38, 2.75, 0, 1.91, 0, roofColors[index % 4]);
box(group, 2.35, .38, 2.05, 0, 2.28, 0, roofColors[index % 4]);
box(group, 1.45, .35, 1.35, 0, 2.62, 0, roofColors[index % 4]);
box(group, .56, 1.05, .09, .42, .78, 1.16, "#6b5143");
box(group, .14, .13, .1, .61, .78, 1.23, "#e6c56d");
const windowMaterial = new THREE.MeshStandardMaterial({
color: "#8ed7df", emissive: "#3b8491", emissiveIntensity: .22,
roughness: .35, flatShading: true
});
box(group, .58, .55, .08, -.65, 1.06, 1.16, windowMaterial);
box(group, .58, .55, .08, .85, 1.06, 1.16, windowMaterial);
box(group, .08, .55, .58, 1.31, 1.06, .36, windowMaterial);
box(group, .4, .78, .4, -.72, 2.54, -.42, "#8d7764");
const snow = new THREE.Group();
box(snow, 2.95, .08, 2.58, 0, 2.12, 0, "#f4faf7", false);
box(snow, 2.2, .08, 1.9, 0, 2.49, 0, "#f4faf7", false);
box(snow, 1.3, .08, 1.2, 0, 2.82, 0, "#f4faf7", false);
snow.visible = false;
group.add(snow);
roofSnowMeshes.push(snow);
box(group, .28, .85, .28, -1.35, .7, -1.2, "#8a6a4b");
}
housePositions.forEach(([x, z], index) => addHouse(x, z, index));
// Gardens and crop rows.
const gardenPositions = [
[-10.7, 6.2], [-6.7, 6.2], [-2.7, 6.2],
[4.4, 6.2], [8.7, 6.2], [13.0, 6.2]
];
const gardenNames = [
"South Meadow", "Herb Plot", "Pumpkin Patch",
"Rose Garden", "Community Plot", "Kitchen Garden"
];
function addGarden(x, z, index) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.userData.pick = {
type: "garden",
label: gardenNames[index],
index
};
interactiveRoots.push(group);
scene.add(group);
box(group, 3.05, .16, 2.45, 0, .16, 0, "#7d593d");
box(group, 3.22, .13, .16, 0, .27, -1.27, "#aa8055");
box(group, 3.22, .13, .16, 0, .27, 1.27, "#aa8055");
box(group, .16, .13, 2.55, -1.55, .27, 0, "#aa8055");
box(group, .16, .13, 2.55, 1.55, .27, 0, "#aa8055");
for (let row = -1; row <= 1; row++) {
for (let col = -1; col <= 1; col++) {
box(group, .38, .35, .38, col * .78, .4, row * .57, cropMaterial);
box(group, .24, .16, .24, col * .78, .64, row * .57, cropMaterial);
}
}
const snow = box(group, 2.98, .07, 2.36, 0, .27, 0, "#eef5ef", false);
snow.visible = false;
gardenSnowMeshes.push(snow);
}
gardenPositions.forEach(([x, z], index) => addGarden(x, z, index));
// Trees.
function addTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, .08, z);
group.scale.setScalar(scale);
scene.add(group);
box(group, .38, 1.35, .38, 0, .68, 0, "#8d6646");
box(group, 1.45, 1.15, 1.35, 0, 1.68, 0, leafMaterial);
box(group, 1.02, .85, .95, -.15, 2.38, .05, leafMaterial);
box(group, .72, .55, .7, .18, 2.87, -.02, leafMaterial);
const snow = box(group, 1.08, .09, 1.0, -.15, 2.82, .05, "#f3f7ef", false);
snow.visible = false;
treeSnowMeshes.push(snow);
}
[
[-14.2, -7.1, 1.05], [-14.4, 1.0, .9],
[-1.1, -8.8, .85], [14.5, -4.8, 1.0],
[14.8, 2.1, .85], [-1.1, 9.1, .95],
[14.5, 8.8, .75]
].forEach(args => addTree(...args));
// Fence around the community gardens.
for (let x = 2.5; x <= 14.5; x += 1.5) {
box(scene, .15, .75, .15, x, .45, 8.05, "#e5d4a3");
}
box(scene, 12.3, .12, .13, 8.5, .67, 8.05, "#e5d4a3");
// Small voxel windmill.
const windmill = new THREE.Group();
windmill.position.set(14, 0, -8.2);
scene.add(windmill);
box(windmill, .75, 3.5, .75, 0, 1.75, 0, "#d9d1b2");
box(windmill, 1.2, .35, 1.2, 0, 3.45, 0, "#92775e");
box(windmill, .5, .7, .08, 0, 2.8, .46, "#658797");
const rotor = new THREE.Group();
rotor.position.set(0, 3.55, .55);
windmill.add(rotor);
box(rotor, .18, 2.25, .12, 0, 0, 0, "#f3dfad");
box(rotor, 2.25, .18, .12, 0, 0, 0, "#f3dfad");
box(rotor, .28, .28, .2, 0, 0, .08, "#bc6a49");
// Clouds.
const cloudMaterial = new THREE.MeshStandardMaterial({
color: "#ffffff", transparent: true, opacity: .82,
roughness: 1, flatShading: true
});
const clouds = [];
for (let i = 0; i < 4; i++) {
const group = new THREE.Group();
group.position.set(-17 + i * 10, 9 + (i % 2) * 1.2, -8 + (i % 3) * 5);
box(group, 2.2, .7, 1.2, 0, 0, 0, cloudMaterial, false);
box(group, 1.4, 1.0, 1.25, -.55, .35, 0, cloudMaterial, false);
box(group, 1.45, .8, 1.1, .7, .28, 0, cloudMaterial, false);
scene.add(group);
clouds.push(group);
}
// Rain / snow particles.
const precipitationCount = 170;
const precipitationPositions = new Float32Array(precipitationCount * 3);
for (let i = 0; i < precipitationCount; i++) {
precipitationPositions[i * 3] = (Math.random() - .5) * 36;
precipitationPositions[i * 3 + 1] = 3 + Math.random() * 13;
precipitationPositions[i * 3 + 2] = (Math.random() - .5) * 27;
}
const precipitationGeometry = new THREE.BufferGeometry();
precipitationGeometry.setAttribute(
"position", new THREE.BufferAttribute(precipitationPositions, 3)
);
const precipitationMaterial = new THREE.PointsMaterial({
color: "#ffffff", size: .11, transparent: true, opacity: .78,
depthWrite: false, sizeAttenuation: true
});
const precipitation = new THREE.Points(
precipitationGeometry, precipitationMaterial
);
precipitation.frustumCulled = false;
scene.add(precipitation);
// Canvas-based voxel labels.
function makeLabel(text, position, background = "#1f6466") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = background;
ctx.beginPath();
ctx.roundRect(8, 10, 496, 108, 22);
ctx.fill();
ctx.fillStyle = "#ffffff";
ctx.font = "800 39px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 65);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
}));
sprite.position.copy(position);
sprite.scale.set(4.8, 1.2, 1);
sprite.renderOrder = 20;
scene.add(sprite);
return sprite;
}
makeLabel("MEADOW RESERVOIR", new THREE.Vector3(-6.7, 4.5, -2.5));
makeLabel("LITTLE VILLAGE", new THREE.Vector3(7.4, 5.0, -2.4), "#55756b");
makeLabel("GARDENS", new THREE.Vector3(7.2, 2.3, 6.5), "#8a6948");
// Season animation targets.
const targetBackground = new THREE.Color(SEASONS[0].sky);
const targetGround = new THREE.Color(SEASONS[0].grass);
const targetLeaf = new THREE.Color(SEASONS[0].leaf);
const targetCrop = new THREE.Color(SEASONS[0].crop);
const targetWater = new THREE.Color(SEASONS[0].water);
function setSeasonTargets(index) {
const palette = SEASONS[index];
targetBackground.set(palette.sky);
targetGround.set(palette.grass);
targetLeaf.set(palette.leaf);
targetCrop.set(palette.crop);
targetWater.set(palette.water);
const winter = index === 3;
roofSnowMeshes.forEach(mesh => mesh.visible = winter);
gardenSnowMeshes.forEach(mesh => mesh.visible = winter);
treeSnowMeshes.forEach(mesh => mesh.visible = winter);
sun.intensity = winter ? 2.45 : 3.1;
}
// ------------------------------------------------------------
// Direct camera controls
// ------------------------------------------------------------
const controls = {
azimuth: .72,
polar: .88,
zoom: 1,
target: new THREE.Vector3(),
radius: 50
};
let viewHeight = 28;
function resetCamera() {
controls.azimuth = .72;
controls.polar = .88;
controls.zoom = 1;
controls.target.set(window.innerWidth > 900 ? 2.0 : 0, 0, 0);
updateCamera();
}
function updateCamera() {
const horizontal = Math.sin(controls.polar) * controls.radius;
camera.position.set(
controls.target.x + horizontal * Math.sin(controls.azimuth),
controls.target.y + Math.cos(controls.polar) * controls.radius,
controls.target.z + horizontal * Math.cos(controls.azimuth)
);
camera.lookAt(controls.target);
camera.zoom = controls.zoom;
camera.updateProjectionMatrix();
camera.updateMatrixWorld();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
viewHeight = Math.max(28, 38 / aspect);
camera.left = -viewHeight * aspect / 2;
camera.right = viewHeight * aspect / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
}
window.addEventListener("resize", resize);
resize();
resetCamera();
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let drag = null;
function pickAt(clientX, clientY) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(interactiveRoots, true);
if (!hits.length) return null;
let object = hits[0].object;
while (object && !object.userData.pick) object = object.parent;
return object ? object.userData.pick : null;
}
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", event => {
renderer.domElement.setPointerCapture(event.pointerId);
drag = {
id: event.pointerId,
x: event.clientX,
y: event.clientY,
startX: event.clientX,
startY: event.clientY,
moved: false,
pan: event.button === 2 || event.shiftKey
};
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", event => {
if (!drag || drag.id !== event.pointerId) return;
const dx = event.clientX - drag.x;
const dy = event.clientY - drag.y;
drag.x = event.clientX;
drag.y = event.clientY;
if (Math.hypot(event.clientX - drag.startX, event.clientY - drag.startY) > 5) {
drag.moved = true;
}
if (drag.pan) {
const scale = viewHeight / controls.zoom / renderer.domElement.clientHeight;
const right = new THREE.Vector3(
Math.cos(controls.azimuth), 0, -Math.sin(controls.azimuth)
);
controls.target.addScaledVector(right, -dx * scale * 1.15);
controls.target.y += dy * scale * 1.15;
controls.target.x = THREE.MathUtils.clamp(controls.target.x, -9, 9);
controls.target.z = THREE.MathUtils.clamp(controls.target.z, -9, 9);
controls.target.y = THREE.MathUtils.clamp(controls.target.y, -3, 5);
} else {
controls.azimuth -= dx * .006;
controls.polar = THREE.MathUtils.clamp(controls.polar - dy * .005, .48, 1.24);
}
updateCamera();
});
renderer.domElement.addEventListener("pointerup", event => {
if (!drag || drag.id !== event.pointerId) return;
const wasClick = !drag.moved;
drag = null;
renderer.domElement.classList.remove("dragging");
if (wasClick) {
const picked = pickAt(event.clientX, event.clientY);
if (picked) {
if (picked.type === "home") {
showToast(`${picked.label} requests ${sim.householdRate} L per day. Adjust household use above.`);
} else if (picked.type === "garden") {
showToast(`${picked.label} requests ${sim.gardenRate} L per day. Adjust garden irrigation above.`);
} else {
showToast(`Meadow Reservoir contains ${sim.storage.toFixed(1)} kL.`);
}
}
}
});
renderer.domElement.addEventListener("pointercancel", () => {
drag = null;
renderer.domElement.classList.remove("dragging");
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
controls.zoom = THREE.MathUtils.clamp(
controls.zoom * Math.exp(-event.deltaY * .001),
.65,
2.4
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
window.addEventListener("keydown", event => {
if (event.target instanceof HTMLInputElement) return;
if (event.code === "Space") {
event.preventDefault();
togglePause();
}
if (event.key.toLowerCase() === "r") resetCamera();
});
// ------------------------------------------------------------
// Simulation and UI
// ------------------------------------------------------------
function seasonForDay(day) {
const index = Math.floor((day - 1) / CONFIG.daysPerSeason) % SEASONS.length;
return { index, data: SEASONS[index] };
}
function formatLiters(kiloliters) {
const liters = kiloliters * 1000;
if (liters >= 1000) return `${(liters / 1000).toFixed(1)} kL`;
return `${Math.round(liters)} L`;
}
function addLog(text, type = "") {
logEntries.unshift({ text, type });
logEntries = logEntries.slice(0, 7);
renderLog();
}
function renderLog() {
$("log").innerHTML = logEntries.map(entry =>
`<li class="${entry.type}">${entry.text}</li>`
).join("");
}
function showToast(message) {
clearTimeout(toastTimer);
$("toast").textContent = message;
$("toast").classList.add("visible");
toastTimer = setTimeout(() => $("toast").classList.remove("visible"), 3000);
}
function currentDemand(seasonIndex = sim.seasonIndex) {
const multiplier = SEASONS[seasonIndex].demand;
const households =
CONFIG.households * sim.householdRate * multiplier / 1000;
const gardens =
CONFIG.gardens * sim.gardenRate * multiplier / 1000;
return { households, gardens, total: households + gardens };
}
function processDay() {
const dayBeingProcessed = sim.day;
const seasonIndex = sim.seasonIndex;
const season = SEASONS[seasonIndex];
const demand = currentDemand(seasonIndex);
const rainAdded = sim.rainPending ? CONFIG.rainBoost : 0;
const inflow = season.inflow + rainAdded;
sim.rainPending = false;
let available = sim.storage + inflow;
const householdEach = sim.householdRate * season.demand / 1000;
const gardenEach = sim.gardenRate * season.demand / 1000;
const householdServed = Math.min(available, demand.households);
available -= householdServed;
const gardenServed = Math.min(available, demand.gardens);
available -= gardenServed;
const unmetHHLiters = Math.max(0, demand.households - householdServed);
const unmetGardenLiters = Math.max(0, demand.gardens - gardenServed);
const householdFulfilled = Math.min(
CONFIG.households,
Math.floor((householdServed + .000001) / householdEach)
);
const gardenFulfilled = Math.min(
CONFIG.gardens,
Math.floor((gardenServed + .000001) / gardenEach)
);
const unmetHHRequests = CONFIG.households - householdFulfilled;
const unmetGardenRequests = CONFIG.gardens - gardenFulfilled;
const overflow = Math.max(0, available - CONFIG.capacity);
sim.storage = THREE.MathUtils.clamp(available, 0, CONFIG.capacity);
const record = {
day: dayBeingProcessed,
seasonIndex,
inflow,
demand: demand.total,
storage: sim.storage,
overflow,
unmetHHLiters,
unmetGardenLiters,
unmetHHRequests,
unmetGardenRequests
};
sim.last = record;
sim.history.push(record);
if (sim.history.length > 40) sim.history.shift();
sim.totalUnmetHHRequests += unmetHHRequests;
sim.totalUnmetGardenRequests += unmetGardenRequests;
sim.totalUnmetHHLiters += unmetHHLiters;
sim.totalUnmetGardenLiters += unmetGardenLiters;
if (unmetHHRequests === 0 && unmetGardenRequests === 0) {
sim.goodDays++;
sim.streak++;
} else {
sim.streak = 0;
}
sim.day++;
const newSeason = seasonForDay(sim.day);
const seasonChanged = newSeason.index !== seasonIndex;
sim.seasonIndex = newSeason.index;
if (seasonChanged) {
sim.rainUsedSeason = false;
setSeasonTargets(sim.seasonIndex);
addLog(`${SEASONS[sim.seasonIndex].name} begins: inflow is ${SEASONS[sim.seasonIndex].inflow.toFixed(1)} kL/day.`, "good");
}
if (unmetHHRequests || unmetGardenRequests) {
const parts = [];
if (unmetHHRequests) parts.push(`${unmetHHRequests} home request${unmetHHRequests > 1 ? "s" : ""}`);
if (unmetGardenRequests) parts.push(`${unmetGardenRequests} garden request${unmetGardenRequests > 1 ? "s" : ""}`);
addLog(`Day ${dayBeingProcessed}: ${parts.join(" and ")} left unmet.`, "danger");
} else if (rainAdded) {
addLog(`Day ${dayBeingProcessed}: rain boost met every request.`, "good");
} else if (inflow < demand.total) {
addLog(`Day ${dayBeingProcessed}: reserve fell by ${(demand.total - inflow).toFixed(1)} kL.`, "warn");
} else if (dayBeingProcessed % 4 === 0) {
addLog(`Day ${dayBeingProcessed}: every request was met.`, "good");
}
updateUI();
}
function updateHistoryChart() {
const records = sim.history.slice(-12);
const svg = $("historyChart");
if (!records.length) {
svg.innerHTML = `
<text x="150" y="53" text-anchor="middle"
fill="#78908f" font-size="10" font-family="system-ui">
Complete a day to begin the forecast
</text>`;
return;
}
const chartLeft = 17;
const chartRight = 289;
const baseline = 77;
const chartHeight = 61;
const maxValue = Math.max(
7,
...records.flatMap(record => [record.inflow, record.demand])
) * 1.1;
const slot = (chartRight - chartLeft) / records.length;
const barWidth = Math.min(9, slot * .28);
let markup = `
<line x1="${chartLeft}" y1="${baseline}" x2="${chartRight}" y2="${baseline}"
stroke="#8aa09f" stroke-opacity=".2" stroke-width="1"/>
<line x1="${chartLeft}" y1="${baseline - chartHeight / 2}" x2="${chartRight}"
y2="${baseline - chartHeight / 2}" stroke="#8aa09f" stroke-opacity=".12"
stroke-dasharray="3 4"/>`;
const storagePoints = [];
records.forEach((record, index) => {
const center = chartLeft + slot * index + slot / 2;
const inflowHeight = record.inflow / maxValue * chartHeight;
const demandHeight = record.demand / maxValue * chartHeight;
markup += `
<rect x="${center - barWidth - 1}" y="${baseline - inflowHeight}"
width="${barWidth}" height="${inflowHeight}" rx="2" fill="#47c1bd">
<title>Inflow: ${record.inflow.toFixed(1)} kL</title>
</rect>
<rect x="${center + 1}" y="${baseline - demandHeight}"
width="${barWidth}" height="${demandHeight}" rx="2" fill="#e48a49">
<title>Demand: ${record.demand.toFixed(1)} kL</title>
</rect>`;
const storageY = baseline - record.storage / CONFIG.capacity * chartHeight;
storagePoints.push(`${center},${storageY}`);
if (index % 3 === 0 || index === records.length - 1) {
markup += `
<text x="${center}" y="98" text-anchor="middle"
fill="#718786" font-size="8" font-family="system-ui">
d${record.day}
</text>`;
}
});
markup += `
<polyline points="${storagePoints.join(" ")}" fill="none"
stroke="#6f7fa8" stroke-width="2" stroke-linejoin="round"
stroke-linecap="round" opacity=".85"/>`;
records.forEach((record, index) => {
const center = chartLeft + slot * index + slot / 2;
const storageY = baseline - record.storage / CONFIG.capacity * chartHeight;
markup += `
<circle cx="${center}" cy="${storageY}" r="2.5"
fill="#6f7fa8" stroke="#fbfcf4" stroke-width="1">
<title>Storage: ${record.storage.toFixed(1)} kL</title>
</circle>`;
});
svg.innerHTML = markup;
}
function updateUI() {
const season = SEASONS[sim.seasonIndex];
const demand = currentDemand();
const inflow = season.inflow + (sim.rainPending ? CONFIG.rainBoost : 0);
const net = inflow - demand.total;
const storagePercent = sim.storage / CONFIG.capacity * 100;
$("seasonBadge").textContent = season.name;
$("dayBadge").textContent = `Day ${sim.day}`;
$("storageText").textContent = `${sim.storage.toFixed(1)} kL`;
$("storageCapacityText").textContent = `of ${CONFIG.capacity} kL capacity`;
$("storageBar").style.width = `${storagePercent}%`;
$("storageMeter").classList.toggle("low", storagePercent < 22);
$("inflowText").textContent = `+${inflow.toFixed(1)} kL`;
$("demandText").textContent = `${demand.total.toFixed(1)} kL`;
$("balanceText").textContent = `${net >= 0 ? "+" : ""}${net.toFixed(1)} kL`;
$("balanceMetric").className = `mini-metric ${net >= 0 ? "good" : "warn"}`;
let status = "Supply balanced";
let statusType = "";
if (sim.rainPending) {
status = "Rain queued";
} else if (sim.last && (
sim.last.unmetHHRequests || sim.last.unmetGardenRequests
)) {
status = "Shortfall logged";
statusType = "danger";
} else if (net < 0) {
status = "Using reserves";
statusType = "warn";
}
$("statusText").textContent = status;
$("statusPill").textContent = status;
$("statusPill").className = `status-pill ${statusType}`;
$("householdValue").textContent = `${sim.householdRate} L / home`;
$("gardenValue").textContent = `${sim.gardenRate} L / garden`;
$("householdHint").textContent =
`${CONFIG.households} homes request ${(demand.households).toFixed(1)} kL with seasonal demand.`;
$("gardenHint").textContent =
`${CONFIG.gardens} gardens request ${(demand.gardens).toFixed(1)} kL with seasonal demand.`;
const last = sim.last;
const unmetHH = last ? last.unmetHHLiters : 0;
const unmetGarden = last ? last.unmetGardenLiters : 0;
$("unmetHouseholds").textContent = last
? `${last.unmetHHRequests} homes · ${formatLiters(unmetHH)}`
: "0 homes · 0 L";
$("unmetGardens").textContent = last
? `${last.unmetGardenRequests} gardens · ${formatLiters(unmetGarden)}`
: "0 gardens · 0 L";
const hhRequestVolume = last
? last.unmetHHLiters + Math.max(0, last.demand - last.unmetHHLiters - last.unmetGardenLiters)
: 1;
const gardenRequestVolume = last
? last.unmetGardenLiters + Math.max(0, last.demand - last.unmetHHLiters - last.unmetGardenLiters)
: 1;
$("unmetHouseholdsBar").style.width =
`${Math.min(100, unmetHH / Math.max(.001, hhRequestVolume) * 100)}%`;
$("unmetGardensBar").style.width =
`${Math.min(100, unmetGarden / Math.max(.001, gardenRequestVolume) * 100)}%`;
$("cumulativeHouseholds").textContent =
`${sim.totalUnmetHHRequests} requests · ${formatLiters(sim.totalUnmetHHLiters)} all-time`;
$("cumulativeGardens").textContent =
`${sim.totalUnmetGardenRequests} requests · ${formatLiters(sim.totalUnmetGardenLiters)} all-time`;
const goal = Math.min(12, sim.goodDays);
$("goalText").textContent = `${goal} / 12 days`;
$("goalBar").style.width = `${goal / 12 * 100}%`;
$("pauseBtn").textContent = sim.running ? "Pause" : "Resume";
$("rainBtn").disabled = sim.rainUsedSeason;
$("rainBtn").textContent = sim.rainPending
? "Rain queued for next day"
: sim.rainUsedSeason
? "Rain already called"
: "Call rain · +6 kL";
document.querySelectorAll(".speed").forEach(button => {
button.classList.toggle("active", Number(button.dataset.speed) === sim.speed);
});
updateHistoryChart();
}
function setSpeed(speed) {
sim.speed = speed;
updateUI();
}
function togglePause() {
sim.running = !sim.running;
updateUI();
showToast(sim.running ? "Simulation resumed." : "Simulation paused.");
}
function callRain() {
if (sim.rainUsedSeason) return;
sim.rainPending = true;
sim.rainUsedSeason = true;
sim.weatherRain = 7;
addLog(`Rain is queued: +${CONFIG.rainBoost} kL of inflow tomorrow.`, "good");
updateUI();
showToast("Rain called! The reservoir gains 6 kL on the next day.");
}
function resetSimulation() {
sim = freshSimulation();
dayAccumulator = 0;
logEntries = [];
$("householdSlider").value = 260;
$("gardenSlider").value = 400;
setSeasonTargets(0);
scene.background.set(SEASONS[0].sky);
scene.fog.color.set(SEASONS[0].sky);
addLog("Spring opens with 68 kL in storage. All village requests are being tracked.", "good");
updateUI();
resetCamera();
showToast("A new four-season run has started.");
}
$("householdSlider").addEventListener("input", event => {
sim.householdRate = Number(event.target.value);
updateUI();
});
$("gardenSlider").addEventListener("input", event => {
sim.gardenRate = Number(event.target.value);
updateUI();
});
document.querySelectorAll(".speed").forEach(button => {
button.addEventListener("click", () => setSpeed(Number(button.dataset.speed)));
});
$("pauseBtn").addEventListener("click", togglePause);
$("rainBtn").addEventListener("click", callRain);
$("resetBtn").addEventListener("click", resetSimulation);
$("cameraReset").addEventListener("click", resetCamera);
function setPanelOpen(open) {
$("controlPanel").classList.toggle("closed", !open);
$("panelToggle").textContent = open ? "Hide panel" : "Controls";
$("panelToggle").setAttribute("aria-expanded", String(open));
}
$("panelToggle").addEventListener("click", () => {
setPanelOpen($("controlPanel").classList.contains("closed"));
});
$("closePanel").addEventListener("click", () => setPanelOpen(false));
// ------------------------------------------------------------
// Animation loop
// ------------------------------------------------------------
const clock = new THREE.Clock();
let elapsed = 0;
function updateWater() {
const storageRatio = sim.storage / CONFIG.capacity;
const height = .12 + storageRatio * 2.9;
waterMesh.scale.y = height;
waterMesh.position.y = .15 + height / 2;
shimmerMeshes.forEach((mesh, index) => {
mesh.position.y = .17 + height + .015;
mesh.position.x = -11.3 + (index * 1.07) % 9.6 +
Math.sin(elapsed * 1.1 + index) * .12;
mesh.material.opacity = .42 + Math.sin(elapsed * 1.5 + index) * .12;
});
}
function updatePrecipitation(dt) {
const winter = sim.seasonIndex === 3;
const raining = sim.weatherRain > 0;
precipitation.visible = winter || raining;
if (!precipitation.visible) return;
precipitationMaterial.size = winter ? .13 : .065;
precipitationMaterial.opacity = winter ? .82 : .58;
const positions = precipitationGeometry.attributes.position.array;
const fallSpeed = winter ? 1.25 : 9.5;
for (let i = 0; i < precipitationCount; i++) {
const index = i * 3;
positions[index + 1] -= dt * fallSpeed;
positions[index] += dt * (winter ? .15 : -.7);
if (positions[index + 1] < .4) {
positions[index + 1] = 13 + Math.random() * 3;
positions[index] = (Math.random() - .5) * 36;
positions[index + 2] = (Math.random() - .5) * 27;
}
}
precipitationGeometry.attributes.position.needsUpdate = true;
}
function animate() {
const dt = Math.min(clock.getDelta(), .05);
elapsed += dt;
if (sim.running) {
dayAccumulator += dt * sim.speed;
while (dayAccumulator >= CONFIG.dayDuration) {
dayAccumulator -= CONFIG.dayDuration;
processDay();
}
}
if (sim.weatherRain > 0) sim.weatherRain = Math.max(0, sim.weatherRain - dt);
const blend = 1 - Math.exp(-dt * 2.3);
scene.background.lerp(targetBackground, blend);
scene.fog.color.copy(scene.background);
groundMaterial.color.lerp(targetGround, blend);
leafMaterial.color.lerp(targetLeaf, blend);
cropMaterial.color.lerp(targetCrop, blend);
waterMaterial.color.lerp(targetWater, blend);
updateWater();
updatePrecipitation(dt);
droplets.forEach((drop, index) => {
const phase = (elapsed * .24 + index / droplets.length) % 1;
drop.position.z = -10 + phase * 3.7;
drop.position.x = -9.1 + Math.sin(phase * Math.PI) * .3;
drop.position.y = .38 + Math.sin(phase * Math.PI) * .15;
const pulse = .85 + Math.sin(elapsed * 6 + index) * .15;
drop.scale.setScalar(pulse);
});
rotor.rotation.z -= dt * .7;
clouds.forEach((cloud, index) => {
cloud.position.x += dt * (.22 + index * .025);
if (cloud.position.x > 23) cloud.position.x = -23;
});
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
addLog("Spring opens with 68 kL in storage. All village requests are being tracked.", "good");
setSeasonTargets(0);
updateUI();
animate();
requestAnimationFrame(() => {
$("loading").classList.add("hidden");
setTimeout(() => $("loading").remove(), 450);
});
</script>
</body>
</html>
```