Prompt specification
Build or customize the Three.js 3D scene "Bridge Closure Changes Service Coverage" 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: Bridge Closure Changes Service Coverage
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/bridge-closure-changes-service-coverage-x3580
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts service locations and reachable coverage. Create a facility-placement puzzle where one connection fails. Recompute access and let users add one backup site or route under a fixed construction budget. Voxel style.
Working Three.js Starter (bridge-closure-changes-service-coverage-x3580):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Relay District — Coverage Recovery</title>
<style>
:root {
--bg: #07111d;
--panel: rgba(12, 24, 39, 0.92);
--panel-solid: #0c1827;
--line: rgba(167, 202, 226, 0.16);
--text: #edf6fc;
--muted: #8da5b7;
--green: #5be5ad;
--red: #ff666d;
--amber: #ffc857;
--blue: #69b7ff;
--purple: #b58cff;
}
* {
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 {
color: inherit;
font: inherit;
}
button:focus-visible {
outline: 2px solid var(--amber);
outline-offset: 2px;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene.dragging {
cursor: grabbing;
}
#labels {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
overflow: hidden;
}
.map-label {
position: absolute;
transform: translate(-50%, -100%);
white-space: nowrap;
padding: 6px 8px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 5px;
background: rgba(6, 14, 24, 0.88);
box-shadow: 0 5px 18px rgba(0, 0, 0, 0.28);
color: #dceaf4;
font: 700 10px/1.15 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
letter-spacing: 0.05em;
backdrop-filter: blur(8px);
}
.map-label::after {
content: "";
position: absolute;
left: 50%;
top: 100%;
width: 1px;
height: 10px;
background: rgba(220, 234, 244, 0.42);
}
.map-label.online {
border-color: rgba(91, 229, 173, 0.38);
}
.map-label.down {
border-color: rgba(255, 102, 109, 0.55);
color: #ffb3b6;
}
.map-label.backup {
border-color: rgba(255, 200, 87, 0.55);
color: #ffe2a0;
}
.map-label.candidate {
color: #ffe2a0;
border-color: rgba(255, 200, 87, 0.35);
}
.topbar {
position: fixed;
z-index: 10;
top: 18px;
left: 20px;
right: 20px;
height: 58px;
display: flex;
align-items: stretch;
justify-content: space-between;
gap: 14px;
pointer-events: none;
}
.brand,
.budget-box,
.network-status {
pointer-events: auto;
border: 1px solid var(--line);
background: var(--panel);
box-shadow: 0 14px 35px rgba(0, 0, 0, 0.25);
backdrop-filter: blur(14px);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 260px;
padding: 9px 14px;
border-radius: 9px;
}
.brand-mark {
position: relative;
width: 34px;
height: 34px;
flex: 0 0 auto;
}
.brand-mark i {
position: absolute;
display: block;
background: var(--green);
border-radius: 2px;
box-shadow: 0 0 18px rgba(91, 229, 173, 0.28);
}
.brand-mark i:nth-child(1) {
width: 10px;
height: 30px;
left: 12px;
top: 2px;
}
.brand-mark i:nth-child(2) {
width: 30px;
height: 10px;
left: 2px;
top: 12px;
}
.brand-copy {
min-width: 0;
}
.brand-title {
font-size: 14px;
font-weight: 850;
letter-spacing: 0.13em;
}
.brand-subtitle {
margin-top: 3px;
color: var(--muted);
font: 600 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
white-space: nowrap;
}
.top-center {
display: flex;
align-items: center;
gap: 10px;
pointer-events: auto;
}
.network-status {
height: 40px;
padding: 0 13px;
display: flex;
align-items: center;
gap: 8px;
border-radius: 7px;
color: #ffc3c6;
font: 750 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--red);
box-shadow: 0 0 12px rgba(255, 102, 109, 0.7);
}
.network-status.good {
color: #baf8df;
}
.network-status.good .status-dot {
background: var(--green);
box-shadow: 0 0 12px rgba(91, 229, 173, 0.7);
}
.budget-box {
min-width: 245px;
padding: 8px 12px 9px;
border-radius: 9px;
display: grid;
grid-template-columns: 1fr auto;
grid-template-rows: auto auto;
column-gap: 12px;
align-items: center;
}
.budget-caption {
color: var(--muted);
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
}
#budgetText {
grid-column: 2;
grid-row: 1 / span 2;
font: 850 22px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
color: var(--amber);
}
.budget-track {
grid-column: 1;
margin-top: 7px;
height: 4px;
background: rgba(255, 255, 255, 0.08);
overflow: hidden;
border-radius: 2px;
}
#budgetFill {
width: 0;
height: 100%;
background: var(--amber);
transition: width 0.3s ease;
}
.panel {
position: fixed;
z-index: 9;
top: 90px;
left: 20px;
width: 322px;
max-height: calc(100vh - 164px);
overflow-y: auto;
padding: 19px;
border: 1px solid var(--line);
border-radius: 11px;
background: var(--panel);
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(16px);
scrollbar-width: thin;
scrollbar-color: #31475b transparent;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
color: var(--red);
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.1em;
}
.eyebrow::before {
content: "";
width: 17px;
height: 3px;
background: currentColor;
box-shadow: 5px 0 0 rgba(255, 255, 255, 0.18);
}
.panel h1 {
margin: 13px 0 8px;
font-size: 27px;
line-height: 1.06;
letter-spacing: -0.035em;
}
.panel h1.success {
color: var(--green);
}
.panel p {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.objective {
margin: 14px 0 0;
padding: 10px 11px;
border: 1px solid rgba(255, 200, 87, 0.22);
border-left: 3px solid var(--amber);
border-radius: 5px;
background: rgba(255, 200, 87, 0.055);
color: #c9d6df;
font-size: 11px;
line-height: 1.45;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin: 16px 0;
}
.metric {
min-width: 0;
padding: 10px 9px;
border: 1px solid var(--line);
border-radius: 6px;
background: rgba(255, 255, 255, 0.025);
}
.metric-label {
color: var(--muted);
font: 700 8px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.08em;
}
.metric-value {
display: block;
margin-top: 7px;
font: 850 20px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.metric-value.green {
color: var(--green);
}
.metric-value.red {
color: var(--red);
}
.section-title {
margin: 17px 0 9px;
color: #dce9f2;
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.action-tabs {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-bottom: 12px;
}
.action-tab {
min-height: 39px;
border: 1px solid var(--line);
border-radius: 6px;
background: rgba(255, 255, 255, 0.025);
cursor: pointer;
color: var(--muted);
font-size: 11px;
font-weight: 750;
transition: 0.18s ease;
}
.action-tab:hover {
border-color: rgba(255, 255, 255, 0.28);
color: var(--text);
}
.action-tab.active {
border-color: rgba(255, 200, 87, 0.55);
background: rgba(255, 200, 87, 0.1);
color: #ffe1a0;
}
.action-tab:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.candidate-list {
display: grid;
gap: 7px;
}
.candidate-card {
width: 100%;
padding: 10px;
display: grid;
grid-template-columns: 1fr auto;
gap: 4px 10px;
text-align: left;
border: 1px solid var(--line);
border-radius: 6px;
background: rgba(255, 255, 255, 0.025);
cursor: pointer;
transition: 0.18s ease;
}
.candidate-card:hover:not(:disabled),
.candidate-card.selected {
border-color: rgba(255, 200, 87, 0.5);
background: rgba(255, 200, 87, 0.075);
transform: translateX(2px);
}
.candidate-card:disabled {
opacity: 0.42;
cursor: not-allowed;
}
.candidate-name {
font-size: 12px;
font-weight: 800;
}
.candidate-cost {
color: var(--amber);
font: 800 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.candidate-detail {
grid-column: 1 / -1;
color: var(--muted);
font: 600 9px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.route-instructions {
padding: 11px;
border: 1px dashed rgba(255, 200, 87, 0.3);
border-radius: 6px;
background: rgba(255, 200, 87, 0.045);
color: #c7d4de;
font-size: 11px;
line-height: 1.5;
}
.route-readout {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 9px;
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 6px;
color: var(--muted);
font-size: 10px;
}
#routeCost {
color: var(--amber);
font: 850 15px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.small-button {
width: 100%;
margin-top: 9px;
padding: 8px;
border: 1px solid var(--line);
border-radius: 5px;
background: rgba(255, 255, 255, 0.035);
color: #c5d3dd;
cursor: pointer;
font-size: 10px;
font-weight: 750;
}
.small-button:hover {
border-color: rgba(255, 255, 255, 0.27);
}
.ledger {
position: fixed;
z-index: 8;
top: 90px;
right: 20px;
width: 275px;
padding: 15px;
border: 1px solid var(--line);
border-radius: 10px;
background: var(--panel);
box-shadow: 0 18px 45px rgba(0, 0, 0, 0.25);
backdrop-filter: blur(14px);
}
.ledger-head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.09em;
}
.ledger-count {
color: var(--green);
}
.ledger-list {
display: grid;
gap: 1px;
}
.ledger-row {
display: grid;
grid-template-columns: 9px 1fr auto;
align-items: center;
gap: 8px;
min-height: 27px;
border-bottom: 1px solid rgba(255, 255, 255, 0.045);
color: #bfd0dc;
font-size: 10px;
}
.ledger-row:last-child {
border-bottom: 0;
}
.ledger-dot {
width: 7px;
height: 7px;
border-radius: 2px;
background: var(--green);
box-shadow: 0 0 7px rgba(91, 229, 173, 0.4);
}
.ledger-dot.offline {
background: var(--red);
box-shadow: 0 0 7px rgba(255, 102, 109, 0.42);
}
.ledger-state {
color: var(--muted);
font: 700 8px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.06em;
}
.ledger-state.offline {
color: #ff9da2;
}
.legend {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 12px;
padding-top: 11px;
border-top: 1px solid var(--line);
color: var(--muted);
font-size: 9px;
}
.legend span {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
}
.modebar {
position: fixed;
z-index: 10;
left: 50%;
bottom: 19px;
transform: translateX(-50%);
min-width: 420px;
max-width: calc(100vw - 40px);
min-height: 43px;
display: flex;
align-items: center;
gap: 11px;
padding: 8px 10px 8px 13px;
border: 1px solid var(--line);
border-radius: 8px;
background: rgba(9, 20, 33, 0.92);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(12px);
}
.mode-icon {
width: 12px;
height: 12px;
flex: 0 0 auto;
border: 2px solid var(--amber);
box-shadow: 4px 4px 0 rgba(255, 200, 87, 0.25);
}
#modeText {
color: #c8d6e0;
font-size: 11px;
font-weight: 650;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.modebar button {
margin-left: auto;
flex: 0 0 auto;
padding: 7px 9px;
border: 1px solid var(--line);
border-radius: 5px;
background: rgba(255, 255, 255, 0.04);
color: #cbd8e2;
cursor: pointer;
font-size: 10px;
font-weight: 750;
}
#toast {
position: fixed;
z-index: 20;
left: 50%;
top: 88px;
max-width: min(460px, calc(100vw - 40px));
transform: translate(-50%, -12px);
padding: 10px 14px;
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: 7px;
background: rgba(10, 21, 34, 0.96);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.3);
color: #dbe8f1;
font-size: 11px;
line-height: 1.4;
opacity: 0;
pointer-events: none;
transition: 0.2s ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.error {
border-color: rgba(255, 102, 109, 0.5);
color: #ffc2c5;
}
#toast.success {
border-color: rgba(91, 229, 173, 0.5);
color: #bcf8df;
}
#loading {
position: fixed;
z-index: 50;
inset: 0;
display: grid;
place-items: center;
background: #07111d;
color: #91a8b9;
font: 800 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
transition: opacity 0.25s ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 1050px) {
.ledger {
display: none;
}
.top-center {
display: none;
}
}
@media (max-width: 720px) {
.topbar {
top: 10px;
left: 10px;
right: 10px;
height: auto;
}
.brand {
min-width: 0;
padding: 8px 10px;
}
.brand-subtitle {
display: none;
}
.budget-box {
min-width: 145px;
}
#budgetText {
font-size: 18px;
}
.panel {
top: 79px;
left: 10px;
width: min(310px, calc(100vw - 20px));
max-height: calc(100vh - 195px);
padding: 15px;
}
.panel h1 {
font-size: 23px;
}
.modebar {
bottom: 10px;
min-width: 0;
width: calc(100vw - 20px);
}
#modeText {
font-size: 10px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel city coverage puzzle"></canvas>
<div id="labels"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"><i></i><i></i></div>
<div class="brand-copy">
<div class="brand-title">RELAY DISTRICT</div>
<div class="brand-subtitle">COVERAGE RECOVERY / PUZZLE 04</div>
</div>
</div>
<div class="top-center">
<div class="network-status" id="networkStatus">
<span class="status-dot"></span>
<span id="networkStatusText">NETWORK DEGRADED</span>
</div>
</div>
<div class="budget-box">
<div class="budget-caption">CONSTRUCTION BUDGET</div>
<div class="budget-track"><div id="budgetFill"></div></div>
<div id="budgetText">$130K</div>
</div>
</header>
<aside class="panel">
<div class="eyebrow" id="missionEyebrow">ONE LINK DOWN</div>
<h1 id="missionTitle">Coverage gap.<br />One move to fix it.</h1>
<p id="missionCopy">
Civic Clinic lost its uplink. Three nearby service blocks can no longer
reach an active facility.
</p>
<div class="objective">
<strong>OBJECTIVE:</strong> Restore all 10 service blocks with one backup
site or one alternate route. Maximum spend: $130K.
</div>
<div class="metrics">
<div class="metric">
<div class="metric-label">ACCESS</div>
<b class="metric-value" id="accessMetric">7 / 10</b>
</div>
<div class="metric">
<div class="metric-label">ONLINE HUBS</div>
<b class="metric-value green" id="facilityMetric">3</b>
</div>
<div class="metric">
<div class="metric-label">STRANDED</div>
<b class="metric-value red" id="strandedMetric">3</b>
</div>
</div>
<div class="section-title">Choose one construction action</div>
<div class="action-tabs">
<button class="action-tab active" data-mode="backup">Backup site</button>
<button class="action-tab" data-mode="route">Repair route</button>
</div>
<div id="backupPane">
<p style="margin-bottom: 9px">
Select a parcel, then click its glowing marker in the city.
</p>
<div class="candidate-list" id="candidateList"></div>
</div>
<div id="routePane" hidden>
<div class="route-instructions">
Start at the red <strong>Civic Clinic</strong>. Follow amber street
junctions one block at a time, then finish at any online hub.
</div>
<div class="route-readout">
<span>Current route estimate</span>
<strong id="routeCost">$0K</strong>
</div>
<button class="small-button" id="clearRoute">Clear route</button>
</div>
<button class="small-button" id="resetButton" style="margin-top: 14px">
Reset district
</button>
</aside>
<aside class="ledger">
<div class="ledger-head">
<span>ACCESS LEDGER</span>
<span class="ledger-count" id="ledgerCount">7 / 10</span>
</div>
<div class="ledger-list" id="ledgerList"></div>
<div class="legend">
<span><i class="swatch" style="background: var(--green)"></i>Reachable</span>
<span><i class="swatch" style="background: var(--red)"></i>Stranded</span>
<span><i class="swatch" style="background: var(--amber)"></i>Backup</span>
<span><i class="swatch" style="background: var(--blue)"></i>Online hub</span>
</div>
</aside>
<div class="modebar">
<div class="mode-icon"></div>
<div id="modeText">Drag to orbit · Scroll to zoom · Click facilities to inspect</div>
<button id="modeAction" hidden>Clear route</button>
</div>
<div id="toast" role="status" aria-live="polite"></div>
<div id="loading">BUILDING DISTRICT...</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const canvas = $("#scene");
const labelsLayer = $("#labels");
const BUDGET_TOTAL = 130000;
const ROUTE_COST_PER_BLOCK = 18000;
const ROAD_X = [-9, -6, -3, 0, 3, 6, 9];
const ROAD_Z = [-6, -3, 0, 3, 6];
const facilities = [
{
id: "civic",
name: "Civic Clinic",
short: "CIVIC CLINIC",
x: -6,
z: -3,
radius: 3.4,
color: 0xffb454,
online: false,
backup: false
},
{
id: "north",
name: "North Relay",
short: "NORTH RELAY",
x: -6,
z: 6,
radius: 3.8,
color: 0x5be5ad,
online: true,
backup: false
},
{
id: "east",
name: "East Works",
short: "EAST WORKS",
x: 6,
z: 0,
radius: 4.7,
color: 0x69b7ff,
online: true,
backup: false
},
{
id: "south",
name: "South Market",
short: "SOUTH MARKET",
x: 3,
z: -6,
radius: 4.2,
color: 0xb58cff,
online: true,
backup: false
}
];
const demands = [
{ id: "B12", name: "Block 12", x: -5, z: -4 },
{ id: "SCH", name: "North School", x: -7, z: -2 },
{ id: "TRN", name: "Transit Stop", x: -4, z: -3 },
{ id: "HIL", name: "Hill Homes", x: -8, z: 7 },
{ id: "LAB", name: "Research Row", x: -3, z: 4 },
{ id: "DOC", name: "Dock Offices", x: 8, z: 2 },
{ id: "MKT", name: "Market East", x: 4, z: -2 },
{ id: "PIE", name: "Pier Homes", x: 7, z: -4 },
{ id: "CRT", name: "Civic Court", x: 8, z: 4 },
{ id: "TER", name: "South Terrace", x: 1, z: -8 }
];
const candidates = [
{
id: "west",
name: "West Parcel",
x: -8,
z: -5,
radius: 5.6,
cost: 95000
},
{
id: "canal",
name: "Canal Lot",
x: -4,
z: -6,
radius: 5.2,
cost: 110000
},
{
id: "signal",
name: "Signal Lot",
x: -8,
z: -1,
radius: 3.4,
cost: 86000
}
];
const state = {
mode: "backup",
actionTaken: false,
remaining: BUDGET_TOTAL,
selectedBackup: null,
activeBackup: null,
route: [],
routeBuilt: false
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111d);
scene.fog = new THREE.Fog(0x07111d, 35, 68);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const camera = new THREE.OrthographicCamera(
-20,
20,
20,
-20,
0.1,
120
);
const controls = {
target: new THREE.Vector3(0, 0, 0),
azimuth: 0.73,
polar: 0.88,
zoom: 1,
dragging: false,
moved: false,
pointerId: null,
lastX: 0,
lastY: 0
};
const hemi = new THREE.HemisphereLight(0x9fd8ff, 0x172235, 1.65);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff0d6, 3.1);
sun.position.set(-13, 24, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -20;
sun.shadow.camera.right = 20;
sun.shadow.camera.top = 20;
sun.shadow.camera.bottom = -20;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 55;
sun.shadow.bias = -0.0005;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x5fa8ff, 0.65);
rim.position.set(15, 9, -14);
scene.add(rim);
const materialCache = new Map();
const geometryCache = new Map();
const pickables = [];
const facilityVisuals = new Map();
const demandVisuals = new Map();
const candidateVisuals = new Map();
const labelItems = [];
const coverageGroup = new THREE.Group();
const routeGroup = new THREE.Group();
const routeNodesGroup = new THREE.Group();
scene.add(coverageGroup, routeGroup, routeNodesGroup);
const staticMaterials = {
window: new THREE.MeshStandardMaterial({
color: 0xffd99a,
emissive: 0xffb84a,
emissiveIntensity: 0.45,
roughness: 0.65
}),
route: new THREE.MeshStandardMaterial({
color: 0xffc857,
emissive: 0xff9f19,
emissiveIntensity: 0.55,
roughness: 0.75
})
};
function material(color, emissive = 0) {
const key = `${color}-${emissive}`;
if (!materialCache.has(key)) {
materialCache.set(
key,
new THREE.MeshStandardMaterial({
color,
emissive,
emissiveIntensity: emissive ? 0.24 : 0,
roughness: 0.86,
metalness: 0.04,
flatShading: true
})
);
}
return materialCache.get(key);
}
function boxGeometry(w, h, d) {
const key = `${w}-${h}-${d}`;
if (!geometryCache.has(key)) {
geometryCache.set(key, new THREE.BoxGeometry(w, h, d));
}
return geometryCache.get(key);
}
function makeBox(parent, w, h, d, color, x = 0, y = 0, z = 0, customMaterial = null) {
const mesh = new THREE.Mesh(
boxGeometry(w, h, d),
customMaterial || material(color)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function formatMoney(value) {
return `$${Math.round(value / 1000)}K`;
}
function seededRandom(seed) {
let value = seed >>> 0;
return () => {
value = (value * 1664525 + 1013904223) >>> 0;
return value / 4294967296;
};
}
function distance2D(a, b) {
return Math.hypot(a.x - b.x, a.z - b.z);
}
function allFacilities() {
return state.activeBackup
? [...facilities, state.activeBackup]
: facilities;
}
function activeFacilities() {
return allFacilities().filter((facility) => facility.online);
}
function createLabel(className, position, text) {
const element = document.createElement("div");
element.className = `map-label ${className}`;
element.textContent = text;
labelsLayer.appendChild(element);
const item = { element, position };
labelItems.push(item);
return item;
}
function buildCity() {
const city = new THREE.Group();
scene.add(city);
makeBox(city, 27, 1, 21, 0x152638, 0, -0.55, 0).castShadow = false;
makeBox(city, 27.3, 0.18, 21.3, 0x30475a, 0, -0.08, 0).castShadow = false;
const roadMat = material(0x1d2c3a);
const stripeMat = material(0x617487);
for (const x of ROAD_X) {
const road = makeBox(city, 0.76, 0.055, 19, 0x1d2c3a, x, 0.015, 0);
road.material = roadMat;
road.castShadow = false;
}
for (const z of ROAD_Z) {
const road = makeBox(city, 25, 0.055, 0.76, 0x1d2c3a, 0, 0.018, z);
road.material = roadMat;
road.castShadow = false;
}
for (const x of ROAD_X) {
for (let z = -8.4; z <= 8.4; z += 1.45) {
if (ROAD_Z.some((roadZ) => Math.abs(roadZ - z) < 0.55)) continue;
makeBox(city, 0.08, 0.012, 0.46, 0x617487, x, 0.052, z).castShadow = false;
}
}
for (const z of ROAD_Z) {
for (let x = -11.8; x <= 11.8; x += 1.45) {
if (ROAD_X.some((roadX) => Math.abs(roadX - x) < 0.55)) continue;
makeBox(city, 0.46, 0.012, 0.08, 0x617487, x, 0.055, z).castShadow = false;
}
}
// Voxel canal along the east edge.
makeBox(city, 2.05, 0.08, 19.5, 0x123f55, 11.45, 0.02, 0).castShadow = false;
makeBox(city, 0.18, 0.16, 4.2, 0xd9e4e7, 11.55, 0.25, -2.5);
makeBox(city, 1.05, 0.18, 0.55, 0xdd5f5f, 11.55, 0.29, -2.5);
const specialPoints = [
...facilities,
...demands,
...candidates
];
const random = seededRandom(74021);
const buildingColors = [0x294056, 0x314c61, 0x3b5264, 0x253a50, 0x40566a];
const roofColors = [0x50677a, 0x617284, 0x435d71];
const xCenters = [-10.5, -7.5, -4.5, -1.5, 1.5, 4.5, 7.5, 10.5];
const zCenters = [-7.5, -4.5, -1.5, 1.5, 4.5, 7.5];
for (const x of xCenters) {
for (const z of zCenters) {
if (x > 10) continue;
const cellHasSpecial = specialPoints.some(
(point) => Math.abs(point.x - x) < 2.05 && Math.abs(point.z - z) < 2.05
);
if (cellHasSpecial) continue;
const buildingCount = random() > 0.73 ? 2 : 1;
for (let index = 0; index < buildingCount; index++) {
const offsetX = buildingCount === 2 ? (index === 0 ? -0.55 : 0.55) : 0;
const offsetZ = buildingCount === 1 && random() > 0.72 ? 0.38 : 0;
const width = 0.9 + random() * 0.72;
const depth = 0.9 + random() * 0.72;
const height = 0.65 + random() * 2.85;
const bx = x + offsetX;
const bz = z + offsetZ;
const building = new THREE.Group();
building.position.set(bx, 0, bz);
city.add(building);
const color = buildingColors[Math.floor(random() * buildingColors.length)];
makeBox(
building,
width,
height,
depth,
color,
0,
height / 2,
0
);
makeBox(
building,
width * 0.62,
0.16,
depth * 0.58,
roofColors[Math.floor(random() * roofColors.length)],
0,
height + 0.08,
0
);
if (random() > 0.28) {
makeBox(
building,
width * 0.22,
0.25,
depth * 0.22,
0x607789,
width * 0.17,
height + 0.28,
-depth * 0.12
);
}
const windowCount = height > 1.5 ? 2 : 1;
for (let level = 0; level < windowCount; level++) {
const wy = 0.55 + level * 0.75;
if (wy > height - 0.2) continue;
for (const side of [-1, 1]) {
makeBox(
building,
0.18,
0.22,
0.035,
0xffd99a,
side * width * 0.23,
wy,
depth / 2 + 0.022,
staticMaterials.window
);
}
}
}
}
}
// Small block trees.
for (const [x, z] of [
[-10.7, 3.3],
[-7.7, -7.6],
[-1.5, 7.6],
[4.5, 7.5],
[7.5, -7.5],
[10.4, -4.5]
]) {
makeBox(city, 0.2, 0.75, 0.2, 0x70503d, x, 0.38, z);
makeBox(city, 0.7, 0.65, 0.7, 0x2d6a59, x, 0.94, z);
makeBox(city, 0.48, 0.38, 0.48, 0x397e68, x, 1.42, z);
}
}
function createFacilityVisual(facility) {
const group = new THREE.Group();
group.position.set(facility.x, 0, facility.z);
group.userData.pick = { kind: "facility", id: facility.id };
scene.add(group);
makeBox(group, 2.15, 0.28, 2.15, 0x21374a, 0, 0.14, 0);
makeBox(group, 1.68, 0.12, 1.68, 0xc6d5dc, 0, 0.34, 0);
const statusMaterial = new THREE.MeshStandardMaterial({
color: 0xff666d,
emissive: 0xff333a,
emissiveIntensity: 0.35,
roughness: 0.7,
flatShading: true
});
makeBox(group, 1.05, 2.05, 1.05, 0xffffff, 0, 1.42, 0, statusMaterial);
makeBox(group, 1.48, 0.28, 0.38, 0xffffff, 0, 2.72, 0, statusMaterial);
makeBox(group, 0.38, 0.28, 1.48, 0xffffff, 0, 2.72, 0, statusMaterial);
const ringMaterial = new THREE.MeshBasicMaterial({
color: 0xff666d,
transparent: true,
opacity: 0.85
});
makeBox(group, 2.45, 0.09, 0.16, 0xffffff, 0, 0.08, 1.05, ringMaterial);
makeBox(group, 2.45, 0.09, 0.16, 0xffffff, 0, 0.08, -1.05, ringMaterial);
makeBox(group, 0.16, 0.09, 2.45, 0xffffff, 1.05, 0.08, 0, ringMaterial);
makeBox(group, 0.16, 0.09, 2.45, 0xffffff, -1.05, 0.08, 0, ringMaterial);
const beacon = new THREE.Group();
beacon.position.y = 3.15;
group.add(beacon);
makeBox(beacon, 0.3, 0.3, 0.3, 0xffffff, 0, 0, 0, statusMaterial);
makeBox(beacon, 0.12, 0.12, 0.95, 0xffffff, 0, 0, 0, statusMaterial);
makeBox(beacon, 0.95, 0.12, 0.12, 0xffffff, 0, 0, 0, statusMaterial);
const label = createLabel(
facility.backup ? "backup" : "online",
new THREE.Vector3(facility.x, 3.75, facility.z),
facility.short
);
pickables.push(group);
facilityVisuals.set(facility.id, {
group,
statusMaterial,
ringMaterial,
beacon,
label
});
}
function createDemandVisual(demand) {
const group = new THREE.Group();
group.position.set(demand.x, 0, demand.z);
group.userData.pick = { kind: "demand", id: demand.id };
scene.add(group);
makeBox(group, 0.72, 0.38, 0.72, 0x465d70, 0, 0.19, 0);
makeBox(group, 0.46, 0.48, 0.46, 0xe3edf2, 0, 0.62, 0);
const statusMaterial = new THREE.MeshStandardMaterial({
color: 0xff666d,
emissive: 0xff3038,
emissiveIntensity: 0.42,
roughness: 0.55,
flatShading: true
});
makeBox(group, 0.15, 0.95, 0.15, 0xffffff, 0, 1.32, 0, statusMaterial);
makeBox(group, 0.72, 0.15, 0.15, 0xffffff, 0, 1.77, 0, statusMaterial);
makeBox(group, 0.15, 0.15, 0.72, 0xffffff, 0, 1.77, 0, statusMaterial);
pickables.push(group);
demandVisuals.set(demand.id, { group, statusMaterial });
}
function createCandidateVisual(candidate) {
const group = new THREE.Group();
group.position.set(candidate.x, 0, candidate.z);
group.userData.pick = { kind: "backup", id: candidate.id };
scene.add(group);
const fillMaterial = new THREE.MeshBasicMaterial({
color: 0xffc857,
transparent: true,
opacity: 0.12,
depthWrite: false
});
const edgeMaterial = new THREE.MeshBasicMaterial({
color: 0xffc857,
transparent: true,
opacity: 0.55
});
const fill = makeBox(group, 2.15, 0.025, 2.15, 0xffffff, 0, 0.11, 0, fillMaterial);
fill.castShadow = false;
fill.receiveShadow = false;
const corners = [
[-0.95, -0.95],
[0.95, -0.95],
[0.95, 0.95],
[-0.95, 0.95]
];
for (const [x, z] of corners) {
makeBox(group, 0.38, 0.28, 0.16, 0xffffff, x, 0.23, z, edgeMaterial);
makeBox(group, 0.16, 0.28, 0.38, 0xffffff, x, 0.23, z, edgeMaterial);
}
makeBox(group, 0.7, 0.08, 0.18, 0xffffff, 0, 0.18, 0, edgeMaterial);
makeBox(group, 0.18, 0.08, 0.7, 0xffffff, 0, 0.18, 0, edgeMaterial);
const label = createLabel(
"candidate",
new THREE.Vector3(candidate.x, 1.1, candidate.z),
candidate.name.toUpperCase()
);
pickables.push(group);
candidateVisuals.set(candidate.id, {
group,
fillMaterial,
edgeMaterial,
label
});
}
function buildRouteNodes() {
const facilityCoordinates = new Set(
facilities.map((facility) => `${facility.x},${facility.z}`)
);
const nodeMaterial = new THREE.MeshBasicMaterial({
color: 0xffc857,
transparent: true,
opacity: 0.8
});
for (const x of ROAD_X) {
for (const z of ROAD_Z) {
if (facilityCoordinates.has(`${x},${z}`)) continue;
const node = makeBox(
routeNodesGroup,
0.32,
0.14,
0.32,
0xffffff,
x,
0.15,
z,
nodeMaterial
);
node.userData.pick = { kind: "junction", x, z };
pickables.push(node);
}
}
routeNodesGroup.visible = false;
}
function buildBrokenUplink() {
const group = new THREE.Group();
scene.add(group);
for (let i = 0; i < 4; i++) {
makeBox(
group,
0.32,
0.24,
0.32,
0xff666d,
-5.35 + i * 0.56,
0.36,
-3
);
}
makeBox(group, 0.16, 1.1, 0.16, 0x6d7780, -3.15, 0.55, -3);
makeBox(group, 0.8, 0.12, 0.12, 0xff666d, -3.55, 1.05, -3);
group.name = "broken-uplink";
return group;
}
const brokenUplink = buildBrokenUplink();
function clearCoverage() {
for (const child of [...coverageGroup.children]) {
coverageGroup.remove(child);
if (child.geometry) child.geometry.dispose();
if (child.material) child.material.dispose();
}
}
function rebuildCoverage() {
clearCoverage();
for (const facility of allFacilities()) {
const tiles = [];
const minX = Math.floor(facility.x - facility.radius);
const maxX = Math.ceil(facility.x + facility.radius);
const minZ = Math.floor(facility.z - facility.radius);
const maxZ = Math.ceil(facility.z + facility.radius);
for (let x = minX; x <= maxX; x++) {
for (let z = minZ; z <= maxZ; z++) {
if (distance2D({ x, z }, facility) <= facility.radius + 0.08) {
tiles.push({ x, z });
}
}
}
if (!tiles.length) continue;
const tileGeometry = new THREE.BoxGeometry(0.91, 0.035, 0.91);
const tileMaterial = new THREE.MeshBasicMaterial({
color: facility.color,
transparent: true,
opacity: facility.online ? 0.13 : 0.045,
depthWrite: false
});
const mesh = new THREE.InstancedMesh(
tileGeometry,
tileMaterial,
tiles.length
);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.frustumCulled = false;
const matrix = new THREE.Matrix4();
tiles.forEach((tile, index) => {
matrix.makeTranslation(tile.x, 0.09, tile.z);
mesh.setMatrixAt(index, matrix);
});
mesh.instanceMatrix.needsUpdate = true;
coverageGroup.add(mesh);
}
}
function computeAccess() {
const active = activeFacilities();
const results = demands.map((demand) => {
const serving = active.filter(
(facility) => distance2D(demand, facility) <= facility.radius + 0.02
);
return {
...demand,
served: serving.length > 0,
serving
};
});
return {
results,
served: results.filter((result) => result.served).length,
stranded: results.filter((result) => !result.served).length
};
}
function updateFacilityVisuals() {
for (const facility of allFacilities()) {
const visual = facilityVisuals.get(facility.id);
if (!visual) continue;
const active = facility.online;
const statusColor = active
? facility.backup
? 0xffc857
: 0x5be5ad
: 0xff666d;
visual.statusMaterial.color.setHex(statusColor);
visual.statusMaterial.emissive.setHex(statusColor);
visual.ringMaterial.color.setHex(statusColor);
visual.label.element.className =
"map-label " +
(facility.backup ? "backup" : active ? "online" : "down");
const statusText = facility.backup
? "BACKUP ONLINE"
: active
? "ONLINE"
: "UPLINK DOWN";
visual.label.element.textContent = `${facility.short} · ${statusText}`;
}
brokenUplink.visible = !facilities[0].online;
}
function updateDemandVisuals(access) {
for (const result of access.results) {
const visual = demandVisuals.get(result.id);
const color = result.served ? 0x5be5ad : 0xff666d;
visual.statusMaterial.color.setHex(color);
visual.statusMaterial.emissive.setHex(color);
}
}
function updateCandidateStyles() {
for (const candidate of candidates) {
const visual = candidateVisuals.get(candidate.id);
const selected = state.selectedBackup === candidate.id;
const inMode = state.mode === "backup" && !state.actionTaken;
visual.edgeMaterial.opacity = inMode
? selected
? 1
: 0.62
: 0.27;
visual.fillMaterial.opacity = inMode
? selected
? 0.22
: 0.1
: 0.045;
visual.group.scale.setScalar(selected ? 1.06 : 1);
visual.label.element.style.display =
inMode && state.selectedBackup === candidate.id ? "block" : "none";
}
}
function renderLedger(access) {
$("#ledgerList").innerHTML = access.results
.map(
(result) => `
<div class="ledger-row">
<i class="ledger-dot ${result.served ? "" : "offline"}"></i>
<span>${result.name}</span>
<span class="ledger-state ${result.served ? "" : "offline"}">
${result.served ? "REACHABLE" : "STRANDED"}
</span>
</div>
`
)
.join("");
}
function updateUI() {
const access = computeAccess();
const activeCount = activeFacilities().length;
$("#budgetText").textContent = formatMoney(state.remaining);
$("#budgetFill").style.width = `${
((BUDGET_TOTAL - state.remaining) / BUDGET_TOTAL) * 100
}%`;
$("#accessMetric").textContent = `${access.served} / ${demands.length}`;
$("#facilityMetric").textContent = activeCount;
$("#strandedMetric").textContent = access.stranded;
$("#ledgerCount").textContent = `${access.served} / ${demands.length}`;
const metric = $("#accessMetric");
metric.classList.toggle("green", access.served === demands.length);
metric.classList.toggle("red", access.served !== demands.length);
const status = $("#networkStatus");
const statusText = $("#networkStatusText");
if (access.served === demands.length) {
$("#missionEyebrow").textContent = "COVERAGE RESTORED";
$("#missionEyebrow").style.color = "var(--green)";
$("#missionTitle").innerHTML = "All blocks<br />are back online.";
$("#missionTitle").classList.add("success");
$("#missionCopy").textContent =
"Every service block can now reach an active facility. The district is operating within its fixed construction budget.";
status.classList.add("good");
statusText.textContent =
state.routeBuilt ? "UPLINK RESTORED" : "COVERAGE COMPLETE";
} else if (state.actionTaken) {
$("#missionEyebrow").textContent = "PARTIAL RECOVERY";
$("#missionEyebrow").style.color = "var(--amber)";
$("#missionTitle").innerHTML = "A gap still<br />remains.";
$("#missionTitle").classList.remove("success");
$("#missionCopy").textContent = `${access.stranded} service blocks remain outside all active coverage. Reset the district to choose a different construction action.`;
status.classList.remove("good");
statusText.textContent = "COVERAGE INCOMPLETE";
} else {
$("#missionEyebrow").textContent = "ONE LINK DOWN";
$("#missionEyebrow").style.color = "var(--red)";
$("#missionTitle").innerHTML = "Coverage gap.<br />One move to fix it.";
$("#missionTitle").classList.remove("success");
$("#missionCopy").textContent =
"Civic Clinic lost its uplink. Three nearby service blocks can no longer reach an active facility.";
status.classList.remove("good");
statusText.textContent = "NETWORK DEGRADED";
}
document.querySelectorAll(".action-tab").forEach((button) => {
button.classList.toggle("active", button.dataset.mode === state.mode);
button.disabled = state.actionTaken;
});
document.querySelectorAll(".candidate-card").forEach((button) => {
button.disabled = state.actionTaken || button.dataset.cost > state.remaining;
button.classList.toggle(
"selected",
button.dataset.candidate === state.selectedBackup
);
});
$("#backupPane").hidden = state.mode !== "backup";
$("#routePane").hidden = state.mode !== "route";
const routeCost = getRouteCost();
$("#routeCost").textContent = formatMoney(routeCost);
$("#modeAction").hidden = state.mode !== "route";
$("#modeText").textContent = getModeText();
routeNodesGroup.visible = state.mode === "route" && !state.actionTaken;
renderLedger(access);
updateCandidateStyles();
}
function getRouteCost() {
return Math.max(0, state.route.length - 1) * ROUTE_COST_PER_BLOCK;
}
function getModeText() {
if (state.actionTaken) {
return "Construction complete · Reset to try another strategy";
}
if (state.mode === "backup") {
return state.selectedBackup
? "Click the highlighted parcel to build the selected backup site"
: "Select a backup parcel, then click its marker in the city";
}
if (state.mode === "route") {
if (state.route.length === 0) {
return "Start at the red Civic Clinic, then follow amber street junctions";
}
return `Route: ${state.route.length - 1} blocks · Finish at an online hub`;
}
return "Drag to orbit · Scroll to zoom · Click facilities to inspect";
}
function showToast(message, type = "") {
const toast = $("#toast");
toast.textContent = message;
toast.className = `show ${type}`;
clearTimeout(showToast.timer);
showToast.timer = setTimeout(() => {
toast.className = "";
}, 3200);
}
function setMode(mode) {
if (state.actionTaken) return;
state.mode = mode;
updateUI();
}
function placeBackup(candidateId) {
if (state.actionTaken) return;
const candidate = candidates.find((item) => item.id === candidateId);
if (!candidate) return;
if (candidate.cost > state.remaining) {
showToast("This backup site exceeds the remaining construction budget.", "error");
return;
}
state.remaining -= candidate.cost;
state.actionTaken = true;
state.mode = "inspect";
state.activeBackup = {
id: `backup-${candidate.id}`,
name: candidate.name,
short: candidate.name.toUpperCase(),
x: candidate.x,
z: candidate.z,
radius: candidate.radius,
color: 0xffc857,
online: true,
backup: true
};
candidateVisuals.get(candidate.id).group.visible = false;
createFacilityVisual(state.activeBackup);
rebuildRouteVisual();
recomputeAccess();
const access = computeAccess();
if (access.served === demands.length) {
showToast(
`${candidate.name} is online. All ${demands.length} service blocks are reachable.`,
"success"
);
} else {
showToast(
`${candidate.name} is online, but ${access.stranded} blocks remain outside its coverage.`,
"error"
);
}
}
function isAdjacent(a, b) {
const dx = Math.abs(a.x - b.x);
const dz = Math.abs(a.z - b.z);
return (dx === 3 && dz === 0) || (dx === 0 && dz === 3);
}
function routeNodeByCoordinate(x, z) {
return { x, z, kind: "junction" };
}
function routeFacilityById(id) {
const facility = facilities.find((item) => item.id === id);
return {
x: facility.x,
z: facility.z,
kind: "facility",
id: facility.id
};
}
function tryRoutePick(pick) {
if (state.actionTaken) return;
if (pick.kind === "facility") {
if (pick.id === "civic") {
if (state.route.length === 0) {
state.route = [routeFacilityById("civic")];
} else if (state.route.length === 1) {
state.route = [routeFacilityById("civic")];
} else {
showToast("Clear the current route before restarting at Civic Clinic.");
}
rebuildRouteVisual();
updateUI();
return;
}
const facility = facilities.find((item) => item.id === pick.id);
if (!facility.online) {
showToast("That facility is not online.", "error");
return;
}
if (state.route.length === 0) {
showToast("Start the route at the red Civic Clinic.");
return;
}
const endpoint = routeFacilityById(facility.id);
const last = state.route[state.route.length - 1];
if (!isAdjacent(last, endpoint)) {
showToast("Routes must continue through the adjacent street junction.");
return;
}
const candidateRoute = [...state.route, endpoint];
const candidateCost =
(candidateRoute.length - 1) * ROUTE_COST_PER_BLOCK;
if (candidateCost > state.remaining) {
showToast("That route exceeds the remaining construction budget.", "error");
return;
}
state.route = candidateRoute;
completeRoute();
return;
}
if (pick.kind === "junction") {
if (state.route.length === 0) {
showToast("Start at the red Civic Clinic before choosing junctions.");
return;
}
const node = routeNodeByCoordinate(pick.x, pick.z);
const last = state.route[state.route.length - 1];
if (last.x === node.x && last.z === node.z) return;
if (!isAdjacent(last, node)) {
showToast("Choose the next amber junction one street block away.");
return;
}
const candidateRoute = [...state.route, node];
const candidateCost =
(candidateRoute.length - 1) * ROUTE_COST_PER_BLOCK;
if (candidateCost > state.remaining) {
showToast("That route exceeds the remaining construction budget.", "error");
return;
}
state.route = candidateRoute;
rebuildRouteVisual();
updateUI();
}
}
function completeRoute() {
const cost = getRouteCost();
state.remaining -= cost;
state.actionTaken = true;
state.routeBuilt = true;
state.mode = "inspect";
facilities[0].online = true;
rebuildRouteVisual();
recomputeAccess();
const access = computeAccess();
if (access.served === demands.length) {
showToast(
`Uplink restored for $${Math.round(cost / 1000)}K. All service blocks are reachable.`,
"success"
);
} else {
showToast(
`The uplink is restored, but ${access.stranded} service blocks remain stranded.`,
"error"
);
}
}
function clearRoute() {
if (state.actionTaken) return;
state.route = [];
rebuildRouteVisual();
updateUI();
}
function rebuildRouteVisual() {
routeGroup.clear();
if (state.route.length < 2) return;
const routeMaterial = new THREE.MeshStandardMaterial({
color: state.routeBuilt ? 0x5be5ad : 0xffc857,
emissive: state.routeBuilt ? 0x27bd85 : 0xff9f19,
emissiveIntensity: 0.65,
roughness: 0.7
});
for (let index = 0; index < state.route.length - 1; index++) {
const a = state.route[index];
const b = state.route[index + 1];
const centerX = (a.x + b.x) / 2;
const centerZ = (a.z + b.z) / 2;
const sameX = a.x === b.x;
makeBox(
routeGroup,
sameX ? 0.22 : 3.0,
0.09,
sameX ? 3.0 : 0.22,
0xffffff,
centerX,
0.19,
centerZ,
routeMaterial
);
}
}
function recomputeAccess() {
rebuildCoverage();
updateFacilityVisuals();
const access = computeAccess();
updateDemandVisuals(access);
updateUI();
return access;
}
function resetGame() {
if (state.activeBackup) {
const visual = facilityVisuals.get(state.activeBackup.id);
if (visual) {
scene.remove(visual.group);
visual.label.element.remove();
const labelIndex = labelItems.indexOf(visual.label);
if (labelIndex >= 0) labelItems.splice(labelIndex, 1);
}
}
state.mode = "backup";
state.actionTaken = false;
state.remaining = BUDGET_TOTAL;
state.selectedBackup = null;
state.activeBackup = null;
state.route = [];
state.routeBuilt = false;
facilities[0].online = false;
for (const candidate of candidates) {
candidateVisuals.get(candidate.id).group.visible = true;
}
rebuildRouteVisual();
recomputeAccess();
showToast("District reset. Choose a backup site or plan a repair route.");
}
// ---------------------------------------------------------------------
// UI events
// ---------------------------------------------------------------------
$("#candidateList").innerHTML = candidates
.map(
(candidate) => `
<button
class="candidate-card"
data-candidate="${candidate.id}"
data-cost="${candidate.cost}"
>
<span class="candidate-name">${candidate.name}</span>
<span class="candidate-cost">${formatMoney(candidate.cost)}</span>
<span class="candidate-detail">
${candidate.radius.toFixed(1)} tile radius · fixed-site coverage
</span>
</button>
`
)
.join("");
$("#candidateList").addEventListener("click", (event) => {
const button = event.target.closest("[data-candidate]");
if (!button || state.actionTaken) return;
state.selectedBackup = button.dataset.candidate;
state.mode = "backup";
updateUI();
});
document.querySelectorAll(".action-tab").forEach((button) => {
button.addEventListener("click", () => setMode(button.dataset.mode));
});
$("#clearRoute").addEventListener("click", clearRoute);
$("#modeAction").addEventListener("click", clearRoute);
$("#resetButton").addEventListener("click", resetGame);
// ---------------------------------------------------------------------
// Picking and custom camera controls
// ---------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function visibleInHierarchy(object) {
let current = object;
while (current) {
if (!current.visible) return false;
current = current.parent;
}
return true;
}
function pickAt(clientX, clientY) {
const rect = canvas.getBoundingClientRect();
pointer.x = ((clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(pickables, true);
for (const intersection of intersections) {
let object = intersection.object;
if (!visibleInHierarchy(object)) continue;
while (object && !object.userData.pick) {
object = object.parent;
}
if (!object || !object.userData.pick) continue;
const pick = object.userData.pick;
if (pick.kind === "backup" && state.mode !== "backup") continue;
if (pick.kind === "junction" && state.mode !== "route") continue;
return pick;
}
return null;
}
function handleClick(pick) {
if (!pick) return;
if (state.mode === "route") {
tryRoutePick(pick);
return;
}
if (pick.kind === "backup") {
if (state.mode === "backup") {
placeBackup(pick.id);
}
return;
}
if (pick.kind === "facility") {
const facility = allFacilities().find((item) => item.id === pick.id);
if (facility) {
showToast(
`${facility.name}: ${
facility.online ? "online" : "uplink down"
}. Coverage radius ${facility.radius.toFixed(1)} tiles.`
);
}
return;
}
if (pick.kind === "demand") {
const demand = demands.find((item) => item.id === pick.id);
const access = computeAccess();
const result = access.results.find((item) => item.id === pick.id);
if (demand && result) {
showToast(
`${demand.name} is ${
result.served
? `reachable through ${result.serving[0].name}`
: "stranded with no active coverage"
}.`
);
}
}
}
function updateCamera() {
const radius = 32;
const horizontal = Math.cos(controls.polar) * radius;
camera.position.set(
controls.target.x + Math.sin(controls.azimuth) * horizontal,
controls.target.y + Math.sin(controls.polar) * radius,
controls.target.z + Math.cos(controls.azimuth) * horizontal
);
camera.lookAt(controls.target);
camera.zoom = controls.zoom;
camera.updateProjectionMatrix();
camera.updateMatrixWorld();
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
const viewSize = 19;
camera.left = -viewSize * aspect;
camera.right = viewSize * aspect;
camera.top = viewSize;
camera.bottom = -viewSize;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", resize);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
controls.dragging = true;
controls.moved = false;
controls.pointerId = event.pointerId;
controls.lastX = event.clientX;
controls.lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
canvas.classList.add("dragging");
});
canvas.addEventListener("pointermove", (event) => {
if (!controls.dragging || event.pointerId !== controls.pointerId) return;
const dx = event.clientX - controls.lastX;
const dy = event.clientY - controls.lastY;
controls.lastX = event.clientX;
controls.lastY = event.clientY;
if (Math.abs(dx) + Math.abs(dy) > 1) controls.moved = true;
if (event.button === 2 || event.shiftKey) {
camera.updateMatrixWorld();
const right = new THREE.Vector3()
.setFromMatrixColumn(camera.matrix, 0)
.setY(0)
.normalize();
const forward = new THREE.Vector3()
.subVectors(controls.target, camera.position)
.setY(0)
.normalize();
const scale = 0.025 / controls.zoom;
controls.target.addScaledVector(right, -dx * scale);
controls.target.addScaledVector(forward, -dy * scale);
} else {
controls.azimuth -= dx * 0.006;
controls.polar = THREE.MathUtils.clamp(
controls.polar + dy * 0.0045,
0.48,
1.24
);
}
updateCamera();
});
canvas.addEventListener("pointerup", (event) => {
if (!controls.dragging || event.pointerId !== controls.pointerId) return;
controls.dragging = false;
canvas.releasePointerCapture(event.pointerId);
canvas.classList.remove("dragging");
if (!controls.moved) {
const pick = pickAt(event.clientX, event.clientY);
handleClick(pick);
}
controls.pointerId = null;
});
canvas.addEventListener("pointercancel", (event) => {
controls.dragging = false;
controls.pointerId = null;
canvas.classList.remove("dragging");
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
controls.zoom = THREE.MathUtils.clamp(
controls.zoom * (event.deltaY > 0 ? 0.9 : 1.1),
0.65,
1.75
);
updateCamera();
},
{ passive: false }
);
// ---------------------------------------------------------------------
// Build scene and start
// ---------------------------------------------------------------------
buildCity();
for (const facility of facilities) createFacilityVisual(facility);
for (const demand of demands) createDemandVisual(demand);
for (const candidate of candidates) createCandidateVisual(candidate);
buildRouteNodes();
resize();
updateCamera();
recomputeAccess();
const projected = new THREE.Vector3();
function updateLabels() {
const width = window.innerWidth;
const height = window.innerHeight;
for (const item of labelItems) {
projected.copy(item.position).project(camera);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.12 &&
projected.x < 1.12 &&
projected.y > -1.12 &&
projected.y < 1.12;
item.element.style.display = visible ? "block" : "none";
if (!visible) continue;
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
item.element.style.left = `${x}px`;
item.element.style.top = `${y}px`;
}
}
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
for (const visual of facilityVisuals.values()) {
visual.beacon.position.y = 3.15 + Math.sin(elapsed * 2.3) * 0.09;
visual.beacon.rotation.y = elapsed * 0.32;
}
for (const visual of demandVisuals.values()) {
visual.statusMaterial.emissiveIntensity =
0.33 + Math.sin(elapsed * 3.2) * 0.11;
}
if (state.mode === "route" && !state.actionTaken) {
routeNodesGroup.children.forEach((node, index) => {
const scale = 1 + Math.sin(elapsed * 3 + index * 0.45) * 0.13;
node.scale.setScalar(scale);
});
}
updateLabels();
renderer.render(scene, camera);
}
animate();
requestAnimationFrame(() => {
$("#loading").classList.add("hidden");
});
</script>
</body>
</html>
```