Prompt specification
Build or customize the Three.js 3D scene "Neighborhood Microgrid Display" 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: Neighborhood Microgrid Display
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/neighborhood-microgrid-display-x3935
Scene Description Prompt:
A voxel neighborhood microgrid with synthetic solar supply, storage, demand, and visible shortages. Build one HTML file using Three.js from cdnjs.
Working Three.js Starter (neighborhood-microgrid-display-x3935):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#07111f" />
<title>VoxelGrid — Neighborhood Microgrid</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 21, 36, 0.82);
--panel-solid: #0c192b;
--border: rgba(163, 195, 224, 0.14);
--text: #edf5ff;
--muted: #8da0b8;
--solar: #ffd166;
--storage: #58e6b4;
--demand: #67b7ff;
--grid: #bb9cff;
--danger: #ff6174;
--radius: 18px;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.topbar {
position: fixed;
z-index: 20;
top: 18px;
left: 20px;
right: 20px;
height: 58px;
display: flex;
align-items: center;
justify-content: space-between;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
padding: 9px 13px 9px 10px;
border: 1px solid var(--border);
border-radius: 15px;
background: rgba(7, 17, 31, 0.72);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.16);
backdrop-filter: blur(18px);
}
.brand-mark {
width: 34px;
height: 34px;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
gap: 3px;
transform: rotate(-4deg);
}
.brand-mark i {
display: block;
border-radius: 3px;
background: #dceaff;
opacity: 0.9;
}
.brand-mark i:nth-child(2),
.brand-mark i:nth-child(4),
.brand-mark i:nth-child(9) {
background: var(--solar);
}
.brand-mark i:nth-child(6),
.brand-mark i:nth-child(8) {
background: var(--storage);
}
.brand-title {
font-size: 14px;
font-weight: 760;
letter-spacing: 0.04em;
}
.brand-subtitle {
margin-top: 2px;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.header-status {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 12px;
border: 1px solid var(--border);
border-radius: 13px;
background: rgba(7, 17, 31, 0.72);
backdrop-filter: blur(18px);
pointer-events: auto;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--storage);
box-shadow: 0 0 14px var(--storage);
}
.status-dot.warning {
background: var(--danger);
box-shadow: 0 0 14px var(--danger);
}
.status-copy {
min-width: 104px;
}
.status-copy small {
display: block;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.status-copy strong {
display: block;
margin-top: 2px;
font-size: 12px;
letter-spacing: 0.04em;
}
#clock {
min-width: 66px;
padding-left: 10px;
border-left: 1px solid var(--border);
font-variant-numeric: tabular-nums;
font-size: 16px;
font-weight: 720;
}
.icon-button {
display: none;
width: 38px;
height: 38px;
align-items: center;
justify-content: center;
border: 1px solid var(--border);
border-radius: 11px;
background: rgba(15, 29, 48, 0.88);
cursor: pointer;
}
.panel {
position: fixed;
z-index: 15;
border: 1px solid var(--border);
border-radius: var(--radius);
background: var(--panel);
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(22px) saturate(125%);
}
.controls-panel {
top: 91px;
bottom: 106px;
left: 20px;
width: 300px;
overflow: auto;
padding: 19px;
scrollbar-width: thin;
scrollbar-color: rgba(141, 160, 184, 0.25) transparent;
}
.right-panel {
top: 91px;
right: 20px;
width: 252px;
padding: 18px;
}
.eyebrow {
margin: 0 0 6px;
color: var(--muted);
font-size: 9px;
font-weight: 720;
letter-spacing: 0.15em;
text-transform: uppercase;
}
h1,
h2,
h3,
p {
margin-top: 0;
}
h2 {
margin-bottom: 5px;
font-size: 19px;
letter-spacing: -0.02em;
}
h3 {
margin-bottom: 12px;
font-size: 12px;
letter-spacing: 0.03em;
}
.section-copy {
margin-bottom: 19px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.control {
margin-bottom: 17px;
}
.control-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 8px;
}
.control-head label {
color: #c8d5e6;
font-size: 11px;
font-weight: 620;
}
.control-value {
color: var(--text);
font-size: 11px;
font-weight: 720;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 0;
appearance: none;
border-radius: 99px;
background: #203149;
outline: none;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
appearance: none;
border: 3px solid #dceaff;
border-radius: 50%;
background: #3c83ca;
box-shadow: 0 0 0 4px rgba(103, 183, 255, 0.12);
}
input[type="range"]::-moz-range-thumb {
width: 10px;
height: 10px;
border: 3px solid #dceaff;
border-radius: 50%;
background: #3c83ca;
box-shadow: 0 0 0 4px rgba(103, 183, 255, 0.12);
}
#solarRange::-webkit-slider-thumb {
background: var(--solar);
}
#storageRange::-webkit-slider-thumb {
background: var(--storage);
}
#gridRange::-webkit-slider-thumb {
background: var(--grid);
}
.scenario-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 3px 0 18px;
}
.soft-button,
.primary-button {
min-height: 36px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(31, 49, 73, 0.62);
color: #dce9f7;
font-size: 10px;
font-weight: 700;
cursor: pointer;
transition:
border-color 160ms ease,
background 160ms ease,
transform 160ms ease;
}
.soft-button:hover,
.primary-button:hover {
border-color: rgba(141, 192, 240, 0.42);
background: rgba(42, 66, 95, 0.72);
}
.soft-button:active,
.primary-button:active {
transform: translateY(1px);
}
.chart-card {
padding: 12px;
border: 1px solid var(--border);
border-radius: 13px;
background: rgba(4, 12, 23, 0.38);
}
.chart-head {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 9px;
color: #cad8e8;
font-size: 10px;
font-weight: 650;
}
#energyChart {
display: block;
width: 100%;
height: 118px;
}
.chart-legend {
display: flex;
gap: 12px;
margin-top: 8px;
color: var(--muted);
font-size: 8px;
letter-spacing: 0.04em;
}
.legend-item {
display: flex;
align-items: center;
gap: 5px;
}
.legend-swatch {
width: 7px;
height: 7px;
border-radius: 2px;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.metric {
min-height: 83px;
padding: 12px;
border: 1px solid var(--border);
border-radius: 13px;
background: rgba(4, 12, 23, 0.34);
}
.metric-label {
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.metric-value {
margin-top: 8px;
font-size: 23px;
font-weight: 760;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.metric-unit {
margin-left: 3px;
color: var(--muted);
font-size: 10px;
font-weight: 600;
letter-spacing: 0;
}
.metric solar .metric-value {
color: var(--solar);
}
.metric storage .metric-value {
color: var(--storage);
}
.metric demand .metric-value {
color: var(--demand);
}
.metric danger {
border-color: rgba(255, 97, 116, 0.38);
background: rgba(255, 97, 116, 0.08);
}
.metric.danger .metric-value {
color: var(--danger);
}
.soc-row {
display: flex;
justify-content: space-between;
margin: 16px 0 8px;
color: var(--muted);
font-size: 10px;
}
.soc-row strong {
color: var(--storage);
font-variant-numeric: tabular-nums;
}
.soc-track {
height: 7px;
overflow: hidden;
border-radius: 99px;
background: rgba(132, 153, 178, 0.15);
}
#socFill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #29a77a, #58e6b4);
box-shadow: 0 0 12px rgba(88, 230, 180, 0.45);
transition: width 120ms linear;
}
.divider {
height: 1px;
margin: 17px 0;
background: var(--border);
}
.breakdown-title {
display: flex;
justify-content: space-between;
margin-bottom: 12px;
color: #c7d4e3;
font-size: 10px;
font-weight: 700;
}
.breakdown-row {
display: grid;
grid-template-columns: 58px 1fr 42px;
align-items: center;
gap: 8px;
margin: 9px 0;
color: var(--muted);
font-size: 9px;
}
.breakdown-track {
height: 5px;
overflow: hidden;
border-radius: 99px;
background: rgba(132, 153, 178, 0.12);
}
.breakdown-fill {
height: 100%;
border-radius: inherit;
}
.breakdown-row strong {
color: #cddaea;
text-align: right;
font-variant-numeric: tabular-nums;
}
.timeline {
position: fixed;
z-index: 18;
left: 20px;
right: 20px;
bottom: 18px;
height: 70px;
display: grid;
grid-template-columns: 48px minmax(260px, 1fr) 56px;
align-items: center;
gap: 16px;
padding: 10px 15px;
border: 1px solid var(--border);
border-radius: 17px;
background: rgba(7, 17, 31, 0.82);
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.24);
backdrop-filter: blur(22px);
}
#playButton {
width: 40px;
height: 40px;
display: grid;
place-items: center;
border: 1px solid rgba(103, 183, 255, 0.35);
border-radius: 12px;
background: rgba(103, 183, 255, 0.13);
color: var(--demand);
cursor: pointer;
}
.timeline-main {
min-width: 0;
}
.timeline-labels {
display: flex;
justify-content: space-between;
margin-bottom: 6px;
color: var(--muted);
font-size: 8px;
letter-spacing: 0.04em;
}
#timeRange {
display: block;
}
#timeRange::-webkit-slider-thumb {
width: 14px;
height: 14px;
border: 3px solid #07111f;
background: #f0f6ff;
box-shadow: 0 0 0 2px var(--demand);
}
#speedButton {
height: 38px;
border: 1px solid var(--border);
border-radius: 11px;
background: rgba(31, 49, 73, 0.62);
color: #dbe8f6;
font-size: 10px;
font-weight: 750;
cursor: pointer;
}
.scene-legend {
position: fixed;
z-index: 8;
left: 342px;
bottom: 102px;
display: flex;
gap: 7px;
pointer-events: none;
}
.scene-chip {
display: flex;
align-items: center;
gap: 6px;
padding: 7px 9px;
border: 1px solid var(--border);
border-radius: 9px;
background: rgba(7, 17, 31, 0.62);
color: #aebed0;
font-size: 9px;
backdrop-filter: blur(10px);
}
.scene-chip i {
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 8px currentColor;
}
.camera-help {
position: fixed;
z-index: 8;
right: 22px;
bottom: 101px;
color: rgba(190, 207, 225, 0.58);
font-size: 9px;
pointer-events: none;
}
#labels {
position: fixed;
inset: 0;
z-index: 7;
overflow: hidden;
pointer-events: none;
}
.world-label {
position: absolute;
display: flex;
align-items: center;
gap: 6px;
width: max-content;
max-width: 190px;
padding: 6px 8px;
border: 1px solid rgba(164, 194, 224, 0.2);
border-radius: 8px;
background: rgba(7, 17, 31, 0.82);
box-shadow: 0 7px 22px rgba(0, 0, 0, 0.2);
color: #dbe8f6;
font-size: 8px;
font-weight: 740;
letter-spacing: 0.06em;
white-space: nowrap;
transform: translate(-50%, -100%);
transition: opacity 140ms ease;
backdrop-filter: blur(10px);
}
.world-label::after {
content: "";
position: absolute;
left: 50%;
bottom: -7px;
width: 1px;
height: 7px;
background: rgba(180, 207, 230, 0.35);
}
.world-label i {
width: 6px;
height: 6px;
flex: 0 0 auto;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 8px currentColor;
}
.world-label.solar-label {
color: var(--solar);
}
.world-label.storage-label {
color: var(--storage);
}
.world-label.hub-label {
color: var(--demand);
}
.world-label.shortage-label {
color: #fff;
border-color: rgba(255, 97, 116, 0.55);
background: rgba(76, 15, 27, 0.9);
box-shadow: 0 0 22px rgba(255, 97, 116, 0.22);
}
.world-label.shortage-label i {
color: var(--danger);
background: var(--danger);
}
@media (max-width: 980px) {
.right-panel {
display: none;
}
.scene-legend {
left: 342px;
}
}
@media (max-width: 700px) {
.topbar {
top: 10px;
left: 10px;
right: 10px;
}
.brand {
padding-right: 10px;
}
.brand-subtitle,
.status-copy {
display: none;
}
.header-status {
gap: 7px;
padding: 7px;
}
#clock {
min-width: 56px;
padding-left: 7px;
font-size: 13px;
}
.icon-button {
display: flex;
}
.controls-panel {
display: none;
top: auto;
left: 10px;
right: 10px;
bottom: 91px;
width: auto;
max-height: 48vh;
}
body.controls-open .controls-panel {
display: block;
}
.timeline {
left: 10px;
right: 10px;
bottom: 10px;
height: 66px;
grid-template-columns: 42px 1fr 46px;
gap: 9px;
padding: 8px 10px;
}
.scene-legend,
.camera-help {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive 3D voxel neighborhood microgrid"></canvas>
<div id="labels"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i>
</div>
<div>
<div class="brand-title">VOXELGRID</div>
<div class="brand-subtitle">Neighborhood microgrid lab</div>
</div>
</div>
<div class="header-status">
<div class="status-dot" id="statusDot"></div>
<div class="status-copy">
<small>Grid state</small>
<strong id="gridState">BALANCED</strong>
</div>
<div id="clock">18:30</div>
<button class="icon-button" id="panelToggle" aria-label="Toggle controls">☰</button>
</div>
</header>
<aside class="panel controls-panel" id="controlsPanel">
<p class="eyebrow">Dispatch controls</p>
<h2>Microgrid scenario</h2>
<p class="section-copy">
Adjust local generation, battery reserves, and load. Red rooftop beacons
mark buildings that cannot be fully served.
</p>
<div class="control">
<div class="control-head">
<label for="solarRange">Solar capacity</label>
<span class="control-value" id="solarValue">6.0 kW</span>
</div>
<input id="solarRange" type="range" min="0" max="12" step="0.1" value="6" />
</div>
<div class="control">
<div class="control-head">
<label for="storageRange">Storage capacity</label>
<span class="control-value" id="storageValue">10.0 kWh</span>
</div>
<input id="storageRange" type="range" min="2" max="20" step="0.5" value="10" />
</div>
<div class="control">
<div class="control-head">
<label for="batteryRange">Battery output limit</label>
<span class="control-value" id="batteryValue">4.0 kW</span>
</div>
<input id="batteryRange" type="range" min="0" max="8" step="0.1" value="4" />
</div>
<div class="control">
<div class="control-head">
<label for="demandRange">Demand multiplier</label>
<span class="control-value" id="demandValue">1.00×</span>
</div>
<input id="demandRange" type="range" min="0.4" max="1.6" step="0.05" value="1" />
</div>
<div class="control">
<div class="control-head">
<label for="gridRange">Grid import limit</label>
<span class="control-value" id="gridValue">0.0 kW</span>
</div>
<input id="gridRange" type="range" min="0" max="6" step="0.1" value="0" />
</div>
<div class="scenario-row">
<button class="primary-button" id="peakButton">Apply evening peak</button>
<button class="soft-button" id="resetButton">Reset scenario</button>
</div>
<div class="chart-card">
<div class="chart-head">
<span>24-hour energy balance</span>
<span id="chartCapacity">8 kW</span>
</div>
<canvas id="energyChart"></canvas>
<div class="chart-legend">
<span class="legend-item">
<i class="legend-swatch" style="background: var(--solar)"></i>SOLAR
</span>
<span class="legend-item">
<i class="legend-swatch" style="background: var(--demand)"></i>DEMAND
</span>
<span class="legend-item">
<i class="legend-swatch" style="background: var(--danger)"></i>SHORT
</span>
</div>
</div>
</aside>
<aside class="panel right-panel">
<p class="eyebrow">Live balance</p>
<h2>District dispatch</h2>
<div class="metric-grid">
<div class="metric solar">
<div class="metric-label">Solar</div>
<div class="metric-value"><span id="solarMetric">0.0</span><span class="metric-unit">kW</span></div>
</div>
<div class="metric demand">
<div class="metric-label">Demand</div>
<div class="metric-value"><span id="demandMetric">0.0</span><span class="metric-unit">kW</span></div>
</div>
<div class="metric storage">
<div class="metric-label">Battery</div>
<div class="metric-value"><span id="batteryMetric">0.0</span><span class="metric-unit">kW</span></div>
</div>
<div class="metric danger" id="shortageCard">
<div class="metric-label">Unserved</div>
<div class="metric-value"><span id="shortageMetric">0.0</span><span class="metric-unit">kW</span></div>
</div>
</div>
<div class="soc-row">
<span>Battery state of charge</span>
<strong id="socText">100%</strong>
</div>
<div class="soc-track"><div id="socFill"></div></div>
<div class="divider"></div>
<div class="breakdown-title">
<span>Supply mix</span>
<span id="totalSupply">0.0 kW</span>
</div>
<div class="breakdown-row">
<span>Solar</span>
<div class="breakdown-track"><div class="breakdown-fill" id="solarBar" style="background:var(--solar)"></div></div>
<strong id="solarBarText">0.0</strong>
</div>
<div class="breakdown-row">
<span>Storage</span>
<div class="breakdown-track"><div class="breakdown-fill" id="batteryBar" style="background:var(--storage)"></div></div>
<strong id="batteryBarText">0.0</strong>
</div>
<div class="breakdown-row">
<span>Grid</span>
<div class="breakdown-track"><div class="breakdown-fill" id="gridBar" style="background:var(--grid)"></div></div>
<strong id="gridBarText">0.0</strong>
</div>
<div class="divider"></div>
<h3>Operating notes</h3>
<p class="section-copy" id="operatingNotes" style="margin-bottom: 0">
Solar is serving the neighborhood. The battery remains available for the
evening ramp.
</p>
</aside>
<div class="scene-legend">
<span class="scene-chip" style="color:var(--solar)"><i></i>Solar</span>
<span class="scene-chip" style="color:var(--storage)"><i></i>Storage</span>
<span class="scene-chip" style="color:var(--demand)"><i></i>Demand</span>
<span class="scene-chip" style="color:var(--danger)"><i></i>Shortage</span>
</div>
<div class="camera-help">Drag to orbit · Scroll to zoom · Right-drag to pan</div>
<footer class="timeline">
<button id="playButton" aria-label="Play simulation">▶</button>
<div class="timeline-main">
<div class="timeline-labels">
<span>00:00</span>
<span>06:00</span>
<span>12:00</span>
<span>18:00</span>
<span>24:00</span>
</div>
<input id="timeRange" type="range" min="0" max="23.95" step="0.05" value="18.5" />
</div>
<button id="speedButton" aria-label="Change simulation speed">1×</button>
</footer>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const clamp = THREE.MathUtils.clamp;
const lerp = THREE.MathUtils.lerp;
const COLORS = {
solar: 0xffd166,
storage: 0x58e6b4,
demand: 0x67b7ff,
grid: 0xbb9cff,
danger: 0xff6174
};
const defaults = {
solarCapacity: 6,
storageCapacity: 10,
batteryPower: 4,
demandScale: 1,
gridLimit: 0
};
const params = { ...defaults };
let currentTime = 18.5;
let playing = false;
let speedMultiplier = 1;
const canvas = $("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 39, 78);
const camera = new THREE.PerspectiveCamera(
40,
window.innerWidth / window.innerHeight,
0.1,
150
);
const orbit = {
target: new THREE.Vector3(0, 0.3, 0),
yaw: -0.56,
pitch: 0.73,
distance: 36,
dragging: false,
panning: false,
lastX: 0,
lastY: 0
};
function updateCamera() {
const horizontal = Math.cos(orbit.pitch) * orbit.distance;
camera.position.set(
orbit.target.x + Math.sin(orbit.yaw) * horizontal,
orbit.target.y + Math.sin(orbit.pitch) * orbit.distance,
orbit.target.z + Math.cos(orbit.yaw) * horizontal
);
camera.lookAt(orbit.target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0x8db8ff, 0x18352f, 1.25);
scene.add(hemisphere);
const sunLight = new THREE.DirectionalLight(0xffd4a3, 2.6);
sunLight.position.set(-12, 22, -12);
sunLight.castShadow = true;
sunLight.shadow.mapSize.set(2048, 2048);
sunLight.shadow.camera.left = -24;
sunLight.shadow.camera.right = 24;
sunLight.shadow.camera.top = 22;
sunLight.shadow.camera.bottom = -22;
sunLight.shadow.camera.near = 1;
sunLight.shadow.camera.far = 65;
sunLight.shadow.bias = -0.0004;
scene.add(sunLight);
const rimLight = new THREE.DirectionalLight(0x4c82ff, 0.75);
rimLight.position.set(12, 9, 18);
scene.add(rimLight);
const world = new THREE.Group();
scene.add(world);
const materials = {
ground: new THREE.MeshStandardMaterial({
color: 0x17372f,
roughness: 0.96,
metalness: 0
}),
groundSide: new THREE.MeshStandardMaterial({
color: 0x0a2025,
roughness: 0.9
}),
road: new THREE.MeshStandardMaterial({
color: 0x172330,
roughness: 0.93
}),
sidewalk: new THREE.MeshStandardMaterial({
color: 0x71818b,
roughness: 0.9
}),
marking: new THREE.MeshBasicMaterial({ color: 0x9caeb8 }),
roof: new THREE.MeshStandardMaterial({
color: 0x344654,
roughness: 0.78
}),
solarPanel: new THREE.MeshStandardMaterial({
color: 0x173c6a,
emissive: 0x155ca8,
emissiveIntensity: 0.45,
metalness: 0.35,
roughness: 0.35
}),
frame: new THREE.MeshStandardMaterial({
color: 0x9eb2be,
metalness: 0.65,
roughness: 0.4
}),
trunk: new THREE.MeshStandardMaterial({ color: 0x6d4934, roughness: 1 }),
leaves: new THREE.MeshStandardMaterial({ color: 0x32785c, roughness: 1 }),
leavesLight: new THREE.MeshStandardMaterial({ color: 0x4b9b70, roughness: 1 })
};
const buildingDefs = [
{ x: -10.0, z: -5.5, w: 2.8, d: 3.0, h: 2.4, color: 0xc5c4ba, weight: 1.0, name: "Alder House" },
{ x: -6.1, z: -5.2, w: 2.4, d: 2.8, h: 3.7, color: 0xa9b8c4, weight: 0.85, name: "Mason Apartments" },
{ x: -3.0, z: -5.5, w: 2.7, d: 3.2, h: 4.6, color: 0xd0c8b7, weight: 1.35, name: "Community Center" },
{ x: -10.0, z: 5.3, w: 2.7, d: 2.9, h: 2.8, color: 0x9fb7ae, weight: 1.15, name: "Willow House" },
{ x: -6.1, z: 5.4, w: 2.5, d: 2.8, h: 3.5, color: 0xd1bca8, weight: 0.95, name: "Birch Apartments" },
{ x: -3.0, z: 5.4, w: 2.8, d: 3.0, h: 4.1, color: 0x9faebc, weight: 1.25, name: "North Clinic" },
{ x: 4.0, z: -5.2, w: 2.6, d: 2.9, h: 2.7, color: 0xb8c3bd, weight: 1.1, name: "Cedar House" },
{ x: 7.2, z: -5.4, w: 2.6, d: 2.8, h: 3.9, color: 0xd3c6b0, weight: 0.8, name: "Elm Apartments" },
{ x: 4.0, z: 5.4, w: 2.7, d: 3.0, h: 2.9, color: 0xc4b9aa, weight: 1.2, name: "Oak House" },
{ x: 7.2, z: 5.4, w: 2.6, d: 2.9, h: 3.5, color: 0xa7b8c5, weight: 0.95, name: "Pine Apartments" }
];
function box(w, h, d, material, x = 0, y = 0, z = 0, parent = world) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), material);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// Island and street grid.
box(32, 0.85, 22, materials.groundSide, 0, -0.52, 0);
box(31.7, 0.22, 21.7, materials.ground, 0, -0.04, 0);
box(3.35, 0.08, 21.3, materials.sidewalk, 0, 0.105, 0);
box(31.3, 0.08, 3.35, materials.sidewalk, 0, 0.106, 0);
box(3.0, 0.09, 21.2, materials.road, 0, 0.155, 0);
box(31.2, 0.09, 3.0, materials.road, 0, 0.156, 0);
for (let z = -9.5; z <= 9.5; z += 2.3) {
box(0.08, 0.018, 0.8, materials.marking, 0, 0.208, z);
}
for (let x = -14.5; x <= 14.5; x += 2.4) {
box(0.8, 0.018, 0.08, materials.marking, x, 0.209, 0);
}
// Building blocks and structures.
const buildings = [];
const windowGeometry = new THREE.BoxGeometry(0.34, 0.48, 0.035);
function createBuilding(def, index) {
const group = new THREE.Group();
group.position.set(def.x, 0, def.z);
world.add(group);
const wallMaterial = new THREE.MeshStandardMaterial({
color: def.color,
roughness: 0.82
});
box(def.w + 0.42, 0.22, def.d + 0.42, materials.sidewalk, 0, 0.23, 0, group);
box(def.w, def.h, def.d, wallMaterial, 0, def.h / 2 + 0.34, 0, group);
box(def.w + 0.18, 0.18, def.d + 0.18, materials.roof, 0, def.h + 0.43, 0, group);
const windowMaterial = new THREE.MeshBasicMaterial({
color: 0x8ec7ff,
transparent: true,
opacity: 0.72
});
const floors = Math.max(1, Math.floor((def.h - 0.4) / 1.15));
const columns = def.w > 2.6 ? 2 : 1;
for (let floor = 0; floor < floors; floor++) {
const y = 0.95 + floor * 1.08;
for (let col = 0; col < columns; col++) {
const wx = columns === 1 ? 0 : (col - 0.5) * 0.95;
const windowMesh = new THREE.Mesh(windowGeometry, windowMaterial);
windowMesh.position.set(wx, y, def.d / 2 + 0.021);
group.add(windowMesh);
}
const sideWindow = new THREE.Mesh(windowGeometry, windowMaterial);
sideWindow.position.set(def.w / 2 + 0.021, y, 0.25);
sideWindow.rotation.y = Math.PI / 2;
group.add(sideWindow);
}
const doorMaterial = new THREE.MeshStandardMaterial({
color: index % 2 ? 0x496776 : 0x755c4d,
roughness: 0.8
});
box(0.55, 1.05, 0.07, doorMaterial, 0, 0.88, def.d / 2 + 0.04, group);
if (def.h > 3.5) {
box(0.62, 0.78, 0.62, wallMaterial, 0.55, def.h + 0.87, -0.35, group);
}
const panelCount = def.h > 4 ? 4 : def.h > 3 ? 3 : 2;
for (let i = 0; i < panelCount; i++) {
const px = (i % 2 - 0.5) * 0.86;
const pz = Math.floor(i / 2) * 0.82 - 0.25;
const panel = box(0.72, 0.08, 0.6, materials.solarPanel, px, def.h + 0.57, pz, group);
panel.rotation.z = -0.06;
box(0.74, 0.025, 0.035, materials.frame, px, def.h + 0.62, pz, group);
}
const shortageMaterial = new THREE.MeshBasicMaterial({
color: COLORS.danger,
transparent: true,
opacity: 0.9
});
const shortageBeacon = new THREE.Group();
shortageBeacon.position.set(0, def.h + 0.85, 0);
group.add(shortageBeacon);
const beacon = new THREE.Mesh(
new THREE.CylinderGeometry(0.1, 0.16, 0.75, 8),
shortageMaterial
);
beacon.position.y = 0.36;
shortageBeacon.add(beacon);
const cap = new THREE.Mesh(
new THREE.ConeGeometry(0.2, 0.3, 8),
shortageMaterial
);
cap.position.y = 0.88;
cap.rotation.x = Math.PI;
shortageBeacon.add(cap);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.72, 0.055, 8, 28),
shortageMaterial
);
ring.rotation.x = Math.PI / 2;
ring.position.set(0, 0.3, 0);
group.add(ring);
const roofWarning = box(
def.w * 0.52,
0.045,
0.13,
shortageMaterial,
0,
def.h + 0.66,
0.42,
group
);
roofWarning.visible = false;
const shortageLabel = document.createElement("div");
shortageLabel.className = "world-label shortage-label";
shortageLabel.innerHTML = "<i></i><span>SHORTAGE</span>";
$("labels").appendChild(shortageLabel);
buildings.push({
...def,
index,
group,
windowMaterial,
shortageBeacon,
shortageMaterial,
ring,
roofWarning,
shortageLabel,
shortage: 0
});
}
buildingDefs.forEach(createBuilding);
// Solar farm.
const solarFarm = new THREE.Group();
solarFarm.position.set(11.4, 0, -6.2);
world.add(solarFarm);
box(5.0, 0.18, 4.5, materials.sidewalk, 0, 0.18, 0, solarFarm);
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 6; col++) {
const x = -1.92 + col * 0.77;
const z = -1.42 + row * 0.94;
const panel = box(0.63, 0.08, 0.72, materials.solarPanel, x, 0.67, z, solarFarm);
panel.rotation.x = -0.22;
box(0.05, 0.48, 0.05, materials.frame, x - 0.2, 0.43, z, solarFarm);
box(0.05, 0.48, 0.05, materials.frame, x + 0.2, 0.43, z, solarFarm);
box(0.65, 0.025, 0.03, materials.frame, x, 0.74, z, solarFarm);
}
}
// Battery rack.
const batteryGroup = new THREE.Group();
batteryGroup.position.set(11.2, 0, 6.2);
world.add(batteryGroup);
box(2.4, 0.22, 2.0, materials.sidewalk, 0, 0.2, 0, batteryGroup);
box(1.85, 0.12, 1.5, materials.frame, 0, 0.37, 0, batteryGroup);
const batteryCells = [];
for (let i = 0; i < 5; i++) {
const cellMaterial = new THREE.MeshStandardMaterial({
color: 0x183b3c,
emissive: COLORS.storage,
emissiveIntensity: 0.8,
metalness: 0.25,
roughness: 0.42
});
const cell = box(1.5, 0.43, 1.15, cellMaterial, 0, 0.62 + i * 0.48, 0, batteryGroup);
batteryCells.push(cell);
box(0.11, 0.08, 0.04, cellMaterial, 0.55, 0.62 + i * 0.48, 0.59, batteryGroup);
}
box(1.7, 0.14, 1.32, materials.frame, 0, 3.0, 0, batteryGroup);
// District hub and transformer.
const hub = new THREE.Group();
hub.position.set(1.8, 0, 2.2);
world.add(hub);
box(1.9, 0.24, 1.8, materials.sidewalk, 0, 0.22, 0, hub);
const hubMaterial = new THREE.MeshStandardMaterial({
color: 0x3c6475,
emissive: 0x173f5f,
emissiveIntensity: 0.65,
metalness: 0.35,
roughness: 0.5
});
box(0.82, 1.35, 0.82, hubMaterial, 0, 0.93, 0, hub);
box(0.94, 0.12, 0.94, materials.frame, 0, 1.65, 0, hub);
for (let i = 0; i < 3; i++) {
const insulator = new THREE.Mesh(
new THREE.CylinderGeometry(0.09, 0.09, 0.2, 10),
materials.frame
);
insulator.position.set(-0.28 + i * 0.28, 1.82, 0);
hub.add(insulator);
}
const hubRing = new THREE.Mesh(
new THREE.TorusGeometry(1.1, 0.045, 8, 42),
new THREE.MeshBasicMaterial({
color: COLORS.demand,
transparent: true,
opacity: 0.55
})
);
hubRing.rotation.x = Math.PI / 2;
hubRing.position.y = 0.37;
hub.add(hubRing);
// Voxel trees.
function createTree(x, z, scale = 1) {
const tree = new THREE.Group();
tree.position.set(x, 0.2, z);
tree.scale.setScalar(scale);
world.add(tree);
box(0.18, 1.15, 0.18, materials.trunk, 0, 0.55, 0, tree);
box(0.85, 0.68, 0.8, materials.leaves, 0, 1.25, 0, tree);
box(0.55, 0.48, 0.55, materials.leavesLight, 0.08, 1.78, 0.03, tree);
}
[
[-13.6, -8.8], [-13.5, -2.5], [-13.7, 2.5], [-13.4, 8.7],
[-8.0, -8.9], [-1.0, -8.8], [5.3, -9.0], [14.8, -8.8],
[14.8, -2.4], [14.7, 2.3], [14.8, 8.9], [8.0, 8.8],
[0.8, 8.8], [-8.2, 8.9], [-3.4, -9.0]
].forEach(([x, z], i) => createTree(x, z, 0.8 + (i % 3) * 0.12));
// Street lamps.
const lampMaterial = new THREE.MeshBasicMaterial({ color: 0xffdda0 });
[
[-1.9, -7.2], [-1.9, -3.4], [-1.9, 4.2], [-1.9, 8],
[2.1, -7.2], [2.1, -3.4], [2.1, 4.2], [2.1, 8],
[-10, -1.9], [-5, -1.9], [5, -1.9], [10, -1.9]
].forEach(([x, z]) => {
box(0.08, 1.45, 0.08, materials.frame, x, 0.84, z);
box(0.34, 0.12, 0.34, lampMaterial, x, 1.58, z);
});
// Visible sun.
const sunMesh = new THREE.Mesh(
new THREE.SphereGeometry(1.25, 20, 20),
new THREE.MeshBasicMaterial({ color: 0xffd68b })
);
scene.add(sunMesh);
// Animated power-flow curves.
const flows = [];
const particleGeometry = new THREE.SphereGeometry(0.09, 8, 8);
function createFlow(points, color, kind, particleCount = 3) {
const curve = new THREE.CatmullRomCurve3(points, false, "catmullrom", 0.25);
const lineMaterial = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.3,
depthTest: false
});
const line = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(curve.getPoints(72)),
lineMaterial
);
line.renderOrder = 8;
scene.add(line);
const particles = [];
const particleMaterial = new THREE.MeshBasicMaterial({
color,
depthTest: false,
transparent: true,
opacity: 0.95
});
for (let i = 0; i < particleCount; i++) {
const particle = new THREE.Mesh(particleGeometry, particleMaterial);
particle.renderOrder = 9;
particle.userData.offset = i / particleCount;
scene.add(particle);
particles.push(particle);
}
const flow = { curve, line, particles, kind, color };
flows.push(flow);
return flow;
}
const hubPoint = new THREE.Vector3(1.8, 1.25, 2.2);
createFlow(
[
new THREE.Vector3(11.4, 0.9, -6.2),
new THREE.Vector3(9.4, 2.3, -5.3),
new THREE.Vector3(5.2, 2.0, -1.5),
hubPoint
],
COLORS.solar,
"solar",
4
);
createFlow(
[
new THREE.Vector3(11.2, 1.1, 6.2),
new THREE.Vector3(8.6, 2.4, 5.3),
new THREE.Vector3(4.8, 2.0, 3.0),
hubPoint
],
COLORS.storage,
"storage",
3
);
buildings.forEach((building) => {
createFlow(
[
hubPoint.clone(),
new THREE.Vector3(lerp(hubPoint.x, building.x, 0.45), 1.7, lerp(hubPoint.z, building.z, 0.45)),
new THREE.Vector3(building.x, 1.45, building.z),
new THREE.Vector3(building.x, building.h + 0.7, building.z)
],
COLORS.demand,
"demand",
2
);
});
// DOM labels projected into the 3D scene.
const labelLayer = $("labels");
function makeWorldLabel(className, html) {
const element = document.createElement("div");
element.className = `world-label ${className}`;
element.innerHTML = html;
labelLayer.appendChild(element);
return element;
}
const solarLabel = makeWorldLabel("solar-label", "<i></i><span>SOLAR ARRAY</span>");
const storageLabel = makeWorldLabel("storage-label", "<i></i><span>BATTERY</span>");
const hubLabel = makeWorldLabel("hub-label", "<i></i><span>DISTRICT HUB</span>");
function placeWorldLabel(element, position, visible = true) {
const projected = position.clone().project(camera);
const onScreen =
visible &&
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.25 &&
projected.x < 1.25 &&
projected.y > -1.25 &&
projected.y < 1.25;
element.style.opacity = onScreen ? "1" : "0";
if (!onScreen) return;
element.style.left = `${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
// Synthetic load and solar profiles.
function solarProfile(hour) {
if (hour < 6 || hour > 19.5) return 0;
const x = (hour - 6) / 13.5;
const clearSky = Math.pow(Math.max(0, Math.sin(Math.PI * x)), 1.25);
const weather = 0.84 + 0.1 * Math.sin(hour * 1.9 + 0.5);
return params.solarCapacity * clearSky * weather;
}
function demandProfile(hour) {
const morning = 1.25 * Math.exp(-Math.pow((hour - 8.2) / 1.45, 2));
const evening = 4.4 * Math.exp(-Math.pow((hour - 18.2) / 2.05, 2));
return (2.1 + morning + evening) * params.demandScale;
}
const schedule = [];
const scheduleStep = 0.1;
function recomputeSchedule() {
schedule.length = 0;
let soc = params.storageCapacity;
const chargeEfficiency = 0.94;
const dischargeEfficiency = 0.94;
for (let index = 0; index <= 240; index++) {
const hour = index * scheduleStep;
const solar = solarProfile(hour);
const demand = demandProfile(hour);
let served = 0;
let discharge = 0;
let charge = 0;
let grid = 0;
let shortage = 0;
if (solar >= demand) {
served = demand;
const excess = solar - demand;
charge = Math.min(
excess * chargeEfficiency,
Math.max(0, params.storageCapacity - soc) / scheduleStep
);
soc += charge;
} else {
served = solar;
let need = demand - solar;
discharge = Math.min(
params.batteryPower,
need,
(soc * dischargeEfficiency) / scheduleStep
);
served += discharge;
soc -= discharge / dischargeEfficiency;
need -= discharge;
grid = Math.min(params.gridLimit, need);
served += grid;
need -= grid;
shortage = Math.max(0, need);
}
schedule.push({
solar,
demand,
served,
discharge,
charge,
grid,
shortage,
soc
});
}
drawChart();
}
function stateAt(hour) {
const position = clamp(hour, 0, 23.95) / scheduleStep;
const low = Math.floor(position);
const high = Math.min(low + 1, schedule.length - 1);
const mix = position - low;
const a = schedule[low];
const b = schedule[high];
return {
solar: lerp(a.solar, b.solar, mix),
demand: lerp(a.demand, b.demand, mix),
served: lerp(a.served, b.served, mix),
discharge: lerp(a.discharge, b.discharge, mix),
charge: lerp(a.charge, b.charge, mix),
grid: lerp(a.grid, b.grid, mix),
shortage: lerp(a.shortage, b.shortage, mix),
soc: lerp(a.soc, b.soc, mix)
};
}
function formatTime(hour) {
const totalMinutes = Math.round(hour * 60) % (24 * 60);
const hours = Math.floor(totalMinutes / 60);
const minutes = totalMinutes % 60;
return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`;
}
function drawChart() {
const chart = $("energyChart");
const rect = chart.getBoundingClientRect();
if (!rect.width || !schedule.length) return;
const dpr = Math.min(window.devicePixelRatio, 2);
const width = rect.width;
const height = rect.height;
if (chart.width !== Math.round(width * dpr) || chart.height !== Math.round(height * dpr)) {
chart.width = Math.round(width * dpr);
chart.height = Math.round(height * dpr);
}
const ctx = chart.getContext("2d");
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
const maxValue = Math.max(
8,
...schedule.map((entry) => Math.max(entry.solar, entry.demand))
) * 1.08;
const padding = { left: 4, right: 4, top: 10, bottom: 13 };
const plotWidth = width - padding.left - padding.right;
const plotHeight = height - padding.top - padding.bottom;
const xFor = (hour) => padding.left + (hour / 24) * plotWidth;
const yFor = (value) => padding.top + plotHeight - (value / maxValue) * plotHeight;
ctx.strokeStyle = "rgba(153, 178, 204, 0.10)";
ctx.lineWidth = 1;
for (let i = 0; i <= 3; i++) {
const y = padding.top + (plotHeight / 3) * i;
ctx.beginPath();
ctx.moveTo(padding.left, y);
ctx.lineTo(width - padding.right, y);
ctx.stroke();
}
// Solar area.
ctx.beginPath();
ctx.moveTo(xFor(0), yFor(0));
schedule.forEach((entry, index) => {
ctx.lineTo(xFor(index * scheduleStep), yFor(entry.solar));
});
ctx.lineTo(xFor(24), yFor(0));
ctx.closePath();
ctx.fillStyle = "rgba(255, 209, 102, 0.15)";
ctx.fill();
ctx.beginPath();
schedule.forEach((entry, index) => {
const x = xFor(index * scheduleStep);
const y = yFor(entry.solar);
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.strokeStyle = "#ffd166";
ctx.lineWidth = 1.7;
ctx.stroke();
// Demand line.
ctx.beginPath();
schedule.forEach((entry, index) => {
const x = xFor(index * scheduleStep);
const y = yFor(entry.demand);
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.strokeStyle = "#67b7ff";
ctx.lineWidth = 1.8;
ctx.stroke();
// Shortage markers along the baseline.
ctx.fillStyle = "#ff6174";
for (const entry of schedule) {
if (entry.shortage > 0.03) {
const index = schedule.indexOf(entry);
ctx.fillRect(xFor(index * scheduleStep), yFor(0) - 2, 1.2, 2.5);
}
}
// Current time cursor.
const currentX = xFor(currentTime);
ctx.strokeStyle = "rgba(237, 245, 255, 0.65)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(currentX, padding.top);
ctx.lineTo(currentX, height - padding.bottom + 2);
ctx.stroke();
ctx.fillStyle = "rgba(141, 160, 184, 0.7)";
ctx.font = "8px system-ui";
ctx.fillText("00", 2, height - 2);
ctx.fillText("12", xFor(12) - 4, height - 2);
ctx.fillText("24", width - 13, height - 2);
$("chartCapacity").textContent = `${maxValue.toFixed(0)} kW`;
}
function updateReadouts(state) {
$("clock").textContent = formatTime(currentTime);
$("solarMetric").textContent = state.solar.toFixed(1);
$("demandMetric").textContent = state.demand.toFixed(1);
$("batteryMetric").textContent = state.discharge.toFixed(1);
$("shortageMetric").textContent = state.shortage.toFixed(1);
const socPercent = clamp(
(state.soc / Math.max(params.storageCapacity, 0.01)) * 100,
0,
100
);
$("socText").textContent = `${socPercent.toFixed(0)}%`;
$("socFill").style.width = `${socPercent}%`;
const totalSupply = state.solar + state.discharge + state.grid;
$("totalSupply").textContent = `${totalSupply.toFixed(1)} kW`;
const denominator = Math.max(totalSupply, state.demand, 0.1);
$("solarBar").style.width = `${(state.solar / denominator) * 100}%`;
$("batteryBar").style.width = `${(state.discharge / denominator) * 100}%`;
$("gridBar").style.width = `${(state.grid / denominator) * 100}%`;
$("solarBarText").textContent = state.solar.toFixed(1);
$("batteryBarText").textContent = state.discharge.toFixed(1);
$("gridBarText").textContent = state.grid.toFixed(1);
const shortageActive = state.shortage > 0.05;
$("statusDot").classList.toggle("warning", shortageActive);
$("gridState").textContent = shortageActive ? "SHORTAGE" : "BALANCED";
$("shortageCard").style.opacity = shortageActive ? "1" : "0.64";
if (shortageActive) {
$("operatingNotes").textContent =
`${state.shortage.toFixed(1)} kW is unserved. Red beacons identify affected loads. ` +
(params.gridLimit === 0
? "Increase grid import or battery output to close the gap."
: "Grid import is active but not sufficient for the current deficit.");
} else if (state.charge > 0.05) {
$("operatingNotes").textContent =
`Solar surplus is charging the battery at ${state.charge.toFixed(1)} kW. ` +
`State of charge is ${socPercent.toFixed(0)}%.`;
} else {
$("operatingNotes").textContent =
`Local supply is balancing demand. The battery remains available for the evening ramp.`;
}
solarLabel.querySelector("span").textContent =
`SOLAR ARRAY · ${state.solar.toFixed(1)} kW`;
storageLabel.querySelector("span").textContent =
`BATTERY · ${socPercent.toFixed(0)}%`;
}
function updateVisuals(state, elapsed) {
// Day/night lighting.
const solarAngle =
currentTime >= 6 && currentTime <= 19.5
? Math.sin(Math.PI * ((currentTime - 6) / 13.5))
: -0.2;
const daylight = clamp(solarAngle, 0, 1);
const sunset = clamp(1 - Math.abs(solarAngle - 0.15) / 0.55, 0, 1);
const nightColor = new THREE.Color(0x07111f);
const dayColor = new THREE.Color(0x142c43);
const sunsetColor = new THREE.Color(0x2a1932);
const background = nightColor.clone().lerp(dayColor, daylight * 0.8);
background.lerp(sunsetColor, sunset * 0.55);
scene.background.copy(background);
scene.fog.color.copy(background);
sunLight.intensity = 0.35 + daylight * 2.8;
sunLight.color.set(sunset > 0.35 ? 0xffad72 : 0xfff0cf);
hemisphere.intensity = 0.65 + daylight * 0.85;
const sunProgress = clamp((currentTime - 6) / 13.5, 0, 1);
sunMesh.position.set(
-15 + sunProgress * 30,
1.4 + Math.max(0, solarAngle) * 19,
-16
);
sunMesh.visible = currentTime >= 6 && currentTime <= 19.5;
sunLight.position.copy(sunMesh.position);
// Solar panels respond to irradiance.
const solarRatio = clamp(state.solar / Math.max(params.solarCapacity, 0.1), 0, 1);
materials.solarPanel.emissiveIntensity = 0.16 + solarRatio * 1.15;
// Battery cell illumination follows SOC.
const socRatio = clamp(state.soc / Math.max(params.storageCapacity, 0.1), 0, 1);
batteryCells.forEach((cell, index) => {
const lowerCells = index === 0 ? 0.25 : 1;
cell.material.emissiveIntensity = 0.08 + socRatio * 1.2 * lowerCells;
cell.material.emissive.set(socRatio < 0.2 ? 0xff6174 : 0x58e6b4);
});
// Distribute shortages among the synthetic neighborhood loads.
const weightTotal = buildings.reduce((sum, building) => sum + building.weight, 0);
buildings.forEach((building) => {
building.shortage = (state.shortage * building.weight) / weightTotal;
building.group.visible = true;
});
const shortageBuildings = [...buildings].sort(
(a, b) => b.shortage - a.shortage
);
const visibleShortageLabels = new Set(shortageBuildings.slice(0, 3));
buildings.forEach((building) => {
const shortageActive = building.shortage > 0.055;
building.shortageBeacon.visible = shortageActive;
building.roofWarning.visible = shortageActive;
if (shortageActive) {
const pulse = 0.72 + Math.sin(elapsed * 5.5 + building.index) * 0.25;
building.shortageMaterial.opacity = pulse;
building.ring.scale.setScalar(1 + Math.sin(elapsed * 4 + building.index) * 0.12);
}
const demandShare = state.demand * (building.weight / weightTotal);
const servedRatio = clamp(
1 - building.shortage / Math.max(demandShare, 0.001),
0.15,
1
);
const nightGlow = 0.25 + (1 - daylight) * 0.75;
const brightness = (0.18 + nightGlow * 0.82) * servedRatio;
building.windowMaterial.color.setRGB(
0.3 + brightness * 0.5,
0.48 + brightness * 0.35,
0.62 + brightness * 0.28
);
building.windowMaterial.opacity = 0.3 + servedRatio * 0.65;
const labelVisible = visibleShortageLabels.has(building);
building.shortageLabel.querySelector("span").textContent =
`${building.name.toUpperCase()} · ${building.shortage.toFixed(1)} kW SHORT`;
building.shortageLabel.style.opacity = labelVisible ? "1" : "0";
});
// Flow particles and line strength.
flows.forEach((flow, index) => {
let value = 0;
let speed = 0.2;
let reverse = false;
if (flow.kind === "solar") {
value = state.solar;
speed = 0.16 + solarRatio * 0.65;
} else if (flow.kind === "storage") {
value = Math.max(state.discharge, state.charge);
speed = 0.18 + clamp(value / 5, 0, 1) * 0.72;
reverse = state.charge > state.discharge + 0.02;
} else {
value = state.demand;
speed = 0.12 + clamp(state.demand / 8, 0, 1) * 0.55;
}
const ratio = clamp(value / 7, 0, 1);
flow.line.material.opacity = 0.13 + ratio * 0.35;
flow.particles.forEach((particle, particleIndex) => {
const progress = (elapsed * speed + particle.userData.offset) % 1;
const pathProgress = reverse ? 1 - progress : progress;
particle.position.copy(flow.curve.getPointAt(pathProgress));
particle.visible = value > 0.035;
particle.scale.setScalar(0.72 + ratio * 0.75);
particle.material.opacity = 0.62 + ratio * 0.38;
});
});
hubRing.material.opacity = 0.36 + Math.sin(elapsed * 2.2) * 0.12;
}
// Custom camera controls, implemented without Three.js addons.
canvas.addEventListener("pointerdown", (event) => {
orbit.dragging = true;
orbit.panning = event.button === 2 || event.shiftKey;
orbit.lastX = event.clientX;
orbit.lastY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!orbit.dragging) return;
const dx = event.clientX - orbit.lastX;
const dy = event.clientY - orbit.lastY;
orbit.lastX = event.clientX;
orbit.lastY = event.clientY;
if (orbit.panning) {
const right = new THREE.Vector3(Math.cos(orbit.yaw), 0, -Math.sin(orbit.yaw));
const forward = new THREE.Vector3(Math.sin(orbit.yaw), 0, Math.cos(orbit.yaw));
const scale = orbit.distance * 0.0015;
orbit.target.addScaledVector(right, -dx * scale);
orbit.target.addScaledVector(forward, -dy * scale);
orbit.target.x = clamp(orbit.target.x, -12, 12);
orbit.target.z = clamp(orbit.target.z, -10, 10);
} else {
orbit.yaw -= dx * 0.0055;
orbit.pitch = clamp(orbit.pitch + dy * 0.0045, 0.35, 1.22);
}
});
function endPointer(event) {
orbit.dragging = false;
orbit.panning = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.distance = clamp(
orbit.distance * Math.exp(event.deltaY * 0.001),
22,
58
);
},
{ passive: false }
);
// UI controls.
function syncControlValues() {
$("solarValue").textContent = `${params.solarCapacity.toFixed(1)} kW`;
$("storageValue").textContent = `${params.storageCapacity.toFixed(1)} kWh`;
$("batteryValue").textContent = `${params.batteryPower.toFixed(1)} kW`;
$("demandValue").textContent = `${params.demandScale.toFixed(2)}×`;
$("gridValue").textContent = `${params.gridLimit.toFixed(1)} kW`;
$("solarRange").value = params.solarCapacity;
$("storageRange").value = params.storageCapacity;
$("batteryRange").value = params.batteryPower;
$("demandRange").value = params.demandScale;
$("gridRange").value = params.gridLimit;
}
function scenarioChanged() {
syncControlValues();
recomputeSchedule();
updateReadouts(stateAt(currentTime));
}
[
["solarRange", "solarCapacity"],
["storageRange", "storageCapacity"],
["batteryRange", "batteryPower"],
["demandRange", "demandScale"],
["gridRange", "gridLimit"]
].forEach(([id, key]) => {
$(id).addEventListener("input", (event) => {
params[key] = Number(event.target.value);
scenarioChanged();
});
});
$("timeRange").addEventListener("input", (event) => {
currentTime = Number(event.target.value);
playing = false;
$("playButton").textContent = "▶";
updateReadouts(stateAt(currentTime));
drawChart();
});
$("playButton").addEventListener("click", () => {
playing = !playing;
$("playButton").textContent = playing ? "Ⅱ" : "▶";
});
$("speedButton").addEventListener("click", () => {
speedMultiplier = speedMultiplier === 1 ? 2 : speedMultiplier === 2 ? 0.5 : 1;
$("speedButton").textContent = `${speedMultiplier}×`;
});
$("peakButton").addEventListener("click", () => {
params.solarCapacity = 4.5;
params.storageCapacity = 8;
params.batteryPower = 3;
params.demandScale = 1.25;
params.gridLimit = 0;
currentTime = 18.5;
$("timeRange").value = currentTime;
scenarioChanged();
drawChart();
});
$("resetButton").addEventListener("click", () => {
Object.assign(params, defaults);
currentTime = 18.5;
$("timeRange").value = currentTime;
scenarioChanged();
drawChart();
});
$("panelToggle").addEventListener("click", () => {
document.body.classList.toggle("controls-open");
});
window.addEventListener("keydown", (event) => {
if (
event.code === "Space" &&
!["INPUT", "BUTTON"].includes(document.activeElement?.tagName)
) {
event.preventDefault();
$("playButton").click();
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
drawChart();
});
// Initial state and render loop.
syncControlValues();
recomputeSchedule();
updateReadouts(stateAt(currentTime));
const clock = new THREE.Clock();
let elapsed = 0;
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
elapsed += delta;
if (playing) {
currentTime = (currentTime + delta * 0.72 * speedMultiplier) % 24;
$("timeRange").value = currentTime;
}
const state = stateAt(currentTime);
updateReadouts(state);
updateVisuals(state, elapsed);
updateCamera();
placeWorldLabel(
solarLabel,
new THREE.Vector3(11.4, 2.5, -6.2)
);
placeWorldLabel(
storageLabel,
new THREE.Vector3(11.2, 4.05, 6.2)
);
placeWorldLabel(
hubLabel,
new THREE.Vector3(1.8, 2.35, 2.2)
);
buildings.forEach((building) => {
const position = building.group.localToWorld(
new THREE.Vector3(0, building.h + 1.65, 0)
);
placeWorldLabel(
building.shortageLabel,
position,
building.shortage > 0.055 && building.shortageLabel.style.opacity !== "0"
);
});
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```