Prompt specification
Build or customize the Three.js 3D scene "Reverse Spin Reverse Deflection Experiment" 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: Reverse Spin Reverse Deflection Experiment
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/reverse-spin-reverse-deflection-experiment-x3660
Scene Description Prompt:
Reverse a voxel ball's spin under identical launch conditions and compare trajectories in a stated simplified model. Three.js from cdnjs, one HTML file.
Working Three.js Starter (reverse-spin-reverse-deflection-experiment-x3660):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Spin Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #050b12;
--panel: rgba(9, 18, 28, 0.82);
--border: rgba(150, 200, 230, 0.16);
--text: #eaf6ff;
--muted: #8ca4b6;
--cyan: #54e2ff;
--pink: #ff61c7;
--green: #91f6bf;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 68% 30%, #10263a 0, transparent 38%),
radial-gradient(circle at 20% 85%, #171329 0, transparent 34%),
var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button, input, select { font: inherit; }
#app {
position: relative;
width: 100%;
height: 100%;
isolation: isolate;
}
#app > canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
.glass {
background: var(--panel);
border: 1px solid var(--border);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(18px) saturate(125%);
-webkit-backdrop-filter: blur(18px) saturate(125%);
}
.panel {
position: absolute;
z-index: 5;
top: 18px;
left: 18px;
width: 338px;
max-height: calc(100vh - 36px);
padding: 18px;
border-radius: 18px;
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: #294358 transparent;
}
.eyebrow {
margin-bottom: 7px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 24px;
line-height: 1.05;
letter-spacing: -0.04em;
}
.intro {
margin: 10px 0 16px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.divider {
height: 1px;
margin: 15px 0;
background: linear-gradient(90deg, var(--border), transparent);
}
.legend {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.legend-card {
padding: 10px;
border: 1px solid var(--border);
border-radius: 11px;
background: rgba(255, 255, 255, 0.025);
}
.legend-title {
display: flex;
align-items: center;
gap: 7px;
font-size: 12px;
font-weight: 750;
}
.dot {
width: 9px;
height: 9px;
border-radius: 50%;
box-shadow: 0 0 12px currentColor;
}
.dot.a { color: var(--cyan); background: var(--cyan); }
.dot.b { color: var(--pink); background: var(--pink); }
.legend-sub {
margin-top: 5px;
color: var(--muted);
font-size: 10px;
}
.control {
margin-top: 14px;
}
.control label {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 7px;
color: #c9d9e6;
font-size: 11px;
font-weight: 650;
}
.control output {
color: var(--text);
font-variant-numeric: tabular-nums;
font-size: 11px;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0;
border-radius: 99px;
outline: none;
background: #203242;
accent-color: var(--cyan);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 14px;
height: 14px;
border: 2px solid #07121c;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 13px rgba(84, 226, 255, 0.6);
appearance: none;
}
input[type="range"]::-moz-range-thumb {
width: 12px;
height: 12px;
border: 2px solid #07121c;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 13px rgba(84, 226, 255, 0.6);
}
.row {
display: flex;
align-items: center;
gap: 9px;
}
.row-between {
justify-content: space-between;
}
select {
min-width: 92px;
padding: 7px 9px;
border: 1px solid var(--border);
border-radius: 8px;
outline: none;
color: var(--text);
background: #0d1b28;
font-size: 11px;
}
.check {
display: flex;
align-items: center;
gap: 7px;
color: var(--muted);
font-size: 11px;
cursor: pointer;
}
.check input {
accent-color: var(--cyan);
}
button {
min-height: 39px;
padding: 0 14px;
border: 1px solid var(--border);
border-radius: 10px;
color: var(--text);
background: rgba(255, 255, 255, 0.055);
font-size: 12px;
font-weight: 750;
cursor: pointer;
transition: transform 120ms ease, border-color 120ms ease,
background 120ms ease;
}
button:hover {
transform: translateY(-1px);
border-color: rgba(150, 220, 255, 0.42);
background: rgba(255, 255, 255, 0.09);
}
button:active { transform: translateY(0); }
button.primary {
flex: 1;
color: #03131c;
border-color: transparent;
background: linear-gradient(135deg, #73eaff, #51cfff);
box-shadow: 0 8px 24px rgba(60, 206, 255, 0.19);
}
.buttons {
display: flex;
gap: 8px;
margin-top: 17px;
}
.status {
position: absolute;
z-index: 4;
top: 18px;
left: 50%;
transform: translateX(-50%);
padding: 8px 12px;
border: 1px solid var(--border);
border-radius: 999px;
color: var(--muted);
background: rgba(7, 15, 23, 0.7);
backdrop-filter: blur(12px);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
pointer-events: none;
}
.status.flying {
color: var(--cyan);
border-color: rgba(84, 226, 255, 0.3);
}
.status.landed {
color: var(--green);
border-color: rgba(145, 246, 191, 0.3);
}
.metrics {
position: absolute;
z-index: 5;
top: 18px;
right: 18px;
width: 270px;
padding: 16px;
border-radius: 16px;
}
.metric-title {
margin-bottom: 12px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.metric {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 14px;
padding: 8px 0;
border-top: 1px solid rgba(150, 200, 230, 0.1);
}
.metric:first-of-type { border-top: 0; }
.metric span {
color: var(--muted);
font-size: 11px;
}
.metric strong {
font-size: 16px;
font-variant-numeric: tabular-nums;
}
.metric-note {
margin-top: 8px;
color: #7790a3;
font-size: 10px;
line-height: 1.45;
}
.model {
position: absolute;
z-index: 5;
right: 18px;
bottom: 18px;
width: 340px;
padding: 15px 16px;
border-radius: 15px;
}
.model h2 {
margin: 0 0 8px;
font-size: 11px;
letter-spacing: 0.03em;
}
.equation {
margin: 8px 0;
padding: 9px 10px;
overflow-x: auto;
border: 1px solid rgba(150, 200, 230, 0.1);
border-radius: 8px;
color: #d9f2ff;
background: rgba(0, 0, 0, 0.16);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
white-space: nowrap;
}
.model p {
margin: 7px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.constants {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 5px 12px;
margin-top: 9px;
color: #b8cbd8;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 9px;
}
.hint {
position: absolute;
z-index: 4;
bottom: 19px;
left: 50%;
transform: translateX(-50%);
padding: 7px 11px;
border-radius: 999px;
color: #72899a;
background: rgba(7, 15, 23, 0.56);
font-size: 10px;
pointer-events: none;
white-space: nowrap;
}
#loading {
position: absolute;
z-index: 20;
inset: 0;
display: grid;
place-items: center;
color: var(--cyan);
background: var(--bg);
font-size: 12px;
letter-spacing: 0.08em;
}
@media (max-width: 900px) {
.model { display: none; }
.metrics { width: 225px; }
}
@media (max-width: 650px) {
.panel {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
max-height: 48vh;
padding: 14px;
}
h1 { font-size: 21px; }
.metrics {
top: auto;
right: 10px;
bottom: 10px;
width: calc(100vw - 20px);
padding: 11px 13px;
}
.metric {
display: inline-flex;
width: 32%;
padding: 4px 7px;
border-top: 0;
border-left: 1px solid rgba(150, 200, 230, 0.1);
vertical-align: top;
}
.metric:first-of-type {
border-left: 0;
}
.metric span {
display: block;
font-size: 9px;
}
.metric strong {
display: block;
margin-top: 3px;
font-size: 13px;
}
.metric-note,
.status,
.hint {
display: none;
}
}
</style>
</head>
<body>
<div id="app">
<div id="loading">INITIALIZING VOXEL SPIN LAB…</div>
<aside class="panel glass">
<div class="eyebrow">Trajectory comparison / 01</div>
<h1>Voxel Spin Lab</h1>
<p class="intro">
One launch vector, two spin vectors. A and B begin at the same
position with identical velocity; only the sign of spin changes.
</p>
<div class="legend">
<div class="legend-card">
<div class="legend-title">
<span class="dot a"></span>
Ball A · +ω
</div>
<div class="legend-sub">Positive Y-axis spin</div>
</div>
<div class="legend-card">
<div class="legend-title">
<span class="dot b"></span>
Ball B · −ω
</div>
<div class="legend-sub">Reversed Y-axis spin</div>
</div>
</div>
<div class="divider"></div>
<div class="control">
<label for="speed">
Launch speed
<output id="speedOut">14.0 m/s</output>
</label>
<input id="speed" type="range" min="8" max="24" step="0.5" value="14">
</div>
<div class="control">
<label for="elevation">
Launch elevation
<output id="elevationOut">34°</output>
</label>
<input id="elevation" type="range" min="15" max="55" step="1" value="34">
</div>
<div class="control">
<label for="spin">
Spin magnitude
<output id="spinOut">90 rad/s</output>
</label>
<input id="spin" type="range" min="0" max="180" step="5" value="90">
</div>
<div class="control">
<label for="drag">
Quadratic drag · kD
<output id="dragOut">0.0060 m⁻¹</output>
</label>
<input id="drag" type="range" min="0.002" max="0.012" step="0.0005" value="0.006">
</div>
<div class="control">
<label for="magnus">
Magnus gain · kM
<output id="magnusOut">7.50e−4</output>
</label>
<input id="magnus" type="range" min="0.0002" max="0.0015" step="0.00005" value="0.00075">
</div>
<div class="control">
<div class="row row-between">
<label for="playback" style="margin:0">Playback</label>
<select id="playback">
<option value="0.25">0.25×</option>
<option value="0.5">0.5×</option>
<option value="1" selected>1×</option>
<option value="2">2×</option>
</select>
</div>
</div>
<div class="control">
<label class="check">
<input id="follow" type="checkbox">
Camera follows the flight
</label>
</div>
<div class="buttons">
<button id="launch" class="primary">Launch comparison</button>
<button id="reset">Reset</button>
</div>
</aside>
<div id="status" class="status">READY</div>
<section class="metrics glass">
<div class="metric-title">Predicted landing</div>
<div class="metric">
<span>Flight time</span>
<strong id="flightValue">—</strong>
</div>
<div class="metric">
<span>Forward range</span>
<strong id="rangeValue">—</strong>
</div>
<div class="metric">
<span>Lateral split</span>
<strong id="separationValue">—</strong>
</div>
<div id="lateralValue" class="metric-note">
A and B lateral offsets appear here.
</div>
</section>
<section class="model glass">
<h2>Simplified point-mass model</h2>
<div class="equation">
v̇ = −gŷ − kD‖v‖v + kM(ω × v)<br>
ω̇ = −kωω
</div>
<div class="constants">
<span>g = 9.81 m/s²</span>
<span>kω = 0.040 s⁻¹</span>
<span id="modelDrag">kD = 0.0060 m⁻¹</span>
<span id="modelMagnus">kM = 7.50e−4</span>
</div>
<p>
No wind, bounce, or spin-dependent lift. The ball is treated as a
point mass for flight and lands when its center reaches the ground.
Opposite spin produces mirror-symmetric lateral paths in this model.
Integration uses fourth-order Runge–Kutta at 1/120 s.
</p>
<p>
Voxel size and the visible spin animation are schematic.
Trajectory values use SI units.
</p>
</section>
<div class="hint">
Drag to orbit · wheel/pinch to zoom · right-drag to pan · double-click to reset view
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = id => document.getElementById(id);
const app = $("app");
const COLORS = {
a: new THREE.Color("#54e2ff"),
b: new THREE.Color("#ff61c7"),
launch: new THREE.Color("#7895aa")
};
const PHYSICS = {
gravity: 9.81,
spinDecay: 0.04,
dt: 1 / 120,
maxTime: 14,
groundY: 0.145,
start: new THREE.Vector3(0, 0.145, 0)
};
let running = false;
let completed = false;
let simulationTime = 0;
let flightDuration = 0;
let elapsedRealTime = 0;
let simA = null;
let simB = null;
const scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x071018, 0.017);
const camera = new THREE.PerspectiveCamera(
46,
innerWidth / innerHeight,
0.05,
180
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute("aria-label", "Interactive 3D trajectory comparison");
app.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xb9e9ff, 0x17101f, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(12, 24, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -30;
keyLight.shadow.camera.right = 35;
keyLight.shadow.camera.top = 25;
keyLight.shadow.camera.bottom = -25;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 70;
keyLight.shadow.bias = -0.0008;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4fc7ff, 1.8);
rimLight.position.set(-8, 7, -14);
scene.add(rimLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(120, 120),
new THREE.MeshStandardMaterial({
color: 0x071019,
roughness: 0.96,
metalness: 0.02
})
);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(80, 80, 0x28465b, 0x132735);
grid.position.y = 0.006;
grid.material.transparent = true;
grid.material.opacity = 0.55;
grid.material.depthWrite = false;
scene.add(grid);
function makeAxisLine(points, color, opacity = 0.3) {
const geometry = new THREE.BufferGeometry().setFromPoints(
points.map(p => new THREE.Vector3(...p))
);
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity
});
return new THREE.Line(geometry, material);
}
scene.add(makeAxisLine(
[[-8, 0.012, 0], [34, 0.012, 0]],
0x5e8299,
0.34
));
scene.add(makeAxisLine(
[[0, 0.013, -18], [0, 0.013, 18]],
0x765b87,
0.26
));
const launchArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(0, 0.03, 0),
2.5,
COLORS.launch,
0.38,
0.2
);
launchArrow.line.material.transparent = true;
launchArrow.line.material.opacity = 0.55;
launchArrow.cone.material.transparent = true;
launchArrow.cone.material.opacity = 0.65;
scene.add(launchArrow);
const startRing = new THREE.Mesh(
new THREE.RingGeometry(0.25, 0.32, 48),
new THREE.MeshBasicMaterial({
color: 0x8ca8b9,
side: THREE.DoubleSide,
transparent: true,
opacity: 0.5
})
);
startRing.rotation.x = -Math.PI / 2;
startRing.position.y = 0.017;
scene.add(startRing);
function makeGlowTexture() {
const canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 128;
const ctx = canvas.getContext("2d");
const gradient = ctx.createRadialGradient(64, 64, 0, 64, 64, 64);
gradient.addColorStop(0, "rgba(255,255,255,0.72)");
gradient.addColorStop(0.2, "rgba(255,255,255,0.28)");
gradient.addColorStop(0.55, "rgba(255,255,255,0.08)");
gradient.addColorStop(1, "rgba(255,255,255,0)");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 128, 128);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
const glowTexture = makeGlowTexture();
function makeVoxelBall(color, hueOffset) {
const group = new THREE.Group();
const cubeGeometry = new THREE.BoxGeometry(0.05, 0.05, 0.05);
const solidMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.32,
metalness: 0.08,
vertexColors: true,
flatShading: true
});
const wireMaterial = new THREE.MeshBasicMaterial({
color,
wireframe: true,
transparent: true,
opacity: 0.28,
depthWrite: false
});
const cells = [];
for (let x = -2; x <= 2; x++) {
for (let y = -2; y <= 2; y++) {
for (let z = -2; z <= 2; z++) {
if (x * x + y * y + z * z <= 5.25) {
cells.push([x, y, z]);
}
}
}
}
const solid = new THREE.InstancedMesh(
cubeGeometry,
solidMaterial,
cells.length
);
const wire = new THREE.InstancedMesh(
cubeGeometry,
wireMaterial,
cells.length
);
const dummy = new THREE.Object3D();
const cellColor = new THREE.Color();
cells.forEach(([x, y, z], index) => {
dummy.position.set(x * 0.052, y * 0.052, z * 0.052);
dummy.scale.setScalar(1);
dummy.updateMatrix();
solid.setMatrixAt(index, dummy.matrix);
dummy.scale.setScalar(1.08);
dummy.updateMatrix();
wire.setMatrixAt(index, dummy.matrix);
const hash = (x * 17 + y * 31 + z * 43 + 100) % 100;
const hue = (hueOffset + hash / 100 * 0.075) % 1;
cellColor.setHSL(hue, 0.78, 0.48 + (hash % 12) / 100);
solid.setColorAt(index, cellColor);
});
solid.instanceMatrix.needsUpdate = true;
solid.instanceColor.needsUpdate = true;
wire.instanceMatrix.needsUpdate = true;
solid.castShadow = true;
solid.receiveShadow = true;
solid.frustumCulled = false;
wire.frustumCulled = false;
group.add(solid, wire);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.19, 0.006, 6, 56),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.7
})
);
ring.rotation.x = Math.PI / 2;
group.add(ring);
const bead = new THREE.Mesh(
new THREE.BoxGeometry(0.027, 0.027, 0.027),
new THREE.MeshBasicMaterial({ color: 0xffffff })
);
bead.position.set(0.19, 0, 0);
group.add(bead);
const halo = new THREE.Sprite(
new THREE.SpriteMaterial({
map: glowTexture,
color,
transparent: true,
opacity: 0.48,
depthWrite: false,
blending: THREE.AdditiveBlending
})
);
halo.scale.setScalar(0.68);
group.add(halo);
group.position.copy(PHYSICS.start);
scene.add(group);
return group;
}
const ballA = makeVoxelBall(COLORS.a, 0.52);
const ballB = makeVoxelBall(COLORS.b, 0.88);
function makeTrail(color) {
const line = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.9,
depthWrite: false
})
);
line.frustumCulled = false;
const glow = new THREE.Points(
line.geometry,
new THREE.PointsMaterial({
color,
size: 0.055,
sizeAttenuation: true,
transparent: true,
opacity: 0.45,
depthWrite: false,
blending: THREE.AdditiveBlending
})
);
glow.frustumCulled = false;
scene.add(line, glow);
return { line, glow };
}
const trailA = makeTrail(COLORS.a);
const trailB = makeTrail(COLORS.b);
function makeLandingMarker(color) {
const group = new THREE.Group();
const ring = new THREE.Mesh(
new THREE.RingGeometry(0.12, 0.19, 40),
new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.85,
side: THREE.DoubleSide
})
);
ring.rotation.x = -Math.PI / 2;
group.add(ring);
const point = new THREE.Mesh(
new THREE.SphereGeometry(0.045, 10, 10),
new THREE.MeshBasicMaterial({ color })
);
point.position.y = 0.05;
group.add(point);
scene.add(group);
return group;
}
const markerA = makeLandingMarker(COLORS.a);
const markerB = makeLandingMarker(COLORS.b);
function readParameters() {
return {
speed: Number($("speed").value),
elevation: THREE.MathUtils.degToRad(Number($("elevation").value)),
spin: Number($("spin").value),
drag: Number($("drag").value),
magnus: Number($("magnus").value)
};
}
function derivative(state, params) {
const vx = state[3];
const vy = state[4];
const vz = state[5];
const wx = state[6];
const wy = state[7];
const wz = state[8];
const speed = Math.hypot(vx, vy, vz);
// omega cross v
const crossX = wy * vz - wz * vy;
const crossY = wz * vx - wx * vz;
const crossZ = wx * vy - wy * vx;
const ax = -params.drag * speed * vx + params.magnus * crossX;
const ay = -PHYSICS.gravity
- params.drag * speed * vy
+ params.magnus * crossY;
const az = -params.drag * speed * vz + params.magnus * crossZ;
return new Float64Array([
vx, vy, vz,
ax, ay, az,
-PHYSICS.spinDecay * wx,
-PHYSICS.spinDecay * wy,
-PHYSICS.spinDecay * wz
]);
}
function combineState(state, derivativeVector, scale) {
const result = new Float64Array(9);
for (let i = 0; i < 9; i++) {
result[i] = state[i] + derivativeVector[i] * scale;
}
return result;
}
function rk4Step(state, params, dt) {
const k1 = derivative(state, params);
const k2 = derivative(combineState(state, k1, dt / 2), params);
const k3 = derivative(combineState(state, k2, dt / 2), params);
const k4 = derivative(combineState(state, k3, dt), params);
const result = new Float64Array(9);
for (let i = 0; i < 9; i++) {
result[i] = state[i] + dt / 6 *
(k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]);
}
return result;
}
function simulate(spinSign, params) {
const velocityX = params.speed * Math.cos(params.elevation);
const velocityY = params.speed * Math.sin(params.elevation);
let state = new Float64Array([
PHYSICS.start.x, PHYSICS.start.y, PHYSICS.start.z,
velocityX, velocityY, 0,
0, spinSign * params.spin, 0
]);
const points = [{
x: state[0],
y: state[1],
z: state[2],
t: 0
}];
const maxSteps = Math.ceil(PHYSICS.maxTime / PHYSICS.dt);
let landing = null;
let duration = PHYSICS.maxTime;
for (let step = 1; step <= maxSteps; step++) {
const previous = state;
const next = rk4Step(previous, params, PHYSICS.dt);
if (
next[1] <= PHYSICS.groundY &&
next[4] < 0 &&
step > 2
) {
const denominator = previous[1] - next[1];
const fraction = denominator > 0
? (previous[1] - PHYSICS.groundY) / denominator
: 1;
const finalState = new Float64Array(9);
for (let i = 0; i < 9; i++) {
finalState[i] = previous[i] +
(next[i] - previous[i]) * fraction;
}
duration = (step - 1 + fraction) * PHYSICS.dt;
landing = {
x: finalState[0],
y: finalState[1],
z: finalState[2]
};
points.push({
x: finalState[0],
y: finalState[1],
z: finalState[2],
t: duration
});
break;
}
state = next;
// Store at 60 Hz; the integrator itself still runs at 120 Hz.
if (step % 2 === 0) {
points.push({
x: state[0],
y: state[1],
z: state[2],
t: step * PHYSICS.dt
});
}
}
if (!landing) {
landing = {
x: state[0],
y: state[1],
z: state[2]
};
}
return {
points,
landing,
duration
};
}
function setTrailGeometry(trail, points) {
const oldGeometry = trail.line.geometry;
const geometry = new THREE.BufferGeometry().setFromPoints(
points.map(point => new THREE.Vector3(point.x, point.y, point.z))
);
trail.line.geometry = geometry;
trail.glow.geometry = geometry;
oldGeometry.dispose();
}
function pathIndexAtTime(points, time) {
let low = 0;
let high = points.length - 1;
while (low <= high) {
const middle = (low + high) >> 1;
if (points[middle].t <= time) {
low = middle + 1;
} else {
high = middle - 1;
}
}
return Math.max(0, Math.min(points.length - 1, low));
}
function samplePath(points, time) {
const index = pathIndexAtTime(points, time);
const current = points[index];
const next = points[Math.min(index + 1, points.length - 1)];
if (current === next) {
return new THREE.Vector3(current.x, current.y, current.z);
}
const span = next.t - current.t;
const alpha = span > 0
? THREE.MathUtils.clamp((time - current.t) / span, 0, 1)
: 0;
return new THREE.Vector3(
THREE.MathUtils.lerp(current.x, next.x, alpha),
THREE.MathUtils.lerp(current.y, next.y, alpha),
THREE.MathUtils.lerp(current.z, next.z, alpha)
);
}
function setTrailStyle(trail, opacity) {
trail.line.material.opacity = opacity;
trail.glow.material.opacity = opacity * 0.5;
}
function updateOutputs() {
const params = readParameters();
$("speedOut").textContent = `${params.speed.toFixed(1)} m/s`;
$("elevationOut").textContent =
`${Number($("elevation").value).toFixed(0)}°`;
$("spinOut").textContent = `${params.spin.toFixed(0)} rad/s`;
$("dragOut").textContent = `${params.drag.toFixed(4)} m⁻¹`;
$("magnusOut").textContent = params.magnus.toExponential(2)
.replace("e-", "e−");
$("modelDrag").textContent = `kD = ${params.drag.toFixed(4)} m⁻¹`;
$("modelMagnus").textContent =
`kM = ${params.magnus.toExponential(2).replace("e-", "e−")}`;
}
function updateMetrics() {
const separation = Math.hypot(
simA.landing.x - simB.landing.x,
simA.landing.z - simB.landing.z
);
$("flightValue").textContent = `${simA.duration.toFixed(2)} s`;
$("rangeValue").textContent =
`${Math.abs(simA.landing.x).toFixed(1)} m`;
$("separationValue").textContent = `${separation.toFixed(2)} m`;
const sign = value => `${value >= 0 ? "+" : "−"}${Math.abs(value).toFixed(2)}`;
$("lateralValue").textContent =
`Lateral offsets — A ${sign(simA.landing.z)} m, ` +
`B ${sign(simB.landing.z)} m. Forward range is equal by symmetry.`;
}
function resetObjects() {
running = false;
completed = false;
simulationTime = 0;
ballA.position.copy(PHYSICS.start);
ballB.position.copy(PHYSICS.start);
setTrailStyle(trailA, 0.25);
setTrailStyle(trailB, 0.25);
trailA.line.geometry.setDrawRange(0, simA.points.length);
trailA.glow.geometry.setDrawRange(0, simA.points.length);
trailB.line.geometry.setDrawRange(0, simB.points.length);
trailB.glow.geometry.setDrawRange(0, simB.points.length);
markerA.position.set(simA.landing.x, 0.018, simA.landing.z);
markerB.position.set(simB.landing.x, 0.018, simB.landing.z);
$("status").textContent = "READY";
$("status").className = "status";
}
function recompute() {
const params = readParameters();
simA = simulate(+1, params);
simB = simulate(-1, params);
flightDuration = Math.max(simA.duration, simB.duration);
setTrailGeometry(trailA, simA.points);
setTrailGeometry(trailB, simB.points);
updateMetrics();
resetObjects();
}
function launchComparison() {
recompute();
running = true;
completed = false;
simulationTime = 0;
setTrailStyle(trailA, 0.95);
setTrailStyle(trailB, 0.95);
$("status").textContent = "IN FLIGHT";
$("status").className = "status flying";
}
$("launch").addEventListener("click", launchComparison);
$("reset").addEventListener("click", recompute);
[
"speed", "elevation", "spin", "drag", "magnus"
].forEach(id => {
$(id).addEventListener("input", () => {
updateOutputs();
recompute();
});
});
document.addEventListener("keydown", event => {
if (
event.code === "Space" &&
!["INPUT", "SELECT", "BUTTON"].includes(document.activeElement.tagName)
) {
event.preventDefault();
launchComparison();
}
});
// ---------------------------------------------------------------------------
// Direct camera controls: orbit, pan, wheel/pinch zoom, double-click reset.
// No Three.js examples/addons are used.
// ---------------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(8, 0.35, 0),
radius: 27,
theta: 0.67,
phi: 1.12
};
const defaultCamera = {
target: new THREE.Vector3(8, 0.35, 0),
radius: 27,
theta: 0.67,
phi: 1.12
};
const pointers = new Map();
let previousPinchDistance = 0;
function pointerDistance() {
const values = [...pointers.values()];
if (values.length < 2) return 0;
return Math.hypot(
values[0].x - values[1].x,
values[0].y - values[1].y
);
}
renderer.domElement.addEventListener("contextmenu", event => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", event => {
renderer.domElement.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY,
startX: event.clientX,
startY: event.clientY,
button: event.button
});
if (pointers.size === 2) {
previousPinchDistance = pointerDistance();
}
});
renderer.domElement.addEventListener("pointermove", event => {
const pointer = pointers.get(event.pointerId);
if (!pointer) return;
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
pointer.x = event.clientX;
pointer.y = event.clientY;
if (pointers.size >= 2) {
const distance = pointerDistance();
if (distance > 0 && previousPinchDistance > 0) {
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * previousPinchDistance / distance,
6,
70
);
}
previousPinchDistance = distance;
return;
}
if (pointer.button === 2) {
const right = new THREE.Vector3()
.setFromMatrixColumn(camera.matrixWorld, 0);
const up = new THREE.Vector3()
.setFromMatrixColumn(camera.matrixWorld, 1);
cameraState.target
.addScaledVector(right, -dx * cameraState.radius * 0.0014)
.addScaledVector(up, dy * cameraState.radius * 0.0014);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.22,
1.48
);
}
});
function endPointer(event) {
pointers.delete(event.pointerId);
if (pointers.size < 2) previousPinchDistance = 0;
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
6,
70
);
}, { passive: false });
renderer.domElement.addEventListener("dblclick", () => {
cameraState.target.copy(defaultCamera.target);
cameraState.radius = defaultCamera.radius;
cameraState.theta = defaultCamera.theta;
cameraState.phi = defaultCamera.phi;
});
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y +
cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
function updateFlightObjects() {
const time = running
? simulationTime
: completed
? flightDuration
: 0;
if (running || completed) {
ballA.position.copy(samplePath(simA.points, time));
ballB.position.copy(samplePath(simB.points, time));
} else {
ballA.position.copy(PHYSICS.start);
ballB.position.copy(PHYSICS.start);
}
const visualSpin = running || completed ? simulationTime * 5.2 : elapsedRealTime * 0.8;
ballA.rotation.y = visualSpin;
ballB.rotation.y = -visualSpin;
let countA = simA.points.length;
let countB = simB.points.length;
if (running || completed) {
countA = Math.min(
simA.points.length,
pathIndexAtTime(simA.points, time) + 1
);
countB = Math.min(
simB.points.length,
pathIndexAtTime(simB.points, time) + 1
);
}
trailA.line.geometry.setDrawRange(0, countA);
trailA.glow.geometry.setDrawRange(0, countA);
trailB.line.geometry.setDrawRange(0, countB);
trailB.glow.geometry.setDrawRange(0, countB);
}
const clock = new THREE.Clock();
const followGoal = new THREE.Vector3();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
elapsedRealTime += delta;
if (running) {
const speed = Number($("playback").value);
simulationTime = Math.min(
flightDuration,
simulationTime + delta * speed
);
if (simulationTime >= flightDuration - 1e-6) {
running = false;
completed = true;
simulationTime = flightDuration;
$("status").textContent = "LANDED";
$("status").className = "status landed";
}
}
updateFlightObjects();
if ($("follow").checked) {
if (running || completed) {
followGoal.copy(ballA.position).add(ballB.position).multiplyScalar(0.5);
followGoal.y = 0.35;
} else {
followGoal.set(8, 0.35, 0);
}
cameraState.target.lerp(
followGoal,
1 - Math.exp(-delta * 2.4)
);
}
updateCamera();
renderer.render(scene, camera);
}
function resize() {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
}
addEventListener("resize", resize);
updateOutputs();
recompute();
updateCamera();
animate();
$("loading").remove();
</script>
</body>
</html>
```