Prompt specification
Build or customize the Three.js 3D scene "Distance Changes Differential Gravity" 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: Distance Changes Differential Gravity
Category: Space & Earth · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/distance-changes-differential-gravity-x3840
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing a low-poly tidal-acceleration comparison. Place a fixed-size spherical body at several selectable distances from a larger attracting mass. Mark points on its near surface, center, and far surface, and calculate gravitational acceleration at each under a stated Newtonian toy model. Subtract the center acceleration to display the differential vectors responsible for the comparison. Keep the body size fixed as distance changes and label the exaggerated vector scale separately from physical units. A small graph can plot the differential magnitude against separation, with invalid overlapping configurations excluded instead of silently clamped into a plausible-looking result.
Working Three.js Starter (distance-changes-differential-gravity-x3840):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Newtonian Tidal Acceleration Comparison</title>
<style>
:root {
color-scheme: dark;
--bg: #070b14;
--panel: rgba(15, 23, 39, 0.94);
--panel-2: rgba(24, 35, 56, 0.78);
--border: rgba(151, 174, 211, 0.18);
--text: #edf4ff;
--muted: #9eb0ca;
--cyan: #55e5e6;
--pink: #ff73d2;
--green: #80eda2;
--orange: #ffad61;
--red: #ff5572;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
min-height: 100%;
background:
radial-gradient(circle at 15% 0%, #182641 0, transparent 35%),
radial-gradient(circle at 100% 25%, #251735 0, transparent 32%),
var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
padding: 18px;
}
header {
width: min(1500px, 100%);
margin: 0 auto 14px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18px;
}
h1 {
margin: 0 0 5px;
font-size: clamp(1.35rem, 2.6vw, 2rem);
letter-spacing: -0.035em;
}
header p {
margin: 0;
color: var(--muted);
font-size: 0.91rem;
max-width: 850px;
line-height: 1.45;
}
.model-chip {
flex: 0 0 auto;
border: 1px solid var(--border);
border-radius: 999px;
padding: 8px 12px;
background: rgba(15, 23, 39, 0.72);
color: #c8d8ef;
font-size: 0.76rem;
white-space: nowrap;
}
main {
width: min(1500px, 100%);
margin: 0 auto;
display: grid;
grid-template-columns: minmax(0, 1fr) 405px;
gap: 14px;
align-items: start;
}
#scenePanel {
position: relative;
min-height: 690px;
height: calc(100vh - 118px);
overflow: hidden;
border: 1px solid var(--border);
border-radius: 17px;
background: #080d18;
box-shadow: 0 25px 80px rgba(0, 0, 0, 0.35);
}
#view {
position: absolute;
inset: 0;
}
#view canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#view canvas:active { cursor: grabbing; }
.hud {
position: absolute;
z-index: 3;
pointer-events: none;
border: 1px solid var(--border);
border-radius: 12px;
background: rgba(8, 14, 27, 0.78);
backdrop-filter: blur(9px);
}
.legend {
top: 14px;
left: 14px;
padding: 11px 13px;
min-width: 225px;
}
.legend-title {
font-size: 0.74rem;
text-transform: uppercase;
letter-spacing: 0.13em;
color: #b9c9df;
margin-bottom: 8px;
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
margin-top: 5px;
font-size: 0.79rem;
color: #dce8f8;
}
.dot {
display: inline-block;
width: 9px;
height: 9px;
border-radius: 50%;
flex: 0 0 auto;
box-shadow: 0 0 12px currentColor;
}
.dot.cyan { background: var(--cyan); color: var(--cyan); }
.dot.pink { background: var(--pink); color: var(--pink); }
.dot.green { background: var(--green); color: var(--green); }
.dot.orange { background: var(--orange); color: var(--orange); }
.scene-help {
left: 14px;
bottom: 14px;
padding: 9px 12px;
color: #b9c9df;
font-size: 0.76rem;
}
#resetView {
position: absolute;
z-index: 4;
right: 14px;
top: 14px;
pointer-events: auto;
}
button {
appearance: none;
border: 1px solid var(--border);
border-radius: 8px;
background: rgba(27, 40, 64, 0.9);
color: var(--text);
padding: 7px 10px;
font: inherit;
font-size: 0.76rem;
cursor: pointer;
transition: border-color 120ms, background 120ms, transform 120ms;
}
button:hover {
border-color: rgba(170, 203, 245, 0.52);
background: rgba(40, 57, 88, 0.95);
transform: translateY(-1px);
}
button.active {
border-color: #68a8ff;
background: rgba(48, 104, 177, 0.55);
}
#invalidWarning {
position: absolute;
z-index: 5;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
display: none;
width: min(470px, calc(100% - 34px));
padding: 16px 18px;
border: 1px solid rgba(255, 85, 114, 0.65);
border-radius: 12px;
background: rgba(61, 8, 22, 0.9);
box-shadow: 0 16px 55px rgba(0, 0, 0, 0.45);
color: #ffe8ed;
line-height: 1.45;
font-size: 0.87rem;
}
#invalidWarning.show { display: block; }
#invalidWarning strong {
display: block;
margin-bottom: 4px;
color: #ff8ba0;
font-size: 1rem;
}
aside {
display: grid;
gap: 12px;
}
.card {
border: 1px solid var(--border);
border-radius: 14px;
padding: 14px;
background: var(--panel);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.18);
}
.card h2 {
margin: 0 0 11px;
font-size: 0.84rem;
letter-spacing: 0.08em;
text-transform: uppercase;
color: #c7d7eb;
}
.control-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 10px;
}
.control-head label {
font-size: 0.82rem;
color: #dce8f8;
}
output {
font-variant-numeric: tabular-nums;
color: #8fc7ff;
font-size: 0.83rem;
font-weight: 700;
}
output.invalid { color: var(--red); }
input[type="range"] {
width: 100%;
margin: 8px 0 4px;
accent-color: #6db5ff;
cursor: pointer;
}
.presets {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 9px;
}
.presets button {
min-width: 48px;
padding: 6px 8px;
font-variant-numeric: tabular-nums;
}
.small {
color: var(--muted);
font-size: 0.74rem;
line-height: 1.45;
}
.note {
margin: 9px 0 0;
padding: 9px 10px;
border-left: 3px solid #568ccc;
background: rgba(56, 98, 151, 0.13);
color: #b8cae0;
font-size: 0.75rem;
line-height: 1.45;
}
.note.warning-note {
border-left-color: var(--red);
background: rgba(160, 33, 61, 0.14);
color: #ffc2cd;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 0.72rem;
font-variant-numeric: tabular-nums;
}
th {
color: #91a7c3;
font-weight: 600;
text-align: left;
padding: 0 5px 7px 0;
white-space: nowrap;
}
td {
padding: 8px 5px 8px 0;
border-top: 1px solid rgba(151, 174, 211, 0.12);
color: #d9e5f5;
white-space: nowrap;
}
td:nth-child(2), td:nth-child(3) {
font-size: 0.68rem;
color: #b7c8dd;
}
.sample-label {
display: inline-flex;
align-items: center;
gap: 6px;
font-weight: 650;
}
#graph {
display: block;
width: 100%;
height: 225px;
margin-top: 3px;
cursor: crosshair;
}
.graph-caption {
display: flex;
justify-content: space-between;
gap: 10px;
margin-top: 2px;
color: var(--muted);
font-size: 0.71rem;
}
details summary {
cursor: pointer;
color: #c7d7eb;
font-size: 0.82rem;
font-weight: 650;
}
details p {
color: var(--muted);
font-size: 0.75rem;
line-height: 1.5;
}
code {
color: #a9d4ff;
font-size: 0.72rem;
}
@media (max-width: 1050px) {
main {
grid-template-columns: 1fr;
}
#scenePanel {
height: 62vh;
min-height: 500px;
}
aside {
grid-template-columns: repeat(2, minmax(0, 1fr));
align-items: start;
}
}
@media (max-width: 660px) {
body { padding: 9px; }
header { flex-direction: column; }
.model-chip { white-space: normal; }
#scenePanel { min-height: 470px; }
aside { grid-template-columns: 1fr; }
.legend { min-width: 205px; }
}
</style>
</head>
<body>
<header>
<div>
<h1>Newtonian Tidal-Acceleration Comparison</h1>
<p>
A fixed-radius test body is placed at several center-to-center separations from a
larger attracting point mass. Near-surface, center, and far-surface gravitational
accelerations are evaluated, then the center acceleration is subtracted.
</p>
</div>
<div class="model-chip">External point mass · self-gravity omitted · toy units</div>
</header>
<main>
<section id="scenePanel" aria-label="Interactive three-dimensional model">
<div id="view"></div>
<div class="hud legend">
<div class="legend-title">Displayed differential vectors</div>
<div class="legend-row">
<span class="dot cyan"></span>
<span>Near-surface Δa = a<sub>near</sub> − a<sub>center</sub></span>
</div>
<div class="legend-row">
<span class="dot pink"></span>
<span>Far-surface Δa = a<sub>far</sub> − a<sub>center</sub></span>
</div>
<div class="legend-row">
<span class="dot green"></span>
<span>Center sample: Δa = 0</span>
</div>
<div class="legend-row">
<span class="dot orange"></span>
<span>Fixed test body, radius 1 L₀</span>
</div>
</div>
<button id="resetView" type="button">Reset view</button>
<div class="hud scene-help">
Drag to orbit · wheel to zoom · double-click to reset
</div>
<div id="invalidWarning" role="alert">
<strong>Invalid overlapping configuration</strong>
<span id="invalidText"></span>
</div>
</section>
<aside>
<section class="card">
<h2>Configuration</h2>
<div class="control-head">
<label for="distance">Center separation D</label>
<output id="distanceValue">8.00 L₀</output>
</div>
<input id="distance" type="range" min="2" max="20" step="0.1" value="8">
<div class="presets" aria-label="Preset separations">
<button type="button" data-distance="4">4</button>
<button type="button" data-distance="4.5">4.5</button>
<button type="button" data-distance="6">6</button>
<button type="button" data-distance="8" class="active">8</button>
<button type="button" data-distance="12">12</button>
<button type="button" data-distance="16">16</button>
</div>
<div class="control-head">
<label for="vectorScale">Vector display multiplier s</label>
<output id="scaleValue">0.12 scene L / model accel unit</output>
</div>
<input id="vectorScale" type="range" min="0.02" max="0.40" step="0.01" value="0.12">
<p class="note">
Arrow length is <code>s × |Δa|</code>. This is an exaggerated, visualization-only
scale. It is separate from the physical/model units used in the table and graph.
The body radius never changes with D.
</p>
<p class="note warning-note">
If D < 4 L₀, the displayed solid spheres overlap. The model then reports
“invalid,” computes no differential vectors, and excludes that separation from
valid graph points.
</p>
</section>
<section class="card">
<h2>Acceleration comparison</h2>
<table>
<thead>
<tr>
<th>Sample</th>
<th>Raw a (x, y, z)</th>
<th>Δa (x, y, z)</th>
<th>|Δa|</th>
</tr>
</thead>
<tbody id="resultRows"></tbody>
</table>
<p id="resultNote" class="small"></p>
</section>
<section class="card">
<h2>Differential magnitude vs. separation</h2>
<canvas id="graph" aria-label="Graph of differential acceleration magnitude versus separation"></canvas>
<div class="graph-caption">
<span><span class="dot cyan"></span> Near surface</span>
<span><span class="dot pink"></span> Far surface</span>
</div>
<p class="small">
Click the graph to select D. The shaded region is excluded because the solid
bodies overlap. Vertical scale is in model acceleration units.
</p>
</section>
<section class="card">
<details open>
<summary>Stated toy model and units</summary>
<p>
The attractor is treated as a point mass at the origin. Choose model length
unit L₀, time unit T₀, mass unit M₀, <code>G = 1</code>, and
<code>M = 1000 M₀</code>. Thus <code>GM = 1000 L₀³/T₀²</code>.
</p>
<p>
Along the separation axis, with the attractor at x = 0 and the test-body
center at x = D:
<br><code>a(x) = −GM x / |x|³</code>.
<br>
The sample positions are
<code>x_near = D − 1</code>,
<code>x_center = D</code>, and
<code>x_far = D + 1</code>.
</p>
<p>
Displayed vectors use
<code>Δa = a(sample) − a(center)</code>. The far-surface residual points
away from the attractor because that point feels less inward acceleration
than the center. Body self-gravity, finite-size attraction, relativistic
effects, and tides from other bodies are intentionally omitted.
</p>
</details>
</section>
</aside>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Model constants
// ------------------------------------------------------------
const G = 1;
const MASS = 1000;
const GM = G * MASS;
const ATTRACTOR_RADIUS = 3;
const BODY_RADIUS = 1;
const CONTACT_DISTANCE = ATTRACTOR_RADIUS + BODY_RADIUS;
const MIN_DISTANCE = 2;
const MAX_DISTANCE = 20;
let separation = 8;
let vectorScale = 0.12;
const $ = id => document.getElementById(id);
const view = $("view");
const distanceInput = $("distance");
const scaleInput = $("vectorScale");
const distanceValue = $("distanceValue");
const scaleValue = $("scaleValue");
const resultRows = $("resultRows");
const resultNote = $("resultNote");
const invalidWarning = $("invalidWarning");
const invalidText = $("invalidText");
const graphCanvas = $("graph");
const graphContext = graphCanvas.getContext("2d");
const isValidSeparation = d => d >= CONTACT_DISTANCE - 1e-10;
// ------------------------------------------------------------
// Three.js scene
// ------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x080d18);
scene.fog = new THREE.Fog(0x080d18, 35, 85);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
view.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 200);
const cameraTarget = new THREE.Vector3(separation / 2, 0, 0);
let cameraYaw = 0.62;
let cameraPitch = 0.38;
let cameraRadius = 23;
function updateCamera() {
const horizontal = cameraRadius * Math.cos(cameraPitch);
camera.position.set(
cameraTarget.x + horizontal * Math.sin(cameraYaw),
cameraTarget.y + cameraRadius * Math.sin(cameraPitch),
cameraTarget.z + horizontal * Math.cos(cameraYaw)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraYaw = 0.62;
cameraPitch = 0.38;
cameraRadius = Math.max(23, separation * 1.35);
updateCamera();
}
scene.add(new THREE.HemisphereLight(0xc6dcff, 0x15131d, 2.0));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.0);
keyLight.position.set(9, 13, 11);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x8e7bff, 1.6);
rimLight.position.set(-12, 6, -8);
scene.add(rimLight);
const attractorMaterial = new THREE.MeshStandardMaterial({
color: 0xff9b45,
emissive: 0x5b2100,
emissiveIntensity: 0.35,
roughness: 0.72,
metalness: 0.08,
flatShading: true
});
const attractor = new THREE.Mesh(
new THREE.IcosahedronGeometry(ATTRACTOR_RADIUS, 2),
attractorMaterial
);
scene.add(attractor);
const attractorEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(attractor.geometry, 18),
new THREE.LineBasicMaterial({ color: 0xffd09a, transparent: true, opacity: 0.24 })
);
attractor.add(attractorEdges);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0x4d8dff,
emissive: 0x071a35,
emissiveIntensity: 0.75,
roughness: 0.54,
metalness: 0.16,
flatShading: true
});
const body = new THREE.Mesh(
new THREE.IcosahedronGeometry(BODY_RADIUS, 1),
bodyMaterial
);
body.position.x = separation;
scene.add(body);
const bodyEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(body.geometry, 15),
new THREE.LineBasicMaterial({ color: 0x9cc7ff, transparent: true, opacity: 0.4 })
);
body.add(bodyEdges);
const ground = new THREE.GridHelper(60, 30, 0x334761, 0x172338);
ground.position.y = -3.08;
ground.material.transparent = true;
ground.material.opacity = 0.48;
scene.add(ground);
const separationGeometry = new THREE.BufferGeometry();
separationGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute([0, 0, 0, separation, 0, 0], 3)
);
const separationLine = new THREE.Line(
separationGeometry,
new THREE.LineDashedMaterial({
color: 0x8ba7c7,
dashSize: 0.45,
gapSize: 0.25,
transparent: true,
opacity: 0.65
})
);
separationLine.computeLineDistances();
scene.add(separationLine);
function makeMarker(color) {
const marker = new THREE.Mesh(
new THREE.SphereGeometry(0.105, 14, 10),
new THREE.MeshBasicMaterial({ color })
);
scene.add(marker);
return marker;
}
const nearMarker = makeMarker(0x55e5e6);
const centerMarker = makeMarker(0x80eda2);
const farMarker = makeMarker(0xff73d2);
function createLabel(initialText, color = "#eef6ff") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
fog: false
});
const sprite = new THREE.Sprite(material);
sprite.renderOrder = 20;
function setText(text) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(7, 13, 26, 0.82)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = "rgba(157, 187, 225, 0.35)";
context.lineWidth = 3;
context.strokeRect(2, 2, canvas.width - 4, canvas.height - 4);
context.fillStyle = color;
context.font = "600 31px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 1);
texture.needsUpdate = true;
}
setText(initialText);
return { sprite, setText };
}
const attractorLabel = createLabel("Attractor: point mass M = 1000", "#ffd099");
attractorLabel.sprite.position.set(0, 3.75, 0);
attractorLabel.sprite.scale.set(4.8, 1.2, 1);
scene.add(attractorLabel.sprite);
const bodyLabel = createLabel("Fixed body: radius 1 L₀", "#b8d9ff");
bodyLabel.sprite.scale.set(3.8, 0.95, 1);
scene.add(bodyLabel.sprite);
const nearLabel = createLabel("Near surface", "#55e5e6");
nearLabel.sprite.scale.set(2.45, 0.62, 1);
scene.add(nearLabel.sprite);
const centerLabel = createLabel("Center", "#80eda2");
centerLabel.sprite.scale.set(2.1, 0.62, 1);
scene.add(centerLabel.sprite);
const farLabel = createLabel("Far surface", "#ff73d2");
farLabel.sprite.scale.set(2.45, 0.62, 1);
scene.add(farLabel.sprite);
const distanceLabel = createLabel("D = 8.00 L₀", "#d8e7fa");
distanceLabel.sprite.scale.set(2.8, 0.7, 1);
scene.add(distanceLabel.sprite);
const nearArrow = new THREE.ArrowHelper(
new THREE.Vector3(-1, 0, 0),
new THREE.Vector3(),
1,
0x55e5e6,
0.3,
0.18
);
scene.add(nearArrow);
const farArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1,
0xff73d2,
0.3,
0.18
);
scene.add(farArrow);
// ------------------------------------------------------------
// Direct camera controls: no addons or example modules
// ------------------------------------------------------------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraYaw -= dx * 0.006;
cameraPitch += dy * 0.005;
cameraPitch = THREE.MathUtils.clamp(cameraPitch, -1.25, 1.25);
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();
cameraRadius *= Math.exp(event.deltaY * 0.001);
cameraRadius = THREE.MathUtils.clamp(cameraRadius, 8, 75);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
$("resetView").addEventListener("click", resetCamera);
// ------------------------------------------------------------
// Newtonian toy-model calculations
// ------------------------------------------------------------
function accelerationAtX(x) {
// The attractor is at x=0 and all valid sample positions are x > 0.
return new THREE.Vector3(-GM / (x * x), 0, 0);
}
function computeModel(d) {
const center = accelerationAtX(d);
const near = accelerationAtX(d - BODY_RADIUS);
const far = accelerationAtX(d + BODY_RADIUS);
return {
center,
near,
far,
deltaNear: near.clone().sub(center),
deltaCenter: center.clone().sub(center),
deltaFar: far.clone().sub(center)
};
}
function formatVector(vector) {
return `(${vector.x.toFixed(2)}, ${vector.y.toFixed(2)}, ${vector.z.toFixed(2)})`;
}
function updateArrow(arrow, x, delta, valid) {
const magnitude = delta.length();
if (!valid || magnitude < 1e-12) {
arrow.visible = false;
return;
}
arrow.visible = true;
arrow.position.set(x, 0, 0);
arrow.setDirection(delta.clone().normalize());
const renderedLength = magnitude * vectorScale;
const headLength = Math.min(0.55, Math.max(0.12, renderedLength * 0.22));
const headWidth = Math.min(0.32, Math.max(0.08, renderedLength * 0.12));
arrow.setLength(renderedLength, headLength, headWidth);
}
function updatePresetButtons() {
document.querySelectorAll("[data-distance]").forEach(button => {
const value = Number(button.dataset.distance);
button.classList.toggle("active", Math.abs(value - separation) < 0.001);
});
}
function setSeparation(value) {
const next = Number(value);
if (!Number.isFinite(next)) return;
const oldTargetX = cameraTarget.x;
separation = next;
cameraTarget.x = separation / 2;
// Keep the relative camera framing while the target follows the midpoint.
camera.position.x += cameraTarget.x - oldTargetX;
// Ensure a larger separation remains comfortably visible.
const suggestedRadius = Math.max(23, separation * 1.35);
if (suggestedRadius > cameraRadius) cameraRadius = suggestedRadius;
distanceInput.value = String(separation);
updateCamera();
updateAll();
}
function updateAll() {
const valid = isValidSeparation(separation);
distanceValue.textContent = `${separation.toFixed(2)} L₀`;
distanceValue.classList.toggle("invalid", !valid);
scaleValue.textContent =
`${vectorScale.toFixed(2)} scene L / model accel unit`;
body.position.x = separation;
bodyLabel.sprite.position.set(separation, 1.8, 0);
distanceLabel.sprite.position.set(separation / 2, 0.85, 0);
distanceLabel.setText(`D = ${separation.toFixed(2)} L₀`);
const positions = separationGeometry.attributes.position;
positions.setXYZ(0, 0, 0, 0);
positions.setXYZ(1, separation, 0, 0);
positions.needsUpdate = true;
separationGeometry.computeBoundingSphere();
separationLine.computeLineDistances();
nearMarker.position.set(separation - BODY_RADIUS, 0, 0);
centerMarker.position.set(separation, 0, 0);
farMarker.position.set(separation + BODY_RADIUS, 0, 0);
nearLabel.sprite.position.set(separation - BODY_RADIUS, 1.1, 0);
centerLabel.sprite.position.set(separation, 1.1, 0);
farLabel.sprite.position.set(separation + BODY_RADIUS, 1.1, 0);
nearMarker.visible = valid;
centerMarker.visible = valid;
farMarker.visible = valid;
nearLabel.sprite.visible = valid;
centerLabel.sprite.visible = valid;
farLabel.sprite.visible = valid;
if (valid) {
bodyMaterial.color.set(0x4d8dff);
bodyMaterial.emissive.set(0x071a35);
bodyEdges.material.color.set(0x9cc7ff);
invalidWarning.classList.remove("show");
const model = computeModel(separation);
updateArrow(
nearArrow,
separation - BODY_RADIUS,
model.deltaNear,
valid
);
updateArrow(
farArrow,
separation + BODY_RADIUS,
model.deltaFar,
valid
);
resultRows.innerHTML = `
<tr>
<td><span class="sample-label"><span class="dot cyan"></span>Near</span></td>
<td>${formatVector(model.near)}</td>
<td>${formatVector(model.deltaNear)}</td>
<td>${model.deltaNear.length().toFixed(3)}</td>
</tr>
<tr>
<td><span class="sample-label"><span class="dot green"></span>Center</span></td>
<td>${formatVector(model.center)}</td>
<td>${formatVector(model.deltaCenter)}</td>
<td>0.000</td>
</tr>
<tr>
<td><span class="sample-label"><span class="dot pink"></span>Far</span></td>
<td>${formatVector(model.far)}</td>
<td>${formatVector(model.deltaFar)}</td>
<td>${model.deltaFar.length().toFixed(3)}</td>
</tr>
`;
resultNote.textContent =
`Unscaled model acceleration units (L₀/T₀²). ` +
`Displayed arrows use the separate multiplier s = ${vectorScale.toFixed(2)}.`;
} else {
bodyMaterial.color.set(0xff4968);
bodyMaterial.emissive.set(0x410715);
bodyEdges.material.color.set(0xffa3b2);
nearArrow.visible = false;
farArrow.visible = false;
invalidWarning.classList.add("show");
invalidText.textContent =
`At D = ${separation.toFixed(2)} L₀, the solid bodies overlap ` +
`(D < ${CONTACT_DISTANCE.toFixed(0)} L₀). No acceleration comparison is computed, ` +
`and this separation is not included as a valid graph point.`;
resultRows.innerHTML = `
<tr>
<td><span class="sample-label"><span class="dot cyan"></span>Near</span></td>
<td>—</td><td>—</td><td>—</td>
</tr>
<tr>
<td><span class="sample-label"><span class="dot green"></span>Center</span></td>
<td>—</td><td>—</td><td>—</td>
</tr>
<tr>
<td><span class="sample-label"><span class="dot pink"></span>Far</span></td>
<td>—</td><td>—</td><td>—</td>
</tr>
`;
resultNote.textContent =
"Invalid overlapping configuration: values are intentionally omitted rather than clamped.";
}
updatePresetButtons();
drawGraph();
}
// ------------------------------------------------------------
// 2D graph, drawn directly on canvas
// ------------------------------------------------------------
let graphWidth = 0;
let graphHeight = 0;
let graphPixelRatio = 1;
function differentialMagnitudes(d) {
const center = accelerationAtX(d);
const nearDelta = accelerationAtX(d - BODY_RADIUS).sub(center);
const farDelta = accelerationAtX(d + BODY_RADIUS).sub(center);
return {
near: nearDelta.length(),
far: farDelta.length()
};
}
let graphYMaximum = 50;
{
let maximum = 0;
for (let i = 0; i <= 500; i++) {
const d = CONTACT_DISTANCE +
(MAX_DISTANCE - CONTACT_DISTANCE) * i / 500;
const values = differentialMagnitudes(d);
maximum = Math.max(maximum, values.near, values.far);
}
graphYMaximum = Math.ceil(maximum / 10) * 10;
}
function resizeGraph() {
const rect = graphCanvas.getBoundingClientRect();
graphPixelRatio = Math.min(window.devicePixelRatio || 1, 2);
graphWidth = rect.width;
graphHeight = rect.height;
graphCanvas.width = Math.round(rect.width * graphPixelRatio);
graphCanvas.height = Math.round(rect.height * graphPixelRatio);
drawGraph();
}
function drawGraph() {
if (!graphWidth || !graphHeight) return;
const ctx = graphContext;
const w = graphWidth;
const h = graphHeight;
ctx.setTransform(graphPixelRatio, 0, 0, graphPixelRatio, 0, 0);
ctx.clearRect(0, 0, w, h);
const margin = { left: 47, right: 13, top: 29, bottom: 34 };
const plotWidth = w - margin.left - margin.right;
const plotHeight = h - margin.top - margin.bottom;
const plotBottom = margin.top + plotHeight;
const xToPixel = d =>
margin.left + (d - MIN_DISTANCE) / (MAX_DISTANCE - MIN_DISTANCE) * plotWidth;
const yToPixel = value =>
plotBottom - value / graphYMaximum * plotHeight;
// Invalid/overlap region.
ctx.fillStyle = "rgba(255, 65, 93, 0.12)";
ctx.fillRect(
xToPixel(MIN_DISTANCE),
margin.top,
xToPixel(CONTACT_DISTANCE) - xToPixel(MIN_DISTANCE),
plotHeight
);
ctx.fillStyle = "rgba(255, 110, 135, 0.8)";
ctx.font = "10px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.fillText(
"excluded",
(xToPixel(MIN_DISTANCE) + xToPixel(CONTACT_DISTANCE)) / 2,
margin.top + 13
);
// Grid and axes.
ctx.strokeStyle = "rgba(157, 184, 220, 0.12)";
ctx.lineWidth = 1;
ctx.fillStyle = "#91a7c3";
ctx.font = "10px system-ui, sans-serif";
ctx.textAlign = "right";
for (let value = 0; value <= graphYMaximum; value += 10) {
const y = yToPixel(value);
ctx.beginPath();
ctx.moveTo(margin.left, y);
ctx.lineTo(w - margin.right, y);
ctx.stroke();
ctx.fillText(String(value), margin.left - 7, y + 3);
}
ctx.textAlign = "center";
for (const value of [2, 4, 8, 12, 16, 20]) {
const x = xToPixel(value);
ctx.strokeStyle = "rgba(157, 184, 220, 0.12)";
ctx.beginPath();
ctx.moveTo(x, margin.top);
ctx.lineTo(x, plotBottom);
ctx.stroke();
ctx.fillText(String(value), x, plotBottom + 15);
}
ctx.strokeStyle = "rgba(190, 211, 240, 0.46)";
ctx.beginPath();
ctx.moveTo(margin.left, margin.top);
ctx.lineTo(margin.left, plotBottom);
ctx.lineTo(w - margin.right, plotBottom);
ctx.stroke();
// Valid curves only: D >= contact distance.
const series = [
{ key: "near", color: "#55e5e6" },
{ key: "far", color: "#ff73d2" }
];
for (const item of series) {
ctx.strokeStyle = item.color;
ctx.lineWidth = 2;
ctx.beginPath();
for (let i = 0; i <= 360; i++) {
const d = CONTACT_DISTANCE +
(MAX_DISTANCE - CONTACT_DISTANCE) * i / 360;
const value = differentialMagnitudes(d)[item.key];
const x = xToPixel(d);
const y = yToPixel(value);
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.stroke();
}
// Current selection.
const currentX = xToPixel(separation);
const valid = isValidSeparation(separation);
ctx.save();
ctx.setLineDash(valid ? [3, 4] : [5, 4]);
ctx.strokeStyle = valid ? "rgba(225, 237, 255, 0.6)" : "#ff5572";
ctx.lineWidth = 1.25;
ctx.beginPath();
ctx.moveTo(currentX, margin.top);
ctx.lineTo(currentX, plotBottom);
ctx.stroke();
ctx.restore();
if (valid) {
const values = differentialMagnitudes(separation);
for (const item of series) {
ctx.fillStyle = item.color;
ctx.beginPath();
ctx.arc(currentX, yToPixel(values[item.key]), 4, 0, Math.PI * 2);
ctx.fill();
}
} else {
ctx.fillStyle = "#ff7790";
ctx.font = "600 10px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.fillText("OVERLAP", currentX, margin.top - 10);
}
ctx.fillStyle = "#91a7c3";
ctx.font = "10px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.fillText("Center separation D (L₀)", margin.left + plotWidth / 2, h - 5);
ctx.save();
ctx.translate(11, margin.top + plotHeight / 2);
ctx.rotate(-Math.PI / 2);
ctx.textAlign = "center";
ctx.fillText("|Δa| (model L₀/T₀²)", 0, 0);
ctx.restore();
}
graphCanvas.addEventListener("click", event => {
const rect = graphCanvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const margin = { left: 47, right: 13 };
const plotWidth = rect.width - margin.left - margin.right;
if (x < margin.left || x > rect.width - margin.right) return;
const fraction = (x - margin.left) / plotWidth;
const selected = MIN_DISTANCE + fraction * (MAX_DISTANCE - MIN_DISTANCE);
setSeparation(selected);
});
// ------------------------------------------------------------
// Controls and initialization
// ------------------------------------------------------------
distanceInput.addEventListener("input", event => {
setSeparation(event.target.value);
});
scaleInput.addEventListener("input", event => {
vectorScale = Number(event.target.value);
updateAll();
});
document.querySelectorAll("[data-distance]").forEach(button => {
button.addEventListener("click", () => {
setSeparation(button.dataset.distance);
});
});
function resizeScene() {
const rect = view.getBoundingClientRect();
renderer.setSize(rect.width, rect.height, false);
camera.aspect = rect.width / Math.max(1, rect.height);
camera.updateProjectionMatrix();
}
const sceneResizeObserver = new ResizeObserver(resizeScene);
sceneResizeObserver.observe(view);
const graphResizeObserver = new ResizeObserver(resizeGraph);
graphResizeObserver.observe(graphCanvas);
resizeScene();
resizeGraph();
resetCamera();
updateAll();
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
</script>
</body>
</html>
```