Prompt specification
Build or customize the Three.js 3D scene "Resistor power and energy counters" 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: Resistor power and energy counters
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/resistor-power-and-energy-counters-x1629
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows a low-poly electrical resistor on a small demonstration board. Four labeled meters sit beside the resistor terminals and battery symbol. Use a fixed resistance and an adjustable supply voltage; compute current from Ohm's law and power from voltage times current. A joule counter accumulates power over elapsed simulation time, while the watt indicator responds immediately to the voltage setting. Include pause and reset controls so stopping the clock freezes accumulated energy without confusing it with instantaneous power.
Working Three.js Starter (resistor-power-and-energy-counters-x1629):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Low-Poly Resistor Energy Lab</title>
<style>
:root {
color-scheme: dark;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 28% 20%, #173045 0, #09131d 42%, #05080d 100%);
color: #e8f5ff;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.title-card {
position: fixed;
z-index: 5;
top: 22px;
left: 24px;
width: min(390px, calc(100vw - 48px));
padding: 17px 19px;
border: 1px solid rgba(159, 217, 255, 0.18);
border-radius: 16px;
background: rgba(8, 16, 25, 0.78);
box-shadow: 0 16px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(14px);
pointer-events: none;
}
.eyebrow {
margin-bottom: 7px;
color: #63d9ff;
font-size: 0.68rem;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(1.35rem, 2.2vw, 2rem);
line-height: 1.08;
letter-spacing: -0.035em;
}
.subtitle {
margin: 9px 0 0;
color: #a9bdcc;
font-size: 0.82rem;
line-height: 1.5;
}
.formula-row {
display: flex;
gap: 8px;
margin-top: 12px;
}
.formula {
padding: 6px 9px;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
background: rgba(255, 255, 255, 0.045);
color: #d9f4ff;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.74rem;
}
.hud {
position: fixed;
z-index: 10;
top: 22px;
right: 22px;
width: 350px;
max-height: calc(100vh - 44px);
overflow: auto;
padding: 18px;
border: 1px solid rgba(159, 217, 255, 0.2);
border-radius: 18px;
background: rgba(7, 14, 23, 0.88);
box-shadow: 0 22px 65px rgba(0, 0, 0, 0.42);
backdrop-filter: blur(16px);
scrollbar-width: thin;
scrollbar-color: #31516a transparent;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 17px;
}
.panel-heading strong {
font-size: 0.76rem;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.status {
display: inline-flex;
align-items: center;
gap: 7px;
color: #7cf7b5;
font-size: 0.68rem;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.status::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 12px currentColor;
content: "";
}
.status.paused {
color: #ffd166;
}
.control-label {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
color: #c3d4df;
font-size: 0.82rem;
}
.control-label output {
color: #7ee9ff;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 1rem;
font-weight: 800;
}
input[type="range"] {
width: 100%;
height: 6px;
margin: 0;
border-radius: 10px;
accent-color: #52d8ff;
cursor: pointer;
}
.range-scale {
display: flex;
justify-content: space-between;
margin-top: 7px;
color: #708797;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.66rem;
}
.fixed-resistance {
display: flex;
justify-content: space-between;
align-items: center;
margin: 15px 0;
padding: 10px 12px;
border: 1px solid rgba(255, 255, 255, 0.09);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
color: #9eb3c1;
font-size: 0.75rem;
}
.fixed-resistance strong {
color: #f4fbff;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.92rem;
}
.readouts {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
.readout {
min-width: 0;
padding: 11px;
border: 1px solid rgba(255, 255, 255, 0.09);
border-radius: 11px;
background: rgba(255, 255, 255, 0.035);
}
.readout.wide {
grid-column: 1 / -1;
}
.readout-label {
display: block;
margin-bottom: 5px;
overflow: hidden;
color: #8199a9;
font-size: 0.62rem;
font-weight: 800;
letter-spacing: 0.1em;
text-overflow: ellipsis;
text-transform: uppercase;
white-space: nowrap;
}
.readout-value {
display: block;
overflow: hidden;
color: #eefaff;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 1.1rem;
font-weight: 800;
text-overflow: ellipsis;
white-space: nowrap;
}
.readout.power {
border-color: rgba(255, 184, 77, 0.3);
background: rgba(255, 174, 51, 0.07);
}
.readout.power .readout-value {
color: #ffc466;
}
.readout.energy {
border-color: rgba(80, 225, 255, 0.3);
background: rgba(54, 204, 236, 0.07);
}
.readout.energy .readout-value {
color: #75e7ff;
}
.clock-row {
display: flex;
align-items: center;
justify-content: space-between;
margin: 11px 0 14px;
padding: 9px 11px;
border-radius: 9px;
background: rgba(0, 0, 0, 0.22);
color: #8199a9;
font-size: 0.7rem;
}
.clock-row strong {
color: #d8e8f2;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.84rem;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
button {
min-height: 43px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 10px;
background: rgba(255, 255, 255, 0.055);
color: #e9f7ff;
font: inherit;
font-size: 0.78rem;
font-weight: 800;
cursor: pointer;
transition:
background 150ms ease,
border-color 150ms ease,
transform 150ms ease;
}
button:hover {
border-color: rgba(126, 233, 255, 0.45);
background: rgba(82, 216, 255, 0.11);
}
button:active {
transform: translateY(1px);
}
#pauseButton {
border-color: rgba(82, 216, 255, 0.35);
background: rgba(82, 216, 255, 0.1);
}
#pauseButton.paused {
border-color: rgba(255, 209, 102, 0.45);
background: rgba(255, 209, 102, 0.1);
color: #ffe0a0;
}
.note {
margin: 12px 1px 0;
color: #7f96a5;
font-size: 0.68rem;
line-height: 1.5;
}
.controls-hint {
position: fixed;
z-index: 4;
bottom: 18px;
left: 24px;
padding: 8px 11px;
border: 1px solid rgba(255, 255, 255, 0.09);
border-radius: 9px;
background: rgba(5, 10, 16, 0.68);
color: #8da5b5;
font-size: 0.7rem;
pointer-events: none;
}
@media (max-width: 760px) {
.title-card {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 12px 14px;
}
.subtitle,
.formula-row {
display: none;
}
.hud {
top: auto;
right: 12px;
bottom: 12px;
width: calc(100vw - 24px);
max-height: 46vh;
padding: 14px;
}
.readouts {
grid-template-columns: repeat(3, 1fr);
}
.readout.wide {
grid-column: auto;
}
.controls-hint {
display: none;
}
}
</style>
</head>
<body>
<canvas
id="scene"
tabindex="0"
aria-label="Interactive 3D resistor demonstration board"
></canvas>
<header class="title-card">
<div class="eyebrow">Interactive Electronics Bench</div>
<h1>Resistor Energy Lab</h1>
<p class="subtitle">
A fixed 220 Ω resistor on a low-poly demonstration board.
Change the supply voltage and watch instantaneous power and accumulated
joules diverge.
</p>
<div class="formula-row">
<span class="formula">I = V / R</span>
<span class="formula">P = V × I</span>
</div>
</header>
<aside class="hud" aria-label="Circuit controls and measurements">
<div class="panel-heading">
<strong>Control Room</strong>
<span id="status" class="status">Running</span>
</div>
<label class="control-label" for="voltage">
<span>Adjustable supply voltage</span>
<output id="voltageOutput" for="voltage">12.0 V</output>
</label>
<input
id="voltage"
type="range"
min="0"
max="24"
step="0.1"
value="12"
aria-label="Supply voltage"
/>
<div class="range-scale">
<span>0 V</span>
<span>12 V</span>
<span>24 V</span>
</div>
<div class="fixed-resistance">
<span>Fixed resistance</span>
<strong>R = 220 Ω</strong>
</div>
<div class="readouts">
<div class="readout">
<span class="readout-label">Supply voltage</span>
<span id="voltageValue" class="readout-value">12.00 V</span>
</div>
<div class="readout">
<span class="readout-label">Current</span>
<span id="currentValue" class="readout-value">54.55 mA</span>
</div>
<div class="readout wide power">
<span class="readout-label">Instantaneous power</span>
<span id="powerValue" class="readout-value">0.655 W</span>
</div>
<div class="readout wide energy">
<span class="readout-label">Accumulated energy</span>
<span id="energyValue" class="readout-value">0.000 J</span>
</div>
<div class="readout wide">
<span class="readout-label">Active simulation clock</span>
<span id="clockValue" class="readout-value">00:00.0</span>
</div>
</div>
<div class="clock-row">
<span id="clockDescription">Integrating P × dt</span>
<strong id="pauseState">Clock running</strong>
</div>
<div class="buttons">
<button id="pauseButton" type="button">Ⅱ Pause clock</button>
<button
id="resetButton"
type="button"
title="Reset elapsed time and accumulated energy while retaining the selected voltage"
>
↺ Reset
</button>
</div>
<p class="note">
Pause freezes elapsed time and accumulated joules. Instantaneous watts
remain live when voltage changes. Reset clears the clock and energy,
retaining the selected supply voltage.
</p>
</aside>
<div class="controls-hint">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";
const canvas = document.querySelector("#scene");
const ui = {
voltage: document.querySelector("#voltage"),
voltageOutput: document.querySelector("#voltageOutput"),
voltageValue: document.querySelector("#voltageValue"),
currentValue: document.querySelector("#currentValue"),
powerValue: document.querySelector("#powerValue"),
energyValue: document.querySelector("#energyValue"),
clockValue: document.querySelector("#clockValue"),
status: document.querySelector("#status"),
pauseState: document.querySelector("#pauseState"),
clockDescription: document.querySelector("#clockDescription"),
pauseButton: document.querySelector("#pauseButton"),
resetButton: document.querySelector("#resetButton")
};
const state = {
voltage: 12,
resistance: 220,
current: 12 / 220,
power: 12 * (12 / 220),
paused: false,
elapsed: 0,
energy: 0
};
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true,
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.08;
const scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x071019, 0.026);
const camera = new THREE.PerspectiveCamera(
39,
window.innerWidth / window.innerHeight,
0.1,
100
);
const view = {
theta: 0.57,
phi: 0.84,
radius: window.innerWidth < 760 ? 21 : 18,
target: new THREE.Vector3(0.5, 0.25, window.innerWidth < 760 ? 0.9 : 0)
};
function updateCamera() {
const sinPhi = Math.sin(view.phi);
camera.position.set(
view.target.x + view.radius * sinPhi * Math.sin(view.theta),
view.target.y + view.radius * Math.cos(view.phi),
view.target.z + view.radius * sinPhi * Math.cos(view.theta)
);
camera.lookAt(view.target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xc8ecff, 0x17261f, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(-7, 12, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.00035;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4cc9ff, 1.6);
rimLight.position.set(8, 6, -8);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffb347, 16, 13, 2);
warmLight.position.set(4, 4, 1);
scene.add(warmLight);
const materials = {
board: new THREE.MeshStandardMaterial({
color: 0x123b3a,
roughness: 0.72,
metalness: 0.12
}),
boardEdge: new THREE.MeshStandardMaterial({
color: 0x082322,
roughness: 0.65
}),
copper: new THREE.MeshStandardMaterial({
color: 0xc9853c,
roughness: 0.3,
metalness: 0.78
}),
brightCopper: new THREE.MeshStandardMaterial({
color: 0xffb45b,
roughness: 0.22,
metalness: 0.72
}),
metal: new THREE.MeshStandardMaterial({
color: 0xcbd8df,
roughness: 0.24,
metalness: 0.9
}),
darkMetal: new THREE.MeshStandardMaterial({
color: 0x33424d,
roughness: 0.42,
metalness: 0.72
}),
resistor: new THREE.MeshStandardMaterial({
color: 0xd7b980,
roughness: 0.78,
metalness: 0.02,
flatShading: true
}),
meterCase: new THREE.MeshStandardMaterial({
color: 0x18232d,
roughness: 0.55,
metalness: 0.35
}),
batteryBase: new THREE.MeshStandardMaterial({
color: 0x1c4e72,
roughness: 0.48,
metalness: 0.3
})
};
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.lineTo(x + width - r, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + r);
ctx.lineTo(x + width, y + height - r);
ctx.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
ctx.lineTo(x + r, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function createRoundedBoardShape(width, height, radius) {
const shape = new THREE.Shape();
const x = -width / 2;
const y = -height / 2;
shape.moveTo(x + radius, y);
shape.lineTo(x + width - radius, y);
shape.quadraticCurveTo(x + width, y, x + width, y + radius);
shape.lineTo(x + width, y + height - radius);
shape.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
shape.lineTo(x + radius, y + height);
shape.quadraticCurveTo(x, y + height, x, y + height - radius);
shape.lineTo(x, y + radius);
shape.quadraticCurveTo(x, y, x + radius, y);
shape.closePath();
return shape;
}
const boardGeometry = new THREE.ExtrudeGeometry(
createRoundedBoardShape(14, 9, 0.55),
{
depth: 0.32,
bevelEnabled: true,
bevelThickness: 0.06,
bevelSize: 0.1,
bevelSegments: 1,
curveSegments: 8
}
);
boardGeometry.rotateX(-Math.PI / 2);
const board = new THREE.Mesh(boardGeometry, materials.board);
board.position.y = -0.03;
board.receiveShadow = true;
board.castShadow = true;
scene.add(board);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
new THREE.MeshStandardMaterial({
color: 0x070c12,
roughness: 0.96,
metalness: 0.03
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.16;
ground.receiveShadow = true;
scene.add(ground);
function cylinderBetween(a, b, radius, material, radialSegments = 8) {
const start = new THREE.Vector3(...a);
const end = new THREE.Vector3(...b);
const direction = end.clone().sub(start);
const length = direction.length();
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, length, radialSegments),
material
);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function addTrace(points, material = materials.copper) {
const curve = new THREE.CatmullRomCurve3(
points.map((point) => new THREE.Vector3(...point)),
false,
"catmullrom",
0.08
);
const trace = new THREE.Mesh(
new THREE.TubeGeometry(curve, 50, 0.037, 6, false),
material
);
trace.castShadow = true;
trace.receiveShadow = true;
scene.add(trace);
return trace;
}
function makeLabel(text, x, z, width, height, color = "#d9f5ff") {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 1024;
labelCanvas.height = 256;
const ctx = labelCanvas.getContext("2d");
ctx.clearRect(0, 0, labelCanvas.width, labelCanvas.height);
ctx.fillStyle = color;
ctx.font = "800 86px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 512, 132);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const label = new THREE.Mesh(
new THREE.PlaneGeometry(width, height),
new THREE.MeshBasicMaterial({
map: texture,
transparent: true,
depthWrite: false,
toneMapped: false
})
);
label.rotation.x = -Math.PI / 2;
label.position.set(x, 0.39, z);
scene.add(label);
return label;
}
// Decorative circuit traces.
addTrace([
[-3.55, 0.405, 0.4],
[-3.55, 0.405, 1.65],
[-2.7, 0.405, 1.9],
[2.55, 0.405, 1.9],
[3.55, 0.405, 1.45],
[3.55, 0.405, 0.4]
]);
addTrace([
[1.1, 0.405, 0.4],
[1.8, 0.405, 0.4],
[2.35, 0.405, 0.4],
[3.05, 0.405, 0.4]
]);
addTrace([
[-4.8, 0.405, -1.05],
[-3.9, 0.405, -1.05],
[-3.55, 0.405, -0.45],
[-3.55, 0.405, 0.4]
]);
// Resistor terminal pads.
for (const x of [-3.55, 1.1]) {
const pad = new THREE.Mesh(
new THREE.CylinderGeometry(0.23, 0.23, 0.09, 16),
materials.brightCopper
);
pad.position.set(x, 0.405, 0.4);
pad.castShadow = true;
pad.receiveShadow = true;
scene.add(pad);
}
// Low-poly resistor body, aligned along the X axis.
const resistorBody = new THREE.Mesh(
new THREE.CylinderGeometry(0.46, 0.46, 2.5, 12, 1, false),
materials.resistor
);
resistorBody.rotation.z = Math.PI / 2;
resistorBody.position.set(-1.4, 0.89, 0.4);
resistorBody.castShadow = true;
resistorBody.receiveShadow = true;
scene.add(resistorBody);
// 220 Ω color code: red, red, brown, gold.
const bandColors = [0xb52b25, 0xb52b25, 0x704321, 0xd8ad45];
const bandPositions = [-2.3, -1.78, -1.24, -0.58];
bandPositions.forEach((x, index) => {
const band = new THREE.Mesh(
new THREE.CylinderGeometry(0.472, 0.472, 0.22, 12),
new THREE.MeshStandardMaterial({
color: bandColors[index],
roughness: 0.56,
metalness: 0.06,
flatShading: true
})
);
band.rotation.z = Math.PI / 2;
band.position.set(x, 0.89, 0.4);
band.castShadow = true;
scene.add(band);
});
// Metal end collars and leads.
for (const x of [-2.69, -0.11]) {
const collar = new THREE.Mesh(
new THREE.CylinderGeometry(0.49, 0.49, 0.16, 12),
materials.metal
);
collar.rotation.z = Math.PI / 2;
collar.position.set(x, 0.89, 0.4);
collar.castShadow = true;
scene.add(collar);
}
scene.add(
cylinderBetween(
[-3.55, 0.84, 0.4],
[-2.69, 0.84, 0.4],
0.065,
materials.metal,
10
)
);
scene.add(
cylinderBetween(
[-0.11, 0.84, 0.4],
[1.1, 0.84, 0.4],
0.065,
materials.metal,
10
)
);
for (const x of [-3.55, 1.1]) {
scene.add(
cylinderBetween(
[x, 0.43, 0.4],
[x, 0.84, 0.4],
0.065,
materials.metal,
10
)
);
}
// Battery symbol: tall positive plate and shorter negative plate.
const batteryBase = new THREE.Mesh(
new THREE.BoxGeometry(2.2, 0.12, 2.0),
materials.batteryBase
);
batteryBase.position.set(3.3, 0.41, 0.4);
batteryBase.castShadow = true;
batteryBase.receiveShadow = true;
scene.add(batteryBase);
const positivePlate = new THREE.Mesh(
new THREE.BoxGeometry(0.15, 1.28, 1.42),
materials.metal
);
positivePlate.position.set(3.05, 0.47 + 1.28 / 2, 0.4);
positivePlate.castShadow = true;
scene.add(positivePlate);
const negativePlate = new THREE.Mesh(
new THREE.BoxGeometry(0.15, 0.78, 1.42),
materials.darkMetal
);
negativePlate.position.set(3.55, 0.47 + 0.78 / 2, 0.4);
negativePlate.castShadow = true;
scene.add(negativePlate);
makeLabel("+", 2.48, 1.45, 0.48, 0.48, "#8effb7");
makeLabel("−", 3.85, 1.45, 0.48, 0.48, "#ff9a9a");
makeLabel("ADJUSTABLE DC", 3.3, -0.7, 2.6, 0.5, "#9ddfef");
makeLabel("R = 220 Ω", -1.45, 1.48, 2.25, 0.48, "#f5d59e");
makeLabel("OHM'S LAW / ENERGY COUNTER", -1.55, -3.48, 5.6, 0.56, "#84eaff");
// Four physical, labeled meters distributed around the components.
const meters = [];
function drawMeter(meter) {
const ctx = meter.ctx;
const width = meter.canvas.width;
const height = meter.canvas.height;
ctx.clearRect(0, 0, width, height);
roundedRect(ctx, 0, 0, width, height, 22);
ctx.fillStyle = "#071018";
ctx.fill();
ctx.strokeStyle = meter.color;
ctx.lineWidth = 5;
ctx.stroke();
ctx.fillStyle = meter.color;
ctx.fillRect(0, 0, width, 14);
ctx.fillStyle = "#8ea8b9";
ctx.font = "800 30px ui-sans-serif, system-ui, sans-serif";
ctx.textAlign = "left";
ctx.textBaseline = "middle";
ctx.fillText(meter.label, 28, 53);
ctx.fillStyle = "#f1fbff";
ctx.font = "800 62px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.fillText(meter.value, 27, 119);
ctx.fillStyle = meter.color;
ctx.font = "700 22px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.textAlign = "right";
ctx.fillText(meter.unit, width - 27, 122);
roundedRect(ctx, 28, 174, width - 56, 20, 10);
ctx.fillStyle = "#172632";
ctx.fill();
const fillWidth = (width - 56) * Math.max(0, Math.min(1, meter.progress));
roundedRect(ctx, 28, 174, Math.max(1, fillWidth), 20, 10);
ctx.fillStyle = meter.color;
ctx.fill();
ctx.fillStyle = "#607d8e";
ctx.font = "700 15px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.textAlign = "left";
ctx.fillText(meter.footer, 28, 224);
ctx.textAlign = "right";
ctx.fillText("LIVE", width - 28, 224);
meter.texture.needsUpdate = true;
}
function createMeter({ label, x, z, color, unit, footer }) {
const group = new THREE.Group();
group.position.set(x, 0.48, z);
const body = new THREE.Mesh(
new THREE.BoxGeometry(2.7, 0.18, 1.48),
materials.meterCase
);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const meterCanvas = document.createElement("canvas");
meterCanvas.width = 512;
meterCanvas.height = 256;
const texture = new THREE.CanvasTexture(meterCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const screen = new THREE.Mesh(
new THREE.PlaneGeometry(2.49, 1.25),
new THREE.MeshBasicMaterial({
map: texture,
toneMapped: false
})
);
screen.rotation.x = -Math.PI / 2;
screen.position.y = 0.101;
group.add(screen);
const led = new THREE.Mesh(
new THREE.SphereGeometry(0.065, 8, 6),
new THREE.MeshBasicMaterial({ color })
);
led.position.set(-1.17, 0.125, 0.59);
group.add(led);
scene.add(group);
const meter = {
label,
unit,
footer,
color,
canvas: meterCanvas,
ctx: meterCanvas.getContext("2d"),
texture,
value: "0",
progress: 0
};
meters.push(meter);
drawMeter(meter);
return meter;
}
createMeter({
label: "VOLTAGE",
unit: "VOLTS",
footer: "SUPPLY",
color: "#62ddff",
x: 5.05,
z: -1.75
});
createMeter({
label: "CURRENT",
unit: "MILLIAMPS",
footer: "I = V / R",
color: "#79f2ae",
x: 0.45,
z: 2.55
});
createMeter({
label: "RESISTANCE",
unit: "OHMS",
footer: "FIXED VALUE",
color: "#d0a0ff",
x: -4.0,
z: 2.55
});
createMeter({
label: "POWER",
unit: "WATTS",
footer: "P = V × I",
color: "#ffc15c",
x: 5.05,
z: 2.35
});
// Corner mounting screws.
const screwPositions = [
[-6.35, -3.8],
[6.35, -3.8],
[-6.35, 3.8],
[6.35, 3.8]
];
for (const [x, z] of screwPositions) {
const screw = new THREE.Mesh(
new THREE.CylinderGeometry(0.14, 0.14, 0.09, 12),
materials.metal
);
screw.position.set(x, 0.41, z);
screw.castShadow = true;
scene.add(screw);
const slot = new THREE.Mesh(
new THREE.BoxGeometry(0.17, 0.015, 0.025),
materials.darkMetal
);
slot.position.set(x, 0.46, z);
slot.rotation.y = x * z > 0 ? 0.55 : -0.55;
scene.add(slot);
}
// Small decorative solder pads.
const padLocations = [
[-4.8, -1.05],
[-2.65, -1.05],
[-1.2, -1.05],
[0.2, -1.05],
[1.65, -1.05],
[2.35, 1.9]
];
for (const [x, z] of padLocations) {
const pad = new THREE.Mesh(
new THREE.CylinderGeometry(0.11, 0.11, 0.055, 12),
materials.brightCopper
);
pad.position.set(x, 0.39, z);
scene.add(pad);
}
function formatClock(seconds) {
const minutes = Math.floor(seconds / 60);
const remaining = seconds - minutes * 60;
return `${String(minutes).padStart(2, "0")}:${remaining
.toFixed(1)
.padStart(4, "0")}`;
}
function updateMeterDisplays() {
const maxCurrent = (24 / state.resistance) * 1000;
const maxPower = (24 * 24) / state.resistance;
const values = [
{
value: state.voltage.toFixed(1),
progress: state.voltage / 24
},
{
value: (state.current * 1000).toFixed(1),
progress: (state.current * 1000) / maxCurrent
},
{
value: String(state.resistance),
progress: state.resistance / 1000
},
{
value: state.power.toFixed(2),
progress: state.power / maxPower
}
];
meters.forEach((meter, index) => {
meter.value = values[index].value;
meter.progress = values[index].progress;
drawMeter(meter);
});
}
function updateReadouts() {
ui.voltageOutput.textContent = `${state.voltage.toFixed(1)} V`;
ui.voltageValue.textContent = `${state.voltage.toFixed(2)} V`;
ui.currentValue.textContent = `${(state.current * 1000).toFixed(2)} mA`;
ui.powerValue.textContent = `${state.power.toFixed(3)} W`;
ui.energyValue.textContent = `${state.energy.toFixed(3)} J`;
ui.clockValue.textContent = formatClock(state.elapsed);
if (state.paused) {
ui.status.textContent = "Paused";
ui.status.classList.add("paused");
ui.pauseState.textContent = "Clock frozen";
ui.clockDescription.textContent = "Energy accumulation stopped";
ui.pauseButton.textContent = "▶ Resume clock";
ui.pauseButton.classList.add("paused");
} else {
ui.status.textContent = "Running";
ui.status.classList.remove("paused");
ui.pauseState.textContent = "Clock running";
ui.clockDescription.textContent = "Integrating P × dt";
ui.pauseButton.textContent = "Ⅱ Pause clock";
ui.pauseButton.classList.remove("paused");
}
}
function computeCircuit() {
state.current = state.voltage / state.resistance;
state.power = state.voltage * state.current;
}
function applyVoltage() {
state.voltage = Number(ui.voltage.value);
computeCircuit();
// W and I update immediately, even while the energy clock is paused.
updateReadouts();
updateMeterDisplays();
}
ui.voltage.addEventListener("input", applyVoltage);
let lastTimestamp = performance.now();
ui.pauseButton.addEventListener("click", () => {
state.paused = !state.paused;
lastTimestamp = performance.now();
updateReadouts();
});
ui.resetButton.addEventListener("click", () => {
state.elapsed = 0;
state.energy = 0;
lastTimestamp = performance.now();
updateReadouts();
updateMeterDisplays();
});
// Avoid a large time jump after returning to a backgrounded tab.
document.addEventListener("visibilitychange", () => {
if (document.hidden && !state.paused) {
state.paused = true;
lastTimestamp = performance.now();
updateReadouts();
}
});
applyVoltage();
// Custom camera controls: no examples/addons are used.
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
view.theta -= deltaX * 0.007;
view.phi = THREE.MathUtils.clamp(
view.phi + deltaY * 0.006,
0.34,
1.35
);
updateCamera();
});
function stopDragging(event) {
dragging = false;
canvas.style.cursor = "grab";
if (event && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.style.cursor = "grab";
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
view.radius = THREE.MathUtils.clamp(
view.radius + event.deltaY * 0.012,
11,
28
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", () => {
view.theta = 0.57;
view.phi = 0.84;
view.radius = window.innerWidth < 760 ? 21 : 18;
view.target.set(
0.5,
0.25,
window.innerWidth < 760 ? 0.9 : 0
);
updateCamera();
});
canvas.addEventListener("keydown", (event) => {
const step = 0.07;
if (event.key === "ArrowLeft") view.theta -= step;
if (event.key === "ArrowRight") view.theta += step;
if (event.key === "ArrowUp") {
view.phi = Math.max(0.34, view.phi - step);
}
if (event.key === "ArrowDown") {
view.phi = Math.min(1.35, view.phi + step);
}
if (event.key === "+" || event.key === "=") {
view.radius = Math.max(11, view.radius - 0.8);
}
if (event.key === "-" || event.key === "_") {
view.radius = Math.min(28, view.radius + 0.8);
}
updateCamera();
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
let lastDisplayUpdate = 0;
function animate(timestamp) {
requestAnimationFrame(animate);
const delta = Math.max(0, Math.min((timestamp - lastTimestamp) / 1000, 0.25));
lastTimestamp = timestamp;
if (!state.paused && !document.hidden) {
state.elapsed += delta;
// Numerical integration of instantaneous power:
// E(t) = integral P(t) dt, measured in joules.
state.energy += state.power * delta;
}
if (timestamp - lastDisplayUpdate > 80) {
updateReadouts();
updateMeterDisplays();
lastDisplayUpdate = timestamp;
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```