Prompt specification
Build or customize the Three.js 3D scene "Charge Discharge and Efficiency Cycle" 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: Charge Discharge and Efficiency Cycle
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/charge-discharge-and-efficiency-cycle-x3934
Scene Description Prompt:
Charge discharge and efficiency cycle. Animate a toy storage cycle with explicit efficiency and capacity rules. Track input, stored, output, and lost energy separately and prevent overcharging beyond the modeled limit. Please build this with Three.js from cdnjs in one self-contained HTML file, using visible voxel blocks.
Working Three.js Starter (charge-discharge-and-efficiency-cycle-x3934):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Energy Storage Cycle</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(8, 19, 34, 0.86);
--border: rgba(143, 196, 255, 0.18);
--text: #edf7ff;
--muted: #8fa8c0;
--cyan: #35d8ff;
--lime: #8bff3c;
--amber: #ffc857;
--red: #ff5474;
}
* {
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;
}
#scene {
position: fixed;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
#hud {
position: fixed;
inset: 0;
pointer-events: none;
}
.glass {
pointer-events: auto;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 16px;
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(14px);
}
#title {
position: absolute;
top: 16px;
left: 16px;
width: 360px;
padding: 18px;
}
.kicker {
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 13px;
font-size: 25px;
line-height: 1.12;
letter-spacing: -0.035em;
}
.status-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
#phaseBadge {
display: inline-flex;
align-items: center;
min-height: 27px;
padding: 5px 10px;
border: 1px solid rgba(53, 216, 255, 0.34);
border-radius: 999px;
background: rgba(53, 216, 255, 0.1);
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
#phaseBadge[data-phase="charge"] {
color: var(--lime);
border-color: rgba(139, 255, 60, 0.35);
background: rgba(139, 255, 60, 0.09);
}
#phaseBadge[data-phase="discharge"] {
color: var(--amber);
border-color: rgba(255, 200, 87, 0.35);
background: rgba(255, 200, 87, 0.09);
}
#phaseBadge[data-phase="loss"] {
color: var(--red);
border-color: rgba(255, 84, 116, 0.35);
background: rgba(255, 84, 116, 0.09);
}
#cycleCount {
color: var(--muted);
font-size: 12px;
white-space: nowrap;
}
#phaseDetail {
min-height: 38px;
margin: 11px 0 7px;
color: #c6d8e9;
font-size: 13px;
line-height: 1.45;
}
#lastTransfer {
min-height: 18px;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 7px 12px;
margin-top: 13px;
padding-top: 12px;
border-top: 1px solid var(--border);
color: var(--muted);
font-size: 11px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.dot {
width: 8px;
height: 8px;
border-radius: 2px;
box-shadow: 0 0 9px currentColor;
}
.dot.input { color: var(--lime); background: var(--lime); }
.dot.stored { color: var(--cyan); background: var(--cyan); }
.dot.output { color: var(--amber); background: var(--amber); }
.dot.loss { color: var(--red); background: var(--red); }
#stats {
position: absolute;
top: 16px;
right: 16px;
width: 390px;
padding: 15px;
}
.metrics {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 9px;
}
.metric {
min-height: 80px;
padding: 11px 12px;
border: 1px solid rgba(143, 196, 255, 0.12);
border-radius: 11px;
background: rgba(255, 255, 255, 0.025);
}
.metric > span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
}
.metric strong {
display: block;
font-size: 21px;
letter-spacing: -0.025em;
}
.metric small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.metric.input strong { color: var(--lime); }
.metric.stored strong { color: var(--cyan); }
.metric.output strong { color: var(--amber); }
.metric.loss strong { color: var(--red); }
.capacity-head {
display: flex;
justify-content: space-between;
margin: 14px 0 6px;
color: var(--muted);
font-size: 10px;
}
.capacity-track {
height: 8px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.08);
}
#capacityFill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #168dff, var(--cyan));
box-shadow: 0 0 15px rgba(53, 216, 255, 0.7);
transition: width 120ms linear;
}
.balance {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 12px;
padding-top: 11px;
border-top: 1px solid var(--border);
color: var(--muted);
font-size: 10px;
}
#balanceLine {
color: #d5e6f5;
font-variant-numeric: tabular-nums;
}
#balanceStatus {
flex: 0 0 auto;
color: var(--lime);
font-weight: 800;
letter-spacing: 0.07em;
}
#blockedLine {
margin-top: 8px;
color: var(--muted);
font-size: 10px;
}
#rules {
position: absolute;
left: 16px;
bottom: 16px;
width: 390px;
padding: 16px;
}
.panel-title {
margin-bottom: 11px;
color: #dcecff;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.rule {
display: grid;
grid-template-columns: 94px 1fr;
gap: 9px;
padding: 7px 0;
border-top: 1px solid rgba(143, 196, 255, 0.1);
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.rule:first-of-type {
border-top: 0;
}
.rule b {
color: #e3f1ff;
}
.formula {
margin-top: 10px;
padding: 10px;
border-radius: 9px;
background: rgba(53, 216, 255, 0.07);
color: #b8d8ec;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.55;
}
#controls {
position: absolute;
right: 16px;
bottom: 16px;
width: 430px;
padding: 14px;
}
.buttons {
display: flex;
gap: 8px;
}
button {
min-height: 39px;
flex: 1;
padding: 9px 12px;
border: 1px solid rgba(143, 196, 255, 0.2);
border-radius: 10px;
background: rgba(255, 255, 255, 0.055);
color: var(--text);
font: inherit;
font-size: 12px;
font-weight: 750;
cursor: pointer;
transition:
transform 120ms ease,
border-color 120ms ease,
background 120ms ease;
}
button:hover {
border-color: rgba(53, 216, 255, 0.55);
background: rgba(53, 216, 255, 0.1);
transform: translateY(-1px);
}
button:active {
transform: translateY(0);
}
#playBtn {
border-color: rgba(53, 216, 255, 0.35);
background: rgba(53, 216, 255, 0.13);
color: var(--cyan);
}
.speed-row {
display: flex;
align-items: center;
gap: 12px;
margin-top: 12px;
color: var(--muted);
font-size: 11px;
}
.speed-row input {
width: 100%;
accent-color: var(--cyan);
}
#speedValue {
flex: 0 0 40px;
color: var(--text);
font-variant-numeric: tabular-nums;
text-align: right;
}
.camera-help {
margin-top: 9px;
color: #69829a;
font-size: 10px;
text-align: center;
}
#toast {
position: absolute;
top: 22px;
left: 50%;
max-width: min(440px, calc(100vw - 32px));
padding: 11px 15px;
border: 1px solid rgba(255, 200, 87, 0.35);
border-radius: 11px;
background: rgba(45, 29, 9, 0.94);
color: #ffe1a6;
font-size: 12px;
font-weight: 700;
opacity: 0;
transform: translate(-50%, -10px);
transition:
opacity 180ms ease,
transform 180ms ease;
pointer-events: none;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 820px) {
#title {
top: 8px;
left: 8px;
width: calc(100% - 16px);
padding: 13px;
}
h1 {
margin-bottom: 9px;
font-size: 20px;
}
#phaseDetail {
min-height: 0;
margin: 7px 0;
}
.legend {
display: none;
}
#stats {
top: 178px;
right: 8px;
width: calc(100% - 16px);
padding: 10px;
}
.metric {
min-height: 66px;
padding: 8px;
}
.metric strong {
font-size: 17px;
}
#rules {
left: 8px;
bottom: 86px;
width: calc(100% - 16px);
max-height: 190px;
padding: 12px;
overflow: auto;
}
#controls {
right: 8px;
bottom: 8px;
width: calc(100% - 16px);
padding: 10px;
}
.camera-help {
display: none;
}
#toast {
top: 172px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Animated voxel battery energy cycle"></canvas>
<div id="hud">
<section id="title" class="glass">
<div class="kicker">Three.js Voxel Lab</div>
<h1>Energy Storage Cycle</h1>
<div class="status-row">
<span id="phaseBadge" data-phase="charge">Charging</span>
<span id="cycleCount">0 cycles complete</span>
</div>
<p id="phaseDetail"></p>
<div id="lastTransfer"></div>
<div class="legend" aria-label="Color legend">
<span><i class="dot input"></i>Accepted input</span>
<span><i class="dot stored"></i>Stored energy</span>
<span><i class="dot output"></i>Useful output</span>
<span><i class="dot loss"></i>Energy loss</span>
</div>
</section>
<section id="stats" class="glass">
<div class="metrics">
<div class="metric input">
<span>INPUT</span>
<strong id="inputValue">0.00 Wh</strong>
<small>Cumulative accepted input</small>
</div>
<div class="metric stored">
<span>STORED</span>
<strong id="storedValue">0.00 / 100 Wh</strong>
<small id="blockSummary">0 full voxel blocks</small>
</div>
<div class="metric output">
<span>OUTPUT</span>
<strong id="outputValue">0.00 Wh</strong>
<small>Cumulative useful output</small>
</div>
<div class="metric loss">
<span>LOST</span>
<strong id="lostValue">0.00 Wh</strong>
<small>Cumulative charging + discharge loss</small>
</div>
</div>
<div class="capacity-head">
<span>HARD STORAGE CAPACITY</span>
<span id="capacityText">0%</span>
</div>
<div class="capacity-track">
<div id="capacityFill"></div>
</div>
<div class="balance">
<span id="balanceLine"></span>
<span id="balanceStatus">BALANCED</span>
</div>
<div id="blockedLine"></div>
</section>
<section id="rules" class="glass">
<div class="panel-title">Explicit model rules</div>
<div class="rule">
<b>Capacity</b>
<span>Stored energy may never exceed <strong>100 Wh</strong>.</span>
</div>
<div class="rule">
<b>Charge</b>
<span>Accepted input × <strong>0.90</strong> is stored; the other 10% is lost.</span>
</div>
<div class="rule">
<b>Discharge</b>
<span>Energy removed × <strong>0.92</strong> becomes output; the other 8% is lost.</span>
</div>
<div class="rule">
<b>Round trip</b>
<span>0.90 × 0.92 = <strong>82.8%</strong> ideal stored-to-useful efficiency.</span>
</div>
<div class="rule">
<b>Requests</b>
<span>Charge in 25 Wh requests; discharge in 30 Wh requests, limited by available storage.</span>
</div>
<div class="rule">
<b>Overcharge</b>
<span>A charge is clamped before acceptance. Rejected energy never enters the balance.</span>
</div>
<div class="formula">
Max accepted charge input = (Capacity − Stored) ÷ 0.90<br>
Conservation: Input = Stored + Output + Lost
</div>
</section>
<section id="controls" class="glass">
<div class="buttons">
<button id="playBtn" type="button">Pause</button>
<button id="oneBtn" type="button">Run one cycle</button>
<button id="resetBtn" type="button">Reset</button>
</div>
<div class="speed-row">
<label for="speed">Animation speed</label>
<input id="speed" type="range" min="0.5" max="2.5" step="0.1" value="1">
<span id="speedValue">1.0×</span>
</div>
<div class="camera-help">
Drag the scene to orbit · Mouse wheel to zoom · Double-click to reset the camera
</div>
</section>
<div id="toast" role="status" aria-live="polite"></div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Modeled energy rules
// -------------------------------------------------------------------------
const CONFIG = Object.freeze({
capacityWh: 100,
voxelEnergyWh: 5,
chargeEfficiency: 0.90,
dischargeEfficiency: 0.92,
chargeRequestWh: 25,
dischargeRequestWh: 30
});
const ROUND_TRIP_EFFICIENCY =
CONFIG.chargeEfficiency * CONFIG.dischargeEfficiency;
const state = {
playing: true,
phase: "idle",
phaseElapsed: 0,
// These four values obey:
// input === stored + output + lost
input: 0,
stored: 0,
output: 0,
lost: 0,
// Rejected input never entered the system, so it is not part of the
// conservation equation.
blocked: 0,
currentAmount: 0,
cycleCount: 0,
lastTransfer: "Waiting for the first transfer.",
singleCycle: false,
singleTarget: 0
};
let speed = 1;
let toastTimer = 0;
const $ = (id) => document.getElementById(id);
const fmt = (value) => value.toFixed(2);
const EPSILON = 1e-8;
// -------------------------------------------------------------------------
// Renderer, camera, lights
// -------------------------------------------------------------------------
const canvas = $("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 15, 29);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
80
);
const cameraTarget = new THREE.Vector3(0, 1.35, 0);
let cameraTheta = 0.18;
let cameraPhi = 1.12;
let cameraRadius = 15.5;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x +
cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z +
cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraTheta = 0.18;
cameraPhi = 1.12;
cameraRadius = 15.5;
updateCamera();
}
resetCamera();
scene.add(new THREE.HemisphereLight(0xb9dcff, 0x101826, 2.0));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(-5, 10, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -9;
keyLight.shadow.camera.right = 9;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -9;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x318dff, 1.8);
rimLight.position.set(7, 4, -7);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Shared geometry and material helpers
// -------------------------------------------------------------------------
const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
function makeMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: options.roughness ?? 0.42,
metalness: options.metalness ?? 0.16,
emissive: options.emissive ?? 0x000000,
emissiveIntensity: options.emissiveIntensity ?? 0,
transparent: options.transparent ?? false,
opacity: options.opacity ?? 1
});
}
function addBox(
parent,
sx,
sy,
sz,
x,
y,
z,
materialOrColor,
options = {}
) {
const material =
typeof materialOrColor === "number"
? makeMaterial(materialOrColor, options)
: materialOrColor;
const mesh = new THREE.Mesh(cubeGeometry, material);
mesh.scale.set(sx, sy, sz);
mesh.position.set(x, y, z);
mesh.castShadow = options.castShadow ?? true;
mesh.receiveShadow = options.receiveShadow ?? true;
parent.add(mesh);
return mesh;
}
function roundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function makeLabel(text, accent = "#35d8ff", width = 3.4) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const ctx = labelCanvas.getContext("2d");
roundedRect(ctx, 4, 4, 504, 120, 18);
ctx.fillStyle = "rgba(4, 12, 24, 0.9)";
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = accent;
ctx.stroke();
ctx.font = "800 42px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#eef8ff";
ctx.fillText(text, 256, 64);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
fog: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, width * 0.25, 1);
sprite.renderOrder = 20;
return sprite;
}
// -------------------------------------------------------------------------
// Ground and scene props
// -------------------------------------------------------------------------
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 20),
makeMaterial(0x0b1725, {
roughness: 0.9,
metalness: 0.05
})
);
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(28, 28, 0x21425f, 0x13283b);
grid.position.y = 0.012;
grid.material.transparent = true;
grid.material.opacity = 0.5;
scene.add(grid);
// Input/source station.
const sourceGroup = new THREE.Group();
sourceGroup.position.set(-5, 0, 0);
scene.add(sourceGroup);
addBox(
sourceGroup,
2.3, 0.25, 2.1,
0, 0.125, 0,
makeMaterial(0x17283a, {
metalness: 0.55,
roughness: 0.28
})
);
const sourceMaterial = makeMaterial(0x8bff3c, {
emissive: 0x4fc700,
emissiveIntensity: 0.35,
roughness: 0.3
});
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 3; col++) {
addBox(
sourceGroup,
0.4, 0.4, 0.4,
(col - 1) * 0.55,
0.55 + row * 0.47,
0,
sourceMaterial
);
}
}
const sourceLabel = makeLabel("INPUT / GRID", "#8bff3c", 3.1);
sourceLabel.position.set(0, 2.65, 0);
sourceGroup.add(sourceLabel);
const sourceLight = new THREE.PointLight(0x8bff3c, 1.2, 4.5);
sourceLight.position.set(0, 1.1, 1.1);
sourceGroup.add(sourceLight);
// Output/load station.
const outputGroup = new THREE.Group();
outputGroup.position.set(5, 0, 0);
scene.add(outputGroup);
addBox(
outputGroup,
2.3, 0.25, 2.1,
0, 0.125, 0,
makeMaterial(0x17283a, {
metalness: 0.55,
roughness: 0.28
})
);
const outputMaterial = makeMaterial(0xffc857, {
emissive: 0xa96500,
emissiveIntensity: 0.32,
roughness: 0.3
});
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 3; col++) {
addBox(
outputGroup,
0.4, 0.4, 0.4,
(col - 1) * 0.55,
0.55 + row * 0.47,
0,
outputMaterial
);
}
}
const outputLabel = makeLabel("USEFUL OUTPUT", "#ffc857", 3.5);
outputLabel.position.set(0, 2.65, 0);
outputGroup.add(outputLabel);
const outputLight = new THREE.PointLight(0xffc857, 1.0, 4.5);
outputLight.position.set(0, 1.1, 1.1);
outputGroup.add(outputLight);
// Loss/heat station.
const lossGroup = new THREE.Group();
lossGroup.position.set(3.15, 0, 2.45);
scene.add(lossGroup);
addBox(
lossGroup,
1.35, 0.25, 1.35,
0, 0.125, 0,
makeMaterial(0x261824, {
metalness: 0.45,
roughness: 0.35
})
);
const lossMaterial = makeMaterial(0xff5474, {
emissive: 0xa00025,
emissiveIntensity: 0.4,
roughness: 0.35
});
for (let i = 0; i < 3; i++) {
addBox(
lossGroup,
0.32, 0.32, 0.32,
(i - 1) * 0.37,
0.55,
0,
lossMaterial
);
}
const lossLabel = makeLabel("LOSS / HEAT", "#ff5474", 3.0);
lossLabel.position.set(0, 1.75, 0);
lossGroup.add(lossLabel);
const lossLight = new THREE.PointLight(0xff315d, 0.8, 4);
lossLight.position.set(0, 0.8, 0.7);
lossGroup.add(lossLight);
// Small splitter/load junction between the battery and output.
addBox(
scene,
0.85, 0.18, 0.85,
2.0, 0.09, -0.25,
makeMaterial(0x213247, {
metalness: 0.65,
roughness: 0.25
})
);
// -------------------------------------------------------------------------
// Battery rack and visible storage voxels
// -------------------------------------------------------------------------
const batteryGroup = new THREE.Group();
batteryGroup.position.y = 0.16;
scene.add(batteryGroup);
const frameMaterial = makeMaterial(0x294a68, {
metalness: 0.78,
roughness: 0.24,
emissive: 0x12344a,
emissiveIntensity: 0.22
});
for (const x of [-1.3, 1.3]) {
for (const z of [-0.57, 0.57]) {
addBox(batteryGroup, 0.07, 3.12, 0.07, x, 1.56, z, frameMaterial);
}
}
for (const y of [0.06, 3.06]) {
for (const z of [-0.57, 0.57]) {
addBox(batteryGroup, 2.66, 0.07, 0.07, 0, y, z, frameMaterial);
}
}
for (const y of [0.06, 3.06]) {
for (const x of [-1.3, 1.3]) {
addBox(batteryGroup, 0.07, 0.07, 1.14, x, y, 0, frameMaterial);
}
}
const batteryLabel = makeLabel("BATTERY / 100 Wh", "#35d8ff", 3.7);
batteryLabel.position.set(0, 3.62, 0);
batteryGroup.add(batteryLabel);
const batteryCapacityLabel = makeLabel(
`20 VOXEL SLOTS × ${CONFIG.voxelEnergyWh} Wh`,
"#6fa8c8",
3.4
);
batteryCapacityLabel.position.set(0, 3.25, 0);
batteryCapacityLabel.scale.multiplyScalar(0.86);
batteryGroup.add(batteryCapacityLabel);
const storageSlots = [];
const wireGeometry = new THREE.EdgesGeometry(cubeGeometry);
const wireMaterial = new THREE.LineBasicMaterial({
color: 0x6aa8c8,
transparent: true,
opacity: 0.22
});
// Four columns, five rows. Filling starts at the bottom-left.
for (let row = 0; row < 5; row++) {
for (let col = 0; col < 4; col++) {
const x = (col - 1.5) * 0.62;
const rowBase = row * 0.62;
const fullY = rowBase + 0.26;
const wire = new THREE.LineSegments(wireGeometry, wireMaterial);
wire.scale.set(0.54, 0.54, 0.54);
wire.position.set(x, fullY, 0);
batteryGroup.add(wire);
const material = makeMaterial(0x35d8ff, {
emissive: 0x087ea7,
emissiveIntensity: 0.65,
roughness: 0.27,
metalness: 0.2
});
const voxel = new THREE.Mesh(cubeGeometry, material);
voxel.scale.set(0.52, 0.52, 0.52);
voxel.position.set(x, fullY, 0);
voxel.castShadow = true;
voxel.receiveShadow = true;
voxel.visible = false;
batteryGroup.add(voxel);
storageSlots.push({
voxel,
x,
rowBase,
row,
col
});
}
}
const batteryLight = new THREE.PointLight(0x35d8ff, 1.4, 5);
batteryLight.position.set(0, 1.8, 1.1);
batteryGroup.add(batteryLight);
function updateStoredVoxels() {
const units = state.stored / CONFIG.voxelEnergyWh;
const fullCount = Math.floor(units + EPSILON);
const fraction = Math.max(0, units - fullCount);
storageSlots.forEach((slot, index) => {
const isFull = index < fullCount;
const isPartial =
index === fullCount &&
fraction > EPSILON &&
fullCount < storageSlots.length;
slot.voxel.visible = isFull || isPartial;
if (isFull) {
slot.voxel.scale.set(0.52, 0.52, 0.52);
slot.voxel.position.y = slot.rowBase + 0.26;
slot.voxel.material.color.setHex(0x35d8ff);
slot.voxel.material.emissive.setHex(0x087ea7);
slot.voxel.material.emissiveIntensity = 0.65;
} else if (isPartial) {
const height = Math.max(0.12, 0.52 * fraction);
slot.voxel.scale.set(0.52, height, 0.52);
slot.voxel.position.y = slot.rowBase + height / 2;
slot.voxel.material.color.setHex(0xb5f6ff);
slot.voxel.material.emissive.setHex(0x20b9e7);
slot.voxel.material.emissiveIntensity = 1.0;
}
});
}
// -------------------------------------------------------------------------
// Moving voxel packets
// -------------------------------------------------------------------------
const packetMaterials = {
input: makeMaterial(0x8bff3c, {
emissive: 0x4ab900,
emissiveIntensity: 1.1,
roughness: 0.24
}),
stored: makeMaterial(0x35d8ff, {
emissive: 0x087ea7,
emissiveIntensity: 1.0,
roughness: 0.24
}),
output: makeMaterial(0xffc857, {
emissive: 0xa96500,
emissiveIntensity: 1.0,
roughness: 0.24
}),
loss: makeMaterial(0xff5474, {
emissive: 0xa00025,
emissiveIntensity: 1.0,
roughness: 0.28
})
};
const packets = [];
function spawnPacket(
kind,
amountWh,
start,
end,
duration,
onComplete,
arcHeight = 1.25
) {
const count = Math.max(1, Math.ceil(amountWh / CONFIG.voxelEnergyWh));
const group = new THREE.Group();
const columns = Math.min(3, count);
const rows = Math.ceil(count / columns);
for (let i = 0; i < count; i++) {
const col = i % columns;
const row = Math.floor(i / columns);
const voxel = new THREE.Mesh(cubeGeometry, packetMaterials[kind]);
voxel.scale.setScalar(0.34);
voxel.position.set(
(col - (columns - 1) / 2) * 0.38,
(row - (rows - 1) / 2) * 0.38,
(i % 2) * 0.04
);
voxel.castShadow = true;
group.add(voxel);
}
group.position.copy(start);
scene.add(group);
const direction = end.clone().sub(start);
const control1 = start
.clone()
.add(
new THREE.Vector3(
direction.x * 0.32,
arcHeight,
direction.z * 0.12
)
);
const control2 = end
.clone()
.add(
new THREE.Vector3(
-direction.x * 0.24,
arcHeight * 0.72,
-direction.z * 0.12
)
);
packets.push({
group,
start: start.clone(),
control1,
control2,
end: end.clone(),
duration,
elapsed: 0,
onComplete
});
}
function cubicBezier(p0, p1, p2, p3, t) {
const u = 1 - t;
const a = u * u * u;
const b = 3 * u * u * t;
const c = 3 * u * t * t;
const d = t * t * t;
return new THREE.Vector3(
a * p0.x + b * p1.x + c * p2.x + d * p3.x,
a * p0.y + b * p1.y + c * p2.y + d * p3.y,
a * p0.z + b * p1.z + c * p2.z + d * p3.z
);
}
function updatePackets(delta) {
for (let i = packets.length - 1; i >= 0; i--) {
const packet = packets[i];
packet.elapsed += delta;
const t = Math.min(1, packet.elapsed / packet.duration);
const eased = t * t * (3 - 2 * t);
packet.group.position.copy(
cubicBezier(
packet.start,
packet.control1,
packet.control2,
packet.end,
eased
)
);
packet.group.rotation.y = eased * Math.PI * 1.5;
packet.group.rotation.z = Math.sin(eased * Math.PI) * 0.08;
if (t >= 1) {
scene.remove(packet.group);
packets.splice(i, 1);
packet.onComplete?.();
}
}
}
function clearPackets() {
for (const packet of packets) {
scene.remove(packet.group);
}
packets.length = 0;
}
// -------------------------------------------------------------------------
// State machine and energy accounting
// -------------------------------------------------------------------------
const sourcePacketStart = new THREE.Vector3(-4.15, 1.4, 0);
const batteryPacketEnd = new THREE.Vector3(-1.22, 1.38, 0);
const batteryDrawStart = new THREE.Vector3(1.18, 1.38, 0);
const splitPoint = new THREE.Vector3(2.0, 1.38, -0.25);
const outputPacketEnd = new THREE.Vector3(4.18, 1.4, 0);
const lossPacketEnd = new THREE.Vector3(3.15, 0.82, 2.42);
const batteryLossStart = new THREE.Vector3(0.35, 1.25, -0.3);
function showToast(message) {
$("toast").textContent = message;
$("toast").classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
$("toast").classList.remove("visible");
}, 3400);
}
function beginCharge() {
if (state.stored >= CONFIG.capacityWh - EPSILON) {
beginDischarge();
return;
}
const desiredInput = CONFIG.chargeRequestWh;
// Hard capacity rule:
// stored + acceptedInput × chargeEfficiency <= capacity
const maxAcceptedInput =
(CONFIG.capacityWh - state.stored) / CONFIG.chargeEfficiency;
const acceptedInput = Math.min(
desiredInput,
Math.max(0, maxAcceptedInput)
);
const rejectedInput = Math.max(
0,
desiredInput - acceptedInput
);
state.blocked += rejectedInput;
state.currentAmount = acceptedInput;
state.phase = "chargeInput";
state.phaseElapsed = 0;
if (rejectedInput > EPSILON) {
showToast(
`Overcharge prevented: ${fmt(rejectedInput)} Wh was rejected before entering the battery.`
);
}
spawnPacket(
"input",
acceptedInput,
sourcePacketStart,
batteryPacketEnd,
acceptedInput > 20 ? 1.55 : 1.25,
completeChargeInput,
1.45
);
}
function completeChargeInput() {
const acceptedInput = state.currentAmount;
const storedGain =
acceptedInput * CONFIG.chargeEfficiency;
const chargeLoss = acceptedInput - storedGain;
state.input += acceptedInput;
state.stored = Math.min(
CONFIG.capacityWh,
state.stored + storedGain
);
state.lost += chargeLoss;
state.lastTransfer =
`Last charge: ${fmt(acceptedInput)} Wh in → ` +
`${fmt(storedGain)} Wh stored + ${fmt(chargeLoss)} Wh lost.`;
updateStoredVoxels();
state.phase = "chargeLoss";
state.phaseElapsed = 0;
spawnPacket(
"loss",
chargeLoss,
batteryLossStart,
lossPacketEnd,
1.05,
() => {
state.phase = "chargeHold";
state.phaseElapsed = 0;
},
1.0
);
}
function beginDischarge() {
const removed =
Math.min(CONFIG.dischargeRequestWh, state.stored);
if (removed <= EPSILON) {
beginCharge();
return;
}
state.currentAmount = removed;
state.phase = "dischargeDraw";
state.phaseElapsed = 0;
spawnPacket(
"stored",
removed,
batteryDrawStart,
splitPoint,
1.45,
completeDischargeDraw,
1.15
);
}
function completeDischargeDraw() {
const removed = state.currentAmount;
const usefulOutput =
removed * CONFIG.dischargeEfficiency;
const dischargeLoss = removed - usefulOutput;
state.stored = Math.max(0, state.stored - removed);
state.output += usefulOutput;
state.lost += dischargeLoss;
state.lastTransfer =
`Last discharge: ${fmt(removed)} Wh removed → ` +
`${fmt(usefulOutput)} Wh output + ${fmt(dischargeLoss)} Wh lost.`;
updateStoredVoxels();
state.phase = "dischargeSplit";
state.phaseElapsed = 0;
let pending = 2;
const splitFinished = () => {
pending--;
if (pending === 0) {
state.phase = "dischargeHold";
state.phaseElapsed = 0;
}
};
spawnPacket(
"output",
usefulOutput,
splitPoint.clone().add(new THREE.Vector3(0, 0, 0.12)),
outputPacketEnd,
1.5,
splitFinished,
1.05
);
spawnPacket(
"loss",
dischargeLoss,
splitPoint.clone().add(new THREE.Vector3(0, -0.12, -0.12)),
lossPacketEnd,
1.15,
splitFinished,
0.85
);
}
function tickSimulation(delta) {
state.phaseElapsed += delta;
updatePackets(delta);
if (
state.phase === "chargeHold" &&
state.phaseElapsed >= 0.38
) {
beginCharge();
} else if (
state.phase === "dischargeHold" &&
state.phaseElapsed >= 0.48
) {
state.cycleCount++;
if (
state.singleCycle &&
state.cycleCount >= state.singleTarget
) {
state.singleCycle = false;
state.playing = false;
state.phase = "complete";
state.phaseElapsed = 0;
} else {
beginCharge();
}
}
}
function resetSimulation(startPlaying = true) {
clearPackets();
Object.assign(state, {
playing: startPlaying,
phase: "idle",
phaseElapsed: 0,
input: 0,
stored: 0,
output: 0,
lost: 0,
blocked: 0,
currentAmount: 0,
cycleCount: 0,
lastTransfer: "Waiting for the first transfer.",
singleCycle: false,
singleTarget: 0
});
clearTimeout(toastTimer);
$("toast").classList.remove("visible");
updateStoredVoxels();
if (startPlaying) {
beginCharge();
} else {
state.phase = "ready";
}
}
// -------------------------------------------------------------------------
// UI
// -------------------------------------------------------------------------
function phaseInfo() {
const amount = state.currentAmount;
switch (state.phase) {
case "chargeInput": {
const gain = amount * CONFIG.chargeEfficiency;
const loss = amount - gain;
return {
title: "Charging",
type: "charge",
detail:
`${fmt(amount)} Wh accepted → ` +
`${fmt(gain)} Wh will store and ${fmt(loss)} Wh will be lost.`
};
}
case "chargeLoss":
return {
title: "Charge Loss",
type: "loss",
detail:
"Charging inefficiency is moving to the red loss/heat voxels."
};
case "chargeHold":
return {
title: "Storage Check",
type: "charge",
detail:
`Storage is ${fmt(state.stored)} Wh. ` +
(state.stored >= CONFIG.capacityWh - EPSILON
? "The hard capacity limit is reached."
: "Another clamped charge request will begin.")
};
case "dischargeDraw":
return {
title: "Discharging",
type: "discharge",
detail:
`Removing ${fmt(amount)} Wh from the battery ` +
`and sending it toward the output junction.`
};
case "dischargeSplit":
return {
title: "Output Split",
type: "discharge",
detail:
"Discharge energy splits into useful output and " +
"discharge loss."
};
case "dischargeHold":
return {
title: "Cycle Complete",
type: "discharge",
detail:
"The cycle counter advances and the next charge begins."
};
case "complete":
return {
title: "Cycle Complete",
type: "stored",
detail:
"One requested cycle is complete. Press Play to continue."
};
default:
return {
title: "Ready",
type: "stored",
detail: "Press Play or Run one cycle to begin."
};
}
}
function updateUI() {
const info = phaseInfo();
$("phaseBadge").textContent = info.title;
$("phaseBadge").dataset.phase = info.type;
$("phaseDetail").textContent = info.detail;
$("lastTransfer").textContent = state.lastTransfer;
$("cycleCount").textContent =
`${state.cycleCount} cycle${state.cycleCount === 1 ? "" : "s"} complete`;
$("inputValue").textContent = `${fmt(state.input)} Wh`;
$("storedValue").textContent =
`${fmt(state.stored)} / ${CONFIG.capacityWh} Wh`;
$("outputValue").textContent = `${fmt(state.output)} Wh`;
$("lostValue").textContent = `${fmt(state.lost)} Wh`;
const capacityPercent =
(state.stored / CONFIG.capacityWh) * 100;
$("capacityFill").style.width =
`${Math.max(0, Math.min(100, capacityPercent))}%`;
$("capacityText").textContent =
`${Math.round(capacityPercent)}%`;
const units = state.stored / CONFIG.voxelEnergyWh;
const fullBlocks = Math.floor(units + EPSILON);
const partial = units - fullBlocks;
$("blockSummary").textContent =
partial > 0.01
? `${fullBlocks} full + ${Math.round(partial * 100)}% voxel`
: `${fullBlocks} full voxel blocks`;
const balance =
state.input - (state.stored + state.output + state.lost);
$("balanceLine").textContent =
`Input ${fmt(state.input)} = ` +
`Stored ${fmt(state.stored)} + ` +
`Output ${fmt(state.output)} + Lost ${fmt(state.lost)}`;
$("balanceStatus").textContent =
Math.abs(balance) < 0.00001 ? "BALANCED" : "CHECK";
$("balanceStatus").style.color =
Math.abs(balance) < 0.00001 ? "#8bff3c" : "#ff5474";
$("blockedLine").textContent =
`${fmt(state.blocked)} Wh rejected before acceptance · ` +
`Round-trip efficiency ${(ROUND_TRIP_EFFICIENCY * 100).toFixed(1)}%`;
$("playBtn").textContent = state.playing ? "Pause" : "Play";
$("speedValue").textContent = `${speed.toFixed(1)}×`;
}
function updateSceneMood(time) {
const charging =
state.phase === "chargeInput" ||
state.phase === "chargeLoss" ||
state.phase === "chargeHold";
const discharging =
state.phase === "dischargeDraw" ||
state.phase === "dischargeSplit" ||
state.phase === "dischargeHold";
const pulse = 0.5 + 0.5 * Math.sin(time * 0.006);
sourceMaterial.emissiveIntensity =
charging ? 0.9 + pulse * 0.65 : 0.3;
sourceLight.intensity = charging ? 1.4 + pulse : 0.65;
outputMaterial.emissiveIntensity =
discharging ? 0.9 + pulse * 0.65 : 0.28;
outputLight.intensity = discharging ? 1.5 + pulse : 0.55;
lossMaterial.emissiveIntensity =
state.phase === "chargeLoss" || state.phase === "dischargeSplit"
? 1.1 + pulse * 0.6
: 0.35;
lossLight.intensity =
state.phase === "chargeLoss" || state.phase === "dischargeSplit"
? 1.5 + pulse
: 0.55;
const fullness = state.stored / CONFIG.capacityWh;
frameMaterial.emissiveIntensity = 0.15 + fullness * 0.42;
batteryLight.intensity = 0.7 + fullness * 1.3 + pulse * 0.15;
}
// -------------------------------------------------------------------------
// Controls
// -------------------------------------------------------------------------
$("playBtn").addEventListener("click", () => {
if (state.phase === "complete") {
resetSimulation(true);
} else {
state.playing = !state.playing;
}
});
$("oneBtn").addEventListener("click", () => {
if (state.phase === "complete") {
resetSimulation(true);
state.singleCycle = true;
state.singleTarget = 1;
} else {
state.singleCycle = true;
state.singleTarget = state.cycleCount + 1;
state.playing = true;
}
});
$("resetBtn").addEventListener("click", () => {
resetSimulation(true);
});
$("speed").addEventListener("input", (event) => {
speed = Number(event.target.value);
});
// Direct camera controls; no examples/addons are imported.
let dragging = false;
let dragX = 0;
let dragY = 0;
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
dragX = event.clientX;
dragY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - dragX;
const dy = event.clientY - dragY;
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi + dy * 0.005,
0.45,
1.43
);
dragX = event.clientX;
dragY = event.clientY;
updateCamera();
});
function endDrag(event) {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius + event.deltaY * 0.012,
9,
24
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
if (event.code === "Space") {
event.preventDefault();
$("playBtn").click();
}
if (event.code === "KeyR") {
resetSimulation(true);
}
});
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
resetSimulation(true);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const realDelta = Math.min(clock.getDelta(), 0.05);
if (state.playing) {
tickSimulation(realDelta * speed);
}
updateSceneMood(performance.now());
updateUI();
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```