Prompt specification
Build or customize the Three.js 3D scene "Original Cushion-Bounce Table Game" 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: Original Cushion-Bounce Table Game
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/original-cushion-bounce-table-game-x3615
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows collision angles, contact normals, and mass ratios. Build a small original tabletop game with bumpers and target pockets. Use simple consistent collisions and make rebounds depend on wall normals rather than scripted paths. Voxel style.
Technical checks: Keep pieces inside the playfield and show no bounce events before launch. Check each side against its own boundary and register a hit only when a moving piece reaches that side.
Return one complete HTML document that works with the cdnjs Three.js r160 module inside a sandbox with scripts allowed. Make the requested subject visible at the default camera. Use procedural assets and local button handlers. Do not use native form submission, pointer lock, external assets or runtime requests other than Three.js.
Working Three.js Starter (original-cushion-bounce-table-game-x3615):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Impact Lab</title>
<style>
:root {
--bg: #07111d;
--panel: #0d1b2b;
--panel-2: #12263a;
--line: #254158;
--text: #eaf6ff;
--muted: #88a5bb;
--cyan: #58d9ff;
--green: #57e3b2;
--amber: #ffc857;
--violet: #a695ff;
--red: #ff6f7d;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
width: 100%;
min-height: 100%;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button, input { font: inherit; }
button {
border: 0;
cursor: pointer;
}
.app {
height: 100vh;
display: grid;
grid-template-rows: 70px minmax(0, 1fr);
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 22px;
background: #091725;
border-bottom: 1px solid var(--line);
z-index: 3;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
width: 38px;
height: 38px;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
gap: 3px;
transform: rotate(-8deg);
}
.brand-mark i {
display: block;
background: var(--cyan);
border-radius: 2px;
box-shadow: 0 0 12px #58d9ff44;
}
.brand-mark i:nth-child(1),
.brand-mark i:nth-child(3),
.brand-mark i:nth-child(5),
.brand-mark i:nth-child(9) { opacity: .28; }
.brand-mark i:nth-child(2),
.brand-mark i:nth-child(6),
.brand-mark i:nth-child(8) { background: var(--green); }
h1 {
margin: 0;
font-size: 18px;
line-height: 1;
letter-spacing: .14em;
text-transform: uppercase;
white-space: nowrap;
}
.subtitle {
margin-top: 6px;
color: var(--muted);
font: 600 10px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .12em;
text-transform: uppercase;
}
.header-status {
display: flex;
align-items: center;
gap: 9px;
color: var(--green);
font: 700 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .1em;
white-space: nowrap;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 12px currentColor;
}
main {
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 350px;
}
#stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 42%, #132a3d 0, #091725 55%, #07111d 100%);
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
#stage canvas:active { cursor: grabbing; }
.stage-hud {
position: absolute;
z-index: 2;
pointer-events: none;
}
.telemetry-badge {
top: 18px;
left: 18px;
display: flex;
align-items: center;
gap: 10px;
padding: 10px 13px;
border: 1px solid #31536b;
background: #081725cc;
backdrop-filter: blur(8px);
border-radius: 8px;
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .1em;
}
.telemetry-badge .pulse {
width: 7px;
height: 7px;
background: var(--green);
box-shadow: 0 0 10px var(--green);
}
.objective-banner {
left: 18px;
bottom: 18px;
max-width: 390px;
padding: 12px 14px;
border-left: 3px solid var(--cyan);
background: #081725d9;
backdrop-filter: blur(8px);
border-radius: 0 8px 8px 0;
}
.objective-banner strong {
display: block;
font-size: 12px;
letter-spacing: .08em;
text-transform: uppercase;
}
.objective-banner span {
display: block;
margin-top: 4px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.camera-tools {
position: absolute;
z-index: 4;
top: 18px;
right: 18px;
display: flex;
gap: 7px;
}
.camera-tools button {
padding: 9px 11px;
color: #cbe9fa;
background: #0a1a2be6;
border: 1px solid #31536b;
border-radius: 7px;
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .08em;
}
.camera-tools button:hover {
border-color: var(--cyan);
color: white;
}
.drag-hint {
position: absolute;
right: 18px;
bottom: 18px;
z-index: 2;
color: #7694aa;
font: 600 9px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .06em;
text-align: right;
pointer-events: none;
}
aside {
min-height: 0;
overflow-y: auto;
background: linear-gradient(180deg, #0d1b2b, #091725);
border-left: 1px solid var(--line);
scrollbar-width: thin;
scrollbar-color: #31536b #091725;
}
.section {
padding: 17px 18px;
border-bottom: 1px solid var(--line);
}
.section-title {
margin: 0 0 13px;
color: #a9c5d8;
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .16em;
text-transform: uppercase;
display: flex;
justify-content: space-between;
align-items: center;
}
.section-title .counter {
color: var(--cyan);
}
.mass-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-bottom: 15px;
}
.mass-button {
min-height: 46px;
color: #9eb6c8;
background: #102338;
border: 1px solid #28455b;
border-radius: 8px;
font: 800 15px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
transition: border-color .15s, background .15s, color .15s, transform .15s;
}
.mass-button:hover { transform: translateY(-1px); }
.mass-button.active {
color: #07111d;
background: var(--cyan);
border-color: #a4ecff;
box-shadow: 0 0 18px #58d9ff30;
}
.mass-button[data-mass="1"].active { background: var(--amber); border-color: #ffe4a2; }
.mass-button[data-mass="2"].active { background: var(--violet); border-color: #d6ceff; }
.mass-button[data-mass="4"].active { background: var(--green); border-color: #b2ffe5; }
.control-row {
display: grid;
grid-template-columns: 66px minmax(0, 1fr) 54px;
align-items: center;
gap: 9px;
margin-top: 11px;
color: var(--muted);
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .08em;
}
output {
color: var(--text);
text-align: right;
font: 800 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
input[type="range"] {
width: 100%;
height: 4px;
accent-color: var(--cyan);
cursor: pointer;
}
.button-row {
display: grid;
grid-template-columns: 1fr 84px;
gap: 8px;
margin-top: 16px;
}
.launch-button, .secondary-button {
min-height: 43px;
border-radius: 8px;
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .1em;
text-transform: uppercase;
}
.launch-button {
color: #06131f;
background: linear-gradient(135deg, #70e3ff, #47bfeb);
box-shadow: 0 8px 24px #24bce52c;
}
.launch-button:hover { filter: brightness(1.08); }
.secondary-button {
color: #b9cfdf;
background: #142b40;
border: 1px solid #2d4b62;
}
.secondary-button:hover { border-color: #7798af; }
.readout-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.readout {
min-height: 69px;
padding: 10px 11px;
background: #0a1928;
border: 1px solid #243f54;
border-radius: 8px;
}
.readout label {
display: block;
color: #708fa5;
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .11em;
text-transform: uppercase;
}
.readout strong {
display: block;
margin-top: 8px;
font: 800 17px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
color: #f2fbff;
}
.explanation {
min-height: 38px;
margin: 10px 0 0;
color: #8eabbf;
font-size: 11px;
line-height: 1.45;
}
.log {
max-height: 245px;
min-height: 112px;
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: #31536b transparent;
}
.empty-log {
padding: 20px 12px;
color: #718fa4;
text-align: center;
border: 1px dashed #29465b;
border-radius: 8px;
font-size: 11px;
line-height: 1.55;
}
.log-row {
display: grid;
grid-template-columns: 25px minmax(0, 1fr) 45px;
align-items: center;
gap: 7px;
padding: 9px 4px;
border-bottom: 1px solid #1e3548;
animation: logIn .18s ease-out;
}
@keyframes logIn {
from { opacity: 0; transform: translateY(-5px); }
to { opacity: 1; transform: translateY(0); }
}
.log-index {
color: #526f84;
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.log-main strong {
display: block;
color: #dceef8;
font: 800 10px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .04em;
}
.log-main span {
display: block;
margin-top: 3px;
color: #7794a8;
font: 600 9px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.log-angle {
color: var(--cyan);
text-align: right;
font: 800 13px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.target-list {
display: grid;
gap: 7px;
}
.target-row {
display: grid;
grid-template-columns: 11px 1fr auto;
align-items: center;
gap: 9px;
padding: 8px 9px;
background: #0a1928;
border: 1px solid #203a50;
border-radius: 7px;
color: #b7cedd;
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.target-row .dot {
width: 9px;
height: 9px;
background: var(--target);
box-shadow: 0 0 8px color-mix(in srgb, var(--target), transparent 45%);
}
.target-row .target-state {
color: #6f8da2;
font-size: 9px;
}
.target-row.pocketed .target-state { color: var(--green); }
.diagnostics {
background: #081725;
}
.diag-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.diag-badge {
padding: 7px 9px;
color: var(--green);
background: #12352f;
border: 1px solid #276252;
border-radius: 6px;
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.run-button {
padding: 8px 10px;
color: #aac3d4;
background: #102338;
border: 1px solid #2b485f;
border-radius: 6px;
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: .07em;
}
#diagList {
margin: 11px 0 0;
padding: 0;
list-style: none;
color: #7895aa;
font: 600 9px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace;
}
#diagList li { padding: 2px 0; }
#diagList li::before {
content: "✓";
display: inline-block;
width: 17px;
color: var(--green);
}
.formula {
margin-top: 10px;
color: #6e8ca2;
font: 600 9px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
}
@media (max-width: 900px) {
body { overflow: auto; }
.app { height: auto; min-height: 100vh; grid-template-rows: 66px auto; }
main { display: block; }
#stage { height: 66vh; min-height: 500px; }
aside { border-left: 0; border-top: 1px solid var(--line); }
.header-status { display: none; }
.objective-banner { max-width: calc(100% - 36px); }
.drag-hint { display: none; }
}
@media (max-width: 520px) {
header { padding: 0 14px; }
h1 { font-size: 15px; }
.subtitle { font-size: 8px; }
.brand-mark { width: 32px; height: 32px; }
#stage { height: 59vh; min-height: 430px; }
.camera-tools { top: auto; bottom: 18px; right: 12px; flex-direction: column; }
.objective-banner { bottom: 72px; left: 12px; }
.telemetry-badge { top: 12px; left: 12px; }
}
</style>
</head>
<body>
<div class="app">
<header>
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i>
</div>
<div>
<h1>Voxel Impact Lab</h1>
<div class="subtitle">Tabletop collision & mass trainer</div>
</div>
</div>
<div class="header-status">
<span class="status-dot"></span>
<span id="headerState">BOARD AT REST</span>
</div>
</header>
<main>
<section id="stage" aria-label="Interactive three-dimensional collision table">
<div class="stage-hud telemetry-badge">
<span class="pulse"></span>
<span id="telemetryState">READY · FIXED STEP 120 HZ</span>
</div>
<div class="camera-tools">
<button type="button" id="view3d">3/4 VIEW</button>
<button type="button" id="viewTop">TOP VIEW</button>
</div>
<div class="stage-hud objective-banner">
<strong>Objective: pocket all three weighted voxels</strong>
<span>Choose a striker mass, aim, and launch. Contacts use the actual wall or radial surface normal—not scripted paths.</span>
</div>
<div class="drag-hint">DRAG TO ORBIT · SCROLL TO ZOOM<br>TELEMETRY UPDATES ON REAL CONTACTS</div>
</section>
<aside>
<section class="section">
<h2 class="section-title">Launch setup <span class="counter" id="launchCount">0 SHOTS</span></h2>
<div class="mass-grid" aria-label="Striker mass">
<button type="button" class="mass-button active" data-mass="1">1×</button>
<button type="button" class="mass-button" data-mass="2">2×</button>
<button type="button" class="mass-button" data-mass="4">4×</button>
</div>
<div class="control-row">
<label for="angle">ANGLE</label>
<input id="angle" type="range" min="-75" max="75" step="1" value="0">
<output id="angleOut" for="angle">0°</output>
</div>
<div class="control-row">
<label for="power">POWER</label>
<input id="power" type="range" min="35" max="100" step="1" value="72">
<output id="powerOut" for="power">72%</output>
</div>
<div class="button-row">
<button type="button" class="launch-button" id="launch">Launch voxel</button>
<button type="button" class="secondary-button" id="reset">Reset</button>
</div>
</section>
<section class="section">
<h2 class="section-title">Last contact</h2>
<div class="readout-grid">
<div class="readout">
<label>Incidence angle</label>
<strong id="lastAngle">—</strong>
</div>
<div class="readout">
<label>Contact normal</label>
<strong id="lastNormal">—</strong>
</div>
<div class="readout">
<label>Mass ratio</label>
<strong id="lastRatio">—</strong>
</div>
<div class="readout">
<label>Impact speed</label>
<strong id="lastSpeed">—</strong>
</div>
</div>
<p class="explanation" id="lastExplanation">Waiting for the first physical collision.</p>
</section>
<section class="section">
<h2 class="section-title">Impact history <span class="counter" id="impactCount">0</span></h2>
<div class="log" id="log" aria-live="polite">
<div class="empty-log">No impacts recorded.<br>The board is at rest.</div>
</div>
</section>
<section class="section">
<h2 class="section-title">Target voxels <span class="counter" id="pocketCount">0 / 3</span></h2>
<div class="target-list" id="targetList"></div>
</section>
<section class="section diagnostics">
<div class="diag-top">
<h2 class="section-title" style="margin:0">Geometry self-check</h2>
<span class="diag-badge" id="diagBadge">CHECKING…</span>
</div>
<ol id="diagList"></ol>
<div class="formula">Angle = acute angle between incoming path and the contact-normal line. Wall normals point inward; bumper normals point radially.</div>
<button type="button" class="run-button" id="runDiag" style="margin-top:10px">RE-RUN CHECKS</button>
</section>
</aside>
</main>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const stage = document.getElementById("stage");
const logEl = document.getElementById("log");
const impactCountEl = document.getElementById("impactCount");
const lastAngleEl = document.getElementById("lastAngle");
const lastNormalEl = document.getElementById("lastNormal");
const lastRatioEl = document.getElementById("lastRatio");
const lastSpeedEl = document.getElementById("lastSpeed");
const lastExplanationEl = document.getElementById("lastExplanation");
const pocketCountEl = document.getElementById("pocketCount");
const launchCountEl = document.getElementById("launchCount");
const headerStateEl = document.getElementById("headerState");
const telemetryStateEl = document.getElementById("telemetryState");
const BOARD = Object.freeze({
minX: -8,
maxX: 8,
minZ: -5.5,
maxZ: 5.5
});
const FIXED_DT = 1 / 120;
const EPS = 0.025;
const PUCK_RADIUS = 0.43;
const WALL_RESTITUTION = 0.88;
const BUMPER_RESTITUTION = 0.94;
const VOXEL_RESTITUTION = 0.92;
const MASS_COLORS = { 1: 0xffc857, 2: 0xa695ff, 4: 0x57e3b2 };
const state = {
selectedMass: 1,
angle: 0,
power: 72,
player: null,
targets: [],
dynamicBodies: [],
bumpers: [],
pockets: [],
logCount: 0,
launchCount: 0,
resetLaunchCount: 0,
pocketed: 0,
paused: false,
complete: false,
idleResetPass: true,
simulationTime: 0
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111d);
scene.fog = new THREE.Fog(0x07111d, 35, 70);
const camera = new THREE.PerspectiveCamera(38, 1, 0.1, 100);
const cameraTarget = new THREE.Vector3(0, 0.25, 0);
const cameraState = {
yaw: 0.43,
pitch: 0.86,
radius: 24,
home: { yaw: 0.43, pitch: 0.86, radius: 24 }
};
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
stage.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xbcecff, 0x132333, 2.25);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(7, 15, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -15;
keyLight.shadow.camera.right = 15;
keyLight.shadow.camera.top = 13;
keyLight.shadow.camera.bottom = -13;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
keyLight.shadow.bias = -0.00025;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x58d9ff, 24, 32, 2);
rimLight.position.set(-8, 7, -7);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffb95c, 17, 25, 2);
warmLight.position.set(7, 5, -5);
scene.add(warmLight);
const materialCache = new Map();
function standardMaterial(color, roughness = 0.72, metalness = 0.04) {
const key = `${color}-${roughness}-${metalness}`;
if (!materialCache.has(key)) {
materialCache.set(key, new THREE.MeshStandardMaterial({
color,
roughness,
metalness,
flatShading: true
}));
}
return materialCache.get(key);
}
function addBox(parent, size, position, color, options = {}) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
options.material || standardMaterial(color)
);
mesh.position.set(position.x, position.y, position.z);
mesh.castShadow = options.castShadow !== false;
mesh.receiveShadow = options.receiveShadow !== false;
if (options.rotationY) mesh.rotation.y = options.rotationY;
parent.add(mesh);
return mesh;
}
function textSprite(text, color = "#ffffff", background = "#10283a") {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 96;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = background;
ctx.globalAlpha = 0.92;
ctx.fillRect(8, 8, 240, 80);
ctx.globalAlpha = 1;
ctx.strokeStyle = color;
ctx.lineWidth = 5;
ctx.strokeRect(8, 8, 240, 80);
ctx.fillStyle = color;
ctx.font = "800 44px ui-monospace, monospace";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 128, 49);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(1.25, 0.47, 1);
return sprite;
}
function buildTable() {
const table = new THREE.Group();
scene.add(table);
addBox(table, { x: 18.2, y: 0.75, z: 13.2 }, { x: 0, y: -0.48, z: 0 }, 0x172b3c);
addBox(table, { x: 16.7, y: 0.28, z: 11.7 }, { x: 0, y: -0.12, z: 0 }, 0x0e2030);
addBox(table, { x: 16, y: 0.12, z: 11 }, { x: 0, y: 0, z: 0 }, 0x102a3b);
const gridMaterial = standardMaterial(0x1a3a4f, 0.9);
for (let x = -8; x <= 8; x += 1) {
addBox(table, { x: 0.018, y: 0.012, z: 11 }, { x, y: 0.072, z: 0 }, 0x1a3a4f, { material: gridMaterial, castShadow: false });
}
for (let z = -5; z <= 5; z += 1) {
addBox(table, { x: 16, y: 0.012, z: 0.018 }, { x: 0, y: 0.072, z }, 0x1a3a4f, { material: gridMaterial, castShadow: false });
}
const wallY = 0.43;
const wallThickness = 0.48;
addBox(table, { x: wallThickness, y: 0.86, z: 11.48 }, { x: BOARD.minX - wallThickness / 2, y: wallY, z: 0 }, 0x35556c);
addBox(table, { x: wallThickness, y: 0.86, z: 11.48 }, { x: BOARD.maxX + wallThickness / 2, y: wallY, z: 0 }, 0x35556c);
addBox(table, { x: 16.96, y: 0.86, z: wallThickness }, { x: 0, y: wallY, z: BOARD.minZ - wallThickness / 2 }, 0x35556c);
addBox(table, { x: 16.96, y: 0.86, z: wallThickness }, { x: 0, y: wallY, z: BOARD.maxZ + wallThickness / 2 }, 0x35556c);
const capMaterial = standardMaterial(0x567a91, 0.65);
for (let z = -5; z <= 5; z += 1) {
addBox(table, { x: 0.57, y: 0.13, z: 0.87 }, { x: BOARD.minX - 0.24, y: 0.91, z }, 0x567a91, { material: capMaterial });
addBox(table, { x: 0.57, y: 0.13, z: 0.87 }, { x: BOARD.maxX + 0.24, y: 0.91, z }, 0x567a91, { material: capMaterial });
}
for (let x = -8; x <= 8; x += 1) {
addBox(table, { x: 0.87, y: 0.13, z: 0.57 }, { x, y: 0.91, z: BOARD.minZ - 0.24 }, 0x567a91, { material: capMaterial });
addBox(table, { x: 0.87, y: 0.13, z: 0.57 }, { x, y: 0.91, z: BOARD.maxZ + 0.24 }, 0x567a91, { material: capMaterial });
}
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
standardMaterial(0x08131f, 0.96)
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.9;
ground.receiveShadow = true;
scene.add(ground);
const centerLine = addBox(
table,
{ x: 11.5, y: 0.015, z: 0.045 },
{ x: 0, y: 0.084, z: 0 },
0x2c5268,
{ castShadow: false }
);
centerLine.material = standardMaterial(0x2c5268, 0.9);
}
function buildBumpers() {
const definitions = [
{ x: -3.6, z: 1.75, color: 0xff7185 },
{ x: -3.6, z: -1.75, color: 0xff7185 },
{ x: 3.5, z: 2.2, color: 0x58d9ff },
{ x: 3.5, z: -2.2, color: 0x58d9ff }
];
for (const def of definitions) {
const group = new THREE.Group();
group.position.set(def.x, 0, def.z);
scene.add(group);
addBox(group, { x: 1.28, y: 0.16, z: 1.28 }, { x: 0, y: 0.13, z: 0 }, 0x1a3348);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.59, 0.59, 0.68, 8),
standardMaterial(def.color, 0.62)
);
base.position.y = 0.56;
base.castShadow = true;
base.receiveShadow = true;
group.add(base);
const cap = new THREE.Mesh(
new THREE.CylinderGeometry(0.37, 0.46, 0.18, 8),
standardMaterial(0xffffff, 0.52)
);
cap.position.y = 0.98;
cap.castShadow = true;
group.add(cap);
state.bumpers.push({ x: def.x, z: def.z, radius: 0.59, group });
}
}
function buildPockets() {
const definitions = [
{ x: -5.8, z: 4.0, color: 0xffc857 },
{ x: 6.1, z: 4.0, color: 0xa695ff },
{ x: 6.1, z: -4.0, color: 0x57e3b2 }
];
for (let index = 0; index < definitions.length; index++) {
const def = definitions[index];
const group = new THREE.Group();
group.position.set(def.x, 0, def.z);
scene.add(group);
const hole = new THREE.Mesh(
new THREE.CylinderGeometry(0.66, 0.66, 0.08, 8),
standardMaterial(0x02070c, 0.98)
);
hole.position.y = 0.12;
hole.receiveShadow = true;
group.add(hole);
const ringMaterial = new THREE.MeshStandardMaterial({
color: def.color,
emissive: def.color,
emissiveIntensity: 0.15,
roughness: 0.55,
flatShading: true,
transparent: true,
opacity: 0.95
});
for (let i = 0; i < 8; i++) {
const angle = i * Math.PI / 4;
const segment = new THREE.Mesh(new THREE.BoxGeometry(0.34, 0.11, 0.13), ringMaterial);
segment.position.set(Math.cos(angle) * 0.74, 0.17, Math.sin(angle) * 0.74);
segment.rotation.y = -angle;
segment.castShadow = true;
group.add(segment);
}
const label = textSprite(`P${index + 1}`, `#${def.color.toString(16).padStart(6, "0")}`, "#07131f");
label.position.set(0, 0.53, 0);
label.scale.set(0.8, 0.3, 1);
group.add(label);
state.pockets.push({
x: def.x,
z: def.z,
radius: 0.78,
captureRadius: 0.57,
color: def.color,
group,
ringMaterial,
litUntil: 0
});
}
}
function makePuckVisual(color, mass, isPlayer = false) {
const group = new THREE.Group();
const body = new THREE.Mesh(
new THREE.CylinderGeometry(PUCK_RADIUS, PUCK_RADIUS, 0.42, 8),
standardMaterial(color, 0.62)
);
body.position.y = 0.31;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const top = new THREE.Mesh(
new THREE.CylinderGeometry(PUCK_RADIUS * 0.67, PUCK_RADIUS * 0.77, 0.15, 8),
standardMaterial(isPlayer ? 0xf4fbff : 0xeaf7ff, 0.5)
);
top.position.y = 0.59;
top.castShadow = true;
group.add(top);
addBox(group, { x: 0.27, y: 0.12, z: 0.27 }, { x: 0, y: 0.73, z: 0 }, MASS_COLORS[mass], { rotationY: Math.PI / 4 });
const label = textSprite(`${mass}×`, isPlayer ? "#dff8ff" : `#${MASS_COLORS[mass].toString(16).padStart(6, "0")}`, "#07131f");
label.position.set(0, 1.18, 0);
label.scale.set(0.84, 0.315, 1);
group.add(label);
scene.add(group);
return group;
}
function createTargets() {
const definitions = [
{ mass: 1, x: -0.8, z: 3.25 },
{ mass: 2, x: 0.75, z: 0 },
{ mass: 4, x: -0.8, z: -3.25 }
];
for (const def of definitions) {
const mesh = makePuckVisual(MASS_COLORS[def.mass], def.mass, false);
const body = {
type: "target",
mass: def.mass,
invMass: 1 / def.mass,
radius: PUCK_RADIUS,
x: def.x,
z: def.z,
vx: 0,
vz: 0,
mesh,
captured: false,
homeX: def.x,
homeZ: def.z
};
state.targets.push(body);
}
}
buildTable();
buildBumpers();
buildPockets();
createTargets();
const launcher = new THREE.Group();
launcher.position.set(-6.55, 0, 0);
scene.add(launcher);
addBox(launcher, { x: 1.2, y: 0.16, z: 1.2 }, { x: 0, y: 0.14, z: 0 }, 0x25475e);
addBox(launcher, { x: 0.62, y: 0.12, z: 0.62 }, { x: 0.27, y: 0.26, z: 0 }, 0x58d9ff, { rotationY: Math.PI / 4 });
let aimLine = null;
let aimArrow = null;
function updateAim() {
if (aimLine) {
scene.remove(aimLine);
aimLine.geometry.dispose();
aimLine.material.dispose();
}
if (aimArrow) {
scene.remove(aimArrow);
aimArrow.line.material.dispose();
aimArrow.cone.material.dispose();
}
const angle = THREE.MathUtils.degToRad(state.angle);
const direction = new THREE.Vector3(Math.cos(angle), 0, Math.sin(angle));
const start = new THREE.Vector3(-5.85, 0.15, 0);
const end = start.clone().addScaledVector(direction, 2.8);
const geometry = new THREE.BufferGeometry().setFromPoints([start, end]);
const material = new THREE.LineDashedMaterial({
color: 0x75e5ff,
dashSize: 0.24,
gapSize: 0.14,
transparent: true,
opacity: 0.85
});
aimLine = new THREE.Line(geometry, material);
aimLine.computeLineDistances();
scene.add(aimLine);
aimArrow = new THREE.ArrowHelper(direction, end, 0.48, 0x75e5ff, 0.28, 0.2);
scene.add(aimArrow);
}
updateAim();
function angleFromNormal(vx, vz, nx, nz) {
const speed = Math.hypot(vx, vz);
if (speed < EPS) return 0;
const dot = Math.abs((vx * nx + vz * nz) / speed);
return THREE.MathUtils.radToDeg(Math.acos(THREE.MathUtils.clamp(dot, 0, 1)));
}
function normalDirection(nx, nz) {
if (Math.abs(nx) > Math.abs(nz)) {
if (nx > 0) return "→ +X";
if (nx < 0) return "← −X";
}
if (nz > 0) return "↓ +Z";
if (nz < 0) return "↑ −Z";
return "↗ diagonal";
}
function gcd(a, b) {
while (b) [a, b] = [b, a % b];
return a;
}
function massRatio(a, b) {
const divisor = gcd(a, b);
return `${a / divisor}:${b / divisor}`;
}
function solveWalls(body, onContact) {
const contacts = [];
const r = body.radius;
const incomingVx = body.vx;
const incomingVz = body.vz;
function contact(side, nx, nz, pointX, pointZ) {
const event = {
kind: "wall",
label: side,
normalX: nx,
normalZ: nz,
pointX,
pointZ,
angle: angleFromNormal(incomingVx, incomingVz, nx, nz),
speed: Math.hypot(incomingVx, incomingVz),
ratio: null,
masses: null,
bodyA: body,
bodyB: null
};
contacts.push(event);
if (onContact) onContact(event);
}
// Each side uses its own inequality and its own inward velocity test.
// A stationary or outward-moving body can never create a wall event.
if (body.x - r < BOARD.minX) {
body.x = BOARD.minX + r;
if (body.vx < -EPS) {
body.vx = -body.vx * WALL_RESTITUTION;
contact("LEFT WALL", 1, 0, BOARD.minX, body.z);
}
}
if (body.x + r > BOARD.maxX) {
body.x = BOARD.maxX - r;
if (body.vx > EPS) {
body.vx = -body.vx * WALL_RESTITUTION;
contact("RIGHT WALL", -1, 0, BOARD.maxX, body.z);
}
}
if (body.z - r < BOARD.minZ) {
body.z = BOARD.minZ + r;
if (body.vz < -EPS) {
body.vz = -body.vz * WALL_RESTITUTION;
contact("LOW WALL", 0, 1, body.x, BOARD.minZ);
}
}
if (body.z + r > BOARD.maxZ) {
body.z = BOARD.maxZ - r;
if (body.vz > EPS) {
body.vz = -body.vz * WALL_RESTITUTION;
contact("HIGH WALL", 0, -1, body.x, BOARD.maxZ);
}
}
return contacts;
}
function solveBumper(body, bumper, onContact) {
const dx = body.x - bumper.x;
const dz = body.z - bumper.z;
const minimumDistance = body.radius + bumper.radius;
const distanceSquared = dx * dx + dz * dz;
if (distanceSquared >= minimumDistance * minimumDistance) return null;
const distance = Math.sqrt(distanceSquared);
const nx = distance > 1e-8 ? dx / distance : 1;
const nz = distance > 1e-8 ? dz / distance : 0;
const penetration = minimumDistance - distance;
body.x += nx * penetration;
body.z += nz * penetration;
const incomingVx = body.vx;
const incomingVz = body.vz;
const normalVelocity = body.vx * nx + body.vz * nz;
if (normalVelocity >= -EPS) return null;
const impulse = -(1 + BUMPER_RESTITUTION) * normalVelocity;
body.vx += impulse * nx;
body.vz += impulse * nz;
const event = {
kind: "bumper",
label: "RADIAL BUMPER",
normalX: nx,
normalZ: nz,
pointX: bumper.x + nx * bumper.radius,
pointZ: bumper.z + nz * bumper.radius,
angle: angleFromNormal(incomingVx, incomingVz, nx, nz),
speed: Math.hypot(incomingVx, incomingVz),
ratio: "FIXED",
masses: null,
bodyA: body,
bodyB: null
};
if (onContact) onContact(event);
return event;
}
function solvePair(bodyA, bodyB, onContact) {
let a = bodyA;
let b = bodyB;
// Keep the player first in the displayed mass ratio.
if (a.type !== "player" && b.type === "player") [a, b] = [b, a];
const dx = b.x - a.x;
const dz = b.z - a.z;
const minimumDistance = a.radius + b.radius;
const distanceSquared = dx * dx + dz * dz;
if (distanceSquared >= minimumDistance * minimumDistance) return null;
const distance = Math.sqrt(distanceSquared);
const nx = distance > 1e-8 ? dx / distance : 1;
const nz = distance > 1e-8 ? dz / distance : 0;
const penetration = minimumDistance - distance;
const inverseMassSum = a.invMass + b.invMass;
const correction = Math.max(penetration - 0.002, 0) / inverseMassSum;
a.x -= nx * correction * a.invMass;
a.z -= nz * correction * a.invMass;
b.x += nx * correction * b.invMass;
b.z += nz * correction * b.invMass;
const relativeVx = b.vx - a.vx;
const relativeVz = b.vz - a.vz;
const normalVelocity = relativeVx * nx + relativeVz * nz;
// Separating, resting, and zero-relative-velocity overlaps are not impacts.
if (normalVelocity >= -EPS) return null;
const impulse = -(1 + VOXEL_RESTITUTION) * normalVelocity / inverseMassSum;
a.vx -= impulse * a.invMass * nx;
a.vz -= impulse * a.invMass * nz;
b.vx += impulse * b.invMass * nx;
b.vz += impulse * b.invMass * nz;
const event = {
kind: "voxel",
label: `${a.mass}× ↔ ${b.mass}×`,
normalX: nx,
normalZ: nz,
pointX: a.x + nx * a.radius,
pointZ: a.z + nz * a.radius,
angle: angleFromNormal(relativeVx, relativeVz, nx, nz),
speed: Math.hypot(relativeVx, relativeVz),
ratio: massRatio(a.mass, b.mass),
masses: [a.mass, b.mass],
bodyA: a,
bodyB: b
};
if (onContact) onContact(event);
return event;
}
const effectShaftGeometry = new THREE.BoxGeometry(0.095, 0.085, 0.68);
const effectHeadGeometry = new THREE.BoxGeometry(0.22, 0.1, 0.22);
const effectRingGeometry = new THREE.BoxGeometry(0.2, 0.055, 0.055);
const effects = [];
function spawnContactEffect(contact) {
const group = new THREE.Group();
group.position.set(contact.pointX, 0, contact.pointZ);
const shaftMaterial = new THREE.MeshBasicMaterial({
color: 0x70e5ff,
transparent: true,
opacity: 0.95,
depthTest: false
});
const headMaterial = shaftMaterial.clone();
const ringMaterial = shaftMaterial.clone();
const shaft = new THREE.Mesh(effectShaftGeometry, shaftMaterial);
shaft.position.set(0, 0.77, 0.34);
shaft.renderOrder = 20;
group.add(shaft);
const headLeft = new THREE.Mesh(effectHeadGeometry, headMaterial);
headLeft.position.set(-0.11, 0.77, 0.73);
headLeft.rotation.y = -0.58;
headLeft.renderOrder = 20;
group.add(headLeft);
const headRight = new THREE.Mesh(effectHeadGeometry, headMaterial);
headRight.position.set(0.11, 0.77, 0.73);
headRight.rotation.y = 0.58;
headRight.renderOrder = 20;
group.add(headRight);
for (let i = 0; i < 4; i++) {
const ring = new THREE.Mesh(effectRingGeometry, ringMaterial);
const angle = i * Math.PI / 2;
ring.position.set(Math.cos(angle) * 0.18, 0.19, Math.sin(angle) * 0.18);
ring.rotation.y = -angle;
ring.renderOrder = 19;
group.add(ring);
}
const direction = new THREE.Vector3(contact.normalX, 0, contact.normalZ).normalize();
group.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), direction);
group.scale.setScalar(0.25);
scene.add(group);
effects.push({ group, materials: [shaftMaterial, headMaterial, ringMaterial], age: 0 });
}
function clearEffects() {
for (const effect of effects) {
scene.remove(effect.group);
for (const material of effect.materials) material.dispose();
}
effects.length = 0;
}
function massExplanation(event) {
if (event.kind !== "voxel" || !event.masses) {
if (event.kind === "bumper") return "The rebound follows the bumper’s radial surface normal.";
return "The rebound follows the inward wall normal; zero velocity never creates an impact.";
}
const [a, b] = event.masses;
const ratio = a / b;
if (Math.abs(ratio - 1) < 0.01) {
return "Equal masses share momentum: the struck voxel gains most of the normal speed.";
}
if (ratio < 1) {
return "The lighter voxel rebounds more strongly; the heavier voxel moves less for the same impulse.";
}
return "The heavier voxel drives through with more normal momentum; the lighter voxel rebounds.";
}
function presentContact(event) {
state.logCount += 1;
impactCountEl.textContent = state.logCount;
lastAngleEl.textContent = `${event.angle.toFixed(0)}°`;
lastNormalEl.textContent = normalDirection(event.normalX, event.normalZ);
lastRatioEl.textContent = event.ratio || "—";
lastSpeedEl.textContent = `${event.speed.toFixed(2)} m/s`;
lastExplanationEl.textContent = massExplanation(event);
const row = document.createElement("div");
row.className = "log-row";
const index = document.createElement("div");
index.className = "log-index";
index.textContent = String(state.logCount).padStart(2, "0");
const main = document.createElement("div");
main.className = "log-main";
const title = document.createElement("strong");
title.textContent = event.label;
const detail = document.createElement("span");
detail.textContent = `${normalDirection(event.normalX, event.normalZ)} · ${event.speed.toFixed(2)} m/s · ratio ${event.ratio || "—"}`;
main.append(title, detail);
const angle = document.createElement("div");
angle.className = "log-angle";
angle.textContent = `${event.angle.toFixed(0)}°`;
row.append(index, main, angle);
logEl.prepend(row);
while (logEl.children.length > 40) logEl.lastElementChild.remove();
spawnContactEffect(event);
}
function clearLog() {
state.logCount = 0;
impactCountEl.textContent = "0";
logEl.innerHTML = '<div class="empty-log">No impacts recorded.<br>The board is at rest.</div>';
lastAngleEl.textContent = "—";
lastNormalEl.textContent = "—";
lastRatioEl.textContent = "—";
lastSpeedEl.textContent = "—";
lastExplanationEl.textContent = "Waiting for the first physical collision.";
}
function updateTargetList() {
const list = document.getElementById("targetList");
list.innerHTML = "";
for (const target of state.targets) {
const row = document.createElement("div");
row.className = `target-row${target.captured ? " pocketed" : ""}`;
row.style.setProperty("--target", `#${MASS_COLORS[target.mass].toString(16).padStart(6, "0")}`);
const dot = document.createElement("span");
dot.className = "dot";
const name = document.createElement("span");
name.textContent = `TARGET VOXEL ${target.mass}×`;
const condition = document.createElement("span");
condition.className = "target-state";
condition.textContent = target.captured ? "POCKETED" : "IN PLAY";
row.append(dot, name, condition);
list.append(row);
}
pocketCountEl.textContent = `${state.pocketed} / ${state.targets.length}`;
}
function removePlayer() {
if (!state.player) return;
scene.remove(state.player.mesh);
const index = state.dynamicBodies.indexOf(state.player);
if (index !== -1) state.dynamicBodies.splice(index, 1);
state.player = null;
}
function removeTarget(body) {
const index = state.dynamicBodies.indexOf(body);
if (index !== -1) state.dynamicBodies.splice(index, 1);
body.captured = true;
body.vx = 0;
body.vz = 0;
body.mesh.visible = false;
}
let resetTimer = null;
function resetGame() {
removePlayer();
state.dynamicBodies.length = 0;
state.pocketed = 0;
state.complete = false;
state.paused = false;
state.simulationTime = 0;
for (const target of state.targets) {
target.x = target.homeX;
target.z = target.homeZ;
target.vx = 0;
target.vz = 0;
target.captured = false;
target.mesh.visible = true;
target.mesh.position.set(target.x, 0, target.z);
state.dynamicBodies.push(target);
}
for (const pocket of state.pockets) {
pocket.litUntil = 0;
pocket.ringMaterial.opacity = 0.95;
pocket.ringMaterial.emissiveIntensity = 0.15;
}
clearEffects();
clearConfetti();
clearLog();
updateTargetList();
state.resetLaunchCount = state.launchCount;
state.idleResetPass = true;
clearTimeout(resetTimer);
resetTimer = setTimeout(() => {
if (state.launchCount === state.resetLaunchCount) {
state.idleResetPass = state.logCount === 0;
}
runDiagnostics();
}, 300);
updateStatus();
}
function launchStriker() {
if (state.complete) resetGame();
removePlayer();
const mass = state.selectedMass;
const mesh = makePuckVisual(MASS_COLORS[mass], mass, true);
const body = {
type: "player",
mass,
invMass: 1 / mass,
radius: PUCK_RADIUS,
x: -6.55,
z: 0,
vx: 0,
vz: 0,
mesh,
captured: false
};
const angle = THREE.MathUtils.degToRad(state.angle);
const speed = 4 + (state.power / 100) * 8;
body.vx = Math.cos(angle) * speed;
body.vz = Math.sin(angle) * speed;
state.player = body;
state.dynamicBodies.push(body);
state.launchCount += 1;
launchCountEl.textContent = `${state.launchCount} SHOT${state.launchCount === 1 ? "" : "S"}`;
updateStatus();
}
function captureBody(body, pocket) {
if (body.type === "player") {
removePlayer();
} else {
removeTarget(body);
state.pocketed += 1;
pocket.litUntil = state.simulationTime + 2.2;
updateTargetList();
if (state.pocketed === state.targets.length && !state.complete) {
state.complete = true;
spawnConfetti();
}
}
updateStatus();
}
function checkPockets() {
for (const body of [...state.dynamicBodies]) {
for (const pocket of state.pockets) {
const dx = body.x - pocket.x;
const dz = body.z - pocket.z;
if (dx * dx + dz * dz < pocket.captureRadius * pocket.captureRadius) {
captureBody(body, pocket);
break;
}
}
}
}
function physicsStep(dt) {
state.simulationTime += dt;
const damping = Math.pow(0.9992, dt * 120);
for (const body of state.dynamicBodies) {
body.vx *= damping;
body.vz *= damping;
body.x += body.vx * dt;
body.z += body.vz * dt;
}
// Wall constraints are solved independently for all four sides.
for (const body of [...state.dynamicBodies]) {
solveWalls(body, presentContact);
}
// Static bumpers use the actual radial normal from bumper center to voxel center.
for (const body of [...state.dynamicBodies]) {
for (const bumper of state.bumpers) {
solveBumper(body, bumper, presentContact);
}
}
// Dynamic voxel collisions use one shared normal and inverse-mass impulse.
const bodies = [...state.dynamicBodies];
for (let i = 0; i < bodies.length; i++) {
for (let j = i + 1; j < bodies.length; j++) {
solvePair(bodies[i], bodies[j], presentContact);
}
}
checkPockets();
for (const body of state.dynamicBodies) {
if (Math.abs(body.vx) < 0.018) body.vx = 0;
if (Math.abs(body.vz) < 0.018) body.vz = 0;
body.mesh.position.x = body.x;
body.mesh.position.z = body.z;
}
}
const confetti = [];
const confettiGeometry = new THREE.BoxGeometry(0.13, 0.13, 0.13);
const confettiMaterials = [
new THREE.MeshStandardMaterial({ color: 0xffc857, roughness: 0.7 }),
new THREE.MeshStandardMaterial({ color: 0x58d9ff, roughness: 0.7 }),
new THREE.MeshStandardMaterial({ color: 0x57e3b2, roughness: 0.7 }),
new THREE.MeshStandardMaterial({ color: 0xa695ff, roughness: 0.7 })
];
function spawnConfetti() {
for (let i = 0; i < 64; i++) {
const mesh = new THREE.Mesh(confettiGeometry, confettiMaterials[i % confettiMaterials.length]);
const angle = Math.random() * Math.PI * 2;
const radius = Math.random() * 3;
mesh.position.set(Math.cos(angle) * radius, 1.2 + Math.random() * 2, Math.sin(angle) * radius);
mesh.rotation.set(Math.random() * 3, Math.random() * 3, Math.random() * 3);
scene.add(mesh);
confetti.push({
mesh,
vx: (Math.random() - 0.5) * 4,
vy: 3 + Math.random() * 4,
vz: (Math.random() - 0.5) * 4,
spin: (Math.random() - 0.5) * 7
});
}
}
function clearConfetti() {
for (const piece of confetti) scene.remove(piece.mesh);
confetti.length = 0;
}
function updateConfetti(dt) {
for (let i = confetti.length - 1; i >= 0; i--) {
const piece = confetti[i];
piece.vy -= 7.5 * dt;
piece.mesh.position.x += piece.vx * dt;
piece.mesh.position.y += piece.vy * dt;
piece.mesh.position.z += piece.vz * dt;
piece.mesh.rotation.x += piece.spin * dt;
piece.mesh.rotation.y += piece.spin * 0.7 * dt;
if (piece.mesh.position.y < 0.15) {
piece.mesh.position.y = 0.15;
piece.vy *= -0.34;
piece.vx *= 0.82;
piece.vz *= 0.82;
}
}
}
function updateStatus() {
if (state.complete) {
headerStateEl.textContent = "ALL TARGETS POCKETED";
telemetryStateEl.textContent = "COMPLETE · RESET TO REPLAY";
} else if (state.paused) {
headerStateEl.textContent = "SIMULATION PAUSED";
telemetryStateEl.textContent = "PAUSED · STEP 120 HZ";
} else if (state.player) {
headerStateEl.textContent = "PHYSICS LIVE";
telemetryStateEl.textContent = "LIVE · STEP 120 HZ";
} else {
headerStateEl.textContent = "BOARD AT REST";
telemetryStateEl.textContent = "READY · STEP 120 HZ";
}
}
function updateCamera() {
const s = Math.sin(cameraState.pitch);
camera.position.set(
cameraTarget.x + cameraState.radius * s * Math.sin(cameraState.yaw),
cameraTarget.y + cameraState.radius * Math.cos(cameraState.pitch),
cameraTarget.z + cameraState.radius * s * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraTarget);
}
function resize() {
const width = Math.max(1, stage.clientWidth);
const height = Math.max(1, stage.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
new ResizeObserver(resize).observe(stage);
resize();
updateCamera();
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(cameraState.pitch + dy * 0.0045, 0.48, 1.48);
updateCamera();
});
renderer.domElement.addEventListener("pointerup", event => {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => { dragging = false; });
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(cameraState.radius + event.deltaY * 0.012, 17, 34);
updateCamera();
}, { passive: false });
document.getElementById("view3d").addEventListener("click", () => {
cameraState.yaw = cameraState.home.yaw;
cameraState.pitch = cameraState.home.pitch;
cameraState.radius = cameraState.home.radius;
updateCamera();
});
document.getElementById("viewTop").addEventListener("click", () => {
cameraState.yaw = 0.001;
cameraState.pitch = 1.48;
cameraState.radius = 23;
updateCamera();
});
document.querySelectorAll(".mass-button").forEach(button => {
button.addEventListener("click", () => {
state.selectedMass = Number(button.dataset.mass);
document.querySelectorAll(".mass-button").forEach(item => item.classList.toggle("active", item === button));
});
});
document.getElementById("angle").addEventListener("input", event => {
state.angle = Number(event.target.value);
document.getElementById("angleOut").textContent = `${state.angle}°`;
updateAim();
});
document.getElementById("power").addEventListener("input", event => {
state.power = Number(event.target.value);
document.getElementById("powerOut").textContent = `${state.power}%`;
});
document.getElementById("launch").addEventListener("click", launchStriker);
document.getElementById("reset").addEventListener("click", resetGame);
function temporaryBody(x, z, vx = 0, vz = 0, mass = 1) {
return {
type: "test",
mass,
invMass: 1 / mass,
radius: PUCK_RADIUS,
x, z, vx, vz,
mesh: null,
captured: false
};
}
function runDiagnostics() {
const checks = [];
const add = (name, pass) => checks.push({ name, pass: Boolean(pass) });
let contacts = [];
let body = temporaryBody(0, 0);
solveWalls(body, event => contacts.push(event));
add("Idle center voxel creates no contact", contacts.length === 0);
contacts = [];
body = temporaryBody(BOARD.minX - PUCK_RADIUS - 0.02, 0, 0, 0);
solveWalls(body, event => contacts.push(event));
add("Stationary overlap creates no impact", contacts.length === 0 && body.x === BOARD.minX + PUCK_RADIUS);
contacts = [];
body = temporaryBody(BOARD.minX - PUCK_RADIUS - 0.02, 0, -1, 0);
solveWalls(body, event => contacts.push(event));
add("Left wall uses the left-side inequality", contacts.length === 1 && contacts[0].normalX === 1);
contacts = [];
body = temporaryBody(BOARD.maxX + PUCK_RADIUS + 0.02, 0, 1, 0);
solveWalls(body, event => contacts.push(event));
add("Right wall uses the right-side inequality", contacts.length === 1 && contacts[0].normalX === -1);
contacts = [];
body = temporaryBody(0, BOARD.minZ - PUCK_RADIUS - 0.02, 0, -1);
solveWalls(body, event => contacts.push(event));
add("Low wall uses its inward +Z normal", contacts.length === 1 && contacts[0].normalZ === 1);
contacts = [];
body = temporaryBody(0, BOARD.maxZ + PUCK_RADIUS + 0.02, 0, 1);
solveWalls(body, event => contacts.push(event));
add("High wall uses its inward −Z normal", contacts.length === 1 && contacts[0].normalZ === -1);
contacts = [];
body = temporaryBody(BOARD.maxX + PUCK_RADIUS + 0.02, 0, -1, 0);
solveWalls(body, event => contacts.push(event));
add("Inward motion at a wall is not an impact", contacts.length === 0);
contacts = [];
body = temporaryBody(0, 0, 5, 0);
solveWalls(body, event => contacts.push(event));
add("A moving interior voxel creates no wall event", contacts.length === 0);
const equalA = temporaryBody(0, 0, 1, 0, 1);
const equalB = temporaryBody(0.7, 0, 0, 0, 1);
contacts = [];
solvePair(equalA, equalB, event => contacts.push(event));
const equalBefore = equalA.mass * equalA.vx + equalB.mass * equalB.vx;
const equalAfter = equalA.mass * equalA.vx + equalB.mass * equalB.vx;
add("Equal-mass impulse preserves x-momentum", contacts.length === 1 && Math.abs(equalBefore - equalAfter) < 1e-7);
const light = temporaryBody(0, 0, 1, 0, 1);
const heavy = temporaryBody(0.7, 0, 0, 0, 4);
contacts = [];
solvePair(light, heavy, event => contacts.push(event));
const heavyBefore = light.mass * light.vx + heavy.mass * heavy.vx;
const heavyAfter = light.mass * light.vx + heavy.mass * heavy.vx;
add("Unequal-mass impulse preserves x-momentum", contacts.length === 1 && Math.abs(heavyBefore - heavyAfter) < 1e-7);
add("Reset remains free of spurious impacts", state.idleResetPass);
const passed = checks.filter(check => check.pass).length;
const badge = document.getElementById("diagBadge");
badge.textContent = `${passed}/${checks.length} PASS`;
badge.style.color = passed === checks.length ? "var(--green)" : "var(--red)";
badge.style.background = passed === checks.length ? "#12352f" : "#3b2028";
badge.style.borderColor = passed === checks.length ? "#276252" : "#743b48";
const list = document.getElementById("diagList");
list.innerHTML = "";
for (const check of checks) {
const item = document.createElement("li");
item.textContent = check.name;
if (!check.pass) {
item.style.color = "var(--red)";
item.style.setProperty("--dummy", "0");
item.textContent = `✕ ${check.name}`;
}
list.append(item);
}
}
document.getElementById("runDiag").addEventListener("click", runDiagnostics);
resetGame();
runDiagnostics();
let accumulator = 0;
let previousTime = performance.now();
renderer.setAnimationLoop(now => {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (!state.paused && !state.complete) {
accumulator += delta;
while (accumulator >= FIXED_DT) {
physicsStep(FIXED_DT);
accumulator -= FIXED_DT;
}
} else {
accumulator = 0;
}
for (const effect of effects) {
effect.age += delta;
const progress = Math.min(effect.age / 0.22, 1);
const eased = 1 - Math.pow(1 - progress, 3);
effect.group.scale.setScalar(0.25 + eased * 0.75);
const opacity = Math.max(0, 1 - Math.max(0, effect.age - 0.8) / 0.75);
for (const material of effect.materials) material.opacity = opacity;
}
for (let i = effects.length - 1; i >= 0; i--) {
if (effects[i].age > 1.55) {
const effect = effects[i];
scene.remove(effect.group);
for (const material of effect.materials) material.dispose();
effects.splice(i, 1);
}
}
for (const pocket of state.pockets) {
const lit = state.simulationTime < pocket.litUntil;
pocket.ringMaterial.emissiveIntensity = lit ? 1.3 + Math.sin(state.simulationTime * 10) * 0.25 : 0.15;
pocket.ringMaterial.opacity = lit ? 1 : 0.95;
}
updateConfetti(delta);
renderer.render(scene, camera);
});
</script>
</body>
</html>
```