Prompt specification
Build or customize the Three.js 3D scene "Original River Town Management Board" 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: Original River Town Management Board
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/original-river-town-management-board-x3559
Scene Description Prompt:
I'd like to see this as a voxel Three.js scene: original river town management board. Build a bounded voxel town with homes, farms, and water distribution. Use fictional transparent rates and let population changes expose capacity limits. Use cdnjs and return one self-contained HTML file.
Working Three.js Starter (original-river-town-management-board-x3559):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Riverworks — Voxel River Town</title>
<style>
:root {
--bg: #091217;
--panel: rgba(13, 26, 32, 0.92);
--panel-2: rgba(19, 37, 44, 0.88);
--line: rgba(150, 210, 214, 0.15);
--text: #e5f1ed;
--muted: #8ea7a7;
--cyan: #65d9d0;
--cyan-2: #2aa89f;
--gold: #efc66f;
--red: #f47f73;
--green: #8fd79b;
--blue: #5cbde4;
--shadow: 0 18px 50px rgba(0, 0, 0, 0.32);
}
* {
box-sizing: border-box;
}
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input {
font: inherit;
}
button {
color: inherit;
}
#app {
position: relative;
width: 100%;
height: 100%;
background:
radial-gradient(circle at 50% 42%, rgba(36, 74, 78, 0.18), transparent 46%),
var(--bg);
}
.topbar {
position: absolute;
inset: 0 0 auto 0;
z-index: 20;
height: 66px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 18px;
border-bottom: 1px solid var(--line);
background: rgba(8, 18, 23, 0.88);
backdrop-filter: blur(18px);
}
.brand {
display: flex;
align-items: center;
gap: 11px;
min-width: 250px;
}
.brand-mark {
width: 34px;
height: 34px;
border-radius: 8px;
position: relative;
background:
linear-gradient(135deg, rgba(101, 217, 208, 0.22), rgba(101, 217, 208, 0.04)),
#12282d;
border: 1px solid rgba(101, 217, 208, 0.38);
box-shadow: inset 0 0 20px rgba(101, 217, 208, 0.08);
}
.brand-mark::before {
content: "";
position: absolute;
left: 6px;
right: 6px;
top: 9px;
height: 6px;
background: var(--cyan);
clip-path: polygon(0 50%, 25% 50%, 38% 0, 62% 100%, 75% 50%, 100% 50%, 100% 100%, 0 100%);
opacity: 0.9;
}
.brand-mark::after {
content: "";
position: absolute;
left: 10px;
right: 10px;
bottom: 7px;
height: 7px;
background: #4b7073;
clip-path: polygon(0 100%, 0 40%, 25% 40%, 25% 0, 75% 0, 75% 40%, 100% 40%, 100% 100%);
}
.brand h1 {
margin: 0;
font-size: 15px;
line-height: 1;
letter-spacing: 0.17em;
text-transform: uppercase;
}
.brand p {
margin: 5px 0 0;
font-size: 10px;
color: var(--muted);
letter-spacing: 0.08em;
text-transform: uppercase;
}
.top-center {
text-align: center;
}
.date-label {
font-size: 12px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.date-sub {
margin-top: 4px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.08em;
}
.top-actions {
display: flex;
align-items: center;
gap: 8px;
min-width: 250px;
justify-content: flex-end;
}
.button {
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.035);
border-radius: 9px;
padding: 9px 12px;
cursor: pointer;
transition: 150ms ease;
font-size: 11px;
font-weight: 750;
letter-spacing: 0.035em;
}
.button:hover {
border-color: rgba(101, 217, 208, 0.45);
background: rgba(101, 217, 208, 0.08);
transform: translateY(-1px);
}
.button.primary {
color: #092024;
background: var(--cyan);
border-color: var(--cyan);
box-shadow: 0 8px 24px rgba(42, 168, 159, 0.18);
}
.button.primary:hover {
background: #83e6de;
}
.button.active {
color: var(--cyan);
border-color: rgba(101, 217, 208, 0.55);
background: rgba(101, 217, 208, 0.12);
}
.panel {
position: absolute;
z-index: 15;
top: 80px;
bottom: 18px;
width: 286px;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--panel);
backdrop-filter: blur(20px);
box-shadow: var(--shadow);
overflow: auto;
scrollbar-width: thin;
scrollbar-color: rgba(101, 217, 208, 0.25) transparent;
}
.panel.left {
left: 14px;
}
.panel.right {
right: 14px;
}
.panel::-webkit-scrollbar {
width: 6px;
}
.panel::-webkit-scrollbar-thumb {
background: rgba(101, 217, 208, 0.25);
border-radius: 8px;
}
.section {
padding: 17px;
border-bottom: 1px solid var(--line);
}
.section:last-child {
border-bottom: 0;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 13px;
}
.section-title h2 {
margin: 0;
font-size: 11px;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.eyebrow {
color: var(--muted);
font-size: 9px;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.badge {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 4px 7px;
border-radius: 999px;
background: rgba(239, 198, 111, 0.1);
border: 1px solid rgba(239, 198, 111, 0.2);
color: var(--gold);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stats-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.stat {
min-height: 72px;
padding: 11px;
border-radius: 11px;
background:
linear-gradient(140deg, rgba(255, 255, 255, 0.04), transparent),
var(--panel-2);
border: 1px solid rgba(255, 255, 255, 0.045);
}
.stat-label {
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stat-value {
margin-top: 6px;
font-size: 23px;
font-weight: 760;
line-height: 1;
}
.stat-detail {
margin-top: 5px;
color: var(--muted);
font-size: 9px;
}
.stat-value.cyan { color: var(--cyan); }
.stat-value.gold { color: var(--gold); }
.stat-value.green { color: var(--green); }
.district {
margin-bottom: 13px;
}
.district:last-child {
margin-bottom: 0;
}
.district-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 6px;
font-size: 10px;
}
.district-name {
font-weight: 800;
letter-spacing: 0.04em;
}
.district-value {
color: var(--muted);
font-variant-numeric: tabular-nums;
}
.meter {
height: 7px;
border-radius: 99px;
overflow: hidden;
background: rgba(255, 255, 255, 0.065);
}
.meter > span {
display: block;
height: 100%;
width: 0;
border-radius: inherit;
background: var(--green);
transition: width 350ms ease, background 250ms ease;
}
.meter.warn > span { background: var(--gold); }
.meter.bad > span { background: var(--red); }
.district-meta {
display: flex;
justify-content: space-between;
gap: 8px;
margin-top: 5px;
color: #718c8d;
font-size: 8px;
}
.policy-row {
margin-bottom: 15px;
}
.policy-row:last-child {
margin-bottom: 0;
}
.policy-head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 8px;
font-size: 10px;
}
.policy-head strong {
color: var(--cyan);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
.range-scale {
display: flex;
justify-content: space-between;
color: #698283;
font-size: 8px;
margin-top: 3px;
}
.toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid var(--line);
}
.toggle-copy strong {
display: block;
font-size: 10px;
}
.toggle-copy span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8px;
}
.switch {
position: relative;
flex: 0 0 auto;
width: 34px;
height: 19px;
}
.switch input {
position: absolute;
opacity: 0;
pointer-events: none;
}
.switch-track {
position: absolute;
inset: 0;
border-radius: 20px;
background: #26383b;
border: 1px solid rgba(255, 255, 255, 0.07);
cursor: pointer;
transition: 150ms;
}
.switch-track::after {
content: "";
position: absolute;
width: 13px;
height: 13px;
left: 2px;
top: 2px;
border-radius: 50%;
background: #789091;
transition: 150ms;
}
.switch input:checked + .switch-track {
background: rgba(42, 168, 159, 0.3);
border-color: rgba(101, 217, 208, 0.4);
}
.switch input:checked + .switch-track::after {
left: 17px;
background: var(--cyan);
}
.tools {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.tool {
position: relative;
min-height: 68px;
padding: 10px;
text-align: left;
border: 1px solid rgba(255, 255, 255, 0.055);
border-radius: 11px;
background: rgba(255, 255, 255, 0.028);
cursor: pointer;
transition: 140ms ease;
}
.tool:hover {
border-color: rgba(101, 217, 208, 0.35);
background: rgba(101, 217, 208, 0.055);
}
.tool.selected {
border-color: var(--cyan);
background: rgba(101, 217, 208, 0.11);
box-shadow: inset 0 0 20px rgba(101, 217, 208, 0.04);
}
.tool-icon {
display: block;
width: 22px;
height: 22px;
margin-bottom: 8px;
color: var(--cyan);
}
.tool-name {
display: block;
font-size: 10px;
font-weight: 800;
}
.tool-cost {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8px;
}
.tool-key {
position: absolute;
right: 7px;
top: 7px;
color: #577172;
font-size: 8px;
}
.tool-hint {
margin-top: 11px;
padding: 9px 10px;
border-radius: 9px;
background: rgba(101, 217, 208, 0.055);
color: #a9c3c2;
font-size: 9px;
line-height: 1.5;
}
.rate-list {
display: grid;
gap: 8px;
}
.rate {
display: grid;
grid-template-columns: 1fr auto;
gap: 10px;
padding-bottom: 8px;
border-bottom: 1px dashed rgba(255, 255, 255, 0.075);
}
.rate:last-child {
border-bottom: 0;
padding-bottom: 0;
}
.rate strong {
display: block;
font-size: 9px;
}
.rate span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8px;
line-height: 1.4;
}
.rate b {
align-self: start;
color: var(--gold);
font-size: 9px;
white-space: nowrap;
}
.inspector-title {
margin: 0 0 6px;
font-size: 14px;
}
.inspector-copy {
margin: 0;
color: var(--muted);
font-size: 9px;
line-height: 1.65;
}
.inspector-tags {
display: flex;
flex-wrap: wrap;
gap: 5px;
margin-top: 10px;
}
.tag {
padding: 4px 6px;
border-radius: 5px;
background: rgba(255, 255, 255, 0.05);
color: #b7cdca;
font-size: 8px;
}
.tag.good {
color: var(--green);
background: rgba(143, 215, 155, 0.08);
}
.tag.bad {
color: var(--red);
background: rgba(244, 127, 115, 0.08);
}
#viewport {
position: absolute;
z-index: 5;
left: 314px;
right: 314px;
top: 78px;
bottom: 58px;
overflow: hidden;
border-radius: 18px;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
outline: none;
}
#viewport canvas.dragging {
cursor: grabbing;
}
#labels {
position: absolute;
inset: 0;
pointer-events: none;
overflow: hidden;
}
.district-label {
position: absolute;
left: 0;
top: 0;
min-width: 112px;
padding: 7px 9px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 8px;
background: rgba(8, 20, 24, 0.72);
backdrop-filter: blur(8px);
box-shadow: 0 8px 22px rgba(0, 0, 0, 0.18);
text-align: center;
will-change: transform;
}
.district-label strong {
display: block;
font-size: 8px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.district-label span {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 8px;
}
#eventFeed {
position: absolute;
z-index: 12;
left: 328px;
right: 328px;
bottom: 10px;
min-height: 36px;
display: flex;
align-items: center;
gap: 9px;
overflow: hidden;
pointer-events: none;
}
.event-item {
flex: 0 0 auto;
max-width: 390px;
padding: 8px 11px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(11, 25, 30, 0.88);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.18);
color: #abc0bf;
font-size: 9px;
white-space: nowrap;
}
.event-item:first-child {
color: var(--text);
border-color: rgba(101, 217, 208, 0.25);
}
.event-item.good { border-left: 3px solid var(--green); }
.event-item.warn { border-left: 3px solid var(--gold); }
.event-item.bad { border-left: 3px solid var(--red); }
#toast {
position: absolute;
z-index: 40;
left: 50%;
top: 82px;
max-width: 420px;
padding: 10px 15px;
border: 1px solid rgba(101, 217, 208, 0.3);
border-radius: 10px;
background: rgba(11, 28, 32, 0.96);
box-shadow: var(--shadow);
color: #d8e8e4;
font-size: 10px;
opacity: 0;
pointer-events: none;
transform: translate(-50%, -8px);
transition: 180ms ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.bad {
border-color: rgba(244, 127, 115, 0.45);
}
#hoverTip {
position: fixed;
z-index: 50;
padding: 6px 8px;
border: 1px solid rgba(255, 255, 255, 0.09);
border-radius: 6px;
background: rgba(7, 17, 21, 0.94);
color: #dceae7;
font-size: 8px;
pointer-events: none;
opacity: 0;
transition: opacity 100ms;
white-space: nowrap;
}
#loading {
position: absolute;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
background: var(--bg);
color: var(--cyan);
font-size: 11px;
letter-spacing: 0.16em;
text-transform: uppercase;
transition: opacity 300ms ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
.water-dot {
display: inline-block;
width: 7px;
height: 7px;
margin-right: 6px;
border-radius: 50%;
background: var(--blue);
box-shadow: 0 0 12px rgba(92, 189, 228, 0.65);
}
@media (max-width: 1150px) {
.panel { width: 248px; }
#viewport { left: 274px; right: 274px; }
#eventFeed { left: 286px; right: 286px; }
.top-center { display: none; }
}
@media (max-width: 820px) {
.brand p, .top-actions .button:not(.primary) { display: none; }
.panel { width: 220px; }
.panel.left { left: 8px; }
.panel.right { right: 8px; }
#viewport { left: 238px; right: 238px; }
#eventFeed { left: 244px; right: 244px; }
.section { padding: 13px; }
}
</style>
</head>
<body>
<div id="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark"></div>
<div>
<h1>Riverworks</h1>
<p>Voxel civic board · River District 07</p>
</div>
</div>
<div class="top-center">
<div id="dateLabel" class="date-label">Month 01 · Spring</div>
<div id="dateSub" class="date-sub">Water year begins · forecast clear</div>
</div>
<div class="top-actions">
<button id="autoBtn" class="button">Auto run</button>
<button id="resetBtn" class="button">Reset</button>
<button id="nextBtn" class="button primary">Advance month →</button>
</div>
</header>
<aside class="panel left">
<section class="section">
<div class="section-title">
<h2>Town ledger</h2>
<span class="eyebrow">Live census</span>
</div>
<div class="stats-grid">
<div class="stat">
<div class="stat-label">Population</div>
<div id="populationStat" class="stat-value cyan">58</div>
<div id="populationDetail" class="stat-detail">58 / 228 housed</div>
</div>
<div class="stat">
<div class="stat-label">Treasury</div>
<div id="treasuryStat" class="stat-value gold">960</div>
<div class="stat-detail">fictional crowns</div>
</div>
<div class="stat">
<div class="stat-label">Farm jobs</div>
<div id="jobsStat" class="stat-value green">42</div>
<div id="farmsDetail" class="stat-detail">7 working farms</div>
</div>
<div class="stat">
<div class="stat-label">Water stress</div>
<div id="stressStat" class="stat-value green">0%</div>
<div id="intakeDetail" class="stat-detail">260 unit intake</div>
</div>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>Water districts</h2>
<span class="badge">Fictional rates</span>
</div>
<div id="districtList"></div>
</section>
<section class="section">
<div class="section-title">
<h2>Civic policy</h2>
<span class="eyebrow">Monthly</span>
</div>
<div class="policy-row">
<div class="policy-head">
<span>Water tariff</span>
<strong id="tariffValue">1.00 cr</strong>
</div>
<input id="tariff" type="range" min="0.6" max="2.2" step="0.05" value="1">
<div class="range-scale">
<span>0.60 · accessible</span>
<span>2.20 · exclusive</span>
</div>
</div>
<div class="toggle-row">
<div class="toggle-copy">
<strong>Conservation order</strong>
<span>18% lower residential demand</span>
</div>
<label class="switch">
<input id="conservation" type="checkbox">
<span class="switch-track"></span>
</label>
</div>
<div class="toggle-row">
<div class="toggle-copy">
<strong>Housing grant</strong>
<span>+2 arrivals, 45 crowns / month</span>
</div>
<label class="switch">
<input id="grant" type="checkbox">
<span class="switch-track"></span>
</label>
</div>
</section>
</aside>
<main id="viewport" aria-label="Interactive voxel town board">
<div id="labels"></div>
</main>
<aside class="panel right">
<section class="section">
<div class="section-title">
<h2>Works board</h2>
<span class="eyebrow">Build & inspect</span>
</div>
<div class="tools">
<button class="tool selected" data-tool="inspect">
<span class="tool-key">1</span>
<span class="tool-icon">⌖</span>
<span class="tool-name">Inspect</span>
<span class="tool-cost">Read a lot</span>
</button>
<button class="tool" data-tool="home">
<span class="tool-key">2</span>
<span class="tool-icon">⌂</span>
<span class="tool-name">Residence</span>
<span class="tool-cost">120 cr · +12 people</span>
</button>
<button class="tool" data-tool="farm">
<span class="tool-key">3</span>
<span class="tool-icon">♧</span>
<span class="tool-name">Farm</span>
<span class="tool-cost">90 cr · +6 jobs</span>
</button>
<button class="tool" data-tool="cistern">
<span class="tool-key">4</span>
<span class="tool-icon">▱</span>
<span class="tool-name">Cistern</span>
<span class="tool-cost">75 cr · +45 storage</span>
</button>
<button class="tool" data-tool="pipe">
<span class="tool-key">5</span>
<span class="tool-icon">━</span>
<span class="tool-name">Water main</span>
<span class="tool-cost">18 cr · 1 tile</span>
</button>
<button class="tool" data-tool="bulldoze">
<span class="tool-key">6</span>
<span class="tool-icon">×</span>
<span class="tool-name">Demolish</span>
<span class="tool-cost">35% refund</span>
</button>
</div>
<div id="toolHint" class="tool-hint">
Inspect any building, lot, cistern, or main to read its live status.
</div>
</section>
<section class="section">
<div class="section-title">
<h2>Transparent rate card</h2>
<span class="eyebrow">Per month</span>
</div>
<div class="rate-list">
<div class="rate">
<div>
<strong>River intake</strong>
<span>260 spring, 235 summer, 245 autumn, 220 winter units.</span>
</div>
<b>220–260</b>
</div>
<div class="rate">
<div>
<strong>Residence</strong>
<span>12 residents; 3 water units per resident.</span>
</div>
<b>120 cr</b>
</div>
<div class="rate">
<div>
<strong>Farm</strong>
<span>6 jobs; 9 water units per month.</span>
</div>
<b>90 cr</b>
</div>
<div class="rate">
<div>
<strong>Cistern</strong>
<span>Adds 45 units of local storage capacity.</span>
</div>
<b>75 cr</b>
</div>
<div class="rate">
<div>
<strong>Water main</strong>
<span>Extends one tile from an existing live main.</span>
</div>
<b>18 cr</b>
</div>
<div class="rate">
<div>
<strong>Tariff income</strong>
<span>0.70 crown per resident before network upkeep.</span>
</div>
<b>0.70 cr</b>
</div>
<div class="rate">
<div>
<strong>Network upkeep</strong>
<span>0.12 crown per main; farms cost 3, cisterns 2.</span>
</div>
<b>0.12 cr</b>
</div>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>Inspector</h2>
<span class="eyebrow" id="inspectorCoords">No selection</span>
</div>
<h3 id="inspectorTitle" class="inspector-title">Choose a lot</h3>
<p id="inspectorCopy" class="inspector-copy">
Click a building or water main to see capacity, service, and local district information.
</p>
<div id="inspectorTags" class="inspector-tags"></div>
</section>
</aside>
<div id="eventFeed"></div>
<div id="toast"></div>
<div id="hoverTip"></div>
<div id="loading"><span><span class="water-dot"></span>Assembling river district…</span></div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const COLS = 30;
const ROWS = 24;
const SOURCE = { x: 23, z: 12 };
const COSTS = {
home: 120,
farm: 90,
cistern: 75,
pipe: 18
};
const DISTRICT_NAMES = ["Upper Rill", "Mill Quarter", "Southbank"];
const PIPE_CAPS = [135, 155, 140];
const DISTRICT_COLORS = [0x74d9d0, 0xefc66f, 0x83c9ef];
const viewport = document.getElementById("viewport");
const labelsLayer = document.getElementById("labels");
const toast = document.getElementById("toast");
const hoverTip = document.getElementById("hoverTip");
const keyOf = (x, z) => `${x},${z}`;
const inBounds = (x, z) => x >= 0 && x < COLS && z >= 0 && z < ROWS;
const districtOf = z => z < 8 ? 0 : z < 16 ? 1 : 2;
const seasonOf = month => ["Spring", "Summer", "Autumn", "Winter"][Math.floor((month - 1) / 3) % 4];
const intakeOf = month => [260, 235, 245, 220][Math.floor((month - 1) / 3) % 4];
const worldX = x => x - (COLS - 1) / 2;
const worldZ = z => z - (ROWS - 1) / 2;
let state;
let currentTool = "inspect";
let selected = null;
let toastTimer;
let autoTimer = null;
const initialAssets = [
["home", 19, 4], ["home", 19, 6], ["home", 17, 4],
["home", 15, 6], ["home", 12, 4], ["home", 12, 6],
["farm", 8, 4], ["farm", 6, 6], ["cistern", 21, 6],
["home", 19, 10], ["home", 19, 14], ["home", 17, 13],
["home", 13, 10], ["home", 13, 14], ["home", 7, 12],
["home", 7, 10], ["home", 7, 14],
["farm", 18, 10], ["farm", 11, 9], ["cistern", 21, 14],
["home", 19, 16], ["home", 19, 18], ["home", 17, 20],
["home", 13, 16], ["home", 15, 20], ["home", 11, 20],
["home", 7, 16],
["farm", 11, 19], ["farm", 19, 20], ["farm", 5, 20],
["cistern", 21, 18]
];
function makeInitialState() {
const next = {
month: 1,
population: 58,
treasury: 960,
tariff: 1,
conservation: false,
grant: false,
assets: new Map(),
pipes: new Set(),
storage: [48, 55, 42]
};
for (const [type, x, z] of initialAssets) {
next.assets.set(keyOf(x, z), {
type,
x,
z,
district: districtOf(z),
statusMaterial: null,
group: null
});
}
for (const z of [5, 11, 17]) {
for (let x = 4; x <= 20; x++) next.pipes.add(keyOf(x, z));
}
for (const x of [4, 10, 16, 20]) {
for (let z = 5; z <= 20; z++) next.pipes.add(keyOf(x, z));
}
for (let x = 20; x <= 22; x++) next.pipes.add(keyOf(x, 12));
return next;
}
function riverX(z) {
return 25 + Math.round(1.2 * Math.sin(z * 0.46));
}
function isRiver(x, z) {
return riverX(z) === x;
}
function isRoad(x, z) {
return (
x === 4 || x === 10 || x === 16 || x === 20 ||
z === 5 || z === 11 || z === 17 ||
(z === 12 && x >= 20 && x <= 22)
);
}
function neighbors(x, z) {
return [
{ x: x + 1, z },
{ x: x - 1, z },
{ x, z: z + 1 },
{ x, z: z - 1 }
].filter(n => inBounds(n.x, n.z));
}
// ---------- Three.js scene ----------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a151a);
scene.fog = new THREE.Fog(0x0a151a, 55, 100);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.18;
viewport.appendChild(renderer.domElement);
const camera = new THREE.OrthographicCamera(-20, 20, 20, -20, 0.1, 200);
const cameraTarget = new THREE.Vector3(0, 0, 0);
let cameraTheta = 0.72;
let cameraPhi = 0.69;
let cameraRadius = 48;
let cameraZoom = 1;
function updateCamera() {
const horizontal = cameraRadius * Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + horizontal * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + horizontal * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
camera.zoom = cameraZoom;
camera.updateProjectionMatrix();
}
function resize() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
const aspect = width / height;
const viewHeight = 41;
camera.left = -viewHeight * aspect / 2;
camera.right = viewHeight * aspect / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
new ResizeObserver(resize).observe(viewport);
window.addEventListener("resize", resize);
const hemi = new THREE.HemisphereLight(0xbce9e3, 0x263329, 2.1);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xffefcf, 3.1);
sun.position.set(-18, 31, 17);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -25;
sun.shadow.camera.right = 25;
sun.shadow.camera.top = 25;
sun.shadow.camera.bottom = -25;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 80;
sun.shadow.bias = -0.0004;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x69c8e2, 1.05);
rim.position.set(20, 12, -18);
scene.add(rim);
const boardGroup = new THREE.Group();
const buildingGroup = new THREE.Group();
const networkGroup = new THREE.Group();
const decorGroup = new THREE.Group();
scene.add(boardGroup, buildingGroup, networkGroup, decorGroup);
const terrainGroup = new THREE.Group();
boardGroup.add(terrainGroup);
const pickables = [terrainGroup, buildingGroup, networkGroup, decorGroup];
let terrainMesh;
let riverMesh;
const terrainCells = [];
const riverCells = [];
const decor = new Set();
const waterGlints = [];
const material = (color, roughness = 0.8, metalness = 0) =>
new THREE.MeshStandardMaterial({ color, roughness, metalness });
const baseMaterial = material(0x25363a);
const foundationMaterial = material(0x647072);
const roofMaterials = [
material(0xad6554),
material(0x517f83),
material(0x9b7858)
];
const wallMaterials = [
material(0xd8c9a6),
material(0xc8d4c9),
material(0xd7bfa8)
];
const pipeMaterial = material(0x43bfc0, 0.45, 0.22);
const pipeCoreMaterial = material(0x8ce6dd, 0.3, 0.15);
const soilMaterial = material(0x6d5945);
const cropMaterials = [material(0x88b95b), material(0xc4ba5a)];
const trunkMaterial = material(0x66503b);
const leafMaterials = [material(0x3f8065), material(0x4f9270), material(0x2e6956)];
const windowMaterial = material(0xf2d889, 0.35, 0.05);
function box(parent, w, h, d, x, y, z, mat, cast = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), mat);
mesh.position.set(x, y, z);
mesh.castShadow = cast;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function buildTerrain() {
const base = new THREE.Mesh(
new THREE.BoxGeometry(COLS + 0.8, 0.9, ROWS + 0.8),
baseMaterial
);
base.position.y = -0.45;
base.receiveShadow = true;
terrainGroup.add(base);
const tileGeometry = new THREE.BoxGeometry(0.96, 0.16, 0.96);
const tileMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.95
});
const landCells = [];
const colors = [];
for (let z = 0; z < ROWS; z++) {
for (let x = 0; x < COLS; x++) {
if (isRiver(x, z)) continue;
landCells.push({ x, z });
let color;
if (isRoad(x, z)) {
color = new THREE.Color(0x526166);
} else if (x >= 21) {
color = new THREE.Color(0x738068);
} else {
const variation = (x * 13 + z * 7) % 5;
color = new THREE.Color([
0x66835e, 0x6d895f, 0x607c58, 0x718d62, 0x647f5a
][variation]);
}
colors.push(color);
}
}
terrainMesh = new THREE.InstancedMesh(tileGeometry, tileMaterial, landCells.length);
terrainMesh.receiveShadow = true;
terrainMesh.userData.kind = "terrain";
const matrix = new THREE.Matrix4();
landCells.forEach((cell, index) => {
matrix.makeTranslation(worldX(cell.x), 0.07, worldZ(cell.z));
terrainMesh.setMatrixAt(index, matrix);
terrainMesh.setColorAt(index, colors[index]);
terrainCells[index] = keyOf(cell.x, cell.z);
});
terrainMesh.instanceMatrix.needsUpdate = true;
terrainMesh.instanceColor.needsUpdate = true;
terrainGroup.add(terrainMesh);
const riverMaterial = new THREE.MeshStandardMaterial({
color: 0x3d9fb9,
emissive: 0x123e4b,
emissiveIntensity: 0.35,
roughness: 0.2,
metalness: 0.12,
transparent: true,
opacity: 0.72
});
const waterGeometry = new THREE.BoxGeometry(0.99, 0.09, 0.99);
const riverList = [];
for (let z = 0; z < ROWS; z++) {
const x = riverX(z);
riverList.push({ x, z });
riverCells.push(keyOf(x, z));
}
riverMesh = new THREE.InstancedMesh(waterGeometry, riverMaterial, riverList.length);
riverMesh.userData.kind = "river";
riverMesh.receiveShadow = true;
riverList.forEach((cell, index) => {
matrix.makeTranslation(worldX(cell.x), 0.085, worldZ(cell.z));
riverMesh.setMatrixAt(index, matrix);
});
riverMesh.instanceMatrix.needsUpdate = true;
terrainGroup.add(riverMesh);
// Low perimeter fence, built from small voxel posts and rails.
const postMaterial = material(0x8d8d76);
const railMaterial = material(0x6b7167);
const fenceY = 0.42;
for (let x = 0; x < COLS; x += 2) {
for (const z of [-0.55, ROWS - 0.45]) {
box(
terrainGroup, 0.12, 0.6, 0.12,
worldX(x), fenceY, worldZ(z), postMaterial, false
);
}
}
for (let z = 0; z < ROWS; z += 2) {
for (const x of [-0.55, COLS - 0.45]) {
box(
terrainGroup, 0.12, 0.6, 0.12,
worldX(x), fenceY, worldZ(z), postMaterial, false
);
}
}
for (const z of [-0.55, ROWS - 0.45]) {
box(
terrainGroup, COLS, 0.1, 0.1,
0, 0.52, worldZ(z), railMaterial, false
);
}
for (const x of [-0.55, COLS - 0.45]) {
box(
terrainGroup, 0.1, 0.1, ROWS,
worldX(x), 0.52, 0, railMaterial, false
);
}
// Small moving highlights make the river read as flowing water.
const glintMaterial = new THREE.MeshBasicMaterial({
color: 0xc8f4f2,
transparent: true,
opacity: 0.38
});
for (let i = 0; i < 8; i++) {
const glint = new THREE.Mesh(
new THREE.BoxGeometry(0.32, 0.025, 0.06),
glintMaterial
);
boardGroup.add(glint);
waterGlints.push({
mesh: glint,
z: i * 3.1,
speed: 0.22 + (i % 3) * 0.045,
phase: i * 1.7
});
}
}
let randomSeed = 72107;
function random() {
randomSeed = (randomSeed * 1664525 + 1013904223) >>> 0;
return randomSeed / 4294967296;
}
function buildDecor() {
decor.clear();
decorGroup.clear();
const occupied = new Set(state.assets.keys());
for (let attempt = 0; attempt < 250 && decor.size < 34; attempt++) {
const x = 1 + Math.floor(random() * 21);
const z = Math.floor(random() * ROWS);
const key = keyOf(x, z);
if (
isRiver(x, z) ||
isRoad(x, z) ||
occupied.has(key) ||
state.pipes.has(key) ||
decor.has(key)
) continue;
decor.add(key);
const group = new THREE.Group();
group.position.set(worldX(x), 0.15, worldZ(z));
group.userData.cell = key;
group.userData.decor = true;
const height = 0.65 + random() * 0.45;
box(group, 0.14, height, 0.14, 0, height / 2, 0, trunkMaterial);
box(
group, 0.52, 0.38, 0.52, 0, height + 0.05, 0,
leafMaterials[Math.floor(random() * leafMaterials.length)]
);
box(
group, 0.34, 0.28, 0.34, 0.08, height + 0.32, -0.04,
leafMaterials[Math.floor(random() * leafMaterials.length)]
);
decorGroup.add(group);
}
}
// ---------- Buildings and water network ----------
function createHouse(asset) {
const group = new THREE.Group();
group.position.set(worldX(asset.x), 0.15, worldZ(asset.z));
group.userData.cell = keyOf(asset.x, asset.z);
const d = asset.district;
box(group, 0.77, 0.12, 0.77, 0, 0.06, 0, foundationMaterial);
box(group, 0.58, 0.42, 0.58, 0, 0.33, 0, wallMaterials[d]);
const roof = roofMaterials[d];
box(group, 0.72, 0.12, 0.72, 0, 0.6, 0, roof);
box(group, 0.48, 0.12, 0.48, 0, 0.72, 0, roof);
const door = material(0x4d5b55);
box(group, 0.15, 0.25, 0.035, 0, 0.25, 0.302, door);
const statusMat = material(0xf1d57e, 0.25, 0.05);
box(group, 0.11, 0.11, 0.035, -0.17, 0.37, 0.302, statusMat, false);
box(group, 0.11, 0.11, 0.035, 0.17, 0.37, 0.302, statusMat, false);
box(group, 0.11, 0.11, 0.035, 0.17, 0.37, -0.302, statusMat, false);
box(group, 0.1, 0.25, 0.1, 0.2, 0.75, -0.16, foundationMaterial);
asset.statusMaterial = statusMat;
asset.group = group;
return group;
}
function createFarm(asset) {
const group = new THREE.Group();
group.position.set(worldX(asset.x), 0.15, worldZ(asset.z));
group.userData.cell = keyOf(asset.x, asset.z);
box(group, 0.84, 0.08, 0.84, 0, 0.04, 0, soilMaterial);
for (let ix = -1; ix <= 1; ix++) {
for (let iz = -1; iz <= 1; iz++) {
if (ix === 0 && iz === 0) continue;
const cropMat = cropMaterials[(ix + iz + 3) % 2];
box(
group, 0.15, 0.13 + ((ix + iz + 2) % 2) * 0.04, 0.15,
ix * 0.2, 0.14, iz * 0.2, cropMat
);
}
}
box(group, 0.25, 0.35, 0.28, 0.24, 0.25, 0.18, wallMaterials[1]);
box(group, 0.31, 0.08, 0.34, 0.24, 0.46, 0.18, roofMaterials[1]);
const statusMat = material(0xf1d57e, 0.25, 0.05);
box(group, 0.08, 0.08, 0.035, 0.24, 0.29, 0.327, statusMat, false);
asset.statusMaterial = statusMat;
asset.group = group;
return group;
}
function createCistern(asset) {
const group = new THREE.Group();
group.position.set(worldX(asset.x), 0.15, worldZ(asset.z));
group.userData.cell = keyOf(asset.x, asset.z);
box(group, 0.82, 0.12, 0.82, 0, 0.06, 0, foundationMaterial);
box(group, 0.67, 0.3, 0.67, 0, 0.26, 0, material(0x87928a));
const waterMat = new THREE.MeshStandardMaterial({
color: 0x57cbd2,
emissive: 0x164d58,
emissiveIntensity: 0.28,
roughness: 0.25,
metalness: 0.1,
transparent: true,
opacity: 0.9
});
box(group, 0.56, 0.05, 0.56, 0, 0.43, 0, waterMat, false);
for (const x of [-0.29, 0.29]) {
for (const z of [-0.29, 0.29]) {
box(group, 0.07, 0.36, 0.07, x, 0.27, z, foundationMaterial);
}
}
asset.statusMaterial = waterMat;
asset.group = group;
return group;
}
function rebuildBuildings() {
buildingGroup.clear();
for (const asset of state.assets.values()) {
let group;
if (asset.type === "home") group = createHouse(asset);
else if (asset.type === "farm") group = createFarm(asset);
else group = createCistern(asset);
buildingGroup.add(group);
}
}
function rebuildNetwork() {
networkGroup.clear();
for (const key of state.pipes) {
const [x, z] = key.split(",").map(Number);
const group = new THREE.Group();
group.userData.cell = key;
group.position.set(worldX(x), 0.2, worldZ(z));
box(group, 0.23, 0.11, 0.23, 0, 0.02, 0, pipeCoreMaterial, false);
for (const n of neighbors(x, z)) {
const nKey = keyOf(n.x, n.z);
const connects = state.pipes.has(nKey) || (n.x === SOURCE.x && n.z === SOURCE.z);
if (!connects) continue;
if (n.x !== x) {
box(
group, 1.02, 0.1, 0.13,
(n.x - x) * 0.5, 0.02, 0, pipeMaterial, false
);
} else {
box(
group, 0.13, 0.1, 1.02,
0, 0.02, (n.z - z) * 0.5, pipeMaterial, false
);
}
}
networkGroup.add(group);
}
// River intake pump.
const pump = new THREE.Group();
pump.position.set(worldX(SOURCE.x), 0.15, worldZ(SOURCE.z));
pump.userData.cell = keyOf(SOURCE.x, SOURCE.z);
box(pump, 0.78, 0.12, 0.78, 0, 0.06, 0, foundationMaterial);
box(pump, 0.42, 0.48, 0.42, 0, 0.36, 0, material(0x66838a, 0.55, 0.2));
box(pump, 0.58, 0.12, 0.58, 0, 0.65, 0, pipeCoreMaterial, false);
box(pump, 0.13, 0.36, 0.13, 0, 0.76, 0, pipeMaterial, false);
const wheel = new THREE.Mesh(
new THREE.TorusGeometry(0.16, 0.035, 4, 8),
material(0xe3bd69, 0.45, 0.2)
);
wheel.rotation.x = Math.PI / 2;
wheel.position.set(0, 0.42, 0.25);
pump.add(wheel);
networkGroup.add(pump);
}
function connectedNetwork() {
const connected = new Set([keyOf(SOURCE.x, SOURCE.z)]);
const queue = [{ ...SOURCE }];
while (queue.length) {
const current = queue.shift();
for (const n of neighbors(current.x, current.z)) {
const key = keyOf(n.x, n.z);
if (state.pipes.has(key) && !connected.has(key)) {
connected.add(key);
queue.push(n);
}
}
}
return connected;
}
function assetIsConnected(asset, connected) {
return neighbors(asset.x, asset.z).some(n => connected.has(keyOf(n.x, n.z)));
}
function computeStats(applyStorage = false) {
const connected = connectedNetwork();
const stats = [];
const homeCap = [0, 0, 0];
const farmCount = [0, 0, 0];
for (const asset of state.assets.values()) {
if (asset.type === "home") homeCap[asset.district] += 12;
if (asset.type === "farm") farmCount[asset.district] += 1;
}
const totalHomeCap = homeCap.reduce((a, b) => a + b, 0);
for (let d = 0; d < 3; d++) {
stats.push({
name: DISTRICT_NAMES[d],
homeCap: homeCap[d],
farmCount: farmCount[d],
residents: totalHomeCap ? state.population * homeCap[d] / totalHomeCap : 0,
demand: 0,
serviceableDemand: 0,
served: 0,
unmet: 0,
delivery: 0,
storage: 0,
storageAfter: 0,
maxStorage: 35,
pipeCap: PIPE_CAPS[d],
connectedPipes: 0,
totalPipes: 0,
connected: false,
connectedCisterns: 0
});
}
for (const key of state.pipes) {
const [, z] = key.split(",").map(Number);
const d = districtOf(z);
stats[d].totalPipes++;
if (connected.has(key)) stats[d].connectedPipes++;
}
for (const asset of state.assets.values()) {
const d = asset.district;
const served = assetIsConnected(asset, connected);
if (asset.type === "cistern" && served) {
stats[d].connectedCisterns++;
}
}
for (const asset of state.assets.values()) {
const d = asset.district;
const served = assetIsConnected(asset, connected);
if (asset.type === "home") {
const residentShare = stats[d].homeCap
? stats[d].residents * 12 / stats[d].homeCap
: 0;
const demand = residentShare * 3;
stats[d].demand += demand;
if (served) stats[d].serviceableDemand += demand;
}
if (asset.type === "farm") {
stats[d].demand += 9;
if (served) stats[d].serviceableDemand += 9;
}
}
for (const d of stats) {
d.connected = d.connectedPipes > 0;
d.maxStorage = 35 + d.connectedCisterns * 45;
const conservationFactor = state.conservation ? 0.82 : 1;
d.demand *= conservationFactor;
d.serviceableDemand *= conservationFactor;
}
let remaining = intakeOf(state.month);
const plans = stats.map(d => {
const need = Math.max(0, d.serviceableDemand - d.storage);
const planned = Math.min(need, d.connected ? d.pipeCap : 0);
return { need, planned };
});
const plannedTotal = plans.reduce((sum, p) => sum + p.planned, 0);
const scale = plannedTotal > remaining && plannedTotal > 0
? remaining / plannedTotal
: 1;
stats.forEach((d, index) => {
const delivery = plans[index].planned * scale;
const maxStorage = Math.max(35, d.maxStorage);
const oldStorage = Math.min(d.storage, maxStorage);
const available = d.connected
? Math.min(maxStorage, oldStorage + delivery)
: 0;
d.delivery = delivery;
d.served = Math.min(d.serviceableDemand, available);
d.storageAfter = d.connected ? available - d.served : oldStorage;
d.unmet = d.demand - d.serviceableDemand + (d.serviceableDemand - d.served);
if (applyStorage) {
state.storage[d] = d.storageAfter;
}
});
const demand = stats.reduce((sum, d) => sum + d.demand, 0);
const unmet = stats.reduce((sum, d) => sum + d.unmet, 0);
const served = stats.reduce((sum, d) => sum + d.served, 0);
return {
districts: stats,
connected,
intake: intakeOf(state.month),
demand,
unmet,
served,
stress: demand ? unmet / demand : 0
};
}
function refreshAssetStatuses(stats) {
for (const asset of state.assets.values()) {
if (!asset.statusMaterial) continue;
const district = stats.districts[asset.district];
const served = assetIsConnected(asset, stats.connected);
const stress = district.demand ? district.unmet / district.demand : 0;
if (asset.type === "cistern") {
asset.statusMaterial.color.setHex(served ? 0x57cbd2 : 0x526d71);
} else if (!served) {
asset.statusMaterial.color.setHex(0xd9635d);
} else if (stress > 0.12) {
asset.statusMaterial.color.setHex(0xeaa75f);
} else {
asset.statusMaterial.color.setHex(0x9bdca1);
}
}
}
// ---------- District labels ----------
const districtLabels = [];
for (let d = 0; d < 3; d++) {
const el = document.createElement("div");
el.className = "district-label";
labelsLayer.appendChild(el);
districtLabels.push({
element: el,
position: new THREE.Vector3(
worldX(3),
2.4,
worldZ(d === 0 ? 2 : d === 1 ? 10 : 20)
)
});
}
function updateDistrictLabels(stats) {
stats.districts.forEach((d, index) => {
const percent = d.demand ? Math.round(d.served / d.demand * 100) : 100;
districtLabels[index].element.innerHTML =
`<strong>${d.name}</strong><span>${percent}% supplied · ${Math.round(d.storageAfter)}/${d.maxStorage} stored</span>`;
});
}
// ---------- Interface ----------
function showToast(message, bad = false) {
clearTimeout(toastTimer);
toast.textContent = message;
toast.classList.toggle("bad", bad);
toast.classList.add("show");
toastTimer = setTimeout(() => toast.classList.remove("show"), 2600);
}
function addLog(message, type = "") {
const feed = document.getElementById("eventFeed");
const item = document.createElement("div");
item.className = `event-item ${type}`;
item.textContent = message;
feed.prepend(item);
while (feed.children.length > 4) feed.lastElementChild.remove();
}
function renderStats(stats) {
const housing = [...state.assets.values()]
.filter(a => a.type === "home")
.reduce((sum, a) => sum + 12, 0);
const farms = [...state.assets.values()].filter(a => a.type === "farm").length;
const jobs = farms * 6;
document.getElementById("populationStat").textContent = state.population;
document.getElementById("populationDetail").textContent =
`${state.population} / ${housing} housed`;
document.getElementById("treasuryStat").textContent = Math.round(state.treasury);
document.getElementById("jobsStat").textContent = jobs;
document.getElementById("farmsDetail").textContent = `${farms} working farms`;
const stressPercent = Math.round(stats.stress * 100);
const stressEl = document.getElementById("stressStat");
stressEl.textContent = `${stressPercent}%`;
stressEl.className = `stat-value ${stressPercent > 12 ? "" : stressPercent > 3 ? "gold" : "green"}`;
if (stressPercent > 12) stressEl.style.color = "var(--red)";
document.getElementById("intakeDetail").textContent =
`${stats.intake} unit intake · ${Math.round(stats.served)} served`;
document.getElementById("dateLabel").textContent =
`Month ${String(state.month).padStart(2, "0")} · ${seasonOf(state.month)}`;
const forecast = seasonOf(state.month) === "Summer"
? "low river forecast"
: seasonOf(state.month) === "Winter"
? "cold-water intake forecast"
: "seasonal intake forecast";
document.getElementById("dateSub").textContent =
`${forecast} · year ${Math.floor((state.month - 1) / 12) + 1}`;
const districtList = document.getElementById("districtList");
districtList.innerHTML = stats.districts.map(d => {
const ratio = d.demand ? d.served / d.demand : 1;
const percent = Math.max(0, Math.min(100, ratio * 100));
const stateClass = d.unmet > d.demand * 0.12 ? "bad" : d.unmet > 0 ? "warn" : "";
return `
<div class="district">
<div class="district-head">
<span class="district-name">${d.name}</span>
<span class="district-value">${Math.round(d.served)} / ${Math.round(d.demand)} u</span>
</div>
<div class="meter ${stateClass}">
<span style="width:${percent}%"></span>
</div>
<div class="district-meta">
<span>Flow ${d.pipeCap} · ${d.connectedPipes}/${d.totalPipes} live mains</span>
<span>${Math.round(d.storageAfter)}/${d.maxStorage} stored</span>
</div>
</div>
`;
}).join("");
updateDistrictLabels(stats);
}
function renderInspector() {
const title = document.getElementById("inspectorTitle");
const copy = document.getElementById("inspectorCopy");
const tags = document.getElementById("inspectorTags");
const coords = document.getElementById("inspectorCoords");
tags.innerHTML = "";
coords.textContent = "No selection";
if (!selected) {
title.textContent = "Choose a lot";
copy.textContent = "Click a building or water main to see capacity, service, and local district information.";
return;
}
const { x, z } = selected;
const key = keyOf(x, z);
coords.textContent = `Lot ${x + 1} · ${z + 1}`;
const asset = state.assets.get(key);
const isPipe = state.pipes.has(key);
const stats = computeStats();
if (asset) {
const district = stats.districts[asset.district];
const served = assetIsConnected(asset, stats.connected);
const stress = district.demand ? district.unmet / district.demand : 0;
title.textContent = asset.type === "home"
? "Voxel residence"
: asset.type === "farm"
? "Working farm"
: "District cistern";
if (asset.type === "home") {
copy.textContent =
`Provides 12 resident places. It currently represents a proportional share of ${state.population} residents and requires 3 water units per resident.`;
} else if (asset.type === "farm") {
copy.textContent =
"Provides 6 local jobs and consumes 9 water units each month. Removing it reduces employment as well as food production.";
} else {
copy.textContent =
`Stores up to 45 additional units for ${district.name}. A cistern only contributes capacity when connected to a live main.`;
}
tags.innerHTML = `
<span class="tag">${district.name}</span>
<span class="tag ${served ? "good" : "bad"}">${served ? "Water connected" : "No live connection"}</span>
${asset.type !== "cistern" ? `<span class="tag ${stress > 0.12 ? "bad" : "good"}">${Math.round(stress * 100)}% district stress</span>` : ""}
`;
return;
}
if (isPipe) {
const d = districtOf(z);
const district = stats.districts[d];
const live = stats.connected.has(key);
title.textContent = live ? "Live water main" : "Disconnected main";
copy.textContent =
`This main belongs to ${district.name}. The district can receive up to ${district.pipeCap} units through its mains each month. Disconnected segments do not carry water.`;
tags.innerHTML = `
<span class="tag">${district.name}</span>
<span class="tag ${live ? "good" : "bad"}">${live ? "Connected to intake" : "No intake path"}</span>
<span class="tag">18 cr replacement</span>
`;
return;
}
const d = districtOf(z);
title.textContent = isRoad(x, z) ? "Public street" : "Undeveloped lot";
copy.textContent = isRoad(x, z)
? "Streets can carry a water main. Houses, farms, and cisterns must be placed on an adjacent non-street lot."
: `This lot belongs to ${DISTRICT_NAMES[d]}. Build a residence, farm, or cistern here after connecting it to a live main.`;
tags.innerHTML = `<span class="tag">${DISTRICT_NAMES[d]}</span><span class="tag">Buildable lot</span>`;
}
function renderAll(stats = computeStats()) {
renderStats(stats);
renderInspector();
refreshAssetStatuses(stats);
}
function setTool(tool) {
currentTool = tool;
document.querySelectorAll(".tool").forEach(button => {
button.classList.toggle("selected", button.dataset.tool === tool);
});
const hints = {
inspect: "Inspect any building, lot, cistern, or main to read its live status.",
home: "Place a 12-person residence on a clear lot touching a live water main.",
farm: "Place a farm on a clear lot touching a live main. Farms provide 6 jobs.",
cistern: "Place a cistern beside a live main to add 45 units of local storage.",
pipe: "Extend the distribution network by one tile from an existing main.",
bulldoze: "Remove a building or main. Demolition returns 35% of its construction cost."
};
document.getElementById("toolHint").textContent = hints[tool];
}
document.querySelectorAll(".tool").forEach(button => {
button.addEventListener("click", () => setTool(button.dataset.tool));
});
document.getElementById("tariff").addEventListener("input", event => {
state.tariff = Number(event.target.value);
document.getElementById("tariffValue").textContent = `${state.tariff.toFixed(2)} cr`;
});
document.getElementById("conservation").addEventListener("change", event => {
state.conservation = event.target.checked;
renderAll();
});
document.getElementById("grant").addEventListener("change", event => {
state.grant = event.target.checked;
});
// ---------- Construction rules ----------
function isBuildLot(x, z) {
return (
inBounds(x, z) &&
!isRiver(x, z) &&
!isRoad(x, z) &&
x >= 1 && x <= 22 &&
!state.assets.has(keyOf(x, z)) &&
!decor.has(keyOf(x, z))
);
}
function validity(x, z) {
const key = keyOf(x, z);
if (!inBounds(x, z)) {
return { ok: false, reason: "That tile is outside the district board." };
}
if (isRiver(x, z)) {
return { ok: false, reason: "The river intake is fixed; river tiles cannot be built on." };
}
if (currentTool === "inspect") return { ok: true };
if (currentTool === "bulldoze") {
if (state.assets.has(key) || state.pipes.has(key)) return { ok: true };
return { ok: false, reason: "There is nothing here to demolish." };
}
if (currentTool === "pipe") {
if (state.assets.has(key) || decor.has(key)) {
return { ok: false, reason: "This tile is already occupied." };
}
if (key === keyOf(SOURCE.x, SOURCE.z)) {
return { ok: false, reason: "The river intake cannot be replaced." };
}
const touchesMain = neighbors(x, z).some(n =>
state.pipes.has(keyOf(n.x, n.z)) ||
(n.x === SOURCE.x && n.z === SOURCE.z)
);
if (!touchesMain) {
return { ok: false, reason: "A water main must extend from an existing main." };
}
if (state.treasury < COSTS.pipe) {
return { ok: false, reason: "Not enough crowns for an 18-crown main." };
}
return { ok: true };
}
if (!isBuildLot(x, z)) {
if (isRoad(x, z)) {
return { ok: false, reason: "Keep streets clear; place the building on an adjacent lot." };
}
return { ok: false, reason: "This tile is occupied or protected." };
}
const connected = connectedNetwork();
const touchesLiveMain = neighbors(x, z).some(n => connected.has(keyOf(n.x, n.z)));
if (!touchesLiveMain) {
return { ok: false, reason: "The lot must touch a live water main." };
}
if (state.treasury < COSTS[currentTool]) {
return { ok: false, reason: `Not enough crowns. This costs ${COSTS[currentTool]} crowns.` };
}
return { ok: true };
}
function performAction(x, z) {
const check = validity(x, z);
const key = keyOf(x, z);
if (!check.ok) {
if (currentTool !== "inspect") showToast(check.reason, true);
return;
}
if (currentTool === "inspect") {
selected = { x, z };
renderInspector();
return;
}
if (currentTool === "bulldoze") {
if (state.assets.has(key)) {
const asset = state.assets.get(key);
const refund = Math.round(COSTS[asset.type] * 0.35);
state.treasury += refund;
if (asset.group) buildingGroup.remove(asset.group);
state.assets.delete(key);
selected = null;
showToast(`${asset.type} demolished. ${refund} crowns recovered.`);
addLog(`${asset.type} removed; ${refund} crowns recovered.`, "warn");
} else if (state.pipes.has(key)) {
const refund = Math.round(COSTS.pipe * 0.35);
state.treasury += refund;
state.pipes.delete(key);
selected = null;
showToast(`Water main removed. ${refund} crowns recovered.`);
addLog("A water main was demolished.", "warn");
}
rebuildNetwork();
renderAll();
return;
}
if (currentTool === "pipe") {
state.treasury -= COSTS.pipe;
state.pipes.add(key);
selected = { x, z };
rebuildNetwork();
showToast("Water main extended.");
addLog("A new main was connected to the distribution network.", "good");
} else {
state.treasury -= COSTS[currentTool];
const asset = {
type: currentTool,
x,
z,
district: districtOf(z),
statusMaterial: null,
group: null
};
state.assets.set(key, asset);
selected = { x, z };
if (currentTool === "home") {
showToast("Residence built: 12 resident places added.");
addLog("A 12-person residence was completed.", "good");
} else if (currentTool === "farm") {
showToast("Farm built: 6 jobs and 9 units of monthly demand.");
addLog("A working farm was added to the district.", "good");
} else {
showToast("Cistern built: +45 units of local storage.");
addLog("Cistern storage was expanded.", "good");
}
}
renderAll();
}
// ---------- Monthly simulation ----------
function advanceMonth() {
state.month += 1;
const stats = computeStats(true);
const housing = [...state.assets.values()]
.filter(a => a.type === "home")
.reduce((sum, a) => sum + 12, 0);
const farms = [...state.assets.values()].filter(a => a.type === "farm").length;
const income = Math.round(state.population * state.tariff * 0.7);
const upkeep = 22 + state.pipes.size * 0.12 + farms * 3 +
[...state.assets.values()].filter(a => a.type === "cistern").length * 2;
const grantCost = state.grant ? 45 : 0;
state.treasury += income - upkeep - grantCost;
if (state.population > housing) {
const displaced = Math.min(state.population - 1, state.population - housing + 1);
state.population -= displaced;
addLog(`${displaced} residents left because housing capacity fell short.`, "bad");
}
if (stats.stress > 0.04) {
const departures = Math.max(1, Math.ceil(stats.stress * 10));
state.population = Math.max(1, state.population - departures);
addLog(
`${departures} residents left after water demand exceeded supply.`,
"bad"
);
showToast("Water limits exposed: residents are leaving the town.", true);
} else {
const freeHousing = housing - state.population;
let growth = state.tariff <= 0.85 ? 3 : state.tariff <= 1.2 ? 2 : state.tariff <= 1.6 ? 1 : 0;
if (state.grant) growth += 2;
if (freeHousing > 0 && growth > 0) {
const arrivals = Math.min(freeHousing, growth);
state.population += arrivals;
addLog(`${arrivals} residents arrived; water and housing remained available.`, "good");
} else if (freeHousing > 0 && growth === 0) {
addLog("No arrivals: the current tariff is discouraging new residents.", "warn");
}
}
if (state.treasury < 0) {
addLog("Treasury is negative. Future construction is unaffordable.", "bad");
} else if (income - upkeep - grantCost >= 0) {
addLog(
`Monthly books closed at ${income - upkeep - grantCost >= 0 ? "+" : ""}${income - upkeep - grantCost} crowns.`,
"good"
);
}
renderAll();
}
document.getElementById("nextBtn").addEventListener("click", advanceMonth);
document.getElementById("autoBtn").addEventListener("click", event => {
const button = event.currentTarget;
if (autoTimer) {
clearInterval(autoTimer);
autoTimer = null;
button.classList.remove("active");
button.textContent = "Auto run";
} else {
autoTimer = setInterval(advanceMonth, 6000);
button.classList.add("active");
button.textContent = "Running";
}
});
document.getElementById("resetBtn").addEventListener("click", () => {
location.reload();
});
window.addEventListener("keydown", event => {
if (["INPUT", "TEXTAREA", "SELECT"].includes(document.activeElement.tagName)) return;
const shortcuts = {
"1": "inspect",
"2": "home",
"3": "farm",
"4": "cistern",
"5": "pipe",
"6": "bulldoze"
};
if (shortcuts[event.key]) setTool(shortcuts[event.key]);
if (event.key.toLowerCase() === "n") advanceMonth();
});
// ---------- Direct camera controls ----------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerDown = false;
let dragDistance = 0;
let lastPointerX = 0;
let lastPointerY = 0;
let activeButton = 0;
const hoverOutline = new THREE.Mesh(
new THREE.BoxGeometry(0.98, 0.045, 0.98),
new THREE.MeshBasicMaterial({
color: 0x65d9d0,
transparent: true,
opacity: 0.58,
depthWrite: false
})
);
hoverOutline.visible = false;
scene.add(hoverOutline);
const selectedOutline = new THREE.Mesh(
new THREE.BoxGeometry(1.02, 0.055, 1.02),
new THREE.MeshBasicMaterial({
color: 0xefc66f,
transparent: true,
opacity: 0.8,
depthWrite: false
})
);
selectedOutline.visible = false;
scene.add(selectedOutline);
function pickCell(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(pickables, true);
for (const hit of hits) {
if (hit.object === terrainMesh && hit.instanceId !== undefined) {
const key = terrainCells[hit.instanceId];
const [x, z] = key.split(",").map(Number);
return { x, z, key };
}
if (hit.object === riverMesh && hit.instanceId !== undefined) {
const key = riverCells[hit.instanceId];
const [x, z] = key.split(",").map(Number);
return { x, z, key };
}
let object = hit.object;
while (object && !object.userData.cell) object = object.parent;
if (object?.userData.cell) {
const key = object.userData.cell;
const [x, z] = key.split(",").map(Number);
return { x, z, key };
}
}
return null;
}
function updateHover(clientX, clientY) {
const hit = pickCell(clientX, clientY);
if (!hit) {
hoverOutline.visible = false;
hoverTip.style.opacity = 0;
return;
}
hoverOutline.visible = true;
hoverOutline.position.set(worldX(hit.x), 0.19, worldZ(hit.z));
const check = validity(hit.x, hit.z);
const hasAsset = state.assets.has(hit.key);
const isPipe = state.pipes.has(hit.key);
const isTree = decor.has(hit.key);
let description;
if (isTree) description = "Protected grove";
else if (hasAsset) description = state.assets.get(hit.key).type;
else if (isPipe) description = "Water main";
else if (isRiver(hit.x, hit.z)) description = "River";
else if (isRoad(hit.x, hit.z)) description = "Street";
else description = "Undeveloped lot";
hoverTip.textContent = `${description} · ${hit.x + 1},${hit.z + 1} · ${
currentTool === "inspect" || check.ok ? "ready" : check.reason
}`;
hoverTip.style.left = `${clientX + 13}px`;
hoverTip.style.top = `${clientY + 13}px`;
hoverTip.style.opacity = 1;
hoverOutline.material.color.setHex(check.ok ? 0x65d9d0 : 0xf47f73);
hoverOutline.material.opacity = currentTool === "inspect" ? 0.4 : 0.68;
}
renderer.domElement.addEventListener("pointerdown", event => {
pointerDown = true;
dragDistance = 0;
activeButton = event.button;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
});
renderer.domElement.addEventListener("pointermove", event => {
if (!pointerDown) {
updateHover(event.clientX, event.clientY);
return;
}
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
dragDistance += Math.abs(dx) + Math.abs(dy);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (activeButton === 2 || event.shiftKey) {
const scale = 0.055 / cameraZoom;
const right = new THREE.Vector3(Math.cos(cameraTheta), 0, -Math.sin(cameraTheta));
const forward = new THREE.Vector3(Math.sin(cameraTheta), 0, Math.cos(cameraTheta));
cameraTarget.addScaledVector(right, -dx * scale);
cameraTarget.addScaledVector(forward, -dy * scale);
} else {
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(cameraPhi + dy * 0.005, 0.38, 1.25);
}
updateCamera();
hoverTip.style.opacity = 0;
});
renderer.domElement.addEventListener("pointerup", event => {
pointerDown = false;
renderer.domElement.classList.remove("dragging");
if (activeButton === 0 && dragDistance < 7) {
const hit = pickCell(event.clientX, event.clientY);
if (hit) performAction(hit.x, hit.z);
}
updateHover(event.clientX, event.clientY);
});
renderer.domElement.addEventListener("pointerleave", () => {
pointerDown = false;
hoverOutline.visible = false;
hoverTip.style.opacity = 0;
renderer.domElement.classList.remove("dragging");
});
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraZoom = THREE.MathUtils.clamp(cameraZoom * Math.exp(-event.deltaY * 0.001), 0.65, 2.35);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
renderer.domElement.addEventListener("dblclick", () => {
cameraTarget.set(0, 0, 0);
cameraTheta = 0.72;
cameraPhi = 0.69;
cameraZoom = 1;
updateCamera();
});
// ---------- Boot and animation ----------
state = makeInitialState();
buildTerrain();
buildDecor();
rebuildBuildings();
rebuildNetwork();
updateCamera();
resize();
addLog("River intake online; the first municipal board is in session.", "good");
addLog("Three districts are connected to the initial water mains.");
addLog("All civic rates and capacities are fictional and shown in full.");
renderAll();
const projected = new THREE.Vector3();
function animate(time) {
requestAnimationFrame(animate);
const t = time * 0.001;
for (const glint of waterGlints) {
const z = (glint.z + t * glint.speed * 2.2) % ROWS;
glint.mesh.position.set(
worldX(riverX(Math.floor(z))),
0.15 + Math.sin(t * 2 + glint.phase) * 0.015,
worldZ(z)
);
glint.mesh.material.opacity = 0.26 + Math.sin(t * 2.5 + glint.phase) * 0.12;
}
hoverOutline.material.opacity =
currentTool === "inspect" ? 0.42 : 0.58 + Math.sin(t * 4) * 0.12;
if (selected) {
selectedOutline.visible = true;
selectedOutline.position.set(worldX(selected.x), 0.21, worldZ(selected.z));
selectedOutline.material.opacity = 0.55 + Math.sin(t * 3) * 0.18;
} else {
selectedOutline.visible = false;
}
for (const label of districtLabels) {
projected.copy(label.position).project(camera);
const visible = projected.z > -1 && projected.z < 1;
label.element.style.display = visible ? "block" : "none";
label.element.style.transform =
`translate(-50%, -50%) translate(${(projected.x * 0.5 + 0.5) * viewport.clientWidth}px, ${(-projected.y * 0.5 + 0.5) * viewport.clientHeight}px)`;
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
setTimeout(() => {
document.getElementById("loading").classList.add("hidden");
}, 350);
</script>
</body>
</html>
```