Prompt specification
Build or customize the Three.js 3D scene "Magnetic-field superposition explorer" 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: Magnetic-field superposition explorer
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/magnetic-field-superposition-explorer-x1652
Scene Description Prompt:
Allow moving two idealized magnetic dipoles and inspecting resultant vectors at probes; state the approximation and avoid displaying isolated magnetic monopoles as ordinary bar-magnet poles. Build this with Three.js from cdnjs as a voxel scene in one self-contained HTML file.
Working Three.js Starter (magnetic-field-superposition-explorer-x1652):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Dipole Field Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #071018;
--panel: rgba(10, 20, 30, 0.92);
--border: rgba(148, 163, 184, 0.22);
--text: #e5eef7;
--muted: #91a4b8;
--cyan: #67e8f9;
--purple: #c4b5fd;
--pink: #f472b6;
--yellow: #fde047;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#hud {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
pointer-events: auto;
background: var(--panel);
border: 1px solid var(--border);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(14px);
}
#title-card {
position: absolute;
top: 18px;
left: 18px;
width: min(390px, calc(100vw - 36px));
padding: 17px 18px;
border-radius: 16px;
}
.eyebrow {
color: var(--cyan);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 7px;
font-size: 1.35rem;
line-height: 1.2;
}
p {
margin: 0;
}
.subtitle {
color: var(--muted);
font-size: 0.82rem;
line-height: 1.45;
}
#controls-panel {
position: absolute;
top: 18px;
right: 18px;
width: 330px;
max-height: calc(100vh - 36px);
overflow: auto;
padding: 17px;
border-radius: 16px;
scrollbar-width: thin;
scrollbar-color: #334155 transparent;
}
.section {
margin-top: 16px;
padding-top: 14px;
border-top: 1px solid var(--border);
}
.section-title {
margin-bottom: 10px;
color: #cbd5e1;
font-size: 0.76rem;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.hint {
color: var(--muted);
font-size: 0.76rem;
line-height: 1.45;
}
.button-row {
display: flex;
gap: 8px;
margin-top: 10px;
}
button {
flex: 1;
padding: 9px 10px;
border: 1px solid #334155;
border-radius: 9px;
background: #172536;
color: var(--text);
font: inherit;
font-size: 0.78rem;
font-weight: 700;
cursor: pointer;
}
button:hover {
border-color: #64748b;
background: #203247;
}
button.primary {
border-color: rgba(103, 232, 249, 0.45);
background: rgba(8, 145, 178, 0.18);
color: #a5f3fc;
}
button:disabled {
opacity: 0.42;
cursor: not-allowed;
}
.checkbox-row {
display: flex;
align-items: center;
gap: 8px;
margin-top: 9px;
color: #cbd5e1;
font-size: 0.78rem;
}
input[type="checkbox"] {
accent-color: var(--yellow);
}
.control {
margin-top: 11px;
}
.control label {
display: flex;
justify-content: space-between;
gap: 10px;
margin-bottom: 5px;
color: #cbd5e1;
font-size: 0.75rem;
}
output {
color: #f8fafc;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
margin: 0;
accent-color: var(--cyan);
}
#dipole-2-controls input[type="range"] {
accent-color: var(--purple);
}
.readout {
display: grid;
gap: 7px;
}
.metric {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
padding: 8px 9px;
border: 1px solid rgba(148, 163, 184, 0.12);
border-radius: 9px;
background: rgba(15, 23, 42, 0.48);
font-size: 0.75rem;
}
.metric span {
color: var(--muted);
}
.metric strong {
color: #f8fafc;
font-size: 0.78rem;
font-variant-numeric: tabular-nums;
text-align: right;
}
.metric.total {
border-color: rgba(253, 224, 71, 0.35);
background: rgba(113, 92, 12, 0.15);
}
.metric.total strong {
color: var(--yellow);
}
.formula {
margin-top: 9px;
padding: 9px;
border-left: 3px solid var(--cyan);
border-radius: 4px;
background: rgba(8, 145, 178, 0.08);
color: #cbd5e1;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 0.71rem;
line-height: 1.55;
overflow-wrap: anywhere;
}
.legend {
position: absolute;
left: 18px;
bottom: 18px;
padding: 12px 14px;
border-radius: 13px;
color: var(--muted);
font-size: 0.73rem;
line-height: 1.6;
}
.legend-row {
display: flex;
align-items: center;
gap: 7px;
}
.swatch {
display: inline-block;
width: 17px;
height: 7px;
border-radius: 2px;
}
#status {
min-height: 1.2em;
margin-top: 9px;
color: #a5f3fc;
font-size: 0.73rem;
line-height: 1.35;
}
@media (max-width: 760px) {
#title-card {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
}
#controls-panel {
top: auto;
right: 10px;
bottom: 10px;
width: calc(100vw - 20px);
max-height: 47vh;
}
.legend {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<div id="hud">
<section id="title-card" class="panel">
<div class="eyebrow">Voxel Field Laboratory</div>
<h1>Two idealized magnetic dipoles</h1>
<p class="subtitle">
Drag either neutral dipole glyph or a probe across the voxel floor.
Yellow arrows show the resultant field sampled at each probe.
</p>
</section>
<aside id="controls-panel" class="panel">
<div class="section-title">Navigation</div>
<div class="hint">
<strong>Left-drag empty space:</strong> orbit<br>
<strong>Right-drag:</strong> pan •
<strong>Wheel:</strong> zoom<br>
<strong>Left-drag D1, D2, or a probe:</strong> move on the floor
</div>
<div class="button-row">
<button id="add-probe" class="primary">+ Add probe</button>
<button id="remove-probe">Remove selected</button>
</div>
<label class="checkbox-row">
<input id="show-components" type="checkbox" checked>
Show individual field contributions
</label>
<div id="status" role="status"></div>
<div class="section">
<div class="section-title">Dipole 1</div>
<div id="dipole-1-controls">
<div class="control">
<label for="mag1">
Moment magnitude
<output id="mag1-out"></output>
</label>
<input id="mag1" type="range" min="1" max="16" step="0.5" value="9">
</div>
<div class="control">
<label for="az1">
Azimuth
<output id="az1-out"></output>
</label>
<input id="az1" type="range" min="-180" max="180" step="1" value="10">
</div>
<div class="control">
<label for="el1">
Elevation
<output id="el1-out"></output>
</label>
<input id="el1" type="range" min="-80" max="80" step="1" value="10">
</div>
</div>
</div>
<div class="section">
<div class="section-title">Dipole 2</div>
<div id="dipole-2-controls">
<div class="control">
<label for="mag2">
Moment magnitude
<output id="mag2-out"></output>
</label>
<input id="mag2" type="range" min="1" max="16" step="0.5" value="8">
</div>
<div class="control">
<label for="az2">
Azimuth
<output id="az2-out"></output>
</label>
<input id="az2" type="range" min="-180" max="180" step="1" value="140">
</div>
<div class="control">
<label for="el2">
Elevation
<output id="el2-out"></output>
</label>
<input id="el2" type="range" min="-80" max="80" step="1" value="-15">
</div>
</div>
</div>
<div class="section">
<div class="section-title">Selected probe</div>
<div class="readout">
<div class="metric">
<span>Probe</span>
<strong id="probe-name">P1</strong>
</div>
<div class="metric">
<span>Position</span>
<strong id="probe-position">—</strong>
</div>
<div class="metric">
<span>B from D1</span>
<strong id="probe-b1">—</strong>
</div>
<div class="metric">
<span>B from D2</span>
<strong id="probe-b2">—</strong>
</div>
<div class="metric">
<span>Resultant direction</span>
<strong id="probe-direction">—</strong>
</div>
<div class="metric total">
<span>|B₁ + B₂|</span>
<strong id="probe-total">—</strong>
</div>
<div class="metric total">
<span>Resultant vector</span>
<strong id="probe-vector">—</strong>
</div>
</div>
</div>
<div class="section">
<div class="section-title">Model and approximation</div>
<p class="hint">
Each finite magnet is approximated by an ideal point dipole in vacuum.
The full point-dipole angular field is used, while magnet dimensions,
material permeability, and dipole–dipole back-action are neglected.
</p>
<div class="formula">
Bᵢ(r) = 10⁻⁷ [3(mᵢ·r̂)r̂ − mᵢ] / r³
</div>
<p class="hint" style="margin-top:9px">
The source glyphs are neutral dipoles with moment arrows only. No
isolated magnetic monopoles or conventional red/blue bar-magnet poles
are drawn. Probe values are physical values in nT; arrow lengths use a
logarithmic display scale.
</p>
</div>
<div class="section">
<button id="reset-layout">Reset layout and moments</button>
</div>
</aside>
<section class="legend panel">
<div class="legend-row">
<span class="swatch" style="background:#22d3ee"></span>
Field contribution from D1
</div>
<div class="legend-row">
<span class="swatch" style="background:#f472b6"></span>
Field contribution from D2
</div>
<div class="legend-row">
<span class="swatch" style="background:#fde047"></span>
Resultant field at probe
</div>
<div>Arrow lengths are logarithmically compressed.</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, camera, and lighting
// ---------------------------------------------------------------------
const canvas = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071018);
scene.fog = new THREE.FogExp2(0x071018, 0.018);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
150
);
const hemisphere = new THREE.HemisphereLight(0xbadfff, 0x15202b, 1.5);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.25);
keyLight.position.set(9, 17, 10);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -20;
keyLight.shadow.camera.right = 20;
keyLight.shadow.camera.top = 20;
keyLight.shadow.camera.bottom = -20;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 55;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x67e8f9, 0.85);
rimLight.position.set(-10, 8, -12);
scene.add(rimLight);
const magentaLight = new THREE.DirectionalLight(0xf472b6, 0.42);
magentaLight.position.set(8, 4, -10);
scene.add(magentaLight);
// ---------------------------------------------------------------------
// Custom camera controls — no examples/addons are used.
// ---------------------------------------------------------------------
const cameraState = {
target: new THREE.Vector3(0, 0, 0),
distance: 25,
yaw: 0.68,
pitch: 0.61,
minDistance: 7,
maxDistance: 46
};
function updateCamera() {
const cp = Math.cos(cameraState.pitch);
camera.position.set(
cameraState.target.x +
cameraState.distance * cp * Math.sin(cameraState.yaw),
cameraState.target.y +
cameraState.distance * Math.sin(cameraState.pitch),
cameraState.target.z +
cameraState.distance * cp * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraState.target);
}
updateCamera();
// ---------------------------------------------------------------------
// Voxel floor
// ---------------------------------------------------------------------
function createVoxelFloor() {
const count = 23;
const spacing = 1.2;
const half = Math.floor(count / 2);
const geometry = new THREE.BoxGeometry(
spacing * 0.93,
0.16,
spacing * 0.93
);
const material = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.92,
metalness: 0.02
});
const tiles = new THREE.InstancedMesh(
geometry,
material,
count * count
);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
let instance = 0;
for (let x = 0; x < count; x++) {
for (let z = 0; z < count; z++) {
const px = (x - half) * spacing;
const pz = (z - half) * spacing;
dummy.position.set(px, -0.12, pz);
dummy.updateMatrix();
tiles.setMatrixAt(instance, dummy.matrix);
const radial = Math.hypot(px, pz);
const variation = 0.018 * Math.sin(px * 0.71 + pz * 0.37);
const lightness = 0.13 + variation - radial * 0.0007;
color.setHSL(0.56, 0.18, lightness);
tiles.setColorAt(instance, color);
instance++;
}
}
tiles.instanceMatrix.needsUpdate = true;
tiles.instanceColor.needsUpdate = true;
tiles.receiveShadow = true;
scene.add(tiles);
}
createVoxelFloor();
// ---------------------------------------------------------------------
// Text labels made with canvas textures
// ---------------------------------------------------------------------
function roundedRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function makeLabel(text, color = "#e5eef7") {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 128;
const ctx = labelCanvas.getContext("2d");
ctx.clearRect(0, 0, 512, 128);
roundedRect(ctx, 8, 10, 496, 108, 24);
ctx.fillStyle = "rgba(7, 16, 24, 0.88)";
ctx.fill();
ctx.strokeStyle = color;
ctx.lineWidth = 5;
ctx.stroke();
ctx.fillStyle = color;
ctx.font = "bold 60px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 256, 65);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(2.05, 0.51, 1);
sprite.renderOrder = 20;
return sprite;
}
// ---------------------------------------------------------------------
// Block-built arrows
// ---------------------------------------------------------------------
const FORWARD = new THREE.Vector3(0, 0, 1);
function createVoxelArrow(color, opacity = 1) {
const group = new THREE.Group();
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.22,
roughness: 0.6,
metalness: 0.05,
transparent: opacity < 1,
opacity,
depthWrite: opacity >= 0.95
});
const shaft = [];
for (let i = 0; i < 18; i++) {
const cube = new THREE.Mesh(geometry, material);
cube.castShadow = true;
group.add(cube);
shaft.push(cube);
}
const head = [];
for (let i = 0; i < 16; i++) {
const cube = new THREE.Mesh(geometry, material);
cube.castShadow = true;
group.add(cube);
head.push(cube);
}
group.userData.shaft = shaft;
group.userData.head = head;
group.userData.material = material;
group.userData.geometry = geometry;
return group;
}
function setVoxelArrow(arrow, direction, length) {
const shaft = arrow.userData.shaft;
const head = arrow.userData.head;
if (length <= 0.08 || direction.lengthSq() < 1e-12) {
arrow.visible = false;
return;
}
arrow.visible = true;
const dir = direction.clone().normalize();
arrow.quaternion.setFromUnitVectors(FORWARD, dir);
const headLength = Math.min(0.5, Math.max(0.3, length * 0.32));
const shaftLength = Math.max(0.04, length - headLength);
const shaftCount = Math.max(1, Math.min(shaft.length, Math.ceil(shaftLength / 0.15)));
const shaftStep = shaftLength / shaftCount;
const shaftSize = Math.min(0.13, shaftStep * 0.92);
for (let i = 0; i < shaft.length; i++) {
const cube = shaft[i];
cube.visible = i < shaftCount;
cube.position.set(0, 0, (i + 0.5) * shaftStep);
cube.scale.setScalar(shaftSize);
}
const offset = headLength / 3;
const size = Math.min(0.13, headLength * 0.25);
let h = 0;
function putHead(x, y, z) {
const cube = head[h++];
cube.visible = true;
cube.position.set(x, y, z);
cube.scale.setScalar(size);
}
putHead(0, 0, length);
putHead(0, 0, length - offset);
// Five-cube cross.
putHead(0, 0, length - 2 * offset);
putHead(-size, 0, length - 2 * offset);
putHead(size, 0, length - 2 * offset);
putHead(0, -size, length - 2 * offset);
putHead(0, size, length - 2 * offset);
// Nine-cube square base.
for (let y = -1; y <= 1; y++) {
for (let x = -1; x <= 1; x++) {
putHead(
x * size,
y * size,
length - 3 * offset
);
}
}
for (let i = h; i < head.length; i++) {
head[i].visible = false;
}
}
// ---------------------------------------------------------------------
// Dipole and probe objects
// ---------------------------------------------------------------------
const PROBE_Y = 0.85;
const sources = [];
const probes = [];
const hitMeshes = [];
function createInvisibleHitbox(entity, size) {
const material = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
});
const hitbox = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
material
);
hitbox.userData.entity = entity;
entity.group.add(hitbox);
hitMeshes.push(hitbox);
return hitbox;
}
function createDipole(id, position, color) {
const group = new THREE.Group();
group.position.copy(position);
const entity = {
kind: "source",
id,
group,
color,
moment: new THREE.Vector3(),
momentArrow: null
};
const bodyMaterial = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.09,
roughness: 0.72,
metalness: 0.04
});
// Neutral voxel lattice: deliberately no separate N/S pole blocks.
const center = new THREE.Mesh(
new THREE.BoxGeometry(0.34, 0.34, 0.34),
bodyMaterial
);
center.castShadow = true;
group.add(center);
const ringGeometry = new THREE.BoxGeometry(0.21, 0.21, 0.21);
for (let i = 0; i < 12; i++) {
const angle = (i / 12) * Math.PI * 2;
const cube = new THREE.Mesh(ringGeometry, bodyMaterial);
cube.position.set(
Math.cos(angle) * 0.56,
0,
Math.sin(angle) * 0.56
);
cube.castShadow = true;
group.add(cube);
}
// Stacked neutral pedestal.
const pedestalMaterial = new THREE.MeshStandardMaterial({
color: 0x334155,
roughness: 0.9
});
const pedestalSizes = [0.24, 0.42, 0.66];
const pedestalHeights = [-0.68, -0.43, -0.21];
for (let i = 0; i < 3; i++) {
const block = new THREE.Mesh(
new THREE.BoxGeometry(
pedestalSizes[i],
0.22,
pedestalSizes[i]
),
pedestalMaterial
);
block.position.y = pedestalHeights[i];
block.castShadow = true;
block.receiveShadow = true;
group.add(block);
}
const momentArrow = createVoxelArrow(color, 0.95);
group.add(momentArrow);
entity.momentArrow = momentArrow;
const label = makeLabel(id, color);
label.position.set(0, 1.18, 0);
group.add(label);
entity.hitbox = createInvisibleHitbox(entity, {
x: 1.45,
y: 1.65,
z: 1.45
});
scene.add(group);
sources.push(entity);
return entity;
}
function createProbe(id, position) {
const group = new THREE.Group();
group.position.copy(position);
const entity = {
kind: "probe",
id,
group,
b1: new THREE.Vector3(),
b2: new THREE.Vector3(),
total: new THREE.Vector3(),
arrow1: null,
arrow2: null,
arrowTotal: null,
markerMaterial: null
};
const markerMaterial = new THREE.MeshStandardMaterial({
color: 0x94a3b8,
emissive: 0x475569,
emissiveIntensity: 0.25,
roughness: 0.55
});
entity.markerMaterial = markerMaterial;
const marker = new THREE.Mesh(
new THREE.BoxGeometry(0.25, 0.25, 0.25),
markerMaterial
);
marker.castShadow = true;
group.add(marker);
const tickGeometry = new THREE.BoxGeometry(0.12, 0.12, 0.12);
const tickMaterial = new THREE.MeshStandardMaterial({
color: 0x64748b,
emissive: 0x334155,
emissiveIntensity: 0.15
});
for (const [x, z] of [
[-0.31, -0.31],
[0.31, -0.31],
[-0.31, 0.31],
[0.31, 0.31]
]) {
const tick = new THREE.Mesh(tickGeometry, tickMaterial);
tick.position.set(x, 0, z);
group.add(tick);
}
const pedestalMaterial = new THREE.MeshStandardMaterial({
color: 0x27364a,
roughness: 0.9
});
for (let i = 0; i < 4; i++) {
const size = 0.18 + i * 0.12;
const block = new THREE.Mesh(
new THREE.BoxGeometry(size, 0.16, size),
pedestalMaterial
);
block.position.y = -0.12 - i * 0.16;
block.castShadow = true;
block.receiveShadow = true;
group.add(block);
}
entity.arrow1 = createVoxelArrow(0x22d3ee, 0.43);
entity.arrow2 = createVoxelArrow(0xf472b6, 0.43);
entity.arrowTotal = createVoxelArrow(0xfde047, 1);
group.add(entity.arrow1, entity.arrow2, entity.arrowTotal);
const label = makeLabel(id, "#dbeafe");
label.position.set(0, 0.78, 0);
group.add(label);
entity.hitbox = createInvisibleHitbox(entity, {
x: 0.95,
y: 1.45,
z: 0.95
});
scene.add(group);
probes.push(entity);
return entity;
}
const source1 = createDipole(
"D1",
new THREE.Vector3(-4.2, PROBE_Y, -1.4),
0x7dd3fc
);
const source2 = createDipole(
"D2",
new THREE.Vector3(4.2, PROBE_Y, 1.4),
0xc4b5fd
);
// ---------------------------------------------------------------------
// Dipole moments and field calculation
// ---------------------------------------------------------------------
function momentFromControls(source, prefix) {
const strength = Number(document.getElementById(`mag${prefix}`).value);
const azimuth = THREE.MathUtils.degToRad(
Number(document.getElementById(`az${prefix}`).value)
);
const elevation = THREE.MathUtils.degToRad(
Number(document.getElementById(`el${prefix}`).value)
);
const direction = new THREE.Vector3(
Math.cos(elevation) * Math.cos(azimuth),
Math.sin(elevation),
Math.cos(elevation) * Math.sin(azimuth)
);
source.moment.copy(direction.multiplyScalar(strength));
setVoxelArrow(source.momentArrow, source.moment, 2.45);
}
function syncMomentOutputs() {
document.getElementById("mag1-out").textContent =
`${Number(document.getElementById("mag1").value).toFixed(1)} A·m²`;
document.getElementById("az1-out").textContent =
`${Number(document.getElementById("az1").value).toFixed(0)}°`;
document.getElementById("el1-out").textContent =
`${Number(document.getElementById("el1").value).toFixed(0)}°`;
document.getElementById("mag2-out").textContent =
`${Number(document.getElementById("mag2").value).toFixed(1)} A·m²`;
document.getElementById("az2-out").textContent =
`${Number(document.getElementById("az2").value).toFixed(0)}°`;
document.getElementById("el2-out").textContent =
`${Number(document.getElementById("el2").value).toFixed(0)}°`;
}
function dipoleField(source, point) {
const displacement = new THREE.Vector3().subVectors(
point,
source.group.position
);
const distance = displacement.length();
if (distance < 1e-6) {
return new THREE.Vector3();
}
const radial = displacement.multiplyScalar(1 / distance);
const mDotR = source.moment.dot(radial);
// μ0/(4π) = 10^-7 in SI units.
return radial.multiplyScalar(3 * mDotR)
.sub(source.moment)
.multiplyScalar(1e-7 / Math.pow(distance, 3));
}
function fieldArrowLength(magnitudeTesla) {
const magnitudeNT = magnitudeTesla * 1e9;
return THREE.MathUtils.clamp(
0.45 + 0.72 * Math.log10(1 + magnitudeNT),
0.45,
5.4
);
}
function updateAllFields() {
const componentsVisible =
document.getElementById("show-components").checked;
for (const probe of probes) {
probe.b1.copy(dipoleField(source1, probe.group.position));
probe.b2.copy(dipoleField(source2, probe.group.position));
probe.total.copy(probe.b1).add(probe.b2);
probe.arrow1.visible = componentsVisible;
probe.arrow2.visible = componentsVisible;
setVoxelArrow(
probe.arrow1,
probe.b1,
fieldArrowLength(probe.b1.length())
);
setVoxelArrow(
probe.arrow2,
probe.b2,
fieldArrowLength(probe.b2.length())
);
setVoxelArrow(
probe.arrowTotal,
probe.total,
fieldArrowLength(probe.total.length())
);
}
updateInspector();
}
// ---------------------------------------------------------------------
// Probe selection and numeric inspector
// ---------------------------------------------------------------------
let selectedProbe = null;
function setSelectedProbe(probe) {
selectedProbe = probe;
for (const item of probes) {
const selected = item === selectedProbe;
item.markerMaterial.color.set(selected ? 0xfde047 : 0x94a3b8);
item.markerMaterial.emissive.set(selected ? 0x92700a : 0x475569);
item.markerMaterial.emissiveIntensity = selected ? 0.55 : 0.25;
}
updateInspector();
}
function vectorText(vector) {
return `(${vector.x.toFixed(2)}, ${vector.y.toFixed(2)}, ${vector.z.toFixed(2)})`;
}
function updateInspector() {
if (!selectedProbe) {
document.getElementById("probe-name").textContent = "—";
document.getElementById("probe-position").textContent = "—";
document.getElementById("probe-b1").textContent = "—";
document.getElementById("probe-b2").textContent = "—";
document.getElementById("probe-direction").textContent = "—";
document.getElementById("probe-total").textContent = "—";
document.getElementById("probe-vector").textContent = "—";
return;
}
const p = selectedProbe;
const b1 = p.b1.clone().multiplyScalar(1e9);
const b2 = p.b2.clone().multiplyScalar(1e9);
const total = p.total.clone().multiplyScalar(1e9);
const magnitude = p.total.length() * 1e9;
const direction = p.total.clone().normalize();
const elevation = THREE.MathUtils.radToDeg(
Math.asin(THREE.MathUtils.clamp(direction.y, -1, 1))
);
const azimuth = THREE.MathUtils.radToDeg(
Math.atan2(direction.z, direction.x)
);
document.getElementById("probe-name").textContent = p.id;
document.getElementById("probe-position").textContent =
`(${p.group.position.x.toFixed(2)}, ${p.group.position.y.toFixed(2)}, ${p.group.position.z.toFixed(2)}) m`;
document.getElementById("probe-b1").textContent =
`${vectorText(b1)} nT`;
document.getElementById("probe-b2").textContent =
`${vectorText(b2)} nT`;
document.getElementById("probe-direction").textContent =
`az ${azimuth.toFixed(1)}°, el ${elevation.toFixed(1)}°`;
document.getElementById("probe-total").textContent =
`${magnitude.toFixed(4)} nT`;
document.getElementById("probe-vector").textContent =
`${vectorText(total)} nT`;
}
// ---------------------------------------------------------------------
// Placement and drag constraints
// ---------------------------------------------------------------------
let placementMode = false;
let nextProbeId = 1;
function setPlacementMode(enabled) {
placementMode = enabled;
const button = document.getElementById("add-probe");
button.textContent = enabled ? "Click floor…" : "+ Add probe";
button.classList.toggle("primary", enabled);
canvas.style.cursor = enabled ? "crosshair" : "default";
setStatus(
enabled
? "Click an open floor position to place a probe."
: ""
);
}
function setStatus(message) {
document.getElementById("status").textContent = message;
}
function positionIsValid(entity, candidate) {
const minSourceSeparation = 1.5;
const minProbeSeparation = 1.25;
for (const source of sources) {
if (source === entity) continue;
const distance = Math.hypot(
candidate.x - source.group.position.x,
candidate.z - source.group.position.z
);
if (entity.kind === "source" && distance < minSourceSeparation) {
return false;
}
if (entity.kind === "probe" && distance < minProbeSeparation) {
return false;
}
}
if (entity.kind === "source") {
for (const probe of probes) {
const distance = Math.hypot(
candidate.x - probe.group.position.x,
candidate.z - probe.group.position.z
);
if (distance < minProbeSeparation) return false;
}
}
return true;
}
function findProbePosition(candidate) {
const clamped = candidate.clone();
clamped.x = THREE.MathUtils.clamp(clamped.x, -12.2, 12.2);
clamped.z = THREE.MathUtils.clamp(clamped.z, -12.2, 12.2);
if (positionIsValid({ kind: "probe" }, clamped)) {
return clamped;
}
for (let radius = 1.4; radius <= 8; radius += 1.2) {
for (let step = 0; step < 16; step++) {
const angle = (step / 16) * Math.PI * 2;
const test = clamped.clone();
test.x += Math.cos(angle) * radius;
test.z += Math.sin(angle) * radius;
test.x = THREE.MathUtils.clamp(test.x, -12.2, 12.2);
test.z = THREE.MathUtils.clamp(test.z, -12.2, 12.2);
if (positionIsValid({ kind: "probe" }, test)) {
return test;
}
}
}
return null;
}
function removeProbeEntity(probe) {
const index = probes.indexOf(probe);
if (index === -1) return;
const hitIndex = hitMeshes.indexOf(probe.hitbox);
if (hitIndex !== -1) hitMeshes.splice(hitIndex, 1);
scene.remove(probe.group);
probe.group.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) {
if (Array.isArray(object.material)) {
object.material.forEach((material) => material.dispose());
} else {
object.material.dispose();
}
}
});
probes.splice(index, 1);
if (selectedProbe === probe) {
selectedProbe = null;
if (probes.length) setSelectedProbe(probes[0]);
}
}
function clearProbes() {
while (probes.length) {
removeProbeEntity(probes[probes.length - 1]);
}
selectedProbe = null;
nextProbeId = 1;
}
function resetLayout() {
source1.group.position.set(-4.2, PROBE_Y, -1.4);
source2.group.position.set(4.2, PROBE_Y, 1.4);
const defaults = {
mag1: 9,
az1: 10,
el1: 10,
mag2: 8,
az2: 140,
el2: -15
};
for (const [id, value] of Object.entries(defaults)) {
document.getElementById(id).value = value;
}
syncMomentOutputs();
momentFromControls(source1, "1");
momentFromControls(source2, "2");
clearProbes();
const initialPositions = [
new THREE.Vector3(-1.4, PROBE_Y, -3.2),
new THREE.Vector3(1.2, PROBE_Y, 3.2),
new THREE.Vector3(0, PROBE_Y, 0),
new THREE.Vector3(7.1, PROBE_Y, -4.1)
];
for (const position of initialPositions) {
createProbe(`P${nextProbeId++}`, position);
}
if (probes.length) setSelectedProbe(probes[0]);
updateAllFields();
cameraState.target.set(0, 0, 0);
cameraState.distance = 25;
cameraState.yaw = 0.68;
cameraState.pitch = 0.61;
updateCamera();
setStatus("Layout reset.");
}
// ---------------------------------------------------------------------
// Pointer interaction: object dragging, probe placement, orbit and pan
// ---------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const interactionPlane = new THREE.Plane(
new THREE.Vector3(0, 1, 0),
-PROBE_Y
);
const planePoint = new THREE.Vector3();
let interaction = 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;
raycaster.setFromCamera(pointer, camera);
}
function getPlaneIntersection() {
return raycaster.ray.intersectPlane(interactionPlane, planePoint)
? planePoint.clone()
: null;
}
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
canvas.addEventListener("pointerdown", (event) => {
updatePointer(event);
if (event.button === 0 && placementMode) {
const point = getPlaneIntersection();
if (!point) return;
const position = findProbePosition(point);
if (!position || probes.length >= 6) {
setStatus(
probes.length >= 6
? "The maximum of six probes is already active."
: "Choose a point farther from either dipole."
);
return;
}
const probe = createProbe(`P${nextProbeId++}`, position);
setSelectedProbe(probe);
updateAllFields();
setPlacementMode(false);
setStatus(`${probe.id} added.`);
return;
}
const hits = raycaster.intersectObjects(hitMeshes, false);
if (event.button === 0 && hits.length) {
const entity = hits[0].object.userData.entity;
const point = getPlaneIntersection();
if (entity.kind === "probe") {
setSelectedProbe(entity);
}
interaction = {
mode: "drag",
entity,
pointerId: event.pointerId,
offset: point
? entity.group.position.clone().sub(point)
: new THREE.Vector3()
};
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
return;
}
interaction = {
mode: event.button === 0 ? "orbit" : "pan",
pointerId: event.pointerId,
x: event.clientX,
y: event.clientY
};
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
updatePointer(event);
if (!interaction) {
if (placementMode) {
canvas.style.cursor = "crosshair";
return;
}
const hits = raycaster.intersectObjects(hitMeshes, false);
canvas.style.cursor = hits.length ? "grab" : "default";
return;
}
if (interaction.mode === "drag") {
const point = getPlaneIntersection();
if (!point) return;
const candidate = point.add(interaction.offset);
candidate.y = interaction.entity.group.position.y;
if (positionIsValid(interaction.entity, candidate)) {
interaction.entity.group.position.x = candidate.x;
interaction.entity.group.position.z = candidate.z;
updateAllFields();
}
return;
}
const dx = event.clientX - interaction.x;
const dy = event.clientY - interaction.y;
interaction.x = event.clientX;
interaction.y = event.clientY;
if (interaction.mode === "orbit") {
cameraState.yaw -= dx * 0.005;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.0045,
0.16,
1.38
);
} else if (interaction.mode === "pan") {
const forward = camera.getWorldDirection(new THREE.Vector3()).normalize();
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
const up = new THREE.Vector3()
.crossVectors(right, forward)
.normalize();
const scale = cameraState.distance * 0.0016;
cameraState.target
.addScaledVector(right, -dx * scale)
.addScaledVector(up, dy * scale);
}
updateCamera();
});
function endInteraction(event) {
if (interaction) {
try {
canvas.releasePointerCapture(interaction.pointerId);
} catch (_) {
// Pointer may already have been released.
}
}
interaction = null;
canvas.style.cursor = placementMode ? "crosshair" : "default";
}
canvas.addEventListener("pointerup", endInteraction);
canvas.addEventListener("pointercancel", endInteraction);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance * Math.exp(event.deltaY * 0.001),
cameraState.minDistance,
cameraState.maxDistance
);
updateCamera();
},
{ passive: false }
);
// ---------------------------------------------------------------------
// UI events
// ---------------------------------------------------------------------
for (const prefix of ["1", "2"]) {
for (const control of ["mag", "az", "el"]) {
document.getElementById(`${control}${prefix}`).addEventListener("input", () => {
syncMomentOutputs();
momentFromControls(
prefix === "1" ? source1 : source2,
prefix
);
updateAllFields();
});
}
}
document.getElementById("show-components").addEventListener("change", () => {
updateAllFields();
});
document.getElementById("add-probe").addEventListener("click", () => {
setPlacementMode(!placementMode);
});
document.getElementById("remove-probe").addEventListener("click", () => {
if (!selectedProbe) {
setStatus("Select a probe first.");
return;
}
if (probes.length <= 1) {
setStatus("At least one probe is kept active.");
return;
}
const id = selectedProbe.id;
removeProbeEntity(selectedProbe);
updateAllFields();
setStatus(`${id} removed.`);
});
document.getElementById("reset-layout").addEventListener("click", resetLayout);
window.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
setPlacementMode(false);
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// ---------------------------------------------------------------------
// Initialization
// ---------------------------------------------------------------------
syncMomentOutputs();
momentFromControls(source1, "1");
momentFromControls(source2, "2");
const initialPositions = [
new THREE.Vector3(-1.4, PROBE_Y, -3.2),
new THREE.Vector3(1.2, PROBE_Y, 3.2),
new THREE.Vector3(0, PROBE_Y, 0),
new THREE.Vector3(7.1, PROBE_Y, -4.1)
];
for (const position of initialPositions) {
createProbe(`P${nextProbeId++}`, position);
}
setSelectedProbe(probes[0]);
updateAllFields();
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
</script>
</body>
</html>
```