Prompt specification
Build or customize the Three.js 3D scene "Navigation magnetism teaching table" 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: Navigation magnetism teaching table
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/navigation-magnetism-teaching-table-x1651
Scene Description Prompt:
A voxel tabletop compass responds to combined bar-magnet and background field arrows in a simplified model. Standalone HTML with Three.js from cdnjs.
Working Three.js Starter (navigation-magnetism-teaching-table-x1651):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voxel Field Compass</title>
<style>
:root {
color-scheme: dark;
--bg: #07131d;
--panel: rgba(9, 25, 37, 0.82);
--border: rgba(163, 213, 226, 0.18);
--text: #e8f4f4;
--muted: #8ca8b4;
--red: #ff655e;
--blue: #4c8cff;
--gold: #f4ba4f;
--cyan: #59ead5;
}
* {
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;
}
button,
input {
font: inherit;
}
#app {
position: relative;
width: 100%;
height: 100%;
isolation: isolate;
}
#scene {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.vignette {
position: absolute;
inset: 0;
pointer-events: none;
background:
radial-gradient(circle at 50% 45%, transparent 38%, rgba(1, 8, 13, 0.25) 78%),
linear-gradient(180deg, rgba(2, 9, 15, 0.1), transparent 35%);
z-index: 1;
}
.panel {
position: absolute;
z-index: 3;
border: 1px solid var(--border);
background:
linear-gradient(145deg, rgba(17, 39, 52, 0.92), rgba(6, 19, 29, 0.88));
box-shadow:
0 18px 50px rgba(0, 0, 0, 0.28),
inset 0 1px 0 rgba(255, 255, 255, 0.04);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.brand {
top: 22px;
left: 22px;
width: min(355px, calc(100vw - 44px));
padding: 18px 20px 19px;
border-radius: 16px;
}
.kicker {
display: flex;
align-items: center;
gap: 8px;
color: var(--cyan);
font: 700 10px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.kicker::before {
width: 7px;
height: 7px;
border-radius: 2px;
background: var(--cyan);
box-shadow: 0 0 14px rgba(89, 234, 213, 0.65);
content: "";
}
h1 {
margin: 9px 0 4px;
color: var(--text);
font-size: clamp(25px, 3vw, 35px);
line-height: 1;
letter-spacing: -0.045em;
}
.brand p {
margin: 9px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.controls {
top: 22px;
right: 22px;
width: 300px;
padding: 17px;
border-radius: 16px;
}
.section-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 13px;
color: var(--text);
font: 700 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.section-head output {
color: var(--cyan);
font-size: 10px;
letter-spacing: 0.08em;
}
.equation {
display: flex;
align-items: center;
justify-content: center;
gap: 9px;
margin-bottom: 16px;
padding: 10px 8px;
border: 1px solid rgba(89, 234, 213, 0.13);
border-radius: 10px;
background: rgba(3, 14, 21, 0.46);
color: var(--muted);
font: 600 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.04em;
}
.equation strong {
color: var(--text);
font-weight: 700;
}
.equation .plus {
color: var(--cyan);
font-size: 17px;
}
.field-control + .field-control {
margin-top: 15px;
}
.control-label {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
color: var(--text);
font-size: 12px;
font-weight: 650;
}
.control-label span {
display: flex;
align-items: center;
gap: 8px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--accent);
box-shadow: 0 0 10px color-mix(in srgb, var(--accent), transparent 45%);
}
.control-label output {
color: var(--muted);
font: 600 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
input[type="range"] {
--accent: var(--cyan);
--pct: 50%;
width: 100%;
height: 4px;
margin: 0;
border-radius: 99px;
appearance: none;
-webkit-appearance: none;
background:
linear-gradient(
90deg,
var(--accent) 0,
var(--accent) var(--pct),
rgba(153, 197, 207, 0.16) var(--pct),
rgba(153, 197, 207, 0.16) 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #102b38;
border-radius: 4px;
appearance: none;
-webkit-appearance: none;
background: var(--accent);
box-shadow: 0 0 0 1px var(--accent), 0 0 12px rgba(89, 234, 213, 0.25);
}
input[type="range"]::-moz-range-thumb {
width: 10px;
height: 10px;
border: 3px solid #102b38;
border-radius: 4px;
background: var(--accent);
box-shadow: 0 0 0 1px var(--accent);
}
#magnetStrength {
--accent: var(--red);
}
#backgroundStrength {
--accent: var(--gold);
}
.readouts {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 17px 0 14px;
}
.readout {
padding: 10px;
border: 1px solid rgba(159, 205, 217, 0.1);
border-radius: 10px;
background: rgba(1, 11, 17, 0.28);
}
.readout span {
display: block;
margin-bottom: 4px;
color: var(--muted);
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
}
.readout strong {
color: var(--text);
font: 700 21px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.readout:first-child strong {
color: var(--cyan);
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
button {
min-height: 36px;
border: 1px solid rgba(152, 205, 216, 0.18);
border-radius: 9px;
background: rgba(106, 166, 181, 0.08);
color: var(--text);
font-size: 11px;
font-weight: 700;
cursor: pointer;
transition: background 140ms ease, border-color 140ms ease, transform 140ms ease;
}
button:hover {
border-color: rgba(89, 234, 213, 0.42);
background: rgba(89, 234, 213, 0.1);
}
button:active {
transform: translateY(1px);
}
.help {
position: absolute;
z-index: 3;
bottom: 22px;
left: 50%;
max-width: calc(100vw - 32px);
padding: 10px 14px;
transform: translateX(-50%);
border: 1px solid var(--border);
border-radius: 12px;
background: rgba(7, 20, 29, 0.78);
color: var(--muted);
font-size: 11px;
line-height: 1.4;
text-align: center;
white-space: nowrap;
backdrop-filter: blur(10px);
}
.help b {
color: var(--text);
font-weight: 650;
}
.world-label {
position: absolute;
z-index: 2;
top: 0;
left: 0;
padding: 6px 9px;
transform: translate(-50%, -50%);
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 7px;
background: rgba(5, 17, 25, 0.77);
color: #dbeaec;
font: 700 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.1em;
pointer-events: none;
white-space: nowrap;
backdrop-filter: blur(8px);
}
.world-label::before {
display: inline-block;
width: 6px;
height: 6px;
margin-right: 6px;
border-radius: 2px;
background: var(--label-color);
content: "";
}
#magnetLabel {
--label-color: var(--red);
}
#backgroundLabel {
--label-color: var(--gold);
}
@media (max-width: 720px) {
.brand {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 14px 16px;
}
.brand p {
display: none;
}
.controls {
top: auto;
right: 12px;
bottom: 67px;
width: min(300px, calc(100vw - 24px));
max-height: 48vh;
overflow: auto;
padding: 14px;
}
.help {
bottom: 12px;
width: calc(100vw - 24px);
white-space: normal;
}
}
</style>
</head>
<body>
<div id="app">
<canvas id="scene" aria-label="Interactive voxel compass showing combined magnetic fields"></canvas>
<div class="vignette"></div>
<header class="brand panel">
<div class="kicker">Field Instrument 03</div>
<h1>Voxel Compass</h1>
<p>Two fields. One heading. Drag the magnet or background arrow to steer the combined vector.</p>
</header>
<section class="controls panel" aria-label="Field controls">
<div class="section-head">
<span>Field Mix</span>
<output id="netState">READY</output>
</div>
<div class="equation" aria-label="Combined field equation">
<strong style="color:var(--red)">B<sub>m</sub></strong>
<span class="plus">+</span>
<strong style="color:var(--gold)">B<sub>b</sub></strong>
<span>=</span>
<strong style="color:var(--cyan)">B<sub>net</sub></strong>
</div>
<div class="field-control">
<label class="control-label" for="magnetStrength">
<span><i class="swatch"></i>Bar magnet</span>
<output id="magnetValue">1.00</output>
</label>
<input id="magnetStrength" type="range" min="0" max="1.5" step="0.01" value="1" />
</div>
<div class="field-control">
<label class="control-label" for="backgroundStrength">
<span><i class="swatch"></i>Background field</span>
<output id="backgroundValue">0.55</output>
</label>
<input id="backgroundStrength" type="range" min="0" max="1.5" step="0.01" value="0.55" />
</div>
<div class="readouts">
<div class="readout">
<span>NET BEARING</span>
<strong id="bearing">—</strong>
</div>
<div class="readout">
<span>NET STRENGTH</span>
<strong id="netStrength">—</strong>
</div>
</div>
<div class="buttons">
<button id="resetButton" type="button">Reset fields</button>
<button id="opposeButton" type="button">Oppose fields</button>
</div>
</section>
<div id="magnetLabel" class="world-label">BAR MAGNET</div>
<div id="backgroundLabel" class="world-label">BACKGROUND FIELD</div>
<div class="help">
<b>Drag arrows</b> to rotate · <b>Drag empty space</b> to orbit · <b>Scroll</b> to zoom
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.getElementById("scene");
const ui = {
magnetStrength: document.getElementById("magnetStrength"),
backgroundStrength: document.getElementById("backgroundStrength"),
magnetValue: document.getElementById("magnetValue"),
backgroundValue: document.getElementById("backgroundValue"),
bearing: document.getElementById("bearing"),
netStrength: document.getElementById("netStrength"),
netState: document.getElementById("netState"),
resetButton: document.getElementById("resetButton"),
opposeButton: document.getElementById("opposeButton"),
magnetLabel: document.getElementById("magnetLabel"),
backgroundLabel: document.getElementById("backgroundLabel")
};
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07131d);
scene.fog = new THREE.Fog(0x07131d, 18, 37);
const camera = new THREE.PerspectiveCamera(
40,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 0.5, 0);
const cameraState = {
yaw: 0.62,
pitch: 0.58,
radius: 16.8
};
function updateCamera() {
const horizontal = Math.cos(cameraState.pitch);
camera.position.set(
cameraTarget.x + Math.sin(cameraState.yaw) * horizontal * cameraState.radius,
cameraTarget.y + Math.sin(cameraState.pitch) * cameraState.radius,
cameraTarget.z + Math.cos(cameraState.yaw) * horizontal * cameraState.radius
);
camera.lookAt(cameraTarget);
}
updateCamera();
scene.add(new THREE.HemisphereLight(0xc8efff, 0x142033, 2.1));
const keyLight = new THREE.DirectionalLight(0xffe7c7, 3.2);
keyLight.position.set(7, 12, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -11;
keyLight.shadow.camera.right = 11;
keyLight.shadow.camera.top = 11;
keyLight.shadow.camera.bottom = -11;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 32;
keyLight.shadow.bias = -0.00035;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(0x50e7d5, 8, 12, 2);
cyanLight.position.set(0, 4, 1);
scene.add(cyanLight);
const warmLight = new THREE.PointLight(0xff8d67, 5, 10, 2);
warmLight.position.set(-6, 3, -3);
scene.add(warmLight);
const material = (color, options = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0.04,
flatShading: true,
...options
});
const MAT = {
underTable: material(0x07131b, { roughness: 0.95 }),
compassBase: material(0x162a37, { roughness: 0.72 }),
compassEdge: material(0x294654),
face: material(0xdce4d7, { roughness: 0.92 }),
faceInset: material(0xb8c7bb, { roughness: 0.94 }),
ink: material(0x17313a, { roughness: 0.85 }),
ring: material(0x476672),
ringLight: material(0x6f8990),
red: material(0xff5f59, {
emissive: 0x5d0907,
emissiveIntensity: 0.18
}),
blue: material(0x4389ed, {
emissive: 0x071c58,
emissiveIntensity: 0.2
}),
gold: material(0xf2b748, {
emissive: 0x5a3100,
emissiveIntensity: 0.22
}),
cyan: material(0x57e2d0, {
emissive: 0x087a70,
emissiveIntensity: 0.28,
transparent: true,
opacity: 0.76,
depthWrite: false
}),
pad: material(0x102b37),
white: material(0xe8f4ec),
fieldArrow: material(0xf2b748, {
emissive: 0x5a3100,
emissiveIntensity: 0.3,
transparent: true,
opacity: 0.3,
depthWrite: false
})
};
const geometryCache = new Map();
function boxGeometry(x, y, z) {
const key = `${x}|${y}|${z}`;
if (!geometryCache.has(key)) {
geometryCache.set(key, new THREE.BoxGeometry(x, y, z));
}
return geometryCache.get(key);
}
function addBox(parent, size, position, mat, castShadow = true) {
const mesh = new THREE.Mesh(boxGeometry(...size), mat);
mesh.position.set(...position);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// Voxel tabletop.
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
material(0x050d14, { roughness: 1 })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.58;
ground.receiveShadow = true;
scene.add(ground);
addBox(
scene,
[15.6, 0.5, 15.6],
[0, -0.31, 0],
MAT.underTable
);
const tileCount = 21;
const tileSpacing = 0.72;
const tileGeometry = new THREE.BoxGeometry(0.67, 0.12, 0.67);
const tileMaterial = material(0xffffff, {
vertexColors: true,
roughness: 0.93
});
const tiles = new THREE.InstancedMesh(
tileGeometry,
tileMaterial,
tileCount * tileCount
);
const dummy = new THREE.Object3D();
const tileColor = new THREE.Color();
let tileIndex = 0;
for (let ix = 0; ix < tileCount; ix++) {
for (let iz = 0; iz < tileCount; iz++) {
const x = (ix - (tileCount - 1) / 2) * tileSpacing;
const z = (iz - (tileCount - 1) / 2) * tileSpacing;
dummy.position.set(x, -0.01, z);
dummy.updateMatrix();
tiles.setMatrixAt(tileIndex, dummy.matrix);
const n = Math.sin(ix * 12.9898 + iz * 78.233) * 43758.5453;
const f = n - Math.floor(n);
const edge = Math.max(Math.abs(x), Math.abs(z));
tileColor.setHSL(
0.53 + f * 0.025,
0.30 + f * 0.12,
edge > 5.8 ? 0.105 : 0.13 + f * 0.045
);
tiles.setColorAt(tileIndex, tileColor);
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
tiles.instanceColor.needsUpdate = true;
tiles.receiveShadow = true;
scene.add(tiles);
// Compass housing.
const compass = new THREE.Group();
scene.add(compass);
addBox(compass, [6.8, 0.42, 6.8], [0, 0.21, 0], MAT.compassBase);
addBox(compass, [6.55, 0.16, 6.55], [0, 0.5, 0], MAT.compassEdge);
addBox(compass, [6.12, 0.14, 6.12], [0, 0.65, 0], MAT.face);
// Stepped circular rim made from individual voxels.
for (let ix = -7; ix <= 7; ix++) {
for (let iz = -7; iz <= 7; iz++) {
const x = ix * 0.4;
const z = iz * 0.4;
const radius = Math.hypot(x, z);
if (radius < 2.12 || radius > 2.95) continue;
let tileMaterial = (ix + iz) % 2 === 0 ? MAT.ring : MAT.ringLight;
if (z < -2.25 && Math.abs(x) < 0.8) tileMaterial = MAT.red;
if (z > 2.25 && Math.abs(x) < 0.8) tileMaterial = MAT.blue;
if (x > 2.25 && Math.abs(z) < 0.8) tileMaterial = MAT.gold;
if (x < -2.25 && Math.abs(z) < 0.8) tileMaterial = MAT.cyan;
addBox(
compass,
[0.38, 0.24, 0.38],
[x, 0.79, z],
tileMaterial
);
}
}
// Inner tick marks.
for (let i = -6; i <= 6; i++) {
const p = i * 0.4;
const major = i % 2 === 0;
const tickSize = major ? 0.2 : 0.12;
const tickHeight = 0.045;
addBox(
compass,
[0.065, tickHeight, tickSize],
[p, 0.745, -1.92],
MAT.ink,
false
);
addBox(
compass,
[0.065, tickHeight, tickSize],
[p, 0.745, 1.92],
MAT.ink,
false
);
addBox(
compass,
[tickSize, tickHeight, 0.065],
[-1.92, 0.745, p],
MAT.ink,
false
);
addBox(
compass,
[tickSize, tickHeight, 0.065],
[1.92, 0.745, p],
MAT.ink,
false
);
}
// Pixel cardinal letters.
const glyphs = {
N: ["10001", "11011", "10101", "10001", "10001"],
E: ["11111", "10001", "11110", "10001", "11111"],
S: ["11111", "10001", "10101", "11011", "11111"],
W: ["10001", "10101", "11011", "10001", "10001"]
};
function addGlyph(pattern, centerX, centerZ) {
const cell = 0.09;
for (let row = 0; row < pattern.length; row++) {
for (let col = 0; col < pattern[row].length; col++) {
if (pattern[row][col] !== "1") continue;
const x = centerX + (col - 2) * cell;
const z = centerZ + (row - 2) * cell;
addBox(
compass,
[0.075, 0.04, 0.075],
[x, 0.76, z],
MAT.ink,
false
);
}
}
}
addGlyph(glyphs.N, 0, -1.48);
addGlyph(glyphs.E, 1.48, 0);
addGlyph(glyphs.S, 0, 1.48);
addGlyph(glyphs.W, -1.48, 0);
// Compass needle: red points along the net field direction.
const needle = new THREE.Group();
needle.position.y = 0.96;
compass.add(needle);
for (let i = -5; i <= 5; i++) {
addBox(
needle,
[0.19, 0.14, 0.19],
[i * 0.21, 0, 0],
i >= 0 ? MAT.red : MAT.blue
);
}
for (let row = -2; row <= 2; row++) {
addBox(
needle,
[0.18, 0.14, 0.18],
[0.95 + (2 - Math.abs(row)) * 0.18, 0, row * 0.18],
MAT.red
);
addBox(
needle,
[0.18, 0.14, 0.18],
[-0.95 - (2 - Math.abs(row)) * 0.18, 0, row * 0.18],
MAT.blue
);
}
addBox(compass, [0.5, 0.28, 0.5], [0, 1.02, 0], MAT.compassBase);
addBox(compass, [0.23, 0.18, 0.23], [0, 1.16, 0], MAT.white);
// Cyan overlay showing the net vector.
const resultantArrow = new THREE.Group();
resultantArrow.position.y = 1.2;
compass.add(resultantArrow);
for (let i = 0; i < 6; i++) {
addBox(
resultantArrow,
[0.17, 0.055, 0.08],
[-0.45 + i * 0.18, 0, 0],
MAT.cyan,
false
);
}
for (let row = -2; row <= 2; row++) {
addBox(
resultantArrow,
[0.14, 0.055, 0.14],
[0.48 + (2 - Math.abs(row)) * 0.14, 0, row * 0.14],
MAT.cyan,
false
);
}
// Draggable bar magnet.
const magnetPosition = new THREE.Vector3(-4.65, 0.26, -0.35);
const magnetGroup = new THREE.Group();
magnetGroup.position.copy(magnetPosition);
scene.add(magnetGroup);
for (let i = 0; i < 6; i++) {
addBox(
magnetGroup,
[0.24, 0.31, 0.42],
[-0.75 + i * 0.25, 0, 0],
i < 3 ? MAT.blue : MAT.red
);
}
for (let row = -2; row <= 2; row++) {
addBox(
magnetGroup,
[0.2, 0.22, 0.2],
[0.72 + (2 - Math.abs(row)) * 0.2, 0, row * 0.2],
MAT.red
);
}
addBox(
scene,
[2.25, 0.1, 1.25],
[magnetPosition.x, 0.11, magnetPosition.z],
MAT.pad
);
// Draggable background-field arrow.
const backgroundPosition = new THREE.Vector3(4.65, 0.27, -0.35);
const backgroundGroup = new THREE.Group();
backgroundGroup.position.copy(backgroundPosition);
scene.add(backgroundGroup);
for (let i = 0; i < 7; i++) {
addBox(
backgroundGroup,
[0.24, 0.22, 0.24],
[-0.84 + i * 0.24, 0, 0],
MAT.gold
);
}
for (let row = -2; row <= 2; row++) {
addBox(
backgroundGroup,
[0.2, 0.22, 0.2],
[0.68 + (2 - Math.abs(row)) * 0.2, 0, row * 0.2],
MAT.gold
);
}
addBox(
scene,
[2.25, 0.1, 1.25],
[backgroundPosition.x, 0.11, backgroundPosition.z],
MAT.pad
);
// Small background-field arrows around the table perimeter.
const fieldArrowEntries = [];
const fieldArrowPositions = [
[-5.8, -5.4], [-3.4, -5.8], [-0.8, -5.9], [2.0, -5.8],
[4.8, -5.3], [6.0, -3.5], [6.3, -1.0], [6.1, 2.8],
[4.6, 5.3], [1.5, 6.2], [-1.8, 6.1], [-4.8, 5.4],
[-6.3, 3.0], [-6.4, 0.3], [-6.0, -2.8], [-3.5, 3.8],
[0.0, 4.4], [3.7, 3.9]
];
for (const [x, z] of fieldArrowPositions) {
const arrow = new THREE.Group();
arrow.position.set(x, 0.19, z);
addBox(arrow, [0.55, 0.09, 0.12], [0, 0, 0], MAT.fieldArrow, false);
addBox(arrow, [0.22, 0.09, 0.22], [0.31, 0, 0], MAT.fieldArrow, false);
addBox(arrow, [0.22, 0.09, 0.22], [0.43, 0, 0], MAT.fieldArrow, false);
addBox(arrow, [0.22, 0.09, 0.22], [0.55, 0, 0], MAT.fieldArrow, false);
scene.add(arrow);
fieldArrowEntries.push({
group: arrow,
base: new THREE.Vector3(x, 0.19, z)
});
}
// Pickable controller meshes.
const pickMeshes = [];
function registerController(group, type) {
group.traverse((object) => {
if (!object.isMesh) return;
object.userData.dragType = type;
pickMeshes.push(object);
});
}
registerController(magnetGroup, "magnet");
registerController(backgroundGroup, "background");
const DEFAULT = {
magnetHeading: THREE.MathUtils.degToRad(25),
backgroundHeading: THREE.MathUtils.degToRad(145),
magnetStrength: 1,
backgroundStrength: 0.55
};
const state = {
...DEFAULT,
magnetVector: new THREE.Vector3(),
backgroundVector: new THREE.Vector3(),
netVector: new THREE.Vector3(),
targetNeedleAngle: 0,
currentNeedleAngle: 0
};
function vectorFromHeading(heading, strength) {
return new THREE.Vector3(
Math.sin(heading) * strength,
0,
-Math.cos(heading) * strength
);
}
function orientationFor(vector) {
// The local +X axis of every arrow follows the field vector.
return -Math.atan2(vector.z, vector.x);
}
function updateRangeFill(input) {
const min = Number(input.min);
const max = Number(input.max);
const value = Number(input.value);
const percentage = ((value - min) / (max - min)) * 100;
input.style.setProperty("--pct", `${percentage}%`);
}
function updateReadout() {
const magnitude = state.netVector.length();
const strengthPercent = Math.round((magnitude / 3) * 100);
if (magnitude > 0.025) {
const bearing = (
THREE.MathUtils.radToDeg(
Math.atan2(state.netVector.x, -state.netVector.z)
) + 360
) % 360;
ui.bearing.textContent = `${String(Math.round(bearing)).padStart(3, "0")}°`;
ui.netStrength.textContent = `${strengthPercent}%`;
ui.netState.textContent = `VECTOR ${String(Math.round(bearing)).padStart(3, "0")}°`;
} else {
ui.bearing.textContent = "—";
ui.netStrength.textContent = "0%";
ui.netState.textContent = "NO NET FIELD";
}
}
function applyFieldState() {
state.magnetVector.copy(
vectorFromHeading(state.magnetHeading, state.magnetStrength)
);
state.backgroundVector.copy(
vectorFromHeading(state.backgroundHeading, state.backgroundStrength)
);
state.netVector
.copy(state.magnetVector)
.add(state.backgroundVector);
magnetGroup.rotation.y = orientationFor(state.magnetVector);
backgroundGroup.rotation.y = orientationFor(state.backgroundVector);
for (const entry of fieldArrowEntries) {
entry.group.rotation.y = orientationFor(state.backgroundVector);
}
const magnitude = state.netVector.length();
resultantArrow.visible = magnitude > 0.025;
resultantArrow.rotation.y = orientationFor(state.netVector);
const normalizedMagnitude = THREE.MathUtils.clamp(magnitude / 3, 0, 1);
const resultScale = 0.78 + normalizedMagnitude * 0.3;
resultantArrow.scale.setScalar(resultScale);
if (magnitude > 0.025) {
state.targetNeedleAngle = Math.atan2(
state.netVector.z,
state.netVector.x
);
}
ui.magnetValue.textContent = state.magnetStrength.toFixed(2);
ui.backgroundValue.textContent = state.backgroundStrength.toFixed(2);
updateRangeFill(ui.magnetStrength);
updateRangeFill(ui.backgroundStrength);
updateReadout();
}
ui.magnetStrength.addEventListener("input", (event) => {
state.magnetStrength = Number(event.target.value);
applyFieldState();
});
ui.backgroundStrength.addEventListener("input", (event) => {
state.backgroundStrength = Number(event.target.value);
applyFieldState();
});
ui.resetButton.addEventListener("click", () => {
state.magnetHeading = DEFAULT.magnetHeading;
state.backgroundHeading = DEFAULT.backgroundHeading;
state.magnetStrength = DEFAULT.magnetStrength;
state.backgroundStrength = DEFAULT.backgroundStrength;
ui.magnetStrength.value = DEFAULT.magnetStrength;
ui.backgroundStrength.value = DEFAULT.backgroundStrength;
applyFieldState();
});
ui.opposeButton.addEventListener("click", () => {
state.backgroundHeading = state.magnetHeading + Math.PI;
applyFieldState();
});
applyFieldState();
state.currentNeedleAngle = state.targetNeedleAngle;
needle.rotation.y = -state.currentNeedleAngle;
// Direct camera and controller interaction.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), -0.26);
const planeHit = new THREE.Vector3();
let drag = null;
function setPointerFromEvent(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 getControllerHit(event) {
setPointerFromEvent(event);
return raycaster.intersectObjects(pickMeshes, false)[0] || null;
}
function updateControllerDirection(event, type) {
setPointerFromEvent(event);
if (!raycaster.ray.intersectPlane(dragPlane, planeHit)) return;
const origin = type === "magnet"
? magnetPosition
: backgroundPosition;
const dx = planeHit.x - origin.x;
const dz = planeHit.z - origin.z;
if (Math.hypot(dx, dz) < 0.05) return;
// Heading 0° points north (-Z); headings increase clockwise.
const heading = Math.atan2(dx, -dz);
if (type === "magnet") {
state.magnetHeading = heading;
} else {
state.backgroundHeading = heading;
}
applyFieldState();
}
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
const hit = getControllerHit(event);
if (hit) {
drag = {
type: hit.object.userData.dragType,
pointerId: event.pointerId
};
updateControllerDirection(event, drag.type);
} else {
drag = {
type: "orbit",
pointerId: event.pointerId,
x: event.clientX,
y: event.clientY
};
}
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = "grabbing";
});
canvas.addEventListener("pointermove", (event) => {
if (!drag) {
const hit = getControllerHit(event);
canvas.style.cursor = hit ? "grab" : "move";
return;
}
if (drag.pointerId !== event.pointerId) return;
if (drag.type === "orbit") {
const dx = event.clientX - drag.x;
const dy = event.clientY - drag.y;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.35,
1.15
);
drag.x = event.clientX;
drag.y = event.clientY;
updateCamera();
} else {
updateControllerDirection(event, drag.type);
}
});
function endDrag(event) {
if (drag && drag.pointerId === event.pointerId) {
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
drag = null;
canvas.style.cursor = "move";
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
10.5,
25
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
const labelPosition = new THREE.Vector3();
const projected = new THREE.Vector3();
function positionLabel(element, worldPosition) {
labelPosition.copy(worldPosition).project(camera);
const visible = labelPosition.z > -1 && labelPosition.z < 1;
const x = (labelPosition.x * 0.5 + 0.5) * window.innerWidth;
const y = (-labelPosition.y * 0.5 + 0.5) * window.innerHeight;
element.style.opacity = visible ? "1" : "0";
element.style.transform =
`translate3d(${x}px, ${y}px, 0) translate(-50%, -50%)`;
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
const clock = new THREE.Clock();
const backgroundDirection = new THREE.Vector3();
function animate() {
const dt = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
// Critically-damped-looking needle response.
const angularDifference = (
((state.targetNeedleAngle - state.currentNeedleAngle + Math.PI) %
(Math.PI * 2) + Math.PI * 2) %
(Math.PI * 2)
) - Math.PI;
state.currentNeedleAngle +=
angularDifference * (1 - Math.exp(-7.5 * dt));
needle.rotation.y = -state.currentNeedleAngle;
if (state.backgroundVector.lengthSq() > 0.0001) {
backgroundDirection
.copy(state.backgroundVector)
.normalize();
}
fieldArrowEntries.forEach((entry, index) => {
const wave = Math.sin(elapsed * 1.35 + index * 0.72) * 0.12;
entry.group.position.x =
entry.base.x + backgroundDirection.x * wave;
entry.group.position.z =
entry.base.z + backgroundDirection.z * wave;
entry.group.position.y =
entry.base.y + Math.sin(elapsed * 1.8 + index) * 0.025;
entry.group.visible = state.backgroundStrength > 0.015;
});
positionLabel(
ui.magnetLabel,
projected.set(
magnetPosition.x,
magnetPosition.y + 0.9,
magnetPosition.z
)
);
positionLabel(
ui.backgroundLabel,
projected.set(
backgroundPosition.x,
backgroundPosition.y + 0.9,
backgroundPosition.z
)
);
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
```