Prompt specification
Build or customize the Three.js 3D scene "Toy launcher energy exhibit" 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: Toy launcher energy exhibit
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/toy-launcher-energy-exhibit-x1431
Scene Description Prompt:
A voxel spring-cart launcher comparing compression energy with motion under a declared ideal or damped model. Three.js from cdnjs, one HTML file.
Working Three.js Starter (toy-launcher-energy-exhibit-x1431):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Spring Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #071019;
--panel: rgba(10, 21, 31, 0.88);
--panel-strong: rgba(7, 15, 23, 0.95);
--border: rgba(159, 198, 216, 0.16);
--border-strong: rgba(159, 198, 216, 0.28);
--text: #edf6f8;
--muted: #8399a7;
--ideal: #4ce6d2;
--damped: #ffb45d;
--spring: #ffd166;
--heat: #ff647c;
--shadow: 0 18px 55px rgba(0, 0, 0, 0.32);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#stage,
#labels {
position: fixed;
inset: 0;
}
#stage {
z-index: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage canvas:active {
cursor: grabbing;
}
#labels {
z-index: 2;
pointer-events: none;
}
.ui {
position: fixed;
z-index: 5;
}
.panel {
border: 1px solid var(--border);
border-radius: 18px;
background:
linear-gradient(145deg, rgba(255, 255, 255, 0.035), transparent 45%),
var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
}
header {
top: 18px;
left: 20px;
right: 20px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
pointer-events: none;
}
header > * {
pointer-events: auto;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 260px;
text-shadow: 0 2px 16px rgba(0, 0, 0, 0.55);
}
.brand-mark {
display: grid;
grid-template-columns: repeat(2, 8px);
grid-template-rows: repeat(2, 8px);
gap: 3px;
transform: rotate(-8deg);
}
.brand-mark i {
display: block;
background: var(--ideal);
box-shadow: 0 0 14px rgba(76, 230, 210, 0.35);
}
.brand-mark i:nth-child(2),
.brand-mark i:nth-child(3) {
background: var(--spring);
}
.brand h1 {
margin: 0;
font-size: 17px;
line-height: 1.1;
letter-spacing: 0.12em;
}
.brand p {
margin: 5px 0 0;
color: #a6bac5;
font-size: 11px;
letter-spacing: 0.07em;
}
.header-right {
display: flex;
align-items: center;
gap: 10px;
}
.mode-switch {
display: flex;
gap: 3px;
padding: 4px;
border: 1px solid var(--border);
border-radius: 12px;
background: rgba(7, 15, 23, 0.76);
backdrop-filter: blur(14px);
}
.mode-switch button {
border: 0;
border-radius: 8px;
padding: 8px 11px;
background: transparent;
color: var(--muted);
font-size: 11px;
font-weight: 750;
letter-spacing: 0.06em;
cursor: pointer;
transition: 160ms ease;
}
.mode-switch button:hover {
color: var(--text);
}
.mode-switch button.active {
background: rgba(125, 180, 197, 0.15);
color: var(--text);
box-shadow: inset 0 0 0 1px var(--border-strong);
}
.status {
min-width: 80px;
padding: 9px 11px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(7, 15, 23, 0.76);
color: var(--ideal);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-align: center;
}
#controls {
top: 82px;
left: 18px;
width: 300px;
max-height: calc(100vh - 100px);
overflow: auto;
padding: 17px;
scrollbar-width: thin;
scrollbar-color: rgba(150, 190, 210, 0.2) transparent;
}
.panel-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 15px;
}
.panel-heading h2 {
margin: 0;
font-size: 12px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.panel-heading span {
color: var(--muted);
font-size: 10px;
}
.control {
margin: 0 0 15px;
}
.control label {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
color: #b7c8d0;
font-size: 11px;
}
.control output {
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
font-weight: 700;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0;
appearance: none;
border-radius: 10px;
background: rgba(159, 198, 216, 0.18);
accent-color: var(--ideal);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
appearance: none;
border: 3px solid #10212d;
border-radius: 4px;
background: var(--ideal);
box-shadow: 0 0 0 1px rgba(76, 230, 210, 0.5);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #10212d;
border-radius: 4px;
background: var(--ideal);
box-shadow: 0 0 0 1px rgba(76, 230, 210, 0.5);
}
#b {
accent-color: var(--damped);
}
#b::-webkit-slider-thumb {
background: var(--damped);
box-shadow: 0 0 0 1px rgba(255, 180, 93, 0.5);
}
#b::-moz-range-thumb {
background: var(--damped);
}
.button-row {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px;
margin-top: 17px;
}
.primary,
.secondary {
min-height: 40px;
border-radius: 10px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
transition: 150ms ease;
}
.primary {
border: 1px solid rgba(76, 230, 210, 0.45);
background: var(--ideal);
color: #071019;
box-shadow: 0 7px 22px rgba(76, 230, 210, 0.12);
}
.primary:hover {
transform: translateY(-1px);
background: #70f0df;
}
.secondary {
border: 1px solid var(--border);
background: rgba(255, 255, 255, 0.035);
color: #b8c9d1;
padding: 0 14px;
}
.secondary:hover {
border-color: var(--border-strong);
color: var(--text);
}
details {
margin-top: 15px;
padding-top: 13px;
border-top: 1px solid var(--border);
}
summary {
color: #b7c8d0;
font-size: 11px;
font-weight: 750;
cursor: pointer;
}
.model-copy {
margin: 11px 0 0;
color: var(--muted);
font-size: 10.5px;
line-height: 1.55;
}
.equation {
display: block;
margin: 8px 0;
padding: 8px 9px;
border: 1px solid var(--border);
border-radius: 8px;
background: rgba(0, 0, 0, 0.17);
color: #d8e6eb;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
line-height: 1.5;
}
.camera-help {
margin-top: 10px;
color: #617987;
font-size: 9.5px;
letter-spacing: 0.03em;
}
#ledger {
top: 82px;
right: 18px;
width: 316px;
max-height: calc(100vh - 100px);
overflow: auto;
padding: 17px;
scrollbar-width: thin;
scrollbar-color: rgba(150, 190, 210, 0.2) transparent;
}
.initial-energy {
margin-bottom: 13px;
padding: 11px 12px;
border: 1px solid var(--border);
border-radius: 11px;
background: rgba(0, 0, 0, 0.16);
}
.initial-energy span {
display: block;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.initial-energy strong {
display: block;
margin-top: 5px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 16px;
}
.energy-card {
--motion: var(--ideal);
margin-top: 10px;
padding: 12px;
border: 1px solid var(--border);
border-left: 3px solid var(--motion);
border-radius: 12px;
background: rgba(0, 0, 0, 0.13);
}
.energy-card.damped {
--motion: var(--damped);
}
.energy-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 10px;
}
.energy-title strong {
color: var(--motion);
font-size: 11px;
letter-spacing: 0.1em;
}
.energy-title span {
color: var(--muted);
font-size: 9px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.energy-bar {
display: flex;
width: 100%;
height: 8px;
overflow: hidden;
border-radius: 10px;
background: rgba(255, 255, 255, 0.055);
}
.energy-bar i {
display: block;
height: 100%;
width: 0;
transition: width 80ms linear;
}
.energy-bar .spring {
background: var(--spring);
}
.energy-bar .kinetic {
background: var(--motion);
}
.energy-bar .heat {
background: var(--heat);
}
.energy-values {
display: grid;
gap: 6px;
margin-top: 10px;
}
.energy-values div {
display: flex;
justify-content: space-between;
gap: 12px;
color: var(--muted);
font-size: 10px;
}
.energy-values strong {
color: #d9e6eb;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-weight: 650;
}
.energy-legend {
display: flex;
flex-wrap: wrap;
gap: 10px;
margin-top: 12px;
color: var(--muted);
font-size: 9px;
}
.energy-legend span {
display: flex;
align-items: center;
gap: 5px;
}
.energy-legend i {
width: 7px;
height: 7px;
border-radius: 2px;
}
#comparisonLine {
min-height: 34px;
margin: 12px 1px 0;
color: #93aab7;
font-size: 10px;
line-height: 1.55;
}
#telemetry {
left: 50%;
bottom: 18px;
display: grid;
grid-template-columns: repeat(6, minmax(78px, 1fr));
width: min(620px, calc(100vw - 680px));
min-width: 490px;
transform: translateX(-50%);
overflow: hidden;
}
.tel-item {
padding: 11px 10px;
border-right: 1px solid var(--border);
text-align: center;
}
.tel-item:last-child {
border-right: 0;
}
.tel-item span {
display: block;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.tel-item strong {
display: block;
margin-top: 4px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
white-space: nowrap;
}
.ideal-text {
color: var(--ideal);
}
.damped-text {
color: var(--damped);
}
.lane-label {
position: absolute;
padding: 7px 10px;
border: 1px solid var(--border-strong);
border-radius: 9px;
background: rgba(7, 15, 23, 0.83);
color: var(--ideal);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.09em;
white-space: nowrap;
transform: translate(-50%, -50%);
backdrop-filter: blur(8px);
}
.lane-label.damped {
color: var(--damped);
}
#panelToggle {
display: none;
border: 1px solid var(--border);
border-radius: 10px;
padding: 8px 10px;
background: rgba(7, 15, 23, 0.82);
color: #c3d3da;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.07em;
cursor: pointer;
}
#webglError {
position: fixed;
inset: 0;
z-index: 20;
display: none;
place-items: center;
padding: 30px;
background: #071019;
color: #ffb4bf;
text-align: center;
}
@media (max-width: 1050px) {
#telemetry {
left: 18px;
right: 18px;
bottom: 14px;
width: auto;
min-width: 0;
transform: none;
}
#controls {
max-height: calc(100vh - 180px);
}
#ledger {
max-height: calc(100vh - 180px);
}
}
@media (max-width: 780px) {
header {
top: 10px;
left: 10px;
right: 10px;
align-items: flex-start;
}
.brand {
min-width: 0;
}
.brand h1 {
font-size: 13px;
}
.brand p,
.status {
display: none;
}
.header-right {
flex-wrap: wrap;
justify-content: flex-end;
}
.mode-switch button {
padding: 7px 8px;
font-size: 9px;
}
#panelToggle {
display: block;
}
#controls {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 48vh;
transform: translateY(calc(100% + 30px));
transition: transform 220ms ease;
}
body.controls-open #controls {
transform: translateY(0);
}
#ledger {
top: 68px;
right: 10px;
width: min(270px, calc(100vw - 20px));
max-height: 47vh;
padding: 12px;
}
.initial-energy {
padding: 8px 10px;
}
.initial-energy strong {
font-size: 13px;
}
.energy-card {
padding: 9px;
}
.energy-values {
gap: 4px;
}
#telemetry {
display: none;
}
.lane-label {
font-size: 8px;
}
}
@media (max-width: 460px) {
.brand-mark {
display: none;
}
.brand h1 {
max-width: 92px;
line-height: 1.2;
}
#ledger {
width: 218px;
}
.energy-legend,
#comparisonLine {
display: none;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<div id="labels"></div>
<header class="ui">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i><i></i>
</div>
<div>
<h1>VOXEL SPRING LAB</h1>
<p>Compression energy → cart motion</p>
</div>
</div>
<div class="header-right">
<div class="mode-switch" aria-label="Model view">
<button type="button" data-mode="compare" class="active" aria-pressed="true">
Compare
</button>
<button type="button" data-mode="ideal" aria-pressed="false">
Ideal
</button>
<button type="button" data-mode="damped" aria-pressed="false">
Damped
</button>
</div>
<div id="status" class="status">READY</div>
<button id="panelToggle" type="button" aria-controls="controls">
CONTROLS
</button>
</div>
</header>
<aside id="controls" class="panel ui">
<div class="panel-heading">
<h2>Launcher setup</h2>
<span>SI units</span>
</div>
<div class="control">
<label for="q0">
Spring compression
<output id="q0Out">0.160 m</output>
</label>
<input id="q0" type="range" min="0.04" max="0.30" step="0.005" value="0.16">
</div>
<div class="control">
<label for="k">
Spring stiffness
<output id="kOut">110 N/m</output>
</label>
<input id="k" type="range" min="30" max="240" step="1" value="110">
</div>
<div class="control">
<label for="m">
Cart mass
<output id="mOut">0.80 kg</output>
</label>
<input id="m" type="range" min="0.30" max="1.80" step="0.01" value="0.80">
</div>
<div class="control">
<label for="b">
Damping coefficient
<output id="bOut">0.55 N·s/m</output>
</label>
<input id="b" type="range" min="0" max="8" step="0.05" value="0.55">
</div>
<div class="control">
<label for="speed">
Playback speed
<output id="speedOut">1.0×</output>
</label>
<input id="speed" type="range" min="0.25" max="2" step="0.05" value="1">
</div>
<div class="button-row">
<button id="playBtn" class="primary" type="button">Launch</button>
<button id="resetBtn" class="secondary" type="button">Reset</button>
</div>
<details open>
<summary>Declared physical model</summary>
<div class="model-copy">
Let <b>q</b> be spring compression. While the spring remains attached:
<span class="equation">
m q̈ + b q̇ + kq = 0<br>
q(0) = q₀, q̇(0) = 0<br>
cart velocity v = −q̇
</span>
At the first <b>q = 0</b>, the spring detaches. The cart then follows:
<span class="equation">m v̇ + bv = 0</span>
The ideal lane sets <b>b = 0</b>. The damped lane uses the slider value.
Viscous work <b>b∫v²dt</b> is booked as heat. The track is horizontal,
the spring is linear, and rolling losses are omitted.
For very strong damping, q approaches zero asymptotically rather than
detaching at a finite time.
</div>
</details>
<div class="camera-help">
Camera: drag to orbit · shift/right-drag to pan · wheel to zoom · double-click to reset
</div>
</aside>
<aside id="ledger" class="panel ui">
<div class="panel-heading">
<h2>Energy ledger</h2>
<span id="modeCaption">side-by-side</span>
</div>
<div class="initial-energy">
<span>Initial spring energy</span>
<strong id="initialEnergy">1.408 J</strong>
</div>
<article id="idealCard" class="energy-card">
<div class="energy-title">
<strong>IDEAL · b = 0</strong>
<span id="idealRetained">100% retained</span>
</div>
<div class="energy-bar" aria-hidden="true">
<i id="idealBarSpring" class="spring"></i>
<i id="idealBarKinetic" class="kinetic"></i>
<i id="idealBarHeat" class="heat"></i>
</div>
<div class="energy-values">
<div><span>Spring potential</span><strong id="idealSpring">1.408 J</strong></div>
<div><span>Cart kinetic</span><strong id="idealKinetic">0.000 J</strong></div>
<div><span>Heat / loss</span><strong id="idealHeat">0.000 J</strong></div>
<div><span>Accounted energy</span><strong id="idealTotal">1.408 J</strong></div>
</div>
</article>
<article id="dampedCard" class="energy-card damped">
<div class="energy-title">
<strong id="dampedTitle">DAMPED · b = 0.55</strong>
<span id="dampedRetained">100% retained</span>
</div>
<div class="energy-bar" aria-hidden="true">
<i id="dampedBarSpring" class="spring"></i>
<i id="dampedBarKinetic" class="kinetic"></i>
<i id="dampedBarHeat" class="heat"></i>
</div>
<div class="energy-values">
<div><span>Spring potential</span><strong id="dampedSpring">1.408 J</strong></div>
<div><span>Cart kinetic</span><strong id="dampedKinetic">0.000 J</strong></div>
<div><span>Heat / loss</span><strong id="dampedHeat">0.000 J</strong></div>
<div><span>Accounted energy</span><strong id="dampedTotal">1.408 J</strong></div>
</div>
</article>
<div class="energy-legend">
<span><i style="background:var(--spring)"></i>Spring</span>
<span><i style="background:var(--ideal)"></i>Motion</span>
<span><i style="background:var(--heat)"></i>Heat</span>
</div>
<div id="comparisonLine">
Both carts begin with the same compressed spring and the same mass.
</div>
</aside>
<footer id="telemetry" class="panel ui">
<div class="tel-item">
<span>Time</span>
<strong id="tTime">0.00 s</strong>
</div>
<div id="idealSpeedTel" class="tel-item">
<span>Ideal speed</span>
<strong id="tIdealSpeed" class="ideal-text">0.00 m/s</strong>
</div>
<div id="idealDistanceTel" class="tel-item">
<span>Ideal travel</span>
<strong id="tIdealDistance" class="ideal-text">0.00 m</strong>
</div>
<div id="dampedSpeedTel" class="tel-item">
<span>Damped speed</span>
<strong id="tDampedSpeed" class="damped-text">0.00 m/s</strong>
</div>
<div id="dampedDistanceTel" class="tel-item">
<span>Damped travel</span>
<strong id="tDampedDistance" class="damped-text">0.00 m</strong>
</div>
<div class="tel-item">
<span>Speed gap</span>
<strong id="tGap">0.00 m/s</strong>
</div>
</footer>
<div id="webglError">
<div>
<h2>WebGL could not be initialized.</h2>
<p>Try a browser with hardware acceleration enabled.</p>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Model parameters and UI
// -------------------------------------------------------------------------
const params = {
q0: 0.16,
k: 110,
m: 0.80,
b: 0.55,
speed: 1
};
const FIXED_DT = 1 / 120;
const MAX_TIME = 8;
const ANCHOR_X = -2.20;
const NATURAL_LENGTH = 1.55;
const CART_HALF_LENGTH = 0.34;
const $ = (id) => document.getElementById(id);
const ui = {
q0: $("q0"),
k: $("k"),
m: $("m"),
b: $("b"),
speed: $("speed"),
q0Out: $("q0Out"),
kOut: $("kOut"),
mOut: $("mOut"),
bOut: $("bOut"),
speedOut: $("speedOut"),
play: $("playBtn"),
reset: $("resetBtn"),
status: $("status"),
initialEnergy: $("initialEnergy"),
comparisonLine: $("comparisonLine"),
modeCaption: $("modeCaption"),
panelToggle: $("panelToggle")
};
let mode = "compare";
let playing = false;
let completed = false;
let simulationTime = 0;
let accumulator = 0;
function initialEnergy() {
return 0.5 * params.k * params.q0 * params.q0;
}
function updateParameterLabels() {
ui.q0Out.textContent = `${params.q0.toFixed(3)} m`;
ui.kOut.textContent = `${params.k.toFixed(0)} N/m`;
ui.mOut.textContent = `${params.m.toFixed(2)} kg`;
ui.bOut.textContent = `${params.b.toFixed(2)} N·s/m`;
ui.speedOut.textContent = `${params.speed.toFixed(2)}×`;
ui.initialEnergy.textContent = `${initialEnergy().toFixed(3)} J`;
$("dampedTitle").textContent = `DAMPED · b = ${params.b.toFixed(2)}`;
idealLane.label.element.textContent = "IDEAL / b = 0";
dampedLane.label.element.textContent = `DAMPED / b = ${params.b.toFixed(2)}`;
}
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071019);
scene.fog = new THREE.Fog(0x071019, 20, 42);
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.05,
100
);
let renderer;
try {
renderer = new THREE.WebGLRenderer({ antialias: true });
} catch (error) {
$("webglError").style.display = "grid";
throw error;
}
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
$("stage").appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xc9efff, 0x101722, 1.7);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 2.7);
sun.position.set(4, 13, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -16;
sun.shadow.camera.right = 16;
sun.shadow.camera.top = 12;
sun.shadow.camera.bottom = -12;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
sun.target.position.set(6, 0, 0);
scene.add(sun, sun.target);
const cyanLight = new THREE.PointLight(0x42e8d2, 16, 14, 2);
cyanLight.position.set(-1, 2.5, -4);
scene.add(cyanLight);
const amberLight = new THREE.PointLight(0xffa74f, 14, 14, 2);
amberLight.position.set(8, 2.5, 5);
scene.add(amberLight);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x0b1620,
roughness: 0.93,
metalness: 0.05
});
const ground = new THREE.Mesh(
new THREE.BoxGeometry(42, 0.12, 30),
groundMaterial
);
ground.position.set(6, -0.18, 0);
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(42, 42, 0x23404e, 0x152a36);
grid.position.set(6, -0.115, 0);
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
function box(parent, size, position, material, castShadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
material
);
mesh.position.copy(position);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeLane(kind, accentColor, floorColor) {
const group = new THREE.Group();
scene.add(group);
const accent = new THREE.MeshStandardMaterial({
color: accentColor,
roughness: 0.48,
metalness: 0.24
});
const dark = new THREE.MeshStandardMaterial({
color: 0x172630,
roughness: 0.72,
metalness: 0.18
});
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x7a929d,
roughness: 0.34,
metalness: 0.82
});
const floorMaterial = new THREE.MeshStandardMaterial({
color: floorColor,
roughness: 0.9,
metalness: 0.06
});
box(
group,
new THREE.Vector3(18.8, 0.08, 1.10),
new THREE.Vector3(7.1, 0.015, 0),
floorMaterial,
false
);
box(
group,
new THREE.Vector3(18.8, 0.075, 0.065),
new THREE.Vector3(7.1, 0.115, 0.34),
railMaterial
);
box(
group,
new THREE.Vector3(18.8, 0.075, 0.065),
new THREE.Vector3(7.1, 0.115, -0.34),
railMaterial
);
for (let x = -2.25; x <= 16.45; x += 0.47) {
box(
group,
new THREE.Vector3(0.15, 0.07, 0.93),
new THREE.Vector3(x, 0.065, 0),
dark,
false
);
}
// Voxel spring anchor.
box(
group,
new THREE.Vector3(0.24, 0.72, 1.02),
new THREE.Vector3(ANCHOR_X - 0.08, 0.38, 0),
dark
);
box(
group,
new THREE.Vector3(0.30, 0.13, 1.12),
new THREE.Vector3(ANCHOR_X - 0.08, 0.10, 0),
accent
);
// End marker.
box(
group,
new THREE.Vector3(0.12, 0.50, 1.04),
new THREE.Vector3(16.42, 0.30, 0),
accent
);
const springMaterial = new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0x7a3e00,
emissiveIntensity: 1.2,
roughness: 0.35,
metalness: 0.58
});
const springBlocks = [];
const springCount = 15;
for (let i = 0; i < springCount; i++) {
const block = box(
group,
new THREE.Vector3(0.105, 0.095, 0.095),
new THREE.Vector3(),
springMaterial
);
springBlocks.push(block);
}
// Vertical stack of voxel energy cells.
const energyCells = [];
const energyCellGeometry = new THREE.BoxGeometry(0.115, 0.115, 0.115);
for (let i = 0; i < 8; i++) {
const material = new THREE.MeshStandardMaterial({
color: 0xffd166,
emissive: 0xa85b00,
emissiveIntensity: 1.4,
roughness: 0.4,
transparent: true,
opacity: 0.95,
depthWrite: false
});
const cell = new THREE.Mesh(energyCellGeometry, material);
cell.position.set(ANCHOR_X - 0.35, 0.62 + i * 0.14, 0.52);
cell.castShadow = true;
group.add(cell);
energyCells.push(cell);
}
// Voxel cart.
const cart = new THREE.Group();
group.add(cart);
const wheelMaterial = new THREE.MeshStandardMaterial({
color: 0x101820,
roughness: 0.72,
metalness: 0.32
});
box(
cart,
new THREE.Vector3(0.72, 0.15, 0.56),
new THREE.Vector3(0, 0.39, 0),
dark
);
box(
cart,
new THREE.Vector3(0.48, 0.18, 0.46),
new THREE.Vector3(0.06, 0.55, 0),
accent
);
box(
cart,
new THREE.Vector3(0.22, 0.16, 0.34),
new THREE.Vector3(-0.08, 0.70, 0),
dark
);
box(
cart,
new THREE.Vector3(0.12, 0.12, 0.50),
new THREE.Vector3(0.39, 0.45, 0),
railMaterial
);
box(
cart,
new THREE.Vector3(0.20, 0.07, 0.10),
new THREE.Vector3(-0.07, 0.83, 0),
springMaterial
);
const wheels = [];
for (const x of [-0.24, 0.24]) {
for (const z of [-0.34, 0.34]) {
const wheel = box(
cart,
new THREE.Vector3(0.18, 0.18, 0.18),
new THREE.Vector3(x, 0.21, z),
wheelMaterial
);
wheels.push(wheel);
}
}
const label = document.createElement("div");
label.className = `lane-label${kind === "damped" ? " damped" : ""}`;
$("labels").appendChild(label);
return {
kind,
group,
accent,
springMaterial,
springBlocks,
energyCells,
cart,
wheels,
label: { element: label },
labelAnchor: new THREE.Vector3(2.1, 1.05, 0)
};
}
const idealLane = makeLane("ideal", 0x4ce6d2, 0x102a2c);
const dampedLane = makeLane("damped", 0xffb45d, 0x30251a);
// -------------------------------------------------------------------------
// Custom camera controls: orbit, pan and zoom
// -------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(6, 0, 0),
radius: 18,
theta: 1.25,
phi: 1.02,
dragging: false,
panning: false,
lastX: 0,
lastY: 0
};
function updateCamera() {
const { target, radius, theta, phi } = cameraState;
const sinPhi = Math.sin(phi);
camera.position.set(
target.x + radius * sinPhi * Math.cos(theta),
target.y + radius * Math.cos(phi),
target.z + radius * sinPhi * Math.sin(theta)
);
camera.lookAt(target);
camera.updateMatrixWorld();
}
function resetCamera() {
cameraState.target.set(6, 0, 0);
cameraState.radius = 18;
cameraState.theta = 1.25;
cameraState.phi = 1.02;
updateCamera();
}
renderer.domElement.addEventListener("pointerdown", (event) => {
cameraState.dragging = true;
cameraState.panning =
event.shiftKey || event.button === 2 || event.button === 1;
cameraState.lastX = event.clientX;
cameraState.lastY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
event.preventDefault();
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!cameraState.dragging) return;
const dx = event.clientX - cameraState.lastX;
const dy = event.clientY - cameraState.lastY;
cameraState.lastX = event.clientX;
cameraState.lastY = event.clientY;
if (cameraState.panning) {
const scale =
2 *
Math.tan(THREE.MathUtils.degToRad(camera.fov * 0.5)) *
cameraState.radius /
innerHeight;
const right = new THREE.Vector3(1, 0, 0).applyQuaternion(
camera.quaternion
);
right.y = 0;
right.normalize();
const forward = new THREE.Vector3(0, 0, -1).applyQuaternion(
camera.quaternion
);
forward.y = 0;
forward.normalize();
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(forward, -dy * scale);
cameraState.target.x = THREE.MathUtils.clamp(
cameraState.target.x,
-4,
18
);
cameraState.target.z = THREE.MathUtils.clamp(
cameraState.target.z,
-8,
8
);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.32,
1.46
);
}
updateCamera();
});
function stopDragging(event) {
cameraState.dragging = false;
if (
renderer.domElement.hasPointerCapture &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener("contextmenu", (e) => e.preventDefault());
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
7,
34
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// Exact spring-contact dynamics
//
// q'' + gamma q' + omega^2 q = 0
// gamma = b/m, omega^2 = k/m
//
// The closed-form solution avoids integration errors and remains stable
// for underdamped, critically damped and overdamped cases.
// -------------------------------------------------------------------------
function evolveAttached(q, w, time, b, k, m) {
const gamma = b / m;
const omega2 = k / m;
if (gamma < 1e-10) {
const omega = Math.sqrt(omega2);
const c = Math.cos(omega * time);
const s = Math.sin(omega * time);
return [
q * c + (w / omega) * s,
-q * omega * s + w * c
];
}
const critical = Math.abs(gamma - 2 * Math.sqrt(omega2));
if (critical < 1e-6) {
const r = -gamma / 2;
const a = q;
const bTerm = w - r * q;
const e = Math.exp(r * time);
return [
(a + bTerm * time) * e,
(bTerm + r * (a + bTerm * time)) * e
];
}
const alpha = gamma / 2;
if (alpha < Math.sqrt(omega2)) {
const wd = Math.sqrt(omega2 - alpha * alpha);
const e = Math.exp(-alpha * time);
const c = Math.cos(wd * time);
const s = Math.sin(wd * time);
const coefficient = (w + alpha * q) / wd;
const qNext = e * (q * c + coefficient * s);
const wNext =
e *
(-alpha * (q * c + coefficient * s) -
q * wd * s +
coefficient * wd * c);
return [qNext, wNext];
}
const root = Math.sqrt(alpha * alpha - omega2);
const r1 = -alpha + root;
const r2 = -alpha - root;
const a = (w - r2 * q) / (r1 - r2);
const bCoefficient = q - a;
const e1 = Math.exp(r1 * time);
const e2 = Math.exp(r2 * time);
return [
a * e1 + bCoefficient * e2,
a * r1 * e1 + bCoefficient * r2 * e2
];
}
function stepFree(state, time, b) {
const gamma = b / params.m;
const decay = Math.exp(-gamma * time);
const nextVelocity = state.v * decay;
const displacement =
gamma < 1e-10
? state.v * time
: state.v * (1 - decay) / gamma;
state.s += displacement;
state.v = nextVelocity;
}
function stepState(state, dt, b) {
if (!state.attached) {
stepFree(state, dt, b);
return;
}
const previousQ = state.q;
const previousW = state.w;
const next = evolveAttached(
previousQ,
previousW,
dt,
b,
params.k,
params.m
);
if (next[0] <= 0 && previousQ > 0) {
// Find the first q=0 crossing within this time step.
let low = 0;
let high = dt;
for (let i = 0; i < 45; i++) {
const middle = (low + high) * 0.5;
const value = evolveAttached(
previousQ,
previousW,
middle,
b,
params.k,
params.m
)[0];
if (value > 0) low = middle;
else high = middle;
}
const rootTime = (low + high) * 0.5;
const rootState = evolveAttached(
previousQ,
previousW,
rootTime,
b,
params.k,
params.m
);
state.q = 0;
state.w = rootState[1];
state.v = -state.w;
state.s = params.q0;
state.attached = false;
stepFree(state, dt - rootTime, b);
} else {
state.q = next[0];
state.w = next[1];
state.v = -state.w;
state.s = params.q0 - state.q;
}
}
function makeState() {
return {
q: params.q0,
w: 0,
v: 0,
s: 0,
attached: true
};
}
let idealState = makeState();
let dampedState = makeState();
function resetSimulation(start = false) {
idealState = makeState();
dampedState = makeState();
simulationTime = 0;
accumulator = 0;
completed = false;
playing = start;
updateUI();
}
function togglePlay() {
if (completed) {
resetSimulation(true);
} else {
playing = !playing;
updateUI();
}
}
// -------------------------------------------------------------------------
// Energy accounting and interface
// -------------------------------------------------------------------------
function energyFor(state) {
const totalInitial = initialEnergy();
const spring = state.attached
? 0.5 * params.k * state.q * state.q
: 0;
const kinetic = 0.5 * params.m * state.v * state.v;
const heat = THREE.MathUtils.clamp(
totalInitial - spring - kinetic,
0,
totalInitial
);
return {
spring,
kinetic,
heat,
total: spring + kinetic + heat,
retained: totalInitial > 0
? 100 * (spring + kinetic) / totalInitial
: 0
};
}
const energyUI = {
ideal: {
card: $("idealCard"),
retained: $("idealRetained"),
spring: $("idealSpring"),
kinetic: $("idealKinetic"),
heat: $("idealHeat"),
total: $("idealTotal"),
barSpring: $("idealBarSpring"),
barKinetic: $("idealBarKinetic"),
barHeat: $("idealBarHeat")
},
damped: {
card: $("dampedCard"),
retained: $("dampedRetained"),
spring: $("dampedSpring"),
kinetic: $("dampedKinetic"),
heat: $("dampedHeat"),
total: $("dampedTotal"),
barSpring: $("dampedBarSpring"),
barKinetic: $("dampedBarKinetic"),
barHeat: $("dampedBarHeat")
}
};
function updateEnergyCard(elements, energy) {
const total = Math.max(initialEnergy(), 1e-9);
elements.spring.textContent = `${energy.spring.toFixed(3)} J`;
elements.kinetic.textContent = `${energy.kinetic.toFixed(3)} J`;
elements.heat.textContent = `${energy.heat.toFixed(3)} J`;
elements.total.textContent = `${energy.total.toFixed(3)} J`;
elements.retained.textContent = `${energy.retained.toFixed(1)}% retained`;
elements.barSpring.style.width =
`${(energy.spring / total) * 100}%`;
elements.barKinetic.style.width =
`${(energy.kinetic / total) * 100}%`;
elements.barHeat.style.width = `${(energy.heat / total) * 100}%`;
}
function updateUI() {
const idealEnergy = energyFor(idealState);
const dampedEnergy = energyFor(dampedState);
updateEnergyCard(energyUI.ideal, idealEnergy);
updateEnergyCard(energyUI.damped, dampedEnergy);
$("tTime").textContent = `${simulationTime.toFixed(2)} s`;
$("tIdealSpeed").textContent = `${idealState.v.toFixed(2)} m/s`;
$("tIdealDistance").textContent = `${idealState.s.toFixed(2)} m`;
$("tDampedSpeed").textContent = `${dampedState.v.toFixed(2)} m/s`;
$("tDampedDistance").textContent = `${dampedState.s.toFixed(2)} m`;
$("tGap").textContent = `${(
idealState.v - dampedState.v
).toFixed(2)} m/s`;
if (playing) {
ui.status.textContent = "RUNNING";
ui.status.style.color = "var(--ideal)";
ui.play.textContent = "Pause";
} else if (completed) {
ui.status.textContent = "COMPLETE";
ui.status.style.color = "var(--damped)";
ui.play.textContent = "Replay";
} else if (simulationTime > 0) {
ui.status.textContent = "PAUSED";
ui.status.style.color = "var(--spring)";
ui.play.textContent = "Resume";
} else {
ui.status.textContent = "READY";
ui.status.style.color = "var(--ideal)";
ui.play.textContent = "Launch";
}
if (mode === "compare") {
ui.comparisonLine.textContent =
`At ${simulationTime.toFixed(2)} s, the ideal cart has traveled ` +
`${idealState.s.toFixed(2)} m. The damped cart has traveled ` +
`${dampedState.s.toFixed(2)} m and dissipated ` +
`${dampedEnergy.heat.toFixed(2)} J.`;
} else if (mode === "ideal") {
ui.comparisonLine.textContent =
`The ideal cart retains all non-kinetic energy as motion; ` +
`no viscous heat is generated.`;
} else {
ui.comparisonLine.textContent =
`The damped cart converts ` +
`${dampedEnergy.heat.toFixed(2)} J into heat while remaining in ` +
`motion.`;
}
}
function setMode(nextMode) {
mode = nextMode;
document.querySelectorAll("[data-mode]").forEach((button) => {
const active = button.dataset.mode === mode;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
idealLane.group.visible = mode !== "damped";
dampedLane.group.visible = mode !== "ideal";
idealLane.group.position.z = mode === "ideal" ? 0 : -1.25;
dampedLane.group.position.z = mode === "damped" ? 0 : 1.25;
energyUI.ideal.card.style.display =
mode === "damped" ? "none" : "block";
energyUI.damped.card.style.display =
mode === "ideal" ? "none" : "block";
$("idealSpeedTel").style.display =
mode === "damped" ? "none" : "block";
$("idealDistanceTel").style.display =
mode === "damped" ? "none" : "block";
$("dampedSpeedTel").style.display =
mode === "ideal" ? "none" : "block";
$("dampedDistanceTel").style.display =
mode === "ideal" ? "none" : "block";
ui.modeCaption.textContent =
mode === "compare"
? "side-by-side"
: mode === "ideal"
? "lossless model"
: "viscous model";
resetSimulation(false);
}
// -------------------------------------------------------------------------
// Scene animation
// -------------------------------------------------------------------------
const darkSpring = new THREE.Color(0x63451d);
const brightSpring = new THREE.Color(0xffd166);
function updateLaneVisual(lane, state, dt) {
const cartX = state.attached
? ANCHOR_X + NATURAL_LENGTH - state.q
: ANCHOR_X + NATURAL_LENGTH + state.s;
lane.cart.position.x = cartX;
const rearX = cartX - CART_HALF_LENGTH;
const springLength = Math.max(0.18, rearX - ANCHOR_X);
const count = lane.springBlocks.length;
lane.springBlocks.forEach((block, index) => {
const t = (index + 0.5) / count;
const alternating = index % 2 === 0 ? 1 : -1;
block.position.set(
ANCHOR_X + t * springLength,
0.46 + alternating * 0.095,
alternating * 0.07
);
block.rotation.z = alternating * 0.17;
});
const energy = energyFor(state);
const springRatio = THREE.MathUtils.clamp(
energy.spring / Math.max(initialEnergy(), 1e-9),
0,
1
);
lane.springMaterial.color
.copy(darkSpring)
.lerp(brightSpring, 0.15 + springRatio * 0.85);
lane.springMaterial.emissiveIntensity = 0.15 + springRatio * 1.4;
const litCells = Math.ceil(springRatio * lane.energyCells.length);
lane.energyCells.forEach((cell, index) => {
const lit = index < litCells;
cell.material.opacity = lit ? 0.96 : 0.08;
cell.material.emissiveIntensity = lit ? 1.6 : 0.05;
cell.scale.setScalar(lit ? 1 : 0.72);
});
lane.wheels.forEach((wheel) => {
wheel.rotation.z -= state.v * dt * 3.2;
});
}
function updateLabels() {
const lanes = [
{ lane: idealLane, visible: idealLane.group.visible },
{ lane: dampedLane, visible: dampedLane.group.visible }
];
for (const { lane, visible } of lanes) {
if (!visible) {
lane.label.element.style.display = "none";
continue;
}
const point = lane.labelAnchor.clone();
point.z += lane.group.position.z;
point.project(camera);
const onScreen =
point.z >= -1 &&
point.z <= 1 &&
point.x >= -1.15 &&
point.x <= 1.15 &&
point.y >= -1.15 &&
point.y <= 1.15;
lane.label.element.style.display = onScreen ? "block" : "none";
if (onScreen) {
const x = (point.x * 0.5 + 0.5) * innerWidth;
const y = (-point.y * 0.5 + 0.5) * innerHeight;
lane.label.element.style.left = `${x}px`;
lane.label.element.style.top = `${y}px`;
}
}
}
// -------------------------------------------------------------------------
// Controls and resize
// -------------------------------------------------------------------------
function bindRange(id, key, parser = Number) {
$(id).addEventListener("input", (event) => {
params[key] = parser(event.target.value);
if (key !== "speed") {
resetSimulation(false);
}
updateParameterLabels();
updateUI();
});
}
bindRange("q0", "q0");
bindRange("k", "k");
bindRange("m", "m");
bindRange("b", "b");
bindRange("speed", "speed");
ui.play.addEventListener("click", togglePlay);
ui.reset.addEventListener("click", () => resetSimulation(false));
document.querySelectorAll("[data-mode]").forEach((button) => {
button.addEventListener("click", () => {
setMode(button.dataset.mode);
});
});
ui.panelToggle.addEventListener("click", () => {
document.body.classList.toggle("controls-open");
});
addEventListener("keydown", (event) => {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLButtonElement
) {
return;
}
if (event.code === "Space") {
event.preventDefault();
togglePlay();
}
if (event.key.toLowerCase() === "r") {
resetSimulation(false);
}
});
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
const frameDelta = Math.min(clock.getDelta(), 0.05);
if (playing && !completed) {
accumulator += frameDelta * params.speed;
while (accumulator >= FIXED_DT && simulationTime < MAX_TIME) {
stepState(idealState, FIXED_DT, 0);
stepState(dampedState, FIXED_DT, params.b);
simulationTime += FIXED_DT;
accumulator -= FIXED_DT;
}
if (simulationTime >= MAX_TIME) {
simulationTime = MAX_TIME;
completed = true;
playing = false;
accumulator = 0;
}
}
updateLaneVisual(idealLane, idealState, frameDelta);
updateLaneVisual(dampedLane, dampedState, frameDelta);
updateUI();
updateCamera();
renderer.render(scene, camera);
updateLabels();
requestAnimationFrame(animate);
}
setMode("compare");
updateParameterLabels();
resetCamera();
animate();
</script>
</body>
</html>
```