Prompt specification
Build or customize the Three.js 3D scene "One Load Turns On in a Toy Grid" 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: One Load Turns On in a Toy Grid
Category: Everyday & Industrial · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/one-load-turns-on-in-a-toy-grid-x3930
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring a small technical cutaway of a toy electricity network. A controllable source feeds two existing loads and a third load that the user can switch on. Show generation and demand as separate labeled power values, with a clear link from each building to the source. When the extra load starts, expose the temporary unmet demand before the source adjusts according to a stated simple rule. Do not represent that imbalance as a realistic grid-frequency simulation. Use transparent building shells to reveal the connected devices, and keep the arithmetic visible beside the network. Reset should restore the original load and generation settings.
Working Three.js Starter (one-load-turns-on-in-a-toy-grid-x3930):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Toy Electricity Network — Technical Cutaway</title>
<style>
:root {
--ink: #14263d;
--muted: #61738a;
--line: #dce5ee;
--paper: #ffffff;
--scene: #edf3f8;
--teal: #159c94;
--blue: #4678dc;
--orange: #e48a32;
--red: #d94c5c;
--green: #278566;
--shadow: 0 18px 45px rgba(31, 57, 83, 0.12);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
min-height: 100%;
margin: 0;
}
body {
color: var(--ink);
background: var(--scene);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.app {
display: grid;
grid-template-columns: minmax(0, 1fr) 390px;
min-height: 100vh;
}
.scene-panel {
position: relative;
min-width: 0;
height: 100vh;
overflow: hidden;
background:
radial-gradient(circle at 45% 42%, rgba(255, 255, 255, 0.95), transparent 46%),
var(--scene);
}
#viewport,
#labels {
position: absolute;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
outline: none;
}
#viewport canvas:active {
cursor: grabbing;
}
#labels {
pointer-events: none;
overflow: hidden;
}
.scene-header {
position: absolute;
top: 24px;
left: 26px;
right: 26px;
z-index: 5;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
pointer-events: none;
}
.eyebrow {
margin: 0 0 7px;
color: var(--teal);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.scene-header h1 {
margin: 0;
font-size: clamp(24px, 3vw, 38px);
line-height: 1;
letter-spacing: -0.045em;
}
.scene-header .subtitle {
max-width: 560px;
margin: 9px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.model-badge {
flex: 0 0 auto;
padding: 9px 12px;
border: 1px solid rgba(20, 38, 61, 0.12);
border-radius: 999px;
color: #455b72;
background: rgba(255, 255, 255, 0.74);
box-shadow: 0 5px 16px rgba(31, 57, 83, 0.06);
backdrop-filter: blur(8px);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.scene-footer {
position: absolute;
z-index: 6;
left: 26px;
right: 26px;
bottom: 22px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
pointer-events: none;
}
.scene-hint,
.legend {
border: 1px solid rgba(20, 38, 61, 0.1);
border-radius: 12px;
background: rgba(255, 255, 255, 0.8);
box-shadow: 0 6px 20px rgba(31, 57, 83, 0.07);
backdrop-filter: blur(9px);
color: var(--muted);
font-size: 11px;
}
.scene-hint {
padding: 9px 12px;
}
.legend {
display: flex;
gap: 14px;
padding: 9px 12px;
}
.legend span {
display: flex;
align-items: center;
gap: 6px;
white-space: nowrap;
}
.legend i {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--dot);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--dot) 18%, transparent);
}
.view-button {
pointer-events: auto;
border: 1px solid rgba(20, 38, 61, 0.13);
border-radius: 11px;
padding: 9px 13px;
background: rgba(255, 255, 255, 0.9);
box-shadow: 0 6px 20px rgba(31, 57, 83, 0.07);
cursor: pointer;
font-size: 12px;
font-weight: 750;
}
.world-label {
position: absolute;
z-index: 4;
min-width: 118px;
padding: 9px 11px;
transform: translate(-50%, -100%);
border: 1px solid rgba(20, 38, 61, 0.14);
border-top: 3px solid var(--tag, var(--teal));
border-radius: 10px;
background: rgba(255, 255, 255, 0.91);
box-shadow: 0 8px 22px rgba(31, 57, 83, 0.13);
backdrop-filter: blur(8px);
transition: border-color 160ms ease, background 160ms ease;
}
.world-label::after {
content: "";
position: absolute;
left: 50%;
bottom: -9px;
width: 1px;
height: 8px;
background: rgba(20, 38, 61, 0.25);
}
.world-label .label-kicker {
margin-bottom: 2px;
color: var(--muted);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.world-label strong {
display: block;
font-size: 17px;
line-height: 1.1;
letter-spacing: -0.03em;
}
.world-label small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
line-height: 1.3;
}
.world-label.link-label {
min-width: 0;
padding: 5px 8px;
border: 1px solid color-mix(in srgb, var(--tag) 35%, white);
border-left: 3px solid var(--tag);
border-radius: 7px;
color: var(--tag);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.03em;
white-space: nowrap;
}
.world-label.link-label::after {
display: none;
}
.world-label.short {
border-color: rgba(217, 76, 92, 0.48);
background: rgba(255, 244, 245, 0.96);
}
.ledger {
position: relative;
z-index: 10;
height: 100vh;
overflow-y: auto;
padding: 24px 22px 26px;
border-left: 1px solid #d8e2eb;
background: rgba(255, 255, 255, 0.97);
box-shadow: -10px 0 35px rgba(31, 57, 83, 0.055);
}
.ledger-top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 17px;
}
.ledger h2 {
margin: 0;
font-size: 20px;
letter-spacing: -0.035em;
}
.ledger-subtitle {
margin: 5px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.live-dot {
display: flex;
flex: 0 0 auto;
align-items: center;
gap: 6px;
margin-top: 3px;
color: var(--green);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.live-dot::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 0 4px rgba(39, 133, 102, 0.11);
}
.status-card {
position: relative;
overflow: hidden;
padding: 15px;
border: 1px solid #cfe8df;
border-radius: 14px;
background: #f2fbf7;
transition: border-color 180ms ease, background 180ms ease;
}
.status-card.short {
border-color: #f0c4ca;
background: #fff5f6;
}
.status-card.pending {
border-color: #efd4b5;
background: #fff9f0;
}
.status-top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.status-kicker {
color: var(--green);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.status-card.short .status-kicker {
color: var(--red);
}
.status-card.pending .status-kicker {
color: #ad6b22;
}
.status-value {
margin-top: 5px;
font-size: 22px;
font-weight: 850;
letter-spacing: -0.04em;
}
.status-card.short .status-value {
color: var(--red);
}
.status-detail {
margin: 7px 0 0;
color: #596c80;
font-size: 11px;
line-height: 1.5;
}
.progress-track {
height: 4px;
margin-top: 12px;
overflow: hidden;
border-radius: 999px;
background: rgba(173, 107, 34, 0.13);
}
.progress-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: var(--orange);
}
.readouts {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-top: 12px;
}
.readout {
padding: 12px;
border: 1px solid var(--line);
border-radius: 12px;
background: #fbfcfd;
}
.readout .readout-label {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.readout strong {
display: block;
margin-top: 6px;
font-size: 25px;
letter-spacing: -0.045em;
}
.readout.generation strong {
color: var(--orange);
}
.readout.demand strong {
color: var(--blue);
}
.readout small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin: 20px 0 9px;
}
.section-title h3 {
margin: 0;
font-size: 12px;
letter-spacing: -0.01em;
}
.section-title span {
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.arithmetic {
overflow: hidden;
border: 1px solid var(--line);
border-radius: 13px;
background: #fbfcfd;
}
.equation-row {
display: grid;
grid-template-columns: 80px 1fr auto;
align-items: center;
gap: 8px;
padding: 10px 12px;
border-bottom: 1px solid #e8edf2;
font-size: 11px;
}
.equation-row:last-child {
border-bottom: 0;
}
.equation-row .eq-label {
color: var(--muted);
font-weight: 700;
}
.equation-row code {
color: #354b63;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
}
.equation-row b {
font-size: 11px;
white-space: nowrap;
}
.equation-row.unmet b {
color: var(--red);
}
.equation-row.spare b {
color: var(--green);
}
.load-table {
width: 100%;
border-collapse: collapse;
font-size: 11px;
}
.load-table th {
padding: 8px 10px;
border-bottom: 1px solid var(--line);
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.04em;
text-align: right;
text-transform: uppercase;
}
.load-table th:first-child,
.load-table td:first-child {
text-align: left;
}
.load-table td {
padding: 10px;
border-bottom: 1px solid #edf1f4;
text-align: right;
}
.load-table tr:last-child td {
border-bottom: 0;
}
.load-name {
display: flex;
align-items: center;
gap: 7px;
font-weight: 750;
}
.load-name i {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--dot);
}
.load-table .total td {
color: var(--ink);
font-weight: 850;
background: #f7f9fb;
}
.control-card {
padding: 13px;
border: 1px solid var(--line);
border-radius: 13px;
background: #fbfcfd;
}
.control-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 9px;
}
.control-head label,
.control-head strong {
font-size: 11px;
}
.control-head output {
color: var(--orange);
font-size: 14px;
font-weight: 850;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 8px 0 10px;
border-radius: 999px;
accent-color: var(--orange);
cursor: pointer;
}
.stepper {
display: grid;
grid-template-columns: 34px 1fr 34px;
align-items: center;
gap: 7px;
}
.stepper button {
height: 30px;
border: 1px solid var(--line);
border-radius: 8px;
background: white;
cursor: pointer;
font-size: 16px;
}
.stepper span {
color: var(--muted);
font-size: 9px;
text-align: center;
}
.switch-control {
margin-top: 10px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 13px;
background: #fbfcfd;
}
.switch-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.switch-copy strong {
display: block;
font-size: 11px;
}
.switch-copy small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
}
.switch-button {
position: relative;
width: 48px;
height: 27px;
flex: 0 0 auto;
border: 0;
border-radius: 999px;
background: #cbd5df;
cursor: pointer;
transition: background 180ms ease;
}
.switch-button::after {
content: "";
position: absolute;
top: 4px;
left: 4px;
width: 19px;
height: 19px;
border-radius: 50%;
background: white;
box-shadow: 0 2px 7px rgba(20, 38, 61, 0.2);
transition: transform 180ms ease;
}
.switch-button[aria-pressed="true"] {
background: var(--orange);
}
.switch-button[aria-pressed="true"]::after {
transform: translateX(21px);
}
.switch-state {
margin-top: 9px;
color: var(--muted);
font-size: 10px;
line-height: 1.4;
}
.rule-note {
margin-top: 13px;
padding: 12px 13px;
border-left: 3px solid var(--orange);
border-radius: 0 10px 10px 0;
background: #fff9f0;
color: #5d6170;
font-size: 10px;
line-height: 1.55;
}
.rule-note strong {
color: #354253;
}
.no-frequency {
display: flex;
gap: 8px;
margin-top: 12px;
padding: 10px 11px;
border: 1px dashed #cfd9e3;
border-radius: 10px;
color: var(--muted);
font-size: 9px;
line-height: 1.45;
}
.no-frequency b {
color: var(--ink);
}
.reset-button {
width: 100%;
margin-top: 14px;
padding: 11px 14px;
border: 0;
border-radius: 11px;
color: white;
background: var(--ink);
cursor: pointer;
font-size: 11px;
font-weight: 800;
transition: transform 150ms ease, background 150ms ease;
}
.reset-button:hover {
background: #203a58;
transform: translateY(-1px);
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
@media (max-width: 900px) {
.app {
grid-template-columns: 1fr;
}
.scene-panel {
height: 62vh;
min-height: 480px;
}
.ledger {
height: auto;
overflow: visible;
border-top: 1px solid var(--line);
border-left: 0;
}
.scene-header {
top: 18px;
left: 18px;
right: 18px;
}
.model-badge {
display: none;
}
.scene-footer {
left: 18px;
right: 18px;
bottom: 14px;
}
.legend {
display: none;
}
}
@media (max-width: 520px) {
.scene-panel {
min-height: 500px;
}
.scene-header h1 {
font-size: 27px;
}
.scene-header .subtitle {
max-width: 310px;
font-size: 11px;
}
.world-label {
min-width: 96px;
padding: 7px 8px;
}
.world-label strong {
font-size: 14px;
}
.world-label.link-label {
font-size: 8px;
}
}
</style>
</head>
<body>
<div class="app">
<main class="scene-panel" aria-label="Interactive three-dimensional electricity network">
<div id="viewport"></div>
<div id="labels" aria-hidden="true"></div>
<header class="scene-header">
<div>
<p class="eyebrow">Technical cutaway / toy network</p>
<h1>Electricity, made visible.</h1>
<p class="subtitle">
One controllable source, two existing loads, and one switchable load.
The colored links show direct source-to-building connections.
</p>
</div>
<div class="model-badge">Power setpoints only · no frequency model</div>
</header>
<footer class="scene-footer">
<div class="scene-hint">Drag to orbit · scroll to zoom · arrow keys also work</div>
<div class="legend" aria-hidden="true">
<span style="--dot: var(--teal)"><i></i>Load A</span>
<span style="--dot: var(--blue)"><i></i>Load B</span>
<span style="--dot: var(--orange)"><i></i>Load C</span>
</div>
<button class="view-button" id="resetView" type="button">Reset view</button>
</footer>
</main>
<aside class="ledger" aria-label="Generation and demand ledger">
<div class="ledger-top">
<div>
<p class="eyebrow">Supply / demand ledger</p>
<h2>Power arithmetic</h2>
<p class="ledger-subtitle">Generation and connected demand are deliberately separate.</p>
</div>
<div class="live-dot">Live values</div>
</div>
<section class="status-card" id="statusCard" aria-live="polite">
<div class="status-top">
<div>
<div class="status-kicker" id="statusKicker">Connected demand balanced</div>
<div class="status-value" id="statusValue">1.00 kW spare</div>
</div>
</div>
<p class="status-detail" id="statusDetail"></p>
<div class="progress-track" id="progressTrack" hidden>
<div class="progress-fill" id="progressFill"></div>
</div>
</section>
<div class="readouts">
<article class="readout generation">
<div class="readout-label">Generation G</div>
<strong id="generationValue">6.00 kW</strong>
<small>source setpoint</small>
</article>
<article class="readout demand">
<div class="readout-label">Demand D</div>
<strong id="demandValue">5.00 kW</strong>
<small>total connected demand</small>
</article>
</div>
<div class="section-title">
<h3>Visible arithmetic</h3>
<span>kilowatts</span>
</div>
<section class="arithmetic" aria-label="Power balance equations">
<div class="equation-row">
<span class="eq-label">Demand</span>
<code id="demandEquation">D = 2.00 + 3.00 + 0.00 = 5.00</code>
<b>kW</b>
</div>
<div class="equation-row">
<span class="eq-label">Generation</span>
<code>G = source setpoint</code>
<b id="generationEquation">6.00 kW</b>
</div>
<div class="equation-row spare">
<span class="eq-label">Spare</span>
<code>max(G − D, 0)</code>
<b id="spareValue">1.00 kW</b>
</div>
<div class="equation-row unmet">
<span class="eq-label">Unmet</span>
<code>max(D − G, 0)</code>
<b id="unmetValue">0.00 kW</b>
</div>
</section>
<div class="section-title">
<h3>Connected loads</h3>
<span>Demand / supplied</span>
</div>
<table class="load-table">
<thead>
<tr>
<th>Load</th>
<th>Demand</th>
<th>Supplied</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="load-name" style="--dot: var(--teal)"><i></i>A · Workshop</span></td>
<td id="rowADemand">2.00</td>
<td id="rowASupplied">2.00</td>
</tr>
<tr>
<td><span class="load-name" style="--dot: var(--blue)"><i></i>B · Homes</span></td>
<td id="rowBDemand">3.00</td>
<td id="rowBSupplied">3.00</td>
</tr>
<tr>
<td><span class="load-name" style="--dot: var(--orange)"><i></i>C · Switchable</span></td>
<td id="rowCDemand">0.00</td>
<td id="rowCSupplied">0.00</td>
</tr>
<tr class="total">
<td>Total</td>
<td id="rowTotalDemand">5.00</td>
<td id="rowTotalSupplied">5.00</td>
</tr>
</tbody>
</table>
<div class="section-title">
<h3>Controls</h3>
<span>manual setpoint</span>
</div>
<section class="control-card">
<div class="control-head">
<label for="sourceRange">Source generation</label>
<output id="sourceOutput" for="sourceRange">6.0 kW</output>
</div>
<input
id="sourceRange"
type="range"
min="0"
max="12"
step="0.5"
value="6"
aria-label="Source generation setpoint in kilowatts"
/>
<div class="stepper">
<button type="button" data-adjust="-0.5" aria-label="Reduce source generation by 0.5 kilowatts">−</button>
<span>0 — 12 kW · half-step control</span>
<button type="button" data-adjust="0.5" aria-label="Increase source generation by 0.5 kilowatts">+</button>
</div>
</section>
<section class="switch-control">
<div class="switch-row">
<div class="switch-copy">
<strong>Load C · Switchable lab</strong>
<small>Adds 2.00 kW when enabled</small>
</div>
<button
class="switch-button"
id="loadSwitch"
type="button"
role="switch"
aria-checked="false"
aria-label="Switch load C on or off"
></button>
</div>
<div class="switch-state" id="switchState">Load C is off. Connected demand is 5.00 kW.</div>
</section>
<div class="rule-note">
<strong>Stated switch-on rule:</strong>
enable C and hold the source setpoint for 2.4 seconds. During that hold,
unmet demand is <strong>D − G</strong>. Then set the source exactly to
<strong>G ← D</strong>. Existing loads A and B have supply priority;
C receives only the remaining generation. A manual source change cancels
the delayed catch-up.
</div>
<div class="no-frequency">
<span>ⓘ</span>
<div>
<b>Not a grid-frequency simulation.</b>
This scene models only instantaneous power setpoints and arithmetic.
Frequency, inertia, protection, and dynamic grid response are intentionally absent.
Moving link markers show direction only.
</div>
</div>
<button class="reset-button" id="resetNetwork" type="button">
Reset network to original settings
</button>
<div class="sr-only" id="announcement" aria-live="assertive"></div>
</aside>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const viewport = document.getElementById("viewport");
const labelLayer = document.getElementById("labels");
const ORIGINAL_GENERATION = 6;
const LOAD_A_DEMAND = 2;
const LOAD_B_DEMAND = 3;
const LOAD_C_DEMAND = 2;
const AUTO_DELAY_MS = 2400;
const COLORS = {
ink: new THREE.Color(0x14263d),
teal: new THREE.Color(0x159c94),
blue: new THREE.Color(0x4678dc),
orange: new THREE.Color(0xe48a32),
red: new THREE.Color(0xd94c5c),
dark: new THREE.Color(0x26384a),
off: new THREE.Color(0x435363)
};
let generation = ORIGINAL_GENERATION;
let loadCOn = false;
let autoAdjust = null;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xedf3f8);
scene.fog = new THREE.Fog(0xedf3f8, 23, 38);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
viewport.appendChild(renderer.domElement);
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"3D toy electricity network. Drag to rotate, use the mouse wheel to zoom."
);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 80);
// Camera controls are implemented here rather than importing an addon.
const cameraState = {
theta: 0.58,
phi: 1.03,
radius: 17.5,
target: new THREE.Vector3(-0.35, 0.85, 0)
};
const desiredCamera = {
theta: cameraState.theta,
phi: cameraState.phi,
radius: cameraState.radius
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z + cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
desiredCamera.theta = 0.58;
desiredCamera.phi = 1.03;
desiredCamera.radius = 17.5;
}
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
desiredCamera.theta -= dx * 0.006;
desiredCamera.phi = THREE.MathUtils.clamp(
desiredCamera.phi - dy * 0.005,
0.48,
1.42
);
});
function stopDragging(event) {
dragging = false;
if (event && 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();
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius + event.deltaY * 0.012,
10,
25
);
},
{ passive: false }
);
renderer.domElement.addEventListener("keydown", (event) => {
let handled = true;
switch (event.key) {
case "ArrowLeft":
desiredCamera.theta -= 0.08;
break;
case "ArrowRight":
desiredCamera.theta += 0.08;
break;
case "ArrowUp":
desiredCamera.phi = THREE.MathUtils.clamp(desiredCamera.phi - 0.06, 0.48, 1.42);
break;
case "ArrowDown":
desiredCamera.phi = THREE.MathUtils.clamp(desiredCamera.phi + 0.06, 0.48, 1.42);
break;
case "+":
case "=":
desiredCamera.radius = Math.max(10, desiredCamera.radius - 1);
break;
case "-":
desiredCamera.radius = Math.min(25, desiredCamera.radius + 1);
break;
case "0":
resetCamera();
break;
default:
handled = false;
}
if (handled) event.preventDefault();
});
document.getElementById("resetView").addEventListener("click", resetCamera);
// Lighting.
scene.add(new THREE.HemisphereLight(0xf7fbff, 0x8b9bab, 2.25));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(-5, 12, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 11;
keyLight.shadow.camera.bottom = -11;
keyLight.shadow.normalBias = 0.035;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x8bc9ff, 1.15);
fillLight.position.set(8, 6, -8);
scene.add(fillLight);
// Ground and technical grid.
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(18, 13.5),
new THREE.MeshStandardMaterial({
color: 0xe5edf3,
roughness: 0.93,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.035;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(18, 36, 0x9fb1c1, 0xc4d0da);
grid.position.y = -0.012;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
const boundaryPoints = [
new THREE.Vector3(-8.5, 0.02, -6.2),
new THREE.Vector3(8.5, 0.02, -6.2),
new THREE.Vector3(8.5, 0.02, 6.2),
new THREE.Vector3(-8.5, 0.02, 6.2),
new THREE.Vector3(-8.5, 0.02, -6.2)
];
scene.add(
new THREE.Line(
new THREE.BufferGeometry().setFromPoints(boundaryPoints),
new THREE.LineBasicMaterial({ color: 0x9cadbc, transparent: true, opacity: 0.65 })
)
);
function addBox(parent, width, height, depth, material, x = 0, y = 0, z = 0) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(width, height, depth), material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addCylinder(
parent,
radiusTop,
radiusBottom,
height,
material,
x = 0,
y = 0,
z = 0,
radialSegments = 24
) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radiusTop, radiusBottom, height, radialSegments),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
const worldLabels = [];
function addWorldLabel(className, html, anchor, tagColor) {
const element = document.createElement("div");
element.className = `world-label ${className}`;
element.innerHTML = html;
if (tagColor) element.style.setProperty("--tag", tagColor);
labelLayer.appendChild(element);
const label = { element, anchor };
worldLabels.push(label);
return label;
}
// ------------------------------------------------------------------
// Source: an exposed generator with a visible rotor and three outlets.
// ------------------------------------------------------------------
const source = new THREE.Group();
source.position.set(-4.6, 0, 0);
scene.add(source);
const sourceBaseMaterial = new THREE.MeshStandardMaterial({
color: 0x334a60,
roughness: 0.66,
metalness: 0.25
});
const sourceMetalMaterial = new THREE.MeshStandardMaterial({
color: 0x91a4b4,
roughness: 0.38,
metalness: 0.68
});
const sourceOrangeMaterial = new THREE.MeshStandardMaterial({
color: 0xe58a32,
emissive: 0x8a3510,
emissiveIntensity: 0.28,
roughness: 0.35,
metalness: 0.18
});
addBox(source, 2.35, 0.28, 2.2, sourceBaseMaterial, 0, 0.14, 0);
addBox(source, 2.05, 0.18, 1.9, sourceMetalMaterial, 0, 0.34, 0);
const sourceFrame = new THREE.Group();
source.add(sourceFrame);
addBox(sourceFrame, 0.12, 1.25, 0.12, sourceMetalMaterial, -0.82, 0.95, -0.61);
addBox(sourceFrame, 0.12, 1.25, 0.12, sourceMetalMaterial, 0.82, 0.95, -0.61);
addBox(sourceFrame, 0.12, 1.25, 0.12, sourceMetalMaterial, -0.82, 0.95, 0.61);
addBox(sourceFrame, 0.12, 1.25, 0.12, sourceMetalMaterial, 0.82, 0.95, 0.61);
addBox(sourceFrame, 1.85, 0.14, 1.42, sourceMetalMaterial, 0, 1.57, 0);
const sourceCover = new THREE.Mesh(
new THREE.BoxGeometry(1.75, 1.2, 1.32),
new THREE.MeshPhysicalMaterial({
color: 0xbfe5f4,
transparent: true,
opacity: 0.13,
roughness: 0.2,
metalness: 0,
depthWrite: false,
side: THREE.DoubleSide
})
);
sourceCover.position.set(0, 0.97, 0);
sourceCover.renderOrder = 2;
source.add(sourceCover);
const rotor = new THREE.Group();
rotor.position.set(0, 0.99, 0);
source.add(rotor);
const rotorCore = addCylinder(
rotor,
0.38,
0.38,
1.25,
sourceOrangeMaterial,
0,
0,
0,
32
);
rotorCore.rotation.z = Math.PI / 2;
for (const x of [-0.48, -0.16, 0.16, 0.48]) {
const coil = new THREE.Mesh(
new THREE.TorusGeometry(0.43, 0.045, 10, 30),
sourceMetalMaterial
);
coil.position.x = x;
coil.rotation.y = Math.PI / 2;
coil.castShadow = true;
rotor.add(coil);
}
const outletBoard = addBox(
source,
0.52,
0.42,
1.25,
sourceBaseMaterial,
0.93,
1.28,
0
);
const terminalLocalPositions = [
new THREE.Vector3(1.18, 1.48, -0.43),
new THREE.Vector3(1.18, 1.48, 0),
new THREE.Vector3(1.18, 1.48, 0.43)
];
for (const terminal of terminalLocalPositions) {
const terminalMesh = new THREE.Mesh(
new THREE.SphereGeometry(0.105, 16, 12),
sourceOrangeMaterial
);
terminalMesh.position.copy(terminal);
source.add(terminalMesh);
}
const sourceRing = new THREE.Mesh(
new THREE.RingGeometry(1.25, 1.31, 64),
new THREE.MeshBasicMaterial({
color: 0xe48a32,
transparent: true,
opacity: 0.38,
side: THREE.DoubleSide
})
);
sourceRing.rotation.x = -Math.PI / 2;
sourceRing.position.y = 0.018;
source.add(sourceRing);
const sourceLabel = addWorldLabel(
"",
`
<div class="label-kicker">Source · generation</div>
<strong id="worldGeneration">6.0 kW</strong>
<small>controllable setpoint</small>
`,
new THREE.Vector3(-4.6, 2.55, 0),
"#e48a32"
);
// ------------------------------------------------------------------
// Buildings: transparent shells with visible devices inside.
// ------------------------------------------------------------------
function makeAccentMaterial(color) {
return new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.75,
roughness: 0.35,
metalness: 0.08
});
}
function createDevice(type, parent, x, z, demand, color) {
const accent = makeAccentMaterial(color);
let accentMesh;
if (type === "motor") {
addBox(parent, 0.82, 0.12, 0.6, sourceBaseMaterial, x, 0.31, z);
const housing = addCylinder(
parent,
0.22,
0.22,
0.62,
sourceMetalMaterial,
x,
0.57,
z,
20
);
housing.rotation.z = Math.PI / 2;
accentMesh = addCylinder(
parent,
0.115,
0.115,
0.66,
accent,
x,
0.57,
z,
16
);
accentMesh.rotation.z = Math.PI / 2;
} else if (type === "home") {
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0xe8edf1,
roughness: 0.64,
metalness: 0.08
});
addBox(parent, 0.62, 0.87, 0.58, bodyMaterial, x, 0.72, z);
addBox(parent, 0.54, 0.14, 0.5, sourceBaseMaterial, x, 0.3, z);
accentMesh = addBox(parent, 0.39, 0.28, 0.025, accent, x, 0.86, z + 0.305);
} else {
const rackMaterial = new THREE.MeshStandardMaterial({
color: 0x334658,
roughness: 0.55,
metalness: 0.34
});
addBox(parent, 0.56, 0.95, 0.42, rackMaterial, x, 0.76, z);
addBox(parent, 0.65, 0.09, 0.5, sourceMetalMaterial, x, 0.28, z);
for (let row = 0; row < 3; row++) {
const strip = addBox(
parent,
0.35,
0.045,
0.025,
row === 0 ? accent : accent.clone(),
x,
0.53 + row * 0.17,
z + 0.225
);
if (row !== 0) {
strip.material.emissiveIntensity = 0;
strip.userData.secondaryAccent = true;
}
}
accentMesh = addBox(parent, 0.12, 0.12, 0.035, accent, x + 0.18, 1.11, z + 0.225);
}
return {
type,
demand,
accent,
accentMesh,
onColor: new THREE.Color(color)
};
}
function createBuilding(config) {
const group = new THREE.Group();
group.position.copy(config.position);
scene.add(group);
const plinthMaterial = new THREE.MeshStandardMaterial({
color: config.plinthColor,
roughness: 0.84,
metalness: 0.04
});
addBox(group, config.width + 0.45, 0.16, config.depth + 0.45, plinthMaterial, 0, 0.08, 0);
addBox(group, config.width, 0.12, config.depth, sourceMetalMaterial, 0, 0.22, 0);
const shellMaterial = new THREE.MeshPhysicalMaterial({
color: config.shellColor,
transparent: true,
opacity: 0.14,
roughness: 0.24,
metalness: 0,
depthWrite: false,
side: THREE.DoubleSide
});
const shell = new THREE.Mesh(
new THREE.BoxGeometry(config.width, config.height, config.depth),
shellMaterial
);
shell.position.y = config.height / 2 + 0.28;
shell.renderOrder = 2;
group.add(shell);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(shell.geometry),
new THREE.LineBasicMaterial({
color: config.edgeColor,
transparent: true,
opacity: 0.65
})
);
edges.position.copy(shell.position);
group.add(edges);
const roof = new THREE.Mesh(
new THREE.BoxGeometry(config.width + 0.12, 0.08, config.depth + 0.12),
new THREE.MeshStandardMaterial({
color: config.edgeColor,
transparent: true,
opacity: 0.45,
roughness: 0.45,
metalness: 0.2
})
);
roof.position.y = config.height + 0.3;
roof.castShadow = true;
group.add(roof);
const devices = [];
if (config.type === "workshop") {
devices.push(createDevice("motor", group, -0.55, 0, 1, 0x159c94));
devices.push(createDevice("motor", group, 0.55, 0, 1, 0x159c94));
} else if (config.type === "homes") {
devices.push(createDevice("home", group, -0.72, 0, 1, 0x4678dc));
devices.push(createDevice("home", group, 0, 0, 1, 0x4678dc));
devices.push(createDevice("home", group, 0.72, 0, 1, 0x4678dc));
} else {
devices.push(createDevice("rack", group, -0.52, -0.25, 0.5, 0xe48a32));
devices.push(createDevice("rack", group, 0, -0.25, 0.5, 0xe48a32));
devices.push(createDevice("rack", group, -0.52, 0.35, 0.5, 0xe48a32));
devices.push(createDevice("rack", group, 0, 0.35, 0.5, 0xe48a32));
}
const socket = new THREE.Mesh(
new THREE.SphereGeometry(0.11, 16, 12),
new THREE.MeshStandardMaterial({
color: config.linkColor,
emissive: config.linkColor,
emissiveIntensity: 0.6,
roughness: 0.3
})
);
socket.position.set(-config.width / 2, 1.15, 0);
group.add(socket);
return {
...config,
group,
devices,
socket
};
}
const loadA = createBuilding({
type: "workshop",
title: "Load A · Workshop",
shortTitle: "A",
demand: LOAD_A_DEMAND,
width: 2.45,
height: 2.0,
depth: 2.0,
position: new THREE.Vector3(1.9, 0, -3.35),
plinthColor: 0xbfded9,
shellColor: 0x5ac4b8,
edgeColor: 0x318e86,
linkColor: COLORS.teal
});
const loadB = createBuilding({
type: "homes",
title: "Load B · Homes",
shortTitle: "B",
demand: LOAD_B_DEMAND,
width: 2.75,
height: 2.15,
depth: 2.05,
position: new THREE.Vector3(4.05, 0, 0),
plinthColor: 0xc6d5ee,
shellColor: 0x6f9de9,
edgeColor: 0x4d75b9,
linkColor: COLORS.blue
});
const loadC = createBuilding({
type: "lab",
title: "Load C · Switchable lab",
shortTitle: "C",
demand: LOAD_C_DEMAND,
width: 2.25,
height: 1.95,
depth: 1.95,
position: new THREE.Vector3(1.9, 0, 3.35),
plinthColor: 0xf0d8ba,
shellColor: 0xf0a959,
edgeColor: 0xc47a32,
linkColor: COLORS.orange
});
const loadALabel = addWorldLabel(
"",
`
<div class="label-kicker">Load A · workshop</div>
<strong id="worldADemand">2.0 kW</strong>
<small id="worldAServed">demand · 2.0 kW supplied</small>
`,
new THREE.Vector3(1.9, 2.95, -3.35),
"#159c94"
);
const loadBLabel = addWorldLabel(
"",
`
<div class="label-kicker">Load B · homes</div>
<strong id="worldBDemand">3.0 kW</strong>
<small id="worldBServed">demand · 3.0 kW supplied</small>
`,
new THREE.Vector3(4.05, 3.12, 0),
"#4678dc"
);
const loadCLabel = addWorldLabel(
"",
`
<div class="label-kicker">Load C · switchable</div>
<strong id="worldCDemand">0.0 kW</strong>
<small id="worldCServed">off · switchable demand</small>
`,
new THREE.Vector3(1.9, 2.9, 3.35),
"#e48a32"
);
// ------------------------------------------------------------------
// Direct source-to-building power links.
// ------------------------------------------------------------------
function createLink(load, terminal, color, name) {
source.updateMatrixWorld(true);
load.group.updateMatrixWorld(true);
const start = source.localToWorld(terminal.clone());
const end = load.group.localToWorld(
new THREE.Vector3(-load.width / 2, 1.15, 0)
);
const control1 = start.clone().lerp(end, 0.24);
control1.y = 2.25;
const midpoint = start.clone().lerp(end, 0.52);
midpoint.y = 3.15 + Math.abs(end.z - start.z) * 0.08;
const control2 = start.clone().lerp(end, 0.76);
control2.y = 2.85;
const curve = new THREE.CatmullRomCurve3(
[start, control1, midpoint, control2, end],
false,
"catmullrom",
0.45
);
const tubeMaterial = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.45,
transparent: true,
opacity: 0.92,
roughness: 0.35,
metalness: 0.15
});
const tube = new THREE.Mesh(
new THREE.TubeGeometry(curve, 72, 0.037, 8, false),
tubeMaterial
);
tube.castShadow = true;
scene.add(tube);
const arrow = new THREE.Mesh(
new THREE.ConeGeometry(0.115, 0.32, 14),
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.35,
roughness: 0.35
})
);
arrow.position.copy(curve.getPoint(0.61));
arrow.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
curve.getTangent(0.61).normalize()
);
scene.add(arrow);
const flowMarkers = [];
for (let i = 0; i < 3; i++) {
const marker = new THREE.Mesh(
new THREE.SphereGeometry(0.075, 12, 8),
new THREE.MeshBasicMaterial({ color })
);
scene.add(marker);
flowMarkers.push(marker);
}
const label = addWorldLabel(
"link-label",
"",
() => curve.getPoint(0.52).add(new THREE.Vector3(0, 0.22, 0)),
`#${color.getHexString()}`
);
return {
name,
load,
curve,
tube,
tubeMaterial,
arrow,
flowMarkers,
label,
baseColor: color.clone()
};
}
const links = [
createLink(loadA, terminalLocalPositions[0], COLORS.teal, "A"),
createLink(loadB, terminalLocalPositions[1], COLORS.blue, "B"),
createLink(loadC, terminalLocalPositions[2], COLORS.orange, "C")
];
// ------------------------------------------------------------------
// Model state and arithmetic.
// ------------------------------------------------------------------
function totalDemand() {
return LOAD_A_DEMAND + LOAD_B_DEMAND + (loadCOn ? LOAD_C_DEMAND : 0);
}
function allocation() {
const fixedDemand = LOAD_A_DEMAND + LOAD_B_DEMAND;
let a = 0;
let b = 0;
let c = 0;
if (generation >= fixedDemand) {
a = LOAD_A_DEMAND;
b = LOAD_B_DEMAND;
c = loadCOn ? Math.min(LOAD_C_DEMAND, generation - fixedDemand) : 0;
} else {
a = LOAD_A_DEMAND * (generation / fixedDemand);
b = LOAD_B_DEMAND * (generation / fixedDemand);
c = 0;
}
return { a, b, c };
}
function setAccent(device, ratio, unserved = false) {
const amount = THREE.MathUtils.clamp(ratio, 0, 1);
if (amount > 0.001) {
device.accent.color.copy(device.onColor);
device.accent.emissive.copy(device.onColor);
device.accent.emissiveIntensity = 0.22 + amount * 0.95;
} else if (unserved) {
device.accent.color.copy(COLORS.red);
device.accent.emissive.copy(COLORS.red);
device.accent.emissiveIntensity = 0.28;
} else {
device.accent.color.copy(COLORS.off);
device.accent.emissive.copy(COLORS.off);
device.accent.emissiveIntensity = 0.015;
}
}
function updateDeviceVisuals() {
const alloc = allocation();
loadA.devices.forEach((device) => {
setAccent(device, alloc.a / device.demand, alloc.a < LOAD_A_DEMAND);
});
loadB.devices.forEach((device) => {
setAccent(device, alloc.b / device.demand, alloc.b < LOAD_B_DEMAND);
});
let remainingC = alloc.c;
loadC.devices.forEach((device) => {
const ratio = loadCOn ? THREE.MathUtils.clamp(remainingC / device.demand, 0, 1) : 0;
remainingC = Math.max(0, remainingC - device.demand);
setAccent(device, ratio, loadCOn && ratio < 0.001);
});
const linksByName = Object.fromEntries(links.map((link) => [link.name, link]));
for (const [name, ratio] of [
["A", alloc.a / LOAD_A_DEMAND],
["B", alloc.b / LOAD_B_DEMAND],
["C", loadCOn ? alloc.c / LOAD_C_DEMAND : 0]
]) {
const link = linksByName[name];
const color = link.baseColor.clone();
if (name === "C" && loadCOn && alloc.c < LOAD_C_DEMAND) {
color.lerp(COLORS.red, 0.58);
}
link.tubeMaterial.color.copy(color);
link.tubeMaterial.emissive.copy(color);
link.arrow.material.color.copy(color);
link.arrow.material.emissive.copy(color);
link.flowMarkers.forEach((marker) => {
marker.material.color.copy(color);
marker.visible = name === "C" ? loadCOn : true;
});
}
}
const elements = {
statusCard: document.getElementById("statusCard"),
statusKicker: document.getElementById("statusKicker"),
statusValue: document.getElementById("statusValue"),
statusDetail: document.getElementById("statusDetail"),
progressTrack: document.getElementById("progressTrack"),
progressFill: document.getElementById("progressFill"),
generationValue: document.getElementById("generationValue"),
demandValue: document.getElementById("demandValue"),
demandEquation: document.getElementById("demandEquation"),
generationEquation: document.getElementById("generationEquation"),
spareValue: document.getElementById("spareValue"),
unmetValue: document.getElementById("unmetValue"),
rowADemand: document.getElementById("rowADemand"),
rowASupplied: document.getElementById("rowASupplied"),
rowBDemand: document.getElementById("rowBDemand"),
rowBSupplied: document.getElementById("rowBSupplied"),
rowCDemand: document.getElementById("rowCDemand"),
rowCSupplied: document.getElementById("rowCSupplied"),
rowTotalDemand: document.getElementById("rowTotalDemand"),
rowTotalSupplied: document.getElementById("rowTotalSupplied"),
sourceRange: document.getElementById("sourceRange"),
sourceOutput: document.getElementById("sourceOutput"),
loadSwitch: document.getElementById("loadSwitch"),
switchState: document.getElementById("switchState"),
announcement: document.getElementById("announcement")
};
function fixed(value) {
return value.toFixed(2);
}
function announce(message) {
elements.announcement.textContent = "";
window.setTimeout(() => {
elements.announcement.textContent = message;
}, 30);
}
function updateUI() {
const demand = totalDemand();
const alloc = allocation();
const spare = Math.max(generation - demand, 0);
const unmet = Math.max(demand - generation, 0);
const supplied = Math.min(generation, demand);
elements.generationValue.textContent = `${fixed(generation)} kW`;
elements.demandValue.textContent = `${fixed(demand)} kW`;
elements.generationEquation.textContent = `${fixed(generation)} kW`;
elements.demandEquation.textContent =
`D = ${fixed(LOAD_A_DEMAND)} + ${fixed(LOAD_B_DEMAND)} + ` +
`${fixed(loadCOn ? LOAD_C_DEMAND : 0)} = ${fixed(demand)}`;
elements.spareValue.textContent = `${fixed(spare)} kW`;
elements.unmetValue.textContent = `${fixed(unmet)} kW`;
elements.rowADemand.textContent = fixed(LOAD_A_DEMAND);
elements.rowASupplied.textContent = fixed(alloc.a);
elements.rowBDemand.textContent = fixed(LOAD_B_DEMAND);
elements.rowBSupplied.textContent = fixed(alloc.b);
elements.rowCDemand.textContent = fixed(loadCOn ? LOAD_C_DEMAND : 0);
elements.rowCSupplied.textContent = fixed(alloc.c);
elements.rowTotalDemand.textContent = fixed(demand);
elements.rowTotalSupplied.textContent = fixed(supplied);
elements.sourceRange.value = generation.toFixed(1);
elements.sourceOutput.textContent = `${generation.toFixed(1)} kW`;
elements.loadSwitch.setAttribute("aria-checked", String(loadCOn));
elements.loadSwitch.setAttribute("aria-pressed", String(loadCOn));
elements.statusCard.className = "status-card";
elements.progressTrack.hidden = true;
if (autoAdjust) {
const remaining = Math.max(
0,
(autoAdjust.start + AUTO_DELAY_MS - performance.now()) / 1000
);
const progress = THREE.MathUtils.clamp(
1 - remaining / (AUTO_DELAY_MS / 1000),
0,
1
);
elements.progressTrack.hidden = false;
elements.progressFill.style.width = `${progress * 100}%`;
if (unmet > 0) {
elements.statusCard.classList.add("short");
elements.statusKicker.textContent =
`Temporary unmet demand · source hold ${remaining.toFixed(1)} s`;
elements.statusValue.textContent = `${fixed(unmet)} kW unmet`;
elements.statusDetail.textContent =
`Load C adds ${fixed(LOAD_C_DEMAND)} kW. A and B are served first; ` +
`C receives ${fixed(alloc.c)} kW and is ${fixed(unmet)} kW short. ` +
`G remains ${fixed(generation)} kW until the hold ends, then G ← D.`;
} else {
elements.statusCard.classList.add("pending");
elements.statusKicker.textContent =
`Source catch-up pending · ${remaining.toFixed(1)} s`;
elements.statusValue.textContent = `${fixed(generation - demand)} kW spare`;
elements.statusDetail.textContent =
`The source setpoint is being held for ${remaining.toFixed(1)} seconds. ` +
`At the end it will be set exactly to the connected demand of ${fixed(demand)} kW.`;
}
} else if (unmet > 0) {
elements.statusCard.classList.add("short");
elements.statusKicker.textContent = "Connected demand exceeds generation";
elements.statusValue.textContent = `${fixed(unmet)} kW unmet`;
elements.statusDetail.textContent =
`D = ${fixed(demand)} kW and G = ${fixed(generation)} kW. ` +
`Unmet demand is D − G = ${fixed(unmet)} kW. ` +
`Increase the source setpoint or reset the network.`;
} else if (spare > 0) {
elements.statusKicker.textContent = "Generation exceeds connected demand";
elements.statusValue.textContent = `${fixed(spare)} kW spare`;
elements.statusDetail.textContent =
`G = ${fixed(generation)} kW and D = ${fixed(demand)} kW. ` +
`The arithmetic balance is G − D = +${fixed(spare)} kW.`;
} else {
elements.statusKicker.textContent = "Connected demand balanced";
elements.statusValue.textContent = "0.00 kW gap";
elements.statusDetail.textContent =
`G = D = ${fixed(demand)} kW. All connected load demand is supplied.`;
}
if (loadCOn) {
elements.switchState.textContent =
`Load C is on. Connected demand is ${fixed(demand)} kW; ` +
`${fixed(alloc.c)} kW is currently supplied to C.`;
} else {
elements.switchState.textContent =
`Load C is off. Connected demand is ${fixed(demand)} kW.`;
}
document.getElementById("worldGeneration").textContent =
`${generation.toFixed(1)} kW`;
document.getElementById("worldADemand").textContent = "2.0 kW";
document.getElementById("worldAServed").textContent =
`demand · ${alloc.a.toFixed(1)} kW supplied`;
document.getElementById("worldBDemand").textContent = "3.0 kW";
document.getElementById("worldBServed").textContent =
`demand · ${alloc.b.toFixed(1)} kW supplied`;
document.getElementById("worldCDemand").textContent =
`${(loadCOn ? LOAD_C_DEMAND : 0).toFixed(1)} kW`;
document.getElementById("worldCServed").textContent = loadCOn
? `demand · ${alloc.c.toFixed(1)} kW supplied` +
(alloc.c < LOAD_C_DEMAND ? ` · ${fixed(unmet)} kW short` : "")
: "off · switchable demand";
loadCLabel.element.classList.toggle("short", loadCOn && unmet > 0);
links[0].label.element.textContent = "A · 2.0 kW demand";
links[1].label.element.textContent = "B · 3.0 kW demand";
links[2].label.element.textContent = loadCOn
? `C · 2.0 kW demand${unmet > 0 ? ` · ${fixed(unmet)} SHORT` : ""}`
: "C · OFF";
links[2].label.element.classList.toggle("short", loadCOn && unmet > 0);
updateDeviceVisuals();
}
// Controls.
elements.sourceRange.addEventListener("input", (event) => {
autoAdjust = null;
generation = Number(event.target.value);
updateUI();
announce(`Source generation set to ${generation.toFixed(1)} kilowatts.`);
});
document.querySelectorAll("[data-adjust]").forEach((button) => {
button.addEventListener("click", () => {
autoAdjust = null;
const adjustment = Number(button.dataset.adjust);
generation = THREE.MathUtils.clamp(generation + adjustment, 0, 12);
updateUI();
announce(`Source generation set to ${generation.toFixed(1)} kilowatts.`);
});
});
elements.loadSwitch.addEventListener("click", () => {
loadCOn = !loadCOn;
if (loadCOn) {
autoAdjust = {
start: performance.now(),
targetDemand: totalDemand()
};
announce(
"Load C is on. The source setpoint is held for 2.4 seconds so unmet demand is visible."
);
} else {
autoAdjust = null;
announce("Load C is off. The source setpoint is unchanged.");
}
updateUI();
});
document.getElementById("resetNetwork").addEventListener("click", () => {
generation = ORIGINAL_GENERATION;
loadCOn = false;
autoAdjust = null;
updateUI();
announce(
`Network reset. Load C is off and source generation is ${ORIGINAL_GENERATION.toFixed(1)} kilowatts.`
);
});
// ------------------------------------------------------------------
// Label projection.
// ------------------------------------------------------------------
const projected = new THREE.Vector3();
function updateLabels() {
const width = viewport.clientWidth;
const height = viewport.clientHeight;
for (const label of worldLabels) {
const anchor =
typeof label.anchor === "function" ? label.anchor() : label.anchor;
projected.copy(anchor).project(camera);
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
const visible = projected.z > -1 && projected.z < 1;
label.element.style.display = visible ? "block" : "none";
label.element.style.left = `${x}px`;
label.element.style.top = `${y}px`;
}
}
// ------------------------------------------------------------------
// Resize and render loop.
// ------------------------------------------------------------------
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();
}
new ResizeObserver(resize).observe(viewport);
resize();
updateCamera();
updateUI();
const clock = new THREE.Clock();
let elapsed = 0;
function animate(now) {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
elapsed += delta;
if (autoAdjust && now >= autoAdjust.start + AUTO_DELAY_MS) {
generation = autoAdjust.targetDemand;
autoAdjust = null;
updateUI();
announce(
`Source adjusted to ${generation.toFixed(1)} kilowatts, equal to connected demand.`
);
}
cameraState.theta += (desiredCamera.theta - cameraState.theta) * 0.09;
cameraState.phi += (desiredCamera.phi - cameraState.phi) * 0.09;
cameraState.radius += (desiredCamera.radius - cameraState.radius) * 0.09;
updateCamera();
// This is a visual machine animation, not a grid-frequency calculation.
rotor.rotation.x += delta * 0.75;
for (const link of links) {
link.flowMarkers.forEach((marker, index) => {
if (!marker.visible) return;
const t = (elapsed * 0.065 + index / link.flowMarkers.length) % 1;
marker.position.copy(link.curve.getPoint(t));
});
}
if (autoAdjust) updateUI();
renderer.render(scene, camera);
updateLabels();
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```