Prompt specification
Build or customize the Three.js 3D scene "Kepler Orbit With Changing Speed" 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: Kepler Orbit With Changing Speed
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/kepler-orbit-with-changing-speed-x3802
Scene Description Prompt:
Animate a voxel ideal Kepler orbit with changing speed and equal-area sweeps over equal times. Three.js from cdnjs, one HTML file.
Working Three.js Starter (kepler-orbit-with-changing-speed-x3802):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Kepler Orbit</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(7, 12, 28, 0.82);
--line: rgba(128, 177, 255, 0.2);
--muted: #8fa5c7;
--text: #eef5ff;
--cyan: #70f4ff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #050816;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, sans-serif;
color: var(--text);
}
canvas {
display: block;
cursor: grab;
touch-action: none;
}
canvas.dragging {
cursor: grabbing;
}
#hud {
position: fixed;
z-index: 10;
top: 14px;
left: 14px;
width: min(370px, calc(100vw - 28px));
padding: 16px;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(16px);
user-select: none;
}
.eyebrow {
margin-bottom: 5px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 23px;
line-height: 1.1;
letter-spacing: -0.03em;
}
.subtitle {
margin: 7px 0 14px;
color: var(--muted);
font-size: 12px;
line-height: 1.45;
}
.formula {
padding: 10px 12px;
border: 1px solid rgba(112, 244, 255, 0.14);
border-radius: 10px;
background: rgba(112, 244, 255, 0.045);
color: #b9d9ed;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 11px;
line-height: 1.65;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin: 12px 0;
}
.stat {
min-width: 0;
padding: 9px 8px;
border: 1px solid rgba(128, 177, 255, 0.12);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
}
.stat span {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stat b {
display: block;
overflow: hidden;
font-size: 12px;
text-overflow: ellipsis;
white-space: nowrap;
}
.section-label {
display: flex;
justify-content: space-between;
gap: 10px;
margin: 12px 0 7px;
color: var(--muted);
font-size: 10px;
}
.section-label strong {
color: #dcecff;
font-weight: 650;
}
#equalBars {
display: grid;
grid-template-columns: repeat(48, 1fr);
gap: 1px;
height: 22px;
padding: 3px;
border: 1px solid rgba(128, 177, 255, 0.12);
border-radius: 7px;
background: rgba(0, 0, 0, 0.18);
}
.bar {
min-width: 0;
border-radius: 1px;
opacity: 0.47;
transition: opacity 80ms linear, filter 80ms linear;
}
.bar.active {
opacity: 1;
filter: brightness(1.45);
outline: 1px solid rgba(255, 255, 255, 0.8);
outline-offset: -1px;
}
.timeline {
margin-top: 11px;
}
input[type="range"] {
width: 100%;
margin: 0;
accent-color: var(--cyan);
cursor: pointer;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 7px;
margin-top: 12px;
}
button {
padding: 8px 10px;
border: 1px solid rgba(128, 177, 255, 0.2);
border-radius: 8px;
background: rgba(255, 255, 255, 0.045);
color: #dbe9fb;
font: inherit;
font-size: 11px;
cursor: pointer;
transition: background 120ms ease, border-color 120ms ease;
}
button:hover {
border-color: rgba(112, 244, 255, 0.5);
background: rgba(112, 244, 255, 0.09);
}
button.active {
border-color: rgba(112, 244, 255, 0.42);
background: rgba(112, 244, 255, 0.12);
color: #efffff;
}
.speed-control {
display: flex;
flex: 1 1 170px;
align-items: center;
gap: 8px;
padding: 5px 9px;
border: 1px solid rgba(128, 177, 255, 0.14);
border-radius: 8px;
color: var(--muted);
font-size: 10px;
}
.speed-control input {
min-width: 70px;
flex: 1;
}
#speedValue {
min-width: 28px;
color: var(--text);
text-align: right;
}
#hint {
position: fixed;
z-index: 5;
right: 14px;
bottom: 14px;
max-width: calc(100vw - 28px);
padding: 8px 11px;
border: 1px solid rgba(128, 177, 255, 0.13);
border-radius: 9px;
background: rgba(7, 12, 28, 0.68);
color: #8fa5c7;
font-size: 10px;
text-align: right;
pointer-events: none;
}
#loading {
position: fixed;
z-index: 30;
inset: 0;
display: grid;
place-items: center;
background: #050816;
color: var(--cyan);
font-size: 12px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
@media (max-width: 600px) {
#hud {
top: 8px;
left: 8px;
width: calc(100vw - 16px);
padding: 12px;
}
.formula {
display: none;
}
.subtitle {
margin-bottom: 9px;
}
#hint {
display: none;
}
}
</style>
</head>
<body>
<div id="loading">Initializing Kepler field…</div>
<aside id="hud">
<div class="eyebrow">Ideal two-body mechanics</div>
<h1>Voxel Kepler Orbit</h1>
<p class="subtitle">
Equal time intervals sweep equal areas. The voxel path bunches near
aphelion because the planet moves more slowly there.
</p>
<div class="formula">
M(t) = M₀ + nt<br>
E − e sin E = M<br>
ΔA = πab / 48
</div>
<div class="stats">
<div class="stat">
<span>Orbital day</span>
<b id="dayValue">0.00</b>
</div>
<div class="stat">
<span>Radius</span>
<b id="radiusValue">—</b>
</div>
<div class="stat">
<span>Speed</span>
<b id="velocityValue">—</b>
</div>
</div>
<div class="section-label">
<span>48 equal-time area slices</span>
<strong id="areaValue">—</strong>
</div>
<div id="equalBars" aria-label="Equal-time and equal-area orbital slices"></div>
<div class="timeline">
<input
id="scrub"
type="range"
min="0"
max="10000"
value="0"
step="1"
aria-label="Scrub orbital phase"
>
</div>
<div class="controls">
<button id="playButton" type="button">Pause</button>
<button id="restartButton" type="button">Restart orbit</button>
<button id="resetViewButton" type="button">Reset view</button>
<label class="speed-control">
Speed
<input
id="speedSlider"
type="range"
min="0.25"
max="3"
step="0.05"
value="1"
aria-label="Animation speed"
>
<span id="speedValue">1×</span>
</label>
<button id="pathButton" class="active" type="button" aria-pressed="true">
Voxels
</button>
<button id="areaButton" class="active" type="button" aria-pressed="true">
Areas
</button>
<button id="trailButton" class="active" type="button" aria-pressed="true">
Trail
</button>
</div>
</aside>
<div id="hint">
Drag to rotate · wheel/pinch to zoom · shift/right-drag to pan<br>
Space: pause · double-click: reset camera
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x050816);
scene.fog = new THREE.FogExp2(0x050816, 0.0125);
const camera = new THREE.PerspectiveCamera(
46,
innerWidth / innerHeight,
0.1,
160
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
document.body.prepend(renderer.domElement);
scene.add(new THREE.AmbientLight(0x9ab8ff, 1.25));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.4);
keyLight.position.set(7, 10, 8);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x5a80ff, 1.2);
rimLight.position.set(-8, 4, -9);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Ideal elliptical orbit, with the Sun at one focus
// -------------------------------------------------------------------------
const TAU = Math.PI * 2;
const ORBIT = {
a: 6.4,
e: 0.58,
get b() {
return this.a * Math.sqrt(1 - this.e * this.e);
}
};
const SECTOR_COUNT = 48;
const PATH_SAMPLES = SECTOR_COUNT * 16;
const ORBIT_DAYS = 100;
const REAL_PERIOD_SECONDS = 24;
const orbitStep = TAU / SECTOR_COUNT;
const exactSliceArea =
(Math.PI * ORBIT.a * ORBIT.b) / SECTOR_COUNT;
const exactSliceTime =
(ORBIT_DAYS / SECTOR_COUNT);
const sectorColors = [];
for (let i = 0; i < SECTOR_COUNT; i++) {
sectorColors.push(
new THREE.Color().setHSL(
0.56 + (0.34 * i) / (SECTOR_COUNT - 1),
0.78,
0.52
)
);
}
function solveKepler(meanAnomaly) {
// Newton's method for E - e sin(E) = M.
let E = meanAnomaly + ORBIT.e * Math.sin(meanAnomaly);
for (let i = 0; i < 12; i++) {
const f =
E - ORBIT.e * Math.sin(E) - meanAnomaly;
const fp = 1 - ORBIT.e * Math.cos(E);
E -= f / fp;
}
return E;
}
function positionAtMean(meanAnomaly, target) {
const E = solveKepler(meanAnomaly);
target.set(
ORBIT.a * (Math.cos(E) - ORBIT.e),
0,
ORBIT.b * Math.sin(E)
);
return target;
}
// -------------------------------------------------------------------------
// Equal-area sector geometry
// -------------------------------------------------------------------------
const areaGroup = new THREE.Group();
scene.add(areaGroup);
const sectorMeshes = [];
const measuredAreas = [];
const subdivisionCount = 24;
for (let sectorIndex = 0; sectorIndex < SECTOR_COUNT; sectorIndex++) {
const m0 = sectorIndex * orbitStep;
const m1 = (sectorIndex + 1) * orbitStep;
const vertices = [];
const polygon = [];
for (let j = 0; j <= subdivisionCount; j++) {
const m = m0 + ((m1 - m0) * j) / subdivisionCount;
const p = positionAtMean(m, new THREE.Vector3());
polygon.push(p);
if (j < subdivisionCount) {
const q = positionAtMean(
m0 + ((m1 - m0) * (j + 1)) / subdivisionCount,
new THREE.Vector3()
);
vertices.push(
0, 0, 0,
p.x, 0, p.z,
q.x, 0, q.z
);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(vertices, 3)
);
const material = new THREE.MeshBasicMaterial({
color: sectorColors[sectorIndex],
transparent: true,
opacity: 0.08,
depthWrite: false,
side: THREE.DoubleSide
});
const mesh = new THREE.Mesh(geometry, material);
mesh.renderOrder = 1;
areaGroup.add(mesh);
sectorMeshes.push(mesh);
// Shoelace area of the rendered polygon.
let twiceArea = 0;
for (let j = 0; j < polygon.length - 1; j++) {
twiceArea +=
polygon[j].x * polygon[j + 1].z -
polygon[j].z * polygon[j + 1].x;
}
measuredAreas.push(Math.abs(twiceArea) * 0.5);
}
// Radial boundaries at equal-time interval endpoints.
const boundaryVertices = [];
for (let i = 0; i < SECTOR_COUNT; i++) {
const p = positionAtMean(
i * orbitStep,
new THREE.Vector3()
);
boundaryVertices.push(
0, 0.012, 0,
p.x, 0.012, p.z
);
}
const boundaryGeometry = new THREE.BufferGeometry();
boundaryGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(boundaryVertices, 3)
);
const boundaries = new THREE.LineSegments(
boundaryGeometry,
new THREE.LineBasicMaterial({
color: 0x7b9ac8,
transparent: true,
opacity: 0.3,
depthWrite: false
})
);
areaGroup.add(boundaries);
// Progressive fill for the currently active sweep.
const activeGeometry = new THREE.BufferGeometry();
const activePositionAttribute = new THREE.BufferAttribute(
new Float32Array(32 * 9),
3
);
activePositionAttribute.setUsage(THREE.DynamicDrawUsage);
activeGeometry.setAttribute(
"position",
activePositionAttribute
);
activeGeometry.setDrawRange(0, 0);
const activeSweep = new THREE.Mesh(
activeGeometry,
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.28,
depthWrite: false,
side: THREE.DoubleSide
})
);
activeSweep.position.y = 0.025;
activeSweep.frustumCulled = false;
activeSweep.renderOrder = 2;
areaGroup.add(activeSweep);
function updateActiveSweep(sectorIndex, phase) {
const start = sectorIndex * orbitStep;
const localPhase = phase - start;
if (localPhase <= 0) {
activeGeometry.setDrawRange(0, 0);
return;
}
const triangleCount = Math.max(
1,
Math.ceil((localPhase / orbitStep) * 24)
);
const array = activePositionAttribute.array;
let offset = 0;
for (let j = 0; j < triangleCount; j++) {
const t0 = j / triangleCount;
const t1 = (j + 1) / triangleCount;
const p = positionAtMean(
start + localPhase * t0,
new THREE.Vector3()
);
const q = positionAtMean(
start + localPhase * t1,
new THREE.Vector3()
);
array[offset++] = 0;
array[offset++] = 0;
array[offset++] = 0;
array[offset++] = p.x;
array[offset++] = 0;
array[offset++] = p.z;
array[offset++] = q.x;
array[offset++] = 0;
array[offset++] = q.z;
}
activePositionAttribute.needsUpdate = true;
activeGeometry.setDrawRange(0, triangleCount * 3);
}
// -------------------------------------------------------------------------
// Voxel orbit path
//
// Samples are taken at equal intervals of mean anomaly, hence equal times.
// They therefore separate farther at perihelion and bunch at aphelion.
// -------------------------------------------------------------------------
const path = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.075, 0.075, 0.075),
new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.58,
metalness: 0.18,
emissive: 0x07152b,
emissiveIntensity: 0.75
}),
PATH_SAMPLES
);
path.instanceMatrix.setUsage(THREE.StaticDrawUsage);
path.frustumCulled = false;
const dummy = new THREE.Object3D();
const white = new THREE.Color(0xffffff);
for (let i = 0; i < PATH_SAMPLES; i++) {
const m = (i / PATH_SAMPLES) * TAU;
const p = positionAtMean(m, new THREE.Vector3());
dummy.position.set(p.x, 0.08, p.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.setScalar(1);
dummy.updateMatrix();
path.setMatrixAt(i, dummy.matrix);
const sectorIndex = Math.min(
SECTOR_COUNT - 1,
Math.floor(m / orbitStep)
);
const color = sectorColors[sectorIndex].clone();
color.lerp(white, 0.1 + 0.08 * Math.sin(i * 0.31));
path.setColorAt(i, color);
}
path.instanceMatrix.needsUpdate = true;
path.instanceColor.needsUpdate = true;
scene.add(path);
// -------------------------------------------------------------------------
// Voxel Sun
// -------------------------------------------------------------------------
const sun = new THREE.Group();
sun.position.y = 0.22;
scene.add(sun);
const sunMaterial = new THREE.MeshStandardMaterial({
color: 0xffb347,
emissive: 0xff6b00,
emissiveIntensity: 3.2,
roughness: 0.35,
metalness: 0.1
});
const sunCore = new THREE.Mesh(
new THREE.BoxGeometry(0.72, 0.72, 0.72),
sunMaterial
);
sun.add(sunCore);
const sunVoxelOffsets = [
[-0.43, 0, 0],
[0.43, 0, 0],
[0, 0.43, 0],
[0, -0.43, 0],
[0, 0, 0.43],
[0, 0, -0.43]
];
for (const offset of sunVoxelOffsets) {
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.25, 0.25, 0.25),
sunMaterial
);
cube.position.set(...offset);
sun.add(cube);
}
const sunLight = new THREE.PointLight(0xff9b3d, 95, 32, 2);
sunLight.position.set(0, 0.7, 0);
scene.add(sunLight);
// Soft additive glow, generated locally.
const glowCanvas = document.createElement("canvas");
glowCanvas.width = 128;
glowCanvas.height = 128;
const glowContext = glowCanvas.getContext("2d");
const glowGradient = glowContext.createRadialGradient(
64, 64, 0,
64, 64, 64
);
glowGradient.addColorStop(0, "rgba(255,220,120,1)");
glowGradient.addColorStop(0.18, "rgba(255,150,40,0.6)");
glowGradient.addColorStop(0.55, "rgba(255,80,10,0.13)");
glowGradient.addColorStop(1, "rgba(255,0,0,0)");
glowContext.fillStyle = glowGradient;
glowContext.fillRect(0, 0, 128, 128);
const glowTexture = new THREE.CanvasTexture(glowCanvas);
glowTexture.colorSpace = THREE.SRGBColorSpace;
const sunGlow = new THREE.Sprite(
new THREE.SpriteMaterial({
map: glowTexture,
transparent: true,
opacity: 0.8,
depthWrite: false,
blending: THREE.AdditiveBlending
})
);
sunGlow.position.set(0, 0.22, 0);
sunGlow.scale.set(4.8, 4.8, 1);
scene.add(sunGlow);
// Perihelion and aphelion markers.
const periMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.18, 0.18, 0.18),
new THREE.MeshBasicMaterial({ color: 0xff6585 })
);
periMarker.position.set(
ORBIT.a * (1 - ORBIT.e),
0.17,
0
);
scene.add(periMarker);
const apoMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.18, 0.18, 0.18),
new THREE.MeshBasicMaterial({ color: 0x9e7cff })
);
apoMarker.position.set(
-ORBIT.a * (1 + ORBIT.e),
0.17,
0
);
scene.add(apoMarker);
// -------------------------------------------------------------------------
// Voxel planet and moving trail
// -------------------------------------------------------------------------
const planet = new THREE.Group();
scene.add(planet);
const planetMaterial = new THREE.MeshStandardMaterial({
color: 0x70f4ff,
emissive: 0x087b91,
emissiveIntensity: 1.3,
roughness: 0.35,
metalness: 0.3
});
const planetBody = new THREE.Mesh(
new THREE.BoxGeometry(0.38, 0.38, 0.38),
planetMaterial
);
planet.add(planetBody);
const panelMaterial = new THREE.MeshStandardMaterial({
color: 0x4166b5,
emissive: 0x101f55,
emissiveIntensity: 0.8,
roughness: 0.6,
metalness: 0.25
});
const panelOffsets = [
[-0.31, 0, 0],
[0.31, 0, 0],
[0, 0.25, 0],
[0, 0, -0.31]
];
for (const offset of panelOffsets) {
const panel = new THREE.Mesh(
new THREE.BoxGeometry(0.18, 0.18, 0.18),
panelMaterial
);
panel.position.set(...offset);
planet.add(panel);
}
const trail = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.105, 0.105, 0.105),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.75,
depthWrite: false
}),
72
);
trail.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
trail.frustumCulled = false;
scene.add(trail);
// A velocity vector makes the speed variation explicit.
const velocityArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1,
0x70f4ff,
0.3,
0.18
);
scene.add(velocityArrow);
// -------------------------------------------------------------------------
// Grid and voxel stars
// -------------------------------------------------------------------------
const gridVertices = [];
for (let x = -17; x <= 10; x++) {
gridVertices.push(x, -0.72, -12, x, -0.72, 12);
}
for (let z = -12; z <= 12; z++) {
gridVertices.push(-17, -0.72, z, 10, -0.72, z);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridVertices, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x1b3157,
transparent: true,
opacity: 0.52
})
);
scene.add(grid);
let randomSeed = 91273;
function random() {
randomSeed |= 0;
randomSeed = (randomSeed + 0x6d2b79f5) | 0;
let t = Math.imul(randomSeed ^ (randomSeed >>> 15), 1 | randomSeed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
}
const starCount = 180;
const stars = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.07, 0.07, 0.07),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.72,
depthWrite: false
}),
starCount
);
stars.frustumCulled = false;
for (let i = 0; i < starCount; i++) {
const radius = 35 + random() * 42;
const theta = random() * TAU;
const phi = Math.acos(2 * random() - 1);
dummy.position.set(
radius * Math.sin(phi) * Math.cos(theta),
radius * Math.cos(phi),
radius * Math.sin(phi) * Math.sin(theta)
);
dummy.rotation.set(
random() * TAU,
random() * TAU,
random() * TAU
);
dummy.scale.setScalar(0.45 + random() * 1.6);
dummy.updateMatrix();
stars.setMatrixAt(i, dummy.matrix);
const color = new THREE.Color().setHSL(
0.55 + random() * 0.16,
0.25,
0.62 + random() * 0.32
);
stars.setColorAt(i, color);
}
stars.instanceMatrix.needsUpdate = true;
stars.instanceColor.needsUpdate = true;
scene.add(stars);
// -------------------------------------------------------------------------
// Direct camera controls: rotate, zoom, pan, reset
// -------------------------------------------------------------------------
const defaultTarget = new THREE.Vector3(-2.8, 0, 0);
const cameraTarget = defaultTarget.clone();
let cameraRadius = 19.5;
let cameraTheta = 0.58;
let cameraPhi = 0.78;
function updateCamera() {
const offset = new THREE.Vector3().setFromSphericalCoords(
cameraRadius,
cameraPhi,
cameraTheta
);
camera.position.copy(cameraTarget).add(offset);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraTarget.copy(defaultTarget);
cameraRadius = 19.5;
cameraTheta = 0.58;
cameraPhi = 0.78;
updateCamera();
}
updateCamera();
let dragging = false;
let dragMode = "rotate";
let lastPointerX = 0;
let lastPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
dragMode =
event.button === 2 || event.shiftKey ? "pan" : "rotate";
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.classList.add("dragging");
event.preventDefault();
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (dragMode === "rotate") {
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi + dy * 0.005,
0.18,
1.43
);
} else {
const right = new THREE.Vector3(
1, 0, 0
).applyQuaternion(camera.quaternion);
const up = new THREE.Vector3(
0, 1, 0
).applyQuaternion(camera.quaternion);
const scale = cameraRadius * 0.0015;
cameraTarget
.addScaledVector(right, -dx * scale)
.addScaledVector(up, dy * scale);
}
updateCamera();
});
function endDrag(event) {
dragging = false;
renderer.domElement.classList.remove("dragging");
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
9,
44
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
// -------------------------------------------------------------------------
// Interface
// -------------------------------------------------------------------------
const dayValue = document.querySelector("#dayValue");
const radiusValue = document.querySelector("#radiusValue");
const velocityValue = document.querySelector("#velocityValue");
const areaValue = document.querySelector("#areaValue");
const equalBars = document.querySelector("#equalBars");
const scrub = document.querySelector("#scrub");
const playButton = document.querySelector("#playButton");
const speedSlider = document.querySelector("#speedSlider");
const speedValue = document.querySelector("#speedValue");
const barElements = [];
for (let i = 0; i < SECTOR_COUNT; i++) {
const bar = document.createElement("div");
bar.className = "bar";
bar.style.background = sectorColors[i].getStyle();
bar.title =
`Slice ${i + 1}: ` +
`Δt = ${exactSliceTime.toFixed(3)} days, ` +
`ΔA = ${exactSliceArea.toFixed(4)} square units`;
equalBars.appendChild(bar);
barElements.push(bar);
}
let maxAreaError = 0;
for (const area of measuredAreas) {
maxAreaError = Math.max(
maxAreaError,
Math.abs(area - exactSliceArea) / exactSliceArea
);
}
areaValue.textContent =
`Δt ${exactSliceTime.toFixed(2)} d · ` +
`ΔA ${exactSliceArea.toFixed(3)} u²`;
let phase = 0;
let playing = true;
let speedMultiplier = 1;
let previousSector = -1;
let scrubbing = false;
let resumeAfterScrub = false;
function updatePlayButton() {
playButton.textContent = playing ? "Pause" : "Play";
}
playButton.addEventListener("click", () => {
playing = !playing;
updatePlayButton();
});
document.querySelector("#restartButton").addEventListener("click", () => {
phase = 0;
});
document.querySelector("#resetViewButton").addEventListener(
"click",
resetCamera
);
speedSlider.addEventListener("input", () => {
speedMultiplier = Number(speedSlider.value);
speedValue.textContent = `${speedMultiplier.toFixed(2).replace(/0$/, "")}×`;
});
scrub.addEventListener("pointerdown", () => {
scrubbing = true;
resumeAfterScrub = playing;
playing = false;
updatePlayButton();
});
scrub.addEventListener("input", () => {
phase = (Number(scrub.value) / Number(scrub.max)) * TAU;
});
function finishScrub() {
if (!scrubbing) return;
scrubbing = false;
playing = resumeAfterScrub;
updatePlayButton();
}
scrub.addEventListener("pointerup", finishScrub);
scrub.addEventListener("pointercancel", finishScrub);
function bindVisibilityButton(id, object) {
const button = document.querySelector(id);
button.addEventListener("click", () => {
object.visible = !object.visible;
button.classList.toggle("active", object.visible);
button.setAttribute(
"aria-pressed",
String(object.visible)
);
});
}
bindVisibilityButton("#pathButton", path);
bindVisibilityButton("#areaButton", areaGroup);
bindVisibilityButton("#trailButton", trail);
window.addEventListener("keydown", (event) => {
const tag = document.activeElement?.tagName;
if (tag === "INPUT" || tag === "BUTTON") return;
if (event.code === "Space") {
event.preventDefault();
playing = !playing;
updatePlayButton();
}
if (event.code === "KeyR") {
resetCamera();
}
});
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
const planetPosition = new THREE.Vector3();
const tangent = new THREE.Vector3();
let statsTimer = 0;
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
if (playing && !scrubbing) {
phase +=
(TAU * delta * speedMultiplier) /
REAL_PERIOD_SECONDS;
phase %= TAU;
}
const sectorIndex = Math.min(
SECTOR_COUNT - 1,
Math.floor(phase / orbitStep)
);
if (sectorIndex !== previousSector) {
barElements.forEach((bar, index) => {
bar.classList.toggle("active", index === sectorIndex);
});
previousSector = sectorIndex;
}
for (let i = 0; i < SECTOR_COUNT; i++) {
if (i < sectorIndex) {
sectorMeshes[i].material.opacity = 0.105;
} else if (i === sectorIndex) {
sectorMeshes[i].material.opacity = 0.025;
} else {
sectorMeshes[i].material.opacity = 0.018;
}
}
updateActiveSweep(sectorIndex, phase);
activeSweep.material.color
.copy(sectorColors[sectorIndex])
.lerp(white, 0.32);
const E = solveKepler(phase);
positionAtMean(phase, planetPosition);
planet.position.set(
planetPosition.x,
0.29,
planetPosition.z
);
planet.rotation.y += delta * 0.9;
planet.rotation.x = Math.sin(phase * 0.5) * 0.08;
// Analytic equal-time trail.
for (let i = 0; i < 72; i++) {
let trailMean = phase - (i + 1) * 0.028;
if (trailMean < 0) trailMean += TAU;
const p = positionAtMean(trailMean, new THREE.Vector3());
const fade = 1 - i / 72;
dummy.position.set(p.x, 0.14, p.z);
dummy.rotation.set(0, 0, 0);
dummy.scale.setScalar(0.2 + fade * 0.85);
dummy.updateMatrix();
trail.setMatrixAt(i, dummy.matrix);
const trailColor = new THREE.Color(0x70f4ff).lerp(
new THREE.Color(0x9e7cff),
i / 71
);
trail.setColorAt(i, trailColor);
}
trail.instanceMatrix.needsUpdate = true;
trail.instanceColor.needsUpdate = true;
// d(position)/d(M), normalized to obtain the tangent.
const dEdM = 1 / (1 - ORBIT.e * Math.cos(E));
tangent.set(
-ORBIT.a * Math.sin(E) * dEdM,
0,
ORBIT.b * Math.cos(E) * dEdM
);
tangent.normalize();
const radius = ORBIT.a * (1 - ORBIT.e * Math.cos(E));
const velocity =
Math.sqrt(
(1 + ORBIT.e * Math.cos(E)) /
(1 - ORBIT.e * Math.cos(E))
);
velocityArrow.position.set(
planetPosition.x,
0.35,
planetPosition.z
);
velocityArrow.setDirection(tangent);
velocityArrow.setLength(
Math.max(0.55, velocity * 1.25),
0.3,
0.18
);
if (!scrubbing) {
scrub.value = String((phase / TAU) * Number(scrub.max));
}
statsTimer += delta;
if (statsTimer > 0.08) {
statsTimer = 0;
dayValue.textContent =
`${((phase / TAU) * ORBIT_DAYS).toFixed(2)} / ${ORBIT_DAYS}`;
radiusValue.textContent = `${radius.toFixed(3)} u`;
velocityValue.textContent = `${velocity.toFixed(3)} v₀`;
}
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
renderer.setAnimationLoop(animate);
document.querySelector("#loading").remove();
</script>
</body>
</html>
```