Prompt specification
Build or customize the Three.js 3D scene "Compass needles around a magnet" 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: Compass needles around a magnet
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/compass-needles-around-a-magnet-x1650
Scene Description Prompt:
Make a stylized Three.js scene in a self-contained HTML file using cdnjs: compass needles around a magnet. Place small compass proxies around a bar-magnet field model; align their north-seeking directions with local field direction without treating needle length as field strength.
Working Three.js Starter (compass-needles-around-a-magnet-x1650):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Compass Needles Around a Bar Magnet</title>
<style>
:root {
color-scheme: dark;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #07131f;
color: #eef9ff;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas.dragging {
cursor: grabbing;
}
#ui {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
border: 1px solid rgba(154, 220, 235, 0.16);
background:
linear-gradient(
145deg,
rgba(13, 34, 49, 0.88),
rgba(6, 19, 30, 0.78)
);
box-shadow:
0 18px 50px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.04);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
#intro {
position: absolute;
top: 24px;
left: 24px;
width: min(430px, calc(100vw - 48px));
padding: 19px 21px 18px;
border-radius: 18px;
}
.eyebrow {
margin-bottom: 8px;
color: #70ddd1;
font-size: 0.7rem;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(1.35rem, 2.7vw, 2rem);
line-height: 1.06;
letter-spacing: -0.035em;
}
#intro p {
margin: 10px 0 0;
max-width: 38rem;
color: #a9c0ce;
font-size: 0.87rem;
line-height: 1.5;
}
#controls {
position: absolute;
top: 24px;
right: 24px;
display: flex;
gap: 8px;
pointer-events: auto;
}
button {
appearance: none;
border: 1px solid rgba(154, 220, 235, 0.2);
border-radius: 11px;
padding: 10px 13px;
background: rgba(10, 29, 43, 0.84);
color: #e8f8ff;
font: inherit;
font-size: 0.78rem;
font-weight: 700;
cursor: pointer;
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
button:hover {
border-color: rgba(112, 221, 209, 0.62);
background: rgba(18, 49, 64, 0.92);
}
button:focus-visible {
outline: 2px solid #70ddd1;
outline-offset: 3px;
}
#legend {
position: absolute;
right: 24px;
bottom: 24px;
padding: 13px 15px;
border-radius: 14px;
color: #b9cbd5;
font-size: 0.76rem;
line-height: 1.65;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
}
.needle-key {
position: relative;
width: 33px;
height: 8px;
flex: 0 0 auto;
}
.needle-key::before {
content: "";
position: absolute;
left: 0;
top: 1px;
width: 25px;
height: 6px;
background: #e9f0ec;
}
.needle-key::after {
content: "";
position: absolute;
right: 0;
top: 0;
border-top: 4px solid transparent;
border-bottom: 4px solid transparent;
border-left: 9px solid #ff4f63;
}
.length-key {
width: 34px;
height: 7px;
flex: 0 0 auto;
border-radius: 8px;
background: linear-gradient(90deg, #ff4f63 50%, #e9f0ec 50%);
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.15);
}
#readout {
position: absolute;
left: 24px;
bottom: 24px;
min-width: 275px;
max-width: calc(100vw - 48px);
padding: 14px 16px;
border-radius: 14px;
color: #9eb5c3;
font-size: 0.78rem;
line-height: 1.55;
}
#readout strong {
display: block;
margin-bottom: 3px;
color: #effbff;
font-size: 0.9rem;
}
#readout .value {
color: #70ddd1;
font-variant-numeric: tabular-nums;
}
#hint {
position: absolute;
right: 24px;
top: 78px;
color: rgba(201, 225, 235, 0.56);
font-size: 0.72rem;
letter-spacing: 0.02em;
text-align: right;
}
@media (max-width: 700px) {
#intro {
top: 14px;
left: 14px;
width: calc(100vw - 28px);
}
#intro p {
display: none;
}
#controls {
top: auto;
right: 14px;
bottom: 14px;
}
#legend {
display: none;
}
#readout {
left: 14px;
bottom: 14px;
min-width: 0;
max-width: calc(100vw - 190px);
padding: 10px 12px;
}
#hint {
display: none;
}
}
</style>
</head>
<body>
<canvas
id="scene"
aria-label="Interactive three-dimensional bar magnet surrounded by compass proxies"
></canvas>
<div id="ui">
<section id="intro" class="panel">
<div class="eyebrow">Magnetic field laboratory</div>
<h1>Compasses Around a Bar Magnet</h1>
<p>
Each red north-seeking tip follows the local direction of an ideal
dipole field. All needles are exactly the same length: magnitude is
reported numerically rather than encoded in needle size.
</p>
</section>
<div id="controls">
<button id="field-toggle" type="button">Field traces: on</button>
<button id="reset-view" type="button">Reset view</button>
</div>
<div id="hint">Drag to orbit · Scroll or pinch to zoom · Hover a compass</div>
<section id="readout" class="panel" aria-live="polite">
<strong>Compass readout</strong>
Hover over a compass proxy to inspect its local field.
</section>
<section id="legend" class="panel">
<div class="legend-row">
<span class="needle-key"></span>
<span>Red tip = north-seeking end</span>
</div>
<div class="legend-row">
<span class="length-key"></span>
<span>Needle length is constant</span>
</div>
</section>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer, scene, and camera
// -------------------------------------------------------------------------
const canvas = document.getElementById("scene");
const readout = document.getElementById("readout");
const fieldToggle = document.getElementById("field-toggle");
const resetViewButton = document.getElementById("reset-view");
let renderer;
try {
renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
} catch (error) {
document.body.innerHTML = `
<div style="padding:2rem;color:#eef9ff;font:16px system-ui">
This scene requires a browser with WebGL enabled.
</div>
`;
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07131f);
scene.fog = new THREE.FogExp2(0x07131f, 0.032);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const target = new THREE.Vector3(0, 0.45, 0);
const initialCamera = {
theta: 0.72,
phi: 1.02,
radius: 10.8
};
const desiredCamera = { ...initialCamera };
const smoothCamera = { ...initialCamera };
function updateCamera(immediate = false) {
const amount = immediate ? 1 : 0.1;
smoothCamera.theta = THREE.MathUtils.lerp(
smoothCamera.theta,
desiredCamera.theta,
amount
);
smoothCamera.phi = THREE.MathUtils.lerp(
smoothCamera.phi,
desiredCamera.phi,
amount
);
smoothCamera.radius = THREE.MathUtils.lerp(
smoothCamera.radius,
desiredCamera.radius,
amount
);
camera.position.setFromSphericalCoords(
smoothCamera.radius,
smoothCamera.phi,
smoothCamera.theta
);
camera.position.add(target);
camera.lookAt(target);
}
updateCamera(true);
// -------------------------------------------------------------------------
// Lighting and laboratory platform
// -------------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xbcecff, 0x102333, 1.6));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(4.5, 8, 5.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 24;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const warmLight = new THREE.PointLight(0xff7a68, 28, 12, 2);
warmLight.position.set(-4, 3.5, -3);
scene.add(warmLight);
const coolLight = new THREE.PointLight(0x5ee9dc, 24, 11, 2);
coolLight.position.set(4, 2.5, 4);
scene.add(coolLight);
const platform = new THREE.Mesh(
new THREE.CircleGeometry(7.6, 128),
new THREE.MeshStandardMaterial({
color: 0x0a2230,
roughness: 0.88,
metalness: 0.08
})
);
platform.rotation.x = -Math.PI / 2;
platform.position.y = -0.025;
platform.receiveShadow = true;
scene.add(platform);
const polarGrid = new THREE.PolarGridHelper(
7.45,
16,
8,
64,
0x327080,
0x1b4050
);
polarGrid.position.y = 0.002;
polarGrid.material.transparent = true;
polarGrid.material.opacity = 0.28;
scene.add(polarGrid);
const rim = new THREE.Mesh(
new THREE.TorusGeometry(7.48, 0.025, 8, 160),
new THREE.MeshBasicMaterial({
color: 0x70ddd1,
transparent: true,
opacity: 0.38
})
);
rim.rotation.x = Math.PI / 2;
rim.position.y = 0.012;
scene.add(rim);
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
function roundedRectangleShape(width, height, radius) {
const shape = new THREE.Shape();
const x = -width / 2;
const y = -height / 2;
shape.moveTo(x + radius, y);
shape.lineTo(x + width - radius, y);
shape.quadraticCurveTo(x + width, y, x + width, y + radius);
shape.lineTo(x + width, y + height - radius);
shape.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
shape.lineTo(x + radius, y + height);
shape.quadraticCurveTo(x, y + height, x, y + height - radius);
shape.lineTo(x, y + radius);
shape.quadraticCurveTo(x, y, x + radius, y);
return shape;
}
function makeTextTexture(character) {
const textCanvas = document.createElement("canvas");
textCanvas.width = 256;
textCanvas.height = 256;
const context = textCanvas.getContext("2d");
context.clearRect(0, 0, 256, 256);
context.fillStyle = "#ffffff";
context.font = "900 170px Arial, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.shadowColor = "rgba(0,0,0,0.28)";
context.shadowBlur = 14;
context.fillText(character, 128, 137);
const texture = new THREE.CanvasTexture(textCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
return texture;
}
function addPoleLabel(parent, character, x) {
const label = new THREE.Mesh(
new THREE.PlaneGeometry(0.38, 0.38),
new THREE.MeshBasicMaterial({
map: makeTextTexture(character),
transparent: true,
depthWrite: false,
toneMapped: false
})
);
label.rotation.x = -Math.PI / 2;
label.position.set(x, 0.345, 0);
parent.add(label);
}
// -------------------------------------------------------------------------
// Bar magnet
// -------------------------------------------------------------------------
const magnetGroup = new THREE.Group();
magnetGroup.position.y = 0.67;
scene.add(magnetGroup);
const northMaterial = new THREE.MeshStandardMaterial({
color: 0xff4f63,
roughness: 0.27,
metalness: 0.18
});
const southMaterial = new THREE.MeshStandardMaterial({
color: 0x3677ff,
roughness: 0.27,
metalness: 0.18
});
function makeMagnetHalf(material) {
const geometry = new THREE.ExtrudeGeometry(
roundedRectangleShape(1.52, 0.72, 0.13),
{
depth: 0.58,
bevelEnabled: true,
bevelSegments: 4,
bevelSize: 0.045,
bevelThickness: 0.045,
curveSegments: 12,
steps: 1
}
);
geometry.rotateX(Math.PI / 2);
geometry.center();
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
const northHalf = makeMagnetHalf(northMaterial);
northHalf.position.x = 0.79;
magnetGroup.add(northHalf);
const southHalf = makeMagnetHalf(southMaterial);
southHalf.position.x = -0.79;
magnetGroup.add(southHalf);
addPoleLabel(magnetGroup, "N", 1.08);
addPoleLabel(magnetGroup, "S", -1.08);
const pedestalMaterial = new THREE.MeshStandardMaterial({
color: 0x132b39,
roughness: 0.45,
metalness: 0.45
});
const pedestal = new THREE.Mesh(
new THREE.BoxGeometry(2.45, 0.17, 0.86),
pedestalMaterial
);
pedestal.position.y = 0.09;
pedestal.castShadow = true;
pedestal.receiveShadow = true;
scene.add(pedestal);
const pedestalAccent = new THREE.Mesh(
new THREE.BoxGeometry(2.15, 0.018, 0.66),
new THREE.MeshBasicMaterial({ color: 0x70ddd1 })
);
pedestalAccent.position.y = 0.184;
scene.add(pedestalAccent);
for (const x of [-1.05, 1.05]) {
const support = new THREE.Mesh(
new THREE.BoxGeometry(0.35, 0.29, 0.56),
pedestalMaterial
);
support.position.set(x, 0.31, 0);
support.castShadow = true;
scene.add(support);
}
// -------------------------------------------------------------------------
// Ideal dipole field
//
// B(r) = 3r(m · r)/r^5 - m/r^3, with m along +X.
// The north pole is at +X.
// -------------------------------------------------------------------------
function localFieldAt(position) {
const x = position.x;
const z = position.z;
const radiusSquared = x * x + z * z;
const radius = Math.sqrt(radiusSquared);
const inverseRadiusCubed = 1 / (radiusSquared * radius);
const inverseRadiusFifth = inverseRadiusCubed / radiusSquared;
const mDotR = x;
return new THREE.Vector3(
3 * x * mDotR * inverseRadiusFifth - inverseRadiusCubed,
0,
3 * z * mDotR * inverseRadiusFifth
);
}
// Stylized top-view field traces derived from ideal dipole streamlines.
const fieldGroup = new THREE.Group();
scene.add(fieldGroup);
const fieldColors = [
0x62e5d4,
0x6bb8ff,
0xe0c36c,
0xff8d76
];
const traceAmplitudes = [0.85, 1.35, 1.9, 2.55];
const poleHalfLength = 1.62;
const thetaStart = 0.42;
const denominator =
Math.sin(thetaStart) ** 2 * Math.cos(thetaStart);
function makeFieldTrace(side, amplitude) {
const points = [];
for (let i = 0; i <= 80; i++) {
const t = i / 80;
const theta =
thetaStart + (Math.PI - 2 * thetaStart) * t;
const x =
poleHalfLength *
((Math.sin(theta) ** 2 * Math.cos(theta)) / denominator);
const radial =
side * amplitude * Math.sin(theta) ** 3;
points.push(new THREE.Vector3(x, 0.055, radial));
}
return new THREE.CatmullRomCurve3(
points,
false,
"catmullrom",
0.35
);
}
traceAmplitudes.forEach((amplitude, index) => {
const color = fieldColors[index];
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.52,
roughness: 0.35,
metalness: 0.02,
transparent: true,
opacity: 0.55,
depthWrite: false
});
for (const side of [-1, 1]) {
const curve = makeFieldTrace(side, amplitude);
const tube = new THREE.Mesh(
new THREE.TubeGeometry(curve, 96, 0.017, 6, false),
material
);
fieldGroup.add(tube);
}
});
const arrowMaterial = new THREE.MeshBasicMaterial({
color: 0xffd789,
toneMapped: false
});
const arrowGeometry = new THREE.ConeGeometry(0.064, 0.18, 8);
for (const side of [-1, 1]) {
const curve = makeFieldTrace(side, 2.55);
for (const t of [0.25, 0.5, 0.75]) {
const arrow = new THREE.Mesh(arrowGeometry, arrowMaterial);
arrow.position.copy(curve.getPointAt(t));
arrow.position.y = 0.105;
const tangent = curve.getTangentAt(t).normalize();
arrow.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
tangent
);
fieldGroup.add(arrow);
}
}
// -------------------------------------------------------------------------
// Compass proxies
//
// Every proxy uses identical geometry. Only the needle's quaternion
// changes with the local field direction. Needle length is never scaled
// by field magnitude.
// -------------------------------------------------------------------------
const compassEntries = [];
const compassHitTargets = [];
const housingMaterial = new THREE.MeshStandardMaterial({
color: 0x102c3c,
roughness: 0.3,
metalness: 0.62
});
const faceMaterial = new THREE.MeshStandardMaterial({
color: 0xe7eee7,
roughness: 0.72,
metalness: 0.02
});
const tickMaterial = new THREE.MeshStandardMaterial({
color: 0x355464,
roughness: 0.5,
metalness: 0.35
});
const needleNorthMaterial = new THREE.MeshStandardMaterial({
color: 0xff4057,
emissive: 0x7b0714,
emissiveIntensity: 0.22,
roughness: 0.28,
metalness: 0.08,
flatShading: true
});
const needleSouthMaterial = new THREE.MeshStandardMaterial({
color: 0xeaf3ec,
roughness: 0.38,
metalness: 0.08,
flatShading: true
});
const hubMaterial = new THREE.MeshStandardMaterial({
color: 0x183847,
roughness: 0.25,
metalness: 0.7
});
const housingGeometry = new THREE.CylinderGeometry(
0.335,
0.355,
0.12,
36
);
const faceGeometry = new THREE.CylinderGeometry(
0.295,
0.295,
0.026,
36
);
const tickGeometry = new THREE.BoxGeometry(0.017, 0.012, 0.06);
const northNeedleGeometry = new THREE.ConeGeometry(
0.042,
0.21,
4
);
const southNeedleGeometry = new THREE.ConeGeometry(
0.042,
0.21,
4
);
const hubGeometry = new THREE.SphereGeometry(0.052, 16, 12);
const xAxis = new THREE.Vector3(1, 0, 0);
function createCompass(index, x, z) {
const root = new THREE.Group();
root.position.set(x, 0.09, z);
scene.add(root);
const housing = new THREE.Mesh(housingGeometry, housingMaterial);
housing.castShadow = true;
housing.receiveShadow = true;
root.add(housing);
const face = new THREE.Mesh(faceGeometry, faceMaterial);
face.position.y = 0.076;
face.receiveShadow = true;
root.add(face);
// Eight fixed face ticks.
for (let tickIndex = 0; tickIndex < 8; tickIndex++) {
const angle = (tickIndex / 8) * Math.PI * 2;
const tick = new THREE.Mesh(tickGeometry, tickMaterial);
tick.position.set(
Math.sin(angle) * 0.263,
0.097,
Math.cos(angle) * 0.263
);
tick.rotation.y = angle;
root.add(tick);
}
const needlePivot = new THREE.Group();
needlePivot.position.y = 0.112;
root.add(needlePivot);
// Both halves have exactly the same length for every compass.
const northNeedle = new THREE.Mesh(
northNeedleGeometry,
needleNorthMaterial
);
northNeedle.rotation.z = -Math.PI / 2;
northNeedle.position.x = 0.105;
northNeedle.castShadow = true;
needlePivot.add(northNeedle);
const southNeedle = new THREE.Mesh(
southNeedleGeometry,
needleSouthMaterial
);
southNeedle.rotation.z = Math.PI / 2;
southNeedle.position.x = -0.105;
southNeedle.castShadow = true;
needlePivot.add(southNeedle);
const hub = new THREE.Mesh(hubGeometry, hubMaterial);
hub.position.y = 0.006;
hub.castShadow = true;
needlePivot.add(hub);
const hoverMaterial = new THREE.MeshBasicMaterial({
color: 0x70ddd1,
transparent: true,
opacity: 0,
depthWrite: false,
toneMapped: false
});
const hoverRing = new THREE.Mesh(
new THREE.TorusGeometry(0.355, 0.016, 8, 48),
hoverMaterial
);
hoverRing.rotation.x = Math.PI / 2;
hoverRing.position.y = 0.035;
root.add(hoverRing);
const hitMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
});
const hitTarget = new THREE.Mesh(
new THREE.CylinderGeometry(0.38, 0.38, 0.22, 16),
hitMaterial
);
hitTarget.position.y = 0.07;
root.add(hitTarget);
const field = localFieldAt(new THREE.Vector3(x, 0, z));
const magnitude = field.length();
const direction = field.clone().normalize();
// Direction is the only field-dependent property of the needle.
// Deliberately no scale operation based on magnitude.
needlePivot.quaternion.setFromUnitVectors(xAxis, direction);
const bearing =
(Math.atan2(direction.z, direction.x) * 180) / Math.PI;
const normalizedBearing = (bearing + 360) % 360;
const entry = {
index,
root,
needlePivot,
hoverRing,
direction,
magnitude,
bearing: normalizedBearing
};
hitTarget.userData.compassEntry = entry;
compassHitTargets.push(hitTarget);
compassEntries.push(entry);
}
const compassCount = 12;
const compassRadiusX = 4.45;
const compassRadiusZ = 3.55;
for (let i = 0; i < compassCount; i++) {
const angle =
(i / compassCount) * Math.PI * 2 + Math.PI / compassCount;
const x = Math.cos(angle) * compassRadiusX;
const z = Math.sin(angle) * compassRadiusZ;
createCompass(i + 1, x, z);
}
// -------------------------------------------------------------------------
// Raycasting and hover readout
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let hoveredEntry = null;
function updatePointer(event) {
const rect = canvas.getBoundingClientRect();
pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function setHoveredEntry(entry) {
if (hoveredEntry === entry) return;
if (hoveredEntry) {
hoveredEntry.hoverRing.material.opacity = 0;
}
hoveredEntry = entry;
if (hoveredEntry) {
hoveredEntry.hoverRing.material.opacity = 0.82;
readout.innerHTML = `
<strong>Compass ${String(hoveredEntry.index).padStart(2, "0")}</strong>
Direction:
<span class="value">${hoveredEntry.bearing.toFixed(1)}°</span>
from +X<br>
Relative field magnitude:
<span class="value">${hoveredEntry.magnitude.toFixed(3)}</span><br>
Needle length:
<span class="value">constant</span>
`;
} else {
readout.innerHTML = `
<strong>Compass readout</strong>
Hover over a compass proxy to inspect its local field.
`;
}
}
// -------------------------------------------------------------------------
// Custom camera controls: pointer orbit, wheel zoom, and pinch zoom
// -------------------------------------------------------------------------
const activePointers = new Map();
let dragging = false;
let lastX = 0;
let lastY = 0;
let pinchDistance = 0;
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
activePointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (activePointers.size === 1) {
dragging = true;
lastX = event.clientX;
lastY = event.clientY;
canvas.classList.add("dragging");
setHoveredEntry(null);
}
if (activePointers.size === 2) {
const points = [...activePointers.values()];
pinchDistance = Math.hypot(
points[0].x - points[1].x,
points[0].y - points[1].y
);
}
});
canvas.addEventListener("pointermove", (event) => {
updatePointer(event);
if (activePointers.has(event.pointerId)) {
activePointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
}
if (activePointers.size === 2) {
const points = [...activePointers.values()];
const distance = Math.hypot(
points[0].x - points[1].x,
points[0].y - points[1].y
);
if (pinchDistance > 0) {
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius * (pinchDistance / distance),
6.3,
16
);
}
pinchDistance = distance;
return;
}
if (dragging) {
const deltaX = event.clientX - lastX;
const deltaY = event.clientY - lastY;
desiredCamera.theta -= deltaX * 0.006;
desiredCamera.phi = THREE.MathUtils.clamp(
desiredCamera.phi - deltaY * 0.006,
0.28,
1.46
);
lastX = event.clientX;
lastY = event.clientY;
return;
}
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(
compassHitTargets,
false
);
if (intersections.length) {
setHoveredEntry(
intersections[0].object.userData.compassEntry
);
} else {
setHoveredEntry(null);
}
});
function endPointer(event) {
activePointers.delete(event.pointerId);
if (activePointers.size < 2) {
pinchDistance = 0;
}
if (activePointers.size === 0) {
dragging = false;
canvas.classList.remove("dragging");
}
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius * Math.exp(event.deltaY * 0.001),
6.3,
16
);
},
{ passive: false }
);
canvas.addEventListener("pointerleave", () => {
if (!dragging) setHoveredEntry(null);
});
canvas.addEventListener("dblclick", () => {
desiredCamera.theta = initialCamera.theta;
desiredCamera.phi = initialCamera.phi;
desiredCamera.radius = initialCamera.radius;
});
fieldToggle.addEventListener("click", () => {
fieldGroup.visible = !fieldGroup.visible;
fieldToggle.textContent = fieldGroup.visible
? "Field traces: on"
: "Field traces: off";
});
resetViewButton.addEventListener("click", () => {
desiredCamera.theta = initialCamera.theta;
desiredCamera.phi = initialCamera.phi;
desiredCamera.radius = initialCamera.radius;
});
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") {
desiredCamera.theta = initialCamera.theta;
desiredCamera.phi = initialCamera.phi;
desiredCamera.radius = initialCamera.radius;
}
if (event.key.toLowerCase() === "f") {
fieldGroup.visible = !fieldGroup.visible;
fieldToggle.textContent = fieldGroup.visible
? "Field traces: on"
: "Field traces: off";
}
});
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
}
window.addEventListener("resize", resize);
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const elapsed = clock.getElapsedTime();
updateCamera();
if (hoveredEntry) {
const pulse = 0.68 + Math.sin(elapsed * 5.5) * 0.12;
hoveredEntry.hoverRing.material.opacity = pulse;
}
renderer.render(scene, camera);
});
</script>
</body>
</html>
```