Prompt specification
Build or customize the Three.js 3D scene "Ideal Billiard Collision Table" 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: Ideal Billiard Collision Table
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/ideal-billiard-collision-table-x3614
Scene Description Prompt:
Animate one frictionless equal-mass collision using an explicit ideal model. Display velocity vectors before and after and test momentum conservation within numerical tolerance. Use Three.js from cdnjs in a single HTML file, with visible voxel blocks.
Working Three.js Starter (ideal-billiard-collision-table-x3614):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ideal Equal-Mass Collision</title>
<style>
:root {
--bg: #07101d;
--panel: rgba(9, 20, 35, 0.88);
--border: rgba(139, 190, 224, 0.18);
--text: #e9f5ff;
--muted: #8fa8bd;
--cyan: #35d8f4;
--green: #9cf56a;
--amber: #ffbd59;
--red: #ff657a;
}
* {
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;
}
canvas {
position: fixed;
inset: 0;
display: block;
touch-action: none;
}
.panel {
position: fixed;
z-index: 10;
padding: 16px;
border: 1px solid var(--border);
border-radius: 14px;
background: var(--panel);
box-shadow: 0 16px 45px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(14px);
}
#stats {
top: 18px;
left: 18px;
width: 330px;
pointer-events: none;
}
#controls {
top: 18px;
right: 18px;
width: 320px;
}
#velocities {
left: 18px;
bottom: 18px;
width: 370px;
pointer-events: none;
}
h1 {
margin: 0 0 5px;
font-size: 19px;
letter-spacing: -0.02em;
}
.subtitle {
margin: 0 0 14px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.status-row,
.test-row,
.button-row,
.legend,
.velocity-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.status-row {
margin-bottom: 13px;
}
.phase {
padding: 5px 9px;
border: 1px solid rgba(143, 168, 189, 0.25);
border-radius: 999px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.11em;
}
.phase.running {
color: var(--cyan);
border-color: rgba(53, 216, 244, 0.45);
background: rgba(53, 216, 244, 0.08);
}
.phase.after {
color: var(--green);
border-color: rgba(156, 245, 106, 0.45);
background: rgba(156, 245, 106, 0.08);
}
.time {
color: var(--muted);
font: 12px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.stats-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.stat {
min-height: 58px;
padding: 10px;
border: 1px solid rgba(139, 190, 224, 0.1);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
}
.stat-label {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.08em;
}
.stat-value {
font: 600 16px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.test-row {
margin-top: 11px;
padding-top: 11px;
border-top: 1px solid var(--border);
}
.test-badge {
padding: 6px 11px;
border-radius: 999px;
color: var(--muted);
background: rgba(143, 168, 189, 0.1);
font-size: 11px;
font-weight: 800;
}
.test-badge.pass {
color: #07150a;
background: var(--green);
}
.test-badge.fail {
color: white;
background: var(--red);
}
.section-title {
margin-bottom: 10px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.12em;
}
.model-note {
margin: 0 0 13px;
color: #c3d6e4;
font-size: 11px;
line-height: 1.5;
}
.formula {
margin: 8px 0 13px;
padding: 9px 10px;
border-left: 2px solid var(--cyan);
color: #d8edf7;
background: rgba(53, 216, 244, 0.055);
font: 11px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace;
overflow-wrap: anywhere;
}
label {
display: block;
margin: 13px 0 6px;
color: var(--muted);
font-size: 11px;
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
.range-labels {
display: flex;
justify-content: space-between;
margin-top: 3px;
color: #657c91;
font-size: 9px;
}
.button-row {
margin-top: 15px;
}
button {
flex: 1;
padding: 9px 12px;
border: 1px solid rgba(53, 216, 244, 0.35);
border-radius: 9px;
color: var(--text);
background: rgba(53, 216, 244, 0.1);
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition: background 120ms ease, transform 120ms ease;
}
button:hover {
background: rgba(53, 216, 244, 0.19);
}
button:active {
transform: translateY(1px);
}
button.secondary {
color: var(--muted);
border-color: var(--border);
background: rgba(255, 255, 255, 0.03);
}
.velocity-columns {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.velocity-card {
padding: 11px;
border: 1px solid rgba(139, 190, 224, 0.12);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.velocity-heading {
margin-bottom: 10px;
font-size: 10px;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.09em;
}
.before .velocity-heading {
color: var(--cyan);
}
.after .velocity-heading {
color: var(--green);
}
.velocity-row {
display: grid;
grid-template-columns: 22px 1fr 58px;
align-items: center;
gap: 7px;
min-height: 29px;
}
.body-tag {
display: grid;
width: 21px;
height: 21px;
place-items: center;
border-radius: 6px;
color: #06131c;
background: var(--cyan);
font-size: 10px;
font-weight: 900;
}
.body-tag.b {
background: var(--amber);
}
.vector-track {
display: flex;
align-items: center;
width: 100%;
height: 18px;
}
.vector-shaft {
--arrow-color: var(--cyan);
position: relative;
display: block;
width: 0;
height: 3px;
border-radius: 3px;
color: var(--arrow-color);
background: var(--arrow-color);
transition: width 140ms ease;
}
.vector-shaft::after {
content: "";
position: absolute;
top: -5px;
right: -8px;
border-top: 6px solid transparent;
border-bottom: 6px solid transparent;
border-left: 9px solid var(--arrow-color);
}
.after .vector-shaft {
--arrow-color: var(--green);
}
.vector-shaft.zero {
width: 10px !important;
height: 10px;
border: 2px solid #778ba0;
border-radius: 50%;
background: transparent;
}
.vector-shaft.zero::after {
display: none;
}
.vector-value {
text-align: right;
color: #d8e8f4;
font: 11px ui-monospace, SFMono-Regular, Menlo, monospace;
}
.legend {
position: fixed;
z-index: 8;
left: 50%;
bottom: 18px;
transform: translateX(-50%);
padding: 9px 13px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(9, 20, 35, 0.72);
color: var(--muted);
font-size: 10px;
pointer-events: none;
white-space: nowrap;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--cyan);
}
.dot.green {
background: var(--green);
}
@media (max-width: 900px) {
#stats {
width: 280px;
}
#controls {
width: 280px;
}
#velocities {
width: 330px;
}
.legend {
display: none;
}
}
@media (max-width: 660px) {
.panel {
padding: 11px;
}
#stats {
top: 8px;
left: 8px;
width: calc(50% - 12px);
}
#controls {
top: 8px;
right: 8px;
width: calc(50% - 12px);
}
#velocities {
left: 8px;
bottom: 8px;
width: calc(100% - 16px);
}
h1 {
font-size: 14px;
}
.subtitle,
.model-note,
.formula,
.legend {
display: none;
}
.stats-grid {
gap: 5px;
}
.stat {
min-height: 48px;
padding: 7px;
}
.stat-label {
font-size: 8px;
}
.stat-value {
font-size: 12px;
}
.velocity-columns {
gap: 6px;
}
.velocity-card {
padding: 7px;
}
.velocity-row {
grid-template-columns: 20px 1fr 49px;
gap: 4px;
}
.section-title {
margin-bottom: 7px;
}
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<section id="stats" class="panel">
<h1>Ideal Equal-Mass Collision</h1>
<p class="subtitle">
One-dimensional, frictionless contact with coefficient of restitution
<strong>e = 1</strong>.
</p>
<div class="status-row">
<span id="phaseBadge" class="phase">READY</span>
<span id="timeText" class="time">t = 0.000 s</span>
</div>
<div class="stats-grid">
<div class="stat">
<span class="stat-label">Before momentum</span>
<span id="beforeMomentum" class="stat-value">—</span>
</div>
<div class="stat">
<span class="stat-label">Live momentum</span>
<span id="liveMomentum" class="stat-value">—</span>
</div>
<div class="stat">
<span class="stat-label">After momentum</span>
<span id="afterMomentum" class="stat-value">—</span>
</div>
<div class="stat">
<span class="stat-label">Momentum error</span>
<span id="momentumError" class="stat-value">—</span>
</div>
<div class="stat">
<span class="stat-label">Tolerance</span>
<span id="tolerance" class="stat-value">1.0e−9</span>
</div>
<div class="stat">
<span class="stat-label">Equal masses</span>
<span class="stat-value">1 kg + 1 kg</span>
</div>
</div>
<div class="test-row">
<span style="color: var(--muted); font-size: 11px;">
Numerical conservation test
</span>
<span id="testBadge" class="test-badge">PENDING</span>
</div>
</section>
<section id="controls" class="panel">
<div class="section-title">Explicit ideal model</div>
<p class="model-note">
The blocks have one translational degree of freedom along x. There is no
floor friction or external x-force. Contact is resolved with a normal
impulse. Equal masses therefore exchange their velocities.
</p>
<div class="formula">
J = −(1 + e)(v₂ − v₁) / (1/m₁ + 1/m₂)<br />
e = 1, m₁ = m₂ = 1 kg
</div>
<label for="launchSpeed">
Initial velocity of block A:
<strong id="speedValue">4.0 m/s</strong>
</label>
<input
id="launchSpeed"
type="range"
min="2"
max="8"
step="0.5"
value="4"
/>
<div class="range-labels">
<span>2 m/s</span>
<span>8 m/s</span>
</div>
<div class="button-row">
<button id="runButton">Run collision</button>
<button id="resetButton" class="secondary">Reset</button>
</div>
</section>
<section id="velocities" class="panel">
<div class="section-title">Velocity vectors — measured from the simulation</div>
<div class="velocity-columns">
<div class="velocity-card before">
<div class="velocity-heading">Before collision</div>
<div class="velocity-row">
<span class="body-tag">A</span>
<span class="vector-track">
<i id="beforeVectorA" class="vector-shaft"></i>
</span>
<span id="beforeVelocityA" class="vector-value">—</span>
</div>
<div class="velocity-row">
<span class="body-tag b">B</span>
<span class="vector-track">
<i id="beforeVectorB" class="vector-shaft"></i>
</span>
<span id="beforeVelocityB" class="vector-value">—</span>
</div>
</div>
<div class="velocity-card after">
<div class="velocity-heading">After collision</div>
<div class="velocity-row">
<span class="body-tag">A</span>
<span class="vector-track">
<i id="afterVectorA" class="vector-shaft zero"></i>
</span>
<span id="afterVelocityA" class="vector-value">—</span>
</div>
<div class="velocity-row">
<span class="body-tag b">B</span>
<span class="vector-track">
<i id="afterVectorB" class="vector-shaft zero"></i>
</span>
<span id="afterVelocityB" class="vector-value">—</span>
</div>
</div>
</div>
</section>
<div class="legend">
<span><i class="dot"></i> Before</span>
<span><i class="dot green"></i> After</span>
<span>Drag: orbit · Wheel: zoom · Space: replay · R: reset</span>
</div>
<script type="module">
// Only the Three.js core ES module is used.
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const canvas = document.querySelector("#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.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07101d);
scene.fog = new THREE.Fog(0x07101d, 17, 32);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0.55, 0.55, 0);
const orbit = {
radius: 14,
theta: 0.47,
phi: 1.04
};
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
cameraTarget.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
cameraTarget.y + orbit.radius * Math.cos(orbit.phi),
cameraTarget.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xbfe8ff, 0x152033, 1.7));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.7);
keyLight.position.set(-5, 11, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -11;
keyLight.shadow.camera.right = 11;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 35;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x46d8ff, 1.25);
rimLight.position.set(8, 4, -8);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(28, 16),
new THREE.MeshStandardMaterial({
color: 0x0b1725,
roughness: 0.94,
metalness: 0.03
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.012;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(28, 56, 0x28516a, 0x163247);
grid.position.y = 0.002;
grid.scale.z = 16 / 28;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
const axisPoints = [
new THREE.Vector3(-8, 0.018, 0),
new THREE.Vector3(8, 0.018, 0)
];
const axis = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(axisPoints),
new THREE.LineBasicMaterial({
color: 0x3e7893,
transparent: true,
opacity: 0.5
})
);
scene.add(axis);
// -------------------------------------------------------------------------
// Voxel construction
// -------------------------------------------------------------------------
const VOXEL_COUNT = 4;
const VOXEL_SIZE = 0.24;
const VOXEL_GAP = 0.03;
const BLOCK_SIZE =
VOXEL_COUNT * VOXEL_SIZE + (VOXEL_COUNT - 1) * VOXEL_GAP;
const BLOCK_HALF = BLOCK_SIZE / 2;
const voxelGeometry = new THREE.BoxGeometry(
VOXEL_SIZE,
VOXEL_SIZE,
VOXEL_SIZE
);
function makeLabel(text, color) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 128;
labelCanvas.height = 64;
const context = labelCanvas.getContext("2d");
context.fillStyle = "rgba(4, 12, 24, 0.88)";
context.fillRect(0, 0, 128, 64);
context.strokeStyle = color;
context.lineWidth = 4;
context.strokeRect(3, 3, 122, 58);
context.fillStyle = color;
context.font = "bold 36px sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 64, 34);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false,
depthTest: false
})
);
sprite.scale.set(0.82, 0.41, 1);
sprite.position.set(0, 0.02, 0.72);
sprite.renderOrder = 20;
return sprite;
}
function createVoxelBlock(letter, colors) {
const group = new THREE.Group();
const materials = colors.map(
(color) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.48,
metalness: 0.12
})
);
const spacing = VOXEL_SIZE + VOXEL_GAP;
const offset = ((VOXEL_COUNT - 1) * spacing) / 2;
let index = 0;
for (let ix = 0; ix < VOXEL_COUNT; ix++) {
for (let iy = 0; iy < VOXEL_COUNT; iy++) {
for (let iz = 0; iz < VOXEL_COUNT; iz++) {
const voxel = new THREE.Mesh(
voxelGeometry,
materials[(index + ix + iy * 2 + iz * 3) % materials.length]
);
voxel.position.set(
ix * spacing - offset,
iy * spacing - offset,
iz * spacing - offset
);
voxel.castShadow = true;
voxel.receiveShadow = true;
group.add(voxel);
index++;
}
}
}
group.add(makeLabel(letter, letter === "A" ? "#35d8f4" : "#ffbd59"));
scene.add(group);
return group;
}
const blockA = createVoxelBlock("A", [
0x21b8d4,
0x35d8f4,
0x68e6f7
]);
const blockB = createVoxelBlock("B", [
0xd88b18,
0xffb743,
0xffd078
]);
// -------------------------------------------------------------------------
// 3D velocity arrows
// -------------------------------------------------------------------------
const BEFORE_COLOR = 0x35d8f4;
const AFTER_COLOR = 0x9cf56a;
function createVelocityArrow() {
const arrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1,
BEFORE_COLOR,
0.25,
0.14
);
arrow.line.material.transparent = true;
arrow.line.material.opacity = 0.95;
arrow.cone.material.transparent = true;
arrow.cone.material.opacity = 0.95;
scene.add(arrow);
const zeroMarker = new THREE.Mesh(
new THREE.SphereGeometry(0.065, 12, 8),
new THREE.MeshBasicMaterial({ color: BEFORE_COLOR })
);
scene.add(zeroMarker);
return { arrow, zeroMarker };
}
const velocityA = createVelocityArrow();
const velocityB = createVelocityArrow();
// -------------------------------------------------------------------------
// Explicit ideal collision model
// -------------------------------------------------------------------------
//
// State variables:
// x, v : translational position and velocity along x
// m : equal mass
//
// Contact occurs when the center separation equals BLOCK_SIZE.
// The collision impulse is:
//
// J = -(1 + e)(v2 - v1) / (1/m1 + 1/m2)
//
// With e = 1 and equal masses, the body velocities exchange.
// There is no tangential impulse, rotation, friction, or external x-force.
// -------------------------------------------------------------------------
const RESTITUTION = 1.0;
const MOMENTUM_TOLERANCE = 1e-9;
const FIXED_TIME_STEP = 1 / 240;
const INITIAL_X_A = -2.4;
const INITIAL_X_B = 1.8;
const simulation = {
phase: "ready",
elapsed: 0,
afterElapsed: 0,
accumulator: 0,
collided: false,
collisionTime: 0,
beforeVelocities: [0, 0],
beforeMomentum: 0,
afterMomentum: null,
momentumError: null,
bodies: [
{
x: INITIAL_X_A,
v: 0,
m: 1,
group: blockA,
vector: velocityA
},
{
x: INITIAL_X_B,
v: 0,
m: 1,
group: blockB,
vector: velocityB
}
]
};
const pulses = [];
function spawnCollisionPulse(x) {
const material = new THREE.MeshBasicMaterial({
color: AFTER_COLOR,
wireframe: true,
transparent: true,
opacity: 0.95
});
const pulse = new THREE.Mesh(
new THREE.SphereGeometry(0.24, 16, 10),
material
);
pulse.position.set(x, BLOCK_HALF + 0.015, 0);
scene.add(pulse);
pulses.push({ mesh: pulse, age: 0 });
}
function resetSimulation() {
const speed = Number(document.querySelector("#launchSpeed").value);
simulation.phase = "ready";
simulation.elapsed = 0;
simulation.afterElapsed = 0;
simulation.accumulator = 0;
simulation.collided = false;
simulation.collisionTime = 0;
simulation.bodies[0].x = INITIAL_X_A;
simulation.bodies[0].v = speed;
simulation.bodies[1].x = INITIAL_X_B;
simulation.bodies[1].v = 0;
simulation.beforeVelocities = [speed, 0];
simulation.beforeMomentum =
simulation.bodies[0].m * simulation.bodies[0].v +
simulation.bodies[1].m * simulation.bodies[1].v;
simulation.afterMomentum = null;
simulation.momentumError = null;
updateVisuals();
updateUI();
}
function startSimulation() {
if (simulation.phase === "complete") {
resetSimulation();
}
simulation.phase = "running";
simulation.accumulator = 0;
updateUI();
}
function resolveCollision() {
const [a, b] = simulation.bodies;
// Relative velocity of B with respect to A, along the +x contact normal.
const relativeNormalVelocity = b.v - a.v;
if (relativeNormalVelocity >= 0) {
return;
}
const inverseMassA = 1 / a.m;
const inverseMassB = 1 / b.m;
// Explicit frictionless normal impulse for a perfectly elastic collision.
const impulse =
-(1 + RESTITUTION) *
relativeNormalVelocity /
(inverseMassA + inverseMassB);
a.v -= impulse * inverseMassA;
b.v += impulse * inverseMassB;
simulation.collided = true;
simulation.phase = "after";
simulation.afterElapsed = 0;
simulation.collisionTime = simulation.elapsed;
simulation.afterMomentum = a.m * a.v + b.m * b.v;
simulation.momentumError = Math.abs(
simulation.afterMomentum - simulation.beforeMomentum
);
spawnCollisionPulse((a.x + b.x) / 2);
updateUI();
}
function physicsStep(dt) {
if (simulation.phase !== "running" && simulation.phase !== "after") {
return;
}
const [a, b] = simulation.bodies;
simulation.elapsed += dt;
if (!simulation.collided) {
// Constant velocity between contacts; there are no external x-forces.
a.x += a.v * dt;
b.x += b.v * dt;
const centerSeparation = b.x - a.x;
if (centerSeparation <= BLOCK_SIZE) {
// Remove any fixed-step overlap, distributing the correction equally.
const overlap = BLOCK_SIZE - centerSeparation;
a.x -= overlap / 2;
b.x += overlap / 2;
resolveCollision();
}
}
if (simulation.collided && simulation.phase === "after") {
a.x += a.v * dt;
b.x += b.v * dt;
simulation.afterElapsed += dt;
// Freeze after a short post-collision drift so the result remains visible.
if (simulation.afterElapsed >= 0.9) {
simulation.phase = "complete";
}
}
}
// -------------------------------------------------------------------------
// Visual updates
// -------------------------------------------------------------------------
function updateVectorGraphic(element, value, maximum) {
const isZero = value === null || Math.abs(value) <= 1e-10;
element.classList.toggle("zero", isZero);
if (isZero) {
element.style.width = "";
return;
}
const width = Math.max(8, (Math.abs(value) / maximum) * 82);
element.style.width = `${width}px`;
}
function updateVisuals() {
const vectorColor = simulation.collided ? AFTER_COLOR : BEFORE_COLOR;
for (const body of simulation.bodies) {
body.group.position.set(
body.x,
BLOCK_HALF + 0.015,
0
);
const { arrow, zeroMarker } = body.vector;
const arrowY = BLOCK_HALF + 0.92;
arrow.position.set(body.x, arrowY, 0);
zeroMarker.position.set(body.x, arrowY, 0);
arrow.setColor(vectorColor);
zeroMarker.material.color.setHex(vectorColor);
if (Math.abs(body.v) > 1e-10) {
const direction = new THREE.Vector3(
body.v >= 0 ? 1 : -1,
0,
0
);
const length = Math.abs(body.v) * 0.42;
arrow.visible = true;
zeroMarker.visible = false;
arrow.setDirection(direction);
arrow.setLength(
length,
Math.min(0.28, length * 0.3),
Math.min(0.15, length * 0.18)
);
} else {
arrow.visible = false;
zeroMarker.visible = true;
}
}
for (let i = pulses.length - 1; i >= 0; i--) {
const pulse = pulses[i];
pulse.age += 1 / 60;
const scale = 1 + pulse.age * 3.8;
pulse.mesh.scale.setScalar(scale);
pulse.mesh.material.opacity = Math.max(0, 0.95 - pulse.age * 1.6);
if (pulse.age >= 0.6) {
scene.remove(pulse.mesh);
pulse.mesh.geometry.dispose();
pulse.mesh.material.dispose();
pulses.splice(i, 1);
}
}
}
function formatMomentum(value) {
if (value === null || !Number.isFinite(value)) {
return "—";
}
if (Math.abs(value) < 1e-12) {
return "0.000000";
}
return value.toFixed(6);
}
function formatError(value) {
if (value === null || !Number.isFinite(value)) {
return "—";
}
if (value === 0) {
return "0";
}
return value.toExponential(2);
}
function updateUI() {
const [a, b] = simulation.bodies;
const liveMomentum = a.m * a.v + b.m * b.v;
const liveError = Math.abs(liveMomentum - simulation.beforeMomentum);
const maximumVelocity = Math.max(
Number(document.querySelector("#launchSpeed").value),
0.001
);
const phaseBadge = document.querySelector("#phaseBadge");
phaseBadge.className = "phase";
if (simulation.phase === "running") {
phaseBadge.textContent = "APPROACH";
phaseBadge.classList.add("running");
} else if (simulation.phase === "after" || simulation.phase === "complete") {
phaseBadge.textContent = "AFTER COLLISION";
phaseBadge.classList.add("after");
} else {
phaseBadge.textContent = "READY";
}
document.querySelector("#timeText").textContent =
`t = ${simulation.elapsed.toFixed(3)} s`;
document.querySelector("#beforeMomentum").textContent =
formatMomentum(simulation.beforeMomentum);
document.querySelector("#liveMomentum").textContent =
formatMomentum(liveMomentum);
document.querySelector("#afterMomentum").textContent =
formatMomentum(simulation.afterMomentum);
document.querySelector("#momentumError").textContent =
formatError(
simulation.momentumError !== null
? simulation.momentumError
: liveError
);
document.querySelector("#tolerance").textContent =
MOMENTUM_TOLERANCE.toExponential(1).replace("e-", "e−");
const testBadge = document.querySelector("#testBadge");
if (simulation.afterMomentum !== null) {
const passed =
simulation.momentumError <= MOMENTUM_TOLERANCE;
testBadge.textContent = passed ? "PASS" : "FAIL";
testBadge.className = `test-badge ${passed ? "pass" : "fail"}`;
} else if (simulation.phase === "running") {
const livePass = liveError <= MOMENTUM_TOLERANCE;
testBadge.textContent = livePass ? "LIVE Δp PASS" : "LIVE Δp FAIL";
testBadge.className = `test-badge ${livePass ? "pass" : "fail"}`;
} else {
testBadge.textContent = "PENDING";
testBadge.className = "test-badge";
}
const beforeA = simulation.beforeVelocities[0];
const beforeB = simulation.beforeVelocities[1];
document.querySelector("#beforeVelocityA").textContent =
`${beforeA.toFixed(2)} m/s`;
document.querySelector("#beforeVelocityB").textContent =
`${beforeB.toFixed(2)} m/s`;
updateVectorGraphic(
document.querySelector("#beforeVectorA"),
beforeA,
maximumVelocity
);
updateVectorGraphic(
document.querySelector("#beforeVectorB"),
beforeB,
maximumVelocity
);
const afterA = simulation.collided ? a.v : null;
const afterB = simulation.collided ? b.v : null;
document.querySelector("#afterVelocityA").textContent =
afterA === null ? "—" : `${afterA.toFixed(2)} m/s`;
document.querySelector("#afterVelocityB").textContent =
afterB === null ? "—" : `${afterB.toFixed(2)} m/s`;
updateVectorGraphic(
document.querySelector("#afterVectorA"),
afterA,
maximumVelocity
);
updateVectorGraphic(
document.querySelector("#afterVectorB"),
afterB,
maximumVelocity
);
}
// -------------------------------------------------------------------------
// Controls
// -------------------------------------------------------------------------
const speedInput = document.querySelector("#launchSpeed");
const speedValue = document.querySelector("#speedValue");
const runButton = document.querySelector("#runButton");
const resetButton = document.querySelector("#resetButton");
let autoStartTimer = null;
speedInput.addEventListener("input", () => {
speedValue.textContent = `${Number(speedInput.value).toFixed(1)} m/s`;
if (autoStartTimer !== null) {
clearTimeout(autoStartTimer);
autoStartTimer = null;
}
resetSimulation();
});
runButton.addEventListener("click", () => {
if (autoStartTimer !== null) {
clearTimeout(autoStartTimer);
autoStartTimer = null;
}
resetSimulation();
startSimulation();
});
resetButton.addEventListener("click", () => {
if (autoStartTimer !== null) {
clearTimeout(autoStartTimer);
autoStartTimer = null;
}
resetSimulation();
});
window.addEventListener("keydown", (event) => {
if (
event.target instanceof HTMLInputElement ||
event.target instanceof HTMLButtonElement
) {
return;
}
if (event.code === "Space") {
event.preventDefault();
resetSimulation();
startSimulation();
}
if (event.key.toLowerCase() === "r") {
resetSimulation();
}
});
// Direct camera controls: no examples/jsm or legacy OrbitControls.
let dragging = false;
let pointerX = 0;
let pointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) {
return;
}
const deltaX = event.clientX - pointerX;
const deltaY = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
orbit.theta -= deltaX * 0.006;
orbit.phi = THREE.MathUtils.clamp(
orbit.phi + deltaY * 0.005,
0.28,
1.43
);
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();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
8,
24
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", () => {
orbit.radius = 14;
orbit.theta = 0.47;
orbit.phi = 1.04;
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);
});
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const frameDelta = Math.min(clock.getDelta(), 0.05);
if (simulation.phase === "running" || simulation.phase === "after") {
simulation.accumulator += frameDelta;
while (simulation.accumulator >= FIXED_TIME_STEP) {
physicsStep(FIXED_TIME_STEP);
simulation.accumulator -= FIXED_TIME_STEP;
}
}
updateVisuals();
updateUI();
renderer.render(scene, camera);
}
resetSimulation();
animate();
// Automatically perform the one collision shortly after loading.
autoStartTimer = window.setTimeout(() => {
if (simulation.phase === "ready") {
startSimulation();
}
autoStartTimer = null;
}, 700);
</script>
</body>
</html>
```