Prompt specification
Build or customize the Three.js 3D scene "Restore a fictional service network after damage" 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: Restore a fictional service network after damage
Category: Art & Culture · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/restore-a-fictional-service-network-after-damage-x2468
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing the 1906 San Francisco earthquake and recovery. Let users reconnect a simplified water-and-road network inspired by the event. Show which neighborhoods regain access while clearly labeling the scenario as an educational model. Low-poly.
Acceptance checks: Use a single complete, fictional node and edge registry for the 3D view and both service networks. Verify every endpoint, use reachability from a named abstract source, and visibly change the service status after a repair. Any historic context should be concise and distinguish it from the fictional layout.
Return a single complete HTML document. It must work in a sandbox that allows scripts, with the cdnjs Three.js r160 module and inline CSS. Use procedural geometry and local button handlers; no native form submission, pointer lock, remote assets, or runtime network requests besides Three.js.
Working Three.js Starter (restore-a-fictional-service-network-after-damage-x2468):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark">
<link rel="icon" href="data:,">
<title>1906 San Francisco — Earthquake & Recovery Educational Model</title>
<style>
:root {
--bg: #071b1f;
--panel: #10292e;
--panel-2: #16363b;
--panel-3: #1b4146;
--line: #2c5056;
--text: #f4f1e6;
--muted: #9db2b4;
--cyan: #55d5e4;
--green: #65d98c;
--red: #ff665b;
--amber: #f4c65d;
--paper: #e8e0c8;
--shadow: 0 18px 50px rgba(0, 0, 0, .24);
}
* { box-sizing: border-box; }
html, body {
margin: 0;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
body { overflow: hidden; }
button, input, select { font: inherit; }
button {
color: inherit;
cursor: pointer;
}
button:focus-visible,
canvas:focus-visible,
summary:focus-visible {
outline: 3px solid var(--cyan);
outline-offset: 2px;
}
#app {
height: 100vh;
height: 100dvh;
display: flex;
flex-direction: column;
}
.topbar {
min-height: 72px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 12px 20px;
border-bottom: 1px solid var(--line);
background:
linear-gradient(110deg, rgba(255, 102, 91, .10), transparent 34%),
#0b2328;
z-index: 20;
}
.brand {
min-width: 0;
display: flex;
align-items: center;
gap: 13px;
}
.brand-mark {
width: 39px;
height: 39px;
flex: 0 0 auto;
background: var(--red);
clip-path: polygon(50% 0, 100% 27%, 82% 100%, 18% 100%, 0 27%);
box-shadow: 0 0 24px rgba(255, 102, 91, .25);
position: relative;
}
.brand-mark::after {
content: "";
position: absolute;
width: 3px;
height: 25px;
left: 18px;
top: 7px;
background: #ffe8c5;
transform: rotate(15deg);
clip-path: polygon(0 0, 100% 7%, 62% 45%, 100% 70%, 48% 50%, 0 100%);
}
.brand h1 {
margin: 0;
font-size: clamp(17px, 2vw, 24px);
line-height: 1.05;
letter-spacing: -.02em;
white-space: nowrap;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: .11em;
text-transform: uppercase;
}
.top-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
flex-wrap: wrap;
}
.badge {
display: inline-flex;
align-items: center;
gap: 6px;
min-height: 28px;
padding: 5px 9px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(255, 255, 255, .035);
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: .07em;
text-transform: uppercase;
white-space: nowrap;
}
.badge.education {
color: #ffe3a7;
border-color: rgba(244, 198, 93, .42);
background: rgba(244, 198, 93, .09);
}
.badge.verified {
color: #a6f0be;
border-color: rgba(101, 217, 140, .35);
background: rgba(101, 217, 140, .08);
}
main {
flex: 1;
min-height: 0;
display: grid;
grid-template-columns: 294px minmax(360px, 1fr) 326px;
grid-template-areas: "left view right";
}
.sidebar {
min-height: 0;
overflow-y: auto;
padding: 13px;
background:
linear-gradient(180deg, rgba(255, 255, 255, .018), transparent 30%),
#091f24;
scrollbar-width: thin;
scrollbar-color: var(--line) transparent;
}
.sidebar.left { grid-area: left; border-right: 1px solid var(--line); }
.sidebar.right { grid-area: right; border-left: 1px solid var(--line); }
.card {
margin-bottom: 11px;
padding: 14px;
border: 1px solid var(--line);
border-radius: 13px;
background: linear-gradient(145deg, rgba(255, 255, 255, .025), transparent), var(--panel);
box-shadow: var(--shadow);
}
.eyebrow {
margin: 0 0 7px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: .14em;
text-transform: uppercase;
}
.card h2,
.card h3 {
margin: 0;
line-height: 1.16;
letter-spacing: -.015em;
}
.card h2 { font-size: 20px; }
.card h3 { font-size: 15px; }
.card-copy {
margin: 9px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.history-grid {
display: grid;
gap: 8px;
margin-top: 12px;
}
.history-row {
padding: 9px 10px;
border-left: 3px solid var(--line);
border-radius: 0 7px 7px 0;
background: rgba(255, 255, 255, .025);
}
.history-row.historical { border-left-color: var(--amber); }
.history-row.model { border-left-color: var(--cyan); }
.history-row strong {
display: block;
margin-bottom: 3px;
color: var(--text);
font-size: 10px;
letter-spacing: .08em;
text-transform: uppercase;
}
.history-row p {
margin: 0;
color: var(--muted);
font-size: 11px;
line-height: 1.42;
}
.button-row {
display: grid;
gap: 8px;
margin-top: 11px;
}
.control-button {
width: 100%;
min-height: 39px;
padding: 9px 12px;
border: 1px solid var(--line);
border-radius: 9px;
background: var(--panel-2);
font-size: 12px;
font-weight: 750;
transition: transform .15s ease, background .15s ease, border-color .15s ease;
}
.control-button:hover:not(:disabled) {
transform: translateY(-1px);
background: var(--panel-3);
border-color: #4b7378;
}
.control-button.primary {
color: #092027;
border-color: #80e6b0;
background: var(--green);
}
.control-button.primary:hover:not(:disabled) { background: #7be6a1; }
.control-button.quake {
color: #ffe5df;
border-color: rgba(255, 102, 91, .42);
background: rgba(255, 102, 91, .10);
}
.control-button:disabled {
cursor: not-allowed;
opacity: .42;
}
.selection-box {
margin-top: 11px;
padding: 11px;
border: 1px solid var(--line);
border-radius: 9px;
background: #0b2227;
}
.selection-kind {
display: block;
margin-bottom: 4px;
color: var(--cyan);
font-size: 9px;
font-weight: 800;
letter-spacing: .12em;
text-transform: uppercase;
}
.selection-box strong {
display: block;
font-size: 13px;
}
.selection-box p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
}
.count-badge {
min-width: 24px;
padding: 3px 7px;
border-radius: 999px;
color: #ffd8d3;
background: rgba(255, 102, 91, .16);
font-size: 10px;
font-weight: 800;
text-align: center;
}
.edge-list {
display: grid;
gap: 7px;
max-height: 255px;
overflow-y: auto;
padding-right: 3px;
scrollbar-width: thin;
scrollbar-color: var(--line) transparent;
}
.edge-item {
width: 100%;
display: grid;
grid-template-columns: 9px 1fr;
gap: 9px;
align-items: start;
padding: 9px;
border: 1px solid #29494f;
border-radius: 8px;
background: rgba(255, 255, 255, .018);
text-align: left;
transition: border-color .15s ease, background .15s ease, transform .15s ease;
}
.edge-item:hover,
.edge-item.selected {
border-color: var(--amber);
background: rgba(244, 198, 93, .08);
transform: translateX(2px);
}
.edge-mode-dot {
width: 8px;
height: 8px;
margin-top: 4px;
border-radius: 50%;
background: var(--red);
box-shadow: 0 0 0 3px rgba(255, 102, 91, .10);
}
.edge-item.road .edge-mode-dot { background: #ff8a72; }
.edge-item.water .edge-mode-dot { background: #4bc9e3; }
.edge-item strong {
display: block;
font-size: 11px;
line-height: 1.2;
}
.edge-item small {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 9.5px;
line-height: 1.35;
}
.all-clear {
padding: 13px 10px;
border: 1px dashed rgba(101, 217, 140, .45);
border-radius: 8px;
color: #a8efc0;
background: rgba(101, 217, 140, .06);
font-size: 11px;
line-height: 1.4;
}
.legend {
display: grid;
gap: 8px;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
color: var(--muted);
font-size: 11px;
}
.swatch {
width: 23px;
height: 4px;
flex: 0 0 auto;
border-radius: 999px;
background: var(--red);
}
.swatch.road { height: 6px; background: var(--green); }
.swatch.water { height: 4px; background: var(--cyan); }
.swatch.waiting { background: var(--amber); }
.swatch.isolated { width: 10px; height: 10px; border-radius: 50%; background: #718184; }
#viewport {
grid-area: view;
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background: #b9d0d0;
isolation: isolate;
}
#scene {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#labelLayer {
position: absolute;
inset: 0;
overflow: hidden;
pointer-events: none;
z-index: 4;
}
.map-label {
position: absolute;
min-width: 92px;
padding: 6px 8px;
border: 1px solid rgba(22, 55, 60, .26);
border-radius: 7px;
color: #17343a;
background: rgba(250, 247, 235, .91);
box-shadow: 0 5px 14px rgba(22, 48, 51, .16);
transform: translate(-50%, -100%);
text-align: center;
will-change: left, top;
}
.map-label.source {
color: #55370b;
border-color: rgba(133, 88, 17, .45);
background: rgba(255, 236, 182, .94);
}
.map-label .label-name {
display: block;
font-size: 10px;
font-weight: 850;
line-height: 1.1;
white-space: nowrap;
}
.map-label .label-sub {
display: block;
margin-top: 3px;
color: #557076;
font-size: 7px;
font-weight: 800;
letter-spacing: .08em;
text-transform: uppercase;
}
.label-status {
display: flex;
justify-content: center;
gap: 8px;
margin-top: 4px;
}
.label-status span {
display: inline-flex;
align-items: center;
gap: 3px;
color: #60777a;
font-size: 7px;
font-weight: 800;
letter-spacing: .05em;
}
.label-status i {
width: 6px;
height: 6px;
border-radius: 50%;
background: #77898b;
}
.label-status .road.on i { background: #26a65b; }
.label-status .water.on i { background: #139eb7; }
.map-label.gained {
animation: label-gain 1.1s ease both;
}
@keyframes label-gain {
0% { transform: translate(-50%, -100%) scale(1); box-shadow: 0 0 0 0 rgba(101, 217, 140, .7); }
35% { transform: translate(-50%, -100%) scale(1.12); box-shadow: 0 0 0 9px rgba(101, 217, 140, 0); }
100% { transform: translate(-50%, -100%) scale(1); }
}
.viewport-caption {
position: absolute;
z-index: 5;
top: 14px;
left: 14px;
max-width: 310px;
padding: 10px 12px;
border: 1px solid rgba(24, 61, 65, .2);
border-radius: 9px;
color: #17363b;
background: rgba(246, 244, 231, .82);
box-shadow: 0 8px 25px rgba(21, 50, 52, .11);
backdrop-filter: blur(8px);
pointer-events: none;
}
.viewport-caption strong {
display: block;
font-size: 10px;
letter-spacing: .11em;
text-transform: uppercase;
}
.viewport-caption span {
display: block;
margin-top: 4px;
color: #567176;
font-size: 10px;
line-height: 1.35;
}
.scene-legend {
position: absolute;
z-index: 5;
left: 14px;
bottom: 14px;
display: flex;
flex-wrap: wrap;
gap: 10px;
max-width: calc(100% - 78px);
padding: 8px 10px;
border: 1px solid rgba(24, 61, 65, .18);
border-radius: 8px;
color: #294c51;
background: rgba(246, 244, 231, .84);
font-size: 9px;
font-weight: 700;
backdrop-filter: blur(7px);
pointer-events: none;
}
.scene-legend span {
display: inline-flex;
align-items: center;
gap: 5px;
white-space: nowrap;
}
.scene-legend i {
width: 13px;
height: 4px;
border-radius: 999px;
background: var(--red);
}
.scene-legend .road-dot { height: 6px; background: var(--green); }
.scene-legend .water-dot { background: var(--cyan); }
.scene-legend .wait-dot { background: var(--amber); }
#homeView {
position: absolute;
z-index: 6;
right: 14px;
bottom: 14px;
width: 43px;
height: 43px;
border: 1px solid rgba(24, 61, 65, .25);
border-radius: 10px;
color: #17363b;
background: rgba(246, 244, 231, .88);
box-shadow: 0 8px 20px rgba(22, 49, 51, .14);
font-size: 19px;
}
#quakeWash {
position: absolute;
inset: 0;
z-index: 3;
pointer-events: none;
opacity: 0;
background:
radial-gradient(circle at 50% 45%, rgba(255, 222, 172, .10), transparent 42%),
linear-gradient(105deg, rgba(255, 62, 43, .26), rgba(255, 167, 83, .10), rgba(255, 62, 43, .18));
mix-blend-mode: multiply;
}
#quakeBanner {
position: absolute;
z-index: 8;
top: 17px;
left: 50%;
padding: 8px 12px;
border: 1px solid rgba(255, 222, 195, .45);
border-radius: 8px;
color: #fff1e8;
background: rgba(115, 31, 24, .84);
box-shadow: 0 8px 25px rgba(63, 17, 12, .24);
transform: translate(-50%, -150%);
opacity: 0;
font-size: 10px;
font-weight: 850;
letter-spacing: .13em;
text-transform: uppercase;
transition: transform .25s ease, opacity .25s ease;
pointer-events: none;
}
#quakeBanner.show {
transform: translate(-50%, 0);
opacity: 1;
}
#toast {
position: absolute;
z-index: 12;
top: 70px;
left: 50%;
width: min(430px, calc(100% - 30px));
padding: 12px 14px;
border: 1px solid rgba(112, 233, 165, .55);
border-radius: 10px;
color: var(--text);
background: rgba(9, 42, 38, .94);
box-shadow: 0 16px 40px rgba(0, 0, 0, .3);
transform: translate(-50%, -18px);
opacity: 0;
transition: opacity .2s ease, transform .2s ease;
pointer-events: none;
}
#toast.show {
transform: translate(-50%, 0);
opacity: 1;
}
#toast strong {
display: block;
color: #9df1ba;
font-size: 12px;
}
#toast p {
margin: 4px 0 0;
color: #c1d5d2;
font-size: 11px;
line-height: 1.4;
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.metric {
min-width: 0;
padding: 10px 8px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, .02);
text-align: center;
}
.metric span {
display: block;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: .08em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 4px;
font-size: 20px;
line-height: 1;
}
.metric.road strong { color: var(--green); }
.metric.water strong { color: var(--cyan); }
.metric.repaired strong { color: var(--amber); }
.progress-track {
height: 7px;
margin-top: 13px;
overflow: hidden;
border-radius: 999px;
background: #071b1f;
}
#recoveryFill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--amber), var(--green));
transition: width .45s ease;
}
.progress-copy {
display: flex;
justify-content: space-between;
gap: 10px;
margin-top: 7px;
color: var(--muted);
font-size: 9px;
}
.phase-track {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 4px;
margin-top: 13px;
}
.phase {
padding-top: 6px;
border-top: 3px solid #29494f;
color: #6f898c;
font-size: 8px;
font-weight: 800;
letter-spacing: .05em;
text-align: center;
text-transform: uppercase;
}
.phase.done { border-top-color: var(--amber); color: #f7d889; }
.phase.active { border-top-color: var(--green); color: #a6efc0; }
.table-wrap { overflow-x: auto; }
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
}
th, td {
padding: 8px 5px;
border-bottom: 1px solid rgba(44, 80, 86, .72);
text-align: left;
vertical-align: middle;
}
thead th {
color: var(--muted);
font-size: 8px;
letter-spacing: .07em;
text-transform: uppercase;
}
tbody th {
color: var(--text);
font-weight: 720;
}
tbody tr:last-child th,
tbody tr:last-child td { border-bottom: 0; }
.status-pill {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 61px;
padding: 4px 5px;
border: 1px solid #40575b;
border-radius: 999px;
color: #92a4a6;
background: rgba(255, 255, 255, .025);
font-size: 8px;
font-weight: 800;
white-space: nowrap;
}
.status-pill.good {
color: #a7efc0;
border-color: rgba(101, 217, 140, .38);
background: rgba(101, 217, 140, .09);
}
tbody tr.gained {
animation: row-gain 1.15s ease both;
}
@keyframes row-gain {
0% { background: rgba(101, 217, 140, .28); }
100% { background: transparent; }
}
.restored-note {
margin-top: 10px;
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 8px;
color: var(--muted);
background: rgba(255, 255, 255, .018);
font-size: 10px;
line-height: 1.4;
}
.restored-note strong {
display: block;
margin-bottom: 3px;
color: #a9efc0;
font-size: 9px;
letter-spacing: .07em;
text-transform: uppercase;
}
.activity-list {
display: grid;
gap: 10px;
max-height: 255px;
margin: 0;
padding: 0;
overflow-y: auto;
list-style: none;
scrollbar-width: thin;
scrollbar-color: var(--line) transparent;
}
.activity-list li {
display: grid;
grid-template-columns: 8px 1fr;
gap: 9px;
align-items: start;
}
.activity-dot {
width: 7px;
height: 7px;
margin-top: 4px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 3px rgba(85, 213, 228, .08);
}
.activity-dot.repair { background: var(--green); }
.activity-dot.access { background: var(--amber); }
.activity-dot.reset { background: var(--red); }
.activity-list strong {
display: block;
font-size: 10px;
}
.activity-list p {
margin: 3px 0 0;
color: var(--muted);
font-size: 9.5px;
line-height: 1.4;
}
details.card {
padding: 0;
overflow: hidden;
}
details summary {
padding: 13px 14px;
cursor: pointer;
font-size: 12px;
font-weight: 800;
list-style-position: inside;
}
.method-body {
padding: 0 14px 14px;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.method-body ol {
margin: 0 0 10px;
padding-left: 18px;
}
.method-body li { margin: 5px 0; }
.audit-box {
padding: 9px;
border: 1px solid var(--line);
border-radius: 7px;
background: #0a2025;
color: #a8efc0;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
line-height: 1.5;
}
#bootMessage {
position: absolute;
z-index: 30;
inset: 0;
display: grid;
place-items: center;
color: #17363b;
background: #b9d0d0;
font-size: 12px;
font-weight: 800;
letter-spacing: .09em;
text-transform: uppercase;
}
.fatal {
position: fixed;
z-index: 100;
inset: 20px;
display: grid;
place-items: center;
padding: 30px;
border: 2px solid var(--red);
border-radius: 16px;
background: #1b2426;
color: #ffe6e2;
text-align: center;
}
@media (max-width: 1120px) {
main { grid-template-columns: 260px minmax(330px, 1fr) 286px; }
.sidebar { padding: 10px; }
.card { padding: 12px; }
.brand p { display: none; }
}
@media (max-width: 850px) {
body { overflow: auto; }
#app { height: auto; min-height: 100dvh; }
.topbar { align-items: flex-start; }
.top-actions .education { display: none; }
main {
display: grid;
grid-template-columns: 1fr;
grid-template-areas: "view" "left" "right";
}
#viewport {
height: 66vh;
min-height: 480px;
border-bottom: 1px solid var(--line);
}
.sidebar {
overflow: visible;
border: 0;
border-bottom: 1px solid var(--line);
}
.edge-list, .activity-list { max-height: none; }
}
@media (max-width: 520px) {
.topbar { padding: 10px 12px; }
.brand-mark { width: 33px; height: 33px; }
.brand h1 { font-size: 16px; white-space: normal; }
.badge.verified { max-width: 145px; overflow: hidden; text-overflow: ellipsis; }
#viewport { height: 58vh; min-height: 410px; }
.viewport-caption { right: 14px; max-width: none; }
.scene-legend { gap: 7px; }
.map-label { transform: translate(-50%, -100%) scale(.9); }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
scroll-behavior: auto !important;
animation-duration: .001ms !important;
animation-iteration-count: 1 !important;
transition-duration: .001ms !important;
}
}
</style>
</head>
<body>
<div id="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>1906 San Francisco: Earthquake & Recovery</h1>
<p>Low-poly network reconnection study</p>
</div>
</div>
<div class="top-actions">
<span class="badge education">Educational model · fictional topology</span>
<span class="badge verified" id="registryBadge">Checking registry</span>
</div>
</header>
<main>
<aside class="sidebar left" aria-label="Scenario controls">
<section class="card">
<p class="eyebrow">Modeled event</p>
<h2>Reconnect an abstract city</h2>
<p class="card-copy">Repair cut links and watch fictional neighborhoods regain road and water access. Every status is recomputed from a named abstract source.</p>
<div class="history-grid">
<div class="history-row historical">
<strong>Historical anchor</strong>
<p>San Francisco’s 18 April 1906 earthquake was followed by widespread fires and major infrastructure damage.</p>
</div>
<div class="history-row model">
<strong>Model boundary</strong>
<p>The wards, links, damage pattern, and restoration rules are fictional. This is not a reconstruction of actual mains, closures, losses, or recovery timing.</p>
</div>
</div>
</section>
<section class="card">
<p class="eyebrow">Recovery controls</p>
<h3>Select a damaged link</h3>
<div class="button-row">
<button class="control-button primary" id="repairBtn" type="button">Repair selected link</button>
<button class="control-button quake" id="quakeBtn" type="button">Replay modeled quake</button>
<button class="control-button" id="resetBtn" type="button">Reset recovery</button>
</div>
<div class="selection-box" aria-live="polite">
<span class="selection-kind" id="selectionKind">No selection</span>
<strong id="selectionTitle">Choose a cut link</strong>
<p id="selectionMeta">Click a red link in the model or use the damaged-link list.</p>
</div>
</section>
<section class="card">
<div class="section-head">
<h3>Damaged links</h3>
<span class="count-badge" id="damagedCount">0</span>
</div>
<div class="edge-list" id="damagedList"></div>
</section>
<section class="card">
<p class="eyebrow">Map key</p>
<div class="legend">
<div class="legend-row"><span class="swatch"></span> Fictional cut / damaged link</div>
<div class="legend-row"><span class="swatch road"></span> Reachable road route</div>
<div class="legend-row"><span class="swatch water"></span> Reachable water main</div>
<div class="legend-row"><span class="swatch waiting"></span> Open, but not connected to source</div>
<div class="legend-row"><span class="swatch isolated"></span> Isolated service marker</div>
</div>
</section>
</aside>
<section id="viewport" aria-label="Interactive low-poly network model">
<canvas id="scene" tabindex="0" aria-label="Three-dimensional fictional San Francisco network. Drag to orbit, scroll to zoom, and click links to select them."></canvas>
<div id="labelLayer" aria-hidden="true"></div>
<div id="quakeWash"></div>
<div id="quakeBanner" role="status">Modeled rupture · fictional damage pattern</div>
<div class="viewport-caption">
<strong>Abstract peninsula · not to scale</strong>
<span>Reachability origin: <b>Cistern Alpha — named abstract source</b>. Drag to orbit, scroll to zoom, and click a red link.</span>
</div>
<div class="scene-legend" aria-hidden="true">
<span><i></i> Cut</span>
<span><i class="road-dot"></i> Road</span>
<span><i class="water-dot"></i> Water</span>
<span><i class="wait-dot"></i> Open / waiting</span>
</div>
<button id="homeView" type="button" title="Reset camera view" aria-label="Reset camera view">⌂</button>
<div id="toast" role="status" aria-live="polite">
<strong id="toastTitle"></strong>
<p id="toastBody"></p>
</div>
<div id="bootMessage">Building abstract network…</div>
</section>
<aside class="sidebar right" aria-label="Service status">
<section class="card">
<div class="section-head">
<div>
<p class="eyebrow">Live model state</p>
<h3>Service reachability</h3>
</div>
<span class="badge" id="modelClock">Recovery model</span>
</div>
<div class="metrics">
<div class="metric road"><span>Road wards</span><strong id="roadMetric">0/6</strong></div>
<div class="metric water"><span>Water wards</span><strong id="waterMetric">0/6</strong></div>
<div class="metric repaired"><span>Links fixed</span><strong id="repairedMetric">0/9</strong></div>
</div>
<div class="progress-track" aria-hidden="true"><div id="recoveryFill"></div></div>
<div class="progress-copy">
<span id="recoveryText">0 of 9 modeled links repaired</span>
<span id="recoveryStage">Isolated</span>
</div>
<div class="phase-track" aria-label="Modeled recovery phases">
<div class="phase done" id="phaseQuake">Quake</div>
<div class="phase done" id="phaseIsolate">Isolate</div>
<div class="phase" id="phaseReconnect">Reconnect</div>
<div class="phase" id="phaseRestore">Restore</div>
</div>
</section>
<section class="card">
<div class="section-head">
<div>
<p class="eyebrow">Fictional neighborhoods</p>
<h3>Who has access?</h3>
</div>
</div>
<div class="table-wrap">
<table aria-label="Road and water service status by fictional neighborhood">
<thead>
<tr>
<th scope="col">Ward</th>
<th scope="col">Road</th>
<th scope="col">Water</th>
</tr>
</thead>
<tbody id="neighborhoodRows"></tbody>
</table>
</div>
<div class="restored-note">
<strong>Most recent access change</strong>
<span id="lastRestored">No repairs yet.</span>
</div>
</section>
<section class="card">
<div class="section-head">
<div>
<p class="eyebrow">Recovery log</p>
<h3>Model events</h3>
</div>
</div>
<ol class="activity-list" id="activityLog" aria-live="polite"></ol>
</section>
<details class="card">
<summary>Model method & registry audit</summary>
<div class="method-body">
<ol>
<li>One fictional registry defines every node, edge endpoint, position, service mode, and initial damage state.</li>
<li>Road and water are separate traversals of that same registry, using only edges with the matching mode.</li>
<li>After every repair, breadth-first reachability starts at <strong>Cistern Alpha</strong>, the named abstract source.</li>
<li>A fictional ward is connected when a valid, repaired route reaches its node. The 3D markers and table use those same results.</li>
</ol>
<div class="audit-box" id="auditText"></div>
</div>
</details>
</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";
const $ = id => document.getElementById(id);
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
// SINGLE COMPLETE FICTIONAL REGISTRY
// The 3D scene, road reachability, water reachability, damaged-link list,
// and neighborhood table all derive from these nodes and edges.
const registry = {
sourceId: "cistern-alpha",
nodes: {
"cistern-alpha": {
kind: "source",
name: "Cistern Alpha",
detail: "Named abstract source for both modeled services",
position: [-5.8, -2.7]
},
"junction-west": {
kind: "junction",
name: "West Junction",
position: [-4.0, -1.1]
},
"junction-north": {
kind: "junction",
name: "North Junction",
position: [-2.6, -3.8]
},
"junction-east": {
kind: "junction",
name: "East Junction",
position: [-0.2, -1.0]
},
"junction-south": {
kind: "junction",
name: "South Junction",
position: [-2.2, 3.1]
},
"junction-harbor": {
kind: "junction",
name: "Harbor Junction",
position: [0.5, 2.5]
},
"ward-beacon": {
kind: "neighborhood",
name: "Beacon Hill Ward",
position: [-4.8, -4.7]
},
"ward-lantern": {
kind: "neighborhood",
name: "Lantern Ward",
position: [0.1, -4.9]
},
"ward-civic": {
kind: "neighborhood",
name: "Civic Ward",
position: [-1.35, -0.15]
},
"ward-orchard": {
kind: "neighborhood",
name: "Orchard Ward",
position: [-5.0, 1.8]
},
"ward-quayside": {
kind: "neighborhood",
name: "Quayside Ward",
position: [2.35, 0.55]
},
"ward-southbank": {
kind: "neighborhood",
name: "Southbank Ward",
position: [-0.7, 4.8]
}
},
edges: [
{ id: "r01", mode: "road", from: "cistern-alpha", to: "junction-west", name: "Alpha Promenade", initialDamaged: false },
{ id: "r02", mode: "road", from: "junction-west", to: "ward-beacon", name: "Beacon Rise", initialDamaged: false },
{ id: "r03", mode: "road", from: "junction-west", to: "ward-orchard", name: "Orchard Cut", initialDamaged: true },
{ id: "r04", mode: "road", from: "ward-beacon", to: "junction-north", name: "North Terrace", initialDamaged: false },
{ id: "r05", mode: "road", from: "junction-north", to: "ward-lantern", name: "Lantern Cut", initialDamaged: true },
{ id: "r06", mode: "road", from: "ward-orchard", to: "ward-civic", name: "Civic Avenue", initialDamaged: false },
{ id: "r07", mode: "road", from: "ward-civic", to: "junction-east", name: "East Crossroad", initialDamaged: true },
{ id: "r08", mode: "road", from: "junction-east", to: "ward-lantern", name: "Lantern Street", initialDamaged: false },
{ id: "r09", mode: "road", from: "junction-east", to: "ward-quayside", name: "Quay Approach", initialDamaged: false },
{ id: "r10", mode: "road", from: "ward-orchard", to: "junction-south", name: "Orchard South", initialDamaged: false },
{ id: "r11", mode: "road", from: "junction-south", to: "ward-southbank", name: "Southbank Cut", initialDamaged: true },
{ id: "r12", mode: "road", from: "junction-south", to: "junction-harbor", name: "Canal Street", initialDamaged: false },
{ id: "r13", mode: "road", from: "junction-harbor", to: "ward-quayside", name: "Harbor Street", initialDamaged: false },
{ id: "r14", mode: "road", from: "ward-quayside", to: "ward-civic", name: "Civic Loop", initialDamaged: false },
{ id: "w01", mode: "water", from: "cistern-alpha", to: "junction-west", name: "Alpha–West Main", initialDamaged: false },
{ id: "w02", mode: "water", from: "junction-west", to: "ward-beacon", name: "Beacon Riser", initialDamaged: false },
{ id: "w03", mode: "water", from: "junction-west", to: "ward-orchard", name: "Orchard Feed", initialDamaged: false },
{ id: "w04", mode: "water", from: "ward-beacon", to: "junction-north", name: "North Standpipe", initialDamaged: false },
{ id: "w05", mode: "water", from: "junction-north", to: "ward-lantern", name: "Lantern Main", initialDamaged: true },
{ id: "w06", mode: "water", from: "ward-orchard", to: "ward-civic", name: "Civic Main", initialDamaged: false },
{ id: "w07", mode: "water", from: "ward-civic", to: "junction-east", name: "East Cross-main", initialDamaged: true },
{ id: "w08", mode: "water", from: "junction-east", to: "ward-quayside", name: "Quay Main", initialDamaged: true },
{ id: "w09", mode: "water", from: "ward-orchard", to: "junction-south", name: "South Feed", initialDamaged: false },
{ id: "w10", mode: "water", from: "junction-south", to: "ward-southbank", name: "Southbank Main", initialDamaged: true },
{ id: "w11", mode: "water", from: "junction-south", to: "junction-harbor", name: "Canal Main", initialDamaged: false },
{ id: "w12", mode: "water", from: "junction-harbor", to: "ward-quayside", name: "Harbor Main", initialDamaged: true },
{ id: "w13", mode: "water", from: "junction-east", to: "ward-lantern", name: "North–East Main", initialDamaged: false },
{ id: "w14", mode: "water", from: "cistern-alpha", to: "ward-civic", name: "Alpha–Civic Main", initialDamaged: false }
]
};
function validateRegistry(reg) {
const errors = [];
const nodeIds = Object.keys(reg.nodes);
const nodeSet = new Set(nodeIds);
const edgeIds = new Set();
const degree = Object.fromEntries(nodeIds.map(id => [id, 0]));
let totalEndpoints = 0;
let validEndpoints = 0;
const modeCounts = { road: 0, water: 0 };
if (!reg.nodes[reg.sourceId] || reg.nodes[reg.sourceId].kind !== "source") {
errors.push("The named source must exist and have kind 'source'.");
}
for (const [id, node] of Object.entries(reg.nodes)) {
if (!node.position || node.position.length !== 2 || !node.position.every(Number.isFinite)) {
errors.push(`Node ${id} has an invalid position.`);
}
}
for (const edge of reg.edges) {
if (edgeIds.has(edge.id)) errors.push(`Duplicate edge id: ${edge.id}.`);
edgeIds.add(edge.id);
if (edge.mode !== "road" && edge.mode !== "water") {
errors.push(`Edge ${edge.id} has invalid mode ${edge.mode}.`);
} else {
modeCounts[edge.mode]++;
}
for (const endpoint of [edge.from, edge.to]) {
totalEndpoints++;
if (nodeSet.has(endpoint)) {
validEndpoints++;
degree[endpoint]++;
} else {
errors.push(`Edge ${edge.id} references missing endpoint ${endpoint}.`);
}
}
if (edge.from === edge.to) errors.push(`Edge ${edge.id} cannot connect a node to itself.`);
}
for (const [id, count] of Object.entries(degree)) {
if (count === 0) errors.push(`Node ${id} is not connected to any edge.`);
}
return {
errors,
validEndpoints,
totalEndpoints,
nodeCount: nodeIds.length,
edgeCount: reg.edges.length,
modeCounts
};
}
const audit = validateRegistry(registry);
if (audit.errors.length) {
const fatal = document.createElement("div");
fatal.className = "fatal";
fatal.textContent = `Registry validation failed: ${audit.errors.join(" ")}`;
document.body.appendChild(fatal);
throw new Error(audit.errors.join("\n"));
}
$("registryBadge").textContent = `✓ ${audit.validEndpoints}/${audit.totalEndpoints} endpoints`;
$("registryBadge").title = `${audit.nodeCount} nodes, ${audit.edgeCount} edges; every endpoint reference verified`;
$("auditText").textContent =
`PASS · ${audit.nodeCount} nodes · ${audit.edgeCount} edges\n` +
`${audit.validEndpoints}/${audit.totalEndpoints} endpoint references valid\n` +
`${audit.modeCounts.road} road edges · ${audit.modeCounts.water} water edges\n` +
`Source: ${registry.nodes[registry.sourceId].name}`;
const districtIds = Object.keys(registry.nodes).filter(id => registry.nodes[id].kind === "neighborhood");
const edgeState = new Map(registry.edges.map(edge => [edge.id, { damaged: edge.initialDamaged }]));
const modeLabel = { road: "Road", water: "Water" };
const totalRepairable = registry.edges.filter(edge => edge.initialDamaged).length;
let selected = null;
let currentReach = {
road: new Set(),
water: new Set(),
edgeReach: new Map()
};
let quakeStart = -Infinity;
let quakeEnd = -Infinity;
let toastTimer = 0;
// ---------- Procedural low-poly scene ----------
const canvas = $("scene");
const viewport = $("viewport");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xb9d0d0);
scene.fog = new THREE.Fog(0xb9d0d0, 22, 42);
const camera = new THREE.PerspectiveCamera(40, 1, 0.1, 80);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const world = new THREE.Group();
scene.add(world);
const hemisphere = new THREE.HemisphereLight(0xeaf7f4, 0x5c6552, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffefd2, 2.4);
sun.position.set(7, 14, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
sun.shadow.camera.left = -12;
sun.shadow.camera.right = 12;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x7ccbd5, 0.7);
fill.position.set(-8, 7, -7);
scene.add(fill);
const pickables = [];
const nodeVisuals = new Map();
const edgeVisuals = new Map();
const labelMap = new Map();
const nodePulse = new Map();
const rowMap = new Map();
function hashString(value) {
let hash = 2166136261;
for (let i = 0; i < value.length; i++) {
hash ^= value.charCodeAt(i);
hash = Math.imul(hash, 16777619);
}
return hash >>> 0;
}
function seededRandom(seed) {
let value = seed >>> 0;
return () => {
value += 0x6D2B79F5;
let t = value;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
function makeIsland() {
const boundary = [
[-7.8, -5.6], [-5.6, -6.7], [-1.9, -6.45], [1.2, -5.5],
[4.7, -4.0], [6.5, -0.5], [5.8, 3.8], [2.3, 6.0],
[-2.5, 5.9], [-6.0, 3.2], [-7.4, -1.0]
];
const center = [-0.65, -0.25];
const positions = [];
const colors = [];
const topColor = new THREE.Color(0xb8b58d);
const sideColor = new THREE.Color(0x777d68);
for (let i = 0; i < boundary.length; i++) {
const p1 = boundary[i];
const p2 = boundary[(i + 1) % boundary.length];
const shade = topColor.clone().offsetHSL(0, (i % 3 - 1) * 0.025, (i % 2 ? 0.025 : -0.015));
positions.push(center[0], 0, center[1], p1[0], 0, p1[1], p2[0], 0, p2[1]);
colors.push(shade.r, shade.g, shade.b, shade.r, shade.g, shade.b, shade.r, shade.g, shade.b);
positions.push(p1[0], 0, p1[1], p2[0], 0, p2[1], p2[0], -0.42, p2[1]);
positions.push(p1[0], 0, p1[1], p2[0], -0.42, p2[1], p1[0], -0.42, p1[1]);
for (let k = 0; k < 3; k++) colors.push(sideColor.r, sideColor.g, sideColor.b);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
geometry.computeVertexNormals();
const mesh = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 1,
flatShading: true,
side: THREE.DoubleSide
})
);
mesh.receiveShadow = true;
world.add(mesh);
const shoreGeometry = new THREE.BufferGeometry().setFromPoints(
boundary.map(([x, z]) => new THREE.Vector3(x, -0.02, z))
);
const shore = new THREE.LineLoop(
shoreGeometry,
new THREE.LineBasicMaterial({ color: 0xe6dfc6, transparent: true, opacity: 0.9 })
);
world.add(shore);
}
const water = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
new THREE.MeshStandardMaterial({ color: 0x73aeb6, roughness: 0.82, metalness: 0.02 })
);
water.rotation.x = -Math.PI / 2;
water.position.y = -0.46;
water.receiveShadow = true;
scene.add(water);
makeIsland();
const wavePositions = [];
const waveRandom = seededRandom(9214);
for (let i = 0; i < 38; i++) {
const x = -17 + waveRandom() * 34;
const z = -16 + waveRandom() * 32;
if (Math.abs(x + 0.6) < 7.4 && Math.abs(z + 0.2) < 6.4) continue;
const length = 0.4 + waveRandom() * 1.4;
wavePositions.push(x, -0.405, z, x + length, -0.405, z + (waveRandom() - 0.5) * 0.18);
}
const waveGeometry = new THREE.BufferGeometry();
waveGeometry.setAttribute("position", new THREE.Float32BufferAttribute(wavePositions, 3));
scene.add(new THREE.LineSegments(
waveGeometry,
new THREE.LineBasicMaterial({ color: 0xc8e0dc, transparent: true, opacity: 0.35 })
));
const faultPoints = [
[-6.5, -3.0], [-5.2, -2.5], [-4.2, -3.3], [-3.4, -2.7],
[-2.6, -3.7], [-1.7, -3.1], [-0.8, -3.7], [0.1, -2.8],
[1.1, -2.0], [2.0, -1.1]
].map(([x, z]) => new THREE.Vector3(x, 0.085, z));
const fault = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(faultPoints),
new THREE.LineDashedMaterial({
color: 0xb84a40,
dashSize: 0.22,
gapSize: 0.13,
transparent: true,
opacity: 0.85
})
);
fault.computeLineDistances();
world.add(fault);
const districtColors = {
"ward-beacon": 0x7fa58a,
"ward-lantern": 0x9eb07c,
"ward-civic": 0xb3a879,
"ward-orchard": 0x8ca56f,
"ward-quayside": 0x829d99,
"ward-southbank": 0xa08f73
};
const buildingColors = [0xd9d0b1, 0xc8b98f, 0xe2d8be, 0xb9c1aa, 0xd3b99b, 0xaeb8b0];
function addBuilding(node, offset, index, random) {
const [ox, oz, width, depth] = offset;
const height = 0.32 + random() * 0.58;
const x = node.position[0] + ox;
const z = node.position[1] + oz;
const body = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
new THREE.MeshStandardMaterial({
color: buildingColors[(index + Math.floor(random() * 4)) % buildingColors.length],
roughness: 0.9,
flatShading: true
})
);
body.position.set(x, 0.1 + height / 2, z);
body.castShadow = true;
body.receiveShadow = true;
world.add(body);
const roof = new THREE.Mesh(
new THREE.ConeGeometry(Math.max(width, depth) * 0.73, 0.18, 4),
new THREE.MeshStandardMaterial({
color: index % 2 ? 0x91675b : 0x6f7770,
roughness: 0.95,
flatShading: true
})
);
roof.position.set(x, 0.1 + height + 0.09, z);
roof.rotation.y = Math.PI / 4;
roof.castShadow = true;
world.add(roof);
}
for (const id of districtIds) {
const node = registry.nodes[id];
const patch = new THREE.Mesh(
new THREE.CylinderGeometry(1.23, 1.31, 0.08, 7),
new THREE.MeshStandardMaterial({
color: districtColors[id],
roughness: 1,
flatShading: true
})
);
patch.position.set(node.position[0], 0.05, node.position[1]);
patch.receiveShadow = true;
world.add(patch);
const random = seededRandom(hashString(id));
const offsets = [
[-0.78, -0.62, 0.27, 0.23],
[0.72, -0.68, 0.31, 0.24],
[-0.90, 0.30, 0.25, 0.29],
[0.75, 0.38, 0.34, 0.23],
[-0.03, 0.91, 0.30, 0.27]
];
offsets.forEach((offset, index) => addBuilding(node, offset, index, random));
}
const hillLocations = [
[-6.75, -4.45, 0.82, 1.05],
[3.85, -4.75, 0.72, 0.88],
[-5.35, 4.15, 0.72, 0.80],
[4.35, 3.65, 0.62, 0.72]
];
for (const [x, z, radius, height] of hillLocations) {
const hill = new THREE.Mesh(
new THREE.ConeGeometry(radius, height, 7),
new THREE.MeshStandardMaterial({ color: 0x708b72, roughness: 1, flatShading: true })
);
hill.position.set(x, height / 2 - 0.02, z);
hill.castShadow = true;
hill.receiveShadow = true;
world.add(hill);
}
function registerPick(mesh, type, id) {
mesh.userData.pickType = type;
mesh.userData.pickId = id;
pickables.push(mesh);
}
function createNodeVisual(id) {
const node = registry.nodes[id];
const group = new THREE.Group();
group.position.set(node.position[0], 0, node.position[1]);
world.add(group);
const baseMaterial = new THREE.MeshStandardMaterial({
color: node.kind === "source" ? 0xd5a64d : 0xe8e0c8,
roughness: 0.72,
flatShading: true
});
const base = new THREE.Mesh(
new THREE.CylinderGeometry(node.kind === "source" ? 0.42 : 0.25, 0.32, 0.19, 6),
baseMaterial
);
base.position.y = 0.16;
base.castShadow = true;
group.add(base);
registerPick(base, "node", id);
if (node.kind === "source") {
const tank = new THREE.Mesh(
new THREE.CylinderGeometry(0.34, 0.38, 0.7, 8),
new THREE.MeshStandardMaterial({ color: 0xe3bd69, roughness: 0.65, flatShading: true })
);
tank.position.y = 0.75;
tank.castShadow = true;
group.add(tank);
registerPick(tank, "node", id);
const cap = new THREE.Mesh(
new THREE.ConeGeometry(0.42, 0.3, 8),
new THREE.MeshStandardMaterial({ color: 0x7d6642, roughness: 0.8, flatShading: true })
);
cap.position.y = 1.24;
cap.castShadow = true;
group.add(cap);
} else {
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(0.055, 0.075, 0.58, 6),
new THREE.MeshStandardMaterial({ color: 0x526a69, roughness: 0.8, flatShading: true })
);
pole.position.y = 0.48;
pole.castShadow = true;
group.add(pole);
if (node.kind === "neighborhood") {
const cap = new THREE.Mesh(
new THREE.ConeGeometry(0.16, 0.28, 6),
new THREE.MeshStandardMaterial({ color: 0xf2ead3, roughness: 0.75, flatShading: true })
);
cap.position.y = 0.86;
cap.castShadow = true;
group.add(cap);
}
}
let roadMaterial = null;
let waterMaterial = null;
if (node.kind === "neighborhood" || node.kind === "source") {
const badgeY = node.kind === "source" ? 1.25 : 0.98;
roadMaterial = new THREE.MeshStandardMaterial({
color: 0x718184,
emissive: 0x223a3b,
emissiveIntensity: 0.25,
roughness: 0.55,
flatShading: true
});
const roadBadge = new THREE.Mesh(new THREE.BoxGeometry(0.18, 0.18, 0.18), roadMaterial);
roadBadge.position.set(-0.27, badgeY, 0);
roadBadge.castShadow = true;
group.add(roadBadge);
registerPick(roadBadge, "node", id);
waterMaterial = new THREE.MeshStandardMaterial({
color: 0x718184,
emissive: 0x223a3b,
emissiveIntensity: 0.25,
roughness: 0.5,
flatShading: true
});
const waterBadge = new THREE.Mesh(new THREE.OctahedronGeometry(0.14, 0), waterMaterial);
waterBadge.position.set(0.27, badgeY, 0);
waterBadge.castShadow = true;
group.add(waterBadge);
registerPick(waterBadge, "node", id);
}
nodeVisuals.set(id, { group, roadMaterial, waterMaterial });
}
Object.keys(registry.nodes).forEach(createNodeVisual);
function edgeCurve(edge) {
const a = registry.nodes[edge.from].position;
const b = registry.nodes[edge.to].position;
const y = edge.mode === "water" ? 0.48 : 0.19;
const start = new THREE.Vector3(a[0], y, a[1]);
const end = new THREE.Vector3(b[0], y, b[1]);
const midpoint = start.clone().add(end).multiplyScalar(0.5);
const direction = end.clone().sub(start);
const perpendicular = new THREE.Vector3(-direction.z, 0, direction.x).normalize();
const edgeIndex = registry.edges.findIndex(item => item.id === edge.id);
const offset = edge.mode === "water" ? (edgeIndex % 2 ? 0.29 : -0.29) : 0;
midpoint.addScaledVector(perpendicular, offset);
midpoint.y = y;
return new THREE.QuadraticBezierCurve3(start, midpoint, end);
}
function ribbonGeometry(curve, width, segments = 14) {
const positions = [];
const indices = [];
for (let i = 0; i <= segments; i++) {
const t = i / segments;
const point = curve.getPoint(t);
const tangent = curve.getTangent(t).normalize();
const side = new THREE.Vector3(-tangent.z, 0, tangent.x).normalize();
const left = point.clone().addScaledVector(side, width / 2);
const right = point.clone().addScaledVector(side, -width / 2);
positions.push(left.x, left.y, left.z, right.x, right.y, right.z);
if (i < segments) {
const a = i * 2;
indices.push(a, a + 1, a + 2, a + 1, a + 3, a + 2);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
function createEdgeVisual(edge) {
const group = new THREE.Group();
const curve = edgeCurve(edge);
const material = new THREE.MeshStandardMaterial({
color: edge.mode === "road" ? 0x477d6d : 0x38bfd2,
emissive: 0x000000,
emissiveIntensity: 0.15,
roughness: edge.mode === "road" ? 0.92 : 0.56,
flatShading: true,
side: THREE.DoubleSide
});
const geometry = edge.mode === "road"
? ribbonGeometry(curve, 0.36)
: new THREE.TubeGeometry(curve, 16, 0.075, 5, false);
const mainMesh = new THREE.Mesh(geometry, material);
mainMesh.castShadow = true;
mainMesh.receiveShadow = true;
group.add(mainMesh);
registerPick(mainMesh, "edge", edge.id);
const midpoint = curve.getPoint(0.5);
const marker = new THREE.Group();
marker.position.copy(midpoint);
marker.position.y += 0.62;
const markerMaterial = new THREE.MeshStandardMaterial({
color: 0xff5d51,
emissive: 0xff392f,
emissiveIntensity: 0.72,
roughness: 0.5,
flatShading: true
});
const markerMesh = new THREE.Mesh(new THREE.OctahedronGeometry(0.18, 0), markerMaterial);
markerMesh.castShadow = true;
marker.add(markerMesh);
registerPick(markerMesh, "edge", edge.id);
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(0.015, 0.015, 0.58, 5),
new THREE.MeshBasicMaterial({ color: 0xff776c, transparent: true, opacity: 0.75 })
);
stem.position.y = -0.31;
marker.add(stem);
group.add(marker);
const selectionRing = new THREE.Mesh(
new THREE.TorusGeometry(0.34, 0.027, 5, 20),
new THREE.MeshBasicMaterial({ color: 0xffdc74, transparent: true, opacity: 0.95 })
);
selectionRing.position.copy(midpoint);
selectionRing.rotation.x = Math.PI / 2;
selectionRing.visible = false;
group.add(selectionRing);
const particles = [];
const particleMaterial = new THREE.MeshBasicMaterial({
color: edge.mode === "road" ? 0xb9f2c8 : 0xb7f6ff
});
for (let i = 0; i < 2; i++) {
const particle = new THREE.Mesh(
new THREE.SphereGeometry(edge.mode === "road" ? 0.065 : 0.075, 6, 4),
particleMaterial
);
particle.visible = false;
group.add(particle);
particles.push(particle);
}
world.add(group);
edgeVisuals.set(edge.id, {
group,
curve,
material,
mainMesh,
marker,
markerMaterial,
selectionRing,
particles,
flashUntil: 0
});
}
registry.edges.forEach(createEdgeVisual);
// ---------- Reachability and status ----------
function computeReachability(mode) {
const adjacency = new Map(Object.keys(registry.nodes).map(id => [id, []]));
for (const edge of registry.edges) {
if (edge.mode !== mode || edgeState.get(edge.id).damaged) continue;
adjacency.get(edge.from).push(edge.to);
adjacency.get(edge.to).push(edge.from);
}
const reached = new Set([registry.sourceId]);
const queue = [registry.sourceId];
for (let index = 0; index < queue.length; index++) {
const nodeId = queue[index];
for (const neighbor of adjacency.get(nodeId)) {
if (!reached.has(neighbor)) {
reached.add(neighbor);
queue.push(neighbor);
}
}
}
return reached;
}
function updateEdgeStyles() {
for (const edge of registry.edges) {
const visual = edgeVisuals.get(edge.id);
const damaged = edgeState.get(edge.id).damaged;
const reachable = currentReach.edgeReach.get(edge.id) === true;
const isSelected = selected?.type === "edge" && selected.id === edge.id;
let color;
if (damaged) color = 0xff5d51;
else if (reachable) color = edge.mode === "road" ? 0x3f8a68 : 0x23bdd2;
else color = 0xd6a13b;
visual.material.color.setHex(color);
visual.material.emissive.setHex(damaged ? 0x9b241d : reachable ? color : 0x7d5314);
visual.material.emissiveIntensity = isSelected ? 0.48 : damaged ? 0.28 : 0.14;
visual.marker.visible = damaged;
visual.selectionRing.visible = isSelected;
visual.particles.forEach(particle => {
particle.visible = !damaged && reachable;
});
}
}
function updateNodeBadges() {
for (const [id, visual] of nodeVisuals) {
const node = registry.nodes[id];
const roadConnected = node.kind === "source" || currentReach.road.has(id);
const waterConnected = node.kind === "source" || currentReach.water.has(id);
if (visual.roadMaterial) {
visual.roadMaterial.color.setHex(roadConnected ? 0x65d98c : 0x718184);
visual.roadMaterial.emissive.setHex(roadConnected ? 0x1d7f42 : 0x263b3c);
visual.roadMaterial.emissiveIntensity = roadConnected ? 0.52 : 0.18;
}
if (visual.waterMaterial) {
visual.waterMaterial.color.setHex(waterConnected ? 0x55d5e4 : 0x718184);
visual.waterMaterial.emissive.setHex(waterConnected ? 0x126f82 : 0x263b3c);
visual.waterMaterial.emissiveIntensity = waterConnected ? 0.55 : 0.18;
}
const label = labelMap.get(id);
if (label?.road && label.water) {
label.road.classList.toggle("on", roadConnected);
label.water.classList.toggle("on", waterConnected);
}
}
}
function setPill(element, connected, connectedText, disconnectedText) {
element.textContent = connected ? connectedText : disconnectedText;
element.classList.toggle("good", connected);
}
function updateTable(previousReach) {
const gainedRoad = [];
const gainedWater = [];
for (const id of districtIds) {
const row = rowMap.get(id);
const roadConnected = currentReach.road.has(id);
const waterConnected = currentReach.water.has(id);
setPill(row.road, roadConnected, "Open", "Cut off");
setPill(row.water, waterConnected, "Supplied", "No supply");
if (previousReach) {
const gained = (!previousReach.road.has(id) && roadConnected) ||
(!previousReach.water.has(id) && waterConnected);
if (gained) {
row.element.classList.remove("gained");
void row.element.offsetWidth;
row.element.classList.add("gained");
nodePulse.set(id, performance.now() + 1150);
labelMap.get(id)?.element.classList.remove("gained");
void labelMap.get(id)?.element.offsetWidth;
labelMap.get(id)?.element.classList.add("gained");
window.setTimeout(() => {
row.element.classList.remove("gained");
labelMap.get(id)?.element.classList.remove("gained");
}, 1200);
}
}
if (previousReach && !previousReach.road.has(id) && roadConnected) gainedRoad.push(registry.nodes[id].name);
if (previousReach && !previousReach.water.has(id) && waterConnected) gainedWater.push(registry.nodes[id].name);
}
if (!previousReach) {
$("lastRestored").textContent = "No repairs yet. The initial service state is shown above.";
} else {
const parts = [];
if (gainedRoad.length) parts.push(`Road regained: ${gainedRoad.join(", ")}.`);
if (gainedWater.length) parts.push(`Water regained: ${gainedWater.join(", ")}.`);
$("lastRestored").textContent = parts.length ? parts.join(" ") : "The link reopened, but no new ward gained access yet.";
}
}
function updateMetrics() {
const roadCount = districtIds.filter(id => currentReach.road.has(id)).length;
const waterCount = districtIds.filter(id => currentReach.water.has(id)).length;
const repairedCount = registry.edges.filter(edge => edge.initialDamaged && !edgeState.get(edge.id).damaged).length;
const percentage = totalRepairable ? (repairedCount / totalRepairable) * 100 : 100;
$("roadMetric").textContent = `${roadCount}/${districtIds.length}`;
$("waterMetric").textContent = `${waterCount}/${districtIds.length}`;
$("repairedMetric").textContent = `${repairedCount}/${totalRepairable}`;
$("recoveryFill").style.width = `${percentage}%`;
$("recoveryText").textContent = `${repairedCount} of ${totalRepairable} modeled links repaired`;
const stage = repairedCount === 0 ? "Isolated" : repairedCount === totalRepairable ? "Fully reconnected" : "Reconnecting";
$("recoveryStage").textContent = stage;
$("phaseReconnect").className = `phase${repairedCount > 0 ? " active" : ""}`;
$("phaseRestore").className = `phase${repairedCount === totalRepairable ? " active" : ""}`;
}
function refreshAll(previousReach = null) {
const road = computeReachability("road");
const water = computeReachability("water");
const edgeReach = new Map();
for (const edge of registry.edges) {
edgeReach.set(
edge.id,
!edgeState.get(edge.id).damaged && road.has(edge.from) && road.has(edge.to)
);
}
currentReach = { road, water, edgeReach };
updateEdgeStyles();
updateNodeBadges();
updateMetrics();
updateTable(previousReach);
renderDamagedList();
updateSelectionUI();
}
// ---------- DOM derived from the registry ----------
function buildNeighborhoodTable() {
const tbody = $("neighborhoodRows");
tbody.replaceChildren();
for (const id of districtIds) {
const node = registry.nodes[id];
const row = document.createElement("tr");
const heading = document.createElement("th");
heading.scope = "row";
heading.textContent = node.name;
const roadCell = document.createElement("td");
const roadPill = document.createElement("span");
roadPill.className = "status-pill";
roadCell.appendChild(roadPill);
const waterCell = document.createElement("td");
const waterPill = document.createElement("span");
waterPill.className = "status-pill";
waterCell.appendChild(waterPill);
row.append(heading, roadCell, waterCell);
tbody.appendChild(row);
rowMap.set(id, { element: row, road: roadPill, water: waterPill });
}
}
function buildLabels() {
const layer = $("labelLayer");
layer.replaceChildren();
for (const [id, node] of Object.entries(registry.nodes)) {
if (node.kind !== "neighborhood" && node.kind !== "source") continue;
const element = document.createElement("div");
element.className = `map-label${node.kind === "source" ? " source" : ""}`;
const name = document.createElement("span");
name.className = "label-name";
name.textContent = node.name;
element.appendChild(name);
const sub = document.createElement("span");
sub.className = "label-sub";
sub.textContent = node.kind === "source" ? "Abstract source" : "Fictional ward";
element.appendChild(sub);
let road = null;
let water = null;
if (node.kind === "neighborhood") {
const status = document.createElement("span");
status.className = "label-status";
road = document.createElement("span");
road.className = "road";
road.append("ROAD");
const roadDot = document.createElement("i");
road.appendChild(roadDot);
water = document.createElement("span");
water.className = "water";
water.append("WATER");
const waterDot = document.createElement("i");
water.appendChild(waterDot);
status.append(road, water);
element.appendChild(status);
}
layer.appendChild(element);
labelMap.set(id, { element, road, water });
}
}
function renderDamagedList() {
const list = $("damagedList");
list.replaceChildren();
const damaged = registry.edges.filter(edge => edgeState.get(edge.id).damaged);
$("damagedCount").textContent = damaged.length;
if (!damaged.length) {
const clear = document.createElement("div");
clear.className = "all-clear";
clear.textContent = "All fictional links are open. Road and water routes reach every modeled ward.";
list.appendChild(clear);
return;
}
for (const edge of damaged) {
const button = document.createElement("button");
button.type = "button";
button.className = `edge-item ${edge.mode}`;
if (selected?.type === "edge" && selected.id === edge.id) button.classList.add("selected");
button.setAttribute("aria-pressed", String(selected?.type === "edge" && selected.id === edge.id));
const dot = document.createElement("span");
dot.className = "edge-mode-dot";
dot.setAttribute("aria-hidden", "true");
const copy = document.createElement("span");
const title = document.createElement("strong");
title.textContent = edge.name;
const detail = document.createElement("small");
detail.textContent = `${modeLabel[edge.mode]} · ${registry.nodes[edge.from].name} → ${registry.nodes[edge.to].name}`;
copy.append(title, detail);
button.append(dot, copy);
button.addEventListener("click", () => selectEdge(edge.id));
list.appendChild(button);
}
}
function updateSelectionUI() {
const button = $("repairBtn");
button.disabled = true;
if (!selected) {
$("selectionKind").textContent = "No selection";
$("selectionTitle").textContent = "Choose a cut link";
$("selectionMeta").textContent = "Click a red link in the model or use the damaged-link list.";
button.textContent = "Repair selected link";
return;
}
if (selected.type === "edge") {
const edge = registry.edges.find(item => item.id === selected.id);
const damaged = edgeState.get(edge.id).damaged;
const reachable = currentReach.edgeReach.get(edge.id);
$("selectionKind").textContent = `${modeLabel[edge.mode]} network link`;
$("selectionTitle").textContent = edge.name;
$("selectionMeta").textContent =
`${registry.nodes[edge.from].name} → ${registry.nodes[edge.to].name} · ` +
(damaged ? "Fictional cut; repair to reopen this link." : reachable ? "Open and carrying modeled service." : "Open, but another upstream cut still isolates part of the network.");
button.disabled = !damaged;
button.textContent = damaged ? "Repair this link" : "Link is already open";
} else {
const node = registry.nodes[selected.id];
const road = node.kind === "source" || currentReach.road.has(node.id);
const water = node.kind === "source" || currentReach.water.has(node.id);
$("selectionKind").textContent = node.kind === "source" ? "Abstract source" : "Fictional neighborhood node";
$("selectionTitle").textContent = node.name;
$("selectionMeta").textContent = `Road: ${road ? "connected" : "isolated"} · Water: ${water ? "supplied" : "not supplied"}.`;
button.textContent = "Select a damaged link";
}
}
function selectEdge(id) {
selected = { type: "edge", id };
updateEdgeStyles();
renderDamagedList();
updateSelectionUI();
}
function selectNode(id) {
selected = { type: "node", id };
updateEdgeStyles();
updateSelectionUI();
}
function addLog(title, message, kind = "info") {
const log = $("activityLog");
const item = document.createElement("li");
const dot = document.createElement("span");
dot.className = `activity-dot ${kind}`;
const copy = document.createElement("div");
const heading = document.createElement("strong");
heading.textContent = title;
const paragraph = document.createElement("p");
paragraph.textContent = message;
copy.append(heading, paragraph);
item.append(dot, copy);
log.prepend(item);
while (log.children.length > 8) log.lastElementChild.remove();
}
function showToast(title, message) {
window.clearTimeout(toastTimer);
$("toastTitle").textContent = title;
$("toastBody").textContent = message;
$("toast").classList.add("show");
toastTimer = window.setTimeout(() => $("toast").classList.remove("show"), 4300);
}
function repairSelected() {
if (selected?.type !== "edge") return;
const edge = registry.edges.find(item => item.id === selected.id);
if (!edge || !edgeState.get(edge.id).damaged) return;
const before = {
road: new Set(currentReach.road),
water: new Set(currentReach.water)
};
edgeState.get(edge.id).damaged = false;
edgeVisuals.get(edge.id).flashUntil = performance.now() + 900;
refreshAll(before);
const gainedRoad = districtIds.filter(id => !before.road.has(id) && currentReach.road.has(id));
const gainedWater = districtIds.filter(id => !before.water.has(id) && currentReach.water.has(id));
const gained = [...new Set([...gainedRoad, ...gainedWater])].map(id => registry.nodes[id].name);
const repairedCount = registry.edges.filter(item => item.initialDamaged && !edgeState.get(item.id).damaged).length;
addLog(
`Repair ${repairedCount}: ${edge.name}`,
`${modeLabel[edge.mode]} link reopened. Reachability was recalculated from Cistern Alpha.`,
"repair"
);
if (gained.length) {
addLog(
"Access regained",
`${gained.join(", ")} gained service after the repair.`,
"access"
);
showToast("Link repaired — access changed", `${gained.join(", ")} regained service in the model.`);
} else {
showToast(
"Link repaired",
"The link is open, but another upstream cut still isolates some modeled wards."
);
}
}
function resetScenario(notify = true) {
for (const edge of registry.edges) {
edgeState.get(edge.id).damaged = edge.initialDamaged;
}
const firstDamaged = registry.edges.find(edge => edge.initialDamaged);
selected = firstDamaged ? { type: "edge", id: firstDamaged.id } : null;
$("activityLog").replaceChildren();
refreshAll(null);
const roadCount = districtIds.filter(id => currentReach.road.has(id)).length;
const waterCount = districtIds.filter(id => currentReach.water.has(id)).length;
addLog("Model opened", `${totalRepairable} fictional links are cut after the modeled rupture.`, "reset");
addLog("Road reachability", `${roadCount} of ${districtIds.length} fictional wards have a route from Cistern Alpha.`);
addLog("Water reachability", `${waterCount} of ${districtIds.length} fictional wards have a water route from Cistern Alpha.`);
if (notify) showToast("Recovery reset", "The fictional damage pattern and initial service states have been restored.");
}
function startQuake(reset = true) {
if (reset) resetScenario(false);
quakeStart = performance.now();
quakeEnd = quakeStart + (reduceMotion ? 500 : 1700);
$("quakeBanner").classList.add("show");
$("modelClock").textContent = "Modeled rupture";
}
$("repairBtn").addEventListener("click", repairSelected);
$("resetBtn").addEventListener("click", () => resetScenario(true));
$("quakeBtn").addEventListener("click", () => startQuake(true));
$("homeView").addEventListener("click", resetCamera);
// ---------- Camera controls implemented without addons ----------
const orbit = {
theta: 0.67,
phi: 0.72,
radius: 16.5,
target: new THREE.Vector3(-0.65, 0.1, -0.15)
};
function resetCamera() {
orbit.theta = 0.67;
orbit.phi = 0.72;
orbit.radius = 16.5;
orbit.target.set(-0.65, 0.1, -0.15);
}
function quakeIntensity(now) {
if (now < quakeStart || now >= quakeEnd) return 0;
const t = (now - quakeStart) / Math.max(1, quakeEnd - quakeStart);
return (reduceMotion ? 0.12 : 1) * (1 - t) * (0.72 + Math.sin(t * 31) * 0.18);
}
function updateCamera(now) {
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)
);
const shake = quakeIntensity(now);
if (shake > 0) {
camera.position.x += (Math.random() - 0.5) * 0.38 * shake;
camera.position.y += (Math.random() - 0.5) * 0.24 * shake;
camera.position.z += (Math.random() - 0.5) * 0.38 * shake;
}
camera.lookAt(orbit.target);
camera.updateMatrixWorld();
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const drag = {
active: false,
pointerId: null,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
button: 0,
moved: false,
pan: false
};
function isVisible(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 hits = raycaster.intersectObjects(pickables, false);
for (const hit of hits) {
if (isVisible(hit.object) && hit.object.userData.pickType) return hit.object.userData;
}
return null;
}
canvas.addEventListener("pointerdown", event => {
if (event.button !== 0 && event.button !== 2) return;
event.preventDefault();
drag.active = true;
drag.pointerId = event.pointerId;
drag.startX = drag.lastX = event.clientX;
drag.startY = drag.lastY = event.clientY;
drag.button = event.button;
drag.moved = false;
drag.pan = event.shiftKey || event.button === 2;
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
});
canvas.addEventListener("pointermove", event => {
if (!drag.active) {
const picked = pickAt(event.clientX, event.clientY);
canvas.style.cursor = picked ? "pointer" : "grab";
return;
}
const dx = event.clientX - drag.lastX;
const dy = event.clientY - drag.lastY;
const totalX = event.clientX - drag.startX;
const totalY = event.clientY - drag.startY;
if (Math.hypot(totalX, totalY) > 5) drag.moved = true;
if (drag.pan) {
const right = new THREE.Vector3(Math.cos(orbit.theta), 0, -Math.sin(orbit.theta));
const forward = new THREE.Vector3(-Math.sin(orbit.theta), 0, -Math.cos(orbit.theta));
orbit.target.addScaledVector(right, -dx * orbit.radius * 0.0014);
orbit.target.addScaledVector(forward, dy * orbit.radius * 0.0014);
orbit.target.x = THREE.MathUtils.clamp(orbit.target.x, -5.5, 4.5);
orbit.target.z = THREE.MathUtils.clamp(orbit.target.z, -5.5, 5.5);
} else {
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(orbit.phi + dy * 0.005, 0.28, 1.36);
}
drag.lastX = event.clientX;
drag.lastY = event.clientY;
});
canvas.addEventListener("pointerup", event => {
if (!drag.active || event.pointerId !== drag.pointerId) return;
const wasClick = !drag.moved && drag.button === 0;
drag.active = false;
if (canvas.hasPointerCapture(event.pointerId)) canvas.releasePointerCapture(event.pointerId);
canvas.style.cursor = "grab";
if (wasClick) {
const picked = pickAt(event.clientX, event.clientY);
if (picked?.pickType === "edge") selectEdge(picked.pickId);
else if (picked?.pickType === "node") selectNode(picked.pickId);
}
});
canvas.addEventListener("pointercancel", () => {
drag.active = false;
canvas.style.cursor = "grab";
});
canvas.addEventListener("contextmenu", event => event.preventDefault());
canvas.addEventListener("wheel", event => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(orbit.radius + event.deltaY * 0.012, 9.5, 25);
}, { passive: false });
canvas.addEventListener("keydown", event => {
let handled = true;
if (event.key === "ArrowLeft") orbit.theta -= 0.09;
else if (event.key === "ArrowRight") orbit.theta += 0.09;
else if (event.key === "ArrowUp") orbit.phi = Math.max(0.28, orbit.phi - 0.07);
else if (event.key === "ArrowDown") orbit.phi = Math.min(1.36, orbit.phi + 0.07);
else if (event.key === "+" || event.key === "=") orbit.radius = Math.max(9.5, orbit.radius - 1);
else if (event.key === "-" || event.key === "_") orbit.radius = Math.min(25, orbit.radius + 1);
else if (event.key === "Home") resetCamera();
else handled = false;
if (handled) event.preventDefault();
});
function resize() {
const width = Math.max(1, viewport.clientWidth);
const height = Math.max(1, viewport.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
if ("ResizeObserver" in window) {
new ResizeObserver(resize).observe(viewport);
} else {
window.addEventListener("resize", resize);
}
// ---------- Labels and animation ----------
const projected = new THREE.Vector3();
function updateLabels() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
for (const [id, label] of labelMap) {
const node = registry.nodes[id];
const heightAbove = node.kind === "source" ? 1.95 : 1.43;
projected.set(node.position[0], heightAbove, node.position[1]).project(camera);
const visible = projected.z > -1 && projected.z < 1 && Math.abs(projected.x) < 1.12 && Math.abs(projected.y) < 1.12;
label.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;
label.element.style.left = `${x}px`;
label.element.style.top = `${y}px`;
}
}
function updateQuakeOverlay(now) {
const intensity = quakeIntensity(now);
$("quakeWash").style.opacity = String(intensity * 0.42);
if (now < quakeEnd) {
$("quakeBanner").classList.add("show");
$("modelClock").textContent = "Modeled rupture";
} else {
$("quakeBanner").classList.remove("show");
$("modelClock").textContent = "Recovery model";
}
}
function animate(now) {
requestAnimationFrame(animate);
updateCamera(now);
updateQuakeOverlay(now);
for (const visual of edgeVisuals.values()) {
if (visual.marker.visible) {
visual.marker.rotation.y = now * 0.0022;
visual.marker.rotation.x = now * 0.0011;
const pulse = 1 + Math.sin(now * 0.006) * 0.12;
visual.marker.scale.setScalar(pulse);
visual.markerMaterial.emissiveIntensity = 0.58 + Math.sin(now * 0.005) * 0.18;
}
visual.particles.forEach((particle, index) => {
if (!particle.visible) return;
const t = (now * 0.000105 + index / visual.particles.length) % 1;
const point = visual.curve.getPoint(t);
particle.position.copy(point);
});
if (visual.flashUntil > now) {
visual.material.emissive.setHex(0xffd978);
visual.material.emissiveIntensity = 0.72 + Math.sin(now * 0.018) * 0.18;
} else if (visual.selectionRing.visible) {
visual.selectionRing.rotation.z = now * 0.0015;
visual.selectionRing.scale.setScalar(1 + Math.sin(now * 0.005) * 0.08);
}
}
for (const [id, visual] of nodeVisuals) {
const pulseEnd = nodePulse.get(id) || 0;
if (pulseEnd > now) {
const pulse = 1 + Math.sin((1 - (pulseEnd - now) / 1150) * Math.PI) * 0.13;
visual.group.scale.setScalar(pulse);
} else {
visual.group.scale.setScalar(1);
}
}
updateLabels();
renderer.render(scene, camera);
}
buildNeighborhoodTable();
buildLabels();
resize();
resetScenario(false);
requestAnimationFrame(animate);
$("bootMessage")?.remove();
window.setTimeout(() => startQuake(false), 280);
</script>
</body>
</html>
```