Prompt specification
Build or customize the Three.js 3D scene "Balance light supply storage and a fixed load" 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: Balance light supply storage and a fixed load
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/balance-light-supply-storage-and-a-fixed-load-x2536
Scene Description Prompt:
Please make a voxel Three.js scene in one standalone HTML file using cdnjs. Let users vary daylight in a simple solar-storage scene. Track energy entering, stored, and consumed under stated assumptions, showing when the load exceeds available supply.
Working Three.js Starter (balance-light-supply-storage-and-a-fixed-load-x2536):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Solar / Storage Lab</title>
<style>
:root {
--ink: #eef8f6;
--muted: #91a7aa;
--panel: rgba(8, 25, 30, 0.88);
--line: rgba(180, 225, 218, 0.14);
--green: #65e3a5;
--blue: #70bfff;
--gold: #ffd166;
--red: #ff6978;
--fill: 65%;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #07151b;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input,
select {
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;
}
.title-block {
position: fixed;
top: 24px;
left: 26px;
z-index: 5;
pointer-events: none;
text-shadow: 0 2px 20px rgba(0, 0, 0, 0.5);
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
color: var(--green);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
width: 18px;
height: 3px;
content: "";
border-radius: 4px;
background: var(--green);
box-shadow: 0 0 14px rgba(101, 227, 165, 0.6);
}
h1 {
margin: 0;
max-width: 430px;
font-size: clamp(28px, 4vw, 50px);
line-height: 0.96;
letter-spacing: -0.045em;
}
.subtitle {
max-width: 370px;
margin: 12px 0 0;
color: #c3d7d4;
font-size: 13px;
line-height: 1.55;
}
.control-panel {
position: fixed;
z-index: 10;
top: 20px;
right: 20px;
width: min(370px, calc(100vw - 40px));
max-height: calc(100dvh - 40px);
padding: 18px;
overflow: auto;
border: 1px solid var(--line);
border-radius: 22px;
background:
linear-gradient(145deg, rgba(19, 48, 53, 0.94), rgba(6, 21, 26, 0.93));
box-shadow:
0 24px 70px rgba(0, 0, 0, 0.35),
inset 0 1px rgba(255, 255, 255, 0.04);
backdrop-filter: blur(18px);
scrollbar-width: thin;
scrollbar-color: rgba(101, 227, 165, 0.35) transparent;
}
.panel-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 14px;
}
.panel-kicker {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.sim-clock {
color: #b7c9c7;
font-variant-numeric: tabular-nums;
font-size: 11px;
}
.status {
display: flex;
align-items: center;
gap: 10px;
min-height: 48px;
padding: 10px 12px;
border: 1px solid rgba(101, 227, 165, 0.25);
border-radius: 13px;
background: rgba(101, 227, 165, 0.08);
}
.status-dot {
width: 10px;
height: 10px;
flex: 0 0 auto;
border-radius: 3px;
background: var(--green);
box-shadow: 0 0 15px rgba(101, 227, 165, 0.8);
}
.status strong {
display: block;
font-size: 12px;
letter-spacing: 0.07em;
}
.status small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.status.bridge {
border-color: rgba(255, 209, 102, 0.3);
background: rgba(255, 209, 102, 0.08);
}
.status.bridge .status-dot {
background: var(--gold);
box-shadow: 0 0 15px rgba(255, 209, 102, 0.75);
}
.status.deficit {
border-color: rgba(255, 105, 120, 0.42);
background: rgba(255, 105, 120, 0.1);
}
.status.deficit .status-dot {
background: var(--red);
box-shadow: 0 0 15px rgba(255, 105, 120, 0.85);
animation: alert-pulse 1s ease-in-out infinite alternate;
}
@keyframes alert-pulse {
to {
transform: scale(1.35);
opacity: 0.6;
}
}
.daylight-control {
margin: 18px 0 14px;
}
.control-title {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.control-title label {
color: #d7e8e5;
font-size: 12px;
font-weight: 700;
}
#daylightValue {
color: var(--gold);
font-size: 19px;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 8px;
margin: 0;
appearance: none;
border-radius: 999px;
outline: none;
background:
linear-gradient(
to right,
var(--gold) 0%,
var(--gold) var(--fill),
rgba(255, 255, 255, 0.12) var(--fill),
rgba(255, 255, 255, 0.12) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 20px;
height: 20px;
appearance: none;
border: 4px solid #f6fffb;
border-radius: 5px;
background: #2d8265;
box-shadow: 0 3px 12px rgba(0, 0, 0, 0.45);
}
input[type="range"]::-moz-range-thumb {
width: 13px;
height: 13px;
border: 4px solid #f6fffb;
border-radius: 5px;
background: #2d8265;
box-shadow: 0 3px 12px rgba(0, 0, 0, 0.45);
}
.range-labels {
display: flex;
justify-content: space-between;
margin-top: 7px;
color: #758c8e;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.preset-row,
.button-row {
display: flex;
gap: 7px;
}
.preset-row {
margin-bottom: 13px;
}
.preset-row button,
.button-row button {
flex: 1;
padding: 8px 6px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.035);
color: #a9bdbc;
font-size: 10px;
font-weight: 750;
cursor: pointer;
transition: 160ms ease;
}
.preset-row button:hover,
.button-row button:hover {
border-color: rgba(101, 227, 165, 0.45);
background: rgba(101, 227, 165, 0.08);
color: white;
}
#runButton {
border-color: rgba(101, 227, 165, 0.38);
background: rgba(101, 227, 165, 0.1);
color: var(--green);
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 14px;
}
.metric {
min-height: 88px;
padding: 11px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.025);
}
.metric-label {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric-value {
display: block;
margin: 6px 0 4px;
font-size: 20px;
line-height: 1;
font-weight: 800;
letter-spacing: -0.035em;
font-variant-numeric: tabular-nums;
}
.metric-meta {
color: #849b9c;
font-size: 10px;
line-height: 1.35;
}
.metric.solar .metric-value {
color: var(--gold);
}
.metric.battery .metric-value {
color: var(--green);
}
.metric.load .metric-value {
color: var(--blue);
}
.metric.deficit.is-alert {
border-color: rgba(255, 105, 120, 0.45);
background: rgba(255, 105, 120, 0.09);
}
.metric.deficit.is-alert .metric-value {
color: var(--red);
}
.battery-meter {
height: 5px;
margin-top: 8px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.09);
}
#batteryMeterFill {
width: 40%;
height: 100%;
border-radius: inherit;
background: var(--green);
box-shadow: 0 0 12px rgba(101, 227, 165, 0.55);
transition: width 180ms linear;
}
.chart-section {
margin-top: 14px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(0, 0, 0, 0.11);
}
.chart-heading {
display: flex;
justify-content: space-between;
align-items: center;
color: #c8d9d7;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.chart-heading span:last-child {
color: #71898a;
font-size: 9px;
font-weight: 600;
letter-spacing: 0;
text-transform: none;
}
#energyChart {
display: block;
width: 100%;
height: 120px;
margin-top: 7px;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 11px;
color: #809697;
font-size: 9px;
}
.legend i {
display: inline-block;
width: 7px;
height: 7px;
margin-right: 4px;
border-radius: 2px;
vertical-align: 0;
}
.assumptions {
margin-top: 12px;
padding: 11px 12px;
border-left: 3px solid rgba(112, 191, 255, 0.55);
border-radius: 0 9px 9px 0;
background: rgba(112, 191, 255, 0.055);
color: #9bb1b1;
font-size: 10px;
line-height: 1.55;
}
.assumptions strong {
display: block;
margin-bottom: 4px;
color: #d5e5e3;
font-size: 10px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.scene-tag {
position: fixed;
z-index: 4;
min-width: 104px;
padding: 7px 9px;
pointer-events: none;
border: 1px solid rgba(210, 242, 236, 0.19);
border-radius: 9px;
background: rgba(6, 20, 25, 0.76);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(8px);
transform: translate(-50%, -100%);
transition: opacity 120ms linear;
}
.scene-tag span {
display: block;
color: #8ca3a2;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.13em;
}
.scene-tag b {
display: block;
margin-top: 2px;
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.help {
position: fixed;
z-index: 4;
left: 26px;
bottom: 22px;
color: rgba(220, 239, 236, 0.62);
font-size: 10px;
font-weight: 650;
letter-spacing: 0.04em;
pointer-events: none;
}
@media (max-width: 760px) {
.title-block {
top: 14px;
left: 16px;
}
h1 {
max-width: 270px;
font-size: 31px;
}
.subtitle {
display: none;
}
.control-panel {
top: auto;
right: 10px;
bottom: 10px;
width: calc(100vw - 20px);
max-height: 54dvh;
padding: 14px;
border-radius: 18px;
}
.metrics {
grid-template-columns: repeat(4, minmax(120px, 1fr));
overflow-x: auto;
padding-bottom: 3px;
}
.metric {
min-height: 82px;
}
.scene-tag {
display: none;
}
.help {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive voxel solar and battery storage scene"></canvas>
<header class="title-block">
<div class="eyebrow">Voxel energy model</div>
<h1>Solar /<br />Storage Lab</h1>
<p class="subtitle">
Vary daylight and watch a small solar array charge a battery,
serve a continuous load, and expose any supply shortfall.
</p>
</header>
<aside class="control-panel" aria-label="Energy simulation controls">
<div class="panel-head">
<div class="panel-kicker">Live energy ledger</div>
<div class="sim-clock" id="simClock">Sim 0.0 h</div>
</div>
<div class="status" id="statusBox" role="status" aria-live="polite">
<span class="status-dot"></span>
<div>
<strong id="statusTitle">SOLAR COVERS LOAD</strong>
<small id="statusDetail">Solar alone supplies the full demand.</small>
</div>
</div>
<div class="daylight-control">
<div class="control-title">
<label for="daylight">Daylight / irradiance</label>
<output id="daylightValue" for="daylight">65%</output>
</div>
<input
id="daylight"
type="range"
min="0"
max="100"
value="65"
step="1"
aria-label="Daylight percentage"
/>
<div class="range-labels">
<span>Night</span>
<span>Overcast</span>
<span>Full sun</span>
</div>
</div>
<div class="preset-row">
<button type="button" data-daylight="0">Night</button>
<button type="button" data-daylight="25">Dawn</button>
<button type="button" data-daylight="65">Daylight</button>
<button type="button" data-daylight="100">Peak sun</button>
</div>
<div class="button-row">
<button type="button" id="runButton">Pause</button>
<button type="button" id="resetButton">Reset scenario</button>
</div>
<div class="metrics">
<section class="metric solar">
<div class="metric-label">Solar entering</div>
<strong class="metric-value" id="solarPower">3.90 kW</strong>
<div class="metric-meta" id="solarEnergy">0.00 kWh captured</div>
</section>
<section class="metric battery">
<div class="metric-label">Battery stored</div>
<strong class="metric-value" id="batteryStored">3.20 kWh</strong>
<div class="metric-meta" id="batteryFlow">40% · idle</div>
<div class="battery-meter">
<div id="batteryMeterFill"></div>
</div>
</section>
<section class="metric load">
<div class="metric-label">Load consumed</div>
<strong class="metric-value" id="loadPower">1.50 kW</strong>
<div class="metric-meta" id="loadEnergy">0.00 kWh served</div>
</section>
<section class="metric deficit" id="deficitCard">
<div class="metric-label">Unmet load</div>
<strong class="metric-value" id="unmetEnergy">0.00 kWh</strong>
<div class="metric-meta" id="unmetDetail">All demand served</div>
</section>
</div>
<section class="chart-section">
<div class="chart-heading">
<span>Energy ledger</span>
<span>recent history · kWh</span>
</div>
<canvas id="energyChart" aria-label="Energy history chart"></canvas>
<div class="legend">
<span><i style="background:#ffd166"></i>Entered</span>
<span><i style="background:#70bfff"></i>Consumed</span>
<span><i style="background:#65e3a5"></i>Stored</span>
</div>
</section>
<div class="assumptions">
<strong>Stated model assumptions</strong>
6.0 kWp PV array; solar output = 6.0 kW × daylight. Continuous
1.5 kW load. Battery: 8.0 kWh usable, 4.0 kW maximum charge,
3.0 kW maximum discharge. Direct load is served first; surplus
charges the battery, then excess is curtailed. Battery serves a
shortfall. Conversion losses and grid export are ignored.
Calculations use 15-minute steps.
</div>
</aside>
<div class="scene-tag" id="tagSolar">
<span>PV ARRAY</span>
<b id="tagSolarValue">3.90 kW</b>
</div>
<div class="scene-tag" id="tagBattery">
<span>BATTERY</span>
<b id="tagBatteryValue">3.20 kWh</b>
</div>
<div class="scene-tag" id="tagHouse">
<span>LOAD</span>
<b id="tagHouseValue">1.50 kW</b>
</div>
<div class="help">DRAG TO ORBIT · SCROLL TO ZOOM · DOUBLE-CLICK TO RESET VIEW</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Model constants and state
// -------------------------------------------------------------------------
const MODEL = Object.freeze({
pvPeakKW: 6.0,
loadKW: 1.5,
batteryCapacityKWh: 8.0,
batteryChargeMaxKW: 4.0,
batteryDischargeMaxKW: 3.0,
stepHours: 0.25,
simulatedHoursPerRealSecond: 0.5
});
const state = {
daylight: 0.65,
batteryKWh: 3.2,
solarEnteredKWh: 0,
loadConsumedKWh: 0,
unmetKWh: 0,
curtailedKWh: 0,
lastDirectKW: 0,
lastChargeKW: 0,
lastDischargeKW: 0,
lastUnmetKW: 0,
simHours: 0,
running: true,
history: []
};
const $ = (id) => document.getElementById(id);
const daylightInput = $("daylight");
const chartCanvas = $("energyChart");
const chartContext = chartCanvas.getContext("2d");
// -------------------------------------------------------------------------
// Renderer, camera, lights
// -------------------------------------------------------------------------
const canvas = $("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 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.08;
const scene = new THREE.Scene();
const nightSky = new THREE.Color(0x07151f);
const daySky = new THREE.Color(0x9fd9e5);
scene.background = nightSky.clone();
scene.fog = new THREE.Fog(nightSky.clone(), 19, 38);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0.7, 1.15, 0);
const cameraState = {
radius: 18,
theta: 0.73,
phi: 1.01
};
function updateCamera() {
const { radius, theta, phi } = cameraState;
const sinPhi = Math.sin(phi);
camera.position.set(
cameraTarget.x + radius * sinPhi * Math.cos(theta),
cameraTarget.y + radius * Math.cos(phi),
cameraTarget.z + radius * sinPhi * Math.sin(theta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xc9eff2, 0x4e4b35, 1.2);
scene.add(hemisphere);
const ambient = new THREE.AmbientLight(0xffffff, 0.2);
scene.add(ambient);
const sunLight = new THREE.DirectionalLight(0xfff0bd, 2.0);
sunLight.position.set(-7, 12, -5);
sunLight.castShadow = true;
sunLight.shadow.mapSize.set(2048, 2048);
sunLight.shadow.camera.left = -14;
sunLight.shadow.camera.right = 14;
sunLight.shadow.camera.top = 12;
sunLight.shadow.camera.bottom = -12;
sunLight.shadow.camera.near = 1;
sunLight.shadow.camera.far = 35;
sunLight.shadow.bias = -0.0008;
scene.add(sunLight);
// -------------------------------------------------------------------------
// Voxel helpers and materials
// -------------------------------------------------------------------------
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.85,
metalness: 0.02,
...options
});
}
function addBox(width, height, depth, material, x, y, z, parent = scene) {
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;
}
const materials = {
platform: standardMaterial(0x263a38),
path: standardMaterial(0xb7a879),
grassA: standardMaterial(0x4f7650),
grassB: standardMaterial(0x587f55),
grassC: standardMaterial(0x456c48),
trunk: standardMaterial(0x6b4b35),
leaves: standardMaterial(0x397a50),
leavesLight: standardMaterial(0x4d925b),
wall: standardMaterial(0xe2d6bd),
wallSide: standardMaterial(0xcbbba0),
roof: standardMaterial(0xb75b48),
roofDark: standardMaterial(0x8f4438),
door: standardMaterial(0x5b4336),
frame: standardMaterial(0x52656b, { metalness: 0.25 }),
support: standardMaterial(0x879396, { metalness: 0.35 }),
battery: standardMaterial(0xd6ded8, { metalness: 0.12 }),
batterySide: standardMaterial(0xaebbb8, { metalness: 0.15 }),
batteryTop: standardMaterial(0xe9a94f),
screen: standardMaterial(0x102a2b, {
emissive: 0x174c3e,
emissiveIntensity: 0.65
}),
conduit: standardMaterial(0x596c67, { metalness: 0.25 })
};
const panelMaterial = standardMaterial(0x19528b, {
roughness: 0.36,
metalness: 0.3,
emissive: 0x08284c,
emissiveIntensity: 0.45
});
const panelGridMaterial = standardMaterial(0x6fc4db, {
roughness: 0.4,
metalness: 0.25,
emissive: 0x0b3047,
emissiveIntensity: 0.25
});
const windowMaterial = standardMaterial(0xffd680, {
emissive: 0xffaa38,
emissiveIntensity: 1.25
});
const cloudMaterial = standardMaterial(0xe7f2ef, {
roughness: 1,
transparent: true,
opacity: 0.9
});
// -------------------------------------------------------------------------
// Voxel terrain
// -------------------------------------------------------------------------
addBox(20.5, 0.65, 14.5, materials.platform, 0, -0.72, 0);
const columns = 20;
const rows = 14;
const tileGeometry = new THREE.BoxGeometry(0.96, 0.42, 0.96);
const tileMaterial = standardMaterial(0xffffff);
const tiles = new THREE.InstancedMesh(
tileGeometry,
tileMaterial,
columns * rows
);
tiles.receiveShadow = true;
tiles.castShadow = false;
const dummy = new THREE.Object3D();
const tileColor = new THREE.Color();
let tileIndex = 0;
for (let row = 0; row < rows; row++) {
for (let col = 0; col < columns; col++) {
const x = col - (columns - 1) / 2;
const z = row - (rows - 1) / 2;
dummy.position.set(x, -0.28, z);
dummy.updateMatrix();
tiles.setMatrixAt(tileIndex, dummy.matrix);
const variation = ((col * 17 + row * 31) % 7) / 100;
tileColor.setHSL(0.29, 0.24, 0.30 + variation);
if (row === 6 || row === 7) {
if (x > -3 && x < 3.5) {
tileColor.set(0xa99c72);
}
}
tiles.setColorAt(tileIndex, tileColor);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
if (tiles.instanceColor) tiles.instanceColor.needsUpdate = true;
scene.add(tiles);
// -------------------------------------------------------------------------
// Solar array
// -------------------------------------------------------------------------
const solarGroup = new THREE.Group();
solarGroup.position.set(-5.15, 0, 0);
scene.add(solarGroup);
function createSolarPanel() {
const group = new THREE.Group();
addBox(1.62, 0.12, 1.72, materials.frame, 0, 0, 0, group);
addBox(1.48, 0.06, 1.58, panelMaterial, 0, 0.09, 0, group);
for (let i = -1; i <= 1; i++) {
addBox(
1.38,
0.025,
0.035,
panelGridMaterial,
0,
0.135,
i * 0.48,
group
);
}
addBox(0.035, 0.025, 1.48, panelGridMaterial, 0, 0.136, 0, group);
return group;
}
const panelXs = [-1.7, 0, 1.7];
const panelZs = [-1.1, 1.1];
for (const px of panelXs) {
for (const pz of panelZs) {
const panel = createSolarPanel();
panel.position.set(px, 1.2, pz);
panel.rotation.x = -0.38;
solarGroup.add(panel);
}
addBox(
0.15,
1.18,
0.15,
materials.support,
px,
0.6,
-1.1,
solarGroup
);
addBox(
0.15,
1.18,
0.15,
materials.support,
px,
0.6,
1.1,
solarGroup
);
addBox(
0.16,
0.14,
3.2,
materials.support,
px,
0.86,
0,
solarGroup
);
}
addBox(4.8, 0.18, 0.2, materials.conduit, 0, 0.13, 1.75, solarGroup);
// -------------------------------------------------------------------------
// Battery cabinet
// -------------------------------------------------------------------------
const batteryGroup = new THREE.Group();
batteryGroup.position.set(0, 0, 0);
scene.add(batteryGroup);
addBox(2.05, 2.65, 1.72, materials.battery, 0, 1.35, 0, batteryGroup);
addBox(2.16, 0.22, 1.84, materials.batterySide, 0, 2.77, 0, batteryGroup);
addBox(2.22, 0.18, 1.9, materials.batteryTop, 0, 2.94, 0, batteryGroup);
addBox(0.72, 0.45, 0.08, materials.screen, 0.45, 2.35, 0.89, batteryGroup);
const batterySegments = [];
for (let i = 0; i < 5; i++) {
const material = standardMaterial(0x65e3a5, {
emissive: 0x23885d,
emissiveIntensity: 0.7
});
const segment = addBox(
1.3,
0.22,
0.08,
material,
0,
0.55 + i * 0.39,
0.9,
batteryGroup
);
batterySegments.push(segment);
}
// Small voxel lightning emblem.
addBox(0.16, 0.58, 0.09, materials.batteryTop, -0.55, 1.65, 0.91, batteryGroup);
addBox(0.35, 0.16, 0.1, materials.batteryTop, -0.46, 1.45, 0.91, batteryGroup);
addBox(0.27, 0.16, 0.1, materials.batteryTop, -0.55, 1.25, 0.91, batteryGroup);
// -------------------------------------------------------------------------
// House / load
// -------------------------------------------------------------------------
const houseGroup = new THREE.Group();
houseGroup.position.set(5.0, 0, 0);
scene.add(houseGroup);
addBox(3.0, 2.55, 2.8, materials.wall, 0, 1.3, 0, houseGroup);
addBox(0.25, 2.55, 2.82, materials.wallSide, -1.48, 1.3, 0, houseGroup);
addBox(3.2, 0.42, 3.0, materials.roof, 0, 2.72, 0, houseGroup);
addBox(2.45, 0.4, 2.45, materials.roofDark, 0, 3.08, 0, houseGroup);
addBox(1.45, 0.38, 1.85, materials.roof, 0, 3.42, 0, houseGroup);
addBox(0.7, 1.4, 0.12, materials.door, 0, 0.73, 1.45, houseGroup);
addBox(0.78, 0.13, 0.16, materials.frame, 0, 1.48, 1.49, houseGroup);
addBox(0.12, 0.12, 0.12, materials.batteryTop, 0.23, 0.72, 1.54, houseGroup);
addBox(0.66, 0.66, 0.1, windowMaterial, -0.9, 1.5, 1.45, houseGroup);
addBox(0.66, 0.66, 0.1, windowMaterial, 0.9, 1.5, 1.45, houseGroup);
addBox(0.08, 0.74, 0.13, materials.frame, -0.9, 1.5, 1.51, houseGroup);
addBox(0.74, 0.08, 0.13, materials.frame, -0.9, 1.5, 1.51, houseGroup);
addBox(0.08, 0.74, 0.13, materials.frame, 0.9, 1.5, 1.51, houseGroup);
addBox(0.74, 0.08, 0.13, materials.frame, 0.9, 1.5, 1.51, houseGroup);
addBox(0.45, 1.25, 0.45, materials.wallSide, 0.85, 3.75, -0.45, houseGroup);
addBox(0.58, 0.16, 0.58, materials.roofDark, 0.85, 4.42, -0.45, houseGroup);
// -------------------------------------------------------------------------
// Voxel landscaping
// -------------------------------------------------------------------------
function addTree(x, z, scale = 1) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.scale.setScalar(scale);
addBox(0.34, 1.65, 0.34, materials.trunk, 0, 0.83, 0, group);
addBox(1.45, 0.95, 1.45, materials.leaves, 0, 2.0, 0, group);
addBox(0.9, 0.85, 0.9, materials.leavesLight, 0.35, 2.72, 0.12, group);
addBox(0.85, 0.65, 1.1, materials.leaves, -0.35, 2.48, -0.18, group);
scene.add(group);
}
addTree(-8.4, -4.5, 0.85);
addTree(-8.3, 4.3, 1.0);
addTree(8.25, -4.4, 0.9);
addTree(8.2, 4.4, 1.05);
addTree(1.8, -4.7, 0.75);
addTree(-1.4, 4.9, 0.72);
function addCloud(x, y, z, scale) {
const group = new THREE.Group();
group.position.set(x, y, z);
group.scale.setScalar(scale);
addBox(2.1, 0.65, 0.9, cloudMaterial, 0, 0, 0, group);
addBox(1.1, 0.9, 1.0, cloudMaterial, -0.45, 0.38, 0, group);
addBox(1.35, 0.75, 0.9, cloudMaterial, 0.75, 0.25, 0, group);
addBox(0.75, 0.55, 0.8, cloudMaterial, 0.1, 0.55, 0.15, group);
scene.add(group);
return group;
}
const clouds = [
addCloud(-5.5, 7.1, -5.5, 1.0),
addCloud(2.7, 8.4, -7.0, 0.78),
addCloud(8.0, 6.8, -4.8, 0.65)
];
// Voxel sun.
const sunGroup = new THREE.Group();
sunGroup.position.set(-6.4, 8.1, -5.7);
scene.add(sunGroup);
const sunMaterial = standardMaterial(0xffd45e, {
emissive: 0xffa928,
emissiveIntensity: 1.7,
roughness: 0.55
});
addBox(1.15, 1.15, 1.15, sunMaterial, 0, 0, 0, sunGroup);
addBox(0.34, 0.34, 0.34, sunMaterial, 1.0, 0.2, 0, sunGroup);
addBox(0.34, 0.34, 0.34, sunMaterial, -1.0, 0.2, 0, sunGroup);
addBox(0.34, 0.34, 0.34, sunMaterial, 0, 1.0, 0, sunGroup);
addBox(0.34, 0.34, 0.34, sunMaterial, 0, -1.0, 0, sunGroup);
// Simple star field, visible mainly at night.
const starGeometry = new THREE.BoxGeometry(0.045, 0.045, 0.045);
const starMaterial = new THREE.MeshBasicMaterial({
color: 0xd9efff,
transparent: true,
opacity: 0
});
const stars = new THREE.InstancedMesh(starGeometry, starMaterial, 42);
let randomSeed = 8391;
function random() {
randomSeed = (randomSeed * 16807) % 2147483647;
return (randomSeed - 1) / 2147483646;
}
for (let i = 0; i < 42; i++) {
dummy.position.set(
(random() - 0.5) * 28,
5.5 + random() * 9,
-7 - random() * 10
);
dummy.rotation.set(random(), random(), random());
dummy.scale.setScalar(0.6 + random() * 1.2);
dummy.updateMatrix();
stars.setMatrixAt(i, dummy.matrix);
}
stars.instanceMatrix.needsUpdate = true;
scene.add(stars);
// Ground conduit segments.
addBox(0.12, 0.08, 2.35, materials.conduit, -2.2, 0.08, 1.15);
addBox(2.25, 0.08, 0.12, materials.conduit, -1.25, 0.08, 0.05);
addBox(0.12, 0.08, 2.2, materials.conduit, 2.15, 0.08, 0.85);
addBox(2.3, 0.08, 0.12, materials.conduit, 2.8, 0.08, 1.85);
// -------------------------------------------------------------------------
// Animated voxel energy packets
// -------------------------------------------------------------------------
function createEnergyRoute(points, color, count = 7) {
const route = {
points: points.map((p) => new THREE.Vector3(...p)),
lengths: [],
totalLength: 0,
meshes: [],
active: false,
speed: 0.2
};
for (let i = 0; i < route.points.length - 1; i++) {
const length = route.points[i].distanceTo(route.points[i + 1]);
route.lengths.push(length);
route.totalLength += length;
}
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 1.35,
roughness: 0.35,
transparent: true,
opacity: 0.95
});
for (let i = 0; i < count; i++) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(0.19, 0.19, 0.19),
material
);
mesh.castShadow = false;
mesh.visible = false;
scene.add(mesh);
route.meshes.push(mesh);
}
return route;
}
function sampleRoute(route, t) {
let distance = THREE.MathUtils.clamp(t, 0, 1) * route.totalLength;
for (let i = 0; i < route.lengths.length; i++) {
const length = route.lengths[i];
if (distance <= length || i === route.lengths.length - 1) {
const localT = length === 0 ? 0 : distance / length;
return route.points[i].clone().lerp(route.points[i + 1], localT);
}
distance -= length;
}
return route.points[0].clone();
}
const directRoute = createEnergyRoute(
[
[-5.0, 1.0, -2.45],
[-1.5, 0.8, -2.45],
[2.8, 0.8, -2.45],
[2.8, 1.35, 1.8],
[3.45, 1.35, 1.8]
],
0xffd166,
10
);
const chargeRoute = createEnergyRoute(
[
[-3.25, 0.62, 1.75],
[-2.2, 0.62, 1.75],
[-2.2, 0.62, 0.62],
[-1.12, 0.62, 0.62]
],
0x65e3a5,
7
);
const dischargeRoute = createEnergyRoute(
[
[1.12, 0.62, 0.62],
[2.05, 0.62, 0.62],
[2.05, 0.62, 1.75],
[3.42, 1.35, 1.75]
],
0x70bfff,
7
);
function animateRoute(route, active, elapsed, speed) {
route.active = active;
route.speed = speed;
route.meshes.forEach((mesh, index) => {
mesh.visible = active;
if (!active) return;
const t = (elapsed * speed + index / route.meshes.length) % 1;
mesh.position.copy(sampleRoute(route, t));
mesh.rotation.y = elapsed * 1.8;
mesh.rotation.x = elapsed * 1.3;
});
}
// -------------------------------------------------------------------------
// Energy simulation
// -------------------------------------------------------------------------
function simulateStep() {
const dt = MODEL.stepHours;
const solarKW = MODEL.pvPeakKW * state.daylight;
const directKW = Math.min(solarKW, MODEL.loadKW);
let chargeKW = 0;
let dischargeKW = 0;
if (solarKW > MODEL.loadKW) {
const roomKWh = Math.max(
0,
MODEL.batteryCapacityKWh - state.batteryKWh
);
chargeKW = Math.min(
solarKW - MODEL.loadKW,
MODEL.batteryChargeMaxKW,
roomKWh / dt
);
state.batteryKWh += chargeKW * dt;
} else {
const gapKW = MODEL.loadKW - solarKW;
dischargeKW = Math.min(
gapKW,
MODEL.batteryDischargeMaxKW,
state.batteryKWh / dt
);
state.batteryKWh = Math.max(
0,
state.batteryKWh - dischargeKW * dt
);
}
const servedKW = directKW + dischargeKW;
const unmetKW = Math.max(0, MODEL.loadKW - servedKW);
const curtailedKW = Math.max(
0,
solarKW - directKW - chargeKW
);
state.lastDirectKW = directKW;
state.lastChargeKW = chargeKW;
state.lastDischargeKW = dischargeKW;
state.lastUnmetKW = unmetKW;
state.solarEnteredKWh += solarKW * dt;
state.loadConsumedKWh += servedKW * dt;
state.unmetKWh += unmetKW * dt;
state.curtailedKWh += curtailedKW * dt;
state.simHours += dt;
state.history.push({
entered: state.solarEnteredKWh,
consumed: state.loadConsumedKWh,
stored: state.batteryKWh
});
if (state.history.length > 120) state.history.shift();
}
function resetScenario() {
state.daylight = 0.65;
state.batteryKWh = 3.2;
state.solarEnteredKWh = 0;
state.loadConsumedKWh = 0;
state.unmetKWh = 0;
state.curtailedKWh = 0;
state.lastDirectKW = 0;
state.lastChargeKW = 0;
state.lastDischargeKW = 0;
state.lastUnmetKW = 0;
state.simHours = 0;
state.running = true;
state.history = [];
daylightInput.value = "65";
$("runButton").textContent = "Pause";
}
// -------------------------------------------------------------------------
// UI updates
// -------------------------------------------------------------------------
function updateUI() {
const solarKW = MODEL.pvPeakKW * state.daylight;
const batteryPercent =
(state.batteryKWh / MODEL.batteryCapacityKWh) * 100;
const deliverableBatteryKW = Math.min(
MODEL.batteryDischargeMaxKW,
state.batteryKWh / MODEL.stepHours
);
const availableSupplyKW = solarKW + deliverableBatteryKW;
const instantShortfallKW = Math.max(
0,
MODEL.loadKW - availableSupplyKW
);
const gapKW = Math.max(0, MODEL.loadKW - solarKW);
const runtimeHours = gapKW > 0 ? state.batteryKWh / gapKW : Infinity;
const daylightPercent = Math.round(state.daylight * 100);
document.documentElement.style.setProperty(
"--fill",
`${daylightPercent}%`
);
$("daylightValue").textContent = `${daylightPercent}%`;
$("solarPower").textContent = `${solarKW.toFixed(2)} kW`;
$("solarEnergy").textContent =
`${state.solarEnteredKWh.toFixed(2)} kWh captured`;
$("batteryStored").textContent =
`${state.batteryKWh.toFixed(2)} kWh`;
$("batteryMeterFill").style.width =
`${Math.max(0, Math.min(100, batteryPercent))}%`;
let batteryFlowText = "idle";
if (state.lastChargeKW > 0.001) {
batteryFlowText = `charging +${state.lastChargeKW.toFixed(2)} kW`;
} else if (state.lastDischargeKW > 0.001) {
batteryFlowText = `discharging −${state.lastDischargeKW.toFixed(2)} kW`;
}
$("batteryFlow").textContent =
`${Math.round(batteryPercent)}% · ${batteryFlowText}`;
const servedKW = state.lastDirectKW + state.lastDischargeKW;
$("loadPower").textContent = `${servedKW.toFixed(2)} kW`;
$("loadEnergy").textContent =
`${state.loadConsumedKWh.toFixed(2)} kWh served`;
$("unmetEnergy").textContent = `${state.unmetKWh.toFixed(2)} kWh`;
$("deficitCard").classList.toggle(
"is-alert",
instantShortfallKW > 0.001 || state.unmetKWh > 0.001
);
if (instantShortfallKW > 0.001) {
$("unmetDetail").textContent =
`Supply gap ${instantShortfallKW.toFixed(2)} kW`;
} else {
$("unmetDetail").textContent = "All demand served";
}
const statusBox = $("statusBox");
statusBox.classList.remove("bridge", "deficit");
if (instantShortfallKW > 0.001) {
statusBox.classList.add("deficit");
$("statusTitle").textContent = "LOAD SHORTFALL";
$("statusDetail").textContent =
`Available ${availableSupplyKW.toFixed(2)} kW is below the ` +
`${MODEL.loadKW.toFixed(2)} kW demand.`;
} else if (solarKW >= MODEL.loadKW) {
$("statusTitle").textContent = "SOLAR COVERS LOAD";
$("statusDetail").textContent =
"Solar alone supplies the full demand.";
} else {
statusBox.classList.add("bridge");
$("statusTitle").textContent = "BATTERY BRIDGING";
$("statusDetail").textContent =
`Solar is ${solarKW.toFixed(2)} kW; battery covers the ` +
`${gapKW.toFixed(2)} kW gap for about ` +
`${Number.isFinite(runtimeHours) ? runtimeHours.toFixed(1) : "∞"} sim h.`;
}
$("simClock").textContent = `Sim ${state.simHours.toFixed(1)} h`;
$("tagSolarValue").textContent = `${solarKW.toFixed(2)} kW`;
$("tagBatteryValue").textContent =
`${state.batteryKWh.toFixed(2)} kWh`;
$("tagHouseValue").textContent =
`${servedKW.toFixed(2)} / ${MODEL.loadKW.toFixed(2)} kW`;
}
// -------------------------------------------------------------------------
// Canvas chart
// -------------------------------------------------------------------------
function drawChart() {
const width = chartCanvas.clientWidth;
const height = chartCanvas.clientHeight;
if (!width || !height) return;
const dpr = Math.min(window.devicePixelRatio || 1, 2);
const pixelWidth = Math.round(width * dpr);
const pixelHeight = Math.round(height * dpr);
if (
chartCanvas.width !== pixelWidth ||
chartCanvas.height !== pixelHeight
) {
chartCanvas.width = pixelWidth;
chartCanvas.height = pixelHeight;
}
const ctx = chartContext;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
const padding = { left: 28, right: 5, top: 8, bottom: 17 };
const plotWidth = width - padding.left - padding.right;
const plotHeight = height - padding.top - padding.bottom;
const history = state.history;
const maxValue = Math.max(
8,
...history.map((item) => Math.max(item.entered, item.consumed))
);
const yMax = Math.ceil(maxValue / 2) * 2;
ctx.font = "9px system-ui";
ctx.textBaseline = "middle";
for (let i = 0; i <= 4; i++) {
const y =
padding.top + plotHeight - (plotHeight * i) / 4;
const value = (yMax * i) / 4;
ctx.strokeStyle = "rgba(180, 225, 218, 0.09)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(padding.left, y);
ctx.lineTo(width - padding.right, y);
ctx.stroke();
ctx.fillStyle = "rgba(164, 187, 185, 0.55)";
ctx.textAlign = "right";
ctx.fillText(value.toFixed(0), padding.left - 5, y);
}
function drawLine(key, color) {
if (history.length === 0) return;
ctx.strokeStyle = color;
ctx.lineWidth = 1.8;
ctx.lineJoin = "round";
ctx.beginPath();
history.forEach((item, index) => {
const x =
padding.left +
(history.length === 1
? plotWidth / 2
: (index / (history.length - 1)) * plotWidth);
const y =
padding.top +
plotHeight -
(Math.min(item[key], yMax) / yMax) * plotHeight;
if (index === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
}
drawLine("entered", "#ffd166");
drawLine("consumed", "#70bfff");
drawLine("stored", "#65e3a5");
ctx.fillStyle = "rgba(164, 187, 185, 0.55)";
ctx.textAlign = "left";
ctx.fillText("older", padding.left, height - 6);
ctx.textAlign = "right";
ctx.fillText("now", width - padding.right, height - 6);
}
// -------------------------------------------------------------------------
// Input and direct camera controls
// -------------------------------------------------------------------------
daylightInput.addEventListener("input", (event) => {
state.daylight = Number(event.target.value) / 100;
});
document.querySelectorAll("[data-daylight]").forEach((button) => {
button.addEventListener("click", () => {
const value = Number(button.dataset.daylight);
daylightInput.value = String(value);
state.daylight = value / 100;
});
});
$("runButton").addEventListener("click", () => {
state.running = !state.running;
$("runButton").textContent = state.running ? "Pause" : "Resume";
});
$("resetButton").addEventListener("click", resetScenario);
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousPointerX;
const dy = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.48,
1.28
);
updateCamera();
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
10,
29
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", () => {
cameraState.radius = 18;
cameraState.theta = 0.73;
cameraState.phi = 1.01;
updateCamera();
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
drawChart();
});
// -------------------------------------------------------------------------
// Dynamic scene appearance
// -------------------------------------------------------------------------
const projected = new THREE.Vector3();
const labelAnchors = {
tagSolar: new THREE.Vector3(-5.15, 3.55, 0),
tagBattery: new THREE.Vector3(0, 3.55, 0),
tagHouse: new THREE.Vector3(5.0, 4.75, 0)
};
function updateSceneAppearance(elapsed) {
const daylight = state.daylight;
const skyColor = new THREE.Color().lerpColors(
nightSky,
daySky,
daylight
);
scene.background.copy(skyColor);
scene.fog.color.copy(skyColor);
hemisphere.intensity = 0.32 + daylight * 1.05;
ambient.intensity = 0.16 + daylight * 0.22;
sunLight.intensity = 0.08 + daylight * 2.25;
panelMaterial.emissiveIntensity = 0.12 + daylight * 0.85;
panelGridMaterial.emissiveIntensity = 0.08 + daylight * 0.4;
sunMaterial.emissiveIntensity = 0.12 + daylight * 1.75;
sunMaterial.color.set(daylight < 0.15 ? 0x8d9aa4 : 0xffd45e);
sunGroup.position.y = 8.1 + Math.sin(elapsed * 0.55) * 0.15;
cloudMaterial.color.set(daylight < 0.2 ? 0x60717b : 0xe7f2ef);
cloudMaterial.opacity = 0.42 + daylight * 0.48;
clouds.forEach((cloud, index) => {
cloud.position.x += Math.sin(elapsed * 0.12 + index) * 0.0015;
});
starMaterial.opacity = Math.max(0, 0.9 - daylight * 2.2);
stars.visible = starMaterial.opacity > 0.01;
const deficit = state.lastUnmetKW > 0.001;
windowMaterial.color.set(deficit ? 0xff6675 : 0xffd680);
windowMaterial.emissive.set(deficit ? 0xff243f : 0xffaa38);
windowMaterial.emissiveIntensity = deficit ? 1.8 : 1.15;
const fraction = state.batteryKWh / MODEL.batteryCapacityKWh;
batterySegments.forEach((segment, index) => {
const segmentStart = index / batterySegments.length;
const segmentEnd = (index + 1) / batterySegments.length;
const fill = THREE.MathUtils.clamp(
(fraction - segmentStart) / (segmentEnd - segmentStart),
0,
1
);
segment.scale.x = Math.max(0.025, fill);
segment.material.color.set(
fill > 0.65 ? 0x65e3a5 : fill > 0 ? 0xffd166 : 0x344744
);
segment.material.emissive.set(
fill > 0.65 ? 0x23885d : fill > 0 ? 0x8a6418 : 0x101918
);
segment.material.emissiveIntensity = fill > 0 ? 0.7 : 0.05;
});
animateRoute(
directRoute,
state.lastDirectKW > 0.001,
elapsed,
0.16 + state.lastDirectKW * 0.015
);
animateRoute(
chargeRoute,
state.lastChargeKW > 0.001,
elapsed,
0.2 + state.lastChargeKW * 0.025
);
animateRoute(
dischargeRoute,
state.lastDischargeKW > 0.001,
elapsed,
0.24 + state.lastDischargeKW * 0.035
);
}
function updateLabels() {
for (const [id, anchor] of Object.entries(labelAnchors)) {
projected.copy(anchor).project(camera);
const element = $(id);
const visible =
projected.z > -1 &&
projected.z < 1 &&
projected.x > -1.1 &&
projected.x < 1.1 &&
projected.y > -1.1 &&
projected.y < 1.1;
element.style.opacity = visible ? "1" : "0";
if (!visible) continue;
element.style.left =
`${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top =
`${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
}
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
let previousTime = performance.now();
let accumulator = 0;
let previousUIUpdate = 0;
let previousChartUpdate = 0;
function animate(now) {
const realDelta = Math.min(0.1, (now - previousTime) / 1000);
previousTime = now;
const elapsed = now / 1000;
if (state.running) {
accumulator +=
realDelta * MODEL.simulatedHoursPerRealSecond;
let safety = 0;
while (
accumulator >= MODEL.stepHours &&
safety < 8
) {
simulateStep();
accumulator -= MODEL.stepHours;
safety++;
}
}
updateSceneAppearance(elapsed);
updateLabels();
if (now - previousUIUpdate > 90) {
updateUI();
previousUIUpdate = now;
}
if (now - previousChartUpdate > 250) {
drawChart();
previousChartUpdate = now;
}
renderer.render(scene, camera);
}
updateUI();
drawChart();
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```