Prompt specification
Build or customize the Three.js 3D scene "Field-mapping 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: Field-mapping teaching table
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/field-mapping-teaching-table-x1623
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows electric fields around point charges. Compose several movable charge markers over a grid with a tiny positive test probe; connect field direction to the force on the probe under stated ideal assumptions. Voxel style.
Working Three.js Starter (field-mapping-teaching-table-x1623):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Voxel Field Lab — Electric Field Explorer</title>
<style>
:root {
--bg: #06101c;
--panel: #0a1726;
--panel-2: #0d1d2e;
--line: #20384c;
--line-bright: #31546d;
--text: #e7f3fb;
--muted: #88a5b8;
--cyan: #45e6ff;
--cyan-soft: rgba(69, 230, 255, 0.14);
--pink: #ff55d8;
--pink-soft: rgba(255, 85, 216, 0.14);
--yellow: #ffe477;
--red: #ff7181;
--green: #55f0ae;
--shadow: 0 18px 50px rgba(0, 0, 0, 0.35);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.app {
display: grid;
grid-template-rows: 66px minmax(0, 1fr);
width: 100%;
height: 100%;
background:
radial-gradient(circle at 22% 18%, rgba(28, 101, 132, 0.12), transparent 35%),
var(--bg);
}
.topbar {
z-index: 20;
display: flex;
align-items: center;
gap: 20px;
min-width: 0;
padding: 0 20px;
border-bottom: 1px solid var(--line);
background: rgba(6, 16, 28, 0.94);
backdrop-filter: blur(14px);
}
.brand {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.brand-mark {
display: grid;
grid-template-columns: repeat(2, 9px);
grid-template-rows: repeat(2, 9px);
gap: 3px;
flex: 0 0 auto;
}
.brand-mark i {
display: block;
background: var(--cyan);
box-shadow: 0 0 14px rgba(69, 230, 255, 0.48);
}
.brand-mark i:nth-child(2) {
background: var(--pink);
box-shadow: 0 0 14px rgba(255, 85, 216, 0.4);
}
.brand-mark i:nth-child(3) {
opacity: 0.45;
}
.brand-copy {
min-width: 0;
}
.brand-copy strong {
display: block;
overflow: hidden;
font-size: 13px;
font-weight: 800;
letter-spacing: 0.13em;
line-height: 1.1;
text-overflow: ellipsis;
white-space: nowrap;
}
.brand-copy span {
display: block;
margin-top: 5px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.12em;
white-space: nowrap;
}
.top-spacer {
flex: 1;
}
.status-chip,
.top-button {
height: 34px;
border: 1px solid var(--line);
background: var(--panel);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.status-chip {
display: flex;
align-items: center;
gap: 9px;
padding: 0 12px;
color: var(--muted);
}
.status-chip::before {
width: 7px;
height: 7px;
background: var(--green);
box-shadow: 0 0 12px rgba(85, 240, 174, 0.65);
content: "";
}
.top-button {
padding: 0 13px;
cursor: pointer;
transition:
border-color 160ms ease,
background 160ms ease,
color 160ms ease;
}
.top-button:hover {
border-color: var(--cyan);
background: var(--cyan-soft);
color: var(--cyan);
}
.main {
display: grid;
grid-template-columns: minmax(0, 1fr) 344px;
min-height: 0;
}
#viewport {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
border-right: 1px solid var(--line);
isolation: isolate;
}
#canvasHost,
#labels {
position: absolute;
inset: 0;
}
#canvasHost canvas {
display: block;
width: 100%;
height: 100%;
outline: none;
touch-action: none;
}
#labels {
z-index: 5;
overflow: hidden;
pointer-events: none;
}
.panel {
z-index: 10;
min-height: 0;
overflow: auto;
background:
linear-gradient(180deg, rgba(16, 36, 53, 0.5), transparent 180px),
var(--panel);
scrollbar-color: var(--line-bright) transparent;
scrollbar-width: thin;
}
.panel-section {
padding: 18px;
border-bottom: 1px solid var(--line);
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 13px;
}
.section-heading h2 {
margin: 0;
color: #cce1ee;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.section-heading .index {
color: #4b6a7e;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
}
.intro-title {
margin: 0 0 8px;
font-size: 21px;
line-height: 1.12;
letter-spacing: -0.025em;
}
.intro-copy {
margin: 0;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.charge-list {
display: grid;
gap: 7px;
margin-bottom: 10px;
}
.charge-row {
display: grid;
grid-template-columns: 13px minmax(0, 1fr) auto;
align-items: center;
gap: 10px;
width: 100%;
min-height: 42px;
padding: 7px 10px;
border: 1px solid var(--line);
border-left-width: 3px;
background: rgba(7, 20, 33, 0.76);
text-align: left;
cursor: pointer;
transition:
border-color 150ms ease,
background 150ms ease,
transform 150ms ease;
}
.charge-row:hover {
border-color: var(--line-bright);
background: var(--panel-2);
transform: translateX(-2px);
}
.charge-row.selected {
border-color: var(--cyan);
background: var(--cyan-soft);
}
.charge-row.positive {
border-left-color: var(--cyan);
}
.charge-row.negative {
border-left-color: var(--red);
}
.charge-swatch {
width: 9px;
height: 9px;
background: var(--cyan);
box-shadow: 0 0 12px rgba(69, 230, 255, 0.5);
}
.charge-row.negative .charge-swatch {
background: var(--red);
box-shadow: 0 0 12px rgba(255, 113, 129, 0.45);
}
.charge-value {
display: block;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
font-weight: 750;
}
.charge-coord {
display: block;
margin-top: 3px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
}
.charge-id {
color: #547387;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
}
.empty-state {
padding: 14px;
border: 1px dashed var(--line-bright);
color: var(--muted);
font-size: 11px;
line-height: 1.5;
text-align: center;
}
.button {
min-height: 36px;
border: 1px solid var(--line-bright);
background: var(--panel-2);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
cursor: pointer;
transition:
border-color 150ms ease,
background 150ms ease,
color 150ms ease;
}
.button:hover {
border-color: var(--cyan);
background: var(--cyan-soft);
color: var(--cyan);
}
.button.full {
width: 100%;
}
.button.danger:hover {
border-color: var(--red);
background: rgba(255, 113, 129, 0.12);
color: var(--red);
}
.inspector {
margin-top: 12px;
padding: 13px;
border: 1px solid var(--line-bright);
background: rgba(5, 15, 27, 0.72);
}
.inspector[hidden] {
display: none;
}
.inspector-title {
display: flex;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.inspector-title strong {
color: var(--cyan);
}
.sign-switch {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
margin-bottom: 13px;
}
.sign-switch button {
min-height: 31px;
border: 1px solid var(--line);
background: transparent;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
cursor: pointer;
}
.sign-switch button[data-sign="1"].active {
border-color: var(--cyan);
background: var(--cyan-soft);
color: var(--cyan);
}
.sign-switch button[data-sign="-1"].active {
border-color: var(--red);
background: rgba(255, 113, 129, 0.12);
color: var(--red);
}
.range-heading {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
color: var(--muted);
font-size: 10px;
}
.range-heading strong {
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
input[type="range"] {
width: 100%;
height: 18px;
margin: 0 0 11px;
accent-color: var(--cyan);
cursor: pointer;
}
.inspector-bottom {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.metric {
min-width: 0;
padding: 11px;
border: 1px solid var(--line);
background: rgba(6, 18, 31, 0.72);
}
.metric.wide {
grid-column: 1 / -1;
}
.metric-label {
display: block;
margin-bottom: 6px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 8px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.metric-value {
display: block;
overflow: hidden;
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 14px;
font-weight: 750;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric-value.cyan {
color: var(--cyan);
}
.metric-value.pink {
color: var(--pink);
}
.metric-value.yellow {
color: var(--yellow);
}
.relation {
display: flex;
align-items: center;
gap: 8px;
margin-top: 8px;
color: var(--green);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.05em;
}
.relation::before {
width: 7px;
height: 7px;
background: currentColor;
box-shadow: 0 0 10px currentColor;
content: "";
}
.probe-note {
margin: 9px 0 0;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.toggle-list {
display: grid;
gap: 9px;
}
.toggle-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
color: #c4d8e5;
font-size: 11px;
cursor: pointer;
}
.toggle-label {
display: flex;
align-items: center;
gap: 9px;
}
.color-key {
width: 9px;
height: 9px;
flex: 0 0 auto;
}
.color-key.field {
background: var(--cyan);
box-shadow: 0 0 9px rgba(69, 230, 255, 0.45);
}
.color-key.force {
background: var(--pink);
box-shadow: 0 0 9px rgba(255, 85, 216, 0.45);
}
.color-key.probe {
background: var(--yellow);
box-shadow: 0 0 9px rgba(255, 228, 119, 0.4);
}
.switch {
position: relative;
width: 33px;
height: 17px;
flex: 0 0 auto;
}
.switch input {
position: absolute;
width: 1px;
height: 1px;
opacity: 0;
}
.switch-track {
position: absolute;
inset: 0;
border: 1px solid var(--line-bright);
background: #081421;
pointer-events: none;
}
.switch-track::after {
position: absolute;
top: 3px;
left: 3px;
width: 9px;
height: 9px;
background: #587387;
content: "";
transition:
left 150ms ease,
background 150ms ease;
}
.switch input:checked + .switch-track {
border-color: var(--cyan);
background: var(--cyan-soft);
}
.switch input:checked + .switch-track::after {
left: 19px;
background: var(--cyan);
box-shadow: 0 0 8px rgba(69, 230, 255, 0.5);
}
details summary {
color: #cce1ee;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.1em;
text-transform: uppercase;
cursor: pointer;
}
details summary::marker {
color: var(--cyan);
}
.assumption-list {
display: grid;
gap: 9px;
margin: 14px 0 0;
padding: 0;
list-style: none;
}
.assumption-list li {
position: relative;
padding-left: 15px;
color: var(--muted);
font-size: 10px;
line-height: 1.5;
}
.assumption-list li::before {
position: absolute;
top: 0.55em;
left: 0;
width: 5px;
height: 5px;
background: var(--cyan);
content: "";
}
.equation-card {
position: absolute;
z-index: 8;
top: 18px;
left: 18px;
width: min(390px, calc(100% - 36px));
padding: 15px 16px;
border: 1px solid var(--line-bright);
background: rgba(6, 18, 31, 0.88);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
pointer-events: none;
}
.equation-topline {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.equation-topline span {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 8px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.equation-topline strong {
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.08em;
}
.equation {
font-family: Georgia, "Times New Roman", serif;
font-size: 18px;
line-height: 1.35;
letter-spacing: 0.01em;
}
.equation .field-term {
color: var(--cyan);
}
.equation .force-term {
color: var(--pink);
}
.equation-arrow {
display: flex;
align-items: center;
gap: 10px;
margin-top: 10px;
color: var(--green);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.equation-arrow::before {
height: 1px;
flex: 1;
background: linear-gradient(90deg, var(--cyan), var(--pink));
content: "";
}
.legend {
position: absolute;
z-index: 7;
top: 18px;
right: 18px;
display: grid;
gap: 8px;
min-width: 126px;
padding: 11px 12px;
border: 1px solid var(--line);
background: rgba(6, 18, 31, 0.78);
backdrop-filter: blur(10px);
pointer-events: none;
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 8px;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.legend-line {
width: 21px;
height: 3px;
background: var(--cyan);
box-shadow: 0 0 8px rgba(69, 230, 255, 0.5);
}
.legend-line.force {
background: var(--pink);
box-shadow: 0 0 8px rgba(255, 85, 216, 0.5);
}
.legend-line.probe {
width: 9px;
height: 9px;
background: var(--yellow);
box-shadow: 0 0 8px rgba(255, 228, 119, 0.5);
}
.hint {
position: absolute;
z-index: 7;
bottom: 16px;
left: 50%;
display: flex;
align-items: center;
gap: 10px;
max-width: calc(100% - 32px);
padding: 9px 13px;
border: 1px solid var(--line);
background: rgba(6, 18, 31, 0.8);
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
white-space: nowrap;
transform: translateX(-50%);
backdrop-filter: blur(10px);
pointer-events: none;
}
.hint b {
color: var(--text);
font-weight: 650;
}
.hint-separator {
width: 1px;
height: 12px;
background: var(--line-bright);
}
.entity-label {
position: absolute;
z-index: 4;
display: flex;
align-items: center;
gap: 5px;
padding: 4px 6px;
border: 1px solid rgba(69, 230, 255, 0.55);
background: rgba(5, 17, 29, 0.86);
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 750;
white-space: nowrap;
transform: translate(-50%, -100%);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.28);
}
.entity-label.negative {
border-color: rgba(255, 113, 129, 0.55);
color: var(--red);
}
.entity-label small {
color: var(--muted);
font-size: 8px;
font-weight: 500;
}
.entity-label.probe-label {
flex-direction: column;
align-items: flex-start;
gap: 1px;
border-color: rgba(255, 228, 119, 0.65);
color: var(--yellow);
font-size: 8px;
letter-spacing: 0.05em;
}
.entity-label.probe-label strong {
font-size: 10px;
}
.vector-label {
position: absolute;
z-index: 5;
padding: 2px 5px;
background: rgba(5, 17, 29, 0.82);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
font-weight: 800;
transform: translate(-50%, -50%);
}
.vector-label.field-label {
color: var(--cyan);
}
.vector-label.force-label {
color: var(--pink);
}
.axis-label {
position: absolute;
color: #4f7188;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 800;
transform: translate(-50%, -50%);
}
.toast {
position: absolute;
z-index: 30;
left: 50%;
bottom: 66px;
padding: 10px 14px;
border: 1px solid var(--cyan);
background: rgba(5, 17, 29, 0.94);
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
letter-spacing: 0.04em;
opacity: 0;
transform: translate(-50%, 10px);
transition:
opacity 180ms ease,
transform 180ms ease;
pointer-events: none;
}
.toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#loading {
position: absolute;
z-index: 50;
inset: 0;
display: grid;
place-items: center;
background: var(--bg);
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
letter-spacing: 0.14em;
text-transform: uppercase;
}
#loading.hidden {
display: none;
}
@media (max-width: 1080px) {
.main {
grid-template-columns: minmax(0, 1fr) 314px;
}
.legend {
top: 155px;
}
}
@media (max-width: 820px) {
html,
body {
height: auto;
min-height: 100%;
overflow: auto;
}
.app {
display: block;
height: auto;
min-height: 100%;
}
.topbar {
position: sticky;
top: 0;
height: 60px;
padding: 0 12px;
}
.brand-copy span,
.status-chip {
display: none;
}
.main {
display: block;
}
#viewport {
height: 62vh;
min-height: 470px;
border-right: 0;
border-bottom: 1px solid var(--line);
}
.panel {
overflow: visible;
}
.equation-card {
top: 12px;
left: 12px;
width: calc(100% - 24px);
}
.legend {
top: auto;
right: 12px;
bottom: 60px;
}
.hint {
overflow: hidden;
text-overflow: ellipsis;
}
}
@media (max-width: 520px) {
.top-button {
padding: 0 9px;
font-size: 9px;
}
.brand-copy strong {
font-size: 11px;
}
.equation {
font-size: 15px;
}
.legend {
display: none;
}
.hint {
width: calc(100% - 24px);
justify-content: center;
}
.hint .optional {
display: none;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<i></i><i></i><i></i><i></i>
</div>
<div class="brand-copy">
<strong>VOXEL FIELD LAB</strong>
<span>ELECTROSTATICS / INTERACTIVE SLICE</span>
</div>
</div>
<div class="top-spacer"></div>
<div class="status-chip" id="sceneStatus">3 charges / 1 probe</div>
<button class="top-button" id="cameraReset" type="button">Reset camera</button>
<button class="top-button" id="resetScene" type="button">Reset scene</button>
</header>
<main class="main">
<section id="viewport" aria-label="Interactive electric field visualization">
<div id="canvasHost"></div>
<div id="labels"></div>
<div class="equation-card">
<div class="equation-topline">
<span>Coulomb superposition</span>
<strong>k = 1 normalized</strong>
</div>
<div class="equation">
<span class="field-term">E(r)</span> =
k Σ q<sub>i</sub>(r − r<sub>i</sub>) / |r − r<sub>i</sub>|<sup>3</sup>
</div>
<div class="equation" style="margin-top: 5px;">
<span class="force-term">F<sub>probe</sub></span> =
q<sub>0</sub><span class="field-term">E</span>,
q<sub>0</sub> = +0.05 q<sub>u</sub>
</div>
<div class="equation-arrow" id="equationRelation">
Positive probe ⇒ force and field are parallel
</div>
</div>
<div class="legend" aria-hidden="true">
<div class="legend-row">
<i class="legend-line"></i>
<span>Field E</span>
</div>
<div class="legend-row">
<i class="legend-line force"></i>
<span>Force F</span>
</div>
<div class="legend-row">
<i class="legend-line probe"></i>
<span>Test probe</span>
</div>
</div>
<div class="hint">
<span><b>Drag</b> charges</span>
<i class="hint-separator"></i>
<span><b>Drag</b> probe</span>
<i class="hint-separator"></i>
<span><b>Drag</b> empty space to orbit</span>
<i class="hint-separator optional"></i>
<span class="optional"><b>Shift-drag</b> pan</span>
<i class="hint-separator optional"></i>
<span class="optional"><b>Wheel</b> zoom</span>
</div>
<div class="toast" id="toast" role="status"></div>
<div id="loading">Initializing field lattice…</div>
</section>
<aside class="panel">
<section class="panel-section">
<h1 class="intro-title">Electric field, one voxel at a time.</h1>
<p class="intro-copy">
Move point charges through the lattice and inspect the net field at a
tiny positive test probe. Cyan shows E; magenta shows the resulting force.
</p>
</section>
<section class="panel-section">
<div class="section-heading">
<h2>Source charges</h2>
<span class="index" id="chargeCount">03</span>
</div>
<div class="charge-list" id="chargeList"></div>
<button class="button full" id="addCharge" type="button">+ Add point charge</button>
<div class="inspector" id="inspector" hidden>
<div class="inspector-title">
<span>Selected charge</span>
<strong id="selectedTitle">CHARGE 01</strong>
</div>
<div class="sign-switch" id="signSwitch">
<button type="button" data-sign="1">POSITIVE +</button>
<button type="button" data-sign="-1">NEGATIVE −</button>
</div>
<div class="range-heading">
<span>Charge magnitude</span>
<strong id="selectedMagnitude">3.50 qᵤ</strong>
</div>
<input
id="magnitudeSlider"
type="range"
min="0.5"
max="5"
step="0.25"
value="3.5"
aria-label="Selected charge magnitude"
/>
<div class="inspector-bottom">
<button class="button" id="focusCharge" type="button">Focus</button>
<button class="button danger" id="removeCharge" type="button">Remove</button>
</div>
</div>
</section>
<section class="panel-section">
<div class="section-heading">
<h2>Test probe</h2>
<span class="index">q₀ = +0.05 qᵤ</span>
</div>
<div class="metric-grid">
<div class="metric">
<span class="metric-label">Net field |E|</span>
<span class="metric-value cyan" id="netE">0.000</span>
</div>
<div class="metric">
<span class="metric-label">Force |F|</span>
<span class="metric-value pink" id="netForce">0.0000</span>
</div>
<div class="metric wide">
<span class="metric-label">Probe position</span>
<span class="metric-value yellow" id="probePosition">(0.00, 2.30)</span>
</div>
</div>
<div class="relation" id="forceRelation">F ∥ E / 0° offset</div>
<p class="probe-note">
The probe samples the field but is assumed too small to perturb it.
Its positive sign makes the force point in the same direction as E.
</p>
</section>
<section class="panel-section">
<div class="section-heading">
<h2>Display layers</h2>
<span class="index">VOXEL VIEW</span>
</div>
<div class="toggle-list">
<label class="toggle-row">
<span class="toggle-label">
<i class="color-key field"></i>
Sampled field arrows
</span>
<span class="switch">
<input id="fieldToggle" type="checkbox" checked />
<i class="switch-track"></i>
</span>
</label>
<label class="toggle-row">
<span class="toggle-label">
<i class="color-key force"></i>
Probe E / force vectors
</span>
<span class="switch">
<input id="vectorToggle" type="checkbox" checked />
<i class="switch-track"></i>
</span>
</label>
<label class="toggle-row">
<span class="toggle-label">
<i class="color-key probe"></i>
Labels and annotations
</span>
<span class="switch">
<input id="labelToggle" type="checkbox" checked />
<i class="switch-track"></i>
</span>
</label>
</div>
</section>
<section class="panel-section">
<details open>
<summary>Ideal model assumptions</summary>
<ul class="assumption-list">
<li>
Fixed point charges in vacuum, combined by Coulomb superposition.
</li>
<li>
No conductors, dielectric polarization, screening, induction, radiation,
or mechanical response.
</li>
<li>
The tiny +0.05 qᵤ probe is a non-perturbing test charge and has
negligible finite size.
</li>
<li>
The view is a horizontal slice through the full three-dimensional
Coulomb field.
</li>
<li>
Vector directions are exact for the sampled model. Arrow lengths are
normalized for readability, not drawn to a common physical scale.
</li>
<li>
A tiny numerical softening radius of 0.12 grid units prevents
singular values when a sample lands on a source.
</li>
</ul>
</details>
</section>
</aside>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const host = $("#canvasHost");
const labelLayer = $("#labels");
const COLORS = {
background: 0x06101c,
floor: 0x081521,
grid: 0x18374a,
gridBright: 0x24526a,
positive: 0x45e6ff,
negative: 0xff7181,
field: 0x45e6ff,
force: 0xff55d8,
probe: 0xffe477,
selected: 0xffe477
};
const GRID_LIMIT = 10.3;
const GRID_SAMPLES = 23;
const GRID_MIN = -11;
const GRID_MAX = 11;
const K = 1;
const SOFTENING = 0.12;
const PROBE_Q = 0.05;
const scene = new THREE.Scene();
scene.background = new THREE.Color(COLORS.background);
scene.fog = new THREE.Fog(COLORS.background, 29, 57);
const camera = new THREE.PerspectiveCamera(43, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute("aria-label", "Three-dimensional electric field voxel grid");
host.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0x8bdfff, 0x07101a, 1.5);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xbcefff, 2.3);
keyLight.position.set(9, 15, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -17;
keyLight.shadow.camera.right = 17;
keyLight.shadow.camera.top = 17;
keyLight.shadow.camera.bottom = -17;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 45;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0xff4fcf, 0.8);
rimLight.position.set(-12, 7, -10);
scene.add(rimLight);
const unitBox = new THREE.BoxGeometry(1, 1, 1);
const unitEdges = new THREE.EdgesGeometry(unitBox);
const hitGeometry = new THREE.BoxGeometry(1.65, 2.5, 1.65);
const invisibleMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
});
const charges = [];
const pickables = [];
let nextChargeId = 1;
let selectedChargeId = null;
// Camera state and direct, dependency-free controls.
const cameraState = {
theta: 0.76,
phi: 0.94,
radius: 25,
target: new THREE.Vector3(0, 0, 0)
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z + cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
function resetCamera() {
cameraState.theta = 0.76;
cameraState.phi = 0.94;
cameraState.radius = 25;
cameraState.target.set(0, 0, 0);
updateCamera();
}
// Floor and voxel lattice.
const floor = new THREE.Mesh(
new THREE.BoxGeometry(28, 0.24, 28),
new THREE.MeshStandardMaterial({
color: COLORS.floor,
roughness: 0.9,
metalness: 0.12
})
);
floor.position.y = -0.18;
floor.receiveShadow = true;
scene.add(floor);
const gridMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.8,
metalness: 0.18
});
const gridCount = GRID_SAMPLES * GRID_SAMPLES;
const gridMesh = new THREE.InstancedMesh(unitBox, gridMaterial, gridCount);
gridMesh.receiveShadow = true;
gridMesh.frustumCulled = false;
const gridMatrix = new THREE.Matrix4();
const gridPosition = new THREE.Vector3();
const gridScale = new THREE.Vector3(0.9, 0.055, 0.9);
const gridQuaternion = new THREE.Quaternion();
const gridColor = new THREE.Color();
let gridIndex = 0;
for (let zIndex = 0; zIndex < GRID_SAMPLES; zIndex++) {
for (let xIndex = 0; xIndex < GRID_SAMPLES; xIndex++) {
const x = GRID_MIN + xIndex;
const z = GRID_MIN + zIndex;
gridPosition.set(x, -0.015, z);
gridMatrix.compose(gridPosition, gridQuaternion, gridScale);
gridMesh.setMatrixAt(gridIndex, gridMatrix);
const onAxis = xIndex === 11 || zIndex === 11;
const variation = ((xIndex * 7 + zIndex * 13) % 5) * 0.018;
gridColor.setHex(onAxis ? COLORS.gridBright : COLORS.grid);
gridColor.offsetHSL(0, 0, variation);
gridMesh.setColorAt(gridIndex, gridColor);
gridIndex++;
}
}
gridMesh.instanceMatrix.needsUpdate = true;
gridMesh.instanceColor.needsUpdate = true;
scene.add(gridMesh);
// Small voxel corner posts make the grid boundary easy to read.
const postMaterial = new THREE.MeshStandardMaterial({
color: 0x1c5269,
emissive: 0x0b2c39,
emissiveIntensity: 0.5,
roughness: 0.55,
metalness: 0.25
});
for (const x of [-11.7, 11.7]) {
for (const z of [-11.7, 11.7]) {
for (let level = 0; level < 3; level++) {
const post = new THREE.Mesh(unitBox, postMaterial);
post.scale.set(0.18, 0.18, 0.18);
post.position.set(x, 0.09 + level * 0.18, z);
scene.add(post);
}
}
}
// Selection ring.
const selectionRing = new THREE.Group();
const selectionMaterial = new THREE.MeshBasicMaterial({
color: COLORS.selected,
transparent: true,
opacity: 0.9
});
for (let index = 0; index < 20; index++) {
const angle = (index / 20) * Math.PI * 2;
const block = new THREE.Mesh(unitBox, selectionMaterial);
block.scale.set(0.13, 0.11, 0.13);
block.position.set(Math.cos(angle) * 1.04, 0.07, Math.sin(angle) * 1.04);
selectionRing.add(block);
}
selectionRing.visible = false;
scene.add(selectionRing);
// Positive test probe, built from five tiny cubes.
const probe = {
x: 0,
z: 2.3,
group: new THREE.Group(),
label: null
};
const probeMaterial = new THREE.MeshBasicMaterial({ color: COLORS.probe });
const probeCenter = new THREE.Mesh(unitBox, probeMaterial);
probeCenter.scale.setScalar(0.2);
probeCenter.position.y = 0.25;
probe.group.add(probeCenter);
for (const offset of [
[-0.14, 0, 0],
[0.14, 0, 0],
[0, 0, -0.14],
[0, 0, 0.14]
]) {
const arm = new THREE.Mesh(unitBox, probeMaterial);
arm.scale.set(0.1, 0.1, 0.1);
arm.position.set(offset[0], 0.25, offset[2]);
probe.group.add(arm);
}
const probeHit = new THREE.Mesh(hitGeometry, invisibleMaterial);
probeHit.scale.set(0.55, 0.8, 0.55);
probeHit.position.y = 0.3;
probeHit.userData = { kind: "probe" };
probe.group.add(probeHit);
pickables.push(probeHit);
probe.group.position.set(probe.x, 0, probe.z);
scene.add(probe.group);
// Sampled field arrows: a shaft and a three-cube voxel head.
const fieldMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.84,
depthWrite: false
});
const fieldMeshes = [];
for (let component = 0; component < 4; component++) {
const mesh = new THREE.InstancedMesh(unitBox, fieldMaterial, gridCount);
mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
mesh.frustumCulled = false;
mesh.renderOrder = 3;
scene.add(mesh);
fieldMeshes.push(mesh);
}
// Probe-local E and F arrows. They are separated vertically for legibility.
function createVectorVisual(color) {
const group = new THREE.Group();
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.96,
depthWrite: false
});
const shaft = new THREE.Mesh(unitBox, material);
shaft.scale.set(0.69, 0.075, 0.075);
shaft.position.x = 0.345;
const tip = new THREE.Mesh(unitBox, material);
tip.scale.set(0.16, 0.14, 0.14);
tip.position.x = 0.91;
const finA = new THREE.Mesh(unitBox, material);
finA.scale.set(0.14, 0.11, 0.11);
finA.position.set(0.76, 0, 0.095);
const finB = new THREE.Mesh(unitBox, material);
finB.scale.set(0.14, 0.11, 0.11);
finB.position.set(0.76, 0, -0.095);
group.add(shaft, tip, finA, finB);
group.renderOrder = 5;
scene.add(group);
return { group, material };
}
const fieldVector = createVectorVisual(COLORS.field);
const forceVector = createVectorVisual(COLORS.force);
fieldVector.group.scale.set(1.08, 1, 1.08);
forceVector.group.scale.set(1.28, 1, 1.28);
const probeVectorDirection = new THREE.Vector3(1, 0, 0);
const vectorQuaternion = new THREE.Quaternion();
const xAxis = new THREE.Vector3(1, 0, 0);
// DOM labels.
function createLabel(className, html) {
const element = document.createElement("div");
element.className = className;
element.innerHTML = html;
labelLayer.appendChild(element);
return element;
}
probe.label = createLabel(
"entity-label probe-label",
"<span>TEST PROBE</span><strong>+0.05 qᵤ</strong>"
);
const fieldVectorLabel = createLabel("vector-label field-label", "E");
const forceVectorLabel = createLabel("vector-label force-label", "F = q₀E");
const xAxisLabel = createLabel("axis-label", "X");
const zAxisLabel = createLabel("axis-label", "Z");
// Charge construction.
function createCharge(x, z, q) {
const id = nextChargeId++;
const group = new THREE.Group();
group.position.set(x, 0, z);
const mainMaterial = new THREE.MeshStandardMaterial({
color: q >= 0 ? COLORS.positive : COLORS.negative,
emissive: q >= 0 ? 0x087e91 : 0x8d2033,
emissiveIntensity: 0.62,
roughness: 0.35,
metalness: 0.18
});
const main = new THREE.Mesh(unitBox, mainMaterial);
main.castShadow = true;
main.receiveShadow = true;
group.add(main);
const edgeMaterial = new THREE.LineBasicMaterial({
color: q >= 0 ? COLORS.positive : COLORS.negative,
transparent: true,
opacity: 0.9
});
const edges = new THREE.LineSegments(unitEdges, edgeMaterial);
group.add(edges);
const capMaterial = new THREE.MeshBasicMaterial({
color: q >= 0 ? 0xbaf8ff : 0xffc1c9
});
const cap = new THREE.Mesh(unitBox, capMaterial);
cap.scale.setScalar(0.21);
group.add(cap);
const hit = new THREE.Mesh(hitGeometry, invisibleMaterial);
hit.position.y = 0.8;
hit.userData = { kind: "charge", id };
group.add(hit);
pickables.push(hit);
const charge = {
id,
x,
z,
q,
group,
main,
mainMaterial,
edges,
edgeMaterial,
cap,
capMaterial,
hit,
visualHeight: 1,
label: null
};
charge.label = createLabel(
"entity-label",
`<span>${q >= 0 ? "+" : "−"}${Math.abs(q).toFixed(2)}</span><small>qᵤ</small>`
);
refreshChargeVisual(charge);
scene.add(group);
charges.push(charge);
return charge;
}
function refreshChargeVisual(charge) {
const positive = charge.q >= 0;
const height = 0.72 + Math.min(Math.abs(charge.q), 5) * 0.14;
charge.visualHeight = height;
charge.main.scale.set(0.78, height, 0.78);
charge.main.position.y = height * 0.5 + 0.035;
charge.edges.scale.copy(charge.main.scale);
charge.edges.position.copy(charge.main.position);
charge.cap.position.y = height + 0.24;
charge.cap.rotation.y = Math.PI * 0.25;
charge.mainMaterial.color.setHex(positive ? COLORS.positive : COLORS.negative);
charge.mainMaterial.emissive.setHex(positive ? 0x087e91 : 0x8d2033);
charge.edgeMaterial.color.setHex(positive ? COLORS.positive : COLORS.negative);
charge.capMaterial.color.setHex(positive ? 0xbaf8ff : 0xffc1c9);
charge.label.className = `entity-label${positive ? "" : " negative"}`;
charge.label.innerHTML =
`<span>${positive ? "+" : "−"}${Math.abs(charge.q).toFixed(2)}</span><small>qᵤ</small>`;
}
function removeCharge(id) {
const index = charges.findIndex((charge) => charge.id === id);
if (index === -1) return;
const charge = charges[index];
scene.remove(charge.group);
charge.label.remove();
const pickIndex = pickables.indexOf(charge.hit);
if (pickIndex !== -1) pickables.splice(pickIndex, 1);
charge.mainMaterial.dispose();
charge.edgeMaterial.dispose();
charge.capMaterial.dispose();
charges.splice(index, 1);
if (selectedChargeId === id) {
selectedChargeId = null;
}
updateAll();
showToast("Point charge removed");
}
// Coulomb field in the horizontal slice.
function fieldAt(x, z) {
let ex = 0;
let ez = 0;
for (const charge of charges) {
const dx = x - charge.x;
const dz = z - charge.z;
const r2 = dx * dx + dz * dz + SOFTENING * SOFTENING;
const factor = (K * charge.q) / (r2 * Math.sqrt(r2));
ex += factor * dx;
ez += factor * dz;
}
return { x: ex, z: ez, magnitude: Math.hypot(ex, ez) };
}
// Update all sampled field arrows.
const arrowMatrix = new THREE.Matrix4();
const arrowQuaternion = new THREE.Quaternion();
const arrowPosition = new THREE.Vector3();
const arrowScale = new THREE.Vector3();
const localOffset = new THREE.Vector3();
const arrowDirection = new THREE.Vector3();
const arrowColor = new THREE.Color();
const white = new THREE.Color(0xd8fbff);
function hideArrowComponent(mesh, index) {
arrowPosition.set(0, -100, 0);
arrowScale.setScalar(0);
arrowMatrix.compose(arrowPosition, arrowQuaternion, arrowScale);
mesh.setMatrixAt(index, arrowMatrix);
}
function setArrowComponent(mesh, index, x, z, sx, sy, sz, color) {
arrowPosition.set(x, 0.15, z);
arrowScale.set(sx, sy, sz);
arrowMatrix.compose(arrowPosition, arrowQuaternion, arrowScale);
mesh.setMatrixAt(index, arrowMatrix);
mesh.setColorAt(index, color);
}
function updateFieldArrows() {
let index = 0;
for (let zIndex = 0; zIndex < GRID_SAMPLES; zIndex++) {
for (let xIndex = 0; xIndex < GRID_SAMPLES; xIndex++) {
const x = GRID_MIN + xIndex;
const z = GRID_MIN + zIndex;
const field = fieldAt(x, z);
let tooCloseToCharge = false;
for (const charge of charges) {
if (Math.hypot(x - charge.x, z - charge.z) < 0.73) {
tooCloseToCharge = true;
break;
}
}
if (field.magnitude < 0.012 || tooCloseToCharge) {
for (const mesh of fieldMeshes) hideArrowComponent(mesh, index);
index++;
continue;
}
arrowDirection.set(field.x / field.magnitude, 0, field.z / field.magnitude);
arrowQuaternion.setFromUnitVectors(xAxis, arrowDirection);
const normalizedMagnitude = Math.min(
1,
Math.log1p(field.magnitude * 1.6) / 3.8
);
const length = 0.22 + normalizedMagnitude * 0.62;
const shaftLength = length * 0.62;
arrowColor.setHex(COLORS.field).lerp(white, normalizedMagnitude * 0.48);
setArrowComponent(
fieldMeshes[0],
index,
x + arrowDirection.x * shaftLength * 0.5,
z + arrowDirection.z * shaftLength * 0.5,
shaftLength,
0.065,
0.065,
arrowColor
);
setArrowComponent(
fieldMeshes[1],
index,
x + arrowDirection.x * length * 0.9,
z + arrowDirection.z * length * 0.9,
0.16,
0.14,
0.14,
arrowColor
);
const perpendicularX = -arrowDirection.z;
const perpendicularZ = arrowDirection.x;
setArrowComponent(
fieldMeshes[2],
index,
x +
arrowDirection.x * length * 0.75 +
perpendicularX * 0.095,
z +
arrowDirection.z * length * 0.75 +
perpendicularZ * 0.095,
0.14,
0.11,
0.11,
arrowColor
);
setArrowComponent(
fieldMeshes[3],
index,
x +
arrowDirection.x * length * 0.75 -
perpendicularX * 0.095,
z +
arrowDirection.z * length * 0.75 -
perpendicularZ * 0.095,
0.14,
0.11,
0.11,
arrowColor
);
index++;
}
}
for (const mesh of fieldMeshes) {
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
}
}
// Update the net field and force at the test probe.
function updateProbeVector() {
const field = fieldAt(probe.x, probe.z);
const forceMagnitude = PROBE_Q * field.magnitude;
$("#netE").textContent = field.magnitude.toFixed(3);
$("#netForce").textContent = forceMagnitude.toFixed(4);
$("#probePosition").textContent = `(${probe.x.toFixed(2)}, ${probe.z.toFixed(2)})`;
if (field.magnitude > 1e-6) {
probeVectorDirection.set(
field.x / field.magnitude,
0,
field.z / field.magnitude
);
vectorQuaternion.setFromUnitVectors(xAxis, probeVectorDirection);
fieldVector.group.quaternion.copy(vectorQuaternion);
forceVector.group.quaternion.copy(vectorQuaternion);
fieldVector.group.position.set(probe.x, 0.25, probe.z);
forceVector.group.position.set(probe.x, 0.47, probe.z);
fieldVector.group.visible = $("#vectorToggle").checked;
forceVector.group.visible = $("#vectorToggle").checked;
$("#forceRelation").textContent = "F ∥ E / 0° offset";
$("#forceRelation").style.color = "var(--green)";
$("#equationRelation").textContent = "Positive probe ⇒ force and field are parallel";
} else {
fieldVector.group.visible = false;
forceVector.group.visible = false;
$("#forceRelation").textContent = "ZERO NET FIELD / NO FORCE";
$("#forceRelation").style.color = "var(--muted)";
$("#equationRelation").textContent = "Net field and force vanish at the probe";
}
}
// UI state.
function getSelectedCharge() {
return charges.find((charge) => charge.id === selectedChargeId) || null;
}
function selectCharge(id) {
selectedChargeId = id;
updateChargeList();
updateInspector();
updateSelectionRing();
}
function updateSelectionRing() {
const selected = getSelectedCharge();
selectionRing.visible = Boolean(selected);
if (selected) {
selectionRing.position.set(selected.x, 0, selected.z);
}
}
function updateChargeList() {
const list = $("#chargeList");
list.innerHTML = "";
if (charges.length === 0) {
list.innerHTML =
'<div class="empty-state">No source charges. Add one to generate a field.</div>';
}
for (const charge of charges) {
const positive = charge.q >= 0;
const button = document.createElement("button");
button.type = "button";
button.className = `charge-row ${positive ? "positive" : "negative"}${
selectedChargeId === charge.id ? " selected" : ""
}`;
button.innerHTML = `
<span class="charge-swatch"></span>
<span>
<span class="charge-value">${positive ? "+" : "−"}${Math.abs(charge.q).toFixed(2)} qᵤ</span>
<span class="charge-coord">x ${charge.x.toFixed(1)} / z ${charge.z.toFixed(1)}</span>
</span>
<span class="charge-id">C-${String(charge.id).padStart(2, "0")}</span>
`;
button.addEventListener("click", () => selectCharge(charge.id));
list.appendChild(button);
}
$("#chargeCount").textContent = String(charges.length).padStart(2, "0");
$("#sceneStatus").textContent = `${charges.length} charge${
charges.length === 1 ? "" : "s"
} / 1 probe`;
}
function updateInspector() {
const inspector = $("#inspector");
const selected = getSelectedCharge();
inspector.hidden = !selected;
if (!selected) return;
$("#selectedTitle").textContent = `CHARGE ${String(selected.id).padStart(2, "0")}`;
$("#selectedMagnitude").textContent = `${Math.abs(selected.q).toFixed(2)} qᵤ`;
$("#magnitudeSlider").value = String(Math.abs(selected.q));
document.querySelectorAll("#signSwitch button").forEach((button) => {
button.classList.toggle(
"active",
Number(button.dataset.sign) === Math.sign(selected.q)
);
});
}
function updateVisibility() {
const fieldVisible = $("#fieldToggle").checked;
for (const mesh of fieldMeshes) mesh.visible = fieldVisible;
const vectorsVisible = $("#vectorToggle").checked;
fieldVector.group.visible = vectorsVisible && fieldAt(probe.x, probe.z).magnitude > 1e-6;
forceVector.group.visible = fieldVector.group.visible;
labelLayer.style.display = $("#labelToggle").checked ? "block" : "none";
}
function updateAll() {
updateFieldArrows();
updateProbeVector();
updateChargeList();
updateInspector();
updateSelectionRing();
updateVisibility();
}
// Add a charge in an open grid position.
function addCharge() {
const candidatePositions = [
[0, 0],
[2, 0],
[-2, 0],
[0, 2],
[0, -2],
[5, 5],
[-5, 5],
[5, -5],
[-5, -5],
[7, -2],
[-7, 2]
];
let position = candidatePositions[0];
for (const candidate of candidatePositions) {
const clearOfCharges = charges.every(
(charge) => Math.hypot(candidate[0] - charge.x, candidate[1] - charge.z) > 1.45
);
const clearOfProbe = Math.hypot(candidate[0] - probe.x, candidate[1] - probe.z) > 1.45;
if (clearOfCharges && clearOfProbe) {
position = candidate;
break;
}
}
const charge = createCharge(position[0], position[1], 2);
selectCharge(charge.id);
updateAll();
showToast("Point charge added — drag it into position");
}
function resetScene() {
for (const charge of [...charges]) {
scene.remove(charge.group);
charge.label.remove();
const pickIndex = pickables.indexOf(charge.hit);
if (pickIndex !== -1) pickables.splice(pickIndex, 1);
charge.mainMaterial.dispose();
charge.edgeMaterial.dispose();
charge.capMaterial.dispose();
}
charges.length = 0;
createCharge(-4, -2, 3.5);
createCharge(3.4, 1.2, -2.5);
createCharge(0.5, -4.5, 1.5);
probe.x = 0;
probe.z = 2.3;
probe.group.position.set(probe.x, 0, probe.z);
selectedChargeId = charges[0].id;
$("#fieldToggle").checked = true;
$("#vectorToggle").checked = true;
$("#labelToggle").checked = true;
resetCamera();
updateAll();
showToast("Scene reset");
}
// Label projection.
const projected = new THREE.Vector3();
function placeLabel(element, x, y, z, enabled = true) {
projected.set(x, y, z).project(camera);
const visible =
enabled &&
projected.z >= -1 &&
projected.z <= 1 &&
projected.x >= -1.15 &&
projected.x <= 1.15 &&
projected.y >= -1.15 &&
projected.y <= 1.15;
element.style.visibility = visible ? "visible" : "hidden";
if (!visible) return;
element.style.left = `${(projected.x * 0.5 + 0.5) * host.clientWidth}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * host.clientHeight}px`;
}
function updateLabelPositions() {
for (const charge of charges) {
placeLabel(
charge.label,
charge.x,
charge.visualHeight + 0.78,
charge.z,
true
);
}
placeLabel(probe.label, probe.x, 0.85, probe.z, true);
const vectorsVisible = $("#vectorToggle").checked;
placeLabel(
fieldVectorLabel,
probe.x + probeVectorDirection.x * 1.3,
0.25,
probe.z + probeVectorDirection.z * 1.3,
vectorsVisible
);
placeLabel(
forceVectorLabel,
probe.x + probeVectorDirection.x * 1.62,
0.47,
probe.z + probeVectorDirection.z * 1.62,
vectorsVisible
);
placeLabel(xAxisLabel, 10.65, 0.15, 0, true);
placeLabel(zAxisLabel, 0, 0.15, 10.65, true);
}
// Raycasting and direct manipulation.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const planePoint = new THREE.Vector3();
let pointerState = null;
function setPointerFromEvent(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 clampToGrid(value) {
return THREE.MathUtils.clamp(value, -GRID_LIMIT, GRID_LIMIT);
}
renderer.domElement.addEventListener("pointerdown", (event) => {
setPointerFromEvent(event);
renderer.domElement.setPointerCapture(event.pointerId);
if (event.button === 2 || event.shiftKey) {
pointerState = {
mode: "pan",
lastX: event.clientX,
lastY: event.clientY
};
return;
}
const intersections = raycaster.intersectObjects(pickables, false);
if (intersections.length) {
const entity = intersections[0].object.userData;
if (entity.kind === "probe") {
raycaster.ray.intersectPlane(dragPlane, planePoint);
pointerState = {
mode: "drag-probe",
offsetX: probe.x - planePoint.x,
offsetZ: probe.z - planePoint.z
};
} else {
const charge = charges.find((item) => item.id === entity.id);
if (!charge) return;
selectCharge(charge.id);
raycaster.ray.intersectPlane(dragPlane, planePoint);
pointerState = {
mode: "drag-charge",
id: charge.id,
offsetX: charge.x - planePoint.x,
offsetZ: charge.z - planePoint.z
};
}
document.body.style.cursor = "grabbing";
} else {
pointerState = {
mode: "orbit",
lastX: event.clientX,
lastY: event.clientY
};
document.body.style.cursor = "grabbing";
}
event.preventDefault();
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerState) return;
if (pointerState.mode === "drag-charge" || pointerState.mode === "drag-probe") {
setPointerFromEvent(event);
if (raycaster.ray.intersectPlane(dragPlane, planePoint)) {
const x = clampToGrid(planePoint.x + pointerState.offsetX);
const z = clampToGrid(planePoint.z + pointerState.offsetZ);
if (pointerState.mode === "drag-probe") {
probe.x = x;
probe.z = z;
probe.group.position.set(x, 0, z);
} else {
const charge = charges.find((item) => item.id === pointerState.id);
if (!charge) return;
charge.x = x;
charge.z = z;
charge.group.position.set(x, 0, z);
}
updateAll();
}
} else if (pointerState.mode === "orbit") {
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.3,
1.36
);
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
updateCamera();
} else if (pointerState.mode === "pan") {
const dx = event.clientX - pointerState.lastX;
const dy = event.clientY - pointerState.lastY;
const scale = cameraState.radius * 0.0014;
const forward = new THREE.Vector3()
.subVectors(cameraState.target, camera.position)
.normalize();
const right = new THREE.Vector3()
.crossVectors(forward, new THREE.Vector3(0, 1, 0))
.normalize();
const up = new THREE.Vector3()
.crossVectors(right, forward)
.normalize();
cameraState.target.addScaledVector(right, -dx * scale);
cameraState.target.addScaledVector(up, dy * scale);
cameraState.target.y = THREE.MathUtils.clamp(cameraState.target.y, -4, 4);
pointerState.lastX = event.clientX;
pointerState.lastY = event.clientY;
updateCamera();
}
});
function endPointerInteraction(event) {
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
pointerState = null;
document.body.style.cursor = "default";
}
renderer.domElement.addEventListener("pointerup", endPointerInteraction);
renderer.domElement.addEventListener("pointercancel", endPointerInteraction);
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
12,
43
);
updateCamera();
},
{ passive: false }
);
// UI events.
$("#addCharge").addEventListener("click", addCharge);
$("#resetScene").addEventListener("click", resetScene);
$("#cameraReset").addEventListener("click", resetCamera);
$("#removeCharge").addEventListener("click", () => {
if (selectedChargeId !== null) removeCharge(selectedChargeId);
});
$("#focusCharge").addEventListener("click", () => {
const selected = getSelectedCharge();
if (!selected) return;
cameraState.target.set(selected.x, 0, selected.z);
cameraState.radius = 18;
updateCamera();
});
$("#magnitudeSlider").addEventListener("input", (event) => {
const selected = getSelectedCharge();
if (!selected) return;
selected.q = Math.sign(selected.q) * Number(event.target.value);
refreshChargeVisual(selected);
updateAll();
});
document.querySelectorAll("#signSwitch button").forEach((button) => {
button.addEventListener("click", () => {
const selected = getSelectedCharge();
if (!selected) return;
selected.q = Number(button.dataset.sign) * Math.abs(selected.q);
refreshChargeVisual(selected);
updateAll();
});
});
$("#fieldToggle").addEventListener("change", updateVisibility);
$("#vectorToggle").addEventListener("change", updateVisibility);
$("#labelToggle").addEventListener("change", updateVisibility);
window.addEventListener("keydown", (event) => {
if (["INPUT", "TEXTAREA", "SELECT"].includes(event.target.tagName)) return;
if (event.key.toLowerCase() === "r") {
resetCamera();
}
if (event.key === "Escape") {
selectedChargeId = null;
updateChargeList();
updateInspector();
updateSelectionRing();
}
});
// Toast.
let toastTimer = 0;
function showToast(message) {
const toast = $("#toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 1700);
}
// Resize handling.
function resize() {
const width = Math.max(1, host.clientWidth);
const height = Math.max(1, host.clientHeight);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(host);
resize();
// Initialize the scene.
createCharge(-4, -2, 3.5);
createCharge(3.4, 1.2, -2.5);
createCharge(0.5, -4.5, 1.5);
selectedChargeId = charges[0].id;
updateCamera();
updateAll();
$("#loading").classList.add("hidden");
// Render loop.
function animate(time) {
requestAnimationFrame(animate);
selectionRing.rotation.y = time * 0.00024;
camera.updateMatrixWorld();
updateLabelPositions();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```