Prompt specification
Build or customize the Three.js 3D scene "Growth Without Infrastructure Expansion" 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: Growth Without Infrastructure Expansion
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/growth-without-infrastructure-expansion-x3560
Scene Description Prompt:
Create a town-planning simulation comparing matched population growth with fixed or expanded capacity. Show the resulting shortages under stated assumptions rather than making real demographic predictions. Use Three.js from cdnjs in a single HTML file, with low-poly forms.
Working Three.js Starter (growth-without-infrastructure-expansion-x3560):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Capacity Common — Town Planning Simulation</title>
<style>
:root {
--ink: #18352e;
--muted: #687a74;
--paper: #f7f9f4;
--panel: #ffffff;
--line: #dce4de;
--teal: #167d6b;
--teal-soft: #dff1e9;
--coral: #df684f;
--coral-soft: #fbe7e1;
--amber: #d89935;
--navy: #17352f;
--shadow: 0 14px 34px rgba(26, 52, 44, 0.08);
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: #e9eee9;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.app {
display: grid;
grid-template-rows: 72px minmax(0, 1fr);
height: 100vh;
min-height: 680px;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 0 22px;
background: rgba(255, 255, 255, 0.95);
border-bottom: 1px solid var(--line);
z-index: 5;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
display: grid;
grid-template-columns: repeat(2, 7px);
grid-template-rows: repeat(2, 7px);
gap: 3px;
padding: 8px;
border-radius: 9px;
background: var(--navy);
transform: rotate(-4deg);
}
.brand-mark i {
display: block;
background: #a8d8c6;
border-radius: 2px;
}
.brand-mark i:nth-child(2),
.brand-mark i:nth-child(3) {
background: #f19a7f;
}
.brand-copy {
min-width: 0;
}
.brand h1 {
margin: 0;
font-size: 17px;
letter-spacing: -0.02em;
line-height: 1.1;
}
.brand p {
margin: 4px 0 0;
color: var(--muted);
font-size: 12px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.header-meta {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 10px;
flex-wrap: wrap;
}
.scenario-badge {
display: inline-flex;
align-items: center;
gap: 7px;
padding: 7px 10px;
border: 1px solid #dfd6ad;
border-radius: 999px;
color: #6c5926;
background: #fff8dc;
font-size: 11px;
font-weight: 750;
letter-spacing: 0.02em;
}
.scenario-badge::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--amber);
}
.population-chip {
min-width: 160px;
padding: 9px 12px;
border: 1px solid var(--line);
border-radius: 11px;
background: #f4f7f3;
color: var(--muted);
font-size: 11px;
text-align: right;
}
.population-chip strong {
display: block;
margin-top: 2px;
color: var(--ink);
font-size: 15px;
}
.workspace {
display: grid;
grid-template-columns: 272px minmax(460px, 1fr) 330px;
gap: 12px;
min-height: 0;
padding: 12px;
}
.panel {
min-width: 0;
min-height: 0;
overflow: auto;
padding: 18px;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 18px;
box-shadow: var(--shadow);
scrollbar-width: thin;
scrollbar-color: #bdc9c2 transparent;
}
.panel h2 {
margin: 0;
font-size: 17px;
letter-spacing: -0.025em;
}
.panel-intro {
margin: 7px 0 19px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.control-block {
padding: 15px 0;
border-top: 1px solid var(--line);
}
.control-heading {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin-bottom: 9px;
}
.control-heading label,
.control-heading span:first-child {
font-size: 12px;
font-weight: 750;
}
.control-heading output {
color: var(--teal);
font-size: 12px;
font-weight: 800;
white-space: nowrap;
}
.hint {
margin: 7px 0 0;
color: var(--muted);
font-size: 10.5px;
line-height: 1.45;
}
input[type="range"] {
width: 100%;
height: 18px;
margin: 0;
accent-color: var(--teal);
cursor: pointer;
}
.number-field {
display: flex;
align-items: center;
gap: 8px;
margin-top: 9px;
}
.number-field input {
width: 100%;
padding: 9px 10px;
color: var(--ink);
background: #f7f9f6;
border: 1px solid var(--line);
border-radius: 9px;
outline: none;
}
.number-field input:focus {
border-color: var(--teal);
box-shadow: 0 0 0 3px rgba(22, 125, 107, 0.1);
}
.number-field span {
color: var(--muted);
font-size: 11px;
white-space: nowrap;
}
.plan-card {
display: grid;
grid-template-columns: 32px 1fr;
gap: 10px;
padding: 11px 0;
border-bottom: 1px solid var(--line);
}
.plan-card:last-child {
border-bottom: 0;
}
.plan-icon {
display: grid;
place-items: center;
width: 32px;
height: 32px;
border-radius: 9px;
font-size: 13px;
font-weight: 850;
}
.plan-card.fixed .plan-icon {
color: #9a4938;
background: var(--coral-soft);
}
.plan-card.expanded .plan-icon {
color: #126451;
background: var(--teal-soft);
}
.plan-card strong {
display: block;
font-size: 12px;
}
.plan-card p {
margin: 3px 0 0;
color: var(--muted);
font-size: 10.5px;
line-height: 1.45;
}
.segmented {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 4px;
padding: 4px;
background: #edf2ed;
border-radius: 10px;
}
.segmented button {
padding: 8px 4px;
border: 0;
border-radius: 7px;
background: transparent;
color: var(--muted);
font-size: 10.5px;
font-weight: 750;
cursor: pointer;
}
.segmented button.active {
color: var(--ink);
background: #fff;
box-shadow: 0 2px 8px rgba(29, 56, 48, 0.09);
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
border: 1px solid #d1dcd5;
border-radius: 18px;
background: #dce8e1;
box-shadow: var(--shadow);
}
#sceneContainer {
position: absolute;
inset: 0;
}
#sceneContainer canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.stage-top {
position: absolute;
top: 16px;
left: 16px;
right: 16px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
pointer-events: none;
z-index: 2;
}
.stage-title-card {
padding: 12px 14px;
border: 1px solid rgba(255, 255, 255, 0.7);
border-radius: 13px;
background: rgba(250, 252, 248, 0.88);
backdrop-filter: blur(10px);
box-shadow: 0 8px 24px rgba(24, 53, 46, 0.08);
}
.eyebrow {
display: block;
margin-bottom: 4px;
color: var(--teal);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.stage-title-card h2 {
margin: 0;
font-size: 15px;
letter-spacing: -0.025em;
}
.stage-title-card p {
margin: 4px 0 0;
color: var(--muted);
font-size: 10px;
}
.stage-population {
padding: 10px 12px;
border-radius: 12px;
color: white;
background: rgba(23, 53, 47, 0.9);
box-shadow: 0 8px 24px rgba(24, 53, 46, 0.12);
white-space: nowrap;
text-align: right;
}
.stage-population span {
display: block;
color: #bcd3ca;
font-size: 9px;
text-transform: uppercase;
letter-spacing: 0.09em;
}
.stage-population strong {
display: block;
margin-top: 2px;
font-size: 16px;
}
.legend {
position: absolute;
top: 98px;
left: 16px;
display: flex;
flex-wrap: wrap;
gap: 7px;
z-index: 2;
pointer-events: none;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border-radius: 999px;
color: #3e544d;
background: rgba(250, 252, 248, 0.84);
backdrop-filter: blur(8px);
font-size: 9.5px;
font-weight: 700;
}
.legend i {
width: 8px;
height: 8px;
border-radius: 2px;
}
.timeline-card {
position: absolute;
left: 16px;
right: 16px;
bottom: 16px;
display: grid;
grid-template-columns: auto minmax(120px, 1fr) auto;
align-items: center;
gap: 14px;
padding: 12px 14px;
border: 1px solid rgba(255, 255, 255, 0.74);
border-radius: 14px;
background: rgba(250, 252, 248, 0.92);
backdrop-filter: blur(12px);
box-shadow: 0 10px 28px rgba(24, 53, 46, 0.12);
z-index: 3;
}
.play-button {
display: grid;
place-items: center;
width: 38px;
height: 38px;
padding: 0;
border: 0;
border-radius: 11px;
color: white;
background: var(--teal);
box-shadow: 0 5px 14px rgba(22, 125, 107, 0.22);
cursor: pointer;
}
.play-button:hover {
background: #126e5e;
}
.timeline-track {
min-width: 0;
}
.timeline-labels {
display: flex;
justify-content: space-between;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
}
.year-readout {
min-width: 68px;
color: var(--ink);
font-size: 11px;
font-weight: 800;
text-align: right;
}
.year-readout strong {
display: block;
font-size: 16px;
}
.camera-help {
position: absolute;
right: 17px;
bottom: 85px;
padding: 6px 8px;
border-radius: 8px;
color: rgba(31, 58, 50, 0.72);
background: rgba(248, 251, 247, 0.72);
font-size: 9px;
pointer-events: none;
}
.outcome-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.year-pill {
padding: 5px 8px;
border-radius: 999px;
color: var(--teal);
background: var(--teal-soft);
font-size: 10px;
font-weight: 800;
}
#shortageGrid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.service-card {
min-width: 0;
padding: 12px;
border: 1px solid var(--line);
border-radius: 13px;
background: #fbfcf9;
}
.service-card.wide {
grid-column: 1 / -1;
}
.service-title {
display: flex;
align-items: center;
gap: 7px;
margin-bottom: 9px;
}
.service-dot {
width: 8px;
height: 8px;
border-radius: 3px;
background: var(--teal);
}
.service-title strong {
font-size: 11.5px;
}
.service-title small {
margin-left: auto;
color: var(--muted);
font-size: 8.5px;
}
.metric-line {
display: grid;
grid-template-columns: 45px minmax(30px, 1fr) auto;
align-items: center;
gap: 6px;
min-height: 23px;
font-size: 9px;
}
.metric-line > span {
color: var(--muted);
}
.metric-line > strong {
min-width: 58px;
font-size: 9px;
text-align: right;
}
.metric-line .ok {
color: var(--teal);
}
.metric-line .bad {
color: #b94f3b;
}
.metric-line .near {
color: #96691f;
}
.mini-track {
height: 6px;
overflow: hidden;
border-radius: 999px;
background: #e7ece7;
}
.mini-track i {
display: block;
height: 100%;
min-width: 2px;
border-radius: inherit;
}
.demand-note {
margin-top: 8px;
padding-top: 7px;
border-top: 1px solid #e5eae5;
color: var(--muted);
font-size: 8.5px;
}
.chart-card {
margin-top: 14px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 14px;
background: #fbfcf9;
}
.chart-card h3 {
margin: 0;
font-size: 12px;
}
.chart-card > p {
margin: 4px 0 9px;
color: var(--muted);
font-size: 9.5px;
}
#housingChart svg {
display: block;
width: 100%;
height: auto;
overflow: visible;
}
.chart-legend {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 7px;
color: var(--muted);
font-size: 8.5px;
}
.chart-legend span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.chart-legend i {
width: 14px;
height: 2px;
background: var(--coral);
}
.chart-legend .fixed {
background: #82908a;
}
.chart-legend .expanded {
background: var(--teal);
}
details {
margin-top: 14px;
border-top: 1px solid var(--line);
padding-top: 13px;
}
summary {
color: var(--ink);
font-size: 11px;
font-weight: 800;
cursor: pointer;
}
.assumptions {
margin: 10px 0 0;
padding-left: 17px;
color: var(--muted);
font-size: 9.5px;
line-height: 1.55;
}
.assumptions li {
margin-bottom: 6px;
}
.assumptions strong {
color: var(--ink);
}
.disclaimer {
margin-top: 13px;
padding: 10px;
border-radius: 10px;
color: #765a25;
background: #fff7dc;
font-size: 9px;
line-height: 1.45;
}
@media (max-width: 1080px) {
body {
overflow: auto;
}
.app {
height: auto;
min-height: 100vh;
}
.workspace {
grid-template-columns: 245px minmax(440px, 1fr);
}
.stage {
min-height: 630px;
}
.outcome-panel {
grid-column: 1 / -1;
}
#shortageGrid {
grid-template-columns: repeat(4, 1fr);
}
.service-card.wide {
grid-column: auto;
}
}
@media (max-width: 740px) {
.app {
grid-template-rows: auto auto;
}
.topbar {
align-items: flex-start;
padding: 14px;
}
.header-meta {
max-width: 170px;
}
.population-chip {
min-width: 140px;
}
.workspace {
display: block;
padding: 8px;
}
.panel,
.stage {
margin-bottom: 8px;
}
.stage {
height: 610px;
}
#shortageGrid {
grid-template-columns: 1fr 1fr;
}
.stage-top {
right: 10px;
left: 10px;
}
.stage-population {
display: none;
}
.legend {
top: 102px;
left: 10px;
}
.camera-help {
display: none;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i><i></i>
</div>
<div class="brand-copy">
<h1>Capacity Common</h1>
<p>A town-planning capacity simulator</p>
</div>
</div>
<div class="header-meta">
<span class="scenario-badge">Illustrative scenario · not a forecast</span>
<div class="population-chip">
Matched population
<strong id="headerPopulation">14,939</strong>
</div>
</div>
</header>
<main class="workspace">
<aside class="panel control-panel">
<h2>Planning controls</h2>
<p class="panel-intro">
Change the demand path or capacity program. Shortages update from the
stated planning assumptions.
</p>
<section class="control-block">
<div class="control-heading">
<label for="growthRate">Matched population growth</label>
<output id="growthOutput" for="growthRate">1.5% / yr</output>
</div>
<input
id="growthRate"
type="range"
min="0"
max="3"
step="0.1"
value="1.5"
/>
<p class="hint">
A compound planning rate applied to the base population. It is a
stress-test input, not a demographic projection.
</p>
</section>
<section class="control-block">
<div class="control-heading">
<label for="basePopulation">Base population</label>
</div>
<div class="number-field">
<input
id="basePopulation"
type="number"
min="4000"
max="30000"
step="500"
value="12000"
/>
<span>residents at year 0</span>
</div>
</section>
<section class="control-block">
<div class="control-heading">
<span>Capacity paths</span>
</div>
<div class="plan-card fixed">
<div class="plan-icon">F</div>
<div>
<strong>Fixed capacity</strong>
<p>Housing, water, schools, and jobs remain at their year-0 levels.</p>
</div>
</div>
<div class="plan-card expanded">
<div class="plan-icon">E</div>
<div>
<strong>Expanded capacity</strong>
<p id="scheduleText">
Bundled infrastructure is delivered every three years, first in year 4.
</p>
</div>
</div>
</section>
<section class="control-block">
<div class="control-heading">
<label for="firstDelivery">First expanded delivery</label>
<output id="deliveryOutput" for="firstDelivery">Year 4</output>
</div>
<input
id="firstDelivery"
type="range"
min="3"
max="9"
step="1"
value="4"
/>
<p class="hint">
Delivery years are the selected year and every third year thereafter.
</p>
</section>
<section class="control-block">
<div class="control-heading">
<span>Camera view</span>
</div>
<div class="segmented" aria-label="Camera view">
<button type="button" class="active" data-view="compare">Compare</button>
<button type="button" data-view="fixed">Fixed</button>
<button type="button" data-view="expanded">Expanded</button>
</div>
</section>
</aside>
<section class="stage" aria-label="Interactive three-dimensional town comparison">
<div id="sceneContainer"></div>
<div class="stage-top">
<div class="stage-title-card">
<span class="eyebrow">Matched demand, alternative capacity</span>
<h2 id="stageTitle">Two capacity paths, one demand path</h2>
<p>Schematic low-poly geometry; not a parcel-level plan.</p>
</div>
<div class="stage-population">
<span>Year population</span>
<strong id="stagePopulation">14,939</strong>
</div>
</div>
<div class="legend" aria-hidden="true">
<span><i style="background:#4e9d83"></i>Within capacity</span>
<span><i style="background:#d89935"></i>Near capacity</span>
<span><i style="background:#df684f"></i>Shortage</span>
<span><i style="background:#243b35"></i>Road</span>
</div>
<div class="camera-help">
Drag to orbit · Shift-drag to pan · Wheel to zoom
</div>
<div class="timeline-card">
<button
id="playButton"
class="play-button"
type="button"
aria-label="Play simulation"
aria-pressed="false"
>
▶
</button>
<div class="timeline-track">
<div class="timeline-labels">
<span>Year 0</span>
<span>Planning horizon</span>
<span>Year 20</span>
</div>
<input
id="yearSlider"
type="range"
min="0"
max="20"
step="1"
value="12"
aria-label="Planning year"
/>
</div>
<div class="year-readout">
Selected year
<strong id="yearDisplay">12</strong>
</div>
</div>
</section>
<aside class="panel outcome-panel">
<div class="outcome-head">
<h2>Shortage readout</h2>
<span class="year-pill" id="readoutYear">Year 12</span>
</div>
<p class="panel-intro">
Positive gaps show demand above capacity under the selected assumptions.
</p>
<div id="shortageGrid"></div>
<section class="chart-card">
<h3>Housing demand vs. capacity</h3>
<p>Absolute homes, with a vertical marker for the selected year.</p>
<div id="housingChart"></div>
<div class="chart-legend">
<span><i></i>Matched housing demand</span>
<span><i class="fixed"></i>Fixed capacity</span>
<span><i class="expanded"></i>Expanded capacity</span>
</div>
</section>
<details open>
<summary>Stated assumptions</summary>
<ul class="assumptions">
<li>
<strong>Population:</strong>
<span id="populationAssumption"></span>.
</li>
<li>
<strong>Housing:</strong>
housing demand = population ÷ 2.4 people per home.
</li>
<li>
<strong>Water:</strong>
demand = 0.15 m³ per resident per day.
</li>
<li>
<strong>Schools:</strong>
demand = 0.18 school places per resident.
</li>
<li>
<strong>Jobs:</strong>
demand = 0.52 jobs per resident.
</li>
<li>
<strong>Expanded program:</strong>
each delivery adds 750 homes, 180 m³/day of water,
250 school places, and 850 jobs.
</li>
<li>
<strong>Shortage:</strong>
max(0, demand − capacity), displayed with the stated units.
</li>
</ul>
</details>
<div class="disclaimer">
These results are a deterministic capacity stress test. They do not
estimate future births, deaths, migration, household formation, or
actual demographic outcomes.
</div>
</aside>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Model
// -------------------------------------------------------------------------
const HORIZON = 20;
const state = {
year: 12,
growth: 1.5,
basePopulation: 12000,
firstDelivery: 4,
playing: false,
view: "compare"
};
const services = [
{
key: "housing",
label: "Housing",
shortLabel: "Homes",
unit: "homes",
decimals: 0,
demandPerResident: 1 / 2.4,
increment: 750
},
{
key: "water",
label: "Water",
shortLabel: "m³/day",
unit: "m³/day",
decimals: 0,
demandPerResident: 0.15,
increment: 180
},
{
key: "schools",
label: "Schools",
shortLabel: "Places",
unit: "places",
decimals: 0,
demandPerResident: 0.18,
increment: 250
},
{
key: "jobs",
label: "Jobs",
shortLabel: "Jobs",
unit: "jobs",
decimals: 0,
demandPerResident: 0.52,
increment: 850
}
];
const $ = (id) => document.getElementById(id);
const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
function integer(value) {
return Math.round(value).toLocaleString("en-US");
}
function serviceFormat(value, service) {
if (service.decimals === 0) {
return integer(value);
}
return value.toLocaleString("en-US", {
minimumFractionDigits: service.decimals,
maximumFractionDigits: service.decimals
});
}
function deliveryYears() {
const years = [];
for (
let year = state.firstDelivery;
year <= HORIZON;
year += 3
) {
years.push(year);
}
return years;
}
function populationAt(year) {
return state.basePopulation * Math.pow(1 + state.growth / 100, year);
}
function baseCapacity(service) {
switch (service.key) {
case "housing":
return Math.round(state.basePopulation / 2.4);
case "water":
return state.basePopulation * 0.15;
case "schools":
return state.basePopulation * 0.18;
case "jobs":
return state.basePopulation * 0.52;
default:
return 0;
}
}
function snapshotAt(year) {
const population = populationAt(year);
const deliveries = deliveryYears();
const result = {
population,
deliveries,
fixed: {},
expanded: {},
demand: {}
};
for (const service of services) {
const base = baseCapacity(service);
const deliveredCount = deliveries.filter((delivery) => delivery <= year).length;
result.demand[service.key] =
population * service.demandPerResident;
result.fixed[service.key] = base;
result.expanded[service.key] =
base + deliveredCount * service.increment;
}
return result;
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const sceneContainer = $("sceneContainer");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdce8e1);
scene.fog = new THREE.Fog(0xdce8e1, 105, 235);
const camera = new THREE.PerspectiveCamera(
39,
1,
0.1,
500
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.75));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
sceneContainer.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xf5fbf7, 0x6d7f6e, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff4dc, 3.2);
sun.position.set(-55, 85, 40);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -105;
sun.shadow.camera.right = 105;
sun.shadow.camera.top = 85;
sun.shadow.camera.bottom = -85;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 220;
sun.shadow.bias = -0.00035;
scene.add(sun);
const palette = {
good: {
body: 0x4e9d83,
roof: 0x2f6f60
},
near: {
body: 0xd89935,
roof: 0x9d6d27
},
bad: {
body: 0xdf684f,
roof: 0x9c4939
}
};
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0xb9cbb8,
roughness: 1,
flatShading: true
});
const roadMaterial = new THREE.MeshStandardMaterial({
color: 0x30413c,
roughness: 0.95,
flatShading: true
});
const pathMaterial = new THREE.MeshStandardMaterial({
color: 0x9cab9e,
roughness: 1,
flatShading: true
});
let randomSeed = 1739;
function random() {
randomSeed =
(randomSeed * 16807) % 2147483647;
return (randomSeed - 1) / 2147483646;
}
function roundedRect(ctx, x, y, w, h, radius) {
const r = Math.min(radius, w / 2, h / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
function makeSign(title, accent) {
const canvas = document.createElement("canvas");
canvas.width = 768;
canvas.height = 240;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(25, 7.8, 1);
sprite.renderOrder = 20;
return {
sprite,
canvas,
context,
texture,
title,
accent
};
}
function updateSign(sign, title, line2, line3) {
const ctx = sign.context;
ctx.clearRect(0, 0, sign.canvas.width, sign.canvas.height);
roundedRect(ctx, 4, 4, 760, 232, 26);
ctx.fillStyle = "rgba(22, 49, 42, 0.94)";
ctx.fill();
roundedRect(ctx, 19, 18, 9, 204, 5);
ctx.fillStyle = sign.accent;
ctx.fill();
ctx.textAlign = "left";
ctx.textBaseline = "alphabetic";
ctx.fillStyle = "#b9d7cb";
ctx.font = "800 25px system-ui, sans-serif";
ctx.fillText(title.toUpperCase(), 50, 64);
ctx.fillStyle = "#ffffff";
ctx.font = "800 39px system-ui, sans-serif";
ctx.fillText(line2, 50, 119);
ctx.fillStyle = "#c9d8d1";
ctx.font = "500 25px system-ui, sans-serif";
ctx.fillText(line3, 50, 170);
sign.texture.needsUpdate = true;
}
function makeBuilding(parent, x, z, width, height, depth, materials, root = null) {
const buildingRoot = root || new THREE.Group();
buildingRoot.position.set(x, 0, z);
const body = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
materials.body
);
body.position.y = height / 2;
body.castShadow = true;
body.receiveShadow = true;
buildingRoot.add(body);
const roof = new THREE.Mesh(
new THREE.ConeGeometry(width * 0.72, 1.4, 4),
materials.roof
);
roof.rotation.y = Math.PI / 4;
roof.position.y = height + 0.7;
roof.castShadow = true;
buildingRoot.add(roof);
if (!root) {
parent.add(buildingRoot);
}
return buildingRoot;
}
function makeTree(parent, x, z, scale = 1) {
const tree = new THREE.Group();
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
const trunk = new THREE.Mesh(
new THREE.CylinderGeometry(0.28, 0.36, 2.4, 5),
new THREE.MeshStandardMaterial({
color: 0x80674d,
roughness: 1,
flatShading: true
})
);
trunk.position.y = 1.2;
trunk.castShadow = true;
tree.add(trunk);
const foliage = new THREE.Mesh(
new THREE.ConeGeometry(1.45, 4.2, 5),
new THREE.MeshStandardMaterial({
color: random() > 0.5 ? 0x477a59 : 0x5d8f68,
roughness: 1,
flatShading: true
})
);
foliage.position.y = 4;
foliage.castShadow = true;
tree.add(foliage);
parent.add(tree);
}
function makeWaterTower(parent, materials) {
const group = new THREE.Group();
group.position.set(-27, 0, 25);
const legMaterial = new THREE.MeshStandardMaterial({
color: 0x697e76,
roughness: 0.9,
flatShading: true
});
for (const x of [-1.7, 1.7]) {
for (const z of [-1.7, 1.7]) {
const leg = new THREE.Mesh(
new THREE.BoxGeometry(0.42, 7, 0.42),
legMaterial
);
leg.position.set(x, 3.5, z);
leg.castShadow = true;
group.add(leg);
}
}
const tank = new THREE.Mesh(
new THREE.CylinderGeometry(3.2, 3.2, 4, 8),
materials.water
);
tank.position.y = 8.4;
tank.castShadow = true;
group.add(tank);
const cap = new THREE.Mesh(
new THREE.ConeGeometry(3.5, 1.7, 8),
materials.waterRoof
);
cap.position.y = 11.2;
cap.castShadow = true;
group.add(cap);
parent.add(group);
return group;
}
function makeCivicBuilding(
parent,
position,
size,
materials,
roofColor = 0x456a76
) {
const group = new THREE.Group();
group.position.set(position[0], 0, position[1]);
const body = new THREE.Mesh(
new THREE.BoxGeometry(size[0], size[1], size[2]),
materials.body
);
body.position.y = size[1] / 2;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const roof = new THREE.Mesh(
new THREE.BoxGeometry(size[0] + 0.45, 0.55, size[2] + 0.45),
new THREE.MeshStandardMaterial({
color: roofColor,
roughness: 0.9,
flatShading: true
})
);
roof.position.y = size[1] + 0.25;
roof.castShadow = true;
group.add(roof);
parent.add(group);
return group;
}
function addTownFrame(group, color) {
const frameMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.8,
flatShading: true
});
const pieces = [
[0, -34, 69, 0.45, 0.45],
[0, 34, 69, 0.45, 0.45],
[-34, 0, 0.45, 0.45, 69],
[34, 0, 0.45, 0.45, 69]
];
for (const [x, z, width, height, depth] of pieces) {
const piece = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
frameMaterial
);
piece.position.set(x, 0.1, z);
group.add(piece);
}
}
function makeTown(kind, worldX) {
const group = new THREE.Group();
group.position.x = worldX;
scene.add(group);
const ground = new THREE.Mesh(
new THREE.BoxGeometry(69, 1.1, 69),
groundMaterial
);
ground.position.y = -0.65;
ground.receiveShadow = true;
group.add(ground);
for (const z of [-13, 0, 13]) {
const road = new THREE.Mesh(
new THREE.BoxGeometry(64, 0.12, 3.1),
roadMaterial
);
road.position.set(0, 0.02, z);
road.receiveShadow = true;
group.add(road);
}
for (const x of [-16, 16]) {
const road = new THREE.Mesh(
new THREE.BoxGeometry(3.1, 0.12, 64),
roadMaterial
);
road.position.set(x, 0.025, 0);
road.receiveShadow = true;
group.add(road);
}
const path = new THREE.Mesh(
new THREE.BoxGeometry(1.2, 0.1, 60),
pathMaterial
);
path.position.set(-2, 0.04, 0);
group.add(path);
const residentialMaterials = {
body: new THREE.MeshStandardMaterial({
color: palette.good.body,
roughness: 0.92,
flatShading: true
}),
roof: new THREE.MeshStandardMaterial({
color: palette.good.roof,
roughness: 0.92,
flatShading: true
})
};
const serviceMaterials = {
water: new THREE.MeshStandardMaterial({
color: 0x4e9d83,
roughness: 0.8,
flatShading: true
}),
waterRoof: new THREE.MeshStandardMaterial({
color: 0x2f6f60,
roughness: 0.8,
flatShading: true
}),
school: new THREE.MeshStandardMaterial({
color: 0x5b8795,
roughness: 0.85,
flatShading: true
}),
jobs: new THREE.MeshStandardMaterial({
color: 0x6e7e91,
roughness: 0.85,
flatShading: true
}),
housing: new THREE.MeshStandardMaterial({
color: 0x4e9d83,
roughness: 0.85,
flatShading: true
})
};
const baseBuildings = [];
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 8; col++) {
const reservedCorner =
(row === 0 && (col === 0 || col === 7)) ||
(row === 3 && (col === 0 || col === 7));
if (reservedCorner) continue;
const x = -25 + col * 7.1;
const z = -21 + row * 11.4;
const width = 2.6 + random() * 1.8;
const depth = 2.5 + random() * 1.8;
const height = 3.5 + random() * 7.2;
baseBuildings.push(
makeBuilding(
group,
x,
z,
width,
height,
depth,
residentialMaterials
)
);
}
}
const extraBuildings = [];
for (let phase = 0; phase < 6; phase++) {
for (let item = 0; item < 2; item++) {
const index = phase * 2 + item;
const x = 30.5;
const z = -21 + index * 4;
const width = 2.2 + random() * 0.5;
const depth = 2.4 + random() * 0.5;
const height = 4.8 + random() * 4.2;
const root = new THREE.Group();
makeBuilding(
group,
x,
z,
width,
height,
depth,
residentialMaterials,
root
);
root.scale.setScalar(0.001);
extraBuildings.push({
root,
delivery: Infinity
});
}
}
const waterTower = makeWaterTower(group, serviceMaterials);
const school = makeCivicBuilding(
group,
[17, 25],
[9, 3.8, 5],
{ body: serviceMaterials.school },
0x385e69
);
const office = makeCivicBuilding(
group,
[25, -26],
[7, 8, 5.5],
{ body: serviceMaterials.jobs },
0x4b586a
);
const clinic = makeCivicBuilding(
group,
[-25, -26],
[6, 4.5, 5],
{ body: serviceMaterials.housing },
0x356c60
);
const station = makeCivicBuilding(
group,
[0, -28],
[12, 2.7, 3.5],
{ body: serviceMaterials.school },
0x456a76
);
for (const [x, z, scale] of [
[-11, 27, 0.9],
[-8, 25, 0.75],
[7, 27, 1],
[11, 24, 0.72],
[-19, -27, 0.8],
[7, -27, 0.88],
[14, -27, 0.7]
]) {
makeTree(group, x, z, scale);
}
addTownFrame(
group,
kind === "fixed" ? 0xcf725d : 0x3a8a74
);
const sign = makeSign(
kind === "fixed" ? "Fixed capacity" : "Expanded capacity",
kind === "fixed" ? "#e27b63" : "#56b596"
);
sign.sprite.position.set(0, 19, -33);
group.add(sign.sprite);
return {
kind,
group,
residentialMaterials,
serviceMaterials,
waterTower,
school,
office,
clinic,
station,
extraBuildings,
sign
};
}
const towns = {
fixed: makeTown("fixed", -38),
expanded: makeTown("expanded", 38)
};
// -------------------------------------------------------------------------
// Direct camera controls — no external control modules
// -------------------------------------------------------------------------
const orbit = {
theta: 0.72,
phi: 0.91,
radius: 148,
desiredTheta: 0.72,
desiredPhi: 0.91,
desiredRadius: 148,
target: new THREE.Vector3(0, 1, 0),
desiredTarget: new THREE.Vector3(0, 1, 0)
};
const canvas = renderer.domElement;
const pointers = new Map();
let pointerMode = "orbit";
let multiGesture = false;
let previousPinchDistance = 0;
function pointerDistance() {
const values = [...pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
if (pointers.size === 1) {
pointerMode = event.shiftKey || event.button === 2 ? "pan" : "orbit";
multiGesture = false;
} else {
multiGesture = true;
previousPinchDistance = pointerDistance();
}
});
canvas.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
const previous = { ...pointers.get(event.pointerId) };
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size >= 2) {
const distance = pointerDistance();
if (previousPinchDistance && distance) {
orbit.desiredRadius = clamp(
orbit.desiredRadius * (previousPinchDistance / distance),
50,
220
);
}
previousPinchDistance = distance;
return;
}
if (multiGesture) return;
const dx = event.clientX - previous.x;
const dy = event.clientY - previous.y;
if (pointerMode === "pan") {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
const right = new THREE.Vector3()
.crossVectors(forward, new THREE.Vector3(0, 1, 0))
.normalize();
const scale = orbit.radius * 0.0014;
orbit.target.addScaledVector(right, -dx * scale);
orbit.target.addScaledVector(forward, dy * scale);
orbit.desiredTarget.copy(orbit.target);
} else {
orbit.desiredTheta -= dx * 0.005;
orbit.desiredPhi = clamp(
orbit.desiredPhi - dy * 0.005,
0.34,
1.38
);
}
});
function releasePointer(event) {
pointers.delete(event.pointerId);
multiGesture = pointers.size > 1;
if (pointers.size === 1) {
previousPinchDistance = 0;
}
}
canvas.addEventListener("pointerup", releasePointer);
canvas.addEventListener("pointercancel", releasePointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.desiredRadius = clamp(
orbit.desiredRadius * Math.exp(event.deltaY * 0.001),
50,
220
);
},
{ passive: false }
);
function setView(view) {
state.view = view;
document.querySelectorAll("[data-view]").forEach((button) => {
button.classList.toggle("active", button.dataset.view === view);
});
if (view === "compare") {
orbit.desiredTarget.set(0, 1, 0);
orbit.desiredRadius = 148;
$("stageTitle").textContent = "Two capacity paths, one demand path";
} else if (view === "fixed") {
orbit.desiredTarget.set(-38, 1, 0);
orbit.desiredRadius = 91;
$("stageTitle").textContent = "Fixed capacity: demand outpaces supply";
} else {
orbit.desiredTarget.set(38, 1, 0);
orbit.desiredRadius = 91;
$("stageTitle").textContent = "Expanded capacity: phased additions";
}
}
document.querySelectorAll("[data-view]").forEach((button) => {
button.addEventListener("click", () => setView(button.dataset.view));
});
const resizeObserver = new ResizeObserver(() => {
const width = sceneContainer.clientWidth;
const height = sceneContainer.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
});
resizeObserver.observe(sceneContainer);
// -------------------------------------------------------------------------
// Visualization state
// -------------------------------------------------------------------------
function stressPalette(utilization) {
if (utilization > 1) return palette.bad;
if (utilization > 0.88) return palette.near;
return palette.good;
}
function applyTownColors(town, snapshot, scenarioKey) {
const capacity = snapshot[scenarioKey];
const housingUtilization =
snapshot.demand.housing / Math.max(1, capacity.housing);
const housingColors = stressPalette(housingUtilization);
town.residentialMaterials.body.color.setHex(housingColors.body);
town.residentialMaterials.roof.color.setHex(housingColors.roof);
const waterUtilization =
snapshot.demand.water / Math.max(1, capacity.water);
const waterColors = stressPalette(waterUtilization);
town.serviceMaterials.water.color.setHex(waterColors.body);
town.serviceMaterials.waterRoof.color.setHex(waterColors.roof);
const schoolUtilization =
snapshot.demand.schools / Math.max(1, capacity.schools);
const schoolColors = stressPalette(schoolUtilization);
town.serviceMaterials.school.color.setHex(schoolColors.body);
const jobsUtilization =
snapshot.demand.jobs / Math.max(1, capacity.jobs);
const jobsColors = stressPalette(jobsUtilization);
town.serviceMaterials.jobs.color.setHex(jobsColors.body);
town.serviceMaterials.housing.color.setHex(housingColors.body);
}
function updateTownSigns(snapshot) {
for (const key of ["fixed", "expanded"]) {
const town = towns[key];
const capacity = snapshot[key].housing;
const demand = snapshot.demand.housing;
const gap = Math.max(0, demand - capacity);
const gapText = gap > 0
? `Shortage ${integer(gap)} homes`
: `Covered · ${integer(capacity - demand)} homes spare`;
updateSign(
town.sign,
key === "fixed" ? "Fixed capacity" : "Expanded capacity",
gapText,
`Demand ${integer(demand)} homes`
);
}
}
function updateExpansionDelivery() {
const schedule = deliveryYears();
towns.expanded.extraBuildings.forEach((building, index) => {
building.delivery = schedule[index] ?? Infinity;
});
}
// -------------------------------------------------------------------------
// Readouts and chart
// -------------------------------------------------------------------------
function shortageClass(shortage, demand, capacity) {
if (shortage > 0) return "bad";
const utilization = demand / Math.max(1, capacity);
if (utilization > 0.88) return "near";
return "ok";
}
function coverageLabel(shortage, surplus, unit) {
if (shortage > 0) {
return `−${integer(shortage)} ${unit}`;
}
return `+${integer(surplus)} spare`;
}
function renderShortages(snapshot) {
$("shortageGrid").innerHTML = services
.map((service, index) => {
const demand = snapshot.demand[service.key];
const fixedCapacity = snapshot.fixed[service.key];
const expandedCapacity = snapshot.expanded[service.key];
const fixedGap = Math.max(0, demand - fixedCapacity);
const expandedGap = Math.max(0, demand - expandedCapacity);
const fixedPercent = clamp(
(demand / Math.max(1, fixedCapacity)) * 100,
0,
100
);
const expandedPercent = clamp(
(demand / Math.max(1, expandedCapacity)) * 100,
0,
100
);
const fixedColor = fixedGap > 0 ? "#df684f" : "#4e9d83";
const expandedColor = expandedGap > 0 ? "#df684f" : "#4e9d83";
return `
<article class="service-card ${index === 0 ? "wide" : ""}">
<div class="service-title">
<i class="service-dot"></i>
<strong>${service.label}</strong>
<small>${service.shortLabel}</small>
</div>
<div class="metric-line">
<span>Fixed</span>
<div class="mini-track">
<i style="width:${fixedPercent}%;background:${fixedColor}"></i>
</div>
<strong class="${shortageClass(fixedGap, demand, fixedCapacity)}">
${coverageLabel(fixedGap, fixedCapacity - demand, service.unit)}
</strong>
</div>
<div class="metric-line">
<span>Expanded</span>
<div class="mini-track">
<i style="width:${expandedPercent}%;background:${expandedColor}"></i>
</div>
<strong class="${shortageClass(expandedGap, demand, expandedCapacity)}">
${coverageLabel(expandedGap, expandedCapacity - demand, service.unit)}
</strong>
</div>
<div class="demand-note">
Matched demand: ${serviceFormat(demand, service)} ${service.unit}
</div>
</article>
`;
})
.join("");
}
function renderHousingChart() {
const width = 300;
const height = 170;
const margin = { top: 14, right: 10, bottom: 25, left: 36 };
const chartWidth = width - margin.left - margin.right;
const chartHeight = height - margin.top - margin.bottom;
const series = [];
for (let year = 0; year <= HORIZON; year++) {
const snapshot = snapshotAt(year);
series.push({
year,
demand: snapshot.demand.housing,
fixed: snapshot.fixed.housing,
expanded: snapshot.expanded.housing
});
}
const maximum = Math.max(
...series.flatMap((point) => [
point.demand,
point.fixed,
point.expanded
])
);
const yMax = Math.max(1000, Math.ceil(maximum / 1000) * 1000);
const x = (year) => margin.left + (year / HORIZON) * chartWidth;
const y = (value) =>
margin.top + chartHeight - (value / yMax) * chartHeight;
const demandPath = series
.map(
(point, index) =>
`${index === 0 ? "M" : "L"} ${x(point.year).toFixed(2)} ${y(point.demand).toFixed(2)}`
)
.join(" ");
const fixedPath = series
.map(
(point, index) =>
`${index === 0 ? "M" : "L"} ${x(point.year).toFixed(2)} ${y(point.fixed).toFixed(2)}`
)
.join(" ");
let expandedPath = `M ${x(0).toFixed(2)} ${y(series[0].expanded).toFixed(2)}`;
for (let index = 1; index < series.length; index++) {
const previous = series[index - 1];
const current = series[index];
expandedPath +=
` L ${x(current.year).toFixed(2)} ${y(previous.expanded).toFixed(2)}` +
` L ${x(current.year).toFixed(2)} ${y(current.expanded).toFixed(2)}`;
}
const grid = [0, 0.5, 1]
.map((ratio) => {
const value = yMax * ratio;
const yy = y(value);
const label = ratio === 0
? "0"
: `${(value / 1000).toFixed(value >= 1000 ? 0 : 1)}k`;
return `
<line
x1="${margin.left}"
x2="${width - margin.right}"
y1="${yy}"
y2="${yy}"
stroke="#dfe6e0"
stroke-width="1"
/>
<text
x="${margin.left - 6}"
y="${yy + 3}"
text-anchor="end"
fill="#7a8983"
font-size="8"
>${label}</text>
`;
})
.join("");
const currentPoint = series[Math.round(state.year)];
const cursorX = x(currentPoint.year);
const xLabels = [0, 5, 10, 15, 20]
.map(
(year) => `
<text
x="${x(year)}"
y="${height - 7}"
text-anchor="middle"
fill="#7a8983"
font-size="8"
>${year}</text>
`
)
.join("");
$("housingChart").innerHTML = `
<svg
viewBox="0 0 ${width} ${height}"
role="img"
aria-label="Housing demand compared with fixed and expanded capacity"
>
<title>Housing demand compared with fixed and expanded capacity</title>
${grid}
${xLabels}
<path
d="${demandPath}"
fill="none"
stroke="#df684f"
stroke-width="2.4"
stroke-linejoin="round"
stroke-linecap="round"
/>
<path
d="${fixedPath}"
fill="none"
stroke="#82908a"
stroke-width="1.8"
stroke-dasharray="5 4"
/>
<path
d="${expandedPath}"
fill="none"
stroke="#167d6b"
stroke-width="2.2"
stroke-linejoin="round"
/>
<line
x1="${cursorX}"
x2="${cursorX}"
y1="${margin.top}"
y2="${margin.top + chartHeight}"
stroke="#243b35"
stroke-width="1"
stroke-dasharray="2 3"
opacity="0.55"
/>
<circle
cx="${cursorX}"
cy="${y(currentPoint.demand)}"
r="3.5"
fill="#df684f"
stroke="#fff"
stroke-width="1.5"
/>
</svg>
`;
}
function refresh() {
const snapshot = snapshotAt(state.year);
const year = Math.round(state.year);
$("yearSlider").value = year;
$("yearDisplay").textContent = year;
$("readoutYear").textContent = `Year ${year}`;
$("headerPopulation").textContent = integer(snapshot.population);
$("stagePopulation").textContent = integer(snapshot.population);
$("populationAssumption").textContent =
`${integer(state.basePopulation)} residents compounded at ` +
`${state.growth.toFixed(1)}% annually for ${year} years`;
renderShortages(snapshot);
renderHousingChart();
applyTownColors(towns.fixed, snapshot, "fixed");
applyTownColors(towns.expanded, snapshot, "expanded");
updateTownSigns(snapshot);
updateExpansionDelivery();
}
// -------------------------------------------------------------------------
// Controls and playback
// -------------------------------------------------------------------------
$("growthRate").addEventListener("input", (event) => {
state.growth = Number(event.target.value);
$("growthOutput").textContent = `${state.growth.toFixed(1)}% / yr`;
refresh();
});
$("basePopulation").addEventListener("change", (event) => {
const value = Number(event.target.value);
state.basePopulation = clamp(
Number.isFinite(value) ? value : 12000,
4000,
30000
);
event.target.value = state.basePopulation;
refresh();
});
$("firstDelivery").addEventListener("input", (event) => {
state.firstDelivery = Number(event.target.value);
$("deliveryOutput").textContent = `Year ${state.firstDelivery}`;
const years = deliveryYears();
$("scheduleText").textContent =
`Bundled infrastructure is delivered in years ` +
`${years.join(", ")}.`;
refresh();
});
$("yearSlider").addEventListener("input", (event) => {
state.year = Number(event.target.value);
refresh();
});
function updatePlayButton() {
$("playButton").textContent = state.playing ? "❚❚" : "▶";
$("playButton").setAttribute("aria-pressed", String(state.playing));
$("playButton").setAttribute(
"aria-label",
state.playing ? "Pause simulation" : "Play simulation"
);
}
$("playButton").addEventListener("click", () => {
if (!state.playing && state.year >= HORIZON) {
state.year = 0;
refresh();
}
state.playing = !state.playing;
updatePlayButton();
});
document.addEventListener("keydown", (event) => {
const tag = document.activeElement?.tagName;
if (["INPUT", "TEXTAREA", "SELECT", "BUTTON"].includes(tag)) return;
if (event.code === "Space") {
event.preventDefault();
$("playButton").click();
}
if (event.code === "ArrowRight") {
event.preventDefault();
state.year = clamp(Math.round(state.year) + 1, 0, HORIZON);
refresh();
}
if (event.code === "ArrowLeft") {
event.preventDefault();
state.year = clamp(Math.round(state.year) - 1, 0, HORIZON);
refresh();
}
});
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
let lastDisplayedYear = Math.floor(state.year);
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
if (state.playing) {
state.year += dt * 0.82;
if (state.year >= HORIZON) {
state.year = HORIZON;
state.playing = false;
updatePlayButton();
}
if (Math.floor(state.year) !== lastDisplayedYear) {
lastDisplayedYear = Math.floor(state.year);
refresh();
}
}
const smoothing = 1 - Math.exp(-dt * 8);
for (const building of towns.expanded.extraBuildings) {
const target = building.delivery <= state.year ? 1 : 0.001;
const nextScale =
building.root.scale.x +
(target - building.root.scale.x) * smoothing;
building.root.scale.setScalar(nextScale);
}
orbit.theta +=
(orbit.desiredTheta - orbit.theta) * (1 - Math.exp(-dt * 10));
orbit.phi +=
(orbit.desiredPhi - orbit.phi) * (1 - Math.exp(-dt * 10));
orbit.radius +=
(orbit.desiredRadius - orbit.radius) * (1 - Math.exp(-dt * 7));
orbit.target.lerp(
orbit.desiredTarget,
1 - Math.exp(-dt * 5)
);
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
renderer.render(scene, camera);
}
$("growthOutput").textContent = `${state.growth.toFixed(1)}% / yr`;
$("deliveryOutput").textContent = `Year ${state.firstDelivery}`;
updatePlayButton();
refresh();
animate();
</script>
</body>
</html>
```