Prompt specification
Build or customize the Three.js 3D scene "Sphere great-circle route model" 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: Sphere great-circle route model
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/sphere-great-circle-route-model-x1697
Scene Description Prompt:
Place two points on a sphere and draw their shorter great-circle arc alongside a latitude-following route; distinguish surface distance from a straight chord through the sphere. Use Three.js from cdnjs in a single HTML file, with low-poly forms.
Working Three.js Starter (sphere-great-circle-route-model-x1697):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Great Circle vs. Straight Chord</title>
<style>
:root {
color-scheme: dark;
--cyan: #28e4ff;
--orange: #ff9f43;
--magenta: #e85cff;
--pink: #ff5470;
--yellow: #ffe66d;
--panel: rgba(8, 18, 31, 0.82);
--border: rgba(157, 207, 235, 0.18);
--muted: #8fa9bc;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 65% 40%, #0b2943 0%, #071321 38%, #03070d 78%);
color: #edf8ff;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
.glass {
background: var(--panel);
border: 1px solid var(--border);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(16px) saturate(125%);
-webkit-backdrop-filter: blur(16px) saturate(125%);
}
#controls {
position: fixed;
top: 18px;
left: 18px;
width: 338px;
max-height: calc(100vh - 36px);
padding: 18px;
border-radius: 18px;
overflow: auto;
scrollbar-width: thin;
}
h1 {
margin: 0;
font-size: 21px;
line-height: 1.15;
letter-spacing: -0.025em;
}
.subtitle {
margin: 8px 0 16px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.point-card {
padding: 12px;
margin-top: 10px;
border: 1px solid rgba(157, 207, 235, 0.12);
border-radius: 13px;
background: rgba(255, 255, 255, 0.025);
}
.point-head {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 9px;
font-size: 13px;
}
.point-head strong {
font-size: 13px;
}
.point-head .coordinates {
margin-left: auto;
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.point-badge {
display: inline-grid;
place-items: center;
width: 23px;
height: 23px;
border-radius: 7px;
color: #09111c;
font-weight: 800;
font-size: 12px;
}
.point-badge.a {
background: var(--pink);
box-shadow: 0 0 18px rgba(255, 84, 112, 0.3);
}
.point-badge.b {
background: var(--yellow);
box-shadow: 0 0 18px rgba(255, 230, 109, 0.25);
}
.range-row {
display: grid;
grid-template-columns: 34px 1fr 66px;
align-items: center;
gap: 8px;
min-height: 30px;
}
.range-row + .range-row {
margin-top: 5px;
}
.range-row label {
color: var(--muted);
font-size: 10px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.08em;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
accent-color: var(--cyan);
cursor: pointer;
}
input[type="number"] {
width: 66px;
padding: 5px 6px;
border: 1px solid rgba(157, 207, 235, 0.17);
border-radius: 7px;
background: rgba(2, 8, 15, 0.7);
color: #edf8ff;
font: 11px ui-monospace, SFMono-Regular, Menlo, monospace;
outline: none;
}
input[type="number"]:focus {
border-color: rgba(40, 228, 255, 0.7);
}
.actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 13px;
}
button {
border: 1px solid rgba(157, 207, 235, 0.18);
border-radius: 9px;
padding: 8px 9px;
background: rgba(255, 255, 255, 0.045);
color: #d9edf9;
font: 600 11px inherit;
cursor: pointer;
transition: background 150ms ease, border-color 150ms ease, transform 150ms ease;
}
button:hover {
background: rgba(40, 228, 255, 0.09);
border-color: rgba(40, 228, 255, 0.4);
}
button:active {
transform: translateY(1px);
}
button.active {
color: #061018;
border-color: var(--cyan);
background: var(--cyan);
}
.secondary-actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-top: 7px;
}
.hint {
min-height: 30px;
margin: 11px 1px 0;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.toggles {
display: flex;
flex-wrap: wrap;
gap: 13px;
margin-top: 11px;
padding-top: 11px;
border-top: 1px solid rgba(157, 207, 235, 0.1);
color: var(--muted);
font-size: 10px;
}
.toggles label {
display: flex;
align-items: center;
gap: 5px;
cursor: pointer;
}
.toggles input {
accent-color: var(--cyan);
}
#metrics {
position: fixed;
top: 18px;
right: 18px;
width: 274px;
padding: 16px;
border-radius: 18px;
}
.metrics-title {
margin-bottom: 12px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric {
position: relative;
padding: 11px 11px 11px 14px;
margin-top: 8px;
overflow: hidden;
border: 1px solid rgba(157, 207, 235, 0.1);
border-radius: 11px;
background: rgba(255, 255, 255, 0.025);
}
.metric::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 3px;
background: var(--metric-color);
box-shadow: 0 0 14px var(--metric-color);
}
.metric-label {
color: #b8ccda;
font-size: 10px;
}
.metric strong {
display: block;
margin-top: 3px;
color: #f4fbff;
font-size: 19px;
font-variant-numeric: tabular-nums;
letter-spacing: -0.025em;
}
.metric small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 9px;
}
.comparison-note {
margin: 12px 2px 0;
color: #a8bdcc;
font-size: 10px;
line-height: 1.5;
}
#legend {
position: fixed;
left: 50%;
bottom: 18px;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 17px;
padding: 10px 15px;
border-radius: 12px;
white-space: nowrap;
font-size: 10px;
color: #c4d7e4;
}
.legend-item {
display: flex;
align-items: center;
gap: 7px;
}
.swatch {
width: 23px;
height: 4px;
border-radius: 3px;
background: currentColor;
box-shadow: 0 0 9px currentColor;
}
.swatch.cyan {
color: var(--cyan);
}
.swatch.orange {
color: var(--orange);
}
.swatch.magenta {
color: var(--magenta);
}
.point-label {
position: fixed;
z-index: 5;
display: flex;
align-items: center;
gap: 5px;
padding: 4px 7px 4px 4px;
border: 1px solid rgba(157, 207, 235, 0.2);
border-radius: 8px;
background: rgba(4, 11, 19, 0.86);
box-shadow: 0 5px 18px rgba(0, 0, 0, 0.3);
pointer-events: none;
transform: translate(-50%, -145%);
font-size: 9px;
color: #d9eaf4;
font-variant-numeric: tabular-nums;
}
.point-label b {
display: grid;
place-items: center;
width: 18px;
height: 18px;
border-radius: 6px;
color: #07111b;
font-size: 10px;
}
#labelA b {
background: var(--pink);
}
#labelB b {
background: var(--yellow);
}
@media (max-width: 760px) {
#controls {
top: 10px;
left: 10px;
width: min(320px, calc(100vw - 20px));
max-height: 48vh;
padding: 14px;
}
#metrics {
top: auto;
right: 10px;
bottom: 10px;
width: min(255px, calc(100vw - 20px));
padding: 12px;
}
#legend {
display: none;
}
h1 {
font-size: 18px;
}
.metric {
padding: 8px 9px 8px 12px;
}
.metric strong {
font-size: 16px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<aside id="controls" class="glass">
<h1>Great Circle vs. Chord</h1>
<p class="subtitle">
Compare the shortest path over a sphere with a latitude-grid route
and a straight line through its interior.
</p>
<div class="point-card">
<div class="point-head">
<span class="point-badge a">A</span>
<strong>Point A</strong>
<span id="coordA" class="coordinates"></span>
</div>
<div class="range-row">
<label for="latRangeA">Lat</label>
<input id="latRangeA" type="range" min="-90" max="90" step="0.1">
<input id="latNumberA" type="number" min="-90" max="90" step="0.1">
</div>
<div class="range-row">
<label for="lonRangeA">Lon</label>
<input id="lonRangeA" type="range" min="-180" max="180" step="0.1">
<input id="lonNumberA" type="number" min="-180" max="180" step="0.1">
</div>
</div>
<div class="point-card">
<div class="point-head">
<span class="point-badge b">B</span>
<strong>Point B</strong>
<span id="coordB" class="coordinates"></span>
</div>
<div class="range-row">
<label for="latRangeB">Lat</label>
<input id="latRangeB" type="range" min="-90" max="90" step="0.1">
<input id="latNumberB" type="number" min="-90" max="90" step="0.1">
</div>
<div class="range-row">
<label for="lonRangeB">Lon</label>
<input id="lonRangeB" type="range" min="-180" max="180" step="0.1">
<input id="lonNumberB" type="number" min="-180" max="180" step="0.1">
</div>
</div>
<div class="actions">
<button id="placeA">Place A on globe</button>
<button id="placeB">Place B on globe</button>
</div>
<div class="secondary-actions">
<button id="swapPoints">Swap points</button>
<button id="resetPoints">Reset</button>
</div>
<p id="modeHint" class="hint">
Drag the globe to orbit, scroll to zoom, and drag either marker to move it.
</p>
<div class="toggles">
<label>
<input id="showGrid" type="checkbox" checked>
Graticule
</label>
<label>
<input id="showChord" type="checkbox" checked>
Reveal chord
</label>
</div>
</aside>
<aside id="metrics" class="glass" aria-live="polite">
<div class="metrics-title">Distance comparison</div>
<div class="metric" style="--metric-color: var(--cyan)">
<div class="metric-label">Surface distance · shorter great circle</div>
<strong id="gcValue">—</strong>
<small id="gcMeta">—</small>
</div>
<div class="metric" style="--metric-color: var(--orange)">
<div class="metric-label">Surface distance · latitude-grid route</div>
<strong id="latitudeValue">—</strong>
<small id="latitudeMeta">—</small>
</div>
<div class="metric" style="--metric-color: var(--magenta)">
<div class="metric-label">Straight chord · through the sphere</div>
<strong id="chordValue">—</strong>
<small id="chordMeta">—</small>
</div>
<p id="comparisonNote" class="comparison-note"></p>
</aside>
<div id="legend" class="glass">
<div class="legend-item">
<span class="swatch cyan"></span>
Great-circle surface path
</div>
<div class="legend-item">
<span class="swatch orange"></span>
Latitude + meridian route
</div>
<div class="legend-item">
<span class="swatch magenta"></span>
Straight interior chord
</div>
</div>
<div id="labelA" class="point-label"><b>A</b><span></span></div>
<div id="labelB" class="point-label"><b>B</b><span></span></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();
const camera = new THREE.PerspectiveCamera(
42,
innerWidth / innerHeight,
0.05,
100
);
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;
document.querySelector("#scene").appendChild(renderer.domElement);
scene.add(new THREE.AmbientLight(0x7ea9d5, 1.25));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.5);
keyLight.position.set(4, 5, 4);
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x00aeea, 24, 14, 2);
rimLight.position.set(-4, 1.5, -3);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff8d5c, 12, 12, 2);
warmLight.position.set(3, -3, 2);
scene.add(warmLight);
const sphereGeometry = new THREE.IcosahedronGeometry(1, 2);
const sphereMaterial = new THREE.MeshStandardMaterial({
color: 0x173a51,
roughness: 0.88,
metalness: 0.04,
flatShading: true
});
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
scene.add(sphere);
const facetMesh = new THREE.Mesh(
sphereGeometry,
new THREE.MeshBasicMaterial({
color: 0x8ed9ee,
wireframe: true,
transparent: true,
opacity: 0.065,
depthWrite: false
})
);
facetMesh.scale.setScalar(1.002);
scene.add(facetMesh);
const atmosphere = new THREE.Mesh(
new THREE.IcosahedronGeometry(1.065, 3),
new THREE.MeshBasicMaterial({
color: 0x1bc8ff,
side: THREE.BackSide,
transparent: true,
opacity: 0.075,
depthWrite: false
})
);
scene.add(atmosphere);
// A sparse background star field.
const starPositions = [];
for (let i = 0; i < 520; i++) {
const direction = new THREE.Vector3(
Math.random() * 2 - 1,
Math.random() * 2 - 1,
Math.random() * 2 - 1
).normalize();
const radius = 11 + Math.random() * 8;
starPositions.push(
direction.x * radius,
direction.y * radius,
direction.z * radius
);
}
const starGeometry = new THREE.BufferGeometry();
starGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(starPositions, 3)
);
const stars = new THREE.Points(
starGeometry,
new THREE.PointsMaterial({
color: 0x9ec8dd,
size: 0.025,
transparent: true,
opacity: 0.48,
sizeAttenuation: true,
depthWrite: false
})
);
scene.add(stars);
// ------------------------------------------------------------
// Graticule
// ------------------------------------------------------------
const graticuleGroup = new THREE.Group();
scene.add(graticuleGroup);
const gridMaterial = new THREE.LineBasicMaterial({
color: 0x8ebbd0,
transparent: true,
opacity: 0.17,
depthWrite: false
});
function addGridLine(points) {
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const line = new THREE.Line(geometry, gridMaterial);
graticuleGroup.add(line);
}
const GRID_RADIUS = 1.004;
for (let latitude = -60; latitude <= 60; latitude += 30) {
const points = [];
for (let longitude = -180; longitude <= 180; longitude += 3) {
points.push(
latLonToVector(latitude, longitude, GRID_RADIUS)
);
}
addGridLine(points);
}
for (let longitude = -180; longitude < 180; longitude += 30) {
const points = [];
for (let latitude = -90; latitude <= 90; latitude += 3) {
points.push(
latLonToVector(latitude, longitude, GRID_RADIUS)
);
}
addGridLine(points);
}
// ------------------------------------------------------------
// State and UI
// ------------------------------------------------------------
const EARTH_RADIUS_KM = 6371;
const SURFACE_RADIUS = 1.012;
const GREAT_CIRCLE_RADIUS = 1.018;
const MARKER_RADIUS = 1.024;
const defaults = {
A: { lat: 38, lon: -35 },
B: { lat: -22, lon: 132 }
};
const pointState = {
A: { ...defaults.A },
B: { ...defaults.B }
};
const controls = {
A: {
latRange: document.querySelector("#latRangeA"),
latNumber: document.querySelector("#latNumberA"),
lonRange: document.querySelector("#lonRangeA"),
lonNumber: document.querySelector("#lonNumberA")
},
B: {
latRange: document.querySelector("#latRangeB"),
latNumber: document.querySelector("#latNumberB"),
lonRange: document.querySelector("#lonRangeB"),
lonNumber: document.querySelector("#lonNumberB")
}
};
const dom = {
coordA: document.querySelector("#coordA"),
coordB: document.querySelector("#coordB"),
placeA: document.querySelector("#placeA"),
placeB: document.querySelector("#placeB"),
modeHint: document.querySelector("#modeHint"),
showGrid: document.querySelector("#showGrid"),
showChord: document.querySelector("#showChord"),
gcValue: document.querySelector("#gcValue"),
gcMeta: document.querySelector("#gcMeta"),
latitudeValue: document.querySelector("#latitudeValue"),
latitudeMeta: document.querySelector("#latitudeMeta"),
chordValue: document.querySelector("#chordValue"),
chordMeta: document.querySelector("#chordMeta"),
comparisonNote: document.querySelector("#comparisonNote"),
labelA: document.querySelector("#labelA"),
labelB: document.querySelector("#labelB")
};
let placementMode = null;
let routeDirty = true;
function latLonToVector(latitude, longitude, radius = 1) {
const phi = THREE.MathUtils.degToRad(latitude);
const lambda = THREE.MathUtils.degToRad(longitude);
return new THREE.Vector3(
Math.cos(phi) * Math.sin(lambda),
Math.sin(phi),
Math.cos(phi) * Math.cos(lambda)
).multiplyScalar(radius);
}
function wrapLongitude(longitude) {
return ((longitude + 180) % 360 + 360) % 360 - 180;
}
function wrapRadians(angle) {
return THREE.MathUtils.euclideanModulo(angle + Math.PI, Math.PI * 2) - Math.PI;
}
function formatCoordinate(value) {
const rounded = Math.abs(value) < 0.05 ? 0 : value;
return `${rounded.toFixed(1)}°`;
}
function formatDistance(kilometers) {
if (kilometers < 1000) {
return `${Math.round(kilometers)} km`;
}
return `${new Intl.NumberFormat("en-US", {
maximumFractionDigits: 1
}).format(kilometers)} km`;
}
function syncControls(pointName) {
const state = pointState[pointName];
const ui = controls[pointName];
ui.latRange.value = state.lat;
ui.latNumber.value = state.lat.toFixed(1);
ui.lonRange.value = state.lon;
ui.lonNumber.value = state.lon.toFixed(1);
}
function setPointValue(pointName, key, rawValue) {
const value = Number(rawValue);
if (!Number.isFinite(value)) return;
if (key === "lat") {
pointState[pointName][key] = THREE.MathUtils.clamp(value, -90, 90);
} else {
pointState[pointName][key] = wrapLongitude(value);
}
syncControls(pointName);
updateMarkerPositions();
updateMetrics();
routeDirty = true;
}
for (const pointName of ["A", "B"]) {
const ui = controls[pointName];
ui.latRange.addEventListener("input", (event) => {
setPointValue(pointName, "lat", event.target.value);
});
ui.latNumber.addEventListener("change", (event) => {
setPointValue(pointName, "lat", event.target.value);
});
ui.lonRange.addEventListener("input", (event) => {
setPointValue(pointName, "lon", event.target.value);
});
ui.lonNumber.addEventListener("change", (event) => {
setPointValue(pointName, "lon", event.target.value);
});
}
function updateModeUI() {
dom.placeA.classList.toggle("active", placementMode === "A");
dom.placeB.classList.toggle("active", placementMode === "B");
renderer.domElement.style.cursor = placementMode
? "crosshair"
: "grab";
if (placementMode) {
dom.modeHint.textContent =
`Click the globe to place Point ${placementMode}. ` +
"Press the same button again to cancel.";
} else {
dom.modeHint.textContent =
"Drag the globe to orbit, scroll to zoom, and drag either marker to move it.";
}
}
function setPlacementMode(pointName) {
placementMode = placementMode === pointName ? null : pointName;
updateModeUI();
}
dom.placeA.addEventListener("click", () => setPlacementMode("A"));
dom.placeB.addEventListener("click", () => setPlacementMode("B"));
document.querySelector("#swapPoints").addEventListener("click", () => {
const oldA = { ...pointState.A };
pointState.A = { ...pointState.B };
pointState.B = oldA;
syncControls("A");
syncControls("B");
updateMarkerPositions();
updateMetrics();
routeDirty = true;
});
document.querySelector("#resetPoints").addEventListener("click", () => {
pointState.A = { ...defaults.A };
pointState.B = { ...defaults.B };
syncControls("A");
syncControls("B");
updateMarkerPositions();
updateMetrics();
routeDirty = true;
});
dom.showGrid.addEventListener("change", () => {
graticuleGroup.visible = dom.showGrid.checked;
});
dom.showChord.addEventListener("change", () => {
chordGroup.visible = dom.showChord.checked;
});
// ------------------------------------------------------------
// Point markers
// ------------------------------------------------------------
const markerA = new THREE.Mesh(
new THREE.OctahedronGeometry(0.038, 0),
new THREE.MeshStandardMaterial({
color: 0xff5470,
emissive: 0x6b1026,
emissiveIntensity: 0.5,
roughness: 0.38,
flatShading: true
})
);
const markerB = new THREE.Mesh(
new THREE.OctahedronGeometry(0.038, 0),
new THREE.MeshStandardMaterial({
color: 0xffe66d,
emissive: 0x695400,
emissiveIntensity: 0.45,
roughness: 0.38,
flatShading: true
})
);
markerA.renderOrder = 10;
markerB.renderOrder = 10;
scene.add(markerA, markerB);
const markerMeshes = [markerA, markerB];
function updateMarkerPositions() {
markerA.position.copy(
latLonToVector(pointState.A.lat, pointState.A.lon, MARKER_RADIUS)
);
markerB.position.copy(
latLonToVector(pointState.B.lat, pointState.B.lon, MARKER_RADIUS)
);
dom.coordA.textContent =
`${formatCoordinate(pointState.A.lat)}, ` +
`${formatCoordinate(pointState.A.lon)}`;
dom.coordB.textContent =
`${formatCoordinate(pointState.B.lat)}, ` +
`${formatCoordinate(pointState.B.lon)}`;
dom.labelA.querySelector("span").textContent =
`${formatCoordinate(pointState.A.lat)}, ` +
`${formatCoordinate(pointState.A.lon)}`;
dom.labelB.querySelector("span").textContent =
`${formatCoordinate(pointState.B.lat)}, ` +
`${formatCoordinate(pointState.B.lon)}`;
}
// ------------------------------------------------------------
// Route geometry
// ------------------------------------------------------------
const greatCircleGroup = new THREE.Group();
const latitudeGroup = new THREE.Group();
const chordGroup = new THREE.Group();
scene.add(greatCircleGroup, latitudeGroup, chordGroup);
const greatCircleMaterial = new THREE.MeshBasicMaterial({
color: 0x28e4ff
});
const latitudeMaterial = new THREE.MeshBasicMaterial({
color: 0xff9f43
});
const chordMaterial = new THREE.MeshBasicMaterial({
color: 0xe85cff,
transparent: true,
opacity: 0.9,
depthTest: false,
depthWrite: false
});
class GreatCircleCurve extends THREE.Curve {
constructor(start, end, axis, angle, radius) {
super();
this.start = start.clone();
this.end = end.clone();
this.axis = axis.clone();
this.angle = angle;
this.radius = radius;
}
getPoint(t, target = new THREE.Vector3()) {
target
.copy(this.start)
.multiplyScalar(Math.cos(this.angle * t))
.addScaledVector(this.axis, Math.sin(this.angle * t))
.normalize()
.multiplyScalar(this.radius);
return target;
}
}
function clearGroup(group) {
for (const child of [...group.children]) {
child.traverse((object) => {
if (object.geometry) object.geometry.dispose();
});
group.remove(child);
}
}
function addTube(group, points, radius, material) {
if (points.length < 2) return;
const first = points[0];
const last = points[points.length - 1];
if (first.distanceToSquared(last) < 1e-12 && points.length === 2) {
return;
}
const curve = points.length === 2
? new THREE.LineCurve3(points[0], points[1])
: new THREE.CatmullRomCurve3(points, false, "centripetal");
const tubularSegments = THREE.MathUtils.clamp(
points.length * 2,
12,
160
);
const geometry = new THREE.TubeGeometry(
curve,
tubularSegments,
radius,
6,
false
);
const mesh = new THREE.Mesh(geometry, material);
mesh.renderOrder = 4;
group.add(mesh);
}
function centralAngleInfo(start, end) {
const dot = THREE.MathUtils.clamp(start.dot(end), -1, 1);
const cross = new THREE.Vector3().crossVectors(start, end);
const crossLength = cross.length();
const angle = Math.acos(dot);
if (crossLength > 1e-8) {
return {
angle,
axis: cross.normalize()
};
}
if (dot > 0) {
return {
angle: 0,
axis: new THREE.Vector3(1, 0, 0)
};
}
// Exactly antipodal points admit infinitely many great circles.
// Pick a stable, visually useful semicircle.
const helper = Math.abs(start.y) < 0.8
? new THREE.Vector3(0, 1, 0)
: new THREE.Vector3(1, 0, 0);
const axis = new THREE.Vector3()
.crossVectors(start, helper)
.normalize();
return { angle, axis };
}
function rebuildRoutes() {
clearGroup(greatCircleGroup);
clearGroup(latitudeGroup);
clearGroup(chordGroup);
const start = latLonToVector(pointState.A.lat, pointState.A.lon);
const end = latLonToVector(pointState.B.lat, pointState.B.lon);
const { angle, axis } = centralAngleInfo(start, end);
// Cyan: the shorter great-circle surface path.
if (angle > 1e-6) {
const curve = new GreatCircleCurve(
start,
end,
axis,
angle,
GREAT_CIRCLE_RADIUS
);
const geometry = new THREE.TubeGeometry(
curve,
128,
0.0105,
6,
false
);
const mesh = new THREE.Mesh(geometry, greatCircleMaterial);
mesh.renderOrder = 5;
greatCircleGroup.add(mesh);
}
// Amber:
// 1. Follow A's latitude to B's longitude.
// 2. Follow B's meridian to B.
const latitudeA = pointState.A.lat;
const latitudeB = pointState.B.lat;
const longitudeA = pointState.A.lon;
const longitudeB = pointState.B.lon;
const longitudeDelta = wrapRadians(
THREE.MathUtils.degToRad(longitudeB - longitudeA)
);
const parallelLength =
Math.cos(THREE.MathUtils.degToRad(latitudeA)) *
Math.abs(longitudeDelta);
if (parallelLength > 1e-7) {
const parallelPoints = [];
for (let i = 0; i <= 64; i++) {
const t = i / 64;
const longitude = longitudeA +
THREE.MathUtils.radToDeg(longitudeDelta) * t;
parallelPoints.push(
latLonToVector(
latitudeA,
longitude,
SURFACE_RADIUS
)
);
}
addTube(latitudeGroup, parallelPoints, 0.0075, latitudeMaterial);
}
if (Math.abs(latitudeB - latitudeA) > 1e-7) {
const meridianPoints = [];
for (let i = 0; i <= 32; i++) {
const t = i / 32;
const latitude =
latitudeA + (latitudeB - latitudeA) * t;
meridianPoints.push(
latLonToVector(
latitude,
longitudeB,
SURFACE_RADIUS
)
);
}
addTube(latitudeGroup, meridianPoints, 0.0075, latitudeMaterial);
}
// Magenta: Euclidean chord. depthTest is disabled so the portion
// passing through the sphere remains visible as an x-ray line.
const chordStart = start.clone().multiplyScalar(MARKER_RADIUS);
const chordEnd = end.clone().multiplyScalar(MARKER_RADIUS);
const chordVector = chordEnd.clone().sub(chordStart);
const chordLength = chordVector.length();
if (chordLength > 1e-7) {
const chordGeometry = new THREE.CylinderGeometry(
0.0075,
0.0075,
chordLength,
8,
1,
true
);
const chordMesh = new THREE.Mesh(chordGeometry, chordMaterial);
chordMesh.position
.copy(chordStart)
.add(chordEnd)
.multiplyScalar(0.5);
chordMesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
chordVector.normalize()
);
chordMesh.renderOrder = 50;
chordGroup.add(chordMesh);
}
}
function updateMetrics() {
const start = latLonToVector(pointState.A.lat, pointState.A.lon);
const end = latLonToVector(pointState.B.lat, pointState.B.lon);
const { angle } = centralAngleInfo(start, end);
const surfaceDistance = EARTH_RADIUS_KM * angle;
const chordDistance =
2 * EARTH_RADIUS_KM * Math.sin(angle / 2);
const longitudeDelta = Math.abs(
wrapRadians(
THREE.MathUtils.degToRad(pointState.B.lon - pointState.A.lon)
)
);
const latitudeA = THREE.MathUtils.degToRad(pointState.A.lat);
const latitudeB = THREE.MathUtils.degToRad(pointState.B.lat);
const latitudeRouteAngle =
Math.cos(latitudeA) * longitudeDelta +
Math.abs(latitudeB - latitudeA);
const latitudeDistance =
EARTH_RADIUS_KM * latitudeRouteAngle;
const chordPercentage = surfaceDistance > 1e-8
? (chordDistance / surfaceDistance) * 100
: 100;
const shortening = Math.max(0, surfaceDistance - chordDistance);
dom.gcValue.textContent = formatDistance(surfaceDistance);
dom.gcMeta.textContent =
`${THREE.MathUtils.radToDeg(angle).toFixed(2)}° central angle`;
dom.latitudeValue.textContent = formatDistance(latitudeDistance);
dom.latitudeMeta.textContent =
`Along A's parallel, then B's meridian`;
dom.chordValue.textContent = formatDistance(chordDistance);
dom.chordMeta.textContent =
`${chordPercentage.toFixed(1)}% of the surface distance`;
dom.comparisonNote.textContent =
`The straight chord is ${formatDistance(shortening)} shorter than ` +
`the surface path, but it passes through the sphere’s interior ` +
`rather than following its surface.`;
}
// ------------------------------------------------------------
// Direct camera controls
// ------------------------------------------------------------
let cameraTheta = 0.72;
let cameraPhi = 1.12;
let cameraRadius = 4.2;
let orbitPointerId = null;
let lastPointerX = 0;
let lastPointerY = 0;
let draggingMarker = null;
const pointerPositions = new Map();
let pinchStartDistance = 0;
let pinchStartRadius = 0;
function updateCamera() {
camera.position.set(
cameraRadius * Math.sin(cameraPhi) * Math.sin(cameraTheta),
cameraRadius * Math.cos(cameraPhi),
cameraRadius * Math.sin(cameraPhi) * Math.cos(cameraTheta)
);
camera.lookAt(0, 0, 0);
}
function pointerDistance() {
const values = [...pointerPositions.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("pointerdown", (event) => {
renderer.domElement.setPointerCapture(event.pointerId);
pointerPositions.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointerPositions.size === 2) {
orbitPointerId = null;
pinchStartDistance = pointerDistance();
pinchStartRadius = cameraRadius;
return;
}
updatePointerRay(event);
if (placementMode) {
placePointFromRay(placementMode);
placementMode = null;
updateModeUI();
return;
}
const markerHits = raycaster.intersectObjects(markerMeshes, false);
if (markerHits.length > 0) {
draggingMarker =
markerHits[0].object === markerA ? "A" : "B";
renderer.domElement.style.cursor = "grabbing";
return;
}
orbitPointerId = event.pointerId;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (pointerPositions.has(event.pointerId)) {
pointerPositions.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
}
if (pointerPositions.size === 2) {
const distance = pointerDistance();
if (distance > 0 && pinchStartDistance > 0) {
cameraRadius = THREE.MathUtils.clamp(
pinchStartRadius * (pinchStartDistance / distance),
2.15,
8.5
);
}
return;
}
if (draggingMarker) {
updatePointerRay(event);
placePointFromRay(draggingMarker);
return;
}
if (orbitPointerId === event.pointerId) {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
cameraTheta -= dx * 0.006;
cameraPhi -= dy * 0.005;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi,
0.12,
Math.PI - 0.12
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
return;
}
updatePointerRay(event);
const hoverHits = raycaster.intersectObjects(markerMeshes, false);
renderer.domElement.style.cursor = hoverHits.length ? "pointer" : "grab";
});
function endPointer(event) {
pointerPositions.delete(event.pointerId);
if (event.pointerId === orbitPointerId) {
orbitPointerId = null;
}
if (draggingMarker) {
draggingMarker = null;
renderer.domElement.style.cursor = "grab";
}
if (pointerPositions.size < 2) {
pinchStartDistance = 0;
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
2.15,
8.5
);
},
{ passive: false }
);
// ------------------------------------------------------------
// Ray-based placement and marker dragging
// ------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const interactionSphere = new THREE.Sphere(
new THREE.Vector3(0, 0, 0),
MARKER_RADIUS
);
function updatePointerRay(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function placePointFromRay(pointName) {
const intersection = new THREE.Vector3();
if (!raycaster.ray.intersectSphere(interactionSphere, intersection)) {
return;
}
intersection.normalize();
const latitude = THREE.MathUtils.radToDeg(
Math.asin(THREE.MathUtils.clamp(intersection.y, -1, 1))
);
const longitude = wrapLongitude(
THREE.MathUtils.radToDeg(
Math.atan2(intersection.x, intersection.z)
)
);
pointState[pointName].lat = latitude;
pointState[pointName].lon = longitude;
syncControls(pointName);
updateMarkerPositions();
updateMetrics();
routeDirty = true;
}
// ------------------------------------------------------------
// Screen-space labels and animation
// ------------------------------------------------------------
function positionLabel(label, marker) {
const projected = marker.position.clone().project(camera);
const normal = marker.position.clone().normalize();
const towardCamera = camera.position.clone().normalize();
const facing = normal.dot(towardCamera) > 0.015;
const visible =
facing &&
projected.z >= -1 &&
projected.z <= 1;
label.style.display = visible ? "flex" : "none";
if (!visible) return;
const x = (projected.x * 0.5 + 0.5) * innerWidth;
const y = (-projected.y * 0.5 + 0.5) * innerHeight;
label.style.left = `${x}px`;
label.style.top = `${y}px`;
}
function animate() {
requestAnimationFrame(animate);
if (routeDirty) {
rebuildRoutes();
routeDirty = false;
}
updateCamera();
positionLabel(dom.labelA, markerA);
positionLabel(dom.labelB, markerB);
stars.rotation.y += 0.00008;
stars.rotation.x += 0.000025;
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);
syncControls("A");
syncControls("B");
updateMarkerPositions();
updateMetrics();
updateModeUI();
updateCamera();
animate();
</script>
</body>
</html>
```