Prompt specification
Build or customize the Three.js 3D scene "Generation Outage and Priority Rules" 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: Generation Outage and Priority Rules
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/generation-outage-and-priority-rules-x3932
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts electric-grid generation and demand balance. Create a bounded toy microgrid scenario with one source outage. Compare explicit load-priority policies under identical inputs and show unserved energy without hiding tradeoffs. Voxel style.
Working Three.js Starter (generation-outage-and-priority-rules-x3932):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Grid Balance Lab — Voxel Microgrid</title>
<style>
:root {
--bg: #081117;
--panel: #101c24;
--panel-2: #14242d;
--line: #263b45;
--text: #edf5f4;
--muted: #8da5aa;
--green: #5ee7a7;
--blue: #70b7ff;
--amber: #ffc857;
--red: #ff6374;
--purple: #b39cff;
}
* { 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 { font: inherit; }
.topbar {
height: 68px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 22px;
border-bottom: 1px solid var(--line);
background: #0b151c;
position: relative;
z-index: 10;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-icon {
width: 34px;
height: 34px;
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 3px;
transform: rotate(45deg);
}
.brand-icon i {
display: block;
background: var(--green);
border-radius: 2px;
}
.brand-icon i:nth-child(2) { opacity: .72; }
.brand-icon i:nth-child(3) { opacity: .48; }
.brand-icon i:nth-child(4) { opacity: .88; }
.brand h1 {
margin: 0;
font-size: 15px;
line-height: 1.1;
letter-spacing: .13em;
white-space: nowrap;
}
.brand p {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: .08em;
white-space: nowrap;
}
.top-actions {
display: flex;
align-items: center;
gap: 12px;
}
.scenario-badge {
color: #d9e6e5;
border: 1px solid #31454e;
background: #111e26;
border-radius: 999px;
padding: 7px 11px;
font-size: 10px;
font-weight: 800;
letter-spacing: .09em;
white-space: nowrap;
}
.scenario-badge::before {
content: "";
display: inline-block;
width: 7px;
height: 7px;
margin-right: 7px;
background: var(--red);
border-radius: 2px;
box-shadow: 0 0 12px rgba(255, 99, 116, .65);
}
.quiet-button {
color: var(--text);
background: #17262e;
border: 1px solid #30464f;
border-radius: 7px;
padding: 8px 11px;
cursor: pointer;
font-size: 11px;
font-weight: 700;
}
.quiet-button:hover { background: #20343d; }
.layout {
height: calc(100vh - 68px);
display: grid;
grid-template-columns: minmax(0, 1fr) 390px;
}
#viewport {
position: relative;
min-width: 0;
overflow: hidden;
background: #0b151c;
}
#scene-canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
z-index: 0;
}
.scene-hud {
position: absolute;
top: 18px;
left: 18px;
z-index: 3;
display: flex;
gap: 7px;
pointer-events: none;
}
.hud-stat {
min-width: 112px;
padding: 10px 12px;
background: rgba(9, 18, 24, .86);
border: 1px solid rgba(95, 128, 139, .36);
border-radius: 8px;
backdrop-filter: blur(10px);
}
.hud-stat small {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: .11em;
}
.hud-stat strong {
display: block;
margin-top: 3px;
font-size: 20px;
font-variant-numeric: tabular-nums;
}
.hud-stat.supply strong { color: var(--green); }
.hud-stat.demand strong { color: var(--blue); }
.hud-stat.shortfall strong { color: var(--red); }
.outage-banner {
position: absolute;
right: 18px;
top: 18px;
z-index: 3;
display: flex;
align-items: center;
gap: 10px;
max-width: 250px;
padding: 10px 12px;
color: #ffd7dc;
background: rgba(55, 18, 27, .88);
border: 1px solid rgba(255, 99, 116, .45);
border-radius: 8px;
font-size: 11px;
line-height: 1.4;
backdrop-filter: blur(10px);
pointer-events: none;
}
.outage-mark {
width: 26px;
height: 26px;
display: grid;
place-items: center;
flex: 0 0 auto;
color: var(--red);
border: 2px solid var(--red);
border-radius: 4px;
font-size: 19px;
font-weight: 900;
transform: rotate(45deg);
}
.outage-mark span { transform: rotate(-45deg); }
.scene-bottom {
position: absolute;
left: 18px;
right: 18px;
bottom: 16px;
z-index: 3;
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 16px;
pointer-events: none;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
padding: 9px 11px;
border: 1px solid rgba(95, 128, 139, .3);
border-radius: 7px;
background: rgba(9, 18, 24, .82);
color: #b8cbce;
font-size: 10px;
backdrop-filter: blur(8px);
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.legend i {
width: 8px;
height: 8px;
display: inline-block;
border-radius: 2px;
}
.camera-hint {
color: #8da5aa;
font-size: 10px;
text-align: right;
text-shadow: 0 1px 4px #000;
}
#labels {
position: absolute;
inset: 0;
z-index: 2;
pointer-events: none;
overflow: hidden;
}
.world-label {
position: absolute;
transform: translate(-50%, -100%);
min-width: 104px;
padding: 6px 8px;
color: #e8f1f1;
background: rgba(7, 15, 20, .84);
border: 1px solid rgba(100, 132, 142, .32);
border-radius: 6px;
box-shadow: 0 5px 14px rgba(0, 0, 0, .18);
font-size: 10px;
line-height: 1.25;
white-space: nowrap;
backdrop-filter: blur(6px);
}
.world-label b {
display: block;
margin-top: 2px;
color: #aec3c5;
font-size: 9px;
font-weight: 600;
}
.world-label .dot {
width: 7px;
height: 7px;
display: inline-block;
margin-right: 5px;
border-radius: 2px;
background: var(--green);
}
.world-label .dot.partial { background: var(--amber); }
.world-label .dot.unserved { background: var(--red); }
.world-label .dot.offline { background: var(--red); }
.world-label.source-label {
min-width: 92px;
border-color: rgba(94, 231, 167, .22);
}
aside {
height: 100%;
overflow-y: auto;
padding: 18px;
background: var(--panel);
border-left: 1px solid var(--line);
scrollbar-width: thin;
scrollbar-color: #314750 transparent;
}
.section {
padding-bottom: 19px;
margin-bottom: 19px;
border-bottom: 1px solid var(--line);
}
.section:last-child { border-bottom: 0; }
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 12px;
}
.section-title h2 {
margin: 0;
font-size: 11px;
letter-spacing: .12em;
text-transform: uppercase;
}
.lock-badge {
padding: 5px 7px;
border-radius: 4px;
color: #b9cdcf;
background: #172a32;
border: 1px solid #2b434c;
font-size: 8px;
font-weight: 800;
letter-spacing: .08em;
}
.control-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
color: #c6d5d6;
font-size: 11px;
}
.control-header output {
color: var(--green);
font-weight: 800;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 6px 0 4px;
appearance: none;
border-radius: 999px;
background: #263b44;
accent-color: var(--green);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
appearance: none;
width: 14px;
height: 14px;
border-radius: 3px;
background: var(--green);
border: 2px solid #d9fff0;
box-shadow: 0 0 12px rgba(94, 231, 167, .35);
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border-radius: 3px;
background: var(--green);
border: 2px solid #d9fff0;
}
.range-labels {
display: flex;
justify-content: space-between;
color: #69828a;
font-size: 9px;
}
.time-row {
display: grid;
grid-template-columns: 1fr 36px;
align-items: center;
gap: 8px;
}
#playButton {
height: 31px;
border: 1px solid #38505a;
border-radius: 6px;
background: #1a2c34;
color: var(--green);
cursor: pointer;
}
#playButton.playing { color: var(--amber); }
.outage-card {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 15px;
padding: 11px;
border: 1px solid rgba(255, 99, 116, .32);
border-radius: 8px;
background: linear-gradient(100deg, rgba(255, 99, 116, .1), rgba(255, 99, 116, .025));
}
.outage-card strong {
display: block;
color: #ffdce0;
font-size: 11px;
}
.outage-card small {
display: block;
margin-top: 4px;
color: #a78d93;
font-size: 9px;
line-height: 1.4;
}
.outage-window {
flex: 0 0 auto;
padding: 7px 8px;
border: 1px solid rgba(255, 99, 116, .35);
border-radius: 5px;
color: var(--red);
font-size: 10px;
font-weight: 800;
}
.source-list {
display: grid;
gap: 8px;
margin-top: 12px;
}
.source-row {
display: grid;
grid-template-columns: 72px 1fr 67px;
align-items: center;
gap: 8px;
color: #b7c8ca;
font-size: 10px;
}
.source-row .bar {
height: 5px;
overflow: hidden;
border-radius: 99px;
background: #233740;
}
.source-row .bar i {
display: block;
height: 100%;
width: 0;
border-radius: inherit;
background: var(--green);
transition: width .25s ease;
}
.source-row.offline .bar i { background: var(--red); }
.source-row .amount { text-align: right; font-variant-numeric: tabular-nums; }
.policy-card {
width: 100%;
margin: 0 0 9px;
padding: 11px;
text-align: left;
color: var(--text);
border: 1px solid #2a414a;
border-radius: 8px;
background: #13232b;
cursor: pointer;
transition: border-color .15s, background .15s, transform .15s;
}
.policy-card:hover {
background: #182b34;
transform: translateY(-1px);
}
.policy-card.active {
border-color: var(--green);
background: linear-gradient(105deg, rgba(94, 231, 167, .11), rgba(19, 35, 43, .96));
box-shadow: inset 3px 0 0 var(--green);
}
.policy-card header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.policy-card h3 {
margin: 0;
font-size: 12px;
}
.policy-card .radio {
width: 13px;
height: 13px;
border: 2px solid #5f7880;
border-radius: 50%;
}
.policy-card.active .radio {
border: 4px solid var(--green);
}
.policy-card p {
margin: 7px 0 0;
color: #8fa8ad;
font-size: 9px;
line-height: 1.5;
}
.order {
margin-top: 7px !important;
color: #b4c9cc !important;
font-variant-numeric: tabular-nums;
}
.table-wrap { overflow-x: auto; }
table {
width: 100%;
border-collapse: collapse;
font-size: 9px;
font-variant-numeric: tabular-nums;
}
th {
padding: 7px 4px;
color: #718b91;
font-size: 8px;
text-align: right;
text-transform: uppercase;
letter-spacing: .06em;
border-bottom: 1px solid #2b424b;
}
td {
padding: 9px 4px;
text-align: right;
color: #b8c9cb;
border-bottom: 1px solid #20343d;
}
th:first-child, td:first-child { text-align: left; }
td strong { color: #edf6f5; }
tbody tr {
cursor: pointer;
}
tbody tr:hover { background: rgba(255, 255, 255, .025); }
tbody tr.selected {
background: rgba(94, 231, 167, .07);
}
tbody tr.selected td:first-child {
color: var(--green);
font-weight: 800;
}
.burden {
margin-top: 13px;
display: grid;
gap: 8px;
}
.burden-row {
display: grid;
grid-template-columns: 58px 1fr 74px;
align-items: center;
gap: 8px;
font-size: 9px;
color: #9db2b6;
}
.burden-track {
height: 7px;
border-radius: 3px;
overflow: hidden;
background: #223640;
}
.burden-track i {
display: block;
height: 100%;
width: 0;
background: var(--red);
}
.burden-value { text-align: right; color: #d6e3e3; }
.callout {
margin-top: 13px;
padding: 12px;
border-left: 3px solid var(--amber);
border-radius: 4px;
background: rgba(255, 200, 87, .07);
color: #cbd8d8;
font-size: 10px;
line-height: 1.55;
}
.callout strong { color: #ffe1a0; }
.method {
margin: 0;
color: #799198;
font-size: 9px;
line-height: 1.6;
}
@media (max-width: 920px) {
body { overflow: auto; }
.topbar { padding: 0 14px; }
.scenario-badge { display: none; }
.layout {
height: auto;
display: block;
}
#viewport { height: 62vh; min-height: 480px; }
aside {
height: auto;
overflow: visible;
border-left: 0;
border-top: 1px solid var(--line);
}
.scene-hud { left: 10px; top: 10px; }
.hud-stat { min-width: 90px; padding: 8px; }
.hud-stat strong { font-size: 16px; }
.outage-banner { top: auto; bottom: 58px; right: 10px; }
.scene-bottom { left: 10px; right: 10px; bottom: 10px; }
.camera-hint { display: none; }
}
@media (max-width: 520px) {
.brand p { display: none; }
.topbar { height: 60px; }
.layout { height: auto; }
.hud-stat { min-width: 77px; }
.hud-stat small { font-size: 7px; }
.outage-banner { max-width: 215px; }
}
</style>
</head>
<body>
<header class="topbar">
<div class="brand">
<div class="brand-icon" aria-hidden="true"><i></i><i></i><i></i><i></i></div>
<div>
<h1>GRID BALANCE LAB</h1>
<p>BOUNDED VOXEL MICROGRID / POLICY COMPARISON</p>
</div>
</div>
<div class="top-actions">
<span class="scenario-badge">ONE-SOURCE OUTAGE</span>
<button class="quiet-button" id="resetView">Reset view</button>
</div>
</header>
<main class="layout">
<section id="viewport" aria-label="Interactive three-dimensional microgrid">
<div class="scene-hud">
<div class="hud-stat supply">
<small>AVAILABLE</small>
<strong id="supplyValue">— MW</strong>
</div>
<div class="hud-stat demand">
<small>DEMAND</small>
<strong id="demandValue">— MW</strong>
</div>
<div class="hud-stat shortfall">
<small>UNSERVED</small>
<strong id="shortfallValue">— MW</strong>
</div>
</div>
<div class="outage-banner" id="outageBanner">
<div class="outage-mark"><span>×</span></div>
<div><strong>WIND FARM OUTAGE</strong><br>Forced unavailable, 12:00–18:00</div>
</div>
<div id="labels"></div>
<div class="scene-bottom">
<div class="legend">
<span><i style="background:#5ee7a7"></i>Fully served</span>
<span><i style="background:#ffc857"></i>Partly served</span>
<span><i style="background:#ff6374"></i>Unserved / offline</span>
<span><i style="background:#7b929a"></i>Transmission line</span>
</div>
<div class="camera-hint">DRAG TO ORBIT · WHEEL TO ZOOM · DOUBLE-CLICK TO RESET</div>
</div>
</section>
<aside>
<section class="section">
<div class="section-title">
<h2>Identical inputs</h2>
<span class="lock-badge">LOCKED FOR ALL POLICIES</span>
</div>
<div class="time-row">
<div>
<div class="control-header">
<label for="timeSlider">Snapshot hour</label>
<output id="timeOutput" for="timeSlider">14:00</output>
</div>
<input id="timeSlider" type="range" min="0" max="23" value="14" step="1">
<div class="range-labels"><span>00:00</span><span>12:00</span><span>23:00</span></div>
</div>
<button id="playButton" aria-label="Play hourly timeline" title="Play hourly timeline">▶</button>
</div>
<div style="margin-top:14px">
<div class="control-header">
<label for="demandSlider">Demand level</label>
<output id="demandOutput" for="demandSlider">100%</output>
</div>
<input id="demandSlider" type="range" min="70" max="130" value="100" step="5">
<div class="range-labels"><span>70%</span><span>100%</span><span>130%</span></div>
</div>
<div class="outage-card">
<div>
<strong>ONE FORCED OUTAGE</strong>
<small>Wind generation is unavailable during the highlighted six-hour window.</small>
</div>
<div class="outage-window">12—18</div>
</div>
<div class="source-list" id="sourceList">
<div class="source-row" data-source="solar">
<span>Solar</span><div class="bar"><i></i></div><span class="amount">—</span>
</div>
<div class="source-row" data-source="wind">
<span>Wind</span><div class="bar"><i></i></div><span class="amount">—</span>
</div>
<div class="source-row" data-source="battery">
<span>Battery</span><div class="bar"><i></i></div><span class="amount">—</span>
</div>
<div class="source-row" data-source="diesel">
<span>Diesel</span><div class="bar"><i></i></div><span class="amount">—</span>
</div>
</div>
</section>
<section class="section">
<div class="section-title">
<h2>Load-priority policy</h2>
<span class="lock-badge">ONLY VARIABLE</span>
</div>
<button class="policy-card active" data-policy="essential">
<header><h3>Essential first</h3><span class="radio"></span></header>
<p>Protect life-safety and critical infrastructure before other loads.</p>
<p class="order">Hospital → Water → Data → Retail → Homes → Irrigation</p>
</button>
<button class="policy-card" data-policy="commercial">
<header><h3>Commercial first</h3><span class="radio"></span></header>
<p>Prioritize revenue-bearing commercial and data-center demand.</p>
<p class="order">Retail → Data → Hospital → Water → Homes → Irrigation</p>
</button>
<button class="policy-card" data-policy="equal">
<header><h3>Equal service</h3><span class="radio"></span></header>
<p>Give every individual customer the same percentage of requested demand.</p>
<p class="order">Hospital = Water = Data = Retail = Homes = Irrigation</p>
</button>
</section>
<section class="section">
<div class="section-title">
<h2>Outcome comparison</h2>
<span class="lock-badge">SAME HOUR + SUPPLY</span>
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Policy</th>
<th title="Unserved MWh in this one-hour snapshot">Unser.</th>
<th title="Critical load served">Crit.</th>
<th title="Residential demand served">Homes</th>
<th title="Flexible irrigation demand served">Flex</th>
<th title="Worst-served individual customer">Min</th>
</tr>
</thead>
<tbody id="outcomeRows"></tbody>
</table>
</div>
<div class="burden" id="burdenBars"></div>
<div class="callout" id="tradeoffCallout" aria-live="polite"></div>
</section>
<section class="section">
<div class="section-title"><h2>Model assumptions</h2></div>
<p class="method">
One-hour dispatch snapshot. No transmission congestion, losses, ramping, or
distribution constraints. All sources connect to the same bus. Battery energy is
treated as available for this snapshot. A policy cannot create energy: it only
changes who receives the identical available supply. “Unser.” is MWh over the
selected one-hour interval.
</p>
</section>
</aside>
</main>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
/* --------------------------------------------------------------------------
State and scenario
--------------------------------------------------------------------------- */
const state = {
hour: 14,
demandScale: 1,
policy: "essential"
};
const sourceDefs = [
{ id: "solar", name: "Solar", x: -6, z: -5, capacity: 5.2 },
{ id: "wind", name: "Wind", x: 6, z: -5, capacity: 4.2 },
{ id: "battery", name: "Battery", x: 0, z: 6, capacity: 4.0 },
{ id: "diesel", name: "Diesel", x: -6, z: 5, capacity: 3.0 }
];
const loadDefs = [
{ id: "hospital", name: "Hospital", priority: "critical", demand: 1.6, x: -3, z: -2, type: "hospital" },
{ id: "water", name: "Water plant",priority: "critical", demand: 0.8, x: -1, z: -4, type: "water" },
{ id: "data", name: "Data center",priority: "high", demand: 4.8, x: 4, z: -2, type: "data" },
{ id: "retail", name: "Retail", priority: "high", demand: 5.2, x: -3, z: 3, type: "retail" },
{ id: "homes", name: "Homes", priority: "normal", demand: 4.1, x: 4, z: 3, type: "homes" },
{ id: "irrigation",name: "Irrigation", priority: "flexible", demand: 2.2, x: 1, z: 2, type: "irrigation" }
];
const groups = {
critical: { name: "Critical", ids: ["hospital", "water"], color: "#ff6374" },
high: { name: "High", ids: ["data", "retail"], color: "#70b7ff" },
normal: { name: "Homes", ids: ["homes"], color: "#b39cff" },
flexible: { name: "Flexible", ids: ["irrigation"], color: "#ffc857" }
};
const policies = {
essential: {
name: "Essential",
order: ["hospital", "water", "data", "retail", "homes", "irrigation"]
},
commercial: {
name: "Commercial",
order: ["retail", "data", "hospital", "water", "homes", "irrigation"]
},
equal: {
name: "Equal",
order: null
}
};
function isWindOutage(hour) {
return hour >= 12 && hour < 18;
}
function sourceAvailability(hour) {
const solarFactor = hour <= 6 || hour >= 19
? 0
: Math.max(0, Math.sin(Math.PI * (hour - 6) / 12));
return {
solar: 5.2 * solarFactor,
wind: isWindOutage(hour)
? 0
: 3.0 + 0.6 * Math.sin((hour - 3) / 24 * Math.PI * 2),
battery: hour >= 7 && hour < 20 ? 3.6 : 2.4,
diesel: 3.0
};
}
function allocate(policy, supply, demands) {
const totalDemand = Object.values(demands).reduce((a, b) => a + b, 0);
const served = {};
const order = policies[policy].order;
if (!order) {
const ratio = totalDemand > 0 ? Math.min(1, supply / totalDemand) : 1;
for (const id of Object.keys(demands)) served[id] = demands[id] * ratio;
return served;
}
let remaining = supply;
for (const id of order) {
const amount = Math.min(demands[id], remaining);
served[id] = amount;
remaining -= amount;
}
return served;
}
function groupMetrics(served, demands) {
const result = {};
for (const [key, group] of Object.entries(groups)) {
const demand = group.ids.reduce((n, id) => n + demands[id], 0);
const servedMW = group.ids.reduce((n, id) => n + served[id], 0);
result[key] = {
demand,
served: servedMW,
unserved: demand - servedMW,
pct: demand > 0 ? servedMW / demand * 100 : 100
};
}
return result;
}
function computeSimulation() {
const availability = sourceAvailability(state.hour);
const totalAvailable = Object.values(availability).reduce((a, b) => a + b, 0);
const demands = {};
for (const load of loadDefs) demands[load.id] = load.demand * state.demandScale;
const totalDemand = Object.values(demands).reduce((a, b) => a + b, 0);
const served = allocate(state.policy, totalAvailable, demands);
const totalServed = Object.values(served).reduce((a, b) => a + b, 0);
const totalUnserved = Math.max(0, totalDemand - totalServed);
const individualRatios = loadDefs.map(load => served[load.id] / demands[load.id]);
const worst = Math.min(...individualRatios) * 100;
const dispatched = {};
for (const source of sourceDefs) {
dispatched[source.id] = totalAvailable > totalDemand
? availability[source.id] * totalDemand / totalAvailable
: availability[source.id];
}
return {
availability,
dispatched,
demands,
served,
totalAvailable,
totalDemand,
totalServed,
totalUnserved,
groups: groupMetrics(served, demands),
worst
};
}
/* --------------------------------------------------------------------------
Three.js scene
--------------------------------------------------------------------------- */
const viewport = document.getElementById("viewport");
const labelLayer = document.getElementById("labels");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0b151c);
scene.fog = new THREE.Fog(0x0b151c, 28, 52);
const camera = new THREE.OrthographicCamera(-12, 12, 10.5, -10.5, 0.1, 100);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.domElement.id = "scene-canvas";
viewport.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xd8f1ff, 0x24342c, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 3.1);
sun.position.set(9, 17, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -14;
sun.shadow.camera.right = 14;
sun.shadow.camera.top = 14;
sun.shadow.camera.bottom = -14;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
sun.shadow.bias = -0.0003;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x6eb7ff, 1.0);
rim.position.set(-10, 7, -8);
scene.add(rim);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const labelAnchors = [];
const loadObjects = {};
const sourceObjects = {};
const sourceRoutes = {};
const loadRoutes = {};
const routePulses = [];
function addBox(parent, size, position, color, options = {}) {
const material = new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.82,
metalness: options.metalness ?? 0,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1
});
const mesh = new THREE.Mesh(unitBox, material);
mesh.scale.set(size[0], size[1], size[2]);
mesh.position.set(position[0], position[1], position[2]);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
parent.add(mesh);
return mesh;
}
function makeWorldLabel(text, className = "") {
const el = document.createElement("div");
el.className = `world-label ${className}`;
el.innerHTML = text;
labelLayer.appendChild(el);
return el;
}
function statusClass(ratio) {
if (ratio >= 0.999) return "";
if (ratio > 0) return "partial";
return "unserved";
}
/* Ground, roads and grid */
addBox(scene, [17.2, 0.56, 17.2], [0, -0.42, 0], 0x14272d);
addBox(scene, [16.7, 0.18, 16.7], [0, -0.08, 0], 0x29413e);
addBox(scene, [15.8, 0.05, 1.15], [0, 0.045, 0], 0x172a31);
addBox(scene, [1.05, 0.05, 15.8], [0, 0.05, 0], 0x172a31);
const gridPositions = [];
for (let i = -7; i <= 7; i++) {
gridPositions.push(i, 0.075, -7.7, i, 0.075, 7.7);
gridPositions.push(-7.7, 0.075, i, 7.7, 0.075, i);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute("position", new THREE.Float32BufferAttribute(gridPositions, 3));
const gridMaterial = new THREE.LineBasicMaterial({
color: 0x9bc1bd,
transparent: true,
opacity: 0.075
});
scene.add(new THREE.LineSegments(gridGeometry, gridMaterial));
for (let i = -8; i <= 8; i += 2) {
addBox(scene, [0.12, 0.48, 0.12], [i, 0.25, -8], 0x527078, { castShadow: false });
addBox(scene, [0.12, 0.48, 0.12], [i, 0.25, 8], 0x527078, { castShadow: false });
addBox(scene, [0.12, 0.48, 0.12], [-8, 0.25, i], 0x527078, { castShadow: false });
addBox(scene, [0.12, 0.48, 0.12], [ 8, 0.25, i], 0x527078, { castShadow: false });
}
addBox(scene, [16.1, 0.08, 0.08], [0, 0.43, -8], 0x607980);
addBox(scene, [16.1, 0.08, 0.08], [0, 0.43, 8], 0x607980);
addBox(scene, [0.08, 0.08, 16.1], [-8, 0.43, 0], 0x607980);
addBox(scene, [0.08, 0.08, 16.1], [ 8, 0.43, 0], 0x607980);
/* Central bus / substation */
const busGroup = new THREE.Group();
scene.add(busGroup);
addBox(busGroup, [2.5, 0.2, 2.5], [0, 0.14, 0], 0x53676a);
addBox(busGroup, [0.8, 1.15, 0.7], [-0.55, 0.78, 0], 0x9baeb0, { metalness: 0.25 });
addBox(busGroup, [0.8, 0.9, 0.7], [0.55, 0.67, 0.35], 0x71898e, { metalness: 0.3 });
addBox(busGroup, [0.38, 0.38, 0.38], [0.25, 1.5, -0.35], 0x5ee7a7, {
emissive: 0x2ed889,
emissiveIntensity: 1.4
});
addBox(busGroup, [2.2, 0.08, 0.08], [0, 0.32, 0], 0xb4c9c8);
addBox(busGroup, [0.08, 0.08, 2.2], [0, 0.32, 0], 0xb4c9c8);
/* Source visuals */
function createSolar(def) {
const group = new THREE.Group();
group.position.set(def.x, 0, def.z);
scene.add(group);
addBox(group, [3.3, 0.18, 2.5], [0, 0.13, 0], 0x526a63);
for (const x of [-0.8, 0.8]) {
for (const z of [-0.55, 0.55]) {
const panel = addBox(group, [1.35, 0.12, 0.85], [x, 0.67, z], 0x315b83, {
roughness: 0.35,
metalness: 0.25
});
panel.rotation.x = -0.32;
addBox(group, [0.09, 0.5, 0.09], [x, 0.36, z], 0x8ca2a2);
}
}
const lamp = addBox(group, [0.25, 0.25, 0.25], [1.25, 1.15, -0.8], 0x5ee7a7, {
emissive: 0x2ed889,
emissiveIntensity: 1.2
});
const label = makeWorldLabel("Solar", "source-label");
labelAnchors.push({ el: label, position: new THREE.Vector3(def.x, 2.0, def.z) });
return { group, label, lamp };
}
function createWind(def) {
const group = new THREE.Group();
group.position.set(def.x, 0, def.z);
scene.add(group);
addBox(group, [3.0, 0.18, 2.6], [0, 0.13, 0], 0x526a63);
addBox(group, [0.2, 3.0, 0.2], [0, 1.65, 0], 0xc5d2d1);
addBox(group, [0.55, 0.3, 0.4], [0, 3.1, 0], 0xd8e1df);
const rotor = new THREE.Group();
rotor.position.set(0, 3.1, 0.22);
group.add(rotor);
for (let i = 0; i < 3; i++) {
const pivot = new THREE.Group();
pivot.rotation.z = i * Math.PI * 2 / 3;
rotor.add(pivot);
addBox(pivot, [0.16, 1.35, 0.13], [0, 0.64, 0], 0xe7eeee);
}
addBox(rotor, [0.28, 0.28, 0.25], [0, 0, 0], 0xffc857);
const outage = new THREE.Group();
group.add(outage);
const x1 = addBox(outage, [1.65, 0.16, 0.16], [0, 1.75, 0.32], 0xff6374, {
emissive: 0x8e1527,
emissiveIntensity: 0.6
});
const x2 = addBox(outage, [1.65, 0.16, 0.16], [0, 1.75, 0.32], 0xff6374, {
emissive: 0x8e1527,
emissiveIntensity: 0.6
});
x1.rotation.z = Math.PI / 4;
x2.rotation.z = -Math.PI / 4;
outage.visible = false;
const label = makeWorldLabel("Wind", "source-label");
labelAnchors.push({ el: label, position: new THREE.Vector3(def.x, 4.1, def.z) });
return { group, label, lamp: null, rotor, outage };
}
function createBattery(def) {
const group = new THREE.Group();
group.position.set(def.x, 0, def.z);
scene.add(group);
addBox(group, [3.0, 0.18, 2.3], [0, 0.13, 0], 0x526a63);
for (let i = 0; i < 4; i++) {
const x = -1.0 + (i % 2) * 1.25;
const y = i < 2 ? 0.72 : 1.47;
const z = i < 2 ? -0.5 : 0.5;
addBox(group, [1.0, 1.12, 0.9], [x, y, z], 0x3e806a, {
emissive: 0x143c2f,
emissiveIntensity: 0.35
});
addBox(group, [0.55, 0.11, 0.08], [x, y + 0.25, z + 0.48], 0x75f1b3, {
emissive: 0x2ed889,
emissiveIntensity: 0.6
});
}
const label = makeWorldLabel("Battery", "source-label");
labelAnchors.push({ el: label, position: new THREE.Vector3(def.x, 2.75, def.z) });
return { group, label, lamp: null };
}
function createDiesel(def) {
const group = new THREE.Group();
group.position.set(def.x, 0, def.z);
scene.add(group);
addBox(group, [3.1, 0.18, 2.7], [0, 0.13, 0], 0x526a63);
addBox(group, [1.55, 0.85, 1.05], [-0.55, 0.65, -0.2], 0xd98b35);
addBox(group, [1.15, 0.62, 1.05], [0.85, 0.53, 0.55], 0x5a6970);
addBox(group, [0.22, 1.4, 0.22], [-0.8, 1.55, -0.4], 0x35464d);
addBox(group, [0.7, 0.35, 0.08], [-0.55, 0.73, 0.36], 0x27373d);
const lamp = addBox(group, [0.22, 0.22, 0.22], [1.05, 1.25, 0.55], 0xffc857, {
emissive: 0x9b5a08,
emissiveIntensity: 0.65
});
const label = makeWorldLabel("Diesel", "source-label");
labelAnchors.push({ el: label, position: new THREE.Vector3(def.x, 2.55, def.z) });
return { group, label, lamp };
}
sourceObjects.solar = createSolar(sourceDefs[0]);
sourceObjects.wind = createWind(sourceDefs[1]);
sourceObjects.battery = createBattery(sourceDefs[2]);
sourceObjects.diesel = createDiesel(sourceDefs[3]);
/* Load visuals */
function createLoad(def) {
const group = new THREE.Group();
group.position.set(def.x, 0, def.z);
scene.add(group);
let statusY = 2.1;
addBox(group, [2.6, 0.16, 2.35], [0, 0.12, 0], 0x536863);
if (def.type === "hospital") {
addBox(group, [1.35, 1.15, 1.45], [-0.15, 0.78, 0], 0xe8eeee);
addBox(group, [0.7, 0.78, 1.2], [0.9, 0.5, 0], 0xd2dddc);
addBox(group, [1.52, 0.15, 1.58], [-0.15, 1.42, 0], 0xff6374);
addBox(group, [0.18, 0.62, 0.08], [-0.15, 0.88, 0.77], 0xff4f62);
addBox(group, [0.58, 0.18, 0.08], [-0.15, 0.88, 0.78], 0xff4f62);
statusY = 2.2;
} else if (def.type === "water") {
addBox(group, [1.15, 1.45, 1.05], [-0.25, 0.86, 0], 0x73b9d1);
addBox(group, [0.9, 0.5, 0.9], [0.85, 0.4, 0.4], 0x91c7da);
addBox(group, [1.45, 0.13, 1.3], [-0.25, 1.65, 0], 0xb4dde7);
addBox(group, [0.16, 0.6, 0.16], [0.55, 1.25, 0.1], 0x527d8b);
statusY = 2.35;
} else if (def.type === "data") {
addBox(group, [1.65, 1.5, 1.35], [-0.25, 0.9, 0], 0x3d6ba8);
addBox(group, [0.65, 0.75, 1.05], [0.9, 0.5, 0.2], 0x537fba);
for (let i = 0; i < 4; i++) {
addBox(group, [0.14, 0.1, 0.06], [-0.75 + i * 0.33, 1.1, 0.71], 0x70b7ff, {
emissive: 0x255e9c,
emissiveIntensity: 0.8
});
}
statusY = 2.45;
} else if (def.type === "retail") {
addBox(group, [1.55, 0.9, 1.25], [-0.45, 0.62, -0.2], 0xd8953c);
addBox(group, [0.95, 1.35, 0.9], [0.8, 0.8, 0.25], 0xe0ad57);
addBox(group, [1.7, 0.14, 1.45], [-0.45, 1.14, -0.2], 0xf3c36f);
addBox(group, [0.7, 0.55, 0.08], [-0.45, 0.65, 0.47], 0x5c8fa0);
statusY = 2.15;
} else if (def.type === "homes") {
const positions = [[-0.75, -0.45], [0.35, -0.5], [0.75, 0.55]];
positions.forEach((p, i) => {
addBox(group, [0.85, 0.65, 0.8], [p[0], 0.48, p[1]], i === 1 ? 0xb69c8a : 0xc7b6a0);
addBox(group, [0.98, 0.18, 0.92], [p[0], 0.9, p[1]], 0x735d70);
addBox(group, [0.18, 0.3, 0.07], [p[0], 0.5, p[1] + 0.42], 0xffd88a, {
emissive: 0x6e4611,
emissiveIntensity: 0.25
});
});
statusY = 1.75;
} else if (def.type === "irrigation") {
addBox(group, [1.65, 0.16, 1.4], [-0.25, 0.32, 0], 0x426f4e);
for (let i = 0; i < 4; i++) {
addBox(group, [0.12, 0.18, 1.2], [-0.8 + i * 0.36, 0.48, 0], 0x70b66f);
}
addBox(group, [0.6, 0.75, 0.6], [0.95, 0.55, 0.2], 0x5a8ca0);
addBox(group, [0.14, 1.1, 0.14], [1.2, 0.8, -0.4], 0x8aa5aa);
statusY = 1.65;
}
const statusBack = addBox(group, [1.65, 0.16, 0.28], [0, statusY, 0], 0x172229);
const statusFill = addBox(group, [1.55, 0.11, 0.19], [0, statusY, 0], 0x5ee7a7, {
emissive: 0x163d2d,
emissiveIntensity: 0.45
});
const beacon = addBox(group, [0.24, 0.24, 0.24], [0, statusY + 0.42, 0], 0xff6374, {
emissive: 0x8d1528,
emissiveIntensity: 0.9
});
beacon.visible = false;
const label = makeWorldLabel(def.name);
labelAnchors.push({
el: label,
position: new THREE.Vector3(def.x, statusY + 0.75, def.z)
});
return { group, label, statusBack, statusFill, beacon, statusY, def };
}
for (const load of loadDefs) loadObjects[load.id] = createLoad(load);
/* Orthogonal power routes with animated voxel pulses */
function createRoute(points, color, pulseCount = 4) {
const vectors = points.map(p => new THREE.Vector3(...p));
const geometry = new THREE.BufferGeometry().setFromPoints(vectors);
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.38
});
const line = new THREE.Line(geometry, material);
scene.add(line);
const lengths = [];
let totalLength = 0;
for (let i = 0; i < vectors.length - 1; i++) {
const length = vectors[i].distanceTo(vectors[i + 1]);
lengths.push(length);
totalLength += length;
}
const pulses = [];
for (let i = 0; i < pulseCount; i++) {
const mesh = new THREE.Mesh(
unitBox,
new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.95 })
);
mesh.scale.set(0.16, 0.16, 0.16);
scene.add(mesh);
pulses.push({ mesh, phase: i / pulseCount, speed: 0.12 + (i % 3) * 0.012 });
}
const route = { vectors, lengths, totalLength, line, pulses };
routePulses.push(route);
return route;
}
function routePoint(route, t) {
let distance = ((t % 1) + 1) % 1 * route.totalLength;
for (let i = 0; i < route.lengths.length; i++) {
if (distance <= route.lengths[i]) {
const alpha = route.lengths[i] === 0 ? 0 : distance / route.lengths[i];
return route.vectors[i].clone().lerp(route.vectors[i + 1], alpha);
}
distance -= route.lengths[i];
}
return route.vectors.at(-1).clone();
}
for (const source of sourceDefs) {
sourceRoutes[source.id] = createRoute([
[source.x, 0.22, source.z],
[source.x, 0.22, 0],
[0, 0.22, 0]
], 0x5ee7a7, 5);
}
for (const load of loadDefs) {
loadRoutes[load.id] = createRoute([
[0, 0.22, 0],
[load.x, 0.22, 0],
[load.x, 0.22, load.z]
], 0x5ee7a7, 4);
}
/* --------------------------------------------------------------------------
Camera controls — implemented without Three.js addons
--------------------------------------------------------------------------- */
const orbit = {
theta: 0.69,
phi: 0.84,
radius: 28,
target: new THREE.Vector3(0, 0, 0)
};
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
}
updateCamera();
function resetCamera() {
orbit.theta = 0.69;
orbit.phi = 0.84;
orbit.radius = 28;
camera.zoom = 1;
camera.updateProjectionMatrix();
updateCamera();
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(orbit.phi + dy * 0.005, 0.52, 1.25);
updateCamera();
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
camera.zoom = THREE.MathUtils.clamp(camera.zoom * Math.exp(-event.deltaY * 0.001), 0.65, 1.8);
camera.updateProjectionMatrix();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
document.getElementById("resetView").addEventListener("click", resetCamera);
function resize() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
const aspect = width / Math.max(1, height);
const halfHeight = 10.5;
camera.left = -halfHeight * aspect;
camera.right = halfHeight * aspect;
camera.top = halfHeight;
camera.bottom = -halfHeight;
camera.updateProjectionMatrix();
renderer.setSize(width, height, false);
}
window.addEventListener("resize", resize);
resize();
/* --------------------------------------------------------------------------
UI updates
--------------------------------------------------------------------------- */
const sourceRows = {};
document.querySelectorAll(".source-row").forEach(row => {
sourceRows[row.dataset.source] = row;
});
function updateSourceUI(sim) {
for (const source of sourceDefs) {
const available = sim.availability[source.id];
const row = sourceRows[source.id];
const bar = row.querySelector("i");
const amount = row.querySelector(".amount");
const offline = available <= 0.001;
row.classList.toggle("offline", offline);
bar.style.width = `${Math.max(0, available / source.capacity * 100)}%`;
amount.textContent = offline ? "OFFLINE" : `${available.toFixed(1)} MW`;
const object = sourceObjects[source.id];
const color = offline ? "#ff6374" : "#5ee7a7";
object.label.innerHTML =
`<span class="dot ${offline ? "offline" : ""}"></span>${source.name}` +
`<b>${offline ? "OFFLINE" : `${available.toFixed(1)} / ${source.capacity.toFixed(1)} MW`}</b>`;
if (object.lamp) {
object.lamp.material.color.setHex(offline ? 0xff6374 : source.id === "diesel" ? 0xffc857 : 0x5ee7a7);
object.lamp.material.emissive.setHex(offline ? 0x8d1528 : source.id === "diesel" ? 0x7a4509 : 0x2ed889);
}
}
}
function updateLoadWorld(sim) {
for (const load of loadDefs) {
const object = loadObjects[load.id];
const demand = sim.demands[load.id];
const served = sim.served[load.id];
const ratio = demand > 0 ? served / demand : 1;
object.statusFill.scale.x = 1.55 * Math.max(0.001, ratio);
object.statusFill.position.x = -0.775 + 0.775 * Math.max(0.001, ratio);
const color = ratio >= 0.999 ? 0x5ee7a7 : ratio > 0 ? 0xffc857 : 0xff6374;
object.statusFill.material.color.setHex(color);
object.statusFill.material.emissive.setHex(ratio >= 0.999 ? 0x163d2d : ratio > 0 ? 0x62450b : 0x59121d);
object.beacon.visible = ratio < 0.999;
object.label.innerHTML =
`<span class="dot ${statusClass(ratio)}"></span>${load.name}` +
`<b>${served.toFixed(1)} / ${demand.toFixed(1)} MW</b>`;
}
}
function policyOutcome(policy, sim) {
const served = allocate(policy, sim.totalAvailable, sim.demands);
const groupsForPolicy = groupMetrics(served, sim.demands);
const totalServed = Object.values(served).reduce((a, b) => a + b, 0);
const worst = Math.min(...loadDefs.map(load => served[load.id] / sim.demands[load.id])) * 100;
return {
served,
groups: groupsForPolicy,
unserved: Math.max(0, sim.totalDemand - totalServed),
worst
};
}
function updateComparisonTable(sim) {
const rows = [];
for (const [id, policy] of Object.entries(policies)) {
const outcome = policyOutcome(id, sim);
rows.push(`
<tr data-policy="${id}" class="${id === state.policy ? "selected" : ""}">
<td><strong>${policy.name}</strong></td>
<td>${outcome.unserved.toFixed(1)}</td>
<td>${outcome.groups.critical.pct.toFixed(0)}%</td>
<td>${outcome.groups.normal.pct.toFixed(0)}%</td>
<td>${outcome.groups.flexible.pct.toFixed(0)}%</td>
<td>${outcome.worst.toFixed(0)}%</td>
</tr>
`);
}
document.getElementById("outcomeRows").innerHTML = rows.join("");
}
function updateBurden(sim) {
const selected = policyOutcome(state.policy, sim);
document.getElementById("burdenBars").innerHTML = Object.entries(groups).map(([key, group]) => {
const metric = selected.groups[key];
const width = metric.demand > 0 ? metric.unserved / metric.demand * 100 : 0;
return `
<div class="burden-row">
<span>${group.name}</span>
<div class="burden-track"><i style="width:${width}%;background:${group.color}"></i></div>
<span class="burden-value">${metric.unserved.toFixed(1)} MWh</span>
</div>
`;
}).join("");
}
function updateCallout(sim) {
const selected = policyOutcome(state.policy, sim);
const critical = selected.groups.critical.pct;
const homes = selected.groups.normal.pct;
const flex = selected.groups.flexible.pct;
let detail;
if (state.policy === "essential") {
detail = `Essential demand receives <strong>${critical.toFixed(0)}%</strong> service.
Later blocks absorb curtailment: homes receive ${homes.toFixed(0)}% and irrigation ${flex.toFixed(0)}%.`;
} else if (state.policy === "commercial") {
detail = `Commercial demand is protected first, but critical demand receives only
<strong>${critical.toFixed(0)}%</strong>. Homes receive ${homes.toFixed(0)}% and irrigation ${flex.toFixed(0)}%.`;
} else {
detail = `Every individual load receives <strong>${selected.worst.toFixed(0)}%</strong>
of requested demand. This is even across customers, but critical service is not prioritized.`;
}
document.getElementById("tradeoffCallout").innerHTML =
`${detail}<br><br><strong>Total unserved energy is ${sim.totalUnserved.toFixed(1)} MWh
for every policy in this snapshot.</strong> The policy changes who bears the shortage, not its size.`;
}
function updateUI(sim) {
document.getElementById("supplyValue").textContent = `${sim.totalAvailable.toFixed(1)} MW`;
document.getElementById("demandValue").textContent = `${sim.totalDemand.toFixed(1)} MW`;
document.getElementById("shortfallValue").textContent = `${sim.totalUnserved.toFixed(1)} MW`;
const time = `${String(state.hour).padStart(2, "0")}:00`;
document.getElementById("timeOutput").textContent = time;
document.getElementById("demandOutput").textContent = `${Math.round(state.demandScale * 100)}%`;
const outageActive = isWindOutage(state.hour);
document.getElementById("outageBanner").style.opacity = outageActive ? "1" : ".48";
document.querySelector("#outageBanner strong").textContent =
outageActive ? "WIND FARM OUTAGE" : "OUTAGE WINDOW INACTIVE";
document.querySelectorAll(".policy-card").forEach(card => {
card.classList.toggle("active", card.dataset.policy === state.policy);
});
updateSourceUI(sim);
updateLoadWorld(sim);
updateComparisonTable(sim);
updateBurden(sim);
updateCallout(sim);
}
/* --------------------------------------------------------------------------
Interaction
--------------------------------------------------------------------------- */
document.querySelectorAll(".policy-card").forEach(card => {
card.addEventListener("click", () => {
state.policy = card.dataset.policy;
refresh();
});
});
document.getElementById("outcomeRows").addEventListener("click", event => {
const row = event.target.closest("tr[data-policy]");
if (!row) return;
state.policy = row.dataset.policy;
refresh();
});
document.getElementById("timeSlider").addEventListener("input", event => {
state.hour = Number(event.target.value);
refresh();
});
document.getElementById("demandSlider").addEventListener("input", event => {
state.demandScale = Number(event.target.value) / 100;
refresh();
});
let playTimer = null;
const playButton = document.getElementById("playButton");
function togglePlayback() {
if (playTimer) {
clearInterval(playTimer);
playTimer = null;
playButton.textContent = "▶";
playButton.classList.remove("playing");
} else {
playTimer = setInterval(() => {
state.hour = (state.hour + 1) % 24;
document.getElementById("timeSlider").value = state.hour;
refresh();
}, 850);
playButton.textContent = "Ⅱ";
playButton.classList.add("playing");
}
}
playButton.addEventListener("click", togglePlayback);
/* --------------------------------------------------------------------------
Animation and simulation refresh
--------------------------------------------------------------------------- */
function refresh() {
updateUI(computeSimulation());
}
const clock = new THREE.Clock();
function animate() {
const elapsed = clock.getElapsedTime();
const sim = computeSimulation();
for (const source of sourceDefs) {
const route = sourceRoutes[source.id];
const available = sim.availability[source.id];
const dispatchedRatio = source.capacity > 0 ? sim.dispatched[source.id] / source.capacity : 0;
const color = available <= 0.001 ? 0xff6374 : 0x5ee7a7;
route.line.material.color.setHex(color);
route.pulses.forEach((pulse, index) => {
pulse.mesh.visible = index < Math.ceil(dispatchedRatio * route.pulses.length);
pulse.mesh.material.color.setHex(color);
pulse.mesh.position.copy(routePoint(route, elapsed * pulse.speed + pulse.phase));
pulse.mesh.position.y += 0.12;
});
}
for (const load of loadDefs) {
const route = loadRoutes[load.id];
const ratio = sim.served[load.id] / sim.demands[load.id];
const color = ratio >= 0.999 ? 0x5ee7a7 : ratio > 0 ? 0xffc857 : 0xff6374;
route.line.material.color.setHex(color);
route.pulses.forEach((pulse, index) => {
pulse.mesh.visible = index < Math.ceil(ratio * route.pulses.length);
pulse.mesh.material.color.setHex(color);
pulse.mesh.position.copy(routePoint(route, elapsed * pulse.speed + pulse.phase));
pulse.mesh.position.y += 0.12;
});
const beacon = loadObjects[load.id].beacon;
if (beacon.visible) {
const scale = 1 + Math.sin(elapsed * 4 + load.x) * 0.12;
beacon.scale.set(0.24 * scale, 0.24 * scale, 0.24 * scale);
beacon.rotation.y = elapsed * 0.8;
}
}
const busPulse = 1 + Math.sin(elapsed * 2.6) * 0.05;
busGroup.children[4].scale.set(0.38 * busPulse, 0.38 * busPulse, 0.38 * busPulse);
const width = viewport.clientWidth;
const height = viewport.clientHeight;
for (const anchor of labelAnchors) {
const projected = anchor.position.clone().project(camera);
const visible = projected.z > -1 && projected.z < 1;
anchor.el.style.display = visible ? "block" : "none";
anchor.el.style.left = `${(projected.x * 0.5 + 0.5) * width}px`;
anchor.el.style.top = `${(-projected.y * 0.5 + 0.5) * height}px`;
}
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
refresh();
animate();
</script>
</body>
</html>
```